_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q57900
|
checkClass
|
train
|
function checkClass(target) {
/*jshint validthis:true*/
var key,
value;
// Check normal functions
for (key in this[$interface].methods) {
value = this[$interface].methods[key];
if (!target[$class].methods[key]) {
throw new Error('Class "' + target.prototype.$name + '" does not implement interface "' + this.prototype.$name + '" correctly, method "' + key + '" was not found.');
}
if (!isFunctionCompatible(target[$class].methods[key], value)) {
throw new Error('Method "' + key + '(' + target[$class].methods[key].signature + ')" defined in class "' + target.prototype.$name + '" is not compatible with the one found in interface "' + this.prototype.$name + '": "' + key + '(' + value.signature + ')".');
}
}
// Check static functions
for (key in this[$interface].staticMethods) {
value = this[$interface].staticMethods[key];
if (!target[$class].staticMethods[key]) {
throw new Error('Class "' + target.prototype.$name + '" does not implement interface "' + this.prototype.$name + '" correctly, static method "' + key + '" was not found.');
}
if (!isFunctionCompatible(target[$class].staticMethods[key], value)) {
throw new Error('Static method "' + key + '(' + target[$class].staticMethods[key].signature + ')" defined in class "' + target.prototype.$name + '" is not compatible with the one found in interface "' + this.prototype.$name + '": "' + key + '(' + value.signature + ')".');
}
}
}
|
javascript
|
{
"resource": ""
}
|
q57901
|
assignConstant
|
train
|
function assignConstant(name, value, interf) {
if (hasDefineProperty) {
Object.defineProperty(interf, name, {
get: function () {
return value;
},
set: function () {
throw new Error('Cannot change value of constant property "' + name + '" of interface "' + this.prototype.$name + '".');
},
configurable: false,
enumerable: true
});
} else {
interf[name] = value;
}
}
|
javascript
|
{
"resource": ""
}
|
q57902
|
addConstant
|
train
|
function addConstant(name, value, interf) {
var target;
// Check if it is public
if (name.charAt(0) === '_') {
throw new Error('Interface "' + interf.prototype.$name + '" contains an unallowed non public method: "' + name + '".');
}
// Check if it is a primitive value
if (!isImmutable(value)) {
throw new Error('Value for constant property "' + name + '" defined in interface "' + interf.prototype.$name + '" must be a primitive type.');
}
target = interf[$interface].constants;
// Check if the constant already exists
if (target[name]) {
throw new Error('Cannot override constant property "' + name + '" in interface "' + interf.prototype.$name + '".');
}
target[name] = true;
assignConstant(name, value, interf);
}
|
javascript
|
{
"resource": ""
}
|
q57903
|
parseCookies
|
train
|
function parseCookies(req, res, next) {
var self = this;
var cookieHeader = req.headers.cookie;
if (cookieHeader) {
req.cookies = cookie.parse(cookieHeader);
} else {
req.cookies = {};
}
/**
* Add a cookie to our response. Uses a Set-Cookie header
* per cookie added.
*
* @param {String} key - Cookie name
* @param {String} val - Cookie value
* @param {[type]} opts - Options object can contain path, secure,
* expires, domain, http
*/
res.setCookie = function setCookie(key, val, opts) {
var HEADER = "Set-Cookie";
if (res.header(HEADER)) {
var curCookies = res.header(HEADER);
if (!(curCookies instanceof Array)) {
curCookies = [curCookies];
}
curCookies.push(cookie.serialize(key, val, opts));
res.setHeader(HEADER, curCookies);
} else {
res.setHeader(HEADER, cookie.serialize(key, val, opts));
}
};
res.clearCookie = function clearCookie (key, opts) {
var options = merge({
expires: new Date(1)
}, opts);
res.setCookie(key, '', options)
}
next();
}
|
javascript
|
{
"resource": ""
}
|
q57904
|
reportManualError
|
train
|
function reportManualError(err, request, additionalMessage, callback) {
if (isString(request)) {
// no request given
callback = additionalMessage;
additionalMessage = request;
request = undefined;
} else if (isFunction(request)) {
// neither request nor additionalMessage given
callback = request;
request = undefined;
additionalMessage = undefined;
}
if (isFunction(additionalMessage)) {
callback = additionalMessage;
additionalMessage = undefined;
}
var em = new ErrorMessage();
em.setServiceContext(config.getServiceContext().service,
config.getServiceContext().version);
errorHandlerRouter(err, em);
if (isObject(request)) {
em.consumeRequestInformation(manualRequestInformationExtractor(request));
}
if (isString(additionalMessage)) {
em.setMessage(additionalMessage);
}
client.sendError(em, callback);
return em;
}
|
javascript
|
{
"resource": ""
}
|
q57905
|
isImmutable
|
train
|
function isImmutable(value) {
return value == null || isBoolean(value) || isNumber(value) || isString(value);
}
|
javascript
|
{
"resource": ""
}
|
q57906
|
mixIn
|
train
|
function mixIn(target, objects){
var i = 0,
n = arguments.length,
obj;
while(++i < n){
obj = arguments[i];
if (obj != null) {
forOwn(obj, copyProp, target);
}
}
return target;
}
|
javascript
|
{
"resource": ""
}
|
q57907
|
indexOf
|
train
|
function indexOf(arr, item, fromIndex) {
fromIndex = fromIndex || 0;
if (arr == null) {
return -1;
}
var len = arr.length,
i = fromIndex < 0 ? len + fromIndex : fromIndex;
while (i < len) {
// we iterate over sparse items since there is no way to make it
// work properly on IE 7-8. see #64
if (arr[i] === item) {
return i;
}
i++;
}
return -1;
}
|
javascript
|
{
"resource": ""
}
|
q57908
|
combine
|
train
|
function combine(arr1, arr2) {
if (arr2 == null) {
return arr1;
}
var i = -1, len = arr2.length;
while (++i < len) {
if (indexOf(arr1, arr2[i]) === -1) {
arr1.push(arr2[i]);
}
}
return arr1;
}
|
javascript
|
{
"resource": ""
}
|
q57909
|
clone
|
train
|
function clone(val){
switch (kindOf(val)) {
case 'Object':
return cloneObject(val);
case 'Array':
return cloneArray(val);
case 'RegExp':
return cloneRegExp(val);
case 'Date':
return cloneDate(val);
default:
return val;
}
}
|
javascript
|
{
"resource": ""
}
|
q57910
|
deepClone
|
train
|
function deepClone(val, instanceClone) {
switch ( kindOf(val) ) {
case 'Object':
return cloneObject(val, instanceClone);
case 'Array':
return cloneArray(val, instanceClone);
default:
return clone(val);
}
}
|
javascript
|
{
"resource": ""
}
|
q57911
|
append
|
train
|
function append(arr1, arr2) {
if (arr2 == null) {
return arr1;
}
var pad = arr1.length,
i = -1,
len = arr2.length;
while (++i < len) {
arr1[pad + i] = arr2[i];
}
return arr1;
}
|
javascript
|
{
"resource": ""
}
|
q57912
|
bind
|
train
|
function bind(fn, context, args){
var argsArr = slice(arguments, 2); //curried args
return function(){
return fn.apply(context, argsArr.concat(slice(arguments)));
};
}
|
javascript
|
{
"resource": ""
}
|
q57913
|
toArray
|
train
|
function toArray(val){
var ret = [],
kind = kindOf(val),
n;
if (val != null) {
if ( val.length == null || kind === 'String' || kind === 'Function' || kind === 'RegExp' || val === _win ) {
//string, regexp, function have .length but user probably just want
//to wrap value into an array..
ret[ret.length] = val;
} else {
//window returns true on isObject in IE7 and may have length
//property. `typeof NodeList` returns `function` on Safari so
//we can't use it (#58)
n = val.length;
while (n--) {
ret[n] = val[n];
}
}
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q57914
|
deepMatches
|
train
|
function deepMatches(target, pattern){
if (target && typeof target === 'object') {
if (isArray(target) && isArray(pattern)) {
return matchArray(target, pattern);
} else {
return matchObject(target, pattern);
}
} else {
return target === pattern;
}
}
|
javascript
|
{
"resource": ""
}
|
q57915
|
difference
|
train
|
function difference(arr) {
var arrs = slice(arguments, 1),
result = filter(unique(arr), function(needle){
return !some(arrs, function(haystack){
return contains(haystack, needle);
});
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q57916
|
insert
|
train
|
function insert(arr, rest_items) {
var diff = difference(slice(arguments, 1), arr);
if (diff.length) {
Array.prototype.push.apply(arr, diff);
}
return arr.length;
}
|
javascript
|
{
"resource": ""
}
|
q57917
|
interfaceDescendantOf
|
train
|
function interfaceDescendantOf(interf1, interf2) {
var x,
parents = interf1[$interface].parents;
for (x = parents.length - 1; x >= 0; x -= 1) {
if (parents[x] === interf2) {
return true;
}
if (interfaceDescendantOf(interf1, parents[x])) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q57918
|
instanceOfInterface
|
train
|
function instanceOfInterface(instance, target) {
var x,
interfaces = instance.$static[$class].interfaces;
for (x = interfaces.length - 1; x >= 0; x -= 1) {
if (interfaces[x] === target || interfaceDescendantOf(interfaces[x], target)) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q57919
|
instanceOf
|
train
|
function instanceOf(instance, target) {
if (!isFunction(target)) {
return false;
}
if (instance instanceof target) {
return true;
}
if (instance && instance.$static && instance.$static[$class] && target && target[$interface]) {
return instanceOfInterface(instance, target);
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q57920
|
functionMeta
|
train
|
function functionMeta(func, name) {
var matches = /^function(\s+[a-zA-Z0-9_\$]*)*\s*\(([^\(]*)\)/m.exec(func.toString()),
ret,
split,
optionalReached = false,
length,
x;
// Analyze arguments
if (!matches) {
return null;
}
split = (matches[2] || '').split(/\s*,\s*/gm);
length = split.length;
ret = { mandatory: 0, optional: 0, signature: '' };
if (split[0] !== '') {
for (x = 0; x < length; x += 1) {
if (split[x].charAt(0) === '$') {
ret.optional += 1;
ret.signature += split[x] + ', ';
optionalReached = true;
} else if (!optionalReached) {
ret.mandatory += 1;
ret.signature += split[x] + ', ';
} else {
return null;
}
}
ret.signature = ret.signature.substr(0, ret.signature.length - 2);
}
// Analyze visibility
if (name) {
if (name.charAt(0) === '_') {
if (name.charAt(1) === '_') {
ret.isPrivate = true;
} else {
ret.isProtected = true;
}
} else {
ret.isPublic = true;
}
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q57921
|
handleErrorClassError
|
train
|
function handleErrorClassError(err, errorMessage) {
if (err instanceof Error) {
extractFromErrorClass(err, errorMessage);
} else {
handleUnknownAsError(err, errorMessage);
}
}
|
javascript
|
{
"resource": ""
}
|
q57922
|
hapiErrorHandler
|
train
|
function hapiErrorHandler(req, err, config) {
var service = '';
var version = '';
if (isObject(config)) {
service = config.getServiceContext().service;
version = config.getServiceContext().version;
}
var em = new ErrorMessage()
.consumeRequestInformation(hapiRequestInformationExtractor(req))
.setServiceContext(service, version);
errorHandlerRouter(err, em);
return em;
}
|
javascript
|
{
"resource": ""
}
|
q57923
|
makeHapiPlugin
|
train
|
function makeHapiPlugin(client, config) {
/**
* The register function serves to attach the hapiErrorHandler to specific
* points in the hapi request-response lifecycle. Namely: it attaches to the
* 'request-error' event in Hapi which is emitted when a plugin or receiver
* throws an error while executing and the 'onPreResponse' event to intercept
* error code carrying requests before they are sent back to the client so
* that the errors can be logged to the Error Reporting API.
* @function hapiRegisterFunction
* @param {Hapi.Server} server - A Hapi server instance
* @param {Object} options - The server configuration options object
* @param {Function} next - The Hapi callback to move execution to the next
* plugin
* @returns {Undefined} - returns the execution of the next callback
*/
function hapiRegisterFunction(server, options, next) {
if (isObject(server)) {
if (isFunction(server.on)) {
server.on('request-error', function(req, err) {
var em = hapiErrorHandler(req, err, config);
client.sendError(em);
});
}
if (isFunction(server.ext)) {
server.ext('onPreResponse', function(request, reply) {
var em = null;
if (isObject(request) && isObject(request.response) &&
request.response.isBoom) {
em = hapiErrorHandler(request, new Error(request.response.message),
config);
client.sendError(em);
}
if (isObject(reply) && isFunction(reply.continue)) {
reply.continue();
}
});
}
}
if (isFunction(next)) {
return next();
}
}
var hapiPlugin = {register : hapiRegisterFunction};
var version = (isPlainObject(config) && config.getVersion()) ?
config.getVersion() : '0.0.0';
hapiPlugin.register.attributes = {
name : '@google/cloud-errors',
version : version
};
return hapiPlugin;
}
|
javascript
|
{
"resource": ""
}
|
q57924
|
extractFromErrorClass
|
train
|
function extractFromErrorClass(err, errorMessage) {
errorMessage.setMessage(err.stack);
if (has(err, 'user')) {
errorMessage.setUser(err.user);
}
if (has(err, 'serviceContext') && isObject(err.serviceContext)) {
errorMessage.setServiceContext(err.serviceContext.service,
err.serviceContext.version);
}
}
|
javascript
|
{
"resource": ""
}
|
q57925
|
ErrorMessage
|
train
|
function ErrorMessage() {
this.eventTime = (new Date()).toISOString();
this.serviceContext = {service : 'node', version : undefined};
this.message = '';
this.context = {
httpRequest : {
method : '',
url : '',
userAgent : '',
referrer : '',
responseStatusCode : 0,
remoteIp : ''
},
user : '',
reportLocation : {filePath : '', lineNumber : 0, functionName : ''}
};
}
|
javascript
|
{
"resource": ""
}
|
q57926
|
handleObjectAsError
|
train
|
function handleObjectAsError(err, errorMessage) {
if (isPlainObject(err)) {
extractFromObject(err, errorMessage);
} else {
handleUnknownAsError(err, errorMessage);
}
}
|
javascript
|
{
"resource": ""
}
|
q57927
|
extractStructuredCallList
|
train
|
function extractStructuredCallList(structuredStackTrace) {
/**
* A function which walks the structuredStackTrace variable of its parent
* and produces a JSON representation of the array of CallSites.
* @function
* @inner
* @returns {String} - A JSON representation of the array of CallSites
*/
return function() {
var structuredCallList = [];
var index = 0;
if (!Array.isArray(structuredStackTrace)) {
return JSON.stringify(structuredCallList);
}
for (index; index < structuredStackTrace.length; index += 1) {
structuredCallList.push({
functionName : structuredStackTrace[index].getFunctionName(),
methodName : structuredStackTrace[index].getMethodName(),
fileName : structuredStackTrace[index].getFileName(),
lineNumber : structuredStackTrace[index].getLineNumber(),
columnNumber : structuredStackTrace[index].getColumnNumber()
});
}
return JSON.stringify(structuredCallList);
};
}
|
javascript
|
{
"resource": ""
}
|
q57928
|
prepareStackTraceError
|
train
|
function prepareStackTraceError(err, structuredStackTrace) {
var returnObj = new CustomStackTrace();
var topFrame = {};
if (!Array.isArray(structuredStackTrace)) {
return returnObj;
}
// Get the topframe of the CallSite array
topFrame = structuredStackTrace[0];
returnObj.setFilePath(topFrame.getFileName())
.setLineNumber(topFrame.getLineNumber())
.setFunctionName(topFrame.getFunctionName())
.setStringifyStructuredCallList(
extractStructuredCallList(structuredStackTrace));
return returnObj;
}
|
javascript
|
{
"resource": ""
}
|
q57929
|
intersection
|
train
|
function intersection(arr) {
var arrs = slice(arguments, 1),
result = filter(unique(arr), function(needle){
return every(arrs, function(haystack){
return contains(haystack, needle);
});
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q57930
|
randomAccessor
|
train
|
function randomAccessor(caller) {
if (nrAccesses > nrAllowed || !contains(allowed, caller)) {
throw new Error('Can\'t access random identifier.');
}
nrAccesses += 1;
return random;
}
|
javascript
|
{
"resource": ""
}
|
q57931
|
fetchCache
|
train
|
function fetchCache(target, cache) {
var x,
length = cache.length,
curr;
for (x = 0; x < length; x += 1) {
curr = cache[x];
if (curr.target === target) {
return curr.inspect;
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q57932
|
inspectInstance
|
train
|
function inspectInstance(target, cache) {
// If browser has no define property it means it is too old and
// in that case we return the target itself.
// This could be improved but I think it does not worth the trouble
if (!hasDefineProperty) {
return target;
}
var def,
simpleConstructor,
methodsCache,
propertiesCache,
obj,
tmp,
key;
obj = fetchCache(target, cache.instances);
if (obj) {
return obj;
}
def = target.$static[$class];
simpleConstructor = def.simpleConstructor;
methodsCache = target[cacheKeyword].methods;
propertiesCache = target[cacheKeyword].properties;
obj = createObject(simpleConstructor.prototype);
cache.instances.push({ target: target, inspect: obj });
// Methods
for (key in target[redefinedCacheKeyword].methods) {
obj[key] = inspect(methodsCache[key], cache, true);
}
// Properties
for (key in target[redefinedCacheKeyword].properties) {
tmp = hasOwn(propertiesCache, key) ? propertiesCache[key] : target[key];
obj[key] = inspect(tmp, cache, true);
}
// Handle undeclared properties
methodsCache = def.methods;
propertiesCache = def.properties;
for (key in target) {
if (hasOwn(target, key) && !hasOwn(obj, key) && !propertiesCache[key] && !methodsCache[key]) {
obj[key] = inspect(target[key], cache, true);
}
}
// Fix the .constructor
tmp = obj.constructor.$constructor;
while (tmp) {
inspectConstructor(tmp, cache, true);
tmp = tmp.$parent;
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q57933
|
inspectConstructor
|
train
|
function inspectConstructor(target, cache) {
// If browser has no define property it means it is too old and
// in that case we return the target itself.
// This could be improved but I think it does not worth the trouble
if (!hasDefineProperty) {
return target;
}
var def,
methodsCache,
propertiesCache,
membersCache,
obj,
tmp,
key;
obj = fetchCache(target, cache.constructors);
if (obj) {
return obj;
}
def = target[$class];
obj = def.simpleConstructor;
methodsCache = target[cacheKeyword].methods;
propertiesCache = target[cacheKeyword].properties;
cache.constructors.push({ target: target, inspect: obj });
// Constructor methods
for (key in methodsCache) {
obj[key] = inspect(methodsCache[key], cache, true);
}
// Constructor properties
for (key in propertiesCache) {
tmp = propertiesCache[key];
obj[key] = inspect(tmp, cache, true);
}
// Handle constructor undeclared properties
methodsCache = def.methods;
propertiesCache = def.properties;
for (key in target) {
if (hasOwn(target, key) && !hasOwn(obj, key) && !propertiesCache[key] && !methodsCache[key]) {
obj[key] = inspect(target[key], cache, true);
}
}
obj = obj.prototype;
// Prototype members
target = target.prototype;
membersCache = def.ownMembers;
methodsCache = def.methods;
propertiesCache = def.properties;
for (key in membersCache) {
tmp = methodsCache[key] ? methodsCache[key].implementation : propertiesCache[key].value;
obj[key] = inspect(tmp, cache, true);
}
// Handle undeclared prototype members
for (key in target) {
if (hasOwn(target, key) && !hasOwn(obj, key) && !membersCache[key]) {
obj[key] = inspect(target[key], cache, true);
}
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q57934
|
protectInstance
|
train
|
function protectInstance(instance) {
var key;
obfuscateProperty(instance, cacheKeyword, { properties: {}, methods: {} });
obfuscateProperty(instance, redefinedCacheKeyword, { properties: {}, methods: {} }); // This is for the inspect
for (key in instance.$static[$class].methods) {
protectMethod(key, instance.$static[$class].methods[key], instance);
}
for (key in instance.$static[$class].properties) {
protectProperty(key, instance.$static[$class].properties[key], instance);
}
}
|
javascript
|
{
"resource": ""
}
|
q57935
|
protectConstructor
|
train
|
function protectConstructor(constructor) {
var key,
target,
meta,
prototype = constructor.prototype;
obfuscateProperty(constructor, cacheKeyword, { properties: {}, methods: {} });
for (key in constructor[$class].staticMethods) {
protectStaticMethod(key, constructor[$class].staticMethods[key], constructor);
}
for (key in constructor[$class].staticProperties) {
protectStaticProperty(key, constructor[$class].staticProperties[key], constructor);
}
// Prevent any properties/methods from being added and deleted to the constructor/prototype
if (isFunction(Object.seal) && constructor[$class].locked && !constructor[$class].forceUnlocked) {
Object.seal(constructor);
Object.seal(prototype);
}
}
|
javascript
|
{
"resource": ""
}
|
q57936
|
parseAbstracts
|
train
|
function parseAbstracts(abstracts, constructor) {
var optsStatic = { isStatic: true },
key,
value,
unallowed;
// Check argument
if (!isObject(abstracts)) {
throw new Error('$abstracts defined in abstract class "' + constructor.prototype.$name + '" must be an object.');
}
// Check reserved keywords
checkKeywords(abstracts);
// Check unallowed keywords
unallowed = testKeywords(abstracts, ['$statics']);
if (unallowed) {
throw new Error('$statics inside $abstracts of abstract class "' + constructor.prototype.$name + '" contains an unallowed keyword: "' + unallowed + '".');
}
if (hasOwn(abstracts, '$statics')) {
// Check argument
if (!isObject(abstracts.$statics)) {
throw new Error('$statics definition in $abstracts of abstract class "' + constructor.prototype.$name + '" must be an object.');
}
// Check keywords
checkKeywords(abstracts.$statics, 'statics');
// Check unallowed keywords
unallowed = testKeywords(abstracts.$statics);
if (unallowed) {
throw new Error('$statics inside $abstracts of abstract class "' + constructor.prototype.$name + '" contains an unallowed keyword: "' + unallowed + '".');
}
for (key in abstracts.$statics) {
value = abstracts.$statics[key];
// Check if it is not a function
if (!isFunction(value) || value[$interface] || value[$class]) {
throw new Error('Abstract member "' + key + '" found in abstract class "' + constructor.prototype.$name + '" is not a function.');
}
addMethod(key, value, constructor, optsStatic);
}
delete abstracts.$statics;
}
for (key in abstracts) {
value = abstracts[key];
// Check if it is not a function
if (!isFunction(value) || value[$interface] || value[$class]) {
throw new Error('Abstract member "' + key + '" found in abstract class "' + constructor.prototype.$name + '" is not a function.');
}
addMethod(key, value, constructor);
}
}
|
javascript
|
{
"resource": ""
}
|
q57937
|
parseInterfaces
|
train
|
function parseInterfaces(interfaces, constructor) {
var interfs = toArray(interfaces),
x = interfs.length,
interf,
key,
value;
for (x -= 1; x >= 0; x -= 1) {
interf = interfs[x];
// Grab methods
for (key in interf[$interface].methods) {
value = interf[$interface].methods[key];
// Check if method is already defined as abstract and is compatible
if (constructor[$abstract].methods[key]) {
if (!isFunctionCompatible(constructor[$abstract].methods[key], value)) {
throw new Error('Method "' + key + '( ' + value.signature + ')" described in interface "' + interf.prototype.$name + '" is not compatible with the one already defined in "' + constructor.prototype.$name + '": "' + key + '(' + constructor[$abstract].methods[key].signature + ')".');
}
} else {
constructor[$abstract].methods[key] = interf[$interface].methods[key];
}
}
// Grab static methods
for (key in interf[$interface].staticMethods) {
value = interf[$interface].staticMethods[key];
// Check if method is already defined as abstract and is compatible
if (constructor[$abstract].staticMethods[key]) {
if (!isFunctionCompatible(constructor[$abstract].staticMethods[key], value)) {
throw new Error('Static method "' + key + '( ' + value.signature + ')" described in interface "' + interf.prototype.$name + '" is not compatible with the one already defined in "' + constructor.prototype.$name + '": "' + key + '(' + constructor[$abstract].staticMethods[key].signature + ')".');
}
} else {
constructor[$abstract].staticMethods[key] = value;
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q57938
|
createFinalClass
|
train
|
function createFinalClass(params, constructor) {
var def = Class.$create(params, constructor);
def[$class].finalClass = true;
return def;
}
|
javascript
|
{
"resource": ""
}
|
q57939
|
makeExpressHandler
|
train
|
function makeExpressHandler(client, config) {
/**
* The Express Error Handler function is an interface for the error handler
* stack into the Express architecture.
* @function expressErrorHandler
* @param {Any} err - a error of some type propagated by the express plugin
* stack
* @param {Object} req - an Express request object
* @param {Object} res - an Express response object
* @param {Function} next - an Express continuation callback
* @returns {ErrorMessage} - Returns the ErrorMessage instance
*/
function expressErrorHandler(err, req, res, next) {
var ctxService = '';
var ctxVersion = '';
if (isObject(config)) {
ctxService = config.getServiceContext().service;
ctxVersion = config.getServiceContext().version;
}
var em = new ErrorMessage()
.consumeRequestInformation(
expressRequestInformationExtractor(req, res))
.setServiceContext(ctxService, ctxVersion);
errorHandlerRouter(err, em);
if (isObject(client) && isFunction(client.sendError)) {
client.sendError(em);
}
if (isFunction(next)) {
next(err);
}
return em;
}
return expressErrorHandler;
}
|
javascript
|
{
"resource": ""
}
|
q57940
|
manualRequestInformationExtractor
|
train
|
function manualRequestInformationExtractor(req) {
var returnObject = new RequestInformationContainer();
if (!isObject(req) || isArray(req) || isFunction(req)) {
return returnObject;
}
if (has(req, 'method')) {
returnObject.setMethod(req.method);
}
if (has(req, 'url')) {
returnObject.setUrl(req.url);
}
if (has(req, 'userAgent')) {
returnObject.setUserAgent(req.userAgent);
}
if (has(req, 'referrer')) {
returnObject.setReferrer(req.referrer);
}
if (has(req, 'statusCode')) {
returnObject.setStatusCode(req.statusCode);
}
if (has(req, 'remoteAddress')) {
returnObject.setRemoteAddress(req.remoteAddress);
}
return returnObject;
}
|
javascript
|
{
"resource": ""
}
|
q57941
|
train
|
function(givenConfig, logger) {
/**
* The _logger property caches the logger instance created at the top-level
* for configuration logging purposes.
* @memberof Configuration
* @private
* @type {Object}
* @defaultvalue Object
*/
this._logger = logger;
/**
* The _reportUncaughtExceptions property is meant to contain the optional
* runtime configuration property reportUncaughtExceptions. This property will
* default to true if not given false through the runtime configuration
* meaning that the default behavior is to catch uncaught exceptions, report
* them to the Stackdriver Errors API and then exit. If given false uncaught
* exceptions will not be listened for and not be caught or reported.
* @memberof Configuration
* @private
* @type {Boolean}
* @defaultvalue true
*/
this._reportUncaughtExceptions = true;
/**
* The _shouldReportErrorsToAPI property is meant to denote whether or not
* the Stackdriver error reporting library will actually try to report Errors
* to the Stackdriver Error API. The value of this property is derived from
* the `NODE_ENV` environmental variable or the value of the ignoreEnvironmentCheck
* property if present in the runtime configuration. If either the `NODE_ENV`
* variable is set to 'production' or the ignoreEnvironmentCheck propery on
* the runtime configuration is set to true then the error reporting library will
* attempt to send errors to the Error API. Otherwise the value will remain
* false and errors will not be reported to the API.
* @memberof Configuration
* @private
* @type {Boolean}
* @defaultvalue false
*/
this._shouldReportErrorsToAPI = false;
/**
* The _projectId property is meant to contain the string project id that the
* hosting application is running under. The project id is a unique string
* identifier for the project. If the Configuration instance is not able to
* retrieve a project id from the metadata service or the runtime-given
* configuration then the property will remain null. If given both a project
* id through the metadata service and the runtime configuration then the
* instance will assign the value given by the metadata service over the
* runtime configuration. If the instance is unable to retrieve a valid
* project id or number from runtime configuration and the metadata service
* then this will trigger the `error` event in which listening components must
* operate in 'offline' mode.
* {@link https://cloud.google.com/compute/docs/storing-retrieving-metadata}
* @memberof Configuration
* @private
* @type {String|Null}
* @defaultvalue null
*/
this._projectId = null;
/**
* The _key property is meant to contain the optional Stackdriver API key that
* may be used in place of default application credentials to authenticate
* with the Stackdriver Error API. This property will remain null if a key
* is not given in the runtime configuration or an invalid type is given as
* the runtime configuration.
* {@link https://support.google.com/cloud/answer/6158862?hl=en}
* @memberof Configuration
* @private
* @type {String|Null}
* @defaultvalue null
*/
this._key = null;
/**
* The _keyFilename property is meant to contain a path to a file containing
* user or service account credentials, which will be used in place of
* application default credentials. This property will remain null if no
* value for keyFilename is given in the runtime configuration.
* @memberof Configuration
* @private
* @type {String|Null}
* @defaultvalue null
*/
this._keyFilename = null;
/**
* The _credentials property is meant to contain an object representation of
* user or service account credentials, which will be used in place of
* application default credentials. This property will remain null if no
* value for credentials is given in the runtime configuration.
* @memberof Configuration
* @private
* @type {Credentials|Null}
* @defaultvalue null
*/
this._credentials = null;
/**
* The _serviceContext property is meant to contain the optional service
* context information which may be given in the runtime configuration. If
* not given in the runtime configuration then the property value will remain
* null.
* @memberof Configuration
* @private
* @type {Object}
*/
this._serviceContext = {service: 'nodejs', version: ''};
/**
* The _version of the Error reporting library that is currently being run.
* This information will be logged in errors communicated to the Stackdriver
* Error API.
* @memberof Configuration
* @private
* @type {String}
*/
this._version = version;
/**
* The _givenConfiguration property holds a ConfigurationOptions object
* which, if valid, will be merged against by the values taken from the meta-
* data service. If the _givenConfiguration property is not valid then only
* metadata values will be used in the Configuration instance.
* @memberof Configuration
* @private
* @type {Object|Null}
* @defaultvalue null
*/
this._givenConfiguration = isPlainObject(givenConfig) ? givenConfig : {};
this._checkLocalServiceContext();
this._gatherLocalConfiguration();
}
|
javascript
|
{
"resource": ""
}
|
|
q57942
|
restifyErrorHandler
|
train
|
function restifyErrorHandler(client, config, err, em) {
var svc = config.getServiceContext();
em.setServiceContext(svc.service, svc.version);
errorHandlerRouter(err, em);
client.sendError(em);
}
|
javascript
|
{
"resource": ""
}
|
q57943
|
restifyRequestFinishHandler
|
train
|
function restifyRequestFinishHandler(client, config, req, res) {
var em;
if (res._body instanceof Error ||
res.statusCode > 309 && res.statusCode < 512) {
em = new ErrorMessage().consumeRequestInformation(
expressRequestInformationExtractor(req, res));
restifyErrorHandler(client, config, res._body, em);
}
}
|
javascript
|
{
"resource": ""
}
|
q57944
|
restifyRequestHandler
|
train
|
function restifyRequestHandler(client, config, req, res, next) {
var listener = {};
if (isObject(res) && isFunction(res.on) && isFunction(res.removeListener)) {
listener = function() {
restifyRequestFinishHandler(client, config, req, res);
res.removeListener('finish', listener);
};
res.on('finish', listener);
}
return next();
}
|
javascript
|
{
"resource": ""
}
|
q57945
|
extractRemoteAddressFromRequest
|
train
|
function extractRemoteAddressFromRequest(req) {
if (typeof req.header('x-forwarded-for') !== 'undefined') {
return req.header('x-forwarded-for');
} else if (isObject(req.connection)) {
return req.connection.remoteAddress;
}
return '';
}
|
javascript
|
{
"resource": ""
}
|
q57946
|
expressRequestInformationExtractor
|
train
|
function expressRequestInformationExtractor(req, res) {
var returnObject = new RequestInformationContainer();
if (!isObject(req) || !isFunction(req.header) || !isObject(res)) {
return returnObject;
}
returnObject.setMethod(req.method)
.setUrl(req.url)
.setUserAgent(req.header('user-agent'))
.setReferrer(req.header('referrer'))
.setStatusCode(res.statusCode)
.setRemoteAddress(extractRemoteAddressFromRequest(req));
return returnObject;
}
|
javascript
|
{
"resource": ""
}
|
q57947
|
handleNumberAsError
|
train
|
function handleNumberAsError(err, errorMessage) {
var fauxError = new Error();
var errChecked = fauxError.stack;
if (isNumber(err) && isFunction(err.toString)) {
errChecked = err.toString();
}
errorMessage.setMessage(errChecked);
}
|
javascript
|
{
"resource": ""
}
|
q57948
|
_msb
|
train
|
function _msb(word) {
word |= word >> 1;
word |= word >> 2;
word |= word >> 4;
word |= word >> 8;
word |= word >> 16;
word = (word >> 1) + 1;
return multiplyDeBruijnBitPosition[(word * 0x077CB531) >>> 27];
}
|
javascript
|
{
"resource": ""
}
|
q57949
|
doMember
|
train
|
function doMember(func) {
/*jshint validthis:true*/
func = func || this;
// Check if it is a named func already
if (func[$name]) {
return func;
}
var caller = process._dejavu.caller;
// Check if outside the instance/class
if (!caller) {
throw new Error('Attempting to mark a function as a member outside an instance/class.');
}
// Check if already marked as anonymous
if (func[$anonymous]) {
throw new Error('Function is already marked as an member.');
}
func[$anonymous] = true;
func = wrapMethod(null, func, caller.constructor);
func[$anonymous] = true;
return func;
}
|
javascript
|
{
"resource": ""
}
|
q57950
|
errorHandlerRouter
|
train
|
function errorHandlerRouter(err, em) {
if (err instanceof Error) {
handleErrorClassError(err, em);
return;
}
switch (typeof err) {
case 'object':
handleObjectAsError(err, em);
break;
case 'string':
handleStringAsError(err, em);
break;
case 'number':
handleNumberAsError(err, em);
break;
default:
handleUnknownAsError(err, em);
}
}
|
javascript
|
{
"resource": ""
}
|
q57951
|
handleStringAsError
|
train
|
function handleStringAsError(err, errorMessage) {
var fauxError = new Error();
var fullStack = fauxError.stack.split('\n');
var cleanedStack = fullStack.slice(0, 1).concat(fullStack.slice(4));
var errChecked = '';
if (isString(err)) {
// Replace the generic error message with the user-provided string
cleanedStack[0] = err;
}
errChecked = cleanedStack.join('\n');
errorMessage.setMessage(errChecked);
}
|
javascript
|
{
"resource": ""
}
|
q57952
|
RequestHandler
|
train
|
function RequestHandler(config, logger) {
this._request = commonDiag.utils.authorizedRequestFactory(SCOPES, {
keyFile: config.getKeyFilename(),
credentials: config.getCredentials()
});
this._config = config;
this._logger = logger;
}
|
javascript
|
{
"resource": ""
}
|
q57953
|
getErrorReportURL
|
train
|
function getErrorReportURL(projectId, key) {
var url = [API, projectId, 'events:report'].join('/');
if (isString(key)) {
url += '?key=' + key;
}
return url;
}
|
javascript
|
{
"resource": ""
}
|
q57954
|
handlerSetup
|
train
|
function handlerSetup(client, config) {
/**
* The actual exception handler creates a new instance of `ErrorMessage`,
* extracts infomation from the propagated `Error` and marshals it into the
* `ErrorMessage` instance, attempts to send this `ErrorMessage` instance to
* the Stackdriver Error Reporting API. Subsequently the process is
* terminated.
* @function uncaughtExceptionHandler
* @listens module:process~event:uncaughtException
* @param {Error} err - The error that has been uncaught to this point
* @returns {Undefined} - does not return a value
*/
function uncaughtExceptionHandler(err) {
var em = new ErrorMessage();
errorHandlerRouter(err, em);
client.sendError(em, handleProcessExit);
setTimeout(handleProcessExit, 2000);
}
if (!config.getReportUncaughtExceptions()) {
// Do not attach a listener to the process
return null;
}
return process.on('uncaughtException', uncaughtExceptionHandler);
}
|
javascript
|
{
"resource": ""
}
|
q57955
|
uncaughtExceptionHandler
|
train
|
function uncaughtExceptionHandler(err) {
var em = new ErrorMessage();
errorHandlerRouter(err, em);
client.sendError(em, handleProcessExit);
setTimeout(handleProcessExit, 2000);
}
|
javascript
|
{
"resource": ""
}
|
q57956
|
get
|
train
|
function get (key, def) {
if (Array.isArray(key)) {
return AsyncStorage.multiGet(key)
.then((values) => values.map(([_, value]) => {
return useDefault(def, value) ? def : parse(value)
}))
.then(results => Promise.all(results))
}
return AsyncStorage.getItem(key).then(value => useDefault(def, value) ? def : parse(value))
}
|
javascript
|
{
"resource": ""
}
|
q57957
|
set
|
train
|
function set (key, value) {
if (Array.isArray(key)) {
const items = key.map(([key, value]) => [key, JSON.stringify(value)])
return AsyncStorage.multiSet(items)
}
return AsyncStorage.setItem(key, JSON.stringify(value))
}
|
javascript
|
{
"resource": ""
}
|
q57958
|
update
|
train
|
function update (key, value) {
if (Array.isArray(key)) {
return AsyncStorage.multiMerge(key.map(([key, val]) => [key, JSON.stringify(val)]))
}
return AsyncStorage.mergeItem(key, JSON.stringify(value))
}
|
javascript
|
{
"resource": ""
}
|
q57959
|
transformResponse
|
train
|
function transformResponse(value, options, context) {
if (options.transform === true) {
assert.func(context.transform, 'context.transform')
return context.transform(value)
}
return value
}
|
javascript
|
{
"resource": ""
}
|
q57960
|
publish
|
train
|
async function publish(props) {
const message = getData(props)
return createClient()
.post('/publish/', {
json: true,
body: message
})
}
|
javascript
|
{
"resource": ""
}
|
q57961
|
train
|
function (records, cb) {
// loop through each record
async.each(records, function (record, recordDone) {
// loop through each field
async.each(Object.keys(req.linz.configList.fields), function (field, fieldDone) {
req.linz.configList.fields[field].renderer(record[field], record, field, req.linz.configs[record._id], function (err, value) {
if (err) {
return fieldDone(err, records);
}
var index = records.indexOf(record);
records[index][field] = value;
return fieldDone(null, records);
});
}, function (err) {
return recordDone(err, records);
});
}, function (err) {
return cb(err, records);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57962
|
grid
|
train
|
function grid (data, callback) {
linz.app.render(linz.api.views.viewPath('modelIndex/grid.jade'), data, (err, html) => {
if (err) {
return callback(err);
}
return callback(null, html);
});
}
|
javascript
|
{
"resource": ""
}
|
q57963
|
train
|
function (cb) {
let actions = req.linz.model.linz.formtools.overview.actions;
if (!actions.length) {
return cb(null);
}
parseDisabledProperties(req.linz.record, actions)
.then((parsedActions) => {
actions = parsedActions;
return cb();
})
.catch(cb);
}
|
javascript
|
{
"resource": ""
}
|
|
q57964
|
train
|
function (cb) {
let footerActions = req.linz.model.linz.formtools.overview.footerActions;
if (!footerActions.length) {
return cb();
}
parseDisabledProperties(req.linz.record, footerActions)
.then((parsedActions) => {
footerActions = parsedActions;
return cb();
})
.catch(cb);
}
|
javascript
|
{
"resource": ""
}
|
|
q57965
|
createResponseHandler
|
train
|
function createResponseHandler(fn, key, context) {
// Assert.func(fn,'createResponseHandler:fn')
return function (props) {
const param = key ? props[key] : props
print(fn(param), props, context)
}
}
|
javascript
|
{
"resource": ""
}
|
q57966
|
get
|
train
|
function get (configName, copy) {
if (copy) {
return clone(linz.get('configs')[configName]);
}
return linz.get('configs')[configName];
}
|
javascript
|
{
"resource": ""
}
|
q57967
|
permissions
|
train
|
function permissions (user, configName, callback) {
return get(configName).schema.statics.getPermissions(user, callback);
}
|
javascript
|
{
"resource": ""
}
|
q57968
|
form
|
train
|
function form (req, configName, callback) {
return get(configName).schema.statics.getForm(req, callback);
}
|
javascript
|
{
"resource": ""
}
|
q57969
|
overview
|
train
|
function overview (req, configName, callback) {
return get(configName).schema.statics.getOverview(req, callback);
}
|
javascript
|
{
"resource": ""
}
|
q57970
|
labels
|
train
|
function labels (configName, callback) {
if (callback) {
return get(configName).schema.statics.getLabels(callback);
}
return get(configName).schema.statics.getLabels();
}
|
javascript
|
{
"resource": ""
}
|
q57971
|
handleQueryError
|
train
|
function handleQueryError (err) {
queryErrorCount++;
// Something has gone terribly wrong. Break from loop.
if (queryErrorCount > 1) {
// Reset all filters.
session.list.formData = {};
// Notify the user that an error has occured.
req.linz.notifications.push(linz.api.views.notification({
text: 'One of the filters is repeatedly generating an error. All filters have been removed.',
type: 'error'
}));
// Rerun the query at the last known working state.
// eslint-disable-next-line no-use-before-define
return getModelIndex();
}
// Reset the last known working state.
session.list.formData = session.list.previous.formData;
// If we're in development mode, return the error
// so that the developers are aware of it and can fix it.
if (isDevelopment) {
return next(err);
}
// Notify the user that an error has occured.
req.linz.notifications.push(linz.api.views.notification({
text: 'An error has occured with one of the filters you added. It has been removed.',
type: 'error'
}));
// Rerun the query at the last known working state.
// eslint-disable-next-line no-use-before-define
return getModelIndex();
}
|
javascript
|
{
"resource": ""
}
|
q57972
|
train
|
function (cb) {
formtoolsAPI.list.renderToolbarItems(req, res, req.params.model, function (err, result) {
if (err) {
return cb(err);
}
req.linz.model.list.toolbarItems = result;
return cb(null);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57973
|
train
|
function (cb) {
// check if we need to render the filters
if (!Object.keys(req.linz.model.list.filters).length) {
return cb(null);
}
formtoolsAPI.list.renderFilters(req, req.params.model, function (err, result) {
if (err) {
return cb(err);
}
req.linz.model.list.filters = result;
return cb(null);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57974
|
train
|
function (cb) {
const filters = req.linz.model.list.filters;
const formData = session.list.formData;
// Make sure we have some filters.
if (!filters) {
return cb(null);
}
// Find the alwaysOn filters, that have a default.
const alwaysOnWithDefault = Object.keys(filters).filter((key) => filters[key].alwaysOn === true && Object.keys(filters[key]).includes('default'));
if (!alwaysOnWithDefault) {
return cb(null);
}
// If it already exists, turn it into an array for easy manipulation.
if (formData.selectedFilters && formData.selectedFilters.length) {
formData.selectedFilters = formData.selectedFilters.split(',');
}
// If it doesn't exist create a default array.
if (!formData.selectedFilters || !formData.selectedFilters.length) {
formData.selectedFilters = [];
}
// Make sure the alwaysOnWithDefault filters have entries in session.list.formData.selectedFilters.
alwaysOnWithDefault.forEach((key) => {
const filter = filters[key];
if (!formData.selectedFilters.includes(key)) {
// Add to the selected filters list.
formData.selectedFilters.push(key);
formData[key] = filter.default;
}
});
formData.selectedFilters = formData.selectedFilters.join(',');
return cb(null);
}
|
javascript
|
{
"resource": ""
}
|
|
q57975
|
train
|
function (cb) {
req.linz.model.list.activeFilters = {};
// check if there are any filters in the form post
if (!session.list.formData.selectedFilters) {
return cb(null);
}
formtoolsAPI.list.getActiveFilters(req, session.list.formData.selectedFilters.split(','), session.list.formData, req.params.model, function (err, result) {
if (err) {
return cb(err);
}
req.linz.model.list.activeFilters = result;
return cb(null);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57976
|
train
|
function (cb) {
// check if there are any filters in the form post
if (!session.list.formData.selectedFilters) {
return cb(null);
}
formtoolsAPI.list.renderSearchFilters(req, session.list.formData.selectedFilters.split(','), session.list.formData, req.params.model, function (err, result) {
if (err) {
return cb(err);
}
filters = result;
return cb(null);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57977
|
train
|
function (cb) {
if (!session.list.formData.search || !session.list.formData.search.length || !req.linz.model.list.search || !Array.isArray(req.linz.model.list.search)) {
return cb(null);
}
// Default the `$and` key.
if (!filters.$and) {
filters.$and = [];
}
async.map(req.linz.model.list.search, (field, fieldCallback) => {
linz.api.model.titleField(req.params.model, field, (err, titleField) => {
if (err) {
return fieldCallback(err);
}
fieldCallback(null, linz.api.query.fieldRegexp(titleField, session.list.formData.search));
});
}, (err, $or) => {
filters.$and.push({ $or });
return cb(null);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57978
|
train
|
function (cb) {
req.linz.model.getQuery(req, filters, function (err, result) {
if (err) {
return cb(err);
}
query = result;
return cb(null);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57979
|
train
|
function (cb) {
let fields = Object.keys(req.linz.model.list.fields);
// Work in the title field
linz.api.model.titleField(req.params.model, 'title', (err, titleField) => {
if (err) {
return cb(err);
}
fields.push(titleField);
const select = fields.join(' ');
query.select(select);
// If they've provided the `listQuery` static, use it to allow customisation of the fields we'll retrieve.
if (!req.linz.model.listQuery) {
return cb();
}
req.linz.model.listQuery(req, query, cb);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57980
|
train
|
function (cb) {
req.linz.model.getCount(req, query, function (err, countQuery) {
if (err) {
return cb(err);
}
countQuery.exec(function (countQueryErr, count) {
// A query error has occured, let's short circuit this entire process
// and start again from the last known working state.
if (countQueryErr) {
return handleQueryError(countQueryErr);
}
if (!countQueryErr && count === 0) {
return cb(new Error('No records found'));
}
if (!countQueryErr) {
totalRecords = count;
}
return cb(countQueryErr);
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57981
|
train
|
function (cb) {
const getDefaultOrder = field => field.defaultOrder.toLowerCase() === 'desc' ? '-' : '';
if (!session.list.formData.sort && req.linz.model.list.sortBy.length) {
req.linz.model.list.sortingBy = req.linz.model.list.sortBy[0];
// set default form sort
session.list.formData.sort = `${getDefaultOrder(req.linz.model.list.sortingBy)}${req.linz.model.list.sortingBy.field}`;
} else {
req.linz.model.list.sortBy.forEach(function (sort) {
if (sort.field === session.list.formData.sort || '-' + sort.field === session.list.formData.sort) {
req.linz.model.list.sortingBy = sort;
}
});
}
query.sort(session.list.formData.sort);
if (req.linz.model.list.paging.active === true) {
// add in paging skip and limit
query.skip(pageIndex*pageSize-pageSize).limit(pageSize);
}
query.exec(function (err, docs) {
// A query error has occured, let's short circuit this entire process
// and start again from the last known working state.
if (err) {
return handleQueryError(err);
}
if (!err && docs.length === 0) {
return cb(new Error('No records found'));
}
if (!err) {
mongooseRecords = docs;
// convert mongoose documents to plain javascript objects
mongooseRecords.forEach(function (record) {
records.push(record.toObject({ virtuals: true}));
});
}
cb(err);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57982
|
train
|
function (cb) {
// skip this if canEdit is not define for model
if (!mongooseRecords[0].canEdit) {
return cb(null);
}
async.each(Object.keys(mongooseRecords), function (index, recordDone) {
mongooseRecords[index].canEdit(req, function (err, result, message) {
if (err) {
return recordDone(err);
}
records[index].edit = { disabled: !result, message: message };
return recordDone(null);
});
}, function (err) {
cb(err);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57983
|
train
|
function (cb) {
// loop through each record
async.each(Object.keys(records), function (index, recordDone) {
// store the rendered content into a separate property
records[index]['rendered'] = {};
// loop through each field
async.each(Object.keys(req.linz.model.list.fields), function (field, fieldDone) {
// Skip this field if we have a falsy value
if (!req.linz.model.list.fields[field]) {
return fieldDone();
}
// If we have a reference field, data has been pre-rendered.
// Let's grab it from there.
if (req.linz.model.schema.tree[field] && req.linz.model.schema.tree[field].ref) {
// The default value, but could be replaced below if the conditions are right.
records[index]['rendered'][field] = records[index][field];
// Do we have a rendered result for this field in this particular record?
// Support multiple types ref fields.
if (refColData[field].rendered && records[index][field] && refColData[field].rendered[linz.api.model.getObjectIdFromRefField(records[index][field]).toString()]) {
records[index]['rendered'][field] = refColData[field].rendered[linz.api.model.getObjectIdFromRefField(records[index][field]).toString()];
}
// We're all done here.
return fieldDone();
}
// This will only execute if we don't have a ref field.
let args = [];
// value is not applicable for virtual field
if (!req.linz.model.list.fields[field].virtual) {
args.push(records[index][field]);
}
args.push(mongooseRecords[index]);
args.push(field);
args.push(req.linz.model);
args.push(function (err, value) {
if (!err) {
records[index]['rendered'][field] = value;
}
return fieldDone(err);
});
// call the cell renderer and update the content with the result
// val, record, fieldname, model, callback
req.linz.model.list.fields[field].renderer.apply(this, args);
}, function (err) {
recordDone(err);
});
}, function (err) {
cb(err);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57984
|
train
|
function (cb) {
if (!req.linz.model.list.recordActions.length) {
return cb(null);
}
async.each(req.linz.model.list.recordActions, function (action, actionDone) {
if (!action.disabled) {
return actionDone(null);
}
if (typeof action.disabled !== 'function') {
throw new Error('Invalid type for record.action.disabled. It must be a function');
}
async.each(Object.keys(records), function (index, recordDone) {
action.disabled(mongooseRecords[index], function (err, isDisabled, message) {
records[index].recordActions = records[index].recordActions || {};
records[index].recordActions[action.label] = {
disabled: isDisabled,
message: message
};
return recordDone(null);
});
}, function (err) {
return actionDone(err);
});
}, function (err) {
return cb(err);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57985
|
train
|
function() {
this.$button = $(this.options.templates.button).addClass(this.options.buttonClass);
// Adopt active state.
if (this.$select.prop('disabled')) {
this.disable();
}
else {
this.enable();
}
// Manually add button width if set.
if (this.options.buttonWidth && this.options.buttonWidth !== 'auto') {
this.$button.css({
'width' : this.options.buttonWidth
});
this.$container.css({
'width': this.options.buttonWidth
});
}
// Keep the tab index from the select.
var tabindex = this.$select.attr('tabindex');
if (tabindex) {
this.$button.attr('tabindex', tabindex);
}
this.$container.prepend(this.$button);
}
|
javascript
|
{
"resource": ""
}
|
|
q57986
|
train
|
function() {
// Build ul.
this.$ul = $(this.options.templates.ul);
if (this.options.dropRight) {
this.$ul.addClass('pull-right');
}
// Set max height of dropdown menu to activate auto scrollbar.
if (this.options.maxHeight) {
// TODO: Add a class for this option to move the css declarations.
this.$ul.css({
'max-height': this.options.maxHeight + 'px',
'overflow-y': 'auto',
'overflow-x': 'hidden'
});
}
this.$container.append(this.$ul);
}
|
javascript
|
{
"resource": ""
}
|
|
q57987
|
train
|
function(group) {
var groupName = $(group).prop('label');
// Add a header for the group.
var $li = $(this.options.templates.liGroup);
$('label', $li).text(groupName);
this.$ul.append($li);
if ($(group).is(':disabled')) {
$li.addClass('disabled');
}
// Add the options of the group.
$('option', group).each($.proxy(function(index, element) {
this.createOptionValue(element);
}, this));
}
|
javascript
|
{
"resource": ""
}
|
|
q57988
|
train
|
function() {
var alreadyHasSelectAll = this.hasSelectAll();
if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple
&& $('option', this.$select).length > this.options.includeSelectAllIfMoreThan) {
// Check whether to add a divider after the select all.
if (this.options.includeSelectAllDivider) {
this.$ul.prepend($(this.options.templates.divider));
}
var $li = $(this.options.templates.li);
$('label', $li).addClass("checkbox");
$('label', $li).append('<input type="checkbox" name="' + this.options.checkboxName + '" />');
var $checkbox = $('input', $li);
$checkbox.val(this.options.selectAllValue);
$li.addClass("multiselect-item multiselect-all");
$checkbox.parent().parent()
.addClass('multiselect-all');
$('label', $li).append(" " + this.options.selectAllText);
this.$ul.prepend($li);
$checkbox.prop('checked', false);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q57989
|
train
|
function() {
$('option', this.$select).each($.proxy(function(index, element) {
var $input = $('li input', this.$ul).filter(function() {
return $(this).val() === $(element).val();
});
if ($(element).is(':selected')) {
$input.prop('checked', true);
if (this.options.selectedClass) {
$input.parents('li')
.addClass(this.options.selectedClass);
}
}
else {
$input.prop('checked', false);
if (this.options.selectedClass) {
$input.parents('li')
.removeClass(this.options.selectedClass);
}
}
if ($(element).is(":disabled")) {
$input.attr('disabled', 'disabled')
.prop('disabled', true)
.parents('li')
.addClass('disabled');
}
else {
$input.prop('disabled', false)
.parents('li')
.removeClass('disabled');
}
}, this));
this.updateButtonText();
this.updateSelectAll();
}
|
javascript
|
{
"resource": ""
}
|
|
q57990
|
train
|
function() {
this.$ul.html('');
// Important to distinguish between radios and checkboxes.
this.options.multiple = this.$select.attr('multiple') === "multiple";
this.buildSelectAll();
this.buildDropdownOptions();
this.buildFilter();
this.updateButtonText();
this.updateSelectAll();
if (this.options.dropRight) {
this.$ul.addClass('pull-right');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q57991
|
train
|
function (value) {
var options = $('option', this.$select);
var valueToCompare = value.toString();
for (var i = 0; i < options.length; i = i + 1) {
var option = options[i];
if (option.value === valueToCompare) {
return $(option);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q57992
|
hasLegacy
|
train
|
function hasLegacy (hashes) {
var ary = Object.keys(hashes).filter(function (k) {
return hashes[k] < 0
})
if(ary.length)
peer.blobs.has(ary, function (err, haves) {
if(err) drain.abort(err) //ERROR: abort this stream.
else haves.forEach(function (have, i) {
if(have) has(peer.id, ary[i], have)
})
})
}
|
javascript
|
{
"resource": ""
}
|
q57993
|
train
|
function (exports) {
var exp = undefined;
// retrieve the export object
exports.forEach(function (_export) {
// Linz's default export function is called export
if (_export.action && _export.action === 'export') {
exp = _export;
}
});
// if the export object could not be found, throw an error
if (!exp) {
throw new Error('The export was using Linz default export method, yet the model\'s list.export object could not be found.');
}
return exp;
}
|
javascript
|
{
"resource": ""
}
|
|
q57994
|
train
|
function (cb) {
model.VersionedModel.find({ refId: record._id }, 'dateCreated modifiedBy', { lean: 1, sort: { dateCreated: -1 } }, function (err, result) {
return cb(err, result);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57995
|
hasPermission
|
train
|
function hasPermission (user, context, permission, cb) {
var _context = context;
/**
* Support three types of permissions:
* - navigation
* - models and model
* - configs and config
*
* Context can either be an object, or a string. If context is a string, no other data need be passed through.
* If context is an object, it must have a type and a related property. Linz supports the following:
* - 'models'
* - 'configs'
* - {type: 'model', model: {string}}
* - {type: 'config', config: {string}}
*/
if (typeof context === 'string') {
_context = {
type: context
};
}
if (_context.type.toLowerCase() === 'models' || _context.type.toLowerCase() === 'configs') {
return linz.get('permissions')(user, _context.type, permission, cb);
}
if (_context.type.toLowerCase() === 'model') {
return linz.api.model.hasPermission(user, _context.model, permission, cb);
}
if (_context.type.toLowerCase() === 'config') {
return linz.api.configs.hasPermission(user, _context.config, permission, cb);
}
}
|
javascript
|
{
"resource": ""
}
|
q57996
|
addLoadEvent
|
train
|
function addLoadEvent (func) {
if (window.attachEvent) {
return window.attachEvent('onload', func);
}
if (window.addEventListener) {
return window.addEventListener('load', func, false);
}
return document.addEventListener('load', func, false);
}
|
javascript
|
{
"resource": ""
}
|
q57997
|
transform
|
train
|
async function transform({ datapath, filepath, inverse = false }) {
assert.string(datapath)
assert.string(filepath)
const data = await loadData(datapath)
const contextdoc = await loadData(filepath)
assert.object(data)
assert.object(contextdoc)
const result = new Context(contextdoc).use(viewPlugin).map(data)
return result
}
|
javascript
|
{
"resource": ""
}
|
q57998
|
renderFilters
|
train
|
function renderFilters (req, modelName, cb) {
if (!req) {
throw new Error('req is required.');
}
if (typeof modelName !== 'string' || !modelName.length) {
throw new Error('modelName is required and must be of type String and cannot be empty.');
}
linz.api.model.list(req, modelName, function (err, list) {
if (err) {
return cb(err);
}
if (!Object.keys(list.filters).length) {
return cb(null);
}
async.each(Object.keys(list.filters), function (fieldName, filtersDone) {
// call the filter renderer and update the content with the result
list.filters[fieldName].filter.renderer(fieldName, function (filterErr, result) {
if (filterErr) {
return filtersDone(filterErr);
}
list.filters[fieldName].formControls = result;
return filtersDone(null);
});
}, function (filterErr) {
return cb(filterErr, list.filters);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q57999
|
renderSearchFilters
|
train
|
function renderSearchFilters(req, fieldNames, data, modelName, cb) {
if (!req) {
throw new Error('req is required.');
}
if (!Array.isArray(fieldNames) || !fieldNames.length) {
throw new Error('fieldNames is required and must be of type Array and cannot be empty.');
}
if (typeof modelName !== 'string' || !modelName.length) {
throw new Error('modelName is required and must be of type String and cannot be empty.');
}
if (!(!Object.is(data, null) && !Array.isArray(data) && data === Object(data))) {
throw new Error('data is required and must be of type Object.');
}
// Sort fieldNames (to make MongoDB queries more predictable, and therefore easier to create indexes for), remove duplicates, and remove anything that doesn't have associated data.
fieldNames = dedupe(fieldNames.sort().filter(fieldName => Object.keys(data).indexOf(fieldName) >= 0));
linz.api.model.list(req, modelName, function (err, list) {
if (err) {
return cb(err);
}
if (!Object.keys(list.filters).length) {
return cb(null);
}
var model = linz.api.model.get(modelName),
dataKeys = Object.keys(data),
filters = {};
async.each(fieldNames, function (fieldName, filtersDone) {
if (!dataKeys.includes(fieldName)) {
return filtersDone(null);
}
// call the filter renderer and update the content with the result
list.filters[fieldName].filter.filter(fieldName, data, function (filterErr, result) {
if (filterErr) {
return filtersDone(filterErr);
}
filters = model.addSearchFilter(filters, result);
return filtersDone(null);
});
}, function (filterErr) {
if (filterErr) {
return cb(filterErr);
}
// consolidate filters into query
filters = model.setFiltersAsQuery(filters);
return cb(filterErr, filters);
});
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.