_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q30900 | add | train | function add (cpu, n) {
const r = cpu.a + n;
cpu.f = 0;
if ((r & 0xff) == 0) cpu.f |= FLAG_Z;
if (((cpu.a ^ n ^ r) & 0x10) != 0) cpu.f |= FLAG_H;
if ((r & 0x100) != 0) cpu.f |= FLAG_C;
return r;
} | javascript | {
"resource": ""
} |
q30901 | adc | train | function adc (cpu, n) {
const cy = cpu.f >> 4 & 1;
const r = cpu.a + n + cy;
cpu.f = 0;
if ((r & 0xff) == 0) cpu.f |= FLAG_Z;
if (((cpu.a ^ n ^ r) & 0x10) != 0) cpu.f |= FLAG_H;
if ((r & 0x100) != 0) cpu.f |= FLAG_C;
return r;
} | javascript | {
"resource": ""
} |
q30902 | sbc | train | function sbc (cpu, n) {
const cy = cpu.f >> 4 & 1;
const r = cpu.a - n - cy;
cpu.f = FLAG_N;
if ((r & 0xff) == 0) cpu.f |= FLAG_Z;
if (((cpu.a ^ n ^ r) & 0x10) != 0) cpu.f |= FLAG_H;
if ((r & 0x100) != 0) cpu.f |= FLAG_C;
return r;
} | javascript | {
"resource": ""
} |
q30903 | swap | train | function swap (cpu, n) {
const r = n << 4 | n >> 4;
cpu.f = 0;
if ((r & 0xff) == 0) cpu.f |= FLAG_Z;
return r;
} | javascript | {
"resource": ""
} |
q30904 | bit | train | function bit (cpu, b, n) {
const r = n & (1 << b);
cpu.f &= ~0xe0;
if (r == 0) cpu.f |= FLAG_Z;
cpu.f |= FLAG_H;
return r;
} | javascript | {
"resource": ""
} |
q30905 | train | function (cpu, mmu, cc) {
if (cc) {
cpu.pc += 2 + mmu.readByte(cpu.pc + 1).signed();
return 12;
}
cpu.pc += 2;
return 8;
} | javascript | {
"resource": ""
} | |
q30906 | train | function (cpu, mmu, cc) {
if (cc) {
mmu.writeWord(cpu.sp -= 2, cpu.pc + 3);
cpu.pc = mmu.readWord(cpu.pc + 1);
return 24;
}
cpu.pc += 3;
return 12;
} | javascript | {
"resource": ""
} | |
q30907 | train | function (data) {
if (mockIndexedDBTestFlags.canSave === true) {
mockIndexedDBItems.push(data);
mockIndexedDB_storeAddTimer = setTimeout(function () {
mockIndexedDBTransaction.callCompleteHandler();
mockIndexedDB_saveSuccess = true;
}, 20);
}
else {
mockIndexedDB_storeAddTimer = setTimeout(function () {
mockIndexedDBTransaction.callErrorHandler();
mockIndexedDB_saveFail = true;
}, 20);
}
return mockIndexedDBTransaction;
} | javascript | {
"resource": ""
} | |
q30908 | train | function (data_id) {
if (mockIndexedDBTestFlags.canDelete === true) {
mockIndexedDB_storeDeleteTimer = setTimeout(function () {
mockIndexedDBStoreTransaction.callSuccessHandler();
mockIndexedDB_deleteSuccess = true;
}, 20);
}
else {
mockIndexedDB_storeDeleteTimer = setTimeout(function () {
mockIndexedDBStoreTransaction.callErrorHandler();
mockIndexedDB_deleteFail = true;
}, 20);
}
return mockIndexedDBStoreTransaction;
} | javascript | {
"resource": ""
} | |
q30909 | train | function (data_id) {
if (mockIndexedDBTestFlags.canClear === true) {
mockIndexedDB_storeClearTimer = setTimeout(function () {
mockIndexedDBStoreTransaction.callSuccessHandler();
mockIndexedDB_clearSuccess = true;
}, 20);
}
else {
mockIndexedDB_storeClearTimer = setTimeout(function () {
mockIndexedDBStoreTransaction.callErrorHandler();
mockIndexedDB_clearFail = true;
}, 20);
}
return mockIndexedDBStoreTransaction;
} | javascript | {
"resource": ""
} | |
q30910 | getNextPageUrl | train | function getNextPageUrl(response) {
const link = response.headers.get('link');
if (!link) {
return null;
}
const nextLink = link.split(',').filter(s => s.indexOf('rel="next"') > -1)[0];
if (!nextLink) {
return null;
}
return nextLink.split(';')[0].slice(1, -1);
} | javascript | {
"resource": ""
} |
q30911 | Packet | train | function Packet(arg) {
if (this instanceof Packet === false) {
return new Packet(arg);
}
if (arg === undefined) {
throw new TypeError('arg should be a Buffer object or a number of slots');
}
if (Buffer.isBuffer(arg)) { // initialize from a buffer
if (arg.length < 126) {
throw new RangeError('buffer size should be of at least 126 bytes');
}
this._buffer = arg;
}
else if (Number.isInteger(arg)) { // initialize using number of slots
if (arg < 1 || arg > 512) {
throw new RangeError("number of slots should be in the range [1-512]");
}
this._buffer = Buffer.alloc(126 + arg);
}
this._rootLayer = new RootLayer(this._buffer.slice(0, 38));
this._frameLayer = new FrameLayer(this._buffer.slice(38, 115));
this._dmpLayer = new DMPLayer(this._buffer.slice(115));
if (Number.isInteger(arg)) {
this.init(arg);
}
} | javascript | {
"resource": ""
} |
q30912 | getData | train | function getData(obj) {
var data = {};
each(supportParam, function(i, o) {
var a = obj.getAttribute('data-' + o);
if (a) data[o] = a;
});
return data;
} | javascript | {
"resource": ""
} |
q30913 | Server | train | function Server(universes, port) {
if (this instanceof Server === false) {
return new Server(port);
}
EventEmitter.call(this);
if (universes !== undefined && !Array.isArray(universes)) {
universes = [universes];
}
this.universes = universes || [0x01];
this.port = port || e131.DEFAULT_PORT;
this._socket = dgram.createSocket('udp4');
this._lastSequenceNumber = {};
var self = this;
this.universes.forEach(function (universe) {
self._lastSequenceNumber[universe] = 0;
});
this._socket.on('error', function onError(err) {
self.emit('error', err);
});
this._socket.on('listening', function onListening() {
self.emit('listening');
});
this._socket.on('close', function onClose() {
self.emit('close');
});
this._socket.on('message', function onMessage(msg) {
var packet = new e131.Packet(msg);
var validation = packet.validate();
if (validation !== packet.ERR_NONE) {
self.emit('packet-error', packet, validation);
return;
}
if (packet.discard(self._lastSequenceNumber[packet.getUniverse()])) {
self.emit('packet-out-of-order', packet);
} else {
self.emit('packet', packet);
}
self._lastSequenceNumber[packet.getUniverse()] = packet.getSequenceNumber();
});
this._socket.bind(this.port, function onListening() {
self.universes.forEach(function (universe) {
var multicastGroup = e131.getMulticastGroup(universe);
self._socket.addMembership(multicastGroup);
});
});
} | javascript | {
"resource": ""
} |
q30914 | ArrayIndex | train | function ArrayIndex (_length) {
Object.defineProperty(this, 'length', {
get: getLength,
set: setLength,
enumerable: false,
configurable: true
});
this[length] = 0;
if (arguments.length > 0) {
setLength.call(this, _length);
}
} | javascript | {
"resource": ""
} |
q30915 | setup | train | function setup (index) {
function get () {
return this[ArrayIndex.get](index);
}
function set (v) {
return this[ArrayIndex.set](index, v);
}
return {
enumerable: true,
configurable: true,
get: get,
set: set
};
} | javascript | {
"resource": ""
} |
q30916 | loadLocale | train | function loadLocale(lang, callback) {
// RFC 4646, section 2.1 states that language tags have to be treated as
// case-insensitive. Convert to lowercase for case-insensitive comparisons.
if (lang) {
lang = lang.toLowerCase();
}
callback = callback || function _callback() {};
clear();
gLanguage = lang;
// check all <link type="application/l10n" href="..." /> nodes
// and load the resource files
var langLinks = getL10nResourceLinks();
var langCount = langLinks.length;
if (langCount === 0) {
// we might have a pre-compiled dictionary instead
var dict = getL10nDictionary();
if (dict && dict.locales && dict.default_locale) {
console.log("using the embedded JSON directory, early way out");
gL10nData = dict.locales[lang];
if (!gL10nData) {
var defaultLocale = dict.default_locale.toLowerCase();
for (var anyCaseLang in dict.locales) {
anyCaseLang = anyCaseLang.toLowerCase();
if (anyCaseLang === lang) {
gL10nData = dict.locales[lang];
break;
} else if (anyCaseLang === defaultLocale) {
gL10nData = dict.locales[defaultLocale];
}
}
}
callback();
} else {
console.log("no resource to load, early way out");
}
// early way out
fireL10nReadyEvent(lang);
gReadyState = "complete";
return;
}
// start the callback when all resources are loaded
var onResourceLoaded = null;
var gResourceCount = 0;
onResourceLoaded = function() {
gResourceCount++;
if (gResourceCount >= langCount) {
callback();
fireL10nReadyEvent(lang);
gReadyState = "complete";
}
};
// load all resource files
function L10nResourceLink(link) {
var href = link.href;
// Note: If |gAsyncResourceLoading| is false, then the following callbacks
// are synchronously called.
this.load = function(lang, callback) {
parseResource(href, lang, callback, function() {
console.warn(href + " not found.");
// lang not found, used default resource instead
console.warn('"' + lang + '" resource not found');
gLanguage = "";
// Resource not loaded, but we still need to call the callback.
callback();
});
};
}
for (var i = 0; i < langCount; i++) {
var resource = new L10nResourceLink(langLinks[i]);
resource.load(lang, onResourceLoaded);
}
} | javascript | {
"resource": ""
} |
q30917 | L10nResourceLink | train | function L10nResourceLink(link) {
var href = link.href;
// Note: If |gAsyncResourceLoading| is false, then the following callbacks
// are synchronously called.
this.load = function(lang, callback) {
parseResource(href, lang, callback, function() {
console.warn(href + " not found.");
// lang not found, used default resource instead
console.warn('"' + lang + '" resource not found');
gLanguage = "";
// Resource not loaded, but we still need to call the callback.
callback();
});
};
} | javascript | {
"resource": ""
} |
q30918 | getL10nData | train | function getL10nData(key, args, fallback) {
var data = gL10nData[key];
if (!data) {
console.warn("#" + key + " is undefined.");
if (!fallback) {
return null;
}
data = fallback;
}
/** This is where l10n expressions should be processed.
* The plan is to support C-style expressions from the l20n project;
* until then, only two kinds of simple expressions are supported:
* {[ index ]} and {{ arguments }}.
*/
var rv = {};
for (var prop in data) {
var str = data[prop];
str = substIndexes(str, args, key, prop);
str = substArguments(str, args, key);
rv[prop] = str;
}
return rv;
} | javascript | {
"resource": ""
} |
q30919 | train | function(key, args, fallbackString) {
var index = key.lastIndexOf(".");
var prop = gTextProp;
if (index > 0) {
// An attribute has been specified
prop = key.substr(index + 1);
key = key.substring(0, index);
}
var fallback;
if (fallbackString) {
fallback = {};
fallback[prop] = fallbackString;
}
var data = getL10nData(key, args, fallback);
if (data && prop in data) {
return data[prop];
}
return "{{" + key + "}}";
} | javascript | {
"resource": ""
} | |
q30920 | Triangle | train | function Triangle ( point1, point2, point3 )
{
/**
* @member {Point}
* @default {x:0,y:0}
*/
this.p1 = point1 || new Point(0,0);
/**
* @member {Point}
* @default {x:0,y:0}
*/
this.p2 = point2 || new Point(0,0);
/**
* @member {Point}
* @default {x:0,y:0}
*/
this.p3 = point3 || new Point(0,0);
/**
* @member {Point}
*/
this.mid0 = new Point ( this.p1.x + ( this.p2.x - this.p1.x )/2,
this.p1.y + ( this.p2.y - this.p1.y )/2 );
/**
* @member {Point}
*/
this.mid1 = new Point ( this.p2.x + ( this.p3.x - this.p2.x )/2,
this.p2.y + ( this.p3.y - this.p2.y )/2 );
/**
* @member {Point}
*/
this.mid2 = new Point ( this.p3.x + ( this.p1.x - this.p3.x )/2,
this.p3.y + ( this.p1.y - this.p3.y )/2 );
} | javascript | {
"resource": ""
} |
q30921 | _buildFromEncodedParts | train | function _buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
var /** @type {?} */ out = [];
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__facade_lang__["c" /* isPresent */])(opt_scheme)) {
out.push(opt_scheme + ':');
}
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__facade_lang__["c" /* isPresent */])(opt_domain)) {
out.push('//');
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__facade_lang__["c" /* isPresent */])(opt_userInfo)) {
out.push(opt_userInfo + '@');
}
out.push(opt_domain);
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__facade_lang__["c" /* isPresent */])(opt_port)) {
out.push(':' + opt_port);
}
}
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__facade_lang__["c" /* isPresent */])(opt_path)) {
out.push(opt_path);
}
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__facade_lang__["c" /* isPresent */])(opt_queryData)) {
out.push('?' + opt_queryData);
}
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__facade_lang__["c" /* isPresent */])(opt_fragment)) {
out.push('#' + opt_fragment);
}
return out.join('');
} | javascript | {
"resource": ""
} |
q30922 | _resolveUrl | train | function _resolveUrl(base, url) {
var /** @type {?} */ parts = _split(encodeURI(url));
var /** @type {?} */ baseParts = _split(base);
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__facade_lang__["c" /* isPresent */])(parts[_ComponentIndex.Scheme])) {
return _joinAndCanonicalizePath(parts);
}
else {
parts[_ComponentIndex.Scheme] = baseParts[_ComponentIndex.Scheme];
}
for (var /** @type {?} */ i = _ComponentIndex.Scheme; i <= _ComponentIndex.Port; i++) {
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__facade_lang__["d" /* isBlank */])(parts[i])) {
parts[i] = baseParts[i];
}
}
if (parts[_ComponentIndex.Path][0] == '/') {
return _joinAndCanonicalizePath(parts);
}
var /** @type {?} */ path = baseParts[_ComponentIndex.Path];
if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__facade_lang__["d" /* isBlank */])(path))
path = '/';
var /** @type {?} */ index = path.lastIndexOf('/');
path = path.substring(0, index + 1) + parts[_ComponentIndex.Path];
parts[_ComponentIndex.Path] = path;
return _joinAndCanonicalizePath(parts);
} | javascript | {
"resource": ""
} |
q30923 | convertPropertyBinding | train | function convertPropertyBinding(builder, nameResolver, implicitReceiver, expression, bindingId) {
var /** @type {?} */ currValExpr = createCurrValueExpr(bindingId);
var /** @type {?} */ stmts = [];
if (!nameResolver) {
nameResolver = new DefaultNameResolver();
}
var /** @type {?} */ visitor = new _AstToIrVisitor(builder, nameResolver, implicitReceiver, VAL_UNWRAPPER_VAR, bindingId, false);
var /** @type {?} */ outputExpr = expression.visit(visitor, _Mode.Expression);
if (!outputExpr) {
// e.g. an empty expression was given
return null;
}
if (visitor.temporaryCount) {
for (var /** @type {?} */ i = 0; i < visitor.temporaryCount; i++) {
stmts.push(temporaryDeclaration(bindingId, i));
}
}
if (visitor.needsValueUnwrapper) {
var /** @type {?} */ initValueUnwrapperStmt = VAL_UNWRAPPER_VAR.callMethod('reset', []).toStmt();
stmts.push(initValueUnwrapperStmt);
}
stmts.push(currValExpr.set(outputExpr).toDeclStmt(null, [__WEBPACK_IMPORTED_MODULE_3__output_output_ast__["k" /* StmtModifier */].Final]));
if (visitor.needsValueUnwrapper) {
return new ConvertPropertyBindingResult(stmts, currValExpr, VAL_UNWRAPPER_VAR.prop('hasWrappedValue'));
}
else {
return new ConvertPropertyBindingResult(stmts, currValExpr, null);
}
} | javascript | {
"resource": ""
} |
q30924 | train | function (prototype) {
// if the prototype is ZoneAwareError.prototype
// we just return the prebuilt errorProperties.
if (prototype === ZoneAwareError.prototype) {
return errorProperties;
}
var newProps = Object.create(null);
var cKeys = Object.getOwnPropertyNames(errorProperties);
var keys = Object.getOwnPropertyNames(prototype);
cKeys.forEach(function (cKey) {
if (keys.filter(function (key) {
return key === cKey;
})
.length === 0) {
newProps[cKey] = errorProperties[cKey];
}
});
return newProps;
} | javascript | {
"resource": ""
} | |
q30925 | ZoneAwareError | train | function ZoneAwareError() {
// make sure we have a valid this
// if this is undefined(call Error without new) or this is global
// or this is some other objects, we should force to create a
// valid ZoneAwareError by call Object.create()
if (!(this instanceof ZoneAwareError)) {
return ZoneAwareError.apply(Object.create(ZoneAwareError.prototype), arguments);
}
// Create an Error.
var error = NativeError.apply(this, arguments);
this[__symbol__('error')] = error;
// Save original stack trace
error.originalStack = error.stack;
// Process the stack trace and rewrite the frames.
if (ZoneAwareError[stackRewrite] && error.originalStack) {
var frames_1 = error.originalStack.split('\n');
var zoneFrame = _currentZoneFrame;
var i = 0;
// Find the first frame
while (frames_1[i] !== zoneAwareFrame && i < frames_1.length) {
i++;
}
for (; i < frames_1.length && zoneFrame; i++) {
var frame = frames_1[i];
if (frame.trim()) {
var frameType = blackListedStackFrames.hasOwnProperty(frame) && blackListedStackFrames[frame];
if (frameType === FrameType.blackList) {
frames_1.splice(i, 1);
i--;
}
else if (frameType === FrameType.transition) {
if (zoneFrame.parent) {
// This is the special frame where zone changed. Print and process it accordingly
frames_1[i] += " [" + zoneFrame.parent.zone.name + " => " + zoneFrame.zone.name + "]";
zoneFrame = zoneFrame.parent;
}
else {
zoneFrame = null;
}
}
else {
frames_1[i] += " [" + zoneFrame.zone.name + "]";
}
}
}
error.stack = error.zoneAwareStack = frames_1.join('\n');
}
// use defineProperties here instead of copy property value
// because of issue #595 which will break angular2.
Object.defineProperties(this, getErrorPropertiesForPrototype(Object.getPrototypeOf(this)));
return this;
} | javascript | {
"resource": ""
} |
q30926 | createI18nMessageFactory | train | function createI18nMessageFactory(interpolationConfig) {
var /** @type {?} */ visitor = new _I18nVisitor(_expParser, interpolationConfig);
return function (nodes, meaning, description) {
return visitor.toI18nMessage(nodes, meaning, description);
};
} | javascript | {
"resource": ""
} |
q30927 | _getOuterContainerOrSelf | train | function _getOuterContainerOrSelf(node) {
var /** @type {?} */ view = node.view;
while (_isNgContainer(node.parent, view)) {
node = node.parent;
}
return node;
} | javascript | {
"resource": ""
} |
q30928 | _getOuterContainerParentOrSelf | train | function _getOuterContainerParentOrSelf(el) {
var /** @type {?} */ view = el.view;
while (_isNgContainer(el, view)) {
el = el.parent;
}
return el;
} | javascript | {
"resource": ""
} |
q30929 | train | function(TYPE){
var IS_MAP = TYPE == 1
, IS_EVERY = TYPE == 4;
return function(object, callbackfn, that /* = undefined */){
var f = ctx(callbackfn, that, 3)
, O = toIObject(object)
, result = IS_MAP || TYPE == 7 || TYPE == 2
? new (typeof this == 'function' ? this : Dict) : undefined
, key, val, res;
for(key in O)if(has(O, key)){
val = O[key];
res = f(val, key, object);
if(TYPE){
if(IS_MAP)result[key] = res; // map
else if(res)switch(TYPE){
case 2: result[key] = val; break; // filter
case 3: return true; // some
case 5: return val; // find
case 6: return key; // findKey
case 7: result[res[0]] = res[1]; // mapPairs
} else if(IS_EVERY)return false; // every
}
}
return TYPE == 3 || IS_EVERY ? IS_EVERY : result;
};
} | javascript | {
"resource": ""
} | |
q30930 | _sha512crypt_intermediate | train | function _sha512crypt_intermediate(password, salt) {
var digest_a = rstr_sha512(password + salt);
var digest_b = rstr_sha512(password + salt + password);
var key_len = password.length;
// extend digest b so that it has the same size as password
var digest_b_extended = _extend(digest_b, password.length);
var intermediate_input = password + salt + digest_b_extended;
for (cnt = key_len; cnt > 0; cnt >>= 1) {
if ((cnt & 1) != 0)
intermediate_input += digest_b
else
intermediate_input += password;
}
var intermediate = rstr_sha512(intermediate_input);
return intermediate;
} | javascript | {
"resource": ""
} |
q30931 | use | train | function use(events, middleware)
{
// if no middleware supplied assume it's single argument call
if (!middleware)
{
middleware = events;
events = null;
}
// make it uniform
events = normalizeEvents(events);
// store middleware per event
events.forEach(function(e)
{
// bind middleware to the current context
(this._stack[e] = this._stack[e] || []).push(middleware.bind(this));
// make mark in history
this.logger.debug({message: 'Added middleware to the stack', event: e, middleware: middleware});
}.bind(this));
} | javascript | {
"resource": ""
} |
q30932 | run | train | function run(events, payload, callback)
{
// if no callback supplied assume it's two arguments call
if (!callback)
{
callback = payload;
payload = events;
events = null;
}
// make it uniform
events = normalizeEvents(events);
// apply events/middleware asynchronously and sequentially
pipeline(events, payload, function(e, data, cb)
{
if (!Array.isArray(this._stack[e]))
{
this.logger.debug({message: 'Reached end of the stack', event: e, data: data});
cb(null, payload);
return;
}
pipeline(this._stack[e], data, tryCall, cb);
}.bind(this), callback);
} | javascript | {
"resource": ""
} |
q30933 | normalizeEvents | train | function normalizeEvents(events)
{
// start with converting falsy events into catch-all placeholder
events = events || entryPoint;
if (!Array.isArray(events))
{
events = [events];
}
// return shallow copy
return events.concat();
} | javascript | {
"resource": ""
} |
q30934 | generateMessage | train | function generateMessage(type, data)
{
var message;
switch (type)
{
// default message type, no need to perform special actions, will be sent as is
case types.MESSAGE:
message = data;
break;
case types.TEXT:
// `text` must be UTF-8 and has a 320 character limit
// https://developers.facebook.com/docs/messenger-platform/send-api-reference/text-message
message = {text: data.substr(0, 320)};
break;
case types.AUDIO:
case types.FILE:
case types.IMAGE:
case types.VIDEO:
message = {attachment: {type: type, payload: {url: data}}};
break;
case types.QUICK_REPLIES:
// `quick_replies` is limited to 10
// https://developers.facebook.com/docs/messenger-platform/send-api-reference/quick-replies
message = {text: data.text, quick_replies: data.quick_replies.slice(0, 10)};
break;
case types.GENERIC:
message = templates.generic.call(this, data);
break;
case types.BUTTON:
message = templates.button.call(this, data);
break;
case types.RECEIPT:
message = templates.receipt.call(this, data);
break;
default:
this.logger.error({message: 'Unrecognized message type', type: type, payload: data});
}
return message;
} | javascript | {
"resource": ""
} |
q30935 | request | train | function request(url, options, callback)
{
var connection;
if (typeof options == 'function')
{
callback = options;
options = {};
}
connection = hyperquest(url, options, once(function(error, response)
{
if (error)
{
callback(error, response);
return;
}
// set body
response.body = '';
// accumulate response body
response.on('data', function(data)
{
response.body += data.toString();
});
response.on('end', function()
{
callback(null, response);
});
}));
return connection;
} | javascript | {
"resource": ""
} |
q30936 | parseJson | train | function parseJson(payload)
{
var data;
try
{
data = JSON.parse(payload);
}
catch (e)
{
this.logger.error({message: 'Unable to parse provided JSON', error: e, payload: payload});
}
return data;
} | javascript | {
"resource": ""
} |
q30937 | userInit | train | function userInit(payload, callback)
{
var type = messaging.getType(payload);
if (payload.sender && payload[type])
{
// detach new object from the source
payload[type].user = clone(payload.sender);
// add user tailored send functions
// but keep it outside of own properties
payload[type].user.__proto__ = {send: send.factory(this, payload[type].user)};
}
callback(null, payload);
} | javascript | {
"resource": ""
} |
q30938 | quickReply | train | function quickReply(payload, callback)
{
if (typeof payload.payload != 'string')
{
payload.payload = JSON.stringify(payload.payload);
}
callback(null, payload);
} | javascript | {
"resource": ""
} |
q30939 | actionCreator | train | function actionCreator(type) {
var props = Array.isArray(arguments[1]) ? arguments[1] : slice.call(arguments, 1)
return function() {
if (!props.length) {
return {type: type}
}
var args = slice.call(arguments)
return props.reduce(function(action, prop, index) {
return (action[prop] = args[index], action)
}, {type: type})
}
} | javascript | {
"resource": ""
} |
q30940 | optionsActionCreator | train | function optionsActionCreator(type) {
var props = Array.isArray(arguments[1]) ? arguments[1] : slice.call(arguments, 1)
return function(options) {
var copyProps = props.length === 0 ? Object.keys(options) : props
return copyProps.reduce(function(action, prop) {
return (action[prop] = options[prop], action)
}, {type: type})
}
} | javascript | {
"resource": ""
} |
q30941 | typeCast | train | function typeCast(payload, callback)
{
var type = find(types, function(t){ return (t in payload); });
if (type)
{
payload.type = normalize(type);
}
callback(null, payload);
} | javascript | {
"resource": ""
} |
q30942 | buttonPostback | train | function buttonPostback(payload, callback)
{
if (typeof payload.payload != 'string')
{
payload.payload = JSON.stringify(payload.payload);
}
callback(null, payload);
} | javascript | {
"resource": ""
} |
q30943 | train | function () {
return {
centered: this.centered,
speedFactor: this.speedFactor * (this._globalOptions.baseSpeedFactor || 1),
radius: this.radius,
color: this.color
};
} | javascript | {
"resource": ""
} | |
q30944 | isNativeFormElement | train | function isNativeFormElement(element) {
var /** @type {?} */ nodeName = element.nodeName.toLowerCase();
return nodeName === 'input' ||
nodeName === 'select' ||
nodeName === 'button' ||
nodeName === 'textarea';
} | javascript | {
"resource": ""
} |
q30945 | hasValidTabIndex | train | function hasValidTabIndex(element) {
if (!element.hasAttribute('tabindex') || element.tabIndex === undefined) {
return false;
}
var /** @type {?} */ tabIndex = element.getAttribute('tabindex');
// IE11 parses tabindex="" as the value "-32768"
if (tabIndex == '-32768') {
return false;
}
return !!(tabIndex && !isNaN(parseInt(tabIndex, 10)));
} | javascript | {
"resource": ""
} |
q30946 | getTabIndexValue | train | function getTabIndexValue(element) {
if (!hasValidTabIndex(element)) {
return null;
}
// See browser issue in Gecko https://bugzilla.mozilla.org/show_bug.cgi?id=1128054
var /** @type {?} */ tabIndex = parseInt(element.getAttribute('tabindex'), 10);
return isNaN(tabIndex) ? -1 : tabIndex;
} | javascript | {
"resource": ""
} |
q30947 | isPotentiallyTabbableIOS | train | function isPotentiallyTabbableIOS(element) {
var /** @type {?} */ nodeName = element.nodeName.toLowerCase();
var /** @type {?} */ inputType = nodeName === 'input' && ((element)).type;
return inputType === 'text'
|| inputType === 'password'
|| nodeName === 'select'
|| nodeName === 'textarea';
} | javascript | {
"resource": ""
} |
q30948 | applyCssTransform | train | function applyCssTransform(element, transformValue) {
// It's important to trim the result, because the browser will ignore the set operation
// if the string contains only whitespace.
var /** @type {?} */ value = transformValue.trim();
element.style.transform = value;
element.style.webkitTransform = value;
} | javascript | {
"resource": ""
} |
q30949 | train | function () {
if (this._multiple) {
var /** @type {?} */ selectedOptions = this._selectionModel.selected.map(function (option) { return option.viewValue; });
if (this._isRtl()) {
selectedOptions.reverse();
}
// TODO(crisbeto): delimiter should be configurable for proper localization.
return selectedOptions.join(', ');
}
return this._selectionModel.selected[0].viewValue;
} | javascript | {
"resource": ""
} | |
q30950 | train | function () {
var /** @type {?} */ axis = this.vertical ? 'Y' : 'X';
// For a horizontal slider in RTL languages we push the ticks container off the left edge
// instead of the right edge to avoid causing a horizontal scrollbar to appear.
var /** @type {?} */ sign = !this.vertical && this._direction == 'rtl' ? '' : '-';
var /** @type {?} */ offset = this._tickIntervalPercent / 2 * 100;
return {
'transform': "translate" + axis + "(" + sign + offset + "%)"
};
} | javascript | {
"resource": ""
} | |
q30951 | train | function () {
var /** @type {?} */ tickSize = this._tickIntervalPercent * 100;
var /** @type {?} */ backgroundSize = this.vertical ? "2px " + tickSize + "%" : tickSize + "% 2px";
var /** @type {?} */ axis = this.vertical ? 'Y' : 'X';
// Depending on the direction we pushed the ticks container, push the ticks the opposite
// direction to re-center them but clip off the end edge. In RTL languages we need to flip the
// ticks 180 degrees so we're really cutting off the end edge abd not the start.
var /** @type {?} */ sign = !this.vertical && this._direction == 'rtl' ? '-' : '';
var /** @type {?} */ rotate = !this.vertical && this._direction == 'rtl' ? ' rotate(180deg)' : '';
var /** @type {?} */ styles = {
'backgroundSize': backgroundSize,
// Without translateZ ticks sometimes jitter as the slider moves on Chrome & Firefox.
'transform': "translateZ(0) translate" + axis + "(" + sign + tickSize / 2 + "%)" + rotate
};
if (this._isMinValue && this._thumbGap) {
var /** @type {?} */ side = this.vertical ?
(this._invertAxis ? 'Bottom' : 'Top') :
(this._invertAxis ? 'Right' : 'Left');
styles["padding" + side] = this._thumbGap + "px";
}
return styles;
} | javascript | {
"resource": ""
} | |
q30952 | polarToCartesian | train | function polarToCartesian(radius, pathRadius, angleInDegrees) {
var /** @type {?} */ angleInRadians = (angleInDegrees - 90) * DEGREE_IN_RADIANS;
return (radius + (pathRadius * Math.cos(angleInRadians))) +
',' + (radius + (pathRadius * Math.sin(angleInRadians)));
} | javascript | {
"resource": ""
} |
q30953 | materialEase | train | function materialEase(currentTime, startValue, changeInValue, duration) {
var /** @type {?} */ time = currentTime / duration;
var /** @type {?} */ timeCubed = Math.pow(time, 3);
var /** @type {?} */ timeQuad = Math.pow(time, 4);
var /** @type {?} */ timeQuint = Math.pow(time, 5);
return startValue + changeInValue * ((6 * timeQuint) + (-15 * timeQuad) + (10 * timeCubed));
} | javascript | {
"resource": ""
} |
q30954 | getSvgArc | train | function getSvgArc(currentValue, rotation) {
var /** @type {?} */ startPoint = rotation || 0;
var /** @type {?} */ radius = 50;
var /** @type {?} */ pathRadius = 40;
var /** @type {?} */ startAngle = startPoint * MAX_ANGLE;
var /** @type {?} */ endAngle = currentValue * MAX_ANGLE;
var /** @type {?} */ start = polarToCartesian(radius, pathRadius, startAngle);
var /** @type {?} */ end = polarToCartesian(radius, pathRadius, endAngle + startAngle);
var /** @type {?} */ arcSweep = endAngle < 0 ? 0 : 1;
var /** @type {?} */ largeArcFlag;
if (endAngle < 0) {
largeArcFlag = endAngle >= -180 ? 0 : 1;
}
else {
largeArcFlag = endAngle <= 180 ? 0 : 1;
}
return "M" + start + "A" + pathRadius + "," + pathRadius + " 0 " + largeArcFlag + "," + arcSweep + " " + end;
} | javascript | {
"resource": ""
} |
q30955 | clamp$1 | train | function clamp$1(v, min, max) {
if (min === void 0) { min = 0; }
if (max === void 0) { max = 100; }
return Math.max(min, Math.min(max, v));
} | javascript | {
"resource": ""
} |
q30956 | train | function (origin) {
if (origin == null) {
return;
}
var /** @type {?} */ dir = this._getLayoutDirection();
if ((dir == 'ltr' && origin <= 0) || (dir == 'rtl' && origin > 0)) {
this._origin = 'left';
}
else {
this._origin = 'right';
}
} | javascript | {
"resource": ""
} | |
q30957 | train | function (value) {
if (!this._isValidIndex(value) || this._focusIndex == value) {
return;
}
this._focusIndex = value;
this.indexFocused.emit(value);
this._setTabFocus(value);
} | javascript | {
"resource": ""
} | |
q30958 | train | function (v) {
this._scrollDistance = Math.max(0, Math.min(this._getMaxScrollDistance(), v));
// Mark that the scroll distance has changed so that after the view is checked, the CSS
// transformation can move the header.
this._scrollDistanceChanged = true;
this._checkScrollingControls();
} | javascript | {
"resource": ""
} | |
q30959 | train | function (classes) {
this._classList = classes.split(' ').reduce(function (obj, className) {
obj[className] = true;
return obj;
}, {});
this.setPositionClasses(this.positionX, this.positionY);
} | javascript | {
"resource": ""
} | |
q30960 | train | function () {
return __WEBPACK_IMPORTED_MODULE_4_rxjs_Observable__["Observable"].merge.apply(__WEBPACK_IMPORTED_MODULE_4_rxjs_Observable__["Observable"], this.autocomplete.options.map(function (option) { return option.onSelectionChange; }));
} | javascript | {
"resource": ""
} | |
q30961 | verifyEndpoint | train | function verifyEndpoint(request, respond)
{
var challenge;
if (typeof request.query == 'string')
{
request.query = qs.parse(request.query);
}
if (typeof request.query == 'object'
&& ((request.query['hub.verify_token'] === this.credentials.secret)
// for hapi@10 and restify/express with queryParser check for `hub` object
|| (typeof request.query.hub == 'object' && request.query.hub['verify_token'] === this.credentials.secret)
)
)
{
challenge = request.query['hub.challenge'] || (request.query.hub ? request.query.hub.challenge : null);
this.logger.debug({message: 'Successfully verified', challenge: challenge});
respond(challenge);
return;
}
this.logger.error({message: 'Unable to verify endpoint', query: request.query});
respond(400, 'Error, wrong validation token');
} | javascript | {
"resource": ""
} |
q30962 | train | function (options, send) {
var clientPath = options.clientPath,
coverage = options.coverage,
parentId = options.parentId,
configuration = options.configuration,
globalConfig = options.globalConfig,
decorators = options.decorators,
decoratorPlugins = options.decoratorPlugins,
ClientClass,
clientInstance,
coverageVar = '__preceptorCoverage__',
instrumenter,
transformer,
globalCoverageConfig = globalConfig.coverage,
coverageIncludes = globalCoverageConfig.includes || ['**/*.js'],
coverageExcludes = globalCoverageConfig.excludes || ['**/node_modules/**', '**/test/**', '**/tests/**'];
// Make global configuration available
global.PRECEPTOR = {
config: globalConfig
};
// Create client and run it
ClientClass = require(clientPath);
clientInstance = new ClientClass(decorators, decoratorPlugins, configuration);
clientInstance.on('reportMessage', function (messageType, data) {
send({
type: "reportMessage",
messageType: messageType,
data: data
});
});
// Is coverage requested?
if (((coverage === undefined) || (coverage === true)) && globalCoverageConfig.active) {
// Prepare coverage instrumentation
instrumenter = new istanbul.Instrumenter({ coverageVariable: coverageVar, preserveComments: true });
transformer = instrumenter.instrumentSync.bind(instrumenter);
// Hook-up transformer for every new file loaded
istanbul.hook.hookRequire(function (filePath) {
var allowed = false;
// Inclusion
_.each(coverageIncludes, function (include) {
allowed = allowed || minimatch(filePath, include);
});
if (allowed) {
// Exclusion
_.each(coverageExcludes, function (exclude) {
allowed = allowed && !minimatch(filePath, exclude);
});
}
return allowed;
}, transformer, {});
// Prepare variable
global[coverageVar] = {};
}
// Run client
clientInstance.run(parentId).then(function () {
send({
type: "completion",
data: {
success: true,
coverage: global[coverageVar]
}
});
global[coverageVar] = {}; // Reset
}, function (err) {
send({
type: "completion",
data: {
success: false,
coverage: global[coverageVar],
context: err.stack
}
});
global[coverageVar] = {}; // Reset
});
} | javascript | {
"resource": ""
} | |
q30963 | train | function(summary) {
// If the file contains an h2, we need to reformat it
if (summary.content.match(/^## /m)) {
var parts = summary.content.split(/(?=##)/);
for (var i = 0; i < parts.length; i++) {
// Remove any blank lines
parts[i] = parts[i].replace(/(\*.*)\n\n/gm, "$1\n");
// If the part has a heading, replace it and indent the child items in the list
// Mark a heading as a part by smuggling some text into the list item.
// Messy, but it's the only way.
if (parts[i].indexOf('##') == 0) {
parts[i] = parts[i].replace(/^([ \t]*\* .+)$/gm, " $1")
.replace(/^## (.*)$/gm, "* -XPARTX-$1")
}
}
summary.content = parts.join('');
}
return summary;
} | javascript | {
"resource": ""
} | |
q30964 | train | function(page) {
var $ = cheerio.load(page.content);
// Replace top level li.chapter with li.part
$('ul.summary > li.chapter').each(function(i, elem) {
var li = $(elem);
// Replace the classes if the chapter is actually a part, and add a divider
if (li.text().indexOf('-XPARTX-') > 0) {
li.removeClass('chapter');
li.addClass('part');
// Don't add a divider before the first part, let it come straight after the Introduction page
if (i > 1)
li.before('<li class="part divider" />');
}
});
// remove chapter numbers from any intro pages (and child pages)
$('ul.summary > li.chapter span > b').remove();
$('ul.summary > li.chapter a > b').remove();
// Remove the chapter number from the part header
$('ul.summary > li.part > span > b').remove();
$('ul.summary > li.part > a > b').remove();
// Replace the nasty munging of the name for part heading
$('ul.summary > li.part > span').each(function(i, elem) {
var span = $(elem);
span.text(span.text().replace(/-XPARTX-/, ""));
});
// Bump the remaining chapter numbers so each chapter is only unique
// within the part
$('ul.summary > li.part li.chapter b').each(function(i, elem) {
var b = $(elem);
var text = b.text();
var index = text.indexOf('.');
if (index > -1)
b.text(text.substring(index + 1));
});
page.content = $.html();
return page;
} | javascript | {
"resource": ""
} | |
q30965 | Fbbot | train | function Fbbot(options)
{
if (!(this instanceof Fbbot)) return new Fbbot(options);
/**
* Custom options per instance
* @type {object}
*/
this.options = merge(Fbbot.defaults, options || {});
/**
* Store credentials
* @type {object}
*/
this.credentials =
{
// keep simple naming for internal reference
token : this.options.pageAccessToken || this.options.token,
secret: this.options.verifyToken || this.options.secret
};
if (!this.credentials.token || !this.credentials.secret)
{
throw new Error('Both `token` (pageAccessToken) and `secret` (verifyToken) are required');
}
// compose apiUrl
this.options.apiUrl += this.credentials.token;
/**
* expose logger
* @type {object}
*/
this.logger = options.logger || bole(options.name || 'fbbot');
/**
* middleware storage (per event)
* @type {object}
* @private
*/
this._stack = {};
/**
* lock-in public methods
* wrap `_handler` with agnostic to accommodate different http servers
* @type {function}
*/
this.requestHandler = agnostic(this._handler.bind(this));
// attach lifecycle filters
inMiddleware(this);
outMiddleware(this);
/**
* create incoming traverse paths
* @type {Traverse}
* @private
*/
this._incoming = new Traverse(inTraverse.steps, {
entry : middleware.entryPoint,
middleware: inTraverse.middleware.bind(this),
emitter : inTraverse.emitter.bind(this),
prefix : inTraverse.prefix
});
// wrap linkParent method
this._incoming.linkParent = inTraverse.linkParent.bind(null, this._incoming.linkParent);
/**
* create outgoing traverse paths
* @type {Traverse}
* @private
*/
this._outgoing = new Traverse(outTraverse.steps, {
middleware: outTraverse.middleware.bind(this),
emitter : outTraverse.emitter.bind(this),
prefix : outTraverse.prefix
});
// wrap linkParent method
this._outgoing.linkParent = outTraverse.linkParent.bind(null, this._outgoing.linkParent);
} | javascript | {
"resource": ""
} |
q30966 | read | train | function read(mode,callback) {
if (spi === undefined) {return;};
var txBuf = new Buffer([1,mode,0]);
var rxBuf = new Buffer([0,0,0]);
spi.transfer(txBuf,rxBuf,function(dev,buffer) {
var value = ((buffer[1] & 3)<< 8) + buffer[2];
callback(value);
});
} | javascript | {
"resource": ""
} |
q30967 | train | function(callback) {
grunt.log.writeln('Prepare tmp path...');
if (!grunt.file.isDir(tmpPath)) {
if (grunt.file.exists(tmpPath)) {
callback(new Error(util.format('"%s" is not a directory', tmpPath)));
}
else {
grunt.file.mkdir(tmpPath);
callback(null);
}
}
else {
callback(null);
}
} | javascript | {
"resource": ""
} | |
q30968 | train | function(callback) {
grunt.log.writeln('Push to tmp path...');
// remove
if (options.remove) {
grunt.file.recurse(tmpPath, function(abs, rootdir, subdir, filename) {
if (typeof subdir !== 'string') {
subdir = '';
}
var subPath = path.join(subdir, filename);
if (testIgnore(subPath, ['.svn', '.git'])) {
return;
}
if (
!grunt.file.exists(path.join(src, subPath)) &&
!grunt.file.isMatch(options.removeIgnore, subPath)
) {
// remove it
grunt.log.writeln(util.format('Remove "%s"...', subPath));
grunt.file.delete(abs);
}
});
}
// copy
grunt.file.recurse(src, function(abs, rootdir, subdir, filename) {
if (typeof subdir !== 'string') {
subdir = '';
}
var subPath = path.join(subdir, filename),
srcFile = abs,
destFile = path.join(tmpPath, subPath),
srcStats = fs.statSync(srcFile),
destStats;
if (testIgnore(subPath, ['.svn', '.git'])) {
return;
}
if (!options.pushIgnore || !grunt.file.isMatch(options.pushIgnore, subPath)) {
// dir
if (grunt.file.isDir(srcFile)) {
if (!grunt.file.isDir(destFile)) {
if (grunt.file.exists(destFile)) {
grunt.file.delete(destFile);
}
grunt.log.writeln(util.format('Create folder "%s"...', subPath));
grunt.file.mkdir(destFile);
}
}
else {
if (grunt.file.isDir(destFile)) {
grunt.file.delete(destFile);
}
else if (grunt.file.exists(destFile)) {
destStats = fs.statSync(destFile);
if (srcStats.size !== destStats.size || (destStats.mtime - srcStats.mtime !== 0)) {
grunt.log.writeln(util.format('Push changed file "%s"...', subPath));
grunt.file.copy(srcFile, destFile);
fs.utimesSync(destFile, srcStats.atime, srcStats.mtime);
}
}
else {
grunt.log.writeln(util.format('Push new file "%s"...', subPath));
grunt.file.copy(srcFile, destFile);
fs.utimesSync(destFile, srcStats.atime, srcStats.mtime);
}
}
}
});
callback(null);
} | javascript | {
"resource": ""
} | |
q30969 | linkParent | train | function linkParent(original, branch, parentPayload, nextPayload)
{
// get proper name
var normalized = normalize(branch);
var result = original(branch, parentPayload, nextPayload);
// add normalized handle reference
// skip if it's empty string
if (normalized)
{
result.__proto__[normalized] = parentPayload;
}
// add user object reference
if (parentPayload.user)
{
result.__proto__['user'] = parentPayload.user;
}
return result;
} | javascript | {
"resource": ""
} |
q30970 | middleware | train | function middleware(branch, payload, callback)
{
// get proper name
var normalized = normalize(branch);
this.logger.debug({message: 'Running middleware for incoming payload', branch: branch, normalized: normalized, payload: payload});
// add branch reference to the parent object
// run through all registered middleware
this._run(normalized, payload, function(error, resolvedPayload)
{
var normalizeType;
if (payload.type)
{
normalizeType = normalize(payload.type);
this._run([normalized, normalizeType].join('.'), resolvedPayload, callback);
}
// be done here
else
{
callback(error, resolvedPayload);
}
}.bind(this));
} | javascript | {
"resource": ""
} |
q30971 | sign | train | function sign(options, cb) {
return new Promise(function (resolve, reject) {
options = options || {};
if (!options.content)
throw new Error('Invalid content.');
if (!options.key)
throw new Error('Invalid key.');
if (!options.cert)
throw new Error('Invalid certificate.');
var command = util.format(
'openssl smime -sign -text -signer %s -inkey %s -outform DER -binary',
options.cert,
options.key
);
if (options.password)
command += util.format(' -passin pass:%s', options.password);
var args = command.split(' ');
var child = spawn(args[0], args.splice(1));
var der = [];
child.stdout.on('data', function (chunk) {
der.push(chunk);
});
child.on('close', function (code) {
if (code !== 0)
reject(new Error('Process failed.'));
else
resolve({
child: child,
der: Buffer.concat(der)
});
});
options.content.pipe(child.stdin);
})
.nodeify(cb);
} | javascript | {
"resource": ""
} |
q30972 | attach | train | function attach(filters, instance)
{
Object.keys(filters).forEach(function(step)
{
filters[step].forEach(function(filter)
{
instance.use(step, filter);
});
});
} | javascript | {
"resource": ""
} |
q30973 | train | function() {
return new Promise(function(resolve, reject) {
VkSdkLoginManager.authorize(function(error, result) {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
} | javascript | {
"resource": ""
} | |
q30974 | pipeline | train | function pipeline(list, payload, handler, callback)
{
var item;
if (!list.length)
{
callback(null, payload);
return;
}
list = list.concat();
item = list.shift();
// pipeline it
handler(item, payload, async(function(err, updatedPayload)
{
if (err)
{
callback(err, updatedPayload);
return;
}
// rinse, repeat
pipeline(list, updatedPayload, handler, callback);
}));
} | javascript | {
"resource": ""
} |
q30975 | gte | train | function gte(num1, num2, message) {
var output,
input = {
operand1: num1,
operand2: num2,
expected: 1, // Untrue but... internal usage, so meh!
message: message
},
cleanedInput = _validateAndClean(input),
pushContext = _getPushContext(this);
if (cleanedInput) {
// Array-ify
cleanedInput.expected = [0, 1];
output = _compare(cleanedInput);
pushContext.push(output.result, output.actual, output.expected, output.message);
}
} | javascript | {
"resource": ""
} |
q30976 | Store | train | function Store(name, id, keys, optionalEngine) {
this.id = id;
this.name = name;
this.keys = keys || {};
this.engine = optionalEngine || defaultEngine;
} | javascript | {
"resource": ""
} |
q30977 | renderToString | train | function renderToString(page) {
var layout = null, child = null, props = {};
while ((layout = page.type.layout || (page.defaultProps && page.defaultProps.layout))) {
child = React.createElement(page, props, child);
_.extend(props, page.defaultProps);
React.renderToString(React.createElement(page, props, child));
page = layout;
}
return React.renderToString(React.createElement(page, props, child));
} | javascript | {
"resource": ""
} |
q30978 | deserialize | train | function deserialize(json) {
var data, deserialized;
var includedMap = {};
each(json.included, function(value) {
var key = value.type + '-' + value.id;
includedMap[key] = value;
});
if (isArray(json.data)) {
data = map(
json.data,
function(record) {
populateRelatedFields(record, includedMap);
return flatten(record);
}
);
}
else if (isObject(json.data)) {
populateRelatedFields(json.data, includedMap);
data = flatten(json.data);
}
deserialized = {
data: data,
jsonapi: json.jsonapi || {}
};
if (json.meta) {
deserialized.meta = json.meta;
}
if (json.errors) {
deserialized.errors = json.errors;
}
if (json.links) {
deserialized.links = json.links;
}
return deserialized;
} | javascript | {
"resource": ""
} |
q30979 | populateRelatedFields | train | function populateRelatedFields(record, includedMap, parents) {
// IF: Object has relationships, update so this record is listed as a parent
if (record.relationships) {
parents = parents ? parents.concat([record]) : [record] ;
}
each(
record.relationships,
function(relationship, property) {
// IF: relationship describes non-record specific meta;
// append relationship meta to the record
if (relationship && isObject(relationship.meta)) {
record.meta = record.meta || {};
record.meta[property] = relationship.meta;
}
// IF: No relationship data, don't add anything
if (!relationship.data) {
return;
}
// IF: Relationship has multiple matches, create an array for matched records
// ELSE: Assign relationship directly to the property
if (isArray(relationship.data)) {
record.attributes[property] = map(
relationship.data,
function(data) {
return getMatchingRecord(data, includedMap, parents);
}
);
}
else {
record.attributes[property] = getMatchingRecord(
relationship.data,
includedMap,
parents
);
}
}
);
} | javascript | {
"resource": ""
} |
q30980 | getMatchingRecord | train | function getMatchingRecord(relationship, included, parents) {
var circular, match;
circular = findWhere(
parents,
{
id: relationship.id,
type: relationship.type
}
);
if (circular) {
return relationship;
}
var key = relationship.type + '-' + relationship.id;
match = included[key];
// IF: No match or match is the same as parent, return the relationship information
if (!match) {
return relationship;
}
populateRelatedFields(match, included, parents);
// IF: relationship defined meta, merge with record provided meta
var contextSpecificMeta = {};
if (relationship && isObject(relationship.meta)) {
contextSpecificMeta = extend({}, match.meta, relationship.meta);
}
return flatten(match, contextSpecificMeta);
} | javascript | {
"resource": ""
} |
q30981 | flatten | train | function flatten(record, extraMeta) {
var meta = extend({}, record.meta, extraMeta)
return extend(
{},
{ links: record.links, meta: meta },
record.attributes,
{ id: record.id, type: record.type }
);
} | javascript | {
"resource": ""
} |
q30982 | extend | train | function extend(from, to, path, overrideLoc) {
for (var prop in from) {
if (!(prop in to) || (prop == "loc" && overrideLoc)) {
to[prop] = from[prop]
} else if (prop == "properties" || prop == "staticProperties") {
extend(from[prop], to[prop], path.concat(prop))
} else {
var msg = "Conflicting information for " + path.join(".") + "." + prop
if (to.loc) msg += " at " + to.loc.file + ":" + to.loc.line
if (from.loc) msg += (to.loc ? " and " : " at ") + from.loc.file + ":" + from.loc.line
throw new SyntaxError(msg)
}
}
return to
} | javascript | {
"resource": ""
} |
q30983 | getHeader | train | function getHeader(data, headerStart)
{
// 'start' position of the header.
let start = headerStart;
// 'end' position of the header.
let end = 0;
// 'partial end' position of the header.
let partialEnd = 0;
// End of message.
if (data.substring(start, start + 2).match(/(^\r\n)/))
{
return -2;
}
while (end === 0)
{
// Partial End of Header.
partialEnd = data.indexOf('\r\n', start);
// 'indexOf' returns -1 if the value to be found never occurs.
if (partialEnd === -1)
{
return partialEnd;
}
if (!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && data.charAt(partialEnd + 2).match(/(^\s+)/))
{
// Not the end of the message. Continue from the next position.
start = partialEnd + 2;
}
else
{
end = partialEnd;
}
}
return end;
} | javascript | {
"resource": ""
} |
q30984 | find | train | function find(prefix, suffix)
{
if(valStack.length > 0)
{
var currentVal = valStack[valStack.length - 1];
if(prefix.length > 0)
{
// Manipulate prefix and suffix
var currentField = prefix.shift();
suffix.push(currentField);
if(currentVal.hasOwnProperty(currentField))
{
if(prefix.length > 0)
{
valStack.push(currentVal[currentField]);
find(prefix, suffix);
valStack.pop();
}
else
{
//finalResults.push(currentVal[currentField]);
store(suffix, currentVal[currentField]);
}
}
else if(currentField == "$")
{
find(prefix, suffix);
}
else if(currentField == "*")
{
findInEachChild(prefix, suffix);
}
else if(currentField == "^")
{
findInParent(prefix, suffix);
}
else if(currentField == "~")
{
findInAllDescendants(prefix, suffix);
}
else if(currentField.indexOf(",") >= 0)
{
findMultiple(prefix, suffix);
}
else if(currentField.substr(0, 1) == "?")
{
findByCondition(currentField.replace(/^\?\((.*?)\)$/,"$1"), prefix, suffix);
}
else
{
// alert("Property not found");
// NOOP
}
// Restore prefix and suffix
prefix.unshift(suffix.pop());
}
else
{
// alert("prefix is empty!");
//finalResults.push(currentVal);
store(suffix, currentVal);
}
}
else
{
// alert("valStack is empty!");
// NOOP
}
} | javascript | {
"resource": ""
} |
q30985 | train | function(token) {
this.token = token;
this.baseUrl = 'https://api.telegram.org/bot' + this.token;
// A sample Telegram bot JSON data, for req options
this.formData = {
chat_id: "87654321",
text: "Hello there"
};
// template options for req the Telegram Bot API
this.baseoptions = {
method: 'POST',
baseUrl: this.baseUrl,
url: "sendMessage",
formData: this.formData
};
///////////////////////////////
// Internal, private methods //
///////////////////////////////
// Convert an data to format proper for HTTP methods
this.toHTTPProper = function(data) {
// currently serialize Array now, leave stream/string
return _.isArray(data) ? JSON.stringify(data) : data;
// return data;
}
// serialize a whole object proper for HTTP methods
// discard key-value pair if value is undefined
// only returns non-empty JSON
this.serialize = function(obj) {
// var ser = _.omit(
// _.mapValues(_.flattenJSON(obj), this.toHTTPProper)
// , _.isUndefined);
var ser = _.omit(
_.mapValues(obj, this.toHTTPProper)
, _.isUndefined);
if (!_.isEmpty(ser)) return ser;
}
// properly set req as its method
this.req = req;
// Extends the options for req for the Telegram Bot.
// @param {string} botMethod Telegram bot API method.
// @param {JSON} JSONdata A JSON object with the required fields (see API).
// @param {string} [HTTPMethod=POST] Optionally change method if need to.
// @returns {JSON} option The extended option.
//
// @example
// extOpt('sendMessage', {chat_id: 123456, text: 'hello world'})
// → {
// method: 'POST',
// baseUrl: 'https://api.telegram.org/bot...',
// url: 'sendMessage',
// formData: {chat_id: 123456, text: 'hello world'} }
this.extOpt = function(botMethod, JSONdata, HTTPMethod) {
var opt = _.clone({
method: 'POST',
baseUrl: this.baseUrl,
url: "sendMessage",
formData: this.formData
});
_.assign(opt, {
url: botMethod
})
if (JSONdata) _.assign(opt, {
formData: this.serialize(JSONdata)
})
if (HTTPMethod) _.assign(opt, {
botMethod: HTTPMethod
});
return opt;
}
// shorthand composition: bot's HTTP request
this.reqBot = _.flow(this.extOpt, this.req)
} | javascript | {
"resource": ""
} | |
q30986 | train | function(name, value) {
var header = { raw: value };
name = Utils.headerize(name);
if(this.headers[name]) {
this.headers[name].push(header);
} else {
this.headers[name] = [header];
}
} | javascript | {
"resource": ""
} | |
q30987 | train | function(name) {
var header = this.headers[Utils.headerize(name)];
if(header) {
if(header[0]) {
return header[0].raw;
}
} else {
return;
}
} | javascript | {
"resource": ""
} | |
q30988 | whitespace | train | function whitespace(layout) {
var whitespace = layout.size[0] * layout.size[1]
for (var i = 0; i < layout.boxes.length; i++) {
var box = layout.boxes[i]
whitespace -= box.size[0] * box.size[1]
}
return whitespace
} | javascript | {
"resource": ""
} |
q30989 | validate | train | function validate(boxes, box) {
var a = box
for (var i = 0; i < boxes.length; i++) {
var b = boxes[i]
if (intersects(a, b)) {
return false
}
}
return true
} | javascript | {
"resource": ""
} |
q30990 | intersects | train | function intersects(a, b) {
return a.position[0] < b.position[0] + b.size[0] && a.position[0] + a.size[0] > b.position[0]
&& a.position[1] < b.position[1] + b.size[1] && a.position[1] + a.size[1] > b.position[1]
} | javascript | {
"resource": ""
} |
q30991 | replaceStream | train | function replaceStream(needle, replacer) {
var ts = new Transform();
var chunks = [], len = 0, pos = 0;
ts._transform = function _transform(chunk, enc, cb) {
chunks.push(chunk);
len += chunk.length;
if (pos === 1) {
var data = Buffer.concat(chunks, len)
.toString()
.replace(needle, replacer);
// TODO: examine and profile garbage
chunks = [];
len = 0;
this.push(data);
}
pos = 1 ^ pos;
cb(null);
};
ts._flush = function _flush(cb) {
if (chunks.length) {
this.push(Buffer.concat(chunks, len)
.toString()
.replace(needle, replacer))
}
cb(null);
}
return ts;
} | javascript | {
"resource": ""
} |
q30992 | Callback | train | function Callback (connection, callbackId, callbackUrl, nuki) {
EventEmitter.call(this);
this.connection = connection;
this.nuki = nuki;
this.callbackId = callbackId;
this.url = callbackUrl;
} | javascript | {
"resource": ""
} |
q30993 | main | train | async function main () {
console.log(`\n\n[Single step producer]`);
const workers1 = [
new Producer(100),
new Producer(100),
new Producer(100),
new Producer(100),
new Producer(100),
new Consumer(200),
new Consumer(300),
];
await Promise.all(workers1.map(x => x.work()));
console.log(`\n\n[Efficient producer]`);
const workers2 = [
new EfficientProducer(10),
new Consumer(10),
new Consumer(10),
new Consumer(10),
new Consumer(10),
new Consumer(10),
new Consumer(10),
new Consumer(20),
new Consumer(20),
];
await Promise.all(workers2.map(x => x.work()));
console.log(`\n\n[RejectAll() API test]`);
const p = new Consumer(1).work();
stock.notempty.rejectAll();
p.then(
() => console.error(`[ERROR] This promise should not resolve.`),
err => console.log(`Successfully received a rejected Error - ${err.message}`)
);
} | javascript | {
"resource": ""
} |
q30994 | Bridge | train | function Bridge (ip, port, token, options) {
if (!(this instanceof Bridge)) {
return new Bridge(ip, port, token);
}
this.ip = ip;
this.port = parseInt(port, 10);
this.token = token;
this.delayBetweenRequests = options && options.delayBetweenRequests || 250;
this.delayer = Promise.resolve();
if (!this.ip || !this.port || !this.token || this.port < 1 || this.port > 65536) {
throw new Error('Please check the arguments!');
}
} | javascript | {
"resource": ""
} |
q30995 | verifyMailgun | train | function verifyMailgun(apikey, token, timestamp, signature) {
var data = [timestamp, token].join('');
var hmac = crypto.createHmac('sha256', apikey).update(data);
var ourSig = hmac.digest('hex');
var output = {
apikey: apikey,
token: token,
timestamp: timestamp,
signature: signature,
generatedSignature: ourSig,
valid: ourSig === signature
};
return output;
} | javascript | {
"resource": ""
} |
q30996 | TimestreamDB | train | function TimestreamDB(instance, options) {
if (!(this instanceof TimestreamDB))
return new TimestreamDB(instance, options)
var db = Version(instance, options)
db.ts = function (key, options) {
var opts = {reverse: true}
if (options.start) opts.minVersion = options.start
if (options.until) opts.maxVersion = options.until
return ts(db.versionStream(key, opts).pipe(toTimestream()))
}
db.timeStream = db.ts
return db
} | javascript | {
"resource": ""
} |
q30997 | Constraint | train | function Constraint(constraintName, constraintPayload) {
var name = constraintName;
var payload = constraintPayload;
/**
* The constraint name.
* @returns {String} a name
*/
this.getName = function () {
return name;
};
/**
* Sets the name of the constraint.
* @param {String} n name
*/
this.setName = function (n) {
name = n;
};
/**
* The payload (a map)
* @returns {Object} an object
*/
this.getPayload = function () {
return payload;
};
/**
* Sets the payload.
* @param {Object} p the payload object
*/
this.setPayload = function (p) {
payload = p;
};
} | javascript | {
"resource": ""
} |
q30998 | train | function (options) {
if (options.username && options.password) {
return (options.protocol + "://" + options.username + ":" + options.password + "@" + options.host + ":" + options.port + "/" + options.database)
}
return (options.protocol + "://" + options.host + ":" + options.port + "/" + options.database)
} | javascript | {
"resource": ""
} | |
q30999 | train | function () {
var len = this.points.length
// Check the length of the point buffer
if (len >= options.batchSize) {
// Write the points and log error if any
client.writePoints(this.points).catch(function (error) {
console.log(error.message)
})
// Reset point buffer
this.points = []
}
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.