_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q26100 | injectReporter | train | function injectReporter() {
page.evaluate(function (script) {
function print(msg) {
console.log(msg);
}
function onComplete(passed) {
window.callPhantom(passed);
}
eval(script);
var reporter = new ConsoleReporter();
reporter.setOptions({
print: print,
printDeprecation: print,
showColors: true,
onComplete: onComplete
});
jasmine.getEnv().addReporter(reporter);
}, reporterScript);
} | javascript | {
"resource": ""
} |
q26101 | removeRipple | train | function removeRipple(e, el, ripple) {
// Check if the ripple still exist
if (!ripple) {
return;
}
ripple.classList.remove('waves-rippling');
var relativeX = ripple.getAttribute('data-x');
var relativeY = ripple.getAttribute('data-y');
var scale = ripple.getAttribute('data-scale');
var translate = ripple.getAttribute('data-translate');
// Get delay beetween mousedown and mouse leave
var diff = Date.now() - Number(ripple.getAttribute('data-hold'));
var delay = 350 - diff;
if (delay < 0) {
delay = 0;
}
if (e.type === 'mousemove') {
delay = 150;
}
// Fade out ripple after delay
var duration = e.type === 'mousemove' ? 2500 : Effect.duration;
setTimeout(function() {
var style = {
top: relativeY + 'px',
left: relativeX + 'px',
opacity: '0',
// Duration
'-webkit-transition-duration': duration + 'ms',
'-moz-transition-duration': duration + 'ms',
'-o-transition-duration': duration + 'ms',
'transition-duration': duration + 'ms',
'-webkit-transform': scale + ' ' + translate,
'-moz-transform': scale + ' ' + translate,
'-ms-transform': scale + ' ' + translate,
'-o-transform': scale + ' ' + translate,
'transform': scale + ' ' + translate
};
ripple.setAttribute('style', convertStyle(style));
setTimeout(function() {
try {
el.removeChild(ripple);
} catch (e) {
return false;
}
}, duration);
}, delay);
} | javascript | {
"resource": ""
} |
q26102 | winwheelStopAnimation | train | function winwheelStopAnimation(canCallback)
{
// When the animation is stopped if canCallback is not false then try to call the callback.
// false can be passed in to stop the after happening if the animation has been stopped before it ended normally.
if (canCallback != false) {
let callback = winwheelToDrawDuringAnimation.animation.callbackFinished;
if (callback != null) {
// If the callback is a function then call it, otherwise evaluate the property as javascript code.
if (typeof callback === 'function') {
// Pass back the indicated segment as 99% of the time you will want to know this to inform the user of their prize.
callback(winwheelToDrawDuringAnimation.getIndicatedSegment());
} else {
eval(callback);
}
}
}
} | javascript | {
"resource": ""
} |
q26103 | aaObtainFurthestBlock | train | function aaObtainFurthestBlock(p, formattingElementEntry) {
let furthestBlock = null;
for (let i = p.openElements.stackTop; i >= 0; i--) {
const element = p.openElements.items[i];
if (element === formattingElementEntry.element) {
break;
}
if (p._isSpecialElement(element)) {
furthestBlock = element;
}
}
if (!furthestBlock) {
p.openElements.popUntilElementPopped(formattingElementEntry.element);
p.activeFormattingElements.removeEntry(formattingElementEntry);
}
return furthestBlock;
} | javascript | {
"resource": ""
} |
q26104 | aaInnerLoop | train | function aaInnerLoop(p, furthestBlock, formattingElement) {
let lastElement = furthestBlock;
let nextElement = p.openElements.getCommonAncestor(furthestBlock);
for (let i = 0, element = nextElement; element !== formattingElement; i++, element = nextElement) {
//NOTE: store next element for the next loop iteration (it may be deleted from the stack by step 9.5)
nextElement = p.openElements.getCommonAncestor(element);
const elementEntry = p.activeFormattingElements.getElementEntry(element);
const counterOverflow = elementEntry && i >= AA_INNER_LOOP_ITER;
const shouldRemoveFromOpenElements = !elementEntry || counterOverflow;
if (shouldRemoveFromOpenElements) {
if (counterOverflow) {
p.activeFormattingElements.removeEntry(elementEntry);
}
p.openElements.remove(element);
} else {
element = aaRecreateElementFromEntry(p, elementEntry);
if (lastElement === furthestBlock) {
p.activeFormattingElements.bookmark = elementEntry;
}
p.treeAdapter.detachNode(lastElement);
p.treeAdapter.appendChild(element, lastElement);
lastElement = element;
}
}
return lastElement;
} | javascript | {
"resource": ""
} |
q26105 | aaRecreateElementFromEntry | train | function aaRecreateElementFromEntry(p, elementEntry) {
const ns = p.treeAdapter.getNamespaceURI(elementEntry.element);
const newElement = p.treeAdapter.createElement(elementEntry.token.tagName, ns, elementEntry.token.attrs);
p.openElements.replace(elementEntry.element, newElement);
elementEntry.element = newElement;
return newElement;
} | javascript | {
"resource": ""
} |
q26106 | aaInsertLastNodeInCommonAncestor | train | function aaInsertLastNodeInCommonAncestor(p, commonAncestor, lastElement) {
if (p._isElementCausesFosterParenting(commonAncestor)) {
p._fosterParentElement(lastElement);
} else {
const tn = p.treeAdapter.getTagName(commonAncestor);
const ns = p.treeAdapter.getNamespaceURI(commonAncestor);
if (tn === $.TEMPLATE && ns === NS.HTML) {
commonAncestor = p.treeAdapter.getTemplateContent(commonAncestor);
}
p.treeAdapter.appendChild(commonAncestor, lastElement);
}
} | javascript | {
"resource": ""
} |
q26107 | aaReplaceFormattingElement | train | function aaReplaceFormattingElement(p, furthestBlock, formattingElementEntry) {
const ns = p.treeAdapter.getNamespaceURI(formattingElementEntry.element);
const token = formattingElementEntry.token;
const newElement = p.treeAdapter.createElement(token.tagName, ns, token.attrs);
p._adoptNodes(furthestBlock, newElement);
p.treeAdapter.appendChild(furthestBlock, newElement);
p.activeFormattingElements.insertElementAfterBookmark(newElement, formattingElementEntry.token);
p.activeFormattingElements.removeEntry(formattingElementEntry);
p.openElements.remove(formattingElementEntry.element);
p.openElements.insertAfter(furthestBlock, newElement);
} | javascript | {
"resource": ""
} |
q26108 | train | function(errors, options) {
errors = v.pruneEmptyErrors(errors, options);
errors = v.expandMultipleErrors(errors, options);
errors = v.convertErrorMessages(errors, options);
var format = options.format || "grouped";
if (typeof v.formatters[format] === 'function') {
errors = v.formatters[format](errors);
} else {
throw new Error(v.format("Unknown format %{format}", options));
}
return v.isEmpty(errors) ? undefined : errors;
} | javascript | {
"resource": ""
} | |
q26109 | train | function(attributes, constraints, options) {
options = v.extend({}, v.async.options, options);
var WrapErrors = options.wrapErrors || function(errors) {
return errors;
};
// Removes unknown attributes
if (options.cleanAttributes !== false) {
attributes = v.cleanAttributes(attributes, constraints);
}
var results = v.runValidations(attributes, constraints, options);
return new v.Promise(function(resolve, reject) {
v.waitForResults(results).then(function() {
var errors = v.processValidationResults(results, options);
if (errors) {
reject(new WrapErrors(errors, options, attributes, constraints));
} else {
resolve(attributes);
}
}, function(err) {
reject(err);
});
});
} | javascript | {
"resource": ""
} | |
q26110 | train | function(results) {
// Create a sequence of all the results starting with a resolved promise.
return results.reduce(function(memo, result) {
// If this result isn't a promise skip it in the sequence.
if (!v.isPromise(result.error)) {
return memo;
}
return memo.then(function() {
return result.error.then(function(error) {
result.error = error || null;
});
});
}, new v.Promise(function(r) { r(); })); // A resolved promise
} | javascript | {
"resource": ""
} | |
q26111 | train | function(value) {
return v.isObject(value) && !v.isArray(value) && !v.isFunction(value);
} | javascript | {
"resource": ""
} | |
q26112 | train | function(errors, options) {
options = options || {};
var ret = []
, prettify = options.prettify || v.prettify;
errors.forEach(function(errorInfo) {
var error = v.result(errorInfo.error,
errorInfo.value,
errorInfo.attribute,
errorInfo.options,
errorInfo.attributes,
errorInfo.globalOptions);
if (!v.isString(error)) {
ret.push(errorInfo);
return;
}
if (error[0] === '^') {
error = error.slice(1);
} else if (options.fullMessages !== false) {
error = v.capitalize(prettify(errorInfo.attribute)) + " " + error;
}
error = error.replace(/\\\^/g, "^");
error = v.format(error, {
value: v.stringifyValue(errorInfo.value, options)
});
ret.push(v.extend({}, errorInfo, {error: error}));
});
return ret;
} | javascript | {
"resource": ""
} | |
q26113 | train | function(value, options) {
options = v.extend({}, this.options, options);
if (options.allowEmpty !== false ? !v.isDefined(value) : v.isEmpty(value)) {
return options.message || this.message || "can't be blank";
}
} | javascript | {
"resource": ""
} | |
q26114 | train | function(value, options) {
if (!v.isDefined(value)) {
return;
}
options = v.extend({}, this.options, options);
var message = options.message || this.message || "is not a valid url"
, schemes = options.schemes || this.schemes || ['http', 'https']
, allowLocal = options.allowLocal || this.allowLocal || false
, allowDataUrl = options.allowDataUrl || this.allowDataUrl || false;
if (!v.isString(value)) {
return message;
}
// https://gist.github.com/dperini/729294
var regex =
"^" +
// protocol identifier
"(?:(?:" + schemes.join("|") + ")://)" +
// user:pass authentication
"(?:\\S+(?::\\S*)?@)?" +
"(?:";
var tld = "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))";
if (allowLocal) {
tld += "?";
} else {
regex +=
// IP address exclusion
// private & local networks
"(?!(?:10|127)(?:\\.\\d{1,3}){3})" +
"(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" +
"(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})";
}
regex +=
// IP address dotted notation octets
// excludes loopback network 0.0.0.0
// excludes reserved space >= 224.0.0.0
// excludes network & broacast addresses
// (first & last IP address of each class)
"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
"|" +
// host name
"(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" +
// domain name
"(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" +
tld +
")" +
// port number
"(?::\\d{2,5})?" +
// resource path
"(?:[/?#]\\S*)?" +
"$";
if (allowDataUrl) {
// RFC 2397
var mediaType = "\\w+\\/[-+.\\w]+(?:;[\\w=]+)*";
var urlchar = "[A-Za-z0-9-_.!~\\*'();\\/?:@&=+$,%]*";
var dataurl = "data:(?:"+mediaType+")?(?:;base64)?,"+urlchar;
regex = "(?:"+regex+")|(?:^"+dataurl+"$)";
}
var PATTERN = new RegExp(regex, 'i');
if (!PATTERN.exec(value)) {
return message;
}
} | javascript | {
"resource": ""
} | |
q26115 | getRgbAColor | train | function getRgbAColor(color, opacity) {
const id = color + '&' + opacity;
if (colorCache[id]) {
return colorCache[id];
}
const div = document.createElement('div');
div.style.background = color;
document.body.appendChild(div);
const computedColor = window.getComputedStyle(div).backgroundColor;
document.body.removeChild(div);
/* istanbul ignore if */
if (!rgbReg.test(computedColor)) {
return color;
}
return (colorCache[id] = `rgba(${
extractRgbColor.exec(computedColor)[1]
}, ${opacity})`);
} | javascript | {
"resource": ""
} |
q26116 | createTipDom | train | function createTipDom(h, context, type, tip) {
const stage = context.vuescroll.state[`${type}Stage`];
let dom = null;
// Return user specified animation dom
/* istanbul ignore if */
if ((dom = context.$slots[`${type}-${stage}`])) {
return dom;
}
switch (stage) {
// The dom will show at deactive stage
case 'deactive':
case 'active':
{
let className = 'active';
if (stage == 'deactive') {
className += ' deactive';
}
dom = (
<svg
class={className}
version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
x="0px"
y="0px"
viewBox="0 0 1000 1000"
enable-background="new 0 0 1000 1000"
xmlSpace="preserve"
>
<metadata> Svg Vector Icons : http://www.sfont.cn </metadata>
<g>
<g transform="matrix(1 0 0 -1 0 1008)">
<path d="M10,543l490,455l490-455L885,438L570,735.5V18H430v717.5L115,438L10,543z" />
</g>
</g>
</svg>
);
}
break;
case 'start':
dom = (
<svg viewBox="0 0 50 50" class="start">
<circle stroke="true" cx="25" cy="25" r="20" class="bg-path" />
<circle cx="25" cy="25" r="20" class="active-path" />
</svg>
);
break;
case 'beforeDeactive':
dom = (
<svg
viewBox="0 0 1024 1024"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
p-id="3562"
>
<path
d="M512 0C229.706831 0 0 229.667446 0 512s229.667446 512 512 512c282.293169 0 512-229.667446 512-512S794.332554 0 512 0z m282.994215 353.406031L433.2544 715.145846a31.484062 31.484062 0 0 1-22.275938 9.231754h-0.4096a31.586462 31.586462 0 0 1-22.449231-9.814646L228.430769 546.327631a31.507692 31.507692 0 0 1 45.701908-43.386093l137.4208 144.785724L750.442338 308.854154a31.507692 31.507692 0 1 1 44.551877 44.551877z"
fill=""
p-id="3563"
/>
</svg>
);
break;
}
return [dom, tip];
} | javascript | {
"resource": ""
} |
q26117 | configValidator | train | function configValidator(ops) {
let renderError = false;
const { vuescroll } = ops;
// validate modes
if (!~modes.indexOf(vuescroll.mode)) {
error(
`Unknown mode: ${
vuescroll.mode
},the vuescroll's option "mode" should be one of the ${modes}`
);
renderError = true;
}
return renderError;
} | javascript | {
"resource": ""
} |
q26118 | BatchOperation | train | function BatchOperation(name, options) {
if (!options) {
options = {};
}
this.name = name;
this.logger = options.logger || new Logger(Logger.LogLevels.INFO);
this.operationMemoryUsage = options.operationMemoryUsage || DEFAULT_OPERATION_MEMORY_USAGE;
this.callbackInOrder = options.callbackInOrder === true;
this.callInOrder = options.callInOrder === true;
this._currentOperationId = this.callbackInOrder ? 1 : -1;
this.concurrency = DEFAULT_GLOBAL_CONCURRENCY;
this.enableReuseSocket = (nodeVersion.major > 0 || nodeVersion.minor >= 10) && options.enableReuseSocket;
this._emitter = new EventEmitter();
this._enableComplete = false;
this._ended = false;
this._error = null;
this._paused = false;
//Total operations count(queued and active and connected)
this._totalOperation = 0;
//Action operations count(The operations which are connecting to remote or executing callback or queued for executing)
this._activeOperation = 0;
//Queued operations count(The operations which are connecting to remote or queued for executing)
this._queuedOperation = 0;
//finished operation should be removed from this array
this._operations = [];
} | javascript | {
"resource": ""
} |
q26119 | RestOperation | train | function RestOperation(serviceClient, operation) {
this.status = OperationState.Inited;
this.operationId = -1;
this._callbackArguments = null;
// setup callback and args
this._userCallback = arguments[arguments.length - 1];
var sliceEnd = arguments.length;
if(azureutil.objectIsFunction(this._userCallback)) {
sliceEnd--;
} else {
this._userCallback = null;
}
var operationArguments = Array.prototype.slice.call(arguments).slice(2, sliceEnd);
this.run = function(cb) {
var func = serviceClient[operation];
if(!func) {
throw new ArgumentError('operation', util.format('Unknown operation %s in serviceclient', operation));
} else {
if(!cb) cb = this._userCallback;
operationArguments.push(cb);
this.status = OperationState.RUNNING;
func.apply(serviceClient, operationArguments);
operationArguments = operation = null;
}
};
this._fireUserCallback = function () {
if(this._userCallback) {
this._userCallback.apply(null, this._callbackArguments);
}
};
} | javascript | {
"resource": ""
} |
q26120 | CommonOperation | train | function CommonOperation(operationFunc, callback) {
this.status = OperationState.Inited;
this.operationId = -1;
this._callbackArguments = null;
var sliceStart = 2;
if (azureutil.objectIsFunction(callback)) {
this._userCallback = callback;
} else {
this._userCallback = null;
sliceStart = 1;
}
var operationArguments = Array.prototype.slice.call(arguments).slice(sliceStart);
this.run = function (cb) {
if (!cb) cb = this._userCallback;
operationArguments.push(cb);
this.status = OperationState.RUNNING;
operationFunc.apply(null, operationArguments);
operationArguments = operationFunc = null;
};
this._fireUserCallback = function () {
if (this._userCallback) {
this._userCallback.apply(null, this._callbackArguments);
}
this._userCallback = this._callbackArguments = null;
};
} | javascript | {
"resource": ""
} |
q26121 | FileRangeStream | train | function FileRangeStream(fileServiceClient, share, directory, file, options) {
FileRangeStream['super_'].call(this, fileServiceClient, null, null, options);
this._lengthHeader = Constants.HeaderConstants.FILE_CONTENT_LENGTH;
if (options.minRangeSize) {
this._minRangeSize = options.minRangeSize;
} else {
this._minRangeSize = Constants.FileConstants.MIN_WRITE_FILE_SIZE_IN_BYTES;
}
if (options.maxRangeSize) {
this._maxRangeSize = options.maxRangeSize;
} else {
this._maxRangeSize = Constants.FileConstants.DEFAULT_WRITE_SIZE_IN_BYTES;
}
this._listFunc = fileServiceClient.listRanges;
this._resourcePath.push(share);
this._resourcePath.push(directory);
this._resourcePath.push(file);
} | javascript | {
"resource": ""
} |
q26122 | train | function () {
var options = { publicAccessLevel: BlobUtilities.BlobContainerPublicAccessType.CONTAINER };
blobService.setContainerAcl(container, signedIdentifiers, options, function(error) {
if (error) {
console.log(error);
} else {
console.log('Uploaded the permissions for the container ' + container);
callback();
}
});
} | javascript | {
"resource": ""
} | |
q26123 | setRetries | train | function setRetries() {
console.log('Starting Sample 1 - setRetries.');
// By default, no retry will be performed with all kinds of services created
// by Azure storage client library for Node.js.
var blobServiceWithoutRetry = azure.createBlobService();
console.log('BlobService instance created, no retry will be performed by default.');
// There are two pre-written retry policies: ExponentialRetryPolicyFilter
// and LinearRetryPolicyFilter can be used with modifiable settings.
// Use an exponential retry with customized settings.
var fileServiceWithExponentialRetry = azure.createFileService().withFilter(
new azure.ExponentialRetryPolicyFilter(
3, // retryCount is set to 3 times.
4000, // retryInterval is set to 4 seconds.
3000, // minRetryInterval is set to 3 seconds.
120000 // maxRetryInterval is set to 120 seconds.
));
console.log('FileService instance created and associated with ExponentialRetryPolicyFilter.');
console.log(' Retries will be performed with exponential back-off.');
// Use a default linear retry policy.
var tableServiceWithLinearRetry = azure.createTableService().withFilter(
new azure.LinearRetryPolicyFilter()); // By default, retryCount is set to 3 times and retryInterval is set to 30 seconds.
console.log('TableService instance created and associated with LinearRetryPolicyFilter,');
console.log(' Retries will be performed with linear back-off.');
console.log('Ending Sample 1 - setRetries.');
} | javascript | {
"resource": ""
} |
q26124 | setCustomRetryPolicy | train | function setCustomRetryPolicy() {
console.log('Starting Sample 2 - setCustomRetryPolicy.');
// Step 1 : Set the retry policy to customized retry policy which will
// not retry on any failing status code other than the excepted one.
var retryOnContainerBeingDeleted = new RetryPolicyFilter();
retryOnContainerBeingDeleted.retryCount = 5;
retryOnContainerBeingDeleted.retryInterval = 5000;
retryOnContainerBeingDeleted.shouldRetry = function (statusCode, retryData) {
console.log(' Made the request at ' + new Date().toUTCString() + ', received StatusCode: ' + statusCode);
var retryInfo = {};
// retries on any bad status code other than 409
if (statusCode >= 300 && statusCode !== 409 && statusCode !== 500) {
retryInfo.retryable = false;
} else {
var currentCount = (retryData && retryData.retryCount) ? retryData.retryCount : 0;
retryInfo = {
retryInterval: this.retryInterval + 2000 * currentCount,
retryable: currentCount < this.retryCount
};
}
return retryInfo;
};
blobService = azure.createBlobService().withFilter(retryOnContainerBeingDeleted);
// optionally set a proxy
/*var proxy = {
protocol: 'http:',
host: '127.0.0.1',
port: 8888
};
blobService.setProxy(proxy);*/
// Step 2: Create the container
createContainer(function () {
// Step 3: Fetch attributes from the container using LocationMode.SECONDARY_THEN_PRIMARY
fetchAttributesContainer(function () {
// Step 4: Lease the container
leaseContainer(function () {
// Step 5: Lease the container again, retrying until it succeeds
leaseContainer(function () {
// Step 6: Delete the container
deleteContainer(function () {
console.log('Ending Sample 2 - setCustomRetryPolicy.');
});
});
});
});
});
} | javascript | {
"resource": ""
} |
q26125 | FileReadStream | train | function FileReadStream(path, options) {
stream.Stream.call(this);
this.readable = true;
if(!options) {
options = {};
}
this._destroyed = false;
this._streamEnded = false;
this._fd = null;
this._fileName = undefined;
this._highWaterMark = options.highWaterMark || bufferSize;
this._offset = 0;
this._paused = undefined;
this._allocator = options.allocator;
this._fileName = path;
this._md5hash = null;
this._md5sum = undefined;
if (options.calcContentMd5) {
this._md5hash = new Md5Wrapper().createMd5Hash();
}
this._open();
} | javascript | {
"resource": ""
} |
q26126 | toHumanReadableSize | train | function toHumanReadableSize(size, len) {
if(!size) return '0B';
if (!len || len <= 0) {
len = 2;
}
var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor( Math.log(size) / Math.log(1024));
return (size/Math.pow(1024, i)).toFixed(len) + units[i];
} | javascript | {
"resource": ""
} |
q26127 | StorageServiceSettings | train | function StorageServiceSettings(name, key, sasToken, blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint, usePathStyleUri, token) {
this._name = name;
this._key = key;
if (sasToken && sasToken[0] === '?') {
this._sasToken = sasToken.slice(1);
} else {
this._sasToken = sasToken;
}
this._blobEndpoint = blobEndpoint;
this._queueEndpoint = queueEndpoint;
this._tableEndpoint = tableEndpoint;
this._fileEndpoint = fileEndpoint;
if (usePathStyleUri) {
this._usePathStyleUri = usePathStyleUri;
} else {
this._usePathStyleUri = false;
}
this._token = token;
} | javascript | {
"resource": ""
} |
q26128 | BatchResult | train | function BatchResult(tableService, table, operations) {
this.tableService = tableService;
this.table = table;
this.operations = operations;
this.batchBoundary = 'batch_' + BatchResult._getBoundary();
this.changesetBoundary = 'changeset_' + BatchResult._getBoundary();
} | javascript | {
"resource": ""
} |
q26129 | StorageServiceClient | train | function StorageServiceClient(storageAccount, storageAccessKey, host, usePathStyleUri, sas, token) {
StorageServiceClient['super_'].call(this);
if(storageAccount && storageAccessKey) {
// account and key
this.storageAccount = storageAccount;
this.storageAccessKey = storageAccessKey;
this.storageCredentials = new SharedKey(this.storageAccount, this.storageAccessKey, usePathStyleUri);
} else if (sas) {
// sas
this.sasToken = sas;
this.storageCredentials = new SharedAccessSignature(sas);
} else if (token) {
// access token
this.token = token;
this.storageCredentials = new TokenSigner(token);
} else {
// anonymous
this.anonymous = true;
this.storageCredentials = {
signRequest: function(webResource, callback){
// no op, anonymous access
callback(null);
}
};
}
if(host){
this.setHost(host);
}
this.apiVersion = HeaderConstants.TARGET_STORAGE_VERSION;
this.usePathStyleUri = usePathStyleUri;
this._initDefaultFilter();
/**
* The logger of the service. To change the log level of the services, set the `[logger.level]{@link Logger#level}`.
* @name StorageServiceClient#logger
* @type Logger
* */
this.logger = new Logger(Logger.LogLevels.INFO);
this._setDefaultProxy();
this.xml2jsSettings = StorageServiceClient._getDefaultXml2jsSettings();
this.defaultLocationMode = StorageUtilities.LocationMode.PRIMARY_ONLY;
} | javascript | {
"resource": ""
} |
q26130 | train | function (postPostRequestOptions, parentFilterCallback) {
// The parentFilterNext is the filter next to the merged filter.
// For 2 filters, that'd be the actual operation.
parentFilterNext(postPostRequestOptions, function (responseObject, responseCallback, finalCallback) {
parentFilterCallback(responseObject, finalCallback, function (postResponseObject) {
newFilterCallback(postResponseObject, responseCallback, finalCallback);
});
});
} | javascript | {
"resource": ""
} | |
q26131 | parseXObject | train | function parseXObject(xObject) {
const objectId = xObject.getObjectID();
const pdfStreamInput = cpyCxtParser.parseNewObject(objectId);
const xObjectDictionary = pdfStreamInput.getDictionary().toJSObject();
if (xObjectDictionary.Subtype.value === 'Image') {
// Create a hash of the compressed stream instead of using
// startReadingFromStream(pdfStreamInput) to skip uneeded decoding
const stream = cpyCxtParser.getParserStream();
stream.setPosition(pdfStreamInput.getStreamContentStart());
const digest = crypto.createHash('SHA1')
.update(Buffer.from(stream.read(pdfStreamInput.getDictionary().toJSObject().Length.value)))
.digest('hex');
if (!context.pdfXObjects[digest]) {
xObjects[digest] = objectId;
} else {
const replacement = {};
replacement[objectId] = context.pdfXObjects[digest];
cpyCxt.replaceSourceObjects(replacement);
}
} else {
parseResources(xObjectDictionary);
}
} | javascript | {
"resource": ""
} |
q26132 | parseFont | train | function parseFont(fontObject) {
const pdfStreamInput = cpyCxtParser.parseNewObject(fontObject.getObjectID());
const fontDictionary = pdfStreamInput.toJSObject();
// See "Introduction to Font Data Structures" from PDF specification
if (fontDictionary.Subtype.value === 'Type0') {
// TODO: properly support composite fonts with multiple descendants
const descendant = cpyCxtParser
.parseNewObject(fontDictionary.DescendantFonts.toJSArray()[0].getObjectID())
.toJSObject();
if (descendant.Subtype.value == 'CIDFontType2') {
const descriptor = cpyCxtParser
.parseNewObject(descendant.FontDescriptor.getObjectID())
.toJSObject();
const id = descriptor.FontFile2.getObjectID();
const buffer = readStream(cpyCxtParser.parseNewObject(id));
const font = Font.create(buffer, { type: 'ttf', hinting: true });
// PDF font name does not contain sub family on Windows 10 so a more robust key
// is computed from the font metadata
const name = descriptor.FontName.value + ' - ' + fontMetadataKey(font.data.name);
if (context.pdfFonts[name]) {
const f = context.pdfFonts[name].font;
font.data.glyf.forEach((g, i) => {
if (g.contours && g.contours.length > 0) {
if (!f.data.glyf[i].contours || f.data.glyf[i].contours.length === 0) {
f.data.glyf[i] = g;
}
} else if (g.compound) {
if (typeof f.data.glyf[i].compound === 'undefined'
&& f.data.glyf[i].contours.length === 0) {
f.data.glyf[i] = g;
}
}
});
const replacement = {};
replacement[id] = context.pdfFonts[name].id;
cpyCxt.replaceSourceObjects(replacement);
} else {
const xObjectId = printer.getObjectsContext().allocateNewObjectID();
context.pdfFonts[name] = { id: xObjectId, font: font };
const replacement = {};
replacement[id] = xObjectId;
cpyCxt.replaceSourceObjects(replacement);
}
}
}
} | javascript | {
"resource": ""
} |
q26133 | getReferences | train | function getReferences(path, variableName) {
const bindings = path.scope.getBinding(variableName);
const references = bindings.referencePaths;
return references;
} | javascript | {
"resource": ""
} |
q26134 | getIdentifierVariableName | train | function getIdentifierVariableName(path) {
if (
path.isIdentifier()
&& path.parentPath.isCallExpression()
&& path.parentPath.parentPath.isVariableDeclarator()
) {
const variableName = path.parentPath.parentPath.node.id.name;
return variableName;
}
return '';
} | javascript | {
"resource": ""
} |
q26135 | getPackageName | train | function getPackageName(content, pluginLookup, identifierPath) {
let memberPath = identifierPath.parentPath;
while (memberPath.isMemberExpression()) {
const code = content.slice(identifierPath.node.end, memberPath.node.end);
const pluginName = pluginLookup[code];
if (pluginName) {
return pluginName;
}
memberPath = memberPath.parentPath;
}
return '';
} | javascript | {
"resource": ""
} |
q26136 | check | train | function check(content, deps, path) {
if (
// Pattern: import plugins from 'gulp-load-plugins', $ = plugins(), $.jshint()
importDetector(path.node)[0] === 'gulp-load-plugins'
&& path.isImportDeclaration()
&& path.get('specifiers')[0]
&& path.get('specifiers')[0].isImportDefaultSpecifier()
&& path.get('specifiers')[0].get('local').isIdentifier()
) {
const importVariableName = path.get('specifiers')[0].get('local').node.name;
const identifierReferences = getIdentifierReferences(path, importVariableName);
const packageNames = identifierReferences.map(r => getPackageName(content, deps, r));
return packageNames;
}
if (
// Pattern: plugins = require('gulp-load-plugins'), $ = plugins(), $.jshint()
requireDetector(path.node)[0] === 'gulp-load-plugins'
&& path.isCallExpression()
&& path.parentPath.isVariableDeclarator()
&& path.parentPath.get('id').isIdentifier()
) {
const requireVariableName = path.parentPath.get('id').node.name;
const identifierReferences = getIdentifierReferences(path, requireVariableName);
const packageNames = identifierReferences.map(r => getPackageName(content, deps, r));
return packageNames;
}
if (
// Pattern: $ = require('gulp-load-plugins')(), $.jshint()
requireDetector(path.node)[0] === 'gulp-load-plugins'
&& path.isCallExpression()
&& path.parentPath.isCallExpression()
&& path.parentPath.parentPath.isVariableDeclarator()
&& path.parentPath.parentPath.get('id').isIdentifier()
) {
const requireVariableName = path.parentPath.parentPath.get('id').node.name;
const identifierReferences = getReferences(path, requireVariableName);
const packageNames = identifierReferences.map(r => getPackageName(content, deps, r));
return packageNames;
}
if (
// Pattern: require('gulp-load-plugins')().thisPlugin()
requireDetector(path.node)[0] === 'gulp-load-plugins'
&& path.isCallExpression()
&& path.parentPath.isCallExpression()
&& path.parentPath.parentPath.isMemberExpression()
) {
const packageName = getPackageName(content, deps, path.parentPath);
return [packageName];
}
return [];
} | javascript | {
"resource": ""
} |
q26137 | Manifold | train | function Manifold() {
this.type;
this.localNormal = Vec2.zero();
this.localPoint = Vec2.zero();
this.points = [ new ManifoldPoint(), new ManifoldPoint() ];
this.pointCount = 0;
} | javascript | {
"resource": ""
} |
q26138 | getPointStates | train | function getPointStates(state1, state2, manifold1, manifold2) {
// for (var i = 0; i < Settings.maxManifoldPoints; ++i) {
// state1[i] = PointState.nullState;
// state2[i] = PointState.nullState;
// }
// Detect persists and removes.
for (var i = 0; i < manifold1.pointCount; ++i) {
var id = manifold1.points[i].id;// ContactID
state1[i] = PointState.removeState;
for (var j = 0; j < manifold2.pointCount; ++j) {
if (manifold2.points[j].id.key == id.key) {
state1[i] = PointState.persistState;
break;
}
}
}
// Detect persists and adds.
for (var i = 0; i < manifold2.pointCount; ++i) {
var id = manifold2.points[i].id;// ContactID
state2[i] = PointState.addState;
for (var j = 0; j < manifold1.pointCount; ++j) {
if (manifold1.points[j].id.key == id.key) {
state2[i] = PointState.persistState;
break;
}
}
}
} | javascript | {
"resource": ""
} |
q26139 | clipSegmentToLine | train | function clipSegmentToLine(vOut, vIn, normal, offset, vertexIndexA) {
// Start with no output points
var numOut = 0;
// Calculate the distance of end points to the line
var distance0 = Vec2.dot(normal, vIn[0].v) - offset;
var distance1 = Vec2.dot(normal, vIn[1].v) - offset;
// If the points are behind the plane
if (distance0 <= 0.0)
vOut[numOut++].set(vIn[0]);
if (distance1 <= 0.0)
vOut[numOut++].set(vIn[1]);
// If the points are on different sides of the plane
if (distance0 * distance1 < 0.0) {
// Find intersection point of edge and plane
var interp = distance0 / (distance0 - distance1);
vOut[numOut].v.setCombine(1 - interp, vIn[0].v, interp, vIn[1].v);
// VertexA is hitting edgeB.
vOut[numOut].id.cf.indexA = vertexIndexA;
vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB;
vOut[numOut].id.cf.typeA = Manifold.e_vertex;
vOut[numOut].id.cf.typeB = Manifold.e_face;
++numOut;
}
return numOut;
} | javascript | {
"resource": ""
} |
q26140 | MotorJoint | train | function MotorJoint(def, bodyA, bodyB) {
if (!(this instanceof MotorJoint)) {
return new MotorJoint(def, bodyA, bodyB);
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = MotorJoint.TYPE;
this.m_linearOffset = def.linearOffset ? def.linearOffset : bodyA.getLocalPoint(bodyB.getPosition());
var angleA = bodyA.getAngle();
var angleB = bodyB.getAngle();
this.m_angularOffset = angleB - angleA;
this.m_linearImpulse = Vec2.zero();
this.m_angularImpulse = 0.0;
this.m_maxForce = def.maxForce;
this.m_maxTorque = def.maxTorque;
this.m_correctionFactor = def.correctionFactor;
// Solver temp
this.m_rA; // Vec2
this.m_rB; // Vec2
this.m_localCenterA; // Vec2
this.m_localCenterB; // Vec2
this.m_linearError; // Vec2
this.m_angularError; // float
this.m_invMassA; // float
this.m_invMassB; // float
this.m_invIA; // float
this.m_invIB; // float
this.m_linearMass; // Mat22
this.m_angularMass; // float
// Point-to-point constraint
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
} | javascript | {
"resource": ""
} |
q26141 | WeldJoint | train | function WeldJoint(def, bodyA, bodyB, anchor) {
if (!(this instanceof WeldJoint)) {
return new WeldJoint(def, bodyA, bodyB, anchor);
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = WeldJoint.TYPE;
this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero();
this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero();
this.m_referenceAngle = Math.isFinite(def.referenceAngle) ? def.referenceAngle : bodyB.getAngle() - bodyA.getAngle();
this.m_frequencyHz = def.frequencyHz;
this.m_dampingRatio = def.dampingRatio;
this.m_impulse = Vec3();
this.m_bias = 0.0;
this.m_gamma = 0.0;
// Solver temp
this.m_rA; // Vec2
this.m_rB; // Vec2
this.m_localCenterA; // Vec2
this.m_localCenterB; // Vec2
this.m_invMassA; // float
this.m_invMassB; // float
this.m_invIA; // float
this.m_invIB; // float
this.m_mass = new Mat33();
// Point-to-point constraint
// C = p2 - p1
// Cdot = v2 - v1
// / = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// C = angle2 - angle1 - referenceAngle
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
} | javascript | {
"resource": ""
} |
q26142 | Mat33 | train | function Mat33(a, b, c) {
if (typeof a === 'object' && a !== null) {
this.ex = Vec3.clone(a);
this.ey = Vec3.clone(b);
this.ez = Vec3.clone(c);
} else {
this.ex = Vec3();
this.ey = Vec3();
this.ez = Vec3();
}
} | javascript | {
"resource": ""
} |
q26143 | Mat22 | train | function Mat22(a, b, c, d) {
if (typeof a === 'object' && a !== null) {
this.ex = Vec2.clone(a);
this.ey = Vec2.clone(b);
} else if (typeof a === 'number') {
this.ex = Vec2.neo(a, c);
this.ey = Vec2.neo(b, d)
} else {
this.ex = Vec2.zero();
this.ey = Vec2.zero()
}
} | javascript | {
"resource": ""
} |
q26144 | RopeJoint | train | function RopeJoint(def, bodyA, bodyB, anchor) {
if (!(this instanceof RopeJoint)) {
return new RopeJoint(def, bodyA, bodyB, anchor);
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = RopeJoint.TYPE;
this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.neo(-1.0, 0.0);
this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.neo(1.0, 0.0);
this.m_maxLength = def.maxLength;
this.m_mass = 0.0;
this.m_impulse = 0.0;
this.m_length = 0.0;
this.m_state = inactiveLimit;
// Solver temp
this.m_u; // Vec2
this.m_rA; // Vec2
this.m_rB; // Vec2
this.m_localCenterA; // Vec2
this.m_localCenterB; // Vec2
this.m_invMassA; // float
this.m_invMassB; // float
this.m_invIA; // float
this.m_invIB; // float
this.m_mass; // float
// Limit:
// C = norm(pB - pA) - L
// u = (pB - pA) / norm(pB - pA)
// Cdot = dot(u, vB + cross(wB, rB) - vA - cross(wA, rA))
// J = [-u -cross(rA, u) u cross(rB, u)]
// K = J * invM * JT
// = invMassA + invIA * cross(rA, u)^2 + invMassB + invIB * cross(rB, u)^2
} | javascript | {
"resource": ""
} |
q26145 | FindMaxSeparation | train | function FindMaxSeparation(poly1, xf1, poly2, xf2) {
var count1 = poly1.m_count;
var count2 = poly2.m_count;
var n1s = poly1.m_normals;
var v1s = poly1.m_vertices;
var v2s = poly2.m_vertices;
var xf = Transform.mulTXf(xf2, xf1);
var bestIndex = 0;
var maxSeparation = -Infinity;
for (var i = 0; i < count1; ++i) {
// Get poly1 normal in frame2.
var n = Rot.mulVec2(xf.q, n1s[i]);
var v1 = Transform.mulVec2(xf, v1s[i]);
// Find deepest point for normal i.
var si = Infinity;
for (var j = 0; j < count2; ++j) {
var sij = Vec2.dot(n, v2s[j]) - Vec2.dot(n, v1);
if (sij < si) {
si = sij;
}
}
if (si > maxSeparation) {
maxSeparation = si;
bestIndex = i;
}
}
// used to keep last FindMaxSeparation call values
FindMaxSeparation._maxSeparation = maxSeparation;
FindMaxSeparation._bestIndex = bestIndex;
} | javascript | {
"resource": ""
} |
q26146 | PolygonShape | train | function PolygonShape(vertices) {
if (!(this instanceof PolygonShape)) {
return new PolygonShape(vertices);
}
PolygonShape._super.call(this);
this.m_type = PolygonShape.TYPE;
this.m_radius = Settings.polygonRadius;
this.m_centroid = Vec2.zero();
this.m_vertices = []; // Vec2[Settings.maxPolygonVertices]
this.m_normals = []; // Vec2[Settings.maxPolygonVertices]
this.m_count = 0;
if (vertices && vertices.length) {
this._set(vertices);
}
} | javascript | {
"resource": ""
} |
q26147 | RevoluteJoint | train | function RevoluteJoint(def, bodyA, bodyB, anchor) {
if (!(this instanceof RevoluteJoint)) {
return new RevoluteJoint(def, bodyA, bodyB, anchor);
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = RevoluteJoint.TYPE;
this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero();
this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero();
this.m_referenceAngle = Math.isFinite(def.referenceAngle) ? def.referenceAngle : bodyB.getAngle() - bodyA.getAngle();
this.m_impulse = Vec3();
this.m_motorImpulse = 0.0;
this.m_lowerAngle = def.lowerAngle;
this.m_upperAngle = def.upperAngle;
this.m_maxMotorTorque = def.maxMotorTorque;
this.m_motorSpeed = def.motorSpeed;
this.m_enableLimit = def.enableLimit;
this.m_enableMotor = def.enableMotor;
// Solver temp
this.m_rA; // Vec2
this.m_rB; // Vec2
this.m_localCenterA; // Vec2
this.m_localCenterB; // Vec2
this.m_invMassA; // float
this.m_invMassB; // float
this.m_invIA; // float
this.m_invIB; // float
// effective mass for point-to-point constraint.
this.m_mass = new Mat33();
// effective mass for motor/limit angular constraint.
this.m_motorMass; // float
this.m_limitState = inactiveLimit;
// Point-to-point constraint
// C = p2 - p1
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Motor constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
} | javascript | {
"resource": ""
} |
q26148 | DistanceInput | train | function DistanceInput() {
this.proxyA = new DistanceProxy();
this.proxyB = new DistanceProxy();
this.transformA = null;
this.transformB = null;
this.useRadii = false;
} | javascript | {
"resource": ""
} |
q26149 | Joint | train | function Joint(def, bodyA, bodyB) {
bodyA = def.bodyA || bodyA;
bodyB = def.bodyB || bodyB;
_ASSERT && common.assert(bodyA);
_ASSERT && common.assert(bodyB);
_ASSERT && common.assert(bodyA != bodyB);
this.m_type = 'unknown-joint';
this.m_bodyA = bodyA;
this.m_bodyB = bodyB;
this.m_index = 0;
this.m_collideConnected = !!def.collideConnected;
this.m_prev = null;
this.m_next = null;
this.m_edgeA = new JointEdge();
this.m_edgeB = new JointEdge();
this.m_islandFlag = false;
this.m_userData = def.userData;
} | javascript | {
"resource": ""
} |
q26150 | ChainShape | train | function ChainShape(vertices, loop) {
if (!(this instanceof ChainShape)) {
return new ChainShape(vertices, loop);
}
ChainShape._super.call(this);
this.m_type = ChainShape.TYPE;
this.m_radius = Settings.polygonRadius;
this.m_vertices = [];
this.m_count = 0;
this.m_prevVertex = null;
this.m_nextVertex = null;
this.m_hasPrevVertex = false;
this.m_hasNextVertex = false;
this.m_isLoop = loop;
if (vertices && vertices.length) {
if (loop) {
this._createLoop(vertices);
} else {
this._createChain(vertices);
}
}
} | javascript | {
"resource": ""
} |
q26151 | TOIInput | train | function TOIInput() {
this.proxyA = new DistanceProxy();
this.proxyB = new DistanceProxy();
this.sweepA = new Sweep();
this.sweepB = new Sweep();
this.tMax;
} | javascript | {
"resource": ""
} |
q26152 | BoxShape | train | function BoxShape(hx, hy, center, angle) {
if (!(this instanceof BoxShape)) {
return new BoxShape(hx, hy, center, angle);
}
BoxShape._super.call(this);
this._setAsBox(hx, hy, center, angle);
} | javascript | {
"resource": ""
} |
q26153 | addAsteroids | train | function addAsteroids() {
while (asteroidBodies.length) {
var asteroidBody = asteroidBodies.shift();
world.destroyBody(asteroidBody);
// asteroidBody.uiRemove();
}
for (var i = 0; i < level; i++) {
var shipPosition = shipBody.getPosition();
var x = shipPosition.x;
var y = shipPosition.y;
// Aviod the ship!
while (Math.abs(x - shipPosition.x) < asteroidRadius * 2
&& Math.abs(y - shipPosition.y) < asteroidRadius * 2) {
x = rand(SPACE_WIDTH);
y = rand(SPACE_HEIGHT);
}
var vx = rand(asteroidSpeed);
var vy = rand(asteroidSpeed);
var va = rand(asteroidSpeed);
// Create asteroid body
var asteroidBody = makeAsteroidBody(x, y, vx, vy, va, 0);
asteroidBody.level = 1;
}
} | javascript | {
"resource": ""
} |
q26154 | wrap | train | function wrap(body) {
var p = body.getPosition();
p.x = wrapNumber(p.x, -SPACE_WIDTH / 2, SPACE_WIDTH / 2);
p.y = wrapNumber(p.y, -SPACE_HEIGHT / 2, SPACE_HEIGHT / 2);
body.setPosition(p);
} | javascript | {
"resource": ""
} |
q26155 | DistanceJoint | train | function DistanceJoint(def, bodyA, bodyB, anchorA, anchorB) {
if (!(this instanceof DistanceJoint)) {
return new DistanceJoint(def, bodyA, bodyB, anchorA, anchorB);
}
// order of constructor arguments is changed in v0.2
if (bodyB && anchorA && ('m_type' in anchorA) && ('x' in bodyB) && ('y' in bodyB)) {
var temp = bodyB;
bodyB = anchorA;
anchorA = temp;
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = DistanceJoint.TYPE;
// Solver shared
this.m_localAnchorA = anchorA ? bodyA.getLocalPoint(anchorA) : def.localAnchorA || Vec2.zero();
this.m_localAnchorB = anchorB ? bodyB.getLocalPoint(anchorB) : def.localAnchorB || Vec2.zero();
this.m_length = Math.isFinite(def.length) ? def.length :
Vec2.distance(bodyA.getWorldPoint(this.m_localAnchorA), bodyB.getWorldPoint(this.m_localAnchorB));
this.m_frequencyHz = def.frequencyHz;
this.m_dampingRatio = def.dampingRatio;
this.m_impulse = 0.0;
this.m_gamma = 0.0;
this.m_bias = 0.0;
// Solver temp
this.m_u; // Vec2
this.m_rA; // Vec2
this.m_rB; // Vec2
this.m_localCenterA; // Vec2
this.m_localCenterB; // Vec2
this.m_invMassA;
this.m_invMassB;
this.m_invIA;
this.m_invIB;
this.m_mass;
// 1-D constrained system
// m (v2 - v1) = lambda
// v2 + (beta/h) * x1 + gamma * lambda = 0, gamma has units of inverse mass.
// x2 = x1 + h * v2
// 1-D mass-damper-spring system
// m (v2 - v1) + h * d * v2 + h * k *
// C = norm(p2 - p1) - L
// u = (p2 - p1) / norm(p2 - p1)
// Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1))
// J = [-u -cross(r1, u) u cross(r2, u)]
// K = J * invM * JT
// = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2
} | javascript | {
"resource": ""
} |
q26156 | FrictionJoint | train | function FrictionJoint(def, bodyA, bodyB, anchor) {
if (!(this instanceof FrictionJoint)) {
return new FrictionJoint(def, bodyA, bodyB, anchor);
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = FrictionJoint.TYPE;
this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero();
this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero();
// Solver shared
this.m_linearImpulse = Vec2.zero();
this.m_angularImpulse = 0.0;
this.m_maxForce = def.maxForce;
this.m_maxTorque = def.maxTorque;
// Solver temp
this.m_rA; // Vec2
this.m_rB; // Vec2
this.m_localCenterA; // Vec2
this.m_localCenterB; // Vec2
this.m_invMassA; // float
this.m_invMassB; // float
this.m_invIA; // float
this.m_invIB; // float
this.m_linearMass; // Mat22
this.m_angularMass; // float
// Point-to-point constraint
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
} | javascript | {
"resource": ""
} |
q26157 | MouseJoint | train | function MouseJoint(def, bodyA, bodyB, target) {
if (!(this instanceof MouseJoint)) {
return new MouseJoint(def, bodyA, bodyB, target);
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = MouseJoint.TYPE;
_ASSERT && common.assert(Math.isFinite(def.maxForce) && def.maxForce >= 0.0);
_ASSERT && common.assert(Math.isFinite(def.frequencyHz) && def.frequencyHz >= 0.0);
_ASSERT && common.assert(Math.isFinite(def.dampingRatio) && def.dampingRatio >= 0.0);
this.m_targetA = target ? Vec2.clone(target) : def.target || Vec2.zero();
this.m_localAnchorB = Transform.mulTVec2(bodyB.getTransform(), this.m_targetA);
this.m_maxForce = def.maxForce;
this.m_impulse = Vec2.zero();
this.m_frequencyHz = def.frequencyHz;
this.m_dampingRatio = def.dampingRatio;
this.m_beta = 0.0;
this.m_gamma = 0.0;
// Solver temp
this.m_rB = Vec2.zero();
this.m_localCenterB = Vec2.zero();
this.m_invMassB = 0.0;
this.m_invIB = 0.0;
this.mass = new Mat22()
this.m_C = Vec2.zero();
// p = attached point, m = mouse point
// C = p - m
// Cdot = v
// = v + cross(w, r)
// J = [I r_skew]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
} | javascript | {
"resource": ""
} |
q26158 | FixtureProxy | train | function FixtureProxy(fixture, childIndex) {
this.aabb = new AABB();
this.fixture = fixture;
this.childIndex = childIndex;
this.proxyId;
} | javascript | {
"resource": ""
} |
q26159 | Fixture | train | function Fixture(body, shape, def) {
if (shape.shape) {
def = shape;
shape = shape.shape;
} else if (typeof def === 'number') {
def = {density : def};
}
def = options(def, FixtureDef);
this.m_body = body;
this.m_friction = def.friction;
this.m_restitution = def.restitution;
this.m_density = def.density;
this.m_isSensor = def.isSensor;
this.m_filterGroupIndex = def.filterGroupIndex;
this.m_filterCategoryBits = def.filterCategoryBits;
this.m_filterMaskBits = def.filterMaskBits;
// TODO validate shape
this.m_shape = shape; //.clone();
this.m_next = null;
this.m_proxies = [];
this.m_proxyCount = 0;
var childCount = this.m_shape.getChildCount();
for (var i = 0; i < childCount; ++i) {
this.m_proxies[i] = new FixtureProxy(this, i);
}
this.m_userData = def.userData;
} | javascript | {
"resource": ""
} |
q26160 | ReferenceFace | train | function ReferenceFace() {
this.i1, this.i2; // int
this.v1, this.v2; // v
this.normal = Vec2.zero();
this.sideNormal1 = Vec2.zero();
this.sideOffset1; // float
this.sideNormal2 = Vec2.zero();
this.sideOffset2; // float
} | javascript | {
"resource": ""
} |
q26161 | TreeNode | train | function TreeNode(id) {
this.id = id;
this.aabb = new AABB();
this.userData = null;
this.parent = null;
this.child1 = null;
this.child2 = null;
this.height = -1;
this.toString = function() {
return this.id + ": " + this.userData;
}
} | javascript | {
"resource": ""
} |
q26162 | train | function(name) {
name = (name || '').toLowerCase();
if (name in elementMap)
return this.getMapping(name);
if (this.isInlineLevel(name))
return 'span';
return 'div';
} | javascript | {
"resource": ""
} | |
q26163 | train | function(name, collection) {
if (!elementTypes[collection])
elementTypes[collection] = [];
var col = this.getCollection(collection);
if (!~col.indexOf(name)) {
col.push(name);
}
} | javascript | {
"resource": ""
} | |
q26164 | train | function(name, collection) {
if (collection in elementTypes) {
elementTypes[collection] = utils.without(this.getCollection(collection), name);
}
} | javascript | {
"resource": ""
} | |
q26165 | addComments | train | function addComments(node, templateBefore, templateAfter) {
// check if comments should be added
var trigger = prefs.get('filter.commentTrigger');
if (trigger != '*') {
var shouldAdd = utils.find(trigger.split(','), function(name) {
return !!node.attribute(utils.trim(name));
});
if (!shouldAdd) {
return;
}
}
var ctx = {
node: node,
name: node.name(),
padding: node.parent ? node.parent.padding : '',
attr: function(name, before, after) {
var attr = node.attribute(name);
if (attr) {
return (before || '') + attr + (after || '');
}
return '';
}
};
var nodeBefore = templateBefore ? templateBefore(ctx) : '';
var nodeAfter = templateAfter ? templateAfter(ctx) : '';
node.start = node.start.replace(/</, nodeBefore + '<');
node.end = node.end.replace(/>/, '>' + nodeAfter);
} | javascript | {
"resource": ""
} |
q26166 | resolveNodeNames | train | function resolveNodeNames(tree) {
tree.children.forEach(function(node) {
if (node.hasImplicitName() || node.data('forceNameResolving')) {
node._name = tagName.resolve(node.parent.name());
node.data('nameResolved', true);
}
resolveNodeNames(node);
});
return tree;
} | javascript | {
"resource": ""
} |
q26167 | isSingleProperty | train | function isSingleProperty(snippet) {
snippet = utils.trim(snippet);
// check if it doesn't contain a comment and a newline
if (/\/\*|\n|\r/.test(snippet)) {
return false;
}
// check if it's a valid snippet definition
if (!/^[a-z0-9\-]+\s*\:/i.test(snippet)) {
return false;
}
return snippet.replace(/\$\{.+?\}/g, '').split(':').length == 2;
} | javascript | {
"resource": ""
} |
q26168 | normalizeValue | train | function normalizeValue(value) {
if (value.charAt(0) == '-' && !/^\-[\.\d]/.test(value)) {
value = value.replace(/^\-+/, '');
}
var ch = value.charAt(0);
if (ch == '#') {
return normalizeHexColor(value);
}
if (ch == '$') {
return utils.escapeText(value);
}
return getKeyword(value);
} | javascript | {
"resource": ""
} |
q26169 | toRgba | train | function toRgba(color, opacity) {
var r = parseInt(color.substr(0, 2), 16);
var g = parseInt(color.substr(2, 2), 16);
var b = parseInt(color.substr(4, 2), 16);
return 'rgba(' + [r, g, b, opacity].join(', ') + ')';
} | javascript | {
"resource": ""
} |
q26170 | hasPrefix | train | function hasPrefix(property, prefix) {
var info = vendorPrefixes[prefix];
if (!info)
info = utils.find(vendorPrefixes, function(data) {
return data.prefix == prefix;
});
return info && info.supports(property);
} | javascript | {
"resource": ""
} |
q26171 | findVendorPrefixes | train | function findVendorPrefixes(property) {
var prefixes = ciu.resolvePrefixes(property);
if (!prefixes) {
// Can I Use database is disabled or prefixes are not
// available for this property
prefixes = [];
Object.keys(vendorPrefixes).forEach(function(key) {
if (hasPrefix(property, key)) {
prefixes.push(vendorPrefixes[key].prefix);
}
});
if (!prefixes.length) {
prefixes = null;
}
}
return prefixes;
} | javascript | {
"resource": ""
} |
q26172 | findInternalPrefixes | train | function findInternalPrefixes(property, noAutofill) {
var result = [];
var prefixes = findVendorPrefixes(property);
if (prefixes) {
var prefixMap = {};
Object.keys(vendorPrefixes).forEach(function(key) {
prefixMap[vendorPrefixes[key].prefix] = key;
});
result = prefixes.map(function(prefix) {
return prefixMap[prefix];
});
}
if (!result.length && !noAutofill) {
// add all non-obsolete prefixes
Object.keys(vendorPrefixes).forEach(function(prefix) {
if (!vendorPrefixes[prefix].obsolete) {
result.push(prefix);
}
});
}
return result;
} | javascript | {
"resource": ""
} |
q26173 | formatProperty | train | function formatProperty(property, syntax) {
var ix = property.indexOf(':');
property = property.substring(0, ix).replace(/\s+$/, '')
+ getSyntaxPreference('valueSeparator', syntax)
+ utils.trim(property.substring(ix + 1));
return property.replace(/\s*;\s*$/, getSyntaxPreference('propertyEnd', syntax));
} | javascript | {
"resource": ""
} |
q26174 | resolvePrefixedValues | train | function resolvePrefixedValues(snippetObj, isImportant, syntax) {
var prefixes = [];
var lookup = {};
var parts = cssEditTree.findParts(snippetObj.value);
parts.reverse();
parts.forEach(function(p) {
var partValue = p.substring(snippetObj.value);
(findVendorPrefixes(partValue) || []).forEach(function(prefix) {
if (!lookup[prefix]) {
lookup[prefix] = snippetObj.value;
prefixes.push(prefix);
}
lookup[prefix] = utils.replaceSubstring(lookup[prefix], '-' + prefix + '-' + partValue, p);
});
});
return prefixes.map(function(prefix) {
return transformSnippet(snippetObj.name + ':' + lookup[prefix], isImportant, syntax);
});
} | javascript | {
"resource": ""
} |
q26175 | train | function(abbr) {
if (abbr.charAt(0) != '-') {
return {
property: abbr,
prefixes: null
};
}
// abbreviation may either contain sequence of one-character prefixes
// or just dash, meaning that user wants to produce all possible
// prefixed properties
var i = 1, il = abbr.length, ch;
var prefixes = [];
while (i < il) {
ch = abbr.charAt(i);
if (ch == '-') {
// end-sequence character found, stop searching
i++;
break;
}
if (ch in vendorPrefixes) {
prefixes.push(ch);
} else {
// no prefix found, meaning user want to produce all
// vendor-prefixed properties
prefixes.length = 0;
i = 1;
break;
}
i++;
}
// reached end of abbreviation and no property name left
if (i == il -1) {
i = 1;
prefixes.length = 1;
}
return {
property: abbr.substring(i),
prefixes: prefixes.length ? prefixes : 'all'
};
} | javascript | {
"resource": ""
} | |
q26176 | train | function(abbr, syntax) {
syntax = syntax || 'css';
var i = 0, il = abbr.length, value = '', ch;
while (i < il) {
ch = abbr.charAt(i);
if (isNumeric(ch) || ch == '#' || ch == '$' || (ch == '-' && isNumeric(abbr.charAt(i + 1)))) {
value = abbr.substring(i);
break;
}
i++;
}
// try to find keywords in abbreviation
var property = abbr.substring(0, abbr.length - value.length);
var keywords = [];
// try to extract some commonly-used properties
while (~property.indexOf('-') && !resources.findSnippet(syntax, property)) {
var parts = property.split('-');
var lastPart = parts.pop();
if (!isValidKeyword(lastPart)) {
break;
}
keywords.unshift(lastPart);
property = parts.join('-');
}
return keywords.join('-') + value;
} | javascript | {
"resource": ""
} | |
q26177 | train | function(abbr) {
// search for value start
var abbrValues = this.findValuesInAbbreviation(abbr);
if (!abbrValues) {
return {
property: abbr,
values: null
};
}
return {
property: abbr.substring(0, abbr.length - abbrValues.length).replace(/-$/, ''),
values: this.parseValues(abbrValues)
};
} | javascript | {
"resource": ""
} | |
q26178 | train | function(value, property) {
property = (property || '').toLowerCase();
var unitlessProps = prefs.getArray('css.unitlessProperties');
return value.replace(/^(\-?[0-9\.]+)([a-z]*)$/, function(str, val, unit) {
if (!unit && (val == '0' || ~unitlessProps.indexOf(property)))
return val;
if (!unit)
return val.replace(/\.$/, '') + prefs.get(~val.indexOf('.') ? 'css.floatUnit' : 'css.intUnit');
return val + getUnit(unit);
});
} | javascript | {
"resource": ""
} | |
q26179 | train | function() {
if (this._name === null) {
var range = this.nameRange();
if (range) {
this._name = range.substring(this.source());
}
}
return this._name;
} | javascript | {
"resource": ""
} | |
q26180 | train | function() {
var out = [];
if (this.parent) {
// add current range if it is not root node
out.push(this.range);
}
this.children.forEach(function(child) {
out = out.concat(child.allRanges());
});
return out;
} | javascript | {
"resource": ""
} | |
q26181 | train | function(content, pos, sanitize) {
if (sanitize) {
content = this.sanitize(content);
}
var stream = stringStream(content);
stream.start = stream.pos = pos;
var stack = [], ranges = [];
var ch;
while (ch = stream.next()) {
if (ch == '{') {
stack.push(stream.pos - 1);
} else if (ch == '}') {
if (!stack.length) {
throw 'Invalid source structure (check for curly braces)';
}
ranges.push(range.create2(stack.pop(), stream.pos));
if (!stack.length) {
return ranges;
}
} else {
stream.skipQuoted();
}
}
return ranges;
} | javascript | {
"resource": ""
} | |
q26182 | train | function(content, pos, sanitize) {
if (sanitize) {
content = this.sanitize(content);
}
var skipString = function() {
var quote = content.charAt(pos);
if (quote == '"' || quote == "'") {
while (--pos >= 0) {
if (content.charAt(pos) == quote && content.charAt(pos - 1) != '\\') {
break;
}
}
return true;
}
return false;
};
// find CSS selector
var ch;
var endPos = pos;
while (--pos >= 0) {
if (skipString()) continue;
ch = content.charAt(pos);
if (ch == ')') {
// looks like it’s a preprocessor thing,
// most likely a mixin arguments list, e.g.
// .mixin (@arg1; @arg2) {...}
while (--pos >= 0) {
if (skipString()) continue;
if (content.charAt(pos) == '(') {
break;
}
}
continue;
}
if (ch == '{' || ch == '}' || ch == ';') {
pos++;
break;
}
}
if (pos < 0) {
pos = 0;
}
var selector = content.substring(pos, endPos);
// trim whitespace from matched selector
var m = selector.replace(reSpace, ' ').match(reSpaceTrim);
if (m) {
pos += m[1].length;
endPos -= m[2].length;
}
return range.create2(pos, endPos);
} | javascript | {
"resource": ""
} | |
q26183 | train | function(content, pos, isBackward) {
// possible case: editor reported that current syntax is
// CSS, but it’s actually a HTML document (either `style` tag or attribute)
var offset = 0;
var subrange = this.styleTagRange(content, pos);
if (subrange) {
offset = subrange.start;
pos -= subrange.start;
content = subrange.substring(content);
}
var rules = this.findAllRules(content);
var ctxRule = this.matchEnclosingRule(rules, pos);
if (ctxRule) {
return ctxRule.shift(offset);
}
for (var i = 0, il = rules.length; i < il; i++) {
if (rules[i].start > pos) {
return rules[isBackward && i > 0 ? i - 1 : i].shift(offset);
}
}
} | javascript | {
"resource": ""
} | |
q26184 | train | function(range, ctx) {
while (ctx && ctx.range) {
if (ctx.range.contains(range)) {
return ctx.addChild(range);
}
ctx = ctx.parent;
}
// if we are here then given range is a top-level section
return root.addChild(range);
} | javascript | {
"resource": ""
} | |
q26185 | train | function(rule) {
var offset = rule.valueRange(true).start;
var nestedSections = this.findAllRules(rule.valueRange().substring(rule.source));
nestedSections.forEach(function(section) {
section.start += offset;
section.end += offset;
section._selectorEnd += offset;
section._contentStart += offset;
});
return nestedSections;
} | javascript | {
"resource": ""
} | |
q26186 | train | function(name, factory) {
var that = this;
factories[name] = function() {
var elem = factory.apply(that, arguments);
if (elem)
elem.type = name;
return elem;
};
} | javascript | {
"resource": ""
} | |
q26187 | train | function(name) {
var args = [].slice.call(arguments, 1);
var factory = this.get(name);
return factory ? factory.apply(this, args) : null;
} | javascript | {
"resource": ""
} | |
q26188 | train | function(name, value, description) {
var prefs = name;
if (typeof name === 'string') {
prefs = {};
prefs[name] = {
value: value,
description: description
};
}
Object.keys(prefs).forEach(function(k) {
var v = prefs[k];
defaults[k] = isValueObj(v) ? v : {value: v};
});
} | javascript | {
"resource": ""
} | |
q26189 | train | function(name) {
var val = this.get(name);
if (typeof val === 'undefined' || val === null || val === '') {
return null;
}
val = val.split(',').map(utils.trim);
if (!val.length) {
return null;
}
return val;
} | javascript | {
"resource": ""
} | |
q26190 | train | function(name) {
var result = {};
this.getArray(name).forEach(function(val) {
var parts = val.split(':');
result[parts[0]] = parts[1];
});
return result;
} | javascript | {
"resource": ""
} | |
q26191 | train | function() {
return Object.keys(defaults).sort().map(function(key) {
return {
name: key,
value: this.get(key),
type: typeof defaults[key].value,
description: defaults[key].description
};
}, this);
} | javascript | {
"resource": ""
} | |
q26192 | train | function(json) {
Object.keys(json).forEach(function(key) {
this.set(key, json[key]);
}, this);
} | javascript | {
"resource": ""
} | |
q26193 | insertPastedContent | train | function insertPastedContent(node, content, overwrite) {
var nodesWithPlaceholders = node.findAll(function(item) {
return hasOutputPlaceholder(item);
});
if (hasOutputPlaceholder(node))
nodesWithPlaceholders.unshift(node);
if (nodesWithPlaceholders.length) {
nodesWithPlaceholders.forEach(function(item) {
item.content = replaceOutputPlaceholders(item.content, content);
item._attributes.forEach(function(attr) {
attr.value = replaceOutputPlaceholders(attr.value, content);
});
});
} else {
// on output placeholders in subtree, insert content in the deepest
// child node
var deepest = node.deepestChild() || node;
if (overwrite) {
deepest.content = content;
} else {
deepest.content = abbrUtils.insertChildContent(deepest.content, content);
}
}
} | javascript | {
"resource": ""
} |
q26194 | shouldAddLineBreak | train | function shouldAddLineBreak(node, profile) {
if (profile.tag_nl === true || abbrUtils.isBlock(node))
return true;
if (!node.parent || !profile.inline_break)
return false;
// check if there are required amount of adjacent inline element
return shouldFormatInline(node.parent, profile);
} | javascript | {
"resource": ""
} |
q26195 | shouldBreakInsideInline | train | function shouldBreakInsideInline(node, profile) {
var hasBlockElems = node.children.some(function(child) {
if (abbrUtils.isSnippet(child))
return false;
return !abbrUtils.isInline(child);
});
if (!hasBlockElems) {
return shouldFormatInline(node, profile);
}
return true;
} | javascript | {
"resource": ""
} |
q26196 | intLength | train | function intLength(num) {
num = num.replace(/^\-/, '');
if (~num.indexOf('.')) {
return num.split('.')[0].length;
}
return num.length;
} | javascript | {
"resource": ""
} |
q26197 | consumeSingleProperty | train | function consumeSingleProperty(it, text) {
var name, value, end;
var token = it.current();
if (!token) {
return null;
}
// skip whitespace
var ws = {'white': 1, 'line': 1, 'comment': 1};
while ((token = it.current())) {
if (!(token.type in ws)) {
break;
}
it.next();
}
if (!it.hasNext()) {
return null;
}
// consume property name
token = it.current();
name = range(token.start, token.value);
var isAtProperty = token.value.charAt(0) == '@';
while (token = it.next()) {
name.end = token.end;
if (token.type == ':' || token.type == 'white') {
name.end = token.start;
it.next();
if (token.type == ':' || isAtProperty) {
// XXX I really ashame of this hardcode, but I need
// to stop parsing if this is an SCSS mixin call,
// for example: @include border-radius(10px)
break;
}
} else if (token.type == ';' || token.type == 'line') {
// there’s no value, looks like a mixin
// or a special use case:
// user is writing a new property or abbreviation
name.end = token.start;
value = range(token.start, 0);
it.next();
break;
}
}
token = it.current();
if (!value && token) {
if (token.type == 'line') {
lastNewline = token;
}
// consume value
value = range(token.start, token.value);
var lastNewline;
while ((token = it.next())) {
value.end = token.end;
if (token.type == 'line') {
lastNewline = token;
} else if (token.type == '}' || token.type == ';') {
value.end = token.start;
if (token.type == ';') {
end = range(token.start, token.value);
}
it.next();
break;
} else if (token.type == ':' && lastNewline) {
// A special case:
// user is writing a value before existing
// property, but didn’t inserted closing semi-colon.
// In this case, limit value range to previous
// newline
value.end = lastNewline.start;
it._i = it.tokens.indexOf(lastNewline);
break;
}
}
}
if (!value) {
value = range(name.end, 0);
}
return {
name: trimWhitespaceInRange(name, text),
value: trimWhitespaceInRange(value, text, WHITESPACE_REMOVE_FROM_START | (end ? WHITESPACE_REMOVE_FROM_END : 0)),
end: end || range(value.end, 0)
};
} | javascript | {
"resource": ""
} |
q26198 | findParts | train | function findParts(str) {
/** @type StringStream */
var stream = stringStream.create(str);
var ch;
var result = [];
var sep = /[\s\u00a0,;]/;
var add = function() {
stream.next();
result.push(range(stream.start, stream.current()));
stream.start = stream.pos;
};
// skip whitespace
stream.eatSpace();
stream.start = stream.pos;
while ((ch = stream.next())) {
if (ch == '"' || ch == "'") {
stream.next();
if (!stream.skipTo(ch)) break;
add();
} else if (ch == '(') {
// function found, may have nested function
stream.backUp(1);
if (!stream.skipToPair('(', ')')) break;
stream.backUp(1);
add();
} else {
if (sep.test(ch)) {
result.push(range(stream.start, stream.current().length - 1));
stream.eatWhile(sep);
stream.start = stream.pos;
}
}
}
add();
return utils.unique(result.filter(function(item) {
return !!item.length();
}));
} | javascript | {
"resource": ""
} |
q26199 | consumeProperties | train | function consumeProperties(node, source, offset) {
var list = extractPropertiesFromSource(source, offset);
list.forEach(function(property) {
node._children.push(new CSSEditElement(node,
editTree.createToken(property.name.start, property.nameText),
editTree.createToken(property.value.start, property.valueText),
editTree.createToken(property.end.start, property.endText)
));
});
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.