_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q51600
|
createSetHeader
|
train
|
function createSetHeader (options) {
// response time digits
var digits = options.digits !== undefined
? options.digits
: 3
// header name
var header = options.header || 'X-Response-Time'
// display suffix
var suffix = options.suffix !== undefined
? Boolean(options.suffix)
: true
return function setResponseHeader (req, res, time) {
if (res.getHeader(header)) {
return
}
var val = time.toFixed(digits)
if (suffix) {
val += 'ms'
}
res.setHeader(header, val)
}
}
|
javascript
|
{
"resource": ""
}
|
q51601
|
translateElement
|
train
|
function translateElement(element) {
var l10n = getL10nAttributes(element);
if (!l10n.id)
return;
// get the related l10n object
var data = getL10nData(l10n.id, l10n.args);
if (!data) {
console.warn('#' + l10n.id + ' is undefined.');
return;
}
// translate element (TODO: security checks?)
if (data[gTextProp]) { // XXX
if (getChildElementCount(element) === 0) {
element[gTextProp] = data[gTextProp];
} else {
// this element has element children: replace the content of the first
// (non-empty) child textNode and clear other child textNodes
var children = element.childNodes;
var found = false;
for (var i = 0, l = children.length; i < l; i++) {
if (children[i].nodeType === 3 && /\S/.test(children[i].nodeValue)) {
if (found) {
children[i].nodeValue = '';
} else {
children[i].nodeValue = data[gTextProp];
found = true;
}
}
}
// if no (non-empty) textNode is found, insert a textNode before the
// first element child.
if (!found) {
var textNode = document.createTextNode(data[gTextProp]);
element.insertBefore(textNode, element.firstChild);
}
}
delete data[gTextProp];
}
for (var k in data) {
element[k] = data[k];
}
}
|
javascript
|
{
"resource": ""
}
|
q51602
|
getChildElementCount
|
train
|
function getChildElementCount(element) {
if (element.children) {
return element.children.length;
}
if (typeof element.childElementCount !== 'undefined') {
return element.childElementCount;
}
var count = 0;
for (var i = 0; i < element.childNodes.length; i++) {
count += element.nodeType === 1 ? 1 : 0;
}
return count;
}
|
javascript
|
{
"resource": ""
}
|
q51603
|
translateFragment
|
train
|
function translateFragment(element) {
element = element || document.documentElement;
// check all translatable children (= w/ a `data-l10n-id' attribute)
var children = getTranslatableChildren(element);
var elementCount = children.length;
for (var i = 0; i < elementCount; i++) {
translateElement(children[i]);
}
// translate element itself if necessary
translateElement(element);
}
|
javascript
|
{
"resource": ""
}
|
q51604
|
preferencesSet
|
train
|
function preferencesSet(name, value) {
return this.initializedPromise.then(function () {
if (this.defaults[name] === undefined) {
throw new Error('preferencesSet: \'' + name + '\' is undefined.');
} else if (value === undefined) {
throw new Error('preferencesSet: no value is specified.');
}
var valueType = typeof value;
var defaultType = typeof this.defaults[name];
if (valueType !== defaultType) {
if (valueType === 'number' && defaultType === 'string') {
value = value.toString();
} else {
throw new Error('Preferences_set: \'' + value + '\' is a \"' + valueType + '\", expected \"' + defaultType + '\".');
}
} else {
if (valueType === 'number' && (value | 0) !== value) {
throw new Error('Preferences_set: \'' + value + '\' must be an \"integer\".');
}
}
this.prefs[name] = value;
return this._writeToStorage(this.prefs);
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q51605
|
PDFOutlineViewer_addToggleButton
|
train
|
function PDFOutlineViewer_addToggleButton(div) {
var toggler = document.createElement('div');
toggler.className = 'outlineItemToggler';
toggler.onclick = function (event) {
event.stopPropagation();
toggler.classList.toggle('outlineItemsHidden');
if (event.shiftKey) {
var shouldShowAll = !toggler.classList.contains('outlineItemsHidden');
this._toggleOutlineItem(div, shouldShowAll);
}
}.bind(this);
div.insertBefore(toggler, div.firstChild);
}
|
javascript
|
{
"resource": ""
}
|
q51606
|
PDFOutlineViewer_toggleOutlineItem
|
train
|
function PDFOutlineViewer_toggleOutlineItem(root, show) {
this.lastToggleIsShow = show;
var togglers = root.querySelectorAll('.outlineItemToggler');
for (var i = 0, ii = togglers.length; i < ii; ++i) {
togglers[i].classList[show ? 'remove' : 'add']('outlineItemsHidden');
}
}
|
javascript
|
{
"resource": ""
}
|
q51607
|
PDFDocumentProperties_open
|
train
|
function PDFDocumentProperties_open() {
Promise.all([
OverlayManager.open(this.overlayName),
this.dataAvailablePromise
]).then(function () {
this._getProperties();
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q51608
|
PDFFindController_updateMatchPosition
|
train
|
function PDFFindController_updateMatchPosition(pageIndex, index, elements, beginIdx) {
if (this.selected.matchIdx === index && this.selected.pageIdx === pageIndex) {
var spot = {
top: FIND_SCROLL_OFFSET_TOP,
left: FIND_SCROLL_OFFSET_LEFT
};
scrollIntoView(elements[beginIdx], spot, /* skipOverflowHiddenElements = */
true);
}
}
|
javascript
|
{
"resource": ""
}
|
q51609
|
train
|
function () {
return this._pages.map(function (pageView) {
var viewport = pageView.pdfPage.getViewport(1);
return {
width: viewport.width,
height: viewport.height
};
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51610
|
pdfViewClose
|
train
|
function pdfViewClose() {
var errorWrapper = this.appConfig.errorWrapper.container;
errorWrapper.setAttribute('hidden', 'true');
if (!this.pdfLoadingTask) {
return Promise.resolve();
}
var promise = this.pdfLoadingTask.destroy();
this.pdfLoadingTask = null;
if (this.pdfDocument) {
this.pdfDocument = null;
this.pdfThumbnailViewer.setDocument(null);
this.pdfViewer.setDocument(null);
this.pdfLinkService.setDocument(null, null);
}
this.store = null;
this.isInitialViewSet = false;
this.pdfSidebar.reset();
this.pdfOutlineViewer.reset();
this.pdfAttachmentViewer.reset();
this.findController.reset();
this.findBar.reset();
if (typeof PDFBug !== 'undefined') {
PDFBug.cleanup();
}
return promise;
}
|
javascript
|
{
"resource": ""
}
|
q51611
|
pdfViewOpen
|
train
|
function pdfViewOpen(file, args) {
if (arguments.length > 2 || typeof args === 'number') {
return Promise.reject(new Error('Call of open() with obsolete signature.'));
}
if (this.pdfLoadingTask) {
// We need to destroy already opened document.
return this.close().then(function () {
// Reload the preferences if a document was previously opened.
Preferences.reload();
// ... and repeat the open() call.
return this.open(file, args);
}.bind(this));
}
var parameters = Object.create(null), scale;
if (typeof file === 'string') {
// URL
this.setTitleUsingUrl(file);
parameters.url = file;
} else if (file && 'byteLength' in file) {
// ArrayBuffer
parameters.data = file;
} else if (file.url && file.originalUrl) {
this.setTitleUsingUrl(file.originalUrl);
parameters.url = file.url;
}
if (args) {
for (var prop in args) {
parameters[prop] = args[prop];
}
if (args.scale) {
scale = args.scale;
}
if (args.length) {
this.pdfDocumentProperties.setFileSize(args.length);
}
}
var self = this;
self.downloadComplete = false;
var loadingTask = pdfjsLib.getDocument(parameters);
this.pdfLoadingTask = loadingTask;
loadingTask.onPassword = function passwordNeeded(updateCallback, reason) {
self.passwordPrompt.setUpdateCallback(updateCallback, reason);
self.passwordPrompt.open();
};
loadingTask.onProgress = function getDocumentProgress(progressData) {
self.progress(progressData.loaded / progressData.total);
};
// Listen for unsupported features to trigger the fallback UI.
loadingTask.onUnsupportedFeature = this.fallback.bind(this);
return loadingTask.promise.then(function getDocumentCallback(pdfDocument) {
self.load(pdfDocument, scale);
}, function getDocumentError(exception) {
var message = exception && exception.message;
var loadingErrorMessage = mozL10n.get('loading_error', null, 'An error occurred while loading the PDF.');
if (exception instanceof pdfjsLib.InvalidPDFException) {
// change error message also for other builds
loadingErrorMessage = mozL10n.get('invalid_file_error', null, 'Invalid or corrupted PDF file.');
} else if (exception instanceof pdfjsLib.MissingPDFException) {
// special message for missing PDF's
loadingErrorMessage = mozL10n.get('missing_file_error', null, 'Missing PDF file.');
} else if (exception instanceof pdfjsLib.UnexpectedResponseException) {
loadingErrorMessage = mozL10n.get('unexpected_response_error', null, 'Unexpected server response.');
}
var moreInfo = { message: message };
self.error(loadingErrorMessage, moreInfo);
throw new Error(loadingErrorMessage);
});
}
|
javascript
|
{
"resource": ""
}
|
q51612
|
pdfViewError
|
train
|
function pdfViewError(message, moreInfo) {
var moreInfoText = mozL10n.get('error_version_info', {
version: pdfjsLib.version || '?',
build: pdfjsLib.build || '?'
}, 'PDF.js v{{version}} (build: {{build}})') + '\n';
if (moreInfo) {
moreInfoText += mozL10n.get('error_message', { message: moreInfo.message }, 'Message: {{message}}');
if (moreInfo.stack) {
moreInfoText += '\n' + mozL10n.get('error_stack', { stack: moreInfo.stack }, 'Stack: {{stack}}');
} else {
if (moreInfo.filename) {
moreInfoText += '\n' + mozL10n.get('error_file', { file: moreInfo.filename }, 'File: {{file}}');
}
if (moreInfo.lineNumber) {
moreInfoText += '\n' + mozL10n.get('error_line', { line: moreInfo.lineNumber }, 'Line: {{line}}');
}
}
}
var errorWrapperConfig = this.appConfig.errorWrapper;
var errorWrapper = errorWrapperConfig.container;
errorWrapper.removeAttribute('hidden');
var errorMessage = errorWrapperConfig.errorMessage;
errorMessage.textContent = message;
var closeButton = errorWrapperConfig.closeButton;
closeButton.onclick = function () {
errorWrapper.setAttribute('hidden', 'true');
};
var errorMoreInfo = errorWrapperConfig.errorMoreInfo;
var moreInfoButton = errorWrapperConfig.moreInfoButton;
var lessInfoButton = errorWrapperConfig.lessInfoButton;
moreInfoButton.onclick = function () {
errorMoreInfo.removeAttribute('hidden');
moreInfoButton.setAttribute('hidden', 'true');
lessInfoButton.removeAttribute('hidden');
errorMoreInfo.style.height = errorMoreInfo.scrollHeight + 'px';
};
lessInfoButton.onclick = function () {
errorMoreInfo.setAttribute('hidden', 'true');
moreInfoButton.removeAttribute('hidden');
lessInfoButton.setAttribute('hidden', 'true');
};
moreInfoButton.oncontextmenu = noContextMenuHandler;
lessInfoButton.oncontextmenu = noContextMenuHandler;
closeButton.oncontextmenu = noContextMenuHandler;
moreInfoButton.removeAttribute('hidden');
lessInfoButton.setAttribute('hidden', 'true');
errorMoreInfo.value = moreInfoText;
}
|
javascript
|
{
"resource": ""
}
|
q51613
|
lint
|
train
|
function lint() {
return gulp.src(srcFiles)
.pipe(gulpTslint({
program: tslint.Linter.createProgram("./tsconfig.json"),
formatter: "stylish"
}))
.pipe(gulpTslint.report({
emitError: !watching
}))
}
|
javascript
|
{
"resource": ""
}
|
q51614
|
_attr
|
train
|
function _attr(el, attr, attrs, i) {
var result = (el.getAttribute && el.getAttribute(attr)) || 0;
if (!result) {
attrs = el.attributes;
for (i = 0; i < attrs.length; ++i) {
if (attrs[i].nodeName === attr) {
return attrs[i].nodeValue;
}
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q51615
|
_getLanguageForBlock
|
train
|
function _getLanguageForBlock(block) {
// if this doesn't have a language but the parent does then use that
// this means if for example you have: <pre data-language="php">
// with a bunch of <code> blocks inside then you do not have
// to specify the language for each block
var language = _attr(block, 'data-language') || _attr(block.parentNode, 'data-language');
// this adds support for specifying language via a css class
// you can use the Google Code Prettify style: <pre class="lang-php">
// or the HTML5 style: <pre><code class="language-php">
if (!language) {
var pattern = /\blang(?:uage)?-(\w+)/,
match = block.className.match(pattern) || block.parentNode.className.match(pattern);
if (match) {
language = match[1];
}
}
return language;
}
|
javascript
|
{
"resource": ""
}
|
q51616
|
_intersects
|
train
|
function _intersects(start1, end1, start2, end2) {
if (start2 >= start1 && start2 < end1) {
return true;
}
return end2 > start1 && end2 < end1;
}
|
javascript
|
{
"resource": ""
}
|
q51617
|
_hasCompleteOverlap
|
train
|
function _hasCompleteOverlap(start1, end1, start2, end2) {
// if the starting and end positions are exactly the same
// then the first one should stay and this one should be ignored
if (start2 == start1 && end2 == end1) {
return false;
}
return start2 <= start1 && end2 >= end1;
}
|
javascript
|
{
"resource": ""
}
|
q51618
|
_matchIsInsideOtherMatch
|
train
|
function _matchIsInsideOtherMatch(start, end) {
for (var key in replacement_positions[CURRENT_LEVEL]) {
key = parseInt(key, 10);
// if this block completely overlaps with another block
// then we should remove the other block and return false
if (_hasCompleteOverlap(key, replacement_positions[CURRENT_LEVEL][key], start, end)) {
delete replacement_positions[CURRENT_LEVEL][key];
delete replacements[CURRENT_LEVEL][key];
}
if (_intersects(key, replacement_positions[CURRENT_LEVEL][key], start, end)) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q51619
|
_indexOfGroup
|
train
|
function _indexOfGroup(match, group_number) {
var index = 0,
i;
for (i = 1; i < group_number; ++i) {
if (match[i]) {
index += match[i].length;
}
}
return index;
}
|
javascript
|
{
"resource": ""
}
|
q51620
|
_getPatternsForLanguage
|
train
|
function _getPatternsForLanguage(language) {
var patterns = language_patterns[language] || [],
default_patterns = language_patterns[DEFAULT_LANGUAGE] || [];
return _bypassDefaultPatterns(language) ? patterns : patterns.concat(default_patterns);
}
|
javascript
|
{
"resource": ""
}
|
q51621
|
_replaceAtPosition
|
train
|
function _replaceAtPosition(position, replace, replace_with, code) {
var sub_string = code.substr(position);
return code.substr(0, position) + sub_string.replace(replace, replace_with);
}
|
javascript
|
{
"resource": ""
}
|
q51622
|
keys
|
train
|
function keys(object) {
var locations = [],
replacement,
pos;
for(var location in object) {
if (object.hasOwnProperty(location)) {
locations.push(location);
}
}
// numeric descending
return locations.sort(function(a, b) {
return b - a;
});
}
|
javascript
|
{
"resource": ""
}
|
q51623
|
_processCodeWithPatterns
|
train
|
function _processCodeWithPatterns(code, patterns, callback)
{
// we have to increase the level here so that the
// replacements will not conflict with each other when
// processing sub blocks of code
++CURRENT_LEVEL;
// patterns are processed one at a time through this function
function _workOnPatterns(patterns, i)
{
// still have patterns to process, keep going
if (i < patterns.length) {
return _processPattern(patterns[i]['pattern'], patterns[i], code, function() {
_workOnPatterns(patterns, ++i);
});
}
// we are done processing the patterns
// process the replacements and update the DOM
_processReplacements(code, function(code) {
// when we are done processing replacements
// we are done at this level so we can go back down
delete replacements[CURRENT_LEVEL];
delete replacement_positions[CURRENT_LEVEL];
--CURRENT_LEVEL;
callback(code);
});
}
_workOnPatterns(patterns, 0);
}
|
javascript
|
{
"resource": ""
}
|
q51624
|
_processReplacements
|
train
|
function _processReplacements(code, onComplete) {
/**
* processes a single replacement
*
* @param {string} code
* @param {Array} positions
* @param {number} i
* @param {Function} onComplete
* @returns void
*/
function _processReplacement(code, positions, i, onComplete) {
if (i < positions.length) {
++replacement_counter;
var pos = positions[i],
replacement = replacements[CURRENT_LEVEL][pos];
code = _replaceAtPosition(pos, replacement['replace'], replacement['with'], code);
// process next function
var next = function() {
_processReplacement(code, positions, ++i, onComplete);
};
// use a timeout every 250 to not freeze up the UI
return replacement_counter % 250 > 0 ? next() : setTimeout(next, 0);
}
onComplete(code);
}
var string_positions = keys(replacements[CURRENT_LEVEL]);
_processReplacement(code, string_positions, 0, onComplete);
}
|
javascript
|
{
"resource": ""
}
|
q51625
|
_highlightBlockForLanguage
|
train
|
function _highlightBlockForLanguage(code, language, onComplete) {
var patterns = _getPatternsForLanguage(language);
_processCodeWithPatterns(_htmlEntities(code), patterns, onComplete);
}
|
javascript
|
{
"resource": ""
}
|
q51626
|
_highlightCodeBlock
|
train
|
function _highlightCodeBlock(code_blocks, i, onComplete) {
if (i < code_blocks.length) {
var block = code_blocks[i],
language = _getLanguageForBlock(block);
if (!_hasClass(block, 'rainbow') && language) {
language = language.toLowerCase();
_addClass(block, 'rainbow');
return _highlightBlockForLanguage(block.innerHTML, language, function(code) {
block.innerHTML = code;
// reset the replacement arrays
replacements = {};
replacement_positions = {};
// if you have a listener attached tell it that this block is now highlighted
if (onHighlight) {
onHighlight(block, language);
}
// process the next block
setTimeout(function() {
_highlightCodeBlock(code_blocks, ++i, onComplete);
}, 0);
});
}
return _highlightCodeBlock(code_blocks, ++i, onComplete);
}
if (onComplete) {
onComplete();
}
}
|
javascript
|
{
"resource": ""
}
|
q51627
|
train
|
function(language, patterns, bypass) {
// if there is only one argument then we assume that we want to
// extend the default language rules
if (arguments.length == 1) {
patterns = language;
language = DEFAULT_LANGUAGE;
}
bypass_defaults[language] = bypass;
language_patterns[language] = patterns.concat(language_patterns[language] || []);
}
|
javascript
|
{
"resource": ""
}
|
|
q51628
|
train
|
function() {
// if you want to straight up highlight a string you can pass the string of code,
// the language, and a callback function
if (typeof arguments[0] == 'string') {
return _highlightBlockForLanguage(arguments[0], arguments[1], arguments[2]);
}
// if you pass a callback function then we rerun the color function
// on all the code and call the callback function on complete
if (typeof arguments[0] == 'function') {
return _highlight(0, arguments[0]);
}
// otherwise we use whatever node you passed in with an optional
// callback function as the second parameter
_highlight(arguments[0], arguments[1]);
}
|
javascript
|
{
"resource": ""
}
|
|
q51629
|
getNumber
|
train
|
function getNumber (type, min, max, format, options) {
var ret;
// Juggle the arguments if the user didn't supply a format string
if (!options) {
options = format;
format = null;
}
if (type === 'int') {
ret = utils.randomInt(min, max);
} else if (type === 'float') {
ret = utils.randomFloat(min, max);
}
if (typeof options.hash.round === 'number') {
ret = Math.round(ret / options.hash.round) * options.hash.round;
}
if (format) {
ret = numbro(ret).format(format);
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q51630
|
getDate
|
train
|
function getDate (type, min, max, format, options) {
var ret;
// Juggle the arguments if the user didn't supply a format string
if (!options) {
options = format;
format = null;
}
if (type === 'date') {
min = Date.parse(min);
max = Date.parse(max);
} else if (type === 'time') {
min = Date.parse('1970-01-01T' + min);
max = Date.parse('1970-01-01T' + max);
}
ret = utils.randomDate(min, max);
if (format === 'unix') {
// We need to undo the timezone offset fix from utils.randomDate()
ret = Math.floor((ret.getTime() - ret.getTimezoneOffset() * 60000) / 1000);
} else if (format) {
ret = fecha.format(ret, format);
} else if (type === 'time') {
// Time has a default format if one is not specified
ret = fecha.format(ret, 'HH:mm');
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q51631
|
_createWish
|
train
|
function _createWish(wish) {
const id = wish.id || `g-${_previousId++}`
const newWish = {
id,
context: _createContext(wish.context),
data: wish.data || {},
magicWords: _arrayify(wish.magicWords),
action: _createAction(wish.action),
}
newWish.data.timesMade = {
total: 0,
magicWords: {},
}
return newWish
}
|
javascript
|
{
"resource": ""
}
|
q51632
|
_createContext
|
train
|
function _createContext(context) {
let newContext = context || _defaultContext
if (_isString(newContext) || _isArray(newContext)) {
newContext = {
any: _arrayify(newContext),
}
} else {
newContext = _arrayizeContext(context)
}
return newContext
}
|
javascript
|
{
"resource": ""
}
|
q51633
|
_arrayizeContext
|
train
|
function _arrayizeContext(context) {
function checkAndAdd(type) {
if (context[type]) {
context[type] = _arrayify(context[type])
}
}
checkAndAdd('all')
checkAndAdd('any')
checkAndAdd('none')
return context
}
|
javascript
|
{
"resource": ""
}
|
q51634
|
_createAction
|
train
|
function _createAction(action) {
if (_isString(action)) {
action = {
destination: action,
}
}
if (_isObject(action)) {
action = (function() {
const openNewTab = action.openNewTab
const destination = action.destination
return function() {
if (openNewTab) {
window.open(destination, '_blank')
} else {
window.location.href = destination
}
}
})()
}
return action
}
|
javascript
|
{
"resource": ""
}
|
q51635
|
deregisterWish
|
train
|
function deregisterWish(wish) {
let indexOfWish = _wishes.indexOf(wish)
if (!indexOfWish) {
_each(_wishes, (aWish, index) => {
// the given parameter could be an id.
if (wish === aWish.id || wish.id === aWish.id) {
indexOfWish = index
wish = aWish
return false
}
})
}
_wishes.splice(indexOfWish, 1)
_removeWishIdFromEnteredMagicWords(wish.id)
return wish
}
|
javascript
|
{
"resource": ""
}
|
q51636
|
_removeWishIdFromEnteredMagicWords
|
train
|
function _removeWishIdFromEnteredMagicWords(id) {
function removeIdFromWishes(charObj, parent, charObjName) {
_each(charObj, (childProp, propName) => {
if (propName === 'wishes') {
const index = childProp.indexOf(id)
if (index !== -1) {
childProp.splice(index, 1)
}
if (!childProp.length) {
delete charObj[propName]
}
} else {
removeIdFromWishes(childProp, charObj, propName)
}
})
const keepCharObj = _getPropFromPosterity(charObj, 'wishes').length > 0
if (!keepCharObj && parent && charObjName) {
delete parent[charObjName]
}
}
removeIdFromWishes(_enteredMagicWords)
}
|
javascript
|
{
"resource": ""
}
|
q51637
|
deregisterWishesWithContext
|
train
|
function deregisterWishesWithContext(context, type, wishContextTypes) {
const deregisteredWishes = getWishesWithContext(
context,
type,
wishContextTypes,
)
_each(deregisteredWishes, (wish, i) => {
deregisteredWishes[i] = deregisterWish(wish)
})
return deregisteredWishes
}
|
javascript
|
{
"resource": ""
}
|
q51638
|
_getWishContext
|
train
|
function _getWishContext(wish, wishContextTypes) {
let wishContext = []
wishContextTypes = wishContextTypes || ['all', 'any', 'none']
wishContextTypes = _arrayify(wishContextTypes)
_each(wishContextTypes, wishContextType => {
if (wish.context[wishContextType]) {
wishContext = wishContext.concat(wish.context[wishContextType])
}
})
return wishContext
}
|
javascript
|
{
"resource": ""
}
|
q51639
|
_getWishIndexById
|
train
|
function _getWishIndexById(id) {
let wishIndex = -1
if (_isArray(id)) {
const wishIndexes = []
_each(id, wishId => {
wishIndexes.push(_getWishIndexById(wishId))
})
return wishIndexes
} else {
_each(_wishes, (aWish, index) => {
if (aWish.id === id) {
wishIndex = index
return false
}
})
return wishIndex
}
}
|
javascript
|
{
"resource": ""
}
|
q51640
|
reset
|
train
|
function reset() {
const oldOptions = options()
options({
wishes: [],
noWishMerge: true,
previousId: 0,
enteredMagicWords: {},
context: _defaultContext,
previousContext: _defaultContext,
enabled: true,
})
return oldOptions
}
|
javascript
|
{
"resource": ""
}
|
q51641
|
_getWishIdsInEnteredMagicWords
|
train
|
function _getWishIdsInEnteredMagicWords(word) {
const startingCharWishesObj = _climbDownChain(
_enteredMagicWords,
word.split(''),
)
if (startingCharWishesObj) {
return _getPropFromPosterity(startingCharWishesObj, 'wishes', true)
} else {
return []
}
}
|
javascript
|
{
"resource": ""
}
|
q51642
|
_filterInContextWishes
|
train
|
function _filterInContextWishes(wishes) {
const inContextWishes = []
_each(wishes, wish => {
if (wish && _wishInContext(wish)) {
inContextWishes.push(wish)
}
})
return inContextWishes
}
|
javascript
|
{
"resource": ""
}
|
q51643
|
_getPropFromPosterity
|
train
|
function _getPropFromPosterity(objToStartWith, prop, unique) {
let values = []
function loadValues(obj) {
if (obj[prop]) {
const propsToAdd = _arrayify(obj[prop])
_each(propsToAdd, propToAdd => {
if (!unique || !_contains(values, propToAdd)) {
values.push(propToAdd)
}
})
}
_each(obj, (oProp, oPropName) => {
if (oPropName !== prop && !_isPrimitive(oProp)) {
values = values.concat(loadValues(oProp))
}
})
}
loadValues(objToStartWith)
return values
}
|
javascript
|
{
"resource": ""
}
|
q51644
|
_sortWishesByMatchingPriority
|
train
|
function _sortWishesByMatchingPriority(
wishes,
currentMatchingWishIds,
givenMagicWord,
) {
const matchPriorityArrays = []
let returnedIds = []
_each(
wishes,
wish => {
if (_wishInContext(wish)) {
const matchPriority = _bestMagicWordsMatch(
wish.magicWords,
givenMagicWord,
)
_maybeAddWishToMatchPriorityArray(
wish,
matchPriority,
matchPriorityArrays,
currentMatchingWishIds,
)
}
},
true,
)
_each(
matchPriorityArrays,
matchTypeArray => {
if (matchTypeArray) {
_each(matchTypeArray, magicWordIndexArray => {
if (magicWordIndexArray) {
returnedIds = returnedIds.concat(magicWordIndexArray)
}
})
}
},
true,
)
return returnedIds
}
|
javascript
|
{
"resource": ""
}
|
q51645
|
_bestMagicWordsMatch
|
train
|
function _bestMagicWordsMatch(wishesMagicWords, givenMagicWord) {
const bestMatch = {
matchType: _matchRankMap.noMatch,
magicWordIndex: -1,
}
_each(wishesMagicWords, (wishesMagicWord, index) => {
const matchRank = _stringsMatch(wishesMagicWord, givenMagicWord)
if (matchRank > bestMatch.matchType) {
bestMatch.matchType = matchRank
bestMatch.magicWordIndex = index
}
return bestMatch.matchType !== _matchRankMap.equals
})
return bestMatch
}
|
javascript
|
{
"resource": ""
}
|
q51646
|
_getAcronym
|
train
|
function _getAcronym(string) {
let acronym = ''
const wordsInString = string.split(' ')
_each(wordsInString, wordInString => {
const splitByHyphenWords = wordInString.split('-')
_each(splitByHyphenWords, splitByHyphenWord => {
acronym += splitByHyphenWord.substr(0, 1)
})
})
return acronym
}
|
javascript
|
{
"resource": ""
}
|
q51647
|
_stringsByCharOrder
|
train
|
function _stringsByCharOrder(magicWord, givenMagicWord) {
let charNumber = 0
function _findMatchingCharacter(matchChar, string) {
let found = false
for (let j = charNumber; j < string.length; j++) {
const stringChar = string[j]
if (stringChar === matchChar) {
found = true
charNumber = j + 1
break
}
}
return found
}
for (let i = 0; i < givenMagicWord.length; i++) {
const matchChar = givenMagicWord[i]
const found = _findMatchingCharacter(matchChar, magicWord)
if (!found) {
return _matchRankMap.noMatch
}
}
return _matchRankMap.matches
}
|
javascript
|
{
"resource": ""
}
|
q51648
|
_maybeAddWishToMatchPriorityArray
|
train
|
function _maybeAddWishToMatchPriorityArray(
wish,
matchPriority,
matchPriorityArrays,
currentMatchingWishIds,
) {
const indexOfWishInCurrent = currentMatchingWishIds.indexOf(wish.id)
if (matchPriority.matchType !== _matchRankMap.noMatch) {
if (indexOfWishInCurrent === -1) {
_getMatchPriorityArray(matchPriorityArrays, matchPriority).push(wish.id)
}
} else if (indexOfWishInCurrent !== -1) {
// remove current matching wishIds if it doesn't match
currentMatchingWishIds.splice(indexOfWishInCurrent, 1)
}
}
|
javascript
|
{
"resource": ""
}
|
q51649
|
_getMatchPriorityArray
|
train
|
function _getMatchPriorityArray(arry, matchPriority) {
arry[matchPriority.matchType] = arry[matchPriority.matchType] || []
const matchTypeArray = arry[matchPriority.matchType]
const matchPriorityArray = (matchTypeArray[matchPriority.magicWordIndex] =
matchTypeArray[matchPriority.magicWordIndex] || [])
return matchPriorityArray
}
|
javascript
|
{
"resource": ""
}
|
q51650
|
_convertToWishObjectFromNullOrId
|
train
|
function _convertToWishObjectFromNullOrId(wish, magicWord) {
let wishObject = wish
// Check if it may be a wish object
if (!_isObject(wishObject)) {
wishObject = getWish(wish)
}
if (_isNullOrUndefined(wishObject)) {
const matchingWishes = getMatchingWishes(magicWord)
if (matchingWishes.length > 0) {
wishObject = matchingWishes[0]
}
}
return wishObject
}
|
javascript
|
{
"resource": ""
}
|
q51651
|
_executeWish
|
train
|
function _executeWish(wish, magicWord) {
wish.action(wish, magicWord)
const timesMade = wish.data.timesMade
timesMade.total++
timesMade.magicWords[magicWord] = timesMade.magicWords[magicWord] || 0
timesMade.magicWords[magicWord]++
}
|
javascript
|
{
"resource": ""
}
|
q51652
|
_contextIsDefault
|
train
|
function _contextIsDefault(context) {
if (!_isObject(context)) {
context = _arrayify(context)
}
if (_isArray(context) && context.length === 1) {
return context[0] === _defaultContext[0]
} else if (context.any && context.any.length === 1) {
return context.any[0] === _defaultContext[0]
} else {
return false
}
}
|
javascript
|
{
"resource": ""
}
|
q51653
|
_createSpotInEnteredMagicWords
|
train
|
function _createSpotInEnteredMagicWords(spot, chars) {
const firstChar = chars.substring(0, 1)
const remainingChars = chars.substring(1)
const nextSpot = (spot[firstChar] = spot[firstChar] || {})
if (remainingChars) {
return _createSpotInEnteredMagicWords(nextSpot, remainingChars)
} else {
return nextSpot
}
}
|
javascript
|
{
"resource": ""
}
|
q51654
|
_getContextsFromPath
|
train
|
function _getContextsFromPath(path) {
const allContexts = {
add: [],
remove: [],
}
_each(_pathContexts, pathContext => {
let contextAdded = false
const contexts = pathContext.contexts
const regexes = pathContext.regexes
const paths = pathContext.paths
_each(regexes, regex => {
regex.lastIndex = 0
const matches = regex.exec(path)
if (matches && matches.length > 0) {
const contextsToAdd = []
_each(contexts, context => {
const replacedContext = context.replace(
_contextRegex,
(match, group) => {
return matches[group]
},
)
contextsToAdd.push(replacedContext)
})
allContexts.add = allContexts.add.concat(contextsToAdd)
contextAdded = true
}
return !contextAdded
})
if (!contextAdded) {
_each(paths, pathToTry => {
if (path === pathToTry) {
allContexts.add = allContexts.add.concat(contexts)
contextAdded = true
}
return !contextAdded
})
if (!contextAdded) {
allContexts.remove = allContexts.remove.concat(contexts)
}
}
})
return allContexts
}
|
javascript
|
{
"resource": ""
}
|
q51655
|
_getContextsMatchingRegexPathContexts
|
train
|
function _getContextsMatchingRegexPathContexts() {
const regexContexts = []
_each(_pathContexts, pathContext => {
const contexts = pathContext.contexts
_each(contexts, context => {
if (_contextRegex.test(context)) {
// context string is a regex context
const replaceContextRegex = context.replace(_contextRegex, '.+?')
_each(_context, currentContext => {
if (new RegExp(replaceContextRegex).test(currentContext)) {
regexContexts.push(currentContext)
}
})
}
})
})
return regexContexts
}
|
javascript
|
{
"resource": ""
}
|
q51656
|
_addUniqueItems
|
train
|
function _addUniqueItems(arry, obj) {
obj = _arrayify(obj)
arry = _arrayify(arry)
_each(obj, o => {
if (arry.indexOf(o) < 0) {
arry.push(o)
}
})
return arry
}
|
javascript
|
{
"resource": ""
}
|
q51657
|
_removeItems
|
train
|
function _removeItems(arry, obj) {
arry = _arrayify(arry)
obj = _arrayify(obj)
let i = 0
while (i < arry.length) {
if (_contains(obj, arry[i])) {
arry.splice(i, 1)
} else {
i++
}
}
return arry
}
|
javascript
|
{
"resource": ""
}
|
q51658
|
_arrayContainsNone
|
train
|
function _arrayContainsNone(arry1, arry2) {
arry1 = _arrayify(arry1)
arry2 = _arrayify(arry2)
for (let i = 0; i < arry2.length; i++) {
if (_contains(arry1, arry2[i])) {
return false
}
}
return true
}
|
javascript
|
{
"resource": ""
}
|
q51659
|
_isEmpty
|
train
|
function _isEmpty(obj) {
if (_isNullOrUndefined(obj)) {
return true
} else if (_isArray(obj)) {
return obj.length === 0
} else if (_isString(obj)) {
return obj === ''
} else if (_isPrimitive(obj)) {
return false
} else if (_isObject(obj)) {
return Object.keys(obj).length < 1
} else {
return false
}
}
|
javascript
|
{
"resource": ""
}
|
q51660
|
_eachArrayReverse
|
train
|
function _eachArrayReverse(arry, fn) {
let ret = true
for (let i = arry.length - 1; i >= 0; i--) {
ret = fn(arry[i], i, arry)
if (ret === false) {
break
}
}
return ret
}
|
javascript
|
{
"resource": ""
}
|
q51661
|
_eachArrayForward
|
train
|
function _eachArrayForward(arry, fn) {
let ret = true
for (let i = 0; i < arry.length; i++) {
ret = fn(arry[i], i, arry)
if (ret === false) {
break
}
}
return ret
}
|
javascript
|
{
"resource": ""
}
|
q51662
|
_eachProperty
|
train
|
function _eachProperty(obj, fn) {
let ret = true
for (const prop in obj) {
if (obj.hasOwnProperty(prop)) {
ret = fn(obj[prop], prop, obj)
if (ret === false) {
break
}
}
}
return ret
}
|
javascript
|
{
"resource": ""
}
|
q51663
|
_updateWishesWithOptions
|
train
|
function _updateWishesWithOptions(opts) {
if (opts.wishes) {
if (opts.noWishMerge) {
_wishes = opts.wishes
} else {
mergeWishes(opts.wishes)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q51664
|
context
|
train
|
function context(newContext) {
if (!_isUndefined(newContext)) {
_previousContext = _context
if (!_isArray(newContext)) {
newContext = [newContext]
}
_context = newContext
}
return _context
}
|
javascript
|
{
"resource": ""
}
|
q51665
|
addContext
|
train
|
function addContext(newContext) {
if (newContext && newContext.length) {
_previousContext = _context
_addUniqueItems(_context, newContext)
}
return _context
}
|
javascript
|
{
"resource": ""
}
|
q51666
|
removeContext
|
train
|
function removeContext(contextToRemove) {
if (contextToRemove && contextToRemove.length) {
_previousContext = _context
_removeItems(_context, contextToRemove)
if (_isEmpty(context)) {
_context = _defaultContext
}
}
return _context
}
|
javascript
|
{
"resource": ""
}
|
q51667
|
updatePathContext
|
train
|
function updatePathContext(path, noDeregister) {
if (path) {
const allContexts = _getContextsFromPath(path)
const contextsToAdd = allContexts.add
let contextsToRemove = _getContextsMatchingRegexPathContexts()
contextsToRemove = contextsToRemove.concat(allContexts.remove)
removeContext(contextsToRemove)
if (!noDeregister) {
// There's no way to prevent users of genie from adding wishes that already exist in genie
// so we're completely removing them here
deregisterWishesWithContext(contextsToRemove)
}
addContext(contextsToAdd)
}
return _context
}
|
javascript
|
{
"resource": ""
}
|
q51668
|
addPathContext
|
train
|
function addPathContext(pathContexts) {
_each(pathContexts, pathContext => {
if (pathContext.paths) {
pathContext.paths = _arrayify(pathContext.paths)
}
if (pathContext.regexes) {
pathContext.regexes = _arrayify(pathContext.regexes)
}
if (pathContext.contexts) {
pathContext.contexts = _arrayify(pathContext.contexts)
}
})
_addUniqueItems(_pathContexts, pathContexts)
return _pathContexts
}
|
javascript
|
{
"resource": ""
}
|
q51669
|
setPathParamsFromArray
|
train
|
function setPathParamsFromArray(data, config, idx) {
// only write parameters if they are not already defined in config
if (data.requestData === undefined || config.pathParams) {
return data;
}
// if we have requestData, fill the path params accordingly
var mockParameters = {};
data.pathParameters.forEach(function(parameter) {
// find the mock data for this parameter name
mockParameters[parameter.name] = data.requestData.filter(function(mock) {
return mock.hasOwnProperty(parameter.name);
})[idx][parameter.name];
});
data.pathParams = mockParameters;
return data;
}
|
javascript
|
{
"resource": ""
}
|
q51670
|
filterOutOptionalQueryParams
|
train
|
function filterOutOptionalQueryParams(data) {
data.queryParameters = data.queryParameters.filter(function(queryParam) {
// Let's be conservative and treat params without explicit required field as not-optional
var optional = queryParam.required !== undefined && !queryParam.required;
var dataProvided = data.requestParameters.hasOwnProperty(queryParam.name);
return !optional || dataProvided;
});
return data;
}
|
javascript
|
{
"resource": ""
}
|
q51671
|
validateResponse
|
train
|
function validateResponse(type, noSchema,
options) {
if (arguments.length < 3) {
throw new Error('Handlebars Helper \'validateResponse\'' +
'needs 2 parameters');
}
if (!noSchema && mediaTypeContainsJson(type)) {
return options.fn(this);
} else {
return options.inverse(this);
}
}
|
javascript
|
{
"resource": ""
}
|
q51672
|
length
|
train
|
function length(description) {
if (arguments.length < 2) {
throw new Error('Handlebar Helper \'length\'' +
' needs 1 parameter');
}
if ((typeof description) !== 'string') {
throw new TypeError('Handlebars Helper \'length\'' +
'requires path to be a string');
}
var desc = description;
if (len !== -1) {
description = strObj(description).truncate(len - 50).s;
}
return jsStringEscape(description);
}
|
javascript
|
{
"resource": ""
}
|
q51673
|
verifyMessage
|
train
|
function verifyMessage(callbackBody, contentSignature, signingKey) {
const hash = crypto.createHash('sha256').update(signingKey).digest();
const hmac = crypto.createHmac('sha256', hash);
return contentSignature === hmac.update(JSON.stringify(callbackBody)).digest('base64');
}
|
javascript
|
{
"resource": ""
}
|
q51674
|
train
|
function (dispatchEvents, name) {
this.dispatchEvent = dispatchEvents;
this.name = name;
this.connection = freedom['core.rtcpeerconnection']();
this.connection.on(function (type, msg) {
if (type === 'onsignalingstatechange' ||
type === 'onnegotiationneeded' ||
type === 'oniceconnectionstatechange') {
this.dispatchEvent('message', '<small style="color:gray">' + type + '</small>');
} else if (type === 'onicecandidate') {
if (msg) {
this.dispatchEvent('ice', JSON.stringify(msg));
}
this.dispatchEvent('message', '<small style="color:lightgray">Ice Candidate Produced</small>');
} else if (type === 'ondatachannel') {
this.dispatchEvent('message', '<small style="color:blue">Data Channel Ready [Recipient]</small>');
this.channel = freedom['core.rtcdatachannel'](msg.channel);
this.channel.on(this.onDataChannelMsg.bind(this));
} else {
this.dispatchEvent('message', JSON.stringify({type: type, msg: msg}));
}
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q51675
|
PeerConnection
|
train
|
function PeerConnection(portModule, dispatchEvent,
RTCPeerConnection, RTCSessionDescription,
RTCIceCandidate) {
// Channel for emitting events to consumer.
this.dispatchEvent = dispatchEvent;
// a (hopefully unique) ID for debugging.
this.peerName = "p" + Math.random();
// This is the portApp (defined in freedom/src/port-app.js). A way to speak
// to freedom.
this.freedomModule = portModule.module;
// For tests we may mock out the PeerConnection and
// SessionDescription implementations
this.RTCPeerConnection = RTCPeerConnection;
this.RTCSessionDescription = RTCSessionDescription;
this.RTCIceCandidate = RTCIceCandidate;
// This is the a channel to send signalling messages.
this.signallingChannel = null;
// The DataPeer object for talking to the peer.
this.peer = null;
// The Core object for managing channels.
this.freedomModule.once('core', function (Core) {
this.core = new Core();
}.bind(this));
this.freedomModule.emit(this.freedomModule.controlChannel, {
type: 'core request delegated to peerconnection',
request: 'core'
});
}
|
javascript
|
{
"resource": ""
}
|
q51676
|
train
|
function (dataChannel, info, event) {
if (event.data instanceof ArrayBuffer) {
self.dispatchEvent('onReceived', {
'channelLabel': info.label,
'buffer': event.data
});
} else if (event.data instanceof Blob) {
self.dispatchEvent('onReceived', {
'channelLabel': info.label,
'binary': event.data
});
} else if (typeof (event.data) === 'string') {
self.dispatchEvent('onReceived', {
'channelLabel': info.label,
'text': event.data
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51677
|
train
|
function (dataChannel, info, err) {
console.error(dataChannel.peerName + ": dataChannel(" +
dataChannel.dataChannel.label + "): error: ", err);
}
|
javascript
|
{
"resource": ""
}
|
|
q51678
|
train
|
function(cap, dispatchEvent) {
this.mod = cap.module;
this.dispatchEvent = dispatchEvent;
util.handleEvents(this);
// The Core object for managing channels.
this.mod.once('core', function(Core) {
this.core = new Core();
}.bind(this));
this.mod.emit(this.mod.controlChannel, {
type: 'core request delegated to echo',
request: 'core'
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51679
|
train
|
function (cap) {
this.level = (cap.config && cap.config.debug) || 'log';
this.console = (cap.config && cap.config.global.console);
util.handleEvents(this);
}
|
javascript
|
{
"resource": ""
}
|
|
q51680
|
train
|
function (manifestURL, manifest, creator, policy) {
this.api = policy.api;
this.policy = policy;
this.resource = policy.resource;
this.debug = policy.debug;
this.config = {};
this.id = manifestURL + Math.random();
this.manifestId = manifestURL;
this.manifest = manifest;
this.lineage = [this.manifestId].concat(creator);
this.quiet = this.manifest.quiet || false;
this.externalPortMap = {};
this.internalPortMap = {};
this.dependantChannels = [];
// Map from dependency names to target URLs, from this module's manifest.
this.dependencyUrls = {};
// Map from depenency names to arrays of pending messages. Once a
// dependency is fully started, the pending messages will be drained and its
// entry in this map will be deleted.
this.pendingMessages = {};
this.started = false;
this.failed = false;
util.handleEvents(this);
}
|
javascript
|
{
"resource": ""
}
|
|
q51681
|
train
|
function (manager) {
this.config = {};
this.manager = manager;
this.debug = manager.debug;
this.binder = new ProxyBinder(this.manager);
this.api = this.manager.api;
this.manifests = {};
this.providers = {};
this.id = 'ModuleInternal';
this.pendingPorts = 0;
this.requests = {};
this.unboundPorts = {};
util.handleEvents(this);
}
|
javascript
|
{
"resource": ""
}
|
|
q51682
|
train
|
function (debug) {
this.debug = debug;
this.files = {};
this.resolvers = [this.httpResolver, this.nullResolver];
this.contentRetrievers = {
'http': this.xhrRetriever,
'https': this.xhrRetriever,
'chrome-extension': this.xhrRetriever,
'resource': this.xhrRetriever,
'chrome': this.xhrRetriever,
'app': this.xhrRetriever,
'gopher': this.xhrRetriever, // For Cordova; see http://crbug.com/513352 .
'manifest': this.manifestRetriever
};
}
|
javascript
|
{
"resource": ""
}
|
|
q51683
|
download
|
train
|
function download(cvs, data, callback) {
var mime = data.mime || DEFAULT_MIME;
root.location.href = cvs.toDataURL(mime).replace(mime, DOWNLOAD_MIME);
if (typeof callback === 'function') callback();
}
|
javascript
|
{
"resource": ""
}
|
q51684
|
overrideAPI
|
train
|
function overrideAPI(qr) {
var methods = [ 'canvas', 'image', 'save', 'saveSync', 'toDataURL' ];
var i;
function overrideMethod(name) {
qr[name] = function () {
throw new Error(name + ' requires HTML5 canvas element support');
};
}
for (i = 0; i < methods.length; i++) {
overrideMethod(methods[i]);
}
}
|
javascript
|
{
"resource": ""
}
|
q51685
|
writeFile
|
train
|
function writeFile(cvs, data, callback) {
if (typeof data.path !== 'string') {
return callback(new TypeError('Invalid path type: ' + typeof data.path));
}
var fd, buff;
// Write the buffer to the open file stream once both prerequisites are met.
function writeBuffer() {
fs.write(fd, buff, 0, buff.length, 0, function (error) {
fs.close(fd);
callback(error);
});
}
// Create a buffer of the canvas' data.
cvs.toBuffer(function (error, _buff) {
if (error) return callback(error);
buff = _buff;
if (fd) {
writeBuffer();
}
});
// Open a stream for the file to be written.
fs.open(data.path, 'w', WRITE_MODE, function (error, _fd) {
if (error) return callback(error);
fd = _fd;
if (buff) {
writeBuffer();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q51686
|
writeBuffer
|
train
|
function writeBuffer() {
fs.write(fd, buff, 0, buff.length, 0, function (error) {
fs.close(fd);
callback(error);
});
}
|
javascript
|
{
"resource": ""
}
|
q51687
|
writeFileSync
|
train
|
function writeFileSync(cvs, data) {
if (typeof data.path !== 'string') {
throw new TypeError('Invalid path type: ' + typeof data.path);
}
var buff = cvs.toBuffer();
var fd = fs.openSync(data.path, 'w', WRITE_MODE);
try {
fs.writeSync(fd, buff, 0, buff.length, 0);
} catch (error) {
fs.closeSync(fd);
}
}
|
javascript
|
{
"resource": ""
}
|
q51688
|
addAlignment
|
train
|
function addAlignment(x, y) {
var i;
frameBuffer[x + width * y] = 1;
for (i = -2; i < 2; i++) {
frameBuffer[(x + i) + width * (y - 2)] = 1;
frameBuffer[(x - 2) + width * (y + i + 1)] = 1;
frameBuffer[(x + 2) + width * (y + i)] = 1;
frameBuffer[(x + i + 1) + width * (y + 2)] = 1;
}
for (i = 0; i < 2; i++) {
setMask(x - 1, y + i);
setMask(x + 1, y - i);
setMask(x - i, y - 1);
setMask(x + i, y + 1);
}
}
|
javascript
|
{
"resource": ""
}
|
q51689
|
appendData
|
train
|
function appendData(data, dataLength, ecc, eccLength) {
var bit, i, j;
for (i = 0; i < eccLength; i++) {
stringBuffer[ecc + i] = 0;
}
for (i = 0; i < dataLength; i++) {
bit = GALOIS_LOG[stringBuffer[data + i] ^ stringBuffer[ecc]];
if (bit !== 255) {
for (j = 1; j < eccLength; j++) {
stringBuffer[ecc + j - 1] = stringBuffer[ecc + j] ^
GALOIS_EXPONENT[modN(bit + polynomial[eccLength - j])];
}
} else {
for (j = ecc; j < ecc + eccLength; j++) {
stringBuffer[j] = stringBuffer[j + 1];
}
}
stringBuffer[ecc + eccLength - 1] = bit === 255 ? 0 :
GALOIS_EXPONENT[modN(bit + polynomial[0])];
}
}
|
javascript
|
{
"resource": ""
}
|
q51690
|
isMasked
|
train
|
function isMasked(x, y) {
var bit;
if (x > y) {
bit = x;
x = y;
y = bit;
}
bit = y;
bit += y * y;
bit >>= 1;
bit += x;
return frameMask[bit] === 1;
}
|
javascript
|
{
"resource": ""
}
|
q51691
|
getBadRuns
|
train
|
function getBadRuns(length) {
var badRuns = 0;
var i;
for (i = 0; i <= length; i++) {
if (badBuffer[i] >= 5) {
badRuns += N1 + badBuffer[i] - 5;
}
}
// FBFFFBF as in finder.
for (i = 3; i < length - 1; i += 2) {
if (badBuffer[i - 2] === badBuffer[i + 2] &&
badBuffer[i + 2] === badBuffer[i - 1] &&
badBuffer[i - 1] === badBuffer[i + 1] &&
badBuffer[i - 1] * 3 === badBuffer[i] &&
// Background around the foreground pattern? Not part of the specs.
(badBuffer[i - 3] === 0 || i + 3 > length ||
badBuffer[i - 3] * 3 >= badBuffer[i] * 4 ||
badBuffer[i + 3] * 3 >= badBuffer[i] * 4)) {
badRuns += N3;
}
}
return badRuns;
}
|
javascript
|
{
"resource": ""
}
|
q51692
|
train
|
function (cap, dispatchEvent, url, protocols, socket) {
var WSImplementation = null,
error;
this.isNode = nodeStyle;
if (typeof socket !== 'undefined') {
WSImplementation = socket;
} else if (WSHandle !== null) {
WSImplementation = WSHandle;
} else if (typeof WebSocket !== 'undefined') {
WSImplementation = WebSocket;
} else {
console.error('Platform does not support WebSocket');
}
this.dispatchEvent = dispatchEvent;
try {
if (protocols) {
this.websocket = new WSImplementation(url, protocols);
} else {
this.websocket = new WSImplementation(url);
}
this.websocket.binaryType = 'arraybuffer';
} catch (e) {
error = {};
if (e instanceof SyntaxError) {
error.errcode = 'SYNTAX';
} else {
error.errcode = e.name;
}
error.message = e.message;
dispatchEvent('onError', error);
return;
}
if (this.isNode) {
this.websocket.on('message', this.onMessage.bind(this));
this.websocket.on('open', this.onOpen.bind(this));
// node.js websocket implementation not compliant
this.websocket.on('close', this.onClose.bind(this, {
code: 0,
reason: 'UNKNOWN',
wasClean: true
}));
this.websocket.on('error', this.onError.bind(this));
} else {
this.websocket.onopen = this.onOpen.bind(this);
this.websocket.onclose = this.onClose.bind(this);
this.websocket.onmessage = this.onMessage.bind(this);
this.websocket.onerror = this.onError.bind(this);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51693
|
train
|
function (def, debug) {
this.id = Consumer.nextId();
util.handleEvents(this);
this.debug = debug;
this.definition = def;
this.mode = Provider.mode.synchronous;
this.channels = {};
this.iface = null;
this.closeHandlers = {};
this.providerCls = null;
this.ifaces = {};
this.emits = {};
}
|
javascript
|
{
"resource": ""
}
|
|
q51694
|
train
|
function(evts, key) {
var saw1 = false, saw2 = false;
for (var i = 0; i < evts.length; i++) {
if (typeof c1State !== "undefined" && evts[i][key] == c1State[key]) {
saw1 = true;
}
if (typeof c2State !== "undefined" && evts[i][key] == c2State[key]) {
saw2 = true;
}
}
return saw1 && saw2;
}
|
javascript
|
{
"resource": ""
}
|
|
q51695
|
train
|
function(arr, info) {
if (typeof arr !== "undefined") {
arr.push(info);
}
if (!triggered &&
seeBoth(c1ProfileEvts, "userId") && seeBoth(c2ProfileEvts, "userId") &&
seeBoth(c1StateEvts, "clientId") && seeBoth(c2StateEvts, "clientId")) {
triggered = true;
Promise.all([ c1.getUsers(), c2.getUsers(), c1.getClients(), c2.getClients() ]).then(function(ret) {
expect(ret[0][c1State.userId]).toEqual(Helper.makeUserProfile(c1State.userId));
expect(ret[0][c2State.userId]).toEqual(Helper.makeUserProfile(c2State.userId));
expect(ret[1][c1State.userId]).toEqual(Helper.makeUserProfile(c1State.userId));
expect(ret[1][c2State.userId]).toEqual(Helper.makeUserProfile(c2State.userId));
expect(ret[2][c1State.clientId]).toEqual(Helper.makeClientState(c1State.userId, c1State.clientId, "ONLINE"));
expect(ret[2][c2State.clientId]).toEqual(Helper.makeClientState(c2State.userId, c2State.clientId, "ONLINE"));
expect(ret[3][c1State.clientId]).toEqual(Helper.makeClientState(c1State.userId, c1State.clientId, "ONLINE"));
expect(ret[3][c2State.clientId]).toEqual(Helper.makeClientState(c2State.userId, c2State.clientId, "ONLINE"));
return Promise.all([ c1.logout(), c2.logout() ]);
}).then(done).catch(Helper.errHandler);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51696
|
train
|
function (name, resource) {
this.id = 'Link' + Math.random();
this.name = name;
this.resource = resource;
this.config = {};
this.src = null;
util.handleEvents(this);
util.mixin(this, Link.prototype);
}
|
javascript
|
{
"resource": ""
}
|
|
q51697
|
train
|
function(manager, resource, config) {
this.api = manager.api;
this.debug = manager.debug;
this.location = config.location;
this.resource = resource;
this.config = config;
this.runtimes = [];
this.policies = [];
this.pending = {};
util.handleEvents(this);
this.add(manager, config.policy);
this.runtimes[0].local = true;
}
|
javascript
|
{
"resource": ""
}
|
|
q51698
|
train
|
function (hub, resource, api) {
this.id = 'control';
this.config = {};
this.controlFlows = {};
this.dataFlows = {};
this.dataFlows[this.id] = [];
this.reverseFlowMap = {};
this.debug = hub.debug;
this.hub = hub;
this.resource = resource;
this.api = api;
this.delegate = null;
this.toDelegate = {};
this.hub.on('config', function (config) {
util.mixin(this.config, config);
this.emit('config');
}.bind(this));
util.handleEvents(this);
this.hub.register(this);
}
|
javascript
|
{
"resource": ""
}
|
|
q51699
|
onState
|
train
|
function onState(data) {
if (data.status === social.STATUS.OFFLINE) {
if (users.hasOwnProperty(data.userId)) {
delete users[data.userId];
}
} else { //Only track non-offline clients
users[data.userId] = data;
}
sendUsers();
// Handle my state separately
if (myClientState !== null && data.clientId === myClientState.clientId) {
view.postMessage({
event: 'status',
online: data.status === social.STATUS.ONLINE
});
view.postMessage({'height': data.status === social.STATUS.ONLINE ? 384 : 109});
if (data.status !== social.STATUS.ONLINE) {
logger.error('got status ' + data.status + ' from social');
doLogin();
}
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.