_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q64000
|
buildCommands
|
test
|
function buildCommands (commands) {
var result = [];
commands.forEach(function (command) {
result.push([
command.name,
command.desc || ''
]);
});
return table(result);
}
|
javascript
|
{
"resource": ""
}
|
q64001
|
Router
|
test
|
function Router(options) {
const logPrefix = topLogPrefix + 'Router() - ';
const that = this;
let defaultRouteFound = false;
that.options = options || {};
if (! that.options.paths) {
that.options.paths = {
'controller': {
'path': 'controllers',
'exts': 'js'
},
'static': {
'path': 'public',
'exts': false
},
'template': {
'path': 'public/templates',
'exts': ['tmpl', 'tmp', 'ejs', 'pug']
}
};
}
if (! that.options.routes) that.options.routes = [];
if (! that.options.basePath) that.options.basePath = process.cwd();
if (! that.options.log) {
const lUtils = new LUtils();
that.options.log = new lUtils.Log();
}
for (const key of Object.keys(that.options.paths)) {
if (! Array.isArray(that.options.paths[key].exts) && that.options.paths[key].exts !== false) {
that.options.paths[key].exts = [that.options.paths[key].exts];
}
}
if (! that.options.lfs) {
that.options.lfs = new Lfs({'basePath': that.options.basePath, 'log': that.options.log});
}
for (let i = 0; that.options.routes[i] !== undefined; i ++) {
if (that.options.routes[i].regex === '^/$') {
defaultRouteFound = true;
break;
}
}
// We should always have a default route, so if none exists, create one
if (defaultRouteFound === false) {
that.options.routes.push({
'regex': '^/$',
'controllerPath': 'default.js',
'templatePath': 'default.tmpl'
});
}
for (const key of Object.keys(that.options)) {
that[key] = that.options[key];
}
that.log.debug(logPrefix + 'Instantiated with options: ' + JSON.stringify(that.options));
}
|
javascript
|
{
"resource": ""
}
|
q64002
|
getDefaultPortByProtocol
|
test
|
function getDefaultPortByProtocol (rawProtocol) {
// port-numbers expect no trailing colon
const protocol = rawProtocol.endsWith(':')
? rawProtocol.slice(0, -1)
: rawProtocol
// e.g. mailto has no port associated
// example return value:
// { port: 80, protocol: 'tcp', description: 'World Wide Web HTTP' }
const portByProtocol = portNumbers.getPort(protocol)
return portByProtocol
? Promise.resolve(String(portByProtocol.port))
: Promise.reject(new Error('Has no port'))
}
|
javascript
|
{
"resource": ""
}
|
q64003
|
clearScripts
|
test
|
function clearScripts(node){
var rslt = {};
for(var key in node){
var val = node[key];
if(_.isString(val)){
if(val.trim()) rslt[key] = "...";
}
else{
var childScripts = clearScripts(val);
if(!_.isEmpty(childScripts)) rslt[key] = childScripts;
}
}
return rslt;
}
|
javascript
|
{
"resource": ""
}
|
q64004
|
test
|
function(obj, array){
if(!Array.prototype.indexOf){
for(var i=0; i<array.length; i++){
if(array[i]===obj){
return i;
}
}
return -1;
}
else {
return array.indexOf(obj);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q64005
|
getElementValues
|
test
|
function getElementValues(nodeList, initialScope) {
const valueList = []
for (let i = 0; i < nodeList.length; ++i) {
const elementNode = nodeList[i]
if (elementNode == null) {
valueList.length = i + 1
} else if (elementNode.type === "SpreadElement") {
const argument = getStaticValueR(elementNode.argument, initialScope)
if (argument == null) {
return null
}
valueList.push(...argument.value)
} else {
const element = getStaticValueR(elementNode, initialScope)
if (element == null) {
return null
}
valueList.push(element.value)
}
}
return valueList
}
|
javascript
|
{
"resource": ""
}
|
q64006
|
getStaticValueR
|
test
|
function getStaticValueR(node, initialScope) {
if (node != null && Object.hasOwnProperty.call(operations, node.type)) {
return operations[node.type](node, initialScope)
}
return null
}
|
javascript
|
{
"resource": ""
}
|
q64007
|
isModifiedGlobal
|
test
|
function isModifiedGlobal(variable) {
return (
variable == null ||
variable.defs.length !== 0 ||
variable.references.some(r => r.isWrite())
)
}
|
javascript
|
{
"resource": ""
}
|
q64008
|
config
|
test
|
function config(ext) {
return {
input: "src/index.js",
output: {
file: `index${ext}`,
format: ext === ".mjs" ? "es" : "cjs",
sourcemap: true,
sourcemapFile: `index${ext}.map`,
strict: true,
banner: `/*! @author Toru Nagashima <https://github.com/mysticatea> */`,
},
plugins: [sourcemaps()],
external: Object.keys(require("./package.json").dependencies),
}
}
|
javascript
|
{
"resource": ""
}
|
q64009
|
isEscaped
|
test
|
function isEscaped(str, index) {
let escaped = false
for (let i = index - 1; i >= 0 && str.charCodeAt(i) === 0x5c; --i) {
escaped = !escaped
}
return escaped
}
|
javascript
|
{
"resource": ""
}
|
q64010
|
replaceS
|
test
|
function replaceS(matcher, str, replacement) {
const chunks = []
let index = 0
/** @type {RegExpExecArray} */
let match = null
/**
* @param {string} key The placeholder.
* @returns {string} The replaced string.
*/
function replacer(key) {
switch (key) {
case "$$":
return "$"
case "$&":
return match[0]
case "$`":
return str.slice(0, match.index)
case "$'":
return str.slice(match.index + match[0].length)
default: {
const i = key.slice(1)
if (i in match) {
return match[i]
}
return key
}
}
}
for (match of matcher.execAll(str)) {
chunks.push(str.slice(index, match.index))
chunks.push(replacement.replace(placeholder, replacer))
index = match.index + match[0].length
}
chunks.push(str.slice(index))
return chunks.join("")
}
|
javascript
|
{
"resource": ""
}
|
q64011
|
replaceF
|
test
|
function replaceF(matcher, str, replace) {
const chunks = []
let index = 0
for (const match of matcher.execAll(str)) {
chunks.push(str.slice(index, match.index))
chunks.push(String(replace(...match, match.index, match.input)))
index = match.index + match[0].length
}
chunks.push(str.slice(index))
return chunks.join("")
}
|
javascript
|
{
"resource": ""
}
|
q64012
|
send
|
test
|
function send(msg) {
switch(ps.readyState) {
case 0: // CONNECTING
setTimeout(function () { send(msg); }, 1000);
break;
case 2: // CLOSING
case 3: // CLOSED
_event('dev', 'pubsub - reconnect: send() - closing/closed state');
connect();
setTimeout(function () { send(msg); }, 2000);
break;
case 1: // OPEN
try {
ps.send(msg);
} catch (err) {
console.error(err);
setTimeout(function () { send(msg); }, 1500);
}
break;
default:
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q64013
|
parseMessage
|
test
|
function parseMessage(data) {
switch (data.topic) {
// https://dev.twitch.tv/docs/v5/guides/PubSub/
case 'channel-bits-events-v1.' + state.channel_id:
bits();
break;
// https://discuss.dev.twitch.tv/t/in-line-broadcaster-chat-mod-logs/7281/12
case 'chat_moderator_actions.' + state.id + '.' + state.id:
moderation();
break;
case 'whispers.' + state.id:
whisper();
break;
// case 'channel-subscribe-events-v1.' + state.channel_id:
// sub();
// break;
default:
break;
}
function bits() {
let bits = JSON.parse(data.message);
_event('bits', bits);
}
function moderation() {
let moderation = JSON.parse(data.message).data;
_event('moderation', moderation);
}
function whisper() {
let message = JSON.parse(data.message).data_object;
// TODO: figure out why some whispers are dropped...
// _event('whisper', message);
}
// function sub() {
// // TODO: https://discuss.dev.twitch.tv/t/subscriptions-beta-changes/10023
// }
}
|
javascript
|
{
"resource": ""
}
|
q64014
|
JWT
|
test
|
function JWT(secret, options) {
this.token = '';
this.payload = {};
this.secret = secret;
this.options = options;
this.valid = false;
this.expired = false;
this.stale = true;
}
|
javascript
|
{
"resource": ""
}
|
q64015
|
test
|
function(payload) {
payload.stales = Date.now() + this.options.stales;
this.payload = payload;
this.token = utils.sign(this.payload, this.secret, this.options.signOptions);
this.valid = true;
this.expired = false;
this.stale = false;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q64016
|
test
|
function(res) {
if (this.options.cookies) {
res.cookie(this.options.cookie, this.token, this.options.cookieOptions);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q64017
|
test
|
function() {
return {
token: this.token,
payload: this.payload,
valid: this.valid,
expired: this.expired,
stale: this.stale
};
}
|
javascript
|
{
"resource": ""
}
|
|
q64018
|
test
|
function(token) {
this.token = token || '';
try {
this.payload = utils.verify(this.token, this.secret, this.options.verifyOptions);
this.valid = true;
} catch (err) {
this.payload = utils.decode(this.token) || {};
if (err.name == 'TokenExpiredError') {
this.expired = true;
}
}
if (this.valid && !this.options.verify(this)) {
this.valid = false;
}
if (this.payload.stales && Date.now() <= this.payload.stales) {
this.stale = false;
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q64019
|
test
|
function(secret, options) {
if (!secret) {
throw new ReferenceError('secret must be defined');
}
if (typeof secret == 'string') {
var _secret = secret;
secret = function(req) {return _secret};
}
options = options || {};
var defaults = {
cookie: 'jwt-express',
cookieOptions: {
httpOnly: true
},
cookies: true,
refresh: true,
reqProperty: 'jwt',
revoke: function(jwt) {},
signOptions: {},
stales: 900000,
verify: function(jwt) {return true},
verifyOptions: {}
};
for (var key in defaults) {
this.options[key] = options[key] !== undefined? options[key]: defaults[key];
}
return function(req, res, next) {
var token;
if (this.options.cookies) {
token = req.cookies[this.options.cookie];
} else if (req.headers.authorization) {
// Authorization: Bearer abc.abc.abc
token = req.headers.authorization.split(' ')[1];
}
var jwt = new JWT(secret(req), this.options);
req[this.options.reqProperty] = jwt.verify(token);
if (jwt.valid && !jwt.stale && jwt.options.refresh) {
jwt.resign().store(res);
}
/**
* jwt - Creates and signs a new JWT. If cookies are in use, it stores
* the JWT in the cookie as well.
* @param object payload The payload of the JWT
* @return JWT
*/
res.jwt = function(payload) {
var jwt = new JWT(secret(req), this.options);
return jwt.sign(payload).store(res);
}.bind(this);
this.clear = function() {
if (this.options.cookies) {
res.clearCookie(this.options.cookie);
}
}.bind(this);
next();
}.bind(this);
}
|
javascript
|
{
"resource": ""
}
|
|
q64020
|
test
|
function() {
return function(req, res, next) {
var jwt = req[this.options.reqProperty] || {};
if (!jwt.valid) {
next(new JWTExpressError('JWT is invalid'));
} else {
next();
}
}.bind(this);
}
|
javascript
|
{
"resource": ""
}
|
|
q64021
|
setupComponent
|
test
|
function setupComponent (fixture, options) {
// tear down any existing component instance
if (this.component) {
this.component.teardown();
this.$node.remove();
}
if (fixture instanceof jQuery || typeof fixture === 'string') {
// use the fixture to create component root node
this.$node = $(fixture).addClass('component-root');
} else {
// create an empty component root node
this.$node = $('<div class="component-root" />');
options = fixture;
fixture = null;
}
// append component root node to body
$('body').append(this.$node);
// normalize options
options = options === undefined ? {} : options;
// instantiate component on component root node
this.component = (new this.Component()).initialize(this.$node, options);
}
|
javascript
|
{
"resource": ""
}
|
q64022
|
describeModuleFactory
|
test
|
function describeModuleFactory (modulePath, specDefinitions) {
return function () {
beforeEach(function (done) {
this.module = null;
var requireCallback = function (module) {
this.module = module;
done();
}.bind(this);
require([modulePath], requireCallback);
});
specDefinitions.apply(this);
};
}
|
javascript
|
{
"resource": ""
}
|
q64023
|
consul
|
test
|
function consul (options, resilient) {
defineResilientOptions(params, options)
return {
// Incoming traffic middleware
'in': function inHandler (err, res, next) {
if (err) return next()
// resilient.js sometimes calls the middleware function more than once, with the output
// of the previous invokation; checking here the type of the items in the response to
// only call `mapServers` with service objects, not URLs (strings)
if (Array.isArray(res.data) && Object(res.data[0]) === res.data[0]) {
res.data = mapServers(res.data)
}
next()
},
// Outgoing traffic middleware
'out': function outHandler (options, next) {
options.params = options.params || {}
if (params.datacenter) {
options.params.dc = params.datacenter
}
if (params.onlyHealthy) {
options.params.passing = true
}
if (params.tag) {
options.params.tag = params.tag
}
next()
}
}
}
|
javascript
|
{
"resource": ""
}
|
q64024
|
inHandler
|
test
|
function inHandler (err, res, next) {
if (err) return next()
// resilient.js sometimes calls the middleware function more than once, with the output
// of the previous invokation; checking here the type of the items in the response to
// only call `mapServers` with service objects, not URLs (strings)
if (Array.isArray(res.data) && Object(res.data[0]) === res.data[0]) {
res.data = mapServers(res.data)
}
next()
}
|
javascript
|
{
"resource": ""
}
|
q64025
|
outHandler
|
test
|
function outHandler (options, next) {
options.params = options.params || {}
if (params.datacenter) {
options.params.dc = params.datacenter
}
if (params.onlyHealthy) {
options.params.passing = true
}
if (params.tag) {
options.params.tag = params.tag
}
next()
}
|
javascript
|
{
"resource": ""
}
|
q64026
|
test
|
function(categoryId, event) {
event.preventDefault();
this.refs.scroller.prepareAnimationSync();
this.setState({
mode: 'single',
selected: categoryId,
previousScrollPosition: this.refs.scroller.scrollTop,
}, function() {
this.refs.scroller.animateAndResetScroll(0, 0);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q64027
|
test
|
function(event) {
event.preventDefault();
this.setState({
mode: 'all',
selected: null,
}, function() {
this.refs.scroller.animateAndResetScroll(0, this.state.previousScrollPosition);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q64028
|
Service
|
test
|
function Service(displayName, UUID, subtype) {
if (!UUID) throw new Error("Services must be created with a valid UUID.");
this.displayName = displayName;
this.UUID = UUID;
this.subtype = subtype;
this.iid = null; // assigned later by our containing Accessory
this.characteristics = [];
this.optionalCharacteristics = [];
// every service has an optional Characteristic.Name property - we'll set it to our displayName
// if one was given
// if you don't provide a display name, some HomeKit apps may choose to hide the device.
if (displayName) {
// create the characteristic if necessary
var nameCharacteristic =
this.getCharacteristic(Characteristic.Name) ||
this.addCharacteristic(Characteristic.Name);
nameCharacteristic.setValue(displayName);
}
}
|
javascript
|
{
"resource": ""
}
|
q64029
|
Characteristic
|
test
|
function Characteristic(displayName, UUID, props) {
this.displayName = displayName;
this.UUID = UUID;
this.iid = null; // assigned by our containing Service
this.value = null;
this.props = props || {
format : null,
unit : null,
minValue: null,
maxValue: null,
minStep : null,
perms : []
};
}
|
javascript
|
{
"resource": ""
}
|
q64030
|
migrateDatabase
|
test
|
function migrateDatabase(nativeDatabase, nativeTransaction, schemaDescriptors,
currentVersion) {
let descriptorsToProcess = schemaDescriptors.filter((descriptor) => {
return descriptor.version > currentVersion
})
if (!descriptorsToProcess.length) {
return PromiseSync.resolve(undefined)
}
return migrateDatabaseVersion(
nativeDatabase,
nativeTransaction,
descriptorsToProcess[0]
).then(() => {
return migrateDatabase(
nativeDatabase,
nativeTransaction,
descriptorsToProcess,
descriptorsToProcess[0].version
)
})
}
|
javascript
|
{
"resource": ""
}
|
q64031
|
migrateDatabaseVersion
|
test
|
function migrateDatabaseVersion(nativeDatabase, nativeTransaction,
descriptor) {
let fetchPromise
if (descriptor.fetchBefore && descriptor.fetchBefore.length) {
let fetcher = new RecordFetcher()
let objectStores = normalizeFetchBeforeObjectStores(descriptor.fetchBefore)
fetchPromise = fetcher.fetchRecords(nativeTransaction, objectStores)
} else {
fetchPromise = PromiseSync.resolve({})
}
return fetchPromise.then((recordsMap) => {
let versionMigrator = new DatabaseVersionMigrator(
nativeDatabase,
nativeTransaction,
descriptor.objectStores
)
return versionMigrator.executeMigration(
descriptor.after || (() => {}),
recordsMap
)
})
}
|
javascript
|
{
"resource": ""
}
|
q64032
|
normalizeFetchBeforeObjectStores
|
test
|
function normalizeFetchBeforeObjectStores(objectStores) {
return objectStores.map((objectStore) => {
if (typeof objectStore === "string") {
return {
objectStore,
preprocessor: record => record
}
} else if (!objectStore.preprocessor) {
return {
objectStore: objectStore.objectStore,
preprocessor: record => record
}
} else {
return objectStore
}
})
}
|
javascript
|
{
"resource": ""
}
|
q64033
|
checkSchemaDescriptorTypes
|
test
|
function checkSchemaDescriptorTypes(schemaDescriptors) {
let onlyPlainObjects = schemaDescriptors.every((descriptor) => {
return descriptor.constructor === Object
})
if (onlyPlainObjects) {
return
}
if (!(schemaDescriptors[0] instanceof DatabaseSchema)) {
throw new TypeError("The schema descriptor of the lowest described " +
`database version (${schemaDescriptors[0].version}) must be a ` +
"DatabaseSchema instance, or all schema descriptors must be plain " +
"objects")
}
schemaDescriptors.slice(1).forEach((descriptor) => {
if (!(descriptor instanceof UpgradedDatabaseSchema)) {
throw new TypeError("The schema descriptors of the upgraded database " +
"versions must be UpgradedDatabaseSchema instances, but the " +
`provided descriptor of version ${descriptor.version} was not an ` +
"UpgradedDatabaseSchema instance, or all schema descriptors must " +
"be plain objects")
}
})
}
|
javascript
|
{
"resource": ""
}
|
q64034
|
list
|
test
|
function list(storage, keyRange, filter, direction, unique, pageSize,
storageFactory) {
return new Promise((resolve, reject) => {
let items = []
storage.createCursorFactory(keyRange, direction)((cursor) => {
if (!filter || filter(cursor.record, cursor.primaryKey, cursor.key)) {
if (items.length === pageSize) {
finalize(true, cursor.key, cursor.primaryKey)
return
} else {
items.push(cursor.record)
}
}
cursor.continue()
}).then(() => finalize(false, null, null)).catch(error => reject(error))
function finalize(hasNextPage, nextKey, nextPrimaryKey) {
resolve(new RecordList(items, storageFactory, nextKey, nextPrimaryKey,
direction, unique, filter, pageSize, hasNextPage))
}
})
}
|
javascript
|
{
"resource": ""
}
|
q64035
|
normalizeCompoundObjectKey
|
test
|
function normalizeCompoundObjectKey(keyPaths, key) {
let normalizedKey = []
keyPaths.forEach((keyPath) => {
let keyValue = key
keyPath.split(".").forEach((fieldName) => {
if (!keyValue.hasOwnProperty(fieldName)) {
throw new Error(`The ${keyPath} key path is not defined in the ` +
"provided compound key")
}
keyValue = keyValue[fieldName]
})
normalizedKey.push(keyValue)
})
return normalizedKey
}
|
javascript
|
{
"resource": ""
}
|
q64036
|
iterateCursor
|
test
|
function iterateCursor(request, cursorConstructor, recordCallback) {
return new PromiseSync((resolve, reject) => {
let traversedRecords = 0
let canIterate = true
request.onerror = () => reject(request.error)
request.onsuccess = () => {
if (!canIterate) {
console.warn("Cursor iteration was requested asynchronously, " +
"ignoring the new cursor position")
return
}
if (!request.result) {
resolve(traversedRecords)
return
}
traversedRecords++
let iterationRequested = handleCursorIteration(
request,
cursorConstructor,
recordCallback,
reject
)
if (!iterationRequested) {
canIterate = false
resolve(traversedRecords)
}
}
})
}
|
javascript
|
{
"resource": ""
}
|
q64037
|
handleCursorIteration
|
test
|
function handleCursorIteration(request, cursorConstructor, recordCallback,
reject) {
let iterationRequested = false
let cursor = new cursorConstructor(request, () => {
iterationRequested = true
}, (subRequest) => {
return PromiseSync.resolve(subRequest).catch((error) => {
reject(error)
throw error
})
})
try {
recordCallback(cursor)
} catch (error) {
iterationRequested = false
reject(error)
}
return iterationRequested
}
|
javascript
|
{
"resource": ""
}
|
q64038
|
fetchAllRecords
|
test
|
function fetchAllRecords(transaction, objectStores) {
return PromiseSync.all(objectStores.map((descriptor) => {
return fetchRecords(
transaction.getObjectStore(descriptor.objectStore),
descriptor.preprocessor
)
})).then((fetchedRecords) => {
let recordsMap = {}
for (let i = 0; i < objectStores.length; i++) {
recordsMap[objectStores[i].objectStore] = fetchedRecords[i]
}
return recordsMap
})
}
|
javascript
|
{
"resource": ""
}
|
q64039
|
fetchRecords
|
test
|
function fetchRecords(objectStore, preprocessor) {
return new PromiseSync((resolve, reject) => {
let records = []
objectStore.openCursor(null, CursorDirection.NEXT, (cursor) => {
let primaryKey = cursor.primaryKey
if (primaryKey instanceof Object) {
Object.freeze(primaryKey)
}
let preprocessedRecord = preprocessor(cursor.record, primaryKey)
if (preprocessedRecord === UpgradedDatabaseSchema.DELETE_RECORD) {
cursor.delete()
cursor.continue()
return
} else if (preprocessedRecord !== UpgradedDatabaseSchema.SKIP_RECORD) {
records.push({
key: primaryKey,
record: preprocessedRecord
})
} else {
// SKIP_RECORD returned, do nothing
}
cursor.continue()
}).then(() => resolve(records)).catch(error => reject(error))
})
}
|
javascript
|
{
"resource": ""
}
|
q64040
|
writeFileP
|
test
|
function writeFileP (outputPath, data, cb) {
outputPath = abs(outputPath);
let dirname = path.dirname(outputPath);
mkdirp(dirname, err => {
if (err) { return cb(err); }
let str = data;
if (typpy(data, Array) || typpy(data, Object)) {
str = JSON.stringify(data, null, 2);
}
fs.writeFile(outputPath, str, err => cb(err, data));
});
}
|
javascript
|
{
"resource": ""
}
|
q64041
|
runTransaction
|
test
|
function runTransaction(transaction, objectStoreNames, transactionOperations) {
let callbackArguments = objectStoreNames.map((objectStoreName) => {
return transaction.getObjectStore(objectStoreName)
})
callbackArguments.push(() => transaction.abort())
let resultPromise = transactionOperations(...callbackArguments)
return Promise.resolve(resultPromise).then((result) => {
return transaction.completionPromise.then(() => result)
})
}
|
javascript
|
{
"resource": ""
}
|
q64042
|
toNativeCursorDirection
|
test
|
function toNativeCursorDirection(direction, unique) {
if (typeof direction === "string") {
if (CURSOR_DIRECTIONS.indexOf(direction.toUpperCase()) === -1) {
throw new Error("When using a string as cursor direction, use NEXT " +
`or PREVIOUS, ${direction} provided`);
}
} else {
direction = direction.value
}
let cursorDirection = direction.toLowerCase().substring(0, 4)
if (unique) {
cursorDirection += "unique"
}
return cursorDirection
}
|
javascript
|
{
"resource": ""
}
|
q64043
|
createIndex
|
test
|
function createIndex(objectStore, indexSchema) {
let indexNames = Array.from(objectStore.indexNames)
if (indexNames.indexOf(indexSchema.name) !== -1) {
return
}
objectStore.createIndex(indexSchema.name, indexSchema.keyPath, {
unique: indexSchema.unique,
multiEntry: indexSchema.multiEntry
})
}
|
javascript
|
{
"resource": ""
}
|
q64044
|
fetchNextPage
|
test
|
function fetchNextPage(storageFactory, keyRange, cursorDirection, unique,
firstPrimaryKey, filter, pageSize) {
let storage = storageFactory()
let nextItems = []
return new Promise((resolve, reject) => {
let idb = idbProvider()
let cursorFactory = storage.createCursorFactory(
keyRange,
cursorDirection,
unique
)
cursorFactory((cursor) => {
if (!unique) {
let shouldSkip =
(
(cursorDirection === CursorDirection.NEXT) &&
(idb.cmp(firstPrimaryKey, cursor.primaryKey) > 0)
) || (
(cursorDirection === CursorDirection.PREVIOUS) &&
(idb.cmp(firstPrimaryKey, cursor.primaryKey) < 0)
)
if (shouldSkip) {
cursor.continue()
return
}
}
if (!filter || filter(cursor.record, cursor.primaryKey, cursor.key)) {
if (nextItems.length === pageSize) {
finalize(true, cursor.key, cursor.primaryKey)
return
} else {
nextItems.push(cursor.record)
}
}
cursor.continue()
}).then(() => finalize(false, null, null)).catch(error => reject(error))
function finalize(hasNextPage, nextKey, nextPrimaryKey) {
resolve(new RecordList(nextItems, storageFactory, nextKey,
nextPrimaryKey, cursorDirection, unique, filter, pageSize,
hasNextPage))
}
})
}
|
javascript
|
{
"resource": ""
}
|
q64045
|
executeEventListeners
|
test
|
function executeEventListeners(listeners, ...parameters) {
listeners.forEach((listener) => {
try {
listener.apply(null, parameters)
} catch (error) {
console.error("An event listener threw an error", error)
}
})
}
|
javascript
|
{
"resource": ""
}
|
q64046
|
resolve
|
test
|
function resolve(instance, newState, value) {
if (instance[FIELDS.state] !== STATE.PENDING) {
return
}
instance[FIELDS.state] = newState
instance[FIELDS.value] = value
let listeners
if (newState === STATE.RESOLVED) {
listeners = instance[FIELDS.fulfillListeners]
} else {
listeners = instance[FIELDS.errorListeners]
}
for (let listener of listeners) {
listener()
}
}
|
javascript
|
{
"resource": ""
}
|
q64047
|
runQuery
|
test
|
function runQuery(cursorFactory, filter, comparator, offset, limit, callback) {
let records = []
let recordIndex = -1
return cursorFactory((cursor) => {
if (!filter && offset && ((recordIndex + 1) < offset)) {
recordIndex = offset - 1
cursor.advance(offset)
return
}
let primaryKey = cursor.primaryKey
if (filter && !filter(cursor.record, primaryKey)) {
cursor.continue()
return
}
if (comparator) {
insertSorted(records, cursor.record, primaryKey, comparator)
if (offset || limit) {
if (records.length > (offset + limit)) {
records.pop()
}
}
cursor.continue()
return
}
recordIndex++
if (recordIndex < offset) {
cursor.continue()
return
}
callback(cursor.record, primaryKey)
if (!limit || ((recordIndex + 1) < (offset + limit))) {
cursor.continue()
}
}).then(() => {
if (!comparator) {
return
}
records = records.slice(offset)
for (let { record, primaryKey } of records) {
callback(record, primaryKey)
}
})
}
|
javascript
|
{
"resource": ""
}
|
q64048
|
insertSorted
|
test
|
function insertSorted(records, record, primaryKey, comparator) {
let index = findInsertIndex(records, record, comparator)
records.splice(index, 0, {
record,
primaryKey
})
}
|
javascript
|
{
"resource": ""
}
|
q64049
|
findInsertIndex
|
test
|
function findInsertIndex(records, record, comparator) {
if (!records.length) {
return 0
}
if (records.length === 1) {
let comparison = comparator(records[0].record, record)
return (comparison > 0) ? 0 : 1
}
let comparison = comparator(records[0].record, record)
if (comparison > 0) {
return 0
}
let bottom = 1
let top = records.length - 1
while (bottom <= top) {
let pivotIndex = Math.floor((bottom + top) / 2)
let comparison = comparator(records[pivotIndex].record, record)
if (comparison > 0) {
let previousElement = records[pivotIndex - 1].record
if (comparator(previousElement, record) <= 0) {
return pivotIndex
}
top = pivotIndex - 1
} else {
bottom = pivotIndex + 1
}
}
return records.length
}
|
javascript
|
{
"resource": ""
}
|
q64050
|
prepareQuery
|
test
|
function prepareQuery(thisStorage, filter, order) {
order = normalizeKeyPath(order)
let expectedSortingDirection = order[0].charAt(0) === "!"
let canSortingBeOptimized
canSortingBeOptimized = canOptimizeSorting(expectedSortingDirection, order)
let storages = new Map()
storages.set(normalizeKeyPath(thisStorage.keyPath), {
storage: thisStorage,
score: 1 // traversing storage is faster than fetching records by index
})
for (let indexName of thisStorage.indexNames) {
let index = thisStorage.getIndex(indexName)
if (!index.multiEntry) {
storages.set(normalizeKeyPath(index.keyPath), {
storage: index,
score: 0
})
}
}
let simplifiedOrderFieldPaths = simplifyOrderingFieldPaths(order)
if (canSortingBeOptimized) {
prepareSortingOptimization(storages, simplifiedOrderFieldPaths)
}
prepareFilteringOptimization(storages, filter)
return chooseStorageForQuery(
storages,
order,
simplifiedOrderFieldPaths,
canSortingBeOptimized,
expectedSortingDirection
)
}
|
javascript
|
{
"resource": ""
}
|
q64051
|
prepareSortingOptimization
|
test
|
function prepareSortingOptimization(storages, simplifiedOrderFieldPaths) {
let idb = idbProvider()
for (let [keyPath, storageAndScore] of storages) {
let keyPathSlice = keyPath.slice(0, simplifiedOrderFieldPaths.length)
if (idb.cmp(keyPathSlice, simplifiedOrderFieldPaths) === 0) {
storageAndScore.score += 4 // optimizing the sorting is more important
}
}
}
|
javascript
|
{
"resource": ""
}
|
q64052
|
prepareFilteringOptimization
|
test
|
function prepareFilteringOptimization(storages, filter) {
if (filter instanceof Function) {
for (let [keyPath, storageAndScore] of storages) {
storageAndScore.filter = filter
}
return
}
for (let [keyPath, storageAndScore] of storages) {
let normalizedFilter = normalizeFilter(filter, keyPath)
if (normalizedFilter instanceof Function) {
let isOptimizableFilter =
(filter instanceof Object) &&
!(filter instanceof Date) &&
!(filter instanceof Array) &&
!(filter instanceof IDBKeyRange)
if (isOptimizableFilter) {
let partialOptimization = partiallyOptimizeFilter(filter, keyPath)
storageAndScore.keyRange = partialOptimization.keyRange
storageAndScore.filter = partialOptimization.filter
if (partialOptimization.score) {
storageAndScore.score += 1 + partialOptimization.score
}
} else {
storageAndScore.filter = normalizedFilter
}
} else {
storageAndScore.keyRange = normalizedFilter
storageAndScore.score += 2
}
}
}
|
javascript
|
{
"resource": ""
}
|
q64053
|
chooseStorageForQuery
|
test
|
function chooseStorageForQuery(storages, order, simplifiedOrderFieldPaths,
canSortingBeOptimized, expectedSortingDirection) {
let sortedStorages = Array.from(storages.values())
sortedStorages.sort((storage1, storage2) => {
return storage2.score - storage1.score
})
let chosenStorageDetails = sortedStorages[0]
let chosenStorage = chosenStorageDetails.storage
let chosenStorageKeyPath = normalizeKeyPath(chosenStorage.keyPath)
let storageKeyPathSlice = chosenStorageKeyPath.slice(
0,
simplifiedOrderFieldPaths.length
)
let optimizeSorting = canSortingBeOptimized &&
(idbProvider().cmp(storageKeyPathSlice, simplifiedOrderFieldPaths) === 0)
return {
storage: chosenStorage,
direction: optimizeSorting ? (
CursorDirection[expectedSortingDirection ? "PREVIOUS" : "NEXT"]
) : CursorDirection.NEXT,
comparator: optimizeSorting ? null : compileOrderingFieldPaths(order),
keyRange: chosenStorageDetails.keyRange,
filter: chosenStorageDetails.filter
}
}
|
javascript
|
{
"resource": ""
}
|
q64054
|
prepareOrderingSpecificationForQuery
|
test
|
function prepareOrderingSpecificationForQuery(order, keyPath) {
if (order === null) {
order = CursorDirection.NEXT
}
let isCursorDirection = ((typeof order === "string") &&
(CURSOR_DIRECTIONS.indexOf(order.toUpperCase()) > -1)) ||
(CURSOR_DIRECTIONS.indexOf(order) > -1)
if (isCursorDirection && (typeof order === "string")) {
order = CursorDirection[order.toUpperCase()] || CursorDirection.PREVIOUS
}
if (order instanceof CursorDirection) {
keyPath = normalizeKeyPath(keyPath)
if (order === CursorDirection.NEXT) {
return keyPath
} else {
return keyPath.map(fieldPath => `!${fieldPath}`)
}
}
return order
}
|
javascript
|
{
"resource": ""
}
|
q64055
|
openConnection
|
test
|
function openConnection(databaseName, sortedSchemaDescriptors) {
let version = sortedSchemaDescriptors.slice().pop().version
let request = NativeDBAccessor.indexedDB.open(databaseName, version)
return new Promise((resolve, reject) => {
let wasBlocked = false
let upgradeTriggered = false
let migrationPromiseResolver, migrationPromiseRejector
let migrationPromise = new Promise((resolve, reject) => {
migrationPromiseResolver = resolve
migrationPromiseRejector = reject
})
// prevent leaking the same error to the console twice
migrationPromise.catch(() => {})
request.onsuccess = () => {
let database = new Database(request.result)
resolve(database)
migrationPromiseResolver()
}
request.onupgradeneeded = (event) => {
if (!wasBlocked) {
upgradeTriggered = true
}
let database = request.result
let transaction = request.transaction
if (wasBlocked) {
transaction.abort()
return
}
upgradeDatabaseSchema(databaseName, event, migrationPromise, database,
transaction, sortedSchemaDescriptors, migrationPromiseResolver,
migrationPromiseRejector).catch((error) => {
transaction.abort()
})
}
request.onerror = (event) => {
handleConnectionError(event, request.error, wasBlocked, upgradeTriggered,
reject, migrationPromiseRejector)
}
request.onblocked = () => {
wasBlocked = true
let error = new Error("A database upgrade was needed, but could not " +
"be performed, because the attempt was blocked by a connection " +
"that remained opened after receiving the notification")
reject(error)
migrationPromiseRejector(error)
}
})
}
|
javascript
|
{
"resource": ""
}
|
q64056
|
handleConnectionError
|
test
|
function handleConnectionError(event, error, wasBlocked, upgradeTriggered,
reject, migrationPromiseRejector) {
if (wasBlocked || upgradeTriggered) {
event.preventDefault()
return
}
reject(request.error)
migrationPromiseRejector(request.error)
}
|
javascript
|
{
"resource": ""
}
|
q64057
|
executeMigrationListeners
|
test
|
function executeMigrationListeners(databaseName, oldVersion, newVersion,
completionPromise) {
for (let listener of migrationListeners) {
try {
listener(databaseName, oldVersion, newVersion, completionPromise)
} catch (e) {
console.warn("A schema migration event listener threw an error", e);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q64058
|
splitFilteringObject
|
test
|
function splitFilteringObject(filter, filterFieldPaths, storageKeyPath) {
let fieldsToOptimize = {}
let fieldsToCompile = {}
filterFieldPaths.forEach((fieldPath) => {
let value = getFieldValue(filter, fieldPath)
if (storageKeyPath.indexOf(fieldPath) > -1) {
setFieldValue(fieldsToOptimize, fieldPath, value)
} else {
setFieldValue(fieldsToCompile, fieldPath, value)
}
})
return {
fieldsToOptimize,
fieldsToCompile
}
}
|
javascript
|
{
"resource": ""
}
|
q64059
|
getFieldPaths
|
test
|
function getFieldPaths(object, stopOnKeyRange = true) {
let fieldPaths = []
fieldPaths.containsKeyRange = false
generateFieldPaths(object, [])
return fieldPaths
function generateFieldPaths(object, parts) {
Object.keys(object).some((fieldName) => {
let value = object[fieldName]
if (stopOnKeyRange && (value instanceof IDBKeyRange)) {
fieldPaths = null
return true
}
let isTerminalValue =
!(value instanceof Object) ||
(value instanceof Date) ||
(value instanceof Array) ||
(value instanceof IDBKeyRange)
let fieldPath = parts.slice()
fieldPath.push(fieldName)
if (isTerminalValue) {
fieldPaths.push(fieldPath.join("."))
} else {
generateFieldPaths(value, fieldPath)
}
})
}
}
|
javascript
|
{
"resource": ""
}
|
q64060
|
setFieldValue
|
test
|
function setFieldValue(object, fieldPath, value) {
let parts = fieldPath.split(".")
let done = []
let currentObject = object
while (parts.length) {
let field = parts.shift()
if (!parts.length) {
if (currentObject.hasOwnProperty(field)) {
throw new Error(`The ${fieldPath} field seems to be already present `)
}
currentObject[field] = value
break
}
if (!currentObject.hasOwnProperty(field)) {
currentObject[field] = {}
}
if (!(currentObject[field] instanceof Object)) {
throw new Error(`The ${fieldPath} field is in a conflict with the ` +
`${done.join(".")} field`)
}
currentObject = currentObject[field]
done.push(field)
}
}
|
javascript
|
{
"resource": ""
}
|
q64061
|
getFieldValue
|
test
|
function getFieldValue(object, fieldPath) {
if (!fieldPath) {
return object
}
let currentObject = object
fieldPath.split(".").forEach((fieldName) => {
if (!currentObject.hasOwnProperty(fieldName)) {
throw new Error(`The field path ${fieldPath} does not exist in the ` +
"provided object")
}
currentObject = currentObject[fieldName]
})
return currentObject
}
|
javascript
|
{
"resource": ""
}
|
q64062
|
upgradeSchema
|
test
|
function upgradeSchema(nativeDatabase, nativeTransaction, descriptors) {
let objectStoreNames = Array.from(nativeDatabase.objectStoreNames)
let newObjectStoreNames = descriptors.map((objectStore) => {
return objectStore.name
})
objectStoreNames.forEach((objectStoreName) => {
if (newObjectStoreNames.indexOf(objectStoreName) === -1) {
nativeDatabase.deleteObjectStore(objectStoreName)
}
})
descriptors.forEach((objectStoreDescriptor) => {
let objectStoreName = objectStoreDescriptor.name
let nativeObjectStore = objectStoreNames.indexOf(objectStoreName) > -1 ?
nativeTransaction.objectStore(objectStoreName) : null
let objectStoreMigrator = new ObjectStoreMigrator(nativeDatabase,
nativeObjectStore, objectStoreDescriptor)
objectStoreMigrator.executeMigration()
})
}
|
javascript
|
{
"resource": ""
}
|
q64063
|
container
|
test
|
function container(width, height, position, elem) {
return new Element(new ContainerElement(position, elem)
, width, height)
}
|
javascript
|
{
"resource": ""
}
|
q64064
|
mainSection
|
test
|
function mainSection(state) {
var todos = state.todos
var route = state.route
return h("section.main", { hidden: todos.length === 0 }, [
toggleAllPool.change(h("input#toggle-all.toggle-all", {
type: "checkbox",
checked: todos.every(function (todo) {
return todo.completed
})
})),
h("label", { htmlFor: "toggle-all" }, "Mark all as complete"),
h("ul.todo-list", todos.filter(function (todo) {
return route === "completed" && todo.completed ||
route === "active" && !todo.completed ||
route === "all"
}).map(todoItem))
])
}
|
javascript
|
{
"resource": ""
}
|
q64065
|
Client
|
test
|
function Client() {
EventEmitter.call(this);
this.debug = true; //false
this.socket = dgram.createSocket('udp4');
this.isSocketBound = false;
this.devices = {};
this.port = constants.DREAMSCREEN_PORT;
this.discoveryTimer = null;
this.messageHandlers = [];
this.messageHandlerTimeout = 5000; // 45000 45 sec
this.broadcastIp = constants.DEFAULT_BROADCAST_IP;
}
|
javascript
|
{
"resource": ""
}
|
q64066
|
Light
|
test
|
function Light(constr) {
this.client = constr.client;
this.ipAddress = constr.ipAddress;
this.serialNumber = constr.serialNumber;
this.productId = constr.productId; //devicetype
this.lastSeen = constr.lastSeen;
this.isReachable = constr.isReachable;
this.name = constr.name; //devicename
this.groupName = constr.groupName; //groupname
this.groupNumber = constr.groupNumber; //groupnumber
this.mode = constr.mode; //mode
this.brightness = constr.brightness; //brightness
this.ambientColor = constr.ambientColor; //ambientr ambientg ambientb
this.ambientShow = constr.ambientShow; //ambientscene
this.ambientModeType = constr.ambientModeType; //
this.hdmiInput = constr.hdmiInput; //hdmiinput
this.hdmiInputName1 = constr.hdmiInputName1; //hdminame1
this.hdmiInputName2 = constr.hdmiInputName2; //hdminame2
this.hdmiInputName3 = constr.hdmiInputName3; //hdminame3
}
|
javascript
|
{
"resource": ""
}
|
q64067
|
plainText
|
test
|
function plainText(content) {
var textSize = getTextSize(content)
return new Element(new TextElement("left", content)
, textSize.width, textSize.height)
}
|
javascript
|
{
"resource": ""
}
|
q64068
|
test
|
function(json) {
var output = '[<ul class="array collapsible">';
var hasContents = false;
for ( var prop in json ) {
hasContents = true;
output += '<li>';
output += this.valueToHTML(json[prop]);
output += '</li>';
}
output += '</ul>]';
if ( ! hasContents ) {
output = "[ ]";
}
return output;
}
|
javascript
|
{
"resource": ""
}
|
|
q64069
|
test
|
function(error, data, uri) {
// var output = '<div id="error">' +
// this.stringbundle.GetStringFromName('errorParsing') + '</div>';
// output += '<h1>' +
// this.stringbundle.GetStringFromName('docContents') + ':</h1>';
var output = '<div id="error">Error parsing JSON: ' +
error.message+'</div>'
output += '<h1>'+error.stack+':</h1>';
output += '<div id="jsonview">' + this.htmlEncode(data) + '</div>';
return this.toHTML(output, uri + ' - Error');
}
|
javascript
|
{
"resource": ""
}
|
|
q64070
|
write
|
test
|
function write(chunk, encoding, callback) {
if (typeof encoding === 'function') {
callback = encoding
encoding = null
}
if (ended) {
throw new Error('Did not expect `write` after `end`')
}
chunks.push((chunk || '').toString(encoding || 'utf8'))
if (callback) {
callback()
}
// Signal succesful write.
return true
}
|
javascript
|
{
"resource": ""
}
|
q64071
|
end
|
test
|
function end() {
write.apply(null, arguments)
ended = true
processor.process(chunks.join(''), done)
return true
function done(err, file) {
var messages = file ? file.messages : []
var length = messages.length
var index = -1
chunks = null
// Trigger messages as warnings, except for fatal error.
while (++index < length) {
/* istanbul ignore else - shouldn’t happen. */
if (messages[index] !== err) {
emitter.emit('warning', messages[index])
}
}
if (err) {
// Don’t enter an infinite error throwing loop.
global.setTimeout(function() {
emitter.emit('error', err)
}, 4)
} else {
emitter.emit('data', file.contents)
emitter.emit('end')
}
}
}
|
javascript
|
{
"resource": ""
}
|
q64072
|
cleanup
|
test
|
function cleanup() {
emitter.removeListener('data', ondata)
emitter.removeListener('end', onend)
emitter.removeListener('error', onerror)
emitter.removeListener('end', cleanup)
emitter.removeListener('close', cleanup)
dest.removeListener('error', onerror)
dest.removeListener('close', cleanup)
}
|
javascript
|
{
"resource": ""
}
|
q64073
|
onerror
|
test
|
function onerror(err) {
var handlers = emitter._events.error
cleanup()
// Cannot use `listenerCount` in node <= 0.12.
if (!handlers || handlers.length === 0 || handlers === onerror) {
throw err // Unhandled stream error in pipe.
}
}
|
javascript
|
{
"resource": ""
}
|
q64074
|
clean
|
test
|
function clean(root, name) {
const blacklist = ['.git', 'node_modules'];
for (const item of blacklist) {
const pathToItem = path.join(root, item);
if (fs.pathExistsSync(pathToItem)) {
fs.removeSync(pathToItem);
console.log(`${chalk.dim.redBright(item)} has been removed from ${chalk.yellow(name)}`);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q64075
|
ls
|
test
|
function ls() {
const vault = path.join(os.homedir(), '.snap');
const list = shell.ls(vault);
if (!list.length) {
console.log("\nIt seems you don't have anything saved...");
console.log(`You can run ${chalk.yellow('snap save')} to save a directory or Git repo for future use!`);
console.log(`Run ${chalk.yellow('snap save -h')} for more info.\n`);
return;
}
console.log('\nThe following boilerplates have been saved...');
console.log(`Run ${chalk.yellow('snap <boilerplate-name> <project-directory>')} to get started with your new project!`);
for (const bplate of list) {
console.log(` ○ ${bplate}`);
}
console.log();
}
|
javascript
|
{
"resource": ""
}
|
q64076
|
sessionData
|
test
|
function sessionData(req, res, session, cb){
const now = new Date();
if(session.continued)
return cb(null, req, res, session);
async.parallelLimit([
getIp,
getLocation,
getSystem
], 2,
function(err){
cb(err, this.req, this.res, this.session);
if(opts.log_all)
log.timer('sessionData', now);
}.bind({
req: req,
res: res,
session: session
})
);
// ======================
// .ip
function getIp(cb){
session.ip = get_ip(req).clientIp;
cb(null)
}
// .geo :: .city, .state, .country
function getLocation(cb){
if(!geo_lookup)
return cb(null);
const loc = geo_lookup.get(session.ip);
if(!session.geo)
session.geo = {};
if(loc){
try {
if(loc.city)
session.geo.city = loc.city.names.en;
if(loc.subdivisions)
session.geo.state = loc.subdivisions[0].iso_code;
if(loc.country)
session.geo.country = loc.country.iso_code;
if(loc.continent)
session.geo.continent = loc.continent.code;
if(loc.location)
session.geo.time_zone = loc.location.time_zone;
}
catch(e){
log.error('geoIP error:', e);
}
}
cb(null)
}
// .system :: .os{, .broswer{ .name, .version
function getSystem(cb){
var agent = useragent.parse(req.headers['user-agent']);
var os = agent.os;
if(!session.system)
session.system = {};
if(!session.system.browser)
session.system.browser = {};
if(!session.system.os)
session.system.os = {};
session.system.browser.name = agent.family;
session.system.browser.version = agent.major + '.' + agent.minor + '.' + agent.patch;
session.system.os.name = os.family;
session.system.os.version = os.major + '.' + os.minor + '.' + os.patch;
cb(null)
}
}
|
javascript
|
{
"resource": ""
}
|
q64077
|
newRequest
|
test
|
function newRequest(req, res, session, cb){
const now = new Date();
const request = {
_id: `r${crypto.randomBytes(16).toString('hex')}${Date.now()}`,
host: req.hostname,
url: req.url,
method: req.method,
referrer: req.get('Referrer') || req.get('Referer')
};
// populate request query
for(let field in req.query){
if(field === 'ref')
request.ref = req.query[field];
else {
if(!request.query)
request.query = [];
request.query.push({
field: field,
value: req.query[field]
})
}
}
// add request cookie for communication/association with socket
res.cookie('na_req', AES.encrypt(request._id), {
maxAge: 1000 * 60 * 15, // 15 mins
httpOnly: true,
secure: opts.secure
});
// return request object: will be added at sessionSave();
cb(null, req, res, session, request);
if(opts.log_all)
log.timer('newRequest', now);
}
|
javascript
|
{
"resource": ""
}
|
q64078
|
test
|
function(packet) {
this.updatePayload = function(packet) {
this.p_previous = this.p;
this.p = packet.payload;
this.changed = this.p_previous != this.p;
this.retained = packet.retain;
this.lastChange = this.currentChange;
this.currentChange = new Date();
};
this.changedFromTo = function(from, to) {
return this.changed && this.p_previous == from && this.p == to;
};
this.changedTo = function(to) {
return this.changed && this.p == to;
};
this.changedFrom = function(from) {
return this.changed && this.p_previous == from;
};
this.t = packet.topic;
this.updatePayload(packet);
this.currentChange = new Date();
this.lastChange = undefined;
//aliases
this.payload = this.p;
this.topic = this.t;
}
|
javascript
|
{
"resource": ""
}
|
|
q64079
|
test
|
function(){
this.date = new Date();
this.getHours = function() {
return this.date.getHours();
};
this.getMinutes = function() {
return this.date.getMinutes();
};
this.hoursIsBetween = function(a, b) {
if(a <= b) return this.date.getHours() >= a && this.date.getHours() <=b;
else return this.date.getHours() >= a || this.date.getHours() <= b;
};
this.step = function(){
this.date = new Date();
this.isMorning = this.hoursIsBetween(6, 11);
this.isNoon = this.hoursIsBetween(12, 14);
this.isAfternoon = this.hoursIsBetween(15, 17);
this.isEvening = this.hoursIsBetween(18, 23);
this.isNight = this.hoursIsBetween(0,5);
return this;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q64080
|
test
|
function(req, cb) {
req = request.normalizeRequest(req);
var page;
try {
page = this.createPageForRequest(req);
} catch(err) {
if (cb)
return cb(err)
else
throw err;
}
var needData = typeof page.fetchData === 'function' && !this.state.request.data;
if (request.isEqual(this.state.request, req) && !needData)
return;
fetchDataForRequest(this, page, req, function(err, req) {
if (err) {
if (cb)
return cb(err)
else
throw err;
}
this.setState({request: req, page: page});
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q64081
|
create
|
test
|
function create (format, options) {
const ogrFormat = ogrFormats[format]
// shapefiles cannot be streamed out of ogr2ogr
const output = format === 'zip' ? `${options.path || '.'}/${options.name}` : '/vsistdout/'
const input = options.input || 'layer.vrt'
let cmd = ['--config', 'SHAPE_ENCODING', 'UTF-8', '-f', ogrFormat, output, input]
options.geometry = options.geometry && options.geometry.toUpperCase() || 'NONE'
if (format === 'csv') cmd = csvParams(cmd, options)
if (format === 'zip') cmd = shapefileParams(cmd, options)
if (format === 'georss') cmd = georssParams(cmd, options)
return finishOgrParams(cmd)
}
|
javascript
|
{
"resource": ""
}
|
q64082
|
csvParams
|
test
|
function csvParams (cmd, options) {
cmd.push('-lco', 'WRITE_BOM=YES')
const hasPointGeom = options.geometry === 'POINT'
const fields = options.fields.join('|').toLowerCase().split('|')
const hasXY = fields.indexOf('x') > -1 && fields.indexOf('y') > -1
if (hasPointGeom && !hasXY) cmd = cmd.concat(['-lco', 'GEOMETRY=AS_XY'])
return cmd
}
|
javascript
|
{
"resource": ""
}
|
q64083
|
shapefileParams
|
test
|
function shapefileParams (cmd, options) {
// make sure geometries are still written even if the first is null
if (options.geometry !== 'NONE') cmd.push('-nlt', options.geometry.toUpperCase())
cmd.push('-fieldmap', 'identity')
if (!options.ignoreShpLimit) cmd.push('-lco', '2GB_LIMIT=yes')
if (options.srs) cmd.push('-t_srs', options.srs)
return cmd
}
|
javascript
|
{
"resource": ""
}
|
q64084
|
watcherFn
|
test
|
function watcherFn(schemaFilepath, watchInterval, reinitBabelRelayPlugin, prevMtime) {
try {
let stats;
try {
stats = fs.statSync(schemaFilepath);
} catch (e) {
// no problem
}
if (stats) {
if (!prevMtime) prevMtime = stats.mtime;
if (stats.mtime.getTime() !== prevMtime.getTime()) {
prevMtime = stats.mtime;
reinitBabelRelayPlugin();
}
}
setTimeout(
() => {
watcherFn(schemaFilepath, watchInterval, reinitBabelRelayPlugin, prevMtime);
},
watchInterval
).unref(); // fs.watch blocks babel from exit, so using `setTimeout` with `unref`
} catch (e) {
log(e);
}
}
|
javascript
|
{
"resource": ""
}
|
q64085
|
AkamaiPurge
|
test
|
function AkamaiPurge(username, password, objects, options) {
var auth = {},
requestBody = {},
requestOptions;
// Ensure options exist and are the right type
if (options === undefined || !lodash.isPlainObject(options)) {
options = {};
}
// Prepare authentication
auth.username = username;
auth.password = password;
// Validate the given type
if (-1 !== constants.VALID_TYPES.indexOf(options.type)) {
requestBody.type = options.type;
} else if (options.hasOwnProperty('type')) {
warn('Invalid purge request type. Valid types: [' + constants.VALID_TYPES.join(', ') + ']. Given: ' + options.type);
}
// Validate the given domain
if (-1 !== constants.VALID_DOMAINS.indexOf(options.domain)) {
requestBody.domain = options.domain;
} else if (options.hasOwnProperty('domain')) {
warn('Invalid purge request domain. Valid domains: [' + constants.VALID_DOMAINS.join(', ') + ']. Given: ' + options.domain);
}
// Validate the given action
if (-1 !== constants.VALID_ACTIONS.indexOf(options.action)) {
requestBody.action = options.action;
} else if (options.hasOwnProperty('action')) {
warn('Invalid purge request action. Valid actions: [' + constants.VALID_ACTIONS.join(', ') + ']. Given: ' + options.action);
}
// Append objects to the request body
requestBody.objects = objects;
// Prepare request's options
requestOptions = {
uri: constants.AKAMAI_API_QUEUE,
method: 'POST',
json: requestBody,
auth: auth
};
// Reset all modifiers
applyModifiers(AkamaiPurge);
// Create request and return the promise
return AkamaiRequest(requestOptions).then(function (response) {
// Do some post-processing on the response
response.requestBody = requestBody;
// Add a status function that pre-configured to call this purge's `progressUri`
response.status = function () {
// If this purge doesn't have a `progressUri`, return a rejection
if (!response.hasOwnProperty('progressUri')) {
return when.reject(new Error('Missing progressUri from response'));
}
// Otherwise, call `AkamaiStatus`
return AkamaiStatus(username, password, response.progressUri);
};
return response;
});
}
|
javascript
|
{
"resource": ""
}
|
q64086
|
test
|
function () {
// Apply the modifier to the current `options`
options = lodash.assign(options, modifier);
// Create new wrapper function.
var AkamaiPurgeChain = function AkamaiPurgeChain (username, password, objects) {
return AkamaiPurge(username, password, objects, options);
};
// Apply new modifiers to given wrapper function
applyModifiers(AkamaiPurgeChain, options);
// Expose current `options`
AkamaiPurgeChain.options = options;
return AkamaiPurgeChain;
}
|
javascript
|
{
"resource": ""
}
|
|
q64087
|
Mock
|
test
|
function Mock(mount, options) {
// convert to absolute path
this.mount = mount;
this.options = options || {};
this.options.params = this.options.params === undefined ? true : this.options.params;
this.locator = new Locator(mount);
debug('mount at %s', this.mount);
}
|
javascript
|
{
"resource": ""
}
|
q64088
|
forEach
|
test
|
function forEach (object, block, context) {
if (object) {
let resolve = Object; // default
if (object instanceof Function) {
// functions have a "length" property
resolve = Function;
} else if (object.forEach instanceof Function) {
// the object implements a custom forEach method so use that
object.forEach(block, context);
return;
} else if (typeof object === "string") {
// the object is a string
resolve = String;
} else if (typeof object.length === "number") {
// the object is array-like
resolve = Array;
}
resolve.forEach(object, block, context);
}
}
|
javascript
|
{
"resource": ""
}
|
q64089
|
test
|
function(target, source) {
var skeys = _.keys(source);
_.each(skeys, function(skey) {
if (!target[skey]) {
target[skey] = source[skey];
}
});
return target;
}
|
javascript
|
{
"resource": ""
}
|
|
q64090
|
createObject
|
test
|
function createObject(proto, args) {
var instance = Object.create(proto);
if (instance.$meta.constructors) {
instance.$meta.constructors.forEach(function(constructor) {
constructor.apply(instance, args);
});
}
return instance;
}
|
javascript
|
{
"resource": ""
}
|
q64091
|
mergeProperty
|
test
|
function mergeProperty(destination, source, property) {
if (source[property] instanceof Array) {
mergeAsArray(destination, source, property);
}
else if (isPrimitive(source[property]) || !isLiteral(source[property])) {
overrideIfNotExists(destination, source, property);
}
else {
mergeAsObject(destination, source, property);
}
}
|
javascript
|
{
"resource": ""
}
|
q64092
|
mergeAsArray
|
test
|
function mergeAsArray(destination, source, property) {
destination[property] = source[property].concat(destination[property] || []);
}
|
javascript
|
{
"resource": ""
}
|
q64093
|
mergeAsObject
|
test
|
function mergeAsObject(destination, source, property) {
destination[property] = destination[property] || {};
merge(destination[property], source[property]);
}
|
javascript
|
{
"resource": ""
}
|
q64094
|
mixin
|
test
|
function mixin(instance, mixins) {
mixins.forEach(function(Mixin) {
mix(instance, Mixin);
});
return instance;
}
|
javascript
|
{
"resource": ""
}
|
q64095
|
mkdirp
|
test
|
function mkdirp(dir, made) {
var mode = 0777 & (~process.umask());
if (!made) made = null;
dir = path.resolve(dir);
try {
fs.mkdirSync(dir, mode);
made = made || dir;
} catch (err0) {
switch (err0.code) {
case 'ENOENT':
made = mkdirp(path.dirname(dir), made);
mkdirp(dir, made);
break;
default:
var stat;
try {
stat = fs.statSync(dir);
} catch (err1) {
throw err0;
}
if (!stat.isDirectory()) throw err0;
break;
}
}
return made;
}
|
javascript
|
{
"resource": ""
}
|
q64096
|
test
|
function(identifier, target, cb) {
var systemId = _sr.findSystem(identifier);
if (!systemId) { logger.error(ERR_NOSYSID); return cb(new Error(ERR_NOSYSID)); }
fetchTarget(systemId, target, function(err, target) {
if (err) { return cb(err); }
logger.info({ systemId: systemId, target: target }, 'get deployed system');
_sr.getDeployedRevision(systemId, target, cb);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q64097
|
test
|
function(user, name, namespace, cwd, cb) {
logger.info('create system name: ' + name + ', namespace: ' + namespace + ', cwd: ' + cwd);
_sr.createSystem(user, namespace, name, cwd, cb);
}
|
javascript
|
{
"resource": ""
}
|
|
q64098
|
test
|
function(user, path, cwd, cb) {
logger.info('link system: ' + path + ', ' + cwd);
_sr.linkSystem(user, path, cwd, cb);
}
|
javascript
|
{
"resource": ""
}
|
|
q64099
|
test
|
function(identifier, revisionId, out, cb) {
logger.info('list containers: ' + identifier);
var systemId = _sr.findSystem(identifier);
var containers = {};
if (!systemId) { return cb(new Error(ERR_NOSYSID)); }
_builder.loadTargets(systemId, revisionId, function(err, targets) {
if (err) { return cb(err); }
_.each(targets, function(target) {
_.each(target.containerDefinitions, function(cdef) {
containers[cdef.id] = cdef;
});
});
cb(null, _.values(containers));
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.