_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q52900
|
train
|
function(code){
this.obj.should.have.property('statusCode');
var status = this.obj.statusCode;
this.assert(
code == status
, function(){ return 'expected response code of ' + code + ' ' + i(statusCodes[code])
+ ', but got ' + status + ' ' + i(statusCodes[status]) }
, function(){ return 'expected to not respond with ' + code + ' ' + i(statusCodes[code]) });
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q52901
|
addToPrefiltersOrTransports
|
train
|
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType, list, placeBefore,
dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ),
i = 0,
length = dataTypes.length;
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
q52902
|
appendDecorations
|
train
|
function appendDecorations(basePos, sourceCode, langHandler, out) {
if (!sourceCode) { return; }
var job = {
sourceCode: sourceCode,
basePos: basePos
};
langHandler(job);
out.push.apply(out, job.decorations);
}
|
javascript
|
{
"resource": ""
}
|
q52903
|
isWindow
|
train
|
function isWindow(obj) {
return obj && obj.document && obj.location && obj.alert && obj.setInterval;
}
|
javascript
|
{
"resource": ""
}
|
q52904
|
shallowCopy
|
train
|
function shallowCopy(src, dst) {
dst = dst || {};
for(var key in src) {
if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
dst[key] = src[key];
}
}
return dst;
}
|
javascript
|
{
"resource": ""
}
|
q52905
|
train
|
function(key, value) {
var array = this[key = hashKey(key)];
if (!array) {
this[key] = [value];
} else {
array.push(value);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52906
|
train
|
function(key) {
var array = this[key = hashKey(key)];
if (array) {
if (array.length == 1) {
delete this[key];
return array[0];
} else {
return array.shift();
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52907
|
train
|
function(key, fn) {
var attrs = this,
$$observers = (attrs.$$observers || (attrs.$$observers = {})),
listeners = ($$observers[key] || ($$observers[key] = []));
listeners.push(fn);
$rootScope.$evalAsync(function() {
if (!listeners.$$inter) {
// no one registered attribute interpolation function, so lets call it manually
fn(attrs[key]);
}
});
return fn;
}
|
javascript
|
{
"resource": ""
}
|
|
q52908
|
$SnifferProvider
|
train
|
function $SnifferProvider() {
this.$get = ['$window', function($window) {
var eventSupport = {},
android = int((/android (\d+)/.exec(lowercase($window.navigator.userAgent)) || [])[1]);
return {
// Android has history.pushState, but it does not update location correctly
// so let's not use the history API at all.
// http://code.google.com/p/android/issues/detail?id=17471
// https://github.com/angular/angular.js/issues/904
history: !!($window.history && $window.history.pushState && !(android < 4)),
hashchange: 'onhashchange' in $window &&
// IE8 compatible mode lies
(!$window.document.documentMode || $window.document.documentMode > 7),
hasEvent: function(event) {
// IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
// it. In particular the event is not fired when backspace or delete key are pressed or
// when cut operation is performed.
if (event == 'input' && msie == 9) return false;
if (isUndefined(eventSupport[event])) {
var divElm = $window.document.createElement('div');
eventSupport[event] = 'on' + event in divElm;
}
return eventSupport[event];
},
// TODO(i): currently there is no way to feature detect CSP without triggering alerts
csp: false
};
}];
}
|
javascript
|
{
"resource": ""
}
|
q52909
|
headersGetter
|
train
|
function headersGetter(headers) {
var headersObj = isObject(headers) ? headers : undefined;
return function(name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
};
}
|
javascript
|
{
"resource": ""
}
|
q52910
|
toggleValidCss
|
train
|
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
$element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
}
|
javascript
|
{
"resource": ""
}
|
q52911
|
isES5DataProperty
|
train
|
function isES5DataProperty(object, key) {
var result = false;
// make sure this works in older browsers without error
if (Object.getOwnPropertyDescriptor && object.hasOwnProperty(key)) {
var descriptor = Object.getOwnPropertyDescriptor(object, key);
result = ('value' in descriptor) && (typeof descriptor.value !== 'function');
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q52912
|
train
|
function(methods) {
var object = {};
for (var i = 0, len = methods.length; i < len; i++) {
// it's safe to use the same method for all since it doesn't do anything
object[methods[i]] = noop;
}
return object;
}
|
javascript
|
{
"resource": ""
}
|
|
q52913
|
nestedPath
|
train
|
function nestedPath (obj, path, val) {
if (typeof obj !== 'object') {
return obj
}
var keys = path.split('.')
if (keys.length > 1) {
path = keys.shift()
return nestedPath(obj[path], keys.join('.'), val)
}
if (val !== undefined) {
obj[path] = val
}
return obj[path]
}
|
javascript
|
{
"resource": ""
}
|
q52914
|
dataToObjects
|
train
|
function dataToObjects (data) {
if (!data) return null
if (data instanceof Array) {
return data.map(function(doc) {
return doc.toObject()
})
}
return data.toObject()
}
|
javascript
|
{
"resource": ""
}
|
q52915
|
dropDatabase
|
train
|
function dropDatabase (db, fn) {
db.connection.db.executeDbCommand({
dropDatabase: 1
}, function(err, result) {
db.disconnect()
fn && fn(err, result)
})
}
|
javascript
|
{
"resource": ""
}
|
q52916
|
dropCollections
|
train
|
function dropCollections (db, each, fn) {
if (each && !fn) { fn = each; each = null }
var conn = db.connection
, cols = Object.keys(conn.collections)
cols.forEach(function (name, k) {
console.log('name: ', name, k)
conn.collections[name].drop(function (err) {
if (err == 'ns not found') {
err = null
}
each && each(err, name)
})
})
fn && fn(null)
}
|
javascript
|
{
"resource": ""
}
|
q52917
|
step5a
|
train
|
function step5a(token) {
var m = measure(token);
if((m > 1 && token.substr(-1) == 'e') || (m == 1 && !(categorizeChars(token).substr(-4, 3) == 'CVC' && token.match(/[^wxy].$/))))
return token.replace(/e$/, '');
return token;
}
|
javascript
|
{
"resource": ""
}
|
q52918
|
step5b
|
train
|
function step5b(token) {
if(measure(token) > 1) {
if(endsWithDoublCons(token) && token.substr(-2) == 'll')
return token.replace(/ll$/, 'l');
}
return token;
}
|
javascript
|
{
"resource": ""
}
|
q52919
|
normalizeTokens
|
train
|
function normalizeTokens(relative, tokens) {
var _index = 0;
// Force as an array
if (!_.isArray(tokens)) tokens = [tokens];
return _.map(tokens, function(subtoken) {
if (_.isNull(subtoken)) return null;
if (_.isString(subtoken)) {
subtoken = {
value: subtoken,
index: _index,
offset: subtoken.length
};
}
if (_.isObject(subtoken)) {
subtoken.index = subtoken.index || 0;
_index = _index + subtoken.index + subtoken.offset;
// Transform as an absolute token
subtoken.index = relative.index + subtoken.index;
subtoken.offset = subtoken.offset || subtoken.value.length;
}
return subtoken;
});
}
|
javascript
|
{
"resource": ""
}
|
q52920
|
encrypt
|
train
|
function encrypt (str) {
var cipher = crypto.createCipher(algorithm, key)
, crypted = cipher.update(str, from, to) + cipher.final(to)
return crypted;
}
|
javascript
|
{
"resource": ""
}
|
q52921
|
decrypt
|
train
|
function decrypt (str) {
var decipher = crypto.createDecipher(algorithm, key)
, dec = decipher.update(str, to, from) + decipher.final(from)
return dec;
}
|
javascript
|
{
"resource": ""
}
|
q52922
|
encode
|
train
|
function encode (schema, doc, toEncrypt) {
if (!doc) return false
var method = (toEncrypt) ? encrypt : decrypt
, obj = (doc.toObject) ? doc.toObject() : doc
// Traverse through all schema paths
schema.eachPath(function (name, path) {
var val = nestedPath(doc, name)
// ObjectID paths
if (path.instance === 'ObjectID' && val) {
nestedPath(obj, name, method(val.toString()))
}
if (path.casterConstructor) {
// Array of DBRefs
if (!!~path.casterConstructor.toString().indexOf('ObjectId')) {
nestedPath(obj, name).forEach(function (v, k) {
nestedPath(obj, name)[k] = method(val[k].toString())
})
// Array of embedded schemas
} else if (!!~path.casterConstructor.toString().indexOf('EmbeddedDocument')) {
nestedPath(obj, name).forEach(function (v, k) {
nestedPath(obj, name)[k] = encode(path.schema, val[k], toEncrypt)
})
}
}
})
return obj
}
|
javascript
|
{
"resource": ""
}
|
q52923
|
getDirectionPositionForRange
|
train
|
function getDirectionPositionForRange (value, min, max, orientation) {
return isVertical(orientation) ? (
// as upper value is used to calculate `top`;
Math.round(((max - value[1]) / max - min) * 100)
) : (
Math.round((value[0] / max - min) * 100)
);
}
|
javascript
|
{
"resource": ""
}
|
q52924
|
isInActiveRange
|
train
|
function isInActiveRange (stepValue, value, isRangeType) {
if (isRangeType) {
return stepValue > value[0] && stepValue < value[1];
} else {
return stepValue < value;
}
}
|
javascript
|
{
"resource": ""
}
|
q52925
|
getSteps
|
train
|
function getSteps (props) {
const { step, min, max, value, isRangeType, orientation } = props;
const steps = [];
const totalSteps = ((max - min) / step) + 1;
for (let i = 0; i < totalSteps; i++) {
let position = getPositionInPercentage(i * step, min, max);
if (isVertical(orientation)) position = 100 - position;
const style = { [constants[orientation].direction]: `${position}%` };
const className = classNames('slider-step', {
'slider-step-active': isInActiveRange(i * step, value, isRangeType)
});
steps.push(<span className={className} key={i} style={style} />);
}
return steps;
}
|
javascript
|
{
"resource": ""
}
|
q52926
|
train
|
function (validator) {
EventEmitter.apply(this);
this._validator = validator || Parser.defaultValidator;
this._configuration = new Configuration();
this._tokenizer = new Tokenizer(this._configuration);
this.state = Parser.states.empty;
this.buffer = '';
}
|
javascript
|
{
"resource": ""
}
|
|
q52927
|
reverse
|
train
|
function reverse (data, callback) {
if (Math.random() > 0.9) {
callback('oh noes!')
} else {
callback(null, data.split('').reverse().join(''))
}
}
|
javascript
|
{
"resource": ""
}
|
q52928
|
createDirectory
|
train
|
function createDirectory(options) {
return new Promise(function(resolve, reject) {
mkdirp( options.directory, function (err) {
if(err && err.code !== 'EEXIST') {
reject(err);
} else {
resolve(options);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q52929
|
writeHTMLFile
|
train
|
function writeHTMLFile(options) {
return new Promise(function(resolve, reject) {
var templateFile = path.join(__dirname, '../template/cli.html');
// read our template file
fs.readFile(templateFile, 'utf8', function (err,data) {
if (err) {
reject(err);
}
// insert the generated json data
var result = data.replace('{{ insertJSONHere }}', 'var embeddedJsonData = '+ options.json + ';');
// write file to directory
fs.writeFile(path.join(options.directory, 'index.html'), result, 'utf8', function (err) {
if (err) {
reject(err);
}
resolve(options.directory);
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q52930
|
describe
|
train
|
function describe(metaData) {
if (item.stack) {
describeRouterRoute(item, metaData);
return item;
}
describeRouterRoute(item._router, metaData);
return item;
}
|
javascript
|
{
"resource": ""
}
|
q52931
|
compile
|
train
|
function compile() {
ensureInitialised('compile');
if (state.app.name === 'router') {
state.app = { _router: state.app };
}
if (!state.app._router) {
throw new Error("app._router was null, either your app is not an express app, or you have called compile before adding at least one route");
}
state.document = generate(state);
state.compiled = true;
}
|
javascript
|
{
"resource": ""
}
|
q52932
|
addTag
|
train
|
function addTag(tag, options) {
addToCommon({
schemaKey: schemaIds.tag,
object: tag,
targetObject: state.common.tags,
displayName: 'Tag'
}, options);
}
|
javascript
|
{
"resource": ""
}
|
q52933
|
addBodyParameter
|
train
|
function addBodyParameter(body, options) {
addToCommon({
schemaKey: schemaIds.parameter.body,
in: 'body',
object: body,
targetObject: state.common.parameters.body,
displayName: 'body parameter'
}, options);
}
|
javascript
|
{
"resource": ""
}
|
q52934
|
addResponse
|
train
|
function addResponse(response, options) {
addToCommon({
schemaKey: schemaIds.response,
object: response,
targetObject: state.common.responses,
displayName: 'response'
}, options);
}
|
javascript
|
{
"resource": ""
}
|
q52935
|
addModel
|
train
|
function addModel(model, inputOptions) {
var options = {
schemaKey: schemaIds.schema,
object: model,
targetObject: state.common.models,
displayName: 'Model',
deleteNameFromCommon: true
};
applyDefaults(options, inputOptions);
ensureObjectExists(options);
cloneObject(options);
delete options.object.$schema;
delete options.object.$id;
var definitions = options.object.definitions;
delete options.object.definitions;
applyValidation(options);
ensureHasName(options);
ensureNotAlreadyAdded(options);
setObjectOnTarget(options);
applyNameDeletion(options);
if (!definitions) {
return;
}
Object.keys(definitions).forEach(function (key) {
var definition = _.cloneDeep(definitions[key]);
definition.name = key;
addModel(definition, inputOptions);
});
}
|
javascript
|
{
"resource": ""
}
|
q52936
|
generateCommentFromOptions
|
train
|
function generateCommentFromOptions(options, callback) {
console.info('\t\tGenerating comments for', options.paramName, '...');
async.waterfall([
async.apply(loadSchema, options),
derefSchema,
generateComment,
addGeneratedComment
], function (err) {
if (err) {
return callback(err);
}
console.info('\t\t\tDone.');
return callback(null, options);
});
}
|
javascript
|
{
"resource": ""
}
|
q52937
|
getErrorMessage
|
train
|
function getErrorMessage(errors) {
var fullMessage = '';
errors.forEach(function (err) {
var message = ajv.errorsText([err]);
if (message.indexOf('should NOT have additional properties') < 0) {
fullMessage += message + os.EOL;
}
else {
fullMessage += message + '. Offending property : ' + err.params.additionalProperty + os.EOL;
}
});
return fullMessage;
}
|
javascript
|
{
"resource": ""
}
|
q52938
|
objToRule
|
train
|
function objToRule(obj, clonedRule) {
var rule = clonedRule || postcss.rule();
var skipKeys = ['selector', 'selectors', 'source'];
if (obj.selector)
rule.selector = obj.selector;
else if (obj.selectors)
rule.selectors = obj.selectors;
if (obj.source)
rule.source = obj.source;
for (var k in obj) {
if (obj.hasOwnProperty(k) && !(skipKeys.indexOf(k) + 1)) {
var v = obj[k];
var found = false;
// If clonedRule was passed in, check for an existing property.
if (clonedRule) {
rule.each(function(decl) {
if (decl.prop == k) {
decl.value = v;
found = true;
return false;
}
});
}
// If no clonedRule or there was no existing prop.
if (!clonedRule || !found)
rule.append({ prop: k, value: v });
}
}
return rule;
}
|
javascript
|
{
"resource": ""
}
|
q52939
|
start
|
train
|
function start (inp) {
var res = parseArgumentList(inp.skipWs());
// If there is any leftover, we have input that did not match our grammar,
// so throw a generic syntax error.
if (inp.skipWs().buffer) syntaxError(inp);
return res;
}
|
javascript
|
{
"resource": ""
}
|
q52940
|
parsePattern
|
train
|
function parsePattern (inp) {
return parseWildcard(inp)
|| parseNullLiteral(inp)
|| parseUndefinedLiteral(inp)
|| parseBooleanLiteral(inp)
|| parseNumberLiteral(inp)
|| parseStringLiteral(inp)
|| parseClassPattern(inp)
|| parseExtractor(inp)
|| parseArray(inp)
|| parseObject(inp)
|| parseIdentPattern(inp);
}
|
javascript
|
{
"resource": ""
}
|
q52941
|
parseExtractor
|
train
|
function parseExtractor (inp) {
var match = inp.takeAPeek(EXTRACTOR);
if (match)
return wrapped("(", ")", parsePattern, extractorRes, inp)
|| nodeExtractor(match[1]);
function extractorRes (res) {
return nodeExtractor(match[1], res);
}
}
|
javascript
|
{
"resource": ""
}
|
q52942
|
parseObjectPattern
|
train
|
function parseObjectPattern (inp) {
var res = parseKey(inp);
if (res) {
if (inp.skipWs().takeAPeek(":")) {
var patt = parsePattern(inp.skipWs());
if (patt) return nodeKeyValue(res, patt);
}
return nodeKey(res);
}
}
|
javascript
|
{
"resource": ""
}
|
q52943
|
parseKey
|
train
|
function parseKey (inp) {
var res = parseString(inp);
if (res) return res;
var match = inp.takeAPeek(JS_IDENT);
if (match) return match[0]
}
|
javascript
|
{
"resource": ""
}
|
q52944
|
parseIdentPattern
|
train
|
function parseIdentPattern (inp) {
var match = inp.takeAPeek(IDENT);
if (match) {
if (inp.takeAPeek("@")) {
var patt = parseBinderPattern(inp);
if (patt) return nodeBinder(match[0], patt);
}
return nodeIdentifier(match[0])
}
}
|
javascript
|
{
"resource": ""
}
|
q52945
|
wrapped
|
train
|
function wrapped (del1, del2, pattFn, nodeFn, inp) {
if (inp.takeAPeek(del1)) {
var res = pattFn(inp.skipWs());
if (inp.skipWs().takeAPeek(del2)) return nodeFn(res);
else syntaxError(inp, "Expected " + del2);
}
}
|
javascript
|
{
"resource": ""
}
|
q52946
|
nodeClass
|
train
|
function nodeClass (name, res) {
var patt = name;
if (res) {
patt += res.type === "array"
? "(" + res.pattern.substring(1, res.pattern.length - 1) + ")"
: res.pattern;
}
return node("class", patt, name, res ? [res] : undefined);
}
|
javascript
|
{
"resource": ""
}
|
q52947
|
compileRest
|
train
|
function compileRest (argName, node) {
var source = [];
var retInit = [];
// Count the number of identifiers we will need to stash.
var i = 0, len = countIdentifiers(node);
for (; i < len; i++) retInit.push('[]');
var retName = argName + '_ret';
var loopName = argName + '_loop';
var iName = argName + '_i';
var lenName = argName + '_len';
var retArgsName = argName + '_retargs';
source.push(
'var ' + retName + ' = [' + retInit.join(',') + '];',
'var ' + loopName + ' = function (val) {',
' var ret = [];',
indent(2, compilePattern('val', node.children[0])),
' return ret;',
'};',
'var ' + iName + ' = 0, ' + lenName + ' = ' + argName + '.length, ' + retArgsName + ';',
'for (; ' + iName + ' < ' + lenName + '; ' + iName + '++) {',
' ' + retArgsName + ' = ' + loopName + '(' + argName + '[' + iName + ']);',
' if (!' + retArgsName + ') return false;',
(function () {
var src = [];
for (i = 0; i < len; i++) {
src.push(' ' + retName + '[' + i + '].push(' + retArgsName + '[' + i + ']);');
}
return src.join('\n');
})(),
'}',
'ret = Array.prototype.concat.call(ret, ' + retName + ');'
);
return source.join('\n');
}
|
javascript
|
{
"resource": ""
}
|
q52948
|
hasRest
|
train
|
function hasRest (node) {
for (var i = 0, child; (child = node.children[i]); i++) {
if (child.type === "rest") return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q52949
|
countIdentifiers
|
train
|
function countIdentifiers (node) {
if (!node.children) return 0;
var count = 0, i = 0, len = node.children.length, type;
for (; i < len; i++) {
type = node.children[i].type;
if (type === "identifier" || type === "binder" || type === "key") count += 1;
else count += countIdentifiers(node.children[i]);
}
return count;
}
|
javascript
|
{
"resource": ""
}
|
q52950
|
getOrCompile
|
train
|
function getOrCompile (patternStr) {
var tree, fn;
if (!patterns.hasOwnProperty(patternStr)) {
tree = parse(patternStr);
if (!normalized.hasOwnProperty(tree.pattern)) {
fn = compile(tree);
fn.pattern = tree.pattern;
normalized[tree.pattern] = fn;
}
patterns[patternStr] = normalized[tree.pattern];
}
return patterns[patternStr];
}
|
javascript
|
{
"resource": ""
}
|
q52951
|
pattern
|
train
|
function pattern () {
var targ0 = typeof arguments[0];
var targ1 = typeof arguments[1];
var targ2 = typeof arguments[2];
// Shared vars
var matcherFn, patternObj, patternFn, patternStr, successFn, chain, tree, last;
// pattern(matcherFn, chain)
if (targ0 == "function" && (targ1 == "undefined" || targ1 == "object")) {
matcherFn = arguments[0];
chain = arguments[1];
// Throw an error if the supplied function does not have a match chain.
if (!matcherFn.__matchChain) throw new Error("Not a matcher function");
// Splice the chains together.
if (chain) {
chain = chain.clone();
chain.last().next = matcherFn.__matchChain.clone();
} else {
chain = matcherFn.__matchChain.clone();
}
last = chain.pop();
return matcher(last.patternFn, last.successFn, chain);
}
// pattern(patternObj, chain)
else if (targ0 == "object" && (targ1 == "undefined" || targ1 == "object")) {
patternObj = arguments[0];
chain = arguments[1] ? arguments[1].clone() : null;
for (patternStr in patternObj) {
matcherFn = pattern(patternStr, patternObj[patternStr], chain);
chain = matcherFn.__matchChain;
}
return matcherFn;
}
// pattern(patternFn, successFn, chain)
else if (targ0 == "function" && targ1 == "function") {
chain = arguments[2] ? arguments[2].clone() : null;
return matcher(arguments[0], arguments[1], chain);
}
// pattern(patternStr, successFn, chain)
else {
patternStr = arguments[0];
successFn = arguments[1];
chain = arguments[2] ? arguments[2].clone() : null;
patternFn = getOrCompile(patternStr);
return matcher(patternFn, successFn, chain);
}
}
|
javascript
|
{
"resource": ""
}
|
q52952
|
matcher
|
train
|
function matcher (patternFn, successFn, chain) {
var matcherObj = new Matcher(patternFn, successFn);
// If a chain was provided, add the new matcher to the end of the chain.
if (chain) {
chain.last().next = matcherObj;
} else {
chain = matcherObj;
}
var fn = function () {
// This seems like an odd optimization, but manually copying the
// arguments object over to an array instead of calling `slice` can
// speed up dispatch time 2-3x.
var args = [], i = 0, len = arguments.length;
for (; i < len; i++) args[i] = arguments[i];
return chain.match(args, this);
};
fn.alt = function () {
var args = slice.call(arguments);
args.push(chain);
return pattern.apply(null, args);
};
fn.__matchChain = chain;
return fn;
}
|
javascript
|
{
"resource": ""
}
|
q52953
|
caseOf
|
train
|
function caseOf (/* ...args, matcher */) {
var args = slice.call(arguments, 0, -1);
var matcher = arguments[arguments.length - 1];
var context = this === exports ? null : this;
if (typeof matcher === "function") {
if (!matcher.__matchChain) throw new Error("Not a matcher function");
return matcher.apply(context, args);
}
return pattern(matcher).apply(context, args);
}
|
javascript
|
{
"resource": ""
}
|
q52954
|
extract
|
train
|
function extract (/* pattern, ...args */) {
var args = slice.call(arguments, 1);
var context = this === exports ? null : this;
var patternFn = getOrCompile(arguments[0]);
return patternFn.call(context, args, runtime) || null;
}
|
javascript
|
{
"resource": ""
}
|
q52955
|
hash
|
train
|
function hash() {
var i = 0,
args = arguments,
length = args.length,
obj = {};
for (; i < length; i++) {
obj[args[i++]] = args[i];
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q52956
|
pad
|
train
|
function pad(number, length) {
// Create an array of the remaining length +1 and join it with 0's
return new Array((length || 2) + 1 - String(number).length).join(0) + number;
}
|
javascript
|
{
"resource": ""
}
|
q52957
|
wrap
|
train
|
function wrap(obj, method, func) {
var proceed = obj[method];
obj[method] = function () {
var args = Array.prototype.slice.call(arguments);
args.unshift(proceed);
return func.apply(this, args);
};
}
|
javascript
|
{
"resource": ""
}
|
q52958
|
format
|
train
|
function format(str, ctx) {
var splitter = '{',
isInside = false,
segment,
valueAndFormat,
path,
i,
len,
ret = [],
val,
index;
while ((index = str.indexOf(splitter)) !== -1) {
segment = str.slice(0, index);
if (isInside) { // we're on the closing bracket looking back
valueAndFormat = segment.split(':');
path = valueAndFormat.shift().split('.'); // get first and leave format
len = path.length;
val = ctx;
// Assign deeper paths
for (i = 0; i < len; i++) {
val = val[path[i]];
}
// Format the replacement
if (valueAndFormat.length) {
val = formatSingle(valueAndFormat.join(':'), val);
}
// Push the result and advance the cursor
ret.push(val);
} else {
ret.push(segment);
}
str = str.slice(index + 1); // the rest
isInside = !isInside; // toggle
splitter = isInside ? '}' : '{'; // now look for next matching bracket
}
ret.push(str);
return ret.join('');
}
|
javascript
|
{
"resource": ""
}
|
q52959
|
getMagnitude
|
train
|
function getMagnitude(num) {
return math.pow(10, mathFloor(math.log(num) / math.LN10));
}
|
javascript
|
{
"resource": ""
}
|
q52960
|
destroyObjectProperties
|
train
|
function destroyObjectProperties(obj, except) {
var n;
for (n in obj) {
// If the object is non-null and destroy is defined
if (obj[n] && obj[n] !== except && obj[n].destroy) {
// Invoke the destroy
obj[n].destroy();
}
// Delete the property from the object.
delete obj[n];
}
}
|
javascript
|
{
"resource": ""
}
|
q52961
|
discardElement
|
train
|
function discardElement(element) {
// create a garbage bin element, not part of the DOM
if (!garbageBin) {
garbageBin = createElement(DIV);
}
// move the node and empty bin
if (element) {
garbageBin.appendChild(element);
}
garbageBin.innerHTML = '';
}
|
javascript
|
{
"resource": ""
}
|
q52962
|
error
|
train
|
function error(code, stop) {
var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code;
if (stop) {
throw msg;
} else if (win.console) {
console.log(msg);
}
}
|
javascript
|
{
"resource": ""
}
|
q52963
|
train
|
function (elem, fromD, toD) {
fromD = fromD || '';
var shift = elem.shift,
bezier = fromD.indexOf('C') > -1,
numParams = bezier ? 7 : 3,
endLength,
slice,
i,
start = fromD.split(' '),
end = [].concat(toD), // copy
startBaseLine,
endBaseLine,
sixify = function (arr) { // in splines make move points have six parameters like bezier curves
i = arr.length;
while (i--) {
if (arr[i] === M) {
arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]);
}
}
};
if (bezier) {
sixify(start);
sixify(end);
}
// pull out the base lines before padding
if (elem.isArea) {
startBaseLine = start.splice(start.length - 6, 6);
endBaseLine = end.splice(end.length - 6, 6);
}
// if shifting points, prepend a dummy point to the end path
if (shift <= end.length / numParams && start.length === end.length) {
while (shift--) {
end = [].concat(end).splice(0, numParams).concat(end);
}
}
elem.shift = 0; // reset for following animations
// copy and append last point until the length matches the end length
if (start.length) {
endLength = end.length;
while (start.length < endLength) {
//bezier && sixify(start);
slice = [].concat(start).splice(start.length - numParams, numParams);
if (bezier) { // disable first control point
slice[numParams - 6] = slice[numParams - 2];
slice[numParams - 5] = slice[numParams - 1];
}
start = start.concat(slice);
}
}
if (startBaseLine) { // append the base lines for areas
start = start.concat(startBaseLine);
end = end.concat(endBaseLine);
}
return [start, end];
}
|
javascript
|
{
"resource": ""
}
|
|
q52964
|
train
|
function (el, eventType, handler) {
// workaround for jQuery issue with unbinding custom events:
// http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2
var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent';
if (doc[func] && el && !el[func]) {
el[func] = function () {};
}
$(el).unbind(eventType, handler);
}
|
javascript
|
{
"resource": ""
}
|
|
q52965
|
train
|
function (el, type, eventArguments, defaultFunction) {
var event = $.Event(type),
detachedType = 'detached' + type,
defaultPrevented;
// Remove warnings in Chrome when accessing layerX and layerY. Although Highcharts
// never uses these properties, Chrome includes them in the default click event and
// raises the warning when they are copied over in the extend statement below.
//
// To avoid problems in IE (see #1010) where we cannot delete the properties and avoid
// testing if they are there (warning in chrome) the only option is to test if running IE.
if (!isIE && eventArguments) {
delete eventArguments.layerX;
delete eventArguments.layerY;
}
extend(event, eventArguments);
// Prevent jQuery from triggering the object method that is named the
// same as the event. For example, if the event is 'select', jQuery
// attempts calling el.select and it goes into a loop.
if (el[type]) {
el[detachedType] = el[type];
el[type] = null;
}
// Wrap preventDefault and stopPropagation in try/catch blocks in
// order to prevent JS errors when cancelling events on non-DOM
// objects. #615.
/*jslint unparam: true*/
$.each(['preventDefault', 'stopPropagation'], function (i, fn) {
var base = event[fn];
event[fn] = function () {
try {
base.call(event);
} catch (e) {
if (fn === 'preventDefault') {
defaultPrevented = true;
}
}
};
});
/*jslint unparam: false*/
// trigger it
$(el).trigger(event);
// attach the method
if (el[detachedType]) {
el[type] = el[detachedType];
el[detachedType] = null;
}
if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) {
defaultFunction(event);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52966
|
train
|
function (e) {
var ret = e.originalEvent || e;
// computed by jQuery, needed by IE8
if (ret.pageX === UNDEFINED) { // #1236
ret.pageX = e.pageX;
ret.pageY = e.pageY;
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
|
q52967
|
train
|
function (renderer, nodeName) {
var wrapper = this;
wrapper.element = nodeName === 'span' ?
createElement(nodeName) :
doc.createElementNS(SVG_NS, nodeName);
wrapper.renderer = renderer;
/**
* A collection of attribute setters. These methods, if defined, are called right before a certain
* attribute is set on an element wrapper. Returning false prevents the default attribute
* setter to run. Returning a value causes the default setter to set that value. Used in
* Renderer.label.
*/
wrapper.attrSetters = {};
}
|
javascript
|
{
"resource": ""
}
|
|
q52968
|
train
|
function (params, options, complete) {
var animOptions = pick(options, globalAnimation, true);
stop(this); // stop regardless of animation actually running, or reverting to .attr (#607)
if (animOptions) {
animOptions = merge(animOptions);
if (complete) { // allows using a callback with the global animation without overwriting it
animOptions.complete = complete;
}
animate(this, params, animOptions);
} else {
this.attr(params);
if (complete) {
complete();
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52969
|
train
|
function (className) {
var element = this.element,
currentClassName = attr(element, 'class') || '';
if (currentClassName.indexOf(className) === -1) {
attr(element, 'class', currentClassName + ' ' + className);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q52970
|
train
|
function (styles) {
/*jslint unparam: true*//* allow unused param a in the regexp function below */
var elemWrapper = this,
elem = elemWrapper.element,
textWidth = styles && styles.width && elem.nodeName.toLowerCase() === 'text',
n,
serializedCss = '',
hyphenate = function (a, b) { return '-' + b.toLowerCase(); };
/*jslint unparam: false*/
// convert legacy
if (styles && styles.color) {
styles.fill = styles.color;
}
// Merge the new styles with the old ones
styles = extend(
elemWrapper.styles,
styles
);
// store object
elemWrapper.styles = styles;
// Don't handle line wrap on canvas
if (useCanVG && textWidth) {
delete styles.width;
}
// serialize and set style attribute
if (isIE && !hasSVG) { // legacy IE doesn't support setting style attribute
if (textWidth) {
delete styles.width;
}
css(elemWrapper.element, styles);
} else {
for (n in styles) {
serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';';
}
attr(elem, 'style', serializedCss); // #1881
}
// re-build text
if (textWidth && elemWrapper.added) {
elemWrapper.renderer.buildText(elemWrapper);
}
return elemWrapper;
}
|
javascript
|
{
"resource": ""
}
|
|
q52971
|
train
|
function (styles) {
var wrapper = this,
element = wrapper.element,
textWidth = styles && element.tagName === 'SPAN' && styles.width;
if (textWidth) {
delete styles.width;
wrapper.textWidth = textWidth;
wrapper.updateTransform();
}
wrapper.styles = extend(wrapper.styles, styles);
css(wrapper.element, styles);
return wrapper;
}
|
javascript
|
{
"resource": ""
}
|
|
q52972
|
train
|
function (path) {
var attr = {
fill: NONE
};
if (isArray(path)) {
attr.d = path;
} else if (isObject(path)) { // attributes
extend(attr, path);
}
return this.createElement('path').attr(attr);
}
|
javascript
|
{
"resource": ""
}
|
|
q52973
|
train
|
function (src, x, y, width, height) {
var attribs = {
preserveAspectRatio: NONE
},
elemWrapper;
// optional properties
if (arguments.length > 1) {
extend(attribs, {
x: x,
y: y,
width: width,
height: height
});
}
elemWrapper = this.createElement('image').attr(attribs);
// set the href in the xlink namespace
if (elemWrapper.element.setAttributeNS) {
elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink',
'href', src);
} else {
// could be exporting in IE
// using href throws "not supported" in ie7 and under, requries regex shim to fix later
elemWrapper.element.setAttribute('hc-svg-href', src);
}
return elemWrapper;
}
|
javascript
|
{
"resource": ""
}
|
|
q52974
|
updateTextPadding
|
train
|
function updateTextPadding() {
var styles = wrapper.styles,
textAlign = styles && styles.textAlign,
x = paddingLeft + padding * (1 - alignFactor),
y;
// determin y based on the baseline
y = baseline ? 0 : baselineOffset;
// compensate for alignment
if (defined(width) && (textAlign === 'center' || textAlign === 'right')) {
x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width);
}
// update if anything changed
if (x !== text.x || y !== text.y) {
text.attr({
x: x,
y: y
});
}
// record current values
text.x = x;
text.y = y;
}
|
javascript
|
{
"resource": ""
}
|
q52975
|
boxAttr
|
train
|
function boxAttr(key, value) {
if (box) {
box.attr(key, value);
} else {
deferredAttr[key] = value;
}
}
|
javascript
|
{
"resource": ""
}
|
q52976
|
train
|
function (styles) {
if (styles) {
var textStyles = {};
styles = merge(styles); // create a copy to avoid altering the original object (#537)
each(['fontSize', 'fontWeight', 'fontFamily', 'color', 'lineHeight', 'width', 'textDecoration', 'textShadow'], function (prop) {
if (styles[prop] !== UNDEFINED) {
textStyles[prop] = styles[prop];
delete styles[prop];
}
});
text.css(textStyles);
}
return baseCss.call(wrapper, styles);
}
|
javascript
|
{
"resource": ""
}
|
|
q52977
|
train
|
function () {
return {
width: bBox.width + 2 * padding,
height: bBox.height + 2 * padding,
x: bBox.x - padding,
y: bBox.y - padding
};
}
|
javascript
|
{
"resource": ""
}
|
|
q52978
|
train
|
function (value) {
// convert paths
var i = value.length,
path = [],
clockwise;
while (i--) {
// Multiply by 10 to allow subpixel precision.
// Substracting half a pixel seems to make the coordinates
// align with SVG, but this hasn't been tested thoroughly
if (isNumber(value[i])) {
path[i] = mathRound(value[i] * 10) - 5;
} else if (value[i] === 'Z') { // close the path
path[i] = 'x';
} else {
path[i] = value[i];
// When the start X and end X coordinates of an arc are too close,
// they are rounded to the same value above. In this case, substract 1 from the end X
// position. #760, #1371.
if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) {
clockwise = value[i] === 'wa' ? 1 : -1; // #1642
if (path[i + 5] === path[i + 7]) {
path[i + 7] -= clockwise;
}
// Start and end Y (#1410)
if (path[i + 6] === path[i + 8]) {
path[i + 8] -= clockwise;
}
}
}
}
// Loop up again to handle path shortcuts (#2132)
/*while (i++ < path.length) {
if (path[i] === 'H') { // horizontal line to
path[i] = 'L';
path.splice(i + 2, 0, path[i - 1]);
} else if (path[i] === 'V') { // vertical line to
path[i] = 'L';
path.splice(i + 1, 0, path[i - 2]);
}
}*/
return path.join(' ') || 'x';
}
|
javascript
|
{
"resource": ""
}
|
|
q52979
|
train
|
function (path, length) {
var len;
path = path.split(/[ ,]/);
len = path.length;
if (len === 9 || len === 11) {
path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length;
}
return path.join(' ');
}
|
javascript
|
{
"resource": ""
}
|
|
q52980
|
train
|
function (path) {
var attr = {
// subpixel precision down to 0.1 (width and height = 1px)
coordsize: '10 10'
};
if (isArray(path)) {
attr.d = path;
} else if (isObject(path)) { // attributes
extend(attr, path);
}
// create the shape
return this.createElement('shape').attr(attr);
}
|
javascript
|
{
"resource": ""
}
|
|
q52981
|
drawDeferred
|
train
|
function drawDeferred() {
var callLength = deferredRenderCalls.length,
callIndex;
// Draw all pending render calls
for (callIndex = 0; callIndex < callLength; callIndex++) {
deferredRenderCalls[callIndex]();
}
// Clear the list
deferredRenderCalls = [];
}
|
javascript
|
{
"resource": ""
}
|
q52982
|
train
|
function () {
var label = this.label,
axis = this.axis;
return label ?
((this.labelBBox = label.getBBox()))[axis.horiz ? 'height' : 'width'] :
0;
}
|
javascript
|
{
"resource": ""
}
|
|
q52983
|
train
|
function (horiz, pos, tickmarkOffset, old) {
var axis = this.axis,
chart = axis.chart,
cHeight = (old && chart.oldChartHeight) || chart.chartHeight;
return {
x: horiz ?
axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB :
axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0),
y: horiz ?
cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) :
cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB
};
}
|
javascript
|
{
"resource": ""
}
|
|
q52984
|
train
|
function (x, y, tickLength, tickWidth, horiz, renderer) {
return renderer.crispLine([
M,
x,
y,
L,
x + (horiz ? 0 : -tickLength),
y + (horiz ? tickLength : 0)
], tickWidth);
}
|
javascript
|
{
"resource": ""
}
|
|
q52985
|
train
|
function (newOptions, redraw) {
var chart = this.chart;
newOptions = chart.options[this.xOrY + 'Axis'][this.options.index] = merge(this.userOptions, newOptions);
this.destroy(true);
this._addedPlotLB = this.userMin = this.userMax = UNDEFINED; // #1611, #2306
this.init(chart, extend(newOptions, { events: UNDEFINED }));
chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52986
|
train
|
function (redraw) {
var chart = this.chart,
key = this.xOrY + 'Axis'; // xAxis or yAxis
// Remove associated series
each(this.series, function (series) {
series.remove(false);
});
// Remove the axis
erase(chart.axes, this);
erase(chart[key], this);
chart.options[key].splice(this.options.index, 1);
each(chart[key], function (axis, i) { // Re-index, #1706
axis.options.index = i;
});
this.destroy();
chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52987
|
train
|
function (value, paneCoordinates) {
return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos);
}
|
javascript
|
{
"resource": ""
}
|
|
q52988
|
train
|
function (from, to) {
var toPath = this.getPlotLinePath(to),
path = this.getPlotLinePath(from);
if (path && toPath) {
path.push(
toPath[4],
toPath[5],
toPath[1],
toPath[2]
);
} else { // outside the axis area
path = null;
}
return path;
}
|
javascript
|
{
"resource": ""
}
|
|
q52989
|
train
|
function (interval, min, max, minor) {
var axis = this,
options = axis.options,
axisLength = axis.len,
// Since we use this method for both major and minor ticks,
// use a local variable and return the result
positions = [];
// Reset
if (!minor) {
axis._minorAutoInterval = null;
}
// First case: All ticks fall on whole logarithms: 1, 10, 100 etc.
if (interval >= 0.5) {
interval = mathRound(interval);
positions = axis.getLinearTickPositions(interval, min, max);
// Second case: We need intermediary ticks. For example
// 1, 2, 4, 6, 8, 10, 20, 40 etc.
} else if (interval >= 0.08) {
var roundedMin = mathFloor(min),
intermediate,
i,
j,
len,
pos,
lastPos,
break2;
if (interval > 0.3) {
intermediate = [1, 2, 4];
} else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc
intermediate = [1, 2, 4, 6, 8];
} else { // 0.1 equals ten minor ticks per 1, 10, 100 etc
intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9];
}
for (i = roundedMin; i < max + 1 && !break2; i++) {
len = intermediate.length;
for (j = 0; j < len && !break2; j++) {
pos = log2lin(lin2log(i) * intermediate[j]);
if (pos > min && (!minor || lastPos <= max)) { // #1670
positions.push(lastPos);
}
if (lastPos > max) {
break2 = true;
}
lastPos = pos;
}
}
// Third case: We are so deep in between whole logarithmic values that
// we might as well handle the tick positions like a linear axis. For
// example 1.01, 1.02, 1.03, 1.04.
} else {
var realMin = lin2log(min),
realMax = lin2log(max),
tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'],
filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption,
tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1),
totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength;
interval = pick(
filteredTickIntervalOption,
axis._minorAutoInterval,
(realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1)
);
interval = normalizeTickInterval(
interval,
null,
getMagnitude(interval)
);
positions = map(axis.getLinearTickPositions(
interval,
realMin,
realMax
), log2lin);
if (!minor) {
axis._minorAutoInterval = interval / 5;
}
}
// Set the axis-level tickInterval variable
if (!minor) {
axis.tickInterval = interval;
}
return positions;
}
|
javascript
|
{
"resource": ""
}
|
|
q52990
|
train
|
function () {
var axis = this,
options = axis.options,
tickPositions = axis.tickPositions,
minorTickInterval = axis.minorTickInterval,
minorTickPositions = [],
pos,
i,
len;
if (axis.isLog) {
len = tickPositions.length;
for (i = 1; i < len; i++) {
minorTickPositions = minorTickPositions.concat(
axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true)
);
}
} else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314
minorTickPositions = minorTickPositions.concat(
getTimeTicks(
normalizeTimeTickInterval(minorTickInterval),
axis.min,
axis.max,
options.startOfWeek
)
);
if (minorTickPositions[0] < axis.min) {
minorTickPositions.shift();
}
} else {
for (pos = axis.min + (tickPositions[0] - axis.min) % minorTickInterval; pos <= axis.max; pos += minorTickInterval) {
minorTickPositions.push(pos);
}
}
return minorTickPositions;
}
|
javascript
|
{
"resource": ""
}
|
|
q52991
|
train
|
function () {
var axis = this,
options = axis.options,
min = axis.min,
max = axis.max,
zoomOffset,
spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange,
closestDataRange,
i,
distance,
xData,
loopLength,
minArgs,
maxArgs;
// Set the automatic minimum range based on the closest point distance
if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) {
if (defined(options.min) || defined(options.max)) {
axis.minRange = null; // don't do this again
} else {
// Find the closest distance between raw data points, as opposed to
// closestPointRange that applies to processed points (cropped and grouped)
each(axis.series, function (series) {
xData = series.xData;
loopLength = series.xIncrement ? 1 : xData.length - 1;
for (i = loopLength; i > 0; i--) {
distance = xData[i] - xData[i - 1];
if (closestDataRange === UNDEFINED || distance < closestDataRange) {
closestDataRange = distance;
}
}
});
axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin);
}
}
// if minRange is exceeded, adjust
if (max - min < axis.minRange) {
var minRange = axis.minRange;
zoomOffset = (minRange - max + min) / 2;
// if min and max options have been set, don't go beyond it
minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)];
if (spaceAvailable) { // if space is available, stay within the data range
minArgs[2] = axis.dataMin;
}
min = arrayMax(minArgs);
maxArgs = [min + minRange, pick(options.max, min + minRange)];
if (spaceAvailable) { // if space is availabe, stay within the data range
maxArgs[2] = axis.dataMax;
}
max = arrayMin(maxArgs);
// now if the max is adjusted, adjust the min back
if (max - min < minRange) {
minArgs[0] = max - minRange;
minArgs[1] = pick(options.min, max - minRange);
min = arrayMax(minArgs);
}
}
// Record modified extremes
axis.min = min;
axis.max = max;
}
|
javascript
|
{
"resource": ""
}
|
|
q52992
|
train
|
function (saveOld) {
var axis = this,
range = axis.max - axis.min,
pointRange = 0,
closestPointRange,
minPointOffset = 0,
pointRangePadding = 0,
linkedParent = axis.linkedParent,
ordinalCorrection,
transA = axis.transA;
// adjust translation for padding
if (axis.isXAxis) {
if (linkedParent) {
minPointOffset = linkedParent.minPointOffset;
pointRangePadding = linkedParent.pointRangePadding;
} else {
each(axis.series, function (series) {
var seriesPointRange = series.pointRange,
pointPlacement = series.options.pointPlacement,
seriesClosestPointRange = series.closestPointRange;
if (seriesPointRange > range) { // #1446
seriesPointRange = 0;
}
pointRange = mathMax(pointRange, seriesPointRange);
// minPointOffset is the value padding to the left of the axis in order to make
// room for points with a pointRange, typically columns. When the pointPlacement option
// is 'between' or 'on', this padding does not apply.
minPointOffset = mathMax(
minPointOffset,
isString(pointPlacement) ? 0 : seriesPointRange / 2
);
// Determine the total padding needed to the length of the axis to make room for the
// pointRange. If the series' pointPlacement is 'on', no padding is added.
pointRangePadding = mathMax(
pointRangePadding,
pointPlacement === 'on' ? 0 : seriesPointRange
);
// Set the closestPointRange
if (!series.noSharedTooltip && defined(seriesClosestPointRange)) {
closestPointRange = defined(closestPointRange) ?
mathMin(closestPointRange, seriesClosestPointRange) :
seriesClosestPointRange;
}
});
}
// Record minPointOffset and pointRangePadding
ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853
axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection;
axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection;
// pointRange means the width reserved for each point, like in a column chart
axis.pointRange = mathMin(pointRange, range);
// closestPointRange means the closest distance between points. In columns
// it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange
// is some other value
axis.closestPointRange = closestPointRange;
}
// Secondary values
if (saveOld) {
axis.oldTransA = transA;
}
axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1);
axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend
axis.minPixelPadding = transA * minPointOffset;
}
|
javascript
|
{
"resource": ""
}
|
|
q52993
|
train
|
function () {
var chart = this.chart,
options = this.options,
offsetLeft = options.offsetLeft || 0,
offsetRight = options.offsetRight || 0,
horiz = this.horiz,
width,
height,
top,
left;
// Expose basic values to use in Series object and navigator
this.left = left = pick(options.left, chart.plotLeft + offsetLeft);
this.top = top = pick(options.top, chart.plotTop);
this.width = width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight);
this.height = height = pick(options.height, chart.plotHeight);
this.bottom = chart.chartHeight - height - top;
this.right = chart.chartWidth - width - left;
// Direction agnostic properties
this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905
this.pos = horiz ? left : top; // distance from SVG origin
}
|
javascript
|
{
"resource": ""
}
|
|
q52994
|
train
|
function (rotation) {
var ret,
angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360;
if (angle > 15 && angle < 165) {
ret = 'right';
} else if (angle > 195 && angle < 345) {
ret = 'left';
} else {
ret = 'center';
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
|
q52995
|
train
|
function (lineWidth) {
var chart = this.chart,
opposite = this.opposite,
offset = this.offset,
horiz = this.horiz,
lineLeft = this.left + (opposite ? this.width : 0) + offset,
lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset;
if (opposite) {
lineWidth *= -1; // crispify the other way - #1480, #1687
}
return chart.renderer.crispLine([
M,
horiz ?
this.left :
lineLeft,
horiz ?
lineTop :
this.top,
L,
horiz ?
chart.chartWidth - this.right :
lineLeft,
horiz ?
lineTop :
chart.chartHeight - this.bottom
], lineWidth);
}
|
javascript
|
{
"resource": ""
}
|
|
q52996
|
train
|
function () {
// compute anchor points for each of the title align options
var horiz = this.horiz,
axisLeft = this.left,
axisTop = this.top,
axisLength = this.len,
axisTitleOptions = this.options.title,
margin = horiz ? axisLeft : axisTop,
opposite = this.opposite,
offset = this.offset,
fontSize = pInt(axisTitleOptions.style.fontSize || 12),
// the position in the length direction of the axis
alongAxis = {
low: margin + (horiz ? 0 : axisLength),
middle: margin + axisLength / 2,
high: margin + (horiz ? axisLength : 0)
}[axisTitleOptions.align],
// the position in the perpendicular direction of the axis
offAxis = (horiz ? axisTop + this.height : axisLeft) +
(horiz ? 1 : -1) * // horizontal axis reverses the margin
(opposite ? -1 : 1) * // so does opposite axes
this.axisTitleMargin +
(this.side === 2 ? fontSize : 0);
return {
x: horiz ?
alongAxis :
offAxis + (opposite ? this.width : 0) + offset +
(axisTitleOptions.x || 0), // x
y: horiz ?
offAxis - (opposite ? this.height : 0) + offset :
alongAxis + (axisTitleOptions.y || 0) // y
};
}
|
javascript
|
{
"resource": ""
}
|
|
q52997
|
train
|
function () {
var series = this.series,
i = series.length;
if (!this.isXAxis) {
while (i--) {
series[i].setStackedPoints();
}
// Loop up again to compute percent stack
if (this.usePercentage) {
for (i = 0; i < series.length; i++) {
series[i].setPercentStacks();
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52998
|
train
|
function (points, mouseEvent) {
var ret,
chart = this.chart,
inverted = chart.inverted,
plotTop = chart.plotTop,
plotX = 0,
plotY = 0,
yAxis;
points = splat(points);
// Pie uses a special tooltipPos
ret = points[0].tooltipPos;
// When tooltip follows mouse, relate the position to the mouse
if (this.followPointer && mouseEvent) {
if (mouseEvent.chartX === UNDEFINED) {
mouseEvent = chart.pointer.normalize(mouseEvent);
}
ret = [
mouseEvent.chartX - chart.plotLeft,
mouseEvent.chartY - plotTop
];
}
// When shared, use the average position
if (!ret) {
each(points, function (point) {
yAxis = point.series.yAxis;
plotX += point.plotX;
plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) +
(!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151
});
plotX /= points.length;
plotY /= points.length;
ret = [
inverted ? chart.plotWidth - plotY : plotX,
this.shared && !inverted && points.length > 1 && mouseEvent ?
mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424)
inverted ? chart.plotHeight - plotX : plotY
];
}
return map(ret, mathRound);
}
|
javascript
|
{
"resource": ""
}
|
|
q52999
|
train
|
function (point) {
var chart = this.chart,
label = this.label,
pos = (this.options.positioner || this.getPosition).call(
this,
label.width,
label.height,
point
);
// do the move
this.move(
mathRound(pos.x),
mathRound(pos.y),
point.plotX + chart.plotLeft,
point.plotY + chart.plotTop
);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.