_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q31000
makePoint
train
function makePoint() { // Pull start time from req and log responseTime var responseTime = Date.now() - req.start; // Add the new point to the batch of points batch.points.push({ measurement: "requests", "tags": { "path": req.path, "host": req.hostname, "verb": req.method, "status": res.statusCode, }, "fields": { "responseTime": responseTime, }, }) // Emit the 'addPoint' event batch.emit("addPoint") }
javascript
{ "resource": "" }
q31001
isGonnaBeLegen
train
function isGonnaBeLegen() { current = shift.call(queue); if (current) { if (typeof current == "function") { current = {name: current[NAME] || "anonymous", test: current}; } (node = putItThereAndGimmeBack( putItThereAndGimmeBack(wru.node, "div"), "span" ))[INNERHTML] = ( (iHasIt(current, NAME) && current[NAME]) || (iHasIt(current, DESCRIPTION) && current[DESCRIPTION]) || UNKNOWN ) + EMPTY + EMPTY; pass = []; fail = []; fatal = []; tmp = {}; giveItATry("setup"); fatal[LENGTH] || giveItATry("test"); waitForIt || Dary(); } else { showSummary(); } }
javascript
{ "resource": "" }
q31002
patch
train
function patch(obj, properties) { var old = {}; for (var name in properties) { old[name] = obj[name]; obj[name] = properties[name]; } return old; }
javascript
{ "resource": "" }
q31003
giveItATry
train
function giveItATry(name) { if (iHasIt(current, name)) { try { current[name](tmp); } catch(doooodeThisIsBAD) { push.call(fatal, EMPTY + doooodeThisIsBAD); } } }
javascript
{ "resource": "" }
q31004
isGonnaBeLegen
train
function isGonnaBeLegen() { current = shift.call(queue); if (current) { if (typeof current == "function") { current = {name: current[NAME] || "anonymous", test: current}; } log(OUTPUT_SEPARATOR); log( (iHasIt(current, NAME) && current[NAME]) || (iHasIt(current, DESCRIPTION) && current[DESCRIPTION]) || UNKNOWN ); pass = []; fail = []; fatal = []; tmp = {}; giveItATry("setup"); fatal[LENGTH] || giveItATry("test"); waitForIt || Dary(); } else { showSummary(); } }
javascript
{ "resource": "" }
q31005
checkVertStretch
train
function checkVertStretch (up, dn, g, doP) /* non-MathML */ { if (g.nodeName.toLowerCase() == 'mo' && g.childNodes.length == 1) { var c = g.firstChild, s = c.data; if (c.nodeType == 3 /* Text */ && (up > 0.9 || dn > 0.9) && (M.prefix_[s] < 25 || M.postfix_[s] < 25 || '|\u2016\u221A' /* ‖ &radic; */.indexOf(s) != -1 || doP)) { var r = (up + dn) / 1.2, radicQ = s == '\u221A', v = (radicQ ? 0.26 : 0.35) + ((radicQ ? 0.15 : 0.25) - dn) / r; g.style.fontSize = r.toFixed(3) + 'em'; g.style.verticalAlign = v.toFixed(3) + 'em'; g.fmUp = up; g.fmDn = dn; g.style.display = 'inline-block'; g.style.transform = g.style.msTransform = g.style.MozTransform = g.style.WebkitTransform = 'scaleX(0.5)'; } } }
javascript
{ "resource": "" }
q31006
parse_table_tokP
train
function parse_table_tokP (dtableQ) { if (dtableQ === undefined) dtableQ = M.dtableQ; var mtrs = []; while (true) { var mtrP_tokP = parse_mtr_tokP(mtrs.length == 0), mtrP = mtrP_tokP[0], tokP = mtrP_tokP[1] || scanTokP(); if (mtrP) mtrs.push(mtrP); if (!(tokP && tokP[1] == ';')) return [newMe_('mtable', mtrs, dtableQ ? {displaystyle: true} : undefined), tokP]; } }
javascript
{ "resource": "" }
q31007
listCacheSet$1
train
function listCacheSet$1(key, value) { var data = this.__data__, index = assocIndexOf$4(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; }
javascript
{ "resource": "" }
q31008
hashDelete$1
train
function hashDelete$1(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; }
javascript
{ "resource": "" }
q31009
getMapData$1
train
function getMapData$1(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; }
javascript
{ "resource": "" }
q31010
arrayEach$1
train
function arrayEach$1(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; }
javascript
{ "resource": "" }
q31011
copyArray$1
train
function copyArray$1(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; }
javascript
{ "resource": "" }
q31012
arrayPush$1
train
function arrayPush$1(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; }
javascript
{ "resource": "" }
q31013
setToArray$1
train
function setToArray$1(set) { var index = -1, result = Array(set.size); set.forEach(function (value) { result[++index] = value; }); return result; }
javascript
{ "resource": "" }
q31014
arrayMap$1
train
function arrayMap$1(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; }
javascript
{ "resource": "" }
q31015
baseSet$1
train
function baseSet$1(object, path, value, customizer) { if (!isObject$6(object)) { return object; } path = castPath$2(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey$2(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject$6(objValue) ? objValue : isIndex$2(path[index + 1]) ? [] : {}; } } assignValue$3(nested, key, newValue); nested = nested[key]; } return object; }
javascript
{ "resource": "" }
q31016
baseSlice$1
train
function baseSlice$1(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : length + start; } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : end - start >>> 0; start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; }
javascript
{ "resource": "" }
q31017
baseUnset$1
train
function baseUnset$1(object, path) { path = castPath$3(path, object); object = parent(object, path); return object == null || delete object[toKey$3(last(path))]; }
javascript
{ "resource": "" }
q31018
baseFindIndex$1
train
function baseFindIndex$1(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while (fromRight ? index-- : ++index < length) { if (predicate(array[index], index, array)) { return index; } } return -1; }
javascript
{ "resource": "" }
q31019
baseIndexOf$1
train
function baseIndexOf$1(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); }
javascript
{ "resource": "" }
q31020
shortOut$1
train
function shortOut$1(func) { var count = 0, lastCalled = 0; return function () { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; }
javascript
{ "resource": "" }
q31021
baseDifference$1
train
function baseDifference$1(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes$2, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap$4(values, baseUnary$3(iteratee)); } if (comparator) { includes = arrayIncludesWith$2; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE$1) { includes = cacheHas$2; isCommon = false; values = new SetCache$2(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = comparator || value !== 0 ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; }
javascript
{ "resource": "" }
q31022
baseFlatten$1
train
function baseFlatten$1(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten$1(value, depth - 1, predicate, isStrict, result); } else { arrayPush$3(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; }
javascript
{ "resource": "" }
q31023
train
function() { if (node.debug) { node.log('STARTING event listener'); } var net = require('net'); var dgram = require('dgram'); node.inputSocket = dgram.createSocket({type:'udp4', reuseAddr: true}); node.inputSocket.on('notify', function (event) { if (node.debug) { node.log('Got a notification.', event) } }); node.inputSocket.on('message', function (msg, rinfo) { //node.log("[" + rinfo.address + "] --> " + msg.toString()); if (rinfo.address == node.address) { if (node.debug) { node.log("UPnP Event from [" + rinfo.address + "] --> " );//+ msg.toString()); } // Split to header and body msg = msg.toString().split('\r\n\r\n'); var header = msg[0]; var body = msg[1]; // Ignore UPNP search requests var method = header.split('\r\n').shift().split(' ').shift().trim(); if (method == 'M-SEARCH'){ return; } // Parse rest of header var arr = header.match(/[^\r\n]+/g); var headerInfo = {}; for (var i = 1; i < arr.length; ++i){ var tem = arr[i].split(/:(.+)?/); if (typeof(tem[1]) == 'string'){ tem[1] = tem[1].trim(); } headerInfo[tem[0].toLowerCase()] = tem[1]; }; //node.log("METHOD: " + method); //node.log("BODY: " + body); //node.log("NTS: " + headerInfo['nts']); // NOTIFY messages tell us about the properties that changed if (method == 'NOTIFY' && headerInfo['nts'] == 'yamaha:propchange') { var parseString = require('xml2js').parseString; parseString(body, function (err, result) { if (err) { node.error('Failed to parse the event with error: ' + err); return; } // Check the received object var zoneName = undefined; if (result.hasOwnProperty('YAMAHA_AV')) { if (result.YAMAHA_AV.hasOwnProperty('Main_Zone')) { zoneName = 'Main_Zone'; } else if (result.YAMAHA_AV.hasOwnProperty('Zone_2')) { zoneName = 'Zone_2'; } else if (result.YAMAHA_AV.hasOwnProperty('Zone_3')) { zoneName = 'Zone_3'; } else if (result.YAMAHA_AV.hasOwnProperty('Zone_4')) { zoneName = 'Zone_4'; } } if (zoneName === undefined || result.YAMAHA_AV[zoneName] === undefined || result.YAMAHA_AV[zoneName][0] === undefined) { if (node.debug) { node.warn('Unknown event message format: ' + JSON.stringify(result)); } return; } for (var i in result.YAMAHA_AV[zoneName][0].Property) { var prop = result.YAMAHA_AV[zoneName][0].Property[i]; if (node.debug) { node.log('Property-Change: ' + prop); } // Event Notification only notifies that there is a change in each item. // It is necessary to issue the GET command to obtain the content of the item with the change. if (prop == 'Power') { // Get current power state and publish to all subscriber. node.sendGetCommand(zoneName + '.Power_Control.Power').then(function(value) { for (var s in node.subscriptions) { node.subscriptions[s].handler(zoneName + '.Power_Control.Power', value); } }).catch(function(error) { node.error('Failed to request data from AVR with error: ' + error); }); } else if (prop == 'Input') { // Get current input selection and publish to all subscriber. node.sendGetCommand(zoneName + '.Input.Input_Sel').then(function(value) { for (var s in node.subscriptions) { node.subscriptions[s].handler(zoneName + '.Input.Input_Sel', value); } }).catch(function(error) { node.error('Failed to request data from AVR with error: ' + error); }); } else if (prop == 'Volume') { // We don't know from the event itself if volume changed or mute/unmute was pressed. // Therefore we read both states. node.sendGetCommand(zoneName + '.Volume.Lvl').then(function(value) { for (var s in node.subscriptions) { node.subscriptions[s].handler(zoneName + '.Volume.Lvl', value); } }).catch(function(error) { node.error('Failed to request data from AVR with error: ' + error); }); node.sendGetCommand(zoneName + '.Volume.Mute').then(function(value) { for (var s in node.subscriptions) { node.subscriptions[s].handler(zoneName + '.Volume.Mute', value); } }).catch(function(error) { node.error('Failed to request data from AVR with error: ' + error); }); } else if (prop == 'Play_Info') { // When getting the Play_Info event we need to check the current input mode and then read // the corresponding item that holds info about current mode. node.sendGetCommand(zoneName + '.Input.Input_Sel').then(function(value) { var validInputs = { 'TUNER': 'Tuner', 'Napster': 'Napster', 'Spotify': 'Spotify', 'JUKE': 'JUKE', 'SERVER': 'SERVER', 'NET RADIO': 'NET_RADIO', 'USB': 'USB', 'iPod_USB': 'iPod_USB', 'AirPlay': 'AirPlay' }; if (validInputs.hasOwnProperty(value)) { node.sendGetCommand(validInputs[value] + '.Play_Info').then(function(value2) { for (var s in node.subscriptions) { node.subscriptions[s].handler(value + '.Play_Info', value2); } }).catch(function(error) { node.error('Received event Play_Info but failed to read play info of current input selection: ' + error); }); } else { if (node.debug) { node.log('Received event Play_Info but do not know or support current input selection ' + value); } } }).catch(function(error) { node.error('Received event Play_Info but failed to read current input selection: ' + error); }); } else if (prop == 'List_Info') { // When getting the List_info event we need to check the current input mode and then read // the corresponding item that holds info about current mode. node.sendGetCommand(zoneName + '.Input.Input_Sel').then(function(value) { var validInputs = { 'Napster': 'Napster', 'JUKE': 'JUKE', 'SERVER': 'SERVER', 'NET RADIO': 'NET_RADIO', 'USB': 'USB', 'iPod_USB': 'iPod_USB' }; if (validInputs.hasOwnProperty(value)) { node.sendGetCommand(validInputs[value] + '.List_Info').then(function(value2) { for (var s in node.subscriptions) { node.subscriptions[s].handler(value + '.List_Info', value2); } }).catch(function(error) { node.error('Received event List_Info but failed to read play info of current input selection: ' + error); }); } else { if (node.debug) { node.log('Received event List_Info but do not know or support current input selection ' + value); } } }).catch(function(error) { node.error('Received event List_Info but failed to read current input selection: ' + error); }); } else { // The event is not known. Maybe the AVR is too new. if (node.debug) { node.log('Received unsupported Property-Change via multicast: ' + prop); } return; } } }); } } }); node.inputSocket.on('listening', function () { try { var address = node.inputSocket.address(); node.log('UDP client listening on ' + address.address + ":" + address.port); node.inputSocket.setBroadcast(true) node.inputSocket.setMulticastTTL(5); node.inputSocket.addMembership('239.255.255.250'); //node.inputSocket.addMembership('239.255.255.250', '192.168.0.101'); //node.inputSocket.addMembership('239.255.255.250', '127.0.0.1'); /* var message = new Buffer( "M-SEARCH * HTTP/1.1\r\n" + "HOST: 239.255.255.250:1900\r\n" + "MAN: \"ssdp:discover\"\r\n" + "ST: ssdp:all\r\n" + // Essential, used by the client to specify what they want to discover, eg 'ST:ge:fridge' "MX: 3\r\n" + // 1 second to respond (but they all respond immediately?) "\r\n"); */ //node.inputSocket.send(message, 0, message.length, 1900, "239.255.255.250"); } catch (err) { node.warn('Cannot bind address for UPNP event listener. Port probably already in use. Error: ' + err); } }); try { node.inputSocket.bind(1900); } catch (err) { node.warn('Cannot bind address for UPNP event listener. Port probably already in use. Error: ' + err); } }
javascript
{ "resource": "" }
q31024
transform
train
function transform(str) { str = str.split(/^lazy\(/gm).join('require('); var lines = str.split(/\r\n|\n/); var len = lines.length; var re = regex(); var idx = 0; var start = false; var isExported = false; var namespace; var res = ''; while (idx < len) { var line = lines[idx++]; res += '\n'; if (/(?:var fn = require|require = utils)/.test(line)) { continue; } if (/^require = fn/.test(line)) { continue; } // adding this line to catch other variable names than the more specific cases above if (/^require = (?:.*)/.test(line)) { continue; } var match = re.exec(line); if (!match) { res += line; continue; } if (match && (match[2] === 'lazy-cache' || match[3] === 'lazy-cache')) { namespace = toNamespace(match[1]); if (/module\.exports/.test(match[1])) { isExported = true; } line = 'var ' + namespace + ' = {};'; start = true; res += line; continue; } if (!start) { res += line; continue; } var variable = toVariable(match); var prefix = toProperty(namespace, variable, match[2]); line = line.split(match[0]).join(prefix); res += line; } if (isExported) { res += '\nmodule.exports = ' + namespace + ';'; } return res.replace(/^\s+/, ''); }
javascript
{ "resource": "" }
q31025
camelcase
train
function camelcase(str) { if (!/[\s\W]/.test(str)) return str; if (str.length === 1) { return str.toLowerCase(); } str = str.replace(/^[\W_]+|[\W_]+$/g, '').toLowerCase(); return str.replace(/[\W_]+(\w|$)/g, function(_, ch) { return ch.toUpperCase(); }); }
javascript
{ "resource": "" }
q31026
createWasmModule
train
function createWasmModule(source, wasm) { var length = wasm.length; var buffer = []; for (var i = 0; i < length; i += 1) { buffer.push(wasm[i]); } var module = "var buffer = new ArrayBuffer(" + wasm.length + ");\n var uint8 = new Uint8Array(buffer);\n uint8.set([" + buffer.join(',') + "]);\n " + wasmFooter; return module; }
javascript
{ "resource": "" }
q31027
createJsModule
train
function createJsModule(source) { var compilerOptions = { compilerOptions: { target: ts.ScriptTarget.ES5, module: ts.ModuleKind.CommonJS, alwaysStrict: false } }; var transpiled = ts.transpileModule(source, compilerOptions); return transpiled.outputText; }
javascript
{ "resource": "" }
q31028
AssemblyScriptLiveLoader
train
function AssemblyScriptLiveLoader(source) { var jsModule; var wasmModule; if (this.cacheable) { this.cacheable(); } this.addDependency(wasmFooterPath); jsModule = createJsModule(source); wasmModule = createWasmModule(source, compile(source)); return createCompatibleModule(jsModule, wasmModule); }
javascript
{ "resource": "" }
q31029
createTimeout
train
function createTimeout(timer, i, callback) { return setTimeout(function() { callback(timer, i); }, timer.seconds * 1000); }
javascript
{ "resource": "" }
q31030
init
train
function init(_config) { if (initialized) return; // Validate the config config = helpers.validateConfig(_config); // Create a user for the bot users[config.name] = helpers.createUser(true); // Create a user for the channel owner var name = config.channel.replace('#', ''); users[name] = helpers.createUser(true); // Init the client ircClient = new irc.Client(config.server, config.name, { userName: config.name, realName: config.name, password: config.password, port: config.port, secure: config.secure, }); // Add listeners ircClient.addListener('error', onError); ircClient.addListener('registered', onRegistered); ircClient.addListener('join' + config.channel, onJoin); ircClient.addListener('part' + config.channel, onPart); ircClient.addListener('motd', onMotd); ircClient.addListener('notice', onNotice); ircClient.addListener('message' + config.channel, onMessage); ircClient.addListener('raw', onRaw); // If there is a discord token if (config.discordToken) { // Init the discord client discordClient = new Discord.Client({ token: config.discordToken, autorun: true, }); // Add listeners discordClient.on('ready', onDiscordReady); discordClient.on('message', onDiscordMessage); } // If we are logging, create the directory if not exists if (config.log && typeof config.log === 'string') mkdirp.sync(config.log); // Init stream checker if (config.autoExit || config.discordToken) streamInterval = setInterval(onCheckStream, 60 * 1000) initialized = true; }
javascript
{ "resource": "" }
q31031
exit
train
function exit() { if (!initialized || exited) return; log('Exiting...', true); // Leave the twitch channel if (ircClient) ircClient.part(config.channel); // Leave discord if (discordClient) discordClient.disconnect(); // Clear the stream check interval if (streamInterval) clearInterval(streamInterval); // Clear all the timeouts timeouts.forEach(function(t) { clearTimeout(t); }); exited = true; }
javascript
{ "resource": "" }
q31032
isSpam
train
function isSpam(from, message) { if (!config.filterSpam) return false; // Skip if this is a mod if (users[from] && users[from].mod) return false; // Check for capital letter spam var uppercaseCount = message.replace(/[^A-Z]/g, '').length; if (uppercaseCount >= 10 && uppercaseCount >= message.length / 2) { timeoutUser(from, null, 'stop using capital letters'); return true; } return false; }
javascript
{ "resource": "" }
q31033
timeoutUser
train
function timeoutUser(name, seconds, reason) { // Create a user if it doesn't exist users[name] = users[name] || helpers.createUser(); users[name].offenses++; var offenses = users[name].offenses; if (offenses > config.maxOffenses) banUser(name); else { seconds = seconds || (offenses === 1 ? 10 : 60); twitchCommand('timeout', name + ' ' + seconds + ' ' + reason + ' - warning ' + offenses + ' of ' + config.maxOffenses); } }
javascript
{ "resource": "" }
q31034
say
train
function say(message, channelId) { channelId = channelId || false; if (channelId) { sendDiscordMessage(channelId, message); return; } if (!ircClient || typeof message !== 'string') return; ircClient.say(config.channel, message); }
javascript
{ "resource": "" }
q31035
sendDiscordMessage
train
function sendDiscordMessage(id, message) { if (!discordClient || typeof id !== 'string' || typeof message !== 'string') return; discordClient.sendMessage({ to: id, message: message, }); }
javascript
{ "resource": "" }
q31036
logChat
train
function logChat(from, message) { if (typeof config.log !== 'string' || !from || typeof message !== 'string') return; // Get the current moment var now = moment(); // Create the file name var file = path.join(config.log, now.format('YYYY-MM-DD') + '-' + 'chat.log'); // Create the text to log based on moment and chat info var text = '[' + now.format('YYYY-MM-DD hh:mm A') + '] ' + from + ': ' + message + '\n'; // Append the text to the log file fs.appendFile(file, text, function(err) { if (err) error(err); }); }
javascript
{ "resource": "" }
q31037
train
function(region) { if (this._isShown) { throw new Error('This component is already shown in a region.'); } if (!region) { throw new Error('Please supply a region to show inside.'); } this.region = region; this.triggerMethod('before:show'); this._showView(); this._isShown = true; this.triggerMethod('show'); }
javascript
{ "resource": "" }
q31038
train
function() { var view = this.view = this._getView(); this._initializeViewEvents(); // Trigger show:view after the view is shown in the region this.listenTo(view, 'show', _.partial(this.triggerMethod, 'show:view')); // Trigger before:show before the region shows the view this.triggerMethod('before:show:view'); // Show the view in the region this.region.show(view); // Destroy the component if the region is emptied because it destroys // the view this.listenToOnce(this.region, 'empty', this.destroy); }
javascript
{ "resource": "" }
q31039
any
train
function any(target, fn) { var keys = Object.keys(target); for(var i = 0, len = keys.length; i < len; i++) { var key = keys[i]; var value = target[key]; if(fn(value, key)) return true; } return false; }
javascript
{ "resource": "" }
q31040
extend
train
function extend(target, source) { var keys = Object.keys(source); for(var i = 0, len = keys.length; i < len; i++) { var key = keys[i]; target[key] = source[key]; } return target; }
javascript
{ "resource": "" }
q31041
train
function() { $.each(watched_props, function(index, value) { if (index != '_interval' && index != '_interval_func' && index != '_element' && index != '_speed' && index != '_status' && index != '_load') { var new_value = value.orig_value; // Are we returning a jQuery function value? if (index.match(/\)/g)) { var j_func = index.replace(/\(\)/g, ""); // Do we have arguments to pass to the function if ($.isPlainObject(value) && 'args' in value.orig_object) { // If function is method of jQuery if (j_func in $) { new_value = $[j_func].apply(j_func, value.orig_object.args); // Assume function is method of jQuery.fn } else { new_value = $.fn[j_func].apply($(plugin.element), value.orig_object.args); } } else { // If function is method of jQuery if (j_func in $) { new_value = $(plugin.element)[j_func](); // Assume function is method of jQuery.fn } else { new_value = $.fn[j_func].apply($(plugin.element)); } } // Are we watching a property of the DOM element } else if (index in plugin.element) { new_value = plugin.element[index]; // Are we watching a CSS property? } else { new_value = plugin.element.style[index]; } } // Execute the interval callback when present if ($.isPlainObject(value.orig_object)) { if ('onInterval' in value.orig_object) { value.orig_object.onInterval( value.orig_value, value.elm_ref); } } // When the currently calculated value differs from the original, execute callback if (new_value != value.orig_value || plugin._load) { if ($.isFunction(value.orig_object)) { plugin._load = false; value.orig_object( value.orig_value, new_value, value.elm_ref ); } else if ($.isPlainObject(value.orig_object)) { plugin._load = false; value.orig_object.onChange( value.orig_value, new_value, value.elm_ref, 'args' in value.orig_object ? value.orig_object.args : [] ); } // Update the original value with the new value value.orig_value = new_value; } }); }
javascript
{ "resource": "" }
q31042
train
function (query, update, fship) { var options = { new: false }; return function (done) { this.findOneAndUpdate(query, update, options, function (err, res) { done(err, fship); }); } }
javascript
{ "resource": "" }
q31043
train
function (m1, m2, fship) { var query = {_id: m1}; query[pathName] = {$elemMatch: {_id: m2}}; var updater = {$set: {}}; updater.$set[pathName+".$.status"] = fship.status; return _update(query, updater, fship); }
javascript
{ "resource": "" }
q31044
train
function (m1, m2, fship) { var query = {_id: m1}; fship.added = new Date(); var updater = {$push: {}}; updater.$push[pathName] = fship; return _update(query, updater, fship); }
javascript
{ "resource": "" }
q31045
train
function (done) { var select = {}; select[pathName] = 1; Model.findOne({_id: model}, select, function (err, doc) { if (err) return done(err); if (!doc) return done(null, []); done(null, doc[pathName].reduce(function (o, friend) { o[friend._id] = friend.toObject(); return o; }, {})); }); }
javascript
{ "resource": "" }
q31046
defaults
train
function defaults(options, defaultOptions) { options || (options = {}); for (var opt in defaultOptions) { if (defaultOptions.hasOwnProperty(opt) && !options.hasOwnProperty(opt)) { options[opt] = defaultOptions[opt]; } } return options; }
javascript
{ "resource": "" }
q31047
resetSeat
train
function resetSeat(s) { const street = this.street const stage = this.stage const preflop = street === 'preflop' const chipsName = 'chips' + street[0].toUpperCase() + street.slice(1) const p = script.players[s.playerIdx] const chips = p[chipsName] return Object.assign({}, seats[p.seatno], { chips : chips , action : null , amount : 0 , chipsInFront: preflop ? p.chipsInFront : 0 , bet : 0 , investedBet : preflop && p.bb ? 1 : 0 , _lastUpdate : stage }) }
javascript
{ "resource": "" }
q31048
train
function() { var min = typeof this.options.start_value !== 'undefined' && this.min >= 0 ? this.options.start_value : this.min, start_value = this.round(min, 1); /* This is a boundary condition */ if (this.min > 0 && start_value > this.min) { return 0; } if (this.min === this.max) { return 0; } return start_value; }
javascript
{ "resource": "" }
q31049
train
function(value) { return Math.pow(10, Math.round((Math.log(value) / Math.LN10)) - 1); }
javascript
{ "resource": "" }
q31050
train
function(data, options) { if (typeof data.length !== 'undefined') { if (typeof data[0].length !== 'undefined') { this.grouped = true; // TODO: Find longest? this.group_size = data[0].length; var o = {}, k, i = 0; for (k in options.labels) { k = options.labels[k]; o[k] = data[i]; i++; } return o; } else { return { 'one': data }; } } else { return data; } }
javascript
{ "resource": "" }
q31051
train
function() { // Make sure the true largest value is used for max return this.options.line ? { start_value: 0, max: Helpers.max([Helpers.max(this.options.line), Helpers.max(this.flat_data)]) } : { start_value: 0 }; }
javascript
{ "resource": "" }
q31052
train
function() { this.bar_padding = this.options.bar_padding || 5; this.bar_width = this.options.bar_size || this.calculateBarWidth(); if (this.options.bar_size && !this.options.bar_padding) { this.bar_padding = this.graph_width / this.data_size; } this.options.plot_padding = (this.bar_width / 2) - (this.bar_padding / 2); this.step = this.calculateStep(); this.grid_start_offset = this.bar_padding - 1; this.start_y = this.options.height - this.y_padding_bottom; }
javascript
{ "resource": "" }
q31053
train
function() { var width = (this.graph_width / this.data_size) - this.bar_padding; if (this.grouped) { //width = width / this.group_size - (this.bar_padding * this.group_size); } if (this.options.max_bar_size && width > this.options.max_bar_size) { width = this.options.max_bar_size; this.bar_padding = this.graph_width / this.data_size; } return width; }
javascript
{ "resource": "" }
q31054
train
function(index, pathString, x, y, colour) { if (this.options.highlight_colours && this.options.highlight_colours.hasOwnProperty(index)) { colour = this.options.highlight_colours[index]; } x = x + this.bar_padding; pathString += 'M' + x + ',' + this.start_y; pathString += 'L' + x + ',' + y; this.paper.path(pathString).attr({ stroke: colour, 'stroke-width': this.bar_width + 'px' }); pathString = ''; x = x + this.step; pathString += 'M' + x + ',' + this.start_y; return pathString; }
javascript
{ "resource": "" }
q31055
attribToHtml
train
function attribToHtml(str) { return str.replace(pr_amp, '&amp;') .replace(pr_lt, '&lt;') .replace(pr_gt, '&gt;') .replace(pr_quot, '&quot;'); }
javascript
{ "resource": "" }
q31056
htmlToText
train
function htmlToText(html) { var pos = html.indexOf('&'); if (pos < 0) { return html; } // Handle numeric entities specially. We can't use functional substitution // since that doesn't work in older versions of Safari. // These should be rare since most browsers convert them to normal chars. for (--pos; (pos = html.indexOf('&#', pos + 1)) >= 0;) { var end = html.indexOf(';', pos); if (end >= 0) { var num = html.substring(pos + 3, end); var radix = 10; if (num && num.charAt(0) === 'x') { num = num.substring(1); radix = 16; } var codePoint = parseInt(num, radix); if (!isNaN(codePoint)) { html = (html.substring(0, pos) + String.fromCharCode(codePoint) + html.substring(end + 1)); } } } return html.replace(pr_ltEnt, '<') .replace(pr_gtEnt, '>') .replace(pr_aposEnt, "'") .replace(pr_quotEnt, '"') .replace(pr_nbspEnt, ' ') .replace(pr_ampEnt, '&'); }
javascript
{ "resource": "" }
q31057
isPreformatted
train
function isPreformatted(node, content) { // PRE means preformatted, and is a very common case, so don't create // unnecessary computed style objects. if ('PRE' === node.tagName) { return true; } if (!newlineRe.test(content)) { return true; } // Don't care var whitespace = ''; // For disconnected nodes, IE has no currentStyle. if (node.currentStyle) { whitespace = node.currentStyle.whiteSpace; } else if (window.getComputedStyle) { // Firefox makes a best guess if node is disconnected whereas Safari // returns the empty string. whitespace = window.getComputedStyle(node, null).whiteSpace; } return !whitespace || whitespace === 'pre'; }
javascript
{ "resource": "" }
q31058
makeTabExpander
train
function makeTabExpander(tabWidth) { var SPACES = ' '; var charInLine = 0; return function (plainText) { // walk over each character looking for tabs and newlines. // On tabs, expand them. On newlines, reset charInLine. // Otherwise increment charInLine var out = null; var pos = 0; for (var i = 0, n = plainText.length; i < n; ++i) { var ch = plainText.charAt(i); switch (ch) { case '\t': if (!out) { out = []; } out.push(plainText.substring(pos, i)); // calculate how much space we need in front of this part // nSpaces is the amount of padding -- the number of spaces needed // to move us to the next column, where columns occur at factors of // tabWidth. var nSpaces = tabWidth - (charInLine % tabWidth); charInLine += nSpaces; for (; nSpaces >= 0; nSpaces -= SPACES.length) { out.push(SPACES.substring(0, nSpaces)); } pos = i + 1; break; case '\n': charInLine = 0; break; default: ++charInLine; } } if (!out) { return plainText; } out.push(plainText.substring(pos)); return out.join(''); }; }
javascript
{ "resource": "" }
q31059
train
function (job) { var sourceCode = job.source, basePos = job.basePos; /** Even entries are positions in source in ascending order. Odd enties * are style markers (e.g., PR_COMMENT) that run from that position until * the end. * @type {Array.<number|string>} */ var decorations = [basePos, PR_PLAIN]; var pos = 0; // index into sourceCode var tokens = sourceCode.match(tokenizer) || []; var styleCache = {}; for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) { var token = tokens[ti]; var style = styleCache[token]; var match = void 0; var isEmbedded; if (typeof style === 'string') { isEmbedded = false; } else { var patternParts = shortcuts[token.charAt(0)]; if (patternParts) { match = token.match(patternParts[1]); style = patternParts[0]; } else { for (var i = 0; i < nPatterns; ++i) { patternParts = fallthroughStylePatterns[i]; match = token.match(patternParts[1]); if (match) { style = patternParts[0]; break; } } if (!match) { // make sure that we make progress style = PR_PLAIN; } } isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5); if (isEmbedded && !(match && typeof match[1] === 'string')) { isEmbedded = false; style = PR_SOURCE; } if (!isEmbedded) { styleCache[token] = style; } } var tokenStart = pos; pos += token.length; if (!isEmbedded) { decorations.push(basePos + tokenStart, style); } else { // Treat group 1 as an embedded block of source code. var embeddedSource = match[1]; var embeddedSourceStart = token.indexOf(embeddedSource); var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length; if (match[2]) { // If embeddedSource can be blank, then it would match at the // beginning which would cause us to infinitely recurse on the // entire token, so we catch the right context in match[2]. embeddedSourceEnd = token.length - match[2].length; embeddedSourceStart = embeddedSourceEnd - embeddedSource.length; } var lang = style.substring(5); // Decorate the left of the embedded source appendDecorations( basePos + tokenStart, token.substring(0, embeddedSourceStart), decorate, decorations); // Decorate the embedded source appendDecorations( basePos + tokenStart + embeddedSourceStart, embeddedSource, langHandlerForExtension(lang, embeddedSource), decorations); // Decorate the right of the embedded section appendDecorations( basePos + tokenStart + embeddedSourceEnd, token.substring(embeddedSourceEnd), decorate, decorations); } } job.decorations = decorations; }
javascript
{ "resource": "" }
q31060
sourceDecorator
train
function sourceDecorator(options) { var shortcutStylePatterns = [], fallthroughStylePatterns = []; if (options['tripleQuotedStrings']) { // '''multi-line-string''', 'single-line-string', and double-quoted shortcutStylePatterns.push( [PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/, null, '\'"']); } else if (options['multiLineStrings']) { // 'multi-line-string', "multi-line-string" shortcutStylePatterns.push( [PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/, null, '\'"`']); } else { // 'single-line-string', "single-line-string" shortcutStylePatterns.push( [PR_STRING, /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/, null, '"\'']); } if (options['verbatimStrings']) { // verbatim-string-literal production from the C# grammar. See issue 93. fallthroughStylePatterns.push( [PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]); } if (options['hashComments']) { if (options['cStyleComments']) { // Stop C preprocessor declarations at an unclosed open comment shortcutStylePatterns.push( [PR_COMMENT, /^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/, null, '#']); fallthroughStylePatterns.push( [PR_STRING, /^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/, null]); } else { shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']); } } if (options['cStyleComments']) { fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]); fallthroughStylePatterns.push( [PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]); } if (options['regexLiterals']) { var REGEX_LITERAL = ( // A regular expression literal starts with a slash that is // not followed by * or / so that it is not confused with // comments. '/(?=[^/*])' // and then contains any number of raw characters, + '(?:[^/\\x5B\\x5C]' // escape sequences (\x5C), + '|\\x5C[\\s\\S]' // or non-nesting character sets (\x5B\x5D); + '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+' // finally closed by a /. + '/'); fallthroughStylePatterns.push( ['lang-regex', new RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')') ]); } var keywords = options['keywords'].replace(/^\s+|\s+$/g, ''); if (keywords.length) { fallthroughStylePatterns.push( [PR_KEYWORD, new RegExp('^(?:' + keywords.replace(/\s+/g, '|') + ')\\b'), null]); } shortcutStylePatterns.push([PR_PLAIN, /^\s+/, null, ' \r\n\t\xA0']); fallthroughStylePatterns.push( // TODO(mikesamuel): recognize non-latin letters and numerals in idents [PR_LITERAL, /^@[a-z_$][a-z_$@0-9]*/i, null], [PR_TYPE, /^@?[A-Z]+[a-z][A-Za-z_$@0-9]*/, null], [PR_PLAIN, /^[a-z_$][a-z_$@0-9]*/i, null], [PR_LITERAL, new RegExp( '^(?:' // A hex number + '0x[a-f0-9]+' // or an octal or decimal number, + '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)' // possibly in scientific notation + '(?:e[+\\-]?\\d+)?' + ')' // with an optional modifier like UL for unsigned long + '[a-z]*', 'i'), null, '0123456789'], [PR_PUNCTUATION, /^.[^\s\w\.$@\'\"\`\/\#]*/, null]); return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns); }
javascript
{ "resource": "" }
q31061
emitTextUpTo
train
function emitTextUpTo(sourceIdx) { if (sourceIdx > outputIdx) { if (openDecoration && openDecoration !== currentDecoration) { // Close the current decoration html.push('</span>'); openDecoration = null; } if (!openDecoration && currentDecoration) { openDecoration = currentDecoration; html.push('<span class="', openDecoration, '">'); } // This interacts badly with some wikis which introduces paragraph tags // into pre blocks for some strange reason. // It's necessary for IE though which seems to lose the preformattedness // of <pre> tags when their innerHTML is assigned. // http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html // and it serves to undo the conversion of <br>s to newlines done in // chunkify. var htmlChunk = textToHtml( tabExpander(sourceText.substring(outputIdx, sourceIdx))) .replace(lastWasSpace ? startOrSpaceRe : adjacentSpaceRe, '$1&#160;'); // Keep track of whether we need to escape space at the beginning of the // next chunk. lastWasSpace = trailingSpaceRe.test(htmlChunk); html.push(htmlChunk.replace(newlineRe, lineBreaker)); outputIdx = sourceIdx; } }
javascript
{ "resource": "" }
q31062
referenceProtection
train
function referenceProtection(session) { function checkScope(funcName) { return (msg) => { if (typeof session[funcName] === 'function') { session[funcName](msg); } } } return { actor: session.actor, debug: checkScope('debug'), sendToClient: checkScope('sendToClient') } }
javascript
{ "resource": "" }
q31063
train
function(raw) { var result = {} var md = raw.split(protocol.FDFS_RECORD_SEPERATOR) md.forEach(function(item) { var arr = item.split(protocol.FDFS_FIELD_SEPERATOR) var key = helpers.trim(arr[0]) var value = helpers.trim(arr[1]) result[key] = value }) return result }
javascript
{ "resource": "" }
q31064
getStyle
train
function getStyle(el, styleProp) { if (typeof window === 'undefined') { return; } var style; if (el.currentStyle) { style = el.currentStyle[styleProp]; } else if (window.getComputedStyle) { style = document.defaultView.getComputedStyle(el, null).getPropertyValue(styleProp); } if (style && style.length === 0) { style = null; } return style; }
javascript
{ "resource": "" }
q31065
parseGraph
train
function parseGraph (rdf, baseUrl, rdfSource, contentType) { let parsedGraph = rdf.graph() rdf.parse(rdfSource, parsedGraph, baseUrl, contentType) return parsedGraph }
javascript
{ "resource": "" }
q31066
train
function(num, dec) { var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec); return result; }
javascript
{ "resource": "" }
q31067
train
function(data) { var values = [], i = 0; for (i = 0; i < data.length; i++) { values.push(this.normalise(data[i])); } return values; }
javascript
{ "resource": "" }
q31068
train
function(data) { var flat_data = []; if (typeof data.length === 'undefined') { if (typeof data === 'object') { for (var key in data) { if (data.hasOwnProperty(key)) flat_data = flat_data.concat(this.flatten(data[key])); } } else { return []; } } for (var i = 0; i < data.length; i++) { if (typeof data[i].length === 'number') { flat_data = flat_data.concat(this.flatten(data[i])); } else { flat_data.push(data[i]); } } return flat_data; }
javascript
{ "resource": "" }
q31069
train
function(start, end, options) { var values = [], i; for (i = start; i < end; i++) { if (options && options.skip) { if (i % options.skip === 0) { values.push(i); } else { values.push(undefined); } } else { values.push(i); } } return values; }
javascript
{ "resource": "" }
q31070
summary
train
function summary(hand) { const res = {} if (hand.players == null || hand.players.length === 0) return res const bb = hand.info.bb res.header = getHeader(hand) const seatsInfo = getSeats(hand) res.seats = seatsInfo.seats res.chipStackRatio = seatsInfo.hero != null ? getChipStackRatio(res.header.gametype, res.header.bb, seatsInfo.hero) : null res.preflopSummary = seatsInfo.preflopSummary res.preflopActions = getPlayerActions(hand, hand.actions.preflop) if (hand.actions.flop != null && hand.actions.flop.length > 0) { res.flopSummary = getFlopSummary(hand, bb) res.flopActions = getPlayerActions(hand, hand.actions.flop) } if (hand.actions.turn != null && hand.actions.turn.length > 0) { res.turnSummary = getTurnSummary(hand, bb) res.turnActions = getPlayerActions(hand, hand.actions.turn) } if (hand.actions.river != null && hand.actions.river.length > 0) { res.riverSummary = getRiverSummary(hand, bb) res.riverActions = getPlayerActions(hand, hand.actions.river) } res.totalPot = getTotalPot(hand) res.spoilers = getSpoilers(hand.players) return res }
javascript
{ "resource": "" }
q31071
sheetToTable
train
function sheetToTable(sheet) { if (sheet.data.length === 0 || sheet.data[0].rowData === undefined) { return { title: sheet.properties.title, headers: [], formats: [], rows: [] }; } const gridData = sheet.data[0]; // first (unique) range const headers = gridData.rowData[0].values // first row (headers) .map(col => formattedValue(col)); const otherRows = gridData.rowData.slice(1); const values = otherRows.length > 0 ? otherRows[0].values : new Array(headers.length).fill({}); return { title: sheet.properties.title, headers: headers, formats: values.map(value => effectiveFormat(value)), rows: otherRows.map(row => zipObject( headers, row.values.map(value => ({ value: effectiveValue(value), stringValue: formattedValue(value) })) ) ) }; }
javascript
{ "resource": "" }
q31072
getRanges
train
async function getRanges( auth, spreadsheetId, ranges, fields = 'properties.title,sheets.properties,sheets.data(rowData.values.effectiveValue,rowData.values.formattedValue,rowData.values.effectiveFormat.numberFormat)' ) { var sheets = google.sheets('v4'); const response = await Q.ninvoke(sheets.spreadsheets, 'get', { auth: auth, spreadsheetId: spreadsheetId, // https://developers.google.com/sheets/guides/concepts, https://developers.google.com/sheets/samples/sheet fields: fields, includeGridData: true, ranges: ranges }); const spreadsheet = response.data; return spreadsheet; }
javascript
{ "resource": "" }
q31073
train
function (options) { if (!(this instanceof Store)) { return new Store(options) } this._opts = options || {} this.db = new Datastore({ filename: this._opts.filename, autoload: true }) }
javascript
{ "resource": "" }
q31074
gain
train
function gain(options) { // gain() if (options == null) options = {volume: 1}; // gain(Function) // gain(Number) else if (typeof options === 'function' || typeof options === 'number') options = {volume: options}; var volume; if (options.mode === 'tan') { volume = Math.tan(options.volume); } else { volume = options.volume; } //in case if volume is fn if (typeof volume === 'function') return buf => util.fill(buf, (v, x, channels) => v * volume(x, channels, v)); return buf => util.fill(buf, v => v * volume); }
javascript
{ "resource": "" }
q31075
train
function(fileId) { var pos = fileId.indexOf('/') return { group: fileId.substring(0, pos), filename: fileId.substring(pos + 1) } }
javascript
{ "resource": "" }
q31076
train
function(){ var clone = element.clone() .removeAttr('vertilize') .css({ height: '', width: element.outerWidth(), position: 'fixed', top: 0, left: 0, visibility: 'hidden' }); element.after(clone); var realHeight = clone.height(); clone['remove'](); return realHeight; }
javascript
{ "resource": "" }
q31077
neighbourhoodSorter
train
function neighbourhoodSorter (a, b) { a = a.join(','); b = b.join(','); return a > b ? 1 : a < b ? -1 : 0; }
javascript
{ "resource": "" }
q31078
getRules
train
function getRules (resource, role, create) { resource = typeof resource === 'undefined' ? null : resource; role = typeof role === 'undefined' ? null : role; create = typeof create === 'undefined' ? false : create; var visitor; // follow $resource do { if (resource === null) { visitor = _rules.allResources; break; } //var resourceId = resource.getResourceId(); var resourceId = resource; if (_rules.byResourceId[resourceId] === undefined) { if (!create) { return null; } _rules.byResourceId[resourceId] = {}; } visitor = _rules.byResourceId[resourceId]; } while (false); // follow $role if (role === null) { if (visitor.allRoles === undefined) { if (!create) { return null; } set(visitor, 'allRoles.byPrivilegeId', {}); } return visitor.allRoles; } //var roleId = role.getRoleId(); var roleId = role; if (visitor.byRoleId === undefined || visitor.byRoleId[roleId] === undefined) { if (!create) { return null; } set(visitor, 'byRoleId.' + roleId + '.byPrivilegeId', {}); } return visitor.byRoleId[roleId]; }
javascript
{ "resource": "" }
q31079
getRuleType
train
function getRuleType(resource, role, privilege) { resource = typeof resource === 'undefined' ? null : resource; role = typeof role === 'undefined' ? null : role; privilege = typeof privilege === 'undefined' ? null : privilege; // get the rules for the $resource and $role var rules = getRules(resource, role), rule; if (rules === null) { return null; } // follow $privilege if (privilege === null) { if (rules.allPrivileges !== undefined) { rule = rules.allPrivileges; } else { return null; } } else if (rules.byPrivilegeId === undefined || rules.byPrivilegeId[privilege] === undefined) { return null; } else { rule = rules.byPrivilegeId[privilege]; } // check assertion first var assertionValue = null; if (rule.assert !== null) { var assertion = rule.assert; assertionValue = assertion.call( self, _isAllowedRole === self.USER_IDENTITY_ROLE && self.getUserIdentity() !== null ? self.getUserIdentity() : role, _isAllowedResource !== null ? _isAllowedResource : resource, privilege ); } if (rule.assert === null || assertionValue === true) { return rule.type; } else if (null !== resource || null !== role || null !== privilege) { return null; } else if (self.TYPE_ALLOW === rule.type) { return self.TYPE_DENY; } return self.TYPE_ALLOW; }
javascript
{ "resource": "" }
q31080
getChildResources
train
function getChildResources(resource){ var result = [], children = _resources[resource].children; children.forEach(function (child) { var childReturn = getChildResources(child); childReturn.push(child); result = result.concat(childReturn); }); return result; }
javascript
{ "resource": "" }
q31081
train
function(evname, callback, context) { this._events = this._events || {}; var a = this._events[evname] = this._events[evname] || []; a.push({ cb: callback, ctxt: context || this }); return this; }
javascript
{ "resource": "" }
q31082
train
function(evname, callback, context) { var self = this, args = arguments; this.on(evname, function() { callback.apply(context, arguments); self.off.apply(self, args); }); return this; }
javascript
{ "resource": "" }
q31083
train
function(evname) { var fns = this._events && this._events[evname] || [], args = __slice.call(arguments, 1); for (var i = 0, ii = fns.length; i < ii; i++) { fns[i].cb.apply(fns[i].ctxt, args); } }
javascript
{ "resource": "" }
q31084
train
function(other, evname, callback) { other.on(evname, callback, this); var a = this._listeningTo = this._listeningTo || {}, b = a[other._cid] = other; }
javascript
{ "resource": "" }
q31085
train
function(other, evname, callback) { if (!this._listeningTo) return; if (!other) { for (var cid in this._listeningTo) { this.stopListening(this._listeningTo[cid], evname, callback); } } else { other.off(evname, callback, this); // TODO: remove local listener tracker } }
javascript
{ "resource": "" }
q31086
Surface
train
function Surface(app, options) { if (!(this instanceof Surface)) { return new Surface(app, options); } this.conf = setting(options); this.middleware(app); context(app, this); }
javascript
{ "resource": "" }
q31087
athost
train
function athost() { var pos = position(); var m = match(/^@host */); if (!m) return; if (!open()) return error("@host missing '{'"); var style = comments().concat(rules()); if (!close()) return error("@host missing '}'"); return pos({ type: 'host', rules: style }); }
javascript
{ "resource": "" }
q31088
atcustommedia
train
function atcustommedia() { var pos = position(); var m = match(/^@custom-media (--[^\s]+) *([^{;]+);/); if (!m) return; return pos({ type: 'custom-media', name: trim(m[1]), media: trim(m[2]) }); }
javascript
{ "resource": "" }
q31089
atfontface
train
function atfontface() { var pos = position(); var m = match(/^@font-face */); if (!m) return; if (!open()) return error("@font-face missing '{'"); var decls = comments(); // declarations var decl; while (decl = declaration()) { decls.push(decl); decls = decls.concat(comments()); } if (!close()) return error("@font-face missing '}'"); return pos({ type: 'font-face', declarations: decls }); }
javascript
{ "resource": "" }
q31090
generateContent
train
function generateContent(globOrGlobArray, options) { // Detect base. const globs = toArray(globOrGlobArray) assert(globs.length > 0, "globs should exist") const base = commonPart(globs) assert(base != null, "the common parent directory of globs is not found.") // Create streams. const globStream = createGlobStream(globs, { base }) const appcacheStream = globStream.pipe(new AppcacheTransform(options)) globStream.on("error", (err) => appcacheStream.emit("error", err)) return appcacheStream }
javascript
{ "resource": "" }
q31091
generate
train
function generate(globs, options, callback) { if (generationQueue.size > 0) { // There is a process not started. return } if (typeof options.delay === "number") { generationQueue.push(next => setTimeout(next, options.delay)) } generationQueue.push(next => { //eslint-disable-next-line require-jsdoc function done(err) { if (err != null) { process.exitCode = 1 console.error(` ERROR: ${err.message}`) } if (options.verbose && err == null) { console.log(" Done.") } next() if (callback != null) { callback(err) } } const appcacheStream = createAppcacheStream(globs, options) if (options.verbose) { console.log(`Generate: ${options.output}`) appcacheStream .on("addpath", (e) => console.log(` Add: ${e.path}`)) .on("addhash", (e) => console.log(` Add fingerprint: ${e.digest}`)) } // Pipe to output. if (options.output) { const dir = path.dirname(path.resolve(options.output)) mkdir(dir, (err) => { if (err != null) { done(err) } else { appcacheStream .pipe(fs.createWriteStream(options.output)) .on("finish", done) .on("error", done) } }) } else { appcacheStream .on("end", done) .pipe(process.stdout) } }) }
javascript
{ "resource": "" }
q31092
watch
train
function watch(globs, options) { options.delay = 1000 chokidar .watch(globs, { persistent: true, ignoreInitial: true }) .on("add", () => generate(globs, options)) .on("unlink", () => generate(globs, options)) .on("change", () => generate(globs, options)) .on("error", (err) => console.error(`ERROR: ${err.message}`)) .on("ready", () => { if (options.verbose) { console.log(`Be watching ${globs.join(", ")}`) } }) // In order to kill by the test harness. process.on("message", () => { process.exit(0) }) }
javascript
{ "resource": "" }
q31093
Server
train
function Server(host, port, options) { var self = this; // Needed to convert this constructor into EventEmitter EventEmitter.call(this); options = options || {}; this.host = host || '127.0.0.1'; this.port = port || 59895; this.debug = options.debug || false; this.json = options.json || true; var parser = new xml2js.Parser(); var responseMessageNumber = 0; // TODO: Build up proper ACKS var applicationAcceptACK = 'MSH|^~\\&|||||20121217154325.194-0700||ACK^RO1|101|T|2.6\nMSA|AA|17'; var applicationErrorACK = 'MSH|^~\\&|NES|NINTENDO|TESTSYSTEM|TESTFACILITY|20121217158325.194-0700||ACK^RO1|101|T|2.6\nMSA|AE|17'; // Bind to TCP socket for HL7 var hl7TcpSocket = net.createServer({ allowHalfOpen: false}, function(socket){ socket.setEncoding("utf8"); function handleError(error){ socket.write(applicationErrorACK); self.emit('error', error); console.log("HL7 TCP Server ERROR: ", error); } function createEL7AckForMessageNumber(messageNumber) { var ack = 'MSH|^~\\&|||||' + generateTimeStamp() + '||ACK^RO1|'+ getUniqueMessageNumber() +'|T|2.6\rMSA|AA|' + messageNumber; return ack; } function zeroFill( number, width ) { width -= number.toString().length; if ( width > 0 ) { return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number; } return number + ""; // always return a string } function generateTimeStamp() { var now = new Date(); var month = zeroFill(now.getUTCMonth() + 1, 2); var date = zeroFill(now.getUTCDate(), 2); var hours = zeroFill(now.getUTCHours(), 2); var minutes = zeroFill(now.getUTCMinutes(), 2); var seconds = zeroFill(now.getUTCSeconds(), 2); var timestamp = now.getUTCFullYear().toString() + month + date + hours + minutes + seconds + '.' + now.getUTCMilliseconds().toString() + '+0000' return timestamp; } function getUniqueMessageNumber() { responseMessageNumber = responseMessageNumber + 1; return responseMessageNumber; } function createXMLAckForMessageNumber(messageNumber) { var ack = String.fromCharCode(0x0b) + '<?xml version="1.0" encoding="UTF-8"?>' + '\n<ACK xmlns="urn:hl7-org:v2xml">'+ '\n<MSH>' + '\n<MSH.1>|</MSH.1>' + '\n<MSH.2>^~\&amp;</MSH.2>' + '\n<MSH.7>' + generateTimeStamp() + '</MSH.7>' + '\n<MSH.9>' + '\n<MSG.1>ACK</MSG.1>' + '\n<MSG.2>R01</MSG.2>' + '\n</MSH.9>' + '\n<MSH.10>' + getUniqueMessageNumber() + '</MSH.10>' + '\n<MSH.11>' + '\n<PT.1>T</PT.1>' + '\n</MSH.11>' + '\n<MSH.12>' + '\n<VID.1>2.6</VID.1>' + '\n</MSH.12>' + '\n</MSH>' + '\n<MSA>' + '\n<MSA.1>AA</MSA.1>' + '\n<MSA.2>' + messageNumber +'</MSA.2>' + '\n</MSA>' + '\n</ACK>\n' + String.fromCharCode(0x1c) + '\r'; console.log("Generated ACK: " + ack); return ack; } function handleXML(xml, sendEL7Ack){ parser.parseString(xml, function(error, result){ if (error) return handleError(error); if (self.debug) { console.log("Message: ", util.inspect(result, false, 7, true)); console.log('Sending ACK'); } self.emit('hl7', result); console.log(result); var messageNumber = 0; for (var key in result) { if (result.hasOwnProperty(key)) { if (result[key].MSH) { var msg = result[key].MSH[0]["MSH.10"][0]; messageNumber = msg; } } } console.log("Sending ACK for messageNumber "+messageNumber); if (sendEL7Ack) { var ack = createEL7AckForMessageNumber(messageNumber); socket.write(ack); } else { var ack = createXMLAckForMessageNumber(messageNumber); socket.write(new Buffer(ack, encoding = "utf8")); } socket.end(); }); } socket.on('connect', function() { if (self.debug) { var now = new Date(); console.log(now + " - HL7 TCP Client Connected"); } }); socket.on('data', function(packet) { if (self.debug) { console.log(packet); } if (!packet) return handleError(new Error('Packet is empty')); // It is XML format if (packet.indexOf('<?xml') !== -1) { handleXML(packet.trim(), false); } // It is EL7 format else { hl7.toXml(packet, function(error, xml){ if (error) return handleError(error); handleXML(xml, true); }); } }); socket.on('error', function(error){ handleError(error); }); socket.on('close', function(){ if (self.debug) { var now = new Date(); console.log(now + " - HL7 TCP Server Disconnected"); } }); socket.on('end', function() { if (self.debug) { var now = new Date(); console.log(now + " - HL7 TCP Client Disconnected"); } }); }); hl7TcpSocket.listen( this.port, function(){ var address = hl7TcpSocket.address(); console.log("HL7 TCP Server listening on: " + address.address + ":" + address.port); }); }
javascript
{ "resource": "" }
q31094
_send
train
function _send(cmd, callback) { cmd_callback = callback; if(connected) { client.write(cmd + '\n'); } else { connect(); } }
javascript
{ "resource": "" }
q31095
globParentToArray
train
function globParentToArray(glob) { return path.resolve(globParent(glob)) .replace(BACK_SLASH, "/") .split("/") .filter(Boolean) }
javascript
{ "resource": "" }
q31096
findLastCommonIndex
train
function findLastCommonIndex(xs, ys) { for (let i = Math.min(xs.length, ys.length) - 1; i >= 0; --i) { if (xs[i] === ys[i]) { return i } } return -1 }
javascript
{ "resource": "" }
q31097
train
function(val) { return val === null ? 'Null' : val === undefined ? 'Undefined' : Object.prototype.toString.call(val).slice(8, -1); }
javascript
{ "resource": "" }
q31098
train
function(expectedType, value) { var actualType = getType(value); if (expectedType!== actualType) { throw new TypeError('Expected type to be ' + expectedType + ', but got ' + actualType); } return value; }
javascript
{ "resource": "" }
q31099
leftPad
train
function leftPad(n, prefix) { var s = n.toString(), nchars = intChars(n), nspaces = nchars - s.length - 1; prefix || (prefix = ' '); for (var i = 0; i < nspaces; i++) { prefix += ' '; } return prefix + s; }
javascript
{ "resource": "" }