text stringlengths 2 1.04M | meta dict |
|---|---|
package org.peerbox.app.manager.user;
public final class LoginMessage extends AbstractUserMessage {
public LoginMessage(final String username) {
super(username);
}
}
| {
"content_hash": "bab1f19cb1299a44748f5b2fd832e6d0",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 61,
"avg_line_length": 19.22222222222222,
"alnum_prop": 0.7803468208092486,
"repo_name": "PeerWasp/PeerWasp",
"id": "0abb18a567c15688abb873b05d1999e182af1708",
"size": "173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "peerbox/src/main/java/org/peerbox/app/manager/user/LoginMessage.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "60437"
},
{
"name": "CSS",
"bytes": "380"
},
{
"name": "Inno Setup",
"bytes": "6826"
},
{
"name": "Java",
"bytes": "961780"
},
{
"name": "Python",
"bytes": "4225"
},
{
"name": "Shell",
"bytes": "794"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_68a.c
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml
Template File: sources-sink-68a.tmpl.c
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate using malloc() and set data pointer to a small buffer
* GoodSource: Allocate using malloc() and set data pointer to a large buffer
* Sink: memcpy
* BadSink : Copy int array to data using memcpy
* Flow Variant: 68 Data flow: data passed as a global variable from one function to another in different source files
*
* */
#include "std_testcase.h"
int * CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_68_badData;
int * CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_68_goodG2BData;
#ifndef OMITBAD
/* bad function declaration */
void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_68b_badSink();
void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_68_bad()
{
int * data;
data = NULL;
/* FLAW: Allocate and point data to a small buffer that is smaller than the large buffer used in the sinks */
data = (int *)malloc(50*sizeof(int));
if (data == NULL) {exit(-1);}
CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_68_badData = data;
CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_68b_badSink();
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_68b_goodG2BSink();
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
int * data;
data = NULL;
/* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */
data = (int *)malloc(100*sizeof(int));
if (data == NULL) {exit(-1);}
CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_68_goodG2BData = data;
CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_68b_goodG2BSink();
}
void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_68_good()
{
goodG2B();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_68_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_68_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {
"content_hash": "a31b770d88bbd0567ba9a2fc0463c485",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 119,
"avg_line_length": 33.640449438202246,
"alnum_prop": 0.6863727454909819,
"repo_name": "JianpingZeng/xcc",
"id": "98347665c4fc4736abaadbbf49cbda62a2c7679f",
"size": "2994",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s08/CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_68a.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package net.explorviz.landscape.model.helper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.explorviz.landscape.model.application.AggregatedClazzCommunication;
import net.explorviz.landscape.model.application.Application;
import net.explorviz.landscape.model.application.ApplicationCommunication;
import net.explorviz.landscape.model.application.Clazz;
import net.explorviz.landscape.model.application.ClazzCommunication;
import net.explorviz.landscape.model.application.Component;
import net.explorviz.landscape.model.application.DatabaseQuery;
import net.explorviz.landscape.model.application.Trace;
import net.explorviz.landscape.model.application.TraceStep;
import net.explorviz.landscape.model.event.Event;
import net.explorviz.landscape.model.landscape.Landscape;
import net.explorviz.landscape.model.landscape.Node;
import net.explorviz.landscape.model.landscape.NodeGroup;
import net.explorviz.landscape.model.landscape.System;
import net.explorviz.landscape.model.store.Timestamp;
public class TypeProvider {
public static Map<String, Class<?>> getExplorVizCoreTypesAsMap() {
final Map<String, Class<?>> typeMap = new HashMap<>();
typeMap.putIfAbsent("Timestamp", Timestamp.class);
typeMap.putIfAbsent("Event", Event.class);
// typeMap.putIfAbsent("EEventType", EEventType.class);
typeMap.putIfAbsent("Landscape", Landscape.class);
typeMap.putIfAbsent("System", System.class);
typeMap.putIfAbsent("NodeGroup", NodeGroup.class);
typeMap.putIfAbsent("Node", Node.class);
typeMap.putIfAbsent("Application", Application.class);
typeMap.putIfAbsent("ApplicationCommunication", ApplicationCommunication.class);
typeMap.putIfAbsent("Component", Component.class);
typeMap.putIfAbsent("Clazz", Clazz.class);
typeMap.putIfAbsent("ClazzCommunication", ClazzCommunication.class);
typeMap.putIfAbsent("Trace", Trace.class);
typeMap.putIfAbsent("TraceStep", TraceStep.class);
typeMap.putIfAbsent("AggregatedClazzCommunication", AggregatedClazzCommunication.class);
typeMap.putIfAbsent("DatabaseQuery", DatabaseQuery.class);
return typeMap;
}
public static List<Class<?>> getExplorVizCoreTypesAsList() {
return new ArrayList<>(TypeProvider.getExplorVizCoreTypesAsMap().values());
}
public static Class<?>[] getExplorVizCoreTypesAsArray() {
final List<Class<?>> typeList = TypeProvider.getExplorVizCoreTypesAsList();
return typeList.toArray(new Class<?>[typeList.size()]);
}
}
| {
"content_hash": "d5d6320bb306b62c7309d41f16ebf5f9",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 92,
"avg_line_length": 43.775862068965516,
"alnum_prop": 0.7892871209137455,
"repo_name": "ExplorViz/explorviz-ui-backend",
"id": "9ac205133f50bbe52bed393379b2dcf6ea1fef48",
"size": "2539",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "landscape-service/landscape-model/src/main/java/net/explorviz/landscape/model/helper/TypeProvider.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "65883"
},
{
"name": "Shell",
"bytes": "595"
},
{
"name": "Xtend",
"bytes": "72998"
}
],
"symlink_target": ""
} |
(pr_checklist)=
# Pull request checklist
We recommend that your contribution complies with the following guidelines before you submit a pull request:
* If your pull request addresses an issue, please use the pull request title to describe the issue and mention the issue number in the pull request description. This will make sure a link back to the original issue is created.
* All public methods must have informative docstrings with sample usage when appropriate.
* Please prefix the title of incomplete contributions with `[WIP]` (to indicate a work in progress). WIPs may be useful to (1) indicate you are working on something to avoid duplicated work, (2) request a broad review of functionality or API, or (3) seek collaborators.
* All other tests pass when everything is rebuilt from scratch.
See {ref}`developing_in_docker` for information on running the test suite locally.
* When adding additional plotting functionality, provide at least one example script in the [arviz/examples/](https://github.com/arviz-devs/arviz/tree/main/examples) folder. Have a look at other examples for reference. Examples should demonstrate why the new functionality is useful in practice and, if possible, compare it to other methods available in ArviZ.
* Added tests follow the [pytest fixture pattern](https://docs.pytest.org/en/latest/fixture.html#fixture).
* Documentation and high-coverage tests are necessary for enhancements to be accepted.
* Documentation follows Numpy style guide.
* Run any of the pre-existing examples in ``docs/source/notebooks`` that contain analyses that would be affected by your changes to ensure that nothing breaks. This is a useful opportunity to not only check your work for bugs that might not be revealed by unit test, but also to show how your contribution improves ArviZ for end users.
* If modifying a plot, render your plot to inspect for changes and copy image in the pull request message on Github.
You can also check for common programming errors with the following
tools:
* Save plots as part of tests. Plots will be saved to a directory named `test_images` by default.
```bash
$ pytest arviz/tests/base_tests/<name of test>.py --save
```
* Optionally save plots to a user named directory. This is useful for comparing changes across branches.
```bash
$ pytest arviz/tests/base_tests/<name of test>.py --save user_defined_directory
```
* Code coverage **cannot** decrease. Coverage can be checked with **pytest-cov** package:
```bash
$ pip install pytest pytest-cov coverage
$ pytest --cov=arviz --cov-report=html arviz/tests/
```
* Your code has been formatted with [black](https://github.com/ambv/black) with a line length of 100 characters.
```bash
$ pip install black
$ black arviz/ examples/ asv_benchmarks/
```
* Your code passes pylint
```bash
$ pip install pylint
$ pylint arviz/
```
* No code style warnings, check with:
```bash
$ ./scripts/lint.sh
```
| {
"content_hash": "86d05393efcf9780bed1f31a75f917b9",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 360,
"avg_line_length": 43.63235294117647,
"alnum_prop": 0.7583417593528817,
"repo_name": "arviz-devs/arviz",
"id": "27041f750fb87ed98513b7d67fffe627d991ef3c",
"size": "2967",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "doc/source/contributing/pr_checklist.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "5900"
},
{
"name": "Dockerfile",
"bytes": "1771"
},
{
"name": "HTML",
"bytes": "1343"
},
{
"name": "Jupyter Notebook",
"bytes": "641262"
},
{
"name": "Makefile",
"bytes": "688"
},
{
"name": "PowerShell",
"bytes": "2668"
},
{
"name": "Python",
"bytes": "1634423"
},
{
"name": "R",
"bytes": "248"
},
{
"name": "Shell",
"bytes": "7276"
},
{
"name": "TeX",
"bytes": "24620"
}
],
"symlink_target": ""
} |
import React from 'react';
import { Container, Form, FormGroup, FormFeedback, Input, Card, CardBlock, CardTitle, Button } from 'reactstrap';
import FontAwesome from 'react-fontawesome';
import Cookies from 'js-cookie';
class LoginForm extends React.Component {
constructor() {
super();
this.state = { username: '', password: '', authResult: '' };
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
handleSubmit(e) {
e.preventDefault();
const username = this.state.username;
const password = this.state.password;
fetch('/api/login', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({ username, password })
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw new Error('fetch error');
}
})
.then(jsonRes => {
if (jsonRes.status === 'ok') {
Cookies.set('token', jsonRes.token._id, { path: '/', expires: 3 });
this.props.callBack(true);
} else if (jsonRes.status === 'ng') {
this.setState({ authResult: jsonRes.status });
this.props.callBack(jsonRes.status);
}
})
.catch(err => {
console.log(err);
});
}
render() {
return (
<Container fluid>
<Card block className="login-card">
<CardBlock>
<CardTitle className="login-card-title">
<FontAwesome name="user-circle-o" size="3x" />
</CardTitle>
</CardBlock>
<Form onSubmit={this.handleSubmit}>
<FormGroup>
<Input type="text" value={this.state.username} onChange={this.handleChange} name="username" id="username" placeholder="Username" />
</FormGroup>
<FormGroup>
<Input type="password" value={this.state.password} onChange={this.handleChange} name="password" id="password" placeholder="Password" />
</FormGroup>
{(this.state.authResult === "ng") ? (
<FormGroup color="danger">
<FormFeedback color="danger">Wrong password. Try again.</FormFeedback>
</FormGroup>
) : null}
<FormGroup>
<Button type="submit" className="login-button" color="info" block>Login</Button>
</FormGroup>
</Form>
</Card>
</Container>
);
}
}
export default LoginForm; | {
"content_hash": "5bb5d67b79e98b43507593c462c03f12",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 149,
"avg_line_length": 29.813953488372093,
"alnum_prop": 0.5659126365054602,
"repo_name": "d0n0/Motion-Timeline",
"id": "46e78968a498a99241d9d72c179a7c61f02dc882",
"size": "2564",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/src/components/LoginForm.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "851"
},
{
"name": "HTML",
"bytes": "687"
},
{
"name": "JavaScript",
"bytes": "14452"
}
],
"symlink_target": ""
} |
package com.lcy.tomcat;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Locale;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
public class Response implements ServletResponse{
private static final int BUFFER_SIZE = 1024;
private Request request ;
private OutputStream os;
public Response(OutputStream os){
this.os = os;
}
public void setRequest(Request r){
request = r;
}
public void sendStaticResource() throws IOException{
String uri = request.getUri();
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fis = null;
File file = new File(HttpServer.WEB_ROOT + File.separator + uri);
try{
if(file.exists()){
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, BUFFER_SIZE);
while(ch != -1){
os.write(bytes, 0, ch);
ch = fis.read(bytes, 0, BUFFER_SIZE);
}
}else{
String errMessage = "HTTP/1.1 404 File Not Found\r\n"+
"Content-Type: text/html\r\n"+
"Content-Length: 27\r\n" +
"\r\n" +
"<h1>File Is Not Found</h1>";
os.write(errMessage.getBytes());
}
}catch(Exception e){
System.out.println(e.toString());
}finally{
if(fis != null){
fis.close();
}
}
}
@Override
public void flushBuffer() throws IOException {
// TODO Auto-generated method stub
}
@Override
public int getBufferSize() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getCharacterEncoding() {
// TODO Auto-generated method stub
return null;
}
@Override
public Locale getLocale() {
// TODO Auto-generated method stub
return null;
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(os, true);
}
@Override
public boolean isCommitted() {
// TODO Auto-generated method stub
return false;
}
@Override
public void reset() {
// TODO Auto-generated method stub
}
@Override
public void resetBuffer() {
// TODO Auto-generated method stub
}
@Override
public void setBufferSize(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void setContentLength(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void setContentType(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void setLocale(Locale arg0) {
// TODO Auto-generated method stub
}
}
| {
"content_hash": "efb0506d2994cdf19820b6206f610b87",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 67,
"avg_line_length": 20.865079365079364,
"alnum_prop": 0.6903765690376569,
"repo_name": "erdangjiade/studyTomcat",
"id": "97bbe453107c2ed8a8113c316daed60f1b982993",
"size": "2629",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "myTomcat/src/com/lcy/tomcat/Response.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1651"
},
{
"name": "Java",
"bytes": "182658"
}
],
"symlink_target": ""
} |
<?php
ini_set("display_errors", 1);
ini_set("error_reporting", E_ALL);
include_once("classes/btupload.php");
if($_POST['submit']) {
$btUploadObj = new BTUpload($_FILES['uploadfile'], "", "", array(".jpg", ".png", ".bmp", ".gif"));
if($btUploadObj->uploadFile()) {
echo "File Uploaded!";
}
else {
echo "Unable to upload file!";
}
echo "<br><br>";
print_r($_FILES);
echo "<br><br>";
}
echo "
<form action='tst.php' method='post' enctype='multipart/form-data'>
<input type='file' name='uploadfile'><br>
<input type='submit' name='submit' value='Upload'>
</form>
<br><br>
";
phpinfo();
?> | {
"content_hash": "481b09162172b5f392dc99f8f2e6a939",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 99,
"avg_line_length": 15.625,
"alnum_prop": 0.5888,
"repo_name": "bluethrust/cs4",
"id": "f9ff532b278c67ab15adc27d2284fa364b4ac13e",
"size": "625",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "classes/tst.php",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "700645"
},
{
"name": "JavaScript",
"bytes": "60297"
},
{
"name": "PHP",
"bytes": "4031302"
}
],
"symlink_target": ""
} |
#include "stdhdr.h"
#include "digi.h"
#include "simveh.h"
#include "aircrft.h"
#include "airframe.h"
#include "campbase.h"
#include "radar.h"
#include "Find.h" // 2002-03-11 MN
#include "Falclib/include/MsgInc/RadioChatterMsg.h" // MN
#include "Flight.h" // MN
#define SHOW_MANEUVERLABELS
#ifdef SHOW_MANEUVERLABELS
#include "Graphics/include/drawbsp.h"
#include "SimDrive.h"
extern int g_nShowDebugLabels;
extern int g_nAirbaseCheck;
extern float g_fBingoReturnDistance;
static const char *ATCModes[] = {
"noATC",
"lReqClearance",
"lReqEmerClearance",
"lIngressing",
"lTakingPosition",
"lAborted",
"lEmerHold",
"lHolding",
"lFirstLeg",
"lToBase",
"lToFinal",
"lOnFinal",
"lClearToLand",
"lLanded",
"TaxiOff",
"lEmergencyToBase",
"lEmergencyToFinal",
"lEmergencyOnFinal",
"lCrashed",
"tReqTaxi",
"tReqTakeoff",
"tEmerStop",
"tTaxi",
"tWait",
"tHoldShort",
"tPrepToTakeRunway",
"tTakeRunway",
"tTakeoff",
"tFlyOut",
"tTaxiBack",
};
static const int MAXATCSTATUS = sizeof(ATCModes) / sizeof(ATCModes[0]);
#endif
void DigitalBrain::Actions(void)
{
float cur;
RadarClass* theRadar = (RadarClass*) FindSensor (self, SensorClass::Radar);
#if 0 // test if each AGmission has a target waypoint
if (missionClass == AGMission)
{
Flight flight = (Flight)self->GetCampaignObject();
if (flight)
{
WayPoint w = flight->GetFirstUnitWP();
bool found = false;
while (w && !found)
{
if (w->GetWPFlags() & WPF_TARGET)
found = true;
w = w->GetNextWP();
}
if (!found)
{
char message[250];
sprintf(message,"Mission: %d doesn't have WPF_TARGET",flight->GetUnitMission());
F4Assert(!message);
}
}
}
#endif
AiMonitorTargets();
#ifdef SHOW_MANEUVERLABELS
char label[100];//cobra change from 40
#endif
// handle threat above all else
if ( threatPtr && curMode != TakeoffMode)
{
if ( curMode == MissileDefeatMode )
{
MissileDefeat();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"ThreatMissileDefeatMode");
#endif
}
else
{
HandleThreat();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"HandleThreatMode");
#endif
}
//tell atc we're going to ignore him
if(atcstatus != noATC)
{
ShiAssert(atcstatus < tReqTaxi);
SendATCMsg(noATC);
ResetATC();
}
}
/*-----------------------------------------------*/
/* stick/throttle commands based on current mode */
/*-----------------------------------------------*/
else
{
// Mode radar appropriately
if (curMode != WaypointMode && theRadar && theRadar->IsAG())
{
theRadar->SetMode (RadarClass::AA);
}
switch (curMode)
{
case FollowOrdersMode:
// edg double check groundAvoidNeeded if set -- could be stuck there
if ( groundAvoidNeeded )
GroundCheck();
AiPerformManeuver();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"FollowOrdersMode");
#endif
break;
case WingyMode:
// edg double check groundAvoidNeeded if set -- could be stuck there
if ( groundAvoidNeeded )
GroundCheck();
AiFollowLead();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"WingmanMode");
#endif
break;
case RefuelingMode:
// edg double check groundAvoidNeeded if set -- could be stuck there
if ( groundAvoidNeeded )
GroundCheck();
AiRefuel();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"RefuelingMode");
#endif
break;
/*------------------*/
/* follow waypoints */
/*------------------*/
// 2002-03-11 MN break up RTBMode and WaypointMode.
// RTBCheck: If we have said Fumes, check for closest airbase and head there instead towards home base...
// If not, continue to follow waypoints.
case RTBMode:
sprintf(label,"RTBMode");
FollowWaypoints();
break;
case WaypointMode:
sprintf(label,"WaypointMode");
FollowWaypoints();
break;
case LandingMode:
Land();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"Landing %s",
atcstatus >= 0 && atcstatus < MAXATCSTATUS ? ATCModes[atcstatus] : "");
#endif
break;
case TakeoffMode:
TakeOff();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"TakeOff %s",
atcstatus >= 0 && atcstatus < MAXATCSTATUS ? ATCModes[atcstatus] : "");
#endif
break;
/*------------*/
/* BVR engage */
/*------------*/
case BVREngageMode:
BvrEngage();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"BVREngagemode");
#endif
break;
/*------------*/
/* WVR engage */
/*------------*/
case WVREngageMode:
WvrEngage();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"WVREngagemode");
#endif
break;
case GunsEngageMode:
GunsEngage();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"GunsEngageMode");
#endif
break;
case MergeMode:
MergeManeuver();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"MergeMode");
#endif
break;
/*-----------------------------------------*/
/* Inside missile range, try to line it up */
/*-----------------------------------------*/
case MissileEngageMode:
MissileEngage();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"MissileEngageMode");
#endif
break;
/*----------------*/
/* missile defeat */
/*----------------*/
case MissileDefeatMode:
MissileDefeat();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"MissileDefeatMode");
#endif
break;
/*-----------*/
/* guns jink */
/*-----------*/
case GunsJinkMode:
GunsJink();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"GunsJinkMode");
#endif
break;
/*--------*/
/* loiter */
/*--------*/
case LoiterMode:
Loiter();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"LoiterMode");
#endif
break;
/*-----------------*/
/* collision avoid */
/*-----------------*/
case CollisionAvoidMode:
CollisionAvoid();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"CollisionAvoidMode");
#endif
break;
/*----------*/
/* Separate */
/*----------*/
case SeparateMode:
case BugoutMode:
if (lastMode != BugoutMode && lastMode != SeparateMode && targetPtr)
{
// 2001-10-28 CHANGED BACK M.N. holdAlt is used in AltitudeHold, which needs a positive value
// altitude error is calculated as holdAlt + self->ZPos() there !!!
// holdAlt = min (-5000.0F, self->ZPos());
//TJL 11/08/03 Hold position altitude but bug out
//holdAlt = min (5000.0F, -self->ZPos());
holdAlt = -self->ZPos();
// Find a heading directly away from the target
cur = TargetAz (self, targetPtr);
if (cur > 0.0F)
cur = self->Yaw() - (180.0F*DTR - cur);
else
cur = self->Yaw() - (-180.0F*DTR - cur);
// Normalize
if (cur > 180.0F * DTR)
cur -= 360.0F * DTR;
holdPsi = cur;
}
WvrBugOut();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"Separate/BugoutMode");
#endif
break;
/*-------------------*/
/* Roll Out of Plane */
/*-------------------*/
case RoopMode:
RollOutOfPlane();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"RollOutOfPlaneMode");
#endif
break;
/*-----------*/
/* Over Bank */
/*-----------*/
case OverBMode:
OverBank(30.0F*DTR);
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"OverBankMode");
#endif
break;
case AccelMode:
AccelManeuver();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"AccelerateMode");
#endif
break;
default:
SimLibPrintError("%s digi.w: Invalid digi mode %d\n",
self->Id().num_, curMode);
FollowWaypoints();
#ifdef SHOW_MANEUVERLABELS
sprintf(label,"InvalidDigiMode");
#endif
break;
} /*switch*/
}
#ifdef SHOW_MANEUVERLABELS
if (g_nShowDebugLabels & 0x01)
{
char element[40];
sprintf(element," %d%d W%d R%d V%d",isWing+1,SkillLevel(),detRWR, detRAD, detVIS);
strcat(label,element);
if (g_nShowDebugLabels & 0x40)
{
RadarClass* theRadar = (RadarClass*)FindSensor(self, SensorClass::Radar);
if (theRadar) {
if (theRadar->digiRadarMode = RadarClass::DigiSTT)
strcat(label, " STT");
else if (theRadar->digiRadarMode = RadarClass::DigiSAM)
strcat(label, " SAM");
else if (theRadar->digiRadarMode = RadarClass::DigiTWS)
strcat(label, " TWS");
else if (theRadar->digiRadarMode = RadarClass::DigiRWS)
strcat(label, " RWS");
else if (theRadar->digiRadarMode = RadarClass::DigiOFF)
strcat(label, " OFF");
else strcat(label, " UNKNOWN");
}
}
if (groundAvoidNeeded || pullupTimer)
strcat(label, " Pullup");
if (g_nShowDebugLabels & 0x8000)
{
if (((AircraftClass*) self)->af->GetSimpleMode())
strcat(label, " SIMP");
else
strcat(label, " COMP");
}
if (g_nShowDebugLabels & 0x1000)
{
if (SimDriver.GetPlayerEntity() && self->GetCampaignObject() && self->GetCampaignObject()->GetIdentified(SimDriver.GetPlayerEntity()->GetTeam()))
strcat(label, "IDed");
else
strcat(label, "Not IDed");
}
if ( self->drawPointer )
((DrawableBSP*)self->drawPointer)->SetLabel (label, ((DrawableBSP*)self->drawPointer)->LabelColor());
}
if (g_nShowDebugLabels & 0x200000)
{
sprintf(label,"%.0f %.0f %.0f",trackX, trackY, trackZ);
if ( self->drawPointer )
((DrawableBSP*)self->drawPointer)->SetLabel (label, ((DrawableBSP*)self->drawPointer)->LabelColor());
}
if (g_nShowDebugLabels & 0x100000)
{
float yaw = self->Yaw();
if (yaw < 0.0f)
yaw += 360.0F * DTR;
yaw *= RTD;
sprintf(label,"%4.0f %3.0f %6.2f %3.3f", self->af->vcas, yaw, -self->ZPos(), self->pctStrength* 100.0F);
if ( self->drawPointer )
((DrawableBSP*)self->drawPointer)->SetLabel (label, ((DrawableBSP*)self->drawPointer)->LabelColor());
}
if (g_nShowDebugLabels & 0x800000)
{
sprintf(label,"0x%x leader: 0x%x",self,flightLead);
if ( self->drawPointer )
((DrawableBSP*)self->drawPointer)->SetLabel (label, ((DrawableBSP*)self->drawPointer)->LabelColor());
}
#endif
// have we got a surprise for you!!
if ((targetPtr || threatPtr) && IsSetATC (HasTrainable) && self->HasPilot())
{
TrainableGunsEngage();
}
if (curMode > WVREngageMode)
engagementTimer = 0;
// if(isWing) {
// PrtMode();
// }
/*-----------------------------------------------------------------*/
/* Ground avoid now runs concurrently with whatever mode has been */
/* selected by the conflict resolver. Ground avoid modifies the */
/* current Pstick and Rstick commands. */
/*-----------------------------------------------------------------*/
// 2002-02-24 MN added pullupTimer - continue last calculated pullup for at least g_nPullupTime seconds
if (groundAvoidNeeded || pullupTimer) {
// 2001-10-21 MODIFIED by M.N.
/* if(((AircraftClass*) self)->af->GetSimpleMode()) {
SimplePullUp();
}
else { */
GroundCheck(); // Cobra - make sure max elev data is current
PullUp(); // let's forget SimplePullUp(); They just set pstick of 0.1f, which is WAY
// too little, the AI must fly into the hills. No more low-alt crashes with PullUp();
}
else
{
ResetMaxRoll();
SetMaxRollDelta(100.0F);
}
}
void DigitalBrain::AirbaseCheck()
{
bool nearestAirbase = false;
bool returnHomebase = false;
if (self->af->Fuel() <= 0.0F) // just float down and try to land - gear is out in that case
return;
GridIndex x,y;
float dist;
vector pos;
Objective obj = NULL;
if (airbasediverted == 1)
{
AddMode(RTBMode);
}
else if (airbasediverted == 2)
{
AddMode(LandingMode);
return;
}
// Only check every g_nAirbaseCheck seconds
if (nextFuelCheck > SimLibElapsedTime)
return;
nextFuelCheck = SimLibElapsedTime + g_nAirbaseCheck * CampaignSeconds;
// when on Bingo, check distance to closest airbase when not having a target and not being threatened
// return if distance is greater than g_fBingoReturnDistance
if (IsSetATC(SaidBingo) && !IsSetATC(SaidFumes) && !targetPtr && !threatPtr && !airbasediverted)
{
pos.x = self->XPos();
pos.y = self->YPos();
ConvertSimToGrid (&pos, &x, &y);
obj = FindNearestFriendlyAirbase (self->GetTeam(), x, y);
if (obj)
{
dist = Distance(self->XPos(), self->YPos(), obj->XPos(), obj->YPos());
if (dist > self->af->GetBingoReturnDistance() * NM_TO_FT)
{
returnHomebase = true;
airbasediverted = 1;
}
}
}
// 2002-03-13 modified by MN works together with checks in Separate.cpp, if 49.9% damage, head to hearest airbase instead of home base
if (IsSetATC(SaidFumes) || self->pctStrength < 0.50f) // when on fumes, force RTB to closest airbase
{
nearestAirbase = true;
airbasediverted = 2;
}
char label[32];
if (returnHomebase)
{
if (!(moreFlags & SaidImADot))
{
moreFlags |= SaidImADot;
int flightIdx = self->GetCampaignObject()->GetComponentIndex(self);
FalconRadioChatterMessage* radioMessage = new FalconRadioChatterMessage( self->Id(), FalconLocalSession );
radioMessage->dataBlock.from = self->Id();
radioMessage->dataBlock.to = MESSAGE_FOR_FLIGHT;
radioMessage->dataBlock.voice_id = ((Flight)(self->GetCampaignObject()))->GetPilotVoiceID(self->vehicleInUnit);
radioMessage->dataBlock.message = rcIMADOT;
radioMessage->dataBlock.edata[0] = (((FlightClass*)self->GetCampaignObject())->callsign_num);
radioMessage->dataBlock.time_to_play = 500; // 0.5 seconds
FalconSendMessage(radioMessage, FALSE);
}
AddMode(RTBMode); // changed from LandingMode to RTBMode
if (g_nShowDebugLabels & 0x40000)
{
sprintf(label,"RTB Homebase");
if ( self->drawPointer )
((DrawableBSP*)self->drawPointer)->SetLabel (label, ((DrawableBSP*)self->drawPointer)->LabelColor());
}
}
if (nearestAirbase)
{
pos.x = self->XPos();
pos.y = self->YPos();
ConvertSimToGrid (&pos, &x, &y);
// 2002-04-02 ADDED BY S.G. Since it's not done above anymore, do it here only if not done within 'SaidBingo' if statement above
if (!obj)
obj = FindNearestFriendlyAirbase (self->GetTeam(), x, y);
// END OF ADDED SECTION 2002-04-02
// change home base, of course only if it is another than our current one...
if(obj && obj->Id() != airbase)
{
airbase = obj->Id();
moreFlags |= NewHomebase; // set this so that ResetATC doesn't reset our new airbase
int flightIdx = self->GetCampaignObject()->GetComponentIndex(self);
FalconRadioChatterMessage* radioMessage = new FalconRadioChatterMessage( self->Id(), FalconLocalSession );
radioMessage->dataBlock.from = self->Id();
radioMessage->dataBlock.to = MESSAGE_FOR_FLIGHT;
radioMessage->dataBlock.voice_id = ((Flight)(self->GetCampaignObject()))->GetPilotVoiceID(self->vehicleInUnit);
radioMessage->dataBlock.message = rcALTLANDING;
radioMessage->dataBlock.edata[0] = ((FlightClass*)self->GetCampaignObject())->callsign_id;
radioMessage->dataBlock.edata[1] = (((FlightClass*)self->GetCampaignObject())->callsign_num - 1) * 4 + flightIdx + 1;
radioMessage->dataBlock.time_to_play = 500; // 0.5 seconds
FalconSendMessage(radioMessage, FALSE); mpActionFlags[AI_FOLLOW_FORMATION] = FALSE;
}
AddMode(LandingMode);
if (g_nShowDebugLabels & 0x40000)
{
sprintf(label,"RTB near ab, pct-Strgth: %1.2f",self->pctStrength);
if ( self->drawPointer )
((DrawableBSP*)self->drawPointer)->SetLabel (label, ((DrawableBSP*)self->drawPointer)->LabelColor());
}
}
} | {
"content_hash": "16e6a8d69d925253db4a8e55b2e2e64b",
"timestamp": "",
"source": "github",
"line_count": 572,
"max_line_length": 147,
"avg_line_length": 27.63986013986014,
"alnum_prop": 0.6075268817204301,
"repo_name": "markbb1957/FFalconSource",
"id": "6dac5d07da2a772e0d1045b398e0007ff3cf193e",
"size": "15810",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/sim/digi/actions.cpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "2185086"
},
{
"name": "C++",
"bytes": "21399641"
},
{
"name": "Objective-C",
"bytes": "351888"
}
],
"symlink_target": ""
} |
var SModule = require('./../SModule.js');
var inherits = require('inherits');
var smartresize = require('../../Smartresize.js');
var helper = require('../../Helper.js')();
var EventType = require('../../EventType.js');
module.exports = UISwitcherModule;
function UISwitcherModule(opts) {
var self = this; //things are gonna get nasty
if (!(this instanceof UISwitcherModule)) return new UISwitcherModule(opts);
opts = helper.extend({
name: 'UISwitcherModule',
id: 'UISwitcherModule'
}, opts);
/*CALL SUPERCLASS*/
SModule.call(this, opts);
this.parent = opts.parent; // where the controls will be displaye
return this;
}
inherits(UISwitcherModule, SModule);
UISwitcherModule.prototype.postInit = function() {
var self = this; //things are gonna get nasty
//this.win -- this.win.$title -- this.win.$content
this.win = this.createModalWindow(
'Mode switcher', // Title
{ //options
content: '<p style="font-size:0.8em">Click the button to switch between edit mode and view mode</p>', //html to be displayed
resizable: false,
modal: true,
width: 200,
height: 150,
position: {
top: '10px',
left: '70%'
}
},
this.parent); //parent div
var isEditMode = self.UIedit.parent().hasClass('active');
this.win.$content.append(($('<span>' + 'Switch to ' + '</span>')));
this.win.$content.append(
this.createButton(isEditMode ? 'VIEW' : 'EDIT',
function(btn, module) {
self.UIedit.parent().toggleClass("active");
self.UIview.parent().toggleClass("active");
$(btn).removeClass('red');
$(btn).removeClass('green');
btn.$text.html(self.UIedit.parent().hasClass('active') ? 'VIEW' : 'EDIT');
$(btn).addClass(self.UIedit.parent().hasClass('active') ? 'green' : 'red');
})
);
return this;
};
| {
"content_hash": "82c031a16c87632eba33ca0326778d39",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 136,
"avg_line_length": 35.6140350877193,
"alnum_prop": 0.5729064039408867,
"repo_name": "gurbano/fuzzy-octo-location",
"id": "6f85a326f665ae863764e420b97b292db051ddc2",
"size": "2030",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/js/storify/modules/UI/UIswitcher.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "335016"
},
{
"name": "JavaScript",
"bytes": "765663"
},
{
"name": "Shell",
"bytes": "425"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/AndroidServicesHomework.iml" filepath="$PROJECT_DIR$/AndroidServicesHomework.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
</modules>
</component>
</project> | {
"content_hash": "086da12d1f3a01f563105296e4101f79",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 128,
"avg_line_length": 42.55555555555556,
"alnum_prop": 0.6840731070496083,
"repo_name": "waiting4tzeentch/AndroidServicesHomework",
"id": "296f1841712f0903bd1774ec1d92c5ac8303d38d",
"size": "383",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/modules.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "3031"
}
],
"symlink_target": ""
} |
namespace peloton {
namespace stats {
StatsAggregator::StatsAggregator(int64_t aggregation_interval_ms)
: stats_history_(0, false),
aggregated_stats_(LATENCY_MAX_HISTORY_AGGREGATOR, false),
aggregation_interval_ms_(aggregation_interval_ms),
thread_number_(0),
total_prev_txn_committed_(0) {
pool_.reset(new type::EphemeralPool());
try {
ofs_.open(peloton_stats_directory_, std::ofstream::out);
} catch (std::ofstream::failure &e) {
LOG_ERROR("Couldn't open the stats log file %s", e.what());
}
LaunchAggregator();
}
StatsAggregator::~StatsAggregator() {
LOG_DEBUG("StatsAggregator destruction");
ShutdownAggregator();
try {
ofs_.close();
} catch (std::ofstream::failure &e) {
LOG_ERROR("Couldn't close the stats log file %s", e.what());
}
}
void StatsAggregator::LaunchAggregator() {
if (!is_aggregating_) {
aggregator_thread_ = std::thread(&StatsAggregator::RunAggregator, this);
is_aggregating_ = true;
}
}
void StatsAggregator::ShutdownAggregator() {
if (is_aggregating_) {
is_aggregating_ = false;
exec_finished_.notify_one();
LOG_DEBUG("notifying aggregator thread...");
aggregator_thread_.join();
LOG_DEBUG("aggregator thread joined");
}
}
void StatsAggregator::Aggregate(int64_t &interval_cnt, double &alpha,
double &weighted_avg_throughput) {
interval_cnt++;
LOG_TRACE(
"\n//////////////////////////////////////////////////////"
"//////////////////////////////////////////////////////\n");
LOG_TRACE("TIME ELAPSED: %ld sec", interval_cnt);
aggregated_stats_.Reset();
std::thread::id this_id = aggregator_thread_.get_id();
for (auto &val : backend_stats_) {
// Exclude the txn stats generated by the aggregator thread
if (val.first != this_id) {
aggregated_stats_.Aggregate((*val.second));
}
}
aggregated_stats_.Aggregate(stats_history_);
LOG_TRACE("%s\n", aggregated_stats_.ToString().c_str());
int64_t current_txns_committed = 0;
// Traverse the metric of all threads to get the total number of committed
// txns.
for (auto &database_item : aggregated_stats_.database_metrics_) {
current_txns_committed +=
database_item.second->GetTxnCommitted().GetCounter();
}
int64_t txns_committed_this_interval =
current_txns_committed - total_prev_txn_committed_;
double throughput_ = (double)txns_committed_this_interval / 1000 *
STATS_AGGREGATION_INTERVAL_MS;
double avg_throughput_ = (double)current_txns_committed / interval_cnt /
STATS_AGGREGATION_INTERVAL_MS * 1000;
if (interval_cnt == 1) {
weighted_avg_throughput = throughput_;
} else {
weighted_avg_throughput =
alpha * throughput_ + (1 - alpha) * weighted_avg_throughput;
}
total_prev_txn_committed_ = current_txns_committed;
LOG_TRACE("Average throughput: %lf txn/s", avg_throughput_);
LOG_TRACE("Moving avg. throughput: %lf txn/s", weighted_avg_throughput);
LOG_TRACE("Current throughput: %lf txn/s", throughput_);
// Write the stats to metric tables
UpdateMetrics();
if (interval_cnt % STATS_LOG_INTERVALS == 0) {
try {
ofs_ << "At interval: " << interval_cnt << std::endl;
ofs_ << aggregated_stats_.ToString();
ofs_ << "Weighted avg. throughput=" << weighted_avg_throughput
<< std::endl;
ofs_ << "Average throughput=" << avg_throughput_ << std::endl;
ofs_ << "Current throughput=" << throughput_;
} catch (std::ofstream::failure &e) {
LOG_ERROR("Error when writing to the stats log file %s", e.what());
}
}
}
void StatsAggregator::UpdateQueryMetrics(int64_t time_stamp,
concurrency::Transaction *txn) {
// Get the target query metrics table
LOG_TRACE("Inserting Query Metric Tuples");
// auto query_metrics_table = GetMetricTable(QUERY_METRIC_NAME);
std::shared_ptr<QueryMetric> query_metric;
auto &completed_query_metrics = aggregated_stats_.GetCompletedQueryMetrics();
while (completed_query_metrics.Dequeue(query_metric)) {
// Get physical stats
auto table_access = query_metric->GetQueryAccess();
auto reads = table_access.GetReads();
auto updates = table_access.GetUpdates();
auto deletes = table_access.GetDeletes();
auto inserts = table_access.GetInserts();
auto latency = query_metric->GetQueryLatency().GetFirstLatencyValue();
auto cpu_system = query_metric->GetProcessorMetric().GetSystemDuration();
auto cpu_user = query_metric->GetProcessorMetric().GetUserDuration();
// Get query params
auto query_params = query_metric->GetQueryParams();
auto num_params = 0;
QueryMetric::QueryParamBuf value_buf;
QueryMetric::QueryParamBuf type_buf;
QueryMetric::QueryParamBuf format_buf;
if (query_params != nullptr) {
value_buf = query_params->val_buf_copy;
num_params = query_params->num_params;
format_buf = query_params->format_buf_copy;
type_buf = query_params->type_buf_copy;
PL_ASSERT(num_params > 0);
}
// Generate and insert the tuple
// auto query_tuple = catalog::GetQueryMetricsCatalogTuple(
// query_metrics_table->GetSchema(), query_metric->GetName(),
// query_metric->GetDatabaseId(), num_params, type_buf, format_buf,
// value_buf, reads, updates, deletes, inserts, (int64_t)latency,
// (int64_t)(cpu_system + cpu_user), time_stamp, pool_.get());
// catalog::InsertTuple(query_metrics_table, std::move(query_tuple), txn);
catalog::QueryMetricsCatalog::GetInstance()->InsertQueryMetrics(
query_metric->GetName(), query_metric->GetDatabaseId(), num_params,
type_buf, format_buf, value_buf, reads, updates, deletes, inserts,
(int64_t)latency, (int64_t)(cpu_system + cpu_user), time_stamp,
pool_.get(), txn);
LOG_TRACE("Query Metric Tuple inserted");
}
}
void StatsAggregator::UpdateMetrics() {
// All tuples are inserted in a single txn
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
// Get the target table metrics table
LOG_TRACE("Inserting stat tuples into catalog database..");
auto storage_manager = storage::StorageManager::GetInstance();
auto time_since_epoch = std::chrono::system_clock::now().time_since_epoch();
auto time_stamp = std::chrono::duration_cast<std::chrono::seconds>(
time_since_epoch).count();
auto database_count = storage_manager->GetDatabaseCount();
for (oid_t database_offset = 0; database_offset < database_count;
database_offset++) {
auto database = storage_manager->GetDatabaseWithOffset(database_offset);
// Update database metrics table
auto database_oid = database->GetOid();
auto database_metric = aggregated_stats_.GetDatabaseMetric(database_oid);
auto txn_committed = database_metric->GetTxnCommitted().GetCounter();
auto txn_aborted = database_metric->GetTxnAborted().GetCounter();
catalog::DatabaseMetricsCatalog::GetInstance()->InsertDatabaseMetrics(
database_oid, txn_committed, txn_aborted, time_stamp, pool_.get(), txn);
LOG_TRACE("DB Metric Tuple inserted");
// Update all the indices of this database
UpdateTableMetrics(database, time_stamp, txn);
}
// Update all query metrics
UpdateQueryMetrics(time_stamp, txn);
txn_manager.CommitTransaction(txn);
}
void StatsAggregator::UpdateTableMetrics(storage::Database *database,
int64_t time_stamp,
concurrency::Transaction *txn) {
// Update table metrics table for each of the indices
auto database_oid = database->GetOid();
auto table_count = database->GetTableCount();
for (oid_t table_offset = 0; table_offset < table_count; table_offset++) {
auto table = database->GetTable(table_offset);
auto table_oid = table->GetOid();
auto table_metrics =
aggregated_stats_.GetTableMetric(database_oid, table_oid);
auto table_access = table_metrics->GetTableAccess();
auto reads = table_access.GetReads();
auto updates = table_access.GetUpdates();
auto deletes = table_access.GetDeletes();
auto inserts = table_access.GetInserts();
catalog::TableMetricsCatalog::GetInstance()->InsertTableMetrics(
database_oid, table_oid, reads, updates, deletes, inserts, time_stamp,
pool_.get(), txn);
LOG_TRACE("Table Metric Tuple inserted");
UpdateIndexMetrics(database, table, time_stamp, txn);
}
}
void StatsAggregator::UpdateIndexMetrics(storage::Database *database,
storage::DataTable *table,
int64_t time_stamp,
concurrency::Transaction *txn) {
// Update index metrics table for each of the indices
auto database_oid = database->GetOid();
auto table_oid = table->GetOid();
auto index_count = table->GetIndexCount();
for (oid_t index_offset = 0; index_offset < index_count; index_offset++) {
auto index = table->GetIndex(index_offset);
if (index == nullptr) continue;
auto index_oid = index->GetOid();
auto index_metric =
aggregated_stats_.GetIndexMetric(database_oid, table_oid, index_oid);
auto index_access = index_metric->GetIndexAccess();
auto reads = index_access.GetReads();
auto deletes = index_access.GetDeletes();
auto inserts = index_access.GetInserts();
catalog::IndexMetricsCatalog::GetInstance()->InsertIndexMetrics(
database_oid, table_oid, index_oid, reads, deletes, inserts, time_stamp,
pool_.get(), txn);
}
}
void StatsAggregator::RunAggregator() {
LOG_DEBUG("Aggregator is now running.");
std::mutex mtx;
std::unique_lock<std::mutex> lck(mtx);
int64_t interval_cnt = 0;
double alpha = 0.4;
double weighted_avg_throughput = 0.0;
while (exec_finished_.wait_for(
lck, std::chrono::milliseconds(aggregation_interval_ms_)) ==
std::cv_status::timeout &&
is_aggregating_) {
Aggregate(interval_cnt, alpha, weighted_avg_throughput);
}
LOG_DEBUG("Aggregator done!");
}
StatsAggregator &StatsAggregator::GetInstance(int64_t aggregation_interval_ms) {
static StatsAggregator stats_aggregator(aggregation_interval_ms);
return stats_aggregator;
}
//===--------------------------------------------------------------------===//
// HELPER FUNCTIONS
//===--------------------------------------------------------------------===//
// Register the BackendStatsContext of a worker thread to global Stats
// Aggregator
void StatsAggregator::RegisterContext(std::thread::id id_,
BackendStatsContext *context_) {
{
std::lock_guard<std::mutex> lock(stats_mutex_);
PL_ASSERT(backend_stats_.find(id_) == backend_stats_.end());
thread_number_++;
backend_stats_[id_] = context_;
}
LOG_DEBUG("Stats aggregator hash map size: %ld", backend_stats_.size());
}
// Unregister a BackendStatsContext. Currently we directly reuse the thread id
// instead of explicitly unregistering it.
void StatsAggregator::UnregisterContext(std::thread::id id) {
{
std::lock_guard<std::mutex> lock(stats_mutex_);
if (backend_stats_.find(id) != backend_stats_.end()) {
stats_history_.Aggregate(*backend_stats_[id]);
backend_stats_.erase(id);
thread_number_--;
} else {
LOG_DEBUG("stats_context already deleted!");
}
}
}
storage::DataTable *StatsAggregator::GetMetricTable(std::string table_name) {
auto storage_manager = storage::StorageManager::GetInstance();
PL_ASSERT(storage_manager->GetDatabaseCount() > 0);
storage::Database *catalog_database =
storage_manager->GetDatabaseWithOid(CATALOG_DATABASE_OID);
PL_ASSERT(catalog_database != nullptr);
auto metrics_table = catalog_database->GetTableWithName(table_name);
PL_ASSERT(metrics_table != nullptr);
return metrics_table;
}
} // namespace stats
} // namespace peloton
| {
"content_hash": "719d6146e4cf7df4a9fdb399bf96bd0e",
"timestamp": "",
"source": "github",
"line_count": 319,
"max_line_length": 80,
"avg_line_length": 37.94984326018809,
"alnum_prop": 0.6500908640343631,
"repo_name": "prashasthip/peloton",
"id": "dfc964f5fa00886402864879e0b73d95030fc115",
"size": "12836",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/statistics/stats_aggregator.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "44625"
},
{
"name": "C++",
"bytes": "5767040"
},
{
"name": "CMake",
"bytes": "109338"
},
{
"name": "Java",
"bytes": "44640"
},
{
"name": "Objective-C",
"bytes": "4030"
},
{
"name": "PLpgSQL",
"bytes": "5855"
},
{
"name": "Python",
"bytes": "63317"
},
{
"name": "Ruby",
"bytes": "1310"
},
{
"name": "Shell",
"bytes": "14149"
}
],
"symlink_target": ""
} |
export const noop = () => {};
export interface AddressModeLogic {
BLOCK_COUNT: number;
SEP: string;
RE_CHAR: RegExp;
RE_BLOCK: RegExp[];
blocks: () => string[];
fromBlocks: (blocks: string[], sep?: string) => string;
split: (value: string, sep?: string, throwError?: boolean) => string[];
isValid: (blocks: string[]) => boolean;
isMaxLen: (value: string) => boolean;
}
const V4_BLOCK_RE = /^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$/;
export const v4: AddressModeLogic = {
BLOCK_COUNT: 4,
SEP: '.',
RE_CHAR: /^[0-9]$/,
RE_BLOCK: [V4_BLOCK_RE, V4_BLOCK_RE, V4_BLOCK_RE, V4_BLOCK_RE],
blocks(): string[] { return ['', '' , '', '']; },
fromBlocks(blocks: string[], sep: string = v4.SEP): string {
return blocks.join(sep);
},
split(value: string, sep: string = v4.SEP, throwError: boolean = false): string[] {
if (!value) {
return v4.blocks();
}
const result = value.split(sep);
if (throwError && result.length !== v4.BLOCK_COUNT ) {
throw new Error('Invalid IPV4');
}
return result;
},
isValid(blocks: string[]): boolean {
return blocks.every(value => parseInt(value, 10) >= 0 && parseInt(value, 10) <= 255);
},
isMaxLen(value: string): boolean {
if (value.length === 3) {
return true;
} else if (value.length === 2 && parseInt(value, 10) > 25) {
return true;
} else {
return false;
}
}
};
export const v4WithMask: AddressModeLogic = Object.assign(Object.create(v4), {
BLOCK_COUNT: 5,
RE_BLOCK: v4.RE_BLOCK.concat([/^([0-2]?[0-9]|30)$/]),
blocks(): string[] { return ['', '' , '', '', '']; },
fromBlocks(blocks: string[], sep: string = v4.SEP): string {
return blocks.slice(0, 4).join(sep) + `/${blocks[4]}`;
},
split(value: string, sep: string = v4.SEP, throwError: boolean = false): string[] {
if (!value) {
return v4WithMask.blocks();
}
const result = value.split(sep);
result.push(...result.pop().split('/'));
if (throwError && result.length !== v4WithMask.BLOCK_COUNT ) {
throw new Error('Invalid IPV4 with Mask');
}
return result;
},
isValid(blocks: string[]): boolean {
for (let i = 0; i < 4; i++) {
const value = parseInt(blocks[i], 10);
if ( !(value >= 0 && value <= 255) ) {
return false;
}
}
const value = parseInt(blocks[4], 10);
return value >= 0 && value <= 30;
},
isMaxLen(value: string): boolean {
if (value.length === 3) {
return true;
} else if (value.length === 2 && parseInt(value, 10) > 25) {
return true;
} else {
return false;
}
}
});
const V6_BLOCK_RE = /^[0-9A-Fa-f]{0,4}$/;
export const v6: AddressModeLogic = {
BLOCK_COUNT: 8,
SEP: ':',
RE_CHAR: /^[0-9A-Fa-f]$/,
RE_BLOCK: v4.RE_BLOCK.map( s => V6_BLOCK_RE).concat(v4.RE_BLOCK.map( s => V6_BLOCK_RE)),
blocks(): string[] { return v4.blocks().concat(v4.blocks()); },
fromBlocks(blocks: string[], sep: string = v6.SEP): string {
return blocks.map(value => value ? value : '0000').join(sep);
},
split(value: string, sep: string = v6.SEP, throwError: boolean = false): string[] {
if (!value) {
return v6.blocks();
}
const consecutiveSplit = value.split(sep + sep);
const result: string[] = consecutiveSplit[0].split(sep);
if (consecutiveSplit.length === 2) {
// if :: is used we need to calculate the amount of empty blocks.
// - Get the right parts (left is already the result)
// - find how much blocks are missing to reach total of 8.
// - fill the empty blocks and append right part.
let rightPart = consecutiveSplit[1].split(sep);
let emptySpaces = v6.BLOCK_COUNT - (result.length + rightPart.length);
result.splice(result.length, 0, ...v6.blocks().slice(0, emptySpaces));
result.splice(result.length, 0, ...rightPart);
}
// consecutive :: allowed once.
if (throwError && (consecutiveSplit.length > 2 || result.length !== v6.BLOCK_COUNT) ) {
throw new Error('Invalid IPV6');
}
return result;
},
isValid(blocks: string[]): boolean {
return blocks.every(value => V6_BLOCK_RE.test(value)) && blocks.some(value => !!value)
},
isMaxLen(value: string): boolean {
return value.length === 4;
}
};
const MAC_BLOCK_RE = /^[0-9A-Fa-f]{1,2}$/;
export const mac: AddressModeLogic = Object.assign(Object.create(v6), {
BLOCK_MAX_LEN: 2,
BLOCK_COUNT: 6,
RE_BLOCK: v4.RE_BLOCK.map( s => MAC_BLOCK_RE).concat([MAC_BLOCK_RE, MAC_BLOCK_RE]),
blocks(): string[] { return ['', '' , '', '', '', '']; },
fromBlocks(blocks: string[], sep: string = mac.SEP): string {
return blocks.join(sep);
},
split(value: string, sep: string = mac.SEP, throwError: boolean = false): string[] {
if (!value) {
return mac.blocks();
}
const result = value.split(sep);
if ( throwError && result.length !== mac.BLOCK_COUNT ) {
throw new Error('Invalid MAC address');
}
return result;
},
isValid(blocks: string[]): boolean {
return blocks.every(value => MAC_BLOCK_RE.test(value)) && blocks.some(value => !!value);
},
isMaxLen(value: string): boolean {
return value.length === 2;
}
});
export const inputSelection = {
/**
* Given an input element, insert the supplied value at the caret position.
* If some (or all) of the text is selected, replaces the selection with the value.
* In case the input is falsy returns the value. (universal)
* @param input
* @param value
*/
insert(input: HTMLInputElement, value: string): string {
return input
? input.value.substr(0, input.selectionStart) + value + input.value.substr(input.selectionEnd)
: value
;
},
caretIsLast(input: HTMLInputElement): boolean {
return input
? input.selectionStart === input.selectionEnd && input.selectionStart === input.value.length
: false
;
},
/**
* Returns true if some (or all) of the text is selected
* @param input
*/
some(input: HTMLInputElement): boolean {
return input.selectionStart > input.selectionEnd;
},
/**
* Returns true if the whole text is selected
* @param input
*/
all(input: HTMLInputElement): boolean {
return input.selectionStart === 0 && input.selectionEnd === input.value.length;
}
};
// https://github.com/angular/material2/blob/master/src/cdk/coercion/boolean-property.ts
export function coerceBooleanProperty(value: any): boolean {
return value != null && `${value}` !== 'false';
}
| {
"content_hash": "fc4a0280dc05a46716b3d35e926b8380",
"timestamp": "",
"source": "github",
"line_count": 202,
"max_line_length": 100,
"avg_line_length": 32.21287128712871,
"alnum_prop": 0.6044260027662517,
"repo_name": "shlomiassaf/ng2-ip",
"id": "417c13aa135403b888d8ced3d42f6e90e03dd825",
"size": "6507",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/ngx-ip/src/utils.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2600"
},
{
"name": "HTML",
"bytes": "9209"
},
{
"name": "JavaScript",
"bytes": "49317"
},
{
"name": "Shell",
"bytes": "698"
},
{
"name": "TypeScript",
"bytes": "31006"
}
],
"symlink_target": ""
} |
package org.diirt.util.stats;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.diirt.util.array.ArrayDouble;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
/**
*
* @author carcassi
*/
public class StatisticsUtilTest {
@Test
public void statisticsOf1() {
Statistics stats = StatisticsUtil.statisticsOf(new ArrayDouble(1.0));
assertThat(stats.getAverage(), equalTo(1.0));
assertThat(stats.getStdDev(), equalTo(0.0));
assertThat(stats.getRange().getMinimum(), equalTo(1.0));
assertThat(stats.getRange().getMaximum(), equalTo(1.0));
assertThat(stats.getCount(), equalTo(1));
}
@Test
public void statisticsOf2() {
Statistics stats = StatisticsUtil.statisticsOf(new ArrayDouble(1, 3, 5, -1, 7));
assertThat(stats.getAverage(), equalTo(3.0));
assertThat(stats.getStdDev(), equalTo(2.8284271247461903));
assertThat(stats.getRange().getMinimum(), equalTo(-1.0));
assertThat(stats.getRange().getMaximum(), equalTo(7.0));
assertThat(stats.getCount(), equalTo(5));
}
@Test
public void statisticsOf3() {
List<Statistics> list = new ArrayList<Statistics>();
for (int i = 0; i < 10; i++) {
list.add(StatisticsUtil.statisticsOf(new ArrayDouble(i)));
}
Statistics stats = StatisticsUtil.statisticsOf(list);
assertThat(stats.getAverage(), equalTo(4.5));
assertThat(stats.getStdDev(), equalTo(2.8722813232690143));
assertThat(stats.getRange().getMinimum(), equalTo(0.0));
assertThat(stats.getRange().getMaximum(), equalTo(9.0));
assertThat(stats.getCount(), equalTo(10));
}
@Test
public void statisticsOf4() {
Statistics stats = StatisticsUtil.statisticsOf(new ArrayDouble(1, 3, 5, Double.NaN, -1, 7));
assertThat(stats.getAverage(), equalTo(3.0));
assertThat(stats.getStdDev(), equalTo(2.8284271247461903));
assertThat(stats.getRange().getMinimum(), equalTo(-1.0));
assertThat(stats.getRange().getMaximum(), equalTo(7.0));
assertThat(stats.getCount(), equalTo(5));
}
@Test
public void statisticsOf5() {
Statistics stats = StatisticsUtil.statisticsOf(new ArrayDouble(1, 3, 5, -1, 7));
stats = StatisticsUtil.statisticsOf(Arrays.asList(stats));
assertThat(stats.getAverage(), equalTo(3.0));
assertThat(stats.getStdDev(), equalTo(2.8284271247461903));
assertThat(stats.getRange().getMinimum(), equalTo(-1.0));
assertThat(stats.getRange().getMaximum(), equalTo(7.0));
assertThat(stats.getCount(), equalTo(5));
}
}
| {
"content_hash": "b7f6c47c305a65ef8e08fbadb061c6e9",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 100,
"avg_line_length": 37.794520547945204,
"alnum_prop": 0.6473359913011961,
"repo_name": "richardfearn/diirt",
"id": "f3725cd20d1615b87ac3928645961304efbeb96a",
"size": "2900",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "util/src/test/java/org/diirt/util/stats/StatisticsUtilTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "74191"
},
{
"name": "GAP",
"bytes": "6519"
},
{
"name": "Java",
"bytes": "4176965"
},
{
"name": "JavaScript",
"bytes": "1716484"
},
{
"name": "Shell",
"bytes": "3421"
}
],
"symlink_target": ""
} |
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: soc2013/dpl/head/sys/cam/scsi/scsi_targ_bh.c 230279 2012-01-12 00:34:33Z ken $");
#include <sys/param.h>
#include <sys/queue.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/types.h>
#include <sys/bio.h>
#include <sys/conf.h>
#include <sys/devicestat.h>
#include <sys/malloc.h>
#include <sys/uio.h>
#include <cam/cam.h>
#include <cam/cam_ccb.h>
#include <cam/cam_periph.h>
#include <cam/cam_queue.h>
#include <cam/cam_xpt_periph.h>
#include <cam/cam_debug.h>
#include <cam/cam_sim.h>
#include <cam/scsi/scsi_all.h>
#include <cam/scsi/scsi_message.h>
static MALLOC_DEFINE(M_SCSIBH, "SCSI bh", "SCSI blackhole buffers");
typedef enum {
TARGBH_STATE_NORMAL,
TARGBH_STATE_EXCEPTION,
TARGBH_STATE_TEARDOWN
} targbh_state;
typedef enum {
TARGBH_FLAG_NONE = 0x00,
TARGBH_FLAG_LUN_ENABLED = 0x01
} targbh_flags;
typedef enum {
TARGBH_CCB_WORKQ,
TARGBH_CCB_WAITING
} targbh_ccb_types;
#define MAX_ACCEPT 8
#define MAX_IMMEDIATE 16
#define MAX_BUF_SIZE 256 /* Max inquiry/sense/mode page transfer */
/* Offsets into our private CCB area for storing accept information */
#define ccb_type ppriv_field0
#define ccb_descr ppriv_ptr1
/* We stick a pointer to the originating accept TIO in each continue I/O CCB */
#define ccb_atio ppriv_ptr1
TAILQ_HEAD(ccb_queue, ccb_hdr);
struct targbh_softc {
struct ccb_queue pending_queue;
struct ccb_queue work_queue;
struct ccb_queue unknown_atio_queue;
struct devstat device_stats;
targbh_state state;
targbh_flags flags;
u_int init_level;
u_int inq_data_len;
struct ccb_accept_tio *accept_tio_list;
struct ccb_hdr_slist immed_notify_slist;
};
struct targbh_cmd_desc {
struct ccb_accept_tio* atio_link;
u_int data_resid; /* How much left to transfer */
u_int data_increment;/* Amount to send before next disconnect */
void* data; /* The data. Can be from backing_store or not */
void* backing_store;/* Backing store allocated for this descriptor*/
u_int max_size; /* Size of backing_store */
u_int32_t timeout;
u_int8_t status; /* Status to return to initiator */
};
static struct scsi_inquiry_data no_lun_inq_data =
{
T_NODEVICE | (SID_QUAL_BAD_LU << 5), 0,
/* version */2, /* format version */2
};
static struct scsi_sense_data_fixed no_lun_sense_data =
{
SSD_CURRENT_ERROR|SSD_ERRCODE_VALID,
0,
SSD_KEY_NOT_READY,
{ 0, 0, 0, 0 },
/*extra_len*/offsetof(struct scsi_sense_data_fixed, fru)
- offsetof(struct scsi_sense_data_fixed, extra_len),
{ 0, 0, 0, 0 },
/* Logical Unit Not Supported */
/*ASC*/0x25, /*ASCQ*/0
};
static const int request_sense_size = offsetof(struct scsi_sense_data_fixed, fru);
static periph_init_t targbhinit;
static void targbhasync(void *callback_arg, u_int32_t code,
struct cam_path *path, void *arg);
static cam_status targbhenlun(struct cam_periph *periph);
static cam_status targbhdislun(struct cam_periph *periph);
static periph_ctor_t targbhctor;
static periph_dtor_t targbhdtor;
static periph_start_t targbhstart;
static void targbhdone(struct cam_periph *periph,
union ccb *done_ccb);
#ifdef NOTYET
static int targbherror(union ccb *ccb, u_int32_t cam_flags,
u_int32_t sense_flags);
#endif
static struct targbh_cmd_desc* targbhallocdescr(void);
static void targbhfreedescr(struct targbh_cmd_desc *buf);
static struct periph_driver targbhdriver =
{
targbhinit, "targbh",
TAILQ_HEAD_INITIALIZER(targbhdriver.units), /* generation */ 0
};
PERIPHDRIVER_DECLARE(targbh, targbhdriver);
static void
targbhinit(void)
{
cam_status status;
/*
* Install a global async callback. This callback will
* receive async callbacks like "new path registered".
*/
status = xpt_register_async(AC_PATH_REGISTERED | AC_PATH_DEREGISTERED,
targbhasync, NULL, NULL);
if (status != CAM_REQ_CMP) {
printf("targbh: Failed to attach master async callback "
"due to status 0x%x!\n", status);
}
}
static void
targbhasync(void *callback_arg, u_int32_t code,
struct cam_path *path, void *arg)
{
struct cam_path *new_path;
struct ccb_pathinq *cpi;
path_id_t bus_path_id;
cam_status status;
cpi = (struct ccb_pathinq *)arg;
if (code == AC_PATH_REGISTERED)
bus_path_id = cpi->ccb_h.path_id;
else
bus_path_id = xpt_path_path_id(path);
/*
* Allocate a peripheral instance for
* this target instance.
*/
status = xpt_create_path(&new_path, NULL,
bus_path_id,
CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
if (status != CAM_REQ_CMP) {
printf("targbhasync: Unable to create path "
"due to status 0x%x\n", status);
return;
}
switch (code) {
case AC_PATH_REGISTERED:
{
/* Only attach to controllers that support target mode */
if ((cpi->target_sprt & PIT_PROCESSOR) == 0)
break;
status = cam_periph_alloc(targbhctor, NULL, targbhdtor,
targbhstart,
"targbh", CAM_PERIPH_BIO,
new_path, targbhasync,
AC_PATH_REGISTERED,
cpi);
break;
}
case AC_PATH_DEREGISTERED:
{
struct cam_periph *periph;
if ((periph = cam_periph_find(new_path, "targbh")) != NULL)
cam_periph_invalidate(periph);
break;
}
default:
break;
}
xpt_free_path(new_path);
}
/* Attempt to enable our lun */
static cam_status
targbhenlun(struct cam_periph *periph)
{
union ccb immed_ccb;
struct targbh_softc *softc;
cam_status status;
int i;
softc = (struct targbh_softc *)periph->softc;
if ((softc->flags & TARGBH_FLAG_LUN_ENABLED) != 0)
return (CAM_REQ_CMP);
xpt_setup_ccb(&immed_ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
immed_ccb.ccb_h.func_code = XPT_EN_LUN;
/* Don't need support for any vendor specific commands */
immed_ccb.cel.grp6_len = 0;
immed_ccb.cel.grp7_len = 0;
immed_ccb.cel.enable = 1;
xpt_action(&immed_ccb);
status = immed_ccb.ccb_h.status;
if (status != CAM_REQ_CMP) {
xpt_print(periph->path,
"targbhenlun - Enable Lun Rejected with status 0x%x\n",
status);
return (status);
}
softc->flags |= TARGBH_FLAG_LUN_ENABLED;
/*
* Build up a buffer of accept target I/O
* operations for incoming selections.
*/
for (i = 0; i < MAX_ACCEPT; i++) {
struct ccb_accept_tio *atio;
atio = (struct ccb_accept_tio*)malloc(sizeof(*atio), M_SCSIBH,
M_NOWAIT);
if (atio == NULL) {
status = CAM_RESRC_UNAVAIL;
break;
}
atio->ccb_h.ccb_descr = targbhallocdescr();
if (atio->ccb_h.ccb_descr == NULL) {
free(atio, M_SCSIBH);
status = CAM_RESRC_UNAVAIL;
break;
}
xpt_setup_ccb(&atio->ccb_h, periph->path, CAM_PRIORITY_NORMAL);
atio->ccb_h.func_code = XPT_ACCEPT_TARGET_IO;
atio->ccb_h.cbfcnp = targbhdone;
xpt_action((union ccb *)atio);
status = atio->ccb_h.status;
if (status != CAM_REQ_INPROG) {
targbhfreedescr(atio->ccb_h.ccb_descr);
free(atio, M_SCSIBH);
break;
}
((struct targbh_cmd_desc*)atio->ccb_h.ccb_descr)->atio_link =
softc->accept_tio_list;
softc->accept_tio_list = atio;
}
if (i == 0) {
xpt_print(periph->path,
"targbhenlun - Could not allocate accept tio CCBs: status "
"= 0x%x\n", status);
targbhdislun(periph);
return (CAM_REQ_CMP_ERR);
}
/*
* Build up a buffer of immediate notify CCBs
* so the SIM can tell us of asynchronous target mode events.
*/
for (i = 0; i < MAX_ACCEPT; i++) {
struct ccb_immed_notify *inot;
inot = (struct ccb_immed_notify*)malloc(sizeof(*inot), M_SCSIBH,
M_NOWAIT);
if (inot == NULL) {
status = CAM_RESRC_UNAVAIL;
break;
}
xpt_setup_ccb(&inot->ccb_h, periph->path, CAM_PRIORITY_NORMAL);
inot->ccb_h.func_code = XPT_IMMED_NOTIFY;
inot->ccb_h.cbfcnp = targbhdone;
xpt_action((union ccb *)inot);
status = inot->ccb_h.status;
if (status != CAM_REQ_INPROG) {
free(inot, M_SCSIBH);
break;
}
SLIST_INSERT_HEAD(&softc->immed_notify_slist, &inot->ccb_h,
periph_links.sle);
}
if (i == 0) {
xpt_print(periph->path,
"targbhenlun - Could not allocate immediate notify "
"CCBs: status = 0x%x\n", status);
targbhdislun(periph);
return (CAM_REQ_CMP_ERR);
}
return (CAM_REQ_CMP);
}
static cam_status
targbhdislun(struct cam_periph *periph)
{
union ccb ccb;
struct targbh_softc *softc;
struct ccb_accept_tio* atio;
struct ccb_hdr *ccb_h;
softc = (struct targbh_softc *)periph->softc;
if ((softc->flags & TARGBH_FLAG_LUN_ENABLED) == 0)
return CAM_REQ_CMP;
/* XXX Block for Continue I/O completion */
/* Kill off all ACCECPT and IMMEDIATE CCBs */
while ((atio = softc->accept_tio_list) != NULL) {
softc->accept_tio_list =
((struct targbh_cmd_desc*)atio->ccb_h.ccb_descr)->atio_link;
xpt_setup_ccb(&ccb.cab.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
ccb.cab.ccb_h.func_code = XPT_ABORT;
ccb.cab.abort_ccb = (union ccb *)atio;
xpt_action(&ccb);
}
while ((ccb_h = SLIST_FIRST(&softc->immed_notify_slist)) != NULL) {
SLIST_REMOVE_HEAD(&softc->immed_notify_slist, periph_links.sle);
xpt_setup_ccb(&ccb.cab.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
ccb.cab.ccb_h.func_code = XPT_ABORT;
ccb.cab.abort_ccb = (union ccb *)ccb_h;
xpt_action(&ccb);
}
/*
* Dissable this lun.
*/
xpt_setup_ccb(&ccb.cel.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
ccb.cel.ccb_h.func_code = XPT_EN_LUN;
ccb.cel.enable = 0;
xpt_action(&ccb);
if (ccb.cel.ccb_h.status != CAM_REQ_CMP)
printf("targbhdislun - Disabling lun on controller failed "
"with status 0x%x\n", ccb.cel.ccb_h.status);
else
softc->flags &= ~TARGBH_FLAG_LUN_ENABLED;
return (ccb.cel.ccb_h.status);
}
static cam_status
targbhctor(struct cam_periph *periph, void *arg)
{
struct targbh_softc *softc;
/* Allocate our per-instance private storage */
softc = (struct targbh_softc *)malloc(sizeof(*softc),
M_SCSIBH, M_NOWAIT);
if (softc == NULL) {
printf("targctor: unable to malloc softc\n");
return (CAM_REQ_CMP_ERR);
}
bzero(softc, sizeof(*softc));
TAILQ_INIT(&softc->pending_queue);
TAILQ_INIT(&softc->work_queue);
softc->accept_tio_list = NULL;
SLIST_INIT(&softc->immed_notify_slist);
softc->state = TARGBH_STATE_NORMAL;
periph->softc = softc;
softc->init_level++;
return (targbhenlun(periph));
}
static void
targbhdtor(struct cam_periph *periph)
{
struct targbh_softc *softc;
softc = (struct targbh_softc *)periph->softc;
softc->state = TARGBH_STATE_TEARDOWN;
targbhdislun(periph);
switch (softc->init_level) {
case 0:
panic("targdtor - impossible init level");
case 1:
/* FALLTHROUGH */
default:
/* XXX Wait for callback of targbhdislun() */
msleep(softc, periph->sim->mtx, PRIBIO, "targbh", hz/2);
free(softc, M_SCSIBH);
break;
}
}
static void
targbhstart(struct cam_periph *periph, union ccb *start_ccb)
{
struct targbh_softc *softc;
struct ccb_hdr *ccbh;
struct ccb_accept_tio *atio;
struct targbh_cmd_desc *desc;
struct ccb_scsiio *csio;
ccb_flags flags;
softc = (struct targbh_softc *)periph->softc;
ccbh = TAILQ_FIRST(&softc->work_queue);
if (periph->immediate_priority <= periph->pinfo.priority) {
start_ccb->ccb_h.ccb_type = TARGBH_CCB_WAITING;
SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
periph_links.sle);
periph->immediate_priority = CAM_PRIORITY_NONE;
wakeup(&periph->ccb_list);
} else if (ccbh == NULL) {
xpt_release_ccb(start_ccb);
} else {
TAILQ_REMOVE(&softc->work_queue, ccbh, periph_links.tqe);
TAILQ_INSERT_HEAD(&softc->pending_queue, ccbh,
periph_links.tqe);
atio = (struct ccb_accept_tio*)ccbh;
desc = (struct targbh_cmd_desc *)atio->ccb_h.ccb_descr;
/* Is this a tagged request? */
flags = atio->ccb_h.flags &
(CAM_DIS_DISCONNECT|CAM_TAG_ACTION_VALID|CAM_DIR_MASK);
csio = &start_ccb->csio;
/*
* If we are done with the transaction, tell the
* controller to send status and perform a CMD_CMPLT.
* If we have associated sense data, see if we can
* send that too.
*/
if (desc->data_resid == desc->data_increment) {
flags |= CAM_SEND_STATUS;
if (atio->sense_len) {
csio->sense_len = atio->sense_len;
csio->sense_data = atio->sense_data;
flags |= CAM_SEND_SENSE;
}
}
cam_fill_ctio(csio,
/*retries*/2,
targbhdone,
flags,
(flags & CAM_TAG_ACTION_VALID)?
MSG_SIMPLE_Q_TAG : 0,
atio->tag_id,
atio->init_id,
desc->status,
/*data_ptr*/desc->data_increment == 0
? NULL : desc->data,
/*dxfer_len*/desc->data_increment,
/*timeout*/desc->timeout);
/* Override our wildcard attachment */
start_ccb->ccb_h.target_id = atio->ccb_h.target_id;
start_ccb->ccb_h.target_lun = atio->ccb_h.target_lun;
start_ccb->ccb_h.ccb_type = TARGBH_CCB_WORKQ;
start_ccb->ccb_h.ccb_atio = atio;
CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
("Sending a CTIO\n"));
xpt_action(start_ccb);
/*
* If the queue was frozen waiting for the response
* to this ATIO (for instance disconnection was disallowed),
* then release it now that our response has been queued.
*/
if ((atio->ccb_h.status & CAM_DEV_QFRZN) != 0) {
cam_release_devq(periph->path,
/*relsim_flags*/0,
/*reduction*/0,
/*timeout*/0,
/*getcount_only*/0);
atio->ccb_h.status &= ~CAM_DEV_QFRZN;
}
ccbh = TAILQ_FIRST(&softc->work_queue);
}
if (ccbh != NULL)
xpt_schedule(periph, CAM_PRIORITY_NORMAL);
}
static void
targbhdone(struct cam_periph *periph, union ccb *done_ccb)
{
struct targbh_softc *softc;
softc = (struct targbh_softc *)periph->softc;
if (done_ccb->ccb_h.ccb_type == TARGBH_CCB_WAITING) {
/* Caller will release the CCB */
wakeup(&done_ccb->ccb_h.cbfcnp);
return;
}
switch (done_ccb->ccb_h.func_code) {
case XPT_ACCEPT_TARGET_IO:
{
struct ccb_accept_tio *atio;
struct targbh_cmd_desc *descr;
u_int8_t *cdb;
int priority;
atio = &done_ccb->atio;
descr = (struct targbh_cmd_desc*)atio->ccb_h.ccb_descr;
cdb = atio->cdb_io.cdb_bytes;
if (softc->state == TARGBH_STATE_TEARDOWN
|| atio->ccb_h.status == CAM_REQ_ABORTED) {
targbhfreedescr(descr);
xpt_free_ccb(done_ccb);
return;
}
/*
* Determine the type of incoming command and
* setup our buffer for a response.
*/
switch (cdb[0]) {
case INQUIRY:
{
struct scsi_inquiry *inq;
inq = (struct scsi_inquiry *)cdb;
CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
("Saw an inquiry!\n"));
/*
* Validate the command. We don't
* support any VPD pages, so complain
* if EVPD is set.
*/
if ((inq->byte2 & SI_EVPD) != 0
|| inq->page_code != 0) {
atio->ccb_h.flags &= ~CAM_DIR_MASK;
atio->ccb_h.flags |= CAM_DIR_NONE;
/*
* This needs to have other than a
* no_lun_sense_data response.
*/
bcopy(&no_lun_sense_data, &atio->sense_data,
min(sizeof(no_lun_sense_data),
sizeof(atio->sense_data)));
atio->sense_len = sizeof(no_lun_sense_data);
descr->data_resid = 0;
descr->data_increment = 0;
descr->status = SCSI_STATUS_CHECK_COND;
break;
}
/*
* Direction is always relative
* to the initator.
*/
atio->ccb_h.flags &= ~CAM_DIR_MASK;
atio->ccb_h.flags |= CAM_DIR_IN;
descr->data = &no_lun_inq_data;
descr->data_resid = MIN(sizeof(no_lun_inq_data),
scsi_2btoul(inq->length));
descr->data_increment = descr->data_resid;
descr->timeout = 5 * 1000;
descr->status = SCSI_STATUS_OK;
break;
}
case REQUEST_SENSE:
{
struct scsi_request_sense *rsense;
rsense = (struct scsi_request_sense *)cdb;
/* Refer to static sense data */
atio->ccb_h.flags &= ~CAM_DIR_MASK;
atio->ccb_h.flags |= CAM_DIR_IN;
descr->data = &no_lun_sense_data;
descr->data_resid = request_sense_size;
descr->data_resid = MIN(descr->data_resid,
SCSI_CDB6_LEN(rsense->length));
descr->data_increment = descr->data_resid;
descr->timeout = 5 * 1000;
descr->status = SCSI_STATUS_OK;
break;
}
default:
/* Constant CA, tell initiator */
/* Direction is always relative to the initator */
atio->ccb_h.flags &= ~CAM_DIR_MASK;
atio->ccb_h.flags |= CAM_DIR_NONE;
bcopy(&no_lun_sense_data, &atio->sense_data,
min(sizeof(no_lun_sense_data),
sizeof(atio->sense_data)));
atio->sense_len = sizeof (no_lun_sense_data);
descr->data_resid = 0;
descr->data_increment = 0;
descr->timeout = 5 * 1000;
descr->status = SCSI_STATUS_CHECK_COND;
break;
}
/* Queue us up to receive a Continue Target I/O ccb. */
if ((atio->ccb_h.flags & CAM_DIS_DISCONNECT) != 0) {
TAILQ_INSERT_HEAD(&softc->work_queue, &atio->ccb_h,
periph_links.tqe);
priority = 0;
} else {
TAILQ_INSERT_TAIL(&softc->work_queue, &atio->ccb_h,
periph_links.tqe);
priority = CAM_PRIORITY_NORMAL;
}
xpt_schedule(periph, priority);
break;
}
case XPT_CONT_TARGET_IO:
{
struct ccb_accept_tio *atio;
struct targbh_cmd_desc *desc;
CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
("Received completed CTIO\n"));
atio = (struct ccb_accept_tio*)done_ccb->ccb_h.ccb_atio;
desc = (struct targbh_cmd_desc *)atio->ccb_h.ccb_descr;
TAILQ_REMOVE(&softc->pending_queue, &atio->ccb_h,
periph_links.tqe);
/*
* We could check for CAM_SENT_SENSE bein set here,
* but since we're not maintaining any CA/UA state,
* there's no point.
*/
atio->sense_len = 0;
done_ccb->ccb_h.flags &= ~CAM_SEND_SENSE;
done_ccb->ccb_h.status &= ~CAM_SENT_SENSE;
/*
* Any errors will not change the data we return,
* so make sure the queue is not left frozen.
* XXX - At some point there may be errors that
* leave us in a connected state with the
* initiator...
*/
if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
printf("Releasing Queue\n");
cam_release_devq(done_ccb->ccb_h.path,
/*relsim_flags*/0,
/*reduction*/0,
/*timeout*/0,
/*getcount_only*/0);
done_ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
}
desc->data_resid -= desc->data_increment;
xpt_release_ccb(done_ccb);
if (softc->state != TARGBH_STATE_TEARDOWN) {
/*
* Send the original accept TIO back to the
* controller to handle more work.
*/
CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
("Returning ATIO to target\n"));
/* Restore wildcards */
atio->ccb_h.target_id = CAM_TARGET_WILDCARD;
atio->ccb_h.target_lun = CAM_LUN_WILDCARD;
xpt_action((union ccb *)atio);
break;
} else {
targbhfreedescr(desc);
free(atio, M_SCSIBH);
}
break;
}
case XPT_IMMED_NOTIFY:
{
int frozen;
frozen = (done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0;
if (softc->state == TARGBH_STATE_TEARDOWN
|| done_ccb->ccb_h.status == CAM_REQ_ABORTED) {
printf("Freed an immediate notify\n");
xpt_free_ccb(done_ccb);
} else {
/* Requeue for another immediate event */
xpt_action(done_ccb);
}
if (frozen != 0)
cam_release_devq(periph->path,
/*relsim_flags*/0,
/*opening reduction*/0,
/*timeout*/0,
/*getcount_only*/0);
break;
}
default:
panic("targbhdone: Unexpected ccb opcode");
break;
}
}
#ifdef NOTYET
static int
targbherror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
{
return 0;
}
#endif
static struct targbh_cmd_desc*
targbhallocdescr()
{
struct targbh_cmd_desc* descr;
/* Allocate the targbh_descr structure */
descr = (struct targbh_cmd_desc *)malloc(sizeof(*descr),
M_SCSIBH, M_NOWAIT);
if (descr == NULL)
return (NULL);
bzero(descr, sizeof(*descr));
/* Allocate buffer backing store */
descr->backing_store = malloc(MAX_BUF_SIZE, M_SCSIBH, M_NOWAIT);
if (descr->backing_store == NULL) {
free(descr, M_SCSIBH);
return (NULL);
}
descr->max_size = MAX_BUF_SIZE;
return (descr);
}
static void
targbhfreedescr(struct targbh_cmd_desc *descr)
{
free(descr->backing_store, M_SCSIBH);
free(descr, M_SCSIBH);
}
| {
"content_hash": "f6e4e230acf89e1c05a481131364ed87",
"timestamp": "",
"source": "github",
"line_count": 755,
"max_line_length": 101,
"avg_line_length": 26.192052980132452,
"alnum_prop": 0.6510745891276865,
"repo_name": "dplbsd/soc2013",
"id": "0e10be75217b64f52339a7d7f4e10a284292c7d8",
"size": "21202",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "head/sys/cam/scsi/scsi_targ_bh.c",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "AGS Script",
"bytes": "62471"
},
{
"name": "Assembly",
"bytes": "4478661"
},
{
"name": "Awk",
"bytes": "278525"
},
{
"name": "Batchfile",
"bytes": "20417"
},
{
"name": "C",
"bytes": "383420305"
},
{
"name": "C++",
"bytes": "72796771"
},
{
"name": "CSS",
"bytes": "109748"
},
{
"name": "ChucK",
"bytes": "39"
},
{
"name": "D",
"bytes": "3784"
},
{
"name": "DIGITAL Command Language",
"bytes": "10640"
},
{
"name": "DTrace",
"bytes": "2311027"
},
{
"name": "Emacs Lisp",
"bytes": "65902"
},
{
"name": "EmberScript",
"bytes": "286"
},
{
"name": "Forth",
"bytes": "184405"
},
{
"name": "GAP",
"bytes": "72156"
},
{
"name": "Groff",
"bytes": "32248806"
},
{
"name": "HTML",
"bytes": "6749816"
},
{
"name": "IGOR Pro",
"bytes": "6301"
},
{
"name": "Java",
"bytes": "112547"
},
{
"name": "KRL",
"bytes": "4950"
},
{
"name": "Lex",
"bytes": "398817"
},
{
"name": "Limbo",
"bytes": "3583"
},
{
"name": "Logos",
"bytes": "187900"
},
{
"name": "Makefile",
"bytes": "3551839"
},
{
"name": "Mathematica",
"bytes": "9556"
},
{
"name": "Max",
"bytes": "4178"
},
{
"name": "Module Management System",
"bytes": "817"
},
{
"name": "NSIS",
"bytes": "3383"
},
{
"name": "Objective-C",
"bytes": "836351"
},
{
"name": "PHP",
"bytes": "6649"
},
{
"name": "Perl",
"bytes": "5530761"
},
{
"name": "Perl6",
"bytes": "41802"
},
{
"name": "PostScript",
"bytes": "140088"
},
{
"name": "Prolog",
"bytes": "29514"
},
{
"name": "Protocol Buffer",
"bytes": "61933"
},
{
"name": "Python",
"bytes": "299247"
},
{
"name": "R",
"bytes": "764"
},
{
"name": "Rebol",
"bytes": "738"
},
{
"name": "Ruby",
"bytes": "45958"
},
{
"name": "Scilab",
"bytes": "197"
},
{
"name": "Shell",
"bytes": "10501540"
},
{
"name": "SourcePawn",
"bytes": "463194"
},
{
"name": "SuperCollider",
"bytes": "80208"
},
{
"name": "Tcl",
"bytes": "80913"
},
{
"name": "TeX",
"bytes": "719821"
},
{
"name": "VimL",
"bytes": "22201"
},
{
"name": "XS",
"bytes": "25451"
},
{
"name": "XSLT",
"bytes": "31488"
},
{
"name": "Yacc",
"bytes": "1857830"
}
],
"symlink_target": ""
} |
var _ = require('underscore');
var Backbone = require('backbone');
var Notifier = DT.lib.Notifier;
var BasePageView = DT.lib.BasePageView;
var ErrorPageView = BasePageView.extend({
pageName: 'ErrorPageView',
useDashMgr: false,
initialize: function(attributes, options) {
BasePageView.prototype.initialize.call(this, attributes, options);
console.log('__ErrorPageView');
},
render: function() {
Notifier.error({
'title': 'Page Not Found',
'text': 'Requested page is not found.',
'delay': 5000
});
}
});
exports = module.exports = ErrorPageView | {
"content_hash": "ab89224d1cc878323dd1b6f04c3b16b3",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 74,
"avg_line_length": 22.862068965517242,
"alnum_prop": 0.6018099547511312,
"repo_name": "andyperlitch/malhar-ui-console-2",
"id": "a649b931433d57651b00261da6349bf1fea7400c",
"size": "1286",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/app/lib/pages/ErrorPageView.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "266291"
},
{
"name": "JavaScript",
"bytes": "1231564"
},
{
"name": "Shell",
"bytes": "283"
}
],
"symlink_target": ""
} |
ENV_VARS_GCS_PATH=gs://your-bucket-name/env.txt
# UPDATE the path to your service account credentials.json stored on your GCS Bucket
CRED_FILE_GCS_PATH=gs://your-bucket-name/credentials.json
# UPDATE the path to your container image
# To be updated with desired conatiner image and with an updated image for every subsequent software update
# GCR Format: gcr.io/<YOUR_GOOGLE_PROJECT_ID>/YOUR_CONTAINER_IMAGE:TAG
CONTAINER_IMAGE_PATH=gcr.io/your-project-id/your-sdrs-build:0.1.0
# UPDATE Cloud Endpoints Services URL
# Format: <ENDPOINT_NAME>.endpoints.<ENDPOINTS_PROJECT_ID>.cloud.goog
ENDPOINT_SERVICE_URL=sdrs-api.endpoints.your-project-id.cloud.goog
# NO CHANGES required below this point unless you know what you are doing
gcloud auth configure-docker
# env.txt contains the environment specific variables.
gsutil cp $ENV_VARS_GCS_PATH .
# Create directory to store GCP credentials file
mkdir /root/cred
# Copy GCP Service Account credentials file to secured directory
gsutil cp $CRED_FILE_GCS_PATH /root/cred
sleep 5
# Create docker networking
docker network create --driver bridge esp_network
sleep 5
# Run docker image containing SDRS
docker run --detach -v /root/cred:/var/sdrs \
--name=sdrs --env-file=./env.txt \
--log-driver=json-file \
--publish=8080:8080 \
--net=esp_network $CONTAINER_IMAGE_PATH
# Delete the env.txt file after running container.
rm -rf ./env.txt
sleep 30
docker run --name=esp \
--log-driver=json-file \
--detach --publish=80:8080 \
--net=esp_network gcr.io/endpoints-release/endpoints-runtime:1 \
--service=$ENDPOINT_SERVICE_URL \
--rollout_strategy=managed --dns=169.254.169.254 --backend=sdrs:8080
| {
"content_hash": "0baea2ac19f4cf9a49a115c0d7830359",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 107,
"avg_line_length": 34.254901960784316,
"alnum_prop": 0.723526044647968,
"repo_name": "GoogleCloudPlatform/storage-sdrs",
"id": "d62a80ec3fcb7ef228d759432ba2b0ccab861bf9",
"size": "1821",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/deployment/mig/scripts/startup.sh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1148"
},
{
"name": "Java",
"bytes": "647104"
},
{
"name": "Jinja",
"bytes": "13965"
},
{
"name": "Python",
"bytes": "25773"
},
{
"name": "Shell",
"bytes": "5689"
}
],
"symlink_target": ""
} |
var parseString = require('xml2js').parseString;
module.exports = {
//Auxilaries function
//Return true if a value is in a tab
isIn : function(value,tab){
var res = false;
if(tab.length > 0){
tab.forEach(function(v){
if(v == value){
res = true;
}
});
}
return res;
},
onRun: function (config, dependencies, jobCallback) {
/**
*Jenkins Job : jobs status
**/
//get the authentication informations
try {
var user = config.globalAuth[config.authName].username;
var password = config.globalAuth[config.authName].password;
} catch(e){
var user = "error";
var password = "error";
}
//This object will allow the authentication
var option = {
'auth' : {
'user' : user,
'pass' : password
}
};
//Check if there is no authentication error
function authenticationVerification(option){
return new Promise(function(resolve,reject){
//This adress send to the jenkins Home Page
var testAdress = config.jenkinsServer;
dependencies.request.get(
testAdress,
option,
function(err,response,data){
try{
parseString(data,function(err,body){
//If body.html.body[0]._ exist and equals '\n\n\nAuthentication required\n\n\n', there is an authentication Error
try{
if( body.html.body[0]._ == '\n\n\nAuthentication required\n\n\n'){
reject(false);
} else{
resolve(true);
}
}catch(e){
resolve(true);
}
});
}catch(e){
reject(false);
}
}
);
});
}
//Adresses
var jobsAdress = config.jenkinsServer + config.jenkinsRequest; //Adress to the Jenkins job list.
var jobAdressBase = config.jenkinsServer + config.jobRequest; //Adress of the job informations
//Job list
var jobList = config.jobList;
//Job informations tab
var jobsInformation = [];//Tab send to the widget, and containning the job informations
//Informations variables
var name = "";
var status = 'none';
var duration = 'none';
var result = 'none';
//Those variables will be stocked in a JSON object for each job
//For a given job, return the right informations
/********************************************************
* But du jeu : Avec les Promesse faire en *
* sorte d'attendre le retours des différentes *
* fonctions asychrones avant de continuer: *
* *
* function test(){ *
* return new Promise(function(resolve, reject){ *
* setTimeout(function(){resolve(4)}, 2000); *
* }); *
* } *
* *
* test().then( *
* function(data){console.log(data)}, *
* function(err){console.error(err)}); *
* *
*********************************************************/
function getJobInformation(jobName){
return new Promise(function(resolve, reject){
//First get the status in the jobsAdress part
try{
dependencies.request.get(
jobsAdress,
option,
function(err,response,data){
//If error, reject it
if(err){
reject(err);
}
//The job list is in data.jobs
//!! data is a string, not a JSON object !!
var jobsListGlobal = JSON.parse(data).jobs;
jobsListGlobal.forEach(function(job){
if(job.name == jobName){
status = job.color;
}
});
resolve(status);
}
);
}catch(e){
reject('none');
}
});
}
//Function use if getJobInformation resolves :
//Get job information on the personnal file
function getJobPersoInfo(job,status){
var adressJob = jobAdressBase.replace(/<jobName>/gi,job);
try{
dependencies.request.get(
adressJob,
option,
function(err,response,data){
if(err){
jobsInformation.push({name : job,status : 'none'});
}
else{
try{
var jobInfo = JSON.parse(data);
//Get the informations
duration = jobInfo.duration;
result = jobInfo.result;
//create the job object
var jobDescription = {
'name' : job,
'status' : status,
'duration' : duration,
'result' : result
}
//Push it to the jobsInformation
jobsInformation.push(jobDescription);
}catch(e){
jobsInformation.push({'name' : job,'status' : 'none'});
}
}
if(jobsInformation.length == jobList.length){
jobCallback(null, {title : config.widgetTitle, jobList : jobsInformation,jenkinsServer : config.jenkinsServer});
}
}
);
}catch(e){
jobsInformation.push({'name' : name,'status' : 'none'});
jobCallback(null,{title : config.widgetTitle, jobList : jobsInformation,jenkinsServer : config.jenkinsServer});
}
}
function main(){
try{
jobList.forEach(function(job){
getJobInformation(job).then(
function(data){
getJobPersoInfo(job,data);
},
function(err){
jobsInformation.push({'name' : name,'status' : 'none'});
jobCallback(null,{title : config.widgetTitle, jobList : jobsInformation,jenkinsServer : config.jenkinsServer});
}
);
});
} catch(e){
jobCallback(null, {title: config.widgetTitle,jobList : jobsInformation,jenkinsServer : config.jenkinsServer});
}
}
//Beginnning of the application
authenticationVerification(option).then(
//If the authentication works
function(data){
main();
},
//else
function(err){
jobsInformation.push({'status': 'authenticationError'});
jobCallback(null, {title: config.widgetTitle,jobList : jobsInformation,jenkinsServer : config.jenkinsServer});
}
);
}
}; | {
"content_hash": "1d875add82cbc8f1aa2865e1cd89becd",
"timestamp": "",
"source": "github",
"line_count": 218,
"max_line_length": 121,
"avg_line_length": 26.380733944954127,
"alnum_prop": 0.5840723352460442,
"repo_name": "bhecquet/qualityBoard",
"id": "a2bd4acab18e099ff8aa0a5ed3e725ef22b3527a",
"size": "5752",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/Quality/jobs/Jenkins/Jenkins.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "18914"
},
{
"name": "HTML",
"bytes": "6780"
},
{
"name": "JavaScript",
"bytes": "115614"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WcfFullDuplexServer
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "OrderService" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select OrderService.svc or OrderService.svc.cs at the Solution Explorer and start debugging.
public class OrderService : IOrderService
{
public void SubmitOrder(Order o)
{
// Save Order ...
var client = OperationContext.Current.GetCallbackChannel<IOrderServiceCallback>();
client.OrderReceived(o);
System.Threading.Thread.Sleep(1234);
client.OrderReceived(o);
System.Threading.Thread.Sleep(2345);
client.OrderReceived(o);
}
}
}
| {
"content_hash": "404167a9eff67dce3b56f27aa947fcaf",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 173,
"avg_line_length": 38.4,
"alnum_prop": 0.6875,
"repo_name": "tlaothong/cat-design-patterns",
"id": "e199412b1952b48ef668a41139e60527b1718ebd",
"size": "962",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WcfFullDuplexServer/OrderService.svc.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "102"
},
{
"name": "C#",
"bytes": "141270"
},
{
"name": "CSS",
"bytes": "1477"
},
{
"name": "HTML",
"bytes": "11790"
},
{
"name": "JavaScript",
"bytes": "34"
}
],
"symlink_target": ""
} |
<?php
namespace JsPackager\Command;
use JsPackager\Compiler;
use JsPackager\DefaultRemotePath;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Logger\ConsoleLogger;
use Symfony\Component\Console\Output\OutputInterface;
class CompileFilesCommand extends Command
{
public function __construct($name = null) {
$defaultRemotePathInstance = new DefaultRemotePath();
$this->defaultRemotePath = $defaultRemotePathInstance->getDefaultRemotePath();
return parent::__construct($name);
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('compile-files')
->setDescription('Compiled given file(s).')
->setDefinition($this->createDefinition())
->setHelp(<<<HELPBLURB
<info>%command.name%</info> provides an easy way to compile a given file or list of files.
\t<info>%command.full_name% src/main.js</info> compiles the src/main.js file with its dependencies.
By default, output is fairly quiet unless there are problems. To see what's going on, increase the verbosity level.
\t<info>%command.full_name% src/main.js -vv</info>
Multiple files are supported.
\t<info>%command.full_name% src/main-file.js src/batched-lib.js</info>.
HELPBLURB
);
;
}
/**
* @var LoggerInterface
*/
protected $logger;
/**
* @var String
*/
protected $defaultRemotePath;
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$foldersToClear = $input->getArgument('file');
$remoteFolderPath = $input->getOption('remotePath');
$completelySuccessful = true;
$this->logger = new ConsoleLogger($output);
$compilerTimeStart = microtime( true );
$compiler = new Compiler();
$hideWarnings = $input->getOption('hideWarnings');
$compiler->setDisplayIndividualWarnings( ! $hideWarnings );
if ( $remoteFolderPath ) {
$this->logger->info('Remote base path given: "'. $remoteFolderPath . '".');
$compiler->remoteFolderPath = $remoteFolderPath;
} else {
$defaultRemotePath = $this->defaultRemotePath;
$this->logger->info('No remote base path given, using "'. $defaultRemotePath . '" as default.');
$compiler->remoteFolderPath = $defaultRemotePath;
}
$compiler->logger = $this->logger;
$filesCompiled = array();
foreach( $foldersToClear as $inputFile )
{
$this->logger->info("Compiling file '{$inputFile}'.");
$compilationSuccessful = $this->compileFile( $compiler, $inputFile );
array_push($filesCompiled, array($inputFile, $compilationSuccessful?'<info>Yes</info>':'<error>No</error>'));
// If this file failed to compile, we were not completely successful
if ( $compilationSuccessful === false )
{
$completelySuccessful = false;
}
}
$compilerTimeEnd = microtime( true );
$compilerTimeTotal = $compilerTimeEnd - $compilerTimeStart;
$this->logger->notice( "JsPackager compiler finished file compilation. (Total time: {$compilerTimeTotal} seconds)." );
$table = new Table($output);
$table->setHeaders(array('Folder','Successfully Compiled'));
$table->setRows($filesCompiled);
$table->render();
return (int)(!$completelySuccessful); // A-OK error code
}
/**
* Compile a file using a Compiler, reporting back to the UI
*
* @param Compiler $compiler
* @param string $filePath
*/
function compileFile($compiler, $filePath) {
$completelySuccessful = true;
$this->logger->info("Confirming path to '{$filePath}'.");
$realPathResult = realpath( $filePath );
if ( $realPathResult === false ) {
$this->logger->error("Path '{$filePath}' resolved to nowhere.");
return false;
} else {
$filePath = $realPathResult;
}
$this->updateUserInterface( "Compiling \"{$filePath}\"\n", 'output' );
$this->updateUserInterface( "[Compiling] Loading file \"{$filePath}\" for compilation..." . PHP_EOL, 'status' );
try
{
$compilationTimingStart = microtime( true );
$compiledFiles = $compiler->compileAndWriteFilesAndManifests( $filePath, 'updateUserInterface' );
$compilationTimingEnd = microtime( true );
$compilationTotalTime = $compilationTimingEnd - $compilationTimingStart;
$this->updateUserInterface( "[Compiling] Successfully compiled file \"{$filePath}\" in {$compilationTotalTime} seconds.", 'status' );
$this->updateUserInterface( "\t\tIt resulted in " . count($compiledFiles) . ' compiled packages:' . PHP_EOL, 'output' );
foreach( $compiledFiles as $compiledFile ) {
$this->updateUserInterface( "\t\t{$compiledFile->sourcePath}\n", 'output' );
$this->updateUserInterface( "\t\t\t{$compiledFile->compiledPath}\n", 'output' );
$this->updateUserInterface( "\t\t\t{$compiledFile->manifestPath}\n", 'output' );
}
}
catch ( MissingFileException $e )
{
$this->updateUserInterface( "[Compiling] [ERROR] {$e->getMessage()}", 'error' );
$completelySuccessful = false;
}
catch ( ParsingException $e )
{
$this->updateUserInterface( "[Compiling] [ERROR] {$e->getMessage()}", 'error' );
$completelySuccessful = false;
}
catch ( CannotWriteException $e )
{
$this->updateUserInterface( "[Compiling] [ERROR] Failed to compile \"{$e->getFilePath()}\" - " . $e->getMessage(), 'error' );
$completelySuccessful = false;
}
return $completelySuccessful;
}
/**
* Exits with the appropriate exit code.
*
* (This wraps the inverted logic of 0 = true in exit codes)
*
* @param bool $success Pass true if successful
*/
function returnWithExitCode($success)
{
// Return with exit code so CI's like us
$exitCode = (int)(!$success);
exit($exitCode);
}
/**
* Update the user interface by decorating and echoing the given string to standard output.
*
* @param string $line
* @param string $type An option out of
* output Outputs the line exactly as given.
* status Outputs the line tabbed, with a newline added.
* error Outputs the line tabbed, colored, and with a newline added.
* warning Outputs the line tabbed, colored, and with a newline added.
* success Outputs the line tabbed, colored, and with a newline added.
*/
function updateUserInterface($line, $type = 'output') {
if ( $type === 'error' )
{
$this->logger->error($line);
}
else if ( $type === 'warning' )
{
$this->logger->warning($line);
}
else if ( $type === 'success' )
{
$this->logger->notice($line);
}
else if ( $type === 'status' )
{
$this->logger->info($line);
}
else if ( $type == 'output' )
{
$this->logger->info($line);
}
else
{
$this->logger->error("Unknown UI Message Type: '$line'.");
}
}
/**
* {@inheritdoc}
*/
public function getNativeDefinition()
{
return $this->createDefinition();
}
/**
* {@inheritdoc}
*/
protected function createDefinition()
{
return new InputDefinition(array(
new InputArgument('file', InputArgument::REQUIRED | InputArgument::IS_ARRAY, 'Relative or absolute path to file to compile.'),
new InputOption('remotePath', 'r', InputArgument::OPTIONAL, 'Relative or absolute base path to use for parsing @remote files.', $this->defaultRemotePath),
new InputOption('hideWarnings', null, InputOption::VALUE_NONE, 'Provide to see individual warnings encountered during compilation.'),
));
}
} | {
"content_hash": "310102beccc46b946386ca7f77f387e5",
"timestamp": "",
"source": "github",
"line_count": 256,
"max_line_length": 166,
"avg_line_length": 33.5234375,
"alnum_prop": 0.6000932183640177,
"repo_name": "r4j4h/jspackager-cli",
"id": "417e8bc6ddfc576ec1dc0b49e921dec6ee7583e9",
"size": "8582",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/JsPackager/Command/CompileFilesCommand.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "34745"
}
],
"symlink_target": ""
} |
function formcheck_school_setup_school()
{
var sel = document.getElementsByTagName('input');
for(var i=1; i<sel.length; i++)
{
var inp_value = sel[i].value;
if(inp_value == "")
{
var inp_name = sel[i].name;
if(inp_name == 'values[TITLE]')
{
document.getElementById('divErr').innerHTML="<b><font color=red>"+unescape("Please enter school name")+"</font></b>";
return false;
}
else if(inp_name == 'values[ADDRESS]')
{
document.getElementById('divErr').innerHTML="<b><font color=red>"+unescape("Please enter address")+"</font></b>";
return false;
}
else if(inp_name == 'values[CITY]')
{
document.getElementById('divErr').innerHTML="<b><font color=red>"+unescape("Please enter city")+"</font></b>";
return false;
}
else if(inp_name == 'values[STATE]')
{
document.getElementById('divErr').innerHTML="<b><font color=red>"+unescape("Please enter state")+"</font></b>";
return false;
}
else if(inp_name == 'values[ZIPCODE]')
{
document.getElementById('divErr').innerHTML="<b><font color=red>"+unescape("Please enter zip/postal code")+"</font></b>";
return false;
}
else if(inp_name == 'values[PHONE]')
{
document.getElementById('divErr').innerHTML="<b><font color=red>"+unescape("Please enter phone number")+"</font></b>";
return false;
}
else if(inp_name == 'values[PRINCIPAL]')
{
document.getElementById('divErr').innerHTML="<b><font color=red>"+unescape("Please enter principal")+"</font></b>";
return false;
}
else if(inp_name == 'values[REPORTING_GP_SCALE]')
{
document.getElementById('divErr').innerHTML="<b><font color=red>"+unescape("Please enter base grading scale")+"</font></b>";
return false;
}
}
else if(inp_value != "")
{
var val = inp_value;
var inp_name1 = sel[i].name;
if(inp_name1 == 'values[ZIPCODE]')
{
var charpos = val.search("[^0-9-\(\)\, ]");
if (charpos >= 0)
{
document.getElementById('divErr').innerHTML="<b><font color=red>"+unescape("Please enter a valid zip/postal code.")+"</font></b>";
return false;
}
}
if(inp_name1 == 'values[PHONE]')
{
var charpos = val.search("[^0-9-\(\)\, ]");
if (charpos >= 0)
{
document.getElementById('divErr').innerHTML="<b><font color=red>"+unescape("Please enter a valid phone number.")+"</font></b>";
return false;
}
}
else if(inp_name1 == 'values[REPORTING_GP_SCALE]')
{
var charpos = val.search("[^0-9.]");
if (charpos >= 0)
{
document.getElementById('divErr').innerHTML="<b><font color=red>"+unescape("Please enter decimal value only.")+"</font></b>";
return false;
}
}
else if(inp_name1 == 'values[E_MAIL]')
{
var emailRegxp = /^(.+)@(.+)$/;
if (emailRegxp.test(val) != true)
{
document.getElementById('divErr').innerHTML="<b><font color=red>"+unescape("Please enter a valid email address.")+"</font></b>";
return false;
}
}
/*else if(inp_name1 == 'values[WWW_ADDRESS]')
{
var urlRegxp = /^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([\w]+)(.[\w]+){1,2}$/;
if (urlRegxp.test(val) != true)
{
document.getElementById('divErr').innerHTML="<b><font color=red>"+unescape("Please Enter a Valid url.")+"</font></b>";
return false;
}
}*/
}
}
return true;
// document.school.submit();
}
function formcheck_school_setup_portalnotes()
{
var frmvalidator = new Validator("F2");
frmvalidator.addValidation("values[new][TITLE]","alphanumeric", "Title allows only alphanumeric value");
frmvalidator.addValidation("values[new][TITLE]","maxlen=50", "Max length for title is 50 characters");
frmvalidator.addValidation("values[new][SORT_ORDER]","num", "Sort order allows only numeric value");
frmvalidator.addValidation("values[new][SORT_ORDER]","maxlen=5", "Max length for sort order is 5 digits");
frmvalidator.setAddnlValidationFunction("ValidateDate_Portal_Notes");
}
function formcheck_student_advnc_srch()
{
var day_to= $('day_to_birthdate');
var month_to= $('month_to_birthdate');
var day_from= $('day_from_birthdate');
var month_from= $('month_from_birthdate');
if(!day_to.value && !month_to.value && !day_from.value && !month_from.value ){
return true;
}
if(!day_to.value || !month_to.value || !day_from.value || !month_from.value )
{
strError="Please provide birthday to day, to month, from day, from month.";
document.getElementById('divErr').innerHTML="<b><font color=red>"+strError+"</font></b>";return false;
}
strError="To date must be equal to or greater than from date.";
if(month_from.value > month_to.value ){
document.getElementById('divErr').innerHTML="<b><font color=red>"+strError+"</font></b>";
return false;
}else if(month_from.value == month_to.value && day_from.value > day_to.value ){
document.getElementById('divErr').innerHTML="<b><font color=red>"+strError+"</font></b>";
return false;
}return true;
}
function ValidateDate_Portal_Notes()
{
var sm, sd, sy, em, ed, ey, psm, psd, psy, pem, ped, pey ;
var frm = document.forms["F2"];
var elem = frm.elements;
for(var i = 0; i < elem.length; i++)
{
if(elem[i].name=="month_values[new][START_DATE]")
{
sm=elem[i];
}
if(elem[i].name=="day_values[new][START_DATE]")
{
sd=elem[i];
}
if(elem[i].name=="year_values[new][START_DATE]")
{
sy=elem[i];
}
if(elem[i].name=="month_values[new][END_DATE]")
{
em=elem[i];
}
if(elem[i].name=="day_values[new][END_DATE]")
{
ed=elem[i];
}
if(elem[i].name=="year_values[new][END_DATE]")
{
ey=elem[i];
}
}
try
{
if (false==CheckDate(sm, sd, sy, em, ed, ey))
{
em.focus();
return false;
}
}
catch(err)
{
}
try
{
if (false==isDate(psm, psd, psy))
{
alert("Please enter the grade posting start date");
psm.focus();
return false;
}
}
catch(err)
{
}
try
{
if (true==isDate(pem, ped, pey))
{
if (false==CheckDate(psm, psd, psy, pem, ped, pey))
{
pem.focus();
return false;
}
}
}
catch(err)
{
}
return true;
}
function formcheck_school_setup_marking(){
var frmvalidator = new Validator("marking_period");
frmvalidator.addValidation("tables[new][TITLE]","req","Please enter the title");
frmvalidator.addValidation("tables[new][TITLE]","maxlen=50", "Max length for title is 50 characters");
frmvalidator.addValidation("tables[new][SHORT_NAME]","req","Please enter the short name");
frmvalidator.addValidation("tables[new][SHORT_NAME]","maxlen=10", "Max length for short name is 10 characters");
frmvalidator.addValidation("tables[new][SORT_ORDER]","maxlen=5", "Max length for sort order is 5 digits");
frmvalidator.addValidation("tables[new][SORT_ORDER]","num", "Enter only numeric value");
frmvalidator.setAddnlValidationFunction("ValidateDate_Marking_Periods");
}
function ValidateDate_Marking_Periods()
{
var sm, sd, sy, em, ed, ey, psm, psd, psy, pem, ped, pey, grd ;
var frm = document.forms["marking_period"];
var elem = frm.elements;
for(var i = 0; i < elem.length; i++)
{
if(elem[i].name=="month_tables[new][START_DATE]")
{
sm=elem[i];
}
if(elem[i].name=="day_tables[new][START_DATE]")
{
sd=elem[i];
}
if(elem[i].name=="year_tables[new][START_DATE]")
{
sy=elem[i];
}
if(elem[i].name=="month_tables[new][END_DATE]")
{
em=elem[i];
}
if(elem[i].name=="day_tables[new][END_DATE]")
{
ed=elem[i];
}
if(elem[i].name=="year_tables[new][END_DATE]")
{
ey=elem[i];
}
if(elem[i].name=="month_tables[new][POST_START_DATE]")
{
psm=elem[i];
}
if(elem[i].name=="day_tables[new][POST_START_DATE]")
{
psd=elem[i];
}
if(elem[i].name=="year_tables[new][POST_START_DATE]")
{
psy=elem[i];
}
if(elem[i].name=="month_tables[new][POST_END_DATE]")
{
pem=elem[i];
}
if(elem[i].name=="day_tables[new][POST_END_DATE]")
{
ped=elem[i];
}
if(elem[i].name=="year_tables[new][POST_END_DATE]")
{
pey=elem[i];
}
if(elem[i].name=="tables[new][DOES_GRADES]")
{
grd=elem[i];
}
}
try
{
if (false==isDate(sm, sd, sy))
{
document.getElementById("divErr").innerHTML="<b><font color=red>"+"Please enter the start date."+"</font></b>";
sm.focus();
return false;
}
}
catch(err)
{
}
try
{
if (false==isDate(em, ed, ey))
{
document.getElementById("divErr").innerHTML="<b><font color=red>"+"Please enter the end date."+"</font></b>";
em.focus();
return false;
}
}
catch(err)
{
}
try
{
if (false==CheckDate(sm, sd, sy, em, ed, ey))
{
em.focus();
return false;
}
}
catch(err)
{
}
if (true==validate_chk(grd))
{
try
{
if (false==isDate(psm, psd, psy))
{
document.getElementById("divErr").innerHTML="<b><font color=red>"+"Please enter the grade posting start date."+"</font></b>";
psm.focus();
return false;
}
}
catch(err)
{
}
try
{
if (true==isDate(pem, ped, pey))
{
if (false==CheckDate(psm, psd, psy, pem, ped, pey))
{
pem.focus();
return false;
}
}
}
catch(err)
{
}
try
{
if (false==CheckDateMar(sm, sd, sy, psm, psd, psy))
{
psm.focus();
return false;
}
}
catch(err)
{
}
}
return true;
}
function formcheck_school_setup_copyschool()
{
var frmvalidator = new Validator("prompt_form");
frmvalidator.addValidation("title","req","Please enter the new school's title");
frmvalidator.addValidation("title","maxlen=100", "Max length for title is 100 characters");
}
function formcheck_school_setup_calender()
{
var frmvalidator = new Validator("prompt_form");
frmvalidator.addValidation("title","req","Please enter the title");
frmvalidator.addValidation("title","maxlen=100", "Max length for title is 100");
}
function formcheck_school_setup_periods()
{
var frmvalidator = new Validator("F1");
var p_name = document.getElementById('values[new][TITLE]');
var p_name_val = p_name.value;
if(p_name_val != "")
{
frmvalidator.addValidation("values[new][TITLE]","maxlen=50", "Max length for title is 50 characters");
frmvalidator.addValidation("values[new][SHORT_NAME]","maxlen=50", "Max length for short name is 50 characters");
frmvalidator.addValidation("values[new][SORT_ORDER]","num", "Sort order allows only numeric value");
frmvalidator.addValidation("values[new][SORT_ORDER]","maxlen=5", "Max length for sort order is 5 digits");
frmvalidator.addValidation("values[new][START_HOUR]","req","Please select start time");
frmvalidator.addValidation("values[new][START_MINUTE]","req","Please select start time");
frmvalidator.addValidation("values[new][START_M]","req","Please select start time");
frmvalidator.addValidation("values[new][END_HOUR]","req","Please select end time");
frmvalidator.addValidation("values[new][END_MINUTE]","req","Please select end time");
frmvalidator.addValidation("values[new][END_M]","req","Please select end time");
}
}
function formcheck_school_setup_grade_levels()
{
var frmvalidator = new Validator("F1");
frmvalidator.addValidation("values[new][TITLE]","maxlen=50", "Max length for title is 50 characters");
frmvalidator.addValidation("values[new][SHORT_NAME]","maxlen=50", "Max length for short name is 50 characters");
frmvalidator.addValidation("values[new][SORT_ORDER]","num", "Sort order allows only numeric value");
frmvalidator.addValidation("values[new][SORT_ORDER]","maxlen=5", "Max length for sort order is 5 digits");
}
function formcheck_student_student()
{
var frmvalidator = new Validator("student");
frmvalidator.addValidation("students[FIRST_NAME]","req","Please enter the first name");
frmvalidator.addValidation("students[FIRST_NAME]","maxlen=100", "Max length for school name is 100 characters");
frmvalidator.addValidation("students[LAST_NAME]","req","Please enter the last name");
frmvalidator.addValidation("students[LAST_NAME]","maxlen=100", "Max length for address is 100 characters");
frmvalidator.addValidation("students[GENDER]","req","Please select gender");
frmvalidator.addValidation("students[ETHNICITY]","req","Please select ethnicity");
frmvalidator.addValidation("assign_student_id","num", "Student ID allows only numeric value");
frmvalidator.addValidation("values[student_enrollment][new][GRADE_ID]","req","Please select a grade");
frmvalidator.addValidation("students[USERNAME]","maxlen=50", "Max length for Username is 50");
frmvalidator.addValidation("students[PASSWORD]","password=8", "Password should be minimum 8 characters with atleast one special character and one number");
frmvalidator.addValidation("students[PASSWORD]","maxlen=20", "Max length for password is 20 characters");
frmvalidator.addValidation("students[EMAIL]","email");
frmvalidator.addValidation("students[PHONE]","phone","Invalid phone number");
frmvalidator.addValidation("values[student_enrollment][new][NEXT_SCHOOL]","req","Please select rolling / retention options");
frmvalidator.addValidation("values[address][ADDRESS]","req","Please enter address");
frmvalidator.addValidation("values[address][CITY]","req","Please enter city");
frmvalidator.addValidation("values[address][STATE]","req","Please enter state");
frmvalidator.addValidation("values[address][ZIPCODE]","req","Please enter zipcode");
frmvalidator.addValidation("values[address][PRIM_STUDENT_RELATION]","req","Relation");
frmvalidator.addValidation("values[address][PRI_FIRST_NAME]","req","Please enter first name");
frmvalidator.addValidation("values[address][PRI_LAST_NAME]","req","Please enter last name");
frmvalidator.addValidation("values[address][SEC_STUDENT_RELATION]","req","Please enter secondary relation");
frmvalidator.addValidation("values[address][SEC_FIRST_NAME]","req","Please enter secondary emergency contact frist name ");
frmvalidator.addValidation("values[address][SEC_LAST_NAME]","req","Please enter secondary emergency contact last name");
frmvalidator.addValidation("values[students_join_people][STUDENT_RELATION]","req","Relation");
frmvalidator.addValidation("values[people][FIRST_NAME]","req","Please enter first name");
frmvalidator.addValidation("values[people][LAST_NAME]","req","Please enter last name");
frmvalidator.addValidation("values[address][ADDRESS]","req","Please enter address");
frmvalidator.addValidation("values[address][PHONE]","ph","Please enter a valid phone number");
frmvalidator.addValidation("values[people][FIRST_NAME]","alphabetic","first name allows only alphabetic value");
frmvalidator.addValidation("values[people][LAST_NAME]","alpha","last name allows only alphabetic value");
frmvalidator.addValidation("students[PHYSICIAN]","req","Please enter the physician name");
frmvalidator.addValidation("students[PHYSICIAN_PHONE]","ph","Phone number cannot not be alphabetic.");
frmvalidator.addValidation("tables[goal][new][GOAL_TITLE]","req","Please enter goal title");
frmvalidator.addValidation("tables[goal][new][GOAL_TITLE]","req","Please enter goal title");
frmvalidator.addValidation("tables[goal][new][GOAL_DESCRIPTION]","req","Please enter goal description");
frmvalidator.addValidation("tables[progress][new][PROGRESS_NAME]","req","Please enter progress period name");
frmvalidator.addValidation("tables[progress][new][PROFICIENCY]","req","Please select proficiency scale");
frmvalidator.addValidation("tables[progress][new][PROGRESS_DESCRIPTION]","req","Please enter progress assessment");
frmvalidator.setAddnlValidationFunction("ValidateDate_Student");
}
function change_pass()
{
var frmvalidator = new Validator("change_password");
frmvalidator.addValidation("old","req","Please enter old password");
frmvalidator.addValidation("new","req","Please enter new password");
frmvalidator.addValidation("retype","req","Please retype password");
frmvalidator.addValidation("new","password=8","Password should be minimum 8 characters with atleast one special character and one number");
}
function ValidateDate_Student()
{
var bm, bd, by ;
var frm = document.forms["student"];
var elem = frm.elements;
for(var i = 0; i < elem.length; i++)
{
if(elem[i].name=="month_students[BIRTHDATE]")
{
bm=elem[i];
}
if(elem[i].name=="day_students[BIRTHDATE]")
{
bd=elem[i];
}
if(elem[i].name=="year_students[BIRTHDATE]")
{
by=elem[i];
}
}
for(var i = 0; i < elem.length; i++)
{
if(elem[i].name=="month_tables[new][START_DATE]")
{
sm=elem[i];
}
if(elem[i].name=="day_tables[new][START_DATE]")
{
sd=elem[i];
}
if(elem[i].name=="year_tables[new][START_DATE]")
{
sy=elem[i];
}
if(elem[i].name=="month_tables[new][END_DATE]")
{
em=elem[i];
}
if(elem[i].name=="day_tables[new][END_DATE]")
{
ed=elem[i];
}
if(elem[i].name=="year_tables[new][END_DATE]")
{
ey=elem[i];
}
}
try
{
if (false==isDate(sm, sd, sy))
{
document.getElementById("divErr").innerHTML="<b><font color=red>"+"Please enter date."+"</font></b>";
sm.focus();
return false;
}
}
catch(err)
{
}
try
{
if (false==isDate(em, ed, ey))
{
document.getElementById("divErr").innerHTML="<b><font color=red>"+"Please enter end date."+"</font></b>";
em.focus();
return false;
}
}
catch(err)
{
}
try
{
if (false==CheckDateGoal(sm, sd, sy, em, ed, ey))
{
em.focus();
return false;
}
}
catch(err)
{
}
//-----
try
{
if (false==CheckValidDateGoal(sm, sd, sy, em, ed, ey))
{
sm.focus();
return false;
}
}
catch(err)
{
}
try
{
if (false==CheckBirthDate(bm, bd, by))
{
bm.focus();
return false;
}
}
catch(err)
{
}
//return true;
//alert("Press a button!");
for(var z = 0; z < elem.length; z++)
{
if(elem[z].name=="students[FIRST_NAME]")
{
var firstnameobj = elem[z];
var firstname =elem[z].value;
}
if(elem[z].name=="students[MIDDLE_NAME]")
{
var middlenameobj = elem[z];
var middlename =elem[z].value;
}
if(elem[z].name=="students[LAST_NAME]")
{
var lastnameobj = elem[z];
var lastname =elem[z].value;
}
if(elem[z].name=="values[student_enrollment][new][GRADE_ID]")
{
var gradeobj= elem[z];
var grade =elem[z].value;
}
var studentbirthday_year = by.value;
var studentbirthday_month = bm.value;
var studentbirthday_day = bd.value;
}
//alert(studentname);
//return false;
if(firstnameobj && middlenameobj && lastnameobj && gradeobj && by && bm && bd)
{
ajax_call('check_duplicate_student.php?fn='+firstname+'&mn='+middlename+'&ln='+lastname+'&gd='+grade+'&byear='+studentbirthday_year+'&bmonth='+studentbirthday_month+'&bday='+studentbirthday_day, studentcheck_match, studentcheck_unmatch);
return false;
}
else
return true;
}
function studentcheck_match(data) {
var response = data;
if(response!=0)
{
var result = confirm("Duplicate student found. There is already a student with the same information. Do you want to proceed?");
if(result==true)
{
document.getElementById("student_isertion").submit();
return true;
}
else
{
return false;
}
}
else
{
document.getElementById("student_isertion").submit();
return true;
}
}
function studentcheck_unmatch (err) {
alert ("Error: " + err);
}
function formcheck_student_studentField_F2()
{
var frmvalidator = new Validator("F2");
frmvalidator.addValidation("tables[new][TITLE]","req","Please enter the title");
frmvalidator.addValidation("values[TITLE]","maxlen=100", "Max length for school name is 100 characters");
frmvalidator.addValidation("tables[new][SORT_ORDER]","num", "sort order code allows only numeric value");
}
function formcheck_student_studentField_F1()
{
var frmvalidator = new Validator("F1");
frmvalidator.addValidation("tables[new][TITLE]","req","Please enter the field name");
frmvalidator.addValidation("tables[new][TYPE]","req","Please select the data type");
frmvalidator.addValidation("tables[new][SORT_ORDER]","num", "sort order allows only numeric value");
}
function formcheck_student_studentField_F1_defalut()
{
var type=document.getElementById('type');
if(type.value=='textarea')
document.getElementById('tables[new][DEFAULT_SELECTION]').disabled=true;
else
document.getElementById('tables[new][DEFAULT_SELECTION]').disabled=false;
}
///////////////////////////////////////// Student Field End ////////////////////////////////////////////////////////////
///////////////////////////////////////// Address Field Start //////////////////////////////////////////////////////////
function formcheck_student_addressField_F2()
{
var frmvalidator = new Validator("F2");
frmvalidator.addValidation("tables[new][TITLE]","req","Please enter the title");
frmvalidator.addValidation("values[TITLE]","maxlen=100", "Max length for school name is 100 characters");
frmvalidator.addValidation("tables[new][SORT_ORDER]","num", "sort order code allows only numeric value");
}
function formcheck_student_addressField_F1()
{
var frmvalidator = new Validator("F1");
frmvalidator.addValidation("tables[new][TITLE]","req","Please enter the field name");
frmvalidator.addValidation("tables[new][TYPE]","req","Please select the Data type");
frmvalidator.addValidation("tables[new][SORT_ORDER]","num", "sort order allows only numeric value");
}
///////////////////////////////////////// Address Field End ////////////////////////////////////////////////////////////
///////////////////////////////////////// Contact Field Start //////////////////////////////////////////////////////////
function formcheck_student_contactField_F2()
{
var frmvalidator = new Validator("F2");
frmvalidator.addValidation("tables[new][TITLE]","req","Please enter the title");
frmvalidator.addValidation("values[TITLE]","maxlen=100", "Max length for school name is 100 characters");
frmvalidator.addValidation("tables[new][SORT_ORDER]","num", "sort order code allows only numeric value");
}
function formcheck_student_contactField_F1()
{
var frmvalidator = new Validator("F1");
frmvalidator.addValidation("tables[new][TITLE]","req","Please enter the field name");
frmvalidator.addValidation("tables[new][TYPE]","req","Please select the data type");
frmvalidator.addValidation("tables[new][SORT_ORDER]","num", "sort order allows only numeric value");
}
function formcheck_user_user(staff_school_chkbox_id){
//alert(par);
var frmvalidator = new Validator("staff");
//frmvalidator.addValidation("month_values[START_DATE]["+1+"]","req","Please Enter start date");
frmvalidator.addValidation("staff[FIRST_NAME]","req","Please enter the first name");
// frmvalidator.addValidation("staff[FIRST_NAME]","alphabetic", "First name allows only alphabetic value");
frmvalidator.addValidation("staff[FIRST_NAME]","maxlen=100", "Max length for first name is 100 characters");
frmvalidator.addValidation("staff[LAST_NAME]","req","Please enter the Last Name");
// frmvalidator.addValidation("staff[LAST_NAME]","alphabetic", "Last name allows only alphabetic value");
frmvalidator.addValidation("staff[LAST_NAME]","maxlen=100", "Max length for Address is 100");
frmvalidator.addValidation("staff[PASSWORD]","password=8", "Password should be minimum 8 characters with one special character and one number");
frmvalidator.addValidation("staff[PROFILE]","req","Please select the user profile");
frmvalidator.addValidation("staff[PHONE]","ph","Please enter a valid telephone number");
return school_check(staff_school_chkbox_id);
}
function school_check(staff_school_chkbox_id)
{
//alert(par);
//alert(document.getElementById('daySelect11').value);
chk='n';
var err='T';
if(staff_school_chkbox_id)
{
for(i=1;i<=staff_school_chkbox_id;i++)
{
if(document.getElementById('staff_SCHOOLS'+i).checked==true)
{
chk='y';
//alert(document.staff.day_values['START_DATE'][i].value);
//alert(document.staff)
sd=document.getElementById('daySelect1'+i).value;
sm=document.getElementById('monthSelect1'+i).value;
sy=document.getElementById('yearSelect1'+i).value;
ed=document.getElementById('daySelect2'+i).value;
em=document.getElementById('monthSelect2'+i).value;
ey=document.getElementById('yearSelect2'+i).value;
//ed=
//alert(sd+sm+sy);
//alert(ed+em+ey);
// if(sm=='' || sd=='' || sy=='')
// {
// err='F';
// break;
// }
// else
// {
var starDate = new Date(sd+"/"+sm+"/"+sy);
var endDate = new Date(ed+"/"+em+"/"+ey);
if (starDate > endDate && endDate!='')
{
err='S';
}
// }
}
}
}
if(chk!='y')
{
var d = $('divErr');
var err = "Please assign at least one school to this new user.";
d.innerHTML="<b><font color=red>"+err+"</font></b>";
return false;
}
else if(chk=='y')
{
// if(err=='F')
// {
// var d = $('divErr');
// var err_date = "Please enter start date to selected school.";
// d.innerHTML="<b><font color=red>"+err_date+"</font></b>";
// return false;
// }
if(err=='S')
{
var d = $('divErr');
var err_stardate = "Start date cannot be greater than end date.";
d.innerHTML="<b><font color=red>"+err_stardate+"</font></b>";
return false;
}
else
{
return true;
}
}
else
{
return true;
}
// else
// {
// var d = $('divErr');
// var err = "Please assign at least one school to this new user asd.";
// d.innerHTML="<b><font color=red>"+err+"</font></b>";
// return false;
// }
}
///////////////////////////////////////// Add User End ////////////////////////////////////////////////////////////
///////////////////////////////////////// User Fields Start //////////////////////////////////////////////////////////
function formcheck_user_userfields_F2()
{
var frmvalidator = new Validator("F2");
frmvalidator.addValidation("tables[new][TITLE]","req","Please enter the title");
frmvalidator.addValidation("tables[new][TITLE]","alphabetic", "Title allows only alphabetic value");
frmvalidator.addValidation("tables[new][TITLE]","maxlen=50", "Max length for title is 100");
}
function formcheck_user_userfields_F1()
{
var frmvalidator1 = new Validator("F1");
frmvalidator1.addValidation("tables[new][TITLE]","req","Please enter the field Name");
frmvalidator1.addValidation("tables[new][TITLE]","alnum", "Field name allows only alphanumeric value");
frmvalidator1.addValidation("tables[new][TITLE]","maxlen=50", "Max length for Field Name is 100");
//frmvalidator1.addValidation("tables[new][SORT_ORDER]","req","Please enter the sort order");
frmvalidator1.addValidation("tables[new][SORT_ORDER]","num", "sort order allows only numeric value");
}
///////////////////////////////////////// User Fields End ////////////////////////////////////////////////////////////
///////////////////////////////////////// User End ////////////////////////////////////////////////////////////
//////////////////////////////////////// Scheduling start ///////////////////////////////////////////////////////
//////////////////////////////////////// Course start ///////////////////////////////////////////////////////
function formcheck_scheduling_course_F4()
{
var frmvalidator = new Validator("F4");
frmvalidator.addValidation("tables[course_subjects][new][TITLE]","req","Please enter the title");
frmvalidator.addValidation("tables[course_subjects][new][TITLE]","maxlen=100", "Max length for title is 100");
}
function formcheck_scheduling_course_F3()
{
var frmvalidator = new Validator("F3");
frmvalidator.addValidation("tables[courses][new][TITLE]","req","Please enter the title");
frmvalidator.addValidation("tables[courses][new][TITLE]","maxlen=50", "Max length for title is 50");
frmvalidator.addValidation("tables[courses][new][SHORT_NAME]","req","Please enter the short name");
frmvalidator.addValidation("tables[courses][new][SHORT_NAME]","maxlen=10", "Max length for short name is 10");
}
function formcheck_scheduling_course_F2()
{
var count;
var check=0;
for(count=1;count<=7;count++)
{
if(document.getElementById("DAYS"+count).checked==true)
check++;
}
if(check==0)
{
document.getElementById("display_meeting_days_chk").innerHTML='<font color="red">Please select atleast one day</font>';
document.getElementById("DAYS1").focus();
return false;
}
else
{
var frmvalidator = new Validator("F2");
frmvalidator.addValidation("tables[course_periods][new][SHORT_NAME]","req","Please enter the short name");
frmvalidator.addValidation("tables[course_periods][new][SHORT_NAME]","maxlen=20", "Max length for short name is 20");
frmvalidator.addValidation("tables[course_periods][new][TEACHER_ID]","req","Please select the teacher");
frmvalidator.addValidation("tables[course_periods][new][ROOM]","req","Please enter the Room");
frmvalidator.addValidation("tables[course_periods][new][ROOM]","maxlen=10", "Max length for room is 10");
frmvalidator.addValidation("tables[course_periods][new][PERIOD_ID]","req","Please select the period");
frmvalidator.addValidation("tables[course_periods][new][MARKING_PERIOD_ID]","req","Please select marking period");
frmvalidator.addValidation("tables[course_periods][new][TOTAL_SEATS]","req","Please input total seats");
frmvalidator.addValidation("tables[course_periods][new][TOTAL_SEATS]","maxlen=10","Max length for seats is 10");
frmvalidator.addValidation("get_status","attendance=0","Cannot take attendance in this period");
// alert(document.forms["F2"]["tables[course_periods][new][DAYS][M]"].value);
}
}
///////////////////////////////////////// Course End ////////////////////////////////////////////////////////
//////////////////////////////////////// Scheduling End ///////////////////////////////////////////////////////
//////////////////////////////////////// Grade Start ///////////////////////////////////////////////////////
function formcheck_grade_grade()
{
var frmvalidator = new Validator("F1");
frmvalidator.addValidation("values[new][TITLE]","maxlen=50", "Max length for title is 50");
frmvalidator.addValidation("values[new][SHORT_NAME]","maxlen=50", "Max length for short name is 50");
frmvalidator.addValidation("values[new][SORT_ORDER]","num", "Sort order allows only numeric value");
frmvalidator.addValidation("values[new][SORT_ORDER]","maxlen=5", "Max length for sort order is 5");
}
function formcheck_honor_roll()
{
var frmvalidator = new Validator("F1");
frmvalidator.addValidation("values[new][TITLE]","maxlen=50", "Max length for Title is 50");
frmvalidator.addValidation("values[new][VALUE]","maxlen=50", "Max length for Short Name is 50");
}
//////////////////////////////////////// Report Card Comment Start ///////////////////////////////////////////////////////
function formcheck_grade_comment()
{
var frmvalidator = new Validator("F1");
frmvalidator.addValidation("values[new][SORT_ORDER]","num", "ID allows only numeric value");
frmvalidator.addValidation("values[new][TITLE]","maxlen=50", "Max length for Comment is 50");
}
//////////////////////////////////////// Report Card Comment End ///////////////////////////////////////////////////////
//////////////////////////////////////// Grade End ///////////////////////////////////////////////////////
///////////////////////////////////////// Eligibility Start ////////////////////////////////////////////////////
///////// Activities Start/////////////////////////////
function formcheck_eligibility_activies()
{
var frmvalidator = new Validator("F1");
frmvalidator.addValidation("values[new][TITLE]","maxlen=50", "Max length for Title is 50");
frmvalidator.setAddnlValidationFunction("ValidateDate_eligibility_activies");
}
function ValidateDate_eligibility_activies()
{
var sm, sd, sy, em, ed, ey, psm, psd, psy, pem, ped, pey ;
var frm = document.forms["F1"];
var elem = frm.elements;
for(var i = 0; i < elem.length; i++)
{
if(elem[i].name=="month_values[new][START_DATE]")
{
sm=elem[i];
}
if(elem[i].name=="day_values[new][START_DATE]")
{
sd=elem[i];
}
if(elem[i].name=="year_values[new][START_DATE]")
{
sy=elem[i];
}
if(elem[i].name=="month_values[new][END_DATE]")
{
em=elem[i];
}
if(elem[i].name=="day_values[new][END_DATE]")
{
ed=elem[i];
}
if(elem[i].name=="year_values[new][END_DATE]")
{
ey=elem[i];
}
}
try
{
if (false==CheckDate(sm, sd, sy, em, ed, ey))
{
em.focus();
return false;
}
}
catch(err)
{
}
try
{
if (false==isDate(psm, psd, psy))
{
alert("Please enter the grade posting start date");
psm.focus();
return false;
}
}
catch(err)
{
}
try
{
if (true==isDate(pem, ped, pey))
{
if (false==CheckDate(psm, psd, psy, pem, ped, pey))
{
pem.focus();
return false;
}
}
}
catch(err)
{
}
return true;
}
///////////////////////////////////////// Activies End ////////////////////////////////////////////////////
///////////////////////////////////////// Entry Times Start ////////////////////////////////////////////////
function formcheck_eligibility_entrytimes()
{
var frmvalidator = new Validator("F1");
frmvalidator.setAddnlValidationFunction("ValidateTime_eligibility_entrytimes");
}
function ValidateTime_eligibility_entrytimes()
{
var sd, sh, sm, sp, ed, eh, em, ep, psm, psd, psy, pem, ped, pey ;
var frm = document.forms["F1"];
var elem = frm.elements;
for(var i = 0; i < elem.length; i++)
{
if(elem[i].name=="values[START_DAY]")
{
sd=elem[i];
}
if(elem[i].name=="values[START_HOUR]")
{
sh=elem[i];
}
if(elem[i].name=="values[START_MINUTE]")
{
sm=elem[i];
}
if(elem[i].name=="values[START_M]")
{
sp=elem[i];
}
if(elem[i].name=="values[END_DAY]")
{
ed=elem[i];
}
if(elem[i].name=="values[END_HOUR]")
{
eh=elem[i];
}
if(elem[i].name=="values[END_MINUTE]")
{
em=elem[i];
}
if(elem[i].name=="values[END_M]")
{
ep=elem[i];
}
}
try
{
if (false==CheckTime(sd, sh, sm, sp, ed, eh, em, ep))
{
sh.focus();
return false;
}
}
catch(err)
{
}
try
{
if (true==isDate(pem, ped, pey))
{
if (false==CheckDate(psm, psd, psy, pem, ped, pey))
{
pem.focus();
return false;
}
}
}
catch(err)
{
}
return true;
}
///////////////////////////////////////// Entry Times End //////////////////////////////////////////////////
function formcheck_mass_drop()
{
if(document.getElementById("course_div").innerHTML=='')
{
alert("Please choose a course period to drop");
return false;
}
else
return true;
}
function formcheck_attendance_category()
{
var frmvalidator = new Validator("F1");
frmvalidator.addValidation("new_category_title","req","Please enter attendance category Name");
frmvalidator.addValidation("new_category_title","maxlen=50", "Max length for category name is 50");
}
function formcheck_attendance_codes()
{
if(document.getElementById("title").value!='')
{
var frmvalidator = new Validator("F1");
frmvalidator.addValidation("values[new][STATE_CODE]","req","Please select state code");
}
}
//-------------------------------------------------assignments Title Validation Starts---------------------------------------------
function formcheck_assignments()
{
var frmvalidator = new Validator("F3");
frmvalidator.addValidation("tables[new][TITLE]","req","Title cannot be blank");
frmvalidator.addValidation("month_tables[new][ASSIGNED_DATE]","req","Month cannot be blank");
frmvalidator.addValidation("day_tables[new][ASSIGNED_DATE]","req","Day cannot be blank");
frmvalidator.addValidation("year_tables[new][ASSIGNED_DATE]","req","Year cannot be blank");
frmvalidator.addValidation("month_tables[new][DUE_DATE]","req","Month cannot be blank");
frmvalidator.addValidation("day_tables[new][DUE_DATE]","req","Day cannot be blank");
frmvalidator.addValidation("year_tables[new][DUE_DATE]","req","Year cannot be blank");
}
//-------------------------------------------------assignments Title Validation Ends---------------------------------------------
function passwordStrength(password)
{
document.getElementById("passwordStrength").style.display = "none";
var desc = new Array();
desc[0] = "Very Weak";
desc[1] = "Weak";
desc[2] = "Good";
desc[3] = "Strong";
desc[4] = "Strongest";
//if password bigger than 7 give 1 point
if (password.length > 0)
{
document.getElementById("passwordStrength").style.display = "block" ;
document.getElementById("passwordStrength").style.backgroundColor = "#cccccc" ;
document.getElementById("passwordStrength").innerHTML = desc[0] ;
}
//if password has at least one number give 1 point
if (password.match(/\d+/) && password.length > 5)
{
document.getElementById("passwordStrength").style.display = "block" ;
document.getElementById("passwordStrength").style.backgroundColor = "#ff0000" ;
document.getElementById("passwordStrength").innerHTML = desc[1] ;
}
//if password has at least one special caracther give 1 point
if (password.match(/\d+/) && password.length > 7 && password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/) )
{
document.getElementById("passwordStrength").style.display = "block" ;
document.getElementById("passwordStrength").style.backgroundColor = "#ff5f5f" ;
document.getElementById("passwordStrength").innerHTML = desc[2] ;
}
//if password has both lower and uppercase characters give 1 point
if (password.match(/\d+/) && password.length > 10 && password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/) && ( password.match(/[A-Z]/) ) )
{
document.getElementById("passwordStrength").style.display = "block" ;
document.getElementById("passwordStrength").style.backgroundColor = "#56e500" ;
document.getElementById("passwordStrength").innerHTML = desc[3] ;
}
//if password bigger than 12 give another 1 point
if (password.match(/\d+/) && password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/) && ( password.match(/[a-z]/) ) && ( password.match(/[A-Z]/) ) && password.length > 12)
{
document.getElementById("passwordStrength").style.display = "block" ;
document.getElementById("passwordStrength").style.backgroundColor = "#4dcd00" ;
document.getElementById("passwordStrength").innerHTML = desc[4] ;
}
}
function passwordMatch()
{
document.getElementById("passwordMatch").style.display = "none" ;
var new_pass = document.getElementById("new_pass").value;
var vpass = document.getElementById("ver_pass").value;
if(new_pass || vpass)
{
if(new_pass==vpass)
{
document.getElementById("passwordMatch").style.display = "block" ;
document.getElementById("passwordMatch").style.backgroundColor = "#4dcd00" ;
document.getElementById("passwordMatch").innerHTML = "Password Match" ;
}
if(new_pass!=vpass)
{
document.getElementById("passwordMatch").style.display = "block" ;
document.getElementById("passwordMatch").style.backgroundColor = "#ff0000" ;
document.getElementById("passwordMatch").innerHTML = "Password MisMatch" ;
}
}
}
function pass_check()
{
if(document.getElementById("new_pass").value==document.getElementById("ver_pass").value)
{
var new_pass = document.getElementById("new_pass").value;
// var ver_pass = document.getElementById("ver_pass").value;
if(new_pass.length < 7 || (new_pass.length > 7 && !new_pass.match((/\d+/))) || (new_pass.length > 7 && !new_pass.match((/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/))))
{
document.getElementById('divErr').innerHTML="<b><font color=red>Password should be minimum 8 characters with atleast one number and one special character</font></b>";
return false;
}
return true;
}
else
{
document.getElementById('divErr').innerHTML="<b><font color=red>New Password MisMatch</font></b>";
return false;
}
}
function reenroll()
{
if(document.getElementById("monthSelect1").value=='' || document.getElementById("daySelect1").value=='' || document.getElementById("yearSelect1").value=='')
{
document.getElementById('divErr').innerHTML="<b><font color=red>Please Enter a Proper Date</font></b>";
return false;
}
if(document.getElementById("grade_id").value=='')
{
document.getElementById('divErr').innerHTML="<b><font color=red>Please Select a Grade Level</font></b>";
return false;
}
if(document.getElementById("en_code").value=='')
{
document.getElementById('divErr').innerHTML="<b><font color=red>Please Select an Enrollment Code</font></b>";
return false;
}
else
return true;
}
| {
"content_hash": "90f69dc1b62668f045e1f50249c9c804",
"timestamp": "",
"source": "github",
"line_count": 1502,
"max_line_length": 238,
"avg_line_length": 30.089214380825567,
"alnum_prop": 0.5650971367880692,
"repo_name": "shamim8888/SMSlib-ParallelPort",
"id": "eedf6a2f4106e9a511a303a778a91980ed2c907c",
"size": "45194",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "opensis1/js/validation.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "32369"
},
{
"name": "CSS",
"bytes": "377271"
},
{
"name": "Java",
"bytes": "1596773"
},
{
"name": "JavaScript",
"bytes": "958712"
},
{
"name": "Makefile",
"bytes": "504"
},
{
"name": "PHP",
"bytes": "9860477"
},
{
"name": "Perl",
"bytes": "41696"
},
{
"name": "Ruby",
"bytes": "88985"
},
{
"name": "Rust",
"bytes": "101"
},
{
"name": "Scala",
"bytes": "362"
},
{
"name": "Shell",
"bytes": "23973"
}
],
"symlink_target": ""
} |
<?php
/*
* By adding type hints and enabling strict type checking, code can become
* easier to read, self-documenting and reduce the number of potential bugs.
* By default, type declarations are non-strict, which means they will attempt
* to change the original type to match the type specified by the
* type-declaration.
*
* In other words, if you pass a string to a function requiring a float,
* it will attempt to convert the string value to a float.
*
* To enable strict mode, a single declare directive must be placed at the top
* of the file.
* This means that the strictness of typing is configured on a per-file basis.
* This directive not only affects the type declarations of parameters, but also
* a function's return type.
*
* For more info review the Concept on strict type checking in the PHP track
* <link>.
*
* To disable strict typing, comment out the directive below.
*/
declare(strict_types=1);
class PhoneNumber
{
private $number;
public function __construct(string $number)
{
$this->number = $this->clean($number);
}
public function number(): string
{
return $this->number;
}
public function areaCode(): string
{
return substr($this->number, 0, 3);
}
public function prettyPrint(): string
{
return '(' . $this->areaCode() . ') ' . $this->prefix() . '-' . $this->lineNumber();
}
private function clean(string $number): string
{
return $this->validate(preg_replace('/[^0-9a-z@:!]+/i', '', $number));
}
private function validate(string $number): string
{
if (strlen($number) === 11 && $number[0] !== '1') {
throw new InvalidArgumentException('11 digits must start with 1');
}
if (strlen($number) > 11) {
throw new InvalidArgumentException('more than 11 digits');
}
if (0 !== preg_match('/[A-z]/', $number)) {
throw new InvalidArgumentException('letters not permitted');
}
if (0 !== preg_match('/[@:!]/', $number)) {
throw new InvalidArgumentException('punctuations not permitted');
}
if (strlen($number) === 11) {
$number = preg_replace('/^1/', '', $number);
}
if (strlen($number) !== 10) {
throw new InvalidArgumentException('incorrect number of digits');
}
if ($number[0] === '0') {
throw new InvalidArgumentException('area code cannot start with zero');
}
if ($number[0] === '1') {
throw new InvalidArgumentException('area code cannot start with one');
}
if ($number[3] === '0') {
throw new InvalidArgumentException('exchange code cannot start with zero');
}
if ($number[3] === '1') {
throw new InvalidArgumentException('exchange code cannot start with one');
}
return $number;
}
private function prefix(): string
{
return substr($this->number, 3, 3);
}
private function lineNumber(): string
{
return substr($this->number, 6, 4);
}
}
| {
"content_hash": "5adade78fbb699666c8f8d2fd26c758a",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 92,
"avg_line_length": 28.545454545454547,
"alnum_prop": 0.5949044585987261,
"repo_name": "exercism/xphp",
"id": "04c2e101f491ff15077af74d5f7fd01445fdeb40",
"size": "3140",
"binary": false,
"copies": "1",
"ref": "refs/heads/dependabot/github_actions/shivammathur/setup-php-a72a638da42bc48de8bd8028b0e36fa6f66151cc",
"path": "exercises/practice/phone-number/.meta/example.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "2482"
},
{
"name": "PHP",
"bytes": "207102"
},
{
"name": "Shell",
"bytes": "640"
}
],
"symlink_target": ""
} |
package x509
import (
"encoding/pem"
"strings"
)
// Roots is a set of certificates.
type CertPool struct {
bySubjectKeyId map[string][]int
byName map[string][]int
certs []*Certificate
}
// NewCertPool returns a new, empty CertPool.
func NewCertPool() *CertPool {
return &CertPool{
make(map[string][]int),
make(map[string][]int),
nil,
}
}
func nameToKey(name *Name) string {
return strings.Join(name.Country, ",") + "/" + strings.Join(name.Organization, ",") + "/" + strings.Join(name.OrganizationalUnit, ",") + "/" + name.CommonName
}
// findVerifiedParents attempts to find certificates in s which have signed the
// given certificate. If no such certificate can be found or the signature
// doesn't match, it returns nil.
func (s *CertPool) findVerifiedParents(cert *Certificate) (parents []int) {
var candidates []int
if len(cert.AuthorityKeyId) > 0 {
candidates = s.bySubjectKeyId[string(cert.AuthorityKeyId)]
}
if len(candidates) == 0 {
candidates = s.byName[nameToKey(&cert.Issuer)]
}
for _, c := range candidates {
if cert.CheckSignatureFrom(s.certs[c]) == nil {
parents = append(parents, c)
}
}
return
}
// AddCert adds a certificate to a pool.
func (s *CertPool) AddCert(cert *Certificate) {
if cert == nil {
panic("adding nil Certificate to CertPool")
}
// Check that the certificate isn't being added twice.
for _, c := range s.certs {
if c.Equal(cert) {
return
}
}
n := len(s.certs)
s.certs = append(s.certs, cert)
if len(cert.SubjectKeyId) > 0 {
keyId := string(cert.SubjectKeyId)
s.bySubjectKeyId[keyId] = append(s.bySubjectKeyId[keyId], n)
}
name := nameToKey(&cert.Subject)
s.byName[name] = append(s.byName[name], n)
}
// AppendCertsFromPEM attempts to parse a series of PEM encoded root
// certificates. It appends any certificates found to s and returns true if any
// certificates were successfully parsed.
//
// On many Linux systems, /etc/ssl/cert.pem will contains the system wide set
// of root CAs in a format suitable for this function.
func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool) {
for len(pemCerts) > 0 {
var block *pem.Block
block, pemCerts = pem.Decode(pemCerts)
if block == nil {
break
}
if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
continue
}
cert, err := ParseCertificate(block.Bytes)
if err != nil {
continue
}
s.AddCert(cert)
ok = true
}
return
}
| {
"content_hash": "536a4d1818d75fcddf7908a62f1afb7c",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 159,
"avg_line_length": 24.168316831683168,
"alnum_prop": 0.6808684965178206,
"repo_name": "SDpower/golang",
"id": "c295fd97e8d4311e6f6ee4596e12c52cf55d161e",
"size": "2601",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/pkg/crypto/x509/cert_pool.go",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
"""improve mssql compatibility
Revision ID: 83f031fd9f1c
Revises: ccde3e26fe78
Create Date: 2021-04-06 12:22:02.197726
"""
from collections import defaultdict
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mssql
# revision identifiers, used by Alembic.
revision = '83f031fd9f1c'
down_revision = 'ccde3e26fe78'
branch_labels = None
depends_on = None
def is_table_empty(conn, table_name):
"""
This function checks if the MS SQL table is empty
:param conn: SQL connection object
:param table_name: table name
:return: Booelan indicating if the table is present
"""
return conn.execute(f'select TOP 1 * from {table_name}').first() is None
def get_table_constraints(conn, table_name):
"""
This function return primary and unique constraint
along with column name. some tables like task_instance
is missing primary key constraint name and the name is
auto-generated by sql server. so this function helps to
retrieve any primary or unique constraint name.
:param conn: sql connection object
:param table_name: table name
:return: a dictionary of ((constraint name, constraint type), column name) of table
:rtype: defaultdict(list)
"""
query = f"""SELECT tc.CONSTRAINT_NAME , tc.CONSTRAINT_TYPE, ccu.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc
JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS ccu ON ccu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
WHERE tc.TABLE_NAME = '{table_name}' AND
(tc.CONSTRAINT_TYPE = 'PRIMARY KEY' or UPPER(tc.CONSTRAINT_TYPE) = 'UNIQUE')
"""
result = conn.execute(query).fetchall()
constraint_dict = defaultdict(list)
for constraint, constraint_type, column in result:
constraint_dict[(constraint, constraint_type)].append(column)
return constraint_dict
def drop_column_constraints(operator, column_name, constraint_dict):
"""
Drop a primary key or unique constraint
:param operator: batch_alter_table for the table
:param constraint_dict: a dictionary of ((constraint name, constraint type), column name) of table
"""
for constraint, columns in constraint_dict.items():
if column_name in columns:
if constraint[1].lower().startswith("primary"):
operator.drop_constraint(constraint[0], type_='primary')
elif constraint[1].lower().startswith("unique"):
operator.drop_constraint(constraint[0], type_='unique')
def create_constraints(operator, column_name, constraint_dict):
"""
Create a primary key or unique constraint
:param operator: batch_alter_table for the table
:param constraint_dict: a dictionary of ((constraint name, constraint type), column name) of table
"""
for constraint, columns in constraint_dict.items():
if column_name in columns:
if constraint[1].lower().startswith("primary"):
operator.create_primary_key(constraint_name=constraint[0], columns=columns)
elif constraint[1].lower().startswith("unique"):
operator.create_unique_constraint(constraint_name=constraint[0], columns=columns)
def _use_date_time2(conn):
result = conn.execute(
"""SELECT CASE WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion'))
like '8%' THEN '2000' WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion'))
like '9%' THEN '2005' ELSE '2005Plus' END AS MajorVersion"""
).fetchone()
mssql_version = result[0]
return mssql_version not in ("2000", "2005")
def _is_timestamp(conn, table_name, column_name):
query = f"""SELECT
TYPE_NAME(C.USER_TYPE_ID) AS DATA_TYPE
FROM SYS.COLUMNS C
JOIN SYS.TYPES T
ON C.USER_TYPE_ID=T.USER_TYPE_ID
WHERE C.OBJECT_ID=OBJECT_ID('{table_name}') and C.NAME='{column_name}';
"""
column_type = conn.execute(query).fetchone()[0]
return column_type == "timestamp"
def recreate_mssql_ts_column(conn, op, table_name, column_name):
"""
Drop the timestamp column and recreate it as
datetime or datetime2(6)
"""
if _is_timestamp(conn, table_name, column_name) and is_table_empty(conn, table_name):
with op.batch_alter_table(table_name) as batch_op:
constraint_dict = get_table_constraints(conn, table_name)
drop_column_constraints(batch_op, column_name, constraint_dict)
batch_op.drop_column(column_name=column_name)
if _use_date_time2(conn):
batch_op.add_column(sa.Column(column_name, mssql.DATETIME2(precision=6), nullable=False))
else:
batch_op.add_column(sa.Column(column_name, mssql.DATETIME, nullable=False))
create_constraints(batch_op, column_name, constraint_dict)
def alter_mssql_datetime_column(conn, op, table_name, column_name, nullable):
"""Update the datetime column to datetime2(6)"""
if _use_date_time2(conn):
op.alter_column(
table_name=table_name,
column_name=column_name,
type_=mssql.DATETIME2(precision=6),
nullable=nullable,
)
def alter_mssql_datetime2_column(conn, op, table_name, column_name, nullable):
"""Update the datetime2(6) column to datetime"""
if _use_date_time2(conn):
op.alter_column(
table_name=table_name, column_name=column_name, type_=mssql.DATETIME, nullable=nullable
)
def _get_timestamp(conn):
if _use_date_time2(conn):
return mssql.DATETIME2(precision=6)
else:
return mssql.DATETIME
def upgrade():
"""Improve compatibility with MSSQL backend"""
conn = op.get_bind()
if conn.dialect.name != 'mssql':
return
recreate_mssql_ts_column(conn, op, 'dag_code', 'last_updated')
recreate_mssql_ts_column(conn, op, 'rendered_task_instance_fields', 'execution_date')
alter_mssql_datetime_column(conn, op, 'serialized_dag', 'last_updated', False)
op.alter_column(table_name="xcom", column_name="timestamp", type_=_get_timestamp(conn), nullable=False)
with op.batch_alter_table('task_reschedule') as task_reschedule_batch_op:
task_reschedule_batch_op.alter_column(
column_name='end_date', type_=_get_timestamp(conn), nullable=False
)
task_reschedule_batch_op.alter_column(
column_name='reschedule_date', type_=_get_timestamp(conn), nullable=False
)
task_reschedule_batch_op.alter_column(
column_name='start_date', type_=_get_timestamp(conn), nullable=False
)
with op.batch_alter_table('task_fail') as task_fail_batch_op:
task_fail_batch_op.drop_index('idx_task_fail_dag_task_date')
task_fail_batch_op.alter_column(
column_name="execution_date", type_=_get_timestamp(conn), nullable=False
)
task_fail_batch_op.create_index(
'idx_task_fail_dag_task_date', ['dag_id', 'task_id', 'execution_date'], unique=False
)
with op.batch_alter_table('task_instance') as task_instance_batch_op:
task_instance_batch_op.drop_index('ti_state_lkp')
task_instance_batch_op.create_index(
'ti_state_lkp', ['dag_id', 'task_id', 'execution_date', 'state'], unique=False
)
constraint_dict = get_table_constraints(conn, 'dag_run')
for constraint, columns in constraint_dict.items():
if 'dag_id' in columns:
if constraint[1].lower().startswith("unique"):
op.drop_constraint(constraint[0], 'dag_run', type_='unique')
# create filtered indexes
conn.execute(
"""CREATE UNIQUE NONCLUSTERED INDEX idx_not_null_dag_id_execution_date
ON dag_run(dag_id,execution_date)
WHERE dag_id IS NOT NULL and execution_date is not null"""
)
conn.execute(
"""CREATE UNIQUE NONCLUSTERED INDEX idx_not_null_dag_id_run_id
ON dag_run(dag_id,run_id)
WHERE dag_id IS NOT NULL and run_id is not null"""
)
def downgrade():
"""Reverse MSSQL backend compatibility improvements"""
conn = op.get_bind()
if conn.dialect.name != 'mssql':
return
alter_mssql_datetime2_column(conn, op, 'serialized_dag', 'last_updated', False)
op.alter_column(table_name="xcom", column_name="timestamp", type_=_get_timestamp(conn), nullable=True)
with op.batch_alter_table('task_reschedule') as task_reschedule_batch_op:
task_reschedule_batch_op.alter_column(
column_name='end_date', type_=_get_timestamp(conn), nullable=True
)
task_reschedule_batch_op.alter_column(
column_name='reschedule_date', type_=_get_timestamp(conn), nullable=True
)
task_reschedule_batch_op.alter_column(
column_name='start_date', type_=_get_timestamp(conn), nullable=True
)
with op.batch_alter_table('task_fail') as task_fail_batch_op:
task_fail_batch_op.drop_index('idx_task_fail_dag_task_date')
task_fail_batch_op.alter_column(
column_name="execution_date", type_=_get_timestamp(conn), nullable=False
)
task_fail_batch_op.create_index(
'idx_task_fail_dag_task_date', ['dag_id', 'task_id', 'execution_date'], unique=False
)
with op.batch_alter_table('task_instance') as task_instance_batch_op:
task_instance_batch_op.drop_index('ti_state_lkp')
task_instance_batch_op.create_index(
'ti_state_lkp', ['dag_id', 'task_id', 'execution_date'], unique=False
)
op.create_unique_constraint('UQ__dag_run__dag_id_run_id', 'dag_run', ['dag_id', 'run_id'])
op.create_unique_constraint('UQ__dag_run__dag_id_execution_date', 'dag_run', ['dag_id', 'execution_date'])
op.drop_index('idx_not_null_dag_id_execution_date', table_name='dag_run')
op.drop_index('idx_not_null_dag_id_run_id', table_name='dag_run')
| {
"content_hash": "d6181c0611b479d63e41e727c37c1ccf",
"timestamp": "",
"source": "github",
"line_count": 237,
"max_line_length": 110,
"avg_line_length": 41.76371308016878,
"alnum_prop": 0.6563952313598707,
"repo_name": "apache/incubator-airflow",
"id": "daaf711b4c79fc0c217ee487aa19406924e10c39",
"size": "10686",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "airflow/migrations/versions/83f031fd9f1c_improve_mssql_compatibility.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "69070"
},
{
"name": "Dockerfile",
"bytes": "2001"
},
{
"name": "HTML",
"bytes": "283783"
},
{
"name": "JavaScript",
"bytes": "1387552"
},
{
"name": "Mako",
"bytes": "1284"
},
{
"name": "Python",
"bytes": "5482822"
},
{
"name": "Shell",
"bytes": "40957"
}
],
"symlink_target": ""
} |
/*
* Generated by SGWrapperGen - DO NOT EDIT!
*
* SwinGame wrapper for C - Sprites
*
* Wrapping sgSprites.pas
*/
#ifndef sgSprites
#define sgSprites
#include <stdint.h>
#ifndef __cplusplus
#include <stdbool.h>
#endif
#include "Types.h"
void call_for_all_sprites(sprite_function fn);
void call_on_sprite_event(sprite_event_handler handler);
point2d center_point(sprite s);
sprite create_basic_sprite(bitmap layer);
sprite create_basic_sprite_named(const char *name, bitmap layer);
sprite create_sprite_with_bitmap_and_animation_name(const char *bitmapName, const char *animationName);
sprite create_sprite_with_animation(bitmap layer, animation_script ani);
sprite create_sprite_with_animation_named(const char *name, bitmap layer, animation_script ani);
void create_sprite_pack(const char *name);
void current_sprite_pack(char *result);
void draw_all_sprites();
void draw_sprite(sprite s);
void draw_sprite_offset_point(sprite s, const point2d *position);
void draw_sprite_offset_point_byval(sprite s, const point2d position);
void draw_sprite_offset_xy(sprite s, int32_t xOffset, int32_t yOffset);
void free_sprite(sprite *s);
bool has_sprite(const char *name);
bool has_sprite_pack(const char *name);
void move_sprite(sprite s);
void move_sprite_vec(sprite s, const vector *distance);
void move_sprite_vec_byval(sprite s, const vector distance);
void move_sprite_pct(sprite s, float pct);
void move_sprite_vec_pct(sprite s, const vector *distance, float pct);
void move_sprite_vec_pct_byval(sprite s, const vector distance, float pct);
void move_sprite_to(sprite s, int32_t x, int32_t y);
void release_all_sprites();
void release_sprite(const char *name);
void select_sprite_pack(const char *name);
int32_t sprite_add_layer(sprite s, bitmap newLayer, const char *layerName);
void sprite_add_to_velocity(sprite s, const vector *value);
void sprite_add_to_velocity_byval(sprite s, const vector value);
void sprite_add_value(sprite s, const char *name);
void sprite_add_value_with_initial_value(sprite s, const char *name, float initVal);
point2d sprite_anchor_point(sprite s);
bool sprite_animation_has_ended(sprite s);
void sprite_animation_name(sprite s, char *result);
void sprite_bring_layer_forward(sprite s, int32_t visibleLayer);
void sprite_bring_layer_to_front(sprite s, int32_t visibleLayer);
void sprite_call_on_event(sprite s, sprite_event_handler handler);
circle sprite_circle(sprite s);
bitmap sprite_collision_bitmap(sprite s);
circle sprite_collision_circle(sprite s);
collision_test_kind sprite_collision_kind(sprite s);
rectangle sprite_collision_rectangle(sprite s);
int32_t sprite_current_cell(sprite s);
rectangle sprite_current_cell_rectangle(sprite s);
float sprite_dx(sprite s);
float sprite_dy(sprite s);
float sprite_heading(sprite s);
int32_t sprite_height(sprite s);
void sprite_hide_layer_named(sprite s, const char *name);
void sprite_hide_layer(sprite s, int32_t id);
bitmap sprite_layer_named(sprite s, const char *name);
bitmap sprite_layer_at_idx(sprite s, int32_t idx);
circle sprite_layer_circle(sprite s, int32_t idx);
circle sprite_layer_named_circle(sprite s, const char *name);
int32_t sprite_layer_count(sprite s);
int32_t sprite_layer_named_height(sprite s, const char *name);
int32_t sprite_layer_height(sprite s, int32_t idx);
int32_t sprite_layer_index(sprite s, const char *name);
void sprite_layer_name(sprite s, int32_t idx, char *result);
point2d sprite_layer_offset_named(sprite s, const char *name);
point2d sprite_layer_offset(sprite s, int32_t idx);
rectangle sprite_layer_rectangle(sprite s, int32_t idx);
rectangle sprite_layer_named_rectangle(sprite s, const char *name);
int32_t sprite_layer_width(sprite s, int32_t idx);
int32_t sprite_layer_named_width(sprite s, const char *name);
matrix2d sprite_location_matrix(sprite s);
float sprite_mass(sprite s);
bool sprite_move_from_anchor_point(sprite s);
void sprite_move_to(sprite s, const point2d *pt, int32_t takingSeconds);
void sprite_move_to_byval(sprite s, const point2d pt, int32_t takingSeconds);
void sprite_name(sprite sprt, char *result);
sprite sprite_named(const char *name);
bool sprite_offscreen(sprite s);
bool sprite_on_screen_at_point(sprite s, const point2d *pt);
bool sprite_on_screen_at_point_byval(sprite s, const point2d pt);
bool sprite_on_screen_at(sprite s, int32_t x, int32_t y);
point2d sprite_position(sprite s);
void sprite_replay_animation(sprite s);
void replay_animation_with_sound(sprite s, bool withSound);
float sprite_rotation(sprite s);
float sprite_scale(sprite s);
rectangle sprite_screen_rectangle(sprite s);
void sprite_send_layer_backward(sprite s, int32_t visibleLayer);
void sprite_send_layer_to_back(sprite s, int32_t visibleLayer);
void sprite_set_anchor_point(sprite s, point2d pt);
void sprite_set_collision_bitmap(sprite s, bitmap bmp);
void sprite_set_collision_kind(sprite s, collision_test_kind value);
void sprite_set_dx(sprite s, float value);
void sprite_set_dy(sprite s, float value);
void sprite_set_heading(sprite s, float value);
void sprite_set_layer_offset(sprite s, int32_t idx, const point2d *value);
void sprite_set_layer_offset_byval(sprite s, int32_t idx, const point2d value);
void sprite_set_layer_offset_named(sprite s, const char *name, const point2d *value);
void sprite_set_layer_offset_named_byval(sprite s, const char *name, const point2d value);
void sprite_set_mass(sprite s, float value);
void sprite_set_move_from_anchor_point(sprite s, bool value);
void sprite_set_position(sprite s, const point2d *value);
void sprite_set_position_byval(sprite s, const point2d value);
void sprite_set_rotation(sprite s, float value);
void sprite_set_scale(sprite s, float value);
void sprite_set_speed(sprite s, float value);
void sprite_set_value_named(sprite s, const char *name, float val);
void sprite_set_value(sprite s, int32_t idx, float val);
void sprite_set_velocity(sprite s, const vector *value);
void sprite_set_velocity_byval(sprite s, const vector value);
void sprite_set_x(sprite s, float value);
void sprite_set_y(sprite s, float value);
int32_t sprite_show_layer(sprite s, int32_t id);
int32_t sprite_show_layer_named(sprite s, const char *name);
float sprite_speed(sprite s);
void sprite_start_animation(sprite s, int32_t idx);
void sprite_start_animation_named(sprite s, const char *named);
void sprite_start_animation_named_with_sound(sprite s, const char *named, bool withSound);
void sprite_start_animation_with_sound(sprite s, int32_t idx, bool withSound);
void sprite_stop_calling_on_event(sprite s, sprite_event_handler handler);
void sprite_toggle_layer_visible(sprite s, int32_t id);
void sprite_toggle_layer_named_visible(sprite s, const char *name);
float sprite_value(sprite s, int32_t index);
float sprite_value_named(sprite s, const char *name);
int32_t sprite_value_count(sprite s);
void sprite_value_name(sprite s, int32_t idx, char *result);
vector sprite_velocity(sprite s);
int32_t sprite_visible_index_of_layer(sprite s, int32_t id);
int32_t sprite_visible_index_of_layer_named(sprite s, const char *name);
int32_t sprite_visible_layer(sprite s, int32_t idx);
int32_t sprite_visible_layer_count(sprite s);
int32_t sprite_visible_layer_id(sprite s, int32_t idx);
int32_t sprite_width(sprite s);
float sprite_x(sprite s);
float sprite_y(sprite s);
void stop_calling_on_sprite_event(sprite_event_handler handler);
void update_all_sprites();
void update_all_sprites_pct(float pct);
void update_sprite(sprite s);
void update_sprite_with_sound(sprite s, bool withSound);
void update_sprite_percent(sprite s, float pct);
void update_sprite_pct_with_sound(sprite s, float pct, bool withSound);
void update_sprite_animation(sprite s);
void update_sprite_animation_with_sound(sprite s, bool withSound);
void update_sprite_animation_percent(sprite s, float pct);
void update_sprite_animation_pct_with_sound(sprite s, float pct, bool withSound);
vector vector_from_center_sprite_to_point(sprite s, const point2d *pt);
vector vector_from_center_sprite_to_point_byval(sprite s, const point2d pt);
vector vector_from_to(sprite s1, sprite s2);
#ifdef __cplusplus
// C++ overloaded functions
sprite create_sprite(bitmap layer);
sprite create_sprite(const char *name, bitmap layer);
sprite create_sprite(const char *bitmapName, const char *animationName);
sprite create_sprite(bitmap layer, animation_script ani);
sprite create_sprite(const char *name, bitmap layer, animation_script ani);
void draw_sprite(sprite s, const point2d &position);
void draw_sprite(sprite s, int32_t xOffset, int32_t yOffset);
void free_sprite(sprite &s);
void move_sprite(sprite s, const vector &distance);
void move_sprite(sprite s, float pct);
void move_sprite(sprite s, const vector &distance, float pct);
void sprite_add_to_velocity(sprite s, const vector &value);
void sprite_add_value(sprite s, const char *name, float initVal);
void sprite_hide_layer(sprite s, const char *name);
bitmap sprite_layer(sprite s, const char *name);
bitmap sprite_layer(sprite s, int32_t idx);
circle sprite_layer_circle(sprite s, const char *name);
int32_t sprite_layer_height(sprite s, const char *name);
point2d sprite_layer_offset(sprite s, const char *name);
rectangle sprite_layer_rectangle(sprite s, const char *name);
int32_t sprite_layer_width(sprite s, const char *name);
void sprite_move_to(sprite s, const point2d &pt, int32_t takingSeconds);
bool sprite_on_screen_at(sprite s, const point2d &pt);
void sprite_replay_animation(sprite s, bool withSound);
void sprite_set_layer_offset(sprite s, int32_t idx, const point2d &value);
void sprite_set_layer_offset(sprite s, const char *name, const point2d &value);
void sprite_set_position(sprite s, const point2d &value);
void sprite_set_value(sprite s, const char *name, float val);
void sprite_set_velocity(sprite s, const vector &value);
int32_t sprite_show_layer(sprite s, const char *name);
void sprite_start_animation(sprite s, const char *named);
void sprite_start_animation(sprite s, const char *named, bool withSound);
void sprite_start_animation(sprite s, int32_t idx, bool withSound);
void sprite_toggle_layer_visible(sprite s, const char *name);
float sprite_value(sprite s, const char *name);
int32_t sprite_visible_index_of_layer(sprite s, const char *name);
void update_all_sprites(float pct);
void update_sprite(sprite s, bool withSound);
void update_sprite(sprite s, float pct);
void update_sprite(sprite s, float pct, bool withSound);
void update_sprite_animation(sprite s, bool withSound);
void update_sprite_animation(sprite s, float pct);
void update_sprite_animation(sprite s, float pct, bool withSound);
vector vector_from_center_sprite_to_point(sprite s, const point2d &pt);
#endif
#endif
| {
"content_hash": "f55245619849c700272c619dfb300774",
"timestamp": "",
"source": "github",
"line_count": 217,
"max_line_length": 103,
"avg_line_length": 49.02304147465438,
"alnum_prop": 0.771197593532619,
"repo_name": "SinZ163/IntroToProgramming_Project",
"id": "75a994e2f72a1c99d75d565b129ab39e25962d54",
"size": "10638",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Project_Client/lib/Sprites.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "531"
},
{
"name": "C",
"bytes": "772557"
},
{
"name": "C++",
"bytes": "1945631"
},
{
"name": "Shell",
"bytes": "5163"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_socket::message_end_of_record</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../basic_socket.html" title="basic_socket">
<link rel="prev" href="message_do_not_route.html" title="basic_socket::message_do_not_route">
<link rel="next" href="message_flags.html" title="basic_socket::message_flags">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="message_do_not_route.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_socket.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="message_flags.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_asio.reference.basic_socket.message_end_of_record"></a><a class="link" href="message_end_of_record.html" title="basic_socket::message_end_of_record">basic_socket::message_end_of_record</a>
</h4></div></div></div>
<p>
<span class="emphasis"><em>Inherited from socket_base.</em></span>
</p>
<p>
<a class="indexterm" name="idp45752640"></a>
Specifies that the data marks the end
of a record.
</p>
<pre class="programlisting"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">int</span> <span class="identifier">message_end_of_record</span> <span class="special">=</span> <span class="identifier">implementation_defined</span><span class="special">;</span>
</pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2015 Christopher M.
Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="message_do_not_route.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_socket.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="message_flags.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "99cfa954012cd0131920c2016cdaf367",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 443,
"avg_line_length": 65.68518518518519,
"alnum_prop": 0.6315195940231181,
"repo_name": "calvinfarias/IC2015-2",
"id": "c63cc16bb31310bfed9e9c42197aceadfe0e9d0e",
"size": "3547",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BOOST/boost_1_61_0/libs/asio/doc/html/boost_asio/reference/basic_socket/message_end_of_record.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "223360"
},
{
"name": "Batchfile",
"bytes": "32233"
},
{
"name": "C",
"bytes": "2977162"
},
{
"name": "C#",
"bytes": "40804"
},
{
"name": "C++",
"bytes": "184445796"
},
{
"name": "CMake",
"bytes": "119765"
},
{
"name": "CSS",
"bytes": "427923"
},
{
"name": "Cuda",
"bytes": "111870"
},
{
"name": "DIGITAL Command Language",
"bytes": "6246"
},
{
"name": "FORTRAN",
"bytes": "5291"
},
{
"name": "Groff",
"bytes": "5189"
},
{
"name": "HTML",
"bytes": "234946752"
},
{
"name": "IDL",
"bytes": "14"
},
{
"name": "JavaScript",
"bytes": "682223"
},
{
"name": "Lex",
"bytes": "1231"
},
{
"name": "M4",
"bytes": "29689"
},
{
"name": "Makefile",
"bytes": "1083443"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Objective-C",
"bytes": "11406"
},
{
"name": "Objective-C++",
"bytes": "630"
},
{
"name": "PHP",
"bytes": "59030"
},
{
"name": "Perl",
"bytes": "39008"
},
{
"name": "Perl6",
"bytes": "2053"
},
{
"name": "Python",
"bytes": "1759984"
},
{
"name": "QML",
"bytes": "593"
},
{
"name": "QMake",
"bytes": "16692"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Ruby",
"bytes": "5532"
},
{
"name": "Shell",
"bytes": "355247"
},
{
"name": "Tcl",
"bytes": "1172"
},
{
"name": "TeX",
"bytes": "126042"
},
{
"name": "XSLT",
"bytes": "552736"
},
{
"name": "Yacc",
"bytes": "19623"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
public class CompareChar
{
public static void Main()
{
List<char> listOfChar1 = new List<char>();
List<char> listOfChar2 = new List<char>();
bool isEqual = false;
Console.WriteLine("Enter the first array (enter \"end\" when you want to end it)");
for (int i = 0; i < 1;)
{
string type = Console.ReadLine();
i = (type == "end") ? 1 : 0;
if (type == "end")
{
break;
}
else
{
listOfChar1.Add(char.Parse(type));
}
}
Console.WriteLine("Enter the second array (enter \"end\" when you want to end it)");
for (int i = 0; i < 1;)
{
string type = Console.ReadLine();
i = (type == "end") ? 1 : 0;
if (type == "end")
{
break;
}
else
{
listOfChar2.Add(char.Parse(type));
}
}
isEqual = listOfChar1.Count != listOfChar2.Count ? false : true;
if (listOfChar1.Count == listOfChar2.Count)
{
for (int index = 0; index < listOfChar1.Count; index++)
{
if (listOfChar1[index] != listOfChar2[index])
{
isEqual = false;
}
}
}
if (isEqual == true)
{
Console.WriteLine("Two arrays are equal");
}
else
{
Console.WriteLine("Two arrays are NOT equal");
}
}
}
| {
"content_hash": "69ff6e57bdd126875f22a6d6c75cd3d1",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 92,
"avg_line_length": 27.016129032258064,
"alnum_prop": 0.4244776119402985,
"repo_name": "emilti/Telerik-Academy-My-Courses",
"id": "f9a4dafa96b2162f12b2f6665ffac39c2a7b94cb",
"size": "1677",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "C#-Part2/01.Arrays/03.CompareChar/CompareChar.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "55351"
},
{
"name": "C#",
"bytes": "2038086"
},
{
"name": "CSS",
"bytes": "61494"
},
{
"name": "HTML",
"bytes": "216441"
},
{
"name": "JavaScript",
"bytes": "678560"
},
{
"name": "XSLT",
"bytes": "4923"
}
],
"symlink_target": ""
} |
using System.Text.Json;
using Azure.Core;
namespace Azure.ResourceManager.DataMigration.Models
{
public partial class FileShare : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
if (Optional.IsDefined(UserName))
{
writer.WritePropertyName("userName");
writer.WriteStringValue(UserName);
}
if (Optional.IsDefined(Password))
{
writer.WritePropertyName("password");
writer.WriteStringValue(Password);
}
writer.WritePropertyName("path");
writer.WriteStringValue(Path);
writer.WriteEndObject();
}
internal static FileShare DeserializeFileShare(JsonElement element)
{
Optional<string> userName = default;
Optional<string> password = default;
string path = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("userName"))
{
userName = property.Value.GetString();
continue;
}
if (property.NameEquals("password"))
{
password = property.Value.GetString();
continue;
}
if (property.NameEquals("path"))
{
path = property.Value.GetString();
continue;
}
}
return new FileShare(userName.Value, password.Value, path);
}
}
}
| {
"content_hash": "c60a22b97f0bfcd5e2056b47ea51e593",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 75,
"avg_line_length": 32.65384615384615,
"alnum_prop": 0.5100117785630153,
"repo_name": "Azure/azure-sdk-for-net",
"id": "8e41d23bd604c606d9c42839a0b528e3262e622e",
"size": "1836",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/datamigration/Azure.ResourceManager.DataMigration/src/Generated/Models/FileShare.Serialization.cs",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
describe("module:ng.provider:$interpolateProvider", function() {
beforeEach(function() {
browser.get("./examples/example-example59/index.html");
});
it('should interpolate binding with custom symbols', function() {
expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
});
}); | {
"content_hash": "bc0587576216d088f2d5a0bb5371bc07",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 119,
"avg_line_length": 39,
"alnum_prop": 0.7122507122507122,
"repo_name": "drewverlee/Blackjack",
"id": "0d2de6b72ddc76320c67c75a6d2b94e433303630",
"size": "351",
"binary": false,
"copies": "16",
"ref": "refs/heads/master",
"path": "vendor/assets/javascripts/docs/ptore2e/example-example59/jqlite_test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1161"
},
{
"name": "JavaScript",
"bytes": "7434"
},
{
"name": "Ruby",
"bytes": "62937"
}
],
"symlink_target": ""
} |
namespace ash {
class ASH_EXPORT SystemTrayNotifier {
public:
SystemTrayNotifier();
~SystemTrayNotifier();
void AddAccessibilityObserver(AccessibilityObserver* observer);
void RemoveAccessibilityObserver(AccessibilityObserver* observer);
void AddBluetoothObserver(BluetoothObserver* observer);
void RemoveBluetoothObserver(BluetoothObserver* observer);
void AddBrightnessObserver(BrightnessObserver* observer);
void RemoveBrightnessObserver(BrightnessObserver* observer);
void AddCapsLockObserver(CapsLockObserver* observer);
void RemoveCapsLockObserver(CapsLockObserver* observer);
void AddClockObserver(ClockObserver* observer);
void RemoveClockObserver(ClockObserver* observer);
void AddDriveObserver(DriveObserver* observer);
void RemoveDriveObserver(DriveObserver* observer);
void AddIMEObserver(IMEObserver* observer);
void RemoveIMEObserver(IMEObserver* observer);
void AddLocaleObserver(LocaleObserver* observer);
void RemoveLocaleObserver(LocaleObserver* observer);
void AddLogoutButtonObserver(LogoutButtonObserver* observer);
void RemoveLogoutButtonObserver(LogoutButtonObserver* observer);
void AddSessionLengthLimitObserver(SessionLengthLimitObserver* observer);
void RemoveSessionLengthLimitObserver(SessionLengthLimitObserver* observer);
void AddUpdateObserver(UpdateObserver* observer);
void RemoveUpdateObserver(UpdateObserver* observer);
void AddUserObserver(UserObserver* observer);
void RemoveUserObserver(UserObserver* observer);
#if defined(OS_CHROMEOS)
void AddAudioObserver(AudioObserver* observer);
void RemoveAudioObserver(AudioObserver* observer);
void AddNetworkObserver(NetworkObserver* observer);
void RemoveNetworkObserver(NetworkObserver* observer);
void AddVpnObserver(NetworkObserver* observer);
void RemoveVpnObserver(NetworkObserver* observer);
void AddSmsObserver(SmsObserver* observer);
void RemoveSmsObserver(SmsObserver* observer);
void AddEnterpriseDomainObserver(EnterpriseDomainObserver* observer);
void RemoveEnterpriseDomainObserver(EnterpriseDomainObserver* observer);
void AddScreenCaptureObserver(ScreenCaptureObserver* observer);
void RemoveScreenCaptureObserver(ScreenCaptureObserver* observer);
#endif
void NotifyAccessibilityModeChanged(
AccessibilityNotificationVisibility notify);
void NotifyRefreshBluetooth();
void NotifyBluetoothDiscoveringChanged();
void NotifyBrightnessChanged(double level, bool user_initialted);
void NotifyCapsLockChanged(bool enabled, bool search_mapped_to_caps_lock);
void NotifyRefreshClock();
void NotifyDateFormatChanged();
void NotifySystemClockTimeUpdated();
void NotifyDriveJobUpdated(const DriveOperationStatus& status);
void NotifyRefreshIME(bool show_message);
void NotifyShowLoginButtonChanged(bool show_login_button);
void NotifyLocaleChanged(LocaleObserver::Delegate* delegate,
const std::string& cur_locale,
const std::string& from_locale,
const std::string& to_locale);
void NotifySessionStartTimeChanged();
void NotifySessionLengthLimitChanged();
void NotifyUpdateRecommended(UpdateObserver::UpdateSeverity severity);
void NotifyUserUpdate();
#if defined(OS_CHROMEOS)
void NotifyVolumeChanged(float level);
void NotifyMuteToggled();
void NotifyRefreshNetwork(const NetworkIconInfo &info);
void NotifySetNetworkMessage(NetworkTrayDelegate* delegate,
NetworkObserver::MessageType message_type,
NetworkObserver::NetworkType network_type,
const base::string16& title,
const base::string16& message,
const std::vector<base::string16>& links);
void NotifyClearNetworkMessage(NetworkObserver::MessageType message_type);
void NotifyVpnRefreshNetwork(const NetworkIconInfo &info);
void NotifyWillToggleWifi();
void NotifyAddSmsMessage(const base::DictionaryValue& message);
void NotifyEnterpriseDomainChanged();
void NotifyScreenCaptureStart(const base::Closure& stop_callback,
const base::string16& sharing_app_name);
void NotifyScreenCaptureStop();
#endif
private:
ObserverList<AccessibilityObserver> accessibility_observers_;
ObserverList<BluetoothObserver> bluetooth_observers_;
ObserverList<BrightnessObserver> brightness_observers_;
ObserverList<CapsLockObserver> caps_lock_observers_;
ObserverList<ClockObserver> clock_observers_;
ObserverList<DriveObserver> drive_observers_;
ObserverList<IMEObserver> ime_observers_;
ObserverList<LocaleObserver> locale_observers_;
ObserverList<LogoutButtonObserver> logout_button_observers_;
ObserverList<SessionLengthLimitObserver> session_length_limit_observers_;
ObserverList<UpdateObserver> update_observers_;
ObserverList<UserObserver> user_observers_;
#if defined(OS_CHROMEOS)
ObserverList<AudioObserver> audio_observers_;
ObserverList<NetworkObserver> network_observers_;
ObserverList<NetworkObserver> vpn_observers_;
ObserverList<SmsObserver> sms_observers_;
ObserverList<EnterpriseDomainObserver> enterprise_domain_observers_;
ObserverList<ScreenCaptureObserver> screen_capture_observers_;
#endif
DISALLOW_COPY_AND_ASSIGN(SystemTrayNotifier);
};
} // namespace ash
#endif // ASH_SYSTEM_TRAY_SYSTEM_TRAY_NOTIFIER_H_
| {
"content_hash": "266327dfa1f850ab6a3f59fbef4e118c",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 78,
"avg_line_length": 41.396946564885496,
"alnum_prop": 0.7807486631016043,
"repo_name": "loopCM/chromium",
"id": "fbd9874643e3f4038f38cd0050f69af65e13ca12",
"size": "6833",
"binary": false,
"copies": "1",
"ref": "refs/heads/trunk",
"path": "ash/system/tray/system_tray_notifier.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
/**
2014/06/29
Block.cpp
Purpose: Add behaivor and define the structure of each block
@author Enrique Ojeda Lara <enriqueojedalara@gmail.com>
@version 0.1
*/
#include "Block.h"
#include "Color.h"
/**
Constructor
*/
Block::Block(){
x = 0;
y = 0;
color = Color::BLACK;
free = true;
moving = false;
readed = false;
falling = false;
pivot = false;
}
/**
Reset the block to the default values
@param void
@return void
*/
void Block::reset(){
color = Color::BLACK;
free = true;
moving = false;
readed = false;
falling = false;
pivot = false;
}
/**
Copy properties from a block (Clone)
@param Block (A Block class)
@return void
*/
void Block::clone(Block block){
color = block.color;
free = block.free;
moving = block.moving;
pivot = block.pivot;
readed = block.readed;
falling = block.falling;
} | {
"content_hash": "1711ad5d5722bd4327b12670b4025f33",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 64,
"avg_line_length": 15.140350877192983,
"alnum_prop": 0.6373117033603708,
"repo_name": "enriqueojedalara/Puyopuyo",
"id": "5321e9f39a3ec2ee88ce9085ce1d72b03ff30d68",
"size": "863",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Block.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "27796"
}
],
"symlink_target": ""
} |
BlackLion est un bot pour le jeu en ligne [3GM](http://www.3gm.fr/) (3ème Guerre Mondiale). Il vous permet ainsi de jouer un ou plusieurs comptes sans être en permanence devant votre ordinateur.
* Gestion multi-compte
* Gestion multi-serveur
* Construction des bâtiments
* Lancement des recherches
* Activation des recherches
* Construction des troupes (En refonte)
* Ordre des constructions/recherches configurable
* Chatbot d'alliance
---
**Attention**: Gardez à l'esprit que cette application est en complet désaccord avec le règlement du jeu et qu'un bannissement de vos comptes est une issue possible !
---
# Installation
### Ubuntu / Debian / Windows 10 (Linux EXT)
Soon..
### Environnement Virtuel
Tout d'abord, il faut installer `venv`, pour ce faire on utilise `pip` insatallé précédemment :
```sh
pip install venv
```
Maintenant, nous pouvons initialiser notre environnement virtuel en utilisant `Python 2.x` :
```sh
virtualenv -p /usr/bin/python2.7 cache/env
cd cache/env && source bin/activate && cd ../../
```
Puis on installe les plugins nécéssaires au fonctionnement du bot :
```sh
pip install -r cache/requirements.txt
```
# Configuration
Soon...
# Execution
Pour executer BlackLion, il vous suffit d'activer l'environnement virtuel dans votre session de terminal (si ce n'est pas déjà fait) :
```sh
cd cache/env && source bin/activate && cd ../../
```
Enfin, nous pouvons le lancer :
```sh
python ./blacklion
```
`Ctrl+C` pour arrêter le bot et déconnecter tous les comptes.
# Ressources (DEV)
* [HTTP Requests](http://requests-fr.readthedocs.io/en/latest/index.html)
* [Regex](https://docs.python.org/2/library/re.html)
* [XPath](https://docs.python.org/2/library/xml.etree.elementtree.html#xpath-support)
| {
"content_hash": "2079dbd1d7100a9f9354072d3fc2061c",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 194,
"avg_line_length": 25.333333333333332,
"alnum_prop": 0.7362700228832952,
"repo_name": "Foohx/blacklion",
"id": "6a92893d51a29d0680356b8a8d7198c0b7c775ac",
"size": "1776",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "35019"
},
{
"name": "Shell",
"bytes": "175"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>img/icons/favicon-32x32.png" type="image/png">
<title>nippou-player</title>
</head>
<body>
<noscript>
<strong>We're sorry but nippou-player doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
| {
"content_hash": "31cccff5195a95e005c82b82005965a2",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 132,
"avg_line_length": 35.05882352941177,
"alnum_prop": 0.6442953020134228,
"repo_name": "hidakatsuya/nippou-player",
"id": "8994e2d95934891471868fb8618efdea36a9c2b8",
"size": "596",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "596"
},
{
"name": "JavaScript",
"bytes": "16985"
},
{
"name": "Vue",
"bytes": "14139"
}
],
"symlink_target": ""
} |
require 'proxy_server/httpservlet/abstract.rb'
require 'erb'
module ProxyServer
module HttpServlet
##
# ERBHandler evaluates an ERB file and returns the result. This handler
# is automatically used if there are .rhtml files in a directory served by
# the FileHandler.
#
# ERBHandler supports GET and POST methods.
#
# The ERB file is evaluated with the local variables +servlet_request+ and
# +servlet_response+ which are a ProxyServer::HttpRequest and
# ProxyServer::HttpResponse respectively.
#
# Example .rhtml file:
#
# Request to <%= servlet_request.request_uri %>
#
# Query params <%= servlet_request.query.inspect %>
class ERBHandler < AbstractServlet
##
# Creates a new ERBHandler on +server+ that will evaluate and serve the
# ERB file +name+
def initialize(server, name)
super(server, name)
@script_filename = name
end
##
# Handles GET requests
def do_GET(req, res)
unless defined?(ERB)
@logger.warn "#{self.class}: ERB not defined."
raise HttpStatus::Forbidden, "ERBHandler cannot work."
end
begin
data = open(@script_filename){|io| io.read }
res.body = evaluate(ERB.new(data), req, res)
res['content-type'] ||=
HttpUtils::mime_type(@script_filename, @config[:MimeTypes])
rescue StandardError
raise
rescue Exception => ex
@logger.error(ex)
raise HttpStatus::InternalServerError, ex.message
end
end
##
# Handles POST requests
alias do_POST do_GET
private
##
# Evaluates +erb+ providing +servlet_request+ and +servlet_response+ as
# local variables.
def evaluate(erb, servlet_request, servlet_response)
Module.new.module_eval{
servlet_request.meta_vars
servlet_request.query
erb.result(binding)
}
end
end
end
end
| {
"content_hash": "d69dd3a290f13cb39e470a4ba41b5fdb",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 78,
"avg_line_length": 26.31168831168831,
"alnum_prop": 0.6080947680157947,
"repo_name": "fedux-org/proxy_server",
"id": "ca79fccc9ddd6660f2d1efd438cfe489543c75a5",
"size": "2331",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/proxy_server/httpservlet/erbhandler.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Cucumber",
"bytes": "443"
},
{
"name": "Ruby",
"bytes": "187164"
},
{
"name": "Shell",
"bytes": "131"
}
],
"symlink_target": ""
} |
/**
*
*/
package com.jeesuite.kafka.monitor.model;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicLong;
/**
* @description <br>
* @author <a href="mailto:vakinge@gmail.com">vakin</a>
* @date 2016年12月10日
*/
public class ProducerStat implements Serializable {
private static final long serialVersionUID = 3381280990522906667L;
private String topic;
private String group;
private long successNums;
private long errorNums;
private long latestSuccessNums;
private long latestErrorNums;
private long updateTime;
private String source;
public ProducerStat() {}
public ProducerStat(String topic, String group, AtomicLong successNums, AtomicLong errorNums, AtomicLong latestSuccessNums,
AtomicLong latestErrorNums) {
super();
this.topic = topic;
this.group = group;
this.successNums = successNums.get();
this.errorNums = errorNums.get();
this.latestSuccessNums = latestSuccessNums.get();
this.latestErrorNums = latestErrorNums.get();
this.updateTime = System.currentTimeMillis();
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public long getSuccessNums() {
return successNums;
}
public void setSuccessNums(long successNums) {
this.successNums = successNums;
}
public long getErrorNums() {
return errorNums;
}
public void setErrorNums(long errorNums) {
this.errorNums = errorNums;
}
public long getLatestSuccessNums() {
return latestSuccessNums;
}
public void setLatestSuccessNums(long latestSuccessNums) {
this.latestSuccessNums = latestSuccessNums;
}
public long getLatestErrorNums() {
return latestErrorNums;
}
public void setLatestErrorNums(long latestErrorNums) {
this.latestErrorNums = latestErrorNums;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public long getUpdateTime() {
return updateTime;
}
public void setUpdateTime(long updateTime) {
this.updateTime = updateTime;
}
public String getFormatLastTime(){
long diffSeconds = (System.currentTimeMillis() - updateTime)/1000;
if(diffSeconds >= 86400){
return (diffSeconds/86400) + " 天前";
}
if(diffSeconds >= 3600){
return (diffSeconds/3600) + " 小时前";
}
if(diffSeconds >= 60){
return (diffSeconds/60) + " 分钟前";
}
return diffSeconds + " 秒前";
}
}
| {
"content_hash": "8c764a3b60fb797195f7e0c64e353c54",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 124,
"avg_line_length": 22.844036697247706,
"alnum_prop": 0.727710843373494,
"repo_name": "vakinge/jeesuite-libs",
"id": "acb8e3010bb0b80553db61600304c969fded3620",
"size": "2516",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jeesuite-kafka/src/main/java/com/jeesuite/kafka/monitor/model/ProducerStat.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1564642"
}
],
"symlink_target": ""
} |
package net.mwplay.bmob;
import java.util.List;
import org.robovm.apple.foundation.NSDate;
import org.robovm.apple.foundation.NSObject;
import org.robovm.objc.annotation.NativeClass;
import org.robovm.objc.annotation.Property;
@NativeClass
public class BQLQueryResult extends NSObject{
/**
* 查询结果的 className
*/
//@property(nonatomic, strong) NSString *className;
@Property
public native void setClassName(String className);
@Property
public native String getClassName();
/**
* 查询的结果 BmobObject 对象列表
*/
//@property(nonatomic, strong) NSArray *resultsAry;
@Property
public native void setResultsAry(List<BmobObject> resultsAry);
@Property
public native List<BmobObject> getResultsAry();
/**
* 查询 count 结果, 只有使用 select count(*) ... 时该值信息才是有效的
*/
//@property(nonatomic) int count;
@Property
public native void setCount(int count);
@Property
public native int getCount();
}
| {
"content_hash": "023a44ba1977825f69514cb29329e11c",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 63,
"avg_line_length": 23.307692307692307,
"alnum_prop": 0.7480748074807481,
"repo_name": "tianqiujie/robovm-ios-bindings",
"id": "c842576b3fd17b68336a988c6b8df701c6ca558e",
"size": "973",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bmob/BQLQueryResult.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "277852"
},
{
"name": "Objective-C",
"bytes": "2509"
}
],
"symlink_target": ""
} |
using System;
namespace Server.Items
{
public abstract class BaseWaist : BaseClothing
{
public BaseWaist( int itemID ) : this( itemID, 0 )
{
}
public BaseWaist( int itemID, int hue ) : base( itemID, Layer.Waist, hue )
{
}
public BaseWaist( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[FlipableAttribute( 0x153b, 0x153c )]
public class HalfApron : BaseWaist
{
[Constructable]
public HalfApron() : this( 0 )
{
}
[Constructable]
public HalfApron( int hue ) : base( 0x153b, hue )
{
Weight = 2.0;
}
public HalfApron( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[Flipable( 0x27A0, 0x27EB )]
public class Obi : BaseWaist
{
[Constructable]
public Obi() : this( 0 )
{
}
[Constructable]
public Obi( int hue ) : base( 0x27A0, hue )
{
Weight = 1.0;
}
public Obi( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[FlipableAttribute( 0x2B68, 0x315F )]
public class WoodlandBelt : BaseWaist
{
//public override Race RequiredRace { get { return Race.Elf; } }
[Constructable]
public WoodlandBelt() : this( 0 )
{
}
[Constructable]
public WoodlandBelt( int hue ) : base( 0x2B68, hue )
{
Weight = 4.0;
Name = "Ceinture Arboricole"; // impossible de rester sérieux devant cet item ^^
}
public WoodlandBelt( Serial serial ) : base( serial )
{
}
public override bool Dye( Mobile from, DyeTub sender )
{
from.SendLocalizedMessage( sender.FailMessage );
return false;
}
public override bool Scissor( Mobile from, Scissors scissors )
{
from.SendLocalizedMessage( 502440 ); // Scissors can not be used on that to produce anything.
return false;
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.WriteEncodedInt( 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadEncodedInt();
}
}
}
| {
"content_hash": "0ac04cf243a2a73bad83e0952b8ee3ee",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 96,
"avg_line_length": 18.62837837837838,
"alnum_prop": 0.6492564381574175,
"repo_name": "ggobbe/vivre-uo",
"id": "791d3ad00a1622bbb3465a4b43be56737b211e14",
"size": "2757",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Scripts/Items/Clothing/Waist.cs",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C#",
"bytes": "19852349"
},
{
"name": "CSS",
"bytes": "699"
},
{
"name": "HTML",
"bytes": "3008"
}
],
"symlink_target": ""
} |
{{define "styles"}}
<style type="text/css">
@import url(https://fonts.googleapis.com/css?family=Cinzel:400,700);
body { font-family: 'Cinzel', serif; font-size: 1em; background-color: #f2f2f2; color: #666; line-height: 1.42857; margin: 1em; font-weight: 500; }
/* header template styling */
.title { font-size: 2.5em; font-weight: bold; font-family: 'Cinzel', serif; }
.subtitle { font-size: 0.8em; margin-top: -1em; margin-bottom: 4em; font-weight: bold; }
/* footer template styling */
.footer { margin-top: 1em; text-align: center; font-size: .7em; font-weight: bold; }
.footer a { color: #666; font-weight: bold; }
.logo { text-align: center; width: 100%; }
/* nav template styling */
.nav { text-align: right; position: absolute; top: 1em; right: 1em; line-height: 3.5em; }
.nav a { color: #666; }
/* generic styling */
a { text-decoration: none; color: inherit; font-weight: bold; }
a:visited {text-decoration: none; color: inherit; font-weight: bold; }
a:hover { color: #444; }
a:active {text-decoration: none; color: inherit; font-weight: bold; }
.label { font-weight: bold; }
.message { }
.inner { min-height: 22em; width: 100%; margin: 0 auto; background-color: #fafafa; border: .1em solid #dbdbdb; border-radius: .2em; overflow: visible; }
.formtitle { height: 100%; line-height: 100%; }
.welcome { line-height: 3.5em; font-size: 1.2em; text-align: center; }
.large { font-size: 2em; }
img { border: 0; }
.note { font-size: .8em; }
/* upload template styling */
input[type="text"], textarea { width: 30em; background-color: #fafafa; border: .1em solid #DBDBDB; border-radius: .2em; }
input[type="submit"] { width: 100%; height: 2.2em; }
/* files template sytling */
table.files { text-align: left; border-spacing: 0em; border-collapse: collapse; table-layout: fixed; }
.files tr { background-color: #fcfcfc; }
.files th { padding: .4em; background-color: #fafafa; border: .1em solid #dbdbdb; }
.files td { padding: .3em; text-overflow: ellipsis; background-color: transparent; font-size: .95em; border: .1em solid #dbdbdb; overflow: hidden; white-space: nowrap; max-width: 75%; }
.files th.size, .files th.date, .files th.email, .files th.filecount { text-align: center; color: inherit; }
.files tr:hover { background-color: #f0f0f0; }
.total { text-align: right; }
.filename a { color: blue; font-weight: normal; }
.filecount { color: black; width: 3em; text-align: right; }
.email { color: black; width: 20em; text-align: right; }
.size { color: black; width: 6em; text-align: right; }
.date { color: black; width: 11em; text-align: center; }
.metalabel { width: 7em; font-weight: bold; display: inline-block; }
.log { font-size: .8em; }
.loglabel { width: 12em; font-weight: bold; display: inline-block; }
</style>
{{end}} | {
"content_hash": "fcb3bfa42fc05ea8526f2a96cc821afc",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 189,
"avg_line_length": 54.148148148148145,
"alnum_prop": 0.6388508891928865,
"repo_name": "jlmeeker/evh2",
"id": "a80121497712efb4dd520d7e538f008f819c594b",
"size": "2924",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tmpl/styles.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "49350"
},
{
"name": "HTML",
"bytes": "13728"
},
{
"name": "Shell",
"bytes": "1396"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_102) on Thu Jan 19 20:03:43 PST 2017 -->
<title>All Classes</title>
<meta name="date" content="2017-01-19">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h1 class="bar">All Classes</h1>
<div class="indexContainer">
<ul>
<li><a href="main/MultipleEightQueens.html" title="class in main">MultipleEightQueens</a></li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "afd112676982188d036cdfc720a1cfc8",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 102,
"avg_line_length": 33.10526315789474,
"alnum_prop": 0.6756756756756757,
"repo_name": "tliang1/Java-Practice",
"id": "d8c8579d0daa952fe36c1caa47b973bebdb11b57",
"size": "629",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Practice/Intro-To-Java-8th-Ed-Daniel-Y.-Liang/Chapter-6/Chapter06P22/doc/allclasses-noframe.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "710145"
}
],
"symlink_target": ""
} |
package com.databricks.spark.sql.perf.mllib.feature
import org.apache.spark.ml
import org.apache.spark.ml.PipelineStage
import org.apache.spark.sql._
import com.databricks.spark.sql.perf.mllib.OptionImplicits._
import com.databricks.spark.sql.perf.mllib.data.DataGenerator
import com.databricks.spark.sql.perf.mllib.{BenchmarkAlgorithm, MLBenchContext, TestFromTraining}
/** Object for testing VectorSlicer performance */
object VectorSlicer extends BenchmarkAlgorithm with TestFromTraining {
override def trainingDataSet(ctx: MLBenchContext): DataFrame = {
import ctx.params._
DataGenerator.generateContinuousFeatures(
ctx.sqlContext,
numExamples,
ctx.seed(),
numPartitions,
numFeatures
)
}
override def getPipelineStage(ctx: MLBenchContext): PipelineStage = {
import ctx.params._
val indices = (0 until numFeatures by 2).toArray
new ml.feature.VectorSlicer()
.setInputCol("features")
.setIndices(indices)
}
}
| {
"content_hash": "2e19a5eb06b3a27ef5375885fd32b5c8",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 97,
"avg_line_length": 28.37142857142857,
"alnum_prop": 0.7492447129909365,
"repo_name": "wayblink/Naive",
"id": "77b66caa5d26cef4ea3ac1043cc222a00dd4fcfb",
"size": "993",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spark/spark-sql-perf-2.2/src/main/scala/com/databricks/spark/sql/perf/mllib/feature/VectorSlicer.scala",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8742"
},
{
"name": "HTML",
"bytes": "97"
},
{
"name": "Java",
"bytes": "23506"
},
{
"name": "Python",
"bytes": "39290"
},
{
"name": "Scala",
"bytes": "944017"
},
{
"name": "Shell",
"bytes": "54337"
},
{
"name": "TSQL",
"bytes": "171984"
},
{
"name": "XSLT",
"bytes": "41986"
}
],
"symlink_target": ""
} |
#import "EC2CancelReservedInstancesListingRequestMarshaller.h"
@implementation EC2CancelReservedInstancesListingRequestMarshaller
+(AmazonServiceRequest *)createRequest:(EC2CancelReservedInstancesListingRequest *)cancelReservedInstancesListingRequest
{
AmazonServiceRequest *request = [[EC2Request alloc] init];
[request setParameterValue:@"CancelReservedInstancesListing" forKey:@"Action"];
[request setParameterValue:@"2012-08-15" forKey:@"Version"];
[request setDelegate:[cancelReservedInstancesListingRequest delegate]];
[request setCredentials:[cancelReservedInstancesListingRequest credentials]];
[request setEndpoint:[cancelReservedInstancesListingRequest requestEndpoint]];
[request setRequestTag:[cancelReservedInstancesListingRequest requestTag]];
if (cancelReservedInstancesListingRequest != nil) {
if (cancelReservedInstancesListingRequest.reservedInstancesListingId != nil) {
[request setParameterValue:[NSString stringWithFormat:@"%@", cancelReservedInstancesListingRequest.reservedInstancesListingId] forKey:[NSString stringWithFormat:@"%@", @"ReservedInstancesListingId"]];
}
}
return [request autorelease];
}
@end
| {
"content_hash": "bca6926be76d23062155c24ce2a2715c",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 212,
"avg_line_length": 40.733333333333334,
"alnum_prop": 0.7864157119476268,
"repo_name": "abovelabs/aws-ios-sdk",
"id": "769aa26867307608a69b9ab5b3969e3e9ed17f60",
"size": "1806",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Amazon.EC2/Model/EC2CancelReservedInstancesListingRequestMarshaller.m",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.opengamma.integration.copier.portfolio;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import com.opengamma.integration.copier.portfolio.reader.PositionReader;
import com.opengamma.integration.copier.portfolio.writer.PositionWriter;
import com.opengamma.master.position.ManageablePosition;
import com.opengamma.master.security.ManageableSecurity;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.tuple.ObjectsPair;
/**
* A simple portfolio copier that copies positions from readers to the specified writer.
*/
public class SimplePortfolioCopier implements PortfolioCopier {
private static final Logger LOGGER = LoggerFactory.getLogger(SimplePortfolioCopier.class);
private final String[] _structure;
public SimplePortfolioCopier() {
_structure = null;
}
public SimplePortfolioCopier(final String[] structure) {
_structure = structure;
}
@Override
public void copy(final PositionReader positionReader, final PositionWriter positionWriter) {
copy(positionReader, positionWriter, null);
}
@Override
public void copy(final PositionReader positionReader, final PositionWriter positionWriter, final PortfolioCopierVisitor visitor) {
ArgumentChecker.notNull(positionWriter, "positionWriter");
ArgumentChecker.notNull(positionReader, "positionReader");
ObjectsPair<ManageablePosition, ManageableSecurity[]> next;
while (true) {
// Read in next row, checking for errors and EOF
try {
next = positionReader.readNext();
} catch (final Exception e) {
// skip to next row on uncaught exception while parsing row
LOGGER.error("Unable to parse row", e);
continue;
}
if (next == null) {
// stop loading on EOF
break;
}
// Is position and security data is available for the current row?
final ManageablePosition position = next.getFirst();
final ManageableSecurity[] securities = next.getSecond();
// Is position and security data available for the current row?
if (position != null && securities != null) {
// Set current path
String[] path;
if (_structure == null) {
path = positionReader.getCurrentPath();
} else {
path = new String[_structure.length];
for (int i = 0; i < _structure.length; i++) {
path[i] = position.getAttributes().get(_structure[i]);
}
}
positionWriter.setPath(path);
// Write position and security data
final ObjectsPair<ManageablePosition, ManageableSecurity[]> written =
positionWriter.writePosition(position, securities);
if (visitor != null && written != null) {
visitor.info(StringUtils.arrayToDelimitedString(path, "/"), written.getFirst(), written.getSecond());
}
} else {
if (visitor != null) {
if (position == null) {
visitor.error("Could not load position");
}
if (securities == null) {
visitor.error("Could not load security(ies)");
}
}
}
}
}
}
| {
"content_hash": "6cedc2294d4387209d1d1488538977d7",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 132,
"avg_line_length": 31.584158415841586,
"alnum_prop": 0.6702194357366771,
"repo_name": "McLeodMoores/starling",
"id": "5b010feed2e7bc6ef410c823fcb088a907d2bc64",
"size": "3327",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "projects/integration/src/main/java/com/opengamma/integration/copier/portfolio/SimplePortfolioCopier.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2505"
},
{
"name": "CSS",
"bytes": "213501"
},
{
"name": "FreeMarker",
"bytes": "310184"
},
{
"name": "GAP",
"bytes": "1490"
},
{
"name": "Groovy",
"bytes": "11518"
},
{
"name": "HTML",
"bytes": "318295"
},
{
"name": "Java",
"bytes": "79541905"
},
{
"name": "JavaScript",
"bytes": "1511230"
},
{
"name": "PLSQL",
"bytes": "398"
},
{
"name": "PLpgSQL",
"bytes": "26901"
},
{
"name": "Shell",
"bytes": "11481"
},
{
"name": "TSQL",
"bytes": "604117"
}
],
"symlink_target": ""
} |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="es_CL" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Bitcoin</source>
<translation>Sobre Angora</translation>
</message>
<message>
<location line="+39"/>
<source><b>Bitcoin</b> version</source>
<translation><b>Angora</b> - versión </translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>
Este es un software experimental.
Distribuido bajo la licencia MIT/X11, vea el archivo adjunto
COPYING o http://www.opensource.org/licenses/mit-license.php.
Este producto incluye software desarrollado por OpenSSL Project para su uso en
el OpenSSL Toolkit (http://www.openssl.org/), software criptográfico escrito por
Eric Young (eay@cryptsoft.com) y UPnP software escrito por Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The Bitcoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Guia de direcciones</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Haz doble clic para editar una dirección o etiqueta</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Crea una nueva dirección</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copia la dirección seleccionada al portapapeles</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Nueva dirección</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Bitcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Estas son tus direcciones Angora para recibir pagos. Puedes utilizar una diferente por cada persona emisora para saber quien te está pagando.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Copia dirección</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Mostrar Código &QR </translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Bitcoin address</source>
<translation>Firmar un mensaje para provar que usted es dueño de esta dirección</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Firmar Mensaje</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Exportar los datos de la pestaña actual a un archivo</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Bitcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Borrar</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Bitcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>These are your Angora addresses for sending payments. Always check the amount and the receiving address before sending coins.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Copia &etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Editar</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Exporta datos de la guia de direcciones</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Archivos separados por coma (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Exportar errores</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>No se pudo escribir al archivo %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(sin etiqueta)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Introduce contraseña actual </translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nueva contraseña</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Repite nueva contraseña:</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Introduce la nueva contraseña para la billetera.<br/>Por favor utiliza un contraseña <b>de 10 o mas caracteres aleatorios</b>, u <b>ocho o mas palabras</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Codificar billetera</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Esta operación necesita la contraseña para desbloquear la billetera.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Desbloquea billetera</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Esta operación necesita la contraseña para decodificar la billetara.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Decodificar cartera</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Cambia contraseña</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Introduce la contraseña anterior y la nueva de cartera</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Confirma la codificación de cartera</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!</source>
<translation>Atención: ¡Si codificas tu billetera y pierdes la contraseña perderás <b>TODOS TUS AngoraS</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>¿Seguro que quieres seguir codificando la billetera?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Precaucion: Mayúsculas Activadas</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Billetera codificada</translation>
</message>
<message>
<location line="-56"/>
<source>Bitcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source>
<translation>Angora se cerrará para finalizar el proceso de encriptación. Recuerde que encriptar su billetera no protegera completatamente sus Angoras de ser robados por malware que infecte su computador</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Falló la codificación de la billetera</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>La codificación de la billetera falló debido a un error interno. Tu billetera no ha sido codificada.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Las contraseñas no coinciden.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Ha fallado el desbloqueo de la billetera</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>La contraseña introducida para decodificar la billetera es incorrecta.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Ha fallado la decodificación de la billetera</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>La contraseña de billetera ha sido cambiada con éxito.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Firmar &Mensaje...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Sincronizando con la red...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Vista general</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Muestra una vista general de la billetera</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transacciónes</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Explora el historial de transacciónes</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Edita la lista de direcciones y etiquetas almacenadas</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Muestra la lista de direcciónes utilizadas para recibir pagos</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Salir</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Salir del programa</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Bitcoin</source>
<translation>Muestra información acerca de Angora</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Acerca de</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Mostrar Información sobre QT</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Opciones</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Codificar la billetera...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Respaldar billetera...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Cambiar la contraseña...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Bitcoin address</source>
<translation>Enviar monedas a una dirección Angora</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Bitcoin</source>
<translation>Modifica las opciones de configuración de Angora</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Respaldar billetera en otra ubicación</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Cambiar la contraseña utilizada para la codificación de la billetera</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Bitcoin</source>
<translation>Angora</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Cartera</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About Bitcoin</source>
<translation>&Sobre Angora</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Mostrar/Ocultar</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Bitcoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Bitcoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Archivo</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Configuración</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Ayuda</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Barra de pestañas</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[red-de-pruebas]</translation>
</message>
<message>
<location line="+47"/>
<source>Bitcoin client</source>
<translation>Cliente Angora</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Bitcoin network</source>
<translation><numerusform>%n conexión activa hacia la red Angora</numerusform><numerusform>%n conexiones activas hacia la red Angora</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Actualizado</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Recuperando...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Transacción enviada</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Transacción entrante</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Fecha: %1
Cantidad: %2
Tipo: %3
Dirección: %4</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Bitcoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>La billetera esta <b>codificada</b> y actualmente <b>desbloqueda</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>La billetera esta <b>codificada</b> y actualmente <b>bloqueda</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Bitcoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Editar dirección</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Etiqueta</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>La etiqueta asociada con esta entrada de la libreta de direcciones</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Dirección</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>La dirección asociada con esta entrada en la libreta de direcciones. Solo puede ser modificada para direcciónes de envío.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Nueva dirección para recibir</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Nueva dirección para enviar</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Editar dirección de recepción</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Editar dirección de envio</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>La dirección introducida "%1" ya esta guardada en la libreta de direcciones.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Bitcoin address.</source>
<translation>La dirección introducida "%1" no es una dirección Angora valida.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>No se pudo desbloquear la billetera.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>La generación de nueva clave falló.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Bitcoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versión</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Uso:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>UI opciones</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Arranca minimizado
</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Opciones</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Principal</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Comisión de &transacciónes</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Bitcoin after logging in to the system.</source>
<translation>Inicia Angora automáticamente despues de encender el computador</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Bitcoin on system login</source>
<translation>&Inicia Angora al iniciar el sistema</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Bitcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Abre automáticamente el puerto del cliente Angora en el router. Esto funciona solo cuando tu router es compatible con UPnP y está habilitado.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Direcciona el puerto usando &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Bitcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Conecta a la red Angora a través de un proxy SOCKS (ej. cuando te conectas por la red Tor)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Conecta a traves de un proxy SOCKS:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP Proxy:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Dirección IP del servidor proxy (ej. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Puerto:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Puerto del servidor proxy (ej. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Muestra solo un ícono en la bandeja después de minimizar la ventana</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimiza a la bandeja en vez de la barra de tareas</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimiza la ventana en lugar de salir del programa cuando la ventana se cierra. Cuando esta opción esta activa el programa solo se puede cerrar seleccionando Salir desde el menu.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimiza a la bandeja al cerrar</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Mostrado</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Bitcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Unidad en la que mostrar cantitades:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Elige la subdivisión por defecto para mostrar cantidaded en la interfaz cuando se envien monedas</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Bitcoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Muestra direcciones en el listado de transaccioines</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Atención</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Bitcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Formulario</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Bitcoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>No confirmados:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Cartera</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Transacciones recientes</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Tu saldo actual</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Total de transacciones que no han sido confirmadas aun, y que no cuentan para el saldo actual.</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start bitcoin: click-to-pay handler</source>
<translation>Cannot start Angora: click-to-pay handler</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Solicitar Pago</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Cantidad:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Mensaje:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Guardar Como...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>Imágenes PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Bitcoin-Qt help message to get a list with possible Bitcoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>Bitcoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Bitcoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Bitcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Bitcoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Enviar monedas</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Enviar a múltiples destinatarios</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Agrega destinatario</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Remover todos los campos de la transacción</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>&Borra todos</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Balance:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 SPUR</source>
<translation>123.456 ANG</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Confirma el envio</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Envía</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> to %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Confirmar el envio de monedas</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Estas seguro que quieres enviar %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>y</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>La dirección de destinatarion no es valida, comprueba otra vez.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>La cantidad por pagar tiene que ser mayor 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>La cantidad sobrepasa tu saldo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>El total sobrepasa tu saldo cuando se incluyen %1 como tasa de envio.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Tienes una dirección duplicada, solo puedes enviar a direcciónes individuales de una sola vez.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Error: La transacción fue rechazada. Esto puede haber ocurrido si alguna de las monedas ya estaba gastada o si ha usado una copia de wallet.dat y las monedas se gastaron en la copia pero no se han marcado como gastadas aqui.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Envio</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Cantidad:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Pagar a:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Introduce una etiqueta a esta dirección para añadirla a tu guia</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Etiqueta:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Elije dirección de la guia</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Pega dirección desde portapapeles</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Elimina destinatario</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Introduce una dirección Angora (ej. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Firmar Mensaje</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Introduce una dirección Angora (ej. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Elije dirección de la guia</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Pega dirección desde portapapeles</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Escriba el mensaje que desea firmar</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Bitcoin address</source>
<translation>Firmar un mensjage para probar que usted es dueño de esta dirección</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>&Borra todos</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Introduce una dirección Angora (ej. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Bitcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Introduce una dirección Angora (ej. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Click en "Firmar Mensage" para conseguir firma</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Bitcoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Bitcoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[red-de-pruebas]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Abierto hasta %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/fuera de linea</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/no confirmado</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmaciónes</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Estado</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generado</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>De</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>etiqueta</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Credito</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>no aceptada</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debito</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Comisión transacción</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Cantidad total</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Mensaje</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Comentario</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID de Transacción</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Las monedas generadas deben esperar 120 bloques antes de ser gastadas. Cuando has generado este bloque se emitió a la red para ser agregado en la cadena de bloques. Si falla al incluirse en la cadena, cambiará a "no aceptado" y las monedas no se podrán gastar. Esto puede ocurrir ocasionalmente si otro nodo genera un bloque casi al mismo tiempo que el tuyo.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transacción</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, no ha sido emitido satisfactoriamente todavía</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>desconocido</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Detalles de transacción</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Esta ventana muestra información detallada sobre la transacción</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Abierto hasta %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Fuera de linea (%1 confirmaciónes)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>No confirmado (%1 de %2 confirmaciónes)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmado (%1 confirmaciones)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Este bloque no ha sido recibido por otros nodos y probablemente no sea aceptado !</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generado pero no acceptado</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Recibido con</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Recibido de</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Enviado a</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Pagar a usted mismo</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Minado</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Estado de transacción. Pasa el raton sobre este campo para ver el numero de confirmaciónes.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Fecha y hora cuando se recibió la transaccion</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Tipo de transacción.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Dirección de destino para la transacción</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Cantidad restada o añadida al balance</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Todo</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Hoy</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Esta semana</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Esta mes</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Mes pasado</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Este año</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Rango...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Recibido con</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Enviado a</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>A ti mismo</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Minado</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Otra</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Introduce una dirección o etiqueta para buscar</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Cantidad minima</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copia dirección</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copia etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiar Cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Edita etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Exportar datos de transacción</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Archivos separados por coma (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Confirmado</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Error exportando</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>No se pudo escribir en el archivo %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Rango:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>para</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Enviar monedas</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Exportar los datos de la pestaña actual a un archivo</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Bitcoin version</source>
<translation>Versión Angora</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Uso:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or bitcoind</source>
<translation>Envia comando a bitcoin lanzado con -server u bitcoind
</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Muestra comandos
</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Recibir ayuda para un comando
</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Opciones:
</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: bitcoin.conf)</source>
<translation>Especifica archivo de configuración (predeterminado: bitcoin.conf)
</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: bitcoind.pid)</source>
<translation>Especifica archivo pid (predeterminado: bitcoin.pid)
</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Especifica directorio para los datos
</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 11070 or testnet: 5744)</source>
<translation>Escuchar por conecciones en <puerto> (Por defecto: 11070 o red de prueba: 5744)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Mantener al menos <n> conecciones por cliente (por defecto: 125) </translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Umbral de desconección de clientes con mal comportamiento (por defecto: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 21070 or testnet: 5745)</source>
<translation>Escucha conexiones JSON-RPC en el puerto <port> (predeterminado: 21070 or testnet: 5745)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Aceptar comandos consola y JSON-RPC
</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Correr como demonio y acepta comandos
</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Usa la red de pruebas
</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=bitcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Bitcoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Bitcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Precaución: -paytxfee es muy alta. Esta es la comisión que pagarás si envias una transacción.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Bitcoin will not work properly.</source>
<translation>Precaución: Por favor revise que la fecha y hora de tu ordenador son correctas. Si tu reloj está mal configurado Angora no funcionará correctamente.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Conecta solo al nodo especificado
</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Dirección -tor invalida: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Adjuntar informacion extra de depuracion. Implies all other -debug* options</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Anteponer salida de depuracion con marca de tiempo</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>Opciones SSL: (ver la Angora Wiki para instrucciones de configuración SSL)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Enviar informacion de seguimiento a la consola en vez del archivo debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Enviar informacion de seguimiento al depurador</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Especifica tiempo de espera para conexion en milisegundos (predeterminado: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Intenta usar UPnP para mapear el puerto de escucha (default: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Intenta usar UPnP para mapear el puerto de escucha (default: 1 when listening)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Usuario para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Contraseña para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Permite conexiones JSON-RPC desde la dirección IP especificada
</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Envia comando al nodo situado en <ip> (predeterminado: 127.0.0.1)
</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Actualizar billetera al formato actual</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Ajusta el numero de claves en reserva <n> (predeterminado: 100)
</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Rescanea la cadena de bloques para transacciones perdidas de la cartera
</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Usa OpenSSL (https) para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Certificado del servidor (Predeterminado: server.cert)
</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Clave privada del servidor (Predeterminado: server.pem)
</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Cifrados aceptados (Predeterminado: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)
</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Este mensaje de ayuda
</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>No es posible escuchar en el %s en este ordenador (bind returned error %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Conecta mediante proxy socks</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Permite búsqueda DNS para addnode y connect
</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Cargando direcciónes...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Error cargando wallet.dat: Billetera corrupta</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Bitcoin</source>
<translation>Error cargando wallet.dat: Billetera necesita una vercion reciente de Angora</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Bitcoin to complete</source>
<translation>La billetera necesita ser reescrita: reinicie Angora para completar</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Error cargando wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Dirección -proxy invalida: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Cantidad inválida para -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Cantidad inválida</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Fondos insuficientes</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Cargando el index de bloques...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Agrega un nodo para conectarse and attempt to keep the connection open</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Bitcoin is probably already running.</source>
<translation>No es posible escuchar en el %s en este ordenador. Probablemente Angora ya se está ejecutando.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Comisión por kB para adicionarla a las transacciones enviadas</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Cargando cartera...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Rescaneando...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Carga completa</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Error</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS> | {
"content_hash": "52faf9a5ff08409439a8d5deeab05c49",
"timestamp": "",
"source": "github",
"line_count": 2952,
"max_line_length": 403,
"avg_line_length": 36.21273712737128,
"alnum_prop": 0.61266604303087,
"repo_name": "angorator/angora_TOR",
"id": "236b10022fcc2422bd5d38b13586d73b0cd0ad4d",
"size": "107056",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/locale/bitcoin_es_CL.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "700929"
},
{
"name": "C++",
"bytes": "2505401"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "HTML",
"bytes": "50615"
},
{
"name": "Makefile",
"bytes": "12141"
},
{
"name": "NSIS",
"bytes": "5947"
},
{
"name": "Objective-C",
"bytes": "858"
},
{
"name": "Objective-C++",
"bytes": "2734"
},
{
"name": "Python",
"bytes": "3779"
},
{
"name": "QMake",
"bytes": "14287"
},
{
"name": "Shell",
"bytes": "7983"
}
],
"symlink_target": ""
} |
package org.jfw.util.bean.define;
public class ConfigException extends Exception {
private static final long serialVersionUID = -3683286340446305667L;
public ConfigException(String message, Throwable cause) {
super(message, cause);
}
public ConfigException(String message) {
super(message);
}
}
| {
"content_hash": "88f8d6b195941e92b16a89e00c51cbca",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 68,
"avg_line_length": 23.071428571428573,
"alnum_prop": 0.7368421052631579,
"repo_name": "saga810203/jfw",
"id": "b1644a756d330262d8896118696c275548426ac4",
"size": "323",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jfw-util/src/main/java/org/jfw/util/bean/define/ConfigException.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "397039"
}
],
"symlink_target": ""
} |
package com.streamsets.pipeline.stage.origin.salesforce;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sforce.async.AsyncApiException;
import com.sforce.async.BatchInfo;
import com.sforce.async.BatchInfoList;
import com.sforce.async.BatchStateEnum;
import com.sforce.async.BulkConnection;
import com.sforce.async.ContentType;
import com.sforce.async.JobInfo;
import com.sforce.async.OperationEnum;
import com.sforce.async.QueryResultList;
import com.sforce.soap.partner.Connector;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.soap.partner.QueryResult;
import com.sforce.soap.partner.sobject.SObject;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
import com.sforce.ws.SessionRenewer;
import com.sforce.ws.bind.XmlObject;
import com.streamsets.pipeline.api.BatchMaker;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.base.BaseSource;
import com.streamsets.pipeline.lib.event.CommonEvents;
import com.streamsets.pipeline.lib.salesforce.BulkRecordCreator;
import com.streamsets.pipeline.lib.salesforce.ChangeDataCaptureRecordCreator;
import com.streamsets.pipeline.lib.salesforce.Errors;
import com.streamsets.pipeline.lib.salesforce.ForceConfigBean;
import com.streamsets.pipeline.lib.salesforce.ForceRecordCreator;
import com.streamsets.pipeline.lib.salesforce.ForceRepeatQuery;
import com.streamsets.pipeline.lib.salesforce.ForceSourceConfigBean;
import com.streamsets.pipeline.lib.salesforce.ForceUtils;
import com.streamsets.pipeline.lib.salesforce.PlatformEventRecordCreator;
import com.streamsets.pipeline.lib.salesforce.PushTopicRecordCreator;
import com.streamsets.pipeline.lib.salesforce.ReplayOption;
import com.streamsets.pipeline.lib.salesforce.SoapRecordCreator;
import com.streamsets.pipeline.lib.salesforce.SobjectRecordCreator;
import com.streamsets.pipeline.lib.salesforce.SubscriptionType;
import com.streamsets.pipeline.lib.util.ThreadUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.cometd.bayeux.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soql.SOQLParser;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
public class ForceSource extends BaseSource {
private static final long EVENT_ID_FROM_NOW = -1;
private static final long EVENT_ID_FROM_START = -2;
private static final String RECORD_ID_OFFSET_PREFIX = "recordId:";
private static final String EVENT_ID_OFFSET_PREFIX = "eventId:";
private static final Logger LOG = LoggerFactory.getLogger(ForceSource.class);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final String REPLAY_ID = "replayId";
private static final String AUTHENTICATION_INVALID = "401::Authentication invalid";
private static final String META = "/meta";
private static final String META_HANDSHAKE = "/meta/handshake";
private static final String READ_EVENTS_FROM_NOW = EVENT_ID_OFFSET_PREFIX + EVENT_ID_FROM_NOW;
private static final String SFORCE_ENABLE_PKCHUNKING = "Sforce-Enable-PKChunking";
private static final String CHUNK_SIZE = "chunkSize";
private static final String ID = "Id";
private static final String START_ROW = "startRow";
private static final String CONF_PREFIX = "conf";
private static final String RECORDS = "records";
static final String READ_EVENTS_FROM_START = EVENT_ID_OFFSET_PREFIX + EVENT_ID_FROM_START;
private static final BigDecimal MAX_OFFSET_INT = new BigDecimal(Integer.MAX_VALUE);
private final ForceSourceConfigBean conf;
private PartnerConnection partnerConnection;
private BulkConnection bulkConnection;
private String sobjectType;
// Bulk API state
private BatchInfo batch;
private JobInfo job;
private QueryResultList queryResultList;
private int resultIndex;
private XMLEventReader xmlEventReader;
private Set<String> processedBatches;
private BatchInfoList batchList;
// SOAP API state
private QueryResult queryResult;
private int recordIndex;
private long lastQueryCompletedTime = 0L;
private BlockingQueue<Message> messageQueue;
private ForceStreamConsumer forceConsumer;
private ForceRecordCreator recordCreator;
private boolean shouldSendNoMoreDataEvent = false;
private AtomicBoolean destroyed = new AtomicBoolean(false);
private XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
public ForceSource(
ForceSourceConfigBean conf
) {
this.conf = conf;
xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
}
// Renew the Salesforce session on timeout
public class ForceSessionRenewer implements SessionRenewer {
@Override
public SessionRenewalHeader renewSession(ConnectorConfig config) throws ConnectionException {
LOG.info("Renewing Salesforce session");
try {
partnerConnection = Connector.newConnection(ForceUtils.getPartnerConfig(conf, new ForceSessionRenewer()));
} catch (StageException e) {
throw new ConnectionException("Can't create partner config", e);
}
SessionRenewalHeader header = new SessionRenewalHeader();
header.name = new QName("urn:enterprise.soap.sforce.com", "SessionHeader");
header.headerElement = partnerConnection.getSessionHeader();
return header;
}
}
@Override
protected List<ConfigIssue> init() {
// Validate configuration values and open any required resources.
List<ConfigIssue> issues = super.init();
Optional
.ofNullable(conf.init(getContext(), CONF_PREFIX))
.ifPresent(issues::addAll);
if (!conf.subscribeToStreaming && !conf.queryExistingData) {
issues.add(
getContext().createConfigIssue(
Groups.FORCE.name(), ForceConfigBean.CONF_PREFIX + "queryExistingData", Errors.FORCE_00,
"You must query existing data, subscribe for notifications, or both!"
)
);
}
if (conf.queryExistingData && conf.subscriptionType == SubscriptionType.PLATFORM_EVENT) {
issues.add(
getContext().createConfigIssue(
Groups.FORCE.name(), ForceConfigBean.CONF_PREFIX + "queryExistingData", Errors.FORCE_00,
"You cannot both query existing data and subscribe to a Platform Event!"
)
);
}
if (conf.queryExistingData) {
if (conf.usePKChunking) {
conf.offsetColumn = ID;
}
if (!conf.disableValidation) {
SOQLParser.StatementContext statementContext = ForceUtils.getStatementContext(conf.soqlQuery);
SOQLParser.ConditionExpressionsContext conditionExpressions = statementContext.conditionExpressions();
SOQLParser.FieldOrderByListContext fieldOrderByList = statementContext.fieldOrderByList();
if (conf.usePKChunking) {
if (fieldOrderByList != null) {
issues.add(getContext().createConfigIssue(Groups.QUERY.name(),
ForceConfigBean.CONF_PREFIX + "soqlQuery", Errors.FORCE_31
));
}
if (conditionExpressions != null && checkConditionExpressions(conditionExpressions, ID)) {
issues.add(getContext().createConfigIssue(Groups.QUERY.name(),
ForceConfigBean.CONF_PREFIX + "soqlQuery",
Errors.FORCE_32
));
}
if (conf.repeatQuery == ForceRepeatQuery.INCREMENTAL) {
issues.add(getContext().createConfigIssue(Groups.QUERY.name(),
ForceConfigBean.CONF_PREFIX + "repeatQuery", Errors.FORCE_33
));
}
} else {
if (conditionExpressions == null || !checkConditionExpressions(conditionExpressions,
conf.offsetColumn
) || fieldOrderByList == null || !checkFieldOrderByList(fieldOrderByList, conf.offsetColumn)) {
issues.add(getContext().createConfigIssue(Groups.QUERY.name(),
ForceConfigBean.CONF_PREFIX + "soqlQuery", Errors.FORCE_07, conf.offsetColumn
));
}
}
}
}
if (issues.isEmpty()) {
try {
ConnectorConfig partnerConfig = ForceUtils.getPartnerConfig(conf, new ForceSessionRenewer());
partnerConnection = new PartnerConnection(partnerConfig);
if (conf.mutualAuth.useMutualAuth) {
ForceUtils.setupMutualAuth(partnerConfig, conf.mutualAuth);
}
bulkConnection = ForceUtils.getBulkConnection(partnerConfig, conf);
LOG.info("Successfully authenticated as {}", conf.username);
if (conf.queryExistingData) {
sobjectType = ForceUtils.getSobjectTypeFromQuery(conf.soqlQuery);
LOG.info("Found sobject type {}", sobjectType);
if (sobjectType == null) {
issues.add(getContext().createConfigIssue(Groups.QUERY.name(),
ForceConfigBean.CONF_PREFIX + "soqlQuery",
Errors.FORCE_00,
"Badly formed SOQL Query: " + conf.soqlQuery
));
}
}
} catch (ConnectionException | AsyncApiException | StageException | URISyntaxException e) {
LOG.error("Error connecting: {}", e);
issues.add(getContext().createConfigIssue(Groups.FORCE.name(),
ForceConfigBean.CONF_PREFIX + "authEndpoint",
Errors.FORCE_00,
ForceUtils.getExceptionCode(e) + ", " + ForceUtils.getExceptionMessage(e)
));
}
}
if (issues.isEmpty() && conf.subscribeToStreaming) {
switch (conf.subscriptionType) {
case PUSH_TOPIC:
setObjectTypeFromQuery(issues);
break;
case PLATFORM_EVENT:
// Do nothing
break;
case CDC:
sobjectType = conf.cdcObject;
break;
}
messageQueue = new ArrayBlockingQueue<>(2 * conf.basicConfig.maxBatchSize);
}
if (issues.isEmpty()) {
recordCreator = buildRecordCreator();
try {
recordCreator.init();
} catch (StageException e) {
issues.add(getContext().createConfigIssue(null, null, Errors.FORCE_34, e));
}
}
// If issues is not empty, the UI will inform the user of each configuration issue in the list.
return issues;
}
private void setObjectTypeFromQuery(List<ConfigIssue> issues) {
String query = "SELECT Id, Query FROM PushTopic WHERE Name = '"+conf.pushTopic+"'";
try {
QueryResult qr = partnerConnection.query(query);
if (qr.getSize() != 1) {
issues.add(
getContext().createConfigIssue(
Groups.SUBSCRIBE.name(), ForceConfigBean.CONF_PREFIX + "pushTopic", Errors.FORCE_00,
"Can't find Push Topic '" + conf.pushTopic +"'"
)
);
} else if (null == sobjectType) {
String soqlQuery = (String)qr.getRecords()[0].getField("Query");
try {
sobjectType = ForceUtils.getSobjectTypeFromQuery(soqlQuery);
LOG.info("Found sobject type {}", sobjectType);
} catch (StageException e) {
issues.add(getContext().createConfigIssue(Groups.SUBSCRIBE.name(),
ForceConfigBean.CONF_PREFIX + "pushTopic",
Errors.FORCE_00,
"Badly formed SOQL Query: " + soqlQuery
));
}
}
} catch (ConnectionException e) {
issues.add(
getContext().createConfigIssue(
Groups.FORCE.name(), ForceConfigBean.CONF_PREFIX + "authEndpoint", Errors.FORCE_00, e
)
);
}
}
// Returns true if the first ORDER BY field matches fieldName
private boolean checkFieldOrderByList(SOQLParser.FieldOrderByListContext fieldOrderByList, String fieldName) {
return fieldOrderByList.fieldOrderByElement(0).fieldElement().getText().equalsIgnoreCase(fieldName);
}
// Returns true if any of the nested conditions contains fieldName
private boolean checkConditionExpressions(
SOQLParser.ConditionExpressionsContext conditionExpressions,
String fieldName
) {
for (SOQLParser.ConditionExpressionContext ce : conditionExpressions.conditionExpression()) {
if ((ce.conditionExpressions() != null && checkConditionExpressions(ce.conditionExpressions(), fieldName))
|| (ce.fieldExpression() != null && ce.fieldExpression().fieldElement().getText().equalsIgnoreCase(fieldName))) {
return true;
}
}
return false;
}
private ForceRecordCreator buildRecordCreator() {
if (conf.queryExistingData) {
if (conf.useBulkAPI) {
//IMPORTANT: BulkRecordCreator is not thread safe since it is using SimpleDateFormat
return new BulkRecordCreator(getContext(), conf, sobjectType);
} else {
return new SoapRecordCreator(getContext(), conf, sobjectType);
}
} else if (conf.subscribeToStreaming) {
switch (conf.subscriptionType) {
case PUSH_TOPIC:
return new PushTopicRecordCreator(getContext(), conf, sobjectType);
case PLATFORM_EVENT:
return new PlatformEventRecordCreator(getContext(), conf.platformEvent, conf);
case CDC:
return new ChangeDataCaptureRecordCreator(getContext(), conf, sobjectType);
}
}
return null;
}
/** {@inheritDoc} */
@Override
public void destroy() {
// SDC-6258 - destroy() is called from a different thread, so we
// need to signal produce() to terminate early
destroyed.set(true);
if (job != null) {
try {
bulkConnection.abortJob(job.getId());
job = null;
} catch (AsyncApiException e) {
LOG.error("Exception while aborting job", e);
}
}
job = null;
if (forceConsumer != null) {
try {
forceConsumer.stop();
forceConsumer = null;
} catch (Exception e) {
LOG.error("Exception while stopping ForceStreamConsumer.", e);
}
if (!messageQueue.isEmpty()) {
LOG.error("Queue still had {} entities at shutdown.", messageQueue.size());
} else {
LOG.info("Queue was empty at shutdown. No data lost.");
}
}
if (recordCreator != null) {
recordCreator.destroy();
}
// Clean up any open resources.
super.destroy();
}
private String prepareQuery(String query, String lastSourceOffset) throws StageException {
final String offset = (null == lastSourceOffset) ? conf.initialOffset : lastSourceOffset;
SobjectRecordCreator sobjectRecordCreator = (SobjectRecordCreator)recordCreator;
String expandedQuery;
if (sobjectRecordCreator.queryHasWildcard(query)) {
// Can't follow relationships on a wildcard query, so build the cache from the object type
sobjectRecordCreator.buildMetadataCache(partnerConnection);
expandedQuery = sobjectRecordCreator.expandWildcard(query);
} else {
// Use the query in building the cache
expandedQuery = query;
sobjectRecordCreator.buildMetadataCacheFromQuery(partnerConnection, query);
}
return expandedQuery.replaceAll("\\$\\{offset\\}", offset);
}
/** {@inheritDoc} */
@Override
public String produce(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker) throws StageException {
String nextSourceOffset = null;
LOG.debug("lastSourceOffset: {}", lastSourceOffset);
// send event only once for each time we run out of data.
if(shouldSendNoMoreDataEvent) {
CommonEvents.NO_MORE_DATA.create(getContext()).createAndSend();
shouldSendNoMoreDataEvent = false;
return lastSourceOffset;
}
int batchSize = Math.min(conf.basicConfig.maxBatchSize, maxBatchSize);
if (!conf.queryExistingData ||
(null != lastSourceOffset && lastSourceOffset.startsWith(EVENT_ID_OFFSET_PREFIX))) {
if (conf.subscribeToStreaming) {
nextSourceOffset = streamingProduce(lastSourceOffset, batchSize, batchMaker);
} else {
// We're done reading existing data, but we don't want to subscribe to Streaming API
return null;
}
} else if (conf.queryExistingData) {
if (!queryInProgress()) {
long now = System.currentTimeMillis();
long delay = Math.max(0, (lastQueryCompletedTime + (1000 * conf.queryInterval)) - now);
if (delay > 0) {
// Sleep in one second increments so we don't tie up the app.
LOG.info("{}ms remaining until next fetch.", delay);
ThreadUtil.sleep(Math.min(delay, 1000));
return lastSourceOffset;
}
}
if (conf.useBulkAPI) {
nextSourceOffset = bulkProduce(lastSourceOffset, batchSize, batchMaker);
} else {
nextSourceOffset = soapProduce(lastSourceOffset, batchSize, batchMaker);
}
} else if (conf.subscribeToStreaming) {
// No offset, and we're not querying existing data, so switch to streaming
nextSourceOffset = READ_EVENTS_FROM_NOW;
}
LOG.debug("nextSourceOffset: {}", nextSourceOffset);
return nextSourceOffset;
}
private boolean queryInProgress() {
return (conf.useBulkAPI && job != null) || (!conf.useBulkAPI && queryResult != null);
}
private String bulkProduce(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker) throws StageException {
String nextSourceOffset = (null == lastSourceOffset) ? RECORD_ID_OFFSET_PREFIX + conf.initialOffset : lastSourceOffset;
if (job == null) {
// No job in progress - start from scratch
try {
String id = (lastSourceOffset == null) ? null : lastSourceOffset.substring(lastSourceOffset.indexOf(':') + 1);
final String preparedQuery = prepareQuery(conf.soqlQuery, id);
LOG.info("SOQL Query is: {}", preparedQuery);
if (destroyed.get()) {
throw new StageException(getContext().isPreview() ? Errors.FORCE_25 : Errors.FORCE_26);
}
job = createJob(sobjectType, bulkConnection);
LOG.info("Created Bulk API job {}", job.getId());
if (destroyed.get()) {
throw new StageException(getContext().isPreview() ? Errors.FORCE_25 : Errors.FORCE_26);
}
BatchInfo b = bulkConnection.createBatchFromStream(job,
new ByteArrayInputStream(preparedQuery.getBytes(StandardCharsets.UTF_8)));
LOG.info("Created Bulk API batch {}", b.getId());
processedBatches = new HashSet<>();
} catch (AsyncApiException e) {
throw new StageException(Errors.FORCE_01, e);
}
}
// We started the job already, see if the results are ready
// Loop here so that we can wait for results in preview mode and not return an empty batch
// Preview will cut us off anyway if we wait too long
while (queryResultList == null) {
if (destroyed.get()) {
throw new StageException(getContext().isPreview() ? Errors.FORCE_25 : Errors.FORCE_26);
}
try {
// PK Chunking gives us multiple batches - process them in turn
batchList = bulkConnection.getBatchInfoList(job.getId());
for (BatchInfo batchInfo : batchList.getBatchInfo()) {
if (batchInfo.getState() == BatchStateEnum.Failed) {
LOG.error("Batch {} failed: {}", batchInfo.getId(), batchInfo.getStateMessage());
throw new StageException(Errors.FORCE_03, batchInfo.getStateMessage());
} else if (!processedBatches.contains(batchInfo.getId())) {
if (batchInfo.getState() == BatchStateEnum.NotProcessed) {
// Skip this batch - it's the 'original batch' in PK chunking
// See https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/asynch_api_code_curl_walkthrough_pk_chunking.htm
LOG.info("Batch {} not processed", batchInfo.getId());
processedBatches.add(batchInfo.getId());
} else if (batchInfo.getState() == BatchStateEnum.Completed) {
LOG.info("Batch {} completed", batchInfo.getId());
batch = batchInfo;
queryResultList = bulkConnection.getQueryResultList(job.getId(), batch.getId());
LOG.info("Query results: {}", queryResultList.getResult());
resultIndex = 0;
break;
}
}
}
if (queryResultList == null) {
// Bulk API is asynchronous, so wait a little while...
try {
LOG.info("Waiting {} milliseconds for job {}", conf.basicConfig.maxWaitTime, job.getId());
Thread.sleep(conf.basicConfig.maxWaitTime);
} catch (InterruptedException e) {
LOG.debug("Interrupted while sleeping");
Thread.currentThread().interrupt();
}
if (!getContext().isPreview()) { // If we're in preview, then don't return an empty batch!
LOG.info("Job {} in progress", job.getId());
return nextSourceOffset;
}
}
} catch (AsyncApiException e) {
throw new StageException(Errors.FORCE_02, e);
}
}
if (xmlEventReader == null && queryResultList != null) {
// We have results - retrieve the next one!
String resultId = queryResultList.getResult()[resultIndex];
resultIndex++;
try {
xmlEventReader = xmlInputFactory.createXMLEventReader(bulkConnection.getQueryResultStream(job.getId(), batch.getId(), resultId));
} catch (AsyncApiException e) {
throw new StageException(Errors.FORCE_05, e);
} catch (XMLStreamException e) {
throw new StageException(Errors.FORCE_36, e);
}
}
if (xmlEventReader != null){
int numRecords = 0;
while (xmlEventReader.hasNext() && numRecords < maxBatchSize) {
try {
XMLEvent event = xmlEventReader.nextEvent();
if (event.isStartElement() && event.asStartElement().getName().getLocalPart().equals(RECORDS)) {
// SDC-9731 will refactor record creators so we don't need this downcast
String offset = ((BulkRecordCreator) recordCreator).createRecord(xmlEventReader, batchMaker);
nextSourceOffset = RECORD_ID_OFFSET_PREFIX + offset;
++numRecords;
}
} catch (XMLStreamException e) {
throw new StageException(Errors.FORCE_37, e);
}
}
if (!xmlEventReader.hasNext()) {
// Exhausted this result - come back in on the next batch
xmlEventReader = null;
if (resultIndex == queryResultList.getResult().length) {
// We're out of results, too!
processedBatches.add(batch.getId());
queryResultList = null;
batch = null;
if (processedBatches.size() == batchList.getBatchInfo().length) {
// And we're done with the job
try {
bulkConnection.closeJob(job.getId());
lastQueryCompletedTime = System.currentTimeMillis();
LOG.info("Query completed at: {}", lastQueryCompletedTime);
} catch (AsyncApiException e) {
LOG.error("Error closing job: {}", e);
}
LOG.info("Partial batch of {} records", numRecords);
job = null;
shouldSendNoMoreDataEvent = true;
if (conf.subscribeToStreaming) {
// Switch to processing events
nextSourceOffset = READ_EVENTS_FROM_NOW;
} else if (conf.repeatQuery == ForceRepeatQuery.FULL) {
nextSourceOffset = RECORD_ID_OFFSET_PREFIX + conf.initialOffset;
} else if (conf.repeatQuery == ForceRepeatQuery.NO_REPEAT) {
nextSourceOffset = null;
}
}
}
}
LOG.info("Full batch of {} records", numRecords);
}
return nextSourceOffset;
}
private static XmlObject getChildIgnoreCase(SObject record, String name) {
XmlObject item = null;
Iterator<XmlObject> iter = record.getChildren();
while(iter.hasNext()) {
XmlObject child = iter.next();
if(child.getName().getLocalPart().equalsIgnoreCase(name)) {
item = child;
break;
}
}
return item;
}
private String soapProduce(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker) throws StageException {
String nextSourceOffset = (null == lastSourceOffset) ? RECORD_ID_OFFSET_PREFIX + conf.initialOffset : lastSourceOffset;
if (queryResult == null) {
try {
String id = (lastSourceOffset == null) ? null : lastSourceOffset.substring(lastSourceOffset.indexOf(':') + 1);
final String preparedQuery = prepareQuery(conf.soqlQuery, id);
LOG.info("preparedQuery: {}", preparedQuery);
queryResult = conf.queryAll
? partnerConnection.queryAll(preparedQuery)
: partnerConnection.query(preparedQuery);
recordIndex = 0;
} catch (ConnectionException e) {
throw new StageException(Errors.FORCE_08, e);
}
}
SObject[] records = queryResult.getRecords();
LOG.info("Retrieved {} records", records.length);
int endIndex = Math.min(recordIndex + maxBatchSize, records.length);
for ( ;recordIndex < endIndex; recordIndex++) {
SObject record = records[recordIndex];
XmlObject offsetField = getChildIgnoreCase(record, conf.offsetColumn);
if (offsetField == null || offsetField.getValue() == null) {
throw new StageException(Errors.FORCE_22, conf.offsetColumn);
}
String offset = fixOffset(conf.offsetColumn, offsetField.getValue().toString());
nextSourceOffset = RECORD_ID_OFFSET_PREFIX + offset;
final String sourceId = conf.soqlQuery + "::" + offset;
Record rec = recordCreator.createRecord(sourceId, record);
batchMaker.addRecord(rec);
}
if (recordIndex == records.length) {
try {
if (queryResult.isDone()) {
// We're out of results
queryResult = null;
lastQueryCompletedTime = System.currentTimeMillis();
LOG.info("Query completed at: {}", lastQueryCompletedTime);
shouldSendNoMoreDataEvent = true;
if (conf.subscribeToStreaming) {
// Switch to processing events
nextSourceOffset = READ_EVENTS_FROM_NOW;
} else if (conf.repeatQuery == ForceRepeatQuery.FULL) {
nextSourceOffset = RECORD_ID_OFFSET_PREFIX + conf.initialOffset;
} else if (conf.repeatQuery == ForceRepeatQuery.NO_REPEAT) {
nextSourceOffset = null;
}
} else {
queryResult = partnerConnection.queryMore(queryResult.getQueryLocator());
recordIndex = 0;
}
} catch (ConnectionException e) {
throw new StageException(Errors.FORCE_08, e);
}
}
return nextSourceOffset;
}
// SDC-9078 - coerce scientific notation away when decimal field scale is zero
// since Salesforce doesn't like scientific notation in queries
private String fixOffset(String offsetColumn, String offset) {
com.sforce.soap.partner.Field sfdcField = ((SobjectRecordCreator)recordCreator).getFieldMetadata(sobjectType, offsetColumn);
if (SobjectRecordCreator.DECIMAL_TYPES.contains(sfdcField.getType().toString())
&& offset.contains("E")) {
BigDecimal val = new BigDecimal(offset);
offset = val.toPlainString();
if (val.compareTo(MAX_OFFSET_INT) > 0 && !offset.contains(".")) {
// We need the ".0" suffix since Salesforce doesn't like integer
// bigger than 2147483647
offset += ".0";
}
}
return offset;
}
private void processMetaMessage(Message message, String nextSourceOffset) throws StageException {
if (message.getChannel().startsWith(META_HANDSHAKE) && message.isSuccessful()) {
// Need to (re)subscribe after handshake - see
// https://developer.salesforce.com/docs/atlas.en-us.api_streaming.meta/api_streaming/using_streaming_api_client_connection.htm
try {
forceConsumer.subscribeForNotifications(nextSourceOffset);
} catch (InterruptedException e) {
LOG.error(Errors.FORCE_10.getMessage(), e);
throw new StageException(Errors.FORCE_10, e.getMessage(), e);
}
} else if (!message.isSuccessful()) {
String error = (String) message.get("error");
LOG.info("Bayeux error message: {}", error);
if (AUTHENTICATION_INVALID.equals(error)) {
// This happens when the session token, stored in the HttpClient as a cookie,
// has expired, and we try to use it in a handshake.
// Just kill the consumer and start all over again.
LOG.info("Reconnecting after {}", AUTHENTICATION_INVALID);
try {
forceConsumer.stop();
} catch (Exception ex) {
LOG.info("Exception stopping consumer", ex);
}
forceConsumer = null;
} else {
// Some other problem...
Exception exception = (Exception) message.get("exception");
LOG.info("Bayeux exception:", exception);
throw new StageException(Errors.FORCE_09, error, exception);
}
}
}
@SuppressWarnings("unchecked")
private String processDataMessage(Message message, BatchMaker batchMaker)
throws IOException, StageException {
String msgJson = message.getJSON();
// PushTopic Message has the form
// {
// "channel": "/topic/AccountUpdates",
// "clientId": "j17ylcz9l0t0fyp0pze7uzpqlt",
// "data": {
// "event": {
// "createdDate": "2016-09-15T06:01:40.000+0000",
// "type": "updated"
// },
// "sobject": {
// "AccountNumber": "3231321",
// "Id": "0013600000dC5xLAAS",
// "Name": "StreamSets",
// ...
// }
// }
// }
// Platform Event Message has the form
// {
// "data": {
// "schema": "dffQ2QLzDNHqwB8_sHMxdA",
// "payload": {
// "CreatedDate": "2017-04-09T18:31:40Z",
// "CreatedById": "005D0000001cSZs",
// "Printer_Model__c": "XZO-5",
// "Serial_Number__c": "12345",
// "Ink_Percentage__c": 0.2
// },
// "event": {
// "replayId": 2
// }
// },
// "channel": "/event/Low_Ink__e"
// }
LOG.info("Processing message: {}", msgJson);
Object json = OBJECT_MAPPER.readValue(msgJson, Object.class);
Map<String, Object> jsonMap = (Map<String, Object>) json;
Map<String, Object> data = (Map<String, Object>) jsonMap.get("data");
Map<String, Object> event = (Map<String, Object>) data.get("event");
Map<String, Object> sobject = (Map<String, Object>) data.get("sobject");
final String sourceId = (conf.subscriptionType == SubscriptionType.PUSH_TOPIC)
? event.get("createdDate") + "::" + sobject.get("Id")
: event.get("replayId").toString();
Record rec = recordCreator.createRecord(sourceId, Pair.of(partnerConnection, data));
batchMaker.addRecord(rec);
return EVENT_ID_OFFSET_PREFIX + event.get(REPLAY_ID).toString();
}
private String streamingProduce(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker) throws StageException {
String nextSourceOffset;
if (getContext().isPreview()) {
nextSourceOffset = READ_EVENTS_FROM_START;
} else if (null == lastSourceOffset) {
if (conf.subscriptionType == SubscriptionType.PLATFORM_EVENT &&
conf.replayOption == ReplayOption.ALL_EVENTS) {
nextSourceOffset = READ_EVENTS_FROM_START;
} else {
nextSourceOffset = READ_EVENTS_FROM_NOW;
}
} else {
nextSourceOffset = lastSourceOffset;
}
if (conf.subscriptionType == SubscriptionType.PUSH_TOPIC && !(recordCreator instanceof PushTopicRecordCreator)) {
recordCreator = new PushTopicRecordCreator((SobjectRecordCreator)recordCreator);
}
if (recordCreator instanceof SobjectRecordCreator) {
SobjectRecordCreator sobjectRecordCreator = (SobjectRecordCreator)recordCreator;
if (!StringUtils.isEmpty(sobjectType) && !sobjectRecordCreator.metadataCacheExists()) {
sobjectRecordCreator.buildMetadataCache(partnerConnection);
}
}
if (forceConsumer == null) {
// Do a request so we ensure that the connection is renewed if necessary
try {
partnerConnection.getUserInfo();
} catch (ConnectionException e) {
LOG.error("Exception getting user info", e);
throw new StageException(Errors.FORCE_19, e.getMessage(), e);
}
forceConsumer = new ForceStreamConsumer(messageQueue, partnerConnection, conf);
forceConsumer.start();
}
if (getContext().isPreview()) {
// Give waiting messages a chance to arrive
ThreadUtil.sleep(1000);
}
// We didn't receive any new data within the time allotted for this batch.
if (messageQueue.isEmpty()) {
// In preview, we already waited
if (! getContext().isPreview()) {
// Sleep for one second so we don't tie up the app.
ThreadUtil.sleep(1000);
}
return nextSourceOffset;
}
// Loop if we're in preview mode - we'll get killed after the preview timeout if no data arrives
boolean done = false;
while (!done) {
List<Message> messages = new ArrayList<>(maxBatchSize);
messageQueue.drainTo(messages, maxBatchSize);
for (Message message : messages) {
try {
if (message.getChannel().startsWith(META)) {
// Handshake, subscription messages
processMetaMessage(message, nextSourceOffset);
} else {
// Yay - actual data messages
nextSourceOffset = processDataMessage(message, batchMaker);
done = true;
}
} catch (IOException e) {
throw new StageException(Errors.FORCE_02, e);
}
}
if (!done && getContext().isPreview()) {
// In preview - give data messages a chance to arrive
if (!ThreadUtil.sleep(1000)) {
// Interrupted!
done = true;
}
} else {
done = true;
}
}
return nextSourceOffset;
}
private JobInfo createJob(String sobjectType, BulkConnection connection)
throws AsyncApiException {
JobInfo job = new JobInfo();
job.setObject(sobjectType);
job.setOperation((conf.queryAll && !conf.usePKChunking) ? OperationEnum.queryAll : OperationEnum.query);
job.setContentType(ContentType.XML);
if (conf.usePKChunking) {
String headerValue = CHUNK_SIZE + "=" + conf.chunkSize;
if (!StringUtils.isEmpty(conf.startId)) {
headerValue += "; " + START_ROW + "=" + conf.startId;
}
connection.addHeader(SFORCE_ENABLE_PKCHUNKING, headerValue);
}
job = connection.createJob(job);
return job;
}
} | {
"content_hash": "a38db0b97118953a3d69a58d16b5c080",
"timestamp": "",
"source": "github",
"line_count": 919,
"max_line_length": 146,
"avg_line_length": 38.674646354733405,
"alnum_prop": 0.6590512632941309,
"repo_name": "rockmkd/datacollector",
"id": "de23a312f20345d9030c81171b7f2fd2b5b3e7a1",
"size": "36140",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "salesforce-lib/src/main/java/com/streamsets/pipeline/stage/origin/salesforce/ForceSource.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "101291"
},
{
"name": "CSS",
"bytes": "120603"
},
{
"name": "Groovy",
"bytes": "11876"
},
{
"name": "HTML",
"bytes": "528951"
},
{
"name": "Java",
"bytes": "20152513"
},
{
"name": "JavaScript",
"bytes": "1070702"
},
{
"name": "Python",
"bytes": "7413"
},
{
"name": "Scala",
"bytes": "6347"
},
{
"name": "Shell",
"bytes": "30088"
}
],
"symlink_target": ""
} |
<?php
/**
* @file
* Definition of Drupal\block\Tests\BlockAdminThemeTest.
*/
namespace Drupal\block\Tests;
use Drupal\simpletest\WebTestBase;
/**
* Tests the block system with admin themes.
*
* @group block
*/
class BlockAdminThemeTest extends WebTestBase {
/**
* Modules to install.
*
* @var array
*/
public static $modules = array('block');
/**
* Check for the accessibility of the admin theme on the block admin page.
*/
function testAdminTheme() {
// Create administrative user.
$admin_user = $this->drupalCreateUser(array('administer blocks', 'administer themes'));
$this->drupalLogin($admin_user);
// Ensure that access to block admin page is denied when theme is not
// installed.
$this->drupalGet('admin/structure/block/list/bartik');
$this->assertResponse(403);
// Install admin theme and confirm that tab is accessible.
\Drupal::service('theme_handler')->install(array('bartik'));
$edit['admin_theme'] = 'bartik';
$this->drupalPostForm('admin/appearance', $edit, t('Save configuration'));
$this->drupalGet('admin/structure/block/list/bartik');
$this->assertResponse(200);
}
}
| {
"content_hash": "ce8407682421d69da7108c8f816d1297",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 91,
"avg_line_length": 25.695652173913043,
"alnum_prop": 0.6725888324873096,
"repo_name": "ital-lion/Drupal4Lions",
"id": "073f64f0d0c4483f4b4a2f3fa687a1f53c70ad73",
"size": "1182",
"binary": false,
"copies": "43",
"ref": "refs/heads/master",
"path": "core/modules/block/src/Tests/BlockAdminThemeTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "280823"
},
{
"name": "JavaScript",
"bytes": "742500"
},
{
"name": "PHP",
"bytes": "20371861"
},
{
"name": "Shell",
"bytes": "70992"
}
],
"symlink_target": ""
} |
Returns the value of the path segment for the index specified or null if not found.
```php
public string|null getSegment ( int $index )
```
## Parameters
##### index
the index of the path segment.
## Returns
The value of the path segment for the index specified or null if not found.
## Details
Class: [BearFramework\App\Request\Path](bearframework.app.request.path.class.md)
Location: ~/src/App/Request/Path.php
---
[back to index](index.md)
| {
"content_hash": "7c323bbd442f81db57c8a5253812865a",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 111,
"avg_line_length": 20.26923076923077,
"alnum_prop": 0.715370018975332,
"repo_name": "bearframework/bearframework",
"id": "09b6aa91358347b624136a551c2bb05d4fba26dc",
"size": "573",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/markdown/bearframework.app.request.path.getsegment.method.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "607088"
}
],
"symlink_target": ""
} |
package org.assertj.core.internal.maps;
import static java.util.Collections.emptyMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.shouldHaveThrown;
import static org.assertj.core.data.MapEntry.entry;
import static org.assertj.core.error.ShouldContainExactly.elementsDifferAtIndex;
import static org.assertj.core.error.ShouldContainExactly.shouldContainExactly;
import static org.assertj.core.error.ShouldHaveSameSizeAs.shouldHaveSameSizeAs;
import static org.assertj.core.test.ErrorMessages.entriesToLookForIsEmpty;
import static org.assertj.core.test.ErrorMessages.entriesToLookForIsNull;
import static org.assertj.core.test.TestData.someInfo;
import static org.assertj.core.util.Arrays.array;
import static org.assertj.core.util.FailureMessages.actualIsNull;
import static org.mockito.Mockito.verify;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.data.MapEntry;
import org.assertj.core.internal.MapsBaseTest;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for
* <code>{@link org.assertj.core.internal.Maps#assertContainsExactly(org.assertj.core.api.AssertionInfo, java.util.Map, org.assertj.core.data.MapEntry...)}</code>
* .
*
* @author Jean-Christophe Gay
*/
public class Maps_assertContainsExactly_Test extends MapsBaseTest {
private LinkedHashMap<String, String> linkedActual;
@Before
public void initLinkedHashMap() throws Exception {
linkedActual = new LinkedHashMap<>(2);
linkedActual.put("name", "Yoda");
linkedActual.put("color", "green");
}
@SuppressWarnings("unchecked")
@Test
public void should_fail_if_actual_is_null() throws Exception {
thrown.expectAssertionError(actualIsNull());
maps.assertContainsExactly(someInfo(), null, entry("name", "Yoda"));
}
@SuppressWarnings("unchecked")
@Test
public void should_fail_if_given_entries_array_is_null() throws Exception {
thrown.expectNullPointerException(entriesToLookForIsNull());
maps.assertContainsExactly(someInfo(), linkedActual, (MapEntry[])null);
}
@SuppressWarnings("unchecked")
@Test
public void should_fail_if_given_entries_array_is_empty() throws Exception {
thrown.expectIllegalArgumentException(entriesToLookForIsEmpty());
maps.assertContainsExactly(someInfo(), linkedActual, emptyEntries());
}
@SuppressWarnings("unchecked")
@Test
public void should_pass_if_actual_and_entries_are_empty() throws Exception {
maps.assertContainsExactly(someInfo(), emptyMap(), emptyEntries());
}
@SuppressWarnings("unchecked")
@Test
public void should_pass_if_actual_contains_given_entries_in_order() throws Exception {
maps.assertContainsExactly(someInfo(), linkedActual, entry("name", "Yoda"), entry("color", "green"));
}
@SuppressWarnings("unchecked")
@Test
public void should_fail_if_actual_contains_given_entries_in_disorder() throws Exception {
AssertionInfo info = someInfo();
try {
maps.assertContainsExactly(info, linkedActual, entry("color", "green"), entry("name", "Yoda"));
} catch (AssertionError e) {
verify(failures).failure(info, elementsDifferAtIndex(entry("name", "Yoda"), entry("color", "green"), 0));
return;
}
shouldHaveThrown(AssertionError.class);
}
@Test
public void should_fail_if_actual_and_expected_entries_have_different_size() throws Exception {
AssertionInfo info = someInfo();
MapEntry<String, String>[] expected = array(entry("name", "Yoda"));
try {
maps.assertContainsExactly(info, linkedActual, expected);
} catch (AssertionError e) {
assertThat(e).hasMessage(shouldHaveSameSizeAs(linkedActual, linkedActual.size(), expected.length).create());
return;
}
shouldHaveThrown(AssertionError.class);
}
@Test
public void should_fail_if_actual_does_not_contains_every_expected_entries_and_contains_unexpected_one()
throws Exception {
AssertionInfo info = someInfo();
MapEntry<String, String>[] expected = array(entry("name", "Yoda"), entry("color", "green"));
Map<String, String> underTest = newLinkedHashMap(entry("name", "Yoda"), entry("job", "Jedi"));
try {
maps.assertContainsExactly(info, underTest, expected);
} catch (AssertionError e) {
verify(failures).failure(
info,
shouldContainExactly(underTest, expected, newHashSet(entry("color", "green")),
newHashSet(entry("job", "Jedi"))));
return;
}
shouldHaveThrown(AssertionError.class);
}
@Test
public void should_fail_if_actual_contains_entry_key_with_different_value() throws Exception {
AssertionInfo info = someInfo();
MapEntry<String, String>[] expectedEntries = array(entry("name", "Yoda"), entry("color", "yellow"));
try {
maps.assertContainsExactly(info, actual, expectedEntries);
} catch (AssertionError e) {
verify(failures).failure(
info,
shouldContainExactly(actual, expectedEntries, newHashSet(entry("color", "yellow")),
newHashSet(entry("color", "green"))));
return;
}
shouldHaveThrown(AssertionError.class);
}
@SafeVarargs
private static Map<String, String> newLinkedHashMap(MapEntry<String, String>... entries) {
LinkedHashMap<String, String> result = new LinkedHashMap<>();
for (MapEntry<String, String> entry : entries) {
result.put(entry.key, entry.value);
}
return result;
}
private static <K, V> Set<MapEntry<K, V>> newHashSet(MapEntry<K, V> entry) {
LinkedHashSet<MapEntry<K, V>> result = new LinkedHashSet<>();
result.add(entry);
return result;
}
}
| {
"content_hash": "b33951b55718113a49ce009925ee92fc",
"timestamp": "",
"source": "github",
"line_count": 155,
"max_line_length": 162,
"avg_line_length": 37.038709677419355,
"alnum_prop": 0.7225222086744469,
"repo_name": "dorzey/assertj-core",
"id": "c92690bedd21c3cedbe99e5b843a8117af6b40b6",
"size": "6348",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/org/assertj/core/internal/maps/Maps_assertContainsExactly_Test.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "8364137"
},
{
"name": "Shell",
"bytes": "40820"
}
],
"symlink_target": ""
} |
/** @file common.h Generic libraries, parameters and functions used in the whole code. */
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include "string.h"
#include "float.h"
#include "svnversion.h"
#include <stdarg.h>
#ifdef _OPENMP
#include "omp.h"
#endif
#ifndef __COMMON__
#define __COMMON__
#define _VERSION_ "v2.5.0"
/* @cond INCLUDE_WITH_DOXYGEN */
#define _TRUE_ 1 /**< integer associated to true statement */
#define _FALSE_ 0 /**< integer associated to false statement */
#define _SUCCESS_ 0 /**< integer returned after successful call of a function */
#define _FAILURE_ 1 /**< integer returned after failure in a function */
#define _ERRORMSGSIZE_ 2048 /**< generic error messages are cut beyond this number of characters */
typedef char ErrorMsg[_ERRORMSGSIZE_]; /**< Generic error messages (there is such a field in each structure) */
#define _FILENAMESIZE_ 256 /**< size of the string read in each line of the file (extra characters not taken into account) */
typedef char FileName[_FILENAMESIZE_];
#define _PI_ 3.1415926535897932384626433832795e0 /**< The number pi */
#define _PIHALF_ 1.57079632679489661923132169164e0 /**< pi divided by 2 */
#define _TWOPI_ 6.283185307179586476925286766559e0 /**< 2 times pi */
#define _SQRT2_ 1.41421356237309504880168872421e0 /** < square root of 2. */
#define _SQRT6_ 2.4494897427831780981972840747059e0 /**< square root of 6. */
#define _SQRT_PI_ 1.77245385090551602729816748334e0 /**< square root of pi. */
#define _MAX_IT_ 10000/**< default maximum number of iterations in conditional loops (to avoid infinite loops) */
#define _QUADRATURE_MAX_ 250 /**< maximum allowed number of abssices in quadrature integral estimation */
#define _QUADRATURE_MAX_BG_ 800 /**< maximum allowed number of abssices in quadrature integral estimation */
#define _TOLVAR_ 100. /**< The minimum allowed variation is the machine precision times this number */
#define _HUGE_ 1.e99
#define _OUTPUTPRECISION_ 12 /**< Number of significant digits in some output files */
#define _COLUMNWIDTH_ 24 /**< Must be at least _OUTPUTPRECISION_+8 for guaranteed fixed width columns */
#define _MAXTITLESTRINGLENGTH_ 8000 /**< Maximum number of characters in title strings */
#define _DELIMITER_ "\t" /**< character used for delimiting titles in the title strings */
#ifndef __CLASSDIR__
#define __CLASSDIR__ "." /**< The directory of CLASS. This is set to the absolute path to the CLASS directory so this is just a failsafe. */
#endif
#define MIN(a,b) (((a)<(b)) ? (a) : (b) ) /**< the usual "min" function */
#define MAX(a,b) (((a)<(b)) ? (b) : (a) ) /**< the usual "max" function */
#define SIGN(a) (((a)>0) ? 1. : -1. )
#define NRSIGN(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a))
#define index_symmetric_matrix(i1,i2,N) (((i1)<=(i2)) ? (i2+N*i1-(i1*(i1+1))/2) : (i1+N*i2-(i2*(i2+1))/2)) /**< assigns an index from 0 to [N(N+1)/2-1] to the coefficients M_{i1,i2} of an N*N symmetric matrix; useful for converting a symmetric matrix to a vector, without losing or double-counting any information */
/* @endcond */
// needed because of weird openmp bug on macosx lion...
void class_protect_sprintf(char* dest, char* tpl,...);
void class_protect_fprintf(FILE* dest, char* tpl,...);
void* class_protect_memcpy(void* dest, void* from, size_t sz);
int get_number_of_titles(char * titlestring);
#define class_build_error_string(dest,tmpl,...) { \
ErrorMsg FMsg; \
class_protect_sprintf(FMsg,tmpl,__VA_ARGS__); \
class_protect_sprintf(dest,"%s(L:%d) :%s",__func__,__LINE__,FMsg); \
}
// Error reporting macros
// Call
#define class_call_message(err_out,extra,err_mess) \
class_build_error_string(err_out,"error in %s;\n=>%s",extra,err_mess);
/* macro for calling function and returning error if it failed */
#define class_call_except(function, error_message_from_function, error_message_output,list_of_commands) { \
if (function == _FAILURE_) { \
class_call_message(error_message_output,#function,error_message_from_function); \
list_of_commands; \
return _FAILURE_; \
} \
}
/* macro for trying to call function */
#define class_call_try(function, error_message_from_function, error_message_output,list_of_commands) { \
if (function == _FAILURE_) { \
class_call_message(error_message_output,#function,error_message_from_function); \
list_of_commands; \
} \
}
/* macro for calling function and returning error if it failed */
#define class_call(function, error_message_from_function, error_message_output) \
class_call_except(function, error_message_from_function,error_message_output,)
/* same in parallel region */
#define class_call_parallel(function, error_message_from_function, error_message_output) { \
if (abort == _FALSE_) { \
if (function == _FAILURE_) { \
class_call_message(error_message_output,#function,error_message_from_function); \
abort=_TRUE_; \
} \
} \
}
// Alloc
#define class_alloc_message(err_out,extra,sz) \
class_build_error_string(err_out,"could not allocate %s with size %d",extra,sz);
/* macro for allocating memory and returning error if it failed */
#define class_alloc(pointer, size, error_message_output) { \
pointer=malloc(size); \
if (pointer == NULL) { \
int size_int; \
size_int = size; \
class_alloc_message(error_message_output,#pointer, size_int); \
return _FAILURE_; \
} \
}
/* same inside parallel structure */
#define class_alloc_parallel(pointer, size, error_message_output) { \
pointer=NULL; \
if (abort == _FALSE_) { \
pointer=malloc(size); \
if (pointer == NULL) { \
int size_int; \
size_int = size; \
class_alloc_message(error_message_output,#pointer, size_int); \
abort=_TRUE_; \
} \
} \
}
/* macro for allocating memory, initializing it with zeros/ and returning error if it failed */
#define class_calloc(pointer, init,size, error_message_output) { \
pointer=calloc(init,size); \
if (pointer == NULL) { \
int size_int; \
size_int = size; \
class_alloc_message(error_message_output,#pointer, size_int); \
return _FAILURE_; \
} \
}
/* macro for re-allocating memory, returning error if it failed */
#define class_realloc(pointer, newname, size, error_message_output) { \
pointer=realloc(newname,size); \
if (pointer == NULL) { \
int size_int; \
size_int = size; \
class_alloc_message(error_message_output,#pointer, size_int); \
return _FAILURE_; \
} \
}
// Testing
#define class_test_message(err_out,extra,args...) { \
ErrorMsg Optional_arguments; \
class_protect_sprintf(Optional_arguments,args); \
class_build_error_string(err_out,"condition (%s) is true; %s",extra,Optional_arguments); \
}
/* macro for testing condition and returning error if condition is true;
args is a variable list of optional arguments, e.g.: args="x=%d",x
args cannot be empty, if there is nothing to pass use args="" */
#define class_test_except(condition, error_message_output,list_of_commands, args...) { \
if (condition) { \
class_test_message(error_message_output,#condition, args); \
list_of_commands; \
return _FAILURE_; \
} \
}
#define class_test(condition, error_message_output, args...) { \
if (condition) { \
class_test_message(error_message_output,#condition, args); \
return _FAILURE_; \
} \
}
#define class_test_parallel(condition, error_message_output, args...) { \
if (abort == _FALSE_) { \
if (condition) { \
class_test_message(error_message_output,#condition, args); \
abort=_TRUE_; \
} \
} \
}
/* macro for returning error message;
args is a variable list of optional arguments, e.g.: args="x=%d",x
args cannot be empty, if there is nothing to pass use args="" */
#define class_stop(error_message_output,args...) { \
ErrorMsg Optional_arguments; \
class_protect_sprintf(Optional_arguments,args); \
class_build_error_string(error_message_output,"error; %s",Optional_arguments); \
return _FAILURE_; \
}
// IO
/* macro for opening file and returning error if it failed */
#define class_open(pointer, filename, mode, error_output) { \
pointer=fopen(filename,mode); \
if (pointer == NULL) { \
class_build_error_string(error_output,"could not open %s with name %s and mode %s",#pointer,filename,#mode); \
return _FAILURE_; \
} \
}
/* macro for defining indices (usually one, sometimes a block) */
#define class_define_index(index, \
condition, \
running_index, \
number_of_indices) { \
if (condition) { \
index = running_index; \
running_index += number_of_indices; \
} \
}
/* macros for writing formatted output */
#define class_fprintf_double(file, \
output, \
condition){ \
if (condition == _TRUE_) \
fprintf(file,"%*.*e ",_COLUMNWIDTH_,_OUTPUTPRECISION_,output); \
}
#define class_fprintf_double_or_default(file, \
output, \
condition, \
defaultvalue){ \
if (condition == _TRUE_) \
fprintf(file,"%*.*e ",_COLUMNWIDTH_,_OUTPUTPRECISION_,output); \
else \
fprintf(file,"%*.*e ",_COLUMNWIDTH_,_OUTPUTPRECISION_,defaultvalue); \
}
#define class_fprintf_int(file, \
output, \
condition){ \
if (condition == _TRUE_) \
fprintf(file,"%*d%*s ", \
MAX(0,_COLUMNWIDTH_-_OUTPUTPRECISION_-5), \
output, _OUTPUTPRECISION_+5," "); \
}
#define class_fprintf_columntitle(file, \
title, \
condition, \
colnum){ \
if (condition == _TRUE_) \
fprintf(file,"%*s%2d:%-*s ", \
MAX(0,MIN(_COLUMNWIDTH_-_OUTPUTPRECISION_-6-3,_COLUMNWIDTH_-((int) strlen(title))-3)), \
"",colnum++,_OUTPUTPRECISION_+6,title); \
}
#define class_store_columntitle(titlestring, \
title, \
condition){ \
if (condition == _TRUE_){ \
strcat(titlestring,title); \
strcat(titlestring,_DELIMITER_); \
} \
}
//,_MAXTITLESTRINGLENGTH_-strlen(titlestring)-1);
#define class_store_double(storage, \
value, \
condition, \
dataindex){ \
if (condition == _TRUE_) \
storage[dataindex++] = value; \
}
#define class_store_double_or_default(storage, \
value, \
condition, \
dataindex, \
defaultvalue){ \
if (condition == _TRUE_) \
storage[dataindex++] = value; \
else \
storage[dataindex++] = defaultvalue; \
}
/** parameters related to the precision of the code and to the method of calculation */
/**
* list of evolver types for integrating perturbations over time
*/
enum evolver_type {
rk, /* Runge-Kutta integrator */
ndf15 /* stiff integrator */
};
/**
* List of ways in which matter power spectrum P(k) can be defined.
* The standard definition is the first one (delta_m_squared) but
* alternative definitions can be useful in some projects.
*
*/
enum pk_def {
delta_m_squared, /**< normal definition (delta_m includes all non-relativistic species at late times) */
delta_tot_squared, /**< delta_tot includes all species contributions to (delta rho), and only non-relativistic contributions to rho */
delta_bc_squared, /**< delta_bc includes contribution of baryons and cdm only to (delta rho) and to rho */
delta_tot_from_poisson_squared /**< use delta_tot inferred from gravitational potential through Poisson equation */
};
/**
* Different ways to present output files
*/
enum file_format {class_format,camb_format};
/**
* All precision parameters.
*
* Includes integrations
* steps, flags telling how the computation is to be performed, etc.
*/
struct precision
{
/** @name - parameters related to the background */
//@{
/**
* default initial value of scale factor in background integration, in
* units of scale factor today
*/
double a_ini_over_a_today_default;
/**
* default step d tau in background integration, in units of
* conformal Hubble time (\f$ d \tau \f$ = back_integration_stepsize / aH )
*/
double back_integration_stepsize;
/**
* parameter controlling precision of background integration
*/
double tol_background_integration;
/**
* parameter controlling how deep inside radiation domination must the
* initial time be chosen
*/
double tol_initial_Omega_r;
/**
* parameter controlling relative precision of ncdm mass for given
* ncdm current density
*/
double tol_M_ncdm;
/**
* parameter controlling relative precision of integrals over ncdm
* phase-space distribution during perturbation calculation: value
* to be applied in Newtonian gauge
*/
double tol_ncdm_newtonian;
/**
* parameter controlling relative precision of integrals over ncdm
* phase-space distribution during perturbation calculation: value
* to be applied in synchronous gauge
*/
double tol_ncdm_synchronous;
/**
* parameter controlling relative precision of integrals over ncdm
* phase-space distribution during perturbation calculation: value
* actually applied in chosen gauge
*/
double tol_ncdm;
/**
* parameter controlling relative precision of integrals over ncdm
* phase-space distribution during background evolution
*/
double tol_ncdm_bg;
/**
* parameter controlling how relativistic must non-cold relics be at
* initial time
*/
double tol_ncdm_initial_w;
/**
* parameter controlling the initial scalar field in background functions
*/
double safe_phi_scf;
//@}
/** @name - parameters related to the thermodynamics */
//@{
/* - for bbn */
/* @cond INCLUDE_WITH_DOXYGEN */
FileName sBBN_file;
/* @endcond */
/* - for recombination */
/* initial and final redshifts in recfast */
double recfast_z_initial; /**< initial redshift in recfast */
/* parameters governing precision of integration */
int recfast_Nz0; /**< number of integration steps */
double tol_thermo_integration; /**< precision of each integration step */
/* He fudge parameters from recfast 1.4 */
int recfast_Heswitch; /**< recfast 1.4 parameter */
double recfast_fudge_He; /**< recfast 1.4 parameter */
/* H fudge parameters from recfast 1.5 (Gaussian fits for extra H physics by Adam Moss) */
int recfast_Hswitch; /**< recfast 1.5 switching parameter */
double recfast_fudge_H; /**< H fudge factor when recfast_Hswitch set to false (v1.4 fudging) */
double recfast_delta_fudge_H; /**< correction to H fudge factor in v1.5 */
double recfast_AGauss1; /**< Amplitude of 1st Gaussian */
double recfast_AGauss2; /**< Amplitude of 2nd Gaussian */
double recfast_zGauss1; /**< ln(1+z) of 1st Gaussian */
double recfast_zGauss2; /**< ln(1+z) of 2nd Gaussian */
double recfast_wGauss1; /**< Width of 1st Gaussian */
double recfast_wGauss2; /**< Width of 2nd Gaussian */
/* triggers for switching approximations; ranges for doing it smoothly */
double recfast_z_He_1; /**< down to which redshift Helium fully ionized */
double recfast_delta_z_He_1; /**< z range over which transition is smoothed */
double recfast_z_He_2; /**< down to which redshift first Helium recombination not complete */
double recfast_delta_z_He_2; /**< z range over which transition is smoothed */
double recfast_z_He_3; /**< down to which redshift Helium singly ionized */
double recfast_delta_z_He_3; /**< z range over which transition is smoothed */
double recfast_x_He0_trigger; /**< value below which recfast uses the full equation for Helium */
double recfast_x_He0_trigger2; /**< a second threshold used in derivative routine */
double recfast_x_He0_trigger_delta; /**< x_He range over which transition is smoothed */
double recfast_x_H0_trigger; /**< value below which recfast uses the full equation for Hydrogen */
double recfast_x_H0_trigger2; /**< a second threshold used in derivative routine */
double recfast_x_H0_trigger_delta; /**< x_H range over which transition is smoothed */
double recfast_H_frac; /**< governs time at which full equation of evolution for Tmat is used */
/* @cond INCLUDE_WITH_DOXYGEN */
FileName hyrec_Alpha_inf_file;
FileName hyrec_R_inf_file;
FileName hyrec_two_photon_tables_file;
/* @endcond */
/* - for reionization */
double reionization_z_start_max; /**< maximum redshift at which reionization should start. If not, return an error. */
double reionization_sampling; /**< control stepsize in z during reionization */
double reionization_optical_depth_tol; /**< fractional error on optical_depth */
double reionization_start_factor; /**< parameter for CAMB-like parametrization */
/* - general */
int thermo_rate_smoothing_radius; /**< plays a minor (almost aesthetic) role in the definition of the variation rate of thermodynamical quantities */
//@}
/** @name - parameters related to the perturbation */
//@{
enum evolver_type evolver; /**< which type of evolver for integrating perturbations (Runge-Kutta? Stiff?...) */
double k_min_tau0; /**< number defining k_min for the computation of Cl's and P(k)'s (dimensionless): (k_min tau_0), usually chosen much smaller than one */
double k_max_tau0_over_l_max; /**< number defining k_max for the computation of Cl's (dimensionless): (k_max tau_0)/l_max, usually chosen around two */
double k_step_sub; /**< step in k space, in units of one period of acoustic oscillation at decoupling, for scales inside sound horizon at decoupling */
double k_step_super; /**< step in k space, in units of one period of acoustic oscillation at decoupling, for scales above sound horizon at decoupling */
double k_step_transition; /**< dimensionless number regulating the transition from 'sub' steps to 'super' steps. Decrease for more precision. */
double k_step_super_reduction; /**< the step k_step_super is reduced by this amount in the k-->0 limit (below scale of Hubble and/or curvature radius) */
double k_per_decade_for_pk; /**< if values needed between kmax inferred from k_oscillations and k_kmax_for_pk, this gives the number of k per decade outside the BAO region*/
double k_per_decade_for_bao; /**< if values needed between kmax inferred from k_oscillations and k_kmax_for_pk, this gives the number of k per decade inside the BAO region (for finer sampling)*/
double k_bao_center; /**< in ln(k) space, the central value of the BAO region where sampling is finer is defined as k_rec times this number (recommended: 3, i.e. finest sampling near 3rd BAO peak) */
double k_bao_width; /**< in ln(k) space, width of the BAO region where sampling is finer: this number gives roughly the number of BAO oscillations well resolved on both sides of the central value (recommended: 4, i.e. finest sampling from before first up to 3+4=7th peak) */
double start_small_k_at_tau_c_over_tau_h; /**< largest wavelengths start being sampled when universe is sufficiently opaque. This is quantified in terms of the ratio of thermo to hubble time scales, \f$ \tau_c/\tau_H \f$. Start when start_largek_at_tau_c_over_tau_h equals this ratio. Decrease this value to start integrating the wavenumbers earlier in time. */
double start_large_k_at_tau_h_over_tau_k; /**< largest wavelengths start being sampled when mode is sufficiently outside Hubble scale. This is quantified in terms of the ratio of hubble time scale to wavenumber time scale, \f$ \tau_h/\tau_k \f$ which is roughly equal to (k*tau). Start when this ratio equals start_large_k_at_tau_k_over_tau_h. Decrease this value to start integrating the wavenumbers earlier in time. */
/**
* when to switch off tight-coupling approximation: first condition:
* \f$ \tau_c/\tau_H \f$ > tight_coupling_trigger_tau_c_over_tau_h.
* Decrease this value to switch off earlier in time. If this
* number is larger than start_sources_at_tau_c_over_tau_h, the code
* returns an error, because the source computation requires
* tight-coupling to be switched off.
*/
double tight_coupling_trigger_tau_c_over_tau_h;
/**
* when to switch off tight-coupling approximation:
* second condition: \f$ \tau_c/\tau_k \equiv k \tau_c \f$ <
* tight_coupling_trigger_tau_c_over_tau_k.
* Decrease this value to switch off earlier in time.
*/
double tight_coupling_trigger_tau_c_over_tau_k;
double start_sources_at_tau_c_over_tau_h; /**< sources start being sampled when universe is sufficiently opaque. This is quantified in terms of the ratio of thermo to hubble time scales, \f$ \tau_c/\tau_H \f$. Start when start_sources_at_tau_c_over_tau_h equals this ratio. Decrease this value to start sampling the sources earlier in time. */
int tight_coupling_approximation; /**< method for tight coupling approximation */
int l_max_g; /**< number of momenta in Boltzmann hierarchy for photon temperature (scalar), at least 4 */
int l_max_pol_g; /**< number of momenta in Boltzmann hierarchy for photon polarization (scalar), at least 4 */
int l_max_dr; /**< number of momenta in Boltzmann hierarchy for decay radiation, at least 4 */
int l_max_ur; /**< number of momenta in Boltzmann hierarchy for relativistic neutrino/relics (scalar), at least 4 */
int l_max_ncdm; /**< number of momenta in Boltzmann hierarchy for relativistic neutrino/relics (scalar), at least 4 */
int l_max_g_ten; /**< number of momenta in Boltzmann hierarchy for photon temperature (tensor), at least 4 */
int l_max_pol_g_ten; /**< number of momenta in Boltzmann hierarchy for photon polarization (tensor), at least 4 */
double curvature_ini; /**< initial condition for curvature for adiabatic */
double entropy_ini; /**< initial condition for entropy perturbation for isocurvature */
double gw_ini; /**< initial condition for tensor metric perturbation h */
/**
* default step \f$ d \tau \f$ in perturbation integration, in units of the timescale involved in the equations (usually, the min of \f$ 1/k \f$, \f$ 1/aH \f$, \f$ 1/\dot{\kappa} \f$)
*/
double perturb_integration_stepsize;
/**
* default step \f$ d \tau \f$ for sampling the source function, in units of the timescale involved in the sources: \f$ (\dot{\kappa}- \ddot{\kappa}/\dot{\kappa})^{-1} \f$
*/
double perturb_sampling_stepsize;
/**
* control parameter for the precision of the perturbation integration
*/
double tol_perturb_integration;
/**
* precision with which the code should determine (by bisection) the
* times at which sources start being sampled, and at which
* approximations must be switched on/off (units of Mpc)
*/
double tol_tau_approx;
/**
* method for switching off photon perturbations
*/
int radiation_streaming_approximation;
/**
* when to switch off photon perturbations, ie when to switch
* on photon free-streaming approximation (keep density and thtau, set
* shear and higher momenta to zero):
* first condition: \f$ k \tau \f$ > radiation_streaming_trigger_tau_h_over_tau_k
*/
double radiation_streaming_trigger_tau_over_tau_k;
/**
* when to switch off photon perturbations, ie when to switch
* on photon free-streaming approximation (keep density and theta, set
* shear and higher momenta to zero):
* second condition:
*/
double radiation_streaming_trigger_tau_c_over_tau;
int ur_fluid_approximation; /**< method for ultra relativistic fluid approximation */
/**
* when to switch off ur (massless neutrinos / ultra-relativistic
* relics) fluid approximation
*/
double ur_fluid_trigger_tau_over_tau_k;
int ncdm_fluid_approximation; /**< method for non-cold dark matter fluid approximation */
/**
* when to switch off ncdm (massive neutrinos / non-cold
* relics) fluid approximation
*/
double ncdm_fluid_trigger_tau_over_tau_k;
/**
* whether CMB source functions can be approximated as zero when
* visibility function g(tau) is tiny
*/
double neglect_CMB_sources_below_visibility;
//@}
/** @name - parameters related to the primordial spectra */
//@{
double k_per_decade_primordial; /**< logarithmic sampling for primordial spectra (number of points per decade in k space) */
double primordial_inflation_ratio_min; /**< for each k, start following wavenumber when aH = k/primordial_inflation_ratio_min */
double primordial_inflation_ratio_max; /**< for each k, stop following wavenumber, at the latest, when aH = k/primordial_inflation_ratio_max */
int primordial_inflation_phi_ini_maxit; /**< maximum number of iteration when searching a suitable initial field value phi_ini (value reached when no long-enough slow-roll period before the pivot scale) */
double primordial_inflation_pt_stepsize; /**< controls the integration timestep for inflaton perturbations */
double primordial_inflation_bg_stepsize; /**< controls the integration timestep for inflaton background */
double primordial_inflation_tol_integration; /**< controls the precision of the ODE integration during inflation */
double primordial_inflation_attractor_precision_pivot; /**< targeted precision when searching attractor solution near phi_pivot */
double primordial_inflation_attractor_precision_initial; /**< targeted precision when searching attractor solution near phi_ini */
int primordial_inflation_attractor_maxit; /**< maximum number of iteration when searching attractor solution */
double primordial_inflation_tol_curvature; /**< for each k, stop following wavenumber, at the latest, when curvature perturbation R is stable up to to this tolerance */
double primordial_inflation_aH_ini_target; /**< control the step size in the search for a suitable initial field value */
double primordial_inflation_end_dphi; /**< first bracketing width, when trying to bracket the value phi_end at which inflation ends naturally */
double primordial_inflation_end_logstep; /**< logarithmic step for updating the bracketing width, when trying to bracket the value phi_end at which inflation ends naturally */
double primordial_inflation_small_epsilon; /**< value of slow-roll parameter epsilon used to define a field value phi_end close to the end of inflation (doesn't need to be exactly at the end): epsilon(phi_end)=small_epsilon (should be smaller than one) */
double primordial_inflation_small_epsilon_tol; /**< tolerance in the search for phi_end */
double primordial_inflation_extra_efolds; /**< a small number of efolds, irrelevant at the end, used in the search for the pivot scale (backward from the end of inflation) */
//@}
/** @name - parameters related to the transfer function */
//@{
int l_linstep; /**< factor for logarithmic spacing of values of l over which bessel and transfer functions are sampled */
double l_logstep; /**< maximum spacing of values of l over which Bessel and transfer functions are sampled (so, spacing becomes linear instead of logarithmic at some point) */
/* parameters relevant for bessel functions */
double hyper_x_min; /**< flat case: lower bound on the smallest value of x at which we sample \f$ \Phi_l^{\nu}(x)\f$ or \f$ j_l(x)\f$ */
double hyper_sampling_flat; /**< flat case: number of sampled points x per approximate wavelength \f$ 2\pi \f$*/
double hyper_sampling_curved_low_nu; /**< open/closed cases: number of sampled points x per approximate wavelength \f$ 2\pi/\nu\f$, when \f$ \nu \f$ smaller than hyper_nu_sampling_step */
double hyper_sampling_curved_high_nu; /**< open/closed cases: number of sampled points x per approximate wavelength \f$ 2\pi/\nu\f$, when \f$ \nu \f$ greater than hyper_nu_sampling_step */
double hyper_nu_sampling_step; /**< open/closed cases: value of nu at which sampling changes */
double hyper_phi_min_abs; /**< small value of Bessel function used in calculation of first point x (\f$ \Phi_l^{\nu}(x) \f$ equals hyper_phi_min_abs) */
double hyper_x_tol; /**< tolerance parameter used to determine first value of x */
double hyper_flat_approximation_nu; /**< value of nu below which the flat approximation is used to compute Bessel function */
/* parameters relevant for transfer function */
double q_linstep; /**< asymptotic linear sampling step in q
space, in units of \f$ 2\pi/r_a(\tau_rec) \f$
(comoving angular diameter distance to
recombination) */
double q_logstep_spline; /**< initial logarithmic sampling step in q
space, in units of \f$ 2\pi/r_a(\tau_{rec})\f$
(comoving angular diameter distance to
recombination) */
double q_logstep_open; /**< in open models, the value of
q_logstep_spline must be decreased
according to curvature. Increasing
this number will make the calculation
more accurate for large positive
Omega_k */
double q_logstep_trapzd; /**< initial logarithmic sampling step in q
space, in units of \f$ 2\pi/r_a(\tau_{rec}) \f$
(comoving angular diameter distance to
recombination), in the case of small
q's in the closed case, for which one
must used trapezoidal integration
instead of spline (the number of q's
for which this is the case decreases
with curvature and vanishes in the
flat limit) */
double q_numstep_transition; /**< number of steps for the transition
from q_logstep_trapzd steps to
q_logstep_spline steps (transition
must be smooth for spline) */
double transfer_neglect_delta_k_S_t0; /**< for temperature source function T0 of scalar mode, range of k values (in 1/Mpc) taken into account in transfer function: for l < (k-delta_k)*tau0, ie for k > (l/tau0 + delta_k), the transfer function is set to zero */
double transfer_neglect_delta_k_S_t1; /**< same for temperature source function T1 of scalar mode */
double transfer_neglect_delta_k_S_t2; /**< same for temperature source function T2 of scalar mode */
double transfer_neglect_delta_k_S_e; /**< same for polarization source function E of scalar mode */
double transfer_neglect_delta_k_V_t1; /**< same for temperature source function T1 of vector mode */
double transfer_neglect_delta_k_V_t2; /**< same for temperature source function T2 of vector mode */
double transfer_neglect_delta_k_V_e; /**< same for polarization source function E of vector mode */
double transfer_neglect_delta_k_V_b; /**< same for polarization source function B of vector mode */
double transfer_neglect_delta_k_T_t2; /**< same for temperature source function T2 of tensor mode */
double transfer_neglect_delta_k_T_e; /**< same for polarization source function E of tensor mode */
double transfer_neglect_delta_k_T_b; /**< same for polarization source function B of tensor mode */
double transfer_neglect_late_source; /**< value of l below which the CMB source functions can be neglected at late time, excepted when there is a Late ISW contribution */
/** when to use the Limber approximation for project gravitational potential cl's */
double l_switch_limber;
/** when to use the Limber approximation for local number count contributions to cl's (relative to central redshift of each bin) */
double l_switch_limber_for_nc_local_over_z;
/** when to use the Limber approximation for number count contributions to cl's integrated along the line-of-sight (relative to central redshift of each bin) */
double l_switch_limber_for_nc_los_over_z;
/** in sigma units, where to cut gaussian selection functions */
double selection_cut_at_sigma;
/** controls sampling of integral over time when selection functions vary quicker than Bessel functions. Increase for better sampling. */
double selection_sampling;
/** controls sampling of integral over time when selection functions vary slower than Bessel functions. Increase for better sampling */
double selection_sampling_bessel;
/** controls sampling of integral over time when selection functions vary slower than Bessel functions. This parameter is specific to number counts contributions to Cl integrated along the line of sight. Increase for better sampling */
double selection_sampling_bessel_los;
/** controls how smooth are the edge of top-hat window function (<<1 for very sharp, 0.1 for sharp) */
double selection_tophat_edge;
//@}
/** @name - parameters related to non-linear computations */
//@{
/** parameters relevant for HALOFIT computation */
double halofit_dz; /**< spacing in redshift space defining values of z
at which HALOFIT will be used. Intermediate
values will be obtained by
interpolation. Decrease for more precise
interpolations, at the expense of increasing
time spent in nonlinear_init() */
double halofit_min_k_nonlinear; /**< value of k in 1/Mpc above
which non-linear corrections will
be computed */
double halofit_sigma_precision; /**< a smaller value will lead to a
more precise halofit result at
the highest requested redshift,
at the expense of requiring a
larger k_max */
double halofit_min_k_max; /**< when halofit is used, k_max must be at
least equal to this value (otherwise
halofit could not find the scale of
non-linearity) */
double halofit_k_per_decade; /**< halofit needs to evalute integrals
(linear power spectrum times some
kernels). They are sampled using
this logarithmic step size. */
//@}
/** @name - parameters related to lensing */
//@{
int accurate_lensing; /**< switch between Gauss-Legendre quadrature integration and simple quadrature on a subdomain of angles */
int num_mu_minus_lmax; /**< difference between num_mu and l_max, increase for more precision */
int delta_l_max; /**< difference between l_max in unlensed and lensed spectra */
double tol_gauss_legendre; /**< tolerance with which quadrature points are found: must be very small for an accurate integration (if not entered manually, set automatically to match machine precision) */
//@}
/** @name - general precision parameters */
//@{
double smallest_allowed_variation; /**< machine-dependent, assigned automatically by the code */
//@}
/** @name - zone for writing error messages */
//@{
ErrorMsg error_message; /**< zone for writing error messages */
//@}
};
#endif
| {
"content_hash": "4ecb90e2a5a371dbd7f3c1143dd8b23e",
"timestamp": "",
"source": "github",
"line_count": 806,
"max_line_length": 423,
"avg_line_length": 54.869727047146405,
"alnum_prop": 0.5374788015828151,
"repo_name": "xyh-cosmo/ClassMC",
"id": "dcc9e1f065164f2377daf8f6684ce783d715ac04",
"size": "44225",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/class_DDE/include/common.h",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2181487"
},
{
"name": "C++",
"bytes": "306017"
},
{
"name": "Fortran",
"bytes": "303109"
},
{
"name": "Gnuplot",
"bytes": "6223"
},
{
"name": "MATLAB",
"bytes": "5559"
},
{
"name": "Makefile",
"bytes": "19014"
},
{
"name": "Python",
"bytes": "130639"
}
],
"symlink_target": ""
} |
#region LICENSE
// Copyright (C) 2015 by Sherif Elmetainy (Grendiser@Kazzak-EU)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Globalization;
using System.Threading;
using Microsoft.Framework.Configuration;
using Microsoft.Framework.DependencyInjection;
using WOWSharp.Core;
using WOWSharp.Warcraft;
namespace WOWSharp.Test
{
public static class TestHelper
{
private static IServiceProvider CreateServiceProvider()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-gb");
var builder = new ConfigurationBuilder().AddUserSecrets();
var configuration = builder.Build();
var services = new ServiceCollection();
services.AddWarcraft();
services.AddBattleNetCache();
services.Configure<BattleNetClientOptions>(options =>
{
options.ApiKey = configuration["Authentication:BattleNet:Key"];
options.ParseApiResponseInformation = true;
options.ThrowErrorOnMissingMembers = true;
});
return services.BuildServiceProvider();
}
public static WarcraftClient CreateDefaultWarcraftClient()
{
var serviceProvider = CreateServiceProvider();
var client = serviceProvider.GetRequiredService<WarcraftClient>();
return client;
}
}
}
| {
"content_hash": "1ce5c8751c2c5f5103983664e033dca8",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 80,
"avg_line_length": 39.87096774193548,
"alnum_prop": 0.7010517799352751,
"repo_name": "sherif-elmetainy/wowsharp",
"id": "9594542bd0f7846f0be5f6b2c36daaa7a6783f26",
"size": "2474",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/WOWSharp.Test/TestHelper.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "647768"
}
],
"symlink_target": ""
} |
package com.imsweb.geocoder;
import java.util.Map;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.QueryMap;
public interface GeocodingService {
/**
* Perform a geocoding call; had a lot of issues with parsing the XML version so this method returns the raw
* response body and we parse the TSV format
*
* @param searchParams A Map of query parameters.
* @return a GeocodingResult
*/
@GET("Geocode/V5/")
Call<ResponseBody> geocode(@QueryMap Map<String, String> searchParams);
@GET("CensusIntersectionWebServiceHttp_V03_01.aspx")
Call<ResponseBody> pointInPolygon(@QueryMap Map<String, String> searchParams);
}
| {
"content_hash": "f7e81980334f49cf1c56bb2b2d3198f7",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 112,
"avg_line_length": 27.653846153846153,
"alnum_prop": 0.7273991655076495,
"repo_name": "imsweb/naaccr-geocoder-client",
"id": "da46180a7863dac22ceb03ccc48e301ffd9bbb3c",
"size": "785",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/imsweb/geocoder/GeocodingService.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "105931"
}
],
"symlink_target": ""
} |
package com.github.jeanadrien.evrythng.scala.rest
import com.github.jeanadrien.evrythng.scala.json.{Product, Property}
import org.specs2.concurrent.ExecutionEnv
import org.specs2.specification.BeforeAll
import org.specs2.specification.core.SpecStructure
import spray.json.JsString
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.util.Random
/**
*
*/
class ProductPropertySpec(implicit val ee : ExecutionEnv) extends TestOperatorContext with BeforeAll {
var containingProduct : Product = null
override def beforeAll() : Unit = {
super.beforeAll()
Await.ready(
operator.products.create(Product(name = Some("TestPropertyProduct"))).exec.map {
containingProduct = _
}, 5 seconds
)
}
val propertyKey1 = Random.alphanumeric.take(8).mkString.toLowerCase
val propertyKey2 = Random.alphanumeric.take(8).mkString.toLowerCase
def randomProperty(key : String) = Property(key = Some(key), value = JsString(Random.nextString(10)))
var theProperties : List[Property] = List()
override def is : SpecStructure =
sequential ^
s2"""
The Product Properties API is able
to add different properties to a Product $addMutipleProperties
and see them $loadProductProperties
to add a new value to a property to the Product $updatePropertyKey2
and see it $loadProperty2History
to delete properties having a given key $deleteProperty2
and see the difference at the key level $loadProperty2History
and at the root context level $loadProductProperties
to delete all properties $deleteAllProperties
and see it's empty $loadProductProperties
"""
def addProductProperties(props : List[Property]) =
operator.product(containingProduct.id.get).properties.create(props).exec map { created =>
theProperties = theProperties ::: created
created.map(_.copy(timestamp = None))
} must containTheSameElementsAs(props).await
def loadProductProperties = operator.product(containingProduct.id.get).properties.list.exec map { page =>
page.items
} must containTheSameElementsAs(theProperties).await
def updateProperty(key : String, value : String) =
operator.product(containingProduct.id.get).properties(key).update(JsString(value)).exec map {
updated : List[Property] =>
theProperties = updated ::: theProperties
updated.map(_.copy(timestamp = None))
} must containTheSameElementsAs(Property(key = Some(key), value = JsString(value)) :: Nil).await
def loadPropertyHistory(key : String) = operator.product(containingProduct.id.get).properties(key).list.exec map {
page =>
page.items
} must containTheSameElementsAs(theProperties.filter(_.key == Some(key)).map(_.copy(key = None))).await
def deletePropertiesOfKey(key : String) = operator.product(containingProduct.id.get).properties(key).remove
.exec map { _ =>
theProperties = theProperties.filterNot(_.key == Some(key))
()
} must beEqualTo(()).await
def deleteAllProperties = operator.product(containingProduct.id.get).properties.remove.exec map { _ =>
theProperties = Nil
()
} must beEqualTo(()).await
def addMutipleProperties = addProductProperties(randomProperty(propertyKey1) :: randomProperty(propertyKey2) :: Nil)
def updatePropertyKey2 = updateProperty(propertyKey2, Random.nextString(10))
def loadProperty2History = loadPropertyHistory(propertyKey2)
def deleteProperty2 = deletePropertiesOfKey(propertyKey2)
}
| {
"content_hash": "7a64e390a07e9457c5ef208970a80eff",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 120,
"avg_line_length": 44.25,
"alnum_prop": 0.6357160402849423,
"repo_name": "jeanadrien/evrythng-scala-sdk",
"id": "6b36360a9237c3837c65bdd1b81568fc944620eb",
"size": "4071",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/scala/com/github/jeanadrien/evrythng/scala/rest/ProductPropertySpec.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "134784"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Slides;
using Aspose.Slides.Charts;
using Aspose.Slides.Examples.CSharp;
using Aspose.Slides.Export;
using DataTable = System.Data.DataTable;
namespace CSharp.Presentations.Conversion
{
// This example demonstrates creating 3D shape and appliing 3D effects to the text in it.
public class WordArt
{
public static void Run()
{
string resultPath = Path.Combine(RunExamples.OutPath, "WordArt_out.pptx");
using (Presentation pres = new Presentation())
{
// Create shape and text frame
IAutoShape shape = pres.Slides[0].Shapes.AddAutoShape(ShapeType.Rectangle, 314, 122, 400, 215.433f);
ITextFrame textFrame = shape.TextFrame;
Portion portion = (Portion)textFrame.Paragraphs[0].Portions[0];
portion.Text = "Aspose.Slides";
FontData fontData = new FontData("Arial Black");
portion.PortionFormat.LatinFont = fontData;
portion.PortionFormat.FontHeight = 36;
// Set format of the text
portion.PortionFormat.FillFormat.FillType = FillType.Pattern;
portion.PortionFormat.FillFormat.PatternFormat.ForeColor.Color = Color.DarkOrange;
portion.PortionFormat.FillFormat.PatternFormat.BackColor.Color = Color.White;
portion.PortionFormat.FillFormat.PatternFormat.PatternStyle = PatternStyle.SmallGrid;
portion.PortionFormat.LineFormat.FillFormat.FillType = FillType.Solid;
portion.PortionFormat.LineFormat.FillFormat.SolidFillColor.Color = Color.Black;
// Add a shadow effect for the text
portion.PortionFormat.EffectFormat.EnableOuterShadowEffect();
portion.PortionFormat.EffectFormat.OuterShadowEffect.ShadowColor.Color = Color.Black;
portion.PortionFormat.EffectFormat.OuterShadowEffect.ScaleHorizontal = 100;
portion.PortionFormat.EffectFormat.OuterShadowEffect.ScaleVertical = 65;
portion.PortionFormat.EffectFormat.OuterShadowEffect.BlurRadius = 4.73;
portion.PortionFormat.EffectFormat.OuterShadowEffect.Direction = 230;
portion.PortionFormat.EffectFormat.OuterShadowEffect.Distance = 2;
portion.PortionFormat.EffectFormat.OuterShadowEffect.SkewHorizontal = 30;
portion.PortionFormat.EffectFormat.OuterShadowEffect.SkewVertical = 0;
portion.PortionFormat.EffectFormat.OuterShadowEffect.ShadowColor.ColorTransform.Add(ColorTransformOperation.SetAlpha, 0.32f);
// Add reflection
portion.PortionFormat.EffectFormat.EnableReflectionEffect();
portion.PortionFormat.EffectFormat.ReflectionEffect.BlurRadius = 0.5;
portion.PortionFormat.EffectFormat.ReflectionEffect.Distance = 4.72;
portion.PortionFormat.EffectFormat.ReflectionEffect.StartPosAlpha = 0f;
portion.PortionFormat.EffectFormat.ReflectionEffect.EndPosAlpha = 60f;
portion.PortionFormat.EffectFormat.ReflectionEffect.Direction = 90;
portion.PortionFormat.EffectFormat.ReflectionEffect.ScaleHorizontal = 100;
portion.PortionFormat.EffectFormat.ReflectionEffect.ScaleVertical = -100;
portion.PortionFormat.EffectFormat.ReflectionEffect.StartReflectionOpacity = 60f;
portion.PortionFormat.EffectFormat.ReflectionEffect.EndReflectionOpacity = 0.9f;
portion.PortionFormat.EffectFormat.ReflectionEffect.RectangleAlign = RectangleAlignment.BottomLeft;
// Add glow effect
portion.PortionFormat.EffectFormat.EnableGlowEffect();
portion.PortionFormat.EffectFormat.GlowEffect.Color.R = 255;
portion.PortionFormat.EffectFormat.GlowEffect.Color.ColorTransform.Add(ColorTransformOperation.SetAlpha, 0.54f);
portion.PortionFormat.EffectFormat.GlowEffect.Radius = 7;
// Add transformation
textFrame.TextFrameFormat.Transform = TextShapeType.ArchUpPour;
// Add 3D effects to the shape
shape.ThreeDFormat.BevelBottom.BevelType = BevelPresetType.Circle;
shape.ThreeDFormat.BevelBottom.Height = 10.5;
shape.ThreeDFormat.BevelBottom.Width = 10.5;
shape.ThreeDFormat.BevelTop.BevelType = BevelPresetType.Circle;
shape.ThreeDFormat.BevelTop.Height = 12.5;
shape.ThreeDFormat.BevelTop.Width = 11;
shape.ThreeDFormat.ExtrusionColor.Color = Color.Orange;
shape.ThreeDFormat.ExtrusionHeight = 6;
shape.ThreeDFormat.ContourColor.Color = Color.DarkRed;
shape.ThreeDFormat.ContourWidth = 1.5;
shape.ThreeDFormat.Depth = 3;
shape.ThreeDFormat.Material = MaterialPresetType.Plastic;
shape.ThreeDFormat.LightRig.Direction = LightingDirection.Top;
shape.ThreeDFormat.LightRig.LightType = LightRigPresetType.Balanced;
shape.ThreeDFormat.LightRig.SetRotation(0, 0, 40);
shape.ThreeDFormat.Camera.CameraType = CameraPresetType.PerspectiveContrastingRightFacing;
// Add 3D effects to the text
textFrame = shape.TextFrame;
textFrame.TextFrameFormat.ThreeDFormat.BevelBottom.BevelType = BevelPresetType.Circle;
textFrame.TextFrameFormat.ThreeDFormat.BevelBottom.Height = 3.5;
textFrame.TextFrameFormat.ThreeDFormat.BevelBottom.Width = 3.5;
textFrame.TextFrameFormat.ThreeDFormat.BevelTop.BevelType = BevelPresetType.Circle;
textFrame.TextFrameFormat.ThreeDFormat.BevelTop.Height = 12.5;
textFrame.TextFrameFormat.ThreeDFormat.BevelTop.Width = 11;
textFrame.TextFrameFormat.ThreeDFormat.ExtrusionColor.Color = Color.Orange;
textFrame.TextFrameFormat.ThreeDFormat.ExtrusionHeight = 6;
textFrame.TextFrameFormat.ThreeDFormat.ContourColor.Color = Color.DarkRed;
textFrame.TextFrameFormat.ThreeDFormat.ContourWidth = 1.5;
textFrame.TextFrameFormat.ThreeDFormat.Depth = 3;
textFrame.TextFrameFormat.ThreeDFormat.Material = MaterialPresetType.Plastic;
textFrame.TextFrameFormat.ThreeDFormat.LightRig.Direction = LightingDirection.Top;
textFrame.TextFrameFormat.ThreeDFormat.LightRig.LightType = LightRigPresetType.Balanced;
textFrame.TextFrameFormat.ThreeDFormat.LightRig.SetRotation(0, 0, 40);
textFrame.TextFrameFormat.ThreeDFormat.Camera.CameraType = CameraPresetType.PerspectiveContrastingRightFacing;
pres.Save(resultPath, SaveFormat.Pptx);
}
}
}
}
| {
"content_hash": "af50076b149018b1e6507e3b74b3eec6",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 141,
"avg_line_length": 52.21167883211679,
"alnum_prop": 0.6777575842303929,
"repo_name": "asposeslides/Aspose_Slides_NET",
"id": "781e8b1e5e3c28b8fb6e457a5e309fd36d1724b4",
"size": "7155",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Examples/CSharp/Text/WordArt.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "322303"
}
],
"symlink_target": ""
} |
<?php
namespace Drupal\Core\Entity\Controller;
use Drupal\Core\Entity\EntityDescriptionInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Link;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
/**
* Provides the add-page and title callbacks for entities.
*
* It provides:
* - The add-page callback.
* - An add title callback for entity types.
* - An add title callback for entity types with bundles.
* - A view title callback.
* - An edit title callback.
* - A delete title callback.
*/
class EntityController implements ContainerInjectionInterface {
use StringTranslationTrait;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The entity type bundle info.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $entityTypeBundleInfo;
/**
* The entity repository.
*
* @var \Drupal\Core\Entity\EntityRepositoryInterface
*/
protected $entityRepository;
/**
* The renderer.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* Constructs a new EntityController.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
* The entity type bundle info.
* @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
* The entity repository.
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation.
* @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
* The url generator.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info, EntityRepositoryInterface $entity_repository, RendererInterface $renderer, TranslationInterface $string_translation, UrlGeneratorInterface $url_generator) {
$this->entityTypeManager = $entity_type_manager;
$this->entityTypeBundleInfo = $entity_type_bundle_info;
$this->entityRepository = $entity_repository;
$this->renderer = $renderer;
$this->stringTranslation = $string_translation;
$this->urlGenerator = $url_generator;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager'),
$container->get('entity_type.bundle.info'),
$container->get('entity.repository'),
$container->get('renderer'),
$container->get('string_translation'),
$container->get('url_generator')
);
}
/**
* Returns a redirect response object for the specified route.
*
* @param string $route_name
* The name of the route to which to redirect.
* @param array $route_parameters
* (optional) Parameters for the route.
* @param array $options
* (optional) An associative array of additional options.
* @param int $status
* (optional) The HTTP redirect status code for the redirect. The default is
* 302 Found.
*
* @return \Symfony\Component\HttpFoundation\RedirectResponse
* A redirect response object that may be returned by the controller.
*/
protected function redirect($route_name, array $route_parameters = [], array $options = [], $status = 302) {
$options['absolute'] = TRUE;
return new RedirectResponse(Url::fromRoute($route_name, $route_parameters, $options)->toString(), $status);
}
/**
* Displays add links for the available bundles.
*
* Redirects to the add form if there's only one bundle available.
*
* @param string $entity_type_id
* The entity type ID.
*
* @return \Symfony\Component\HttpFoundation\RedirectResponse|array
* If there's only one available bundle, a redirect response.
* Otherwise, a render array with the add links for each bundle.
*/
public function addPage($entity_type_id) {
$entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
$bundles = $this->entityTypeBundleInfo->getBundleInfo($entity_type_id);
$bundle_key = $entity_type->getKey('bundle');
$bundle_entity_type_id = $entity_type->getBundleEntityType();
$build = [
'#theme' => 'entity_add_list',
'#bundles' => [],
];
if ($bundle_entity_type_id) {
$bundle_argument = $bundle_entity_type_id;
$bundle_entity_type = $this->entityTypeManager->getDefinition($bundle_entity_type_id);
$bundle_entity_type_label = $bundle_entity_type->getSingularLabel();
$build['#cache']['tags'] = $bundle_entity_type->getListCacheTags();
// Build the message shown when there are no bundles.
$link_text = $this->t('Add a new @entity_type.', ['@entity_type' => $bundle_entity_type_label]);
$link_route_name = 'entity.' . $bundle_entity_type->id() . '.add_form';
$build['#add_bundle_message'] = $this->t('There is no @entity_type yet. @add_link', [
'@entity_type' => $bundle_entity_type_label,
'@add_link' => Link::createFromRoute($link_text, $link_route_name)->toString(),
]);
// Filter out the bundles the user doesn't have access to.
$access_control_handler = $this->entityTypeManager->getAccessControlHandler($entity_type_id);
foreach ($bundles as $bundle_name => $bundle_info) {
$access = $access_control_handler->createAccess($bundle_name, NULL, [], TRUE);
if (!$access->isAllowed()) {
unset($bundles[$bundle_name]);
}
$this->renderer->addCacheableDependency($build, $access);
}
// Add descriptions from the bundle entities.
$bundles = $this->loadBundleDescriptions($bundles, $bundle_entity_type);
}
else {
$bundle_argument = $bundle_key;
}
$form_route_name = 'entity.' . $entity_type_id . '.add_form';
// Redirect if there's only one bundle available.
if (count($bundles) == 1) {
$bundle_names = array_keys($bundles);
$bundle_name = reset($bundle_names);
return $this->redirect($form_route_name, [$bundle_argument => $bundle_name]);
}
// Prepare the #bundles array for the template.
foreach ($bundles as $bundle_name => $bundle_info) {
$build['#bundles'][$bundle_name] = [
'label' => $bundle_info['label'],
'description' => $bundle_info['description'] ?? '',
'add_link' => Link::createFromRoute($bundle_info['label'], $form_route_name, [$bundle_argument => $bundle_name]),
];
}
return $build;
}
/**
* Provides a generic add title callback for an entity type.
*
* @param string $entity_type_id
* The entity type ID.
*
* @return string
* The title for the entity add page.
*/
public function addTitle($entity_type_id) {
$entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
return $this->t('Add @entity-type', ['@entity-type' => $entity_type->getSingularLabel()]);
}
/**
* Provides a generic add title callback for entities with bundles.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match.
* @param string $entity_type_id
* The entity type ID.
* @param string $bundle_parameter
* The name of the route parameter that holds the bundle.
*
* @return string
* The title for the entity add page, if the bundle was found.
*/
public function addBundleTitle(RouteMatchInterface $route_match, $entity_type_id, $bundle_parameter) {
$bundles = $this->entityTypeBundleInfo->getBundleInfo($entity_type_id);
// If the entity has bundle entities, the parameter might have been upcasted
// so fetch the raw parameter.
$bundle = $route_match->getRawParameter($bundle_parameter);
if ((count($bundles) > 1) && isset($bundles[$bundle])) {
return $this->t('Add @bundle', ['@bundle' => $bundles[$bundle]['label']]);
}
// If the entity supports bundles generally, but only has a single bundle,
// the bundle is probably something like 'Default' so that it preferable to
// use the entity type label.
else {
return $this->addTitle($entity_type_id);
}
}
/**
* Provides a generic title callback for a single entity.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match.
* @param \Drupal\Core\Entity\EntityInterface $_entity
* (optional) An entity, passed in directly from the request attributes.
*
* @return string|null
* The title for the entity view page, if an entity was found.
*/
public function title(RouteMatchInterface $route_match, EntityInterface $_entity = NULL) {
if ($entity = $this->doGetEntity($route_match, $_entity)) {
return $entity->label();
}
}
/**
* Provides a generic edit title callback.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match.
* @param \Drupal\Core\Entity\EntityInterface $_entity
* (optional) An entity, passed in directly from the request attributes.
*
* @return string|null
* The title for the entity edit page, if an entity was found.
*/
public function editTitle(RouteMatchInterface $route_match, EntityInterface $_entity = NULL) {
if ($entity = $this->doGetEntity($route_match, $_entity)) {
return $this->t('Edit %label', ['%label' => $entity->label()]);
}
}
/**
* Provides a generic delete title callback.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match.
* @param \Drupal\Core\Entity\EntityInterface $_entity
* (optional) An entity, passed in directly from the request attributes, and
* set in \Drupal\Core\Entity\Enhancer\EntityRouteEnhancer.
*
* @return string
* The title for the entity delete page.
*/
public function deleteTitle(RouteMatchInterface $route_match, EntityInterface $_entity = NULL) {
if ($entity = $this->doGetEntity($route_match, $_entity)) {
return $this->t('Delete %label', ['%label' => $entity->label()]);
}
}
/**
* Determines the entity.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match.
* @param \Drupal\Core\Entity\EntityInterface $_entity
* (optional) The entity, set in
* \Drupal\Core\Entity\Enhancer\EntityRouteEnhancer.
*
* @return \Drupal\Core\Entity\EntityInterface|null
* The entity, if it is passed in directly or if the first parameter of the
* active route is an entity; otherwise, NULL.
*/
protected function doGetEntity(RouteMatchInterface $route_match, EntityInterface $_entity = NULL) {
if ($_entity) {
$entity = $_entity;
}
else {
// Let's look up in the route object for the name of upcasted values.
foreach ($route_match->getParameters() as $parameter) {
if ($parameter instanceof EntityInterface) {
$entity = $parameter;
break;
}
}
}
if (isset($entity)) {
return $this->entityRepository->getTranslationFromContext($entity);
}
}
/**
* Expands the bundle information with descriptions, if known.
*
* @param array $bundles
* An array of bundle information.
* @param \Drupal\Core\Entity\EntityTypeInterface $bundle_entity_type
* The bundle entity type definition.
*
* @return array
* The expanded array of bundle information.
*/
protected function loadBundleDescriptions(array $bundles, EntityTypeInterface $bundle_entity_type) {
if (!$bundle_entity_type->entityClassImplements(EntityDescriptionInterface::class)) {
return $bundles;
}
$bundle_names = array_keys($bundles);
$storage = $this->entityTypeManager->getStorage($bundle_entity_type->id());
/** @var \Drupal\Core\Entity\EntityDescriptionInterface[] $bundle_entities */
$bundle_entities = $storage->loadMultiple($bundle_names);
foreach ($bundles as $bundle_name => &$bundle_info) {
if (isset($bundle_entities[$bundle_name])) {
$bundle_info['description'] = $bundle_entities[$bundle_name]->getDescription();
}
}
return $bundles;
}
}
| {
"content_hash": "0eb0125f591055a209ef294e8901a861",
"timestamp": "",
"source": "github",
"line_count": 348,
"max_line_length": 291,
"avg_line_length": 37.08045977011494,
"alnum_prop": 0.6745195288282703,
"repo_name": "electric-eloquence/fepper-drupal",
"id": "4dd93475fb72850bb7e73f0a9265f8d1dc021f91",
"size": "12904",
"binary": false,
"copies": "9",
"ref": "refs/heads/dev",
"path": "backend/drupal/core/lib/Drupal/Core/Entity/Controller/EntityController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2300765"
},
{
"name": "HTML",
"bytes": "68444"
},
{
"name": "JavaScript",
"bytes": "2453602"
},
{
"name": "Mustache",
"bytes": "40698"
},
{
"name": "PHP",
"bytes": "41684915"
},
{
"name": "PowerShell",
"bytes": "755"
},
{
"name": "Shell",
"bytes": "72896"
},
{
"name": "Stylus",
"bytes": "32803"
},
{
"name": "Twig",
"bytes": "1820730"
},
{
"name": "VBScript",
"bytes": "466"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Test for http://bugs.webkit.org/show_bug.cgi?id=13680</title>
<script src="resources/repaint.js" type="text/javascript"></script>
<script>
function repaintTest()
{
document.getElementById('t').style.outline = '';
}
</script>
</head>
<body onload="runRepaintTest();">
<div style="width: 50px; text-align: center;">
<span id="t" style="outline: auto;"><div style="width: 30px; height:40px; background-color: silver; margin: auto"></div>
x
</span>
</div>
</body>
</html>
| {
"content_hash": "6b22ec7f97ffae76886e4400a2eeef3b",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 128,
"avg_line_length": 37.45,
"alnum_prop": 0.6048064085447263,
"repo_name": "lordmos/blink",
"id": "889898a600ac72796e0796e1817d9e0ac8bcf018",
"size": "749",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "LayoutTests/fast/repaint/continuation-after-outline.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "6433"
},
{
"name": "C",
"bytes": "753714"
},
{
"name": "C++",
"bytes": "40028043"
},
{
"name": "CSS",
"bytes": "539440"
},
{
"name": "F#",
"bytes": "8755"
},
{
"name": "Java",
"bytes": "18650"
},
{
"name": "JavaScript",
"bytes": "25700387"
},
{
"name": "Objective-C",
"bytes": "426711"
},
{
"name": "PHP",
"bytes": "141755"
},
{
"name": "Perl",
"bytes": "901523"
},
{
"name": "Python",
"bytes": "3748305"
},
{
"name": "Ruby",
"bytes": "141818"
},
{
"name": "Shell",
"bytes": "9635"
},
{
"name": "XSLT",
"bytes": "49328"
}
],
"symlink_target": ""
} |
* The `End()` functions defined on the `Segment`, `DatastoreSegment`, and
`ExternalSegment` types now receive the segment as a pointer, rather than as
a value. This prevents unexpected behaviour when a call to `End()` is
deferred before one or more fields are changed on the segment.
In practice, this is likely to only affect this pattern:
```go
defer newrelic.DatastoreSegment{
// ...
}.End()
```
Instead, you will now need to separate the literal from the deferred call:
```go
ds := newrelic.DatastoreSegment{
// ...
}
defer ds.End()
```
When creating custom and external segments, we recommend using
[`newrelic.StartSegment()`](https://godoc.org/github.com/newrelic/go-agent#StartSegment)
and
[`newrelic.StartExternalSegment()`](https://godoc.org/github.com/newrelic/go-agent#StartExternalSegment),
respectively.
* Added GoDoc badge to README. Thanks to @mrhwick for the contribution!
* `Config.UseTLS` configuration setting has been removed to increase security.
TLS will now always be used in communication with New Relic Servers.
## 1.11.0
* We've closed the Issues tab on GitHub. Please visit our
[support site](https://support.newrelic.com) to get timely help with any
problems you're having, or to report issues.
* Added support for Cross Application Tracing (CAT). Please refer to the
[upgrading section of the guide](GUIDE.md#upgrading-applications-to-support-cross-application-tracing)
for more detail on how to ensure you get the most out of the Go agent's new
CAT support.
* The agent now collects additional metadata when running within Amazon Web
Services, Google Cloud Platform, Microsoft Azure, and Pivotal Cloud Foundry.
This information is used to provide an enhanced experience when the agent is
deployed on those platforms.
## 1.10.0
* Added new `RecordCustomMetric` method to [Application](https://godoc.org/github.com/newrelic/go-agent#Application).
This functionality can be used to track averages or counters without using
custom events.
* [Custom Metric Documentation](https://docs.newrelic.com/docs/agents/manage-apm-agents/agent-data/collect-custom-metrics)
* Fixed import needed for logrus. The import Sirupsen/logrus had been renamed to sirupsen/logrus.
Thanks to @alfred-landrum for spotting this.
* Added [ErrorAttributer](https://godoc.org/github.com/newrelic/go-agent#ErrorAttributer),
an optional interface that can be implemented by errors provided to
`Transaction.NoticeError` to attach additional attributes. These attributes are
subject to attribute configuration.
* Added [Error](https://godoc.org/github.com/newrelic/go-agent#Error), a type
that allows direct control of error fields. Example use:
```go
txn.NoticeError(newrelic.Error{
// Message is returned by the Error() method.
Message: "error message: something went very wrong",
Class: "errors are aggregated by class",
Attributes: map[string]interface{}{
"important_number": 97232,
"relevant_string": "zap",
},
})
```
* Updated license to address scope of usage.
## 1.9.0
* Added support for [github.com/gin-gonic/gin](https://github.com/gin-gonic/gin)
in the new `nrgin` package.
* [Documentation](http://godoc.org/github.com/newrelic/go-agent/_integrations/nrgin/v1)
* [Example](examples/_gin/main.go)
## 1.8.0
* Fixed incorrect metric rule application when the metric rule is flagged to
terminate and matches but the name is unchanged.
* `Segment.End()`, `DatastoreSegment.End()`, and `ExternalSegment.End()` methods now return an
error which may be helpful in diagnosing situations where segment data is unexpectedly missing.
## 1.7.0
* Added support for [gorilla/mux](http://github.com/gorilla/mux) in the new `nrgorilla`
package.
* [Documentation](http://godoc.org/github.com/newrelic/go-agent/_integrations/nrgorilla/v1)
* [Example](examples/_gorilla/main.go)
## 1.6.0
* Added support for custom error messages and stack traces. Errors provided
to `Transaction.NoticeError` will now be checked to see if
they implement [ErrorClasser](https://godoc.org/github.com/newrelic/go-agent#ErrorClasser)
and/or [StackTracer](https://godoc.org/github.com/newrelic/go-agent#StackTracer).
Thanks to @fgrosse for this proposal.
* Added support for [pkg/errors](https://github.com/pkg/errors). Thanks to
@fgrosse for this work.
* [documentation](https://godoc.org/github.com/newrelic/go-agent/_integrations/nrpkgerrors)
* [example](https://github.com/newrelic/go-agent/blob/master/_integrations/nrpkgerrors/nrpkgerrors.go)
* Fixed tests for Go 1.8.
## 1.5.0
* Added support for Windows. Thanks to @ianomad and @lvxv for the contributions.
* The number of heap objects allocated is recorded in the
`Memory/Heap/AllocatedObjects` metric. This will soon be displayed on the "Go
runtime" page.
* If the [DatastoreSegment](https://godoc.org/github.com/newrelic/go-agent#DatastoreSegment)
fields `Host` and `PortPathOrID` are not provided, they will no longer appear
as `"unknown"` in transaction traces and slow query traces.
* Stack traces will now be nicely aligned in the APM UI.
## 1.4.0
* Added support for slow query traces. Slow datastore segments will now
generate slow query traces viewable on the datastore tab. These traces include
a stack trace and help you to debug slow datastore activity.
[Slow Query Documentation](https://docs.newrelic.com/docs/apm/applications-menu/monitoring/viewing-slow-query-details)
* Added new
[DatastoreSegment](https://godoc.org/github.com/newrelic/go-agent#DatastoreSegment)
fields `ParameterizedQuery`, `QueryParameters`, `Host`, `PortPathOrID`, and
`DatabaseName`. These fields will be shown in transaction traces and in slow
query traces.
## 1.3.0
* Breaking Change: Added a timeout parameter to the `Application.Shutdown` method.
## 1.2.0
* Added support for instrumenting short-lived processes:
* The new `Application.Shutdown` method allows applications to report
data to New Relic without waiting a full minute.
* The new `Application.WaitForConnection` method allows your process to
defer instrumentation until the application is connected and ready to
gather data.
* Full documentation here: [application.go](application.go)
* Example short-lived process: [examples/short-lived-process/main.go](examples/short-lived-process/main.go)
* Error metrics are no longer created when `ErrorCollector.Enabled = false`.
* Added support for [github.com/mgutz/logxi](github.com/mgutz/logxi). See
[_integrations/nrlogxi/v1/nrlogxi.go](_integrations/nrlogxi/v1/nrlogxi.go).
* Fixed bug where Transaction Trace thresholds based upon Apdex were not being
applied to background transactions.
## 1.1.0
* Added support for Transaction Traces.
* Stack trace filenames have been shortened: Any thing preceding the first
`/src/` is now removed.
## 1.0.0
* Removed `BetaToken` from the `Config` structure.
* Breaking Datastore Change: `datastore` package contents moved to top level
`newrelic` package. `datastore.MySQL` has become `newrelic.DatastoreMySQL`.
* Breaking Attributes Change: `attributes` package contents moved to top
level `newrelic` package. `attributes.ResponseCode` has become
`newrelic.AttributeResponseCode`. Some attribute name constants have been
shortened.
* Added "runtime.NumCPU" to the environment tab. Thanks sergeylanzman for the
contribution.
* Prefixed the environment tab values "Compiler", "GOARCH", "GOOS", and
"Version" with "runtime.".
## 0.8.0
* Breaking Segments API Changes: The segments API has been rewritten with the
goal of being easier to use and to avoid nil Transaction checks. See:
* [segments.go](segments.go)
* [examples/server/main.go](examples/server/main.go)
* [GUIDE.md#segments](GUIDE.md#segments)
* Updated LICENSE.txt with contribution information.
## 0.7.1
* Fixed a bug causing the `Config` to fail to serialize into JSON when the
`Transport` field was populated.
## 0.7.0
* Eliminated `api`, `version`, and `log` packages. `Version`, `Config`,
`Application`, and `Transaction` now live in the top level `newrelic` package.
If you imported the `attributes` or `datastore` packages then you will need
to remove `api` from the import path.
* Breaking Logging Changes
Logging is no longer controlled though a single global. Instead, logging is
configured on a per-application basis with the new `Config.Logger` field. The
logger is an interface described in [log.go](log.go). See
[GUIDE.md#logging](GUIDE.md#logging).
## 0.6.1
* No longer create "GC/System/Pauses" metric if no GC pauses happened.
## 0.6.0
* Introduced beta token to support our beta program.
* Rename `Config.Development` to `Config.Enabled` (and change boolean
direction).
* Fixed a bug where exclusive time could be incorrect if segments were not
ended.
* Fix unit tests broken in 1.6.
* In `Config.Enabled = false` mode, the license must be the proper length or empty.
* Added runtime statistics for CPU/memory usage, garbage collection, and number
of goroutines.
## 0.5.0
* Added segment timing methods to `Transaction`. These methods must only be
used in a single goroutine.
* The license length check will not be performed in `Development` mode.
* Rename `SetLogFile` to `SetFile` to reduce redundancy.
* Added `DebugEnabled` logging guard to reduce overhead.
* `Transaction` now implements an `Ignore` method which will prevent
any of the transaction's data from being recorded.
* `Transaction` now implements a subset of the interfaces
`http.CloseNotifier`, `http.Flusher`, `http.Hijacker`, and `io.ReaderFrom`
to match the behavior of its wrapped `http.ResponseWriter`.
* Changed project name from `go-sdk` to `go-agent`.
## 0.4.0
* Queue time support added: if the inbound request contains an
`"X-Request-Start"` or `"X-Queue-Start"` header with a unix timestamp, the
agent will report queue time metrics. Queue time will appear on the
application overview chart. The timestamp may fractional seconds,
milliseconds, or microseconds: the agent will deduce the correct units.
| {
"content_hash": "f1907a5886f20c0e4f41f5173fb22b41",
"timestamp": "",
"source": "github",
"line_count": 271,
"max_line_length": 124,
"avg_line_length": 37.48339483394834,
"alnum_prop": 0.7492616656822209,
"repo_name": "evepraisal/go-evepraisal",
"id": "df43531dee1e0b6601a6e38b78a4268e0982cee6",
"size": "10182",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/github.com/newrelic/go-agent/CHANGELOG.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1263"
},
{
"name": "Dockerfile",
"bytes": "633"
},
{
"name": "Go",
"bytes": "245014"
},
{
"name": "HTML",
"bytes": "54451"
},
{
"name": "Makefile",
"bytes": "2137"
},
{
"name": "Shell",
"bytes": "1323"
}
],
"symlink_target": ""
} |
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->text('body');
$table->integer('topic_id')->unsigned()->index();
$table->integer('user_id')->unsigned()->index();
$table->timestamps();
$table->foreign('topic_id')->references('id')->on('topics')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
| {
"content_hash": "28c9daecf5100d05f538d41e9a7ba61c",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 93,
"avg_line_length": 25.135135135135137,
"alnum_prop": 0.553763440860215,
"repo_name": "lester-hashtagdigital/dgo",
"id": "daa6db48b21e3acf7c71d4361dabeb42d145ecd9",
"size": "930",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "database/migrations/2017_10_18_012600_create_posts_table.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2736"
},
{
"name": "PHP",
"bytes": "91896"
},
{
"name": "Vue",
"bytes": "563"
}
],
"symlink_target": ""
} |
<?php
namespace Family\Bundle\TreeBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Family\Bundle\TreeBundle\Entity\Family as Family;
use Family\Bundle\TreeBundle\Model\FamilySettings;
class FamilySettingsType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', "text", array(
'label' => "Titre de la famille"
))
->add('privacy', 'choice', array(
'choices' => FamilySettings::$privacyList,
'required' => true,
'data' => $options['privacyIndex'],
'label' => "Confidentialité"
))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Family\Bundle\TreeBundle\Entity\Family',
'cascade_validation' => true, //needed to validate embeed forms.
'validation_groups' => array('registration'), //use of validation groups.
'csrf_protection' => true,
'csrf_field_name' => '_token',
// a unique key to help generate the secret token
'intention' => 'family_settings',
'privacyIndex' => null,
));
}
/**
* @return string
*/
public function getName()
{
return 'family_settings';
}
}
| {
"content_hash": "084bd56bcc916cd1ea5479b11d3aa0a9",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 85,
"avg_line_length": 30.57894736842105,
"alnum_prop": 0.5754446356855996,
"repo_name": "Artemis-Haven/family-tree",
"id": "e4dbaae760f2dbc7fde5e89aa18b5fe342776f59",
"size": "1744",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Family/Bundle/TreeBundle/Form/FamilySettingsType.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8828"
},
{
"name": "JavaScript",
"bytes": "447980"
},
{
"name": "PHP",
"bytes": "148059"
}
],
"symlink_target": ""
} |
angular.module('codexApp')
.service('PrefsService', [ '$rootScope', '$http', function($rootScope, $http) {
var views = ["All Notes", "All Files", "Notebooks", "Notebook"];
var current_view = "All Notes"
this.getCurrentView = function() {
return current_view;
}
this.setCurrentView = function(view) {
current_view = view;
}
}])
| {
"content_hash": "f68001ec32c4a63d4f19c261c4ac9555",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 80,
"avg_line_length": 25.071428571428573,
"alnum_prop": 0.6410256410256411,
"repo_name": "jamesperet/codex",
"id": "b7d3b61a77711578971a2800a68fcb64c33962f0",
"size": "351",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/scripts/services/prefs-service.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "39400"
},
{
"name": "HTML",
"bytes": "13608"
},
{
"name": "JavaScript",
"bytes": "67655"
}
],
"symlink_target": ""
} |
package org.apache.flink.runtime.executiongraph.failover.flip1;
import org.apache.flink.runtime.execution.ExecutionState;
import org.apache.flink.runtime.io.network.partition.ResultPartitionID;
import org.apache.flink.runtime.io.network.partition.ResultPartitionType;
import org.apache.flink.runtime.io.network.partition.consumer.PartitionConnectionException;
import org.apache.flink.runtime.jobgraph.IntermediateResultPartitionID;
import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID;
import org.apache.flink.runtime.scheduler.strategy.SchedulingExecutionVertex;
import org.apache.flink.runtime.scheduler.strategy.SchedulingResultPartition;
import org.apache.flink.runtime.scheduler.strategy.TestingSchedulingExecutionVertex;
import org.apache.flink.runtime.scheduler.strategy.TestingSchedulingResultPartition;
import org.apache.flink.runtime.scheduler.strategy.TestingSchedulingTopology;
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId;
import static org.assertj.core.api.Assertions.assertThat;
/** Tests the failure handling logic of the {@link RestartPipelinedRegionFailoverStrategy}. */
class RestartPipelinedRegionFailoverStrategyTest {
/**
* Tests for scenes that a task fails for its own error, in which case the region containing the
* failed task and its consumer regions should be restarted.
*
* <pre>
* (v1) -+-> (v4)
* x
* (v2) -+-> (v5)
*
* (v3) -+-> (v6)
*
* ^
* |
* (blocking)
* </pre>
*
* Each vertex is in an individual region.
*/
@Test
void testRegionFailoverForRegionInternalErrors() {
final TestingSchedulingTopology topology = new TestingSchedulingTopology();
TestingSchedulingExecutionVertex v1 = topology.newExecutionVertex(ExecutionState.FINISHED);
TestingSchedulingExecutionVertex v2 = topology.newExecutionVertex(ExecutionState.FINISHED);
TestingSchedulingExecutionVertex v3 = topology.newExecutionVertex(ExecutionState.FINISHED);
TestingSchedulingExecutionVertex v4 = topology.newExecutionVertex(ExecutionState.FINISHED);
TestingSchedulingExecutionVertex v5 = topology.newExecutionVertex(ExecutionState.SCHEDULED);
TestingSchedulingExecutionVertex v6 = topology.newExecutionVertex(ExecutionState.RUNNING);
topology.connect(v1, v4, ResultPartitionType.BLOCKING);
topology.connect(v1, v5, ResultPartitionType.BLOCKING);
topology.connect(v2, v4, ResultPartitionType.BLOCKING);
topology.connect(v2, v5, ResultPartitionType.BLOCKING);
topology.connect(v3, v6, ResultPartitionType.BLOCKING);
RestartPipelinedRegionFailoverStrategy strategy =
new RestartPipelinedRegionFailoverStrategy(topology);
verifyThatFailedExecution(strategy, v1).restarts(v1, v4, v5);
verifyThatFailedExecution(strategy, v2).restarts(v2, v4, v5);
verifyThatFailedExecution(strategy, v3).restarts(v3, v6);
verifyThatFailedExecution(strategy, v4).restarts(v4);
verifyThatFailedExecution(strategy, v5).restarts(v5);
verifyThatFailedExecution(strategy, v6).restarts(v6);
}
/**
* Tests for scenes that a task fails for data consumption error, in which case the region
* containing the failed task, the region containing the unavailable result partition and all
* their consumer regions should be restarted.
*
* <pre>
* (v1) -+-> (v4)
* x
* (v2) -+-> (v5)
*
* (v3) -+-> (v6)
*
* ^
* |
* (blocking)
* </pre>
*
* Each vertex is in an individual region.
*/
@Test
void testRegionFailoverForDataConsumptionErrors() throws Exception {
TestingSchedulingTopology topology = new TestingSchedulingTopology();
TestingSchedulingExecutionVertex v1 = topology.newExecutionVertex(ExecutionState.FINISHED);
TestingSchedulingExecutionVertex v2 = topology.newExecutionVertex(ExecutionState.FINISHED);
TestingSchedulingExecutionVertex v3 = topology.newExecutionVertex(ExecutionState.FINISHED);
TestingSchedulingExecutionVertex v4 = topology.newExecutionVertex(ExecutionState.RUNNING);
TestingSchedulingExecutionVertex v5 = topology.newExecutionVertex(ExecutionState.RUNNING);
TestingSchedulingExecutionVertex v6 = topology.newExecutionVertex(ExecutionState.RUNNING);
topology.connect(v1, v4, ResultPartitionType.BLOCKING);
topology.connect(v1, v5, ResultPartitionType.BLOCKING);
topology.connect(v2, v4, ResultPartitionType.BLOCKING);
topology.connect(v2, v5, ResultPartitionType.BLOCKING);
topology.connect(v3, v6, ResultPartitionType.BLOCKING);
RestartPipelinedRegionFailoverStrategy strategy =
new RestartPipelinedRegionFailoverStrategy(topology);
Iterator<TestingSchedulingResultPartition> v4InputEdgeIterator =
v4.getConsumedResults().iterator();
TestingSchedulingResultPartition v1out = v4InputEdgeIterator.next();
verifyThatFailedExecution(strategy, v4)
.partitionConnectionCause(v1out)
.restarts(v1, v4, v5);
TestingSchedulingResultPartition v2out = v4InputEdgeIterator.next();
verifyThatFailedExecution(strategy, v4)
.partitionConnectionCause(v2out)
.restarts(v2, v4, v5);
Iterator<TestingSchedulingResultPartition> v5InputEdgeIterator =
v5.getConsumedResults().iterator();
v1out = v5InputEdgeIterator.next();
verifyThatFailedExecution(strategy, v5)
.partitionConnectionCause(v1out)
.restarts(v1, v4, v5);
v2out = v5InputEdgeIterator.next();
verifyThatFailedExecution(strategy, v5)
.partitionConnectionCause(v2out)
.restarts(v2, v4, v5);
TestingSchedulingResultPartition v3out = v6.getConsumedResults().iterator().next();
verifyThatFailedExecution(strategy, v6).partitionConnectionCause(v3out).restarts(v3, v6);
}
/**
* Tests to verify region failover results regarding different input result partition
* availability combinations.
*
* <pre>
* (v1) --rp1--\
* (v3)
* (v2) --rp2--/
*
* ^
* |
* (blocking)
* </pre>
*
* Each vertex is in an individual region. rp1, rp2 are result partitions.
*/
@Test
void testRegionFailoverForVariousResultPartitionAvailabilityCombinations() throws Exception {
TestingSchedulingTopology topology = new TestingSchedulingTopology();
TestingSchedulingExecutionVertex v1 = topology.newExecutionVertex(ExecutionState.FINISHED);
TestingSchedulingExecutionVertex v2 = topology.newExecutionVertex(ExecutionState.FINISHED);
TestingSchedulingExecutionVertex v3 = topology.newExecutionVertex(ExecutionState.RUNNING);
topology.connect(v1, v3, ResultPartitionType.BLOCKING);
topology.connect(v2, v3, ResultPartitionType.BLOCKING);
TestResultPartitionAvailabilityChecker availabilityChecker =
new TestResultPartitionAvailabilityChecker();
RestartPipelinedRegionFailoverStrategy strategy =
new RestartPipelinedRegionFailoverStrategy(topology, availabilityChecker);
IntermediateResultPartitionID rp1ID = v1.getProducedResults().iterator().next().getId();
IntermediateResultPartitionID rp2ID = v2.getProducedResults().iterator().next().getId();
// -------------------------------------------------
// Combination1: (rp1 == available, rp2 == available)
// -------------------------------------------------
availabilityChecker.failedPartitions.clear();
verifyThatFailedExecution(strategy, v1).restarts(v1, v3);
verifyThatFailedExecution(strategy, v2).restarts(v2, v3);
verifyThatFailedExecution(strategy, v3).restarts(v3);
// -------------------------------------------------
// Combination2: (rp1 == unavailable, rp2 == available)
// -------------------------------------------------
availabilityChecker.failedPartitions.clear();
availabilityChecker.markResultPartitionFailed(rp1ID);
verifyThatFailedExecution(strategy, v1).restarts(v1, v3);
verifyThatFailedExecution(strategy, v2).restarts(v1, v2, v3);
verifyThatFailedExecution(strategy, v3).restarts(v1, v3);
// -------------------------------------------------
// Combination3: (rp1 == available, rp2 == unavailable)
// -------------------------------------------------
availabilityChecker.failedPartitions.clear();
availabilityChecker.markResultPartitionFailed(rp2ID);
verifyThatFailedExecution(strategy, v1).restarts(v1, v2, v3);
verifyThatFailedExecution(strategy, v2).restarts(v2, v3);
verifyThatFailedExecution(strategy, v3).restarts(v2, v3);
// -------------------------------------------------
// Combination4: (rp1 == unavailable, rp == unavailable)
// -------------------------------------------------
availabilityChecker.failedPartitions.clear();
availabilityChecker.markResultPartitionFailed(rp1ID);
availabilityChecker.markResultPartitionFailed(rp2ID);
verifyThatFailedExecution(strategy, v1).restarts(v1, v2, v3);
verifyThatFailedExecution(strategy, v2).restarts(v1, v2, v3);
verifyThatFailedExecution(strategy, v3).restarts(v1, v2, v3);
}
/**
* Tests region failover scenes for topology with multiple vertices.
*
* <pre>
* (v1) ---> (v2) --|--> (v3) ---> (v4) --|--> (v5) ---> (v6)
*
* ^ ^ ^ ^ ^
* | | | | |
* (pipelined) (blocking) (pipelined) (blocking) (pipelined)
* </pre>
*
* Component 1: 1,2; component 2: 3,4; component 3: 5,6
*/
@Test
void testRegionFailoverForMultipleVerticesRegions() throws Exception {
TestingSchedulingTopology topology = new TestingSchedulingTopology();
TestingSchedulingExecutionVertex v1 = topology.newExecutionVertex(ExecutionState.FINISHED);
TestingSchedulingExecutionVertex v2 = topology.newExecutionVertex(ExecutionState.FINISHED);
TestingSchedulingExecutionVertex v3 = topology.newExecutionVertex(ExecutionState.RUNNING);
TestingSchedulingExecutionVertex v4 = topology.newExecutionVertex(ExecutionState.RUNNING);
TestingSchedulingExecutionVertex v5 = topology.newExecutionVertex(ExecutionState.FAILED);
TestingSchedulingExecutionVertex v6 = topology.newExecutionVertex(ExecutionState.CANCELED);
topology.connect(v1, v2, ResultPartitionType.PIPELINED);
topology.connect(v2, v3, ResultPartitionType.BLOCKING);
topology.connect(v3, v4, ResultPartitionType.PIPELINED);
topology.connect(v4, v5, ResultPartitionType.BLOCKING);
topology.connect(v5, v6, ResultPartitionType.PIPELINED);
RestartPipelinedRegionFailoverStrategy strategy =
new RestartPipelinedRegionFailoverStrategy(topology);
verifyThatFailedExecution(strategy, v3).restarts(v3, v4, v5, v6);
TestingSchedulingResultPartition v2out = v3.getConsumedResults().iterator().next();
verifyThatFailedExecution(strategy, v3)
.partitionConnectionCause(v2out)
.restarts(v1, v2, v3, v4, v5, v6);
}
/**
* Tests region failover does not restart vertexes which are already in initial CREATED state.
*
* <pre>
* (v1) --|--> (v2)
*
* ^
* |
* (blocking)
* </pre>
*
* Component 1: 1; component 2: 2
*/
@Test
void testRegionFailoverDoesNotRestartCreatedExecutions() {
TestingSchedulingTopology topology = new TestingSchedulingTopology();
TestingSchedulingExecutionVertex v1 = topology.newExecutionVertex(ExecutionState.CREATED);
TestingSchedulingExecutionVertex v2 = topology.newExecutionVertex(ExecutionState.CREATED);
topology.connect(v1, v2, ResultPartitionType.BLOCKING);
FailoverStrategy strategy = new RestartPipelinedRegionFailoverStrategy(topology);
verifyThatFailedExecution(strategy, v2).restarts();
TestingSchedulingResultPartition v1out = v2.getConsumedResults().iterator().next();
verifyThatFailedExecution(strategy, v2).partitionConnectionCause(v1out).restarts();
}
/**
* Tests approximate local recovery downstream failover .
*
* <pre>
* (v1) -----> (v2) -----> (v4)
* | ^
* |--------> (v3) --------|
* </pre>
*/
@Test
void testRegionFailoverForPipelinedApproximate() {
final TestingSchedulingTopology topology = new TestingSchedulingTopology();
TestingSchedulingExecutionVertex v1 = topology.newExecutionVertex(ExecutionState.RUNNING);
TestingSchedulingExecutionVertex v2 = topology.newExecutionVertex(ExecutionState.RUNNING);
TestingSchedulingExecutionVertex v3 = topology.newExecutionVertex(ExecutionState.RUNNING);
TestingSchedulingExecutionVertex v4 = topology.newExecutionVertex(ExecutionState.RUNNING);
topology.connect(v1, v2, ResultPartitionType.PIPELINED_APPROXIMATE);
topology.connect(v1, v3, ResultPartitionType.PIPELINED_APPROXIMATE);
topology.connect(v2, v4, ResultPartitionType.PIPELINED_APPROXIMATE);
topology.connect(v3, v4, ResultPartitionType.PIPELINED_APPROXIMATE);
RestartPipelinedRegionFailoverStrategy strategy =
new RestartPipelinedRegionFailoverStrategy(topology);
verifyThatFailedExecution(strategy, v1).restarts(v1, v2, v3, v4);
verifyThatFailedExecution(strategy, v2).restarts(v2, v4);
verifyThatFailedExecution(strategy, v3).restarts(v3, v4);
verifyThatFailedExecution(strategy, v4).restarts(v4);
}
/**
* Tests to verify region failover results of PIPELINED/BLOCKING/HYBRID_FULL/HYBRID_SELECTIVE
* type.
*
* <pre>
*
* (v1) -**- \
* \
* (v2) -//- (v5) -**-(v6)
* / /
* (v3) -##- / /
* /
* (v4)----/
*
*
* ----: pipelined edge
* -**-: hybrid_full edge
* -##-: hybrid_selective edge
* -//-: blocking edge
*
* </pre>
*
* Except that v4 and v5 belong to the same region, each vertex is in an individual region.
*/
@Test
void testRegionFailoverForHybridEdge() {
final TestingSchedulingTopology topology = new TestingSchedulingTopology();
TestingSchedulingExecutionVertex v1 = topology.newExecutionVertex(ExecutionState.FINISHED);
TestingSchedulingExecutionVertex v2 = topology.newExecutionVertex(ExecutionState.FINISHED);
TestingSchedulingExecutionVertex v3 = topology.newExecutionVertex(ExecutionState.FINISHED);
TestingSchedulingExecutionVertex v4 = topology.newExecutionVertex(ExecutionState.RUNNING);
TestingSchedulingExecutionVertex v5 = topology.newExecutionVertex(ExecutionState.FINISHED);
TestingSchedulingExecutionVertex v6 = topology.newExecutionVertex(ExecutionState.RUNNING);
topology.connect(v1, v5, ResultPartitionType.HYBRID_FULL);
topology.connect(v2, v5, ResultPartitionType.BLOCKING);
topology.connect(v3, v5, ResultPartitionType.HYBRID_SELECTIVE);
topology.connect(v4, v5, ResultPartitionType.PIPELINED);
topology.connect(v5, v6, ResultPartitionType.HYBRID_FULL);
RestartPipelinedRegionFailoverStrategy strategy =
new RestartPipelinedRegionFailoverStrategy(topology);
verifyThatFailedExecution(strategy, v5).restarts(v3, v4, v5, v6);
verifyThatFailedExecution(strategy, v6).restarts(v6);
}
private static VerificationContext verifyThatFailedExecution(
FailoverStrategy strategy, SchedulingExecutionVertex executionVertex) {
return new VerificationContext(strategy, executionVertex);
}
private static class VerificationContext {
private final FailoverStrategy strategy;
private final SchedulingExecutionVertex executionVertex;
private Throwable cause = new Exception("Test failure");
private VerificationContext(
FailoverStrategy strategy, SchedulingExecutionVertex executionVertex) {
this.strategy = strategy;
this.executionVertex = executionVertex;
}
private VerificationContext partitionConnectionCause(
SchedulingResultPartition failedProducer) {
return cause(
new PartitionConnectionException(
new ResultPartitionID(
failedProducer.getId(),
createExecutionAttemptId(
failedProducer.getProducer().getId(), 0)),
new Exception("Test failure")));
}
private VerificationContext cause(Throwable cause) {
this.cause = cause;
return this;
}
private void restarts(SchedulingExecutionVertex... expectedResult) {
Set<ExecutionVertexID> tasksNeedingRestart =
strategy.getTasksNeedingRestart(executionVertex.getId(), cause);
assertThat(tasksNeedingRestart)
.containsExactlyInAnyOrderElementsOf(
Stream.of(expectedResult)
.map(SchedulingExecutionVertex::getId)
.collect(Collectors.toList()));
}
}
private static class TestResultPartitionAvailabilityChecker
implements ResultPartitionAvailabilityChecker {
private final HashSet<IntermediateResultPartitionID> failedPartitions;
public TestResultPartitionAvailabilityChecker() {
this.failedPartitions = new HashSet<>();
}
@Override
public boolean isAvailable(IntermediateResultPartitionID resultPartitionID) {
return !failedPartitions.contains(resultPartitionID);
}
public void markResultPartitionFailed(IntermediateResultPartitionID resultPartitionID) {
failedPartitions.add(resultPartitionID);
}
public void removeResultPartitionFromFailedState(
IntermediateResultPartitionID resultPartitionID) {
failedPartitions.remove(resultPartitionID);
}
}
}
| {
"content_hash": "c70f823fb6890e05cd9242e8573ec56b",
"timestamp": "",
"source": "github",
"line_count": 434,
"max_line_length": 103,
"avg_line_length": 44.23041474654378,
"alnum_prop": 0.6600854344655136,
"repo_name": "lincoln-lil/flink",
"id": "da3014b13598587372e252e57975e2471027689b",
"size": "20001",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "flink-runtime/src/test/java/org/apache/flink/runtime/executiongraph/failover/flip1/RestartPipelinedRegionFailoverStrategyTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "20596"
},
{
"name": "Batchfile",
"bytes": "1863"
},
{
"name": "C",
"bytes": "847"
},
{
"name": "Cython",
"bytes": "137975"
},
{
"name": "Dockerfile",
"bytes": "5579"
},
{
"name": "FreeMarker",
"bytes": "101034"
},
{
"name": "GAP",
"bytes": "139876"
},
{
"name": "HTML",
"bytes": "188268"
},
{
"name": "HiveQL",
"bytes": "215858"
},
{
"name": "Java",
"bytes": "96014255"
},
{
"name": "JavaScript",
"bytes": "7038"
},
{
"name": "Less",
"bytes": "84321"
},
{
"name": "Makefile",
"bytes": "5134"
},
{
"name": "Python",
"bytes": "3100138"
},
{
"name": "Scala",
"bytes": "10647786"
},
{
"name": "Shell",
"bytes": "513298"
},
{
"name": "TypeScript",
"bytes": "381893"
},
{
"name": "q",
"bytes": "16945"
}
],
"symlink_target": ""
} |
import sys
from avatar2.targets import Target, TargetStates
from avatar2.protocols.jlink import JLinkProtocol
from avatar2.watchmen import watch
if sys.version_info < (3, 0):
from Queue import PriorityQueue
else:
from queue import PriorityQueue
class JLinkTarget(Target):
def __init__(self, avatar, serial=None, device="ARM7", interface="swd", **kwargs):
"""
Create a JLink target instance
:param avatar: The avatar instance
:param serial: The JLink's serial number
:param device: The Device string to use (e.g., ARM7, see JlinkExe for the list)
:param kwargs:
"""
super(JLinkTarget, self).__init__(avatar, **kwargs)
self.avatar = avatar
self.serial = serial
self.interface = interface
self.device = device
@watch("TargetInit")
def init(self):
jlink = JLinkProtocol(serial=self.serial, device=self.device, interface=self.interface, avatar=self.avatar, origin=self)
self.protocols.set_all(jlink)
if jlink.jlink.halted():
self.state = TargetStates.STOPPED
else:
self.state = TargetStates.RUNNING
#self.wait()
def reset(self, halt=True):
self.protocols.execution.reset(halt=halt)
if halt:
self.state = TargetStates.STOPPED
else:
self.state = TargetStates.RUNNING
| {
"content_hash": "f07d04f9c37bbf167ef7e75fc99208fe",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 128,
"avg_line_length": 33.26190476190476,
"alnum_prop": 0.6413743736578382,
"repo_name": "avatartwo/avatar2",
"id": "d41f390b1724f8f6ed12ebf0a6016b4666769daa",
"size": "1397",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "avatar2/targets/jlink_target.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2369"
},
{
"name": "Python",
"bytes": "368478"
},
{
"name": "Shell",
"bytes": "2439"
}
],
"symlink_target": ""
} |
// PkgCmdID.cs
// MUST match PkgCmdID.h
namespace WakaTime
{
internal static class PkgCmdIdList
{
public const uint UpdateWakaTimeSettings = 0x100;
};
} | {
"content_hash": "d436bd8b5f39458f82fbb4bfdad44cd4",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 57,
"avg_line_length": 17.4,
"alnum_prop": 0.6781609195402298,
"repo_name": "gandarez/visualstudio-wakatime",
"id": "7843c0e6572c67eacbc2543a9b31e58314bf60e6",
"size": "176",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WakaTime/PkgCmdID.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "14545"
}
],
"symlink_target": ""
} |
package org.jclouds.openstack.nova.ec2.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.ec2.compute.strategy.ReviseParsedImage;
import org.jclouds.openstack.nova.v2_0.domain.Image;
import com.google.common.base.Function;
@Singleton
public class NovaReviseParsedImage implements ReviseParsedImage {
private final Function<Image, OperatingSystem> imageToOs;
@Inject
public NovaReviseParsedImage(Function<Image, OperatingSystem> imageToOs) {
this.imageToOs = checkNotNull(imageToOs, "imageToOs");
}
@Override
public void reviseParsedImage(org.jclouds.ec2.domain.Image from, ImageBuilder builder, OsFamily family,
OperatingSystem.Builder osBuilder) {
Image image = Image.builder().id(from.getId()).name(from.getName()).build();
OperatingSystem os = imageToOs.apply(image);
osBuilder.description(os.getDescription());
osBuilder.family(os.getFamily());
osBuilder.name(os.getName());
osBuilder.is64Bit(os.is64Bit());
osBuilder.version(os.getVersion());
// arch is accurate already
}
}
| {
"content_hash": "9d2725de8860025d16c677e70325105b",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 106,
"avg_line_length": 33.87179487179487,
"alnum_prop": 0.7562452687358062,
"repo_name": "yanzhijun/jclouds-aliyun",
"id": "94446e3e8d0072a81b31765c14737a236b1206b9",
"size": "2122",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "apis/openstack-nova-ec2/src/main/java/org/jclouds/openstack/nova/ec2/strategy/NovaReviseParsedImage.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "12999"
},
{
"name": "CSS",
"bytes": "10692"
},
{
"name": "Clojure",
"bytes": "99051"
},
{
"name": "Emacs Lisp",
"bytes": "852"
},
{
"name": "HTML",
"bytes": "381689"
},
{
"name": "Java",
"bytes": "19478047"
},
{
"name": "JavaScript",
"bytes": "7110"
},
{
"name": "Shell",
"bytes": "121121"
}
],
"symlink_target": ""
} |
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatButtonModule } from '@angular/material/button';
import { NgProgressModule } from 'ngx-progressbar';
// import { NgProgressModule } from '../../../../ngx-progressbar/src/public-api';
import { CustomComponent } from './custom/custom.component';
@NgModule({
imports: [
CommonModule,
RouterModule.forChild([
{path: '', component: CustomComponent}
]),
MatProgressBarModule,
MatProgressSpinnerModule,
MatCardModule,
NgProgressModule,
MatButtonModule,
MatIconModule
],
declarations: [CustomComponent]
})
export class CustomModule {
}
| {
"content_hash": "1d0c32ef37f06a33ef8a42358b0b520b",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 81,
"avg_line_length": 32.96666666666667,
"alnum_prop": 0.7209302325581395,
"repo_name": "MurhafSousli/ngx-progressbar",
"id": "0126802eac93dab5c6a1369b34d6d410c6624892",
"size": "989",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "projects/ngx-progressbar-demo/src/app/custom/custom.module.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "13152"
},
{
"name": "JavaScript",
"bytes": "5425"
},
{
"name": "SCSS",
"bytes": "8739"
},
{
"name": "TypeScript",
"bytes": "43087"
}
],
"symlink_target": ""
} |
python setup.py test
# check
check-manifest -u -v
# Build packages
python setup.py sdist
python setup.py bdist_wheel # Not universal
# Deploy with gpg
twine upload dist/* -r pypitest --sign --skip-existing
twine upload dist/* --sign
# Deploy legacy version
# Upload to test PyPi
# python setup.py sdist upload -r https://testpypi.python.org/pypi
# Upload to prod PyPi
# python setup.py sdist upload
| {
"content_hash": "c78cbc8b127beaa33b7979e8b7d6f0e7",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 66,
"avg_line_length": 22.444444444444443,
"alnum_prop": 0.745049504950495,
"repo_name": "michaelboulton/debinterface",
"id": "c53d9ad46557c3771a843160382b06ab3312f43e",
"size": "566",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "deploy.sh",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "54392"
},
{
"name": "Shell",
"bytes": "566"
}
],
"symlink_target": ""
} |
package blackbox
import (
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"time"
"github.com/concourse/blackbox/syslog"
"github.com/tedsuo/ifrit/grouper"
)
const POLL_INTERVAL = 5 * time.Second
type fileWatcher struct {
logger *log.Logger
sourceDir string
dynamicGroupClient grouper.DynamicClient
drainerFactory syslog.DrainerFactory
}
func NewFileWatcher(
logger *log.Logger,
sourceDir string,
dynamicGroupClient grouper.DynamicClient,
drainerFactory syslog.DrainerFactory,
) *fileWatcher {
return &fileWatcher{
logger: logger,
sourceDir: sourceDir,
dynamicGroupClient: dynamicGroupClient,
drainerFactory: drainerFactory,
}
}
func (f *fileWatcher) Watch() {
for {
logDirs, err := ioutil.ReadDir(f.sourceDir)
if err != nil {
f.logger.Fatalf("could not list directories in source dir: %s\n", err)
}
for _, logDir := range logDirs {
tag := logDir.Name()
tagDirPath := filepath.Join(f.sourceDir, tag)
fileInfo, err := os.Stat(tagDirPath)
if err != nil {
f.logger.Fatalf("failed to determine if path is directory: %s\n", err)
}
if !fileInfo.IsDir() {
continue
}
f.findLogsToWatch(tag, tagDirPath, fileInfo)
}
time.Sleep(POLL_INTERVAL)
}
}
func (f *fileWatcher) findLogsToWatch(tag string, filePath string, file os.FileInfo) {
if !file.IsDir() {
if strings.HasSuffix(file.Name(), ".log") {
if _, found := f.dynamicGroupClient.Get(filePath); !found {
f.dynamicGroupClient.Inserter() <- f.memberForFile(filePath)
}
}
return
}
dirContents, err := ioutil.ReadDir(filePath)
if err != nil {
f.logger.Printf("skipping log dir '%s' (could not list files): %s\n", tag, err)
return
}
for _, content := range dirContents {
currentFilePath := filepath.Join(filePath, content.Name())
f.findLogsToWatch(tag, currentFilePath, content)
}
}
func (f *fileWatcher) memberForFile(logfilePath string) grouper.Member {
drainer, err := f.drainerFactory.NewDrainer()
if err != nil {
f.logger.Fatalf("could not drain to syslog: %s\n", err)
}
logfileDir := filepath.Dir(logfilePath)
tag, err := filepath.Rel(f.sourceDir, logfileDir)
if err != nil {
f.logger.Fatalf("could not compute tag from file path %s: %s\n", logfilePath, err)
}
tailer := &Tailer{
Path: logfilePath,
Tag: tag,
Drainer: drainer,
}
return grouper.Member{tailer.Path, tailer}
}
| {
"content_hash": "25f330379bdadcb3aaeae4de191a846e",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 86,
"avg_line_length": 21.87272727272727,
"alnum_prop": 0.6828761429758936,
"repo_name": "concourse/blackbox",
"id": "2e78b3ef98e75c0cb318d15b5bebc3da1290def2",
"size": "2406",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "file_watcher.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "27020"
},
{
"name": "Shell",
"bytes": "319"
}
],
"symlink_target": ""
} |
#include "stdlib.h"
#include "stdio.h"
#include "chipmunk/chipmunk_private.h"
static inline cpSpatialIndexClass *Klass(void);
typedef struct Node Node;
typedef struct Pair Pair;
struct cpBBTree {
cpSpatialIndex spatialIndex;
cpBBTreeVelocityFunc velocityFunc;
cpHashSet *leaves;
Node *root;
Node *pooledNodes;
Pair *pooledPairs;
cpArray *allocatedBuffers;
cpTimestamp stamp;
};
struct Node {
void *obj;
cpBB bb;
Node *parent;
union {
// Internal nodes
struct { Node *a, *b; } children;
// Leaves
struct {
cpTimestamp stamp;
Pair *pairs;
} leaf;
} node;
};
// Can't use anonymous unions and still get good x-compiler compatability
#define A node.children.a
#define B node.children.b
#define STAMP node.leaf.stamp
#define PAIRS node.leaf.pairs
typedef struct Thread {
Pair *prev;
Node *leaf;
Pair *next;
} Thread;
struct Pair {
Thread a, b;
cpCollisionID id;
};
//MARK: Misc Functions
static inline cpBB
GetBB(cpBBTree *tree, void *obj)
{
cpBB bb = tree->spatialIndex.bbfunc(obj);
cpBBTreeVelocityFunc velocityFunc = tree->velocityFunc;
if(velocityFunc){
cpFloat coef = 0.1f;
cpFloat x = (bb.r - bb.l)*coef;
cpFloat y = (bb.t - bb.b)*coef;
cpVect v = cpvmult(velocityFunc(obj), 0.1f);
return cpBBNew(bb.l + cpfmin(-x, v.x), bb.b + cpfmin(-y, v.y), bb.r + cpfmax(x, v.x), bb.t + cpfmax(y, v.y));
} else {
return bb;
}
}
static inline cpBBTree *
GetTree(cpSpatialIndex *index)
{
return (index && index->klass == Klass() ? (cpBBTree *)index : NULL);
}
static inline Node *
GetRootIfTree(cpSpatialIndex *index){
return (index && index->klass == Klass() ? ((cpBBTree *)index)->root : NULL);
}
static inline cpBBTree *
GetMasterTree(cpBBTree *tree)
{
cpBBTree *dynamicTree = GetTree(tree->spatialIndex.dynamicIndex);
return (dynamicTree ? dynamicTree : tree);
}
static inline void
IncrementStamp(cpBBTree *tree)
{
cpBBTree *dynamicTree = GetTree(tree->spatialIndex.dynamicIndex);
if(dynamicTree){
dynamicTree->stamp++;
} else {
tree->stamp++;
}
}
//MARK: Pair/Thread Functions
static void
PairRecycle(cpBBTree *tree, Pair *pair)
{
// Share the pool of the master tree.
// TODO: would be lovely to move the pairs stuff into an external data structure.
tree = GetMasterTree(tree);
pair->a.next = tree->pooledPairs;
tree->pooledPairs = pair;
}
static Pair *
PairFromPool(cpBBTree *tree)
{
// Share the pool of the master tree.
// TODO: would be lovely to move the pairs stuff into an external data structure.
tree = GetMasterTree(tree);
Pair *pair = tree->pooledPairs;
if(pair){
tree->pooledPairs = pair->a.next;
return pair;
} else {
// Pool is exhausted, make more
int count = CP_BUFFER_BYTES/sizeof(Pair);
cpAssertHard(count, "Internal Error: Buffer size is too small.");
Pair *buffer = (Pair *)cpcalloc(1, CP_BUFFER_BYTES);
cpArrayPush(tree->allocatedBuffers, buffer);
// push all but the first one, return the first instead
for(int i=1; i<count; i++) PairRecycle(tree, buffer + i);
return buffer;
}
}
static inline void
ThreadUnlink(Thread thread)
{
Pair *next = thread.next;
Pair *prev = thread.prev;
if(next){
if(next->a.leaf == thread.leaf) next->a.prev = prev; else next->b.prev = prev;
}
if(prev){
if(prev->a.leaf == thread.leaf) prev->a.next = next; else prev->b.next = next;
} else {
thread.leaf->PAIRS = next;
}
}
static void
PairsClear(Node *leaf, cpBBTree *tree)
{
Pair *pair = leaf->PAIRS;
leaf->PAIRS = NULL;
while(pair){
if(pair->a.leaf == leaf){
Pair *next = pair->a.next;
ThreadUnlink(pair->b);
PairRecycle(tree, pair);
pair = next;
} else {
Pair *next = pair->b.next;
ThreadUnlink(pair->a);
PairRecycle(tree, pair);
pair = next;
}
}
}
static void
PairInsert(Node *a, Node *b, cpBBTree *tree)
{
Pair *nextA = a->PAIRS, *nextB = b->PAIRS;
Pair *pair = PairFromPool(tree);
Pair temp = {{NULL, a, nextA},{NULL, b, nextB}, 0};
a->PAIRS = b->PAIRS = pair;
*pair = temp;
if(nextA){
if(nextA->a.leaf == a) nextA->a.prev = pair; else nextA->b.prev = pair;
}
if(nextB){
if(nextB->a.leaf == b) nextB->a.prev = pair; else nextB->b.prev = pair;
}
}
//MARK: Node Functions
static void
NodeRecycle(cpBBTree *tree, Node *node)
{
node->parent = tree->pooledNodes;
tree->pooledNodes = node;
}
static Node *
NodeFromPool(cpBBTree *tree)
{
Node *node = tree->pooledNodes;
if(node){
tree->pooledNodes = node->parent;
return node;
} else {
// Pool is exhausted, make more
int count = CP_BUFFER_BYTES/sizeof(Node);
cpAssertHard(count, "Internal Error: Buffer size is too small.");
Node *buffer = (Node *)cpcalloc(1, CP_BUFFER_BYTES);
cpArrayPush(tree->allocatedBuffers, buffer);
// push all but the first one, return the first instead
for(int i=1; i<count; i++) NodeRecycle(tree, buffer + i);
return buffer;
}
}
static inline void
NodeSetA(Node *node, Node *value)
{
node->A = value;
value->parent = node;
}
static inline void
NodeSetB(Node *node, Node *value)
{
node->B = value;
value->parent = node;
}
static Node *
NodeNew(cpBBTree *tree, Node *a, Node *b)
{
Node *node = NodeFromPool(tree);
node->obj = NULL;
node->bb = cpBBMerge(a->bb, b->bb);
node->parent = NULL;
NodeSetA(node, a);
NodeSetB(node, b);
return node;
}
static inline cpBool
NodeIsLeaf(Node *node)
{
return (node->obj != NULL);
}
static inline Node *
NodeOther(Node *node, Node *child)
{
return (node->A == child ? node->B : node->A);
}
static inline void
NodeReplaceChild(Node *parent, Node *child, Node *value, cpBBTree *tree)
{
cpAssertSoft(!NodeIsLeaf(parent), "Internal Error: Cannot replace child of a leaf.");
cpAssertSoft(child == parent->A || child == parent->B, "Internal Error: Node is not a child of parent.");
if(parent->A == child){
NodeRecycle(tree, parent->A);
NodeSetA(parent, value);
} else {
NodeRecycle(tree, parent->B);
NodeSetB(parent, value);
}
for(Node *node=parent; node; node = node->parent){
node->bb = cpBBMerge(node->A->bb, node->B->bb);
}
}
//MARK: Subtree Functions
static inline cpFloat
cpBBProximity(cpBB a, cpBB b)
{
return cpfabs(a.l + a.r - b.l - b.r) + cpfabs(a.b + a.t - b.b - b.t);
}
static Node *
SubtreeInsert(Node *subtree, Node *leaf, cpBBTree *tree)
{
if(subtree == NULL){
return leaf;
} else if(NodeIsLeaf(subtree)){
return NodeNew(tree, leaf, subtree);
} else {
cpFloat cost_a = cpBBArea(subtree->B->bb) + cpBBMergedArea(subtree->A->bb, leaf->bb);
cpFloat cost_b = cpBBArea(subtree->A->bb) + cpBBMergedArea(subtree->B->bb, leaf->bb);
if(cost_a == cost_b){
cost_a = cpBBProximity(subtree->A->bb, leaf->bb);
cost_b = cpBBProximity(subtree->B->bb, leaf->bb);
}
if(cost_b < cost_a){
NodeSetB(subtree, SubtreeInsert(subtree->B, leaf, tree));
} else {
NodeSetA(subtree, SubtreeInsert(subtree->A, leaf, tree));
}
subtree->bb = cpBBMerge(subtree->bb, leaf->bb);
return subtree;
}
}
static void
SubtreeQuery(Node *subtree, void *obj, cpBB bb, cpSpatialIndexQueryFunc func, void *data)
{
if(cpBBIntersects(subtree->bb, bb)){
if(NodeIsLeaf(subtree)){
func(obj, subtree->obj, 0, data);
} else {
SubtreeQuery(subtree->A, obj, bb, func, data);
SubtreeQuery(subtree->B, obj, bb, func, data);
}
}
}
static cpFloat
SubtreeSegmentQuery(Node *subtree, void *obj, cpVect a, cpVect b, cpFloat t_exit, cpSpatialIndexSegmentQueryFunc func, void *data)
{
if(NodeIsLeaf(subtree)){
return func(obj, subtree->obj, data);
} else {
cpFloat t_a = cpBBSegmentQuery(subtree->A->bb, a, b);
cpFloat t_b = cpBBSegmentQuery(subtree->B->bb, a, b);
if(t_a < t_b){
if(t_a < t_exit) t_exit = cpfmin(t_exit, SubtreeSegmentQuery(subtree->A, obj, a, b, t_exit, func, data));
if(t_b < t_exit) t_exit = cpfmin(t_exit, SubtreeSegmentQuery(subtree->B, obj, a, b, t_exit, func, data));
} else {
if(t_b < t_exit) t_exit = cpfmin(t_exit, SubtreeSegmentQuery(subtree->B, obj, a, b, t_exit, func, data));
if(t_a < t_exit) t_exit = cpfmin(t_exit, SubtreeSegmentQuery(subtree->A, obj, a, b, t_exit, func, data));
}
return t_exit;
}
}
static void
SubtreeRecycle(cpBBTree *tree, Node *node)
{
if(!NodeIsLeaf(node)){
SubtreeRecycle(tree, node->A);
SubtreeRecycle(tree, node->B);
NodeRecycle(tree, node);
}
}
static inline Node *
SubtreeRemove(Node *subtree, Node *leaf, cpBBTree *tree)
{
if(leaf == subtree){
return NULL;
} else {
Node *parent = leaf->parent;
if(parent == subtree){
Node *other = NodeOther(subtree, leaf);
other->parent = subtree->parent;
NodeRecycle(tree, subtree);
return other;
} else {
NodeReplaceChild(parent->parent, parent, NodeOther(parent, leaf), tree);
return subtree;
}
}
}
//MARK: Marking Functions
typedef struct MarkContext {
cpBBTree *tree;
Node *staticRoot;
cpSpatialIndexQueryFunc func;
void *data;
} MarkContext;
static void
MarkLeafQuery(Node *subtree, Node *leaf, cpBool left, MarkContext *context)
{
if(cpBBIntersects(leaf->bb, subtree->bb)){
if(NodeIsLeaf(subtree)){
if(left){
PairInsert(leaf, subtree, context->tree);
} else {
if(subtree->STAMP < leaf->STAMP) PairInsert(subtree, leaf, context->tree);
context->func(leaf->obj, subtree->obj, 0, context->data);
}
} else {
MarkLeafQuery(subtree->A, leaf, left, context);
MarkLeafQuery(subtree->B, leaf, left, context);
}
}
}
static void
MarkLeaf(Node *leaf, MarkContext *context)
{
cpBBTree *tree = context->tree;
if(leaf->STAMP == GetMasterTree(tree)->stamp){
Node *staticRoot = context->staticRoot;
if(staticRoot) MarkLeafQuery(staticRoot, leaf, cpFalse, context);
for(Node *node = leaf; node->parent; node = node->parent){
if(node == node->parent->A){
MarkLeafQuery(node->parent->B, leaf, cpTrue, context);
} else {
MarkLeafQuery(node->parent->A, leaf, cpFalse, context);
}
}
} else {
Pair *pair = leaf->PAIRS;
while(pair){
if(leaf == pair->b.leaf){
pair->id = context->func(pair->a.leaf->obj, leaf->obj, pair->id, context->data);
pair = pair->b.next;
} else {
pair = pair->a.next;
}
}
}
}
static void
MarkSubtree(Node *subtree, MarkContext *context)
{
if(NodeIsLeaf(subtree)){
MarkLeaf(subtree, context);
} else {
MarkSubtree(subtree->A, context);
MarkSubtree(subtree->B, context); // TODO: Force TCO here?
}
}
//MARK: Leaf Functions
static Node *
LeafNew(cpBBTree *tree, void *obj, cpBB bb)
{
Node *node = NodeFromPool(tree);
node->obj = obj;
node->bb = GetBB(tree, obj);
node->parent = NULL;
node->STAMP = 0;
node->PAIRS = NULL;
return node;
}
static cpBool
LeafUpdate(Node *leaf, cpBBTree *tree)
{
Node *root = tree->root;
cpBB bb = tree->spatialIndex.bbfunc(leaf->obj);
if(!cpBBContainsBB(leaf->bb, bb)){
leaf->bb = GetBB(tree, leaf->obj);
root = SubtreeRemove(root, leaf, tree);
tree->root = SubtreeInsert(root, leaf, tree);
PairsClear(leaf, tree);
leaf->STAMP = GetMasterTree(tree)->stamp;
return cpTrue;
} else {
return cpFalse;
}
}
static cpCollisionID VoidQueryFunc(void *obj1, void *obj2, cpCollisionID id, void *data){return id;}
static void
LeafAddPairs(Node *leaf, cpBBTree *tree)
{
cpSpatialIndex *dynamicIndex = tree->spatialIndex.dynamicIndex;
if(dynamicIndex){
Node *dynamicRoot = GetRootIfTree(dynamicIndex);
if(dynamicRoot){
cpBBTree *dynamicTree = GetTree(dynamicIndex);
MarkContext context = {dynamicTree, NULL, NULL, NULL};
MarkLeafQuery(dynamicRoot, leaf, cpTrue, &context);
}
} else {
Node *staticRoot = GetRootIfTree(tree->spatialIndex.staticIndex);
MarkContext context = {tree, staticRoot, VoidQueryFunc, NULL};
MarkLeaf(leaf, &context);
}
}
//MARK: Memory Management Functions
cpBBTree *
cpBBTreeAlloc(void)
{
return (cpBBTree *)cpcalloc(1, sizeof(cpBBTree));
}
static int
leafSetEql(void *obj, Node *node)
{
return (obj == node->obj);
}
static void *
leafSetTrans(void *obj, cpBBTree *tree)
{
return LeafNew(tree, obj, tree->spatialIndex.bbfunc(obj));
}
cpSpatialIndex *
cpBBTreeInit(cpBBTree *tree, cpSpatialIndexBBFunc bbfunc, cpSpatialIndex *staticIndex)
{
cpSpatialIndexInit((cpSpatialIndex *)tree, Klass(), bbfunc, staticIndex);
tree->velocityFunc = NULL;
tree->leaves = cpHashSetNew(0, (cpHashSetEqlFunc)leafSetEql);
tree->root = NULL;
tree->pooledNodes = NULL;
tree->allocatedBuffers = cpArrayNew(0);
tree->stamp = 0;
return (cpSpatialIndex *)tree;
}
void
cpBBTreeSetVelocityFunc(cpSpatialIndex *index, cpBBTreeVelocityFunc func)
{
if(index->klass != Klass()){
cpAssertWarn(cpFalse, "Ignoring cpBBTreeSetVelocityFunc() call to non-tree spatial index.");
return;
}
((cpBBTree *)index)->velocityFunc = func;
}
cpSpatialIndex *
cpBBTreeNew(cpSpatialIndexBBFunc bbfunc, cpSpatialIndex *staticIndex)
{
return cpBBTreeInit(cpBBTreeAlloc(), bbfunc, staticIndex);
}
static void
cpBBTreeDestroy(cpBBTree *tree)
{
cpHashSetFree(tree->leaves);
if(tree->allocatedBuffers) cpArrayFreeEach(tree->allocatedBuffers, cpfree);
cpArrayFree(tree->allocatedBuffers);
}
//MARK: Insert/Remove
static void
cpBBTreeInsert(cpBBTree *tree, void *obj, cpHashValue hashid)
{
Node *leaf = (Node *)cpHashSetInsert(tree->leaves, hashid, obj, (cpHashSetTransFunc)leafSetTrans, tree);
Node *root = tree->root;
tree->root = SubtreeInsert(root, leaf, tree);
leaf->STAMP = GetMasterTree(tree)->stamp;
LeafAddPairs(leaf, tree);
IncrementStamp(tree);
}
static void
cpBBTreeRemove(cpBBTree *tree, void *obj, cpHashValue hashid)
{
Node *leaf = (Node *)cpHashSetRemove(tree->leaves, hashid, obj);
tree->root = SubtreeRemove(tree->root, leaf, tree);
PairsClear(leaf, tree);
NodeRecycle(tree, leaf);
}
static cpBool
cpBBTreeContains(cpBBTree *tree, void *obj, cpHashValue hashid)
{
return (cpHashSetFind(tree->leaves, hashid, obj) != NULL);
}
//MARK: Reindex
static void LeafUpdateWrap(Node *leaf, cpBBTree *tree) {LeafUpdate(leaf, tree);}
static void
cpBBTreeReindexQuery(cpBBTree *tree, cpSpatialIndexQueryFunc func, void *data)
{
if(!tree->root) return;
// LeafUpdate() may modify tree->root. Don't cache it.
cpHashSetEach(tree->leaves, (cpHashSetIteratorFunc)LeafUpdateWrap, tree);
cpSpatialIndex *staticIndex = tree->spatialIndex.staticIndex;
Node *staticRoot = (staticIndex && staticIndex->klass == Klass() ? ((cpBBTree *)staticIndex)->root : NULL);
MarkContext context = {tree, staticRoot, func, data};
MarkSubtree(tree->root, &context);
if(staticIndex && !staticRoot) cpSpatialIndexCollideStatic((cpSpatialIndex *)tree, staticIndex, func, data);
IncrementStamp(tree);
}
static void
cpBBTreeReindex(cpBBTree *tree)
{
cpBBTreeReindexQuery(tree, VoidQueryFunc, NULL);
}
static void
cpBBTreeReindexObject(cpBBTree *tree, void *obj, cpHashValue hashid)
{
Node *leaf = (Node *)cpHashSetFind(tree->leaves, hashid, obj);
if(leaf){
if(LeafUpdate(leaf, tree)) LeafAddPairs(leaf, tree);
IncrementStamp(tree);
}
}
//MARK: Query
static void
cpBBTreeSegmentQuery(cpBBTree *tree, void *obj, cpVect a, cpVect b, cpFloat t_exit, cpSpatialIndexSegmentQueryFunc func, void *data)
{
Node *root = tree->root;
if(root) SubtreeSegmentQuery(root, obj, a, b, t_exit, func, data);
}
static void
cpBBTreeQuery(cpBBTree *tree, void *obj, cpBB bb, cpSpatialIndexQueryFunc func, void *data)
{
if(tree->root) SubtreeQuery(tree->root, obj, bb, func, data);
}
//MARK: Misc
static int
cpBBTreeCount(cpBBTree *tree)
{
return cpHashSetCount(tree->leaves);
}
typedef struct eachContext {
cpSpatialIndexIteratorFunc func;
void *data;
} eachContext;
static void each_helper(Node *node, eachContext *context){context->func(node->obj, context->data);}
static void
cpBBTreeEach(cpBBTree *tree, cpSpatialIndexIteratorFunc func, void *data)
{
eachContext context = {func, data};
cpHashSetEach(tree->leaves, (cpHashSetIteratorFunc)each_helper, &context);
}
static cpSpatialIndexClass klass = {
(cpSpatialIndexDestroyImpl)cpBBTreeDestroy,
(cpSpatialIndexCountImpl)cpBBTreeCount,
(cpSpatialIndexEachImpl)cpBBTreeEach,
(cpSpatialIndexContainsImpl)cpBBTreeContains,
(cpSpatialIndexInsertImpl)cpBBTreeInsert,
(cpSpatialIndexRemoveImpl)cpBBTreeRemove,
(cpSpatialIndexReindexImpl)cpBBTreeReindex,
(cpSpatialIndexReindexObjectImpl)cpBBTreeReindexObject,
(cpSpatialIndexReindexQueryImpl)cpBBTreeReindexQuery,
(cpSpatialIndexQueryImpl)cpBBTreeQuery,
(cpSpatialIndexSegmentQueryImpl)cpBBTreeSegmentQuery,
};
static inline cpSpatialIndexClass *Klass(){return &klass;}
//MARK: Tree Optimization
static int
cpfcompare(const cpFloat *a, const cpFloat *b){
return (*a < *b ? -1 : (*b < *a ? 1 : 0));
}
static void
fillNodeArray(Node *node, Node ***cursor){
(**cursor) = node;
(*cursor)++;
}
static Node *
partitionNodes(cpBBTree *tree, Node **nodes, int count)
{
if(count == 1){
return nodes[0];
} else if(count == 2) {
return NodeNew(tree, nodes[0], nodes[1]);
}
// Find the AABB for these nodes
cpBB bb = nodes[0]->bb;
for(int i=1; i<count; i++) bb = cpBBMerge(bb, nodes[i]->bb);
// Split it on it's longest axis
cpBool splitWidth = (bb.r - bb.l > bb.t - bb.b);
// Sort the bounds and use the median as the splitting point
cpFloat *bounds = (cpFloat *)cpcalloc(count*2, sizeof(cpFloat));
if(splitWidth){
for(int i=0; i<count; i++){
bounds[2*i + 0] = nodes[i]->bb.l;
bounds[2*i + 1] = nodes[i]->bb.r;
}
} else {
for(int i=0; i<count; i++){
bounds[2*i + 0] = nodes[i]->bb.b;
bounds[2*i + 1] = nodes[i]->bb.t;
}
}
qsort(bounds, count*2, sizeof(cpFloat), (int (*)(const void *, const void *))cpfcompare);
cpFloat split = (bounds[count - 1] + bounds[count])*0.5f; // use the medain as the split
cpfree(bounds);
// Generate the child BBs
cpBB a = bb, b = bb;
if(splitWidth) a.r = b.l = split; else a.t = b.b = split;
// Partition the nodes
int right = count;
for(int left=0; left < right;){
Node *node = nodes[left];
if(cpBBMergedArea(node->bb, b) < cpBBMergedArea(node->bb, a)){
// if(cpBBProximity(node->bb, b) < cpBBProximity(node->bb, a)){
right--;
nodes[left] = nodes[right];
nodes[right] = node;
} else {
left++;
}
}
if(right == count){
Node *node = NULL;
for(int i=0; i<count; i++) node = SubtreeInsert(node, nodes[i], tree);
return node;
}
// Recurse and build the node!
return NodeNew(tree,
partitionNodes(tree, nodes, right),
partitionNodes(tree, nodes + right, count - right)
);
}
//static void
//cpBBTreeOptimizeIncremental(cpBBTree *tree, int passes)
//{
// for(int i=0; i<passes; i++){
// Node *root = tree->root;
// Node *node = root;
// int bit = 0;
// unsigned int path = tree->opath;
//
// while(!NodeIsLeaf(node)){
// node = (path&(1<<bit) ? node->a : node->b);
// bit = (bit + 1)&(sizeof(unsigned int)*8 - 1);
// }
//
// root = subtreeRemove(root, node, tree);
// tree->root = subtreeInsert(root, node, tree);
// }
//}
void
cpBBTreeOptimize(cpSpatialIndex *index)
{
if(index->klass != &klass){
cpAssertWarn(cpFalse, "Ignoring cpBBTreeOptimize() call to non-tree spatial index.");
return;
}
cpBBTree *tree = (cpBBTree *)index;
Node *root = tree->root;
if(!root) return;
int count = cpBBTreeCount(tree);
Node **nodes = (Node **)cpcalloc(count, sizeof(Node *));
Node **cursor = nodes;
cpHashSetEach(tree->leaves, (cpHashSetIteratorFunc)fillNodeArray, &cursor);
SubtreeRecycle(tree, root);
tree->root = partitionNodes(tree, nodes, count);
cpfree(nodes);
}
//MARK: Debug Draw
//#define CP_BBTREE_DEBUG_DRAW
#ifdef CP_BBTREE_DEBUG_DRAW
#include "OpenGL/gl.h"
#include "OpenGL/glu.h"
#include <GLUT/glut.h>
static void
NodeRender(Node *node, int depth)
{
if(!NodeIsLeaf(node) && depth <= 10){
NodeRender(node->a, depth + 1);
NodeRender(node->b, depth + 1);
}
cpBB bb = node->bb;
// GLfloat v = depth/2.0f;
// glColor3f(1.0f - v, v, 0.0f);
glLineWidth(cpfmax(5.0f - depth, 1.0f));
glBegin(GL_LINES); {
glVertex2f(bb.l, bb.b);
glVertex2f(bb.l, bb.t);
glVertex2f(bb.l, bb.t);
glVertex2f(bb.r, bb.t);
glVertex2f(bb.r, bb.t);
glVertex2f(bb.r, bb.b);
glVertex2f(bb.r, bb.b);
glVertex2f(bb.l, bb.b);
}; glEnd();
}
void
cpBBTreeRenderDebug(cpSpatialIndex *index){
if(index->klass != &klass){
cpAssertWarn(cpFalse, "Ignoring cpBBTreeRenderDebug() call to non-tree spatial index.");
return;
}
cpBBTree *tree = (cpBBTree *)index;
if(tree->root) NodeRender(tree->root, 0);
}
#endif
| {
"content_hash": "afcd0797ff3fc9f109263700c0ae22a5",
"timestamp": "",
"source": "github",
"line_count": 877,
"max_line_length": 132,
"avg_line_length": 23.168757126567844,
"alnum_prop": 0.6805453024263005,
"repo_name": "slembcke/Chipmunk2D",
"id": "2cef7bc755c831f9fa60a5ec536740fd9a20480b",
"size": "21462",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/cpBBTree.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "460221"
},
{
"name": "CMake",
"bytes": "4618"
},
{
"name": "Makefile",
"bytes": "4062"
},
{
"name": "Objective-C",
"bytes": "219100"
},
{
"name": "Ruby",
"bytes": "17137"
},
{
"name": "Shell",
"bytes": "105"
}
],
"symlink_target": ""
} |
'use strict';
module.exports = function (server, options, services) {
return {
/*
test: function (request, reply) {
services.TestService.create(request.payload)
.then(res => reply(res))
.catch(err => reply(err));
}
*/
};
}; | {
"content_hash": "4db38d5e9d9229e55fa2822ec17266af",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 55,
"avg_line_length": 15.882352941176471,
"alnum_prop": 0.5592592592592592,
"repo_name": "AhmedAli7O1/hapi-arch",
"id": "f6c61259fcc40ee861a4b12a1802a572f595b7ea",
"size": "270",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/generator/templates/controller.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "62028"
}
],
"symlink_target": ""
} |
<?php
namespace ExtendsFramework\Application\Factory;
use ExtendsFramework\Application\Application;
use ExtendsFramework\Application\Server\Server;
use ExtendsFramework\Application\Service\ServiceLocator;
class ApplicationFactoryTest extends \PHPUnit_Framework_TestCase
{
/**
* @covers \ExtendsFramework\Application\Factory\ApplicationFactory::create
*/
public function testCanCreateApplication()
{
$locator = $this->createMock(ServiceLocator::class);
$locator
->expects($this->once())
->method('get')
->with(Server::class)
->willReturn($this->createMock(Server::class));
/**
* @var ServiceLocator $locator
*/
$factory = new ApplicationFactory();
$application = $factory->create($locator, Application::class);
$this->assertInstanceOf(Application::class, $application);
}
}
| {
"content_hash": "e8b45a92c7c41ebfd9c65d5d00961a10",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 79,
"avg_line_length": 29.612903225806452,
"alnum_prop": 0.6612200435729847,
"repo_name": "extendssoftware/ExtendsFramework",
"id": "82662b88b69764d732280b135c62e9641bf1f085",
"size": "918",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/unit/Application/Factory/ApplicationFactoryTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "315838"
}
],
"symlink_target": ""
} |
> Living in this world --\\
> to what shall I compare it?\\
> Its like a boat\\
> rowing out at break of day,\\
> leaving no trace behind.
>
> by Sami Mansei in the Man'yōshū, 759 AD
> {:.attribution}
| {
"content_hash": "a8466806d62ec039b93e0c45b651c801",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 41,
"avg_line_length": 22.444444444444443,
"alnum_prop": 0.6534653465346535,
"repo_name": "profound-labs/prophecy",
"id": "b617bb34f760c4d50831e4691d5fe68e95365234",
"size": "220",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/prophecy/generators/book/manuscript/markdown/like-a-boat.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "33621"
},
{
"name": "Cucumber",
"bytes": "986"
},
{
"name": "HTML",
"bytes": "10971"
},
{
"name": "Makefile",
"bytes": "583"
},
{
"name": "Python",
"bytes": "10371"
},
{
"name": "Ruby",
"bytes": "38881"
},
{
"name": "Shell",
"bytes": "9168"
},
{
"name": "TeX",
"bytes": "39238"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "6ac083c43cd9614ff8d16493abb83c80",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "abf4e1b9f008c8fec052ea6751bf72936d9f9f01",
"size": "183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Gesneriaceae/Sinningia/Sinningia velutina/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
"""
Copyright 2015 Sai Gopal
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.
"""
from Logger import Logger
from ProfileLookup import ProfileLookup
from RedisConn import RedisConn
class IPPolicy:
"""
This class provides ip rate limiting
"""
key = 'client_address'
prefix = 'IPPolicy_'
quota = {}
def __init__(self, parsed_config):
self.parsed_config = parsed_config
self.Enforce = parsed_config.getboolean('IPPolicy', 'Enforce')
self.RejectMessage = parsed_config.get('IPPolicy', 'RejectMessage')
self.ProfileLookupObj = ProfileLookup.create_profile_lookup('IPPolicy', parsed_config)
self.ProfileCacheTTL = parsed_config.getint('IPPolicy', 'ProfileCacheTime')
for i in parsed_config.items('IPPolicy-Profiles'):
limits = i[1].split(',')
profile = i[0].lower()
IPPolicy.quota[profile] = (int(limits[0]), int(limits[1]))
self.value = self.profile = self.error = None
def check_quota(self, message, redis_pipe):
self.value = message.data[self.key]
self.profile = self.ProfileLookupObj.lookup(self.value, self.ProfileCacheTTL)
RedisConn.LUA_CALL_CHECK_LIMIT(keys=[IPPolicy.prefix + self.value], args=[IPPolicy.quota[self.profile][0]],
client=redis_pipe)
def update_quota(self, redis_pipe):
RedisConn.LUA_CALL_INCR(keys=[IPPolicy.prefix + self.value], args=[IPPolicy.quota[self.profile][1]],
client=redis_pipe)
def log_quota(self, accept, redis_val=None):
if accept:
Logger.log('IPPolicy IP: %s Quota: (%s/%s) Profile: %s Action: accept' % (
self.value, str(int(redis_val)), str(IPPolicy.quota[self.profile][0]), self.profile))
else:
Logger.log('IPPolicy IP: %s Quota: Exceeded Profile: %s Action: reject' % (self.value, self.profile))
| {
"content_hash": "632a9613776acdbfa76c44bd8fc52ed3",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 115,
"avg_line_length": 42.910714285714285,
"alnum_prop": 0.6629213483146067,
"repo_name": "EnduranceIndia/ratelimitd",
"id": "9f17e77d67e20d1333cb9c728495507128407462",
"size": "2403",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Policies/IPPolicy.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "46722"
}
],
"symlink_target": ""
} |
import * as React from 'react';
import { SxProps } from '@material-ui/system';
import { Theme } from '../styles';
import { InternalStandardProps as StandardProps } from '..';
export interface SpeedDialIconProps
extends StandardProps<React.HTMLAttributes<HTMLSpanElement>, 'children'> {
/**
* Override or extend the styles applied to the component.
*/
classes?: {
/** Styles applied to the root element. */
root?: string;
/** Styles applied to the icon component. */
icon?: string;
/** Styles applied to the icon component if `open={true}`. */
iconOpen?: string;
/** Styles applied to the icon when an `openIcon` is provided and if `open={true}`. */
iconWithOpenIconOpen?: string;
/** Styles applied to the `openIcon` if provided. */
openIcon?: string;
/** Styles applied to the `openIcon` if provided and if `open={true}`. */
openIconOpen?: string;
};
/**
* The icon to display.
*/
icon?: React.ReactNode;
/**
* The icon to display in the SpeedDial Floating Action Button when the SpeedDial is open.
*/
openIcon?: React.ReactNode;
/**
* @ignore
* If `true`, the component is shown.
*/
open?: boolean;
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx?: SxProps<Theme>;
}
export type SpeedDialIconClassKey = keyof NonNullable<SpeedDialIconProps['classes']>;
/**
*
* Demos:
*
* - [Speed Dial](https://material-ui.com/components/speed-dial/)
*
* API:
*
* - [SpeedDialIcon API](https://material-ui.com/api/speed-dial-icon/)
*/
export default function SpeedDialIcon(props: SpeedDialIconProps): JSX.Element;
| {
"content_hash": "06f0451901104a2d93e8e1ebf12ddc6a",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 92,
"avg_line_length": 29.803571428571427,
"alnum_prop": 0.6632714200119832,
"repo_name": "cdnjs/cdnjs",
"id": "d7ab93804c098cfc41f170dc79fadb64a4c4bd81",
"size": "1669",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "ajax/libs/material-ui/5.0.0-alpha.28/SpeedDialIcon/SpeedDialIcon.d.ts",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
{-# LANGUAGE CPP #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}
#if __GLASGOW_HASKELL__ >= 800
{-# OPTIONS_GHC -Wno-orphans #-}
#endif
#include "Streams/inline.hs"
-- |
-- Module : Streamly.Prelude
-- Copyright : (c) 2017 Harendra Kumar
--
-- License : BSD3
-- Maintainer : streamly@composewell.com
-- Stability : experimental
-- Portability : GHC
--
-- This module is designed to be imported qualified:
--
-- @
-- import qualified Streamly.Prelude as S
-- @
--
-- Functions with the suffix @M@ are general functions that work on monadic
-- arguments. The corresponding functions without the suffix @M@ work on pure
-- arguments and can in general be derived from their monadic versions but are
-- provided for convenience and for consistency with other pure APIs in the
-- @base@ package.
--
-- In many cases, short definitions of the combinators are provided in the
-- documentation for illustration. The actual implementation may differ for
-- performance reasons.
--
-- Functions having a 'MonadAsync' constraint work concurrently when used with
-- appropriate stream type combinator. Please be careful to not use 'parallely'
-- with infinite streams.
--
-- Deconstruction and folds accept a 'SerialT' type instead of a polymorphic
-- type to ensure that streams always have a concrete monomorphic type by
-- default, reducing type errors. In case you want to use any other type of
-- stream you can use one of the type combinators provided in the "Streamly"
-- module to convert the stream type.
module Streamly.Prelude
(
-- * Construction
-- ** Primitives
-- | Primitives to construct a stream from pure values or monadic actions.
-- All other stream construction and generation combinators described later
-- can be expressed in terms of these primitives. However, the special
-- versions provided in this module can be much more efficient in most
-- cases. Users can create custom combinators using these primitives.
nil
, cons
, (.:)
, consM
, (|:)
-- ** From Values
-- | Generate a monadic stream from a seed value or values.
, yield
, yieldM
, repeat
, repeatM
, replicate
, replicateM
-- Note: Using enumeration functions e.g. 'Prelude.enumFromThen' turns out
-- to be slightly faster than the idioms like @[from, then..]@.
--
-- ** Enumeration
-- | We can use the 'Enum' type class to enumerate a type producing a list
-- and then convert it to a stream:
--
-- @
-- 'fromList' $ 'Prelude.enumFromThen' from then
-- @
--
-- However, this is not particularly efficient.
-- The 'Enumerable' type class provides corresponding functions that
-- generate a stream instead of a list, efficiently.
, Enumerable (..)
, enumerate
, enumerateTo
-- ** From Generators
-- | Generate a monadic stream from a seed value and a generator function.
, unfoldr
, unfoldrM
, unfold
, iterate
, iterateM
, fromIndices
, fromIndicesM
-- ** From Containers
-- | Convert an input structure, container or source into a stream. All of
-- these can be expressed in terms of primitives.
, fromList
, fromListM
, fromFoldable
, fromFoldableM
-- * Elimination
-- ** Deconstruction
-- | It is easy to express all the folds in terms of the 'uncons' primitive,
-- however the specific implementations provided later are generally more
-- efficient.
--
, uncons
, tail
, init
-- ** Folding
-- | In imperative terms a fold can be considered as a loop over the stream
-- that reduces the stream to a single value.
-- Left and right folds use a fold function @f@ and an identity element @z@
-- (@zero@) to recursively deconstruct a structure and then combine and reduce
-- the values or transform and reconstruct a new container.
--
-- In general, a right fold is suitable for transforming and reconstructing a
-- right associated structure (e.g. cons lists and streamly streams) and a left
-- fold is suitable for reducing a right associated structure. The behavior of
-- right and left folds are described in detail in the individual fold's
-- documentation. To illustrate the two folds for cons lists:
--
-- > foldr :: (a -> b -> b) -> b -> [a] -> b
-- > foldr f z [] = z
-- > foldr f z (x:xs) = x `f` foldr f z xs
-- >
-- > foldl :: (b -> a -> b) -> b -> [a] -> b
-- > foldl f z [] = z
-- > foldl f z (x:xs) = foldl f (z `f` x) xs
--
-- @foldr@ is conceptually equivalent to:
--
-- > foldr f z [] = z
-- > foldr f z [x] = f x z
-- > foldr f z xs = foldr f (foldr f z (tail xs)) [head xs]
--
-- @foldl@ is conceptually equivalent to:
--
-- > foldl f z [] = z
-- > foldl f z [x] = f z x
-- > foldl f z xs = foldl f (foldl f z (init xs)) [last xs]
--
-- Left and right folds are duals of each other.
--
-- @
-- foldr f z xs = foldl (flip f) z (reverse xs)
-- foldl f z xs = foldr (flip f) z (reverse xs)
-- @
--
-- More generally:
--
-- @
-- foldr f z xs = foldl g id xs z where g k x = k . f x
-- foldl f z xs = foldr g id xs z where g x k = k . flip f x
-- @
--
-- As a general rule, foldr cannot have state and foldl cannot have control.
-- NOTE: Folds are inherently serial as each step needs to use the result of
-- the previous step. However, it is possible to fold parts of the stream in
-- parallel and then combine the results using a monoid.
-- ** Right Folds
-- $rightfolds
, foldrM
-- , foldrS
-- , foldrT
, foldr
-- ** Left Folds
-- $leftfolds
, foldl'
, foldl1'
, foldlM'
-- ** Composable Left Folds
-- $runningfolds
, fold
-- ** Full Folds
-- | Folds that are guaranteed to evaluate the whole stream.
-- -- ** To Summary (Full Folds)
-- -- | Folds that summarize the stream to a single value.
, drain
, last
, length
, sum
, product
--, mconcat
-- -- ** To Summary (Maybe) (Full Folds)
-- -- | Folds that summarize a non-empty stream to a 'Just' value and return
-- 'Nothing' for an empty stream.
, maximumBy
, maximum
, minimumBy
, minimum
, the
-- , toListRev -- experimental
-- ** Lazy Folds
--
-- | Folds that generate a lazy structure. Note that the generated
-- structure may not be lazy if the underlying monad is strict.
-- -- ** To Containers (Full Folds)
-- -- | Convert or divert a stream into an output structure, container or
-- sink.
, toList
-- ** Partial Folds
-- | Folds that may terminate before evaluating the whole stream. These
-- folds strictly evaluate the stream until the result is determined.
-- -- ** To Elements (Partial Folds)
, drainN
, drainWhile
-- -- | Folds that extract selected elements of a stream or their properties.
, (!!)
, head
, findM
, find
, lookup
, findIndex
, elemIndex
-- -- ** To Boolean (Partial Folds)
-- -- | Folds that summarize the stream to a boolean value.
, null
, elem
, notElem
, all
, any
, and
, or
-- ** Multi-Stream folds
, eqBy
, cmpBy
, isPrefixOf
-- , isSuffixOf
-- , isInfixOf
, isSubsequenceOf
-- trimming sequences
, stripPrefix
-- , stripSuffix
-- , stripInfix
-- * Transformation
--, transform
-- ** Mapping
-- | In imperative terms a map operation can be considered as a loop over
-- the stream that transforms the stream into another stream by performing
-- an operation on each element of the stream.
--
-- 'map' is the least powerful transformation operation with strictest
-- guarantees. A map, (1) is a stateless loop which means that no state is
-- allowed to be carried from one iteration to another, therefore,
-- operations on different elements are guaranteed to not affect each
-- other, (2) is a strictly one-to-one transformation of stream elements
-- which means it guarantees that no elements can be added or removed from
-- the stream, it can merely transform them.
, map
, sequence
, mapM
-- ** Special Maps
, mapM_
, trace
, tap
-- ** Scanning
--
-- | A scan is more powerful than map. While a 'map' is a stateless loop, a
-- @scan@ is a stateful loop which means that a state can be shared across
-- all the loop iterations, therefore, future iterations can be impacted by
-- the state changes made by the past iterations. A scan yields the state
-- of the loop after each iteration. Like a map, a @postscan@ or @prescan@
-- does not add or remove elements in the stream, it just transforms them.
-- However, a @scan@ adds one extra element to the stream.
--
-- A left associative scan, also known as a prefix sum, can be thought of
-- as a stream transformation consisting of left folds of all prefixes of a
-- stream. Another way of thinking about it is that it streams all the
-- intermediate values of the accumulator while applying a left fold on the
-- input stream. A right associative scan, on the other hand, can be
-- thought of as a stream consisting of right folds of all the suffixes of
-- a stream.
--
-- The following equations hold for lists:
--
-- > scanl f z xs == map (foldl f z) $ inits xs
-- > scanr f z xs == map (foldr f z) $ tails xs
--
-- @
-- > scanl (+) 0 [1,2,3,4]
-- 0 = 0
-- 0 + 1 = 1
-- 0 + 1 + 2 = 3
-- 0 + 1 + 2 + 3 = 6
-- 0 + 1 + 2 + 3 + 4 = 10
--
-- > scanr (+) 0 [1,2,3,4]
-- 1 + 2 + 3 + 4 + 0 = 10
-- 2 + 3 + 4 + 0 = 9
-- 3 + 4 + 0 = 7
-- 4 + 0 = 4
-- 0 = 0
-- @
--
-- Left and right scans are duals:
--
-- > scanr f z xs == reverse $ scanl (flip f) z (reverse xs)
-- > scanl f z xs == reverse $ scanr (flip f) z (reverse xs)
--
-- A scan is a stateful map i.e. a combination of map and fold:
--
-- > map f xs = tail $ scanl (\_ x -> f x) z xs
-- > map f xs = reverse $ head $ scanr (\_ x -> f x) z xs
--
-- > foldl f z xs = last $ scanl f z xs
-- > foldr f z xs = head $ scanr f z xs
-- ** Left scans
, scanl'
, scanlM'
, postscanl'
, postscanlM'
-- , prescanl'
-- , prescanlM'
, scanl1'
, scanl1M'
-- ** Scan Using Fold
, scan
, postscan
-- , lscanl'
-- , lscanlM'
-- , lscanl1'
-- , lscanl1M'
--
-- , lpostscanl'
-- , lpostscanlM'
-- , lprescanl'
-- , lprescanlM'
-- ** Filtering
-- | Remove some elements from the stream based on a predicate. In
-- imperative terms a filter over a stream corresponds to a loop with a
-- @continue@ clause for the cases when the predicate fails.
, filter
, filterM
-- ** Mapping Filters
-- | Mapping along with filtering
, mapMaybe
, mapMaybeM
-- ** Deleting Elements
-- | Deleting elements is a special case of de-interleaving streams.
, deleteBy
, uniq
-- , uniqBy -- by predicate e.g. to remove duplicate "/" in a path
-- , uniqOn -- to remove duplicate sequences
-- , pruneBy -- dropAround + uniqBy - like words
-- ** Inserting Elements
-- | Inserting elements is a special case of interleaving/merging streams.
, insertBy
, intersperseM
, intersperse
-- , insertAfterEach
-- , intersperseBySpan
-- , intersperseByIndices -- using an index function/stream
-- , intersperseByTime
-- , intersperseByEvent
-- -- * Inserting Streams in Streams
-- , interposeBy
-- , intercalate
-- ** Indexing
-- | Indexing can be considered as a special type of zipping where we zip a
-- stream with an index stream.
, indexed
, indexedR
-- , timestamped
-- , timestampedR -- timer
-- ** Reordering Elements
, reverse
-- , reverse'
-- ** Trimming
-- | Take or remove elements from one or both ends of a stream.
, take
-- , takeEnd
, takeWhile
, takeWhileM
-- , takeWhileEnd
, drop
-- , dropEnd
, dropWhile
, dropWhileM
-- , dropWhileEnd
-- , dropAround
-- -- ** Breaking
-- By chunks
-- , splitAt -- spanN
-- , splitIn -- sessionN
-- By elements
-- , span -- spanWhile
-- , break -- breakBefore
-- , breakAfter
-- , breakOn
-- , breakAround
-- , spanBy
-- , spanByRolling
-- By sequences
-- breakOnSeq/breakOnArray -- on a fixed sequence
-- breakOnStream -- on a stream
-- ** Slicing
-- | Streams can be sliced into segments in space or in time. We use the
-- term @chunk@ to refer to a spatial length of the stream (spatial window)
-- and the term @session@ to refer to a length in time (time window).
-- In imperative terms, grouped folding can be considered as a nested loop
-- where we loop over the stream to group elements and then loop over
-- individual groups to fold them to a single value that is yielded in the
-- output stream.
-- , groupScan
, chunksOf
, intervalsOf
-- ** Searching
-- | Finding the presence or location of an element, a sequence of elements
-- or another stream within a stream.
-- -- ** Searching Elements
, findIndices
, elemIndices
-- -- *** Searching Sequences
-- , seqIndices -- search a sequence in the stream
-- -- *** Searching Multiple Sequences
-- , seqIndices -- search a sequence in the stream
-- -- ** Searching Streams
-- -- | Finding a stream within another stream.
-- ** Splitting
-- | In general we can express splitting in terms of parser combinators.
-- These are some common use functions for convenience and efficiency.
-- While parsers can fail these functions are designed to transform a
-- stream without failure with a predefined behavior for all cases.
--
-- In general, there are three possible ways of combining stream segments
-- with a separator. The separator could be prefixed to each segment,
-- suffixed to each segment, or it could be infixed between segments.
-- 'intersperse' and 'intercalate' operations are examples of infixed
-- combining whereas 'unlines' is an example of suffixed combining. When we
-- split a stream with separators we can split in three different ways,
-- each being an opposite of the three ways of combining.
--
-- Splitting may keep the separator or drop it. Depending on how we split,
-- the separator may be kept attached to the stream segments in prefix or
-- suffix position or as a separate element in infix position. Combinators
-- like 'splitOn' that use @On@ in their names drop the separator and
-- combinators that use 'With' in their names keep the separator. When a
-- segment is missing it is considered as empty, therefore, we never
-- encounter an error in parsing.
-- -- ** Splitting By Elements
, splitOn
, splitOnSuffix
-- , splitOnPrefix
-- , splitBy
, splitWithSuffix
-- , splitByPrefix
, wordsBy -- strip, compact and split
-- -- *** Splitting By Sequences
-- , splitOnSeq
-- , splitOnSuffixSeq
-- , splitOnPrefixSeq
-- Keeping the delimiters
-- , splitBySeq
-- , splitBySeqSuffix
-- , splitBySeqPrefix
-- , wordsBySeq
-- Splitting By Multiple Sequences
-- , splitOnAnySeq
-- , splitOnAnySuffixSeq
-- , splitOnAnyPrefixSeq
-- -- ** Splitting By Streams
-- -- | Splitting a stream using another stream as separator.
-- ** Grouping
-- | Splitting a stream by combining multiple contiguous elements into
-- groups using some criterion.
, groups
, groupsBy
, groupsByRolling
{-
-- * Windowed Classification
-- | Split the stream into windows or chunks in space or time. Each window
-- can be associated with a key, all events associated with a particular
-- key in the window can be folded to a single result. The stream is split
-- into windows of specified size, the window can be terminated early if
-- the closing flag is specified in the input stream.
--
-- The term "chunk" is used for a space window and the term "session" is
-- used for a time window.
-- ** Tumbling Windows
-- | A new window starts after the previous window is finished.
-- , classifyChunksOf
-- , classifySessionsOf
-- ** Keep Alive Windows
-- | The window size is extended if an event arrives within the specified
-- window size. This can represent sessions with idle or inactive timeout.
-- , classifyKeepAliveChunks
-- , classifyKeepAliveSessions
{-
-- ** Sliding Windows
-- | A new window starts after the specified slide from the previous
-- window. Therefore windows can overlap.
, classifySlidingChunks
, classifySlidingSessions
-}
-- ** Sliding Window Buffers
-- , slidingChunkBuffer
-- , slidingSessionBuffer
-}
-- * Combining Streams
-- | New streams can be constructed by appending, merging or zipping
-- existing streams.
-- ** Appending
-- | Streams form a 'Semigroup' and a 'Monoid' under the append
-- operation. Appending can be considered as a generalization of the `cons`
-- operation to consing a stream to a stream.
--
-- @
--
-- -------Stream m a------|-------Stream m a------|=>----Stream m a---
--
-- @
--
-- @
-- >> S.toList $ S.fromList [1,2] \<> S.fromList [3,4]
-- [1,2,3,4]
-- >> S.toList $ fold $ [S.fromList [1,2], S.fromList [3,4]]
-- [1,2,3,4]
-- @
-- ** Merging
-- | Streams form a commutative semigroup under the merge
-- operation. Merging can be considered as a generalization of inserting an
-- element in a stream to interleaving a stream with another stream.
--
-- @
--
-- -------Stream m a------|
-- |=>----Stream m a---
-- -------Stream m a------|
-- @
--
-- , merge
, mergeBy
, mergeByM
, mergeAsyncBy
, mergeAsyncByM
-- ** Zipping
-- |
-- @
--
-- -------Stream m a------|
-- |=>----Stream m c---
-- -------Stream m b------|
-- @
--
, zipWith
, zipWithM
, zipAsyncWith
, zipAsyncWithM
{-
-- ** Folding Containers of Streams
-- | These are variants of standard 'Foldable' fold functions that use a
-- polymorphic stream sum operation (e.g. 'async' or 'wSerial') to fold a
-- finite container of streams. Note that these are just special cases of
-- the more general 'concatMapWith' operation.
--
, foldMapWith
, forEachWith
, foldWith
-}
-- ** Folding Streams of Streams
-- | Stream operations like map and filter represent loop processing in
-- imperative programming terms. Similarly, the imperative concept of
-- nested loops are represented by streams of streams. The 'concatMap'
-- operation represents nested looping.
-- A 'concatMap' operation loops over the input stream and then for each
-- element of the input stream generates another stream and then loops over
-- that inner stream as well producing effects and generating a single
-- output stream.
-- The 'Monad' instances of different stream types provide a more
-- convenient way of writing nested loops. Note that the monad bind
-- operation is just @flip concatMap@.
--
-- One dimension loops are just a special case of nested loops. For
-- example, 'concatMap' can degenerate to a simple map operation:
--
-- > map f m = S.concatMap (\x -> S.yield (f x)) m
--
-- Similarly, 'concatMap' can perform filtering by mapping an element to a
-- 'nil' stream:
--
-- > filter p m = S.concatMap (\x -> if p x then S.yield x else S.nil) m
--
-- XXX add stateful concatMapWith
, concatMapWith
--, bindWith
, concatMap
, concatMapM
, concatUnfold
-- * Exceptions
, before
, after
, bracket
, onException
, finally
, handle
-- * Deprecated
, once
, each
, scanx
, foldx
, foldxM
, foldr1
, runStream
, runN
, runWhile
, fromHandle
, toHandle
)
where
import Prelude
hiding (filter, drop, dropWhile, take, takeWhile, zipWith, foldr,
foldl, map, mapM, mapM_, sequence, all, any, sum, product, elem,
notElem, maximum, minimum, head, last, tail, length, null,
reverse, iterate, init, and, or, lookup, foldr1, (!!),
scanl, scanl1, repeat, replicate, concatMap, span)
import Streamly.Internal.Prelude
-- $rightfolds
--
-- Let's take a closer look at the @foldr@ definition for lists, as given
-- earlier:
--
-- @
-- foldr f z (x:xs) = x \`f` foldr f z xs
-- @
--
-- @foldr@ invokes the fold step function @f@ as @f x (foldr f z xs)@. At each
-- invocation of @f@, @foldr@ gives us the next element in the input container
-- @x@ and a recursive expression @foldr f z xs@ representing the yet unbuilt
-- (lazy thunk) part of the output.
--
-- When @f x xs@ is lazy in @xs@ it can consume the input one element at a time
-- in FIFO order to build a lazy output expression. For example,
--
-- > f x remaining = show x : remaining
--
-- @take 2 $ foldr f [] (1:2:undefined)@ would consume the input lazily on
-- demand, consuming only first two elements and resulting in ["1", "2"]. @f@
-- can terminate recursion by not evaluating the @remaining@ part:
--
-- > f 2 remaining = show 2 : []
-- > f x remaining = show x : remaining
--
-- @f@ would terminate recursion whenever it sees element @2@ in the input.
-- Therefore, @take 2 $ foldr f [] (1:2:undefined)@ would work without any
-- problem.
--
-- On the other hand, if @f a b@ is strict in @b@ it would end up consuming the
-- whole input right away and expanding the recursive expression @b@ (i.e.
-- @foldr f z xs@) fully before it yields an output expression, resulting in
-- the following /right associated expression/:
--
-- @
-- foldr f z xs == x1 \`f` (x2 \`f` ...(xn \`f` z))
-- @
--
-- For example,
--
-- > f x remaining = x + remaining
--
-- With this definition, @foldr f 0 [1..1000]@, would recurse completely until
-- it reaches the terminating case @... `f` (1000 `f` 0)@, and then
-- start reducing the whole expression from right to left, therefore, consuming
-- the input elements in LIFO order. Thus, such an evaluation would require
-- memory proportional to the size of input. Try out @foldr (+) 0 (map (\\x ->
-- trace (show x) x) [1..10])@.
--
-- Notice the order of the arguments to the step function @f a b@. It follows
-- the order of @a@ and @b@ in the right associative recursive expression
-- generated by expanding @a \`f` b@.
--
-- A right fold is a pull fold, the step function is the puller, it can pull
-- more data from the input container by using its second argument in the
-- output expression or terminate pulling by not using it. As a corollary:
--
-- 1. a step function which is lazy in its second argument (usually functions
-- or constructors that build a lazy structure e.g. @(:)@) can pull lazily on
-- demand.
-- 2. a step function strict in its second argument (usually reducers e.g.
-- (+)) would end up pulling all of its input and buffer it in memory before
-- potentially reducing it.
--
-- A right fold is suitable for lazy reconstructions e.g. transformation,
-- mapping, filtering of /right associated input structures/ (e.g. cons lists).
-- Whereas a left fold is suitable for reductions (e.g. summing a stream of
-- numbers) of right associated structures. Note that these roles will reverse
-- for left associated structures (e.g. snoc lists). Most of our observations
-- here assume right associated structures, lists being the canonical example.
--
-- 1. A lazy FIFO style pull using a right fold allows pulling a potentially
-- /infinite/ input stream lazily, perform transformations on it, and
-- reconstruct a new structure without having to buffer the whole structure. In
-- contrast, a left fold would buffer the entire structure before the
-- reconstructed structure can be consumed.
-- 2. Even if buffering the entire input structure is ok, we need to keep in
-- mind that a right fold reconstructs structures in a FIFO style, whereas a
-- left fold reconstructs in a LIFO style, thereby reversing the order of
-- elements..
-- 3. A right fold has termination control and therefore can terminate early
-- without going through the entire input, a left fold cannot terminate
-- without consuming all of its input. For example, a right fold
-- implementation of 'or' can terminate as soon as it finds the first 'True'
-- element, whereas a left fold would necessarily go through the entire input
-- irrespective of that.
-- 4. Reduction (e.g. using (+) on a stream of numbers) using a right fold
-- occurs in a LIFO style, which means that the entire input gets buffered
-- before reduction starts. Whereas with a strict left fold reductions occur
-- incrementally in FIFO style. Therefore, a strict left fold is more suitable
-- for reductions.
--
-- $leftfolds
--
-- Note that the observations below about the behavior of a left fold assume
-- that we are working on a right associated structure like cons lists and
-- streamly streams. If we are working on a left associated structure (e.g.
-- snoc lists) the roles of right and left folds would reverse.
--
-- Let's take a closer look at the @foldl@ definition for lists given above:
--
-- @
-- foldl f z (x:xs) = foldl f (z \`f` x) xs
-- @
--
-- @foldl@ calls itself recursively, in each call it invokes @f@ as @f z x@
-- providing it with the result accumulated till now @z@ (the state) and the
-- next element from the input container. First call to @f@ is supplied with
-- the initial value of the accumulator @z@ and each subsequent call uses the
-- output of the previous call to @f z x@.
--
-- >> foldl' (+) 0 [1,2,3]
-- > 6
--
-- The recursive call at the head of the output expression is bound to be
-- evaluated until recursion terminates, therefore, a left fold always
-- /consumes the whole input container/. The following would result in an
-- error, even though the fold is not using the values at all:
--
-- >> foldl' (\_ _ -> 0) 0 (1:undefined)
-- > *** Exception: Prelude.undefined
--
-- As @foldl@ recurses, it builds the left associated expression shown below.
-- Notice, the order of the arguments to the step function @f b a@. It follows
-- the left associative recursive expression generated by expanding @b \`f` a@.
--
-- @
-- foldl f z xs == (((z \`f` x1) \`f` x2) ...) \`f` xn
-- @
--
--
-- The strict left fold @foldl'@ forces the reduction of its argument @z \`f`
-- x@ before using it, therefore it never builds the whole expression in
-- memory. Thus, @z \`f` x1@ would get reduced to @z1@ and then @z1 \`f` x2@
-- would get reduced to @z2@ and so on, incrementally reducing the expression
-- from left to right as it recurses, consuming the input in FIFO order. Try
-- out @foldl' (+) 0 (map (\\x -> trace (show x) x) [1..10])@ to see how it
-- works. For example:
--
-- @
-- > S.foldl' (+) 0 $ S.fromList [1,2,3,4]
-- 10
-- @
--
-- @
-- 0 + 1 = 1
-- 1 + 2 = 3
-- 3 + 3 = 6
-- 6 + 4 = 10
-- @
--
-- However, @foldl'@ evaluates the accumulator only to WHNF. It may further
-- help if the step function uses a strict data structure as accumulator to
-- improve performance and to keep the expression fully reduced at all times
-- during the fold.
--
-- A left fold can also build a new structure instead of reducing one if a
-- constructor is used as a fold step. However, it may not be very useful
-- because it will consume the whole input and construct the new structure in
-- memory before we can consume it. Thus the whole structure gets buffered in
-- memory. When the list constructor is used it would build a new list in
-- reverse (LIFO) order:
--
-- @
-- > S.foldl' (flip (:)) [] $ S.fromList [1,2,3,4]
-- [4,3,2,1]
-- @
--
-- A left fold is a push fold. The producer pushes its contents to the step
-- function of the fold. The step function therefore has no control to stop the
-- input, it can only discard it if it does not need it. We can also consider a
-- left fold as a state machine where the state is store in the accumulator,
-- the state can be modified based on new inputs that are pushed to the fold.
--
-- In general, a strict left fold is a reducing fold, whereas a right fold is a
-- constructing fold. A strict left fold reduces in a FIFO order whereas it
-- constructs in a LIFO order, and vice-versa for the right fold. See the
-- documentation of 'foldrM' for a discussion on where a left or right fold is
-- suitable.
--
-- To perform a left fold lazily without having to consume all the input one
-- can use @scanl@ to stream the intermediate results of the fold and consume
-- the resulting stream lazily.
--
-- $runningfolds
--
-- "Streamly.Data.Fold" module defines composable left folds which can be combined
-- together in many interesting ways. Those folds can be run using 'fold'.
-- The following two ways of folding are equivalent in functionality and
-- performance,
--
-- >>> S.fold FL.sum (S.enumerateFromTo 1 100)
-- 5050
-- >>> S.sum (S.enumerateFromTo 1 100)
-- 5050
--
-- However, left folds cannot terminate early even if it does not need to
-- consume more input to determine the result. Therefore, the performance is
-- equivalent only for full folds like 'sum' and 'length'. For partial folds
-- like 'head' or 'any' the the folds defined in this module may be much more
-- efficient because they are implemented as right folds that terminate as soon
-- as we get the result. Note that when a full fold is composed with a partial
-- fold in parallel the performance is not impacted as we anyway have to
-- consume the whole stream due to the full fold.
--
-- >>> S.head (1 `S.cons` undefined)
-- Just 1
-- >>> S.fold FL.head (1 `S.cons` undefined)
-- *** Exception: Prelude.undefined
--
-- However, we can wrap the fold in a scan to convert it into a lazy stream of
-- fold steps. We can then terminate the stream whenever we want. For example,
--
-- >>> S.toList $ S.take 1 $ S.scan FL.head (1 `S.cons` undefined)
-- [Nothing]
--
-- The following example extracts the input stream up to a point where the
-- running average of elements is no more than 10:
--
-- @
-- > S.toList
-- $ S.map (fromJust . fst)
-- $ S.takeWhile (\\(_,x) -> x <= 10)
-- $ S.postscan ((,) \<$> FL.last \<*> avg) (S.enumerateFromTo 1.0 100.0)
-- @
-- @
-- [1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0]
-- @
| {
"content_hash": "e6c35058059caa40cb74f64ae3d572fe",
"timestamp": "",
"source": "github",
"line_count": 932,
"max_line_length": 91,
"avg_line_length": 33.19849785407725,
"alnum_prop": 0.640024562877735,
"repo_name": "harendra-kumar/asyncly",
"id": "c56c5e0d6603b4ab838cbf44404438439f420472",
"size": "30941",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Streamly/Prelude.hs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Haskell",
"bytes": "139406"
}
],
"symlink_target": ""
} |
module.exports = function( caminio ){
'use strict';
var async = require('async');
var inflection = require('inflection');
caminio.hooks = {};
caminio.hooks._data = {};
/**
* @method invokeHook
* @param {String} name of the hook
* @param {Object} options
* @param {Object} options.scope the scope (this-object) for the hooks
* @param {Function} callback
*/
caminio.hooks.invoke = function invokeHook( name, options, cb ){
if( typeof(options) === 'function' ){
cb = options;
options = {};
}
options = options || {};
if( caminio.hooks._data[ name ] )
return async.eachSeries( caminio.hooks._data[ name ], function( hook, nextIteration ){
hook.call( options.scope || null, nextIteration );
}, cb || null );
if( cb )
cb();
};
/**
* @method registerHook
* @param {String} name of the hook
* @param {Function} function to be called
*/
caminio.hooks.register = function registerHook( name, hook ){
name = inflection.dasherize( name.replace('.js','') );
caminio.hooks._data[ name ] = caminio.hooks._data[ name ] || [];
caminio.hooks._data[ name ].push( hook );
};
};
// DEPRECATED since 1.1
//
///*
// * camin.io
// *
// * @author quaqua <quaqua@tastenwerk.com>
// * @date 01/2014
// * @copyright TASTENWERK http://tastenwerk.com
// * @license MIT
// *
// */
//
//var _ = require('lodash')
// , async = require('async');
//
//
//module.exports = function( caminio ){
//
// var hooks = {
// before: {},
// after: {}
// }
//
// return {
// define: defineHook,
// invoke: invokeHook
// }
//
// /**
// * hook something inbetween an initializiation process.
// * The hook will be invoked, either before or after the
// * defined method.
// *
// * @class Caminio
// * @method define
// *
// * @param {String} type ['before','after']
// * @param {String} initialiser an initializer name. Possible
// * values: ['session']
// * @param {Function} fn the function to be executed
// *
// * @example:
// *
// * new Hook( 'before', 'session' )
// * => will be invoked before session is invoked
// *
// */
// function defineHook( type, initializer, name, fn ){
// hooks[type][initializer] = hooks[type][initializer] || [];
// hooks[type][initializer].push( { name: name, fn: fn } );
// }
//
// /**
// * invoke hooks for given type and initializer
// *
// * @class Caminio
// * @method invoke
// *
// * @param {String} type ['before', 'after']
// * @param {String} initializer
// * @param {Function} cb
// *
// */
// function invokeHook( type, initializer, cb ){
// if( !hooks[type][initializer] || hooks[type][initializer].length < 1 )
// return (typeof(cb) === 'function' ? cb() : null);
//
// async.each( hooks[type][initializer], function( runner, cbAsync ){
// caminio.logger.debug('invoking hook', runner.name, 'in:', type, initializer);
// runner.fn( cbAsync );
// }, cb );
//
// }
//
//}
| {
"content_hash": "74d18c3dcd1338c79d9dff3e5e33725e",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 92,
"avg_line_length": 24.91869918699187,
"alnum_prop": 0.5628058727569332,
"repo_name": "caminio/caminio",
"id": "49eace5f1374e1f6b416d18c0072d2677cec132c",
"size": "3065",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/loader/hooks.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "100266"
},
{
"name": "CoffeeScript",
"bytes": "67878"
},
{
"name": "JavaScript",
"bytes": "183154"
},
{
"name": "Ruby",
"bytes": "81573"
}
],
"symlink_target": ""
} |
#pragma once
#include <aws/iot1click-projects/IoT1ClickProjects_EXPORTS.h>
#include <aws/iot1click-projects/IoT1ClickProjectsRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace IoT1ClickProjects
{
namespace Model
{
/**
*/
class AWS_IOT1CLICKPROJECTS_API DeleteProjectRequest : public IoT1ClickProjectsRequest
{
public:
DeleteProjectRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "DeleteProject"; }
Aws::String SerializePayload() const override;
/**
* <p>The name of the empty project to delete.</p>
*/
inline const Aws::String& GetProjectName() const{ return m_projectName; }
/**
* <p>The name of the empty project to delete.</p>
*/
inline bool ProjectNameHasBeenSet() const { return m_projectNameHasBeenSet; }
/**
* <p>The name of the empty project to delete.</p>
*/
inline void SetProjectName(const Aws::String& value) { m_projectNameHasBeenSet = true; m_projectName = value; }
/**
* <p>The name of the empty project to delete.</p>
*/
inline void SetProjectName(Aws::String&& value) { m_projectNameHasBeenSet = true; m_projectName = std::move(value); }
/**
* <p>The name of the empty project to delete.</p>
*/
inline void SetProjectName(const char* value) { m_projectNameHasBeenSet = true; m_projectName.assign(value); }
/**
* <p>The name of the empty project to delete.</p>
*/
inline DeleteProjectRequest& WithProjectName(const Aws::String& value) { SetProjectName(value); return *this;}
/**
* <p>The name of the empty project to delete.</p>
*/
inline DeleteProjectRequest& WithProjectName(Aws::String&& value) { SetProjectName(std::move(value)); return *this;}
/**
* <p>The name of the empty project to delete.</p>
*/
inline DeleteProjectRequest& WithProjectName(const char* value) { SetProjectName(value); return *this;}
private:
Aws::String m_projectName;
bool m_projectNameHasBeenSet;
};
} // namespace Model
} // namespace IoT1ClickProjects
} // namespace Aws
| {
"content_hash": "b670c92014049a0af438d973ec856f79",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 121,
"avg_line_length": 31.3125,
"alnum_prop": 0.6846307385229541,
"repo_name": "awslabs/aws-sdk-cpp",
"id": "ece7972ea1a040cb1e5c5a351d00b061933f83b0",
"size": "2624",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-iot1click-projects/include/aws/iot1click-projects/model/DeleteProjectRequest.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "7596"
},
{
"name": "C++",
"bytes": "61740540"
},
{
"name": "CMake",
"bytes": "337520"
},
{
"name": "Java",
"bytes": "223122"
},
{
"name": "Python",
"bytes": "47357"
}
],
"symlink_target": ""
} |
using System;
using System.Collections;
using System.IO;
using MbUnit.Core.Framework;
using MbUnit.Framework;
#endregion
using MbUnit.Core.Reports;
namespace MbUnit.Tests.Core.Reports
{
/// <summary>
/// <see cref="TestFixture"/> for the <see cref="NamePretifier"/> class.
/// </summary>
[TestFixture]
public class NamePretifierTest
{
private NamePretifier np;
[SetUp]
public void SetUp()
{
this.np=new NamePretifier();
}
#region Property checking
[Test]
public void FixtureSuffixGetSet()
{
Guid guid = Guid.NewGuid();
np.FixtureSuffix = guid.ToString();
Assert.AreEqual(guid.ToString(), np.FixtureSuffix);
}
[Test]
public void TestSuffixGetSet()
{
Guid guid = Guid.NewGuid();
np.TestSuffix = guid.ToString();
Assert.AreEqual(guid.ToString(), np.TestSuffix);
}
#endregion
#region Argument checking
[Test]
[ExpectedArgumentNullException]
public void PretifyNullFixtureName()
{
np.PretifyFixture(null);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void PretifyEmptyFixtureName()
{
np.PretifyFixture("");
}
[Test]
public void PretifySuffixOnlyFixtureName()
{
np.PretifyFixture("Test");
}
[Test]
[ExpectedArgumentNullException]
public void PretifyNullTestName()
{
np.PretifyTest(null);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void PretifyEmptyTestName()
{
np.PretifyTest(null);
}
[Test]
public void PretifySuffixTestName()
{
np.PretifyTest("Test");
}
#endregion
#region Capitalize
[Test]
public void PrefityFixtureName()
{
string pretty = np.PretifyFixture("Abcd");
Assert.AreEqual("Abcd", pretty);
}
[Test]
public void PrefityFixtureNameWithSuffix()
{
string pretty = np.PretifyFixture("AbcdTest");
Assert.AreEqual("Abcd", pretty);
}
[Test]
public void PrefityFixtureNameWithSuffixInside()
{
string pretty = np.PretifyFixture("AbcdTestHello");
Assert.AreEqual("AbcdTestHello", pretty);
}
[Test]
public void PrefityFixtureNameOfSize1()
{
string pretty = np.PretifyFixture("A");
Assert.AreEqual("A", pretty);
}
[Test]
public void PrefityFixtureNameOfSize2()
{
string pretty = np.PretifyFixture("Ab");
Assert.AreEqual("Ab", pretty);
}
[Test]
public void PretifyTestTest()
{
string value = "AaBbbbbCcccDdd";
string pretty = np.PretifyTest(value);
Assert.AreEqual("aa bbbbb cccc ddd",pretty);
}
[Test]
public void PretifyTestWithSuffix()
{
string value = "AaBbbbbCcccDddTest";
string pretty = np.PretifyTest(value);
Assert.AreEqual("aa bbbbb cccc ddd", pretty);
}
[Test]
public void PretifyTestWithSuffixInside()
{
string value = "AaBbbbbCcccDddTestHello";
string pretty = np.PretifyTest(value);
Assert.AreEqual("aa bbbbb cccc ddd test hello", pretty);
}
[Test]
public void PretifyTestWithSetUp()
{
string value = "SetUp.AaBbbbbCcccDddTest";
string pretty = np.PretifyTest(value);
Assert.AreEqual("aa bbbbb cccc ddd", pretty);
}
[Test]
public void PretifyTestWithTearDown()
{
string value = "SetUp.AaBbbbbCcccDddTest.TearDown";
string pretty = np.PretifyTest(value);
Assert.AreEqual("aa bbbbb cccc ddd", pretty);
}
#endregion
}
}
| {
"content_hash": "92a8983f7a71668fa839b55c83532a14",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 73,
"avg_line_length": 27.782894736842106,
"alnum_prop": 0.5349277764622307,
"repo_name": "Gallio/mbunit-v2",
"id": "636ef67acc23bac71e00f98cdc73a3113e233bb8",
"size": "4241",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/mbunit/MbUnit.Tests/Core/Reports/NamePretifierTest.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
[](https://travis-ci.org/joecorcoran/cities) [](https://codeclimate.com/github/joecorcoran/cities)
All the cities of the world (according to the periodically updated MaxMind database).
## Data
To use this gem, you'll need the JSON data.
Download it, extract it and connect it up as follows.
```
$ wget https://s3-us-west-2.amazonaws.com/cities-gem/cities.tar.gz
$ tar -xzf cities.tar.gz
```
```ruby
City.data_path = '/path/to/cities'
```
## Usage
Countries are identified by their [ISO 3166-1 alpha-2](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) codes.
```ruby
cities = City.cities_in_country('GB')
#=> { "abberley"=> #<City:0x000001049b9ba0>, "abberton"=> #<City:0x000001049b9b50>, ... }
mcr = cities['manchester']
#=> #<City:0x00000102fb4ea8>
mcr.name
#=> "Manchester"
mcr.population
#=> 395516
mcr.latlong
#=> [53,5, -2.216667]
```
The database is exhaustive and certainly stretches the definition of the word "city".
```ruby
City.cities_in_country('GB')['buchlyvie'].population
#=> 448
```
## Countries
This gem was designed as an extension to the [Countries gem](https://github.com/hexorx/countries). Installing Cities adds two new instance methods to the `Country` class.
```ruby
us = Country.search('US')
#=> #<Country:0x000001020cf5f0>
us.cities?
#=> true
us.cities
#=> { "abanda" => #<City:0x00000114b34a38>, ... }
```
## Credits
Provided under an MIT license by [Joe Corcoran](http://blog.joecorcoran.co.uk). Thanks to [hexorx](https://github.com/hexorx) for the countries gem that brought this idea about.
This product includes data created by MaxMind, available from [http://www.maxmind.com](http://www.maxmind.com). All data © 2008 MaxMind Inc. Read the [MaxMind WorldCities open data license](http://download.maxmind.com/download/geoip/database/LICENSE_WC.txt) for more details.
| {
"content_hash": "ccb602bb61d87d259e17cfe4b8119ba8",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 280,
"avg_line_length": 29.70149253731343,
"alnum_prop": 0.7130653266331658,
"repo_name": "asiniy/cities",
"id": "3849586204ee8273c5eef2aa776685141a013dcd",
"size": "2000",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "4596"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
{% include head.html %}
<!-- hack iOS CSS :active style -->
<body ontouchstart="">
{% include nav.html %}
{{ content }}
{% include footer.html %}
<!-- Image to hack wechat -->
<img src="/img/config/icon_wechat.png" width="0" height="0" />
<!-- Migrate from head to bottom, no longer block render and still work -->
<!-- back-to-top -->
<div id="back-top">
<a href="#section" data-toggle="tooltip" data-placement="top" title="top">
<i class="fa fa-chevron-up" aria-hidden="true"></i>
</a>
</div>
<!-- <script type="text/javascript" src="{{ site.BASE_PATH }}/assets/resources/jquery/jquery-1.8.3.js"></script> -->
<script>
$('#back-top').hide();
$(document).ready(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 250) {
$('#back-top').fadeIn();
} else {
$('#back-top').fadeOut();
}
});
$('#back-top a').click(function () {
$('body,html').animate({
scrollTop: 0
}, 800);
return false;
});
});
</script>
</body>
</html>
| {
"content_hash": "fa8964885d4603af170792cb7cfb0d2c",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 116,
"avg_line_length": 22.782608695652176,
"alnum_prop": 0.5658396946564885,
"repo_name": "comesome/comesome.github.io",
"id": "004d853216ba175e94539c5ef1d27afd69209b54",
"size": "1048",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "_layouts/default.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "54807"
},
{
"name": "HTML",
"bytes": "58904"
},
{
"name": "JavaScript",
"bytes": "21461"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<title>GSFileManager Demo</title>
<meta charset="UTF-8" />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<link rel="stylesheet" href="../src/gsFileManager.css"/>
<style type="text/css">
body {
height: 100%;
width: 100%;
}
html {
height: 100%;
width: 100%;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="../src/jquery.form.js"></script>
<script src="../src/gsFileManager.js"></script>
<script>
$(document).ready(function() {
jQuery('#fileTreeDemo_1').gsFileManager({ script: 'connector.php' });
});
</script>
</head>
<body>
<div id="fileTreeDemo_1" class="demoto"></div>
</body>
</html>
| {
"content_hash": "b2e5cfd0ae044817f2881017ae30161e",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 100,
"avg_line_length": 28.545454545454547,
"alnum_prop": 0.5753715498938429,
"repo_name": "schoettl/GSFileManager",
"id": "61560791122200135408f09af0649606337ea6f4",
"size": "942",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "demo/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8577"
},
{
"name": "JavaScript",
"bytes": "88106"
},
{
"name": "PHP",
"bytes": "25627"
}
],
"symlink_target": ""
} |
<?php
const ROOT = '../';
function load($input) {
$input = json_decode($input);
$file_name = ROOT . $input -> name;
$content = file_get_contents($file_name);
return $content;
}
$input = file_get_contents('php://input');
echo load($input);
?>
| {
"content_hash": "f1d7a50fb104f82537ed1de01685a6e6",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 43,
"avg_line_length": 19.76923076923077,
"alnum_prop": 0.5992217898832685,
"repo_name": "mazett/Tank-Game",
"id": "474153db5698464f1830ebb692506b2c315de857",
"size": "257",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "php/load.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "334"
},
{
"name": "HTML",
"bytes": "2510"
},
{
"name": "JavaScript",
"bytes": "47104"
},
{
"name": "PHP",
"bytes": "848"
}
],
"symlink_target": ""
} |
import { isUndefined } from 'lodash';
export default class Paginator {
page = 1;
itemsPerPage = 20;
totalCount = 0;
get totalPages() {
return Math.ceil(this.totalCount / this.itemsPerPage);
}
setPage(value, validate = true) {
if (isUndefined(value)) {
return;
}
value = parseInt(value, 10) || 1;
if (validate) {
this.page = ((value >= 1) && (value <= this.totalPages)) ? value : 1;
} else {
this.page = (value >= 1) ? value : 1;
}
}
setItemsPerPage(value, validate = true) {
if (isUndefined(value)) {
return;
}
value = parseInt(value, 10) || 20;
this.itemsPerPage = (value >= 1) ? value : 1;
if (validate) {
this.setPage(this.page, validate);
}
}
setTotalCount(value, validate = true) {
if (isUndefined(value)) {
return;
}
value = parseInt(value, 10) || 0;
this.totalCount = value;
if (validate) {
this.setPage(this.page, validate);
}
}
constructor({ page, itemsPerPage, totalCount, validate = true } = {}) {
this.setItemsPerPage(itemsPerPage, validate);
this.setTotalCount(totalCount, validate);
this.setPage(page, validate);
}
getItemsForPage(items) {
const first = this.itemsPerPage * (this.page - 1);
const last = first + this.itemsPerPage;
return items.slice(first, last);
}
}
| {
"content_hash": "fc0525c36e288446b35ac509ee50bc1f",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 75,
"avg_line_length": 22.733333333333334,
"alnum_prop": 0.5960410557184751,
"repo_name": "chriszs/redash",
"id": "a380be3f39f45bdf9da6d1d8f3f9ab442cb41dfc",
"size": "1364",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/app/components/items-list/classes/Paginator.js",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "370602"
},
{
"name": "HTML",
"bytes": "140434"
},
{
"name": "JavaScript",
"bytes": "301669"
},
{
"name": "Mako",
"bytes": "494"
},
{
"name": "Python",
"bytes": "727118"
},
{
"name": "Shell",
"bytes": "26552"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal partial class SymbolTreeInfo
{
private readonly VersionStamp _version;
/// <summary>
/// To prevent lots of allocations, we concatenate all the names in all our
/// Nodes into one long string. Each Node then just points at the span in
/// this string with the portion they care about.
/// </summary>
private readonly string _concatenatedNames;
/// <summary>
/// The list of nodes that represent symbols. The primary key into the sorting of this
/// list is the name. They are sorted case-insensitively with the <see cref="s_totalComparer" />.
/// Finding case-sensitive matches can be found by binary searching for something that
/// matches insensitively, and then searching around that equivalence class for one that
/// matches.
/// </summary>
private readonly ImmutableArray<Node> _nodes;
/// <summary>
/// Inheritance information for the types in this assembly. The mapping is between
/// a type's simple name (like 'IDictionary') and the simple metadata names of types
/// that implement it or derive from it (like 'Dictionary').
///
/// Note: to save space, all names in this map are stored with simple ints. These
/// ints are the indices into _nodes that contain the nodes with the appropriate name.
///
/// This mapping is only produced for metadata assemblies.
/// </summary>
private readonly OrderPreservingMultiDictionary<int, int> _inheritanceMap;
/// <summary>
/// The task that produces the spell checker we use for fuzzy match queries.
/// We use a task so that we can generate the <see cref="SymbolTreeInfo"/>
/// without having to wait for the spell checker construction to finish.
///
/// Features that don't need fuzzy matching don't want to incur the cost of
/// the creation of this value. And the only feature which does want fuzzy
/// matching (add-using) doesn't want to block waiting for the value to be
/// created.
/// </summary>
private readonly Task<SpellChecker> _spellCheckerTask;
private static readonly StringSliceComparer s_caseInsensitiveComparer =
StringSliceComparer.OrdinalIgnoreCase;
// We first sort in a case insensitive manner. But, within items that match insensitively,
// we then sort in a case sensitive manner. This helps for searching as we'll walk all
// the items of a specific casing at once. This way features can cache values for that
// casing and reuse them. i.e. if we didn't do this we might get "Prop, prop, Prop, prop"
// which might cause other features to continually recalculate if that string matches what
// they're searching for. However, with this sort of comparison we now get
// "prop, prop, Prop, Prop". Features can take advantage of that by caching their previous
// result and reusing it when they see they're getting the same string again.
private static readonly Comparison<string> s_totalComparer = (s1, s2) =>
{
var diff = CaseInsensitiveComparison.Comparer.Compare(s1, s2);
return diff != 0
? diff
: StringComparer.Ordinal.Compare(s1, s2);
};
private SymbolTreeInfo(
VersionStamp version,
string concatenatedNames,
Node[] sortedNodes,
Task<SpellChecker> spellCheckerTask,
OrderPreservingMultiDictionary<string, string> inheritanceMap)
: this(version, concatenatedNames, sortedNodes, spellCheckerTask)
{
var indexBasedInheritanceMap = CreateIndexBasedInheritanceMap(inheritanceMap);
_inheritanceMap = indexBasedInheritanceMap;
}
private SymbolTreeInfo(
VersionStamp version,
string concatenatedNames,
Node[] sortedNodes,
Task<SpellChecker> spellCheckerTask,
OrderPreservingMultiDictionary<int, int> inheritanceMap)
: this(version, concatenatedNames, sortedNodes, spellCheckerTask)
{
_inheritanceMap = inheritanceMap;
}
private SymbolTreeInfo(
VersionStamp version,
string concatenatedNames,
Node[] sortedNodes,
Task<SpellChecker> spellCheckerTask)
{
_version = version;
_concatenatedNames = concatenatedNames;
_nodes = ImmutableArray.Create(sortedNodes);
_spellCheckerTask = spellCheckerTask;
}
public Task<ImmutableArray<SymbolAndProjectId>> FindAsync(
SearchQuery query, IAssemblySymbol assembly, ProjectId assemblyProjectId, SymbolFilter filter, CancellationToken cancellationToken)
{
// All entrypoints to this function are Find functions that are only searching
// for specific strings (i.e. they never do a custom search).
Contract.ThrowIfTrue(query.Kind == SearchKind.Custom, "Custom queries are not supported in this API");
return this.FindAsync(
query, new AsyncLazy<IAssemblySymbol>(assembly),
assemblyProjectId, filter, cancellationToken);
}
public async Task<ImmutableArray<SymbolAndProjectId>> FindAsync(
SearchQuery query, AsyncLazy<IAssemblySymbol> lazyAssembly, ProjectId assemblyProjectId,
SymbolFilter filter, CancellationToken cancellationToken)
{
// All entrypoints to this function are Find functions that are only searching
// for specific strings (i.e. they never do a custom search).
Contract.ThrowIfTrue(query.Kind == SearchKind.Custom, "Custom queries are not supported in this API");
var symbols = await FindAsyncWorker(query, lazyAssembly, cancellationToken).ConfigureAwait(false);
return DeclarationFinder.FilterByCriteria(
symbols.SelectAsArray(s => new SymbolAndProjectId(s, assemblyProjectId)),
filter);
}
private Task<ImmutableArray<ISymbol>> FindAsyncWorker(
SearchQuery query, AsyncLazy<IAssemblySymbol> lazyAssembly, CancellationToken cancellationToken)
{
// All entrypoints to this function are Find functions that are only searching
// for specific strings (i.e. they never do a custom search).
Contract.ThrowIfTrue(query.Kind == SearchKind.Custom, "Custom queries are not supported in this API");
// If the query has a specific string provided, then call into the SymbolTreeInfo
// helpers optimized for lookup based on an exact name.
switch (query.Kind)
{
case SearchKind.Exact:
return this.FindAsync(lazyAssembly, query.Name, ignoreCase: false, cancellationToken: cancellationToken);
case SearchKind.ExactIgnoreCase:
return this.FindAsync(lazyAssembly, query.Name, ignoreCase: true, cancellationToken: cancellationToken);
case SearchKind.Fuzzy:
return this.FuzzyFindAsync(lazyAssembly, query.Name, cancellationToken);
}
throw new InvalidOperationException();
}
/// <summary>
/// Finds symbols in this assembly that match the provided name in a fuzzy manner.
/// </summary>
private async Task<ImmutableArray<ISymbol>> FuzzyFindAsync(
AsyncLazy<IAssemblySymbol> lazyAssembly, string name, CancellationToken cancellationToken)
{
if (_spellCheckerTask.Status != TaskStatus.RanToCompletion)
{
// Spell checker isn't ready. Just return immediately.
return ImmutableArray<ISymbol>.Empty;
}
var spellChecker = await _spellCheckerTask.ConfigureAwait(false);
var similarNames = spellChecker.FindSimilarWords(name, substringsAreSimilar: false);
var result = ArrayBuilder<ISymbol>.GetInstance();
foreach (var similarName in similarNames)
{
var symbols = await FindAsync(lazyAssembly, similarName, ignoreCase: true, cancellationToken: cancellationToken).ConfigureAwait(false);
result.AddRange(symbols);
}
return result.ToImmutableAndFree();
}
/// <summary>
/// Get all symbols that have a name matching the specified name.
/// </summary>
private async Task<ImmutableArray<ISymbol>> FindAsync(
AsyncLazy<IAssemblySymbol> lazyAssembly,
string name,
bool ignoreCase,
CancellationToken cancellationToken)
{
var comparer = GetComparer(ignoreCase);
var results = ArrayBuilder<ISymbol>.GetInstance();
IAssemblySymbol assemblySymbol = null;
foreach (var node in FindNodeIndices(name, comparer))
{
cancellationToken.ThrowIfCancellationRequested();
assemblySymbol = assemblySymbol ?? await lazyAssembly.GetValueAsync(cancellationToken).ConfigureAwait(false);
Bind(node, assemblySymbol.GlobalNamespace, results, cancellationToken);
}
return results.ToImmutableAndFree(); ;
}
private static StringSliceComparer GetComparer(bool ignoreCase)
{
return ignoreCase
? StringSliceComparer.OrdinalIgnoreCase
: StringSliceComparer.Ordinal;
}
/// <summary>
/// Gets all the node indices with matching names per the <paramref name="comparer" />.
/// </summary>
private IEnumerable<int> FindNodeIndices(
string name, StringSliceComparer comparer)
{
// find any node that matches case-insensitively
var startingPosition = BinarySearch(name);
var nameSlice = new StringSlice(name);
if (startingPosition != -1)
{
// yield if this matches by the actual given comparer
if (comparer.Equals(nameSlice, GetNameSlice(startingPosition)))
{
yield return startingPosition;
}
int position = startingPosition;
while (position > 0 && s_caseInsensitiveComparer.Equals(GetNameSlice(position - 1), nameSlice))
{
position--;
if (comparer.Equals(GetNameSlice(position), nameSlice))
{
yield return position;
}
}
position = startingPosition;
while (position + 1 < _nodes.Length && s_caseInsensitiveComparer.Equals(GetNameSlice(position + 1), nameSlice))
{
position++;
if (comparer.Equals(GetNameSlice(position), nameSlice))
{
yield return position;
}
}
}
}
private StringSlice GetNameSlice(int nodeIndex)
{
return new StringSlice(_concatenatedNames, _nodes[nodeIndex].NameSpan);
}
/// <summary>
/// Searches for a name in the ordered list that matches per the <see cref="s_caseInsensitiveComparer" />.
/// </summary>
private int BinarySearch(string name)
{
var nameSlice = new StringSlice(name);
int max = _nodes.Length - 1;
int min = 0;
while (max >= min)
{
int mid = min + ((max - min) >> 1);
var comparison = s_caseInsensitiveComparer.Compare(GetNameSlice(mid), nameSlice);
if (comparison < 0)
{
min = mid + 1;
}
else if (comparison > 0)
{
max = mid - 1;
}
else
{
return mid;
}
}
return -1;
}
#region Construction
// Cache the symbol tree infos for assembly symbols that share the same underlying metadata.
// Generating symbol trees for metadata can be expensive (in large metadata cases). And it's
// common for us to have many threads to want to search the same metadata simultaneously.
// As such, we want to only allow one thread to produce the tree for some piece of metadata
// at a time.
//
// AsyncLazy would normally be an ok choice here. However, in the case where all clients
// cancel their request, we don't want ot keep the AsyncLazy around. It may capture a lot
// of immutable state (like a Solution) that we don't want kept around indefinitely. So we
// only cache results (the symbol tree infos) if they successfully compute to completion.
private static readonly ConditionalWeakTable<MetadataId, SemaphoreSlim> s_metadataIdToGate = new ConditionalWeakTable<MetadataId, SemaphoreSlim>();
private static readonly ConditionalWeakTable<MetadataId, Task<SymbolTreeInfo>> s_metadataIdToInfo =
new ConditionalWeakTable<MetadataId, Task<SymbolTreeInfo>>();
private static readonly ConditionalWeakTable<MetadataId, SemaphoreSlim>.CreateValueCallback s_metadataIdToGateCallback =
_ => new SemaphoreSlim(1);
private static Task<SpellChecker> GetSpellCheckerTask(
Solution solution, VersionStamp version, string filePath,
string concatenatedNames, Node[] sortedNodes)
{
// Create a new task to attempt to load or create the spell checker for this
// SymbolTreeInfo. This way the SymbolTreeInfo will be ready immediately
// for non-fuzzy searches, and soon afterwards it will be able to perform
// fuzzy searches as well.
return Task.Run(() => LoadOrCreateSpellCheckerAsync(solution, filePath,
v => new SpellChecker(v, sortedNodes.Select(n => new StringSlice(concatenatedNames, n.NameSpan)))));
}
private static void SortNodes(
ImmutableArray<BuilderNode> unsortedNodes,
out string concatenatedNames,
out Node[] sortedNodes)
{
// Generate index numbers from 0 to Count-1
var tmp = new int[unsortedNodes.Length];
for (int i = 0; i < tmp.Length; i++)
{
tmp[i] = i;
}
// Sort the index according to node elements
Array.Sort<int>(tmp, (a, b) => CompareNodes(unsortedNodes[a], unsortedNodes[b], unsortedNodes));
// Use the sort order to build the ranking table which will
// be used as the map from original (unsorted) location to the
// sorted location.
var ranking = new int[unsortedNodes.Length];
for (int i = 0; i < tmp.Length; i++)
{
ranking[tmp[i]] = i;
}
// No longer need the tmp array
tmp = null;
var result = new Node[unsortedNodes.Length];
var concatenatedNamesBuilder = new StringBuilder();
string lastName = null;
// Copy nodes into the result array in the appropriate order and fixing
// up parent indexes as we go.
for (int i = 0; i < unsortedNodes.Length; i++)
{
var n = unsortedNodes[i];
var currentName = n.Name;
// Don't bother adding the exact same name the concatenated sequence
// over and over again. This can trivially happen because we'll run
// into the same names with different parents all through metadata
// and source symbols.
if (currentName != lastName)
{
concatenatedNamesBuilder.Append(currentName);
}
result[ranking[i]] = new Node(
new TextSpan(concatenatedNamesBuilder.Length - currentName.Length, currentName.Length),
n.IsRoot ? n.ParentIndex : ranking[n.ParentIndex]);
lastName = currentName;
}
sortedNodes = result;
concatenatedNames = concatenatedNamesBuilder.ToString();
}
private static int CompareNodes(
BuilderNode x, BuilderNode y, ImmutableArray<BuilderNode> nodeList)
{
var comp = s_totalComparer(x.Name, y.Name);
if (comp == 0)
{
if (x.ParentIndex != y.ParentIndex)
{
if (x.IsRoot)
{
return -1;
}
else if (y.IsRoot)
{
return 1;
}
else
{
return CompareNodes(nodeList[x.ParentIndex], nodeList[y.ParentIndex], nodeList);
}
}
}
return comp;
}
#endregion
#region Binding
// returns all the symbols in the container corresponding to the node
private void Bind(
int index, INamespaceOrTypeSymbol rootContainer, ArrayBuilder<ISymbol> results, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var node = _nodes[index];
if (node.IsRoot)
{
return;
}
if (_nodes[node.ParentIndex].IsRoot)
{
results.AddRange(rootContainer.GetMembers(GetName(node)));
}
else
{
var containerSymbols = ArrayBuilder<ISymbol>.GetInstance();
try
{
Bind(node.ParentIndex, rootContainer, containerSymbols, cancellationToken);
foreach (var containerSymbol in containerSymbols)
{
cancellationToken.ThrowIfCancellationRequested();
var nsOrType = containerSymbol as INamespaceOrTypeSymbol;
if (nsOrType != null)
{
results.AddRange(nsOrType.GetMembers(GetName(node)));
}
}
}
finally
{
containerSymbols.Free();
}
}
}
private string GetName(Node node)
{
// TODO(cyrusn): We could consider caching the strings we create in the
// Nodes themselves. i.e. we could have a field in the node where the
// string could be stored once created. The reason i'm not doing that now
// is because, in general, we shouldn't actually be allocating that many
// strings here. This data structure is not in a hot path, and does not
// have a usage pattern where may strings are accessed in it. Rather,
// some features generally use it to just see if they can find a symbol
// corresponding to a single name. As such, caching doesn't seem valuable.
return _concatenatedNames.Substring(node.NameSpan.Start, node.NameSpan.Length);
}
#endregion
internal void AssertEquivalentTo(SymbolTreeInfo other)
{
Debug.Assert(_version.Equals(other._version));
Debug.Assert(_concatenatedNames == other._concatenatedNames);
Debug.Assert(_nodes.Length == other._nodes.Length);
for (int i = 0, n = _nodes.Length; i < n; i++)
{
_nodes[i].AssertEquivalentTo(other._nodes[i]);
}
Debug.Assert(_inheritanceMap.Keys.Count == other._inheritanceMap.Keys.Count);
var orderedKeys1 = this._inheritanceMap.Keys.Order().ToList();
var orderedKeys2 = other._inheritanceMap.Keys.Order().ToList();
for (int i = 0; i < orderedKeys1.Count; i++)
{
var values1 = this._inheritanceMap[i];
var values2 = other._inheritanceMap[i];
Debug.Assert(values1.Length == values2.Length);
for (int j = 0; j < values1.Length; j++)
{
Debug.Assert(values1[j] == values2[j]);
}
}
}
private static SymbolTreeInfo CreateSymbolTreeInfo(
Solution solution, VersionStamp version,
string filePath, ImmutableArray<BuilderNode> unsortedNodes,
OrderPreservingMultiDictionary<string, string> inheritanceMap)
{
SortNodes(unsortedNodes, out var concatenatedNames, out var sortedNodes);
var createSpellCheckerTask = GetSpellCheckerTask(
solution, version, filePath, concatenatedNames, sortedNodes);
return new SymbolTreeInfo(
version, concatenatedNames, sortedNodes, createSpellCheckerTask, inheritanceMap);
}
private OrderPreservingMultiDictionary<int, int> CreateIndexBasedInheritanceMap(
OrderPreservingMultiDictionary<string, string> inheritanceMap)
{
// All names in metadata will be case sensitive.
var comparer = GetComparer(ignoreCase: false);
var result = new OrderPreservingMultiDictionary<int, int>();
foreach (var kvp in inheritanceMap)
{
var baseName = kvp.Key;
var baseNameIndex = BinarySearch(baseName);
Debug.Assert(baseNameIndex >= 0);
foreach (var derivedName in kvp.Value)
{
foreach (var derivedNameIndex in FindNodeIndices(derivedName, comparer))
{
result.Add(baseNameIndex, derivedNameIndex);
}
}
}
return result;
}
public ImmutableArray<INamedTypeSymbol> GetDerivedMetadataTypes(
string baseTypeName, Compilation compilation, CancellationToken cancellationToken)
{
var baseTypeNameIndex = BinarySearch(baseTypeName);
var derivedTypeIndices = _inheritanceMap[baseTypeNameIndex];
var builder = ArrayBuilder<INamedTypeSymbol>.GetInstance();
foreach (var derivedTypeIndex in derivedTypeIndices)
{
var tempBuilder = ArrayBuilder<ISymbol>.GetInstance();
try
{
Bind(derivedTypeIndex, compilation.GlobalNamespace, tempBuilder, cancellationToken);
foreach (var symbol in tempBuilder)
{
var namedType = symbol as INamedTypeSymbol;
if (namedType != null)
{
builder.Add(namedType);
}
}
}
finally
{
tempBuilder.Free();
}
}
return builder.ToImmutableAndFree();
}
}
} | {
"content_hash": "427496f6622f858ed1a1fb2ac94b5ae7",
"timestamp": "",
"source": "github",
"line_count": 571,
"max_line_length": 161,
"avg_line_length": 42.46584938704028,
"alnum_prop": 0.5840894094358298,
"repo_name": "zooba/roslyn",
"id": "0e8daa8c9ad1bbe46bc928f305154212bd1edb0c",
"size": "24250",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "1C Enterprise",
"bytes": "289100"
},
{
"name": "Batchfile",
"bytes": "10490"
},
{
"name": "C#",
"bytes": "93850864"
},
{
"name": "C++",
"bytes": "5392"
},
{
"name": "F#",
"bytes": "3632"
},
{
"name": "Groovy",
"bytes": "10141"
},
{
"name": "Makefile",
"bytes": "3294"
},
{
"name": "PowerShell",
"bytes": "104698"
},
{
"name": "Shell",
"bytes": "8363"
},
{
"name": "Visual Basic",
"bytes": "72726084"
}
],
"symlink_target": ""
} |
package calc
import "github.com/emicklei/melrose/core"
func resolveInt(v interface{}) (int, bool) {
if i, ok := v.(int); ok {
return i, true
}
if v, ok := v.(core.HasValue); ok {
return resolveInt(v.Value())
}
return 0, false
}
func resolveFloat(v interface{}) (float64, bool) {
if i, ok := v.(float64); ok {
return i, true
}
if v, ok := v.(core.HasValue); ok {
return resolveFloat(v.Value())
}
return 0.0, false
}
| {
"content_hash": "285d2c6a3f8c0fd59a14af35e74638bf",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 50,
"avg_line_length": 18.956521739130434,
"alnum_prop": 0.6238532110091743,
"repo_name": "emicklei/melrose",
"id": "18c8f224a9dbf17df312a023c413d73404435aa2",
"size": "436",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dsl/calc/util.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "383885"
},
{
"name": "Makefile",
"bytes": "599"
}
],
"symlink_target": ""
} |
using namespace std;
class Infirmary : public Building
{
public:
Location Site;
public:
Infirmary::Infirmary(int x, int y);
void Print();
void PrintAssignment();
vector<Supply*> TakeSupplies();
};
#endif | {
"content_hash": "3841aa82c83454ab567227625ae275f5",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 36,
"avg_line_length": 16.076923076923077,
"alnum_prop": 0.7272727272727273,
"repo_name": "cobbie/obj-2.0",
"id": "4a011eef7a3e8fc52012fe44d6b6cc4eb468e836",
"size": "405",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ProjektBazy/ProjektBazy/Infirmary.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "15814"
}
],
"symlink_target": ""
} |
package com.smallchill.web.controller;
import com.smallchill.common.base.BaseController;
import com.smallchill.common.pay.util.TimeUtil;
import com.smallchill.core.interfaces.ILoader;
import com.smallchill.core.plugins.dao.Db;
import com.smallchill.core.toolbox.Record;
import com.smallchill.core.toolbox.ajax.AjaxResult;
import com.smallchill.core.toolbox.grid.JqGrid;
import com.smallchill.core.toolbox.kit.CacheKit;
import com.smallchill.core.toolbox.kit.DateTimeKit;
import com.smallchill.core.toolbox.support.BladePage;
import com.smallchill.web.meta.intercept.GroupIntercept;
import com.smallchill.web.meta.intercept.OrderIntercept;
import com.smallchill.web.model.GroupExtend;
import com.smallchill.web.model.Trading;
import com.smallchill.web.service.TradingService;
import org.beetl.sql.core.kit.CaseInsensitiveHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* 交易流水-交易
* Created by Administrator on 2016/11/15.
*/
@Controller
@RequestMapping(value = "/trading")
public class TradingController extends BaseController {
private static String CODE = "trading";
private static String LIST_SOURCE = "Order.groupOrderList";
private static String BASE_PATH = "/web/trading/";
@Autowired
TradingService tradingService;
@RequestMapping(KEY_MAIN)
public String index(ModelMap mm) {
mm.put("code", CODE);
return BASE_PATH + "trading_list.html";
}
@ResponseBody
@RequestMapping(KEY_LIST)
public Object list() {
Object grid = paginate(LIST_SOURCE);
return grid;
}
@RequestMapping(value = "/trend_chart")
public String trendChart(ModelMap mm) {
mm.put("code", CODE);
return BASE_PATH + "trend_chart.html";
}
@RequestMapping(value = "/yearMonth")
@ResponseBody
public List yearMonth(String val,Integer type){
Map<String,Object> map = new TreeMap<>();
List list = new ArrayList();
try{
list = tradingService.yearMonth(val,type);
}catch (RuntimeException e){
e.printStackTrace();
}
return list;
}
@RequestMapping(value = "/day")
@ResponseBody
public List day(Long val){
List list = new ArrayList();
try{
list = tradingService.day(val);
}catch (RuntimeException e){
e.printStackTrace();
}
return list;
}
@RequestMapping(value = "/scope")
@ResponseBody
public AjaxResult scope(Integer type){
StringBuilder sb = new StringBuilder();
try{
if(type==null){
sb.append("<select class=\"form-control\" style=\"margin:0 10px 0 -3px;cursor:pointer;width:auto;\" id=\"scope_list\">");
sb.append("<option value></option>");
sb.append("</select>");
}
else if(type==1){ //年
String sql = "SELECT\n" +
" DATE_FORMAT(FROM_UNIXTIME(create_time / 1000),'%Y') t\n" +
"FROM\n" +
" tb_order\n" +
" WHERE flow = '1' \n" +
" GROUP BY t \n" +
" ORDER BY t";
List<Record> list = Db.init().selectList(sql);
sb.append("<select class=\"form-control\" style=\"margin:0 10px 0 -3px;cursor:pointer;width:auto;\" id=\"scope_list\" onchange=\"yearMonth(this,'1')\"> ");
sb.append("<option value></option>");
for(Record record:list){
sb.append("<option value=\"" + record.get("t") + "\">" + record.get("t") + "</option>");
}
sb.append("</select>");
}
else if(type==2){ //月
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
long lcc_time = Long.valueOf(DateTimeKit.nowLong());
String re_StrTime = sdf.format(new Date(lcc_time));
sb.append("<select class=\"form-control\" style=\"margin:0 10px 0 -3px;cursor:pointer;width:auto;\" id=\"scope_list\" onchange=\"yearMonth(this,'2')\" >");
sb.append("<option value></option>");
for (int i=1;i<13;i++) {
String y="";
if(i<10){
y = "0";
}
sb.append("<option value=\"" +re_StrTime+"-"+ y + i + "\">" + i + "</option>");
}
sb.append("</select>");
}
else if(type==3){ //日
sb.append("<select class=\"form-control\" style=\"margin:0 10px 0 -3px;cursor:pointer;width:auto;\" id=\"scope_list\" onchange=\"yearMonth(this,'3')\" >");
sb.append("<option value></option>");
sb.append("<option value=\"7\">7天</option>");
sb.append("<option value=\"14\">14天</option>");
sb.append("<option value=\"30\">30天</option>");
sb.append("</select>");
}
}catch (RuntimeException e){
e.printStackTrace();
}
return json(sb.toString());
}
}
| {
"content_hash": "878bc7b5f66db5f95c1e7a1dc857f7da",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 171,
"avg_line_length": 37.77777777777778,
"alnum_prop": 0.5744485294117647,
"repo_name": "ys305751572/shouye",
"id": "0aaad4644d928b171cac9e8d21099f0211c91de0",
"size": "5464",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/smallchill/web/controller/TradingController.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1669031"
},
{
"name": "HTML",
"bytes": "643757"
},
{
"name": "Java",
"bytes": "1831571"
},
{
"name": "JavaScript",
"bytes": "6437446"
}
],
"symlink_target": ""
} |
- locale parameter now defaults to [NSLocale autoupdatingCurrentLocale]
- Added example project to enable 'pod try' command and Travis CI
## 1.0
###### Enhancements
- Adjust address formatting by use of locale property
- Ability to pass address components and receive formatted address output | {
"content_hash": "6d7487fb5adb045bb85bd6405690db82",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 73,
"avg_line_length": 32.77777777777778,
"alnum_prop": 0.7864406779661017,
"repo_name": "damienpontifex/DMAddressFormatter",
"id": "c3bb8df2fc81ac75886da61417ead50c1ed22cf6",
"size": "326",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CHANGELOG.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "11583"
},
{
"name": "Ruby",
"bytes": "734"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
Brassica bivoniana Mazzola & Raimondo
### Remarks
null | {
"content_hash": "15409fbe10088295bf800e3ccd03a512",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 37,
"avg_line_length": 12.23076923076923,
"alnum_prop": 0.7358490566037735,
"repo_name": "mdoering/backbone",
"id": "383f3ce534e810de4f465010ea92de4c71cd6d40",
"size": "261",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Brassica/Brassica villosa/Brassica villosa bivoniana/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
@interface PasswordAddonCell : KMTableViewCell
@property (nonatomic, strong) IBOutlet UILabel *addonLabel;
@property (nonatomic, strong) IBOutlet UISwitch *passwordSwitch;
@end
| {
"content_hash": "c4d52f4095eb79693483d880576a589f",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 64,
"avg_line_length": 29.833333333333332,
"alnum_prop": 0.8100558659217877,
"repo_name": "1box/onedayapp",
"id": "4dee2fd594c9f27b891b51d4574361f2e1219480",
"size": "344",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OneDay/OneBase/view/PasswordAddonCell.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "952"
},
{
"name": "CSS",
"bytes": "6448"
},
{
"name": "HTML",
"bytes": "42235"
},
{
"name": "JavaScript",
"bytes": "5914"
},
{
"name": "Objective-C",
"bytes": "769619"
},
{
"name": "Shell",
"bytes": "2739"
}
],
"symlink_target": ""
} |
This is an example dummy module, It is built and loaded, but has a minimal performance impact.
| {
"content_hash": "eac808270bea812efcfc33368d543118",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 94,
"avg_line_length": 95,
"alnum_prop": 0.7894736842105263,
"repo_name": "XAMPP/Celty",
"id": "a841803bffc9b320e722ea9fca4eaeb98a7264bf",
"size": "110",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/dummy/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "32180"
},
{
"name": "CMake",
"bytes": "16973"
},
{
"name": "Shell",
"bytes": "1444"
}
],
"symlink_target": ""
} |
saw-las
=======
Installs NOAA's [LAS](http://ferret.pmel.noaa.gov/LAS) web-based visualisation tool
Usage
-----
### Class las
```Puppet
class {'las':
las_title => 'LAS' # Title to add to web pages
proxy_fqdn => $::fqdn # Reverse proxy FQDN
tomcat_fqdn => $::fqdn # Tomcat server FQDN
tomcat_port => '8080' # Tomcat port
tomcat_user => 'tomcat' # Tomcat user
catalina_home => '/usr/share/tomcat6' # Tomcat home directory
manage_dependencies => false # Install all dependencies
}
```
### Dependencies
* [puppetlabs-stdlib](https://forge.puppetlabs.com/puppetlabs/stdlib)
* [puppetlabs-java](https://forge.puppetlabs.com/puppetlabs/java)
* [nanliu-staging](https://forge.puppetlabs.com/nanliu/staging)
* [saw-ferret](https://forge.puppetlabs.com/saw/ferret)
Developing
----------
The development tools make use of [bundler](http://bundler.io/)
Install development libraries with
bundle config build.nokogiri --use-system-libraries
bundle install --path vendor
Run unit tests with
bundle exec rake spec
Run integration tests on a Vagrant VM with
bundle exec rake acceptance
See the [Beaker workflow
documentation](https://github.com/puppetlabs/beaker/wiki/How-to-Write-a-Beaker-Test-for-a-Module#typical-workflow)
for how to re-use the test VM.
| {
"content_hash": "40fd047ae4fb0cae770fa341eef3b8d4",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 114,
"avg_line_length": 28.34,
"alnum_prop": 0.6492589978828511,
"repo_name": "coecms/climate-cms",
"id": "5f3cca8d91aa42cc09cc66cc558a3b58b2a04a59",
"size": "1417",
"binary": false,
"copies": "1",
"ref": "refs/heads/production",
"path": "local/las/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "4627"
},
{
"name": "Perl",
"bytes": "8715"
},
{
"name": "Puppet",
"bytes": "151146"
},
{
"name": "Ruby",
"bytes": "24331"
},
{
"name": "Shell",
"bytes": "5899"
}
],
"symlink_target": ""
} |
package com.coolweather.app.model;
/**
* 省份
* Created by xiaof_000 on 2015/4/6.
*/
public class Province {
private int id;
private String name;
private String code;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
| {
"content_hash": "b4d17830f74f376b8e28189bf112cd2f",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 38,
"avg_line_length": 15.857142857142858,
"alnum_prop": 0.5531531531531532,
"repo_name": "xiaofeiluo/coolweather",
"id": "ca712fbe62415be97483a4e4e5b2aa72265109d7",
"size": "559",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/coolweather/app/model/Province.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "32236"
}
],
"symlink_target": ""
} |
import json
import struct
import re
import base64
import httplib
import sys
ERR_SLEEP = 15
MAX_NONCE = 1000000L
settings = {}
class CatchcoinRPC:
OBJID = 1
def __init__(self, host, port, username, password):
authpair = "%s:%s" % (username, password)
self.authhdr = "Basic %s" % (base64.b64encode(authpair))
self.conn = httplib.HTTPConnection(host, port, False, 30)
def rpc(self, method, params=None):
self.OBJID += 1
obj = { 'version' : '1.1',
'method' : method,
'id' : self.OBJID }
if params is None:
obj['params'] = []
else:
obj['params'] = params
self.conn.request('POST', '/', json.dumps(obj),
{ 'Authorization' : self.authhdr,
'Content-type' : 'application/json' })
resp = self.conn.getresponse()
if resp is None:
print "JSON-RPC: no response"
return None
body = resp.read()
resp_obj = json.loads(body)
if resp_obj is None:
print "JSON-RPC: cannot JSON-decode body"
return None
if 'error' in resp_obj and resp_obj['error'] != None:
return resp_obj['error']
if 'result' not in resp_obj:
print "JSON-RPC: no result in object"
return None
return resp_obj['result']
def getblock(self, hash, verbose=True):
return self.rpc('getblock', [hash, verbose])
def getblockhash(self, index):
return self.rpc('getblockhash', [index])
def getblock(rpc, settings, n):
hash = rpc.getblockhash(n)
hexdata = rpc.getblock(hash, False)
data = hexdata.decode('hex')
return data
def get_blocks(settings):
rpc = CatchcoinRPC(settings['host'], settings['port'],
settings['rpcuser'], settings['rpcpassword'])
outf = open(settings['output'], 'ab')
for height in xrange(settings['min_height'], settings['max_height']+1):
data = getblock(rpc, settings, height)
outhdr = settings['netmagic']
outhdr += struct.pack("<i", len(data))
outf.write(outhdr)
outf.write(data)
if (height % 1000) == 0:
sys.stdout.write("Wrote block " + str(height) + "\n")
if __name__ == '__main__':
if len(sys.argv) != 2:
print "Usage: linearize.py CONFIG-FILE"
sys.exit(1)
f = open(sys.argv[1])
for line in f:
# skip comment lines
m = re.search('^\s*#', line)
if m:
continue
# parse key=value lines
m = re.search('^(\w+)\s*=\s*(\S.*)$', line)
if m is None:
continue
settings[m.group(1)] = m.group(2)
f.close()
if 'netmagic' not in settings:
settings['netmagic'] = 'f9beb4d9'
if 'output' not in settings:
settings['output'] = 'bootstrap.dat'
if 'host' not in settings:
settings['host'] = '127.0.0.1'
if 'port' not in settings:
settings['port'] = 8332
if 'min_height' not in settings:
settings['min_height'] = 0
if 'max_height' not in settings:
settings['max_height'] = 279000
if 'rpcuser' not in settings or 'rpcpassword' not in settings:
print "Missing username and/or password in cfg file"
sys.exit(1)
settings['netmagic'] = settings['netmagic'].decode('hex')
settings['port'] = int(settings['port'])
settings['min_height'] = int(settings['min_height'])
settings['max_height'] = int(settings['max_height'])
get_blocks(settings)
| {
"content_hash": "94ecee4e549f66e349e4e370745e9c37",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 72,
"avg_line_length": 25.12295081967213,
"alnum_prop": 0.6522022838499184,
"repo_name": "tinybike/catchcoin",
"id": "cc3366f8f36acfcc1b4963378f4104b1b0efd3af",
"size": "3388",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "contrib/linearize/linearize.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "301826"
},
{
"name": "C++",
"bytes": "2879017"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Objective-C++",
"bytes": "6266"
},
{
"name": "Python",
"bytes": "95592"
},
{
"name": "Shell",
"bytes": "40370"
},
{
"name": "TypeScript",
"bytes": "10322619"
}
],
"symlink_target": ""
} |
package apple.foundation;
import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.uikit.*;
import apple.coreanimation.*;
import apple.coredata.*;
import apple.coremedia.*;
import apple.security.*;
import apple.dispatch.*;
@Library("Foundation/Foundation.h") @Mapping("NSFileManagerDelegate")
public interface NSFileManagerDelegate
extends NSObjectProtocol {
@Mapping("fileManager:shouldCopyItemAtPath:toPath:")
boolean shouldCopyItemAtPath(NSFileManager fileManager, String srcPath, String dstPath);
/**
* @since Available in iOS 4.0 and later.
*/
@Mapping("fileManager:shouldCopyItemAtURL:toURL:")
boolean shouldCopyItemAtURL(NSFileManager fileManager, NSURL srcURL, NSURL dstURL);
@Mapping("fileManager:shouldProceedAfterError:copyingItemAtPath:toPath:")
boolean shouldProceedCopyingItemAtPath(NSFileManager fileManager, NSError error, String srcPath, String dstPath);
/**
* @since Available in iOS 4.0 and later.
*/
@Mapping("fileManager:shouldProceedAfterError:copyingItemAtURL:toURL:")
boolean shouldProceedCopyingItemAtURL(NSFileManager fileManager, NSError error, NSURL srcURL, NSURL dstURL);
@Mapping("fileManager:shouldMoveItemAtPath:toPath:")
boolean shouldMoveItemAtPath(NSFileManager fileManager, String srcPath, String dstPath);
/**
* @since Available in iOS 4.0 and later.
*/
@Mapping("fileManager:shouldMoveItemAtURL:toURL:")
boolean shouldMoveItemAtURL(NSFileManager fileManager, NSURL srcURL, NSURL dstURL);
@Mapping("fileManager:shouldProceedAfterError:movingItemAtPath:toPath:")
boolean shouldProceedMovingItemAtPath(NSFileManager fileManager, NSError error, String srcPath, String dstPath);
/**
* @since Available in iOS 4.0 and later.
*/
@Mapping("fileManager:shouldProceedAfterError:movingItemAtURL:toURL:")
boolean shouldProceedMovingItemAtURL(NSFileManager fileManager, NSError error, NSURL srcURL, NSURL dstURL);
@Mapping("fileManager:shouldLinkItemAtPath:toPath:")
boolean shouldLinkItemAtPath(NSFileManager fileManager, String srcPath, String dstPath);
/**
* @since Available in iOS 4.0 and later.
*/
@Mapping("fileManager:shouldLinkItemAtURL:toURL:")
boolean shouldLinkItemAtURL(NSFileManager fileManager, NSURL srcURL, NSURL dstURL);
@Mapping("fileManager:shouldProceedAfterError:linkingItemAtPath:toPath:")
boolean shouldProceedLinkingItemAtPath(NSFileManager fileManager, NSError error, String srcPath, String dstPath);
/**
* @since Available in iOS 4.0 and later.
*/
@Mapping("fileManager:shouldProceedAfterError:linkingItemAtURL:toURL:")
boolean shouldProceedLinkingItemAtURL(NSFileManager fileManager, NSError error, NSURL srcURL, NSURL dstURL);
@Mapping("fileManager:shouldRemoveItemAtPath:")
boolean shouldRemoveItemAtPath(NSFileManager fileManager, String path);
/**
* @since Available in iOS 4.0 and later.
*/
@Mapping("fileManager:shouldRemoveItemAtURL:")
boolean shouldRemoveItemAtURL(NSFileManager fileManager, NSURL URL);
@Mapping("fileManager:shouldProceedAfterError:removingItemAtPath:")
boolean shouldProceedRemovingItemAtPath(NSFileManager fileManager, NSError error, String path);
/**
* @since Available in iOS 4.0 and later.
*/
@Mapping("fileManager:shouldProceedAfterError:removingItemAtURL:")
boolean shouldProceedRemovingItemAtURL(NSFileManager fileManager, NSError error, NSURL URL);
/*<adapter>*/
/*</adapter>*/
}
| {
"content_hash": "5812a2210951443d7e3da7d6179bd6f5",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 117,
"avg_line_length": 42.144444444444446,
"alnum_prop": 0.7561297126285262,
"repo_name": "Sellegit/j2objc",
"id": "b94a04ffd4e5d57d3029a1d3253451f125a42095",
"size": "3793",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "runtime/src/main/java/apple/foundation/NSFileManagerDelegate.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "1103"
},
{
"name": "C",
"bytes": "561283"
},
{
"name": "C++",
"bytes": "93021"
},
{
"name": "Java",
"bytes": "27971072"
},
{
"name": "Makefile",
"bytes": "184549"
},
{
"name": "Objective-C",
"bytes": "570829"
},
{
"name": "Python",
"bytes": "798"
},
{
"name": "Shell",
"bytes": "6921"
}
],
"symlink_target": ""
} |
/*
This is an optimized version of Dojo, built for deployment and not for
development. To get sources and documentation, please visit:
http://dojotoolkit.org
*/
//>>built
require({cache:{
'dojox/charting/plot2d/_PlotEvents':function(){
define("dojox/charting/plot2d/_PlotEvents", ["dojo/_base/lang", "dojo/_base/array", "dojo/_base/declare", "dojo/_base/connect"],
function(lang, arr, declare, hub){
return declare("dojox.charting.plot2d._PlotEvents", null, {
constructor: function(){
this._shapeEvents = [];
this._eventSeries = {};
},
destroy: function(){
// summary:
// Destroy any internal elements and event handlers.
this.resetEvents();
this.inherited(arguments);
},
plotEvent: function(o){
// summary:
// Stub function for use by specific plots.
// o: Object
// An object intended to represent event parameters.
},
raiseEvent: function(o){
// summary:
// Raises events in predefined order
// o: Object
// An object intended to represent event parameters.
this.plotEvent(o);
var t = lang.delegate(o);
t.originalEvent = o.type;
t.originalPlot = o.plot;
t.type = "onindirect";
arr.forEach(this.chart.stack, function(plot){
if(plot !== this && plot.plotEvent){
t.plot = plot;
plot.plotEvent(t);
}
}, this);
},
connect: function(object, method){
// summary:
// Helper function to connect any object's method to our plotEvent.
// object: Object
// The object to connect to.
// method: String|Function
// The method to fire when our plotEvent is fired.
// returns: Array
// The handle as returned from dojo.connect (see dojo.connect).
this.dirty = true;
return hub.connect(this, "plotEvent", object, method); // Array
},
events: function(){
// summary:
// Find out if any event handlers have been connected to our plotEvent.
// returns: Boolean
// A flag indicating that there are handlers attached.
return !!this.plotEvent.after;
},
resetEvents: function(){
// summary:
// Reset all events attached to our plotEvent (i.e. disconnect).
if(this._shapeEvents.length){
arr.forEach(this._shapeEvents, function(item){
item.shape.disconnect(item.handle);
});
this._shapeEvents = [];
}
this.raiseEvent({type: "onplotreset", plot: this});
},
_connectSingleEvent: function(o, eventName){
this._shapeEvents.push({
shape: o.eventMask,
handle: o.eventMask.connect(eventName, this, function(e){
o.type = eventName;
o.event = e;
this.raiseEvent(o);
o.event = null;
})
});
},
_connectEvents: function(o){
if(o){
o.chart = this.chart;
o.plot = this;
o.hAxis = this.hAxis || null;
o.vAxis = this.vAxis || null;
o.eventMask = o.eventMask || o.shape;
this._connectSingleEvent(o, "onmouseover");
this._connectSingleEvent(o, "onmouseout");
this._connectSingleEvent(o, "onclick");
}
},
_reconnectEvents: function(seriesName){
var a = this._eventSeries[seriesName];
if(a){
arr.forEach(a, this._connectEvents, this);
}
},
fireEvent: function(seriesName, eventName, index, eventObject){
// summary:
// Emulates firing an event for a given data value (specified by
// an index) of a given series.
// seriesName: String:
// Series name.
// eventName: String:
// Event name to emulate.
// index: Number:
// Valid data value index used to raise an event.
// eventObject: Object?:
// Optional event object. Especially useful for synthetic events.
// Default: null.
var s = this._eventSeries[seriesName];
if(s && s.length && index < s.length){
var o = s[index];
o.type = eventName;
o.event = eventObject || null;
this.raiseEvent(o);
o.event = null;
}
}
});
});
},
'dojo/uacss':function(){
define(["./dom-geometry", "./_base/lang", "./ready", "./_base/sniff", "./_base/window"],
function(geometry, lang, ready, has, baseWindow){
// module:
// dojo/uacss
// summary:
// Applies pre-set CSS classes to the top-level HTML node, based on:
// - browser (ex: dj_ie)
// - browser version (ex: dj_ie6)
// - box model (ex: dj_contentBox)
// - text direction (ex: dijitRtl)
//
// In addition, browser, browser version, and box model are
// combined with an RTL flag when browser text is RTL. ex: dj_ie-rtl.
var
html = baseWindow.doc.documentElement,
ie = has("ie"),
opera = has("opera"),
maj = Math.floor,
ff = has("ff"),
boxModel = geometry.boxModel.replace(/-/,''),
classes = {
"dj_ie": ie,
"dj_ie6": maj(ie) == 6,
"dj_ie7": maj(ie) == 7,
"dj_ie8": maj(ie) == 8,
"dj_ie9": maj(ie) == 9,
"dj_quirks": has("quirks"),
"dj_iequirks": ie && has("quirks"),
// NOTE: Opera not supported by dijit
"dj_opera": opera,
"dj_khtml": has("khtml"),
"dj_webkit": has("webkit"),
"dj_safari": has("safari"),
"dj_chrome": has("chrome"),
"dj_gecko": has("mozilla"),
"dj_ff3": maj(ff) == 3
}; // no dojo unsupported browsers
classes["dj_" + boxModel] = true;
// apply browser, browser version, and box model class names
var classStr = "";
for(var clz in classes){
if(classes[clz]){
classStr += clz + " ";
}
}
html.className = lang.trim(html.className + " " + classStr);
// If RTL mode, then add dj_rtl flag plus repeat existing classes with -rtl extension.
// We can't run the code below until the <body> tag has loaded (so we can check for dir=rtl).
// priority is 90 to run ahead of parser priority of 100
ready(90, function(){
if(!geometry.isBodyLtr()){
var rtlClassStr = "dj_rtl dijitRtl " + classStr.replace(/ /g, "-rtl ");
html.className = lang.trim(html.className + " " + rtlClassStr + "dj_rtl dijitRtl " + classStr.replace(/ /g, "-rtl "));
}
});
return has;
});
},
'dojox/charting/axis2d/Invisible':function(){
define(["dojo/_base/lang", "dojo/_base/declare", "./Base", "../scaler/linear",
"dojox/gfx", "dojox/lang/utils", "dojox/lang/functional", "dojo/string"],
function(lang, declare, Base, lin, g, du, df, dstring){
/*=====
var Base = dojox.charting.axis2d.Base;
=====*/
var merge = du.merge,
labelGap = 4, // in pixels
centerAnchorLimit = 45; // in degrees
return declare("dojox.charting.axis2d.Invisible", Base, {
// summary:
// The default axis object used in dojox.charting. See dojox.charting.Chart.addAxis for details.
//
// defaultParams: Object
// The default parameters used to define any axis.
// optionalParams: Object
// Any optional parameters needed to define an axis.
/*
// TODO: the documentation tools need these to be pre-defined in order to pick them up
// correctly, but the code here is partially predicated on whether or not the properties
// actually exist. For now, we will leave these undocumented but in the code for later. -- TRT
// opt: Object
// The actual options used to define this axis, created at initialization.
// scalar: Object
// The calculated helper object to tell charts how to draw an axis and any data.
// ticks: Object
// The calculated tick object that helps a chart draw the scaling on an axis.
// dirty: Boolean
// The state of the axis (whether it needs to be redrawn or not)
// scale: Number
// The current scale of the axis.
// offset: Number
// The current offset of the axis.
opt: null,
scalar: null,
ticks: null,
dirty: true,
scale: 1,
offset: 0,
*/
defaultParams: {
vertical: false, // true for vertical axis
fixUpper: "none", // align the upper on ticks: "major", "minor", "micro", "none"
fixLower: "none", // align the lower on ticks: "major", "minor", "micro", "none"
natural: false, // all tick marks should be made on natural numbers
leftBottom: true, // position of the axis, used with "vertical"
includeZero: false, // 0 should be included
fixed: true, // all labels are fixed numbers
majorLabels: true, // draw major labels
minorTicks: true, // draw minor ticks
minorLabels: true, // draw minor labels
microTicks: false, // draw micro ticks
rotation: 0 // label rotation angle in degrees
},
optionalParams: {
min: 0, // minimal value on this axis
max: 1, // maximal value on this axis
from: 0, // visible from this value
to: 1, // visible to this value
majorTickStep: 4, // major tick step
minorTickStep: 2, // minor tick step
microTickStep: 1, // micro tick step
labels: [], // array of labels for major ticks
// with corresponding numeric values
// ordered by values
labelFunc: null, // function to compute label values
maxLabelSize: 0, // size in px. For use with labelFunc
maxLabelCharCount: 0, // size in word count.
trailingSymbol: null
// TODO: add support for minRange!
// minRange: 1, // smallest distance from min allowed on the axis
},
constructor: function(chart, kwArgs){
// summary:
// The constructor for an axis.
// chart: dojox.charting.Chart
// The chart the axis belongs to.
// kwArgs: dojox.charting.axis2d.__AxisCtorArgs?
// Any optional keyword arguments to be used to define this axis.
this.opt = lang.clone(this.defaultParams);
du.updateWithObject(this.opt, kwArgs);
du.updateWithPattern(this.opt, kwArgs, this.optionalParams);
},
dependOnData: function(){
// summary:
// Find out whether or not the axis options depend on the data in the axis.
return !("min" in this.opt) || !("max" in this.opt); // Boolean
},
clear: function(){
// summary:
// Clear out all calculated properties on this axis;
// returns: dojox.charting.axis2d.Default
// The reference to the axis for functional chaining.
delete this.scaler;
delete this.ticks;
this.dirty = true;
return this; // dojox.charting.axis2d.Default
},
initialized: function(){
// summary:
// Finds out if this axis has been initialized or not.
// returns: Boolean
// Whether a scaler has been calculated and if the axis is not dirty.
return "scaler" in this && !(this.dirty && this.dependOnData());
},
setWindow: function(scale, offset){
// summary:
// Set the drawing "window" for the axis.
// scale: Number
// The new scale for the axis.
// offset: Number
// The new offset for the axis.
// returns: dojox.charting.axis2d.Default
// The reference to the axis for functional chaining.
this.scale = scale;
this.offset = offset;
return this.clear(); // dojox.charting.axis2d.Default
},
getWindowScale: function(){
// summary:
// Get the current windowing scale of the axis.
return "scale" in this ? this.scale : 1; // Number
},
getWindowOffset: function(){
// summary:
// Get the current windowing offset for the axis.
return "offset" in this ? this.offset : 0; // Number
},
_groupLabelWidth: function(labels, font, wcLimit){
if(!labels.length){
return 0;
}
if(lang.isObject(labels[0])){
labels = df.map(labels, function(label){ return label.text; });
}
if (wcLimit) {
labels = df.map(labels, function(label){
return lang.trim(label).length == 0 ? "" : label.substring(0, wcLimit) + this.trailingSymbol;
}, this);
}
var s = labels.join("<br>");
return g._base._getTextBox(s, {font: font}).w || 0;
},
calculate: function(min, max, span, labels){
// summary:
// Perform all calculations needed to render this axis.
// min: Number
// The smallest value represented on this axis.
// max: Number
// The largest value represented on this axis.
// span: Number
// The span in pixels over which axis calculations are made.
// labels: String[]
// Optional list of labels.
// returns: dojox.charting.axis2d.Default
// The reference to the axis for functional chaining.
if(this.initialized()){
return this;
}
var o = this.opt;
this.labels = "labels" in o ? o.labels : labels;
this.scaler = lin.buildScaler(min, max, span, o);
var tsb = this.scaler.bounds;
if("scale" in this){
// calculate new range
o.from = tsb.lower + this.offset;
o.to = (tsb.upper - tsb.lower) / this.scale + o.from;
// make sure that bounds are correct
if( !isFinite(o.from) ||
isNaN(o.from) ||
!isFinite(o.to) ||
isNaN(o.to) ||
o.to - o.from >= tsb.upper - tsb.lower
){
// any error --- remove from/to bounds
delete o.from;
delete o.to;
delete this.scale;
delete this.offset;
}else{
// shift the window, if we are out of bounds
if(o.from < tsb.lower){
o.to += tsb.lower - o.from;
o.from = tsb.lower;
}else if(o.to > tsb.upper){
o.from += tsb.upper - o.to;
o.to = tsb.upper;
}
// update the offset
this.offset = o.from - tsb.lower;
}
// re-calculate the scaler
this.scaler = lin.buildScaler(min, max, span, o);
tsb = this.scaler.bounds;
// cleanup
if(this.scale == 1 && this.offset == 0){
delete this.scale;
delete this.offset;
}
}
var ta = this.chart.theme.axis, labelWidth = 0, rotation = o.rotation % 360,
// TODO: we use one font --- of major tick, we need to use major and minor fonts
taFont = o.font || (ta.majorTick && ta.majorTick.font) || (ta.tick && ta.tick.font),
size = taFont ? g.normalizedLength(g.splitFontString(taFont).size) : 0,
cosr = Math.abs(Math.cos(rotation * Math.PI / 180)),
sinr = Math.abs(Math.sin(rotation * Math.PI / 180));
if(rotation < 0){
rotation += 360;
}
if(size){
if(this.vertical ? rotation != 0 && rotation != 180 : rotation != 90 && rotation != 270){
// we need width of all labels
if(this.labels){
labelWidth = this._groupLabelWidth(this.labels, taFont, o.maxLabelCharCount);
}else{
var labelLength = Math.ceil(
Math.log(
Math.max(
Math.abs(tsb.from),
Math.abs(tsb.to)
)
) / Math.LN10
),
t = [];
if(tsb.from < 0 || tsb.to < 0){
t.push("-");
}
t.push(dstring.rep("9", labelLength));
var precision = Math.floor(
Math.log( tsb.to - tsb.from ) / Math.LN10
);
if(precision > 0){
t.push(".");
t.push(dstring.rep("9", precision));
}
labelWidth = g._base._getTextBox(
t.join(""),
{ font: taFont }
).w;
}
labelWidth = o.maxLabelSize ? Math.min(o.maxLabelSize, labelWidth) : labelWidth;
}else{
labelWidth = size;
}
switch(rotation){
case 0:
case 90:
case 180:
case 270:
// trivial cases: use labelWidth
break;
default:
// rotated labels
var gap1 = Math.sqrt(labelWidth * labelWidth + size * size), // short labels
gap2 = this.vertical ? size * cosr + labelWidth * sinr : labelWidth * cosr + size * sinr; // slanted labels
labelWidth = Math.min(gap1, gap2);
break;
}
}
this.scaler.minMinorStep = labelWidth + labelGap;
this.ticks = lin.buildTicks(this.scaler, o);
return this; // dojox.charting.axis2d.Default
},
getScaler: function(){
// summary:
// Get the pre-calculated scaler object.
return this.scaler; // Object
},
getTicks: function(){
// summary:
// Get the pre-calculated ticks object.
return this.ticks; // Object
}
});
});
},
'dojox/lang/utils':function(){
define("dojox/lang/utils", ["..", "dojo/_base/lang"],
function(dojox, lang){
var du = lang.getObject("lang.utils", true, dojox);
var empty = {}, opts = Object.prototype.toString;
var clone = function(o){
if(o){
switch(opts.call(o)){
case "[object Array]":
return o.slice(0);
case "[object Object]":
return lang.delegate(o);
}
}
return o;
}
lang.mixin(du, {
coerceType: function(target, source){
// summary: Coerces one object to the type of another.
// target: Object: object, which typeof result is used to coerce "source" object.
// source: Object: object, which will be forced to change type.
switch(typeof target){
case "number": return Number(eval("(" + source + ")"));
case "string": return String(source);
case "boolean": return Boolean(eval("(" + source + ")"));
}
return eval("(" + source + ")");
},
updateWithObject: function(target, source, conv){
// summary: Updates an existing object in place with properties from an "source" object.
// target: Object: the "target" object to be updated
// source: Object: the "source" object, whose properties will be used to source the existed object.
// conv: Boolean?: force conversion to the original type
if(!source){ return target; }
for(var x in target){
if(x in source && !(x in empty)){
var t = target[x];
if(t && typeof t == "object"){
du.updateWithObject(t, source[x], conv);
}else{
target[x] = conv ? du.coerceType(t, source[x]) : clone(source[x]);
}
}
}
return target; // Object
},
updateWithPattern: function(target, source, pattern, conv){
// summary: Updates an existing object in place with properties from an "source" object.
// target: Object: the "target" object to be updated
// source: Object: the "source" object, whose properties will be used to source the existed object.
// pattern: Object: object, whose properties will be used to pull values from the "source"
// conv: Boolean?: force conversion to the original type
if(!source || !pattern){ return target; }
for(var x in pattern){
if(x in source && !(x in empty)){
target[x] = conv ? du.coerceType(pattern[x], source[x]) : clone(source[x]);
}
}
return target; // Object
},
merge: function(object, mixin){
// summary: Merge two objects structurally, mixin properties will override object's properties.
// object: Object: original object.
// mixin: Object: additional object, which properties will override object's properties.
if(mixin){
var otype = opts.call(object), mtype = opts.call(mixin), t, i, l, m;
switch(mtype){
case "[object Array]":
if(mtype == otype){
t = new Array(Math.max(object.length, mixin.length));
for(i = 0, l = t.length; i < l; ++i){
t[i] = du.merge(object[i], mixin[i]);
}
return t;
}
return mixin.slice(0);
case "[object Object]":
if(mtype == otype && object){
t = lang.delegate(object);
for(i in mixin){
if(i in object){
l = object[i];
m = mixin[i];
if(m !== l){
t[i] = du.merge(l, m);
}
}else{
t[i] = lang.clone(mixin[i]);
}
}
return t;
}
return lang.clone(mixin);
}
}
return mixin;
}
});
return du;
});
},
'dojox/charting/plot2d/Pie':function(){
define("dojox/charting/plot2d/Pie", ["dojo/_base/lang", "dojo/_base/array" ,"dojo/_base/declare",
"../Element", "./_PlotEvents", "./common", "../axis2d/common",
"dojox/gfx", "dojox/gfx/matrix", "dojox/lang/functional", "dojox/lang/utils"],
function(lang, arr, declare, Element, PlotEvents, dc, da, g, m, df, du){
/*=====
var Element = dojox.charting.Element;
var PlotEvents = dojox.charting.plot2d._PlotEvents;
dojo.declare("dojox.charting.plot2d.__PieCtorArgs", dojox.charting.plot2d.__DefaultCtorArgs, {
// summary:
// Specialized keyword arguments object for use in defining parameters on a Pie chart.
// labels: Boolean?
// Whether or not to draw labels for each pie slice. Default is true.
labels: true,
// ticks: Boolean?
// Whether or not to draw ticks to labels within each slice. Default is false.
ticks: false,
// fixed: Boolean?
// TODO
fixed: true,
// precision: Number?
// The precision at which to sum/add data values. Default is 1.
precision: 1,
// labelOffset: Number?
// The amount in pixels by which to offset labels. Default is 20.
labelOffset: 20,
// labelStyle: String?
// Options as to where to draw labels. Values include "default", and "columns". Default is "default".
labelStyle: "default", // default/columns
// htmlLabels: Boolean?
// Whether or not to use HTML to render slice labels. Default is true.
htmlLabels: true,
// radGrad: String?
// The type of radial gradient to use in rendering. Default is "native".
radGrad: "native",
// fanSize: Number?
// The amount for a radial gradient. Default is 5.
fanSize: 5,
// startAngle: Number?
// Where to being rendering gradients in slices, in degrees. Default is 0.
startAngle: 0,
// radius: Number?
// The size of the radial gradient. Default is 0.
radius: 0
});
=====*/
var FUDGE_FACTOR = 0.2; // use to overlap fans
return declare("dojox.charting.plot2d.Pie", [Element, PlotEvents], {
// summary:
// The plot that represents a typical pie chart.
defaultParams: {
labels: true,
ticks: false,
fixed: true,
precision: 1,
labelOffset: 20,
labelStyle: "default", // default/columns
htmlLabels: true, // use HTML to draw labels
radGrad: "native", // or "linear", or "fan"
fanSize: 5, // maximum fan size in degrees
startAngle: 0 // start angle for slices in degrees
},
optionalParams: {
radius: 0,
// theme components
stroke: {},
outline: {},
shadow: {},
fill: {},
font: "",
fontColor: "",
labelWiring: {}
},
constructor: function(chart, kwArgs){
// summary:
// Create a pie plot.
this.opt = lang.clone(this.defaultParams);
du.updateWithObject(this.opt, kwArgs);
du.updateWithPattern(this.opt, kwArgs, this.optionalParams);
this.run = null;
this.dyn = [];
},
clear: function(){
// summary:
// Clear out all of the information tied to this plot.
// returns: dojox.charting.plot2d.Pie
// A reference to this plot for functional chaining.
this.dirty = true;
this.dyn = [];
this.run = null;
return this; // dojox.charting.plot2d.Pie
},
setAxis: function(axis){
// summary:
// Dummy method, since axes are irrelevant with a Pie chart.
// returns: dojox.charting.plot2d.Pie
// The reference to this plot for functional chaining.
return this; // dojox.charting.plot2d.Pie
},
addSeries: function(run){
// summary:
// Add a series of data to this plot.
// returns: dojox.charting.plot2d.Pie
// The reference to this plot for functional chaining.
this.run = run;
return this; // dojox.charting.plot2d.Pie
},
getSeriesStats: function(){
// summary:
// Returns default stats (irrelevant for this type of plot).
// returns: Object
// {hmin, hmax, vmin, vmax} min/max in both directions.
return lang.delegate(dc.defaultStats);
},
initializeScalers: function(){
// summary:
// Does nothing (irrelevant for this type of plot).
return this;
},
getRequiredColors: function(){
// summary:
// Return the number of colors needed to draw this plot.
return this.run ? this.run.data.length : 0;
},
render: function(dim, offsets){
// summary:
// Render the plot on the chart.
// dim: Object
// An object of the form { width, height }.
// offsets: Object
// An object of the form { l, r, t, b }.
// returns: dojox.charting.plot2d.Pie
// A reference to this plot for functional chaining.
if(!this.dirty){ return this; }
this.resetEvents();
this.dirty = false;
this._eventSeries = {};
this.cleanGroup();
var s = this.group, t = this.chart.theme;
if(!this.run || !this.run.data.length){
return this;
}
// calculate the geometry
var rx = (dim.width - offsets.l - offsets.r) / 2,
ry = (dim.height - offsets.t - offsets.b) / 2,
r = Math.min(rx, ry),
taFont = "font" in this.opt ? this.opt.font : t.axis.font,
size = taFont ? g.normalizedLength(g.splitFontString(taFont).size) : 0,
taFontColor = "fontColor" in this.opt ? this.opt.fontColor : t.axis.fontColor,
startAngle = m._degToRad(this.opt.startAngle),
start = startAngle, step, filteredRun, slices, labels, shift, labelR,
run = this.run.data,
events = this.events();
if(typeof run[0] == "number"){
filteredRun = df.map(run, "x ? Math.max(x, 0) : 0");
if(df.every(filteredRun, "<= 0")){
return this;
}
slices = df.map(filteredRun, "/this", df.foldl(filteredRun, "+", 0));
if(this.opt.labels){
labels = arr.map(slices, function(x){
return x > 0 ? this._getLabel(x * 100) + "%" : "";
}, this);
}
}else{
filteredRun = df.map(run, "x ? Math.max(x.y, 0) : 0");
if(df.every(filteredRun, "<= 0")){
return this;
}
slices = df.map(filteredRun, "/this", df.foldl(filteredRun, "+", 0));
if(this.opt.labels){
labels = arr.map(slices, function(x, i){
if(x <= 0){ return ""; }
var v = run[i];
return "text" in v ? v.text : this._getLabel(x * 100) + "%";
}, this);
}
}
var themes = df.map(run, function(v, i){
if(v === null || typeof v == "number"){
return t.next("slice", [this.opt, this.run], true);
}
return t.next("slice", [this.opt, this.run, v], true);
}, this);
if(this.opt.labels){
shift = df.foldl1(df.map(labels, function(label, i){
var font = themes[i].series.font;
return g._base._getTextBox(label, {font: font}).w;
}, this), "Math.max(a, b)") / 2;
if(this.opt.labelOffset < 0){
r = Math.min(rx - 2 * shift, ry - size) + this.opt.labelOffset;
}
labelR = r - this.opt.labelOffset;
}
if("radius" in this.opt){
r = this.opt.radius;
labelR = r - this.opt.labelOffset;
}
var circle = {
cx: offsets.l + rx,
cy: offsets.t + ry,
r: r
};
this.dyn = [];
// draw slices
var eventSeries = new Array(slices.length);
arr.some(slices, function(slice, i){
if(slice < 0){
// degenerated slice
return false; // continue
}
if(slice == 0){
this.dyn.push({fill: null, stroke: null});
return false;
}
var v = run[i], theme = themes[i], specialFill;
if(slice >= 1){
// whole pie
specialFill = this._plotFill(theme.series.fill, dim, offsets);
specialFill = this._shapeFill(specialFill,
{
x: circle.cx - circle.r, y: circle.cy - circle.r,
width: 2 * circle.r, height: 2 * circle.r
});
specialFill = this._pseudoRadialFill(specialFill, {x: circle.cx, y: circle.cy}, circle.r);
var shape = s.createCircle(circle).setFill(specialFill).setStroke(theme.series.stroke);
this.dyn.push({fill: specialFill, stroke: theme.series.stroke});
if(events){
var o = {
element: "slice",
index: i,
run: this.run,
shape: shape,
x: i,
y: typeof v == "number" ? v : v.y,
cx: circle.cx,
cy: circle.cy,
cr: r
};
this._connectEvents(o);
eventSeries[i] = o;
}
return true; // stop iteration
}
// calculate the geometry of the slice
var end = start + slice * 2 * Math.PI;
if(i + 1 == slices.length){
end = startAngle + 2 * Math.PI;
}
var step = end - start,
x1 = circle.cx + r * Math.cos(start),
y1 = circle.cy + r * Math.sin(start),
x2 = circle.cx + r * Math.cos(end),
y2 = circle.cy + r * Math.sin(end);
// draw the slice
var fanSize = m._degToRad(this.opt.fanSize);
if(theme.series.fill && theme.series.fill.type === "radial" && this.opt.radGrad === "fan" && step > fanSize){
var group = s.createGroup(), nfans = Math.ceil(step / fanSize), delta = step / nfans;
specialFill = this._shapeFill(theme.series.fill,
{x: circle.cx - circle.r, y: circle.cy - circle.r, width: 2 * circle.r, height: 2 * circle.r});
for(var j = 0; j < nfans; ++j){
var fansx = j == 0 ? x1 : circle.cx + r * Math.cos(start + (j - FUDGE_FACTOR) * delta),
fansy = j == 0 ? y1 : circle.cy + r * Math.sin(start + (j - FUDGE_FACTOR) * delta),
fanex = j == nfans - 1 ? x2 : circle.cx + r * Math.cos(start + (j + 1 + FUDGE_FACTOR) * delta),
faney = j == nfans - 1 ? y2 : circle.cy + r * Math.sin(start + (j + 1 + FUDGE_FACTOR) * delta),
fan = group.createPath().
moveTo(circle.cx, circle.cy).
lineTo(fansx, fansy).
arcTo(r, r, 0, delta > Math.PI, true, fanex, faney).
lineTo(circle.cx, circle.cy).
closePath().
setFill(this._pseudoRadialFill(specialFill, {x: circle.cx, y: circle.cy}, r, start + (j + 0.5) * delta, start + (j + 0.5) * delta));
}
group.createPath().
moveTo(circle.cx, circle.cy).
lineTo(x1, y1).
arcTo(r, r, 0, step > Math.PI, true, x2, y2).
lineTo(circle.cx, circle.cy).
closePath().
setStroke(theme.series.stroke);
shape = group;
}else{
shape = s.createPath().
moveTo(circle.cx, circle.cy).
lineTo(x1, y1).
arcTo(r, r, 0, step > Math.PI, true, x2, y2).
lineTo(circle.cx, circle.cy).
closePath().
setStroke(theme.series.stroke);
var specialFill = theme.series.fill;
if(specialFill && specialFill.type === "radial"){
specialFill = this._shapeFill(specialFill, {x: circle.cx - circle.r, y: circle.cy - circle.r, width: 2 * circle.r, height: 2 * circle.r});
if(this.opt.radGrad === "linear"){
specialFill = this._pseudoRadialFill(specialFill, {x: circle.cx, y: circle.cy}, r, start, end);
}
}else if(specialFill && specialFill.type === "linear"){
specialFill = this._plotFill(specialFill, dim, offsets);
specialFill = this._shapeFill(specialFill, shape.getBoundingBox());
}
shape.setFill(specialFill);
}
this.dyn.push({fill: specialFill, stroke: theme.series.stroke});
if(events){
var o = {
element: "slice",
index: i,
run: this.run,
shape: shape,
x: i,
y: typeof v == "number" ? v : v.y,
cx: circle.cx,
cy: circle.cy,
cr: r
};
this._connectEvents(o);
eventSeries[i] = o;
}
start = end;
return false; // continue
}, this);
// draw labels
if(this.opt.labels){
if(this.opt.labelStyle == "default"){
start = startAngle;
arr.some(slices, function(slice, i){
if(slice <= 0){
// degenerated slice
return false; // continue
}
var theme = themes[i];
if(slice >= 1){
// whole pie
var v = run[i], elem = da.createText[this.opt.htmlLabels && g.renderer != "vml" ? "html" : "gfx"](
this.chart, s, circle.cx, circle.cy + size / 2, "middle", labels[i],
theme.series.font, theme.series.fontColor);
if(this.opt.htmlLabels){
this.htmlElements.push(elem);
}
return true; // stop iteration
}
// calculate the geometry of the slice
var end = start + slice * 2 * Math.PI, v = run[i];
if(i + 1 == slices.length){
end = startAngle + 2 * Math.PI;
}
var labelAngle = (start + end) / 2,
x = circle.cx + labelR * Math.cos(labelAngle),
y = circle.cy + labelR * Math.sin(labelAngle) + size / 2;
// draw the label
var elem = da.createText[this.opt.htmlLabels && g.renderer != "vml" ? "html" : "gfx"]
(this.chart, s, x, y, "middle", labels[i], theme.series.font, theme.series.fontColor);
if(this.opt.htmlLabels){
this.htmlElements.push(elem);
}
start = end;
return false; // continue
}, this);
}else if(this.opt.labelStyle == "columns"){
start = startAngle;
//calculate label angles
var labeledSlices = [];
arr.forEach(slices, function(slice, i){
var end = start + slice * 2 * Math.PI;
if(i + 1 == slices.length){
end = startAngle + 2 * Math.PI;
}
var labelAngle = (start + end) / 2;
labeledSlices.push({
angle: labelAngle,
left: Math.cos(labelAngle) < 0,
theme: themes[i],
index: i,
omit: end - start < 0.001
});
start = end;
});
//calculate label radius to each slice
var labelHeight = g._base._getTextBox("a",{font:taFont}).h;
this._getProperLabelRadius(labeledSlices, labelHeight, circle.r * 1.1);
//draw label and wiring
arr.forEach(labeledSlices, function(slice, i){
if (!slice.omit) {
var leftColumn = circle.cx - circle.r * 2,
rightColumn = circle.cx + circle.r * 2,
labelWidth = g._base._getTextBox(labels[i], {font: taFont}).w,
x = circle.cx + slice.labelR * Math.cos(slice.angle),
y = circle.cy + slice.labelR * Math.sin(slice.angle),
jointX = (slice.left) ? (leftColumn + labelWidth) : (rightColumn - labelWidth),
labelX = (slice.left) ? leftColumn : jointX;
var wiring = s.createPath().moveTo(circle.cx + circle.r * Math.cos(slice.angle), circle.cy + circle.r * Math.sin(slice.angle))
if (Math.abs(slice.labelR * Math.cos(slice.angle)) < circle.r * 2 - labelWidth) {
wiring.lineTo(x, y);
}
wiring.lineTo(jointX, y).setStroke(slice.theme.series.labelWiring);
var elem = da.createText[this.opt.htmlLabels && g.renderer != "vml" ? "html" : "gfx"](
this.chart, s, labelX, y, "left", labels[i], slice.theme.series.font, slice.theme.series.fontColor);
if (this.opt.htmlLabels) {
this.htmlElements.push(elem);
}
}
},this);
}
}
// post-process events to restore the original indexing
var esi = 0;
this._eventSeries[this.run.name] = df.map(run, function(v){
return v <= 0 ? null : eventSeries[esi++];
});
return this; // dojox.charting.plot2d.Pie
},
_getProperLabelRadius: function(slices, labelHeight, minRidius){
var leftCenterSlice = {},rightCenterSlice = {},leftMinSIN = 1, rightMinSIN = 1;
if (slices.length == 1) {
slices[0].labelR = minRidius;
return;
}
for(var i = 0;i<slices.length;i++){
var tempSIN = Math.abs(Math.sin(slices[i].angle));
if(slices[i].left){
if(leftMinSIN > tempSIN){
leftMinSIN = tempSIN;
leftCenterSlice = slices[i];
}
}else{
if(rightMinSIN > tempSIN){
rightMinSIN = tempSIN;
rightCenterSlice = slices[i];
}
}
}
leftCenterSlice.labelR = rightCenterSlice.labelR = minRidius;
this._calculateLabelR(leftCenterSlice,slices,labelHeight);
this._calculateLabelR(rightCenterSlice,slices,labelHeight);
},
_calculateLabelR: function(firstSlice,slices,labelHeight){
var i = firstSlice.index,length = slices.length,
currentLabelR = firstSlice.labelR;
while(!(slices[i%length].left ^ slices[(i+1)%length].left)){
if (!slices[(i + 1) % length].omit) {
var nextLabelR = (Math.sin(slices[i % length].angle) * currentLabelR + ((slices[i % length].left) ? (-labelHeight) : labelHeight)) /
Math.sin(slices[(i + 1) % length].angle);
currentLabelR = (nextLabelR < firstSlice.labelR) ? firstSlice.labelR : nextLabelR;
slices[(i + 1) % length].labelR = currentLabelR;
}
i++;
}
i = firstSlice.index;
var j = (i == 0)?length-1 : i - 1;
while(!(slices[i].left ^ slices[j].left)){
if (!slices[j].omit) {
var nextLabelR = (Math.sin(slices[i].angle) * currentLabelR + ((slices[i].left) ? labelHeight : (-labelHeight))) /
Math.sin(slices[j].angle);
currentLabelR = (nextLabelR < firstSlice.labelR) ? firstSlice.labelR : nextLabelR;
slices[j].labelR = currentLabelR;
}
i--;j--;
i = (i < 0)?i+slices.length:i;
j = (j < 0)?j+slices.length:j;
}
},
// utilities
_getLabel: function(number){
return dc.getLabel(number, this.opt.fixed, this.opt.precision);
}
});
});
},
'dijit/hccss':function(){
define("dijit/hccss", [
"require", // require.toUrl
"dojo/_base/config", // config.blankGif
"dojo/dom-class", // domClass.add domConstruct.create domStyle.getComputedStyle
"dojo/dom-construct", // domClass.add domConstruct.create domStyle.getComputedStyle
"dojo/dom-style", // domClass.add domConstruct.create domStyle.getComputedStyle
"dojo/ready", // ready
"dojo/_base/sniff", // has("ie") has("mozilla")
"dojo/_base/window" // win.body
], function(require, config, domClass, domConstruct, domStyle, ready, has, win){
// module:
// dijit/hccss
// summary:
// Test if computer is in high contrast mode, and sets dijit_a11y flag on <body> if it is.
if(has("ie") || has("mozilla")){ // NOTE: checking in Safari messes things up
// priority is 90 to run ahead of parser priority of 100
ready(90, function(){
// summary:
// Detects if we are in high-contrast mode or not
// create div for testing if high contrast mode is on or images are turned off
var div = domConstruct.create("div",{
id: "a11yTestNode",
style:{
cssText:'border: 1px solid;'
+ 'border-color:red green;'
+ 'position: absolute;'
+ 'height: 5px;'
+ 'top: -999px;'
+ 'background-image: url("' + (config.blankGif || require.toUrl("dojo/resources/blank.gif")) + '");'
}
}, win.body());
// test it
var cs = domStyle.getComputedStyle(div);
if(cs){
var bkImg = cs.backgroundImage;
var needsA11y = (cs.borderTopColor == cs.borderRightColor) || (bkImg != null && (bkImg == "none" || bkImg == "url(invalid-url:)" ));
if(needsA11y){
domClass.add(win.body(), "dijit_a11y");
}
if(has("ie")){
div.outerHTML = ""; // prevent mixed-content warning, see http://support.microsoft.com/kb/925014
}else{
win.body().removeChild(div);
}
}
});
}
});
},
'dojox/charting/action2d/Shake':function(){
define("dojox/charting/action2d/Shake", ["dojo/_base/connect", "dojo/_base/declare", "./PlotAction",
"dojo/fx", "dojo/fx/easing", "dojox/gfx/matrix", "dojox/gfx/fx"],
function(hub, declare, PlotAction, df, dfe, m, gf){
/*=====
dojo.declare("dojox.charting.action2d.__ShakeCtorArgs", dojox.charting.action2d.__PlotActionCtorArgstorArgs, {
// summary:
// Additional arguments for highlighting actions.
// shift: Number?
// The amount in pixels to shift the pie slice. Default is 3.
shift: 3
});
var PlotAction = dojox.charting.action2d.PlotAction;
=====*/
var DEFAULT_SHIFT = 3;
return declare("dojox.charting.action2d.Shake", PlotAction, {
// summary:
// Create a shaking action for use on an element in a chart.
// the data description block for the widget parser
defaultParams: {
duration: 400, // duration of the action in ms
easing: dfe.backOut, // easing for the action
shiftX: DEFAULT_SHIFT, // shift of the element along the X axis
shiftY: DEFAULT_SHIFT // shift of the element along the Y axis
},
optionalParams: {}, // no optional parameters
constructor: function(chart, plot, kwArgs){
// summary:
// Create the shaking action and connect it to the plot.
// chart: dojox.charting.Chart
// The chart this action belongs to.
// plot: String?
// The plot this action is attached to. If not passed, "default" is assumed.
// kwArgs: dojox.charting.action2d.__ShakeCtorArgs?
// Optional keyword arguments object for setting parameters.
if(!kwArgs){ kwArgs = {}; }
this.shiftX = typeof kwArgs.shiftX == "number" ? kwArgs.shiftX : DEFAULT_SHIFT;
this.shiftY = typeof kwArgs.shiftY == "number" ? kwArgs.shiftY : DEFAULT_SHIFT;
this.connect();
},
process: function(o){
// summary:
// Process the action on the given object.
// o: dojox.gfx.Shape
// The object on which to process the slice moving action.
if(!o.shape || !(o.type in this.overOutEvents)){ return; }
var runName = o.run.name, index = o.index, vector = [], anim,
shiftX = o.type == "onmouseover" ? this.shiftX : -this.shiftX,
shiftY = o.type == "onmouseover" ? this.shiftY : -this.shiftY;
if(runName in this.anim){
anim = this.anim[runName][index];
}else{
this.anim[runName] = {};
}
if(anim){
anim.action.stop(true);
}else{
this.anim[runName][index] = anim = {};
}
var kwArgs = {
shape: o.shape,
duration: this.duration,
easing: this.easing,
transform: [
{name: "translate", start: [this.shiftX, this.shiftY], end: [0, 0]},
m.identity
]
};
if(o.shape){
vector.push(gf.animateTransform(kwArgs));
}
if(o.oultine){
kwArgs.shape = o.outline;
vector.push(gf.animateTransform(kwArgs));
}
if(o.shadow){
kwArgs.shape = o.shadow;
vector.push(gf.animateTransform(kwArgs));
}
if(!vector.length){
delete this.anim[runName][index];
return;
}
anim.action = df.combine(vector);
if(o.type == "onmouseout"){
hub.connect(anim.action, "onEnd", this, function(){
if(this.anim[runName]){
delete this.anim[runName][index];
}
});
}
anim.action.play();
}
});
});
},
'dojox/lang/functional/lambda':function(){
define("dojox/lang/functional/lambda", ["../..", "dojo/_base/kernel", "dojo/_base/lang", "dojo/_base/array"], function(dojox, dojo, lang, arr){
var df = lang.getObject("lang.functional", true, dojox);
// This module adds high-level functions and related constructs:
// - anonymous functions built from the string
// Acknoledgements:
// - lambda() is based on work by Oliver Steele
// (http://osteele.com/sources/javascript/functional/functional.js)
// which was published under MIT License
// Notes:
// - lambda() produces functions, which after the compilation step are
// as fast as regular JS functions (at least theoretically).
// Lambda input values:
// - returns functions unchanged
// - converts strings to functions
// - converts arrays to a functional composition
var lcache = {};
// split() is augmented on IE6 to ensure the uniform behavior
var split = "ab".split(/a*/).length > 1 ? String.prototype.split :
function(sep){
var r = this.split.call(this, sep),
m = sep.exec(this);
if(m && m.index == 0){ r.unshift(""); }
return r;
};
var lambda = function(/*String*/ s){
var args = [], sects = split.call(s, /\s*->\s*/m);
if(sects.length > 1){
while(sects.length){
s = sects.pop();
args = sects.pop().split(/\s*,\s*|\s+/m);
if(sects.length){ sects.push("(function(" + args + "){return (" + s + ")})"); }
}
}else if(s.match(/\b_\b/)){
args = ["_"];
}else{
var l = s.match(/^\s*(?:[+*\/%&|\^\.=<>]|!=)/m),
r = s.match(/[+\-*\/%&|\^\.=<>!]\s*$/m);
if(l || r){
if(l){
args.push("$1");
s = "$1" + s;
}
if(r){
args.push("$2");
s = s + "$2";
}
}else{
// the point of the long regex below is to exclude all well-known
// lower-case words from the list of potential arguments
var vars = s.
replace(/(?:\b[A-Z]|\.[a-zA-Z_$])[a-zA-Z_$\d]*|[a-zA-Z_$][a-zA-Z_$\d]*:|this|true|false|null|undefined|typeof|instanceof|in|delete|new|void|arguments|decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|escape|eval|isFinite|isNaN|parseFloat|parseInt|unescape|dojo|dijit|dojox|window|document|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g, "").
match(/([a-z_$][a-z_$\d]*)/gi) || [], t = {};
arr.forEach(vars, function(v){
if(!(v in t)){
args.push(v);
t[v] = 1;
}
});
}
}
return {args: args, body: s}; // Object
};
var compose = function(/*Array*/ a){
return a.length ?
function(){
var i = a.length - 1, x = df.lambda(a[i]).apply(this, arguments);
for(--i; i >= 0; --i){ x = df.lambda(a[i]).call(this, x); }
return x;
}
:
// identity
function(x){ return x; };
};
lang.mixin(df, {
// lambda
rawLambda: function(/*String*/ s){
// summary:
// builds a function from a snippet, or array (composing),
// returns an object describing the function; functions are
// passed through unmodified.
// description:
// This method is to normalize a functional representation (a
// text snippet) to an object that contains an array of
// arguments, and a body , which is used to calculate the
// returning value.
return lambda(s); // Object
},
buildLambda: function(/*String*/ s){
// summary:
// builds a function from a snippet, returns a string, which
// represents the function.
// description:
// This method returns a textual representation of a function
// built from the snippet. It is meant to be evaled in the
// proper context, so local variables can be pulled from the
// environment.
s = lambda(s);
return "function(" + s.args.join(",") + "){return (" + s.body + ");}"; // String
},
lambda: function(/*Function|String|Array*/ s){
// summary:
// builds a function from a snippet, or array (composing),
// returns a function object; functions are passed through
// unmodified.
// description:
// This method is used to normalize a functional
// representation (a text snippet, an array, or a function) to
// a function object.
if(typeof s == "function"){ return s; }
if(s instanceof Array){ return compose(s); }
if(s in lcache){ return lcache[s]; }
s = lambda(s);
return lcache[s] = new Function(s.args, "return (" + s.body + ");"); // Function
},
clearLambdaCache: function(){
// summary:
// clears internal cache of lambdas
lcache = {};
}
});
return df;
});
},
'dojox/lang/functional/reversed':function(){
define(["dojo/_base/lang", "dojo/_base/window" ,"./lambda"],
function(lang, win, df){
// This module adds high-level functions and related constructs:
// - reversed versions of array-processing functions similar to standard JS functions
// Notes:
// - this module provides reversed versions of standard array-processing functions:
// forEachRev, mapRev, filterRev
// Defined methods:
// - take any valid lambda argument as the functional argument
// - operate on dense arrays
// - take a string as the array argument
/*=====
var df = dojox.lang.functional;
=====*/
lang.mixin(df, {
// JS 1.6 standard array functions, which can take a lambda as a parameter.
// Consider using dojo._base.array functions, if you don't need the lambda support.
filterRev: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: creates a new array with all elements that pass the test
// implemented by the provided function.
if(typeof a == "string"){ a = a.split(""); }
o = o || win.global; f = df.lambda(f);
var t = [], v, i = a.length - 1;
for(; i >= 0; --i){
v = a[i];
if(f.call(o, v, i, a)){ t.push(v); }
}
return t; // Array
},
forEachRev: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: executes a provided function once per array element.
if(typeof a == "string"){ a = a.split(""); }
o = o || win.global; f = df.lambda(f);
for(var i = a.length - 1; i >= 0; f.call(o, a[i], i, a), --i);
},
mapRev: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: creates a new array with the results of calling
// a provided function on every element in this array.
if(typeof a == "string"){ a = a.split(""); }
o = o || win.global; f = df.lambda(f);
var n = a.length, t = new Array(n), i = n - 1, j = 0;
for(; i >= 0; t[j++] = f.call(o, a[i], i, a), --i);
return t; // Array
},
everyRev: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: tests whether all elements in the array pass the test
// implemented by the provided function.
if(typeof a == "string"){ a = a.split(""); }
o = o || win.global; f = df.lambda(f);
for(var i = a.length - 1; i >= 0; --i){
if(!f.call(o, a[i], i, a)){
return false; // Boolean
}
}
return true; // Boolean
},
someRev: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: tests whether some element in the array passes the test
// implemented by the provided function.
if(typeof a == "string"){ a = a.split(""); }
o = o || win.global; f = df.lambda(f);
for(var i = a.length - 1; i >= 0; --i){
if(f.call(o, a[i], i, a)){
return true; // Boolean
}
}
return false; // Boolean
}
});
return df;
});
},
'dojox/charting/scaler/primitive':function(){
define("dojox/charting/scaler/primitive", ["dojo/_base/lang"],
function(lang){
var primitive = lang.getObject("dojox.charting.scaler.primitive", true);
return lang.mixin(primitive, {
buildScaler: function(/*Number*/ min, /*Number*/ max, /*Number*/ span, /*Object*/ kwArgs){
if(min == max){
// artificially extend bounds
min -= 0.5;
max += 0.5;
// now the line will be centered
}
return {
bounds: {
lower: min,
upper: max,
from: min,
to: max,
scale: span / (max - min),
span: span
},
scaler: primitive
};
},
buildTicks: function(/*Object*/ scaler, /*Object*/ kwArgs){
return {major: [], minor: [], micro: []}; // Object
},
getTransformerFromModel: function(/*Object*/ scaler){
var offset = scaler.bounds.from, scale = scaler.bounds.scale;
return function(x){ return (x - offset) * scale; }; // Function
},
getTransformerFromPlot: function(/*Object*/ scaler){
var offset = scaler.bounds.from, scale = scaler.bounds.scale;
return function(x){ return x / scale + offset; }; // Function
}
});
});
},
'dojox/charting/plot2d/Candlesticks':function(){
define("dojox/charting/plot2d/Candlesticks", ["dojo/_base/lang", "dojo/_base/declare", "dojo/_base/array", "./Base", "./common",
"dojox/lang/functional", "dojox/lang/functional/reversed", "dojox/lang/utils", "dojox/gfx/fx"],
function(lang, declare, arr, Base, dc, df, dfr, du, fx){
/*=====
var Base = dojox.charting.plot2d.Base;
=====*/
var purgeGroup = dfr.lambda("item.purgeGroup()");
// Candlesticks are based on the Bars plot type; we expect the following passed
// as values in a series:
// { x?, open, close, high, low, mid? }
// if x is not provided, the array index is used.
// failing to provide the OHLC values will throw an error.
return declare("dojox.charting.plot2d.Candlesticks", Base, {
// summary:
// A plot that represents typical candlesticks (financial reporting, primarily).
// Unlike most charts, the Candlestick expects data points to be represented by
// an object of the form { x?, open, close, high, low, mid? }, where both
// x and mid are optional parameters. If x is not provided, the index of the
// data array is used.
defaultParams: {
hAxis: "x", // use a horizontal axis named "x"
vAxis: "y", // use a vertical axis named "y"
gap: 2, // gap between columns in pixels
animate: null // animate bars into place
},
optionalParams: {
minBarSize: 1, // minimal candle width in pixels
maxBarSize: 1, // maximal candle width in pixels
// theme component
stroke: {},
outline: {},
shadow: {},
fill: {},
font: "",
fontColor: ""
},
constructor: function(chart, kwArgs){
// summary:
// The constructor for a candlestick chart.
// chart: dojox.charting.Chart
// The chart this plot belongs to.
// kwArgs: dojox.charting.plot2d.__BarCtorArgs?
// An optional keyword arguments object to help define the plot.
this.opt = lang.clone(this.defaultParams);
du.updateWithObject(this.opt, kwArgs);
du.updateWithPattern(this.opt, kwArgs, this.optionalParams);
this.series = [];
this.hAxis = this.opt.hAxis;
this.vAxis = this.opt.vAxis;
this.animate = this.opt.animate;
},
collectStats: function(series){
// summary:
// Collect all statistics for drawing this chart. Since the common
// functionality only assumes x and y, Candlesticks must create it's own
// stats (since data has no y value, but open/close/high/low instead).
// series: dojox.charting.Series[]
// The data series array to be drawn on this plot.
// returns: Object
// Returns an object in the form of { hmin, hmax, vmin, vmax }.
// we have to roll our own, since we need to use all four passed
// values to figure out our stats, and common only assumes x and y.
var stats = lang.delegate(dc.defaultStats);
for(var i=0; i<series.length; i++){
var run = series[i];
if(!run.data.length){ continue; }
var old_vmin = stats.vmin, old_vmax = stats.vmax;
if(!("ymin" in run) || !("ymax" in run)){
arr.forEach(run.data, function(val, idx){
if(val !== null){
var x = val.x || idx + 1;
stats.hmin = Math.min(stats.hmin, x);
stats.hmax = Math.max(stats.hmax, x);
stats.vmin = Math.min(stats.vmin, val.open, val.close, val.high, val.low);
stats.vmax = Math.max(stats.vmax, val.open, val.close, val.high, val.low);
}
});
}
if("ymin" in run){ stats.vmin = Math.min(old_vmin, run.ymin); }
if("ymax" in run){ stats.vmax = Math.max(old_vmax, run.ymax); }
}
return stats; // Object
},
getSeriesStats: function(){
// summary:
// Calculate the min/max on all attached series in both directions.
// returns: Object
// {hmin, hmax, vmin, vmax} min/max in both directions.
var stats = this.collectStats(this.series);
stats.hmin -= 0.5;
stats.hmax += 0.5;
return stats;
},
render: function(dim, offsets){
// summary:
// Run the calculations for any axes for this plot.
// dim: Object
// An object in the form of { width, height }
// offsets: Object
// An object of the form { l, r, t, b}.
// returns: dojox.charting.plot2d.Candlesticks
// A reference to this plot for functional chaining.
if(this.zoom && !this.isDataDirty()){
return this.performZoom(dim, offsets);
}
this.resetEvents();
this.dirty = this.isDirty();
if(this.dirty){
arr.forEach(this.series, purgeGroup);
this._eventSeries = {};
this.cleanGroup();
var s = this.group;
df.forEachRev(this.series, function(item){ item.cleanGroup(s); });
}
var t = this.chart.theme, f, gap, width,
ht = this._hScaler.scaler.getTransformerFromModel(this._hScaler),
vt = this._vScaler.scaler.getTransformerFromModel(this._vScaler),
baseline = Math.max(0, this._vScaler.bounds.lower),
baselineHeight = vt(baseline),
events = this.events();
f = dc.calculateBarSize(this._hScaler.bounds.scale, this.opt);
gap = f.gap;
width = f.size;
for(var i = this.series.length - 1; i >= 0; --i){
var run = this.series[i];
if(!this.dirty && !run.dirty){
t.skip();
this._reconnectEvents(run.name);
continue;
}
run.cleanGroup();
var theme = t.next("candlestick", [this.opt, run]), s = run.group,
eventSeries = new Array(run.data.length);
for(var j = 0; j < run.data.length; ++j){
var v = run.data[j];
if(v !== null){
var finalTheme = t.addMixin(theme, "candlestick", v, true);
// calculate the points we need for OHLC
var x = ht(v.x || (j+0.5)) + offsets.l + gap,
y = dim.height - offsets.b,
open = vt(v.open),
close = vt(v.close),
high = vt(v.high),
low = vt(v.low);
if("mid" in v){
var mid = vt(v.mid);
}
if(low > high){
var tmp = high;
high = low;
low = tmp;
}
if(width >= 1){
// draw the line and rect, set up as a group and pass that to the events.
var doFill = open > close;
var line = { x1: width/2, x2: width/2, y1: y - high, y2: y - low },
rect = {
x: 0, y: y-Math.max(open, close),
width: width, height: Math.max(doFill ? open-close : close-open, 1)
};
var shape = s.createGroup();
shape.setTransform({dx: x, dy: 0 });
var inner = shape.createGroup();
inner.createLine(line).setStroke(finalTheme.series.stroke);
inner.createRect(rect).setStroke(finalTheme.series.stroke).
setFill(doFill ? finalTheme.series.fill : "white");
if("mid" in v){
// add the mid line.
inner.createLine({
x1: (finalTheme.series.stroke.width||1), x2: width - (finalTheme.series.stroke.width || 1),
y1: y - mid, y2: y - mid
}).setStroke(doFill ? "white" : finalTheme.series.stroke);
}
// TODO: double check this.
run.dyn.fill = finalTheme.series.fill;
run.dyn.stroke = finalTheme.series.stroke;
if(events){
var o = {
element: "candlestick",
index: j,
run: run,
shape: inner,
x: x,
y: y-Math.max(open, close),
cx: width/2,
cy: (y-Math.max(open, close)) + (Math.max(doFill ? open-close : close-open, 1)/2),
width: width,
height: Math.max(doFill ? open-close : close-open, 1),
data: v
};
this._connectEvents(o);
eventSeries[j] = o;
}
}
if(this.animate){
this._animateCandlesticks(shape, y - low, high - low);
}
}
}
this._eventSeries[run.name] = eventSeries;
run.dirty = false;
}
this.dirty = false;
return this; // dojox.charting.plot2d.Candlesticks
},
_animateCandlesticks: function(shape, voffset, vsize){
fx.animateTransform(lang.delegate({
shape: shape,
duration: 1200,
transform: [
{name: "translate", start: [0, voffset - (voffset/vsize)], end: [0, 0]},
{name: "scale", start: [1, 1/vsize], end: [1, 1]},
{name: "original"}
]
}, this.animate)).play();
}
});
});
},
'dojox/charting/widget/Sparkline':function(){
define("dojox/charting/widget/Sparkline", ["dojo/_base/lang", "dojo/_base/array", "dojo/_base/declare", "dojo/_base/html", "dojo/query",
"./Chart", "../themes/GreySkies", "../plot2d/Lines", "dojo/dom-prop"],
function(lang, arrayUtil, declare, html, query, Chart, GreySkies, Lines, domProp){
/*=====
var Chart = dojox.charting.widget.Chart;
=====*/
declare("dojox.charting.widget.Sparkline", Chart, {
theme: GreySkies,
margins: { l: 0, r: 0, t: 0, b: 0 },
type: "Lines",
valueFn: "Number(x)",
store: "",
field: "",
query: "",
queryOptions: "",
start: "0",
count: "Infinity",
sort: "",
data: "",
name: "default",
buildRendering: function(){
var n = this.srcNodeRef;
if( !n.childNodes.length || // shortcut the query
!query("> .axis, > .plot, > .action, > .series", n).length){
var plot = document.createElement("div");
domProp.set(plot, {
"class": "plot",
"name": "default",
"type": this.type
});
n.appendChild(plot);
var series = document.createElement("div");
domProp.set(series, {
"class": "series",
plot: "default",
name: this.name,
start: this.start,
count: this.count,
valueFn: this.valueFn
});
arrayUtil.forEach(
["store", "field", "query", "queryOptions", "sort", "data"],
function(i){
if(this[i].length){
domProp.set(series, i, this[i]);
}
},
this
);
n.appendChild(series);
}
this.inherited(arguments);
}
}
);
});
},
'dojox/gfx/matrix':function(){
define("dojox/gfx/matrix", ["./_base","dojo/_base/lang"],
function(g, lang){
var m = g.matrix = {};
/*===== g = dojox.gfx; m = dojox.gfx.matrix =====*/
// candidates for dojox.math:
var _degToRadCache = {};
m._degToRad = function(degree){
return _degToRadCache[degree] || (_degToRadCache[degree] = (Math.PI * degree / 180));
};
m._radToDeg = function(radian){ return radian / Math.PI * 180; };
m.Matrix2D = function(arg){
// summary:
// a 2D matrix object
// description: Normalizes a 2D matrix-like object. If arrays is passed,
// all objects of the array are normalized and multiplied sequentially.
// arg: Object
// a 2D matrix-like object, a number, or an array of such objects
if(arg){
if(typeof arg == "number"){
this.xx = this.yy = arg;
}else if(arg instanceof Array){
if(arg.length > 0){
var matrix = m.normalize(arg[0]);
// combine matrices
for(var i = 1; i < arg.length; ++i){
var l = matrix, r = m.normalize(arg[i]);
matrix = new m.Matrix2D();
matrix.xx = l.xx * r.xx + l.xy * r.yx;
matrix.xy = l.xx * r.xy + l.xy * r.yy;
matrix.yx = l.yx * r.xx + l.yy * r.yx;
matrix.yy = l.yx * r.xy + l.yy * r.yy;
matrix.dx = l.xx * r.dx + l.xy * r.dy + l.dx;
matrix.dy = l.yx * r.dx + l.yy * r.dy + l.dy;
}
lang.mixin(this, matrix);
}
}else{
lang.mixin(this, arg);
}
}
};
// the default (identity) matrix, which is used to fill in missing values
lang.extend(m.Matrix2D, {xx: 1, xy: 0, yx: 0, yy: 1, dx: 0, dy: 0});
lang.mixin(m, {
// summary: class constants, and methods of dojox.gfx.matrix
// matrix constants
// identity: dojox.gfx.matrix.Matrix2D
// an identity matrix constant: identity * (x, y) == (x, y)
identity: new m.Matrix2D(),
// flipX: dojox.gfx.matrix.Matrix2D
// a matrix, which reflects points at x = 0 line: flipX * (x, y) == (-x, y)
flipX: new m.Matrix2D({xx: -1}),
// flipY: dojox.gfx.matrix.Matrix2D
// a matrix, which reflects points at y = 0 line: flipY * (x, y) == (x, -y)
flipY: new m.Matrix2D({yy: -1}),
// flipXY: dojox.gfx.matrix.Matrix2D
// a matrix, which reflects points at the origin of coordinates: flipXY * (x, y) == (-x, -y)
flipXY: new m.Matrix2D({xx: -1, yy: -1}),
// matrix creators
translate: function(a, b){
// summary: forms a translation matrix
// description: The resulting matrix is used to translate (move) points by specified offsets.
// a: Number: an x coordinate value
// b: Number: a y coordinate value
if(arguments.length > 1){
return new m.Matrix2D({dx: a, dy: b}); // dojox.gfx.matrix.Matrix2D
}
// branch
// a: dojox.gfx.Point: a point-like object, which specifies offsets for both dimensions
// b: null
return new m.Matrix2D({dx: a.x, dy: a.y}); // dojox.gfx.matrix.Matrix2D
},
scale: function(a, b){
// summary: forms a scaling matrix
// description: The resulting matrix is used to scale (magnify) points by specified offsets.
// a: Number: a scaling factor used for the x coordinate
// b: Number: a scaling factor used for the y coordinate
if(arguments.length > 1){
return new m.Matrix2D({xx: a, yy: b}); // dojox.gfx.matrix.Matrix2D
}
if(typeof a == "number"){
// branch
// a: Number: a uniform scaling factor used for the both coordinates
// b: null
return new m.Matrix2D({xx: a, yy: a}); // dojox.gfx.matrix.Matrix2D
}
// branch
// a: dojox.gfx.Point: a point-like object, which specifies scale factors for both dimensions
// b: null
return new m.Matrix2D({xx: a.x, yy: a.y}); // dojox.gfx.matrix.Matrix2D
},
rotate: function(angle){
// summary: forms a rotating matrix
// description: The resulting matrix is used to rotate points
// around the origin of coordinates (0, 0) by specified angle.
// angle: Number: an angle of rotation in radians (>0 for CW)
var c = Math.cos(angle);
var s = Math.sin(angle);
return new m.Matrix2D({xx: c, xy: -s, yx: s, yy: c}); // dojox.gfx.matrix.Matrix2D
},
rotateg: function(degree){
// summary: forms a rotating matrix
// description: The resulting matrix is used to rotate points
// around the origin of coordinates (0, 0) by specified degree.
// See dojox.gfx.matrix.rotate() for comparison.
// degree: Number: an angle of rotation in degrees (>0 for CW)
return m.rotate(m._degToRad(degree)); // dojox.gfx.matrix.Matrix2D
},
skewX: function(angle) {
// summary: forms an x skewing matrix
// description: The resulting matrix is used to skew points in the x dimension
// around the origin of coordinates (0, 0) by specified angle.
// angle: Number: an skewing angle in radians
return new m.Matrix2D({xy: Math.tan(angle)}); // dojox.gfx.matrix.Matrix2D
},
skewXg: function(degree){
// summary: forms an x skewing matrix
// description: The resulting matrix is used to skew points in the x dimension
// around the origin of coordinates (0, 0) by specified degree.
// See dojox.gfx.matrix.skewX() for comparison.
// degree: Number: an skewing angle in degrees
return m.skewX(m._degToRad(degree)); // dojox.gfx.matrix.Matrix2D
},
skewY: function(angle){
// summary: forms a y skewing matrix
// description: The resulting matrix is used to skew points in the y dimension
// around the origin of coordinates (0, 0) by specified angle.
// angle: Number: an skewing angle in radians
return new m.Matrix2D({yx: Math.tan(angle)}); // dojox.gfx.matrix.Matrix2D
},
skewYg: function(degree){
// summary: forms a y skewing matrix
// description: The resulting matrix is used to skew points in the y dimension
// around the origin of coordinates (0, 0) by specified degree.
// See dojox.gfx.matrix.skewY() for comparison.
// degree: Number: an skewing angle in degrees
return m.skewY(m._degToRad(degree)); // dojox.gfx.matrix.Matrix2D
},
reflect: function(a, b){
// summary: forms a reflection matrix
// description: The resulting matrix is used to reflect points around a vector,
// which goes through the origin.
// a: dojox.gfx.Point: a point-like object, which specifies a vector of reflection
// b: null
if(arguments.length == 1){
b = a.y;
a = a.x;
}
// branch
// a: Number: an x coordinate value
// b: Number: a y coordinate value
// make a unit vector
var a2 = a * a, b2 = b * b, n2 = a2 + b2, xy = 2 * a * b / n2;
return new m.Matrix2D({xx: 2 * a2 / n2 - 1, xy: xy, yx: xy, yy: 2 * b2 / n2 - 1}); // dojox.gfx.matrix.Matrix2D
},
project: function(a, b){
// summary: forms an orthogonal projection matrix
// description: The resulting matrix is used to project points orthogonally on a vector,
// which goes through the origin.
// a: dojox.gfx.Point: a point-like object, which specifies a vector of projection
// b: null
if(arguments.length == 1){
b = a.y;
a = a.x;
}
// branch
// a: Number: an x coordinate value
// b: Number: a y coordinate value
// make a unit vector
var a2 = a * a, b2 = b * b, n2 = a2 + b2, xy = a * b / n2;
return new m.Matrix2D({xx: a2 / n2, xy: xy, yx: xy, yy: b2 / n2}); // dojox.gfx.matrix.Matrix2D
},
// ensure matrix 2D conformance
normalize: function(matrix){
// summary: converts an object to a matrix, if necessary
// description: Converts any 2D matrix-like object or an array of
// such objects to a valid dojox.gfx.matrix.Matrix2D object.
// matrix: Object: an object, which is converted to a matrix, if necessary
return (matrix instanceof m.Matrix2D) ? matrix : new m.Matrix2D(matrix); // dojox.gfx.matrix.Matrix2D
},
// common operations
clone: function(matrix){
// summary: creates a copy of a 2D matrix
// matrix: dojox.gfx.matrix.Matrix2D: a 2D matrix-like object to be cloned
var obj = new m.Matrix2D();
for(var i in matrix){
if(typeof(matrix[i]) == "number" && typeof(obj[i]) == "number" && obj[i] != matrix[i]) obj[i] = matrix[i];
}
return obj; // dojox.gfx.matrix.Matrix2D
},
invert: function(matrix){
// summary: inverts a 2D matrix
// matrix: dojox.gfx.matrix.Matrix2D: a 2D matrix-like object to be inverted
var M = m.normalize(matrix),
D = M.xx * M.yy - M.xy * M.yx;
M = new m.Matrix2D({
xx: M.yy/D, xy: -M.xy/D,
yx: -M.yx/D, yy: M.xx/D,
dx: (M.xy * M.dy - M.yy * M.dx) / D,
dy: (M.yx * M.dx - M.xx * M.dy) / D
});
return M; // dojox.gfx.matrix.Matrix2D
},
_multiplyPoint: function(matrix, x, y){
// summary: applies a matrix to a point
// matrix: dojox.gfx.matrix.Matrix2D: a 2D matrix object to be applied
// x: Number: an x coordinate of a point
// y: Number: a y coordinate of a point
return {x: matrix.xx * x + matrix.xy * y + matrix.dx, y: matrix.yx * x + matrix.yy * y + matrix.dy}; // dojox.gfx.Point
},
multiplyPoint: function(matrix, /* Number||Point */ a, /* Number? */ b){
// summary: applies a matrix to a point
// matrix: dojox.gfx.matrix.Matrix2D: a 2D matrix object to be applied
// a: Number: an x coordinate of a point
// b: Number?: a y coordinate of a point
var M = m.normalize(matrix);
if(typeof a == "number" && typeof b == "number"){
return m._multiplyPoint(M, a, b); // dojox.gfx.Point
}
// branch
// matrix: dojox.gfx.matrix.Matrix2D: a 2D matrix object to be applied
// a: dojox.gfx.Point: a point
// b: null
return m._multiplyPoint(M, a.x, a.y); // dojox.gfx.Point
},
multiply: function(matrix){
// summary: combines matrices by multiplying them sequentially in the given order
// matrix: dojox.gfx.matrix.Matrix2D...: a 2D matrix-like object,
// all subsequent arguments are matrix-like objects too
var M = m.normalize(matrix);
// combine matrices
for(var i = 1; i < arguments.length; ++i){
var l = M, r = m.normalize(arguments[i]);
M = new m.Matrix2D();
M.xx = l.xx * r.xx + l.xy * r.yx;
M.xy = l.xx * r.xy + l.xy * r.yy;
M.yx = l.yx * r.xx + l.yy * r.yx;
M.yy = l.yx * r.xy + l.yy * r.yy;
M.dx = l.xx * r.dx + l.xy * r.dy + l.dx;
M.dy = l.yx * r.dx + l.yy * r.dy + l.dy;
}
return M; // dojox.gfx.matrix.Matrix2D
},
// high level operations
_sandwich: function(matrix, x, y){
// summary: applies a matrix at a centrtal point
// matrix: dojox.gfx.matrix.Matrix2D: a 2D matrix-like object, which is applied at a central point
// x: Number: an x component of the central point
// y: Number: a y component of the central point
return m.multiply(m.translate(x, y), matrix, m.translate(-x, -y)); // dojox.gfx.matrix.Matrix2D
},
scaleAt: function(a, b, c, d){
// summary: scales a picture using a specified point as a center of scaling
// description: Compare with dojox.gfx.matrix.scale().
// a: Number: a scaling factor used for the x coordinate
// b: Number: a scaling factor used for the y coordinate
// c: Number: an x component of a central point
// d: Number: a y component of a central point
// accepts several signatures:
// 1) uniform scale factor, Point
// 2) uniform scale factor, x, y
// 3) x scale, y scale, Point
// 4) x scale, y scale, x, y
switch(arguments.length){
case 4:
// a and b are scale factor components, c and d are components of a point
return m._sandwich(m.scale(a, b), c, d); // dojox.gfx.matrix.Matrix2D
case 3:
if(typeof c == "number"){
// branch
// a: Number: a uniform scaling factor used for both coordinates
// b: Number: an x component of a central point
// c: Number: a y component of a central point
// d: null
return m._sandwich(m.scale(a), b, c); // dojox.gfx.matrix.Matrix2D
}
// branch
// a: Number: a scaling factor used for the x coordinate
// b: Number: a scaling factor used for the y coordinate
// c: dojox.gfx.Point: a central point
// d: null
return m._sandwich(m.scale(a, b), c.x, c.y); // dojox.gfx.matrix.Matrix2D
}
// branch
// a: Number: a uniform scaling factor used for both coordinates
// b: dojox.gfx.Point: a central point
// c: null
// d: null
return m._sandwich(m.scale(a), b.x, b.y); // dojox.gfx.matrix.Matrix2D
},
rotateAt: function(angle, a, b){
// summary: rotates a picture using a specified point as a center of rotation
// description: Compare with dojox.gfx.matrix.rotate().
// angle: Number: an angle of rotation in radians (>0 for CW)
// a: Number: an x component of a central point
// b: Number: a y component of a central point
// accepts several signatures:
// 1) rotation angle in radians, Point
// 2) rotation angle in radians, x, y
if(arguments.length > 2){
return m._sandwich(m.rotate(angle), a, b); // dojox.gfx.matrix.Matrix2D
}
// branch
// angle: Number: an angle of rotation in radians (>0 for CCW)
// a: dojox.gfx.Point: a central point
// b: null
return m._sandwich(m.rotate(angle), a.x, a.y); // dojox.gfx.matrix.Matrix2D
},
rotategAt: function(degree, a, b){
// summary: rotates a picture using a specified point as a center of rotation
// description: Compare with dojox.gfx.matrix.rotateg().
// degree: Number: an angle of rotation in degrees (>0 for CW)
// a: Number: an x component of a central point
// b: Number: a y component of a central point
// accepts several signatures:
// 1) rotation angle in degrees, Point
// 2) rotation angle in degrees, x, y
if(arguments.length > 2){
return m._sandwich(m.rotateg(degree), a, b); // dojox.gfx.matrix.Matrix2D
}
// branch
// degree: Number: an angle of rotation in degrees (>0 for CCW)
// a: dojox.gfx.Point: a central point
// b: null
return m._sandwich(m.rotateg(degree), a.x, a.y); // dojox.gfx.matrix.Matrix2D
},
skewXAt: function(angle, a, b){
// summary: skews a picture along the x axis using a specified point as a center of skewing
// description: Compare with dojox.gfx.matrix.skewX().
// angle: Number: an skewing angle in radians
// a: Number: an x component of a central point
// b: Number: a y component of a central point
// accepts several signatures:
// 1) skew angle in radians, Point
// 2) skew angle in radians, x, y
if(arguments.length > 2){
return m._sandwich(m.skewX(angle), a, b); // dojox.gfx.matrix.Matrix2D
}
// branch
// angle: Number: an skewing angle in radians
// a: dojox.gfx.Point: a central point
// b: null
return m._sandwich(m.skewX(angle), a.x, a.y); // dojox.gfx.matrix.Matrix2D
},
skewXgAt: function(degree, a, b){
// summary: skews a picture along the x axis using a specified point as a center of skewing
// description: Compare with dojox.gfx.matrix.skewXg().
// degree: Number: an skewing angle in degrees
// a: Number: an x component of a central point
// b: Number: a y component of a central point
// accepts several signatures:
// 1) skew angle in degrees, Point
// 2) skew angle in degrees, x, y
if(arguments.length > 2){
return m._sandwich(m.skewXg(degree), a, b); // dojox.gfx.matrix.Matrix2D
}
// branch
// degree: Number: an skewing angle in degrees
// a: dojox.gfx.Point: a central point
// b: null
return m._sandwich(m.skewXg(degree), a.x, a.y); // dojox.gfx.matrix.Matrix2D
},
skewYAt: function(angle, a, b){
// summary: skews a picture along the y axis using a specified point as a center of skewing
// description: Compare with dojox.gfx.matrix.skewY().
// angle: Number: an skewing angle in radians
// a: Number: an x component of a central point
// b: Number: a y component of a central point
// accepts several signatures:
// 1) skew angle in radians, Point
// 2) skew angle in radians, x, y
if(arguments.length > 2){
return m._sandwich(m.skewY(angle), a, b); // dojox.gfx.matrix.Matrix2D
}
// branch
// angle: Number: an skewing angle in radians
// a: dojox.gfx.Point: a central point
// b: null
return m._sandwich(m.skewY(angle), a.x, a.y); // dojox.gfx.matrix.Matrix2D
},
skewYgAt: function(/* Number */ degree, /* Number||Point */ a, /* Number? */ b){
// summary: skews a picture along the y axis using a specified point as a center of skewing
// description: Compare with dojox.gfx.matrix.skewYg().
// degree: Number: an skewing angle in degrees
// a: Number: an x component of a central point
// b: Number?: a y component of a central point
// accepts several signatures:
// 1) skew angle in degrees, Point
// 2) skew angle in degrees, x, y
if(arguments.length > 2){
return m._sandwich(m.skewYg(degree), a, b); // dojox.gfx.matrix.Matrix2D
}
// branch
// degree: Number: an skewing angle in degrees
// a: dojox.gfx.Point: a central point
// b: null
return m._sandwich(m.skewYg(degree), a.x, a.y); // dojox.gfx.matrix.Matrix2D
}
//TODO: rect-to-rect mapping, scale-to-fit (isotropic and anisotropic versions)
});
// propagate Matrix2D up
g.Matrix2D = m.Matrix2D;
return m;
});
},
'dojox/charting/plot2d/Scatter':function(){
define("dojox/charting/plot2d/Scatter", ["dojo/_base/lang", "dojo/_base/array", "dojo/_base/declare", "./Base", "./common",
"dojox/lang/functional", "dojox/lang/functional/reversed", "dojox/lang/utils", "dojox/gfx/fx", "dojox/gfx/gradutils"],
function(lang, arr, declare, Base, dc, df, dfr, du, fx, gradutils){
/*=====
var Base = dojox.charting.plot2d.Base;
=====*/
var purgeGroup = dfr.lambda("item.purgeGroup()");
return declare("dojox.charting.plot2d.Scatter", Base, {
// summary:
// A plot object representing a typical scatter chart.
defaultParams: {
hAxis: "x", // use a horizontal axis named "x"
vAxis: "y", // use a vertical axis named "y"
shadows: null, // draw shadows
animate: null // animate chart to place
},
optionalParams: {
// theme component
markerStroke: {},
markerOutline: {},
markerShadow: {},
markerFill: {},
markerFont: "",
markerFontColor: ""
},
constructor: function(chart, kwArgs){
// summary:
// Create the scatter plot.
// chart: dojox.charting.Chart
// The chart this plot belongs to.
// kwArgs: dojox.charting.plot2d.__DefaultCtorArgs?
// An optional keyword arguments object to help define this plot's parameters.
this.opt = lang.clone(this.defaultParams);
du.updateWithObject(this.opt, kwArgs);
du.updateWithPattern(this.opt, kwArgs, this.optionalParams);
this.series = [];
this.hAxis = this.opt.hAxis;
this.vAxis = this.opt.vAxis;
this.animate = this.opt.animate;
},
render: function(dim, offsets){
// summary:
// Run the calculations for any axes for this plot.
// dim: Object
// An object in the form of { width, height }
// offsets: Object
// An object of the form { l, r, t, b}.
// returns: dojox.charting.plot2d.Scatter
// A reference to this plot for functional chaining.
if(this.zoom && !this.isDataDirty()){
return this.performZoom(dim, offsets);
}
this.resetEvents();
this.dirty = this.isDirty();
if(this.dirty){
arr.forEach(this.series, purgeGroup);
this._eventSeries = {};
this.cleanGroup();
var s = this.group;
df.forEachRev(this.series, function(item){ item.cleanGroup(s); });
}
var t = this.chart.theme, events = this.events();
for(var i = this.series.length - 1; i >= 0; --i){
var run = this.series[i];
if(!this.dirty && !run.dirty){
t.skip();
this._reconnectEvents(run.name);
continue;
}
run.cleanGroup();
if(!run.data.length){
run.dirty = false;
t.skip();
continue;
}
var theme = t.next("marker", [this.opt, run]), s = run.group, lpoly,
ht = this._hScaler.scaler.getTransformerFromModel(this._hScaler),
vt = this._vScaler.scaler.getTransformerFromModel(this._vScaler);
if(typeof run.data[0] == "number"){
lpoly = arr.map(run.data, function(v, i){
return {
x: ht(i + 1) + offsets.l,
y: dim.height - offsets.b - vt(v)
};
}, this);
}else{
lpoly = arr.map(run.data, function(v, i){
return {
x: ht(v.x) + offsets.l,
y: dim.height - offsets.b - vt(v.y)
};
}, this);
}
var shadowMarkers = new Array(lpoly.length),
frontMarkers = new Array(lpoly.length),
outlineMarkers = new Array(lpoly.length);
arr.forEach(lpoly, function(c, i){
var finalTheme = typeof run.data[i] == "number" ?
t.post(theme, "marker") :
t.addMixin(theme, "marker", run.data[i], true),
path = "M" + c.x + " " + c.y + " " + finalTheme.symbol;
if(finalTheme.marker.shadow){
shadowMarkers[i] = s.createPath("M" + (c.x + finalTheme.marker.shadow.dx) + " " +
(c.y + finalTheme.marker.shadow.dy) + " " + finalTheme.symbol).
setStroke(finalTheme.marker.shadow).setFill(finalTheme.marker.shadow.color);
if(this.animate){
this._animateScatter(shadowMarkers[i], dim.height - offsets.b);
}
}
if(finalTheme.marker.outline){
var outline = dc.makeStroke(finalTheme.marker.outline);
outline.width = 2 * outline.width + finalTheme.marker.stroke.width;
outlineMarkers[i] = s.createPath(path).setStroke(outline);
if(this.animate){
this._animateScatter(outlineMarkers[i], dim.height - offsets.b);
}
}
var stroke = dc.makeStroke(finalTheme.marker.stroke),
fill = this._plotFill(finalTheme.marker.fill, dim, offsets);
if(fill && (fill.type === "linear" || fill.type == "radial")){
var color = gradutils.getColor(fill, {x: c.x, y: c.y});
if(stroke){
stroke.color = color;
}
frontMarkers[i] = s.createPath(path).setStroke(stroke).setFill(color);
}else{
frontMarkers[i] = s.createPath(path).setStroke(stroke).setFill(fill);
}
if(this.animate){
this._animateScatter(frontMarkers[i], dim.height - offsets.b);
}
}, this);
if(frontMarkers.length){
run.dyn.stroke = frontMarkers[frontMarkers.length - 1].getStroke();
run.dyn.fill = frontMarkers[frontMarkers.length - 1].getFill();
}
if(events){
var eventSeries = new Array(frontMarkers.length);
arr.forEach(frontMarkers, function(s, i){
var o = {
element: "marker",
index: i,
run: run,
shape: s,
outline: outlineMarkers && outlineMarkers[i] || null,
shadow: shadowMarkers && shadowMarkers[i] || null,
cx: lpoly[i].x,
cy: lpoly[i].y
};
if(typeof run.data[0] == "number"){
o.x = i + 1;
o.y = run.data[i];
}else{
o.x = run.data[i].x;
o.y = run.data[i].y;
}
this._connectEvents(o);
eventSeries[i] = o;
}, this);
this._eventSeries[run.name] = eventSeries;
}else{
delete this._eventSeries[run.name];
}
run.dirty = false;
}
this.dirty = false;
return this; // dojox.charting.plot2d.Scatter
},
_animateScatter: function(shape, offset){
fx.animateTransform(lang.delegate({
shape: shape,
duration: 1200,
transform: [
{name: "translate", start: [0, offset], end: [0, 0]},
{name: "scale", start: [0, 0], end: [1, 1]},
{name: "original"}
]
}, this.animate)).play();
}
});
});
},
'dojox/lang/functional/scan':function(){
define("dojox/lang/functional/scan", ["dojo/_base/kernel", "dojo/_base/lang", "./lambda"], function(d, darray, df){
// This module adds high-level functions and related constructs:
// - "scan" family of functions
// Notes:
// - missing high-level functions are provided with the compatible API:
// scanl, scanl1, scanr, scanr1
// Defined methods:
// - take any valid lambda argument as the functional argument
// - operate on dense arrays
// - take a string as the array argument
// - take an iterator objects as the array argument (only scanl, and scanl1)
var empty = {};
d.mixin(df, {
// classic reduce-class functions
scanl: function(/*Array|String|Object*/ a, /*Function|String|Array*/ f, /*Object*/ z, /*Object?*/ o){
// summary: repeatedly applies a binary function to an array from left
// to right using a seed value as a starting point; returns an array
// of values produced by foldl() at that point.
if(typeof a == "string"){ a = a.split(""); }
o = o || d.global; f = df.lambda(f);
var t, n, i;
if(d.isArray(a)){
// array
t = new Array((n = a.length) + 1);
t[0] = z;
for(i = 0; i < n; z = f.call(o, z, a[i], i, a), t[++i] = z);
}else if(typeof a.hasNext == "function" && typeof a.next == "function"){
// iterator
t = [z];
for(i = 0; a.hasNext(); t.push(z = f.call(o, z, a.next(), i++, a)));
}else{
// object/dictionary
t = [z];
for(i in a){
if(!(i in empty)){
t.push(z = f.call(o, z, a[i], i, a));
}
}
}
return t; // Array
},
scanl1: function(/*Array|String|Object*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: repeatedly applies a binary function to an array from left
// to right; returns an array of values produced by foldl1() at that
// point.
if(typeof a == "string"){ a = a.split(""); }
o = o || d.global; f = df.lambda(f);
var t, n, z, first = true;
if(d.isArray(a)){
// array
t = new Array(n = a.length);
t[0] = z = a[0];
for(var i = 1; i < n; t[i] = z = f.call(o, z, a[i], i, a), ++i);
}else if(typeof a.hasNext == "function" && typeof a.next == "function"){
// iterator
if(a.hasNext()){
t = [z = a.next()];
for(i = 1; a.hasNext(); t.push(z = f.call(o, z, a.next(), i++, a)));
}
}else{
// object/dictionary
for(i in a){
if(!(i in empty)){
if(first){
t = [z = a[i]];
first = false;
}else{
t.push(z = f.call(o, z, a[i], i, a));
}
}
}
}
return t; // Array
},
scanr: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object*/ z, /*Object?*/ o){
// summary: repeatedly applies a binary function to an array from right
// to left using a seed value as a starting point; returns an array
// of values produced by foldr() at that point.
if(typeof a == "string"){ a = a.split(""); }
o = o || d.global; f = df.lambda(f);
var n = a.length, t = new Array(n + 1), i = n;
t[n] = z;
for(; i > 0; --i, z = f.call(o, z, a[i], i, a), t[i] = z);
return t; // Array
},
scanr1: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: repeatedly applies a binary function to an array from right
// to left; returns an array of values produced by foldr1() at that
// point.
if(typeof a == "string"){ a = a.split(""); }
o = o || d.global; f = df.lambda(f);
var n = a.length, t = new Array(n), z = a[n - 1], i = n - 1;
t[i] = z;
for(; i > 0; --i, z = f.call(o, z, a[i], i, a), t[i] = z);
return t; // Array
}
});
});
},
'dojox/color/_base':function(){
define("dojox/color/_base", ["dojo/_base/kernel", "../main", "dojo/_base/lang", "dojo/_base/Color", "dojo/colors"],
function(dojo, dojox, lang, Color, colors){
var cx = lang.getObject("dojox.color", true);
/*===== cx = dojox.color =====*/
// alias all the dojo.Color mechanisms
cx.Color=Color;
cx.blend=Color.blendColors;
cx.fromRgb=Color.fromRgb;
cx.fromHex=Color.fromHex;
cx.fromArray=Color.fromArray;
cx.fromString=Color.fromString;
// alias the dojo.colors mechanisms
cx.greyscale=colors.makeGrey;
lang.mixin(cx,{
fromCmy: function(/* Object|Array|int */cyan, /*int*/magenta, /*int*/yellow){
// summary
// Create a dojox.color.Color from a CMY defined color.
// All colors should be expressed as 0-100 (percentage)
if(lang.isArray(cyan)){
magenta=cyan[1], yellow=cyan[2], cyan=cyan[0];
} else if(lang.isObject(cyan)){
magenta=cyan.m, yellow=cyan.y, cyan=cyan.c;
}
cyan/=100, magenta/=100, yellow/=100;
var r=1-cyan, g=1-magenta, b=1-yellow;
return new Color({ r:Math.round(r*255), g:Math.round(g*255), b:Math.round(b*255) }); // dojox.color.Color
},
fromCmyk: function(/* Object|Array|int */cyan, /*int*/magenta, /*int*/yellow, /*int*/black){
// summary
// Create a dojox.color.Color from a CMYK defined color.
// All colors should be expressed as 0-100 (percentage)
if(lang.isArray(cyan)){
magenta=cyan[1], yellow=cyan[2], black=cyan[3], cyan=cyan[0];
} else if(lang.isObject(cyan)){
magenta=cyan.m, yellow=cyan.y, black=cyan.b, cyan=cyan.c;
}
cyan/=100, magenta/=100, yellow/=100, black/=100;
var r,g,b;
r = 1-Math.min(1, cyan*(1-black)+black);
g = 1-Math.min(1, magenta*(1-black)+black);
b = 1-Math.min(1, yellow*(1-black)+black);
return new Color({ r:Math.round(r*255), g:Math.round(g*255), b:Math.round(b*255) }); // dojox.color.Color
},
fromHsl: function(/* Object|Array|int */hue, /* int */saturation, /* int */luminosity){
// summary
// Create a dojox.color.Color from an HSL defined color.
// hue from 0-359 (degrees), saturation and luminosity 0-100.
if(lang.isArray(hue)){
saturation=hue[1], luminosity=hue[2], hue=hue[0];
} else if(lang.isObject(hue)){
saturation=hue.s, luminosity=hue.l, hue=hue.h;
}
saturation/=100;
luminosity/=100;
while(hue<0){ hue+=360; }
while(hue>=360){ hue-=360; }
var r, g, b;
if(hue<120){
r=(120-hue)/60, g=hue/60, b=0;
} else if (hue<240){
r=0, g=(240-hue)/60, b=(hue-120)/60;
} else {
r=(hue-240)/60, g=0, b=(360-hue)/60;
}
r=2*saturation*Math.min(r, 1)+(1-saturation);
g=2*saturation*Math.min(g, 1)+(1-saturation);
b=2*saturation*Math.min(b, 1)+(1-saturation);
if(luminosity<0.5){
r*=luminosity, g*=luminosity, b*=luminosity;
}else{
r=(1-luminosity)*r+2*luminosity-1;
g=(1-luminosity)*g+2*luminosity-1;
b=(1-luminosity)*b+2*luminosity-1;
}
return new Color({ r:Math.round(r*255), g:Math.round(g*255), b:Math.round(b*255) }); // dojox.color.Color
}
});
cx.fromHsv = function(/* Object|Array|int */hue, /* int */saturation, /* int */value){
// summary
// Create a dojox.color.Color from an HSV defined color.
// hue from 0-359 (degrees), saturation and value 0-100.
if(lang.isArray(hue)){
saturation=hue[1], value=hue[2], hue=hue[0];
} else if (lang.isObject(hue)){
saturation=hue.s, value=hue.v, hue=hue.h;
}
if(hue==360){ hue=0; }
saturation/=100;
value/=100;
var r, g, b;
if(saturation==0){
r=value, b=value, g=value;
}else{
var hTemp=hue/60, i=Math.floor(hTemp), f=hTemp-i;
var p=value*(1-saturation);
var q=value*(1-(saturation*f));
var t=value*(1-(saturation*(1-f)));
switch(i){
case 0:{ r=value, g=t, b=p; break; }
case 1:{ r=q, g=value, b=p; break; }
case 2:{ r=p, g=value, b=t; break; }
case 3:{ r=p, g=q, b=value; break; }
case 4:{ r=t, g=p, b=value; break; }
case 5:{ r=value, g=p, b=q; break; }
}
}
return new Color({ r:Math.round(r*255), g:Math.round(g*255), b:Math.round(b*255) }); // dojox.color.Color
};
lang.extend(Color,{
toCmy: function(){
// summary
// Convert this Color to a CMY definition.
var cyan=1-(this.r/255), magenta=1-(this.g/255), yellow=1-(this.b/255);
return { c:Math.round(cyan*100), m:Math.round(magenta*100), y:Math.round(yellow*100) }; // Object
},
toCmyk: function(){
// summary
// Convert this Color to a CMYK definition.
var cyan, magenta, yellow, black;
var r=this.r/255, g=this.g/255, b=this.b/255;
black = Math.min(1-r, 1-g, 1-b);
cyan = (1-r-black)/(1-black);
magenta = (1-g-black)/(1-black);
yellow = (1-b-black)/(1-black);
return { c:Math.round(cyan*100), m:Math.round(magenta*100), y:Math.round(yellow*100), b:Math.round(black*100) }; // Object
},
toHsl: function(){
// summary
// Convert this Color to an HSL definition.
var r=this.r/255, g=this.g/255, b=this.b/255;
var min = Math.min(r, b, g), max = Math.max(r, g, b);
var delta = max-min;
var h=0, s=0, l=(min+max)/2;
if(l>0 && l<1){
s = delta/((l<0.5)?(2*l):(2-2*l));
}
if(delta>0){
if(max==r && max!=g){
h+=(g-b)/delta;
}
if(max==g && max!=b){
h+=(2+(b-r)/delta);
}
if(max==b && max!=r){
h+=(4+(r-g)/delta);
}
h*=60;
}
return { h:h, s:Math.round(s*100), l:Math.round(l*100) }; // Object
},
toHsv: function(){
// summary
// Convert this Color to an HSV definition.
var r=this.r/255, g=this.g/255, b=this.b/255;
var min = Math.min(r, b, g), max = Math.max(r, g, b);
var delta = max-min;
var h = null, s = (max==0)?0:(delta/max);
if(s==0){
h = 0;
}else{
if(r==max){
h = 60*(g-b)/delta;
}else if(g==max){
h = 120 + 60*(b-r)/delta;
}else{
h = 240 + 60*(r-g)/delta;
}
if(h<0){ h+=360; }
}
return { h:h, s:Math.round(s*100), v:Math.round(max*100) }; // Object
}
});
return cx;
});
},
'dojox/charting/plot2d/OHLC':function(){
define(["dojo/_base/lang", "dojo/_base/array", "dojo/_base/declare", "./Base", "./common",
"dojox/lang/functional", "dojox/lang/functional/reversed", "dojox/lang/utils", "dojox/gfx/fx"],
function(lang, arr, declare, Base, dc, df, dfr, du, fx){
/*=====
var Base = dojox.charting.plot2d.Base;
=====*/
var purgeGroup = dfr.lambda("item.purgeGroup()");
// Candlesticks are based on the Bars plot type; we expect the following passed
// as values in a series:
// { x?, open, close, high, low }
// if x is not provided, the array index is used.
// failing to provide the OHLC values will throw an error.
return declare("dojox.charting.plot2d.OHLC", Base, {
// summary:
// A plot that represents typical open/high/low/close (financial reporting, primarily).
// Unlike most charts, the Candlestick expects data points to be represented by
// an object of the form { x?, open, close, high, low, mid? }, where both
// x and mid are optional parameters. If x is not provided, the index of the
// data array is used.
defaultParams: {
hAxis: "x", // use a horizontal axis named "x"
vAxis: "y", // use a vertical axis named "y"
gap: 2, // gap between columns in pixels
animate: null // animate chart to place
},
optionalParams: {
minBarSize: 1, // minimal bar size in pixels
maxBarSize: 1, // maximal bar size in pixels
// theme component
stroke: {},
outline: {},
shadow: {},
fill: {},
font: "",
fontColor: ""
},
constructor: function(chart, kwArgs){
// summary:
// The constructor for a candlestick chart.
// chart: dojox.charting.Chart
// The chart this plot belongs to.
// kwArgs: dojox.charting.plot2d.__BarCtorArgs?
// An optional keyword arguments object to help define the plot.
this.opt = lang.clone(this.defaultParams);
du.updateWithObject(this.opt, kwArgs);
du.updateWithPattern(this.opt, kwArgs, this.optionalParams);
this.series = [];
this.hAxis = this.opt.hAxis;
this.vAxis = this.opt.vAxis;
this.animate = this.opt.animate;
},
collectStats: function(series){
// summary:
// Collect all statistics for drawing this chart. Since the common
// functionality only assumes x and y, OHLC must create it's own
// stats (since data has no y value, but open/close/high/low instead).
// series: dojox.charting.Series[]
// The data series array to be drawn on this plot.
// returns: Object
// Returns an object in the form of { hmin, hmax, vmin, vmax }.
// we have to roll our own, since we need to use all four passed
// values to figure out our stats, and common only assumes x and y.
var stats = lang.delegate(dc.defaultStats);
for(var i=0; i<series.length; i++){
var run = series[i];
if(!run.data.length){ continue; }
var old_vmin = stats.vmin, old_vmax = stats.vmax;
if(!("ymin" in run) || !("ymax" in run)){
arr.forEach(run.data, function(val, idx){
if(val !== null){
var x = val.x || idx + 1;
stats.hmin = Math.min(stats.hmin, x);
stats.hmax = Math.max(stats.hmax, x);
stats.vmin = Math.min(stats.vmin, val.open, val.close, val.high, val.low);
stats.vmax = Math.max(stats.vmax, val.open, val.close, val.high, val.low);
}
});
}
if("ymin" in run){ stats.vmin = Math.min(old_vmin, run.ymin); }
if("ymax" in run){ stats.vmax = Math.max(old_vmax, run.ymax); }
}
return stats;
},
getSeriesStats: function(){
// summary:
// Calculate the min/max on all attached series in both directions.
// returns: Object
// {hmin, hmax, vmin, vmax} min/max in both directions.
var stats = this.collectStats(this.series);
stats.hmin -= 0.5;
stats.hmax += 0.5;
return stats;
},
render: function(dim, offsets){
// summary:
// Run the calculations for any axes for this plot.
// dim: Object
// An object in the form of { width, height }
// offsets: Object
// An object of the form { l, r, t, b}.
// returns: dojox.charting.plot2d.OHLC
// A reference to this plot for functional chaining.
if(this.zoom && !this.isDataDirty()){
return this.performZoom(dim, offsets);
}
this.resetEvents();
this.dirty = this.isDirty();
if(this.dirty){
arr.forEach(this.series, purgeGroup);
this._eventSeries = {};
this.cleanGroup();
var s = this.group;
df.forEachRev(this.series, function(item){ item.cleanGroup(s); });
}
var t = this.chart.theme, f, gap, width,
ht = this._hScaler.scaler.getTransformerFromModel(this._hScaler),
vt = this._vScaler.scaler.getTransformerFromModel(this._vScaler),
baseline = Math.max(0, this._vScaler.bounds.lower),
baselineHeight = vt(baseline),
events = this.events();
f = dc.calculateBarSize(this._hScaler.bounds.scale, this.opt);
gap = f.gap;
width = f.size;
for(var i = this.series.length - 1; i >= 0; --i){
var run = this.series[i];
if(!this.dirty && !run.dirty){
t.skip();
this._reconnectEvents(run.name);
continue;
}
run.cleanGroup();
var theme = t.next("candlestick", [this.opt, run]), s = run.group,
eventSeries = new Array(run.data.length);
for(var j = 0; j < run.data.length; ++j){
var v = run.data[j];
if(v !== null){
var finalTheme = t.addMixin(theme, "candlestick", v, true);
// calculate the points we need for OHLC
var x = ht(v.x || (j+0.5)) + offsets.l + gap,
y = dim.height - offsets.b,
open = vt(v.open),
close = vt(v.close),
high = vt(v.high),
low = vt(v.low);
if(low > high){
var tmp = high;
high = low;
low = tmp;
}
if(width >= 1){
var hl = {x1: width/2, x2: width/2, y1: y - high, y2: y - low},
op = {x1: 0, x2: ((width/2) + ((finalTheme.series.stroke.width||1)/2)), y1: y-open, y2: y-open},
cl = {x1: ((width/2) - ((finalTheme.series.stroke.width||1)/2)), x2: width, y1: y-close, y2: y-close};
var shape = s.createGroup();
shape.setTransform({dx: x, dy: 0});
var inner = shape.createGroup();
inner.createLine(hl).setStroke(finalTheme.series.stroke);
inner.createLine(op).setStroke(finalTheme.series.stroke);
inner.createLine(cl).setStroke(finalTheme.series.stroke);
// TODO: double check this.
run.dyn.stroke = finalTheme.series.stroke;
if(events){
var o = {
element: "candlestick",
index: j,
run: run,
shape: inner,
x: x,
y: y-Math.max(open, close),
cx: width/2,
cy: (y-Math.max(open, close)) + (Math.max(open > close ? open-close : close-open, 1)/2),
width: width,
height: Math.max(open > close ? open-close : close-open, 1),
data: v
};
this._connectEvents(o);
eventSeries[j] = o;
}
}
if(this.animate){
this._animateOHLC(shape, y - low, high - low);
}
}
}
this._eventSeries[run.name] = eventSeries;
run.dirty = false;
}
this.dirty = false;
return this; // dojox.charting.plot2d.OHLC
},
_animateOHLC: function(shape, voffset, vsize){
fx.animateTransform(lang.delegate({
shape: shape,
duration: 1200,
transform: [
{name: "translate", start: [0, voffset - (voffset/vsize)], end: [0, 0]},
{name: "scale", start: [1, 1/vsize], end: [1, 1]},
{name: "original"}
]
}, this.animate)).play();
}
});
});
},
'dojox/charting/plot2d/ClusteredColumns':function(){
define("dojox/charting/plot2d/ClusteredColumns", ["dojo/_base/array", "dojo/_base/declare", "./Columns", "./common",
"dojox/lang/functional", "dojox/lang/functional/reversed", "dojox/lang/utils"],
function(arr, declare, Columns, dc, df, dfr, du){
/*=====
var Columns = dojox.charting.plot2d.Columns;
=====*/
var purgeGroup = dfr.lambda("item.purgeGroup()");
return declare("dojox.charting.plot2d.ClusteredColumns", Columns, {
// summary:
// A plot representing grouped or clustered columns (vertical bars).
render: function(dim, offsets){
// summary:
// Run the calculations for any axes for this plot.
// dim: Object
// An object in the form of { width, height }
// offsets: Object
// An object of the form { l, r, t, b}.
// returns: dojox.charting.plot2d.ClusteredColumns
// A reference to this plot for functional chaining.
if(this.zoom && !this.isDataDirty()){
return this.performZoom(dim, offsets);
}
this.resetEvents();
this.dirty = this.isDirty();
if(this.dirty){
arr.forEach(this.series, purgeGroup);
this._eventSeries = {};
this.cleanGroup();
var s = this.group;
df.forEachRev(this.series, function(item){ item.cleanGroup(s); });
}
var t = this.chart.theme, f, gap, width, thickness,
ht = this._hScaler.scaler.getTransformerFromModel(this._hScaler),
vt = this._vScaler.scaler.getTransformerFromModel(this._vScaler),
baseline = Math.max(0, this._vScaler.bounds.lower),
baselineHeight = vt(baseline),
events = this.events();
f = dc.calculateBarSize(this._hScaler.bounds.scale, this.opt, this.series.length);
gap = f.gap;
width = thickness = f.size;
for(var i = 0; i < this.series.length; ++i){
var run = this.series[i], shift = thickness * i;
if(!this.dirty && !run.dirty){
t.skip();
this._reconnectEvents(run.name);
continue;
}
run.cleanGroup();
var theme = t.next("column", [this.opt, run]), s = run.group,
eventSeries = new Array(run.data.length);
for(var j = 0; j < run.data.length; ++j){
var value = run.data[j];
if(value !== null){
var v = typeof value == "number" ? value : value.y,
vv = vt(v),
height = vv - baselineHeight,
h = Math.abs(height),
finalTheme = typeof value != "number" ?
t.addMixin(theme, "column", value, true) :
t.post(theme, "column");
if(width >= 1 && h >= 0){
var rect = {
x: offsets.l + ht(j + 0.5) + gap + shift,
y: dim.height - offsets.b - (v > baseline ? vv : baselineHeight),
width: width, height: h
};
var specialFill = this._plotFill(finalTheme.series.fill, dim, offsets);
specialFill = this._shapeFill(specialFill, rect);
var shape = s.createRect(rect).setFill(specialFill).setStroke(finalTheme.series.stroke);
run.dyn.fill = shape.getFill();
run.dyn.stroke = shape.getStroke();
if(events){
var o = {
element: "column",
index: j,
run: run,
shape: shape,
x: j + 0.5,
y: v
};
this._connectEvents(o);
eventSeries[j] = o;
}
if(this.animate){
this._animateColumn(shape, dim.height - offsets.b - baselineHeight, h);
}
}
}
}
this._eventSeries[run.name] = eventSeries;
run.dirty = false;
}
this.dirty = false;
return this; // dojox.charting.plot2d.ClusteredColumns
}
});
});
},
'dojox/charting/Chart':function(){
define("dojox/charting/Chart", ["dojo/_base/lang", "dojo/_base/array","dojo/_base/declare", "dojo/_base/html",
"dojo/dom", "dojo/dom-geometry", "dojo/dom-construct","dojo/_base/Color", "dojo/_base/sniff",
"./Element", "./Theme", "./Series", "./axis2d/common",
"dojox/gfx", "dojox/lang/functional", "dojox/lang/functional/fold", "dojox/lang/functional/reversed"],
function(lang, arr, declare, html,
dom, domGeom, domConstruct, Color, has,
Element, Theme, Series, common,
g, func, funcFold, funcReversed){
/*=====
dojox.charting.__ChartCtorArgs = function(margins, stroke, fill, delayInMs){
// summary:
// The keyword arguments that can be passed in a Chart constructor.
//
// margins: Object?
// Optional margins for the chart, in the form of { l, t, r, b}.
// stroke: dojox.gfx.Stroke?
// An optional outline/stroke for the chart.
// fill: dojox.gfx.Fill?
// An optional fill for the chart.
// delayInMs: Number
// Delay in ms for delayedRender(). Default: 200.
this.margins = margins;
this.stroke = stroke;
this.fill = fill;
this.delayInMs = delayInMs;
}
=====*/
var dc = dojox.charting,
clear = func.lambda("item.clear()"),
purge = func.lambda("item.purgeGroup()"),
destroy = func.lambda("item.destroy()"),
makeClean = func.lambda("item.dirty = false"),
makeDirty = func.lambda("item.dirty = true"),
getName = func.lambda("item.name");
declare("dojox.charting.Chart", null, {
// summary:
// The main chart object in dojox.charting. This will create a two dimensional
// chart based on dojox.gfx.
//
// description:
// dojox.charting.Chart is the primary object used for any kind of charts. It
// is simple to create--just pass it a node reference, which is used as the
// container for the chart--and a set of optional keyword arguments and go.
//
// Note that like most of dojox.gfx, most of dojox.charting.Chart's methods are
// designed to return a reference to the chart itself, to allow for functional
// chaining. This makes defining everything on a Chart very easy to do.
//
// example:
// Create an area chart, with smoothing.
// | new dojox.charting.Chart(node))
// | .addPlot("default", { type: "Areas", tension: "X" })
// | .setTheme(dojox.charting.themes.Shrooms)
// | .addSeries("Series A", [1, 2, 0.5, 1.5, 1, 2.8, 0.4])
// | .addSeries("Series B", [2.6, 1.8, 2, 1, 1.4, 0.7, 2])
// | .addSeries("Series C", [6.3, 1.8, 3, 0.5, 4.4, 2.7, 2])
// | .render();
//
// example:
// The form of data in a data series can take a number of forms: a simple array,
// an array of objects {x,y}, or something custom (as determined by the plot).
// Here's an example of a Candlestick chart, which expects an object of
// { open, high, low, close }.
// | new dojox.charting.Chart(node))
// | .addPlot("default", {type: "Candlesticks", gap: 1})
// | .addAxis("x", {fixLower: "major", fixUpper: "major", includeZero: true})
// | .addAxis("y", {vertical: true, fixLower: "major", fixUpper: "major", natural: true})
// | .addSeries("Series A", [
// | { open: 20, close: 16, high: 22, low: 8 },
// | { open: 16, close: 22, high: 26, low: 6, mid: 18 },
// | { open: 22, close: 18, high: 22, low: 11, mid: 21 },
// | { open: 18, close: 29, high: 32, low: 14, mid: 27 },
// | { open: 29, close: 24, high: 29, low: 13, mid: 27 },
// | { open: 24, close: 8, high: 24, low: 5 },
// | { open: 8, close: 16, high: 22, low: 2 },
// | { open: 16, close: 12, high: 19, low: 7 },
// | { open: 12, close: 20, high: 22, low: 8 },
// | { open: 20, close: 16, high: 22, low: 8 },
// | { open: 16, close: 22, high: 26, low: 6, mid: 18 },
// | { open: 22, close: 18, high: 22, low: 11, mid: 21 },
// | { open: 18, close: 29, high: 32, low: 14, mid: 27 },
// | { open: 29, close: 24, high: 29, low: 13, mid: 27 },
// | { open: 24, close: 8, high: 24, low: 5 },
// | { open: 8, close: 16, high: 22, low: 2 },
// | { open: 16, close: 12, high: 19, low: 7 },
// | { open: 12, close: 20, high: 22, low: 8 },
// | { open: 20, close: 16, high: 22, low: 8 },
// | { open: 16, close: 22, high: 26, low: 6 },
// | { open: 22, close: 18, high: 22, low: 11 },
// | { open: 18, close: 29, high: 32, low: 14 },
// | { open: 29, close: 24, high: 29, low: 13 },
// | { open: 24, close: 8, high: 24, low: 5 },
// | { open: 8, close: 16, high: 22, low: 2 },
// | { open: 16, close: 12, high: 19, low: 7 },
// | { open: 12, close: 20, high: 22, low: 8 },
// | { open: 20, close: 16, high: 22, low: 8 }
// | ],
// | { stroke: { color: "green" }, fill: "lightgreen" }
// | )
// | .render();
// theme: dojox.charting.Theme?
// An optional theme to use for styling the chart.
// axes: dojox.charting.Axis{}?
// A map of axes for use in plotting a chart.
// stack: dojox.charting.plot2d.Base[]
// A stack of plotters.
// plots: dojox.charting.plot2d.Base{}
// A map of plotter indices
// series: dojox.charting.Series[]
// The stack of data runs used to create plots.
// runs: dojox.charting.Series{}
// A map of series indices
// margins: Object?
// The margins around the chart. Default is { l:10, t:10, r:10, b:10 }.
// stroke: dojox.gfx.Stroke?
// The outline of the chart (stroke in vector graphics terms).
// fill: dojox.gfx.Fill?
// The color for the chart.
// node: DOMNode
// The container node passed to the constructor.
// surface: dojox.gfx.Surface
// The main graphics surface upon which a chart is drawn.
// dirty: Boolean
// A boolean flag indicating whether or not the chart needs to be updated/re-rendered.
// coords: Object
// The coordinates on a page of the containing node, as returned from dojo.coords.
constructor: function(/* DOMNode */node, /* dojox.charting.__ChartCtorArgs? */kwArgs){
// summary:
// The constructor for a new Chart. Initializes all parameters used for a chart.
// returns: dojox.charting.Chart
// The newly created chart.
// initialize parameters
if(!kwArgs){ kwArgs = {}; }
this.margins = kwArgs.margins ? kwArgs.margins : {l: 10, t: 10, r: 10, b: 10};
this.stroke = kwArgs.stroke;
this.fill = kwArgs.fill;
this.delayInMs = kwArgs.delayInMs || 200;
this.title = kwArgs.title;
this.titleGap = kwArgs.titleGap;
this.titlePos = kwArgs.titlePos;
this.titleFont = kwArgs.titleFont;
this.titleFontColor = kwArgs.titleFontColor;
this.chartTitle = null;
// default initialization
this.theme = null;
this.axes = {}; // map of axes
this.stack = []; // stack of plotters
this.plots = {}; // map of plotter indices
this.series = []; // stack of data runs
this.runs = {}; // map of data run indices
this.dirty = true;
this.coords = null;
// create a surface
this.node = dom.byId(node);
var box = domGeom.getMarginBox(node);
this.surface = g.createSurface(this.node, box.w || 400, box.h || 300);
},
destroy: function(){
// summary:
// Cleanup when a chart is to be destroyed.
// returns: void
arr.forEach(this.series, destroy);
arr.forEach(this.stack, destroy);
func.forIn(this.axes, destroy);
if(this.chartTitle && this.chartTitle.tagName){
// destroy title if it is a DOM node
domConstruct.destroy(this.chartTitle);
}
this.surface.destroy();
},
getCoords: function(){
// summary:
// Get the coordinates and dimensions of the containing DOMNode, as
// returned by dojo.coords.
// returns: Object
// The resulting coordinates of the chart. See dojo.coords for details.
return html.coords(this.node, true); // Object
},
setTheme: function(theme){
// summary:
// Set a theme of the chart.
// theme: dojox.charting.Theme
// The theme to be used for visual rendering.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
this.theme = theme.clone();
this.dirty = true;
return this; // dojox.charting.Chart
},
addAxis: function(name, kwArgs){
// summary:
// Add an axis to the chart, for rendering.
// name: String
// The name of the axis.
// kwArgs: dojox.charting.axis2d.__AxisCtorArgs?
// An optional keyword arguments object for use in defining details of an axis.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
var axis, axisType = kwArgs && kwArgs.type || "Default";
if(typeof axisType == "string"){
if(!dc.axis2d || !dc.axis2d[axisType]){
throw Error("Can't find axis: " + axisType + " - Check " + "require() dependencies.");
}
axis = new dc.axis2d[axisType](this, kwArgs);
}else{
axis = new axisType(this, kwArgs);
}
axis.name = name;
axis.dirty = true;
if(name in this.axes){
this.axes[name].destroy();
}
this.axes[name] = axis;
this.dirty = true;
return this; // dojox.charting.Chart
},
getAxis: function(name){
// summary:
// Get the given axis, by name.
// name: String
// The name the axis was defined by.
// returns: dojox.charting.axis2d.Default
// The axis as stored in the chart's axis map.
return this.axes[name]; // dojox.charting.axis2d.Default
},
removeAxis: function(name){
// summary:
// Remove the axis that was defined using name.
// name: String
// The axis name, as defined in addAxis.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
if(name in this.axes){
// destroy the axis
this.axes[name].destroy();
delete this.axes[name];
// mark the chart as dirty
this.dirty = true;
}
return this; // dojox.charting.Chart
},
addPlot: function(name, kwArgs){
// summary:
// Add a new plot to the chart, defined by name and using the optional keyword arguments object.
// Note that dojox.charting assumes the main plot to be called "default"; if you do not have
// a plot called "default" and attempt to add data series to the chart without specifying the
// plot to be rendered on, you WILL get errors.
// name: String
// The name of the plot to be added to the chart. If you only plan on using one plot, call it "default".
// kwArgs: dojox.charting.plot2d.__PlotCtorArgs
// An object with optional parameters for the plot in question.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
var plot, plotType = kwArgs && kwArgs.type || "Default";
if(typeof plotType == "string"){
if(!dc.plot2d || !dc.plot2d[plotType]){
throw Error("Can't find plot: " + plotType + " - didn't you forget to dojo" + ".require() it?");
}
plot = new dc.plot2d[plotType](this, kwArgs);
}else{
plot = new plotType(this, kwArgs);
}
plot.name = name;
plot.dirty = true;
if(name in this.plots){
this.stack[this.plots[name]].destroy();
this.stack[this.plots[name]] = plot;
}else{
this.plots[name] = this.stack.length;
this.stack.push(plot);
}
this.dirty = true;
return this; // dojox.charting.Chart
},
getPlot: function(name){
// summary:
// Get the given plot, by name.
// name: String
// The name the plot was defined by.
// returns: dojox.charting.plot2d.Base
// The plot.
return this.stack[this.plots[name]];
},
removePlot: function(name){
// summary:
// Remove the plot defined using name from the chart's plot stack.
// name: String
// The name of the plot as defined using addPlot.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
if(name in this.plots){
// get the index and remove the name
var index = this.plots[name];
delete this.plots[name];
// destroy the plot
this.stack[index].destroy();
// remove the plot from the stack
this.stack.splice(index, 1);
// update indices to reflect the shift
func.forIn(this.plots, function(idx, name, plots){
if(idx > index){
plots[name] = idx - 1;
}
});
// remove all related series
var ns = arr.filter(this.series, function(run){ return run.plot != name; });
if(ns.length < this.series.length){
// kill all removed series
arr.forEach(this.series, function(run){
if(run.plot == name){
run.destroy();
}
});
// rebuild all necessary data structures
this.runs = {};
arr.forEach(ns, function(run, index){
this.runs[run.plot] = index;
}, this);
this.series = ns;
}
// mark the chart as dirty
this.dirty = true;
}
return this; // dojox.charting.Chart
},
getPlotOrder: function(){
// summary:
// Returns an array of plot names in the current order
// (the top-most plot is the first).
// returns: Array
return func.map(this.stack, getName); // Array
},
setPlotOrder: function(newOrder){
// summary:
// Sets new order of plots. newOrder cannot add or remove
// plots. Wrong names, or dups are ignored.
// newOrder: Array:
// Array of plot names compatible with getPlotOrder().
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
var names = {},
order = func.filter(newOrder, function(name){
if(!(name in this.plots) || (name in names)){
return false;
}
names[name] = 1;
return true;
}, this);
if(order.length < this.stack.length){
func.forEach(this.stack, function(plot){
var name = plot.name;
if(!(name in names)){
order.push(name);
}
});
}
var newStack = func.map(order, function(name){
return this.stack[this.plots[name]];
}, this);
func.forEach(newStack, function(plot, i){
this.plots[plot.name] = i;
}, this);
this.stack = newStack;
this.dirty = true;
return this; // dojox.charting.Chart
},
movePlotToFront: function(name){
// summary:
// Moves a given plot to front.
// name: String:
// Plot's name to move.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
if(name in this.plots){
var index = this.plots[name];
if(index){
var newOrder = this.getPlotOrder();
newOrder.splice(index, 1);
newOrder.unshift(name);
return this.setPlotOrder(newOrder); // dojox.charting.Chart
}
}
return this; // dojox.charting.Chart
},
movePlotToBack: function(name){
// summary:
// Moves a given plot to back.
// name: String:
// Plot's name to move.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
if(name in this.plots){
var index = this.plots[name];
if(index < this.stack.length - 1){
var newOrder = this.getPlotOrder();
newOrder.splice(index, 1);
newOrder.push(name);
return this.setPlotOrder(newOrder); // dojox.charting.Chart
}
}
return this; // dojox.charting.Chart
},
addSeries: function(name, data, kwArgs){
// summary:
// Add a data series to the chart for rendering.
// name: String:
// The name of the data series to be plotted.
// data: Array|Object:
// The array of data points (either numbers or objects) that
// represents the data to be drawn. Or it can be an object. In
// the latter case, it should have a property "data" (an array),
// destroy(), and setSeriesObject().
// kwArgs: dojox.charting.__SeriesCtorArgs?:
// An optional keyword arguments object that will be mixed into
// the resultant series object.
// returns: dojox.charting.Chart:
// A reference to the current chart for functional chaining.
var run = new Series(this, data, kwArgs);
run.name = name;
if(name in this.runs){
this.series[this.runs[name]].destroy();
this.series[this.runs[name]] = run;
}else{
this.runs[name] = this.series.length;
this.series.push(run);
}
this.dirty = true;
// fix min/max
if(!("ymin" in run) && "min" in run){ run.ymin = run.min; }
if(!("ymax" in run) && "max" in run){ run.ymax = run.max; }
return this; // dojox.charting.Chart
},
getSeries: function(name){
// summary:
// Get the given series, by name.
// name: String
// The name the series was defined by.
// returns: dojox.charting.Series
// The series.
return this.series[this.runs[name]];
},
removeSeries: function(name){
// summary:
// Remove the series defined by name from the chart.
// name: String
// The name of the series as defined by addSeries.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
if(name in this.runs){
// get the index and remove the name
var index = this.runs[name];
delete this.runs[name];
// destroy the run
this.series[index].destroy();
// remove the run from the stack of series
this.series.splice(index, 1);
// update indices to reflect the shift
func.forIn(this.runs, function(idx, name, runs){
if(idx > index){
runs[name] = idx - 1;
}
});
this.dirty = true;
}
return this; // dojox.charting.Chart
},
updateSeries: function(name, data){
// summary:
// Update the given series with a new set of data points.
// name: String
// The name of the series as defined in addSeries.
// data: Array|Object:
// The array of data points (either numbers or objects) that
// represents the data to be drawn. Or it can be an object. In
// the latter case, it should have a property "data" (an array),
// destroy(), and setSeriesObject().
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
if(name in this.runs){
var run = this.series[this.runs[name]];
run.update(data);
this._invalidateDependentPlots(run.plot, false);
this._invalidateDependentPlots(run.plot, true);
}
return this; // dojox.charting.Chart
},
getSeriesOrder: function(plotName){
// summary:
// Returns an array of series names in the current order
// (the top-most series is the first) within a plot.
// plotName: String:
// Plot's name.
// returns: Array
return func.map(func.filter(this.series, function(run){
return run.plot == plotName;
}), getName);
},
setSeriesOrder: function(newOrder){
// summary:
// Sets new order of series within a plot. newOrder cannot add
// or remove series. Wrong names, or dups are ignored.
// newOrder: Array:
// Array of series names compatible with getPlotOrder(). All
// series should belong to the same plot.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
var plotName, names = {},
order = func.filter(newOrder, function(name){
if(!(name in this.runs) || (name in names)){
return false;
}
var run = this.series[this.runs[name]];
if(plotName){
if(run.plot != plotName){
return false;
}
}else{
plotName = run.plot;
}
names[name] = 1;
return true;
}, this);
func.forEach(this.series, function(run){
var name = run.name;
if(!(name in names) && run.plot == plotName){
order.push(name);
}
});
var newSeries = func.map(order, function(name){
return this.series[this.runs[name]];
}, this);
this.series = newSeries.concat(func.filter(this.series, function(run){
return run.plot != plotName;
}));
func.forEach(this.series, function(run, i){
this.runs[run.name] = i;
}, this);
this.dirty = true;
return this; // dojox.charting.Chart
},
moveSeriesToFront: function(name){
// summary:
// Moves a given series to front of a plot.
// name: String:
// Series' name to move.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
if(name in this.runs){
var index = this.runs[name],
newOrder = this.getSeriesOrder(this.series[index].plot);
if(name != newOrder[0]){
newOrder.splice(index, 1);
newOrder.unshift(name);
return this.setSeriesOrder(newOrder); // dojox.charting.Chart
}
}
return this; // dojox.charting.Chart
},
moveSeriesToBack: function(name){
// summary:
// Moves a given series to back of a plot.
// name: String:
// Series' name to move.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
if(name in this.runs){
var index = this.runs[name],
newOrder = this.getSeriesOrder(this.series[index].plot);
if(name != newOrder[newOrder.length - 1]){
newOrder.splice(index, 1);
newOrder.push(name);
return this.setSeriesOrder(newOrder); // dojox.charting.Chart
}
}
return this; // dojox.charting.Chart
},
resize: function(width, height){
// summary:
// Resize the chart to the dimensions of width and height.
// description:
// Resize the chart and its surface to the width and height dimensions.
// If no width/height or box is provided, resize the surface to the marginBox of the chart.
// width: Number
// The new width of the chart.
// height: Number
// The new height of the chart.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
var box;
switch(arguments.length){
// case 0, do not resize the div, just the surface
case 1:
// argument, override node box
box = lang.mixin({}, width);
domGeom.setMarginBox(this.node, box);
break;
case 2:
box = {w: width, h: height};
// argument, override node box
domGeom.setMarginBox(this.node, box);
break;
}
// in all cases take back the computed box
box = domGeom.getMarginBox(this.node);
var d = this.surface.getDimensions();
if(d.width != box.w || d.height != box.h){
// and set it on the surface
this.surface.setDimensions(box.w, box.h);
this.dirty = true;
return this.render(); // dojox.charting.Chart
}else{
return this;
}
},
getGeometry: function(){
// summary:
// Returns a map of information about all axes in a chart and what they represent
// in terms of scaling (see dojox.charting.axis2d.Default.getScaler).
// returns: Object
// An map of geometry objects, a one-to-one mapping of axes.
var ret = {};
func.forIn(this.axes, function(axis){
if(axis.initialized()){
ret[axis.name] = {
name: axis.name,
vertical: axis.vertical,
scaler: axis.scaler,
ticks: axis.ticks
};
}
});
return ret; // Object
},
setAxisWindow: function(name, scale, offset, zoom){
// summary:
// Zooms an axis and all dependent plots. Can be used to zoom in 1D.
// name: String
// The name of the axis as defined by addAxis.
// scale: Number
// The scale on the target axis.
// offset: Number
// Any offest, as measured by axis tick
// zoom: Boolean|Object?
// The chart zooming animation trigger. This is null by default,
// e.g. {duration: 1200}, or just set true.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
var axis = this.axes[name];
if(axis){
axis.setWindow(scale, offset);
arr.forEach(this.stack,function(plot){
if(plot.hAxis == name || plot.vAxis == name){
plot.zoom = zoom;
}
});
}
return this; // dojox.charting.Chart
},
setWindow: function(sx, sy, dx, dy, zoom){
// summary:
// Zooms in or out any plots in two dimensions.
// sx: Number
// The scale for the x axis.
// sy: Number
// The scale for the y axis.
// dx: Number
// The pixel offset on the x axis.
// dy: Number
// The pixel offset on the y axis.
// zoom: Boolean|Object?
// The chart zooming animation trigger. This is null by default,
// e.g. {duration: 1200}, or just set true.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
if(!("plotArea" in this)){
this.calculateGeometry();
}
func.forIn(this.axes, function(axis){
var scale, offset, bounds = axis.getScaler().bounds,
s = bounds.span / (bounds.upper - bounds.lower);
if(axis.vertical){
scale = sy;
offset = dy / s / scale;
}else{
scale = sx;
offset = dx / s / scale;
}
axis.setWindow(scale, offset);
});
arr.forEach(this.stack, function(plot){ plot.zoom = zoom; });
return this; // dojox.charting.Chart
},
zoomIn: function(name, range){
// summary:
// Zoom the chart to a specific range on one axis. This calls render()
// directly as a convenience method.
// name: String
// The name of the axis as defined by addAxis.
// range: Array
// The end points of the zoom range, measured in axis ticks.
var axis = this.axes[name];
if(axis){
var scale, offset, bounds = axis.getScaler().bounds;
var lower = Math.min(range[0],range[1]);
var upper = Math.max(range[0],range[1]);
lower = range[0] < bounds.lower ? bounds.lower : lower;
upper = range[1] > bounds.upper ? bounds.upper : upper;
scale = (bounds.upper - bounds.lower) / (upper - lower);
offset = lower - bounds.lower;
this.setAxisWindow(name, scale, offset);
this.render();
}
},
calculateGeometry: function(){
// summary:
// Calculate the geometry of the chart based on the defined axes of
// a chart.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
if(this.dirty){
return this.fullGeometry();
}
// calculate geometry
var dirty = arr.filter(this.stack, function(plot){
return plot.dirty ||
(plot.hAxis && this.axes[plot.hAxis].dirty) ||
(plot.vAxis && this.axes[plot.vAxis].dirty);
}, this);
calculateAxes(dirty, this.plotArea);
return this; // dojox.charting.Chart
},
fullGeometry: function(){
// summary:
// Calculate the full geometry of the chart. This includes passing
// over all major elements of a chart (plots, axes, series, container)
// in order to ensure proper rendering.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
this._makeDirty();
// clear old values
arr.forEach(this.stack, clear);
// rebuild new connections, and add defaults
// set up a theme
if(!this.theme){
this.setTheme(new Theme(dojox.charting._def));
}
// assign series
arr.forEach(this.series, function(run){
if(!(run.plot in this.plots)){
if(!dc.plot2d || !dc.plot2d.Default){
throw Error("Can't find plot: Default - didn't you forget to dojo" + ".require() it?");
}
var plot = new dc.plot2d.Default(this, {});
plot.name = run.plot;
this.plots[run.plot] = this.stack.length;
this.stack.push(plot);
}
this.stack[this.plots[run.plot]].addSeries(run);
}, this);
// assign axes
arr.forEach(this.stack, function(plot){
if(plot.hAxis){
plot.setAxis(this.axes[plot.hAxis]);
}
if(plot.vAxis){
plot.setAxis(this.axes[plot.vAxis]);
}
}, this);
// calculate geometry
// 1st pass
var dim = this.dim = this.surface.getDimensions();
dim.width = g.normalizedLength(dim.width);
dim.height = g.normalizedLength(dim.height);
func.forIn(this.axes, clear);
calculateAxes(this.stack, dim);
// assumption: we don't have stacked axes yet
var offsets = this.offsets = { l: 0, r: 0, t: 0, b: 0 };
func.forIn(this.axes, function(axis){
func.forIn(axis.getOffsets(), function(o, i){ offsets[i] += o; });
});
// add title area
if(this.title){
this.titleGap = (this.titleGap==0) ? 0 : this.titleGap || this.theme.chart.titleGap || 20;
this.titlePos = this.titlePos || this.theme.chart.titlePos || "top";
this.titleFont = this.titleFont || this.theme.chart.titleFont;
this.titleFontColor = this.titleFontColor || this.theme.chart.titleFontColor || "black";
var tsize = g.normalizedLength(g.splitFontString(this.titleFont).size);
offsets[this.titlePos=="top" ? "t":"b"] += (tsize + this.titleGap);
}
// add margins
func.forIn(this.margins, function(o, i){ offsets[i] += o; });
// 2nd pass with realistic dimensions
this.plotArea = {
width: dim.width - offsets.l - offsets.r,
height: dim.height - offsets.t - offsets.b
};
func.forIn(this.axes, clear);
calculateAxes(this.stack, this.plotArea);
return this; // dojox.charting.Chart
},
render: function(){
// summary:
// Render the chart according to the current information defined. This should
// be the last call made when defining/creating a chart, or if data within the
// chart has been changed.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
if(this.theme){
this.theme.clear();
}
if(this.dirty){
return this.fullRender();
}
this.calculateGeometry();
// go over the stack backwards
func.forEachRev(this.stack, function(plot){ plot.render(this.dim, this.offsets); }, this);
// go over axes
func.forIn(this.axes, function(axis){ axis.render(this.dim, this.offsets); }, this);
this._makeClean();
// BEGIN FOR HTML CANVAS
if(this.surface.render){ this.surface.render(); };
// END FOR HTML CANVAS
return this; // dojox.charting.Chart
},
fullRender: function(){
// summary:
// Force a full rendering of the chart, including full resets on the chart itself.
// You should not call this method directly unless absolutely necessary.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
// calculate geometry
this.fullGeometry();
var offsets = this.offsets, dim = this.dim, rect;
// get required colors
//var requiredColors = func.foldl(this.stack, "z + plot.getRequiredColors()", 0);
//this.theme.defineColors({num: requiredColors, cache: false});
// clear old shapes
arr.forEach(this.series, purge);
func.forIn(this.axes, purge);
arr.forEach(this.stack, purge);
if(this.chartTitle && this.chartTitle.tagName){
// destroy title if it is a DOM node
domConstruct.destroy(this.chartTitle);
}
this.surface.clear();
this.chartTitle = null;
// generate shapes
// draw a plot background
var t = this.theme,
fill = t.plotarea && t.plotarea.fill,
stroke = t.plotarea && t.plotarea.stroke,
// size might be neg if offsets are bigger that chart size this happens quite often at
// initialization time if the chart widget is used in a BorderContainer
// this will fail on IE/VML
w = Math.max(0, dim.width - offsets.l - offsets.r),
h = Math.max(0, dim.height - offsets.t - offsets.b),
rect = {
x: offsets.l - 1, y: offsets.t - 1,
width: w + 2,
height: h + 2
};
if(fill){
fill = Element.prototype._shapeFill(Element.prototype._plotFill(fill, dim, offsets), rect);
this.surface.createRect(rect).setFill(fill);
}
if(stroke){
this.surface.createRect({
x: offsets.l, y: offsets.t,
width: w + 1,
height: h + 1
}).setStroke(stroke);
}
// go over the stack backwards
func.foldr(this.stack, function(z, plot){ return plot.render(dim, offsets), 0; }, 0);
// pseudo-clipping: matting
fill = this.fill !== undefined ? this.fill : (t.chart && t.chart.fill);
stroke = this.stroke !== undefined ? this.stroke : (t.chart && t.chart.stroke);
// TRT: support for "inherit" as a named value in a theme.
if(fill == "inherit"){
// find the background color of the nearest ancestor node, and use that explicitly.
var node = this.node, fill = new Color(html.style(node, "backgroundColor"));
while(fill.a==0 && node!=document.documentElement){
fill = new Color(html.style(node, "backgroundColor"));
node = node.parentNode;
}
}
if(fill){
fill = Element.prototype._plotFill(fill, dim, offsets);
if(offsets.l){ // left
rect = {
width: offsets.l,
height: dim.height + 1
};
this.surface.createRect(rect).setFill(Element.prototype._shapeFill(fill, rect));
}
if(offsets.r){ // right
rect = {
x: dim.width - offsets.r,
width: offsets.r + 1,
height: dim.height + 2
};
this.surface.createRect(rect).setFill(Element.prototype._shapeFill(fill, rect));
}
if(offsets.t){ // top
rect = {
width: dim.width + 1,
height: offsets.t
};
this.surface.createRect(rect).setFill(Element.prototype._shapeFill(fill, rect));
}
if(offsets.b){ // bottom
rect = {
y: dim.height - offsets.b,
width: dim.width + 1,
height: offsets.b + 2
};
this.surface.createRect(rect).setFill(Element.prototype._shapeFill(fill, rect));
}
}
if(stroke){
this.surface.createRect({
width: dim.width - 1,
height: dim.height - 1
}).setStroke(stroke);
}
//create title: Whether to make chart title as a widget which extends dojox.charting.Element?
if(this.title){
var forceHtmlLabels = (g.renderer == "canvas"),
labelType = forceHtmlLabels || !has("ie") && !has("opera") ? "html" : "gfx",
tsize = g.normalizedLength(g.splitFontString(this.titleFont).size);
this.chartTitle = common.createText[labelType](
this,
this.surface,
dim.width/2,
this.titlePos=="top" ? tsize + this.margins.t : dim.height - this.margins.b,
"middle",
this.title,
this.titleFont,
this.titleFontColor
);
}
// go over axes
func.forIn(this.axes, function(axis){ axis.render(dim, offsets); });
this._makeClean();
// BEGIN FOR HTML CANVAS
if(this.surface.render){ this.surface.render(); };
// END FOR HTML CANVAS
return this; // dojox.charting.Chart
},
delayedRender: function(){
// summary:
// Delayed render, which is used to collect multiple updates
// within a delayInMs time window.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
if(!this._delayedRenderHandle){
this._delayedRenderHandle = setTimeout(
lang.hitch(this, function(){
clearTimeout(this._delayedRenderHandle);
this._delayedRenderHandle = null;
this.render();
}),
this.delayInMs
);
}
return this; // dojox.charting.Chart
},
connectToPlot: function(name, object, method){
// summary:
// A convenience method to connect a function to a plot.
// name: String
// The name of the plot as defined by addPlot.
// object: Object
// The object to be connected.
// method: Function
// The function to be executed.
// returns: Array
// A handle to the connection, as defined by dojo.connect (see dojo.connect).
return name in this.plots ? this.stack[this.plots[name]].connect(object, method) : null; // Array
},
fireEvent: function(seriesName, eventName, index){
// summary:
// Fires a synthetic event for a series item.
// seriesName: String:
// Series name.
// eventName: String:
// Event name to simulate: onmouseover, onmouseout, onclick.
// index: Number:
// Valid data value index for the event.
// returns: dojox.charting.Chart
// A reference to the current chart for functional chaining.
if(seriesName in this.runs){
var plotName = this.series[this.runs[seriesName]].plot;
if(plotName in this.plots){
var plot = this.stack[this.plots[plotName]];
if(plot){
plot.fireEvent(seriesName, eventName, index);
}
}
}
return this; // dojox.charting.Chart
},
_makeClean: function(){
// reset dirty flags
arr.forEach(this.axes, makeClean);
arr.forEach(this.stack, makeClean);
arr.forEach(this.series, makeClean);
this.dirty = false;
},
_makeDirty: function(){
// reset dirty flags
arr.forEach(this.axes, makeDirty);
arr.forEach(this.stack, makeDirty);
arr.forEach(this.series, makeDirty);
this.dirty = true;
},
_invalidateDependentPlots: function(plotName, /* Boolean */ verticalAxis){
if(plotName in this.plots){
var plot = this.stack[this.plots[plotName]], axis,
axisName = verticalAxis ? "vAxis" : "hAxis";
if(plot[axisName]){
axis = this.axes[plot[axisName]];
if(axis && axis.dependOnData()){
axis.dirty = true;
// find all plots and mark them dirty
arr.forEach(this.stack, function(p){
if(p[axisName] && p[axisName] == plot[axisName]){
p.dirty = true;
}
});
}
}else{
plot.dirty = true;
}
}
}
});
function hSection(stats){
return {min: stats.hmin, max: stats.hmax};
}
function vSection(stats){
return {min: stats.vmin, max: stats.vmax};
}
function hReplace(stats, h){
stats.hmin = h.min;
stats.hmax = h.max;
}
function vReplace(stats, v){
stats.vmin = v.min;
stats.vmax = v.max;
}
function combineStats(target, source){
if(target && source){
target.min = Math.min(target.min, source.min);
target.max = Math.max(target.max, source.max);
}
return target || source;
}
function calculateAxes(stack, plotArea){
var plots = {}, axes = {};
arr.forEach(stack, function(plot){
var stats = plots[plot.name] = plot.getSeriesStats();
if(plot.hAxis){
axes[plot.hAxis] = combineStats(axes[plot.hAxis], hSection(stats));
}
if(plot.vAxis){
axes[plot.vAxis] = combineStats(axes[plot.vAxis], vSection(stats));
}
});
arr.forEach(stack, function(plot){
var stats = plots[plot.name];
if(plot.hAxis){
hReplace(stats, axes[plot.hAxis]);
}
if(plot.vAxis){
vReplace(stats, axes[plot.vAxis]);
}
plot.initializeScalers(plotArea, stats);
});
}
return dojox.charting.Chart;
});
},
'dojox/lang/functional/sequence':function(){
define("dojox/lang/functional/sequence", ["dojo/_base/lang", "./lambda"], function(lang, df){
// This module adds high-level functions and related constructs:
// - sequence generators
// If you want more general sequence builders check out listcomp.js and
// unfold() (in fold.js).
// Defined methods:
// - take any valid lambda argument as the functional argument
/*=====
var df = dojox.lang.functional;
=====*/
lang.mixin(df, {
// sequence generators
repeat: function(/*Number*/ n, /*Function|String|Array*/ f, /*Object*/ z, /*Object?*/ o){
// summary: builds an array by repeatedly applying a unary function N times
// with a seed value Z. N should be greater than 0.
o = o || dojo.global; f = df.lambda(f);
var t = new Array(n), i = 1;
t[0] = z;
for(; i < n; t[i] = z = f.call(o, z), ++i);
return t; // Array
},
until: function(/*Function|String|Array*/ pr, /*Function|String|Array*/ f, /*Object*/ z, /*Object?*/ o){
// summary: builds an array by repeatedly applying a unary function with
// a seed value Z until the predicate is satisfied.
o = o || dojo.global; f = df.lambda(f); pr = df.lambda(pr);
var t = [];
for(; !pr.call(o, z); t.push(z), z = f.call(o, z));
return t; // Array
}
});
return df;
});
},
'dojox/charting/plot2d/MarkersOnly':function(){
define("dojox/charting/plot2d/MarkersOnly", ["dojo/_base/declare", "./Default"], function(declare, Default){
/*=====
var Default = dojox.charting.plot2d.Default;
=====*/
return declare("dojox.charting.plot2d.MarkersOnly", Default, {
// summary:
// A convenience object to draw only markers (like a scatter but not quite).
constructor: function(){
// summary:
// Set up our default plot to only have markers and no lines.
this.opt.lines = false;
this.opt.markers = true;
}
});
});
},
'dojox/charting/plot2d/Areas':function(){
define("dojox/charting/plot2d/Areas", ["dojo/_base/declare", "./Default"],
function(declare, Default){
/*=====
var Default = dojox.charting.plot2d.Default;
=====*/
return declare("dojox.charting.plot2d.Areas", Default, {
// summary:
// Represents an area chart. See dojox.charting.plot2d.Default for details.
constructor: function(){
this.opt.lines = true;
this.opt.areas = true;
}
});
});
},
'dojox/charting/action2d/Base':function(){
define("dojox/charting/action2d/Base", ["dojo/_base/lang", "dojo/_base/declare"],
function(lang, declare){
return declare("dojox.charting.action2d.Base", null, {
// summary:
// Base action class for plot and chart actions.
constructor: function(chart, plot){
// summary:
// Create a new base action. This can either be a plot or a chart action.
// chart: dojox.charting.Chart
// The chart this action applies to.
// plot: String?|dojox.charting.plot2d.Base?
// Optional target plot for this action. Default is "default".
this.chart = chart;
this.plot = plot ? (lang.isString(plot) ? this.chart.getPlot(plot) : plot) : this.chart.getPlot("default");
},
connect: function(){
// summary:
// Connect this action to the plot or the chart.
},
disconnect: function(){
// summary:
// Disconnect this action from the plot or the chart.
},
destroy: function(){
// summary:
// Do any cleanup needed when destroying parent elements.
this.disconnect();
}
});
});
},
'dojo/fx':function(){
define([
"./_base/lang",
"./Evented",
"./_base/kernel",
"./_base/array",
"./_base/connect",
"./_base/fx",
"./dom",
"./dom-style",
"./dom-geometry",
"./ready",
"require" // for context sensitive loading of Toggler
], function(lang, Evented, dojo, arrayUtil, connect, baseFx, dom, domStyle, geom, ready, require) {
// module:
// dojo/fx
// summary:
// TODOC
/*=====
dojo.fx = {
// summary: Effects library on top of Base animations
};
var coreFx = dojo.fx;
=====*/
// For back-compat, remove in 2.0.
if(!dojo.isAsync){
ready(0, function(){
var requires = ["./fx/Toggler"];
require(requires); // use indirection so modules not rolled into a build
});
}
var coreFx = dojo.fx = {};
var _baseObj = {
_fire: function(evt, args){
if(this[evt]){
this[evt].apply(this, args||[]);
}
return this;
}
};
var _chain = function(animations){
this._index = -1;
this._animations = animations||[];
this._current = this._onAnimateCtx = this._onEndCtx = null;
this.duration = 0;
arrayUtil.forEach(this._animations, function(a){
this.duration += a.duration;
if(a.delay){ this.duration += a.delay; }
}, this);
};
_chain.prototype = new Evented();
lang.extend(_chain, {
_onAnimate: function(){
this._fire("onAnimate", arguments);
},
_onEnd: function(){
connect.disconnect(this._onAnimateCtx);
connect.disconnect(this._onEndCtx);
this._onAnimateCtx = this._onEndCtx = null;
if(this._index + 1 == this._animations.length){
this._fire("onEnd");
}else{
// switch animations
this._current = this._animations[++this._index];
this._onAnimateCtx = connect.connect(this._current, "onAnimate", this, "_onAnimate");
this._onEndCtx = connect.connect(this._current, "onEnd", this, "_onEnd");
this._current.play(0, true);
}
},
play: function(/*int?*/ delay, /*Boolean?*/ gotoStart){
if(!this._current){ this._current = this._animations[this._index = 0]; }
if(!gotoStart && this._current.status() == "playing"){ return this; }
var beforeBegin = connect.connect(this._current, "beforeBegin", this, function(){
this._fire("beforeBegin");
}),
onBegin = connect.connect(this._current, "onBegin", this, function(arg){
this._fire("onBegin", arguments);
}),
onPlay = connect.connect(this._current, "onPlay", this, function(arg){
this._fire("onPlay", arguments);
connect.disconnect(beforeBegin);
connect.disconnect(onBegin);
connect.disconnect(onPlay);
});
if(this._onAnimateCtx){
connect.disconnect(this._onAnimateCtx);
}
this._onAnimateCtx = connect.connect(this._current, "onAnimate", this, "_onAnimate");
if(this._onEndCtx){
connect.disconnect(this._onEndCtx);
}
this._onEndCtx = connect.connect(this._current, "onEnd", this, "_onEnd");
this._current.play.apply(this._current, arguments);
return this;
},
pause: function(){
if(this._current){
var e = connect.connect(this._current, "onPause", this, function(arg){
this._fire("onPause", arguments);
connect.disconnect(e);
});
this._current.pause();
}
return this;
},
gotoPercent: function(/*Decimal*/percent, /*Boolean?*/ andPlay){
this.pause();
var offset = this.duration * percent;
this._current = null;
arrayUtil.some(this._animations, function(a){
if(a.duration <= offset){
this._current = a;
return true;
}
offset -= a.duration;
return false;
});
if(this._current){
this._current.gotoPercent(offset / this._current.duration, andPlay);
}
return this;
},
stop: function(/*boolean?*/ gotoEnd){
if(this._current){
if(gotoEnd){
for(; this._index + 1 < this._animations.length; ++this._index){
this._animations[this._index].stop(true);
}
this._current = this._animations[this._index];
}
var e = connect.connect(this._current, "onStop", this, function(arg){
this._fire("onStop", arguments);
connect.disconnect(e);
});
this._current.stop();
}
return this;
},
status: function(){
return this._current ? this._current.status() : "stopped";
},
destroy: function(){
if(this._onAnimateCtx){ connect.disconnect(this._onAnimateCtx); }
if(this._onEndCtx){ connect.disconnect(this._onEndCtx); }
}
});
lang.extend(_chain, _baseObj);
coreFx.chain = /*===== dojo.fx.chain = =====*/ function(/*dojo.Animation[]*/ animations){
// summary:
// Chain a list of `dojo.Animation`s to run in sequence
//
// description:
// Return a `dojo.Animation` which will play all passed
// `dojo.Animation` instances in sequence, firing its own
// synthesized events simulating a single animation. (eg:
// onEnd of this animation means the end of the chain,
// not the individual animations within)
//
// example:
// Once `node` is faded out, fade in `otherNode`
// | dojo.fx.chain([
// | dojo.fadeIn({ node:node }),
// | dojo.fadeOut({ node:otherNode })
// | ]).play();
//
return new _chain(animations); // dojo.Animation
};
var _combine = function(animations){
this._animations = animations||[];
this._connects = [];
this._finished = 0;
this.duration = 0;
arrayUtil.forEach(animations, function(a){
var duration = a.duration;
if(a.delay){ duration += a.delay; }
if(this.duration < duration){ this.duration = duration; }
this._connects.push(connect.connect(a, "onEnd", this, "_onEnd"));
}, this);
this._pseudoAnimation = new baseFx.Animation({curve: [0, 1], duration: this.duration});
var self = this;
arrayUtil.forEach(["beforeBegin", "onBegin", "onPlay", "onAnimate", "onPause", "onStop", "onEnd"],
function(evt){
self._connects.push(connect.connect(self._pseudoAnimation, evt,
function(){ self._fire(evt, arguments); }
));
}
);
};
lang.extend(_combine, {
_doAction: function(action, args){
arrayUtil.forEach(this._animations, function(a){
a[action].apply(a, args);
});
return this;
},
_onEnd: function(){
if(++this._finished > this._animations.length){
this._fire("onEnd");
}
},
_call: function(action, args){
var t = this._pseudoAnimation;
t[action].apply(t, args);
},
play: function(/*int?*/ delay, /*Boolean?*/ gotoStart){
this._finished = 0;
this._doAction("play", arguments);
this._call("play", arguments);
return this;
},
pause: function(){
this._doAction("pause", arguments);
this._call("pause", arguments);
return this;
},
gotoPercent: function(/*Decimal*/percent, /*Boolean?*/ andPlay){
var ms = this.duration * percent;
arrayUtil.forEach(this._animations, function(a){
a.gotoPercent(a.duration < ms ? 1 : (ms / a.duration), andPlay);
});
this._call("gotoPercent", arguments);
return this;
},
stop: function(/*boolean?*/ gotoEnd){
this._doAction("stop", arguments);
this._call("stop", arguments);
return this;
},
status: function(){
return this._pseudoAnimation.status();
},
destroy: function(){
arrayUtil.forEach(this._connects, connect.disconnect);
}
});
lang.extend(_combine, _baseObj);
coreFx.combine = /*===== dojo.fx.combine = =====*/ function(/*dojo.Animation[]*/ animations){
// summary:
// Combine a list of `dojo.Animation`s to run in parallel
//
// description:
// Combine an array of `dojo.Animation`s to run in parallel,
// providing a new `dojo.Animation` instance encompasing each
// animation, firing standard animation events.
//
// example:
// Fade out `node` while fading in `otherNode` simultaneously
// | dojo.fx.combine([
// | dojo.fadeIn({ node:node }),
// | dojo.fadeOut({ node:otherNode })
// | ]).play();
//
// example:
// When the longest animation ends, execute a function:
// | var anim = dojo.fx.combine([
// | dojo.fadeIn({ node: n, duration:700 }),
// | dojo.fadeOut({ node: otherNode, duration: 300 })
// | ]);
// | dojo.connect(anim, "onEnd", function(){
// | // overall animation is done.
// | });
// | anim.play(); // play the animation
//
return new _combine(animations); // dojo.Animation
};
coreFx.wipeIn = /*===== dojo.fx.wipeIn = =====*/ function(/*Object*/ args){
// summary:
// Expand a node to it's natural height.
//
// description:
// Returns an animation that will expand the
// node defined in 'args' object from it's current height to
// it's natural height (with no scrollbar).
// Node must have no margin/border/padding.
//
// args: Object
// A hash-map of standard `dojo.Animation` constructor properties
// (such as easing: node: duration: and so on)
//
// example:
// | dojo.fx.wipeIn({
// | node:"someId"
// | }).play()
var node = args.node = dom.byId(args.node), s = node.style, o;
var anim = baseFx.animateProperty(lang.mixin({
properties: {
height: {
// wrapped in functions so we wait till the last second to query (in case value has changed)
start: function(){
// start at current [computed] height, but use 1px rather than 0
// because 0 causes IE to display the whole panel
o = s.overflow;
s.overflow = "hidden";
if(s.visibility == "hidden" || s.display == "none"){
s.height = "1px";
s.display = "";
s.visibility = "";
return 1;
}else{
var height = domStyle.get(node, "height");
return Math.max(height, 1);
}
},
end: function(){
return node.scrollHeight;
}
}
}
}, args));
var fini = function(){
s.height = "auto";
s.overflow = o;
};
connect.connect(anim, "onStop", fini);
connect.connect(anim, "onEnd", fini);
return anim; // dojo.Animation
};
coreFx.wipeOut = /*===== dojo.fx.wipeOut = =====*/ function(/*Object*/ args){
// summary:
// Shrink a node to nothing and hide it.
//
// description:
// Returns an animation that will shrink node defined in "args"
// from it's current height to 1px, and then hide it.
//
// args: Object
// A hash-map of standard `dojo.Animation` constructor properties
// (such as easing: node: duration: and so on)
//
// example:
// | dojo.fx.wipeOut({ node:"someId" }).play()
var node = args.node = dom.byId(args.node), s = node.style, o;
var anim = baseFx.animateProperty(lang.mixin({
properties: {
height: {
end: 1 // 0 causes IE to display the whole panel
}
}
}, args));
connect.connect(anim, "beforeBegin", function(){
o = s.overflow;
s.overflow = "hidden";
s.display = "";
});
var fini = function(){
s.overflow = o;
s.height = "auto";
s.display = "none";
};
connect.connect(anim, "onStop", fini);
connect.connect(anim, "onEnd", fini);
return anim; // dojo.Animation
};
coreFx.slideTo = /*===== dojo.fx.slideTo = =====*/ function(/*Object*/ args){
// summary:
// Slide a node to a new top/left position
//
// description:
// Returns an animation that will slide "node"
// defined in args Object from its current position to
// the position defined by (args.left, args.top).
//
// args: Object
// A hash-map of standard `dojo.Animation` constructor properties
// (such as easing: node: duration: and so on). Special args members
// are `top` and `left`, which indicate the new position to slide to.
//
// example:
// | .slideTo({ node: node, left:"40", top:"50", units:"px" }).play()
var node = args.node = dom.byId(args.node),
top = null, left = null;
var init = (function(n){
return function(){
var cs = domStyle.getComputedStyle(n);
var pos = cs.position;
top = (pos == 'absolute' ? n.offsetTop : parseInt(cs.top) || 0);
left = (pos == 'absolute' ? n.offsetLeft : parseInt(cs.left) || 0);
if(pos != 'absolute' && pos != 'relative'){
var ret = geom.position(n, true);
top = ret.y;
left = ret.x;
n.style.position="absolute";
n.style.top=top+"px";
n.style.left=left+"px";
}
};
})(node);
init();
var anim = baseFx.animateProperty(lang.mixin({
properties: {
top: args.top || 0,
left: args.left || 0
}
}, args));
connect.connect(anim, "beforeBegin", anim, init);
return anim; // dojo.Animation
};
return coreFx;
});
},
'dojox/gfx/fx':function(){
define("dojox/gfx/fx", ["dojo/_base/lang", "./_base", "./matrix", "dojo/_base/Color", "dojo/_base/array", "dojo/_base/fx", "dojo/_base/connect"],
function(lang, g, m, Color, arr, fx, Hub){
var fxg = g.fx = {};
/*===== g = dojox.gfx; fxg = dojox.gfx.fx; =====*/
// Generic interpolators. Should they be moved to dojox.fx?
function InterpolNumber(start, end){
this.start = start, this.end = end;
}
InterpolNumber.prototype.getValue = function(r){
return (this.end - this.start) * r + this.start;
};
function InterpolUnit(start, end, units){
this.start = start, this.end = end;
this.units = units;
}
InterpolUnit.prototype.getValue = function(r){
return (this.end - this.start) * r + this.start + this.units;
};
function InterpolColor(start, end){
this.start = start, this.end = end;
this.temp = new Color();
}
InterpolColor.prototype.getValue = function(r){
return Color.blendColors(this.start, this.end, r, this.temp);
};
function InterpolValues(values){
this.values = values;
this.length = values.length;
}
InterpolValues.prototype.getValue = function(r){
return this.values[Math.min(Math.floor(r * this.length), this.length - 1)];
};
function InterpolObject(values, def){
this.values = values;
this.def = def ? def : {};
}
InterpolObject.prototype.getValue = function(r){
var ret = lang.clone(this.def);
for(var i in this.values){
ret[i] = this.values[i].getValue(r);
}
return ret;
};
function InterpolTransform(stack, original){
this.stack = stack;
this.original = original;
}
InterpolTransform.prototype.getValue = function(r){
var ret = [];
arr.forEach(this.stack, function(t){
if(t instanceof m.Matrix2D){
ret.push(t);
return;
}
if(t.name == "original" && this.original){
ret.push(this.original);
return;
}
if(!(t.name in m)){ return; }
var f = m[t.name];
if(typeof f != "function"){
// constant
ret.push(f);
return;
}
var val = arr.map(t.start, function(v, i){
return (t.end[i] - v) * r + v;
}),
matrix = f.apply(m, val);
if(matrix instanceof m.Matrix2D){
ret.push(matrix);
}
}, this);
return ret;
};
var transparent = new Color(0, 0, 0, 0);
function getColorInterpol(prop, obj, name, def){
if(prop.values){
return new InterpolValues(prop.values);
}
var value, start, end;
if(prop.start){
start = g.normalizeColor(prop.start);
}else{
start = value = obj ? (name ? obj[name] : obj) : def;
}
if(prop.end){
end = g.normalizeColor(prop.end);
}else{
if(!value){
value = obj ? (name ? obj[name] : obj) : def;
}
end = value;
}
return new InterpolColor(start, end);
}
function getNumberInterpol(prop, obj, name, def){
if(prop.values){
return new InterpolValues(prop.values);
}
var value, start, end;
if(prop.start){
start = prop.start;
}else{
start = value = obj ? obj[name] : def;
}
if(prop.end){
end = prop.end;
}else{
if(typeof value != "number"){
value = obj ? obj[name] : def;
}
end = value;
}
return new InterpolNumber(start, end);
}
fxg.animateStroke = function(/*Object*/ args){
// summary:
// Returns an animation which will change stroke properties over time.
// example:
// | dojox.gfx.fx.animateStroke{{
// | shape: shape,
// | duration: 500,
// | color: {start: "red", end: "green"},
// | width: {end: 15},
// | join: {values: ["miter", "bevel", "round"]}
// | }).play();
if(!args.easing){ args.easing = fx._defaultEasing; }
var anim = new fx.Animation(args), shape = args.shape, stroke;
Hub.connect(anim, "beforeBegin", anim, function(){
stroke = shape.getStroke();
var prop = args.color, values = {}, value, start, end;
if(prop){
values.color = getColorInterpol(prop, stroke, "color", transparent);
}
prop = args.style;
if(prop && prop.values){
values.style = new InterpolValues(prop.values);
}
prop = args.width;
if(prop){
values.width = getNumberInterpol(prop, stroke, "width", 1);
}
prop = args.cap;
if(prop && prop.values){
values.cap = new InterpolValues(prop.values);
}
prop = args.join;
if(prop){
if(prop.values){
values.join = new InterpolValues(prop.values);
}else{
start = prop.start ? prop.start : (stroke && stroke.join || 0);
end = prop.end ? prop.end : (stroke && stroke.join || 0);
if(typeof start == "number" && typeof end == "number"){
values.join = new InterpolNumber(start, end);
}
}
}
this.curve = new InterpolObject(values, stroke);
});
Hub.connect(anim, "onAnimate", shape, "setStroke");
return anim; // dojo.Animation
};
fxg.animateFill = function(/*Object*/ args){
// summary:
// Returns an animation which will change fill color over time.
// Only solid fill color is supported at the moment
// example:
// | dojox.gfx.fx.animateFill{{
// | shape: shape,
// | duration: 500,
// | color: {start: "red", end: "green"}
// | }).play();
if(!args.easing){ args.easing = fx._defaultEasing; }
var anim = new fx.Animation(args), shape = args.shape, fill;
Hub.connect(anim, "beforeBegin", anim, function(){
fill = shape.getFill();
var prop = args.color, values = {};
if(prop){
this.curve = getColorInterpol(prop, fill, "", transparent);
}
});
Hub.connect(anim, "onAnimate", shape, "setFill");
return anim; // dojo.Animation
};
fxg.animateFont = function(/*Object*/ args){
// summary:
// Returns an animation which will change font properties over time.
// example:
// | dojox.gfx.fx.animateFont{{
// | shape: shape,
// | duration: 500,
// | variant: {values: ["normal", "small-caps"]},
// | size: {end: 10, units: "pt"}
// | }).play();
if(!args.easing){ args.easing = fx._defaultEasing; }
var anim = new fx.Animation(args), shape = args.shape, font;
Hub.connect(anim, "beforeBegin", anim, function(){
font = shape.getFont();
var prop = args.style, values = {}, value, start, end;
if(prop && prop.values){
values.style = new InterpolValues(prop.values);
}
prop = args.variant;
if(prop && prop.values){
values.variant = new InterpolValues(prop.values);
}
prop = args.weight;
if(prop && prop.values){
values.weight = new InterpolValues(prop.values);
}
prop = args.family;
if(prop && prop.values){
values.family = new InterpolValues(prop.values);
}
prop = args.size;
if(prop && prop.units){
start = parseFloat(prop.start ? prop.start : (shape.font && shape.font.size || "0"));
end = parseFloat(prop.end ? prop.end : (shape.font && shape.font.size || "0"));
values.size = new InterpolUnit(start, end, prop.units);
}
this.curve = new InterpolObject(values, font);
});
Hub.connect(anim, "onAnimate", shape, "setFont");
return anim; // dojo.Animation
};
fxg.animateTransform = function(/*Object*/ args){
// summary:
// Returns an animation which will change transformation over time.
// example:
// | dojox.gfx.fx.animateTransform{{
// | shape: shape,
// | duration: 500,
// | transform: [
// | {name: "translate", start: [0, 0], end: [200, 200]},
// | {name: "original"}
// | ]
// | }).play();
if(!args.easing){ args.easing = fx._defaultEasing; }
var anim = new fx.Animation(args), shape = args.shape, original;
Hub.connect(anim, "beforeBegin", anim, function(){
original = shape.getTransform();
this.curve = new InterpolTransform(args.transform, original);
});
Hub.connect(anim, "onAnimate", shape, "setTransform");
return anim; // dojo.Animation
};
return fxg;
});
},
'dojox/charting/action2d/PlotAction':function(){
define("dojox/charting/action2d/PlotAction", ["dojo/_base/connect", "dojo/_base/declare", "./Base", "dojo/fx/easing", "dojox/lang/functional",
"dojox/lang/functional/object"],
function(hub, declare, Base, dfe, df, dlfo){
/*=====
dojox.charting.action2d.__PlotActionCtorArgs = function(duration, easing){
// summary:
// The base keyword arguments object for creating an action2d.
// duration: Number?
// The amount of time in milliseconds for an animation to last. Default is 400.
// easing: dojo.fx.easing.*?
// An easing object (see dojo.fx.easing) for use in an animation. The
// default is dojo.fx.easing.backOut.
this.duration = duration;
this.easing = easing;
}
var Base = dojox.charting.action2d.Base;
=====*/
var DEFAULT_DURATION = 400, // ms
DEFAULT_EASING = dfe.backOut;
return declare("dojox.charting.action2d.PlotAction", Base, {
// summary:
// Base action class for plot actions.
overOutEvents: {onmouseover: 1, onmouseout: 1},
constructor: function(chart, plot, kwargs){
// summary:
// Create a new base PlotAction.
// chart: dojox.charting.Chart
// The chart this action applies to.
// plot: String?
// The name of the plot this action belongs to. If none is passed "default" is assumed.
// kwargs: dojox.charting.action2d.__PlotActionCtorArgs?
// Optional arguments for the action.
this.anim = {};
// process common optional named parameters
if(!kwargs){ kwargs = {}; }
this.duration = kwargs.duration ? kwargs.duration : DEFAULT_DURATION;
this.easing = kwargs.easing ? kwargs.easing : DEFAULT_EASING;
},
connect: function(){
// summary:
// Connect this action to the given plot.
this.handle = this.chart.connectToPlot(this.plot.name, this, "process");
},
disconnect: function(){
// summary:
// Disconnect this action from the given plot, if connected.
if(this.handle){
hub.disconnect(this.handle);
this.handle = null;
}
},
reset: function(){
// summary:
// Reset the action.
},
destroy: function(){
// summary:
// Do any cleanup needed when destroying parent elements.
this.inherited(arguments);
df.forIn(this.anim, function(o){
df.forIn(o, function(anim){
anim.action.stop(true);
});
});
this.anim = {};
}
});
});
},
'dijit/BackgroundIframe':function(){
define("dijit/BackgroundIframe", [
"require", // require.toUrl
".", // to export dijit.BackgroundIframe
"dojo/_base/config",
"dojo/dom-construct", // domConstruct.create
"dojo/dom-style", // domStyle.set
"dojo/_base/lang", // lang.extend lang.hitch
"dojo/on",
"dojo/_base/sniff", // has("ie"), has("mozilla"), has("quirks")
"dojo/_base/window" // win.doc.createElement
], function(require, dijit, config, domConstruct, domStyle, lang, on, has, win){
// module:
// dijit/BackgroundIFrame
// summary:
// new dijit.BackgroundIframe(node)
// Makes a background iframe as a child of node, that fills
// area (and position) of node
// TODO: remove _frames, it isn't being used much, since popups never release their
// iframes (see [22236])
var _frames = new function(){
// summary:
// cache of iframes
var queue = [];
this.pop = function(){
var iframe;
if(queue.length){
iframe = queue.pop();
iframe.style.display="";
}else{
if(has("ie") < 9){
var burl = config["dojoBlankHtmlUrl"] || require.toUrl("dojo/resources/blank.html") || "javascript:\"\"";
var html="<iframe src='" + burl + "' role='presentation'"
+ " style='position: absolute; left: 0px; top: 0px;"
+ "z-index: -1; filter:Alpha(Opacity=\"0\");'>";
iframe = win.doc.createElement(html);
}else{
iframe = domConstruct.create("iframe");
iframe.src = 'javascript:""';
iframe.className = "dijitBackgroundIframe";
iframe.setAttribute("role", "presentation");
domStyle.set(iframe, "opacity", 0.1);
}
iframe.tabIndex = -1; // Magic to prevent iframe from getting focus on tab keypress - as style didn't work.
}
return iframe;
};
this.push = function(iframe){
iframe.style.display="none";
queue.push(iframe);
}
}();
dijit.BackgroundIframe = function(/*DomNode*/ node){
// summary:
// For IE/FF z-index schenanigans. id attribute is required.
//
// description:
// new dijit.BackgroundIframe(node)
// Makes a background iframe as a child of node, that fills
// area (and position) of node
if(!node.id){ throw new Error("no id"); }
if(has("ie") || has("mozilla")){
var iframe = (this.iframe = _frames.pop());
node.appendChild(iframe);
if(has("ie")<7 || has("quirks")){
this.resize(node);
this._conn = on(node, 'resize', lang.hitch(this, function(){
this.resize(node);
}));
}else{
domStyle.set(iframe, {
width: '100%',
height: '100%'
});
}
}
};
lang.extend(dijit.BackgroundIframe, {
resize: function(node){
// summary:
// Resize the iframe so it's the same size as node.
// Needed on IE6 and IE/quirks because height:100% doesn't work right.
if(this.iframe){
domStyle.set(this.iframe, {
width: node.offsetWidth + 'px',
height: node.offsetHeight + 'px'
});
}
},
destroy: function(){
// summary:
// destroy the iframe
if(this._conn){
this._conn.remove();
this._conn = null;
}
if(this.iframe){
_frames.push(this.iframe);
delete this.iframe;
}
}
});
return dijit.BackgroundIframe;
});
},
'dojox/main':function(){
define("dojox/main", ["dojo/_base/kernel"], function(dojo) {
// module:
// dojox/main
// summary:
// The dojox package main module; dojox package is somewhat unusual in that the main module currently just provides an empty object.
return dojo.dojox;
});
},
'dojox/charting/action2d/Magnify':function(){
define("dojox/charting/action2d/Magnify", ["dojo/_base/connect", "dojo/_base/declare",
"./PlotAction", "dojox/gfx/matrix",
"dojox/gfx/fx", "dojo/fx", "dojo/fx/easing"],
function(Hub, declare, PlotAction, m, gf, df, dfe){
/*=====
dojo.declare("dojox.charting.action2d.__MagnifyCtorArgs", dojox.charting.action2d.__PlotActionCtorArgs, {
// summary:
// Additional arguments for highlighting actions.
// scale: Number?
// The amount to magnify the given object to. Default is 2.
scale: 2
});
var PlotAction = dojox.charting.action2d.PlotAction;
=====*/
var DEFAULT_SCALE = 2;
return declare("dojox.charting.action2d.Magnify", PlotAction, {
// summary:
// Create an action that magnifies the object the action is applied to.
// the data description block for the widget parser
defaultParams: {
duration: 400, // duration of the action in ms
easing: dfe.backOut, // easing for the action
scale: DEFAULT_SCALE // scale of magnification
},
optionalParams: {}, // no optional parameters
constructor: function(chart, plot, kwArgs){
// summary:
// Create the magnifying action.
// chart: dojox.charting.Chart
// The chart this action belongs to.
// plot: String?
// The plot to apply the action to. If not passed, "default" is assumed.
// kwArgs: dojox.charting.action2d.__MagnifyCtorArgs?
// Optional keyword arguments for this action.
// process optional named parameters
this.scale = kwArgs && typeof kwArgs.scale == "number" ? kwArgs.scale : DEFAULT_SCALE;
this.connect();
},
process: function(o){
// summary:
// Process the action on the given object.
// o: dojox.gfx.Shape
// The object on which to process the magnifying action.
if(!o.shape || !(o.type in this.overOutEvents) ||
!("cx" in o) || !("cy" in o)){ return; }
var runName = o.run.name, index = o.index, vector = [], anim, init, scale;
if(runName in this.anim){
anim = this.anim[runName][index];
}else{
this.anim[runName] = {};
}
if(anim){
anim.action.stop(true);
}else{
this.anim[runName][index] = anim = {};
}
if(o.type == "onmouseover"){
init = m.identity;
scale = this.scale;
}else{
init = m.scaleAt(this.scale, o.cx, o.cy);
scale = 1 / this.scale;
}
var kwArgs = {
shape: o.shape,
duration: this.duration,
easing: this.easing,
transform: [
{name: "scaleAt", start: [1, o.cx, o.cy], end: [scale, o.cx, o.cy]},
init
]
};
if(o.shape){
vector.push(gf.animateTransform(kwArgs));
}
if(o.oultine){
kwArgs.shape = o.outline;
vector.push(gf.animateTransform(kwArgs));
}
if(o.shadow){
kwArgs.shape = o.shadow;
vector.push(gf.animateTransform(kwArgs));
}
if(!vector.length){
delete this.anim[runName][index];
return;
}
anim.action = df.combine(vector);
if(o.type == "onmouseout"){
Hub.connect(anim.action, "onEnd", this, function(){
if(this.anim[runName]){
delete this.anim[runName][index];
}
});
}
anim.action.play();
}
});
});
},
'dojo/Stateful':function(){
define(["./_base/kernel", "./_base/declare", "./_base/lang", "./_base/array"], function(dojo, declare, lang, array) {
// module:
// dojo/Stateful
// summary:
// TODOC
return dojo.declare("dojo.Stateful", null, {
// summary:
// Base class for objects that provide named properties with optional getter/setter
// control and the ability to watch for property changes
// example:
// | var obj = new dojo.Stateful();
// | obj.watch("foo", function(){
// | console.log("foo changed to " + this.get("foo"));
// | });
// | obj.set("foo","bar");
postscript: function(mixin){
if(mixin){
lang.mixin(this, mixin);
}
},
get: function(/*String*/name){
// summary:
// Get a property on a Stateful instance.
// name:
// The property to get.
// returns:
// The property value on this Stateful instance.
// description:
// Get a named property on a Stateful object. The property may
// potentially be retrieved via a getter method in subclasses. In the base class
// this just retrieves the object's property.
// For example:
// | stateful = new dojo.Stateful({foo: 3});
// | stateful.get("foo") // returns 3
// | stateful.foo // returns 3
return this[name]; //Any
},
set: function(/*String*/name, /*Object*/value){
// summary:
// Set a property on a Stateful instance
// name:
// The property to set.
// value:
// The value to set in the property.
// returns:
// The function returns this dojo.Stateful instance.
// description:
// Sets named properties on a stateful object and notifies any watchers of
// the property. A programmatic setter may be defined in subclasses.
// For example:
// | stateful = new dojo.Stateful();
// | stateful.watch(function(name, oldValue, value){
// | // this will be called on the set below
// | }
// | stateful.set(foo, 5);
//
// set() may also be called with a hash of name/value pairs, ex:
// | myObj.set({
// | foo: "Howdy",
// | bar: 3
// | })
// This is equivalent to calling set(foo, "Howdy") and set(bar, 3)
if(typeof name === "object"){
for(var x in name){
this.set(x, name[x]);
}
return this;
}
var oldValue = this[name];
this[name] = value;
if(this._watchCallbacks){
this._watchCallbacks(name, oldValue, value);
}
return this; //dojo.Stateful
},
watch: function(/*String?*/name, /*Function*/callback){
// summary:
// Watches a property for changes
// name:
// Indicates the property to watch. This is optional (the callback may be the
// only parameter), and if omitted, all the properties will be watched
// returns:
// An object handle for the watch. The unwatch method of this object
// can be used to discontinue watching this property:
// | var watchHandle = obj.watch("foo", callback);
// | watchHandle.unwatch(); // callback won't be called now
// callback:
// The function to execute when the property changes. This will be called after
// the property has been changed. The callback will be called with the |this|
// set to the instance, the first argument as the name of the property, the
// second argument as the old value and the third argument as the new value.
var callbacks = this._watchCallbacks;
if(!callbacks){
var self = this;
callbacks = this._watchCallbacks = function(name, oldValue, value, ignoreCatchall){
var notify = function(propertyCallbacks){
if(propertyCallbacks){
propertyCallbacks = propertyCallbacks.slice();
for(var i = 0, l = propertyCallbacks.length; i < l; i++){
try{
propertyCallbacks[i].call(self, name, oldValue, value);
}catch(e){
console.error(e);
}
}
}
};
notify(callbacks['_' + name]);
if(!ignoreCatchall){
notify(callbacks["*"]); // the catch-all
}
}; // we use a function instead of an object so it will be ignored by JSON conversion
}
if(!callback && typeof name === "function"){
callback = name;
name = "*";
}else{
// prepend with dash to prevent name conflicts with function (like "name" property)
name = '_' + name;
}
var propertyCallbacks = callbacks[name];
if(typeof propertyCallbacks !== "object"){
propertyCallbacks = callbacks[name] = [];
}
propertyCallbacks.push(callback);
return {
unwatch: function(){
propertyCallbacks.splice(array.indexOf(propertyCallbacks, callback), 1);
}
}; //Object
}
});
});
},
'dojox/charting/plot2d/Markers':function(){
define("dojox/charting/plot2d/Markers", ["dojo/_base/declare", "./Default"], function(declare, Default){
/*=====
var Default = dojox.charting.plot2d.Default
=====*/
return declare("dojox.charting.plot2d.Markers", Default, {
// summary:
// A convenience plot to draw a line chart with markers.
constructor: function(){
// summary:
// Set up the plot for lines and markers.
this.opt.markers = true;
}
});
});
},
'dojox/charting/plot2d/Bubble':function(){
define("dojox/charting/plot2d/Bubble", ["dojo/_base/lang", "dojo/_base/declare", "dojo/_base/array",
"./Base", "./common", "dojox/lang/functional", "dojox/lang/functional/reversed",
"dojox/lang/utils", "dojox/gfx/fx"],
function(lang, declare, arr, Base, dc, df, dfr, du, fx){
/*=====
var Base = dojox.charting.plot2d.Base;
=====*/
var purgeGroup = dfr.lambda("item.purgeGroup()");
return declare("dojox.charting.plot2d.Bubble", Base, {
// summary:
// A plot representing bubbles. Note that data for Bubbles requires 3 parameters,
// in the form of: { x, y, size }, where size determines the size of the bubble.
defaultParams: {
hAxis: "x", // use a horizontal axis named "x"
vAxis: "y", // use a vertical axis named "y"
animate: null // animate bars into place
},
optionalParams: {
// theme component
stroke: {},
outline: {},
shadow: {},
fill: {},
font: "",
fontColor: ""
},
constructor: function(chart, kwArgs){
// summary:
// Create a plot of bubbles.
// chart: dojox.charting.Chart
// The chart this plot belongs to.
// kwArgs: dojox.charting.plot2d.__DefaultCtorArgs?
// Optional keyword arguments object to help define plot parameters.
this.opt = lang.clone(this.defaultParams);
du.updateWithObject(this.opt, kwArgs);
du.updateWithPattern(this.opt, kwArgs, this.optionalParams);
this.series = [];
this.hAxis = this.opt.hAxis;
this.vAxis = this.opt.vAxis;
this.animate = this.opt.animate;
},
// override the render so that we are plotting only circles.
render: function(dim, offsets){
// summary:
// Run the calculations for any axes for this plot.
// dim: Object
// An object in the form of { width, height }
// offsets: Object
// An object of the form { l, r, t, b}.
// returns: dojox.charting.plot2d.Bubble
// A reference to this plot for functional chaining.
if(this.zoom && !this.isDataDirty()){
return this.performZoom(dim, offsets);
}
this.resetEvents();
this.dirty = this.isDirty();
if(this.dirty){
arr.forEach(this.series, purgeGroup);
this._eventSeries = {};
this.cleanGroup();
var s = this.group;
df.forEachRev(this.series, function(item){ item.cleanGroup(s); });
}
var t = this.chart.theme,
ht = this._hScaler.scaler.getTransformerFromModel(this._hScaler),
vt = this._vScaler.scaler.getTransformerFromModel(this._vScaler),
events = this.events();
for(var i = this.series.length - 1; i >= 0; --i){
var run = this.series[i];
if(!this.dirty && !run.dirty){
t.skip();
this._reconnectEvents(run.name);
continue;
}
run.cleanGroup();
if(!run.data.length){
run.dirty = false;
t.skip();
continue;
}
if(typeof run.data[0] == "number"){
console.warn("dojox.charting.plot2d.Bubble: the data in the following series cannot be rendered as a bubble chart; ", run);
continue;
}
var theme = t.next("circle", [this.opt, run]), s = run.group,
points = arr.map(run.data, function(v, i){
return v ? {
x: ht(v.x) + offsets.l,
y: dim.height - offsets.b - vt(v.y),
radius: this._vScaler.bounds.scale * (v.size / 2)
} : null;
}, this);
var frontCircles = null, outlineCircles = null, shadowCircles = null;
// make shadows if needed
if(theme.series.shadow){
shadowCircles = arr.map(points, function(item){
if(item !== null){
var finalTheme = t.addMixin(theme, "circle", item, true),
shadow = finalTheme.series.shadow;
var shape = s.createCircle({
cx: item.x + shadow.dx, cy: item.y + shadow.dy, r: item.radius
}).setStroke(shadow).setFill(shadow.color);
if(this.animate){
this._animateBubble(shape, dim.height - offsets.b, item.radius);
}
return shape;
}
return null;
}, this);
if(shadowCircles.length){
run.dyn.shadow = shadowCircles[shadowCircles.length - 1].getStroke();
}
}
// make outlines if needed
if(theme.series.outline){
outlineCircles = arr.map(points, function(item){
if(item !== null){
var finalTheme = t.addMixin(theme, "circle", item, true),
outline = dc.makeStroke(finalTheme.series.outline);
outline.width = 2 * outline.width + theme.series.stroke.width;
var shape = s.createCircle({
cx: item.x, cy: item.y, r: item.radius
}).setStroke(outline);
if(this.animate){
this._animateBubble(shape, dim.height - offsets.b, item.radius);
}
return shape;
}
return null;
}, this);
if(outlineCircles.length){
run.dyn.outline = outlineCircles[outlineCircles.length - 1].getStroke();
}
}
// run through the data and add the circles.
frontCircles = arr.map(points, function(item){
if(item !== null){
var finalTheme = t.addMixin(theme, "circle", item, true),
rect = {
x: item.x - item.radius,
y: item.y - item.radius,
width: 2 * item.radius,
height: 2 * item.radius
};
var specialFill = this._plotFill(finalTheme.series.fill, dim, offsets);
specialFill = this._shapeFill(specialFill, rect);
var shape = s.createCircle({
cx: item.x, cy: item.y, r: item.radius
}).setFill(specialFill).setStroke(finalTheme.series.stroke);
if(this.animate){
this._animateBubble(shape, dim.height - offsets.b, item.radius);
}
return shape;
}
return null;
}, this);
if(frontCircles.length){
run.dyn.fill = frontCircles[frontCircles.length - 1].getFill();
run.dyn.stroke = frontCircles[frontCircles.length - 1].getStroke();
}
if(events){
var eventSeries = new Array(frontCircles.length);
arr.forEach(frontCircles, function(s, i){
if(s !== null){
var o = {
element: "circle",
index: i,
run: run,
shape: s,
outline: outlineCircles && outlineCircles[i] || null,
shadow: shadowCircles && shadowCircles[i] || null,
x: run.data[i].x,
y: run.data[i].y,
r: run.data[i].size / 2,
cx: points[i].x,
cy: points[i].y,
cr: points[i].radius
};
this._connectEvents(o);
eventSeries[i] = o;
}
}, this);
this._eventSeries[run.name] = eventSeries;
}else{
delete this._eventSeries[run.name];
}
run.dirty = false;
}
this.dirty = false;
return this; // dojox.charting.plot2d.Bubble
},
_animateBubble: function(shape, offset, size){
fx.animateTransform(lang.delegate({
shape: shape,
duration: 1200,
transform: [
{name: "translate", start: [0, offset], end: [0, 0]},
{name: "scale", start: [0, 1/size], end: [1, 1]},
{name: "original"}
]
}, this.animate)).play();
}
});
});
},
'dojo/touch':function(){
define(["./_base/kernel", "./on", "./has", "./mouse"], function(dojo, on, has, mouse){
// module:
// dojo/touch
/*=====
dojo.touch = {
// summary:
// This module provides unified touch event handlers by exporting
// press, move, release and cancel which can also run well on desktop.
// Based on http://dvcs.w3.org/hg/webevents/raw-file/tip/touchevents.html
//
// example:
// 1. Used with dojo.connect()
// | dojo.connect(node, dojo.touch.press, function(e){});
// | dojo.connect(node, dojo.touch.move, function(e){});
// | dojo.connect(node, dojo.touch.release, function(e){});
// | dojo.connect(node, dojo.touch.cancel, function(e){});
//
// 2. Used with dojo.on
// | define(["dojo/on", "dojo/touch"], function(on, touch){
// | on(node, touch.press, function(e){});
// | on(node, touch.move, function(e){});
// | on(node, touch.release, function(e){});
// | on(node, touch.cancel, function(e){});
//
// 3. Used with dojo.touch.* directly
// | dojo.touch.press(node, function(e){});
// | dojo.touch.move(node, function(e){});
// | dojo.touch.release(node, function(e){});
// | dojo.touch.cancel(node, function(e){});
press: function(node, listener){
// summary:
// Register a listener to 'touchstart'|'mousedown' for the given node
// node: Dom
// Target node to listen to
// listener: Function
// Callback function
// returns:
// A handle which will be used to remove the listener by handle.remove()
},
move: function(node, listener){
// summary:
// Register a listener to 'touchmove'|'mousemove' for the given node
// node: Dom
// Target node to listen to
// listener: Function
// Callback function
// returns:
// A handle which will be used to remove the listener by handle.remove()
},
release: function(node, listener){
// summary:
// Register a listener to 'touchend'|'mouseup' for the given node
// node: Dom
// Target node to listen to
// listener: Function
// Callback function
// returns:
// A handle which will be used to remove the listener by handle.remove()
},
cancel: function(node, listener){
// summary:
// Register a listener to 'touchcancel'|'mouseleave' for the given node
// node: Dom
// Target node to listen to
// listener: Function
// Callback function
// returns:
// A handle which will be used to remove the listener by handle.remove()
}
};
=====*/
function _handle(/*String - press | move | release | cancel*/type){
return function(node, listener){//called by on(), see dojo.on
return on(node, type, listener);
};
}
var touch = has("touch");
//device neutral events - dojo.touch.press|move|release|cancel
dojo.touch = {
press: _handle(touch ? "touchstart": "mousedown"),
move: _handle(touch ? "touchmove": "mousemove"),
release: _handle(touch ? "touchend": "mouseup"),
cancel: touch ? _handle("touchcancel") : mouse.leave
};
return dojo.touch;
});
},
'dojox/gfx/gradutils':function(){
// Various generic utilities to deal with a linear gradient
define(["./_base", "dojo/_base/lang", "./matrix", "dojo/_base/Color"],
function(g, lang, m, Color){
/*===== g= dojox.gfx =====*/
var gradutils = g.gradutils = {};
/*===== g= dojox.gfx; gradutils = dojox.gfx.gradutils; =====*/
function findColor(o, c){
if(o <= 0){
return c[0].color;
}
var len = c.length;
if(o >= 1){
return c[len - 1].color;
}
//TODO: use binary search
for(var i = 0; i < len; ++i){
var stop = c[i];
if(stop.offset >= o){
if(i){
var prev = c[i - 1];
return Color.blendColors(new Color(prev.color), new Color(stop.color),
(o - prev.offset) / (stop.offset - prev.offset));
}
return stop.color;
}
}
return c[len - 1].color;
}
gradutils.getColor = function(fill, pt){
// summary:
// sample a color from a gradient using a point
// fill: Object:
// fill object
// pt: dojox.gfx.Point:
// point where to sample a color
var o;
if(fill){
switch(fill.type){
case "linear":
var angle = Math.atan2(fill.y2 - fill.y1, fill.x2 - fill.x1),
rotation = m.rotate(-angle),
projection = m.project(fill.x2 - fill.x1, fill.y2 - fill.y1),
p = m.multiplyPoint(projection, pt),
pf1 = m.multiplyPoint(projection, fill.x1, fill.y1),
pf2 = m.multiplyPoint(projection, fill.x2, fill.y2),
scale = m.multiplyPoint(rotation, pf2.x - pf1.x, pf2.y - pf1.y).x;
o = m.multiplyPoint(rotation, p.x - pf1.x, p.y - pf1.y).x / scale;
break;
case "radial":
var dx = pt.x - fill.cx, dy = pt.y - fill.cy;
o = Math.sqrt(dx * dx + dy * dy) / fill.r;
break;
}
return findColor(o, fill.colors); // dojo.Color
}
// simple color
return new Color(fill || [0, 0, 0, 0]); // dojo.Color
};
gradutils.reverse = function(fill){
// summary:
// reverses a gradient
// fill: Object:
// fill object
if(fill){
switch(fill.type){
case "linear":
case "radial":
fill = lang.delegate(fill);
if(fill.colors){
var c = fill.colors, l = c.length, i = 0, stop,
n = fill.colors = new Array(c.length);
for(; i < l; ++i){
stop = c[i];
n[i] = {
offset: 1 - stop.offset,
color: stop.color
};
}
n.sort(function(a, b){ return a.offset - b.offset; });
}
break;
}
}
return fill; // Object
};
return gradutils;
});
},
'dojo/string':function(){
define(["./_base/kernel", "./_base/lang"], function(dojo, lang) {
// module:
// dojo/string
// summary:
// TODOC
lang.getObject("string", true, dojo);
/*=====
dojo.string = {
// summary: String utilities for Dojo
};
=====*/
dojo.string.rep = function(/*String*/str, /*Integer*/num){
// summary:
// Efficiently replicate a string `n` times.
// str:
// the string to replicate
// num:
// number of times to replicate the string
if(num <= 0 || !str){ return ""; }
var buf = [];
for(;;){
if(num & 1){
buf.push(str);
}
if(!(num >>= 1)){ break; }
str += str;
}
return buf.join(""); // String
};
dojo.string.pad = function(/*String*/text, /*Integer*/size, /*String?*/ch, /*Boolean?*/end){
// summary:
// Pad a string to guarantee that it is at least `size` length by
// filling with the character `ch` at either the start or end of the
// string. Pads at the start, by default.
// text:
// the string to pad
// size:
// length to provide padding
// ch:
// character to pad, defaults to '0'
// end:
// adds padding at the end if true, otherwise pads at start
// example:
// | // Fill the string to length 10 with "+" characters on the right. Yields "Dojo++++++".
// | dojo.string.pad("Dojo", 10, "+", true);
if(!ch){
ch = '0';
}
var out = String(text),
pad = dojo.string.rep(ch, Math.ceil((size - out.length) / ch.length));
return end ? out + pad : pad + out; // String
};
dojo.string.substitute = function( /*String*/ template,
/*Object|Array*/map,
/*Function?*/ transform,
/*Object?*/ thisObject){
// summary:
// Performs parameterized substitutions on a string. Throws an
// exception if any parameter is unmatched.
// template:
// a string with expressions in the form `${key}` to be replaced or
// `${key:format}` which specifies a format function. keys are case-sensitive.
// map:
// hash to search for substitutions
// transform:
// a function to process all parameters before substitution takes
// place, e.g. mylib.encodeXML
// thisObject:
// where to look for optional format function; default to the global
// namespace
// example:
// Substitutes two expressions in a string from an Array or Object
// | // returns "File 'foo.html' is not found in directory '/temp'."
// | // by providing substitution data in an Array
// | dojo.string.substitute(
// | "File '${0}' is not found in directory '${1}'.",
// | ["foo.html","/temp"]
// | );
// |
// | // also returns "File 'foo.html' is not found in directory '/temp'."
// | // but provides substitution data in an Object structure. Dotted
// | // notation may be used to traverse the structure.
// | dojo.string.substitute(
// | "File '${name}' is not found in directory '${info.dir}'.",
// | { name: "foo.html", info: { dir: "/temp" } }
// | );
// example:
// Use a transform function to modify the values:
// | // returns "file 'foo.html' is not found in directory '/temp'."
// | dojo.string.substitute(
// | "${0} is not found in ${1}.",
// | ["foo.html","/temp"],
// | function(str){
// | // try to figure out the type
// | var prefix = (str.charAt(0) == "/") ? "directory": "file";
// | return prefix + " '" + str + "'";
// | }
// | );
// example:
// Use a formatter
// | // returns "thinger -- howdy"
// | dojo.string.substitute(
// | "${0:postfix}", ["thinger"], null, {
// | postfix: function(value, key){
// | return value + " -- howdy";
// | }
// | }
// | );
thisObject = thisObject || dojo.global;
transform = transform ?
lang.hitch(thisObject, transform) : function(v){ return v; };
return template.replace(/\$\{([^\s\:\}]+)(?:\:([^\s\:\}]+))?\}/g,
function(match, key, format){
var value = lang.getObject(key, false, map);
if(format){
value = lang.getObject(format, false, thisObject).call(thisObject, value, key);
}
return transform(value, key).toString();
}); // String
};
/*=====
dojo.string.trim = function(str){
// summary:
// Trims whitespace from both sides of the string
// str: String
// String to be trimmed
// returns: String
// Returns the trimmed string
// description:
// This version of trim() was taken from [Steven Levithan's blog](http://blog.stevenlevithan.com/archives/faster-trim-javascript).
// The short yet performant version of this function is dojo.trim(),
// which is part of Dojo base. Uses String.prototype.trim instead, if available.
return ""; // String
}
=====*/
dojo.string.trim = String.prototype.trim ?
lang.trim : // aliasing to the native function
function(str){
str = str.replace(/^\s+/, '');
for(var i = str.length - 1; i >= 0; i--){
if(/\S/.test(str.charAt(i))){
str = str.substring(0, i + 1);
break;
}
}
return str;
};
return dojo.string;
});
},
'dijit/registry':function(){
define("dijit/registry", [
"dojo/_base/array", // array.forEach array.map
"dojo/_base/sniff", // has("ie")
"dojo/_base/unload", // unload.addOnWindowUnload
"dojo/_base/window", // win.body
"." // dijit._scopeName
], function(array, has, unload, win, dijit){
// module:
// dijit/registry
// summary:
// Registry of existing widget on page, plus some utility methods.
// Must be accessed through AMD api, ex:
// require(["dijit/registry"], function(registry){ registry.byId("foo"); })
var _widgetTypeCtr = {}, hash = {};
var registry = {
// summary:
// A set of widgets indexed by id
length: 0,
add: function(/*dijit._Widget*/ widget){
// summary:
// Add a widget to the registry. If a duplicate ID is detected, a error is thrown.
//
// widget: dijit._Widget
// Any dijit._Widget subclass.
if(hash[widget.id]){
throw new Error("Tried to register widget with id==" + widget.id + " but that id is already registered");
}
hash[widget.id] = widget;
this.length++;
},
remove: function(/*String*/ id){
// summary:
// Remove a widget from the registry. Does not destroy the widget; simply
// removes the reference.
if(hash[id]){
delete hash[id];
this.length--;
}
},
byId: function(/*String|Widget*/ id){
// summary:
// Find a widget by it's id.
// If passed a widget then just returns the widget.
return typeof id == "string" ? hash[id] : id; // dijit._Widget
},
byNode: function(/*DOMNode*/ node){
// summary:
// Returns the widget corresponding to the given DOMNode
return hash[node.getAttribute("widgetId")]; // dijit._Widget
},
toArray: function(){
// summary:
// Convert registry into a true Array
//
// example:
// Work with the widget .domNodes in a real Array
// | array.map(dijit.registry.toArray(), function(w){ return w.domNode; });
var ar = [];
for(var id in hash){
ar.push(hash[id]);
}
return ar; // dijit._Widget[]
},
getUniqueId: function(/*String*/widgetType){
// summary:
// Generates a unique id for a given widgetType
var id;
do{
id = widgetType + "_" +
(widgetType in _widgetTypeCtr ?
++_widgetTypeCtr[widgetType] : _widgetTypeCtr[widgetType] = 0);
}while(hash[id]);
return dijit._scopeName == "dijit" ? id : dijit._scopeName + "_" + id; // String
},
findWidgets: function(/*DomNode*/ root){
// summary:
// Search subtree under root returning widgets found.
// Doesn't search for nested widgets (ie, widgets inside other widgets).
var outAry = [];
function getChildrenHelper(root){
for(var node = root.firstChild; node; node = node.nextSibling){
if(node.nodeType == 1){
var widgetId = node.getAttribute("widgetId");
if(widgetId){
var widget = hash[widgetId];
if(widget){ // may be null on page w/multiple dojo's loaded
outAry.push(widget);
}
}else{
getChildrenHelper(node);
}
}
}
}
getChildrenHelper(root);
return outAry;
},
_destroyAll: function(){
// summary:
// Code to destroy all widgets and do other cleanup on page unload
// Clean up focus manager lingering references to widgets and nodes
dijit._curFocus = null;
dijit._prevFocus = null;
dijit._activeStack = [];
// Destroy all the widgets, top down
array.forEach(registry.findWidgets(win.body()), function(widget){
// Avoid double destroy of widgets like Menu that are attached to <body>
// even though they are logically children of other widgets.
if(!widget._destroyed){
if(widget.destroyRecursive){
widget.destroyRecursive();
}else if(widget.destroy){
widget.destroy();
}
}
});
},
getEnclosingWidget: function(/*DOMNode*/ node){
// summary:
// Returns the widget whose DOM tree contains the specified DOMNode, or null if
// the node is not contained within the DOM tree of any widget
while(node){
var id = node.getAttribute && node.getAttribute("widgetId");
if(id){
return hash[id];
}
node = node.parentNode;
}
return null;
},
// In case someone needs to access hash.
// Actually, this is accessed from WidgetSet back-compatibility code
_hash: hash
};
if(has("ie")){
// Only run _destroyAll() for IE because we think it's only necessary in that case,
// and because it causes problems on FF. See bug #3531 for details.
unload.addOnWindowUnload(function(){
registry._destroyAll();
});
}
/*=====
dijit.registry = {
// summary:
// A list of widgets on a page.
};
=====*/
dijit.registry = registry;
return registry;
});
},
'dojox/charting/plot2d/Lines':function(){
define("dojox/charting/plot2d/Lines", ["dojo/_base/declare", "./Default"], function(declare, Default){
/*=====
var Default = dojox.charting.plot2d.Default;
=====*/
return declare("dojox.charting.plot2d.Lines", Default, {
// summary:
// A convenience constructor to create a typical line chart.
constructor: function(){
// summary:
// Preset our default plot to be line-based.
this.opt.lines = true;
}
});
});
},
'dijit/_base/manager':function(){
define("dijit/_base/manager", [
"dojo/_base/array",
"dojo/_base/config", // defaultDuration
"../registry",
".." // for setting exports to dijit namespace
], function(array, config, registry, dijit){
// module:
// dijit/_base/manager
// summary:
// Shim to methods on registry, plus a few other declarations.
// New code should access dijit/registry directly when possible.
/*=====
dijit.byId = function(id){
// summary:
// Returns a widget by it's id, or if passed a widget, no-op (like dom.byId())
// id: String|dijit._Widget
return registry.byId(id); // dijit._Widget
};
dijit.getUniqueId = function(widgetType){
// summary:
// Generates a unique id for a given widgetType
// widgetType: String
return registry.getUniqueId(widgetType); // String
};
dijit.findWidgets = function(root){
// summary:
// Search subtree under root returning widgets found.
// Doesn't search for nested widgets (ie, widgets inside other widgets).
// root: DOMNode
return registry.findWidgets(root);
};
dijit._destroyAll = function(){
// summary:
// Code to destroy all widgets and do other cleanup on page unload
return registry._destroyAll();
};
dijit.byNode = function(node){
// summary:
// Returns the widget corresponding to the given DOMNode
// node: DOMNode
return registry.byNode(node); // dijit._Widget
};
dijit.getEnclosingWidget = function(node){
// summary:
// Returns the widget whose DOM tree contains the specified DOMNode, or null if
// the node is not contained within the DOM tree of any widget
// node: DOMNode
return registry.getEnclosingWidget(node);
};
=====*/
array.forEach(["byId", "getUniqueId", "findWidgets", "_destroyAll", "byNode", "getEnclosingWidget"], function(name){
dijit[name] = registry[name];
});
/*=====
dojo.mixin(dijit, {
// defaultDuration: Integer
// The default fx.animation speed (in ms) to use for all Dijit
// transitional fx.animations, unless otherwise specified
// on a per-instance basis. Defaults to 200, overrided by
// `djConfig.defaultDuration`
defaultDuration: 200
});
=====*/
dijit.defaultDuration = config["defaultDuration"] || 200;
return dijit;
});
},
'dojox/charting/plot2d/StackedAreas':function(){
define("dojox/charting/plot2d/StackedAreas", ["dojo/_base/declare", "./Stacked"], function(declare, Stacked){
/*=====
var Stacked = dojox.charting.plot2d.Stacked;
=====*/
return declare("dojox.charting.plot2d.StackedAreas", Stacked, {
// summary:
// A convenience object to set up a stacked area plot.
constructor: function(){
// summary:
// Force our Stacked plotter to include both lines and areas.
this.opt.lines = true;
this.opt.areas = true;
}
});
});
},
'dojox/charting/plot2d/Stacked':function(){
define("dojox/charting/plot2d/Stacked", ["dojo/_base/lang", "dojo/_base/declare", "dojo/_base/array", "./Default", "./common",
"dojox/lang/functional", "dojox/lang/functional/reversed", "dojox/lang/functional/sequence"],
function(lang, declare, arr, Default, dc, df, dfr, dfs){
/*=====
var Default = dojox.charting.plot2d.Default;
=====*/
var purgeGroup = dfr.lambda("item.purgeGroup()");
return declare("dojox.charting.plot2d.Stacked", Default, {
// summary:
// Like the default plot, Stacked sets up lines, areas and markers
// in a stacked fashion (values on the y axis added to each other)
// as opposed to a direct one.
getSeriesStats: function(){
// summary:
// Calculate the min/max on all attached series in both directions.
// returns: Object
// {hmin, hmax, vmin, vmax} min/max in both directions.
var stats = dc.collectStackedStats(this.series);
this._maxRunLength = stats.hmax;
return stats;
},
render: function(dim, offsets){
// summary:
// Run the calculations for any axes for this plot.
// dim: Object
// An object in the form of { width, height }
// offsets: Object
// An object of the form { l, r, t, b}.
// returns: dojox.charting.plot2d.Stacked
// A reference to this plot for functional chaining.
if(this._maxRunLength <= 0){
return this;
}
// stack all values
var acc = df.repeat(this._maxRunLength, "-> 0", 0);
for(var i = 0; i < this.series.length; ++i){
var run = this.series[i];
for(var j = 0; j < run.data.length; ++j){
var v = run.data[j];
if(v !== null){
if(isNaN(v)){ v = 0; }
acc[j] += v;
}
}
}
// draw runs in backwards
if(this.zoom && !this.isDataDirty()){
return this.performZoom(dim, offsets);
}
this.resetEvents();
this.dirty = this.isDirty();
if(this.dirty){
arr.forEach(this.series, purgeGroup);
this._eventSeries = {};
this.cleanGroup();
var s = this.group;
df.forEachRev(this.series, function(item){ item.cleanGroup(s); });
}
var t = this.chart.theme, events = this.events(),
ht = this._hScaler.scaler.getTransformerFromModel(this._hScaler),
vt = this._vScaler.scaler.getTransformerFromModel(this._vScaler);
for(var i = this.series.length - 1; i >= 0; --i){
var run = this.series[i];
if(!this.dirty && !run.dirty){
t.skip();
this._reconnectEvents(run.name);
continue;
}
run.cleanGroup();
var theme = t.next(this.opt.areas ? "area" : "line", [this.opt, run], true),
s = run.group, outline,
lpoly = arr.map(acc, function(v, i){
return {
x: ht(i + 1) + offsets.l,
y: dim.height - offsets.b - vt(v)
};
}, this);
var lpath = this.opt.tension ? dc.curve(lpoly, this.opt.tension) : "";
if(this.opt.areas){
var apoly = lang.clone(lpoly);
if(this.opt.tension){
var p=dc.curve(apoly, this.opt.tension);
p += " L" + lpoly[lpoly.length - 1].x + "," + (dim.height - offsets.b) +
" L" + lpoly[0].x + "," + (dim.height - offsets.b) +
" L" + lpoly[0].x + "," + lpoly[0].y;
run.dyn.fill = s.createPath(p).setFill(theme.series.fill).getFill();
} else {
apoly.push({x: lpoly[lpoly.length - 1].x, y: dim.height - offsets.b});
apoly.push({x: lpoly[0].x, y: dim.height - offsets.b});
apoly.push(lpoly[0]);
run.dyn.fill = s.createPolyline(apoly).setFill(theme.series.fill).getFill();
}
}
if(this.opt.lines || this.opt.markers){
if(theme.series.outline){
outline = dc.makeStroke(theme.series.outline);
outline.width = 2 * outline.width + theme.series.stroke.width;
}
}
if(this.opt.markers){
run.dyn.marker = theme.symbol;
}
var frontMarkers, outlineMarkers, shadowMarkers;
if(theme.series.shadow && theme.series.stroke){
var shadow = theme.series.shadow,
spoly = arr.map(lpoly, function(c){
return {x: c.x + shadow.dx, y: c.y + shadow.dy};
});
if(this.opt.lines){
if(this.opt.tension){
run.dyn.shadow = s.createPath(dc.curve(spoly, this.opt.tension)).setStroke(shadow).getStroke();
} else {
run.dyn.shadow = s.createPolyline(spoly).setStroke(shadow).getStroke();
}
}
if(this.opt.markers){
shadow = theme.marker.shadow;
shadowMarkers = arr.map(spoly, function(c){
return s.createPath("M" + c.x + " " + c.y + " " + theme.symbol).
setStroke(shadow).setFill(shadow.color);
}, this);
}
}
if(this.opt.lines){
if(outline){
if(this.opt.tension){
run.dyn.outline = s.createPath(lpath).setStroke(outline).getStroke();
} else {
run.dyn.outline = s.createPolyline(lpoly).setStroke(outline).getStroke();
}
}
if(this.opt.tension){
run.dyn.stroke = s.createPath(lpath).setStroke(theme.series.stroke).getStroke();
} else {
run.dyn.stroke = s.createPolyline(lpoly).setStroke(theme.series.stroke).getStroke();
}
}
if(this.opt.markers){
frontMarkers = new Array(lpoly.length);
outlineMarkers = new Array(lpoly.length);
outline = null;
if(theme.marker.outline){
outline = dc.makeStroke(theme.marker.outline);
outline.width = 2 * outline.width + (theme.marker.stroke ? theme.marker.stroke.width : 0);
}
arr.forEach(lpoly, function(c, i){
var path = "M" + c.x + " " + c.y + " " + theme.symbol;
if(outline){
outlineMarkers[i] = s.createPath(path).setStroke(outline);
}
frontMarkers[i] = s.createPath(path).setStroke(theme.marker.stroke).setFill(theme.marker.fill);
}, this);
if(events){
var eventSeries = new Array(frontMarkers.length);
arr.forEach(frontMarkers, function(s, i){
var o = {
element: "marker",
index: i,
run: run,
shape: s,
outline: outlineMarkers[i] || null,
shadow: shadowMarkers && shadowMarkers[i] || null,
cx: lpoly[i].x,
cy: lpoly[i].y,
x: i + 1,
y: run.data[i]
};
this._connectEvents(o);
eventSeries[i] = o;
}, this);
this._eventSeries[run.name] = eventSeries;
}else{
delete this._eventSeries[run.name];
}
}
run.dirty = false;
// update the accumulator
for(var j = 0; j < run.data.length; ++j){
var v = run.data[j];
if(v !== null){
if(isNaN(v)){ v = 0; }
acc[j] -= v;
}
}
}
this.dirty = false;
return this; // dojox.charting.plot2d.Stacked
}
});
});
},
'dojo/fx/easing':function(){
define(["../_base/lang"], function(lang) {
// module:
// dojo/fx/easing
// summary:
// This module defines standard easing functions that are useful for animations.
var easingFuncs = /*===== dojo.fx.easing= =====*/ {
// summary:
// Collection of easing functions to use beyond the default
// `dojo._defaultEasing` function.
//
// description:
//
// Easing functions are used to manipulate the iteration through
// an `dojo.Animation`s _Line. _Line being the properties of an Animation,
// and the easing function progresses through that Line determing
// how quickly (or slowly) it should go. Or more accurately: modify
// the value of the _Line based on the percentage of animation completed.
//
// All functions follow a simple naming convention of "ease type" + "when".
// If the name of the function ends in Out, the easing described appears
// towards the end of the animation. "In" means during the beginning,
// and InOut means both ranges of the Animation will applied, both
// beginning and end.
//
// One does not call the easing function directly, it must be passed to
// the `easing` property of an animation.
//
// example:
// | dojo.require("dojo.fx.easing");
// | var anim = dojo.fadeOut({
// | node: 'node',
// | duration: 2000,
// | // note there is no ()
// | easing: dojo.fx.easing.quadIn
// | }).play();
//
linear: function(/* Decimal? */n){
// summary: A linear easing function
return n;
},
quadIn: function(/* Decimal? */n){
return Math.pow(n, 2);
},
quadOut: function(/* Decimal? */n){
return n * (n - 2) * -1;
},
quadInOut: function(/* Decimal? */n){
n = n * 2;
if(n < 1){ return Math.pow(n, 2) / 2; }
return -1 * ((--n) * (n - 2) - 1) / 2;
},
cubicIn: function(/* Decimal? */n){
return Math.pow(n, 3);
},
cubicOut: function(/* Decimal? */n){
return Math.pow(n - 1, 3) + 1;
},
cubicInOut: function(/* Decimal? */n){
n = n * 2;
if(n < 1){ return Math.pow(n, 3) / 2; }
n -= 2;
return (Math.pow(n, 3) + 2) / 2;
},
quartIn: function(/* Decimal? */n){
return Math.pow(n, 4);
},
quartOut: function(/* Decimal? */n){
return -1 * (Math.pow(n - 1, 4) - 1);
},
quartInOut: function(/* Decimal? */n){
n = n * 2;
if(n < 1){ return Math.pow(n, 4) / 2; }
n -= 2;
return -1 / 2 * (Math.pow(n, 4) - 2);
},
quintIn: function(/* Decimal? */n){
return Math.pow(n, 5);
},
quintOut: function(/* Decimal? */n){
return Math.pow(n - 1, 5) + 1;
},
quintInOut: function(/* Decimal? */n){
n = n * 2;
if(n < 1){ return Math.pow(n, 5) / 2; }
n -= 2;
return (Math.pow(n, 5) + 2) / 2;
},
sineIn: function(/* Decimal? */n){
return -1 * Math.cos(n * (Math.PI / 2)) + 1;
},
sineOut: function(/* Decimal? */n){
return Math.sin(n * (Math.PI / 2));
},
sineInOut: function(/* Decimal? */n){
return -1 * (Math.cos(Math.PI * n) - 1) / 2;
},
expoIn: function(/* Decimal? */n){
return (n == 0) ? 0 : Math.pow(2, 10 * (n - 1));
},
expoOut: function(/* Decimal? */n){
return (n == 1) ? 1 : (-1 * Math.pow(2, -10 * n) + 1);
},
expoInOut: function(/* Decimal? */n){
if(n == 0){ return 0; }
if(n == 1){ return 1; }
n = n * 2;
if(n < 1){ return Math.pow(2, 10 * (n - 1)) / 2; }
--n;
return (-1 * Math.pow(2, -10 * n) + 2) / 2;
},
circIn: function(/* Decimal? */n){
return -1 * (Math.sqrt(1 - Math.pow(n, 2)) - 1);
},
circOut: function(/* Decimal? */n){
n = n - 1;
return Math.sqrt(1 - Math.pow(n, 2));
},
circInOut: function(/* Decimal? */n){
n = n * 2;
if(n < 1){ return -1 / 2 * (Math.sqrt(1 - Math.pow(n, 2)) - 1); }
n -= 2;
return 1 / 2 * (Math.sqrt(1 - Math.pow(n, 2)) + 1);
},
backIn: function(/* Decimal? */n){
// summary:
// An easing function that starts away from the target,
// and quickly accelerates towards the end value.
//
// Use caution when the easing will cause values to become
// negative as some properties cannot be set to negative values.
var s = 1.70158;
return Math.pow(n, 2) * ((s + 1) * n - s);
},
backOut: function(/* Decimal? */n){
// summary:
// An easing function that pops past the range briefly, and slowly comes back.
//
// description:
// An easing function that pops past the range briefly, and slowly comes back.
//
// Use caution when the easing will cause values to become negative as some
// properties cannot be set to negative values.
n = n - 1;
var s = 1.70158;
return Math.pow(n, 2) * ((s + 1) * n + s) + 1;
},
backInOut: function(/* Decimal? */n){
// summary:
// An easing function combining the effects of `backIn` and `backOut`
//
// description:
// An easing function combining the effects of `backIn` and `backOut`.
// Use caution when the easing will cause values to become negative
// as some properties cannot be set to negative values.
var s = 1.70158 * 1.525;
n = n * 2;
if(n < 1){ return (Math.pow(n, 2) * ((s + 1) * n - s)) / 2; }
n-=2;
return (Math.pow(n, 2) * ((s + 1) * n + s) + 2) / 2;
},
elasticIn: function(/* Decimal? */n){
// summary:
// An easing function the elastically snaps from the start value
//
// description:
// An easing function the elastically snaps from the start value
//
// Use caution when the elasticity will cause values to become negative
// as some properties cannot be set to negative values.
if(n == 0 || n == 1){ return n; }
var p = .3;
var s = p / 4;
n = n - 1;
return -1 * Math.pow(2, 10 * n) * Math.sin((n - s) * (2 * Math.PI) / p);
},
elasticOut: function(/* Decimal? */n){
// summary:
// An easing function that elasticly snaps around the target value,
// near the end of the Animation
//
// description:
// An easing function that elasticly snaps around the target value,
// near the end of the Animation
//
// Use caution when the elasticity will cause values to become
// negative as some properties cannot be set to negative values.
if(n==0 || n == 1){ return n; }
var p = .3;
var s = p / 4;
return Math.pow(2, -10 * n) * Math.sin((n - s) * (2 * Math.PI) / p) + 1;
},
elasticInOut: function(/* Decimal? */n){
// summary:
// An easing function that elasticly snaps around the value, near
// the beginning and end of the Animation.
//
// description:
// An easing function that elasticly snaps around the value, near
// the beginning and end of the Animation.
//
// Use caution when the elasticity will cause values to become
// negative as some properties cannot be set to negative values.
if(n == 0) return 0;
n = n * 2;
if(n == 2) return 1;
var p = .3 * 1.5;
var s = p / 4;
if(n < 1){
n -= 1;
return -.5 * (Math.pow(2, 10 * n) * Math.sin((n - s) * (2 * Math.PI) / p));
}
n -= 1;
return .5 * (Math.pow(2, -10 * n) * Math.sin((n - s) * (2 * Math.PI) / p)) + 1;
},
bounceIn: function(/* Decimal? */n){
// summary:
// An easing function that 'bounces' near the beginning of an Animation
return (1 - easingFuncs.bounceOut(1 - n)); // Decimal
},
bounceOut: function(/* Decimal? */n){
// summary:
// An easing function that 'bounces' near the end of an Animation
var s = 7.5625;
var p = 2.75;
var l;
if(n < (1 / p)){
l = s * Math.pow(n, 2);
}else if(n < (2 / p)){
n -= (1.5 / p);
l = s * Math.pow(n, 2) + .75;
}else if(n < (2.5 / p)){
n -= (2.25 / p);
l = s * Math.pow(n, 2) + .9375;
}else{
n -= (2.625 / p);
l = s * Math.pow(n, 2) + .984375;
}
return l;
},
bounceInOut: function(/* Decimal? */n){
// summary:
// An easing function that 'bounces' at the beginning and end of the Animation
if(n < 0.5){ return easingFuncs.bounceIn(n * 2) / 2; }
return (easingFuncs.bounceOut(n * 2 - 1) / 2) + 0.5; // Decimal
}
};
lang.setObject("dojo.fx.easing", easingFuncs);
return easingFuncs;
});
},
'dojox/charting/action2d/Highlight':function(){
define("dojox/charting/action2d/Highlight", ["dojo/_base/kernel", "dojo/_base/lang", "dojo/_base/declare", "dojo/_base/Color", "dojo/_base/connect", "dojox/color/_base",
"./PlotAction", "dojo/fx/easing", "dojox/gfx/fx"],
function(dojo, lang, declare, Color, hub, c, PlotAction, dfe, dgf){
/*=====
dojo.declare("dojox.charting.action2d.__HighlightCtorArgs", dojox.charting.action2d.__PlotActionCtorArgs, {
// summary:
// Additional arguments for highlighting actions.
// highlight: String|dojo.Color|Function?
// Either a color or a function that creates a color when highlighting happens.
highlight: null
});
var PlotAction = dojox.charting.action2d.PlotAction;
=====*/
var DEFAULT_SATURATION = 100, // %
DEFAULT_LUMINOSITY1 = 75, // %
DEFAULT_LUMINOSITY2 = 50, // %
cc = function(color){
return function(){ return color; };
},
hl = function(color){
var a = new c.Color(color),
x = a.toHsl();
if(x.s == 0){
x.l = x.l < 50 ? 100 : 0;
}else{
x.s = DEFAULT_SATURATION;
if(x.l < DEFAULT_LUMINOSITY2){
x.l = DEFAULT_LUMINOSITY1;
}else if(x.l > DEFAULT_LUMINOSITY1){
x.l = DEFAULT_LUMINOSITY2;
}else{
x.l = x.l - DEFAULT_LUMINOSITY2 > DEFAULT_LUMINOSITY1 - x.l ?
DEFAULT_LUMINOSITY2 : DEFAULT_LUMINOSITY1;
}
}
return c.fromHsl(x);
};
return declare("dojox.charting.action2d.Highlight", PlotAction, {
// summary:
// Creates a highlighting action on a plot, where an element on that plot
// has a highlight on it.
// the data description block for the widget parser
defaultParams: {
duration: 400, // duration of the action in ms
easing: dfe.backOut // easing for the action
},
optionalParams: {
highlight: "red" // name for the highlight color
// programmatic instantiation can use functions and color objects
},
constructor: function(chart, plot, kwArgs){
// summary:
// Create the highlighting action and connect it to the plot.
// chart: dojox.charting.Chart
// The chart this action belongs to.
// plot: String?
// The plot this action is attached to. If not passed, "default" is assumed.
// kwArgs: charting.action2d.__HighlightCtorArgs?
// Optional keyword arguments object for setting parameters.
var a = kwArgs && kwArgs.highlight;
this.colorFun = a ? (lang.isFunction(a) ? a : cc(a)) : hl;
this.connect();
},
process: function(o){
// summary:
// Process the action on the given object.
// o: dojox.gfx.Shape
// The object on which to process the highlighting action.
if(!o.shape || !(o.type in this.overOutEvents)){ return; }
var runName = o.run.name, index = o.index, anim, startFill, endFill;
if(runName in this.anim){
anim = this.anim[runName][index];
}else{
this.anim[runName] = {};
}
if(anim){
anim.action.stop(true);
}else{
var color = o.shape.getFill();
if(!color || !(color instanceof Color)){
return;
}
this.anim[runName][index] = anim = {
start: color,
end: this.colorFun(color)
};
}
var start = anim.start, end = anim.end;
if(o.type == "onmouseout"){
// swap colors
var t = start;
start = end;
end = t;
}
anim.action = dgf.animateFill({
shape: o.shape,
duration: this.duration,
easing: this.easing,
color: {start: start, end: end}
});
if(o.type == "onmouseout"){
hub.connect(anim.action, "onEnd", this, function(){
if(this.anim[runName]){
delete this.anim[runName][index];
}
});
}
anim.action.play();
}
});
});
},
'dojox/color/Palette':function(){
define("dojox/color/Palette", ["dojo/_base/kernel", "../main", "dojo/_base/lang", "dojo/_base/array", "./_base"],
function(dojo, dojox, lang, arr, dxc){
/***************************************************************
* dojox.color.Palette
*
* The Palette object is loosely based on the color palettes
* at Kuler (http://kuler.adobe.com). They are 5 color palettes
* with the base color considered to be the third color in the
* palette (for generation purposes).
*
* Palettes can be generated from well-known algorithms or they
* can be manually created by passing an array to the constructor.
*
* Palettes can be transformed, using a set of specific params
* similar to the way shapes can be transformed with dojox.gfx.
* However, unlike with transformations in dojox.gfx, transforming
* a palette will return you a new Palette object, in effect
* a clone of the original.
***************************************************************/
// ctor ----------------------------------------------------------------------------
dxc.Palette = function(/* String|Array|dojox.color.Color|dojox.color.Palette */base){
// summary:
// An object that represents a palette of colors.
// description:
// A Palette is a representation of a set of colors. While the standard
// number of colors contained in a palette is 5, it can really handle any
// number of colors.
//
// A palette is useful for the ability to transform all the colors in it
// using a simple object-based approach. In addition, you can generate
// palettes using dojox.color.Palette.generate; these generated palettes
// are based on the palette generators at http://kuler.adobe.com.
//
// colors: dojox.color.Color[]
// The actual color references in this palette.
this.colors = [];
if(base instanceof dxc.Palette){
this.colors = base.colors.slice(0);
}
else if(base instanceof dxc.Color){
this.colors = [ null, null, base, null, null ];
}
else if(lang.isArray(base)){
this.colors = arr.map(base.slice(0), function(item){
if(lang.isString(item)){ return new dxc.Color(item); }
return item;
});
}
else if (lang.isString(base)){
this.colors = [ null, null, new dxc.Color(base), null, null ];
}
}
// private functions ---------------------------------------------------------------
// transformations
function tRGBA(p, param, val){
var ret = new dxc.Palette();
ret.colors = [];
arr.forEach(p.colors, function(item){
var r=(param=="dr")?item.r+val:item.r,
g=(param=="dg")?item.g+val:item.g,
b=(param=="db")?item.b+val:item.b,
a=(param=="da")?item.a+val:item.a
ret.colors.push(new dxc.Color({
r: Math.min(255, Math.max(0, r)),
g: Math.min(255, Math.max(0, g)),
b: Math.min(255, Math.max(0, b)),
a: Math.min(1, Math.max(0, a))
}));
});
return ret;
}
function tCMY(p, param, val){
var ret = new dxc.Palette();
ret.colors = [];
arr.forEach(p.colors, function(item){
var o=item.toCmy(),
c=(param=="dc")?o.c+val:o.c,
m=(param=="dm")?o.m+val:o.m,
y=(param=="dy")?o.y+val:o.y;
ret.colors.push(dxc.fromCmy(
Math.min(100, Math.max(0, c)),
Math.min(100, Math.max(0, m)),
Math.min(100, Math.max(0, y))
));
});
return ret;
}
function tCMYK(p, param, val){
var ret = new dxc.Palette();
ret.colors = [];
arr.forEach(p.colors, function(item){
var o=item.toCmyk(),
c=(param=="dc")?o.c+val:o.c,
m=(param=="dm")?o.m+val:o.m,
y=(param=="dy")?o.y+val:o.y,
k=(param=="dk")?o.b+val:o.b;
ret.colors.push(dxc.fromCmyk(
Math.min(100, Math.max(0, c)),
Math.min(100, Math.max(0, m)),
Math.min(100, Math.max(0, y)),
Math.min(100, Math.max(0, k))
));
});
return ret;
}
function tHSL(p, param, val){
var ret = new dxc.Palette();
ret.colors = [];
arr.forEach(p.colors, function(item){
var o=item.toHsl(),
h=(param=="dh")?o.h+val:o.h,
s=(param=="ds")?o.s+val:o.s,
l=(param=="dl")?o.l+val:o.l;
ret.colors.push(dxc.fromHsl(h%360, Math.min(100, Math.max(0, s)), Math.min(100, Math.max(0, l))));
});
return ret;
}
function tHSV(p, param, val){
var ret = new dxc.Palette();
ret.colors = [];
arr.forEach(p.colors, function(item){
var o=item.toHsv(),
h=(param=="dh")?o.h+val:o.h,
s=(param=="ds")?o.s+val:o.s,
v=(param=="dv")?o.v+val:o.v;
ret.colors.push(dxc.fromHsv(h%360, Math.min(100, Math.max(0, s)), Math.min(100, Math.max(0, v))));
});
return ret;
}
// helper functions
function rangeDiff(val, low, high){
// given the value in a range from 0 to high, find the equiv
// using the range low to high.
return high-((high-val)*((high-low)/high));
}
// object methods ---------------------------------------------------------------
lang.extend(dxc.Palette, {
transform: function(/* dojox.color.Palette.__transformArgs */kwArgs){
// summary:
// Transform the palette using a specific transformation function
// and a set of transformation parameters.
// description:
// {palette}.transform is a simple way to uniformly transform
// all of the colors in a palette using any of 5 formulae:
// RGBA, HSL, HSV, CMYK or CMY.
//
// Once the forumula to be used is determined, you can pass any
// number of parameters based on the formula "d"[param]; for instance,
// { use: "rgba", dr: 20, dg: -50 } will take all of the colors in
// palette, add 20 to the R value and subtract 50 from the G value.
//
// Unlike other types of transformations, transform does *not* alter
// the original palette but will instead return a new one.
var fn=tRGBA; // the default transform function.
if(kwArgs.use){
// we are being specific about the algo we want to use.
var use=kwArgs.use.toLowerCase();
if(use.indexOf("hs")==0){
if(use.charAt(2)=="l"){ fn=tHSL; }
else { fn=tHSV; }
}
else if(use.indexOf("cmy")==0){
if(use.charAt(3)=="k"){ fn=tCMYK; }
else { fn=tCMY; }
}
}
// try to guess the best choice.
else if("dc" in kwArgs || "dm" in kwArgs || "dy" in kwArgs){
if("dk" in kwArgs){ fn = tCMYK; }
else { fn = tCMY; }
}
else if("dh" in kwArgs || "ds" in kwArgs){
if("dv" in kwArgs){ fn = tHSV; }
else { fn = tHSL; }
}
var palette = this;
for(var p in kwArgs){
// ignore use
if(p=="use"){ continue; }
palette = fn(palette, p, kwArgs[p]);
}
return palette; // dojox.color.Palette
},
clone: function(){
// summary:
// Clones the current palette.
return new dxc.Palette(this); // dojox.color.Palette
}
});
/*=====
dojox.color.Palette.__transformArgs = function(use, dr, dg, db, da, dc, dm, dy, dk, dh, ds, dv, dl){
// summary:
// The keywords argument to be passed to the dojox.color.Palette.transform function. Note that
// while all arguments are optional, *some* arguments must be passed. The basic concept is that
// you pass a delta value for a specific aspect of a color model (or multiple aspects of the same
// color model); for instance, if you wish to transform a palette based on the HSV color model,
// you would pass one of "dh", "ds", or "dv" as a value.
//
// use: String?
// Specify the color model to use for the transformation. Can be "rgb", "rgba", "hsv", "hsl", "cmy", "cmyk".
// dr: Number?
// The delta to be applied to the red aspect of the RGB/RGBA color model.
// dg: Number?
// The delta to be applied to the green aspect of the RGB/RGBA color model.
// db: Number?
// The delta to be applied to the blue aspect of the RGB/RGBA color model.
// da: Number?
// The delta to be applied to the alpha aspect of the RGBA color model.
// dc: Number?
// The delta to be applied to the cyan aspect of the CMY/CMYK color model.
// dm: Number?
// The delta to be applied to the magenta aspect of the CMY/CMYK color model.
// dy: Number?
// The delta to be applied to the yellow aspect of the CMY/CMYK color model.
// dk: Number?
// The delta to be applied to the black aspect of the CMYK color model.
// dh: Number?
// The delta to be applied to the hue aspect of the HSL/HSV color model.
// ds: Number?
// The delta to be applied to the saturation aspect of the HSL/HSV color model.
// dl: Number?
// The delta to be applied to the luminosity aspect of the HSL color model.
// dv: Number?
// The delta to be applied to the value aspect of the HSV color model.
this.use = use;
this.dr = dr;
this.dg = dg;
this.db = db;
this.da = da;
this.dc = dc;
this.dm = dm;
this.dy = dy;
this.dk = dk;
this.dh = dh;
this.ds = ds;
this.dl = dl;
this.dv = dv;
}
dojox.color.Palette.__generatorArgs = function(base){
// summary:
// The keyword arguments object used to create a palette based on a base color.
//
// base: dojo.Color
// The base color to be used to generate the palette.
this.base = base;
}
dojox.color.Palette.__analogousArgs = function(base, high, low){
// summary:
// The keyword arguments object that is used to create a 5 color palette based on the
// analogous rules as implemented at http://kuler.adobe.com, using the HSV color model.
//
// base: dojo.Color
// The base color to be used to generate the palette.
// high: Number?
// The difference between the hue of the base color and the highest hue. In degrees, default is 60.
// low: Number?
// The difference between the hue of the base color and the lowest hue. In degrees, default is 18.
this.base = base;
this.high = high;
this.low = low;
}
dojox.color.Palette.__splitComplementaryArgs = function(base, da){
// summary:
// The keyword arguments object used to create a palette based on the split complementary rules
// as implemented at http://kuler.adobe.com.
//
// base: dojo.Color
// The base color to be used to generate the palette.
// da: Number?
// The delta angle to be used to determine where the split for the complementary rules happen.
// In degrees, the default is 30.
this.base = base;
this.da = da;
}
=====*/
lang.mixin(dxc.Palette, {
generators: {
analogous:function(/* dojox.color.Palette.__analogousArgs */args){
// summary:
// Create a 5 color palette based on the analogous rules as implemented at
// http://kuler.adobe.com.
var high=args.high||60, // delta between base hue and highest hue (subtracted from base)
low=args.low||18, // delta between base hue and lowest hue (added to base)
base = lang.isString(args.base)?new dxc.Color(args.base):args.base,
hsv=base.toHsv();
// generate our hue angle differences
var h=[
(hsv.h+low+360)%360,
(hsv.h+Math.round(low/2)+360)%360,
hsv.h,
(hsv.h-Math.round(high/2)+360)%360,
(hsv.h-high+360)%360
];
var s1=Math.max(10, (hsv.s<=95)?hsv.s+5:(100-(hsv.s-95))),
s2=(hsv.s>1)?hsv.s-1:21-hsv.s,
v1=(hsv.v>=92)?hsv.v-9:Math.max(hsv.v+9, 20),
v2=(hsv.v<=90)?Math.max(hsv.v+5, 20):(95+Math.ceil((hsv.v-90)/2)),
s=[ s1, s2, hsv.s, s1, s1 ],
v=[ v1, v2, hsv.v, v1, v2 ]
return new dxc.Palette(arr.map(h, function(hue, i){
return dxc.fromHsv(hue, s[i], v[i]);
})); // dojox.color.Palette
},
monochromatic: function(/* dojox.color.Palette.__generatorArgs */args){
// summary:
// Create a 5 color palette based on the monochromatic rules as implemented at
// http://kuler.adobe.com.
var base = lang.isString(args.base)?new dxc.Color(args.base):args.base,
hsv = base.toHsv();
// figure out the saturation and value
var s1 = (hsv.s-30>9)?hsv.s-30:hsv.s+30,
s2 = hsv.s,
v1 = rangeDiff(hsv.v, 20, 100),
v2 = (hsv.v-20>20)?hsv.v-20:hsv.v+60,
v3 = (hsv.v-50>20)?hsv.v-50:hsv.v+30;
return new dxc.Palette([
dxc.fromHsv(hsv.h, s1, v1),
dxc.fromHsv(hsv.h, s2, v3),
base,
dxc.fromHsv(hsv.h, s1, v3),
dxc.fromHsv(hsv.h, s2, v2)
]); // dojox.color.Palette
},
triadic: function(/* dojox.color.Palette.__generatorArgs */args){
// summary:
// Create a 5 color palette based on the triadic rules as implemented at
// http://kuler.adobe.com.
var base = lang.isString(args.base)?new dxc.Color(args.base):args.base,
hsv = base.toHsv();
var h1 = (hsv.h+57+360)%360,
h2 = (hsv.h-157+360)%360,
s1 = (hsv.s>20)?hsv.s-10:hsv.s+10,
s2 = (hsv.s>90)?hsv.s-10:hsv.s+10,
s3 = (hsv.s>95)?hsv.s-5:hsv.s+5,
v1 = (hsv.v-20>20)?hsv.v-20:hsv.v+20,
v2 = (hsv.v-30>20)?hsv.v-30:hsv.v+30,
v3 = (hsv.v-30>70)?hsv.v-30:hsv.v+30;
return new dxc.Palette([
dxc.fromHsv(h1, s1, hsv.v),
dxc.fromHsv(hsv.h, s2, v2),
base,
dxc.fromHsv(h2, s2, v1),
dxc.fromHsv(h2, s3, v3)
]); // dojox.color.Palette
},
complementary: function(/* dojox.color.Palette.__generatorArgs */args){
// summary:
// Create a 5 color palette based on the complementary rules as implemented at
// http://kuler.adobe.com.
var base = lang.isString(args.base)?new dxc.Color(args.base):args.base,
hsv = base.toHsv();
var h1 = ((hsv.h*2)+137<360)?(hsv.h*2)+137:Math.floor(hsv.h/2)-137,
s1 = Math.max(hsv.s-10, 0),
s2 = rangeDiff(hsv.s, 10, 100),
s3 = Math.min(100, hsv.s+20),
v1 = Math.min(100, hsv.v+30),
v2 = (hsv.v>20)?hsv.v-30:hsv.v+30;
return new dxc.Palette([
dxc.fromHsv(hsv.h, s1, v1),
dxc.fromHsv(hsv.h, s2, v2),
base,
dxc.fromHsv(h1, s3, v2),
dxc.fromHsv(h1, hsv.s, hsv.v)
]); // dojox.color.Palette
},
splitComplementary: function(/* dojox.color.Palette.__splitComplementaryArgs */args){
// summary:
// Create a 5 color palette based on the split complementary rules as implemented at
// http://kuler.adobe.com.
var base = lang.isString(args.base)?new dxc.Color(args.base):args.base,
dangle = args.da || 30,
hsv = base.toHsv();
var baseh = ((hsv.h*2)+137<360)?(hsv.h*2)+137:Math.floor(hsv.h/2)-137,
h1 = (baseh-dangle+360)%360,
h2 = (baseh+dangle)%360,
s1 = Math.max(hsv.s-10, 0),
s2 = rangeDiff(hsv.s, 10, 100),
s3 = Math.min(100, hsv.s+20),
v1 = Math.min(100, hsv.v+30),
v2 = (hsv.v>20)?hsv.v-30:hsv.v+30;
return new dxc.Palette([
dxc.fromHsv(h1, s1, v1),
dxc.fromHsv(h1, s2, v2),
base,
dxc.fromHsv(h2, s3, v2),
dxc.fromHsv(h2, hsv.s, hsv.v)
]); // dojox.color.Palette
},
compound: function(/* dojox.color.Palette.__generatorArgs */args){
// summary:
// Create a 5 color palette based on the compound rules as implemented at
// http://kuler.adobe.com.
var base = lang.isString(args.base)?new dxc.Color(args.base):args.base,
hsv = base.toHsv();
var h1 = ((hsv.h*2)+18<360)?(hsv.h*2)+18:Math.floor(hsv.h/2)-18,
h2 = ((hsv.h*2)+120<360)?(hsv.h*2)+120:Math.floor(hsv.h/2)-120,
h3 = ((hsv.h*2)+99<360)?(hsv.h*2)+99:Math.floor(hsv.h/2)-99,
s1 = (hsv.s-40>10)?hsv.s-40:hsv.s+40,
s2 = (hsv.s-10>80)?hsv.s-10:hsv.s+10,
s3 = (hsv.s-25>10)?hsv.s-25:hsv.s+25,
v1 = (hsv.v-40>10)?hsv.v-40:hsv.v+40,
v2 = (hsv.v-20>80)?hsv.v-20:hsv.v+20,
v3 = Math.max(hsv.v, 20);
return new dxc.Palette([
dxc.fromHsv(h1, s1, v1),
dxc.fromHsv(h1, s2, v2),
base,
dxc.fromHsv(h2, s3, v3),
dxc.fromHsv(h3, s2, v2)
]); // dojox.color.Palette
},
shades: function(/* dojox.color.Palette.__generatorArgs */args){
// summary:
// Create a 5 color palette based on the shades rules as implemented at
// http://kuler.adobe.com.
var base = lang.isString(args.base)?new dxc.Color(args.base):args.base,
hsv = base.toHsv();
var s = (hsv.s==100 && hsv.v==0)?0:hsv.s,
v1 = (hsv.v-50>20)?hsv.v-50:hsv.v+30,
v2 = (hsv.v-25>=20)?hsv.v-25:hsv.v+55,
v3 = (hsv.v-75>=20)?hsv.v-75:hsv.v+5,
v4 = Math.max(hsv.v-10, 20);
return new dxc.Palette([
new dxc.fromHsv(hsv.h, s, v1),
new dxc.fromHsv(hsv.h, s, v2),
base,
new dxc.fromHsv(hsv.h, s, v3),
new dxc.fromHsv(hsv.h, s, v4)
]); // dojox.color.Palette
}
},
generate: function(/* String|dojox.color.Color */base, /* Function|String */type){
// summary:
// Generate a new Palette using any of the named functions in
// dojox.color.Palette.generators or an optional function definition. Current
// generators include "analogous", "monochromatic", "triadic", "complementary",
// "splitComplementary", and "shades".
if(lang.isFunction(type)){
return type({ base: base }); // dojox.color.Palette
}
else if(dxc.Palette.generators[type]){
return dxc.Palette.generators[type]({ base: base }); // dojox.color.Palette
}
throw new Error("dojox.color.Palette.generate: the specified generator ('" + type + "') does not exist.");
}
});
return dxc.Palette;
});
},
'dijit/a11y':function(){
define("dijit/a11y", [
"dojo/_base/array", // array.forEach array.map
"dojo/_base/config", // defaultDuration
"dojo/_base/declare", // declare
"dojo/dom", // dom.byId
"dojo/dom-attr", // domAttr.attr domAttr.has
"dojo/dom-style", // style.style
"dojo/_base/sniff", // has("ie")
"./_base/manager", // manager._isElementShown
"." // for exporting methods to dijit namespace
], function(array, config, declare, dom, domAttr, domStyle, has, manager, dijit){
// module:
// dijit/a11y
// summary:
// Accessibility utility functions (keyboard, tab stops, etc.)
var shown = (dijit._isElementShown = function(/*Element*/ elem){
var s = domStyle.get(elem);
return (s.visibility != "hidden")
&& (s.visibility != "collapsed")
&& (s.display != "none")
&& (domAttr.get(elem, "type") != "hidden");
});
dijit.hasDefaultTabStop = function(/*Element*/ elem){
// summary:
// Tests if element is tab-navigable even without an explicit tabIndex setting
// No explicit tabIndex setting, need to investigate node type
switch(elem.nodeName.toLowerCase()){
case "a":
// An <a> w/out a tabindex is only navigable if it has an href
return domAttr.has(elem, "href");
case "area":
case "button":
case "input":
case "object":
case "select":
case "textarea":
// These are navigable by default
return true;
case "iframe":
// If it's an editor <iframe> then it's tab navigable.
var body;
try{
// non-IE
var contentDocument = elem.contentDocument;
if("designMode" in contentDocument && contentDocument.designMode == "on"){
return true;
}
body = contentDocument.body;
}catch(e1){
// contentWindow.document isn't accessible within IE7/8
// if the iframe.src points to a foreign url and this
// page contains an element, that could get focus
try{
body = elem.contentWindow.document.body;
}catch(e2){
return false;
}
}
return body && (body.contentEditable == 'true' ||
(body.firstChild && body.firstChild.contentEditable == 'true'));
default:
return elem.contentEditable == 'true';
}
};
var isTabNavigable = (dijit.isTabNavigable = function(/*Element*/ elem){
// summary:
// Tests if an element is tab-navigable
// TODO: convert (and rename method) to return effective tabIndex; will save time in _getTabNavigable()
if(domAttr.get(elem, "disabled")){
return false;
}else if(domAttr.has(elem, "tabIndex")){
// Explicit tab index setting
return domAttr.get(elem, "tabIndex") >= 0; // boolean
}else{
// No explicit tabIndex setting, so depends on node type
return dijit.hasDefaultTabStop(elem);
}
});
dijit._getTabNavigable = function(/*DOMNode*/ root){
// summary:
// Finds descendants of the specified root node.
//
// description:
// Finds the following descendants of the specified root node:
// * the first tab-navigable element in document order
// without a tabIndex or with tabIndex="0"
// * the last tab-navigable element in document order
// without a tabIndex or with tabIndex="0"
// * the first element in document order with the lowest
// positive tabIndex value
// * the last element in document order with the highest
// positive tabIndex value
var first, last, lowest, lowestTabindex, highest, highestTabindex, radioSelected = {};
function radioName(node){
// If this element is part of a radio button group, return the name for that group.
return node && node.tagName.toLowerCase() == "input" &&
node.type && node.type.toLowerCase() == "radio" &&
node.name && node.name.toLowerCase();
}
var walkTree = function(/*DOMNode*/parent){
for(var child = parent.firstChild; child; child = child.nextSibling){
// Skip text elements, hidden elements, and also non-HTML elements (those in custom namespaces) in IE,
// since show() invokes getAttribute("type"), which crash on VML nodes in IE.
if(child.nodeType != 1 || (has("ie") && child.scopeName !== "HTML") || !shown(child)){
continue;
}
if(isTabNavigable(child)){
var tabindex = domAttr.get(child, "tabIndex");
if(!domAttr.has(child, "tabIndex") || tabindex == 0){
if(!first){
first = child;
}
last = child;
}else if(tabindex > 0){
if(!lowest || tabindex < lowestTabindex){
lowestTabindex = tabindex;
lowest = child;
}
if(!highest || tabindex >= highestTabindex){
highestTabindex = tabindex;
highest = child;
}
}
var rn = radioName(child);
if(domAttr.get(child, "checked") && rn){
radioSelected[rn] = child;
}
}
if(child.nodeName.toUpperCase() != 'SELECT'){
walkTree(child);
}
}
};
if(shown(root)){
walkTree(root);
}
function rs(node){
// substitute checked radio button for unchecked one, if there is a checked one with the same name.
return radioSelected[radioName(node)] || node;
}
return { first: rs(first), last: rs(last), lowest: rs(lowest), highest: rs(highest) };
};
dijit.getFirstInTabbingOrder = function(/*String|DOMNode*/ root){
// summary:
// Finds the descendant of the specified root node
// that is first in the tabbing order
var elems = dijit._getTabNavigable(dom.byId(root));
return elems.lowest ? elems.lowest : elems.first; // DomNode
};
dijit.getLastInTabbingOrder = function(/*String|DOMNode*/ root){
// summary:
// Finds the descendant of the specified root node
// that is last in the tabbing order
var elems = dijit._getTabNavigable(dom.byId(root));
return elems.last ? elems.last : elems.highest; // DomNode
};
return {
hasDefaultTabStop: dijit.hasDefaultTabStop,
isTabNavigable: dijit.isTabNavigable,
_getTabNavigable: dijit._getTabNavigable,
getFirstInTabbingOrder: dijit.getFirstInTabbingOrder,
getLastInTabbingOrder: dijit.getLastInTabbingOrder
};
});
},
'dojox/charting/axis2d/Base':function(){
define("dojox/charting/axis2d/Base", ["dojo/_base/declare", "../Element"],
function(declare, Element){
/*=====
var Element = dojox.charting.Element;
=====*/
return declare("dojox.charting.axis2d.Base", Element, {
// summary:
// The base class for any axis. This is more of an interface/API
// definition than anything else; see dojox.charting.axis2d.Default
// for more details.
constructor: function(chart, kwArgs){
// summary:
// Return a new base axis.
// chart: dojox.charting.Chart
// The chart this axis belongs to.
// kwArgs: dojox.charting.axis2d.__AxisCtorArgs?
// An optional arguments object to define the axis parameters.
this.vertical = kwArgs && kwArgs.vertical;
},
clear: function(){
// summary:
// Stub function for clearing the axis.
// returns: dojox.charting.axis2d.Base
// A reference to the axis for functional chaining.
return this; // dojox.charting.axis2d.Base
},
initialized: function(){
// summary:
// Return a flag as to whether or not this axis has been initialized.
// returns: Boolean
// If the axis is initialized or not.
return false; // Boolean
},
calculate: function(min, max, span){
// summary:
// Stub function to run the calcuations needed for drawing this axis.
// returns: dojox.charting.axis2d.Base
// A reference to the axis for functional chaining.
return this; // dojox.charting.axis2d.Base
},
getScaler: function(){
// summary:
// A stub function to return the scaler object created during calculate.
// returns: Object
// The scaler object (see dojox.charting.scaler.linear for more information)
return null; // Object
},
getTicks: function(){
// summary:
// A stub function to return the object that helps define how ticks are rendered.
// returns: Object
// The ticks object.
return null; // Object
},
getOffsets: function(){
// summary:
// A stub function to return any offsets needed for axis and series rendering.
// returns: Object
// An object of the form { l, r, t, b }.
return {l: 0, r: 0, t: 0, b: 0}; // Object
},
render: function(dim, offsets){
// summary:
// Stub function to render this axis.
// returns: dojox.charting.axis2d.Base
// A reference to the axis for functional chaining.
this.dirty = false;
return this; // dojox.charting.axis2d.Base
}
});
});
},
'dojox/charting/plot2d/Grid':function(){
define("dojox/charting/plot2d/Grid", ["dojo/_base/lang", "dojo/_base/declare", "dojo/_base/connect", "dojo/_base/array",
"../Element", "./common", "dojox/lang/utils", "dojox/gfx/fx"],
function(lang, declare, hub, arr, Element, dc, du, fx){
/*=====
dojo.declare("dojox.charting.plot2d.__GridCtorArgs", dojox.charting.plot2d.__DefaultCtorArgs, {
// summary:
// A special keyword arguments object that is specific to a grid "plot".
// hMajorLines: Boolean?
// Whether to show lines at the major ticks along the horizontal axis. Default is true.
hMajorLines: true,
// hMinorLines: Boolean?
// Whether to show lines at the minor ticks along the horizontal axis. Default is false.
hMinorLines: false,
// vMajorLines: Boolean?
// Whether to show lines at the major ticks along the vertical axis. Default is true.
vMajorLines: true,
// vMinorLines: Boolean?
// Whether to show lines at the major ticks along the vertical axis. Default is false.
vMinorLines: false,
// hStripes: String?
// Whether or not to show stripes (alternating fills) along the horizontal axis. Default is "none".
hStripes: "none",
// vStripes: String?
// Whether or not to show stripes (alternating fills) along the vertical axis. Default is "none".
vStripes: "none",
// enableCache: Boolean?
// Whether the grid lines are cached from one rendering to another. This improves the rendering performance of
// successive rendering but penalize the first rendering. Default false.
enableCache: false
});
var Element = dojox.charting.plot2d.Element;
=====*/
return declare("dojox.charting.plot2d.Grid", Element, {
// summary:
// A "faux" plot that can be placed behind other plots to represent
// a grid against which other plots can be easily measured.
defaultParams: {
hAxis: "x", // use a horizontal axis named "x"
vAxis: "y", // use a vertical axis named "y"
hMajorLines: true, // draw horizontal major lines
hMinorLines: false, // draw horizontal minor lines
vMajorLines: true, // draw vertical major lines
vMinorLines: false, // draw vertical minor lines
hStripes: "none", // TBD
vStripes: "none", // TBD
animate: null, // animate bars into place
enableCache: false
},
optionalParams: {}, // no optional parameters
constructor: function(chart, kwArgs){
// summary:
// Create the faux Grid plot.
// chart: dojox.charting.Chart
// The chart this plot belongs to.
// kwArgs: dojox.charting.plot2d.__GridCtorArgs?
// An optional keyword arguments object to help define the parameters of the underlying grid.
this.opt = lang.clone(this.defaultParams);
du.updateWithObject(this.opt, kwArgs);
this.hAxis = this.opt.hAxis;
this.vAxis = this.opt.vAxis;
this.dirty = true;
this.animate = this.opt.animate;
this.zoom = null,
this.zoomQueue = []; // zooming action task queue
this.lastWindow = {vscale: 1, hscale: 1, xoffset: 0, yoffset: 0};
if(this.opt.enableCache){
this._lineFreePool = [];
this._lineUsePool = [];
}
},
clear: function(){
// summary:
// Clear out any parameters set on this plot.
// returns: dojox.charting.plot2d.Grid
// The reference to this plot for functional chaining.
this._hAxis = null;
this._vAxis = null;
this.dirty = true;
return this; // dojox.charting.plot2d.Grid
},
setAxis: function(axis){
// summary:
// Set an axis for this plot.
// returns: dojox.charting.plot2d.Grid
// The reference to this plot for functional chaining.
if(axis){
this[axis.vertical ? "_vAxis" : "_hAxis"] = axis;
}
return this; // dojox.charting.plot2d.Grid
},
addSeries: function(run){
// summary:
// Ignored but included as a dummy method.
// returns: dojox.charting.plot2d.Grid
// The reference to this plot for functional chaining.
return this; // dojox.charting.plot2d.Grid
},
getSeriesStats: function(){
// summary:
// Returns default stats (irrelevant for this type of plot).
// returns: Object
// {hmin, hmax, vmin, vmax} min/max in both directions.
return lang.delegate(dc.defaultStats);
},
initializeScalers: function(){
// summary:
// Does nothing (irrelevant for this type of plot).
return this;
},
isDirty: function(){
// summary:
// Return whether or not this plot needs to be redrawn.
// returns: Boolean
// If this plot needs to be rendered, this will return true.
return this.dirty || this._hAxis && this._hAxis.dirty || this._vAxis && this._vAxis.dirty; // Boolean
},
performZoom: function(dim, offsets){
// summary:
// Create/alter any zooming windows on this plot.
// dim: Object
// An object of the form { width, height }.
// offsets: Object
// An object of the form { l, r, t, b }.
// returns: dojox.charting.plot2d.Grid
// A reference to this plot for functional chaining.
// get current zooming various
var vs = this._vAxis.scale || 1,
hs = this._hAxis.scale || 1,
vOffset = dim.height - offsets.b,
hBounds = this._hAxis.getScaler().bounds,
xOffset = (hBounds.from - hBounds.lower) * hBounds.scale,
vBounds = this._vAxis.getScaler().bounds,
yOffset = (vBounds.from - vBounds.lower) * vBounds.scale,
// get incremental zooming various
rVScale = vs / this.lastWindow.vscale,
rHScale = hs / this.lastWindow.hscale,
rXOffset = (this.lastWindow.xoffset - xOffset)/
((this.lastWindow.hscale == 1)? hs : this.lastWindow.hscale),
rYOffset = (yOffset - this.lastWindow.yoffset)/
((this.lastWindow.vscale == 1)? vs : this.lastWindow.vscale),
shape = this.group,
anim = fx.animateTransform(lang.delegate({
shape: shape,
duration: 1200,
transform:[
{name:"translate", start:[0, 0], end: [offsets.l * (1 - rHScale), vOffset * (1 - rVScale)]},
{name:"scale", start:[1, 1], end: [rHScale, rVScale]},
{name:"original"},
{name:"translate", start: [0, 0], end: [rXOffset, rYOffset]}
]}, this.zoom));
lang.mixin(this.lastWindow, {vscale: vs, hscale: hs, xoffset: xOffset, yoffset: yOffset});
//add anim to zooming action queue,
//in order to avoid several zooming action happened at the same time
this.zoomQueue.push(anim);
//perform each anim one by one in zoomQueue
hub.connect(anim, "onEnd", this, function(){
this.zoom = null;
this.zoomQueue.shift();
if(this.zoomQueue.length > 0){
this.zoomQueue[0].play();
}
});
if(this.zoomQueue.length == 1){
this.zoomQueue[0].play();
}
return this; // dojox.charting.plot2d.Grid
},
getRequiredColors: function(){
// summary:
// Ignored but included as a dummy method.
// returns: Number
// Returns 0, since there are no series associated with this plot type.
return 0; // Number
},
cleanGroup: function(){
this.inherited(arguments);
if(this.opt.enableCache){
this._lineFreePool = this._lineFreePool.concat(this._lineUsePool);
this._lineUsePool = [];
}
},
createLine: function(creator, params){
var line;
if(this.opt.enableCache && this._lineFreePool.length > 0){
line = this._lineFreePool.pop();
line.setShape(params);
// was cleared, add it back
creator.add(line);
}else{
line = creator.createLine(params);
}
if(this.opt.enableCache){
this._lineUsePool.push(line);
}
return line;
},
render: function(dim, offsets){
// summary:
// Render the plot on the chart.
// dim: Object
// An object of the form { width, height }.
// offsets: Object
// An object of the form { l, r, t, b }.
// returns: dojox.charting.plot2d.Grid
// A reference to this plot for functional chaining.
if(this.zoom){
return this.performZoom(dim, offsets);
}
this.dirty = this.isDirty();
if(!this.dirty){ return this; }
this.cleanGroup();
var s = this.group, ta = this.chart.theme.axis;
// draw horizontal stripes and lines
try{
var vScaler = this._vAxis.getScaler(),
vt = vScaler.scaler.getTransformerFromModel(vScaler),
ticks = this._vAxis.getTicks();
if(ticks != null){
if(this.opt.hMinorLines){
arr.forEach(ticks.minor, function(tick){
var y = dim.height - offsets.b - vt(tick.value);
var hMinorLine = this.createLine(s, {
x1: offsets.l,
y1: y,
x2: dim.width - offsets.r,
y2: y
}).setStroke(ta.minorTick);
if(this.animate){
this._animateGrid(hMinorLine, "h", offsets.l, offsets.r + offsets.l - dim.width);
}
}, this);
}
if(this.opt.hMajorLines){
arr.forEach(ticks.major, function(tick){
var y = dim.height - offsets.b - vt(tick.value);
var hMajorLine = this.createLine(s, {
x1: offsets.l,
y1: y,
x2: dim.width - offsets.r,
y2: y
}).setStroke(ta.majorTick);
if(this.animate){
this._animateGrid(hMajorLine, "h", offsets.l, offsets.r + offsets.l - dim.width);
}
}, this);
}
}
}catch(e){
// squelch
}
// draw vertical stripes and lines
try{
var hScaler = this._hAxis.getScaler(),
ht = hScaler.scaler.getTransformerFromModel(hScaler),
ticks = this._hAxis.getTicks();
if(this != null){
if(ticks && this.opt.vMinorLines){
arr.forEach(ticks.minor, function(tick){
var x = offsets.l + ht(tick.value);
var vMinorLine = this.createLine(s, {
x1: x,
y1: offsets.t,
x2: x,
y2: dim.height - offsets.b
}).setStroke(ta.minorTick);
if(this.animate){
this._animateGrid(vMinorLine, "v", dim.height - offsets.b, dim.height - offsets.b - offsets.t);
}
}, this);
}
if(ticks && this.opt.vMajorLines){
arr.forEach(ticks.major, function(tick){
var x = offsets.l + ht(tick.value);
var vMajorLine = this.createLine(s, {
x1: x,
y1: offsets.t,
x2: x,
y2: dim.height - offsets.b
}).setStroke(ta.majorTick);
if(this.animate){
this._animateGrid(vMajorLine, "v", dim.height - offsets.b, dim.height - offsets.b - offsets.t);
}
}, this);
}
}
}catch(e){
// squelch
}
this.dirty = false;
return this; // dojox.charting.plot2d.Grid
},
_animateGrid: function(shape, type, offset, size){
var transStart = type == "h" ? [offset, 0] : [0, offset];
var scaleStart = type == "h" ? [1/size, 1] : [1, 1/size];
fx.animateTransform(lang.delegate({
shape: shape,
duration: 1200,
transform: [
{name: "translate", start: transStart, end: [0, 0]},
{name: "scale", start: scaleStart, end: [1, 1]},
{name: "original"}
]
}, this.animate)).play();
}
});
});
},
'dojox/gfx/utils':function(){
define("dojox/gfx/utils", ["dojo/_base/kernel","dojo/_base/lang","./_base", "dojo/_base/html","dojo/_base/array", "dojo/_base/window", "dojo/_base/json",
"dojo/_base/Deferred", "dojo/_base/sniff", "require","dojo/_base/config"],
function(kernel, lang, g, html, arr, win, jsonLib, Deferred, has, require, config){
var gu = g.utils = {};
/*===== g= dojox.gfx; gu = dojox.gfx.utils; =====*/
lang.mixin(gu, {
forEach: function(
/*dojox.gfx.Surface|dojox.gfx.Shape*/ object,
/*Function|String|Array*/ f, /*Object?*/ o
){
// summary:
// Takes a shape or a surface and applies a function "f" to in the context of "o"
// (or global, if missing). If "shape" was a surface or a group, it applies the same
// function to all children recursively effectively visiting all shapes of the underlying scene graph.
// object : The gfx container to iterate.
// f : The function to apply.
// o : The scope.
o = o || win.global;
f.call(o, object);
if(object instanceof g.Surface || object instanceof g.Group){
arr.forEach(object.children, function(shape){
gu.forEach(shape, f, o);
});
}
},
serialize: function(
/* dojox.gfx.Surface|dojox.gfx.Shape */ object
){
// summary:
// Takes a shape or a surface and returns a DOM object, which describes underlying shapes.
var t = {}, v, isSurface = object instanceof g.Surface;
if(isSurface || object instanceof g.Group){
t.children = arr.map(object.children, gu.serialize);
if(isSurface){
return t.children; // Array
}
}else{
t.shape = object.getShape();
}
if(object.getTransform){
v = object.getTransform();
if(v){ t.transform = v; }
}
if(object.getStroke){
v = object.getStroke();
if(v){ t.stroke = v; }
}
if(object.getFill){
v = object.getFill();
if(v){ t.fill = v; }
}
if(object.getFont){
v = object.getFont();
if(v){ t.font = v; }
}
return t; // Object
},
toJson: function(
/* dojox.gfx.Surface|dojox.gfx.Shape */ object,
/* Boolean? */ prettyPrint
){
// summary:
// Works just like serialize() but returns a JSON string. If prettyPrint is true, the string is pretty-printed to make it more human-readable.
return jsonLib.toJson(gu.serialize(object), prettyPrint); // String
},
deserialize: function(
/* dojox.gfx.Surface|dojox.gfx.Shape */ parent,
/* dojox.gfx.Shape|Array */ object
){
// summary:
// Takes a surface or a shape and populates it with an object produced by serialize().
if(object instanceof Array){
return arr.map(object, lang.hitch(null, gu.deserialize, parent)); // Array
}
var shape = ("shape" in object) ? parent.createShape(object.shape) : parent.createGroup();
if("transform" in object){
shape.setTransform(object.transform);
}
if("stroke" in object){
shape.setStroke(object.stroke);
}
if("fill" in object){
shape.setFill(object.fill);
}
if("font" in object){
shape.setFont(object.font);
}
if("children" in object){
arr.forEach(object.children, lang.hitch(null, gu.deserialize, shape));
}
return shape; // dojox.gfx.Shape
},
fromJson: function(
/* dojox.gfx.Surface|dojox.gfx.Shape */ parent,
/* String */ json){
// summary:
// Works just like deserialize() but takes a JSON representation of the object.
return gu.deserialize(parent, jsonLib.fromJson(json)); // Array || dojox.gfx.Shape
},
toSvg: function(/*GFX object*/surface){
// summary:
// Function to serialize a GFX surface to SVG text.
// description:
// Function to serialize a GFX surface to SVG text. The value of this output
// is that there are numerous serverside parser libraries that can render
// SVG into images in various formats. This provides a way that GFX objects
// can be captured in a known format and sent serverside for serialization
// into an image.
// surface:
// The GFX surface to serialize.
// returns:
// Deferred object that will be called when SVG serialization is complete.
//Since the init and even surface creation can be async, we need to
//return a deferred that will be called when content has serialized.
var deferred = new Deferred();
if(g.renderer === "svg"){
//If we're already in SVG mode, this is easy and quick.
try{
var svg = gu._cleanSvg(gu._innerXML(surface.rawNode));
deferred.callback(svg);
}catch(e){
deferred.errback(e);
}
}else{
//Okay, now we have to get creative with hidden iframes and the like to
//serialize SVG.
if (!gu._initSvgSerializerDeferred) {
gu._initSvgSerializer();
}
var jsonForm = gu.toJson(surface);
var serializer = function(){
try{
var sDim = surface.getDimensions();
var width = sDim.width;
var height = sDim.height;
//Create an attach point in the iframe for the contents.
var node = gu._gfxSvgProxy.document.createElement("div");
gu._gfxSvgProxy.document.body.appendChild(node);
//Set the node scaling.
win.withDoc(gu._gfxSvgProxy.document, function() {
html.style(node, "width", width);
html.style(node, "height", height);
}, this);
//Create temp surface to render object to and render.
var ts = gu._gfxSvgProxy[dojox._scopeName].gfx.createSurface(node, width, height);
//It's apparently possible that a suface creation is async, so we need to use
//the whenLoaded function. Probably not needed for SVG, but making it common
var draw = function(surface) {
try{
gu._gfxSvgProxy[dojox._scopeName].gfx.utils.fromJson(surface, jsonForm);
//Get contents and remove temp surface.
var svg = gu._cleanSvg(node.innerHTML);
surface.clear();
surface.destroy();
gu._gfxSvgProxy.document.body.removeChild(node);
deferred.callback(svg);
}catch(e){
deferred.errback(e);
}
};
ts.whenLoaded(null,draw);
}catch (ex) {
deferred.errback(ex);
}
};
//See if we can call it directly or pass it to the deferred to be
//called on initialization.
if(gu._initSvgSerializerDeferred.fired > 0){
serializer();
}else{
gu._initSvgSerializerDeferred.addCallback(serializer);
}
}
return deferred; //dojo.Deferred that will be called when serialization finishes.
},
//iFrame document used for handling SVG serialization.
_gfxSvgProxy: null,
//Serializer loaded.
_initSvgSerializerDeferred: null,
_svgSerializerInitialized: function() {
// summary:
// Internal function to call when the serializer init completed.
// tags:
// private
gu._initSvgSerializerDeferred.callback(true);
},
_initSvgSerializer: function(){
// summary:
// Internal function to initialize the hidden iframe where SVG rendering
// will occur.
// tags:
// private
if(!gu._initSvgSerializerDeferred){
gu._initSvgSerializerDeferred = new Deferred();
var f = win.doc.createElement("iframe");
html.style(f, {
display: "none",
position: "absolute",
width: "1em",
height: "1em",
top: "-10000px"
});
var intv;
if(has("ie")){
f.onreadystatechange = function(){
if(f.contentWindow.document.readyState == "complete"){
f.onreadystatechange = function() {};
intv = setInterval(function() {
if(f.contentWindow[kernel.scopeMap["dojo"][1]._scopeName] &&
f.contentWindow[kernel.scopeMap["dojox"][1]._scopeName].gfx &&
f.contentWindow[kernel.scopeMap["dojox"][1]._scopeName].gfx.utils){
clearInterval(intv);
f.contentWindow.parent[kernel.scopeMap["dojox"][1]._scopeName].gfx.utils._gfxSvgProxy = f.contentWindow;
f.contentWindow.parent[kernel.scopeMap["dojox"][1]._scopeName].gfx.utils._svgSerializerInitialized();
}
}, 50);
}
};
}else{
f.onload = function(){
f.onload = function() {};
intv = setInterval(function() {
if(f.contentWindow[kernel.scopeMap["dojo"][1]._scopeName] &&
f.contentWindow[kernel.scopeMap["dojox"][1]._scopeName].gfx &&
f.contentWindow[kernel.scopeMap["dojox"][1]._scopeName].gfx.utils){
clearInterval(intv);
f.contentWindow.parent[kernel.scopeMap["dojox"][1]._scopeName].gfx.utils._gfxSvgProxy = f.contentWindow;
f.contentWindow.parent[kernel.scopeMap["dojox"][1]._scopeName].gfx.utils._svgSerializerInitialized();
}
}, 50);
};
}
//We have to load the GFX SVG proxy frame. Default is to use the one packaged in dojox.
var uri = (config["dojoxGfxSvgProxyFrameUrl"]||require.toUrl("dojox/gfx/resources/gfxSvgProxyFrame.html"));
f.setAttribute("src", uri.toString());
win.body().appendChild(f);
}
},
_innerXML: function(/*Node*/node){
// summary:
// Implementation of MS's innerXML function, borrowed from dojox.xml.parser.
// node:
// The node from which to generate the XML text representation.
// tags:
// private
if(node.innerXML){
return node.innerXML; //String
}else if(node.xml){
return node.xml; //String
}else if(typeof XMLSerializer != "undefined"){
return (new XMLSerializer()).serializeToString(node); //String
}
return null;
},
_cleanSvg: function(svg) {
// summary:
// Internal function that cleans up artifacts in extracted SVG content.
// tags:
// private
if(svg){
//Make sure the namespace is set.
if(svg.indexOf("xmlns=\"http://www.w3.org/2000/svg\"") == -1){
svg = svg.substring(4, svg.length);
svg = "<svg xmlns=\"http://www.w3.org/2000/svg\"" + svg;
}
//Same for xmlns:xlink (missing in Chrome and Safari)
if(svg.indexOf("xmlns:xlink=\"http://www.w3.org/1999/xlink\"") == -1){
svg = svg.substring(4, svg.length);
svg = "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\"" + svg;
}
//and add namespace to href attribute if not done yet
//(FF 5+ adds xlink:href but not the xmlns def)
if(svg.indexOf("xlink:href") === -1){
svg = svg.replace(/href\s*=/g, "xlink:href=");
}
//Do some other cleanup, like stripping out the
//dojoGfx attributes and quoting ids.
svg = svg.replace(/\bdojoGfx\w*\s*=\s*(['"])\w*\1/g, "");
svg = svg.replace(/\b__gfxObject__\s*=\s*(['"])\w*\1/g, "");
svg = svg.replace(/[=]([^"']+?)(\s|>)/g,'="$1"$2');
}
return svg; //Cleaned SVG text.
}
});
return gu;
});
},
'dojox/lang/functional/fold':function(){
define("dojox/lang/functional/fold", ["dojo/_base/lang", "dojo/_base/array", "dojo/_base/window", "./lambda"],
function(lang, arr, win, df){
// This module adds high-level functions and related constructs:
// - "fold" family of functions
// Notes:
// - missing high-level functions are provided with the compatible API:
// foldl, foldl1, foldr, foldr1
// - missing JS standard functions are provided with the compatible API:
// reduce, reduceRight
// - the fold's counterpart: unfold
// Defined methods:
// - take any valid lambda argument as the functional argument
// - operate on dense arrays
// - take a string as the array argument
// - take an iterator objects as the array argument (only foldl, foldl1, and reduce)
var empty = {};
/*=====
var df = dojox.lang.functional;
=====*/
lang.mixin(df, {
// classic reduce-class functions
foldl: function(/*Array|String|Object*/ a, /*Function*/ f, /*Object*/ z, /*Object?*/ o){
// summary: repeatedly applies a binary function to an array from left
// to right using a seed value as a starting point; returns the final
// value.
if(typeof a == "string"){ a = a.split(""); }
o = o || win.global; f = df.lambda(f);
var i, n;
if(lang.isArray(a)){
// array
for(i = 0, n = a.length; i < n; z = f.call(o, z, a[i], i, a), ++i);
}else if(typeof a.hasNext == "function" && typeof a.next == "function"){
// iterator
for(i = 0; a.hasNext(); z = f.call(o, z, a.next(), i++, a));
}else{
// object/dictionary
for(i in a){
if(!(i in empty)){
z = f.call(o, z, a[i], i, a);
}
}
}
return z; // Object
},
foldl1: function(/*Array|String|Object*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: repeatedly applies a binary function to an array from left
// to right; returns the final value.
if(typeof a == "string"){ a = a.split(""); }
o = o || win.global; f = df.lambda(f);
var z, i, n;
if(lang.isArray(a)){
// array
z = a[0];
for(i = 1, n = a.length; i < n; z = f.call(o, z, a[i], i, a), ++i);
}else if(typeof a.hasNext == "function" && typeof a.next == "function"){
// iterator
if(a.hasNext()){
z = a.next();
for(i = 1; a.hasNext(); z = f.call(o, z, a.next(), i++, a));
}
}else{
// object/dictionary
var first = true;
for(i in a){
if(!(i in empty)){
if(first){
z = a[i];
first = false;
}else{
z = f.call(o, z, a[i], i, a);
}
}
}
}
return z; // Object
},
foldr: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object*/ z, /*Object?*/ o){
// summary: repeatedly applies a binary function to an array from right
// to left using a seed value as a starting point; returns the final
// value.
if(typeof a == "string"){ a = a.split(""); }
o = o || win.global; f = df.lambda(f);
for(var i = a.length; i > 0; --i, z = f.call(o, z, a[i], i, a));
return z; // Object
},
foldr1: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: repeatedly applies a binary function to an array from right
// to left; returns the final value.
if(typeof a == "string"){ a = a.split(""); }
o = o || win.global; f = df.lambda(f);
var n = a.length, z = a[n - 1], i = n - 1;
for(; i > 0; --i, z = f.call(o, z, a[i], i, a));
return z; // Object
},
// JS 1.8 standard array functions, which can take a lambda as a parameter.
reduce: function(/*Array|String|Object*/ a, /*Function|String|Array*/ f, /*Object?*/ z){
// summary: apply a function simultaneously against two values of the array
// (from left-to-right) as to reduce it to a single value.
return arguments.length < 3 ? df.foldl1(a, f) : df.foldl(a, f, z); // Object
},
reduceRight: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object?*/ z){
// summary: apply a function simultaneously against two values of the array
// (from right-to-left) as to reduce it to a single value.
return arguments.length < 3 ? df.foldr1(a, f) : df.foldr(a, f, z); // Object
},
// the fold's counterpart: unfold
unfold: function(/*Function|String|Array*/ pr, /*Function|String|Array*/ f,
/*Function|String|Array*/ g, /*Object*/ z, /*Object?*/ o){
// summary: builds an array by unfolding a value
o = o || win.global; f = df.lambda(f); g = df.lambda(g); pr = df.lambda(pr);
var t = [];
for(; !pr.call(o, z); t.push(f.call(o, z)), z = g.call(o, z));
return t; // Array
}
});
});
},
'url:dijit/templates/Tooltip.html':"<div class=\"dijitTooltip dijitTooltipLeft\" id=\"dojoTooltip\"\n\t><div class=\"dijitTooltipContainer dijitTooltipContents\" data-dojo-attach-point=\"containerNode\" role='alert'></div\n\t><div class=\"dijitTooltipConnector\" data-dojo-attach-point=\"connectorNode\"></div\n></div>\n",
'dojox/charting/plot2d/Spider':function(){
define("dojox/charting/plot2d/Spider", ["dojo/_base/lang", "dojo/_base/declare", "dojo/_base/connect", "dojo/_base/html", "dojo/_base/array",
"dojo/dom-geometry", "dojo/_base/fx", "dojo/fx", "dojo/_base/sniff",
"../Element", "./_PlotEvents", "dojo/_base/Color", "dojox/color/_base", "./common", "../axis2d/common",
"../scaler/primitive", "dojox/gfx", "dojox/gfx/matrix", "dojox/gfx/fx", "dojox/lang/functional",
"dojox/lang/utils", "dojo/fx/easing"],
function(lang, declare, hub, html, arr, domGeom, baseFx, coreFx, has,
Element, PlotEvents, Color, dxcolor, dc, da, primitive,
g, m, gfxfx, df, du, easing){
/*=====
var Element = dojox.charting.Element;
var PlotEvents = dojox.charting.plot2d._PlotEvents;
=====*/
var FUDGE_FACTOR = 0.2; // use to overlap fans
var Spider = declare("dojox.charting.plot2d.Spider", [Element, PlotEvents], {
// summary:
// The plot that represents a typical Spider chart.
defaultParams: {
labels: true,
ticks: false,
fixed: true,
precision: 1,
labelOffset: -10,
labelStyle: "default", // default/rows/auto
htmlLabels: true, // use HTML to draw labels
startAngle: -90, // start angle for slices in degrees
divisions: 3, // radius tick count
axisColor: "", // spider axis color
axisWidth: 0, // spider axis stroke width
spiderColor: "", // spider web color
spiderWidth: 0, // spider web stroke width
seriesWidth: 0, // plot border with
seriesFillAlpha: 0.2, // plot fill alpha
spiderOrigin: 0.16,
markerSize: 3, // radius of plot vertex (px)
spiderType: "polygon", //"circle"
animationType: easing.backOut,
axisTickFont: "",
axisTickFontColor: "",
axisFont: "",
axisFontColor: ""
},
optionalParams: {
radius: 0,
font: "",
fontColor: ""
},
constructor: function(chart, kwArgs){
// summary:
// Create a Spider plot.
this.opt = lang.clone(this.defaultParams);
du.updateWithObject(this.opt, kwArgs);
du.updateWithPattern(this.opt, kwArgs, this.optionalParams);
this.series = [];
this.dyn = [];
this.datas = {};
this.labelKey = [];
this.oldSeriePoints = {};
this.animations = {};
},
clear: function(){
// summary:
// Clear out all of the information tied to this plot.
// returns: dojox.charting.plot2d.Spider
// A reference to this plot for functional chaining.
this.dirty = true;
this.dyn = [];
this.series = [];
this.datas = {};
this.labelKey = [];
this.oldSeriePoints = {};
this.animations = {};
return this; // dojox.charting.plot2d.Spider
},
setAxis: function(axis){
// summary:
// Dummy method, since axes are irrelevant with a Spider chart.
// returns: dojox.charting.plot2d.Spider
// The reference to this plot for functional chaining.
return this; // dojox.charting.plot2d.Spider
},
addSeries: function(run){
// summary:
// Add a data series to this plot.
// run: dojox.charting.Series
// The series to be added.
// returns: dojox.charting.plot2d.Base
// A reference to this plot for functional chaining.
var matched = false;
this.series.push(run);
for(var key in run.data){
var val = run.data[key],
data = this.datas[key];
if(data){
data.vlist.push(val);
data.min = Math.min(data.min, val);
data.max = Math.max(data.max, val);
}else{
this.datas[key] = {min: val, max: val, vlist: [val]};
}
}
if (this.labelKey.length <= 0) {
for (var key in run.data) {
this.labelKey.push(key);
}
}
return this; // dojox.charting.plot2d.Base
},
getSeriesStats: function(){
// summary:
// Calculate the min/max on all attached series in both directions.
// returns: Object
// {hmin, hmax, vmin, vmax} min/max in both directions.
return dc.collectSimpleStats(this.series);
},
calculateAxes: function(dim){
// summary:
// Stub function for running the axis calculations (depricated).
// dim: Object
// An object of the form { width, height }
// returns: dojox.charting.plot2d.Base
// A reference to this plot for functional chaining.
this.initializeScalers(dim, this.getSeriesStats());
return this; // dojox.charting.plot2d.Base
},
getRequiredColors: function(){
// summary:
// Get how many data series we have, so we know how many colors to use.
// returns: Number
// The number of colors needed.
return this.series.length; // Number
},
initializeScalers: function(dim, stats){
// summary:
// Initializes scalers using attached axes.
// dim: Object:
// Size of a plot area in pixels as {width, height}.
// stats: Object:
// Min/max of data in both directions as {hmin, hmax, vmin, vmax}.
// returns: dojox.charting.plot2d.Base
// A reference to this plot for functional chaining.
if(this._hAxis){
if(!this._hAxis.initialized()){
this._hAxis.calculate(stats.hmin, stats.hmax, dim.width);
}
this._hScaler = this._hAxis.getScaler();
}else{
this._hScaler = primitive.buildScaler(stats.hmin, stats.hmax, dim.width);
}
if(this._vAxis){
if(!this._vAxis.initialized()){
this._vAxis.calculate(stats.vmin, stats.vmax, dim.height);
}
this._vScaler = this._vAxis.getScaler();
}else{
this._vScaler = primitive.buildScaler(stats.vmin, stats.vmax, dim.height);
}
return this; // dojox.charting.plot2d.Base
},
render: function(dim, offsets){
// summary:
// Render the plot on the chart.
// dim: Object
// An object of the form { width, height }.
// offsets: Object
// An object of the form { l, r, t, b }.
// returns: dojox.charting.plot2d.Spider
// A reference to this plot for functional chaining.
if(!this.dirty){ return this; }
this.dirty = false;
this.cleanGroup();
var s = this.group, t = this.chart.theme;
this.resetEvents();
if(!this.series || !this.series.length){
return this;
}
// calculate the geometry
var o = this.opt, ta = t.axis,
rx = (dim.width - offsets.l - offsets.r) / 2,
ry = (dim.height - offsets.t - offsets.b) / 2,
r = Math.min(rx, ry),
axisTickFont = o.font || (ta.majorTick && ta.majorTick.font) || (ta.tick && ta.tick.font) || "normal normal normal 7pt Tahoma",
axisFont = o.axisFont || (ta.tick && ta.tick.titleFont) || "normal normal normal 11pt Tahoma",
axisTickFontColor = o.axisTickFontColor || (ta.majorTick && ta.majorTick.fontColor) || (ta.tick && ta.tick.fontColor) || "silver",
axisFontColor = o.axisFontColor || (ta.tick && ta.tick.titleFontColor) || "black",
axisColor = o.axisColor || (ta.tick && ta.tick.axisColor) || "silver",
spiderColor = o.spiderColor || (ta.tick && ta.tick.spiderColor) || "silver",
axisWidth = o.axisWidth || (ta.stroke && ta.stroke.width) || 2,
spiderWidth = o.spiderWidth || (ta.stroke && ta.stroke.width) || 2,
seriesWidth = o.seriesWidth || (ta.stroke && ta.stroke.width) || 2,
asize = g.normalizedLength(g.splitFontString(axisFont).size),
startAngle = m._degToRad(o.startAngle),
start = startAngle, step, filteredRun, slices, labels, shift, labelR,
outerPoints, innerPoints, divisionPoints, divisionRadius, labelPoints,
ro = o.spiderOrigin, dv = o.divisions >= 3 ? o.divisions : 3, ms = o.markerSize,
spt = o.spiderType, at = o.animationType, lboffset = o.labelOffset < -10 ? o.labelOffset : -10,
axisExtra = 0.2;
if(o.labels){
labels = arr.map(this.series, function(s){
return s.name;
}, this);
shift = df.foldl1(df.map(labels, function(label, i){
var font = t.series.font;
return g._base._getTextBox(label, {
font: font
}).w;
}, this), "Math.max(a, b)") / 2;
r = Math.min(rx - 2 * shift, ry - asize) + lboffset;
labelR = r - lboffset;
}
if ("radius" in o) {
r = o.radius;
labelR = r - lboffset;
}
r /= (1+axisExtra);
var circle = {
cx: offsets.l + rx,
cy: offsets.t + ry,
r: r
};
for (var i = this.series.length - 1; i >= 0; i--) {
var serieEntry = this.series[i];
if (!this.dirty && !serieEntry.dirty) {
t.skip();
continue;
}
serieEntry.cleanGroup();
var run = serieEntry.data;
if (run !== null) {
var len = this._getObjectLength(run);
//construct connect points
if (!outerPoints || outerPoints.length <= 0) {
outerPoints = [], innerPoints = [], labelPoints = [];
this._buildPoints(outerPoints, len, circle, r, start, true);
this._buildPoints(innerPoints, len, circle, r*ro, start, true);
this._buildPoints(labelPoints, len, circle, labelR, start);
if(dv > 2){
divisionPoints = [], divisionRadius = [];
for (var j = 0; j < dv - 2; j++) {
divisionPoints[j] = [];
this._buildPoints(divisionPoints[j], len, circle, r*(ro + (1-ro)*(j+1)/(dv-1)), start, true);
divisionRadius[j] = r*(ro + (1-ro)*(j+1)/(dv-1));
}
}
}
}
}
//draw Spider
//axis
var axisGroup = s.createGroup(), axisStroke = {color: axisColor, width: axisWidth},
spiderStroke = {color: spiderColor, width: spiderWidth};
for (var j = outerPoints.length - 1; j >= 0; --j) {
var point = outerPoints[j],
st = {
x: point.x + (point.x - circle.cx) * axisExtra,
y: point.y + (point.y - circle.cy) * axisExtra
},
nd = {
x: point.x + (point.x - circle.cx) * axisExtra / 2,
y: point.y + (point.y - circle.cy) * axisExtra / 2
};
axisGroup.createLine({
x1: circle.cx,
y1: circle.cy,
x2: st.x,
y2: st.y
}).setStroke(axisStroke);
//arrow
this._drawArrow(axisGroup, st, nd, axisStroke);
}
// draw the label
var labelGroup = s.createGroup();
for (var j = labelPoints.length - 1; j >= 0; --j) {
var point = labelPoints[j],
fontWidth = g._base._getTextBox(this.labelKey[j], {font: axisFont}).w || 0,
render = this.opt.htmlLabels && g.renderer != "vml" ? "html" : "gfx",
elem = da.createText[render](this.chart, labelGroup, (!domGeom.isBodyLtr() && render == "html") ? (point.x + fontWidth - dim.width) : point.x, point.y,
"middle", this.labelKey[j], axisFont, axisFontColor);
if (this.opt.htmlLabels) {
this.htmlElements.push(elem);
}
}
//spider web: polygon or circle
var spiderGroup = s.createGroup();
if(spt == "polygon"){
spiderGroup.createPolyline(outerPoints).setStroke(spiderStroke);
spiderGroup.createPolyline(innerPoints).setStroke(spiderStroke);
if (divisionPoints.length > 0) {
for (var j = divisionPoints.length - 1; j >= 0; --j) {
spiderGroup.createPolyline(divisionPoints[j]).setStroke(spiderStroke);
}
}
}else{//circle
var ccount = this._getObjectLength(this.datas);
spiderGroup.createCircle({cx: circle.cx, cy: circle.cy, r: r}).setStroke(spiderStroke);
spiderGroup.createCircle({cx: circle.cx, cy: circle.cy, r: r*ro}).setStroke(spiderStroke);
if (divisionRadius.length > 0) {
for (var j = divisionRadius.length - 1; j >= 0; --j) {
spiderGroup.createCircle({cx: circle.cx, cy: circle.cy, r: divisionRadius[j]}).setStroke(spiderStroke);
}
}
}
//text
var textGroup = s.createGroup(), len = this._getObjectLength(this.datas), k = 0;
for(var key in this.datas){
var data = this.datas[key], min = data.min, max = data.max, distance = max - min,
end = start + 2 * Math.PI * k / len;
for (var i = 0; i < dv; i++) {
var text = min + distance*i/(dv-1), point = this._getCoordinate(circle, r*(ro + (1-ro)*i/(dv-1)), end);
text = this._getLabel(text);
var fontWidth = g._base._getTextBox(text, {font: axisTickFont}).w || 0,
render = this.opt.htmlLabels && g.renderer != "vml" ? "html" : "gfx";
if (this.opt.htmlLabels) {
this.htmlElements.push(da.createText[render]
(this.chart, textGroup, (!domGeom.isBodyLtr() && render == "html") ? (point.x + fontWidth - dim.width) : point.x, point.y,
"start", text, axisTickFont, axisTickFontColor));
}
}
k++;
}
//draw series (animation)
this.chart.seriesShapes = {};
var animationConnections = [];
for (var i = this.series.length - 1; i >= 0; i--) {
var serieEntry = this.series[i], run = serieEntry.data;
if (run !== null) {
//series polygon
var seriePoints = [], k = 0, tipData = [];
for(var key in run){
var data = this.datas[key], min = data.min, max = data.max, distance = max - min,
entry = run[key], end = start + 2 * Math.PI * k / len,
point = this._getCoordinate(circle, r*(ro + (1-ro)*(entry-min)/distance), end);
seriePoints.push(point);
tipData.push({sname: serieEntry.name, key: key, data: entry});
k++;
}
seriePoints[seriePoints.length] = seriePoints[0];
tipData[tipData.length] = tipData[0];
var polygonBoundRect = this._getBoundary(seriePoints),
theme = t.next("spider", [o, serieEntry]), ts = serieEntry.group,
f = g.normalizeColor(theme.series.fill), sk = {color: theme.series.fill, width: seriesWidth};
f.a = o.seriesFillAlpha;
serieEntry.dyn = {fill: f, stroke: sk};
var osps = this.oldSeriePoints[serieEntry.name];
var cs = this._createSeriesEntry(ts, (osps || innerPoints), seriePoints, f, sk, r, ro, ms, at);
this.chart.seriesShapes[serieEntry.name] = cs;
this.oldSeriePoints[serieEntry.name] = seriePoints;
var po = {
element: "spider_poly",
index: i,
id: "spider_poly_"+serieEntry.name,
run: serieEntry,
plot: this,
shape: cs.poly,
parent: ts,
brect: polygonBoundRect,
cx: circle.cx,
cy: circle.cy,
cr: r,
f: f,
s: s
};
this._connectEvents(po);
var so = {
element: "spider_plot",
index: i,
id: "spider_plot_"+serieEntry.name,
run: serieEntry,
plot: this,
shape: serieEntry.group
};
this._connectEvents(so);
arr.forEach(cs.circles, function(c, i){
var shape = c.getShape(),
co = {
element: "spider_circle",
index: i,
id: "spider_circle_"+serieEntry.name+i,
run: serieEntry,
plot: this,
shape: c,
parent: ts,
tdata: tipData[i],
cx: seriePoints[i].x,
cy: seriePoints[i].y,
f: f,
s: s
};
this._connectEvents(co);
}, this);
}
}
return this; // dojox.charting.plot2d.Spider
},
_createSeriesEntry: function(ts, osps, sps, f, sk, r, ro, ms, at){
//polygon
var spoly = ts.createPolyline(osps).setFill(f).setStroke(sk), scircle = [];
for (var j = 0; j < osps.length; j++) {
var point = osps[j], cr = ms;
var circle = ts.createCircle({cx: point.x, cy: point.y, r: cr}).setFill(f).setStroke(sk);
scircle.push(circle);
}
var anims = arr.map(sps, function(np, j){
// create animation
var sp = osps[j],
anim = new baseFx.Animation({
duration: 1000,
easing: at,
curve: [sp.y, np.y]
});
var spl = spoly, sc = scircle[j];
hub.connect(anim, "onAnimate", function(y){
//apply poly
var pshape = spl.getShape();
pshape.points[j].y = y;
spl.setShape(pshape);
//apply circle
var cshape = sc.getShape();
cshape.cy = y;
sc.setShape(cshape);
});
return anim;
});
var anims1 = arr.map(sps, function(np, j){
// create animation
var sp = osps[j],
anim = new baseFx.Animation({
duration: 1000,
easing: at,
curve: [sp.x, np.x]
});
var spl = spoly, sc = scircle[j];
hub.connect(anim, "onAnimate", function(x){
//apply poly
var pshape = spl.getShape();
pshape.points[j].x = x;
spl.setShape(pshape);
//apply circle
var cshape = sc.getShape();
cshape.cx = x;
sc.setShape(cshape);
});
return anim;
});
var masterAnimation = coreFx.combine(anims.concat(anims1)); //dojo.fx.chain(anims);
masterAnimation.play();
return {group :ts, poly: spoly, circles: scircle};
},
plotEvent: function(o){
// summary:
// Stub function for use by specific plots.
// o: Object
// An object intended to represent event parameters.
var runName = o.id ? o.id : "default", a;
if (runName in this.animations) {
a = this.animations[runName];
a.anim && a.anim.stop(true);
} else {
a = this.animations[runName] = {};
}
if(o.element == "spider_poly"){
if(!a.color){
var color = o.shape.getFill();
if(!color || !(color instanceof Color)){
return;
}
a.color = {
start: color,
end: transColor(color)
};
}
var start = a.color.start, end = a.color.end;
if(o.type == "onmouseout"){
// swap colors
var t = start; start = end; end = t;
}
a.anim = gfxfx.animateFill({
shape: o.shape,
duration: 800,
easing: easing.backOut,
color: {start: start, end: end}
});
a.anim.play();
}else if(o.element == "spider_circle"){
var init, scale, defaultScale = 1.5;
if(o.type == "onmouseover"){
init = m.identity;
scale = defaultScale;
//show tooltip
var aroundRect = {type: "rect"};
aroundRect.x = o.cx;
aroundRect.y = o.cy;
aroundRect.width = aroundRect.height = 1;
var lt = html.coords(this.chart.node, true);
aroundRect.x += lt.x;
aroundRect.y += lt.y;
aroundRect.x = Math.round(aroundRect.x);
aroundRect.y = Math.round(aroundRect.y);
aroundRect.width = Math.ceil(aroundRect.width);
aroundRect.height = Math.ceil(aroundRect.height);
this.aroundRect = aroundRect;
var position = ["after", "before"];
dc.doIfLoaded("dijit/Tooltip", dojo.hitch(this, function(Tooltip){
Tooltip.show(o.tdata.sname + "<br/>" + o.tdata.key + "<br/>" + o.tdata.data, this.aroundRect, position);
}));
}else{
init = m.scaleAt(defaultScale, o.cx, o.cy);
scale = 1/defaultScale;
dc.doIfLoaded("dijit/Tooltip", dojo.hitch(this, function(Tooltip){
this.aroundRect && Tooltip.hide(this.aroundRect);
}));
}
var cs = o.shape.getShape(),
init = m.scaleAt(defaultScale, cs.cx, cs.cy),
kwArgs = {
shape: o.shape,
duration: 200,
easing: easing.backOut,
transform: [
{name: "scaleAt", start: [1, cs.cx, cs.cy], end: [scale, cs.cx, cs.cy]},
init
]
};
a.anim = gfxfx.animateTransform(kwArgs);
a.anim.play();
}else if(o.element == "spider_plot"){
//dojo gfx function "moveToFront" not work in IE
if (o.type == "onmouseover" && !has("ie")) {
o.shape.moveToFront();
}
}
},
_getBoundary: function(points){
var xmax = points[0].x,
xmin = points[0].x,
ymax = points[0].y,
ymin = points[0].y;
for(var i = 0; i < points.length; i++){
var point = points[i];
xmax = Math.max(point.x, xmax);
ymax = Math.max(point.y, ymax);
xmin = Math.min(point.x, xmin);
ymin = Math.min(point.y, ymin);
}
return {
x: xmin,
y: ymin,
width: xmax - xmin,
height: ymax - ymin
};
},
_drawArrow: function(s, start, end, stroke){
var len = Math.sqrt(Math.pow(end.x - start.x, 2) + Math.pow(end.y - start.y, 2)),
sin = (end.y - start.y)/len, cos = (end.x - start.x)/len,
point2 = {x: end.x + (len/3)*(-sin), y: end.y + (len/3)*cos},
point3 = {x: end.x + (len/3)*sin, y: end.y + (len/3)*(-cos)};
s.createPolyline([start, point2, point3]).setFill(stroke.color).setStroke(stroke);
},
_buildPoints: function(points, count, circle, radius, angle, recursive){
for (var i = 0; i < count; i++) {
var end = angle + 2 * Math.PI * i / count;
points.push(this._getCoordinate(circle, radius, end));
}
if(recursive){
points.push(this._getCoordinate(circle, radius, angle + 2 * Math.PI));
}
},
_getCoordinate: function(circle, radius, angle){
return {
x: circle.cx + radius * Math.cos(angle),
y: circle.cy + radius * Math.sin(angle)
}
},
_getObjectLength: function(obj){
var count = 0;
if(lang.isObject(obj)){
for(var key in obj){
count++;
}
}
return count;
},
// utilities
_getLabel: function(number){
return dc.getLabel(number, this.opt.fixed, this.opt.precision);
}
});
function transColor(color){
var a = new dxcolor.Color(color),
x = a.toHsl();
if(x.s == 0){
x.l = x.l < 50 ? 100 : 0;
}else{
x.s = 100;
if(x.l < 50){
x.l = 75;
}else if(x.l > 75){
x.l = 50;
}else{
x.l = x.l - 50 > 75 - x.l ?
50 : 75;
}
}
var color = dxcolor.fromHsl(x);
color.a = 0.7;
return color;
}
return Spider; // dojox.plot2d.Spider
});
},
'dojox/charting/plot2d/StackedBars':function(){
define("dojox/charting/plot2d/StackedBars", ["dojo/_base/lang", "dojo/_base/array", "dojo/_base/declare", "./Bars", "./common",
"dojox/lang/functional", "dojox/lang/functional/reversed", "dojox/lang/functional/sequence"],
function(lang, arr, declare, Bars, dc, df, dfr, dfs){
var purgeGroup = dfr.lambda("item.purgeGroup()");
/*=====
var bars = dojox.charting.plot2d.Bars;
=====*/
return declare("dojox.charting.plot2d.StackedBars", Bars, {
// summary:
// The plot object representing a stacked bar chart (horizontal bars).
getSeriesStats: function(){
// summary:
// Calculate the min/max on all attached series in both directions.
// returns: Object
// {hmin, hmax, vmin, vmax} min/max in both directions.
var stats = dc.collectStackedStats(this.series), t;
this._maxRunLength = stats.hmax;
stats.hmin -= 0.5;
stats.hmax += 0.5;
t = stats.hmin, stats.hmin = stats.vmin, stats.vmin = t;
t = stats.hmax, stats.hmax = stats.vmax, stats.vmax = t;
return stats;
},
render: function(dim, offsets){
// summary:
// Run the calculations for any axes for this plot.
// dim: Object
// An object in the form of { width, height }
// offsets: Object
// An object of the form { l, r, t, b}.
// returns: dojox.charting.plot2d.StackedBars
// A reference to this plot for functional chaining.
if(this._maxRunLength <= 0){
return this;
}
// stack all values
var acc = df.repeat(this._maxRunLength, "-> 0", 0);
for(var i = 0; i < this.series.length; ++i){
var run = this.series[i];
for(var j = 0; j < run.data.length; ++j){
var value = run.data[j];
if(value !== null){
var v = typeof value == "number" ? value : value.y;
if(isNaN(v)){ v = 0; }
acc[j] += v;
}
}
}
// draw runs in backwards
if(this.zoom && !this.isDataDirty()){
return this.performZoom(dim, offsets);
}
this.resetEvents();
this.dirty = this.isDirty();
if(this.dirty){
arr.forEach(this.series, purgeGroup);
this._eventSeries = {};
this.cleanGroup();
var s = this.group;
df.forEachRev(this.series, function(item){ item.cleanGroup(s); });
}
var t = this.chart.theme, f, gap, height,
ht = this._hScaler.scaler.getTransformerFromModel(this._hScaler),
vt = this._vScaler.scaler.getTransformerFromModel(this._vScaler),
events = this.events();
f = dc.calculateBarSize(this._vScaler.bounds.scale, this.opt);
gap = f.gap;
height = f.size;
for(var i = this.series.length - 1; i >= 0; --i){
var run = this.series[i];
if(!this.dirty && !run.dirty){
t.skip();
this._reconnectEvents(run.name);
continue;
}
run.cleanGroup();
var theme = t.next("bar", [this.opt, run]), s = run.group,
eventSeries = new Array(acc.length);
for(var j = 0; j < acc.length; ++j){
var value = run.data[j];
if(value !== null){
var v = acc[j],
width = ht(v),
finalTheme = typeof value != "number" ?
t.addMixin(theme, "bar", value, true) :
t.post(theme, "bar");
if(width >= 0 && height >= 1){
var rect = {
x: offsets.l,
y: dim.height - offsets.b - vt(j + 1.5) + gap,
width: width, height: height
};
var specialFill = this._plotFill(finalTheme.series.fill, dim, offsets);
specialFill = this._shapeFill(specialFill, rect);
var shape = s.createRect(rect).setFill(specialFill).setStroke(finalTheme.series.stroke);
run.dyn.fill = shape.getFill();
run.dyn.stroke = shape.getStroke();
if(events){
var o = {
element: "bar",
index: j,
run: run,
shape: shape,
x: v,
y: j + 1.5
};
this._connectEvents(o);
eventSeries[j] = o;
}
if(this.animate){
this._animateBar(shape, offsets.l, -width);
}
}
}
}
this._eventSeries[run.name] = eventSeries;
run.dirty = false;
// update the accumulator
for(var j = 0; j < run.data.length; ++j){
var value = run.data[j];
if(value !== null){
var v = typeof value == "number" ? value : value.y;
if(isNaN(v)){ v = 0; }
acc[j] -= v;
}
}
}
this.dirty = false;
return this; // dojox.charting.plot2d.StackedBars
}
});
});
},
'dojox/charting/themes/GreySkies':function(){
define("dojox/charting/themes/GreySkies", ["../Theme", "./common"], function(Theme, themes){
themes.GreySkies=new Theme(Theme._def);
return themes.GreySkies;
});
},
'dojox/charting/plot2d/Columns':function(){
define("dojox/charting/plot2d/Columns", ["dojo/_base/lang", "dojo/_base/array", "dojo/_base/declare", "./Base", "./common",
"dojox/lang/functional", "dojox/lang/functional/reversed", "dojox/lang/utils", "dojox/gfx/fx"],
function(lang, arr, declare, Base, dc, df, dfr, du, fx){
var purgeGroup = dfr.lambda("item.purgeGroup()");
/*=====
var Base = dojox.charting.plot2d.Base;
=====*/
return declare("dojox.charting.plot2d.Columns", Base, {
// summary:
// The plot object representing a column chart (vertical bars).
defaultParams: {
hAxis: "x", // use a horizontal axis named "x"
vAxis: "y", // use a vertical axis named "y"
gap: 0, // gap between columns in pixels
animate: null, // animate bars into place
enableCache: false
},
optionalParams: {
minBarSize: 1, // minimal column width in pixels
maxBarSize: 1, // maximal column width in pixels
// theme component
stroke: {},
outline: {},
shadow: {},
fill: {},
font: "",
fontColor: ""
},
constructor: function(chart, kwArgs){
// summary:
// The constructor for a columns chart.
// chart: dojox.charting.Chart
// The chart this plot belongs to.
// kwArgs: dojox.charting.plot2d.__BarCtorArgs?
// An optional keyword arguments object to help define the plot.
this.opt = lang.clone(this.defaultParams);
du.updateWithObject(this.opt, kwArgs);
du.updateWithPattern(this.opt, kwArgs, this.optionalParams);
this.series = [];
this.hAxis = this.opt.hAxis;
this.vAxis = this.opt.vAxis;
this.animate = this.opt.animate;
},
getSeriesStats: function(){
// summary:
// Calculate the min/max on all attached series in both directions.
// returns: Object
// {hmin, hmax, vmin, vmax} min/max in both directions.
var stats = dc.collectSimpleStats(this.series);
stats.hmin -= 0.5;
stats.hmax += 0.5;
return stats;
},
createRect: function(run, creator, params){
var rect;
if(this.opt.enableCache && run._rectFreePool.length > 0){
rect = run._rectFreePool.pop();
rect.setShape(params);
// was cleared, add it back
creator.add(rect);
}else{
rect = creator.createRect(params);
}
if(this.opt.enableCache){
run._rectUsePool.push(rect);
}
return rect;
},
render: function(dim, offsets){
// summary:
// Run the calculations for any axes for this plot.
// dim: Object
// An object in the form of { width, height }
// offsets: Object
// An object of the form { l, r, t, b}.
// returns: dojox.charting.plot2d.Columns
// A reference to this plot for functional chaining.
if(this.zoom && !this.isDataDirty()){
return this.performZoom(dim, offsets);
}
var t = this.getSeriesStats();
this.resetEvents();
this.dirty = this.isDirty();
if(this.dirty){
arr.forEach(this.series, purgeGroup);
this._eventSeries = {};
this.cleanGroup();
var s = this.group;
df.forEachRev(this.series, function(item){ item.cleanGroup(s); });
}
var t = this.chart.theme, f, gap, width,
ht = this._hScaler.scaler.getTransformerFromModel(this._hScaler),
vt = this._vScaler.scaler.getTransformerFromModel(this._vScaler),
baseline = Math.max(0, this._vScaler.bounds.lower),
baselineHeight = vt(baseline),
min = Math.max(0, Math.floor(this._hScaler.bounds.from - 1)), max = Math.ceil(this._hScaler.bounds.to),
events = this.events();
f = dc.calculateBarSize(this._hScaler.bounds.scale, this.opt);
gap = f.gap;
width = f.size;
for(var i = this.series.length - 1; i >= 0; --i){
var run = this.series[i];
if(!this.dirty && !run.dirty){
t.skip();
this._reconnectEvents(run.name);
continue;
}
run.cleanGroup();
if(this.opt.enableCache){
run._rectFreePool = (run._rectFreePool?run._rectFreePool:[]).concat(run._rectUsePool?run._rectUsePool:[]);
run._rectUsePool = [];
}
var theme = t.next("column", [this.opt, run]), s = run.group,
eventSeries = new Array(run.data.length);
var l = Math.min(run.data.length, max);
for(var j = min; j < l; ++j){
var value = run.data[j];
if(value !== null){
var v = typeof value == "number" ? value : value.y,
vv = vt(v),
height = vv - baselineHeight,
h = Math.abs(height),
finalTheme = typeof value != "number" ?
t.addMixin(theme, "column", value, true) :
t.post(theme, "column");
if(width >= 1 && h >= 0){
var rect = {
x: offsets.l + ht(j + 0.5) + gap,
y: dim.height - offsets.b - (v > baseline ? vv : baselineHeight),
width: width, height: h
};
var specialFill = this._plotFill(finalTheme.series.fill, dim, offsets);
specialFill = this._shapeFill(specialFill, rect);
var shape = this.createRect(run, s, rect).setFill(specialFill).setStroke(finalTheme.series.stroke);
run.dyn.fill = shape.getFill();
run.dyn.stroke = shape.getStroke();
if(events){
var o = {
element: "column",
index: j,
run: run,
shape: shape,
x: j + 0.5,
y: v
};
this._connectEvents(o);
eventSeries[j] = o;
}
if(this.animate){
this._animateColumn(shape, dim.height - offsets.b - baselineHeight, h);
}
}
}
}
this._eventSeries[run.name] = eventSeries;
run.dirty = false;
}
this.dirty = false;
return this; // dojox.charting.plot2d.Columns
},
_animateColumn: function(shape, voffset, vsize){
fx.animateTransform(lang.delegate({
shape: shape,
duration: 1200,
transform: [
{name: "translate", start: [0, voffset - (voffset/vsize)], end: [0, 0]},
{name: "scale", start: [1, 1/vsize], end: [1, 1]},
{name: "original"}
]
}, this.animate)).play();
}
});
});
},
'dijit/place':function(){
define("dijit/place", [
"dojo/_base/array", // array.forEach array.map array.some
"dojo/dom-geometry", // domGeometry.getMarginBox domGeometry.position
"dojo/dom-style", // domStyle.getComputedStyle
"dojo/_base/kernel", // kernel.deprecated
"dojo/_base/window", // win.body
"dojo/window", // winUtils.getBox
"." // dijit (defining dijit.place to match API doc)
], function(array, domGeometry, domStyle, kernel, win, winUtils, dijit){
// module:
// dijit/place
// summary:
// Code to place a popup relative to another node
function _place(/*DomNode*/ node, choices, layoutNode, aroundNodeCoords){
// summary:
// Given a list of spots to put node, put it at the first spot where it fits,
// of if it doesn't fit anywhere then the place with the least overflow
// choices: Array
// Array of elements like: {corner: 'TL', pos: {x: 10, y: 20} }
// Above example says to put the top-left corner of the node at (10,20)
// layoutNode: Function(node, aroundNodeCorner, nodeCorner, size)
// for things like tooltip, they are displayed differently (and have different dimensions)
// based on their orientation relative to the parent. This adjusts the popup based on orientation.
// It also passes in the available size for the popup, which is useful for tooltips to
// tell them that their width is limited to a certain amount. layoutNode() may return a value expressing
// how much the popup had to be modified to fit into the available space. This is used to determine
// what the best placement is.
// aroundNodeCoords: Object
// Size of aroundNode, ex: {w: 200, h: 50}
// get {x: 10, y: 10, w: 100, h:100} type obj representing position of
// viewport over document
var view = winUtils.getBox();
// This won't work if the node is inside a <div style="position: relative">,
// so reattach it to win.doc.body. (Otherwise, the positioning will be wrong
// and also it might get cutoff)
if(!node.parentNode || String(node.parentNode.tagName).toLowerCase() != "body"){
win.body().appendChild(node);
}
var best = null;
array.some(choices, function(choice){
var corner = choice.corner;
var pos = choice.pos;
var overflow = 0;
// calculate amount of space available given specified position of node
var spaceAvailable = {
w: {
'L': view.l + view.w - pos.x,
'R': pos.x - view.l,
'M': view.w
}[corner.charAt(1)],
h: {
'T': view.t + view.h - pos.y,
'B': pos.y - view.t,
'M': view.h
}[corner.charAt(0)]
};
// configure node to be displayed in given position relative to button
// (need to do this in order to get an accurate size for the node, because
// a tooltip's size changes based on position, due to triangle)
if(layoutNode){
var res = layoutNode(node, choice.aroundCorner, corner, spaceAvailable, aroundNodeCoords);
overflow = typeof res == "undefined" ? 0 : res;
}
// get node's size
var style = node.style;
var oldDisplay = style.display;
var oldVis = style.visibility;
if(style.display == "none"){
style.visibility = "hidden";
style.display = "";
}
var mb = domGeometry. getMarginBox(node);
style.display = oldDisplay;
style.visibility = oldVis;
// coordinates and size of node with specified corner placed at pos,
// and clipped by viewport
var
startXpos = {
'L': pos.x,
'R': pos.x - mb.w,
'M': Math.max(view.l, Math.min(view.l + view.w, pos.x + (mb.w >> 1)) - mb.w) // M orientation is more flexible
}[corner.charAt(1)],
startYpos = {
'T': pos.y,
'B': pos.y - mb.h,
'M': Math.max(view.t, Math.min(view.t + view.h, pos.y + (mb.h >> 1)) - mb.h)
}[corner.charAt(0)],
startX = Math.max(view.l, startXpos),
startY = Math.max(view.t, startYpos),
endX = Math.min(view.l + view.w, startXpos + mb.w),
endY = Math.min(view.t + view.h, startYpos + mb.h),
width = endX - startX,
height = endY - startY;
overflow += (mb.w - width) + (mb.h - height);
if(best == null || overflow < best.overflow){
best = {
corner: corner,
aroundCorner: choice.aroundCorner,
x: startX,
y: startY,
w: width,
h: height,
overflow: overflow,
spaceAvailable: spaceAvailable
};
}
return !overflow;
});
// In case the best position is not the last one we checked, need to call
// layoutNode() again.
if(best.overflow && layoutNode){
layoutNode(node, best.aroundCorner, best.corner, best.spaceAvailable, aroundNodeCoords);
}
// And then position the node. Do this last, after the layoutNode() above
// has sized the node, due to browser quirks when the viewport is scrolled
// (specifically that a Tooltip will shrink to fit as though the window was
// scrolled to the left).
//
// In RTL mode, set style.right rather than style.left so in the common case,
// window resizes move the popup along with the aroundNode.
var l = domGeometry.isBodyLtr(),
s = node.style;
s.top = best.y + "px";
s[l ? "left" : "right"] = (l ? best.x : view.w - best.x - best.w) + "px";
s[l ? "right" : "left"] = "auto"; // needed for FF or else tooltip goes to far left
return best;
}
/*=====
dijit.place.__Position = function(){
// x: Integer
// horizontal coordinate in pixels, relative to document body
// y: Integer
// vertical coordinate in pixels, relative to document body
this.x = x;
this.y = y;
};
=====*/
/*=====
dijit.place.__Rectangle = function(){
// x: Integer
// horizontal offset in pixels, relative to document body
// y: Integer
// vertical offset in pixels, relative to document body
// w: Integer
// width in pixels. Can also be specified as "width" for backwards-compatibility.
// h: Integer
// height in pixels. Can also be specified as "height" from backwards-compatibility.
this.x = x;
this.y = y;
this.w = w;
this.h = h;
};
=====*/
return (dijit.place = {
// summary:
// Code to place a DOMNode relative to another DOMNode.
// Load using require(["dijit/place"], function(place){ ... }).
at: function(node, pos, corners, padding){
// summary:
// Positions one of the node's corners at specified position
// such that node is fully visible in viewport.
// description:
// NOTE: node is assumed to be absolutely or relatively positioned.
// node: DOMNode
// The node to position
// pos: dijit.place.__Position
// Object like {x: 10, y: 20}
// corners: String[]
// Array of Strings representing order to try corners in, like ["TR", "BL"].
// Possible values are:
// * "BL" - bottom left
// * "BR" - bottom right
// * "TL" - top left
// * "TR" - top right
// padding: dijit.place.__Position?
// optional param to set padding, to put some buffer around the element you want to position.
// example:
// Try to place node's top right corner at (10,20).
// If that makes node go (partially) off screen, then try placing
// bottom left corner at (10,20).
// | place(node, {x: 10, y: 20}, ["TR", "BL"])
var choices = array.map(corners, function(corner){
var c = { corner: corner, pos: {x:pos.x,y:pos.y} };
if(padding){
c.pos.x += corner.charAt(1) == 'L' ? padding.x : -padding.x;
c.pos.y += corner.charAt(0) == 'T' ? padding.y : -padding.y;
}
return c;
});
return _place(node, choices);
},
around: function(
/*DomNode*/ node,
/*DomNode || dijit.place.__Rectangle*/ anchor,
/*String[]*/ positions,
/*Boolean*/ leftToRight,
/*Function?*/ layoutNode){
// summary:
// Position node adjacent or kitty-corner to anchor
// such that it's fully visible in viewport.
//
// description:
// Place node such that corner of node touches a corner of
// aroundNode, and that node is fully visible.
//
// anchor:
// Either a DOMNode or a __Rectangle (object with x, y, width, height).
//
// positions:
// Ordered list of positions to try matching up.
// * before: places drop down to the left of the anchor node/widget, or to the right in the case
// of RTL scripts like Hebrew and Arabic; aligns either the top of the drop down
// with the top of the anchor, or the bottom of the drop down with bottom of the anchor.
// * after: places drop down to the right of the anchor node/widget, or to the left in the case
// of RTL scripts like Hebrew and Arabic; aligns either the top of the drop down
// with the top of the anchor, or the bottom of the drop down with bottom of the anchor.
// * before-centered: centers drop down to the left of the anchor node/widget, or to the right
// in the case of RTL scripts like Hebrew and Arabic
// * after-centered: centers drop down to the right of the anchor node/widget, or to the left
// in the case of RTL scripts like Hebrew and Arabic
// * above-centered: drop down is centered above anchor node
// * above: drop down goes above anchor node, left sides aligned
// * above-alt: drop down goes above anchor node, right sides aligned
// * below-centered: drop down is centered above anchor node
// * below: drop down goes below anchor node
// * below-alt: drop down goes below anchor node, right sides aligned
//
// layoutNode: Function(node, aroundNodeCorner, nodeCorner)
// For things like tooltip, they are displayed differently (and have different dimensions)
// based on their orientation relative to the parent. This adjusts the popup based on orientation.
//
// leftToRight:
// True if widget is LTR, false if widget is RTL. Affects the behavior of "above" and "below"
// positions slightly.
//
// example:
// | placeAroundNode(node, aroundNode, {'BL':'TL', 'TR':'BR'});
// This will try to position node such that node's top-left corner is at the same position
// as the bottom left corner of the aroundNode (ie, put node below
// aroundNode, with left edges aligned). If that fails it will try to put
// the bottom-right corner of node where the top right corner of aroundNode is
// (ie, put node above aroundNode, with right edges aligned)
//
// if around is a DOMNode (or DOMNode id), convert to coordinates
var aroundNodePos = (typeof anchor == "string" || "offsetWidth" in anchor)
? domGeometry.position(anchor, true)
: anchor;
// Adjust anchor positioning for the case that a parent node has overflw hidden, therefore cuasing the anchor not to be completely visible
if(anchor.parentNode){
var parent = anchor.parentNode;
while(parent && parent.nodeType == 1 && parent.nodeName != "BODY"){ //ignoring the body will help performance
var parentPos = domGeometry.position(parent, true);
var parentStyleOverflow = domStyle.getComputedStyle(parent).overflow;
if(parentStyleOverflow == "hidden" || parentStyleOverflow == "auto" || parentStyleOverflow == "scroll"){
var bottomYCoord = Math.min(aroundNodePos.y + aroundNodePos.h, parentPos.y + parentPos.h);
var rightXCoord = Math.min(aroundNodePos.x + aroundNodePos.w, parentPos.x + parentPos.w);
aroundNodePos.x = Math.max(aroundNodePos.x, parentPos.x);
aroundNodePos.y = Math.max(aroundNodePos.y, parentPos.y);
aroundNodePos.h = bottomYCoord - aroundNodePos.y;
aroundNodePos.w = rightXCoord - aroundNodePos.x;
}
parent = parent.parentNode;
}
}
var x = aroundNodePos.x,
y = aroundNodePos.y,
width = "w" in aroundNodePos ? aroundNodePos.w : (aroundNodePos.w = aroundNodePos.width),
height = "h" in aroundNodePos ? aroundNodePos.h : (kernel.deprecated("place.around: dijit.place.__Rectangle: { x:"+x+", y:"+y+", height:"+aroundNodePos.height+", width:"+width+" } has been deprecated. Please use { x:"+x+", y:"+y+", h:"+aroundNodePos.height+", w:"+width+" }", "", "2.0"), aroundNodePos.h = aroundNodePos.height);
// Convert positions arguments into choices argument for _place()
var choices = [];
function push(aroundCorner, corner){
choices.push({
aroundCorner: aroundCorner,
corner: corner,
pos: {
x: {
'L': x,
'R': x + width,
'M': x + (width >> 1)
}[aroundCorner.charAt(1)],
y: {
'T': y,
'B': y + height,
'M': y + (height >> 1)
}[aroundCorner.charAt(0)]
}
})
}
array.forEach(positions, function(pos){
var ltr = leftToRight;
switch(pos){
case "above-centered":
push("TM", "BM");
break;
case "below-centered":
push("BM", "TM");
break;
case "after-centered":
ltr = !ltr;
// fall through
case "before-centered":
push(ltr ? "ML" : "MR", ltr ? "MR" : "ML");
break;
case "after":
ltr = !ltr;
// fall through
case "before":
push(ltr ? "TL" : "TR", ltr ? "TR" : "TL");
push(ltr ? "BL" : "BR", ltr ? "BR" : "BL");
break;
case "below-alt":
ltr = !ltr;
// fall through
case "below":
// first try to align left borders, next try to align right borders (or reverse for RTL mode)
push(ltr ? "BL" : "BR", ltr ? "TL" : "TR");
push(ltr ? "BR" : "BL", ltr ? "TR" : "TL");
break;
case "above-alt":
ltr = !ltr;
// fall through
case "above":
// first try to align left borders, next try to align right borders (or reverse for RTL mode)
push(ltr ? "TL" : "TR", ltr ? "BL" : "BR");
push(ltr ? "TR" : "TL", ltr ? "BR" : "BL");
break;
default:
// To assist dijit/_base/place, accept arguments of type {aroundCorner: "BL", corner: "TL"}.
// Not meant to be used directly.
push(pos.aroundCorner, pos.corner);
}
});
var position = _place(node, choices, layoutNode, {w: width, h: height});
position.aroundNodePos = aroundNodePos;
return position;
}
});
});
},
'dojox/lang/functional/array':function(){
define("dojox/lang/functional/array", ["dojo/_base/kernel", "dojo/_base/lang", "dojo/_base/array", "dojo/_base/window", "./lambda"],
function(dojo, lang, arr, win, df){
// This module adds high-level functions and related constructs:
// - array-processing functions similar to standard JS functions
// Notes:
// - this module provides JS standard methods similar to high-level functions in dojo/_base/array.js:
// forEach, map, filter, every, some
// Defined methods:
// - take any valid lambda argument as the functional argument
// - operate on dense arrays
// - take a string as the array argument
// - take an iterator objects as the array argument
var empty = {};
/*=====
var df = dojox.lang.functional;
=====*/
lang.mixin(df, {
// JS 1.6 standard array functions, which can take a lambda as a parameter.
// Consider using dojo._base.array functions, if you don't need the lambda support.
filter: function(/*Array|String|Object*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: creates a new array with all elements that pass the test
// implemented by the provided function.
if(typeof a == "string"){ a = a.split(""); }
o = o || win.global; f = df.lambda(f);
var t = [], v, i, n;
if(lang.isArray(a)){
// array
for(i = 0, n = a.length; i < n; ++i){
v = a[i];
if(f.call(o, v, i, a)){ t.push(v); }
}
}else if(typeof a.hasNext == "function" && typeof a.next == "function"){
// iterator
for(i = 0; a.hasNext();){
v = a.next();
if(f.call(o, v, i++, a)){ t.push(v); }
}
}else{
// object/dictionary
for(i in a){
if(!(i in empty)){
v = a[i];
if(f.call(o, v, i, a)){ t.push(v); }
}
}
}
return t; // Array
},
forEach: function(/*Array|String|Object*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: executes a provided function once per array element.
if(typeof a == "string"){ a = a.split(""); }
o = o || win.global; f = df.lambda(f);
var i, n;
if(lang.isArray(a)){
// array
for(i = 0, n = a.length; i < n; f.call(o, a[i], i, a), ++i);
}else if(typeof a.hasNext == "function" && typeof a.next == "function"){
// iterator
for(i = 0; a.hasNext(); f.call(o, a.next(), i++, a));
}else{
// object/dictionary
for(i in a){
if(!(i in empty)){
f.call(o, a[i], i, a);
}
}
}
return o; // Object
},
map: function(/*Array|String|Object*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: creates a new array with the results of calling
// a provided function on every element in this array.
if(typeof a == "string"){ a = a.split(""); }
o = o || win.global; f = df.lambda(f);
var t, n, i;
if(lang.isArray(a)){
// array
t = new Array(n = a.length);
for(i = 0; i < n; t[i] = f.call(o, a[i], i, a), ++i);
}else if(typeof a.hasNext == "function" && typeof a.next == "function"){
// iterator
t = [];
for(i = 0; a.hasNext(); t.push(f.call(o, a.next(), i++, a)));
}else{
// object/dictionary
t = [];
for(i in a){
if(!(i in empty)){
t.push(f.call(o, a[i], i, a));
}
}
}
return t; // Array
},
every: function(/*Array|String|Object*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: tests whether all elements in the array pass the test
// implemented by the provided function.
if(typeof a == "string"){ a = a.split(""); }
o = o || win.global; f = df.lambda(f);
var i, n;
if(lang.isArray(a)){
// array
for(i = 0, n = a.length; i < n; ++i){
if(!f.call(o, a[i], i, a)){
return false; // Boolean
}
}
}else if(typeof a.hasNext == "function" && typeof a.next == "function"){
// iterator
for(i = 0; a.hasNext();){
if(!f.call(o, a.next(), i++, a)){
return false; // Boolean
}
}
}else{
// object/dictionary
for(i in a){
if(!(i in empty)){
if(!f.call(o, a[i], i, a)){
return false; // Boolean
}
}
}
}
return true; // Boolean
},
some: function(/*Array|String|Object*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: tests whether some element in the array passes the test
// implemented by the provided function.
if(typeof a == "string"){ a = a.split(""); }
o = o || win.global; f = df.lambda(f);
var i, n;
if(lang.isArray(a)){
// array
for(i = 0, n = a.length; i < n; ++i){
if(f.call(o, a[i], i, a)){
return true; // Boolean
}
}
}else if(typeof a.hasNext == "function" && typeof a.next == "function"){
// iterator
for(i = 0; a.hasNext();){
if(f.call(o, a.next(), i++, a)){
return true; // Boolean
}
}
}else{
// object/dictionary
for(i in a){
if(!(i in empty)){
if(f.call(o, a[i], i, a)){
return true; // Boolean
}
}
}
}
return false; // Boolean
}
});
return df;
});
},
'dojox/charting/Theme':function(){
define("dojox/charting/Theme", ["dojo/_base/lang", "dojo/_base/array","dojo/_base/declare","dojo/_base/Color",
"dojox/color/_base", "dojox/color/Palette", "dojox/lang/utils", "dojox/gfx/gradutils"],
function(lang, arr, declare, Color, colorX, Palette, dlu, dgg){
var Theme = declare("dojox.charting.Theme", null, {
// summary:
// A Theme is a pre-defined object, primarily JSON-based, that makes up the definitions to
// style a chart.
//
// description:
// While you can set up style definitions on a chart directly (usually through the various add methods
// on a dojox.charting.Chart object), a Theme simplifies this manual setup by allowing you to
// pre-define all of the various visual parameters of each element in a chart.
//
// Most of the properties of a Theme are straight-forward; if something is line-based (such as
// an axis or the ticks on an axis), they will be defined using basic stroke parameters. Likewise,
// if an element is primarily block-based (such as the background of a chart), it will be primarily
// fill-based.
//
// In addition (for convenience), a Theme definition does not have to contain the entire JSON-based
// structure. Each theme is built on top of a default theme (which serves as the basis for the theme
// "GreySkies"), and is mixed into the default theme object. This allows you to create a theme based,
// say, solely on colors for data series.
//
// Defining a new theme is relatively easy; see any of the themes in dojox.charting.themes for examples
// on how to define your own.
//
// When you set a theme on a chart, the theme itself is deep-cloned. This means that you cannot alter
// the theme itself after setting the theme value on a chart, and expect it to change your chart. If you
// are looking to make alterations to a theme for a chart, the suggestion would be to create your own
// theme, based on the one you want to use, that makes those alterations before it is applied to a chart.
//
// Finally, a Theme contains a number of functions to facilitate rendering operations on a chart--the main
// helper of which is the ~next~ method, in which a chart asks for the information for the next data series
// to be rendered.
//
// A note on colors:
// The Theme constructor was on the use of dojox.color.Palette (in general) for creating a visually distinct
// set of colors for usage in a chart. A palette is usually comprised of 5 different color definitions, and
// no more. If you have a need to render a chart with more than 5 data elements, you can simply "push"
// new color definitions into the theme's .color array. Make sure that you do that with the actual
// theme object from a Chart, and not in the theme itself (i.e. either do that before using .setTheme
// on a chart).
//
// example:
// The default theme (and structure) looks like so:
// | // all objects are structs used directly in dojox.gfx
// | chart:{
// | stroke: null,
// | fill: "white",
// | pageStyle: null // suggested page style as an object suitable for dojo.style()
// | },
// | plotarea:{
// | stroke: null,
// | fill: "white"
// | },
// | axis:{
// | stroke: { // the axis itself
// | color: "#333",
// | width: 1
// | },
// | tick: { // used as a foundation for all ticks
// | color: "#666",
// | position: "center",
// | font: "normal normal normal 7pt Tahoma", // labels on axis
// | fontColor: "#333" // color of labels
// | },
// | majorTick: { // major ticks on axis, and used for major gridlines
// | width: 1,
// | length: 6
// | },
// | minorTick: { // minor ticks on axis, and used for minor gridlines
// | width: 0.8,
// | length: 3
// | },
// | microTick: { // minor ticks on axis, and used for minor gridlines
// | width: 0.5,
// | length: 1
// | }
// | },
// | series: {
// | stroke: {width: 1.5, color: "#333"}, // line
// | outline: {width: 0.1, color: "#ccc"}, // outline
// | //shadow: {dx: 1, dy: 1, width: 2, color: [0, 0, 0, 0.3]},
// | shadow: null, // no shadow
// | fill: "#ccc", // fill, if appropriate
// | font: "normal normal normal 8pt Tahoma", // if there's a label
// | fontColor: "#000" // color of labels
// | labelWiring: {width: 1, color: "#ccc"}, // connect marker and target data item(slice, column, bar...)
// | },
// | marker: { // any markers on a series
// | symbol: "m-3,3 l3,-6 3,6 z", // symbol
// | stroke: {width: 1.5, color: "#333"}, // stroke
// | outline: {width: 0.1, color: "#ccc"}, // outline
// | shadow: null, // no shadow
// | fill: "#ccc", // fill if needed
// | font: "normal normal normal 8pt Tahoma", // label
// | fontColor: "#000"
// | },
// | indicator: {
// | lineStroke: {width: 1.5, color: "#333"}, // line
// | lineOutline: {width: 0.1, color: "#ccc"}, // line outline
// | lineShadow: null, // no line shadow
// | stroke: {width: 1.5, color: "#333"}, // label background stroke
// | outline: {width: 0.1, color: "#ccc"}, // label background outline
// | shadow: null, // no label background shadow
// | fill: "#ccc", // label background fill
// | radius: 3, // radius of the label background
// | font: "normal normal normal 10pt Tahoma", // label font
// | fontColor: "#000" // label color
// | markerFill: "#ccc", // marker fill
// | markerSymbol: "m-3,0 c0,-4 6,-4 6,0 m-6,0 c0,4 6,4 6,0", // marker symbol
// | markerStroke: {width: 1.5, color: "#333"}, // marker stroke
// | markerOutline: {width: 0.1, color: "#ccc"}, // marker outline
// | markerShadow: null, // no marker shadow
// | }
//
// example:
// Defining a new theme is pretty simple:
// | dojox.charting.themes.Grasslands = new dojox.charting.Theme({
// | colors: [ "#70803a", "#dde574", "#788062", "#b1cc5d", "#eff2c2" ]
// | });
// |
// | myChart.setTheme(dojox.charting.themes.Grasslands);
shapeSpaces: {shape: 1, shapeX: 1, shapeY: 1},
constructor: function(kwArgs){
// summary:
// Initialize a theme using the keyword arguments. Note that the arguments
// look like the example (above), and may include a few more parameters.
kwArgs = kwArgs || {};
// populate theme with defaults updating them if needed
var def = Theme.defaultTheme;
arr.forEach(["chart", "plotarea", "axis", "series", "marker", "indicator"], function(name){
this[name] = lang.delegate(def[name], kwArgs[name]);
}, this);
// personalize theme
if(kwArgs.seriesThemes && kwArgs.seriesThemes.length){
this.colors = null;
this.seriesThemes = kwArgs.seriesThemes.slice(0);
}else{
this.seriesThemes = null;
this.colors = (kwArgs.colors || Theme.defaultColors).slice(0);
}
this.markerThemes = null;
if(kwArgs.markerThemes && kwArgs.markerThemes.length){
this.markerThemes = kwArgs.markerThemes.slice(0);
}
this.markers = kwArgs.markers ? lang.clone(kwArgs.markers) : lang.delegate(Theme.defaultMarkers);
// set flags
this.noGradConv = kwArgs.noGradConv;
this.noRadialConv = kwArgs.noRadialConv;
if(kwArgs.reverseFills){
this.reverseFills();
}
// private housekeeping
this._current = 0;
this._buildMarkerArray();
},
clone: function(){
// summary:
// Clone the current theme.
// returns: dojox.charting.Theme
// The cloned theme; any alterations made will not affect the original.
var theme = new Theme({
// theme components
chart: this.chart,
plotarea: this.plotarea,
axis: this.axis,
series: this.series,
marker: this.marker,
// individual arrays
colors: this.colors,
markers: this.markers,
indicator: this.indicator,
seriesThemes: this.seriesThemes,
markerThemes: this.markerThemes,
// flags
noGradConv: this.noGradConv,
noRadialConv: this.noRadialConv
});
// copy custom methods
arr.forEach(
["clone", "clear", "next", "skip", "addMixin", "post", "getTick"],
function(name){
if(this.hasOwnProperty(name)){
theme[name] = this[name];
}
},
this
);
return theme; // dojox.charting.Theme
},
clear: function(){
// summary:
// Clear and reset the internal pointer to start fresh.
this._current = 0;
},
next: function(elementType, mixin, doPost){
// summary:
// Get the next color or series theme.
// elementType: String?
// An optional element type (for use with series themes)
// mixin: Object?
// An optional object to mix into the theme.
// doPost: Boolean?
// A flag to post-process the results.
// returns: Object
// An object of the structure { series, marker, symbol }
var merge = dlu.merge, series, marker;
if(this.colors){
series = lang.delegate(this.series);
marker = lang.delegate(this.marker);
var color = new Color(this.colors[this._current % this.colors.length]), old;
// modify the stroke
if(series.stroke && series.stroke.color){
series.stroke = lang.delegate(series.stroke);
old = new Color(series.stroke.color);
series.stroke.color = new Color(color);
series.stroke.color.a = old.a;
}else{
series.stroke = {color: color};
}
if(marker.stroke && marker.stroke.color){
marker.stroke = lang.delegate(marker.stroke);
old = new Color(marker.stroke.color);
marker.stroke.color = new Color(color);
marker.stroke.color.a = old.a;
}else{
marker.stroke = {color: color};
}
// modify the fill
if(!series.fill || series.fill.type){
series.fill = color;
}else{
old = new Color(series.fill);
series.fill = new Color(color);
series.fill.a = old.a;
}
if(!marker.fill || marker.fill.type){
marker.fill = color;
}else{
old = new Color(marker.fill);
marker.fill = new Color(color);
marker.fill.a = old.a;
}
}else{
series = this.seriesThemes ?
merge(this.series, this.seriesThemes[this._current % this.seriesThemes.length]) :
this.series;
marker = this.markerThemes ?
merge(this.marker, this.markerThemes[this._current % this.markerThemes.length]) :
series;
}
var symbol = marker && marker.symbol || this._markers[this._current % this._markers.length];
var theme = {series: series, marker: marker, symbol: symbol};
// advance the counter
++this._current;
if(mixin){
theme = this.addMixin(theme, elementType, mixin);
}
if(doPost){
theme = this.post(theme, elementType);
}
return theme; // Object
},
skip: function(){
// summary:
// Skip the next internal color.
++this._current;
},
addMixin: function(theme, elementType, mixin, doPost){
// summary:
// Add a mixin object to the passed theme and process.
// theme: dojox.charting.Theme
// The theme to mixin to.
// elementType: String
// The type of element in question. Can be "line", "bar" or "circle"
// mixin: Object|Array
// The object or objects to mix into the theme.
// doPost: Boolean
// If true, run the new theme through the post-processor.
// returns: dojox.charting.Theme
// The new theme.
if(lang.isArray(mixin)){
arr.forEach(mixin, function(m){
theme = this.addMixin(theme, elementType, m);
}, this);
}else{
var t = {};
if("color" in mixin){
if(elementType == "line" || elementType == "area"){
lang.setObject("series.stroke.color", mixin.color, t);
lang.setObject("marker.stroke.color", mixin.color, t);
}else{
lang.setObject("series.fill", mixin.color, t);
}
}
arr.forEach(["stroke", "outline", "shadow", "fill", "font", "fontColor", "labelWiring"], function(name){
var markerName = "marker" + name.charAt(0).toUpperCase() + name.substr(1),
b = markerName in mixin;
if(name in mixin){
lang.setObject("series." + name, mixin[name], t);
if(!b){
lang.setObject("marker." + name, mixin[name], t);
}
}
if(b){
lang.setObject("marker." + name, mixin[markerName], t);
}
});
if("marker" in mixin){
t.symbol = mixin.marker;
}
theme = dlu.merge(theme, t);
}
if(doPost){
theme = this.post(theme, elementType);
}
return theme; // dojox.charting.Theme
},
post: function(theme, elementType){
// summary:
// Process any post-shape fills.
// theme: dojox.charting.Theme
// The theme to post process with.
// elementType: String
// The type of element being filled. Can be "bar" or "circle".
// returns: dojox.charting.Theme
// The post-processed theme.
var fill = theme.series.fill, t;
if(!this.noGradConv && this.shapeSpaces[fill.space] && fill.type == "linear"){
if(elementType == "bar"){
// transpose start and end points
t = {
x1: fill.y1,
y1: fill.x1,
x2: fill.y2,
y2: fill.x2
};
}else if(!this.noRadialConv && fill.space == "shape" && (elementType == "slice" || elementType == "circle")){
// switch to radial
t = {
type: "radial",
cx: 0,
cy: 0,
r: 100
};
}
if(t){
return dlu.merge(theme, {series: {fill: t}});
}
}
return theme; // dojox.charting.Theme
},
getTick: function(name, mixin){
// summary:
// Calculates and merges tick parameters.
// name: String
// Tick name, can be "major", "minor", or "micro".
// mixin: Object?
// Optional object to mix in to the tick.
var tick = this.axis.tick, tickName = name + "Tick",
merge = dlu.merge;
if(tick){
if(this.axis[tickName]){
tick = merge(tick, this.axis[tickName]);
}
}else{
tick = this.axis[tickName];
}
if(mixin){
if(tick){
if(mixin[tickName]){
tick = merge(tick, mixin[tickName]);
}
}else{
tick = mixin[tickName];
}
}
return tick; // Object
},
inspectObjects: function(f){
arr.forEach(["chart", "plotarea", "axis", "series", "marker", "indicator"], function(name){
f(this[name]);
}, this);
if(this.seriesThemes){
arr.forEach(this.seriesThemes, f);
}
if(this.markerThemes){
arr.forEach(this.markerThemes, f);
}
},
reverseFills: function(){
this.inspectObjects(function(o){
if(o && o.fill){
o.fill = dgg.reverse(o.fill);
}
});
},
addMarker:function(/*String*/ name, /*String*/ segment){
// summary:
// Add a custom marker to this theme.
// example:
// | myTheme.addMarker("Ellipse", foo);
this.markers[name] = segment;
this._buildMarkerArray();
},
setMarkers:function(/*Object*/ obj){
// summary:
// Set all the markers of this theme at once. obj should be a
// dictionary of keys and path segments.
//
// example:
// | myTheme.setMarkers({ "CIRCLE": foo });
this.markers = obj;
this._buildMarkerArray();
},
_buildMarkerArray: function(){
this._markers = [];
for(var p in this.markers){
this._markers.push(this.markers[p]);
}
}
});
/*=====
dojox.charting.Theme.__DefineColorArgs = function(num, colors, hue, saturation, low, high, base, generator){
// summary:
// The arguments object that can be passed to define colors for a theme.
// num: Number?
// The number of colors to generate. Defaults to 5.
// colors: String[]|dojo.Color[]?
// A pre-defined set of colors; this is passed through to the Theme directly.
// hue: Number?
// A hue to base the generated colors from (a number from 0 - 359).
// saturation: Number?
// If a hue is passed, this is used for the saturation value (0 - 100).
// low: Number?
// An optional value to determine the lowest value used to generate a color (HSV model)
// high: Number?
// An optional value to determine the highest value used to generate a color (HSV model)
// base: String|dojo.Color?
// A base color to use if we are defining colors using dojox.color.Palette
// generator: String?
// The generator function name from dojox.color.Palette.
this.num = num;
this.colors = colors;
this.hue = hue;
this.saturation = saturation;
this.low = low;
this.high = high;
this.base = base;
this.generator = generator;
}
=====*/
lang.mixin(Theme, {
defaultMarkers: {
CIRCLE: "m-3,0 c0,-4 6,-4 6,0 m-6,0 c0,4 6,4 6,0",
SQUARE: "m-3,-3 l0,6 6,0 0,-6 z",
DIAMOND: "m0,-3 l3,3 -3,3 -3,-3 z",
CROSS: "m0,-3 l0,6 m-3,-3 l6,0",
X: "m-3,-3 l6,6 m0,-6 l-6,6",
TRIANGLE: "m-3,3 l3,-6 3,6 z",
TRIANGLE_INVERTED: "m-3,-3 l3,6 3,-6 z"
},
defaultColors:[
// gray skies
"#54544c", "#858e94", "#6e767a", "#948585", "#474747"
],
defaultTheme: {
// all objects are structs used directly in dojox.gfx
chart:{
stroke: null,
fill: "white",
pageStyle: null,
titleGap: 20,
titlePos: "top",
titleFont: "normal normal bold 14pt Tahoma", // labels on axis
titleFontColor: "#333"
},
plotarea:{
stroke: null,
fill: "white"
},
// TODO: label rotation on axis
axis:{
stroke: { // the axis itself
color: "#333",
width: 1
},
tick: { // used as a foundation for all ticks
color: "#666",
position: "center",
font: "normal normal normal 7pt Tahoma", // labels on axis
fontColor: "#333", // color of labels
titleGap: 15,
titleFont: "normal normal normal 11pt Tahoma", // labels on axis
titleFontColor: "#333", // color of labels
titleOrientation: "axis" // "axis": facing the axis, "away": facing away
},
majorTick: { // major ticks on axis, and used for major gridlines
width: 1,
length: 6
},
minorTick: { // minor ticks on axis, and used for minor gridlines
width: 0.8,
length: 3
},
microTick: { // minor ticks on axis, and used for minor gridlines
width: 0.5,
length: 1
}
},
series: {
// used as a "main" theme for series, sThemes augment it
stroke: {width: 1.5, color: "#333"}, // line
outline: {width: 0.1, color: "#ccc"}, // outline
//shadow: {dx: 1, dy: 1, width: 2, color: [0, 0, 0, 0.3]},
shadow: null, // no shadow
fill: "#ccc", // fill, if appropriate
font: "normal normal normal 8pt Tahoma", // if there's a label
fontColor: "#000", // color of labels
labelWiring: {width: 1, color: "#ccc"} // connect marker and target data item(slice, column, bar...)
},
marker: { // any markers on a series
stroke: {width: 1.5, color: "#333"}, // stroke
outline: {width: 0.1, color: "#ccc"}, // outline
//shadow: {dx: 1, dy: 1, width: 2, color: [0, 0, 0, 0.3]},
shadow: null, // no shadow
fill: "#ccc", // fill if needed
font: "normal normal normal 8pt Tahoma", // label
fontColor: "#000"
},
indicator: {
lineStroke: {width: 1.5, color: "#333"},
lineOutline: {width: 0.1, color: "#ccc"},
lineShadow: null,
stroke: {width: 1.5, color: "#333"},
outline: {width: 0.1, color: "#ccc"},
shadow: null,
fill : "#ccc",
radius: 3,
font: "normal normal normal 10pt Tahoma",
fontColor: "#000",
markerFill: "#ccc",
markerSymbol: "m-3,0 c0,-4 6,-4 6,0 m-6,0 c0,4 6,4 6,0",
markerStroke: {width: 1.5, color: "#333"},
markerOutline: {width: 0.1, color: "#ccc"},
markerShadow: null
}
},
defineColors: function(kwArgs){
// summary:
// Generate a set of colors for the theme based on keyword
// arguments.
// kwArgs: dojox.charting.Theme.__DefineColorArgs
// The arguments object used to define colors.
// returns: dojo.Color[]
// An array of colors for use in a theme.
//
// example:
// | var colors = dojox.charting.Theme.defineColors({
// | base: "#369",
// | generator: "compound"
// | });
//
// example:
// | var colors = dojox.charting.Theme.defineColors({
// | hue: 60,
// | saturation: 90,
// | low: 30,
// | high: 80
// | });
kwArgs = kwArgs || {};
var l, c = [], n = kwArgs.num || 5; // the number of colors to generate
if(kwArgs.colors){
// we have an array of colors predefined, so fix for the number of series.
l = kwArgs.colors.length;
for(var i = 0; i < n; i++){
c.push(kwArgs.colors[i % l]);
}
return c; // dojo.Color[]
}
if(kwArgs.hue){
// single hue, generate a set based on brightness
var s = kwArgs.saturation || 100, // saturation
st = kwArgs.low || 30,
end = kwArgs.high || 90;
// we'd like it to be a little on the darker side.
l = (end + st) / 2;
// alternately, use "shades"
return colorX.Palette.generate(
colorX.fromHsv(kwArgs.hue, s, l), "monochromatic"
).colors;
}
if(kwArgs.generator){
// pass a base color and the name of a generator
return colorX.Palette.generate(kwArgs.base, kwArgs.generator).colors;
}
return c; // dojo.Color[]
},
generateGradient: function(fillPattern, colorFrom, colorTo){
var fill = lang.delegate(fillPattern);
fill.colors = [
{offset: 0, color: colorFrom},
{offset: 1, color: colorTo}
];
return fill;
},
generateHslColor: function(color, luminance){
color = new Color(color);
var hsl = color.toHsl(),
result = colorX.fromHsl(hsl.h, hsl.s, luminance);
result.a = color.a; // add missing opacity
return result;
},
generateHslGradient: function(color, fillPattern, lumFrom, lumTo){
color = new Color(color);
var hsl = color.toHsl(),
colorFrom = colorX.fromHsl(hsl.h, hsl.s, lumFrom),
colorTo = colorX.fromHsl(hsl.h, hsl.s, lumTo);
colorFrom.a = colorTo.a = color.a; // add missing opacity
return Theme.generateGradient(fillPattern, colorFrom, colorTo); // Object
}
});
return Theme;
});
},
'dojox/charting/themes/common':function(){
define("dojox/charting/themes/common", ["dojo/_base/lang"], function(lang){
return lang.getObject("dojox.charting.themes", true);
});
},
'dojox/charting/plot2d/common':function(){
define("dojox/charting/plot2d/common", ["dojo/_base/lang", "dojo/_base/array", "dojo/_base/Color",
"dojox/gfx", "dojox/lang/functional", "../scaler/common"],
function(lang, arr, Color, g, df, sc){
var common = lang.getObject("dojox.charting.plot2d.common", true);
return lang.mixin(common, {
doIfLoaded: sc.doIfLoaded,
makeStroke: function(stroke){
if(!stroke){ return stroke; }
if(typeof stroke == "string" || stroke instanceof Color){
stroke = {color: stroke};
}
return g.makeParameters(g.defaultStroke, stroke);
},
augmentColor: function(target, color){
var t = new Color(target),
c = new Color(color);
c.a = t.a;
return c;
},
augmentStroke: function(stroke, color){
var s = common.makeStroke(stroke);
if(s){
s.color = common.augmentColor(s.color, color);
}
return s;
},
augmentFill: function(fill, color){
var fc, c = new Color(color);
if(typeof fill == "string" || fill instanceof Color){
return common.augmentColor(fill, color);
}
return fill;
},
defaultStats: {
vmin: Number.POSITIVE_INFINITY, vmax: Number.NEGATIVE_INFINITY,
hmin: Number.POSITIVE_INFINITY, hmax: Number.NEGATIVE_INFINITY
},
collectSimpleStats: function(series){
var stats = lang.delegate(common.defaultStats);
for(var i = 0; i < series.length; ++i){
var run = series[i];
for(var j = 0; j < run.data.length; j++){
if(run.data[j] !== null){
if(typeof run.data[j] == "number"){
// 1D case
var old_vmin = stats.vmin, old_vmax = stats.vmax;
if(!("ymin" in run) || !("ymax" in run)){
arr.forEach(run.data, function(val, i){
if(val !== null){
var x = i + 1, y = val;
if(isNaN(y)){ y = 0; }
stats.hmin = Math.min(stats.hmin, x);
stats.hmax = Math.max(stats.hmax, x);
stats.vmin = Math.min(stats.vmin, y);
stats.vmax = Math.max(stats.vmax, y);
}
});
}
if("ymin" in run){ stats.vmin = Math.min(old_vmin, run.ymin); }
if("ymax" in run){ stats.vmax = Math.max(old_vmax, run.ymax); }
}else{
// 2D case
var old_hmin = stats.hmin, old_hmax = stats.hmax,
old_vmin = stats.vmin, old_vmax = stats.vmax;
if(!("xmin" in run) || !("xmax" in run) || !("ymin" in run) || !("ymax" in run)){
arr.forEach(run.data, function(val, i){
if(val !== null){
var x = "x" in val ? val.x : i + 1, y = val.y;
if(isNaN(x)){ x = 0; }
if(isNaN(y)){ y = 0; }
stats.hmin = Math.min(stats.hmin, x);
stats.hmax = Math.max(stats.hmax, x);
stats.vmin = Math.min(stats.vmin, y);
stats.vmax = Math.max(stats.vmax, y);
}
});
}
if("xmin" in run){ stats.hmin = Math.min(old_hmin, run.xmin); }
if("xmax" in run){ stats.hmax = Math.max(old_hmax, run.xmax); }
if("ymin" in run){ stats.vmin = Math.min(old_vmin, run.ymin); }
if("ymax" in run){ stats.vmax = Math.max(old_vmax, run.ymax); }
}
break;
}
}
}
return stats;
},
calculateBarSize: function(/* Number */ availableSize, /* Object */ opt, /* Number? */ clusterSize){
if(!clusterSize){
clusterSize = 1;
}
var gap = opt.gap, size = (availableSize - 2 * gap) / clusterSize;
if("minBarSize" in opt){
size = Math.max(size, opt.minBarSize);
}
if("maxBarSize" in opt){
size = Math.min(size, opt.maxBarSize);
}
size = Math.max(size, 1);
gap = (availableSize - size * clusterSize) / 2;
return {size: size, gap: gap}; // Object
},
collectStackedStats: function(series){
// collect statistics
var stats = lang.clone(common.defaultStats);
if(series.length){
// 1st pass: find the maximal length of runs
stats.hmin = Math.min(stats.hmin, 1);
stats.hmax = df.foldl(series, "seed, run -> Math.max(seed, run.data.length)", stats.hmax);
// 2nd pass: stack values
for(var i = 0; i < stats.hmax; ++i){
var v = series[0].data[i];
v = v && (typeof v == "number" ? v : v.y);
if(isNaN(v)){ v = 0; }
stats.vmin = Math.min(stats.vmin, v);
for(var j = 1; j < series.length; ++j){
var t = series[j].data[i];
t = t && (typeof t == "number" ? t : t.y);
if(isNaN(t)){ t = 0; }
v += t;
}
stats.vmax = Math.max(stats.vmax, v);
}
}
return stats;
},
curve: function(/* Number[] */a, /* Number|String */tension){
// FIX for #7235, submitted by Enzo Michelangeli.
// Emulates the smoothing algorithms used in a famous, unnamed spreadsheet
// program ;)
var array = a.slice(0);
if(tension == "x") {
array[array.length] = arr[0]; // add a last element equal to the first, closing the loop
}
var p=arr.map(array, function(item, i){
if(i==0){ return "M" + item.x + "," + item.y; }
if(!isNaN(tension)) { // use standard Dojo smoothing in tension is numeric
var dx=item.x-array[i-1].x, dy=array[i-1].y;
return "C"+(item.x-(tension-1)*(dx/tension))+","+dy+" "+(item.x-(dx/tension))+","+item.y+" "+item.x+","+item.y;
} else if(tension == "X" || tension == "x" || tension == "S") {
// use Excel "line smoothing" algorithm (http://xlrotor.com/resources/files.shtml)
var p0, p1 = array[i-1], p2 = array[i], p3;
var bz1x, bz1y, bz2x, bz2y;
var f = 1/6;
if(i==1) {
if(tension == "x") {
p0 = array[array.length-2];
} else { // "tension == X || tension == "S"
p0 = p1;
}
f = 1/3;
} else {
p0 = array[i-2];
}
if(i==(array.length-1)) {
if(tension == "x") {
p3 = array[1];
} else { // "tension == X || tension == "S"
p3 = p2;
}
f = 1/3;
} else {
p3 = array[i+1];
}
var p1p2 = Math.sqrt((p2.x-p1.x)*(p2.x-p1.x)+(p2.y-p1.y)*(p2.y-p1.y));
var p0p2 = Math.sqrt((p2.x-p0.x)*(p2.x-p0.x)+(p2.y-p0.y)*(p2.y-p0.y));
var p1p3 = Math.sqrt((p3.x-p1.x)*(p3.x-p1.x)+(p3.y-p1.y)*(p3.y-p1.y));
var p0p2f = p0p2 * f;
var p1p3f = p1p3 * f;
if(p0p2f > p1p2/2 && p1p3f > p1p2/2) {
p0p2f = p1p2/2;
p1p3f = p1p2/2;
} else if(p0p2f > p1p2/2) {
p0p2f = p1p2/2;
p1p3f = p1p2/2 * p1p3/p0p2;
} else if(p1p3f > p1p2/2) {
p1p3f = p1p2/2;
p0p2f = p1p2/2 * p0p2/p1p3;
}
if(tension == "S") {
if(p0 == p1) { p0p2f = 0; }
if(p2 == p3) { p1p3f = 0; }
}
bz1x = p1.x + p0p2f*(p2.x - p0.x)/p0p2;
bz1y = p1.y + p0p2f*(p2.y - p0.y)/p0p2;
bz2x = p2.x - p1p3f*(p3.x - p1.x)/p1p3;
bz2y = p2.y - p1p3f*(p3.y - p1.y)/p1p3;
}
return "C"+(bz1x+","+bz1y+" "+bz2x+","+bz2y+" "+p2.x+","+p2.y);
});
return p.join(" ");
},
getLabel: function(/*Number*/number, /*Boolean*/fixed, /*Number*/precision){
return sc.doIfLoaded("dojo/number", function(numberLib){
return (fixed ? numberLib.format(number, {places : precision}) :
numberLib.format(number)) || "";
}, function(){
return fixed ? number.toFixed(precision) : number.toString();
});
}
});
});
},
'dijit/_Widget':function(){
define("dijit/_Widget", [
"dojo/aspect", // aspect.around
"dojo/_base/config", // config.isDebug
"dojo/_base/connect", // connect.connect
"dojo/_base/declare", // declare
"dojo/_base/kernel", // kernel.deprecated
"dojo/_base/lang", // lang.hitch
"dojo/query",
"dojo/ready",
"./registry", // registry.byNode
"./_WidgetBase",
"./_OnDijitClickMixin",
"./_FocusMixin",
"dojo/uacss", // browser sniffing (included for back-compat; subclasses may be using)
"./hccss" // high contrast mode sniffing (included to set CSS classes on <body>, module ret value unused)
], function(aspect, config, connect, declare, kernel, lang, query, ready,
registry, _WidgetBase, _OnDijitClickMixin, _FocusMixin){
/*=====
var _WidgetBase = dijit._WidgetBase;
var _OnDijitClickMixin = dijit._OnDijitClickMixin;
var _FocusMixin = dijit._FocusMixin;
=====*/
// module:
// dijit/_Widget
// summary:
// Old base for widgets. New widgets should extend _WidgetBase instead
function connectToDomNode(){
// summary:
// If user connects to a widget method === this function, then they will
// instead actually be connecting the equivalent event on this.domNode
}
// Trap dojo.connect() calls to connectToDomNode methods, and redirect to _Widget.on()
function aroundAdvice(originalConnect){
return function(obj, event, scope, method){
if(obj && typeof event == "string" && obj[event] == connectToDomNode){
return obj.on(event.substring(2).toLowerCase(), lang.hitch(scope, method));
}
return originalConnect.apply(connect, arguments);
};
}
aspect.around(connect, "connect", aroundAdvice);
if(kernel.connect){
aspect.around(kernel, "connect", aroundAdvice);
}
var _Widget = declare("dijit._Widget", [_WidgetBase, _OnDijitClickMixin, _FocusMixin], {
// summary:
// Base class for all Dijit widgets.
//
// Extends _WidgetBase, adding support for:
// - declaratively/programatically specifying widget initialization parameters like
// onMouseMove="foo" that call foo when this.domNode gets a mousemove event
// - ondijitclick
// Support new data-dojo-attach-event="ondijitclick: ..." that is triggered by a mouse click or a SPACE/ENTER keypress
// - focus related functions
// In particular, the onFocus()/onBlur() callbacks. Driven internally by
// dijit/_base/focus.js.
// - deprecated methods
// - onShow(), onHide(), onClose()
//
// Also, by loading code in dijit/_base, turns on:
// - browser sniffing (putting browser id like .dj_ie on <html> node)
// - high contrast mode sniffing (add .dijit_a11y class to <body> if machine is in high contrast mode)
////////////////// DEFERRED CONNECTS ///////////////////
onClick: connectToDomNode,
/*=====
onClick: function(event){
// summary:
// Connect to this function to receive notifications of mouse click events.
// event:
// mouse Event
// tags:
// callback
},
=====*/
onDblClick: connectToDomNode,
/*=====
onDblClick: function(event){
// summary:
// Connect to this function to receive notifications of mouse double click events.
// event:
// mouse Event
// tags:
// callback
},
=====*/
onKeyDown: connectToDomNode,
/*=====
onKeyDown: function(event){
// summary:
// Connect to this function to receive notifications of keys being pressed down.
// event:
// key Event
// tags:
// callback
},
=====*/
onKeyPress: connectToDomNode,
/*=====
onKeyPress: function(event){
// summary:
// Connect to this function to receive notifications of printable keys being typed.
// event:
// key Event
// tags:
// callback
},
=====*/
onKeyUp: connectToDomNode,
/*=====
onKeyUp: function(event){
// summary:
// Connect to this function to receive notifications of keys being released.
// event:
// key Event
// tags:
// callback
},
=====*/
onMouseDown: connectToDomNode,
/*=====
onMouseDown: function(event){
// summary:
// Connect to this function to receive notifications of when the mouse button is pressed down.
// event:
// mouse Event
// tags:
// callback
},
=====*/
onMouseMove: connectToDomNode,
/*=====
onMouseMove: function(event){
// summary:
// Connect to this function to receive notifications of when the mouse moves over nodes contained within this widget.
// event:
// mouse Event
// tags:
// callback
},
=====*/
onMouseOut: connectToDomNode,
/*=====
onMouseOut: function(event){
// summary:
// Connect to this function to receive notifications of when the mouse moves off of nodes contained within this widget.
// event:
// mouse Event
// tags:
// callback
},
=====*/
onMouseOver: connectToDomNode,
/*=====
onMouseOver: function(event){
// summary:
// Connect to this function to receive notifications of when the mouse moves onto nodes contained within this widget.
// event:
// mouse Event
// tags:
// callback
},
=====*/
onMouseLeave: connectToDomNode,
/*=====
onMouseLeave: function(event){
// summary:
// Connect to this function to receive notifications of when the mouse moves off of this widget.
// event:
// mouse Event
// tags:
// callback
},
=====*/
onMouseEnter: connectToDomNode,
/*=====
onMouseEnter: function(event){
// summary:
// Connect to this function to receive notifications of when the mouse moves onto this widget.
// event:
// mouse Event
// tags:
// callback
},
=====*/
onMouseUp: connectToDomNode,
/*=====
onMouseUp: function(event){
// summary:
// Connect to this function to receive notifications of when the mouse button is released.
// event:
// mouse Event
// tags:
// callback
},
=====*/
constructor: function(params){
// extract parameters like onMouseMove that should connect directly to this.domNode
this._toConnect = {};
for(var name in params){
if(this[name] === connectToDomNode){
this._toConnect[name.replace(/^on/, "").toLowerCase()] = params[name];
delete params[name];
}
}
},
postCreate: function(){
this.inherited(arguments);
// perform connection from this.domNode to user specified handlers (ex: onMouseMove)
for(var name in this._toConnect){
this.on(name, this._toConnect[name]);
}
delete this._toConnect;
},
on: function(/*String*/ type, /*Function*/ func){
if(this[this._onMap(type)] === connectToDomNode){
// Use connect.connect() rather than on() to get handling for "onmouseenter" on non-IE, etc.
// Also, need to specify context as "this" rather than the default context of the DOMNode
return connect.connect(this.domNode, type.toLowerCase(), this, func);
}
return this.inherited(arguments);
},
_setFocusedAttr: function(val){
// Remove this method in 2.0 (or sooner), just here to set _focused == focused, for back compat
// (but since it's a private variable we aren't required to keep supporting it).
this._focused = val;
this._set("focused", val);
},
////////////////// DEPRECATED METHODS ///////////////////
setAttribute: function(/*String*/ attr, /*anything*/ value){
// summary:
// Deprecated. Use set() instead.
// tags:
// deprecated
kernel.deprecated(this.declaredClass+"::setAttribute(attr, value) is deprecated. Use set() instead.", "", "2.0");
this.set(attr, value);
},
attr: function(/*String|Object*/name, /*Object?*/value){
// summary:
// Set or get properties on a widget instance.
// name:
// The property to get or set. If an object is passed here and not
// a string, its keys are used as names of attributes to be set
// and the value of the object as values to set in the widget.
// value:
// Optional. If provided, attr() operates as a setter. If omitted,
// the current value of the named property is returned.
// description:
// This method is deprecated, use get() or set() directly.
// Print deprecation warning but only once per calling function
if(config.isDebug){
var alreadyCalledHash = arguments.callee._ach || (arguments.callee._ach = {}),
caller = (arguments.callee.caller || "unknown caller").toString();
if(!alreadyCalledHash[caller]){
kernel.deprecated(this.declaredClass + "::attr() is deprecated. Use get() or set() instead, called from " +
caller, "", "2.0");
alreadyCalledHash[caller] = true;
}
}
var args = arguments.length;
if(args >= 2 || typeof name === "object"){ // setter
return this.set.apply(this, arguments);
}else{ // getter
return this.get(name);
}
},
getDescendants: function(){
// summary:
// Returns all the widgets contained by this, i.e., all widgets underneath this.containerNode.
// This method should generally be avoided as it returns widgets declared in templates, which are
// supposed to be internal/hidden, but it's left here for back-compat reasons.
kernel.deprecated(this.declaredClass+"::getDescendants() is deprecated. Use getChildren() instead.", "", "2.0");
return this.containerNode ? query('[widgetId]', this.containerNode).map(registry.byNode) : []; // dijit._Widget[]
},
////////////////// MISCELLANEOUS METHODS ///////////////////
_onShow: function(){
// summary:
// Internal method called when this widget is made visible.
// See `onShow` for details.
this.onShow();
},
onShow: function(){
// summary:
// Called when this widget becomes the selected pane in a
// `dijit.layout.TabContainer`, `dijit.layout.StackContainer`,
// `dijit.layout.AccordionContainer`, etc.
//
// Also called to indicate display of a `dijit.Dialog`, `dijit.TooltipDialog`, or `dijit.TitlePane`.
// tags:
// callback
},
onHide: function(){
// summary:
// Called when another widget becomes the selected pane in a
// `dijit.layout.TabContainer`, `dijit.layout.StackContainer`,
// `dijit.layout.AccordionContainer`, etc.
//
// Also called to indicate hide of a `dijit.Dialog`, `dijit.TooltipDialog`, or `dijit.TitlePane`.
// tags:
// callback
},
onClose: function(){
// summary:
// Called when this widget is being displayed as a popup (ex: a Calendar popped
// up from a DateTextBox), and it is hidden.
// This is called from the dijit.popup code, and should not be called directly.
//
// Also used as a parameter for children of `dijit.layout.StackContainer` or subclasses.
// Callback if a user tries to close the child. Child will be closed if this function returns true.
// tags:
// extension
return true; // Boolean
}
});
// For back-compat, remove in 2.0.
if(!kernel.isAsync){
ready(0, function(){
var requires = ["dijit/_base"];
require(requires); // use indirection so modules not rolled into a build
});
}
return _Widget;
});
},
'dijit/_FocusMixin':function(){
define("dijit/_FocusMixin", [
"./focus",
"./_WidgetBase",
"dojo/_base/declare", // declare
"dojo/_base/lang" // lang.extend
], function(focus, _WidgetBase, declare, lang){
/*=====
var _WidgetBase = dijit._WidgetBase;
=====*/
// module:
// dijit/_FocusMixin
// summary:
// Mixin to widget to provide _onFocus() and _onBlur() methods that
// fire when a widget or it's descendants get/lose focus
// We don't know where _FocusMixin will occur in the inheritance chain, but we need the _onFocus()/_onBlur() below
// to be last in the inheritance chain, so mixin to _WidgetBase.
lang.extend(_WidgetBase, {
// focused: [readonly] Boolean
// This widget or a widget it contains has focus, or is "active" because
// it was recently clicked.
focused: false,
onFocus: function(){
// summary:
// Called when the widget becomes "active" because
// it or a widget inside of it either has focus, or has recently
// been clicked.
// tags:
// callback
},
onBlur: function(){
// summary:
// Called when the widget stops being "active" because
// focus moved to something outside of it, or the user
// clicked somewhere outside of it, or the widget was
// hidden.
// tags:
// callback
},
_onFocus: function(){
// summary:
// This is where widgets do processing for when they are active,
// such as changing CSS classes. See onFocus() for more details.
// tags:
// protected
this.onFocus();
},
_onBlur: function(){
// summary:
// This is where widgets do processing for when they stop being active,
// such as changing CSS classes. See onBlur() for more details.
// tags:
// protected
this.onBlur();
}
});
return declare("dijit._FocusMixin", null, {
// summary:
// Mixin to widget to provide _onFocus() and _onBlur() methods that
// fire when a widget or it's descendants get/lose focus
// flag that I want _onFocus()/_onBlur() notifications from focus manager
_focusManager: focus
});
});
},
'dijit/_OnDijitClickMixin':function(){
define("dijit/_OnDijitClickMixin", [
"dojo/on",
"dojo/_base/array", // array.forEach
"dojo/keys", // keys.ENTER keys.SPACE
"dojo/_base/declare", // declare
"dojo/_base/sniff", // has("ie")
"dojo/_base/unload", // unload.addOnWindowUnload
"dojo/_base/window" // win.doc.addEventListener win.doc.attachEvent win.doc.detachEvent
], function(on, array, keys, declare, has, unload, win){
// module:
// dijit/_OnDijitClickMixin
// summary:
// Mixin so you can pass "ondijitclick" to this.connect() method,
// as a way to handle clicks by mouse, or by keyboard (SPACE/ENTER key)
// Keep track of where the last keydown event was, to help avoid generating
// spurious ondijitclick events when:
// 1. focus is on a <button> or <a>
// 2. user presses then releases the ENTER key
// 3. onclick handler fires and shifts focus to another node, with an ondijitclick handler
// 4. onkeyup event fires, causing the ondijitclick handler to fire
var lastKeyDownNode = null;
if(has("ie")){
(function(){
var keydownCallback = function(evt){
lastKeyDownNode = evt.srcElement;
};
win.doc.attachEvent('onkeydown', keydownCallback);
unload.addOnWindowUnload(function(){
win.doc.detachEvent('onkeydown', keydownCallback);
});
})();
}else{
win.doc.addEventListener('keydown', function(evt){
lastKeyDownNode = evt.target;
}, true);
}
// Custom a11yclick (a.k.a. ondijitclick) event
var a11yclick = function(node, listener){
if(/input|button/i.test(node.nodeName)){
// pass through, the browser already generates click event on SPACE/ENTER key
return on(node, "click", listener);
}else{
// Don't fire the click event unless both the keydown and keyup occur on this node.
// Avoids problems where focus shifted to this node or away from the node on keydown,
// either causing this node to process a stray keyup event, or causing another node
// to get a stray keyup event.
function clickKey(/*Event*/ e){
return (e.keyCode == keys.ENTER || e.keyCode == keys.SPACE) &&
!e.ctrlKey && !e.shiftKey && !e.altKey && !e.metaKey;
}
var handles = [
on(node, "keypress", function(e){
//console.log(this.id + ": onkeydown, e.target = ", e.target, ", lastKeyDownNode was ", lastKeyDownNode, ", equality is ", (e.target === lastKeyDownNode));
if(clickKey(e)){
// needed on IE for when focus changes between keydown and keyup - otherwise dropdown menus do not work
lastKeyDownNode = e.target;
// Prevent viewport scrolling on space key in IE<9.
// (Reproducible on test_Button.html on any of the first dijit.form.Button examples)
// Do this onkeypress rather than onkeydown because onkeydown.preventDefault() will
// suppress the onkeypress event, breaking _HasDropDown
e.preventDefault();
}
}),
on(node, "keyup", function(e){
//console.log(this.id + ": onkeyup, e.target = ", e.target, ", lastKeyDownNode was ", lastKeyDownNode, ", equality is ", (e.target === lastKeyDownNode));
if(clickKey(e) && e.target == lastKeyDownNode){ // === breaks greasemonkey
//need reset here or have problems in FF when focus returns to trigger element after closing popup/alert
lastKeyDownNode = null;
listener.call(this, e);
}
}),
on(node, "click", function(e){
// and connect for mouse clicks too (or touch-clicks on mobile)
listener.call(this, e);
})
];
return {
remove: function(){
array.forEach(handles, function(h){ h.remove(); });
}
};
}
};
return declare("dijit._OnDijitClickMixin", null, {
connect: function(
/*Object|null*/ obj,
/*String|Function*/ event,
/*String|Function*/ method){
// summary:
// Connects specified obj/event to specified method of this object
// and registers for disconnect() on widget destroy.
// description:
// Provide widget-specific analog to connect.connect, except with the
// implicit use of this widget as the target object.
// This version of connect also provides a special "ondijitclick"
// event which triggers on a click or space or enter keyup.
// Events connected with `this.connect` are disconnected upon
// destruction.
// returns:
// A handle that can be passed to `disconnect` in order to disconnect before
// the widget is destroyed.
// example:
// | var btn = new dijit.form.Button();
// | // when foo.bar() is called, call the listener we're going to
// | // provide in the scope of btn
// | btn.connect(foo, "bar", function(){
// | console.debug(this.toString());
// | });
// tags:
// protected
return this.inherited(arguments, [obj, event == "ondijitclick" ? a11yclick : event, method]);
}
});
});
},
'dojo/cache':function(){
define(["./_base/kernel", "./text"], function(dojo, text){
// module:
// dojo/cache
// summary:
// The module defines dojo.cache by loading dojo/text.
//dojo.cache is defined in dojo/text
return dojo.cache;
});
},
'dojox/charting/plot2d/Bars':function(){
define("dojox/charting/plot2d/Bars", ["dojo/_base/kernel", "dojo/_base/lang", "dojo/_base/array", "dojo/_base/declare", "./Base", "./common",
"dojox/gfx/fx", "dojox/lang/utils", "dojox/lang/functional", "dojox/lang/functional/reversed"],
function(dojo, lang, arr, declare, Base, dc, fx, du, df, dfr){
/*=====
dojo.declare("dojox.charting.plot2d.__BarCtorArgs", dojox.charting.plot2d.__DefaultCtorArgs, {
// summary:
// Additional keyword arguments for bar charts.
// minBarSize: Number?
// The minimum size for a bar in pixels. Default is 1.
minBarSize: 1,
// maxBarSize: Number?
// The maximum size for a bar in pixels. Default is 1.
maxBarSize: 1,
// enableCache: Boolean?
// Whether the bars rect are cached from one rendering to another. This improves the rendering performance of
// successive rendering but penalize the first rendering. Default false.
enableCache: false
});
var Base = dojox.charting.plot2d.Base;
=====*/
var purgeGroup = dfr.lambda("item.purgeGroup()");
return declare("dojox.charting.plot2d.Bars", Base, {
// summary:
// The plot object representing a bar chart (horizontal bars).
defaultParams: {
hAxis: "x", // use a horizontal axis named "x"
vAxis: "y", // use a vertical axis named "y"
gap: 0, // gap between columns in pixels
animate: null, // animate bars into place
enableCache: false
},
optionalParams: {
minBarSize: 1, // minimal bar width in pixels
maxBarSize: 1, // maximal bar width in pixels
// theme component
stroke: {},
outline: {},
shadow: {},
fill: {},
font: "",
fontColor: ""
},
constructor: function(chart, kwArgs){
// summary:
// The constructor for a bar chart.
// chart: dojox.charting.Chart
// The chart this plot belongs to.
// kwArgs: dojox.charting.plot2d.__BarCtorArgs?
// An optional keyword arguments object to help define the plot.
this.opt = lang.clone(this.defaultParams);
du.updateWithObject(this.opt, kwArgs);
du.updateWithPattern(this.opt, kwArgs, this.optionalParams);
this.series = [];
this.hAxis = this.opt.hAxis;
this.vAxis = this.opt.vAxis;
this.animate = this.opt.animate;
},
getSeriesStats: function(){
// summary:
// Calculate the min/max on all attached series in both directions.
// returns: Object
// {hmin, hmax, vmin, vmax} min/max in both directions.
var stats = dc.collectSimpleStats(this.series), t;
stats.hmin -= 0.5;
stats.hmax += 0.5;
t = stats.hmin, stats.hmin = stats.vmin, stats.vmin = t;
t = stats.hmax, stats.hmax = stats.vmax, stats.vmax = t;
return stats;
},
createRect: function(run, creator, params){
var rect;
if(this.opt.enableCache && run._rectFreePool.length > 0){
rect = run._rectFreePool.pop();
rect.setShape(params);
// was cleared, add it back
creator.add(rect);
}else{
rect = creator.createRect(params);
}
if(this.opt.enableCache){
run._rectUsePool.push(rect);
}
return rect;
},
render: function(dim, offsets){
// summary:
// Run the calculations for any axes for this plot.
// dim: Object
// An object in the form of { width, height }
// offsets: Object
// An object of the form { l, r, t, b}.
// returns: dojox.charting.plot2d.Bars
// A reference to this plot for functional chaining.
if(this.zoom && !this.isDataDirty()){
return this.performZoom(dim, offsets);
}
this.dirty = this.isDirty();
this.resetEvents();
if(this.dirty){
arr.forEach(this.series, purgeGroup);
this._eventSeries = {};
this.cleanGroup();
var s = this.group;
df.forEachRev(this.series, function(item){ item.cleanGroup(s); });
}
var t = this.chart.theme, f, gap, height,
ht = this._hScaler.scaler.getTransformerFromModel(this._hScaler),
vt = this._vScaler.scaler.getTransformerFromModel(this._vScaler),
baseline = Math.max(0, this._hScaler.bounds.lower),
baselineWidth = ht(baseline),
events = this.events();
f = dc.calculateBarSize(this._vScaler.bounds.scale, this.opt);
gap = f.gap;
height = f.size;
for(var i = this.series.length - 1; i >= 0; --i){
var run = this.series[i];
if(!this.dirty && !run.dirty){
t.skip();
this._reconnectEvents(run.name);
continue;
}
run.cleanGroup();
if(this.opt.enableCache){
run._rectFreePool = (run._rectFreePool?run._rectFreePool:[]).concat(run._rectUsePool?run._rectUsePool:[]);
run._rectUsePool = [];
}
var theme = t.next("bar", [this.opt, run]), s = run.group,
eventSeries = new Array(run.data.length);
for(var j = 0; j < run.data.length; ++j){
var value = run.data[j];
if(value !== null){
var v = typeof value == "number" ? value : value.y,
hv = ht(v),
width = hv - baselineWidth,
w = Math.abs(width),
finalTheme = typeof value != "number" ?
t.addMixin(theme, "bar", value, true) :
t.post(theme, "bar");
if(w >= 0 && height >= 1){
var rect = {
x: offsets.l + (v < baseline ? hv : baselineWidth),
y: dim.height - offsets.b - vt(j + 1.5) + gap,
width: w, height: height
};
var specialFill = this._plotFill(finalTheme.series.fill, dim, offsets);
specialFill = this._shapeFill(specialFill, rect);
var shape = this.createRect(run, s, rect).setFill(specialFill).setStroke(finalTheme.series.stroke);
run.dyn.fill = shape.getFill();
run.dyn.stroke = shape.getStroke();
if(events){
var o = {
element: "bar",
index: j,
run: run,
shape: shape,
x: v,
y: j + 1.5
};
this._connectEvents(o);
eventSeries[j] = o;
}
if(this.animate){
this._animateBar(shape, offsets.l + baselineWidth, -w);
}
}
}
}
this._eventSeries[run.name] = eventSeries;
run.dirty = false;
}
this.dirty = false;
return this; // dojox.charting.plot2d.Bars
},
_animateBar: function(shape, hoffset, hsize){
fx.animateTransform(lang.delegate({
shape: shape,
duration: 1200,
transform: [
{name: "translate", start: [hoffset - (hoffset/hsize), 0], end: [0, 0]},
{name: "scale", start: [1/hsize, 1], end: [1, 1]},
{name: "original"}
]
}, this.animate)).play();
}
});
});
},
'dojox/gfx/_base':function(){
define("dojox/gfx/_base", ["dojo/_base/lang", "dojo/_base/html", "dojo/_base/Color", "dojo/_base/sniff", "dojo/_base/window",
"dojo/_base/array","dojo/dom", "dojo/dom-construct","dojo/dom-geometry"],
function(lang, html, Color, has, win, arr, dom, domConstruct, domGeom){
// module:
// dojox/gfx
// summary:
// This module contains common core Graphics API used by different graphics renderers.
var g = lang.getObject("dojox.gfx", true),
b = g._base = {};
/*===== g = dojox.gfx; b = dojox.gfx._base; =====*/
// candidates for dojox.style (work on VML and SVG nodes)
g._hasClass = function(/*DomNode*/node, /*String*/classStr){
// summary:
// Returns whether or not the specified classes are a portion of the
// class list currently applied to the node.
// return (new RegExp('(^|\\s+)'+classStr+'(\\s+|$)')).test(node.className) // Boolean
var cls = node.getAttribute("className");
return cls && (" " + cls + " ").indexOf(" " + classStr + " ") >= 0; // Boolean
};
g._addClass = function(/*DomNode*/node, /*String*/classStr){
// summary:
// Adds the specified classes to the end of the class list on the
// passed node.
var cls = node.getAttribute("className") || "";
if(!cls || (" " + cls + " ").indexOf(" " + classStr + " ") < 0){
node.setAttribute("className", cls + (cls ? " " : "") + classStr);
}
};
g._removeClass = function(/*DomNode*/node, /*String*/classStr){
// summary: Removes classes from node.
var cls = node.getAttribute("className");
if(cls){
node.setAttribute(
"className",
cls.replace(new RegExp('(^|\\s+)' + classStr + '(\\s+|$)'), "$1$2")
);
}
};
// candidate for dojox.html.metrics (dynamic font resize handler is not implemented here)
// derived from Morris John's emResized measurer
b._getFontMeasurements = function(){
// summary:
// Returns an object that has pixel equivilents of standard font
// size values.
var heights = {
'1em': 0, '1ex': 0, '100%': 0, '12pt': 0, '16px': 0, 'xx-small': 0,
'x-small': 0, 'small': 0, 'medium': 0, 'large': 0, 'x-large': 0,
'xx-large': 0
};
var p;
if(has("ie")){
// we do a font-size fix if and only if one isn't applied already.
// NOTE: If someone set the fontSize on the HTML Element, this will kill it.
win.doc.documentElement.style.fontSize="100%";
}
// set up the measuring node.
var div = domConstruct.create("div", {style: {
position: "absolute",
left: "0",
top: "-100px",
width: "30px",
height: "1000em",
borderWidth: "0",
margin: "0",
padding: "0",
outline: "none",
lineHeight: "1",
overflow: "hidden"
}}, win.body());
// do the measurements.
for(p in heights){
div.style.fontSize = p;
heights[p] = Math.round(div.offsetHeight * 12/16) * 16/12 / 1000;
}
win.body().removeChild(div);
return heights; //object
};
var fontMeasurements = null;
b._getCachedFontMeasurements = function(recalculate){
if(recalculate || !fontMeasurements){
fontMeasurements = b._getFontMeasurements();
}
return fontMeasurements;
};
// candidate for dojox.html.metrics
var measuringNode = null, empty = {};
b._getTextBox = function( /*String*/ text,
/*Object*/ style,
/*String?*/ className){
var m, s, al = arguments.length;
var i;
if(!measuringNode){
measuringNode = domConstruct.create("div", {style: {
position: "absolute",
top: "-10000px",
left: "0"
}}, win.body());
}
m = measuringNode;
// reset styles
m.className = "";
s = m.style;
s.borderWidth = "0";
s.margin = "0";
s.padding = "0";
s.outline = "0";
// set new style
if(al > 1 && style){
for(i in style){
if(i in empty){ continue; }
s[i] = style[i];
}
}
// set classes
if(al > 2 && className){
m.className = className;
}
// take a measure
m.innerHTML = text;
if(m["getBoundingClientRect"]){
var bcr = m.getBoundingClientRect();
return {l: bcr.left, t: bcr.top, w: bcr.width || (bcr.right - bcr.left), h: bcr.height || (bcr.bottom - bcr.top)};
}else{
return domGeom.getMarginBox(m);
}
};
// candidate for dojo.dom
var uniqueId = 0;
b._getUniqueId = function(){
// summary: returns a unique string for use with any DOM element
var id;
do{
id = dojo._scopeName + "xUnique" + (++uniqueId);
}while(dom.byId(id));
return id;
};
lang.mixin(g, {
// summary:
// defines constants, prototypes, and utility functions for the core Graphics API
// default shapes, which are used to fill in missing parameters
defaultPath: {
// summary:
// Defines the default Path prototype object.
type: "path",
// type: String
// Specifies this object is a Path, default value 'path'.
path: ""
// path: String
// The path commands. See W32C SVG 1.0 specification.
// Defaults to empty string value.
},
defaultPolyline: {
// summary:
// Defines the default PolyLine prototype.
type: "polyline",
// type: String
// Specifies this object is a PolyLine, default value 'polyline'.
points: []
// points: Array
// An array of point objects [{x:0,y:0},...] defining the default polyline's line segments. Value is an empty array [].
},
defaultRect: {
// summary:
// Defines the default Rect prototype.
type: "rect",
// type: String
// Specifies this default object is a type of Rect. Value is 'rect'
x: 0,
// x: Number
// The X coordinate of the default rectangles position, value 0.
y: 0,
// y: Number
// The Y coordinate of the default rectangle's position, value 0.
width: 100,
// width: Number
// The width of the default rectangle, value 100.
height: 100,
// height: Number
// The height of the default rectangle, value 100.
r: 0
// r: Number
// The corner radius for the default rectangle, value 0.
},
defaultEllipse: {
// summary:
// Defines the default Ellipse prototype.
type: "ellipse",
// type: String
// Specifies that this object is a type of Ellipse, value is 'ellipse'
cx: 0,
// cx: Number
// The X coordinate of the center of the ellipse, default value 0.
cy: 0,
// cy: Number
// The Y coordinate of the center of the ellipse, default value 0.
rx: 200,
// rx: Number
// The radius of the ellipse in the X direction, default value 200.
ry: 100
// ry: Number
// The radius of the ellipse in the Y direction, default value 200.
},
defaultCircle: {
// summary:
// An object defining the default Circle prototype.
type: "circle",
// type: String
// Specifies this object is a circle, value 'circle'
cx: 0,
// cx: Number
// The X coordinate of the center of the circle, default value 0.
cy: 0,
// cy: Number
// The Y coordinate of the center of the circle, default value 0.
r: 100
// r: Number
// The radius, default value 100.
},
defaultLine: {
// summary:
// An pbject defining the default Line prototype.
type: "line",
// type: String
// Specifies this is a Line, value 'line'
x1: 0,
// x1: Number
// The X coordinate of the start of the line, default value 0.
y1: 0,
// y1: Number
// The Y coordinate of the start of the line, default value 0.
x2: 100,
// x2: Number
// The X coordinate of the end of the line, default value 100.
y2: 100
// y2: Number
// The Y coordinate of the end of the line, default value 100.
},
defaultImage: {
// summary:
// Defines the default Image prototype.
type: "image",
// type: String
// Specifies this object is an image, value 'image'.
x: 0,
// x: Number
// The X coordinate of the image's position, default value 0.
y: 0,
// y: Number
// The Y coordinate of the image's position, default value 0.
width: 0,
// width: Number
// The width of the image, default value 0.
height: 0,
// height:Number
// The height of the image, default value 0.
src: ""
// src: String
// The src url of the image, defaults to empty string.
},
defaultText: {
// summary:
// Defines the default Text prototype.
type: "text",
// type: String
// Specifies this is a Text shape, value 'text'.
x: 0,
// x: Number
// The X coordinate of the text position, default value 0.
y: 0,
// y: Number
// The Y coordinate of the text position, default value 0.
text: "",
// text: String
// The text to be displayed, default value empty string.
align: "start",
// align: String
// The horizontal text alignment, one of 'start', 'end', 'center'. Default value 'start'.
decoration: "none",
// decoration: String
// The text decoration , one of 'none', ... . Default value 'none'.
rotated: false,
// rotated: Boolean
// Whether the text is rotated, boolean default value false.
kerning: true
// kerning: Boolean
// Whether kerning is used on the text, boolean default value true.
},
defaultTextPath: {
// summary:
// Defines the default TextPath prototype.
type: "textpath",
// type: String
// Specifies this is a TextPath, value 'textpath'.
text: "",
// text: String
// The text to be displayed, default value empty string.
align: "start",
// align: String
// The horizontal text alignment, one of 'start', 'end', 'center'. Default value 'start'.
decoration: "none",
// decoration: String
// The text decoration , one of 'none', ... . Default value 'none'.
rotated: false,
// rotated: Boolean
// Whether the text is rotated, boolean default value false.
kerning: true
// kerning: Boolean
// Whether kerning is used on the text, boolean default value true.
},
// default stylistic attributes
defaultStroke: {
// summary:
// A stroke defines stylistic properties that are used when drawing a path.
// This object defines the default Stroke prototype.
type: "stroke",
// type: String
// Specifies this object is a type of Stroke, value 'stroke'.
color: "black",
// color: String
// The color of the stroke, default value 'black'.
style: "solid",
// style: String
// The style of the stroke, one of 'solid', ... . Default value 'solid'.
width: 1,
// width: Number
// The width of a stroke, default value 1.
cap: "butt",
// cap: String
// The endcap style of the path. One of 'butt', 'round', ... . Default value 'butt'.
join: 4
// join: Number
// The join style to use when combining path segments. Default value 4.
},
defaultLinearGradient: {
// summary:
// An object defining the default stylistic properties used for Linear Gradient fills.
// Linear gradients are drawn along a virtual line, which results in appearance of a rotated pattern in a given direction/orientation.
type: "linear",
// type: String
// Specifies this object is a Linear Gradient, value 'linear'
x1: 0,
// x1: Number
// The X coordinate of the start of the virtual line along which the gradient is drawn, default value 0.
y1: 0,
// y1: Number
// The Y coordinate of the start of the virtual line along which the gradient is drawn, default value 0.
x2: 100,
// x2: Number
// The X coordinate of the end of the virtual line along which the gradient is drawn, default value 100.
y2: 100,
// y2: Number
// The Y coordinate of the end of the virtual line along which the gradient is drawn, default value 100.
colors: [
{ offset: 0, color: "black" }, { offset: 1, color: "white" }
]
// colors: Array
// An array of colors at given offsets (from the start of the line). The start of the line is
// defined at offest 0 with the end of the line at offset 1.
// Default value, [{ offset: 0, color: 'black'},{offset: 1, color: 'white'}], is a gradient from black to white.
},
defaultRadialGradient: {
// summary:
// An object specifying the default properties for RadialGradients using in fills patterns.
type: "radial",
// type: String
// Specifies this is a RadialGradient, value 'radial'
cx: 0,
// cx: Number
// The X coordinate of the center of the radial gradient, default value 0.
cy: 0,
// cy: Number
// The Y coordinate of the center of the radial gradient, default value 0.
r: 100,
// r: Number
// The radius to the end of the radial gradient, default value 100.
colors: [
{ offset: 0, color: "black" }, { offset: 1, color: "white" }
]
// colors: Array
// An array of colors at given offsets (from the center of the radial gradient).
// The center is defined at offest 0 with the outer edge of the gradient at offset 1.
// Default value, [{ offset: 0, color: 'black'},{offset: 1, color: 'white'}], is a gradient from black to white.
},
defaultPattern: {
// summary:
// An object specifying the default properties for a Pattern using in fill operations.
type: "pattern",
// type: String
// Specifies this object is a Pattern, value 'pattern'.
x: 0,
// x: Number
// The X coordinate of the position of the pattern, default value is 0.
y: 0,
// y: Number
// The Y coordinate of the position of the pattern, default value is 0.
width: 0,
// width: Number
// The width of the pattern image, default value is 0.
height: 0,
// height: Number
// The height of the pattern image, default value is 0.
src: ""
// src: String
// A url specifing the image to use for the pattern.
},
defaultFont: {
// summary:
// An object specifying the default properties for a Font used in text operations.
type: "font",
// type: String
// Specifies this object is a Font, value 'font'.
style: "normal",
// style: String
// The font style, one of 'normal', 'bold', default value 'normal'.
variant: "normal",
// variant: String
// The font variant, one of 'normal', ... , default value 'normal'.
weight: "normal",
// weight: String
// The font weight, one of 'normal', ..., default value 'normal'.
size: "10pt",
// size: String
// The font size (including units), default value '10pt'.
family: "serif"
// family: String
// The font family, one of 'serif', 'sanserif', ..., default value 'serif'.
},
getDefault: (function(){
// summary:
// Returns a function used to access default memoized prototype objects (see them defined above).
var typeCtorCache = {};
// a memoized delegate()
return function(/*String*/ type){
var t = typeCtorCache[type];
if(t){
return new t();
}
t = typeCtorCache[type] = new Function();
t.prototype = g[ "default" + type ];
return new t();
}
})(),
normalizeColor: function(/*dojo.Color|Array|string|Object*/ color){
// summary:
// converts any legal color representation to normalized
// dojo.Color object
return (color instanceof Color) ? color : new Color(color); // dojo.Color
},
normalizeParameters: function(existed, update){
// summary:
// updates an existing object with properties from an 'update'
// object
// existed: Object
// the target object to be updated
// update: Object
// the 'update' object, whose properties will be used to update
// the existed object
var x;
if(update){
var empty = {};
for(x in existed){
if(x in update && !(x in empty)){
existed[x] = update[x];
}
}
}
return existed; // Object
},
makeParameters: function(defaults, update){
// summary:
// copies the original object, and all copied properties from the
// 'update' object
// defaults: Object
// the object to be cloned before updating
// update: Object
// the object, which properties are to be cloned during updating
var i = null;
if(!update){
// return dojo.clone(defaults);
return lang.delegate(defaults);
}
var result = {};
for(i in defaults){
if(!(i in result)){
result[i] = lang.clone((i in update) ? update[i] : defaults[i]);
}
}
return result; // Object
},
formatNumber: function(x, addSpace){
// summary: converts a number to a string using a fixed notation
// x: Number
// number to be converted
// addSpace: Boolean
// whether to add a space before a positive number
var val = x.toString();
if(val.indexOf("e") >= 0){
val = x.toFixed(4);
}else{
var point = val.indexOf(".");
if(point >= 0 && val.length - point > 5){
val = x.toFixed(4);
}
}
if(x < 0){
return val; // String
}
return addSpace ? " " + val : val; // String
},
// font operations
makeFontString: function(font){
// summary: converts a font object to a CSS font string
// font: Object: font object (see dojox.gfx.defaultFont)
return font.style + " " + font.variant + " " + font.weight + " " + font.size + " " + font.family; // Object
},
splitFontString: function(str){
// summary:
// converts a CSS font string to a font object
// description:
// Converts a CSS font string to a gfx font object. The CSS font
// string components should follow the W3C specified order
// (see http://www.w3.org/TR/CSS2/fonts.html#font-shorthand):
// style, variant, weight, size, optional line height (will be
// ignored), and family.
// str: String
// a CSS font string
var font = g.getDefault("Font");
var t = str.split(/\s+/);
do{
if(t.length < 5){ break; }
font.style = t[0];
font.variant = t[1];
font.weight = t[2];
var i = t[3].indexOf("/");
font.size = i < 0 ? t[3] : t[3].substring(0, i);
var j = 4;
if(i < 0){
if(t[4] == "/"){
j = 6;
}else if(t[4].charAt(0) == "/"){
j = 5;
}
}
if(j < t.length){
font.family = t.slice(j).join(" ");
}
}while(false);
return font; // Object
},
// length operations
cm_in_pt: 72 / 2.54,
// cm_in_pt: Number
// points per centimeter (constant)
mm_in_pt: 7.2 / 2.54,
// mm_in_pt: Number
// points per millimeter (constant)
px_in_pt: function(){
// summary: returns the current number of pixels per point.
return g._base._getCachedFontMeasurements()["12pt"] / 12; // Number
},
pt2px: function(len){
// summary: converts points to pixels
// len: Number
// a value in points
return len * g.px_in_pt(); // Number
},
px2pt: function(len){
// summary: converts pixels to points
// len: Number
// a value in pixels
return len / g.px_in_pt(); // Number
},
normalizedLength: function(len) {
// summary: converts any length value to pixels
// len: String
// a length, e.g., '12pc'
if(len.length === 0){ return 0; }
if(len.length > 2){
var px_in_pt = g.px_in_pt();
var val = parseFloat(len);
switch(len.slice(-2)){
case "px": return val;
case "pt": return val * px_in_pt;
case "in": return val * 72 * px_in_pt;
case "pc": return val * 12 * px_in_pt;
case "mm": return val * g.mm_in_pt * px_in_pt;
case "cm": return val * g.cm_in_pt * px_in_pt;
}
}
return parseFloat(len); // Number
},
pathVmlRegExp: /([A-Za-z]+)|(\d+(\.\d+)?)|(\.\d+)|(-\d+(\.\d+)?)|(-\.\d+)/g,
// pathVmlRegExp: RegExp
// a constant regular expression used to split a SVG/VML path into primitive components
pathSvgRegExp: /([A-Za-z])|(\d+(\.\d+)?)|(\.\d+)|(-\d+(\.\d+)?)|(-\.\d+)/g,
// pathVmlRegExp: RegExp
// a constant regular expression used to split a SVG/VML path into primitive components
equalSources: function(a /*Object*/, b /*Object*/){
// summary: compares event sources, returns true if they are equal
// a: first event source
// b: event source to compare against a
return a && b && a === b;
},
switchTo: function(renderer/*String|Object*/){
// summary: switch the graphics implementation to the specified renderer.
// renderer:
// Either the string name of a renderer (eg. 'canvas', 'svg, ...) or the renderer
// object to switch to.
var ns = typeof renderer == "string" ? g[renderer] : renderer;
if(ns){
arr.forEach(["Group", "Rect", "Ellipse", "Circle", "Line",
"Polyline", "Image", "Text", "Path", "TextPath",
"Surface", "createSurface", "fixTarget"], function(name){
g[name] = ns[name];
});
}
}
});
return g; // defaults object api
});
},
'dijit/focus':function(){
define("dijit/focus", [
"dojo/aspect",
"dojo/_base/declare", // declare
"dojo/dom", // domAttr.get dom.isDescendant
"dojo/dom-attr", // domAttr.get dom.isDescendant
"dojo/dom-construct", // connect to domConstruct.empty, domConstruct.destroy
"dojo/Evented",
"dojo/_base/lang", // lang.hitch
"dojo/on",
"dojo/ready",
"dojo/_base/sniff", // has("ie")
"dojo/Stateful",
"dojo/_base/unload", // unload.addOnWindowUnload
"dojo/_base/window", // win.body
"dojo/window", // winUtils.get
"./a11y", // a11y.isTabNavigable
"./registry", // registry.byId
"." // to set dijit.focus
], function(aspect, declare, dom, domAttr, domConstruct, Evented, lang, on, ready, has, Stateful, unload, win, winUtils,
a11y, registry, dijit){
// module:
// dijit/focus
// summary:
// Returns a singleton that tracks the currently focused node, and which widgets are currently "active".
/*=====
dijit.focus = {
// summary:
// Tracks the currently focused node, and which widgets are currently "active".
// Access via require(["dijit/focus"], function(focus){ ... }).
//
// A widget is considered active if it or a descendant widget has focus,
// or if a non-focusable node of this widget or a descendant was recently clicked.
//
// Call focus.watch("curNode", callback) to track the current focused DOMNode,
// or focus.watch("activeStack", callback) to track the currently focused stack of widgets.
//
// Call focus.on("widget-blur", func) or focus.on("widget-focus", ...) to monitor when
// when widgets become active/inactive
//
// Finally, focus(node) will focus a node, suppressing errors if the node doesn't exist.
// curNode: DomNode
// Currently focused item on screen
curNode: null,
// activeStack: dijit._Widget[]
// List of currently active widgets (focused widget and it's ancestors)
activeStack: [],
registerIframe: function(iframe){
// summary:
// Registers listeners on the specified iframe so that any click
// or focus event on that iframe (or anything in it) is reported
// as a focus/click event on the <iframe> itself.
// description:
// Currently only used by editor.
// returns:
// Handle with remove() method to deregister.
},
registerWin: function(targetWindow, effectiveNode){
// summary:
// Registers listeners on the specified window (either the main
// window or an iframe's window) to detect when the user has clicked somewhere
// or focused somewhere.
// description:
// Users should call registerIframe() instead of this method.
// targetWindow: Window?
// If specified this is the window associated with the iframe,
// i.e. iframe.contentWindow.
// effectiveNode: DOMNode?
// If specified, report any focus events inside targetWindow as
// an event on effectiveNode, rather than on evt.target.
// returns:
// Handle with remove() method to deregister.
}
};
=====*/
var FocusManager = declare([Stateful, Evented], {
// curNode: DomNode
// Currently focused item on screen
curNode: null,
// activeStack: dijit._Widget[]
// List of currently active widgets (focused widget and it's ancestors)
activeStack: [],
constructor: function(){
// Don't leave curNode/prevNode pointing to bogus elements
var check = lang.hitch(this, function(node){
if(dom.isDescendant(this.curNode, node)){
this.set("curNode", null);
}
if(dom.isDescendant(this.prevNode, node)){
this.set("prevNode", null);
}
});
aspect.before(domConstruct, "empty", check);
aspect.before(domConstruct, "destroy", check);
},
registerIframe: function(/*DomNode*/ iframe){
// summary:
// Registers listeners on the specified iframe so that any click
// or focus event on that iframe (or anything in it) is reported
// as a focus/click event on the <iframe> itself.
// description:
// Currently only used by editor.
// returns:
// Handle with remove() method to deregister.
return this.registerWin(iframe.contentWindow, iframe);
},
registerWin: function(/*Window?*/targetWindow, /*DomNode?*/ effectiveNode){
// summary:
// Registers listeners on the specified window (either the main
// window or an iframe's window) to detect when the user has clicked somewhere
// or focused somewhere.
// description:
// Users should call registerIframe() instead of this method.
// targetWindow:
// If specified this is the window associated with the iframe,
// i.e. iframe.contentWindow.
// effectiveNode:
// If specified, report any focus events inside targetWindow as
// an event on effectiveNode, rather than on evt.target.
// returns:
// Handle with remove() method to deregister.
// TODO: make this function private in 2.0; Editor/users should call registerIframe(),
var _this = this;
var mousedownListener = function(evt){
_this._justMouseDowned = true;
setTimeout(function(){ _this._justMouseDowned = false; }, 0);
// workaround weird IE bug where the click is on an orphaned node
// (first time clicking a Select/DropDownButton inside a TooltipDialog)
if(has("ie") && evt && evt.srcElement && evt.srcElement.parentNode == null){
return;
}
_this._onTouchNode(effectiveNode || evt.target || evt.srcElement, "mouse");
};
// Listen for blur and focus events on targetWindow's document.
// IIRC, I'm using attachEvent() rather than dojo.connect() because focus/blur events don't bubble
// through dojo.connect(), and also maybe to catch the focus events early, before onfocus handlers
// fire.
// Connect to <html> (rather than document) on IE to avoid memory leaks, but document on other browsers because
// (at least for FF) the focus event doesn't fire on <html> or <body>.
var doc = has("ie") ? targetWindow.document.documentElement : targetWindow.document;
if(doc){
if(has("ie")){
targetWindow.document.body.attachEvent('onmousedown', mousedownListener);
var activateListener = function(evt){
// IE reports that nodes like <body> have gotten focus, even though they have tabIndex=-1,
// ignore those events
var tag = evt.srcElement.tagName.toLowerCase();
if(tag == "#document" || tag == "body"){ return; }
// Previous code called _onTouchNode() for any activate event on a non-focusable node. Can
// probably just ignore such an event as it will be handled by onmousedown handler above, but
// leaving the code for now.
if(a11y.isTabNavigable(evt.srcElement)){
_this._onFocusNode(effectiveNode || evt.srcElement);
}else{
_this._onTouchNode(effectiveNode || evt.srcElement);
}
};
doc.attachEvent('onactivate', activateListener);
var deactivateListener = function(evt){
_this._onBlurNode(effectiveNode || evt.srcElement);
};
doc.attachEvent('ondeactivate', deactivateListener);
return {
remove: function(){
targetWindow.document.detachEvent('onmousedown', mousedownListener);
doc.detachEvent('onactivate', activateListener);
doc.detachEvent('ondeactivate', deactivateListener);
doc = null; // prevent memory leak (apparent circular reference via closure)
}
};
}else{
doc.body.addEventListener('mousedown', mousedownListener, true);
doc.body.addEventListener('touchstart', mousedownListener, true);
var focusListener = function(evt){
_this._onFocusNode(effectiveNode || evt.target);
};
doc.addEventListener('focus', focusListener, true);
var blurListener = function(evt){
_this._onBlurNode(effectiveNode || evt.target);
};
doc.addEventListener('blur', blurListener, true);
return {
remove: function(){
doc.body.removeEventListener('mousedown', mousedownListener, true);
doc.body.removeEventListener('touchstart', mousedownListener, true);
doc.removeEventListener('focus', focusListener, true);
doc.removeEventListener('blur', blurListener, true);
doc = null; // prevent memory leak (apparent circular reference via closure)
}
};
}
}
},
_onBlurNode: function(/*DomNode*/ /*===== node =====*/){
// summary:
// Called when focus leaves a node.
// Usually ignored, _unless_ it *isn't* followed by touching another node,
// which indicates that we tabbed off the last field on the page,
// in which case every widget is marked inactive
this.set("prevNode", this.curNode);
this.set("curNode", null);
if(this._justMouseDowned){
// the mouse down caused a new widget to be marked as active; this blur event
// is coming late, so ignore it.
return;
}
// if the blur event isn't followed by a focus event then mark all widgets as inactive.
if(this._clearActiveWidgetsTimer){
clearTimeout(this._clearActiveWidgetsTimer);
}
this._clearActiveWidgetsTimer = setTimeout(lang.hitch(this, function(){
delete this._clearActiveWidgetsTimer;
this._setStack([]);
this.prevNode = null;
}), 100);
},
_onTouchNode: function(/*DomNode*/ node, /*String*/ by){
// summary:
// Callback when node is focused or mouse-downed
// node:
// The node that was touched.
// by:
// "mouse" if the focus/touch was caused by a mouse down event
// ignore the recent blurNode event
if(this._clearActiveWidgetsTimer){
clearTimeout(this._clearActiveWidgetsTimer);
delete this._clearActiveWidgetsTimer;
}
// compute stack of active widgets (ex: ComboButton --> Menu --> MenuItem)
var newStack=[];
try{
while(node){
var popupParent = domAttr.get(node, "dijitPopupParent");
if(popupParent){
node=registry.byId(popupParent).domNode;
}else if(node.tagName && node.tagName.toLowerCase() == "body"){
// is this the root of the document or just the root of an iframe?
if(node === win.body()){
// node is the root of the main document
break;
}
// otherwise, find the iframe this node refers to (can't access it via parentNode,
// need to do this trick instead). window.frameElement is supported in IE/FF/Webkit
node=winUtils.get(node.ownerDocument).frameElement;
}else{
// if this node is the root node of a widget, then add widget id to stack,
// except ignore clicks on disabled widgets (actually focusing a disabled widget still works,
// to support MenuItem)
var id = node.getAttribute && node.getAttribute("widgetId"),
widget = id && registry.byId(id);
if(widget && !(by == "mouse" && widget.get("disabled"))){
newStack.unshift(id);
}
node=node.parentNode;
}
}
}catch(e){ /* squelch */ }
this._setStack(newStack, by);
},
_onFocusNode: function(/*DomNode*/ node){
// summary:
// Callback when node is focused
if(!node){
return;
}
if(node.nodeType == 9){
// Ignore focus events on the document itself. This is here so that
// (for example) clicking the up/down arrows of a spinner
// (which don't get focus) won't cause that widget to blur. (FF issue)
return;
}
this._onTouchNode(node);
if(node == this.curNode){ return; }
this.set("curNode", node);
},
_setStack: function(/*String[]*/ newStack, /*String*/ by){
// summary:
// The stack of active widgets has changed. Send out appropriate events and records new stack.
// newStack:
// array of widget id's, starting from the top (outermost) widget
// by:
// "mouse" if the focus/touch was caused by a mouse down event
var oldStack = this.activeStack;
this.set("activeStack", newStack);
// compare old stack to new stack to see how many elements they have in common
for(var nCommon=0; nCommon<Math.min(oldStack.length, newStack.length); nCommon++){
if(oldStack[nCommon] != newStack[nCommon]){
break;
}
}
var widget;
// for all elements that have gone out of focus, set focused=false
for(var i=oldStack.length-1; i>=nCommon; i--){
widget = registry.byId(oldStack[i]);
if(widget){
widget._hasBeenBlurred = true; // TODO: used by form widgets, should be moved there
widget.set("focused", false);
if(widget._focusManager == this){
widget._onBlur(by);
}
this.emit("widget-blur", widget, by);
}
}
// for all element that have come into focus, set focused=true
for(i=nCommon; i<newStack.length; i++){
widget = registry.byId(newStack[i]);
if(widget){
widget.set("focused", true);
if(widget._focusManager == this){
widget._onFocus(by);
}
this.emit("widget-focus", widget, by);
}
}
},
focus: function(node){
// summary:
// Focus the specified node, suppressing errors if they occur
if(node){
try{ node.focus(); }catch(e){/*quiet*/}
}
}
});
var singleton = new FocusManager();
// register top window and all the iframes it contains
ready(function(){
var handle = singleton.registerWin(win.doc.parentWindow || win.doc.defaultView);
if(has("ie")){
unload.addOnWindowUnload(function(){
handle.remove();
handle = null;
})
}
});
// Setup dijit.focus as a pointer to the singleton but also (for backwards compatibility)
// as a function to set focus.
dijit.focus = function(node){
singleton.focus(node); // indirection here allows dijit/_base/focus.js to override behavior
};
for(var attr in singleton){
if(!/^_/.test(attr)){
dijit.focus[attr] = typeof singleton[attr] == "function" ? lang.hitch(singleton, attr) : singleton[attr];
}
}
singleton.watch(function(attr, oldVal, newVal){
dijit.focus[attr] = newVal;
});
return singleton;
});
},
'dojox/charting/widget/Legend':function(){
define("dojox/charting/widget/Legend", ["dojo/_base/lang", "dojo/_base/html", "dojo/_base/declare", "dijit/_Widget", "dojox/gfx","dojo/_base/array",
"dojox/lang/functional", "dojox/lang/functional/array", "dojox/lang/functional/fold",
"dojo/dom", "dojo/dom-construct", "dojo/dom-class","dijit/_base/manager"],
function(lang, html, declare, Widget, gfx, arrayUtil, df, dfa, dff,
dom, domFactory, domClass, widgetManager){
/*=====
var Widget = dijit._Widget;
=====*/
var REVERSED_SERIES = /\.(StackedColumns|StackedAreas|ClusteredBars)$/;
return declare("dojox.charting.widget.Legend", Widget, {
// summary: A legend for a chart. A legend contains summary labels for
// each series of data contained in the chart.
//
// Set the horizontal attribute to boolean false to layout legend labels vertically.
// Set the horizontal attribute to a number to layout legend labels in horizontal
// rows each containing that number of labels (except possibly the last row).
//
// (Line or Scatter charts (colored lines with shape symbols) )
// -o- Series1 -X- Series2 -v- Series3
//
// (Area/Bar/Pie charts (letters represent colors))
// [a] Series1 [b] Series2 [c] Series3
chartRef: "",
horizontal: true,
swatchSize: 18,
legendBody: null,
postCreate: function(){
if(!this.chart){
if(!this.chartRef){ return; }
this.chart = widgetManager.byId(this.chartRef);
if(!this.chart){
var node = dom.byId(this.chartRef);
if(node){
this.chart = widgetManager.byNode(node);
}else{
console.log("Could not find chart instance with id: " + this.chartRef);
return;
}
}
this.series = this.chart.chart.series;
}else{
this.series = this.chart.series;
}
this.refresh();
},
buildRendering: function(){
this.domNode = domFactory.create("table",
{role: "group", "aria-label": "chart legend", "class": "dojoxLegendNode"});
this.legendBody = domFactory.create("tbody", null, this.domNode);
this.inherited(arguments);
},
refresh: function(){
// summary: regenerates the legend to reflect changes to the chart
// cleanup
if(this._surfaces){
arrayUtil.forEach(this._surfaces, function(surface){
surface.destroy();
});
}
this._surfaces = [];
while(this.legendBody.lastChild){
domFactory.destroy(this.legendBody.lastChild);
}
if(this.horizontal){
domClass.add(this.domNode, "dojoxLegendHorizontal");
// make a container <tr>
this._tr = domFactory.create("tr", null, this.legendBody);
this._inrow = 0;
}
var s = this.series;
if(s.length == 0){
return;
}
if(s[0].chart.stack[0].declaredClass == "dojox.charting.plot2d.Pie"){
var t = s[0].chart.stack[0];
if(typeof t.run.data[0] == "number"){
var filteredRun = df.map(t.run.data, "Math.max(x, 0)");
if(df.every(filteredRun, "<= 0")){
return;
}
var slices = df.map(filteredRun, "/this", df.foldl(filteredRun, "+", 0));
arrayUtil.forEach(slices, function(x, i){
this._addLabel(t.dyn[i], t._getLabel(x * 100) + "%");
}, this);
}else{
arrayUtil.forEach(t.run.data, function(x, i){
this._addLabel(t.dyn[i], x.legend || x.text || x.y);
}, this);
}
}else{
if(this._isReversal()){
s = s.slice(0).reverse();
}
arrayUtil.forEach(s, function(x){
this._addLabel(x.dyn, x.legend || x.name);
}, this);
}
},
_addLabel: function(dyn, label){
// create necessary elements
var wrapper = domFactory.create("td"),
icon = domFactory.create("div", null, wrapper),
text = domFactory.create("label", null, wrapper),
div = domFactory.create("div", {
style: {
"width": this.swatchSize + "px",
"height":this.swatchSize + "px",
"float": "left"
}
}, icon);
domClass.add(icon, "dojoxLegendIcon dijitInline");
domClass.add(text, "dojoxLegendText");
// create a skeleton
if(this._tr){
// horizontal
this._tr.appendChild(wrapper);
if(++this._inrow === this.horizontal){
// make a fresh container <tr>
this._tr = domFactory.create("tr", null, this.legendBody);
this._inrow = 0;
}
}else{
// vertical
var tr = domFactory.create("tr", null, this.legendBody);
tr.appendChild(wrapper);
}
// populate the skeleton
this._makeIcon(div, dyn);
text.innerHTML = String(label);
text.dir = this.getTextDir(label, text.dir);
},
_makeIcon: function(div, dyn){
var mb = { h: this.swatchSize, w: this.swatchSize };
var surface = gfx.createSurface(div, mb.w, mb.h);
this._surfaces.push(surface);
if(dyn.fill){
// regions
surface.createRect({x: 2, y: 2, width: mb.w - 4, height: mb.h - 4}).
setFill(dyn.fill).setStroke(dyn.stroke);
}else if(dyn.stroke || dyn.marker){
// draw line
var line = {x1: 0, y1: mb.h / 2, x2: mb.w, y2: mb.h / 2};
if(dyn.stroke){
surface.createLine(line).setStroke(dyn.stroke);
}
if(dyn.marker){
// draw marker on top
var c = {x: mb.w / 2, y: mb.h / 2};
if(dyn.stroke){
surface.createPath({path: "M" + c.x + " " + c.y + " " + dyn.marker}).
setFill(dyn.stroke.color).setStroke(dyn.stroke);
}else{
surface.createPath({path: "M" + c.x + " " + c.y + " " + dyn.marker}).
setFill(dyn.color).setStroke(dyn.color);
}
}
}else{
// nothing
surface.createRect({x: 2, y: 2, width: mb.w - 4, height: mb.h - 4}).
setStroke("black");
surface.createLine({x1: 2, y1: 2, x2: mb.w - 2, y2: mb.h - 2}).setStroke("black");
surface.createLine({x1: 2, y1: mb.h - 2, x2: mb.w - 2, y2: 2}).setStroke("black");
}
},
_isReversal: function(){
return (!this.horizontal) && arrayUtil.some(this.chart.stack, function(item){
return REVERSED_SERIES.test(item.declaredClass);
});
}
});
});
},
'dojox/charting/plot2d/StackedLines':function(){
define("dojox/charting/plot2d/StackedLines", ["dojo/_base/declare", "./Stacked"], function(declare, Stacked){
/*=====
var Stacked = dojox.charting.plot2d.Stacked;
=====*/
return declare("dojox.charting.plot2d.StackedLines", Stacked, {
// summary:
// A convenience object to create a stacked line chart.
constructor: function(){
// summary:
// Force our Stacked base to be lines only.
this.opt.lines = true;
}
});
});
},
'dojox/charting/plot2d/StackedColumns':function(){
define("dojox/charting/plot2d/StackedColumns", ["dojo/_base/lang", "dojo/_base/array", "dojo/_base/declare", "./Columns", "./common",
"dojox/lang/functional", "dojox/lang/functional/reversed", "dojox/lang/functional/sequence"],
function(lang, arr, declare, Columns, dc, df, dfr, dfs){
var purgeGroup = dfr.lambda("item.purgeGroup()");
/*=====
var Columns = dojox.charting.plot2d.Columns;
=====*/
return declare("dojox.charting.plot2d.StackedColumns", Columns, {
// summary:
// The plot object representing a stacked column chart (vertical bars).
getSeriesStats: function(){
// summary:
// Calculate the min/max on all attached series in both directions.
// returns: Object
// {hmin, hmax, vmin, vmax} min/max in both directions.
var stats = dc.collectStackedStats(this.series);
this._maxRunLength = stats.hmax;
stats.hmin -= 0.5;
stats.hmax += 0.5;
return stats;
},
render: function(dim, offsets){
// summary:
// Run the calculations for any axes for this plot.
// dim: Object
// An object in the form of { width, height }
// offsets: Object
// An object of the form { l, r, t, b}.
// returns: dojox.charting.plot2d.StackedColumns
// A reference to this plot for functional chaining.
if(this._maxRunLength <= 0){
return this;
}
// stack all values
var acc = df.repeat(this._maxRunLength, "-> 0", 0);
for(var i = 0; i < this.series.length; ++i){
var run = this.series[i];
for(var j = 0; j < run.data.length; ++j){
var value = run.data[j];
if(value !== null){
var v = typeof value == "number" ? value : value.y;
if(isNaN(v)){ v = 0; }
acc[j] += v;
}
}
}
// draw runs in backwards
if(this.zoom && !this.isDataDirty()){
return this.performZoom(dim, offsets);
}
this.resetEvents();
this.dirty = this.isDirty();
if(this.dirty){
arr.forEach(this.series, purgeGroup);
this._eventSeries = {};
this.cleanGroup();
var s = this.group;
df.forEachRev(this.series, function(item){ item.cleanGroup(s); });
}
var t = this.chart.theme, f, gap, width,
ht = this._hScaler.scaler.getTransformerFromModel(this._hScaler),
vt = this._vScaler.scaler.getTransformerFromModel(this._vScaler),
events = this.events();
f = dc.calculateBarSize(this._hScaler.bounds.scale, this.opt);
gap = f.gap;
width = f.size;
for(var i = this.series.length - 1; i >= 0; --i){
var run = this.series[i];
if(!this.dirty && !run.dirty){
t.skip();
this._reconnectEvents(run.name);
continue;
}
run.cleanGroup();
var theme = t.next("column", [this.opt, run]), s = run.group,
eventSeries = new Array(acc.length);
for(var j = 0; j < acc.length; ++j){
var value = run.data[j];
if(value !== null){
var v = acc[j],
height = vt(v),
finalTheme = typeof value != "number" ?
t.addMixin(theme, "column", value, true) :
t.post(theme, "column");
if(width >= 1 && height >= 0){
var rect = {
x: offsets.l + ht(j + 0.5) + gap,
y: dim.height - offsets.b - vt(v),
width: width, height: height
};
var specialFill = this._plotFill(finalTheme.series.fill, dim, offsets);
specialFill = this._shapeFill(specialFill, rect);
var shape = s.createRect(rect).setFill(specialFill).setStroke(finalTheme.series.stroke);
run.dyn.fill = shape.getFill();
run.dyn.stroke = shape.getStroke();
if(events){
var o = {
element: "column",
index: j,
run: run,
shape: shape,
x: j + 0.5,
y: v
};
this._connectEvents(o);
eventSeries[j] = o;
}
if(this.animate){
this._animateColumn(shape, dim.height - offsets.b, height);
}
}
}
}
this._eventSeries[run.name] = eventSeries;
run.dirty = false;
// update the accumulator
for(var j = 0; j < run.data.length; ++j){
var value = run.data[j];
if(value !== null){
var v = typeof value == "number" ? value : value.y;
if(isNaN(v)){ v = 0; }
acc[j] -= v;
}
}
}
this.dirty = false;
return this; // dojox.charting.plot2d.StackedColumns
}
});
});
},
'dojox/charting/Series':function(){
define(["dojo/_base/lang", "dojo/_base/declare", "./Element"],
function(lang, declare, Element){
/*=====
dojox.charting.__SeriesCtorArgs = function(plot){
// summary:
// An optional arguments object that can be used in the Series constructor.
// plot: String?
// The plot (by name) that this series belongs to.
this.plot = plot;
}
var Element = dojox.charting.Element;
=====*/
return declare("dojox.charting.Series", Element, {
// summary:
// An object representing a series of data for plotting on a chart.
constructor: function(chart, data, kwArgs){
// summary:
// Create a new data series object for use within charting.
// chart: dojox.charting.Chart
// The chart that this series belongs to.
// data: Array|Object:
// The array of data points (either numbers or objects) that
// represents the data to be drawn. Or it can be an object. In
// the latter case, it should have a property "data" (an array),
// destroy(), and setSeriesObject().
// kwArgs: dojox.charting.__SeriesCtorArgs?
// An optional keyword arguments object to set details for this series.
lang.mixin(this, kwArgs);
if(typeof this.plot != "string"){ this.plot = "default"; }
this.update(data);
},
clear: function(){
// summary:
// Clear the calculated additional parameters set on this series.
this.dyn = {};
},
update: function(data){
// summary:
// Set data and make this object dirty, so it can be redrawn.
// data: Array|Object:
// The array of data points (either numbers or objects) that
// represents the data to be drawn. Or it can be an object. In
// the latter case, it should have a property "data" (an array),
// destroy(), and setSeriesObject().
if(lang.isArray(data)){
this.data = data;
}else{
this.source = data;
this.data = this.source.data;
if(this.source.setSeriesObject){
this.source.setSeriesObject(this);
}
}
this.dirty = true;
this.clear();
}
});
});
},
'dojox/charting/plot2d/Default':function(){
define("dojox/charting/plot2d/Default", ["dojo/_base/lang", "dojo/_base/declare", "dojo/_base/array",
"./Base", "./common", "dojox/lang/functional", "dojox/lang/functional/reversed", "dojox/lang/utils", "dojox/gfx/fx"],
function(lang, declare, arr, Base, dc, df, dfr, du, fx){
/*=====
dojo.declare("dojox.charting.plot2d.__DefaultCtorArgs", dojox.charting.plot2d.__PlotCtorArgs, {
// summary:
// The arguments used for any/most plots.
// hAxis: String?
// The horizontal axis name.
hAxis: "x",
// vAxis: String?
// The vertical axis name
vAxis: "y",
// lines: Boolean?
// Whether or not to draw lines on this plot. Defaults to true.
lines: true,
// areas: Boolean?
// Whether or not to draw areas on this plot. Defaults to false.
areas: false,
// markers: Boolean?
// Whether or not to draw markers at data points on this plot. Default is false.
markers: false,
// tension: Number|String?
// Whether or not to apply 'tensioning' to the lines on this chart.
// Options include a number, "X", "x", or "S"; if a number is used, the
// simpler bezier curve calculations are used to draw the lines. If X, x or S
// is used, the more accurate smoothing algorithm is used.
tension: "",
// animate: Boolean?
// Whether or not to animate the chart to place.
animate: false,
// stroke: dojox.gfx.Stroke?
// An optional stroke to use for any series on the plot.
stroke: {},
// outline: dojox.gfx.Stroke?
// An optional stroke used to outline any series on the plot.
outline: {},
// shadow: dojox.gfx.Stroke?
// An optional stroke to use to draw any shadows for a series on a plot.
shadow: {},
// fill: dojox.gfx.Fill?
// Any fill to be used for elements on the plot (such as areas).
fill: {},
// font: String?
// A font definition to be used for labels and other text-based elements on the plot.
font: "",
// fontColor: String|dojo.Color?
// The color to be used for any text-based elements on the plot.
fontColor: "",
// markerStroke: dojo.gfx.Stroke?
// An optional stroke to use for any markers on the plot.
markerStroke: {},
// markerOutline: dojo.gfx.Stroke?
// An optional outline to use for any markers on the plot.
markerOutline: {},
// markerShadow: dojo.gfx.Stroke?
// An optional shadow to use for any markers on the plot.
markerShadow: {},
// markerFill: dojo.gfx.Fill?
// An optional fill to use for any markers on the plot.
markerFill: {},
// markerFont: String?
// An optional font definition to use for any markers on the plot.
markerFont: "",
// markerFontColor: String|dojo.Color?
// An optional color to use for any marker text on the plot.
markerFontColor: "",
// enableCache: Boolean?
// Whether the markers are cached from one rendering to another. This improves the rendering performance of
// successive rendering but penalize the first rendering. Default false.
enableCache: false
});
var Base = dojox.charting.plot2d.Base;
=====*/
var purgeGroup = dfr.lambda("item.purgeGroup()");
var DEFAULT_ANIMATION_LENGTH = 1200; // in ms
return declare("dojox.charting.plot2d.Default", Base, {
defaultParams: {
hAxis: "x", // use a horizontal axis named "x"
vAxis: "y", // use a vertical axis named "y"
lines: true, // draw lines
areas: false, // draw areas
markers: false, // draw markers
tension: "", // draw curved lines (tension is "X", "x", or "S")
animate: false, // animate chart to place
enableCache: false
},
optionalParams: {
// theme component
stroke: {},
outline: {},
shadow: {},
fill: {},
font: "",
fontColor: "",
markerStroke: {},
markerOutline: {},
markerShadow: {},
markerFill: {},
markerFont: "",
markerFontColor: ""
},
constructor: function(chart, kwArgs){
// summary:
// Return a new plot.
// chart: dojox.charting.Chart
// The chart this plot belongs to.
// kwArgs: dojox.charting.plot2d.__DefaultCtorArgs?
// An optional arguments object to help define this plot.
this.opt = lang.clone(this.defaultParams);
du.updateWithObject(this.opt, kwArgs);
du.updateWithPattern(this.opt, kwArgs, this.optionalParams);
this.series = [];
this.hAxis = this.opt.hAxis;
this.vAxis = this.opt.vAxis;
// animation properties
this.animate = this.opt.animate;
},
createPath: function(run, creator, params){
var path;
if(this.opt.enableCache && run._pathFreePool.length > 0){
path = run._pathFreePool.pop();
path.setShape(params);
// was cleared, add it back
creator.add(path);
}else{
path = creator.createPath(params);
}
if(this.opt.enableCache){
run._pathUsePool.push(path);
}
return path;
},
render: function(dim, offsets){
// summary:
// Render/draw everything on this plot.
// dim: Object
// An object of the form { width, height }
// offsets: Object
// An object of the form { l, r, t, b }
// returns: dojox.charting.plot2d.Default
// A reference to this plot for functional chaining.
// make sure all the series is not modified
if(this.zoom && !this.isDataDirty()){
return this.performZoom(dim, offsets);
}
this.resetEvents();
this.dirty = this.isDirty();
if(this.dirty){
arr.forEach(this.series, purgeGroup);
this._eventSeries = {};
this.cleanGroup();
this.group.setTransform(null);
var s = this.group;
df.forEachRev(this.series, function(item){ item.cleanGroup(s); });
}
var t = this.chart.theme, stroke, outline, marker, events = this.events();
for(var i = this.series.length - 1; i >= 0; --i){
var run = this.series[i];
if(!this.dirty && !run.dirty){
t.skip();
this._reconnectEvents(run.name);
continue;
}
run.cleanGroup();
if(this.opt.enableCache){
run._pathFreePool = (run._pathFreePool?run._pathFreePool:[]).concat(run._pathUsePool?run._pathUsePool:[]);
run._pathUsePool = [];
}
if(!run.data.length){
run.dirty = false;
t.skip();
continue;
}
var theme = t.next(this.opt.areas ? "area" : "line", [this.opt, run], true),
s = run.group, rsegments = [], startindexes = [], rseg = null, lpoly,
ht = this._hScaler.scaler.getTransformerFromModel(this._hScaler),
vt = this._vScaler.scaler.getTransformerFromModel(this._vScaler),
eventSeries = this._eventSeries[run.name] = new Array(run.data.length);
// optim works only for index based case
var indexed = typeof run.data[0] == "number";
var min = indexed?Math.max(0, Math.floor(this._hScaler.bounds.from - 1)):0,
max = indexed?Math.min(run.data.length, Math.ceil(this._hScaler.bounds.to)):run.data.length;
// split the run data into dense segments (each containing no nulls)
for(var j = min; j < max; j++){
if(run.data[j] != null){
if(!rseg){
rseg = [];
startindexes.push(j);
rsegments.push(rseg);
}
rseg.push(run.data[j]);
}else{
rseg = null;
}
}
for(var seg = 0; seg < rsegments.length; seg++){
if(typeof rsegments[seg][0] == "number"){
lpoly = arr.map(rsegments[seg], function(v, i){
return {
x: ht(i + startindexes[seg] + 1) + offsets.l,
y: dim.height - offsets.b - vt(v)
};
}, this);
}else{
lpoly = arr.map(rsegments[seg], function(v, i){
return {
x: ht(v.x) + offsets.l,
y: dim.height - offsets.b - vt(v.y)
};
}, this);
}
var lpath = this.opt.tension ? dc.curve(lpoly, this.opt.tension) : "";
if(this.opt.areas && lpoly.length > 1){
var fill = theme.series.fill;
var apoly = lang.clone(lpoly);
if(this.opt.tension){
var apath = "L" + apoly[apoly.length-1].x + "," + (dim.height - offsets.b) +
" L" + apoly[0].x + "," + (dim.height - offsets.b) +
" L" + apoly[0].x + "," + apoly[0].y;
run.dyn.fill = s.createPath(lpath + " " + apath).setFill(fill).getFill();
} else {
apoly.push({x: lpoly[lpoly.length - 1].x, y: dim.height - offsets.b});
apoly.push({x: lpoly[0].x, y: dim.height - offsets.b});
apoly.push(lpoly[0]);
run.dyn.fill = s.createPolyline(apoly).setFill(fill).getFill();
}
}
if(this.opt.lines || this.opt.markers){
// need a stroke
stroke = theme.series.stroke;
if(theme.series.outline){
outline = run.dyn.outline = dc.makeStroke(theme.series.outline);
outline.width = 2 * outline.width + stroke.width;
}
}
if(this.opt.markers){
run.dyn.marker = theme.symbol;
}
var frontMarkers = null, outlineMarkers = null, shadowMarkers = null;
if(stroke && theme.series.shadow && lpoly.length > 1){
var shadow = theme.series.shadow,
spoly = arr.map(lpoly, function(c){
return {x: c.x + shadow.dx, y: c.y + shadow.dy};
});
if(this.opt.lines){
if(this.opt.tension){
run.dyn.shadow = s.createPath(dc.curve(spoly, this.opt.tension)).setStroke(shadow).getStroke();
} else {
run.dyn.shadow = s.createPolyline(spoly).setStroke(shadow).getStroke();
}
}
if(this.opt.markers && theme.marker.shadow){
shadow = theme.marker.shadow;
shadowMarkers = arr.map(spoly, function(c){
return this.createPath(run, s, "M" + c.x + " " + c.y + " " + theme.symbol).
setStroke(shadow).setFill(shadow.color);
}, this);
}
}
if(this.opt.lines && lpoly.length > 1){
if(outline){
if(this.opt.tension){
run.dyn.outline = s.createPath(lpath).setStroke(outline).getStroke();
} else {
run.dyn.outline = s.createPolyline(lpoly).setStroke(outline).getStroke();
}
}
if(this.opt.tension){
run.dyn.stroke = s.createPath(lpath).setStroke(stroke).getStroke();
} else {
run.dyn.stroke = s.createPolyline(lpoly).setStroke(stroke).getStroke();
}
}
if(this.opt.markers){
frontMarkers = new Array(lpoly.length);
outlineMarkers = new Array(lpoly.length);
outline = null;
if(theme.marker.outline){
outline = dc.makeStroke(theme.marker.outline);
outline.width = 2 * outline.width + (theme.marker.stroke ? theme.marker.stroke.width : 0);
}
arr.forEach(lpoly, function(c, i){
var path = "M" + c.x + " " + c.y + " " + theme.symbol;
if(outline){
outlineMarkers[i] = this.createPath(run, s, path).setStroke(outline);
}
frontMarkers[i] = this.createPath(run, s, path).setStroke(theme.marker.stroke).setFill(theme.marker.fill);
}, this);
run.dyn.markerFill = theme.marker.fill;
run.dyn.markerStroke = theme.marker.stroke;
if(events){
arr.forEach(frontMarkers, function(s, i){
var o = {
element: "marker",
index: i + startindexes[seg],
run: run,
shape: s,
outline: outlineMarkers[i] || null,
shadow: shadowMarkers && shadowMarkers[i] || null,
cx: lpoly[i].x,
cy: lpoly[i].y
};
if(typeof rsegments[seg][0] == "number"){
o.x = i + startindexes[seg] + 1;
o.y = rsegments[seg][i];
}else{
o.x = rsegments[seg][i].x;
o.y = rsegments[seg][i].y;
}
this._connectEvents(o);
eventSeries[i + startindexes[seg]] = o;
}, this);
}else{
delete this._eventSeries[run.name];
}
}
}
run.dirty = false;
}
if(this.animate){
// grow from the bottom
var plotGroup = this.group;
fx.animateTransform(lang.delegate({
shape: plotGroup,
duration: DEFAULT_ANIMATION_LENGTH,
transform:[
{name:"translate", start: [0, dim.height - offsets.b], end: [0, 0]},
{name:"scale", start: [1, 0], end:[1, 1]},
{name:"original"}
]
}, this.animate)).play();
}
this.dirty = false;
return this; // dojox.charting.plot2d.Default
}
});
});
},
'dijit/main':function(){
define("dijit/main", [
"dojo/_base/kernel"
], function(dojo){
// module:
// dijit
// summary:
// The dijit package main module
return dojo.dijit;
});
},
'dojox/charting/plot2d/Base':function(){
define("dojox/charting/plot2d/Base", ["dojo/_base/lang", "dojo/_base/declare", "dojo/_base/connect",
"../Element", "./_PlotEvents", "dojo/_base/array",
"../scaler/primitive", "./common", "dojox/gfx/fx"],
function(lang, declare, hub, Element, PlotEvents, arr, primitive, common, fx){
/*=====
var Element = dojox.charting.Element;
var PlotEvents = dojox.charting.plot2d._PlotEvents;
dojox.charting.plot2d.__PlotCtorArgs = function(){
// summary:
// The base keyword arguments object for plot constructors.
// Note that the parameters for this may change based on the
// specific plot type (see the corresponding plot type for
// details).
}
=====*/
return declare("dojox.charting.plot2d.Base", [Element, PlotEvents], {
constructor: function(chart, kwArgs){
// summary:
// Create a base plot for charting.
// chart: dojox.chart.Chart
// The chart this plot belongs to.
// kwArgs: dojox.charting.plot2d.__PlotCtorArgs?
// An optional arguments object to help define the plot.
this.zoom = null,
this.zoomQueue = []; // zooming action task queue
this.lastWindow = {vscale: 1, hscale: 1, xoffset: 0, yoffset: 0};
},
clear: function(){
// summary:
// Clear out all of the information tied to this plot.
// returns: dojox.charting.plot2d.Base
// A reference to this plot for functional chaining.
this.series = [];
this._hAxis = null;
this._vAxis = null;
this.dirty = true;
return this; // dojox.charting.plot2d.Base
},
setAxis: function(axis){
// summary:
// Set an axis for this plot.
// axis: dojox.charting.axis2d.Base
// The axis to set.
// returns: dojox.charting.plot2d.Base
// A reference to this plot for functional chaining.
if(axis){
this[axis.vertical ? "_vAxis" : "_hAxis"] = axis;
}
return this; // dojox.charting.plot2d.Base
},
toPage: function(coord){
// summary:
// Compute page coordinates from plot axis data coordinates.
// coord: Object?
// The coordinates in plot axis data coordinate space. For cartesian charts that is of the following form:
// `{ hAxisName: 50, vAxisName: 200 }`
// If not provided return the tranform method instead of the result of the transformation.
// returns: Object
// The resulting page pixel coordinates. That is of the following form:
// `{ x: 50, y: 200 }`
var ah = this._hAxis, av = this._vAxis,
sh = ah.getScaler(), sv = av.getScaler(),
th = sh.scaler.getTransformerFromModel(sh),
tv = sv.scaler.getTransformerFromModel(sv),
c = this.chart.getCoords(),
o = this.chart.offsets, dim = this.chart.dim;
var t = function(coord){
var r = {};
r.x = th(coord[ah.name]) + c.x + o.l;
r.y = c.y + dim.height - o.b - tv(coord[av.name]);
return r;
};
// if no coord return the function so that we can capture the current transforms
// and reuse them later on
return coord?t(coord):t;
},
toData: function(coord){
// summary:
// Compute plot axis data coordinates from page coordinates.
// coord: Object
// The pixel coordinate in page coordinate space. That is of the following form:
// `{ x: 50, y: 200 }`
// If not provided return the tranform method instead of the result of the transformation.
// returns: Object
// The resulting plot axis data coordinates. For cartesian charts that is of the following form:
// `{ hAxisName: 50, vAxisName: 200 }`
var ah = this._hAxis, av = this._vAxis,
sh = ah.getScaler(), sv = av.getScaler(),
th = sh.scaler.getTransformerFromPlot(sh),
tv = sv.scaler.getTransformerFromPlot(sv),
c = this.chart.getCoords(),
o = this.chart.offsets, dim = this.chart.dim;
var t = function(coord){
var r = {};
r[ah.name] = th(coord.x - c.x - o.l);
r[av.name] = tv(c.y + dim.height - coord.y - o.b);
return r;
};
// if no coord return the function so that we can capture the current transforms
// and reuse them later on
return coord?t(coord):t;
},
addSeries: function(run){
// summary:
// Add a data series to this plot.
// run: dojox.charting.Series
// The series to be added.
// returns: dojox.charting.plot2d.Base
// A reference to this plot for functional chaining.
this.series.push(run);
return this; // dojox.charting.plot2d.Base
},
getSeriesStats: function(){
// summary:
// Calculate the min/max on all attached series in both directions.
// returns: Object
// {hmin, hmax, vmin, vmax} min/max in both directions.
return common.collectSimpleStats(this.series);
},
calculateAxes: function(dim){
// summary:
// Stub function for running the axis calculations (depricated).
// dim: Object
// An object of the form { width, height }
// returns: dojox.charting.plot2d.Base
// A reference to this plot for functional chaining.
this.initializeScalers(dim, this.getSeriesStats());
return this; // dojox.charting.plot2d.Base
},
isDirty: function(){
// summary:
// Returns whether or not this plot needs to be rendered.
// returns: Boolean
// The state of the plot.
return this.dirty || this._hAxis && this._hAxis.dirty || this._vAxis && this._vAxis.dirty; // Boolean
},
isDataDirty: function(){
// summary:
// Returns whether or not any of this plot's data series need to be rendered.
// returns: Boolean
// Flag indicating if any of this plot's series are invalid and need rendering.
return arr.some(this.series, function(item){ return item.dirty; }); // Boolean
},
performZoom: function(dim, offsets){
// summary:
// Create/alter any zooming windows on this plot.
// dim: Object
// An object of the form { width, height }.
// offsets: Object
// An object of the form { l, r, t, b }.
// returns: dojox.charting.plot2d.Base
// A reference to this plot for functional chaining.
// get current zooming various
var vs = this._vAxis.scale || 1,
hs = this._hAxis.scale || 1,
vOffset = dim.height - offsets.b,
hBounds = this._hScaler.bounds,
xOffset = (hBounds.from - hBounds.lower) * hBounds.scale,
vBounds = this._vScaler.bounds,
yOffset = (vBounds.from - vBounds.lower) * vBounds.scale,
// get incremental zooming various
rVScale = vs / this.lastWindow.vscale,
rHScale = hs / this.lastWindow.hscale,
rXOffset = (this.lastWindow.xoffset - xOffset)/
((this.lastWindow.hscale == 1)? hs : this.lastWindow.hscale),
rYOffset = (yOffset - this.lastWindow.yoffset)/
((this.lastWindow.vscale == 1)? vs : this.lastWindow.vscale),
shape = this.group,
anim = fx.animateTransform(lang.delegate({
shape: shape,
duration: 1200,
transform:[
{name:"translate", start:[0, 0], end: [offsets.l * (1 - rHScale), vOffset * (1 - rVScale)]},
{name:"scale", start:[1, 1], end: [rHScale, rVScale]},
{name:"original"},
{name:"translate", start: [0, 0], end: [rXOffset, rYOffset]}
]}, this.zoom));
lang.mixin(this.lastWindow, {vscale: vs, hscale: hs, xoffset: xOffset, yoffset: yOffset});
//add anim to zooming action queue,
//in order to avoid several zooming action happened at the same time
this.zoomQueue.push(anim);
//perform each anim one by one in zoomQueue
hub.connect(anim, "onEnd", this, function(){
this.zoom = null;
this.zoomQueue.shift();
if(this.zoomQueue.length > 0){
this.zoomQueue[0].play();
}
});
if(this.zoomQueue.length == 1){
this.zoomQueue[0].play();
}
return this; // dojox.charting.plot2d.Base
},
render: function(dim, offsets){
// summary:
// Render the plot on the chart.
// dim: Object
// An object of the form { width, height }.
// offsets: Object
// An object of the form { l, r, t, b }.
// returns: dojox.charting.plot2d.Base
// A reference to this plot for functional chaining.
return this; // dojox.charting.plot2d.Base
},
getRequiredColors: function(){
// summary:
// Get how many data series we have, so we know how many colors to use.
// returns: Number
// The number of colors needed.
return this.series.length; // Number
},
initializeScalers: function(dim, stats){
// summary:
// Initializes scalers using attached axes.
// dim: Object:
// Size of a plot area in pixels as {width, height}.
// stats: Object:
// Min/max of data in both directions as {hmin, hmax, vmin, vmax}.
// returns: dojox.charting.plot2d.Base
// A reference to this plot for functional chaining.
if(this._hAxis){
if(!this._hAxis.initialized()){
this._hAxis.calculate(stats.hmin, stats.hmax, dim.width);
}
this._hScaler = this._hAxis.getScaler();
}else{
this._hScaler = primitive.buildScaler(stats.hmin, stats.hmax, dim.width);
}
if(this._vAxis){
if(!this._vAxis.initialized()){
this._vAxis.calculate(stats.vmin, stats.vmax, dim.height);
}
this._vScaler = this._vAxis.getScaler();
}else{
this._vScaler = primitive.buildScaler(stats.vmin, stats.vmax, dim.height);
}
return this; // dojox.charting.plot2d.Base
}
});
});
},
'dojox/charting/action2d/Tooltip':function(){
define("dojox/charting/action2d/Tooltip", ["dojo/_base/kernel", "dijit/Tooltip","dojo/_base/lang", "dojo/_base/html", "dojo/_base/declare", "./PlotAction",
"dojox/gfx/matrix", "dojox/lang/functional", "dojox/lang/functional/scan", "dojox/lang/functional/fold"],
function(dojo, Tooltip, lang, html, declare, PlotAction, m, df, dfs, dff){
/*=====
dojo.declare("dojox.charting.action2d.__TooltipCtorArgs", dojox.charting.action2d.__PlotActionCtorArgs, {
// summary:
// Additional arguments for tooltip actions.
// text: Function?
// The function that produces the text to be shown within a tooltip. By default this will be
// set by the plot in question, by returning the value of the element.
text: null
});
var PlotAction = dojox.charting.action2d.PlotAction;
=====*/
var DEFAULT_TEXT = function(o){
var t = o.run && o.run.data && o.run.data[o.index];
if(t && typeof t != "number" && (t.tooltip || t.text)){
return t.tooltip || t.text;
}
if(o.element == "candlestick"){
return '<table cellpadding="1" cellspacing="0" border="0" style="font-size:0.9em;">'
+ '<tr><td>Open:</td><td align="right"><strong>' + o.data.open + '</strong></td></tr>'
+ '<tr><td>High:</td><td align="right"><strong>' + o.data.high + '</strong></td></tr>'
+ '<tr><td>Low:</td><td align="right"><strong>' + o.data.low + '</strong></td></tr>'
+ '<tr><td>Close:</td><td align="right"><strong>' + o.data.close + '</strong></td></tr>'
+ (o.data.mid !== undefined ? '<tr><td>Mid:</td><td align="right"><strong>' + o.data.mid + '</strong></td></tr>' : '')
+ '</table>';
}
return o.element == "bar" ? o.x : o.y;
};
var pi4 = Math.PI / 4, pi2 = Math.PI / 2;
return declare("dojox.charting.action2d.Tooltip", PlotAction, {
// summary:
// Create an action on a plot where a tooltip is shown when hovering over an element.
// the data description block for the widget parser
defaultParams: {
text: DEFAULT_TEXT // the function to produce a tooltip from the object
},
optionalParams: {}, // no optional parameters
constructor: function(chart, plot, kwArgs){
// summary:
// Create the tooltip action and connect it to the plot.
// chart: dojox.charting.Chart
// The chart this action belongs to.
// plot: String?
// The plot this action is attached to. If not passed, "default" is assumed.
// kwArgs: dojox.charting.action2d.__TooltipCtorArgs?
// Optional keyword arguments object for setting parameters.
this.text = kwArgs && kwArgs.text ? kwArgs.text : DEFAULT_TEXT;
this.connect();
},
process: function(o){
// summary:
// Process the action on the given object.
// o: dojox.gfx.Shape
// The object on which to process the highlighting action.
if(o.type === "onplotreset" || o.type === "onmouseout"){
Tooltip.hide(this.aroundRect);
this.aroundRect = null;
if(o.type === "onplotreset"){
delete this.angles;
}
return;
}
if(!o.shape || o.type !== "onmouseover"){ return; }
// calculate relative coordinates and the position
var aroundRect = {type: "rect"}, position = ["after", "before"];
switch(o.element){
case "marker":
aroundRect.x = o.cx;
aroundRect.y = o.cy;
aroundRect.w = aroundRect.h = 1;
break;
case "circle":
aroundRect.x = o.cx - o.cr;
aroundRect.y = o.cy - o.cr;
aroundRect.w = aroundRect.h = 2 * o.cr;
break;
case "column":
position = ["above", "below"];
// intentional fall down
case "bar":
aroundRect = lang.clone(o.shape.getShape());
aroundRect.w = aroundRect.width;
aroundRect.h = aroundRect.height;
break;
case "candlestick":
aroundRect.x = o.x;
aroundRect.y = o.y;
aroundRect.w = o.width;
aroundRect.h = o.height;
break;
default:
//case "slice":
if(!this.angles){
// calculate the running total of slice angles
if(typeof o.run.data[0] == "number"){
this.angles = df.map(df.scanl(o.run.data, "+", 0),
"* 2 * Math.PI / this", df.foldl(o.run.data, "+", 0));
}else{
this.angles = df.map(df.scanl(o.run.data, "a + b.y", 0),
"* 2 * Math.PI / this", df.foldl(o.run.data, "a + b.y", 0));
}
}
var startAngle = m._degToRad(o.plot.opt.startAngle),
angle = (this.angles[o.index] + this.angles[o.index + 1]) / 2 + startAngle;
aroundRect.x = o.cx + o.cr * Math.cos(angle);
aroundRect.y = o.cy + o.cr * Math.sin(angle);
aroundRect.w = aroundRect.h = 1;
// calculate the position
if(angle < pi4){
// do nothing: the position is right
}else if(angle < pi2 + pi4){
position = ["below", "above"];
}else if(angle < Math.PI + pi4){
position = ["before", "after"];
}else if(angle < 2 * Math.PI - pi4){
position = ["above", "below"];
}
/*
else{
// do nothing: the position is right
}
*/
break;
}
// adjust relative coordinates to absolute, and remove fractions
var lt = this.chart.getCoords();
aroundRect.x += lt.x;
aroundRect.y += lt.y;
aroundRect.x = Math.round(aroundRect.x);
aroundRect.y = Math.round(aroundRect.y);
aroundRect.w = Math.ceil(aroundRect.w);
aroundRect.h = Math.ceil(aroundRect.h);
this.aroundRect = aroundRect;
var tooltip = this.text(o);
if(this.chart.getTextDir){
var isChartDirectionRtl = (html.style(this.chart.node,"direction") == "rtl");
var isBaseTextDirRtl = (this.chart.getTextDir(tooltip) == "rtl");
}
if(tooltip){
if(isBaseTextDirRtl && !isChartDirectionRtl){
Tooltip.show("<span dir = 'rtl'>" + tooltip +"</span>", this.aroundRect, position);
}
else if(!isBaseTextDirRtl && isChartDirectionRtl){
Tooltip.show("<span dir = 'ltr'>" + tooltip +"</span>", this.aroundRect, position);
}else{
Tooltip.show(tooltip, this.aroundRect, position);
}
}
}
});
});
},
'dojox/gfx':function(){
define(["dojo/_base/lang", "./gfx/_base", "./gfx/renderer!"],
function(lang, gfxBase, renderer){
// module:
// dojox/gfx
// summary:
// This the root of the Dojo Graphics package
gfxBase.switchTo(renderer);
return gfxBase;
});
},
'dojox/gfx/shape':function(){
define("dojox/gfx/shape", ["./_base", "dojo/_base/lang", "dojo/_base/declare", "dojo/_base/window", "dojo/_base/sniff",
"dojo/_base/connect", "dojo/_base/array", "dojo/dom-construct", "dojo/_base/Color", "./matrix"],
function(g, lang, declare, win, has, events, arr, domConstruct, Color, matrixLib){
/*=====
dojox.gfx.shape = {
// summary:
// This module contains the core graphics Shape API.
// Different graphics renderer implementation modules (svg, canvas, vml, silverlight, etc.) extend this
// basic api to provide renderer-specific implementations for each shape.
};
=====*/
var shape = g.shape = {};
// a set of ids (keys=type)
var _ids = {};
// a simple set impl to map shape<->id
var registry = {};
shape.register = function(/*dojox.gfx.shape.Shape*/shape){
// summary:
// Register the specified shape into the graphics registry.
// shape: dojox.gfx.shape.Shape
// The shape to register.
// returns:
// The unique id associated with this shape.
// the id pattern : type+number (ex: Rect0,Rect1,etc)
var t = shape.declaredClass.split('.').pop();
var i = t in _ids ? ++_ids[t] : ((_ids[t] = 0));
var uid = t+i;
registry[uid] = shape;
return uid;
};
shape.byId = function(/*String*/id){
// summary:
// Returns the shape that matches the specified id.
// id: String
// The unique identifier for this Shape.
return registry[id]; //dojox.gfx.shape.Shape
};
shape.dispose = function(/*dojox.gfx.shape.Shape*/shape){
// summary:
// Removes the specified shape from the registry.
// shape: dojox.gfx.shape.Shape
// The shape to unregister.
delete registry[shape.getUID()];
};
declare("dojox.gfx.shape.Shape", null, {
// summary: a Shape object, which knows how to apply
// graphical attributes and transformations
constructor: function(){
// rawNode: Node
// underlying graphics-renderer-specific implementation object (if applicable)
this.rawNode = null;
// shape: Object: an abstract shape object
// (see dojox.gfx.defaultPath,
// dojox.gfx.defaultPolyline,
// dojox.gfx.defaultRect,
// dojox.gfx.defaultEllipse,
// dojox.gfx.defaultCircle,
// dojox.gfx.defaultLine,
// or dojox.gfx.defaultImage)
this.shape = null;
// matrix: dojox.gfx.Matrix2D
// a transformation matrix
this.matrix = null;
// fillStyle: Object
// a fill object
// (see dojox.gfx.defaultLinearGradient,
// dojox.gfx.defaultRadialGradient,
// dojox.gfx.defaultPattern,
// or dojo.Color)
this.fillStyle = null;
// strokeStyle: Object
// a stroke object
// (see dojox.gfx.defaultStroke)
this.strokeStyle = null;
// bbox: dojox.gfx.Rectangle
// a bounding box of this shape
// (see dojox.gfx.defaultRect)
this.bbox = null;
// virtual group structure
// parent: Object
// a parent or null
// (see dojox.gfx.Surface,
// dojox.gfx.shape.VirtualGroup,
// or dojox.gfx.Group)
this.parent = null;
// parentMatrix: dojox.gfx.Matrix2D
// a transformation matrix inherited from the parent
this.parentMatrix = null;
var uid = shape.register(this);
this.getUID = function(){
return uid;
}
},
// trivial getters
getNode: function(){
// summary: Different graphics rendering subsystems implement shapes in different ways. This
// method provides access to the underlying graphics subsystem object. Clients calling this
// method and using the return value must be careful not to try sharing or using the underlying node
// in a general way across renderer implementation.
// Returns the underlying graphics Node, or null if no underlying graphics node is used by this shape.
return this.rawNode; // Node
},
getShape: function(){
// summary: returns the current Shape object or null
// (see dojox.gfx.defaultPath,
// dojox.gfx.defaultPolyline,
// dojox.gfx.defaultRect,
// dojox.gfx.defaultEllipse,
// dojox.gfx.defaultCircle,
// dojox.gfx.defaultLine,
// or dojox.gfx.defaultImage)
return this.shape; // Object
},
getTransform: function(){
// summary: Returns the current transformation matrix applied to this Shape or null
return this.matrix; // dojox.gfx.Matrix2D
},
getFill: function(){
// summary: Returns the current fill object or null
// (see dojox.gfx.defaultLinearGradient,
// dojox.gfx.defaultRadialGradient,
// dojox.gfx.defaultPattern,
// or dojo.Color)
return this.fillStyle; // Object
},
getStroke: function(){
// summary: Returns the current stroke object or null
// (see dojox.gfx.defaultStroke)
return this.strokeStyle; // Object
},
getParent: function(){
// summary: Returns the parent Shape, Group or VirtualGroup or null if this Shape is unparented.
// (see dojox.gfx.Surface,
// dojox.gfx.shape.VirtualGroup,
// or dojox.gfx.Group)
return this.parent; // Object
},
getBoundingBox: function(){
// summary: Returns the bounding box Rectanagle for this shape or null if a BoundingBox cannot be
// calculated for the shape on the current renderer or for shapes with no geometric area (points).
// A bounding box is a rectangular geometric region
// defining the X and Y extent of the shape.
// (see dojox.gfx.defaultRect)
return this.bbox; // dojox.gfx.Rectangle
},
getTransformedBoundingBox: function(){
// summary: returns an array of four points or null
// four points represent four corners of the untransformed bounding box
var b = this.getBoundingBox();
if(!b){
return null; // null
}
var m = this._getRealMatrix(),
gm = matrixLib;
return [ // Array
gm.multiplyPoint(m, b.x, b.y),
gm.multiplyPoint(m, b.x + b.width, b.y),
gm.multiplyPoint(m, b.x + b.width, b.y + b.height),
gm.multiplyPoint(m, b.x, b.y + b.height)
];
},
getEventSource: function(){
// summary: returns a Node, which is used as
// a source of events for this shape
// COULD BE RE-IMPLEMENTED BY THE RENDERER!
return this.rawNode; // Node
},
// empty settings
setShape: function(shape){
// summary: sets a shape object
// (the default implementation simply ignores it)
// shape: Object
// a shape object
// (see dojox.gfx.defaultPath,
// dojox.gfx.defaultPolyline,
// dojox.gfx.defaultRect,
// dojox.gfx.defaultEllipse,
// dojox.gfx.defaultCircle,
// dojox.gfx.defaultLine,
// or dojox.gfx.defaultImage)
// COULD BE RE-IMPLEMENTED BY THE RENDERER!
this.shape = g.makeParameters(this.shape, shape);
this.bbox = null;
return this; // self
},
setFill: function(fill){
// summary: sets a fill object
// (the default implementation simply ignores it)
// fill: Object
// a fill object
// (see dojox.gfx.defaultLinearGradient,
// dojox.gfx.defaultRadialGradient,
// dojox.gfx.defaultPattern,
// or dojo.Color)
// COULD BE RE-IMPLEMENTED BY THE RENDERER!
if(!fill){
// don't fill
this.fillStyle = null;
return this; // self
}
var f = null;
if(typeof(fill) == "object" && "type" in fill){
// gradient or pattern
switch(fill.type){
case "linear":
f = g.makeParameters(g.defaultLinearGradient, fill);
break;
case "radial":
f = g.makeParameters(g.defaultRadialGradient, fill);
break;
case "pattern":
f = g.makeParameters(g.defaultPattern, fill);
break;
}
}else{
// color object
f = g.normalizeColor(fill);
}
this.fillStyle = f;
return this; // self
},
setStroke: function(stroke){
// summary: sets a stroke object
// (the default implementation simply ignores it)
// stroke: Object
// a stroke object
// (see dojox.gfx.defaultStroke)
// COULD BE RE-IMPLEMENTED BY THE RENDERER!
if(!stroke){
// don't stroke
this.strokeStyle = null;
return this; // self
}
// normalize the stroke
if(typeof stroke == "string" || lang.isArray(stroke) || stroke instanceof Color){
stroke = {color: stroke};
}
var s = this.strokeStyle = g.makeParameters(g.defaultStroke, stroke);
s.color = g.normalizeColor(s.color);
return this; // self
},
setTransform: function(matrix){
// summary: sets a transformation matrix
// matrix: dojox.gfx.Matrix2D
// a matrix or a matrix-like object
// (see an argument of dojox.gfx.Matrix2D
// constructor for a list of acceptable arguments)
// COULD BE RE-IMPLEMENTED BY THE RENDERER!
this.matrix = matrixLib.clone(matrix ? matrixLib.normalize(matrix) : matrixLib.identity);
return this._applyTransform(); // self
},
_applyTransform: function(){
// summary: physically sets a matrix
// COULD BE RE-IMPLEMENTED BY THE RENDERER!
return this; // self
},
// z-index
moveToFront: function(){
// summary: moves a shape to front of its parent's list of shapes
var p = this.getParent();
if(p){
p._moveChildToFront(this);
this._moveToFront(); // execute renderer-specific action
}
return this; // self
},
moveToBack: function(){
// summary: moves a shape to back of its parent's list of shapes
var p = this.getParent();
if(p){
p._moveChildToBack(this);
this._moveToBack(); // execute renderer-specific action
}
return this;
},
_moveToFront: function(){
// summary: renderer-specific hook, see dojox.gfx.shape.Shape.moveToFront()
// COULD BE RE-IMPLEMENTED BY THE RENDERER!
},
_moveToBack: function(){
// summary: renderer-specific hook, see dojox.gfx.shape.Shape.moveToFront()
// COULD BE RE-IMPLEMENTED BY THE RENDERER!
},
// apply left & right transformation
applyRightTransform: function(matrix){
// summary: multiplies the existing matrix with an argument on right side
// (this.matrix * matrix)
// matrix: dojox.gfx.Matrix2D
// a matrix or a matrix-like object
// (see an argument of dojox.gfx.Matrix2D
// constructor for a list of acceptable arguments)
return matrix ? this.setTransform([this.matrix, matrix]) : this; // self
},
applyLeftTransform: function(matrix){
// summary: multiplies the existing matrix with an argument on left side
// (matrix * this.matrix)
// matrix: dojox.gfx.Matrix2D
// a matrix or a matrix-like object
// (see an argument of dojox.gfx.Matrix2D
// constructor for a list of acceptable arguments)
return matrix ? this.setTransform([matrix, this.matrix]) : this; // self
},
applyTransform: function(matrix){
// summary: a shortcut for dojox.gfx.Shape.applyRightTransform
// matrix: dojox.gfx.Matrix2D
// a matrix or a matrix-like object
// (see an argument of dojox.gfx.Matrix2D
// constructor for a list of acceptable arguments)
return matrix ? this.setTransform([this.matrix, matrix]) : this; // self
},
// virtual group methods
removeShape: function(silently){
// summary: removes the shape from its parent's list of shapes
// silently: Boolean
// if true, do not redraw a picture yet
if(this.parent){
this.parent.remove(this, silently);
}
return this; // self
},
_setParent: function(parent, matrix){
// summary: sets a parent
// parent: Object
// a parent or null
// (see dojox.gfx.Surface,
// dojox.gfx.shape.VirtualGroup,
// or dojox.gfx.Group)
// matrix: dojox.gfx.Matrix2D
// a 2D matrix or a matrix-like object
this.parent = parent;
return this._updateParentMatrix(matrix); // self
},
_updateParentMatrix: function(matrix){
// summary: updates the parent matrix with new matrix
// matrix: dojox.gfx.Matrix2D
// a 2D matrix or a matrix-like object
this.parentMatrix = matrix ? matrixLib.clone(matrix) : null;
return this._applyTransform(); // self
},
_getRealMatrix: function(){
// summary: returns the cumulative ('real') transformation matrix
// by combining the shape's matrix with its parent's matrix
var m = this.matrix;
var p = this.parent;
while(p){
if(p.matrix){
m = matrixLib.multiply(p.matrix, m);
}
p = p.parent;
}
return m; // dojox.gfx.Matrix2D
}
});
shape._eventsProcessing = {
connect: function(name, object, method){
// summary: connects a handler to an event on this shape
// COULD BE RE-IMPLEMENTED BY THE RENDERER!
// redirect to fixCallback to normalize events and add the gfxTarget to the event. The latter
// is done by dojox.gfx.fixTarget which is defined by each renderer
return events.connect(this.getEventSource(), name, shape.fixCallback(this, g.fixTarget, object, method));
},
disconnect: function(token){
// summary: connects a handler by token from an event on this shape
// COULD BE RE-IMPLEMENTED BY THE RENDERER!
events.disconnect(token);
}
};
shape.fixCallback = function(gfxElement, fixFunction, scope, method){
// summary:
// Wraps the callback to allow for tests and event normalization
// before it gets invoked. This is where 'fixTarget' is invoked.
// gfxElement: Object
// The GFX object that triggers the action (ex.:
// dojox.gfx.Surface and dojox.gfx.Shape). A new event property
// 'gfxTarget' is added to the event to reference this object.
// for easy manipulation of GFX objects by the event handlers.
// fixFunction: Function
// The function that implements the logic to set the 'gfxTarget'
// property to the event. It should be 'dojox.gfx.fixTarget' for
// most of the cases
// scope: Object
// Optional. The scope to be used when invoking 'method'. If
// omitted, a global scope is used.
// method: Function|String
// The original callback to be invoked.
if(!method){
method = scope;
scope = null;
}
if(lang.isString(method)){
scope = scope || win.global;
if(!scope[method]){ throw(['dojox.gfx.shape.fixCallback: scope["', method, '"] is null (scope="', scope, '")'].join('')); }
return function(e){
return fixFunction(e,gfxElement) ? scope[method].apply(scope, arguments || []) : undefined; }; // Function
}
return !scope
? function(e){
return fixFunction(e,gfxElement) ? method.apply(scope, arguments) : undefined; }
: function(e){
return fixFunction(e,gfxElement) ? method.apply(scope, arguments || []) : undefined; }; // Function
};
lang.extend(shape.Shape, shape._eventsProcessing);
shape.Container = {
// summary: a container of shapes, which can be used
// as a foundation for renderer-specific groups, or as a way
// to logically group shapes (e.g, to propagate matricies)
_init: function() {
// children: Array: a list of children
this.children = [];
},
// group management
openBatch: function() {
// summary: starts a new batch, subsequent new child shapes will be held in
// the batch instead of appending to the container directly
},
closeBatch: function() {
// summary: submits the current batch, append all pending child shapes to DOM
},
add: function(shape){
// summary: adds a shape to the list
// shape: dojox.gfx.Shape
// the shape to add to the list
var oldParent = shape.getParent();
if(oldParent){
oldParent.remove(shape, true);
}
this.children.push(shape);
return shape._setParent(this, this._getRealMatrix()); // self
},
remove: function(shape, silently){
// summary: removes a shape from the list
// shape: dojox.gfx.shape.Shape
// the shape to remove
// silently: Boolean
// if true, do not redraw a picture yet
for(var i = 0; i < this.children.length; ++i){
if(this.children[i] == shape){
if(silently){
// skip for now
}else{
shape.parent = null;
shape.parentMatrix = null;
}
this.children.splice(i, 1);
break;
}
}
return this; // self
},
clear: function(){
// summary: removes all shapes from a group/surface
var shape;
for(var i = 0; i < this.children.length;++i){
shape = this.children[i];
shape.parent = null;
shape.parentMatrix = null;
}
this.children = [];
return this; // self
},
// moving child nodes
_moveChildToFront: function(shape){
// summary: moves a shape to front of the list of shapes
// shape: dojox.gfx.shape.Shape
// one of the child shapes to move to the front
for(var i = 0; i < this.children.length; ++i){
if(this.children[i] == shape){
this.children.splice(i, 1);
this.children.push(shape);
break;
}
}
return this; // self
},
_moveChildToBack: function(shape){
// summary: moves a shape to back of the list of shapes
// shape: dojox.gfx.shape.Shape
// one of the child shapes to move to the front
for(var i = 0; i < this.children.length; ++i){
if(this.children[i] == shape){
this.children.splice(i, 1);
this.children.unshift(shape);
break;
}
}
return this; // self
}
};
declare("dojox.gfx.shape.Surface", null, {
// summary: a surface object to be used for drawings
constructor: function(){
// underlying node
this.rawNode = null;
// the parent node
this._parent = null;
// the list of DOM nodes to be deleted in the case of destruction
this._nodes = [];
// the list of events to be detached in the case of destruction
this._events = [];
},
destroy: function(){
// summary: destroy all relevant external resources and release all
// external references to make this object garbage-collectible
arr.forEach(this._nodes, domConstruct.destroy);
this._nodes = [];
arr.forEach(this._events, events.disconnect);
this._events = [];
this.rawNode = null; // recycle it in _nodes, if it needs to be recycled
if(has("ie")){
while(this._parent.lastChild){
domConstruct.destroy(this._parent.lastChild);
}
}else{
this._parent.innerHTML = "";
}
this._parent = null;
},
getEventSource: function(){
// summary: returns a node, which can be used to attach event listeners
return this.rawNode; // Node
},
_getRealMatrix: function(){
// summary: always returns the identity matrix
return null; // dojox.gfx.Matrix2D
},
isLoaded: true,
onLoad: function(/*dojox.gfx.Surface*/ surface){
// summary: local event, fired once when the surface is created
// asynchronously, used only when isLoaded is false, required
// only for Silverlight.
},
whenLoaded: function(/*Object|Null*/ context, /*Function|String*/ method){
var f = lang.hitch(context, method);
if(this.isLoaded){
f(this);
}else{
var h = events.connect(this, "onLoad", function(surface){
events.disconnect(h);
f(surface);
});
}
}
});
lang.extend(shape.Surface, shape._eventsProcessing);
declare("dojox.gfx.Point", null, {
// summary: a hypothetical 2D point to be used for drawings - {x, y}
// description: This object is defined for documentation purposes.
// You should use the naked object instead: {x: 1, y: 2}.
});
declare("dojox.gfx.Rectangle", null, {
// summary: a hypothetical rectangle - {x, y, width, height}
// description: This object is defined for documentation purposes.
// You should use the naked object instead: {x: 1, y: 2, width: 100, height: 200}.
});
declare("dojox.gfx.shape.Rect", shape.Shape, {
// summary: a generic rectangle
constructor: function(rawNode){
// rawNode: Node
// The underlying graphics system object (typically a DOM Node)
this.shape = g.getDefault("Rect");
this.rawNode = rawNode;
},
getBoundingBox: function(){
// summary: returns the bounding box (its shape in this case)
return this.shape; // dojox.gfx.Rectangle
}
});
declare("dojox.gfx.shape.Ellipse", shape.Shape, {
// summary: a generic ellipse
constructor: function(rawNode){
// rawNode: Node
// a DOM Node
this.shape = g.getDefault("Ellipse");
this.rawNode = rawNode;
},
getBoundingBox: function(){
// summary: returns the bounding box
if(!this.bbox){
var shape = this.shape;
this.bbox = {x: shape.cx - shape.rx, y: shape.cy - shape.ry,
width: 2 * shape.rx, height: 2 * shape.ry};
}
return this.bbox; // dojox.gfx.Rectangle
}
});
declare("dojox.gfx.shape.Circle", shape.Shape, {
// summary: a generic circle
// (this is a helper object, which is defined for convenience)
constructor: function(rawNode){
// rawNode: Node
// a DOM Node
this.shape = g.getDefault("Circle");
this.rawNode = rawNode;
},
getBoundingBox: function(){
// summary: returns the bounding box
if(!this.bbox){
var shape = this.shape;
this.bbox = {x: shape.cx - shape.r, y: shape.cy - shape.r,
width: 2 * shape.r, height: 2 * shape.r};
}
return this.bbox; // dojox.gfx.Rectangle
}
});
declare("dojox.gfx.shape.Line", shape.Shape, {
// summary: a generic line
// (this is a helper object, which is defined for convenience)
constructor: function(rawNode){
// rawNode: Node
// a DOM Node
this.shape = g.getDefault("Line");
this.rawNode = rawNode;
},
getBoundingBox: function(){
// summary: returns the bounding box
if(!this.bbox){
var shape = this.shape;
this.bbox = {
x: Math.min(shape.x1, shape.x2),
y: Math.min(shape.y1, shape.y2),
width: Math.abs(shape.x2 - shape.x1),
height: Math.abs(shape.y2 - shape.y1)
};
}
return this.bbox; // dojox.gfx.Rectangle
}
});
declare("dojox.gfx.shape.Polyline", shape.Shape, {
// summary: a generic polyline/polygon
// (this is a helper object, which is defined for convenience)
constructor: function(rawNode){
// rawNode: Node
// a DOM Node
this.shape = g.getDefault("Polyline");
this.rawNode = rawNode;
},
setShape: function(points, closed){
// summary: sets a polyline/polygon shape object
// points: Object
// a polyline/polygon shape object
// closed: Boolean
// close the polyline to make a polygon
if(points && points instanceof Array){
// points: Array: an array of points
this.inherited(arguments, [{points: points}]);
if(closed && this.shape.points.length){
this.shape.points.push(this.shape.points[0]);
}
}else{
this.inherited(arguments, [points]);
}
return this; // self
},
_normalizePoints: function(){
// summary: normalize points to array of {x:number, y:number}
var p = this.shape.points, l = p && p.length;
if(l && typeof p[0] == "number"){
var points = [];
for(var i = 0; i < l; i += 2){
points.push({x: p[i], y: p[i + 1]});
}
this.shape.points = points;
}
},
getBoundingBox: function(){
// summary: returns the bounding box
if(!this.bbox && this.shape.points.length){
var p = this.shape.points;
var l = p.length;
var t = p[0];
var bbox = {l: t.x, t: t.y, r: t.x, b: t.y};
for(var i = 1; i < l; ++i){
t = p[i];
if(bbox.l > t.x) bbox.l = t.x;
if(bbox.r < t.x) bbox.r = t.x;
if(bbox.t > t.y) bbox.t = t.y;
if(bbox.b < t.y) bbox.b = t.y;
}
this.bbox = {
x: bbox.l,
y: bbox.t,
width: bbox.r - bbox.l,
height: bbox.b - bbox.t
};
}
return this.bbox; // dojox.gfx.Rectangle
}
});
declare("dojox.gfx.shape.Image", shape.Shape, {
// summary: a generic image
// (this is a helper object, which is defined for convenience)
constructor: function(rawNode){
// rawNode: Node
// a DOM Node
this.shape = g.getDefault("Image");
this.rawNode = rawNode;
},
getBoundingBox: function(){
// summary: returns the bounding box (its shape in this case)
return this.shape; // dojox.gfx.Rectangle
},
setStroke: function(){
// summary: ignore setting a stroke style
return this; // self
},
setFill: function(){
// summary: ignore setting a fill style
return this; // self
}
});
declare("dojox.gfx.shape.Text", shape.Shape, {
// summary: a generic text
constructor: function(rawNode){
// rawNode: Node
// a DOM Node
this.fontStyle = null;
this.shape = g.getDefault("Text");
this.rawNode = rawNode;
},
getFont: function(){
// summary: returns the current font object or null
return this.fontStyle; // Object
},
setFont: function(newFont){
// summary: sets a font for text
// newFont: Object
// a font object (see dojox.gfx.defaultFont) or a font string
this.fontStyle = typeof newFont == "string" ? g.splitFontString(newFont) :
g.makeParameters(g.defaultFont, newFont);
this._setFont();
return this; // self
}
});
shape.Creator = {
// summary: shape creators
createShape: function(shape){
// summary: creates a shape object based on its type; it is meant to be used
// by group-like objects
// shape: Object
// a shape descriptor object
switch(shape.type){
case g.defaultPath.type: return this.createPath(shape);
case g.defaultRect.type: return this.createRect(shape);
case g.defaultCircle.type: return this.createCircle(shape);
case g.defaultEllipse.type: return this.createEllipse(shape);
case g.defaultLine.type: return this.createLine(shape);
case g.defaultPolyline.type: return this.createPolyline(shape);
case g.defaultImage.type: return this.createImage(shape);
case g.defaultText.type: return this.createText(shape);
case g.defaultTextPath.type: return this.createTextPath(shape);
}
return null;
},
createGroup: function(){
// summary: creates a group shape
return this.createObject(g.Group); // dojox.gfx.Group
},
createRect: function(rect){
// summary: creates a rectangle shape
// rect: Object
// a path object (see dojox.gfx.defaultRect)
return this.createObject(g.Rect, rect); // dojox.gfx.Rect
},
createEllipse: function(ellipse){
// summary: creates an ellipse shape
// ellipse: Object
// an ellipse object (see dojox.gfx.defaultEllipse)
return this.createObject(g.Ellipse, ellipse); // dojox.gfx.Ellipse
},
createCircle: function(circle){
// summary: creates a circle shape
// circle: Object
// a circle object (see dojox.gfx.defaultCircle)
return this.createObject(g.Circle, circle); // dojox.gfx.Circle
},
createLine: function(line){
// summary: creates a line shape
// line: Object
// a line object (see dojox.gfx.defaultLine)
return this.createObject(g.Line, line); // dojox.gfx.Line
},
createPolyline: function(points){
// summary: creates a polyline/polygon shape
// points: Object
// a points object (see dojox.gfx.defaultPolyline)
// or an Array of points
return this.createObject(g.Polyline, points); // dojox.gfx.Polyline
},
createImage: function(image){
// summary: creates a image shape
// image: Object
// an image object (see dojox.gfx.defaultImage)
return this.createObject(g.Image, image); // dojox.gfx.Image
},
createText: function(text){
// summary: creates a text shape
// text: Object
// a text object (see dojox.gfx.defaultText)
return this.createObject(g.Text, text); // dojox.gfx.Text
},
createPath: function(path){
// summary: creates a path shape
// path: Object
// a path object (see dojox.gfx.defaultPath)
return this.createObject(g.Path, path); // dojox.gfx.Path
},
createTextPath: function(text){
// summary: creates a text shape
// text: Object
// a textpath object (see dojox.gfx.defaultTextPath)
return this.createObject(g.TextPath, {}).setText(text); // dojox.gfx.TextPath
},
createObject: function(shapeType, rawShape){
// summary: creates an instance of the passed shapeType class
// SHOULD BE RE-IMPLEMENTED BY THE RENDERER!
// shapeType: Function
// a class constructor to create an instance of
// rawShape: Object
// properties to be passed in to the classes 'setShape' method
return null; // dojox.gfx.Shape
}
};
return shape;
});
},
'dojox/charting/Chart2D':function(){
define("dojox/charting/Chart2D", ["dojo/_base/kernel", "dojox", "./Chart",
"./axis2d/Default", "./axis2d/Invisible", "./plot2d/Default", "./plot2d/Lines", "./plot2d/Areas",
"./plot2d/Markers", "./plot2d/MarkersOnly", "./plot2d/Scatter", "./plot2d/Stacked", "./plot2d/StackedLines",
"./plot2d/StackedAreas", "./plot2d/Columns", "./plot2d/StackedColumns", "./plot2d/ClusteredColumns",
"./plot2d/Bars", "./plot2d/StackedBars", "./plot2d/ClusteredBars", "./plot2d/Grid", "./plot2d/Pie",
"./plot2d/Bubble", "./plot2d/Candlesticks", "./plot2d/OHLC", "./plot2d/Spider"],
function(dojo, dojox, Chart){
dojo.deprecated("dojox.charting.Chart2D", "Use dojo.charting.Chart instead and require all other components explicitly", "2.0");
// module:
// dojox/charting/Chart2D
// summary:
// This is a compatibility module which loads all charting modules that used to be automatically
// loaded in versions prior to 1.6. It is highly recommended for performance reasons that
// this module no longer be referenced by applications. Instead, use dojox/charting/Chart.
return dojox.charting.Chart2D = Chart;
});
},
'dojox/charting/scaler/linear':function(){
define("dojox/charting/scaler/linear", ["dojo/_base/lang", "./common"],
function(lang, common){
var linear = lang.getObject("dojox.charting.scaler.linear", true);
var deltaLimit = 3, // pixels
findString = common.findString,
getLabel = common.getNumericLabel;
var calcTicks = function(min, max, kwArgs, majorTick, minorTick, microTick, span){
kwArgs = lang.delegate(kwArgs);
if(!majorTick){
if(kwArgs.fixUpper == "major"){ kwArgs.fixUpper = "minor"; }
if(kwArgs.fixLower == "major"){ kwArgs.fixLower = "minor"; }
}
if(!minorTick){
if(kwArgs.fixUpper == "minor"){ kwArgs.fixUpper = "micro"; }
if(kwArgs.fixLower == "minor"){ kwArgs.fixLower = "micro"; }
}
if(!microTick){
if(kwArgs.fixUpper == "micro"){ kwArgs.fixUpper = "none"; }
if(kwArgs.fixLower == "micro"){ kwArgs.fixLower = "none"; }
}
var lowerBound = findString(kwArgs.fixLower, ["major"]) ?
Math.floor(kwArgs.min / majorTick) * majorTick :
findString(kwArgs.fixLower, ["minor"]) ?
Math.floor(kwArgs.min / minorTick) * minorTick :
findString(kwArgs.fixLower, ["micro"]) ?
Math.floor(kwArgs.min / microTick) * microTick : kwArgs.min,
upperBound = findString(kwArgs.fixUpper, ["major"]) ?
Math.ceil(kwArgs.max / majorTick) * majorTick :
findString(kwArgs.fixUpper, ["minor"]) ?
Math.ceil(kwArgs.max / minorTick) * minorTick :
findString(kwArgs.fixUpper, ["micro"]) ?
Math.ceil(kwArgs.max / microTick) * microTick : kwArgs.max;
if(kwArgs.useMin){ min = lowerBound; }
if(kwArgs.useMax){ max = upperBound; }
var majorStart = (!majorTick || kwArgs.useMin && findString(kwArgs.fixLower, ["major"])) ?
min : Math.ceil(min / majorTick) * majorTick,
minorStart = (!minorTick || kwArgs.useMin && findString(kwArgs.fixLower, ["major", "minor"])) ?
min : Math.ceil(min / minorTick) * minorTick,
microStart = (! microTick || kwArgs.useMin && findString(kwArgs.fixLower, ["major", "minor", "micro"])) ?
min : Math.ceil(min / microTick) * microTick,
majorCount = !majorTick ? 0 : (kwArgs.useMax && findString(kwArgs.fixUpper, ["major"]) ?
Math.round((max - majorStart) / majorTick) :
Math.floor((max - majorStart) / majorTick)) + 1,
minorCount = !minorTick ? 0 : (kwArgs.useMax && findString(kwArgs.fixUpper, ["major", "minor"]) ?
Math.round((max - minorStart) / minorTick) :
Math.floor((max - minorStart) / minorTick)) + 1,
microCount = !microTick ? 0 : (kwArgs.useMax && findString(kwArgs.fixUpper, ["major", "minor", "micro"]) ?
Math.round((max - microStart) / microTick) :
Math.floor((max - microStart) / microTick)) + 1,
minorPerMajor = minorTick ? Math.round(majorTick / minorTick) : 0,
microPerMinor = microTick ? Math.round(minorTick / microTick) : 0,
majorPrecision = majorTick ? Math.floor(Math.log(majorTick) / Math.LN10) : 0,
minorPrecision = minorTick ? Math.floor(Math.log(minorTick) / Math.LN10) : 0,
scale = span / (max - min);
if(!isFinite(scale)){ scale = 1; }
return {
bounds: {
lower: lowerBound,
upper: upperBound,
from: min,
to: max,
scale: scale,
span: span
},
major: {
tick: majorTick,
start: majorStart,
count: majorCount,
prec: majorPrecision
},
minor: {
tick: minorTick,
start: minorStart,
count: minorCount,
prec: minorPrecision
},
micro: {
tick: microTick,
start: microStart,
count: microCount,
prec: 0
},
minorPerMajor: minorPerMajor,
microPerMinor: microPerMinor,
scaler: linear
};
};
return lang.mixin(linear, {
buildScaler: function(/*Number*/ min, /*Number*/ max, /*Number*/ span, /*Object*/ kwArgs){
var h = {fixUpper: "none", fixLower: "none", natural: false};
if(kwArgs){
if("fixUpper" in kwArgs){ h.fixUpper = String(kwArgs.fixUpper); }
if("fixLower" in kwArgs){ h.fixLower = String(kwArgs.fixLower); }
if("natural" in kwArgs){ h.natural = Boolean(kwArgs.natural); }
}
// update bounds
if("min" in kwArgs){ min = kwArgs.min; }
if("max" in kwArgs){ max = kwArgs.max; }
if(kwArgs.includeZero){
if(min > 0){ min = 0; }
if(max < 0){ max = 0; }
}
h.min = min;
h.useMin = true;
h.max = max;
h.useMax = true;
if("from" in kwArgs){
min = kwArgs.from;
h.useMin = false;
}
if("to" in kwArgs){
max = kwArgs.to;
h.useMax = false;
}
// check for erroneous condition
if(max <= min){
return calcTicks(min, max, h, 0, 0, 0, span); // Object
}
var mag = Math.floor(Math.log(max - min) / Math.LN10),
major = kwArgs && ("majorTickStep" in kwArgs) ? kwArgs.majorTickStep : Math.pow(10, mag),
minor = 0, micro = 0, ticks;
// calculate minor ticks
if(kwArgs && ("minorTickStep" in kwArgs)){
minor = kwArgs.minorTickStep;
}else{
do{
minor = major / 10;
if(!h.natural || minor > 0.9){
ticks = calcTicks(min, max, h, major, minor, 0, span);
if(ticks.bounds.scale * ticks.minor.tick > deltaLimit){ break; }
}
minor = major / 5;
if(!h.natural || minor > 0.9){
ticks = calcTicks(min, max, h, major, minor, 0, span);
if(ticks.bounds.scale * ticks.minor.tick > deltaLimit){ break; }
}
minor = major / 2;
if(!h.natural || minor > 0.9){
ticks = calcTicks(min, max, h, major, minor, 0, span);
if(ticks.bounds.scale * ticks.minor.tick > deltaLimit){ break; }
}
return calcTicks(min, max, h, major, 0, 0, span); // Object
}while(false);
}
// calculate micro ticks
if(kwArgs && ("microTickStep" in kwArgs)){
micro = kwArgs.microTickStep;
ticks = calcTicks(min, max, h, major, minor, micro, span);
}else{
do{
micro = minor / 10;
if(!h.natural || micro > 0.9){
ticks = calcTicks(min, max, h, major, minor, micro, span);
if(ticks.bounds.scale * ticks.micro.tick > deltaLimit){ break; }
}
micro = minor / 5;
if(!h.natural || micro > 0.9){
ticks = calcTicks(min, max, h, major, minor, micro, span);
if(ticks.bounds.scale * ticks.micro.tick > deltaLimit){ break; }
}
micro = minor / 2;
if(!h.natural || micro > 0.9){
ticks = calcTicks(min, max, h, major, minor, micro, span);
if(ticks.bounds.scale * ticks.micro.tick > deltaLimit){ break; }
}
micro = 0;
}while(false);
}
return micro ? ticks : calcTicks(min, max, h, major, minor, 0, span); // Object
},
buildTicks: function(/*Object*/ scaler, /*Object*/ kwArgs){
var step, next, tick,
nextMajor = scaler.major.start,
nextMinor = scaler.minor.start,
nextMicro = scaler.micro.start;
if(kwArgs.microTicks && scaler.micro.tick){
step = scaler.micro.tick, next = nextMicro;
}else if(kwArgs.minorTicks && scaler.minor.tick){
step = scaler.minor.tick, next = nextMinor;
}else if(scaler.major.tick){
step = scaler.major.tick, next = nextMajor;
}else{
// no ticks
return null;
}
// make sure that we have finite bounds
var revScale = 1 / scaler.bounds.scale;
if(scaler.bounds.to <= scaler.bounds.from || isNaN(revScale) || !isFinite(revScale) ||
step <= 0 || isNaN(step) || !isFinite(step)){
// no ticks
return null;
}
// loop over all ticks
var majorTicks = [], minorTicks = [], microTicks = [];
while(next <= scaler.bounds.to + revScale){
if(Math.abs(nextMajor - next) < step / 2){
// major tick
tick = {value: nextMajor};
if(kwArgs.majorLabels){
tick.label = getLabel(nextMajor, scaler.major.prec, kwArgs);
}
majorTicks.push(tick);
nextMajor += scaler.major.tick;
nextMinor += scaler.minor.tick;
nextMicro += scaler.micro.tick;
}else if(Math.abs(nextMinor - next) < step / 2){
// minor tick
if(kwArgs.minorTicks){
tick = {value: nextMinor};
if(kwArgs.minorLabels && (scaler.minMinorStep <= scaler.minor.tick * scaler.bounds.scale)){
tick.label = getLabel(nextMinor, scaler.minor.prec, kwArgs);
}
minorTicks.push(tick);
}
nextMinor += scaler.minor.tick;
nextMicro += scaler.micro.tick;
}else{
// micro tick
if(kwArgs.microTicks){
microTicks.push({value: nextMicro});
}
nextMicro += scaler.micro.tick;
}
next += step;
}
return {major: majorTicks, minor: minorTicks, micro: microTicks}; // Object
},
getTransformerFromModel: function(/*Object*/ scaler){
var offset = scaler.bounds.from, scale = scaler.bounds.scale;
return function(x){ return (x - offset) * scale; }; // Function
},
getTransformerFromPlot: function(/*Object*/ scaler){
var offset = scaler.bounds.from, scale = scaler.bounds.scale;
return function(x){ return x / scale + offset; }; // Function
}
});
});
},
'dojox/gfx/renderer':function(){
define("dojox/gfx/renderer", ["./_base","dojo/_base/lang", "dojo/_base/sniff", "dojo/_base/window", "dojo/_base/config"],
function(g, lang, has, win, config){
//>> noBuildResolver
/*=====
dojox.gfx.renderer = {
// summary:
// This module is an AMD loader plugin that loads the appropriate graphics renderer
// implementation based on detected environment and current configuration settings.
};
=====*/
var currentRenderer = null;
return {
load: function(id, require, load){
if(currentRenderer && id != "force"){
load(currentRenderer);
return;
}
var renderer = config.forceGfxRenderer,
renderers = !renderer && (lang.isString(config.gfxRenderer) ?
config.gfxRenderer : "svg,vml,canvas,silverlight").split(","),
silverlightObject, silverlightFlag;
while(!renderer && renderers.length){
switch(renderers.shift()){
case "svg":
// the next test is from https://github.com/phiggins42/has.js
if("SVGAngle" in win.global){
renderer = "svg";
}
break;
case "vml":
if(has("ie")){
renderer = "vml";
}
break;
case "silverlight":
try{
if(has("ie")){
silverlightObject = new ActiveXObject("AgControl.AgControl");
if(silverlightObject && silverlightObject.IsVersionSupported("1.0")){
silverlightFlag = true;
}
}else{
if(navigator.plugins["Silverlight Plug-In"]){
silverlightFlag = true;
}
}
}catch(e){
silverlightFlag = false;
}finally{
silverlightObject = null;
}
if(silverlightFlag){
renderer = "silverlight";
}
break;
case "canvas":
if(win.global.CanvasRenderingContext2D){
renderer = "canvas";
}
break;
}
}
if (renderer === 'canvas' && config.canvasEvents !== false) {
renderer = "canvasWithEvents";
}
if(config.isDebug){
console.log("gfx renderer = " + renderer);
}
function loadRenderer(){
require(["dojox/gfx/" + renderer], function(module){
g.renderer = renderer;
// memorize the renderer module
currentRenderer = module;
// now load it
load(module);
});
}
if(renderer == "svg" && typeof window.svgweb != "undefined"){
window.svgweb.addOnLoad(loadRenderer);
}else{
loadRenderer();
}
}
};
});
},
'dojox/charting/widget/Chart':function(){
define("dojox/charting/widget/Chart", ["dojo/_base/kernel", "dojo/_base/lang", "dojo/_base/array","dojo/_base/html","dojo/_base/declare", "dojo/query",
"dijit/_Widget", "../Chart", "dojox/lang/utils", "dojox/lang/functional","dojox/lang/functional/lambda",
"dijit/_base/manager"],
function(kernel, lang, arr, html, declare, query, Widget, Chart, du, df, dfl){
/*=====
var Widget = dijit._Widget;
=====*/
var collectParams, collectAxisParams, collectPlotParams,
collectActionParams, collectDataParams,
notNull = function(o){ return o; },
dc = lang.getObject("dojox.charting");
var ChartWidget = declare("dojox.charting.widget.Chart", Widget, {
// parameters for the markup
// theme for the chart
theme: null,
// margins for the chart: {l: 10, r: 10, t: 10, b: 10}
margins: null,
// chart area, define them as undefined to:
// allow the parser to take them into account
// but make sure they have no defined value to not override theme
stroke: undefined,
fill: undefined,
// methods
buildRendering: function(){
this.inherited(arguments);
n = this.domNode;
// collect chart parameters
var axes = query("> .axis", n).map(collectAxisParams).filter(notNull),
plots = query("> .plot", n).map(collectPlotParams).filter(notNull),
actions = query("> .action", n).map(collectActionParams).filter(notNull),
series = query("> .series", n).map(collectDataParams).filter(notNull);
// build the chart
n.innerHTML = "";
var c = this.chart = new Chart(n, {
margins: this.margins,
stroke: this.stroke,
fill: this.fill,
textDir: this.textDir
});
// add collected parameters
if(this.theme){
c.setTheme(this.theme);
}
axes.forEach(function(axis){
c.addAxis(axis.name, axis.kwArgs);
});
plots.forEach(function(plot){
c.addPlot(plot.name, plot.kwArgs);
});
this.actions = actions.map(function(action){
return new action.action(c, action.plot, action.kwArgs);
});
var render = df.foldl(series, function(render, series){
if(series.type == "data"){
c.addSeries(series.name, series.data, series.kwArgs);
render = true;
}else{
c.addSeries(series.name, [0], series.kwArgs);
var kw = {};
du.updateWithPattern(
kw,
series.kwArgs,
{
"query": "",
"queryOptions": null,
"start": 0,
"count": 1 //,
// "sort": []
},
true
);
if(series.kwArgs.sort){
// sort is a complex object type and doesn't survive coercian
kw.sort = lang.clone(series.kwArgs.sort);
}
lang.mixin(kw, {
onComplete: function(data){
var values;
if("valueFn" in series.kwArgs){
var fn = series.kwArgs.valueFn;
values = arr.map(data, function(x){
return fn(series.data.getValue(x, series.field, 0));
});
}else{
values = arr.map(data, function(x){
return series.data.getValue(x, series.field, 0);
});
}
c.addSeries(series.name, values, series.kwArgs).render();
}
});
series.data.fetch(kw);
}
return render;
}, false);
if(render){ c.render(); }
},
destroy: function(){
// summary: properly destroy the widget
this.chart.destroy();
this.inherited(arguments);
},
resize: function(box){
// summary:
// Resize the widget.
// description:
// Resize the domNode and the widget surface to the dimensions of a box of the following form:
// `{ l: 50, t: 200, w: 300: h: 150 }`
// If no box is provided, resize the surface to the marginBox of the domNode.
// box:
// If passed, denotes the new size of the widget.
this.chart.resize(box);
}
});
collectParams = function(node, type, kw){
var dp = eval("(" + type + ".prototype.defaultParams)");
var x, attr;
for(x in dp){
if(x in kw){ continue; }
attr = node.getAttribute(x);
kw[x] = du.coerceType(dp[x], attr == null || typeof attr == "undefined" ? dp[x] : attr);
}
var op = eval("(" + type + ".prototype.optionalParams)");
for(x in op){
if(x in kw){ continue; }
attr = node.getAttribute(x);
if(attr != null){
kw[x] = du.coerceType(op[x], attr);
}
}
};
collectAxisParams = function(node){
var name = node.getAttribute("name"), type = node.getAttribute("type");
if(!name){ return null; }
var o = {name: name, kwArgs: {}}, kw = o.kwArgs;
if(type){
if(dc.axis2d[type]){
type = dojo._scopeName + "x.charting.axis2d." + type;
}
var axis = eval("(" + type + ")");
if(axis){ kw.type = axis; }
}else{
type = dojo._scopeName + "x.charting.axis2d.Default";
}
collectParams(node, type, kw);
// compatibility conversions
if(kw.font || kw.fontColor){
if(!kw.tick){
kw.tick = {};
}
if(kw.font){
kw.tick.font = kw.font;
}
if(kw.fontColor){
kw.tick.fontColor = kw.fontColor;
}
}
return o;
};
collectPlotParams = function(node){
// var name = d.attr(node, "name"), type = d.attr(node, "type");
var name = node.getAttribute("name"), type = node.getAttribute("type");
if(!name){ return null; }
var o = {name: name, kwArgs: {}}, kw = o.kwArgs;
if(type){
if(dc.plot2d && dc.plot2d[type]){
type = dojo._scopeName + "x.charting.plot2d." + type;
}
var plot = eval("(" + type + ")");
if(plot){ kw.type = plot; }
}else{
type = dojo._scopeName + "x.charting.plot2d.Default";
}
collectParams(node, type, kw);
return o;
};
collectActionParams = function(node){
// var plot = d.attr(node, "plot"), type = d.attr(node, "type");
var plot = node.getAttribute("plot"), type = node.getAttribute("type");
if(!plot){ plot = "default"; }
var o = {plot: plot, kwArgs: {}}, kw = o.kwArgs;
if(type){
if(dc.action2d[type]){
type = dojo._scopeName + "x.charting.action2d." + type;
}
var action = eval("(" + type + ")");
if(!action){ return null; }
o.action = action;
}else{
return null;
}
collectParams(node, type, kw);
return o;
};
collectDataParams = function(node){
var ga = lang.partial(html.attr, node);
var name = ga("name");
if(!name){ return null; }
var o = { name: name, kwArgs: {} }, kw = o.kwArgs, t;
t = ga("plot");
if(t != null){ kw.plot = t; }
t = ga("marker");
if(t != null){ kw.marker = t; }
t = ga("stroke");
if(t != null){ kw.stroke = eval("(" + t + ")"); }
t = ga("outline");
if(t != null){ kw.outline = eval("(" + t + ")"); }
t = ga("shadow");
if(t != null){ kw.shadow = eval("(" + t + ")"); }
t = ga("fill");
if(t != null){ kw.fill = eval("(" + t + ")"); }
t = ga("font");
if(t != null){ kw.font = t; }
t = ga("fontColor");
if(t != null){ kw.fontColor = eval("(" + t + ")"); }
t = ga("legend");
if(t != null){ kw.legend = t; }
t = ga("data");
if(t != null){
o.type = "data";
o.data = t ? arr.map(String(t).split(','), Number) : [];
return o;
}
t = ga("array");
if(t != null){
o.type = "data";
o.data = eval("(" + t + ")");
return o;
}
t = ga("store");
if(t != null){
o.type = "store";
o.data = eval("(" + t + ")");
t = ga("field");
o.field = t != null ? t : "value";
t = ga("query");
if(!!t){ kw.query = t; }
t = ga("queryOptions");
if(!!t){ kw.queryOptions = eval("(" + t + ")"); }
t = ga("start");
if(!!t){ kw.start = Number(t); }
t = ga("count");
if(!!t){ kw.count = Number(t); }
t = ga("sort");
if(!!t){ kw.sort = eval("("+t+")"); }
t = ga("valueFn");
if(!!t){ kw.valueFn = dfl.lambda(t); }
return o;
}
return null;
};
return ChartWidget;
});
},
'dojox/lang/functional':function(){
define("dojox/lang/functional", ["./functional/lambda", "./functional/array", "./functional/object"], function(df){
return df;
});
},
'dojox/charting/scaler/common':function(){
define("dojox/charting/scaler/common", ["dojo/_base/lang"], function(lang){
var eq = function(/*Number*/ a, /*Number*/ b){
// summary: compare two FP numbers for equality
return Math.abs(a - b) <= 1e-6 * (Math.abs(a) + Math.abs(b)); // Boolean
};
var common = lang.getObject("dojox.charting.scaler.common", true);
var testedModules = {};
return lang.mixin(common, {
doIfLoaded: function(moduleName, ifloaded, ifnotloaded){
if(testedModules[moduleName] == undefined){
try{
testedModules[moduleName] = require(moduleName);
}catch(e){
testedModules[moduleName] = null;
}
}
if(testedModules[moduleName]){
return ifloaded(testedModules[moduleName]);
}else{
return ifnotloaded();
}
},
findString: function(/*String*/ val, /*Array*/ text){
val = val.toLowerCase();
for(var i = 0; i < text.length; ++i){
if(val == text[i]){ return true; }
}
return false;
},
getNumericLabel: function(/*Number*/ number, /*Number*/ precision, /*Object*/ kwArgs){
var def = "";
common.doIfLoaded("dojo/number", function(numberLib){
def = (kwArgs.fixed ? numberLib.format(number, {places : precision < 0 ? -precision : 0}) :
numberLib.format(number)) || "";
}, function(){
def = kwArgs.fixed ? number.toFixed(precision < 0 ? -precision : 0) : number.toString();
});
if(kwArgs.labelFunc){
var r = kwArgs.labelFunc(def, number, precision);
if(r){ return r; }
// else fall through to the regular labels search
}
if(kwArgs.labels){
// classic binary search
var l = kwArgs.labels, lo = 0, hi = l.length;
while(lo < hi){
var mid = Math.floor((lo + hi) / 2), val = l[mid].value;
if(val < number){
lo = mid + 1;
}else{
hi = mid;
}
}
// lets take into account FP errors
if(lo < l.length && eq(l[lo].value, number)){
return l[lo].text;
}
--lo;
if(lo >= 0 && lo < l.length && eq(l[lo].value, number)){
return l[lo].text;
}
lo += 2;
if(lo < l.length && eq(l[lo].value, number)){
return l[lo].text;
}
// otherwise we will produce a number
}
return def;
}
});
});
},
'dojox/charting/axis2d/common':function(){
define("dojox/charting/axis2d/common", ["dojo/_base/lang", "dojo/_base/html", "dojo/_base/window", "dojo/dom-geometry", "dojox/gfx"],
function(lang, html, win, domGeom, g){
var common = lang.getObject("dojox.charting.axis2d.common", true);
var clearNode = function(s){
s.marginLeft = "0px";
s.marginTop = "0px";
s.marginRight = "0px";
s.marginBottom = "0px";
s.paddingLeft = "0px";
s.paddingTop = "0px";
s.paddingRight = "0px";
s.paddingBottom = "0px";
s.borderLeftWidth = "0px";
s.borderTopWidth = "0px";
s.borderRightWidth = "0px";
s.borderBottomWidth = "0px";
};
var getBoxWidth = function(n){
// marginBox is incredibly slow, so avoid it if we can
if(n["getBoundingClientRect"]){
var bcr = n.getBoundingClientRect();
return bcr.width || (bcr.right - bcr.left);
}else{
return domGeom.getMarginBox(n).w;
}
};
return lang.mixin(common, {
// summary:
// Common methods to be used by any axis. This is considered "static".
createText: {
gfx: function(chart, creator, x, y, align, text, font, fontColor){
// summary:
// Use dojox.gfx to create any text.
// chart: dojox.charting.Chart
// The chart to create the text into.
// creator: dojox.gfx.Surface
// The graphics surface to use for creating the text.
// x: Number
// Where to create the text along the x axis (CSS left).
// y: Number
// Where to create the text along the y axis (CSS top).
// align: String
// How to align the text. Can be "left", "right", "center".
// text: String
// The text to render.
// font: String
// The font definition, a la CSS "font".
// fontColor: String|dojo.Color
// The color of the resultant text.
// returns: dojox.gfx.Text
// The resultant GFX object.
return creator.createText({
x: x, y: y, text: text, align: align
}).setFont(font).setFill(fontColor); // dojox.gfx.Text
},
html: function(chart, creator, x, y, align, text, font, fontColor, labelWidth){
// summary:
// Use the HTML DOM to create any text.
// chart: dojox.charting.Chart
// The chart to create the text into.
// creator: dojox.gfx.Surface
// The graphics surface to use for creating the text.
// x: Number
// Where to create the text along the x axis (CSS left).
// y: Number
// Where to create the text along the y axis (CSS top).
// align: String
// How to align the text. Can be "left", "right", "center".
// text: String
// The text to render.
// font: String
// The font definition, a la CSS "font".
// fontColor: String|dojo.Color
// The color of the resultant text.
// labelWidth: Number?
// The maximum width of the resultant DOM node.
// returns: DOMNode
// The resultant DOMNode (a "div" element).
// setup the text node
var p = win.doc.createElement("div"), s = p.style, boxWidth;
// bidi support, if this function exists the module was loaded
if(chart.getTextDir){
p.dir = chart.getTextDir(text);
}
clearNode(s);
s.font = font;
p.innerHTML = String(text).replace(/\s/g, " ");
s.color = fontColor;
// measure the size
s.position = "absolute";
s.left = "-10000px";
win.body().appendChild(p);
var size = g.normalizedLength(g.splitFontString(font).size);
// do we need to calculate the label width?
if(!labelWidth){
boxWidth = getBoxWidth(p);
}
// when the textDir is rtl, but the UI ltr needs
// to recalculate the starting point
if(p.dir == "rtl"){
x += labelWidth ? labelWidth : boxWidth;
}
// new settings for the text node
win.body().removeChild(p);
s.position = "relative";
if(labelWidth){
s.width = labelWidth + "px";
// s.border = "1px dotted grey";
switch(align){
case "middle":
s.textAlign = "center";
s.left = (x - labelWidth / 2) + "px";
break;
case "end":
s.textAlign = "right";
s.left = (x - labelWidth) + "px";
break;
default:
s.left = x + "px";
s.textAlign = "left";
break;
}
}else{
switch(align){
case "middle":
s.left = Math.floor(x - boxWidth / 2) + "px";
// s.left = Math.floor(x - p.offsetWidth / 2) + "px";
break;
case "end":
s.left = Math.floor(x - boxWidth) + "px";
// s.left = Math.floor(x - p.offsetWidth) + "px";
break;
//case "start":
default:
s.left = Math.floor(x) + "px";
break;
}
}
s.top = Math.floor(y - size) + "px";
s.whiteSpace = "nowrap"; // hack for WebKit
// setup the wrapper node
var wrap = win.doc.createElement("div"), w = wrap.style;
clearNode(w);
w.width = "0px";
w.height = "0px";
// insert nodes
wrap.appendChild(p)
chart.node.insertBefore(wrap, chart.node.firstChild);
return wrap; // DOMNode
}
}
});
});
},
'dijit/_TemplatedMixin':function(){
define("dijit/_TemplatedMixin", [
"dojo/_base/lang", // lang.getObject
"dojo/touch",
"./_WidgetBase",
"dojo/string", // string.substitute string.trim
"dojo/cache", // dojo.cache
"dojo/_base/array", // array.forEach
"dojo/_base/declare", // declare
"dojo/dom-construct", // domConstruct.destroy, domConstruct.toDom
"dojo/_base/sniff", // has("ie")
"dojo/_base/unload", // unload.addOnWindowUnload
"dojo/_base/window" // win.doc
], function(lang, touch, _WidgetBase, string, cache, array, declare, domConstruct, has, unload, win) {
/*=====
var _WidgetBase = dijit._WidgetBase;
=====*/
// module:
// dijit/_TemplatedMixin
// summary:
// Mixin for widgets that are instantiated from a template
var _TemplatedMixin = declare("dijit._TemplatedMixin", null, {
// summary:
// Mixin for widgets that are instantiated from a template
// templateString: [protected] String
// A string that represents the widget template.
// Use in conjunction with dojo.cache() to load from a file.
templateString: null,
// templatePath: [protected deprecated] String
// Path to template (HTML file) for this widget relative to dojo.baseUrl.
// Deprecated: use templateString with require([... "dojo/text!..."], ...) instead
templatePath: null,
// skipNodeCache: [protected] Boolean
// If using a cached widget template nodes poses issues for a
// particular widget class, it can set this property to ensure
// that its template is always re-built from a string
_skipNodeCache: false,
// _earlyTemplatedStartup: Boolean
// A fallback to preserve the 1.0 - 1.3 behavior of children in
// templates having their startup called before the parent widget
// fires postCreate. Defaults to 'false', causing child widgets to
// have their .startup() called immediately before a parent widget
// .startup(), but always after the parent .postCreate(). Set to
// 'true' to re-enable to previous, arguably broken, behavior.
_earlyTemplatedStartup: false,
/*=====
// _attachPoints: [private] String[]
// List of widget attribute names associated with data-dojo-attach-point=... in the
// template, ex: ["containerNode", "labelNode"]
_attachPoints: [],
=====*/
/*=====
// _attachEvents: [private] Handle[]
// List of connections associated with data-dojo-attach-event=... in the
// template
_attachEvents: [],
=====*/
constructor: function(){
this._attachPoints = [];
this._attachEvents = [];
},
_stringRepl: function(tmpl){
// summary:
// Does substitution of ${foo} type properties in template string
// tags:
// private
var className = this.declaredClass, _this = this;
// Cache contains a string because we need to do property replacement
// do the property replacement
return string.substitute(tmpl, this, function(value, key){
if(key.charAt(0) == '!'){ value = lang.getObject(key.substr(1), false, _this); }
if(typeof value == "undefined"){ throw new Error(className+" template:"+key); } // a debugging aide
if(value == null){ return ""; }
// Substitution keys beginning with ! will skip the transform step,
// in case a user wishes to insert unescaped markup, e.g. ${!foo}
return key.charAt(0) == "!" ? value :
// Safer substitution, see heading "Attribute values" in
// http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.3.2
value.toString().replace(/"/g,"""); //TODO: add &? use encodeXML method?
}, this);
},
buildRendering: function(){
// summary:
// Construct the UI for this widget from a template, setting this.domNode.
// tags:
// protected
if(!this.templateString){
this.templateString = cache(this.templatePath, {sanitize: true});
}
// Lookup cached version of template, and download to cache if it
// isn't there already. Returns either a DomNode or a string, depending on
// whether or not the template contains ${foo} replacement parameters.
var cached = _TemplatedMixin.getCachedTemplate(this.templateString, this._skipNodeCache);
var node;
if(lang.isString(cached)){
node = domConstruct.toDom(this._stringRepl(cached));
if(node.nodeType != 1){
// Flag common problems such as templates with multiple top level nodes (nodeType == 11)
throw new Error("Invalid template: " + cached);
}
}else{
// if it's a node, all we have to do is clone it
node = cached.cloneNode(true);
}
this.domNode = node;
// Call down to _Widget.buildRendering() to get base classes assigned
// TODO: change the baseClass assignment to _setBaseClassAttr
this.inherited(arguments);
// recurse through the node, looking for, and attaching to, our
// attachment points and events, which should be defined on the template node.
this._attachTemplateNodes(node, function(n,p){ return n.getAttribute(p); });
this._beforeFillContent(); // hook for _WidgetsInTemplateMixin
this._fillContent(this.srcNodeRef);
},
_beforeFillContent: function(){
},
_fillContent: function(/*DomNode*/ source){
// summary:
// Relocate source contents to templated container node.
// this.containerNode must be able to receive children, or exceptions will be thrown.
// tags:
// protected
var dest = this.containerNode;
if(source && dest){
while(source.hasChildNodes()){
dest.appendChild(source.firstChild);
}
}
},
_attachTemplateNodes: function(rootNode, getAttrFunc){
// summary:
// Iterate through the template and attach functions and nodes accordingly.
// Alternately, if rootNode is an array of widgets, then will process data-dojo-attach-point
// etc. for those widgets.
// description:
// Map widget properties and functions to the handlers specified in
// the dom node and it's descendants. This function iterates over all
// nodes and looks for these properties:
// * dojoAttachPoint/data-dojo-attach-point
// * dojoAttachEvent/data-dojo-attach-event
// rootNode: DomNode|Widget[]
// the node to search for properties. All children will be searched.
// getAttrFunc: Function
// a function which will be used to obtain property for a given
// DomNode/Widget
// tags:
// private
var nodes = lang.isArray(rootNode) ? rootNode : (rootNode.all || rootNode.getElementsByTagName("*"));
var x = lang.isArray(rootNode) ? 0 : -1;
for(; x<nodes.length; x++){
var baseNode = (x == -1) ? rootNode : nodes[x];
if(this.widgetsInTemplate && (getAttrFunc(baseNode, "dojoType") || getAttrFunc(baseNode, "data-dojo-type"))){
continue;
}
// Process data-dojo-attach-point
var attachPoint = getAttrFunc(baseNode, "dojoAttachPoint") || getAttrFunc(baseNode, "data-dojo-attach-point");
if(attachPoint){
var point, points = attachPoint.split(/\s*,\s*/);
while((point = points.shift())){
if(lang.isArray(this[point])){
this[point].push(baseNode);
}else{
this[point]=baseNode;
}
this._attachPoints.push(point);
}
}
// Process data-dojo-attach-event
var attachEvent = getAttrFunc(baseNode, "dojoAttachEvent") || getAttrFunc(baseNode, "data-dojo-attach-event");
if(attachEvent){
// NOTE: we want to support attributes that have the form
// "domEvent: nativeEvent; ..."
var event, events = attachEvent.split(/\s*,\s*/);
var trim = lang.trim;
while((event = events.shift())){
if(event){
var thisFunc = null;
if(event.indexOf(":") != -1){
// oh, if only JS had tuple assignment
var funcNameArr = event.split(":");
event = trim(funcNameArr[0]);
thisFunc = trim(funcNameArr[1]);
}else{
event = trim(event);
}
if(!thisFunc){
thisFunc = event;
}
// Map "press", "move" and "release" to keys.touch, keys.move, keys.release
this._attachEvents.push(this.connect(baseNode, touch[event] || event, thisFunc));
}
}
}
}
},
destroyRendering: function(){
// Delete all attach points to prevent IE6 memory leaks.
array.forEach(this._attachPoints, function(point){
delete this[point];
}, this);
this._attachPoints = [];
// And same for event handlers
array.forEach(this._attachEvents, this.disconnect, this);
this._attachEvents = [];
this.inherited(arguments);
}
});
// key is templateString; object is either string or DOM tree
_TemplatedMixin._templateCache = {};
_TemplatedMixin.getCachedTemplate = function(templateString, alwaysUseString){
// summary:
// Static method to get a template based on the templatePath or
// templateString key
// templateString: String
// The template
// alwaysUseString: Boolean
// Don't cache the DOM tree for this template, even if it doesn't have any variables
// returns: Mixed
// Either string (if there are ${} variables that need to be replaced) or just
// a DOM tree (if the node can be cloned directly)
// is it already cached?
var tmplts = _TemplatedMixin._templateCache;
var key = templateString;
var cached = tmplts[key];
if(cached){
try{
// if the cached value is an innerHTML string (no ownerDocument) or a DOM tree created within the current document, then use the current cached value
if(!cached.ownerDocument || cached.ownerDocument == win.doc){
// string or node of the same document
return cached;
}
}catch(e){ /* squelch */ } // IE can throw an exception if cached.ownerDocument was reloaded
domConstruct.destroy(cached);
}
templateString = string.trim(templateString);
if(alwaysUseString || templateString.match(/\$\{([^\}]+)\}/g)){
// there are variables in the template so all we can do is cache the string
return (tmplts[key] = templateString); //String
}else{
// there are no variables in the template so we can cache the DOM tree
var node = domConstruct.toDom(templateString);
if(node.nodeType != 1){
throw new Error("Invalid template: " + templateString);
}
return (tmplts[key] = node); //Node
}
};
if(has("ie")){
unload.addOnWindowUnload(function(){
var cache = _TemplatedMixin._templateCache;
for(var key in cache){
var value = cache[key];
if(typeof value == "object"){ // value is either a string or a DOM node template
domConstruct.destroy(value);
}
delete cache[key];
}
});
}
// These arguments can be specified for widgets which are used in templates.
// Since any widget can be specified as sub widgets in template, mix it
// into the base widget class. (This is a hack, but it's effective.)
lang.extend(_WidgetBase,{
dojoAttachEvent: "",
dojoAttachPoint: ""
});
return _TemplatedMixin;
});
},
'dojox/lang/functional/object':function(){
define(["dojo/_base/kernel", "dojo/_base/lang", "dojo/_base/window", "./lambda"], function(dojo, lang, win, df){
// This module adds high-level functions and related constructs:
// - object/dictionary helpers
// Defined methods:
// - take any valid lambda argument as the functional argument
// - skip all attributes that are present in the empty object
// (IE and/or 3rd-party libraries).
var empty = {};
/*=====
var df = dojox.lang.functional;
=====*/
lang.mixin(df, {
// object helpers
keys: function(/*Object*/ obj){
// summary: returns an array of all keys in the object
var t = [];
for(var i in obj){
if(!(i in empty)){
t.push(i);
}
}
return t; // Array
},
values: function(/*Object*/ obj){
// summary: returns an array of all values in the object
var t = [];
for(var i in obj){
if(!(i in empty)){
t.push(obj[i]);
}
}
return t; // Array
},
filterIn: function(/*Object*/ obj, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: creates new object with all attributes that pass the test
// implemented by the provided function.
o = o || win.global; f = df.lambda(f);
var t = {}, v, i;
for(i in obj){
if(!(i in empty)){
v = obj[i];
if(f.call(o, v, i, obj)){ t[i] = v; }
}
}
return t; // Object
},
forIn: function(/*Object*/ obj, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: iterates over all object attributes.
o = o || win.global; f = df.lambda(f);
for(var i in obj){
if(!(i in empty)){
f.call(o, obj[i], i, obj);
}
}
return o; // Object
},
mapIn: function(/*Object*/ obj, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: creates new object with the results of calling
// a provided function on every attribute in this object.
o = o || win.global; f = df.lambda(f);
var t = {}, i;
for(i in obj){
if(!(i in empty)){
t[i] = f.call(o, obj[i], i, obj);
}
}
return t; // Object
}
});
return df;
});
},
'dojo/window':function(){
define(["./_base/lang", "./_base/sniff", "./_base/window", "./dom", "./dom-geometry", "./dom-style"],
function(lang, has, baseWindow, dom, geom, style) {
// module:
// dojo/window
// summary:
// TODOC
var window = lang.getObject("dojo.window", true);
/*=====
dojo.window = {
// summary:
// TODO
};
window = dojo.window;
=====*/
window.getBox = function(){
// summary:
// Returns the dimensions and scroll position of the viewable area of a browser window
var
scrollRoot = (baseWindow.doc.compatMode == 'BackCompat') ? baseWindow.body() : baseWindow.doc.documentElement,
// get scroll position
scroll = geom.docScroll(), // scrollRoot.scrollTop/Left should work
w, h;
if(has("touch")){ // if(scrollbars not supported)
var uiWindow = baseWindow.doc.parentWindow || baseWindow.doc.defaultView; // use UI window, not dojo.global window. baseWindow.doc.parentWindow probably not needed since it's not defined for webkit
// on mobile, scrollRoot.clientHeight <= uiWindow.innerHeight <= scrollRoot.offsetHeight, return uiWindow.innerHeight
w = uiWindow.innerWidth || scrollRoot.clientWidth; // || scrollRoot.clientXXX probably never evaluated
h = uiWindow.innerHeight || scrollRoot.clientHeight;
}else{
// on desktops, scrollRoot.clientHeight <= scrollRoot.offsetHeight <= uiWindow.innerHeight, return scrollRoot.clientHeight
// uiWindow.innerWidth/Height includes the scrollbar and cannot be used
w = scrollRoot.clientWidth;
h = scrollRoot.clientHeight;
}
return {
l: scroll.x,
t: scroll.y,
w: w,
h: h
};
};
window.get = function(doc){
// summary:
// Get window object associated with document doc
// In some IE versions (at least 6.0), document.parentWindow does not return a
// reference to the real window object (maybe a copy), so we must fix it as well
// We use IE specific execScript to attach the real window reference to
// document._parentWindow for later use
if(has("ie") && window !== document.parentWindow){
/*
In IE 6, only the variable "window" can be used to connect events (others
may be only copies).
*/
doc.parentWindow.execScript("document._parentWindow = window;", "Javascript");
//to prevent memory leak, unset it after use
//another possibility is to add an onUnload handler which seems overkill to me (liucougar)
var win = doc._parentWindow;
doc._parentWindow = null;
return win; // Window
}
return doc.parentWindow || doc.defaultView; // Window
};
window.scrollIntoView = function(/*DomNode*/ node, /*Object?*/ pos){
// summary:
// Scroll the passed node into view, if it is not already.
// don't rely on node.scrollIntoView working just because the function is there
try{ // catch unexpected/unrecreatable errors (#7808) since we can recover using a semi-acceptable native method
node = dom.byId(node);
var doc = node.ownerDocument || baseWindow.doc,
body = doc.body || baseWindow.body(),
html = doc.documentElement || body.parentNode,
isIE = has("ie"), isWK = has("webkit");
// if an untested browser, then use the native method
if((!(has("mozilla") || isIE || isWK || has("opera")) || node == body || node == html) && (typeof node.scrollIntoView != "undefined")){
node.scrollIntoView(false); // short-circuit to native if possible
return;
}
var backCompat = doc.compatMode == 'BackCompat',
clientAreaRoot = (isIE >= 9 && node.ownerDocument.parentWindow.frameElement)
? ((html.clientHeight > 0 && html.clientWidth > 0 && (body.clientHeight == 0 || body.clientWidth == 0 || body.clientHeight > html.clientHeight || body.clientWidth > html.clientWidth)) ? html : body)
: (backCompat ? body : html),
scrollRoot = isWK ? body : clientAreaRoot,
rootWidth = clientAreaRoot.clientWidth,
rootHeight = clientAreaRoot.clientHeight,
rtl = !geom.isBodyLtr(),
nodePos = pos || geom.position(node),
el = node.parentNode,
isFixed = function(el){
return ((isIE <= 6 || (isIE && backCompat))? false : (style.get(el, 'position').toLowerCase() == "fixed"));
};
if(isFixed(node)){ return; } // nothing to do
while(el){
if(el == body){ el = scrollRoot; }
var elPos = geom.position(el),
fixedPos = isFixed(el);
if(el == scrollRoot){
elPos.w = rootWidth; elPos.h = rootHeight;
if(scrollRoot == html && isIE && rtl){ elPos.x += scrollRoot.offsetWidth-elPos.w; } // IE workaround where scrollbar causes negative x
if(elPos.x < 0 || !isIE){ elPos.x = 0; } // IE can have values > 0
if(elPos.y < 0 || !isIE){ elPos.y = 0; }
}else{
var pb = geom.getPadBorderExtents(el);
elPos.w -= pb.w; elPos.h -= pb.h; elPos.x += pb.l; elPos.y += pb.t;
var clientSize = el.clientWidth,
scrollBarSize = elPos.w - clientSize;
if(clientSize > 0 && scrollBarSize > 0){
elPos.w = clientSize;
elPos.x += (rtl && (isIE || el.clientLeft > pb.l/*Chrome*/)) ? scrollBarSize : 0;
}
clientSize = el.clientHeight;
scrollBarSize = elPos.h - clientSize;
if(clientSize > 0 && scrollBarSize > 0){
elPos.h = clientSize;
}
}
if(fixedPos){ // bounded by viewport, not parents
if(elPos.y < 0){
elPos.h += elPos.y; elPos.y = 0;
}
if(elPos.x < 0){
elPos.w += elPos.x; elPos.x = 0;
}
if(elPos.y + elPos.h > rootHeight){
elPos.h = rootHeight - elPos.y;
}
if(elPos.x + elPos.w > rootWidth){
elPos.w = rootWidth - elPos.x;
}
}
// calculate overflow in all 4 directions
var l = nodePos.x - elPos.x, // beyond left: < 0
t = nodePos.y - Math.max(elPos.y, 0), // beyond top: < 0
r = l + nodePos.w - elPos.w, // beyond right: > 0
bot = t + nodePos.h - elPos.h; // beyond bottom: > 0
if(r * l > 0){
var s = Math[l < 0? "max" : "min"](l, r);
if(rtl && ((isIE == 8 && !backCompat) || isIE >= 9)){ s = -s; }
nodePos.x += el.scrollLeft;
el.scrollLeft += s;
nodePos.x -= el.scrollLeft;
}
if(bot * t > 0){
nodePos.y += el.scrollTop;
el.scrollTop += Math[t < 0? "max" : "min"](t, bot);
nodePos.y -= el.scrollTop;
}
el = (el != scrollRoot) && !fixedPos && el.parentNode;
}
}catch(error){
console.error('scrollIntoView: ' + error);
node.scrollIntoView(false);
}
};
return window;
});
},
'dojox/charting/axis2d/Default':function(){
define("dojox/charting/axis2d/Default", ["dojo/_base/lang", "dojo/_base/array","dojo/_base/sniff", "dojo/_base/declare",
"dojo/_base/connect", "dojo/_base/html", "dojo/dom-geometry", "./Invisible",
"../scaler/common", "../scaler/linear", "./common", "dojox/gfx", "dojox/lang/utils"],
function(lang, arr, has, declare, connect, html, domGeom, Invisible, scommon,
lin, acommon, g, du){
/*=====
dojox.charting.axis2d.__AxisCtorArgs = function(
vertical, fixUpper, fixLower, natural, leftBottom,
includeZero, fixed, majorLabels, minorTicks, minorLabels, microTicks, htmlLabels,
min, max, from, to, majorTickStep, minorTickStep, microTickStep,
labels, labelFunc, maxLabelSize,
stroke, majorTick, minorTick, microTick, tick,
font, fontColor
){
// summary:
// Optional arguments used in the definition of an axis.
//
// vertical: Boolean?
// A flag that says whether an axis is vertical (i.e. y axis) or horizontal. Default is false (horizontal).
// fixUpper: String?
// Align the greatest value on the axis with the specified tick level. Options are "major", "minor", "micro", or "none". Defaults to "none".
// fixLower: String?
// Align the smallest value on the axis with the specified tick level. Options are "major", "minor", "micro", or "none". Defaults to "none".
// natural: Boolean?
// Ensure tick marks are made on "natural" numbers. Defaults to false.
// leftBottom: Boolean?
// The position of a vertical axis; if true, will be placed against the left-bottom corner of the chart. Defaults to true.
// includeZero: Boolean?
// Include 0 on the axis rendering. Default is false.
// fixed: Boolean?
// Force all axis labels to be fixed numbers. Default is true.
// majorLabels: Boolean?
// Flag to draw all labels at major ticks. Default is true.
// minorTicks: Boolean?
// Flag to draw minor ticks on an axis. Default is true.
// minorLabels: Boolean?
// Flag to draw labels on minor ticks. Default is true.
// microTicks: Boolean?
// Flag to draw micro ticks on an axis. Default is false.
// htmlLabels: Boolean?
// Flag to use HTML (as opposed to the native vector graphics engine) to draw labels. Default is true.
// min: Number?
// The smallest value on an axis. Default is 0.
// max: Number?
// The largest value on an axis. Default is 1.
// from: Number?
// Force the chart to render data visible from this value. Default is 0.
// to: Number?
// Force the chart to render data visible to this value. Default is 1.
// majorTickStep: Number?
// The amount to skip before a major tick is drawn. Default is 4.
// minorTickStep: Number?
// The amount to skip before a minor tick is drawn. Default is 2.
// microTickStep: Number?
// The amount to skip before a micro tick is drawn. Default is 1.
// labels: Object[]?
// An array of labels for major ticks, with corresponding numeric values, ordered by value.
// labelFunc: Function?
// An optional function used to compute label values.
// maxLabelSize: Number?
// The maximum size, in pixels, for a label. To be used with the optional label function.
// stroke: dojox.gfx.Stroke?
// An optional stroke to be used for drawing an axis.
// majorTick: Object?
// An object containing a dojox.gfx.Stroke, and a length (number) for a major tick.
// minorTick: Object?
// An object containing a dojox.gfx.Stroke, and a length (number) for a minor tick.
// microTick: Object?
// An object containing a dojox.gfx.Stroke, and a length (number) for a micro tick.
// tick: Object?
// An object containing a dojox.gfx.Stroke, and a length (number) for a tick.
// font: String?
// An optional font definition (as used in the CSS font property) for labels.
// fontColor: String|dojo.Color?
// An optional color to be used in drawing labels.
// enableCache: Boolean?
// Whether the ticks and labels are cached from one rendering to another. This improves the rendering performance of
// successive rendering but penalize the first rendering. For labels it is only working with gfx labels
// not html ones. Default false.
this.vertical = vertical;
this.fixUpper = fixUpper;
this.fixLower = fixLower;
this.natural = natural;
this.leftBottom = leftBottom;
this.includeZero = includeZero;
this.fixed = fixed;
this.majorLabels = majorLabels;
this.minorTicks = minorTicks;
this.minorLabels = minorLabels;
this.microTicks = microTicks;
this.htmlLabels = htmlLabels;
this.min = min;
this.max = max;
this.from = from;
this.to = to;
this.majorTickStep = majorTickStep;
this.minorTickStep = minorTickStep;
this.microTickStep = microTickStep;
this.labels = labels;
this.labelFunc = labelFunc;
this.maxLabelSize = maxLabelSize;
this.stroke = stroke;
this.majorTick = majorTick;
this.minorTick = minorTick;
this.microTick = microTick;
this.tick = tick;
this.font = font;
this.fontColor = fontColor;
this.enableCache = enableCache;
}
var Invisible = dojox.charting.axis2d.Invisible
=====*/
var labelGap = 4, // in pixels
centerAnchorLimit = 45; // in degrees
return declare("dojox.charting.axis2d.Default", Invisible, {
// summary:
// The default axis object used in dojox.charting. See dojox.charting.Chart.addAxis for details.
//
// defaultParams: Object
// The default parameters used to define any axis.
// optionalParams: Object
// Any optional parameters needed to define an axis.
/*
// TODO: the documentation tools need these to be pre-defined in order to pick them up
// correctly, but the code here is partially predicated on whether or not the properties
// actually exist. For now, we will leave these undocumented but in the code for later. -- TRT
// opt: Object
// The actual options used to define this axis, created at initialization.
// scalar: Object
// The calculated helper object to tell charts how to draw an axis and any data.
// ticks: Object
// The calculated tick object that helps a chart draw the scaling on an axis.
// dirty: Boolean
// The state of the axis (whether it needs to be redrawn or not)
// scale: Number
// The current scale of the axis.
// offset: Number
// The current offset of the axis.
opt: null,
scalar: null,
ticks: null,
dirty: true,
scale: 1,
offset: 0,
*/
defaultParams: {
vertical: false, // true for vertical axis
fixUpper: "none", // align the upper on ticks: "major", "minor", "micro", "none"
fixLower: "none", // align the lower on ticks: "major", "minor", "micro", "none"
natural: false, // all tick marks should be made on natural numbers
leftBottom: true, // position of the axis, used with "vertical"
includeZero: false, // 0 should be included
fixed: true, // all labels are fixed numbers
majorLabels: true, // draw major labels
minorTicks: true, // draw minor ticks
minorLabels: true, // draw minor labels
microTicks: false, // draw micro ticks
rotation: 0, // label rotation angle in degrees
htmlLabels: true, // use HTML to draw labels
enableCache: false // whether we cache or not
},
optionalParams: {
min: 0, // minimal value on this axis
max: 1, // maximal value on this axis
from: 0, // visible from this value
to: 1, // visible to this value
majorTickStep: 4, // major tick step
minorTickStep: 2, // minor tick step
microTickStep: 1, // micro tick step
labels: [], // array of labels for major ticks
// with corresponding numeric values
// ordered by values
labelFunc: null, // function to compute label values
maxLabelSize: 0, // size in px. For use with labelFunc
maxLabelCharCount: 0, // size in word count.
trailingSymbol: null,
// TODO: add support for minRange!
// minRange: 1, // smallest distance from min allowed on the axis
// theme components
stroke: {}, // stroke for an axis
majorTick: {}, // stroke + length for a tick
minorTick: {}, // stroke + length for a tick
microTick: {}, // stroke + length for a tick
tick: {}, // stroke + length for a tick
font: "", // font for labels
fontColor: "", // color for labels as a string
title: "", // axis title
titleGap: 0, // gap between axis title and axis label
titleFont: "", // axis title font
titleFontColor: "", // axis title font color
titleOrientation: "" // "axis" means the title facing the axis, "away" means facing away
},
constructor: function(chart, kwArgs){
// summary:
// The constructor for an axis.
// chart: dojox.charting.Chart
// The chart the axis belongs to.
// kwArgs: dojox.charting.axis2d.__AxisCtorArgs?
// Any optional keyword arguments to be used to define this axis.
this.opt = lang.clone(this.defaultParams);
du.updateWithObject(this.opt, kwArgs);
du.updateWithPattern(this.opt, kwArgs, this.optionalParams);
if(this.opt.enableCache){
this._textFreePool = [];
this._lineFreePool = [];
this._textUsePool = [];
this._lineUsePool = [];
}
},
getOffsets: function(){
// summary:
// Get the physical offset values for this axis (used in drawing data series).
// returns: Object
// The calculated offsets in the form of { l, r, t, b } (left, right, top, bottom).
var s = this.scaler, offsets = { l: 0, r: 0, t: 0, b: 0 };
if(!s){
return offsets;
}
var o = this.opt, labelWidth = 0, a, b, c, d,
gl = scommon.getNumericLabel,
offset = 0, ma = s.major, mi = s.minor,
ta = this.chart.theme.axis,
// TODO: we use one font --- of major tick, we need to use major and minor fonts
taFont = o.font || (ta.majorTick && ta.majorTick.font) || (ta.tick && ta.tick.font),
taTitleFont = o.titleFont || (ta.tick && ta.tick.titleFont),
taTitleGap = (o.titleGap==0) ? 0 : o.titleGap || (ta.tick && ta.tick.titleGap) || 15,
taMajorTick = this.chart.theme.getTick("major", o),
taMinorTick = this.chart.theme.getTick("minor", o),
size = taFont ? g.normalizedLength(g.splitFontString(taFont).size) : 0,
tsize = taTitleFont ? g.normalizedLength(g.splitFontString(taTitleFont).size) : 0,
rotation = o.rotation % 360, leftBottom = o.leftBottom,
cosr = Math.abs(Math.cos(rotation * Math.PI / 180)),
sinr = Math.abs(Math.sin(rotation * Math.PI / 180));
this.trailingSymbol = (o.trailingSymbol === undefined || o.trailingSymbol === null) ? this.trailingSymbol : o.trailingSymbol;
if(rotation < 0){
rotation += 360;
}
if(size){
// we need width of all labels
if(this.labels){
labelWidth = this._groupLabelWidth(this.labels, taFont, o.maxLabelCharCount);
}else{
labelWidth = this._groupLabelWidth([
gl(ma.start, ma.prec, o),
gl(ma.start + ma.count * ma.tick, ma.prec, o),
gl(mi.start, mi.prec, o),
gl(mi.start + mi.count * mi.tick, mi.prec, o)
], taFont, o.maxLabelCharCount);
}
labelWidth = o.maxLabelSize ? Math.min(o.maxLabelSize, labelWidth) : labelWidth;
if(this.vertical){
var side = leftBottom ? "l" : "r";
switch(rotation){
case 0:
case 180:
offsets[side] = labelWidth;
offsets.t = offsets.b = size / 2;
break;
case 90:
case 270:
offsets[side] = size;
offsets.t = offsets.b = labelWidth / 2;
break;
default:
if(rotation <= centerAnchorLimit || (180 < rotation && rotation <= (180 + centerAnchorLimit))){
offsets[side] = size * sinr / 2 + labelWidth * cosr;
offsets[leftBottom ? "t" : "b"] = size * cosr / 2 + labelWidth * sinr;
offsets[leftBottom ? "b" : "t"] = size * cosr / 2;
}else if(rotation > (360 - centerAnchorLimit) || (180 > rotation && rotation > (180 - centerAnchorLimit))){
offsets[side] = size * sinr / 2 + labelWidth * cosr;
offsets[leftBottom ? "b" : "t"] = size * cosr / 2 + labelWidth * sinr;
offsets[leftBottom ? "t" : "b"] = size * cosr / 2;
}else if(rotation < 90 || (180 < rotation && rotation < 270)){
offsets[side] = size * sinr + labelWidth * cosr;
offsets[leftBottom ? "t" : "b"] = size * cosr + labelWidth * sinr;
}else{
offsets[side] = size * sinr + labelWidth * cosr;
offsets[leftBottom ? "b" : "t"] = size * cosr + labelWidth * sinr;
}
break;
}
offsets[side] += labelGap + Math.max(taMajorTick.length, taMinorTick.length) + (o.title ? (tsize + taTitleGap) : 0);
}else{
var side = leftBottom ? "b" : "t";
switch(rotation){
case 0:
case 180:
offsets[side] = size;
offsets.l = offsets.r = labelWidth / 2;
break;
case 90:
case 270:
offsets[side] = labelWidth;
offsets.l = offsets.r = size / 2;
break;
default:
if((90 - centerAnchorLimit) <= rotation && rotation <= 90 || (270 - centerAnchorLimit) <= rotation && rotation <= 270){
offsets[side] = size * sinr / 2 + labelWidth * cosr;
offsets[leftBottom ? "r" : "l"] = size * cosr / 2 + labelWidth * sinr;
offsets[leftBottom ? "l" : "r"] = size * cosr / 2;
}else if(90 <= rotation && rotation <= (90 + centerAnchorLimit) || 270 <= rotation && rotation <= (270 + centerAnchorLimit)){
offsets[side] = size * sinr / 2 + labelWidth * cosr;
offsets[leftBottom ? "l" : "r"] = size * cosr / 2 + labelWidth * sinr;
offsets[leftBottom ? "r" : "l"] = size * cosr / 2;
}else if(rotation < centerAnchorLimit || (180 < rotation && rotation < (180 - centerAnchorLimit))){
offsets[side] = size * sinr + labelWidth * cosr;
offsets[leftBottom ? "r" : "l"] = size * cosr + labelWidth * sinr;
}else{
offsets[side] = size * sinr + labelWidth * cosr;
offsets[leftBottom ? "l" : "r"] = size * cosr + labelWidth * sinr;
}
break;
}
offsets[side] += labelGap + Math.max(taMajorTick.length, taMinorTick.length) + (o.title ? (tsize + taTitleGap) : 0);
}
}
if(labelWidth){
this._cachedLabelWidth = labelWidth;
}
return offsets; // Object
},
cleanGroup: function(creator){
if(this.opt.enableCache && this.group){
this._lineFreePool = this._lineFreePool.concat(this._lineUsePool);
this._lineUsePool = [];
this._textFreePool = this._textFreePool.concat(this._textUsePool);
this._textUsePool = [];
}
this.inherited(arguments);
},
createText: function(labelType, creator, x, y, align, textContent, font, fontColor, labelWidth){
if(!this.opt.enableCache || labelType=="html"){
return acommon.createText[labelType](
this.chart,
creator,
x,
y,
align,
textContent,
font,
fontColor,
labelWidth
);
}
var text;
if (this._textFreePool.length > 0){
text = this._textFreePool.pop();
text.setShape({x: x, y: y, text: textContent, align: align});
// For now all items share the same font, no need to re-set it
//.setFont(font).setFill(fontColor);
// was cleared, add it back
creator.add(text);
}else{
text = acommon.createText[labelType](
this.chart,
creator,
x,
y,
align,
textContent,
font,
fontColor,
labelWidth
); }
this._textUsePool.push(text);
return text;
},
createLine: function(creator, params){
var line;
if(this.opt.enableCache && this._lineFreePool.length > 0){
line = this._lineFreePool.pop();
line.setShape(params);
// was cleared, add it back
creator.add(line);
}else{
line = creator.createLine(params);
}
if(this.opt.enableCache){
this._lineUsePool.push(line);
}
return line;
},
render: function(dim, offsets){
// summary:
// Render/draw the axis.
// dim: Object
// An object of the form { width, height}.
// offsets: Object
// An object of the form { l, r, t, b }.
// returns: dojox.charting.axis2d.Default
// The reference to the axis for functional chaining.
if(!this.dirty){
return this; // dojox.charting.axis2d.Default
}
// prepare variable
var o = this.opt, ta = this.chart.theme.axis, leftBottom = o.leftBottom, rotation = o.rotation % 360,
start, stop, titlePos, titleRotation=0, titleOffset, axisVector, tickVector, anchorOffset, labelOffset, labelAlign,
// TODO: we use one font --- of major tick, we need to use major and minor fonts
taFont = o.font || (ta.majorTick && ta.majorTick.font) || (ta.tick && ta.tick.font),
taTitleFont = o.titleFont || (ta.tick && ta.tick.titleFont),
// TODO: we use one font color --- we need to use different colors
taFontColor = o.fontColor || (ta.majorTick && ta.majorTick.fontColor) || (ta.tick && ta.tick.fontColor) || "black",
taTitleFontColor = o.titleFontColor || (ta.tick && ta.tick.titleFontColor) || "black",
taTitleGap = (o.titleGap==0) ? 0 : o.titleGap || (ta.tick && ta.tick.titleGap) || 15,
taTitleOrientation = o.titleOrientation || (ta.tick && ta.tick.titleOrientation) || "axis",
taMajorTick = this.chart.theme.getTick("major", o),
taMinorTick = this.chart.theme.getTick("minor", o),
taMicroTick = this.chart.theme.getTick("micro", o),
tickSize = Math.max(taMajorTick.length, taMinorTick.length, taMicroTick.length),
taStroke = "stroke" in o ? o.stroke : ta.stroke,
size = taFont ? g.normalizedLength(g.splitFontString(taFont).size) : 0,
cosr = Math.abs(Math.cos(rotation * Math.PI / 180)),
sinr = Math.abs(Math.sin(rotation * Math.PI / 180)),
tsize = taTitleFont ? g.normalizedLength(g.splitFontString(taTitleFont).size) : 0;
if(rotation < 0){
rotation += 360;
}
if(this.vertical){
start = {y: dim.height - offsets.b};
stop = {y: offsets.t};
titlePos = {y: (dim.height - offsets.b + offsets.t)/2};
titleOffset = size * sinr + (this._cachedLabelWidth || 0) * cosr + labelGap + Math.max(taMajorTick.length, taMinorTick.length) + tsize + taTitleGap;
axisVector = {x: 0, y: -1};
labelOffset = {x: 0, y: 0};
tickVector = {x: 1, y: 0};
anchorOffset = {x: labelGap, y: 0};
switch(rotation){
case 0:
labelAlign = "end";
labelOffset.y = size * 0.4;
break;
case 90:
labelAlign = "middle";
labelOffset.x = -size;
break;
case 180:
labelAlign = "start";
labelOffset.y = -size * 0.4;
break;
case 270:
labelAlign = "middle";
break;
default:
if(rotation < centerAnchorLimit){
labelAlign = "end";
labelOffset.y = size * 0.4;
}else if(rotation < 90){
labelAlign = "end";
labelOffset.y = size * 0.4;
}else if(rotation < (180 - centerAnchorLimit)){
labelAlign = "start";
}else if(rotation < (180 + centerAnchorLimit)){
labelAlign = "start";
labelOffset.y = -size * 0.4;
}else if(rotation < 270){
labelAlign = "start";
labelOffset.x = leftBottom ? 0 : size * 0.4;
}else if(rotation < (360 - centerAnchorLimit)){
labelAlign = "end";
labelOffset.x = leftBottom ? 0 : size * 0.4;
}else{
labelAlign = "end";
labelOffset.y = size * 0.4;
}
}
if(leftBottom){
start.x = stop.x = offsets.l;
titleRotation = (taTitleOrientation && taTitleOrientation == "away") ? 90 : 270;
titlePos.x = offsets.l - titleOffset + (titleRotation == 270 ? tsize : 0);
tickVector.x = -1;
anchorOffset.x = -anchorOffset.x;
}else{
start.x = stop.x = dim.width - offsets.r;
titleRotation = (taTitleOrientation && taTitleOrientation == "axis") ? 90 : 270;
titlePos.x = dim.width - offsets.r + titleOffset - (titleRotation == 270 ? 0 : tsize);
switch(labelAlign){
case "start":
labelAlign = "end";
break;
case "end":
labelAlign = "start";
break;
case "middle":
labelOffset.x += size;
break;
}
}
}else{
start = {x: offsets.l};
stop = {x: dim.width - offsets.r};
titlePos = {x: (dim.width - offsets.r + offsets.l)/2};
titleOffset = size * cosr + (this._cachedLabelWidth || 0) * sinr + labelGap + Math.max(taMajorTick.length, taMinorTick.length) + tsize + taTitleGap;
axisVector = {x: 1, y: 0};
labelOffset = {x: 0, y: 0};
tickVector = {x: 0, y: 1};
anchorOffset = {x: 0, y: labelGap};
switch(rotation){
case 0:
labelAlign = "middle";
labelOffset.y = size;
break;
case 90:
labelAlign = "start";
labelOffset.x = -size * 0.4;
break;
case 180:
labelAlign = "middle";
break;
case 270:
labelAlign = "end";
labelOffset.x = size * 0.4;
break;
default:
if(rotation < (90 - centerAnchorLimit)){
labelAlign = "start";
labelOffset.y = leftBottom ? size : 0;
}else if(rotation < (90 + centerAnchorLimit)){
labelAlign = "start";
labelOffset.x = -size * 0.4;
}else if(rotation < 180){
labelAlign = "start";
labelOffset.y = leftBottom ? 0 : -size;
}else if(rotation < (270 - centerAnchorLimit)){
labelAlign = "end";
labelOffset.y = leftBottom ? 0 : -size;
}else if(rotation < (270 + centerAnchorLimit)){
labelAlign = "end";
labelOffset.y = leftBottom ? size * 0.4 : 0;
}else{
labelAlign = "end";
labelOffset.y = leftBottom ? size : 0;
}
}
if(leftBottom){
start.y = stop.y = dim.height - offsets.b;
titleRotation = (taTitleOrientation && taTitleOrientation == "axis") ? 180 : 0;
titlePos.y = dim.height - offsets.b + titleOffset - (titleRotation ? tsize : 0);
}else{
start.y = stop.y = offsets.t;
titleRotation = (taTitleOrientation && taTitleOrientation == "away") ? 180 : 0;
titlePos.y = offsets.t - titleOffset + (titleRotation ? 0 : tsize);
tickVector.y = -1;
anchorOffset.y = -anchorOffset.y;
switch(labelAlign){
case "start":
labelAlign = "end";
break;
case "end":
labelAlign = "start";
break;
case "middle":
labelOffset.y -= size;
break;
}
}
}
// render shapes
this.cleanGroup();
try{
var s = this.group,
c = this.scaler,
t = this.ticks,
canLabel,
f = lin.getTransformerFromModel(this.scaler),
// GFX Canvas now supports labels, so let's _not_ fallback to HTML anymore on canvas, just use
// HTML labels if explicitly asked + no rotation + no IE + no Opera
labelType = (!o.title || !titleRotation) && !rotation && this.opt.htmlLabels && !has("ie") && !has("opera") ? "html" : "gfx",
dx = tickVector.x * taMajorTick.length,
dy = tickVector.y * taMajorTick.length;
s.createLine({
x1: start.x,
y1: start.y,
x2: stop.x,
y2: stop.y
}).setStroke(taStroke);
//create axis title
if(o.title){
var axisTitle = acommon.createText[labelType](
this.chart,
s,
titlePos.x,
titlePos.y,
"middle",
o.title,
taTitleFont,
taTitleFontColor
);
if(labelType == "html"){
this.htmlElements.push(axisTitle);
}else{
//as soon as rotation is provided, labelType won't be "html"
//rotate gfx labels
axisTitle.setTransform(g.matrix.rotategAt(titleRotation, titlePos.x, titlePos.y));
}
}
// go out nicely instead of try/catch
if(t==null){
this.dirty = false;
return this;
}
arr.forEach(t.major, function(tick){
var offset = f(tick.value), elem,
x = start.x + axisVector.x * offset,
y = start.y + axisVector.y * offset;
this.createLine(s, {
x1: x, y1: y,
x2: x + dx,
y2: y + dy
}).setStroke(taMajorTick);
if(tick.label){
var label = o.maxLabelCharCount ? this.getTextWithLimitCharCount(tick.label, taFont, o.maxLabelCharCount) : {
text: tick.label,
truncated: false
};
label = o.maxLabelSize ? this.getTextWithLimitLength(label.text, taFont, o.maxLabelSize, label.truncated) : label;
elem = this.createText(labelType,
s,
x + dx + anchorOffset.x + (rotation ? 0 : labelOffset.x),
y + dy + anchorOffset.y + (rotation ? 0 : labelOffset.y),
labelAlign,
label.text,
taFont,
taFontColor
//this._cachedLabelWidth
);
// if bidi support was required, the textDir is "auto" and truncation
// took place, we need to update the dir of the element for cases as:
// Fool label: 111111W (W for bidi character)
// truncated label: 11...
// in this case for auto textDir the dir will be "ltr" which is wrong.
if(this.chart.truncateBidi && label.truncated){
this.chart.truncateBidi(elem, tick.label, labelType);
}
label.truncated && this.labelTooltip(elem, this.chart, tick.label, label.text, taFont, labelType);
if(labelType == "html"){
this.htmlElements.push(elem);
}else if(rotation){
elem.setTransform([
{dx: labelOffset.x, dy: labelOffset.y},
g.matrix.rotategAt(
rotation,
x + dx + anchorOffset.x,
y + dy + anchorOffset.y
)
]);
}
}
}, this);
dx = tickVector.x * taMinorTick.length;
dy = tickVector.y * taMinorTick.length;
canLabel = c.minMinorStep <= c.minor.tick * c.bounds.scale;
arr.forEach(t.minor, function(tick){
var offset = f(tick.value), elem,
x = start.x + axisVector.x * offset,
y = start.y + axisVector.y * offset;
this.createLine(s, {
x1: x, y1: y,
x2: x + dx,
y2: y + dy
}).setStroke(taMinorTick);
if(canLabel && tick.label){
var label = o.maxLabelCharCount ? this.getTextWithLimitCharCount(tick.label, taFont, o.maxLabelCharCount) : {
text: tick.label,
truncated: false
};
label = o.maxLabelSize ? this.getTextWithLimitLength(label.text, taFont, o.maxLabelSize, label.truncated) : label;
elem = this.createText(labelType,
s,
x + dx + anchorOffset.x + (rotation ? 0 : labelOffset.x),
y + dy + anchorOffset.y + (rotation ? 0 : labelOffset.y),
labelAlign,
label.text,
taFont,
taFontColor
//this._cachedLabelWidth
);
// if bidi support was required, the textDir is "auto" and truncation
// took place, we need to update the dir of the element for cases as:
// Fool label: 111111W (W for bidi character)
// truncated label: 11...
// in this case for auto textDir the dir will be "ltr" which is wrong.
if(this.chart.getTextDir && label.truncated){
this.chart.truncateBidi(elem, tick.label, labelType);
}
label.truncated && this.labelTooltip(elem, this.chart, tick.label, label.text, taFont, labelType);
if(labelType == "html"){
this.htmlElements.push(elem);
}else if(rotation){
elem.setTransform([
{dx: labelOffset.x, dy: labelOffset.y},
g.matrix.rotategAt(
rotation,
x + dx + anchorOffset.x,
y + dy + anchorOffset.y
)
]);
}
}
}, this);
dx = tickVector.x * taMicroTick.length;
dy = tickVector.y * taMicroTick.length;
arr.forEach(t.micro, function(tick){
var offset = f(tick.value), elem,
x = start.x + axisVector.x * offset,
y = start.y + axisVector.y * offset;
this.createLine(s, {
x1: x, y1: y,
x2: x + dx,
y2: y + dy
}).setStroke(taMicroTick);
}, this);
}catch(e){
// squelch
}
this.dirty = false;
return this; // dojox.charting.axis2d.Default
},
labelTooltip: function(elem, chart, label, truncatedLabel, font, elemType){
var modules = ["dijit/Tooltip"];
var aroundRect = {type: "rect"}, position = ["above", "below"],
fontWidth = g._base._getTextBox(truncatedLabel, {font: font}).w || 0,
fontHeight = font ? g.normalizedLength(g.splitFontString(font).size) : 0;
if(elemType == "html"){
lang.mixin(aroundRect, html.coords(elem.firstChild, true));
aroundRect.width = Math.ceil(fontWidth);
aroundRect.height = Math.ceil(fontHeight);
this._events.push({
shape: dojo,
handle: connect.connect(elem.firstChild, "onmouseover", this, function(e){
require(modules, function(Tooltip){
Tooltip.show(label, aroundRect, position);
});
})
});
this._events.push({
shape: dojo,
handle: connect.connect(elem.firstChild, "onmouseout", this, function(e){
require(modules, function(Tooltip){
Tooltip.hide(aroundRect);
});
})
});
}else{
var shp = elem.getShape(),
lt = html.coords(chart.node, true);
aroundRect = lang.mixin(aroundRect, {
x: shp.x - fontWidth / 2,
y: shp.y
});
aroundRect.x += lt.x;
aroundRect.y += lt.y;
aroundRect.x = Math.round(aroundRect.x);
aroundRect.y = Math.round(aroundRect.y);
aroundRect.width = Math.ceil(fontWidth);
aroundRect.height = Math.ceil(fontHeight);
this._events.push({
shape: elem,
handle: elem.connect("onmouseenter", this, function(e){
require(modules, function(Tooltip){
Tooltip.show(label, aroundRect, position);
});
})
});
this._events.push({
shape: elem,
handle: elem.connect("onmouseleave", this, function(e){
require(modules, function(Tooltip){
Tooltip.hide(aroundRect);
});
})
});
}
}
});
});
},
'dojox/charting/plot2d/ClusteredBars':function(){
define("dojox/charting/plot2d/ClusteredBars", ["dojo/_base/lang", "dojo/_base/array", "dojo/_base/declare", "./Bars", "./common",
"dojox/lang/functional", "dojox/lang/functional/reversed", "dojox/lang/utils"],
function(lang, arr, declare, Bars, dc, df, dfr, du){
/*=====
var Bars = dojox.charting.plot2d.Bars;
=====*/
var purgeGroup = dfr.lambda("item.purgeGroup()");
return declare("dojox.charting.plot2d.ClusteredBars", Bars, {
// summary:
// A plot representing grouped or clustered bars (horizontal bars)
render: function(dim, offsets){
// summary:
// Run the calculations for any axes for this plot.
// dim: Object
// An object in the form of { width, height }
// offsets: Object
// An object of the form { l, r, t, b}.
// returns: dojox.charting.plot2d.ClusteredBars
// A reference to this plot for functional chaining.
if(this.zoom && !this.isDataDirty()){
return this.performZoom(dim, offsets);
}
this.resetEvents();
this.dirty = this.isDirty();
if(this.dirty){
arr.forEach(this.series, purgeGroup);
this._eventSeries = {};
this.cleanGroup();
var s = this.group;
df.forEachRev(this.series, function(item){ item.cleanGroup(s); });
}
var t = this.chart.theme, f, gap, height, thickness,
ht = this._hScaler.scaler.getTransformerFromModel(this._hScaler),
vt = this._vScaler.scaler.getTransformerFromModel(this._vScaler),
baseline = Math.max(0, this._hScaler.bounds.lower),
baselineWidth = ht(baseline),
events = this.events();
f = dc.calculateBarSize(this._vScaler.bounds.scale, this.opt, this.series.length);
gap = f.gap;
height = thickness = f.size;
for(var i = this.series.length - 1; i >= 0; --i){
var run = this.series[i], shift = thickness * (this.series.length - i - 1);
if(!this.dirty && !run.dirty){
t.skip();
this._reconnectEvents(run.name);
continue;
}
run.cleanGroup();
var theme = t.next("bar", [this.opt, run]), s = run.group,
eventSeries = new Array(run.data.length);
for(var j = 0; j < run.data.length; ++j){
var value = run.data[j];
if(value !== null){
var v = typeof value == "number" ? value : value.y,
hv = ht(v),
width = hv - baselineWidth,
w = Math.abs(width),
finalTheme = typeof value != "number" ?
t.addMixin(theme, "bar", value, true) :
t.post(theme, "bar");
if(w >= 0 && height >= 1){
var rect = {
x: offsets.l + (v < baseline ? hv : baselineWidth),
y: dim.height - offsets.b - vt(j + 1.5) + gap + shift,
width: w, height: height
};
var specialFill = this._plotFill(finalTheme.series.fill, dim, offsets);
specialFill = this._shapeFill(specialFill, rect);
var shape = s.createRect(rect).setFill(specialFill).setStroke(finalTheme.series.stroke);
run.dyn.fill = shape.getFill();
run.dyn.stroke = shape.getStroke();
if(events){
var o = {
element: "bar",
index: j,
run: run,
shape: shape,
x: v,
y: j + 1.5
};
this._connectEvents(o);
eventSeries[j] = o;
}
if(this.animate){
this._animateBar(shape, offsets.l + baselineWidth, -width);
}
}
}
}
this._eventSeries[run.name] = eventSeries;
run.dirty = false;
}
this.dirty = false;
return this; // dojox.charting.plot2d.ClusteredBars
}
});
});
},
'dojox/charting/action2d/MoveSlice':function(){
define("dojox/charting/action2d/MoveSlice", ["dojo/_base/connect", "dojo/_base/declare", "./PlotAction", "dojo/fx/easing", "dojox/gfx/matrix",
"dojox/gfx/fx", "dojox/lang/functional", "dojox/lang/functional/scan", "dojox/lang/functional/fold"],
function(hub, declare, PlotAction, dfe, m, gf, df, dfs, dff){
/*=====
dojo.declare("dojox.charting.action2d.__MoveSliceCtorArgs", dojox.charting.action2d.__PlotActionCtorArgs, {
// summary:
// Additional arguments for highlighting actions.
// scale: Number?
// The amount to scale the pie slice. Default is 1.05.
scale: 1.05,
// shift: Number?
// The amount in pixels to shift the pie slice. Default is 7.
shift: 7
});
var PlotAction = dojox.charting.action2d.PlotAction;
=====*/
var DEFAULT_SCALE = 1.05,
DEFAULT_SHIFT = 7; // px
return declare("dojox.charting.action2d.MoveSlice", PlotAction, {
// summary:
// Create an action for a pie chart that moves and scales a pie slice.
// the data description block for the widget parser
defaultParams: {
duration: 400, // duration of the action in ms
easing: dfe.backOut, // easing for the action
scale: DEFAULT_SCALE, // scale of magnification
shift: DEFAULT_SHIFT // shift of the slice
},
optionalParams: {}, // no optional parameters
constructor: function(chart, plot, kwArgs){
// summary:
// Create the slice moving action and connect it to the plot.
// chart: dojox.charting.Chart
// The chart this action belongs to.
// plot: String?
// The plot this action is attached to. If not passed, "default" is assumed.
// kwArgs: dojox.charting.action2d.__MoveSliceCtorArgs?
// Optional keyword arguments object for setting parameters.
if(!kwArgs){ kwArgs = {}; }
this.scale = typeof kwArgs.scale == "number" ? kwArgs.scale : DEFAULT_SCALE;
this.shift = typeof kwArgs.shift == "number" ? kwArgs.shift : DEFAULT_SHIFT;
this.connect();
},
process: function(o){
// summary:
// Process the action on the given object.
// o: dojox.gfx.Shape
// The object on which to process the slice moving action.
if(!o.shape || o.element != "slice" || !(o.type in this.overOutEvents)){ return; }
if(!this.angles){
// calculate the running total of slice angles
var startAngle = m._degToRad(o.plot.opt.startAngle);
if(typeof o.run.data[0] == "number"){
this.angles = df.map(df.scanl(o.run.data, "+", startAngle),
"* 2 * Math.PI / this", df.foldl(o.run.data, "+", 0));
}else{
this.angles = df.map(df.scanl(o.run.data, "a + b.y", startAngle),
"* 2 * Math.PI / this", df.foldl(o.run.data, "a + b.y", 0));
}
}
var index = o.index, anim, startScale, endScale, startOffset, endOffset,
angle = (this.angles[index] + this.angles[index + 1]) / 2,
rotateTo0 = m.rotateAt(-angle, o.cx, o.cy),
rotateBack = m.rotateAt( angle, o.cx, o.cy);
anim = this.anim[index];
if(anim){
anim.action.stop(true);
}else{
this.anim[index] = anim = {};
}
if(o.type == "onmouseover"){
startOffset = 0;
endOffset = this.shift;
startScale = 1;
endScale = this.scale;
}else{
startOffset = this.shift;
endOffset = 0;
startScale = this.scale;
endScale = 1;
}
anim.action = gf.animateTransform({
shape: o.shape,
duration: this.duration,
easing: this.easing,
transform: [
rotateBack,
{name: "translate", start: [startOffset, 0], end: [endOffset, 0]},
{name: "scaleAt", start: [startScale, o.cx, o.cy], end: [endScale, o.cx, o.cy]},
rotateTo0
]
});
if(o.type == "onmouseout"){
hub.connect(anim.action, "onEnd", this, function(){
delete this.anim[index];
});
}
anim.action.play();
},
reset: function(){
delete this.angles;
}
});
});
},
'dojo/colors':function(){
define(["./_base/kernel", "./_base/lang", "./_base/Color", "./_base/array"], function(dojo, lang, Color, ArrayUtil) {
// module:
// dojo/colors
// summary:
// TODOC
var ColorExt = lang.getObject("dojo.colors", true);
//TODO: this module appears to break naming conventions
/*=====
lang.mixin(dojo, {
colors: {
// summary: Color utilities, extending Base dojo.Color
}
});
=====*/
// this is a standard conversion prescribed by the CSS3 Color Module
var hue2rgb = function(m1, m2, h){
if(h < 0){ ++h; }
if(h > 1){ --h; }
var h6 = 6 * h;
if(h6 < 1){ return m1 + (m2 - m1) * h6; }
if(2 * h < 1){ return m2; }
if(3 * h < 2){ return m1 + (m2 - m1) * (2 / 3 - h) * 6; }
return m1;
};
// Override base Color.fromRgb with the impl in this module
dojo.colorFromRgb = Color.fromRgb = function(/*String*/ color, /*dojo.Color?*/ obj){
// summary:
// get rgb(a) array from css-style color declarations
// description:
// this function can handle all 4 CSS3 Color Module formats: rgb,
// rgba, hsl, hsla, including rgb(a) with percentage values.
var m = color.toLowerCase().match(/^(rgba?|hsla?)\(([\s\.\-,%0-9]+)\)/);
if(m){
var c = m[2].split(/\s*,\s*/), l = c.length, t = m[1], a;
if((t == "rgb" && l == 3) || (t == "rgba" && l == 4)){
var r = c[0];
if(r.charAt(r.length - 1) == "%"){
// 3 rgb percentage values
a = ArrayUtil.map(c, function(x){
return parseFloat(x) * 2.56;
});
if(l == 4){ a[3] = c[3]; }
return Color.fromArray(a, obj); // dojo.Color
}
return Color.fromArray(c, obj); // dojo.Color
}
if((t == "hsl" && l == 3) || (t == "hsla" && l == 4)){
// normalize hsl values
var H = ((parseFloat(c[0]) % 360) + 360) % 360 / 360,
S = parseFloat(c[1]) / 100,
L = parseFloat(c[2]) / 100,
// calculate rgb according to the algorithm
// recommended by the CSS3 Color Module
m2 = L <= 0.5 ? L * (S + 1) : L + S - L * S,
m1 = 2 * L - m2;
a = [
hue2rgb(m1, m2, H + 1 / 3) * 256,
hue2rgb(m1, m2, H) * 256,
hue2rgb(m1, m2, H - 1 / 3) * 256,
1
];
if(l == 4){ a[3] = c[3]; }
return Color.fromArray(a, obj); // dojo.Color
}
}
return null; // dojo.Color
};
var confine = function(c, low, high){
// summary:
// sanitize a color component by making sure it is a number,
// and clamping it to valid values
c = Number(c);
return isNaN(c) ? high : c < low ? low : c > high ? high : c; // Number
};
Color.prototype.sanitize = function(){
// summary: makes sure that the object has correct attributes
var t = this;
t.r = Math.round(confine(t.r, 0, 255));
t.g = Math.round(confine(t.g, 0, 255));
t.b = Math.round(confine(t.b, 0, 255));
t.a = confine(t.a, 0, 1);
return this; // dojo.Color
};
ColorExt.makeGrey = Color.makeGrey = function(/*Number*/ g, /*Number?*/ a){
// summary: creates a greyscale color with an optional alpha
return Color.fromArray([g, g, g, a]); // dojo.Color
};
// mixin all CSS3 named colors not already in _base, along with SVG 1.0 variant spellings
lang.mixin(Color.named, {
"aliceblue": [240,248,255],
"antiquewhite": [250,235,215],
"aquamarine": [127,255,212],
"azure": [240,255,255],
"beige": [245,245,220],
"bisque": [255,228,196],
"blanchedalmond": [255,235,205],
"blueviolet": [138,43,226],
"brown": [165,42,42],
"burlywood": [222,184,135],
"cadetblue": [95,158,160],
"chartreuse": [127,255,0],
"chocolate": [210,105,30],
"coral": [255,127,80],
"cornflowerblue": [100,149,237],
"cornsilk": [255,248,220],
"crimson": [220,20,60],
"cyan": [0,255,255],
"darkblue": [0,0,139],
"darkcyan": [0,139,139],
"darkgoldenrod": [184,134,11],
"darkgray": [169,169,169],
"darkgreen": [0,100,0],
"darkgrey": [169,169,169],
"darkkhaki": [189,183,107],
"darkmagenta": [139,0,139],
"darkolivegreen": [85,107,47],
"darkorange": [255,140,0],
"darkorchid": [153,50,204],
"darkred": [139,0,0],
"darksalmon": [233,150,122],
"darkseagreen": [143,188,143],
"darkslateblue": [72,61,139],
"darkslategray": [47,79,79],
"darkslategrey": [47,79,79],
"darkturquoise": [0,206,209],
"darkviolet": [148,0,211],
"deeppink": [255,20,147],
"deepskyblue": [0,191,255],
"dimgray": [105,105,105],
"dimgrey": [105,105,105],
"dodgerblue": [30,144,255],
"firebrick": [178,34,34],
"floralwhite": [255,250,240],
"forestgreen": [34,139,34],
"gainsboro": [220,220,220],
"ghostwhite": [248,248,255],
"gold": [255,215,0],
"goldenrod": [218,165,32],
"greenyellow": [173,255,47],
"grey": [128,128,128],
"honeydew": [240,255,240],
"hotpink": [255,105,180],
"indianred": [205,92,92],
"indigo": [75,0,130],
"ivory": [255,255,240],
"khaki": [240,230,140],
"lavender": [230,230,250],
"lavenderblush": [255,240,245],
"lawngreen": [124,252,0],
"lemonchiffon": [255,250,205],
"lightblue": [173,216,230],
"lightcoral": [240,128,128],
"lightcyan": [224,255,255],
"lightgoldenrodyellow": [250,250,210],
"lightgray": [211,211,211],
"lightgreen": [144,238,144],
"lightgrey": [211,211,211],
"lightpink": [255,182,193],
"lightsalmon": [255,160,122],
"lightseagreen": [32,178,170],
"lightskyblue": [135,206,250],
"lightslategray": [119,136,153],
"lightslategrey": [119,136,153],
"lightsteelblue": [176,196,222],
"lightyellow": [255,255,224],
"limegreen": [50,205,50],
"linen": [250,240,230],
"magenta": [255,0,255],
"mediumaquamarine": [102,205,170],
"mediumblue": [0,0,205],
"mediumorchid": [186,85,211],
"mediumpurple": [147,112,219],
"mediumseagreen": [60,179,113],
"mediumslateblue": [123,104,238],
"mediumspringgreen": [0,250,154],
"mediumturquoise": [72,209,204],
"mediumvioletred": [199,21,133],
"midnightblue": [25,25,112],
"mintcream": [245,255,250],
"mistyrose": [255,228,225],
"moccasin": [255,228,181],
"navajowhite": [255,222,173],
"oldlace": [253,245,230],
"olivedrab": [107,142,35],
"orange": [255,165,0],
"orangered": [255,69,0],
"orchid": [218,112,214],
"palegoldenrod": [238,232,170],
"palegreen": [152,251,152],
"paleturquoise": [175,238,238],
"palevioletred": [219,112,147],
"papayawhip": [255,239,213],
"peachpuff": [255,218,185],
"peru": [205,133,63],
"pink": [255,192,203],
"plum": [221,160,221],
"powderblue": [176,224,230],
"rosybrown": [188,143,143],
"royalblue": [65,105,225],
"saddlebrown": [139,69,19],
"salmon": [250,128,114],
"sandybrown": [244,164,96],
"seagreen": [46,139,87],
"seashell": [255,245,238],
"sienna": [160,82,45],
"skyblue": [135,206,235],
"slateblue": [106,90,205],
"slategray": [112,128,144],
"slategrey": [112,128,144],
"snow": [255,250,250],
"springgreen": [0,255,127],
"steelblue": [70,130,180],
"tan": [210,180,140],
"thistle": [216,191,216],
"tomato": [255,99,71],
"turquoise": [64,224,208],
"violet": [238,130,238],
"wheat": [245,222,179],
"whitesmoke": [245,245,245],
"yellowgreen": [154,205,50]
});
return Color;
});
},
'dijit/Tooltip':function(){
require({cache:{
'url:dijit/templates/Tooltip.html':"<div class=\"dijitTooltip dijitTooltipLeft\" id=\"dojoTooltip\"\n\t><div class=\"dijitTooltipContainer dijitTooltipContents\" data-dojo-attach-point=\"containerNode\" role='alert'></div\n\t><div class=\"dijitTooltipConnector\" data-dojo-attach-point=\"connectorNode\"></div\n></div>\n"}});
define("dijit/Tooltip", [
"dojo/_base/array", // array.forEach array.indexOf array.map
"dojo/_base/declare", // declare
"dojo/_base/fx", // fx.fadeIn fx.fadeOut
"dojo/dom", // dom.byId
"dojo/dom-class", // domClass.add
"dojo/dom-geometry", // domGeometry.getMarginBox domGeometry.position
"dojo/dom-style", // domStyle.set, domStyle.get
"dojo/_base/lang", // lang.hitch lang.isArrayLike
"dojo/_base/sniff", // has("ie")
"dojo/_base/window", // win.body
"./_base/manager", // manager.defaultDuration
"./place",
"./_Widget",
"./_TemplatedMixin",
"./BackgroundIframe",
"dojo/text!./templates/Tooltip.html",
"." // sets dijit.showTooltip etc. for back-compat
], function(array, declare, fx, dom, domClass, domGeometry, domStyle, lang, has, win,
manager, place, _Widget, _TemplatedMixin, BackgroundIframe, template, dijit){
/*=====
var _Widget = dijit._Widget;
var BackgroundIframe = dijit.BackgroundIframe;
var _TemplatedMixin = dijit._TemplatedMixin;
=====*/
// module:
// dijit/Tooltip
// summary:
// Defines dijit.Tooltip widget (to display a tooltip), showTooltip()/hideTooltip(), and _MasterTooltip
var MasterTooltip = declare("dijit._MasterTooltip", [_Widget, _TemplatedMixin], {
// summary:
// Internal widget that holds the actual tooltip markup,
// which occurs once per page.
// Called by Tooltip widgets which are just containers to hold
// the markup
// tags:
// protected
// duration: Integer
// Milliseconds to fade in/fade out
duration: manager.defaultDuration,
templateString: template,
postCreate: function(){
win.body().appendChild(this.domNode);
this.bgIframe = new BackgroundIframe(this.domNode);
// Setup fade-in and fade-out functions.
this.fadeIn = fx.fadeIn({ node: this.domNode, duration: this.duration, onEnd: lang.hitch(this, "_onShow") });
this.fadeOut = fx.fadeOut({ node: this.domNode, duration: this.duration, onEnd: lang.hitch(this, "_onHide") });
},
show: function(innerHTML, aroundNode, position, rtl, textDir){
// summary:
// Display tooltip w/specified contents to right of specified node
// (To left if there's no space on the right, or if rtl == true)
// innerHTML: String
// Contents of the tooltip
// aroundNode: DomNode || dijit.__Rectangle
// Specifies that tooltip should be next to this node / area
// position: String[]?
// List of positions to try to position tooltip (ex: ["right", "above"])
// rtl: Boolean?
// Corresponds to `WidgetBase.dir` attribute, where false means "ltr" and true
// means "rtl"; specifies GUI direction, not text direction.
// textDir: String?
// Corresponds to `WidgetBase.textdir` attribute; specifies direction of text.
if(this.aroundNode && this.aroundNode === aroundNode && this.containerNode.innerHTML == innerHTML){
return;
}
// reset width; it may have been set by orient() on a previous tooltip show()
this.domNode.width = "auto";
if(this.fadeOut.status() == "playing"){
// previous tooltip is being hidden; wait until the hide completes then show new one
this._onDeck=arguments;
return;
}
this.containerNode.innerHTML=innerHTML;
this.set("textDir", textDir);
this.containerNode.align = rtl? "right" : "left"; //fix the text alignment
var pos = place.around(this.domNode, aroundNode,
position && position.length ? position : Tooltip.defaultPosition, !rtl, lang.hitch(this, "orient"));
// Position the tooltip connector for middle alignment.
// This could not have been done in orient() since the tooltip wasn't positioned at that time.
var aroundNodeCoords = pos.aroundNodePos;
if(pos.corner.charAt(0) == 'M' && pos.aroundCorner.charAt(0) == 'M'){
this.connectorNode.style.top = aroundNodeCoords.y + ((aroundNodeCoords.h - this.connectorNode.offsetHeight) >> 1) - pos.y + "px";
this.connectorNode.style.left = "";
}else if(pos.corner.charAt(1) == 'M' && pos.aroundCorner.charAt(1) == 'M'){
this.connectorNode.style.left = aroundNodeCoords.x + ((aroundNodeCoords.w - this.connectorNode.offsetWidth) >> 1) - pos.x + "px";
}
// show it
domStyle.set(this.domNode, "opacity", 0);
this.fadeIn.play();
this.isShowingNow = true;
this.aroundNode = aroundNode;
},
orient: function(/*DomNode*/ node, /*String*/ aroundCorner, /*String*/ tooltipCorner, /*Object*/ spaceAvailable, /*Object*/ aroundNodeCoords){
// summary:
// Private function to set CSS for tooltip node based on which position it's in.
// This is called by the dijit popup code. It will also reduce the tooltip's
// width to whatever width is available
// tags:
// protected
this.connectorNode.style.top = ""; //reset to default
//Adjust the spaceAvailable width, without changing the spaceAvailable object
var tooltipSpaceAvaliableWidth = spaceAvailable.w - this.connectorNode.offsetWidth;
node.className = "dijitTooltip " +
{
"MR-ML": "dijitTooltipRight",
"ML-MR": "dijitTooltipLeft",
"TM-BM": "dijitTooltipAbove",
"BM-TM": "dijitTooltipBelow",
"BL-TL": "dijitTooltipBelow dijitTooltipABLeft",
"TL-BL": "dijitTooltipAbove dijitTooltipABLeft",
"BR-TR": "dijitTooltipBelow dijitTooltipABRight",
"TR-BR": "dijitTooltipAbove dijitTooltipABRight",
"BR-BL": "dijitTooltipRight",
"BL-BR": "dijitTooltipLeft"
}[aroundCorner + "-" + tooltipCorner];
// reduce tooltip's width to the amount of width available, so that it doesn't overflow screen
this.domNode.style.width = "auto";
var size = domGeometry.getContentBox(this.domNode);
var width = Math.min((Math.max(tooltipSpaceAvaliableWidth,1)), size.w);
var widthWasReduced = width < size.w;
this.domNode.style.width = width+"px";
//Adjust width for tooltips that have a really long word or a nowrap setting
if(widthWasReduced){
this.containerNode.style.overflow = "auto"; //temp change to overflow to detect if our tooltip needs to be wider to support the content
var scrollWidth = this.containerNode.scrollWidth;
this.containerNode.style.overflow = "visible"; //change it back
if(scrollWidth > width){
scrollWidth = scrollWidth + domStyle.get(this.domNode,"paddingLeft") + domStyle.get(this.domNode,"paddingRight");
this.domNode.style.width = scrollWidth + "px";
}
}
// Reposition the tooltip connector.
if(tooltipCorner.charAt(0) == 'B' && aroundCorner.charAt(0) == 'B'){
var mb = domGeometry.getMarginBox(node);
var tooltipConnectorHeight = this.connectorNode.offsetHeight;
if(mb.h > spaceAvailable.h){
// The tooltip starts at the top of the page and will extend past the aroundNode
var aroundNodePlacement = spaceAvailable.h - ((aroundNodeCoords.h + tooltipConnectorHeight) >> 1);
this.connectorNode.style.top = aroundNodePlacement + "px";
this.connectorNode.style.bottom = "";
}else{
// Align center of connector with center of aroundNode, except don't let bottom
// of connector extend below bottom of tooltip content, or top of connector
// extend past top of tooltip content
this.connectorNode.style.bottom = Math.min(
Math.max(aroundNodeCoords.h/2 - tooltipConnectorHeight/2, 0),
mb.h - tooltipConnectorHeight) + "px";
this.connectorNode.style.top = "";
}
}else{
// reset the tooltip back to the defaults
this.connectorNode.style.top = "";
this.connectorNode.style.bottom = "";
}
return Math.max(0, size.w - tooltipSpaceAvaliableWidth);
},
_onShow: function(){
// summary:
// Called at end of fade-in operation
// tags:
// protected
if(has("ie")){
// the arrow won't show up on a node w/an opacity filter
this.domNode.style.filter="";
}
},
hide: function(aroundNode){
// summary:
// Hide the tooltip
if(this._onDeck && this._onDeck[1] == aroundNode){
// this hide request is for a show() that hasn't even started yet;
// just cancel the pending show()
this._onDeck=null;
}else if(this.aroundNode === aroundNode){
// this hide request is for the currently displayed tooltip
this.fadeIn.stop();
this.isShowingNow = false;
this.aroundNode = null;
this.fadeOut.play();
}else{
// just ignore the call, it's for a tooltip that has already been erased
}
},
_onHide: function(){
// summary:
// Called at end of fade-out operation
// tags:
// protected
this.domNode.style.cssText=""; // to position offscreen again
this.containerNode.innerHTML="";
if(this._onDeck){
// a show request has been queued up; do it now
this.show.apply(this, this._onDeck);
this._onDeck=null;
}
},
_setAutoTextDir: function(/*Object*/node){
// summary:
// Resolve "auto" text direction for children nodes
// tags:
// private
this.applyTextDir(node, has("ie") ? node.outerText : node.textContent);
array.forEach(node.children, function(child){this._setAutoTextDir(child); }, this);
},
_setTextDirAttr: function(/*String*/ textDir){
// summary:
// Setter for textDir.
// description:
// Users shouldn't call this function; they should be calling
// set('textDir', value)
// tags:
// private
this._set("textDir", typeof textDir != 'undefined'? textDir : "");
if (textDir == "auto"){
this._setAutoTextDir(this.containerNode);
}else{
this.containerNode.dir = this.textDir;
}
}
});
dijit.showTooltip = function(innerHTML, aroundNode, position, rtl, textDir){
// summary:
// Static method to display tooltip w/specified contents in specified position.
// See description of dijit.Tooltip.defaultPosition for details on position parameter.
// If position is not specified then dijit.Tooltip.defaultPosition is used.
// innerHTML: String
// Contents of the tooltip
// aroundNode: dijit.__Rectangle
// Specifies that tooltip should be next to this node / area
// position: String[]?
// List of positions to try to position tooltip (ex: ["right", "above"])
// rtl: Boolean?
// Corresponds to `WidgetBase.dir` attribute, where false means "ltr" and true
// means "rtl"; specifies GUI direction, not text direction.
// textDir: String?
// Corresponds to `WidgetBase.textdir` attribute; specifies direction of text.
if(!Tooltip._masterTT){ dijit._masterTT = Tooltip._masterTT = new MasterTooltip(); }
return Tooltip._masterTT.show(innerHTML, aroundNode, position, rtl, textDir);
};
dijit.hideTooltip = function(aroundNode){
// summary:
// Static method to hide the tooltip displayed via showTooltip()
return Tooltip._masterTT && Tooltip._masterTT.hide(aroundNode);
};
var Tooltip = declare("dijit.Tooltip", _Widget, {
// summary:
// Pops up a tooltip (a help message) when you hover over a node.
// label: String
// Text to display in the tooltip.
// Specified as innerHTML when creating the widget from markup.
label: "",
// showDelay: Integer
// Number of milliseconds to wait after hovering over/focusing on the object, before
// the tooltip is displayed.
showDelay: 400,
// connectId: String|String[]
// Id of domNode(s) to attach the tooltip to.
// When user hovers over specified dom node, the tooltip will appear.
connectId: [],
// position: String[]
// See description of `dijit.Tooltip.defaultPosition` for details on position parameter.
position: [],
_setConnectIdAttr: function(/*String|String[]*/ newId){
// summary:
// Connect to specified node(s)
// Remove connections to old nodes (if there are any)
array.forEach(this._connections || [], function(nested){
array.forEach(nested, lang.hitch(this, "disconnect"));
}, this);
// Make array of id's to connect to, excluding entries for nodes that don't exist yet, see startup()
this._connectIds = array.filter(lang.isArrayLike(newId) ? newId : (newId ? [newId] : []),
function(id){ return dom.byId(id); });
// Make connections
this._connections = array.map(this._connectIds, function(id){
var node = dom.byId(id);
return [
this.connect(node, "onmouseenter", "_onHover"),
this.connect(node, "onmouseleave", "_onUnHover"),
this.connect(node, "onfocus", "_onHover"),
this.connect(node, "onblur", "_onUnHover")
];
}, this);
this._set("connectId", newId);
},
addTarget: function(/*DOMNODE || String*/ node){
// summary:
// Attach tooltip to specified node if it's not already connected
// TODO: remove in 2.0 and just use set("connectId", ...) interface
var id = node.id || node;
if(array.indexOf(this._connectIds, id) == -1){
this.set("connectId", this._connectIds.concat(id));
}
},
removeTarget: function(/*DomNode || String*/ node){
// summary:
// Detach tooltip from specified node
// TODO: remove in 2.0 and just use set("connectId", ...) interface
var id = node.id || node, // map from DOMNode back to plain id string
idx = array.indexOf(this._connectIds, id);
if(idx >= 0){
// remove id (modifies original this._connectIds but that's OK in this case)
this._connectIds.splice(idx, 1);
this.set("connectId", this._connectIds);
}
},
buildRendering: function(){
this.inherited(arguments);
domClass.add(this.domNode,"dijitTooltipData");
},
startup: function(){
this.inherited(arguments);
// If this tooltip was created in a template, or for some other reason the specified connectId[s]
// didn't exist during the widget's initialization, then connect now.
var ids = this.connectId;
array.forEach(lang.isArrayLike(ids) ? ids : [ids], this.addTarget, this);
},
_onHover: function(/*Event*/ e){
// summary:
// Despite the name of this method, it actually handles both hover and focus
// events on the target node, setting a timer to show the tooltip.
// tags:
// private
if(!this._showTimer){
var target = e.target;
this._showTimer = setTimeout(lang.hitch(this, function(){this.open(target)}), this.showDelay);
}
},
_onUnHover: function(/*Event*/ /*===== e =====*/){
// summary:
// Despite the name of this method, it actually handles both mouseleave and blur
// events on the target node, hiding the tooltip.
// tags:
// private
// keep a tooltip open if the associated element still has focus (even though the
// mouse moved away)
if(this._focus){ return; }
if(this._showTimer){
clearTimeout(this._showTimer);
delete this._showTimer;
}
this.close();
},
open: function(/*DomNode*/ target){
// summary:
// Display the tooltip; usually not called directly.
// tags:
// private
if(this._showTimer){
clearTimeout(this._showTimer);
delete this._showTimer;
}
Tooltip.show(this.label || this.domNode.innerHTML, target, this.position, !this.isLeftToRight(), this.textDir);
this._connectNode = target;
this.onShow(target, this.position);
},
close: function(){
// summary:
// Hide the tooltip or cancel timer for show of tooltip
// tags:
// private
if(this._connectNode){
// if tooltip is currently shown
Tooltip.hide(this._connectNode);
delete this._connectNode;
this.onHide();
}
if(this._showTimer){
// if tooltip is scheduled to be shown (after a brief delay)
clearTimeout(this._showTimer);
delete this._showTimer;
}
},
onShow: function(/*===== target, position =====*/){
// summary:
// Called when the tooltip is shown
// tags:
// callback
},
onHide: function(){
// summary:
// Called when the tooltip is hidden
// tags:
// callback
},
uninitialize: function(){
this.close();
this.inherited(arguments);
}
});
Tooltip._MasterTooltip = MasterTooltip; // for monkey patching
Tooltip.show = dijit.showTooltip; // export function through module return value
Tooltip.hide = dijit.hideTooltip; // export function through module return value
// dijit.Tooltip.defaultPosition: String[]
// This variable controls the position of tooltips, if the position is not specified to
// the Tooltip widget or *TextBox widget itself. It's an array of strings with the values
// possible for `dijit/place::around()`. The recommended values are:
//
// * before-centered: centers tooltip to the left of the anchor node/widget, or to the right
// in the case of RTL scripts like Hebrew and Arabic
// * after-centered: centers tooltip to the right of the anchor node/widget, or to the left
// in the case of RTL scripts like Hebrew and Arabic
// * above-centered: tooltip is centered above anchor node
// * below-centered: tooltip is centered above anchor node
//
// The list is positions is tried, in order, until a position is found where the tooltip fits
// within the viewport.
//
// Be careful setting this parameter. A value of "above-centered" may work fine until the user scrolls
// the screen so that there's no room above the target node. Nodes with drop downs, like
// DropDownButton or FilteringSelect, are especially problematic, in that you need to be sure
// that the drop down and tooltip don't overlap, even when the viewport is scrolled so that there
// is only room below (or above) the target node, but not both.
Tooltip.defaultPosition = ["after-centered", "before-centered"];
return Tooltip;
});
},
'dojox/charting/Element':function(){
define("dojox/charting/Element", ["dojo/_base/lang", "dojo/_base/array", "dojo/dom-construct","dojo/_base/declare", "dojox/gfx", "dojox/gfx/utils", "dojox/gfx/shape"],
function(lang, arr, domConstruct, declare, gfx, utils, shape){
return declare("dojox.charting.Element", null, {
// summary:
// A base class that is used to build other elements of a chart, such as
// a series.
// chart: dojox.charting.Chart
// The parent chart for this element.
// group: dojox.gfx.Group
// The visual GFX group representing this element.
// htmlElement: Array
// Any DOMNodes used as a part of this element (such as HTML-based labels).
// dirty: Boolean
// A flag indicating whether or not this element needs to be rendered.
chart: null,
group: null,
htmlElements: null,
dirty: true,
constructor: function(chart){
// summary:
// Creates a new charting element.
// chart: dojox.charting.Chart
// The chart that this element belongs to.
this.chart = chart;
this.group = null;
this.htmlElements = [];
this.dirty = true;
this.trailingSymbol = "...";
this._events = [];
},
createGroup: function(creator){
// summary:
// Convenience function to create a new dojox.gfx.Group.
// creator: dojox.gfx.Surface?
// An optional surface in which to create this group.
// returns: dojox.charting.Element
// A reference to this object for functional chaining.
if(!creator){ creator = this.chart.surface; }
if(!this.group){
this.group = creator.createGroup();
}
return this; // dojox.charting.Element
},
purgeGroup: function(){
// summary:
// Clear any elements out of our group, and destroy the group.
// returns: dojox.charting.Element
// A reference to this object for functional chaining.
this.destroyHtmlElements();
if(this.group){
// since 1.7.x we need dispose shape otherwise there is a memoryleak
utils.forEach(this.group, function(child){
shape.dispose(child);
});
this.group.clear();
this.group.removeShape();
this.group = null;
}
this.dirty = true;
if(this._events.length){
arr.forEach(this._events, function(item){
item.shape.disconnect(item.handle);
});
this._events = [];
}
return this; // dojox.charting.Element
},
cleanGroup: function(creator){
// summary:
// Clean any elements (HTML or GFX-based) out of our group, and create a new one.
// creator: dojox.gfx.Surface?
// An optional surface to work with.
// returns: dojox.charting.Element
// A reference to this object for functional chaining.
this.destroyHtmlElements();
if(!creator){ creator = this.chart.surface; }
if(this.group){
this.group.clear();
}else{
this.group = creator.createGroup();
}
this.dirty = true;
return this; // dojox.charting.Element
},
destroyHtmlElements: function(){
// summary:
// Destroy any DOMNodes that may have been created as a part of this element.
if(this.htmlElements.length){
arr.forEach(this.htmlElements, domConstruct.destroy);
this.htmlElements = [];
}
},
destroy: function(){
// summary:
// API addition to conform to the rest of the Dojo Toolkit's standard.
this.purgeGroup();
},
//text utilities
getTextWidth: function(s, font){
return gfx._base._getTextBox(s, {font: font}).w || 0;
},
getTextWithLimitLength: function(s, font, limitWidth, truncated){
// summary:
// Get the truncated string based on the limited width in px(dichotomy algorithm)
// s: String?
// candidate text.
// font: String?
// text's font style.
// limitWidth: Number?
// text limited width in px.
// truncated: Boolean?
// whether the input text(s) has already been truncated.
// returns: Object
// {
// text: processed text, maybe truncated or not
// truncated: whether text has been truncated
// }
if (!s || s.length <= 0) {
return {
text: "",
truncated: truncated || false
};
}
if(!limitWidth || limitWidth <= 0){
return {
text: s,
truncated: truncated || false
};
}
var delta = 2,
//golden section for dichotomy algorithm
trucPercentage = 0.618,
minStr = s.substring(0,1) + this.trailingSymbol,
minWidth = this.getTextWidth(minStr, font);
if (limitWidth <= minWidth) {
return {
text: minStr,
truncated: true
};
}
var width = this.getTextWidth(s, font);
if(width <= limitWidth){
return {
text: s,
truncated: truncated || false
};
}else{
var begin = 0,
end = s.length;
while(begin < end){
if(end - begin <= delta ){
while (this.getTextWidth(s.substring(0, begin) + this.trailingSymbol, font) > limitWidth) {
begin -= 1;
}
return {
text: (s.substring(0,begin) + this.trailingSymbol),
truncated: true
};
}
var index = begin + Math.round((end - begin) * trucPercentage),
widthIntercepted = this.getTextWidth(s.substring(0, index), font);
if(widthIntercepted < limitWidth){
begin = index;
end = end;
}else{
begin = begin;
end = index;
}
}
}
},
getTextWithLimitCharCount: function(s, font, wcLimit, truncated){
// summary:
// Get the truncated string based on the limited character count(dichotomy algorithm)
// s: String?
// candidate text.
// font: String?
// text's font style.
// wcLimit: Number?
// text limited character count.
// truncated: Boolean?
// whether the input text(s) has already been truncated.
// returns: Object
// {
// text: processed text, maybe truncated or not
// truncated: whether text has been truncated
// }
if (!s || s.length <= 0) {
return {
text: "",
truncated: truncated || false
};
}
if(!wcLimit || wcLimit <= 0 || s.length <= wcLimit){
return {
text: s,
truncated: truncated || false
};
}
return {
text: s.substring(0, wcLimit) + this.trailingSymbol,
truncated: true
};
},
// fill utilities
_plotFill: function(fill, dim, offsets){
// process a plot-wide fill
if(!fill || !fill.type || !fill.space){
return fill;
}
var space = fill.space;
switch(fill.type){
case "linear":
if(space === "plot" || space === "shapeX" || space === "shapeY"){
// clone a fill so we can modify properly directly
fill = gfx.makeParameters(gfx.defaultLinearGradient, fill);
fill.space = space;
// process dimensions
if(space === "plot" || space === "shapeX"){
// process Y
var span = dim.height - offsets.t - offsets.b;
fill.y1 = offsets.t + span * fill.y1 / 100;
fill.y2 = offsets.t + span * fill.y2 / 100;
}
if(space === "plot" || space === "shapeY"){
// process X
var span = dim.width - offsets.l - offsets.r;
fill.x1 = offsets.l + span * fill.x1 / 100;
fill.x2 = offsets.l + span * fill.x2 / 100;
}
}
break;
case "radial":
if(space === "plot"){
// this one is used exclusively for scatter charts
// clone a fill so we can modify properly directly
fill = gfx.makeParameters(gfx.defaultRadialGradient, fill);
fill.space = space;
// process both dimensions
var spanX = dim.width - offsets.l - offsets.r,
spanY = dim.height - offsets.t - offsets.b;
fill.cx = offsets.l + spanX * fill.cx / 100;
fill.cy = offsets.t + spanY * fill.cy / 100;
fill.r = fill.r * Math.sqrt(spanX * spanX + spanY * spanY) / 200;
}
break;
case "pattern":
if(space === "plot" || space === "shapeX" || space === "shapeY"){
// clone a fill so we can modify properly directly
fill = gfx.makeParameters(gfx.defaultPattern, fill);
fill.space = space;
// process dimensions
if(space === "plot" || space === "shapeX"){
// process Y
var span = dim.height - offsets.t - offsets.b;
fill.y = offsets.t + span * fill.y / 100;
fill.height = span * fill.height / 100;
}
if(space === "plot" || space === "shapeY"){
// process X
var span = dim.width - offsets.l - offsets.r;
fill.x = offsets.l + span * fill.x / 100;
fill.width = span * fill.width / 100;
}
}
break;
}
return fill;
},
_shapeFill: function(fill, bbox){
// process shape-specific fill
if(!fill || !fill.space){
return fill;
}
var space = fill.space;
switch(fill.type){
case "linear":
if(space === "shape" || space === "shapeX" || space === "shapeY"){
// clone a fill so we can modify properly directly
fill = gfx.makeParameters(gfx.defaultLinearGradient, fill);
fill.space = space;
// process dimensions
if(space === "shape" || space === "shapeX"){
// process X
var span = bbox.width;
fill.x1 = bbox.x + span * fill.x1 / 100;
fill.x2 = bbox.x + span * fill.x2 / 100;
}
if(space === "shape" || space === "shapeY"){
// process Y
var span = bbox.height;
fill.y1 = bbox.y + span * fill.y1 / 100;
fill.y2 = bbox.y + span * fill.y2 / 100;
}
}
break;
case "radial":
if(space === "shape"){
// this one is used exclusively for bubble charts and pie charts
// clone a fill so we can modify properly directly
fill = gfx.makeParameters(gfx.defaultRadialGradient, fill);
fill.space = space;
// process both dimensions
fill.cx = bbox.x + bbox.width / 2;
fill.cy = bbox.y + bbox.height / 2;
fill.r = fill.r * bbox.width / 200;
}
break;
case "pattern":
if(space === "shape" || space === "shapeX" || space === "shapeY"){
// clone a fill so we can modify properly directly
fill = gfx.makeParameters(gfx.defaultPattern, fill);
fill.space = space;
// process dimensions
if(space === "shape" || space === "shapeX"){
// process X
var span = bbox.width;
fill.x = bbox.x + span * fill.x / 100;
fill.width = span * fill.width / 100;
}
if(space === "shape" || space === "shapeY"){
// process Y
var span = bbox.height;
fill.y = bbox.y + span * fill.y / 100;
fill.height = span * fill.height / 100;
}
}
break;
}
return fill;
},
_pseudoRadialFill: function(fill, center, radius, start, end){
// process pseudo-radial fills
if(!fill || fill.type !== "radial" || fill.space !== "shape"){
return fill;
}
// clone and normalize fill
var space = fill.space;
fill = gfx.makeParameters(gfx.defaultRadialGradient, fill);
fill.space = space;
if(arguments.length < 4){
// process both dimensions
fill.cx = center.x;
fill.cy = center.y;
fill.r = fill.r * radius / 100;
return fill;
}
// convert to a linear gradient
var angle = arguments.length < 5 ? start : (end + start) / 2;
return {
type: "linear",
x1: center.x,
y1: center.y,
x2: center.x + fill.r * radius * Math.cos(angle) / 100,
y2: center.y + fill.r * radius * Math.sin(angle) / 100,
colors: fill.colors
};
return fill;
}
});
});
},
'dijit/_WidgetBase':function(){
define("dijit/_WidgetBase", [
"require", // require.toUrl
"dojo/_base/array", // array.forEach array.map
"dojo/aspect",
"dojo/_base/config", // config.blankGif
"dojo/_base/connect", // connect.connect
"dojo/_base/declare", // declare
"dojo/dom", // dom.byId
"dojo/dom-attr", // domAttr.set domAttr.remove
"dojo/dom-class", // domClass.add domClass.replace
"dojo/dom-construct", // domConstruct.create domConstruct.destroy domConstruct.place
"dojo/dom-geometry", // isBodyLtr
"dojo/dom-style", // domStyle.set, domStyle.get
"dojo/_base/kernel",
"dojo/_base/lang", // mixin(), isArray(), etc.
"dojo/on",
"dojo/ready",
"dojo/Stateful", // Stateful
"dojo/topic",
"dojo/_base/window", // win.doc.createTextNode
"./registry" // registry.getUniqueId(), registry.findWidgets()
], function(require, array, aspect, config, connect, declare,
dom, domAttr, domClass, domConstruct, domGeometry, domStyle, kernel,
lang, on, ready, Stateful, topic, win, registry){
/*=====
var Stateful = dojo.Stateful;
=====*/
// module:
// dijit/_WidgetBase
// summary:
// Future base class for all Dijit widgets.
// For back-compat, remove in 2.0.
if(!kernel.isAsync){
ready(0, function(){
var requires = ["dijit/_base/manager"];
require(requires); // use indirection so modules not rolled into a build
});
}
// Nested hash listing attributes for each tag, all strings in lowercase.
// ex: {"div": {"style": true, "tabindex" true}, "form": { ...
var tagAttrs = {};
function getAttrs(obj){
var ret = {};
for(var attr in obj){
ret[attr.toLowerCase()] = true;
}
return ret;
}
function nonEmptyAttrToDom(attr){
// summary:
// Returns a setter function that copies the attribute to this.domNode,
// or removes the attribute from this.domNode, depending on whether the
// value is defined or not.
return function(val){
domAttr[val ? "set" : "remove"](this.domNode, attr, val);
this._set(attr, val);
};
}
return declare("dijit._WidgetBase", Stateful, {
// summary:
// Future base class for all Dijit widgets.
// description:
// Future base class for all Dijit widgets.
// _Widget extends this class adding support for various features needed by desktop.
//
// Provides stubs for widget lifecycle methods for subclasses to extend, like postMixInProperties(), buildRendering(),
// postCreate(), startup(), and destroy(), and also public API methods like set(), get(), and watch().
//
// Widgets can provide custom setters/getters for widget attributes, which are called automatically by set(name, value).
// For an attribute XXX, define methods _setXXXAttr() and/or _getXXXAttr().
//
// _setXXXAttr can also be a string/hash/array mapping from a widget attribute XXX to the widget's DOMNodes:
//
// - DOM node attribute
// | _setFocusAttr: {node: "focusNode", type: "attribute"}
// | _setFocusAttr: "focusNode" (shorthand)
// | _setFocusAttr: "" (shorthand, maps to this.domNode)
// Maps this.focus to this.focusNode.focus, or (last example) this.domNode.focus
//
// - DOM node innerHTML
// | _setTitleAttr: { node: "titleNode", type: "innerHTML" }
// Maps this.title to this.titleNode.innerHTML
//
// - DOM node innerText
// | _setTitleAttr: { node: "titleNode", type: "innerText" }
// Maps this.title to this.titleNode.innerText
//
// - DOM node CSS class
// | _setMyClassAttr: { node: "domNode", type: "class" }
// Maps this.myClass to this.domNode.className
//
// If the value of _setXXXAttr is an array, then each element in the array matches one of the
// formats of the above list.
//
// If the custom setter is null, no action is performed other than saving the new value
// in the widget (in this).
//
// If no custom setter is defined for an attribute, then it will be copied
// to this.focusNode (if the widget defines a focusNode), or this.domNode otherwise.
// That's only done though for attributes that match DOMNode attributes (title,
// alt, aria-labelledby, etc.)
// id: [const] String
// A unique, opaque ID string that can be assigned by users or by the
// system. If the developer passes an ID which is known not to be
// unique, the specified ID is ignored and the system-generated ID is
// used instead.
id: "",
_setIdAttr: "domNode", // to copy to this.domNode even for auto-generated id's
// lang: [const] String
// Rarely used. Overrides the default Dojo locale used to render this widget,
// as defined by the [HTML LANG](http://www.w3.org/TR/html401/struct/dirlang.html#adef-lang) attribute.
// Value must be among the list of locales specified during by the Dojo bootstrap,
// formatted according to [RFC 3066](http://www.ietf.org/rfc/rfc3066.txt) (like en-us).
lang: "",
// set on domNode even when there's a focus node. but don't set lang="", since that's invalid.
_setLangAttr: nonEmptyAttrToDom("lang"),
// dir: [const] String
// Bi-directional support, as defined by the [HTML DIR](http://www.w3.org/TR/html401/struct/dirlang.html#adef-dir)
// attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's
// default direction.
dir: "",
// set on domNode even when there's a focus node. but don't set dir="", since that's invalid.
_setDirAttr: nonEmptyAttrToDom("dir"), // to set on domNode even when there's a focus node
// textDir: String
// Bi-directional support, the main variable which is responsible for the direction of the text.
// The text direction can be different than the GUI direction by using this parameter in creation
// of a widget.
// Allowed values:
// 1. "ltr"
// 2. "rtl"
// 3. "auto" - contextual the direction of a text defined by first strong letter.
// By default is as the page direction.
textDir: "",
// class: String
// HTML class attribute
"class": "",
_setClassAttr: { node: "domNode", type: "class" },
// style: String||Object
// HTML style attributes as cssText string or name/value hash
style: "",
// title: String
// HTML title attribute.
//
// For form widgets this specifies a tooltip to display when hovering over
// the widget (just like the native HTML title attribute).
//
// For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer,
// etc., it's used to specify the tab label, accordion pane title, etc.
title: "",
// tooltip: String
// When this widget's title attribute is used to for a tab label, accordion pane title, etc.,
// this specifies the tooltip to appear when the mouse is hovered over that text.
tooltip: "",
// baseClass: [protected] String
// Root CSS class of the widget (ex: dijitTextBox), used to construct CSS classes to indicate
// widget state.
baseClass: "",
// srcNodeRef: [readonly] DomNode
// pointer to original DOM node
srcNodeRef: null,
// domNode: [readonly] DomNode
// This is our visible representation of the widget! Other DOM
// Nodes may by assigned to other properties, usually through the
// template system's data-dojo-attach-point syntax, but the domNode
// property is the canonical "top level" node in widget UI.
domNode: null,
// containerNode: [readonly] DomNode
// Designates where children of the source DOM node will be placed.
// "Children" in this case refers to both DOM nodes and widgets.
// For example, for myWidget:
//
// | <div data-dojo-type=myWidget>
// | <b> here's a plain DOM node
// | <span data-dojo-type=subWidget>and a widget</span>
// | <i> and another plain DOM node </i>
// | </div>
//
// containerNode would point to:
//
// | <b> here's a plain DOM node
// | <span data-dojo-type=subWidget>and a widget</span>
// | <i> and another plain DOM node </i>
//
// In templated widgets, "containerNode" is set via a
// data-dojo-attach-point assignment.
//
// containerNode must be defined for any widget that accepts innerHTML
// (like ContentPane or BorderContainer or even Button), and conversely
// is null for widgets that don't, like TextBox.
containerNode: null,
/*=====
// _started: Boolean
// startup() has completed.
_started: false,
=====*/
// attributeMap: [protected] Object
// Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute
// for each XXX attribute to be mapped to the DOM.
//
// attributeMap sets up a "binding" between attributes (aka properties)
// of the widget and the widget's DOM.
// Changes to widget attributes listed in attributeMap will be
// reflected into the DOM.
//
// For example, calling set('title', 'hello')
// on a TitlePane will automatically cause the TitlePane's DOM to update
// with the new title.
//
// attributeMap is a hash where the key is an attribute of the widget,
// and the value reflects a binding to a:
//
// - DOM node attribute
// | focus: {node: "focusNode", type: "attribute"}
// Maps this.focus to this.focusNode.focus
//
// - DOM node innerHTML
// | title: { node: "titleNode", type: "innerHTML" }
// Maps this.title to this.titleNode.innerHTML
//
// - DOM node innerText
// | title: { node: "titleNode", type: "innerText" }
// Maps this.title to this.titleNode.innerText
//
// - DOM node CSS class
// | myClass: { node: "domNode", type: "class" }
// Maps this.myClass to this.domNode.className
//
// If the value is an array, then each element in the array matches one of the
// formats of the above list.
//
// There are also some shorthands for backwards compatibility:
// - string --> { node: string, type: "attribute" }, for example:
// | "focusNode" ---> { node: "focusNode", type: "attribute" }
// - "" --> { node: "domNode", type: "attribute" }
attributeMap: {},
// _blankGif: [protected] String
// Path to a blank 1x1 image.
// Used by <img> nodes in templates that really get their image via CSS background-image.
_blankGif: config.blankGif || require.toUrl("dojo/resources/blank.gif"),
//////////// INITIALIZATION METHODS ///////////////////////////////////////
postscript: function(/*Object?*/params, /*DomNode|String*/srcNodeRef){
// summary:
// Kicks off widget instantiation. See create() for details.
// tags:
// private
this.create(params, srcNodeRef);
},
create: function(/*Object?*/params, /*DomNode|String?*/srcNodeRef){
// summary:
// Kick off the life-cycle of a widget
// params:
// Hash of initialization parameters for widget, including
// scalar values (like title, duration etc.) and functions,
// typically callbacks like onClick.
// srcNodeRef:
// If a srcNodeRef (DOM node) is specified:
// - use srcNodeRef.innerHTML as my contents
// - if this is a behavioral widget then apply behavior
// to that srcNodeRef
// - otherwise, replace srcNodeRef with my generated DOM
// tree
// description:
// Create calls a number of widget methods (postMixInProperties, buildRendering, postCreate,
// etc.), some of which of you'll want to override. See http://dojotoolkit.org/reference-guide/dijit/_WidgetBase.html
// for a discussion of the widget creation lifecycle.
//
// Of course, adventurous developers could override create entirely, but this should
// only be done as a last resort.
// tags:
// private
// store pointer to original DOM tree
this.srcNodeRef = dom.byId(srcNodeRef);
// For garbage collection. An array of listener handles returned by this.connect() / this.subscribe()
this._connects = [];
// For widgets internal to this widget, invisible to calling code
this._supportingWidgets = [];
// this is here for back-compat, remove in 2.0 (but check NodeList-instantiate.html test)
if(this.srcNodeRef && (typeof this.srcNodeRef.id == "string")){ this.id = this.srcNodeRef.id; }
// mix in our passed parameters
if(params){
this.params = params;
lang.mixin(this, params);
}
this.postMixInProperties();
// generate an id for the widget if one wasn't specified
// (be sure to do this before buildRendering() because that function might
// expect the id to be there.)
if(!this.id){
this.id = registry.getUniqueId(this.declaredClass.replace(/\./g,"_"));
}
registry.add(this);
this.buildRendering();
if(this.domNode){
// Copy attributes listed in attributeMap into the [newly created] DOM for the widget.
// Also calls custom setters for all attributes with custom setters.
this._applyAttributes();
// If srcNodeRef was specified, then swap out original srcNode for this widget's DOM tree.
// For 2.0, move this after postCreate(). postCreate() shouldn't depend on the
// widget being attached to the DOM since it isn't when a widget is created programmatically like
// new MyWidget({}). See #11635.
var source = this.srcNodeRef;
if(source && source.parentNode && this.domNode !== source){
source.parentNode.replaceChild(this.domNode, source);
}
}
if(this.domNode){
// Note: for 2.0 may want to rename widgetId to dojo._scopeName + "_widgetId",
// assuming that dojo._scopeName even exists in 2.0
this.domNode.setAttribute("widgetId", this.id);
}
this.postCreate();
// If srcNodeRef has been processed and removed from the DOM (e.g. TemplatedWidget) then delete it to allow GC.
if(this.srcNodeRef && !this.srcNodeRef.parentNode){
delete this.srcNodeRef;
}
this._created = true;
},
_applyAttributes: function(){
// summary:
// Step during widget creation to copy widget attributes to the
// DOM according to attributeMap and _setXXXAttr objects, and also to call
// custom _setXXXAttr() methods.
//
// Skips over blank/false attribute values, unless they were explicitly specified
// as parameters to the widget, since those are the default anyway,
// and setting tabIndex="" is different than not setting tabIndex at all.
//
// For backwards-compatibility reasons attributeMap overrides _setXXXAttr when
// _setXXXAttr is a hash/string/array, but _setXXXAttr as a functions override attributeMap.
// tags:
// private
// Get list of attributes where this.set(name, value) will do something beyond
// setting this[name] = value. Specifically, attributes that have:
// - associated _setXXXAttr() method/hash/string/array
// - entries in attributeMap.
var ctor = this.constructor,
list = ctor._setterAttrs;
if(!list){
list = (ctor._setterAttrs = []);
for(var attr in this.attributeMap){
list.push(attr);
}
var proto = ctor.prototype;
for(var fxName in proto){
if(fxName in this.attributeMap){ continue; }
var setterName = "_set" + fxName.replace(/^[a-z]|-[a-zA-Z]/g, function(c){ return c.charAt(c.length-1).toUpperCase(); }) + "Attr";
if(setterName in proto){
list.push(fxName);
}
}
}
// Call this.set() for each attribute that was either specified as parameter to constructor,
// or was found above and has a default non-null value. For correlated attributes like value and displayedValue, the one
// specified as a parameter should take precedence, so apply attributes in this.params last.
// Particularly important for new DateTextBox({displayedValue: ...}) since DateTextBox's default value is
// NaN and thus is not ignored like a default value of "".
array.forEach(list, function(attr){
if(this.params && attr in this.params){
// skip this one, do it below
}else if(this[attr]){
this.set(attr, this[attr]);
}
}, this);
for(var param in this.params){
this.set(param, this[param]);
}
},
postMixInProperties: function(){
// summary:
// Called after the parameters to the widget have been read-in,
// but before the widget template is instantiated. Especially
// useful to set properties that are referenced in the widget
// template.
// tags:
// protected
},
buildRendering: function(){
// summary:
// Construct the UI for this widget, setting this.domNode.
// Most widgets will mixin `dijit._TemplatedMixin`, which implements this method.
// tags:
// protected
if(!this.domNode){
// Create root node if it wasn't created by _Templated
this.domNode = this.srcNodeRef || domConstruct.create('div');
}
// baseClass is a single class name or occasionally a space-separated list of names.
// Add those classes to the DOMNode. If RTL mode then also add with Rtl suffix.
// TODO: make baseClass custom setter
if(this.baseClass){
var classes = this.baseClass.split(" ");
if(!this.isLeftToRight()){
classes = classes.concat( array.map(classes, function(name){ return name+"Rtl"; }));
}
domClass.add(this.domNode, classes);
}
},
postCreate: function(){
// summary:
// Processing after the DOM fragment is created
// description:
// Called after the DOM fragment has been created, but not necessarily
// added to the document. Do not include any operations which rely on
// node dimensions or placement.
// tags:
// protected
},
startup: function(){
// summary:
// Processing after the DOM fragment is added to the document
// description:
// Called after a widget and its children have been created and added to the page,
// and all related widgets have finished their create() cycle, up through postCreate().
// This is useful for composite widgets that need to control or layout sub-widgets.
// Many layout widgets can use this as a wiring phase.
if(this._started){ return; }
this._started = true;
array.forEach(this.getChildren(), function(obj){
if(!obj._started && !obj._destroyed && lang.isFunction(obj.startup)){
obj.startup();
obj._started = true;
}
});
},
//////////// DESTROY FUNCTIONS ////////////////////////////////
destroyRecursive: function(/*Boolean?*/ preserveDom){
// summary:
// Destroy this widget and its descendants
// description:
// This is the generic "destructor" function that all widget users
// should call to cleanly discard with a widget. Once a widget is
// destroyed, it is removed from the manager object.
// preserveDom:
// If true, this method will leave the original DOM structure
// alone of descendant Widgets. Note: This will NOT work with
// dijit._Templated widgets.
this._beingDestroyed = true;
this.destroyDescendants(preserveDom);
this.destroy(preserveDom);
},
destroy: function(/*Boolean*/ preserveDom){
// summary:
// Destroy this widget, but not its descendants.
// This method will, however, destroy internal widgets such as those used within a template.
// preserveDom: Boolean
// If true, this method will leave the original DOM structure alone.
// Note: This will not yet work with _Templated widgets
this._beingDestroyed = true;
this.uninitialize();
// remove this.connect() and this.subscribe() listeners
var c;
while(c = this._connects.pop()){
c.remove();
}
// destroy widgets created as part of template, etc.
var w;
while(w = this._supportingWidgets.pop()){
if(w.destroyRecursive){
w.destroyRecursive();
}else if(w.destroy){
w.destroy();
}
}
this.destroyRendering(preserveDom);
registry.remove(this.id);
this._destroyed = true;
},
destroyRendering: function(/*Boolean?*/ preserveDom){
// summary:
// Destroys the DOM nodes associated with this widget
// preserveDom:
// If true, this method will leave the original DOM structure alone
// during tear-down. Note: this will not work with _Templated
// widgets yet.
// tags:
// protected
if(this.bgIframe){
this.bgIframe.destroy(preserveDom);
delete this.bgIframe;
}
if(this.domNode){
if(preserveDom){
domAttr.remove(this.domNode, "widgetId");
}else{
domConstruct.destroy(this.domNode);
}
delete this.domNode;
}
if(this.srcNodeRef){
if(!preserveDom){
domConstruct.destroy(this.srcNodeRef);
}
delete this.srcNodeRef;
}
},
destroyDescendants: function(/*Boolean?*/ preserveDom){
// summary:
// Recursively destroy the children of this widget and their
// descendants.
// preserveDom:
// If true, the preserveDom attribute is passed to all descendant
// widget's .destroy() method. Not for use with _Templated
// widgets.
// get all direct descendants and destroy them recursively
array.forEach(this.getChildren(), function(widget){
if(widget.destroyRecursive){
widget.destroyRecursive(preserveDom);
}
});
},
uninitialize: function(){
// summary:
// Stub function. Override to implement custom widget tear-down
// behavior.
// tags:
// protected
return false;
},
////////////////// GET/SET, CUSTOM SETTERS, ETC. ///////////////////
_setStyleAttr: function(/*String||Object*/ value){
// summary:
// Sets the style attribute of the widget according to value,
// which is either a hash like {height: "5px", width: "3px"}
// or a plain string
// description:
// Determines which node to set the style on based on style setting
// in attributeMap.
// tags:
// protected
var mapNode = this.domNode;
// Note: technically we should revert any style setting made in a previous call
// to his method, but that's difficult to keep track of.
if(lang.isObject(value)){
domStyle.set(mapNode, value);
}else{
if(mapNode.style.cssText){
mapNode.style.cssText += "; " + value;
}else{
mapNode.style.cssText = value;
}
}
this._set("style", value);
},
_attrToDom: function(/*String*/ attr, /*String*/ value, /*Object?*/ commands){
// summary:
// Reflect a widget attribute (title, tabIndex, duration etc.) to
// the widget DOM, as specified by commands parameter.
// If commands isn't specified then it's looked up from attributeMap.
// Note some attributes like "type"
// cannot be processed this way as they are not mutable.
//
// tags:
// private
commands = arguments.length >= 3 ? commands : this.attributeMap[attr];
array.forEach(lang.isArray(commands) ? commands : [commands], function(command){
// Get target node and what we are doing to that node
var mapNode = this[command.node || command || "domNode"]; // DOM node
var type = command.type || "attribute"; // class, innerHTML, innerText, or attribute
switch(type){
case "attribute":
if(lang.isFunction(value)){ // functions execute in the context of the widget
value = lang.hitch(this, value);
}
// Get the name of the DOM node attribute; usually it's the same
// as the name of the attribute in the widget (attr), but can be overridden.
// Also maps handler names to lowercase, like onSubmit --> onsubmit
var attrName = command.attribute ? command.attribute :
(/^on[A-Z][a-zA-Z]*$/.test(attr) ? attr.toLowerCase() : attr);
domAttr.set(mapNode, attrName, value);
break;
case "innerText":
mapNode.innerHTML = "";
mapNode.appendChild(win.doc.createTextNode(value));
break;
case "innerHTML":
mapNode.innerHTML = value;
break;
case "class":
domClass.replace(mapNode, value, this[attr]);
break;
}
}, this);
},
get: function(name){
// summary:
// Get a property from a widget.
// name:
// The property to get.
// description:
// Get a named property from a widget. The property may
// potentially be retrieved via a getter method. If no getter is defined, this
// just retrieves the object's property.
//
// For example, if the widget has properties `foo` and `bar`
// and a method named `_getFooAttr()`, calling:
// `myWidget.get("foo")` would be equivalent to calling
// `widget._getFooAttr()` and `myWidget.get("bar")`
// would be equivalent to the expression
// `widget.bar2`
var names = this._getAttrNames(name);
return this[names.g] ? this[names.g]() : this[name];
},
set: function(name, value){
// summary:
// Set a property on a widget
// name:
// The property to set.
// value:
// The value to set in the property.
// description:
// Sets named properties on a widget which may potentially be handled by a
// setter in the widget.
//
// For example, if the widget has properties `foo` and `bar`
// and a method named `_setFooAttr()`, calling
// `myWidget.set("foo", "Howdy!")` would be equivalent to calling
// `widget._setFooAttr("Howdy!")` and `myWidget.set("bar", 3)`
// would be equivalent to the statement `widget.bar = 3;`
//
// set() may also be called with a hash of name/value pairs, ex:
//
// | myWidget.set({
// | foo: "Howdy",
// | bar: 3
// | });
//
// This is equivalent to calling `set(foo, "Howdy")` and `set(bar, 3)`
if(typeof name === "object"){
for(var x in name){
this.set(x, name[x]);
}
return this;
}
var names = this._getAttrNames(name),
setter = this[names.s];
if(lang.isFunction(setter)){
// use the explicit setter
var result = setter.apply(this, Array.prototype.slice.call(arguments, 1));
}else{
// Mapping from widget attribute to DOMNode attribute/value/etc.
// Map according to:
// 1. attributeMap setting, if one exists (TODO: attributeMap deprecated, remove in 2.0)
// 2. _setFooAttr: {...} type attribute in the widget (if one exists)
// 3. apply to focusNode or domNode if standard attribute name, excluding funcs like onClick.
// Checks if an attribute is a "standard attribute" by whether the DOMNode JS object has a similar
// attribute name (ex: accept-charset attribute matches jsObject.acceptCharset).
// Note also that Tree.focusNode() is a function not a DOMNode, so test for that.
var defaultNode = this.focusNode && !lang.isFunction(this.focusNode) ? "focusNode" : "domNode",
tag = this[defaultNode].tagName,
attrsForTag = tagAttrs[tag] || (tagAttrs[tag] = getAttrs(this[defaultNode])),
map = name in this.attributeMap ? this.attributeMap[name] :
names.s in this ? this[names.s] :
((names.l in attrsForTag && typeof value != "function") ||
/^aria-|^data-|^role$/.test(name)) ? defaultNode : null;
if(map != null){
this._attrToDom(name, value, map);
}
this._set(name, value);
}
return result || this;
},
_attrPairNames: {}, // shared between all widgets
_getAttrNames: function(name){
// summary:
// Helper function for get() and set().
// Caches attribute name values so we don't do the string ops every time.
// tags:
// private
var apn = this._attrPairNames;
if(apn[name]){ return apn[name]; }
var uc = name.replace(/^[a-z]|-[a-zA-Z]/g, function(c){ return c.charAt(c.length-1).toUpperCase(); });
return (apn[name] = {
n: name+"Node",
s: "_set"+uc+"Attr", // converts dashes to camel case, ex: accept-charset --> _setAcceptCharsetAttr
g: "_get"+uc+"Attr",
l: uc.toLowerCase() // lowercase name w/out dashes, ex: acceptcharset
});
},
_set: function(/*String*/ name, /*anything*/ value){
// summary:
// Helper function to set new value for specified attribute, and call handlers
// registered with watch() if the value has changed.
var oldValue = this[name];
this[name] = value;
if(this._watchCallbacks && this._created && value !== oldValue){
this._watchCallbacks(name, oldValue, value);
}
},
on: function(/*String*/ type, /*Function*/ func){
// summary:
// Call specified function when event occurs, ex: myWidget.on("click", function(){ ... }).
// description:
// Call specified function when event `type` occurs, ex: `myWidget.on("click", function(){ ... })`.
// Note that the function is not run in any particular scope, so if (for example) you want it to run in the
// widget's scope you must do `myWidget.on("click", lang.hitch(myWidget, func))`.
return aspect.after(this, this._onMap(type), func, true);
},
_onMap: function(/*String*/ type){
// summary:
// Maps on() type parameter (ex: "mousemove") to method name (ex: "onMouseMove")
var ctor = this.constructor, map = ctor._onMap;
if(!map){
map = (ctor._onMap = {});
for(var attr in ctor.prototype){
if(/^on/.test(attr)){
map[attr.replace(/^on/, "").toLowerCase()] = attr;
}
}
}
return map[type.toLowerCase()]; // String
},
toString: function(){
// summary:
// Returns a string that represents the widget
// description:
// When a widget is cast to a string, this method will be used to generate the
// output. Currently, it does not implement any sort of reversible
// serialization.
return '[Widget ' + this.declaredClass + ', ' + (this.id || 'NO ID') + ']'; // String
},
getChildren: function(){
// summary:
// Returns all the widgets contained by this, i.e., all widgets underneath this.containerNode.
// Does not return nested widgets, nor widgets that are part of this widget's template.
return this.containerNode ? registry.findWidgets(this.containerNode) : []; // dijit._Widget[]
},
getParent: function(){
// summary:
// Returns the parent widget of this widget
return registry.getEnclosingWidget(this.domNode.parentNode);
},
connect: function(
/*Object|null*/ obj,
/*String|Function*/ event,
/*String|Function*/ method){
// summary:
// Connects specified obj/event to specified method of this object
// and registers for disconnect() on widget destroy.
// description:
// Provide widget-specific analog to dojo.connect, except with the
// implicit use of this widget as the target object.
// Events connected with `this.connect` are disconnected upon
// destruction.
// returns:
// A handle that can be passed to `disconnect` in order to disconnect before
// the widget is destroyed.
// example:
// | var btn = new dijit.form.Button();
// | // when foo.bar() is called, call the listener we're going to
// | // provide in the scope of btn
// | btn.connect(foo, "bar", function(){
// | console.debug(this.toString());
// | });
// tags:
// protected
var handle = connect.connect(obj, event, this, method);
this._connects.push(handle);
return handle; // _Widget.Handle
},
disconnect: function(handle){
// summary:
// Disconnects handle created by `connect`.
// Also removes handle from this widget's list of connects.
// tags:
// protected
var i = array.indexOf(this._connects, handle);
if(i != -1){
handle.remove();
this._connects.splice(i, 1);
}
},
subscribe: function(t, method){
// summary:
// Subscribes to the specified topic and calls the specified method
// of this object and registers for unsubscribe() on widget destroy.
// description:
// Provide widget-specific analog to dojo.subscribe, except with the
// implicit use of this widget as the target object.
// t: String
// The topic
// method: Function
// The callback
// example:
// | var btn = new dijit.form.Button();
// | // when /my/topic is published, this button changes its label to
// | // be the parameter of the topic.
// | btn.subscribe("/my/topic", function(v){
// | this.set("label", v);
// | });
// tags:
// protected
var handle = topic.subscribe(t, lang.hitch(this, method));
this._connects.push(handle);
return handle; // _Widget.Handle
},
unsubscribe: function(/*Object*/ handle){
// summary:
// Unsubscribes handle created by this.subscribe.
// Also removes handle from this widget's list of subscriptions
// tags:
// protected
this.disconnect(handle);
},
isLeftToRight: function(){
// summary:
// Return this widget's explicit or implicit orientation (true for LTR, false for RTL)
// tags:
// protected
return this.dir ? (this.dir == "ltr") : domGeometry.isBodyLtr(); //Boolean
},
isFocusable: function(){
// summary:
// Return true if this widget can currently be focused
// and false if not
return this.focus && (domStyle.get(this.domNode, "display") != "none");
},
placeAt: function(/* String|DomNode|_Widget */reference, /* String?|Int? */position){
// summary:
// Place this widget's domNode reference somewhere in the DOM based
// on standard domConstruct.place conventions, or passing a Widget reference that
// contains and addChild member.
//
// description:
// A convenience function provided in all _Widgets, providing a simple
// shorthand mechanism to put an existing (or newly created) Widget
// somewhere in the dom, and allow chaining.
//
// reference:
// The String id of a domNode, a domNode reference, or a reference to a Widget possessing
// an addChild method.
//
// position:
// If passed a string or domNode reference, the position argument
// accepts a string just as domConstruct.place does, one of: "first", "last",
// "before", or "after".
//
// If passed a _Widget reference, and that widget reference has an ".addChild" method,
// it will be called passing this widget instance into that method, supplying the optional
// position index passed.
//
// returns:
// dijit._Widget
// Provides a useful return of the newly created dijit._Widget instance so you
// can "chain" this function by instantiating, placing, then saving the return value
// to a variable.
//
// example:
// | // create a Button with no srcNodeRef, and place it in the body:
// | var button = new dijit.form.Button({ label:"click" }).placeAt(win.body());
// | // now, 'button' is still the widget reference to the newly created button
// | button.on("click", function(e){ console.log('click'); }));
//
// example:
// | // create a button out of a node with id="src" and append it to id="wrapper":
// | var button = new dijit.form.Button({},"src").placeAt("wrapper");
//
// example:
// | // place a new button as the first element of some div
// | var button = new dijit.form.Button({ label:"click" }).placeAt("wrapper","first");
//
// example:
// | // create a contentpane and add it to a TabContainer
// | var tc = dijit.byId("myTabs");
// | new dijit.layout.ContentPane({ href:"foo.html", title:"Wow!" }).placeAt(tc)
if(reference.declaredClass && reference.addChild){
reference.addChild(this, position);
}else{
domConstruct.place(this.domNode, reference, position);
}
return this;
},
getTextDir: function(/*String*/ text,/*String*/ originalDir){
// summary:
// Return direction of the text.
// The function overridden in the _BidiSupport module,
// its main purpose is to calculate the direction of the
// text, if was defined by the programmer through textDir.
// tags:
// protected.
return originalDir;
},
applyTextDir: function(/*===== element, text =====*/){
// summary:
// The function overridden in the _BidiSupport module,
// originally used for setting element.dir according to this.textDir.
// In this case does nothing.
// element: DOMNode
// text: String
// tags:
// protected.
}
});
});
}}});
require(["dojo/i18n"], function(i18n){
i18n._preloadLocalizations("dojox/charting/widget/nls/Chart2D", []);
});
define("dojox/charting/widget/Chart2D", ["dojo/_base/kernel", "./Chart", "../Chart2D",
"../action2d/Highlight", "../action2d/Magnify",
"../action2d/MoveSlice", "../action2d/Shake", "../action2d/Tooltip"], function(dojo, Chart) {
dojo.deprecated("dojox.charting.widget.Chart2D", "Use dojo.charting.widget.Chart instead and require all other components explicitly", "2.0");
return dojox.charting.widget.Chart2D = Chart;
});
| {
"content_hash": "3aaa92250fa2242ec37510aa76a2b2d7",
"timestamp": "",
"source": "github",
"line_count": 19335,
"max_line_length": 345,
"avg_line_length": 32.86128782001552,
"alnum_prop": 0.6216521633748995,
"repo_name": "cfxram/grails-dojo",
"id": "7510f20363c6255990d7e650d9c9666ef2b36450",
"size": "635567",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "web-app/js/dojo/1.7.2/dojox/charting/widget/Chart2D.js.uncompressed.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "19954"
},
{
"name": "CSS",
"bytes": "2579518"
},
{
"name": "Groovy",
"bytes": "102829"
},
{
"name": "JavaScript",
"bytes": "18492972"
},
{
"name": "PHP",
"bytes": "38090"
},
{
"name": "Shell",
"bytes": "9076"
},
{
"name": "XSLT",
"bytes": "47380"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "567b77fb3611d27e7814def8b5ee4168",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "a2cbbe809f2f9333b9fd9bbe598526e556848147",
"size": "187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Xanthorrhoeaceae/Asphodeline/Asphodeline baytopiae/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using namespace swift;
typedef llvm::SmallSet<unsigned, 4> IndicesSet;
typedef llvm::DenseMap<PartialApplyInst*, IndicesSet> PartialApplyIndicesMap;
STATISTIC(NumCapturesPromoted, "Number of captures promoted");
namespace {
/// Transient reference to a block set within ReachabilityInfo.
///
/// This is a bitset that conveniently flattens into a matrix allowing bit-wise
/// operations without masking.
///
/// TODO: If this sticks around, maybe we'll make a BitMatrix ADT.
class ReachingBlockSet {
public:
enum { BITWORD_SIZE = (unsigned)sizeof(uint64_t) * CHAR_BIT };
static size_t numBitWords(unsigned NumBlocks) {
return (NumBlocks + BITWORD_SIZE - 1) / BITWORD_SIZE;
}
/// Transient reference to a reaching block matrix.
struct ReachingBlockMatrix {
uint64_t *Bits;
unsigned NumBitWords; // Words per row.
ReachingBlockMatrix() : Bits(nullptr), NumBitWords(0) {}
bool empty() const { return !Bits; }
};
static ReachingBlockMatrix allocateMatrix(unsigned NumBlocks) {
ReachingBlockMatrix M;
M.NumBitWords = numBitWords(NumBlocks);
M.Bits = new uint64_t[NumBlocks * M.NumBitWords];
memset(M.Bits, 0, NumBlocks * M.NumBitWords * sizeof(uint64_t));
return M;
}
static void deallocateMatrix(ReachingBlockMatrix &M) {
delete [] M.Bits;
M.Bits = nullptr;
M.NumBitWords = 0;
}
static ReachingBlockSet allocateSet(unsigned NumBlocks) {
ReachingBlockSet S;
S.NumBitWords = numBitWords(NumBlocks);
S.Bits = new uint64_t[S.NumBitWords];
return S;
}
static void deallocateSet(ReachingBlockSet &S) {
delete [] S.Bits;
S.Bits = nullptr;
S.NumBitWords = 0;
}
private:
uint64_t *Bits;
unsigned NumBitWords;
public:
ReachingBlockSet() : Bits(nullptr), NumBitWords(0) {}
ReachingBlockSet(unsigned BlockID, ReachingBlockMatrix &M)
: Bits(&M.Bits[BlockID * M.NumBitWords]),
NumBitWords(M.NumBitWords) {}
bool test(unsigned ID) const {
assert(ID / BITWORD_SIZE < NumBitWords && "block ID out-of-bounds");
unsigned int modulus = ID % BITWORD_SIZE;
long shifted = 1L << modulus;
return Bits[ID / BITWORD_SIZE] & shifted;
}
void set(unsigned ID) {
unsigned int modulus = ID % BITWORD_SIZE;
long shifted = 1L << modulus;
assert(ID / BITWORD_SIZE < NumBitWords && "block ID out-of-bounds");
Bits[ID / BITWORD_SIZE] |= shifted;
}
ReachingBlockSet &operator|=(const ReachingBlockSet &RHS) {
for (size_t i = 0, e = NumBitWords; i != e; ++i)
Bits[i] |= RHS.Bits[i];
return *this;
}
void clear() {
memset(Bits, 0, NumBitWords * sizeof(uint64_t));
}
bool operator==(const ReachingBlockSet &RHS) const {
assert(NumBitWords == RHS.NumBitWords && "mismatched sets");
for (size_t i = 0, e = NumBitWords; i != e; ++i) {
if (Bits[i] != RHS.Bits[i])
return false;
}
return true;
}
bool operator!=(const ReachingBlockSet &RHS) const {
return !(*this == RHS);
}
const ReachingBlockSet &operator=(const ReachingBlockSet &RHS) {
assert(NumBitWords == RHS.NumBitWords && "mismatched sets");
for (size_t i = 0, e = NumBitWords; i != e; ++i)
Bits[i] = RHS.Bits[i];
return *this;
}
};
/// Store the reachability matrix: ToBlock -> FromBlocks.
class ReachabilityInfo {
SILFunction *F;
llvm::DenseMap<SILBasicBlock*, unsigned> BlockMap;
ReachingBlockSet::ReachingBlockMatrix Matrix;
public:
ReachabilityInfo(SILFunction *f) : F(f) {}
~ReachabilityInfo() { ReachingBlockSet::deallocateMatrix(Matrix); }
bool isComputed() const { return !Matrix.empty(); }
bool isReachable(SILBasicBlock *From, SILBasicBlock *To);
private:
void compute();
};
} // end anonymous namespace
namespace {
/// A SILCloner subclass which clones a closure function while converting
/// one or more captures from 'inout' (by-reference) to by-value.
class ClosureCloner : public SILClonerWithScopes<ClosureCloner> {
public:
friend class SILInstructionVisitor<ClosureCloner>;
friend class SILCloner<ClosureCloner>;
ClosureCloner(SILOptFunctionBuilder &FuncBuilder,
SILFunction *Orig, IsSerialized_t Serialized,
StringRef ClonedName,
IndicesSet &PromotableIndices);
void populateCloned();
SILFunction *getCloned() { return &getBuilder().getFunction(); }
private:
static SILFunction *initCloned(SILOptFunctionBuilder &FuncBuilder,
SILFunction *Orig, IsSerialized_t Serialized,
StringRef ClonedName,
IndicesSet &PromotableIndices);
SILValue getProjectBoxMappedVal(SILValue Operand);
void visitDebugValueAddrInst(DebugValueAddrInst *Inst);
void visitStrongReleaseInst(StrongReleaseInst *Inst);
void visitDestroyValueInst(DestroyValueInst *Inst);
void visitStructElementAddrInst(StructElementAddrInst *Inst);
void visitLoadInst(LoadInst *Inst);
void visitLoadBorrowInst(LoadBorrowInst *Inst);
void visitProjectBoxInst(ProjectBoxInst *Inst);
void visitBeginAccessInst(BeginAccessInst *Inst);
void visitEndAccessInst(EndAccessInst *Inst);
SILFunction *Orig;
IndicesSet &PromotableIndices;
llvm::DenseMap<SILArgument *, SILValue> BoxArgumentMap;
llvm::DenseMap<ProjectBoxInst *, SILValue> ProjectBoxArgumentMap;
};
} // end anonymous namespace
/// Compute ReachabilityInfo so that it can answer queries about
/// whether a given basic block in a function is reachable from another basic
/// block in the function.
///
/// FIXME: Computing global reachability requires initializing an N^2
/// bitset. This could be avoided by computing reachability on-the-fly
/// for each alloc_box by walking backward from mutations.
void ReachabilityInfo::compute() {
assert(!isComputed() && "already computed");
unsigned N = 0;
for (auto &BB : *F)
BlockMap.insert({ &BB, N++ });
Matrix = ReachingBlockSet::allocateMatrix(N);
ReachingBlockSet NewSet = ReachingBlockSet::allocateSet(N);
LLVM_DEBUG(llvm::dbgs() << "Computing Reachability for " << F->getName()
<< " with " << N << " blocks.\n");
// Iterate to a fix point, two times for a topological DAG.
bool Changed;
do {
Changed = false;
// Visit all blocks in a predictable order, hopefully close to topological.
for (auto &BB : *F) {
ReachingBlockSet CurSet(BlockMap[&BB], Matrix);
if (!Changed) {
// If we have not detected a change yet, then calculate new
// reachabilities into a new bit vector so we can determine if any
// change has occurred.
NewSet = CurSet;
for (auto PI = BB.pred_begin(), PE = BB.pred_end(); PI != PE; ++PI) {
unsigned PredID = BlockMap[*PI];
ReachingBlockSet PredSet(PredID, Matrix);
NewSet |= PredSet;
NewSet.set(PredID);
}
if (NewSet != CurSet) {
CurSet = NewSet;
Changed = true;
}
} else {
// Otherwise, just update the existing reachabilities in-place.
for (auto PI = BB.pred_begin(), PE = BB.pred_end(); PI != PE; ++PI) {
unsigned PredID = BlockMap[*PI];
ReachingBlockSet PredSet(PredID, Matrix);
CurSet |= PredSet;
CurSet.set(PredID);
}
}
LLVM_DEBUG(llvm::dbgs() << " Block " << BlockMap[&BB] << " reached by ";
for (unsigned i = 0; i < N; ++i) {
if (CurSet.test(i))
llvm::dbgs() << i << " ";
}
llvm::dbgs() << "\n");
}
} while (Changed);
ReachingBlockSet::deallocateSet(NewSet);
}
/// Return true if the To basic block is reachable from the From basic
/// block. A block is considered reachable from itself only if its entry can be
/// recursively reached from its own exit.
bool
ReachabilityInfo::isReachable(SILBasicBlock *From, SILBasicBlock *To) {
if (!isComputed())
compute();
auto FI = BlockMap.find(From), TI = BlockMap.find(To);
assert(FI != BlockMap.end() && TI != BlockMap.end());
ReachingBlockSet FromSet(TI->second, Matrix);
return FromSet.test(FI->second);
}
ClosureCloner::ClosureCloner(SILOptFunctionBuilder &FuncBuilder,
SILFunction *Orig, IsSerialized_t Serialized,
StringRef ClonedName,
IndicesSet &PromotableIndices)
: SILClonerWithScopes<ClosureCloner>(
*initCloned(FuncBuilder, Orig, Serialized, ClonedName, PromotableIndices)),
Orig(Orig), PromotableIndices(PromotableIndices) {
assert(Orig->getDebugScope()->Parent != getCloned()->getDebugScope()->Parent);
}
/// Compute the SILParameterInfo list for the new cloned closure.
///
/// Our goal as a result of this transformation is to:
///
/// 1. Let through all arguments not related to a promotable box.
/// 2. Replace container box value arguments for the cloned closure with the
/// transformed address or value argument.
static void
computeNewArgInterfaceTypes(SILFunction *F,
IndicesSet &PromotableIndices,
SmallVectorImpl<SILParameterInfo> &OutTys) {
auto fnConv = F->getConventions();
auto Parameters = fnConv.funcTy->getParameters();
LLVM_DEBUG(llvm::dbgs() << "Preparing New Args!\n");
auto fnTy = F->getLoweredFunctionType();
auto &Types = F->getModule().Types;
Lowering::GenericContextScope scope(Types, fnTy->getGenericSignature());
// For each parameter in the old function...
for (unsigned Index : indices(Parameters)) {
auto ¶m = Parameters[Index];
// The PromotableIndices index is expressed as the argument index (num
// indirect result + param index). Add back the num indirect results to get
// the arg index when working with PromotableIndices.
unsigned ArgIndex = Index + fnConv.getSILArgIndexOfFirstParam();
LLVM_DEBUG(llvm::dbgs() << "Index: " << Index << "; PromotableIndices: "
<< (PromotableIndices.count(ArgIndex)?"yes":"no")
<< " Param: "; param.dump());
if (!PromotableIndices.count(ArgIndex)) {
OutTys.push_back(param);
continue;
}
// Perform the proper conversions and then add it to the new parameter list
// for the type.
assert(!param.isFormalIndirect());
auto paramTy = param.getSILStorageType();
auto paramBoxTy = paramTy.castTo<SILBoxType>();
assert(paramBoxTy->getLayout()->getFields().size() == 1
&& "promoting compound box not implemented yet");
auto paramBoxedTy = paramBoxTy->getFieldType(F->getModule(), 0);
auto ¶mTL = Types.getTypeLowering(paramBoxedTy);
ParameterConvention convention;
if (paramTL.isFormallyPassedIndirectly()) {
convention = ParameterConvention::Indirect_In;
} else if (paramTL.isTrivial()) {
convention = ParameterConvention::Direct_Unowned;
} else {
convention = param.isGuaranteed() ? ParameterConvention::Direct_Guaranteed
: ParameterConvention::Direct_Owned;
}
OutTys.push_back(SILParameterInfo(paramBoxedTy.getASTType(),
convention));
}
}
static std::string getSpecializedName(SILFunction *F,
IsSerialized_t Serialized,
IndicesSet &PromotableIndices) {
auto P = Demangle::SpecializationPass::CapturePromotion;
Mangle::FunctionSignatureSpecializationMangler Mangler(P, Serialized, F);
auto fnConv = F->getConventions();
for (unsigned argIdx = 0, endIdx = fnConv.getNumSILArguments();
argIdx < endIdx; ++argIdx) {
if (!PromotableIndices.count(argIdx))
continue;
Mangler.setArgumentBoxToValue(argIdx);
}
return Mangler.mangle();
}
/// Create the function corresponding to the clone of the original
/// closure with the signature modified to reflect promotable captures (which
/// are given by PromotableIndices, such that each entry in the set is the
/// index of the box containing the variable in the closure's argument list, and
/// the address of the box's contents is the argument immediately following each
/// box argument); does not actually clone the body of the function
///
/// *NOTE* PromotableIndices only contains the container value of the box, not
/// the address value.
SILFunction*
ClosureCloner::initCloned(SILOptFunctionBuilder &FunctionBuilder,
SILFunction *Orig, IsSerialized_t Serialized,
StringRef ClonedName,
IndicesSet &PromotableIndices) {
SILModule &M = Orig->getModule();
// Compute the arguments for our new function.
SmallVector<SILParameterInfo, 4> ClonedInterfaceArgTys;
computeNewArgInterfaceTypes(Orig, PromotableIndices, ClonedInterfaceArgTys);
SILFunctionType *OrigFTI = Orig->getLoweredFunctionType();
// Create the thin function type for the cloned closure.
auto ClonedTy = SILFunctionType::get(
OrigFTI->getGenericSignature(), OrigFTI->getExtInfo(),
OrigFTI->getCoroutineKind(), OrigFTI->getCalleeConvention(),
ClonedInterfaceArgTys, OrigFTI->getYields(),
OrigFTI->getResults(), OrigFTI->getOptionalErrorResult(),
M.getASTContext(), OrigFTI->getWitnessMethodConformanceOrNone());
assert((Orig->isTransparent() || Orig->isBare() || Orig->getLocation())
&& "SILFunction missing location");
assert((Orig->isTransparent() || Orig->isBare() || Orig->getDebugScope())
&& "SILFunction missing DebugScope");
assert(!Orig->isGlobalInit() && "Global initializer cannot be cloned");
auto *Fn = FunctionBuilder.createFunction(
Orig->getLinkage(), ClonedName, ClonedTy, Orig->getGenericEnvironment(),
Orig->getLocation(), Orig->isBare(), IsNotTransparent, Serialized,
IsNotDynamic, Orig->getEntryCount(), Orig->isThunk(),
Orig->getClassSubclassScope(), Orig->getInlineStrategy(),
Orig->getEffectsKind(), Orig, Orig->getDebugScope());
for (auto &Attr : Orig->getSemanticsAttrs())
Fn->addSemanticsAttr(Attr);
if (!Orig->hasOwnership()) {
Fn->setOwnershipEliminated();
}
return Fn;
}
/// Populate the body of the cloned closure, modifying instructions as
/// necessary to take into consideration the promoted capture(s)
void
ClosureCloner::populateCloned() {
SILFunction *Cloned = getCloned();
// Create arguments for the entry block
SILBasicBlock *OrigEntryBB = &*Orig->begin();
SILBasicBlock *ClonedEntryBB = Cloned->createBasicBlock();
getBuilder().setInsertionPoint(ClonedEntryBB);
SmallVector<SILValue, 4> entryArgs;
entryArgs.reserve(OrigEntryBB->getArguments().size());
unsigned ArgNo = 0;
auto I = OrigEntryBB->args_begin(), E = OrigEntryBB->args_end();
for (; I != E; ++ArgNo, ++I) {
if (!PromotableIndices.count(ArgNo)) {
// Simply create a new argument which copies the original argument
SILValue MappedValue = ClonedEntryBB->createFunctionArgument(
(*I)->getType(), (*I)->getDecl());
entryArgs.push_back(MappedValue);
continue;
}
// Handle the case of a promoted capture argument.
auto BoxTy = (*I)->getType().castTo<SILBoxType>();
assert(BoxTy->getLayout()->getFields().size() == 1 &&
"promoting compound box not implemented");
auto BoxedTy = BoxTy->getFieldType(Cloned->getModule(), 0).getObjectType();
SILValue MappedValue =
ClonedEntryBB->createFunctionArgument(BoxedTy, (*I)->getDecl());
// If SIL ownership is enabled, we need to perform a borrow here if we have
// a non-trivial value. We know that our value is not written to and it does
// not escape. The use of a borrow enforces this.
if (Cloned->hasOwnership() &&
MappedValue.getOwnershipKind() != ValueOwnershipKind::Any) {
SILLocation Loc(const_cast<ValueDecl *>((*I)->getDecl()));
MappedValue = getBuilder().createBeginBorrow(Loc, MappedValue);
}
entryArgs.push_back(MappedValue);
BoxArgumentMap.insert(std::make_pair(*I, MappedValue));
// Track the projections of the box.
for (auto *Use : (*I)->getUses()) {
if (auto Proj = dyn_cast<ProjectBoxInst>(Use->getUser())) {
ProjectBoxArgumentMap.insert(std::make_pair(Proj, MappedValue));
}
}
}
// Visit original BBs in depth-first preorder, starting with the
// entry block, cloning all instructions and terminators.
cloneFunctionBody(Orig, ClonedEntryBB, entryArgs);
}
/// If this operand originates from a mapped ProjectBox, return the mapped
/// value. Otherwise return an invalid value.
SILValue ClosureCloner::getProjectBoxMappedVal(SILValue Operand) {
if (auto *Access = dyn_cast<BeginAccessInst>(Operand))
Operand = Access->getSource();
if (auto *Project = dyn_cast<ProjectBoxInst>(Operand)) {
auto I = ProjectBoxArgumentMap.find(Project);
if (I != ProjectBoxArgumentMap.end())
return I->second;
}
return SILValue();
}
/// Handle a debug_value_addr instruction during cloning of a closure;
/// if its operand is the promoted address argument then lower it to a
/// debug_value, otherwise it is handled normally.
void ClosureCloner::visitDebugValueAddrInst(DebugValueAddrInst *Inst) {
if (SILValue Val = getProjectBoxMappedVal(Inst->getOperand())) {
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
getBuilder().createDebugValue(Inst->getLoc(), Val, *Inst->getVarInfo());
return;
}
SILCloner<ClosureCloner>::visitDebugValueAddrInst(Inst);
}
/// Handle a strong_release instruction during cloning of a closure; if
/// it is a strong release of a promoted box argument, then it is replaced with
/// a ReleaseValue of the new object type argument, otherwise it is handled
/// normally.
void
ClosureCloner::visitStrongReleaseInst(StrongReleaseInst *Inst) {
assert(
!Inst->getFunction()->hasOwnership() &&
"Should not see strong release in a function with qualified ownership");
SILValue Operand = Inst->getOperand();
if (auto *A = dyn_cast<SILArgument>(Operand)) {
auto I = BoxArgumentMap.find(A);
if (I != BoxArgumentMap.end()) {
// Releases of the box arguments get replaced with ReleaseValue of the new
// object type argument.
SILFunction &F = getBuilder().getFunction();
auto &typeLowering = F.getModule().getTypeLowering(I->second->getType());
SILBuilderWithPostProcess<ClosureCloner, 1> B(this, Inst);
typeLowering.emitDestroyValue(B, Inst->getLoc(), I->second);
return;
}
}
SILCloner<ClosureCloner>::visitStrongReleaseInst(Inst);
}
/// Handle a destroy_value instruction during cloning of a closure; if
/// it is a strong release of a promoted box argument, then it is replaced with
/// a destroy_value of the new object type argument, otherwise it is handled
/// normally.
void ClosureCloner::visitDestroyValueInst(DestroyValueInst *Inst) {
SILValue Operand = Inst->getOperand();
if (auto *A = dyn_cast<SILArgument>(Operand)) {
auto I = BoxArgumentMap.find(A);
if (I != BoxArgumentMap.end()) {
// Releases of the box arguments get replaced with an end_borrow,
// destroy_value of the new object type argument.
SILFunction &F = getBuilder().getFunction();
auto &typeLowering = F.getModule().getTypeLowering(I->second->getType());
SILBuilderWithPostProcess<ClosureCloner, 1> B(this, Inst);
SILValue Value = I->second;
// If ownership is enabled, then we must emit a begin_borrow for any
// non-trivial value.
if (F.hasOwnership() &&
Value.getOwnershipKind() != ValueOwnershipKind::Any) {
auto *BBI = cast<BeginBorrowInst>(Value);
Value = BBI->getOperand();
B.createEndBorrow(Inst->getLoc(), BBI, Value);
}
typeLowering.emitDestroyValue(B, Inst->getLoc(), Value);
return;
}
}
SILCloner<ClosureCloner>::visitDestroyValueInst(Inst);
}
/// Handle a struct_element_addr instruction during cloning of a closure.
///
/// If its operand is the promoted address argument then ignore it, otherwise it
/// is handled normally.
void
ClosureCloner::visitStructElementAddrInst(StructElementAddrInst *Inst) {
if (getProjectBoxMappedVal(Inst->getOperand()))
return;
SILCloner<ClosureCloner>::visitStructElementAddrInst(Inst);
}
/// project_box of captured boxes can be eliminated.
void
ClosureCloner::visitProjectBoxInst(ProjectBoxInst *I) {
if (auto Arg = dyn_cast<SILArgument>(I->getOperand()))
if (BoxArgumentMap.count(Arg))
return;
SILCloner<ClosureCloner>::visitProjectBoxInst(I);
}
/// If its operand is the promoted address argument then ignore it, otherwise it
/// is handled normally.
void ClosureCloner::visitBeginAccessInst(BeginAccessInst *Inst) {
if (getProjectBoxMappedVal(Inst->getSource()))
return;
SILCloner<ClosureCloner>::visitBeginAccessInst(Inst);
}
/// If its operand is the promoted address argument then ignore it, otherwise it
/// is handled normally.
void ClosureCloner::visitEndAccessInst(EndAccessInst *Inst) {
if (getProjectBoxMappedVal(Inst->getBeginAccess()))
return;
SILCloner<ClosureCloner>::visitEndAccessInst(Inst);
}
/// Handle a load_borrow instruction during cloning of a closure.
///
/// The two relevant cases are a direct load from a promoted address argument or
/// a load of a struct_element_addr of a promoted address argument.
void ClosureCloner::visitLoadBorrowInst(LoadBorrowInst *LI) {
assert(LI->getFunction()->hasOwnership() &&
"We should only see a load borrow in ownership qualified SIL");
if (SILValue Val = getProjectBoxMappedVal(LI->getOperand())) {
// Loads of the address argument get eliminated completely; the uses of
// the loads get mapped to uses of the new object type argument.
//
// We assume that the value is already guaranteed.
assert(Val.getOwnershipKind().isCompatibleWith(ValueOwnershipKind::Guaranteed) &&
"Expected argument value to be guaranteed");
recordFoldedValue(LI, Val);
return;
}
SILCloner<ClosureCloner>::visitLoadBorrowInst(LI);
return;
}
/// Handle a load instruction during cloning of a closure.
///
/// The two relevant cases are a direct load from a promoted address argument or
/// a load of a struct_element_addr of a promoted address argument.
void ClosureCloner::visitLoadInst(LoadInst *LI) {
if (SILValue Val = getProjectBoxMappedVal(LI->getOperand())) {
// Loads of the address argument get eliminated completely; the uses of
// the loads get mapped to uses of the new object type argument.
//
// If we are compiling with SIL ownership, we need to take different
// behaviors depending on the type of load. Specifically, if we have a
// load [copy], then we need to add a copy_value here. If we have a take
// or trivial, we just propagate the value through.
if (LI->getFunction()->hasOwnership()
&& LI->getOwnershipQualifier() == LoadOwnershipQualifier::Copy) {
Val = getBuilder().createCopyValue(LI->getLoc(), Val);
}
recordFoldedValue(LI, Val);
return;
}
auto *SEAI = dyn_cast<StructElementAddrInst>(LI->getOperand());
if (!SEAI) {
SILCloner<ClosureCloner>::visitLoadInst(LI);
return;
}
if (SILValue Val = getProjectBoxMappedVal(SEAI->getOperand())) {
// Loads of a struct_element_addr of an argument get replaced with a
// struct_extract of the new passed in value. The value should be borrowed
// already, so we can just extract the value.
assert(!getBuilder().getFunction().hasOwnership() ||
Val.getOwnershipKind().isCompatibleWith(ValueOwnershipKind::Guaranteed));
Val = getBuilder().emitStructExtract(LI->getLoc(), Val, SEAI->getField(),
LI->getType());
// If we were performing a load [copy], then we need to a perform a copy
// here since when cloning, we do not eliminate the destroy on the copied
// value.
if (LI->getFunction()->hasOwnership()
&& LI->getOwnershipQualifier() == LoadOwnershipQualifier::Copy) {
Val = getBuilder().createCopyValue(LI->getLoc(), Val);
}
recordFoldedValue(LI, Val);
return;
}
SILCloner<ClosureCloner>::visitLoadInst(LI);
}
static SILArgument *getBoxFromIndex(SILFunction *F, unsigned Index) {
assert(F->isDefinition() && "Expected definition not external declaration!");
auto &Entry = F->front();
return Entry.getArgument(Index);
}
static bool isNonMutatingLoad(SILInstruction *I) {
auto *LI = dyn_cast<LoadInst>(I);
if (!LI)
return false;
return LI->getOwnershipQualifier() != LoadOwnershipQualifier::Take;
}
/// Given a partial_apply instruction and the argument index into its
/// callee's argument list of a box argument (which is followed by an argument
/// for the address of the box's contents), return true if the closure is known
/// not to mutate the captured variable.
static bool
isNonMutatingCapture(SILArgument *BoxArg) {
SmallVector<ProjectBoxInst*, 2> Projections;
// Conservatively do not allow any use of the box argument other than a
// strong_release or projection, since this is the pattern expected from
// SILGen.
for (auto *O : BoxArg->getUses()) {
if (isa<StrongReleaseInst>(O->getUser()) ||
isa<DestroyValueInst>(O->getUser()))
continue;
if (auto Projection = dyn_cast<ProjectBoxInst>(O->getUser())) {
Projections.push_back(Projection);
continue;
}
return false;
}
// Only allow loads of projections, either directly or via
// struct_element_addr instructions.
//
// TODO: This seems overly limited. Why not projections of tuples and other
// stuff? Also, why not recursive struct elements? This should be a helper
// function that mirrors isNonEscapingUse.
auto isAddrUseMutating = [](SILInstruction *AddrInst) {
if (auto *SEAI = dyn_cast<StructElementAddrInst>(AddrInst)) {
return all_of(SEAI->getUses(),
[](Operand *Op) -> bool {
return isNonMutatingLoad(Op->getUser());
});
}
return isNonMutatingLoad(AddrInst) || isa<DebugValueAddrInst>(AddrInst)
|| isa<MarkFunctionEscapeInst>(AddrInst)
|| isa<EndAccessInst>(AddrInst);
};
for (auto *Projection : Projections) {
for (auto *UseOper : Projection->getUses()) {
if (auto *Access = dyn_cast<BeginAccessInst>(UseOper->getUser())) {
for (auto *AccessUseOper : Access->getUses()) {
if (!isAddrUseMutating(AccessUseOper->getUser()))
return false;
}
continue;
}
if (!isAddrUseMutating(UseOper->getUser()))
return false;
}
}
return true;
}
namespace {
class NonEscapingUserVisitor
: public SILInstructionVisitor<NonEscapingUserVisitor, bool> {
llvm::SmallVector<Operand *, 32> Worklist;
llvm::SmallVectorImpl<SILInstruction *> &Mutations;
NullablePtr<Operand> CurrentOp;
public:
NonEscapingUserVisitor(Operand *Op,
llvm::SmallVectorImpl<SILInstruction *> &Mutations)
: Worklist(), Mutations(Mutations), CurrentOp() {
Worklist.push_back(Op);
}
NonEscapingUserVisitor(const NonEscapingUserVisitor &) = delete;
NonEscapingUserVisitor &operator=(const NonEscapingUserVisitor &) = delete;
NonEscapingUserVisitor(NonEscapingUserVisitor &&) = delete;
NonEscapingUserVisitor &operator=(NonEscapingUserVisitor &&) = delete;
bool compute() {
while (!Worklist.empty()) {
CurrentOp = Worklist.pop_back_val();
SILInstruction *User = CurrentOp.get()->getUser();
// Ignore type dependent operands.
if (User->isTypeDependentOperand(*(CurrentOp.get())))
continue;
// Then visit the specific user. This routine returns true if the value
// does not escape. In such a case, continue.
if (visit(User)) {
continue;
}
return false;
}
return true;
}
/// Visit a random value base.
///
/// These are considered to be escapes.
bool visitSILInstruction(SILInstruction *I) {
LLVM_DEBUG(llvm::dbgs() << " FAIL! Have unknown escaping user: " << *I);
return false;
}
#define ALWAYS_NON_ESCAPING_INST(INST) \
bool visit##INST##Inst(INST##Inst *V) { return true; }
// Marking the boxed value as escaping is OK. It's just a DI annotation.
ALWAYS_NON_ESCAPING_INST(MarkFunctionEscape)
// These remaining instructions are ok and don't count as mutations.
ALWAYS_NON_ESCAPING_INST(StrongRetain)
ALWAYS_NON_ESCAPING_INST(Load)
ALWAYS_NON_ESCAPING_INST(StrongRelease)
ALWAYS_NON_ESCAPING_INST(DestroyValue)
#undef ALWAYS_NON_ESCAPING_INST
bool visitDeallocBoxInst(DeallocBoxInst *DBI) {
Mutations.push_back(DBI);
return true;
}
bool visitEndAccessInst(EndAccessInst *EAI) { return true; }
bool visitApplyInst(ApplyInst *AI) {
auto argIndex = CurrentOp.get()->getOperandNumber() - 1;
SILFunctionConventions substConv(AI->getSubstCalleeType(), AI->getModule());
auto convention = substConv.getSILArgumentConvention(argIndex);
if (!convention.isIndirectConvention()) {
LLVM_DEBUG(llvm::dbgs() << " FAIL! Found non indirect apply user: "
<< *AI);
return false;
}
Mutations.push_back(AI);
return true;
}
/// Add the Operands of a transitive use instruction to the worklist.
void addUserOperandsToWorklist(SingleValueInstruction *I) {
for (auto *User : I->getUses()) {
Worklist.push_back(User);
}
}
/// This is separate from the normal copy value handling since we are matching
/// the old behavior of non-top-level uses not being able to have partial
/// apply and project box uses.
struct detail {
enum IsMutating_t {
IsNotMutating = 0,
IsMutating = 1,
};
};
#define RECURSIVE_INST_VISITOR(MUTATING, INST) \
bool visit##INST##Inst(INST##Inst *I) { \
if (bool(detail::MUTATING)) { \
Mutations.push_back(I); \
} \
addUserOperandsToWorklist(I); \
return true; \
}
// *NOTE* It is important that we do not have copy_value here. The reason why
// is that we only want to handle copy_value directly of the alloc_box without
// going through any other instructions. This protects our optimization later
// on.
//
// Additionally, copy_value is not a valid use of any of the instructions that
// we allow through.
//
// TODO: Can we ever hit copy_values here? If we do, we may be missing
// opportunities.
RECURSIVE_INST_VISITOR(IsNotMutating, StructElementAddr)
RECURSIVE_INST_VISITOR(IsNotMutating, TupleElementAddr)
RECURSIVE_INST_VISITOR(IsNotMutating, InitEnumDataAddr)
RECURSIVE_INST_VISITOR(IsNotMutating, OpenExistentialAddr)
// begin_access may signify a modification, but is considered nonmutating
// because we will peek though it's uses to find the actual mutation.
RECURSIVE_INST_VISITOR(IsNotMutating, BeginAccess)
RECURSIVE_INST_VISITOR(IsMutating , UncheckedTakeEnumDataAddr)
#undef RECURSIVE_INST_VISITOR
bool visitCopyAddrInst(CopyAddrInst *CAI) {
if (CurrentOp.get()->getOperandNumber() == 1 || CAI->isTakeOfSrc())
Mutations.push_back(CAI);
return true;
}
bool visitStoreInst(StoreInst *SI) {
if (CurrentOp.get()->getOperandNumber() != 1) {
LLVM_DEBUG(llvm::dbgs() << " FAIL! Found store of pointer: " << *SI);
return false;
}
Mutations.push_back(SI);
return true;
}
bool visitAssignInst(AssignInst *AI) {
if (CurrentOp.get()->getOperandNumber() != 1) {
LLVM_DEBUG(llvm::dbgs() << " FAIL! Found store of pointer: " << *AI);
return false;
}
Mutations.push_back(AI);
return true;
}
};
} // end anonymous namespace
namespace {
struct EscapeMutationScanningState {
/// The list of mutations that we found while checking for escapes.
llvm::SmallVector<SILInstruction *, 8> Mutations;
/// A flag that we use to ensure that we only ever see 1 project_box on an
/// alloc_box.
bool SawProjectBoxInst;
/// The global partial_apply -> index map.
llvm::DenseMap<PartialApplyInst *, unsigned> &IM;
};
} // end anonymous namespace
/// Given a use of an alloc_box instruction, return true if the use
/// definitely does not allow the box to escape; also, if the use is an
/// instruction which possibly mutates the contents of the box, then add it to
/// the Mutations vector.
static bool isNonEscapingUse(Operand *InitialOp,
EscapeMutationScanningState &State) {
return NonEscapingUserVisitor(InitialOp, State.Mutations).compute();
}
bool isPartialApplyNonEscapingUser(Operand *CurrentOp, PartialApplyInst *PAI,
EscapeMutationScanningState &State) {
LLVM_DEBUG(llvm::dbgs() << " Found partial: " << *PAI);
unsigned OpNo = CurrentOp->getOperandNumber();
assert(OpNo != 0 && "Alloc box used as callee of partial apply?");
// If we've already seen this partial apply, then it means the same alloc
// box is being captured twice by the same closure, which is odd and
// unexpected: bail instead of trying to handle this case.
if (State.IM.count(PAI)) {
LLVM_DEBUG(llvm::dbgs() << " FAIL! Already seen.\n");
return false;
}
SILModule &M = PAI->getModule();
auto closureType = PAI->getType().castTo<SILFunctionType>();
SILFunctionConventions closureConv(closureType, M);
// Calculate the index into the closure's argument list of the captured
// box pointer (the captured address is always the immediately following
// index so is not stored separately);
unsigned Index = OpNo - 1 + closureConv.getNumSILArguments();
auto *Fn = PAI->getReferencedFunction();
if (!Fn || !Fn->isDefinition()) {
LLVM_DEBUG(llvm::dbgs() << " FAIL! Not a direct function definition "
"reference.\n");
return false;
}
SILArgument *BoxArg = getBoxFromIndex(Fn, Index);
// For now, return false is the address argument is an address-only type,
// since we currently handle loadable types only.
// TODO: handle address-only types
auto BoxTy = BoxArg->getType().castTo<SILBoxType>();
assert(BoxTy->getLayout()->getFields().size() == 1 &&
"promoting compound box not implemented yet");
if (BoxTy->getFieldType(M, 0).isAddressOnly(M)) {
LLVM_DEBUG(llvm::dbgs() << " FAIL! Box is an address only "
"argument!\n");
return false;
}
// Verify that this closure is known not to mutate the captured value; if
// it does, then conservatively refuse to promote any captures of this
// value.
if (!isNonMutatingCapture(BoxArg)) {
LLVM_DEBUG(llvm::dbgs() << " FAIL: Have a mutating capture!\n");
return false;
}
// Record the index and continue.
LLVM_DEBUG(llvm::dbgs()
<< " Partial apply does not escape, may be optimizable!\n");
LLVM_DEBUG(llvm::dbgs() << " Index: " << Index << "\n");
State.IM.insert(std::make_pair(PAI, Index));
return true;
}
static bool isProjectBoxNonEscapingUse(ProjectBoxInst *PBI,
EscapeMutationScanningState &State) {
LLVM_DEBUG(llvm::dbgs() << " Found project box: " << *PBI);
for (Operand *AddrOp : PBI->getUses()) {
if (!isNonEscapingUse(AddrOp, State)) {
LLVM_DEBUG(llvm::dbgs() << " FAIL! Has escaping user of addr:"
<< *AddrOp->getUser());
return false;
}
}
return true;
}
static bool scanUsesForEscapesAndMutations(Operand *Op,
EscapeMutationScanningState &State) {
SILInstruction *User = Op->getUser();
if (auto *PAI = dyn_cast<PartialApplyInst>(User)) {
return isPartialApplyNonEscapingUser(Op, PAI, State);
}
// A mark_dependence user on a partial_apply is safe.
if (auto *MD = dyn_cast<MarkDependenceInst>(User)) {
if (MD->getBase() == Op->get()) {
auto parent = MD->getValue();
while ((MD = dyn_cast<MarkDependenceInst>(parent))) {
parent = MD->getValue();
}
return isa<PartialApplyInst>(parent);
}
}
if (auto *PBI = dyn_cast<ProjectBoxInst>(User)) {
// It is assumed in later code that we will only have 1 project_box. This
// can be seen since there is no code for reasoning about multiple
// boxes. Just put in the restriction so we are consistent.
if (State.SawProjectBoxInst)
return false;
State.SawProjectBoxInst = true;
return isProjectBoxNonEscapingUse(PBI, State);
}
// Given a top level copy value use or mark_uninitialized, check all of its
// user operands as if they were apart of the use list of the base operand.
//
// This is a separate code path from the non escaping user visitor check since
// we want to be more conservative around non-top level copies (i.e. a copy
// derived from a projection like instruction). In fact such a thing may not
// even make any sense!
if (isa<CopyValueInst>(User) || isa<MarkUninitializedInst>(User)) {
return all_of(cast<SingleValueInstruction>(User)->getUses(),
[&State](Operand *UserOp) -> bool {
return scanUsesForEscapesAndMutations(UserOp, State);
});
}
// Verify that this use does not otherwise allow the alloc_box to
// escape.
return isNonEscapingUse(Op, State);
}
/// Examine an alloc_box instruction, returning true if at least one
/// capture of the boxed variable is promotable. If so, then the pair of the
/// partial_apply instruction and the index of the box argument in the closure's
/// argument list is added to IM.
static bool
examineAllocBoxInst(AllocBoxInst *ABI, ReachabilityInfo &RI,
llvm::DenseMap<PartialApplyInst *, unsigned> &IM) {
LLVM_DEBUG(llvm::dbgs() << "Visiting alloc box: " << *ABI);
EscapeMutationScanningState State{{}, false, IM};
// Scan the box for interesting uses.
if (any_of(ABI->getUses(), [&State](Operand *Op) {
return !scanUsesForEscapesAndMutations(Op, State);
})) {
LLVM_DEBUG(llvm::dbgs()
<< "Found an escaping use! Can not optimize this alloc box?!\n");
return false;
}
LLVM_DEBUG(llvm::dbgs() << "We can optimize this alloc box!\n");
// Helper lambda function to determine if instruction b is strictly after
// instruction a, assuming both are in the same basic block.
auto isAfter = [](SILInstruction *a, SILInstruction *b) {
auto fIter = b->getParent()->begin();
auto bIter = b->getIterator();
auto aIter = a->getIterator();
while (bIter != fIter) {
--bIter;
if (aIter == bIter)
return true;
}
return false;
};
LLVM_DEBUG(llvm::dbgs()
<< "Checking for any mutations that invalidate captures...\n");
// Loop over all mutations to possibly invalidate captures.
for (auto *I : State.Mutations) {
auto Iter = IM.begin();
while (Iter != IM.end()) {
auto *PAI = Iter->first;
// The mutation invalidates a capture if it occurs in a block reachable
// from the block the partial_apply is in, or if it is in the same
// block is after the partial_apply.
if (RI.isReachable(PAI->getParent(), I->getParent()) ||
(PAI->getParent() == I->getParent() && isAfter(PAI, I))) {
LLVM_DEBUG(llvm::dbgs() << " Invalidating: " << *PAI);
LLVM_DEBUG(llvm::dbgs() << " Because of user: " << *I);
auto Prev = Iter++;
IM.erase(Prev);
continue;
}
++Iter;
}
// If there are no valid captures left, then stop.
if (IM.empty()) {
LLVM_DEBUG(llvm::dbgs() << " Ran out of valid captures... bailing!\n");
return false;
}
}
LLVM_DEBUG(llvm::dbgs() << " We can optimize this box!\n");
return true;
}
static SILFunction *
constructClonedFunction(SILOptFunctionBuilder &FuncBuilder,
PartialApplyInst *PAI, FunctionRefInst *FRI,
IndicesSet &PromotableIndices) {
SILFunction *F = PAI->getFunction();
// Create the Cloned Name for the function.
SILFunction *Orig = FRI->getReferencedFunction();
IsSerialized_t Serialized = IsNotSerialized;
if (F->isSerialized() && Orig->isSerialized())
Serialized = IsSerializable;
auto ClonedName = getSpecializedName(Orig, Serialized, PromotableIndices);
// If we already have such a cloned function in the module then just use it.
if (auto *PrevF = F->getModule().lookUpFunction(ClonedName)) {
assert(PrevF->isSerialized() == Serialized);
return PrevF;
}
// Otherwise, create a new clone.
ClosureCloner cloner(FuncBuilder, Orig, Serialized, ClonedName, PromotableIndices);
cloner.populateCloned();
return cloner.getCloned();
}
/// For an alloc_box or iterated copy_value alloc_box, get or create the
/// project_box for the copy or original alloc_box.
///
/// There are two possible case here:
///
/// 1. It could be an alloc box.
/// 2. It could be an iterated copy_value from an alloc_box.
///
/// Some important constraints from our initial safety condition checks:
///
/// 1. We only see a project_box paired with an alloc_box. e.x.:
///
/// (project_box (alloc_box)).
///
/// 2. We only see a mark_uninitialized when paired with an (alloc_box,
/// project_box). e.x.:
///
/// (mark_uninitialized (project_box (alloc_box)))
///
/// The asserts are to make sure that if the initial safety condition check
/// is changed, this code is changed as well.
static SILValue getOrCreateProjectBoxHelper(SILValue PartialOperand) {
// If we have a copy_value, just create a project_box on the copy and return.
if (auto *CVI = dyn_cast<CopyValueInst>(PartialOperand)) {
SILBuilderWithScope B(std::next(CVI->getIterator()));
return B.createProjectBox(CVI->getLoc(), CVI, 0);
}
// Otherwise, handle the alloc_box case. If we have a mark_uninitialized on
// the box, we create the project value through that.
SingleValueInstruction *Box = cast<AllocBoxInst>(PartialOperand);
if (auto *Op = Box->getSingleUse()) {
if (auto *MUI = dyn_cast<MarkUninitializedInst>(Op->getUser())) {
Box = MUI;
}
}
// Just return a project_box.
SILBuilderWithScope B(std::next(Box->getIterator()));
return B.createProjectBox(Box->getLoc(), Box, 0);
}
/// Change the base in mark_dependence.
static void
mapMarkDependenceArguments(SingleValueInstruction *root,
llvm::DenseMap<SILValue, SILValue> &map,
SmallVectorImpl<SILInstruction *> &Delete) {
SmallVector<Operand *, 16> Uses(root->getUses());
for (auto *Use : Uses) {
if (auto *MD = dyn_cast<MarkDependenceInst>(Use->getUser())) {
mapMarkDependenceArguments(MD, map, Delete);
auto iter = map.find(MD->getBase());
if (iter != map.end()) {
MD->setBase(iter->second);
}
// Remove mark_dependence on trivial values.
if (MD->getBase()->getType().isTrivial(MD->getModule())) {
MD->replaceAllUsesWith(MD->getValue());
Delete.push_back(MD);
}
}
}
}
/// Given a partial_apply instruction and a set of promotable indices,
/// clone the closure with the promoted captures and replace the partial_apply
/// with a partial_apply of the new closure, fixing up reference counting as
/// necessary. Also, if the closure is cloned, the cloned function is added to
/// the worklist.
static SILFunction *
processPartialApplyInst(SILOptFunctionBuilder &FuncBuilder,
PartialApplyInst *PAI, IndicesSet &PromotableIndices,
SmallVectorImpl<SILFunction*> &Worklist) {
SILModule &M = PAI->getModule();
auto *FRI = dyn_cast<FunctionRefInst>(PAI->getCallee());
// Clone the closure with the given promoted captures.
SILFunction *ClonedFn = constructClonedFunction(FuncBuilder, PAI, FRI, PromotableIndices);
Worklist.push_back(ClonedFn);
// Initialize a SILBuilder and create a function_ref referencing the cloned
// closure.
SILBuilderWithScope B(PAI);
B.addOpenedArchetypeOperands(PAI);
SILValue FnVal = B.createFunctionRef(PAI->getLoc(), ClonedFn);
// Populate the argument list for a new partial_apply instruction, taking into
// consideration any captures.
auto CalleeFunctionTy = PAI->getCallee()->getType().castTo<SILFunctionType>();
auto SubstCalleeFunctionTy = CalleeFunctionTy;
if (PAI->hasSubstitutions())
SubstCalleeFunctionTy =
CalleeFunctionTy->substGenericArgs(M, PAI->getSubstitutionMap());
SILFunctionConventions calleeConv(SubstCalleeFunctionTy, M);
auto CalleePInfo = SubstCalleeFunctionTy->getParameters();
SILFunctionConventions paConv(PAI->getType().castTo<SILFunctionType>(), M);
unsigned FirstIndex = paConv.getNumSILArguments();
unsigned OpNo = 1;
unsigned OpCount = PAI->getNumOperands() - PAI->getNumTypeDependentOperands();
SmallVector<SILValue, 16> Args;
auto NumIndirectResults = calleeConv.getNumIndirectSILResults();
llvm::DenseMap<SILValue, SILValue> capturedMap;
llvm::SmallSet<SILValue, 16> newCaptures;
for (; OpNo != OpCount; ++OpNo) {
unsigned Index = OpNo - 1 + FirstIndex;
if (!PromotableIndices.count(Index)) {
Args.push_back(PAI->getOperand(OpNo));
continue;
}
// First the grab the box and projected_box for the box value.
//
// *NOTE* Box may be a copy_value.
SILValue Box = PAI->getOperand(OpNo);
SILValue Addr = getOrCreateProjectBoxHelper(Box);
auto &typeLowering = M.getTypeLowering(Addr->getType());
auto newCaptured =
typeLowering.emitLoadOfCopy(B, PAI->getLoc(), Addr, IsNotTake);
Args.push_back(newCaptured);
capturedMap[Box] = newCaptured;
newCaptures.insert(newCaptured);
// A partial_apply [stack] does not own the captured argument but we must
// destroy the projected object. We will do so after having created the new
// partial_apply below.
if (PAI->isOnStack())
continue;
// Cleanup the captured argument.
//
// *NOTE* If we initially had a box, then this is on the actual
// alloc_box. Otherwise, it is on the specific iterated copy_value that we
// started with.
SILParameterInfo CPInfo = CalleePInfo[Index - NumIndirectResults];
assert(calleeConv.getSILType(CPInfo) == Box->getType() &&
"SILType of parameter info does not match type of parameter");
releasePartialApplyCapturedArg(B, PAI->getLoc(), Box, CPInfo);
++NumCapturesPromoted;
}
// Create a new partial apply with the new arguments.
auto *NewPAI = B.createPartialApply(
PAI->getLoc(), FnVal, PAI->getSubstitutionMap(), Args,
PAI->getType().getAs<SILFunctionType>()->getCalleeConvention(),
PAI->isOnStack());
PAI->replaceAllUsesWith(NewPAI);
PAI->eraseFromParent();
if (FRI->use_empty()) {
FRI->eraseFromParent();
// TODO: If this is the last use of the closure, and if it has internal
// linkage, we should remove it from the SILModule now.
}
if (NewPAI->isOnStack()) {
// Insert destroy's of new captured arguments.
for (auto *Use : NewPAI->getUses()) {
if (auto *DS = dyn_cast<DeallocStackInst>(Use->getUser())) {
B.setInsertionPoint(std::next(SILBasicBlock::iterator(DS)));
insertDestroyOfCapturedArguments(NewPAI, B, [&](SILValue arg) -> bool {
return newCaptures.count(arg);
});
}
}
// Map the mark dependence arguments.
SmallVector<SILInstruction *, 16> Delete;
mapMarkDependenceArguments(NewPAI, capturedMap, Delete);
for (auto *inst : Delete)
inst->eraseFromParent();
}
return ClonedFn;
}
static void
constructMapFromPartialApplyToPromotableIndices(SILFunction *F,
PartialApplyIndicesMap &Map) {
ReachabilityInfo RS(F);
// This is a map from each partial apply to a single index which is a
// promotable box variable for the alloc_box currently being considered.
llvm::DenseMap<PartialApplyInst*, unsigned> IndexMap;
// Consider all alloc_box instructions in the function.
for (auto &BB : *F) {
for (auto &I : BB) {
if (auto *ABI = dyn_cast<AllocBoxInst>(&I)) {
IndexMap.clear();
if (examineAllocBoxInst(ABI, RS, IndexMap)) {
// If we are able to promote at least one capture of the alloc_box,
// then add the promotable index to the main map.
for (auto &IndexPair : IndexMap)
Map[IndexPair.first].insert(IndexPair.second);
}
LLVM_DEBUG(llvm::dbgs() << "\n");
}
}
}
}
namespace {
class CapturePromotionPass : public SILModuleTransform {
/// The entry point to the transformation.
void run() override {
SmallVector<SILFunction*, 128> Worklist;
for (auto &F : *getModule()) {
if (F.wasDeserializedCanonical())
continue;
processFunction(&F, Worklist);
}
while (!Worklist.empty()) {
processFunction(Worklist.pop_back_val(), Worklist);
}
}
void processFunction(SILFunction *F, SmallVectorImpl<SILFunction*> &Worklist);
};
} // end anonymous namespace
void CapturePromotionPass::processFunction(SILFunction *F,
SmallVectorImpl<SILFunction*> &Worklist) {
LLVM_DEBUG(llvm::dbgs() << "******** Performing Capture Promotion on: "
<< F->getName() << "********\n");
// This is a map from each partial apply to a set of indices of promotable
// box variables.
PartialApplyIndicesMap IndicesMap;
constructMapFromPartialApplyToPromotableIndices(F, IndicesMap);
// Do the actual promotions; all promotions on a single partial_apply are
// handled together.
SILOptFunctionBuilder FuncBuilder(*this);
for (auto &IndicesPair : IndicesMap) {
PartialApplyInst *PAI = IndicesPair.first;
SILFunction *ClonedFn = processPartialApplyInst(FuncBuilder,
PAI, IndicesPair.second,
Worklist);
(void)ClonedFn;
}
invalidateAnalysis(F, SILAnalysis::InvalidationKind::Everything);
}
SILTransform *swift::createCapturePromotion() {
return new CapturePromotionPass();
}
| {
"content_hash": "a7fe6b8f7d707e42674b831127fb85b1",
"timestamp": "",
"source": "github",
"line_count": 1362,
"max_line_length": 92,
"avg_line_length": 36.994126284875186,
"alnum_prop": 0.6691541301155083,
"repo_name": "amraboelela/swift",
"id": "48a7ff528a34afa935de7aec1fad82b277dac2ff",
"size": "52698",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/SILOptimizer/IPO/CapturePromotion.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "34"
},
{
"name": "C",
"bytes": "215281"
},
{
"name": "C++",
"bytes": "31712568"
},
{
"name": "CMake",
"bytes": "485566"
},
{
"name": "D",
"bytes": "1107"
},
{
"name": "DTrace",
"bytes": "2438"
},
{
"name": "Emacs Lisp",
"bytes": "57215"
},
{
"name": "LLVM",
"bytes": "71817"
},
{
"name": "Makefile",
"bytes": "1841"
},
{
"name": "Objective-C",
"bytes": "406345"
},
{
"name": "Objective-C++",
"bytes": "253129"
},
{
"name": "Perl",
"bytes": "2211"
},
{
"name": "Python",
"bytes": "1416364"
},
{
"name": "Ruby",
"bytes": "2091"
},
{
"name": "Shell",
"bytes": "223303"
},
{
"name": "Swift",
"bytes": "26299789"
},
{
"name": "Vim script",
"bytes": "16303"
},
{
"name": "sed",
"bytes": "1050"
}
],
"symlink_target": ""
} |
Use github’s interface to make a fork of the repo, then add that repo as an upstream remote:
```
git remote add upstream https://github.com/reactorcore/<NAME_OF_REPO>.git
```
### Cut a namespaced feature branch from master
Your branch should follow this naming convention:
- bug/...
- feat/...
- test/...
- doc/...
- refactor/...
These commands will help you do this:
``` bash
# Creates your branch and brings you there
git checkout -b `your-branch-name`
```
### Make commits to your feature branch.
Prefix each commit like so
- (feat) Added a new feature
- (fix) Fixed inconsistent tests [Fixes #0]
- (refactor) ...
- (cleanup) ...
- (test) ...
- (doc) ...
Make changes and commits on your branch, and make sure that you
only make changes that are relevant to this branch. If you find
yourself making unrelated changes, make a new branch for those
changes.
### Rebase upstream changes into your branch
Once you are done making changes, you can begin the process of getting
your code merged into the main repo.
First switch to your master branch and grab the latest updates from upstream
```bash
git checkout master
git pull --rebase upstream master
```
Then go back to your branch and rebase those changes to your branch:
```bash
git checkout `your-branch-name`
git rebase master
```
If a conflict arises between your new code and what exists on upstream,
git will yell at you to fix the conflicts. To get a better picture of what
conflicts you need to fix, type:
```bash
git status
```
You should see a picture something like this:
<img width="689" alt="rebase_conflict_ex" src="https://cloud.githubusercontent.com/assets/19274618/22439788/d9a80a0a-e6e5-11e6-822d-a2d1203f00e4.png">
In this example, it's saying there's a conflict in the package.json file. If you navigate to that file in your editor (sublime or atom), you'll see something like this:
<img width="716" alt="rebase_conflict_ex2" src="https://cloud.githubusercontent.com/assets/19274618/22439795/df2d93e6-e6e5-11e6-8ecc-3cb5c22d0808.png">
In this particular example, Maurice had added the dependencies mysql and sequelize while I had added request. To resolve this issue, simply delete the text that git inserted (the red highlighted text), and format the package.json to include all 3 (mysql, sequelize, and request):
<img width="630" alt="rebase_conflict_ex3" src="https://cloud.githubusercontent.com/assets/19274618/22439797/e2289c62-e6e5-11e6-901e-f5a48c2d626d.png">
Once you are done fixing conflicts for a specific commit, run:
```bash
git rebase --continue
```
This will continue the rebasing process. If all conflicts are resolved,
the rebase should complete. Go back to master and merge your branch with your
master as follows:
```bash
git checkout master
git merge --ff-only `your-branch-name`
```
Finally, push your code to your fork (origin), but with the same
branch name as the branch you've been working on (not to orgin master)
```bash
git push origin master
```
Note: If you run into difficulty pushing to your origin (i.e.
it says your local master has diverged from origin/master), you can force
a push with:
```bash
git push origin master -f
```
### Make a pull request
Make a clear pull request from your fork and branch to the upstream master
branch, detailing exactly what changes you made and what feature this
should add. The clearer your pull request is the faster you can get
your changes incorporated into this repo.
At least one other person MUST give your changes a code review, and once
they are satisfied they will merge your changes into upstream. Alternatively,
they may have some requested changes. You should make more commits to your
branch to fix these, then follow this process again from rebasing onwards.
If all changes are good to go, instead of doing the default merge, select the
drop down arrow next to the button and select the "Rebase and merge" option:
<img width="630" alt="rebase_and_merge" src="https://cloud.githubusercontent.com/assets/19274618/22439832/fc13f054-e6e5-11e6-8a5b-deb179ce2fde.png">
This should give us a nice, clean, linear history :)
Thanks for contributing!
### Guidelines
1. Uphold the current code standard:
- Keep your code [DRY][].
- Apply the [boy scout rule][].
- Follow [STYLE-GUIDE.md](STYLE-GUIDE.md)
1. Run the [tests][] before submitting a pull request.
1. Tests are very, very important. Submit tests if your pull request contains
new, testable behavior.
1. Your pull request is comprised of a single ([squashed][]) commit.
## Checklist:
This is just to help you organize your process
- [ ] Did I cut my work branch off of master (don't cut new branches from existing feature brances)?
- [ ] Did I follow the correct naming convention for my branch?
- [ ] Is my branch focused on a single main change?
- [ ] Do all of my changes directly relate to this change?
- [ ] Did I rebase the upstream master branch after I finished all my
work?
- [ ] Did I write a clear pull request message detailing what changes I made?
- [ ] Did I get a code review?
- [ ] Did I make any requested changes from that code review?
If you follow all of these guidelines and make good changes, you should have
no problem getting your changes merged in.
<!-- Links -->
[style guide]: https://github.com/reactorcore/style-guide
[n-queens]: https://github.com/reactorcore/n-queens
[Underbar]: https://github.com/reactorcore/underbar
[curriculum workflow diagram]: http://i.imgur.com/p0e4tQK.png
[cons of merge]: https://f.cloud.github.com/assets/1577682/1458274/1391ac28-435e-11e3-88b6-69c85029c978.png
[Bookstrap]: https://github.com/reactorcore/bookstrap
[Taser]: https://github.com/reactorcore/bookstrap
[tools workflow diagram]: http://i.imgur.com/kzlrDj7.png
[Git Flow]: http://nvie.com/posts/a-successful-git-branching-model/
[GitHub Flow]: http://scottchacon.com/2011/08/31/github-flow.html
[Squash]: http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html
| {
"content_hash": "693cc799a3ef57224d1cf83befdb9471",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 279,
"avg_line_length": 36.0722891566265,
"alnum_prop": 0.7503340013360054,
"repo_name": "MauriceOkumu/bracegirdles",
"id": "48c7f3bfcbddd528f577ecc00c839d7b68ecd10e",
"size": "6047",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_CONTRIBUTING.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9976"
},
{
"name": "HTML",
"bytes": "4403"
},
{
"name": "JavaScript",
"bytes": "30236"
}
],
"symlink_target": ""
} |
@interface FMXAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| {
"content_hash": "a7e063b0aa4cfd3450ff4a09686a7944",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 63,
"avg_line_length": 23.8,
"alnum_prop": 0.7983193277310925,
"repo_name": "kohkimakimoto/FMDBx",
"id": "66acb6e7fdb3222e2b3dcdbe364150e4ec7b4c0f",
"size": "285",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "FMDBx/FMXAppDelegate.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "76532"
},
{
"name": "Ruby",
"bytes": "1003"
}
],
"symlink_target": ""
} |
- adding line 2 for you
| {
"content_hash": "31be1f15d4ff5645b04c959f2044dec3",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 23,
"avg_line_length": 24,
"alnum_prop": 0.7083333333333334,
"repo_name": "githubteacher/furry-computing-machine",
"id": "1a7e45f6b4332344e70ed512e52384af07657ff3",
"size": "45",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jagmagfile1.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "156"
},
{
"name": "C++",
"bytes": "82"
},
{
"name": "Shell",
"bytes": "29"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.1"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>libfly: Class Members - Related Functions</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="doxygen-awesome.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">libfly
 <span id="projectnumber">6.2.2</span>
</div>
<div id="projectbrief">C++20 utility library for Linux, macOS, and Windows</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.9.1 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search','.html');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(document).ready(function(){initNavTree('functions_rela.html',''); initResizable(); });
/* @license-end */
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="contents">
 <ul>
<li>operator!=
: <a class="el" href="classfly_1_1_json.html#ab17204d4937ef6cf10f4ff1acca019e7">fly::Json</a>
</li>
<li>operator+
: <a class="el" href="classfly_1_1detail_1_1_json_iterator.html#ae31a19467299236ce54c39c80b86eacc">fly::detail::JsonIterator< JsonType ></a>
</li>
<li>operator<
: <a class="el" href="structfly_1_1coders_1_1_huffman_code.html#a326b978d11f6e1a9be3bb950b0c8bc9b">fly::coders::HuffmanCode</a>
, <a class="el" href="classfly_1_1_json.html#a0ffc0151d6d394452fe7354a47c39e84">fly::Json</a>
</li>
<li>operator<<
: <a class="el" href="classfly_1_1logger_1_1detail_1_1_styler_proxy.html#a870fd5f78216e112cc9936726d58a0db">fly::logger::detail::StylerProxy</a>
, <a class="el" href="classfly_1_1logger_1_1_styler.html#a0a6b2719b3f9b08f2e8c6d1c164c26c4">fly::logger::Styler</a>
</li>
<li>operator<=
: <a class="el" href="classfly_1_1_json.html#a1b3d9d7bc97b572ffcc13161101d2ef1">fly::Json</a>
</li>
<li>operator==
: <a class="el" href="structfly_1_1detail_1_1_basic_format_specifier.html#ac100e4ea2da65e8b67a5087888c25ee0">fly::detail::BasicFormatSpecifier< CharType ></a>
, <a class="el" href="classfly_1_1_json.html#a3dbe745b24800b24ff6e0a21ff9f02cc">fly::Json</a>
</li>
<li>operator>
: <a class="el" href="classfly_1_1_json.html#a8caeea567996fc663d4d3b620fa85a5a">fly::Json</a>
</li>
<li>operator>=
: <a class="el" href="classfly_1_1_json.html#a5a09cebbb999668ee7055cd0bfbfaacf">fly::Json</a>
</li>
</ul>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Generated by <a href="https://www.doxygen.org/index.html"><img class="footer" src="doxygen.svg" width="104" height="31" alt="doxygen"/></a> 1.9.1 </li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "7c9b4f0662d89eef2d633ea0e8843376",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 174,
"avg_line_length": 42.344,
"alnum_prop": 0.6965803891932741,
"repo_name": "trflynn89/libfly",
"id": "d8411bf174eec3b5e0b5adef87622bee1cdb4173",
"size": "5293",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "docs/functions_rela.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "1688157"
},
{
"name": "Dockerfile",
"bytes": "1644"
},
{
"name": "Makefile",
"bytes": "9176"
},
{
"name": "Objective-C++",
"bytes": "17014"
},
{
"name": "PowerShell",
"bytes": "1950"
},
{
"name": "Python",
"bytes": "4867"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.