_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q35300
train
function( editor, buttonName, buttonLabel, commandName, command, menugroup, menuOrder ) { editor.addCommand( commandName, command ); // If the "menu" plugin is loaded, register the menu item. editor.addMenuItem( commandName, { label : buttonLabel, command : commandName, group : menugroup, order : menuOrder }); }
javascript
{ "resource": "" }
q35301
handlePermissionUpdate
train
function handlePermissionUpdate() { permissionArea.find("form").submit(function (e) { e.preventDefault(); //console.log(e); var form = e.currentTarget; appendFormFields(form); Rocket.Util.submitFormAsync(form, function (responseData) { //console.log(responseData); if (responseData && responseData.status && responseData.status == "success") { location.reload(); } }); }); }
javascript
{ "resource": "" }
q35302
addManifest
train
function addManifest(file, options) { file = file || '/app.manifest'; var stream = new Transform({objectMode: true}); var domains = {}; var hostProtocols = {}; stream._transform = function (page, _, callback) { if (!(options && options.justManifests)) { if (page.statusCode !== 404 || url.resolve(page.url, file) !== page.url) { if (page.statusCode === 200 && page.headers['content-type'] && page.headers['content-type'].indexOf('text/html') !== -1 && options && options.addLinks) { var body = page.body.toString(); var link = '<link href="' + file + '" rel="manifest"/>'; page.body = new Buffer(body.replace(/<\/head>/, link + '</head>')); } this.push(page); } } if (page.statusCode === 200) { var host = url.parse(page.url).host; var protocol = hostProtocols[host] || (hostProtocols[host] = url.parse(page.url).protocol); var domain = protocol + '//' + host; domain = domains[domain] || (domains[domain] = {hash: crypto.createHash('sha512'), urls: []}); domain.hash.update(page.statusCode + ' - ' + page.url); domain.hash.update(page.body || ''); domain.urls.push(page.url); } callback(null); }; stream._flush = function (callback) { Object.keys(domains).forEach(function (domain) { stream.push({ statusCode: 200, url: url.resolve(domain, file), headers: {}, body: new Buffer('CACHE MANIFEST\n\n# hash: ' + domains[domain].hash.digest('base64') + '\n\n' + domains[domain].urls.map(function (u) { return url.parse(u).pathname; }).join('\n') + '\n'), dependencies: domains[domain].urls }); }); callback(); }; return stream; }
javascript
{ "resource": "" }
q35303
report
train
function report(){ if(responses < 1) return; var dt = new Date - starttime; console.log( '%s invokes per second, avg request time: %s ms, worst: %s ms, best: %s ms, invokes without response in queue: %s', (responses/dt*1000).toFixed(2), (totaltime/responses).toFixed(2), maxtime, mintime, Object.keys(esb.responseCallbacks).length ); responses = 0; totaltime = 0; maxtime = 0; mintime = 100000; }
javascript
{ "resource": "" }
q35304
train
function (path) { 'use strict'; path = fs.realpathSync(path); var config = require(path); this.setData(config, false); return this; }
javascript
{ "resource": "" }
q35305
train
function (path) { 'use strict'; path = fs.realpathSync(path); var updateConf = require(path); this.setData(updateConf, true); return this; }
javascript
{ "resource": "" }
q35306
train
function (key) { 'use strict'; var value = conf[key]; if (!isStr(key)) { throw new Error(confKeyStrMsg, 'config-manager'); } if (key.indexOf('.') !== -1) { value = getNestedValue(conf, key); } if (isObj(value)) { if (isExtensionObj(value)) { value = applyExtension.call(this, value); } else { value = openReferences.call(this, value); value = JSON.parse(JSON.stringify(value)); } } return value; }
javascript
{ "resource": "" }
q35307
train
function (key, value) { 'use strict'; var obj; if (!isStr(key)) { throw new Error(confKeyStrMsg, 'config-manager'); } if (key.indexOf('.') === -1) { conf[key] = value; } else { obj = getLastNodeKey(key, conf); obj.node[obj.key] = value; } return this; }
javascript
{ "resource": "" }
q35308
formatStream
train
function formatStream(options) { if (!_.isObject(options)) { options = {}; } var statsOptions = options.verbose === true ? _.defaults(options, DEFAULT_VERBOSE_STATS_OPTIONS) : _.defaults(options, DEFAULT_STATS_OPTIONS); if (!gutil.colors.supportsColor) { statsOptions.colors = false; } return through.obj(function(chunk, enc, cb) { var stats = chunk[processStats.STATS_DATA_FIELD_NAME], isStats = chunk[processStats.STATS_FLAG_FIELD_NAME]; if (isStats) { var filename = path.resolve(chunk.path); gutil.log(MESSAGE, gutil.colors.magenta(tildify(filename))); gutil.log('\n' + stats.toString(statsOptions)); } cb(null, chunk); }); }
javascript
{ "resource": "" }
q35309
parseString
train
function parseString(input) { var stripped = input.substring(1, input.length - 1); return stripped.replace(/\\(\w|\\)/gi, function(_, b) { switch (b) { case '\\r': return '\r'; case '\\n': return '\n'; case '\\t': return '\t'; case '\\0': return '\0'; case '\\\\': return '\\'; default: throw new SyntaxError('Invalid escape code "' + b + '"'); } }); }
javascript
{ "resource": "" }
q35310
parseSwitchType
train
function parseSwitchType(lex) { var start = lex.accept('switchtype'); if (!start) { return null; } var expr = parseExpression(lex); lex.assert('{'); var cases = []; var end; do { let c = parseSwitchTypeCase(lex); cases.push(c); } while (!(end = lex.accept('}'))); return new nodes.SwitchTypeNode(expr, cases, start.start, end.end); }
javascript
{ "resource": "" }
q35311
parseSwitchTypeCase
train
function parseSwitchTypeCase(lex) { var start = lex.assert('case'); var type = parseType(lex); lex.assert('{'); var body = parseStatements(lex, '}', false); var end = lex.assert('}'); return new nodes.SwitchTypeCaseNode(type, body, start.start, end.end); }
javascript
{ "resource": "" }
q35312
parseStatement
train
function parseStatement(lex, isRoot = false) { return parseFunctionDeclaration(lex) || isRoot && parseOperatorStatement(lex) || isRoot && parseObjectDeclaration(lex) || parseIf(lex) || parseReturn(lex) || isRoot && parseExport(lex) || isRoot && parseImport(lex) || parseSwitchType(lex) || parseWhile(lex) || parseDoWhile(lex) || parseFor(lex) || parseBreak(lex) || parseContinue(lex) || parseExpressionBase(lex); }
javascript
{ "resource": "" }
q35313
parseStatements
train
function parseStatements(lex, endTokens, isRoot) { endTokens = Array.isArray(endTokens) ? endTokens : [endTokens]; var statements = []; var temp = lex.peek(); while (endTokens.indexOf(temp) === -1 && (temp.type && endTokens.indexOf(temp.type) === -1)) { var statement = parseStatement(lex, isRoot); if (!statement) { throw new Error('Invalid statement'); } temp = lex.peek(); statements.push(statement); } return statements; }
javascript
{ "resource": "" }
q35314
requestAsync
train
function requestAsync(resource, opts = {}) { const settings = { followRedirect: true, encoding: null, rejectUnauthorized: false }; if (opts.user && opts.pass) { settings.headers = {Authorization: 'Basic ' + token(opts.user, opts.pass)}; } return new Bluebird((resolve, reject) => { // Handle protocol-relative urls resource = url.resolve('http://te.st', resource); request(resource, settings, (err, resp, body) => { let msg; if (err) { debug('Url failed:', err.message || err); return reject(err); } if (resp.statusCode !== 200) { msg = 'Wrong status code ' + resp.statusCode + ' for ' + resource; debug(msg); return reject(new Error(msg)); } const mimeType = result(resp, 'headers.content-type') || mime.getType(resource); resolve({ contents: body, path: resource, mime: mimeType }); }); }); }
javascript
{ "resource": "" }
q35315
readAsync
train
function readAsync(resource) { return fs.readFile(resource).then(body => { const mimeType = mime.getType(resource); debug('Fetched:', resource); return Bluebird.resolve({ contents: body, path: resource, mime: mimeType }); }); }
javascript
{ "resource": "" }
q35316
checkMissingDir
train
function checkMissingDir(destinationFile) { var filePath = path.dirname(destinationFile); var pathAbsolute = path.isAbsolute(filePath); var directories = filePath.split(path.sep); return transversePath(directories); }
javascript
{ "resource": "" }
q35317
generateCache
train
function generateCache(filePath) { var id = generateIdFromFilePath(filePath); Debug._l(id); fs.readFile(filePath, 'utf8', function (err, data) { if (err) { Debug._l("err: " + err); return; } fs.stat(filePath, function (err, stat) { setCache(id, {modified:stat.mtime, content:data }); }); }); }
javascript
{ "resource": "" }
q35318
train
function (options) { if (!options) { throw Error("Ajax options missing"); } var that = this, util = Rocket.Util; options.success = util.ajaxResponse(options.callback); util.ajax(options); }
javascript
{ "resource": "" }
q35319
train
function (msg, nodeId, ns, isShow) { ns = ns || Rocket.Plugin.currentPlugin.namespace; var node = $("#" + ns + "_" + nodeId), msgSpan = node.find("span.message"); isShow ? node.removeClass("hide") && node.css("display", "block") : node.addClass("hide"); if (node.data("autohide") == true && !node.hasClass("hide")) { node.delay(4000).fadeOut(1000, function () { $(this).addClass("hide"); $(msgSpan).html(""); }); } //attach close listener to hide the flash message $(node.find(".close")).click(function () { node.addClass('hide').css("display", "none"); $(msgSpan).html(""); }); if (msg) msgSpan.html(msg); }
javascript
{ "resource": "" }
q35320
train
function (msg, nodeId, ns) { nodeId = nodeId || "errorFlash"; this.flashMessage(msg, nodeId, ns, true); }
javascript
{ "resource": "" }
q35321
ErrorRenderer
train
function ErrorRenderer(err, req, res) { PageRenderer.call(this, req, res); Object.defineProperties(this, { err: { value: err || new Error() } }); req.attrs.isErrorPage = true; }
javascript
{ "resource": "" }
q35322
Strategy
train
function Strategy (options, verify) { if (typeof options === 'function') { verify = options options = {} } else { if (options && options.log) { log = options.log } } if (!verify) { throw new Error('apikey authentication strategy requires a verify function') } passport.Strategy.call(this) this._apiKeyHeader = options.apiKeyHeader || 'api_key' this.name = 'apikey' this._verify = verify this._passReqToCallback = true }
javascript
{ "resource": "" }
q35323
CString
train
function CString(value, written, cond) { this.value = value || ''; this.written = written || false; this.cond = cond || false; }
javascript
{ "resource": "" }
q35324
train
function( event ) { var keystroke = event && event.data.getKey(), isModifierKey = keystroke in modifierKeyCodes, isEditingKey = keystroke in editingKeyCodes, wasEditingKey = this.lastKeystroke in editingKeyCodes, sameAsLastEditingKey = isEditingKey && keystroke == this.lastKeystroke, // Keystrokes which navigation through contents. isReset = keystroke in navigationKeyCodes, wasReset = this.lastKeystroke in navigationKeyCodes, // Keystrokes which just introduce new contents. isContent = ( !isEditingKey && !isReset ), // Create undo snap for every different modifier key. modifierSnapshot = ( isEditingKey && !sameAsLastEditingKey ), // Create undo snap on the following cases: // 1. Just start to type . // 2. Typing some content after a modifier. // 3. Typing some content after make a visible selection. startedTyping = !( isModifierKey || this.typing ) || ( isContent && ( wasEditingKey || wasReset ) ); if ( startedTyping || modifierSnapshot ) { var beforeTypeImage = new Image( this.editor ); // Use setTimeout, so we give the necessary time to the // browser to insert the character into the DOM. CKEDITOR.tools.setTimeout( function() { var currentSnapshot = this.editor.getSnapshot(); // In IE, we need to remove the expando attributes. if ( CKEDITOR.env.ie ) currentSnapshot = currentSnapshot.replace( /\s+data-cke-expando=".*?"/g, '' ); if ( beforeTypeImage.contents != currentSnapshot ) { // It's safe to now indicate typing state. this.typing = true; // This's a special save, with specified snapshot // and without auto 'fireChange'. if ( !this.save( false, beforeTypeImage, false ) ) // Drop future snapshots. this.snapshots.splice( this.index + 1, this.snapshots.length - this.index - 1 ); this.hasUndo = true; this.hasRedo = false; this.typesCount = 1; this.modifiersCount = 1; this.onChange(); } }, 0, this ); } this.lastKeystroke = keystroke; // Create undo snap after typed too much (over 25 times). if ( isEditingKey ) { this.typesCount = 0; this.modifiersCount++; if ( this.modifiersCount > 25 ) { this.save( false, null, false ); this.modifiersCount = 1; } } else if ( !isReset ) { this.modifiersCount = 0; this.typesCount++; if ( this.typesCount > 25 ) { this.save( false, null, false ); this.typesCount = 1; } } }
javascript
{ "resource": "" }
q35325
train
function( onContentOnly, image, autoFireChange ) { var snapshots = this.snapshots; // Get a content image. if ( !image ) image = new Image( this.editor ); // Do nothing if it was not possible to retrieve an image. if ( image.contents === false ) return false; // Check if this is a duplicate. In such case, do nothing. if ( this.currentImage && image.equals( this.currentImage, onContentOnly ) ) return false; // Drop future snapshots. snapshots.splice( this.index + 1, snapshots.length - this.index - 1 ); // If we have reached the limit, remove the oldest one. if ( snapshots.length == this.limit ) snapshots.shift(); // Add the new image, updating the current index. this.index = snapshots.push( image ) - 1; this.currentImage = image; if ( autoFireChange !== false ) this.fireChange(); return true; }
javascript
{ "resource": "" }
q35326
train
function( isUndo ) { var snapshots = this.snapshots, currentImage = this.currentImage, image, i; if ( currentImage ) { if ( isUndo ) { for ( i = this.index - 1 ; i >= 0 ; i-- ) { image = snapshots[ i ]; if ( !currentImage.equals( image, true ) ) { image.index = i; return image; } } } else { for ( i = this.index + 1 ; i < snapshots.length ; i++ ) { image = snapshots[ i ]; if ( !currentImage.equals( image, true ) ) { image.index = i; return image; } } } } return null; }
javascript
{ "resource": "" }
q35327
train
function() { if ( this.undoable() ) { this.save( true ); var image = this.getNextImage( true ); if ( image ) return this.restoreImage( image ), true; } return false; }
javascript
{ "resource": "" }
q35328
train
function() { if ( this.redoable() ) { // Try to save. If no changes have been made, the redo stack // will not change, so it will still be redoable. this.save( true ); // If instead we had changes, we can't redo anymore. if ( this.redoable() ) { var image = this.getNextImage( false ); if ( image ) return this.restoreImage( image ), true; } } return false; }
javascript
{ "resource": "" }
q35329
create
train
function create(type, constructor) { return function projection() { var p = constructor(); p.type = type; p.path = geoPath().projection(p); p.copy = p.copy || function() { var c = projection(); projectionProperties.forEach(function(prop) { if (p.hasOwnProperty(prop)) c[prop](p[prop]()); }); c.path.pointRadius(p.path.pointRadius()); return c; }; return p; }; }
javascript
{ "resource": "" }
q35330
createObbFromRenderableShape
train
function createObbFromRenderableShape(params, physicsJob) { const halfRangeX = params.scale[0] / 2; const halfRangeY = params.scale[1] / 2; const halfRangeZ = params.scale[2] / 2; return new Obb(halfRangeX, halfRangeY, halfRangeZ, params.isStationary, physicsJob); }
javascript
{ "resource": "" }
q35331
createSphereFromRenderableShape
train
function createSphereFromRenderableShape(params, physicsJob) { const radius = params.radius || vec3.length(params.scale) / Math.sqrt(3); return new Sphere(0, 0, 0, radius, params.isStationary, physicsJob); }
javascript
{ "resource": "" }
q35332
createCapsuleFromRenderableShape
train
function createCapsuleFromRenderableShape(params, physicsJob) { const scale = params.scale; const capsuleEndPointsDistance = params.capsuleEndPointsDistance; const isStationary = params.isStationary; let radius = params.radius; let halfDistance; // There are two modes: either we use scale, or we use radius and capsuleEndPointsDistance. if (typeof radius === 'number' && typeof capsuleEndPointsDistance === 'number') { halfDistance = capsuleEndPointsDistance / 2; } else { const copy = vec3.clone(scale); copy.sort(); const length = copy[2]; radius = (copy[0] + copy[1]) / 2; halfDistance = length / 2 - radius; } const orientation = quat.create(); if (scale[0] > scale[1]) { if (scale[0] > scale[2]) { vec3.rotateY(orientation, orientation, _geometry.HALF_PI); } else { // Do nothing; the capsule defaults to being aligned with the z-axis. } } else { if (scale[1] > scale[2]) { vec3.rotateX(orientation, orientation, -_geometry.HALF_PI); } else { // Do nothing; the capsule defaults to being aligned with the z-axis. } } const capsule = new Capsule(halfDistance, radius, isStationary, physicsJob); capsule.orientation = orientation; return capsule; }
javascript
{ "resource": "" }
q35333
train
function( node, index ) { isNaN( index ) && ( index = this.children.length ); var previous = index > 0 ? this.children[ index - 1 ] : null; if ( previous ) { // If the block to be appended is following text, trim spaces at // the right of it. if ( node._.isBlockLike && previous.type == CKEDITOR.NODE_TEXT ) { previous.value = CKEDITOR.tools.rtrim( previous.value ); // If we have completely cleared the previous node. if ( previous.value.length === 0 ) { // Remove it from the list and add the node again. this.children.pop(); this.add( node ); return; } } previous.next = node; } node.previous = previous; node.parent = this; this.children.splice( index, 0, node ); this._.hasInlineStarted = node.type == CKEDITOR.NODE_TEXT || ( node.type == CKEDITOR.NODE_ELEMENT && !node._.isBlockLike ); }
javascript
{ "resource": "" }
q35334
train
function( writer, filter ) { var isChildrenFiltered; this.filterChildren = function() { var writer = new CKEDITOR.htmlParser.basicWriter(); this.writeChildrenHtml.call( this, writer, filter, true ); var html = writer.getHtml(); this.children = new CKEDITOR.htmlParser.fragment.fromHtml( html ).children; isChildrenFiltered = 1; }; // Filtering the root fragment before anything else. !this.name && filter && filter.onFragment( this ); this.writeChildrenHtml( writer, isChildrenFiltered ? null : filter ); }
javascript
{ "resource": "" }
q35335
train
function(constructorFn, args) { var newConstructorFn = function () { constructorFn.apply(this, args); }; newConstructorFn.prototype = constructorFn.prototype; return new newConstructorFn(); }
javascript
{ "resource": "" }
q35336
getMasterPillarRow
train
function getMasterPillarRow( table ) { var $rows = table.$.rows, maxCells = 0, cellsCount, $elected, $tr; for ( var i = 0, len = $rows.length ; i < len; i++ ) { $tr = $rows[ i ]; cellsCount = $tr.cells.length; if ( cellsCount > maxCells ) { maxCells = cellsCount; $elected = $tr; } } return $elected; }
javascript
{ "resource": "" }
q35337
catchErrors
train
function catchErrors() { // don't use an arrow function, we need the `this` instance! return plumber(function(err) { if (!err.plugin) { err.plugin = 'gulp-task-maker' } showError(err) // keep watch tasks running if (this && typeof this.emit === 'function') { this.emit('end') } }) }
javascript
{ "resource": "" }
q35338
dirToListItems
train
function dirToListItems( list ) { var dir = list.getDirection(); if ( dir ) { for ( var i = 0, children = list.getChildren(), child; child = children.getItem( i ), i < children.count(); i++ ) { if ( child.type == CKEDITOR.NODE_ELEMENT && child.is( 'li' ) && !child.getDirection() ) child.setAttribute( 'dir', dir ); } list.removeAttribute( 'dir' ); } }
javascript
{ "resource": "" }
q35339
Rorschach
train
function Rorschach(connectionString, options) { EventEmitter.call(this); options = options || {}; var retryPolicy = options.retryPolicy; if (retryPolicy instanceof RetryPolicy) { this.retryPolicy = retryPolicy; } else { this.retryPolicy = new RetryPolicy(retryPolicy); } // Initial state this.state = ConnectionState.LOST; initZooKeeper(this, connectionString, options.zookeeper); }
javascript
{ "resource": "" }
q35340
initZooKeeper
train
function initZooKeeper(rorschach, connectionString, options) { var error; var zk = zookeeper.createClient(connectionString, options); rorschach.zk = zk; zk.connect(); zk.on('connected', onconnected); zk.on('expired', setError); zk.on('authenticationFailed', setError); zk.on('disconnected', ondisconnected); zk.on('state', handleStateChange); function onconnected() { error = false; } function setError() { error = true; } function ondisconnected() { if (rorschach.closed) { return; } if (error) { zk.removeListener('connected', onconnected); zk.removeListener('disconnected', ondisconnected); zk.removeListener('expired', setError); zk.removeListener('authenticationFailed', setError); zk.removeListener('state', handleStateChange); zk.close(); initZooKeeper(rorschach, connectionString, options); } } function handleStateChange(state) { var newState; if (state === State.SYNC_CONNECTED) { if (!rorschach.ready) { rorschach.ready = true; rorschach.emit('connected'); newState = ConnectionState.CONNECTED; } else { newState = ConnectionState.RECONNECTED; } } else if (state === State.CONNECTED_READ_ONLY) { newState = ConnectionState.READ_ONLY; } else if (state === State.EXPIRED) { newState = ConnectionState.LOST; } else if (state === State.DISCONNECTED) { newState = ConnectionState.SUSPENDED; } else { // AUTH_FAILED and SASL_AUTHENTICATED are not handled, yep. return; } rorschach.state = newState; rorschach.emit('connectionStateChanged', newState); } }
javascript
{ "resource": "" }
q35341
updateComponents
train
function updateComponents (address, node, state, diff, bindings, renderResult, relativeAddress, stateCallers, opts) { // TODO pull these out to top level const updateRecurse = ([ d, s ], k) => { // TODO in updateRecurse functions where k can be null, there must be a // nicer way to organize things with fewer null checks const component = k !== null ? node.component : node const newAddress = k !== null ? addressWith(address, k) : address const newRelativeAddress = k !== null ? addressWith(relativeAddress, k) : relativeAddress const b = k !== null ? get(bindings, k) : bindings // Get binding el const lastRenderedEl = get(b, 'data') const el = renderResult !== null ? renderResult[makeBindingKey(newRelativeAddress)] : lastRenderedEl // Update the component. If DESTROY, then there will not be a binding. const res = updateEl(newAddress, component, s, d.data, lastRenderedEl, el, stateCallers, opts) // Fall back on old bindings. const nextRenderResult = res.renderResult !== null ? res.renderResult : null // Update children const children = updateComponents(newAddress, component.model, s, d.children, get(b, 'children'), nextRenderResult, [], stateCallers, opts) return tagType(NODE, { data: el, children }) } // TODO pull these out to top level const recurse = (n, k) => { return updateComponents(addressWith(address, k), n, get(state, k), diff[k], get(bindings, k), renderResult, addressWith(relativeAddress, k), stateCallers, opts) } return match(node, match_updateComponents, null, diff, state, updateRecurse, recurse) }
javascript
{ "resource": "" }
q35342
treeGet
train
function treeGet (address, tree) { return address.reduce((accum, val) => { return checkType(NODE, accum) ? accum.children[val] : accum[val] }, tree) }
javascript
{ "resource": "" }
q35343
treeSet
train
function treeSet (address, tree, value) { if (address.length === 0) { return value } else { const [ k, rest ] = head(address) return (typeof k === 'string' ? { ...tree, [k]: treeSet(rest, treeGet([ k ], tree), value) } : [ ...tree.slice(0, k), treeSet(rest, treeGet([ k ], tree), value), ...tree.slice(k + 1) ]) } }
javascript
{ "resource": "" }
q35344
treeSetMutable
train
function treeSetMutable (address, tree, value) { if (address.length === 0) { return value } else { const [ rest, last ] = tail(address) const parent = treeGet(rest, tree) if (checkType(NODE, parent)) { parent.children[last] = value } else { parent[last] = value } return tree } }
javascript
{ "resource": "" }
q35345
diffWithModel
train
function diffWithModel (modelNode, state, lastState, address, triggeringAddress) { return match(modelNode, match_diffWithModel, null, modelNode, state, lastState, address, triggeringAddress) }
javascript
{ "resource": "" }
q35346
singleOrAll
train
function singleOrAll (modelNode, address, minTreeAr) { const getMin = indices => { if (indices.length === 0) { // If all elements in the array are null, return null. return null } else if (nonNullIndices.signals.length === 1) { // If there is a single value, return that tree, with an updated address. return { minSignals: { diff: minTreeAr.map(a => a.minSignals.diff), address, modelNode, }, minUpdate: { diff: minTreeAr.map(a => a.minUpdate.diff), address, modelNode, }, } } else { // Otherwise, return full trees from this level. return { minSignals: { diff: minTreeAr.map(a => a.minSignals.diff), address, modelNode, }, minUpdate: { diff: minTreeAr.map(a => a.minUpdate.diff), address, modelNode, }, } } } // Get the indices where the signal and update trees are not null. const nonNullIndices = minTreeAr.reduce((accum, val, i) => { return { signals: val.minSignals !== null ? [ ...accum.signals, i ]: accum.signals, update: val.minUpdate !== null ? [ ...accum.update, i ]: accum.update, } }, { signals: [], update: [] }) // For each set of indices, test the diffs with these tests to get a minimum // tree. const minSignals = getMin(nonNullIndices.signals) const minUpdate = getMin(nonNullIndices.update) return { minSignals, minUpdate } }
javascript
{ "resource": "" }
q35347
makeSignalsAPI
train
function makeSignalsAPI (signalNames, isCollection) { return fromPairs(signalNames.map(name => { return [ name, makeOneSignalAPI(isCollection) ] })) }
javascript
{ "resource": "" }
q35348
runSignalSetup
train
function runSignalSetup (component, address, stateCallers) { const signalsAPI = makeSignalsAPI(component.signalNames, false) const childSignalsAPI = makeChildSignalsAPI(component.model) const reducers = patchReducersWithState(address, component, stateCallers.callReducer) const signals = patchSignals(address, component, stateCallers.callSignal) const methods = patchMethods(address, component, stateCallers.callMethod, reducers, signals) // cannot call signalSetup any earlier because it needs a reference to // `methods`, which must know the address component.signalSetup({ methods, reducers, signals: signalsAPI, childSignals: childSignalsAPI, }) return { signalsAPI, childSignalsAPI } }
javascript
{ "resource": "" }
q35349
makeCallSignal
train
function makeCallSignal (signals, opts) { return (address, signalName, arg) => { if (opts.verbose) { console.log('Called signal ' + signalName + ' at [' + address.join(', ') + '].') } signals.get(address).data.signals[signalName].call(arg) } }
javascript
{ "resource": "" }
q35350
keyBy
train
function keyBy (arr, key) { var obj = {} arr.map(x => obj[x[key]] = x) return obj }
javascript
{ "resource": "" }
q35351
isText
train
function isText (o) { return (o && typeof o === 'object' && o !== null && o.nodeType === 3 && typeof o.nodeName === 'string') }
javascript
{ "resource": "" }
q35352
flattenElementsAr
train
function flattenElementsAr (ar) { return ar.reduce((acc, el) => { return isArray(el) ? [ ...acc, ...el ] : [ ...acc, el ] }, []).filter(notNull) // null means ignore }
javascript
{ "resource": "" }
q35353
redirect
train
function redirect(e) { if (e && e.preventDefault) e.preventDefault(); // // Assume that the value in the $control_input is uptodate. If not get the // value directly through the constructor. When the selectize is still // loading results the `getValue()` will return an empty value. This is why // we do a double value check. // var selectize = select[0].selectize , value = selectize.$control_input.val() || selectize.getValue(); if (!value) return; window.location = '/package/'+ value; }
javascript
{ "resource": "" }
q35354
load
train
function load(query, callback) { if (!query.length) return callback(); pagelet.complete(query, function complete(err, results) { if (err) return callback(); callback(results); }); }
javascript
{ "resource": "" }
q35355
render
train
function render(item, escape) { return [ '<div class="completed">', '<strong class="name">'+ escape(item.name) +'</strong>', 'string' === typeof item.desc ? '<span class="description">'+ escape(item.desc) +'</span>' : '', '</div>' ].join(''); }
javascript
{ "resource": "" }
q35356
customLog
train
function customLog(message) { const trimmed = message.trim() const limit = trimmed.indexOf('\n') if (limit === -1) { fancyLog(trimmed) } else { const title = trimmed.slice(0, limit).trim() const details = trimmed.slice(limit).trim() fancyLog(`${title}${('\n' + details).replace(/\n/g, '\n ')}`) } }
javascript
{ "resource": "" }
q35357
toUniqueStrings
train
function toUniqueStrings(input) { const list = (Array.isArray(input) ? input : [input]) .map(el => (typeof el === 'string' ? el.trim() : null)) .filter(Boolean) return list.length > 1 ? Array.from(new Set(list)) : list }
javascript
{ "resource": "" }
q35358
removeSelectedOptions
train
function removeSelectedOptions( combo ) { combo = getSelect( combo ); // Save the selected index var iSelectedIndex = getSelectedIndex( combo ); // Remove all selected options. for ( var i = combo.getChildren().count() - 1 ; i >= 0 ; i-- ) { if ( combo.getChild( i ).$.selected ) combo.getChild( i ).remove(); } // Reset the selection based on the original selected index. setSelectedIndex( combo, iSelectedIndex ); }
javascript
{ "resource": "" }
q35359
modifyOption
train
function modifyOption( combo, index, title, value ) { combo = getSelect( combo ); if ( index < 0 ) return false; var child = combo.getChild( index ); child.setText( title ); child.setValue( value ); return child; }
javascript
{ "resource": "" }
q35360
dir2TreeStr
train
function dir2TreeStr(){ argD = Type.isBoolean(argD) ? "./" : trimAndDelQuotes(argD); let dirJson,djOpt; try{ djOpt = { // preChars:{ // directory: ":open_file_folder: ", // file:":page_facing_up: " // }, exclude:{ outExcludeDir: true //将过滤掉的文件夹输出 }, extChars:{ directory: " /" }, maxDepth: argM }; dirJson = dir2Json(argD, djOpt); }catch(e3){ errorOut("Gen Json via dir failed: " + e3.toString()); dirJson = false; } if(!dirJson){ if(dirJson===null){ warningOut("The directory '" + argD + "' is empty! (exclude-filter: .git|.svn|.idea|node_modules|bower_components )"); } }else if(Type.isString(dirJson)){ warningOut("The directory '" + argD + "' is '" + dirJson + "'"); }else{ // 间距配置和上面不一样 s = Type.isNaN(s) ? 2 : s; v = Type.isNaN(v) ? 0 : v; jsonName = (djOpt.preChars && djOpt.preChars.directory || "") + argD.replace(/\\/g,"/"); outputVal = false; _doMain(dirJson,true); } }
javascript
{ "resource": "" }
q35361
VertexIterator
train
function VertexIterator(graph, startFrom) { if (graph === undefined) { throw new Error('Graph is required by VertexIterator'); } this._graph = graph; this._startFrom = startFrom; this._currentIndex = 0; this._allNodes = []; this._initialized = false; this._current = undefined; }
javascript
{ "resource": "" }
q35362
CacheStore
train
function CacheStore(options) { if (!options.id) { throw new IdNotDefinedError(); } var storeType, _cache; function parseKey(key) { return key.replace(/[^a-z0-9]/gi, '_').replace(/^-+/, '').replace(/-+$/, '').toLowerCase(); } /** * Returns Cache Store object * @returns {Object} */ this.getCacheStore = function () { return _cache; }; /** * Method initiates cache store depends on type * @param type {String} cache store type * @returns {CacheStore} */ this._setStoreType = function (type) { storeType = type; var ttl = options.expires || DEFAULT_EXPIRATION_TIME; options.max = options.max || 0; //makes lru cache to store infinite no of items switch (type) { case STORE_TYPE_MEMORY: _cache = CacheManager.caching({store: STORE_TYPE_MEMORY, max: options.max, ttl: ttl}); break; case STORE_TYPE_REDIS: _cache = CacheManager.caching({store: RedisStore, db: options.db, ttl: ttl, host: options.host, port: options.port, id: options.id }); break; default : throw new InvalidCacheStoreTypeError(type); } //exposing delete method alias of _del _cache.delete = _cache.del; return this; }; //setting public functions /** * Gets cache item * @param key {String} Key to retrieve cache item * @param next {Function} callback. parameters are err, value */ this.get = function (key, next) { _cache.get(parseKey(key), next); }; /** * Sets cache item in cache. * @param key {String} Key to retrieve cache item * @param value {String} Value to save cache item * @param next {Function} callback. parameters are err */ this.set = function (key, value, next) { _cache.set(parseKey(key), value, next); }; /** * Delete from cache * @param key {String} Key to retrieve cache item * @param next {Function} callback. parameters are err */ this.delete = function (key, next) { _cache.del(parseKey(key), next); }; /** * Wraps a function in cache, the first time the function is run, * its results are stored in cache so subsequent calls retrieve from cache * instead of calling the function. * * @example * * var key = 'user_' + user_id; * cache.wrap(key, function(cb) { * User.get(user_id, cb); * }, function(err, user) { * console.log(user); * }); * * @param key {String} Key to retrieve cache item * @param wrapFn * @param next {Function} callback. parameters are err, value */ this.wrap = function (key, wrapFn, next) { _cache.wrap(parseKey(key), wrapFn, next); }; /** * Flushes the current cache store * @param next {Function} callback. parameters are err, success */ this.reset = function (next) { _cache.reset(next); }; /** * Gets all keys associated with this cache store * @param next {Function} callback. parameters are err, keys */ this.keys = function (next) { _cache.keys(next); }; }
javascript
{ "resource": "" }
q35363
train
function(options) { "use strict"; stream.Transform.call(this, options); options = options || {}; this.probability = options.probability || 0; this.deviation = Math.abs(options.deviation || 0); this.whiteList = options.whiteList || []; this.blackList = options.blackList || []; this.func = options.func; }
javascript
{ "resource": "" }
q35364
train
function(fileSrc, fileDst, probability, deviation, mode) { "use strict"; var rstream = fs.createReadStream(fileSrc); var woptions = mode ? { 'mode' : mode } : {}; var wstream = fs.createWriteStream(fileDst, woptions); var gstream = new GlitchedStream({ 'probability' : probability, 'deviation' : deviation }); rstream.pipe(gstream).pipe(wstream); }
javascript
{ "resource": "" }
q35365
CInt
train
function CInt(base, offset, isSet) { this.base = base || 0; this.offset = offset || 0; this.isSet = isSet || false; }
javascript
{ "resource": "" }
q35366
VText
train
function VText(text, config) { this.virtual = true; extend(this, config); // Non-overridable this.text = [].concat(text); this.textOnly = true; this.simple = true; }
javascript
{ "resource": "" }
q35367
appendColorRow
train
function appendColorRow( rangeA, rangeB ) { for ( var i = rangeA ; i < rangeA + 3 ; i++ ) { var row = table.$.insertRow( -1 ); for ( var j = rangeB ; j < rangeB + 3 ; j++ ) { for ( var n = 0 ; n < 6 ; n++ ) { appendColorCell( row, '#' + aColors[j] + aColors[n] + aColors[i] ); } } } }
javascript
{ "resource": "" }
q35368
CEntity
train
function CEntity(indexes, properties, states) { CArray.call(this, indexes, properties); this.states = {} || states; this.uid = 0; }
javascript
{ "resource": "" }
q35369
attachMenu
train
function attachMenu(item) { var menuType = item.find('a').hasClass(FOLDER_TYPE) ? "folderMenu" : "itemMenu"; item.contextMenu({ menu:menuType }, function (action, el, pos) { switch (action) { case ADD_SUBFOLDER_MENU_COMMAND: var parentFolderId = el.find('a').attr('id'); addFolder(parentFolderId); break; case DOWNLOAD_MENU_COMMAND: download(el.find('a').attr('id')); break; case RENAME_MENU_COMMAND: rename(el.find('a').attr('id'), true); break; case DELETE_MENU_COMMAND: var link = el.find('a'); remove(link.attr('id'), link.hasClass(FOLDER_TYPE) ? FOLDER_TYPE : ""); break; default: alert("Todo: apply action '" + action + "' to node " + el); } }); }
javascript
{ "resource": "" }
q35370
injectStyle
train
function injectStyle(obj) { if (!obj) return '' var selectors = Object.keys(obj) var styles = selectors.map(function(key) { var selector = obj[key] var style = inlineStyle(selector) var inline = key.concat('{').concat(style).concat('}') return inline }) var results = styles.join('') insertCss(results) return results }
javascript
{ "resource": "" }
q35371
fetchWithRetry
train
function fetchWithRetry(url, options) { async function fetchWrapper() { const response = await fetch(url, options); // don't retry if status is 4xx if (response.status >= 400 && response.status < 500) { const contentType = response.headers.get('content-type'); if (contentType && contentType.includes('application/json')) { const body = await response.json(); throw new p_retry_1.default.AbortError(body.message); } else { throw new p_retry_1.default.AbortError(response.statusText); } } return response; } return p_retry_1.default(fetchWrapper, { retries: RETRY_COUNT }); }
javascript
{ "resource": "" }
q35372
hydrateDates
train
function hydrateDates(body) { /** * Hydrates a string date to a Date object. Mutates input. * @param item object potentially containing a meta object */ function hydrateMeta(item) { const meta = item.meta; if (meta && meta.created) { // parse ISO-8601 string to Date meta.created = new Date(meta.created); } } if (Array.isArray(body.data)) { // paginated response for (const item of body.data) { hydrateMeta(item); } } else { // object response hydrateMeta(body); } return body; }
javascript
{ "resource": "" }
q35373
hydrateMeta
train
function hydrateMeta(item) { const meta = item.meta; if (meta && meta.created) { // parse ISO-8601 string to Date meta.created = new Date(meta.created); } }
javascript
{ "resource": "" }
q35374
LeaderElection
train
function LeaderElection(client, path, id) { EventEmitter.call(this); /** * Ref. to client. * * @type {Rorschach} */ this.client = client; /** * ZooKeeper path where participants' nodes exist. * * @type {String} */ this.path = path; /** * Id of participant. It's kept in node. * * @type {String} */ this.id = id; /** * Leadership state * * @type {Boolean} */ this.isLeader = false; /** * Initial state. * * @type {State} */ this.state = State.LATENT; }
javascript
{ "resource": "" }
q35375
handleStateChange
train
function handleStateChange(election, state) { if (state === ConnectionState.RECONNECTED) { reset(election, afterReset); } else if (state === ConnectionState.SUSPENDED || state === ConnectionState.LOST) { setLeadership(election, false); } function afterReset(err) { if (err) { election.emit('error', err); setLeadership(election, false); } } }
javascript
{ "resource": "" }
q35376
fileUploaded
train
function fileUploaded( error, response ) { this.debug( 'File Uploaded' ); console.log( require( 'util' ).inspect( error || response, { showHidden: false, colors: true, depth: 4 } ) ); }
javascript
{ "resource": "" }
q35377
train
function( writer, filter ) { var text = this.value; if ( filter && !( text = filter.onText( text, this ) ) ) return; writer.text( text ); }
javascript
{ "resource": "" }
q35378
checkCircular
train
function checkCircular(obj){ let isCcl = false; let cclKeysArr = []; travelJson(obj,function(k,v,kp,ts,cpl,cd,isCircular){ if(isCircular){ isCcl = true; cclKeysArr.push({ keyPath: kp, circularTo: v.slice(11,-1), key: k, value: v }); } },"ROOT",true); return { isCircular: isCcl, circularProps: cclKeysArr }; }
javascript
{ "resource": "" }
q35379
BufferView
train
function BufferView(buffer, byteOffset, byteLength) { if (typeof byteOffset === "undefined") byteOffset = 0; if (typeof byteLength === "undefined") byteLength = buffer.length; this._buffer = byteOffset === 0 && byteLength === buffer.length ? buffer : buffer.slice(byteOffset, byteLength); }
javascript
{ "resource": "" }
q35380
train
function (message, data) { var datastr = data === undefined ? "no-data" : inspect(data); logfn(format(" [EMIT] %s %s", pad(message), datastr)); EEProto.emit.apply(this, arguments); }
javascript
{ "resource": "" }
q35381
train
function( evaluator ) { var next = this.$, retval; do { next = next.nextSibling; retval = next && new CKEDITOR.dom.node( next ); } while ( retval && evaluator && !evaluator( retval ) ) return retval; }
javascript
{ "resource": "" }
q35382
train
function( reference, includeSelf ) { var $ = this.$, name; if ( !includeSelf ) $ = $.parentNode; while ( $ ) { if ( $.nodeName && ( name = $.nodeName.toLowerCase(), ( typeof reference == 'string' ? name == reference : name in reference ) ) ) return new CKEDITOR.dom.node( $ ); $ = $.parentNode; } return null; }
javascript
{ "resource": "" }
q35383
train
function( preserveChildren ) { var $ = this.$; var parent = $.parentNode; if ( parent ) { if ( preserveChildren ) { // Move all children before the node. for ( var child ; ( child = $.firstChild ) ; ) { parent.insertBefore( $.removeChild( child ), $ ); } } parent.removeChild( $ ); } return this; }
javascript
{ "resource": "" }
q35384
train
function() { if ( cssIsLoaded && jsIsLoaded ) { // Mark the part as loaded. part._isLoaded = 1; // Call all pending callbacks. for ( var i = 0 ; i < pending.length ; i++ ) { if ( pending[ i ] ) pending[ i ](); } } }
javascript
{ "resource": "" }
q35385
train
function( skinName, skinDefinition ) { loaded[ skinName ] = skinDefinition; skinDefinition.skinPath = paths[ skinName ] || ( paths[ skinName ] = CKEDITOR.getUrl( '_source/' + // @Packager.RemoveLine 'skins/' + skinName + '/' ) ); }
javascript
{ "resource": "" }
q35386
train
function( editor, skinPart, callback ) { var skinName = editor.skinName, skinPath = editor.skinPath; if ( loaded[ skinName ] ) loadPart( editor, skinName, skinPart, callback ); else { paths[ skinName ] = skinPath; CKEDITOR.scriptLoader.load( CKEDITOR.getUrl( skinPath + 'skin.js' ), function() { loadPart( editor, skinName, skinPart, callback ); }); } }
javascript
{ "resource": "" }
q35387
forOwnDeep
train
function forOwnDeep(object, callback, prefix) { prefix = prefix ? prefix + '.' : ''; _.forOwn(object, function(value, key) { if (_.isString(value)) { callback(value, prefix + key); } else { forOwnDeep(value, callback, prefix + key); } }); }
javascript
{ "resource": "" }
q35388
Lock
train
function Lock(client, basePath, lockName, lockDriver) { if (lockName instanceof LockDriver) { lockDriver = lockName; lockName = null; } if (!lockName) { lockName = Lock.LOCK_NAME; } if (!lockDriver) { lockDriver = new LockDriver(); } /** * Keep ref to client as all the low-level operations are done through it. * * @type {Rorschach} */ this.client = client; /** * Base path should be valid ZooKeeper path. * * @type {String} */ this.basePath = basePath; /** * Node name. * * @type {String} */ this.lockName = lockName; /** * Lock driver. * * @type {LockDriver} */ this.driver = lockDriver; /** * Sequence node name (set when acquired). * * @type {String} */ this.lockPath; /** * Number of max leases. * * @type {Number} */ this.maxLeases = 1; /** * Number of acquires. * * @type {Number} */ this.acquires = 0; }
javascript
{ "resource": "" }
q35389
attemptLock
train
function attemptLock(lock, timeout, callback) { var lockPath; var sequenceNodeName; var timerId = null; var start = Date.now(); createNode(lock, afterCreate); function afterCreate(err, nodePath) { if (err) { return exit(err); } lockPath = nodePath; sequenceNodeName = nodePath.substring(lock.basePath.length + 1); getSortedChildren(lock, afterGetChildren); } function afterGetChildren(err, list) { if (exited()) { return; } if (err) { return exit(err); } var result = lock.driver.getsTheLock(list, sequenceNodeName, lock.maxLeases); if (result.error) { return exit(result.error); } else if (result.hasLock) { return exit(null, lockPath); } var watchPath = utils.join(lock.basePath, result.watchPath); lock.client .getData() .usingWatcher(watcher) .forPath(watchPath, afterGetData); setTimer(); } function afterGetData(err) { if (exited() || !err) { return; } if (err.getCode() === Exception.NO_NODE) { getSortedChildren(lock, afterGetChildren); } else { exit(err); } } function watcher(event) { if (!exited() && event.getType() === Event.NODE_DELETED) { getSortedChildren(lock, afterGetChildren); } } function setTimer() { if (timerId) { return; } if (timeout >= 0) { timeout -= Date.now() - start; if (timeout <= 0) { return sayBye(); } timerId = setTimeout(sayBye, timeout); } } function sayBye() { exit(new TimeoutError('Could not acquire lock %s', lock.basePath)); } function exit(err, path) { if (timerId) { clearTimeout(timerId); timerId = -1; } var cb = callback; callback = null; if (!err) { cb(null, path); } else if (lockPath) { deleteNode(lock, lockPath, proceed); } else { cb(err); } function proceed(deleteError) { if (deleteError) { cb(deleteError); } else { cb(err); } } } function exited() { return !callback; } }
javascript
{ "resource": "" }
q35390
createNode
train
function createNode(lock, callback) { var nodePath = utils.join(lock.basePath, lock.lockName); var client = lock.client; client .create() .creatingParentsIfNeeded() .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) .forPath(nodePath, callback); }
javascript
{ "resource": "" }
q35391
deleteNode
train
function deleteNode(lock, lockPath, callback) { lock.client .delete() .guaranteed() .forPath(lockPath, callback); }
javascript
{ "resource": "" }
q35392
dupBuffer
train
function dupBuffer(buf){ var cloned = new Buffer(buf.length); buf.copy(cloned); return cloned; }
javascript
{ "resource": "" }
q35393
compare
train
function compare(buf1, buf2){ if (buf1.length !== buf2.length) return buf1.length - buf2.length; for (var i = 0; i < buf1.length; i++) if (buf1[i] !== buf2[i]) return buf1[i] - buf2[i]; return 0; }
javascript
{ "resource": "" }
q35394
strongify
train
function strongify(o) { /** * Cloning object. */ var params = _.clone(o); /** * Returns all object data. * * @return {object} * @api public */ params.all = function() { return params = _.omit(params, ['all', 'only', 'except', 'require', 'merge']); } /** * Returns only listed object keys. * * @return {object} * @api public */ params.only = function() { return params = _.pick(params, _.flatten(arguments)); } /** * Returns all object keys except those listed. * * @return {object} * @api public */ params.except = function() { params = _.omit(params, _.flatten(arguments)); return params = params.all(params); } /** * Returns a sub-object or throws an error if the requested key does not * exist. This is usefull when working with nested data (e.g. user[name]). * * @return {object} * @api public */ params.require = function(key) { if (Object.keys(params).indexOf(key) == -1) throw new Error('param `'+key+'` required'); if (typeof params[key] != 'object') throw new Error('param `'+key+'` is not an object'); return params = strongify(params[key]); } /** * Returns params with merged data. * * @return {object} * @api public */ params.merge = function(data) { return params = _.merge(params, data); } /** * Return object. */ return params; }
javascript
{ "resource": "" }
q35395
saveFileChanges
train
function saveFileChanges(themeId, folderName, fileName, text) { io({ url:getURL("save") + "/" + themeId + "/" + folderName + "/" + fileName, data:{ content:encodeURI(text) }, callback:function (isSuccess, message, response) { if (!isSuccess) { showErrorMsg(message); } } }); }
javascript
{ "resource": "" }
q35396
initAceEditor
train
function initAceEditor(themeId, folderName, fileName, text, mode) { hideImageHolder(); $("#" + editorId).show(); var doc = new Document(text); var session = new EditSession(doc, "ace/mode/" + mode); session.setUndoManager(new UndoManager()); editor.setSession(session); //bind change event for text changes in opened file and save them. doc.on('change', function (e) { // e.type, etc console.log(e); saveFileChanges(themeId, folderName, fileName, doc.getValue()); }); }
javascript
{ "resource": "" }
q35397
openFile
train
function openFile(themeId, folderName, fileName) { if (themeId && folderName && fileName) { //if image then display it if (folderName === "images") { showImage(themeId, folderName, fileName); return; } var options = { url:getURL("show") + "/" + themeId + "/" + folderName + "/" + fileName, success:function (response) { if (response.status === "error") { util.showErrorFlash(response.message); } else { // if js, css or jade file then show in editor var mode = "scss"; if (fileName.indexOf(".js") > -1) { mode = "javascript"; } else if (fileName.indexOf(".css") > -1) { mode = "css"; } initAceEditor(themeId, folderName, fileName, response, mode); } } }; Rocket.ajax(options); } }
javascript
{ "resource": "" }
q35398
renderThemeTree
train
function renderThemeTree(themeId, fileList, themeName) { var getTreeNodes = function (arr) { var ret = []; _.each(arr, function (fileName) { ret.push({title:fileName}); }); return ret; }; var css = {title:validTitleName[0], isFolder:true, children:getTreeNodes(fileList["css"])}, js = {title:validTitleName[1], isFolder:true, children:getTreeNodes(fileList["js"])}, images = {title:validTitleName[2], isFolder:true, children:getTreeNodes(fileList["images"])}, tmpl = {title:validTitleName[3], isFolder:true, children:getTreeNodes(fileList["tmpl"])}, children = [css, images, js, tmpl]; tree = treeObj.dynatree({ onActivate:function (node) { var data = node.data; if (!data.isFolder) { openFile(themeId, node.parent.data.title, data.title); } else { hideEditor(); hideImageHolder(); } }, children:{title:themeName, children:children, isFolder:true, expand:true} } ); $(tree).dynatree("getTree").reload(); }
javascript
{ "resource": "" }
q35399
train
function (workingDirectory) { var gitPath = getClosestGitPath(workingDirectory); if (!gitPath) { throw new Error('git-hooks must be run inside a git repository'); } var hooksPath = path.resolve(gitPath, HOOKS_DIRNAME); var pathToGitHooks = path.join(path.relative(hooksPath, __dirname), 'git-hooks'); if (isWin32) { pathToGitHooks = pathToGitHooks.replace(/\\/g, '\\\\'); } if (fsHelpers.exists(hooksOldPath)) { throw new Error('git-hooks already installed'); } if (fsHelpers.exists(hooksPath)) { fs.renameSync(hooksPath, hooksOldPath); } var hookTemplate = fs.readFileSync(__dirname + '/' + HOOKS_TEMPLATE_FILE_NAME); var pathToGitHooks = path.relative(hooksPath, __dirname); // Fix non-POSIX (Windows) separators pathToGitHooks = pathToGitHooks.replace(new RegExp(path.sep.replace(/\\/g, '\\$&'), 'g'), '/'); var hook = util.format(hookTemplate.toString(), pathToGitHooks); fsHelpers.makeDir(hooksPath); HOOKS.forEach(function (hookName) { var hookPath = path.resolve(hooksPath, hookName); try { fs.writeFileSync(hookPath, hook, {mode: '0777'}); } catch (e) { // node 0.8 fallback fs.writeFileSync(hookPath, hook, 'utf8'); fs.chmodSync(hookPath, '0777'); } }); }
javascript
{ "resource": "" }