hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b9e29ff51e6c280de664c6883a4b35a80d905a41 | 3,426 | js | JavaScript | react/features/local-recording/middleware.js | navalsynergy/jitsi | 33891094a69579ef9480d74f86c7324be6187747 | [
"Apache-2.0"
] | null | null | null | react/features/local-recording/middleware.js | navalsynergy/jitsi | 33891094a69579ef9480d74f86c7324be6187747 | [
"Apache-2.0"
] | null | null | null | react/features/local-recording/middleware.js | navalsynergy/jitsi | 33891094a69579ef9480d74f86c7324be6187747 | [
"Apache-2.0"
] | null | null | null | /* @flow */
import { createShortcutEvent, sendAnalytics } from '../analytics';
import { APP_WILL_UNMOUNT } from '../base/app/actionTypes';
import { CONFERENCE_JOINED } from '../base/conference/actionTypes';
import { toggleDialog } from '../base/dialog/actions';
import { i18next } from '../base/i18n';
import { SET_AUDIO_MUTED } from '../base/media/actionTypes';
import { MiddlewareRegistry } from '../base/redux';
import { SETTINGS_UPDATED } from '../base/settings/actionTypes';
import { showNotification } from '../notifications/actions';
import { localRecordingEngaged, localRecordingUnengaged } from './actions';
import { LocalRecordingInfoDialog } from './components';
import { recordingController } from './controller';
declare var APP: Object;
MiddlewareRegistry.register(({ getState, dispatch }) => next => action => {
const result = next(action);
switch (action.type) {
case CONFERENCE_JOINED: {
const { localRecording } = getState()['features/base/config'];
const isLocalRecordingEnabled = Boolean(
localRecording
&& localRecording.enabled
&& typeof APP === 'object'
);
if (!isLocalRecordingEnabled) {
break;
}
// realize the delegates on recordingController, allowing the UI to
// react to state changes in recordingController.
recordingController.onStateChanged = isEngaged => {
if (isEngaged) {
const nowTime = new Date();
dispatch(localRecordingEngaged(nowTime));
} else {
dispatch(localRecordingUnengaged());
}
};
recordingController.onWarning = (messageKey, messageParams) => {
dispatch(showNotification({
titleKey: 'localRecording.localRecording',
description: i18next.t(messageKey, messageParams)
}, 10000));
};
recordingController.onNotify = (messageKey, messageParams) => {
dispatch(showNotification({
titleKey: 'localRecording.localRecording',
description: i18next.t(messageKey, messageParams)
}, 10000));
};
typeof APP === 'object' && typeof APP.keyboardshortcut === 'object'
&& APP.keyboardshortcut.registerShortcut('L', null, () => {
sendAnalytics(createShortcutEvent('local.recording'));
dispatch(toggleDialog(LocalRecordingInfoDialog));
}, 'keyboardShortcuts.localRecording');
if (localRecording.format) {
recordingController.switchFormat(localRecording.format);
}
const { conference } = getState()['features/base/conference'];
recordingController.registerEvents(conference);
break;
}
case APP_WILL_UNMOUNT:
recordingController.onStateChanged = null;
recordingController.onNotify = null;
recordingController.onWarning = null;
break;
case SET_AUDIO_MUTED:
recordingController.setMuted(action.muted);
break;
case SETTINGS_UPDATED: {
const { micDeviceId } = getState()['features/base/settings'];
if (micDeviceId) {
recordingController.setMicDevice(micDeviceId);
}
break;
}
}
return result;
});
| 35.319588 | 76 | 0.605371 |
b9e2c542b0feda8b463ec8f09e60a49b5b557427 | 1,079 | js | JavaScript | The Core/6 Labyrinth of Nested Loops/43-isPower.js | TomaszRybacki/Algorithms | e333c7df4234a7d3841b5dbfdedacea8cef17358 | [
"MIT"
] | null | null | null | The Core/6 Labyrinth of Nested Loops/43-isPower.js | TomaszRybacki/Algorithms | e333c7df4234a7d3841b5dbfdedacea8cef17358 | [
"MIT"
] | null | null | null | The Core/6 Labyrinth of Nested Loops/43-isPower.js | TomaszRybacki/Algorithms | e333c7df4234a7d3841b5dbfdedacea8cef17358 | [
"MIT"
] | null | null | null | /*
Determine if the given number is a power of some non-negative integer.
Example
For n = 125, the output should be
isPower(n) = true;
For n = 72, the output should be
isPower(n) = false.
Input/Output
[execution time limit] 4 seconds (js)
[input] integer n
A positive integer.
Guaranteed constraints:
1 ≤ n ≤ 400.
[output] boolean
true if n can be represented in the form ab (a to the power of b)
where a and b are some non-negative integers and b ≥ 2, false otherwise.
*/
function isPower(n) {
let b = 2;
for (let a = 1; a <= 20; a += 1) {
if (a ** b === n) {
return true;
}
for (let b = 2; b <= 20; b += 1) {
if (a ** b === n) {
return true;
}
}
}
return false;
}
console.log(isPower(125)); // true
console.log(isPower(72)); // false
console.log(isPower(100)); // true
console.log(isPower(11)); // false
console.log(isPower(324)); // true
console.log(isPower(256)); // true
console.log(isPower(119)); // false
console.log(isPower(400)); // true
console.log(isPower(350)); // false
console.log(isPower(361)); // true
| 20.358491 | 72 | 0.626506 |
b9e2e87f59b5711d05a7b15438ff87a7ed3efb1f | 96 | js | JavaScript | node_modules/carbon-icons-svelte/lib/DataUnstructured32/index.js | seekersapp2013/new | 1e393c593ad30dc1aa8642703dad69b84bad3992 | [
"MIT"
] | null | null | null | node_modules/carbon-icons-svelte/lib/DataUnstructured32/index.js | seekersapp2013/new | 1e393c593ad30dc1aa8642703dad69b84bad3992 | [
"MIT"
] | null | null | null | node_modules/carbon-icons-svelte/lib/DataUnstructured32/index.js | seekersapp2013/new | 1e393c593ad30dc1aa8642703dad69b84bad3992 | [
"MIT"
] | null | null | null | import DataUnstructured32 from "./DataUnstructured32.svelte";
export default DataUnstructured32; | 48 | 61 | 0.864583 |
b9e3f4b3efd8c2545348f951645f66b95c289b8a | 69 | js | JavaScript | node_modules/carbon-icons-svelte/lib/Scooter32/index.js | seekersapp2013/new | 1e393c593ad30dc1aa8642703dad69b84bad3992 | [
"MIT"
] | null | null | null | node_modules/carbon-icons-svelte/lib/Scooter32/index.js | seekersapp2013/new | 1e393c593ad30dc1aa8642703dad69b84bad3992 | [
"MIT"
] | null | null | null | node_modules/carbon-icons-svelte/lib/Scooter32/index.js | seekersapp2013/new | 1e393c593ad30dc1aa8642703dad69b84bad3992 | [
"MIT"
] | null | null | null | import Scooter32 from "./Scooter32.svelte";
export default Scooter32; | 34.5 | 43 | 0.811594 |
b9e44949c88c30770e6a85433bea59c0023db425 | 1,037 | js | JavaScript | .history/client/myapp/src/components/createFlight_20211107015528.js | EmanOss/It-s-Not-A-Bug-It-s-A-Feature | 59bb9b0b6138335c1ace7d4589ef6999bdd57a80 | [
"MIT"
] | 3 | 2022-02-01T13:45:18.000Z | 2022-02-02T14:44:10.000Z | .history/client/myapp/src/components/createFlight_20211107015528.js | EmanOss/It-s-Not-A-Bug-It-s-A-Feature | 59bb9b0b6138335c1ace7d4589ef6999bdd57a80 | [
"MIT"
] | null | null | null | .history/client/myapp/src/components/createFlight_20211107015528.js | EmanOss/It-s-Not-A-Bug-It-s-A-Feature | 59bb9b0b6138335c1ace7d4589ef6999bdd57a80 | [
"MIT"
] | 5 | 2021-12-27T13:03:49.000Z | 2022-01-17T11:54:17.000Z | import * as React from 'react';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import axios from 'axios';
import { Link } from 'react-router-dom';
import {useState,useEffect} from 'react';
import Button from '@material-ui/core/Button';
export default function createFlight() {
// const[rows, setRows]= useState([]);
// useEffect(()=>{
// axios.get('http://localhost:8000/Admin//createFlight')
// .then(res=> {setRows(res.data);console.log(res)}).catch(err=>console.log(err))
// },[]);
return (
<div style={{display: 'flex', justifyContent:'center', alignItems:'center'}}>
{containerData()}
</div>
);
}
function containerData(){
return(
<Box
component="form"
sx={{
'& > :not(style)': { m: 1, width: '25ch' },
}}
noValidate
autoComplete="off"
>
<TextField error
id="outlined-error"
label="Validate"
defaultValue="Flight Number" variant="outlined" />
</Box>
);
}
| 24.690476 | 85 | 0.594986 |
b9e49b6779f2ad97b44a95eefd0e596eab96ac59 | 41 | js | JavaScript | src/components/pages/home/drawer-content/profile-contacts/profile-body/index.js | effortlesscoding/react-developer | cb0cf35c1c3a114aa9b52a69ca459bf1c963a1ac | [
"MIT"
] | null | null | null | src/components/pages/home/drawer-content/profile-contacts/profile-body/index.js | effortlesscoding/react-developer | cb0cf35c1c3a114aa9b52a69ca459bf1c963a1ac | [
"MIT"
] | null | null | null | src/components/pages/home/drawer-content/profile-contacts/profile-body/index.js | effortlesscoding/react-developer | cb0cf35c1c3a114aa9b52a69ca459bf1c963a1ac | [
"MIT"
] | null | null | null | export * from './profile-body.component'; | 41 | 41 | 0.731707 |
b9e4feeae2e0bfe3cdcf18ccc7a973aa2855511b | 433 | js | JavaScript | index.js | antonioalbert349/ZeroTwo3.0 | 55d83f58f66c07f2d0ff0579be49df1fb270d584 | [
"MIT"
] | null | null | null | index.js | antonioalbert349/ZeroTwo3.0 | 55d83f58f66c07f2d0ff0579be49df1fb270d584 | [
"MIT"
] | null | null | null | index.js | antonioalbert349/ZeroTwo3.0 | 55d83f58f66c07f2d0ff0579be49df1fb270d584 | [
"MIT"
] | null | null | null | const Discord = require("discord.js");
const fs = require("fs");
const firebase = require("firebase");
const banco = require("./banco.js");
const ms = require("parse-ms");
const server = require("./server.js");
const client = new Discord.Client();
module.exports = client;
const message = require("./events/message.js");
const ready = require("./events/ready.js");
console.log(`eventos carregados`)
client.login(process.env.TOKEN); | 30.928571 | 47 | 0.706697 |
b9e551cc865435817cc03c97194dea5fd100d0d5 | 2,279 | js | JavaScript | src/components/ResultsTable.js | jonnyi/leaderboard-app | f822cea33d5da71b85059a0541136af2d6a47e1c | [
"MIT"
] | 1 | 2018-01-30T15:51:45.000Z | 2018-01-30T15:51:45.000Z | src/components/ResultsTable.js | jonnyi/leaderboard-app | f822cea33d5da71b85059a0541136af2d6a47e1c | [
"MIT"
] | null | null | null | src/components/ResultsTable.js | jonnyi/leaderboard-app | f822cea33d5da71b85059a0541136af2d6a47e1c | [
"MIT"
] | null | null | null | import React from 'react';
import RowSelector from './RowSelector';
import ResultsRow from './ResultsRow';
class ResultsTable extends React.PureComponent {
constructor(props) {
super(props);
this.sortBy = this.sortBy.bind(this);
this.state = {
tableSortedBy: 'recent'
};
}
componentDidMount() {
this.props.updateTableData('recent');
}
sortBy(sortByValue) {
this.props.updateLoadingFlag(true);
this.props.updateTableData(sortByValue);
this.props.updateTitle(
sortByValue == 'recent'
? 'Top scores in the last 30 days!'
: 'Top scores of all time!'
);
this.setState({
tableSortedBy: sortByValue
});
}
render() {
const { updateRowCount, rowCount, scoreData, loadingFlag } = this.props;
const { tableSortedBy } = this.state;
const scoreDataTrimmed = scoreData.slice(0, rowCount);
const isSortedByRecent = tableSortedBy == 'recent' ? true : false;
if (loadingFlag) {
return <h2>Loading...</h2>;
} else {
return (
<div id="results-table">
{loadingFlag}
<RowSelector updateRowCount={updateRowCount} rowCount={rowCount} />
<div className="table-responsive">
<table className="table table-sm table-striped">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th
id="recent-selector"
className={isSortedByRecent ? 'selected thCta' : 'thCta'}
onClick={() => this.sortBy('recent')}
>
Last 30 Days
</th>
<th
id="alltime-selector"
className={!isSortedByRecent ? 'selected thCta' : 'thCta'}
onClick={() => this.sortBy('alltime')}
>
All time score
</th>
</tr>
</thead>
<tbody>
{scoreDataTrimmed.map((row, i) => (
<ResultsRow key={i} rowData={row} rowNumber={i + 1} />
))}
</tbody>
</table>
</div>
</div>
);
}
}
}
export default ResultsTable;
| 29.217949 | 78 | 0.502852 |
b9e58cfc2bab4bcc9c344f3c3611f9398fa6cb74 | 606 | js | JavaScript | src/Components/ImageGalleryItem/ImageGalleryItem.js | Alina-Pavliuk/goit-react-hw-03-image-finder | 678623f51864dcbc6a92b5ccd6be42025443508b | [
"MIT"
] | null | null | null | src/Components/ImageGalleryItem/ImageGalleryItem.js | Alina-Pavliuk/goit-react-hw-03-image-finder | 678623f51864dcbc6a92b5ccd6be42025443508b | [
"MIT"
] | null | null | null | src/Components/ImageGalleryItem/ImageGalleryItem.js | Alina-Pavliuk/goit-react-hw-03-image-finder | 678623f51864dcbc6a92b5ccd6be42025443508b | [
"MIT"
] | null | null | null | import styles from "./ImageGalleryItem.module.css"
import React from 'react';
import PropTypes from "prop-types"
const ImageGalleryItem = ({ webformatURL, largeImageURL, type, activePictures }) => {
return (
<li className={styles.ImageGalleryItem} onClick={activePictures} >
<img src={webformatURL} alt={type} className={styles.ImageGalleryItem_image} data-source={largeImageURL} />
</li>);
};
ImageGalleryItem.propTypes = {
activePictures: PropTypes.func,
type: PropTypes.string,
largeImageURL: PropTypes.string,
webformatURL: PropTypes.string,
}
export default ImageGalleryItem; | 35.647059 | 113 | 0.750825 |
b9e646752cd70857c2281a6f15cec8314091753a | 516 | js | JavaScript | assets/js/interactive-tutorial.js | svj-aventador/xrpl-dev-portal | c54395ba17b02b9454ac6677166dc42043fba72a | [
"Apache-2.0"
] | null | null | null | assets/js/interactive-tutorial.js | svj-aventador/xrpl-dev-portal | c54395ba17b02b9454ac6677166dc42043fba72a | [
"Apache-2.0"
] | null | null | null | assets/js/interactive-tutorial.js | svj-aventador/xrpl-dev-portal | c54395ba17b02b9454ac6677166dc42043fba72a | [
"Apache-2.0"
] | null | null | null | // Helper functions for interactive tutorials
function slugify(s) {
const unacceptable_chars = /[^A-Za-z0-9._ ]+/
const whitespace_regex = /\s+/
s = s.replace(unacceptable_chars, "")
s = s.replace(whitespace_regex, "_")
s = s.toLowerCase()
if (!s) {
s = "_"
}
return s
}
function complete_step(step_name) {
const step_id = slugify(step_name)
$(".bc-"+step_id).removeClass("active").addClass("done")
$(".bc-"+step_id).next().removeClass("disabled").addClass("active")
}
| 25.8 | 70 | 0.631783 |
b9e6761645875d170cba18bc475fb7ee4bb805e4 | 1,344 | js | JavaScript | test/slonik/sqlFragmentFactories/createArraySqlFragment.js | nem035/slonik | 3fd1b7ac9e01a45a41e073d05a5e693531193444 | [
"BSD-3-Clause"
] | null | null | null | test/slonik/sqlFragmentFactories/createArraySqlFragment.js | nem035/slonik | 3fd1b7ac9e01a45a41e073d05a5e693531193444 | [
"BSD-3-Clause"
] | null | null | null | test/slonik/sqlFragmentFactories/createArraySqlFragment.js | nem035/slonik | 3fd1b7ac9e01a45a41e073d05a5e693531193444 | [
"BSD-3-Clause"
] | null | null | null | // @flow
import test from 'ava';
import createArraySqlFragment from '../../../src/sqlFragmentFactories/createArraySqlFragment';
import {
ArrayToken,
} from '../../../src/tokens';
test('creates an empty array binding', (t) => {
const sqlFragment = createArraySqlFragment({
memberType: 'int4',
type: ArrayToken,
values: [],
}, 0);
t.assert(sqlFragment.sql === '$1::"int4"[]');
t.deepEqual(sqlFragment.values, [[]]);
});
test('creates an array binding with a single value', (t) => {
const sqlFragment = createArraySqlFragment({
memberType: 'int4',
type: ArrayToken,
values: [
1,
],
}, 0);
t.assert(sqlFragment.sql === '$1::"int4"[]');
t.deepEqual(sqlFragment.values, [[1]]);
});
test('creates an array binding with multiple values', (t) => {
const sqlFragment = createArraySqlFragment({
memberType: 'int4',
type: ArrayToken,
values: [
1,
2,
3,
],
}, 0);
t.assert(sqlFragment.sql === '$1::"int4"[]');
t.deepEqual(sqlFragment.values, [[1, 2, 3]]);
});
test('offsets parameter position', (t) => {
const sqlFragment = createArraySqlFragment({
memberType: 'int4',
type: ArrayToken,
values: [
1,
2,
3,
],
}, 3);
t.assert(sqlFragment.sql === '$4::"int4"[]');
t.deepEqual(sqlFragment.values, [[1, 2, 3]]);
});
| 21.677419 | 94 | 0.588542 |
b9e6acbf690b20e4a5be283844f0e5530ae2f8c5 | 1,928 | js | JavaScript | app/scripts/smb_client/auth/subkey.js | godwebpl/chromeos-filesystem-cifs | f33713ddc7051dc99152945cd2c895d40f43f9bb | [
"BSD-3-Clause"
] | 65 | 2015-05-27T22:13:20.000Z | 2021-09-01T10:41:11.000Z | app/scripts/smb_client/auth/subkey.js | godwebpl/chromeos-filesystem-cifs | f33713ddc7051dc99152945cd2c895d40f43f9bb | [
"BSD-3-Clause"
] | 155 | 2015-06-02T08:11:10.000Z | 2021-10-11T14:05:07.000Z | app/scripts/smb_client/auth/subkey.js | godwebpl/chromeos-filesystem-cifs | f33713ddc7051dc99152945cd2c895d40f43f9bb | [
"BSD-3-Clause"
] | 20 | 2015-06-02T14:59:29.000Z | 2021-01-28T01:06:05.000Z | (function(Auth, Types, Constants) {
"use strict";
// Constructor
var Subkey = function() {
this.types_ = new Types();
};
// Public functions
// originalMasterKey: ArrayBuffer
Subkey.prototype.createClientSigningKey = function(originalMasterKey) {
return calculaeKey.call(
this, originalMasterKey, Constants.NTLM2_SUBKEY_CLIENT_SIGNING_KEY);
};
// originalMasterKey: ArrayBuffer
Subkey.prototype.createServerSigningKey = function(originalMasterKey) {
return calculaeKey.call(
this, originalMasterKey, Constants.NTLM2_SUBKEY_SERVER_SIGNING_KEY);
};
// weakenedMasterKey: ArrayBuffer
Subkey.prototype.createClientSealingKey = function(weakenedMasterKey) {
return calculaeKey.call(
this, weakenedMasterKey, Constants.NTLM2_SUBKEY_CLIENT_SEALING_KEY);
};
// weakenedMasterKey: ArrayBuffer
Subkey.prototype.createServerSealingKey = function(weakenedMasterKey) {
return calculaeKey.call(
this, weakenedMasterKey, Constants.NTLM2_SUBKEY_SERVER_SEALING_KEY);
};
// Private functions
var calculaeKey = function(originalMasterKey, magicString) {
var magic = this.types_.createSimpleStringArrayBuffer(magicString);
var total = originalMasterKey.byteLength + magic.byteLength + 1;
var buffer = new ArrayBuffer(total);
var array = new Uint8Array(buffer);
array.set(new Uint8Array(originalMasterKey), 0);
array.set(new Uint8Array(magic), originalMasterKey.byteLength);
array[total - 1] = 0; // Null terminated
var wordArray = CryptoJS.lib.WordArray.create(buffer);
var md5 = CryptoJS.MD5(wordArray);
// This returns the result as ArrayBuffer
return md5.toArrayBuffer();
};
// Export
Auth.Subkey = Subkey;
})(SmbClient.Auth, SmbClient.Types, SmbClient.Constants);
| 31.606557 | 80 | 0.686722 |
b9e79a8c6649c91cc6852e00e4ac6896906cb6a4 | 2,568 | js | JavaScript | dist/bundle.js | jidan745le/egg-movable | cd5924f6c1e00ce841c308329e4ee514f80f8b9b | [
"MIT"
] | null | null | null | dist/bundle.js | jidan745le/egg-movable | cd5924f6c1e00ce841c308329e4ee514f80f8b9b | [
"MIT"
] | null | null | null | dist/bundle.js | jidan745le/egg-movable | cd5924f6c1e00ce841c308329e4ee514f80f8b9b | [
"MIT"
] | null | null | null | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.EggMovable = factory());
}(this, (function () { 'use strict';
class Movable {
constructor(selector) {
if (!selector instanceof HTMLElement && typeof selector !== "string") {
throw TypeError("Constructor params Expected to be typeof String or HTMLElement")
}
// debugger;
this.selectorCollections = selector instanceof HTMLElement ?
[selector] :
document.querySelectorAll(selector);
this.dataTransfer = new Map;
}
wrapProxyForEvent(e) {
return new Proxy(e, {
get: (target, key, receiver) => {
if (key === "dataTransfer") {
return this.dataTransfer;
}
return Reflect.get(target, key)
}
})
}
subscribe(...args) {
const [mouseDownHandler, moveHandler, mouseUpHandler] = args;
let onMoveHandler;
let onMouseupHandler;
document.addEventListener("mousedown", e => {
console.log(this.selectorCollections);
if (Array.prototype.includes.call(this.selectorCollections,e.target)) {
//如果命中所需选取的元素
const { clientX, clientY } = e;
const wrappedEvent = this.wrapProxyForEvent(e);
wrappedEvent.dataTransfer.set("dragged", e.target);
wrappedEvent.dataTransfer.set("position", { clientX, clientY });
mouseDownHandler(wrappedEvent);
document.addEventListener("mousemove", (onMoveHandler = e => {
moveHandler(e, this.dataTransfer);
}));
document.addEventListener("mouseup", (onMouseupHandler = e => {
const wrappedEvent = this.wrapProxyForEvent(e);
mouseUpHandler(wrappedEvent);
document.removeEventListener("mousemove", onMoveHandler);
document.removeEventListener("mouseup", onMouseupHandler);
}));
}
});
}
}
return Movable;
})));
| 38.328358 | 110 | 0.51324 |
b9e855c5ce9e2f4fbf94c582122d26731908036a | 309 | js | JavaScript | src/dev/js/App/Store/projectAnimation/reducers.js | BorisLaporte/ronan_polin-portfolio | 4905364b9de8fac36c9f85f321c46e355f2d9630 | [
"MIT"
] | null | null | null | src/dev/js/App/Store/projectAnimation/reducers.js | BorisLaporte/ronan_polin-portfolio | 4905364b9de8fac36c9f85f321c46e355f2d9630 | [
"MIT"
] | null | null | null | src/dev/js/App/Store/projectAnimation/reducers.js | BorisLaporte/ronan_polin-portfolio | 4905364b9de8fac36c9f85f321c46e355f2d9630 | [
"MIT"
] | null | null | null | import {SETUP_TIME} from './actions'
function projectAnimationReducer(state = {
timers: {}
}, action) {
switch (action.type) {
case SETUP_TIME:
return Object.assign({}, state, {
timers: action.timers
})
default:
return state
}
}
export default projectAnimationReducer | 19.3125 | 42 | 0.647249 |
b9e8cd0b25b26582d7faebe58ddaa923ed4868bf | 557 | js | JavaScript | src/js/astrology-service.js | bordonj/astrological-movie | c415448d3092c42c59e4ea925124a7408e974b87 | [
"MIT"
] | null | null | null | src/js/astrology-service.js | bordonj/astrological-movie | c415448d3092c42c59e4ea925124a7408e974b87 | [
"MIT"
] | null | null | null | src/js/astrology-service.js | bordonj/astrological-movie | c415448d3092c42c59e4ea925124a7408e974b87 | [
"MIT"
] | 4 | 2021-07-08T23:56:29.000Z | 2021-07-09T03:31:02.000Z | //import axios from "axios";
var axios = require("axios").default;
export default class Zodiac {
static async fetchData(input) {
var options = {
method: 'POST',
url: 'https://sameer-kumar-aztro-v1.p.rapidapi.com/',
params: {sign: `${input}`, day: 'today'},
headers: {
'x-rapidapi-key': `${process.env.ZODIAC_API_KEY}`,
'x-rapidapi-host': 'sameer-kumar-aztro-v1.p.rapidapi.com'
}
};
let data = await axios.request(options);
return data;
} catch(error) {
return error;
}
}
| 21.423077 | 65 | 0.583483 |
b9e8f49f973feb7e139c8fce46c1065bf25fd3fa | 2,930 | js | JavaScript | src/renderer/components/Content/index.js | rubenandre/simulator | ff2529ca967ee69790701967525564a13442fa44 | [
"MIT"
] | 66 | 2019-03-13T01:58:44.000Z | 2022-03-27T14:59:59.000Z | src/renderer/components/Content/index.js | rubenandre/simulator | ff2529ca967ee69790701967525564a13442fa44 | [
"MIT"
] | 11 | 2019-04-05T11:24:25.000Z | 2021-12-04T23:51:47.000Z | src/renderer/components/Content/index.js | rubenandre/simulator | ff2529ca967ee69790701967525564a13442fa44 | [
"MIT"
] | 37 | 2019-03-14T23:06:36.000Z | 2022-02-02T15:39:54.000Z | import React from 'react'
import styled from 'styled-components'
import Exams from './Main/Exams'
import History from './Main/History'
import Sessions from './Main/Sessions'
import Cover from './Cover'
import Exam from './Exam'
import Review from './Review'
import Options from './Options'
import AddRemoteExam from './AddRemoteExam'
const ContentStyles = styled.div`
display: grid;
justify-items: center;
align-items: center;
padding: 2rem;
padding-right: ${props => (props.open ? '28rem' : '7rem')};
transition: 0.3s;
`
export default class Content extends React.Component {
renderContent = () => {
const p = this.props
if (p.mode === 0) {
if (p.mainMode === 0) {
return (
<Exams
exams={p.exams}
setIndexExam={p.setIndexExam}
initExam={p.initExam}
setConfirmDeleteExam={p.setConfirmDeleteExam}
/>
)
} else if (p.mainMode === 1) {
return (
<History
history={p.history}
setIndexHistory={p.setIndexHistory}
setConfirmReviewExam={p.setConfirmReviewExam}
setConfirmDeleteHistory={p.setConfirmDeleteHistory}
/>
)
} else if (p.mainMode === 2) {
return (
<Sessions
sessions={p.sessions}
setIndexSession={p.setIndexSession}
setConfirmStartSession={p.setConfirmStartSession}
setConfirmDeleteSession={p.setConfirmDeleteSession}
/>
)
} else if (p.mainMode === 3) {
return <Options options={p.options} />
} else if (p.mainMode === 4) {
return <AddRemoteExam loadRemoteExam={p.loadRemoteExam} />
}
} else if (p.mode === 1) {
return <Cover cover={p.exam.cover} />
} else if (p.mode === 2) {
return (
<Exam
explanationRef={p.explanationRef}
explanation={p.explanation}
examMode={p.examMode}
exam={p.exam}
question={p.question}
answers={p.answers}
fillIns={p.fillIns}
orders={p.orders}
intervals={p.intervals}
marked={p.marked}
confirmPauseTimer={p.confirmPauseTimer}
onBookmarkQuestion={p.onBookmarkQuestion}
onMultipleChoice={p.onMultipleChoice}
onMultipleAnswer={p.onMultipleAnswer}
onFillIn={p.onFillIn}
onListOrder={p.onListOrder}
setIntervals={p.setIntervals}
/>
)
} else if (p.mode === 3) {
return (
<Review
exam={p.exam}
reviewMode={p.reviewMode}
reviewType={p.reviewType}
reviewQuestion={p.reviewQuestion}
report={p.report}
/>
)
} else {
return null
}
}
render() {
const {
props: { open }
} = this
return <ContentStyles open={open}>{this.renderContent()}</ContentStyles>
}
}
| 28.446602 | 76 | 0.569966 |
b9e8f7d5cbb76cd44e29df036286658fb3240b08 | 7,892 | js | JavaScript | p/racer/track.js | llnek/czlabio | 7ea97081d2fca1f0aa851e6b28315e3db7bfc64d | [
"Apache-2.0"
] | null | null | null | p/racer/track.js | llnek/czlabio | 7ea97081d2fca1f0aa851e6b28315e3db7bfc64d | [
"Apache-2.0"
] | null | null | null | p/racer/track.js | llnek/czlabio | 7ea97081d2fca1f0aa851e6b28315e3db7bfc64d | [
"Apache-2.0"
] | null | null | null | /* 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.
*
* Copyright © 2020-2022, Kenneth Leung. All rights reserved. */
;(function(window,UNDEF){
"use strict";
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
//original source: https://github.com/jakesgordon/javascript-racer
window["io/czlab/racer/track"]= function(Mojo,SEGLEN){
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
const {Sprites:_S,
Scenes:_Z,
Input:_I,
Game:_G,
v2:_V,
math:_M,
ute:_,is}=Mojo;
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
const int=Math.floor, ceil=Math.ceil;
const sin=Math.sin, cos=Math.cos;
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
const CARS = ["car01.png","car02.png","car03.png","car04.png","semi.png","truck.png"];
const FLORA = ["tree1.png", "tree2.png", "dead_tree1.png", "dead_tree2.png",
"palm_tree.png", "bush1.png", "bush2.png", "cactus.png",
"stump.png", "boulder1.png", "boulder2.png", "boulder3.png"];
const ROAD= { E:25, M:50, H:100 };
const BEND= { E:2, M:4, H:6 };
const HILL= { E:20, M:40, H:60 };
const C_LIGHT={ road: _S.color("#6B6B6B"), grass: _S.color("#10AA10"),
rumble: _S.color("#555555"), lane: _S.color("#CCCCCC") };
const C_DARK={ road: _S.color("#696969"), grass: _S.color("#009A00"), rumble: _S.color("#bbbbbb") };
const C_START= { road: _S.SomeColors.white, grass: _S.SomeColors.white, rumble: _S.SomeColors.white };
const C_FINISH= { road: _S.SomeColors.black, grass: _S.SomeColors.black, rumble: _S.SomeColors.yellow };
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
const easeInOut=(a,b,perc)=> a + (b-a)*((-Math.cos(perc*Math.PI)/2) + 0.5);
const easeIn=(a,b,perc)=> a + (b-a)*Math.pow(perc,2);
const lastY=()=> _G.lines.length == 0 ? 0 : _.last(_G.lines).p2.world.y;
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
const addBend=(n=ROAD.M, curve=BEND.M, height=0)=> addStretch(n, curve, height);
const addHill=(n=ROAD.M, height=HILL.M)=> addStretch(n,0, height);
const addRoad=(n=ROAD.M)=> addStretch(n,0, 0);
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
const addLowRollingHills=(n=ROAD.E, height=HILL.E)=>
[[n, 0, height/2],
[n, 0, -height],
[n, BEND.E, height],
[n, 0, 0],
[n, -BEND.E, height/2],
[n, 0, 0]].forEach(a=>addStretch(...a));
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
const addSBends=()=>
[[ROAD.M, -BEND.E, 0],
[ROAD.M, BEND.M, HILL.M],
[ROAD.M, BEND.E, -HILL.E],
[ROAD.M, -BEND.E, HILL.M],
[ROAD.M, -BEND.M, -HILL.M]].forEach(a=>addStretch(...a));
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
const addBumps=()=>
[[10, 0, 5],
[10, 0, -2],
[10, 0, -5],
[10, 0, 8],
[10, 0, 5],
[10, 0, -7],
[10, 0, 5],
[10, 0, -2]].forEach(a=>addStretch(...a));
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
const addDownhillToEnd=(n=200)=> addStretch(n, -BEND.E, - lastY()/SEGLEN);
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function addStretch(enter, curve, y){
function newSeg(curve,Y){
let n = _G.lines.length;
_G.lines.push({
index: n,
p1:{ world: { y: lastY(), z: n * SEGLEN }, camera: {}, screen: {} },
p2:{ world: { y: Y, z: (n+1) * SEGLEN }, camera: {}, screen: {} },
curve,
sprites: [],
cars: [],
color: _M.ndiv(n,_G.rumbles)%2 ? C_DARK : C_LIGHT
});
}
let hold=enter,
leave=enter,
startY= lastY(),
total = enter + hold + leave,
n,endY= startY + (_.toNum(y, 0) * SEGLEN);
for(n = 0 ; n < enter ; ++n)
newSeg(easeIn(0, curve, n/enter), easeInOut(startY, endY, n/total));
for(n = 0 ; n < hold ; ++n)
newSeg(curve, easeInOut(startY, endY, (enter+n)/total));
for(n = 0 ; n < leave ; ++n)
newSeg(easeInOut(curve, 0, n/leave), easeInOut(startY, endY, (enter+hold+n)/total));
}
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function addTrees(){
function add(n, sprite, offset){
_G.lines[n].sprites.push({source: sprite, offset, w: Mojo.tcached(sprite).width })
}
let n, side, sprite, offset;
for(n = 10; n < 200; n += 4 + int(n/100)){
if(_.rand()<0.3){
add(n, "palm_tree.png", 0.5 + _.rand()*0.5);
add(n, "palm_tree.png", 1 + _.rand()*2);
}
}
for(n = 250 ; n < 1000 ; n += 5){
if(_.rand()>0.7){
add(n,"column.png", 1.1);
add(n + _.randInt2(0,5), "tree1.png", -1 - _.rand() * 2);
add(n + _.randInt2(0,5), "tree2.png", -1 - _.rand() * 2);
}
}
for(n = 200 ; n < _G.lines.length ; n += 3){
if(_.rand()<0.3)
add(n, _.randItem(FLORA), _.randSign * (2 + _.rand() * 5));
}
for(n = 1000 ; n < (_G.lines.length-50) ; n += 100){
if(_.rand()>0.7){
side = _.randSign();
for(let i = 0 ; i < 20 ; ++i){
if(_.rand()<0.3){
sprite = _.randItem(FLORA);
offset = side * (1.5 + _.rand());
add(n + _.randInt2(0, 50), sprite, offset);
}
}
}
}
}
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function addCars(){
let t,n, car, segment, offset, z, sprite, speed;
_G.cars.length=0;
for(n = 0; n < _G.totalCars; ++n){
offset = _.rand() * _.randSign()*0.8;
z = int(_.rand() * _G.lines.length) * SEGLEN;
sprite = _.randItem(CARS);
speed = _G.maxSpeed/4 + _.rand() * _G.maxSpeed/(sprite == "semi.png" ? 4 : 2);
car = { offset, z, sprite, speed, w: Mojo.tcached(sprite).width};
_G.getLine(car.z).cars.push(car);
_G.cars.push(car);
}
}
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
_G.initTrack=function(){
_G.lines.length=0;
addRoad(ROAD.E);
addLowRollingHills();
addSBends();
addBend(ROAD.M, BEND.M, HILL.E);
addBumps();
addLowRollingHills();
addBend(ROAD.H*2, BEND.M, HILL.M);
addRoad();
addHill(ROAD.M, HILL.H);
addSBends();
addBend(ROAD.H, -BEND.M, 0);
addHill(ROAD.H, HILL.H);
addBend(ROAD.H, BEND.M, -HILL.E);
addBumps();
addHill(ROAD.H, -HILL.M);
addRoad();
addSBends();
addDownhillToEnd();
addTrees();
addCars();
_G.lines[_G.getLine(_G.player.z).index + 2].color = C_START;
_G.lines[_G.getLine(_G.player.z).index + 3].color = C_START;
for(let n = 0 ; n < _G.rumbles ; ++n)
_G.lines[_G.lines.length-1-n].color = C_FINISH;
_G.SEGN=_G.lines.length;
_G.trackLength = _G.SEGN * SEGLEN;
};
}
})(this);
| 37.226415 | 112 | 0.449062 |
b9e900ccdacee64cf595ed3839d6fbf9858c6fd2 | 2,565 | js | JavaScript | packages/d3fc-technical-indicator/examples/macd.js | Ro4052/d3fc | b660aef7bd0e57bd2712fb6d3e7d7d0e90f4524c | [
"MIT"
] | 35 | 2020-03-25T06:50:08.000Z | 2021-12-16T10:54:52.000Z | packages/d3fc-technical-indicator/examples/macd.js | Ro4052/d3fc | b660aef7bd0e57bd2712fb6d3e7d7d0e90f4524c | [
"MIT"
] | 143 | 2019-03-07T20:53:33.000Z | 2022-03-18T15:26:58.000Z | packages/d3fc-technical-indicator/examples/macd.js | Ro4052/d3fc | b660aef7bd0e57bd2712fb6d3e7d7d0e90f4524c | [
"MIT"
] | 3 | 2019-11-27T08:07:07.000Z | 2021-12-23T19:48:14.000Z | const macdExample = () => {
let xScale = d3.scaleTime();
let yScale = d3.scaleLinear();
let crossValue = d => d.date;
const macdLine = fc.seriesSvgLine();
const signalLine = fc.seriesSvgLine();
const divergenceBar = fc.seriesSvgBar();
const multiSeries = fc.seriesSvgMulti();
const macd = (selection) => {
macdLine.crossValue(crossValue)
.mainValue(d => d.macd);
signalLine.crossValue(crossValue)
.mainValue(d => d.signal);
divergenceBar.crossValue(crossValue)
.mainValue(d => d.divergence);
multiSeries.xScale(xScale)
.yScale(yScale)
.series([divergenceBar, macdLine, signalLine])
.decorate((g, data, index) => {
g.enter()
.attr('class', (d, i) => (
'multi ' + ['macd-divergence', 'macd', 'macd-signal'][i]
));
});
selection.call(multiSeries);
};
macd.xScale = (...args) => {
if (!args.length) {
return xScale;
}
xScale = args[0];
return macd;
};
macd.crossValue = (...args) => {
if (!args.length) {
return crossValue;
}
crossValue = args[0];
return macd;
};
macd.yScale = (...args) => {
if (!args.length) {
return yScale;
}
yScale = args[0];
return macd;
};
fc.rebind(macd, divergenceBar, 'barWidth');
return macd;
};
const width = 500;
const height = 250;
const container = d3.select('#macd')
.append('svg')
.attr('width', width)
.attr('height', height);
const dataGenerator = fc.randomFinancial()
.startDate(new Date(2014, 1, 1));
const data = dataGenerator(50);
const xScale = d3.scaleTime()
.domain(fc.extentDate().accessors([d => d.date])(data))
.range([0, width]);
// START
// Create and apply the macd algorithm
const macdAlgorithm = fc.indicatorMacd()
.fastPeriod(4)
.slowPeriod(10)
.signalPeriod(5)
.value(d => d.close);
const macdData = macdAlgorithm(data);
const mergedData = data.map((d, i) => Object.assign({}, d, macdData[i]));
// the MACD is rendered on its own scale, centered around zero
const yDomain = fc.extentLinear()
.accessors([d => d.macd])
.symmetricalAbout(0);
const yScale = d3.scaleLinear()
.domain(yDomain(mergedData))
.range([height, 0]);
// Create the renderer
const macd = macdExample()
.xScale(xScale)
.yScale(yScale);
// Add it to the container
container.append('g')
.datum(mergedData)
.call(macd);
| 24.428571 | 76 | 0.575828 |
b9e935fe0a7a9f97dcc9082b06ac8f864674e4df | 5,638 | js | JavaScript | dist/compiler.js | niieani/node-webpackify | c32f740f8b4985045a78ba5aeaacc498b01b71ae | [
"MIT"
] | 55 | 2018-05-02T00:29:25.000Z | 2021-09-21T09:56:57.000Z | dist/compiler.js | niieani/node-webpackify | c32f740f8b4985045a78ba5aeaacc498b01b71ae | [
"MIT"
] | null | null | null | dist/compiler.js | niieani/node-webpackify | c32f740f8b4985045a78ba5aeaacc498b01b71ae | [
"MIT"
] | 3 | 2018-05-21T12:26:03.000Z | 2019-07-24T22:33:40.000Z | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const webpack_1 = tslib_1.__importDefault(require("webpack/lib/webpack"));
const fs_1 = tslib_1.__importDefault(require("fs"));
const SingleEntryDependency_1 = tslib_1.__importDefault(require("webpack/lib/dependencies/SingleEntryDependency"));
const SingleEntryPlugin_1 = tslib_1.__importDefault(require("webpack/lib/SingleEntryPlugin"));
const util_1 = require("util");
const util_webpack_1 = require("./util-webpack");
const deasync = require('deasync');
/** @typedef {import("webpack").Configuration} Configuration */
/**
* @typedef {{
* compile: function(callback : function(Error, string) : void): void,
* filename: string,
* request: string,
* needsTransforming: boolean,
* loaders: Array<Object>,
* }} SimpleCompiler
*/
/**
* @typedef {{
* compile: function(): Promise<string>,
* filename: string,
* request: string,
* needsTransforming: boolean,
* loaders: Array<Object>,
* }} SimpleCompilerAsync
*/
/**
* @typedef {{
* compile: function(): string,
* filename: string,
* request: string,
* needsTransforming: boolean,
* loaders: Array<Object>,
* }} SimpleCompilerSync
*/
/**
* @param {Configuration} wpOptions
* @param {function(Error, function(Error, SimpleCompiler=): void): void} callback
* @returns {function(string, string, function(Error, SimpleCompiler=): void): void}
*/
function getSimpleCompiler(wpOptions, callback) {
const compiler = webpack_1.default(wpOptions || {});
compiler.hooks.beforeRun.callAsync(compiler, (err) => {
if (err)
return callback(err);
const params = compiler.newCompilationParams();
compiler.hooks.beforeCompile.callAsync(params, (err) => {
if (err)
return callback(err);
compiler.hooks.compile.call(params);
const compilation = compiler.newCompilation(params);
const moduleFactory = compilation.dependencyFactories.get(SingleEntryDependency_1.default);
const { options, resolverFactory } = compiler;
// we never need to parse:
options.module.noParse = '';
callback(undefined, (request, context, callback) => {
moduleFactory.create({
context,
contextInfo: { issuer: '', compiler: 'webpack-node' },
dependencies: [SingleEntryPlugin_1.default.createDependency(request, 'main')]
}, (err, module) => {
if (err)
return callback(err);
const resolver = resolverFactory.get('normal', module.resolveOptions);
const compile = (callback) => {
module.build(options, compilation, resolver, fs_1.default, () => {
const { _source: sourceObject } = module;
if (sourceObject != null)
callback(null, sourceObject.source());
else
callback(new Error('No source returned'));
});
};
const resourceAndQuery = module.request != null
? util_webpack_1.buildFilename(module.request)
: [];
const filename = resourceAndQuery && resourceAndQuery.join('?');
const loaders = module.loaders || [];
callback(null, {
compile,
module,
request: module.request,
loaders,
resource: module.resource,
filename,
resourceAndQuery,
needsTransforming: resourceAndQuery.length > 1 || loaders.length > 1,
});
});
});
});
});
}
exports.getSimpleCompiler = getSimpleCompiler;
const getSimpleCompilerAsyncBase = util_1.promisify(exports.getSimpleCompiler);
const getSimpleCompilerSyncBase = deasync(exports.getSimpleCompiler);
/**
* @typedef {function(string, string): SimpleCompilerSync} GetModuleSync
*/
/**
* @type {function(Configuration): GetModuleSync}
*/
exports.getSimpleCompilerSync = (wpOptions) => {
const getModule = deasync(getSimpleCompilerSyncBase(wpOptions));
/**
* @param {string} request
* @param {string} context
* @returns {SimpleCompilerSync}
*/
return function getModuleSync(request, context) {
const _a = getModule(request, context), { compile } = _a, props = tslib_1.__rest(_a, ["compile"]);
/** @type {SimpleCompilerSync} */
return Object.assign({}, props, { compile: deasync(compile) });
};
};
/**
* @typedef {function(string, string): Promise<SimpleCompilerAsync>} GetModuleAsync
*/
/**
* @type {function(Configuration): Promise<GetModuleAsync>}
*/
exports.getSimpleCompilerAsync = async (wpOptions) => {
const getModule = util_1.promisify(await getSimpleCompilerAsyncBase(wpOptions));
/**
* @param {string} request
* @param {string} context
* @returns {Promise<GetModuleAsync>}
*/
return async function getModuleAsync(request, context) {
const _a = await getModule(request, context), { compile } = _a, props = tslib_1.__rest(_a, ["compile"]);
/** @type {SimpleCompilerAsync} */
return Object.assign({}, props, { compile: util_1.promisify(compile) });
};
};
//# sourceMappingURL=compiler.js.map | 40.855072 | 115 | 0.592409 |
b9e9de824bd5465782432a332ffc1b68aad57592 | 1,370 | js | JavaScript | public/js/list_image.js | riusDeath/project_telephone | 66aa63be83cac2917275d6b618d1e5a3cc134ce7 | [
"MIT"
] | null | null | null | public/js/list_image.js | riusDeath/project_telephone | 66aa63be83cac2917275d6b618d1e5a3cc134ce7 | [
"MIT"
] | null | null | null | public/js/list_image.js | riusDeath/project_telephone | 66aa63be83cac2917275d6b618d1e5a3cc134ce7 | [
"MIT"
] | null | null | null | $(document).ready(function(){
var dem = 0;
$(document).on('click', '.add_color', function(e){
e.preventDefault();
var color = '.color'+dem;
var total = '.total'+dem;
var color = $(color).val();
var total = $(total).val();
if (color.length !=0 && total !=0) {
dem ++;
$('.double_div').append('<div class="my_form"><div class="form-group"><input type="text" class="form-control color'+dem+' color" id="" placeholder="Color" name="color'+dem+'"></div><div class="form-group"><input type="number" min="1" class="form-control total'+dem+'" id="" placeholder="total" name="total'+dem+'"></div><div class="form-group"><input type="file" class="form-control " id="" placeholder="image" name="image'+dem+'"></div><a class="add_color form-group"><img src="{{url('/')}}/uploads/search.png" width="50px"></a></div>');
$('.dem').val(dem);
} else {
alert('not ok');
}
});
$(document).on('keyup', '.color', function(e){
e.preventDefault();
for (var i = dem - 1; i >= 0; i--) {
var c = '.color'+i;
if ($(this).val() == $(c).val()) {
$(this).val('');
break;
}
}
});
}); | 50.740741 | 554 | 0.464234 |
b9ea2dd02ff235b289fc77138b169572b6598995 | 20,284 | js | JavaScript | dashboard/src/actions/scheduledEvent.js | augustinebest/app | 74e797de5b43e8e9d34e6323ed8590f4c0bc1bb2 | [
"Apache-2.0"
] | null | null | null | dashboard/src/actions/scheduledEvent.js | augustinebest/app | 74e797de5b43e8e9d34e6323ed8590f4c0bc1bb2 | [
"Apache-2.0"
] | null | null | null | dashboard/src/actions/scheduledEvent.js | augustinebest/app | 74e797de5b43e8e9d34e6323ed8590f4c0bc1bb2 | [
"Apache-2.0"
] | null | null | null | import { postApi, getApi, deleteApi, putApi } from '../api';
import * as types from '../constants/scheduledEvent';
export const fetchscheduledEvent = (
projectId,
scheduledEventId
) => async dispatch => {
try {
dispatch(fetchscheduledEventRequest());
const response = await getApi(
`scheduledEvent/${projectId}/${scheduledEventId}`
);
dispatch(fetchscheduledEventSuccess(response.data));
} catch (error) {
const errorMsg =
error.response && error.response.data
? error.response.data
: error.data
? error.data
: error.message
? error.message
: 'Network Error';
dispatch(fetchscheduledEventFailure(errorMsg));
}
};
export function fetchscheduledEventSuccess(scheduledEvents) {
return {
type: types.FETCH_SCHEDULED_EVENT_SUCCESS,
payload: scheduledEvents,
};
}
export function fetchscheduledEventRequest() {
return {
type: types.FETCH_SCHEDULED_EVENT_REQUEST,
};
}
export function addScheduleEvent(payload) {
return {
type: types.ADD_SCHEDULE_EVENT,
payload: payload,
};
}
export function fetchscheduledEventFailure(error) {
return {
type: types.FETCH_SCHEDULED_EVENT_FAILURE,
payload: error,
};
}
export const fetchscheduledEvents = (
projectId,
skip,
limit
) => async dispatch => {
skip = Number(skip);
limit = Number(limit);
dispatch(fetchscheduledEventsRequest());
try {
let response = {};
if (!skip && !limit) {
response = await getApi(
`scheduledEvent/${projectId}?skip=${0}&limit=${10}`
);
} else {
response = await getApi(
`scheduledEvent/${projectId}?skip=${skip}&limit=${limit}`
);
}
const { data, count } = response.data;
dispatch(fetchscheduledEventsSuccess({ data, count, skip, limit }));
} catch (error) {
const errorMsg =
error.response && error.response.data
? error.response.data
: error.data
? error.data
: error.message
? error.message
: 'Network Error';
dispatch(fetchscheduledEventsFailure(errorMsg));
}
};
export function fetchscheduledEventsSuccess(scheduledEvents) {
return {
type: types.FETCH_SCHEDULED_EVENTS_SUCCESS,
payload: scheduledEvents,
};
}
export function fetchscheduledEventsRequest() {
return {
type: types.FETCH_SCHEDULED_EVENTS_REQUEST,
};
}
export function fetchscheduledEventsFailure(error) {
return {
type: types.FETCH_SCHEDULED_EVENTS_FAILURE,
payload: error,
};
}
export function fetchSubProjectScheduledEventsRequest() {
return {
type: types.FETCH_SUBPROJECT_SCHEDULED_EVENTS_REQUEST,
};
}
export function fetchSubProjectScheduledEventsSuccess(payload) {
return {
type: types.FETCH_SUBPROJECT_SCHEDULED_EVENTS_SUCCESS,
payload,
};
}
export function fetchSubProjectScheduledEventsFailure(error) {
return {
type: types.FETCH_SUBPROJECT_SCHEDULED_EVENTS_FAILURE,
payload: error,
};
}
export const fetchSubProjectScheduledEvents = projectId => async dispatch => {
try {
dispatch(fetchSubProjectScheduledEventsRequest());
const response = await getApi(
`scheduledEvent/${projectId}/scheduledEvents/all`
);
dispatch(fetchSubProjectScheduledEventsSuccess(response.data));
} catch (error) {
const errorMsg =
error.response && error.response.data
? error.response.data
: error.data
? error.data
: error.message
? error.message
: 'Network Error';
dispatch(fetchSubProjectScheduledEventsFailure(errorMsg));
}
};
export const fetchOngoingScheduledEventsRequest = () => ({
type: types.FETCH_ONGOING_SCHEDULED_EVENTS_REQUEST,
});
export const fetchOngoingScheduledEventsSuccess = payload => ({
type: types.FETCH_ONGOING_SCHEDULED_EVENTS_SUCCESS,
payload,
});
export const fetchOngoingScheduledEventsFailure = error => ({
type: types.FETCH_ONGOING_SCHEDULED_EVENTS_FAILURE,
payload: error,
});
export const fetchOngoingScheduledEvents = projectId => async dispatch => {
try {
dispatch(fetchOngoingScheduledEventsRequest());
const response = await getApi(
`scheduledEvent/${projectId}/ongoingEvent`
);
dispatch(fetchOngoingScheduledEventsSuccess(response.data));
} catch (error) {
const errorMsg =
error.response && error.response.data
? error.response.data
: error.data
? error.data
: error.message
? error.message
: 'Network Error';
dispatch(fetchOngoingScheduledEventsFailure(errorMsg));
}
};
export const fetchSubProjectOngoingScheduledEventsRequest = () => ({
type: types.FETCH_SUBPROJECT_ONGOING_SCHEDULED_EVENTS_REQUEST,
});
export const fetchSubProjectOngoingScheduledEventsSuccess = payload => ({
type: types.FETCH_SUBPROJECT_ONGOING_SCHEDULED_EVENTS_SUCCESS,
payload,
});
export const fetchSubProjectOngoingScheduledEventsFailure = error => ({
type: types.FETCH_SUBPROJECT_ONGOING_SCHEDULED_EVENTS_FAILURE,
payload: error,
});
export const fetchSubProjectOngoingScheduledEvents = projectId => async dispatch => {
try {
dispatch(fetchSubProjectOngoingScheduledEventsRequest());
const response = await getApi(
`scheduledEvent/${projectId}/ongoingEvent/all`
);
dispatch(fetchSubProjectOngoingScheduledEventsSuccess(response.data));
} catch (error) {
const errorMsg =
error.response && error.response.data
? error.response.data
: error.data
? error.data
: error.message
? error.message
: 'Network Error';
dispatch(fetchSubProjectOngoingScheduledEventsFailure(errorMsg));
}
};
export const createScheduledEvent = (projectId, values) => async dispatch => {
try {
dispatch(createScheduledEventRequest());
const response = await postApi(`scheduledEvent/${projectId}`, values);
dispatch(createScheduledEventSuccess(response.data));
} catch (error) {
const errorMsg =
error.response && error.response.data
? error.response.data
: error.data
? error.data
: error.message
? error.message
: 'Network Error';
dispatch(createScheduledEventFailure(errorMsg));
}
};
export function createScheduledEventSuccess(newScheduledEvent) {
return {
type: types.CREATE_SCHEDULED_EVENT_SUCCESS,
payload: newScheduledEvent,
};
}
export function createScheduledEventRequest() {
return {
type: types.CREATE_SCHEDULED_EVENT_REQUEST,
};
}
export function createScheduledEventFailure(error) {
return {
type: types.CREATE_SCHEDULED_EVENT_FAILURE,
payload: error,
};
}
export const deleteScheduledEvent = (
projectId,
scheduledEventId
) => async dispatch => {
try {
dispatch(deleteScheduledEventRequest());
const response = await deleteApi(
`scheduledEvent/${projectId}/${scheduledEventId}`
);
dispatch(deleteScheduledEventSuccess(response.data));
} catch (error) {
const errorMsg =
error.response && error.response.data
? error.response.data
: error.data
? error.data
: error.message
? error.message
: 'Network Error';
dispatch(deleteScheduledEventFailure(errorMsg));
}
};
export function deleteScheduledEventSuccess(payload) {
return {
type: types.DELETE_SCHEDULED_EVENT_SUCCESS,
payload,
};
}
export function deleteScheduledEventRequest() {
return {
type: types.DELETE_SCHEDULED_EVENT_REQUEST,
};
}
export function deleteScheduledEventFailure(error) {
return {
type: types.DELETE_SCHEDULED_EVENT_FAILURE,
payload: error,
};
}
export const cancelScheduledEvent = (
projectId,
scheduledEventId,
history,
redirect,
closeModal,
modalId
) => async dispatch => {
try {
dispatch(cancelScheduledEventRequest());
const response = await putApi(
`scheduledEvent/${projectId}/${scheduledEventId}/cancel`
);
dispatch(cancelScheduledEventSuccess(response.data));
closeModal({ id: modalId });
history.push(redirect);
} catch (error) {
const errorMsg =
error.response && error.response.data
? error.response.data
: error.data
? error.data
: error.message
? error.message
: 'Network Error';
dispatch(cancelScheduledEventFailure(errorMsg));
}
};
export function cancelScheduledEventSuccess(payload) {
return {
type: types.CANCEL_SCHEDULED_EVENT_SUCCESS,
payload,
};
}
export function cancelScheduledEventRequest() {
return {
type: types.CANCEL_SCHEDULED_EVENT_REQUEST,
};
}
export function cancelScheduledEventFailure(error) {
return {
type: types.CANCEL_SCHEDULED_EVENT_FAILURE,
payload: error,
};
}
export function updateScheduledEvent(projectId, scheduledEventId, values) {
return function(dispatch) {
const promise = putApi(
`scheduledEvent/${projectId}/${scheduledEventId}`,
values
);
dispatch(updateScheduledEventRequest());
promise.then(
function(scheduledEvent) {
dispatch(updateScheduledEventSuccess(scheduledEvent.data));
},
function(error) {
const errorMsg =
error.response && error.response.data
? error.response.data
: error.data
? error.data
: error.message
? error.message
: 'Network Error';
dispatch(updateScheduledEventFailure(errorMsg));
}
);
return promise;
};
}
export function updateScheduledEventSuccess(updatedScheduledEvent) {
return {
type: types.UPDATE_SCHEDULED_EVENT_SUCCESS,
payload: updatedScheduledEvent,
};
}
export function updateScheduledEventRequest() {
return {
type: types.UPDATE_SCHEDULED_EVENT_REQUEST,
};
}
export function updateScheduledEventFailure(error) {
return {
type: types.UPDATE_SCHEDULED_EVENT_FAILURE,
payload: error,
};
}
// Scheduled Event Note
export const fetchScheduledEventNotesInternalRequest = () => ({
type: types.FETCH_SCHEDULED_EVENT_NOTES_INTERNAL_REQUEST,
});
export const fetchScheduledEventNotesInternalSuccess = payload => ({
type: types.FETCH_SCHEDULED_EVENT_NOTES_INTERNAL_SUCCESS,
payload,
});
export const fetchScheduledEventNotesInternalFailure = error => ({
type: types.FETCH_SCHEDULED_EVENT_NOTES_INTERNAL_FAILURE,
payload: error,
});
export const fetchScheduledEventNotesInternal = (
projectId,
scheduledEventId,
limit,
skip,
type
) => async dispatch => {
try {
dispatch(fetchScheduledEventNotesInternalRequest());
skip = Number(skip);
limit = Number(limit);
let response = {};
if (skip >= 0 && limit >= 0) {
response = await getApi(
`scheduledEvent/${projectId}/${scheduledEventId}/notes?limit=${limit}&skip=${skip}&type=${type}`
);
} else {
response = await getApi(
`scheduledEvent/${projectId}/${scheduledEventId}/notes?`
);
}
const { data, count } = response.data;
dispatch(
fetchScheduledEventNotesInternalSuccess({
data,
count,
skip,
limit,
})
);
} catch (error) {
const errorMsg =
error.response && error.response.data
? error.response.data
: error.data
? error.data
: error.message
? error.message
: 'Network Error';
dispatch(fetchScheduledEventNotesInternalFailure(errorMsg));
}
};
export const createScheduledEventNoteRequest = () => ({
type: types.CREATE_SCHEDULED_EVENT_NOTE_REQUEST,
});
export const createScheduledEventNoteSuccess = payload => ({
type: types.CREATE_SCHEDULED_EVENT_NOTE_SUCCESS,
payload,
});
export const createScheduledEventNoteFailure = error => ({
type: types.CREATE_SCHEDULED_EVENT_NOTE_FAILURE,
payload: error,
});
export const createScheduledEventNote = (
projectId,
scheduledEventId,
data
) => async dispatch => {
try {
dispatch(createScheduledEventNoteRequest());
const response = await postApi(
`scheduledEvent/${projectId}/${scheduledEventId}/notes`,
data
);
dispatch(createScheduledEventNoteSuccess(response.data));
} catch (error) {
const errorMsg =
error.response && error.response.data
? error.response.data
: error.data
? error.data
: error.message
? error.message
: 'Network Error';
dispatch(createScheduledEventNoteFailure(errorMsg));
}
};
export const updateScheduledEventNoteInternalRequest = () => ({
type: types.UPDATE_SCHEDULED_EVENT_NOTE_INTERNAL_REQUEST,
});
export const updateScheduledEventNoteInternalSuccess = payload => ({
type: types.UPDATE_SCHEDULED_EVENT_NOTE_INTERNAL_SUCCESS,
payload,
});
export const updateScheduledEventNoteInternalFailure = error => ({
type: types.UPDATE_SCHEDULED_EVENT_NOTE_INTERNAL_FAILURE,
paylod: error,
});
export const updateScheduledEventNoteInternal = (
projectId,
scheduledEventId,
scheduledEventNoteId,
data
) => async dispatch => {
try {
dispatch(updateScheduledEventNoteInternalRequest());
const response = await putApi(
`scheduledEvent/${projectId}/${scheduledEventId}/notes/${scheduledEventNoteId}`,
data
);
dispatch(updateScheduledEventNoteInternalSuccess(response.data));
} catch (error) {
const errorMsg =
error.response && error.response.data
? error.response.data
: error.data
? error.data
: error.message
? error.message
: 'Network Error';
dispatch(updateScheduledEventNoteInternalFailure(errorMsg));
}
};
export const updateScheduledEventNoteInvestigationRequest = () => ({
type: types.UPDATE_SCHEDULED_EVENT_NOTE_INVESTIGATION_REQUEST,
});
export const updateScheduledEventNoteInvestigationSuccess = payload => ({
type: types.UPDATE_SCHEDULED_EVENT_NOTE_INVESTIGATION_SUCCESS,
payload,
});
export const updateScheduledEventNoteInvestigationFailure = error => ({
type: types.UPDATE_SCHEDULED_EVENT_NOTE_INVESTIGATION_FAILURE,
paylod: error,
});
export const updateScheduledEventNoteInvestigation = (
projectId,
scheduledEventId,
scheduledEventNoteId,
data
) => async dispatch => {
try {
dispatch(updateScheduledEventNoteInvestigationRequest());
const response = await putApi(
`scheduledEvent/${projectId}/${scheduledEventId}/notes/${scheduledEventNoteId}`,
data
);
dispatch(updateScheduledEventNoteInvestigationSuccess(response.data));
} catch (error) {
const errorMsg =
error.response && error.response.data
? error.response.data
: error.data
? error.data
: error.message
? error.message
: 'Network Error';
dispatch(updateScheduledEventNoteInvestigationFailure(errorMsg));
}
};
export const deleteScheduledEventNoteRequest = () => ({
type: types.DELETE_SCHEDULED_EVENT_NOTE_REQUEST,
});
export const deleteScheduledEventNoteSuccess = payload => ({
type: types.DELETE_SCHEDULED_EVENT_NOTE_SUCCESS,
payload,
});
export const deleteScheduledEventNoteFailure = error => ({
type: types.DELETE_SCHEDULED_EVENT_NOTE_FAILURE,
payload: error,
});
export const deleteScheduledEventNote = (
projectId,
scheduledEventId,
scheduledEventNoteId
) => async dispatch => {
try {
dispatch(deleteScheduledEventNoteRequest());
const response = await deleteApi(
`scheduledEvent/${projectId}/${scheduledEventId}/notes/${scheduledEventNoteId}`
);
dispatch(deleteScheduledEventNoteSuccess(response.data));
} catch (error) {
const errorMsg =
error.response && error.response.data
? error.response.data
: error.data
? error.data
: error.message
? error.message
: 'Network Error';
dispatch(deleteScheduledEventNoteFailure(errorMsg));
}
};
export const resolveScheduledEventRequest = () => ({
type: types.RESOLVE_SCHEDULED_EVENT_REQUEST,
});
export const resolveScheduledEventSuccess = payload => ({
type: types.RESOLVE_SCHEDULED_EVENT_SUCCESS,
payload,
});
export const resolveScheduledEventFailure = error => ({
type: types.RESOLVE_SCHEDULED_EVENT_FAILURE,
payload: error,
});
export const resolveScheduledEvent = (
projectId,
scheduledEventId
) => async dispatch => {
try {
dispatch(resolveScheduledEventRequest());
const response = await putApi(
`scheduledEvent/${projectId}/resolve/${scheduledEventId}`
);
dispatch(resolveScheduledEventSuccess(response.data));
} catch (error) {
const errorMsg =
error.response && error.response.data
? error.response.data
: error.data
? error.data
: error.message
? error.message
: 'Network Error';
dispatch(resolveScheduledEventFailure(errorMsg));
}
};
export const nextPage = projectId => {
return {
type: types.NEXT_PAGE,
payload: projectId,
};
};
export const prevPage = projectId => {
return {
type: types.PREV_PAGE,
payload: projectId,
};
};
export function fetchScheduledEventRequest() {
return {
type: types.FETCH_SCHEDULED_EVENT_REQUEST_SLUG,
};
}
export function fetchScheduledEventSuccess(payload) {
return {
type: types.FETCH_SCHEDULED_EVENT_SUCCESS_SLUG,
payload,
};
}
export function fetchScheduledEventFailure(error) {
return {
type: types.FETCH_SCHEDULED_EVENT_FAILURE_SLUG,
payload: error,
};
}
export function fetchScheduledEvent(projectId, slug) {
return function(dispatch) {
const promise = getApi(`scheduledEvent/${projectId}/slug/${slug}`);
dispatch(fetchScheduledEventRequest());
promise.then(
function(component) {
dispatch(fetchScheduledEventSuccess(component.data));
},
function(error) {
const errorMsg =
error.response && error.response.data
? error.response.data
: error.data
? error.data
: error.message
? error.message
: 'Network Error';
dispatch(fetchScheduledEventFailure(errorMsg));
}
);
return promise;
};
}
| 28.211405 | 112 | 0.613981 |
b9ea62595e6973f10b657ce6bc7acea6f11a10e7 | 4,255 | js | JavaScript | modals/JET.js | ojaha065/JustEnoughTime | d3a928575302d0d235805c126dbab1d9f63dfcd5 | [
"MIT"
] | 3 | 2019-10-14T10:59:04.000Z | 2021-06-09T14:51:27.000Z | modals/JET.js | ojaha065/JustEnoughTime | d3a928575302d0d235805c126dbab1d9f63dfcd5 | [
"MIT"
] | null | null | null | modals/JET.js | ojaha065/JustEnoughTime | d3a928575302d0d235805c126dbab1d9f63dfcd5 | [
"MIT"
] | null | null | null | "use strict";
let crypto;
try{
crypto = require("crypto");
}
catch(error){
throw "Crypto not available. Exiting."
}
const fs = require("fs");
const datafile = "./data.json";
if(!fs.existsSync(datafile)){
let emptyJSON = {
users: [
],
reservations: [
]
};
fs.writeFile(datafile,JSON.stringify(emptyJSON,null,2),(error) => {
if(!error){
console.info(`${datafile} file was not found and new one was created`);
}
});
}
module.exports = {
createAdminAccount: (password) => {
return new Promise((resolve,reject) => {
fs.readFile(datafile,"UTF-8",(error,data) => {
if(!error){
data = JSON.parse(data);
let adminAccount = {
username: "admin",
password: crypto.createHash("sha256").update(password).digest("hex")
}
data.users.push(adminAccount);
fs.writeFile(datafile,JSON.stringify(data,null,2),(error) => {
if(!error){
resolve();
}
else{
reject(error);
}
});
}
else{
reject(error);
}
});
});
},
newReservation: (body) => {
return new Promise((resolve,reject) => {
let thisReservation = {
name: body.name,
email: body.email || null,
message: body.extraInfo || null,
time : {
weekNumber: body.weekNumber,
year: body.year,
cellId: body.cellId
}
};
fs.readFile(datafile,"UTF-8",(error,data) => {
if(!error){
let currentData = JSON.parse(data);
let doesExist = currentData.reservations.find((reservation) => {
return reservation.time.weekNumber === thisReservation.time.weekNumber && reservation.time.year === thisReservation.time.year && reservation.time.cellId === thisReservation.time.cellId;
});
if(!doesExist){
currentData.reservations.push(thisReservation);
fs.writeFile(datafile,JSON.stringify(currentData,null,2),(error) => {
if(!error){
resolve();
}
else{
reject();
}
});
}
else{ // If there's already a reservation on this slot
reject();
}
}
else{ // Error reading file
reject();
}
});
});
},
getAllReservations: () => {
return new Promise((resolve,reject) => {
fs.readFile(datafile,"UTF-8",(error,data) => {
if(!error){
resolve(JSON.parse(data).reservations);
}
else{
reject(error);
}
});
});
},
login: (body) => {
return new Promise((resolve,reject) => {
fs.readFile(datafile,"UTF-8",(error,data) => {
if(!error){
let users = JSON.parse(data).users;
let hash = (body.password) ? crypto.createHash("sha256").update(body.password).digest("hex") : "Nope";
let thisUser = users.find((user) => {
return body.username === user.username;
});
if(thisUser && hash === thisUser.password){
resolve();
}
else{
reject();
}
}
else{
reject();
}
});
});
}
}; | 32.234848 | 209 | 0.389189 |
b9eb0b5a1a8f4bc247938cd8e0e25e47628d4de6 | 24,511 | js | JavaScript | ajax/libs/yui/3.6.0/autocomplete-list/autocomplete-list.js | platanus/cdnjs | daa228b7426fa70b2e3c82f9ef9e8d19548bc255 | [
"MIT"
] | 5 | 2015-02-20T16:11:30.000Z | 2017-05-15T11:50:44.000Z | ajax/libs/yui/3.6.0/autocomplete-list/autocomplete-list.js | platanus/cdnjs | daa228b7426fa70b2e3c82f9ef9e8d19548bc255 | [
"MIT"
] | null | null | null | ajax/libs/yui/3.6.0/autocomplete-list/autocomplete-list.js | platanus/cdnjs | daa228b7426fa70b2e3c82f9ef9e8d19548bc255 | [
"MIT"
] | 4 | 2015-07-14T16:16:05.000Z | 2021-03-10T08:15:54.000Z | YUI.add('autocomplete-list', function(Y) {
/**
Traditional autocomplete dropdown list widget, just like Mom used to make.
@module autocomplete
@submodule autocomplete-list
**/
/**
Traditional autocomplete dropdown list widget, just like Mom used to make.
@class AutoCompleteList
@extends Widget
@uses AutoCompleteBase
@uses WidgetPosition
@uses WidgetPositionAlign
@constructor
@param {Object} config Configuration object.
**/
var Lang = Y.Lang,
Node = Y.Node,
YArray = Y.Array,
// Whether or not we need an iframe shim.
useShim = Y.UA.ie && Y.UA.ie < 7,
// keyCode constants.
KEY_TAB = 9,
// String shorthand.
_CLASS_ITEM = '_CLASS_ITEM',
_CLASS_ITEM_ACTIVE = '_CLASS_ITEM_ACTIVE',
_CLASS_ITEM_HOVER = '_CLASS_ITEM_HOVER',
_SELECTOR_ITEM = '_SELECTOR_ITEM',
ACTIVE_ITEM = 'activeItem',
ALWAYS_SHOW_LIST = 'alwaysShowList',
CIRCULAR = 'circular',
HOVERED_ITEM = 'hoveredItem',
ID = 'id',
ITEM = 'item',
LIST = 'list',
RESULT = 'result',
RESULTS = 'results',
VISIBLE = 'visible',
WIDTH = 'width',
// Event names.
EVT_SELECT = 'select',
List = Y.Base.create('autocompleteList', Y.Widget, [
Y.AutoCompleteBase,
Y.WidgetPosition,
Y.WidgetPositionAlign
], {
// -- Prototype Properties -------------------------------------------------
ARIA_TEMPLATE: '<div/>',
ITEM_TEMPLATE: '<li/>',
LIST_TEMPLATE: '<ul/>',
// Widget automatically attaches delegated event handlers to everything in
// Y.Node.DOM_EVENTS, including synthetic events. Since Widget's event
// delegation won't work for the synthetic valuechange event, and since
// it creates a name collision between the backcompat "valueChange" synth
// event alias and AutoCompleteList's "valueChange" event for the "value"
// attr, this hack is necessary in order to prevent Widget from attaching
// valuechange handlers.
UI_EVENTS: (function () {
var uiEvents = Y.merge(Y.Node.DOM_EVENTS);
delete uiEvents.valuechange;
delete uiEvents.valueChange;
return uiEvents;
}()),
// -- Lifecycle Prototype Methods ------------------------------------------
initializer: function () {
var inputNode = this.get('inputNode');
if (!inputNode) {
Y.error('No inputNode specified.');
return;
}
this._inputNode = inputNode;
this._listEvents = [];
// This ensures that the list is rendered inside the same parent as the
// input node by default, which is necessary for proper ARIA support.
this.DEF_PARENT_NODE = inputNode.get('parentNode');
// Cache commonly used classnames and selectors for performance.
this[_CLASS_ITEM] = this.getClassName(ITEM);
this[_CLASS_ITEM_ACTIVE] = this.getClassName(ITEM, 'active');
this[_CLASS_ITEM_HOVER] = this.getClassName(ITEM, 'hover');
this[_SELECTOR_ITEM] = '.' + this[_CLASS_ITEM];
/**
Fires when an autocomplete suggestion is selected from the list,
typically via a keyboard action or mouse click.
@event select
@param {Node} itemNode List item node that was selected.
@param {Object} result AutoComplete result object.
@preventable _defSelectFn
**/
this.publish(EVT_SELECT, {
defaultFn: this._defSelectFn
});
},
destructor: function () {
while (this._listEvents.length) {
this._listEvents.pop().detach();
}
if (this._ariaNode) {
this._ariaNode.remove().destroy(true);
}
},
bindUI: function () {
this._bindInput();
this._bindList();
},
renderUI: function () {
var ariaNode = this._createAriaNode(),
boundingBox = this.get('boundingBox'),
contentBox = this.get('contentBox'),
inputNode = this._inputNode,
listNode = this._createListNode(),
parentNode = inputNode.get('parentNode');
inputNode.addClass(this.getClassName('input')).setAttrs({
'aria-autocomplete': LIST,
'aria-expanded' : false,
'aria-owns' : listNode.get('id')
});
// ARIA node must be outside the widget or announcements won't be made
// when the widget is hidden.
parentNode.append(ariaNode);
// Add an iframe shim for IE6.
if (useShim) {
boundingBox.plug(Y.Plugin.Shim);
}
// Force position: absolute on the boundingBox. This works around a
// potential CSS loading race condition in Gecko that can cause the
// boundingBox to become relatively positioned, which is all kinds of
// no good.
boundingBox.setStyle('position', 'absolute');
this._ariaNode = ariaNode;
this._boundingBox = boundingBox;
this._contentBox = contentBox;
this._listNode = listNode;
this._parentNode = parentNode;
},
syncUI: function () {
// No need to call _syncPosition() here; the other _sync methods will
// call it when necessary.
this._syncResults();
this._syncVisibility();
},
// -- Public Prototype Methods ---------------------------------------------
/**
Hides the list, unless the `alwaysShowList` attribute is `true`.
@method hide
@see show
@chainable
**/
hide: function () {
return this.get(ALWAYS_SHOW_LIST) ? this : this.set(VISIBLE, false);
},
/**
Selects the specified _itemNode_, or the current `activeItem` if _itemNode_
is not specified.
@method selectItem
@param {Node} [itemNode] Item node to select.
@param {EventFacade} [originEvent] Event that triggered the selection, if
any.
@chainable
**/
selectItem: function (itemNode, originEvent) {
if (itemNode) {
if (!itemNode.hasClass(this[_CLASS_ITEM])) {
return this;
}
} else {
itemNode = this.get(ACTIVE_ITEM);
if (!itemNode) {
return this;
}
}
this.fire(EVT_SELECT, {
itemNode : itemNode,
originEvent: originEvent || null,
result : itemNode.getData(RESULT)
});
return this;
},
// -- Protected Prototype Methods ------------------------------------------
/**
Activates the next item after the currently active item. If there is no next
item and the `circular` attribute is `true`, focus will wrap back to the
input node.
@method _activateNextItem
@chainable
@protected
**/
_activateNextItem: function () {
var item = this.get(ACTIVE_ITEM),
nextItem;
if (item) {
nextItem = item.next(this[_SELECTOR_ITEM]) ||
(this.get(CIRCULAR) ? null : item);
} else {
nextItem = this._getFirstItemNode();
}
this.set(ACTIVE_ITEM, nextItem);
return this;
},
/**
Activates the item previous to the currently active item. If there is no
previous item and the `circular` attribute is `true`, focus will wrap back
to the input node.
@method _activatePrevItem
@chainable
@protected
**/
_activatePrevItem: function () {
var item = this.get(ACTIVE_ITEM),
prevItem = item ? item.previous(this[_SELECTOR_ITEM]) :
this.get(CIRCULAR) && this._getLastItemNode();
this.set(ACTIVE_ITEM, prevItem || null);
return this;
},
/**
Appends the specified result _items_ to the list inside a new item node.
@method _add
@param {Array|Node|HTMLElement|String} items Result item or array of
result items.
@return {NodeList} Added nodes.
@protected
**/
_add: function (items) {
var itemNodes = [];
YArray.each(Lang.isArray(items) ? items : [items], function (item) {
itemNodes.push(this._createItemNode(item).setData(RESULT, item));
}, this);
itemNodes = Y.all(itemNodes);
this._listNode.append(itemNodes.toFrag());
return itemNodes;
},
/**
Updates the ARIA live region with the specified message.
@method _ariaSay
@param {String} stringId String id (from the `strings` attribute) of the
message to speak.
@param {Object} [subs] Substitutions for placeholders in the string.
@protected
**/
_ariaSay: function (stringId, subs) {
var message = this.get('strings.' + stringId);
this._ariaNode.set('text', subs ? Lang.sub(message, subs) : message);
},
/**
Binds `inputNode` events and behavior.
@method _bindInput
@protected
**/
_bindInput: function () {
var inputNode = this._inputNode,
alignNode, alignWidth, tokenInput;
// Null align means we can auto-align. Set align to false to prevent
// auto-alignment, or a valid alignment config to customize the
// alignment.
if (this.get('align') === null) {
// If this is a tokenInput, align with its bounding box.
// Otherwise, align with the inputNode. Bit of a cheat.
tokenInput = this.get('tokenInput');
alignNode = (tokenInput && tokenInput.get('boundingBox')) || inputNode;
this.set('align', {
node : alignNode,
points: ['tl', 'bl']
});
// If no width config is set, attempt to set the list's width to the
// width of the alignment node. If the alignment node's width is
// falsy, do nothing.
if (!this.get(WIDTH) && (alignWidth = alignNode.get('offsetWidth'))) {
this.set(WIDTH, alignWidth);
}
}
// Attach inputNode events.
this._listEvents = this._listEvents.concat([
inputNode.after('blur', this._afterListInputBlur, this),
inputNode.after('focus', this._afterListInputFocus, this)
]);
},
/**
Binds list events.
@method _bindList
@protected
**/
_bindList: function () {
this._listEvents = this._listEvents.concat([
Y.one('doc').after('click', this._afterDocClick, this),
Y.one('win').after('windowresize', this._syncPosition, this),
this.after({
mouseover: this._afterMouseOver,
mouseout : this._afterMouseOut,
activeItemChange : this._afterActiveItemChange,
alwaysShowListChange: this._afterAlwaysShowListChange,
hoveredItemChange : this._afterHoveredItemChange,
resultsChange : this._afterResultsChange,
visibleChange : this._afterVisibleChange
}),
this._listNode.delegate('click', this._onItemClick,
this[_SELECTOR_ITEM], this)
]);
},
/**
Clears the contents of the tray.
@method _clear
@protected
**/
_clear: function () {
this.set(ACTIVE_ITEM, null);
this._set(HOVERED_ITEM, null);
this._listNode.get('children').remove(true);
},
/**
Creates and returns an ARIA live region node.
@method _createAriaNode
@return {Node} ARIA node.
@protected
**/
_createAriaNode: function () {
var ariaNode = Node.create(this.ARIA_TEMPLATE);
return ariaNode.addClass(this.getClassName('aria')).setAttrs({
'aria-live': 'polite',
role : 'status'
});
},
/**
Creates and returns an item node with the specified _content_.
@method _createItemNode
@param {Object} result Result object.
@return {Node} Item node.
@protected
**/
_createItemNode: function (result) {
var itemNode = Node.create(this.ITEM_TEMPLATE);
return itemNode.addClass(this[_CLASS_ITEM]).setAttrs({
id : Y.stamp(itemNode),
role: 'option'
}).setAttribute('data-text', result.text).append(result.display);
},
/**
Creates and returns a list node. If the `listNode` attribute is already set
to an existing node, that node will be used.
@method _createListNode
@return {Node} List node.
@protected
**/
_createListNode: function () {
var listNode = this.get('listNode') || Node.create(this.LIST_TEMPLATE);
listNode.addClass(this.getClassName(LIST)).setAttrs({
id : Y.stamp(listNode),
role: 'listbox'
});
this._set('listNode', listNode);
this.get('contentBox').append(listNode);
return listNode;
},
/**
Gets the first item node in the list, or `null` if the list is empty.
@method _getFirstItemNode
@return {Node|null}
@protected
**/
_getFirstItemNode: function () {
return this._listNode.one(this[_SELECTOR_ITEM]);
},
/**
Gets the last item node in the list, or `null` if the list is empty.
@method _getLastItemNode
@return {Node|null}
@protected
**/
_getLastItemNode: function () {
return this._listNode.one(this[_SELECTOR_ITEM] + ':last-child');
},
/**
Synchronizes the result list's position and alignment.
@method _syncPosition
@protected
**/
_syncPosition: function () {
// Force WidgetPositionAlign to refresh its alignment.
this._syncUIPosAlign();
// Resize the IE6 iframe shim to match the list's dimensions.
this._syncShim();
},
/**
Synchronizes the results displayed in the list with those in the _results_
argument, or with the `results` attribute if an argument is not provided.
@method _syncResults
@param {Array} [results] Results.
@protected
**/
_syncResults: function (results) {
if (!results) {
results = this.get(RESULTS);
}
this._clear();
if (results.length) {
this._add(results);
this._ariaSay('items_available');
}
this._syncPosition();
if (this.get('activateFirstItem') && !this.get(ACTIVE_ITEM)) {
this.set(ACTIVE_ITEM, this._getFirstItemNode());
}
},
/**
Synchronizes the size of the iframe shim used for IE6 and lower. In other
browsers, this method is a noop.
@method _syncShim
@protected
**/
_syncShim: useShim ? function () {
var shim = this._boundingBox.shim;
if (shim) {
shim.sync();
}
} : function () {},
/**
Synchronizes the visibility of the tray with the _visible_ argument, or with
the `visible` attribute if an argument is not provided.
@method _syncVisibility
@param {Boolean} [visible] Visibility.
@protected
**/
_syncVisibility: function (visible) {
if (this.get(ALWAYS_SHOW_LIST)) {
visible = true;
this.set(VISIBLE, visible);
}
if (typeof visible === 'undefined') {
visible = this.get(VISIBLE);
}
this._inputNode.set('aria-expanded', visible);
this._boundingBox.set('aria-hidden', !visible);
if (visible) {
this._syncPosition();
} else {
this.set(ACTIVE_ITEM, null);
this._set(HOVERED_ITEM, null);
// Force a reflow to work around a glitch in IE6 and 7 where some of
// the contents of the list will sometimes remain visible after the
// container is hidden.
this._boundingBox.get('offsetWidth');
}
// In some pages, IE7 fails to repaint the contents of the list after it
// becomes visible. Toggling a bogus class on the body forces a repaint
// that fixes the issue.
if (Y.UA.ie === 7) {
// Note: We don't actually need to use ClassNameManager here. This
// class isn't applying any actual styles; it's just frobbing the
// body element to force a repaint. The actual class name doesn't
// really matter.
Y.one('body')
.addClass('yui3-ie7-sucks')
.removeClass('yui3-ie7-sucks');
}
},
// -- Protected Event Handlers ---------------------------------------------
/**
Handles `activeItemChange` events.
@method _afterActiveItemChange
@param {EventFacade} e
@protected
**/
_afterActiveItemChange: function (e) {
var inputNode = this._inputNode,
newVal = e.newVal,
prevVal = e.prevVal,
node;
// The previous item may have disappeared by the time this handler runs,
// so we need to be careful.
if (prevVal && prevVal._node) {
prevVal.removeClass(this[_CLASS_ITEM_ACTIVE]);
}
if (newVal) {
newVal.addClass(this[_CLASS_ITEM_ACTIVE]);
inputNode.set('aria-activedescendant', newVal.get(ID));
} else {
inputNode.removeAttribute('aria-activedescendant');
}
if (this.get('scrollIntoView')) {
node = newVal || inputNode;
if (!node.inRegion(Y.DOM.viewportRegion(), true)
|| !node.inRegion(this._contentBox, true)) {
node.scrollIntoView();
}
}
},
/**
Handles `alwaysShowListChange` events.
@method _afterAlwaysShowListChange
@param {EventFacade} e
@protected
**/
_afterAlwaysShowListChange: function (e) {
this.set(VISIBLE, e.newVal || this.get(RESULTS).length > 0);
},
/**
Handles click events on the document. If the click is outside both the
input node and the bounding box, the list will be hidden.
@method _afterDocClick
@param {EventFacade} e
@protected
@since 3.5.0
**/
_afterDocClick: function (e) {
var boundingBox = this._boundingBox,
target = e.target;
if(target !== this._inputNode && target !== boundingBox &&
target.ancestor('#' + boundingBox.get('id'), true)){
this.hide();
}
},
/**
Handles `hoveredItemChange` events.
@method _afterHoveredItemChange
@param {EventFacade} e
@protected
**/
_afterHoveredItemChange: function (e) {
var newVal = e.newVal,
prevVal = e.prevVal;
if (prevVal) {
prevVal.removeClass(this[_CLASS_ITEM_HOVER]);
}
if (newVal) {
newVal.addClass(this[_CLASS_ITEM_HOVER]);
}
},
/**
Handles `inputNode` blur events.
@method _afterListInputBlur
@protected
**/
_afterListInputBlur: function () {
this._listInputFocused = false;
if (this.get(VISIBLE) &&
!this._mouseOverList &&
(this._lastInputKey !== KEY_TAB ||
!this.get('tabSelect') ||
!this.get(ACTIVE_ITEM))) {
this.hide();
}
},
/**
Handles `inputNode` focus events.
@method _afterListInputFocus
@protected
**/
_afterListInputFocus: function () {
this._listInputFocused = true;
},
/**
Handles `mouseover` events.
@method _afterMouseOver
@param {EventFacade} e
@protected
**/
_afterMouseOver: function (e) {
var itemNode = e.domEvent.target.ancestor(this[_SELECTOR_ITEM], true);
this._mouseOverList = true;
if (itemNode) {
this._set(HOVERED_ITEM, itemNode);
}
},
/**
Handles `mouseout` events.
@method _afterMouseOut
@param {EventFacade} e
@protected
**/
_afterMouseOut: function () {
this._mouseOverList = false;
this._set(HOVERED_ITEM, null);
},
/**
Handles `resultsChange` events.
@method _afterResultsChange
@param {EventFacade} e
@protected
**/
_afterResultsChange: function (e) {
this._syncResults(e.newVal);
if (!this.get(ALWAYS_SHOW_LIST)) {
this.set(VISIBLE, !!e.newVal.length);
}
},
/**
Handles `visibleChange` events.
@method _afterVisibleChange
@param {EventFacade} e
@protected
**/
_afterVisibleChange: function (e) {
this._syncVisibility(!!e.newVal);
},
/**
Delegated event handler for item `click` events.
@method _onItemClick
@param {EventFacade} e
@protected
**/
_onItemClick: function (e) {
var itemNode = e.currentTarget;
this.set(ACTIVE_ITEM, itemNode);
this.selectItem(itemNode, e);
},
// -- Protected Default Event Handlers -------------------------------------
/**
Default `select` event handler.
@method _defSelectFn
@param {EventFacade} e
@protected
**/
_defSelectFn: function (e) {
var text = e.result.text;
// TODO: support typeahead completion, etc.
this._inputNode.focus();
this._updateValue(text);
this._ariaSay('item_selected', {item: text});
this.hide();
}
}, {
ATTRS: {
/**
If `true`, the first item in the list will be activated by default when
the list is initially displayed and when results change.
@attribute activateFirstItem
@type Boolean
@default false
**/
activateFirstItem: {
value: false
},
/**
Item that's currently active, if any. When the user presses enter, this
is the item that will be selected.
@attribute activeItem
@type Node
**/
activeItem: {
setter: Y.one,
value: null
},
/**
If `true`, the list will remain visible even when there are no results
to display.
@attribute alwaysShowList
@type Boolean
@default false
**/
alwaysShowList: {
value: false
},
/**
If `true`, keyboard navigation will wrap around to the opposite end of
the list when navigating past the first or last item.
@attribute circular
@type Boolean
@default true
**/
circular: {
value: true
},
/**
Item currently being hovered over by the mouse, if any.
@attribute hoveredItem
@type Node|null
@readOnly
**/
hoveredItem: {
readOnly: true,
value: null
},
/**
Node that will contain result items.
@attribute listNode
@type Node|null
@initOnly
**/
listNode: {
writeOnce: 'initOnly',
value: null
},
/**
If `true`, the viewport will be scrolled to ensure that the active list
item is visible when necessary.
@attribute scrollIntoView
@type Boolean
@default false
**/
scrollIntoView: {
value: false
},
/**
Translatable strings used by the AutoCompleteList widget.
@attribute strings
@type Object
**/
strings: {
valueFn: function () {
return Y.Intl.get('autocomplete-list');
}
},
/**
If `true`, pressing the tab key while the list is visible will select
the active item, if any.
@attribute tabSelect
@type Boolean
@default true
**/
tabSelect: {
value: true
},
// The "visible" attribute is documented in Widget.
visible: {
value: false
}
},
CSS_PREFIX: Y.ClassNameManager.getClassName('aclist')
});
Y.AutoCompleteList = List;
/**
Alias for <a href="AutoCompleteList.html">`AutoCompleteList`</a>. See that class
for API docs.
@class AutoComplete
**/
Y.AutoComplete = List;
}, '@VERSION@' ,{lang:['en'], after:['autocomplete-sources'], skinnable:true, requires:['autocomplete-base', 'event-resize', 'node-screen', 'selector-css3', 'shim-plugin', 'widget', 'widget-position', 'widget-position-align']});
| 27.386592 | 228 | 0.569459 |
b9eb54824b496de5116231f7b7488b27369cc6c4 | 1,273 | js | JavaScript | src/platforms/mp-xhs/runtime/wrapper/util.js | Songllgons/uni-app | aeda8f124995a9d754aa4b5e9fb55275f2982d20 | [
"Apache-2.0"
] | null | null | null | src/platforms/mp-xhs/runtime/wrapper/util.js | Songllgons/uni-app | aeda8f124995a9d754aa4b5e9fb55275f2982d20 | [
"Apache-2.0"
] | null | null | null | src/platforms/mp-xhs/runtime/wrapper/util.js | Songllgons/uni-app | aeda8f124995a9d754aa4b5e9fb55275f2982d20 | [
"Apache-2.0"
] | null | null | null | import {
isFn,
hasOwn
} from 'uni-shared'
export const isComponent2 = xhs.canIUse('component2')
export const mocks = ['$id']
export function initSpecialMethods (mpInstance) {
if (!mpInstance.$vm) {
return
}
let path = mpInstance.is || mpInstance.route
if (!path) {
return
}
if (path.indexOf('/') === 0) {
path = path.substr(1)
}
const specialMethods = xhs.specialMethods && xhs.specialMethods[path]
if (specialMethods) {
specialMethods.forEach(method => {
if (isFn(mpInstance.$vm[method])) {
mpInstance[method] = function (event) {
if (hasOwn(event, 'markerId')) {
event.detail = typeof event.detail === 'object' ? event.detail : {}
event.detail.markerId = event.markerId
}
// TODO normalizeEvent
mpInstance.$vm[method](event)
}
}
})
}
}
export const handleWrap = function (mp, destory) {
const vueId = mp.props.vueId
const list = mp.props['data-event-list'].split(',')
list.forEach(eventName => {
const key = `${eventName}${vueId}`
if (destory) {
delete this[key]
} else {
// TODO remove handleRef
this[key] = function () {
mp.props[eventName].apply(this, arguments)
}
}
})
}
| 24.018868 | 79 | 0.588374 |
b9ec36f53897bb4bfd5a449580faffabd24d2388 | 617 | js | JavaScript | src/main/mocks/ExpenseTestService.js | aniskchaou/GYM-FRONTEND-ADMIN | 4ab0c1adcd279c56347a0549edc796263a922628 | [
"MIT"
] | 1 | 2022-02-23T08:42:41.000Z | 2022-02-23T08:42:41.000Z | src/main/mocks/ExpenseTestService.js | aniskchaou/GYM-FRONTEND-ADMIN | 4ab0c1adcd279c56347a0549edc796263a922628 | [
"MIT"
] | null | null | null | src/main/mocks/ExpenseTestService.js | aniskchaou/GYM-FRONTEND-ADMIN | 4ab0c1adcd279c56347a0549edc796263a922628 | [
"MIT"
] | null | null | null | const _expense = [{ "supplier": "maintenance matériel", "amount": "6764" }]
const getAll = () => {
return _expense;
};
const get = id => {
return _expense.find(item => item.id === id);
};
const create = (data) => {
_expense.push(data);
};
const update = (old, data) => {
var foundIndex = _expense.findIndex(item => item === old);
_expense[foundIndex] = data;
};
const remove = id => {
_expense.splice(id, 1);
};
const removeAll = () => {
};
const findByTitle = title => {
};
export default {
getAll,
get,
create,
update,
remove,
removeAll,
findByTitle
}; | 15.04878 | 75 | 0.570502 |
b9ec4e6a6c0ed8fded197cf7415b532e9f1f8f65 | 74 | js | JavaScript | B2G/gecko/js/xpconnect/tests/chrome/utf8_subscript.js | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/gecko/js/xpconnect/tests/chrome/utf8_subscript.js | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/gecko/js/xpconnect/tests/chrome/utf8_subscript.js | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | // -*- coding: utf-8 -*-
var str = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢";
function f() { return 42; }
| 18.5 | 27 | 0.540541 |
b9edfdad7512e39020ffe53d402d7e596537094b | 1,049 | js | JavaScript | public/javascripts/easter-egg.js | camtwo/sprints | 32abe5a53d1210c46484d1e564500186a8ca4c7e | [
"Apache-2.0"
] | null | null | null | public/javascripts/easter-egg.js | camtwo/sprints | 32abe5a53d1210c46484d1e564500186a8ca4c7e | [
"Apache-2.0"
] | 2 | 2020-07-16T10:42:30.000Z | 2021-05-07T19:27:21.000Z | public/javascripts/easter-egg.js | camtwo/sprints | 32abe5a53d1210c46484d1e564500186a8ca4c7e | [
"Apache-2.0"
] | 1 | 2019-05-25T00:16:26.000Z | 2019-05-25T00:16:26.000Z |
let umaVez = false;
const todoCheckados = ()=>{
const todosOsInputs = Array.from(document.getElementsByClassName("itemTarefa"));
const inputsCheckados = todosOsInputs.filter((e)=>{return e.checked});
return todosOsInputs.length == inputsCheckados.length;
}
Array.from(document.getElementsByClassName("itemTarefa")).forEach((e)=>{
e.onclick = (ev) =>{
if (todoCheckados()) {
document.getElementById('atualização').style.display = 'block';
if (!umaVez) {
window.scrollTo({
top: 10000,
behavior: "smooth"
});
}
umaVez = true;
}else{
document.getElementById('atualização').style.display = 'none';
umaVez = false;
}
salvarTarefas();
}
});
function salvarTarefas(){
const todosOsInputs = Array.from(document.getElementsByClassName("itemTarefa"));
const inputsCheckados = todosOsInputs.filter((e)=>{return e.checked});
const dados = inputsCheckados.map(function(inp){
return inp.dataset.numero;
});
return StorageController.salvarTarefas(document.getElementById("numero-sprint").value, dados);
} | 28.351351 | 95 | 0.7102 |
b9ee81600bc9c619cfe3095410f72439c3afd21d | 388 | js | JavaScript | __test__/port.test.js | Siphon880gh/simple-note-taker | 3e2534371e12d2d6f8810903d98d8488a7e0dc30 | [
"MIT"
] | null | null | null | __test__/port.test.js | Siphon880gh/simple-note-taker | 3e2534371e12d2d6f8810903d98d8488a7e0dc30 | [
"MIT"
] | null | null | null | __test__/port.test.js | Siphon880gh/simple-note-taker | 3e2534371e12d2d6f8810903d98d8488a7e0dc30 | [
"MIT"
] | 1 | 2021-12-29T18:00:01.000Z | 2021-12-29T18:00:01.000Z | const PortDetector = require("../lib/Port");
describe("Test port detector", () => {
test("Test port is 3001 when running tests on localhost", () => {
const portDetector = new PortDetector();
// Port Detector returns an object
expect(portDetector).toEqual(expect.any(Object));
// Port is 3001
expect(portDetector.port).toBe(3001);
});
}); | 29.846154 | 69 | 0.615979 |
b9ee8515719353ff59aad7f3b4bed90e16d157bc | 5,098 | js | JavaScript | server/game/baseability.js | Crescens/townsquare | 62b53f46b98038672a1f22ac7f01be3cafb9d36b | [
"MIT"
] | null | null | null | server/game/baseability.js | Crescens/townsquare | 62b53f46b98038672a1f22ac7f01be3cafb9d36b | [
"MIT"
] | null | null | null | server/game/baseability.js | Crescens/townsquare | 62b53f46b98038672a1f22ac7f01be3cafb9d36b | [
"MIT"
] | null | null | null | const _ = require('underscore');
/**
* Base class representing an ability that can be done by the player. This
* includes card actions, reactions, interrupts, playing a card, marshaling a
* card, or ambushing a card.
*
* Most of the methods take a context object. While the structure will vary from
* inheriting classes, it is guaranteed to have at least the `game` object, the
* `player` that is executing the action, and the `source` card object that the
* ability is generated from.
*/
class BaseAbility {
/**
* Creates an ability.
*
* @param {Object} properties - An object with ability related properties.
* @param {Object|Array} properties.cost - optional property that specifies
* the cost for the ability. Can either be a cost object or an array of cost
* objects.
*/
constructor(properties) {
this.cost = this.buildCost(properties.cost);
this.targets = this.buildTargets(properties);
}
buildCost(cost) {
if(!cost) {
return [];
}
if(!_.isArray(cost)) {
return [cost];
}
return cost;
}
buildTargets(properties) {
if(properties.target) {
return {
target: properties.target
};
}
if(properties.targets) {
return properties.targets;
}
return {};
}
/**
* Return whether all costs are capable of being paid for the ability.
*
* @returns {Boolean}
*/
canPayCosts(context) {
return _.all(this.cost, cost => cost.canPay(context));
}
/**
* Resolves all costs for the ability prior to payment. Some cost objects
* have a `resolve` method in order to prompt the user to make a choice,
* such as choosing a card to kneel. Consumers of this method should wait
* until all costs have a `resolved` value of `true` before proceeding.
*
* @returns {Array} An array of cost resolution results.
*/
resolveCosts(context) {
return _.map(this.cost, cost => {
if(cost.resolve) {
return cost.resolve(context);
}
return { resolved: true, value: cost.canPay(context) };
});
}
/**
* Pays all costs for the ability simultaneously.
*/
payCosts(context) {
_.each(this.cost, cost => {
cost.pay(context);
});
}
/**
* Return whether when unpay is implemented for the ability cost and the
* cost can be unpaid.
*
* @returns {boolean}
*/
canUnpayCosts(context) {
return _.all(this.cost, cost => cost.unpay && cost.canUnpay(context));
}
/**
* Unpays each cost associated with the ability.
*/
unpayCosts(context) {
_.each(this.cost, cost => {
cost.unpay(context);
});
}
/**
* Returns whether there are eligible cards available to fulfill targets.
*
* @returns {Boolean}
*/
canResolveTargets(context) {
const ValidTypes = ['character', 'attachment', 'location', 'event'];
return _.all(this.targets, target => {
return context.game.allCards.any(card => {
if(!ValidTypes.includes(card.getType())) {
return false;
}
return target.cardCondition(card, context);
});
});
}
/**
* Prompts the current player to choose each target defined for the ability.
*
* @returns {Array} An array of target resolution objects.
*/
resolveTargets(context) {
return _.map(this.targets, (targetProperties, name) => {
return this.resolveTarget(context, name, targetProperties);
});
}
resolveTarget(context, name, targetProperties) {
let cardCondition = targetProperties.cardCondition;
let otherProperties = _.omit(targetProperties, 'cardCondition');
let result = { resolved: false, name: name, value: null };
let promptProperties = {
source: context.source,
cardCondition: card => cardCondition(card, context),
onSelect: (player, card) => {
result.resolved = true;
result.value = card;
return true;
},
onCancel: () => {
result.resolved = true;
return true;
}
};
context.game.promptForSelect(context.player, _.extend(promptProperties, otherProperties));
return result;
}
/**
* Executes the ability once all costs have been paid. Inheriting classes
* should override this method to implement their behavior; by default it
* does nothing.
*/
executeHandler(context) { // eslint-disable-line no-unused-vars
}
isAction() {
return true;
}
isPlayableEventAbility() {
return false;
}
isCardAbility() {
return true;
}
hasMax() {
return false;
}
}
module.exports = BaseAbility;
| 27.706522 | 98 | 0.572185 |
b9ee9b44ae8d8432872e39406ee34b9441ca7072 | 90 | js | JavaScript | src/config.js | daisybaicai/react-drag | 69422493fd4288f4e074d3b826fb1618d0a66c44 | [
"MIT"
] | 51 | 2020-03-13T08:00:28.000Z | 2022-02-09T06:28:31.000Z | src/config.js | daisybaicai/react-drag | 69422493fd4288f4e074d3b826fb1618d0a66c44 | [
"MIT"
] | 2 | 2020-12-21T08:13:30.000Z | 2021-04-05T12:41:38.000Z | src/config.js | daisybaicai/react-drag | 69422493fd4288f4e074d3b826fb1618d0a66c44 | [
"MIT"
] | 20 | 2020-05-10T01:58:44.000Z | 2022-01-05T17:10:43.000Z | const config = {
projectName: 'react-drag', // 权限的项目名,存在本地缓存里
};
export default config;
| 18 | 46 | 0.7 |
b9ef7ef651b5de951097433b6defb29687462c56 | 231 | js | JavaScript | spec-requirejs/requirejs.spec.js | punkle/jasmine-node | 8da90f2221986e1cfef2c0be0dfd6a41f8b9bba7 | [
"MIT"
] | 3 | 2015-01-06T08:34:42.000Z | 2017-01-24T04:45:00.000Z | node_modules/jasmine-node/spec-requirejs/requirejs.spec.js | xeolabs/gl-matrix | 4cbb9339ee074a7ad7e65fa7b40ca279d5253eef | [
"Zlib"
] | null | null | null | node_modules/jasmine-node/spec-requirejs/requirejs.spec.js | xeolabs/gl-matrix | 4cbb9339ee074a7ad7e65fa7b40ca279d5253eef | [
"Zlib"
] | null | null | null | require(['requirejs.sut'], function(sut){
describe('RequireJs basic tests', function(){
it('should load sut', function(){
expect(sut.name).toBe('Subject To Test');
expect(sut.method(2)).toBe(3);
});
});
});
| 25.666667 | 47 | 0.601732 |
b9ef8265f771c850f00b9b7cacd44d81a3202ac3 | 336 | js | JavaScript | src/js_src/containers/about/test.js | ClinGen/python_react_programming_starter | d3e5eeae681e2419a9bdcff22050f4b69be59f39 | [
"MIT"
] | 1 | 2020-01-03T17:07:05.000Z | 2020-01-03T17:07:05.000Z | src/js_src/containers/about/test.js | ClinGen/python_react_programming_starter | d3e5eeae681e2419a9bdcff22050f4b69be59f39 | [
"MIT"
] | 7 | 2018-03-20T04:31:34.000Z | 2020-02-28T00:11:11.000Z | src/js_src/containers/about/test.js | ClinGen/python_react_programming_starter | d3e5eeae681e2419a9bdcff22050f4b69be59f39 | [
"MIT"
] | 6 | 2018-03-22T04:42:45.000Z | 2020-02-25T05:18:19.000Z | import assert from 'assert';
import React from 'react';
import { renderToString } from 'react-dom/server';
import Component from './index';
describe('About', () => {
it('should be able to render to an HTML string', () => {
let htmlString = renderToString(<Component />);
assert.equal(typeof htmlString, 'string');
});
});
| 25.846154 | 58 | 0.660714 |
b9ef82d29bc037a4f4e6a8324c35466055ce47db | 5,804 | js | JavaScript | packages/ckeditor5-table/tests/commands/splitcellcommand.js | embarkcorp/ckeditor5-1 | 2c7dde14f95855a22837fdaf5bb32d7ac7f468e8 | [
"MIT"
] | 6,052 | 2015-01-09T08:19:35.000Z | 2022-03-31T12:31:27.000Z | packages/ckeditor5-table/tests/commands/splitcellcommand.js | r1s2e3/ckeditor5 | dd660e1cf318c26157aa77da9a17e89e22ef7919 | [
"MIT"
] | 10,555 | 2015-01-09T13:17:12.000Z | 2022-03-31T21:31:00.000Z | packages/ckeditor5-table/tests/commands/splitcellcommand.js | r1s2e3/ckeditor5 | dd660e1cf318c26157aa77da9a17e89e22ef7919 | [
"MIT"
] | 3,702 | 2015-01-09T13:33:31.000Z | 2022-03-31T09:28:54.000Z | /**
* @license Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
import ModelTestEditor from '@ckeditor/ckeditor5-core/tests/_utils/modeltesteditor';
import Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph';
import { getData, setData } from '@ckeditor/ckeditor5-engine/src/dev-utils/model';
import { assertEqualMarkup } from '@ckeditor/ckeditor5-utils/tests/_utils/utils';
import TableEditing from '../../src/tableediting';
import TableSelection from '../../src/tableselection';
import { modelTable } from '../_utils/utils';
import SplitCellCommand from '../../src/commands/splitcellcommand';
describe( 'SplitCellCommand', () => {
let editor, model, command;
beforeEach( () => {
return ModelTestEditor
.create( {
plugins: [ Paragraph, TableEditing, TableSelection ]
} )
.then( newEditor => {
editor = newEditor;
model = editor.model;
command = new SplitCellCommand( editor );
} );
} );
afterEach( () => {
return editor.destroy();
} );
describe( 'direction=vertically', () => {
beforeEach( () => {
command = new SplitCellCommand( editor, { direction: 'vertically' } );
} );
describe( 'isEnabled', () => {
it( 'should be true if in a table cell', () => {
setData( model, modelTable( [
[ '00[]' ]
] ) );
expect( command.isEnabled ).to.be.true;
} );
it( 'should be true if in an entire cell is selected', () => {
setData( model, modelTable( [
[ '00', '01' ]
] ) );
const tableSelection = editor.plugins.get( TableSelection );
const modelRoot = model.document.getRoot();
tableSelection.setCellSelection(
modelRoot.getNodeByPath( [ 0, 0, 0 ] ),
modelRoot.getNodeByPath( [ 0, 0, 0 ] )
);
expect( command.isEnabled ).to.be.true;
} );
it( 'should be false if multiple cells are selected', () => {
setData( model, modelTable( [
[ '00', '01' ]
] ) );
const tableSelection = editor.plugins.get( TableSelection );
const modelRoot = model.document.getRoot();
tableSelection.setCellSelection(
modelRoot.getNodeByPath( [ 0, 0, 0 ] ),
modelRoot.getNodeByPath( [ 0, 0, 1 ] )
);
expect( command.isEnabled ).to.be.false;
} );
it( 'should be false if not in cell', () => {
setData( model, '<paragraph>11[]</paragraph>' );
expect( command.isEnabled ).to.be.false;
} );
} );
describe( 'execute()', () => {
it( 'should split table cell for two table cells', () => {
setData( model, modelTable( [
[ '00', '01', '02' ],
[ '10', '[]11', '12' ],
[ '20', { colspan: 2, contents: '21' } ],
[ { colspan: 2, contents: '30' }, '32' ]
] ) );
command.execute();
assertEqualMarkup( getData( model ), modelTable( [
[ '00', { colspan: 2, contents: '01' }, '02' ],
[ '10', '[]11', '', '12' ],
[ '20', { colspan: 3, contents: '21' } ],
[ { colspan: 3, contents: '30' }, '32' ]
] ) );
} );
it( 'should unsplit table cell if split is equal to colspan', () => {
setData( model, modelTable( [
[ '00', '01', '02' ],
[ '10', '11', '12' ],
[ '20', { colspan: 2, contents: '21[]' } ],
[ { colspan: 2, contents: '30' }, '32' ]
] ) );
command.execute();
assertEqualMarkup( getData( model ), modelTable( [
[ '00', '01', '02' ],
[ '10', '11', '12' ],
[ '20', '21[]', '' ],
[ { colspan: 2, contents: '30' }, '32' ]
] ) );
} );
it( 'should properly unsplit table cell if split is uneven', () => {
setData( model, modelTable( [
[ '00', '01', '02' ],
[ { colspan: 3, contents: '10[]' } ]
] ) );
command.execute();
assertEqualMarkup( getData( model ), modelTable( [
[ '00', '01', '02' ],
[ { colspan: 2, contents: '10[]' }, '' ]
] ) );
} );
it( 'should properly set colspan of inserted cells', () => {
setData( model, modelTable( [
[ '00', '01', '02', '03' ],
[ { colspan: 4, contents: '10[]' } ]
] ) );
command.execute();
assertEqualMarkup( getData( model ), modelTable( [
[ '00', '01', '02', '03' ],
[ { colspan: 2, contents: '10[]' }, { colspan: 2, contents: '' } ]
] ) );
} );
it( 'should keep rowspan attribute for newly inserted cells', () => {
setData( model, modelTable( [
[ '00', '01', '02', '03', '04', '05' ],
[ { colspan: 5, rowspan: 2, contents: '10[]' }, '15' ],
[ '25' ]
] ) );
command.execute();
assertEqualMarkup( getData( model ), modelTable( [
[ '00', '01', '02', '03', '04', '05' ],
[ { colspan: 3, rowspan: 2, contents: '10[]' }, { colspan: 2, rowspan: 2, contents: '' }, '15' ],
[ '25' ]
] ) );
} );
} );
} );
describe( 'direction=horizontally', () => {
beforeEach( () => {
command = new SplitCellCommand( editor, { direction: 'horizontally' } );
} );
describe( 'isEnabled', () => {
it( 'should be true if in a table cell', () => {
setData( model, modelTable( [
[ '00[]' ]
] ) );
expect( command.isEnabled ).to.be.true;
} );
it( 'should be false if not in cell', () => {
setData( model, '<paragraph>11[]</paragraph>' );
expect( command.isEnabled ).to.be.false;
} );
} );
describe( 'execute()', () => {
it( 'should split table cell for two table cells', () => {
setData( model, modelTable( [
[ '00', '01', '02' ],
[ '10', '[]11', '12' ],
[ '20', '21', '22' ]
] ) );
command.execute();
assertEqualMarkup( getData( model ), modelTable( [
[ '00', '01', '02' ],
[ { rowspan: 2, contents: '10' }, '[]11', { rowspan: 2, contents: '12' } ],
[ '' ],
[ '20', '21', '22' ]
] ) );
} );
} );
} );
} );
| 27.507109 | 102 | 0.533081 |
b9efc504c34e9249ef5fe16118507f805eb2a95b | 11 | js | JavaScript | test/fixtures/project/src/index.js | tommcc/gulp-jshint | 32a25b0ab904416b392a947f656e9e65f1d42db0 | [
"MIT"
] | 353 | 2015-02-10T09:02:34.000Z | 2021-04-02T02:44:33.000Z | test/fixtures/project/src/index.js | tommcc/gulp-jshint | 32a25b0ab904416b392a947f656e9e65f1d42db0 | [
"MIT"
] | 68 | 2015-02-09T03:51:50.000Z | 2020-02-06T17:02:08.000Z | test/fixtures/project/src/index.js | tommcc/gulp-jshint | 32a25b0ab904416b392a947f656e9e65f1d42db0 | [
"MIT"
] | 63 | 2015-02-27T19:58:51.000Z | 2020-03-29T08:26:48.000Z | angular();
| 5.5 | 10 | 0.636364 |
b9f0f2e55f2690d3297d066a924a7ddf3fad40a7 | 1,740 | js | JavaScript | src/helpers/util.js | wayou/react-carousel | 4d0ad2f2d727c8823f3ad8c2268c439bd2c302c0 | [
"MIT"
] | null | null | null | src/helpers/util.js | wayou/react-carousel | 4d0ad2f2d727c8823f3ad8c2268c439bd2c302c0 | [
"MIT"
] | null | null | null | src/helpers/util.js | wayou/react-carousel | 4d0ad2f2d727c8823f3ad8c2268c439bd2c302c0 | [
"MIT"
] | null | null | null | export default {
fallbackImg: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAacAAADwCAMAAACTzVtRAAAAM1BMVEXn5+e9vb3i4uK/v7/a2trg4ODFxcXCwsLk5OTU1NTR0dHX19fd3d3Nzc3Hx8fJycnBwcEYtqTYAAAEdElEQVR42uzBgQAAAACAoP2pF6kCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABm396224SBKAzP1gmdMH7/p22x0yJprJqQrqAs5rsrbrj5l2QhCyGEEEKIr1ImLA7akBiUz2F2Gk+axHhsisuEiiIxEGXC7PAgnYbkc5pvGivpNKZimpNOQyqmOek0pGKak05jsubvNCedhlRMc9JpVKE3zek0hZt0GsSMnpkiBek0CI2eQJFm6TQIdCU10ySdBoGuHKKVdcQo0OUXk6TTKNBzo8knwGXpNIJupkyWDGYi6TQCvLQoekhEVjqNoPPotAnSaQQAd6OCmqTTAMDdFZWsdBoAOEO1JJ3OByZSa5ZOp0PLEeMn6XQ2NLQiLkuns6Fh6JUgnU6G2kyv3d53yjFRhV/xJsSYLG3UdmVj2J1MvPoJaVQcdSj9rpNpH7woNd3Nn9hT8B9XHJ5caAbvTKUIINKloWKpJ73r9IiQqTBV/0Et2NwNEVmHzZTrny49FeQoO6EUqG9+08mxbzddlrd3VAJljUqiD+yLz2NFl8b2i3r89JVO6o5G1GgY6dT3ryV5XKiQv9LJ4ek2LxpP7IpW0mlPp0SV7ABTZTveKeEhevrNTPgrPK6kO1aLdOrq7ZInBwATldzhThPKT73Dk871pryVTj3gaz0V3f3lysIe7ZSxSmyVb5pbR+nUw55w84KC9lQIBzvFdmxGNoJnAHDSqaf5drLLP3fPl2OdXHsnywZrxko67RtPESU+oJQ+1Emz4qyTwkpJpw78lXx24CKVzPFOgQp8gSmd/gkMH1Cl+UiniX2GlWVXvHTqwFuBbUt8qlPnM+n0vzvdqZKl0xnwXqLKLJ1OgPcc1Zx0+n7YwVDFSqfvhx0WqoVXne6sBaTT93aCpZpjnbrPSOZAp/YzJZ0Ie0SqWb27Uz7YKdPGSifCHpoaiXXq7eH5z3fS7SLTyPkIwi6JGkvVqb8nPtHnOy3lXnpx4dKwy613Tkw1z7+hGU7zgU4JK8PufGnYx1LDVJ34b7bKYZUPdPK6+q3Xajl52+m0/yUOxb6zZvX4h/4Yhwc6USxOU/igPwbmtWEf3TknpvjZZrjF4UnbQ538xO5093Rt2MlQK7ed1MT/6FAnshqNTBeHnRZi5qYT2SZUooOd2rOy+vKZCHt5YlzTifyMjcv1jGjZjoZi5baxecPmZunysFcgxraditNKLpVX2YA0bGkQAMRXb3fcrv5Kzec6OeJMIsbnFIJRTdFg6N2VHDJVvFnvdPUFxAfsJpPPmbCPvCh2Muw2kTgPZOL7ESAT348Amfh+BMjE96tdezlCGIZiAJgHEzs/JvRfLS1wizXeLUIHSRG64Itwtf6Pr+ALsQu+DMf023eGV1VbGN89/Ukhw1l1Lgxve9e9ML5PlTUowFVlW03Qp7/RZThmf+OHWB3pMjTBF+HQxUZYdbEZmhEqwq6LjbDtXRcLAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE/7Af6vJa5eZ2zjAAAAAElFTkSuQmCC"
} | 580 | 1,721 | 0.970115 |
b9f132b21702c9d3c365a26c6af52c5bebed1ac9 | 2,725 | js | JavaScript | spec/connect-hopping-spec.js | rehanvdm/ssh2-promise | d876a376858c3cbbad7acfa4eb1541632aff2735 | [
"MIT"
] | 135 | 2017-12-05T11:54:19.000Z | 2022-03-10T06:38:15.000Z | spec/connect-hopping-spec.js | rehanvdm/ssh2-promise | d876a376858c3cbbad7acfa4eb1541632aff2735 | [
"MIT"
] | 58 | 2017-12-26T09:13:09.000Z | 2022-03-28T16:26:40.000Z | spec/connect-hopping-spec.js | rehanvdm/ssh2-promise | d876a376858c3cbbad7acfa4eb1541632aff2735 | [
"MIT"
] | 25 | 2018-07-05T09:24:13.000Z | 2021-11-09T17:43:05.000Z | var SSHTunnel = require("../lib/index");
var SSHConstants = require("../lib/index").Constants;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 100000;
Promise.prototype.finally = function (cb) {
const res = () => this;
const fin = () => Promise.resolve(cb()).then(res);
return this.then(fin, fin);
};
var fs = require("fs");
var sshConfigs = require('./fixture')//JSON.parse(fs.readFileSync("./spec/fixture.json"));
var util = require('util');
describe("connect to dummy server via hopping", function () {
it("should connect to server with hopping with default nc", function (done) {
var sshTunnel = new SSHTunnel(sshConfigs.multiple);
return sshTunnel.connect().then((ssh) => {
expect(ssh).toBeDefined();
}, (error) => {
expect('1').toBe('2');
expect(error).toBeUndefined();
}).finally(() => {
sshTunnel.close();
console.log("closed one")
done();
});
});
it("should connect to server with hopping with nc", function (done) {
let m = sshConfigs.multiple.slice()
m[0] = Object.assign({hoppingTool:SSHConstants.HOPPINGTOOL.NETCAT}, m[0])
var sshTunnel = new SSHTunnel(m, true);
return sshTunnel.connect().then((ssh) => {
expect(ssh).toBeDefined();
}, (error) => {
expect('1').toBe('2');
expect(error).toBeUndefined();
}).finally(() => {
sshTunnel.close();
console.log("closed one")
done();
});
});
it("should connect to server with hopping with socat", function (done) {
let m = sshConfigs.multiple.slice()
m[0] = Object.assign({hoppingTool:SSHConstants.HOPPINGTOOL.SOCAT}, m[0])
var sshTunnel = new SSHTunnel(m, true);
return sshTunnel.connect().then((ssh) => {
expect(ssh).toBeDefined();
}, (error) => {
expect('1').toBe('2');
expect(error).toBeUndefined();
}).finally(() => {
sshTunnel.close();
console.log("closed one")
done();
});
});
it("should connect to server with hopping with native", function (done) {
let m = sshConfigs.multiple.slice()
m[0] = Object.assign({hoppingTool:SSHConstants.HOPPINGTOOL.NATIVE}, m[0])
var sshTunnel = new SSHTunnel(m, true);
return sshTunnel.connect().then((ssh) => {
expect(ssh).toBeDefined();
}, (error) => {
expect('1').toBe('2');
expect(error).toBeUndefined();
}).finally(() => {
sshTunnel.close();
console.log("closed one")
done();
});
});
}); | 35.38961 | 90 | 0.542018 |
b9f14f0fb3d9a7cea3e838605302abbe7d690798 | 619 | js | JavaScript | 6.3.0/blocks/Meroitic-Hieroglyphs-symbols.js | mathiasbynens/unicode-data | 68cadd44a5b5078075ff54b6d07f2355bea4c933 | [
"MIT"
] | 25 | 2015-01-19T19:29:26.000Z | 2021-01-28T09:18:19.000Z | 6.3.0/blocks/Meroitic-Hieroglyphs-symbols.js | mathiasbynens/unicode-data | 68cadd44a5b5078075ff54b6d07f2355bea4c933 | [
"MIT"
] | 3 | 2015-08-21T14:50:31.000Z | 2017-12-08T21:33:29.000Z | 6.3.0/blocks/Meroitic-Hieroglyphs-symbols.js | mathiasbynens/unicode-data | 68cadd44a5b5078075ff54b6d07f2355bea4c933 | [
"MIT"
] | 3 | 2017-12-07T21:45:19.000Z | 2021-05-06T20:53:51.000Z | // All symbols in the Meroitic Hieroglyphs block as per Unicode v6.3.0:
[
'\uD802\uDD80',
'\uD802\uDD81',
'\uD802\uDD82',
'\uD802\uDD83',
'\uD802\uDD84',
'\uD802\uDD85',
'\uD802\uDD86',
'\uD802\uDD87',
'\uD802\uDD88',
'\uD802\uDD89',
'\uD802\uDD8A',
'\uD802\uDD8B',
'\uD802\uDD8C',
'\uD802\uDD8D',
'\uD802\uDD8E',
'\uD802\uDD8F',
'\uD802\uDD90',
'\uD802\uDD91',
'\uD802\uDD92',
'\uD802\uDD93',
'\uD802\uDD94',
'\uD802\uDD95',
'\uD802\uDD96',
'\uD802\uDD97',
'\uD802\uDD98',
'\uD802\uDD99',
'\uD802\uDD9A',
'\uD802\uDD9B',
'\uD802\uDD9C',
'\uD802\uDD9D',
'\uD802\uDD9E',
'\uD802\uDD9F'
]; | 17.685714 | 71 | 0.605816 |
b9f1b618c8f7824845b67f8a3441de7198cdd9bc | 2,198 | js | JavaScript | test/cameras/OrthographicCamera.spec.js | itanka9/2gl | a0aaa7a7775f6020febe5f6793a887ca48af38d8 | [
"BSD-2-Clause"
] | 21 | 2015-12-07T05:26:05.000Z | 2020-10-14T07:54:33.000Z | test/cameras/OrthographicCamera.spec.js | itanka9/2gl | a0aaa7a7775f6020febe5f6793a887ca48af38d8 | [
"BSD-2-Clause"
] | 92 | 2015-08-04T05:20:38.000Z | 2021-06-15T05:13:07.000Z | test/cameras/OrthographicCamera.spec.js | itanka9/2gl | a0aaa7a7775f6020febe5f6793a887ca48af38d8 | [
"BSD-2-Clause"
] | 8 | 2016-06-24T13:07:00.000Z | 2022-01-27T11:28:44.000Z | import assert from 'assert';
import {slice, round} from '../utils';
import Camera from '../../src/cameras/Camera';
import {ORTHOGRAPHIC_CAMERA} from '../../src/libConstants';
import OrthographicCamera from '../../src/cameras/OrthographicCamera';
describe('OrthographicCamera', () => {
let camera, left, right, top, bottom, near, far;
beforeEach(() => {
left = -10;
right = 10;
top = 10;
bottom = -10;
near = 0.1;
far = 1000;
camera = new OrthographicCamera(left, right, top, bottom, near, far);
});
describe('#constructor', () => {
it('should inherited from Camera', () => {
assert.ok(camera instanceof Camera);
});
it('should have same fields', () => {
assert.equal(left, camera.left);
assert.equal(right, camera.right);
assert.equal(top, camera.top);
assert.equal(bottom, camera.bottom);
assert.equal(near, camera.near);
assert.equal(far, camera.far);
});
it('should have right type', () => {
assert.equal(ORTHOGRAPHIC_CAMERA, camera.type);
});
});
describe('#updateProjectionMatrix', () => {
it('should update projection matrix', () => {
const oldMatrix = slice(camera.projectionMatrix);
camera.updateProjectionMatrix();
assert.notDeepEqual(slice(camera.projectionMatrix), oldMatrix);
});
});
describe('#project', () => {
it('should return right', () => {
camera.position[2] = 10;
camera.updateLocalMatrix();
camera.updateWorldMatrix();
camera.updateProjectionMatrix();
assert.deepEqual(slice(camera.project([1, 0.5, 0])), [1, 0.5, -10]);
});
});
describe('#unproject', () => {
it('should return right', () => {
camera.position[2] = 10;
camera.updateLocalMatrix();
camera.updateWorldMatrix();
camera.updateProjectionMatrix();
assert.deepEqual(slice(camera.unproject([10, 25, 0])).map(c => round(c, 3)), [100, 250, -490.05]);
});
});
});
| 31.855072 | 110 | 0.541401 |
b9f2524382c3ed0e7330460957ed359b8ede7044 | 551 | js | JavaScript | mobileapp/src/components/Game.js | yyypasserby/millershollow | 1f8d010185af83216e02de07ab035e9150589d98 | [
"MIT"
] | null | null | null | mobileapp/src/components/Game.js | yyypasserby/millershollow | 1f8d010185af83216e02de07ab035e9150589d98 | [
"MIT"
] | null | null | null | mobileapp/src/components/Game.js | yyypasserby/millershollow | 1f8d010185af83216e02de07ab035e9150589d98 | [
"MIT"
] | null | null | null | import React from 'react';
import {
TouchableOpacity,
Text,
} from 'react-native';
import {
createFragmentContainer,
graphql,
} from 'react-relay';
class Game extends React.Component {
render() {
const {
createdAt,
isPublic,
name,
} = this.props.game;
return (
<TouchableOpacity>
<Text>
{name}
</Text>
</TouchableOpacity>
);
}
}
export default createFragmentContainer(Game, graphql`
fragment Game_game on Game {
createdAt
id
isPublic
name
}
`);
| 15.305556 | 53 | 0.597096 |
b9f26055d3366af05e3bbbdf049baa01123316fc | 308 | js | JavaScript | public/js/loginValidate.js | cryonthewind/PushProject | 3cbbfea6c990c2576d6d3b4c32109011590f55af | [
"MIT"
] | null | null | null | public/js/loginValidate.js | cryonthewind/PushProject | 3cbbfea6c990c2576d6d3b4c32109011590f55af | [
"MIT"
] | null | null | null | public/js/loginValidate.js | cryonthewind/PushProject | 3cbbfea6c990c2576d6d3b4c32109011590f55af | [
"MIT"
] | null | null | null | $(document).ready(function(){
$('#loginButton').on("click",function() {
email = $('#inputEmail');
password = $('#inputPassword');
if((email.val() == '') || (password.val() == '')){
alert('email or pass word is empty.');
return false;
}
});
}); | 28 | 58 | 0.461039 |
b9f26e056c8ae6d6398c7ab38162ade3dfbc20a9 | 38 | js | JavaScript | src/events/guildUnavailable.js | Skario37/victini2.0 | 815a4f29bfceb7daa36c89ecf37c122482b96a03 | [
"MIT"
] | null | null | null | src/events/guildUnavailable.js | Skario37/victini2.0 | 815a4f29bfceb7daa36c89ecf37c122482b96a03 | [
"MIT"
] | null | null | null | src/events/guildUnavailable.js | Skario37/victini2.0 | 815a4f29bfceb7daa36c89ecf37c122482b96a03 | [
"MIT"
] | null | null | null | module.exports = (client, guild) => {} | 38 | 38 | 0.631579 |
b9f2d60e8bd3905998323ec4fbbeea7dca04cfe5 | 460 | js | JavaScript | examples/parse.js | GluuFederation/node-xtraverse | f1497025b67d7c46cd32af967714871a697899e1 | [
"MIT"
] | 2 | 2016-07-27T17:42:24.000Z | 2018-03-17T14:37:59.000Z | examples/parse.js | GluuFederation/node-xtraverse | f1497025b67d7c46cd32af967714871a697899e1 | [
"MIT"
] | 1 | 2021-04-08T15:29:00.000Z | 2022-03-14T08:05:13.000Z | examples/parse.js | GluuFederation/node-xtraverse | f1497025b67d7c46cd32af967714871a697899e1 | [
"MIT"
] | 6 | 2021-03-17T09:43:57.000Z | 2021-11-11T16:07:22.000Z | var fs = require('fs')
, XT = require('..');
var xml = fs.readFileSync(__dirname + '/feed.xml', 'utf8');
var feed = XT(xml);
console.log(feed.children('title').text());
for (var link = feed.children().first('link'); link.length > 0; link = link.next('link')) {
console.log(link.attr('href'));
}
for (var entry = feed.children().first('entry'); entry.length > 0; entry = entry.next('entry')) {
console.log('Entry: ' + entry.children('title').text());
}
| 32.857143 | 97 | 0.623913 |
b9f3b1481b3a38021c6e083d84b2470e988b04c6 | 815 | js | JavaScript | src/utils/__tests__/create-graph.spec.js | karanisverma/graph.gl | e917607b3c7d5eb929319f220500b3d09c28139a | [
"MIT"
] | 43 | 2019-09-04T03:30:29.000Z | 2021-09-25T07:18:31.000Z | src/utils/__tests__/create-graph.spec.js | karanisverma/graph.gl | e917607b3c7d5eb929319f220500b3d09c28139a | [
"MIT"
] | 1 | 2020-07-16T20:54:17.000Z | 2020-07-16T20:54:17.000Z | src/utils/__tests__/create-graph.spec.js | karanisverma/graph.gl | e917607b3c7d5eb929319f220500b3d09c28139a | [
"MIT"
] | 14 | 2019-11-26T17:34:12.000Z | 2021-09-24T17:25:55.000Z | import SAMPLE_GRAPH from './__fixtures__/graph';
import createGraph from '../create-graph';
describe('util/create-graph', () => {
it('test createGraph with custom parsers', () => {
const graph = createGraph({
nodes: SAMPLE_GRAPH.nodes,
edges: SAMPLE_GRAPH.edges,
nodeParser: node => ({id: node.name}),
edgeParser: edge => ({
id: edge.name,
directed: false,
sourceId: edge.source,
targetId: edge.target,
}),
});
const nodeIds = graph.getNodes().map(n => n.getId());
expect(SAMPLE_GRAPH.nodes.map(n => n.name)).toEqual(
expect.arrayContaining(nodeIds)
);
const edgeIds = graph.getEdges().map(e => e.getId());
expect(SAMPLE_GRAPH.edges.map(n => n.name)).toEqual(
expect.arrayContaining(edgeIds)
);
});
});
| 29.107143 | 57 | 0.606135 |
b9f4bebdbea5f9ad4dc5191cf295ff0a7fa2e989 | 2,079 | js | JavaScript | src/react-ultimate-pagination.js | villebro/react-ultimate-pagination | 057b4b52a283031431252923f45d8adf8af1d587 | [
"MIT"
] | 82 | 2016-04-25T18:06:21.000Z | 2022-01-03T09:51:56.000Z | src/react-ultimate-pagination.js | villebro/react-ultimate-pagination | 057b4b52a283031431252923f45d8adf8af1d587 | [
"MIT"
] | 23 | 2016-11-24T06:12:38.000Z | 2022-01-11T17:49:33.000Z | src/react-ultimate-pagination.js | villebro/react-ultimate-pagination | 057b4b52a283031431252923f45d8adf8af1d587 | [
"MIT"
] | 22 | 2016-05-02T07:20:16.000Z | 2022-01-26T05:10:41.000Z | import React from 'react';
import PropTypes from 'prop-types'
import {getPaginationModel, ITEM_TYPES} from 'ultimate-pagination';
const renderItemComponentFunctionFactory = (itemTypeToComponent, currentPage, onChange) => {
const onItemClickFunctionFactory = ({ value, isDisabled }) => {
return () => {
if (!isDisabled && onChange && currentPage !== value) {
onChange(value);
}
}
};
return (props) => {
const ItemComponent = itemTypeToComponent[props.type];
const onItemClick = onItemClickFunctionFactory(props);
return <ItemComponent onClick={onItemClick} {...props}/>;
}
};
export const createUltimatePagination = ({itemTypeToComponent, WrapperComponent = 'div'}) => {
const UltimatePaginationComponent = (props) => {
const {
currentPage,
totalPages,
boundaryPagesRange,
siblingPagesRange,
hideEllipsis,
hidePreviousAndNextPageLinks,
hideFirstAndLastPageLinks,
onChange,
disabled,
...restProps
} = props;
const paginationModel = getPaginationModel({
currentPage,
totalPages,
boundaryPagesRange,
siblingPagesRange,
hideEllipsis,
hidePreviousAndNextPageLinks,
hideFirstAndLastPageLinks
});
const renderItemComponent = renderItemComponentFunctionFactory(itemTypeToComponent, currentPage, onChange);
return (
<WrapperComponent {...restProps}>
{paginationModel.map((itemModel) => renderItemComponent({
...itemModel,
isDisabled: !!disabled,
}))}
</WrapperComponent>
);
};
UltimatePaginationComponent.propTypes = {
currentPage: PropTypes.number.isRequired,
totalPages: PropTypes.number.isRequired,
boundaryPagesRange: PropTypes.number,
siblingPagesRange: PropTypes.number,
hideEllipsis: PropTypes.bool,
hidePreviousAndNextPageLinks: PropTypes.bool,
hideFirstAndLastPageLinks: PropTypes.bool,
onChange: PropTypes.func,
disabled: PropTypes.bool
};
return UltimatePaginationComponent;
};
export {ITEM_TYPES};
| 28.875 | 111 | 0.690717 |
b9f516946fda8e2a84a46db6793e1f0143e81a0e | 1,167 | js | JavaScript | src/Foundation/Theming/code/bower_components/jquery-validation/src/localization/messages_sl.js | jameshirka/Habitat | ea0a593ea022e59facfe291eace54c8fd22c7b47 | [
"Apache-2.0"
] | 470 | 2015-09-22T12:01:42.000Z | 2022-03-18T21:17:49.000Z | src/Foundation/Theming/code/bower_components/jquery-validation/src/localization/messages_sl.js | jameshirka/Habitat | ea0a593ea022e59facfe291eace54c8fd22c7b47 | [
"Apache-2.0"
] | 278 | 2015-09-22T10:39:55.000Z | 2019-12-06T14:36:49.000Z | src/Foundation/Theming/code/bower_components/jquery-validation/src/localization/messages_sl.js | jameshirka/Habitat | ea0a593ea022e59facfe291eace54c8fd22c7b47 | [
"Apache-2.0"
] | 563 | 2015-10-25T17:35:00.000Z | 2022-02-16T14:13:50.000Z | /*
* Translated default messages for the jQuery validation plugin.
* Language: SL (Slovenian; slovenski jezik)
*/
$.extend( $.validator.messages, {
required: "To polje je obvezno.",
remote: "Prosimo popravite to polje.",
email: "Prosimo vnesite veljaven email naslov.",
url: "Prosimo vnesite veljaven URL naslov.",
date: "Prosimo vnesite veljaven datum.",
dateISO: "Prosimo vnesite veljaven ISO datum.",
number: "Prosimo vnesite veljavno število.",
digits: "Prosimo vnesite samo števila.",
creditcard: "Prosimo vnesite veljavno številko kreditne kartice.",
equalTo: "Prosimo ponovno vnesite vrednost.",
extension: "Prosimo vnesite vrednost z veljavno končnico.",
maxlength: $.validator.format( "Prosimo vnesite največ {0} znakov." ),
minlength: $.validator.format( "Prosimo vnesite najmanj {0} znakov." ),
rangelength: $.validator.format( "Prosimo vnesite najmanj {0} in največ {1} znakov." ),
range: $.validator.format( "Prosimo vnesite vrednost med {0} in {1}." ),
max: $.validator.format( "Prosimo vnesite vrednost manjše ali enako {0}." ),
min: $.validator.format( "Prosimo vnesite vrednost večje ali enako {0}." )
} );
| 48.625 | 89 | 0.712082 |
b9f518f13cc2e0cc5021c8a4f2fe3a2f5844c0c6 | 1,360 | js | JavaScript | src/store/index.js | FanXiaodong-fx/iot | 58b7176a30c55b8dba0d4829d09ab599c625dbbc | [
"MIT"
] | 3 | 2021-01-10T14:24:15.000Z | 2022-02-13T05:43:42.000Z | src/store/index.js | FanXiaodong-fx/iot | 58b7176a30c55b8dba0d4829d09ab599c625dbbc | [
"MIT"
] | 2 | 2021-10-06T19:51:00.000Z | 2022-02-27T07:56:29.000Z | src/store/index.js | FanXiaodong-fx/iot | 58b7176a30c55b8dba0d4829d09ab599c625dbbc | [
"MIT"
] | null | null | null | import Vue from 'vue'
import Vuex from 'vuex'
import modal from './modules/modals';
Vue.use(Vuex)
export default new Vuex.Store({
state: {
//当前活跃的行政区划列表
CurrentRegions: [],
//当前活跃的圆盘菜单项(数据图表:CHART, 场所搜索:PLACE_SEARCH)
CurrentDiskMenu: 'CHART',
//当前活跃的圆盘子菜单项(单位:CUSTOMER, 行业:INDUSTRY, 设备:EQUIPMENT)
CurrentDiskSubMenu: 'CUSTOMER',
//底部面板是否可见
FooterBoxVisible: true,
//html字体大小
HtmlFontSize: 100,
//当前地图覆盖物显示类型(街道/镇:STREET, 场所:PLACE)
CurrentOverlayType: 'PLACE'
},
mutations: {
set_CurrentRegions(state, val) {
state.CurrentRegions = val;
},
set_CurrentDiskMenu(state, val) {
state.CurrentDiskMenu = val;
//如果没有记忆中的子菜单,则默认选中一项(因为父菜单没有对应的单独展示的内容)
if (val === 'CHART' && !state.CurrentDiskSubMenu) {
state.CurrentDiskSubMenu = "CUSTOMER";
}
//如果底部面板是隐藏状态,则开启它
if (state.FooterBoxVisible === false) {
state.FooterBoxVisible = true;
}
},
set_CurrentDiskSubMenu(state, val) {
state.CurrentDiskSubMenu = val;
},
set_HtmlFontSize(state, val) {
state.HtmlFontSize = val;
},
set_FooterBoxVisible(state, val) {
state.FooterBoxVisible = val;
},
set_CurrentOverlayType(state, val) {
state.CurrentOverlayType = val;
}
},
actions: {
},
modules: {
modal
}
})
| 19.710145 | 57 | 0.626471 |
b9f528d59e5f9f2ebf855b0e5b06eea5eefa7f95 | 1,478 | js | JavaScript | src/components/Base/FooterComponents/ContactInfo.js | vikrantrath/gatsbyDemoSEO | f8c9007eb6054934b14f08adf2770276b2b60533 | [
"MIT"
] | null | null | null | src/components/Base/FooterComponents/ContactInfo.js | vikrantrath/gatsbyDemoSEO | f8c9007eb6054934b14f08adf2770276b2b60533 | [
"MIT"
] | null | null | null | src/components/Base/FooterComponents/ContactInfo.js | vikrantrath/gatsbyDemoSEO | f8c9007eb6054934b14f08adf2770276b2b60533 | [
"MIT"
] | null | null | null | import React from 'react';
export default function ContactInfo() {
return (
<div class="row">
<div className="col-xs-12 col-sm-12 col-md-12 p-md-0 p-4">
<h6 class="font-weight-bold text-white mt-2 mb-2"><ins>Registered Office</ins></h6>
<div class="font-weight-lighter text-white">
RDB Boulevard, 8th Floor, Plot K 1, Sector 5, Block EP and GP, Kolkata 700091, India.
</div>
<h6 class="font-weight-bold text-white mt-2 mb-2"><ins>Contact Us</ins></h6>
<div class="row align-items-center font-weight-lighter text-white col-md-12 pl-0 ml-0">
<i class="fa fa-phone" aria-hidden="true"></i>
<div class="font-weight-lighter text-white ml-1">+91-33-4600-9199</div>
</div>
<div class="row align-items-center font-weight-lighter text-white col-md-12 pl-0 ml-0">
<i class="fa fa-phone" aria-hidden="true"></i>
<div class="font-weight-lighter text-white ml-1">+1-414-240-5010</div>
</div>
<div class="row align-items-center font-weight-lighter text-white col-md-12 pl-0 ml-0">
<i class="fa fa-envelope" aria-hidden="true"></i>
<div class="font-weight-lighter text-white ml-1">sales@sheeranalyticsandinsights.com</div>
</div>
</div>
</div>
);
} | 54.740741 | 110 | 0.543302 |
b9f53c98d6a128550953d9f64459f0a933534e19 | 222 | js | JavaScript | scripts/dao-tu-CUA.js | tranminhhuydn/macros | 781c12c4a26111ddcb899b12a62d1ea33a767f86 | [
"MIT"
] | null | null | null | scripts/dao-tu-CUA.js | tranminhhuydn/macros | 781c12c4a26111ddcb899b12a62d1ea33a767f86 | [
"MIT"
] | null | null | null | scripts/dao-tu-CUA.js | tranminhhuydn/macros | 781c12c4a26111ddcb899b12a62d1ea33a767f86 | [
"MIT"
] | null | null | null | console.clear();
var editor = atom.workspace.getActiveTextEditor()
var text = editor.getSelectedText()
text = text.split("của")
if(text.length>1)
editor.insertText(text[1].trim()+" của "+text[0].trim())
//a của b
| 27.75 | 59 | 0.684685 |
b9f5a398fa10462f97360f654a2acd90eeb40646 | 279 | js | JavaScript | public/js/judge-cookie.js | hongxuepeng/ulzz | 360bbfe6b31d6f28a15087cceab4495de32e9c77 | [
"MIT"
] | null | null | null | public/js/judge-cookie.js | hongxuepeng/ulzz | 360bbfe6b31d6f28a15087cceab4495de32e9c77 | [
"MIT"
] | null | null | null | public/js/judge-cookie.js | hongxuepeng/ulzz | 360bbfe6b31d6f28a15087cceab4495de32e9c77 | [
"MIT"
] | null | null | null | function language() {
$("#language-switch>li").click(function () {
var lan = $.session.get('lan');
var type = $(this).attr("type");
if(lan != type){
$.session.set('lan',type);
location.reload();
}
})
}
language();
| 23.25 | 48 | 0.469534 |
b9f5d51b1c3711490c78953c38a4be2e9b107516 | 650 | js | JavaScript | packages/react-hooks/build/useBalancesAll.js | arjunchamyal/apps | f638587627afb07299a5c8738fdd29d1ca8bebf5 | [
"Apache-2.0"
] | null | null | null | packages/react-hooks/build/useBalancesAll.js | arjunchamyal/apps | f638587627afb07299a5c8738fdd29d1ca8bebf5 | [
"Apache-2.0"
] | null | null | null | packages/react-hooks/build/useBalancesAll.js | arjunchamyal/apps | f638587627afb07299a5c8738fdd29d1ca8bebf5 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017-2021 @axia-js/react-hooks authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { useApi } from "./useApi.js";
import { useCall } from "./useCall.js";
/**
* Gets the account full balance information
*
* @param accountAddress The account address of which balance is to be returned
* @returns full information about account's balances
*/
export function useBalancesAll(accountAddress) {
var _api$derive$balances;
const {
api
} = useApi();
return useCall((_api$derive$balances = api.derive.balances) === null || _api$derive$balances === void 0 ? void 0 : _api$derive$balances.all, [accountAddress]);
} | 34.210526 | 161 | 0.716923 |
b9f6f8746b96a7022bc7ebe28b852659743f713a | 13,621 | js | JavaScript | node_modules/material-ui/lib/table/table-body.js | aykutyaman/meteor1.3-react-flowrouter-demo | 73a45dfd4f73ad34ab8bbc6bf18988c513c817a1 | [
"MIT"
] | null | null | null | node_modules/material-ui/lib/table/table-body.js | aykutyaman/meteor1.3-react-flowrouter-demo | 73a45dfd4f73ad34ab8bbc6bf18988c513c817a1 | [
"MIT"
] | null | null | null | node_modules/material-ui/lib/table/table-body.js | aykutyaman/meteor1.3-react-flowrouter-demo | 73a45dfd4f73ad34ab8bbc6bf18988c513c817a1 | [
"MIT"
] | null | null | null | 'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _checkbox = require('../checkbox');
var _checkbox2 = _interopRequireDefault(_checkbox);
var _tableRowColumn = require('./table-row-column');
var _tableRowColumn2 = _interopRequireDefault(_tableRowColumn);
var _clickAwayable = require('../mixins/click-awayable');
var _clickAwayable2 = _interopRequireDefault(_clickAwayable);
var _stylePropable = require('../mixins/style-propable');
var _stylePropable2 = _interopRequireDefault(_stylePropable);
var _lightRawTheme = require('../styles/raw-themes/light-raw-theme');
var _lightRawTheme2 = _interopRequireDefault(_lightRawTheme);
var _themeManager = require('../styles/theme-manager');
var _themeManager2 = _interopRequireDefault(_themeManager);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var TableBody = _react2.default.createClass({
displayName: 'TableBody',
propTypes: {
allRowsSelected: _react2.default.PropTypes.bool,
children: _react2.default.PropTypes.node,
/**
* The css class name of the root element.
*/
className: _react2.default.PropTypes.string,
deselectOnClickaway: _react2.default.PropTypes.bool,
displayRowCheckbox: _react2.default.PropTypes.bool,
multiSelectable: _react2.default.PropTypes.bool,
onCellClick: _react2.default.PropTypes.func,
onCellHover: _react2.default.PropTypes.func,
onCellHoverExit: _react2.default.PropTypes.func,
onRowHover: _react2.default.PropTypes.func,
onRowHoverExit: _react2.default.PropTypes.func,
onRowSelection: _react2.default.PropTypes.func,
preScanRows: _react2.default.PropTypes.bool,
selectable: _react2.default.PropTypes.bool,
showRowHover: _react2.default.PropTypes.bool,
stripedRows: _react2.default.PropTypes.bool,
/**
* Override the inline-styles of the root element.
*/
style: _react2.default.PropTypes.object
},
contextTypes: {
muiTheme: _react2.default.PropTypes.object
},
//for passing default theme context to children
childContextTypes: {
muiTheme: _react2.default.PropTypes.object
},
mixins: [_clickAwayable2.default, _stylePropable2.default],
getDefaultProps: function getDefaultProps() {
return {
allRowsSelected: false,
deselectOnClickaway: true,
displayRowCheckbox: true,
multiSelectable: false,
preScanRows: true,
selectable: true,
style: {}
};
},
getInitialState: function getInitialState() {
return {
muiTheme: this.context.muiTheme ? this.context.muiTheme : _themeManager2.default.getMuiTheme(_lightRawTheme2.default),
selectedRows: this._calculatePreselectedRows(this.props)
};
},
getChildContext: function getChildContext() {
return {
muiTheme: this.state.muiTheme
};
},
//to update theme inside state whenever a new theme is passed down
//from the parent / owner using context
componentWillReceiveProps: function componentWillReceiveProps(nextProps, nextContext) {
var newMuiTheme = nextContext.muiTheme ? nextContext.muiTheme : this.state.muiTheme;
this.setState({ muiTheme: newMuiTheme });
var newState = {};
if (this.props.allRowsSelected && !nextProps.allRowsSelected) {
newState.selectedRows = this.state.selectedRows.length > 0 ? [this.state.selectedRows[this.state.selectedRows.length - 1]] : [];
} else {
newState.selectedRows = this._calculatePreselectedRows(nextProps);
}
this.setState(newState);
},
componentClickAway: function componentClickAway() {
if (this.props.deselectOnClickaway && this.state.selectedRows.length) {
this.setState({ selectedRows: [] });
if (this.props.onRowSelection) this.props.onRowSelection([]);
}
},
_createRows: function _createRows() {
var _this = this;
var numChildren = _react2.default.Children.count(this.props.children);
var rowNumber = 0;
var handlers = {
onCellClick: this._onCellClick,
onCellHover: this._onCellHover,
onCellHoverExit: this._onCellHoverExit,
onRowHover: this._onRowHover,
onRowHoverExit: this._onRowHoverExit,
onRowClick: this._onRowClick
};
return _react2.default.Children.map(this.props.children, function (child) {
if (_react2.default.isValidElement(child)) {
var _ret = function () {
var props = {
displayRowCheckbox: _this.props.displayRowCheckbox,
hoverable: _this.props.showRowHover,
selected: _this._isRowSelected(rowNumber),
striped: _this.props.stripedRows && rowNumber % 2 === 0,
rowNumber: rowNumber++
};
var checkboxColumn = _this._createRowCheckboxColumn(props);
if (rowNumber === numChildren) {
props.displayBorder = false;
}
var children = [checkboxColumn];
_react2.default.Children.forEach(child.props.children, function (child) {
children.push(child);
});
return {
v: _react2.default.cloneElement(child, _extends({}, props, handlers), children)
};
}();
if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
}
});
},
_createRowCheckboxColumn: function _createRowCheckboxColumn(rowProps) {
if (!this.props.displayRowCheckbox) return null;
var key = rowProps.rowNumber + '-cb';
var checkbox = _react2.default.createElement(_checkbox2.default, {
ref: 'rowSelectCB',
name: key,
value: 'selected',
disabled: !this.props.selectable,
checked: rowProps.selected
});
return _react2.default.createElement(
_tableRowColumn2.default,
{
key: key,
columnNumber: 0,
style: { width: 24 } },
checkbox
);
},
_calculatePreselectedRows: function _calculatePreselectedRows(props) {
// Determine what rows are 'pre-selected'.
var preSelectedRows = [];
if (props.selectable && props.preScanRows) {
(function () {
var index = 0;
_react2.default.Children.forEach(props.children, function (child) {
if (_react2.default.isValidElement(child)) {
if (child.props.selected && (preSelectedRows.length === 0 || props.multiSelectable)) {
preSelectedRows.push(index);
}
index++;
}
});
})();
}
return preSelectedRows;
},
_isRowSelected: function _isRowSelected(rowNumber) {
if (this.props.allRowsSelected) {
return true;
}
for (var i = 0; i < this.state.selectedRows.length; i++) {
var selection = this.state.selectedRows[i];
if ((typeof selection === 'undefined' ? 'undefined' : _typeof(selection)) === 'object') {
if (this._isValueInRange(rowNumber, selection)) return true;
} else {
if (selection === rowNumber) return true;
}
}
return false;
},
_isValueInRange: function _isValueInRange(value, range) {
if (!range) return false;
if (range.start <= value && value <= range.end || range.end <= value && value <= range.start) {
return true;
}
return false;
},
_onRowClick: function _onRowClick(e, rowNumber) {
e.stopPropagation();
if (this.props.selectable) {
// Prevent text selection while selecting rows.
window.getSelection().removeAllRanges();
this._processRowSelection(e, rowNumber);
}
},
_processRowSelection: function _processRowSelection(e, rowNumber) {
var selectedRows = this.state.selectedRows;
if (e.shiftKey && this.props.multiSelectable && selectedRows.length) {
var lastIndex = selectedRows.length - 1;
var lastSelection = selectedRows[lastIndex];
if ((typeof lastSelection === 'undefined' ? 'undefined' : _typeof(lastSelection)) === 'object') {
lastSelection.end = rowNumber;
} else {
selectedRows.splice(lastIndex, 1, { start: lastSelection, end: rowNumber });
}
} else if ((e.ctrlKey && !e.metaKey || e.metaKey && !e.ctrlKey) && this.props.multiSelectable) {
var idx = selectedRows.indexOf(rowNumber);
if (idx < 0) {
var foundRange = false;
for (var i = 0; i < selectedRows.length; i++) {
var range = selectedRows[i];
if ((typeof range === 'undefined' ? 'undefined' : _typeof(range)) !== 'object') continue;
if (this._isValueInRange(rowNumber, range)) {
var _selectedRows;
foundRange = true;
var values = this._splitRange(range, rowNumber);
(_selectedRows = selectedRows).splice.apply(_selectedRows, [i, 1].concat(_toConsumableArray(values)));
}
}
if (!foundRange) selectedRows.push(rowNumber);
} else {
selectedRows.splice(idx, 1);
}
} else {
if (selectedRows.length === 1 && selectedRows[0] === rowNumber) {
selectedRows = [];
} else {
selectedRows = [rowNumber];
}
}
this.setState({ selectedRows: selectedRows });
if (this.props.onRowSelection) this.props.onRowSelection(this._flattenRanges(selectedRows));
},
_splitRange: function _splitRange(range, splitPoint) {
var splitValues = [];
var startOffset = range.start - splitPoint;
var endOffset = range.end - splitPoint;
// Process start half
splitValues.push.apply(splitValues, _toConsumableArray(this._genRangeOfValues(splitPoint, startOffset)));
// Process end half
splitValues.push.apply(splitValues, _toConsumableArray(this._genRangeOfValues(splitPoint, endOffset)));
return splitValues;
},
_genRangeOfValues: function _genRangeOfValues(start, offset) {
var values = [];
var dir = offset > 0 ? -1 : 1; // This forces offset to approach 0 from either direction.
while (offset !== 0) {
values.push(start + offset);
offset += dir;
}
return values;
},
_flattenRanges: function _flattenRanges(selectedRows) {
var rows = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = selectedRows[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var selection = _step.value;
if ((typeof selection === 'undefined' ? 'undefined' : _typeof(selection)) === 'object') {
var values = this._genRangeOfValues(selection.end, selection.start - selection.end);
rows.push.apply(rows, [selection.end].concat(_toConsumableArray(values)));
} else {
rows.push(selection);
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return rows.sort();
},
_onCellClick: function _onCellClick(e, rowNumber, columnNumber) {
e.stopPropagation();
if (this.props.onCellClick) this.props.onCellClick(rowNumber, this._getColumnId(columnNumber));
},
_onCellHover: function _onCellHover(e, rowNumber, columnNumber) {
if (this.props.onCellHover) this.props.onCellHover(rowNumber, this._getColumnId(columnNumber));
this._onRowHover(e, rowNumber);
},
_onCellHoverExit: function _onCellHoverExit(e, rowNumber, columnNumber) {
if (this.props.onCellHoverExit) this.props.onCellHoverExit(rowNumber, this._getColumnId(columnNumber));
this._onRowHoverExit(e, rowNumber);
},
_onRowHover: function _onRowHover(e, rowNumber) {
if (this.props.onRowHover) this.props.onRowHover(rowNumber);
},
_onRowHoverExit: function _onRowHoverExit(e, rowNumber) {
if (this.props.onRowHoverExit) this.props.onRowHoverExit(rowNumber);
},
_getColumnId: function _getColumnId(columnNumber) {
var columnId = columnNumber;
if (this.props.displayRowCheckbox) columnId--;
return columnId;
},
render: function render() {
var _props = this.props;
var className = _props.className;
var style = _props.style;
var other = _objectWithoutProperties(_props, ['className', 'style']);
var rows = this._createRows();
return _react2.default.createElement(
'tbody',
{ className: className, style: this.prepareStyles(style) },
rows
);
}
});
exports.default = TableBody;
module.exports = exports['default']; | 34.396465 | 257 | 0.662874 |
b9f74f09284eef85b4d42cdd23a17bcbe4b4ee19 | 14,856 | js | JavaScript | player/js/utils/text/TextProperty.js | russellgoldenberg/lottie-web | 9ce3178df133d3bf7d01744087f6fbe96006a226 | [
"MIT"
] | 1 | 2018-11-01T05:59:37.000Z | 2018-11-01T05:59:37.000Z | player/js/utils/text/TextProperty.js | we452366/lottie-web | 0bf7483657a08208e044a6b7085009304ceddbc9 | [
"MIT"
] | null | null | null | player/js/utils/text/TextProperty.js | we452366/lottie-web | 0bf7483657a08208e044a6b7085009304ceddbc9 | [
"MIT"
] | null | null | null | function TextProperty(elem, data){
this._frameId = initialDefaultFrame;
this.pv = '';
this.v = '';
this.kf = false;
this._isFirstFrame = true;
this._mdf = false;
this.data = data;
this.elem = elem;
this.comp = this.elem.comp;
this.keysIndex = 0;
this.canResize = false;
this.minimumFontSize = 1;
this.effectsSequence = [];
this.currentData = {
ascent: 0,
boxWidth: this.defaultBoxWidth,
f: '',
fStyle: '',
fWeight: '',
fc: '',
j: '',
justifyOffset: '',
l: [],
lh: 0,
lineWidths: [],
ls: '',
of: '',
s: '',
sc: '',
sw: 0,
t: 0,
tr: 0,
sz:0,
ps:null,
fillColorAnim: false,
strokeColorAnim: false,
strokeWidthAnim: false,
yOffset: 0,
finalSize:0,
finalText:[],
finalLineHeight: 0,
__complete: false
};
this.copyData(this.currentData, this.data.d.k[0].s);
if(!this.searchProperty()) {
this.completeTextData(this.currentData);
}
}
TextProperty.prototype.defaultBoxWidth = [0,0];
TextProperty.prototype.copyData = function(obj, data) {
for(var s in data) {
if(data.hasOwnProperty(s)) {
obj[s] = data[s];
}
}
return obj;
}
TextProperty.prototype.setCurrentData = function(data){
if(!data.__complete) {
this.completeTextData(data);
}
this.currentData = data;
this.currentData.boxWidth = this.currentData.boxWidth || this.defaultBoxWidth;
this._mdf = true;
};
TextProperty.prototype.searchProperty = function() {
return this.searchKeyframes();
};
TextProperty.prototype.searchKeyframes = function() {
this.kf = this.data.d.k.length > 1;
if(this.kf) {
this.addEffect(this.getKeyframeValue.bind(this));
}
return this.kf;
}
TextProperty.prototype.addEffect = function(effectFunction) {
this.effectsSequence.push(effectFunction);
this.elem.addDynamicProperty(this);
};
TextProperty.prototype.getValue = function(_finalValue) {
if((this.elem.globalData.frameId === this.frameId || !this.effectsSequence.length) && !_finalValue) {
return;
}
var currentValue = this.currentData;
var currentIndex = this.keysIndex;
if(this.lock) {
this.setCurrentData(this.currentData, currentTextValue);
return;
}
this.lock = true;
this._mdf = false;
var multipliedValue;
var i, len = this.effectsSequence.length;
var finalValue = _finalValue || this.data.d.k[this.keysIndex].s;
for(i = 0; i < len; i += 1) {
//Checking if index changed to prevent creating a new object every time the expression updates.
if(currentIndex !== this.keysIndex) {
finalValue = this.effectsSequence[i](finalValue, finalValue.t);
} else {
finalValue = this.effectsSequence[i](this.currentData, finalValue.t);
}
}
if(currentValue !== finalValue) {
this.setCurrentData(finalValue);
}
this.pv = this.v = this.currentData;
this.lock = false;
this.frameId = this.elem.globalData.frameId;
}
TextProperty.prototype.getKeyframeValue = function() {
var textKeys = this.data.d.k, textDocumentData;
var frameNum = this.elem.comp.renderedFrame;
var i = 0, len = textKeys.length;
while(i <= len - 1) {
textDocumentData = textKeys[i].s;
if(i === len - 1 || textKeys[i+1].t > frameNum){
break;
}
i += 1;
}
if(this.keysIndex !== i) {
this.keysIndex = i;
}
return this.data.d.k[this.keysIndex].s;
};
TextProperty.prototype.buildFinalText = function(text) {
var combinedCharacters = FontManager.getCombinedCharacterCodes();
var charactersArray = [];
var i = 0, len = text.length;
while (i < len) {
if (combinedCharacters.indexOf(text.charCodeAt(i)) !== -1) {
charactersArray[charactersArray.length - 1] += text.charAt(i);
} else {
charactersArray.push(text.charAt(i));
}
i += 1;
}
return charactersArray;
}
TextProperty.prototype.completeTextData = function(documentData) {
documentData.__complete = true;
var fontManager = this.elem.globalData.fontManager;
var data = this.data;
var letters = [];
var i, len;
var newLineFlag, index = 0, val;
var anchorGrouping = data.m.g;
var currentSize = 0, currentPos = 0, currentLine = 0, lineWidths = [];
var lineWidth = 0;
var maxLineWidth = 0;
var j, jLen;
var fontData = fontManager.getFontByName(documentData.f);
var charData, cLength = 0;
var styles = fontData.fStyle ? fontData.fStyle.split(' ') : [];
var fWeight = 'normal', fStyle = 'normal';
len = styles.length;
var styleName;
for(i=0;i<len;i+=1){
styleName = styles[i].toLowerCase();
switch(styleName) {
case 'italic':
fStyle = 'italic';
break;
case 'bold':
fWeight = '700';
break;
case 'black':
fWeight = '900';
break;
case 'medium':
fWeight = '500';
break;
case 'regular':
case 'normal':
fWeight = '400';
break;
case 'light':
case 'thin':
fWeight = '200';
break;
}
}
documentData.fWeight = fontData.fWeight || fWeight;
documentData.fStyle = fStyle;
len = documentData.t.length;
documentData.finalSize = documentData.s;
documentData.finalText = this.buildFinalText(documentData.t);
documentData.finalLineHeight = documentData.lh;
var trackingOffset = documentData.tr/1000*documentData.finalSize;
var charCode;
if(documentData.sz){
var flag = true;
var boxWidth = documentData.sz[0];
var boxHeight = documentData.sz[1];
var currentHeight, finalText;
while(flag) {
finalText = this.buildFinalText(documentData.t);
currentHeight = 0;
lineWidth = 0;
len = finalText.length;
trackingOffset = documentData.tr/1000*documentData.finalSize;
var lastSpaceIndex = -1;
for(i=0;i<len;i+=1){
charCode = finalText[i].charCodeAt(0);
newLineFlag = false;
if(finalText[i] === ' '){
lastSpaceIndex = i;
}else if(charCode === 13 || charCode === 3){
lineWidth = 0;
newLineFlag = true;
currentHeight += documentData.finalLineHeight || documentData.finalSize*1.2;
}
if(fontManager.chars){
charData = fontManager.getCharData(finalText[i], fontData.fStyle, fontData.fFamily);
cLength = newLineFlag ? 0 : charData.w*documentData.finalSize/100;
}else{
//tCanvasHelper.font = documentData.s + 'px '+ fontData.fFamily;
cLength = fontManager.measureText(finalText[i], documentData.f, documentData.finalSize);
}
if(lineWidth + cLength > boxWidth && finalText[i] !== ' '){
if(lastSpaceIndex === -1){
len += 1;
} else {
i = lastSpaceIndex;
}
currentHeight += documentData.finalLineHeight || documentData.finalSize*1.2;
finalText.splice(i, lastSpaceIndex === i ? 1 : 0,"\r");
//finalText = finalText.substr(0,i) + "\r" + finalText.substr(i === lastSpaceIndex ? i + 1 : i);
lastSpaceIndex = -1;
lineWidth = 0;
}else {
lineWidth += cLength;
lineWidth += trackingOffset;
}
}
currentHeight += fontData.ascent*documentData.finalSize/100;
if(this.canResize && documentData.finalSize > this.minimumFontSize && boxHeight < currentHeight) {
documentData.finalSize -= 1;
documentData.finalLineHeight = documentData.finalSize * documentData.lh / documentData.s;
} else {
documentData.finalText = finalText;
len = documentData.finalText.length;
flag = false;
}
}
}
lineWidth = - trackingOffset;
cLength = 0;
var uncollapsedSpaces = 0;
var currentChar;
for (i = 0;i < len ;i += 1) {
newLineFlag = false;
currentChar = documentData.finalText[i];
charCode = currentChar.charCodeAt(0);
if (currentChar === ' '){
val = '\u00A0';
} else if (charCode === 13 || charCode === 3) {
uncollapsedSpaces = 0;
lineWidths.push(lineWidth);
maxLineWidth = lineWidth > maxLineWidth ? lineWidth : maxLineWidth;
lineWidth = - 2 * trackingOffset;
val = '';
newLineFlag = true;
currentLine += 1;
}else{
val = documentData.finalText[i];
}
if(fontManager.chars){
charData = fontManager.getCharData(currentChar, fontData.fStyle, fontManager.getFontByName(documentData.f).fFamily);
cLength = newLineFlag ? 0 : charData.w*documentData.finalSize/100;
}else{
//var charWidth = fontManager.measureText(val, documentData.f, documentData.finalSize);
//tCanvasHelper.font = documentData.finalSize + 'px '+ fontManager.getFontByName(documentData.f).fFamily;
cLength = fontManager.measureText(val, documentData.f, documentData.finalSize);
}
//
if(currentChar === ' '){
uncollapsedSpaces += cLength + trackingOffset;
} else {
lineWidth += cLength + trackingOffset + uncollapsedSpaces;
uncollapsedSpaces = 0;
}
letters.push({l:cLength,an:cLength,add:currentSize,n:newLineFlag, anIndexes:[], val: val, line: currentLine, animatorJustifyOffset: 0});
if(anchorGrouping == 2){
currentSize += cLength;
if(val === '' || val === '\u00A0' || i === len - 1){
if(val === '' || val === '\u00A0'){
currentSize -= cLength;
}
while(currentPos<=i){
letters[currentPos].an = currentSize;
letters[currentPos].ind = index;
letters[currentPos].extra = cLength;
currentPos += 1;
}
index += 1;
currentSize = 0;
}
}else if(anchorGrouping == 3){
currentSize += cLength;
if(val === '' || i === len - 1){
if(val === ''){
currentSize -= cLength;
}
while(currentPos<=i){
letters[currentPos].an = currentSize;
letters[currentPos].ind = index;
letters[currentPos].extra = cLength;
currentPos += 1;
}
currentSize = 0;
index += 1;
}
}else{
letters[index].ind = index;
letters[index].extra = 0;
index += 1;
}
}
documentData.l = letters;
maxLineWidth = lineWidth > maxLineWidth ? lineWidth : maxLineWidth;
lineWidths.push(lineWidth);
if(documentData.sz){
documentData.boxWidth = documentData.sz[0];
documentData.justifyOffset = 0;
}else{
documentData.boxWidth = maxLineWidth;
switch(documentData.j){
case 1:
documentData.justifyOffset = - documentData.boxWidth;
break;
case 2:
documentData.justifyOffset = - documentData.boxWidth/2;
break;
default:
documentData.justifyOffset = 0;
}
}
documentData.lineWidths = lineWidths;
var animators = data.a, animatorData, letterData;
jLen = animators.length;
var based, ind, indexes = [];
for(j=0;j<jLen;j+=1){
animatorData = animators[j];
if(animatorData.a.sc){
documentData.strokeColorAnim = true;
}
if(animatorData.a.sw){
documentData.strokeWidthAnim = true;
}
if(animatorData.a.fc || animatorData.a.fh || animatorData.a.fs || animatorData.a.fb){
documentData.fillColorAnim = true;
}
ind = 0;
based = animatorData.s.b;
for(i=0;i<len;i+=1){
letterData = letters[i];
letterData.anIndexes[j] = ind;
if((based == 1 && letterData.val !== '') || (based == 2 && letterData.val !== '' && letterData.val !== '\u00A0') || (based == 3 && (letterData.n || letterData.val == '\u00A0' || i == len - 1)) || (based == 4 && (letterData.n || i == len - 1))){
if(animatorData.s.rn === 1){
indexes.push(ind);
}
ind += 1;
}
}
data.a[j].s.totalChars = ind;
var currentInd = -1, newInd;
if(animatorData.s.rn === 1){
for(i = 0; i < len; i += 1){
letterData = letters[i];
if(currentInd != letterData.anIndexes[j]){
currentInd = letterData.anIndexes[j];
newInd = indexes.splice(Math.floor(Math.random()*indexes.length),1)[0];
}
letterData.anIndexes[j] = newInd;
}
}
}
documentData.yOffset = documentData.finalLineHeight || documentData.finalSize*1.2;
documentData.ls = documentData.ls || 0;
documentData.ascent = fontData.ascent*documentData.finalSize/100;
};
TextProperty.prototype.updateDocumentData = function(newData, index) {
index = index === undefined ? this.keysIndex : index;
var dData = this.copyData({}, this.data.d.k[index].s);
dData = this.copyData(dData, newData);
this.data.d.k[index].s = dData;
this.recalculate(index);
this.elem.addDynamicProperty(this);
};
TextProperty.prototype.recalculate = function(index) {
var dData = this.data.d.k[index].s;
dData.__complete = false;
this.keysIndex = 0;
this._isFirstFrame = true;
this.getValue(dData);
}
TextProperty.prototype.canResizeFont = function(_canResize) {
this.canResize = _canResize;
this.recalculate(this.keysIndex);
this.elem.addDynamicProperty(this);
};
TextProperty.prototype.setMinimumFontSize = function(_fontValue) {
this.minimumFontSize = Math.floor(_fontValue) || 1;
this.recalculate(this.keysIndex);
this.elem.addDynamicProperty(this);
};
| 34.629371 | 256 | 0.551898 |
b9f75869b38d193b1cf7a485ad52dbc69f704ce2 | 500 | js | JavaScript | WebRoot/static/v2/js/patient/mutation-types.7d94c57bbed0390af54e.js | guoxiangran/main | 3c9b80611230f4f0c85070be0394286d7afd65b5 | [
"MIT"
] | null | null | null | WebRoot/static/v2/js/patient/mutation-types.7d94c57bbed0390af54e.js | guoxiangran/main | 3c9b80611230f4f0c85070be0394286d7afd65b5 | [
"MIT"
] | null | null | null | WebRoot/static/v2/js/patient/mutation-types.7d94c57bbed0390af54e.js | guoxiangran/main | 3c9b80611230f4f0c85070be0394286d7afd65b5 | [
"MIT"
] | null | null | null | webpackJsonp([93],[function(S,E,n){"use strict";Object.defineProperty(E,"__esModule",{value:!0}),n.d(E,"GET_DISTCODES",function(){return T}),n.d(E,"SET_STATE",function(){return t}),n.d(E,"SET_KEEPSTATE",function(){return r}),n.d(E,"SET_GPS",function(){return u}),n.d(E,"SET_SGPS",function(){return e}),n.d(E,"SET_WXINFO",function(){return _}),n.d(E,"SET_GOEASY",function(){return c});var T="GET_DISTCODES",t="SET_STATE",r="SET_KEEPSTATE",u="SET_GPS",e="SET_SGPS",_="SET_WXINFO",c="SET_GOEASY"}],[0]); | 500 | 500 | 0.696 |
b9f780e6ea68c789470cb63d2ab12ba735f5be51 | 612 | js | JavaScript | src/ai.worker.js | serprex/openEtG | 56479bbb939df42a9eb1b04259825444f2d66637 | [
"MIT"
] | 48 | 2015-04-30T15:22:25.000Z | 2022-03-25T05:10:19.000Z | src/ai.worker.js | serprex/openEtG | 56479bbb939df42a9eb1b04259825444f2d66637 | [
"MIT"
] | 20 | 2015-05-31T23:20:18.000Z | 2021-10-17T19:28:15.000Z | src/ai.worker.js | serprex/openEtG | 56479bbb939df42a9eb1b04259825444f2d66637 | [
"MIT"
] | 18 | 2015-05-12T17:41:11.000Z | 2021-07-31T03:33:43.000Z | import CreateGame from './Game.js';
let game = null,
premoves = null;
onmessage = async function (e) {
const {
id,
data: { data, moves },
} = e.data;
if (
game === null ||
premoves.length > moves.length ||
JSON.stringify(data) !== JSON.stringify(game.data) ||
JSON.stringify(premoves) !== JSON.stringify(moves.slice(0, premoves.length))
) {
game = await CreateGame(data);
premoves = null;
}
for (let i = premoves !== null ? premoves.length : 0; i < moves.length; i++) {
game.next(moves[i], false);
}
premoves = moves;
postMessage({ id, cmd: game.aiSearch() });
};
postMessage(null);
| 23.538462 | 79 | 0.630719 |
b9f7c487303dfa8590621c687b2e042045c9779a | 2,220 | js | JavaScript | test/unit-tests/switchTo.test.js | jfgreffier/taiko | 0be7642ba4bbe9a97d5a93af6b34722097e9138d | [
"MIT"
] | null | null | null | test/unit-tests/switchTo.test.js | jfgreffier/taiko | 0be7642ba4bbe9a97d5a93af6b34722097e9138d | [
"MIT"
] | null | null | null | test/unit-tests/switchTo.test.js | jfgreffier/taiko | 0be7642ba4bbe9a97d5a93af6b34722097e9138d | [
"MIT"
] | null | null | null | const chai = require('chai');
const expect = require('chai').expect;
let chaiAsPromised = require('chai-as-promised');
const rewire = require('rewire');
chai.use(chaiAsPromised);
describe('switchTo', () => {
let argument, taiko;
let registeredTarget;
before(async () => {
taiko = rewire('../../lib/taiko');
taiko.__set__('validate', () => {});
taiko.__set__('targetHandler.getCriTargets', (arg) => {
argument = arg;
return { matching: [] };
});
taiko.__set__('targetHandler.register', () => {
return registeredTarget;
});
taiko.__set__('connect_to_cri', () => {
return registeredTarget;
});
});
after(() => {
taiko = rewire('../../lib/taiko');
});
it('should throw error if no url specified', async () => {
await expect(taiko.switchTo()).to.eventually.rejectedWith(
'The "targetUrl" argument must be of type string, regex or identifier. Received type undefined',
);
});
it('should throw error if url is empty', async () => {
await expect(taiko.switchTo('')).to.eventually.rejectedWith(
'Cannot switch to tab or window as the targetUrl is empty. Please use a valid string, regex or identifier',
);
});
it('should throw error if url is only spaces', async () => {
await expect(taiko.switchTo(' ')).to.eventually.rejectedWith(
'Cannot switch to tab or window as the targetUrl is empty. Please use a valid string, regex or identifier',
);
});
it('should accept regex and call targetHandler with RegExp', async () => {
await expect(taiko.switchTo(/http(s):\/\/www.google.com/)).to.eventually.rejectedWith(
'No tab(s) matching /http(s):\\/\\/www.google.com/ found',
);
await expect(argument).to.deep.equal(new RegExp(/http(s):\/\/www.google.com/));
});
it('should accept window identifier', async () => {
await expect(taiko.switchTo({ name: 'github' })).to.eventually.rejectedWith(
'Could not find window/tab with name github to switch.',
);
});
it('should switch to tab matching identifier', async () => {
registeredTarget = {
id: 'github',
};
await expect(taiko.switchTo({ name: 'github' })).to.eventually.fulfilled;
});
});
| 32.173913 | 113 | 0.628378 |
b9f7fb321dad185d6e5f0b8e2ddc9c75270b371b | 2,279 | js | JavaScript | app/ns-framework-modules-category/file-system/update/update-page.js | yringler/nativescript-sdk-examples-js | c91c3db1f36674fffaf98c7e8a4912470883b927 | [
"Apache-2.0"
] | 2 | 2019-12-26T11:48:07.000Z | 2019-12-26T11:48:09.000Z | app/ns-framework-modules-category/file-system/update/update-page.js | yringler/nativescript-sdk-examples-js | c91c3db1f36674fffaf98c7e8a4912470883b927 | [
"Apache-2.0"
] | null | null | null | app/ns-framework-modules-category/file-system/update/update-page.js | yringler/nativescript-sdk-examples-js | c91c3db1f36674fffaf98c7e8a4912470883b927 | [
"Apache-2.0"
] | 1 | 2019-11-01T11:16:15.000Z | 2019-11-01T11:16:15.000Z | const Observable = require("tns-core-modules/data/observable").Observable;
const fileSystemModule = require("tns-core-modules/file-system");
const dialogs = require("tns-core-modules/ui/dialogs");
let file;
let myFolder;
function onNavigatingTo(args) {
const page = args.object;
const vm = new Observable();
const documents = fileSystemModule.knownFolders.documents();
file = documents.getFile("TestFileName.txt");
myFolder = documents.getFolder("TestFolderName");
vm.set("fileName", "TestFileName");
vm.set("fileSuccessMessage", "");
vm.set("folderName", "TestFolderName");
vm.set("folderSuccessMessage", "");
vm.set("isItemVisible", false);
vm.set("isFolderItemVisible", false);
page.bindingContext = vm;
}
function onFileRename(args) {
const page = args.object.page;
const vm = page.bindingContext;
// >> fs-update-rename-file-code
const fileName = vm.get("fileName");
file.rename(`${fileName}.txt`)
.then((res) => {
// File Successfully Renamed.
vm.set("fileSuccessMessage", `File renamed to: ${fileName}.txt`);
vm.set("isItemVisible", true);
}).catch((err) => {
// Error!
console.log("Error: ");
console.log(err);
dialogs.alert(err)
.then(() => {
console.log("Dialog closed!");
});
});
// << fs-update-rename-file-code
}
function onFolderRename(args) {
const page = args.object.page;
const vm = page.bindingContext;
// >> fs-update-rename-folder-code
const folderName = vm.get("folderName");
myFolder.rename(folderName)
.then((res) => {
// Folder Successfully Renamed.
vm.set("folderSuccessMessage", `Folder renamed to: ${folderName}`);
vm.set("isFolderItemVisible", true);
}).catch((err) => {
// Error!
console.log("Error: ");
console.log(err);
dialogs.alert(err)
.then(() => {
console.log("Dialog closed!");
});
});
// << fs-update-rename-folder-code
}
exports.onNavigatingTo = onNavigatingTo;
exports.onFileRename = onFileRename;
exports.onFolderRename = onFolderRename;
| 32.098592 | 80 | 0.592365 |
b9f81c711b230c1120935945af20a923eef41eaa | 1,000 | js | JavaScript | demos/ext-react-modern-tester/src/Renderer.js | msgimanila/EXT-React-MSG | 9e78cceedc85204d28584849d64214e638f2b6f6 | [
"Apache-2.0"
] | 94 | 2018-08-29T15:23:23.000Z | 2022-01-30T07:46:28.000Z | demos/ext-react-modern-tester/src/Renderer.js | msgimanila/EXT-React-MSG | 9e78cceedc85204d28584849d64214e638f2b6f6 | [
"Apache-2.0"
] | 49 | 2018-08-21T22:44:33.000Z | 2021-08-11T21:08:29.000Z | demos/ext-react-modern-tester/src/Renderer.js | msgimanila/EXT-React-MSG | 9e78cceedc85204d28584849d64214e638f2b6f6 | [
"Apache-2.0"
] | 46 | 2018-08-08T17:12:19.000Z | 2021-11-11T10:00:49.000Z | import React, { Component } from 'react';
import { ExtGrid, ExtColumn } from "@sencha/ext-react-modern";
const Ext = window['Ext'];
export default class Renderer extends Component {
constructor() {
super()
var data=[
{ name: 'Marc', email: 'marc@gmail.com',priceChangePct: .25 },
{ name: 'Nick', email: 'nick@gmail.com',priceChangePct: .35 },
{ name: 'Andy', email: 'andy@gmail.com',priceChangePct: .45 }
]
this.store = {xtype: 'store',data: data}
}
renderSign = (format, value) => (
<span style={{ color: value > 0 ? 'green' : value < 0 ? 'red' : ''}}>
{Ext.util.Format.number(value, format)}
</span>
)
render() {
return (
<ExtGrid
viewport={ true }
title="The Grid"
store={ this.store }
>
<ExtColumn
text="% Change"
dataIndex="priceChangePct"
align="right"
renderer={ this.renderSign.bind(this, '0.00') }
/>
</ExtGrid>
)
}
}
| 24.390244 | 73 | 0.545 |
b9f8a6a27d95ddcdceb5905f51ecd636b11593ab | 1,143 | js | JavaScript | src/components/_globals.js | mfeyx/vue-enterprise-boilerplate | 0a0c307ded9caebad66097650ca0a356ab3461d5 | [
"MIT"
] | 5 | 2019-02-20T01:31:24.000Z | 2019-02-20T16:23:31.000Z | src/components/_globals.js | FantasiaMoon/vue-enterprise-boilerplate | 0a0c307ded9caebad66097650ca0a356ab3461d5 | [
"MIT"
] | 12 | 2020-09-04T23:11:55.000Z | 2022-02-26T11:29:20.000Z | src/components/_globals.js | FantasiaMoon/vue-enterprise-boilerplate | 0a0c307ded9caebad66097650ca0a356ab3461d5 | [
"MIT"
] | 3 | 2020-06-03T13:58:49.000Z | 2020-06-10T05:17:43.000Z | // Globally register all base components for convenience, because they
// will be used very frequently. Components are registered using the
// PascalCased version of their file name.
import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
// https://webpack.js.org/guides/dependency-management/#require-context
const requireComponent = require.context(
// Look for files in the current directory
'.',
// Do not look in subdirectories
false,
// Only include "_base-" prefixed .vue files
/_base-[\w-]+\.vue$/
)
// For each matching file name...
requireComponent.keys().forEach((fileName) => {
// Get the component config
const componentConfig = requireComponent(fileName)
// Get the PascalCase version of the component name
const componentName = upperFirst(
camelCase(
fileName
// Remove the "./_" from the beginning
.replace(/^\.\/_/, '')
// Remove the file extension from the end
.replace(/\.\w+$/, '')
)
)
// Globally register the component
Vue.component(componentName, componentConfig.default || componentConfig)
})
| 31.75 | 74 | 0.700787 |
b9f8aed003ee152c7ab5b28614b4f98314e06dd1 | 404 | js | JavaScript | src/checkbox.js | armand1m/ink-multi-select | 7aac41bd3ddb41a28d0c9f9bced64125f8f4ea2a | [
"MIT"
] | 2 | 2020-09-23T09:26:18.000Z | 2020-09-24T08:55:28.000Z | src/checkbox.js | armand1m/ink-multi-select | 7aac41bd3ddb41a28d0c9f9bced64125f8f4ea2a | [
"MIT"
] | null | null | null | src/checkbox.js | armand1m/ink-multi-select | 7aac41bd3ddb41a28d0c9f9bced64125f8f4ea2a | [
"MIT"
] | 1 | 2020-09-26T02:55:12.000Z | 2020-09-26T02:55:12.000Z | import React from 'react';
import PropTypes from 'prop-types';
import {Box, Color} from 'ink';
import figures from 'figures';
const CheckBox = ({isSelected}) => (
<Box marginRight={1}>
<Color green>{isSelected ? figures.circleFilled : figures.circle}</Color>
</Box>
);
CheckBox.propTypes = {
isSelected: PropTypes.bool
};
CheckBox.defaultProps = {
isSelected: false
};
export default CheckBox;
| 19.238095 | 75 | 0.710396 |
b9f90daef9216142edb4219f322fe5a635eeb9b8 | 772 | js | JavaScript | Gerador_CodigoAleatorio.js | ysh-rael/Gerador-codigos | 94776453b4bc4b495c0d076765cc3fa821c4c6b1 | [
"MIT"
] | null | null | null | Gerador_CodigoAleatorio.js | ysh-rael/Gerador-codigos | 94776453b4bc4b495c0d076765cc3fa821c4c6b1 | [
"MIT"
] | null | null | null | Gerador_CodigoAleatorio.js | ysh-rael/Gerador-codigos | 94776453b4bc4b495c0d076765cc3fa821c4c6b1 | [
"MIT"
] | null | null | null | //Gera um Código aleatorio (apenas números)
function random(Tcollun, min=0, max=10) {//caso não seja especificado o valor do parâmetro, eles recebem 1 e 10.
let codigoAle = []
for(let i = 0; i < Tcollun; i++) {
const nAle = Math.floor(Math.random()*(max-min)+min)
codigoAle += [nAle]
}
console.log(codigoAle)
}
function codigo(tcoluna=10, linha=1,min,max) {
for(let i = 0; i < linha; i++) {
random(tcoluna,min,max)
}
}
/*!!Sequencias dos parâmetros da Função codigo!!
1 => n° Colunas (quantidade de caracteres de cada código)
2 => n° Linhas (quantidade de códigos a serem gerados)
3/4 => Dois últimos parâmetros: possíveis números gerados {
gerar codigo usando números entre..[x]
até.... [y-1] visão do parametro:(x,y) }
*/
codigo()
//!!FUNCIONANDO!! | 27.571429 | 112 | 0.676166 |
b9f9313af1c6f717986992842b4e4a321bdfd2ee | 1,812 | js | JavaScript | kityformula-plugin/getKfContent.js | backgroundColor/ueditor | 2d810c05ee7933230a8abd7a03aa20ea063b4ea0 | [
"MIT"
] | null | null | null | kityformula-plugin/getKfContent.js | backgroundColor/ueditor | 2d810c05ee7933230a8abd7a03aa20ea063b4ea0 | [
"MIT"
] | null | null | null | kityformula-plugin/getKfContent.js | backgroundColor/ueditor | 2d810c05ee7933230a8abd7a03aa20ea063b4ea0 | [
"MIT"
] | null | null | null | /**
* Created by zhangbo21 on 14-9-2.
*/
/*
* getKfContent : 将image的src从base64替换为文件名
* param : callback -- 回调函数 其参数为替换之后的内容
* return : void
* */
UE.Editor.prototype.getKfContent = function(callback){
var me = this;
var actionUrl = me.getActionUrl(me.getOpt('scrawlActionName')),
params = UE.utils.serializeParam(me.queryCommandValue('serverparam')) || '',
url = UE.utils.formatUrl(actionUrl + (actionUrl.indexOf('?') == -1 ? '?':'&') + params);
// 找到所有的base64
var count = 0;
var imgs =me.body.getElementsByTagName('img');
var base64Imgs = [];
UE.utils.each(imgs, function(item){
var imgType = item.getAttribute('src').match(/^[^;]+/)[0];
if ( imgType === 'data:image/png') {
base64Imgs.push(item);
}
});
if (base64Imgs.length == 0){
execCallback();
} else {
UE.utils.each(base64Imgs, function(item){
var opt ={};
opt[me.getOpt('scrawlFieldName')]= item.getAttribute('src').replace(/^[^,]+,/, '');
opt.onsuccess = function(xhr){
var json = UE.utils.str2json(xhr.responseText),
url = me.options.scrawlUrlPrefix + json.url;
item.setAttribute('src', url);
item.setAttribute('_src', url);
count++;
execCallback();
}
opt.onerror = function(err){
console.error(err);
count++;
execCallback();
}
UE.ajax.request(url, opt);
});
}
function execCallback(){
if (count >= base64Imgs.length) {
me.sync();
callback(me.getContent());
}
}
}; | 27.454545 | 97 | 0.497792 |
b9fabf458e79a62d5f0aa0b28d41254bc269065e | 270 | js | JavaScript | frontend/src/utils/getTaskContributors.js | KathmanduLivingLabs/tasking-manager | 259f16d068617293edbdcdd983168c56c26cf4b1 | [
"BSD-2-Clause"
] | 421 | 2017-02-16T15:02:51.000Z | 2022-03-06T07:12:14.000Z | frontend/src/utils/getTaskContributors.js | KathmanduLivingLabs/tasking-manager | 259f16d068617293edbdcdd983168c56c26cf4b1 | [
"BSD-2-Clause"
] | 3,143 | 2017-02-14T16:47:25.000Z | 2022-03-30T11:25:20.000Z | frontend/src/utils/getTaskContributors.js | drklrd/tasking-manager | 3c12892ac1e506e2170bff7e5e1094c416f6603e | [
"BSD-2-Clause"
] | 280 | 2017-04-06T19:51:32.000Z | 2022-03-16T09:21:27.000Z | export const getTaskContributors = (taskHistory, usernameToExclude) =>
taskHistory.reduce((acc, history) => {
if (!acc.includes(history.actionBy) && history.actionBy !== usernameToExclude) {
acc.push(history.actionBy);
}
return acc.sort();
}, []);
| 33.75 | 84 | 0.666667 |
b9fb1396b36d6fcb630602894e102f4ce41b537e | 1,085 | js | JavaScript | js/task-08.js | elenrosee/goit-js-hw-07 | ea47dd01087f143a757edf11f3f8aff5caeb463c | [
"MIT"
] | null | null | null | js/task-08.js | elenrosee/goit-js-hw-07 | ea47dd01087f143a757edf11f3f8aff5caeb463c | [
"MIT"
] | null | null | null | js/task-08.js | elenrosee/goit-js-hw-07 | ea47dd01087f143a757edf11f3f8aff5caeb463c | [
"MIT"
] | null | null | null | const refs = {
input: document.querySelector('input'),
renderBtn: document.querySelector('[data-action="render"]'),
destroyBtn: document.querySelector('[data-action="destroy"]'),
boxes: document.querySelector('#boxes'),
};
refs.renderBtn.addEventListener('click', () => createBoxes(refs.input.value));
refs.destroyBtn.addEventListener('click', destroyBoxes);
function destroyBoxes() {
refs.boxes.innerHTML = '';
}
function createBoxes(amount) {
const fragment = document.createDocumentFragment();
for (let i = 0; i < amount; i += 1) {
const box = document.createElement('div');
box.style.width = `${30 + i * 10}px`;
box.style.height = `${30 + i * 10}px`;
box.style.backgroundColor = createRandomRGB();
fragment.appendChild(box);
}
refs.boxes.appendChild(fragment);
}
function createRandomRGB() {
const red = Math.round(Math.random() * (255 - 0) + 1);
const blue = Math.round(Math.random() * (255 - 0) + 1);
const green = Math.round(Math.random() * (255 - 0) + 1);
const color = `rgb(${red}, ${green},${blue})`;
return color;
}
| 27.125 | 78 | 0.657143 |
b9fb18a4d631afad6929a8c8d0a65eb74a2eab33 | 1,112 | js | JavaScript | src/cartesian.js | jrus/d3-geo | 6668d1593f6deca8f9ee234a09434b73885f2ba7 | [
"BSD-3-Clause"
] | 1 | 2020-04-16T09:59:23.000Z | 2020-04-16T09:59:23.000Z | src/cartesian.js | jrus/d3-geo | 6668d1593f6deca8f9ee234a09434b73885f2ba7 | [
"BSD-3-Clause"
] | null | null | null | src/cartesian.js | jrus/d3-geo | 6668d1593f6deca8f9ee234a09434b73885f2ba7 | [
"BSD-3-Clause"
] | null | null | null | import {asin, atan2, cos, hypot, sin} from "./math.js";
export function spherical(cartesian) {
return [atan2(cartesian[1], cartesian[0]), asin(cartesian[2])];
}
export function cartesian(spherical) {
var lambda = spherical[0], phi = spherical[1], cosPhi = cos(phi);
return [cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi)];
}
export function cartesianDot(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
export function cartesianCross(a, b) {
return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
}
export function cartesianMidpoint(a, b) {
var m0 = a[0] + b[0],
m1 = a[1] + b[1],
m2 = a[2] + b[2],
scale = 1 / hypot(m0, m1, m2);
return [m0 * scale, m1 * scale, m2 * scale];
}
// TODO return a
export function cartesianAddInPlace(a, b) {
a[0] += b[0], a[1] += b[1], a[2] += b[2];
}
export function cartesianScale(vector, k) {
return [vector[0] * k, vector[1] * k, vector[2] * k];
}
// TODO return d
export function cartesianNormalizeInPlace(d) {
var l = hypot(d[0], d[1], d[2]);
d[0] /= l, d[1] /= l, d[2] /= l;
}
| 26.47619 | 91 | 0.569245 |
b9fb8a6703dd47df7f1550ad5b475450d3f76b04 | 539 | js | JavaScript | cms/smarty/templates/tpls/lvsecanyin/nav.js | taobataoma/saivi | d25a7990ab5f5f408987885bfcb83b09179e2251 | [
"Apache-2.0"
] | 5 | 2015-06-28T16:35:02.000Z | 2018-10-21T02:15:05.000Z | cms/smarty/templates/tpls/lvsecanyin/nav.js | taobataoma/saivi | d25a7990ab5f5f408987885bfcb83b09179e2251 | [
"Apache-2.0"
] | null | null | null | cms/smarty/templates/tpls/lvsecanyin/nav.js | taobataoma/saivi | d25a7990ab5f5f408987885bfcb83b09179e2251 | [
"Apache-2.0"
] | 6 | 2015-06-28T16:35:02.000Z | 2018-10-21T02:15:07.000Z | $(document).ready(function() {
$('.iconnav').click(function() {
$('.nav').slideToggle();
});
$('.backtop').click(function() {
$('.nav').slideUp();
});
$('.iconsearch').click(function() {
$('.search').slideToggle(500);
});
$('.classbtn').click(function(){
$(".classbtn").css('display','none');
$(".classbtn2").css('display','block');
$('.subnav').slideDown();
});
$('.classbtn2').click(function(){
$(".classbtn").css('display','block');
$(".classbtn2").css('display','none');
$('.subnav').slideUp();
});
});
| 24.5 | 41 | 0.539889 |
b9fbb0978db6399dbedaac68ba7783e2fb39d1a7 | 650 | js | JavaScript | src/styles/contactStyle.js | agielasyari1/personal-website-react | 8ce8e0452f6dd72f0b046c052ebded4ee83b5a60 | [
"MIT"
] | 59 | 2018-10-12T05:54:11.000Z | 2022-02-15T11:39:46.000Z | src/styles/contactStyle.js | agielasyari1/personal-website-react | 8ce8e0452f6dd72f0b046c052ebded4ee83b5a60 | [
"MIT"
] | 14 | 2019-04-04T09:17:34.000Z | 2022-02-27T23:26:03.000Z | src/styles/contactStyle.js | agielasyari1/personal-website-react | 8ce8e0452f6dd72f0b046c052ebded4ee83b5a60 | [
"MIT"
] | 31 | 2019-04-04T08:47:07.000Z | 2022-01-27T07:54:44.000Z | import styled from "styled-components";
export const ContactWrapper = styled.div`
margin: 10% auto;
@media (max-width: 700px) {
margin: 15% auto;
}
`;
export const ContactHeader = styled.h1`
text-align: CENTER;
color: #7fa1e8;
margin-bottom: 5%;
font-weight: 300;
`;
export const ContactDetails = styled.div`
display: flex;
align-items: baseline;
justify-content: center;
@media (max-width: 700px) {
flex-direction: column;
align-items: center;
}
`;
export const ContactBox = styled.div`
display: flex;
align-items: center;
flex-direction: column;
font-weight: 300;
@media (max-width: 700px) {
flex-direction: column;
}
`;
| 19.69697 | 41 | 0.698462 |
b9fbb0fcdcaab2bd8d304fd2d0f01d7f8f274628 | 984 | js | JavaScript | html/namespaceBench__mod.js | cdslaborg/paramonte-api-kernel | b0aa0aae26b0c531b52b003dab3b89a6d1aeff87 | [
"MIT"
] | null | null | null | html/namespaceBench__mod.js | cdslaborg/paramonte-api-kernel | b0aa0aae26b0c531b52b003dab3b89a6d1aeff87 | [
"MIT"
] | null | null | null | html/namespaceBench__mod.js | cdslaborg/paramonte-api-kernel | b0aa0aae26b0c531b52b003dab3b89a6d1aeff87 | [
"MIT"
] | null | null | null | var namespaceBench__mod =
[
[ "Bench_type", "structBench__mod_1_1Bench__type.html", "structBench__mod_1_1Bench__type" ],
[ "BenchBase_type", "structBench__mod_1_1BenchBase__type.html", "structBench__mod_1_1BenchBase__type" ],
[ "exec_proc", "interfaceBench__mod_1_1exec__proc.html", "interfaceBench__mod_1_1exec__proc" ],
[ "Stat_type", "structBench__mod_1_1Stat__type.html", "structBench__mod_1_1Stat__type" ],
[ "Timing_type", "structBench__mod_1_1Timing__type.html", "structBench__mod_1_1Timing__type" ],
[ "constructBench", "namespaceBench__mod.html#a16467ea4d1853b462976b52e0d95f53f", null ],
[ "execEmpty", "namespaceBench__mod.html#a24459d76861f1112be532f76d4801b5f", null ],
[ "finalizeBench", "namespaceBench__mod.html#a8f3249a84c6762174cafe01ef8179a85", null ],
[ "timeExec", "namespaceBench__mod.html#a614b800597a05c0abca522f81f71769f", null ],
[ "MODULE_NAME", "namespaceBench__mod.html#a871abba5d3131ad228625eb9c9f4a6b1", null ]
]; | 75.692308 | 108 | 0.784553 |
b9fcdfe4f91792327ae59f28ab3475771d959483 | 1,015 | js | JavaScript | cloudfunctions/ty-service/node_modules/@cloudbase/node-sdk/node_modules/@cloudbase/database/dist/esm/utils/symbol.js | qq81860186/tuya-weapp-demo | 4101e9203200a9c5a81931aceb25084ab67626ec | [
"MIT"
] | 137 | 2018-08-11T14:42:03.000Z | 2022-03-11T11:56:50.000Z | cloudfunctions/ty-service/node_modules/@cloudbase/node-sdk/node_modules/@cloudbase/database/dist/esm/utils/symbol.js | qq81860186/tuya-weapp-demo | 4101e9203200a9c5a81931aceb25084ab67626ec | [
"MIT"
] | 19 | 2019-09-06T09:58:56.000Z | 2022-03-19T07:35:02.000Z | cloudfunctions/ty-service/node_modules/@cloudbase/node-sdk/node_modules/@cloudbase/database/dist/esm/utils/symbol.js | qq81860186/tuya-weapp-demo | 4101e9203200a9c5a81931aceb25084ab67626ec | [
"MIT"
] | 27 | 2018-08-15T00:01:26.000Z | 2021-09-24T03:25:35.000Z | const _symbols = [];
const __internalMark__ = {};
class HiddenSymbol {
constructor(target) {
Object.defineProperties(this, {
target: {
enumerable: false,
writable: false,
configurable: false,
value: target,
},
});
}
}
export class InternalSymbol extends HiddenSymbol {
constructor(target, __mark__) {
if (__mark__ !== __internalMark__) {
throw new TypeError('InternalSymbol cannot be constructed with new operator');
}
super(target);
}
static for(target) {
for (let i = 0, len = _symbols.length; i < len; i++) {
if (_symbols[i].target === target) {
return _symbols[i].instance;
}
}
const symbol = new InternalSymbol(target, __internalMark__);
_symbols.push({
target,
instance: symbol,
});
return symbol;
}
}
export default InternalSymbol;
| 27.432432 | 90 | 0.531034 |
b9fd1a9c20c129e2f53a78dbc56eef330e5faea1 | 3,313 | js | JavaScript | lib/device-log/ios-simulator-log.js | pup2878-cpu/appium-xcuitest-driver | 112ed6d04562ea253b2fce4afef3c332dfa4802c | [
"Apache-2.0"
] | 6 | 2017-02-23T11:35:39.000Z | 2020-02-23T14:42:22.000Z | lib/device-log/ios-simulator-log.js | pup2878-cpu/appium-xcuitest-driver | 112ed6d04562ea253b2fce4afef3c332dfa4802c | [
"Apache-2.0"
] | null | null | null | lib/device-log/ios-simulator-log.js | pup2878-cpu/appium-xcuitest-driver | 112ed6d04562ea253b2fce4afef3c332dfa4802c | [
"Apache-2.0"
] | 24 | 2017-02-09T10:44:12.000Z | 2021-03-24T05:37:38.000Z | import _ from 'lodash';
import { IOSLog } from './ios-log';
import { logger } from 'appium-support';
import { SubProcess, exec } from 'teen_process';
const log = logger.getLogger('IOSSimulatorLog');
const START_TIMEOUT = 10000;
class IOSSimulatorLog extends IOSLog {
constructor (opts) {
super();
this.sim = opts.sim;
this.showLogs = !!opts.showLogs;
this.xcodeVersion = opts.xcodeVersion;
this.proc = null;
}
async startCapture () {
if (_.isUndefined(this.sim.udid)) {
throw new Error(`Log capture requires a sim udid`);
}
if (!await this.sim.isRunning()) {
throw new Error(`iOS Simulator with udid ${this.sim.udid} is not running`);
}
const tool = 'xcrun';
const args = ['simctl', 'spawn', this.sim.udid, 'log', 'stream', '--style', 'compact'];
log.debug(`Starting log capture for iOS Simulator with udid '${this.sim.udid}', ` +
`using '${tool} ${args.join(' ')}'`);
try {
// cleanup existing listeners if the previous session has not been terminated properly
await exec('pkill', ['-xf', [tool, ...args].join(' ')]);
} catch (ign) {}
try {
this.proc = new SubProcess(tool, args);
await this.finishStartingLogCapture();
} catch (e) {
throw new Error(`Simulator log capture failed. Original error: ${e.message}`);
}
}
async finishStartingLogCapture () {
if (!this.proc) {
log.errorAndThrow('Could not capture simulator log');
}
let firstLine = true;
let logRow = '';
this.proc.on('output', (stdout, stderr) => {
if (stdout) {
if (firstLine) {
if (stdout.endsWith('\n')) {
// don't store the first line of the log because it came before the sim was launched
firstLine = false;
}
} else {
logRow += stdout;
if (stdout.endsWith('\n')) {
this.onOutput(logRow);
logRow = '';
}
}
}
if (stderr) {
this.onOutput(logRow, 'STDERR');
}
});
let sd = (stdout, stderr) => {
if (/execvp\(\)/.test(stderr)) {
throw new Error('iOS log capture process failed to start');
}
return stdout || stderr;
};
await this.proc.start(sd, START_TIMEOUT);
}
async stopCapture () {
if (!this.proc) {
return;
}
await this.killLogSubProcess();
this.proc = null;
}
async killLogSubProcess () {
if (!this.proc.isRunning) {
return;
}
log.debug('Stopping iOS log capture');
try {
await this.proc.stop('SIGTERM', 1000);
} catch (e) {
if (!this.proc.isRunning) {
return;
}
logger.warn('Cannot stop log capture process. Sending SIGKILL...');
await this.proc.stop('SIGKILL');
}
}
get isCapturing () {
return this.proc && this.proc.isRunning;
}
onOutput (logRow, prefix = '') {
const logs = _.cloneDeep(logRow.split('\n'));
for (const logLine of logs) {
if (!logLine) continue; // eslint-disable-line curly
this.broadcast(logLine);
if (this.showLogs) {
const space = prefix.length > 0 ? ' ' : '';
log.info(`[IOS_SYSLOG_ROW${space}${prefix}] ${logLine}`);
}
}
}
}
export { IOSSimulatorLog };
export default IOSSimulatorLog; | 27.608333 | 96 | 0.573196 |
b9fd2879f6a1f595e3706601901e0b064c130c8b | 340 | js | JavaScript | lib/competition/upsert.js | richardschneider/club-server | 97bb3430ae29916a3254f6ddb1b010021468e355 | [
"MIT"
] | null | null | null | lib/competition/upsert.js | richardschneider/club-server | 97bb3430ae29916a3254f6ddb1b010021468e355 | [
"MIT"
] | 3 | 2017-05-30T05:10:36.000Z | 2017-06-27T00:06:22.000Z | lib/competition/upsert.js | richardschneider/club-server | 97bb3430ae29916a3254f6ddb1b010021468e355 | [
"MIT"
] | null | null | null | import { Competition } from '../../data/connectors';
function update (id, input) {
return Competition
.findOrBuild({where: { id: id}})
.then(result => {
let competition = result[0] /*, wasCreated = result[1] */;
Object.assign(competition, input);
return competition.save();
})
;
}
export default update;
| 22.666667 | 64 | 0.614706 |
b9fd4a42c63470877475cd4b745f8525f9129eaf | 2,886 | js | JavaScript | src/actions/index.js | rares985/rmt-web | 150e0a31b5cf5c33c2b28a88a418c670a1a33460 | [
"MIT"
] | null | null | null | src/actions/index.js | rares985/rmt-web | 150e0a31b5cf5c33c2b28a88a418c670a1a33460 | [
"MIT"
] | null | null | null | src/actions/index.js | rares985/rmt-web | 150e0a31b5cf5c33c2b28a88a418c670a1a33460 | [
"MIT"
] | null | null | null | import axios from 'axios';
import {
LOGIN_USER_BEGIN,
LOGIN_USER_SUCCESS,
LOGIN_USER_FAILURE,
FETCH_NEWS_BEGIN,
FETCH_NEWS_SUCCESS,
FETCH_NEWS_FAILURE,
FETCH_REFEREES_BEGIN,
FETCH_REFEREES_SUCCESS,
FETCH_REFEREES_FAILURE,
FETCH_MATCHES_BEGIN,
FETCH_MATCHES_SUCCESS,
FETCH_MATCHES_FAILURE,
} from '../constants/action-types';
const LoginUserBegin = () => ({
type: LOGIN_USER_BEGIN,
});
const LoginUserSuccess = () => ({
type: LOGIN_USER_SUCCESS,
});
const LoginUserFailure = (error) => ({
type: LOGIN_USER_FAILURE,
payload: {
error,
},
});
export const LoginUser = (request) => {
const url = 'localhost:3001/api/login';
return (dispatch) => {
dispatch(LoginUserBegin());
axios
.get(url, request)
// eslint-disable-next-line no-unused-vars
.then((res) => {
dispatch(LoginUserSuccess());
})
.catch((err) => {
dispatch(LoginUserFailure(err.error));
});
};
};
const FetchNewsBegin = () => ({
type: FETCH_NEWS_BEGIN,
});
const FetchNewsSuccess = (articles) => ({
type: FETCH_NEWS_SUCCESS,
payload: {
articles,
},
});
const FetchNewsFailure = (error) => ({
type: FETCH_NEWS_FAILURE,
payload: {
error,
},
});
export const FetchNews = (request) => {
const url = 'localhost:3001/api/news';
return (dispatch) => {
dispatch(FetchNewsBegin());
axios
.get(url, request)
.then((res) => {
dispatch(FetchNewsSuccess(res.articles));
})
.catch((err) => {
dispatch(FetchNewsFailure(err.error));
});
};
};
const FetchRefereesBegin = () => ({
type: FETCH_REFEREES_BEGIN,
});
const FetchRefereesSuccess = (referees) => ({
type: FETCH_REFEREES_SUCCESS,
payload: {
referees,
},
});
const FetchRefereesFailure = (error) => ({
type: FETCH_REFEREES_FAILURE,
payload: {
error,
},
});
export const FetchReferees = (request) => {
const url = 'localhost:3001/api/referees';
return (dispatch) => {
dispatch(FetchRefereesBegin());
axios
.get(url, request)
.then((res) => {
dispatch(FetchRefereesSuccess(res.referees));
})
.catch((err) => {
dispatch(FetchRefereesFailure(err.error));
});
};
};
const FetchMatchesBegin = () => ({
type: FETCH_MATCHES_BEGIN,
});
const FetchMatchesSuccess = (matches) => ({
type: FETCH_MATCHES_SUCCESS,
payload: {
matches,
},
});
const FetchMatchesFailure = (error) => ({
type: FETCH_MATCHES_FAILURE,
payload: {
error,
},
});
export const FetchMatches = (request) => {
const url = 'localhost:3001/api/matches';
return (dispatch) => {
dispatch(FetchMatchesBegin());
axios
.get(url, request)
.then((res) => {
dispatch(FetchMatchesSuccess(res.matches));
})
.catch((err) => {
dispatch(FetchMatchesFailure(err.error));
});
};
};
| 19.632653 | 53 | 0.615731 |
b9fdced8e428b65d6adf29a5bc7c715153884a20 | 622 | js | JavaScript | interfaces/networking.js | brian-dlee/flow-interfaces-chrome | d7b494479a052b92acd63e570b56362fb8ef1596 | [
"MIT"
] | null | null | null | interfaces/networking.js | brian-dlee/flow-interfaces-chrome | d7b494479a052b92acd63e570b56362fb8ef1596 | [
"MIT"
] | null | null | null | interfaces/networking.js | brian-dlee/flow-interfaces-chrome | d7b494479a052b92acd63e570b56362fb8ef1596 | [
"MIT"
] | null | null | null | type chrome$NetworkInfo = {
BSSID?: string,
GUID?: string,
HexSSID?: string,
SSID?: string,
Security?: 'None' | 'WEB-PSK' | 'WPA-EAP' | 'WPA-PSK',
Type: 'WiFi'
};
type $networking$AuthResult = 'failed' | 'rejected' | 'succeeded' | 'unhandled';
type chrome$networking = {
config: {
finishAuthentication(GUID: string, result: $networking$AuthResult, callback?: () => void): void,
setNetworkFilter(networks: Array<chrome$NetworkInfo>, callback: () => void): void,
onCaptivePortalDetected: chrome$Event & {
addListener(callback: (networkInfo: chrome$NetworkInfo) => void): void
}
}
};
| 28.272727 | 100 | 0.655949 |
b9fdfea6cfe782162ddf7a6f47fcdde4489e08c5 | 1,215 | js | JavaScript | packages/fether-electron/src/main/app/methods/loadTray.js | openvapory/fether | 32a836b4630ea07b8d33679170ade5880b0304e7 | [
"BSD-3-Clause"
] | null | null | null | packages/fether-electron/src/main/app/methods/loadTray.js | openvapory/fether | 32a836b4630ea07b8d33679170ade5880b0304e7 | [
"BSD-3-Clause"
] | null | null | null | packages/fether-electron/src/main/app/methods/loadTray.js | openvapory/fether | 32a836b4630ea07b8d33679170ade5880b0304e7 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity.
//
// SPDX-License-Identifier: BSD-3-Clause
import Pino from '../utils/pino';
const pino = Pino();
function loadTray (fetherApp) {
const { app, onTrayClick, options, showTrayBalloon, tray } = fetherApp;
if (options.withTaskbar) {
fetherApp.emit('load-tray');
if (process.platform === 'darwin' && app.dock && !options.showDockIcon) {
app.dock.hide();
}
// Note: See https://github.com/RocketChat/Rocket.Chat.Electron/issues/44
if (process.platform === 'win32') {
showTrayBalloon(fetherApp);
}
tray.setContextMenu(fetherApp.contextTrayMenu.getMenu());
// Right-click event listener does not work on Windows
tray.on('right-click', () => {
pino.info('Detected right-click on tray icon');
tray.popUpContextMenu();
fetherApp.win.focus();
});
// Single click event listener works on Windows
tray.on('click', () => {
pino.info('Detected single click on tray icon');
onTrayClick(fetherApp);
fetherApp.win.focus();
});
tray.setToolTip(options.tooltip);
tray.setHighlightMode('never');
}
}
export default loadTray;
| 25.3125 | 77 | 0.650206 |
b9fe1f39d84a86f625dd35d571ca18e9cdf5fab9 | 400 | js | JavaScript | packages/material-ui-icons/src/RemoveDone.js | silver-snoopy/material-ui | 917a3ddb8c72651fdbd4d35b1cd48ce9a06f8139 | [
"MIT"
] | 8 | 2021-03-18T08:41:32.000Z | 2021-04-19T10:24:50.000Z | packages/material-ui-icons/src/RemoveDone.js | Hypermona/material-ui | 9ff8d1627016ee2eb3bded3dd55bccebe8f3a306 | [
"MIT"
] | 129 | 2021-05-05T15:07:04.000Z | 2022-03-27T02:51:27.000Z | packages/material-ui-icons/src/RemoveDone.js | danncortes/material-ui | 1eea9427971f716bd7fd17401d918841a9bd749e | [
"MIT"
] | 1 | 2021-04-18T16:53:17.000Z | 2021-04-18T16:53:17.000Z | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M1.79 12l5.58 5.59L5.96 19 .37 13.41 1.79 12zm.45-7.78L12.9 14.89l-1.28 1.28L7.44 12l-1.41 1.41L11.62 19l2.69-2.69 4.89 4.89 1.41-1.41L3.65 2.81 2.24 4.22zm14.9 9.27L23.62 7 22.2 5.59l-6.48 6.48 1.42 1.42zM17.96 7l-1.41-1.41-3.65 3.66 1.41 1.41L17.96 7z" />
, 'RemoveDone');
| 57.142857 | 268 | 0.685 |
b9fe2a4853e8dbd9d2e0a91a9f155d2d63236877 | 229 | js | JavaScript | app/web/layout/standard/index.js | daoos/page-open-source | 437678e233d9950a1fbd616c7f40794bcbed9512 | [
"MIT"
] | 1 | 2021-05-17T06:50:07.000Z | 2021-05-17T06:50:07.000Z | app/web/layout/standard/index.js | daoos/page-open-source | 437678e233d9950a1fbd616c7f40794bcbed9512 | [
"MIT"
] | null | null | null | app/web/layout/standard/index.js | daoos/page-open-source | 437678e233d9950a1fbd616c7f40794bcbed9512 | [
"MIT"
] | null | null | null | import MainLayout from './main';
const content = '<div id="app"><MainLayout><div slot="main"><slot></slot></div></MainLayout></div>';
export default {
name: 'Layout',
components: {
MainLayout
},
template: content
};
| 20.818182 | 100 | 0.641921 |
b9fe6a27b3a12e4dc20fad359219d73f423c96b2 | 1,250 | js | JavaScript | src/app/components/Button.js | DmitryKorlas/js-test-recorder | 65201ac183ba13d03fb07226f2700e4aaa3acb19 | [
"MIT"
] | 1 | 2016-12-19T10:38:27.000Z | 2016-12-19T10:38:27.000Z | src/app/components/Button.js | DmitryKorlas/js-test-recorder | 65201ac183ba13d03fb07226f2700e4aaa3acb19 | [
"MIT"
] | 6 | 2017-02-09T16:10:03.000Z | 2017-02-11T17:41:50.000Z | src/app/components/Button.js | DmitryKorlas/js-test-recorder | 65201ac183ba13d03fb07226f2700e4aaa3acb19 | [
"MIT"
] | null | null | null | import React from 'react';
import Ink from 'react-ink';
import classnames from 'classnames';
import style from './Button.pcss';
export class Button extends React.Component {
static propTypes = {
flat: React.PropTypes.bool, // opt
floating: React.PropTypes.bool, // opt
disabled: React.PropTypes.bool, // opt
primary: React.PropTypes.bool, // opt
iconOnly: React.PropTypes.bool // opt
};
static defaultProps = {
flat: false,
floating: false,
disabled: false,
iconOnly: false,
primary: false
};
render() {
let {flat, disabled, floating, iconOnly, className, primary, ...props} = this.props;
let classes = classnames('btn', 'waves-effect', 'waves-light', className, {
'btn-flat': flat,
'btn-floating': floating,
'blue-text': primary,
disabled: disabled,
[style['icon-only']]: iconOnly
});
let rippleStyles = iconOnly ? {color:'#1e1e1e'} : null;
return (
<button className={classes} {...props}>
{this.props.children}
<Ink background={false} style={rippleStyles}/>
</button>
);
}
}
| 29.069767 | 92 | 0.5584 |
b9fe83a5dd4411d84d0c1dfcd93034c2de3ee031 | 46,672 | js | JavaScript | test/solution/447.js | flowmemo/leetcode-in-js | 495483fd1565599d8830d40e6a03228e890eb296 | [
"WTFPL"
] | 1 | 2017-03-04T04:12:39.000Z | 2017-03-04T04:12:39.000Z | test/solution/447.js | flowmemo/leetcode-in-js | 495483fd1565599d8830d40e6a03228e890eb296 | [
"WTFPL"
] | null | null | null | test/solution/447.js | flowmemo/leetcode-in-js | 495483fd1565599d8830d40e6a03228e890eb296 | [
"WTFPL"
] | null | null | null | // 447. Number of Boomerangs
const data = [
{
input: [[[0, 0], [1, 0], [2, 0]]],
ans: 2
},
{
input: [[[7822, -3128], [8230, -7843], [4481, -8255], [3566, -847], [592, -3459], [7070, 5458], [9838, 6585], [6216, 1424], [8539, 1192], [1083, -7828], [7177, 6872], [9832, -6962], [6242, -7194], [5482, -5909], [8586, -7950], [2918, -3591], [8922, -8852], [4918, -245], [9245, -1516], [8908, 6189], [1378, -4021], [1647, 1216], [2564, 4215], [8993, -2545], [5407, 76], [5979, 2585], [3301, 5811], [1975, 5895], [4969, 3810], [9986, -6444], [2212, 9257], [6317, 7486], [6757, 1235], [7241, 6003], [6072, -3851], [2192, -2550], [8480, -6160], [5018, -2603], [8055, 4011], [1204, 9815], [440, 7184], [2400, -9907], [9347, -9273], [5988, -5683], [4537, 5974], [7873, -6899], [1583, 4190], [587, -1659], [1777, -2172], [696, 4201], [330, 2888], [8003, 8810], [3080, 3022], [2559, 1136], [3385, 3764], [7303, -9823], [7300, 6055], [270, 6647], [6782, 6258], [964, -2328], [8585, -1163], [773, -9832], [9379, 1361], [4861, 7509], [9189, -4443], [1710, -481], [8446, -3934], [4682, -2122], [9088, -2759], [5366, 8825], [7357, -7331], [9003, -5343], [8724, 5625], [1305, 5507], [1884, -7731], [9531, -9531], [7459, 304], [6989, -6810], [1665, -8149], [7051, 7207], [7408, -1238], [3078, -7794], [4828, -2240], [85, 268], [1354, -4549], [5445, -1289], [8121, -9200], [3369, -3155], [6426, 1026], [8704, -5338], [3295, 8235], [5131, 7106], [8540, -7880], [6649, -3443], [323, 3700], [116, -2268], [8814, -6805], [6290, 3642], [7307, 6375], [262, 5013], [8179, -7940], [77, -3700], [2860, 3446], [9497, 5638], [824, -5446], [300, 471], [2789, -4569], [7578, -2319], [3904, -9421], [591, -5773], [4279, 707], [8311, 3094], [254, 4602], [3088, 3914], [7329, 9703], [5279, -4492], [1763, -4644], [8160, -9025], [5154, 4010], [6614, 5978], [8564, 6914], [6450, -8647], [8698, 380], [5387, 8954], [959, 5978], [9533, -4762], [3037, -2155], [4684, -356], [8799, 7773], [3558, -3872], [3828, -1163], [7989, 5591], [546, 6149], [2918, -4300], [159, -468], [1679, -1277], [2799, -1871], [6429, -8503], [8509, 1816], [6803, -4180], [4146, 6336], [1058, -2817], [533, -7905], [6827, 9332], [6220, 6737], [1813, 48], [1927, -198], [1991, 2473], [2303, 4909], [4525, 2463], [4442, 6204], [7538, -6407], [685, -9681], [1442, 5546], [8487, 8245], [1366, 2633], [4581, -1223], [6169, 5115], [872, -652], [799, -2908], [2438, 2612], [7140, -5635], [2414, 9131], [3190, -8930], [392, -2285], [3533, 1186], [272, -2577], [4779, -9043], [4095, 6221], [6504, 2582], [818, 4222], [1568, -8248], [2999, 4089], [3219, 3871], [9789, -5982], [7315, -7773], [2983, 4455], [2944, 1749], [9938, 6134], [2819, 6683], [202, -7296], [7869, -9526], [128, -7351], [7783, 4223], [5222, 639], [3157, -7607], [4862, -5275], [4145, -5787], [5166, 7364], [4437, 4956], [7734, 1752], [7183, 717], [2560, 6480], [2467, -1150], [8966, 5286], [5533, -832], [7991, 3403], [5994, -5529], [2404, -6222], [5046, -6022], [4417, 4555], [6371, 9279], [5633, -3132], [3493, 799], [584, 4282], [5755, 8319], [6034, 9291], [5388, -1406], [5771, -5793], [3797, -8911], [9494, 9330], [258, 3837], [9085, 2604], [4660, -8511], [6382, -3942], [1820, 800], [613, -1809], [6431, 6246], [1412, -3724], [7046, 1996], [558, -847], [6667, -7055], [8444, 2056], [7891, -9433], [6263, -8312], [8009, 2109], [1019, -5381], [2298, -3544], [7223, 6958], [4298, 3606], [3016, -3882], [758, 9982], [661, -6459], [6228, -7927], [9818, 9626], [4070, -3272], [8780, -9263], [9673, 3576], [9145, 7565], [496, -4591], [9253, -1495], [3870, 6624], [3124, 6169], [9433, 347], [3127, -6269], [305, 2496], [9849, -8937], [2478, -9490], [957, -4942], [8936, 775], [4685, -642], [7503, 3465], [6447, -6471], [7041, 5593], [1094, 7537], [7354, 6699], [2394, 1224], [9676, 5518], [3745, -891], [2218, 3225], [9192, -7477], [5721, 9041], [9939, 4551], [5903, -9104], [9609, 1191], [8023, -5706], [549, -8122], [4111, -3003], [1759, -8847], [2590, -7147], [5042, 6296], [5905, 3789], [3872, -8067], [9307, -2382], [7394, -2123], [843, 6586], [6753, -7084], [1979, -3308], [7467, -2118], [3940, 3428], [9074, -1685], [7723, 5975], [6545, 1834], [2972, -1695], [9339, -8086], [7510, -9266], [8210, -6585], [4523, 8435], [1700, -9818], [6053, -906], [8060, -3104], [2032, 4813], [9812, 4011], [7857, -6369], [1894, 8149], [7059, 7320], [2816, 1134], [3295, -639], [9321, 2620], [7666, -4988], [886, -4823], [5746, -4551], [4944, 6621], [3884, -3355], [3156, -63], [2091, -8784], [3185, 4124], [2381, 9349], [4487, -3410], [2980, -3619], [1091, 6391], [53, -6093], [7526, -299], [3268, -3153], [8673, -2713], [8211, -441], [2464, 310], [5008, 3760], [6931, 5244], [6757, -9913], [1533, -1151], [7655, 4718], [9325, -3612], [4067, -6188], [2978, 3399], [6546, 4069], [9791, -7049], [4328, 3669], [9004, -2403], [6868, -2323], [4884, -4921], [3589, -6300], [5389, -5051], [7460, 8673], [194, 4218], [5112, -8273], [9419, -880], [6446, 5096], [5508, -3135], [5260, -5161], [6617, -8194], [5260, -3592], [1110, -411], [6429, 114], [3538, 3297], [7792, -5226], [4728, 1381], [8474, 118], [6330, -7714], [5143, 2876], [2856, -9745], [4604, -1373], [5727, -2598], [75, -8764], [619, 5336], [2427, -2764], [3494, 7687], [3644, 4604], [7276, 73], [4719, 7166], [9722, 8863], [1940, 4451], [6596, -3234], [921, 9278], [5405, -3936], [2155, 8261], [2671, -6889], [3241, -1601], [513, -6684], [5987, -8868], [5004, -1586], [4721, -1501], [6101, 8365], [9455, -270], [4791, -9474], [6896, -9135], [9389, -1163], [5316, -7663], [5603, 2589], [1616, -8992], [5005, 123], [5622, 7677], [9586, 5215], [2428, 6451], [4883, -1585], [7583, -112], [6829, 8656], [4739, 9282], [7022, 4194], [9012, 8165], [4721, 5909], [5382, 462], [4746, -2949], [2800, 6701], [9640, 768], [4062, 4646], [7243, -3964], [8675, -3171], [7603, 1103], [3280, 2486], [9518, 7215], [8726, 2699], [5872, 3465], [1981, -754], [7660, -9006], [3763, -7619], [3255, 9145], [2843, 4353], [6196, -8005], [1054, -7811], [2763, -8532], [6835, -3642], [3856, -4490], [3187, -8541], [2965, 6467], [3946, 2483], [3683, 2672], [1534, -4093], [6138, 3515], [5153, 150], [4509, 8916], [8883, -2236], [8061, 8078], [8469, -9390], [74, -476], [2799, -811], [7344, 9634], [5548, 1201], [1496, -1265], [2660, 4461], [1555, -7042], [3296, 1590], [5631, -5170], [7497, 8121], [4697, 2650], [4623, -4441], [7918, 3506], [9675, -7669], [1584, -1855], [2941, -1990], [7669, -4260], [7200, -8635], [1726, -900], [2566, 9574], [7835, -4773], [387, 5742], [4537, 3683], [7332, -9832], [4865, -5171], [4641, -437], [3831, 9264], [5122, -8251], [2770, -8851], [4081, -9293], [9294, -2978], [8717, -6685], [9115, -4083], [4681, -2807], [5017, 7247], [6768, -795], [8826, 7155], [4947, -6636], [7191, -1368], [9884, -7944], [3461, 878], [7971, -6355], [142, 9445], [5394, 9265], [595, -4173], [9972, -111], [9202, -1311], [3205, 8317], [959, 7886], [5510, -7672], [1485, -1370], [7885, -3336], [5786, -815], [6380, 2977], [7817, -3736], [1385, -2370], [7142, 5709], [1275, -6363], [5154, 3022], [2902, 2101], [8849, 9226], [1991, -1949], [4267, 1548], [2720, 5226], [5786, -5417], [3907, 7271], [3213, -8208], [287, 5351], [7329, -3333], [4680, -4854], [2932, 6066], [2777, -3574], [8127, -9596], [63, -6719], [3426, -683], [1735, -1372]]],
ans: 4
},
{
input: [[[489, 238], [323, 460], [853, 965], [327, 426], [264, 871], [580, 947], [362, 275], [241, 772], [967, 240], [68, 847], [825, 703], [922, 898], [769, 217], [23, 160], [472, 802], [755, 313], [40, 78], [125, 246], [396, 452], [672, 660], [323, 253], [607, 37], [880, 201], [161, 847], [441, 229], [46, 266], [284, 320], [516, 53], [889, 539], [565, 713], [341, 320], [26, 381], [751, 504], [979, 147], [956, 652], [807, 632], [257, 767], [669, 489], [968, 831], [336, 409], [60, 734], [27, 697], [54, 543], [750, 944], [82, 668], [657, 423], [988, 36], [156, 91], [540, 136], [238, 496], [140, 398], [128, 397], [165, 150], [238, 133], [981, 926], [894, 393], [660, 921], [90, 66], [464, 193], [10, 898], [861, 20], [321, 201], [408, 829], [293, 948], [965, 531], [796, 457], [929, 277], [206, 446], [427, 444], [931, 760], [370, 825], [153, 30], [98, 244], [449, 914], [789, 811], [812, 650], [831, 485], [203, 239], [315, 496], [539, 632], [380, 336], [442, 661], [613, 648], [108, 392], [93, 391], [152, 815], [217, 305], [198, 667], [901, 647], [934, 690], [458, 746], [692, 642], [584, 896], [233, 251], [744, 773], [235, 124], [109, 677], [786, 74], [326, 246], [466, 771], [989, 618], [586, 558], [923, 136], [226, 177], [783, 160], [867, 594], [258, 912], [236, 842], [808, 469], [445, 552], [242, 681], [29, 703], [358, 167], [777, 36], [765, 595], [807, 754], [213, 746], [313, 489], [882, 539], [666, 18], [51, 885], [612, 309], [149, 200], [504, 957], [669, 949], [862, 264], [630, 891], [319, 341], [410, 449], [377, 175], [44, 537], [929, 610], [635, 242], [99, 869], [133, 117], [887, 184], [354, 851], [846, 504], [51, 350], [813, 73], [651, 675], [337, 634], [918, 656], [975, 328], [105, 704], [503, 502], [241, 785], [112, 876], [27, 211], [98, 513], [680, 985], [697, 386], [189, 895], [890, 240], [245, 56], [313, 897], [83, 2], [531, 2], [659, 858], [682, 116], [562, 538], [618, 804], [323, 730], [32, 702], [293, 482], [215, 325], [468, 265], [64, 657], [160, 306], [249, 406], [362, 915], [655, 446], [917, 538], [800, 576], [396, 482], [45, 310], [20, 15], [466, 343], [98, 851], [46, 743], [333, 261], [421, 801], [878, 485], [810, 39], [791, 412], [797, 154], [327, 452], [600, 244], [342, 400], [173, 90], [234, 570], [400, 255], [585, 867], [950, 683], [718, 996], [779, 51], [610, 200], [205, 488], [685, 367], [879, 476], [779, 676], [982, 458], [128, 934], [703, 822], [686, 228], [912, 921], [798, 313], [176, 735], [180, 478], [771, 898], [475, 550], [301, 437], [750, 506], [277, 787], [226, 157], [615, 5], [833, 598], [816, 314], [532, 519], [136, 219], [99, 49], [492, 249], [362, 20], [984, 894], [498, 755], [144, 325], [657, 445], [762, 407], [304, 392], [546, 530], [549, 162], [887, 734], [760, 703], [48, 644], [574, 537], [215, 673], [938, 707], [922, 652], [727, 259], [546, 226], [14, 42], [551, 24], [487, 666], [783, 143], [58, 330], [673, 959], [492, 913], [693, 604], [616, 94], [248, 191], [631, 816], [216, 569], [523, 491], [573, 603], [750, 119], [181, 116], [513, 84], [140, 0], [750, 924], [496, 160], [254, 521], [119, 98], [434, 165], [702, 51], [259, 302], [594, 242], [118, 810], [163, 994], [653, 736], [597, 403], [207, 778], [520, 720], [862, 12], [72, 965], [936, 568], [125, 542], [442, 597], [640, 876], [762, 694], [279, 373], [997, 225], [967, 467], [388, 130], [461, 41], [218, 410], [445, 425], [540, 317], [497, 403], [329, 569], [720, 266], [490, 197], [808, 932], [146, 801], [160, 260], [495, 440], [633, 844], [17, 600], [312, 405], [82, 125], [447, 300], [536, 244], [77, 76], [561, 574], [831, 890], [144, 903], [508, 986], [101, 669], [918, 599], [470, 78], [860, 965], [870, 845], [810, 888], [446, 122], [645, 880], [599, 92], [181, 487], [688, 610], [916, 249], [185, 747], [492, 681], [3, 352], [667, 456], [21, 937], [55, 491], [15, 915], [457, 238], [761, 267], [478, 559], [741, 123], [439, 692], [568, 972], [180, 256], [935, 96], [858, 120], [195, 702], [801, 198], [54, 820], [654, 76], [757, 62], [567, 772], [977, 376], [362, 90], [995, 840], [1, 88], [316, 793], [781, 884], [765, 961], [492, 700], [57, 702], [172, 604], [404, 325], [803, 459], [145, 809], [887, 902], [871, 454], [27, 201], [183, 741], [643, 178], [582, 645], [267, 250], [438, 48], [134, 555], [361, 978], [608, 770], [681, 780], [374, 437], [106, 529], [896, 603], [339, 135], [858, 562], [590, 885], [115, 125], [626, 759], [303, 560], [404, 922], [810, 842], [970, 296], [397, 683], [627, 5], [453, 308], [138, 828], [745, 596], [709, 994], [199, 48], [129, 57], [963, 71], [294, 78], [196, 273], [189, 852], [833, 593], [774, 996], [787, 97], [644, 537], [780, 271], [894, 234], [579, 32], [414, 677], [628, 123], [23, 180], [524, 504], [589, 487], [576, 884], [917, 124], [157, 107], [976, 342], [52, 103], [690, 840], [200, 335], [377, 980], [606, 271], [566, 538], [656, 980], [567, 636], [456, 590], [168, 980], [94, 758], [819, 22], [994, 88], [147, 503], [195, 475], [197, 600], [578, 888], [792, 130], [223, 169], [463, 181], [792, 29], [719, 800], [10, 286], [789, 466], [228, 957], [798, 323], [715, 617], [697, 61], [705, 196], [564, 253], [672, 762], [205, 602], [650, 997], [85, 225], [518, 548], [406, 662], [577, 478], [463, 939], [116, 252], [757, 345], [561, 555], [20, 277], [524, 717], [690, 582], [914, 255], [187, 938], [17, 392], [892, 19], [741, 977], [596, 259], [525, 2], [273, 455], [832, 736], [394, 949], [340, 504], [294, 902], [59, 314], [531, 936], [383, 221], [870, 297], [828, 57], [587, 197], [801, 480], [568, 894], [457, 164], [153, 335], [519, 426], [790, 351], [515, 536], [652, 207], [40, 946], [461, 452], [612, 344], [388, 996], [918, 610], [645, 746], [19, 233], [296, 820], [65, 864], [66, 522], [29, 219], [209, 548], [997, 351], [251, 864], [888, 904], [72, 928], [202, 885], [732, 815], [230, 472], [163, 148], [82, 160], [246, 101], [745, 542], [273, 810], [407, 339]]],
ans: 1000
},
{
input: [[[3327, -549], [9196, -8118], [7610, -9506], [5098, 8392], [8582, 7953], [1053, 5802], [3847, 2652], [7654, 8355], [1614, -9409], [9986, 5538], [4660, 2944], [4528, -9512], [7483, -1455], [3422, -3966], [2037, -4456], [5107, -4635], [4996, 655], [7247, 2606], [1149, 8697], [7350, 6083], [3002, 8403], [8238, 6850], [1055, 5892], [5205, 9021], [2835, 5191], [911, -2505], [4488, -4561], [7983, -1677], [336, -2243], [4358, -1274], [3302, 9465], [4091, -5350], [120, 7690], [3608, 7622], [6388, -9042], [57, -610], [9361, 8295], [6240, -3232], [540, 7797], [2141, -6625], [9341, 3053], [7223, 3829], [4844, 1558], [2152, -8467], [9316, 6510], [259, -1030], [2327, -5650], [9972, 8800], [2040, -6420], [2774, 4780], [4538, -7169], [4171, -6101], [7479, -3237], [7019, -1981], [4561, -4488], [7746, 254], [4917, 4969], [4083, -238], [6528, -7413], [1295, -7804], [5450, -8446], [1166, -5871], [2256, -8862], [2929, -5704], [4718, 2055], [5429, -4392], [4887, 9600], [9507, -1282], [2715, 2878], [6737, -6372], [8390, -9165], [3882, 3308], [5805, 4317], [9422, 8685], [3257, -2931], [881, -1293], [8623, -1601], [2836, 879], [5889, 2118], [1527, 607], [4173, -3044], [6215, 5412], [2908, -7926], [4130, -8024], [1304, 7219], [1956, -3954], [8055, 5839], [5706, 212], [6508, 5128], [8897, 9765], [2197, -3870], [8472, -2828], [4529, 7661], [4403, -9582], [6131, -7717], [7377, -3344], [5591, 9944], [2069, -5148], [8370, -7449], [6828, -3974], [6123, -1216], [2072, 530], [975, -2221], [7094, -2516], [9259, -4009], [7249, 7809], [8473, 2074], [4981, -6998], [9735, 5737], [9772, 5866], [8020, -6499], [8874, -6389], [3445, -9057], [4815, 8167], [9847, 1643], [4193, 2322], [6780, 2617], [9204, 4107], [396, 6298], [1591, 6008], [2289, -4807], [3817, 762], [7267, 5150], [116, -6646], [887, -3760], [5572, -4741], [9741, 4446], [5223, -462], [1742, 38], [7705, 1589], [1682, -1750], [263, 4814], [867, 9467], [8921, 7616], [5765, -3135], [3624, 4406], [2058, -2559], [1520, -675], [2591, -2012], [2679, -169], [4228, -1749], [5090, -6031], [2697, -9687], [9859, 791], [352, 3916], [8732, -1614], [2166, 8995], [3200, 9385], [4814, -1527], [7001, 579], [5338, -3023], [1337, -2604], [4418, -7143], [3073, 3362], [845, -7896], [3193, -8575], [6707, 4635], [1746, -595], [4949, 1605], [6548, -8347], [1873, 5281], [39, -5961], [4276, -409], [9777, -909], [8064, 3130], [6022, -245], [108, 7360], [7151, 4526], [6569, -3423], [4240, -2585], [8681, -2567], [5192, 5389], [2069, -3061], [1146, 3370], [4896, 7694], [5023, 6770], [2975, -8586], [7161, -6396], [1005, 6938], [2695, -4579], [69, -4931], [5176, 177], [2429, -1320], [1055, 8999], [5257, -4704], [2766, -6062], [9081, -2042], [5679, -2498], [1249, 6825], [7224, -3854], [872, 2247], [2916, -6153], [3661, -9923], [7451, -8982], [7016, 6498], [6440, -6563], [1568, -8384], [9966, -9651], [296, 1021], [9348, -8095], [2669, 8466], [2196, -8249], [2777, 7875], [5605, 4026], [1053, -7170], [172, -8075], [1429, -6912], [5772, -8557], [9518, -424], [2461, 2886], [2426, -1099], [6323, -6006], [6870, -3711], [696, 3518], [3662, 6396], [5424, -3668], [4863, 7620], [4435, 7640], [1847, -3608], [8018, -7100], [9222, -5457], [4825, 7004], [3983, -3050], [8447, -6499], [2878, -9092], [6387, 5304], [6162, -938], [5651, 3032], [5351, 6347], [2902, -4634], [2743, 8326], [8050, -6042], [2298, -1163], [7950, -9502], [5229, -4031], [3398, -9196], [512, -5424], [7808, 847], [7878, 6255], [4349, 7108], [7163, 736], [8764, 9677], [6151, -5585], [2709, -2146], [7114, 5612], [3220, -3790], [290, -8730], [168, 8941], [107, -5529], [9439, -8311], [440, 9189], [2493, 7304], [117, 6653], [8151, -5653], [2908, 8852], [1455, -3577], [5941, -3428], [6101, -7908], [7339, 5162], [9946, -5546], [7126, 9519], [7016, 3769], [789, 7184], [2710, -2751], [1655, -1499], [5290, -1553], [4042, -2217], [2103, -9488], [788, -3393], [1211, 3696], [1811, 9019], [6471, -2248], [5591, 8924], [6196, 2930], [4087, 6143], [3736, 7565], [5662, -9248], [1334, 2803], [4289, -9604], [6404, 2296], [8897, -8306], [7096, -708], [5829, 9199], [6156, -3383], [2158, -2633], [6665, -9678], [6386, 3137], [8074, 1977], [2061, 4271], [4908, -7500], [6766, 4996], [66, 8780], [5749, 1400], [7935, 38], [1797, -5660], [2334, 7046], [2386, 9430], [2690, -1784], [4982, -1154], [1185, 3492], [6214, -2149], [3814, 8952], [7340, 8241], [930, -4247], [8864, 2190], [8254, 5630], [7186, -5328], [762, 9287], [6072, 8697], [9325, -5779], [9389, 1660], [7620, -8224], [7442, -9690], [9992, -7576], [5509, 7529], [2269, 8075], [5380, -3917], [7027, -7280], [4324, -5691], [8474, 3188], [6499, 3080], [5170, -9962], [7752, 5932], [9325, 176], [982, -1349], [4398, 371], [6663, -1630], [2147, -9543], [5032, 8491], [9234, 541], [6021, 1503], [8616, 7753], [3938, -8004], [6826, 8263], [6305, -8348], [7803, 9157], [4732, -674], [9195, -1164], [5258, 8520], [9012, 2592], [3523, -238], [2964, 6538], [8132, 1463], [3348, -6835], [6307, 2582], [58, -7672], [437, 5027], [6433, 4375], [7023, 3259], [8990, -6672], [4911, 3146], [2485, -4005], [2472, 8032], [4831, -5918], [2905, 196], [6675, 6428], [9958, 9639], [9319, 4443], [7454, -7333], [3960, 3761], [1601, -9630], [2441, 2038], [5397, -1125], [6413, 2420], [8486, 1756], [2101, 3398], [4902, 938], [5745, -2626], [5323, -3071], [1456, 8228], [7125, -1869], [1008, 3435], [4122, 6679], [4230, 1577], [9346, 8190], [1690, 947], [4913, 4132], [9337, 310], [3007, -4249], [9083, -8507], [7507, -2464], [1243, -7591], [4826, -3011], [6135, -9851], [3918, 7591], [8377, -2605], [5723, -4262], [830, -3803], [2417, -8587], [7774, 8116], [5955, 9465], [5415, 868], [9949, -5247], [1179, 2956], [6856, 6614], [801, -9285], [4150, 8397], [9476, 8976], [1738, -4389], [9126, 2008], [3202, 3855], [9403, -4723], [9593, 6585], [1475, -7989], [7998, -4399], [127, 306], [1418, -4458], [1174, 1367], [6647, -7647], [4323, 3503], [8967, 1477], [4218, 9469], [6226, 3694], [8446, -2036], [9305, 3924], [9972, 8860], [7779, 5727], [4137, -6275], [8664, 1964], [5736, -6985], [7566, -7785], [3321, 8984], [4109, 4495], [352, 757], [3201, 1027], [4260, -1480], [8856, 4831], [7990, -4918], [8525, -7212], [3046, -5817], [6712, -630], [3043, -5509], [1449, -6468], [8216, -3534], [5497, 304], [9481, 3063], [8871, 9154], [8399, 2981], [1, 8751], [90, -6798], [6131, -9298], [8075, -5013], [5533, 6065], [70, -9589], [5205, 9468], [946, 1917], [5191, -6011], [2760, -7008], [3873, 7329], [9458, 9370], [7633, 5291], [8785, 2857], [797, 3537], [2190, -9201], [2288, -7720], [353, 4771], [9334, -1572], [9759, 1220], [845, -3819], [7983, 6050], [2001, -1071], [4319, -2808], [9270, 7080], [6537, 3143], [4409, 2347], [8866, 8394], [7639, 4003], [7603, 4788], [7540, -207], [5587, 6181], [8425, 5941], [952, -5888], [721, -2937], [5332, -8433], [3244, -6685], [3969, 5246], [2244, 8289], [8790, -8486], [1721, -4673], [1009, -3870], [7675, 9875], [876, -8334], [231, -1520], [6454, 7771], [4625, 2042], [304, 9403], [4335, -8743], [3515, -4944], [4672, 8847], [2975, 7917], [8514, 6945], [3163, 758], [1586, 1953], [8624, -6693], [7281, 9633], [5789, 1308], [5861, -6983], [2974, -3908], [7849, -572], [215, -7525]]],
ans: 6
},
{
input: [[[8543, 78], [3031, 2811], [1626, 2104], [4389, -2588], [6687, 8296], [1035, -3748], [6441, 7675], [1604, -6230], [4342, -3716], [8917, 7274], [8702, 8046], [53, -3171], [8450, 116], [6463, -1771], [5786, 8198], [6857, -5671], [8276, -112], [7140, -3746], [1992, -8470], [18, 5031], [6178, -2595], [1284, 2619], [5080, 9240], [2742, -577], [1876, -8341], [3049, 6931], [6057, -6898], [3760, 859], [9571, -3425], [9088, -4643], [4773, 5945], [6038, -599], [2186, 9531], [5655, -9470], [7413, -4327], [5562, 3591], [3079, 3198], [2563, 8159], [8790, 5305], [7582, 666], [3316, -3016], [7597, -627], [86, -2290], [6584, 6009], [4285, 5673], [7718, 5411], [7970, -6243], [4812, -3492], [3288, -9532], [7039, -9299], [2493, 8953], [644, 1924], [2151, -441], [84, 7293], [4864, 4018], [7959, 4532], [1002, 1909], [257, -2559], [9619, 6842], [9802, 256], [2515, 7521], [5667, 6837], [7630, -3168], [3346, -9082], [3652, 385], [7971, -3855], [5690, -5033], [8070, 7841], [4527, -5494], [1486, 5743], [4876, 9445], [276, 5879], [7706, -3115], [9672, -6323], [3727, 9474], [286, 2594], [3347, 5953], [9432, 977], [9137, -870], [8247, -7211], [9515, -7430], [5287, -4795], [7538, 9709], [9398, 8417], [4215, 884], [512, 9091], [6681, 7140], [1322, 740], [4026, -2654], [4417, -5895], [6821, -8945], [6700, -9832], [7009, -7516], [7498, 2498], [1614, 5745], [5288, -2519], [8316, 6927], [9038, -7794], [6636, -5212], [6975, 7203], [2024, -2513], [2646, 5057], [4628, -6031], [5797, -1346], [7667, 6567], [9111, 4488], [7622, -4189], [1009, 983], [4647, 8507], [3482, 2613], [604, 5122], [94, -1080], [8401, -4516], [7478, -4963], [272, -5547], [8592, -7704], [1941, 1238], [7354, 2921], [1559, -6849], [7927, 9227], [6070, -2962], [67, 3693], [9202, 7428], [1028, 3849], [5935, -5490], [2815, -7108], [5984, -7091], [8164, -5615], [4746, 5643], [5774, 5018], [6448, -5634], [7315, -5259], [1957, 1021], [7662, 9868], [524, 1941], [9095, -3405], [8980, -4485], [6640, -1818], [2943, 7668], [8383, 5231], [8531, -8802], [8123, 867], [460, -7361], [5253, -4794], [8282, -8973], [224, 4731], [1746, 3891], [5824, 3703], [1264, 3487], [9923, 1789], [5428, -4629], [4736, -9240], [886, 1376], [8942, 181], [5396, -6322], [1764, -9721], [4876, 6239], [1147, -4664], [8879, -7248], [6894, 7161], [131, -2881], [8244, -8123], [7362, -5931], [1932, 8627], [3908, -8144], [6768, 5688], [7227, -8496], [6449, 4465], [9232, -8257], [4646, 980], [1773, -3589], [1260, -3350], [2650, 8759], [8338, -8471], [1511, 5233], [5043, 7994], [8704, 9639], [6224, 2418], [60, -1844], [7397, 3968], [6364, 4165], [6009, -57], [5669, -7542], [760, -5099], [553, -8241], [2234, -7673], [4522, 9846], [5329, -6476], [8605, 19], [5054, 6468], [1604, 6449], [4462, 6660], [2440, 686], [9079, 2501], [5195, 6476], [6469, 7911], [642, -1170], [4207, -7337], [7640, -5033], [3917, -1806], [3078, 6151], [6873, -2400], [5997, 2202], [1125, 4602], [8573, 2531], [7422, -9822], [8980, 8236], [6838, -8580], [8923, -4083], [3921, -9530], [8746, 6743], [4733, -4260], [1925, 8940], [8403, -434], [260, 2320], [4112, -6662], [4823, -9015], [939, -9180], [9539, 8416], [1774, -1888], [947, 9196], [8290, 9927], [3785, -8519], [7699, 9060], [3750, -2027], [9530, -7504], [1068, 615], [8236, -7007], [9556, 2992], [8911, -3832], [1664, -6977], [5858, -3512], [4008, 3149], [7308, -101], [1565, 5435], [4364, -7488], [983, -7346], [8791, -5232], [487, 2843], [3828, -5762], [816, 9710], [6734, 8236], [326, 1323], [7581, 6234], [4315, -3507], [2402, -4021], [9516, -1740], [2467, -123], [7762, 6128], [9776, -673], [1563, 4140], [1840, 8898], [3147, 631], [3667, 3634], [3474, -2505], [4224, -9358], [3558, -9041], [5230, 3884], [8634, 2812], [118, 2949], [5657, -1128], [5280, -4827], [3484, -5900], [1402, 1246], [6580, -2469], [574, -5505], [8023, -1234], [3393, -2478], [9397, -2940], [1157, 9224], [908, 5381], [6218, 4466], [2692, 1449], [4702, -8674], [613, 1172], [627, 6270], [44, -7740], [7795, 3528], [6360, -4450], [1127, -7060], [3081, 8053], [3787, 1104], [6819, -2820], [8627, -7432], [593, 6136], [8144, 7853], [7869, 4363], [8671, 6914], [2164, 3373], [4592, 9129], [4545, -4780], [1751, -9059], [7480, -4102], [821, 192], [1448, 1948], [9484, -5471], [1, 3271], [1986, 3172], [6803, -3035], [5741, -2604], [9453, 3885], [5249, -6326], [4600, 272], [588, -3236], [3645, 5181], [5893, -5458], [6753, 3996], [5483, -9415], [9895, 2657], [777, 1343], [4605, -9739], [2225, 959], [9884, -9437], [4131, -3313], [7528, 6224], [436, -6667], [110, 2037], [7007, 4710], [2310, -2404], [7827, -7693], [9129, -9928], [3202, 2234], [4069, -4963], [2819, 3964], [7694, 9948], [5307, 8652], [6561, 7532], [9611, -3555], [8095, 94], [9484, -8025], [6319, 9920], [5308, 6429], [1958, -1332], [7491, 620], [6264, -4682], [2927, 1745], [5391, 6129], [3979, 5812], [1167, 3150], [9776, 8861], [3098, 5083], [3865, -341], [8968, -6524], [6104, -6585], [9923, -8060], [1743, 6242], [1861, -6597], [9023, 3819], [2071, 2866], [4439, -5313], [8185, 3718], [6432, 9928], [9848, 6763], [5740, -2633], [9913, -8132], [2580, 9363], [3303, 6446], [9022, -7729], [6274, -8522], [2039, -3803], [3419, -6218], [2439, -8368], [3537, -2186], [5451, 5609], [681, 6242], [296, 5218], [6312, 3081], [1498, 2512], [9844, -6410], [9879, 6110], [5458, 8812], [1825, 5113], [1610, -9152], [7385, -2116], [8678, 5776], [4082, 8449], [5910, 2873], [81, 9447], [7040, 1884], [5056, 4073], [4478, 5353], [9291, 791], [4786, 7141], [3303, 982], [731, 9535], [3444, -7459], [8347, 5270], [7654, -43], [2470, 1391], [4193, 1148], [3519, -1725], [9598, 9429], [7501, -321], [8877, 893], [7916, 285], [4966, -7606], [1990, 4257], [3185, -3224], [7750, 6489], [7759, -5167], [2376, -8797], [3726, 723], [6473, 7732], [7032, -1057], [9124, 1225], [6444, 2643], [5853, -7606], [8425, -294], [8425, -6346], [599, -3659], [3939, -4435], [8736, 5930], [6174, -8079], [9058, -6076], [4762, 3169], [5109, -2862], [4373, -1165], [4213, -2802], [6567, 1245], [2494, 2043], [8823, -4710], [4687, 1028], [7684, -536], [734, 6109], [3118, 7685], [2451, -2943], [9602, 1187], [9339, 5776], [9460, 8398], [6052, -5777], [7919, -8839], [1361, -7708], [6348, -4425], [5843, 2915], [3172, 4689], [4959, -1653], [9979, -4002], [9375, -5985], [5462, 6461], [124, -5068], [4146, 8927], [1989, 3748], [6466, -2319], [5876, 5927], [2431, 8280], [150, 350], [5793, -2137], [8995, -7859], [9790, 1190], [1409, 9315], [5879, 6368], [7662, -7790], [8718, -6610], [6225, 4180], [9851, -7299], [9112, 3998], [7981, -2547], [4098, -5553], [1486, -3673], [374, 3917], [4607, 6876], [620, -9599], [1092, -385], [8894, 882], [805, 303], [6549, -6964], [3023, 4212], [1598, -8259], [7602, -5825], [2273, 3805], [3228, -2263], [7803, -8791], [5191, -1746], [5657, -3323], [4581, -7617], [6947, 5540], [9260, 7567], [2293, -9648], [3534, -2460], [7586, -9309], [7843, 4136], [3727, -9133], [4700, -4675], [8960, 8654], [5852, 1234], [2459, -920], [8971, 6615], [290, 514], [1221, 2299], [3544, 2154], [4682, 491], [7694, 3942], [4410, 6340], [646, -2056], [3880, 4585], [8635, 8075], [5073, -1286], [8942, -227], [391, 4255], [8427, 6243]]],
ans: 8
},
{
input: [[[6685, 436], [910, -8106], [5336, 5260], [5246, 2939], [8124, -514], [6843, -9452], [5766, -3602], [1434, 499], [1213, -5984], [4971, 7728], [8164, -3594], [888, 5410], [5507, -8366], [8305, 5133], [6444, -5288], [3472, -519], [1500, -9265], [1376, 3188], [5995, 2974], [6127, 471], [2460, -677], [1020, 8226], [2073, -1194], [8725, 3286], [2822, -9951], [7366, -2662], [6455, -5394], [9100, -1686], [2592, 7405], [3447, -4611], [8469, -6728], [4870, -3679], [4007, -3754], [9509, 6354], [9220, -8011], [6825, 8032], [7664, 4197], [6259, 9737], [9355, -5016], [9375, -1471], [5033, 3093], [5867, -2160], [7699, 1320], [6155, -9708], [8725, 9602], [2033, -6453], [9226, 6903], [9868, -6767], [9502, -4270], [5939, 5074], [7719, 9117], [3107, 1735], [3314, -634], [1472, -978], [702, 7199], [7551, 2088], [292, -229], [9928, -2009], [1091, 2435], [4635, -3832], [2038, -3332], [9715, 1264], [3572, 5936], [850, 9426], [1666, -6859], [4500, -4263], [2258, -2393], [7472, 1925], [3325, -1056], [947, -5972], [6143, 4850], [6116, 6435], [4621, 2396], [778, -4288], [4832, -4586], [1881, 3222], [8434, 7948], [838, -1642], [3884, -1960], [7784, 1902], [1182, -7715], [7639, -208], [6244, 5111], [1717, 9570], [407, 9016], [3598, -7098], [3867, 6066], [5689, 4840], [4814, 6468], [553, -354], [8234, -1214], [9220, -3332], [3086, -9941], [5027, 3323], [4451, 9163], [5225, 5633], [1448, -7135], [5426, -2307], [7976, -6505], [7263, 8384], [8864, -2787], [7638, 2731], [3279, 3328], [7571, -5555], [9796, -5524], [444, -1970], [9614, -336], [1050, -947], [6075, -7571], [2376, 527], [1593, -6047], [2512, 9393], [6818, -5710], [7086, -8853], [7786, 701], [5883, -3350], [7914, 3521], [5733, 7545], [6849, 9656], [8343, 6645], [485, -1213], [1027, -3549], [8451, -1570], [5504, -9121], [7211, 4232], [7758, -1196], [8186, 270], [4550, -4996], [4561, 1636], [2503, 8699], [8690, 8386], [1701, 2956], [1908, 3786], [6854, 5109], [9794, -4803], [8107, 279], [3984, -4514], [3083, -1213], [3916, -5061], [6018, -8872], [9172, 3776], [6284, 7358], [4047, 834], [8714, 4960], [8823, 7570], [11, 3865], [5956, -1936], [6821, -5784], [8202, 27], [9326, -2004], [1576, -6215], [4628, -8088], [9271, -2289], [700, 9540], [9002, 3070], [7020, -1826], [6847, -6696], [1884, -2754], [491, 6951], [2206, -4334], [4521, -1431], [9531, -3171], [6633, -7296], [1046, 4835], [2732, -3276], [9183, -5692], [509, 3811], [6221, 6132], [7874, 3273], [5672, -3123], [6343, 2692], [1403, -458], [5997, 3288], [6788, -7160], [6591, 8994], [8506, -8888], [3915, -5611], [7941, -9452], [7093, 5339], [1735, 6177], [8415, 919], [486, -4724], [1082, -6941], [1409, 8957], [2684, 7081], [2186, 9027], [6126, 3589], [4922, 8475], [6877, -8290], [1315, 3468], [7057, -3827], [932, -9028], [562, 5226], [7873, 4007], [6917, -392], [185, -4667], [6879, -2977], [6961, 4314], [82, -1630], [3271, -7234], [1804, 1809], [8145, -2070], [5398, -6933], [6405, -1372], [4778, -5928], [8448, 8187], [245, -619], [9159, 7159], [959, 3384], [1166, -2124], [9345, -8649], [3209, 6224], [8374, -9829], [538, 8456], [4893, -9839], [7574, -6951], [1970, 2072], [979, 3721], [1491, 3736], [2349, 2621], [7808, -9203], [808, -5595], [6530, -32], [1564, -2511], [3352, 2731], [5366, -7303], [4082, -5073], [5274, 8809], [1450, -7836], [3617, -7304], [8678, 1192], [5745, -3000], [9616, 6725], [721, 1107], [6813, 9422], [3729, -9026], [220, 4537], [5379, -6898], [857, -6704], [592, -9438], [6027, -4042], [3259, -3539], [7237, 4885], [5270, -1312], [3402, 5240], [1384, 2080], [6432, 7129], [9080, -7600], [206, 6154], [3507, 3372], [5576, 7236], [4346, 2148], [1774, 6077], [5251, 2631], [9373, -7805], [3193, 5400], [4505, 2805], [8214, 1742], [4042, 9836], [6782, 7444], [5076, -5482], [9524, 7860], [8000, -5043], [260, -1794], [1111, 3768], [7930, 3039], [7356, 2276], [5188, 9130], [8354, 6791], [8114, -2273], [5338, 7659], [9480, 9843], [6816, 4046], [1585, 859], [3882, -5280], [8303, -4689], [9238, 4180], [3171, -2762], [5489, 9784], [1797, 6600], [9904, -273], [5991, 7260], [2004, -2469], [6391, -3290], [674, -9143], [789, 6012], [8516, 269], [5855, -8315], [4315, -6207], [2544, 4550], [8513, 7199], [9861, 4103], [7731, -6968], [1342, -6780], [9168, -509], [6172, -928], [9218, 8516], [6333, 7574], [6047, 9076], [636, -3278], [9933, 1426], [2734, 4801], [1695, 4942], [6486, -7637], [5087, -4618], [6913, -6400], [8934, 6774], [4055, -6983], [6158, 1749], [6238, 5327], [1240, 8762], [751, -9541], [7278, -2916], [4385, 9678], [6160, 5022], [6400, -7555], [6448, -4514], [7247, -5505], [6780, 85], [6858, 1867], [1820, -9877], [1819, -2894], [6897, -4125], [123, -592], [7624, 2713], [1087, 8865], [1476, -8162], [5676, -4894], [8923, -3587], [4784, 1435], [1435, -2464], [3881, -5765], [9375, -2520], [8731, -3845], [3917, 1941], [8023, -4263], [2065, -3806], [9195, -1038], [2069, 9319], [4722, -3954], [2032, 5809], [1263, 9860], [7648, 6939], [4967, -7077], [3352, -3897], [4358, -8860], [3640, -1761], [5375, 9367], [5719, 4106], [5522, -363], [6048, 9897], [1726, 4465], [2444, -9078], [3427, 4513], [6593, 4502], [6911, -1375], [311, 8174], [4838, -5689], [5113, -3843], [7234, 4818], [8612, -8407], [2310, 8604], [6184, 7685], [7971, 8256], [8144, 9846], [7893, 544], [9743, 5971], [5009, 8539], [3245, -5212], [3053, -162], [9290, -36], [4816, -4046], [4491, 9654], [265, 9604], [2163, 7500], [774, 775], [5445, -6916], [9380, -8371], [7122, -2649], [9885, -4734], [7197, -5870], [2162, -6707], [6454, 7171], [1832, -301], [8311, 1237], [9538, 7602], [7554, 706], [9908, -7955], [6712, 173], [8001, -1125], [4025, -4872], [6002, 9470], [4564, -4618], [1100, -8314], [9086, 7337], [3304, 2635], [1468, 5466], [2280, 7922], [8989, 465], [3973, -2699], [8054, 9863], [1255, 5608], [569, -8837], [4005, 7281], [7688, -1641], [2508, 1714], [9839, 4863], [1184, 4403], [245, -1364], [6090, -4317], [5974, 5746], [4671, -6206], [1213, -3049], [8068, 6554], [3768, 8393], [3855, 1823], [8257, -8538], [3783, -4822], [8977, 4141], [8812, -3334], [2500, -8680], [8380, 2339], [6183, -4084], [3094, 2781], [905, 9184], [4816, 6879], [4931, -513], [7025, -7504], [2791, 1445], [9050, -3441], [9838, 9258], [8382, -1905], [7072, -7834], [3274, 6050], [6307, 2086], [9068, 5159], [9758, 3800], [3850, -7706], [9716, -3056], [1427, -3027], [2481, -3757], [3852, 3764], [5731, 7229], [2612, -1478], [8674, 1662], [5081, 8513], [7272, -184], [6608, -5655], [8334, 6234], [6747, -9007], [4672, 5815], [6152, 4431], [9615, 6354], [3077, -4317], [3298, -5496], [2657, -7869], [747, 2861], [5895, -7170], [91, -5141], [7704, 5117], [6522, 9138], [3630, -9854], [8954, 6591], [843, 3640], [9177, 7590], [4633, 3850], [3405, -2863], [4633, 9372], [3491, 7710], [1408, -6859], [8566, 417], [1625, -4335], [9630, 3872], [8496, -3927], [8732, 6200], [1191, 1606], [1690, 1173], [1752, 6996], [7764, 2596], [636, 3294], [186, -4731], [7144, 9944], [2406, -1871], [5668, 2249], [5839, 3428], [1743, -5595], [3845, 3368], [70, 9828], [3592, 4918], [5901, -7676], [7471, -2908], [3930, 9161], [4618, -4317], [6158, 8734], [4631, -3206], [2028, -5183], [8416, 9172], [1113, 7174], [3653, 3134], [5776, -508]]],
ans: 2
},
{
input: [[[693, 334], [439, 334], [421, 159], [985, 957], [354, 761], [762, 972], [541, 716], [852, 850], [662, 482], [399, 217], [154, 173], [15, 506], [851, 364], [790, 263], [491, 172], [37, 537], [859, 828], [871, 280], [987, 856], [590, 341], [970, 352], [665, 511], [69, 517], [361, 83], [351, 112], [300, 506], [638, 667], [364, 489], [32, 154], [104, 875], [679, 141], [412, 538], [969, 636], [170, 956], [844, 760], [649, 814], [465, 314], [326, 886], [183, 39], [969, 535], [152, 621], [393, 790], [289, 109], [631, 673], [264, 735], [548, 295], [877, 313], [833, 198], [949, 355], [155, 793], [468, 156], [960, 933], [823, 286], [171, 358], [677, 140], [245, 181], [761, 990], [323, 50], [100, 954], [75, 364], [42, 624], [659, 919], [289, 844], [469, 238], [551, 976], [383, 19], [133, 343], [304, 956], [981, 475], [666, 11], [967, 912], [192, 729], [902, 868], [131, 2], [174, 207], [718, 216], [183, 377], [487, 472], [573, 957], [62, 125], [933, 797], [496, 418], [141, 153], [726, 474], [980, 393], [485, 948], [305, 30], [29, 559], [898, 160], [562, 424], [719, 280], [641, 902], [10, 480], [726, 583], [789, 140], [708, 723], [938, 557], [493, 431], [710, 220], [905, 690], [613, 391], [638, 270], [421, 667], [829, 671], [180, 743], [95, 899], [24, 88], [154, 386], [569, 232], [969, 710], [373, 30], [433, 663], [587, 279], [94, 649], [499, 351], [339, 464], [742, 330], [86, 515], [349, 915], [186, 881], [11, 634], [133, 387], [722, 287], [773, 643], [519, 742], [354, 244], [124, 139], [259, 63], [418, 353], [712, 269], [705, 404], [733, 799], [734, 819], [315, 435], [87, 853], [669, 450], [487, 802], [837, 562], [89, 610], [205, 960], [704, 911], [557, 829], [403, 816], [892, 821], [522, 605], [443, 579], [361, 528], [378, 447], [700, 45], [882, 787], [899, 551], [589, 386], [353, 426], [948, 794], [36, 506], [107, 92], [417, 664], [921, 820], [480, 166], [994, 354], [123, 437], [933, 484], [317, 312], [931, 17], [709, 165], [156, 608], [69, 745], [995, 422], [171, 295], [569, 559], [801, 676], [652, 571], [340, 925], [743, 172], [91, 89], [527, 566], [878, 812], [50, 196], [124, 333], [213, 186], [499, 370], [794, 568], [115, 141], [342, 639], [437, 263], [198, 590], [939, 202], [513, 631], [128, 257], [804, 571], [346, 683], [138, 225], [495, 540], [421, 972], [226, 634], [158, 725], [356, 952], [645, 472], [446, 339], [111, 883], [603, 661], [825, 542], [216, 339], [174, 344], [596, 330], [267, 294], [13, 757], [519, 860], [650, 292], [832, 876], [279, 990], [953, 635], [295, 598], [107, 741], [937, 570], [976, 540], [584, 801], [83, 800], [492, 609], [496, 440], [939, 763], [735, 304], [873, 606], [164, 523], [251, 349], [751, 530], [339, 704], [165, 986], [302, 625], [79, 591], [547, 407], [484, 131], [561, 919], [931, 53], [528, 427], [494, 819], [543, 581], [123, 768], [187, 639], [643, 438], [988, 394], [320, 680], [98, 486], [18, 752], [463, 98], [695, 10], [505, 179], [142, 66], [98, 425], [472, 978], [853, 966], [797, 748], [547, 272], [516, 86], [912, 159], [877, 900], [553, 197], [932, 3], [35, 951], [107, 498], [49, 154], [861, 906], [334, 3], [325, 784], [428, 797], [763, 633], [115, 560], [381, 14], [185, 897], [100, 97], [408, 329], [349, 313], [879, 634], [316, 914], [585, 775], [765, 986], [930, 626], [892, 616], [629, 569], [752, 409], [366, 515], [395, 833], [428, 776], [847, 613], [26, 300], [62, 786], [629, 763], [100, 508], [397, 416], [775, 982], [544, 540], [320, 826], [518, 565], [794, 499], [134, 546], [908, 853], [62, 303], [686, 842], [432, 534], [807, 810], [834, 869], [596, 815], [984, 696], [324, 382], [465, 451], [716, 361], [343, 37], [187, 861], [602, 981], [360, 88], [879, 620], [941, 293], [924, 628], [135, 708], [162, 942], [870, 996], [163, 466], [811, 500], [515, 487], [234, 332], [290, 950], [693, 633], [339, 880], [494, 293], [213, 854], [382, 444], [475, 323], [738, 751], [951, 873], [811, 465], [168, 681], [813, 683], [499, 977], [535, 14], [464, 769], [346, 107], [72, 391], [740, 411], [623, 587], [57, 836], [793, 439], [281, 620], [114, 371], [371, 418], [596, 534], [883, 764], [567, 697], [800, 67], [674, 335], [433, 490], [457, 132], [949, 529], [523, 690], [292, 147], [629, 349], [335, 422], [140, 968], [43, 255], [339, 766], [25, 936], [653, 260], [52, 220], [957, 204], [287, 983], [540, 721], [826, 997], [205, 127], [878, 728], [169, 170], [227, 798], [520, 563], [221, 660], [883, 616], [267, 223], [382, 292], [511, 35], [553, 563], [608, 862], [768, 895], [198, 660], [968, 376], [9, 173], [503, 887], [254, 673], [57, 481], [823, 929], [396, 44], [942, 280], [12, 209], [855, 747], [854, 366], [134, 759], [281, 742], [973, 401], [638, 171], [413, 958], [899, 422], [484, 755], [661, 90], [780, 71], [923, 603], [0, 320], [0, 942], [952, 12], [504, 807], [759, 358], [525, 894], [117, 158], [636, 90], [560, 626], [614, 973], [937, 865], [748, 421], [620, 409], [863, 400], [832, 786], [4, 833], [458, 356], [127, 410], [368, 631], [569, 128], [341, 446], [374, 458], [605, 10], [901, 165], [989, 867], [490, 926], [732, 238], [699, 705], [0, 562], [457, 832], [348, 461], [17, 807], [169, 497], [569, 538], [128, 139], [18, 470], [585, 392], [280, 542], [754, 533], [707, 743], [400, 550], [21, 485], [788, 720], [190, 140], [634, 647], [325, 983], [461, 694], [142, 630], [191, 63], [520, 320], [554, 538], [142, 492], [930, 422], [34, 685], [308, 94], [780, 708], [644, 802], [545, 784], [522, 87], [925, 157], [735, 602], [492, 548], [296, 986], [530, 840], [49, 51], [512, 956], [589, 654], [448, 872], [428, 482], [557, 88], [576, 337], [797, 220], [139, 694], [5, 14], [782, 282], [523, 869], [236, 15], [417, 884], [353, 299], [724, 754], [350, 236], [710, 292], [242, 158], [164, 23], [641, 721], [111, 569], [410, 260], [790, 902], [955, 147], [916, 89], [781, 439], [958, 17], [806, 375], [901, 511], [674, 978], [265, 377], [566, 976], [669, 161], [134, 833]]],
ans: 1062
},
{
input: [[[536, 127], [906, 999], [697, 316], [260, 839], [570, 567], [986, 486], [8, 767], [277, 966], [136, 435], [693, 37], [946, 719], [367, 212], [96, 934], [540, 117], [95, 674], [950, 631], [802, 208], [630, 851], [525, 242], [690, 447], [161, 676], [934, 169], [795, 563], [135, 931], [351, 180], [320, 297], [900, 688], [861, 996], [974, 401], [114, 69], [428, 416], [52, 582], [625, 682], [433, 502], [277, 123], [949, 790], [151, 235], [960, 946], [799, 447], [229, 502], [628, 549], [799, 528], [589, 13], [876, 563], [766, 990], [984, 194], [759, 36], [776, 384], [71, 209], [238, 700], [684, 539], [490, 835], [775, 450], [781, 926], [250, 362], [428, 878], [264, 579], [758, 853], [944, 634], [769, 711], [977, 105], [257, 736], [142, 34], [472, 565], [595, 710], [265, 632], [249, 107], [467, 376], [558, 601], [302, 160], [963, 82], [38, 227], [14, 796], [433, 958], [430, 554], [669, 407], [659, 927], [495, 801], [313, 967], [718, 260], [29, 335], [892, 631], [443, 712], [7, 353], [313, 662], [513, 628], [96, 551], [856, 110], [699, 641], [69, 481], [195, 90], [889, 854], [369, 736], [8, 682], [704, 726], [295, 733], [414, 187], [364, 857], [251, 724], [210, 564], [738, 723], [193, 834], [626, 401], [945, 325], [394, 366], [806, 589], [456, 47], [795, 826], [784, 803], [860, 840], [882, 155], [573, 648], [695, 290], [505, 946], [366, 67], [863, 104], [790, 408], [290, 768], [161, 235], [93, 555], [601, 251], [144, 410], [651, 291], [588, 435], [447, 448], [275, 681], [956, 200], [329, 651], [842, 834], [949, 560], [901, 164], [664, 43], [572, 955], [811, 733], [542, 256], [640, 496], [859, 136], [258, 510], [428, 846], [297, 875], [294, 924], [556, 250], [125, 885], [253, 319], [71, 555], [880, 324], [719, 896], [367, 644], [203, 530], [729, 746], [786, 370], [594, 645], [858, 852], [508, 286], [698, 805], [513, 344], [730, 421], [947, 207], [658, 200], [878, 729], [107, 758], [53, 179], [7, 772], [175, 210], [302, 904], [308, 440], [626, 902], [86, 485], [106, 946], [123, 804], [751, 637], [501, 833], [410, 448], [392, 69], [0, 271], [150, 108], [381, 556], [287, 388], [328, 462], [951, 983], [718, 259], [423, 345], [514, 861], [182, 972], [807, 657], [129, 911], [294, 630], [744, 57], [78, 137], [126, 78], [760, 628], [186, 141], [184, 825], [882, 865], [639, 833], [848, 358], [444, 623], [55, 310], [485, 589], [283, 644], [246, 412], [555, 893], [42, 300], [950, 120], [789, 428], [550, 549], [56, 737], [42, 241], [914, 924], [458, 554], [109, 658], [264, 554], [281, 319], [216, 118], [260, 499], [763, 506], [263, 318], [399, 305], [970, 701], [777, 111], [129, 328], [12, 186], [417, 55], [779, 683], [979, 589], [237, 89], [247, 853], [995, 880], [524, 211], [999, 784], [711, 114], [643, 326], [784, 42], [632, 107], [96, 761], [218, 225], [441, 231], [763, 210], [286, 894], [894, 617], [835, 483], [58, 82], [337, 53], [315, 213], [617, 314], [998, 680], [780, 641], [6, 564], [35, 638], [23, 131], [752, 242], [709, 545], [825, 824], [756, 463], [71, 2], [80, 906], [485, 491], [989, 174], [544, 656], [388, 161], [970, 738], [841, 102], [379, 848], [18, 766], [838, 42], [250, 942], [284, 959], [488, 461], [135, 596], [924, 206], [598, 356], [113, 435], [847, 454], [962, 744], [110, 702], [257, 432], [440, 451], [886, 171], [299, 904], [289, 489], [946, 539], [784, 582], [850, 272], [43, 986], [868, 319], [192, 818], [676, 657], [253, 875], [463, 215], [619, 925], [269, 877], [709, 709], [680, 595], [232, 331], [500, 522], [820, 446], [413, 956], [29, 264], [228, 424], [250, 448], [744, 794], [618, 772], [804, 872], [647, 267], [439, 619], [193, 709], [848, 254], [770, 528], [850, 355], [859, 350], [229, 31], [148, 642], [988, 177], [906, 568], [954, 508], [369, 698], [303, 987], [470, 107], [211, 469], [726, 3], [440, 271], [64, 288], [526, 186], [816, 376], [541, 27], [78, 122], [59, 226], [765, 399], [404, 23], [967, 358], [532, 688], [408, 187], [676, 230], [294, 239], [51, 372], [242, 492], [644, 306], [780, 522], [493, 949], [898, 386], [328, 976], [509, 387], [202, 626], [138, 958], [649, 458], [668, 181], [146, 428], [720, 174], [658, 14], [414, 62], [739, 656], [554, 735], [315, 334], [257, 160], [635, 507], [546, 964], [483, 55], [703, 37], [33, 842], [348, 683], [300, 368], [216, 446], [149, 937], [621, 159], [303, 387], [221, 42], [43, 775], [777, 710], [462, 386], [870, 97], [893, 417], [61, 728], [824, 117], [766, 858], [959, 466], [893, 259], [186, 109], [57, 335], [46, 30], [495, 702], [417, 716], [96, 813], [492, 874], [523, 306], [260, 394], [403, 506], [163, 817], [234, 339], [934, 352], [549, 893], [818, 442], [504, 5], [904, 913], [692, 302], [944, 187], [4, 361], [256, 101], [526, 748], [327, 50], [54, 939], [796, 809], [445, 311], [626, 680], [2, 912], [32, 552], [157, 203], [346, 661], [560, 250], [927, 252], [553, 871], [440, 557], [584, 48], [10, 111], [148, 337], [513, 554], [277, 661], [363, 74], [324, 342], [754, 326], [254, 139], [878, 764], [342, 225], [777, 902], [827, 704], [154, 380], [575, 946], [290, 160], [994, 300], [623, 142], [990, 488], [696, 619], [149, 412], [693, 825], [754, 448], [151, 360], [587, 382], [124, 929], [959, 902], [183, 786], [606, 337], [167, 534], [636, 809], [46, 630], [109, 669], [125, 451], [157, 173], [70, 658], [585, 764], [483, 339], [564, 986], [52, 503], [368, 176], [432, 327], [430, 967], [466, 37], [304, 633], [571, 292], [794, 617], [275, 255], [638, 400], [707, 147], [573, 777], [157, 159], [893, 992], [850, 457], [978, 902], [960, 347], [431, 744], [26, 861], [711, 492], [898, 368], [477, 821], [660, 271], [790, 287], [879, 780], [687, 586], [279, 613], [363, 436], [124, 609], [428, 974], [66, 759], [229, 27], [458, 660], [771, 484], [873, 835], [329, 124], [203, 158], [945, 215], [782, 88], [503, 661], [868, 542], [247, 500], [155, 962], [936, 631], [571, 717], [958, 638], [476, 187], [17, 934], [199, 140], [770, 72]]],
ans: 966
}
]
module.exports = {
data,
checker: require('../checkers.js').normalChecker
}
| 1,111.238095 | 7,169 | 0.522712 |
b9ff2832a3e473deed7f85c803b050d9688f7cd3 | 885 | js | JavaScript | src/main/webapp/app/layouts/navbar/active-menu.directive.js | lugavin/jhipster | 6147ecd2cd5742f7b7a37b09764d9979759c5489 | [
"Apache-2.0"
] | 1 | 2019-08-05T07:53:03.000Z | 2019-08-05T07:53:03.000Z | src/main/webapp/app/layouts/navbar/active-menu.directive.js | danimaniarqsoft/kukulcan | d7f82d361da69ef37121b1d33f880ed7c08c9f5d | [
"MIT"
] | 13 | 2020-06-05T07:38:30.000Z | 2022-03-02T04:34:06.000Z | src/main/webapp/app/layouts/navbar/active-menu.directive.js | lugavin/jhipster | 6147ecd2cd5742f7b7a37b09764d9979759c5489 | [
"Apache-2.0"
] | null | null | null | (function() {
'use strict';
angular
.module('jhipsterApp')
.directive('activeMenu', activeMenu);
activeMenu.$inject = ['$translate', '$locale', 'tmhDynamicLocale'];
function activeMenu($translate, $locale, tmhDynamicLocale) {
var directive = {
restrict: 'A',
link: linkFunc
};
return directive;
function linkFunc(scope, element, attrs) {
var language = attrs.activeMenu;
scope.$watch(function() {
return $translate.use();
}, function(selectedLanguage) {
if (language === selectedLanguage) {
tmhDynamicLocale.set(language);
element.addClass('active');
} else {
element.removeClass('active');
}
});
}
}
})();
| 26.029412 | 71 | 0.491525 |
b9ffc4e3f4e180e8fa7da0297c4b2b867c4185bc | 28,021 | js | JavaScript | dist/angular-formly-templates-brave.js | bravelab/angular-formly-templates-brave | 475483906e9440953547628b1bc4f45bca299604 | [
"MIT"
] | null | null | null | dist/angular-formly-templates-brave.js | bravelab/angular-formly-templates-brave | 475483906e9440953547628b1bc4f45bca299604 | [
"MIT"
] | null | null | null | dist/angular-formly-templates-brave.js | bravelab/angular-formly-templates-brave | 475483906e9440953547628b1bc4f45bca299604 | [
"MIT"
] | null | null | null | //! angular-formly-templates-brave version 0.0.7 built with ♥ by Sizeof (ó ì_í)=óò=(ì_í ò)
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("angular"), require("angular-formly"), require("api-check"));
else if(typeof define === 'function' && define.amd)
define(["angular", "angular-formly", "api-check"], factory);
else if(typeof exports === 'object')
exports["ngFormlyTemplatesBrave"] = factory(require("angular"), require("angular-formly"), require("api-check"));
else
root["ngFormlyTemplatesBrave"] = factory(root["angular"], root["ngFormly"], root["apiCheck"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_3__, __WEBPACK_EXTERNAL_MODULE_4__, __WEBPACK_EXTERNAL_MODULE_5__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = __webpack_require__(1);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var ngModuleName = 'formlyBrave';
var angular = __webpack_require__(2);
var ngModule = angular.module(ngModuleName, [__webpack_require__(4)]);
ngModule.constant('formlyBraveApiCheck', __webpack_require__(5)({
output: {
prefix: 'angular-formly-brave'
}
}));
ngModule.constant('formlyBraveVersion', ("0.0.7"));
__webpack_require__(6)(ngModule);
__webpack_require__(9)(ngModule);
__webpack_require__(25)(ngModule);
exports['default'] = ngModuleName;
module.exports = exports['default'];
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
// some versions of angular don't export the angular module properly,
// so we get it from window in this case.
'use strict';
var angular = __webpack_require__(3);
if (!angular.version) {
angular = window.angular;
}
module.exports = angular;
/***/ },
/* 3 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_3__;
/***/ },
/* 4 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_4__;
/***/ },
/* 5 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_5__;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = function (ngModule) {
ngModule.config(addWrappers);
function addWrappers(formlyConfigProvider) {
formlyConfigProvider.setWrapper([{
name: 'bootstrapLabel',
template: __webpack_require__(7),
apiCheck: function apiCheck(check) {
return {
templateOptions: {
label: check.string.optional,
required: check.bool.optional,
labelSrOnly: check.bool.optional,
sectionClass: check.string.optional
}
};
}
}, { name: 'bootstrapHasError', template: __webpack_require__(8) }]);
}
addWrappers.$inject = ["formlyConfigProvider"];
};
module.exports = exports['default'];
/***/ },
/* 7 */
/***/ function(module, exports) {
module.exports = "<section class=\"{{ to.sectionClass }}\">\n <label for=\"{{id}}\" class=\"label {{to.labelSrOnly ? 'sr-only' : ''}}\" ng-if=\"to.label\">\n {{to.label}}\n {{to.required ? '*' : ''}}\n </label>\n <formly-transclude></formly-transclude>\n</section>\n"
/***/ },
/* 8 */
/***/ function(module, exports) {
module.exports = "<formly-transclude></formly-transclude>\n<div ng-messages=\"fc.$error\" ng-if=\"(form.$submitted || options.formControl.$touched) && options.formControl.$invalid\" class=\"note note-error darkred\">\n <span ng-message=\"{{ ::name }}\" ng-repeat=\"(name, message) in ::options.validation.messages\">\n {{ message(fc.$viewValue, fc.$modelValue, this) }}\n </span>\n</div>\n"
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = function (ngModule) {
__webpack_require__(10)(ngModule);
__webpack_require__(12)(ngModule);
__webpack_require__(14)(ngModule);
__webpack_require__(16)(ngModule);
__webpack_require__(17)(ngModule);
__webpack_require__(19)(ngModule);
__webpack_require__(20)(ngModule);
__webpack_require__(21)(ngModule);
__webpack_require__(23)(ngModule);
};
module.exports = exports['default'];
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = function (ngModule) {
ngModule.config(addCheckboxType);
function addCheckboxType(formlyConfigProvider) {
formlyConfigProvider.setType({
name: 'checkbox',
template: __webpack_require__(11),
apiCheck: function apiCheck(check) {
return {
templateOptions: {
label: check.string
}
};
}
});
}
addCheckboxType.$inject = ["formlyConfigProvider"];
};
module.exports = exports['default'];
/***/ },
/* 11 */
/***/ function(module, exports) {
module.exports = "<section>\n<label class=\"checkbox\">\n\t<input type=\"checkbox\"\n\t class=\"formly-field-checkbox\"\n\t\t ng-model=\"model[options.key]\">\n\t<i></i> {{to.label}}\n\t{{to.required ? '*' : ''}}\n</label>\n</section>"
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = function (ngModule) {
ngModule.config(addCheckboxType);
function addCheckboxType(formlyConfigProvider) {
formlyConfigProvider.setType({
name: 'multiCheckbox',
template: __webpack_require__(13),
wrapper: ['bootstrapLabel', 'bootstrapHasError'],
apiCheck: function apiCheck(check) {
return {
templateOptions: {
options: check.arrayOf(check.object),
labelProp: check.string.optional,
valueProp: check.string.optional
}
};
},
defaultOptions: {
noFormControl: false,
ngModelAttrs: {
required: {
attribute: '',
bound: ''
}
}
},
controller: /* @ngInject */["$scope", function controller($scope) {
var to = $scope.to;
var opts = $scope.options;
$scope.multiCheckbox = {
checked: [],
change: setModel
};
// initialize the checkboxes check property
$scope.$watch('model', function modelWatcher(newModelValue) {
var modelValue, valueProp;
if (Object.keys(newModelValue).length) {
modelValue = newModelValue[opts.key];
$scope.$watch('to.options', function optionsWatcher(newOptionsValues) {
if (newOptionsValues && Array.isArray(newOptionsValues) && Array.isArray(modelValue)) {
valueProp = to.valueProp || 'value';
for (var index = 0; index < newOptionsValues.length; index++) {
$scope.multiCheckbox.checked[index] = modelValue.indexOf(newOptionsValues[index][valueProp]) !== -1;
}
}
});
}
}, true);
function checkValidity(expressionValue) {
var valid;
if ($scope.to.required) {
valid = angular.isArray($scope.model[opts.key]) && $scope.model[opts.key].length > 0 && expressionValue;
$scope.fc.$setValidity('required', valid);
}
}
function setModel() {
$scope.model[opts.key] = [];
angular.forEach($scope.multiCheckbox.checked, function (checkbox, index) {
if (checkbox) {
$scope.model[opts.key].push(to.options[index][to.valueProp || 'value']);
}
});
// Must make sure we mark as touched because only the last checkbox due to a bug in angular.
$scope.fc.$setTouched();
checkValidity(true);
if ($scope.to.onChange) {
$scope.to.onChange();
}
}
if (opts.expressionProperties && opts.expressionProperties['templateOptions.required']) {
$scope.$watch(function () {
return $scope.to.required;
}, function (newValue) {
checkValidity(newValue);
});
}
if ($scope.to.required) {
var unwatchFormControl = $scope.$watch('fc', function (newValue) {
if (!newValue) {
return;
}
checkValidity(true);
unwatchFormControl();
});
}
}]
});
}
addCheckboxType.$inject = ["formlyConfigProvider"];
};
module.exports = exports['default'];
/***/ },
/* 13 */
/***/ function(module, exports) {
module.exports = "<div class=\"radio-group\">\n <div ng-repeat=\"(key, option) in to.options\" class=\"checkbox\">\n <label>\n <input type=\"checkbox\"\n id=\"{{id + '_'+ $index}}\"\n ng-model=\"multiCheckbox.checked[$index]\"\n ng-change=\"multiCheckbox.change()\">\n {{option[to.labelProp || 'name']}}\n </label>\n </div>\n</div>\n"
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = function (ngModule) {
ngModule.config(addMatchInputType);
function addMatchInputType(formlyConfigProvider) {
formlyConfigProvider.setType({
name: 'matchField',
template: __webpack_require__(15),
apiCheck: function apiCheck() {
return {
data: {
fieldToMatch: formlyExampleApiCheck.string
}
};
},
apiCheckOptions: {
prefix: 'matchField type'
},
defaultOptions: function matchFieldDefaultOptions(options) {
return {
extras: {
validateOnModelChange: true
},
expressionProperties: {
'templateOptions.disabled': function templateOptionsDisabled(viewValue, modelValue, scope) {
var matchField = find(scope.fields, 'key', options.data.fieldToMatch);
if (!matchField) {
throw new Error('Could not find a field for the key ' + options.data.fieldToMatch);
}
var model = options.data.modelToMatch || scope.model;
var originalValue = model[options.data.fieldToMatch];
var invalidOriginal = matchField.formControl && matchField.formControl.$invalid;
return !originalValue || invalidOriginal;
}
},
validators: {
fieldMatch: {
expression: function expression(viewValue, modelValue, fieldScope) {
var value = modelValue || viewValue;
var model = options.data.modelToMatch || fieldScope.model;
return value === model[options.data.fieldToMatch];
},
message: options.data.matchFieldMessage || '"Must match"'
}
}
};
function find(array, prop, value) {
var foundItem;
array.some(function (item) {
if (item[prop] === value) {
foundItem = item;
}
return !!foundItem;
});
return foundItem;
}
},
wrapper: ['bootstrapHasError', 'bootstrapLabel']
});
}
addMatchInputType.$inject = ["formlyConfigProvider"];
};
module.exports = exports['default'];
/***/ },
/* 15 */
/***/ function(module, exports) {
module.exports = "<label class=\"input\" ng-class=\"{ 'state-error': showError }\">\n <i class=\"icon-append fa fa-question-circle\"></i>\n <input ng-model=\"model[options.key]\">\n <b class=\"tooltip tooltip-top-right\">\n <i class=\"fa fa-warning txt-color-teal\"></i>\n {{ to.helpText }}\n </b>\n</label>"
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = function (ngModule) {
ngModule.config(addInputType);
function addInputType(formlyConfigProvider) {
formlyConfigProvider.setType({
name: 'input',
template: __webpack_require__(15),
apiCheck: function apiCheck(check) {
return {
templateOptions: {
helpText: check.string
}
};
},
wrapper: ['bootstrapHasError', 'bootstrapLabel']
});
}
addInputType.$inject = ["formlyConfigProvider"];
};
module.exports = exports['default'];
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = function (ngModule) {
ngModule.config(addRadioType);
function addRadioType(formlyConfigProvider) {
formlyConfigProvider.setType({
name: 'radio',
template: __webpack_require__(18),
wrapper: ['bootstrapLabel', 'bootstrapHasError'],
defaultOptions: {
noFormControl: false
},
apiCheck: function apiCheck(check) {
return {
templateOptions: {
options: check.arrayOf(check.object),
labelProp: check.string.optional,
valueProp: check.string.optional,
inline: check.bool.optional
}
};
}
});
}
addRadioType.$inject = ["formlyConfigProvider"];
};
module.exports = exports['default'];
/***/ },
/* 18 */
/***/ function(module, exports) {
module.exports = "<div class=\"radio-group\">\n <div ng-repeat=\"(key, option) in to.options\" ng-class=\"{ 'radio': !to.inline, 'radio-inline': to.inline }\">\n <label>\n <input type=\"radio\"\n id=\"{{id + '_'+ $index}}\"\n tabindex=\"0\"\n ng-value=\"option[to.valueProp || 'value']\"\n ng-model=\"model[options.key]\">\n {{option[to.labelProp || 'name']}}\n </label>\n </div>\n</div>\n"
/***/ },
/* 19 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
exports['default'] = function (ngModule) {
ngModule.config(addSelectType);
var template = '<label class="select" ng-class="{ \'state-error\': showError }"><select ng-model="model[options.key]"></select><i></i></label>';
function addSelectType(formlyConfigProvider) {
formlyConfigProvider.setType({
name: 'select',
template: template,
wrapper: ['bootstrapHasError', 'bootstrapLabel'],
defaultOptions: function defaultOptions(options) {
/* jshint maxlen:195 */
var ngOptions = options.templateOptions.ngOptions || 'option[to.valueProp || \'value\'] as option[to.labelProp || \'name\'] group by option[to.groupProp || \'group\'] for option in to.options';
return {
ngModelAttrs: _defineProperty({}, ngOptions, {
value: options.templateOptions.optionsAttr || 'ng-options'
})
};
},
apiCheck: function apiCheck(check) {
return {
templateOptions: {
options: check.arrayOf(check.object),
optionsAttr: check.string.optional,
labelProp: check.string.optional,
valueProp: check.string.optional,
groupProp: check.string.optional
}
};
}
});
}
addSelectType.$inject = ["formlyConfigProvider"];
};
module.exports = exports['default'];
/***/ },
/* 20 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = function (ngModule) {
ngModule.config(addTextareaType);
function addTextareaType(formlyConfigProvider) {
formlyConfigProvider.setType({
name: 'textarea',
template: '<label class="textarea"><textarea ng-model="model[options.key]"></textarea></label>',
wrapper: ['bootstrapLabel'],
defaultOptions: {
ngModelAttrs: {
rows: { attribute: 'rows' },
cols: { attribute: 'cols' }
}
},
apiCheck: function apiCheck(check) {
return {
templateOptions: {
rows: check.number.optional,
cols: check.number.optional
}
};
}
});
}
addTextareaType.$inject = ["formlyConfigProvider"];
};
module.exports = exports['default'];
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = function (ngModule) {
ngModule.config(addFileSelectorType);
function addFileSelectorType(formlyConfigProvider) {
formlyConfigProvider.setType({
name: 'fileselector',
template: __webpack_require__(22),
wrapper: ['bootstrapLabel']
});
}
addFileSelectorType.$inject = ["formlyConfigProvider"];
};
module.exports = exports['default'];
/***/ },
/* 22 */
/***/ function(module, exports) {
module.exports = "<div class=\"input input-file\">\n <span class=\"button\" ng-click=\"openTinyBrowse('destination','image')\">{{ \"Browse\" | translate }}</span>\n <!--<span class=\"button\" ng-click=\"clearSelection('destination')\"><i class=\"glyphicon glyphicon-remove\"></i></span>-->\n <input placeholder=\"{{ 'Choose file' | translate }}\" name=\"model[options.key]\"\n id=\"destinationInput\" type=\"text\" ng-click=\"openTinyBrowse('destination','image')\">\n</div>\n\n\n<div class=\"img-preview margin-top ng-hide well col col-6\" id=\"destinationImg\">\n <div class=\"preview-text\">{{\"Preview\" | translate }}</div>\n</div>\n<div class=\"clearfix\"></div>\n\n\n<div id=\"tinyCtrl\" ng-app=\"app.files\" ng-controller=\"FilesSelectorController as tiny\">\n <div class=\"tb\" ng-if=\"browserOn\">\n <div class=\"tb-container\">\n <div class=\"tb-frame\">\n <div class=\"tb-toolbar\">\n <div class=\"tb-heading\">Browse - {{getHeading()}}</div>\n <div class=\"tb-right\">\n <div class=\"tb-views\">\n <button class=\"tb-btn\" ng-click=\"changeView('grid')\"><icon></icon></button>\n <button class=\"tb-btn\" ng-click=\"changeView('row')\"><icon></icon></button>\n </div>\n <div class=\"tb-search\">\n\n <input id=\"tb-input\" formnovalidate=\"formnovalidate\" placeholder=\"search\" type=\"text\" ng-model=\"$parent.searchTerm\" ng-keyup=\"search()\"/>\n <div class=\"tb-clear\" ng-click=\"searchClear()\"><icon></icon></div>\n </div>\n <div class=\"tb-btn tb-close\" ng-click=\"close()\"><icon></icon></div>\n </div>\n </div>\n <div class=\"tb-window\">\n <div class=\"tb-scroll\">\n <div class=\"tb-images\">\n\n <!-- FOLDERS -->\n <div class=\"tb-image {{view}}\" ng-click=\"openFolder(folder.sysName)\" ng-repeat=\"folder in folders\">\n <div class=\"tb-image-frame tb-folder\">\n <span ng-bind-html=\"getIcon(folder.type)\"></span>\n </div><div class=\"tb-image-name\">{{folder.name}}</div>\n </div>\n <!-- /FOLDERS -->\n\n <!-- IMAGES -->\n <div class=\"tb-image {{view}}\" ng-click=\"selectItem($index)\" ng-repeat=\"item in items\">\n\n <!-- IMAGE PREVIEW -->\n <div class=\"tb-image-frame\" style=\"background:url('{{item.img}}')\" ng-if=\"browseType == 'image'\">\n <icon ng-bind-html=\"getIcon(item.type)\"></icon>\n </div>\n <!-- IMAGE PREVIEW -->\n\n <!-- FILE PREVIEW -->\n <div class=\"tb-image-frame tb-file-frame\" ng-if=\"browseType == 'file'\">\n <icon ng-bind-html=\"getExtIcon(item.name)\"></icon>\n </div>\n <!-- FILE PREVIEW -->\n\n\n <div class=\"tb-image-name\">{{item.name}}</div>\n </div>\n <!-- /IMAGES -->\n\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n</div>\n"
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = function (ngModule) {
ngModule.config(addUiSelectType);
function addUiSelectType(formlyConfigProvider) {
formlyConfigProvider.setType({
name: 'ui-select',
'extends': 'select',
template: __webpack_require__(24),
wrapper: ['bootstrapHasError', 'bootstrapLabel']
});
}
addUiSelectType.$inject = ["formlyConfigProvider"];
};
module.exports = exports['default'];
/***/ },
/* 24 */
/***/ function(module, exports) {
module.exports = "<ui-select data-ng-model=\"model[options.key]\" data-required=\"{{to.required}}\" data-disabled=\"{{to.disabled}}\" theme=\"bootstrap\">\n <ui-select-match placeholder=\"{{to.placeholder}}\">{{$select.selected[to.labelProp]}} <span ng-show=\"to.loading\"><i class=\"fa fa-cog fa-spin fa-fw\"></i> Loading...</span></ui-select-match>\n <ui-select-choices data-repeat=\"option[to.valueProp] as option in to.options | filter: $select.search\">\n <div ng-bind-html=\"option[to.labelProp] | highlight: $select.search\"></div>\n </ui-select-choices>\n</ui-select>"
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _addons = __webpack_require__(26);
var _addons2 = _interopRequireDefault(_addons);
var _description = __webpack_require__(28);
var _description2 = _interopRequireDefault(_description);
exports['default'] = function (ngModule) {
(0, _addons2['default'])(ngModule);
(0, _description2['default'])(ngModule);
};
module.exports = exports['default'];
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = function (ngModule) {
ngModule.run(addAddonsManipulator);
function addAddonsManipulator(formlyConfig, formlyBraveApiCheck) {
var addonTemplate = __webpack_require__(27);
var addonChecker = formlyBraveApiCheck.shape({
'class': formlyBraveApiCheck.string.optional,
text: formlyBraveApiCheck.string.optional,
onClick: formlyBraveApiCheck.func.optional
}).strict.optional;
var api = formlyBraveApiCheck.shape({
templateOptions: formlyBraveApiCheck.shape({
addonLeft: addonChecker,
addonRight: addonChecker
})
});
formlyConfig.templateManipulators.preWrapper.push(function (template, options) {
if (!options.templateOptions.addonLeft && !options.templateOptions.addonRight) {
return template;
}
formlyBraveApiCheck.warn([api], [options]);
return addonTemplate.replace('<formly-transclude></formly-transclude>', template);
});
}
addAddonsManipulator.$inject = ["formlyConfig", "formlyBraveApiCheck"];
};
module.exports = exports['default'];
/***/ },
/* 27 */
/***/ function(module, exports) {
module.exports = "<div ng-class=\"{'input-group': to.addonLeft || to.addonRight}\">\n <div class=\"input-group-addon\"\n ng-if=\"to.addonLeft\"\n ng-style=\"{cursor: to.addonLeft.onClick ? 'pointer' : 'inherit'}\"\n ng-click=\"to.addonLeft.onClick(options, this, $event)\">\n <i class=\"{{to.addonLeft.class}}\" ng-if=\"to.addonLeft.class\"></i>\n <span ng-if=\"to.addonLeft.text\">{{to.addonLeft.text}}</span>\n </div>\n <formly-transclude></formly-transclude>\n <div class=\"input-group-addon\"\n ng-if=\"to.addonRight\"\n ng-style=\"{cursor: to.addonRight.onClick ? 'pointer' : 'inherit'}\"\n ng-click=\"to.addonRight.onClick(options, this, $event)\">\n <i class=\"{{to.addonRight.class}}\" ng-if=\"to.addonRight.class\"></i>\n <span ng-if=\"to.addonRight.text\">{{to.addonRight.text}}</span>\n </div>\n</div>\n"
/***/ },
/* 28 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = function (ngModule) {
ngModule.run(addDescriptionManipulator);
function addDescriptionManipulator(formlyConfig) {
formlyConfig.templateManipulators.preWrapper.push(function ariaDescribedBy(template, options, scope) {
if (angular.isDefined(options.templateOptions.description)) {
var el = document.createElement('div');
el.appendChild(angular.element(template)[0]);
el.appendChild(angular.element('<p id="' + scope.id + '_description"' + 'class="help-block"' + 'ng-if="to.description">' + '{{to.description}}' + '</p>')[0]);
var modelEls = angular.element(el.querySelectorAll('[ng-model]'));
if (modelEls) {
modelEls.attr('aria-describedby', scope.id + '_description');
}
return el.innerHTML;
} else {
return template;
}
});
}
addDescriptionManipulator.$inject = ["formlyConfig"];
};
module.exports = exports['default'];
/***/ }
/******/ ])
});
; | 36.628758 | 3,794 | 0.575104 |
b9ffe8e6768c4346af6f4a976f0d15fdd7fffe6d | 281 | js | JavaScript | models/user.js | Alex1309/madesoft1 | cdc91884145bd935cac05f1a2e0c747b72756f6d | [
"MIT"
] | 2 | 2020-09-25T09:18:50.000Z | 2020-10-15T10:25:40.000Z | models/user.js | Alex1309/madesoft1 | cdc91884145bd935cac05f1a2e0c747b72756f6d | [
"MIT"
] | 6 | 2020-09-25T05:34:03.000Z | 2020-10-09T17:21:55.000Z | models/user.js | Alex1309/madesoft1 | cdc91884145bd935cac05f1a2e0c747b72756f6d | [
"MIT"
] | 4 | 2020-09-25T05:39:14.000Z | 2022-01-10T09:52:50.000Z | var mongoose = require("mongoose");
var passportlocalmongoose = require("passport-local-mongoose");
var userschema= new mongoose.Schema({
username: String,
password: String
});
userschema.plugin(passportlocalmongoose);
module.exports= mongoose.model("user",userschema); | 25.545455 | 63 | 0.758007 |
6a0050dd26a603514a2c4f6e6f4b93ba4a1cc719 | 5,115 | js | JavaScript | node_modules/redux-form-material-ui/lib/__tests__/TimePicker.spec.js | Dozacode/ResumeChain | 9aa91b4c0f1e36bc88822074e1d719363243972e | [
"MIT"
] | 86 | 2020-08-05T21:04:32.000Z | 2022-02-08T08:55:41.000Z | node_modules/redux-form-material-ui/lib/__tests__/TimePicker.spec.js | Dozacode/ResumeChain | 9aa91b4c0f1e36bc88822074e1d719363243972e | [
"MIT"
] | 7 | 2020-07-21T12:42:14.000Z | 2022-03-02T04:33:56.000Z | node_modules/redux-form-material-ui/lib/__tests__/TimePicker.spec.js | Dozacode/ResumeChain | 9aa91b4c0f1e36bc88822074e1d719363243972e | [
"MIT"
] | 16 | 2020-08-24T08:28:58.000Z | 2021-12-14T12:44:36.000Z | 'use strict';
var _expect = require('expect');
var _expect2 = _interopRequireDefault(_expect);
var _expectJsx = require('expect-jsx');
var _expectJsx2 = _interopRequireDefault(_expectJsx);
var _lodash = require('lodash.noop');
var _lodash2 = _interopRequireDefault(_lodash);
var _getMuiTheme = require('material-ui/styles/getMuiTheme');
var _getMuiTheme2 = _interopRequireDefault(_getMuiTheme);
var _MuiThemeProvider = require('material-ui/styles/MuiThemeProvider');
var _MuiThemeProvider2 = _interopRequireDefault(_MuiThemeProvider);
var _TimePicker = require('material-ui/TimePicker');
var _TimePicker2 = _interopRequireDefault(_TimePicker);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _testUtils = require('react-dom/test-utils');
var _testUtils2 = _interopRequireDefault(_testUtils);
var _TimePicker3 = require('../TimePicker');
var _TimePicker4 = _interopRequireDefault(_TimePicker3);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
_expect2.default.extend(_expectJsx2.default);
describe('TimePicker', function () {
it('has a display name', function () {
(0, _expect2.default)(_TimePicker4.default.displayName).toBe('ReduxFormMaterialUITimePicker');
});
it('renders a TimePicker with no value', function () {
(0, _expect2.default)(new _TimePicker4.default({
input: {
name: 'myTimePicker',
onChange: _lodash2.default
}
}).render()).toEqualJSX(_react2.default.createElement(_TimePicker2.default, { name: 'myTimePicker', onChange: _lodash2.default, ref: 'component' }));
});
it('renders a TimePicker with a value', function () {
var value = new Date('2016-01-01');
(0, _expect2.default)(new _TimePicker4.default({
input: {
name: 'myTimePicker',
onChange: _lodash2.default,
value: value
}
}).render()).toEqualJSX(_react2.default.createElement(_TimePicker2.default, {
name: 'myTimePicker',
onChange: _lodash2.default,
value: value,
ref: 'component'
}));
});
it('renders a TimePicker with an error', function () {
var value = new Date('2016-01-01');
(0, _expect2.default)(new _TimePicker4.default({
input: {
name: 'myTimePicker',
value: value
},
meta: {
error: 'FooError',
touched: true
}
}).render()).toEqualJSX(_react2.default.createElement(_TimePicker2.default, {
name: 'myTimePicker',
value: value,
errorText: 'FooError',
onChange: _lodash2.default,
ref: 'component'
}));
});
it('renders a TimePicker with an warning', function () {
var value = new Date('2016-01-01');
(0, _expect2.default)(new _TimePicker4.default({
input: {
name: 'myTimePicker',
value: value
},
meta: {
warning: 'FooWarning',
touched: true
}
}).render()).toEqualJSX(_react2.default.createElement(_TimePicker2.default, {
name: 'myTimePicker',
value: value,
errorText: 'FooWarning',
onChange: _lodash2.default,
ref: 'component'
}));
});
it('should ignore defaultTime', function () {
var defaultTime = new Date('2016-01-01');
(0, _expect2.default)(new _TimePicker4.default({
input: {
name: 'myTimePicker'
},
meta: {
warning: 'FooWarning',
touched: true
},
defaultTime: defaultTime
}).render()).toEqualJSX(_react2.default.createElement(_TimePicker2.default, {
name: 'myTimePicker',
errorText: 'FooWarning',
onChange: _lodash2.default,
ref: 'component'
}));
});
it('maps onChange properly', function () {
var onChange = (0, _expect.createSpy)();
var first = new Date('August 22, 2016 10:15:00');
var second = new Date('August 22, 2016 11:20:00');
var dom = _testUtils2.default.renderIntoDocument(_react2.default.createElement(
_MuiThemeProvider2.default,
{ muiTheme: (0, _getMuiTheme2.default)() },
_react2.default.createElement(_TimePicker4.default, {
input: { name: 'myTimePicker', onChange: onChange, value: first }
})
));
var timePicker = _testUtils2.default.findRenderedComponentWithType(dom, _TimePicker2.default);
(0, _expect2.default)(onChange).toNotHaveBeenCalled();
timePicker.props.onChange(undefined, second);
(0, _expect2.default)(onChange).toHaveBeenCalled().toHaveBeenCalledWith(second);
});
it('provides getRenderedComponent', function () {
var dom = _testUtils2.default.renderIntoDocument(_react2.default.createElement(
_MuiThemeProvider2.default,
{ muiTheme: (0, _getMuiTheme2.default)() },
_react2.default.createElement(_TimePicker4.default, {
input: { name: 'myTimePicker', onChange: _lodash2.default }
})
));
var element = _testUtils2.default.findRenderedComponentWithType(dom, _TimePicker4.default);
(0, _expect2.default)(element.getRenderedComponent).toBeA('function');
(0, _expect2.default)(element.getRenderedComponent()).toExist();
});
}); | 31.189024 | 153 | 0.666667 |
6a00a4f47f8f3dc99419b588bc09351a397d7a7b | 26,636 | js | JavaScript | mpmath.js | ibdafna/webdash_dist | bc514ded7374ab42a0a87cd659f064043c7c2d09 | [
"BSD-3-Clause"
] | null | null | null | mpmath.js | ibdafna/webdash_dist | bc514ded7374ab42a0a87cd659f064043c7c2d09 | [
"BSD-3-Clause"
] | null | null | null | mpmath.js | ibdafna/webdash_dist | bc514ded7374ab42a0a87cd659f064043c7c2d09 | [
"BSD-3-Clause"
] | null | null | null | var Module=typeof pyodide._module!=="undefined"?pyodide._module:{};if(!Module.expectedDataFileDownloads){Module.expectedDataFileDownloads=0}Module.expectedDataFileDownloads++;(function(){var loadPackage=function(metadata){var PACKAGE_PATH;if(typeof window==="object"){PACKAGE_PATH=window["encodeURIComponent"](window.location.pathname.toString().substring(0,window.location.pathname.toString().lastIndexOf("/"))+"/")}else if(typeof location!=="undefined"){PACKAGE_PATH=encodeURIComponent(location.pathname.toString().substring(0,location.pathname.toString().lastIndexOf("/"))+"/")}else{throw"using preloaded data can only be done on a web page or in a web worker"}var PACKAGE_NAME="mpmath.data";var REMOTE_PACKAGE_BASE="mpmath.data";if(typeof Module["locateFilePackage"]==="function"&&!Module["locateFile"]){Module["locateFile"]=Module["locateFilePackage"];err("warning: you defined Module.locateFilePackage, that has been renamed to Module.locateFile (using your locateFilePackage for now)")}var REMOTE_PACKAGE_NAME=Module["locateFile"]?Module["locateFile"](REMOTE_PACKAGE_BASE,""):REMOTE_PACKAGE_BASE;var REMOTE_PACKAGE_SIZE=metadata["remote_package_size"];var PACKAGE_UUID=metadata["package_uuid"];function fetchRemotePackage(packageName,packageSize,callback,errback){var xhr=new XMLHttpRequest;xhr.open("GET",packageName,true);xhr.responseType="arraybuffer";xhr.onprogress=function(event){var url=packageName;var size=packageSize;if(event.total)size=event.total;if(event.loaded){if(!xhr.addedTotal){xhr.addedTotal=true;if(!Module.dataFileDownloads)Module.dataFileDownloads={};Module.dataFileDownloads[url]={loaded:event.loaded,total:size}}else{Module.dataFileDownloads[url].loaded=event.loaded}var total=0;var loaded=0;var num=0;for(var download in Module.dataFileDownloads){var data=Module.dataFileDownloads[download];total+=data.total;loaded+=data.loaded;num++}total=Math.ceil(total*Module.expectedDataFileDownloads/num);if(Module["setStatus"])Module["setStatus"]("Downloading data... ("+loaded+"/"+total+")")}else if(!Module.dataFileDownloads){if(Module["setStatus"])Module["setStatus"]("Downloading data...")}};xhr.onerror=function(event){throw new Error("NetworkError for: "+packageName)};xhr.onload=function(event){if(xhr.status==200||xhr.status==304||xhr.status==206||xhr.status==0&&xhr.response){var packageData=xhr.response;callback(packageData)}else{throw new Error(xhr.statusText+" : "+xhr.responseURL)}};xhr.send(null)}function handleError(error){console.error("package error:",error)}var fetchedCallback=null;var fetched=Module["getPreloadedPackage"]?Module["getPreloadedPackage"](REMOTE_PACKAGE_NAME,REMOTE_PACKAGE_SIZE):null;if(!fetched)fetchRemotePackage(REMOTE_PACKAGE_NAME,REMOTE_PACKAGE_SIZE,function(data){if(fetchedCallback){fetchedCallback(data);fetchedCallback=null}else{fetched=data}},handleError);function runWithFS(){function assert(check,msg){if(!check)throw msg+(new Error).stack}Module["FS_createPath"]("/","lib",true,true);Module["FS_createPath"]("/lib","python3.8",true,true);Module["FS_createPath"]("/lib/python3.8","site-packages",true,true);Module["FS_createPath"]("/lib/python3.8/site-packages","mpmath",true,true);Module["FS_createPath"]("/lib/python3.8/site-packages/mpmath","matrices",true,true);Module["FS_createPath"]("/lib/python3.8/site-packages/mpmath","libmp",true,true);Module["FS_createPath"]("/lib/python3.8/site-packages/mpmath","tests",true,true);Module["FS_createPath"]("/lib/python3.8/site-packages/mpmath","calculus",true,true);Module["FS_createPath"]("/lib/python3.8/site-packages/mpmath","functions",true,true);function processPackageData(arrayBuffer){assert(arrayBuffer,"Loading data file failed.");assert(arrayBuffer instanceof ArrayBuffer,"bad input to processPackageData");var byteArray=new Uint8Array(arrayBuffer);var curr;var compressedData={data:null,cachedOffset:1106107,cachedIndexes:[-1,-1],cachedChunks:[null,null],offsets:[0,1311,2276,3500,4657,5832,7058,8260,9419,11058,12424,13433,14178,14745,15604,16440,17423,18511,19504,20824,21900,23023,24143,25236,26419,27455,28620,29721,30815,31909,32990,33966,35159,36289,37232,38222,39511,40645,41744,42784,43502,44630,46027,47239,48700,49814,51047,52476,53827,55089,56040,57429,58675,60098,61410,62683,64138,65646,66932,68172,69616,70950,72348,73743,74884,76214,77400,78837,80099,81348,82373,83636,84713,85959,87133,88739,90190,91372,92762,94009,95353,96746,98171,99694,101183,102661,104050,105555,106884,108279,109724,110880,112348,113815,115310,116887,118146,119725,121170,122498,124008,125331,126849,128337,129850,131227,132559,133957,135238,136478,137806,139227,140586,142099,143371,144516,145898,147351,148548,150022,151305,152603,153952,155399,156897,158290,159655,161100,162504,163848,165267,166657,168069,169563,170931,172212,173489,174916,176003,177406,178838,180344,181704,183087,184528,185681,187052,188508,190030,191644,193060,194580,196052,197402,198895,200335,201762,203039,204441,205388,206712,208102,209489,210832,212276,213733,215035,216289,217759,218922,220326,221779,222984,224305,225614,226883,228379,229743,231254,232627,234097,235425,236979,238276,239460,240847,242037,243437,244854,246e3,247412,248741,250092,251547,252719,253655,254423,255525,256384,257557,258407,258919,259816,260960,261978,262857,264047,264999,265945,267070,268099,269260,270675,272046,272905,273356,274701,275717,276580,277556,278590,279429,280414,281375,282736,284013,285044,286520,287926,289056,290468,291423,292546,293843,295110,296354,297575,298978,300059,301146,302302,303231,304455,305546,306487,307497,308589,310016,311079,312405,313785,314871,316080,317373,318483,319739,320936,322154,323304,324575,325848,327035,328194,329416,330457,331386,332329,333326,334238,335164,335993,337145,338380,339703,341130,342491,343623,344818,345944,347221,348406,349508,350599,351985,353095,353826,354739,355836,357228,358337,359661,360743,362001,363309,364456,365722,367015,368320,369477,370627,371676,373033,373898,374776,375738,376942,378288,378999,379817,380839,381755,382885,384096,385282,386584,387822,388725,389424,390594,391436,392546,393643,394789,395996,397057,397958,399133,400143,401029,402436,403645,405011,406481,407587,408807,410178,411271,412719,413917,415118,416424,417703,418897,419921,421159,422354,423573,424720,425786,426691,428119,429207,430370,431855,433074,434244,435574,437040,438298,439317,440205,441285,442441,443595,444873,445956,446669,447951,449052,449972,451113,452430,453884,454846,455697,456806,457942,459321,460503,461374,462335,463272,464268,465547,466737,467945,469001,470237,471185,472465,473623,474815,476080,477393,478553,479866,481292,482833,484160,485636,486813,488206,489484,490857,492218,493428,494698,495875,497379,498743,500030,501309,502559,503791,505080,506332,507614,508825,510010,510801,512161,513361,514571,515667,516564,517861,518926,519887,520988,522247,523273,524561,525680,526810,528116,529286,530633,531761,532794,533819,535031,536098,537474,538636,539832,540539,541811,542733,543881,545095,546346,547534,548970,550084,551490,552650,553829,555115,556357,557548,558524,560494,561503,562745,564440,565640,566745,567615,568574,569327,570254,571369,572181,573271,574199,574995,575761,576932,577753,578742,579139,579878,580700,582301,584152,585992,587469,588810,589895,590827,591493,592029,592888,593879,594676,595602,596693,597926,599198,600295,601570,602496,604145,605302,605928,606901,607850,608778,609527,610833,611769,612488,613578,614596,615394,616164,616693,617373,618246,619253,620402,621483,622733,623903,625146,626352,627590,628408,629256,630070,631130,632037,633365,634701,636084,637345,638465,639437,640368,641363,642555,643383,644556,645041,646109,646941,648089,649136,650277,651496,652486,653253,654073,655277,656512,657412,659068,660887,662704,664502,666334,668176,669981,671801,673616,675431,676714,678108,678947,680028,681304,681868,682975,684108,685078,686075,687203,688659,690343,691860,692769,693311,694079,694903,695877,696933,698505,699903,701039,701980,703004,704211,704982,705940,706894,707778,708582,709736,710453,711583,712759,713655,714822,716046,716661,717482,718560,719608,720837,721777,722314,723436,724675,725796,726851,727811,728984,730153,730828,731673,732522,733402,734253,735111,735996,736826,737341,737911,738769,739628,740504,741342,742235,743100,743974,744842,745505,746391,747261,748148,748976,749810,750587,751301,751944,752754,753574,754385,755161,756013,756890,757772,758691,759556,760167,761320,762457,763591,764563,765771,767080,768077,769126,770370,771598,772876,774074,775245,776408,777760,779004,780374,781619,782677,783707,784891,786056,787323,788518,789668,791112,792408,793887,795268,796613,797793,799031,800170,801465,802596,803745,804996,806193,807710,809044,810475,811828,813119,814445,815656,816850,818044,818917,820244,821536,822819,823974,825413,826938,828385,829784,831166,832597,833989,835042,836356,837618,838667,839498,840771,841960,842984,844429,845964,847259,848430,849464,850353,851809,853270,854699,855836,857130,858413,859625,860704,861990,863018,864406,865503,866825,868309,869632,871075,872568,874029,875367,876599,877980,879331,880632,881941,883274,884571,885977,887294,888699,890102,891409,892649,893987,895244,896610,897967,899381,900715,902063,903189,904598,905978,907326,908611,909848,911276,912661,914027,915387,916626,917994,919034,920195,921258,922355,923422,924500,925770,926782,927936,928998,930062,930786,931990,933007,934099,935039,936090,937289,938432,939764,940851,942181,943406,944630,945878,947176,948605,949712,950976,952188,953466,954819,955861,956913,957698,958550,959766,961187,962556,963938,965055,966110,967400,968674,969893,971094,972220,973600,974570,975429,976587,977890,979170,980392,981730,982847,984239,985473,986721,988073,989377,990716,991952,993308,994494,995551,996866,997961,999329,1000918,1002173,1003197,1004347,1005281,1006363,1007592,1008930,1010102,1011234,1012537,1013943,1015298,1016666,1018063,1019159,1020495,1021745,1023174,1024407,1025788,1027005,1027834,1028787,1029625,1030585,1031468,1032398,1033420,1034446,1035262,1036109,1037156,1038081,1039012,1040047,1040854,1041891,1042609,1043436,1044622,1045714,1046572,1047622,1048547,1049629,1050927,1052201,1053697,1054811,1055766,1056980,1058172,1059349,1060460,1061668,1062694,1063927,1064868,1066073,1067215,1068175,1069247,1070414,1071803,1073069,1074143,1075534,1076335,1077726,1078994,1080281,1081569,1083039,1084194,1085379,1086519,1087648,1088799,1089998,1090916,1092067,1093196,1094346,1095375,1096526,1097404,1098272,1099502,1100647,1101626,1102841,1104095,1105398],sizes:[1311,965,1224,1157,1175,1226,1202,1159,1639,1366,1009,745,567,859,836,983,1088,993,1320,1076,1123,1120,1093,1183,1036,1165,1101,1094,1094,1081,976,1193,1130,943,990,1289,1134,1099,1040,718,1128,1397,1212,1461,1114,1233,1429,1351,1262,951,1389,1246,1423,1312,1273,1455,1508,1286,1240,1444,1334,1398,1395,1141,1330,1186,1437,1262,1249,1025,1263,1077,1246,1174,1606,1451,1182,1390,1247,1344,1393,1425,1523,1489,1478,1389,1505,1329,1395,1445,1156,1468,1467,1495,1577,1259,1579,1445,1328,1510,1323,1518,1488,1513,1377,1332,1398,1281,1240,1328,1421,1359,1513,1272,1145,1382,1453,1197,1474,1283,1298,1349,1447,1498,1393,1365,1445,1404,1344,1419,1390,1412,1494,1368,1281,1277,1427,1087,1403,1432,1506,1360,1383,1441,1153,1371,1456,1522,1614,1416,1520,1472,1350,1493,1440,1427,1277,1402,947,1324,1390,1387,1343,1444,1457,1302,1254,1470,1163,1404,1453,1205,1321,1309,1269,1496,1364,1511,1373,1470,1328,1554,1297,1184,1387,1190,1400,1417,1146,1412,1329,1351,1455,1172,936,768,1102,859,1173,850,512,897,1144,1018,879,1190,952,946,1125,1029,1161,1415,1371,859,451,1345,1016,863,976,1034,839,985,961,1361,1277,1031,1476,1406,1130,1412,955,1123,1297,1267,1244,1221,1403,1081,1087,1156,929,1224,1091,941,1010,1092,1427,1063,1326,1380,1086,1209,1293,1110,1256,1197,1218,1150,1271,1273,1187,1159,1222,1041,929,943,997,912,926,829,1152,1235,1323,1427,1361,1132,1195,1126,1277,1185,1102,1091,1386,1110,731,913,1097,1392,1109,1324,1082,1258,1308,1147,1266,1293,1305,1157,1150,1049,1357,865,878,962,1204,1346,711,818,1022,916,1130,1211,1186,1302,1238,903,699,1170,842,1110,1097,1146,1207,1061,901,1175,1010,886,1407,1209,1366,1470,1106,1220,1371,1093,1448,1198,1201,1306,1279,1194,1024,1238,1195,1219,1147,1066,905,1428,1088,1163,1485,1219,1170,1330,1466,1258,1019,888,1080,1156,1154,1278,1083,713,1282,1101,920,1141,1317,1454,962,851,1109,1136,1379,1182,871,961,937,996,1279,1190,1208,1056,1236,948,1280,1158,1192,1265,1313,1160,1313,1426,1541,1327,1476,1177,1393,1278,1373,1361,1210,1270,1177,1504,1364,1287,1279,1250,1232,1289,1252,1282,1211,1185,791,1360,1200,1210,1096,897,1297,1065,961,1101,1259,1026,1288,1119,1130,1306,1170,1347,1128,1033,1025,1212,1067,1376,1162,1196,707,1272,922,1148,1214,1251,1188,1436,1114,1406,1160,1179,1286,1242,1191,976,1970,1009,1242,1695,1200,1105,870,959,753,927,1115,812,1090,928,796,766,1171,821,989,397,739,822,1601,1851,1840,1477,1341,1085,932,666,536,859,991,797,926,1091,1233,1272,1097,1275,926,1649,1157,626,973,949,928,749,1306,936,719,1090,1018,798,770,529,680,873,1007,1149,1081,1250,1170,1243,1206,1238,818,848,814,1060,907,1328,1336,1383,1261,1120,972,931,995,1192,828,1173,485,1068,832,1148,1047,1141,1219,990,767,820,1204,1235,900,1656,1819,1817,1798,1832,1842,1805,1820,1815,1815,1283,1394,839,1081,1276,564,1107,1133,970,997,1128,1456,1684,1517,909,542,768,824,974,1056,1572,1398,1136,941,1024,1207,771,958,954,884,804,1154,717,1130,1176,896,1167,1224,615,821,1078,1048,1229,940,537,1122,1239,1121,1055,960,1173,1169,675,845,849,880,851,858,885,830,515,570,858,859,876,838,893,865,874,868,663,886,870,887,828,834,777,714,643,810,820,811,776,852,877,882,919,865,611,1153,1137,1134,972,1208,1309,997,1049,1244,1228,1278,1198,1171,1163,1352,1244,1370,1245,1058,1030,1184,1165,1267,1195,1150,1444,1296,1479,1381,1345,1180,1238,1139,1295,1131,1149,1251,1197,1517,1334,1431,1353,1291,1326,1211,1194,1194,873,1327,1292,1283,1155,1439,1525,1447,1399,1382,1431,1392,1053,1314,1262,1049,831,1273,1189,1024,1445,1535,1295,1171,1034,889,1456,1461,1429,1137,1294,1283,1212,1079,1286,1028,1388,1097,1322,1484,1323,1443,1493,1461,1338,1232,1381,1351,1301,1309,1333,1297,1406,1317,1405,1403,1307,1240,1338,1257,1366,1357,1414,1334,1348,1126,1409,1380,1348,1285,1237,1428,1385,1366,1360,1239,1368,1040,1161,1063,1097,1067,1078,1270,1012,1154,1062,1064,724,1204,1017,1092,940,1051,1199,1143,1332,1087,1330,1225,1224,1248,1298,1429,1107,1264,1212,1278,1353,1042,1052,785,852,1216,1421,1369,1382,1117,1055,1290,1274,1219,1201,1126,1380,970,859,1158,1303,1280,1222,1338,1117,1392,1234,1248,1352,1304,1339,1236,1356,1186,1057,1315,1095,1368,1589,1255,1024,1150,934,1082,1229,1338,1172,1132,1303,1406,1355,1368,1397,1096,1336,1250,1429,1233,1381,1217,829,953,838,960,883,930,1022,1026,816,847,1047,925,931,1035,807,1037,718,827,1186,1092,858,1050,925,1082,1298,1274,1496,1114,955,1214,1192,1177,1111,1208,1026,1233,941,1205,1142,960,1072,1167,1389,1266,1074,1391,801,1391,1268,1287,1288,1470,1155,1185,1140,1129,1151,1199,918,1151,1129,1150,1029,1151,878,868,1230,1145,979,1215,1254,1303,709],successes:[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]};compressedData["data"]=byteArray;assert(typeof Module.LZ4==="object","LZ4 not present - was your app build with -s LZ4=1 ?");Module.LZ4.loadPackage({metadata:metadata,compressedData:compressedData},true);Module["removeRunDependency"]("datafile_mpmath.data")}Module["addRunDependency"]("datafile_mpmath.data");if(!Module.preloadResults)Module.preloadResults={};Module.preloadResults[PACKAGE_NAME]={fromCache:false};if(fetched){processPackageData(fetched);fetched=null}else{fetchedCallback=processPackageData}}if(Module["calledRun"]){runWithFS()}else{if(!Module["preRun"])Module["preRun"]=[];Module["preRun"].push(runWithFS)}};loadPackage({files:[{filename:"/lib/python3.8/site-packages/mpmath-1.1.0-py3.8.egg-info",start:0,end:332,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/math2.py",start:332,end:18893,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/ctx_mp.py",start:18893,end:68565,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/ctx_base.py",start:68565,end:84550,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/identification.py",start:84550,end:113820,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/function_docs.py",start:113820,end:394286,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/ctx_mp_python.py",start:394286,end:432399,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/usertools.py",start:432399,end:435428,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/rational.py",start:435428,end:441398,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/ctx_iv.py",start:441398,end:458196,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/visualization.py",start:458196,end:468823,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/ctx_fp.py",start:468823,end:475395,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/__init__.py",start:475395,end:483995,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/matrices/calculus.py",start:483995,end:502604,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/matrices/eigen.py",start:502604,end:526986,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/matrices/matrices.py",start:526986,end:558581,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/matrices/linalg.py",start:558581,end:585601,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/matrices/eigen_symmetric.py",start:585601,end:644125,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/matrices/__init__.py",start:644125,end:644219,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/libmp/libmpi.py",start:644219,end:671841,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/libmp/libelefun.py",start:671841,end:715702,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/libmp/libintmath.py",start:715702,end:732164,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/libmp/libmpc.py",start:732164,end:759033,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/libmp/six.py",start:759033,end:770888,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/libmp/libhyper.py",start:770888,end:807512,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/libmp/gammazeta.py",start:807512,end:886438,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/libmp/libmpf.py",start:886438,end:931454,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/libmp/backend.py",start:931454,end:934311,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/libmp/__init__.py",start:934311,end:938171,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/extratest_gamma.py",start:938171,end:945399,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/extratest_zeta.py",start:945399,end:946402,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_compatibility.py",start:946402,end:948708,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_functions.py",start:948708,end:979663,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_str.py",start:979663,end:980207,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_bitwise.py",start:980207,end:987893,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_hp.py",start:987893,end:998354,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_interval.py",start:998354,end:1015487,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_linalg.py",start:1015487,end:1025943,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/torture.py",start:1025943,end:1033811,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_identify.py",start:1033811,end:1034503,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_eigen_symmetric.py",start:1034503,end:1043281,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_basic_ops.py",start:1043281,end:1058480,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_pickle.py",start:1058480,end:1058881,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_diff.py",start:1058881,end:1061347,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_functions2.py",start:1061347,end:1158337,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_ode.py",start:1158337,end:1160159,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_elliptic.py",start:1160159,end:1184804,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_trig.py",start:1184804,end:1189603,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_eigen.py",start:1189603,end:1193508,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_quad.py",start:1193508,end:1197262,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_calculus.py",start:1197262,end:1206233,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_rootfinding.py",start:1206233,end:1209475,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_division.py",start:1209475,end:1214815,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_special.py",start:1214815,end:1217663,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_convert.py",start:1217663,end:1226173,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_mpmath.py",start:1226173,end:1226369,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_visualization.py",start:1226369,end:1227313,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_matrices.py",start:1227313,end:1232731,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_power.py",start:1232731,end:1237958,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/__init__.py",start:1237958,end:1237958,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_summation.py",start:1237958,end:1239817,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_levin.py",start:1239817,end:1244907,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_fp.py",start:1244907,end:1334904,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/test_gammazeta.py",start:1334904,end:1362567,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/tests/runtests.py",start:1362567,end:1367385,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/calculus/calculus.py",start:1367385,end:1367484,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/calculus/polynomials.py",start:1367484,end:1375338,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/calculus/optimization.py",start:1375338,end:1407757,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/calculus/quadrature.py",start:1407757,end:1446069,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/calculus/extrapolation.py",start:1446069,end:1519358,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/calculus/approximation.py",start:1519358,end:1528175,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/calculus/differentiation.py",start:1528175,end:1548401,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/calculus/inverselaplace.py",start:1548401,end:1579536,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/calculus/odes.py",start:1579536,end:1589444,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/calculus/__init__.py",start:1589444,end:1589606,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/functions/orthogonal.py",start:1589606,end:1605703,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/functions/bessel.py",start:1605703,end:1643641,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/functions/rszeta.py",start:1643641,end:1689825,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/functions/elliptic.py",start:1689825,end:1728855,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/functions/zeta.py",start:1728855,end:1765226,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/functions/factorials.py",start:1765226,end:1770941,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/functions/qfunctions.py",start:1770941,end:1778574,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/functions/theta.py",start:1778574,end:1815894,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/functions/hypergeometric.py",start:1815894,end:1867464,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/functions/zetazeros.py",start:1867464,end:1898415,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/functions/expintegrals.py",start:1898415,end:1910059,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/functions/functions.py",start:1910059,end:1928120,audio:0},{filename:"/lib/python3.8/site-packages/mpmath/functions/__init__.py",start:1928120,end:1928428,audio:0}],remote_package_size:1110203,package_uuid:"62d676e7-10ba-4f97-895c-1b9cdb3571e9"})})(); | 26,636 | 26,636 | 0.789345 |
6a020235b9239412482d52d3fd0a7fa1ac176a1e | 3,566 | js | JavaScript | module/item-sheet.js | HonzoNebro/hitos-foundryVTT | 3f90916afd670e192f3bfdeb4859f6a00662238c | [
"MIT"
] | null | null | null | module/item-sheet.js | HonzoNebro/hitos-foundryVTT | 3f90916afd670e192f3bfdeb4859f6a00662238c | [
"MIT"
] | null | null | null | module/item-sheet.js | HonzoNebro/hitos-foundryVTT | 3f90916afd670e192f3bfdeb4859f6a00662238c | [
"MIT"
] | null | null | null | /**
* Extend the basic ItemSheet with some very simple modifications
* @extends {ItemSheet}
*/
export class SimpleItemSheet extends ItemSheet {
/** @override */
static get defaultOptions() {
return mergeObject(super.defaultOptions, {
classes: ["hitos", "sheet", "item"],
template: "systems/hitos/templates/item-sheet.html",
width: 520,
height: 480,
tabs: [{navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "description"}]
});
}
/* -------------------------------------------- */
/** @override */
getData() {
const data = super.getData();
data.dtypes = ["String", "Number", "Boolean"];
for ( let attr of Object.values(data.data.attributes) ) {
attr.isCheckbox = attr.dtype === "Boolean";
}
return data;
}
/* -------------------------------------------- */
/** @override */
setPosition(options={}) {
const position = super.setPosition(options);
const sheetBody = this.element.find(".sheet-body");
const bodyHeight = position.height - 192;
sheetBody.css("height", bodyHeight);
return position;
}
/* -------------------------------------------- */
/** @override */
activateListeners(html) {
super.activateListeners(html);
// Everything below here is only needed if the sheet is editable
if (!this.options.editable) return;
// Add or Remove Attribute
html.find(".attributes").on("click", ".attribute-control", this._onClickAttributeControl.bind(this));
}
/* -------------------------------------------- */
/**
* Listen for click events on an attribute control to modify the composition of attributes in the sheet
* @param {MouseEvent} event The originating left click event
* @private
*/
async _onClickAttributeControl(event) {
event.preventDefault();
const a = event.currentTarget;
const action = a.dataset.action;
const attrs = this.object.data.data.attributes;
const form = this.form;
// Add new attribute
if ( action === "create" ) {
const nk = Object.keys(attrs).length + 1;
let newKey = document.createElement("div");
newKey.innerHTML = `<input type="text" name="data.attributes.attr${nk}.key" value="attr${nk}"/>`;
newKey = newKey.children[0];
form.appendChild(newKey);
await this._onSubmit(event);
}
// Remove existing attribute
else if ( action === "delete" ) {
const li = a.closest(".attribute");
li.parentElement.removeChild(li);
await this._onSubmit(event);
}
}
/* -------------------------------------------- */
/** @override */
_updateObject(event, formData) {
// Handle the free-form attributes list
const formAttrs = expandObject(formData).data.attributes || {};
const attributes = Object.values(formAttrs).reduce((obj, v) => {
let k = v["key"].trim();
if ( /[\s\.]/.test(k) ) return ui.notifications.error("Attribute keys may not contain spaces or periods");
delete v["key"];
obj[k] = v;
return obj;
}, {});
// Remove attributes which are no longer used
for ( let k of Object.keys(this.object.data.data.attributes) ) {
if ( !attributes.hasOwnProperty(k) ) attributes[`-=${k}`] = null;
}
// Re-combine formData
formData = Object.entries(formData).filter(e => !e[0].startsWith("data.attributes")).reduce((obj, e) => {
obj[e[0]] = e[1];
return obj;
}, {_id: this.object._id, "data.attributes": attributes});
// Update the Item
return this.object.update(formData);
}
}
| 30.741379 | 113 | 0.586932 |
6a022b1518df072a7de7f6409acbd48da028698a | 6,847 | js | JavaScript | js/main.js | ThiagoOMiranda/gameflix | 60cee2ed2c6a52f94c091e949336135c48eafa06 | [
"MIT"
] | null | null | null | js/main.js | ThiagoOMiranda/gameflix | 60cee2ed2c6a52f94c091e949336135c48eafa06 | [
"MIT"
] | null | null | null | js/main.js | ThiagoOMiranda/gameflix | 60cee2ed2c6a52f94c091e949336135c48eafa06 | [
"MIT"
] | null | null | null | /* Animação na barra de navegação */
window.onscroll = function() {
let distanceScrolled = document.documentElement.scrollTop;
if (distanceScrolled > 0) {
document.getElementById("header").className = "navbar-mod";
vidCover[1].pause();
vidCover[1].currentTime = 0;
fly.style.display = "none";
// document.getElementById("header").style.background = "rgb(34, 2, 66)";
} else {
document.getElementById("header").className = "navbar";
// document.getElementById("header").style.background = "linear-gradient(rgb(34, 2, 66), rgba(255, 255, 255, 0))";
}
// console.log("Scrolled: " + distanceScrolled);
}
/* Animação do caret do ícone de usuário */
let uMenu = document.getElementsByClassName("user-menu")[0];
uMenu.onmouseover = function() {
// function hover() {
// document.getElementById("drip").style.transform = "rotate(180deg)";
document.getElementsByClassName("fa-caret-down")[1].style.transform = "rotate(180deg)";
}
uMenu.onmouseout = function() {
// function reHover() {
// document.getElementById("drip").style.transform = "rotate(0)";
document.getElementsByClassName("fa-caret-down")[1].style.transform = "rotate(0)";
}
/* Animação da barra de busca */
let boxOne = document.getElementsByClassName("search-box")[0],
barOne = document.getElementsByClassName("search-bar")[0],
inputOne = document.getElementById("input-search");
window.addEventListener('click', function(e) {
if (document.getElementById("lupa").contains(e.target)) {
boxOne.classList.toggle("search-box-focused");
barOne.classList.toggle("search-bar-focused");
inputOne.focus();
} else {
boxOne.classList.remove("search-box-focused");
barOne.classList.remove("search-bar-focused");
}
})
/* Animação da logo do destaque e troca entre capa e vídeo */
// playBtn = document.getElementById("play")
let infoText = document.getElementById("info-text"),
playSign = document.getElementById("play-sign"),
playTrailer = document.getElementById("play-Trailer"),
mainGame = document.getElementsByClassName("main-game-logo"),
// mainGame = document.getElementById("main-game"),
// vidCover = document.getElementById("gvideo"),
vidCover = document.getElementsByClassName("vid-cover"),
imgCover = document.getElementsByClassName("img-cover"),
// imgCover = document.getElementById("main-cover"),
playBtn = document.getElementById("play");
playBtn.addEventListener("click", function() {
if (infoText.classList.contains("visuallyhidden")) {
vidCover[0].classList.toggle("hidden");
imgCover[0].classList.toggle("hidden");
playSign.classList.add("fa-play")
playSign.classList.remove("blink", "fa-pause");
playTrailer.innerHTML = "Trailer";
vidCover[0].pause();
vidCover[0].currentTime = 0;
// vidCover.load();
mainGame[1].style.transform = "scale(100%)", transitionDuration = "2s";
// mainGame.style.transitionDuration = "2s";
setTimeout(function() {
infoText.classList.remove("visuallyhidden");
}, 1000);
} else {
infoText.classList.add("visuallyhidden");
mainGame[1].style.transform = "scale(65%) translateY(8.5vw)";
mainGame[1].style.transitionDuration = "2s";
vidCover[0].classList.toggle("hidden");
imgCover[0].classList.toggle("hidden");
playSign.classList.add("blink", "fa-pause");
playSign.classList.remove("fa-play");
playTrailer.innerHTML = "Pausar";
vidCover[0].play();
vidCover[0].onended = function() {
vidCover[0].classList.toggle("hidden");
imgCover[0].classList.toggle("hidden");
mainGame[1].style.transform = "scale(100%)";
mainGame[1].style.transitionDuration = "2s";
playSign.classList.add("fa-play")
playSign.classList.remove("blink", "fa-pause");
playTrailer.innerHTML = "Trailer";
setTimeout(function() {
infoText.classList.remove("visuallyhidden");
}, 1000);
}
}
}, false);
/*Atribui a função "mudo" para o vídeo principal*/
let volMute = document.getElementById("vol-mute"),
mute = document.getElementById("mute");
mute.addEventListener("click", function() {
volMute.classList.toggle("fa-volume-mute");
if (vidCover[0].muted == false) {
vidCover[0].muted = true;
} else {
vidCover[0].muted = false;
}
}, false);
/*Carrega o vídeo ao abrir o menu "pop-up"*/
let fly = document.getElementsByClassName("fly-board")[0],
info = document.getElementById("info");
info.addEventListener("click", function() {
if (imgCover[1].classList.contains("hidden")) {
vidCover[1].play();
vidCover[1].currentTime = 13;
fly.style.display = "flex";
vidCover[1].onended = function() {
vidCover[1].classList.toggle("hidden");
imgCover[1].classList.toggle("hidden");
}
} else {
vidCover[1].pause();
vidCover[1].currentTime = 0;
vidCover[1].classList.add("hidden");
imgCover[1].classList.remove("hidden");
}
});
/*Atribui a função "mudo" para o vídeo da Janela*/
let volMute2 = document.getElementById("vol-mute2"),
mute2 = document.getElementById("mute2");
mute2.addEventListener("click", function() {
volMute2.classList.toggle("fa-volume-mute");
if (vidCover[1].muted == false) {
vidCover[1].muted = true;
} else {
vidCover[1].muted = false;
}
}, false);
/* Atribui a função fechar no botão da Janela*/
let close = document.getElementById("close");
close.addEventListener("click", function() {
if (fly.style.display != "none") {
vidCover[1].pause();
vidCover[1].currentTime = 0;
fly.style.display = "none";
}
}, false);
/* Captura o tamanho atual da Janela */
let w, h;
function displayWindowSize() {
w = document.documentElement.clientWidth;
h = document.documentElement.clientHeight;
// console.log("Width: " + w + ", " + "Height: " + h)
};
window.addEventListener("resize", displayWindowSize);
displayWindowSize();
// console.log(displayWindowSize);
/* Define a posição o background */
let bgd = document.getElementById("back"),
// flyBgd = document.getElementById("fly-back"),
mainCover = document.getElementById("main-cover");
function backgroundSize() {
// console.log(mainCover.clientHeight);
// console.log((h / 10) + "px");
// flyBgd.style.top = (h / 20) + "px";
setTimeout(function() {
bgd.style.top = (mainCover.clientHeight - (mainCover.clientHeight / 3.5)) + "px";
}, 500);
};
window.addEventListener("resize", backgroundSize);
backgroundSize(); | 32.604762 | 122 | 0.637359 |
6a02435772ee95f8f2c22000a0bfca6199ea4af0 | 1,263 | js | JavaScript | community-edition/getColumnState/updateWithShowingColumns.js | fattynoparents/reactdatagrid | 5b577e92d3364c5e4ae75b2b52225e5b28ec54aa | [
"MIT"
] | null | null | null | community-edition/getColumnState/updateWithShowingColumns.js | fattynoparents/reactdatagrid | 5b577e92d3364c5e4ae75b2b52225e5b28ec54aa | [
"MIT"
] | null | null | null | community-edition/getColumnState/updateWithShowingColumns.js | fattynoparents/reactdatagrid | 5b577e92d3364c5e4ae75b2b52225e5b28ec54aa | [
"MIT"
] | null | null | null | /**
* Copyright (c) INOVUA SOFTWARE TECHNOLOGIES.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import assign from 'object-assign';
import getShowingColumns from '../getShowingColumns';
export default (columns, props, state, context) => {
context = context || {};
const showingColumnsMap = assign(
context.showingColumnsMap,
getShowingColumns(columns, state.columnsMap)
);
const showingKeys = Object.keys(showingColumnsMap);
if (showingKeys.length) {
const showingColumn = showingColumnsMap[showingKeys[0]];
const duration =
showingColumn.showTransitionDuration !== undefined
? showingColumn.showTransitionDuration
: showingColumn.visibilityTransitionDuration;
columns = columns.map(c => {
const id = c.id || c.name;
c.inTransition = !!context.inTransition;
if (c.inTransition) {
c.inShowTransition = true;
}
if (!c.inTransition && showingColumnsMap[id]) {
c.width = 0;
c.minWidth = 0;
c.maxWidth = 0;
}
c.showTransitionDuration = duration;
c.visibilityTransitionDuration = duration;
return c;
});
}
return columns;
};
| 25.26 | 66 | 0.664291 |
6a0284c0b8a16660d13af6d9f44207912161d47c | 756 | js | JavaScript | src/applications/disability-benefits/all-claims/tests/config/submitForm.unit.spec.js | joshuakfarrar/vets-website | a7caaf71105ac780bb4caf9845721ea1c5d30cd0 | [
"CC0-1.0"
] | 241 | 2015-11-12T05:48:25.000Z | 2022-03-24T16:10:53.000Z | src/applications/disability-benefits/all-claims/tests/config/submitForm.unit.spec.js | joshuakfarrar/vets-website | a7caaf71105ac780bb4caf9845721ea1c5d30cd0 | [
"CC0-1.0"
] | 7,794 | 2015-11-11T20:15:51.000Z | 2022-03-31T20:19:59.000Z | src/applications/disability-benefits/all-claims/tests/config/submitForm.unit.spec.js | snowdensb/vets-website | ca255a4489b5c937cfb850ddee46dc5b8c99d85e | [
"CC0-1.0"
] | 137 | 2015-11-12T14:39:27.000Z | 2022-03-07T19:27:01.000Z | import { expect } from 'chai';
import sinon from 'sinon';
import formConfig from '../../config/form';
describe('Form 526 submit reject timer', () => {
let xhr;
beforeEach(() => {
xhr = sinon.useFakeXMLHttpRequest();
});
afterEach(() => {
global.XMLHttpRequest = window.XMLHttpRequest;
xhr.restore();
});
it('should trigger reject timer', async () => {
const blankFormConfig = {
chapters: {},
};
const form = {
pages: {
testing: {},
},
data: {
testing: 1,
},
};
return formConfig
.submit(form, blankFormConfig, { mode: 'testing' })
.catch(error => {
expect(error.message).to.eql('client_error: Request taking too long');
});
});
});
| 19.894737 | 78 | 0.548942 |
6a0307f0c12f7c72b08af7406095831a886589fa | 517 | js | JavaScript | JS Advanced/01. Syntax, Functions and Statements - Exercise/02. GreatestCommonDivisor.js | A-Manev/SoftUni-JavaScript | d1989e570f0b29112ab74f4921db3b79d19fff1d | [
"MIT"
] | 1 | 2021-04-12T10:11:28.000Z | 2021-04-12T10:11:28.000Z | JS Advanced/01. Syntax, Functions and Statements - Exercise/02. GreatestCommonDivisor.js | A-Manev/SoftUni-JavaScript | d1989e570f0b29112ab74f4921db3b79d19fff1d | [
"MIT"
] | null | null | null | JS Advanced/01. Syntax, Functions and Statements - Exercise/02. GreatestCommonDivisor.js | A-Manev/SoftUni-JavaScript | d1989e570f0b29112ab74f4921db3b79d19fff1d | [
"MIT"
] | 5 | 2021-01-20T21:51:20.000Z | 2022-03-05T16:12:35.000Z | function findGreatestDivisor(firstNumber, secondNumber) {
let greatestCommonDivisor;
for (let i = 1; i <= 9; i++) {
if (firstNumber % i == 0 && secondNumber % i == 0) {
greatestCommonDivisor = i;
}
}
console.log(greatestCommonDivisor);
}
findGreatestDivisor(15, 5);
findGreatestDivisor(2154, 458);
function solve(first, second) {
while(second !== 0){
let temp = first % second;
first = second;
second = temp;
}
console.log(first);
} | 21.541667 | 60 | 0.589942 |
6a036c885850292976fc8626255a7c02907b9962 | 272 | js | JavaScript | babel.config.js | MichaelDurfey/bloomingcats | 1397bc52551d6c9453a72164a4145b55bf46a042 | [
"MIT"
] | null | null | null | babel.config.js | MichaelDurfey/bloomingcats | 1397bc52551d6c9453a72164a4145b55bf46a042 | [
"MIT"
] | 1 | 2021-08-15T05:42:54.000Z | 2021-08-15T05:42:54.000Z | babel.config.js | MichaelDurfey/bloomingcats | 1397bc52551d6c9453a72164a4145b55bf46a042 | [
"MIT"
] | null | null | null | module.exports = (api) => {
api.cache(false);
return {
presets: [
[
'@babel/env',
{
targets: { node: 'current' },
},
],
'@babel/preset-react',
],
plugins: [
'@loadable/babel-plugin',
],
};
};
| 15.111111 | 39 | 0.404412 |
6a0494c8ca78d217b3c6fc79e5fab48960a14915 | 985 | js | JavaScript | popup.js | sutter/css-debug-alignement | 397a72198381491d4da3ee818b946539ea1211db | [
"MIT"
] | null | null | null | popup.js | sutter/css-debug-alignement | 397a72198381491d4da3ee818b946539ea1211db | [
"MIT"
] | null | null | null | popup.js | sutter/css-debug-alignement | 397a72198381491d4da3ee818b946539ea1211db | [
"MIT"
] | null | null | null | function click(e) {
chrome.tabs.executeScript(null, {
code:
"if(document.getElementById('debugCSS')){document.getElementById('debugCSS').remove()} ;var box = document.body.appendChild(document.createElement('div')); box.id = 'debugCSS'; box.innerHTML+= '<style>*, *:before, *:after {background: " +
e.target.getAttribute("data-colorAlpha") +
" !important;box-shadow: inset 0 0 0 1px " +
e.target.getAttribute("data-color") +
" !important;}</style>'",
});
window.close();
}
function destroy(e) {
chrome.tabs.executeScript(null, {
code: "document.getElementById('debugCSS').remove()",
});
window.close();
}
document.addEventListener("DOMContentLoaded", function() {
var divs = document.querySelectorAll(".js-activeColor");
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener("click", click);
}
var destroyDebugCSS = document.getElementById("remove");
destroyDebugCSS.addEventListener("click", destroy);
});
| 33.965517 | 244 | 0.66802 |
6a0510e5e269c58e73ec168426bb30bc55a3bbcf | 5,446 | js | JavaScript | src/Tree/Tree.js | Software-Eng-THU-2015/pacific-rim | e969d1d9924f4756c2e57c1a68e826923ebfdc33 | [
"MIT"
] | null | null | null | src/Tree/Tree.js | Software-Eng-THU-2015/pacific-rim | e969d1d9924f4756c2e57c1a68e826923ebfdc33 | [
"MIT"
] | 3 | 2020-06-05T17:06:59.000Z | 2021-06-10T17:54:44.000Z | src/Tree/Tree.js | Software-Eng-THU-2015/pacific-rim | e969d1d9924f4756c2e57c1a68e826923ebfdc33 | [
"MIT"
] | 1 | 2015-11-04T14:26:52.000Z | 2015-11-04T14:26:52.000Z | import React, { Component } from 'react';
// import AddPlan from './AddPlan';
import moment from 'moment';
export default class Tree extends Component{
constructor(props){
super(props);
}
componentDidMount(){
/*var level_list = '{ "level_list2" : [' +
'{"level":0, "name":"树芽"},' +
'{"level":1, "name":"青树苗"},' +
'{"level":2, "name":"小树"},' +
'{"level":3, "name":"初生之树"},' +
'{"level":4, "name":"弱冠之树"},' +
'{"level":5, "name":"拔地之树"},' +
'{"level":6, "name":"凌云之树"},' +
'{"level":7, "name":"通天之树"},' +
'{"level":8, "name":"银河之树"},' +
'{"level":9, "name":"寰宇之树"} ]}';*/
var level_list = [
{"level":0, "name":"树芽"},
{"level":1, "name":"青树苗"},
{"level":2, "name":"小树"},
{"level":3, "name":"初生之树"},
{"level":4, "name":"弱冠之树"},
{"level":5, "name":"拔地之树"},
{"level":6, "name":"凌云之树"},
{"level":7, "name":"通天之树"},
{"level":8, "name":"银河之树"},
{"level":9, "name":"寰宇之树"}
];
var level = 0;
var height = 0;
var health = 0;
var water = 0;
var fertilizer = 0;
var level_name = "树芽";
var nowDate = new Date();
var myopenid;
function getTree(){
$.getJSON("/apis/get_tree", {openid: myopenid}, function(data){
level = data.level;
height = data.height;
health = data.health;
water = data.water;
fertilizer = data.fertilizer;
if(nowDate.getHours() < 6 && nowDate.getHours() >1) {//for night
$("#img").attr("src", "/img/"+level+"0.png")
}else {//for day
$("#img").attr("src", "/img/"+level+"1.png")
}
console.log(0);
if(level == 0)
level_name = "树芽";
else if(level == 1)
level_name = "青树苗";
else if(level == 2)
level_name = "小树";
else if(level == 3)
level_name = "初生之树";
else if(level == 4)
level_name = "弱冠之树";
else if(level == 5)
level_name = "拔地之树";
else if(level == 6)
level_name = "凌云之树";
else if(level == 7)
level_name = "通天之树";
else if(level == 8)
level_name = "银河之树";
else if(level == 9)
level_name = "寰宇之树";
/*
var obj = JSON.parse(level_list);
level_name = level_list[level].name;
*/
console.log(1);
$("#level").html("lv"+level+" : "+level_name+"");
$("#health").html("健康度: "+ health);
$("#height").html("高度: "+ height);
$("#show_water").html("剩余浇水次数: "+ water+"次");
$("#show_fertilizer").text("剩余施肥次数: " + fertilizer + "次");
console.log(2);
});
}
function getOpenid(){
var _code;
var reg = new RegExp("(^|&)code=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r!=null){
_code = unescape(r[2]);
}
else
_code = "";
$.getJSON("/apis/getOpenid", {code: _code}, function(data){
myopenid = data.openid;
getTree();
});
}
getOpenid();
var self = this;
$("#water").click(function(){
if(water <= 0){
alert("no more water to pour!");
}else{
var id = self.props.params.id;
var url = '/apis/care_tree';
$.post(url, {openid: myopenid,
water: true,
fertilizer: false},
function(){
alert("浇水成功!");
getTree();
});
}
});
$("#fertilizer").click(function(){
if(fertilizer <= 0){
alert("no more fertilizer to feed!");
}else{
var id = self.props.params.id;
var url = '/apis/care_tree';
$.post(url, {openid: myopenid,
water: false,
fertilizer: true},
function(){
alert("施肥成功!");
getTree();
});
}
});
}
render(){
return(
<div>
<div className="col-xs-12 label label-primary" style={{"padding":"10px 10px 10px 10px"}}>
<h1>Tree</h1>
</div>
<<<<<<< HEAD
<div className="col-xs-12" style={{"padding":"10px 10px 10px 10px"}}>
<img id="img" className="ui small left floated image"/>
=======
<div className="col-xs-12">
<img id="img" className="ui small left floated image" style = {{"width": "45%"}}/>
>>>>>>> f34bb463c491691431c2f0e4cd28e21bfc432ae0
<div>
<p className="item level" id = "level">
</p>
<p className="item health" id = "health">
</p>
<p className="item height" id = "height">
</p>
</div>
</div>
<div className="col-xs-12 label label-default" style={{"padding":"10px 10px 10px 10px"}}>
<div className="col-xs-6">
<div className="item water" id = "show_water">
</div>
<input type="submit" className="ui button" id="water" value="浇水" />
</div>
<div className="cocol-xs-6">
<div className="item fertilizer" id = "show_fertilizer">
</div>
<input type="submit" className="ui button" id="fertilizer" value="施肥" />
</div>
</div>
<div className="col-xs-12 label label-success" style={{"padding":"10px 10px 10px 10px"}}>
<h5>
生命之树生长规则:完成每日打卡,奖浇水机会一次<br/>
完成每日挑战任务(每日一个),奖施肥或浇水机会一次<br/>
设健康度为x(0到10,初始为10)<br/>
施肥:x大于等于6时,树高度增加2cm;<br/>x小于6的时候,树高度增加0.4*x cm;<br/>增加一点健康度(上限10)<br/>
浇水:x大于等于6时,树高度增加1cm;<br/>x小于6的时候,树高度增加0.2*x cm;<br/>增加一点健康度(上限10)<br/>
每日0点,所有树健康度降低1点,最低到0<br/>
</h5>
</div>
</div>
)
}
}
| 26.696078 | 101 | 0.502387 |
6a0525ff48f532c6626a0bd5cfc1bf7dd820ec30 | 66 | js | JavaScript | test/configCases/entry/issue-12562/home.js | fourstash/webpack | f07a3b82327f4f7894500595f6619c7880eb31a7 | [
"MIT"
] | 66,493 | 2015-01-01T02:28:31.000Z | 2022-03-31T23:46:51.000Z | test/configCases/entry/issue-12562/home.js | takhello/webpack | f3dce69e9df5f778fb4850662b0f16f9fd9951d2 | [
"MIT"
] | 14,141 | 2015-01-01T21:00:12.000Z | 2022-03-31T23:59:55.000Z | test/configCases/entry/issue-12562/home.js | takhello/webpack | f3dce69e9df5f778fb4850662b0f16f9fd9951d2 | [
"MIT"
] | 11,585 | 2015-01-01T02:28:31.000Z | 2022-03-31T19:47:10.000Z | import log from "./log";
log("Hi");
it("should load", () => {});
| 13.2 | 28 | 0.5 |
6a056c7ff67b6de2be83329ddf522e69d62e0c1b | 800 | js | JavaScript | ui/src/index.js | jimmycrequer/roth-2019 | 33dac27e7d203c0ca9d5ea60abe365eed200eb45 | [
"Apache-2.0"
] | 7 | 2019-10-08T11:48:20.000Z | 2021-05-31T04:20:42.000Z | ui/src/index.js | andychan94/roth-2019 | 33dac27e7d203c0ca9d5ea60abe365eed200eb45 | [
"Apache-2.0"
] | 11 | 2020-09-07T07:06:46.000Z | 2022-02-26T17:39:38.000Z | ui/src/index.js | jimmycrequer/roth-2019 | 33dac27e7d203c0ca9d5ea60abe365eed200eb45 | [
"Apache-2.0"
] | 1 | 2019-09-18T08:55:38.000Z | 2019-09-18T08:55:38.000Z | import React from "react";
import ReactDOM from "react-dom";
import {Route, BrowserRouter as Router} from 'react-router-dom'
import "./index.css";
import registerServiceWorker from "./registerServiceWorker";
import ApolloClient from "apollo-boost";
import {ApolloProvider} from "react-apollo";
import NameInputPage from "./NameInputPage";
import QuizPage from "./QuizPage";
const client = new ApolloClient({
uri: process.env.REACT_APP_GRAPHQL_URI
});
const Main = () => (
<ApolloProvider client={client}>
<Router>
<div>
<Route exact={true} path="/" component={NameInputPage}/>
<Route exact={true} path="/quiz" component={QuizPage}/>
</div>
</Router>
</ApolloProvider>
);
ReactDOM.render(<Main/>, document.getElementById("root"));
registerServiceWorker();
| 28.571429 | 64 | 0.70375 |
6a05c31efaa9d46aec34aceb75cec79cd33ece99 | 29,716 | js | JavaScript | node_modules/d3/node_modules/d3-geo/build/d3-geo.min.js | malaneti/Genomes | fd68141497635b8a05196206c0bdc4695f4cba5c | [
"MIT"
] | 1 | 2016-08-10T18:36:24.000Z | 2016-08-10T18:36:24.000Z | node_modules/d3-geo/build/d3-geo.min.js | steinernein/deckbuilder | a794db23fca11d873cf78dbc3ec6521f271392e3 | [
"MIT"
] | 2 | 2016-07-12T17:28:21.000Z | 2016-07-12T17:52:17.000Z | node_modules/d3-geo/build/d3-geo.min.js | steinernein/deckbuilder | a794db23fca11d873cf78dbc3ec6521f271392e3 | [
"MIT"
] | null | null | null | // https://d3js.org/d3-geo/ Version 1.1.0. Copyright 2016 Mike Bostock.
!function(n,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("d3-array")):"function"==typeof define&&define.amd?define(["exports","d3-array"],t):t(n.d3=n.d3||{},n.d3)}(this,function(n,t){"use strict";function r(){return new i}function i(){this.reset()}function e(n,t,r){var i=n.s=t+r,e=i-t,o=i-e;n.t=t-o+(r-e)}function o(n){return n>1?0:-1>n?hr:Math.acos(n)}function u(n){return n>1?dr:-1>n?-dr:Math.asin(n)}function a(n){return(n=Cr(n/2))*n}function c(){}function l(n,t){n&&Or.hasOwnProperty(n.type)&&Or[n.type](n,t)}function f(n,t,r){var i,e=-1,o=n.length-r;for(t.lineStart();++e<o;)i=n[e],t.point(i[0],i[1],i[2]);t.lineEnd()}function p(n,t){var r=-1,i=n.length;for(t.polygonStart();++r<i;)f(n[r],t,1);t.polygonEnd()}function s(n,t){n&&Lr.hasOwnProperty(n.type)?Lr[n.type](n,t):l(n,t)}function g(){Tr.point=h}function v(){d(Ot,Tt)}function h(n,t){Tr.point=d,Ot=n,Tt=t,n*=mr,t*=mr,Gt=n,Ft=wr(t=t/2+Er),It=Cr(t)}function d(n,t){n*=mr,t*=mr,t=t/2+Er;var r=n-Gt,i=r>=0?1:-1,e=i*r,o=wr(t),u=Cr(t),a=It*u,c=Ft*o+a*wr(e),l=a*i*Cr(e);bt.add(Nr(l,c)),Gt=n,Ft=o,It=u}function E(n){return Lt?Lt.reset():(Lt=r(),bt=r()),s(n,Tr),2*Lt}function S(n){return[Nr(n[1],n[0]),u(n[2])]}function y(n){var t=n[0],r=n[1],i=wr(r);return[i*wr(t),i*Cr(t),Cr(r)]}function m(n,t){return n[0]*t[0]+n[1]*t[1]+n[2]*t[2]}function M(n,t){return[n[1]*t[2]-n[2]*t[1],n[2]*t[0]-n[0]*t[2],n[0]*t[1]-n[1]*t[0]]}function x(n,t){n[0]+=t[0],n[1]+=t[1],n[2]+=t[2]}function N(n,t){return[n[0]*t,n[1]*t,n[2]*t]}function w(n){var t=zr(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);n[0]/=t,n[1]/=t,n[2]/=t}function R(n,t){Qt.push(Vt=[_t=n,Dt=n]),Bt>t&&(Bt=t),t>Ut&&(Ut=t)}function A(n,t){var r=y([n*mr,t*mr]);if(Jt){var i=M(Jt,r),e=[i[1],-i[0],0],o=M(e,i);w(o),o=S(o);var u,a=n-Zt,c=a>0?1:-1,l=o[0]*yr*c,f=Mr(a)>180;f^(l>c*Zt&&c*n>l)?(u=o[1]*yr,u>Ut&&(Ut=u)):(l=(l+360)%360-180,f^(l>c*Zt&&c*n>l)?(u=-o[1]*yr,Bt>u&&(Bt=u)):(Bt>t&&(Bt=t),t>Ut&&(Ut=t))),f?Zt>n?b(_t,n)>b(_t,Dt)&&(Dt=n):b(n,Dt)>b(_t,Dt)&&(_t=n):Dt>=_t?(_t>n&&(_t=n),n>Dt&&(Dt=n)):n>Zt?b(_t,n)>b(_t,Dt)&&(Dt=n):b(n,Dt)>b(_t,Dt)&&(_t=n)}else R(n,t);Jt=r,Zt=n}function j(){Gr.point=A}function P(){Vt[0]=_t,Vt[1]=Dt,Gr.point=R,Jt=null}function C(n,t){if(Jt){var r=n-Zt;Kt.add(Mr(r)>180?r+(r>0?360:-360):r)}else kt=n,Ht=t;Tr.point(n,t),A(n,t)}function q(){Tr.lineStart()}function z(){C(kt,Ht),Tr.lineEnd(),Mr(Kt)>gr&&(_t=-(Dt=180)),Vt[0]=_t,Vt[1]=Dt,Jt=null}function b(n,t){return(t-=n)<0?t+360:t}function L(n,t){return n[0]-t[0]}function O(n,t){return n[0]<=n[1]?n[0]<=t&&t<=n[1]:t<n[0]||n[1]<t}function T(n){var t,i,e,o,u,a,c;if(Kt?Kt.reset():Kt=r(),Ut=Dt=-(_t=Bt=1/0),Qt=[],s(n,Gr),i=Qt.length){for(Qt.sort(L),t=1,e=Qt[0],u=[e];i>t;++t)o=Qt[t],O(e,o[0])||O(e,o[1])?(b(e[0],o[1])>b(e[0],e[1])&&(e[1]=o[1]),b(o[0],e[1])>b(e[0],e[1])&&(e[0]=o[0])):u.push(e=o);for(a=-(1/0),i=u.length-1,t=0,e=u[i];i>=t;e=o,++t)o=u[t],(c=b(e[1],o[0]))>a&&(a=c,_t=o[0],Dt=e[1])}return Qt=Vt=null,_t===1/0||Bt===1/0?[[NaN,NaN],[NaN,NaN]]:[[_t,Bt],[Dt,Ut]]}function G(n,t){n*=mr,t*=mr;var r=wr(t);F(r*wr(n),r*Cr(n),Cr(t))}function F(n,t,r){++Wt,Yt+=(n-Yt)/Wt,$t+=(t-$t)/Wt,nr+=(r-nr)/Wt}function I(){Fr.point=_}function _(n,t){n*=mr,t*=mr;var r=wr(t);lr=r*wr(n),fr=r*Cr(n),pr=Cr(t),Fr.point=B,F(lr,fr,pr)}function B(n,t){n*=mr,t*=mr;var r=wr(t),i=r*wr(n),e=r*Cr(n),o=Cr(t),u=Nr(zr((u=fr*o-pr*e)*u+(u=pr*i-lr*o)*u+(u=lr*e-fr*i)*u),lr*i+fr*e+pr*o);Xt+=u,tr+=u*(lr+(lr=i)),rr+=u*(fr+(fr=e)),ir+=u*(pr+(pr=o)),F(lr,fr,pr)}function D(){Fr.point=G}function U(){Fr.point=k}function Z(){H(ar,cr),Fr.point=G}function k(n,t){ar=n,cr=t,n*=mr,t*=mr,Fr.point=H;var r=wr(t);lr=r*wr(n),fr=r*Cr(n),pr=Cr(t),F(lr,fr,pr)}function H(n,t){n*=mr,t*=mr;var r=wr(t),i=r*wr(n),e=r*Cr(n),u=Cr(t),a=fr*u-pr*e,c=pr*i-lr*u,l=lr*e-fr*i,f=zr(a*a+c*c+l*l),p=lr*i+fr*e+pr*u,s=f&&-o(p)/f,g=Nr(f,p);er+=s*a,or+=s*c,ur+=s*l,Xt+=g,tr+=g*(lr+(lr=i)),rr+=g*(fr+(fr=e)),ir+=g*(pr+(pr=u)),F(lr,fr,pr)}function J(n){Wt=Xt=Yt=$t=nr=tr=rr=ir=er=or=ur=0,s(n,Fr);var t=er,r=or,i=ur,e=t*t+r*r+i*i;return vr>e&&(t=tr,r=rr,i=ir,gr>Xt&&(t=Yt,r=$t,i=nr),e=t*t+r*r+i*i,vr>e)?[NaN,NaN]:[Nr(r,t)*yr,u(i/zr(e))*yr]}function K(n){return function(){return n}}function Q(n,t){function r(r,i){return r=n(r,i),t(r[0],r[1])}return n.invert&&t.invert&&(r.invert=function(r,i){return r=t.invert(r,i),r&&n.invert(r[0],r[1])}),r}function V(n,t){return[n>hr?n-Sr:-hr>n?n+Sr:n,t]}function W(n,t,r){return(n%=Sr)?t||r?Q(Y(n),$(t,r)):Y(n):t||r?$(t,r):V}function X(n){return function(t,r){return t+=n,[t>hr?t-Sr:-hr>t?t+Sr:t,r]}}function Y(n){var t=X(n);return t.invert=X(-n),t}function $(n,t){function r(n,t){var r=wr(t),c=wr(n)*r,l=Cr(n)*r,f=Cr(t),p=f*i+c*e;return[Nr(l*o-p*a,c*i-f*e),u(p*o+l*a)]}var i=wr(n),e=Cr(n),o=wr(t),a=Cr(t);return r.invert=function(n,t){var r=wr(t),c=wr(n)*r,l=Cr(n)*r,f=Cr(t),p=f*o-l*a;return[Nr(l*o+f*a,c*i+p*e),u(p*i-c*e)]},r}function nn(n){function t(t){return t=n(t[0]*mr,t[1]*mr),t[0]*=yr,t[1]*=yr,t}return n=W(n[0]*mr,n[1]*mr,n.length>2?n[2]*mr:0),t.invert=function(t){return t=n.invert(t[0]*mr,t[1]*mr),t[0]*=yr,t[1]*=yr,t},t}function tn(n,t,r,i,e,o){if(r){var u=wr(t),a=Cr(t),c=i*r;null==e?(e=t+i*Sr,o=t-c/2):(e=rn(u,e),o=rn(u,o),(i>0?o>e:e>o)&&(e+=i*Sr));for(var l,f=e;i>0?f>o:o>f;f-=c)l=S([u,-a*wr(f),-a*Cr(f)]),n.point(l[0],l[1])}}function rn(n,t){t=y(t),t[0]-=n,w(t);var r=o(-t[1]);return((-t[2]<0?-r:r)+Sr-gr)%Sr}function en(){function n(n,t){r.push(n=i(n,t)),n[0]*=yr,n[1]*=yr}function t(){var n=e.apply(this,arguments),t=o.apply(this,arguments)*mr,c=u.apply(this,arguments)*mr;return r=[],i=W(-n[0]*mr,-n[1]*mr,0).invert,tn(a,t,c,1),n={type:"Polygon",coordinates:[r]},r=i=null,n}var r,i,e=K([0,0]),o=K(90),u=K(6),a={point:n};return t.center=function(n){return arguments.length?(e="function"==typeof n?n:K([+n[0],+n[1]]),t):e},t.radius=function(n){return arguments.length?(o="function"==typeof n?n:K(+n),t):o},t.precision=function(n){return arguments.length?(u="function"==typeof n?n:K(+n),t):u},t}function on(){var n,t=[];return{point:function(t,r){n.push([t,r])},lineStart:function(){t.push(n=[])},lineEnd:c,rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))},result:function(){var r=t;return t=[],n=null,r}}}function un(n,t,r,i,e,o){var u,a=n[0],c=n[1],l=t[0],f=t[1],p=0,s=1,g=l-a,v=f-c;if(u=r-a,g||!(u>0)){if(u/=g,0>g){if(p>u)return;s>u&&(s=u)}else if(g>0){if(u>s)return;u>p&&(p=u)}if(u=e-a,g||!(0>u)){if(u/=g,0>g){if(u>s)return;u>p&&(p=u)}else if(g>0){if(p>u)return;s>u&&(s=u)}if(u=i-c,v||!(u>0)){if(u/=v,0>v){if(p>u)return;s>u&&(s=u)}else if(v>0){if(u>s)return;u>p&&(p=u)}if(u=o-c,v||!(0>u)){if(u/=v,0>v){if(u>s)return;u>p&&(p=u)}else if(v>0){if(p>u)return;s>u&&(s=u)}return p>0&&(n[0]=a+p*g,n[1]=c+p*v),1>s&&(t[0]=a+s*g,t[1]=c+s*v),!0}}}}}function an(n,t){return Mr(n[0]-t[0])<gr&&Mr(n[1]-t[1])<gr}function cn(n,t,r,i){this.x=n,this.z=t,this.o=r,this.e=i,this.v=!1,this.n=this.p=null}function ln(n,t,r,i,e){var o,u,a=[],c=[];if(n.forEach(function(n){if(!((t=n.length-1)<=0)){var t,r,i=n[0],u=n[t];if(an(i,u)){for(e.lineStart(),o=0;t>o;++o)e.point((i=n[o])[0],i[1]);return void e.lineEnd()}a.push(r=new cn(i,n,null,!0)),c.push(r.o=new cn(i,null,r,!1)),a.push(r=new cn(u,n,null,!1)),c.push(r.o=new cn(u,null,r,!0))}}),a.length){for(c.sort(t),fn(a),fn(c),o=0,u=c.length;u>o;++o)c[o].e=r=!r;for(var l,f,p=a[0];;){for(var s=p,g=!0;s.v;)if((s=s.n)===p)return;l=s.z,e.lineStart();do{if(s.v=s.o.v=!0,s.e){if(g)for(o=0,u=l.length;u>o;++o)e.point((f=l[o])[0],f[1]);else i(s.x,s.n.x,1,e);s=s.n}else{if(g)for(l=s.p.z,o=l.length-1;o>=0;--o)e.point((f=l[o])[0],f[1]);else i(s.x,s.p.x,-1,e);s=s.p}s=s.o,l=s.z,g=!g}while(!s.v);e.lineEnd()}}}function fn(n){if(t=n.length){for(var t,r,i=0,e=n[0];++i<t;)e.n=r=n[i],r.p=e,e=r;e.n=r=n[0],r.p=e}}function pn(n,r,i,e){function o(t,o){return t>=n&&i>=t&&o>=r&&e>=o}function u(t,o,u,c){var f=0,p=0;if(null==t||(f=a(t,u))!==(p=a(o,u))||l(t,o)<0^u>0){do c.point(0===f||3===f?n:i,f>1?e:r);while((f=(f+u+4)%4)!==p)}else c.point(o[0],o[1])}function a(t,e){return Mr(t[0]-n)<gr?e>0?0:3:Mr(t[0]-i)<gr?e>0?2:1:Mr(t[1]-r)<gr?e>0?1:0:e>0?3:2}function c(n,t){return l(n.x,t.x)}function l(n,t){var r=a(n,1),i=a(t,1);return r!==i?r-i:0===r?t[1]-n[1]:1===r?n[0]-t[0]:2===r?n[1]-t[1]:t[0]-n[0]}return function(a){function l(n,t){o(n,t)&&j.point(n,t)}function f(){for(var t=0,r=0,i=E.length;i>r;++r)for(var o,u,a=E[r],c=1,l=a.length,f=a[0],p=f[0],s=f[1];l>c;++c)o=p,u=s,f=a[c],p=f[0],s=f[1],e>=u?s>e&&(p-o)*(e-u)>(s-u)*(n-o)&&++t:e>=s&&(s-u)*(n-o)>(p-o)*(e-u)&&--t;return t}function p(){j=P,d=[],E=[],A=!0}function s(){var n=f(),r=A&&n,i=(d=t.merge(d)).length;(r||i)&&(a.polygonStart(),r&&(a.lineStart(),u(null,null,1,a),a.lineEnd()),i&&ln(d,c,n,u,a),a.polygonEnd()),j=a,d=E=S=null}function g(){C.point=h,E&&E.push(S=[]),R=!0,w=!1,x=N=NaN}function v(){d&&(h(y,m),M&&w&&P.rejoin(),d.push(P.result())),C.point=l,w&&j.lineEnd()}function h(t,u){var a=o(t,u);if(E&&S.push([t,u]),R)y=t,m=u,M=a,R=!1,a&&(j.lineStart(),j.point(t,u));else if(a&&w)j.point(t,u);else{var c=[x=Math.max(Xr,Math.min(Wr,x)),N=Math.max(Xr,Math.min(Wr,N))],l=[t=Math.max(Xr,Math.min(Wr,t)),u=Math.max(Xr,Math.min(Wr,u))];un(c,l,n,r,i,e)?(w||(j.lineStart(),j.point(c[0],c[1])),j.point(l[0],l[1]),a||j.lineEnd(),A=!1):a&&(j.lineStart(),j.point(t,u),A=!1)}x=t,N=u,w=a}var d,E,S,y,m,M,x,N,w,R,A,j=a,P=on(),C={point:l,lineStart:g,lineEnd:v,polygonStart:p,polygonEnd:s};return C}}function sn(){var n,t,r,i=0,e=0,o=960,u=500;return r={stream:function(r){return n&&t===r?n:n=pn(i,e,o,u)(t=r)},extent:function(a){return arguments.length?(i=+a[0][0],e=+a[0][1],o=+a[1][0],u=+a[1][1],n=t=null,r):[[i,e],[o,u]]}}}function gn(){Yr.point=hn,Yr.lineEnd=vn}function vn(){Yr.point=Yr.lineEnd=c}function hn(n,t){n*=mr,t*=mr,_r=n,Br=Cr(t),Dr=wr(t),Yr.point=dn}function dn(n,t){n*=mr,t*=mr;var r=Cr(t),i=wr(t),e=Mr(n-_r),o=wr(e),u=Cr(e),a=i*u,c=Dr*r-Br*i*o,l=Br*r+Dr*i*o;Ir.add(Nr(zr(a*a+c*c),l)),_r=n,Br=r,Dr=i}function En(n){return Ir?Ir.reset():Ir=r(),s(n,Yr),+Ir}function Sn(n,t){return $r[0]=n,$r[1]=t,En(ni)}function yn(n,r,i){var e=t.range(n,r-gr,i).concat(r);return function(n){return e.map(function(t){return[n,t]})}}function mn(n,r,i){var e=t.range(n,r-gr,i).concat(r);return function(n){return e.map(function(t){return[t,n]})}}function Mn(){function n(){return{type:"MultiLineString",coordinates:r()}}function r(){return t.range(Rr(u/E)*E,o,E).map(g).concat(t.range(Rr(f/S)*S,l,S).map(v)).concat(t.range(Rr(e/h)*h,i,h).filter(function(n){return Mr(n%E)>gr}).map(p)).concat(t.range(Rr(c/d)*d,a,d).filter(function(n){return Mr(n%S)>gr}).map(s))}var i,e,o,u,a,c,l,f,p,s,g,v,h=10,d=h,E=90,S=360,y=2.5;return n.lines=function(){return r().map(function(n){return{type:"LineString",coordinates:n}})},n.outline=function(){return{type:"Polygon",coordinates:[g(u).concat(v(l).slice(1),g(o).reverse().slice(1),v(f).reverse().slice(1))]}},n.extent=function(t){return arguments.length?n.extentMajor(t).extentMinor(t):n.extentMinor()},n.extentMajor=function(t){return arguments.length?(u=+t[0][0],o=+t[1][0],f=+t[0][1],l=+t[1][1],u>o&&(t=u,u=o,o=t),f>l&&(t=f,f=l,l=t),n.precision(y)):[[u,f],[o,l]]},n.extentMinor=function(t){return arguments.length?(e=+t[0][0],i=+t[1][0],c=+t[0][1],a=+t[1][1],e>i&&(t=e,e=i,i=t),c>a&&(t=c,c=a,a=t),n.precision(y)):[[e,c],[i,a]]},n.step=function(t){return arguments.length?n.stepMajor(t).stepMinor(t):n.stepMinor()},n.stepMajor=function(t){return arguments.length?(E=+t[0],S=+t[1],n):[E,S]},n.stepMinor=function(t){return arguments.length?(h=+t[0],d=+t[1],n):[h,d]},n.precision=function(t){return arguments.length?(y=+t,p=yn(c,a,90),s=mn(e,i,y),g=yn(f,l,90),v=mn(u,o,y),n):y},n.extentMajor([[-180,-90+gr],[180,90-gr]]).extentMinor([[-180,-80-gr],[180,80+gr]])}function xn(n,t){var r=n[0]*mr,i=n[1]*mr,e=t[0]*mr,o=t[1]*mr,c=wr(i),l=Cr(i),f=wr(o),p=Cr(o),s=c*wr(r),g=c*Cr(r),v=f*wr(e),h=f*Cr(e),d=2*u(zr(a(o-i)+c*f*a(e-r))),E=Cr(d),S=d?function(n){var t=Cr(n*=d)/E,r=Cr(d-n)/E,i=r*s+t*v,e=r*g+t*h,o=r*l+t*p;return[Nr(e,i)*yr,Nr(o,zr(i*i+e*e))*yr]}:function(){return[r*yr,i*yr]};return S.distance=d,S}function Nn(n){return n}function wn(){ii.point=Rn}function Rn(n,t){ii.point=An,Ur=kr=n,Zr=Hr=t}function An(n,t){ri.add(Hr*n-kr*t),kr=n,Hr=t}function jn(){An(Ur,Zr)}function Pn(n,t){ei>n&&(ei=n),n>ui&&(ui=n),oi>t&&(oi=t),t>ai&&(ai=t)}function Cn(n,t){li+=n,fi+=t,++pi}function qn(){Si.point=zn}function zn(n,t){Si.point=bn,Cn(Qr=n,Vr=t)}function bn(n,t){var r=n-Qr,i=t-Vr,e=zr(r*r+i*i);si+=e*(Qr+n)/2,gi+=e*(Vr+t)/2,vi+=e,Cn(Qr=n,Vr=t)}function Ln(){Si.point=Cn}function On(){Si.point=Gn}function Tn(){Fn(Jr,Kr)}function Gn(n,t){Si.point=Fn,Cn(Jr=Qr=n,Kr=Vr=t)}function Fn(n,t){var r=n-Qr,i=t-Vr,e=zr(r*r+i*i);si+=e*(Qr+n)/2,gi+=e*(Vr+t)/2,vi+=e,e=Vr*n-Qr*t,hi+=e*(Qr+n),di+=e*(Vr+t),Ei+=3*e,Cn(Qr=n,Vr=t)}function In(n){function t(t,r){n.moveTo(t+u,r),n.arc(t,r,u,0,Sr)}function r(t,r){n.moveTo(t,r),a.point=i}function i(t,r){n.lineTo(t,r)}function e(){a.point=t}function o(){n.closePath()}var u=4.5,a={point:t,lineStart:function(){a.point=r},lineEnd:e,polygonStart:function(){a.lineEnd=o},polygonEnd:function(){a.lineEnd=e,a.point=t},pointRadius:function(n){return u=n,a},result:c};return a}function _n(){function n(n,t){a.push("M",n,",",t,u)}function t(n,t){a.push("M",n,",",t),c.point=r}function r(n,t){a.push("L",n,",",t)}function i(){c.point=t}function e(){c.point=n}function o(){a.push("Z")}var u=Bn(4.5),a=[],c={point:n,lineStart:i,lineEnd:e,polygonStart:function(){c.lineEnd=o},polygonEnd:function(){c.lineEnd=e,c.point=n},pointRadius:function(n){return u=Bn(n),c},result:function(){if(a.length){var n=a.join("");return a=[],n}}};return c}function Bn(n){return"m0,"+n+"a"+n+","+n+" 0 1,1 0,"+-2*n+"a"+n+","+n+" 0 1,1 0,"+2*n+"z"}function Dn(){function n(n){return n&&("function"==typeof o&&e.pointRadius(+o.apply(this,arguments)),s(n,r(e))),e.result()}var t,r,i,e,o=4.5;return n.area=function(n){return s(n,r(ii)),ii.result()},n.bounds=function(n){return s(n,r(ci)),ci.result()},n.centroid=function(n){return s(n,r(Si)),Si.result()},n.projection=function(i){return arguments.length?(r=null==(t=i)?Nn:i.stream,n):t},n.context=function(t){return arguments.length?(e=null==(i=t)?new _n:new In(t),"function"!=typeof o&&e.pointRadius(o),n):i},n.pointRadius=function(t){return arguments.length?(o="function"==typeof t?t:(e.pointRadius(+t),+t),n):o},n.projection(null).context(null)}function Un(n,t){for(var r=t[0],i=t[1],e=[Cr(r),-wr(r),0],o=0,a=0,c=0,l=n.length;l>c;++c)if(p=(f=n[c]).length)for(var f,p,s=f[p-1],g=s[0],v=s[1]/2+Er,h=Cr(v),d=wr(v),E=0;p>E;++E,g=m,h=N,d=R,s=S){var S=f[E],m=S[0],x=S[1]/2+Er,N=Cr(x),R=wr(x),A=m-g,j=A>=0?1:-1,P=j*A,C=P>hr,q=h*N;if(yi.add(Nr(q*j*Cr(P),d*R+q*wr(P))),o+=C?A+j*Sr:A,C^g>=r^m>=r){var z=M(y(s),y(S));w(z);var b=M(e,z);w(b);var L=(C^A>=0?-1:1)*u(b[2]);(i>L||i===L&&(z[0]||z[1]))&&(a+=C^A>=0?1:-1)}}var O=(-gr>o||gr>o&&-gr>yi)^1&a;return yi.reset(),O}function Zn(n,r,i,e){return function(o,u){function a(t,r){var i=o(t,r);n(t=i[0],r=i[1])&&u.point(t,r)}function c(n,t){var r=o(n,t);E.point(r[0],r[1])}function l(){x.point=c,E.lineStart()}function f(){x.point=a,E.lineEnd()}function p(n,t){d.push([n,t]);var r=o(n,t);m.point(r[0],r[1])}function s(){m.lineStart(),d=[]}function g(){p(d[0][0],d[0][1]),m.lineEnd();var n,t,r,i,e=m.clean(),o=y.result(),a=o.length;if(d.pop(),v.push(d),d=null,a)if(1&e){if(r=o[0],(t=r.length-1)>0){for(M||(u.polygonStart(),M=!0),u.lineStart(),n=0;t>n;++n)u.point((i=r[n])[0],i[1]);u.lineEnd()}}else a>1&&2&e&&o.push(o.pop().concat(o.shift())),h.push(o.filter(kn))}var v,h,d,E=r(u),S=o.invert(e[0],e[1]),y=on(),m=r(y),M=!1,x={point:a,lineStart:l,lineEnd:f,polygonStart:function(){x.point=p,x.lineStart=s,x.lineEnd=g,h=[],v=[]},polygonEnd:function(){x.point=a,x.lineStart=l,x.lineEnd=f,h=t.merge(h);var n=Un(v,S);h.length?(M||(u.polygonStart(),M=!0),ln(h,Hn,n,i,u)):n&&(M||(u.polygonStart(),M=!0),u.lineStart(),i(null,null,1,u),u.lineEnd()),M&&(u.polygonEnd(),M=!1),h=v=null},sphere:function(){u.polygonStart(),u.lineStart(),i(null,null,1,u),u.lineEnd(),u.polygonEnd()}};return x}}function kn(n){return n.length>1}function Hn(n,t){return((n=n.x)[0]<0?n[1]-dr-gr:dr-n[1])-((t=t.x)[0]<0?t[1]-dr-gr:dr-t[1])}function Jn(n){var t,r=NaN,i=NaN,e=NaN;return{lineStart:function(){n.lineStart(),t=1},point:function(o,u){var a=o>0?hr:-hr,c=Mr(o-r);Mr(c-hr)<gr?(n.point(r,i=(i+u)/2>0?dr:-dr),n.point(e,i),n.lineEnd(),n.lineStart(),n.point(a,i),n.point(o,i),t=0):e!==a&&c>=hr&&(Mr(r-e)<gr&&(r-=e*gr),Mr(o-a)<gr&&(o-=a*gr),i=Kn(r,i,o,u),n.point(e,i),n.lineEnd(),n.lineStart(),n.point(a,i),t=0),n.point(r=o,i=u),e=a},lineEnd:function(){n.lineEnd(),r=i=NaN},clean:function(){return 2-t}}}function Kn(n,t,r,i){var e,o,u=Cr(n-r);return Mr(u)>gr?xr((Cr(t)*(o=wr(i))*Cr(r)-Cr(i)*(e=wr(t))*Cr(n))/(e*o*u)):(t+i)/2}function Qn(n,t,r,i){var e;if(null==n)e=r*dr,i.point(-hr,e),i.point(0,e),i.point(hr,e),i.point(hr,0),i.point(hr,-e),i.point(0,-e),i.point(-hr,-e),i.point(-hr,0),i.point(-hr,e);else if(Mr(n[0]-t[0])>gr){var o=n[0]<t[0]?hr:-hr;e=r*o/2,i.point(-o,e),i.point(0,e),i.point(o,e)}else i.point(t[0],t[1])}function Vn(n,t){function r(r,i,e,o){tn(o,n,t,e,r,i)}function i(n,t){return wr(n)*wr(t)>a}function e(n){var t,r,e,a,f;return{lineStart:function(){a=e=!1,f=1},point:function(p,s){var g,v=[p,s],h=i(p,s),d=c?h?0:u(p,s):h?u(p+(0>p?hr:-hr),s):0;if(!t&&(a=e=h)&&n.lineStart(),h!==e&&(g=o(t,v),(an(t,g)||an(v,g))&&(v[0]+=gr,v[1]+=gr,h=i(v[0],v[1]))),h!==e)f=0,h?(n.lineStart(),g=o(v,t),n.point(g[0],g[1])):(g=o(t,v),n.point(g[0],g[1]),n.lineEnd()),t=g;else if(l&&t&&c^h){var E;d&r||!(E=o(v,t,!0))||(f=0,c?(n.lineStart(),n.point(E[0][0],E[0][1]),n.point(E[1][0],E[1][1]),n.lineEnd()):(n.point(E[1][0],E[1][1]),n.lineEnd(),n.lineStart(),n.point(E[0][0],E[0][1])))}!h||t&&an(t,v)||n.point(v[0],v[1]),t=v,e=h,r=d},lineEnd:function(){e&&n.lineEnd(),t=null},clean:function(){return f|(a&&e)<<1}}}function o(n,t,r){var i=y(n),e=y(t),o=[1,0,0],u=M(i,e),c=m(u,u),l=u[0],f=c-l*l;if(!f)return!r&&n;var p=a*c/f,s=-a*l/f,g=M(o,u),v=N(o,p),h=N(u,s);x(v,h);var d=g,E=m(v,d),w=m(d,d),R=E*E-w*(m(v,v)-1);if(!(0>R)){var A=zr(R),j=N(d,(-E-A)/w);if(x(j,v),j=S(j),!r)return j;var P,C=n[0],q=t[0],z=n[1],b=t[1];C>q&&(P=C,C=q,q=P);var L=q-C,O=Mr(L-hr)<gr,T=O||gr>L;if(!O&&z>b&&(P=z,z=b,b=P),T?O?z+b>0^j[1]<(Mr(j[0]-C)<gr?z:b):z<=j[1]&&j[1]<=b:L>hr^(C<=j[0]&&j[0]<=q)){var G=N(d,(-E+A)/w);return x(G,v),[j,S(G)]}}}function u(t,r){var i=c?n:hr-n,e=0;return-i>t?e|=1:t>i&&(e|=2),-i>r?e|=4:r>i&&(e|=8),e}var a=wr(n),c=a>0,l=Mr(a)>gr;return Zn(i,e,r,c?[0,-n]:[-hr,n-hr])}function Wn(n){return{stream:Xn(n)}}function Xn(n){function t(){}var r=t.prototype=Object.create(Yn.prototype);for(var i in n)r[i]=n[i];return function(n){var r=new t;return r.stream=n,r}}function Yn(){}function $n(n,t){return+t?tt(n,t):nt(n)}function nt(n){return Xn({point:function(t,r){t=n(t,r),this.stream.point(t[0],t[1])}})}function tt(n,t){function r(i,e,o,a,c,l,f,p,s,g,v,h,d,E){var S=f-i,y=p-e,m=S*S+y*y;if(m>4*t&&d--){var M=a+g,x=c+v,N=l+h,w=zr(M*M+x*x+N*N),R=u(N/=w),A=Mr(Mr(N)-1)<gr||Mr(o-s)<gr?(o+s)/2:Nr(x,M),j=n(A,R),P=j[0],C=j[1],q=P-i,z=C-e,b=y*q-S*z;(b*b/m>t||Mr((S*q+y*z)/m-.5)>.3||xi>a*g+c*v+l*h)&&(r(i,e,o,a,c,l,P,C,A,M/=w,x/=w,N,d,E),E.point(P,C),r(P,C,A,M,x,N,f,p,s,g,v,h,d,E))}}return function(t){function i(r,i){r=n(r,i),t.point(r[0],r[1])}function e(){E=NaN,N.point=o,t.lineStart()}function o(i,e){var o=y([i,e]),u=n(i,e);r(E,S,d,m,M,x,E=u[0],S=u[1],d=i,m=o[0],M=o[1],x=o[2],Mi,t),t.point(E,S)}function u(){N.point=i,t.lineEnd()}function a(){e(),N.point=c,N.lineEnd=l}function c(n,t){o(f=n,t),p=E,s=S,g=m,v=M,h=x,N.point=o}function l(){r(E,S,d,m,M,x,p,s,f,g,v,h,Mi,t),N.lineEnd=u,u()}var f,p,s,g,v,h,d,E,S,m,M,x,N={point:i,lineStart:e,lineEnd:u,polygonStart:function(){t.polygonStart(),N.lineStart=a},polygonEnd:function(){t.polygonEnd(),N.lineStart=e}};return N}}function rt(n){return it(function(){return n})()}function it(n){function t(n){return n=f(n[0]*mr,n[1]*mr),[n[0]*d+a,c-n[1]*d]}function r(n){return n=f.invert((n[0]-a)/d,(c-n[1])/d),n&&[n[0]*yr,n[1]*yr]}function i(n,t){return n=u(n,t),[n[0]*d+a,c-n[1]*d]}function e(){f=Q(l=W(M,x,N),u);var n=u(y,m);return a=E-n[0]*d,c=S+n[1]*d,o()}function o(){return v=h=null,t}var u,a,c,l,f,p,s,g,v,h,d=150,E=480,S=250,y=0,m=0,M=0,x=0,N=0,w=null,R=mi,A=null,j=Nn,P=.5,C=$n(i,P);return t.stream=function(n){return v&&h===n?v:v=Ni(R(l,C(j(h=n))))},t.clipAngle=function(n){return arguments.length?(R=+n?Vn(w=n*mr,6*mr):(w=null,mi),o()):w*yr},t.clipExtent=function(n){return arguments.length?(j=null==n?(A=p=s=g=null,Nn):pn(A=+n[0][0],p=+n[0][1],s=+n[1][0],g=+n[1][1]),o()):null==A?null:[[A,p],[s,g]]},t.scale=function(n){return arguments.length?(d=+n,e()):d},t.translate=function(n){return arguments.length?(E=+n[0],S=+n[1],e()):[E,S]},t.center=function(n){return arguments.length?(y=n[0]%360*mr,m=n[1]%360*mr,e()):[y*yr,m*yr]},t.rotate=function(n){return arguments.length?(M=n[0]%360*mr,x=n[1]%360*mr,N=n.length>2?n[2]%360*mr:0,e()):[M*yr,x*yr,N*yr]},t.precision=function(n){return arguments.length?(C=$n(i,P=n*n),o()):zr(P)},function(){return u=n.apply(this,arguments),t.invert=u.invert&&r,e()}}function et(n){var t=0,r=hr/3,i=it(n),e=i(t,r);return e.parallels=function(n){return arguments.length?i(t=n[0]*mr,r=n[1]*mr):[t*yr,r*yr]},e}function ot(n,t){function r(n,t){var r=zr(o-2*e*Cr(t))/e;return[r*Cr(n*=e),a-r*wr(n)]}var i=Cr(n),e=(i+Cr(t))/2,o=1+i*(2*e-i),a=zr(o)/e;return r.invert=function(n,t){var r=a-t;return[Nr(n,r)/e,u((o-(n*n+r*r)*e*e)/(2*e))]},r}function ut(){return et(ot).scale(151).translate([480,347])}function at(){return ut().parallels([29.5,45.5]).scale(1070).translate([480,250]).rotate([96,0]).center([-.6,38.7])}function ct(n){var t=n.length;return{point:function(r,i){for(var e=-1;++e<t;)n[e].point(r,i)},sphere:function(){for(var r=-1;++r<t;)n[r].sphere()},lineStart:function(){for(var r=-1;++r<t;)n[r].lineStart()},lineEnd:function(){for(var r=-1;++r<t;)n[r].lineEnd()},polygonStart:function(){for(var r=-1;++r<t;)n[r].polygonStart()},polygonEnd:function(){for(var r=-1;++r<t;)n[r].polygonEnd()}}}function lt(){function n(n){var t=n[0],r=n[1];return u=null,i.point(t,r),u||(e.point(t,r),u)||(o.point(t,r),u)}var t,r,i,e,o,u,a=at(),c=ut().rotate([154,0]).center([-2,58.5]).parallels([55,65]),l=ut().rotate([157,0]).center([-3,19.9]).parallels([8,18]),f={point:function(n,t){u=[n,t]}};return n.invert=function(n){var t=a.scale(),r=a.translate(),i=(n[0]-r[0])/t,e=(n[1]-r[1])/t;return(e>=.12&&.234>e&&i>=-.425&&-.214>i?c:e>=.166&&.234>e&&i>=-.214&&-.115>i?l:a).invert(n)},n.stream=function(n){return t&&r===n?t:t=ct([a.stream(r=n),c.stream(n),l.stream(n)])},n.precision=function(t){return arguments.length?(a.precision(t),c.precision(t),l.precision(t),n):a.precision()},n.scale=function(t){return arguments.length?(a.scale(t),c.scale(.35*t),l.scale(t),n.translate(a.translate())):a.scale()},n.translate=function(t){if(!arguments.length)return a.translate();var r=a.scale(),u=+t[0],p=+t[1];return i=a.translate(t).clipExtent([[u-.455*r,p-.238*r],[u+.455*r,p+.238*r]]).stream(f),e=c.translate([u-.307*r,p+.201*r]).clipExtent([[u-.425*r+gr,p+.12*r+gr],[u-.214*r-gr,p+.234*r-gr]]).stream(f),o=l.translate([u-.205*r,p+.212*r]).clipExtent([[u-.214*r+gr,p+.166*r+gr],[u-.115*r-gr,p+.234*r-gr]]).stream(f),n},n.scale(1070)}function ft(n){return function(t,r){var i=wr(t),e=wr(r),o=n(i*e);return[o*e*Cr(t),o*Cr(r)]}}function pt(n){return function(t,r){var i=zr(t*t+r*r),e=n(i),o=Cr(e),a=wr(e);return[Nr(t*o,i*a),u(i&&r*o/i)]}}function st(){return rt(wi).scale(120).clipAngle(179.999)}function gt(){return rt(Ri).scale(480/Sr).clipAngle(179.999)}function vt(n,t){return[n,jr(br((dr+t)/2))]}function ht(){return dt(vt)}function dt(n){var t,r=rt(n),i=r.scale,e=r.translate,o=r.clipExtent;return r.scale=function(n){return arguments.length?(i(n),t&&r.clipExtent(null),r):i()},r.translate=function(n){return arguments.length?(e(n),t&&r.clipExtent(null),r):e()},r.clipExtent=function(n){if(!arguments.length)return t?null:o();if(t=null==n){var u=hr*i(),a=e();n=[[a[0]-u,a[1]-u],[a[0]+u,a[1]+u]]}return o(n),r},r.clipExtent(null).scale(961/Sr)}function Et(n){return br((dr+n)/2)}function St(n,t){function r(n,t){o>0?-dr+gr>t&&(t=-dr+gr):t>dr-gr&&(t=dr-gr);var r=o/Pr(Et(t),e);return[r*Cr(e*n),o-r*wr(e*n)]}var i=wr(n),e=n===t?Cr(n):jr(i/wr(t))/jr(Et(t)/Et(n)),o=i*Pr(Et(n),e)/e;return e?(r.invert=function(n,t){var r=o-t,i=qr(e)*zr(n*n+r*r);return[Nr(n,r)/e,2*xr(Pr(o/i,1/e))-dr]},r):vt}function yt(){return et(St)}function mt(n,t){return[n,t]}function Mt(){return rt(mt).scale(480/hr)}function xt(n,t){function r(n,t){var r=o-t,i=e*n;return[r*Cr(i),o-r*wr(i)]}var i=wr(n),e=n===t?Cr(n):(i-wr(t))/(t-n),o=i/e+n;return Mr(e)<gr?mt:(r.invert=function(n,t){var r=o-t;return[Nr(n,r)/e,o-qr(e)*zr(n*n+r*r)]},r)}function Nt(){return et(xt).scale(128).translate([480,280])}function wt(n,t){var r=wr(t),i=wr(n)*r;return[r*Cr(n)/i,Cr(t)/i]}function Rt(){return rt(wt).scale(139).clipAngle(60)}function At(n,t){return[wr(t)*Cr(n),Cr(t)]}function jt(){return rt(At).scale(240).clipAngle(90+gr)}function Pt(n,t){var r=wr(t),i=1+wr(n)*r;return[r*Cr(n)/i,Cr(t)/i]}function Ct(){return rt(Pt).scale(240).clipAngle(142)}function qt(n,t){return[jr(br((dr+t)/2)),-n]}function zt(){var n=dt(qt),t=n.center,r=n.rotate;return n.center=function(n){return arguments.length?t([-n[1],n[0]]):(n=t(),[n[1],-n[0]])},n.rotate=function(n){return arguments.length?r([n[0],n[1],n.length>2?n[2]+90:90]):(n=r(),[n[0],n[1],n[2]-90])},r([0,0,90])}i.prototype={constructor:i,reset:function(){this.s=this.t=0},add:function(n){e(sr,n,this.t),e(this,sr.s,this.s),this.s?this.t+=sr.t:this.s=sr.t},valueOf:function(){return this.s}};var bt,Lt,Ot,Tt,Gt,Ft,It,_t,Bt,Dt,Ut,Zt,kt,Ht,Jt,Kt,Qt,Vt,Wt,Xt,Yt,$t,nr,tr,rr,ir,er,or,ur,ar,cr,lr,fr,pr,sr=new i,gr=1e-6,vr=1e-12,hr=Math.PI,dr=hr/2,Er=hr/4,Sr=2*hr,yr=180/hr,mr=hr/180,Mr=Math.abs,xr=Math.atan,Nr=Math.atan2,wr=Math.cos,Rr=Math.ceil,Ar=Math.exp,jr=Math.log,Pr=Math.pow,Cr=Math.sin,qr=Math.sign||function(n){return n>0?1:0>n?-1:0},zr=Math.sqrt,br=Math.tan,Lr={Feature:function(n,t){l(n.geometry,t)},FeatureCollection:function(n,t){for(var r=n.features,i=-1,e=r.length;++i<e;)l(r[i].geometry,t)}},Or={Sphere:function(n,t){t.sphere()},Point:function(n,t){n=n.coordinates,t.point(n[0],n[1],n[2])},MultiPoint:function(n,t){for(var r=n.coordinates,i=-1,e=r.length;++i<e;)n=r[i],t.point(n[0],n[1],n[2])},LineString:function(n,t){f(n.coordinates,t,0)},MultiLineString:function(n,t){for(var r=n.coordinates,i=-1,e=r.length;++i<e;)f(r[i],t,0)},Polygon:function(n,t){p(n.coordinates,t)},MultiPolygon:function(n,t){for(var r=n.coordinates,i=-1,e=r.length;++i<e;)p(r[i],t)},GeometryCollection:function(n,t){for(var r=n.geometries,i=-1,e=r.length;++i<e;)l(r[i],t)}},Tr={point:c,lineStart:c,lineEnd:c,polygonStart:function(){bt.reset(),Tr.lineStart=g,Tr.lineEnd=v},polygonEnd:function(){var n=+bt;Lt.add(0>n?Sr+n:n),this.lineStart=this.lineEnd=this.point=c},sphere:function(){Lt.add(Sr)}},Gr={point:R,lineStart:j,lineEnd:P,polygonStart:function(){Gr.point=C,Gr.lineStart=q,Gr.lineEnd=z,Kt.reset(),Tr.polygonStart()},polygonEnd:function(){Tr.polygonEnd(),Gr.point=R,Gr.lineStart=j,Gr.lineEnd=P,0>bt?(_t=-(Dt=180),Bt=-(Ut=90)):Kt>gr?Ut=90:-gr>Kt&&(Bt=-90),Vt[0]=_t,Vt[1]=Dt}},Fr={sphere:c,point:G,lineStart:I,lineEnd:D,polygonStart:function(){Fr.lineStart=U,Fr.lineEnd=Z},polygonEnd:function(){Fr.lineStart=I,Fr.lineEnd=D}};V.invert=V;var Ir,_r,Br,Dr,Ur,Zr,kr,Hr,Jr,Kr,Qr,Vr,Wr=1e9,Xr=-Wr,Yr={sphere:c,point:c,lineStart:gn,lineEnd:c,polygonStart:c,polygonEnd:c},$r=[null,null],ni={type:"LineString",coordinates:$r},ti=r(),ri=r(),ii={point:c,lineStart:c,lineEnd:c,polygonStart:function(){ii.lineStart=wn,ii.lineEnd=jn},polygonEnd:function(){ii.lineStart=ii.lineEnd=ii.point=c,ti.add(Mr(ri)),ri.reset()},result:function(){var n=ti/2;return ti.reset(),n}},ei=1/0,oi=ei,ui=-ei,ai=ui,ci={point:Pn,lineStart:c,lineEnd:c,polygonStart:c,polygonEnd:c,result:function(){var n=[[ei,oi],[ui,ai]];return ui=ai=-(oi=ei=1/0),n}},li=0,fi=0,pi=0,si=0,gi=0,vi=0,hi=0,di=0,Ei=0,Si={point:Cn,lineStart:qn,lineEnd:Ln,polygonStart:function(){Si.lineStart=On,Si.lineEnd=Tn},polygonEnd:function(){Si.point=Cn,Si.lineStart=qn,Si.lineEnd=Ln},result:function(){var n=Ei?[hi/Ei,di/Ei]:vi?[si/vi,gi/vi]:pi?[li/pi,fi/pi]:[NaN,NaN];return li=fi=pi=si=gi=vi=hi=di=Ei=0,n}},yi=r(),mi=Zn(function(){return!0},Jn,Qn,[-hr,-dr]);Yn.prototype={point:function(n,t){this.stream.point(n,t)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};var Mi=16,xi=wr(30*mr),Ni=Xn({point:function(n,t){this.stream.point(n*mr,t*mr)}}),wi=ft(function(n){return zr(2/(1+n))});wi.invert=pt(function(n){return 2*u(n/2)});var Ri=ft(function(n){return(n=o(n))&&n/Cr(n)});Ri.invert=pt(function(n){return n}),vt.invert=function(n,t){return[n,2*xr(Ar(t))-dr]},mt.invert=mt,wt.invert=pt(xr),At.invert=pt(u),Pt.invert=pt(function(n){return 2+xr(n)}),qt.invert=function(n,t){return[-t,2*xr(Ar(n))-dr]},n.geoArea=E,n.geoBounds=T,n.geoCentroid=J,n.geoCircle=en,n.geoClipExtent=sn,n.geoDistance=Sn,n.geoGraticule=Mn,n.geoInterpolate=xn,n.geoLength=En,n.geoPath=Dn,n.geoAlbers=at,n.geoAlbersUsa=lt,n.geoAzimuthalEqualArea=st,n.geoAzimuthalEqualAreaRaw=wi,n.geoAzimuthalEquidistant=gt,n.geoAzimuthalEquidistantRaw=Ri,n.geoConicConformal=yt,n.geoConicConformalRaw=St,n.geoConicEqualArea=ut,n.geoConicEqualAreaRaw=ot,n.geoConicEquidistant=Nt,n.geoConicEquidistantRaw=xt,n.geoEquirectangular=Mt,n.geoEquirectangularRaw=mt,n.geoGnomonic=Rt,n.geoGnomonicRaw=wt,n.geoProjection=rt,n.geoProjectionMutator=it,n.geoMercator=ht,n.geoMercatorRaw=vt,n.geoOrthographic=jt,n.geoOrthographicRaw=At,n.geoStereographic=Ct,n.geoStereographicRaw=Pt,n.geoTransverseMercator=zt,n.geoTransverseMercatorRaw=qt,n.geoRotation=nn,n.geoStream=s,n.geoTransform=Wn,Object.defineProperty(n,"__esModule",{value:!0})}); | 14,858 | 29,644 | 0.619666 |
6a06e20f3e36a237a33cd5df9eaa517cc07e496d | 54,504 | js | JavaScript | public/vue/vue-app.js | markgeek95/Dashpayroll | c3fc41c3f716c6cb61566a1d0ff9ac242e99dee4 | [
"MIT"
] | null | null | null | public/vue/vue-app.js | markgeek95/Dashpayroll | c3fc41c3f716c6cb61566a1d0ff9ac242e99dee4 | [
"MIT"
] | null | null | null | public/vue/vue-app.js | markgeek95/Dashpayroll | c3fc41c3f716c6cb61566a1d0ff9ac242e99dee4 | [
"MIT"
] | null | null | null | var vue_app = new Vue({
el: '#vue-app',
data: {
errors: [], // for viewing of errors
password_user: 'password',
employee_list: [], // for philhealth modal
range_value: '', // for philhealth maintenace module addition
amount_value: '', // for philhealth maintenace module addition
rate_value: '', // for philhealth maintenace module addition
employer_value: '', // for philhealth maintenace module addition
employee_value: '', // for philhealth maintenace module addition
ec_value: '', // for sss maintenace module edit
percentage_value: '', // for sss maintenace module edit
philhealth_id: '', // for philhealth maintenace module addition
sss_id: '', // for philhealth maintenace module addition
withholding_tax_id: '', // for update of witholding tax
frequency_id: '', // for update of witholding tax
frequency: {}, // holder of frequency table
witholding_tax_delete_id: '',
annual_tax_id: '',
fixed_rate_value: '',
tax_rate_value: '',
global_delete_id: '',
global_delete_name: '',
amount_money: '324',
leave_array: [],
holiday_types_array: {},
shifts_array: {}, // store shifts array here
bank: {}, // for updating banks
ot_nightdifferential: {}, // OT
statutory_array: {}, // for editing statutory
},
methods: {
// toggle password on user
password_toggle: function () {
if (this.password_user == 'password'){
this.password_user = 'text';
} else{
this.password_user = 'password';
}
},
full_loader: function() {
$('#loader-modal').modal({
backdrop: 'static',
keyboard: false
});
},
decrypt_encrypt: function (event) {
var input = $(event.target).closest('div').find('input.password_holder');
var type = $(input).attr('type');
if (type == 'text'){
$(input).attr('type','password');
} else{
$(input).attr('type','text');
}
},
philhealth_get_all_employees: function ($element)
{
var root_element = this; // the parent element
request = $.ajax({
url: baseUrl+'/get_all_employees',
type: "post",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
root_element.employee_list = response;
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#'+$element+' .loaderRefresh').fadeOut('fast');
});
},
philhealth_maintenance: function () {
$('#add_philheatlh_modal').find('.loaderRefresh').fadeIn(0);
$('#add_philheatlh_modal').modal();
this.philhealth_get_all_employees('add_philheatlh_modal');
},
philhealth_maintenance_submit: function (event) {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#add_philheatlh_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/philhealth',
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Philhealth Maintenance Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#add_philheatlh_modal .loaderRefresh').fadeOut('fast');
});
},
philhealth_maintenance_edit: function (event, $id)
{
var root_element = this; // the parent element
$('#edit_philheatlh_modal').find('.loaderRefresh').fadeIn(0);
$('#edit_philheatlh_modal').modal();
request = $.ajax({
url: baseUrl+'/philhealth/'+$id+'/edit',
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
root_element.philhealth_id = response.id;
root_element.range_value = response.ranges;
root_element.amount_value = response.amount;
root_element.rate_value = response.rate;
root_element.employer_value = response.employer;
root_element.employee_value = response.employee_id;
root_element.philhealth_get_all_employees('edit_philheatlh_modal');
root_element.check_employee_id();
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
// $('#edit_philheatlh_modal').find('.loaderRefresh').fadeOut('fast');
});
},
check_employee_id: function($employee_id)
{
return ($employee_id == this.employee_value)? true : false;
},
philhealth_maintenance_edit_submit: function (event) {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#edit_philheatlh_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/philhealth/'+root_element.philhealth_id,
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Philhealth Maintenance Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#edit_philheatlh_modal .loaderRefresh').fadeOut('fast');
});
},
philhealth_maintenance_delete: function ($id)
{
var ans = confirm('Do you really want to delete this data?');
if (ans) {
this.full_loader(); // show window loader
var root_element = this; // the parent element
request = $.ajax({
url: baseUrl+'/philhealth_delete/'+$id,
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
toaster('info', 'Philhealth Maintenance Has Been Deleted.');
location.reload();
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
// $('#edit_philheatlh_modal .loaderRefresh').fadeOut('fast');
});
}
},
// SSS MODULE
sss_add: function() {
$('#sss_add_modal').find('.loaderRefresh').fadeIn(0);
$('#sss_add_modal').modal();
this.philhealth_get_all_employees('sss_add_modal');
},
sss_submit_form: function (event) {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#sss_add_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/sss',
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'SSS Maintenance Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#sss_add_modal .loaderRefresh').fadeOut('fast');
});
},
sss_maintenance_edit: function (event, $id)
{
var root_element = this; // the parent element
$('#sss_edit_modal').find('.loaderRefresh').fadeIn(0);
$('#sss_edit_modal').modal();
request = $.ajax({
url: baseUrl+'/sss/'+$id+'/edit',
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
root_element.sss_id = response.id;
root_element.range_value = response.ranges;
root_element.employer_value = response.employer;
root_element.employee_value = response.employee_id;
root_element.ec_value = response.ec;
root_element.philhealth_get_all_employees('sss_edit_modal');
// root_element.check_employee_id();
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#sss_edit_modal').find('.loaderRefresh').fadeOut('fast');
});
},
sss_edit_submit_form: function (event) {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#sss_edit_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/sss/'+root_element.sss_id,
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'SSS Maintenance Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#sss_edit_modal .loaderRefresh').fadeOut('fast');
});
},
sss_maintenance_delete: function ($id)
{
var ans = confirm('Do you really want to delete this data?');
if (ans) {
this.full_loader(); // show window loader
var root_element = this; // the parent element
request = $.ajax({
url: baseUrl+'/sss_delete/'+$id,
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
toaster('info', 'SSS Maintenance Has Been Deleted.');
location.reload();
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
// $('#edit_philheatlh_modal .loaderRefresh').fadeOut('fast');
});
}
},
get_frequency: function () {
var root_element = this; // the parent element
request = $.ajax({
url: baseUrl+'/get_frequency',
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
root_element.frequency = response;
});
},
withholding_tax_new: function() {
var root_element = this; // the parent element
$('#withholding_tax_modal').find('.loaderRefresh').fadeIn(0);
$('#withholding_tax_modal').modal();
request = $.ajax({
url: baseUrl+'/get_frequency',
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
root_element.frequency = response;
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#withholding_tax_modal .loaderRefresh').fadeOut('fast');
});
},
witholding_tax_submit: function(event){
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#withholding_tax_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/withholding_tax',
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Withholding Tax Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#withholding_tax_modal .loaderRefresh').fadeOut('fast');
});
},
witholding_tax_edit: function (event, $id) {
var root_element = this; // the parent element
var data = $(event.target).serialize();
this.get_frequency();
$('#withholding_tax_edit').find('.loaderRefresh').fadeIn(0);
$('#withholding_tax_edit').modal();
request = $.ajax({
url: baseUrl+'/withholding_tax/'+$id+'/edit',
type: "get",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
root_element.withholding_tax_id = response.id;
root_element.frequency_id = response.frequency_id;
root_element.range_value = response.ranges;
root_element.percentage_value = response.percentage;
root_element.amount_value = response.amount;
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#withholding_tax_edit .loaderRefresh').fadeOut('fast');
});
},
check_frequency_id: function($frequency_id)
{
return ($frequency_id == this.frequency_id)? true : false;
},
witholding_tax_edit_submit: function (event) {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#withholding_tax_edit').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/withholding_tax/'+root_element.withholding_tax_id,
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Withholding Tax Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#withholding_tax_edit').find('.loaderRefresh').fadeOut('fast');
});
},
witholding_tax_delete_modal: function ($id) {
this.witholding_tax_delete_id = $id;
$('#withholding_tax_delete').modal();
},
witholding_tax_delete: function ()
{
var root_element = this; // the parent element
$('#withholding_tax_delete').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/withholding_tax_delete/'+root_element.witholding_tax_delete_id,
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
toaster('info', response.info);
location.reload();
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#withholding_tax_delete').find('.loaderRefresh').fadeOut('fast');
});
},
// annual tax
annual_tax_new: function () {
$('#annualtax_new').modal();
},
annualtax_new_submit: function(event){
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#annualtax_new').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/annual_tax',
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Annual Tax Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#annualtax_new').find('.loaderRefresh').fadeOut('fast');
});
},
annual_tax_edit: function ($id) {
var root_element = this; // the parent element
$('#annualtax_edit').find('.loaderRefresh').fadeIn(0);
$('#annualtax_edit').modal();
request = $.ajax({
url: baseUrl+'/annual_tax/'+$id+'/edit',
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
root_element.annual_tax_id = response.id;
root_element.range_value = response.ranges;
root_element.fixed_rate_value = response.fixed_rate;
root_element.tax_rate_value = response.tax_rate;
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#annualtax_edit .loaderRefresh').fadeOut('fast');
});
},
annualtax_edit_submit: function (event) {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#annualtax_edit').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/annual_tax/'+root_element.annual_tax_id,
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Annual Tax Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#annualtax_edit').find('.loaderRefresh').fadeOut('fast');
});
},
global_delete: function($id, $name) {
this.global_delete_id = $id;
this.global_delete_name = $name;
$('#delete_modal').modal();
},
delete_yes: function () {
var delName = this.global_delete_name;
if (delName == 'annual_tax_delete') {
this.annual_tax_delete();
}else if (delName == 'leave_delete') {
this.leave_delete();
}else if (delName == 'bank_delete') {
this.bank_delete();
}else if (delName == 'statutory_delete') {
this.statutory_delete();
}
},
annual_tax_delete: function (){
var root_element = this; // the parent element
$('#delete_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/annual_tax_delete/'+root_element.global_delete_id,
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
toaster('info', 'Annual Tax Has Been Deleted.');
location.reload();
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
});
},
/* leave tables */
leave_new_open: function () {
$('#leave_new_modal').modal();
},
leave_new_submit: function (event) {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#leave_new_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/leave',
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Leave Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#leave_new_modal').find('.loaderRefresh').fadeOut('fast');
});
},
leave_edit: function ($id) {
var root_element = this; // the parent element
$('#leave_edit_modal').find('.loaderRefresh').fadeIn(0);
$('#leave_edit_modal').modal();
request = $.ajax({
url: baseUrl+'/leave/'+$id+'/edit',
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
root_element.leave_array = response;
console.log(root_element.leave_array);
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#leave_edit_modal .loaderRefresh').fadeOut('fast');
});
},
cash_convertible_check: function (status) {
return (status == 'Y')? true : false;
},
carry_over_check: function (status) {
return (status == 'Y')? true : false;
},
leave_edit_submit: function (event) {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#leave_edit_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/leave/'+root_element.leave_array.id,
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Leave Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#leave_edit_modal').find('.loaderRefresh').fadeOut('fast');
});
},
leave_delete: function (){
var root_element = this; // the parent element
$('#delete_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/leave_delete/'+root_element.global_delete_id,
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
toaster('info', 'Leave Has Been Deleted.');
location.reload();
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
},
/* holiday */
holiday_new: function () {
var root_element = this; // the parent element
$('#holiday_new_modal').modal();
$('#holiday_new_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/holiday_types',
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
root_element.holiday_types_array = response;
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#holiday_new_modal').find('.loaderRefresh').fadeOut('fast');
});
},
holiday_new_submit: function (event) {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#holiday_new_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/holiday',
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Leave Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#holiday_new_modal').find('.loaderRefresh').fadeOut('fast');
});
},
rest_day_new: function () {
var root_element = this; // the parent element
$('#rest_day_new_modal').modal();
$('#rest_day_new_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/shifts',
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
root_element.shifts_array = response;
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#rest_day_new_modal').find('.loaderRefresh').fadeOut('fast');
});
},
rest_day_new_submit: function (event) {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#rest_day_new_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/rest_day',
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Leave Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#rest_day_new_modal').find('.loaderRefresh').fadeOut('fast');
});
},
// for editing of banks
banks_edit: function ($id) {
var root_element = this; // the parent element
$('#banks_edit_modal').modal();
var data = $(event.target).serialize();
$('#banks_edit_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/banks/'+$id+'/edit',
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
root_element.bank = response;
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#banks_edit_modal').find('.loaderRefresh').fadeOut('fast');
});
},
bank_edit_submit: function (event) {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#banks_edit_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/banks/'+root_element.bank.id,
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Leave Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#banks_edit_modal').find('.loaderRefresh').fadeOut('fast');
});
},
bank_delete: function (){
var root_element = this; // the parent element
$('#delete_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/bank_delete/'+root_element.global_delete_id,
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
toaster('info', 'Bank Has Been Deleted.');
location.reload();
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
},
departments_new_open_modal: function () {
$('#department_modal').modal();
},
department_new_submit: function (event) {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#department_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/departments',
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Department Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#department_modal').find('.loaderRefresh').fadeOut('fast');
});
},
position_new_open_modal: function () {
$('#position_modal').modal();
},
position_new_submit: function (event) {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#position_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/positions',
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Position Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#position_modal').find('.loaderRefresh').fadeOut('fast');
});
},
cost_center_new_open_modal: function () {
$('#cost_center_modal').modal();
},
cost_center_new_submit: function (event) {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#cost_center_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/cost_center',
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Cost Center Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#cost_center_modal').find('.loaderRefresh').fadeOut('fast');
});
},
open_employee_status_new_modal: function () {
$('#employee_status_new_modal').modal();
},
employee_status_new_submit: function () {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#employee_status_new_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/employee_status',
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Cost Center Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#employee_status_new_modal').find('.loaderRefresh').fadeOut('fast');
});
},
open_night_differential_modal: function () {
$('#overtime_nightdifferential_new_modal').modal();
},
overtime_nightdifferential_new_submit: function (event) {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#overtime_nightdifferential_new_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/overtime_nightdifferential',
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Overtime Night Differential Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#overtime_nightdifferential_new_modal').find('.loaderRefresh').fadeOut('fast');
});
},
overtime_nightdifferential_edit: function ($id) {
var root_element = this; // the parent element
$('#overtime_nightdifferential_edit_modal').modal();
var data = $(event.target).serialize();
$('#overtime_nightdifferential_edit_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/overtime_nightdifferential/'+$id+'/edit',
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
root_element.ot_nightdifferential = response;
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#overtime_nightdifferential_edit_modal').find('.loaderRefresh').fadeOut('fast');
});
},
overtime_nightdifferential_edit_submit: function (event) {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#overtime_nightdifferential_edit_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/overtime_nightdifferential/'+root_element.ot_nightdifferential.id,
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Overtime Night Differential Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#overtime_nightdifferential_edit_modal').find('.loaderRefresh').fadeOut('fast');
});
},
statutory_add_modal: function () {
var root_element = this; // the parent element
$('#statutorydeduction_add').modal();
$('#statutorydeduction_add').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/get_frequency',
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
root_element.frequency = response;
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#statutorydeduction_add').find('.loaderRefresh').fadeOut('fast');
});
},
statutory_deduction_submit: function () {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#statutorydeduction_add').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/statutory_deduction_schedule',
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Statutory Deduction Schedule Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#statutorydeduction_add').find('.loaderRefresh').fadeOut('fast');
});
},
statutory_edit: function ($id) {
var root_element = this; // the parent element
$('#statutorydeduction_edit').modal();
$('#statutorydeduction_edit').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/statutory_deduction_schedule/'+$id+'/edit',
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
root_element.statutory_array = response;
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
root_element.get_frequency(); // get all frequency
$('#statutorydeduction_edit').find('.loaderRefresh').fadeOut('fast');
});
},
deduction_count_if: function ($i) {
return ($i == this.statutory_array.deduction_count)? true : false;
},
days_deduction_if: function ($i) {
return ($i == this.statutory_array.days_of_deduction)? true : false;
},
frequency_select: function ($id) {
return ($id == this.statutory_array.frequency_id)? true : false;
},
statutory_edit_submit: function () {
var root_element = this; // the parent element
var data = $(event.target).serialize();
$('#statutorydeduction_edit').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/statutory_deduction_schedule/'+root_element.statutory_array.id,
type: "post",
data: data,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
if ($.isEmptyObject(response.errors)) {
toaster('success', response.success);
location.reload();
}else{
toaster('error', 'Statutory Deduction Schedule Not Saved.');
root_element.errors = response.errors;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
request.always(function(){
$('#statutorydeduction_edit').find('.loaderRefresh').fadeOut('fast');
});
},
statutory_delete: function (){
var root_element = this; // the parent element
$('#delete_modal').find('.loaderRefresh').fadeIn(0);
request = $.ajax({
url: baseUrl+'/statutory_delete/'+root_element.global_delete_id,
type: "get",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
});
request.done(function (response, textStatus, jqXHR) {
console.log(response);
toaster('info', 'Statutory Deduction Schedule Been Deleted.');
location.reload();
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+ jqXHR, textStatus, errorThrown);
});
},
}, // end of method
computed: {
},
filters: {
textuppercase: function (value){
if (!value) return '';
return value.toString().toUpperCase();
},
formatMoney: function (n, c, d, t) {
var c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))),
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
},
}
}) | 38.792883 | 156 | 0.49945 |
6a06e94224ba5d8fddf6af5c00b0953bdb45003f | 2,270 | js | JavaScript | src/FakeCodeTyper.js | WANGJIEKE/fake-code-editor | a4b8a59c9b5075ef352d1407129fe23ca6e17066 | [
"MIT"
] | 1 | 2020-06-21T08:32:45.000Z | 2020-06-21T08:32:45.000Z | src/FakeCodeTyper.js | WANGJIEKE/fake-code-editor | a4b8a59c9b5075ef352d1407129fe23ca6e17066 | [
"MIT"
] | null | null | null | src/FakeCodeTyper.js | WANGJIEKE/fake-code-editor | a4b8a59c9b5075ef352d1407129fe23ca6e17066 | [
"MIT"
] | null | null | null | import React from 'react';
import './FakeCodeTyper.scss';
import CodeDisplay from './CodeDisplay';
import InfoPanel from './InfoPanel';
import infoIcon from './assets/info-circle.svg';
import DEFAULT_CODE from './constants';
function getRandIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
class FakeCodeTyper extends React.Component {
constructor(props) {
super(props);
this.state = {
content: DEFAULT_CODE,
nextCharIndex: 0,
language: 'python',
minStep: 10,
maxStep: 20,
isUsingPanel: true
};
}
showNextChar() {
if (this.state.nextCharIndex >= this.state.content.length) {
return;
}
this.setState((state) => {
return {
nextCharIndex: state.nextCharIndex + getRandIntInclusive(this.state.minStep, this.state.maxStep)
}
});
}
keyDownHandler(event) {
if (this.state.isUsingPanel) {
return;
}
this.showNextChar();
const pre = document.querySelector('.CodeDisplay > pre');
const code = document.querySelector('.CodeDisplay > pre > code');
pre.scrollTo(0, code.clientHeight);
}
componentDidMount() {
document.addEventListener('keydown', (event) => { this.keyDownHandler(event); })
}
onInfoIconClicked(event) {
const infoPanel = document.querySelector('.InfoPanel');
if (this.state.isUsingPanel) {
infoPanel.style.display = 'none';
} else {
infoPanel.style.display = 'flex';
}
this.setState((state) => {
return { isUsingPanel: !state.isUsingPanel };
});
event.preventDefault();
}
onInfoPanelUpdate(newState) {
this.setState(newState);
this.setState({nextCharIndex: 0});
}
render() {
return (
<div className="FakeCodeTyper">
<div className="InfoIcon" onClick={(event) => { this.onInfoIconClicked(event); }}>
<img src={infoIcon} alt=""></img>
</div>
<CodeDisplay
content={this.state.content.slice(0, this.state.nextCharIndex)}
language={this.state.language}
/>
<InfoPanel onUpdate={(newState) => { this.onInfoPanelUpdate(newState); }} />
</div>
);
}
}
export default FakeCodeTyper;
| 25.505618 | 104 | 0.627313 |
6a071f381d22bb1edcf01817993d3ad526796297 | 2,856 | js | JavaScript | static/scripts/gis/Gazetteer.js | whanderley/eden | 08ced3be3d52352c54cbd412ed86128fbb68b1d2 | [
"MIT"
] | 205 | 2015-01-20T08:26:09.000Z | 2022-03-27T19:59:33.000Z | static/scripts/gis/Gazetteer.js | nursix/eden-asp | e49f46cb6488918f8d5a163dcd5a900cd686978c | [
"MIT"
] | 249 | 2015-02-10T09:56:35.000Z | 2022-03-23T19:54:36.000Z | static/scripts/gis/Gazetteer.js | nursix/eden-asp | e49f46cb6488918f8d5a163dcd5a900cd686978c | [
"MIT"
] | 231 | 2015-02-10T09:33:17.000Z | 2022-02-18T19:56:05.000Z | Gazetteer = OpenLayers.Class({
initialize: function() {
},
osmGaz: function(search) {
try {
var u = new USNG2();
var data = u.toLonLat(search);
if (data && data.lon && data.lat) {
var lonlat = new OpenLayers.LonLat(data.lon, data.lat);
var zoom = HAITI.map.getZoom() > 14 ? HAITI.map.getZoom() : 14;
HAITI.map.setCenter(lonlat.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")), zoom);
return;
}
} catch (E) {
}
var reg = /([\d-.]+),\s*([\d-.]+)/.exec(search);
if (reg) {
var lon = parseFloat(reg[2]);
var lat = parseFloat(reg[1]);
if (lon < 0 && lat > 0) {
var lonlat = new OpenLayers.LonLat(lon, lat);
} else {
var lonlat = new OpenLayers.LonLat(lat, lon);
}
var zoom = HAITI.map.getZoom() > 14 ? HAITI.map.getZoom() : 14;
HAITI.map.setCenter(lonlat.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")), zoom);
}
var s = document.createElement("script");
s.src="http://nominatim.openstreetmap.org/haiti/?viewbox=-76.24%2C21%2C-69.2%2C17&format=json&json_callback=gazhandleOsmLoc&q="+encodeURIComponent(search);
document.body.appendChild(s);
},
handleOsmLoc: function(data) {
if(this.panel) {
ltPanel.remove(this.panel);
}
var html = '';
for (var i = 0; i < data.length; i++) {
data[i]['lon'] = data[i].lon.toFixed(4);
data[i]['lat'] = data[i].lat.toFixed(4);
html += OpenLayers.String.format('<div class="result" onClick="gaz.go(${lon}, ${lat});"> <span class="name">${display_name}</span> <span class="latlon">Lat/Lon: ${lat}, ${lon}</span> <span class="place_id">${place_id}</span> <span class="type">(${type})</span> </div>', data[i]);
}
var panel = new Ext.Panel({'title':"Gazetter", html: html, autoScroll: true})
ltPanel.add(panel);
ltPanel.doLayout();
panel.expand();
ltPanel.doLayout();
this.panel = panel;
},
go: function(lon, lat) {
var lonlat = new OpenLayers.LonLat(lon, lat);
lonlat.transform(HAITI.map.displayProjection, HAITI.map.getProjectionObject());
lookupLayer.destroyFeatures();
lookupLayer.addFeatures(new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat)));
var zoom = HAITI.map.getZoom() > 15 ? HAITI.map.getZoom() : 15;
HAITI.map.setCenter(lonlat, zoom);
}
});
var gaz = new Gazetteer();
gazhandleOsmLoc = gaz.handleOsmLoc;
| 46.819672 | 293 | 0.547619 |
6a0795f5c02c241dac485ca71f8beb71fa94b644 | 8,479 | js | JavaScript | semantic/tasks/collections/internal.js | hossein-nas/AUSMT_new | 9ef444e1c075ae0c9e374648b8cf4f279e03e683 | [
"MIT"
] | null | null | null | semantic/tasks/collections/internal.js | hossein-nas/AUSMT_new | 9ef444e1c075ae0c9e374648b8cf4f279e03e683 | [
"MIT"
] | null | null | null | semantic/tasks/collections/internal.js | hossein-nas/AUSMT_new | 9ef444e1c075ae0c9e374648b8cf4f279e03e683 | [
"MIT"
] | null | null | null | /*******************************
Internal Task Collection
*******************************/
/* These tasks create packaged files from **dist** components
Not intended to be called directly by a user because
these do not build fresh from **src**
*/
module.exports = function(gulp) {
var
// node dependencies
fs = require('fs'),
chmod = require('gulp-chmod'),
concat = require('gulp-concat'),
concatCSS = require('gulp-concat-css'),
clone = require('gulp-clone'),
dedupe = require('gulp-dedupe'),
gulpif = require('gulp-if'),
header = require('gulp-header'),
less = require('gulp-less'),
minifyCSS = require('gulp-clean-css'),
plumber = require('gulp-plumber'),
print = require('gulp-print'),
rename = require('gulp-rename'),
replace = require('gulp-replace'),
uglify = require('gulp-uglify'),
// user config
config = require('./../config/user'),
docsConfig = require('./../config/docs'),
// user function
filepublisher = require('../rtl/filepublisher'),
// install config
tasks = require('./../config/tasks'),
release = require('./../config/project/release'),
// shorthand
globs = config.globs,
assets = config.paths.assets,
output = config.paths.output,
banner = tasks.banner,
filenames = tasks.filenames,
log = tasks.log,
settings = tasks.settings
;
/*--------------
Packaged
---------------*/
gulp.task('package uncompressed css', function() {
return gulp.src(output.uncompressed + '/**/' + globs.components + globs.ignored + '.css')
.pipe(plumber())
.pipe(dedupe())
.pipe(replace(assets.uncompressed, assets.packaged))
.pipe(concatCSS(filenames.concatenatedCSS, settings.concatCSS))
.pipe(gulpif(config.hasPermission, chmod(config.permission)))
.pipe(header(banner, settings.header))
.pipe(gulp.dest(output.packaged))
.pipe(print(log.created))
;
});
gulp.task('package compressed css', function() {
return gulp.src(output.uncompressed + '/**/' + globs.components + globs.ignored + '.css')
.pipe(plumber())
.pipe(dedupe())
.pipe(replace(assets.uncompressed, assets.packaged))
.pipe(concatCSS(filenames.concatenatedMinifiedCSS, settings.concatCSS))
.pipe(gulpif(config.hasPermission, chmod(config.permission)))
.pipe(minifyCSS(settings.concatMinify))
.pipe(header(banner, settings.header))
.pipe(gulp.dest(output.packaged))
.pipe(print(log.created))
;
});
gulp.task('package uncompressed js', function() {
return gulp.src(output.uncompressed + '/**/' + globs.components + globs.ignored + '.js')
.pipe(plumber())
.pipe(dedupe())
.pipe(replace(assets.uncompressed, assets.packaged))
.pipe(concat(filenames.concatenatedJS))
.pipe(header(banner, settings.header))
.pipe(gulpif(config.hasPermission, chmod(config.permission)))
.pipe(gulp.dest(output.packaged))
.pipe(print(log.created))
;
});
gulp.task('package compressed js', function() {
return gulp.src(output.uncompressed + '/**/' + globs.components + globs.ignored + '.js')
.pipe(plumber())
.pipe(dedupe())
.pipe(replace(assets.uncompressed, assets.packaged))
.pipe(concat(filenames.concatenatedMinifiedJS))
.pipe(uglify(settings.concatUglify))
.pipe(header(banner, settings.header))
.pipe(gulpif(config.hasPermission, chmod(config.permission)))
.pipe(gulp.dest(output.packaged))
.pipe(print(log.created))
.on('end', function(){
filepublisher.js();
})
;
});
/*--------------
RTL
---------------*/
if(config.rtl) {
gulp.task('package uncompressed rtl css', function () {
return gulp.src(output.uncompressed + '/**/' + globs.components + globs.ignoredRTL + '.rtl.css')
.pipe(dedupe())
.pipe(replace(assets.uncompressed, assets.packaged))
.pipe(concatCSS(filenames.concatenatedRTLCSS, settings.concatCSS))
.pipe(gulpif(config.hasPermission, chmod(config.permission)))
.pipe(header(banner, settings.header))
.pipe(gulp.dest(output.packaged))
.pipe(print(log.created))
;
});
gulp.task('package compressed rtl css', function () {
return gulp.src(output.uncompressed + '/**/' + globs.components + globs.ignoredRTL + '.rtl.css')
.pipe(dedupe())
.pipe(replace(assets.uncompressed, assets.packaged))
.pipe(concatCSS(filenames.concatenatedMinifiedRTLCSS, settings.concatCSS))
.pipe(gulpif(config.hasPermission, chmod(config.permission)))
.pipe(minifyCSS(settings.concatMinify))
.pipe(header(banner, settings.header))
.pipe(gulp.dest(output.packaged))
.pipe(print(log.created))
.on('end', function(){
filepublisher.css();
})
;
});
gulp.task('package uncompressed docs css', function() {
return gulp.src(output.uncompressed + '/**/' + globs.components + globs.ignored + '.css')
.pipe(dedupe())
.pipe(plumber())
.pipe(replace(assets.uncompressed, assets.packaged))
.pipe(concatCSS(filenames.concatenatedCSS, settings.concatCSS))
.pipe(gulpif(config.hasPermission, chmod(config.permission)))
.pipe(gulp.dest(output.packaged))
.pipe(print(log.created))
;
});
gulp.task('package compressed docs css', function() {
return gulp.src(output.uncompressed + '/**/' + globs.components + globs.ignored + '.css')
.pipe(dedupe())
.pipe(plumber())
.pipe(replace(assets.uncompressed, assets.packaged))
.pipe(concatCSS(filenames.concatenatedMinifiedCSS, settings.concatCSS))
.pipe(minifyCSS(settings.concatMinify))
.pipe(header(banner, settings.header))
.pipe(gulpif(config.hasPermission, chmod(config.permission)))
.pipe(gulp.dest(output.packaged))
.pipe(print(log.created))
;
});
}
/*--------------
Docs
---------------*/
var
docsOutput = docsConfig.paths.output
;
gulp.task('package uncompressed docs css', function() {
return gulp.src(docsOutput.uncompressed + '/**/' + globs.components + globs.ignored + '.css')
.pipe(dedupe())
.pipe(plumber())
.pipe(replace(assets.uncompressed, assets.packaged))
.pipe(concatCSS(filenames.concatenatedCSS, settings.concatCSS))
.pipe(gulpif(config.hasPermission, chmod(config.permission)))
.pipe(gulp.dest(docsOutput.packaged))
.pipe(print(log.created))
;
});
gulp.task('package compressed docs css', function() {
return gulp.src(docsOutput.uncompressed + '/**/' + globs.components + globs.ignored + '.css')
.pipe(dedupe())
.pipe(plumber())
.pipe(replace(assets.uncompressed, assets.packaged))
.pipe(concatCSS(filenames.concatenatedMinifiedCSS, settings.concatCSS))
.pipe(minifyCSS(settings.concatMinify))
.pipe(header(banner, settings.header))
.pipe(gulpif(config.hasPermission, chmod(config.permission)))
.pipe(gulp.dest(docsOutput.packaged))
.pipe(print(log.created))
;
});
gulp.task('package uncompressed docs js', function() {
return gulp.src(docsOutput.uncompressed + '/**/' + globs.components + globs.ignored + '.js')
.pipe(dedupe())
.pipe(plumber())
.pipe(replace(assets.uncompressed, assets.packaged))
.pipe(concat(filenames.concatenatedJS))
.pipe(header(banner, settings.header))
.pipe(gulpif(config.hasPermission, chmod(config.permission)))
.pipe(gulp.dest(docsOutput.packaged))
.pipe(print(log.created))
;
});
gulp.task('package compressed docs js', function() {
return gulp.src(docsOutput.uncompressed + '/**/' + globs.components + globs.ignored + '.js')
.pipe(dedupe())
.pipe(plumber())
.pipe(replace(assets.uncompressed, assets.packaged))
.pipe(concat(filenames.concatenatedMinifiedJS))
.pipe(uglify(settings.concatUglify))
.pipe(header(banner, settings.header))
.pipe(gulpif(config.hasPermission, chmod(config.permission)))
.pipe(gulp.dest(docsOutput.packaged))
.pipe(print(log.created));
;
});
};
| 35.776371 | 102 | 0.612454 |
6a0812f0673617c525a7586bf4c997c6d4ab4ae5 | 11,135 | js | JavaScript | template_src/www/static/js/app.9e21d961edcde6712a97.js | jeeinn/hello-cordova-vuejs | df3ddcbc129516532b7f602bb22b95396fb36371 | [
"MIT"
] | 2 | 2018-10-08T03:06:45.000Z | 2019-01-30T02:34:34.000Z | template_src/www/static/js/app.9e21d961edcde6712a97.js | jeeinn/hello-cordova-vuejs | df3ddcbc129516532b7f602bb22b95396fb36371 | [
"MIT"
] | 5 | 2019-07-08T08:38:02.000Z | 2022-02-26T05:49:16.000Z | template_src/www/static/js/app.9e21d961edcde6712a97.js | jeeinn/hello-cordova-vuejs | df3ddcbc129516532b7f602bb22b95396fb36371 | [
"MIT"
] | 1 | 2019-01-01T18:15:47.000Z | 2019-01-01T18:15:47.000Z | webpackJsonp([0],{"68Fd":function(t,i){},NHnr:function(t,i,e){"use strict";Object.defineProperty(i,"__esModule",{value:!0});var n=e("/5sW"),c={render:function(){var t=this.$createElement,i=this._self._c||t;return i("div",{attrs:{id:"app"}},[i("img",{attrs:{src:e("SFhU")}}),this._v(" "),i("img",{attrs:{src:e("U6PP")}}),this._v(" "),i("router-view")],1)},staticRenderFns:[]};var s=e("VU/8")({name:"App"},c,!1,function(t){e("UcoW")},null,null).exports,a=e("/ocq"),h={name:"HelloWorld",data:function(){return{msg:"Welcome to Your Cordova & Vue.js App"}},mounted:function(){({initialize:function(){document.addEventListener("deviceready",this.onDeviceReady.bind(this),!1)},onDeviceReady:function(){this.receivedEvent("deviceready")},receivedEvent:function(t){console.log("Received Event: "+t)}}).initialize(),setTimeout(function(){console.log("hello vue.")},5e3)}},l={render:function(){var t=this.$createElement,i=this._self._c||t;return i("div",{staticClass:"hello"},[i("h1",[this._v(this._s(this.msg))]),this._v(" "),i("h2",[this._v("Essential Links")]),this._v(" "),this._m(0)])},staticRenderFns:[function(){var t=this.$createElement,i=this._self._c||t;return i("ul",[i("li",[i("a",{attrs:{href:"https://cordova.apache.org/",target:"_blank"}},[this._v("\n Cordava\n ")])]),this._v(" "),i("li"),i("li",[i("a",{attrs:{href:"https://vuejs.org",target:"_blank"}},[this._v("\n Vue\n ")])]),this._v(" "),i("li",[i("a",{attrs:{href:"https://github.com/jeeinn",target:"_blank"}},[this._v("\n Github\n ")])])])}]};var r=e("VU/8")(h,l,!1,function(t){e("68Fd")},"data-v-44447cfa",null).exports;n.a.use(a.a);var I=new a.a({routes:[{path:"/",name:"HelloWorld",component:r}]});n.a.config.productionTip=!1,new n.a({el:"#app",router:I,render:function(t){return t(s)}})},SFhU:function(t,i,e){t.exports=e.p+"static/img/cordova_bot.2d401fa.png"},U6PP:function(t,i){t.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyNpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMDE0IDc5LjE1Njc5NywgMjAxNC8wOC8yMC0wOTo1MzowMiAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6OTk2QkI4RkE3NjE2MTFFNUE4NEU4RkIxNjQ5MTYyRDgiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6OTk2QkI4Rjk3NjE2MTFFNUE4NEU4RkIxNjQ5MTYyRDgiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIChNYWNpbnRvc2gpIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6NjU2QTEyNzk3NjkyMTFFMzkxODk4RDkwQkY4Q0U0NzYiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6NjU2QTEyN0E3NjkyMTFFMzkxODk4RDkwQkY4Q0U0NzYiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz5WHowqAAAXNElEQVR42uxda4xd1XVe53XvvD2eGQ/lXQcKuDwc2eFlCAGnUn7kT6T86J/+aNTgsWPchJJYciEOCQ8hF+G0hFCIHRSEqAuJBCqRaUEIEbmBppAIBGnESwZje8COZ+y587j3PLq+ffadGJix53HvPevcuz60xPjec89ZZ+39nf04+9vLSZKEFArFzHA1BAqFEkShUIIoFEoQhUIJolAoQRQKJYhCoQRRKJQgCoUSRKFQKEEUCiWIQrFo+Gv/8/YH+f/nsMWSHHMChyhxqPTTdyncWyJ3ScD/ztipiB3wXSqu6P17avN+TyFC5ggv4tRnmoxWTP1+5F+Mz17GPvPl49EKBWd3UsfXllPiso8VcYtmPba3fNuKrBVXrGFCbrdPwXndFL49ltI367roOpSUI4pGypv9s7q+ltj6JxqOQ07Bo/DgxGb2/a8cX0CnAWXJ5etz2TqdHiXHKlKj9w6i9XX8Ic41DmI8FVHhmmXk85MmRhCzJoiTWnig9LfJRHihgydxzAxJhBr7Bh/hK3yu+p9568FliTJF2aKMZfVd/kQOcKP6OBmS9+Rjm4zJ6faoeN0gOUn61MncLX4CJ+MRhe+P/dRxhfew2Df4CF/hs4jWg8vQYUKYMuWyRRkLjeHQ8YP0Z9mekVjA8Qj3VVcuoeDiXu63lkUE0ym6FA5PXBaNVr7qtPumGyPR4Bt8hK/wWUR5chn6XJYoU5StUHL8l+XEx2axhkS6yk+chJuP4rXLyOkIKJkS0B67adcqfL/0Y4pixxSysK6V8Yl9Mz7i3272NRFlhzJsu24Z5l9E9Ahmwfrpoj7uw3fZtktsRZKjIXnndlLxin7+W8ZTBwPf6I+Tg9HwxK2Ob8citbCoBoaxBxMCvsFH+CqjHCtUvLzflKWUcpwB91gupG5f9/Rtx39ZZBtmWyJtphKzHTQW0diP36b4aJmcLj/zGaSkHJPb4SWFi/tOJd8bTqd9s48VBRh4RKeUX/vjgXg8cpyCmz05xkJylxSoa8M5RF0eJaVIIkGOsg2yTc3UgpD94psiWxEOqDNYoOIXuHnGwE5AXUTFi46FTnRw4l/dwEm7/pSxcYnCF/gE3zInh52RRJkVP7/MlKFQcgCbjifHTAQBfsb2qsgBO3e1Cpf3UXBej3nRJKKrxU/rcH/pKzz4vNIQuRJTEmZklbg6EL4SPsE3GQPzinmfhbJDGQolB+r8w58abs5y8DqRt4ABeptLRR7koY9NleybEYw/MPisvF/ayT1/SvDewcnIcG32wfiCAbEvoCZyGaGsitdyz6XdTctQJq6fcT5mloNfYvu5yFZkpEz+RT0UrFoqpxVBV+vQxIrkaPnrbqdvXs6hcjbU+Jq4Nvvwd/BFRNeq2npwWfkX95iyE9p6PM72P/MhCPANTBSKu5WITHcC074Y9CUTkYglKBgcV/aVtlM5Kpp/RHFjDdfka7MP/2wG6m72661QNigjlBXKTGBtsjWKNs5atCf44Uds3xc5YD8Wknd2BxWuGjCzIxLWQzlFj+IjU108OL7bafM5sm5DDdfka/8T+9AJXyTMpqFsUEYoK5SZ0NbjVlvX500Q4Ha2A+JuCcEvhVS8qp/8MzspHhMSfO7mVPaP35BMRp9JsCQldbX+hmvxNfnamzJfqVvtWnGZoGxQRigroYs6UbfvOGHn4ORVkTaIbEWwtqg3MNO+Zql0JGCdVuCayhDuG9uJB7vp+oR17FbZc+NauCauLWLmKkqXr6NsUEYoK6GtxwY6CXXnEs0n2faIHLCPhhR8bikFKwRN+xZddHWu5a7Ol9yCZ2ZwHKdOxufGNeKRqS/hmnLWW1VMmQSrl5oyEkqOPbZu02IJAsic9sU7B+5uF9cOmqUfeLOdOaAZYb/CA+M/Ic9NxUoYMNfD/PT84f7xB807EAnrrbgMUBZt1w1SEpCIqfjF1Om5EuQNth0iu1r8tPLP76LCpX2yWpHDk2dGH018p6brtD5hOHf04cR3okOTZ0lqPVAW3gVdlMhdrfsTW6drRhDgRrYJcbeKZQxTkenvegNt6YBQwrQvOxG+P3ZHEia9TuClS9Br1XKge8XnxLlxjelzZ/2w4tijDMxyoHIsVQg1zvYPcy7KeZx4jG2zyFakFJF7Whu1XT2QvhfJeryeVNdplYPo4Pi9hKd7VVxVC8O5cH4+N65hXgoKuGfEHmWAskjGxI49Ntu6XHOCAD9ie1PcLSepjDNY00fB8m6KpSyJx/jgg9LfJEfLK40818w+LXY5e5zKaMfKl+DcIlSCZp0cd3U59igDI4+WOa2LunvfvDoD9RrcNLqAjDy3yzfrtKqbAkggSDIZmSlYxzz9a8BaJ101zF2rh3BuSTJaCKGMDEGujHbedXch0X2ebbdEkkDC6a9cQoWVguS53P0JP5xcHY1W/tppD9KxgrdAw5QxnwPn4nOukrPeqkzBJb0m9oJltLtt3a07QYD1IkMAeS7/hw0BXMhzJwXJc/eV7kuiyIN8OOGuUhLP06JUeoxz4FxiZLRouTsDM9WO2OdBRtsIgrzHtk3kgH00JO+cTipc2S9jqyCaluf2xwcnfuB6LndHuEsSzdP4N/gtzoFzSZHRIsaQQiPmidyXgttsnW0YQYDvsh2ROGBPxkMqXjNA/qlCFsnZ8UdlX+kfk0pymlnMWH2JOBfz0sWI+C3OMS1dzPphhPVWHOPC5wdMzIUOzFFHb1lwB2ARF+ZOPt0gshWBPLe/wCRZlu6CIkSei/cE0fD4g2ZbVWceyxH5WPwGvzXrrSTJaDnG7oBoGS3qaCULggCPsv1W5IAd8tzLllJwvpx1WthMIfyg9OVotHy1WVQ4V37wsfgNfkuSZLQcW8Q4lruU/RVbRykrggDXiwwN3uQWnXTa1xMkz2W/on2lndNajpNtAGePw2/MOicBMlqs+8K7GBNbjrFgGe2iX0nUgiAvs+0S2YpgndaFPVRc3SdmVanZlfGjifOiw5PrT/oGvPpG/vDkEH4jZ70Vt86rl5rYimmdP41/s3Uzc4Isup9XNxwvz+0tyNAlONPrtO6hctR+QnluKqNt52O3pxvtClhvxTH0egtmEwbBMlrUxU21OFGtCHKYbavIATv3j90z26kIea4QZRtahfhIuT0anrjH7O3rpjNVHzPIaLG3Lh8Tj5TbRQihjlNyehxTwTLarbZOiiEIcBfbPnGhMtroChXW9JN/VqeYdyPEY4nwwPj6ZCL8C1T+T61JhDqRv8MxZgwlJG2BxzEsrBmgeEzseqt9ti6SNIIA8t6wm901eFDZ66d7M4UkQ56LVgTTvvtKaRqFqoTWymjxGb6LpUzrImYcuzaOIWKJmAptPWpaB2sd+V+yvSB1wB6s7qXgwiUyBpbJdBqFq6MjU18mKCKhRsTyEbx558/wnRmYJzLiV+DYBat6JQ/MX7B1UCxBAKHy3IQrH6W7MhY9MWkUMNAN948/8Mm35/jMDIKlpC3gmBWQtsAjifkE61b36kGQP7DdL7KrVZXnXiYpjYKZxj09Gh7f4kB4yIa/8ZmU1brIIYiYIXaJ3Nbjflv3xBME+DZbSVwIzfIIK89dJkSea18Ihu+XflD9yPztCJnW5Ri5VRntpNh8giVb5ygvBIHu9yaRrchYRO6fFU0CSTPQlDLte6zshx9O3g3D3yJajySd4EDaAsQMsRPaetxk61zty+YTCXRqjf9jO19cOLnyYV+p8QffpcreMXJ7BeRgh77Ds6SIYhGbMBgB2tld1DW0nGL4VxbZfKBbdUHdhol1dl7mOi0MOjttGgWT11lAwU9r1mMSsX0oxwSxgYyWOvKXtiAvBPkV239I7GqZdVqX9FDw2V5+UoYipn2nt/WRMK3LMQlW9poYCZ7WfcrWsdwSBNggMrRYdcLdhjas0+q28lzJOc8bOU7jWLh2AwzEyLxclYm6Z2ZuBEE+YLtTZEVA9tzPdBh5biJ3q5rGD8yRjXbNAPkcm0RuyjTUqf3NQBDge2yHJFaGeDyi4tUD5J3WIXmzs8Y9NDgG3un80OCYIDZCHxqHbJ2iZiEIGmnB8twgzYIkd7vMxiBON59GLJyBQLKMdiM1qOPXyMn2f2f7X5EDdshzkUbhAtED0oZMXCAGiIXgtAW/YXusURdr9NsoufLcgmP20zKy2ErrNSNGRuunMUAshL7zABq61q/RBPkd2yNSn57+X3ZTQZA8t7H3H5p7RwwEt6KP2DrUtAQBIIUsiwt99Kf+tydFntuocVhVRltNWyBTRlumGslopRNkhO1mkRVlLCT3jHYzqyU48WSN+1ZWRou0BZDRyp3Ju9nWnaYnCHA3216JlQWy0gKy557dJSaNQn0nKNL1VrhnwTLavbbOUKsQBBApzzVpFHqsPFdIGoW6AfeG7cMwrcv3TC0io80LQZ5me07kU3WkYqSlhYvkpFGoz8C8bO7RyGjlpi14ztaVliMIIFOeizQKbpI+WdsDGfLcWvcmsaK53b4gdUW3lENZXjxrgrzNdq/IAftohbzzOql4eV/zjUUcu96K7w33KFhGi7rxVisTBEBSxWPiiqYqz71mGfmDQuS5tSIHstHyPZnd7+XKaI+RgKSxEggySWmKaXkVaSwi5xSbRmGiSdZpxVZGy/eEexMso73R1o2WJwiwk+11kQNZrNO6oo+Cc7vz39Wy07q4l+CKfnNvQu/ndVsnSAkifcCOAXq7R8W1y9JdRvI87QvfnTRtgdPeujLavBLkv9meEPnUHS2Tf1EPFT67lOKRnE77munrsrkH/+IeydPXqAO/VoLMDMhz5T2irTzXpFHoKeRPnluV0XYX0mlduTLamIRJtKUR5CDbbSIrGPfX/eUdVFyTQ3luku6OaNIW/HmH5LQFt9k6oAQ5Ab7PNiyxkmGndUhRvTNyJM9F1wrZaM9IZbQmG63MocewxIejRIKg+DaKbEXGI3KWBtT2hUFKyonUZeEfB3xkX4vsM3wXvIx/IwmMqCu0WH/B9qLIpzG6Wp/rpWBFj/x1WnaCAb4G7LPgad0XbZmTEmTukDnti0yzgZvKcwNPtDzXyGjZR5ONFincVEbbVAR5je0hkU/lkTL5F3TZzQ2EvjysJr1hH/0LuiVPTz9ky1oJsgB8iwQsN5hplISns5Hn9hXl9eurMlr2zUzrVsQuk5m0ZUxKkIXhKNsWkQN2yHNPhzx3WbqQMRZGYCOjXWZ8FDzjtsWWsRJkEfgh2zvyOvhWnovsucu75GTPtdlo4RN8i+W+s3nHli0pQRaPIXEeVeW53V46YJciz2Uf4IvxiX0juW/9h/JQ8fJCkGfZnpE5YK9QsHIJBZcIkOdW141d3Gt8EiyjfcaWqRKk6Z84kOc6duODjmzluUZGyz4g6Q18UhltaxHkXbbtIgfsRyvknQt5bobZc6dltP3Gl0SudmW7LUslSJ1mPUbFeWVUepDnDpB3SgazRtW0BXxt+ABfhE7rypyVbCKCTLF9U2QrgjQKg3b7zskGv3eI0+XsuDZ8EJy2YJMtQyVIHfEztldFDtghz728j4LzGphGoZq2gK9ZMDuwiH3ngTJ7OG+VLY8EAeTKc9ts9lwk42zEOi2st+JrYZIA1xYso12Xx4qWV4K8xPZzka3ISCrPDVY1YJ1WtfVYZWW0ctdbPW7LTAnSQHyDJCoykEYhTNdpuUsK6YDZqQ85cG5cw6y3CsWmLYBXG/NayfJMkI8oVR/KG7AfC8k7u4MKVw2kM1r1eB2RpDNXuAauJVhGe6stKyVIBrid7YA4r6o5N5BG4cxOI3mtaeWtymj53LiG4FwmKJs78lzB8k4QVIsN4ryqynN7AzP1ShXIc2tYg3GuSpJO6/aKltHK3KWmhQgCPMm2R+SAfTSkANlzV9Rw2rc6MDcyWtHZaPfYsiElSPaQOYVYiSnxiIprB8kpeGn+v8U2mZD8FjxzTpybKjqtqwQ5Od5g2yGyq4Xsued3UeHSvsW3IlUZLZ8L5xSctmCHLRMliCBgN/AJcV7F6SpbjBe8gUWkUaimLeBzmOUsU2JltOMkcbd+JQiNkYB8ErNVbPe0Nmq72i4kXMiwNUnfe+AcOJfgfCWbbVkoQQTiR2xvivPKynODNX0ULF9AGoVq2gL+Lc4hWEaL2N/XTBWq2Qgic3BYled2+ekeVfOV51az0WKNF59DsIx2XbNVpmYkyPNsuyWSBBJYf+USKsxHnlvNRsu/8WXLaHfb2CtBcoD1Ir2CPJf/wxSt2xmkupGT9c6QtoCPNdO66FfJldGub8aK1KwEeY9tm8gB+2hI3jmdVLii/+RbBdktfHAsfpPIfSm4zcZcCZIjfJftiMQBO1IQQBrrn3qCRYZ20SOOMTLacbHrrRDjW5q1EjUzQbiTTzeIbEUgz+232XNne59RfX+CbLT9omW0iHFFCZJPPMr2W5EDdshzL1tKwfkzrNOqrrfi73CMYBntKzbGpATJL64X6RXWZRVtxlnP+VgaBZO2wEu/wzGatkAJUk+8zLZLZCuCdVoXciux+rhVuXYVMD7Dd7Hc9Va7bGyVIE0Amf3kaXnuIHm9qTwXhr/xmWAZbUXk+E4JsmAcZtsqcsAOee6Z7VS08lwY/sZngmW0W21MlSBNhLvY9onzCqtIxipUuKqf3L6iMfyNz4RO6+6zsWwJ+NRawNvep8S1IhMxucie+8VT0o+6PIqPiB17rG+lCtNqBPkl2wts14gbsCONwqVLzT8Fr7d6wcawZeBS60Hm1GSSTu+a6d5EY6cEyQ5/YLtf4oCd4iQ1ma3H/TZ2SpAWwLfZSqSYK0o2ZqQEaQ1AN32T1vs54yYbMyVIC+GBVuwyLLBL+kCr3rzb4oV/vdZ/jZESZHb8iqS9F5GFp2yMlCAtjCENgcZGCTI79rPdqWH4FO60sVGCKOh7bIc0DNM4ZGNCShAFEFKOsyDVARttTJQgGoJpPMb2Gw2DicFjGgYlyExYpyHQGChBZsfv2B5p4ft/xMZAoQSZFZso3TKo1VC2965QgpwQI2w3t+B932zvXaEEOSnuZtvbQve7196zQgkyZ6zXe1UoQWbH02zPtcB9PmfvVaEEmTeG9B6VIIrZ8RbbvU18f/fae1QoQRYMJKU81oT3dYwkJj1VguQOk9REaY2Pw4323hRKkEVjJ9vrTXQ/r9t7UihBaobr9V6UIIrZ8Wu2J5rgPp6w96JQgtQcG2jmhGl5QWzvQaEEqQsOst2WY/9vs/egUILUtZIN59Dv4ZyTWwmSEyDnUx7luRtJar4qJUjT4RdsL+bI3xetzwolSMOwTn1Vgihmx2tsD+XAz4esrwolSMPxLZK9XGPS+qhQgmSCo2xbBPu3xfqoUIJkhh+yvSPQr3esbwolSOYYUp+UIIrZ8SzbM4L8ecb6pFCC6BNbWw8lSB7wLtt2AX5st74olCDikPWskfRZNSVIi2OKst2+c5P1QaEEEYuH2V7N4Lqv2msrlCDisa5FrqkEUSwIL7E93sDrPW6vqVCC5AaN0l/kVZ+iBGlxfMR2awOuc6u9lkIJkjvcwXagjuc/YK+hUILkEgnVdxeRDfYaCiVIbvEk2546nHePPbdCCZJ7rMvJORVKkEzwBtuOGp5vhz2nQgnSNMBu6uM1OM84Nedu80qQFscY1SYfx2Z7LoUSpOlwH9ubi/j9m/YcCiWIDth1YK4EaUU8z7Z7Ab/bbX+rUII0PdY36DcKJUgu8R7btnkcv83+RqEEaRncwnZkDscdsccqlCAthQrbDXM47gZ7rEIJ0nJ4lO2VE3z/ij1GoQRpWaxb4HcKJUhL4GW2XTN8vst+p1CCtDw+Oc6Y6/hEoQRpCRxm23rcv7fazxRKEIXFXZRuwBDZvxUC4GsIREHflguDkyQqaVYotIulUChBFAoliEKhBFEolCAKhRJEoVCCKBRKEIVCCaJQKJQgCoUSRKFQgigUShCFIhP8vwADACog5YM65zugAAAAAElFTkSuQmCC"},UcoW:function(t,i){}},["NHnr"]);
//# sourceMappingURL=app.9e21d961edcde6712a97.js.map | 5,567.5 | 11,082 | 0.916929 |
6a082c3db552d4673e59f9d0bc9219bf8595eec6 | 2,098 | js | JavaScript | src/slam/test/test-start-stop.js | 01org/node-realsense | 9c000380f61912415c2943a20f8caeb41d579f7b | [
"MIT"
] | 12 | 2017-02-27T14:10:12.000Z | 2017-09-25T08:02:07.000Z | src/slam/test/test-start-stop.js | 01org/node-realsense | 9c000380f61912415c2943a20f8caeb41d579f7b | [
"MIT"
] | 209 | 2017-02-22T08:02:38.000Z | 2017-09-27T09:26:24.000Z | src/slam/test/test-start-stop.js | 01org/node-realsense | 9c000380f61912415c2943a20f8caeb41d579f7b | [
"MIT"
] | 18 | 2017-02-22T09:05:42.000Z | 2017-09-21T07:52:40.000Z | // Copyright (c) 2016 Intel Corporation. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
'use strict';
/* global describe, it */
const assert = require('assert');
const addon = require('bindings')('realsense_slam');
let EventEmitter = require('events').EventEmitter;
function inherits(target, source) {
// eslint-disable-next-line
for (let k in source.prototype) {
target.prototype[k] = source.prototype[k];
}
}
inherits(addon.Instance, EventEmitter);
describe('SLAM Test Suite - start-stop', function() {
let slamInstance = undefined;
before(function() {
// eslint-disable-next-line no-invalid-this
this.timeout(50000);
return new Promise((resolve, reject) => {
addon.createInstance().then(function(instance) {
assert.equal(typeof (instance), 'object');
slamInstance = instance;
assert.equal(slamInstance.state, 'ready');
resolve();
}).catch((e) => {
reject(e);
});
});
});
it('Test start-stop-start-stop', function() {
// eslint-disable-next-line no-invalid-this
this.timeout(50000);
return new Promise((resolve, reject) => {
slamInstance.start().then(function() {
assert.equal(slamInstance.state, 'tracking');
return slamInstance.stop();
}, function(e) {
console.log('start error:' + e);
reject(e);
})
.then(function() {
// Start SLAM again.
assert.equal(slamInstance.state, 'ready');
return slamInstance.start();
}, function(e) {
console.log('stop error:' + e);
reject(e);
})
.then(function() {
assert.equal(slamInstance.state, 'tracking');
return slamInstance.stop();
}, function(e) {
console.log('start again error:' + e);
reject(e);
})
.then(function() {
assert.equal(slamInstance.state, 'ready');
resolve();
}, function(e) {
console.log('stop again error:' + e);
reject(e);
});
});
});
});
| 28.739726 | 73 | 0.593899 |
6a08359189ce121f5c43279546c5d68d3b405f0c | 556,449 | js | JavaScript | amza-ui/src/main/resources/resources/static/amza/scripts/protovis-r3.2.js | jivesoftware/amza | be79c33833d725eb0338cb3b278ef52a182af45f | [
"Apache-2.0"
] | 8 | 2015-03-29T09:21:47.000Z | 2017-08-05T17:35:03.000Z | amza-ui/src/main/resources/resources/static/amza/scripts/protovis-r3.2.js | jivesoftware/amza | be79c33833d725eb0338cb3b278ef52a182af45f | [
"Apache-2.0"
] | null | null | null | amza-ui/src/main/resources/resources/static/amza/scripts/protovis-r3.2.js | jivesoftware/amza | be79c33833d725eb0338cb3b278ef52a182af45f | [
"Apache-2.0"
] | 3 | 2016-08-01T21:35:57.000Z | 2018-03-08T04:17:16.000Z | /**
* @class The built-in Array class.
* @name Array
*/
/**
* Creates a new array with the results of calling a provided function on every
* element in this array. Implemented in Javascript 1.6.
*
* @function
* @name Array.prototype.map
* @see <a
* href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Map">map</a>
* documentation.
* @param {function} f function that produces an element of the new Array from
* an element of the current one.
* @param [o] object to use as <tt>this</tt> when executing <tt>f</tt>.
*/
if (!Array.prototype.map)
Array.prototype.map = function (f, o) {
var n = this.length;
var result = new Array(n);
for (var i = 0; i < n; i++) {
if (i in this) {
result[i] = f.call(o, this[i], i, this);
}
}
return result;
};
/**
* Creates a new array with all elements that pass the test implemented by the
* provided function. Implemented in Javascript 1.6.
*
* @function
* @name Array.prototype.filter
* @see <a
* href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/filter">filter</a>
* documentation.
* @param {function} f function to test each element of the array.
* @param [o] object to use as <tt>this</tt> when executing <tt>f</tt>.
*/
if (!Array.prototype.filter)
Array.prototype.filter = function (f, o) {
var n = this.length;
var result = new Array();
for (var i = 0; i < n; i++) {
if (i in this) {
var v = this[i];
if (f.call(o, v, i, this))
result.push(v);
}
}
return result;
};
/**
* Executes a provided function once per array element. Implemented in
* Javascript 1.6.
*
* @function
* @name Array.prototype.forEach
* @see <a
* href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/ForEach">forEach</a>
* documentation.
* @param {function} f function to execute for each element.
* @param [o] object to use as <tt>this</tt> when executing <tt>f</tt>.
*/
if (!Array.prototype.forEach)
Array.prototype.forEach = function (f, o) {
var n = this.length >>> 0;
for (var i = 0; i < n; i++) {
if (i in this)
f.call(o, this[i], i, this);
}
};
/**
* Apply a function against an accumulator and each value of the array (from
* left-to-right) as to reduce it to a single value. Implemented in Javascript
* 1.8.
*
* @function
* @name Array.prototype.reduce
* @see <a
* href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Reduce">reduce</a>
* documentation.
* @param {function} f function to execute on each value in the array.
* @param [v] object to use as the first argument to the first call of
* <tt>t</tt>.
*/
if (!Array.prototype.reduce)
Array.prototype.reduce = function (f, v) {
var len = this.length;
if (!len && (arguments.length == 1)) {
throw new Error("reduce: empty array, no initial value");
}
var i = 0;
if (arguments.length < 2) {
while (true) {
if (i in this) {
v = this[i++];
break;
}
if (++i >= len) {
throw new Error("reduce: no values, no initial value");
}
}
}
for (; i < len; i++) {
if (i in this) {
v = f(v, this[i], i, this);
}
}
return v;
};
/**
* The top-level Protovis namespace. All public methods and fields should be
* registered on this object. Note that core Protovis source is surrounded by an
* anonymous function, so any other declared globals will not be visible outside
* of core methods. This also allows multiple versions of Protovis to coexist,
* since each version will see their own <tt>pv</tt> namespace.
*
* @namespace The top-level Protovis namespace, <tt>pv</tt>.
*/
var pv = {};
/**
* Protovis version number. See <a href="http://semver.org">semver.org</a>.
*
* @type string
* @constant
*/
pv.version = "3.3.1";
/**
* Returns the passed-in argument, <tt>x</tt>; the identity function. This method
* is provided for convenience since it is used as the default behavior for a
* number of property functions.
*
* @param x a value.
* @returns the value <tt>x</tt>.
*/
pv.identity = function (x) {
return x;
};
/**
* Returns <tt>this.index</tt>. This method is provided for convenience for use
* with scales. For example, to color bars by their index, say:
*
* <pre>.fillStyle(pv.Colors.category10().by(pv.index))</pre>
*
* This method is equivalent to <tt>function() this.index</tt>, but more
* succinct. Note that the <tt>index</tt> property is also supported for
* accessor functions with {@link pv.max}, {@link pv.min} and other array
* utility methods.
*
* @see pv.Scale
* @see pv.Mark#index
*/
pv.index = function () {
return this.index;
};
/**
* Returns <tt>this.childIndex</tt>. This method is provided for convenience for
* use with scales. For example, to color bars by their child index, say:
*
* <pre>.fillStyle(pv.Colors.category10().by(pv.child))</pre>
*
* This method is equivalent to <tt>function() this.childIndex</tt>, but more
* succinct.
*
* @see pv.Scale
* @see pv.Mark#childIndex
*/
pv.child = function () {
return this.childIndex;
};
/**
* Returns <tt>this.parent.index</tt>. This method is provided for convenience
* for use with scales. This method is provided for convenience for use with
* scales. For example, to color bars by their parent index, say:
*
* <pre>.fillStyle(pv.Colors.category10().by(pv.parent))</pre>
*
* Tthis method is equivalent to <tt>function() this.parent.index</tt>, but more
* succinct.
*
* @see pv.Scale
* @see pv.Mark#index
*/
pv.parent = function () {
return this.parent.index;
};
/**
* Stores the current event. This field is only set within event handlers.
*
* @type Event
* @name pv.event
*/
/**
* @private Returns a prototype object suitable for extending the given class
* <tt>f</tt>. Rather than constructing a new instance of <tt>f</tt> to serve as
* the prototype (which unnecessarily runs the constructor on the created
* prototype object, potentially polluting it), an anonymous function is
* generated internally that shares the same prototype:
*
* <pre>function g() {}
* g.prototype = f.prototype;
* return new g();</pre>
*
* For more details, see Douglas Crockford's essay on prototypal inheritance.
*
* @param {function} f a constructor.
* @returns a suitable prototype object.
* @see Douglas Crockford's essay on <a
* href="http://javascript.crockford.com/prototypal.html">prototypal
* inheritance</a>.
*/
pv.extend = function (f) {
function g() {
}
g.prototype = f.prototype || f;
return new g();
};
try {
eval("pv.parse = function(x) x;"); // native support
} catch (e) {
/**
* @private Parses a Protovis specification, which may use JavaScript 1.8
* function expresses, replacing those function expressions with proper
* functions such that the code can be run by a JavaScript 1.6 interpreter. This
* hack only supports function expressions (using clumsy regular expressions, no
* less), and not other JavaScript 1.8 features such as let expressions.
*
* @param {string} s a Protovis specification (i.e., a string of JavaScript 1.8
* source code).
* @returns {string} a conformant JavaScript 1.6 source code.
*/
pv.parse = function (js) { // hacky regex support
var re = new RegExp("function\\s*(\\b\\w+)?\\s*\\([^)]*\\)\\s*", "mg"), m, d, i = 0, s = "";
while (m = re.exec(js)) {
var j = m.index + m[0].length;
if (js.charAt(j) != '{') {
s += js.substring(i, j) + "{return ";
i = j;
for (var p = 0; p >= 0 && j < js.length; j++) {
var c = js.charAt(j);
switch (c) {
case '"':
case '\'':
{
while (++j < js.length && (d = js.charAt(j)) != c) {
if (d == '\\')
j++;
}
break;
}
case '[':
case '(':
p++;
break;
case ']':
case ')':
p--;
break;
case ';':
case ',':
if (p == 0)
p--;
break;
}
}
s += pv.parse(js.substring(i, --j)) + ";}";
i = j;
}
re.lastIndex = j;
}
s += js.substring(i);
return s;
};
}
/**
* @private Computes the value of the specified CSS property <tt>p</tt> on the
* specified element <tt>e</tt>.
*
* @param {string} p the name of the CSS property.
* @param e the element on which to compute the CSS property.
*/
pv.css = function (e, p) {
return window.getComputedStyle
? window.getComputedStyle(e, null).getPropertyValue(p)
: e.currentStyle[p];
};
/**
* @private Reports the specified error to the JavaScript console. Mozilla only
* allows logging to the console for privileged code; if the console is
* unavailable, the alert dialog box is used instead.
*
* @param e the exception that triggered the error.
*/
pv.error = function (e) {
(typeof console == "undefined") ? alert(e) : console.error(e);
};
/**
* @private Registers the specified listener for events of the specified type on
* the specified target. For standards-compliant browsers, this method uses
* <tt>addEventListener</tt>; for Internet Explorer, <tt>attachEvent</tt>.
*
* @param target a DOM element.
* @param {string} type the type of event, such as "click".
* @param {function} the event handler callback.
*/
pv.listen = function (target, type, listener) {
listener = pv.listener(listener);
return target.addEventListener
? target.addEventListener(type, listener, false)
: target.attachEvent("on" + type, listener);
};
/**
* @private Returns a wrapper for the specified listener function such that the
* {@link pv.event} is set for the duration of the listener's invocation. The
* wrapper is cached on the returned function, such that duplicate registrations
* of the wrapped event handler are ignored.
*
* @param {function} f an event handler.
* @returns {function} the wrapped event handler.
*/
pv.listener = function (f) {
return f.$listener || (f.$listener = function (e) {
try {
pv.event = e;
return f.call(this, e);
} finally {
delete pv.event;
}
});
};
/**
* @private Returns true iff <i>a</i> is an ancestor of <i>e</i>. This is useful
* for ignoring mouseout and mouseover events that are contained within the
* target element.
*/
pv.ancestor = function (a, e) {
while (e) {
if (e == a)
return true;
e = e.parentNode;
}
return false;
};
/** @private Returns a locally-unique positive id. */
pv.id = function () {
var id = 1;
return function () {
return id++;
};
}();
/** @private Returns a function wrapping the specified constant. */
pv.functor = function (v) {
return typeof v == "function" ? v : function () {
return v;
};
};
/*
* Parses the Protovis specifications on load, allowing the use of JavaScript
* 1.8 function expressions on browsers that only support JavaScript 1.6.
*
* @see pv.parse
*/
pv.listen(window, "load", function () {
/*
* Note: in Firefox any variables declared here are visible to the eval'd
* script below. Even worse, any global variables declared by the script
* could overwrite local variables here (such as the index, `i`)! To protect
* against this, all variables are explicitly scoped on a pv.$ object.
*/
pv.$ = {i: 0, x: document.getElementsByTagName("script")};
for (; pv.$.i < pv.$.x.length; pv.$.i++) {
pv.$.s = pv.$.x[pv.$.i];
if (pv.$.s.type == "text/javascript+protovis") {
try {
window.eval(pv.parse(pv.$.s.text));
} catch (e) {
pv.error(e);
}
}
}
delete pv.$;
});
/**
* Abstract; see an implementing class.
*
* @class Represents an abstract text formatter and parser. A <i>format</i> is a
* function that converts an object of a given type, such as a <tt>Date</tt>, to
* a human-readable string representation. The format may also have a
* {@link #parse} method for converting a string representation back to the
* given object type.
*
* <p>Because formats are themselves functions, they can be used directly as
* mark properties. For example, if the data associated with a label are dates,
* a date format can be used as label text:
*
* <pre> .text(pv.Format.date("%m/%d/%y"))</pre>
*
* And as with scales, if the format is used in multiple places, it can be
* convenient to declare it as a global variable and then reference it from the
* appropriate property functions. For example, if the data has a <tt>date</tt>
* attribute, and <tt>format</tt> references a given date format:
*
* <pre> .text(function(d) format(d.date))</pre>
*
* Similarly, to parse a string into a date:
*
* <pre>var date = format.parse("4/30/2010");</pre>
*
* Not all format implementations support parsing. See the implementing class
* for details.
*
* @see pv.Format.date
* @see pv.Format.number
* @see pv.Format.time
*/
pv.Format = {};
/**
* Formats the specified object, returning the string representation.
*
* @function
* @name pv.Format.prototype.format
* @param {object} x the object to format.
* @returns {string} the formatted string.
*/
/**
* Parses the specified string, returning the object representation.
*
* @function
* @name pv.Format.prototype.parse
* @param {string} x the string to parse.
* @returns {object} the parsed object.
*/
/**
* @private Given a string that may be used as part of a regular expression,
* this methods returns an appropriately quoted version of the specified string,
* with any special characters escaped.
*
* @param {string} s a string to quote.
* @returns {string} the quoted string.
*/
pv.Format.re = function (s) {
return s.replace(/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g, "\\$&");
};
/**
* @private Optionally pads the specified string <i>s</i> so that it is at least
* <i>n</i> characters long, using the padding character <i>c</i>.
*
* @param {string} c the padding character.
* @param {number} n the minimum string length.
* @param {string} s the string to pad.
* @returns {string} the padded string.
*/
pv.Format.pad = function (c, n, s) {
var m = n - String(s).length;
return (m < 1) ? s : new Array(m + 1).join(c) + s;
};
/**
* Constructs a new date format with the specified string pattern.
*
* @class The format string is in the same format expected by the
* <tt>strftime</tt> function in C. The following conversion specifications are
* supported:<ul>
*
* <li>%a - abbreviated weekday name.</li>
* <li>%A - full weekday name.</li>
* <li>%b - abbreviated month names.</li>
* <li>%B - full month names.</li>
* <li>%c - locale's appropriate date and time.</li>
* <li>%C - century number.</li>
* <li>%d - day of month [01,31] (zero padded).</li>
* <li>%D - same as %m/%d/%y.</li>
* <li>%e - day of month [ 1,31] (space padded).</li>
* <li>%h - same as %b.</li>
* <li>%H - hour (24-hour clock) [00,23] (zero padded).</li>
* <li>%I - hour (12-hour clock) [01,12] (zero padded).</li>
* <li>%m - month number [01,12] (zero padded).</li>
* <li>%M - minute [0,59] (zero padded).</li>
* <li>%n - newline character.</li>
* <li>%p - locale's equivalent of a.m. or p.m.</li>
* <li>%r - same as %I:%M:%S %p.</li>
* <li>%R - same as %H:%M.</li>
* <li>%S - second [00,61] (zero padded).</li>
* <li>%t - tab character.</li>
* <li>%T - same as %H:%M:%S.</li>
* <li>%x - same as %m/%d/%y.</li>
* <li>%X - same as %I:%M:%S %p.</li>
* <li>%y - year with century [00,99] (zero padded).</li>
* <li>%Y - year including century.</li>
* <li>%% - %.</li>
*
* </ul>The following conversion specifications are currently <i>unsupported</i>
* for formatting:<ul>
*
* <li>%j - day number [1,366].</li>
* <li>%u - weekday number [1,7].</li>
* <li>%U - week number [00,53].</li>
* <li>%V - week number [01,53].</li>
* <li>%w - weekday number [0,6].</li>
* <li>%W - week number [00,53].</li>
* <li>%Z - timezone name or abbreviation.</li>
*
* </ul>In addition, the following conversion specifications are currently
* <i>unsupported</i> for parsing:<ul>
*
* <li>%a - day of week, either abbreviated or full name.</li>
* <li>%A - same as %a.</li>
* <li>%c - locale's appropriate date and time.</li>
* <li>%C - century number.</li>
* <li>%D - same as %m/%d/%y.</li>
* <li>%I - hour (12-hour clock) [1,12].</li>
* <li>%n - any white space.</li>
* <li>%p - locale's equivalent of a.m. or p.m.</li>
* <li>%r - same as %I:%M:%S %p.</li>
* <li>%R - same as %H:%M.</li>
* <li>%t - same as %n.</li>
* <li>%T - same as %H:%M:%S.</li>
* <li>%x - locale's equivalent to %m/%d/%y.</li>
* <li>%X - locale's equivalent to %I:%M:%S %p.</li>
*
* </ul>
*
* @see <a
* href="http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html">strftime</a>
* documentation.
* @see <a
* href="http://www.opengroup.org/onlinepubs/007908799/xsh/strptime.html">strptime</a>
* documentation.
* @extends pv.Format
* @param {string} pattern the format pattern.
*/
pv.Format.date = function (pattern) {
var pad = pv.Format.pad;
/** @private */
function format(d) {
return pattern.replace(/%[a-zA-Z0-9]/g, function (s) {
switch (s) {
case '%a':
return [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
][d.getDay()];
case '%A':
return [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday"
][d.getDay()];
case '%h':
case '%b':
return [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"
][d.getMonth()];
case '%B':
return [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
][d.getMonth()];
case '%c':
return d.toLocaleString();
case '%C':
return pad("0", 2, Math.floor(d.getFullYear() / 100) % 100);
case '%d':
return pad("0", 2, d.getDate());
case '%x':
case '%D':
return pad("0", 2, d.getMonth() + 1)
+ "/" + pad("0", 2, d.getDate())
+ "/" + pad("0", 2, d.getFullYear() % 100);
case '%e':
return pad(" ", 2, d.getDate());
case '%H':
return pad("0", 2, d.getHours());
case '%I':
{
var h = d.getHours() % 12;
return h ? pad("0", 2, h) : 12;
}
// TODO %j: day of year as a decimal number [001,366]
case '%m':
return pad("0", 2, d.getMonth() + 1);
case '%M':
return pad("0", 2, d.getMinutes());
case '%n':
return "\n";
case '%p':
return d.getHours() < 12 ? "AM" : "PM";
case '%T':
case '%X':
case '%r':
{
var h = d.getHours() % 12;
return (h ? pad("0", 2, h) : 12)
+ ":" + pad("0", 2, d.getMinutes())
+ ":" + pad("0", 2, d.getSeconds())
+ " " + (d.getHours() < 12 ? "AM" : "PM");
}
case '%R':
return pad("0", 2, d.getHours()) + ":" + pad("0", 2, d.getMinutes());
case '%S':
return pad("0", 2, d.getSeconds());
case '%Q':
return pad("0", 3, d.getMilliseconds());
case '%t':
return "\t";
case '%u':
{
var w = d.getDay();
return w ? w : 1;
}
// TODO %U: week number (sunday first day) [00,53]
// TODO %V: week number (monday first day) [01,53] ... with weirdness
case '%w':
return d.getDay();
// TODO %W: week number (monday first day) [00,53] ... with weirdness
case '%y':
return pad("0", 2, d.getFullYear() % 100);
case '%Y':
return d.getFullYear();
// TODO %Z: timezone name or abbreviation
case '%%':
return "%";
}
return s;
});
}
/**
* Converts a date to a string using the associated formatting pattern.
*
* @function
* @name pv.Format.date.prototype.format
* @param {Date} date a date to format.
* @returns {string} the formatted date as a string.
*/
format.format = format;
/**
* Parses a date from a string using the associated formatting pattern.
*
* @function
* @name pv.Format.date.prototype.parse
* @param {string} s the string to parse as a date.
* @returns {Date} the parsed date.
*/
format.parse = function (s) {
var year = 1970, month = 0, date = 1, hour = 0, minute = 0, second = 0;
var fields = [function () {
}];
/* Register callbacks for each field in the format pattern. */
var re = pv.Format.re(pattern).replace(/%[a-zA-Z0-9]/g, function (s) {
switch (s) {
// TODO %a: day of week, either abbreviated or full name
// TODO %A: same as %a
case '%b':
{
fields.push(function (x) {
month = {
Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7,
Sep: 8, Oct: 9, Nov: 10, Dec: 11
}[x];
});
return "([A-Za-z]+)";
}
case '%h':
case '%B':
{
fields.push(function (x) {
month = {
January: 0, February: 1, March: 2, April: 3, May: 4, June: 5,
July: 6, August: 7, September: 8, October: 9, November: 10,
December: 11
}[x];
});
return "([A-Za-z]+)";
}
// TODO %c: locale's appropriate date and time
// TODO %C: century number[0,99]
case '%e':
case '%d':
{
fields.push(function (x) {
date = x;
});
return "([0-9]+)";
}
// TODO %D: same as %m/%d/%y
case '%I':
case '%H':
{
fields.push(function (x) {
hour = x;
});
return "([0-9]+)";
}
// TODO %j: day number [1,366]
case '%m':
{
fields.push(function (x) {
month = x - 1;
});
return "([0-9]+)";
}
case '%M':
{
fields.push(function (x) {
minute = x;
});
return "([0-9]+)";
}
// TODO %n: any white space
// TODO %p: locale's equivalent of a.m. or p.m.
case '%p':
{ // TODO this is a hack
fields.push(function (x) {
if (hour == 12) {
if (x == "am")
hour = 0;
} else if (x == "pm") {
hour = Number(hour) + 12;
}
});
return "(am|pm)";
}
// TODO %r: %I:%M:%S %p
// TODO %R: %H:%M
case '%S':
{
fields.push(function (x) {
second = x;
});
return "([0-9]+)";
}
// TODO %t: any white space
// TODO %T: %H:%M:%S
// TODO %U: week number [00,53]
// TODO %w: weekday [0,6]
// TODO %W: week number [00, 53]
// TODO %x: locale date (%m/%d/%y)
// TODO %X: locale time (%I:%M:%S %p)
case '%y':
{
fields.push(function (x) {
x = Number(x);
year = x + (((0 <= x) && (x < 69)) ? 2000
: (((x >= 69) && (x < 100) ? 1900 : 0)));
});
return "([0-9]+)";
}
case '%Y':
{
fields.push(function (x) {
year = x;
});
return "([0-9]+)";
}
case '%%':
{
fields.push(function () {
});
return "%";
}
}
return s;
});
var match = s.match(re);
if (match)
match.forEach(function (m, i) {
fields[i](m);
});
return new Date(year, month, date, hour, minute, second);
};
return format;
};
/**
* Returns a time format of the given type, either "short" or "long".
*
* @class Represents a time format, converting between a <tt>number</tt>
* representing a duration in milliseconds, and a <tt>string</tt>. Two types of
* time formats are supported: "short" and "long". The <i>short</i> format type
* returns a string such as "3.3 days" or "12.1 minutes", while the <i>long</i>
* format returns "13:04:12" or similar.
*
* @extends pv.Format
* @param {string} type the type; "short" or "long".
*/
pv.Format.time = function (type) {
var pad = pv.Format.pad;
/*
* MILLISECONDS = 1
* SECONDS = 1e3
* MINUTES = 6e4
* HOURS = 36e5
* DAYS = 864e5
* WEEKS = 6048e5
* MONTHS = 2592e6
* YEARS = 31536e6
*/
/** @private */
function format(t) {
t = Number(t); // force conversion from Date
switch (type) {
case "short":
{
if (t >= 31536e6) {
return (t / 31536e6).toFixed(1) + " years";
} else if (t >= 6048e5) {
return (t / 6048e5).toFixed(1) + " weeks";
} else if (t >= 864e5) {
return (t / 864e5).toFixed(1) + " days";
} else if (t >= 36e5) {
return (t / 36e5).toFixed(1) + " hours";
} else if (t >= 6e4) {
return (t / 6e4).toFixed(1) + " minutes";
}
return (t / 1e3).toFixed(1) + " seconds";
}
case "long":
{
var a = [],
s = ((t % 6e4) / 1e3) >> 0,
m = ((t % 36e5) / 6e4) >> 0;
a.push(pad("0", 2, s));
if (t >= 36e5) {
var h = ((t % 864e5) / 36e5) >> 0;
a.push(pad("0", 2, m));
if (t >= 864e5) {
a.push(pad("0", 2, h));
a.push(Math.floor(t / 864e5).toFixed());
} else {
a.push(h.toFixed());
}
} else {
a.push(m.toFixed());
}
return a.reverse().join(":");
}
}
}
/**
* Formats the specified time, returning the string representation.
*
* @function
* @name pv.Format.time.prototype.format
* @param {number} t the duration in milliseconds. May also be a <tt>Date</tt>.
* @returns {string} the formatted string.
*/
format.format = format;
/**
* Parses the specified string, returning the time in milliseconds.
*
* @function
* @name pv.Format.time.prototype.parse
* @param {string} s a formatted string.
* @returns {number} the parsed duration in milliseconds.
*/
format.parse = function (s) {
switch (type) {
case "short":
{
var re = /([0-9,.]+)\s*([a-z]+)/g, a, t = 0;
while (a = re.exec(s)) {
var f = parseFloat(a[0].replace(",", "")), u = 0;
switch (a[2].toLowerCase()) {
case "year":
case "years":
u = 31536e6;
break;
case "week":
case "weeks":
u = 6048e5;
break;
case "day":
case "days":
u = 864e5;
break;
case "hour":
case "hours":
u = 36e5;
break;
case "minute":
case "minutes":
u = 6e4;
break;
case "second":
case "seconds":
u = 1e3;
break;
}
t += f * u;
}
return t;
}
case "long":
{
var a = s.replace(",", "").split(":").reverse(), t = 0;
if (a.length)
t += parseFloat(a[0]) * 1e3;
if (a.length > 1)
t += parseFloat(a[1]) * 6e4;
if (a.length > 2)
t += parseFloat(a[2]) * 36e5;
if (a.length > 3)
t += parseFloat(a[3]) * 864e5;
return t;
}
}
}
return format;
};
/**
* Returns a default number format.
*
* @class Represents a number format, converting between a <tt>number</tt> and a
* <tt>string</tt>. This class allows numbers to be formatted with variable
* precision (both for the integral and fractional part of the number), optional
* thousands grouping, and optional padding. The thousands (",") and decimal
* (".") separator can be customized.
*
* @returns {pv.Format.number} a number format.
*/
pv.Format.number = function () {
var mini = 0, // default minimum integer digits
maxi = Infinity, // default maximum integer digits
mins = 0, // mini, including group separators
minf = 0, // default minimum fraction digits
maxf = 0, // default maximum fraction digits
maxk = 1, // 10^maxf
padi = "0", // default integer pad
padf = "0", // default fraction pad
padg = true, // whether group separator affects integer padding
decimal = ".", // default decimal separator
group = ",", // default group separator
np = "\u2212", // default negative prefix
ns = ""; // default negative suffix
/** @private */
function format(x) {
/* Round the fractional part, and split on decimal separator. */
if (Infinity > maxf)
x = Math.round(x * maxk) / maxk;
var s = String(Math.abs(x)).split(".");
/* Pad, truncate and group the integral part. */
var i = s[0];
if (i.length > maxi)
i = i.substring(i.length - maxi);
if (padg && (i.length < mini))
i = new Array(mini - i.length + 1).join(padi) + i;
if (i.length > 3)
i = i.replace(/\B(?=(?:\d{3})+(?!\d))/g, group);
if (!padg && (i.length < mins))
i = new Array(mins - i.length + 1).join(padi) + i;
s[0] = x < 0 ? np + i + ns : i;
/* Pad the fractional part. */
var f = s[1] || "";
if (f.length < minf)
s[1] = f + new Array(minf - f.length + 1).join(padf);
return s.join(decimal);
}
/**
* @function
* @name pv.Format.number.prototype.format
* @param {number} x
* @returns {string}
*/
format.format = format;
/**
* Parses the specified string as a number. Before parsing, leading and
* trailing padding is removed. Group separators are also removed, and the
* decimal separator is replaced with the standard point ("."). The integer
* part is truncated per the maximum integer digits, and the fraction part is
* rounded per the maximum fraction digits.
*
* @function
* @name pv.Format.number.prototype.parse
* @param {string} x the string to parse.
* @returns {number} the parsed number.
*/
format.parse = function (x) {
var re = pv.Format.re;
/* Remove leading and trailing padding. Split on the decimal separator. */
var s = String(x)
.replace(new RegExp("^(" + re(padi) + ")*"), "")
.replace(new RegExp("(" + re(padf) + ")*$"), "")
.split(decimal);
/* Remove grouping and truncate the integral part. */
var i = s[0].replace(new RegExp(re(group), "g"), "");
if (i.length > maxi)
i = i.substring(i.length - maxi);
/* Round the fractional part. */
var f = s[1] ? Number("0." + s[1]) : 0;
if (Infinity > maxf)
f = Math.round(f * maxk) / maxk;
return Math.round(i) + f;
};
/**
* Sets or gets the minimum and maximum number of integer digits. This
* controls the number of decimal digits to display before the decimal
* separator for the integral part of the number. If the number of digits is
* smaller than the minimum, the digits are padded; if the number of digits is
* larger, the digits are truncated, showing only the lower-order digits. The
* default range is [0, Infinity].
*
* <p>If only one argument is specified to this method, this value is used as
* both the minimum and maximum number. If no arguments are specified, a
* two-element array is returned containing the minimum and the maximum.
*
* @function
* @name pv.Format.number.prototype.integerDigits
* @param {number} [min] the minimum integer digits.
* @param {number} [max] the maximum integer digits.
* @returns {pv.Format.number} <tt>this</tt>, or the current integer digits.
*/
format.integerDigits = function (min, max) {
if (arguments.length) {
mini = Number(min);
maxi = (arguments.length > 1) ? Number(max) : mini;
mins = mini + Math.floor(mini / 3) * group.length;
return this;
}
return [mini, maxi];
};
/**
* Sets or gets the minimum and maximum number of fraction digits. The
* controls the number of decimal digits to display after the decimal
* separator for the fractional part of the number. If the number of digits is
* smaller than the minimum, the digits are padded; if the number of digits is
* larger, the fractional part is rounded, showing only the higher-order
* digits. The default range is [0, 0].
*
* <p>If only one argument is specified to this method, this value is used as
* both the minimum and maximum number. If no arguments are specified, a
* two-element array is returned containing the minimum and the maximum.
*
* @function
* @name pv.Format.number.prototype.fractionDigits
* @param {number} [min] the minimum fraction digits.
* @param {number} [max] the maximum fraction digits.
* @returns {pv.Format.number} <tt>this</tt>, or the current fraction digits.
*/
format.fractionDigits = function (min, max) {
if (arguments.length) {
minf = Number(min);
maxf = (arguments.length > 1) ? Number(max) : minf;
maxk = Math.pow(10, maxf);
return this;
}
return [minf, maxf];
};
/**
* Sets or gets the character used to pad the integer part. The integer pad is
* used when the number of integer digits is smaller than the minimum. The
* default pad character is "0" (zero).
*
* @param {string} [x] the new pad character.
* @returns {pv.Format.number} <tt>this</tt> or the current pad character.
*/
format.integerPad = function (x) {
if (arguments.length) {
padi = String(x);
padg = /\d/.test(padi);
return this;
}
return padi;
};
/**
* Sets or gets the character used to pad the fration part. The fraction pad
* is used when the number of fraction digits is smaller than the minimum. The
* default pad character is "0" (zero).
*
* @param {string} [x] the new pad character.
* @returns {pv.Format.number} <tt>this</tt> or the current pad character.
*/
format.fractionPad = function (x) {
if (arguments.length) {
padf = String(x);
return this;
}
return padf;
};
/**
* Sets or gets the character used as the decimal point, separating the
* integer and fraction parts of the number. The default decimal point is ".".
*
* @param {string} [x] the new decimal separator.
* @returns {pv.Format.number} <tt>this</tt> or the current decimal separator.
*/
format.decimal = function (x) {
if (arguments.length) {
decimal = String(x);
return this;
}
return decimal;
};
/**
* Sets or gets the character used as the group separator, grouping integer
* digits by thousands. The default decimal point is ",". Grouping can be
* disabled by using "" for the separator.
*
* @param {string} [x] the new group separator.
* @returns {pv.Format.number} <tt>this</tt> or the current group separator.
*/
format.group = function (x) {
if (arguments.length) {
group = x ? String(x) : "";
mins = mini + Math.floor(mini / 3) * group.length;
return this;
}
return group;
};
/**
* Sets or gets the negative prefix and suffix. The default negative prefix is
* "−", and the default negative suffix is the empty string.
*
* @param {string} [x] the negative prefix.
* @param {string} [y] the negative suffix.
* @returns {pv.Format.number} <tt>this</tt> or the current negative format.
*/
format.negativeAffix = function (x, y) {
if (arguments.length) {
np = String(x || "");
ns = String(y || "");
return this;
}
return [np, ns];
};
return format;
};
/**
* @private A private variant of Array.prototype.map that supports the index
* property.
*/
pv.map = function (array, f) {
var o = {};
return f
? array.map(function (d, i) {
o.index = i;
return f.call(o, d);
})
: array.slice();
};
/**
* Concatenates the specified array with itself <i>n</i> times. For example,
* <tt>pv.repeat([1, 2])</tt> returns [1, 2, 1, 2].
*
* @param {array} a an array.
* @param {number} [n] the number of times to repeat; defaults to two.
* @returns {array} an array that repeats the specified array.
*/
pv.repeat = function (array, n) {
if (arguments.length == 1)
n = 2;
return pv.blend(pv.range(n).map(function () {
return array;
}));
};
/**
* Given two arrays <tt>a</tt> and <tt>b</tt>, <style
* type="text/css">sub{line-height:0}</style> returns an array of all possible
* pairs of elements [a<sub>i</sub>, b<sub>j</sub>]. The outer loop is on array
* <i>a</i>, while the inner loop is on <i>b</i>, such that the order of
* returned elements is [a<sub>0</sub>, b<sub>0</sub>], [a<sub>0</sub>,
* b<sub>1</sub>], ... [a<sub>0</sub>, b<sub>m</sub>], [a<sub>1</sub>,
* b<sub>0</sub>], [a<sub>1</sub>, b<sub>1</sub>], ... [a<sub>1</sub>,
* b<sub>m</sub>], ... [a<sub>n</sub>, b<sub>m</sub>]. If either array is empty,
* an empty array is returned.
*
* @param {array} a an array.
* @param {array} b an array.
* @returns {array} an array of pairs of elements in <tt>a</tt> and <tt>b</tt>.
*/
pv.cross = function (a, b) {
var array = [];
for (var i = 0, n = a.length, m = b.length; i < n; i++) {
for (var j = 0, x = a[i]; j < m; j++) {
array.push([x, b[j]]);
}
}
return array;
};
/**
* Given the specified array of arrays, concatenates the arrays into a single
* array. If the individual arrays are explicitly known, an alternative to blend
* is to use JavaScript's <tt>concat</tt> method directly. These two equivalent
* expressions:<ul>
*
* <li><tt>pv.blend([[1, 2, 3], ["a", "b", "c"]])</tt>
* <li><tt>[1, 2, 3].concat(["a", "b", "c"])</tt>
*
* </ul>return [1, 2, 3, "a", "b", "c"].
*
* @param {array[]} arrays an array of arrays.
* @returns {array} an array containing all the elements of each array in
* <tt>arrays</tt>.
*/
pv.blend = function (arrays) {
return Array.prototype.concat.apply([], arrays);
};
/**
* Given the specified array of arrays, <style
* type="text/css">sub{line-height:0}</style> transposes each element
* array<sub>ij</sub> with array<sub>ji</sub>. If the array has dimensions
* <i>n</i>×<i>m</i>, it will have dimensions <i>m</i>×<i>n</i>
* after this method returns. This method transposes the elements of the array
* in place, mutating the array, and returning a reference to the array.
*
* @param {array[]} arrays an array of arrays.
* @returns {array[]} the passed-in array, after transposing the elements.
*/
pv.transpose = function (arrays) {
var n = arrays.length, m = pv.max(arrays, function (d) {
return d.length;
});
if (m > n) {
arrays.length = m;
for (var i = n; i < m; i++) {
arrays[i] = new Array(n);
}
for (var i = 0; i < n; i++) {
for (var j = i + 1; j < m; j++) {
var t = arrays[i][j];
arrays[i][j] = arrays[j][i];
arrays[j][i] = t;
}
}
} else {
for (var i = 0; i < m; i++) {
arrays[i].length = n;
}
for (var i = 0; i < n; i++) {
for (var j = 0; j < i; j++) {
var t = arrays[i][j];
arrays[i][j] = arrays[j][i];
arrays[j][i] = t;
}
}
}
arrays.length = m;
for (var i = 0; i < m; i++) {
arrays[i].length = n;
}
return arrays;
};
/**
* Returns a normalized copy of the specified array, such that the sum of the
* returned elements sum to one. If the specified array is not an array of
* numbers, an optional accessor function <tt>f</tt> can be specified to map the
* elements to numbers. For example, if <tt>array</tt> is an array of objects,
* and each object has a numeric property "foo", the expression
*
* <pre>pv.normalize(array, function(d) d.foo)</pre>
*
* returns a normalized array on the "foo" property. If an accessor function is
* not specified, the identity function is used. Accessor functions can refer to
* <tt>this.index</tt>.
*
* @param {array} array an array of objects, or numbers.
* @param {function} [f] an optional accessor function.
* @returns {number[]} an array of numbers that sums to one.
*/
pv.normalize = function (array, f) {
var norm = pv.map(array, f), sum = pv.sum(norm);
for (var i = 0; i < norm.length; i++)
norm[i] /= sum;
return norm;
};
/**
* Returns a permutation of the specified array, using the specified array of
* indexes. The returned array contains the corresponding element in
* <tt>array</tt> for each index in <tt>indexes</tt>, in order. For example,
*
* <pre>pv.permute(["a", "b", "c"], [1, 2, 0])</pre>
*
* returns <tt>["b", "c", "a"]</tt>. It is acceptable for the array of indexes
* to be a different length from the array of elements, and for indexes to be
* duplicated or omitted. The optional accessor function <tt>f</tt> can be used
* to perform a simultaneous mapping of the array elements. Accessor functions
* can refer to <tt>this.index</tt>.
*
* @param {array} array an array.
* @param {number[]} indexes an array of indexes into <tt>array</tt>.
* @param {function} [f] an optional accessor function.
* @returns {array} an array of elements from <tt>array</tt>; a permutation.
*/
pv.permute = function (array, indexes, f) {
if (!f)
f = pv.identity;
var p = new Array(indexes.length), o = {};
indexes.forEach(function (j, i) {
o.index = j;
p[i] = f.call(o, array[j]);
});
return p;
};
/**
* Returns a map from key to index for the specified <tt>keys</tt> array. For
* example,
*
* <pre>pv.numerate(["a", "b", "c"])</pre>
*
* returns <tt>{a: 0, b: 1, c: 2}</tt>. Note that since JavaScript maps only
* support string keys, <tt>keys</tt> must contain strings, or other values that
* naturally map to distinct string values. Alternatively, an optional accessor
* function <tt>f</tt> can be specified to compute the string key for the given
* element. Accessor functions can refer to <tt>this.index</tt>.
*
* @param {array} keys an array, usually of string keys.
* @param {function} [f] an optional key function.
* @returns a map from key to index.
*/
pv.numerate = function (keys, f) {
if (!f)
f = pv.identity;
var map = {}, o = {};
keys.forEach(function (x, i) {
o.index = i;
map[f.call(o, x)] = i;
});
return map;
};
/**
* Returns the unique elements in the specified array, in the order they appear.
* Note that since JavaScript maps only support string keys, <tt>array</tt> must
* contain strings, or other values that naturally map to distinct string
* values. Alternatively, an optional accessor function <tt>f</tt> can be
* specified to compute the string key for the given element. Accessor functions
* can refer to <tt>this.index</tt>.
*
* @param {array} array an array, usually of string keys.
* @param {function} [f] an optional key function.
* @returns {array} the unique values.
*/
pv.uniq = function (array, f) {
if (!f)
f = pv.identity;
var map = {}, keys = [], o = {}, y;
array.forEach(function (x, i) {
o.index = i;
y = f.call(o, x);
if (!(y in map))
map[y] = keys.push(y);
});
return keys;
};
/**
* The comparator function for natural order. This can be used in conjunction with
* the built-in array <tt>sort</tt> method to sort elements by their natural
* order, ascending. Note that if no comparator function is specified to the
* built-in <tt>sort</tt> method, the default order is lexicographic, <i>not</i>
* natural!
*
* @see <a
* href="http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/sort">Array.sort</a>.
* @param a an element to compare.
* @param b an element to compare.
* @returns {number} negative if a < b; positive if a > b; otherwise 0.
*/
pv.naturalOrder = function (a, b) {
return (a < b) ? -1 : ((a > b) ? 1 : 0);
};
/**
* The comparator function for reverse natural order. This can be used in
* conjunction with the built-in array <tt>sort</tt> method to sort elements by
* their natural order, descending. Note that if no comparator function is
* specified to the built-in <tt>sort</tt> method, the default order is
* lexicographic, <i>not</i> natural!
*
* @see #naturalOrder
* @param a an element to compare.
* @param b an element to compare.
* @returns {number} negative if a < b; positive if a > b; otherwise 0.
*/
pv.reverseOrder = function (b, a) {
return (a < b) ? -1 : ((a > b) ? 1 : 0);
};
/**
* Searches the specified array of numbers for the specified value using the
* binary search algorithm. The array must be sorted (as by the <tt>sort</tt>
* method) prior to making this call. If it is not sorted, the results are
* undefined. If the array contains multiple elements with the specified value,
* there is no guarantee which one will be found.
*
* <p>The <i>insertion point</i> is defined as the point at which the value
* would be inserted into the array: the index of the first element greater than
* the value, or <tt>array.length</tt>, if all elements in the array are less
* than the specified value. Note that this guarantees that the return value
* will be nonnegative if and only if the value is found.
*
* @param {number[]} array the array to be searched.
* @param {number} value the value to be searched for.
* @returns the index of the search value, if it is contained in the array;
* otherwise, (-(<i>insertion point</i>) - 1).
* @param {function} [f] an optional key function.
*/
pv.search = function (array, value, f) {
if (!f)
f = pv.identity;
var low = 0, high = array.length - 1;
while (low <= high) {
var mid = (low + high) >> 1, midValue = f(array[mid]);
if (midValue < value)
low = mid + 1;
else if (midValue > value)
high = mid - 1;
else
return mid;
}
return -low - 1;
};
pv.search.index = function (array, value, f) {
var i = pv.search(array, value, f);
return (i < 0) ? (-i - 1) : i;
};
/**
* Returns an array of numbers, starting at <tt>start</tt>, incrementing by
* <tt>step</tt>, until <tt>stop</tt> is reached. The stop value is
* exclusive. If only a single argument is specified, this value is interpeted
* as the <i>stop</i> value, with the <i>start</i> value as zero. If only two
* arguments are specified, the step value is implied to be one.
*
* <p>The method is modeled after the built-in <tt>range</tt> method from
* Python. See the Python documentation for more details.
*
* @see <a href="http://docs.python.org/library/functions.html#range">Python range</a>
* @param {number} [start] the start value.
* @param {number} stop the stop value.
* @param {number} [step] the step value.
* @returns {number[]} an array of numbers.
*/
pv.range = function (start, stop, step) {
if (arguments.length == 1) {
stop = start;
start = 0;
}
if (step == undefined)
step = 1;
if ((stop - start) / step == Infinity)
throw new Error("range must be finite");
var array = [], i = 0, j;
stop -= (stop - start) * 1e-10; // floating point precision!
if (step < 0) {
while ((j = start + step * i++) > stop) {
array.push(j);
}
} else {
while ((j = start + step * i++) < stop) {
array.push(j);
}
}
return array;
};
/**
* Returns a random number in the range [<tt>start</tt>, <tt>stop</tt>) that is
* a multiple of <tt>step</tt>. More specifically, the returned number is of the
* form <tt>start</tt> + <i>n</i> * <tt>step</tt>, where <i>n</i> is a
* nonnegative integer. If <tt>step</tt> is not specified, it defaults to 1,
* returning a random integer if <tt>start</tt> is also an integer.
*
* @param {number} [start] the start value value.
* @param {number} stop the stop value.
* @param {number} [step] the step value.
* @returns {number} a random number between <i>start</i> and <i>stop</i>.
*/
pv.random = function (start, stop, step) {
if (arguments.length == 1) {
stop = start;
start = 0;
}
if (step == undefined)
step = 1;
return step
? (Math.floor(Math.random() * (stop - start) / step) * step + start)
: (Math.random() * (stop - start) + start);
};
/**
* Returns the sum of the specified array. If the specified array is not an
* array of numbers, an optional accessor function <tt>f</tt> can be specified
* to map the elements to numbers. See {@link #normalize} for an example.
* Accessor functions can refer to <tt>this.index</tt>.
*
* @param {array} array an array of objects, or numbers.
* @param {function} [f] an optional accessor function.
* @returns {number} the sum of the specified array.
*/
pv.sum = function (array, f) {
var o = {};
return array.reduce(f
? function (p, d, i) {
o.index = i;
return p + f.call(o, d);
}
: function (p, d) {
return p + d;
}, 0);
};
/**
* Returns the maximum value of the specified array. If the specified array is
* not an array of numbers, an optional accessor function <tt>f</tt> can be
* specified to map the elements to numbers. See {@link #normalize} for an
* example. Accessor functions can refer to <tt>this.index</tt>.
*
* @param {array} array an array of objects, or numbers.
* @param {function} [f] an optional accessor function.
* @returns {number} the maximum value of the specified array.
*/
pv.max = function (array, f) {
if (f == pv.index)
return array.length - 1;
return Math.max.apply(null, f ? pv.map(array, f) : array);
};
/**
* Returns the index of the maximum value of the specified array. If the
* specified array is not an array of numbers, an optional accessor function
* <tt>f</tt> can be specified to map the elements to numbers. See
* {@link #normalize} for an example. Accessor functions can refer to
* <tt>this.index</tt>.
*
* @param {array} array an array of objects, or numbers.
* @param {function} [f] an optional accessor function.
* @returns {number} the index of the maximum value of the specified array.
*/
pv.max.index = function (array, f) {
if (!array.length)
return -1;
if (f == pv.index)
return array.length - 1;
if (!f)
f = pv.identity;
var maxi = 0, maxx = -Infinity, o = {};
for (var i = 0; i < array.length; i++) {
o.index = i;
var x = f.call(o, array[i]);
if (x > maxx) {
maxx = x;
maxi = i;
}
}
return maxi;
}
/**
* Returns the minimum value of the specified array of numbers. If the specified
* array is not an array of numbers, an optional accessor function <tt>f</tt>
* can be specified to map the elements to numbers. See {@link #normalize} for
* an example. Accessor functions can refer to <tt>this.index</tt>.
*
* @param {array} array an array of objects, or numbers.
* @param {function} [f] an optional accessor function.
* @returns {number} the minimum value of the specified array.
*/
pv.min = function (array, f) {
if (f == pv.index)
return 0;
return Math.min.apply(null, f ? pv.map(array, f) : array);
};
/**
* Returns the index of the minimum value of the specified array. If the
* specified array is not an array of numbers, an optional accessor function
* <tt>f</tt> can be specified to map the elements to numbers. See
* {@link #normalize} for an example. Accessor functions can refer to
* <tt>this.index</tt>.
*
* @param {array} array an array of objects, or numbers.
* @param {function} [f] an optional accessor function.
* @returns {number} the index of the minimum value of the specified array.
*/
pv.min.index = function (array, f) {
if (!array.length)
return -1;
if (f == pv.index)
return 0;
if (!f)
f = pv.identity;
var mini = 0, minx = Infinity, o = {};
for (var i = 0; i < array.length; i++) {
o.index = i;
var x = f.call(o, array[i]);
if (x < minx) {
minx = x;
mini = i;
}
}
return mini;
}
/**
* Returns the arithmetic mean, or average, of the specified array. If the
* specified array is not an array of numbers, an optional accessor function
* <tt>f</tt> can be specified to map the elements to numbers. See
* {@link #normalize} for an example. Accessor functions can refer to
* <tt>this.index</tt>.
*
* @param {array} array an array of objects, or numbers.
* @param {function} [f] an optional accessor function.
* @returns {number} the mean of the specified array.
*/
pv.mean = function (array, f) {
return pv.sum(array, f) / array.length;
};
/**
* Returns the median of the specified array. If the specified array is not an
* array of numbers, an optional accessor function <tt>f</tt> can be specified
* to map the elements to numbers. See {@link #normalize} for an example.
* Accessor functions can refer to <tt>this.index</tt>.
*
* @param {array} array an array of objects, or numbers.
* @param {function} [f] an optional accessor function.
* @returns {number} the median of the specified array.
*/
pv.median = function (array, f) {
if (f == pv.index)
return (array.length - 1) / 2;
array = pv.map(array, f).sort(pv.naturalOrder);
if (array.length % 2)
return array[Math.floor(array.length / 2)];
var i = array.length / 2;
return (array[i - 1] + array[i]) / 2;
};
/**
* Returns the unweighted variance of the specified array. If the specified
* array is not an array of numbers, an optional accessor function <tt>f</tt>
* can be specified to map the elements to numbers. See {@link #normalize} for
* an example. Accessor functions can refer to <tt>this.index</tt>.
*
* @param {array} array an array of objects, or numbers.
* @param {function} [f] an optional accessor function.
* @returns {number} the variance of the specified array.
*/
pv.variance = function (array, f) {
if (array.length < 1)
return NaN;
if (array.length == 1)
return 0;
var mean = pv.mean(array, f), sum = 0, o = {};
if (!f)
f = pv.identity;
for (var i = 0; i < array.length; i++) {
o.index = i;
var d = f.call(o, array[i]) - mean;
sum += d * d;
}
return sum;
};
/**
* Returns an unbiased estimation of the standard deviation of a population,
* given the specified random sample. If the specified array is not an array of
* numbers, an optional accessor function <tt>f</tt> can be specified to map the
* elements to numbers. See {@link #normalize} for an example. Accessor
* functions can refer to <tt>this.index</tt>.
*
* @param {array} array an array of objects, or numbers.
* @param {function} [f] an optional accessor function.
* @returns {number} the standard deviation of the specified array.
*/
pv.deviation = function (array, f) {
return Math.sqrt(pv.variance(array, f) / (array.length - 1));
};
/**
* Returns the logarithm with a given base value.
*
* @param {number} x the number for which to compute the logarithm.
* @param {number} b the base of the logarithm.
* @returns {number} the logarithm value.
*/
pv.log = function (x, b) {
return Math.log(x) / Math.log(b);
};
/**
* Computes a zero-symmetric logarithm. Computes the logarithm of the absolute
* value of the input, and determines the sign of the output according to the
* sign of the input value.
*
* @param {number} x the number for which to compute the logarithm.
* @param {number} b the base of the logarithm.
* @returns {number} the symmetric log value.
*/
pv.logSymmetric = function (x, b) {
return (x == 0) ? 0 : ((x < 0) ? -pv.log(-x, b) : pv.log(x, b));
};
/**
* Computes a zero-symmetric logarithm, with adjustment to values between zero
* and the logarithm base. This adjustment introduces distortion for values less
* than the base number, but enables simultaneous plotting of log-transformed
* data involving both positive and negative numbers.
*
* @param {number} x the number for which to compute the logarithm.
* @param {number} b the base of the logarithm.
* @returns {number} the adjusted, symmetric log value.
*/
pv.logAdjusted = function (x, b) {
if (!isFinite(x))
return x;
var negative = x < 0;
if (x < b)
x += (b - x) / b;
return negative ? -pv.log(x, b) : pv.log(x, b);
};
/**
* Rounds an input value down according to its logarithm. The method takes the
* floor of the logarithm of the value and then uses the resulting value as an
* exponent for the base value.
*
* @param {number} x the number for which to compute the logarithm floor.
* @param {number} b the base of the logarithm.
* @returns {number} the rounded-by-logarithm value.
*/
pv.logFloor = function (x, b) {
return (x > 0)
? Math.pow(b, Math.floor(pv.log(x, b)))
: -Math.pow(b, -Math.floor(-pv.log(-x, b)));
};
/**
* Rounds an input value up according to its logarithm. The method takes the
* ceiling of the logarithm of the value and then uses the resulting value as an
* exponent for the base value.
*
* @param {number} x the number for which to compute the logarithm ceiling.
* @param {number} b the base of the logarithm.
* @returns {number} the rounded-by-logarithm value.
*/
pv.logCeil = function (x, b) {
return (x > 0)
? Math.pow(b, Math.ceil(pv.log(x, b)))
: -Math.pow(b, -Math.ceil(-pv.log(-x, b)));
};
(function () {
var radians = Math.PI / 180,
degrees = 180 / Math.PI;
/** Returns the number of radians corresponding to the specified degrees. */
pv.radians = function (degrees) {
return radians * degrees;
};
/** Returns the number of degrees corresponding to the specified radians. */
pv.degrees = function (radians) {
return degrees * radians;
};
})();
/**
* Returns all of the property names (keys) of the specified object (a map). The
* order of the returned array is not defined.
*
* @param map an object.
* @returns {string[]} an array of strings corresponding to the keys.
* @see #entries
*/
pv.keys = function (map) {
var array = [];
for (var key in map) {
array.push(key);
}
return array;
};
/**
* Returns all of the entries (key-value pairs) of the specified object (a
* map). The order of the returned array is not defined. Each key-value pair is
* represented as an object with <tt>key</tt> and <tt>value</tt> attributes,
* e.g., <tt>{key: "foo", value: 42}</tt>.
*
* @param map an object.
* @returns {array} an array of key-value pairs corresponding to the keys.
*/
pv.entries = function (map) {
var array = [];
for (var key in map) {
array.push({key: key, value: map[key]});
}
return array;
};
/**
* Returns all of the values (attribute values) of the specified object (a
* map). The order of the returned array is not defined.
*
* @param map an object.
* @returns {array} an array of objects corresponding to the values.
* @see #entries
*/
pv.values = function (map) {
var array = [];
for (var key in map) {
array.push(map[key]);
}
return array;
};
/**
* Returns a map constructed from the specified <tt>keys</tt>, using the
* function <tt>f</tt> to compute the value for each key. The single argument to
* the value function is the key. The callback is invoked only for indexes of
* the array which have assigned values; it is not invoked for indexes which
* have been deleted or which have never been assigned values.
*
* <p>For example, this expression creates a map from strings to string length:
*
* <pre>pv.dict(["one", "three", "seventeen"], function(s) s.length)</pre>
*
* The returned value is <tt>{one: 3, three: 5, seventeen: 9}</tt>. Accessor
* functions can refer to <tt>this.index</tt>.
*
* @param {array} keys an array.
* @param {function} f a value function.
* @returns a map from keys to values.
*/
pv.dict = function (keys, f) {
var m = {}, o = {};
for (var i = 0; i < keys.length; i++) {
if (i in keys) {
var k = keys[i];
o.index = i;
m[k] = f.call(o, k);
}
}
return m;
};
/**
* Returns a {@link pv.Dom} operator for the given map. This is a convenience
* factory method, equivalent to <tt>new pv.Dom(map)</tt>. To apply the operator
* and retrieve the root node, call {@link pv.Dom#root}; to retrieve all nodes
* flattened, use {@link pv.Dom#nodes}.
*
* @see pv.Dom
* @param map a map from which to construct a DOM.
* @returns {pv.Dom} a DOM operator for the specified map.
*/
pv.dom = function (map) {
return new pv.Dom(map);
};
/**
* Constructs a DOM operator for the specified map. This constructor should not
* be invoked directly; use {@link pv.dom} instead.
*
* @class Represets a DOM operator for the specified map. This allows easy
* transformation of a hierarchical JavaScript object (such as a JSON map) to a
* W3C Document Object Model hierarchy. For more information on which attributes
* and methods from the specification are supported, see {@link pv.Dom.Node}.
*
* <p>Leaves in the map are determined using an associated <i>leaf</i> function;
* see {@link #leaf}. By default, leaves are any value whose type is not
* "object", such as numbers or strings.
*
* @param map a map from which to construct a DOM.
*/
pv.Dom = function (map) {
this.$map = map;
};
/** @private The default leaf function. */
pv.Dom.prototype.$leaf = function (n) {
return typeof n != "object";
};
/**
* Sets or gets the leaf function for this DOM operator. The leaf function
* identifies which values in the map are leaves, and which are internal nodes.
* By default, objects are considered internal nodes, and primitives (such as
* numbers and strings) are considered leaves.
*
* @param {function} f the new leaf function.
* @returns the current leaf function, or <tt>this</tt>.
*/
pv.Dom.prototype.leaf = function (f) {
if (arguments.length) {
this.$leaf = f;
return this;
}
return this.$leaf;
};
/**
* Applies the DOM operator, returning the root node.
*
* @returns {pv.Dom.Node} the root node.
* @param {string} [nodeName] optional node name for the root.
*/
pv.Dom.prototype.root = function (nodeName) {
var leaf = this.$leaf, root = recurse(this.$map);
/** @private */
function recurse(map) {
var n = new pv.Dom.Node();
for (var k in map) {
var v = map[k];
n.appendChild(leaf(v) ? new pv.Dom.Node(v) : recurse(v)).nodeName = k;
}
return n;
}
root.nodeName = nodeName;
return root;
};
/**
* Applies the DOM operator, returning the array of all nodes in preorder
* traversal.
*
* @returns {array} the array of nodes in preorder traversal.
*/
pv.Dom.prototype.nodes = function () {
return this.root().nodes();
};
/**
* Constructs a DOM node for the specified value. Instances of this class are
* not typically created directly; instead they are generated from a JavaScript
* map using the {@link pv.Dom} operator.
*
* @class Represents a <tt>Node</tt> in the W3C Document Object Model.
*/
pv.Dom.Node = function (value) {
this.nodeValue = value;
this.childNodes = [];
};
/**
* The node name. When generated from a map, the node name corresponds to the
* key at the given level in the map. Note that the root node has no associated
* key, and thus has an undefined node name (and no <tt>parentNode</tt>).
*
* @type string
* @field pv.Dom.Node.prototype.nodeName
*/
/**
* The node value. When generated from a map, node value corresponds to the leaf
* value for leaf nodes, and is undefined for internal nodes.
*
* @field pv.Dom.Node.prototype.nodeValue
*/
/**
* The array of child nodes. This array is empty for leaf nodes. An easy way to
* check if child nodes exist is to query <tt>firstChild</tt>.
*
* @type array
* @field pv.Dom.Node.prototype.childNodes
*/
/**
* The parent node, which is null for root nodes.
*
* @type pv.Dom.Node
*/
pv.Dom.Node.prototype.parentNode = null;
/**
* The first child, which is null for leaf nodes.
*
* @type pv.Dom.Node
*/
pv.Dom.Node.prototype.firstChild = null;
/**
* The last child, which is null for leaf nodes.
*
* @type pv.Dom.Node
*/
pv.Dom.Node.prototype.lastChild = null;
/**
* The previous sibling node, which is null for the first child.
*
* @type pv.Dom.Node
*/
pv.Dom.Node.prototype.previousSibling = null;
/**
* The next sibling node, which is null for the last child.
*
* @type pv.Dom.Node
*/
pv.Dom.Node.prototype.nextSibling = null;
/**
* Removes the specified child node from this node.
*
* @throws Error if the specified child is not a child of this node.
* @returns {pv.Dom.Node} the removed child.
*/
pv.Dom.Node.prototype.removeChild = function (n) {
var i = this.childNodes.indexOf(n);
if (i == -1)
throw new Error("child not found");
this.childNodes.splice(i, 1);
if (n.previousSibling)
n.previousSibling.nextSibling = n.nextSibling;
else
this.firstChild = n.nextSibling;
if (n.nextSibling)
n.nextSibling.previousSibling = n.previousSibling;
else
this.lastChild = n.previousSibling;
delete n.nextSibling;
delete n.previousSibling;
delete n.parentNode;
return n;
};
/**
* Appends the specified child node to this node. If the specified child is
* already part of the DOM, the child is first removed before being added to
* this node.
*
* @returns {pv.Dom.Node} the appended child.
*/
pv.Dom.Node.prototype.appendChild = function (n) {
if (n.parentNode)
n.parentNode.removeChild(n);
n.parentNode = this;
n.previousSibling = this.lastChild;
if (this.lastChild)
this.lastChild.nextSibling = n;
else
this.firstChild = n;
this.lastChild = n;
this.childNodes.push(n);
return n;
};
/**
* Inserts the specified child <i>n</i> before the given reference child
* <i>r</i> of this node. If <i>r</i> is null, this method is equivalent to
* {@link #appendChild}. If <i>n</i> is already part of the DOM, it is first
* removed before being inserted.
*
* @throws Error if <i>r</i> is non-null and not a child of this node.
* @returns {pv.Dom.Node} the inserted child.
*/
pv.Dom.Node.prototype.insertBefore = function (n, r) {
if (!r)
return this.appendChild(n);
var i = this.childNodes.indexOf(r);
if (i == -1)
throw new Error("child not found");
if (n.parentNode)
n.parentNode.removeChild(n);
n.parentNode = this;
n.nextSibling = r;
n.previousSibling = r.previousSibling;
if (r.previousSibling) {
r.previousSibling.nextSibling = n;
} else {
if (r == this.lastChild)
this.lastChild = n;
this.firstChild = n;
}
this.childNodes.splice(i, 0, n);
return n;
};
/**
* Replaces the specified child <i>r</i> of this node with the node <i>n</i>. If
* <i>n</i> is already part of the DOM, it is first removed before being added.
*
* @throws Error if <i>r</i> is not a child of this node.
*/
pv.Dom.Node.prototype.replaceChild = function (n, r) {
var i = this.childNodes.indexOf(r);
if (i == -1)
throw new Error("child not found");
if (n.parentNode)
n.parentNode.removeChild(n);
n.parentNode = this;
n.nextSibling = r.nextSibling;
n.previousSibling = r.previousSibling;
if (r.previousSibling)
r.previousSibling.nextSibling = n;
else
this.firstChild = n;
if (r.nextSibling)
r.nextSibling.previousSibling = n;
else
this.lastChild = n;
this.childNodes[i] = n;
return r;
};
/**
* Visits each node in the tree in preorder traversal, applying the specified
* function <i>f</i>. The arguments to the function are:<ol>
*
* <li>The current node.
* <li>The current depth, starting at 0 for the root node.</ol>
*
* @param {function} f a function to apply to each node.
*/
pv.Dom.Node.prototype.visitBefore = function (f) {
function visit(n, i) {
f(n, i);
for (var c = n.firstChild; c; c = c.nextSibling) {
visit(c, i + 1);
}
}
visit(this, 0);
};
/**
* Visits each node in the tree in postorder traversal, applying the specified
* function <i>f</i>. The arguments to the function are:<ol>
*
* <li>The current node.
* <li>The current depth, starting at 0 for the root node.</ol>
*
* @param {function} f a function to apply to each node.
*/
pv.Dom.Node.prototype.visitAfter = function (f) {
function visit(n, i) {
for (var c = n.firstChild; c; c = c.nextSibling) {
visit(c, i + 1);
}
f(n, i);
}
visit(this, 0);
};
/**
* Sorts child nodes of this node, and all descendent nodes recursively, using
* the specified comparator function <tt>f</tt>. The comparator function is
* passed two nodes to compare.
*
* <p>Note: during the sort operation, the comparator function should not rely
* on the tree being well-formed; the values of <tt>previousSibling</tt> and
* <tt>nextSibling</tt> for the nodes being compared are not defined during the
* sort operation.
*
* @param {function} f a comparator function.
* @returns this.
*/
pv.Dom.Node.prototype.sort = function (f) {
if (this.firstChild) {
this.childNodes.sort(f);
var p = this.firstChild = this.childNodes[0], c;
delete p.previousSibling;
for (var i = 1; i < this.childNodes.length; i++) {
p.sort(f);
c = this.childNodes[i];
c.previousSibling = p;
p = p.nextSibling = c;
}
this.lastChild = p;
delete p.nextSibling;
p.sort(f);
}
return this;
};
/**
* Reverses all sibling nodes.
*
* @returns this.
*/
pv.Dom.Node.prototype.reverse = function () {
var childNodes = [];
this.visitAfter(function (n) {
while (n.lastChild)
childNodes.push(n.removeChild(n.lastChild));
for (var c; c = childNodes.pop(); )
n.insertBefore(c, n.firstChild);
});
return this;
};
/** Returns all descendants of this node in preorder traversal. */
pv.Dom.Node.prototype.nodes = function () {
var array = [];
/** @private */
function flatten(node) {
array.push(node);
node.childNodes.forEach(flatten);
}
flatten(this, array);
return array;
};
/**
* Toggles the child nodes of this node. If this node is not yet toggled, this
* method removes all child nodes and appends them to a new <tt>toggled</tt>
* array attribute on this node. Otherwise, if this node is toggled, this method
* re-adds all toggled child nodes and deletes the <tt>toggled</tt> attribute.
*
* <p>This method has no effect if the node has no child nodes.
*
* @param {boolean} [recursive] whether the toggle should apply to descendants.
*/
pv.Dom.Node.prototype.toggle = function (recursive) {
if (recursive)
return this.toggled
? this.visitBefore(function (n) {
if (n.toggled)
n.toggle();
})
: this.visitAfter(function (n) {
if (!n.toggled)
n.toggle();
});
var n = this;
if (n.toggled) {
for (var c; c = n.toggled.pop(); )
n.appendChild(c);
delete n.toggled;
} else if (n.lastChild) {
n.toggled = [];
while (n.lastChild)
n.toggled.push(n.removeChild(n.lastChild));
}
};
/**
* Given a flat array of values, returns a simple DOM with each value wrapped by
* a node that is a child of the root node.
*
* @param {array} values.
* @returns {array} nodes.
*/
pv.nodes = function (values) {
var root = new pv.Dom.Node();
for (var i = 0; i < values.length; i++) {
root.appendChild(new pv.Dom.Node(values[i]));
}
return root.nodes();
};
/**
* Returns a {@link pv.Tree} operator for the specified array. This is a
* convenience factory method, equivalent to <tt>new pv.Tree(array)</tt>.
*
* @see pv.Tree
* @param {array} array an array from which to construct a tree.
* @returns {pv.Tree} a tree operator for the specified array.
*/
pv.tree = function (array) {
return new pv.Tree(array);
};
/**
* Constructs a tree operator for the specified array. This constructor should
* not be invoked directly; use {@link pv.tree} instead.
*
* @class Represents a tree operator for the specified array. The tree operator
* allows a hierarchical map to be constructed from an array; it is similar to
* the {@link pv.Nest} operator, except the hierarchy is derived dynamically
* from the array elements.
*
* <p>For example, given an array of size information for ActionScript classes:
*
* <pre>{ name: "flare.flex.FlareVis", size: 4116 },
* { name: "flare.physics.DragForce", size: 1082 },
* { name: "flare.physics.GravityForce", size: 1336 }, ...</pre>
*
* To facilitate visualization, it may be useful to nest the elements by their
* package hierarchy:
*
* <pre>var tree = pv.tree(classes)
* .keys(function(d) d.name.split("."))
* .map();</pre>
*
* The resulting tree is:
*
* <pre>{ flare: {
* flex: {
* FlareVis: {
* name: "flare.flex.FlareVis",
* size: 4116 } },
* physics: {
* DragForce: {
* name: "flare.physics.DragForce",
* size: 1082 },
* GravityForce: {
* name: "flare.physics.GravityForce",
* size: 1336 } },
* ... } }</pre>
*
* By specifying a value function,
*
* <pre>var tree = pv.tree(classes)
* .keys(function(d) d.name.split("."))
* .value(function(d) d.size)
* .map();</pre>
*
* we can further eliminate redundant data:
*
* <pre>{ flare: {
* flex: {
* FlareVis: 4116 },
* physics: {
* DragForce: 1082,
* GravityForce: 1336 },
* ... } }</pre>
*
* For visualizations with large data sets, performance improvements may be seen
* by storing the data in a tree format, and then flattening it into an array at
* runtime with {@link pv.Flatten}.
*
* @param {array} array an array from which to construct a tree.
*/
pv.Tree = function (array) {
this.array = array;
};
/**
* Assigns a <i>keys</i> function to this operator; required. The keys function
* returns an array of <tt>string</tt>s for each element in the associated
* array; these keys determine how the elements are nested in the tree. The
* returned keys should be unique for each element in the array; otherwise, the
* behavior of this operator is undefined.
*
* @param {function} k the keys function.
* @returns {pv.Tree} this.
*/
pv.Tree.prototype.keys = function (k) {
this.k = k;
return this;
};
/**
* Assigns a <i>value</i> function to this operator; optional. The value
* function specifies an optional transformation of the element in the array
* before it is inserted into the map. If no value function is specified, it is
* equivalent to using the identity function.
*
* @param {function} k the value function.
* @returns {pv.Tree} this.
*/
pv.Tree.prototype.value = function (v) {
this.v = v;
return this;
};
/**
* Returns a hierarchical map of values. The hierarchy is determined by the keys
* function; the values in the map are determined by the value function.
*
* @returns a hierarchical map of values.
*/
pv.Tree.prototype.map = function () {
var map = {}, o = {};
for (var i = 0; i < this.array.length; i++) {
o.index = i;
var value = this.array[i], keys = this.k.call(o, value), node = map;
for (var j = 0; j < keys.length - 1; j++) {
node = node[keys[j]] || (node[keys[j]] = {});
}
node[keys[j]] = this.v ? this.v.call(o, value) : value;
}
return map;
};
/**
* Returns a {@link pv.Nest} operator for the specified array. This is a
* convenience factory method, equivalent to <tt>new pv.Nest(array)</tt>.
*
* @see pv.Nest
* @param {array} array an array of elements to nest.
* @returns {pv.Nest} a nest operator for the specified array.
*/
pv.nest = function (array) {
return new pv.Nest(array);
};
/**
* Constructs a nest operator for the specified array. This constructor should
* not be invoked directly; use {@link pv.nest} instead.
*
* @class Represents a {@link Nest} operator for the specified array. Nesting
* allows elements in an array to be grouped into a hierarchical tree
* structure. The levels in the tree are specified by <i>key</i> functions. The
* leaf nodes of the tree can be sorted by value, while the internal nodes can
* be sorted by key. Finally, the tree can be returned either has a
* multidimensional array via {@link #entries}, or as a hierarchical map via
* {@link #map}. The {@link #rollup} routine similarly returns a map, collapsing
* the elements in each leaf node using a summary function.
*
* <p>For example, consider the following tabular data structure of Barley
* yields, from various sites in Minnesota during 1931-2:
*
* <pre>{ yield: 27.00, variety: "Manchuria", year: 1931, site: "University Farm" },
* { yield: 48.87, variety: "Manchuria", year: 1931, site: "Waseca" },
* { yield: 27.43, variety: "Manchuria", year: 1931, site: "Morris" }, ...</pre>
*
* To facilitate visualization, it may be useful to nest the elements first by
* year, and then by variety, as follows:
*
* <pre>var nest = pv.nest(yields)
* .key(function(d) d.year)
* .key(function(d) d.variety)
* .entries();</pre>
*
* This returns a nested array. Each element of the outer array is a key-values
* pair, listing the values for each distinct key:
*
* <pre>{ key: 1931, values: [
* { key: "Manchuria", values: [
* { yield: 27.00, variety: "Manchuria", year: 1931, site: "University Farm" },
* { yield: 48.87, variety: "Manchuria", year: 1931, site: "Waseca" },
* { yield: 27.43, variety: "Manchuria", year: 1931, site: "Morris" },
* ...
* ] },
* { key: "Glabron", values: [
* { yield: 43.07, variety: "Glabron", year: 1931, site: "University Farm" },
* { yield: 55.20, variety: "Glabron", year: 1931, site: "Waseca" },
* ...
* ] },
* ] },
* { key: 1932, values: ... }</pre>
*
* Further details, including sorting and rollup, is provided below on the
* corresponding methods.
*
* @param {array} array an array of elements to nest.
*/
pv.Nest = function (array) {
this.array = array;
this.keys = [];
};
/**
* Nests using the specified key function. Multiple keys may be added to the
* nest; the array elements will be nested in the order keys are specified.
*
* @param {function} key a key function; must return a string or suitable map
* key.
* @returns {pv.Nest} this.
*/
pv.Nest.prototype.key = function (key) {
this.keys.push(key);
return this;
};
/**
* Sorts the previously-added keys. The natural sort order is used by default
* (see {@link pv.naturalOrder}); if an alternative order is desired,
* <tt>order</tt> should be a comparator function. If this method is not called
* (i.e., keys are <i>unsorted</i>), keys will appear in the order they appear
* in the underlying elements array. For example,
*
* <pre>pv.nest(yields)
* .key(function(d) d.year)
* .key(function(d) d.variety)
* .sortKeys()
* .entries()</pre>
*
* groups yield data by year, then variety, and sorts the variety groups
* lexicographically (since the variety attribute is a string).
*
* <p>Key sort order is only used in conjunction with {@link #entries}, which
* returns an array of key-values pairs. If the nest is used to construct a
* {@link #map} instead, keys are unsorted.
*
* @param {function} [order] an optional comparator function.
* @returns {pv.Nest} this.
*/
pv.Nest.prototype.sortKeys = function (order) {
this.keys[this.keys.length - 1].order = order || pv.naturalOrder;
return this;
};
/**
* Sorts the leaf values. The natural sort order is used by default (see
* {@link pv.naturalOrder}); if an alternative order is desired, <tt>order</tt>
* should be a comparator function. If this method is not called (i.e., values
* are <i>unsorted</i>), values will appear in the order they appear in the
* underlying elements array. For example,
*
* <pre>pv.nest(yields)
* .key(function(d) d.year)
* .key(function(d) d.variety)
* .sortValues(function(a, b) a.yield - b.yield)
* .entries()</pre>
*
* groups yield data by year, then variety, and sorts the values for each
* variety group by yield.
*
* <p>Value sort order, unlike keys, applies to both {@link #entries} and
* {@link #map}. It has no effect on {@link #rollup}.
*
* @param {function} [order] an optional comparator function.
* @returns {pv.Nest} this.
*/
pv.Nest.prototype.sortValues = function (order) {
this.order = order || pv.naturalOrder;
return this;
};
/**
* Returns a hierarchical map of values. Each key adds one level to the
* hierarchy. With only a single key, the returned map will have a key for each
* distinct value of the key function; the correspond value with be an array of
* elements with that key value. If a second key is added, this will be a nested
* map. For example:
*
* <pre>pv.nest(yields)
* .key(function(d) d.variety)
* .key(function(d) d.site)
* .map()</pre>
*
* returns a map <tt>m</tt> such that <tt>m[variety][site]</tt> is an array, a subset of
* <tt>yields</tt>, with each element having the given variety and site.
*
* @returns a hierarchical map of values.
*/
pv.Nest.prototype.map = function () {
var map = {}, values = [];
/* Build the map. */
for (var i, j = 0; j < this.array.length; j++) {
var x = this.array[j];
var m = map;
for (i = 0; i < this.keys.length - 1; i++) {
var k = this.keys[i](x);
if (!m[k])
m[k] = {};
m = m[k];
}
k = this.keys[i](x);
if (!m[k]) {
var a = [];
values.push(a);
m[k] = a;
}
m[k].push(x);
}
/* Sort each leaf array. */
if (this.order) {
for (var i = 0; i < values.length; i++) {
values[i].sort(this.order);
}
}
return map;
};
/**
* Returns a hierarchical nested array. This method is similar to
* {@link pv.entries}, but works recursively on the entire hierarchy. Rather
* than returning a map like {@link #map}, this method returns a nested
* array. Each element of the array has a <tt>key</tt> and <tt>values</tt>
* field. For leaf nodes, the <tt>values</tt> array will be a subset of the
* underlying elements array; for non-leaf nodes, the <tt>values</tt> array will
* contain more key-values pairs.
*
* <p>For an example usage, see the {@link Nest} constructor.
*
* @returns a hierarchical nested array.
*/
pv.Nest.prototype.entries = function () {
/** Recursively extracts the entries for the given map. */
function entries(map) {
var array = [];
for (var k in map) {
var v = map[k];
array.push({key: k, values: (v instanceof Array) ? v : entries(v)});
}
;
return array;
}
/** Recursively sorts the values for the given key-values array. */
function sort(array, i) {
var o = this.keys[i].order;
if (o)
array.sort(function (a, b) {
return o(a.key, b.key);
});
if (++i < this.keys.length) {
for (var j = 0; j < array.length; j++) {
sort.call(this, array[j].values, i);
}
}
return array;
}
return sort.call(this, entries(this.map()), 0);
};
/**
* Returns a rollup map. The behavior of this method is the same as
* {@link #map}, except that the leaf values are replaced with the return value
* of the specified rollup function <tt>f</tt>. For example,
*
* <pre>pv.nest(yields)
* .key(function(d) d.site)
* .rollup(function(v) pv.median(v, function(d) d.yield))</pre>
*
* first groups yield data by site, and then returns a map from site to median
* yield for the given site.
*
* @see #map
* @param {function} f a rollup function.
* @returns a hierarchical map, with the leaf values computed by <tt>f</tt>.
*/
pv.Nest.prototype.rollup = function (f) {
/** Recursively descends to the leaf nodes (arrays) and does rollup. */
function rollup(map) {
for (var key in map) {
var value = map[key];
if (value instanceof Array) {
map[key] = f(value);
} else {
rollup(value);
}
}
return map;
}
return rollup(this.map());
};
/**
* Returns a {@link pv.Flatten} operator for the specified map. This is a
* convenience factory method, equivalent to <tt>new pv.Flatten(map)</tt>.
*
* @see pv.Flatten
* @param map a map to flatten.
* @returns {pv.Flatten} a flatten operator for the specified map.
*/
pv.flatten = function (map) {
return new pv.Flatten(map);
};
/**
* Constructs a flatten operator for the specified map. This constructor should
* not be invoked directly; use {@link pv.flatten} instead.
*
* @class Represents a flatten operator for the specified array. Flattening
* allows hierarchical maps to be flattened into an array. The levels in the
* input tree are specified by <i>key</i> functions.
*
* <p>For example, consider the following hierarchical data structure of Barley
* yields, from various sites in Minnesota during 1931-2:
*
* <pre>{ 1931: {
* Manchuria: {
* "University Farm": 27.00,
* "Waseca": 48.87,
* "Morris": 27.43,
* ... },
* Glabron: {
* "University Farm": 43.07,
* "Waseca": 55.20,
* ... } },
* 1932: {
* ... } }</pre>
*
* To facilitate visualization, it may be useful to flatten the tree into a
* tabular array:
*
* <pre>var array = pv.flatten(yields)
* .key("year")
* .key("variety")
* .key("site")
* .key("yield")
* .array();</pre>
*
* This returns an array of object elements. Each element in the array has
* attributes corresponding to this flatten operator's keys:
*
* <pre>{ site: "University Farm", variety: "Manchuria", year: 1931, yield: 27 },
* { site: "Waseca", variety: "Manchuria", year: 1931, yield: 48.87 },
* { site: "Morris", variety: "Manchuria", year: 1931, yield: 27.43 },
* { site: "University Farm", variety: "Glabron", year: 1931, yield: 43.07 },
* { site: "Waseca", variety: "Glabron", year: 1931, yield: 55.2 }, ...</pre>
*
* <p>The flatten operator is roughly the inverse of the {@link pv.Nest} and
* {@link pv.Tree} operators.
*
* @param map a map to flatten.
*/
pv.Flatten = function (map) {
this.map = map;
this.keys = [];
};
/**
* Flattens using the specified key function. Multiple keys may be added to the
* flatten; the tiers of the underlying tree must correspond to the specified
* keys, in order. The order of the returned array is undefined; however, you
* can easily sort it.
*
* @param {string} key the key name.
* @param {function} [f] an optional value map function.
* @returns {pv.Nest} this.
*/
pv.Flatten.prototype.key = function (key, f) {
this.keys.push({name: key, value: f});
delete this.$leaf;
return this;
};
/**
* Flattens using the specified leaf function. This is an alternative to
* specifying an explicit set of keys; the tiers of the underlying tree will be
* determined dynamically by recursing on the values, and the resulting keys
* will be stored in the entries <tt>keys</tt> attribute. The leaf function must
* return true for leaves, and false for internal nodes.
*
* @param {function} f a leaf function.
* @returns {pv.Nest} this.
*/
pv.Flatten.prototype.leaf = function (f) {
this.keys.length = 0;
this.$leaf = f;
return this;
};
/**
* Returns the flattened array. Each entry in the array is an object; each
* object has attributes corresponding to this flatten operator's keys.
*
* @returns an array of elements from the flattened map.
*/
pv.Flatten.prototype.array = function () {
var entries = [], stack = [], keys = this.keys, leaf = this.$leaf;
/* Recursively visit using the leaf function. */
if (leaf) {
function recurse(value, i) {
if (leaf(value)) {
entries.push({keys: stack.slice(), value: value});
} else {
for (var key in value) {
stack.push(key);
recurse(value[key], i + 1);
stack.pop();
}
}
}
recurse(this.map, 0);
return entries;
}
/* Recursively visits the specified value. */
function visit(value, i) {
if (i < keys.length - 1) {
for (var key in value) {
stack.push(key);
visit(value[key], i + 1);
stack.pop();
}
} else {
entries.push(stack.concat(value));
}
}
visit(this.map, 0);
return entries.map(function (stack) {
var m = {};
for (var i = 0; i < keys.length; i++) {
var k = keys[i], v = stack[i];
m[k.name] = k.value ? k.value.call(null, v) : v;
}
return m;
});
};
/**
* Returns a {@link pv.Vector} for the specified <i>x</i> and <i>y</i>
* coordinate. This is a convenience factory method, equivalent to <tt>new
* pv.Vector(x, y)</tt>.
*
* @see pv.Vector
* @param {number} x the <i>x</i> coordinate.
* @param {number} y the <i>y</i> coordinate.
* @returns {pv.Vector} a vector for the specified coordinates.
*/
pv.vector = function (x, y) {
return new pv.Vector(x, y);
};
/**
* Constructs a {@link pv.Vector} for the specified <i>x</i> and <i>y</i>
* coordinate. This constructor should not be invoked directly; use
* {@link pv.vector} instead.
*
* @class Represents a two-dimensional vector; a 2-tuple <i>⟨x,
* y⟩</i>. The intent of this class is to simplify vector math. Note that
* in performance-sensitive cases it may be more efficient to represent 2D
* vectors as simple objects with <tt>x</tt> and <tt>y</tt> attributes, rather
* than using instances of this class.
*
* @param {number} x the <i>x</i> coordinate.
* @param {number} y the <i>y</i> coordinate.
*/
pv.Vector = function (x, y) {
this.x = x;
this.y = y;
};
/**
* Returns a vector perpendicular to this vector: <i>⟨-y, x⟩</i>.
*
* @returns {pv.Vector} a perpendicular vector.
*/
pv.Vector.prototype.perp = function () {
return new pv.Vector(-this.y, this.x);
};
/**
* Returns a normalized copy of this vector: a vector with the same direction,
* but unit length. If this vector has zero length this method returns a copy of
* this vector.
*
* @returns {pv.Vector} a unit vector.
*/
pv.Vector.prototype.norm = function () {
var l = this.length();
return this.times(l ? (1 / l) : 1);
};
/**
* Returns the magnitude of this vector, defined as <i>sqrt(x * x + y * y)</i>.
*
* @returns {number} a length.
*/
pv.Vector.prototype.length = function () {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
/**
* Returns a scaled copy of this vector: <i>⟨x * k, y * k⟩</i>.
* To perform the equivalent divide operation, use <i>1 / k</i>.
*
* @param {number} k the scale factor.
* @returns {pv.Vector} a scaled vector.
*/
pv.Vector.prototype.times = function (k) {
return new pv.Vector(this.x * k, this.y * k);
};
/**
* Returns this vector plus the vector <i>v</i>: <i>⟨x + v.x, y +
* v.y⟩</i>. If only one argument is specified, it is interpreted as the
* vector <i>v</i>.
*
* @param {number} x the <i>x</i> coordinate to add.
* @param {number} y the <i>y</i> coordinate to add.
* @returns {pv.Vector} a new vector.
*/
pv.Vector.prototype.plus = function (x, y) {
return (arguments.length == 1)
? new pv.Vector(this.x + x.x, this.y + x.y)
: new pv.Vector(this.x + x, this.y + y);
};
/**
* Returns this vector minus the vector <i>v</i>: <i>⟨x - v.x, y -
* v.y⟩</i>. If only one argument is specified, it is interpreted as the
* vector <i>v</i>.
*
* @param {number} x the <i>x</i> coordinate to subtract.
* @param {number} y the <i>y</i> coordinate to subtract.
* @returns {pv.Vector} a new vector.
*/
pv.Vector.prototype.minus = function (x, y) {
return (arguments.length == 1)
? new pv.Vector(this.x - x.x, this.y - x.y)
: new pv.Vector(this.x - x, this.y - y);
};
/**
* Returns the dot product of this vector and the vector <i>v</i>: <i>x * v.x +
* y * v.y</i>. If only one argument is specified, it is interpreted as the
* vector <i>v</i>.
*
* @param {number} x the <i>x</i> coordinate to dot.
* @param {number} y the <i>y</i> coordinate to dot.
* @returns {number} a dot product.
*/
pv.Vector.prototype.dot = function (x, y) {
return (arguments.length == 1)
? this.x * x.x + this.y * x.y
: this.x * x + this.y * y;
};
/**
* Returns a new identity transform.
*
* @class Represents a transformation matrix. The transformation matrix is
* limited to expressing translate and uniform scale transforms only; shearing,
* rotation, general affine, and other transforms are not supported.
*
* <p>The methods on this class treat the transform as immutable, returning a
* copy of the transformation matrix with the specified transform applied. Note,
* alternatively, that the matrix fields can be get and set directly.
*/
pv.Transform = function () {
};
pv.Transform.prototype = {k: 1, x: 0, y: 0};
/**
* The scale magnitude; defaults to 1.
*
* @type number
* @name pv.Transform.prototype.k
*/
/**
* The x-offset; defaults to 0.
*
* @type number
* @name pv.Transform.prototype.x
*/
/**
* The y-offset; defaults to 0.
*
* @type number
* @name pv.Transform.prototype.y
*/
/**
* @private The identity transform.
*
* @type pv.Transform
*/
pv.Transform.identity = new pv.Transform();
// k 0 x 1 0 a k 0 ka+x
// 0 k y * 0 1 b = 0 k kb+y
// 0 0 1 0 0 1 0 0 1
/**
* Returns a translated copy of this transformation matrix.
*
* @param {number} x the x-offset.
* @param {number} y the y-offset.
* @returns {pv.Transform} the translated transformation matrix.
*/
pv.Transform.prototype.translate = function (x, y) {
var v = new pv.Transform();
v.k = this.k;
v.x = this.k * x + this.x;
v.y = this.k * y + this.y;
return v;
};
// k 0 x d 0 0 kd 0 x
// 0 k y * 0 d 0 = 0 kd y
// 0 0 1 0 0 1 0 0 1
/**
* Returns a scaled copy of this transformation matrix.
*
* @param {number} k
* @returns {pv.Transform} the scaled transformation matrix.
*/
pv.Transform.prototype.scale = function (k) {
var v = new pv.Transform();
v.k = this.k * k;
v.x = this.x;
v.y = this.y;
return v;
};
/**
* Returns the inverse of this transformation matrix.
*
* @returns {pv.Transform} the inverted transformation matrix.
*/
pv.Transform.prototype.invert = function () {
var v = new pv.Transform(), k = 1 / this.k;
v.k = k;
v.x = -this.x * k;
v.y = -this.y * k;
return v;
};
// k 0 x d 0 a kd 0 ka+x
// 0 k y * 0 d b = 0 kd kb+y
// 0 0 1 0 0 1 0 0 1
/**
* Returns this matrix post-multiplied by the specified matrix <i>m</i>.
*
* @param {pv.Transform} m
* @returns {pv.Transform} the post-multiplied transformation matrix.
*/
pv.Transform.prototype.times = function (m) {
var v = new pv.Transform();
v.k = this.k * m.k;
v.x = this.k * m.x + this.x;
v.y = this.k * m.y + this.y;
return v;
};
/**
* Abstract; see the various scale implementations.
*
* @class Represents a scale; a function that performs a transformation from
* data domain to visual range. For quantitative and quantile scales, the domain
* is expressed as numbers; for ordinal scales, the domain is expressed as
* strings (or equivalently objects with unique string representations). The
* "visual range" may correspond to pixel space, colors, font sizes, and the
* like.
*
* <p>Note that scales are functions, and thus can be used as properties
* directly, assuming that the data associated with a mark is a number. While
* this is convenient for single-use scales, frequently it is desirable to
* define scales globally:
*
* <pre>var y = pv.Scale.linear(0, 100).range(0, 640);</pre>
*
* The <tt>y</tt> scale can now be equivalently referenced within a property:
*
* <pre> .height(function(d) y(d))</pre>
*
* Alternatively, if the data are not simple numbers, the appropriate value can
* be passed to the <tt>y</tt> scale (e.g., <tt>d.foo</tt>). The {@link #by}
* method similarly allows the data to be mapped to a numeric value before
* performing the linear transformation.
*
* @see pv.Scale.quantitative
* @see pv.Scale.quantile
* @see pv.Scale.ordinal
* @extends function
*/
pv.Scale = function () {
};
/**
* @private Returns a function that interpolators from the start value to the
* end value, given a parameter <i>t</i> in [0, 1].
*
* @param start the start value.
* @param end the end value.
*/
pv.Scale.interpolator = function (start, end) {
if (typeof start == "number") {
return function (t) {
return t * (end - start) + start;
};
}
/* For now, assume color. */
start = pv.color(start).rgb();
end = pv.color(end).rgb();
return function (t) {
var a = start.a * (1 - t) + end.a * t;
if (a < 1e-5)
a = 0; // avoid scientific notation
return (start.a == 0) ? pv.rgb(end.r, end.g, end.b, a)
: ((end.a == 0) ? pv.rgb(start.r, start.g, start.b, a)
: pv.rgb(
Math.round(start.r * (1 - t) + end.r * t),
Math.round(start.g * (1 - t) + end.g * t),
Math.round(start.b * (1 - t) + end.b * t), a));
};
};
/**
* Returns a view of this scale by the specified accessor function <tt>f</tt>.
* Given a scale <tt>y</tt>, <tt>y.by(function(d) d.foo)</tt> is equivalent to
* <tt>function(d) y(d.foo)</tt>.
*
* <p>This method is provided for convenience, such that scales can be
* succinctly defined inline. For example, given an array of data elements that
* have a <tt>score</tt> attribute with the domain [0, 1], the height property
* could be specified as:
*
* <pre> .height(pv.Scale.linear().range(0, 480).by(function(d) d.score))</pre>
*
* This is equivalent to:
*
* <pre> .height(function(d) d.score * 480)</pre>
*
* This method should be used judiciously; it is typically more clear to invoke
* the scale directly, passing in the value to be scaled.
*
* @function
* @name pv.Scale.prototype.by
* @param {function} f an accessor function.
* @returns {pv.Scale} a view of this scale by the specified accessor function.
*/
/**
* Returns a default quantitative, linear, scale for the specified domain. The
* arguments to this constructor are optional, and equivalent to calling
* {@link #domain}. The default domain and range are [0,1].
*
* <p>This constructor is typically not used directly; see one of the
* quantitative scale implementations instead.
*
* @class Represents an abstract quantitative scale; a function that performs a
* numeric transformation. This class is typically not used directly; see one of
* the quantitative scale implementations (linear, log, root, etc.)
* instead. <style type="text/css">sub{line-height:0}</style> A quantitative
* scale represents a 1-dimensional transformation from a numeric domain of
* input data [<i>d<sub>0</sub></i>, <i>d<sub>1</sub></i>] to a numeric range of
* pixels [<i>r<sub>0</sub></i>, <i>r<sub>1</sub></i>]. In addition to
* readability, scales offer several useful features:
*
* <p>1. The range can be expressed in colors, rather than pixels. For example:
*
* <pre> .fillStyle(pv.Scale.linear(0, 100).range("red", "green"))</pre>
*
* will fill the marks "red" on an input value of 0, "green" on an input value
* of 100, and some color in-between for intermediate values.
*
* <p>2. The domain and range can be subdivided for a non-uniform
* transformation. For example, you may want a diverging color scale that is
* increasingly red for negative values, and increasingly green for positive
* values:
*
* <pre> .fillStyle(pv.Scale.linear(-1, 0, 1).range("red", "white", "green"))</pre>
*
* The domain can be specified as a series of <i>n</i> monotonically-increasing
* values; the range must also be specified as <i>n</i> values, resulting in
* <i>n - 1</i> contiguous linear scales.
*
* <p>3. Quantitative scales can be inverted for interaction. The
* {@link #invert} method takes a value in the output range, and returns the
* corresponding value in the input domain. This is frequently used to convert
* the mouse location (see {@link pv.Mark#mouse}) to a value in the input
* domain. Note that inversion is only supported for numeric ranges, and not
* colors.
*
* <p>4. A scale can be queried for reasonable "tick" values. The {@link #ticks}
* method provides a convenient way to get a series of evenly-spaced rounded
* values in the input domain. Frequently these are used in conjunction with
* {@link pv.Rule} to display tick marks or grid lines.
*
* <p>5. A scale can be "niced" to extend the domain to suitable rounded
* numbers. If the minimum and maximum of the domain are messy because they are
* derived from data, you can use {@link #nice} to round these values down and
* up to even numbers.
*
* @param {number...} domain... optional domain values.
* @see pv.Scale.linear
* @see pv.Scale.log
* @see pv.Scale.root
* @extends pv.Scale
*/
pv.Scale.quantitative = function () {
var d = [0, 1], // default domain
l = [0, 1], // default transformed domain
r = [0, 1], // default range
i = [pv.identity], // default interpolators
type = Number, // default type
n = false, // whether the domain is negative
f = pv.identity, // default forward transform
g = pv.identity, // default inverse transform
tickFormat = String; // default tick formatting function
/** @private */
function newDate(x) {
return new Date(x);
}
/** @private */
function scale(x) {
var j = pv.search(d, x);
if (j < 0)
j = -j - 2;
j = Math.max(0, Math.min(i.length - 1, j));
return i[j]((f(x) - l[j]) / (l[j + 1] - l[j]));
}
/** @private */
scale.transform = function (forward, inverse) {
/** @ignore */ f = function (x) {
return n ? -forward(-x) : forward(x);
};
/** @ignore */ g = function (y) {
return n ? -inverse(-y) : inverse(y);
};
l = d.map(f);
return this;
};
/**
* Sets or gets the input domain. This method can be invoked several ways:
*
* <p>1. <tt>domain(min, ..., max)</tt>
*
* <p>Specifying the domain as a series of numbers is the most explicit and
* recommended approach. Most commonly, two numbers are specified: the minimum
* and maximum value. However, for a diverging scale, or other subdivided
* non-uniform scales, multiple values can be specified. Values can be derived
* from data using {@link pv.min} and {@link pv.max}. For example:
*
* <pre> .domain(0, pv.max(array))</pre>
*
* An alternative method for deriving minimum and maximum values from data
* follows.
*
* <p>2. <tt>domain(array, minf, maxf)</tt>
*
* <p>When both the minimum and maximum value are derived from data, the
* arguments to the <tt>domain</tt> method can be specified as the array of
* data, followed by zero, one or two accessor functions. For example, if the
* array of data is just an array of numbers:
*
* <pre> .domain(array)</pre>
*
* On the other hand, if the array elements are objects representing stock
* values per day, and the domain should consider the stock's daily low and
* daily high:
*
* <pre> .domain(array, function(d) d.low, function(d) d.high)</pre>
*
* The first method of setting the domain is preferred because it is more
* explicit; setting the domain using this second method should be used only
* if brevity is required.
*
* <p>3. <tt>domain()</tt>
*
* <p>Invoking the <tt>domain</tt> method with no arguments returns the
* current domain as an array of numbers.
*
* @function
* @name pv.Scale.quantitative.prototype.domain
* @param {number...} domain... domain values.
* @returns {pv.Scale.quantitative} <tt>this</tt>, or the current domain.
*/
scale.domain = function (array, min, max) {
if (arguments.length) {
var o; // the object we use to infer the domain type
if (array instanceof Array) {
if (arguments.length < 2)
min = pv.identity;
if (arguments.length < 3)
max = min;
o = array.length && min(array[0]);
d = array.length ? [pv.min(array, min), pv.max(array, max)] : [];
} else {
o = array;
d = Array.prototype.slice.call(arguments).map(Number);
}
if (!d.length)
d = [-Infinity, Infinity];
else if (d.length == 1)
d = [d[0], d[0]];
n = (d[0] || d[d.length - 1]) < 0;
l = d.map(f);
type = (o instanceof Date) ? newDate : Number;
return this;
}
return d.map(type);
};
/**
* Sets or gets the output range. This method can be invoked several ways:
*
* <p>1. <tt>range(min, ..., max)</tt>
*
* <p>The range may be specified as a series of numbers or colors. Most
* commonly, two numbers are specified: the minimum and maximum pixel values.
* For a color scale, values may be specified as {@link pv.Color}s or
* equivalent strings. For a diverging scale, or other subdivided non-uniform
* scales, multiple values can be specified. For example:
*
* <pre> .range("red", "white", "green")</pre>
*
* <p>Currently, only numbers and colors are supported as range values. The
* number of range values must exactly match the number of domain values, or
* the behavior of the scale is undefined.
*
* <p>2. <tt>range()</tt>
*
* <p>Invoking the <tt>range</tt> method with no arguments returns the current
* range as an array of numbers or colors.
*
* @function
* @name pv.Scale.quantitative.prototype.range
* @param {...} range... range values.
* @returns {pv.Scale.quantitative} <tt>this</tt>, or the current range.
*/
scale.range = function () {
if (arguments.length) {
r = Array.prototype.slice.call(arguments);
if (!r.length)
r = [-Infinity, Infinity];
else if (r.length == 1)
r = [r[0], r[0]];
i = [];
for (var j = 0; j < r.length - 1; j++) {
i.push(pv.Scale.interpolator(r[j], r[j + 1]));
}
return this;
}
return r;
};
/**
* Inverts the specified value in the output range, returning the
* corresponding value in the input domain. This is frequently used to convert
* the mouse location (see {@link pv.Mark#mouse}) to a value in the input
* domain. Inversion is only supported for numeric ranges, and not colors.
*
* <p>Note that this method does not do any rounding or bounds checking. If
* the input domain is discrete (e.g., an array index), the returned value
* should be rounded. If the specified <tt>y</tt> value is outside the range,
* the returned value may be equivalently outside the input domain.
*
* @function
* @name pv.Scale.quantitative.prototype.invert
* @param {number} y a value in the output range (a pixel location).
* @returns {number} a value in the input domain.
*/
scale.invert = function (y) {
var j = pv.search(r, y);
if (j < 0)
j = -j - 2;
j = Math.max(0, Math.min(i.length - 1, j));
return type(g(l[j] + (y - r[j]) / (r[j + 1] - r[j]) * (l[j + 1] - l[j])));
};
/**
* Returns an array of evenly-spaced, suitably-rounded values in the input
* domain. This method attempts to return between 5 and 10 tick values. These
* values are frequently used in conjunction with {@link pv.Rule} to display
* tick marks or grid lines.
*
* @function
* @name pv.Scale.quantitative.prototype.ticks
* @param {number} [m] optional number of desired ticks.
* @returns {number[]} an array input domain values to use as ticks.
*/
scale.ticks = function (m) {
var start = d[0],
end = d[d.length - 1],
reverse = end < start,
min = reverse ? end : start,
max = reverse ? start : end,
span = max - min;
/* Special case: empty, invalid or infinite span. */
if (!span || !isFinite(span)) {
if (type == newDate)
tickFormat = pv.Format.date("%x");
return [type(min)];
}
/* Special case: dates. */
if (type == newDate) {
/* Floor the date d given the precision p. */
function floor(d, p) {
switch (p) {
case 31536e6:
d.setMonth(0);
case 2592e6:
d.setDate(1);
case 6048e5:
if (p == 6048e5)
d.setDate(d.getDate() - d.getDay());
case 864e5:
d.setHours(0);
case 36e5:
d.setMinutes(0);
case 6e4:
d.setSeconds(0);
case 1e3:
d.setMilliseconds(0);
}
}
var precision, format, increment, step = 1;
if (span >= 3 * 31536e6) {
precision = 31536e6;
format = "%Y";
/** @ignore */ increment = function (d) {
d.setFullYear(d.getFullYear() + step);
};
} else if (span >= 3 * 2592e6) {
precision = 2592e6;
format = "%m/%Y";
/** @ignore */ increment = function (d) {
d.setMonth(d.getMonth() + step);
};
} else if (span >= 3 * 6048e5) {
precision = 6048e5;
format = "%m/%d";
/** @ignore */ increment = function (d) {
d.setDate(d.getDate() + 7 * step);
};
} else if (span >= 3 * 864e5) {
precision = 864e5;
format = "%m/%d";
/** @ignore */ increment = function (d) {
d.setDate(d.getDate() + step);
};
} else if (span >= 3 * 36e5) {
precision = 36e5;
format = "%I:%M %p";
/** @ignore */ increment = function (d) {
d.setHours(d.getHours() + step);
};
} else if (span >= 3 * 6e4) {
precision = 6e4;
format = "%I:%M %p";
/** @ignore */ increment = function (d) {
d.setMinutes(d.getMinutes() + step);
};
} else if (span >= 3 * 1e3) {
precision = 1e3;
format = "%I:%M:%S";
/** @ignore */ increment = function (d) {
d.setSeconds(d.getSeconds() + step);
};
} else {
precision = 1;
format = "%S.%Qs";
/** @ignore */ increment = function (d) {
d.setTime(d.getTime() + step);
};
}
tickFormat = pv.Format.date(format);
var date = new Date(min), dates = [];
floor(date, precision);
/* If we'd generate too many ticks, skip some!. */
var n = span / precision;
if (n > 10) {
switch (precision) {
case 36e5:
{
step = (n > 20) ? 6 : 3;
date.setHours(Math.floor(date.getHours() / step) * step);
break;
}
case 2592e6:
{
step = 3; // seasons
date.setMonth(Math.floor(date.getMonth() / step) * step);
break;
}
case 6e4:
{
step = (n > 30) ? 15 : ((n > 15) ? 10 : 5);
date.setMinutes(Math.floor(date.getMinutes() / step) * step);
break;
}
case 1e3:
{
step = (n > 90) ? 15 : ((n > 60) ? 10 : 5);
date.setSeconds(Math.floor(date.getSeconds() / step) * step);
break;
}
case 1:
{
step = (n > 1000) ? 250 : ((n > 200) ? 100 : ((n > 100) ? 50 : ((n > 50) ? 25 : 5)));
date.setMilliseconds(Math.floor(date.getMilliseconds() / step) * step);
break;
}
default:
{
step = pv.logCeil(n / 15, 10);
if (n / step < 2)
step /= 5;
else if (n / step < 5)
step /= 2;
date.setFullYear(Math.floor(date.getFullYear() / step) * step);
break;
}
}
}
while (true) {
increment(date);
if (date > max)
break;
dates.push(new Date(date));
}
return reverse ? dates.reverse() : dates;
}
/* Normal case: numbers. */
if (!arguments.length)
m = 10;
var step = pv.logFloor(span / m, 10),
err = m / (span / step);
if (err <= .15)
step *= 10;
else if (err <= .35)
step *= 5;
else if (err <= .75)
step *= 2;
var start = Math.ceil(min / step) * step,
end = Math.floor(max / step) * step;
tickFormat = pv.Format.number()
.fractionDigits(Math.max(0, -Math.floor(pv.log(step, 10) + .01)));
var ticks = pv.range(start, end + step, step);
return reverse ? ticks.reverse() : ticks;
};
/**
* Formats the specified tick value using the appropriate precision, based on
* the step interval between tick marks. If {@link #ticks} has not been called,
* the argument is converted to a string, but no formatting is applied.
*
* @function
* @name pv.Scale.quantitative.prototype.tickFormat
* @param {number} t a tick value.
* @returns {string} a formatted tick value.
*/
scale.tickFormat = function (t) {
return tickFormat(t);
};
/**
* "Nices" this scale, extending the bounds of the input domain to
* evenly-rounded values. Nicing is useful if the domain is computed
* dynamically from data, and may be irregular. For example, given a domain of
* [0.20147987687960267, 0.996679553296417], a call to <tt>nice()</tt> might
* extend the domain to [0.2, 1].
*
* <p>This method must be invoked each time after setting the domain.
*
* @function
* @name pv.Scale.quantitative.prototype.nice
* @returns {pv.Scale.quantitative} <tt>this</tt>.
*/
scale.nice = function () {
if (d.length != 2)
return this; // TODO support non-uniform domains
var start = d[0],
end = d[d.length - 1],
reverse = end < start,
min = reverse ? end : start,
max = reverse ? start : end,
span = max - min;
/* Special case: empty, invalid or infinite span. */
if (!span || !isFinite(span))
return this;
var step = Math.pow(10, Math.round(Math.log(span) / Math.log(10)) - 1);
d = [Math.floor(min / step) * step, Math.ceil(max / step) * step];
if (reverse)
d.reverse();
l = d.map(f);
return this;
};
/**
* Returns a view of this scale by the specified accessor function <tt>f</tt>.
* Given a scale <tt>y</tt>, <tt>y.by(function(d) d.foo)</tt> is equivalent to
* <tt>function(d) y(d.foo)</tt>.
*
* <p>This method is provided for convenience, such that scales can be
* succinctly defined inline. For example, given an array of data elements
* that have a <tt>score</tt> attribute with the domain [0, 1], the height
* property could be specified as:
*
* <pre> .height(pv.Scale.linear().range(0, 480).by(function(d) d.score))</pre>
*
* This is equivalent to:
*
* <pre> .height(function(d) d.score * 480)</pre>
*
* This method should be used judiciously; it is typically more clear to
* invoke the scale directly, passing in the value to be scaled.
*
* @function
* @name pv.Scale.quantitative.prototype.by
* @param {function} f an accessor function.
* @returns {pv.Scale.quantitative} a view of this scale by the specified
* accessor function.
*/
scale.by = function (f) {
function by() {
return scale(f.apply(this, arguments));
}
for (var method in scale)
by[method] = scale[method];
return by;
};
scale.domain.apply(scale, arguments);
return scale;
};
/**
* Returns a linear scale for the specified domain. The arguments to this
* constructor are optional, and equivalent to calling {@link #domain}.
* The default domain and range are [0,1].
*
* @class Represents a linear scale; a function that performs a linear
* transformation. <style type="text/css">sub{line-height:0}</style> Most
* commonly, a linear scale represents a 1-dimensional linear transformation
* from a numeric domain of input data [<i>d<sub>0</sub></i>,
* <i>d<sub>1</sub></i>] to a numeric range of pixels [<i>r<sub>0</sub></i>,
* <i>r<sub>1</sub></i>]. The equation for such a scale is:
*
* <blockquote><i>f(x) = (x - d<sub>0</sub>) / (d<sub>1</sub> - d<sub>0</sub>) *
* (r<sub>1</sub> - r<sub>0</sub>) + r<sub>0</sub></i></blockquote>
*
* For example, a linear scale from the domain [0, 100] to range [0, 640]:
*
* <blockquote><i>f(x) = (x - 0) / (100 - 0) * (640 - 0) + 0</i><br>
* <i>f(x) = x / 100 * 640</i><br>
* <i>f(x) = x * 6.4</i><br>
* </blockquote>
*
* Thus, saying
*
* <pre> .height(function(d) d * 6.4)</pre>
*
* is identical to
*
* <pre> .height(pv.Scale.linear(0, 100).range(0, 640))</pre>
*
* Note that the scale is itself a function, and thus can be used as a property
* directly, assuming that the data associated with a mark is a number. While
* this is convenient for single-use scales, frequently it is desirable to
* define scales globally:
*
* <pre>var y = pv.Scale.linear(0, 100).range(0, 640);</pre>
*
* The <tt>y</tt> scale can now be equivalently referenced within a property:
*
* <pre> .height(function(d) y(d))</pre>
*
* Alternatively, if the data are not simple numbers, the appropriate value can
* be passed to the <tt>y</tt> scale (e.g., <tt>d.foo</tt>). The {@link #by}
* method similarly allows the data to be mapped to a numeric value before
* performing the linear transformation.
*
* @param {number...} domain... optional domain values.
* @extends pv.Scale.quantitative
*/
pv.Scale.linear = function () {
var scale = pv.Scale.quantitative();
scale.domain.apply(scale, arguments);
return scale;
};
/**
* Returns a log scale for the specified domain. The arguments to this
* constructor are optional, and equivalent to calling {@link #domain}.
* The default domain is [1,10] and the default range is [0,1].
*
* @class Represents a log scale. <style
* type="text/css">sub{line-height:0}</style> Most commonly, a log scale
* represents a 1-dimensional log transformation from a numeric domain of input
* data [<i>d<sub>0</sub></i>, <i>d<sub>1</sub></i>] to a numeric range of
* pixels [<i>r<sub>0</sub></i>, <i>r<sub>1</sub></i>]. The equation for such a
* scale is:
*
* <blockquote><i>f(x) = (log(x) - log(d<sub>0</sub>)) / (log(d<sub>1</sub>) -
* log(d<sub>0</sub>)) * (r<sub>1</sub> - r<sub>0</sub>) +
* r<sub>0</sub></i></blockquote>
*
* where <i>log(x)</i> represents the zero-symmetric logarthim of <i>x</i> using
* the scale's associated base (default: 10, see {@link pv.logSymmetric}). For
* example, a log scale from the domain [1, 100] to range [0, 640]:
*
* <blockquote><i>f(x) = (log(x) - log(1)) / (log(100) - log(1)) * (640 - 0) + 0</i><br>
* <i>f(x) = log(x) / 2 * 640</i><br>
* <i>f(x) = log(x) * 320</i><br>
* </blockquote>
*
* Thus, saying
*
* <pre> .height(function(d) Math.log(d) * 138.974)</pre>
*
* is equivalent to
*
* <pre> .height(pv.Scale.log(1, 100).range(0, 640))</pre>
*
* Note that the scale is itself a function, and thus can be used as a property
* directly, assuming that the data associated with a mark is a number. While
* this is convenient for single-use scales, frequently it is desirable to
* define scales globally:
*
* <pre>var y = pv.Scale.log(1, 100).range(0, 640);</pre>
*
* The <tt>y</tt> scale can now be equivalently referenced within a property:
*
* <pre> .height(function(d) y(d))</pre>
*
* Alternatively, if the data are not simple numbers, the appropriate value can
* be passed to the <tt>y</tt> scale (e.g., <tt>d.foo</tt>). The {@link #by}
* method similarly allows the data to be mapped to a numeric value before
* performing the log transformation.
*
* @param {number...} domain... optional domain values.
* @extends pv.Scale.quantitative
*/
pv.Scale.log = function () {
var scale = pv.Scale.quantitative(1, 10),
b, // logarithm base
p, // cached Math.log(b)
/** @ignore */ log = function (x) {
return Math.log(x) / p;
},
/** @ignore */ pow = function (y) {
return Math.pow(b, y);
};
/**
* Returns an array of evenly-spaced, suitably-rounded values in the input
* domain. These values are frequently used in conjunction with
* {@link pv.Rule} to display tick marks or grid lines.
*
* @function
* @name pv.Scale.log.prototype.ticks
* @returns {number[]} an array input domain values to use as ticks.
*/
scale.ticks = function () {
// TODO support non-uniform domains
var d = scale.domain(),
n = d[0] < 0,
i = Math.floor(n ? -log(-d[0]) : log(d[0])),
j = Math.ceil(n ? -log(-d[1]) : log(d[1])),
ticks = [];
if (n) {
ticks.push(-pow(-i));
for (; i++ < j; )
for (var k = b - 1; k > 0; k--)
ticks.push(-pow(-i) * k);
} else {
for (; i < j; i++)
for (var k = 1; k < b; k++)
ticks.push(pow(i) * k);
ticks.push(pow(i));
}
for (i = 0; ticks[i] < d[0]; i++)
; // strip small values
for (j = ticks.length; ticks[j - 1] > d[1]; j--)
; // strip big values
return ticks.slice(i, j);
};
/**
* Formats the specified tick value using the appropriate precision, assuming
* base 10.
*
* @function
* @name pv.Scale.log.prototype.tickFormat
* @param {number} t a tick value.
* @returns {string} a formatted tick value.
*/
scale.tickFormat = function (t) {
return t.toPrecision(1);
};
/**
* "Nices" this scale, extending the bounds of the input domain to
* evenly-rounded values. This method uses {@link pv.logFloor} and
* {@link pv.logCeil}. Nicing is useful if the domain is computed dynamically
* from data, and may be irregular. For example, given a domain of
* [0.20147987687960267, 0.996679553296417], a call to <tt>nice()</tt> might
* extend the domain to [0.1, 1].
*
* <p>This method must be invoked each time after setting the domain (and
* base).
*
* @function
* @name pv.Scale.log.prototype.nice
* @returns {pv.Scale.log} <tt>this</tt>.
*/
scale.nice = function () {
// TODO support non-uniform domains
var d = scale.domain();
return scale.domain(pv.logFloor(d[0], b), pv.logCeil(d[1], b));
};
/**
* Sets or gets the logarithm base. Defaults to 10.
*
* @function
* @name pv.Scale.log.prototype.base
* @param {number} [v] the new base.
* @returns {pv.Scale.log} <tt>this</tt>, or the current base.
*/
scale.base = function (v) {
if (arguments.length) {
b = Number(v);
p = Math.log(b);
scale.transform(log, pow); // update transformed domain
return this;
}
return b;
};
scale.domain.apply(scale, arguments);
return scale.base(10);
};
/**
* Returns a root scale for the specified domain. The arguments to this
* constructor are optional, and equivalent to calling {@link #domain}.
* The default domain and range are [0,1].
*
* @class Represents a root scale; a function that performs a power
* transformation. <style type="text/css">sub{line-height:0}</style> Most
* commonly, a root scale represents a 1-dimensional root transformation from a
* numeric domain of input data [<i>d<sub>0</sub></i>, <i>d<sub>1</sub></i>] to
* a numeric range of pixels [<i>r<sub>0</sub></i>, <i>r<sub>1</sub></i>].
*
* <p>Note that the scale is itself a function, and thus can be used as a
* property directly, assuming that the data associated with a mark is a
* number. While this is convenient for single-use scales, frequently it is
* desirable to define scales globally:
*
* <pre>var y = pv.Scale.root(0, 100).range(0, 640);</pre>
*
* The <tt>y</tt> scale can now be equivalently referenced within a property:
*
* <pre> .height(function(d) y(d))</pre>
*
* Alternatively, if the data are not simple numbers, the appropriate value can
* be passed to the <tt>y</tt> scale (e.g., <tt>d.foo</tt>). The {@link #by}
* method similarly allows the data to be mapped to a numeric value before
* performing the root transformation.
*
* @param {number...} domain... optional domain values.
* @extends pv.Scale.quantitative
*/
pv.Scale.root = function () {
var scale = pv.Scale.quantitative();
/**
* Sets or gets the exponent; defaults to 2.
*
* @function
* @name pv.Scale.root.prototype.power
* @param {number} [v] the new exponent.
* @returns {pv.Scale.root} <tt>this</tt>, or the current base.
*/
scale.power = function (v) {
if (arguments.length) {
var b = Number(v), p = 1 / b;
scale.transform(
function (x) {
return Math.pow(x, p);
},
function (y) {
return Math.pow(y, b);
});
return this;
}
return b;
};
scale.domain.apply(scale, arguments);
return scale.power(2);
};
/**
* Returns an ordinal scale for the specified domain. The arguments to this
* constructor are optional, and equivalent to calling {@link #domain}.
*
* @class Represents an ordinal scale. <style
* type="text/css">sub{line-height:0}</style> An ordinal scale represents a
* pairwise mapping from <i>n</i> discrete values in the input domain to
* <i>n</i> discrete values in the output range. For example, an ordinal scale
* might map a domain of species ["setosa", "versicolor", "virginica"] to colors
* ["red", "green", "blue"]. Thus, saying
*
* <pre> .fillStyle(function(d) {
* switch (d.species) {
* case "setosa": return "red";
* case "versicolor": return "green";
* case "virginica": return "blue";
* }
* })</pre>
*
* is equivalent to
*
* <pre> .fillStyle(pv.Scale.ordinal("setosa", "versicolor", "virginica")
* .range("red", "green", "blue")
* .by(function(d) d.species))</pre>
*
* If the mapping from species to color does not need to be specified
* explicitly, the domain can be omitted. In this case it will be inferred
* lazily from the data:
*
* <pre> .fillStyle(pv.colors("red", "green", "blue")
* .by(function(d) d.species))</pre>
*
* When the domain is inferred, the first time the scale is invoked, the first
* element from the range will be returned. Subsequent calls with unique values
* will return subsequent elements from the range. If the inferred domain grows
* larger than the range, range values will be reused. However, it is strongly
* recommended that the domain and the range contain the same number of
* elements.
*
* <p>A range can be discretized from a continuous interval (e.g., for pixel
* positioning) by using {@link #split}, {@link #splitFlush} or
* {@link #splitBanded} after the domain has been set. For example, if
* <tt>states</tt> is an array of the fifty U.S. state names, the state name can
* be encoded in the left position:
*
* <pre> .left(pv.Scale.ordinal(states)
* .split(0, 640)
* .by(function(d) d.state))</pre>
*
* <p>N.B.: ordinal scales are not invertible (at least not yet), since the
* domain and range and discontinuous. A workaround is to use a linear scale.
*
* @param {...} domain... optional domain values.
* @extends pv.Scale
* @see pv.colors
*/
pv.Scale.ordinal = function () {
var d = [], i = {}, r = [], band = 0;
/** @private */
function scale(x) {
if (!(x in i))
i[x] = d.push(x) - 1;
return r[i[x] % r.length];
}
/**
* Sets or gets the input domain. This method can be invoked several ways:
*
* <p>1. <tt>domain(values...)</tt>
*
* <p>Specifying the domain as a series of values is the most explicit and
* recommended approach. However, if the domain values are derived from data,
* you may find the second method more appropriate.
*
* <p>2. <tt>domain(array, f)</tt>
*
* <p>Rather than enumerating the domain values as explicit arguments to this
* method, you can specify a single argument of an array. In addition, you can
* specify an optional accessor function to extract the domain values from the
* array.
*
* <p>3. <tt>domain()</tt>
*
* <p>Invoking the <tt>domain</tt> method with no arguments returns the
* current domain as an array.
*
* @function
* @name pv.Scale.ordinal.prototype.domain
* @param {...} domain... domain values.
* @returns {pv.Scale.ordinal} <tt>this</tt>, or the current domain.
*/
scale.domain = function (array, f) {
if (arguments.length) {
array = (array instanceof Array)
? ((arguments.length > 1) ? pv.map(array, f) : array)
: Array.prototype.slice.call(arguments);
/* Filter the specified ordinals to their unique values. */
d = [];
var seen = {};
for (var j = 0; j < array.length; j++) {
var o = array[j];
if (!(o in seen)) {
seen[o] = true;
d.push(o);
}
}
i = pv.numerate(d);
return this;
}
return d;
};
/**
* Sets or gets the output range. This method can be invoked several ways:
*
* <p>1. <tt>range(values...)</tt>
*
* <p>Specifying the range as a series of values is the most explicit and
* recommended approach. However, if the range values are derived from data,
* you may find the second method more appropriate.
*
* <p>2. <tt>range(array, f)</tt>
*
* <p>Rather than enumerating the range values as explicit arguments to this
* method, you can specify a single argument of an array. In addition, you can
* specify an optional accessor function to extract the range values from the
* array.
*
* <p>3. <tt>range()</tt>
*
* <p>Invoking the <tt>range</tt> method with no arguments returns the
* current range as an array.
*
* @function
* @name pv.Scale.ordinal.prototype.range
* @param {...} range... range values.
* @returns {pv.Scale.ordinal} <tt>this</tt>, or the current range.
*/
scale.range = function (array, f) {
if (arguments.length) {
r = (array instanceof Array)
? ((arguments.length > 1) ? pv.map(array, f) : array)
: Array.prototype.slice.call(arguments);
if (typeof r[0] == "string")
r = r.map(pv.color);
return this;
}
return r;
};
/**
* Sets the range from the given continuous interval. The interval
* [<i>min</i>, <i>max</i>] is subdivided into <i>n</i> equispaced points,
* where <i>n</i> is the number of (unique) values in the domain. The first
* and last point are offset from the edge of the range by half the distance
* between points.
*
* <p>This method must be called <i>after</i> the domain is set.
*
* @function
* @name pv.Scale.ordinal.prototype.split
* @param {number} min minimum value of the output range.
* @param {number} max maximum value of the output range.
* @returns {pv.Scale.ordinal} <tt>this</tt>.
* @see #splitFlush
* @see #splitBanded
*/
scale.split = function (min, max) {
var step = (max - min) / this.domain().length;
r = pv.range(min + step / 2, max, step);
return this;
};
/**
* Sets the range from the given continuous interval. The interval
* [<i>min</i>, <i>max</i>] is subdivided into <i>n</i> equispaced points,
* where <i>n</i> is the number of (unique) values in the domain. The first
* and last point are exactly on the edge of the range.
*
* <p>This method must be called <i>after</i> the domain is set.
*
* @function
* @name pv.Scale.ordinal.prototype.splitFlush
* @param {number} min minimum value of the output range.
* @param {number} max maximum value of the output range.
* @returns {pv.Scale.ordinal} <tt>this</tt>.
* @see #split
*/
scale.splitFlush = function (min, max) {
var n = this.domain().length, step = (max - min) / (n - 1);
r = (n == 1) ? [(min + max) / 2]
: pv.range(min, max + step / 2, step);
return this;
};
/**
* Sets the range from the given continuous interval. The interval
* [<i>min</i>, <i>max</i>] is subdivided into <i>n</i> equispaced bands,
* where <i>n</i> is the number of (unique) values in the domain. The first
* and last band are offset from the edge of the range by the distance between
* bands.
*
* <p>The band width argument, <tt>band</tt>, is typically in the range [0, 1]
* and defaults to 1. This fraction corresponds to the amount of space in the
* range to allocate to the bands, as opposed to padding. A value of 0.5 means
* that the band width will be equal to the padding width. The computed
* absolute band width can be retrieved from the range as
* <tt>scale.range().band</tt>.
*
* <p>If the band width argument is negative, this method will allocate bands
* of a <i>fixed</i> width <tt>-band</tt>, rather than a relative fraction of
* the available space.
*
* <p>Tip: to inset the bands by a fixed amount <tt>p</tt>, specify a minimum
* value of <tt>min + p</tt> (or simply <tt>p</tt>, if <tt>min</tt> is
* 0). Then set the mark width to <tt>scale.range().band - p</tt>.
*
* <p>This method must be called <i>after</i> the domain is set.
*
* @function
* @name pv.Scale.ordinal.prototype.splitBanded
* @param {number} min minimum value of the output range.
* @param {number} max maximum value of the output range.
* @param {number} [band] the fractional band width in [0, 1]; defaults to 1.
* @returns {pv.Scale.ordinal} <tt>this</tt>.
* @see #split
*/
scale.splitBanded = function (min, max, band) {
if (arguments.length < 3)
band = 1;
if (band < 0) {
var n = this.domain().length,
total = -band * n,
remaining = max - min - total,
padding = remaining / (n + 1);
r = pv.range(min + padding, max, padding - band);
r.band = -band;
} else {
var step = (max - min) / (this.domain().length + (1 - band));
r = pv.range(min + step * (1 - band), max, step);
r.band = step * band;
}
return this;
};
/**
* Returns a view of this scale by the specified accessor function <tt>f</tt>.
* Given a scale <tt>y</tt>, <tt>y.by(function(d) d.foo)</tt> is equivalent to
* <tt>function(d) y(d.foo)</tt>. This method should be used judiciously; it
* is typically more clear to invoke the scale directly, passing in the value
* to be scaled.
*
* @function
* @name pv.Scale.ordinal.prototype.by
* @param {function} f an accessor function.
* @returns {pv.Scale.ordinal} a view of this scale by the specified accessor
* function.
*/
scale.by = function (f) {
function by() {
return scale(f.apply(this, arguments));
}
for (var method in scale)
by[method] = scale[method];
return by;
};
scale.domain.apply(scale, arguments);
return scale;
};
/**
* Constructs a default quantile scale. The arguments to this constructor are
* optional, and equivalent to calling {@link #domain}. The default domain is
* the empty set, and the default range is [0,1].
*
* @class Represents a quantile scale; a function that maps from a value within
* a sortable domain to a quantized numeric range. Typically, the domain is a
* set of numbers, but any sortable value (such as strings) can be used as the
* domain of a quantile scale. The range defaults to [0,1], with 0 corresponding
* to the smallest value in the domain, 1 the largest, .5 the median, etc.
*
* <p>By default, the number of quantiles in the range corresponds to the number
* of values in the domain. The {@link #quantiles} method can be used to specify
* an explicit number of quantiles; for example, <tt>quantiles(4)</tt> produces
* a standard quartile scale. A quartile scale's range is a set of four discrete
* values, such as [0, 1/3, 2/3, 1]. Calling the {@link #range} method will
* scale these discrete values accordingly, similar to {@link
* pv.Scale.ordinal#splitFlush}.
*
* <p>For example, given the strings ["c", "a", "b"], a default quantile scale:
*
* <pre>pv.Scale.quantile("c", "a", "b")</pre>
*
* will return 0 for "a", .5 for "b", and 1 for "c".
*
* @extends pv.Scale
*/
pv.Scale.quantile = function () {
var n = -1, // number of quantiles
j = -1, // max quantile index
q = [], // quantile boundaries
d = [], // domain
y = pv.Scale.linear(); // range
/** @private */
function scale(x) {
return y(Math.max(0, Math.min(j, pv.search.index(q, x) - 1)) / j);
}
/**
* Sets or gets the quantile boundaries. By default, each element in the
* domain is in its own quantile. If the argument to this method is a number,
* it specifies the number of equal-sized quantiles by which to divide the
* domain.
*
* <p>If no arguments are specified, this method returns the quantile
* boundaries; the first element is always the minimum value of the domain,
* and the last element is the maximum value of the domain. Thus, the length
* of the returned array is always one greater than the number of quantiles.
*
* @function
* @name pv.Scale.quantile.prototype.quantiles
* @param {number} x the number of quantiles.
*/
scale.quantiles = function (x) {
if (arguments.length) {
n = Number(x);
if (n < 0) {
q = [d[0]].concat(d);
j = d.length - 1;
} else {
q = [];
q[0] = d[0];
for (var i = 1; i <= n; i++) {
q[i] = d[~~(i * (d.length - 1) / n)];
}
j = n - 1;
}
return this;
}
return q;
};
/**
* Sets or gets the input domain. This method can be invoked several ways:
*
* <p>1. <tt>domain(values...)</tt>
*
* <p>Specifying the domain as a series of values is the most explicit and
* recommended approach. However, if the domain values are derived from data,
* you may find the second method more appropriate.
*
* <p>2. <tt>domain(array, f)</tt>
*
* <p>Rather than enumerating the domain values as explicit arguments to this
* method, you can specify a single argument of an array. In addition, you can
* specify an optional accessor function to extract the domain values from the
* array.
*
* <p>3. <tt>domain()</tt>
*
* <p>Invoking the <tt>domain</tt> method with no arguments returns the
* current domain as an array.
*
* @function
* @name pv.Scale.quantile.prototype.domain
* @param {...} domain... domain values.
* @returns {pv.Scale.quantile} <tt>this</tt>, or the current domain.
*/
scale.domain = function (array, f) {
if (arguments.length) {
d = (array instanceof Array)
? pv.map(array, f)
: Array.prototype.slice.call(arguments);
d.sort(pv.naturalOrder);
scale.quantiles(n); // recompute quantiles
return this;
}
return d;
};
/**
* Sets or gets the output range. This method can be invoked several ways:
*
* <p>1. <tt>range(min, ..., max)</tt>
*
* <p>The range may be specified as a series of numbers or colors. Most
* commonly, two numbers are specified: the minimum and maximum pixel values.
* For a color scale, values may be specified as {@link pv.Color}s or
* equivalent strings. For a diverging scale, or other subdivided non-uniform
* scales, multiple values can be specified. For example:
*
* <pre> .range("red", "white", "green")</pre>
*
* <p>Currently, only numbers and colors are supported as range values. The
* number of range values must exactly match the number of domain values, or
* the behavior of the scale is undefined.
*
* <p>2. <tt>range()</tt>
*
* <p>Invoking the <tt>range</tt> method with no arguments returns the current
* range as an array of numbers or colors.
*
* @function
* @name pv.Scale.quantile.prototype.range
* @param {...} range... range values.
* @returns {pv.Scale.quantile} <tt>this</tt>, or the current range.
*/
scale.range = function () {
if (arguments.length) {
y.range.apply(y, arguments);
return this;
}
return y.range();
};
/**
* Returns a view of this scale by the specified accessor function <tt>f</tt>.
* Given a scale <tt>y</tt>, <tt>y.by(function(d) d.foo)</tt> is equivalent to
* <tt>function(d) y(d.foo)</tt>.
*
* <p>This method is provided for convenience, such that scales can be
* succinctly defined inline. For example, given an array of data elements
* that have a <tt>score</tt> attribute with the domain [0, 1], the height
* property could be specified as:
*
* <pre>.height(pv.Scale.linear().range(0, 480).by(function(d) d.score))</pre>
*
* This is equivalent to:
*
* <pre>.height(function(d) d.score * 480)</pre>
*
* This method should be used judiciously; it is typically more clear to
* invoke the scale directly, passing in the value to be scaled.
*
* @function
* @name pv.Scale.quantile.prototype.by
* @param {function} f an accessor function.
* @returns {pv.Scale.quantile} a view of this scale by the specified
* accessor function.
*/
scale.by = function (f) {
function by() {
return scale(f.apply(this, arguments));
}
for (var method in scale)
by[method] = scale[method];
return by;
};
scale.domain.apply(scale, arguments);
return scale;
};
/**
* Returns a histogram operator for the specified data, with an optional
* accessor function. If the data specified is not an array of numbers, an
* accessor function must be specified to map the data to numeric values.
*
* @class Represents a histogram operator.
*
* @param {array} data an array of numbers or objects.
* @param {function} [f] an optional accessor function.
*/
pv.histogram = function (data, f) {
var frequency = true;
return {
/**
* Returns the computed histogram bins. An optional array of numbers,
* <tt>ticks</tt>, may be specified as the break points. If the ticks are
* not specified, default ticks will be computed using a linear scale on the
* data domain.
*
* <p>The returned array contains {@link pv.histogram.Bin}s. The <tt>x</tt>
* attribute corresponds to the bin's start value (inclusive), while the
* <tt>dx</tt> attribute stores the bin size (end - start). The <tt>y</tt>
* attribute stores either the frequency count or probability, depending on
* how the histogram operator has been configured.
*
* <p>The {@link pv.histogram.Bin} objects are themselves arrays, containing
* the data elements present in each bin, i.e., the elements in the
* <tt>data</tt> array (prior to invoking the accessor function, if any).
* For example, if the data represented countries, and the accessor function
* returned the GDP of each country, the returned bins would be arrays of
* countries (not GDPs).
*
* @function
* @name pv.histogram.prototype.bins
* @param {array} [ticks]
* @returns {array}
*/ /** @private */
bins: function (ticks) {
var x = pv.map(data, f), bins = [];
/* Initialize default ticks. */
if (!arguments.length)
ticks = pv.Scale.linear(x).ticks();
/* Initialize the bins. */
for (var i = 0; i < ticks.length - 1; i++) {
var bin = bins[i] = [];
bin.x = ticks[i];
bin.dx = ticks[i + 1] - ticks[i];
bin.y = 0;
}
/* Count the number of samples per bin. */
for (var i = 0; i < x.length; i++) {
var j = pv.search.index(ticks, x[i]) - 1,
bin = bins[Math.max(0, Math.min(bins.length - 1, j))];
bin.y++;
bin.push(data[i]);
}
/* Convert frequencies to probabilities. */
if (!frequency)
for (var i = 0; i < bins.length; i++) {
bins[i].y /= x.length;
}
return bins;
},
/**
* Sets or gets whether this histogram operator returns frequencies or
* probabilities.
*
* @function
* @name pv.histogram.prototype.frequency
* @param {boolean} [x]
* @returns {pv.histogram} this.
*/ /** @private */
frequency: function (x) {
if (arguments.length) {
frequency = Boolean(x);
return this;
}
return frequency;
}
};
};
/**
* @class Represents a bin returned by the {@link pv.histogram} operator. Bins
* are themselves arrays containing the data elements present in the given bin
* (prior to the accessor function being invoked to convert the data object to a
* numeric value). These bin arrays have additional attributes with meta
* information about the bin.
*
* @name pv.histogram.Bin
* @extends array
* @see pv.histogram
*/
/**
* The start value of the bin's range.
*
* @type number
* @name pv.histogram.Bin.prototype.x
*/
/**
* The magnitude value of the bin's range; end - start.
*
* @type number
* @name pv.histogram.Bin.prototype.dx
*/
/**
* The frequency or probability of the bin, depending on how the histogram
* operator was configured.
*
* @type number
* @name pv.histogram.Bin.prototype.y
*/
/**
* Returns the {@link pv.Color} for the specified color format string. Colors
* may have an associated opacity, or alpha channel. Color formats are specified
* by CSS Color Modular Level 3, using either in RGB or HSL color space. For
* example:<ul>
*
* <li>#f00 // #rgb
* <li>#ff0000 // #rrggbb
* <li>rgb(255, 0, 0)
* <li>rgb(100%, 0%, 0%)
* <li>hsl(0, 100%, 50%)
* <li>rgba(0, 0, 255, 0.5)
* <li>hsla(120, 100%, 50%, 1)
*
* </ul>The SVG 1.0 color keywords names are also supported, such as "aliceblue"
* and "yellowgreen". The "transparent" keyword is supported for fully-
* transparent black.
*
* <p>If the <tt>format</tt> argument is already an instance of <tt>Color</tt>,
* the argument is returned with no further processing.
*
* @param {string} format the color specification string, such as "#f00".
* @returns {pv.Color} the corresponding <tt>Color</tt>.
* @see <a href="http://www.w3.org/TR/SVG/types.html#ColorKeywords">SVG color
* keywords</a>
* @see <a href="http://www.w3.org/TR/css3-color/">CSS3 color module</a>
*/
pv.color = function (format) {
if (format.rgb)
return format.rgb();
/* Handle hsl, rgb. */
var m1 = /([a-z]+)\((.*)\)/i.exec(format);
if (m1) {
var m2 = m1[2].split(","), a = 1;
switch (m1[1]) {
case "hsla":
case "rgba":
{
a = parseFloat(m2[3]);
if (!a)
return pv.Color.transparent;
break;
}
}
switch (m1[1]) {
case "hsla":
case "hsl":
{
var h = parseFloat(m2[0]), // degrees
s = parseFloat(m2[1]) / 100, // percentage
l = parseFloat(m2[2]) / 100; // percentage
return (new pv.Color.Hsl(h, s, l, a)).rgb();
}
case "rgba":
case "rgb":
{
function parse(c) { // either integer or percentage
var f = parseFloat(c);
return (c[c.length - 1] == '%') ? Math.round(f * 2.55) : f;
}
var r = parse(m2[0]), g = parse(m2[1]), b = parse(m2[2]);
return pv.rgb(r, g, b, a);
}
}
}
/* Named colors. */
var named = pv.Color.names[format];
if (named)
return named;
/* Hexadecimal colors: #rgb and #rrggbb. */
if (format.charAt(0) == "#") {
var r, g, b;
if (format.length == 4) {
r = format.charAt(1);
r += r;
g = format.charAt(2);
g += g;
b = format.charAt(3);
b += b;
} else if (format.length == 7) {
r = format.substring(1, 3);
g = format.substring(3, 5);
b = format.substring(5, 7);
}
return pv.rgb(parseInt(r, 16), parseInt(g, 16), parseInt(b, 16), 1);
}
/* Otherwise, pass-through unsupported colors. */
return new pv.Color(format, 1);
};
/**
* Constructs a color with the specified color format string and opacity. This
* constructor should not be invoked directly; use {@link pv.color} instead.
*
* @class Represents an abstract (possibly translucent) color. The color is
* divided into two parts: the <tt>color</tt> attribute, an opaque color format
* string, and the <tt>opacity</tt> attribute, a float in [0, 1]. The color
* space is dependent on the implementing class; all colors support the
* {@link #rgb} method to convert to RGB color space for interpolation.
*
* <p>See also the <a href="../../api/Color.html">Color guide</a>.
*
* @param {string} color an opaque color format string, such as "#f00".
* @param {number} opacity the opacity, in [0,1].
* @see pv.color
*/
pv.Color = function (color, opacity) {
/**
* An opaque color format string, such as "#f00".
*
* @type string
* @see <a href="http://www.w3.org/TR/SVG/types.html#ColorKeywords">SVG color
* keywords</a>
* @see <a href="http://www.w3.org/TR/css3-color/">CSS3 color module</a>
*/
this.color = color;
/**
* The opacity, a float in [0, 1].
*
* @type number
*/
this.opacity = opacity;
};
/**
* Returns a new color that is a brighter version of this color. The behavior of
* this method may vary slightly depending on the underlying color space.
* Although brighter and darker are inverse operations, the results of a series
* of invocations of these two methods might be inconsistent because of rounding
* errors.
*
* @param [k] {number} an optional scale factor; defaults to 1.
* @see #darker
* @returns {pv.Color} a brighter color.
*/
pv.Color.prototype.brighter = function (k) {
return this.rgb().brighter(k);
};
/**
* Returns a new color that is a brighter version of this color. The behavior of
* this method may vary slightly depending on the underlying color space.
* Although brighter and darker are inverse operations, the results of a series
* of invocations of these two methods might be inconsistent because of rounding
* errors.
*
* @param [k] {number} an optional scale factor; defaults to 1.
* @see #brighter
* @returns {pv.Color} a darker color.
*/
pv.Color.prototype.darker = function (k) {
return this.rgb().darker(k);
};
/**
* Constructs a new RGB color with the specified channel values.
*
* @param {number} r the red channel, an integer in [0,255].
* @param {number} g the green channel, an integer in [0,255].
* @param {number} b the blue channel, an integer in [0,255].
* @param {number} [a] the alpha channel, a float in [0,1].
* @returns pv.Color.Rgb
*/
pv.rgb = function (r, g, b, a) {
return new pv.Color.Rgb(r, g, b, (arguments.length == 4) ? a : 1);
};
/**
* Constructs a new RGB color with the specified channel values.
*
* @class Represents a color in RGB space.
*
* @param {number} r the red channel, an integer in [0,255].
* @param {number} g the green channel, an integer in [0,255].
* @param {number} b the blue channel, an integer in [0,255].
* @param {number} a the alpha channel, a float in [0,1].
* @extends pv.Color
*/
pv.Color.Rgb = function (r, g, b, a) {
pv.Color.call(this, a ? ("rgb(" + r + "," + g + "," + b + ")") : "none", a);
/**
* The red channel, an integer in [0, 255].
*
* @type number
*/
this.r = r;
/**
* The green channel, an integer in [0, 255].
*
* @type number
*/
this.g = g;
/**
* The blue channel, an integer in [0, 255].
*
* @type number
*/
this.b = b;
/**
* The alpha channel, a float in [0, 1].
*
* @type number
*/
this.a = a;
};
pv.Color.Rgb.prototype = pv.extend(pv.Color);
/**
* Constructs a new RGB color with the same green, blue and alpha channels as
* this color, with the specified red channel.
*
* @param {number} r the red channel, an integer in [0,255].
*/
pv.Color.Rgb.prototype.red = function (r) {
return pv.rgb(r, this.g, this.b, this.a);
};
/**
* Constructs a new RGB color with the same red, blue and alpha channels as this
* color, with the specified green channel.
*
* @param {number} g the green channel, an integer in [0,255].
*/
pv.Color.Rgb.prototype.green = function (g) {
return pv.rgb(this.r, g, this.b, this.a);
};
/**
* Constructs a new RGB color with the same red, green and alpha channels as
* this color, with the specified blue channel.
*
* @param {number} b the blue channel, an integer in [0,255].
*/
pv.Color.Rgb.prototype.blue = function (b) {
return pv.rgb(this.r, this.g, b, this.a);
};
/**
* Constructs a new RGB color with the same red, green and blue channels as this
* color, with the specified alpha channel.
*
* @param {number} a the alpha channel, a float in [0,1].
*/
pv.Color.Rgb.prototype.alpha = function (a) {
return pv.rgb(this.r, this.g, this.b, a);
};
/**
* Returns the RGB color equivalent to this color. This method is abstract and
* must be implemented by subclasses.
*
* @returns {pv.Color.Rgb} an RGB color.
* @function
* @name pv.Color.prototype.rgb
*/
/**
* Returns this.
*
* @returns {pv.Color.Rgb} this.
*/
pv.Color.Rgb.prototype.rgb = function () {
return this;
};
/**
* Returns a new color that is a brighter version of this color. This method
* applies an arbitrary scale factor to each of the three RGB components of this
* color to create a brighter version of this color. Although brighter and
* darker are inverse operations, the results of a series of invocations of
* these two methods might be inconsistent because of rounding errors.
*
* @param [k] {number} an optional scale factor; defaults to 1.
* @see #darker
* @returns {pv.Color.Rgb} a brighter color.
*/
pv.Color.Rgb.prototype.brighter = function (k) {
k = Math.pow(0.7, arguments.length ? k : 1);
var r = this.r, g = this.g, b = this.b, i = 30;
if (!r && !g && !b)
return pv.rgb(i, i, i, this.a);
if (r && (r < i))
r = i;
if (g && (g < i))
g = i;
if (b && (b < i))
b = i;
return pv.rgb(
Math.min(255, Math.floor(r / k)),
Math.min(255, Math.floor(g / k)),
Math.min(255, Math.floor(b / k)),
this.a);
};
/**
* Returns a new color that is a darker version of this color. This method
* applies an arbitrary scale factor to each of the three RGB components of this
* color to create a darker version of this color. Although brighter and darker
* are inverse operations, the results of a series of invocations of these two
* methods might be inconsistent because of rounding errors.
*
* @param [k] {number} an optional scale factor; defaults to 1.
* @see #brighter
* @returns {pv.Color.Rgb} a darker color.
*/
pv.Color.Rgb.prototype.darker = function (k) {
k = Math.pow(0.7, arguments.length ? k : 1);
return pv.rgb(
Math.max(0, Math.floor(k * this.r)),
Math.max(0, Math.floor(k * this.g)),
Math.max(0, Math.floor(k * this.b)),
this.a);
};
/**
* Constructs a new HSL color with the specified values.
*
* @param {number} h the hue, an integer in [0, 360].
* @param {number} s the saturation, a float in [0, 1].
* @param {number} l the lightness, a float in [0, 1].
* @param {number} [a] the opacity, a float in [0, 1].
* @returns pv.Color.Hsl
*/
pv.hsl = function (h, s, l, a) {
return new pv.Color.Hsl(h, s, l, (arguments.length == 4) ? a : 1);
};
/**
* Constructs a new HSL color with the specified values.
*
* @class Represents a color in HSL space.
*
* @param {number} h the hue, an integer in [0, 360].
* @param {number} s the saturation, a float in [0, 1].
* @param {number} l the lightness, a float in [0, 1].
* @param {number} a the opacity, a float in [0, 1].
* @extends pv.Color
*/
pv.Color.Hsl = function (h, s, l, a) {
pv.Color.call(this, "hsl(" + h + "," + (s * 100) + "%," + (l * 100) + "%)", a);
/**
* The hue, an integer in [0, 360].
*
* @type number
*/
this.h = h;
/**
* The saturation, a float in [0, 1].
*
* @type number
*/
this.s = s;
/**
* The lightness, a float in [0, 1].
*
* @type number
*/
this.l = l;
/**
* The opacity, a float in [0, 1].
*
* @type number
*/
this.a = a;
};
pv.Color.Hsl.prototype = pv.extend(pv.Color);
/**
* Constructs a new HSL color with the same saturation, lightness and alpha as
* this color, and the specified hue.
*
* @param {number} h the hue, an integer in [0, 360].
*/
pv.Color.Hsl.prototype.hue = function (h) {
return pv.hsl(h, this.s, this.l, this.a);
};
/**
* Constructs a new HSL color with the same hue, lightness and alpha as this
* color, and the specified saturation.
*
* @param {number} s the saturation, a float in [0, 1].
*/
pv.Color.Hsl.prototype.saturation = function (s) {
return pv.hsl(this.h, s, this.l, this.a);
};
/**
* Constructs a new HSL color with the same hue, saturation and alpha as this
* color, and the specified lightness.
*
* @param {number} l the lightness, a float in [0, 1].
*/
pv.Color.Hsl.prototype.lightness = function (l) {
return pv.hsl(this.h, this.s, l, this.a);
};
/**
* Constructs a new HSL color with the same hue, saturation and lightness as
* this color, and the specified alpha.
*
* @param {number} a the opacity, a float in [0, 1].
*/
pv.Color.Hsl.prototype.alpha = function (a) {
return pv.hsl(this.h, this.s, this.l, a);
};
/**
* Returns the RGB color equivalent to this HSL color.
*
* @returns {pv.Color.Rgb} an RGB color.
*/
pv.Color.Hsl.prototype.rgb = function () {
var h = this.h, s = this.s, l = this.l;
/* Some simple corrections for h, s and l. */
h = h % 360;
if (h < 0)
h += 360;
s = Math.max(0, Math.min(s, 1));
l = Math.max(0, Math.min(l, 1));
/* From FvD 13.37, CSS Color Module Level 3 */
var m2 = (l <= .5) ? (l * (1 + s)) : (l + s - l * s);
var m1 = 2 * l - m2;
function v(h) {
if (h > 360)
h -= 360;
else if (h < 0)
h += 360;
if (h < 60)
return m1 + (m2 - m1) * h / 60;
if (h < 180)
return m2;
if (h < 240)
return m1 + (m2 - m1) * (240 - h) / 60;
return m1;
}
function vv(h) {
return Math.round(v(h) * 255);
}
return pv.rgb(vv(h + 120), vv(h), vv(h - 120), this.a);
};
/**
* @private SVG color keywords, per CSS Color Module Level 3.
*
* @see <a href="http://www.w3.org/TR/SVG/types.html#ColorKeywords">SVG color
* keywords</a>
*/
pv.Color.names = {
aliceblue: "#f0f8ff",
antiquewhite: "#faebd7",
aqua: "#00ffff",
aquamarine: "#7fffd4",
azure: "#f0ffff",
beige: "#f5f5dc",
bisque: "#ffe4c4",
black: "#000000",
blanchedalmond: "#ffebcd",
blue: "#0000ff",
blueviolet: "#8a2be2",
brown: "#a52a2a",
burlywood: "#deb887",
cadetblue: "#5f9ea0",
chartreuse: "#7fff00",
chocolate: "#d2691e",
coral: "#ff7f50",
cornflowerblue: "#6495ed",
cornsilk: "#fff8dc",
crimson: "#dc143c",
cyan: "#00ffff",
darkblue: "#00008b",
darkcyan: "#008b8b",
darkgoldenrod: "#b8860b",
darkgray: "#a9a9a9",
darkgreen: "#006400",
darkgrey: "#a9a9a9",
darkkhaki: "#bdb76b",
darkmagenta: "#8b008b",
darkolivegreen: "#556b2f",
darkorange: "#ff8c00",
darkorchid: "#9932cc",
darkred: "#8b0000",
darksalmon: "#e9967a",
darkseagreen: "#8fbc8f",
darkslateblue: "#483d8b",
darkslategray: "#2f4f4f",
darkslategrey: "#2f4f4f",
darkturquoise: "#00ced1",
darkviolet: "#9400d3",
deeppink: "#ff1493",
deepskyblue: "#00bfff",
dimgray: "#696969",
dimgrey: "#696969",
dodgerblue: "#1e90ff",
firebrick: "#b22222",
floralwhite: "#fffaf0",
forestgreen: "#228b22",
fuchsia: "#ff00ff",
gainsboro: "#dcdcdc",
ghostwhite: "#f8f8ff",
gold: "#ffd700",
goldenrod: "#daa520",
gray: "#808080",
green: "#008000",
greenyellow: "#adff2f",
grey: "#808080",
honeydew: "#f0fff0",
hotpink: "#ff69b4",
indianred: "#cd5c5c",
indigo: "#4b0082",
ivory: "#fffff0",
khaki: "#f0e68c",
lavender: "#e6e6fa",
lavenderblush: "#fff0f5",
lawngreen: "#7cfc00",
lemonchiffon: "#fffacd",
lightblue: "#add8e6",
lightcoral: "#f08080",
lightcyan: "#e0ffff",
lightgoldenrodyellow: "#fafad2",
lightgray: "#d3d3d3",
lightgreen: "#90ee90",
lightgrey: "#d3d3d3",
lightpink: "#ffb6c1",
lightsalmon: "#ffa07a",
lightseagreen: "#20b2aa",
lightskyblue: "#87cefa",
lightslategray: "#778899",
lightslategrey: "#778899",
lightsteelblue: "#b0c4de",
lightyellow: "#ffffe0",
lime: "#00ff00",
limegreen: "#32cd32",
linen: "#faf0e6",
magenta: "#ff00ff",
maroon: "#800000",
mediumaquamarine: "#66cdaa",
mediumblue: "#0000cd",
mediumorchid: "#ba55d3",
mediumpurple: "#9370db",
mediumseagreen: "#3cb371",
mediumslateblue: "#7b68ee",
mediumspringgreen: "#00fa9a",
mediumturquoise: "#48d1cc",
mediumvioletred: "#c71585",
midnightblue: "#191970",
mintcream: "#f5fffa",
mistyrose: "#ffe4e1",
moccasin: "#ffe4b5",
navajowhite: "#ffdead",
navy: "#000080",
oldlace: "#fdf5e6",
olive: "#808000",
olivedrab: "#6b8e23",
orange: "#ffa500",
orangered: "#ff4500",
orchid: "#da70d6",
palegoldenrod: "#eee8aa",
palegreen: "#98fb98",
paleturquoise: "#afeeee",
palevioletred: "#db7093",
papayawhip: "#ffefd5",
peachpuff: "#ffdab9",
peru: "#cd853f",
pink: "#ffc0cb",
plum: "#dda0dd",
powderblue: "#b0e0e6",
purple: "#800080",
red: "#ff0000",
rosybrown: "#bc8f8f",
royalblue: "#4169e1",
saddlebrown: "#8b4513",
salmon: "#fa8072",
sandybrown: "#f4a460",
seagreen: "#2e8b57",
seashell: "#fff5ee",
sienna: "#a0522d",
silver: "#c0c0c0",
skyblue: "#87ceeb",
slateblue: "#6a5acd",
slategray: "#708090",
slategrey: "#708090",
snow: "#fffafa",
springgreen: "#00ff7f",
steelblue: "#4682b4",
tan: "#d2b48c",
teal: "#008080",
thistle: "#d8bfd8",
tomato: "#ff6347",
turquoise: "#40e0d0",
violet: "#ee82ee",
wheat: "#f5deb3",
white: "#ffffff",
whitesmoke: "#f5f5f5",
yellow: "#ffff00",
yellowgreen: "#9acd32",
transparent: pv.Color.transparent = pv.rgb(0, 0, 0, 0)
};
/* Initialized named colors. */
(function () {
var names = pv.Color.names;
for (var name in names)
names[name] = pv.color(names[name]);
})();
/**
* Returns a new categorical color encoding using the specified colors. The
* arguments to this method are an array of colors; see {@link pv.color}. For
* example, to create a categorical color encoding using the <tt>species</tt>
* attribute:
*
* <pre>pv.colors("red", "green", "blue").by(function(d) d.species)</pre>
*
* The result of this expression can be used as a fill- or stroke-style
* property. This assumes that the data's <tt>species</tt> attribute is a
* string.
*
* @param {string} colors... categorical colors.
* @see pv.Scale.ordinal
* @returns {pv.Scale.ordinal} an ordinal color scale.
*/
pv.colors = function () {
var scale = pv.Scale.ordinal();
scale.range.apply(scale, arguments);
return scale;
};
/**
* A collection of standard color palettes for categorical encoding.
*
* @namespace A collection of standard color palettes for categorical encoding.
*/
pv.Colors = {};
/**
* Returns a new 10-color scheme. The arguments to this constructor are
* optional, and equivalent to calling {@link pv.Scale.OrdinalScale#domain}. The
* following colors are used:
*
* <div style="background:#1f77b4;">#1f77b4</div>
* <div style="background:#ff7f0e;">#ff7f0e</div>
* <div style="background:#2ca02c;">#2ca02c</div>
* <div style="background:#d62728;">#d62728</div>
* <div style="background:#9467bd;">#9467bd</div>
* <div style="background:#8c564b;">#8c564b</div>
* <div style="background:#e377c2;">#e377c2</div>
* <div style="background:#7f7f7f;">#7f7f7f</div>
* <div style="background:#bcbd22;">#bcbd22</div>
* <div style="background:#17becf;">#17becf</div>
*
* @param {number...} domain... domain values.
* @returns {pv.Scale.ordinal} a new ordinal color scale.
* @see pv.color
*/
pv.Colors.category10 = function () {
var scale = pv.colors(
"#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd",
"#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf");
scale.domain.apply(scale, arguments);
return scale;
};
/**
* Returns a new 20-color scheme. The arguments to this constructor are
* optional, and equivalent to calling {@link pv.Scale.OrdinalScale#domain}. The
* following colors are used:
*
* <div style="background:#1f77b4;">#1f77b4</div>
* <div style="background:#aec7e8;">#aec7e8</div>
* <div style="background:#ff7f0e;">#ff7f0e</div>
* <div style="background:#ffbb78;">#ffbb78</div>
* <div style="background:#2ca02c;">#2ca02c</div>
* <div style="background:#98df8a;">#98df8a</div>
* <div style="background:#d62728;">#d62728</div>
* <div style="background:#ff9896;">#ff9896</div>
* <div style="background:#9467bd;">#9467bd</div>
* <div style="background:#c5b0d5;">#c5b0d5</div>
* <div style="background:#8c564b;">#8c564b</div>
* <div style="background:#c49c94;">#c49c94</div>
* <div style="background:#e377c2;">#e377c2</div>
* <div style="background:#f7b6d2;">#f7b6d2</div>
* <div style="background:#7f7f7f;">#7f7f7f</div>
* <div style="background:#c7c7c7;">#c7c7c7</div>
* <div style="background:#bcbd22;">#bcbd22</div>
* <div style="background:#dbdb8d;">#dbdb8d</div>
* <div style="background:#17becf;">#17becf</div>
* <div style="background:#9edae5;">#9edae5</div>
*
* @param {number...} domain... domain values.
* @returns {pv.Scale.ordinal} a new ordinal color scale.
* @see pv.color
*/
pv.Colors.category20 = function () {
var scale = pv.colors(
"#1f77b4", "#aec7e8", "#ff7f0e", "#ffbb78", "#2ca02c",
"#98df8a", "#d62728", "#ff9896", "#9467bd", "#c5b0d5",
"#8c564b", "#c49c94", "#e377c2", "#f7b6d2", "#7f7f7f",
"#c7c7c7", "#bcbd22", "#dbdb8d", "#17becf", "#9edae5");
scale.domain.apply(scale, arguments);
return scale;
};
/**
* Returns a new alternative 19-color scheme. The arguments to this constructor
* are optional, and equivalent to calling
* {@link pv.Scale.OrdinalScale#domain}. The following colors are used:
*
* <div style="background:#9c9ede;">#9c9ede</div>
* <div style="background:#7375b5;">#7375b5</div>
* <div style="background:#4a5584;">#4a5584</div>
* <div style="background:#cedb9c;">#cedb9c</div>
* <div style="background:#b5cf6b;">#b5cf6b</div>
* <div style="background:#8ca252;">#8ca252</div>
* <div style="background:#637939;">#637939</div>
* <div style="background:#e7cb94;">#e7cb94</div>
* <div style="background:#e7ba52;">#e7ba52</div>
* <div style="background:#bd9e39;">#bd9e39</div>
* <div style="background:#8c6d31;">#8c6d31</div>
* <div style="background:#e7969c;">#e7969c</div>
* <div style="background:#d6616b;">#d6616b</div>
* <div style="background:#ad494a;">#ad494a</div>
* <div style="background:#843c39;">#843c39</div>
* <div style="background:#de9ed6;">#de9ed6</div>
* <div style="background:#ce6dbd;">#ce6dbd</div>
* <div style="background:#a55194;">#a55194</div>
* <div style="background:#7b4173;">#7b4173</div>
*
* @param {number...} domain... domain values.
* @returns {pv.Scale.ordinal} a new ordinal color scale.
* @see pv.color
*/
pv.Colors.category19 = function () {
var scale = pv.colors(
"#9c9ede", "#7375b5", "#4a5584", "#cedb9c", "#b5cf6b",
"#8ca252", "#637939", "#e7cb94", "#e7ba52", "#bd9e39",
"#8c6d31", "#e7969c", "#d6616b", "#ad494a", "#843c39",
"#de9ed6", "#ce6dbd", "#a55194", "#7b4173");
scale.domain.apply(scale, arguments);
return scale;
};
/**
* Returns a linear color ramp from the specified <tt>start</tt> color to the
* specified <tt>end</tt> color. The color arguments may be specified either as
* <tt>string</tt>s or as {@link pv.Color}s. This is equivalent to:
*
* <pre> pv.Scale.linear().domain(0, 1).range(...)</pre>
*
* @param {string} start the start color; may be a <tt>pv.Color</tt>.
* @param {string} end the end color; may be a <tt>pv.Color</tt>.
* @returns {Function} a color ramp from <tt>start</tt> to <tt>end</tt>.
* @see pv.Scale.linear
*/
pv.ramp = function (start, end) {
var scale = pv.Scale.linear();
scale.range.apply(scale, arguments);
return scale;
};
/**
* @private
* @namespace
*/
pv.Scene = pv.SvgScene = {
/* Various namespaces. */
svg: "http://www.w3.org/2000/svg",
xmlns: "http://www.w3.org/2000/xmlns",
xlink: "http://www.w3.org/1999/xlink",
xhtml: "http://www.w3.org/1999/xhtml",
/** The pre-multipled scale, based on any enclosing transforms. */
scale: 1,
/** The set of supported events. */
events: [
"DOMMouseScroll", // for Firefox
"mousewheel",
"mousedown",
"mouseup",
"mouseover",
"mouseout",
"mousemove",
"click",
"dblclick"
],
/** Implicit values for SVG and CSS properties. */
implicit: {
svg: {
"shape-rendering": "auto",
"pointer-events": "painted",
"x": 0,
"y": 0,
"dy": 0,
"text-anchor": "start",
"transform": "translate(0,0)",
"fill": "none",
"fill-opacity": 1,
"stroke": "none",
"stroke-opacity": 1,
"stroke-width": 1.5,
"stroke-linejoin": "miter"
},
css: {
"font": "10px sans-serif"
}
}
};
/**
* Updates the display for the specified array of scene nodes.
*
* @param scenes {array} an array of scene nodes.
*/
pv.SvgScene.updateAll = function (scenes) {
if (scenes.length
&& scenes[0].reverse
&& (scenes.type != "line")
&& (scenes.type != "area")) {
var reversed = pv.extend(scenes);
for (var i = 0, j = scenes.length - 1; j >= 0; i++, j--) {
reversed[i] = scenes[j];
}
scenes = reversed;
}
this.removeSiblings(this[scenes.type](scenes));
};
/**
* Creates a new SVG element of the specified type.
*
* @param type {string} an SVG element type, such as "rect".
* @returns a new SVG element.
*/
pv.SvgScene.create = function (type) {
return document.createElementNS(this.svg, type);
};
/**
* Expects the element <i>e</i> to be the specified type. If the element does
* not exist, a new one is created. If the element does exist but is the wrong
* type, it is replaced with the specified element.
*
* @param e the current SVG element.
* @param type {string} an SVG element type, such as "rect".
* @param attributes an optional attribute map.
* @param style an optional style map.
* @returns a new SVG element.
*/
pv.SvgScene.expect = function (e, type, attributes, style) {
if (e) {
if (e.tagName == "a")
e = e.firstChild;
if (e.tagName != type) {
var n = this.create(type);
e.parentNode.replaceChild(n, e);
e = n;
}
} else {
e = this.create(type);
}
for (var name in attributes) {
var value = attributes[name];
if (value == this.implicit.svg[name])
value = null;
if (value == null)
e.removeAttribute(name);
else
e.setAttribute(name, value);
}
for (var name in style) {
var value = style[name];
if (value == this.implicit.css[name])
value = null;
if (value == null)
e.style.removeProperty(name);
else
e.style[name] = value;
}
return e;
};
/** TODO */
pv.SvgScene.append = function (e, scenes, index) {
e.$scene = {scenes: scenes, index: index};
e = this.title(e, scenes[index]);
if (!e.parentNode)
scenes.$g.appendChild(e);
return e.nextSibling;
};
/**
* Applies a title tooltip to the specified element <tt>e</tt>, using the
* <tt>title</tt> property of the specified scene node <tt>s</tt>. Note that
* this implementation does not create an SVG <tt>title</tt> element as a child
* of <tt>e</tt>; although this is the recommended standard, it is only
* supported in Opera. Instead, an anchor element is created around the element
* <tt>e</tt>, and the <tt>xlink:title</tt> attribute is set accordingly.
*
* @param e an SVG element.
* @param s a scene node.
*/
pv.SvgScene.title = function (e, s) {
var a = e.parentNode;
if (a && (a.tagName != "a"))
a = null;
if (s.title) {
if (!a) {
a = this.create("a");
if (e.parentNode)
e.parentNode.replaceChild(a, e);
a.appendChild(e);
}
a.setAttributeNS(this.xlink, "title", s.title);
return a;
}
if (a)
a.parentNode.replaceChild(e, a);
return e;
};
/** TODO */
pv.SvgScene.dispatch = pv.listener(function (e) {
var t = e.target.$scene;
if (t) {
var type = e.type;
/* Fixes for mousewheel support on Firefox & Opera. */
switch (type) {
case "DOMMouseScroll":
{
type = "mousewheel";
e.wheel = -480 * e.detail;
break;
}
case "mousewheel":
{
e.wheel = (window.opera ? 12 : 1) * e.wheelDelta;
break;
}
}
if (pv.Mark.dispatch(type, t.scenes, t.index))
e.preventDefault();
}
});
/** @private Remove siblings following element <i>e</i>. */
pv.SvgScene.removeSiblings = function (e) {
while (e) {
var n = e.nextSibling;
e.parentNode.removeChild(e);
e = n;
}
};
/** @private Do nothing when rendering undefined mark types. */
pv.SvgScene.undefined = function () {
};
/**
* @private Converts the specified b-spline curve segment to a bezier curve
* compatible with SVG "C".
*
* @param p0 the first control point.
* @param p1 the second control point.
* @param p2 the third control point.
* @param p3 the fourth control point.
*/
pv.SvgScene.pathBasis = (function () {
/**
* Matrix to transform basis (b-spline) control points to bezier control
* points. Derived from FvD 11.2.8.
*/
var basis = [
[1 / 6, 2 / 3, 1 / 6, 0],
[0, 2 / 3, 1 / 3, 0],
[0, 1 / 3, 2 / 3, 0],
[0, 1 / 6, 2 / 3, 1 / 6]
];
/**
* Returns the point that is the weighted sum of the specified control points,
* using the specified weights. This method requires that there are four
* weights and four control points.
*/
function weight(w, p0, p1, p2, p3) {
return {
x: w[0] * p0.left + w[1] * p1.left + w[2] * p2.left + w[3] * p3.left,
y: w[0] * p0.top + w[1] * p1.top + w[2] * p2.top + w[3] * p3.top
};
}
var convert = function (p0, p1, p2, p3) {
var b1 = weight(basis[1], p0, p1, p2, p3),
b2 = weight(basis[2], p0, p1, p2, p3),
b3 = weight(basis[3], p0, p1, p2, p3);
return "C" + b1.x + "," + b1.y
+ "," + b2.x + "," + b2.y
+ "," + b3.x + "," + b3.y;
};
convert.segment = function (p0, p1, p2, p3) {
var b0 = weight(basis[0], p0, p1, p2, p3),
b1 = weight(basis[1], p0, p1, p2, p3),
b2 = weight(basis[2], p0, p1, p2, p3),
b3 = weight(basis[3], p0, p1, p2, p3);
return "M" + b0.x + "," + b0.y
+ "C" + b1.x + "," + b1.y
+ "," + b2.x + "," + b2.y
+ "," + b3.x + "," + b3.y;
};
return convert;
})();
/**
* @private Interpolates the given points using the basis spline interpolation.
* Returns an SVG path without the leading M instruction to allow path
* appending.
*
* @param points the array of points.
*/
pv.SvgScene.curveBasis = function (points) {
if (points.length <= 2)
return "";
var path = "",
p0 = points[0],
p1 = p0,
p2 = p0,
p3 = points[1];
path += this.pathBasis(p0, p1, p2, p3);
for (var i = 2; i < points.length; i++) {
p0 = p1;
p1 = p2;
p2 = p3;
p3 = points[i];
path += this.pathBasis(p0, p1, p2, p3);
}
/* Cycle through to get the last point. */
path += this.pathBasis(p1, p2, p3, p3);
path += this.pathBasis(p2, p3, p3, p3);
return path;
};
/**
* @private Interpolates the given points using the basis spline interpolation.
* If points.length == tangents.length then a regular Hermite interpolation is
* performed, if points.length == tangents.length + 2 then the first and last
* segments are filled in with cubic bazier segments. Returns an array of path
* strings.
*
* @param points the array of points.
*/
pv.SvgScene.curveBasisSegments = function (points) {
if (points.length <= 2)
return "";
var paths = [],
p0 = points[0],
p1 = p0,
p2 = p0,
p3 = points[1],
firstPath = this.pathBasis.segment(p0, p1, p2, p3);
p0 = p1;
p1 = p2;
p2 = p3;
p3 = points[2];
paths.push(firstPath + this.pathBasis(p0, p1, p2, p3)); // merge first & second path
for (var i = 3; i < points.length; i++) {
p0 = p1;
p1 = p2;
p2 = p3;
p3 = points[i];
paths.push(this.pathBasis.segment(p0, p1, p2, p3));
}
// merge last & second-to-last path
paths.push(this.pathBasis.segment(p1, p2, p3, p3) + this.pathBasis(p2, p3, p3, p3));
return paths;
};
/**
* @private Interpolates the given points with respective tangents using the cubic
* Hermite spline interpolation. If points.length == tangents.length then a regular
* Hermite interpolation is performed, if points.length == tangents.length + 2 then
* the first and last segments are filled in with cubic bazier segments.
* Returns an SVG path without the leading M instruction to allow path appending.
*
* @param points the array of points.
* @param tangents the array of tangent vectors.
*/
pv.SvgScene.curveHermite = function (points, tangents) {
if (tangents.length < 1
|| (points.length != tangents.length
&& points.length != tangents.length + 2))
return "";
var quad = points.length != tangents.length,
path = "",
p0 = points[0],
p = points[1],
t0 = tangents[0],
t = t0,
pi = 1;
if (quad) {
path += "Q" + (p.left - t0.x * 2 / 3) + "," + (p.top - t0.y * 2 / 3)
+ "," + p.left + "," + p.top;
p0 = points[1];
pi = 2;
}
if (tangents.length > 1) {
t = tangents[1];
p = points[pi];
pi++;
path += "C" + (p0.left + t0.x) + "," + (p0.top + t0.y)
+ "," + (p.left - t.x) + "," + (p.top - t.y)
+ "," + p.left + "," + p.top;
for (var i = 2; i < tangents.length; i++, pi++) {
p = points[pi];
t = tangents[i];
path += "S" + (p.left - t.x) + "," + (p.top - t.y)
+ "," + p.left + "," + p.top;
}
}
if (quad) {
var lp = points[pi];
path += "Q" + (p.left + t.x * 2 / 3) + "," + (p.top + t.y * 2 / 3) + ","
+ lp.left + "," + lp.top;
}
return path;
};
/**
* @private Interpolates the given points with respective tangents using the
* cubic Hermite spline interpolation. Returns an array of path strings.
*
* @param points the array of points.
* @param tangents the array of tangent vectors.
*/
pv.SvgScene.curveHermiteSegments = function (points, tangents) {
if (tangents.length < 1
|| (points.length != tangents.length
&& points.length != tangents.length + 2))
return [];
var quad = points.length != tangents.length,
paths = [],
p0 = points[0],
p = p0,
t0 = tangents[0],
t = t0,
pi = 1;
if (quad) {
p = points[1];
paths.push("M" + p0.left + "," + p0.top
+ "Q" + (p.left - t.x * 2 / 3) + "," + (p.top - t.y * 2 / 3)
+ "," + p.left + "," + p.top);
pi = 2;
}
for (var i = 1; i < tangents.length; i++, pi++) {
p0 = p;
t0 = t;
p = points[pi];
t = tangents[i];
paths.push("M" + p0.left + "," + p0.top
+ "C" + (p0.left + t0.x) + "," + (p0.top + t0.y)
+ "," + (p.left - t.x) + "," + (p.top - t.y)
+ "," + p.left + "," + p.top);
}
if (quad) {
var lp = points[pi];
paths.push("M" + p.left + "," + p.top
+ "Q" + (p.left + t.x * 2 / 3) + "," + (p.top + t.y * 2 / 3) + ","
+ lp.left + "," + lp.top);
}
return paths;
};
/**
* @private Computes the tangents for the given points needed for cardinal
* spline interpolation. Returns an array of tangent vectors. Note: that for n
* points only the n-2 well defined tangents are returned.
*
* @param points the array of points.
* @param tension the tension of hte cardinal spline.
*/
pv.SvgScene.cardinalTangents = function (points, tension) {
var tangents = [],
a = (1 - tension) / 2,
p0 = points[0],
p1 = points[1],
p2 = points[2];
for (var i = 3; i < points.length; i++) {
tangents.push({x: a * (p2.left - p0.left), y: a * (p2.top - p0.top)});
p0 = p1;
p1 = p2;
p2 = points[i];
}
tangents.push({x: a * (p2.left - p0.left), y: a * (p2.top - p0.top)});
return tangents;
};
/**
* @private Interpolates the given points using cardinal spline interpolation.
* Returns an SVG path without the leading M instruction to allow path
* appending.
*
* @param points the array of points.
* @param tension the tension of hte cardinal spline.
*/
pv.SvgScene.curveCardinal = function (points, tension) {
if (points.length <= 2)
return "";
return this.curveHermite(points, this.cardinalTangents(points, tension));
};
/**
* @private Interpolates the given points using cardinal spline interpolation.
* Returns an array of path strings.
*
* @param points the array of points.
* @param tension the tension of hte cardinal spline.
*/
pv.SvgScene.curveCardinalSegments = function (points, tension) {
if (points.length <= 2)
return "";
return this.curveHermiteSegments(points, this.cardinalTangents(points, tension));
};
/**
* @private Interpolates the given points using Fritsch-Carlson Monotone cubic
* Hermite interpolation. Returns an array of tangent vectors.
*
* @param points the array of points.
*/
pv.SvgScene.monotoneTangents = function (points) {
var tangents = [],
d = [],
m = [],
dx = [],
k = 0;
/* Compute the slopes of the secant lines between successive points. */
for (k = 0; k < points.length - 1; k++) {
d[k] = (points[k + 1].top - points[k].top) / (points[k + 1].left - points[k].left);
}
/* Initialize the tangents at every point as the average of the secants. */
m[0] = d[0];
dx[0] = points[1].left - points[0].left;
for (k = 1; k < points.length - 1; k++) {
m[k] = (d[k - 1] + d[k]) / 2;
dx[k] = (points[k + 1].left - points[k - 1].left) / 2;
}
m[k] = d[k - 1];
dx[k] = (points[k].left - points[k - 1].left);
/* Step 3. Very important, step 3. Yep. Wouldn't miss it. */
for (k = 0; k < points.length - 1; k++) {
if (d[k] == 0) {
m[ k ] = 0;
m[k + 1] = 0;
}
}
/* Step 4 + 5. Out of 5 or more steps. */
for (k = 0; k < points.length - 1; k++) {
if ((Math.abs(m[k]) < 1e-5) || (Math.abs(m[k + 1]) < 1e-5))
continue;
var ak = m[k] / d[k],
bk = m[k + 1] / d[k],
s = ak * ak + bk * bk; // monotone constant (?)
if (s > 9) {
var tk = 3 / Math.sqrt(s);
m[k] = tk * ak * d[k];
m[k + 1] = tk * bk * d[k];
}
}
var len;
for (var i = 0; i < points.length; i++) {
len = 1 + m[i] * m[i]; // pv.vector(1, m[i]).norm().times(dx[i]/3)
tangents.push({x: dx[i] / 3 / len, y: m[i] * dx[i] / 3 / len});
}
return tangents;
};
/**
* @private Interpolates the given points using Fritsch-Carlson Monotone cubic
* Hermite interpolation. Returns an SVG path without the leading M instruction
* to allow path appending.
*
* @param points the array of points.
*/
pv.SvgScene.curveMonotone = function (points) {
if (points.length <= 2)
return "";
return this.curveHermite(points, this.monotoneTangents(points));
}
/**
* @private Interpolates the given points using Fritsch-Carlson Monotone cubic
* Hermite interpolation.
* Returns an array of path strings.
*
* @param points the array of points.
*/
pv.SvgScene.curveMonotoneSegments = function (points) {
if (points.length <= 2)
return "";
return this.curveHermiteSegments(points, this.monotoneTangents(points));
};
pv.SvgScene.area = function (scenes) {
var e = scenes.$g.firstChild;
if (!scenes.length)
return e;
var s = scenes[0];
/* segmented */
if (s.segmented)
return this.areaSegment(scenes);
/* visible */
if (!s.visible)
return e;
var fill = s.fillStyle, stroke = s.strokeStyle;
if (!fill.opacity && !stroke.opacity)
return e;
/** @private Computes the straight path for the range [i, j]. */
function path(i, j) {
var p1 = [], p2 = [];
for (var k = j; i <= k; i++, j--) {
var si = scenes[i],
sj = scenes[j],
pi = si.left + "," + si.top,
pj = (sj.left + sj.width) + "," + (sj.top + sj.height);
/* interpolate */
if (i < k) {
var sk = scenes[i + 1], sl = scenes[j - 1];
switch (s.interpolate) {
case "step-before":
{
pi += "V" + sk.top;
pj += "H" + (sl.left + sl.width);
break;
}
case "step-after":
{
pi += "H" + sk.left;
pj += "V" + (sl.top + sl.height);
break;
}
}
}
p1.push(pi);
p2.push(pj);
}
return p1.concat(p2).join("L");
}
/** @private Computes the curved path for the range [i, j]. */
function pathCurve(i, j) {
var pointsT = [], pointsB = [], pathT, pathB;
for (var k = j; i <= k; i++, j--) {
var sj = scenes[j];
pointsT.push(scenes[i]);
pointsB.push({left: sj.left + sj.width, top: sj.top + sj.height});
}
if (s.interpolate == "basis") {
pathT = pv.SvgScene.curveBasis(pointsT);
pathB = pv.SvgScene.curveBasis(pointsB);
} else if (s.interpolate == "cardinal") {
pathT = pv.SvgScene.curveCardinal(pointsT, s.tension);
pathB = pv.SvgScene.curveCardinal(pointsB, s.tension);
} else { // monotone
pathT = pv.SvgScene.curveMonotone(pointsT);
pathB = pv.SvgScene.curveMonotone(pointsB);
}
return pointsT[0].left + "," + pointsT[0].top + pathT
+ "L" + pointsB[0].left + "," + pointsB[0].top + pathB;
}
/* points */
var d = [], si, sj;
for (var i = 0; i < scenes.length; i++) {
si = scenes[i];
if (!si.width && !si.height)
continue;
for (var j = i + 1; j < scenes.length; j++) {
sj = scenes[j];
if (!sj.width && !sj.height)
break;
}
if (i && (s.interpolate != "step-after"))
i--;
if ((j < scenes.length) && (s.interpolate != "step-before"))
j++;
d.push(((j - i > 2
&& (s.interpolate == "basis"
|| s.interpolate == "cardinal"
|| s.interpolate == "monotone"))
? pathCurve : path)(i, j - 1));
i = j - 1;
}
if (!d.length)
return e;
e = this.expect(e, "path", {
"shape-rendering": s.antialias ? null : "crispEdges",
"pointer-events": s.events,
"cursor": s.cursor,
"d": "M" + d.join("ZM") + "Z",
"fill": fill.color,
"fill-opacity": fill.opacity || null,
"stroke": stroke.color,
"stroke-opacity": stroke.opacity || null,
"stroke-width": stroke.opacity ? s.lineWidth / this.scale : null
});
return this.append(e, scenes, 0);
};
pv.SvgScene.areaSegment = function (scenes) {
var e = scenes.$g.firstChild, s = scenes[0], pathsT, pathsB;
if (s.interpolate == "basis"
|| s.interpolate == "cardinal"
|| s.interpolate == "monotone") {
var pointsT = [], pointsB = [];
for (var i = 0, n = scenes.length; i < n; i++) {
var sj = scenes[n - i - 1];
pointsT.push(scenes[i]);
pointsB.push({left: sj.left + sj.width, top: sj.top + sj.height});
}
if (s.interpolate == "basis") {
pathsT = this.curveBasisSegments(pointsT);
pathsB = this.curveBasisSegments(pointsB);
} else if (s.interpolate == "cardinal") {
pathsT = this.curveCardinalSegments(pointsT, s.tension);
pathsB = this.curveCardinalSegments(pointsB, s.tension);
} else { // monotone
pathsT = this.curveMonotoneSegments(pointsT);
pathsB = this.curveMonotoneSegments(pointsB);
}
}
for (var i = 0, n = scenes.length - 1; i < n; i++) {
var s1 = scenes[i], s2 = scenes[i + 1];
/* visible */
if (!s1.visible || !s2.visible)
continue;
var fill = s1.fillStyle, stroke = s1.strokeStyle;
if (!fill.opacity && !stroke.opacity)
continue;
var d;
if (pathsT) {
var pathT = pathsT[i],
pathB = "L" + pathsB[n - i - 1].substr(1);
d = pathT + pathB + "Z";
} else {
/* interpolate */
var si = s1, sj = s2;
switch (s1.interpolate) {
case "step-before":
si = s2;
break;
case "step-after":
sj = s1;
break;
}
/* path */
d = "M" + s1.left + "," + si.top
+ "L" + s2.left + "," + sj.top
+ "L" + (s2.left + s2.width) + "," + (sj.top + sj.height)
+ "L" + (s1.left + s1.width) + "," + (si.top + si.height)
+ "Z";
}
e = this.expect(e, "path", {
"shape-rendering": s1.antialias ? null : "crispEdges",
"pointer-events": s1.events,
"cursor": s1.cursor,
"d": d,
"fill": fill.color,
"fill-opacity": fill.opacity || null,
"stroke": stroke.color,
"stroke-opacity": stroke.opacity || null,
"stroke-width": stroke.opacity ? s1.lineWidth / this.scale : null
});
e = this.append(e, scenes, i);
}
return e;
};
pv.SvgScene.bar = function (scenes) {
var e = scenes.$g.firstChild;
for (var i = 0; i < scenes.length; i++) {
var s = scenes[i];
/* visible */
if (!s.visible)
continue;
var fill = s.fillStyle, stroke = s.strokeStyle;
if (!fill.opacity && !stroke.opacity)
continue;
e = this.expect(e, "rect", {
"shape-rendering": s.antialias ? null : "crispEdges",
"pointer-events": s.events,
"cursor": s.cursor,
"x": s.left,
"y": s.top,
"width": Math.max(1E-10, s.width),
"height": Math.max(1E-10, s.height),
"fill": fill.color,
"fill-opacity": fill.opacity || null,
"stroke": stroke.color,
"stroke-opacity": stroke.opacity || null,
"stroke-width": stroke.opacity ? s.lineWidth / this.scale : null
});
e = this.append(e, scenes, i);
}
return e;
};
pv.SvgScene.dot = function (scenes) {
var e = scenes.$g.firstChild;
for (var i = 0; i < scenes.length; i++) {
var s = scenes[i];
/* visible */
if (!s.visible)
continue;
var fill = s.fillStyle, stroke = s.strokeStyle;
if (!fill.opacity && !stroke.opacity)
continue;
/* points */
var radius = s.radius, path = null;
switch (s.shape) {
case "cross":
{
path = "M" + -radius + "," + -radius
+ "L" + radius + "," + radius
+ "M" + radius + "," + -radius
+ "L" + -radius + "," + radius;
break;
}
case "triangle":
{
var h = radius, w = radius * 1.1547; // 2 / Math.sqrt(3)
path = "M0," + h
+ "L" + w + "," + -h
+ " " + -w + "," + -h
+ "Z";
break;
}
case "diamond":
{
radius *= Math.SQRT2;
path = "M0," + -radius
+ "L" + radius + ",0"
+ " 0," + radius
+ " " + -radius + ",0"
+ "Z";
break;
}
case "square":
{
path = "M" + -radius + "," + -radius
+ "L" + radius + "," + -radius
+ " " + radius + "," + radius
+ " " + -radius + "," + radius
+ "Z";
break;
}
case "tick":
{
path = "M0,0L0," + -s.size;
break;
}
case "bar":
{
path = "M0," + (s.size / 2) + "L0," + -(s.size / 2);
break;
}
}
/* Use <circle> for circles, <path> for everything else. */
var svg = {
"shape-rendering": s.antialias ? null : "crispEdges",
"pointer-events": s.events,
"cursor": s.cursor,
"fill": fill.color,
"fill-opacity": fill.opacity || null,
"stroke": stroke.color,
"stroke-opacity": stroke.opacity || null,
"stroke-width": stroke.opacity ? s.lineWidth / this.scale : null
};
if (path) {
svg.transform = "translate(" + s.left + "," + s.top + ")";
if (s.angle)
svg.transform += " rotate(" + 180 * s.angle / Math.PI + ")";
svg.d = path;
e = this.expect(e, "path", svg);
} else {
svg.cx = s.left;
svg.cy = s.top;
svg.r = radius;
e = this.expect(e, "circle", svg);
}
e = this.append(e, scenes, i);
}
return e;
};
pv.SvgScene.image = function (scenes) {
var e = scenes.$g.firstChild;
for (var i = 0; i < scenes.length; i++) {
var s = scenes[i];
/* visible */
if (!s.visible)
continue;
/* fill */
e = this.fill(e, scenes, i);
/* image */
if (s.image) {
e = this.expect(e, "foreignObject", {
"cursor": s.cursor,
"x": s.left,
"y": s.top,
"width": s.width,
"height": s.height
});
var c = e.firstChild || e.appendChild(document.createElementNS(this.xhtml, "canvas"));
c.$scene = {scenes: scenes, index: i};
c.style.width = s.width;
c.style.height = s.height;
c.width = s.imageWidth;
c.height = s.imageHeight;
c.getContext("2d").putImageData(s.image, 0, 0);
} else {
e = this.expect(e, "image", {
"preserveAspectRatio": "none",
"cursor": s.cursor,
"x": s.left,
"y": s.top,
"width": s.width,
"height": s.height
});
e.setAttributeNS(this.xlink, "href", s.url);
}
e = this.append(e, scenes, i);
/* stroke */
e = this.stroke(e, scenes, i);
}
return e;
};
pv.SvgScene.label = function (scenes) {
var e = scenes.$g.firstChild;
for (var i = 0; i < scenes.length; i++) {
var s = scenes[i];
/* visible */
if (!s.visible)
continue;
var fill = s.textStyle;
if (!fill.opacity || !s.text)
continue;
/* text-baseline, text-align */
var x = 0, y = 0, dy = 0, anchor = "start";
switch (s.textBaseline) {
case "middle":
dy = ".35em";
break;
case "top":
dy = ".71em";
y = s.textMargin;
break;
case "bottom":
y = "-" + s.textMargin;
break;
}
switch (s.textAlign) {
case "right":
anchor = "end";
x = "-" + s.textMargin;
break;
case "center":
anchor = "middle";
break;
case "left":
x = s.textMargin;
break;
}
e = this.expect(e, "text", {
"pointer-events": s.events,
"cursor": s.cursor,
"x": x,
"y": y,
"dy": dy,
"transform": "translate(" + s.left + "," + s.top + ")"
+ (s.textAngle ? " rotate(" + 180 * s.textAngle / Math.PI + ")" : "")
+ (this.scale != 1 ? " scale(" + 1 / this.scale + ")" : ""),
"fill": fill.color,
"fill-opacity": fill.opacity || null,
"text-anchor": anchor
}, {
"font": s.font,
"text-shadow": s.textShadow,
"text-decoration": s.textDecoration
});
if (e.firstChild)
e.firstChild.nodeValue = s.text;
else
e.appendChild(document.createTextNode(s.text));
e = this.append(e, scenes, i);
}
return e;
};
pv.SvgScene.line = function (scenes) {
var e = scenes.$g.firstChild;
if (scenes.length < 2)
return e;
var s = scenes[0];
/* segmented */
if (s.segmented)
return this.lineSegment(scenes);
/* visible */
if (!s.visible)
return e;
var fill = s.fillStyle, stroke = s.strokeStyle;
if (!fill.opacity && !stroke.opacity)
return e;
/* points */
var d = "M" + s.left + "," + s.top;
if (scenes.length > 2 && (s.interpolate == "basis" || s.interpolate == "cardinal" || s.interpolate == "monotone")) {
switch (s.interpolate) {
case "basis":
d += this.curveBasis(scenes);
break;
case "cardinal":
d += this.curveCardinal(scenes, s.tension);
break;
case "monotone":
d += this.curveMonotone(scenes);
break;
}
} else {
for (var i = 1; i < scenes.length; i++) {
d += this.pathSegment(scenes[i - 1], scenes[i]);
}
}
e = this.expect(e, "path", {
"shape-rendering": s.antialias ? null : "crispEdges",
"pointer-events": s.events,
"cursor": s.cursor,
"d": d,
"fill": fill.color,
"fill-opacity": fill.opacity || null,
"stroke": stroke.color,
"stroke-opacity": stroke.opacity || null,
"stroke-width": stroke.opacity ? s.lineWidth / this.scale : null,
"stroke-linejoin": s.lineJoin
});
return this.append(e, scenes, 0);
};
pv.SvgScene.lineSegment = function (scenes) {
var e = scenes.$g.firstChild;
var s = scenes[0];
var paths;
switch (s.interpolate) {
case "basis":
paths = this.curveBasisSegments(scenes);
break;
case "cardinal":
paths = this.curveCardinalSegments(scenes, s.tension);
break;
case "monotone":
paths = this.curveMonotoneSegments(scenes);
break;
}
for (var i = 0, n = scenes.length - 1; i < n; i++) {
var s1 = scenes[i], s2 = scenes[i + 1];
/* visible */
if (!s1.visible || !s2.visible)
continue;
var stroke = s1.strokeStyle, fill = pv.Color.transparent;
if (!stroke.opacity)
continue;
/* interpolate */
var d;
if ((s1.interpolate == "linear") && (s1.lineJoin == "miter")) {
fill = stroke;
stroke = pv.Color.transparent;
d = this.pathJoin(scenes[i - 1], s1, s2, scenes[i + 2]);
} else if (paths) {
d = paths[i];
} else {
d = "M" + s1.left + "," + s1.top + this.pathSegment(s1, s2);
}
e = this.expect(e, "path", {
"shape-rendering": s1.antialias ? null : "crispEdges",
"pointer-events": s1.events,
"cursor": s1.cursor,
"d": d,
"fill": fill.color,
"fill-opacity": fill.opacity || null,
"stroke": stroke.color,
"stroke-opacity": stroke.opacity || null,
"stroke-width": stroke.opacity ? s1.lineWidth / this.scale : null,
"stroke-linejoin": s1.lineJoin
});
e = this.append(e, scenes, i);
}
return e;
};
/** @private Returns the path segment for the specified points. */
pv.SvgScene.pathSegment = function (s1, s2) {
var l = 1; // sweep-flag
switch (s1.interpolate) {
case "polar-reverse":
l = 0;
case "polar":
{
var dx = s2.left - s1.left,
dy = s2.top - s1.top,
e = 1 - s1.eccentricity,
r = Math.sqrt(dx * dx + dy * dy) / (2 * e);
if ((e <= 0) || (e > 1))
break; // draw a straight line
return "A" + r + "," + r + " 0 0," + l + " " + s2.left + "," + s2.top;
}
case "step-before":
return "V" + s2.top + "H" + s2.left;
case "step-after":
return "H" + s2.left + "V" + s2.top;
}
return "L" + s2.left + "," + s2.top;
};
/** @private Line-line intersection, per Akenine-Moller 16.16.1. */
pv.SvgScene.lineIntersect = function (o1, d1, o2, d2) {
return o1.plus(d1.times(o2.minus(o1).dot(d2.perp()) / d1.dot(d2.perp())));
}
/** @private Returns the miter join path for the specified points. */
pv.SvgScene.pathJoin = function (s0, s1, s2, s3) {
/*
* P1-P2 is the current line segment. V is a vector that is perpendicular to
* the line segment, and has length lineWidth / 2. ABCD forms the initial
* bounding box of the line segment (i.e., the line segment if we were to do
* no joins).
*/
var p1 = pv.vector(s1.left, s1.top),
p2 = pv.vector(s2.left, s2.top),
p = p2.minus(p1),
v = p.perp().norm(),
w = v.times(s1.lineWidth / (2 * this.scale)),
a = p1.plus(w),
b = p2.plus(w),
c = p2.minus(w),
d = p1.minus(w);
/*
* Start join. P0 is the previous line segment's start point. We define the
* cutting plane as the average of the vector perpendicular to P0-P1, and
* the vector perpendicular to P1-P2. This insures that the cross-section of
* the line on the cutting plane is equal if the line-width is unchanged.
* Note that we don't implement miter limits, so these can get wild.
*/
if (s0 && s0.visible) {
var v1 = p1.minus(s0.left, s0.top).perp().norm().plus(v);
d = this.lineIntersect(p1, v1, d, p);
a = this.lineIntersect(p1, v1, a, p);
}
/* Similarly, for end join. */
if (s3 && s3.visible) {
var v2 = pv.vector(s3.left, s3.top).minus(p2).perp().norm().plus(v);
c = this.lineIntersect(p2, v2, c, p);
b = this.lineIntersect(p2, v2, b, p);
}
return "M" + a.x + "," + a.y
+ "L" + b.x + "," + b.y
+ " " + c.x + "," + c.y
+ " " + d.x + "," + d.y;
};
pv.SvgScene.panel = function (scenes) {
var g = scenes.$g, e = g && g.firstChild;
for (var i = 0; i < scenes.length; i++) {
var s = scenes[i];
/* visible */
if (!s.visible)
continue;
/* svg */
if (!scenes.parent) {
s.canvas.style.display = "inline-block";
if (g && (g.parentNode != s.canvas)) {
g = s.canvas.firstChild;
e = g && g.firstChild;
}
if (!g) {
g = s.canvas.appendChild(this.create("svg"));
g.setAttribute("font-size", "10px");
g.setAttribute("font-family", "sans-serif");
g.setAttribute("fill", "none");
g.setAttribute("stroke", "none");
g.setAttribute("stroke-width", 1.5);
for (var j = 0; j < this.events.length; j++) {
g.addEventListener(this.events[j], this.dispatch, false);
}
e = g.firstChild;
}
scenes.$g = g;
g.setAttribute("width", s.width + s.left + s.right);
g.setAttribute("height", s.height + s.top + s.bottom);
}
/* clip (nest children) */
if (s.overflow == "hidden") {
var id = pv.id().toString(36),
c = this.expect(e, "g", {"clip-path": "url(#" + id + ")"});
if (!c.parentNode)
g.appendChild(c);
scenes.$g = g = c;
e = c.firstChild;
e = this.expect(e, "clipPath", {"id": id});
var r = e.firstChild || e.appendChild(this.create("rect"));
r.setAttribute("x", s.left);
r.setAttribute("y", s.top);
r.setAttribute("width", s.width);
r.setAttribute("height", s.height);
if (!e.parentNode)
g.appendChild(e);
e = e.nextSibling;
}
/* fill */
e = this.fill(e, scenes, i);
/* transform (push) */
var k = this.scale,
t = s.transform,
x = s.left + t.x,
y = s.top + t.y;
this.scale *= t.k;
/* children */
for (var j = 0; j < s.children.length; j++) {
s.children[j].$g = e = this.expect(e, "g", {
"transform": "translate(" + x + "," + y + ")"
+ (t.k != 1 ? " scale(" + t.k + ")" : "")
});
this.updateAll(s.children[j]);
if (!e.parentNode)
g.appendChild(e);
e = e.nextSibling;
}
/* transform (pop) */
this.scale = k;
/* stroke */
e = this.stroke(e, scenes, i);
/* clip (restore group) */
if (s.overflow == "hidden") {
scenes.$g = g = c.parentNode;
e = c.nextSibling;
}
}
return e;
};
pv.SvgScene.fill = function (e, scenes, i) {
var s = scenes[i], fill = s.fillStyle;
if (fill.opacity || s.events == "all") {
e = this.expect(e, "rect", {
"shape-rendering": s.antialias ? null : "crispEdges",
"pointer-events": s.events,
"cursor": s.cursor,
"x": s.left,
"y": s.top,
"width": s.width,
"height": s.height,
"fill": fill.color,
"fill-opacity": fill.opacity,
"stroke": null
});
e = this.append(e, scenes, i);
}
return e;
};
pv.SvgScene.stroke = function (e, scenes, i) {
var s = scenes[i], stroke = s.strokeStyle;
if (stroke.opacity || s.events == "all") {
e = this.expect(e, "rect", {
"shape-rendering": s.antialias ? null : "crispEdges",
"pointer-events": s.events == "all" ? "stroke" : s.events,
"cursor": s.cursor,
"x": s.left,
"y": s.top,
"width": Math.max(1E-10, s.width),
"height": Math.max(1E-10, s.height),
"fill": null,
"stroke": stroke.color,
"stroke-opacity": stroke.opacity,
"stroke-width": s.lineWidth / this.scale
});
e = this.append(e, scenes, i);
}
return e;
};
pv.SvgScene.rule = function (scenes) {
var e = scenes.$g.firstChild;
for (var i = 0; i < scenes.length; i++) {
var s = scenes[i];
/* visible */
if (!s.visible)
continue;
var stroke = s.strokeStyle;
if (!stroke.opacity)
continue;
e = this.expect(e, "line", {
"shape-rendering": s.antialias ? null : "crispEdges",
"pointer-events": s.events,
"cursor": s.cursor,
"x1": s.left,
"y1": s.top,
"x2": s.left + s.width,
"y2": s.top + s.height,
"stroke": stroke.color,
"stroke-opacity": stroke.opacity,
"stroke-width": s.lineWidth / this.scale
});
e = this.append(e, scenes, i);
}
return e;
};
pv.SvgScene.wedge = function (scenes) {
var e = scenes.$g.firstChild;
for (var i = 0; i < scenes.length; i++) {
var s = scenes[i];
/* visible */
if (!s.visible)
continue;
var fill = s.fillStyle, stroke = s.strokeStyle;
if (!fill.opacity && !stroke.opacity)
continue;
/* points */
var r1 = s.innerRadius, r2 = s.outerRadius, a = Math.abs(s.angle), p;
if (a >= 2 * Math.PI) {
if (r1) {
p = "M0," + r2
+ "A" + r2 + "," + r2 + " 0 1,1 0," + (-r2)
+ "A" + r2 + "," + r2 + " 0 1,1 0," + r2
+ "M0," + r1
+ "A" + r1 + "," + r1 + " 0 1,1 0," + (-r1)
+ "A" + r1 + "," + r1 + " 0 1,1 0," + r1
+ "Z";
} else {
p = "M0," + r2
+ "A" + r2 + "," + r2 + " 0 1,1 0," + (-r2)
+ "A" + r2 + "," + r2 + " 0 1,1 0," + r2
+ "Z";
}
} else {
var sa = Math.min(s.startAngle, s.endAngle),
ea = Math.max(s.startAngle, s.endAngle),
c1 = Math.cos(sa), c2 = Math.cos(ea),
s1 = Math.sin(sa), s2 = Math.sin(ea);
if (r1) {
p = "M" + r2 * c1 + "," + r2 * s1
+ "A" + r2 + "," + r2 + " 0 "
+ ((a < Math.PI) ? "0" : "1") + ",1 "
+ r2 * c2 + "," + r2 * s2
+ "L" + r1 * c2 + "," + r1 * s2
+ "A" + r1 + "," + r1 + " 0 "
+ ((a < Math.PI) ? "0" : "1") + ",0 "
+ r1 * c1 + "," + r1 * s1 + "Z";
} else {
p = "M" + r2 * c1 + "," + r2 * s1
+ "A" + r2 + "," + r2 + " 0 "
+ ((a < Math.PI) ? "0" : "1") + ",1 "
+ r2 * c2 + "," + r2 * s2 + "L0,0Z";
}
}
e = this.expect(e, "path", {
"shape-rendering": s.antialias ? null : "crispEdges",
"pointer-events": s.events,
"cursor": s.cursor,
"transform": "translate(" + s.left + "," + s.top + ")",
"d": p,
"fill": fill.color,
"fill-rule": "evenodd",
"fill-opacity": fill.opacity || null,
"stroke": stroke.color,
"stroke-opacity": stroke.opacity || null,
"stroke-width": stroke.opacity ? s.lineWidth / this.scale : null
});
e = this.append(e, scenes, i);
}
return e;
};
/**
* Constructs a new mark with default properties. Marks, with the exception of
* the root panel, are not typically constructed directly; instead, they are
* added to a panel or an existing mark via {@link pv.Mark#add}.
*
* @class Represents a data-driven graphical mark. The <tt>Mark</tt> class is
* the base class for all graphical marks in Protovis; it does not provide any
* specific rendering functionality, but together with {@link Panel} establishes
* the core framework.
*
* <p>Concrete mark types include familiar visual elements such as bars, lines
* and labels. Although a bar mark may be used to construct a bar chart, marks
* know nothing about charts; it is only through their specification and
* composition that charts are produced. These building blocks permit many
* combinatorial possibilities.
*
* <p>Marks are associated with <b>data</b>: a mark is generated once per
* associated datum, mapping the datum to visual <b>properties</b> such as
* position and color. Thus, a single mark specification represents a set of
* visual elements that share the same data and visual encoding. The type of
* mark defines the names of properties and their meaning. A property may be
* static, ignoring the associated datum and returning a constant; or, it may be
* dynamic, derived from the associated datum or index. Such dynamic encodings
* can be specified succinctly using anonymous functions. Special properties
* called event handlers can be registered to add interactivity.
*
* <p>Protovis uses <b>inheritance</b> to simplify the specification of related
* marks: a new mark can be derived from an existing mark, inheriting its
* properties. The new mark can then override properties to specify new
* behavior, potentially in terms of the old behavior. In this way, the old mark
* serves as the <b>prototype</b> for the new mark. Most mark types share the
* same basic properties for consistency and to facilitate inheritance.
*
* <p>The prioritization of redundant properties is as follows:<ol>
*
* <li>If the <tt>width</tt> property is not specified (i.e., null), its value
* is the width of the parent panel, minus this mark's left and right margins;
* the left and right margins are zero if not specified.
*
* <li>Otherwise, if the <tt>right</tt> margin is not specified, its value is
* the width of the parent panel, minus this mark's width and left margin; the
* left margin is zero if not specified.
*
* <li>Otherwise, if the <tt>left</tt> property is not specified, its value is
* the width of the parent panel, minus this mark's width and the right margin.
*
* </ol>This prioritization is then duplicated for the <tt>height</tt>,
* <tt>bottom</tt> and <tt>top</tt> properties, respectively.
*
* <p>While most properties are <i>variable</i>, some mark types, such as lines
* and areas, generate a single visual element rather than a distinct visual
* element per datum. With these marks, some properties may be <b>fixed</b>.
* Fixed properties can vary per mark, but not <i>per datum</i>! These
* properties are evaluated solely for the first (0-index) datum, and typically
* are specified as a constant. However, it is valid to use a function if the
* property varies between panels or is dynamically generated.
*
* <p>See also the <a href="../../api/">Protovis guide</a>.
*/
pv.Mark = function () {
/*
* TYPE 0 constant defs
* TYPE 1 function defs
* TYPE 2 constant properties
* TYPE 3 function properties
* in order of evaluation!
*/
this.$properties = [];
this.$handlers = {};
};
/** @private Records which properties are defined on this mark type. */
pv.Mark.prototype.properties = {};
/** @private Records the cast function for each property. */
pv.Mark.cast = {};
/**
* @private Defines and registers a property method for the property with the
* given name. This method should be called on a mark class prototype to define
* each exposed property. (Note this refers to the JavaScript
* <tt>prototype</tt>, not the Protovis mark prototype, which is the {@link
* #proto} field.)
*
* <p>The created property method supports several modes of invocation: <ol>
*
* <li>If invoked with a <tt>Function</tt> argument, this function is evaluated
* for each associated datum. The return value of the function is used as the
* computed property value. The context of the function (<tt>this</tt>) is this
* mark. The arguments to the function are the associated data of this mark and
* any enclosing panels. For example, a linear encoding of numerical data to
* height is specified as
*
* <pre>m.height(function(d) d * 100);</pre>
*
* The expression <tt>d * 100</tt> will be evaluated for the height property of
* each mark instance. The return value of the property method (e.g.,
* <tt>m.height</tt>) is this mark (<tt>m</tt>)).<p>
*
* <li>If invoked with a non-function argument, the property is treated as a
* constant. The return value of the property method (e.g., <tt>m.height</tt>)
* is this mark.<p>
*
* <li>If invoked with no arguments, the computed property value for the current
* mark instance in the scene graph is returned. This facilitates <i>property
* chaining</i>, where one mark's properties are defined in terms of another's.
* For example, to offset a mark's location from its prototype, you might say
*
* <pre>m.top(function() this.proto.top() + 10);</pre>
*
* Note that the index of the mark being evaluated (in the above example,
* <tt>this.proto</tt>) is inherited from the <tt>Mark</tt> class and set by
* this mark. So, if the fifth element's top property is being evaluated, the
* fifth instance of <tt>this.proto</tt> will similarly be queried for the value
* of its top property. If the mark being evaluated has a different number of
* instances, or its data is unrelated, the behavior of this method is
* undefined. In these cases it may be better to index the <tt>scene</tt>
* explicitly to specify the exact instance.
*
* </ol><p>Property names should follow standard JavaScript method naming
* conventions, using lowerCamel-style capitalization.
*
* <p>In addition to creating the property method, every property is registered
* in the {@link #properties} map on the <tt>prototype</tt>. Although this is an
* instance field, it is considered immutable and shared by all instances of a
* given mark type. The <tt>properties</tt> map can be queried to see if a mark
* type defines a particular property, such as width or height.
*
* @param {string} name the property name.
* @param {function} [cast] the cast function for this property.
*/
pv.Mark.prototype.property = function (name, cast) {
if (!this.hasOwnProperty("properties")) {
this.properties = pv.extend(this.properties);
}
this.properties[name] = true;
/*
* Define the setter-getter globally, since the default behavior should be the
* same for all properties, and since the Protovis inheritance chain is
* independent of the JavaScript inheritance chain. For example, anchors
* define a "name" property that is evaluated on derived marks, even though
* those marks don't normally have a name.
*/
pv.Mark.prototype.propertyMethod(name, false, pv.Mark.cast[name] = cast);
return this;
};
/**
* @private Defines a setter-getter for the specified property.
*
* <p>If a cast function has been assigned to the specified property name, the
* property function is wrapped by the cast function, or, if a constant is
* specified, the constant is immediately cast. Note, however, that if the
* property value is null, the cast function is not invoked.
*
* @param {string} name the property name.
* @param {boolean} [def] whether is a property or a def.
* @param {function} [cast] the cast function for this property.
*/
pv.Mark.prototype.propertyMethod = function (name, def, cast) {
if (!cast)
cast = pv.Mark.cast[name];
this[name] = function (v) {
/* If this is a def, use it rather than property. */
if (def && this.scene) {
var defs = this.scene.defs;
if (arguments.length) {
defs[name] = {
id: (v == null) ? 0 : pv.id(),
value: ((v != null) && cast) ? cast(v) : v
};
return this;
}
return defs[name] ? defs[name].value : null;
}
/* If arguments are specified, set the property value. */
if (arguments.length) {
var type = !def << 1 | (typeof v == "function");
this.propertyValue(name, (type & 1 && cast) ? function () {
var x = v.apply(this, arguments);
return (x != null) ? cast(x) : null;
} : (((v != null) && cast) ? cast(v) : v)).type = type;
return this;
}
return this.instance()[name];
};
};
/** @private Sets the value of the property <i>name</i> to <i>v</i>. */
pv.Mark.prototype.propertyValue = function (name, v) {
var properties = this.$properties, p = {name: name, id: pv.id(), value: v};
for (var i = 0; i < properties.length; i++) {
if (properties[i].name == name) {
properties.splice(i, 1);
break;
}
}
properties.push(p);
return p;
};
/* Define all global properties. */
pv.Mark.prototype
.property("data")
.property("visible", Boolean)
.property("left", Number)
.property("right", Number)
.property("top", Number)
.property("bottom", Number)
.property("cursor", String)
.property("title", String)
.property("reverse", Boolean)
.property("antialias", Boolean)
.property("events", String);
/**
* The mark type; a lower camelCase name. The type name controls rendering
* behavior, and unless the rendering engine is extended, must be one of the
* built-in concrete mark types: area, bar, dot, image, label, line, panel,
* rule, or wedge.
*
* @type string
* @name pv.Mark.prototype.type
*/
/**
* The mark prototype, possibly undefined, from which to inherit property
* functions. The mark prototype is not necessarily of the same type as this
* mark. Any properties defined on this mark will override properties inherited
* either from the prototype or from the type-specific defaults.
*
* @type pv.Mark
* @name pv.Mark.prototype.proto
*/
/**
* The mark anchor target, possibly undefined.
*
* @type pv.Mark
* @name pv.Mark.prototype.target
*/
/**
* The enclosing parent panel. The parent panel is generally undefined only for
* the root panel; however, it is possible to create "offscreen" marks that are
* used only for inheritance purposes.
*
* @type pv.Panel
* @name pv.Mark.prototype.parent
*/
/**
* The child index. -1 if the enclosing parent panel is null; otherwise, the
* zero-based index of this mark into the parent panel's <tt>children</tt> array.
*
* @type number
*/
pv.Mark.prototype.childIndex = -1;
/**
* The mark index. The value of this field depends on which instance (i.e.,
* which element of the data array) is currently being evaluated. During the
* build phase, the index is incremented over each datum; when handling events,
* the index is set to the instance that triggered the event.
*
* @type number
*/
pv.Mark.prototype.index = -1;
/**
* The current scale factor, based on any enclosing transforms. The current
* scale can be used to create scale-independent graphics. For example, to
* define a dot that has a radius of 10 irrespective of any zooming, say:
*
* <pre>dot.radius(function() 10 / this.scale)</pre>
*
* Note that the stroke width and font size are defined irrespective of scale
* (i.e., in screen space) already. Also note that when a transform is applied
* to a panel, the scale affects only the child marks, not the panel itself.
*
* @type number
* @see pv.Panel#transform
*/
pv.Mark.prototype.scale = 1;
/**
* @private The scene graph. The scene graph is an array of objects; each object
* (or "node") corresponds to an instance of this mark and an element in the
* data array. The scene graph can be traversed to lookup previously-evaluated
* properties.
*
* @name pv.Mark.prototype.scene
*/
/**
* The root parent panel. This may be undefined for "offscreen" marks that are
* created for inheritance purposes only.
*
* @type pv.Panel
* @name pv.Mark.prototype.root
*/
/**
* The data property; an array of objects. The size of the array determines the
* number of marks that will be instantiated; each element in the array will be
* passed to property functions to compute the property values. Typically, the
* data property is specified as a constant array, such as
*
* <pre>m.data([1, 2, 3, 4, 5]);</pre>
*
* However, it is perfectly acceptable to define the data property as a
* function. This function might compute the data dynamically, allowing
* different data to be used per enclosing panel. For instance, in the stacked
* area graph example (see {@link #scene}), the data function on the area mark
* dereferences each series.
*
* @type array
* @name pv.Mark.prototype.data
*/
/**
* The visible property; a boolean determining whether or not the mark instance
* is visible. If a mark instance is not visible, its other properties will not
* be evaluated. Similarly, for panels no child marks will be rendered.
*
* @type boolean
* @name pv.Mark.prototype.visible
*/
/**
* The left margin; the distance, in pixels, between the left edge of the
* enclosing panel and the left edge of this mark. Note that in some cases this
* property may be redundant with the right property, or with the conjunction of
* right and width.
*
* @type number
* @name pv.Mark.prototype.left
*/
/**
* The right margin; the distance, in pixels, between the right edge of the
* enclosing panel and the right edge of this mark. Note that in some cases this
* property may be redundant with the left property, or with the conjunction of
* left and width.
*
* @type number
* @name pv.Mark.prototype.right
*/
/**
* The top margin; the distance, in pixels, between the top edge of the
* enclosing panel and the top edge of this mark. Note that in some cases this
* property may be redundant with the bottom property, or with the conjunction
* of bottom and height.
*
* @type number
* @name pv.Mark.prototype.top
*/
/**
* The bottom margin; the distance, in pixels, between the bottom edge of the
* enclosing panel and the bottom edge of this mark. Note that in some cases
* this property may be redundant with the top property, or with the conjunction
* of top and height.
*
* @type number
* @name pv.Mark.prototype.bottom
*/
/**
* The cursor property; corresponds to the CSS cursor property. This is
* typically used in conjunction with event handlers to indicate interactivity.
*
* @type string
* @name pv.Mark.prototype.cursor
* @see <a href="http://www.w3.org/TR/CSS2/ui.html#propdef-cursor">CSS2 cursor</a>
*/
/**
* The title property; corresponds to the HTML/SVG title property, allowing the
* general of simple plain text tooltips.
*
* @type string
* @name pv.Mark.prototype.title
*/
/**
* The events property; corresponds to the SVG pointer-events property,
* specifying how the mark should participate in mouse events. The default value
* is "painted". Supported values are:
*
* <p>"painted": The given mark may receive events when the mouse is over a
* "painted" area. The painted areas are the interior (i.e., fill) of the mark
* if a 'fillStyle' is specified, and the perimeter (i.e., stroke) of the mark
* if a 'strokeStyle' is specified.
*
* <p>"all": The given mark may receive events when the mouse is over either the
* interior (i.e., fill) or the perimeter (i.e., stroke) of the mark, regardless
* of the specified fillStyle and strokeStyle.
*
* <p>"none": The given mark may not receive events.
*
* @type string
* @name pv.Mark.prototype.events
*/
/**
* The reverse property; a boolean determining whether marks are ordered from
* front-to-back or back-to-front. SVG does not support explicit z-ordering;
* shapes are rendered in the order they appear. Thus, by default, marks are
* rendered in data order. Setting the reverse property to false reverses the
* order in which they are rendered; however, the properties are still evaluated
* (i.e., built) in forward order.
*
* @type boolean
* @name pv.Mark.prototype.reverse
*/
/**
* Default properties for all mark types. By default, the data array is the
* parent data as a single-element array; if the data property is not specified,
* this causes each mark to be instantiated as a singleton with the parents
* datum. The visible property is true by default, and the reverse property is
* false.
*
* @type pv.Mark
*/
pv.Mark.prototype.defaults = new pv.Mark()
.data(function (d) {
return [d];
})
.visible(true)
.antialias(true)
.events("painted");
/**
* Sets the prototype of this mark to the specified mark. Any properties not
* defined on this mark may be inherited from the specified prototype mark, or
* its prototype, and so on. The prototype mark need not be the same type of
* mark as this mark. (Note that for inheritance to be useful, properties with
* the same name on different mark types should have equivalent meaning.)
*
* @param {pv.Mark} proto the new prototype.
* @returns {pv.Mark} this mark.
* @see #add
*/
pv.Mark.prototype.extend = function (proto) {
this.proto = proto;
this.target = proto.target;
return this;
};
/**
* Adds a new mark of the specified type to the enclosing parent panel, whilst
* simultaneously setting the prototype of the new mark to be this mark.
*
* @param {function} type the type of mark to add; a constructor, such as
* <tt>pv.Bar</tt>.
* @returns {pv.Mark} the new mark.
* @see #extend
*/
pv.Mark.prototype.add = function (type) {
return this.parent.add(type).extend(this);
};
/**
* Defines a custom property on this mark. Custom properties are currently
* fixed, in that they are initialized once per mark set (i.e., per parent panel
* instance). Custom properties can be used to store local state for the mark,
* such as data needed by other properties (e.g., a custom scale) or interaction
* state.
*
* <p>WARNING We plan on changing this feature in a future release to define
* standard properties, as opposed to <i>fixed</i> properties that behave
* idiosyncratically within event handlers. Furthermore, we recommend storing
* state in an external data structure, rather than tying it to the
* visualization specification as with defs.
*
* @param {string} name the name of the local variable.
* @param {function} [v] an optional initializer; may be a constant or a
* function.
*/
pv.Mark.prototype.def = function (name, v) {
this.propertyMethod(name, true);
return this[name](arguments.length > 1 ? v : null);
};
/**
* Returns an anchor with the specified name. All marks support the five
* standard anchor names:<ul>
*
* <li>top
* <li>left
* <li>center
* <li>bottom
* <li>right
*
* </ul>In addition to positioning properties (left, right, top bottom), the
* anchors support text rendering properties (text-align, text-baseline). Text is
* rendered to appear inside the mark by default.
*
* <p>To facilitate stacking, anchors are defined in terms of their opposite
* edge. For example, the top anchor defines the bottom property, such that the
* mark extends upwards; the bottom anchor instead defines the top property,
* such that the mark extends downwards. See also {@link pv.Layout.Stack}.
*
* <p>While anchor names are typically constants, the anchor name is a true
* property, which means you can specify a function to compute the anchor name
* dynamically. See the {@link pv.Anchor#name} property for details.
*
* @param {string} name the anchor name; either a string or a property function.
* @returns {pv.Anchor} the new anchor.
*/
pv.Mark.prototype.anchor = function (name) {
if (!name)
name = "center"; // default anchor name
return new pv.Anchor(this)
.name(name)
.data(function () {
return this.scene.target.map(function (s) {
return s.data;
});
})
.visible(function () {
return this.scene.target[this.index].visible;
})
.left(function () {
var s = this.scene.target[this.index], w = s.width || 0;
switch (this.name()) {
case "bottom":
case "top":
case "center":
return s.left + w / 2;
case "left":
return null;
}
return s.left + w;
})
.top(function () {
var s = this.scene.target[this.index], h = s.height || 0;
switch (this.name()) {
case "left":
case "right":
case "center":
return s.top + h / 2;
case "top":
return null;
}
return s.top + h;
})
.right(function () {
var s = this.scene.target[this.index];
return this.name() == "left" ? s.right + (s.width || 0) : null;
})
.bottom(function () {
var s = this.scene.target[this.index];
return this.name() == "top" ? s.bottom + (s.height || 0) : null;
})
.textAlign(function () {
switch (this.name()) {
case "bottom":
case "top":
case "center":
return "center";
case "right":
return "right";
}
return "left";
})
.textBaseline(function () {
switch (this.name()) {
case "right":
case "left":
case "center":
return "middle";
case "top":
return "top";
}
return "bottom";
});
};
/** @deprecated Replaced by {@link #target}. */
pv.Mark.prototype.anchorTarget = function () {
return this.target;
};
/**
* Alias for setting the left, right, top and bottom properties simultaneously.
*
* @see #left
* @see #right
* @see #top
* @see #bottom
* @returns {pv.Mark} this.
*/
pv.Mark.prototype.margin = function (n) {
return this.left(n).right(n).top(n).bottom(n);
};
/**
* @private Returns the current instance of this mark in the scene graph. This
* is typically equivalent to <tt>this.scene[this.index]</tt>, however if the
* scene or index is unset, the default instance of the mark is returned. If no
* default is set, the default is the last instance. Similarly, if the scene or
* index of the parent panel is unset, the default instance of this mark in the
* last instance of the enclosing panel is returned, and so on.
*
* @returns a node in the scene graph.
*/
pv.Mark.prototype.instance = function (defaultIndex) {
var scene = this.scene || this.parent.instance(-1).children[this.childIndex],
index = !arguments.length || this.hasOwnProperty("index") ? this.index : defaultIndex;
return scene[index < 0 ? scene.length - 1 : index];
};
/**
* @private Find the instances of this mark that match source.
*
* @see pv.Anchor
*/
pv.Mark.prototype.instances = function (source) {
var mark = this, index = [], scene;
/* Mirrored descent. */
while (!(scene = mark.scene)) {
source = source.parent;
index.push({index: source.index, childIndex: mark.childIndex});
mark = mark.parent;
}
while (index.length) {
var i = index.pop();
scene = scene[i.index].children[i.childIndex];
}
/*
* When the anchor target is also an ancestor, as in the case of adding
* to a panel anchor, only generate one instance per panel. Also, set
* the margins to zero, since they are offset by the enclosing panel.
*/
if (this.hasOwnProperty("index")) {
var s = pv.extend(scene[this.index]);
s.right = s.top = s.left = s.bottom = 0;
return [s];
}
return scene;
};
/**
* @private Returns the first instance of this mark in the scene graph. This
* method can only be called when the mark is bound to the scene graph (for
* example, from an event handler, or within a property function).
*
* @returns a node in the scene graph.
*/
pv.Mark.prototype.first = function () {
return this.scene[0];
};
/**
* @private Returns the last instance of this mark in the scene graph. This
* method can only be called when the mark is bound to the scene graph (for
* example, from an event handler, or within a property function). In addition,
* note that mark instances are built sequentially, so the last instance of this
* mark may not yet be constructed.
*
* @returns a node in the scene graph.
*/
pv.Mark.prototype.last = function () {
return this.scene[this.scene.length - 1];
};
/**
* @private Returns the previous instance of this mark in the scene graph, or
* null if this is the first instance.
*
* @returns a node in the scene graph, or null.
*/
pv.Mark.prototype.sibling = function () {
return (this.index == 0) ? null : this.scene[this.index - 1];
};
/**
* @private Returns the current instance in the scene graph of this mark, in the
* previous instance of the enclosing parent panel. May return null if this
* instance could not be found.
*
* @returns a node in the scene graph, or null.
*/
pv.Mark.prototype.cousin = function () {
var p = this.parent, s = p && p.sibling();
return (s && s.children) ? s.children[this.childIndex][this.index] : null;
};
/**
* Renders this mark, including recursively rendering all child marks if this is
* a panel. This method finds all instances of this mark and renders them. This
* method descends recursively to the level of the mark to be rendered, finding
* all visible instances of the mark. After the marks are rendered, the scene
* and index attributes are removed from the mark to restore them to a clean
* state.
*
* <p>If an enclosing panel has an index property set (as is the case inside in
* an event handler), then only instances of this mark inside the given instance
* of the panel will be rendered; otherwise, all visible instances of the mark
* will be rendered.
*/
pv.Mark.prototype.render = function () {
var parent = this.parent,
stack = pv.Mark.stack;
/* For the first render, take it from the top. */
if (parent && !this.root.scene) {
this.root.render();
return;
}
/* Record the path to this mark. */
var indexes = [];
for (var mark = this; mark.parent; mark = mark.parent) {
indexes.unshift(mark.childIndex);
}
/** @private */
function render(mark, depth, scale) {
mark.scale = scale;
if (depth < indexes.length) {
stack.unshift(null);
if (mark.hasOwnProperty("index")) {
renderInstance(mark, depth, scale);
} else {
for (var i = 0, n = mark.scene.length; i < n; i++) {
mark.index = i;
renderInstance(mark, depth, scale);
}
delete mark.index;
}
stack.shift();
} else {
mark.build();
/*
* In the update phase, the scene is rendered by creating and updating
* elements and attributes in the SVG image. No properties are evaluated
* during the update phase; instead the values computed previously in the
* build phase are simply translated into SVG. The update phase is
* decoupled (see pv.Scene) to allow different rendering engines.
*/
pv.Scene.scale = scale;
pv.Scene.updateAll(mark.scene);
}
delete mark.scale;
}
/**
* @private Recursively renders the current instance of the specified mark.
* This is slightly tricky because `index` and `scene` properties may or may
* not already be set; if they are set, it means we are rendering only a
* specific instance; if they are unset, we are rendering all instances.
* Furthermore, we must preserve the original context of these properties when
* rendering completes.
*
* <p>Another tricky aspect is that the `scene` attribute should be set for
* any preceding children, so as to allow property chaining. This is
* consistent with first-pass rendering.
*/
function renderInstance(mark, depth, scale) {
var s = mark.scene[mark.index], i;
if (s.visible) {
var childIndex = indexes[depth],
child = mark.children[childIndex];
/* Set preceding child scenes. */
for (i = 0; i < childIndex; i++) {
mark.children[i].scene = s.children[i];
}
/* Set current child scene, if necessary. */
stack[0] = s.data;
if (child.scene) {
render(child, depth + 1, scale * s.transform.k);
} else {
child.scene = s.children[childIndex];
render(child, depth + 1, scale * s.transform.k);
delete child.scene;
}
/* Clear preceding child scenes. */
for (i = 0; i < childIndex; i++) {
delete mark.children[i].scene;
}
}
}
/* Bind this mark's property definitions. */
this.bind();
/* The render context is the first ancestor with an explicit index. */
while (parent && !parent.hasOwnProperty("index"))
parent = parent.parent;
/* Recursively render all instances of this mark. */
this.context(
parent ? parent.scene : undefined,
parent ? parent.index : -1,
function () {
render(this.root, 0, 1);
});
};
/** @private Stores the current data stack. */
pv.Mark.stack = [];
/**
* @private In the bind phase, inherited property definitions are cached so they
* do not need to be queried during build.
*/
pv.Mark.prototype.bind = function () {
var seen = {}, types = [[], [], [], []], data, visible;
/** Scans the proto chain for the specified mark. */
function bind(mark) {
do {
var properties = mark.$properties;
for (var i = properties.length - 1; i >= 0; i--) {
var p = properties[i];
if (!(p.name in seen)) {
seen[p.name] = p;
switch (p.name) {
case "data":
data = p;
break;
case "visible":
visible = p;
break;
default:
types[p.type].push(p);
break;
}
}
}
} while (mark = mark.proto);
}
/* Scan the proto chain for all defined properties. */
bind(this);
bind(this.defaults);
types[1].reverse();
types[3].reverse();
/* Any undefined properties are null. */
var mark = this;
do
for (var name in mark.properties) {
if (!(name in seen)) {
types[2].push(seen[name] = {name: name, type: 2, value: null});
}
}
while (mark = mark.proto);
/* Define setter-getter for inherited defs. */
var defs = types[0].concat(types[1]);
for (var i = 0; i < defs.length; i++) {
this.propertyMethod(defs[i].name, true);
}
/* Setup binds to evaluate constants before functions. */
this.binds = {
properties: seen,
data: data,
defs: defs,
required: [visible],
optional: pv.blend(types)
};
};
/**
* @private Evaluates properties and computes implied properties. Properties are
* stored in the {@link #scene} array for each instance of this mark.
*
* <p>As marks are built recursively, the {@link #index} property is updated to
* match the current index into the data array for each mark. Note that the
* index property is only set for the mark currently being built and its
* enclosing parent panels. The index property for other marks is unset, but is
* inherited from the global <tt>Mark</tt> class prototype. This allows mark
* properties to refer to properties on other marks <i>in the same panel</i>
* conveniently; however, in general it is better to reference mark instances
* specifically through the scene graph rather than depending on the magical
* behavior of {@link #index}.
*
* <p>The root scene array has a special property, <tt>data</tt>, which stores
* the current data stack. The first element in this stack is the current datum,
* followed by the datum of the enclosing parent panel, and so on. The data
* stack should not be accessed directly; instead, property functions are passed
* the current data stack as arguments.
*
* <p>The evaluation of the <tt>data</tt> and <tt>visible</tt> properties is
* special. The <tt>data</tt> property is evaluated first; unlike the other
* properties, the data stack is from the parent panel, rather than the current
* mark, since the data is not defined until the data property is evaluated.
* The <tt>visisble</tt> property is subsequently evaluated for each instance;
* only if true will the {@link #buildInstance} method be called, evaluating
* other properties and recursively building the scene graph.
*
* <p>If this mark is being re-built, any old instances of this mark that no
* longer exist (because the new data array contains fewer elements) will be
* cleared using {@link #clearInstance}.
*
* @param parent the instance of the parent panel from the scene graph.
*/
pv.Mark.prototype.build = function () {
var scene = this.scene, stack = pv.Mark.stack;
if (!scene) {
scene = this.scene = [];
scene.mark = this;
scene.type = this.type;
scene.childIndex = this.childIndex;
if (this.parent) {
scene.parent = this.parent.scene;
scene.parentIndex = this.parent.index;
}
}
/* Resolve anchor target. */
if (this.target)
scene.target = this.target.instances(scene);
/* Evaluate defs. */
if (this.binds.defs.length) {
var defs = scene.defs;
if (!defs)
scene.defs = defs = {};
for (var i = 0; i < this.binds.defs.length; i++) {
var p = this.binds.defs[i], d = defs[p.name];
if (!d || (p.id > d.id)) {
defs[p.name] = {
id: 0, // this def will be re-evaluated on next build
value: (p.type & 1) ? p.value.apply(this, stack) : p.value
};
}
}
}
/* Evaluate special data property. */
var data = this.binds.data;
data = data.type & 1 ? data.value.apply(this, stack) : data.value;
/* Create, update and delete scene nodes. */
stack.unshift(null);
scene.length = data.length;
for (var i = 0; i < data.length; i++) {
pv.Mark.prototype.index = this.index = i;
var s = scene[i];
if (!s)
scene[i] = s = {};
s.data = stack[0] = data[i];
this.buildInstance(s);
}
pv.Mark.prototype.index = -1;
delete this.index;
stack.shift();
return this;
};
/**
* @private Evaluates the specified array of properties for the specified
* instance <tt>s</tt> in the scene graph.
*
* @param s a node in the scene graph; the instance of the mark to build.
* @param properties an array of properties.
*/
pv.Mark.prototype.buildProperties = function (s, properties) {
for (var i = 0, n = properties.length; i < n; i++) {
var p = properties[i], v = p.value; // assume case 2 (constant)
switch (p.type) {
case 0:
case 1:
v = this.scene.defs[p.name].value;
break;
case 3:
v = v.apply(this, pv.Mark.stack);
break;
}
s[p.name] = v;
}
};
/**
* @private Evaluates all of the properties for this mark for the specified
* instance <tt>s</tt> in the scene graph. The set of properties to evaluate is
* retrieved from the {@link #properties} array for this mark type (see {@link
* #type}). After these properties are evaluated, any <b>implied</b> properties
* may be computed by the mark and set on the scene graph; see
* {@link #buildImplied}.
*
* <p>For panels, this method recursively builds the scene graph for all child
* marks as well. In general, this method should not need to be overridden by
* concrete mark types.
*
* @param s a node in the scene graph; the instance of the mark to build.
*/
pv.Mark.prototype.buildInstance = function (s) {
this.buildProperties(s, this.binds.required);
if (s.visible) {
this.buildProperties(s, this.binds.optional);
this.buildImplied(s);
}
};
/**
* @private Computes the implied properties for this mark for the specified
* instance <tt>s</tt> in the scene graph. Implied properties are those with
* dependencies on multiple other properties; for example, the width property
* may be implied if the left and right properties are set. This method can be
* overridden by concrete mark types to define new implied properties, if
* necessary.
*
* @param s a node in the scene graph; the instance of the mark to build.
*/
pv.Mark.prototype.buildImplied = function (s) {
var l = s.left;
var r = s.right;
var t = s.top;
var b = s.bottom;
/* Assume width and height are zero if not supported by this mark type. */
var p = this.properties;
var w = p.width ? s.width : 0;
var h = p.height ? s.height : 0;
/* Compute implied width, right and left. */
var width = this.parent ? this.parent.width() : (w + l + r);
if (w == null) {
w = width - (r = r || 0) - (l = l || 0);
} else if (r == null) {
if (l == null) {
l = r = (width - w) / 2;
} else {
r = width - w - (l = l || 0);
}
} else if (l == null) {
l = width - w - r;
}
/* Compute implied height, bottom and top. */
var height = this.parent ? this.parent.height() : (h + t + b);
if (h == null) {
h = height - (t = t || 0) - (b = b || 0);
} else if (b == null) {
if (t == null) {
b = t = (height - h) / 2;
} else {
b = height - h - (t = t || 0);
}
} else if (t == null) {
t = height - h - b;
}
s.left = l;
s.right = r;
s.top = t;
s.bottom = b;
/* Only set width and height if they are supported by this mark type. */
if (p.width)
s.width = w;
if (p.height)
s.height = h;
/* Set any null colors to pv.Color.transparent. */
if (p.textStyle && !s.textStyle)
s.textStyle = pv.Color.transparent;
if (p.fillStyle && !s.fillStyle)
s.fillStyle = pv.Color.transparent;
if (p.strokeStyle && !s.strokeStyle)
s.strokeStyle = pv.Color.transparent;
};
/**
* Returns the current location of the mouse (cursor) relative to this mark's
* parent. The <i>x</i> coordinate corresponds to the left margin, while the
* <i>y</i> coordinate corresponds to the top margin.
*
* @returns {pv.Vector} the mouse location.
*/
pv.Mark.prototype.mouse = function () {
/* Compute xy-coordinates relative to the panel. */
var x = pv.event.pageX || 0,
y = pv.event.pageY || 0,
n = this.root.canvas();
do {
x -= n.offsetLeft;
y -= n.offsetTop;
} while (n = n.offsetParent);
/* Compute the inverse transform of all enclosing panels. */
var t = pv.Transform.identity,
p = this.properties.transform ? this : this.parent,
pz = [];
do {
pz.push(p);
} while (p = p.parent);
while (p = pz.pop())
t = t.translate(p.left(), p.top()).times(p.transform());
t = t.invert();
return pv.vector(x * t.k + t.x, y * t.k + t.y);
};
/**
* Registers an event handler for the specified event type with this mark. When
* an event of the specified type is triggered, the specified handler will be
* invoked. The handler is invoked in a similar method to property functions:
* the context is <tt>this</tt> mark instance, and the arguments are the full
* data stack. Event handlers can use property methods to manipulate the display
* properties of the mark:
*
* <pre>m.event("click", function() this.fillStyle("red"));</pre>
*
* Alternatively, the external data can be manipulated and the visualization
* redrawn:
*
* <pre>m.event("click", function(d) {
* data = all.filter(function(k) k.name == d);
* vis.render();
* });</pre>
*
* The return value of the event handler determines which mark gets re-rendered.
* Use defs ({@link #def}) to set temporary state from event handlers.
*
* <p>The complete set of event types is defined by SVG; see the reference
* below. The set of supported event types is:<ul>
*
* <li>click
* <li>mousedown
* <li>mouseup
* <li>mouseover
* <li>mousemove
* <li>mouseout
*
* </ul>Since Protovis does not specify any concept of focus, it does not
* support key events; these should be handled outside the visualization using
* standard JavaScript. In the future, support for interaction may be extended
* to support additional event types, particularly those most relevant to
* interactive visualization, such as selection.
*
* <p>TODO In the current implementation, event handlers are not inherited from
* prototype marks. They must be defined explicitly on each interactive mark. In
* addition, only one event handler for a given event type can be defined; when
* specifying multiple event handlers for the same type, only the last one will
* be used.
*
* @see <a href="http://www.w3.org/TR/SVGTiny12/interact.html#SVGEvents">SVG events</a>
* @param {string} type the event type.
* @param {function} handler the event handler.
* @returns {pv.Mark} this.
*/
pv.Mark.prototype.event = function (type, handler) {
this.$handlers[type] = pv.functor(handler);
return this;
};
/** @private Evaluates the function <i>f</i> with the specified context. */
pv.Mark.prototype.context = function (scene, index, f) {
var proto = pv.Mark.prototype,
stack = pv.Mark.stack,
oscene = pv.Mark.scene,
oindex = proto.index;
/** @private Sets the context. */
function apply(scene, index) {
pv.Mark.scene = scene;
proto.index = index;
if (!scene)
return;
var that = scene.mark,
mark = that,
ancestors = [];
/* Set ancestors' scene and index; populate data stack. */
do {
ancestors.push(mark);
stack.push(scene[index].data);
mark.index = index;
mark.scene = scene;
index = scene.parentIndex;
scene = scene.parent;
} while (mark = mark.parent);
/* Set ancestors' scale; requires top-down. */
for (var i = ancestors.length - 1, k = 1; i > 0; i--) {
mark = ancestors[i];
mark.scale = k;
k *= mark.scene[mark.index].transform.k;
}
/* Set children's scene and scale. */
if (that.children)
for (var i = 0, n = that.children.length; i < n; i++) {
mark = that.children[i];
mark.scene = that.scene[that.index].children[i];
mark.scale = k;
}
}
/** @private Clears the context. */
function clear(scene, index) {
if (!scene)
return;
var that = scene.mark,
mark;
/* Reset children. */
if (that.children)
for (var i = 0, n = that.children.length; i < n; i++) {
mark = that.children[i];
delete mark.scene;
delete mark.scale;
}
/* Reset ancestors. */
mark = that;
do {
stack.pop();
if (mark.parent) {
delete mark.scene;
delete mark.scale;
}
delete mark.index;
} while (mark = mark.parent);
}
/* Context switch, invoke the function, then switch back. */
clear(oscene, oindex);
apply(scene, index);
try {
f.apply(this, stack);
} finally {
clear(scene, index);
apply(oscene, oindex);
}
};
/** @private Execute the event listener, then re-render. */
pv.Mark.dispatch = function (type, scene, index) {
var m = scene.mark, p = scene.parent, l = m.$handlers[type];
if (!l)
return p && pv.Mark.dispatch(type, p, scene.parentIndex);
m.context(scene, index, function () {
m = l.apply(m, pv.Mark.stack);
if (m && m.render)
m.render();
});
return true;
};
/**
* Constructs a new mark anchor with default properties.
*
* @class Represents an anchor on a given mark. An anchor is itself a mark, but
* without a visual representation. It serves only to provide useful default
* properties that can be inherited by other marks. Each type of mark can define
* any number of named anchors for convenience. If the concrete mark type does
* not define an anchor implementation specifically, one will be inherited from
* the mark's parent class.
*
* <p>For example, the bar mark provides anchors for its four sides: left,
* right, top and bottom. Adding a label to the top anchor of a bar,
*
* <pre>bar.anchor("top").add(pv.Label);</pre>
*
* will render a text label on the top edge of the bar; the top anchor defines
* the appropriate position properties (top and left), as well as text-rendering
* properties for convenience (textAlign and textBaseline).
*
* <p>Note that anchors do not <i>inherit</i> from their targets; the positional
* properties are copied from the scene graph, which guarantees that the anchors
* are positioned correctly, even if the positional properties are not defined
* deterministically. (In addition, it also improves performance by avoiding
* re-evaluating expensive properties.) If you want the anchor to inherit from
* the target, use {@link pv.Mark#extend} before adding. For example:
*
* <pre>bar.anchor("top").extend(bar).add(pv.Label);</pre>
*
* The anchor defines it's own positional properties, but other properties (such
* as the title property, say) can be inherited using the above idiom. Also note
* that you can override positional properties in the anchor for custom
* behavior.
*
* @extends pv.Mark
* @param {pv.Mark} target the anchor target.
*/
pv.Anchor = function (target) {
pv.Mark.call(this);
this.target = target;
this.parent = target.parent;
};
pv.Anchor.prototype = pv.extend(pv.Mark)
.property("name", String);
/**
* The anchor name. The set of supported anchor names is dependent on the
* concrete mark type; see the mark type for details. For example, bars support
* left, right, top and bottom anchors.
*
* <p>While anchor names are typically constants, the anchor name is a true
* property, which means you can specify a function to compute the anchor name
* dynamically. For instance, if you wanted to alternate top and bottom anchors,
* saying
*
* <pre>m.anchor(function() (this.index % 2) ? "top" : "bottom").add(pv.Dot);</pre>
*
* would have the desired effect.
*
* @type string
* @name pv.Anchor.prototype.name
*/
/**
* Sets the prototype of this anchor to the specified mark. Any properties not
* defined on this mark may be inherited from the specified prototype mark, or
* its prototype, and so on. The prototype mark need not be the same type of
* mark as this mark. (Note that for inheritance to be useful, properties with
* the same name on different mark types should have equivalent meaning.)
*
* <p>This method differs slightly from the normal mark behavior in that the
* anchor's target is preserved.
*
* @param {pv.Mark} proto the new prototype.
* @returns {pv.Anchor} this anchor.
* @see pv.Mark#add
*/
pv.Anchor.prototype.extend = function (proto) {
this.proto = proto;
return this;
};
/**
* Constructs a new area mark with default properties. Areas are not typically
* constructed directly, but by adding to a panel or an existing mark via
* {@link pv.Mark#add}.
*
* @class Represents an area mark: the solid area between two series of
* connected line segments. Unsurprisingly, areas are used most frequently for
* area charts.
*
* <p>Just as a line represents a polyline, the <tt>Area</tt> mark type
* represents a <i>polygon</i>. However, an area is not an arbitrary polygon;
* vertices are paired either horizontally or vertically into parallel
* <i>spans</i>, and each span corresponds to an associated datum. Either the
* width or the height must be specified, but not both; this determines whether
* the area is horizontally-oriented or vertically-oriented. Like lines, areas
* can be stroked and filled with arbitrary colors.
*
* <p>See also the <a href="../../api/Area.html">Area guide</a>.
*
* @extends pv.Mark
*/
pv.Area = function () {
pv.Mark.call(this);
};
pv.Area.prototype = pv.extend(pv.Mark)
.property("width", Number)
.property("height", Number)
.property("lineWidth", Number)
.property("strokeStyle", pv.color)
.property("fillStyle", pv.color)
.property("segmented", Boolean)
.property("interpolate", String)
.property("tension", Number);
pv.Area.prototype.type = "area";
/**
* The width of a given span, in pixels; used for horizontal spans. If the width
* is specified, the height property should be 0 (the default). Either the top
* or bottom property should be used to space the spans vertically, typically as
* a multiple of the index.
*
* @type number
* @name pv.Area.prototype.width
*/
/**
* The height of a given span, in pixels; used for vertical spans. If the height
* is specified, the width property should be 0 (the default). Either the left
* or right property should be used to space the spans horizontally, typically
* as a multiple of the index.
*
* @type number
* @name pv.Area.prototype.height
*/
/**
* The width of stroked lines, in pixels; used in conjunction with
* <tt>strokeStyle</tt> to stroke the perimeter of the area. Unlike the
* {@link Line} mark type, the entire perimeter is stroked, rather than just one
* edge. The default value of this property is 1.5, but since the default stroke
* style is null, area marks are not stroked by default.
*
* <p>This property is <i>fixed</i> for non-segmented areas. See
* {@link pv.Mark}.
*
* @type number
* @name pv.Area.prototype.lineWidth
*/
/**
* The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
* stroke the perimeter of the area. Unlike the {@link Line} mark type, the
* entire perimeter is stroked, rather than just one edge. The default value of
* this property is null, meaning areas are not stroked by default.
*
* <p>This property is <i>fixed</i> for non-segmented areas. See
* {@link pv.Mark}.
*
* @type string
* @name pv.Area.prototype.strokeStyle
* @see pv.color
*/
/**
* The area fill style; if non-null, the interior of the polygon forming the
* area is filled with the specified color. The default value of this property
* is a categorical color.
*
* <p>This property is <i>fixed</i> for non-segmented areas. See
* {@link pv.Mark}.
*
* @type string
* @name pv.Area.prototype.fillStyle
* @see pv.color
*/
/**
* Whether the area is segmented; whether variations in fill style, stroke
* style, and the other properties are treated as fixed. Rendering segmented
* areas is noticeably slower than non-segmented areas.
*
* <p>This property is <i>fixed</i>. See {@link pv.Mark}.
*
* @type boolean
* @name pv.Area.prototype.segmented
*/
/**
* How to interpolate between values. Linear interpolation ("linear") is the
* default, producing a straight line between points. For piecewise constant
* functions (i.e., step functions), either "step-before" or "step-after" can be
* specified. To draw open uniform b-splines, specify "basis". To draw cardinal
* splines, specify "cardinal"; see also {@link #tension}.
*
* <p>This property is <i>fixed</i>. See {@link pv.Mark}.
*
* @type string
* @name pv.Area.prototype.interpolate
*/
/**
* The tension of cardinal splines; used in conjunction with
* interpolate("cardinal"). A value between 0 and 1 draws cardinal splines with
* the given tension. In some sense, the tension can be interpreted as the
* "length" of the tangent; a tension of 1 will yield all zero tangents (i.e.,
* linear interpolation), and a tension of 0 yields a Catmull-Rom spline. The
* default value is 0.7.
*
* <p>This property is <i>fixed</i>. See {@link pv.Mark}.
*
* @type number
* @name pv.Area.prototype.tension
*/
/**
* Default properties for areas. By default, there is no stroke and the fill
* style is a categorical color.
*
* @type pv.Area
*/
pv.Area.prototype.defaults = new pv.Area()
.extend(pv.Mark.prototype.defaults)
.lineWidth(1.5)
.fillStyle(pv.Colors.category20().by(pv.parent))
.interpolate("linear")
.tension(.7);
/** @private Sets width and height to zero if null. */
pv.Area.prototype.buildImplied = function (s) {
if (s.height == null)
s.height = 0;
if (s.width == null)
s.width = 0;
pv.Mark.prototype.buildImplied.call(this, s);
};
/** @private Records which properties may be fixed. */
pv.Area.fixed = {
lineWidth: 1,
lineJoin: 1,
strokeStyle: 1,
fillStyle: 1,
segmented: 1,
interpolate: 1,
tension: 1
};
/**
* @private Make segmented required, such that this fixed property is always
* evaluated, even if the first segment is not visible. Also cache which
* properties are normally fixed.
*/
pv.Area.prototype.bind = function () {
pv.Mark.prototype.bind.call(this);
var binds = this.binds,
required = binds.required,
optional = binds.optional;
for (var i = 0, n = optional.length; i < n; i++) {
var p = optional[i];
p.fixed = p.name in pv.Area.fixed;
if (p.name == "segmented") {
required.push(p);
optional.splice(i, 1);
i--;
n--;
}
}
/* Cache the original arrays so they can be restored on build. */
this.binds.$required = required;
this.binds.$optional = optional;
};
/**
* @private Override the default build behavior such that fixed properties are
* determined dynamically, based on the value of the (always) fixed segmented
* property. Any fixed properties are only evaluated on the first instance,
* although their values are propagated to subsequent instances, so that they
* are available for property chaining and the like.
*/
pv.Area.prototype.buildInstance = function (s) {
var binds = this.binds;
/* Handle fixed properties on secondary instances. */
if (this.index) {
var fixed = binds.fixed;
/* Determine which properties are fixed. */
if (!fixed) {
fixed = binds.fixed = [];
function f(p) {
return !p.fixed || (fixed.push(p), false);
}
binds.required = binds.required.filter(f);
if (!this.scene[0].segmented)
binds.optional = binds.optional.filter(f);
}
/* Copy fixed property values from the first instance. */
for (var i = 0, n = fixed.length; i < n; i++) {
var p = fixed[i].name;
s[p] = this.scene[0][p];
}
}
/* Evaluate all properties on the first instance. */
else {
binds.required = binds.$required;
binds.optional = binds.$optional;
binds.fixed = null;
}
pv.Mark.prototype.buildInstance.call(this, s);
};
/**
* Constructs a new area anchor with default properties. Areas support five
* different anchors:<ul>
*
* <li>top
* <li>left
* <li>center
* <li>bottom
* <li>right
*
* </ul>In addition to positioning properties (left, right, top bottom), the
* anchors support text rendering properties (text-align, text-baseline). Text
* is rendered to appear inside the area. The area anchor also propagates the
* interpolate, eccentricity, and tension properties such that an anchored area
* or line will match positions between control points.
*
* <p>For consistency with the other mark types, the anchor positions are
* defined in terms of their opposite edge. For example, the top anchor defines
* the bottom property, such that an area added to the top anchor grows upward.
*
* @param {string} name the anchor name; either a string or a property function.
* @returns {pv.Anchor}
*/
pv.Area.prototype.anchor = function (name) {
return pv.Mark.prototype.anchor.call(this, name)
.interpolate(function () {
return this.scene.target[this.index].interpolate;
})
.eccentricity(function () {
return this.scene.target[this.index].eccentricity;
})
.tension(function () {
return this.scene.target[this.index].tension;
});
};
/**
* Constructs a new bar mark with default properties. Bars are not typically
* constructed directly, but by adding to a panel or an existing mark via
* {@link pv.Mark#add}.
*
* @class Represents a bar: an axis-aligned rectangle that can be stroked and
* filled. Bars are used for many chart types, including bar charts, histograms
* and Gantt charts. Bars can also be used as decorations, for example to draw a
* frame border around a panel; in fact, a panel is a special type (a subclass)
* of bar.
*
* <p>Bars can be positioned in several ways. Most commonly, one of the four
* corners is fixed using two margins, and then the width and height properties
* determine the extent of the bar relative to this fixed location. For example,
* using the bottom and left properties fixes the bottom-left corner; the width
* then extends to the right, while the height extends to the top. As an
* alternative to the four corners, a bar can be positioned exclusively using
* margins; this is convenient as an inset from the containing panel, for
* example. See {@link pv.Mark} for details on the prioritization of redundant
* positioning properties.
*
* <p>See also the <a href="../../api/Bar.html">Bar guide</a>.
*
* @extends pv.Mark
*/
pv.Bar = function () {
pv.Mark.call(this);
};
pv.Bar.prototype = pv.extend(pv.Mark)
.property("width", Number)
.property("height", Number)
.property("lineWidth", Number)
.property("strokeStyle", pv.color)
.property("fillStyle", pv.color);
pv.Bar.prototype.type = "bar";
/**
* The width of the bar, in pixels. If the left position is specified, the bar
* extends rightward from the left edge; if the right position is specified, the
* bar extends leftward from the right edge.
*
* @type number
* @name pv.Bar.prototype.width
*/
/**
* The height of the bar, in pixels. If the bottom position is specified, the
* bar extends upward from the bottom edge; if the top position is specified,
* the bar extends downward from the top edge.
*
* @type number
* @name pv.Bar.prototype.height
*/
/**
* The width of stroked lines, in pixels; used in conjunction with
* <tt>strokeStyle</tt> to stroke the bar's border.
*
* @type number
* @name pv.Bar.prototype.lineWidth
*/
/**
* The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
* stroke the bar's border. The default value of this property is null, meaning
* bars are not stroked by default.
*
* @type string
* @name pv.Bar.prototype.strokeStyle
* @see pv.color
*/
/**
* The bar fill style; if non-null, the interior of the bar is filled with the
* specified color. The default value of this property is a categorical color.
*
* @type string
* @name pv.Bar.prototype.fillStyle
* @see pv.color
*/
/**
* Default properties for bars. By default, there is no stroke and the fill
* style is a categorical color.
*
* @type pv.Bar
*/
pv.Bar.prototype.defaults = new pv.Bar()
.extend(pv.Mark.prototype.defaults)
.lineWidth(1.5)
.fillStyle(pv.Colors.category20().by(pv.parent));
/**
* Constructs a new dot mark with default properties. Dots are not typically
* constructed directly, but by adding to a panel or an existing mark via
* {@link pv.Mark#add}.
*
* @class Represents a dot; a dot is simply a sized glyph centered at a given
* point that can also be stroked and filled. The <tt>size</tt> property is
* proportional to the area of the rendered glyph to encourage meaningful visual
* encodings. Dots can visually encode up to eight dimensions of data, though
* this may be unwise due to integrality. See {@link pv.Mark} for details on the
* prioritization of redundant positioning properties.
*
* <p>See also the <a href="../../api/Dot.html">Dot guide</a>.
*
* @extends pv.Mark
*/
pv.Dot = function () {
pv.Mark.call(this);
};
pv.Dot.prototype = pv.extend(pv.Mark)
.property("size", Number)
.property("radius", Number)
.property("shape", String)
.property("angle", Number)
.property("lineWidth", Number)
.property("strokeStyle", pv.color)
.property("fillStyle", pv.color);
pv.Dot.prototype.type = "dot";
/**
* The size of the dot, in square pixels. Square pixels are used such that the
* area of the dot is linearly proportional to the value of the size property,
* facilitating representative encodings.
*
* @see #radius
* @type number
* @name pv.Dot.prototype.size
*/
/**
* The radius of the dot, in pixels. This is an alternative to using
* {@link #size}.
*
* @see #size
* @type number
* @name pv.Dot.prototype.radius
*/
/**
* The shape name. Several shapes are supported:<ul>
*
* <li>cross
* <li>triangle
* <li>diamond
* <li>square
* <li>circle
* <li>tick
* <li>bar
*
* </ul>These shapes can be further changed using the {@link #angle} property;
* for instance, a cross can be turned into a plus by rotating. Similarly, the
* tick, which is vertical by default, can be rotated horizontally. Note that
* some shapes (cross and tick) do not have interior areas, and thus do not
* support fill style meaningfully.
*
* <p>Note: it may be more natural to use the {@link pv.Rule} mark for
* horizontal and vertical ticks. The tick shape is only necessary if angled
* ticks are needed.
*
* @type string
* @name pv.Dot.prototype.shape
*/
/**
* The rotation angle, in radians. Used to rotate shapes, such as to turn a
* cross into a plus.
*
* @type number
* @name pv.Dot.prototype.angle
*/
/**
* The width of stroked lines, in pixels; used in conjunction with
* <tt>strokeStyle</tt> to stroke the dot's shape.
*
* @type number
* @name pv.Dot.prototype.lineWidth
*/
/**
* The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
* stroke the dot's shape. The default value of this property is a categorical
* color.
*
* @type string
* @name pv.Dot.prototype.strokeStyle
* @see pv.color
*/
/**
* The fill style; if non-null, the interior of the dot is filled with the
* specified color. The default value of this property is null, meaning dots are
* not filled by default.
*
* @type string
* @name pv.Dot.prototype.fillStyle
* @see pv.color
*/
/**
* Default properties for dots. By default, there is no fill and the stroke
* style is a categorical color. The default shape is "circle" with size 20.
*
* @type pv.Dot
*/
pv.Dot.prototype.defaults = new pv.Dot()
.extend(pv.Mark.prototype.defaults)
.size(20)
.shape("circle")
.lineWidth(1.5)
.strokeStyle(pv.Colors.category10().by(pv.parent));
/**
* Constructs a new dot anchor with default properties. Dots support five
* different anchors:<ul>
*
* <li>top
* <li>left
* <li>center
* <li>bottom
* <li>right
*
* </ul>In addition to positioning properties (left, right, top bottom), the
* anchors support text rendering properties (text-align, text-baseline). Text is
* rendered to appear outside the dot. Note that this behavior is different from
* other mark anchors, which default to rendering text <i>inside</i> the mark.
*
* <p>For consistency with the other mark types, the anchor positions are
* defined in terms of their opposite edge. For example, the top anchor defines
* the bottom property, such that a bar added to the top anchor grows upward.
*
* @param {string} name the anchor name; either a string or a property function.
* @returns {pv.Anchor}
*/
pv.Dot.prototype.anchor = function (name) {
return pv.Mark.prototype.anchor.call(this, name)
.left(function () {
var s = this.scene.target[this.index];
switch (this.name()) {
case "bottom":
case "top":
case "center":
return s.left;
case "left":
return null;
}
return s.left + s.radius;
})
.right(function () {
var s = this.scene.target[this.index];
return this.name() == "left" ? s.right + s.radius : null;
})
.top(function () {
var s = this.scene.target[this.index];
switch (this.name()) {
case "left":
case "right":
case "center":
return s.top;
case "top":
return null;
}
return s.top + s.radius;
})
.bottom(function () {
var s = this.scene.target[this.index];
return this.name() == "top" ? s.bottom + s.radius : null;
})
.textAlign(function () {
switch (this.name()) {
case "left":
return "right";
case "bottom":
case "top":
case "center":
return "center";
}
return "left";
})
.textBaseline(function () {
switch (this.name()) {
case "right":
case "left":
case "center":
return "middle";
case "bottom":
return "top";
}
return "bottom";
});
};
/** @private Sets radius based on size or vice versa. */
pv.Dot.prototype.buildImplied = function (s) {
if (s.radius == null)
s.radius = Math.sqrt(s.size);
else if (s.size == null)
s.size = s.radius * s.radius;
pv.Mark.prototype.buildImplied.call(this, s);
};
/**
* Constructs a new label mark with default properties. Labels are not typically
* constructed directly, but by adding to a panel or an existing mark via
* {@link pv.Mark#add}.
*
* @class Represents a text label, allowing textual annotation of other marks or
* arbitrary text within the visualization. The character data must be plain
* text (unicode), though the text can be styled using the {@link #font}
* property. If rich text is needed, external HTML elements can be overlaid on
* the canvas by hand.
*
* <p>Labels are positioned using the box model, similarly to {@link Dot}. Thus,
* a label has no width or height, but merely a text anchor location. The text
* is positioned relative to this anchor location based on the
* {@link #textAlign}, {@link #textBaseline} and {@link #textMargin} properties.
* Furthermore, the text may be rotated using {@link #textAngle}.
*
* <p>Labels ignore events, so as to not interfere with event handlers on
* underlying marks, such as bars. In the future, we may support event handlers
* on labels.
*
* <p>See also the <a href="../../api/Label.html">Label guide</a>.
*
* @extends pv.Mark
*/
pv.Label = function () {
pv.Mark.call(this);
};
pv.Label.prototype = pv.extend(pv.Mark)
.property("text", String)
.property("font", String)
.property("textAngle", Number)
.property("textStyle", pv.color)
.property("textAlign", String)
.property("textBaseline", String)
.property("textMargin", Number)
.property("textDecoration", String)
.property("textShadow", String);
pv.Label.prototype.type = "label";
/**
* The character data to render; a string. The default value of the text
* property is the identity function, meaning the label's associated datum will
* be rendered using its <tt>toString</tt>.
*
* @type string
* @name pv.Label.prototype.text
*/
/**
* The font format, per the CSS Level 2 specification. The default font is "10px
* sans-serif", for consistency with the HTML 5 canvas element specification.
* Note that since text is not wrapped, any line-height property will be
* ignored. The other font-style, font-variant, font-weight, font-size and
* font-family properties are supported.
*
* @see <a href="http://www.w3.org/TR/CSS2/fonts.html#font-shorthand">CSS2 fonts</a>
* @type string
* @name pv.Label.prototype.font
*/
/**
* The rotation angle, in radians. Text is rotated clockwise relative to the
* anchor location. For example, with the default left alignment, an angle of
* Math.PI / 2 causes text to proceed downwards. The default angle is zero.
*
* @type number
* @name pv.Label.prototype.textAngle
*/
/**
* The text color. The name "textStyle" is used for consistency with "fillStyle"
* and "strokeStyle", although it might be better to rename this property (and
* perhaps use the same name as "strokeStyle"). The default color is black.
*
* @type string
* @name pv.Label.prototype.textStyle
* @see pv.color
*/
/**
* The horizontal text alignment. One of:<ul>
*
* <li>left
* <li>center
* <li>right
*
* </ul>The default horizontal alignment is left.
*
* @type string
* @name pv.Label.prototype.textAlign
*/
/**
* The vertical text alignment. One of:<ul>
*
* <li>top
* <li>middle
* <li>bottom
*
* </ul>The default vertical alignment is bottom.
*
* @type string
* @name pv.Label.prototype.textBaseline
*/
/**
* The text margin; may be specified in pixels, or in font-dependent units (such
* as ".1ex"). The margin can be used to pad text away from its anchor location,
* in a direction dependent on the horizontal and vertical alignment
* properties. For example, if the text is left- and middle-aligned, the margin
* shifts the text to the right. The default margin is 3 pixels.
*
* @type number
* @name pv.Label.prototype.textMargin
*/
/**
* A list of shadow effects to be applied to text, per the CSS Text Level 3
* text-shadow property. An example specification is "0.1em 0.1em 0.1em
* rgba(0,0,0,.5)"; the first length is the horizontal offset, the second the
* vertical offset, and the third the blur radius.
*
* @see <a href="http://www.w3.org/TR/css3-text/#text-shadow">CSS3 text</a>
* @type string
* @name pv.Label.prototype.textShadow
*/
/**
* A list of decoration to be applied to text, per the CSS Text Level 3
* text-decoration property. An example specification is "underline".
*
* @see <a href="http://www.w3.org/TR/css3-text/#text-decoration">CSS3 text</a>
* @type string
* @name pv.Label.prototype.textDecoration
*/
/**
* Default properties for labels. See the individual properties for the default
* values.
*
* @type pv.Label
*/
pv.Label.prototype.defaults = new pv.Label()
.extend(pv.Mark.prototype.defaults)
.events("none")
.text(pv.identity)
.font("10px sans-serif")
.textAngle(0)
.textStyle("black")
.textAlign("left")
.textBaseline("bottom")
.textMargin(3);
/**
* Constructs a new line mark with default properties. Lines are not typically
* constructed directly, but by adding to a panel or an existing mark via
* {@link pv.Mark#add}.
*
* @class Represents a series of connected line segments, or <i>polyline</i>,
* that can be stroked with a configurable color and thickness. Each
* articulation point in the line corresponds to a datum; for <i>n</i> points,
* <i>n</i>-1 connected line segments are drawn. The point is positioned using
* the box model. Arbitrary paths are also possible, allowing radar plots and
* other custom visualizations.
*
* <p>Like areas, lines can be stroked and filled with arbitrary colors. In most
* cases, lines are only stroked, but the fill style can be used to construct
* arbitrary polygons.
*
* <p>See also the <a href="../../api/Line.html">Line guide</a>.
*
* @extends pv.Mark
*/
pv.Line = function () {
pv.Mark.call(this);
};
pv.Line.prototype = pv.extend(pv.Mark)
.property("lineWidth", Number)
.property("lineJoin", String)
.property("strokeStyle", pv.color)
.property("fillStyle", pv.color)
.property("segmented", Boolean)
.property("interpolate", String)
.property("eccentricity", Number)
.property("tension", Number);
pv.Line.prototype.type = "line";
/**
* The width of stroked lines, in pixels; used in conjunction with
* <tt>strokeStyle</tt> to stroke the line.
*
* @type number
* @name pv.Line.prototype.lineWidth
*/
/**
* The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
* stroke the line. The default value of this property is a categorical color.
*
* @type string
* @name pv.Line.prototype.strokeStyle
* @see pv.color
*/
/**
* The type of corners where two lines meet. Accepted values are "bevel",
* "round" and "miter". The default value is "miter".
*
* <p>For segmented lines, only "miter" joins and "linear" interpolation are
* currently supported. Any other value, including null, will disable joins,
* producing disjoint line segments. Note that the miter joins must be computed
* manually (at least in the current SVG renderer); since this calculation may
* be expensive and unnecessary for small lines, specifying null can improve
* performance significantly.
*
* <p>This property is <i>fixed</i>. See {@link pv.Mark}.
*
* @type string
* @name pv.Line.prototype.lineJoin
*/
/**
* The line fill style; if non-null, the interior of the line is closed and
* filled with the specified color. The default value of this property is a
* null, meaning that lines are not filled by default.
*
* <p>This property is <i>fixed</i>. See {@link pv.Mark}.
*
* @type string
* @name pv.Line.prototype.fillStyle
* @see pv.color
*/
/**
* Whether the line is segmented; whether variations in stroke style, line width
* and the other properties are treated as fixed. Rendering segmented lines is
* noticeably slower than non-segmented lines.
*
* <p>This property is <i>fixed</i>. See {@link pv.Mark}.
*
* @type boolean
* @name pv.Line.prototype.segmented
*/
/**
* How to interpolate between values. Linear interpolation ("linear") is the
* default, producing a straight line between points. For piecewise constant
* functions (i.e., step functions), either "step-before" or "step-after" can be
* specified. To draw a clockwise circular arc between points, specify "polar";
* to draw a counterclockwise circular arc between points, specify
* "polar-reverse". To draw open uniform b-splines, specify "basis". To draw
* cardinal splines, specify "cardinal"; see also {@link #tension}.
*
* <p>This property is <i>fixed</i>. See {@link pv.Mark}.
*
* @type string
* @name pv.Line.prototype.interpolate
*/
/**
* The eccentricity of polar line segments; used in conjunction with
* interpolate("polar"). The default value of 0 means that line segments are
* drawn as circular arcs. A value of 1 draws a straight line. A value between 0
* and 1 draws an elliptical arc with the given eccentricity.
*
* @type number
* @name pv.Line.prototype.eccentricity
*/
/**
* The tension of cardinal splines; used in conjunction with
* interpolate("cardinal"). A value between 0 and 1 draws cardinal splines with
* the given tension. In some sense, the tension can be interpreted as the
* "length" of the tangent; a tension of 1 will yield all zero tangents (i.e.,
* linear interpolation), and a tension of 0 yields a Catmull-Rom spline. The
* default value is 0.7.
*
* <p>This property is <i>fixed</i>. See {@link pv.Mark}.
*
* @type number
* @name pv.Line.prototype.tension
*/
/**
* Default properties for lines. By default, there is no fill and the stroke
* style is a categorical color. The default interpolation is linear.
*
* @type pv.Line
*/
pv.Line.prototype.defaults = new pv.Line()
.extend(pv.Mark.prototype.defaults)
.lineJoin("miter")
.lineWidth(1.5)
.strokeStyle(pv.Colors.category10().by(pv.parent))
.interpolate("linear")
.eccentricity(0)
.tension(.7);
/** @private Reuse Area's implementation for segmented bind & build. */
pv.Line.prototype.bind = pv.Area.prototype.bind;
pv.Line.prototype.buildInstance = pv.Area.prototype.buildInstance;
/**
* Constructs a new line anchor with default properties. Lines support five
* different anchors:<ul>
*
* <li>top
* <li>left
* <li>center
* <li>bottom
* <li>right
*
* </ul>In addition to positioning properties (left, right, top bottom), the
* anchors support text rendering properties (text-align, text-baseline). Text is
* rendered to appear outside the line. Note that this behavior is different
* from other mark anchors, which default to rendering text <i>inside</i> the
* mark.
*
* <p>For consistency with the other mark types, the anchor positions are
* defined in terms of their opposite edge. For example, the top anchor defines
* the bottom property, such that a bar added to the top anchor grows upward.
*
* @param {string} name the anchor name; either a string or a property function.
* @returns {pv.Anchor}
*/
pv.Line.prototype.anchor = function (name) {
return pv.Area.prototype.anchor.call(this, name)
.textAlign(function (d) {
switch (this.name()) {
case "left":
return "right";
case "bottom":
case "top":
case "center":
return "center";
case "right":
return "left";
}
})
.textBaseline(function (d) {
switch (this.name()) {
case "right":
case "left":
case "center":
return "middle";
case "top":
return "bottom";
case "bottom":
return "top";
}
});
};
/**
* Constructs a new rule with default properties. Rules are not typically
* constructed directly, but by adding to a panel or an existing mark via
* {@link pv.Mark#add}.
*
* @class Represents a horizontal or vertical rule. Rules are frequently used
* for axes and grid lines. For example, specifying only the bottom property
* draws horizontal rules, while specifying only the left draws vertical
* rules. Rules can also be used as thin bars. The visual style is controlled in
* the same manner as lines.
*
* <p>Rules are positioned exclusively the standard box model properties. The
* following combinations of properties are supported:
*
* <table>
* <thead><th style="width:12em;">Properties</th><th>Orientation</th></thead>
* <tbody>
* <tr><td>left</td><td>vertical</td></tr>
* <tr><td>right</td><td>vertical</td></tr>
* <tr><td>left, bottom, top</td><td>vertical</td></tr>
* <tr><td>right, bottom, top</td><td>vertical</td></tr>
* <tr><td>top</td><td>horizontal</td></tr>
* <tr><td>bottom</td><td>horizontal</td></tr>
* <tr><td>top, left, right</td><td>horizontal</td></tr>
* <tr><td>bottom, left, right</td><td>horizontal</td></tr>
* <tr><td>left, top, height</td><td>vertical</td></tr>
* <tr><td>left, bottom, height</td><td>vertical</td></tr>
* <tr><td>right, top, height</td><td>vertical</td></tr>
* <tr><td>right, bottom, height</td><td>vertical</td></tr>
* <tr><td>left, top, width</td><td>horizontal</td></tr>
* <tr><td>left, bottom, width</td><td>horizontal</td></tr>
* <tr><td>right, top, width</td><td>horizontal</td></tr>
* <tr><td>right, bottom, width</td><td>horizontal</td></tr>
* </tbody>
* </table>
*
* <p>Small rules can be used as tick marks; alternatively, a {@link Dot} with
* the "tick" shape can be used.
*
* <p>See also the <a href="../../api/Rule.html">Rule guide</a>.
*
* @see pv.Line
* @extends pv.Mark
*/
pv.Rule = function () {
pv.Mark.call(this);
};
pv.Rule.prototype = pv.extend(pv.Mark)
.property("width", Number)
.property("height", Number)
.property("lineWidth", Number)
.property("strokeStyle", pv.color);
pv.Rule.prototype.type = "rule";
/**
* The width of the rule, in pixels. If the left position is specified, the rule
* extends rightward from the left edge; if the right position is specified, the
* rule extends leftward from the right edge.
*
* @type number
* @name pv.Rule.prototype.width
*/
/**
* The height of the rule, in pixels. If the bottom position is specified, the
* rule extends upward from the bottom edge; if the top position is specified,
* the rule extends downward from the top edge.
*
* @type number
* @name pv.Rule.prototype.height
*/
/**
* The width of stroked lines, in pixels; used in conjunction with
* <tt>strokeStyle</tt> to stroke the rule. The default value is 1 pixel.
*
* @type number
* @name pv.Rule.prototype.lineWidth
*/
/**
* The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
* stroke the rule. The default value of this property is black.
*
* @type string
* @name pv.Rule.prototype.strokeStyle
* @see pv.color
*/
/**
* Default properties for rules. By default, a single-pixel black line is
* stroked.
*
* @type pv.Rule
*/
pv.Rule.prototype.defaults = new pv.Rule()
.extend(pv.Mark.prototype.defaults)
.lineWidth(1)
.strokeStyle("black")
.antialias(false);
/**
* Constructs a new rule anchor with default properties. Rules support five
* different anchors:<ul>
*
* <li>top
* <li>left
* <li>center
* <li>bottom
* <li>right
*
* </ul>In addition to positioning properties (left, right, top bottom), the
* anchors support text rendering properties (text-align, text-baseline). Text is
* rendered to appear outside the rule. Note that this behavior is different
* from other mark anchors, which default to rendering text <i>inside</i> the
* mark.
*
* <p>For consistency with the other mark types, the anchor positions are
* defined in terms of their opposite edge. For example, the top anchor defines
* the bottom property, such that a bar added to the top anchor grows upward.
*
* @param {string} name the anchor name; either a string or a property function.
* @returns {pv.Anchor}
*/
pv.Rule.prototype.anchor = pv.Line.prototype.anchor;
/** @private Sets width or height based on orientation. */
pv.Rule.prototype.buildImplied = function (s) {
var l = s.left, r = s.right, t = s.top, b = s.bottom;
/* Determine horizontal or vertical orientation. */
if ((s.width != null)
|| ((l == null) && (r == null))
|| ((r != null) && (l != null))) {
s.height = 0;
} else {
s.width = 0;
}
pv.Mark.prototype.buildImplied.call(this, s);
};
/**
* Constructs a new, empty panel with default properties. Panels, with the
* exception of the root panel, are not typically constructed directly; instead,
* they are added to an existing panel or mark via {@link pv.Mark#add}.
*
* @class Represents a container mark. Panels allow repeated or nested
* structures, commonly used in small multiple displays where a small
* visualization is tiled to facilitate comparison across one or more
* dimensions. Other types of visualizations may benefit from repeated and
* possibly overlapping structure as well, such as stacked area charts. Panels
* can also offset the position of marks to provide padding from surrounding
* content.
*
* <p>All Protovis displays have at least one panel; this is the root panel to
* which marks are rendered. The box model properties (four margins, width and
* height) are used to offset the positions of contained marks. The data
* property determines the panel count: a panel is generated once per associated
* datum. When nested panels are used, property functions can declare additional
* arguments to access the data associated with enclosing panels.
*
* <p>Panels can be rendered inline, facilitating the creation of sparklines.
* This allows designers to reuse browser layout features, such as text flow and
* tables; designers can also overlay HTML elements such as rich text and
* images.
*
* <p>All panels have a <tt>children</tt> array (possibly empty) containing the
* child marks in the order they were added. Panels also have a <tt>root</tt>
* field which points to the root (outermost) panel; the root panel's root field
* points to itself.
*
* <p>See also the <a href="../../api/">Protovis guide</a>.
*
* @extends pv.Bar
*/
pv.Panel = function () {
pv.Bar.call(this);
/**
* The child marks; zero or more {@link pv.Mark}s in the order they were
* added.
*
* @see #add
* @type pv.Mark[]
*/
this.children = [];
this.root = this;
/**
* The internal $dom field is set by the Protovis loader; see lang/init.js. It
* refers to the script element that contains the Protovis specification, so
* that the panel knows where in the DOM to insert the generated SVG element.
*
* @private
*/
this.$dom = pv.$ && pv.$.s;
};
pv.Panel.prototype = pv.extend(pv.Bar)
.property("transform")
.property("overflow", String)
.property("canvas", function (c) {
return (typeof c == "string")
? document.getElementById(c)
: c; // assume that c is the passed-in element
});
pv.Panel.prototype.type = "panel";
/**
* The canvas element; either the string ID of the canvas element in the current
* document, or a reference to the canvas element itself. If null, a canvas
* element will be created and inserted into the document at the location of the
* script element containing the current Protovis specification. This property
* only applies to root panels and is ignored on nested panels.
*
* <p>Note: the "canvas" element here refers to a <tt>div</tt> (or other suitable
* HTML container element), <i>not</i> a <tt>canvas</tt> element. The name of
* this property is a historical anachronism from the first implementation that
* used HTML 5 canvas, rather than SVG.
*
* @type string
* @name pv.Panel.prototype.canvas
*/
/**
* Specifies whether child marks are clipped when they overflow this panel.
* This affects the clipping of all this panel's descendant marks.
*
* @type string
* @name pv.Panel.prototype.overflow
* @see <a href="http://www.w3.org/TR/CSS2/visufx.html#overflow">CSS2</a>
*/
/**
* The transform to be applied to child marks. The default transform is
* identity, which has no effect. Note that the panel's own fill and stroke are
* not affected by the transform, and panel's transform only affects the
* <tt>scale</tt> of child marks, not the panel itself.
*
* @type pv.Transform
* @name pv.Panel.prototype.transform
* @see pv.Mark#scale
*/
/**
* Default properties for panels. By default, the margins are zero, the fill
* style is transparent.
*
* @type pv.Panel
*/
pv.Panel.prototype.defaults = new pv.Panel()
.extend(pv.Bar.prototype.defaults)
.fillStyle(null) // override Bar default
.overflow("visible");
/**
* Returns an anchor with the specified name. This method is overridden such
* that adding to a panel's anchor adds to the panel, rather than to the panel's
* parent.
*
* @param {string} name the anchor name; either a string or a property function.
* @returns {pv.Anchor} the new anchor.
*/
pv.Panel.prototype.anchor = function (name) {
var anchor = pv.Bar.prototype.anchor.call(this, name);
anchor.parent = this;
return anchor;
};
/**
* Adds a new mark of the specified type to this panel. Unlike the normal
* {@link Mark#add} behavior, adding a mark to a panel does not cause the mark
* to inherit from the panel. Since the contained marks are offset by the panel
* margins already, inheriting properties is generally undesirable; of course,
* it is always possible to change this behavior by calling {@link Mark#extend}
* explicitly.
*
* @param {function} type the type of the new mark to add.
* @returns {pv.Mark} the new mark.
*/
pv.Panel.prototype.add = function (type) {
var child = new type();
child.parent = this;
child.root = this.root;
child.childIndex = this.children.length;
this.children.push(child);
return child;
};
/** @private Bind this panel, then any child marks recursively. */
pv.Panel.prototype.bind = function () {
pv.Mark.prototype.bind.call(this);
for (var i = 0; i < this.children.length; i++) {
this.children[i].bind();
}
};
/**
* @private Evaluates all of the properties for this panel for the specified
* instance <tt>s</tt> in the scene graph, including recursively building the
* scene graph for child marks.
*
* @param s a node in the scene graph; the instance of the panel to build.
* @see Mark#scene
*/
pv.Panel.prototype.buildInstance = function (s) {
pv.Bar.prototype.buildInstance.call(this, s);
if (!s.visible)
return;
if (!s.children)
s.children = [];
/*
* Multiply the current scale factor by this panel's transform. Also clear the
* default index as we recurse into child marks; it will be reset to the
* current index when the next panel instance is built.
*/
var scale = this.scale * s.transform.k, child, n = this.children.length;
pv.Mark.prototype.index = -1;
/*
* Build each child, passing in the parent (this panel) scene graph node. The
* child mark's scene is initialized from the corresponding entry in the
* existing scene graph, such that properties from the previous build can be
* reused; this is largely to facilitate the recycling of SVG elements.
*/
for (var i = 0; i < n; i++) {
child = this.children[i];
child.scene = s.children[i]; // possibly undefined
child.scale = scale;
child.build();
}
/*
* Once the child marks have been built, the new scene graph nodes are removed
* from the child marks and placed into the scene graph. The nodes cannot
* remain on the child nodes because this panel (or a parent panel) may be
* instantiated multiple times!
*/
for (var i = 0; i < n; i++) {
child = this.children[i];
s.children[i] = child.scene;
delete child.scene;
delete child.scale;
}
/* Delete any expired child scenes. */
s.children.length = n;
};
/**
* @private Computes the implied properties for this panel for the specified
* instance <tt>s</tt> in the scene graph. Panels have two implied
* properties:<ul>
*
* <li>The <tt>canvas</tt> property references the DOM element, typically a DIV,
* that contains the SVG element that is used to display the visualization. This
* property may be specified as a string, referring to the unique ID of the
* element in the DOM. The string is converted to a reference to the DOM
* element. The width and height of the SVG element is inferred from this DOM
* element. If no canvas property is specified, a new SVG element is created and
* inserted into the document, using the panel dimensions; see
* {@link #createCanvas}.
*
* <li>The <tt>children</tt> array, while not a property per se, contains the
* scene graph for each child mark. This array is initialized to be empty, and
* is populated above in {@link #buildInstance}.
*
* </ul>The current implementation creates the SVG element, if necessary, during
* the build phase; in the future, it may be preferrable to move this to the
* update phase, although then the canvas property would be undefined. In
* addition, DOM inspection is necessary to define the implied width and height
* properties that may be inferred from the DOM.
*
* @param s a node in the scene graph; the instance of the panel to build.
*/
pv.Panel.prototype.buildImplied = function (s) {
if (!this.parent) {
var c = s.canvas;
if (c) {
/* Clear the container if it's not associated with this panel. */
if (c.$panel != this) {
c.$panel = this;
while (c.lastChild)
c.removeChild(c.lastChild);
}
/* If width and height weren't specified, inspect the container. */
var w, h;
if (s.width == null) {
w = parseFloat(pv.css(c, "width"));
s.width = w - s.left - s.right;
}
if (s.height == null) {
h = parseFloat(pv.css(c, "height"));
s.height = h - s.top - s.bottom;
}
} else {
var cache = this.$canvas || (this.$canvas = []);
if (!(c = cache[this.index])) {
c = cache[this.index] = document.createElement("span");
if (this.$dom) { // script element for text/javascript+protovis
this.$dom.parentNode.insertBefore(c, this.$dom);
} else { // find the last element in the body
var n = document.body;
while (n.lastChild && n.lastChild.tagName)
n = n.lastChild;
if (n != document.body)
n = n.parentNode;
n.appendChild(c);
}
}
}
s.canvas = c;
}
if (!s.transform)
s.transform = pv.Transform.identity;
pv.Mark.prototype.buildImplied.call(this, s);
};
/**
* Constructs a new image with default properties. Images are not typically
* constructed directly, but by adding to a panel or an existing mark via
* {@link pv.Mark#add}.
*
* @class Represents an image, either a static resource or a dynamically-
* generated pixel buffer. Images share the same layout and style properties as
* bars. The external image resource is specified via the {@link #url}
* property. The optional fill, if specified, appears beneath the image, while
* the optional stroke appears above the image.
*
* <p>Dynamic images such as heatmaps are supported using the {@link #image}
* psuedo-property. This function is passed the <i>x</i> and <i>y</i> index, in
* addition to the current data stack. The return value is a {@link pv.Color},
* or null for transparent. A string can also be returned, which will be parsed
* into a color; however, it is typically much faster to return an object with
* <tt>r</tt>, <tt>g</tt>, <tt>b</tt> and <tt>a</tt> attributes, to avoid the
* cost of parsing and object instantiation.
*
* <p>See {@link pv.Bar} for details on positioning properties.
*
* @extends pv.Bar
*/
pv.Image = function () {
pv.Bar.call(this);
};
pv.Image.prototype = pv.extend(pv.Bar)
.property("url", String)
.property("imageWidth", Number)
.property("imageHeight", Number);
pv.Image.prototype.type = "image";
/**
* The URL of the image to display. The set of supported image types is
* browser-dependent; PNG and JPEG are recommended.
*
* @type string
* @name pv.Image.prototype.url
*/
/**
* The width of the image in pixels. For static images, this property is
* computed implicitly from the loaded image resources. For dynamic images, this
* property can be used to specify the width of the pixel buffer; otherwise, the
* value is derived from the <tt>width</tt> property.
*
* @type number
* @name pv.Image.prototype.imageWidth
*/
/**
* The height of the image in pixels. For static images, this property is
* computed implicitly from the loaded image resources. For dynamic images, this
* property can be used to specify the height of the pixel buffer; otherwise, the
* value is derived from the <tt>height</tt> property.
*
* @type number
* @name pv.Image.prototype.imageHeight
*/
/**
* Default properties for images. By default, there is no stroke or fill style.
*
* @type pv.Image
*/
pv.Image.prototype.defaults = new pv.Image()
.extend(pv.Bar.prototype.defaults)
.fillStyle(null);
/**
* Specifies the dynamic image function. By default, no image function is
* specified and the <tt>url</tt> property is used to load a static image
* resource. If an image function is specified, it will be invoked for each
* pixel in the image, based on the related <tt>imageWidth</tt> and
* <tt>imageHeight</tt> properties.
*
* <p>For example, given a two-dimensional array <tt>heatmap</tt>, containing
* numbers in the range [0, 1] in row-major order, a simple monochrome heatmap
* image can be specified as:
*
* <pre>vis.add(pv.Image)
* .imageWidth(heatmap[0].length)
* .imageHeight(heatmap.length)
* .image(pv.ramp("white", "black").by(function(x, y) heatmap[y][x]));</pre>
*
* For fastest performance, use an ordinal scale which caches the fixed color
* palette, or return an object literal with <tt>r</tt>, <tt>g</tt>, <tt>b</tt>
* and <tt>a</tt> attributes. A {@link pv.Color} or string can also be returned,
* though this typically results in slower performance.
*
* @param {function} f the new sizing function.
* @returns {pv.Layout.Pack} this.
*/
pv.Image.prototype.image = function (f) {
/** @private */
this.$image = function () {
var c = f.apply(this, arguments);
return c == null ? pv.Color.transparent
: typeof c == "string" ? pv.color(c)
: c;
};
return this;
};
/** @private Scan the proto chain for an image function. */
pv.Image.prototype.bind = function () {
pv.Bar.prototype.bind.call(this);
var binds = this.binds, mark = this;
do {
binds.image = mark.$image;
} while (!binds.image && (mark = mark.proto));
};
/** @private */
pv.Image.prototype.buildImplied = function (s) {
pv.Bar.prototype.buildImplied.call(this, s);
if (!s.visible)
return;
/* Compute the implied image dimensions. */
if (s.imageWidth == null)
s.imageWidth = s.width;
if (s.imageHeight == null)
s.imageHeight = s.height;
/* Compute the pixel values. */
if ((s.url == null) && this.binds.image) {
/* Cache the canvas element to reuse across renders. */
var canvas = this.$canvas || (this.$canvas = document.createElement("canvas")),
context = canvas.getContext("2d"),
w = s.imageWidth,
h = s.imageHeight,
stack = pv.Mark.stack,
data;
/* Evaluate the image function, storing into a CanvasPixelArray. */
canvas.width = w;
canvas.height = h;
data = (s.image = context.createImageData(w, h)).data;
stack.unshift(null, null);
for (var y = 0, p = 0; y < h; y++) {
stack[1] = y;
for (var x = 0; x < w; x++) {
stack[0] = x;
var color = this.binds.image.apply(this, stack);
data[p++] = color.r;
data[p++] = color.g;
data[p++] = color.b;
data[p++] = 255 * color.a;
}
}
stack.splice(0, 2);
}
};
/**
* Constructs a new wedge with default properties. Wedges are not typically
* constructed directly, but by adding to a panel or an existing mark via
* {@link pv.Mark#add}.
*
* @class Represents a wedge, or pie slice. Specified in terms of start and end
* angle, inner and outer radius, wedges can be used to construct donut charts
* and polar bar charts as well. If the {@link #angle} property is used, the end
* angle is implied by adding this value to start angle. By default, the start
* angle is the previously-generated wedge's end angle. This design allows
* explicit control over the wedge placement if desired, while offering
* convenient defaults for the construction of radial graphs.
*
* <p>The center point of the circle is positioned using the standard box model.
* The wedge can be stroked and filled, similar to {@link pv.Bar}.
*
* <p>See also the <a href="../../api/Wedge.html">Wedge guide</a>.
*
* @extends pv.Mark
*/
pv.Wedge = function () {
pv.Mark.call(this);
};
pv.Wedge.prototype = pv.extend(pv.Mark)
.property("startAngle", Number)
.property("endAngle", Number)
.property("angle", Number)
.property("innerRadius", Number)
.property("outerRadius", Number)
.property("lineWidth", Number)
.property("strokeStyle", pv.color)
.property("fillStyle", pv.color);
pv.Wedge.prototype.type = "wedge";
/**
* The start angle of the wedge, in radians. The start angle is measured
* clockwise from the 3 o'clock position. The default value of this property is
* the end angle of the previous instance (the {@link Mark#sibling}), or -PI / 2
* for the first wedge; for pie and donut charts, typically only the
* {@link #angle} property needs to be specified.
*
* @type number
* @name pv.Wedge.prototype.startAngle
*/
/**
* The end angle of the wedge, in radians. If not specified, the end angle is
* implied as the start angle plus the {@link #angle}.
*
* @type number
* @name pv.Wedge.prototype.endAngle
*/
/**
* The angular span of the wedge, in radians. This property is used if end angle
* is not specified.
*
* @type number
* @name pv.Wedge.prototype.angle
*/
/**
* The inner radius of the wedge, in pixels. The default value of this property
* is zero; a positive value will produce a donut slice rather than a pie slice.
* The inner radius can vary per-wedge.
*
* @type number
* @name pv.Wedge.prototype.innerRadius
*/
/**
* The outer radius of the wedge, in pixels. This property is required. For
* pies, only this radius is required; for donuts, the inner radius must be
* specified as well. The outer radius can vary per-wedge.
*
* @type number
* @name pv.Wedge.prototype.outerRadius
*/
/**
* The width of stroked lines, in pixels; used in conjunction with
* <tt>strokeStyle</tt> to stroke the wedge's border.
*
* @type number
* @name pv.Wedge.prototype.lineWidth
*/
/**
* The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
* stroke the wedge's border. The default value of this property is null,
* meaning wedges are not stroked by default.
*
* @type string
* @name pv.Wedge.prototype.strokeStyle
* @see pv.color
*/
/**
* The wedge fill style; if non-null, the interior of the wedge is filled with
* the specified color. The default value of this property is a categorical
* color.
*
* @type string
* @name pv.Wedge.prototype.fillStyle
* @see pv.color
*/
/**
* Default properties for wedges. By default, there is no stroke and the fill
* style is a categorical color.
*
* @type pv.Wedge
*/
pv.Wedge.prototype.defaults = new pv.Wedge()
.extend(pv.Mark.prototype.defaults)
.startAngle(function () {
var s = this.sibling();
return s ? s.endAngle : -Math.PI / 2;
})
.innerRadius(0)
.lineWidth(1.5)
.strokeStyle(null)
.fillStyle(pv.Colors.category20().by(pv.index));
/**
* Returns the mid-radius of the wedge, which is defined as half-way between the
* inner and outer radii.
*
* @see #innerRadius
* @see #outerRadius
* @returns {number} the mid-radius, in pixels.
*/
pv.Wedge.prototype.midRadius = function () {
return (this.innerRadius() + this.outerRadius()) / 2;
};
/**
* Returns the mid-angle of the wedge, which is defined as half-way between the
* start and end angles.
*
* @see #startAngle
* @see #endAngle
* @returns {number} the mid-angle, in radians.
*/
pv.Wedge.prototype.midAngle = function () {
return (this.startAngle() + this.endAngle()) / 2;
};
/**
* Constructs a new wedge anchor with default properties. Wedges support five
* different anchors:<ul>
*
* <li>outer
* <li>inner
* <li>center
* <li>start
* <li>end
*
* </ul>In addition to positioning properties (left, right, top bottom), the
* anchors support text rendering properties (text-align, text-baseline,
* textAngle). Text is rendered to appear inside the wedge.
*
* @param {string} name the anchor name; either a string or a property function.
* @returns {pv.Anchor}
*/
pv.Wedge.prototype.anchor = function (name) {
function partial(s) {
return s.innerRadius || s.angle < 2 * Math.PI;
}
function midRadius(s) {
return (s.innerRadius + s.outerRadius) / 2;
}
function midAngle(s) {
return (s.startAngle + s.endAngle) / 2;
}
return pv.Mark.prototype.anchor.call(this, name)
.left(function () {
var s = this.scene.target[this.index];
if (partial(s))
switch (this.name()) {
case "outer":
return s.left + s.outerRadius * Math.cos(midAngle(s));
case "inner":
return s.left + s.innerRadius * Math.cos(midAngle(s));
case "start":
return s.left + midRadius(s) * Math.cos(s.startAngle);
case "center":
return s.left + midRadius(s) * Math.cos(midAngle(s));
case "end":
return s.left + midRadius(s) * Math.cos(s.endAngle);
}
return s.left;
})
.top(function () {
var s = this.scene.target[this.index];
if (partial(s))
switch (this.name()) {
case "outer":
return s.top + s.outerRadius * Math.sin(midAngle(s));
case "inner":
return s.top + s.innerRadius * Math.sin(midAngle(s));
case "start":
return s.top + midRadius(s) * Math.sin(s.startAngle);
case "center":
return s.top + midRadius(s) * Math.sin(midAngle(s));
case "end":
return s.top + midRadius(s) * Math.sin(s.endAngle);
}
return s.top;
})
.textAlign(function () {
var s = this.scene.target[this.index];
if (partial(s))
switch (this.name()) {
case "outer":
return pv.Wedge.upright(midAngle(s)) ? "right" : "left";
case "inner":
return pv.Wedge.upright(midAngle(s)) ? "left" : "right";
}
return "center";
})
.textBaseline(function () {
var s = this.scene.target[this.index];
if (partial(s))
switch (this.name()) {
case "start":
return pv.Wedge.upright(s.startAngle) ? "top" : "bottom";
case "end":
return pv.Wedge.upright(s.endAngle) ? "bottom" : "top";
}
return "middle";
})
.textAngle(function () {
var s = this.scene.target[this.index], a = 0;
if (partial(s))
switch (this.name()) {
case "center":
case "inner":
case "outer":
a = midAngle(s);
break;
case "start":
a = s.startAngle;
break;
case "end":
a = s.endAngle;
break;
}
return pv.Wedge.upright(a) ? a : (a + Math.PI);
});
};
/**
* Returns true if the specified angle is considered "upright", as in, text
* rendered at that angle would appear upright. If the angle is not upright,
* text is rotated 180 degrees to be upright, and the text alignment properties
* are correspondingly changed.
*
* @param {number} angle an angle, in radius.
* @returns {boolean} true if the specified angle is upright.
*/
pv.Wedge.upright = function (angle) {
angle = angle % (2 * Math.PI);
angle = (angle < 0) ? (2 * Math.PI + angle) : angle;
return (angle < Math.PI / 2) || (angle >= 3 * Math.PI / 2);
};
/** @private Sets angle based on endAngle or vice versa. */
pv.Wedge.prototype.buildImplied = function (s) {
if (s.angle == null)
s.angle = s.endAngle - s.startAngle;
else if (s.endAngle == null)
s.endAngle = s.startAngle + s.angle;
pv.Mark.prototype.buildImplied.call(this, s);
};
/**
* Abstract; not implemented. There is no explicit constructor; this class
* merely serves to document the attributes that are used on particles in
* physics simulations.
*
* @class A weighted particle that can participate in a force simulation.
*
* @name pv.Particle
*/
/**
* The next particle in the simulation. Particles form a singly-linked list.
*
* @field
* @type pv.Particle
* @name pv.Particle.prototype.next
*/
/**
* The <i>x</i>-position of the particle.
*
* @field
* @type number
* @name pv.Particle.prototype.x
*/
/**
* The <i>y</i>-position of the particle.
*
* @field
* @type number
* @name pv.Particle.prototype.y
*/
/**
* The <i>x</i>-velocity of the particle.
*
* @field
* @type number
* @name pv.Particle.prototype.vx
*/
/**
* The <i>y</i>-velocity of the particle.
*
* @field
* @type number
* @name pv.Particle.prototype.vy
*/
/**
* The <i>x</i>-position of the particle at -dt.
*
* @field
* @type number
* @name pv.Particle.prototype.px
*/
/**
* The <i>y</i>-position of the particle at -dt.
*
* @field
* @type number
* @name pv.Particle.prototype.py
*/
/**
* The <i>x</i>-force on the particle.
*
* @field
* @type number
* @name pv.Particle.prototype.fx
*/
/**
* The <i>y</i>-force on the particle.
*
* @field
* @type number
* @name pv.Particle.prototype.fy
*/
/**
* Constructs a new empty simulation.
*
* @param {array} particles
* @returns {pv.Simulation} a new simulation for the specified particles.
* @see pv.Simulation
*/
pv.simulation = function (particles) {
return new pv.Simulation(particles);
};
/**
* Constructs a new simulation for the specified particles.
*
* @class Represents a particle simulation. Particles are massive points in
* two-dimensional space. Forces can be applied to these particles, causing them
* to move. Constraints can also be applied to restrict particle movement, for
* example, constraining particles to a fixed position, or simulating collision
* between circular particles with area.
*
* <p>The simulation uses <a
* href="http://en.wikipedia.org/wiki/Verlet_integration">Position Verlet</a>
* integration, due to the ease with which <a
* href="http://www.teknikus.dk/tj/gdc2001.htm">geometric constraints</a> can be
* implemented. For each time step, Verlet integration is performed, new forces
* are accumulated, and then constraints are applied.
*
* <p>The simulation makes two simplifying assumptions: all particles are
* equal-mass, and the time step of the simulation is fixed. It would be easy to
* incorporate variable-mass particles as a future enhancement. Variable time
* steps are also possible, but are likely to introduce instability in the
* simulation.
*
* <p>This class can be used directly to simulate particle interaction.
* Alternatively, for network diagrams, see {@link pv.Layout.Force}.
*
* @param {array} particles an array of {@link pv.Particle}s to simulate.
* @see pv.Layout.Force
* @see pv.Force
* @see pv.Constraint
*/
pv.Simulation = function (particles) {
for (var i = 0; i < particles.length; i++)
this.particle(particles[i]);
};
/**
* The particles in the simulation. Particles are stored as a linked list; this
* field represents the first particle in the simulation.
*
* @field
* @type pv.Particle
* @name pv.Simulation.prototype.particles
*/
/**
* The forces in the simulation. Forces are stored as a linked list; this field
* represents the first force in the simulation.
*
* @field
* @type pv.Force
* @name pv.Simulation.prototype.forces
*/
/**
* The constraints in the simulation. Constraints are stored as a linked list;
* this field represents the first constraint in the simulation.
*
* @field
* @type pv.Constraint
* @name pv.Simulation.prototype.constraints
*/
/**
* Adds the specified particle to the simulation.
*
* @param {pv.Particle} p the new particle.
* @returns {pv.Simulation} this.
*/
pv.Simulation.prototype.particle = function (p) {
p.next = this.particles;
/* Default velocities and forces to zero if unset. */
if (isNaN(p.px))
p.px = p.x;
if (isNaN(p.py))
p.py = p.y;
if (isNaN(p.fx))
p.fx = 0;
if (isNaN(p.fy))
p.fy = 0;
this.particles = p;
return this;
};
/**
* Adds the specified force to the simulation.
*
* @param {pv.Force} f the new force.
* @returns {pv.Simulation} this.
*/
pv.Simulation.prototype.force = function (f) {
f.next = this.forces;
this.forces = f;
return this;
};
/**
* Adds the specified constraint to the simulation.
*
* @param {pv.Constraint} c the new constraint.
* @returns {pv.Simulation} this.
*/
pv.Simulation.prototype.constraint = function (c) {
c.next = this.constraints;
this.constraints = c;
return this;
};
/**
* Apply constraints, and then set the velocities to zero.
*
* @returns {pv.Simulation} this.
*/
pv.Simulation.prototype.stabilize = function (n) {
var c;
if (!arguments.length)
n = 3; // TODO use cooling schedule
for (var i = 0; i < n; i++) {
var q = new pv.Quadtree(this.particles);
for (c = this.constraints; c; c = c.next)
c.apply(this.particles, q);
}
for (var p = this.particles; p; p = p.next) {
p.px = p.x;
p.py = p.y;
}
return this;
};
/**
* Advances the simulation one time-step.
*/
pv.Simulation.prototype.step = function () {
var p, f, c;
/*
* Assumptions:
* - The mass (m) of every particles is 1.
* - The time step (dt) is 1.
*/
/* Position Verlet integration. */
for (p = this.particles; p; p = p.next) {
var px = p.px, py = p.py;
p.px = p.x;
p.py = p.y;
p.x += p.vx = ((p.x - px) + p.fx);
p.y += p.vy = ((p.y - py) + p.fy);
}
/* Apply constraints, then accumulate new forces. */
var q = new pv.Quadtree(this.particles);
for (c = this.constraints; c; c = c.next)
c.apply(this.particles, q);
for (p = this.particles; p; p = p.next)
p.fx = p.fy = 0;
for (f = this.forces; f; f = f.next)
f.apply(this.particles, q);
};
/**
* Constructs a new quadtree for the specified array of particles.
*
* @class Represents a quadtree: a two-dimensional recursive spatial
* subdivision. This particular implementation uses square partitions, dividing
* each square into four equally-sized squares. Each particle exists in a unique
* node; if multiple particles are in the same position, some particles may be
* stored on internal nodes rather than leaf nodes.
*
* <p>This quadtree can be used to accelerate various spatial operations, such
* as the Barnes-Hut approximation for computing n-body forces, or collision
* detection.
*
* @see pv.Force.charge
* @see pv.Constraint.collision
* @param {pv.Particle} particles the linked list of particles.
*/
pv.Quadtree = function (particles) {
var p;
/* Compute bounds. */
var x1 = Number.POSITIVE_INFINITY, y1 = x1,
x2 = Number.NEGATIVE_INFINITY, y2 = x2;
for (p = particles; p; p = p.next) {
if (p.x < x1)
x1 = p.x;
if (p.y < y1)
y1 = p.y;
if (p.x > x2)
x2 = p.x;
if (p.y > y2)
y2 = p.y;
}
/* Squarify the bounds. */
var dx = x2 - x1, dy = y2 - y1;
if (dx > dy)
y2 = y1 + dx;
else
x2 = x1 + dy;
this.xMin = x1;
this.yMin = y1;
this.xMax = x2;
this.yMax = y2;
/**
* @ignore Recursively inserts the specified particle <i>p</i> at the node
* <i>n</i> or one of its descendants. The bounds are defined by [<i>x1</i>,
* <i>x2</i>] and [<i>y1</i>, <i>y2</i>].
*/
function insert(n, p, x1, y1, x2, y2) {
if (isNaN(p.x) || isNaN(p.y))
return; // ignore invalid particles
if (n.leaf) {
if (n.p) {
/*
* If the particle at this leaf node is at the same position as the new
* particle we are adding, we leave the particle associated with the
* internal node while adding the new particle to a child node. This
* avoids infinite recursion.
*/
if ((Math.abs(n.p.x - p.x) + Math.abs(n.p.y - p.y)) < .01) {
insertChild(n, p, x1, y1, x2, y2);
} else {
var v = n.p;
n.p = null;
insertChild(n, v, x1, y1, x2, y2);
insertChild(n, p, x1, y1, x2, y2);
}
} else {
n.p = p;
}
} else {
insertChild(n, p, x1, y1, x2, y2);
}
}
/**
* @ignore Recursively inserts the specified particle <i>p</i> into a
* descendant of node <i>n</i>. The bounds are defined by [<i>x1</i>,
* <i>x2</i>] and [<i>y1</i>, <i>y2</i>].
*/
function insertChild(n, p, x1, y1, x2, y2) {
/* Compute the split point, and the quadrant in which to insert p. */
var sx = (x1 + x2) * .5,
sy = (y1 + y2) * .5,
right = p.x >= sx,
bottom = p.y >= sy;
/* Recursively insert into the child node. */
n.leaf = false;
switch ((bottom << 1) + right) {
case 0:
n = n.c1 || (n.c1 = new pv.Quadtree.Node());
break;
case 1:
n = n.c2 || (n.c2 = new pv.Quadtree.Node());
break;
case 2:
n = n.c3 || (n.c3 = new pv.Quadtree.Node());
break;
case 3:
n = n.c4 || (n.c4 = new pv.Quadtree.Node());
break;
}
/* Update the bounds as we recurse. */
if (right)
x1 = sx;
else
x2 = sx;
if (bottom)
y1 = sy;
else
y2 = sy;
insert(n, p, x1, y1, x2, y2);
}
/* Insert all particles. */
this.root = new pv.Quadtree.Node();
for (p = particles; p; p = p.next)
insert(this.root, p, x1, y1, x2, y2);
};
/**
* The root node of the quadtree.
*
* @type pv.Quadtree.Node
* @name pv.Quadtree.prototype.root
*/
/**
* The minimum x-coordinate value of all contained particles.
*
* @type number
* @name pv.Quadtree.prototype.xMin
*/
/**
* The maximum x-coordinate value of all contained particles.
*
* @type number
* @name pv.Quadtree.prototype.xMax
*/
/**
* The minimum y-coordinate value of all contained particles.
*
* @type number
* @name pv.Quadtree.prototype.yMin
*/
/**
* The maximum y-coordinate value of all contained particles.
*
* @type number
* @name pv.Quadtree.prototype.yMax
*/
/**
* Constructs a new node.
*
* @class A node in a quadtree.
*
* @see pv.Quadtree
*/
pv.Quadtree.Node = function () {
/*
* Prepopulating all attributes significantly increases performance! Also,
* letting the language interpreter manage garbage collection was moderately
* faster than creating a cache pool.
*/
this.leaf = true;
this.c1 = null;
this.c2 = null;
this.c3 = null;
this.c4 = null;
this.p = null;
};
/**
* True if this node is a leaf node; i.e., it has no children. Note that both
* leaf nodes and non-leaf (internal) nodes may have associated particles. If
* this is a non-leaf node, then at least one of {@link #c1}, {@link #c2},
* {@link #c3} or {@link #c4} is guaranteed to be non-null.
*
* @type boolean
* @name pv.Quadtree.Node.prototype.leaf
*/
/**
* The particle associated with this node, if any.
*
* @type pv.Particle
* @name pv.Quadtree.Node.prototype.p
*/
/**
* The child node for the second quadrant, if any.
*
* @type pv.Quadtree.Node
* @name pv.Quadtree.Node.prototype.c2
*/
/**
* The child node for the third quadrant, if any.
*
* @type pv.Quadtree.Node
* @name pv.Quadtree.Node.prototype.c3
*/
/**
* The child node for the fourth quadrant, if any.
*
* @type pv.Quadtree.Node
* @name pv.Quadtree.Node.prototype.c4
*/
/**
* Abstract; see an implementing class.
*
* @class Represents a force that acts on particles. Note that this interface
* does not specify how to bind a force to specific particles; in general,
* forces are applied globally to all particles. However, some forces may be
* applied to specific particles or between particles, such as spring forces,
* through additional specialization.
*
* @see pv.Simulation
* @see pv.Particle
* @see pv.Force.charge
* @see pv.Force.drag
* @see pv.Force.spring
*/
pv.Force = {};
/**
* Applies this force to the specified particles.
*
* @function
* @name pv.Force.prototype.apply
* @param {pv.Particle} particles particles to which to apply this force.
* @param {pv.Quadtree} q a quadtree for spatial acceleration.
*/
/**
* Constructs a new charge force, with an optional charge constant. The charge
* constant can be negative for repulsion (e.g., particles with electrical
* charge of equal sign), or positive for attraction (e.g., massive particles
* with mutual gravity). The default charge constant is -40.
*
* @class An n-body force, as defined by Coulomb's law or Newton's law of
* gravitation, inversely proportional to the square of the distance between
* particles. Note that the force is independent of the <i>mass</i> of the
* associated particles, and that the particles do not have charges of varying
* magnitude; instead, the attraction or repulsion of all particles is globally
* specified as the charge {@link #constant}.
*
* <p>This particular implementation uses the Barnes-Hut algorithm. For details,
* see <a
* href="http://www.nature.com/nature/journal/v324/n6096/abs/324446a0.html">"A
* hierarchical O(N log N) force-calculation algorithm"</a>, J. Barnes &
* P. Hut, <i>Nature</i> 1986.
*
* @name pv.Force.charge
* @param {number} [k] the charge constant.
*/
pv.Force.charge = function (k) {
var min = 2, // minimum distance at which to observe forces
min1 = 1 / min,
max = 500, // maximum distance at which to observe forces
max1 = 1 / max,
theta = .9, // Barnes-Hut theta approximation constant
force = {};
if (!arguments.length)
k = -40; // default charge constant (repulsion)
/**
* Sets or gets the charge constant. If an argument is specified, it is the
* new charge constant. The charge constant can be negative for repulsion
* (e.g., particles with electrical charge of equal sign), or positive for
* attraction (e.g., massive particles with mutual gravity). The default
* charge constant is -40.
*
* @function
* @name pv.Force.charge.prototype.constant
* @param {number} x the charge constant.
* @returns {pv.Force.charge} this.
*/
force.constant = function (x) {
if (arguments.length) {
k = Number(x);
return force;
}
return k;
};
/**
* Sets or gets the domain; specifies the minimum and maximum domain within
* which charge forces are applied. A minimum distance threshold avoids
* applying forces that are two strong (due to granularity of the simulation's
* numeric integration). A maximum distance threshold improves performance by
* skipping force calculations for particles that are far apart.
*
* <p>The default domain is [2, 500].
*
* @function
* @name pv.Force.charge.prototype.domain
* @param {number} a
* @param {number} b
* @returns {pv.Force.charge} this.
*/
force.domain = function (a, b) {
if (arguments.length) {
min = Number(a);
min1 = 1 / min;
max = Number(b);
max1 = 1 / max;
return force;
}
return [min, max];
};
/**
* Sets or gets the Barnes-Hut approximation factor. The Barnes-Hut
* approximation criterion is the ratio of the size of the quadtree node to
* the distance from the point to the node's center of mass is beneath some
* threshold.
*
* @function
* @name pv.Force.charge.prototype.theta
* @param {number} x the new Barnes-Hut approximation factor.
* @returns {pv.Force.charge} this.
*/
force.theta = function (x) {
if (arguments.length) {
theta = Number(x);
return force;
}
return theta;
};
/**
* @ignore Recursively computes the center of charge for each node in the
* quadtree. This is equivalent to the center of mass, assuming that all
* particles have unit weight.
*/
function accumulate(n) {
var cx = 0, cy = 0;
n.cn = 0;
function accumulateChild(c) {
accumulate(c);
n.cn += c.cn;
cx += c.cn * c.cx;
cy += c.cn * c.cy;
}
if (!n.leaf) {
if (n.c1)
accumulateChild(n.c1);
if (n.c2)
accumulateChild(n.c2);
if (n.c3)
accumulateChild(n.c3);
if (n.c4)
accumulateChild(n.c4);
}
if (n.p) {
n.cn += k;
cx += k * n.p.x;
cy += k * n.p.y;
}
n.cx = cx / n.cn;
n.cy = cy / n.cn;
}
/**
* @ignore Recursively computes forces on the given particle using the given
* quadtree node. The Barnes-Hut approximation criterion is the ratio of the
* size of the quadtree node to the distance from the point to the node's
* center of mass is beneath some threshold.
*/
function forces(n, p, x1, y1, x2, y2) {
var dx = n.cx - p.x,
dy = n.cy - p.y,
dn = 1 / Math.sqrt(dx * dx + dy * dy);
/* Barnes-Hut criterion. */
if ((n.leaf && (n.p != p)) || ((x2 - x1) * dn < theta)) {
if (dn < max1)
return;
if (dn > min1)
dn = min1;
var kc = n.cn * dn * dn * dn,
fx = dx * kc,
fy = dy * kc;
p.fx += fx;
p.fy += fy;
} else if (!n.leaf) {
var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5;
if (n.c1)
forces(n.c1, p, x1, y1, sx, sy);
if (n.c2)
forces(n.c2, p, sx, y1, x2, sy);
if (n.c3)
forces(n.c3, p, x1, sy, sx, y2);
if (n.c4)
forces(n.c4, p, sx, sy, x2, y2);
if (dn < max1)
return;
if (dn > min1)
dn = min1;
if (n.p && (n.p != p)) {
var kc = k * dn * dn * dn,
fx = dx * kc,
fy = dy * kc;
p.fx += fx;
p.fy += fy;
}
}
}
/**
* Applies this force to the specified particles. The force is applied between
* all pairs of particles within the domain, using the specified quadtree to
* accelerate n-body force calculation using the Barnes-Hut approximation
* criterion.
*
* @function
* @name pv.Force.charge.prototype.apply
* @param {pv.Particle} particles particles to which to apply this force.
* @param {pv.Quadtree} q a quadtree for spatial acceleration.
*/
force.apply = function (particles, q) {
accumulate(q.root);
for (var p = particles; p; p = p.next) {
forces(q.root, p, q.xMin, q.yMin, q.xMax, q.yMax);
}
};
return force;
};
/**
* Constructs a new drag force with the specified constant.
*
* @class Implements a drag force, simulating friction. The drag force is
* applied in the opposite direction of the particle's velocity. Since Position
* Verlet integration does not track velocities explicitly, the error term with
* this estimate of velocity is fairly high, so the drag force may be
* inaccurate.
*
* @extends pv.Force
* @param {number} k the drag constant.
* @see #constant
*/
pv.Force.drag = function (k) {
var force = {};
if (!arguments.length)
k = .1; // default drag constant
/**
* Sets or gets the drag constant, in the range [0,1]. The default drag
* constant is 0.1. The drag forces scales linearly with the particle's
* velocity based on the given drag constant.
*
* @function
* @name pv.Force.drag.prototype.constant
* @param {number} x the new drag constant.
* @returns {pv.Force.drag} this, or the current drag constant.
*/
force.constant = function (x) {
if (arguments.length) {
k = x;
return force;
}
return k;
};
/**
* Applies this force to the specified particles.
*
* @function
* @name pv.Force.drag.prototype.apply
* @param {pv.Particle} particles particles to which to apply this force.
*/
force.apply = function (particles) {
if (k)
for (var p = particles; p; p = p.next) {
p.fx -= k * p.vx;
p.fy -= k * p.vy;
}
};
return force;
};
/**
* Constructs a new spring force with the specified constant. The links
* associated with this spring force must be specified before the spring force
* can be applied.
*
* @class Implements a spring force, per Hooke's law. The spring force can be
* configured with a tension constant, rest length, and damping factor. The
* tension and damping will automatically be normalized using the inverse square
* root of the maximum link degree of attached nodes; this makes springs weaker
* between nodes of high link degree.
*
* <p>Unlike other forces (such as charge and drag forces) which may be applied
* globally, spring forces are only applied between linked particles. Therefore,
* an array of links must be specified before this force can be applied; the
* links should be an array of {@link pv.Layout.Network.Link}s. See also
* {@link pv.Layout.Force} for an example of using spring and charge forces for
* network layout.
*
* @extends pv.Force
* @param {number} k the spring constant.
* @see #constant
* @see #links
*/
pv.Force.spring = function (k) {
var d = .1, // default damping factor
l = 20, // default rest length
links, // links on which to apply spring forces
kl, // per-spring normalization
force = {};
if (!arguments.length)
k = .1; // default spring constant (tension)
/**
* Sets or gets the links associated with this spring force. Unlike other
* forces (such as charge and drag forces) which may be applied globally,
* spring forces are only applied between linked particles. Therefore, an
* array of links must be specified before this force can be applied; the
* links should be an array of {@link pv.Layout.Network.Link}s.
*
* @function
* @name pv.Force.spring.prototype.links
* @param {array} x the new array of links.
* @returns {pv.Force.spring} this, or the current array of links.
*/
force.links = function (x) {
if (arguments.length) {
links = x;
kl = x.map(function (l) {
return 1 / Math.sqrt(Math.max(
l.sourceNode.linkDegree,
l.targetNode.linkDegree));
});
return force;
}
return links;
};
/**
* Sets or gets the spring constant. The default value is 0.1; greater values
* will result in stronger tension. The spring tension is automatically
* normalized using the inverse square root of the maximum link degree of
* attached nodes.
*
* @function
* @name pv.Force.spring.prototype.constant
* @param {number} x the new spring constant.
* @returns {pv.Force.spring} this, or the current spring constant.
*/
force.constant = function (x) {
if (arguments.length) {
k = Number(x);
return force;
}
return k;
};
/**
* The spring damping factor, in the range [0,1]. Damping functions
* identically to drag forces, damping spring bounciness by applying a force
* in the opposite direction of attached nodes' velocities. The default value
* is 0.1. The spring damping is automatically normalized using the inverse
* square root of the maximum link degree of attached nodes.
*
* @function
* @name pv.Force.spring.prototype.damping
* @param {number} x the new spring damping factor.
* @returns {pv.Force.spring} this, or the current spring damping factor.
*/
force.damping = function (x) {
if (arguments.length) {
d = Number(x);
return force;
}
return d;
};
/**
* The spring rest length. The default value is 20 pixels.
*
* @function
* @name pv.Force.spring.prototype.length
* @param {number} x the new spring rest length.
* @returns {pv.Force.spring} this, or the current spring rest length.
*/
force.length = function (x) {
if (arguments.length) {
l = Number(x);
return force;
}
return l;
};
/**
* Applies this force to the specified particles.
*
* @function
* @name pv.Force.spring.prototype.apply
* @param {pv.Particle} particles particles to which to apply this force.
*/
force.apply = function (particles) {
for (var i = 0; i < links.length; i++) {
var a = links[i].sourceNode,
b = links[i].targetNode,
dx = a.x - b.x,
dy = a.y - b.y,
dn = Math.sqrt(dx * dx + dy * dy),
dd = dn ? (1 / dn) : 1,
ks = k * kl[i], // normalized tension
kd = d * kl[i], // normalized damping
kk = (ks * (dn - l) + kd * (dx * (a.vx - b.vx) + dy * (a.vy - b.vy)) * dd) * dd,
fx = -kk * (dn ? dx : (.01 * (.5 - Math.random()))),
fy = -kk * (dn ? dy : (.01 * (.5 - Math.random())));
a.fx += fx;
a.fy += fy;
b.fx -= fx;
b.fy -= fy;
}
};
return force;
};
/**
* Abstract; see an implementing class.
*
* @class Represents a constraint that acts on particles. Note that this
* interface does not specify how to bind a constraint to specific particles; in
* general, constraints are applied globally to all particles. However, some
* constraints may be applied to specific particles or between particles, such
* as position constraints, through additional specialization.
*
* @see pv.Simulation
* @see pv.Particle
* @see pv.Constraint.bound
* @see pv.Constraint.collision
* @see pv.Constraint.position
*/
pv.Constraint = {};
/**
* Applies this constraint to the specified particles.
*
* @function
* @name pv.Constraint.prototype.apply
* @param {pv.Particle} particles particles to which to apply this constraint.
* @param {pv.Quadtree} q a quadtree for spatial acceleration.
* @returns {pv.Constraint} this.
*/
/**
* Constructs a new collision constraint. The default search radius is 10, and
* the default repeat count is 1. A radius function must be specified to compute
* the radius of particles.
*
* @class Constraints circles to avoid overlap. Each particle is treated as a
* circle, with the radius of the particle computed using a specified function.
* For example, if the particle has an <tt>r</tt> attribute storing the radius,
* the radius <tt>function(d) d.r</tt> specifies a collision constraint using
* this radius. The radius function is passed each {@link pv.Particle} as the
* first argument.
*
* <p>To accelerate collision detection, this implementation uses a quadtree and
* a search radius. The search radius is computed as the maximum radius of all
* particles in the simulation.
*
* @see pv.Constraint
* @param {function} radius the radius function.
*/
pv.Constraint.collision = function (radius) {
var n = 1, // number of times to repeat the constraint
r1,
px1,
py1,
px2,
py2,
constraint = {};
if (!arguments.length)
r1 = 10; // default search radius
/**
* Sets or gets the repeat count. If the repeat count is greater than 1, the
* constraint will be applied repeatedly; this is a form of the Gauss-Seidel
* method for constraints relaxation. Repeating the collision constraint makes
* the constraint have more of an effect when there is a potential for many
* co-occurring collisions.
*
* @function
* @name pv.Constraint.collision.prototype.repeat
* @param {number} x the number of times to repeat this constraint.
* @returns {pv.Constraint.collision} this.
*/
constraint.repeat = function (x) {
if (arguments.length) {
n = Number(x);
return constraint;
}
return n;
};
/** @private */
function constrain(n, p, x1, y1, x2, y2) {
if (!n.leaf) {
var sx = (x1 + x2) * .5,
sy = (y1 + y2) * .5,
top = sy > py1,
bottom = sy < py2,
left = sx > px1,
right = sx < px2;
if (top) {
if (n.c1 && left)
constrain(n.c1, p, x1, y1, sx, sy);
if (n.c2 && right)
constrain(n.c2, p, sx, y1, x2, sy);
}
if (bottom) {
if (n.c3 && left)
constrain(n.c3, p, x1, sy, sx, y2);
if (n.c4 && right)
constrain(n.c4, p, sx, sy, x2, y2);
}
}
if (n.p && (n.p != p)) {
var dx = p.x - n.p.x,
dy = p.y - n.p.y,
l = Math.sqrt(dx * dx + dy * dy),
d = r1 + radius(n.p);
if (l < d) {
var k = (l - d) / l * .5;
dx *= k;
dy *= k;
p.x -= dx;
p.y -= dy;
n.p.x += dx;
n.p.y += dy;
}
}
}
/**
* Applies this constraint to the specified particles.
*
* @function
* @name pv.Constraint.collision.prototype.apply
* @param {pv.Particle} particles particles to which to apply this constraint.
* @param {pv.Quadtree} q a quadtree for spatial acceleration.
*/
constraint.apply = function (particles, q) {
var p, r, max = -Infinity;
for (p = particles; p; p = p.next) {
r = radius(p);
if (r > max)
max = r;
}
for (var i = 0; i < n; i++) {
for (p = particles; p; p = p.next) {
r = (r1 = radius(p)) + max;
px1 = p.x - r;
px2 = p.x + r;
py1 = p.y - r;
py2 = p.y + r;
constrain(q.root, p, q.xMin, q.yMin, q.xMax, q.yMax);
}
}
};
return constraint;
};
/**
* Constructs a default position constraint using the <tt>fix</tt> attribute.
* An optional position function can be specified to determine how the fixed
* position per-particle is determined.
*
* @class Constraints particles to a fixed position. The fixed position per
* particle is determined using a given position function, which defaults to
* <tt>function(d) d.fix</tt>.
*
* <p>If the position function returns null, then no position constraint is
* applied to the given particle. Otherwise, the particle's position is set to
* the returned position, as expressed by a {@link pv.Vector}. (Note: the
* position does not need to be an instance of <tt>pv.Vector</tt>, but simply an
* object with <tt>x</tt> and <tt>y</tt> attributes.)
*
* <p>This constraint also supports a configurable alpha parameter, which
* defaults to 1. If the alpha parameter is in the range [0,1], then rather than
* setting the particle's new position directly to the position returned by the
* supplied position function, the particle's position is interpolated towards
* the fixed position. This results is a smooth (exponential) drift towards the
* fixed position, which can increase the stability of the physics simulation.
* In addition, the alpha parameter can be decayed over time, relaxing the
* position constraint, which helps to stabilize on an optimal solution.
*
* @param {function} [f] the position function.
*/
pv.Constraint.position = function (f) {
var a = 1, // default alpha
constraint = {};
if (!arguments.length) /** @ignore */
f = function (p) {
return p.fix;
};
/**
* Sets or gets the alpha parameter for position interpolation. If the alpha
* parameter is in the range [0,1], then rather than setting the particle's
* new position directly to the position returned by the supplied position
* function, the particle's position is interpolated towards the fixed
* position.
*
* @function
* @name pv.Constraint.position.prototype.alpha
* @param {number} x the new alpha parameter, in the range [0,1].
* @returns {pv.Constraint.position} this.
*/
constraint.alpha = function (x) {
if (arguments.length) {
a = Number(x);
return constraint;
}
return a;
};
/**
* Applies this constraint to the specified particles.
*
* @function
* @name pv.Constraint.position.prototype.apply
* @param {pv.Particle} particles particles to which to apply this constraint.
*/
constraint.apply = function (particles) {
for (var p = particles; p; p = p.next) {
var v = f(p);
if (v) {
p.x += (v.x - p.x) * a;
p.y += (v.y - p.y) * a;
p.fx = p.fy = p.vx = p.vy = 0;
}
}
};
return constraint;
};
/**
* Constructs a new bound constraint. Before the constraint can be used, the
* {@link #x} and {@link #y} methods must be call to specify the bounds.
*
* @class Constrains particles to within fixed rectangular bounds. For example,
* this constraint can be used to constrain particles in a physics simulation
* within the bounds of an enclosing panel.
*
* <p>Note that the current implementation treats particles as points, with no
* area. If the particles are rendered as dots, be sure to include some
* additional padding to inset the bounds such that the edges of the dots do not
* get clipped by the panel bounds. If the particles have different radii, this
* constraint would need to be extended using a radius function, similar to
* {@link pv.Constraint.collision}.
*
* @see pv.Layout.Force
* @extends pv.Constraint
*/
pv.Constraint.bound = function () {
var constraint = {},
x,
y;
/**
* Sets or gets the bounds on the x-coordinate.
*
* @function
* @name pv.Constraint.bound.prototype.x
* @param {number} min the minimum allowed x-coordinate.
* @param {number} max the maximum allowed x-coordinate.
* @returns {pv.Constraint.bound} this.
*/
constraint.x = function (min, max) {
if (arguments.length) {
x = {min: Math.min(min, max), max: Math.max(min, max)};
return this;
}
return x;
};
/**
* Sets or gets the bounds on the y-coordinate.
*
* @function
* @name pv.Constraint.bound.prototype.y
* @param {number} min the minimum allowed y-coordinate.
* @param {number} max the maximum allowed y-coordinate.
* @returns {pv.Constraint.bound} this.
*/
constraint.y = function (min, max) {
if (arguments.length) {
y = {min: Math.min(min, max), max: Math.max(min, max)};
return this;
}
return y;
};
/**
* Applies this constraint to the specified particles.
*
* @function
* @name pv.Constraint.bound.prototype.apply
* @param {pv.Particle} particles particles to which to apply this constraint.
*/
constraint.apply = function (particles) {
if (x)
for (var p = particles; p; p = p.next) {
p.x = p.x < x.min ? x.min : (p.x > x.max ? x.max : p.x);
}
if (y)
for (var p = particles; p; p = p.next) {
p.y = p.y < y.min ? y.min : (p.y > y.max ? y.max : p.y);
}
};
return constraint;
};
/**
* Constructs a new, empty layout with default properties. Layouts are not
* typically constructed directly; instead, a concrete subclass is added to an
* existing panel via {@link pv.Mark#add}.
*
* @class Represents an abstract layout, encapsulating a visualization technique
* such as a streamgraph or treemap. Layouts are themselves containers,
* extending from {@link pv.Panel}, and defining a set of mark prototypes as
* children. These mark prototypes provide default properties that together
* implement the given visualization technique.
*
* <p>Layouts do not initially contain any marks; any exported marks (such as a
* network layout's <tt>link</tt> and <tt>node</tt>) are intended to be used as
* prototypes. By adding a concrete mark, such as a {@link pv.Bar}, to the
* appropriate mark prototype, the mark is added to the layout and inherits the
* given properties. This approach allows further customization of the layout,
* either by choosing a different mark type to add, or more simply by overriding
* some of the layout's defined properties.
*
* <p>Each concrete layout, such as treemap or circle-packing, has different
* behavior and may export different mark prototypes, depending on what marks
* are typically needed to render the desired visualization. Therefore it is
* important to understand how each layout is structured, such that the provided
* mark prototypes are used appropriately.
*
* <p>In addition to the mark prototypes, layouts may define custom properties
* that affect the overall behavior of the layout. For example, a treemap layout
* might use a property to specify which layout algorithm to use. These
* properties are just like other mark properties, and can be defined as
* constants or as functions. As with panels, the data property can be used to
* replicate layouts, and properties can be defined to in terms of layout data.
*
* @extends pv.Panel
*/
pv.Layout = function () {
pv.Panel.call(this);
};
pv.Layout.prototype = pv.extend(pv.Panel);
/**
* @private Defines a local property with the specified name and cast. Note that
* although the property method is only defined locally, the cast function is
* global, which is necessary since properties are inherited!
*
* @param {string} name the property name.
* @param {function} [cast] the cast function for this property.
*/
pv.Layout.prototype.property = function (name, cast) {
if (!this.hasOwnProperty("properties")) {
this.properties = pv.extend(this.properties);
}
this.properties[name] = true;
this.propertyMethod(name, false, pv.Mark.cast[name] = cast);
return this;
};
/**
* Constructs a new, empty network layout. Layouts are not typically constructed
* directly; instead, they are added to an existing panel via
* {@link pv.Mark#add}.
*
* @class Represents an abstract layout for network diagrams. This class
* provides the basic structure for both node-link diagrams (such as
* force-directed graph layout) and space-filling network diagrams (such as
* sunbursts and treemaps). Note that "network" here is a general term that
* includes hierarchical structures; a tree is represented using links from
* child to parent.
*
* <p>Network layouts require the graph data structure to be defined using two
* properties:<ul>
*
* <li><tt>nodes</tt> - an array of objects representing nodes. Objects in this
* array must conform to the {@link pv.Layout.Network.Node} interface; which is
* to say, be careful to avoid naming collisions with automatic attributes such
* as <tt>index</tt> and <tt>linkDegree</tt>. If the nodes property is defined
* as an array of primitives, such as numbers or strings, these primitives are
* automatically wrapped in an object; the resulting object's <tt>nodeValue</tt>
* attribute points to the original primitive value.
*
* <p><li><tt>links</tt> - an array of objects representing links. Objects in
* this array must conform to the {@link pv.Layout.Network.Link} interface; at a
* minimum, either <tt>source</tt> and <tt>target</tt> indexes or
* <tt>sourceNode</tt> and <tt>targetNode</tt> references must be set. Note that
* if the links property is defined after the nodes property, the links can be
* defined in terms of <tt>this.nodes()</tt>.
*
* </ul>
*
* <p>Three standard mark prototypes are provided:<ul>
*
* <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Dot}. The node
* mark is added directly to the layout, with the data property defined via the
* layout's <tt>nodes</tt> property. Properties such as <tt>strokeStyle</tt> and
* <tt>fillStyle</tt> can be overridden to compute properties from node data
* dynamically.
*
* <p><li><tt>link</tt> - for rendering links; typically a {@link pv.Line}. The
* link mark is added to a child panel, whose data property is defined as
* layout's <tt>links</tt> property. The link's data property is then a
* two-element array of the source node and target node. Thus, poperties such as
* <tt>strokeStyle</tt> and <tt>fillStyle</tt> can be overridden to compute
* properties from either the node data (the first argument) or the link data
* (the second argument; the parent panel data) dynamically.
*
* <p><li><tt>label</tt> - for rendering node labels; typically a
* {@link pv.Label}. The label mark is added directly to the layout, with the
* data property defined via the layout's <tt>nodes</tt> property. Properties
* such as <tt>strokeStyle</tt> and <tt>fillStyle</tt> can be overridden to
* compute properties from node data dynamically.
*
* </ul>Note that some network implementations may not support all three
* standard mark prototypes; for example, space-filling hierarchical layouts
* typically do not use a <tt>link</tt> prototype, as the parent-child links are
* implied by the structure of the space-filling <tt>node</tt> marks. Check the
* specific network layout for implementation details.
*
* <p>Network layout properties, including <tt>nodes</tt> and <tt>links</tt>,
* are typically cached rather than re-evaluated with every call to render. This
* is a performance optimization, as network layout algorithms can be
* expensive. If the network structure changes, call {@link #reset} to clear the
* cache before rendering. Note that although the network layout properties are
* cached, child mark properties, such as the marks used to render the nodes and
* links, <i>are not</i>. Therefore, non-structural changes to the network
* layout, such as changing the color of a mark on mouseover, do not need to
* reset the layout.
*
* @see pv.Layout.Hierarchy
* @see pv.Layout.Force
* @see pv.Layout.Matrix
* @see pv.Layout.Arc
* @see pv.Layout.Rollup
* @extends pv.Layout
*/
pv.Layout.Network = function () {
pv.Layout.call(this);
var that = this;
/* @private Version tracking to cache layout state, improving performance. */
this.$id = pv.id();
/**
* The node prototype. This prototype is intended to be used with a Dot mark
* in conjunction with the link prototype.
*
* @type pv.Mark
* @name pv.Layout.Network.prototype.node
*/
(this.node = new pv.Mark()
.data(function () {
return that.nodes();
})
.strokeStyle("#1f77b4")
.fillStyle("#fff")
.left(function (n) {
return n.x;
})
.top(function (n) {
return n.y;
})).parent = this;
/**
* The link prototype, which renders edges between source nodes and target
* nodes. This prototype is intended to be used with a Line mark in
* conjunction with the node prototype.
*
* @type pv.Mark
* @name pv.Layout.Network.prototype.link
*/
this.link = new pv.Mark()
.extend(this.node)
.data(function (p) {
return [p.sourceNode, p.targetNode];
})
.fillStyle(null)
.lineWidth(function (d, p) {
return p.linkValue * 1.5;
})
.strokeStyle("rgba(0,0,0,.2)");
this.link.add = function (type) {
return that.add(pv.Panel)
.data(function () {
return that.links();
})
.add(type)
.extend(this);
};
/**
* The node label prototype, which renders the node name adjacent to the node.
* This prototype is provided as an alternative to using the anchor on the
* node mark; it is primarily intended to be used with radial node-link
* layouts, since it provides a convenient mechanism to set the text angle.
*
* @type pv.Mark
* @name pv.Layout.Network.prototype.label
*/
(this.label = new pv.Mark()
.extend(this.node)
.textMargin(7)
.textBaseline("middle")
.text(function (n) {
return n.nodeName || n.nodeValue;
})
.textAngle(function (n) {
var a = n.midAngle;
return pv.Wedge.upright(a) ? a : (a + Math.PI);
})
.textAlign(function (n) {
return pv.Wedge.upright(n.midAngle) ? "left" : "right";
})).parent = this;
};
/**
* @class Represents a node in a network layout. There is no explicit
* constructor; this class merely serves to document the attributes that are
* used on nodes in network layouts. (Note that hierarchical nodes place
* additional requirements on node representation, vis {@link pv.Dom.Node}.)
*
* @see pv.Layout.Network
* @name pv.Layout.Network.Node
*/
/**
* The node index, zero-based. This attribute is populated automatically based
* on the index in the array returned by the <tt>nodes</tt> property.
*
* @type number
* @name pv.Layout.Network.Node.prototype.index
*/
/**
* The link degree; the sum of link values for all incoming and outgoing links.
* This attribute is populated automatically.
*
* @type number
* @name pv.Layout.Network.Node.prototype.linkDegree
*/
/**
* The node name; optional. If present, this attribute will be used to provide
* the text for node labels. If not present, the label text will fallback to the
* <tt>nodeValue</tt> attribute.
*
* @type string
* @name pv.Layout.Network.Node.prototype.nodeName
*/
/**
* The node value; optional. If present, and no <tt>nodeName</tt> attribute is
* present, the node value will be used as the label text. This attribute is
* also automatically populated if the nodes are specified as an array of
* primitives, such as strings or numbers.
*
* @type object
* @name pv.Layout.Network.Node.prototype.nodeValue
*/
/**
* @class Represents a link in a network layout. There is no explicit
* constructor; this class merely serves to document the attributes that are
* used on links in network layouts. For hierarchical layouts, this class is
* used to represent the parent-child links.
*
* @see pv.Layout.Network
* @name pv.Layout.Network.Link
*/
/**
* The link value, or weight; optional. If not specified (or not a number), the
* default value of 1 is used.
*
* @type number
* @name pv.Layout.Network.Link.prototype.linkValue
*/
/**
* The link's source node. If not set, this value will be derived from the
* <tt>source</tt> attribute index.
*
* @type pv.Layout.Network.Node
* @name pv.Layout.Network.Link.prototype.sourceNode
*/
/**
* The link's target node. If not set, this value will be derived from the
* <tt>target</tt> attribute index.
*
* @type pv.Layout.Network.Node
* @name pv.Layout.Network.Link.prototype.targetNode
*/
/**
* Alias for <tt>sourceNode</tt>, as expressed by the index of the source node.
* This attribute is not populated automatically, but may be used as a more
* convenient identification of the link's source, for example in a static JSON
* representation.
*
* @type number
* @name pv.Layout.Network.Link.prototype.source
*/
/**
* Alias for <tt>targetNode</tt>, as expressed by the index of the target node.
* This attribute is not populated automatically, but may be used as a more
* convenient identification of the link's target, for example in a static JSON
* representation.
*
* @type number
* @name pv.Layout.Network.Link.prototype.target
*/
/**
* Alias for <tt>linkValue</tt>. This attribute is not populated automatically,
* but may be used instead of the <tt>linkValue</tt> attribute when specifying
* links.
*
* @type number
* @name pv.Layout.Network.Link.prototype.value
*/
/** @private Transform nodes and links on cast. */
pv.Layout.Network.prototype = pv.extend(pv.Layout)
.property("nodes", function (v) {
return v.map(function (d, i) {
if (typeof d != "object")
d = {nodeValue: d};
d.index = i;
return d;
});
})
.property("links", function (v) {
return v.map(function (d) {
if (isNaN(d.linkValue))
d.linkValue = isNaN(d.value) ? 1 : d.value;
return d;
});
});
/**
* Resets the cache, such that changes to layout property definitions will be
* visible on subsequent render. Unlike normal marks (and normal layouts),
* properties associated with network layouts are not automatically re-evaluated
* on render; the properties are cached, and any expensive layout algorithms are
* only run after the layout is explicitly reset.
*
* @returns {pv.Layout.Network} this.
*/
pv.Layout.Network.prototype.reset = function () {
this.$id = pv.id();
return this;
};
/** @private Skip evaluating properties if cached. */
pv.Layout.Network.prototype.buildProperties = function (s, properties) {
if ((s.$id || 0) < this.$id) {
pv.Layout.prototype.buildProperties.call(this, s, properties);
}
};
/** @private Compute link degrees; map source and target indexes to nodes. */
pv.Layout.Network.prototype.buildImplied = function (s) {
pv.Layout.prototype.buildImplied.call(this, s);
if (s.$id >= this.$id)
return true;
s.$id = this.$id;
s.nodes.forEach(function (d) {
d.linkDegree = 0;
});
s.links.forEach(function (d) {
var v = d.linkValue;
(d.sourceNode || (d.sourceNode = s.nodes[d.source])).linkDegree += v;
(d.targetNode || (d.targetNode = s.nodes[d.target])).linkDegree += v;
});
};
/**
* Constructs a new, empty hierarchy layout. Layouts are not typically
* constructed directly; instead, they are added to an existing panel via
* {@link pv.Mark#add}.
*
* @class Represents an abstract layout for hierarchy diagrams. This class is a
* specialization of {@link pv.Layout.Network}, providing the basic structure
* for both hierarchical node-link diagrams (such as Reingold-Tilford trees) and
* space-filling hierarchy diagrams (such as sunbursts and treemaps).
*
* <p>Unlike general network layouts, the <tt>links</tt> property need not be
* defined explicitly. Instead, the links are computed implicitly from the
* <tt>parentNode</tt> attribute of the node objects, as defined by the
* <tt>nodes</tt> property. This implementation is also available as
* {@link #links}, for reuse with non-hierarchical layouts; for example, to
* render a tree using force-directed layout.
*
* <p>Correspondingly, the <tt>nodes</tt> property is represented as a union of
* {@link pv.Layout.Network.Node} and {@link pv.Dom.Node}. To construct a node
* hierarchy from a simple JSON map, use the {@link pv.Dom} operator; this
* operator also provides an easy way to sort nodes before passing them to the
* layout.
*
* <p>For more details on how to use this layout, see
* {@link pv.Layout.Network}.
*
* @see pv.Layout.Cluster
* @see pv.Layout.Partition
* @see pv.Layout.Tree
* @see pv.Layout.Treemap
* @see pv.Layout.Indent
* @see pv.Layout.Pack
* @extends pv.Layout.Network
*/
pv.Layout.Hierarchy = function () {
pv.Layout.Network.call(this);
this.link.strokeStyle("#ccc");
};
pv.Layout.Hierarchy.prototype = pv.extend(pv.Layout.Network);
/** @private Compute the implied links. (Links are null by default.) */
pv.Layout.Hierarchy.prototype.buildImplied = function (s) {
if (!s.links)
s.links = pv.Layout.Hierarchy.links.call(this);
pv.Layout.Network.prototype.buildImplied.call(this, s);
};
/** The implied links; computes links using the <tt>parentNode</tt> attribute. */
pv.Layout.Hierarchy.links = function () {
return this.nodes()
.filter(function (n) {
return n.parentNode;
})
.map(function (n) {
return {
sourceNode: n,
targetNode: n.parentNode,
linkValue: 1
};
});
};
/** @private Provides standard node-link layout based on breadth & depth. */
pv.Layout.Hierarchy.NodeLink = {
/** @private */
buildImplied: function (s) {
var nodes = s.nodes,
orient = s.orient,
horizontal = /^(top|bottom)$/.test(orient),
w = s.width,
h = s.height;
/* Compute default inner and outer radius. */
if (orient == "radial") {
var ir = s.innerRadius, or = s.outerRadius;
if (ir == null)
ir = 0;
if (or == null)
or = Math.min(w, h) / 2;
}
/** @private Returns the radius of the given node. */
function radius(n) {
return n.parentNode ? (n.depth * (or - ir) + ir) : 0;
}
/** @private Returns the angle of the given node. */
function midAngle(n) {
return (n.parentNode ? (n.breadth - .25) * 2 * Math.PI : 0);
}
/** @private */
function x(n) {
switch (orient) {
case "left":
return n.depth * w;
case "right":
return w - n.depth * w;
case "top":
return n.breadth * w;
case "bottom":
return w - n.breadth * w;
case "radial":
return w / 2 + radius(n) * Math.cos(n.midAngle);
}
}
/** @private */
function y(n) {
switch (orient) {
case "left":
return n.breadth * h;
case "right":
return h - n.breadth * h;
case "top":
return n.depth * h;
case "bottom":
return h - n.depth * h;
case "radial":
return h / 2 + radius(n) * Math.sin(n.midAngle);
}
}
for (var i = 0; i < nodes.length; i++) {
var n = nodes[i];
n.midAngle = orient == "radial" ? midAngle(n)
: horizontal ? Math.PI / 2 : 0;
n.x = x(n);
n.y = y(n);
if (n.firstChild)
n.midAngle += Math.PI;
}
}
};
/** @private Provides standard space-filling layout based on breadth & depth. */
pv.Layout.Hierarchy.Fill = {
/** @private */
constructor: function () {
this.node
.strokeStyle("#fff")
.fillStyle("#ccc")
.width(function (n) {
return n.dx;
})
.height(function (n) {
return n.dy;
})
.innerRadius(function (n) {
return n.innerRadius;
})
.outerRadius(function (n) {
return n.outerRadius;
})
.startAngle(function (n) {
return n.startAngle;
})
.angle(function (n) {
return n.angle;
});
this.label
.textAlign("center")
.left(function (n) {
return n.x + (n.dx / 2);
})
.top(function (n) {
return n.y + (n.dy / 2);
});
/* Hide unsupported link. */
delete this.link;
},
/** @private */
buildImplied: function (s) {
var nodes = s.nodes,
orient = s.orient,
horizontal = /^(top|bottom)$/.test(orient),
w = s.width,
h = s.height,
depth = -nodes[0].minDepth;
/* Compute default inner and outer radius. */
if (orient == "radial") {
var ir = s.innerRadius, or = s.outerRadius;
if (ir == null)
ir = 0;
if (ir)
depth *= 2; // use full depth step for root
if (or == null)
or = Math.min(w, h) / 2;
}
/** @private Scales the specified depth for a space-filling layout. */
function scale(d, depth) {
return (d + depth) / (1 + depth);
}
/** @private */
function x(n) {
switch (orient) {
case "left":
return scale(n.minDepth, depth) * w;
case "right":
return (1 - scale(n.maxDepth, depth)) * w;
case "top":
return n.minBreadth * w;
case "bottom":
return (1 - n.maxBreadth) * w;
case "radial":
return w / 2;
}
}
/** @private */
function y(n) {
switch (orient) {
case "left":
return n.minBreadth * h;
case "right":
return (1 - n.maxBreadth) * h;
case "top":
return scale(n.minDepth, depth) * h;
case "bottom":
return (1 - scale(n.maxDepth, depth)) * h;
case "radial":
return h / 2;
}
}
/** @private */
function dx(n) {
switch (orient) {
case "left":
case "right":
return (n.maxDepth - n.minDepth) / (1 + depth) * w;
case "top":
case "bottom":
return (n.maxBreadth - n.minBreadth) * w;
case "radial":
return n.parentNode ? (n.innerRadius + n.outerRadius) * Math.cos(n.midAngle) : 0;
}
}
/** @private */
function dy(n) {
switch (orient) {
case "left":
case "right":
return (n.maxBreadth - n.minBreadth) * h;
case "top":
case "bottom":
return (n.maxDepth - n.minDepth) / (1 + depth) * h;
case "radial":
return n.parentNode ? (n.innerRadius + n.outerRadius) * Math.sin(n.midAngle) : 0;
}
}
/** @private */
function innerRadius(n) {
return Math.max(0, scale(n.minDepth, depth / 2)) * (or - ir) + ir;
}
/** @private */
function outerRadius(n) {
return scale(n.maxDepth, depth / 2) * (or - ir) + ir;
}
/** @private */
function startAngle(n) {
return (n.parentNode ? n.minBreadth - .25 : 0) * 2 * Math.PI;
}
/** @private */
function angle(n) {
return (n.parentNode ? n.maxBreadth - n.minBreadth : 1) * 2 * Math.PI;
}
for (var i = 0; i < nodes.length; i++) {
var n = nodes[i];
n.x = x(n);
n.y = y(n);
if (orient == "radial") {
n.innerRadius = innerRadius(n);
n.outerRadius = outerRadius(n);
n.startAngle = startAngle(n);
n.angle = angle(n);
n.midAngle = n.startAngle + n.angle / 2;
} else {
n.midAngle = horizontal ? -Math.PI / 2 : 0;
}
n.dx = dx(n);
n.dy = dy(n);
}
}
};
/**
* Constructs a new, empty grid layout. Layouts are not typically constructed
* directly; instead, they are added to an existing panel via
* {@link pv.Mark#add}.
*
* @class Implements a grid layout with regularly-sized rows and columns. The
* number of rows and columns are determined from their respective
* properties. For example, the 2×3 array:
*
* <pre>1 2 3
* 4 5 6</pre>
*
* can be represented using the <tt>rows</tt> property as:
*
* <pre>[[1, 2, 3], [4, 5, 6]]</pre>
*
* If your data is in column-major order, you can equivalently use the
* <tt>columns</tt> property. If the <tt>rows</tt> property is an array, it
* takes priority over the <tt>columns</tt> property. The data is implicitly
* transposed, as if the {@link pv.transpose} operator were applied.
*
* <p>This layout exports a single <tt>cell</tt> mark prototype, which is
* intended to be used with a bar, panel, layout, or subclass thereof. The data
* property of the cell prototype is defined as the elements in the array. For
* example, if the array is a two-dimensional array of values in the range
* [0,1], a simple heatmap can be generated as:
*
* <pre>vis.add(pv.Layout.Grid)
* .rows(arrays)
* .cell.add(pv.Bar)
* .fillStyle(pv.ramp("white", "black"))</pre>
*
* The grid subdivides the full width and height of the parent panel into equal
* rectangles. Note, however, that for large, interactive, or animated heatmaps,
* you may see significantly better performance through dynamic {@link pv.Image}
* generation.
*
* <p>For irregular grids using value-based spatial partitioning, see {@link
* pv.Layout.Treemap}.
*
* @extends pv.Layout
*/
pv.Layout.Grid = function () {
pv.Layout.call(this);
var that = this;
/**
* The cell prototype. This prototype is intended to be used with a bar,
* panel, or layout (or subclass thereof) to render the grid cells.
*
* @type pv.Mark
* @name pv.Layout.Grid.prototype.cell
*/
(this.cell = new pv.Mark()
.data(function () {
return that.scene[that.index].$grid;
})
.width(function () {
return that.width() / that.cols();
})
.height(function () {
return that.height() / that.rows();
})
.left(function () {
return this.width() * (this.index % that.cols());
})
.top(function () {
return this.height() * Math.floor(this.index / that.cols());
})).parent = this;
};
pv.Layout.Grid.prototype = pv.extend(pv.Layout)
.property("rows")
.property("cols");
/**
* Default properties for grid layouts. By default, there is one row and one
* column, and the data is the propagated to the child cell.
*
* @type pv.Layout.Grid
*/
pv.Layout.Grid.prototype.defaults = new pv.Layout.Grid()
.extend(pv.Layout.prototype.defaults)
.rows(1)
.cols(1);
/** @private */
pv.Layout.Grid.prototype.buildImplied = function (s) {
pv.Layout.prototype.buildImplied.call(this, s);
var r = s.rows, c = s.cols;
if (typeof c == "object")
r = pv.transpose(c);
if (typeof r == "object") {
s.$grid = pv.blend(r);
s.rows = r.length;
s.cols = r[0] ? r[0].length : 0;
} else {
s.$grid = pv.repeat([s.data], r * c);
}
};
/**
* The number of rows. This property can also be specified as the data in
* row-major order; in this case, the rows property is implicitly set to the
* length of the array, and the cols property is set to the length of the first
* element in the array.
*
* @type number
* @name pv.Layout.Grid.prototype.rows
*/
/**
* The number of columns. This property can also be specified as the data in
* column-major order; in this case, the cols property is implicitly set to the
* length of the array, and the rows property is set to the length of the first
* element in the array.
*
* @type number
* @name pv.Layout.Grid.prototype.cols
*/
/**
* Constructs a new, empty stack layout. Layouts are not typically constructed
* directly; instead, they are added to an existing panel via
* {@link pv.Mark#add}.
*
* @class Implements a layout for stacked visualizations, ranging from simple
* stacked bar charts to more elaborate "streamgraphs" composed of stacked
* areas. Stack layouts uses length as a visual encoding, as opposed to
* position, as the layers do not share an aligned axis.
*
* <p>Marks can be stacked vertically or horizontally. For example,
*
* <pre>vis.add(pv.Layout.Stack)
* .layers([[1, 1.2, 1.7, 1.5, 1.7],
* [.5, 1, .8, 1.1, 1.3],
* [.2, .5, .8, .9, 1]])
* .x(function() this.index * 35)
* .y(function(d) d * 40)
* .layer.add(pv.Area);</pre>
*
* specifies a vertically-stacked area chart, using the default "bottom-left"
* orientation with "zero" offset. This visualization can be easily changed into
* a streamgraph using the "wiggle" offset, which attempts to minimize change in
* slope weighted by layer thickness. See the {@link #offset} property for more
* supported streamgraph algorithms.
*
* <p>In the simplest case, the layer data can be specified as a two-dimensional
* array of numbers. The <tt>x</tt> and <tt>y</tt> psuedo-properties are used to
* define the thickness of each layer at the given position, respectively; in
* the above example of the "bottom-left" orientation, the <tt>x</tt> and
* <tt>y</tt> psuedo-properties are equivalent to the <tt>left</tt> and
* <tt>height</tt> properties that you might use if you implemented a stacked
* area by hand.
*
* <p>The advantage of using the stack layout is that the baseline, i.e., the
* <tt>bottom</tt> property is computed automatically using the specified offset
* algorithm. In addition, the order of layers can be computed using a built-in
* algorithm via the <tt>order</tt> property.
*
* <p>With the exception of the "expand" <tt>offset</tt>, the stack layout does
* not perform any automatic scaling of data; the values returned from
* <tt>x</tt> and <tt>y</tt> specify pixel sizes. To simplify scaling math, use
* this layout in conjunction with {@link pv.Scale.linear} or similar.
*
* <p>In other cases, the <tt>values</tt> psuedo-property can be used to define
* the data more flexibly. As with a typical panel & area, the
* <tt>layers</tt> property corresponds to the data in the enclosing panel,
* while the <tt>values</tt> psuedo-property corresponds to the data for the
* area within the panel. For example, given an array of data values:
*
* <pre>var crimea = [
* { date: "4/1854", wounds: 0, other: 110, disease: 110 },
* { date: "5/1854", wounds: 0, other: 95, disease: 105 },
* { date: "6/1854", wounds: 0, other: 40, disease: 95 },
* ...</pre>
*
* and a corresponding array of series names:
*
* <pre>var causes = ["wounds", "other", "disease"];</pre>
*
* Separate layers can be defined for each cause like so:
*
* <pre>vis.add(pv.Layout.Stack)
* .layers(causes)
* .values(crimea)
* .x(function(d) x(d.date))
* .y(function(d, p) y(d[p]))
* .layer.add(pv.Area)
* ...</pre>
*
* As with the panel & area case, the datum that is passed to the
* psuedo-properties <tt>x</tt> and <tt>y</tt> are the values (an element in
* <tt>crimea</tt>); the second argument is the layer data (a string in
* <tt>causes</tt>). Additional arguments specify the data of enclosing panels,
* if any.
*
* @extends pv.Layout
*/
pv.Layout.Stack = function () {
pv.Layout.call(this);
var that = this,
/** @ignore */ none = function () {
return null;
},
prop = {t: none, l: none, r: none, b: none, w: none, h: none},
values,
buildImplied = that.buildImplied;
/** @private Proxy the given property on the layer. */
function proxy(name) {
return function () {
return prop[name](this.parent.index, this.index);
};
}
/** @private Compute the layout! */
this.buildImplied = function (s) {
buildImplied.call(this, s);
var data = s.layers,
n = data.length,
m,
orient = s.orient,
horizontal = /^(top|bottom)\b/.test(orient),
h = this.parent[horizontal ? "height" : "width"](),
x = [],
y = [],
dy = [];
/*
* Iterate over the data, evaluating the values, x and y functions. The
* context in which the x and y psuedo-properties are evaluated is a
* pseudo-mark that is a grandchild of this layout.
*/
var stack = pv.Mark.stack, o = {parent: {parent: this}};
stack.unshift(null);
values = [];
for (var i = 0; i < n; i++) {
dy[i] = [];
y[i] = [];
o.parent.index = i;
stack[0] = data[i];
values[i] = this.$values.apply(o.parent, stack);
if (!i)
m = values[i].length;
stack.unshift(null);
for (var j = 0; j < m; j++) {
stack[0] = values[i][j];
o.index = j;
if (!i)
x[j] = this.$x.apply(o, stack);
dy[i][j] = this.$y.apply(o, stack);
}
stack.shift();
}
stack.shift();
/* order */
var index;
switch (s.order) {
case "inside-out":
{
var max = dy.map(function (v) {
return pv.max.index(v);
}),
map = pv.range(n).sort(function (a, b) {
return max[a] - max[b];
}),
sums = dy.map(function (v) {
return pv.sum(v);
}),
top = 0,
bottom = 0,
tops = [],
bottoms = [];
for (var i = 0; i < n; i++) {
var j = map[i];
if (top < bottom) {
top += sums[j];
tops.push(j);
} else {
bottom += sums[j];
bottoms.push(j);
}
}
index = bottoms.reverse().concat(tops);
break;
}
case "reverse":
index = pv.range(n - 1, -1, -1);
break;
default:
index = pv.range(n);
break;
}
/* offset */
switch (s.offset) {
case "silohouette":
{
for (var j = 0; j < m; j++) {
var o = 0;
for (var i = 0; i < n; i++)
o += dy[i][j];
y[index[0]][j] = (h - o) / 2;
}
break;
}
case "wiggle":
{
var o = 0;
for (var i = 0; i < n; i++)
o += dy[i][0];
y[index[0]][0] = o = (h - o) / 2;
for (var j = 1; j < m; j++) {
var s1 = 0, s2 = 0, dx = x[j] - x[j - 1];
for (var i = 0; i < n; i++)
s1 += dy[i][j];
for (var i = 0; i < n; i++) {
var s3 = (dy[index[i]][j] - dy[index[i]][j - 1]) / (2 * dx);
for (var k = 0; k < i; k++) {
s3 += (dy[index[k]][j] - dy[index[k]][j - 1]) / dx;
}
s2 += s3 * dy[index[i]][j];
}
y[index[0]][j] = o -= s1 ? s2 / s1 * dx : 0;
}
break;
}
case "expand":
{
for (var j = 0; j < m; j++) {
y[index[0]][j] = 0;
var k = 0;
for (var i = 0; i < n; i++)
k += dy[i][j];
if (k) {
k = h / k;
for (var i = 0; i < n; i++)
dy[i][j] *= k;
} else {
k = h / n;
for (var i = 0; i < n; i++)
dy[i][j] = k;
}
}
break;
}
default:
{
for (var j = 0; j < m; j++)
y[index[0]][j] = 0;
break;
}
}
/* Propagate the offset to the other series. */
for (var j = 0; j < m; j++) {
var o = y[index[0]][j];
for (var i = 1; i < n; i++) {
o += dy[index[i - 1]][j];
y[index[i]][j] = o;
}
}
/* Find the property definitions for dynamic substitution. */
var i = orient.indexOf("-"),
pdy = horizontal ? "h" : "w",
px = i < 0 ? (horizontal ? "l" : "b") : orient.charAt(i + 1),
py = orient.charAt(0);
for (var p in prop)
prop[p] = none;
prop[px] = function (i, j) {
return x[j];
};
prop[py] = function (i, j) {
return y[i][j];
};
prop[pdy] = function (i, j) {
return dy[i][j];
};
};
/**
* The layer prototype. This prototype is intended to be used with an area,
* bar or panel mark (or subclass thereof). Other mark types may be possible,
* though note that the stack layout is not currently designed to support
* radial stacked visualizations using wedges.
*
* <p>The layer is not a direct child of the stack layout; a hidden panel is
* used to replicate layers.
*
* @type pv.Mark
* @name pv.Layout.Stack.prototype.layer
*/
this.layer = new pv.Mark()
.data(function () {
return values[this.parent.index];
})
.top(proxy("t"))
.left(proxy("l"))
.right(proxy("r"))
.bottom(proxy("b"))
.width(proxy("w"))
.height(proxy("h"));
this.layer.add = function (type) {
return that.add(pv.Panel)
.data(function () {
return that.layers();
})
.add(type)
.extend(this);
};
};
pv.Layout.Stack.prototype = pv.extend(pv.Layout)
.property("orient", String)
.property("offset", String)
.property("order", String)
.property("layers");
/**
* Default properties for stack layouts. The default orientation is
* "bottom-left", the default offset is "zero", and the default layers is
* <tt>[[]]</tt>.
*
* @type pv.Layout.Stack
*/
pv.Layout.Stack.prototype.defaults = new pv.Layout.Stack()
.extend(pv.Layout.prototype.defaults)
.orient("bottom-left")
.offset("zero")
.layers([[]]);
/** @private */
pv.Layout.Stack.prototype.$x
= /** @private */ pv.Layout.Stack.prototype.$y
= function () {
return 0;
};
/**
* The x psuedo-property; determines the position of the value within the layer.
* This typically corresponds to the independent variable. For example, with the
* default "bottom-left" orientation, this function defines the "left" property.
*
* @param {function} f the x function.
* @returns {pv.Layout.Stack} this.
*/
pv.Layout.Stack.prototype.x = function (f) {
/** @private */ this.$x = pv.functor(f);
return this;
};
/**
* The y psuedo-property; determines the thickness of the layer at the given
* value. This typically corresponds to the dependent variable. For example,
* with the default "bottom-left" orientation, this function defines the
* "height" property.
*
* @param {function} f the y function.
* @returns {pv.Layout.Stack} this.
*/
pv.Layout.Stack.prototype.y = function (f) {
/** @private */ this.$y = pv.functor(f);
return this;
};
/** @private The default value function; identity. */
pv.Layout.Stack.prototype.$values = pv.identity;
/**
* The values function; determines the values for a given layer. The default
* value is the identity function, which assumes that the layers property is
* specified as a two-dimensional (i.e., nested) array.
*
* @param {function} f the values function.
* @returns {pv.Layout.Stack} this.
*/
pv.Layout.Stack.prototype.values = function (f) {
this.$values = pv.functor(f);
return this;
};
/**
* The layer data in row-major order. The value of this property is typically a
* two-dimensional (i.e., nested) array, but any array can be used, provided the
* values psuedo-property is defined accordingly.
*
* @type array[]
* @name pv.Layout.Stack.prototype.layers
*/
/**
* The layer orientation. The following values are supported:<ul>
*
* <li>bottom-left == bottom
* <li>bottom-right
* <li>top-left == top
* <li>top-right
* <li>left-top
* <li>left-bottom == left
* <li>right-top
* <li>right-bottom == right
*
* </ul>. The default value is "bottom-left", which means that the layers will
* be built from the bottom-up, and the values within layers will be laid out
* from left-to-right.
*
* <p>Note that with non-zero baselines, some orientations may give similar
* results. For example, offset("silohouette") centers the layers, resulting in
* a streamgraph. Thus, the orientations "bottom-left" and "top-left" will
* produce similar results, differing only in the layer order.
*
* @type string
* @name pv.Layout.Stack.prototype.orient
*/
/**
* The layer order. The following values are supported:<ul>
*
* <li><i>null</i> - use given layer order.
* <li>inside-out - sort by maximum value, with balanced order.
* <li>reverse - use reverse of given layer order.
*
* </ul>For details on the inside-out order algorithm, refer to "Stacked Graphs
* -- Geometry & Aesthetics" by L. Byron and M. Wattenberg, IEEE TVCG
* November/December 2008.
*
* @type string
* @name pv.Layout.Stack.prototype.order
*/
/**
* The layer offset; the y-position of the bottom of the lowest layer. The
* following values are supported:<ul>
*
* <li>zero - use a zero baseline, i.e., the y-axis.
* <li>silohouette - center the stream, i.e., ThemeRiver.
* <li>wiggle - minimize weighted change in slope.
* <li>expand - expand layers to fill the enclosing layout dimensions.
*
* </ul>For details on these offset algorithms, refer to "Stacked Graphs --
* Geometry & Aesthetics" by L. Byron and M. Wattenberg, IEEE TVCG
* November/December 2008.
*
* @type string
* @name pv.Layout.Stack.prototype.offset
*/
/**
* Constructs a new, empty treemap layout. Layouts are not typically
* constructed directly; instead, they are added to an existing panel via
* {@link pv.Mark#add}.
*
* @class Implements a space-filling rectangular layout, with the hierarchy
* represented via containment. Treemaps represent nodes as boxes, with child
* nodes placed within parent boxes. The size of each box is proportional to the
* size of the node in the tree. This particular algorithm is taken from Bruls,
* D.M., C. Huizing, and J.J. van Wijk, <a
* href="http://www.win.tue.nl/~vanwijk/stm.pdf">"Squarified Treemaps"</a> in
* <i>Data Visualization 2000, Proceedings of the Joint Eurographics and IEEE
* TCVG Sumposium on Visualization</i>, 2000, pp. 33-42.
*
* <p>The meaning of the exported mark prototypes changes slightly in the
* space-filling implementation:<ul>
*
* <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Bar}. The node
* data is populated with <tt>dx</tt> and <tt>dy</tt> attributes, in addition to
* the standard <tt>x</tt> and <tt>y</tt> position attributes.
*
* <p><li><tt>leaf</tt> - for rendering leaf nodes only, with no fill or stroke
* style by default; typically a {@link pv.Panel} or another layout!
*
* <p><li><tt>link</tt> - unsupported; undefined. Links are encoded implicitly
* in the arrangement of the space-filling nodes.
*
* <p><li><tt>label</tt> - for rendering node labels; typically a
* {@link pv.Label}.
*
* </ul>For more details on how to use this layout, see
* {@link pv.Layout.Hierarchy}.
*
* @extends pv.Layout.Hierarchy
*/
pv.Layout.Treemap = function () {
pv.Layout.Hierarchy.call(this);
this.node
.strokeStyle("#fff")
.fillStyle("rgba(31, 119, 180, .25)")
.width(function (n) {
return n.dx;
})
.height(function (n) {
return n.dy;
});
this.label
.visible(function (n) {
return !n.firstChild;
})
.left(function (n) {
return n.x + (n.dx / 2);
})
.top(function (n) {
return n.y + (n.dy / 2);
})
.textAlign("center")
.textAngle(function (n) {
return n.dx > n.dy ? 0 : -Math.PI / 2;
});
(this.leaf = new pv.Mark()
.extend(this.node)
.fillStyle(null)
.strokeStyle(null)
.visible(function (n) {
return !n.firstChild;
})).parent = this;
/* Hide unsupported link. */
delete this.link;
};
pv.Layout.Treemap.prototype = pv.extend(pv.Layout.Hierarchy)
.property("round", Boolean)
.property("paddingLeft", Number)
.property("paddingRight", Number)
.property("paddingTop", Number)
.property("paddingBottom", Number)
.property("mode", String)
.property("order", String);
/**
* Default propertiess for treemap layouts. The default mode is "squarify" and
* the default order is "ascending".
*
* @type pv.Layout.Treemap
*/
pv.Layout.Treemap.prototype.defaults = new pv.Layout.Treemap()
.extend(pv.Layout.Hierarchy.prototype.defaults)
.mode("squarify") // squarify, slice-and-dice, slice, dice
.order("ascending"); // ascending, descending, reverse, null
/**
* Whether node sizes should be rounded to integer values. This has a similar
* effect to setting <tt>antialias(false)</tt> for node values, but allows the
* treemap algorithm to accumulate error related to pixel rounding.
*
* @type boolean
* @name pv.Layout.Treemap.prototype.round
*/
/**
* The left inset between parent add child in pixels. Defaults to 0.
*
* @type number
* @name pv.Layout.Treemap.prototype.paddingLeft
* @see #padding
*/
/**
* The right inset between parent add child in pixels. Defaults to 0.
*
* @type number
* @name pv.Layout.Treemap.prototype.paddingRight
* @see #padding
*/
/**
* The top inset between parent and child in pixels. Defaults to 0.
*
* @type number
* @name pv.Layout.Treemap.prototype.paddingTop
* @see #padding
*/
/**
* The bottom inset between parent and child in pixels. Defaults to 0.
*
* @type number
* @name pv.Layout.Treemap.prototype.paddingBottom
* @see #padding
*/
/**
* The treemap algorithm. The default value is "squarify". The "slice-and-dice"
* algorithm may also be used, which alternates between horizontal and vertical
* slices for different depths. In addition, the "slice" and "dice" algorithms
* may be specified explicitly to control whether horizontal or vertical slices
* are used, which may be useful for nested treemap layouts.
*
* @type string
* @name pv.Layout.Treemap.prototype.mode
* @see <a
* href="ftp://ftp.cs.umd.edu/pub/hcil/Reports-Abstracts-Bibliography/2001-06html/2001-06.pdf"
* >"Ordered Treemap Layouts"</a> by B. Shneiderman & M. Wattenberg, IEEE
* InfoVis 2001.
*/
/**
* The sibling node order. A <tt>null</tt> value means to use the sibling order
* specified by the nodes property as-is; "reverse" will reverse the given
* order. The default value "ascending" will sort siblings in ascending order of
* size, while "descending" will do the reverse. For sorting based on data
* attributes other than size, use the default <tt>null</tt> for the order
* property, and sort the nodes beforehand using the {@link pv.Dom} operator.
*
* @type string
* @name pv.Layout.Treemap.prototype.order
*/
/**
* Alias for setting the left, right, top and bottom padding properties
* simultaneously.
*
* @see #paddingLeft
* @see #paddingRight
* @see #paddingTop
* @see #paddingBottom
* @returns {pv.Layout.Treemap} this.
*/
pv.Layout.Treemap.prototype.padding = function (n) {
return this.paddingLeft(n).paddingRight(n).paddingTop(n).paddingBottom(n);
};
/** @private The default size function. */
pv.Layout.Treemap.prototype.$size = function (d) {
return Number(d.nodeValue);
};
/**
* Specifies the sizing function. By default, the size function uses the
* <tt>nodeValue</tt> attribute of nodes as a numeric value: <tt>function(d)
* Number(d.nodeValue)</tt>.
*
* <p>The sizing function is invoked for each leaf node in the tree, per the
* <tt>nodes</tt> property. For example, if the tree data structure represents a
* file system, with files as leaf nodes, and each file has a <tt>bytes</tt>
* attribute, you can specify a size function as:
*
* <pre> .size(function(d) d.bytes)</pre>
*
* @param {function} f the new sizing function.
* @returns {pv.Layout.Treemap} this.
*/
pv.Layout.Treemap.prototype.size = function (f) {
this.$size = pv.functor(f);
return this;
};
/** @private */
pv.Layout.Treemap.prototype.buildImplied = function (s) {
if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s))
return;
var that = this,
nodes = s.nodes,
root = nodes[0],
stack = pv.Mark.stack,
left = s.paddingLeft,
right = s.paddingRight,
top = s.paddingTop,
bottom = s.paddingBottom,
/** @ignore */ size = function (n) {
return n.size;
},
round = s.round ? Math.round : Number,
mode = s.mode;
/** @private */
function slice(row, sum, horizontal, x, y, w, h) {
for (var i = 0, d = 0; i < row.length; i++) {
var n = row[i];
if (horizontal) {
n.x = x + d;
n.y = y;
d += n.dx = round(w * n.size / sum);
n.dy = h;
} else {
n.x = x;
n.y = y + d;
n.dx = w;
d += n.dy = round(h * n.size / sum);
}
}
if (n) { // correct on-axis rounding error
if (horizontal) {
n.dx += w - d;
} else {
n.dy += h - d;
}
}
}
/** @private */
function ratio(row, l) {
var rmax = -Infinity, rmin = Infinity, s = 0;
for (var i = 0; i < row.length; i++) {
var r = row[i].size;
if (r < rmin)
rmin = r;
if (r > rmax)
rmax = r;
s += r;
}
s = s * s;
l = l * l;
return Math.max(l * rmax / s, s / (l * rmin));
}
/** @private */
function layout(n, i) {
var x = n.x + left,
y = n.y + top,
w = n.dx - left - right,
h = n.dy - top - bottom;
/* Assume squarify by default. */
if (mode != "squarify") {
slice(n.childNodes, n.size,
mode == "slice" ? true
: mode == "dice" ? false
: i & 1, x, y, w, h);
return;
}
var row = [],
mink = Infinity,
l = Math.min(w, h),
k = w * h / n.size;
/* Abort if the size is nonpositive. */
if (n.size <= 0)
return;
/* Scale the sizes to fill the current subregion. */
n.visitBefore(function (n) {
n.size *= k;
});
/** @private Position the specified nodes along one dimension. */
function position(row) {
var horizontal = w == l,
sum = pv.sum(row, size),
r = l ? round(sum / l) : 0;
slice(row, sum, horizontal, x, y, horizontal ? w : r, horizontal ? r : h);
if (horizontal) {
y += r;
h -= r;
} else {
x += r;
w -= r;
}
l = Math.min(w, h);
return horizontal;
}
var children = n.childNodes.slice(); // copy
while (children.length) {
var child = children[children.length - 1];
if (!child.size) {
children.pop();
continue;
}
row.push(child);
var k = ratio(row, l);
if (k <= mink) {
children.pop();
mink = k;
} else {
row.pop();
position(row);
row.length = 0;
mink = Infinity;
}
}
/* correct off-axis rounding error */
if (position(row))
for (var i = 0; i < row.length; i++) {
row[i].dy += h;
}
else
for (var i = 0; i < row.length; i++) {
row[i].dx += w;
}
}
/* Recursively compute the node depth and size. */
stack.unshift(null);
root.visitAfter(function (n, i) {
n.depth = i;
n.x = n.y = n.dx = n.dy = 0;
n.size = n.firstChild
? pv.sum(n.childNodes, function (n) {
return n.size;
})
: that.$size.apply(that, (stack[0] = n, stack));
});
stack.shift();
/* Sort. */
switch (s.order) {
case "ascending":
{
root.sort(function (a, b) {
return a.size - b.size;
});
break;
}
case "descending":
{
root.sort(function (a, b) {
return b.size - a.size;
});
break;
}
case "reverse":
root.reverse();
break;
}
/* Recursively compute the layout. */
root.x = 0;
root.y = 0;
root.dx = s.width;
root.dy = s.height;
root.visitBefore(layout);
};
/**
* Constructs a new, empty tree layout. Layouts are not typically constructed
* directly; instead, they are added to an existing panel via
* {@link pv.Mark#add}.
*
* @class Implements a node-link tree diagram using the Reingold-Tilford "tidy"
* tree layout algorithm. The specific algorithm used by this layout is based on
* <a href="http://citeseer.ist.psu.edu/buchheim02improving.html">"Improving
* Walker's Algorithm to Run in Linear Time"</A> by C. Buchheim, M. Jünger
* & S. Leipert, Graph Drawing 2002. This layout supports both cartesian and
* radial orientations orientations for node-link diagrams.
*
* <p>The tree layout supports a "group" property, which if true causes siblings
* to be positioned closer together than unrelated nodes at the same depth. The
* layout can be configured using the <tt>depth</tt> and <tt>breadth</tt>
* properties, which control the increments in pixel space between nodes in both
* dimensions, similar to the indent layout.
*
* <p>For more details on how to use this layout, see
* {@link pv.Layout.Hierarchy}.
*
* @extends pv.Layout.Hierarchy
*/
pv.Layout.Tree = function () {
pv.Layout.Hierarchy.call(this);
};
pv.Layout.Tree.prototype = pv.extend(pv.Layout.Hierarchy)
.property("group", Number)
.property("breadth", Number)
.property("depth", Number)
.property("orient", String);
/**
* Default properties for tree layouts. The default orientation is "top", the
* default group parameter is 1, and the default breadth and depth offsets are
* 15 and 60 respectively.
*
* @type pv.Layout.Tree
*/
pv.Layout.Tree.prototype.defaults = new pv.Layout.Tree()
.extend(pv.Layout.Hierarchy.prototype.defaults)
.group(1)
.breadth(15)
.depth(60)
.orient("top");
/** @private */
pv.Layout.Tree.prototype.buildImplied = function (s) {
if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s))
return;
var nodes = s.nodes,
orient = s.orient,
depth = s.depth,
breadth = s.breadth,
group = s.group,
w = s.width,
h = s.height;
/** @private */
function firstWalk(v) {
var l, r, a;
if (!v.firstChild) {
if (l = v.previousSibling) {
v.prelim = l.prelim + distance(v.depth, true);
}
} else {
l = v.firstChild;
r = v.lastChild;
a = l; // default ancestor
for (var c = l; c; c = c.nextSibling) {
firstWalk(c);
a = apportion(c, a);
}
executeShifts(v);
var midpoint = .5 * (l.prelim + r.prelim);
if (l = v.previousSibling) {
v.prelim = l.prelim + distance(v.depth, true);
v.mod = v.prelim - midpoint;
} else {
v.prelim = midpoint;
}
}
}
/** @private */
function secondWalk(v, m, depth) {
v.breadth = v.prelim + m;
m += v.mod;
for (var c = v.firstChild; c; c = c.nextSibling) {
secondWalk(c, m, depth);
}
}
/** @private */
function apportion(v, a) {
var w = v.previousSibling;
if (w) {
var vip = v,
vop = v,
vim = w,
vom = v.parentNode.firstChild,
sip = vip.mod,
sop = vop.mod,
sim = vim.mod,
som = vom.mod,
nr = nextRight(vim),
nl = nextLeft(vip);
while (nr && nl) {
vim = nr;
vip = nl;
vom = nextLeft(vom);
vop = nextRight(vop);
vop.ancestor = v;
var shift = (vim.prelim + sim) - (vip.prelim + sip) + distance(vim.depth, false);
if (shift > 0) {
moveSubtree(ancestor(vim, v, a), v, shift);
sip += shift;
sop += shift;
}
sim += vim.mod;
sip += vip.mod;
som += vom.mod;
sop += vop.mod;
nr = nextRight(vim);
nl = nextLeft(vip);
}
if (nr && !nextRight(vop)) {
vop.thread = nr;
vop.mod += sim - sop;
}
if (nl && !nextLeft(vom)) {
vom.thread = nl;
vom.mod += sip - som;
a = v;
}
}
return a;
}
/** @private */
function nextLeft(v) {
return v.firstChild || v.thread;
}
/** @private */
function nextRight(v) {
return v.lastChild || v.thread;
}
/** @private */
function moveSubtree(wm, wp, shift) {
var subtrees = wp.number - wm.number;
wp.change -= shift / subtrees;
wp.shift += shift;
wm.change += shift / subtrees;
wp.prelim += shift;
wp.mod += shift;
}
/** @private */
function executeShifts(v) {
var shift = 0, change = 0;
for (var c = v.lastChild; c; c = c.previousSibling) {
c.prelim += shift;
c.mod += shift;
change += c.change;
shift += c.shift + change;
}
}
/** @private */
function ancestor(vim, v, a) {
return (vim.ancestor.parentNode == v.parentNode) ? vim.ancestor : a;
}
/** @private */
function distance(depth, siblings) {
return (siblings ? 1 : (group + 1)) / ((orient == "radial") ? depth : 1);
}
/* Initialize temporary layout variables. TODO: store separately. */
var root = nodes[0];
root.visitAfter(function (v, i) {
v.ancestor = v;
v.prelim = 0;
v.mod = 0;
v.change = 0;
v.shift = 0;
v.number = v.previousSibling ? (v.previousSibling.number + 1) : 0;
v.depth = i;
});
/* Compute the layout using Buchheim et al.'s algorithm. */
firstWalk(root);
secondWalk(root, -root.prelim, 0);
/** @private Returns the angle of the given node. */
function midAngle(n) {
return (orient == "radial") ? n.breadth / depth : 0;
}
/** @private */
function x(n) {
switch (orient) {
case "left":
return n.depth;
case "right":
return w - n.depth;
case "top":
case "bottom":
return n.breadth + w / 2;
case "radial":
return w / 2 + n.depth * Math.cos(midAngle(n));
}
}
/** @private */
function y(n) {
switch (orient) {
case "left":
case "right":
return n.breadth + h / 2;
case "top":
return n.depth;
case "bottom":
return h - n.depth;
case "radial":
return h / 2 + n.depth * Math.sin(midAngle(n));
}
}
/* Clear temporary layout variables; transform depth and breadth. */
root.visitAfter(function (v) {
v.breadth *= breadth;
v.depth *= depth;
v.midAngle = midAngle(v);
v.x = x(v);
v.y = y(v);
if (v.firstChild)
v.midAngle += Math.PI;
delete v.breadth;
delete v.depth;
delete v.ancestor;
delete v.prelim;
delete v.mod;
delete v.change;
delete v.shift;
delete v.number;
delete v.thread;
});
};
/**
* The offset between siblings nodes; defaults to 15.
*
* @type number
* @name pv.Layout.Tree.prototype.breadth
*/
/**
* The offset between parent and child nodes; defaults to 60.
*
* @type number
* @name pv.Layout.Tree.prototype.depth
*/
/**
* The orientation. The default orientation is "top", which means that the root
* node is placed on the top edge, leaf nodes appear at the bottom, and internal
* nodes are in-between. The following orientations are supported:<ul>
*
* <li>left - left-to-right.
* <li>right - right-to-left.
* <li>top - top-to-bottom.
* <li>bottom - bottom-to-top.
* <li>radial - radially, with the root at the center.</ul>
*
* @type string
* @name pv.Layout.Tree.prototype.orient
*/
/**
* The sibling grouping, i.e., whether differentiating space is placed between
* sibling groups. The default is 1 (or true), causing sibling leaves to be
* separated by one breadth offset. Setting this to false (or 0) causes
* non-siblings to be adjacent.
*
* @type number
* @name pv.Layout.Tree.prototype.group
*/
/**
* Constructs a new, empty indent layout. Layouts are not typically constructed
* directly; instead, they are added to an existing panel via
* {@link pv.Mark#add}.
*
* @class Implements a hierarchical layout using the indent algorithm. This
* layout implements a node-link diagram where the nodes are presented in
* preorder traversal, and nodes are indented based on their depth from the
* root. This technique is used ubiquitously by operating systems to represent
* file directories; although it requires much vertical space, indented trees
* allow efficient <i>interactive</i> exploration of trees to find a specific
* node. In addition they allow rapid scanning of node labels, and multivariate
* data such as file sizes can be displayed adjacent to the hierarchy.
*
* <p>The indent layout can be configured using the <tt>depth</tt> and
* <tt>breadth</tt> properties, which control the increments in pixel space for
* each indent and row in the layout. This layout does not support multiple
* orientations; the root node is rendered in the top-left, while
* <tt>breadth</tt> is a vertical offset from the top, and <tt>depth</tt> is a
* horizontal offset from the left.
*
* <p>For more details on how to use this layout, see
* {@link pv.Layout.Hierarchy}.
*
* @extends pv.Layout.Hierarchy
*/
pv.Layout.Indent = function () {
pv.Layout.Hierarchy.call(this);
this.link.interpolate("step-after");
};
pv.Layout.Indent.prototype = pv.extend(pv.Layout.Hierarchy)
.property("depth", Number)
.property("breadth", Number);
/**
* The horizontal offset between different levels of the tree; defaults to 15.
*
* @type number
* @name pv.Layout.Indent.prototype.depth
*/
/**
* The vertical offset between nodes; defaults to 15.
*
* @type number
* @name pv.Layout.Indent.prototype.breadth
*/
/**
* Default properties for indent layouts. By default the depth and breadth
* offsets are 15 pixels.
*
* @type pv.Layout.Indent
*/
pv.Layout.Indent.prototype.defaults = new pv.Layout.Indent()
.extend(pv.Layout.Hierarchy.prototype.defaults)
.depth(15)
.breadth(15);
/** @private */
pv.Layout.Indent.prototype.buildImplied = function (s) {
if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s))
return;
var nodes = s.nodes,
bspace = s.breadth,
dspace = s.depth,
ax = 0,
ay = 0;
/** @private */
function position(n, breadth, depth) {
n.x = ax + depth++ * dspace;
n.y = ay + breadth++ * bspace;
n.midAngle = 0;
for (var c = n.firstChild; c; c = c.nextSibling) {
breadth = position(c, breadth, depth);
}
return breadth;
}
position(nodes[0], 1, 1);
};
/**
* Constructs a new, empty circle-packing layout. Layouts are not typically
* constructed directly; instead, they are added to an existing panel via
* {@link pv.Mark#add}.
*
* @class Implements a hierarchical layout using circle-packing. The meaning of
* the exported mark prototypes changes slightly in the space-filling
* implementation:<ul>
*
* <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Dot}.
*
* <p><li><tt>link</tt> - unsupported; undefined. Links are encoded implicitly
* in the arrangement of the space-filling nodes.
*
* <p><li><tt>label</tt> - for rendering node labels; typically a
* {@link pv.Label}.
*
* </ul>The pack layout support dynamic sizing for leaf nodes, if a
* {@link #size} psuedo-property is specified. The default size function returns
* 1, causing all leaf nodes to be sized equally, and all internal nodes to be
* sized by the number of leaf nodes they have as descendants.
*
* <p>The size function can be used in conjunction with the order property,
* which allows the nodes to the sorted by the computed size. Note: for sorting
* based on other data attributes, simply use the default <tt>null</tt> for the
* order property, and sort the nodes beforehand using the {@link pv.Dom}
* operator.
*
* <p>For more details on how to use this layout, see
* {@link pv.Layout.Hierarchy}.
*
* @extends pv.Layout.Hierarchy
* @see <a href="http://portal.acm.org/citation.cfm?id=1124772.1124851"
* >"Visualization of large hierarchical data by circle packing"</a> by W. Wang,
* H. Wang, G. Dai, and H. Wang, ACM CHI 2006.
*/
pv.Layout.Pack = function () {
pv.Layout.Hierarchy.call(this);
this.node
.radius(function (n) {
return n.radius;
})
.strokeStyle("rgb(31, 119, 180)")
.fillStyle("rgba(31, 119, 180, .25)");
this.label
.textAlign("center");
/* Hide unsupported link. */
delete this.link;
};
pv.Layout.Pack.prototype = pv.extend(pv.Layout.Hierarchy)
.property("spacing", Number)
.property("order", String); // ascending, descending, reverse, null
/**
* Default properties for circle-packing layouts. The default spacing parameter
* is 1 and the default order is "ascending".
*
* @type pv.Layout.Pack
*/
pv.Layout.Pack.prototype.defaults = new pv.Layout.Pack()
.extend(pv.Layout.Hierarchy.prototype.defaults)
.spacing(1)
.order("ascending");
/**
* The spacing parameter; defaults to 1, which provides a little bit of padding
* between sibling nodes and the enclosing circle. Larger values increase the
* spacing, by making the sibling nodes smaller; a value of zero makes the leaf
* nodes as large as possible, with no padding on enclosing circles.
*
* @type number
* @name pv.Layout.Pack.prototype.spacing
*/
/**
* The sibling node order. The default order is <tt>null</tt>, which means to
* use the sibling order specified by the nodes property as-is. A value of
* "ascending" will sort siblings in ascending order of size, while "descending"
* will do the reverse. For sorting based on data attributes other than size,
* use the default <tt>null</tt> for the order property, and sort the nodes
* beforehand using the {@link pv.Dom} operator.
*
* @see pv.Dom.Node#sort
* @type string
* @name pv.Layout.Pack.prototype.order
*/
/** @private The default size function. */
pv.Layout.Pack.prototype.$radius = function () {
return 1;
};
// TODO is it possible for spacing to operate in pixel space?
// Right now it appears to be multiples of the smallest radius.
/**
* Specifies the sizing function. By default, a sizing function is disabled and
* all nodes are given constant size. The sizing function is invoked for each
* leaf node in the tree (passed to the constructor).
*
* <p>For example, if the tree data structure represents a file system, with
* files as leaf nodes, and each file has a <tt>bytes</tt> attribute, you can
* specify a size function as:
*
* <pre> .size(function(d) d.bytes)</pre>
*
* As with other properties, a size function may specify additional arguments to
* access the data associated with the layout and any enclosing panels.
*
* @param {function} f the new sizing function.
* @returns {pv.Layout.Pack} this.
*/
pv.Layout.Pack.prototype.size = function (f) {
this.$radius = typeof f == "function"
? function () {
return Math.sqrt(f.apply(this, arguments));
}
: (f = Math.sqrt(f), function () {
return f;
});
return this;
};
/** @private */
pv.Layout.Pack.prototype.buildImplied = function (s) {
if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s))
return;
var that = this,
nodes = s.nodes,
root = nodes[0];
/** @private Compute the radii of the leaf nodes. */
function radii(nodes) {
var stack = pv.Mark.stack;
stack.unshift(null);
for (var i = 0, n = nodes.length; i < n; i++) {
var c = nodes[i];
if (!c.firstChild) {
c.radius = that.$radius.apply(that, (stack[0] = c, stack));
}
}
stack.shift();
}
/** @private */
function packTree(n) {
var nodes = [];
for (var c = n.firstChild; c; c = c.nextSibling) {
if (c.firstChild)
c.radius = packTree(c);
c.n = c.p = c;
nodes.push(c);
}
/* Sort. */
switch (s.order) {
case "ascending":
{
nodes.sort(function (a, b) {
return a.radius - b.radius;
});
break;
}
case "descending":
{
nodes.sort(function (a, b) {
return b.radius - a.radius;
});
break;
}
case "reverse":
nodes.reverse();
break;
}
return packCircle(nodes);
}
/** @private */
function packCircle(nodes) {
var xMin = Infinity,
xMax = -Infinity,
yMin = Infinity,
yMax = -Infinity,
a, b, c, j, k;
/** @private */
function bound(n) {
xMin = Math.min(n.x - n.radius, xMin);
xMax = Math.max(n.x + n.radius, xMax);
yMin = Math.min(n.y - n.radius, yMin);
yMax = Math.max(n.y + n.radius, yMax);
}
/** @private */
function insert(a, b) {
var c = a.n;
a.n = b;
b.p = a;
b.n = c;
c.p = b;
}
/** @private */
function splice(a, b) {
a.n = b;
b.p = a;
}
/** @private */
function intersects(a, b) {
var dx = b.x - a.x,
dy = b.y - a.y,
dr = a.radius + b.radius;
return (dr * dr - dx * dx - dy * dy) > .001; // within epsilon
}
/* Create first node. */
a = nodes[0];
a.x = -a.radius;
a.y = 0;
bound(a);
/* Create second node. */
if (nodes.length > 1) {
b = nodes[1];
b.x = b.radius;
b.y = 0;
bound(b);
/* Create third node and build chain. */
if (nodes.length > 2) {
c = nodes[2];
place(a, b, c);
bound(c);
insert(a, c);
a.p = c;
insert(c, b);
b = a.n;
/* Now iterate through the rest. */
for (var i = 3; i < nodes.length; i++) {
place(a, b, c = nodes[i]);
/* Search for the closest intersection. */
var isect = 0, s1 = 1, s2 = 1;
for (j = b.n; j != b; j = j.n, s1++) {
if (intersects(j, c)) {
isect = 1;
break;
}
}
if (isect == 1) {
for (k = a.p; k != j.p; k = k.p, s2++) {
if (intersects(k, c)) {
if (s2 < s1) {
isect = -1;
j = k;
}
break;
}
}
}
/* Update node chain. */
if (isect == 0) {
insert(a, c);
b = c;
bound(c);
} else if (isect > 0) {
splice(a, j);
b = j;
i--;
} else if (isect < 0) {
splice(j, b);
a = j;
i--;
}
}
}
}
/* Re-center the circles and return the encompassing radius. */
var cx = (xMin + xMax) / 2,
cy = (yMin + yMax) / 2,
cr = 0;
for (var i = 0; i < nodes.length; i++) {
var n = nodes[i];
n.x -= cx;
n.y -= cy;
cr = Math.max(cr, n.radius + Math.sqrt(n.x * n.x + n.y * n.y));
}
return cr + s.spacing;
}
/** @private */
function place(a, b, c) {
var da = b.radius + c.radius,
db = a.radius + c.radius,
dx = b.x - a.x,
dy = b.y - a.y,
dc = Math.sqrt(dx * dx + dy * dy),
cos = (db * db + dc * dc - da * da) / (2 * db * dc),
theta = Math.acos(cos),
x = cos * db,
h = Math.sin(theta) * db;
dx /= dc;
dy /= dc;
c.x = a.x + x * dx + h * dy;
c.y = a.y + x * dy - h * dx;
}
/** @private */
function transform(n, x, y, k) {
for (var c = n.firstChild; c; c = c.nextSibling) {
c.x += n.x;
c.y += n.y;
transform(c, x, y, k);
}
n.x = x + k * n.x;
n.y = y + k * n.y;
n.radius *= k;
}
radii(nodes);
/* Recursively compute the layout. */
root.x = 0;
root.y = 0;
root.radius = packTree(root);
var w = this.width(),
h = this.height(),
k = 1 / Math.max(2 * root.radius / w, 2 * root.radius / h);
transform(root, w / 2, h / 2, k);
};
/**
* Constructs a new, empty force-directed layout. Layouts are not typically
* constructed directly; instead, they are added to an existing panel via
* {@link pv.Mark#add}.
*
* @class Implements force-directed network layout as a node-link diagram. This
* layout uses the Fruchterman-Reingold algorithm, which applies an attractive
* spring force between neighboring nodes, and a repulsive electrical charge
* force between all nodes. An additional drag force improves stability of the
* simulation. See {@link pv.Force.spring}, {@link pv.Force.drag} and {@link
* pv.Force.charge} for more details; note that the n-body charge force is
* approximated using the Barnes-Hut algorithm.
*
* <p>This layout is implemented on top of {@link pv.Simulation}, which can be
* used directly for more control over simulation parameters. The simulation
* uses Position Verlet integration, which does not compute velocities
* explicitly, but allows for easy geometric constraints, such as bounding the
* nodes within the layout panel. Many of the configuration properties supported
* by this layout are simply passed through to the underlying forces and
* constraints of the simulation.
*
* <p>Force layouts are typically interactive. The gradual movement of the nodes
* as they stabilize to a local stress minimum can help reveal the structure of
* the network, as can {@link pv.Behavior.drag}, which allows the user to pick
* up nodes and reposition them while the physics simulation continues. This
* layout can also be used with pan & zoom behaviors for interaction.
*
* <p>To facilitate interaction, this layout by default automatically re-renders
* using a <tt>setInterval</tt> every 42 milliseconds. This can be disabled via
* the <tt>iterations</tt> property, which if non-null specifies the number of
* simulation iterations to run before the force-directed layout is finalized.
* Be careful not to use too high an iteration count, as this can lead to an
* annoying delay on page load.
*
* <p>As with other network layouts, the network data can be updated
* dynamically, provided the property cache is reset. See
* {@link pv.Layout.Network} for details. New nodes are initialized with random
* positions near the center. Alternatively, positions can be specified manually
* by setting the <tt>x</tt> and <tt>y</tt> attributes on nodes.
*
* @extends pv.Layout.Network
* @see <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.13.8444&rep=rep1&type=pdf"
* >"Graph Drawing by Force-directed Placement"</a> by T. Fruchterman &
* E. Reingold, Software--Practice & Experience, November 1991.
*/
pv.Layout.Force = function () {
pv.Layout.Network.call(this);
/* Force-directed graphs can be messy, so reduce the link width. */
this.link.lineWidth(function (d, p) {
return Math.sqrt(p.linkValue) * 1.5;
});
this.label.textAlign("center");
};
pv.Layout.Force.prototype = pv.extend(pv.Layout.Network)
.property("bound", Boolean)
.property("iterations", Number)
.property("dragConstant", Number)
.property("chargeConstant", Number)
.property("chargeMinDistance", Number)
.property("chargeMaxDistance", Number)
.property("chargeTheta", Number)
.property("springConstant", Number)
.property("springDamping", Number)
.property("springLength", Number);
/**
* The bound parameter; true if nodes should be constrained within the layout
* panel. Bounding is disabled by default. Currently the layout does not observe
* the radius of the nodes; strictly speaking, only the center of the node is
* constrained to be within the panel, with an additional 6-pixel offset for
* padding. A future enhancement could extend the bound constraint to observe
* the node's radius, which would also support bounding for variable-size nodes.
*
* <p>Note that if this layout is used in conjunction with pan & zoom
* behaviors, those behaviors should have their bound parameter set to the same
* value.
*
* @type boolean
* @name pv.Layout.Force.prototype.bound
*/
/**
* The number of simulation iterations to run, or null if this layout is
* interactive. Force-directed layouts are interactive by default, using a
* <tt>setInterval</tt> to advance the physics simulation and re-render
* automatically.
*
* @type number
* @name pv.Layout.Force.prototype.iterations
*/
/**
* The drag constant, in the range [0,1]. A value of 0 means no drag (a
* perfectly frictionless environment), while a value of 1 means friction
* immediately cancels all momentum. The default value is 0.1, which provides a
* minimum amount of drag that helps stabilize bouncy springs; lower values may
* result in excessive bounciness, while higher values cause the simulation to
* take longer to converge.
*
* @type number
* @name pv.Layout.Force.prototype.dragConstant
* @see pv.Force.drag#constant
*/
/**
* The charge constant, which should be a negative number. The default value is
* -40; more negative values will result in a stronger repulsive force, which
* may lead to faster convergence at the risk of instability. Too strong
* repulsive charge forces can cause comparatively weak springs to be stretched
* well beyond their rest length, emphasizing global structure over local
* structure. A nonnegative value will break the Fruchterman-Reingold algorithm,
* and is for entertainment purposes only.
*
* @type number
* @name pv.Layout.Force.prototype.chargeConstant
* @see pv.Force.charge#constant
*/
/**
* The minimum distance at which charge forces are applied. The default minimum
* distance of 2 avoids applying forces that are two strong; because the physics
* simulation is run at discrete time intervals, it is possible for two same-
* charged particles to become very close or even a singularity! Since the
* charge force is inversely proportional to the square of the distance, very
* small distances can break the simulation.
*
* <p>In rare cases, two particles can become stuck on top of each other, as a
* minimum distance threshold will prevent the charge force from repelling them.
* However, this occurs very rarely because other forces and momentum typically
* cause the particles to become separated again, at which point the repulsive
* charge force kicks in.
*
* @type number
* @name pv.Layout.Force.prototype.chargeMinDistance
* @see pv.Force.charge#domain
*/
/**
* The maximum distance at which charge forces are applied. This improves
* performance by ignoring weak charge forces at great distances. Note that this
* parameter is partly redundant, as the Barnes-Hut algorithm for n-body forces
* already improves performance for far-away particles through approximation.
*
* @type number
* @name pv.Layout.Force.prototype.chargeMaxDistance
* @see pv.Force.charge#domain
*/
/**
* The Barnes-Hut approximation factor. The Barnes-Hut approximation criterion
* is the ratio of the size of the quadtree node to the distance from the point
* to the node's center of mass is beneath some threshold. The default value is
* 0.9.
*
* @type number
* @name pv.Layout.Force.prototype.chargeTheta
* @see pv.Force.charge#theta
*/
/**
* The spring constant, which should be a positive number. The default value is
* 0.1; greater values will result in a stronger attractive force, which may
* lead to faster convergence at the risk of instability. Too strong spring
* forces can cause comparatively weak charge forces to be ignored, emphasizing
* local structure over global structure. A nonpositive value will break the
* Fruchterman-Reingold algorithm, and is for entertainment purposes only.
*
* <p>The spring tension is automatically normalized using the inverse square
* root of the maximum link degree of attached nodes.
*
* @type number
* @name pv.Layout.Force.prototype.springConstant
* @see pv.Force.spring#constant
*/
/**
* The spring damping factor, in the range [0,1]. Damping functions identically
* to drag forces, damping spring bounciness by applying a force in the opposite
* direction of attached nodes' velocities. The default value is 0.3.
*
* <p>The spring damping is automatically normalized using the inverse square
* root of the maximum link degree of attached nodes.
*
* @type number
* @name pv.Layout.Force.prototype.springDamping
* @see pv.Force.spring#damping
*/
/**
* The spring rest length. The default value is 20 pixels. Larger values may be
* appropriate if the layout panel is larger, or if the nodes are rendered
* larger than the default dot size of 20.
*
* @type number
* @name pv.Layout.Force.prototype.springLength
* @see pv.Force.spring#length
*/
/**
* Default properties for force-directed layouts. The default drag constant is
* 0.1, the default charge constant is -40 (with a domain of [2, 500] and theta
* of 0.9), and the default spring constant is 0.1 (with a damping of 0.3 and a
* rest length of 20).
*
* @type pv.Layout.Force
*/
pv.Layout.Force.prototype.defaults = new pv.Layout.Force()
.extend(pv.Layout.Network.prototype.defaults)
.dragConstant(.1)
.chargeConstant(-40)
.chargeMinDistance(2)
.chargeMaxDistance(500)
.chargeTheta(.9)
.springConstant(.1)
.springDamping(.3)
.springLength(20);
/** @private Initialize the physics simulation. */
pv.Layout.Force.prototype.buildImplied = function (s) {
/* Any cached interactive layouts need to be rebound for the timer. */
if (pv.Layout.Network.prototype.buildImplied.call(this, s)) {
var f = s.$force;
if (f) {
f.next = this.binds.$force;
this.binds.$force = f;
}
return;
}
var that = this,
nodes = s.nodes,
links = s.links,
k = s.iterations,
w = s.width,
h = s.height;
/* Initialize positions randomly near the center. */
for (var i = 0, n; i < nodes.length; i++) {
n = nodes[i];
if (isNaN(n.x))
n.x = w / 2 + 40 * Math.random() - 20;
if (isNaN(n.y))
n.y = h / 2 + 40 * Math.random() - 20;
}
/* Initialize the simulation. */
var sim = pv.simulation(nodes);
/* Drag force. */
sim.force(pv.Force.drag(s.dragConstant));
/* Charge (repelling) force. */
sim.force(pv.Force.charge(s.chargeConstant)
.domain(s.chargeMinDistance, s.chargeMaxDistance)
.theta(s.chargeTheta));
/* Spring (attracting) force. */
sim.force(pv.Force.spring(s.springConstant)
.damping(s.springDamping)
.length(s.springLength)
.links(links));
/* Position constraint (for interactive dragging). */
sim.constraint(pv.Constraint.position());
/* Optionally add bound constraint. TODO: better padding. */
if (s.bound) {
sim.constraint(pv.Constraint.bound().x(6, w - 6).y(6, h - 6));
}
/** @private Returns the speed of the given node, to determine cooling. */
function speed(n) {
return n.fix ? 1 : n.vx * n.vx + n.vy * n.vy;
}
/*
* If the iterations property is null (the default), the layout is
* interactive. The simulation is run until the fastest particle drops below
* an arbitrary minimum speed. Although the timer keeps firing, this speed
* calculation is fast so there is minimal CPU overhead. Note: if a particle
* is fixed for interactivity, treat this as a high speed and resume
* simulation.
*/
if (k == null) {
sim.step(); // compute initial previous velocities
sim.step(); // compute initial velocities
/* Add the simulation state to the bound list. */
var force = s.$force = this.binds.$force = {
next: this.binds.$force,
nodes: nodes,
min: 1e-4 * (links.length + 1),
sim: sim
};
/* Start the timer, if not already started. */
if (!this.$timer)
this.$timer = setInterval(function () {
var render = false;
for (var f = that.binds.$force; f; f = f.next) {
if (pv.max(f.nodes, speed) > f.min) {
f.sim.step();
render = true;
}
}
if (render)
that.render();
}, 42);
} else
for (var i = 0; i < k; i++) {
sim.step();
}
};
/**
* Constructs a new, empty cluster layout. Layouts are not typically
* constructed directly; instead, they are added to an existing panel via
* {@link pv.Mark#add}.
*
* @class Implements a hierarchical layout using the cluster (or dendrogram)
* algorithm. This layout provides both node-link and space-filling
* implementations of cluster diagrams. In many ways it is similar to
* {@link pv.Layout.Partition}, except that leaf nodes are positioned at maximum
* depth, and the depth of internal nodes is based on their distance from their
* deepest descendant, rather than their distance from the root.
*
* <p>The cluster layout supports a "group" property, which if true causes
* siblings to be positioned closer together than unrelated nodes at the same
* depth. Unlike the partition layout, this layout does not support dynamic
* sizing for leaf nodes; all leaf nodes are the same size.
*
* <p>For more details on how to use this layout, see
* {@link pv.Layout.Hierarchy}.
*
* @see pv.Layout.Cluster.Fill
* @extends pv.Layout.Hierarchy
*/
pv.Layout.Cluster = function () {
pv.Layout.Hierarchy.call(this);
var interpolate, // cached interpolate
buildImplied = this.buildImplied;
/** @private Cache layout state to optimize properties. */
this.buildImplied = function (s) {
buildImplied.call(this, s);
interpolate
= /^(top|bottom)$/.test(s.orient) ? "step-before"
: /^(left|right)$/.test(s.orient) ? "step-after"
: "linear";
};
this.link.interpolate(function () {
return interpolate;
});
};
pv.Layout.Cluster.prototype = pv.extend(pv.Layout.Hierarchy)
.property("group", Number)
.property("orient", String)
.property("innerRadius", Number)
.property("outerRadius", Number);
/**
* The group parameter; defaults to 0, disabling grouping of siblings. If this
* parameter is set to a positive number (or true, which is equivalent to 1),
* then additional space will be allotted between sibling groups. In other
* words, siblings (nodes that share the same parent) will be positioned more
* closely than nodes at the same depth that do not share a parent.
*
* @type number
* @name pv.Layout.Cluster.prototype.group
*/
/**
* The orientation. The default orientation is "top", which means that the root
* node is placed on the top edge, leaf nodes appear on the bottom edge, and
* internal nodes are in-between. The following orientations are supported:<ul>
*
* <li>left - left-to-right.
* <li>right - right-to-left.
* <li>top - top-to-bottom.
* <li>bottom - bottom-to-top.
* <li>radial - radially, with the root at the center.</ul>
*
* @type string
* @name pv.Layout.Cluster.prototype.orient
*/
/**
* The inner radius; defaults to 0. This property applies only to radial
* orientations, and can be used to compress the layout radially. Note that for
* the node-link implementation, the root node is always at the center,
* regardless of the value of this property; this property only affects internal
* and leaf nodes. For the space-filling implementation, a non-zero value of
* this property will result in the root node represented as a ring rather than
* a circle.
*
* @type number
* @name pv.Layout.Cluster.prototype.innerRadius
*/
/**
* The outer radius; defaults to fill the containing panel, based on the height
* and width of the layout. If the layout has no height and width specified, it
* will extend to fill the enclosing panel.
*
* @type number
* @name pv.Layout.Cluster.prototype.outerRadius
*/
/**
* Defaults for cluster layouts. The default group parameter is 0 and the
* default orientation is "top".
*
* @type pv.Layout.Cluster
*/
pv.Layout.Cluster.prototype.defaults = new pv.Layout.Cluster()
.extend(pv.Layout.Hierarchy.prototype.defaults)
.group(0)
.orient("top");
/** @private */
pv.Layout.Cluster.prototype.buildImplied = function (s) {
if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s))
return;
var root = s.nodes[0],
group = s.group,
breadth,
depth,
leafCount = 0,
leafIndex = .5 - group / 2;
/* Count the leaf nodes and compute the depth of descendants. */
var p = undefined;
root.visitAfter(function (n) {
if (n.firstChild) {
n.depth = 1 + pv.max(n.childNodes, function (n) {
return n.depth;
});
} else {
if (group && (p != n.parentNode)) {
p = n.parentNode;
leafCount += group;
}
leafCount++;
n.depth = 0;
}
});
breadth = 1 / leafCount;
depth = 1 / root.depth;
/* Compute the unit breadth and depth of each node. */
var p = undefined;
root.visitAfter(function (n) {
if (n.firstChild) {
n.breadth = pv.mean(n.childNodes, function (n) {
return n.breadth;
});
} else {
if (group && (p != n.parentNode)) {
p = n.parentNode;
leafIndex += group;
}
n.breadth = breadth * leafIndex++;
}
n.depth = 1 - n.depth * depth;
});
/* Compute breadth and depth ranges for space-filling layouts. */
root.visitAfter(function (n) {
n.minBreadth = n.firstChild
? n.firstChild.minBreadth
: (n.breadth - breadth / 2);
n.maxBreadth = n.firstChild
? n.lastChild.maxBreadth
: (n.breadth + breadth / 2);
});
root.visitBefore(function (n) {
n.minDepth = n.parentNode
? n.parentNode.maxDepth
: 0;
n.maxDepth = n.parentNode
? (n.depth + root.depth)
: (n.minDepth + 2 * root.depth);
});
root.minDepth = -depth;
pv.Layout.Hierarchy.NodeLink.buildImplied.call(this, s);
};
/**
* Constructs a new, empty space-filling cluster layout. Layouts are not
* typically constructed directly; instead, they are added to an existing panel
* via {@link pv.Mark#add}.
*
* @class A variant of cluster layout that is space-filling. The meaning of the
* exported mark prototypes changes slightly in the space-filling
* implementation:<ul>
*
* <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Bar} for
* non-radial orientations, and a {@link pv.Wedge} for radial orientations.
*
* <p><li><tt>link</tt> - unsupported; undefined. Links are encoded implicitly
* in the arrangement of the space-filling nodes.
*
* <p><li><tt>label</tt> - for rendering node labels; typically a
* {@link pv.Label}.
*
* </ul>For more details on how to use this layout, see
* {@link pv.Layout.Cluster}.
*
* @extends pv.Layout.Cluster
*/
pv.Layout.Cluster.Fill = function () {
pv.Layout.Cluster.call(this);
pv.Layout.Hierarchy.Fill.constructor.call(this);
};
pv.Layout.Cluster.Fill.prototype = pv.extend(pv.Layout.Cluster);
/** @private */
pv.Layout.Cluster.Fill.prototype.buildImplied = function (s) {
if (pv.Layout.Cluster.prototype.buildImplied.call(this, s))
return;
pv.Layout.Hierarchy.Fill.buildImplied.call(this, s);
};
/**
* Constructs a new, empty partition layout. Layouts are not typically
* constructed directly; instead, they are added to an existing panel via
* {@link pv.Mark#add}.
*
* @class Implemeents a hierarchical layout using the partition (or sunburst,
* icicle) algorithm. This layout provides both node-link and space-filling
* implementations of partition diagrams. In many ways it is similar to
* {@link pv.Layout.Cluster}, except that leaf nodes are positioned based on
* their distance from the root.
*
* <p>The partition layout support dynamic sizing for leaf nodes, if a
* {@link #size} psuedo-property is specified. The default size function returns
* 1, causing all leaf nodes to be sized equally, and all internal nodes to be
* sized by the number of leaf nodes they have as descendants.
*
* <p>The size function can be used in conjunction with the order property,
* which allows the nodes to the sorted by the computed size. Note: for sorting
* based on other data attributes, simply use the default <tt>null</tt> for the
* order property, and sort the nodes beforehand using the {@link pv.Dom}
* operator.
*
* <p>For more details on how to use this layout, see
* {@link pv.Layout.Hierarchy}.
*
* @see pv.Layout.Partition.Fill
* @extends pv.Layout.Hierarchy
*/
pv.Layout.Partition = function () {
pv.Layout.Hierarchy.call(this);
};
pv.Layout.Partition.prototype = pv.extend(pv.Layout.Hierarchy)
.property("order", String) // null, ascending, descending?
.property("orient", String) // top, left, right, bottom, radial
.property("innerRadius", Number)
.property("outerRadius", Number);
/**
* The sibling node order. The default order is <tt>null</tt>, which means to
* use the sibling order specified by the nodes property as-is. A value of
* "ascending" will sort siblings in ascending order of size, while "descending"
* will do the reverse. For sorting based on data attributes other than size,
* use the default <tt>null</tt> for the order property, and sort the nodes
* beforehand using the {@link pv.Dom} operator.
*
* @see pv.Dom.Node#sort
* @type string
* @name pv.Layout.Partition.prototype.order
*/
/**
* The orientation. The default orientation is "top", which means that the root
* node is placed on the top edge, leaf nodes appear at the bottom, and internal
* nodes are in-between. The following orientations are supported:<ul>
*
* <li>left - left-to-right.
* <li>right - right-to-left.
* <li>top - top-to-bottom.
* <li>bottom - bottom-to-top.
* <li>radial - radially, with the root at the center.</ul>
*
* @type string
* @name pv.Layout.Partition.prototype.orient
*/
/**
* The inner radius; defaults to 0. This property applies only to radial
* orientations, and can be used to compress the layout radially. Note that for
* the node-link implementation, the root node is always at the center,
* regardless of the value of this property; this property only affects internal
* and leaf nodes. For the space-filling implementation, a non-zero value of
* this property will result in the root node represented as a ring rather than
* a circle.
*
* @type number
* @name pv.Layout.Partition.prototype.innerRadius
*/
/**
* The outer radius; defaults to fill the containing panel, based on the height
* and width of the layout. If the layout has no height and width specified, it
* will extend to fill the enclosing panel.
*
* @type number
* @name pv.Layout.Partition.prototype.outerRadius
*/
/**
* Default properties for partition layouts. The default orientation is "top".
*
* @type pv.Layout.Partition
*/
pv.Layout.Partition.prototype.defaults = new pv.Layout.Partition()
.extend(pv.Layout.Hierarchy.prototype.defaults)
.orient("top");
/** @private */
pv.Layout.Partition.prototype.$size = function () {
return 1;
};
/**
* Specifies the sizing function. By default, a sizing function is disabled and
* all nodes are given constant size. The sizing function is invoked for each
* leaf node in the tree (passed to the constructor).
*
* <p>For example, if the tree data structure represents a file system, with
* files as leaf nodes, and each file has a <tt>bytes</tt> attribute, you can
* specify a size function as:
*
* <pre> .size(function(d) d.bytes)</pre>
*
* As with other properties, a size function may specify additional arguments to
* access the data associated with the layout and any enclosing panels.
*
* @param {function} f the new sizing function.
* @returns {pv.Layout.Partition} this.
*/
pv.Layout.Partition.prototype.size = function (f) {
this.$size = f;
return this;
};
/** @private */
pv.Layout.Partition.prototype.buildImplied = function (s) {
if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s))
return;
var that = this,
root = s.nodes[0],
stack = pv.Mark.stack,
maxDepth = 0;
/* Recursively compute the tree depth and node size. */
stack.unshift(null);
root.visitAfter(function (n, i) {
if (i > maxDepth)
maxDepth = i;
n.size = n.firstChild
? pv.sum(n.childNodes, function (n) {
return n.size;
})
: that.$size.apply(that, (stack[0] = n, stack));
});
stack.shift();
/* Order */
switch (s.order) {
case "ascending":
root.sort(function (a, b) {
return a.size - b.size;
});
break;
case "descending":
root.sort(function (b, a) {
return a.size - b.size;
});
break;
}
/* Compute the unit breadth and depth of each node. */
var ds = 1 / maxDepth;
root.minBreadth = 0;
root.breadth = .5;
root.maxBreadth = 1;
root.visitBefore(function (n) {
var b = n.minBreadth, s = n.maxBreadth - b;
for (var c = n.firstChild; c; c = c.nextSibling) {
c.minBreadth = b;
c.maxBreadth = b += (c.size / n.size) * s;
c.breadth = (b + c.minBreadth) / 2;
}
});
root.visitAfter(function (n, i) {
n.minDepth = (i - 1) * ds;
n.maxDepth = n.depth = i * ds;
});
pv.Layout.Hierarchy.NodeLink.buildImplied.call(this, s);
};
/**
* Constructs a new, empty space-filling partition layout. Layouts are not
* typically constructed directly; instead, they are added to an existing panel
* via {@link pv.Mark#add}.
*
* @class A variant of partition layout that is space-filling. The meaning of
* the exported mark prototypes changes slightly in the space-filling
* implementation:<ul>
*
* <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Bar} for
* non-radial orientations, and a {@link pv.Wedge} for radial orientations.
*
* <p><li><tt>link</tt> - unsupported; undefined. Links are encoded implicitly
* in the arrangement of the space-filling nodes.
*
* <p><li><tt>label</tt> - for rendering node labels; typically a
* {@link pv.Label}.
*
* </ul>For more details on how to use this layout, see
* {@link pv.Layout.Partition}.
*
* @extends pv.Layout.Partition
*/
pv.Layout.Partition.Fill = function () {
pv.Layout.Partition.call(this);
pv.Layout.Hierarchy.Fill.constructor.call(this);
};
pv.Layout.Partition.Fill.prototype = pv.extend(pv.Layout.Partition);
/** @private */
pv.Layout.Partition.Fill.prototype.buildImplied = function (s) {
if (pv.Layout.Partition.prototype.buildImplied.call(this, s))
return;
pv.Layout.Hierarchy.Fill.buildImplied.call(this, s);
};
/**
* Constructs a new, empty arc layout. Layouts are not typically constructed
* directly; instead, they are added to an existing panel via
* {@link pv.Mark#add}.
*
* @class Implements a layout for arc diagrams. An arc diagram is a network
* visualization with a one-dimensional layout of nodes, using circular arcs to
* render links between nodes. For undirected networks, arcs are rendering on a
* single side; this makes arc diagrams useful as annotations to other
* two-dimensional network layouts, such as rollup, matrix or table layouts. For
* directed networks, links in opposite directions can be rendered on opposite
* sides using <tt>directed(true)</tt>.
*
* <p>Arc layouts are particularly sensitive to node ordering; for best results,
* order the nodes such that related nodes are close to each other. A poor
* (e.g., random) order may result in large arcs with crossovers that impede
* visual processing. A future improvement to this layout may include automatic
* reordering using, e.g., spectral graph layout or simulated annealing.
*
* <p>This visualization technique is related to that developed by
* M. Wattenberg, <a
* href="http://www.research.ibm.com/visual/papers/arc-diagrams.pdf">"Arc
* Diagrams: Visualizing Structure in Strings"</a> in <i>IEEE InfoVis</i>, 2002.
* However, this implementation is limited to simple node-link networks, as
* opposed to structures with hierarchical self-similarity (such as strings).
*
* <p>As with other network layouts, three mark prototypes are provided:<ul>
*
* <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Dot}.
* <li><tt>link</tt> - for rendering links; typically a {@link pv.Line}.
* <li><tt>label</tt> - for rendering node labels; typically a {@link pv.Label}.
*
* </ul>For more details on how this layout is structured and can be customized,
* see {@link pv.Layout.Network}.
*
* @extends pv.Layout.Network
**/
pv.Layout.Arc = function () {
pv.Layout.Network.call(this);
var interpolate, // cached interpolate
directed, // cached directed
reverse, // cached reverse
buildImplied = this.buildImplied;
/** @private Cache layout state to optimize properties. */
this.buildImplied = function (s) {
buildImplied.call(this, s);
directed = s.directed;
interpolate = s.orient == "radial" ? "linear" : "polar";
reverse = s.orient == "right" || s.orient == "top";
};
/* Override link properties to handle directedness and orientation. */
this.link
.data(function (p) {
var s = p.sourceNode, t = p.targetNode;
return reverse != (directed || (s.breadth < t.breadth)) ? [s, t] : [t, s];
})
.interpolate(function () {
return interpolate;
});
};
pv.Layout.Arc.prototype = pv.extend(pv.Layout.Network)
.property("orient", String)
.property("directed", Boolean);
/**
* Default properties for arc layouts. By default, the orientation is "bottom".
*
* @type pv.Layout.Arc
*/
pv.Layout.Arc.prototype.defaults = new pv.Layout.Arc()
.extend(pv.Layout.Network.prototype.defaults)
.orient("bottom");
/**
* Specifies an optional sort function. The sort function follows the same
* comparator contract required by {@link pv.Dom.Node#sort}. Specifying a sort
* function provides an alternative to sort the nodes as they are specified by
* the <tt>nodes</tt> property; the main advantage of doing this is that the
* comparator function can access implicit fields populated by the network
* layout, such as the <tt>linkDegree</tt>.
*
* <p>Note that arc diagrams are particularly sensitive to order. This is
* referred to as the seriation problem, and many different techniques exist to
* find good node orders that emphasize clusters, such as spectral layout and
* simulated annealing.
*
* @param {function} f comparator function for nodes.
* @returns {pv.Layout.Arc} this.
*/
pv.Layout.Arc.prototype.sort = function (f) {
this.$sort = f;
return this;
};
/** @private Populates the x, y and angle attributes on the nodes. */
pv.Layout.Arc.prototype.buildImplied = function (s) {
if (pv.Layout.Network.prototype.buildImplied.call(this, s))
return;
var nodes = s.nodes,
orient = s.orient,
sort = this.$sort,
index = pv.range(nodes.length),
w = s.width,
h = s.height,
r = Math.min(w, h) / 2;
/* Sort the nodes. */
if (sort)
index.sort(function (a, b) {
return sort(nodes[a], nodes[b]);
});
/** @private Returns the mid-angle, given the breadth. */
function midAngle(b) {
switch (orient) {
case "top":
return -Math.PI / 2;
case "bottom":
return Math.PI / 2;
case "left":
return Math.PI;
case "right":
return 0;
case "radial":
return (b - .25) * 2 * Math.PI;
}
}
/** @private Returns the x-position, given the breadth. */
function x(b) {
switch (orient) {
case "top":
case "bottom":
return b * w;
case "left":
return 0;
case "right":
return w;
case "radial":
return w / 2 + r * Math.cos(midAngle(b));
}
}
/** @private Returns the y-position, given the breadth. */
function y(b) {
switch (orient) {
case "top":
return 0;
case "bottom":
return h;
case "left":
case "right":
return b * h;
case "radial":
return h / 2 + r * Math.sin(midAngle(b));
}
}
/* Populate the x, y and mid-angle attributes. */
for (var i = 0; i < nodes.length; i++) {
var n = nodes[index[i]], b = n.breadth = (i + .5) / nodes.length;
n.x = x(b);
n.y = y(b);
n.midAngle = midAngle(b);
}
};
/**
* The orientation. The default orientation is "left", which means that nodes
* will be positioned from left-to-right in the order they are specified in the
* <tt>nodes</tt> property. The following orientations are supported:<ul>
*
* <li>left - left-to-right.
* <li>right - right-to-left.
* <li>top - top-to-bottom.
* <li>bottom - bottom-to-top.
* <li>radial - radially, starting at 12 o'clock and proceeding clockwise.</ul>
*
* @type string
* @name pv.Layout.Arc.prototype.orient
*/
/**
* Whether this arc digram is directed (bidirectional); only applies to
* non-radial orientations. By default, arc digrams are undirected, such that
* all arcs appear on one side. If the arc digram is directed, then forward
* links are drawn on the conventional side (the same as as undirected
* links--right, left, bottom and top for left, right, top and bottom,
* respectively), while reverse links are drawn on the opposite side.
*
* @type boolean
* @name pv.Layout.Arc.prototype.directed
*/
/**
* Constructs a new, empty horizon layout. Layouts are not typically constructed
* directly; instead, they are added to an existing panel via
* {@link pv.Mark#add}.
*
* @class Implements a horizon layout, which is a variation of a single-series
* area chart where the area is folded into multiple bands. Color is used to
* encode band, allowing the size of the chart to be reduced significantly
* without impeding readability. This layout algorithm is based on the work of
* J. Heer, N. Kong and M. Agrawala in <a
* href="http://hci.stanford.edu/publications/2009/heer-horizon-chi09.pdf">"Sizing
* the Horizon: The Effects of Chart Size and Layering on the Graphical
* Perception of Time Series Visualizations"</a>, CHI 2009.
*
* <p>This layout exports a single <tt>band</tt> mark prototype, which is
* intended to be used with an area mark. The band mark is contained in a panel
* which is replicated per band (and for negative/positive bands). For example,
* to create a simple horizon graph given an array of numbers:
*
* <pre>vis.add(pv.Layout.Horizon)
* .bands(n)
* .band.add(pv.Area)
* .data(data)
* .left(function() this.index * 35)
* .height(function(d) d * 40);</pre>
*
* The layout can be further customized by changing the number of bands, and
* toggling whether the negative bands are mirrored or offset. (See the
* above-referenced paper for guidance.)
*
* <p>The <tt>fillStyle</tt> of the area can be overridden, though typically it
* is easier to customize the layout's behavior through the custom
* <tt>backgroundStyle</tt>, <tt>positiveStyle</tt> and <tt>negativeStyle</tt>
* properties. By default, the background is white, positive bands are blue, and
* negative bands are red. For the most accurate presentation, use fully-opaque
* colors of equal intensity for the negative and positive bands.
*
* @extends pv.Layout
*/
pv.Layout.Horizon = function () {
pv.Layout.call(this);
var that = this,
bands, // cached bands
mode, // cached mode
size, // cached height
fill, // cached background style
red, // cached negative color (ramp)
blue, // cached positive color (ramp)
buildImplied = this.buildImplied;
/** @private Cache the layout state to optimize properties. */
this.buildImplied = function (s) {
buildImplied.call(this, s);
bands = s.bands;
mode = s.mode;
size = Math.round((mode == "color" ? .5 : 1) * s.height);
fill = s.backgroundStyle;
red = pv.ramp(fill, s.negativeStyle).domain(0, bands);
blue = pv.ramp(fill, s.positiveStyle).domain(0, bands);
};
var bands = new pv.Panel()
.data(function () {
return pv.range(bands * 2);
})
.overflow("hidden")
.height(function () {
return size;
})
.top(function (i) {
return mode == "color" ? (i & 1) * size : 0;
})
.fillStyle(function (i) {
return i ? null : fill;
});
/**
* The band prototype. This prototype is intended to be used with an Area
* mark to render the horizon bands.
*
* @type pv.Mark
* @name pv.Layout.Horizon.prototype.band
*/
this.band = new pv.Mark()
.top(function (d, i) {
return mode == "mirror" && i & 1
? (i + 1 >> 1) * size
: null;
})
.bottom(function (d, i) {
return mode == "mirror"
? (i & 1 ? null : (i + 1 >> 1) * -size)
: ((i & 1 || -1) * (i + 1 >> 1) * size);
})
.fillStyle(function (d, i) {
return (i & 1 ? red : blue)((i >> 1) + 1);
});
this.band.add = function (type) {
return that.add(pv.Panel).extend(bands).add(type).extend(this);
};
};
pv.Layout.Horizon.prototype = pv.extend(pv.Layout)
.property("bands", Number)
.property("mode", String)
.property("backgroundStyle", pv.color)
.property("positiveStyle", pv.color)
.property("negativeStyle", pv.color);
/**
* Default properties for horizon layouts. By default, there are two bands, the
* mode is "offset", the background style is "white", the positive style is
* blue, negative style is red.
*
* @type pv.Layout.Horizon
*/
pv.Layout.Horizon.prototype.defaults = new pv.Layout.Horizon()
.extend(pv.Layout.prototype.defaults)
.bands(2)
.mode("offset")
.backgroundStyle("white")
.positiveStyle("#1f77b4")
.negativeStyle("#d62728");
/**
* The horizon mode: offset, mirror, or color. The default is "offset".
*
* @type string
* @name pv.Layout.Horizon.prototype.mode
*/
/**
* The number of bands. Must be at least one. The default value is two.
*
* @type number
* @name pv.Layout.Horizon.prototype.bands
*/
/**
* The positive band color; if non-null, the interior of positive bands are
* filled with the specified color. The default value of this property is blue.
* For accurate blending, this color should be fully opaque.
*
* @type pv.Color
* @name pv.Layout.Horizon.prototype.positiveStyle
*/
/**
* The negative band color; if non-null, the interior of negative bands are
* filled with the specified color. The default value of this property is red.
* For accurate blending, this color should be fully opaque.
*
* @type pv.Color
* @name pv.Layout.Horizon.prototype.negativeStyle
*/
/**
* The background color. The panel background is filled with the specified
* color, and the negative and positive bands are filled with an interpolated
* color between this color and the respective band color. The default value of
* this property is white. For accurate blending, this color should be fully
* opaque.
*
* @type pv.Color
* @name pv.Layout.Horizon.prototype.backgroundStyle
*/
/**
* Constructs a new, empty rollup network layout. Layouts are not typically
* constructed directly; instead, they are added to an existing panel via
* {@link pv.Mark#add}.
*
* @class Implements a network visualization using a node-link diagram where
* nodes are rolled up along two dimensions. This implementation is based on the
* "PivotGraph" designed by Martin Wattenberg:
*
* <blockquote>The method is designed for graphs that are "multivariate", i.e.,
* where each node is associated with several attributes. Unlike visualizations
* which emphasize global graph topology, PivotGraph uses a simple grid-based
* approach to focus on the relationship between node attributes &
* connections.</blockquote>
*
* This layout requires two psuedo-properties to be specified, which assign node
* positions along the two dimensions {@link #x} and {@link #y}, corresponding
* to the left and top properties, respectively. Typically, these functions are
* specified using an {@link pv.Scale.ordinal}. Nodes that share the same
* position in <i>x</i> and <i>y</i> are "rolled up" into a meta-node, and
* similarly links are aggregated between meta-nodes. For example, to construct
* a rollup to analyze links by gender and affiliation, first define two ordinal
* scales:
*
* <pre>var x = pv.Scale.ordinal(nodes, function(d) d.gender).split(0, w),
* y = pv.Scale.ordinal(nodes, function(d) d.aff).split(0, h);</pre>
*
* Next, define the position psuedo-properties:
*
* <pre> .x(function(d) x(d.gender))
* .y(function(d) y(d.aff))</pre>
*
* Linear and other quantitative scales can alternatively be used to position
* the nodes along either dimension. Note, however, that the rollup requires
* that the positions match exactly, and thus ordinal scales are recommended to
* avoid precision errors.
*
* <p>Note that because this layout provides a visualization of the rolled up
* graph, the data properties for the mark prototypes (<tt>node</tt>,
* <tt>link</tt> and <tt>label</tt>) are different from most other network
* layouts: they reference the rolled-up nodes and links, rather than the nodes
* and links of the full network. The underlying nodes and links for each
* rolled-up node and link can be accessed via the <tt>nodes</tt> and
* <tt>links</tt> attributes, respectively. The aggregated link values for
* rolled-up links can similarly be accessed via the <tt>linkValue</tt>
* attribute.
*
* <p>For undirected networks, links are duplicated in both directions. For
* directed networks, use <tt>directed(true)</tt>. The graph is assumed to be
* undirected by default.
*
* @extends pv.Layout.Network
* @see <a href="http://www.research.ibm.com/visual/papers/pivotgraph.pdf"
* >"Visual Exploration of Multivariate Graphs"</a> by M. Wattenberg, CHI 2006.
*/
pv.Layout.Rollup = function () {
pv.Layout.Network.call(this);
var that = this,
nodes, // cached rollup nodes
links, // cached rollup links
buildImplied = that.buildImplied;
/** @private Cache layout state to optimize properties. */
this.buildImplied = function (s) {
buildImplied.call(this, s);
nodes = s.$rollup.nodes;
links = s.$rollup.links;
};
/* Render rollup nodes. */
this.node
.data(function () {
return nodes;
})
.size(function (d) {
return d.nodes.length * 20;
});
/* Render rollup links. */
this.link
.interpolate("polar")
.eccentricity(.8);
this.link.add = function (type) {
return that.add(pv.Panel)
.data(function () {
return links;
})
.add(type)
.extend(this);
};
};
pv.Layout.Rollup.prototype = pv.extend(pv.Layout.Network)
.property("directed", Boolean);
/**
* Whether the underlying network is directed. By default, the graph is assumed
* to be undirected, and links are rendered in both directions. If the network
* is directed, then forward links are drawn above the diagonal, while reverse
* links are drawn below.
*
* @type boolean
* @name pv.Layout.Rollup.prototype.directed
*/
/**
* Specifies the <i>x</i>-position function used to rollup nodes. The rolled up
* nodes are positioned horizontally using the return values from the given
* function. Typically the function is specified as an ordinal scale. For
* single-dimension rollups, a constant value can be specified.
*
* @param {function} f the <i>x</i>-position function.
* @returns {pv.Layout.Rollup} this.
* @see pv.Scale.ordinal
*/
pv.Layout.Rollup.prototype.x = function (f) {
this.$x = pv.functor(f);
return this;
};
/**
* Specifies the <i>y</i>-position function used to rollup nodes. The rolled up
* nodes are positioned vertically using the return values from the given
* function. Typically the function is specified as an ordinal scale. For
* single-dimension rollups, a constant value can be specified.
*
* @param {function} f the <i>y</i>-position function.
* @returns {pv.Layout.Rollup} this.
* @see pv.Scale.ordinal
*/
pv.Layout.Rollup.prototype.y = function (f) {
this.$y = pv.functor(f);
return this;
};
/** @private */
pv.Layout.Rollup.prototype.buildImplied = function (s) {
if (pv.Layout.Network.prototype.buildImplied.call(this, s))
return;
var nodes = s.nodes,
links = s.links,
directed = s.directed,
n = nodes.length,
x = [],
y = [],
rnindex = 0,
rnodes = {},
rlinks = {};
/** @private */
function id(i) {
return x[i] + "," + y[i];
}
/* Iterate over the data, evaluating the x and y functions. */
var stack = pv.Mark.stack, o = {parent: this};
stack.unshift(null);
for (var i = 0; i < n; i++) {
o.index = i;
stack[0] = nodes[i];
x[i] = this.$x.apply(o, stack);
y[i] = this.$y.apply(o, stack);
}
stack.shift();
/* Compute rollup nodes. */
for (var i = 0; i < nodes.length; i++) {
var nodeId = id(i),
rn = rnodes[nodeId];
if (!rn) {
rn = rnodes[nodeId] = pv.extend(nodes[i]);
rn.index = rnindex++;
rn.x = x[i];
rn.y = y[i];
rn.nodes = [];
}
rn.nodes.push(nodes[i]);
}
/* Compute rollup links. */
for (var i = 0; i < links.length; i++) {
var source = links[i].sourceNode,
target = links[i].targetNode,
rsource = rnodes[id(source.index)],
rtarget = rnodes[id(target.index)],
reverse = !directed && rsource.index > rtarget.index,
linkId = reverse
? rtarget.index + "," + rsource.index
: rsource.index + "," + rtarget.index,
rl = rlinks[linkId];
if (!rl) {
rl = rlinks[linkId] = {
sourceNode: rsource,
targetNode: rtarget,
linkValue: 0,
links: []
};
}
rl.links.push(links[i]);
rl.linkValue += links[i].linkValue;
}
/* Export the rolled up nodes and links to the scene. */
s.$rollup = {
nodes: pv.values(rnodes),
links: pv.values(rlinks)
};
};
/**
* Constructs a new, empty matrix network layout. Layouts are not typically
* constructed directly; instead, they are added to an existing panel via
* {@link pv.Mark#add}.
*
* @class Implements a network visualization using a matrix view. This is, in
* effect, a visualization of the graph's <i>adjacency matrix</i>: the cell at
* row <i>i</i>, column <i>j</i>, corresponds to the link from node <i>i</i> to
* node <i>j</i>. The fill color of each cell is binary by default, and
* corresponds to whether a link exists between the two nodes. If the underlying
* graph has links with variable values, the <tt>fillStyle</tt> property can be
* substited to use an appropriate color function, such as {@link pv.ramp}.
*
* <p>For undirected networks, the matrix is symmetric around the diagonal. For
* directed networks, links in opposite directions can be rendered on opposite
* sides of the diagonal using <tt>directed(true)</tt>. The graph is assumed to
* be undirected by default.
*
* <p>The mark prototypes for this network layout are slightly different than
* other implementations:<ul>
*
* <li><tt>node</tt> - unsupported; undefined. No mark is needed to visualize
* nodes directly, as the nodes are implicit in the location (rows and columns)
* of the links.
*
* <p><li><tt>link</tt> - for rendering links; typically a {@link pv.Bar}. The
* link mark is added directly to the layout, with the data property defined as
* all possible pairs of nodes. Each pair is represented as a
* {@link pv.Network.Layout.Link}, though the <tt>linkValue</tt> attribute may
* be 0 if no link exists in the graph.
*
* <p><li><tt>label</tt> - for rendering node labels; typically a
* {@link pv.Label}. The label mark is added directly to the layout, with the
* data property defined via the layout's <tt>nodes</tt> property; note,
* however, that the nodes are duplicated so as to provide a label across the
* top and down the side. Properties such as <tt>strokeStyle</tt> and
* <tt>fillStyle</tt> can be overridden to compute properties from node data
* dynamically.
*
* </ul>For more details on how to use this layout, see
* {@link pv.Layout.Network}.
*
* @extends pv.Layout.Network
*/
pv.Layout.Matrix = function () {
pv.Layout.Network.call(this);
var that = this,
n, // cached matrix size
dx, // cached cell width
dy, // cached cell height
labels, // cached labels (array of strings)
pairs, // cached pairs (array of links)
buildImplied = that.buildImplied;
/** @private Cache layout state to optimize properties. */
this.buildImplied = function (s) {
buildImplied.call(this, s);
n = s.nodes.length;
dx = s.width / n;
dy = s.height / n;
labels = s.$matrix.labels;
pairs = s.$matrix.pairs;
};
/* Links are all pairs of nodes. */
this.link
.data(function () {
return pairs;
})
.left(function () {
return dx * (this.index % n);
})
.top(function () {
return dy * Math.floor(this.index / n);
})
.width(function () {
return dx;
})
.height(function () {
return dy;
})
.lineWidth(1.5)
.strokeStyle("#fff")
.fillStyle(function (l) {
return l.linkValue ? "#555" : "#eee";
})
.parent = this;
/* No special add for links! */
delete this.link.add;
/* Labels are duplicated for top & left. */
this.label
.data(function () {
return labels;
})
.left(function () {
return this.index & 1 ? dx * ((this.index >> 1) + .5) : 0;
})
.top(function () {
return this.index & 1 ? 0 : dy * ((this.index >> 1) + .5);
})
.textMargin(4)
.textAlign(function () {
return this.index & 1 ? "left" : "right";
})
.textAngle(function () {
return this.index & 1 ? -Math.PI / 2 : 0;
});
/* The node mark is unused. */
delete this.node;
};
pv.Layout.Matrix.prototype = pv.extend(pv.Layout.Network)
.property("directed", Boolean);
/**
* Whether this matrix visualization is directed (bidirectional). By default,
* the graph is assumed to be undirected, such that the visualization is
* symmetric across the matrix diagonal. If the network is directed, then
* forward links are drawn above the diagonal, while reverse links are drawn
* below.
*
* @type boolean
* @name pv.Layout.Matrix.prototype.directed
*/
/**
* Specifies an optional sort function. The sort function follows the same
* comparator contract required by {@link pv.Dom.Node#sort}. Specifying a sort
* function provides an alternative to sort the nodes as they are specified by
* the <tt>nodes</tt> property; the main advantage of doing this is that the
* comparator function can access implicit fields populated by the network
* layout, such as the <tt>linkDegree</tt>.
*
* <p>Note that matrix visualizations are particularly sensitive to order. This
* is referred to as the seriation problem, and many different techniques exist
* to find good node orders that emphasize clusters, such as spectral layout and
* simulated annealing.
*
* @param {function} f comparator function for nodes.
* @returns {pv.Layout.Matrix} this.
*/
pv.Layout.Matrix.prototype.sort = function (f) {
this.$sort = f;
return this;
};
/** @private */
pv.Layout.Matrix.prototype.buildImplied = function (s) {
if (pv.Layout.Network.prototype.buildImplied.call(this, s))
return;
var nodes = s.nodes,
links = s.links,
sort = this.$sort,
n = nodes.length,
index = pv.range(n),
labels = [],
pairs = [],
map = {};
s.$matrix = {labels: labels, pairs: pairs};
/* Sort the nodes. */
if (sort)
index.sort(function (a, b) {
return sort(nodes[a], nodes[b]);
});
/* Create pairs. */
for (var i = 0; i < n; i++) {
for (var j = 0; j < n; j++) {
var a = index[i],
b = index[j],
p = {
row: i,
col: j,
sourceNode: nodes[a],
targetNode: nodes[b],
linkValue: 0
};
pairs.push(map[a + "." + b] = p);
}
}
/* Create labels. */
for (var i = 0; i < n; i++) {
var a = index[i];
labels.push(nodes[a], nodes[a]);
}
/* Accumulate link values. */
for (var i = 0; i < links.length; i++) {
var l = links[i],
source = l.sourceNode.index,
target = l.targetNode.index,
value = l.linkValue;
map[source + "." + target].linkValue += value;
if (!s.directed)
map[target + "." + source].linkValue += value;
}
};
// ranges (bad, satisfactory, good)
// measures (actual, forecast)
// markers (previous, goal)
/*
* Chart design based on the recommendations of Stephen Few. Implementation
* based on the work of Clint Ivy, Jamie Love, and Jason Davies.
* http://projects.instantcognition.com/protovis/bulletchart/
*/
/**
* Constructs a new, empty bullet layout. Layouts are not typically constructed
* directly; instead, they are added to an existing panel via
* {@link pv.Mark#add}.
*
* @class
* @extends pv.Layout
*/
pv.Layout.Bullet = function () {
pv.Layout.call(this);
var that = this,
buildImplied = that.buildImplied,
scale = that.x = pv.Scale.linear(),
orient,
horizontal,
rangeColor,
measureColor,
x;
/** @private Cache layout state to optimize properties. */
this.buildImplied = function (s) {
buildImplied.call(this, x = s);
orient = s.orient;
horizontal = /^left|right$/.test(orient);
rangeColor = pv.ramp("#bbb", "#eee")
.domain(0, Math.max(1, x.ranges.length - 1));
measureColor = pv.ramp("steelblue", "lightsteelblue")
.domain(0, Math.max(1, x.measures.length - 1));
};
/**
* The range prototype.
*
* @type pv.Mark
* @name pv.Layout.Bullet.prototype.range
*/
(this.range = new pv.Mark())
.data(function () {
return x.ranges;
})
.reverse(true)
.left(function () {
return orient == "left" ? 0 : null;
})
.top(function () {
return orient == "top" ? 0 : null;
})
.right(function () {
return orient == "right" ? 0 : null;
})
.bottom(function () {
return orient == "bottom" ? 0 : null;
})
.width(function (d) {
return horizontal ? scale(d) : null;
})
.height(function (d) {
return horizontal ? null : scale(d);
})
.fillStyle(function () {
return rangeColor(this.index);
})
.antialias(false)
.parent = that;
/**
* The measure prototype.
*
* @type pv.Mark
* @name pv.Layout.Bullet.prototype.measure
*/
(this.measure = new pv.Mark())
.extend(this.range)
.data(function () {
return x.measures;
})
.left(function () {
return orient == "left" ? 0 : horizontal ? null : this.parent.width() / 3.25;
})
.top(function () {
return orient == "top" ? 0 : horizontal ? this.parent.height() / 3.25 : null;
})
.right(function () {
return orient == "right" ? 0 : horizontal ? null : this.parent.width() / 3.25;
})
.bottom(function () {
return orient == "bottom" ? 0 : horizontal ? this.parent.height() / 3.25 : null;
})
.fillStyle(function () {
return measureColor(this.index);
})
.parent = that;
/**
* The marker prototype.
*
* @type pv.Mark
* @name pv.Layout.Bullet.prototype.marker
*/
(this.marker = new pv.Mark())
.data(function () {
return x.markers;
})
.left(function (d) {
return orient == "left" ? scale(d) : horizontal ? null : this.parent.width() / 2;
})
.top(function (d) {
return orient == "top" ? scale(d) : horizontal ? this.parent.height() / 2 : null;
})
.right(function (d) {
return orient == "right" ? scale(d) : null;
})
.bottom(function (d) {
return orient == "bottom" ? scale(d) : null;
})
.strokeStyle("black")
.shape("bar")
.angle(function () {
return horizontal ? 0 : Math.PI / 2;
})
.parent = that;
(this.tick = new pv.Mark())
.data(function () {
return scale.ticks(7);
})
.left(function (d) {
return orient == "left" ? scale(d) : null;
})
.top(function (d) {
return orient == "top" ? scale(d) : null;
})
.right(function (d) {
return orient == "right" ? scale(d) : horizontal ? null : -6;
})
.bottom(function (d) {
return orient == "bottom" ? scale(d) : horizontal ? -8 : null;
})
.height(function () {
return horizontal ? 6 : null;
})
.width(function () {
return horizontal ? null : 6;
})
.parent = that;
};
pv.Layout.Bullet.prototype = pv.extend(pv.Layout)
.property("orient", String) // left, right, top, bottom
.property("ranges")
.property("markers")
.property("measures")
.property("maximum", Number);
/**
* Default properties for bullet layouts.
*
* @type pv.Layout.Bullet
*/
pv.Layout.Bullet.prototype.defaults = new pv.Layout.Bullet()
.extend(pv.Layout.prototype.defaults)
.orient("left")
.ranges([])
.markers([])
.measures([]);
/**
* The orientation.
*
* @type string
* @name pv.Layout.Bullet.prototype.orient
*/
/**
* The array of range values.
*
* @type array
* @name pv.Layout.Bullet.prototype.ranges
*/
/**
* The array of marker values.
*
* @type array
* @name pv.Layout.Bullet.prototype.markers
*/
/**
* The array of measure values.
*
* @type array
* @name pv.Layout.Bullet.prototype.measures
*/
/**
* Optional; the maximum range value.
*
* @type number
* @name pv.Layout.Bullet.prototype.maximum
*/
/** @private */
pv.Layout.Bullet.prototype.buildImplied = function (s) {
pv.Layout.prototype.buildImplied.call(this, s);
var size = this.parent[/^left|right$/.test(s.orient) ? "width" : "height"]();
s.maximum = s.maximum || pv.max([].concat(s.ranges, s.markers, s.measures));
this.x.domain(0, s.maximum).range(0, size);
};
/**
* Abstract; see an implementing class for details.
*
* @class Represents a reusable interaction; applies an interactive behavior to
* a given mark. Behaviors are themselves functions designed to be used as event
* handlers. For example, to add pan and zoom support to any panel, say:
*
* <pre> .event("mousedown", pv.Behavior.pan())
* .event("mousewheel", pv.Behavior.zoom())</pre>
*
* The behavior should be registered on the event that triggers the start of the
* behavior. Typically, the behavior will take care of registering for any
* additional events that are necessary. For example, dragging starts on
* mousedown, while the drag behavior automatically listens for mousemove and
* mouseup events on the window. By listening to the window, the behavior can
* continue to receive mouse events even if the mouse briefly leaves the mark
* being dragged, or even the root panel.
*
* <p>Each behavior implementation has specific requirements as to which events
* it supports, and how it should be used. For example, the drag behavior
* requires that the data associated with the mark be an object with <tt>x</tt>
* and <tt>y</tt> attributes, such as a {@link pv.Vector}, storing the mark's
* position. See an implementing class for details.
*
* @see pv.Behavior.drag
* @see pv.Behavior.pan
* @see pv.Behavior.point
* @see pv.Behavior.select
* @see pv.Behavior.zoom
* @extends function
*/
pv.Behavior = {};
/**
* Returns a new drag behavior to be registered on mousedown events.
*
* @class Implements interactive dragging starting with mousedown events.
* Register this behavior on marks that should be draggable by the user, such as
* the selected region for brushing and linking. This behavior can be used in
* tandom with {@link pv.Behavior.select} to allow the selected region to be
* dragged interactively.
*
* <p>After the initial mousedown event is triggered, this behavior listens for
* mousemove and mouseup events on the window. This allows dragging to continue
* even if the mouse temporarily leaves the mark that is being dragged, or even
* the root panel.
*
* <p>This behavior requires that the data associated with the mark being
* dragged have <tt>x</tt> and <tt>y</tt> attributes that correspond to the
* mark's location in pixels. The mark's positional properties are not set
* directly by this behavior; instead, the positional properties should be
* defined as:
*
* <pre> .left(function(d) d.x)
* .top(function(d) d.y)</pre>
*
* Thus, the behavior does not move the mark directly, but instead updates the
* mark position by updating the underlying data. Note that if the positional
* properties are defined with bottom and right (rather than top and left), the
* drag behavior will be inverted, which will confuse users!
*
* <p>The drag behavior is bounded by the parent panel; the <tt>x</tt> and
* <tt>y</tt> attributes are clamped such that the mark being dragged does not
* extend outside the enclosing panel's bounds. To facilitate this, the drag
* behavior also queries for <tt>dx</tt> and <tt>dy</tt> attributes on the
* underlying data, to determine the dimensions of the bar being dragged. For
* non-rectangular marks, the drag behavior simply treats the mark as a point,
* which means that only the mark's center is bounded.
*
* <p>The mark being dragged is automatically re-rendered for each mouse event
* as part of the drag operation. In addition, a <tt>fix</tt> attribute is
* populated on the mark, which allows visual feedback for dragging. For
* example, to change the mark fill color while dragging:
*
* <pre> .fillStyle(function(d) d.fix ? "#ff7f0e" : "#aec7e8")</pre>
*
* In some cases, such as with network layouts, dragging the mark may cause
* related marks to change, in which case additional marks may also need to be
* rendered. This can be accomplished by listening for the drag
* psuedo-events:<ul>
*
* <li>dragstart (on mousedown)
* <li>drag (on mousemove)
* <li>dragend (on mouseup)
*
* </ul>For example, to render the parent panel while dragging, thus
* re-rendering all sibling marks:
*
* <pre> .event("mousedown", pv.Behavior.drag())
* .event("drag", function() this.parent)</pre>
*
* This behavior may be enhanced in the future to allow more flexible
* configuration of drag behavior.
*
* @extends pv.Behavior
* @see pv.Behavior
* @see pv.Behavior.select
* @see pv.Layout.force
*/
pv.Behavior.drag = function () {
var scene, // scene context
index, // scene context
p, // particle being dragged
v1, // initial mouse-particle offset
max;
/** @private */
function mousedown(d) {
index = this.index;
scene = this.scene;
var m = this.mouse();
v1 = ((p = d).fix = pv.vector(d.x, d.y)).minus(m);
max = {
x: this.parent.width() - (d.dx || 0),
y: this.parent.height() - (d.dy || 0)
};
scene.mark.context(scene, index, function () {
this.render();
});
pv.Mark.dispatch("dragstart", scene, index);
}
/** @private */
function mousemove() {
if (!scene)
return;
scene.mark.context(scene, index, function () {
var m = this.mouse();
p.x = p.fix.x = Math.max(0, Math.min(v1.x + m.x, max.x));
p.y = p.fix.y = Math.max(0, Math.min(v1.y + m.y, max.y));
this.render();
});
pv.Mark.dispatch("drag", scene, index);
}
/** @private */
function mouseup() {
if (!scene)
return;
p.fix = null;
scene.mark.context(scene, index, function () {
this.render();
});
pv.Mark.dispatch("dragend", scene, index);
scene = null;
}
pv.listen(window, "mousemove", mousemove);
pv.listen(window, "mouseup", mouseup);
return mousedown;
};
/**
* Returns a new point behavior to be registered on mousemove events.
*
* @class Implements interactive fuzzy pointing, identifying marks that are in
* close proximity to the mouse cursor. This behavior is an alternative to the
* native mouseover and mouseout events, improving usability. Rather than
* requiring the user to mouseover a mark exactly, the mouse simply needs to
* move near the given mark and a "point" event is triggered. In addition, if
* multiple marks overlap, the point behavior can be used to identify the mark
* instance closest to the cursor, as opposed to the one that is rendered on
* top.
*
* <p>The point behavior can also identify the closest mark instance for marks
* that produce a continuous graphic primitive. The point behavior can thus be
* used to provide details-on-demand for both discrete marks (such as dots and
* bars), as well as continuous marks (such as lines and areas).
*
* <p>This behavior is implemented by finding the closest mark instance to the
* mouse cursor on every mousemove event. If this closest mark is within the
* given radius threshold, which defaults to 30 pixels, a "point" psuedo-event
* is dispatched to the given mark instance. If any mark were previously
* pointed, it would receive a corresponding "unpoint" event. These two
* psuedo-event types correspond to the native "mouseover" and "mouseout"
* events, respectively. To increase the radius at which the point behavior can
* be applied, specify an appropriate threshold to the constructor, up to
* <tt>Infinity</tt>.
*
* <p>By default, the standard Cartesian distance is computed. However, with
* some visualizations it is desirable to consider only a single dimension, such
* as the <i>x</i>-dimension for an independent variable. In this case, the
* collapse parameter can be set to collapse the <i>y</i> dimension:
*
* <pre> .event("mousemove", pv.Behavior.point(Infinity).collapse("y"))</pre>
*
* <p>This behavior only listens to mousemove events on the assigned panel,
* which is typically the root panel. The behavior will search recursively for
* descendant marks to point. If the mouse leaves the assigned panel, the
* behavior no longer receives mousemove events; an unpoint psuedo-event is
* automatically dispatched to unpoint any pointed mark. Marks may be re-pointed
* when the mouse reenters the panel.
*
* <p>Panels have transparent fill styles by default; this means that panels may
* not receive the initial mousemove event to start pointing. To fix this
* problem, either given the panel a visible fill style (such as "white"), or
* set the <tt>events</tt> property to "all" such that the panel receives events
* despite its transparent fill.
*
* <p>Note: this behavior does not currently wedge marks.
*
* @extends pv.Behavior
*
* @param {number} [r] the fuzzy radius threshold in pixels
* @see <a href="http://www.tovigrossman.com/papers/chi2005bubblecursor.pdf"
* >"The Bubble Cursor: Enhancing Target Acquisition by Dynamic Resizing of the
* Cursor's Activation Area"</a> by T. Grossman & R. Balakrishnan, CHI 2005.
*/
pv.Behavior.point = function (r) {
var unpoint, // the current pointer target
collapse = null, // dimensions to collapse
kx = 1, // x-dimension cost scale
ky = 1, // y-dimension cost scale
r2 = arguments.length ? r * r : 900; // fuzzy radius
/** @private Search for the mark closest to the mouse. */
function search(scene, index) {
var s = scene[index],
point = {cost: Infinity};
for (var i = 0, n = s.visible && s.children.length; i < n; i++) {
var child = s.children[i], mark = child.mark, p;
if (mark.type == "panel") {
mark.scene = child;
for (var j = 0, m = child.length; j < m; j++) {
mark.index = j;
p = search(child, j);
if (p.cost < point.cost)
point = p;
}
delete mark.scene;
delete mark.index;
} else if (mark.$handlers.point) {
var v = mark.mouse();
for (var j = 0, m = child.length; j < m; j++) {
var c = child[j],
dx = v.x - c.left - (c.width || 0) / 2,
dy = v.y - c.top - (c.height || 0) / 2,
dd = kx * dx * dx + ky * dy * dy;
if (dd < point.cost) {
point.distance = dx * dx + dy * dy;
point.cost = dd;
point.scene = child;
point.index = j;
}
}
}
}
return point;
}
/** @private */
function mousemove() {
/* If the closest mark is far away, clear the current target. */
var point = search(this.scene, this.index);
if ((point.cost == Infinity) || (point.distance > r2))
point = null;
/* Unpoint the old target, if it's not the new target. */
if (unpoint) {
if (point
&& (unpoint.scene == point.scene)
&& (unpoint.index == point.index))
return;
pv.Mark.dispatch("unpoint", unpoint.scene, unpoint.index);
}
/* Point the new target, if there is one. */
if (unpoint = point) {
pv.Mark.dispatch("point", point.scene, point.index);
/* Unpoint when the mouse leaves the root panel. */
pv.listen(this.root.canvas(), "mouseout", mouseout);
}
}
/** @private */
function mouseout(e) {
if (unpoint && !pv.ancestor(this, e.relatedTarget)) {
pv.Mark.dispatch("unpoint", unpoint.scene, unpoint.index);
unpoint = null;
}
}
/**
* Sets or gets the collapse parameter. By default, the standard Cartesian
* distance is computed. However, with some visualizations it is desirable to
* consider only a single dimension, such as the <i>x</i>-dimension for an
* independent variable. In this case, the collapse parameter can be set to
* collapse the <i>y</i> dimension:
*
* <pre> .event("mousemove", pv.Behavior.point(Infinity).collapse("y"))</pre>
*
* @function
* @returns {pv.Behavior.point} this, or the current collapse parameter.
* @name pv.Behavior.point.prototype.collapse
* @param {string} [x] the new collapse parameter
*/
mousemove.collapse = function (x) {
if (arguments.length) {
collapse = String(x);
switch (collapse) {
case "y":
kx = 1;
ky = 0;
break;
case "x":
kx = 0;
ky = 1;
break;
default:
kx = 1;
ky = 1;
break;
}
return mousemove;
}
return collapse;
};
return mousemove;
};
/**
* Returns a new select behavior to be registered on mousedown events.
*
* @class Implements interactive selecting starting with mousedown events.
* Register this behavior on panels that should be selectable by the user, such
* for brushing and linking. This behavior can be used in tandom with
* {@link pv.Behavior.drag} to allow the selected region to be dragged
* interactively.
*
* <p>After the initial mousedown event is triggered, this behavior listens for
* mousemove and mouseup events on the window. This allows selecting to continue
* even if the mouse temporarily leaves the assigned panel, or even the root
* panel.
*
* <p>This behavior requires that the data associated with the mark being
* dragged have <tt>x</tt>, <tt>y</tt>, <tt>dx</tt> and <tt>dy</tt> attributes
* that correspond to the mark's location and dimensions in pixels. The mark's
* positional properties are not set directly by this behavior; instead, the
* positional properties should be defined as:
*
* <pre> .left(function(d) d.x)
* .top(function(d) d.y)
* .width(function(d) d.dx)
* .height(function(d) d.dy)</pre>
*
* Thus, the behavior does not resize the mark directly, but instead updates the
* selection by updating the assigned panel's underlying data. Note that if the
* positional properties are defined with bottom and right (rather than top and
* left), the drag behavior will be inverted, which will confuse users!
*
* <p>The select behavior is bounded by the assigned panel; the positional
* attributes are clamped such that the selection does not extend outside the
* panel's bounds.
*
* <p>The panel being selected is automatically re-rendered for each mouse event
* as part of the drag operation. This behavior may be enhanced in the future to
* allow more flexible configuration of select behavior. In some cases, such as
* with parallel coordinates, making a selection may cause related marks to
* change, in which case additional marks may also need to be rendered. This can
* be accomplished by listening for the select psuedo-events:<ul>
*
* <li>selectstart (on mousedown)
* <li>select (on mousemove)
* <li>selectend (on mouseup)
*
* </ul>For example, to render the parent panel while selecting, thus
* re-rendering all sibling marks:
*
* <pre> .event("mousedown", pv.Behavior.drag())
* .event("select", function() this.parent)</pre>
*
* This behavior may be enhanced in the future to allow more flexible
* configuration of the selection behavior.
*
* @extends pv.Behavior
* @see pv.Behavior.drag
*/
pv.Behavior.select = function () {
var scene, // scene context
index, // scene context
r, // region being selected
m1; // initial mouse position
/** @private */
function mousedown(d) {
index = this.index;
scene = this.scene;
m1 = this.mouse();
r = d;
r.x = m1.x;
r.y = m1.y;
r.dx = r.dy = 0;
pv.Mark.dispatch("selectstart", scene, index);
}
/** @private */
function mousemove() {
if (!scene)
return;
scene.mark.context(scene, index, function () {
var m2 = this.mouse();
r.x = Math.max(0, Math.min(m1.x, m2.x));
r.y = Math.max(0, Math.min(m1.y, m2.y));
r.dx = Math.min(this.width(), Math.max(m2.x, m1.x)) - r.x;
r.dy = Math.min(this.height(), Math.max(m2.y, m1.y)) - r.y;
this.render();
});
pv.Mark.dispatch("select", scene, index);
}
/** @private */
function mouseup() {
if (!scene)
return;
pv.Mark.dispatch("selectend", scene, index);
scene = null;
}
pv.listen(window, "mousemove", mousemove);
pv.listen(window, "mouseup", mouseup);
return mousedown;
};
/**
* Returns a new resize behavior to be registered on mousedown events.
*
* @class Implements interactive resizing of a selection starting with mousedown
* events. Register this behavior on selection handles that should be resizeable
* by the user, such for brushing and linking. This behavior can be used in
* tandom with {@link pv.Behavior.select} and {@link pv.Behavior.drag} to allow
* the selected region to be selected and dragged interactively.
*
* <p>After the initial mousedown event is triggered, this behavior listens for
* mousemove and mouseup events on the window. This allows resizing to continue
* even if the mouse temporarily leaves the assigned panel, or even the root
* panel.
*
* <p>This behavior requires that the data associated with the mark being
* resized have <tt>x</tt>, <tt>y</tt>, <tt>dx</tt> and <tt>dy</tt> attributes
* that correspond to the mark's location and dimensions in pixels. The mark's
* positional properties are not set directly by this behavior; instead, the
* positional properties should be defined as:
*
* <pre> .left(function(d) d.x)
* .top(function(d) d.y)
* .width(function(d) d.dx)
* .height(function(d) d.dy)</pre>
*
* Thus, the behavior does not resize the mark directly, but instead updates the
* size by updating the assigned panel's underlying data. Note that if the
* positional properties are defined with bottom and right (rather than top and
* left), the resize behavior will be inverted, which will confuse users!
*
* <p>The resize behavior is bounded by the assigned mark's enclosing panel; the
* positional attributes are clamped such that the selection does not extend
* outside the panel's bounds.
*
* <p>The mark being resized is automatically re-rendered for each mouse event
* as part of the resize operation. This behavior may be enhanced in the future
* to allow more flexible configuration. In some cases, such as with parallel
* coordinates, resizing the selection may cause related marks to change, in
* which case additional marks may also need to be rendered. This can be
* accomplished by listening for the select psuedo-events:<ul>
*
* <li>resizestart (on mousedown)
* <li>resize (on mousemove)
* <li>resizeend (on mouseup)
*
* </ul>For example, to render the parent panel while resizing, thus
* re-rendering all sibling marks:
*
* <pre> .event("mousedown", pv.Behavior.resize("left"))
* .event("resize", function() this.parent)</pre>
*
* This behavior may be enhanced in the future to allow more flexible
* configuration of the selection behavior.
*
* @extends pv.Behavior
* @see pv.Behavior.select
* @see pv.Behavior.drag
*/
pv.Behavior.resize = function (side) {
var scene, // scene context
index, // scene context
r, // region being selected
m1; // initial mouse position
/** @private */
function mousedown(d) {
index = this.index;
scene = this.scene;
m1 = this.mouse();
r = d;
switch (side) {
case "left":
m1.x = r.x + r.dx;
break;
case "right":
m1.x = r.x;
break;
case "top":
m1.y = r.y + r.dy;
break;
case "bottom":
m1.y = r.y;
break;
}
pv.Mark.dispatch("resizestart", scene, index);
}
/** @private */
function mousemove() {
if (!scene)
return;
scene.mark.context(scene, index, function () {
var m2 = this.mouse();
r.x = Math.max(0, Math.min(m1.x, m2.x));
r.y = Math.max(0, Math.min(m1.y, m2.y));
r.dx = Math.min(this.parent.width(), Math.max(m2.x, m1.x)) - r.x;
r.dy = Math.min(this.parent.height(), Math.max(m2.y, m1.y)) - r.y;
this.render();
});
pv.Mark.dispatch("resize", scene, index);
}
/** @private */
function mouseup() {
if (!scene)
return;
pv.Mark.dispatch("resizeend", scene, index);
scene = null;
}
pv.listen(window, "mousemove", mousemove);
pv.listen(window, "mouseup", mouseup);
return mousedown;
};
/**
* Returns a new pan behavior to be registered on mousedown events.
*
* @class Implements interactive panning starting with mousedown events.
* Register this behavior on panels to allow panning. This behavior can be used
* in tandem with {@link pv.Behavior.zoom} to allow both panning and zooming:
*
* <pre> .event("mousedown", pv.Behavior.pan())
* .event("mousewheel", pv.Behavior.zoom())</pre>
*
* The pan behavior currently supports only mouse events; support for keyboard
* shortcuts to improve accessibility may be added in the future.
*
* <p>After the initial mousedown event is triggered, this behavior listens for
* mousemove and mouseup events on the window. This allows panning to continue
* even if the mouse temporarily leaves the panel that is being panned, or even
* the root panel.
*
* <p>The implementation of this behavior relies on the panel's
* <tt>transform</tt> property, which specifies a matrix transformation that is
* applied to child marks. Note that the transform property only affects the
* panel's children, but not the panel itself; therefore the panel's fill and
* stroke will not change when the contents are panned.
*
* <p>Panels have transparent fill styles by default; this means that panels may
* not receive the initial mousedown event to start panning. To fix this
* problem, either given the panel a visible fill style (such as "white"), or
* set the <tt>events</tt> property to "all" such that the panel receives events
* despite its transparent fill.
*
* <p>The pan behavior has optional support for bounding. If enabled, the user
* will not be able to pan the panel outside of the initial bounds. This feature
* is designed to work in conjunction with the zoom behavior; otherwise,
* bounding the panel effectively disables all panning.
*
* @extends pv.Behavior
* @see pv.Behavior.zoom
* @see pv.Panel#transform
*/
pv.Behavior.pan = function () {
var scene, // scene context
index, // scene context
m1, // transformation matrix at the start of panning
v1, // mouse location at the start of panning
k, // inverse scale
bound; // whether to bound to the panel
/** @private */
function mousedown() {
index = this.index;
scene = this.scene;
v1 = pv.vector(pv.event.pageX, pv.event.pageY);
m1 = this.transform();
k = 1 / (m1.k * this.scale);
if (bound) {
bound = {
x: (1 - m1.k) * this.width(),
y: (1 - m1.k) * this.height()
};
}
}
/** @private */
function mousemove() {
if (!scene)
return;
scene.mark.context(scene, index, function () {
var x = (pv.event.pageX - v1.x) * k,
y = (pv.event.pageY - v1.y) * k,
m = m1.translate(x, y);
if (bound) {
m.x = Math.max(bound.x, Math.min(0, m.x));
m.y = Math.max(bound.y, Math.min(0, m.y));
}
this.transform(m).render();
});
pv.Mark.dispatch("pan", scene, index);
}
/** @private */
function mouseup() {
scene = null;
}
/**
* Sets or gets the bound parameter. If bounding is enabled, the user will not
* be able to pan outside the initial panel bounds; this typically applies
* only when the pan behavior is used in tandem with the zoom behavior.
* Bounding is not enabled by default.
*
* <p>Note: enabling bounding after panning has already occurred will not
* immediately reset the transform. Bounding should be enabled before the
* panning behavior is applied.
*
* @function
* @returns {pv.Behavior.pan} this, or the current bound parameter.
* @name pv.Behavior.pan.prototype.bound
* @param {boolean} [x] the new bound parameter.
*/
mousedown.bound = function (x) {
if (arguments.length) {
bound = Boolean(x);
return this;
}
return Boolean(bound);
};
pv.listen(window, "mousemove", mousemove);
pv.listen(window, "mouseup", mouseup);
return mousedown;
};
/**
* Returns a new zoom behavior to be registered on mousewheel events.
*
* @class Implements interactive zooming using mousewheel events. Register this
* behavior on panels to allow zooming. This behavior can be used in tandem with
* {@link pv.Behavior.pan} to allow both panning and zooming:
*
* <pre> .event("mousedown", pv.Behavior.pan())
* .event("mousewheel", pv.Behavior.zoom())</pre>
*
* The zoom behavior currently supports only mousewheel events; support for
* keyboard shortcuts and gesture events to improve accessibility may be added
* in the future.
*
* <p>The implementation of this behavior relies on the panel's
* <tt>transform</tt> property, which specifies a matrix transformation that is
* applied to child marks. Note that the transform property only affects the
* panel's children, but not the panel itself; therefore the panel's fill and
* stroke will not change when the contents are zoomed. The built-in support for
* transforms only supports uniform scaling and translates, which is sufficient
* for panning and zooming. Note that this is not a strict geometric
* transformation, as the <tt>lineWidth</tt> property is scale-aware: strokes
* are drawn at constant size independent of scale.
*
* <p>Panels have transparent fill styles by default; this means that panels may
* not receive mousewheel events to zoom. To fix this problem, either given the
* panel a visible fill style (such as "white"), or set the <tt>events</tt>
* property to "all" such that the panel receives events despite its transparent
* fill.
*
* <p>The zoom behavior has optional support for bounding. If enabled, the user
* will not be able to zoom out farther than the initial bounds. This feature is
* designed to work in conjunction with the pan behavior.
*
* @extends pv.Behavior
* @see pv.Panel#transform
* @see pv.Mark#scale
* @param {number} speed
*/
pv.Behavior.zoom = function (speed) {
var bound; // whether to bound to the panel
if (!arguments.length)
speed = 1 / 48;
/** @private */
function mousewheel() {
var v = this.mouse(),
k = pv.event.wheel * speed,
m = this.transform().translate(v.x, v.y)
.scale((k < 0) ? (1e3 / (1e3 - k)) : ((1e3 + k) / 1e3))
.translate(-v.x, -v.y);
if (bound) {
m.k = Math.max(1, m.k);
m.x = Math.max((1 - m.k) * this.width(), Math.min(0, m.x));
m.y = Math.max((1 - m.k) * this.height(), Math.min(0, m.y));
}
this.transform(m).render();
pv.Mark.dispatch("zoom", this.scene, this.index);
}
/**
* Sets or gets the bound parameter. If bounding is enabled, the user will not
* be able to zoom out farther than the initial panel bounds. Bounding is not
* enabled by default. If this behavior is used in tandem with the pan
* behavior, both should use the same bound parameter.
*
* <p>Note: enabling bounding after zooming has already occurred will not
* immediately reset the transform. Bounding should be enabled before the zoom
* behavior is applied.
*
* @function
* @returns {pv.Behavior.zoom} this, or the current bound parameter.
* @name pv.Behavior.zoom.prototype.bound
* @param {boolean} [x] the new bound parameter.
*/
mousewheel.bound = function (x) {
if (arguments.length) {
bound = Boolean(x);
return this;
}
return Boolean(bound);
};
return mousewheel;
};
/**
* @ignore
* @namespace
*/
pv.Geo = function () {
};
/**
* Abstract; not implemented. There is no explicit constructor; this class
* merely serves to document the representation used by {@link pv.Geo.scale}.
*
* @class Represents a pair of geographic coordinates.
*
* @name pv.Geo.LatLng
* @see pv.Geo.scale
*/
/**
* The <i>latitude</i> coordinate in degrees; positive is North.
*
* @type number
* @name pv.Geo.LatLng.prototype.lat
*/
/**
* The <i>longitude</i> coordinate in degrees; positive is East.
*
* @type number
* @name pv.Geo.LatLng.prototype.lng
*/
/**
* Abstract; not implemented. There is no explicit constructor; this class
* merely serves to document the representation used by {@link pv.Geo.scale}.
*
* @class Represents a geographic projection. This class provides the core
* implementation for {@link pv.Geo.scale}s, mapping between geographic
* coordinates (latitude and longitude) and normalized screen space in the range
* [-1,1]. The remaining mapping between normalized screen space and actual
* pixels is performed by <tt>pv.Geo.scale</tt>.
*
* <p>Many geographic projections have a point around which the projection is
* centered. Rather than have each implementation add support for a
* user-specified center point, the <tt>pv.Geo.scale</tt> translates the
* geographic coordinates relative to the center point for both the forward and
* inverse projection.
*
* <p>In general, this class should not be used directly, unless the desire is
* to implement a new geographic projection. Instead, use <tt>pv.Geo.scale</tt>.
* Implementations are not required to implement inverse projections, but are
* needed for some forms of interactivity. Also note that some inverse
* projections are ambiguous, such as the connecting points in Dymaxian maps.
*
* @name pv.Geo.Projection
* @see pv.Geo.scale
*/
/**
* The <i>forward</i> projection.
*
* @function
* @name pv.Geo.Projection.prototype.project
* @param {pv.Geo.LatLng} latlng the latitude and longitude to project.
* @returns {pv.Vector} the xy-coordinates of the given point.
*/
/**
* The <i>inverse</i> projection; optional.
*
* @function
* @name pv.Geo.Projection.prototype.invert
* @param {pv.Vector} xy the x- and y-coordinates to invert.
* @returns {pv.Geo.LatLng} the latitude and longitude of the given point.
*/
/**
* The built-in projections.
*
* @see pv.Geo.Projection
* @namespace
*/
pv.Geo.projections = {
/** @see http://en.wikipedia.org/wiki/Mercator_projection */
mercator: {
project: function (latlng) {
return {
x: latlng.lng / 180,
y: latlng.lat > 85 ? 1 : latlng.lat < -85 ? -1
: Math.log(Math.tan(Math.PI / 4
+ pv.radians(latlng.lat) / 2)) / Math.PI
};
},
invert: function (xy) {
return {
lng: xy.x * 180,
lat: pv.degrees(2 * Math.atan(Math.exp(xy.y * Math.PI)) - Math.PI / 2)
};
}
},
/** @see http://en.wikipedia.org/wiki/Gall-Peters_projection */
"gall-peters": {
project: function (latlng) {
return {
x: latlng.lng / 180,
y: Math.sin(pv.radians(latlng.lat))
};
},
invert: function (xy) {
return {
lng: xy.x * 180,
lat: pv.degrees(Math.asin(xy.y))
};
}
},
/** @see http://en.wikipedia.org/wiki/Sinusoidal_projection */
sinusoidal: {
project: function (latlng) {
return {
x: pv.radians(latlng.lng) * Math.cos(pv.radians(latlng.lat)) / Math.PI,
y: latlng.lat / 90
};
},
invert: function (xy) {
return {
lng: pv.degrees((xy.x * Math.PI) / Math.cos(xy.y * Math.PI / 2)),
lat: xy.y * 90
};
}
},
/** @see http://en.wikipedia.org/wiki/Aitoff_projection */
aitoff: {
project: function (latlng) {
var l = pv.radians(latlng.lng),
f = pv.radians(latlng.lat),
a = Math.acos(Math.cos(f) * Math.cos(l / 2));
return {
x: 2 * (a ? (Math.cos(f) * Math.sin(l / 2) * a / Math.sin(a)) : 0) / Math.PI,
y: 2 * (a ? (Math.sin(f) * a / Math.sin(a)) : 0) / Math.PI
};
},
invert: function (xy) {
var x = xy.x * Math.PI / 2,
y = xy.y * Math.PI / 2;
return {
lng: pv.degrees(x / Math.cos(y)),
lat: pv.degrees(y)
};
}
},
/** @see http://en.wikipedia.org/wiki/Hammer_projection */
hammer: {
project: function (latlng) {
var l = pv.radians(latlng.lng),
f = pv.radians(latlng.lat),
c = Math.sqrt(1 + Math.cos(f) * Math.cos(l / 2));
return {
x: 2 * Math.SQRT2 * Math.cos(f) * Math.sin(l / 2) / c / 3,
y: Math.SQRT2 * Math.sin(f) / c / 1.5
};
},
invert: function (xy) {
var x = xy.x * 3,
y = xy.y * 1.5,
z = Math.sqrt(1 - x * x / 16 - y * y / 4);
return {
lng: pv.degrees(2 * Math.atan2(z * x, 2 * (2 * z * z - 1))),
lat: pv.degrees(Math.asin(z * y))
};
}
},
/** The identity or "none" projection. */
identity: {
project: function (latlng) {
return {
x: latlng.lng / 180,
y: latlng.lat / 90
};
},
invert: function (xy) {
return {
lng: xy.x * 180,
lat: xy.y * 90
};
}
}
};
/**
* Returns a geographic scale. The arguments to this constructor are optional,
* and equivalent to calling {@link #projection}.
*
* @class Represents a geographic scale; a mapping between latitude-longitude
* coordinates and screen pixel coordinates. By default, the domain is inferred
* from the geographic coordinates, so that the domain fills the output range.
*
* <p>Note that geographic scales are two-dimensional transformations, rather
* than the one-dimensional bidrectional mapping typical of other scales.
* Rather than mapping (for example) between a numeric domain and a numeric
* range, geographic scales map between two coordinate objects: {@link
* pv.Geo.LatLng} and {@link pv.Vector}.
*
* @param {pv.Geo.Projection} [p] optional projection.
* @see pv.Geo.scale#ticks
*/
pv.Geo.scale = function (p) {
var rmin = {x: 0, y: 0}, // default range minimum
rmax = {x: 1, y: 1}, // default range maximum
d = [], // default domain
j = pv.Geo.projections.identity, // domain <-> normalized range
x = pv.Scale.linear(-1, 1).range(0, 1), // normalized <-> range
y = pv.Scale.linear(-1, 1).range(1, 0), // normalized <-> range
c = {lng: 0, lat: 0}, // Center Point
lastLatLng, // cached latlng
lastPoint; // cached point
/** @private */
function scale(latlng) {
if (!lastLatLng
|| (latlng.lng != lastLatLng.lng)
|| (latlng.lat != lastLatLng.lat)) {
lastLatLng = latlng;
var p = project(latlng);
lastPoint = {x: x(p.x), y: y(p.y)};
}
return lastPoint;
}
/** @private */
function project(latlng) {
var offset = {lng: latlng.lng - c.lng, lat: latlng.lat};
return j.project(offset);
}
/** @private */
function invert(xy) {
var latlng = j.invert(xy);
latlng.lng += c.lng;
return latlng;
}
/** Returns the projected x-coordinate. */
scale.x = function (latlng) {
return scale(latlng).x;
};
/** Returns the projected y-coordinate. */
scale.y = function (latlng) {
return scale(latlng).y;
};
/**
* Abstract; this is a local namespace on a given geographic scale.
*
* @namespace Tick functions for geographic scales. Because geographic scales
* represent two-dimensional transformations (as opposed to one-dimensional
* transformations typical of other scales), the tick values are similarly
* represented as two-dimensional coordinates in the input domain, i.e.,
* {@link pv.Geo.LatLng} objects.
*
* <p>Also, note that non-rectilinear projections, such as sinsuoidal and
* aitoff, may not produce straight lines for constant longitude or constant
* latitude. Therefore the returned array of ticks is a two-dimensional array,
* sampling various latitudes as constant longitude, and vice versa.
*
* <p>The tick lines can therefore be approximated as polylines, either with
* "linear" or "cardinal" interpolation. This is not as accurate as drawing
* the true curve through the projection space, but is usually sufficient.
*
* @name pv.Geo.scale.prototype.ticks
* @see pv.Geo.scale
* @see pv.Geo.LatLng
* @see pv.Line#interpolate
*/
scale.ticks = {
/**
* Returns longitude ticks.
*
* @function
* @param {number} [m] the desired number of ticks.
* @returns {array} a nested array of <tt>pv.Geo.LatLng</tt> ticks.
* @name pv.Geo.scale.prototype.ticks.prototype.lng
*/
lng: function (m) {
var lat, lng;
if (d.length > 1) {
var s = pv.Scale.linear();
if (m == undefined)
m = 10;
lat = s.domain(d, function (d) {
return d.lat;
}).ticks(m);
lng = s.domain(d, function (d) {
return d.lng;
}).ticks(m);
} else {
lat = pv.range(-80, 81, 10);
lng = pv.range(-180, 181, 10);
}
return lng.map(function (lng) {
return lat.map(function (lat) {
return {lat: lat, lng: lng};
});
});
},
/**
* Returns latitude ticks.
*
* @function
* @param {number} [m] the desired number of ticks.
* @returns {array} a nested array of <tt>pv.Geo.LatLng</tt> ticks.
* @name pv.Geo.scale.prototype.ticks.prototype.lat
*/
lat: function (m) {
return pv.transpose(scale.ticks.lng(m));
}
};
/**
* Inverts the specified value in the output range, returning the
* corresponding value in the input domain. This is frequently used to convert
* the mouse location (see {@link pv.Mark#mouse}) to a value in the input
* domain. Inversion is only supported for numeric ranges, and not colors.
*
* <p>Note that this method does not do any rounding or bounds checking. If
* the input domain is discrete (e.g., an array index), the returned value
* should be rounded. If the specified <tt>y</tt> value is outside the range,
* the returned value may be equivalently outside the input domain.
*
* @function
* @name pv.Geo.scale.prototype.invert
* @param {number} y a value in the output range (a pixel location).
* @returns {number} a value in the input domain.
*/
scale.invert = function (p) {
return invert({x: x.invert(p.x), y: y.invert(p.y)});
};
/**
* Sets or gets the input domain. Note that unlike quantitative scales, the
* domain cannot be reduced to a simple rectangle (i.e., minimum and maximum
* values for latitude and longitude). Instead, the domain values must be
* projected to normalized space, effectively finding the domain in normalized
* space rather than in terms of latitude and longitude. Thus, changing the
* projection requires recomputing the normalized domain.
*
* <p>This method can be invoked several ways:
*
* <p>1. <tt>domain(values...)</tt>
*
* <p>Specifying the domain as a series of {@link pv.Geo.LatLng}s is the most
* explicit and recommended approach. However, if the domain values are
* derived from data, you may find the second method more appropriate.
*
* <p>2. <tt>domain(array, f)</tt>
*
* <p>Rather than enumerating the domain explicitly, you can specify a single
* argument of an array. In addition, you can specify an optional accessor
* function to extract the domain values (as {@link pv.Geo.LatLng}s) from the
* array. If the specified array has fewer than two elements, this scale will
* default to the full normalized domain.
*
* <p>2. <tt>domain()</tt>
*
* <p>Invoking the <tt>domain</tt> method with no arguments returns the
* current domain as an array.
*
* @function
* @name pv.Geo.scale.prototype.domain
* @param {...} domain... domain values.
* @returns {pv.Geo.scale} <tt>this</tt>, or the current domain.
*/
scale.domain = function (array, f) {
if (arguments.length) {
d = (array instanceof Array)
? ((arguments.length > 1) ? pv.map(array, f) : array)
: Array.prototype.slice.call(arguments);
if (d.length > 1) {
var lngs = d.map(function (c) {
return c.lng;
});
var lats = d.map(function (c) {
return c.lat;
});
c = {
lng: (pv.max(lngs) + pv.min(lngs)) / 2,
lat: (pv.max(lats) + pv.min(lats)) / 2
};
var n = d.map(project); // normalized domain
x.domain(n, function (p) {
return p.x;
});
y.domain(n, function (p) {
return p.y;
});
} else {
c = {lng: 0, lat: 0};
x.domain(-1, 1);
y.domain(-1, 1);
}
lastLatLng = null; // invalidate the cache
return this;
}
return d;
};
/**
* Sets or gets the output range. This method can be invoked several ways:
*
* <p>1. <tt>range(min, max)</tt>
*
* <p>If two objects are specified, the arguments should be {@link pv.Vector}s
* which specify the minimum and maximum values of the x- and y-coordinates
* explicitly.
*
* <p>2. <tt>range(width, height)</tt>
*
* <p>If two numbers are specified, the arguments specify the maximum values
* of the x- and y-coordinates explicitly; the minimum values are implicitly
* zero.
*
* <p>3. <tt>range()</tt>
*
* <p>Invoking the <tt>range</tt> method with no arguments returns the current
* range as an array of two {@link pv.Vector}s: the minimum (top-left) and
* maximum (bottom-right) values.
*
* @function
* @name pv.Geo.scale.prototype.range
* @param {...} range... range values.
* @returns {pv.Geo.scale} <tt>this</tt>, or the current range.
*/
scale.range = function (min, max) {
if (arguments.length) {
if (typeof min == "object") {
rmin = {x: Number(min.x), y: Number(min.y)};
rmax = {x: Number(max.x), y: Number(max.y)};
} else {
rmin = {x: 0, y: 0};
rmax = {x: Number(min), y: Number(max)};
}
x.range(rmin.x, rmax.x);
y.range(rmax.y, rmin.y); // XXX flipped?
lastLatLng = null; // invalidate the cache
return this;
}
return [rmin, rmax];
};
/**
* Sets or gets the projection. This method can be invoked several ways:
*
* <p>1. <tt>projection(string)</tt>
*
* <p>Specifying a string sets the projection to the given named projection in
* {@link pv.Geo.projections}. If no such projection is found, the identity
* projection is used.
*
* <p>2. <tt>projection(object)</tt>
*
* <p>Specifying an object sets the projection to the given custom projection,
* which must implement the <i>forward</i> and <i>inverse</i> methods per the
* {@link pv.Geo.Projection} interface.
*
* <p>3. <tt>projection()</tt>
*
* <p>Invoking the <tt>projection</tt> method with no arguments returns the
* current object that defined the projection.
*
* @function
* @name pv.Scale.geo.prototype.projection
* @param {...} range... range values.
* @returns {pv.Scale.geo} <tt>this</tt>, or the current range.
*/
scale.projection = function (p) {
if (arguments.length) {
j = typeof p == "string"
? pv.Geo.projections[p] || pv.Geo.projections.identity
: p;
return this.domain(d); // recompute normalized domain
}
return p;
};
/**
* Returns a view of this scale by the specified accessor function <tt>f</tt>.
* Given a scale <tt>g</tt>, <tt>g.by(function(d) d.foo)</tt> is equivalent to
* <tt>function(d) g(d.foo)</tt>. This method should be used judiciously; it
* is typically more clear to invoke the scale directly, passing in the value
* to be scaled.
*
* @function
* @name pv.Geo.scale.prototype.by
* @param {function} f an accessor function.
* @returns {pv.Geo.scale} a view of this scale by the specified accessor
* function.
*/
scale.by = function (f) {
function by() {
return scale(f.apply(this, arguments));
}
for (var method in scale)
by[method] = scale[method];
return by;
};
if (arguments.length)
scale.projection(p);
return scale;
};
| 34.200922 | 120 | 0.580184 |