_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q42900
train
function (is_ignore_errors) { var file_paths = []; // root of dependence source directory file_paths.push('./commands.json'); // root of denhub-device directory file_paths.push(__dirname + '/../commands.json'); var file = null; for (var i = 0, l = file_paths.length; i < l; i++) { try { file = require('fs').readFileSync(file_paths[i]); } catch (e) { continue; } if (file) break; } if (!file && !is_ignore_errors) { console.log(colors.bold.red('Error: Could not read the commands file.')); console.log(file_paths.join('\n')); console.log(colors.bold('If you never created it, please try the following command:')); console.log('$ denhub-device-generator --init\n'); process.exit(255); } var commands = {}; if (file) { try { commands = JSON.parse(file); } catch (e) { if (!is_ignore_errors) throw e; commands = null; } } return commands; }
javascript
{ "resource": "" }
q42901
train
function (str) { var self = this; if ('i' !== 'I'.toLowerCase()) { // Thanks for http://qiita.com/niusounds/items/fff91f3f236c31ca910f return str.replace(/[a-z]/g, function(ch) { return String.fromCharCode(ch.charCodeAt(0) & ~32); }); } return str.toUpperCase(); }
javascript
{ "resource": "" }
q42902
train
function (obj, var_type) { var text_class = Object.prototype.toString.call(obj).slice(8, -1); return (text_class == var_type); }
javascript
{ "resource": "" }
q42903
train
function(paramd) { var self = this paramd = defaults(paramd, { iri: "http://data.sparkfun.com" }) self.iri = paramd.iri }
javascript
{ "resource": "" }
q42904
train
function(paramd, defaultd) { if (paramd === undefined) { return defaultd } for (var key in defaultd) { var pvalue = paramd[key] if (pvalue === undefined) { paramd[key] = defaultd[key] } } return paramd; }
javascript
{ "resource": "" }
q42905
train
function (customEvent, callback, filter, prepend) { return Event.after(customEvent, callback, this, filter, prepend); }
javascript
{ "resource": "" }
q42906
train
function (customEvent, callback, filter, prepend) { return Event.before(customEvent, callback, this, filter, prepend); }
javascript
{ "resource": "" }
q42907
setBox
train
function setBox(){ if(my.container){ my.box = { x: 0, y: 0, width: my.container.clientWidth, height: my.container.clientHeight }; } }
javascript
{ "resource": "" }
q42908
aliasesInLayout
train
function aliasesInLayout(layout, sizes){ return Object.keys(computeLayout(layout, sizes, { width: 100, height: 100 })); }
javascript
{ "resource": "" }
q42909
parseParams
train
function parseParams(params, init) { return reduce(params, function(obj, param) { var parts = param.split(/ *= */); var key = removeQuote(parts[0]); obj[key] = removeQuote(parts[1]); return obj; }, init); }
javascript
{ "resource": "" }
q42910
CompileModules
train
function CompileModules(inputTree, options) { this.setInputTree(inputTree); this.setInputFiles(options.inputFiles); this.setResolvers(options.resolvers || []); this.setOutput(options.output); this.setFormatter(options.formatter); if (options.output) { this.description = 'CompileModules (' + options.output + ')'; } }
javascript
{ "resource": "" }
q42911
ObfuscatingStorageWrapper
train
function ObfuscatingStorageWrapper(storage) { var SECRET_KEY_KEY = "___XX"; var wellKnownKey = "ce56c9aa-d287-4e7c-b9d5-edca7a985487"; function getSecretKey() { var secretKeyName = scrambleKey(SECRET_KEY_KEY, wellKnownKey); var secretKey = storage.getItem(secretKeyName); if (secretKey === null) { secretKey = GuidGenerator(); storage.setItem(secretKeyName, encryptValue(secretKey, wellKnownKey)); } else { secretKey = decryptValue(secretKey, wellKnownKey); } return secretKey; } function scrambleKey(key, encryptionKey) { return CryptoJS.HmacMD5(key, encryptionKey || getSecretKey()).toString(); } function encryptValue(value, encryptionKey) { return CryptoJS.AES.encrypt(JSON.stringify(value), encryptionKey || getSecretKey()).toString(); } function decryptValue(value, encryptionKey) { if (value === null) { return null; } try { var decryptedValue = CryptoJS.AES.decrypt(value, encryptionKey || getSecretKey()).toString(CryptoJS.enc.Utf8); return JSON.parse(decryptedValue); } catch (e) { return null; } } this.getItem = function (key) { return decryptValue(storage.getItem(scrambleKey(key))); }; this.setItem = function (key, value) { storage.setItem(scrambleKey(key), encryptValue(value)); }; this.removeItem = function (key) { storage.removeItem(scrambleKey(key)); }; this.clear = function () { storage.clear(); }; getSecretKey(); }
javascript
{ "resource": "" }
q42912
phaserShimDebug
train
function phaserShimDebug(source) { this.cacheable && this.cacheable(); source = source.replace(/(var\s+ui\s*=\s*require\('\.\/util\/ui'\))/, 'var Phaser = _Phaser; $1'); source = '(function () { var _Phaser = require("phaser").Phaser;\n\n' + source + '\n\n}());'; return source; }
javascript
{ "resource": "" }
q42913
retry
train
function retry(err) { if (currentAttempt >= retryCount) { return callback(err, null, currentAttempt); } currentAttempt += 1; // Since the currentAttempt starts at 1 and it was just incremented // currentAttempt - 2 will be the actual timeout index. return setTimeout(attempt, timeouts[currentAttempt - 2]); }
javascript
{ "resource": "" }
q42914
make
train
function make(component, config) { var Constructor, Subclass, conf = config || {}; // Config exists as a way to create pass a set of derived options. In the original use case a function was created // to parse the DOM and pass information to the component at the time of creation. // Allow the $el to be passed directly as part of component instead of with the configuration. if (component.$el && !conf.$el) { conf.$el = component.$el; } Constructor = Component.subclass(new ApiInstance()); if (!subclasses[component.name]) { // Cache initialized subclasses so we can reuse them with custom configuration. subclasses[component.name] = Constructor.subclass(component); } // Create the subclass constructor Subclass = subclasses[component.name].subclass(conf); // Return an instance return new Subclass(); }
javascript
{ "resource": "" }
q42915
emitEvents
train
function emitEvents(stream) { //if emitEvents gets called while in emitEvents we don't want to screw up the order if (stream._emittingMatches) { return; } var matches = stream.matches, i = matches.length; stream.matches = []; stream._emittingMatches = true; while (i--) { stream.emit('data', matches[i]); } stream._emittingMatches = false; //test to see if someone tried to emit events within emitting events if (stream.emitEvents && stream.matches[0] !== undefined) { emitEvents(stream); } }
javascript
{ "resource": "" }
q42916
handleData
train
function handleData(stream, asString, data, dataLimit) { var dataLen = data.length, i = dataLen, trailingDataIndex = -1, //index of data after the last delimiter match in data lastMatchIndex = 0, matchLimit = dataLimit || Infinity, len = 0; //first start going back through data to find the last match //we do this loop separately so we can just store the index of the last match and then add that to the buffer at the end for the next packet while (i--) { if (data[i] === stream.delimiter) { //now that we found the match, store the index (+1 so we don't store the delimiter) trailingDataIndex = i + 1; break; } } //if we didn't find a match at all, just push the data onto the buffer if (trailingDataIndex === -1) { //don't use dataLimit here since we shouldn't pass in infinity to concatBuffer stream.buffer = concatBuffer(stream.buffer, data, dataLimit); return; } lastMatchIndex = i; while (i--) { if (data[i] === stream.delimiter) { //make sure we ignore back-to-back delimiters len = lastMatchIndex - (i + 1); //i + 1 so we don't include the delimiter we just matched if (len > matchLimit) { stream.matches.push(data.slice(lastMatchIndex - matchLimit, lastMatchIndex)); } else if (len > 0) { stream.matches.push(data.slice(i + 1, lastMatchIndex)); } lastMatchIndex = i; } } //since the loop stops at the beginning of data we need to store the bytes before the first match in the string if (lastMatchIndex > 0) { stream.buffer = concatBuffer(stream.buffer, data.slice(0, lastMatchIndex), dataLimit); } //add the leftover buffer to the matches at the end (beginning when we emit events) if (asString) { if (isNode) { stream.matches.push(stream.buffer.toString()); stream.buffer = new BUFFER_CONSTRUCTOR(0); } else { stream.matches.push(stream.buffer.splice(0, stream.buffer.length).join('')); } } else { stream.matches.push(stream.buffer); stream.buffer = new BUFFER_CONSTRUCTOR(0); } //todo: optimize this to not make an empty buffer just to fill it with a new thing immediately after //make sure the lastMatchIndex isn't the end if (lastMatchIndex < dataLen) { //don't use dataLimit here since we shouldn't pass in infinity to concatBuffer stream.buffer = concatBuffer(stream.buffer, data.slice(trailingDataIndex), dataLimit); } if (stream.emitEvents) { emitEvents(stream); } }
javascript
{ "resource": "" }
q42917
train
function (pkg, options) { var settingsFile = new SettingsFile(pkg, options); var save = settingsFile.save; settingsFile.save = _.bind(function (config) { return save.call(settingsFile, config) .then(function () { client.emit('config.global-changed', { app: pkg, config: config }); }); }, settingsFile); var settingsSet = settingsFile.set; settingsFile.set = _.bind(function (config) { return settingsSet.call(settingsFile, config) .then(function () { client.emit('config.global-changed', { app: pkg, config: config }); }); }, settingsFile); /** * Register for global settings changes * * @param {function} cb Event callback */ settingsFile.onChange = function (cb) { client.on('settings.global-changed:' + pkg, cb); }; var instance = settingsFile.instance; settingsFile.instance = _.bind(function (id) { var returnedInstance = instance.call(settingsFile, id); var save = returnedInstance.save; returnedInstance.save = _.bind(function (config) { return save.call(returnedInstance, config) .then(function () { client.emit('settings.instance-changed:' + returnedInstance._id, { instance: returnedInstance._id, config: config }); }); }, returnedInstance); var instanceSet = returnedInstance.set; returnedInstance.set = _.bind(function (config) { return instanceSet.call(returnedInstance, config) .then(function () { client.emit('settings.instance-changed:' + returnedInstance._id, { instance: returnedInstance._id, config: config }); }); }, returnedInstance); /** * Register for instance settings changes * * @param {function} cb Event callback */ returnedInstance.onChange = function (cb) { client.on('settings.instance-changed:' + returnedInstance._id, cb); }; return returnedInstance; }, settingsFile); return settingsFile; }
javascript
{ "resource": "" }
q42918
Rule
train
function Rule(lhs, rhs, valuator) { let arr = []; if (!rhs || rhs.length === 0) { throw new Error('Rule does not produce anything'); } arr.push.apply(arr, rhs); arr.lhs = lhs; Object.defineProperty(arr, 'lhs', { value: lhs }); Object.defineProperty(arr, 'evaluate', { value: (values) => (valuator) ? valuator.apply(null, values) : null }); arr.__proto__ = Rule.prototype; return arr; }
javascript
{ "resource": "" }
q42919
Sym
train
function Sym(name) { let symbol = {}; symbol.__proto__ = Sym.prototype; symbol.name = name; return symbol; }
javascript
{ "resource": "" }
q42920
_getMatches
train
function _getMatches(character, modifiers, e, sequenceName, combination, level) { var i, callback, matches = [], action = e.type; // if there are no events related to this keycode if (!this._callbacks[character]) { return []; } // if a modifier key is coming up on its own we should allow it if (action == 'keyup' && _isModifier(character)) { modifiers = [character]; } // loop through all callbacks for the key that was pressed // and see if any of them match for (i = 0; i < this._callbacks[character].length; ++i) { callback = this._callbacks[character][i]; // if a sequence name is not specified, but this is a sequence at // the wrong level then move onto the next match if (!sequenceName && callback.seq && this._sequenceLevels[callback.seq] != callback.level) { continue; } // if the action we are looking for doesn't match the action we got // then we should keep going if (action != callback.action) { continue; } // if this is a keypress event and the meta key and control key // are not pressed that means that we need to only look at the // character, otherwise check the modifiers as well // // chrome will not fire a keypress if meta or control is down // safari will fire a keypress if meta or meta+shift is down // firefox will fire a keypress if meta or control is down if ((action == 'keypress' && !e.metaKey && !e.ctrlKey) || _modifiersMatch(modifiers, callback.modifiers)) { // when you bind a combination or sequence a second time it // should overwrite the first one. if a sequenceName or // combination is specified in this call it does just that // // @todo make deleting its own method? var deleteCombo = !sequenceName && callback.combo == combination; var deleteSequence = sequenceName && callback.seq == sequenceName && callback.level == level; if (deleteCombo || deleteSequence) { this._callbacks[character].splice(i, 1); } matches.push(callback); } } return matches; }
javascript
{ "resource": "" }
q42921
_getReverseMap
train
function _getReverseMap() { if (!this._REVERSE_MAP) { this._REVERSE_MAP = {}; for (var key in _MAP) { // pull out the numeric keypad from here cause keypress should // be able to detect the keys from the character if (key > 95 && key < 112) { continue; } if (_MAP.hasOwnProperty(key)) { this._REVERSE_MAP[_MAP[key]] = key; } } } return this._REVERSE_MAP; }
javascript
{ "resource": "" }
q42922
_bindSequence
train
function _bindSequence(combo, keys, callback, action) { var that = this; // start off by adding a sequence level record for this combination // and setting the level to 0 this._sequenceLevels[combo] = 0; /** * callback to increase the sequence level for this sequence and reset * all other sequences that were active * * @param {string} nextAction * @returns {Function} */ function _increaseSequence(nextAction) { return function() { that._nextExpectedAction = nextAction; ++that._sequenceLevels[combo]; _resetSequenceTimer.call(that); }; } /** * wraps the specified callback inside of another function in order * to reset all sequence counters as soon as this sequence is done * * @param {Event} e * @returns void */ function _callbackAndReset(e) { _fireCallback.call(this, callback, e, combo); // we should ignore the next key up if the action is key down // or keypress. this is so if you finish a sequence and // release the key the final key will not trigger a keyup if (action !== 'keyup') { this._ignoreNextKeyup = _characterFromEvent(e); } // weird race condition if a sequence ends with the key // another sequence begins with setTimeout(_resetSequences.bind(this), 10); } // loop through keys one at a time and bind the appropriate callback // function. for any key leading up to the final one it should // increase the sequence. after the final, it should reset all sequences // // if an action is specified in the original bind call then that will // be used throughout. otherwise we will pass the action that the // next key in the sequence should match. this allows a sequence // to mix and match keypress and keydown events depending on which // ones are better suited to the key provided for (var i = 0; i < keys.length; ++i) { var isFinal = i + 1 === keys.length; var wrappedCallback = isFinal ? _callbackAndReset : _increaseSequence.call(this, action || _getKeyInfo(keys[i + 1]).action); _bindSingle.call(this, keys[i], wrappedCallback, action, combo, i); } }
javascript
{ "resource": "" }
q42923
_increaseSequence
train
function _increaseSequence(nextAction) { return function() { that._nextExpectedAction = nextAction; ++that._sequenceLevels[combo]; _resetSequenceTimer.call(that); }; }
javascript
{ "resource": "" }
q42924
_callbackAndReset
train
function _callbackAndReset(e) { _fireCallback.call(this, callback, e, combo); // we should ignore the next key up if the action is key down // or keypress. this is so if you finish a sequence and // release the key the final key will not trigger a keyup if (action !== 'keyup') { this._ignoreNextKeyup = _characterFromEvent(e); } // weird race condition if a sequence ends with the key // another sequence begins with setTimeout(_resetSequences.bind(this), 10); }
javascript
{ "resource": "" }
q42925
train
function( languageCode, defaultLanguage, callback ) { // If no languageCode - fallback to browser or default. // If languageCode - fallback to no-localized version or default. if ( !languageCode || !CKEDITOR.lang.languages[ languageCode ] ) languageCode = this.detect( defaultLanguage, languageCode ); var that = this, loadedCallback = function() { that[ languageCode ].dir = that.rtl[ languageCode ] ? 'rtl' : 'ltr'; callback( languageCode, that[ languageCode ] ); }; if ( !this[ languageCode ] ) CKEDITOR.scriptLoader.load( CKEDITOR.getUrl( 'lang/' + languageCode + '.js' ), loadedCallback, this ); else loadedCallback(); }
javascript
{ "resource": "" }
q42926
train
function(title, obj) { if (arguments.length == 2) { this.msg(title); } else { obj = title; } doLog(generalUtils.getProperties(obj)); }
javascript
{ "resource": "" }
q42927
split
train
function split(url) { assert.equal(typeof url, 'string', 'url-querystring: url should be a string'); var res = {}; var nw = url.split('?'); res.url = nw[0]; res.qs = nw.length == 2 ? qs.parse(nw[1]) : {}; return res; }
javascript
{ "resource": "" }
q42928
dirExist
train
function dirExist(dirName) { return new Promise((resolve, reject) => { fs.stat(dirName, (err, stats) => { if (err === null && stats.isDirectory()) { resolve(dirName); } else { resolve(false); } }); }); }
javascript
{ "resource": "" }
q42929
Identity
train
function Identity(userID, passphrase, keyPair) { if (!(this instanceof Identity)) { return new Identity(userID, passphrase, keyPair); } assert(typeof userID === 'string', 'Invalid userID supplied'); assert(typeof passphrase === 'string', 'Invalid passphrase supplied'); this._publicKeyArmored = keyPair.publicKey.toString(); this._privateKeyArmored = keyPair.privateKey.toString(); this.userID = userID; this.publicKey = pgp.key.readArmored(this._publicKeyArmored).keys[0]; this.privateKey = pgp.key.readArmored(this._privateKeyArmored).keys[0]; assert(this.privateKey.decrypt(passphrase), 'Failed to decrypt private key'); }
javascript
{ "resource": "" }
q42930
extend
train
function extend(x, y){ for(var key in y) { if (y.hasOwnProperty(key)) { x[key] = y[key]; } } return x; }
javascript
{ "resource": "" }
q42931
train
function(mongo_host, db, collection) { var arrayMongo = function() { }; arrayMongo.prototype = Array.prototype; extend(arrayMongo.prototype, { /** * Store the parameters */ host: function() { return mongo_host; }, db: function() { return db; }, mongoCollection: function() { return collection; }, load: function(finished) { console.log('HERE'); var self = this; var cname = this.mongoCollection(); mongoCache.getConnection(this.host(), this.db(), (function(err, db) { if(err) return; var collection = db.collection(cname); collection.find().toArray(function(err, docs) { if(err || docs.length < 1) { finished(); return; } // Copy all the documents in the array docs.forEach(function(doc) { self.push(doc); }); finished(); }.bind(this)); }).bind(this)); }, save: function() { var self = this; var cname = this.mongoCollection(); mongoCache.getConnection(this.host(), this.db(), (function(err, db) { if(err) return; var collection = db.collection(cname); self.forEach(function(element) { if(element['_id']) { collection.update({_id: element['_id']}, element, function(){ }); } else { collection.insert(element, function(){ }); } }); }).bind(this)); } }); // Create instance and return it return new arrayMongo(); }
javascript
{ "resource": "" }
q42932
pwCipher
train
function pwCipher(string) { if(string) { if ( typeof pw !== 'string' || pw.length < 8 ) { throw new Error('Please set a password with 8 or ' + 'more chars on process.env.CIPHER_UTIL_PW!'); } if ( typeof algo !== 'string' || algo.length < 1 ) { throw new Error('Please choose an algorithm' + ' on process.env.CIPHER_UTIL_ALGO!'); } var ciphered = crypto.createCipher(algo, pw), /* * Array */ encrypted = [ciphered.update(string)]; encrypted.push(ciphered.final()); return Buffer.concat(encrypted).toString(pwEnc); } return null; }
javascript
{ "resource": "" }
q42933
pwDecipher
train
function pwDecipher(string) { if(string) { if ( typeof pw !== 'string' || pw.length < 8 ) { throw new Error('Please set a password with 8 or ' + 'more chars on process.env.CIPHER_UTIL_PW!'); } if ( typeof algo !== 'string' || algo.length < 1 ) { throw new Error('Please choose an algorithm' + ' on process.env.CIPHER_UTIL_ALGO!'); } var buffer = new Buffer(string, pwEnc), toDecipher = crypto.createDecipher(algo, pw), deciphered = [toDecipher.update(buffer)]; deciphered.push(toDecipher.final()); return Buffer.concat(deciphered).toString(dec); } return null; }
javascript
{ "resource": "" }
q42934
bundle
train
function bundle(entryPoint, buildContext, opts) { if (!opts) { opts = {}; } if (!opts.outputFileName) { opts.outputFileName = 'index.js'; } if (!opts.destPath) { opts.destPath = buildContext.destPath; } if (opts.rev !== false) { opts.rev = true; } var shouldUglify = false; var config = { // these are needed for watchify cache: {}, packageCache: {}, fullPaths: false, // Specify the entry point of the bundle entries: entryPoint, // Enable source maps debug: buildContext.dev }; var bundler = browserify(config) .transform(babelify.configure({stage: 1})); if (buildContext.watch) { // Wrap with watchify and rebundle on changes bundler = watchify(bundler); // Rebundle on update bundler.on('update', doBundle.bind(null, bundler, buildContext, opts)); } return doBundle(bundler, buildContext, opts); }
javascript
{ "resource": "" }
q42935
is
train
function is(obj, name) { if (typeof name !== 'string') { throw new TypeError('expected name to be a string'); } utils.define(obj, 'is' + utils.pascal(name), true); utils.define(obj, '_name', name); }
javascript
{ "resource": "" }
q42936
beforeParse
train
function beforeParse(e) { var namespace = e.source.match(rgxNamespace); var className = e.source.match(rgxClassName); // Fix members not showing up attached to class if (namespace && className) { // console.log(`${namespace[1]}.${className[2]}`); // Replaces "@member {Type}"" with "@member {Type} PIXI.ClassName#prop" e.source = e.source.replace(rgxMember, '$1 '+ namespace[1] + '.' + className[2] + '#$4$2$3'); } e.source = e.source.replace(rgxGross, grossReplace); }
javascript
{ "resource": "" }
q42937
Suite
train
function Suite(title, ctx) { this.title = title; this.ctx = ctx; this.suites = []; this.tests = []; this.pending = false; this._beforeEach = []; this._beforeAll = []; this._afterEach = []; this._afterAll = []; this.root = !title; this._timeout = 2000; this._slow = 75; this._bail = false; }
javascript
{ "resource": "" }
q42938
unbox
train
function unbox(value){ if (value instanceof ResType) return when(value, unbox) if (value && typeof value == 'object') return unboxAll(value) return value }
javascript
{ "resource": "" }
q42939
useGatewayAuthentication
train
function useGatewayAuthentication(req) { // can be set on request if via application supplied callback if (req.useGateway == true) { return true; } // otherwise via query parameter var origUrl = req.originalUrl; var useGateway = false; var idx = origUrl.indexOf(gatewayParameter); if (idx >= 0) { useGateway = true; } return useGateway; }
javascript
{ "resource": "" }
q42940
stripGatewayAuthenticationParameter
train
function stripGatewayAuthenticationParameter(aUrl) { if (aUrl.query && aUrl.query.useGateway) { delete aUrl.query.useGateway; } if (aUrl.query.nextUrl) { var theNextUrl = decodeURIComponent(aUrl.query.nextUrl); aUrl.query.nextUrl = decodeURIComponent(theNextUrl); } var theUrl = url.format(aUrl); return theUrl; }
javascript
{ "resource": "" }
q42941
train
function ( h ) { getData ( h, true ) .then ( function ( data ) { if ( h.readValue == data ) { // same. ignore } else { // console.log ( `onChangedPath ( "${h.path}" ) ` ) h.evalValue = null h.readValue = data // reload let callbacks = h.callbacks for ( let i = callbacks.length-1; i >= 0; --i ) { let clbk = callbacks [ i ] clbk.handler ( h, clbk.callback ) } } } ) }
javascript
{ "resource": "" }
q42942
train
function ( path, base ) { let filename let start = path.substr ( 0, 2 ) if ( path.charAt ( 0 ) === '/' ) { // absolute path filename = path } else if ( start == './' || start == '..' || path == '.' ) { filename = lpath.resolve ( base, path ) } else { // funky node_modules path not supported throw new Error ( `Cannot watch path '${ path }' ( not a relative or absolute path ) ` ) } return filename }
javascript
{ "resource": "" }
q42943
train
function ( path, base ) { let start = path.substr ( 0, 2 ) let paths if ( start != './' && start != '..' ) { // absolute or funky node_modules require paths = module.paths } else { paths = [ base ] } let filename = findPath ( path, paths ) if ( !filename ) { throw new Error ( `Cannot find path '${ path }'` ) } return filename }
javascript
{ "resource": "" }
q42944
train
function(date) { if (_.isDate(date)) { this._date = date.toSerialNumber(); } else if (_.isNumber(date)) { this._date = date; } else { throw new CError('wrong date type').log(); } }
javascript
{ "resource": "" }
q42945
train
function(password) { // empty password not allowed if (password) { var hmac = forge.hmac.create(); hmac.start('sha256', SECRET); hmac.update(password); this._password = password; this._passwordHash = hmac.digest().toHex(); } }
javascript
{ "resource": "" }
q42946
find
train
function find(key, target, opts) { opts = opts || {}; var path = [] , o = target, i, k, p , re = opts.re = opts.re || /\./ , parts = key.split(re); for(i =0;i < parts.length;i++) { k = parts[i]; p = o; if(opts.create && o[k] === undefined) o[k] = {}; o = o[k]; path.push(k); if(!o) break; } return {key: k, value: o, parent: p, path: path.join('.')}; }
javascript
{ "resource": "" }
q42947
camelToSnake
train
function camelToSnake( string ) { return string.replace( ptnCamel, ( all, predecessor, match ) => predecessor + "_" + match.toLocaleLowerCase() ); }
javascript
{ "resource": "" }
q42948
camelToKebab
train
function camelToKebab( string ) { return string.replace( ptnCamel, ( all, predecessor, match ) => predecessor + "-" + match.toLocaleLowerCase() ); }
javascript
{ "resource": "" }
q42949
snakeToCamel
train
function snakeToCamel( string ) { return string.replace( ptnSnake, ( all, predecessor, match ) => predecessor + match.toLocaleUpperCase() ); }
javascript
{ "resource": "" }
q42950
snakeToKebab
train
function snakeToKebab( string ) { return string.replace( ptnSnake, ( all, predecessor, match ) => predecessor + "-" + match ); }
javascript
{ "resource": "" }
q42951
kebabToCamel
train
function kebabToCamel( string ) { return string.replace( ptnKebab, ( all, predecessor, match ) => predecessor + match.toLocaleUpperCase() ); }
javascript
{ "resource": "" }
q42952
kebabToPascal
train
function kebabToPascal( string ) { const camel = kebabToCamel( string ); return camel.slice( 0, 1 ).toUpperCase() + camel.slice( 1 ); }
javascript
{ "resource": "" }
q42953
kebabToSnake
train
function kebabToSnake( string ) { return string.replace( ptnKebab, ( all, predecessor, match ) => predecessor + "_" + match ); }
javascript
{ "resource": "" }
q42954
CodecConfiguration
train
function CodecConfiguration(codecConfigurationDict){ if(!(this instanceof CodecConfiguration)) return new CodecConfiguration(codecConfigurationDict) // Check codecConfigurationDict has the required fields checkType('String', 'codecConfigurationDict.name', codecConfigurationDict.name, {required: true}); checkType('String', 'codecConfigurationDict.properties', codecConfigurationDict.properties); // Init parent class CodecConfiguration.super_.call(this, codecConfigurationDict) // Set object properties Object.defineProperties(this, { name: { writable: true, enumerable: true, value: codecConfigurationDict.name }, properties: { writable: true, enumerable: true, value: codecConfigurationDict.properties } }) }
javascript
{ "resource": "" }
q42955
DefaultHandle
train
function DefaultHandle(done, req, res, parsedUrl) { this.res = res; this.res.once('error', this.error.bind(this)); this.req = req; this.req.once('error', this.error.bind(this)); this.url = parsedUrl; // If this is the actual constructor call done now if (this.constructor === DefaultHandle) done(null); }
javascript
{ "resource": "" }
q42956
varargs
train
function varargs(args) { var argl = args.length; var arga; if (!Array.isArray(args)) { arga = new Array(argl); for (var i = 0; i < argl; i++) { arga[i] = args[i]; } } return arga; }
javascript
{ "resource": "" }
q42957
solveCurveX
train
function solveCurveX(x) { var t2 = x, derivative, x2; // https://trac.webkit.org/browser/trunk/Source/WebCore/platform/animation // First try a few iterations of Newton's method -- normally very fast. // http://en.wikipedia.org/wiki/Newton's_method for (var i = 0; i < 8; i++) { // f(t)-x=0 x2 = sampleCurveX(t2) - x; if (Math.abs(x2) < ZERO_LIMIT) { return t2; } derivative = sampleCurveDerivativeX(t2); // == 0, failure if (Math.abs(derivative) < ZERO_LIMIT) { break; } t2 -= x2 / derivative; } // Fall back to the bisection method for reliability. // bisection // http://en.wikipedia.org/wiki/Bisection_method var t1 = 1, t0 = 0; t2 = x; while (t1 > t0) { x2 = sampleCurveX(t2) - x; if (Math.abs(x2) < ZERO_LIMIT) { return t2; } if (x2 > 0) { t1 = t2; } else { t0 = t2; } t2 = (t1 + t0) / 2; } // Failure return t2; }
javascript
{ "resource": "" }
q42958
train
function (name) { return function (state) { // Write to output stream var time = new Date(); self.write(messages[name][state].replace('{pid}', self.pid[name])); self.write('=== Time: ' + time.toString()); }; }
javascript
{ "resource": "" }
q42959
ExactPath
train
function ExactPath() { /** * Uri to action::method mapping * @type {Object} */ var mapping = {}; /** * Resolve uri * @param request * @returns {*} */ this.resolve = function (request) { var uri = request.url.split('?')[0]; if (mapping[request.method] && mapping[request.method][uri]) { return decode.call(this, mapping[request.method][uri]); } return null; }; /** * Add a route mapping * @param method * @param uri * @param callback * @returns {ExactPath} */ this.addRoute = function (method, uri, callback) { method = method.toUpperCase(); if (!mapping[method]) { mapping[method] = {}; } mapping[method][uri] = callback; return this; }; /** * Add route mapping for get http method * @param uri * @param callback * @returns {ExactPath} */ this.get = function (uri, callback) { return this.addRoute('GET', uri, callback); }; /** * Add route mapping for post http method * @param uri * @param callback * @returns {ExactPath} */ this.post = function (uri, callback) { return this.addRoute('POST', uri, callback); }; /** * Add route mapping for put http method * @param uri * @param callback * @returns {ExactPath} */ this.put = function (uri, callback) { return this.addRoute('PUT', uri, callback); }; /** * Add route mapping for delete http method * @param uri * @param callback * @returns {ExactPath} */ this.delete = function (uri, callback) { return this.addRoute('DELETE', uri, callback); }; return this; /** * Decode callback * @param callback * @returns {*} */ function decode(callback) { if (typeof callback == 'function') { return callback; } else { var split = callback.split('::'); var action = split[0]; var method = split[1] || 'index'; return { action: action, method: method, arguments: [] }; } } }
javascript
{ "resource": "" }
q42960
train
function(config){ this.options = { hostname : config.url, port : 443, path : '', //override method : '', //override auth : config.user + ':' + config.passwd, headers : config.headers }; }
javascript
{ "resource": "" }
q42961
decorateWithSessionsData
train
function decorateWithSessionsData(command, session, options) { if (!session) { return; } // first apply non-transaction-specific sessions data const serverSession = session.serverSession; const inTransaction = session.inTransaction() || isTransactionCommand(command); const isRetryableWrite = options.willRetryWrite; if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) { command.txnNumber = BSON.Long.fromNumber(serverSession.txnNumber); } // now attempt to apply transaction-specific sessions data if (!inTransaction) { if (session.transaction.state !== TxnState.NO_TRANSACTION) { session.transaction.transition(TxnState.NO_TRANSACTION); } // for causal consistency if (session.supports.causalConsistency && session.operationTime) { command.readConcern = command.readConcern || {}; Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); } return; } if (options.readPreference && !options.readPreference.equals(ReadPreference.primary)) { return new MongoError( `Read preference in a transaction must be primary, not: ${options.readPreference.mode}` ); } // `autocommit` must always be false to differentiate from retryable writes command.autocommit = false; if (session.transaction.state === TxnState.STARTING_TRANSACTION) { session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS); command.startTransaction = true; const readConcern = session.transaction.options.readConcern || session.clientOptions.readConcern; if (readConcern) { command.readConcern = readConcern; } if (session.supports.causalConsistency && session.operationTime) { command.readConcern = command.readConcern || {}; Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); } } }
javascript
{ "resource": "" }
q42962
executeWrite
train
function executeWrite(pool, bson, type, opsField, ns, ops, options, callback) { if (ops.length === 0) throw new MongoError('insert must contain at least one document'); if (typeof options === 'function') { callback = options; options = {}; options = options || {}; } // Split the ns up to get db and collection const p = ns.split('.'); const d = p.shift(); // Options const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; const writeConcern = options.writeConcern; // return skeleton const writeCommand = {}; writeCommand[type] = p.join('.'); writeCommand[opsField] = ops; writeCommand.ordered = ordered; // Did we specify a write concern if (writeConcern && Object.keys(writeConcern).length > 0) { writeCommand.writeConcern = writeConcern; } // If we have collation passed in if (options.collation) { for (let i = 0; i < writeCommand[opsField].length; i++) { if (!writeCommand[opsField][i].collation) { writeCommand[opsField][i].collation = options.collation; } } } // Do we have bypassDocumentValidation set, then enable it on the write command if (options.bypassDocumentValidation === true) { writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; } // optionally decorate command with transactions data const err = decorateWithSessionsData(writeCommand, options.session, options, callback); if (err) { return callback(err, null); } // Options object const opts = { command: true }; if (typeof options.session !== 'undefined') opts.session = options.session; const queryOptions = { checkKeys: false, numberToSkip: 0, numberToReturn: 1 }; if (type === 'insert') queryOptions.checkKeys = true; if (typeof options.checkKeys === 'boolean') queryOptions.checkKeys = options.checkKeys; // Ensure we support serialization of functions if (options.serializeFunctions) queryOptions.serializeFunctions = options.serializeFunctions; // Do not serialize the undefined fields if (options.ignoreUndefined) queryOptions.ignoreUndefined = options.ignoreUndefined; try { // Create write command const cmd = new Query(bson, `${d}.$cmd`, writeCommand, queryOptions); // Execute command pool.write(cmd, opts, callback); } catch (err) { callback(err); } }
javascript
{ "resource": "" }
q42963
killCursorCallback
train
function killCursorCallback(err, result) { if (err) { if (typeof callback !== 'function') return; return callback(err); } // Result const r = result.message; // If we have a timed out query or a cursor that was killed if ((r.responseFlags & (1 << 0)) !== 0) { if (typeof callback !== 'function') return; return callback(new MongoNetworkError('cursor killed or timed out'), null); } if (!Array.isArray(r.documents) || r.documents.length === 0) { if (typeof callback !== 'function') return; return callback( new MongoError(`invalid killCursors result returned for cursor id ${cursorId}`) ); } // Return the result if (typeof callback === 'function') { callback(null, r.documents[0]); } }
javascript
{ "resource": "" }
q42964
train
function(dependencies) { var _dependencies = dependencies || {}; var _numberOfOudatedPackages = Object.keys(_dependencies).length; var _minor = semver.allMinor(dependencies, 'latest'); var _major = semver.allMajor(dependencies, 'latest'); var _patch = semver.allPatch(dependencies, 'latest`'); var _passing = ( options['up-to-dateness'].number >= _numberOfOudatedPackages && _major.passing === true && _minor.passing === true && _patch.passing === true ); return { passing: _passing, outdated: _.merge(_major.outdated, _minor.outdated, _patch.outdated) }; }
javascript
{ "resource": "" }
q42965
resolve_
train
function resolve_(element, resolve) { // if element is a fragment, it will load everything // up to child element if (element.MaterialFragment) { element.MaterialFragment.loaded.then(() => { slice.call(element.querySelectorAll(selClass)) .forEach(element => componentHandler.upgradeElement(element)); resolve(); }); } else { element.addEventListener('load', resolve, { once: true }); } }
javascript
{ "resource": "" }
q42966
hashchange_
train
function hashchange_(e) { if (counterLastMatch > 1) { counterLastMatch = 0; throw new Error(`Cannot go back to last matched hash ${e.oldURL}`); } // Look for all router3 elements in order Promise.all(slice .call(document.querySelectorAll(selClass)) .map(element => { /** * link router3 with fragment * (This process should be decoupled...) */ return new Promise(resolve => { let fragments = slice.call(element.querySelectorAll('.mdl-fragment')); if (element.classList.contains('mdl-fragment')) { resolve_(element, resolve); } else { // if there's at least one child fragment, then load all fragments // and resolve their promises Promise.all(fragments.map(fragment => { return new Promise(resolve => resolve_(fragment, resolve)); })).then(resolve); } }); }) ).then(() => { // when everything was loaded... let match = slice .call(document.querySelectorAll(selClass)) .map(element => route_(element, e && e.newURL ? e.newURL : window.location.href, lastMatch)) .find(result => result); if (match) { stateRevert = false; lastMatch = match; counterLastMatch = 0; } else { let newHash = window.location.hash || ''; if (newHash !== '') { stateRevert = true; counterLastMatch++; window.location.hash = e && e.oldURL ? e.oldURL.split('#')[1] : ''; setTimeout(() => { throw new Error(`Cannot navigate to ${newHash.slice(1)}`); }); } } }); }
javascript
{ "resource": "" }
q42967
hide_
train
function hide_(element) { if (!element.hidden) { element.hidden = true; element.style.visibility = 'hidden'; element.style.height = '0px'; element.style.width = '0px'; /** * Dispatch hide event if URL's fragment matches with a route * and router.hidden = true * * @event MaterialRouter3#hide * @type {CustomEvent} * @property {HTMLElement} router - The router that dispatches * this event */ element.dispatchEvent(new CustomEvent('hide', { detail: { router: element } })); } return true; }
javascript
{ "resource": "" }
q42968
dispatchShow_
train
function dispatchShow_(element, detail) { /** * Dispatch show event if URL's fragment matches with a route * * @event MaterialRouter3#show * @type {CustomEvent} * @property {HTMLElement} router - The router that dispatches * this event * @property {String} param1 * @property {String} param2 * @property {String} ... * @property {String} paramN - The values extracted * from the URL's fragment. These params go in order of appearance * from left to right. */ element.dispatchEvent(new CustomEvent('show', { bubbles: true, detail: detail })); }
javascript
{ "resource": "" }
q42969
unhide_
train
function unhide_(element) { if (element.hidden) { element.hidden = false; element.style.visibility = 'visible'; element.style.height = null; element.style.width = null; /** * Dispatch unhide even if URL's fragment matches with a route * and router.hidden = false * * @event MaterialRouter3#unhide * @type {CustomEvent} * @property {HTMLElement} router - The router that dispatches * this event */ element.dispatchEvent(new CustomEvent('unhide', { detail: { router: element } })); } return true; }
javascript
{ "resource": "" }
q42970
match_
train
function match_(newHash, parents, hashes) { parents.push(parents[hashes.length].parentElement.closest(selClass)); hashes.push(parents[hashes.length].getAttribute('hash')); if (parents[hashes.length]) { return match_(newHash, parents, hashes); } else { return hashes.slice(0, hashes.length).reverse().join('/'); } }
javascript
{ "resource": "" }
q42971
Client
train
function Client(identity) { if (!(this instanceof Client)) { return new Client(identity); } assert(identity instanceof Identity, 'Invalid identity supplied'); this._identity = identity; this._podhost = utils.getPodHostFromUserID(this._identity.userID); this._baseUrl = 'https://' + this._podhost; this._pubkey = this._identity._publicKeyArmored; }
javascript
{ "resource": "" }
q42972
ender
train
function ender(input) { return signal(function(next) { var pending = 0 var state = null return spawn(input, function(item) { state = item === START ? (pending = pending + 1, state) : item === END ? (pending = pending - 1, pending ? state : next(item)) : next(item) return state }) }) }
javascript
{ "resource": "" }
q42973
bulkWrite
train
function bulkWrite(coll, operations, options, callback) { // Add ignoreUndfined if (coll.s.options.ignoreUndefined) { options = Object.assign({}, options); options.ignoreUndefined = coll.s.options.ignoreUndefined; } // Create the bulk operation const bulk = options.ordered === true || options.ordered == null ? coll.initializeOrderedBulkOp(options) : coll.initializeUnorderedBulkOp(options); // Do we have a collation let collation = false; // for each op go through and add to the bulk try { for (let i = 0; i < operations.length; i++) { // Get the operation type const key = Object.keys(operations[i])[0]; // Check if we have a collation if (operations[i][key].collation) { collation = true; } // Pass to the raw bulk bulk.raw(operations[i]); } } catch (err) { return callback(err, null); } // Final options for retryable writes and write concern let finalOptions = Object.assign({}, options); finalOptions = applyRetryableWrites(finalOptions, coll.s.db); finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); const writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; const capabilities = coll.s.topology.capabilities(); // Did the user pass in a collation, check if our write server supports it if (collation && capabilities && !capabilities.commandsTakeCollation) { return callback(new MongoError('server/primary/mongos does not support collation')); } // Execute the bulk bulk.execute(writeCon, finalOptions, (err, r) => { // We have connection level error if (!r && err) { return callback(err, null); } r.insertedCount = r.nInserted; r.matchedCount = r.nMatched; r.modifiedCount = r.nModified || 0; r.deletedCount = r.nRemoved; r.upsertedCount = r.getUpsertedIds().length; r.upsertedIds = {}; r.insertedIds = {}; // Update the n r.n = r.insertedCount; // Inserted documents const inserted = r.getInsertedIds(); // Map inserted ids for (let i = 0; i < inserted.length; i++) { r.insertedIds[inserted[i].index] = inserted[i]._id; } // Upserted documents const upserted = r.getUpsertedIds(); // Map upserted ids for (let i = 0; i < upserted.length; i++) { r.upsertedIds[upserted[i].index] = upserted[i]._id; } // Return the results callback(null, r); }); }
javascript
{ "resource": "" }
q42974
rename
train
function rename(coll, newName, options, callback) { const Collection = require('../collection'); // Check the collection name checkCollectionName(newName); // Build the command const renameCollection = `${coll.s.dbName}.${coll.s.name}`; const toCollection = `${coll.s.dbName}.${newName}`; const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false; const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget }; // Decorate command with writeConcern if supported applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options); // Execute against admin executeDbAdminCommand(coll.s.db.admin().s.db, cmd, options, (err, doc) => { if (err) return handleCallback(callback, err, null); // We have an error if (doc.errmsg) return handleCallback(callback, toError(doc), null); try { return handleCallback( callback, null, new Collection( coll.s.db, coll.s.topology, coll.s.dbName, newName, coll.s.pkFactory, coll.s.options ) ); } catch (err) { return handleCallback(callback, toError(err), null); } }); }
javascript
{ "resource": "" }
q42975
toPositiveInt
train
function toPositiveInt(num, _default) { if (isNumeric(num)) { num = parseInt(num, 10); } else { return _default; } if (num < 0) { return _default; } return num; }
javascript
{ "resource": "" }
q42976
validateIODActions
train
function validateIODActions(IOD, IODOpts) { // Validate IOD action schema var actionErr = validateAction(IOD, IODOpts.action, IODOpts.params) if (actionErr) return actionErr // Validate IOD action required inputs var inputErr = validateActionInputs(IOD, IODOpts) if (inputErr) return inputErr // Validate IOD action parameter pairs var pairErr = validateParamPairs(IOD, IODOpts) if (pairErr) return pairErr }
javascript
{ "resource": "" }
q42977
validateIODJob
train
function validateIODJob(IOD, IODOpts) { var job = IODOpts.job var errors = [] _.each(job.actions, function(action) { // Validate every IOD action in job var err = validateAction(IOD, action.name, action.params) if (err) return errors.push({ action: action.name, error: err }) // Validate every IOD action required inputs in job var inputErr = validateActionInputs(IOD, { action: action.name, params: action.params }) if (inputErr) return errors.push({ action: action.name, error: inputErr }) // Validate every IOD action parameter pairs in job var pairErr = validateParamPairs(IOD, { action: action.name, params: action.params }) if (pairErr) return errors.push({ action: action.name, error: pairErr }) }) if (errors.length) return errors }
javascript
{ "resource": "" }
q42978
create
train
function create(options, cb) { options.force = (options.force) ? options.force : false; options.preserve = (options.preserve) ? options.preserve : true; options.password = getPwHash(options.password); console.log('Gernerating directories with folling options:\n', options, '\n'); if(options.test) {return;} //create directory if(options.force || !fs.existsSync(options.dest)) { wrench.mkdirSyncRecursive(options.dest); wrench.copyDirSyncRecursive(options.src, options.dest, { preserve: options.preserve }); } if(options.files.length) { _.each(options.files, function(file) { fs.exists(path.join(options.dest,options.pwfile), function(exists) { if(!exists || options.force || file.force) { fs.writeFile(path.join(options.dest,strReplace(file.name, options)), strReplace(file.data, options), function(err){ if(err) {throw err;} }); } }); }); } //Search and replace replace(options.dest, { filters: ['index\.php$', '\.htaccess'] , type: 'replace' , values: [{ user: options.user , root: options.root , project: options.project , title: options.title , userDir: options.userDir , pwfile: options.pwfile }] }, function(err, data) { if(cb) { cb(err, data); } }); }
javascript
{ "resource": "" }
q42979
replace
train
function replace(root, options, callback) { analyser.readDir(root, options, function(err, files) { files = _.flatten(files); _.each(files, function(file){ fs.readFile(file, 'UTF-8', function(err, data) { if(err) {throw err;} var i, value; for(i=0; i<options.values.length; i++) { value = options.values[i]; if(value === Object(value)) { for(var key in value) { if(value.hasOwnProperty(key)) { data = data.replace(new RegExp('{{'+key+'}}','g'), value[key]); } } } fs.writeFile(file, data); } }); }); if(callback) { callback(err, files); } }); }
javascript
{ "resource": "" }
q42980
abs_path
train
function abs_path(file, cwd) { if(!file || file.length === 0) { return null; } function get_path(p) { var dir = grunt.file.isPathAbsolute(p) ? "" : (cwd || "."); return path.join(dir, p); } if(_.isArray(file)) { return _.map(file, function(p) { return get_path(p); }); } else { return get_path(file); } }
javascript
{ "resource": "" }
q42981
format
train
function format(ms) { if (ms == d) return Math.round(ms / d) + ' day'; if (ms > d) return Math.round(ms / d) + ' days'; if (ms == h) return Math.round(ms / h) + ' hour'; if (ms > h) return Math.round(ms / h) + ' hours'; if (ms == m) return Math.round(ms / m) + ' minute'; if (ms > m) return Math.round(ms / m) + ' minutes'; if (ms == s) return Math.round(ms / s) + ' second'; if (ms > s) return Math.round(ms / s) + ' seconds'; return ms + ' ms'; }
javascript
{ "resource": "" }
q42982
getPartials
train
function getPartials(file, sourcePath, templates, customPartialName, callback) { const { partials } = templates; if (file.meta.customLayout === undefined) { async.nextTick(callback, null, partials); return; } const customLayoutPath = path.join( sourcePath, path.resolve(path.sep, file.meta.filePath.dir, file.meta.customLayout) ); read(customLayoutPath, ReadMode.UTF8, (error, data) => { if (error) { console.error(`${file.path}: Could not load the custom layout`); async.nextTick(callback, error); return; } const customPartials = { [customPartialName]: data }; async.nextTick(callback, null, Object.assign({}, partials, customPartials)); }); }
javascript
{ "resource": "" }
q42983
render
train
function render(file, layout, context, partials, callback) { try { const data = mustache.render(layout, context, partials); async.nextTick(callback, null, data); } catch (error) { console.error(`${file.path}: Could not render the layout`); async.nextTick(callback, error); } }
javascript
{ "resource": "" }
q42984
wrapFunctions
train
function wrapFunctions(fns, file, files) { return Object.entries(fns) .reduce((obj1, [groupName, group]) => { return Object.assign(obj1, { [groupName]: Object.entries(group) .reduce((obj2, [fnName, fn]) => { return Object.assign(obj2, { [fnName]: fn(file, files) }); }, {}) }); }, {}); }
javascript
{ "resource": "" }
q42985
train
function (fullPath, autoDefine) { if (!this.instances[fullPath]) { this.instances[fullPath] = DevFixturesModule.create({ fullPath: fullPath, autoDefine: Boolean(autoDefine) }); } return this.instances[fullPath]; }
javascript
{ "resource": "" }
q42986
train
function( obj ) { var clone; // Array. if ( obj && ( obj instanceof Array ) ) { clone = []; for ( var i = 0; i < obj.length; i++ ) clone[ i ] = CKEDITOR.tools.clone( obj[ i ] ); return clone; } // "Static" types. if ( obj === null || ( typeof( obj ) != 'object' ) || ( obj instanceof String ) || ( obj instanceof Number ) || ( obj instanceof Boolean ) || ( obj instanceof Date ) || ( obj instanceof RegExp ) ) return obj; // DOM objects and window. if ( obj.nodeType || obj.window === obj ) return obj; // Objects. clone = new obj.constructor(); for ( var propertyName in obj ) { var property = obj[ propertyName ]; clone[ propertyName ] = CKEDITOR.tools.clone( property ); } return clone; }
javascript
{ "resource": "" }
q42987
train
function( str, keepCase ) { return str.charAt( 0 ).toUpperCase() + ( keepCase ? str.slice( 1 ) : str.slice( 1 ).toLowerCase() ); }
javascript
{ "resource": "" }
q42988
train
function( property, value, asString ) { if ( asString ) return cssVendorPrefix + property + ':' + value + ';' + property + ':' + value; var ret = {}; ret[ property ] = value; ret[ cssVendorPrefix + property ] = value; return ret; }
javascript
{ "resource": "" }
q42989
train
function( originalFunction, functionBuilder ) { var newFn = functionBuilder( originalFunction ); newFn.prototype = originalFunction.prototype; return newFn; }
javascript
{ "resource": "" }
q42990
train
function( styleText, nativeNormalize ) { var props = [], name, parsedProps = CKEDITOR.tools.parseCssText( styleText, true, nativeNormalize ); for ( name in parsedProps ) props.push( name + ':' + parsedProps[ name ] ); props.sort(); return props.length ? ( props.join( ';' ) + ';' ) : ''; }
javascript
{ "resource": "" }
q42991
train
function( styleText, normalize, nativeNormalize ) { var retval = {}; if ( nativeNormalize ) { // Injects the style in a temporary span object, so the browser parses it, // retrieving its final format. var temp = new CKEDITOR.dom.element( 'span' ); temp.setAttribute( 'style', styleText ); styleText = CKEDITOR.tools.convertRgbToHex( temp.getAttribute( 'style' ) || '' ); } // IE will leave a single semicolon when failed to parse the style text. (#3891) if ( !styleText || styleText == ';' ) return retval; styleText.replace( /&quot;/g, '"' ).replace( /\s*([^:;\s]+)\s*:\s*([^;]+)\s*(?=;|$)/g, function( match, name, value ) { if ( normalize ) { name = name.toLowerCase(); // Normalize font-family property, ignore quotes and being case insensitive. (#7322) // http://www.w3.org/TR/css3-fonts/#font-family-the-font-family-property if ( name == 'font-family' ) value = value.toLowerCase().replace( /["']/g, '' ).replace( /\s*,\s*/g, ',' ); value = CKEDITOR.tools.trim( value ); } retval[ name ] = value; } ); return retval; }
javascript
{ "resource": "" }
q42992
train
function( styles, sort ) { var name, stylesArr = []; for ( name in styles ) stylesArr.push( name + ':' + styles[ name ] ); if ( sort ) stylesArr.sort(); return stylesArr.join( '; ' ); }
javascript
{ "resource": "" }
q42993
train
function( left, right, onlyLeft ) { var name; if ( !left && !right ) return true; if ( !left || !right ) return false; for ( name in left ) { if ( left[ name ] != right[ name ] ) return false; } if ( !onlyLeft ) { for ( name in right ) { if ( left[ name ] != right[ name ] ) return false; } } return true; }
javascript
{ "resource": "" }
q42994
train
function( arr, fillWith ) { var obj = {}; if ( arguments.length == 1 ) fillWith = true; for ( var i = 0, l = arr.length; i < l; ++i ) obj[ arr[ i ] ] = fillWith; return obj; }
javascript
{ "resource": "" }
q42995
train
function() { var domain; while ( 1 ) { try { // Try to access the parent document. It throws // "access denied" if restricted by the "Same Origin" policy. domain = window.parent.document.domain; break; } catch ( e ) { // Calculate the value to set to document.domain. domain = domain ? // If it is not the first pass, strip one part of the // name. E.g. "test.example.com" => "example.com" domain.replace( /.+?(?:\.|$)/, '' ) : // In the first pass, we'll handle the // "document.domain = document.domain" case. document.domain; // Stop here if there is no more domain parts available. if ( !domain ) break; document.domain = domain; } } return !!domain; }
javascript
{ "resource": "" }
q42996
train
function( arr, regexp ) { for ( var i = 0, l = arr.length; i < l; ++i ) { if ( arr[ i ].match( regexp ) ) return true; } return false; }
javascript
{ "resource": "" }
q42997
loadDocument
train
function loadDocument (directory, callback) { var docPath = path.resolve(directory, '_design.js') fs.stat(docPath, function (err, stat) { if (err) return callback.call(null, err); if (stat.isFile()) { var document = require(docPath); return callback.call(null, null, document); } return callback.call(null, new Error('No _design.js file found!')); }); }
javascript
{ "resource": "" }
q42998
loadAttachments
train
function loadAttachments (doc, directory, callback) { doc._attachments = doc._attachments || {}; glob('**/*', { cwd: directory }, function (err, files) { async.each(files, function (file, done) { if (file.indexOf('_') === 0) return done(); fs.stat(path.join(directory, file), function (err, stat) { if (err) return done(err); if (stat.isFile()) { fs.readFile(path.join(directory, file), function (err, data) { if (err) return done(err); var ext = file.split('.').pop() doc._attachments[file] = {} doc._attachments[file]['content_type'] = lookup(ext); doc._attachments[file]['data'] = data.toString('base64'); done(); }); } else { done(); } }); }, function (err) { callback.call(null, err, doc); }); }); }
javascript
{ "resource": "" }
q42999
push
train
function push (directory, uri, callback) { var db = nano(uri); loadDocument(directory, function (err, doc) { if (err) return callback.call(null, err); loadAttachments(doc, directory, function (err, doc) { if (err) return callback.call(null, err); db.get(doc._id, function (err, body) { if (err && err.reason !== "missing") return callback.call(null, err); if (body && body._rev) { doc._rev = body._rev; } db.insert(doc, doc._id, callback); }); }); }); }
javascript
{ "resource": "" }