_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q47000
|
theme
|
train
|
function theme (env) {
let promise = env.theme(env.dest, env)
if (!is.promise(promise)) {
let type = Object.prototype.toString.call(promise)
throw new errors.Error(`Theme didn't return a promise, got ${type}.`)
}
return promise
.then(() => {
let displayTheme = env.displayTheme || 'anonymous'
env.logger.log(`Theme \`${displayTheme}\` successfully rendered.`)
})
}
|
javascript
|
{
"resource": ""
}
|
q47001
|
documentize
|
train
|
async function documentize (env) {
init(env)
let data = await baseDocumentize(env)
try {
await refresh(env)
await theme(env)
okay(env)
} catch (err) {
env.emit('error', err)
throw err
}
return data
}
|
javascript
|
{
"resource": ""
}
|
q47002
|
stream
|
train
|
function stream (env) {
let filter = parseFilter(env)
filter.promise
.then(data => {
env.logger.log('Sass sources successfully parsed.')
env.data = data
onEmpty(data, env)
})
/**
* Returned Promise await the full sequence,
* instead of just the parsing step.
*/
filter.promise = new Promise((resolve, reject) => {
async function documentize () {
try {
init(env)
await refresh(env)
await theme(env)
okay(env)
resolve()
} catch (err) {
reject(err)
env.emit('error', err)
throw err
}
}
filter
.on('end', documentize)
.on('error', err => env.emit('error', err))
.resume() // Drain.
})
return filter
}
|
javascript
|
{
"resource": ""
}
|
q47003
|
stream
|
train
|
function stream (env) {
let parseStream = parseFilter(env)
let filter = through.obj((file, enc, cb) => cb(), function (cb) {
parseStream.promise.then(data => {
this.push(data)
cb()
}, cb)
})
return pipe(parseStream, filter)
}
|
javascript
|
{
"resource": ""
}
|
q47004
|
baseDocumentize
|
train
|
async function baseDocumentize (env) {
let filter = parseFilter(env)
filter.promise
.then(data => {
env.logger.log(`Folder \`${env.src}\` successfully parsed.`)
env.data = data
onEmpty(data, env)
env.logger.debug(() => {
fs.writeFile(
'sassdoc-data.json',
JSON.stringify(data, null, 2) + '\n',
err => {
if (err) throw err
}
)
return 'Dumping data to `sassdoc-data.json`.'
})
})
let streams = [
vfs.src(env.src),
recurse(),
exclude(env.exclude || []),
converter({ from: 'sass', to: 'scss' }),
filter
]
let pipeline = () => {
return new Promise((resolve, reject) => {
pipe(...streams, err =>
err ? reject(err) : resolve())
.resume() // Drain.
})
}
try {
await pipeline()
await filter.promise
} catch (err) {
env.emit('error', err)
throw err
}
return env.data
}
|
javascript
|
{
"resource": ""
}
|
q47005
|
onEmpty
|
train
|
function onEmpty (data, env) {
let message = `SassDoc could not find anything to document.\n
* Are you still using \`/**\` comments ? They're no more supported since 2.0.
See <http://sassdoc.com/upgrading/#c-style-comments>.\n`
if (!data.length && env.verbose) {
env.emit('warning', new errors.Warning(message))
}
}
|
javascript
|
{
"resource": ""
}
|
q47006
|
ensure
|
train
|
function ensure (env, options, names) {
for (let k of Object.keys(names)) {
let v = names[k]
if (options[v]) {
env[k] = options[v]
env[k + 'Cwd'] = true
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47007
|
handleOpenURL
|
train
|
function handleOpenURL (event) {
console.tron.log(event.url)
let splitUrl = event.url.split('/') // ['https:', '', 'domain', 'route', 'params']
let importantParameters = splitUrl.splice(3) // ['route', 'params']
if (importantParameters.length === 0) {
console.tron.log('Sending to home page')
return null
}
if (importantParameters.length === 1) {
switch (importantParameters[0]) {
case 'register':
console.tron.log(`Sending to Register Page`)
registerScreen()
break
default:
console.tron.warn(`Unhandled deep link: ${event.url}`)
// default code block
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47008
|
mergePackageJsons
|
train
|
async function mergePackageJsons () {
// transform our package.json incase we need to replace variables
const rawJson = await template.generate({
directory: `${ignite.ignitePluginPath()}/boilerplate`,
template: 'package.json.ejs',
props: props
})
const newPackageJson = JSON.parse(rawJson)
// read in the react-native created package.json
const currentPackage = filesystem.read('package.json', 'json')
// deep merge, lol
const newPackage = pipe(
assoc(
'dependencies',
merge(currentPackage.dependencies, newPackageJson.dependencies)
),
assoc(
'devDependencies',
merge(currentPackage.devDependencies, newPackageJson.devDependencies)
),
assoc('scripts', merge(currentPackage.scripts, newPackageJson.scripts)),
merge(
__,
omit(['dependencies', 'devDependencies', 'scripts'], newPackageJson)
)
)(currentPackage)
// write this out
filesystem.write('package.json', newPackage, { jsonIndent: 2 })
}
|
javascript
|
{
"resource": ""
}
|
q47009
|
subscribeToChat
|
train
|
function subscribeToChat () {
console.tron.log('Subscribing to Chat')
if (!subscriptions.hasOwnProperty('chat')) {
subscriptions.chat = { subscribed: true }
connection.then(() => {
chatSubscriber = stompClient.subscribe('/topic/chat', onMessage.bind(this, 'chat'))
})
}
}
|
javascript
|
{
"resource": ""
}
|
q47010
|
sendChat
|
train
|
function sendChat (ev) {
if (stompClient !== null && stompClient.connected) {
var p = '/topic/chat'
stompClient.send(p, {}, JSON.stringify(ev))
}
}
|
javascript
|
{
"resource": ""
}
|
q47011
|
onMessage
|
train
|
function onMessage (subscription, fullMessage) {
let msg = null
try {
msg = JSON.parse(fullMessage.body)
} catch (fullMessage) {
console.tron.error(`Error parsing : ${fullMessage}`)
}
if (msg) {
return em({ subscription, msg })
}
}
|
javascript
|
{
"resource": ""
}
|
q47012
|
generateInterval
|
train
|
function generateInterval (k) {
let maxInterval = (Math.pow(2, k) - 1) * 1000
if (maxInterval > 30 * 1000) {
// If the generated interval is more than 30 seconds, truncate it down to 30 seconds.
maxInterval = 30 * 1000
}
// generate the interval to a random number between 0 and the maxInterval determined from above
return Math.random() * maxInterval
}
|
javascript
|
{
"resource": ""
}
|
q47013
|
train
|
function (data) {
return this.fields.reduce(function (output, field) {
var replacement = ''
var placeholder = field.placeholder
var width = field.width
if (field.prefix) {
output += field.prefix
}
if (placeholder) {
replacement = data[placeholder] || ''
if (width && (placeholder === 'hash' || placeholder === 'chunkhash')) {
replacement = replacement.slice(0, width)
}
output += replacement
}
return output
}, '')
}
|
javascript
|
{
"resource": ""
}
|
|
q47014
|
Rules
|
train
|
function Rules (options) {
this.options = options;
this._keep = [];
this._remove = [];
this.blankRule = {
replacement: options.blankReplacement
};
this.keepReplacement = options.keepReplacement;
this.defaultRule = {
replacement: options.defaultReplacement
};
this.array = [];
for (var key in options.rules) this.array.push(options.rules[key]);
}
|
javascript
|
{
"resource": ""
}
|
q47015
|
train
|
function (input) {
if (!canConvert(input)) {
throw new TypeError(
input + ' is not a string, or an element/document/fragment node.'
)
}
if (input === '') return ''
var output = process.call(this, new RootNode(input));
return postProcess.call(this, output)
}
|
javascript
|
{
"resource": ""
}
|
|
q47016
|
train
|
function (plugin) {
if (Array.isArray(plugin)) {
for (var i = 0; i < plugin.length; i++) this.use(plugin[i]);
} else if (typeof plugin === 'function') {
plugin(this);
} else {
throw new TypeError('plugin must be a Function or an Array of Functions')
}
return this
}
|
javascript
|
{
"resource": ""
}
|
|
q47017
|
train
|
function (string) {
return (
string
// Escape backslash escapes!
.replace(/\\(\S)/g, '\\\\$1')
// Escape headings
.replace(/^(#{1,6} )/gm, '\\$1')
// Escape hr
.replace(/^([-*_] *){3,}$/gm, function (match, character) {
return match.split(character).join('\\' + character)
})
// Escape ol bullet points
.replace(/^(\W* {0,3})(\d+)\. /gm, '$1$2\\. ')
// Escape ul bullet points
.replace(/^([^\\\w]*)[*+-] /gm, function (match) {
return match.replace(/([*+-])/g, '\\$1')
})
// Escape blockquote indents
.replace(/^(\W* {0,3})> /gm, '$1\\> ')
// Escape em/strong *
.replace(/\*+(?![*\s\W]).+?\*+/g, function (match) {
return match.replace(/\*/g, '\\*')
})
// Escape em/strong _
.replace(/_+(?![_\s\W]).+?_+/g, function (match) {
return match.replace(/_/g, '\\_')
})
// Escape code _
.replace(/`+(?![`\s\W]).+?`+/g, function (match) {
return match.replace(/`/g, '\\`')
})
// Escape link brackets
.replace(/[\[\]]/g, '\\{{{toMarkdown}}}') // eslint-disable-line no-useless-escape
)
}
|
javascript
|
{
"resource": ""
}
|
|
q47018
|
process
|
train
|
function process (parentNode) {
var self = this;
return reduce.call(parentNode.childNodes, function (output, node) {
node = new Node(node);
var replacement = '';
if (node.nodeType === 3) {
replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue);
} else if (node.nodeType === 1) {
replacement = replacementForNode.call(self, node);
}
return join(output, replacement)
}, '')
}
|
javascript
|
{
"resource": ""
}
|
q47019
|
postProcess
|
train
|
function postProcess (output) {
var self = this;
this.rules.forEach(function (rule) {
if (typeof rule.append === 'function') {
output = join(output, rule.append(self.options));
}
});
return output.replace(/^[\t\r\n]+/, '').replace(/[\t\r\n\s]+$/, '')
}
|
javascript
|
{
"resource": ""
}
|
q47020
|
train
|
function (matchedValue, expectedValue, currencySymbol, isFraction) {
// get value with fraction
expectedValue = getNumberWithCommas(expectedValue);
if (isFraction === true && expectedValue.indexOf('.') === -1) {
expectedValue += '.00';
}
// add minus and symbol if needed
var expression = '^';
if (matchedValue.indexOf('-') !== -1) {
expression += '-';
}
expression += '\\s*';
if (typeof currencySymbol === 'string') {
expression += '\\' + currencySymbol + '\\s*';
}
return new RegExp(expression + expectedValue + '$');
}
|
javascript
|
{
"resource": ""
}
|
|
q47021
|
round
|
train
|
function round(num, places) {
const n = Math.pow(10, places);
return Math.round(num * n) / n;
}
|
javascript
|
{
"resource": ""
}
|
q47022
|
train
|
function(patternDef, latLngs) {
return {
symbolFactory: patternDef.symbol,
// Parse offset and repeat values, managing the two cases:
// absolute (in pixels) or relative (in percentage of the polyline length)
offset: parseRelativeOrAbsoluteValue(patternDef.offset),
endOffset: parseRelativeOrAbsoluteValue(patternDef.endOffset),
repeat: parseRelativeOrAbsoluteValue(patternDef.repeat),
};
}
|
javascript
|
{
"resource": ""
}
|
|
q47023
|
train
|
function() {
const allPathCoords = this._paths.reduce((acc, path) => acc.concat(path), []);
return L.latLngBounds(allPathCoords);
}
|
javascript
|
{
"resource": ""
}
|
|
q47024
|
train
|
function(latLngs, symbolFactory, directionPoints) {
return directionPoints.map((directionPoint, i) =>
symbolFactory.buildSymbol(directionPoint, latLngs, this._map, i, directionPoints.length)
);
}
|
javascript
|
{
"resource": ""
}
|
|
q47025
|
train
|
function(latLngs, pattern) {
if (latLngs.length < 2) {
return [];
}
const pathAsPoints = latLngs.map(latLng => this._map.project(latLng));
return projectPatternOnPointPath(pathAsPoints, pattern)
.map(point => ({
latLng: this._map.unproject(L.point(point.pt)),
heading: point.heading,
}));
}
|
javascript
|
{
"resource": ""
}
|
|
q47026
|
train
|
function(pattern) {
const mapBounds = this._map.getBounds().pad(0.1);
return this._paths.map(path => {
const directionPoints = this._getDirectionPoints(path, pattern)
// filter out invisible points
.filter(point => mapBounds.contains(point.latLng));
return L.featureGroup(this._buildSymbols(path, pattern.symbolFactory, directionPoints));
});
}
|
javascript
|
{
"resource": ""
}
|
|
q47027
|
train
|
function () {
this._patterns
.map(pattern => this._getPatternLayers(pattern))
.forEach(layers => { this.addLayer(L.featureGroup(layers)); });
}
|
javascript
|
{
"resource": ""
}
|
|
q47028
|
getConnection
|
train
|
async function getConnection(){
// already connected ?
if (_nodeMcuConnector.isConnected()){
return;
}
// create new connector
try{
const msg = await _nodeMcuConnector.connect(_options.device, _options.baudrate, true, _options.connectionDelay);
// status message
_logger.log('Connected');
_mculogger.log(msg);
}catch(e){
_logger.error('Unable to establish connection');
throw e;
}
}
|
javascript
|
{
"resource": ""
}
|
q47029
|
fsinfo
|
train
|
async function fsinfo(format){
// try to establish a connection to the module
await getConnection();
const {metadata, files} = await _nodeMcuConnector.fsinfo();
// json output - third party applications
if (format == 'json') {
writeOutput(JSON.stringify({
files: files,
meta: metadata
}));
// raw format - suitable for use in bash scripts
}else if (format == 'raw'){
// print fileinfo
files.forEach(function(file){
writeOutput(file.name);
});
}else{
_mculogger.log('Free Disk Space: ' + metadata.remaining + ' KB | Total: ' + metadata.total + ' KB | ' + files.length + ' Files');
// files found ?
if (files.length==0){
_mculogger.log('No Files found - have you created the file-system?');
}else{
_mculogger.log('Files stored into Flash (SPIFFS)');
// print fileinfo
files.forEach(function(file){
_mculogger.log(' - ' + file.name + ' (' + file.size + ' Bytes)');
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47030
|
upload
|
train
|
async function upload(localFiles, options, onProgess){
// the index of the current uploaded file
let fileUploadIndex = 0;
async function uploadFile(localFile, remoteFilename){
// increment upload index
fileUploadIndex++;
// get file stats
try{
const stats = await _fs.statx(localFile);
// check if file is directory
if (stats.isDirectory()) {
_mculogger.error('Path "' + localFile + '" is a directory.');
return;
}
// local file available
}catch (err){
_logger.error('Local file not found "' + localFile + '" skipping...');
_logger.debug(err);
return;
}
// display filename
_logger.log('Uploading "' + localFile + '" >> "' + remoteFilename + '"...');
// normalize the remote filename (strip relative parts)
remoteFilename = remoteFilename.replace(/\.\.\//g, '').replace(/\.\./g, '').replace(/^\.\//, '');
// delete old file (may existent)
await _nodeMcuConnector.remove(remoteFilename);
// start file transfer
await _nodeMcuConnector.upload(localFile, remoteFilename, options, function(current, total){
// proxy and append file-number
onProgess(current, total, fileUploadIndex);
});
// compile flag set ? and is a lua file ?
if (options.compile && _path.extname(localFile).toLowerCase() == '.lua'){
_mculogger.log(' |- compiling lua file..');
await _nodeMcuConnector.compile(remoteFilename);
_mculogger.log(' |- success');
// drop original lua file
await _nodeMcuConnector.remove(remoteFilename);
_mculogger.log(' |- original Lua file removed');
}
}
// try to establish a connection to the module
await getConnection();
// single file upload ?
if (localFiles.length == 1){
// extract first element
const localFile = localFiles[0];
// filename defaults to original filename minus path.
// this behaviour can be overridden by --keeppath and --remotename options
const remoteFile = options.remotename ? options.remotename : (options.keeppath ? localFile : _path.basename(localFile));
// start single file upload
await uploadFile(localFile, remoteFile);
// log message
_logger.log('File Transfer complete!');
// run file ?
if (options.run === true){
await run(remoteFile);
}
// bulk upload ?
}else{
// file available ?
while (localFiles.length > 0){
// extract file
const localFile = localFiles.shift();
// keep-path option set ?
const remoteFile = (options.keeppath ? localFile : _path.basename(localFile));
// trigger upload
await uploadFile(localFile, remoteFile);
}
// log message
_logger.log('Bulk File Transfer complete!');
}
}
|
javascript
|
{
"resource": ""
}
|
q47031
|
download
|
train
|
async function download(remoteFile){
// strip path
let localFilename = _path.basename(remoteFile);
// local file with same name already available ?
if (await _fs.exists(remoteFile)){
// change filename
localFilename += '.' + (new Date().getTime());
_logger.log('Local file "' + remoteFile + '" already exist - new file renamed to "' + localFilename + '"');
}
// try to establish a connection to the module
await getConnection();
_logger.log('Downloading "' + remoteFile + '" ...');
let data = null;
// download the file
try{
data = await _nodeMcuConnector.download(remoteFile);
_logger.log('Data Transfer complete!');
}catch(e){
_logger.debug(e);
throw new Error('Data Transfer FAILED!');
}
// store the file
try{
await _fs.writeFile(localFilename, data);
_logger.log('File "' + localFilename + '" created');
}catch(e){
_logger.debug(e);
throw new Error('i/o error - cannot save file');
}
}
|
javascript
|
{
"resource": ""
}
|
q47032
|
remove
|
train
|
async function remove(filename){
// try to establish a connection to the module
await getConnection();
// remove the file
await _nodeMcuConnector.remove(filename);
// just show complete message (no feedback from nodemcu)
_mculogger.log('File "' + filename + '" removed!');
}
|
javascript
|
{
"resource": ""
}
|
q47033
|
mkfs
|
train
|
async function mkfs(){
// try to establish a connection to the module
await getConnection();
_mculogger.log('Formatting the file system...this will take around ~30s');
try{
const response = await _nodeMcuConnector.format();
// just show complete message
_mculogger.log('File System created | ' + response);
}catch(e){
_mculogger.error('Formatting failed');
_logger.debug(e);
}
}
|
javascript
|
{
"resource": ""
}
|
q47034
|
devices
|
train
|
async function devices(showAll, jsonOutput){
try{
const serialDevices = await _nodeMcuConnector.listDevices(showAll);
if (jsonOutput){
writeOutput(JSON.stringify(serialDevices));
}else{
// just show complete message
if (serialDevices.length == 0){
_mculogger.error('No Connected Devices found | Total: ' + serialDevices.length);
}else{
_mculogger.log('Connected Devices | Total: ' + serialDevices.length);
// print fileinfo
serialDevices.forEach(function(device){
_mculogger.log('- ' + device.comName + ' (' + device.manufacturer + ', ' + device.pnpId + ')');
});
}
}
}catch(e){
_mculogger.alert('Cannot retrieve serial device list - ');
_logger.debug(e);
}
}
|
javascript
|
{
"resource": ""
}
|
q47035
|
train
|
function(opt){
// merge with default options
Object.keys(_options).forEach(function(key){
_options[key] = opt[key] || _options[key];
});
}
|
javascript
|
{
"resource": ""
}
|
|
q47036
|
luaPrepare
|
train
|
function luaPrepare(commandName, args){
// get command by name
let command = _esp8266_commands[commandName] || null;
// valid command name provided ?
if (command == null){
return null;
}
// replace all placeholders with given args
args.forEach(function(arg){
// simple escaping quotes
arg = arg.replace(/[^\\]"/g, '"');
// apply arg
command = command.replace(/\?/, arg);
});
return command;
}
|
javascript
|
{
"resource": ""
}
|
q47037
|
prompt
|
train
|
function prompt(menu){
return new Promise(function(resolve, reject){
// user confirmation required!
_prompt.start();
_prompt.message = '';
_prompt.delimiter = '';
_prompt.colors = false;
_prompt.get(menu, function (err, result){
if (err){
reject(err);
}else{
resolve(result);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q47038
|
fetchDeviceInfo
|
train
|
async function fetchDeviceInfo(){
// run the node.info() command
let {response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.nodeInfo);
// replace whitespaces with single delimiter
const p = response.replace(/\s+/gi, '-').split('-');
// 8 elements found ? nodemcu on esp8266
if (p.length === 8){
return {
version: p[0] + '.' + p[1] + '.' + p[2],
arch: 'esp8266',
chipID: parseInt(p[3]).toString(16),
flashID: parseInt(p[4]).toString(16),
flashsize: p[5] + 'kB',
flashmode: p[6],
flashspeed: parseInt(p[7]) / 1000000 + 'MHz'
};
// maybe an esp32 module with missing node.info()
}else{
try{
({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.chipid));
// esp32 chipid (hex with '0x' prefix)?
const chipid = response.match(/^0x(\w+)/);
if (chipid){
return {
version: 'unknown',
arch: 'esp32',
chipID: chipid[1],
flashID: 'unknown',
flashsize: 'unknown',
flashmode:'unknown',
flashspeed: 'unknown'
};
}else{
throw new Error('Invalid node.chipid() Response: ' + response);
}
}catch(e){
_logger.debug(e);
throw new Error('Invalid node.chipid() Response: ' + response);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47039
|
fsinfo
|
train
|
async function fsinfo(){
// get file system info (size)
let {response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.fsInfo);
// extract size (remaining, used, total)
response = response.replace(/\s+/gi, '-').split('-');
const meta = {
remaining: toKB(response[0]),
used: toKB(response[1]),
total: toKB(response[2])
};
// print a full file-list including size
({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.listFiles));
// file-list to return
const files = [];
// files available (list not empty) ?
if (response.length > 0){
// split the file-list by ";"
const entries = response.trim().split(';');
// process each entry
entries.forEach(function(entry){
// entry format: <name>:<size>
const matches = /^(.*):(\d+)$/gi.exec(entry);
// valid format ?
if (matches){
// append file entry to list
files.push({
name: matches[1],
size: parseInt(matches[2])
});
}
});
}
return {metadata: meta, files: files}
}
|
javascript
|
{
"resource": ""
}
|
q47040
|
format
|
train
|
async function format(){
// create new filesystem
const {response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.fsFormat);
return response;
}
|
javascript
|
{
"resource": ""
}
|
q47041
|
compile
|
train
|
async function compile(remoteName){
// run the lua compiler/interpreter to cache the file as bytecode
const {response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.prepare('compile', [remoteName]));
return response;
}
|
javascript
|
{
"resource": ""
}
|
q47042
|
onData
|
train
|
function onData(rawData){
// strip delimiter sequence from array
const input = rawData.toString(_encoding);
// response data object - default no response data
const data = {
echo: input,
response: null
};
// response found ? split echo and response
const splitIndex = input.indexOf('\n');
if (splitIndex > 0){
data.echo = input.substr(0, splitIndex).trim();
data.response = input.substr(splitIndex + 1).trim();
}
// process waiting for input ?
if (_waitingForInput !== null){
const resolver = _waitingForInput;
_waitingForInput = null;
resolver(data);
}else{
_inputbuffer.push(data);
}
}
|
javascript
|
{
"resource": ""
}
|
q47043
|
getNextResponse
|
train
|
function getNextResponse(){
if (_waitingForInput !== null){
throw new Error('concurreny error - receive listener already in-queue');
}
return new Promise(function(resolve){
// data received ?
if (_inputbuffer.length > 0){
resolve(_inputbuffer.shift());
}else{
// add as waiting instance (no concurrent!)
_waitingForInput = resolve;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q47044
|
write
|
train
|
async function write(data){
await _serialport.write(data);
await _serialport.drain();
}
|
javascript
|
{
"resource": ""
}
|
q47045
|
startTransfer
|
train
|
async function startTransfer(rawContent, localName, remoteName, progressCb){
// convert buffer to hex or base64
const content = rawContent.toString(_transferEncoding);
// get absolute filesize
const absoluteFilesize = content.length;
// split file content into chunks
const chunks = content.match(/[\s\S]{1,232}/g) || [];
// command response buffer
let response = null;
// current upload size in bytes
let currentUploadSize = 0;
// open remote file for write
try{
({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.prepare('fileOpen', [remoteName, 'w+'])));
// valid handle ?
if (response == 'nil'){
throw new Error('i/o error - cannot open nodemcu file-handle for write');
}
}catch(e){
_logger.debug(e);
throw new Error('Cannot open remote file "' + remoteName + '" for write');
}
// initial progress update
progressCb.apply(progressCb, [0, absoluteFilesize]);
// internal helper to write chunks
async function writeChunk(){
if (chunks.length > 0){
// get first element
const l = chunks.shift();
// increment size counter
currentUploadSize += l.length;
// write first element to file
try{
await _virtualTerminal.executeCommand('__nmtwrite("' + l + '")');
}catch(e){
_logger.debug(e);
throw new Error('cannot write chunk to remote file');
}
// run progress callback
progressCb.apply(progressCb, [currentUploadSize, absoluteFilesize]);
// write next
await writeChunk();
}else{
// ensure that the progress callback is called, even for empty files
progressCb.apply(progressCb, [currentUploadSize, absoluteFilesize]);
// send file close command
try{
await _virtualTerminal.executeCommand(_luaCommandBuilder.command.fileCloseFlush);
}catch(e){
_logger.debug(e);
throw new Error('cannot flush/close remote file');
}
}
}
// start transfer
return writeChunk();
}
|
javascript
|
{
"resource": ""
}
|
q47046
|
writeChunk
|
train
|
async function writeChunk(){
if (chunks.length > 0){
// get first element
const l = chunks.shift();
// increment size counter
currentUploadSize += l.length;
// write first element to file
try{
await _virtualTerminal.executeCommand('__nmtwrite("' + l + '")');
}catch(e){
_logger.debug(e);
throw new Error('cannot write chunk to remote file');
}
// run progress callback
progressCb.apply(progressCb, [currentUploadSize, absoluteFilesize]);
// write next
await writeChunk();
}else{
// ensure that the progress callback is called, even for empty files
progressCb.apply(progressCb, [currentUploadSize, absoluteFilesize]);
// send file close command
try{
await _virtualTerminal.executeCommand(_luaCommandBuilder.command.fileCloseFlush);
}catch(e){
_logger.debug(e);
throw new Error('cannot flush/close remote file');
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47047
|
requireTransferHelper
|
train
|
async function requireTransferHelper(){
// hex write helper already uploaded within current session ?
// otherwise upload helper
if (_isTransferWriteHelperUploaded !== true){
let response = null;
try{
({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.transferWriteHelper));
}catch(e){
_logger.debug(e);
throw new Error('cannot upload transfer helper function');
}
// get transfer encoding
if (response == 'b'){
_transferEncoding = 'base64'
}else if (response == 'h'){
_transferEncoding = 'hex'
}else{
throw new Error('unknown transfer encoding - ' + response);
}
// show encoding
_logger.log('Transfer-Mode: ' + _transferEncoding);
// set flag
_isTransferWriteHelperUploaded = true;
}
}
|
javascript
|
{
"resource": ""
}
|
q47048
|
passthrough
|
train
|
function passthrough(devicename, baudrate, initialCommand=null){
return new Promise(function(resolve, reject){
// try to open the serial port
const _device = new _serialport(devicename, {
baudRate: parseInt(baudrate),
autoOpen: false
});
// new length parser
const parser = _device.pipe(new _lengthParser({length: 1}));
// handle low-level errors
_device.on('error', reject);
// listen on incomming data
parser.on('data', function(input){
// passthrough
process.stdout.write(input.toString('utf8'));
});
// open connection
_device.open(function(err){
if (err){
reject(err);
}else{
// prepare
if (process.stdin.isTTY){
process.stdin.setRawMode(true);
}
process.stdin.setEncoding('utf8');
// initial command set ?
if (initialCommand !== null){
_device.write(initialCommand + '\n');
}
// pass-through
process.stdin.on('data', function(data){
// ctrl-c ?
if (data == '\u0003'){
_device.close(function(e){
if (e){
reject(e);
}else{
resolve();
}
});
}else{
// passthrough stdin->serial
_device.write(data);
}
});
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q47049
|
asyncWrapper
|
train
|
function asyncWrapper(promise){
return function(...args){
// extract options (last argument)
_optionsManager.parse(args.pop())
// trigger command
.then(options => {
// re-merge
return promise(...args, options)
})
// trigger disconnect
.then(() => {
if (_nodemcutool.Connector.isConnected()){
_logger.log('disconnecting');
return _nodemcutool.disconnect();
}
})
// gracefull exit
.then(() => {
process.exit(0)
})
// handle low-level errors
.catch(err => {
_logger.error(err.message);
_logger.debug(err.stack);
process.exit(1);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q47050
|
checkConnection
|
train
|
function checkConnection(){
return new Promise(function(resolve, reject){
// 1.5s connection timeout
const watchdog = setTimeout(function(){
// throw error
reject(new Error('Timeout, no response detected - is NodeMCU online and the Lua interpreter ready ?'));
}, 1500);
// send a simple print command to the lua engine
_virtualTerminal.executeCommand(_luaCommandBuilder.command.echo)
.then(({echo, response}) => {
// clear watchdog
clearTimeout(watchdog);
// validate command echo and command output
if (response == 'echo1337' && echo == 'print("echo1337")') {
resolve();
} else {
_logger.log('Echo:', echo);
_logger.debug('Response:', response);
reject(new Error('No response detected - is NodeMCU online and the Lua interpreter ready ?'));
}
})
.catch(reject)
});
}
|
javascript
|
{
"resource": ""
}
|
q47051
|
download
|
train
|
async function download(remoteName){
let response = null;
let data = null;
// transfer helper function to encode hex data
try{
({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.transferReadHelper));
}catch(e){
_logger.debug(e);
throw new Error('Cannot transfer hex.encode helper function');
}
// open remote file for read
try{
({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.prepare('fileOpen', [remoteName, 'r'])));
}catch(e){
_logger.debug(e);
throw new Error('Cannot open remote file "' + remoteName + '" for read');
}
// read content
try{
({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.fileRead));
// encoding
const tEncoding = response.match(/^[0-9A-F]+$/gi) ? 'hex' : 'base64';
_logger.log('Transfer-Encoding: ' + tEncoding);
// decode file content + detect encoding
data = new Buffer(response, tEncoding);
}catch(e){
_logger.debug(e);
throw new Error('Cannot read remote file content');
}
// close remote file for read
try{
({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.fileClose));
}catch(e){
_logger.debug(e);
throw new Error('Cannot close remote file "' + remoteName + '"');
}
return data;
}
|
javascript
|
{
"resource": ""
}
|
q47052
|
listDevices
|
train
|
async function listDevices(showAll){
// get all available serial ports
const ports = (await _serialport.list()) || [];
// just pass-through
if (showAll){
return ports;
// filter by vendorIDs
}else{
return ports.filter(function(item){
//
return knownVendorIDs.includes(item.vendorId && item.vendorId.toUpperCase());
});
}
}
|
javascript
|
{
"resource": ""
}
|
q47053
|
mergeOptions
|
train
|
function mergeOptions(...opt){
// extract default (last argument)
const result = opt.pop();
// try to find first match
while (opt.length > 0){
// extract first argument (priority)
const o = opt.shift();
// value set ?
if (typeof o !== 'undefined' && o !== null){
return o;
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q47054
|
storeOptions
|
train
|
async function storeOptions(options){
await _fs.writeFile(_configFilename, JSON.stringify(options, null, 4));
}
|
javascript
|
{
"resource": ""
}
|
q47055
|
startWatch
|
train
|
function startWatch() {
if (watcher) return
watcher = setInterval(function() {
if (self.root[self.origin.offset]) {
stopWatch()
self.update()
}
}, 300) // is it good enought for you?)
}
|
javascript
|
{
"resource": ""
}
|
q47056
|
baron
|
train
|
function baron(user) {
var withParams = !!user
var tryNode = (user && user[0]) || user
var isNode = typeof user == 'string' || tryNode instanceof HTMLElement
var params = isNode ? { root: user } : clone(user)
var jQueryMode
var rootNode
var defaultParams = {
direction: 'v',
barOnCls: '_scrollbar',
resizeDebounce: 0,
event: event,
cssGuru: false,
impact: 'scroller',
position: 'static'
}
params = params || {}
// Extending default params by user-defined params
for (var key in defaultParams) {
if (params[key] == null) { // eslint-disable-line
params[key] = defaultParams[key]
}
}
if (process.env.NODE_ENV !== 'production') {
if (params.position == 'absolute' && params.impact == 'clipper') {
log('error', [
'Simultaneous use of `absolute` position and `clipper` impact values detected.',
'Those values cannot be used together.',
'See more https://github.com/Diokuz/baron/issues/138'
].join(' '), params)
}
}
// `this` could be a jQuery instance
jQueryMode = this && this instanceof scopedWindow.jQuery
if (params._chain) {
rootNode = params.root
} else if (jQueryMode) {
params.root = rootNode = this[0]
} else {
rootNode = qs(params.root || params.scroller)
}
if (process.env.NODE_ENV !== 'production') {
if (!rootNode) {
log('error', [
'Baron initialization failed: root node not found.'
].join(', '), params)
return // or return baron-shell?
}
}
var attr = manageAttr(rootNode, params.direction)
var id = +attr // Could be NaN
params.index = id
// baron() can return existing instances,
// @TODO update params on-the-fly
// https://github.com/Diokuz/baron/issues/124
if (id == id && attr !== null && instances[id]) {
if (process.env.NODE_ENV !== 'production') {
if (withParams) {
log('error', [
'repeated initialization for html-node detected',
'https://github.com/Diokuz/baron/blob/master/docs/logs/repeated.md'
].join(', '), params.root)
}
}
return instances[id]
}
// root and scroller can be different nodes
if (params.root && params.scroller) {
params.scroller = qs(params.scroller, rootNode)
if (process.env.NODE_ENV !== 'production') {
if (!params.scroller) {
log('error', 'Scroller not found!', rootNode, params.scroller)
}
}
} else {
params.scroller = rootNode
}
params.root = rootNode
var instance = init(params)
if (instance.autoUpdate) {
instance.autoUpdate()
}
return instance
}
|
javascript
|
{
"resource": ""
}
|
q47057
|
manageAttr
|
train
|
function manageAttr(node, direction, mode, id) {
var attrName = 'data-baron-' + direction + '-id'
if (mode == 'on') {
node.setAttribute(attrName, id)
} else if (mode == 'off') {
node.removeAttribute(attrName)
}
return node.getAttribute(attrName)
}
|
javascript
|
{
"resource": ""
}
|
q47058
|
train
|
function(func, wait) {
var self = this,
timeout,
// args, // right now there is no need for arguments
// context, // and for context
timestamp
// result // and for result
var later = function() {
if (self._disposed) {
clearTimeout(timeout)
timeout = self = null
return
}
var last = getTime() - timestamp
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last)
} else {
timeout = null
// result = func.apply(context, args)
func()
// context = args = null
}
}
return function() {
// context = this
// args = arguments
timestamp = getTime()
if (!timeout) {
timeout = setTimeout(later, wait)
}
// return result
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47059
|
setBarSize
|
train
|
function setBarSize(_size) {
var barMinSize = this.barMinSize || 20
var size = _size
if (size > 0 && size < barMinSize) {
size = barMinSize
}
if (this.bar) {
css(this.bar, this.origin.size, parseInt(size, 10) + 'px')
}
}
|
javascript
|
{
"resource": ""
}
|
q47060
|
posBar
|
train
|
function posBar(_pos) {
if (this.bar) {
var was = css(this.bar, this.origin.pos),
will = +_pos + 'px'
if (will && will != was) {
css(this.bar, this.origin.pos, will)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47061
|
train
|
function(params) {
if (process.env.NODE_ENV !== 'production') {
if (this._disposed) {
log('error', [
'Update on disposed baron instance detected.',
'You should clear your stored baron value for this instance:',
this
].join(' '), params)
}
}
fire.call(this, 'upd', params) // Update all plugins' params
this.resize(1)
this.updatePositions(1)
return this
}
|
javascript
|
{
"resource": ""
}
|
|
q47062
|
HelloSignResource
|
train
|
function HelloSignResource(hellosign, urlData) {
this._hellosign = hellosign;
this._urlData = urlData || {};
this.basePath = utils.makeURLInterpolator(hellosign.getApiField('basePath'));
this.path = utils.makeURLInterpolator(this.path);
if (this.includeBasic) {
this.includeBasic.forEach(function(methodName) {
this[methodName] = HelloSignResource.BASIC_METHODS[methodName];
}, this);
}
this.initialize.apply(this, arguments);
}
|
javascript
|
{
"resource": ""
}
|
q47063
|
Agent
|
train
|
function Agent(consul) {
this.consul = consul;
this.check = new Agent.Check(consul);
this.service = new Agent.Service(consul);
}
|
javascript
|
{
"resource": ""
}
|
q47064
|
Lock
|
train
|
function Lock(consul, opts) {
events.EventEmitter.call(this);
opts = utils.normalizeKeys(opts);
this.consul = consul;
this._opts = opts;
this._defaults = utils.defaultCommonOptions(opts);
if (opts.session) {
switch (typeof opts.session) {
case 'string':
opts.session = { id: opts.session };
break;
case 'object':
opts.session = utils.normalizeKeys(opts.session);
break;
default:
throw errors.Validation('session must be an object or string');
}
} else {
opts.session = {};
}
if (!opts.key) {
throw errors.Validation('key required');
} else if (typeof opts.key !== 'string') {
throw errors.Validation('key must be a string');
}
}
|
javascript
|
{
"resource": ""
}
|
q47065
|
bodyItem
|
train
|
function bodyItem(request, next) {
if (request.err) return next(false, request.err, undefined, request.res);
if (request.res.body && request.res.body.length) {
return next(false, undefined, request.res.body[0], request.res);
}
next(false, undefined, undefined, request.res);
}
|
javascript
|
{
"resource": ""
}
|
q47066
|
defaultCommonOptions
|
train
|
function defaultCommonOptions(opts) {
opts = normalizeKeys(opts);
var defaults;
constants.DEFAULT_OPTIONS.forEach(function(key) {
if (!opts.hasOwnProperty(key)) return;
if (!defaults) defaults = {};
defaults[key] = opts[key];
});
return defaults;
}
|
javascript
|
{
"resource": ""
}
|
q47067
|
setTimeoutContext
|
train
|
function setTimeoutContext(fn, ctx, timeout) {
var id;
var cancel = function() {
clearTimeout(id);
};
id = setTimeout(function() {
ctx.removeListener('cancel', cancel);
fn();
}, timeout);
ctx.once('cancel', cancel);
}
|
javascript
|
{
"resource": ""
}
|
q47068
|
setIntervalContext
|
train
|
function setIntervalContext(fn, ctx, timeout) {
var id;
var cancel = function() {
clearInterval(id);
};
id = setInterval(function() { fn(); }, timeout);
ctx.once('cancel', cancel);
}
|
javascript
|
{
"resource": ""
}
|
q47069
|
hasIndexChanged
|
train
|
function hasIndexChanged(index, prevIndex) {
if (typeof index !== 'string' || !index) return false;
if (typeof prevIndex !== 'string' || !prevIndex) return true;
return index !== prevIndex;
}
|
javascript
|
{
"resource": ""
}
|
q47070
|
parseQueryMeta
|
train
|
function parseQueryMeta(res) {
var meta = {};
if (res && res.headers) {
if (res.headers['x-consul-index']) {
meta.LastIndex = res.headers['x-consul-index'];
}
if (res.headers['x-consul-lastcontact']) {
meta.LastContact = parseInt(res.headers['x-consul-lastcontact'], 10);
}
if (res.headers['x-consul-knownleader']) {
meta.KnownLeader = res.headers['x-consul-knownleader'] === 'true';
}
if (res.headers['x-consul-translate-addresses']) {
meta.AddressTranslationEnabled = res.headers['x-consul-translate-addresses'] === 'true';
}
}
return meta;
}
|
javascript
|
{
"resource": ""
}
|
q47071
|
Catalog
|
train
|
function Catalog(consul) {
this.consul = consul;
this.connect = new Catalog.Connect(consul);
this.node = new Catalog.Node(consul);
this.service = new Catalog.Service(consul);
}
|
javascript
|
{
"resource": ""
}
|
q47072
|
Consul
|
train
|
function Consul(opts) {
if (!(this instanceof Consul)) {
return new Consul(opts);
}
opts = utils.defaults({}, opts);
if (!opts.baseUrl) {
opts.baseUrl = (opts.secure ? 'https:' : 'http:') + '//' +
(opts.host || '127.0.0.1') + ':' +
(opts.port || 8500) + '/v1';
}
opts.name = 'consul';
opts.type = 'json';
if (opts.defaults) {
var defaults = utils.defaultCommonOptions(opts.defaults);
if (defaults) this._defaults = defaults;
}
delete opts.defaults;
papi.Client.call(this, opts);
this.acl = new Consul.Acl(this);
this.agent = new Consul.Agent(this);
this.catalog = new Consul.Catalog(this);
this.event = new Consul.Event(this);
this.health = new Consul.Health(this);
this.kv = new Consul.Kv(this);
this.query = new Consul.Query(this);
this.session = new Consul.Session(this);
this.status = new Consul.Status(this);
try {
if (opts.promisify) {
if (typeof opts.promisify === 'function') {
papi.tools.promisify(this, opts.promisify);
} else {
papi.tools.promisify(this);
}
}
} catch (err) {
err.message = 'promisify: ' + err.message;
throw err;
}
}
|
javascript
|
{
"resource": ""
}
|
q47073
|
Watch
|
train
|
function Watch(consul, opts) {
var self = this;
events.EventEmitter.call(self);
opts = utils.normalizeKeys(opts);
var options = utils.normalizeKeys(opts.options || {});
options = utils.defaults(options, consul._defaults);
options.wait = options.wait || '30s';
options.index = options.index || '0';
if (typeof options.timeout !== 'string' && typeof options.timeout !== 'number') {
var wait = utils.parseDuration(options.wait);
// A small random amount of additional wait time is added to the supplied
// maximum wait time to spread out the wake up time of any concurrent
// requests. This adds up to wait / 16 additional time to the maximum duration.
options.timeout = Math.ceil(wait + Math.max(wait * 0.1, 500));
}
var backoffFactor = 100;
if (opts.hasOwnProperty('backofffactor') && typeof opts.backofffactor === 'number') {
backoffFactor = opts.backofffactor;
}
var backoffMax = 30 * 1000;
if (opts.hasOwnProperty('backoffmax') && typeof opts.backoffmax === 'number') {
backoffMax = opts.backoffmax;
}
var maxAttempts = -1;
if (opts.hasOwnProperty('maxattempts') && typeof opts.maxattempts === 'number') {
maxAttempts = opts.maxattempts;
}
self._context = { consul: consul };
self._options = options;
self._attempts = 0;
self._maxAttempts = maxAttempts;
self._backoffMax = backoffMax;
self._backoffFactor = backoffFactor;
self._method = opts.method;
if (typeof opts.method !== 'function') {
throw errors.Validation('method required');
}
process.nextTick(function() { self._run(); });
}
|
javascript
|
{
"resource": ""
}
|
q47074
|
getClientIpFromXForwardedFor
|
train
|
function getClientIpFromXForwardedFor(value) {
if (!is.existy(value)) {
return null;
}
if (is.not.string(value)) {
throw new TypeError(`Expected a string, got "${typeof value}"`);
}
// x-forwarded-for may return multiple IP addresses in the format:
// "client IP, proxy 1 IP, proxy 2 IP"
// Therefore, the right-most IP address is the IP address of the most recent proxy
// and the left-most IP address is the IP address of the originating client.
// source: http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html
// Azure Web App's also adds a port for some reason, so we'll only use the first part (the IP)
const forwardedIps = value.split(',').map((e) => {
const ip = e.trim();
if (ip.includes(':')) {
const splitted = ip.split(':');
// make sure we only use this if it's ipv4 (ip:port)
if (splitted.length === 2) {
return splitted[0];
}
}
return ip;
});
// Sometimes IP addresses in this header can be 'unknown' (http://stackoverflow.com/a/11285650).
// Therefore taking the left-most IP address that is not unknown
// A Squid configuration directive can also set the value to "unknown" (http://www.squid-cache.org/Doc/config/forwarded_for/)
return forwardedIps.find(is.ip);
}
|
javascript
|
{
"resource": ""
}
|
q47075
|
getClientIp
|
train
|
function getClientIp(req) {
// Server is probably behind a proxy.
if (req.headers) {
// Standard headers used by Amazon EC2, Heroku, and others.
if (is.ip(req.headers['x-client-ip'])) {
return req.headers['x-client-ip'];
}
// Load-balancers (AWS ELB) or proxies.
const xForwardedFor = getClientIpFromXForwardedFor(req.headers['x-forwarded-for']);
if (is.ip(xForwardedFor)) {
return xForwardedFor;
}
// Cloudflare.
// @see https://support.cloudflare.com/hc/en-us/articles/200170986-How-does-Cloudflare-handle-HTTP-Request-headers-
// CF-Connecting-IP - applied to every request to the origin.
if (is.ip(req.headers['cf-connecting-ip'])) {
return req.headers['cf-connecting-ip'];
}
// Fastly and Firebase hosting header (When forwared to cloud function)
if (is.ip(req.headers['fastly-client-ip'])) {
return req.headers['fastly-client-ip'];
}
// Akamai and Cloudflare: True-Client-IP.
if (is.ip(req.headers['true-client-ip'])) {
return req.headers['true-client-ip'];
}
// Default nginx proxy/fcgi; alternative to x-forwarded-for, used by some proxies.
if (is.ip(req.headers['x-real-ip'])) {
return req.headers['x-real-ip'];
}
// (Rackspace LB and Riverbed's Stingray)
// http://www.rackspace.com/knowledge_center/article/controlling-access-to-linux-cloud-sites-based-on-the-client-ip-address
// https://splash.riverbed.com/docs/DOC-1926
if (is.ip(req.headers['x-cluster-client-ip'])) {
return req.headers['x-cluster-client-ip'];
}
if (is.ip(req.headers['x-forwarded'])) {
return req.headers['x-forwarded'];
}
if (is.ip(req.headers['forwarded-for'])) {
return req.headers['forwarded-for'];
}
if (is.ip(req.headers.forwarded)) {
return req.headers.forwarded;
}
}
// Remote address checks.
if (is.existy(req.connection)) {
if (is.ip(req.connection.remoteAddress)) {
return req.connection.remoteAddress;
}
if (is.existy(req.connection.socket) && is.ip(req.connection.socket.remoteAddress)) {
return req.connection.socket.remoteAddress;
}
}
if (is.existy(req.socket) && is.ip(req.socket.remoteAddress)) {
return req.socket.remoteAddress;
}
if (is.existy(req.info) && is.ip(req.info.remoteAddress)) {
return req.info.remoteAddress;
}
// AWS Api Gateway + Lambda
if (is.existy(req.requestContext) && is.existy(req.requestContext.identity) && is.ip(req.requestContext.identity.sourceIp)) {
return req.requestContext.identity.sourceIp;
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q47076
|
mw
|
train
|
function mw(options) {
// Defaults.
const configuration = is.not.existy(options) ? {} : options;
// Validation.
if (is.not.object(configuration)) {
throw new TypeError('Options must be an object!');
}
const attributeName = configuration.attributeName || 'clientIp';
return (req, res, next) => {
const ip = getClientIp(req);
Object.defineProperty(req, attributeName, {
get: () => ip,
configurable: true
});
next();
};
}
|
javascript
|
{
"resource": ""
}
|
q47077
|
missingSupport
|
train
|
function missingSupport (browserRequest, from) {
const browsers = new BrowserSelection(browserRequest, from)
let result = {}
Object.keys(features).forEach(function (feature) {
const featureData = caniuse.feature(caniuse.features[feature])
const lackData = filterStats(browsers, featureData.stats)
const missingData = lackData.missing
const partialData = lackData.partial
// browsers with missing or partial support for this feature
const missing = lackingBrowsers(missingData)
const partial = lackingBrowsers(partialData)
if (missing.length > 0 || partial.length > 0) {
result[feature] = {
title: featureData.title,
caniuseData: featureData
}
if (missing.length > 0) {
result[feature].missingData = missingData
result[feature].missing = missing
}
if (partial.length > 0) {
result[feature].partialData = partialData
result[feature].partial = partial
}
}
})
return {
browsers: browsers.list(),
features: result
}
}
|
javascript
|
{
"resource": ""
}
|
q47078
|
removeErrorRecovery
|
train
|
function removeErrorRecovery (fn) {
var parseFn = String(fn);
try {
var JSONSelect = require("JSONSelect");
var Reflect = require("reflect");
var ast = Reflect.parse(parseFn);
var labeled = JSONSelect.match(':has(:root > .label > .name:val("_handle_error"))', ast);
labeled[0].body.consequent.body = [labeled[0].body.consequent.body[0], labeled[0].body.consequent.body[1]];
return Reflect.stringify(ast).replace(/_handle_error:\s?/,"").replace(/\\\\n/g,"\\n");
} catch (e) {
return parseFn;
}
}
|
javascript
|
{
"resource": ""
}
|
q47079
|
layerMethod
|
train
|
function layerMethod(k, fun) {
var pos = k.match(position)[0],
key = k.replace(position, ''),
prop = this[key];
if (pos === 'after') {
this[key] = function () {
var ret = prop.apply(this, arguments);
var args = [].slice.call(arguments);
args.splice(0, 0, ret);
fun.apply(this, args);
return ret;
};
} else if (pos === 'before') {
this[key] = function () {
fun.apply(this, arguments);
var ret = prop.apply(this, arguments);
return ret;
};
}
}
|
javascript
|
{
"resource": ""
}
|
q47080
|
typal_construct
|
train
|
function typal_construct() {
var o = typal_mix.apply(create(this), arguments);
var constructor = o.constructor;
var Klass = o.constructor = function () { return constructor.apply(this, arguments); };
Klass.prototype = o;
Klass.mix = typal_mix; // allow for easy singleton property extension
return Klass;
}
|
javascript
|
{
"resource": ""
}
|
q47081
|
buildTable
|
train
|
function buildTable(tbody, data) {
tbody.empty();
data.forEach(function(item) {
var row = $('<tr>').appendTo(tbody);
$('<td>').appendTo(row).text(item.price);
$('<td>').appendTo(row).text(item.weight);
$('<td>').appendTo(row).text(item.taste);
// Associate underlying data with row node so we can access it later
// for filtering.
row.data('item', item);
});
}
|
javascript
|
{
"resource": ""
}
|
q47082
|
updateExpression
|
train
|
function updateExpression() {
// Default highlighter will not highlight anything
var nullHighlighter = function(item) { return false; }
var input = $('.expression');
var expression = input.val();
var highlighter;
if (!expression) {
// No expression specified. Don't highlight anything.
highlighter = nullHighlighter;
input.css('background-color', '#fff');
} else {
try {
// Build highlighter from user's expression
highlighter = compileExpression(expression); // <-- Filtrex!
input.css('background-color', '#dfd');
} catch (e) {
// Failed to parse expression. Don't highlight anything.
highlighter = nullHighlighter;
input.css('background-color', '#fdd');
}
}
highlightRows(highlighter);
}
|
javascript
|
{
"resource": ""
}
|
q47083
|
isInsideFunctionCall
|
train
|
function isInsideFunctionCall(string, index) {
const result = { is: false, fn: null };
const before = string.substring(0, index).trim();
const after = string.substring(index + 1).trim();
const beforeMatch = before.match(/([a-zA-Z_-][a-zA-Z0-9_-]*)\([^(){},]+$/);
if (beforeMatch && beforeMatch[0] && after.search(/^[^(,]+\)/) !== -1) {
result.is = true;
result.fn = beforeMatch[1];
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q47084
|
isStringBefore
|
train
|
function isStringBefore(before) {
const result = { is: false, opsBetween: false };
const stringOpsClipped = before.replace(/(\s*[+/*%]|\s+-)+$/, "");
if (stringOpsClipped !== before) {
result.opsBetween = true;
}
// If it is quoted
if (
stringOpsClipped[stringOpsClipped.length - 1] === '"' ||
stringOpsClipped[stringOpsClipped.length - 1] === "'"
) {
result.is = true;
} else if (
stringOpsClipped.search(
/(?:^|[/(){},: ])([a-zA-Z_][a-zA-Z_0-9-]*|-+[a-zA-Z_]+[a-zA-Z_0-9-]*)$/
) !== -1
) {
// First pattern: a1, a1a, a-1,
result.is = true;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q47085
|
isInterpolationBefore
|
train
|
function isInterpolationBefore(before) {
const result = { is: false, opsBetween: false };
// Removing preceding operators if any
const beforeOpsClipped = before.replace(/(\s*[+/*%-])+$/, "");
if (beforeOpsClipped !== before) {
result.opsBetween = true;
}
if (beforeOpsClipped[beforeOpsClipped.length - 1] === "}") {
result.is = true;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q47086
|
createError
|
train
|
function createError(code, details) {
var error = {
code: code,
message: errors.get(code) || "Internal Server Error"
};
if (details) error["data"] = details;
return error;
}
|
javascript
|
{
"resource": ""
}
|
q47087
|
create_node_in_parent
|
train
|
function create_node_in_parent(error, parentDirectoryNode) {
if(error) {
callback(error);
} else if(parentDirectoryNode.type !== NODE_TYPE_DIRECTORY) {
callback(new Errors.ENOTDIR('a component of the path prefix is not a directory', path));
} else {
parentNode = parentDirectoryNode;
find_node(context, path, check_if_node_exists);
}
}
|
javascript
|
{
"resource": ""
}
|
q47088
|
check_if_node_exists
|
train
|
function check_if_node_exists(error, result) {
if(!error && result) {
callback(new Errors.EEXIST('path name already exists', path));
} else if(error && !(error instanceof Errors.ENOENT)) {
callback(error);
} else {
context.getObject(parentNode.data, create_node);
}
}
|
javascript
|
{
"resource": ""
}
|
q47089
|
create_node
|
train
|
function create_node(error, result) {
if(error) {
callback(error);
} else {
parentNodeData = result;
Node.create({
guid: context.guid,
type: type
}, function(error, result) {
if(error) {
callback(error);
return;
}
node = result;
node.nlinks += 1;
context.putObject(node.id, node, update_parent_node_data);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q47090
|
update_parent_node_data
|
train
|
function update_parent_node_data(error) {
if(error) {
callback(error);
} else {
parentNodeData[name] = new DirectoryEntry(node.id, type);
context.putObject(parentNode.data, parentNodeData, update_time);
}
}
|
javascript
|
{
"resource": ""
}
|
q47091
|
ensure_root_directory
|
train
|
function ensure_root_directory(context, callback) {
var superNode;
var directoryNode;
var directoryData;
function ensure_super_node(error, existingNode) {
if(!error && existingNode) {
// Another instance has beat us and already created the super node.
callback();
} else if(error && !(error instanceof Errors.ENOENT)) {
callback(error);
} else {
SuperNode.create({guid: context.guid}, function(error, result) {
if(error) {
callback(error);
return;
}
superNode = result;
context.putObject(superNode.id, superNode, write_directory_node);
});
}
}
function write_directory_node(error) {
if(error) {
callback(error);
} else {
Node.create({
guid: context.guid,
id: superNode.rnode,
type: NODE_TYPE_DIRECTORY
}, function(error, result) {
if(error) {
callback(error);
return;
}
directoryNode = result;
directoryNode.nlinks += 1;
context.putObject(directoryNode.id, directoryNode, write_directory_data);
});
}
}
function write_directory_data(error) {
if(error) {
callback(error);
} else {
directoryData = {};
context.putObject(directoryNode.data, directoryData, callback);
}
}
context.getObject(SUPER_NODE_ID, ensure_super_node);
}
|
javascript
|
{
"resource": ""
}
|
q47092
|
ensureID
|
train
|
function ensureID(options, prop, callback) {
if(options[prop]) {
return callback();
}
options.guid(function(err, id) {
if(err) {
return callback(err);
}
options[prop] = id;
callback();
});
}
|
javascript
|
{
"resource": ""
}
|
q47093
|
wrappedGuidFn
|
train
|
function wrappedGuidFn(context) {
return function (callback) {
// Skip the duplicate ID check if asked to
if (flags.includes(FS_NODUPEIDCHECK)) {
callback(null, guid());
return;
}
// Otherwise (default) make sure this id is unused first
function guidWithCheck(callback) {
const id = guid();
context.getObject(id, function (err, value) {
if (err) {
callback(err);
return;
}
// If this id is unused, use it, otherwise find another
if (!value) {
callback(null, id);
} else {
guidWithCheck(callback);
}
});
}
guidWithCheck(callback);
};
}
|
javascript
|
{
"resource": ""
}
|
q47094
|
train
|
function (countries, preferred, preferredDelim) {
var preferredShortCodes = preferred.split(',').reverse();
var preferredMap = {};
var foundPreferred = false;
var updatedCountries = countries.filter(function (c) {
if (preferredShortCodes.indexOf(c[1]) !== -1) {
preferredMap[c[1]] = c;
foundPreferred = true;
return false;
}
return true;
});
if (foundPreferred && preferredDelim) {
updatedCountries.unshift([preferredDelim, "", "", {}, true]);
}
// now prepend the preferred countries
for (var i=0; i<preferredShortCodes.length; i++) {
var code = preferredShortCodes[i];
updatedCountries.unshift(preferredMap[code]);
}
return updatedCountries;
}
|
javascript
|
{
"resource": ""
}
|
|
q47095
|
getCountryList
|
train
|
function getCountryList() {
var countries = grunt.option("countries");
if (!countries) {
grunt.fail.fatal("Country list not passed. Example usage: `grunt customBuild --countries=Canada,United States`");
}
// countries may contain commas in their names. Bit ugly, but simple. This swiches out those escaped commas
// and replaces them later
var commaReplaced = countries.replace(/\\,/g, '{COMMA}');
var targetCountries = _.map(commaReplaced.split(","), function (country) {
return country.replace(/\{COMMA\}/, ',').trim();
});
var countryData = [];
var foundCountryNames = [];
var formattedData = minifyJSON(countriesJSON);
_.each(formattedData, function (countryInfo) {
var countryName = countryInfo[0];
if (_.contains(targetCountries, countryName)) {
countryData.push(countryInfo);
foundCountryNames.push(countryName);
}
});
// if one or more of the countries wasn't found, they probably made a typo: throw a warning but continue
if (targetCountries.length !== countryData.length) {
grunt.log.error("The following countries weren't found (check the source/data.json file to ensure you entered the exact country string):");
var missing = _.difference(targetCountries, foundCountryNames);
_.each(missing, function (countryName) {
grunt.log.error("--", countryName);
});
// all good! Let the user know what bundle is being created, just to remove any ambiguity
} else {
grunt.log.writeln("");
grunt.log.writeln("Creating bundle with following countries:");
_.each(targetCountries, function (country) {
grunt.log.writeln("* " + country);
});
}
config.template.customBuild.options.data.__DATA__ = "\nvar _data = " + JSON.stringify(countryData);
}
|
javascript
|
{
"resource": ""
}
|
q47096
|
minifyJSON
|
train
|
function minifyJSON(json) {
var js = [];
json.forEach(function (countryData) {
var pairs = [];
countryData.regions.forEach(function (info) {
if (_.has(info, 'shortCode')) {
pairs.push(info.name + '~' + info.shortCode);
} else {
pairs.push(info.name);
}
});
var regionListStr = pairs.join('|');
js.push([
countryData.countryName,
countryData.countryShortCode,
regionListStr
]);
});
return js;
}
|
javascript
|
{
"resource": ""
}
|
q47097
|
urlConfig
|
train
|
function urlConfig (url) {
var config = {
path: true,
query: true,
hash: true
};
if (!url) {
return config;
}
if (RX_PROTOCOL.test(url)) {
config.protocol = true;
config.host = true;
if (RX_PORT.test(url)) {
config.port = true;
}
if (RX_CREDS.test(url)) {
config.user = true;
config.pass = true;
}
}
return config;
}
|
javascript
|
{
"resource": ""
}
|
q47098
|
keysIndex
|
train
|
function keysIndex(a) {
var keys = [],
l,
k,
i;
for (i = 0, l = a.length; i < l; i++)
for (k in a[i])
if (!~keys.indexOf(k))
keys.push(k);
return keys;
}
|
javascript
|
{
"resource": ""
}
|
q47099
|
toCSVString
|
train
|
function toCSVString(data, params) {
if (data.length === 0) {
return '';
}
params = params || {};
var header = params.headers || [],
plainObject = isPlainObject(data[0]),
keys = plainObject && (params.order || keysIndex(data)),
oData,
i;
// Defaults
var escape = params.escape || '"',
delimiter = params.delimiter || ',';
// Dealing with headers polymorphism
if (!header.length)
if (plainObject && params.headers !== false)
header = keys;
// Should we append headers
oData = (header.length ? [header] : []).concat(
plainObject ?
data.map(function(e) { return objectToArray(e, keys); }) :
data
);
// Converting to string
return oData.map(function(row) {
return row.map(function(item) {
// Wrapping escaping characters
var i = ('' + (typeof item === 'undefined' ? '' : item)).replace(
new RegExp(rescape(escape), 'g'),
escape + escape
);
// Escaping if needed
return ~i.indexOf(delimiter) || ~i.indexOf(escape) || ~i.indexOf('\n') ?
escape + i + escape :
i;
}).join(delimiter);
}).join('\n');
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.