_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q10600
Columns
train
function Columns(props) { // require and bind methods //---------------------------------------------------------- [ 'bindState' , 'solve' ].forEach(method => this.constructor.prototype[method] = require(`./methods/${method}`) ) // bind props (immutable) and state (mutable) //---------------------------------------------------------- this.props = props this.bindState(1) // find solution state //---------------------------------------------------------- this.solve() }
javascript
{ "resource": "" }
q10601
train
function(str, maxLength, where) { if (!_.isString(str)) { return str; } var strLength = str.length; if (strLength <= maxLength) { return str; } // limit the length of the series name by dropping characters and inserting an ELLIPSIS where specified switch(where) { case 'start': str = ELLIPSIS + str.substr(strLength - maxLength - 1); break; case 'end': str = str.substr(0, Math.floor(maxLength) - 1) + ELLIPSIS; break; default: str = str.substr(0, Math.floor(maxLength/2) - 1) + ELLIPSIS + str.substr(-1 * (Math.floor(maxLength/2) + 1)); } return str; }
javascript
{ "resource": "" }
q10602
processContents
train
function processContents( contentDir, contentRoot, submenuFile, contentStock, menuStock, references, language, renderer ) { var typeName = 'Content'; // Read directory items. var items = fs.readdirSync( path.join( process.cwd(), contentDir ) ); items.forEach( function ( item ) { // Get full path of item. var itemPath = path.join( contentDir, item ); // Get item info. var stats = fs.statSync( path.join( process.cwd(), itemPath ) ); if (stats.isDirectory()) { // Determine content path. var directoryPath = contentRoot + '/' + item; // Create menu item. var directoryNode = MenuBuilder.buildSubMenu( menuStock, path.join( itemPath, submenuFile ), directoryPath ); // Read subdirectory. processContents( itemPath, directoryPath, submenuFile, contentStock, directoryNode ? directoryNode.children : menuStock, references, language, renderer ); } else if (stats.isFile()) { var ext = path.extname( item ); var basename = path.basename( item, ext ); var isMarkdown = true; switch (ext) { case '.html': isMarkdown = false; case '.md': // Read the content file. var content = getContent( itemPath, isMarkdown ? "markdown" : 'html' ); // Set content path. content.path = contentRoot + '/' + basename; // Read content definition. var definition = getDefinition( content ); // Contains menu info? if (definition.order || definition.text) // Create menu item. MenuBuilder.createMenuItem( menuStock, definition, content.path, false ); // Generate HTML from markdown text. if (isMarkdown) content.html = marked( content.html + '\n' + references.get( language ), { renderer: renderer } ); // Omit menu separator. if (definition.text !== '---') // Store content. contentStock.add( content, definition ); logger.fileProcessed( typeName, itemPath ); break; default: if (item !== submenuFile) logger.fileSkipped( typeName, itemPath ); break; } } } ); }
javascript
{ "resource": "" }
q10603
toState
train
function toState (preset) { if (preset) { const norm = (preset.replace(/[^012345678]/g, "") + "000000000").slice(0, 9) const gains = norm.split("").map((n) => Math.abs(+n / 8)) return { bank: { gains } } } }
javascript
{ "resource": "" }
q10604
train
function (name, extension, engine) { // add to storage this[name] = engine.render || engine; enginesByExtension[extension] = engine; return this; }
javascript
{ "resource": "" }
q10605
train
function (name, options, cb) { var engine = enginesByExtension[this.ext], that = this, // queue stack = [], ctx = { name : name, options : options, cb : cb }; this.engines = engines; this.thru = function (name, _name, _options, _cb) { var engine = engines[name]; if (!engine) { return cb(Error('Unknown engine ' + name)); } this.ext = engine.extension; engine.call(this, _name || ctx.name, _options || ctx.options, _cb || ctx.cb); }; options.forceLoad = options.hasOwnProperty('forceLoad') ? options.forceLoad : !expressBem.envLoadCache; options.forceExec = options.hasOwnProperty('forceExec') ? options.forceExec : !expressBem.envExecCache; if (!middlewares.length) { return engine.call(this, ctx.name, ctx.options, ctx.cb); } // async fn queue middlewares.forEach(function (mw) { if (!mw.engine /* || shouldUseMiddlewareFor(mw.engine)*/) { stack.push(mw.fn); } }); // put engine as last call stack.push(function (ctx) { engine.call(this, ctx.name, ctx.options, ctx.cb); }); function next () { var fn = stack.shift(); fn.call(that, ctx, next); } process.nextTick(next); return this; }
javascript
{ "resource": "" }
q10606
addListener
train
function addListener(uid) { var addedListener = false; if(typeof(dashboardListeners[uid]) === 'undefined') { dashboardListeners[uid] = { 'startTime': new Date(), 'numIterations': 0, 'uid': uid, 'numStarts': 1, }; addedListener = true; } else { // Don't add the listener. dashboardListeners[uid].numStarts += 1; } return addedListener; }
javascript
{ "resource": "" }
q10607
removeListener
train
function removeListener(uid) { var removedListener = false; if(typeof(dashboardListeners[uid]) !== 'undefined') { dashboardListeners[uid] = undefined; delete dashboardListeners[uid]; removedListener = true; } return removedListener; }
javascript
{ "resource": "" }
q10608
dataCollectorHandler
train
function dataCollectorHandler(data) { // debugDDC('New data', data['FIO0']); var diffObj = _.diff(data, self.dataCache); // console.log('Data Difference - diff', diffObj); // Clean the object to get rid of empty results. diffObj = _.pickBy(diffObj, function(value, key) { return Object.keys(value).length > 0; }); var numKeys = Object.keys(data); var numNewKeys = Object.keys(diffObj); // console.log('Num Keys for new data', numKeys, numNewKeys); // console.log('Data Difference - pickBy', diffObj); self.dataCache = data; self.emit(device_events.DASHBOARD_DATA_UPDATE, diffObj); }
javascript
{ "resource": "" }
q10609
innerStart
train
function innerStart (bundle) { var defered = q.defer(); // Device Type is either T4, T5, or T7 var deviceType = self.savedAttributes.deviceTypeName; // Save the created data collector object dataCollector = new dashboard_data_collector.create(deviceType); // Listen to only the next 'data' event emitted by the dataCollector. dataCollector.once('data', function(data) { debugDStart('dev_cur-dash_ops: First bit of data!'); // Listen to future data. dataCollector.on('data', dataCollectorHandler); // Save the data to the data cache. self.dataCache = data; bundle.data = data; // Declare the innerStart function to be finished. defered.resolve(bundle); }); // Start the data collector. dataCollector.start(self); return defered.promise; }
javascript
{ "resource": "" }
q10610
train
function(k, i) { var rval; if(typeof(k) === 'undefined') { rval = frag.query; } else { rval = frag.query[k]; if(rval && typeof(i) !== 'undefined') { rval = rval[i]; } } return rval; }
javascript
{ "resource": "" }
q10611
_expandKey
train
function _expandKey(key, decrypt) { // copy the key's words to initialize the key schedule var w = key.slice(0); /* RotWord() will rotate a word, moving the first byte to the last byte's position (shifting the other bytes left). We will be getting the value of Rcon at i / Nk. 'i' will iterate from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will increase by 1. We use a counter iNk to keep track of this. */ // go through the rounds expanding the key var temp, iNk = 1; var Nk = w.length; var Nr1 = Nk + 6 + 1; var end = Nb * Nr1; for(var i = Nk; i < end; ++i) { temp = w[i - 1]; if(i % Nk === 0) { // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk] temp = sbox[temp >>> 16 & 255] << 24 ^ sbox[temp >>> 8 & 255] << 16 ^ sbox[temp & 255] << 8 ^ sbox[temp >>> 24] ^ (rcon[iNk] << 24); iNk++; } else if(Nk > 6 && (i % Nk === 4)) { // temp = SubWord(temp) temp = sbox[temp >>> 24] << 24 ^ sbox[temp >>> 16 & 255] << 16 ^ sbox[temp >>> 8 & 255] << 8 ^ sbox[temp & 255]; } w[i] = w[i - Nk] ^ temp; } /* When we are updating a cipher block we always use the code path for encryption whether we are decrypting or not (to shorten code and simplify the generation of look up tables). However, because there are differences in the decryption algorithm, other than just swapping in different look up tables, we must transform our key schedule to account for these changes: 1. The decryption algorithm gets its key rounds in reverse order. 2. The decryption algorithm adds the round key before mixing columns instead of afterwards. We don't need to modify our key schedule to handle the first case, we can just traverse the key schedule in reverse order when decrypting. The second case requires a little work. The tables we built for performing rounds will take an input and then perform SubBytes() and MixColumns() or, for the decrypt version, InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires us to AddRoundKey() before InvMixColumns(). This means we'll need to apply some transformations to the round key to inverse-mix its columns so they'll be correct for moving AddRoundKey() to after the state has had its columns inverse-mixed. To inverse-mix the columns of the state when we're decrypting we use a lookup table that will apply InvSubBytes() and InvMixColumns() at the same time. However, the round key's bytes are not inverse-substituted in the decryption algorithm. To get around this problem, we can first substitute the bytes in the round key so that when we apply the transformation via the InvSubBytes()+InvMixColumns() table, it will undo our substitution leaving us with the original value that we want -- and then inverse-mix that value. This change will correctly alter our key schedule so that we can XOR each round key with our already transformed decryption state. This allows us to use the same code path as the encryption algorithm. We make one more change to the decryption key. Since the decryption algorithm runs in reverse from the encryption algorithm, we reverse the order of the round keys to avoid having to iterate over the key schedule backwards when running the encryption algorithm later in decryption mode. In addition to reversing the order of the round keys, we also swap each round key's 2nd and 4th rows. See the comments section where rounds are performed for more details about why this is done. These changes are done inline with the other substitution described above. */ if(decrypt) { var tmp; var m0 = imix[0]; var m1 = imix[1]; var m2 = imix[2]; var m3 = imix[3]; var wnew = w.slice(0); end = w.length; for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) { // do not sub the first or last round key (round keys are Nb // words) as no column mixing is performed before they are added, // but do change the key order if(i === 0 || i === (end - Nb)) { wnew[i] = w[wi]; wnew[i + 1] = w[wi + 3]; wnew[i + 2] = w[wi + 2]; wnew[i + 3] = w[wi + 1]; } else { // substitute each round key byte because the inverse-mix // table will inverse-substitute it (effectively cancel the // substitution because round key bytes aren't sub'd in // decryption mode) and swap indexes 3 and 1 for(var n = 0; n < Nb; ++n) { tmp = w[wi + n]; wnew[i + (3&-n)] = m0[sbox[tmp >>> 24]] ^ m1[sbox[tmp >>> 16 & 255]] ^ m2[sbox[tmp >>> 8 & 255]] ^ m3[sbox[tmp & 255]]; } } } w = wnew; } return w; }
javascript
{ "resource": "" }
q10612
_update
train
function _update(s, w, bytes) { // consume 512 bit (64 byte) chunks var t, a, b, c, d, f, r, i; var len = bytes.length(); while(len >= 64) { // initialize hash value for this chunk a = s.h0; b = s.h1; c = s.h2; d = s.h3; // round 1 for(i = 0; i < 16; ++i) { w[i] = bytes.getInt32Le(); f = d ^ (b & (c ^ d)); t = (a + f + _k[i] + w[i]); r = _r[i]; a = d; d = c; c = b; b += (t << r) | (t >>> (32 - r)); } // round 2 for(; i < 32; ++i) { f = c ^ (d & (b ^ c)); t = (a + f + _k[i] + w[_g[i]]); r = _r[i]; a = d; d = c; c = b; b += (t << r) | (t >>> (32 - r)); } // round 3 for(; i < 48; ++i) { f = b ^ c ^ d; t = (a + f + _k[i] + w[_g[i]]); r = _r[i]; a = d; d = c; c = b; b += (t << r) | (t >>> (32 - r)); } // round 4 for(; i < 64; ++i) { f = c ^ (b | ~d); t = (a + f + _k[i] + w[_g[i]]); r = _r[i]; a = d; d = c; c = b; b += (t << r) | (t >>> (32 - r)); } // update hash state s.h0 = (s.h0 + a) | 0; s.h1 = (s.h1 + b) | 0; s.h2 = (s.h2 + c) | 0; s.h3 = (s.h3 + d) | 0; len -= 64; } }
javascript
{ "resource": "" }
q10613
_reseed
train
function _reseed(callback) { if(ctx.pools[0].messageLength >= 32) { _seed(); return callback(); } // not enough seed data... var needed = (32 - ctx.pools[0].messageLength) << 5; ctx.seedFile(needed, function(err, bytes) { if(err) { return callback(err); } ctx.collect(bytes); _seed(); callback(); }); }
javascript
{ "resource": "" }
q10614
train
function(e) { var data = e.data; if(data.forge && data.forge.prng) { ctx.seedFile(data.forge.prng.needed, function(err, bytes) { worker.postMessage({forge: {prng: {err: err, bytes: bytes}}}); }); } }
javascript
{ "resource": "" }
q10615
train
function(iv, output) { if(iv) { /* CBC mode */ if(typeof iv === 'string') { iv = forge.util.createBuffer(iv); } } _finish = false; _input = forge.util.createBuffer(); _output = output || new forge.util.createBuffer(); _iv = iv; cipher.output = _output; }
javascript
{ "resource": "" }
q10616
generateRandom
train
function generateRandom(bits, rng) { var num = new BigInteger(bits, rng); // force MSB set var bits1 = bits - 1; if(!num.testBit(bits1)) { num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num); } // align number on 30k+1 boundary num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0); return num; }
javascript
{ "resource": "" }
q10617
train
function(md) { // get the oid for the algorithm var oid; if(md.algorithm in pki.oids) { oid = pki.oids[md.algorithm]; } else { var error = new Error('Unknown message digest algorithm.'); error.algorithm = md.algorithm; throw error; } var oidBytes = asn1.oidToDer(oid).getBytes(); // create the digest info var digestInfo = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); var digestAlgorithm = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); digestAlgorithm.value.push(asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes)); digestAlgorithm.value.push(asn1.create( asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')); var digest = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, md.digest().getBytes()); digestInfo.value.push(digestAlgorithm); digestInfo.value.push(digest); // encode digest info return asn1.toDer(digestInfo).getBytes(); }
javascript
{ "resource": "" }
q10618
_getAttribute
train
function _getAttribute(obj, options) { if(typeof options === 'string') { options = {shortName: options}; } var rval = null; var attr; for(var i = 0; rval === null && i < obj.attributes.length; ++i) { attr = obj.attributes[i]; if(options.type && options.type === attr.type) { rval = attr; } else if(options.name && options.name === attr.name) { rval = attr; } else if(options.shortName && options.shortName === attr.shortName) { rval = attr; } } return rval; }
javascript
{ "resource": "" }
q10619
train
function(oid, obj, fillDefaults) { var params = {}; if(oid !== oids['RSASSA-PSS']) { return params; } if(fillDefaults) { params = { hash: { algorithmOid: oids['sha1'] }, mgf: { algorithmOid: oids['mgf1'], hash: { algorithmOid: oids['sha1'] } }, saltLength: 20 }; } var capture = {}; var errors = []; if(!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) { var error = new Error('Cannot read RSASSA-PSS parameter block.'); error.errors = errors; throw error; } if(capture.hashOid !== undefined) { params.hash = params.hash || {}; params.hash.algorithmOid = asn1.derToOid(capture.hashOid); } if(capture.maskGenOid !== undefined) { params.mgf = params.mgf || {}; params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid); params.mgf.hash = params.mgf.hash || {}; params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid); } if(capture.saltLength !== undefined) { params.saltLength = capture.saltLength.charCodeAt(0); } return params; }
javascript
{ "resource": "" }
q10620
_dnToAsn1
train
function _dnToAsn1(obj) { // create an empty RDNSequence var rval = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); // iterate over attributes var attr, set; var attrs = obj.attributes; for(var i = 0; i < attrs.length; ++i) { attr = attrs[i]; var value = attr.value; // reuse tag class for attribute value if available var valueTagClass = asn1.Type.PRINTABLESTRING; if('valueTagClass' in attr) { valueTagClass = attr.valueTagClass; if(valueTagClass === asn1.Type.UTF8) { value = forge.util.encodeUtf8(value); } // FIXME: handle more encodings } // create a RelativeDistinguishedName set // each value in the set is an AttributeTypeAndValue first // containing the type (an OID) and second the value set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // AttributeType asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(attr.type).getBytes()), // AttributeValue asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value) ]) ]); rval.value.push(set); } return rval; }
javascript
{ "resource": "" }
q10621
_signatureParametersToAsn1
train
function _signatureParametersToAsn1(oid, params) { switch(oid) { case oids['RSASSA-PSS']: var parts = []; if(params.hash.algorithmOid !== undefined) { parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(params.hash.algorithmOid).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') ]) ])); } if(params.mgf.algorithmOid !== undefined) { parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(params.mgf.algorithmOid).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') ]) ]) ])); } if(params.saltLength !== undefined) { parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(params.saltLength).getBytes()) ])); } return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts); default: return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''); } }
javascript
{ "resource": "" }
q10622
_getBagsByAttribute
train
function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) { var result = []; for(var i = 0; i < safeContents.length; i ++) { for(var j = 0; j < safeContents[i].safeBags.length; j ++) { var bag = safeContents[i].safeBags[j]; if(bagType !== undefined && bag.type !== bagType) { continue; } // only filter by bag type, no attribute specified if(attrName === null) { result.push(bag); continue; } if(bag.attributes[attrName] !== undefined && bag.attributes[attrName].indexOf(attrValue) >= 0) { result.push(bag); } } } return result; }
javascript
{ "resource": "" }
q10623
train
function(c, record, s) { var rval = false; try { var bytes = c.inflate(record.fragment.getBytes()); record.fragment = forge.util.createBuffer(bytes); record.length = bytes.length; rval = true; } catch(ex) { // inflate error, fail out } return rval; }
javascript
{ "resource": "" }
q10624
train
function(b, lenBytes) { var len = 0; switch(lenBytes) { case 1: len = b.getByte(); break; case 2: len = b.getInt16(); break; case 3: len = b.getInt24(); break; case 4: len = b.getInt32(); break; } // read vector bytes into a new buffer return forge.util.createBuffer(b.getBytes(len)); }
javascript
{ "resource": "" }
q10625
train
function(b, lenBytes, v) { // encode length at the start of the vector, where the number of bytes for // the length is the maximum number of bytes it would take to encode the // vector's ceiling b.putInt(v.length(), lenBytes << 3); b.putBuffer(v); }
javascript
{ "resource": "" }
q10626
train
function(desc) { switch(desc) { case true: return true; case tls.Alert.Description.bad_certificate: return forge.pki.certificateError.bad_certificate; case tls.Alert.Description.unsupported_certificate: return forge.pki.certificateError.unsupported_certificate; case tls.Alert.Description.certificate_revoked: return forge.pki.certificateError.certificate_revoked; case tls.Alert.Description.certificate_expired: return forge.pki.certificateError.certificate_expired; case tls.Alert.Description.certificate_unknown: return forge.pki.certificateError.certificate_unknown; case tls.Alert.Description.unknown_ca: return forge.pki.certificateError.unknown_ca; default: return forge.pki.certificateError.bad_certificate; } }
javascript
{ "resource": "" }
q10627
train
function(c, record) { // get record handler (align type in table by subtracting lowest) var aligned = record.type - tls.ContentType.change_cipher_spec; var handlers = ctTable[c.entity][c.expect]; if(aligned in handlers) { handlers[aligned](c, record); } else { // unexpected record tls.handleUnexpected(c, record); } }
javascript
{ "resource": "" }
q10628
train
function(c) { var rval = 0; // get input buffer and its length var b = c.input; var len = b.length(); // need at least 5 bytes to initialize a record if(len < 5) { rval = 5 - len; } else { // enough bytes for header // initialize record c.record = { type: b.getByte(), version: { major: b.getByte(), minor: b.getByte() }, length: b.getInt16(), fragment: forge.util.createBuffer(), ready: false }; // check record version var compatibleVersion = (c.record.version.major === c.version.major); if(compatibleVersion && c.session && c.session.version) { // session version already set, require same minor version compatibleVersion = (c.record.version.minor === c.version.minor); } if(!compatibleVersion) { c.error(c, { message: 'Incompatible TLS version.', send: true, alert: { level: tls.Alert.Level.fatal, description: tls.Alert.Description.protocol_version } }); } } return rval; }
javascript
{ "resource": "" }
q10629
train
function(c) { var rval = 0; // ensure there is enough input data to get the entire record var b = c.input; var len = b.length(); if(len < c.record.length) { // not enough data yet, return how much is required rval = c.record.length - len; } else { // there is enough data to parse the pending record // fill record fragment and compact input buffer c.record.fragment.putBytes(b.getBytes(c.record.length)); b.compact(); // update record using current read state var s = c.state.current.read; if(s.update(c, c.record)) { // see if there is a previously fragmented message that the // new record's message fragment should be appended to if(c.fragmented !== null) { // if the record type matches a previously fragmented // record, append the record fragment to it if(c.fragmented.type === c.record.type) { // concatenate record fragments c.fragmented.fragment.putBuffer(c.record.fragment); c.record = c.fragmented; } else { // error, invalid fragmented record c.error(c, { message: 'Invalid fragmented record.', send: true, alert: { level: tls.Alert.Level.fatal, description: tls.Alert.Description.unexpected_message } }); } } // record is now ready c.record.ready = true; } } return rval; }
javascript
{ "resource": "" }
q10630
encrypt_aes_cbc_sha1_padding
train
function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) { /* The encrypted data length (TLSCiphertext.length) is one more than the sum of SecurityParameters.block_length, TLSCompressed.length, SecurityParameters.mac_length, and padding_length. The padding may be any length up to 255 bytes long, as long as it results in the TLSCiphertext.length being an integral multiple of the block length. Lengths longer than necessary might be desirable to frustrate attacks on a protocol based on analysis of the lengths of exchanged messages. Each uint8 in the padding data vector must be filled with the padding length value. The padding length should be such that the total size of the GenericBlockCipher structure is a multiple of the cipher's block length. Legal values range from zero to 255, inclusive. This length specifies the length of the padding field exclusive of the padding_length field itself. This is slightly different from PKCS#7 because the padding value is 1 less than the actual number of padding bytes if you include the padding_length uint8 itself as a padding byte. */ if(!decrypt) { // get the number of padding bytes required to reach the blockSize and // subtract 1 for the padding value (to make room for the padding_length // uint8) var padding = blockSize - (input.length() % blockSize); input.fillWithByte(padding - 1, padding); } return true; }
javascript
{ "resource": "" }
q10631
compareMacs
train
function compareMacs(key, mac1, mac2) { var hmac = forge.hmac.create(); hmac.start('SHA1', key); hmac.update(mac1); mac1 = hmac.digest().getBytes(); hmac.start(null, null); hmac.update(mac2); mac2 = hmac.digest().getBytes(); return mac1 === mac2; }
javascript
{ "resource": "" }
q10632
_createKDF
train
function _createKDF(kdf, md, counterStart, digestLength) { /** * Generate a key of the specified length. * * @param x the binary-encoded byte string to generate a key from. * @param length the number of bytes to generate (the size of the key). * * @return the key as a binary-encoded string. */ kdf.generate = function(x, length) { var key = new forge.util.ByteBuffer(); // run counter from counterStart to ceil(length / Hash.len) var k = Math.ceil(length / digestLength) + counterStart; var c = new forge.util.ByteBuffer(); for(var i = counterStart; i < k; ++i) { // I2OSP(i, 4): convert counter to an octet string of 4 octets c.putInt32(i); // digest 'x' and the counter and add the result to the key md.start(); md.update(x + c.getBytes()); var hash = md.digest(); key.putBytes(hash.getBytes(digestLength)); } // truncate to the correct key length key.truncate(key.length() - length); return key.getBytes(); }; }
javascript
{ "resource": "" }
q10633
train
function(logger, message) { forge.log.prepareStandardFull(message); console.log(message.standardFull); }
javascript
{ "resource": "" }
q10634
train
function(cert) { // convert from PEM if(typeof cert === 'string') { cert = forge.pki.certificateFromPem(cert); } msg.certificates.push(cert); }
javascript
{ "resource": "" }
q10635
train
function(cert) { var sAttr = cert.issuer.attributes; for(var i = 0; i < msg.recipients.length; ++i) { var r = msg.recipients[i]; var rAttr = r.issuer; if(r.serialNumber !== cert.serialNumber) { continue; } if(rAttr.length !== sAttr.length) { continue; } var match = true; for(var j = 0; j < sAttr.length; ++j) { if(rAttr[j].type !== sAttr[j].type || rAttr[j].value !== sAttr[j].value) { match = false; break; } } if(match) { return r; } } return null; }
javascript
{ "resource": "" }
q10636
train
function(recipient, privKey) { if(msg.encryptedContent.key === undefined && recipient !== undefined && privKey !== undefined) { switch(recipient.encryptedContent.algorithm) { case forge.pki.oids.rsaEncryption: case forge.pki.oids.desCBC: var key = privKey.decrypt(recipient.encryptedContent.content); msg.encryptedContent.key = forge.util.createBuffer(key); break; default: throw new Error('Unsupported asymmetric cipher, ' + 'OID ' + recipient.encryptedContent.algorithm); } } _decryptContent(msg); }
javascript
{ "resource": "" }
q10637
train
function(key, cipher) { // Part 1: Symmetric encryption if(msg.encryptedContent.content === undefined) { cipher = cipher || msg.encryptedContent.algorithm; key = key || msg.encryptedContent.key; var keyLen, ivLen, ciphFn; switch(cipher) { case forge.pki.oids['aes128-CBC']: keyLen = 16; ivLen = 16; ciphFn = forge.aes.createEncryptionCipher; break; case forge.pki.oids['aes192-CBC']: keyLen = 24; ivLen = 16; ciphFn = forge.aes.createEncryptionCipher; break; case forge.pki.oids['aes256-CBC']: keyLen = 32; ivLen = 16; ciphFn = forge.aes.createEncryptionCipher; break; case forge.pki.oids['des-EDE3-CBC']: keyLen = 24; ivLen = 8; ciphFn = forge.des.createEncryptionCipher; break; default: throw new Error('Unsupported symmetric cipher, OID ' + cipher); } if(key === undefined) { key = forge.util.createBuffer(forge.random.getBytes(keyLen)); } else if(key.length() != keyLen) { throw new Error('Symmetric key has wrong length; ' + 'got ' + key.length() + ' bytes, expected ' + keyLen + '.'); } // Keep a copy of the key & IV in the object, so the caller can // use it for whatever reason. msg.encryptedContent.algorithm = cipher; msg.encryptedContent.key = key; msg.encryptedContent.parameter = forge.util.createBuffer( forge.random.getBytes(ivLen)); var ciph = ciphFn(key); ciph.start(msg.encryptedContent.parameter.copy()); ciph.update(msg.content); // The finish function does PKCS#7 padding by default, therefore // no action required by us. if(!ciph.finish()) { throw new Error('Symmetric encryption failed.'); } msg.encryptedContent.content = ciph.output; } // Part 2: asymmetric encryption for each recipient for(var i = 0; i < msg.recipients.length; ++i) { var recipient = msg.recipients[i]; // Nothing to do, encryption already done. if(recipient.encryptedContent.content !== undefined) { continue; } switch(recipient.encryptedContent.algorithm) { case forge.pki.oids.rsaEncryption: recipient.encryptedContent.content = recipient.encryptedContent.key.encrypt( msg.encryptedContent.key.data); break; default: throw new Error('Unsupported asymmetric cipher, OID ' + recipient.encryptedContent.algorithm); } } }
javascript
{ "resource": "" }
q10638
_recipientFromAsn1
train
function _recipientFromAsn1(obj) { // validate EnvelopedData content block and capture data var capture = {}; var errors = []; if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) { var error = new Error('Cannot read PKCS#7 RecipientInfo. ' + 'ASN.1 object is not an PKCS#7 RecipientInfo.'); error.errors = errors; throw error; } return { version: capture.version.charCodeAt(0), issuer: forge.pki.RDNAttributesAsArray(capture.issuer), serialNumber: forge.util.createBuffer(capture.serial).toHex(), encryptedContent: { algorithm: asn1.derToOid(capture.encAlgorithm), parameter: capture.encParameter.value, content: capture.encKey } }; }
javascript
{ "resource": "" }
q10639
_recipientToAsn1
train
function _recipientToAsn1(obj) { return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // Version asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(obj.version).getBytes()), // IssuerAndSerialNumber asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // Name forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}), // Serial asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, forge.util.hexToBytes(obj.serialNumber)) ]), // KeyEncryptionAlgorithmIdentifier asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // Algorithm asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()), // Parameter, force NULL, only RSA supported for now. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') ]), // EncryptedKey asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.encryptedContent.content) ]); }
javascript
{ "resource": "" }
q10640
_recipientsFromAsn1
train
function _recipientsFromAsn1(infos) { var ret = []; for(var i = 0; i < infos.length; ++i) { ret.push(_recipientFromAsn1(infos[i])); } return ret; }
javascript
{ "resource": "" }
q10641
_recipientsToAsn1
train
function _recipientsToAsn1(recipients) { var ret = []; for(var i = 0; i < recipients.length; ++i) { ret.push(_recipientToAsn1(recipients[i])); } return ret; }
javascript
{ "resource": "" }
q10642
_signerFromAsn1
train
function _signerFromAsn1(obj) { // validate EnvelopedData content block and capture data var capture = {}; var errors = []; if(!asn1.validate(obj, p7.asn1.signerInfoValidator, capture, errors)) { var error = new Error('Cannot read PKCS#7 SignerInfo. ' + 'ASN.1 object is not an PKCS#7 SignerInfo.'); error.errors = errors; throw error; } var rval = { version: capture.version.charCodeAt(0), issuer: forge.pki.RDNAttributesAsArray(capture.issuer), serialNumber: forge.util.createBuffer(capture.serial).toHex(), digestAlgorithm: asn1.derToOid(capture.digestAlgorithm), signatureAlgorithm: asn1.derToOid(capture.signatureAlgorithm), signature: capture.signature, authenticatedAttributes: [], unauthenticatedAttributes: [] }; // TODO: convert attributes var authenticatedAttributes = capture.authenticatedAttributes || []; var unauthenticatedAttributes = capture.unauthenticatedAttributes || []; return rval; }
javascript
{ "resource": "" }
q10643
_signerToAsn1
train
function _signerToAsn1(obj) { // SignerInfo var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // version asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(obj.version).getBytes()), // issuerAndSerialNumber asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // name forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}), // serial asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, forge.util.hexToBytes(obj.serialNumber)) ]), // digestAlgorithm asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // algorithm asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(obj.digestAlgorithm).getBytes()), // parameters (null) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') ]) ]); // authenticatedAttributes (OPTIONAL) if(obj.authenticatedAttributesAsn1) { // add ASN.1 previously generated during signing rval.value.push(obj.authenticatedAttributesAsn1); } // digestEncryptionAlgorithm rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // algorithm asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(obj.signatureAlgorithm).getBytes()), // parameters (null) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') ])); // encryptedDigest rval.value.push(asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature)); // unauthenticatedAttributes (OPTIONAL) if(obj.unauthenticatedAttributes.length > 0) { // [1] IMPLICIT var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []); for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) { var attr = obj.unauthenticatedAttributes[i]; attrsAsn1.values.push(_attributeToAsn1(attr)); } rval.value.push(attrsAsn1); } return rval; }
javascript
{ "resource": "" }
q10644
_signersFromAsn1
train
function _signersFromAsn1(signerInfoAsn1s) { var ret = []; for(var i = 0; i < signerInfoAsn1s.length; ++i) { ret.push(_signerFromAsn1(signerInfoAsn1s[i])); } return ret; }
javascript
{ "resource": "" }
q10645
_signersToAsn1
train
function _signersToAsn1(signers) { var ret = []; for(var i = 0; i < signers.length; ++i) { ret.push(_signerToAsn1(signers[i])); } return ret; }
javascript
{ "resource": "" }
q10646
_attributeToAsn1
train
function _attributeToAsn1(attr) { var value; // TODO: generalize to support more attributes if(attr.type === forge.pki.oids.contentType) { value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(attr.value).getBytes()); } else if(attr.type === forge.pki.oids.messageDigest) { value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, attr.value.bytes()); } else if(attr.type === forge.pki.oids.signingTime) { /* Note per RFC 2985: Dates between 1 January 1950 and 31 December 2049 (inclusive) MUST be encoded as UTCTime. Any dates with year values before 1950 or after 2049 MUST be encoded as GeneralizedTime. [Further,] UTCTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST include seconds (i.e., times are YYMMDDHHMMSSZ), even where the number of seconds is zero. Midnight (GMT) must be represented as "YYMMDD000000Z". */ // TODO: make these module-level constants var jan_1_1950 = new Date('Jan 1, 1950 00:00:00Z'); var jan_1_2050 = new Date('Jan 1, 2050 00:00:00Z'); var date = attr.value; if(typeof date === 'string') { // try to parse date var timestamp = Date.parse(date); if(!isNaN(timestamp)) { date = new Date(timestamp); } else if(date.length === 13) { // YYMMDDHHMMSSZ (13 chars for UTCTime) date = asn1.utcTimeToDate(date); } else { // assume generalized time date = asn1.generalizedTimeToDate(date); } } if(date >= jan_1_1950 && date < jan_1_2050) { value = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false, asn1.dateToUtcTime(date)); } else { value = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false, asn1.dateToGeneralizedTime(date)); } } // TODO: expose as common API call // create a RelativeDistinguishedName set // each value in the set is an AttributeTypeAndValue first // containing the type (an OID) and second the value return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // AttributeType asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(attr.type).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ // AttributeValue value ]) ]); }
javascript
{ "resource": "" }
q10647
_encryptedContentToAsn1
train
function _encryptedContentToAsn1(ec) { return [ // ContentType, always Data for the moment asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(forge.pki.oids.data).getBytes()), // ContentEncryptionAlgorithmIdentifier asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // Algorithm asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(ec.algorithm).getBytes()), // Parameters (IV) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ec.parameter.getBytes()) ]), // [0] EncryptedContent asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ec.content.getBytes()) ]) ]; }
javascript
{ "resource": "" }
q10648
_sha1
train
function _sha1() { var sha = forge.md.sha1.create(); var num = arguments.length; for (var i = 0; i < num; ++i) { sha.update(arguments[i]); } return sha.digest(); }
javascript
{ "resource": "" }
q10649
train
function(options) { // task id this.id = -1; // task name this.name = options.name || sNoTaskName; // task has no parent this.parent = options.parent || null; // save run function this.run = options.run; // create a queue of subtasks to run this.subtasks = []; // error flag this.error = false; // state of the task this.state = READY; // number of times the task has been blocked (also the number // of permits needed to be released to continue running) this.blocks = 0; // timeout id when sleeping this.timeoutId = null; // no swap time yet this.swapTime = null; // no user data this.userData = null; // initialize task // FIXME: deal with overflow this.id = sNextTaskId++; sTasks[this.id] = this; if(sVL >= 1) { forge.log.verbose(cat, '[%s][%s] init', this.id, this.name, this); } }
javascript
{ "resource": "" }
q10650
train
function(task) { task.error = false; task.state = sStateTable[task.state][START]; setTimeout(function() { if(task.state === RUNNING) { task.swapTime = +new Date(); task.run(task); runNext(task, 0); } }, 0); }
javascript
{ "resource": "" }
q10651
bundle
train
function bundle() { return browserify( config.inputDir + config.inputFile ).bundle() .pipe( source( config.outputFile ) ) .pipe( rename( config.outputFile ) ) .pipe( gulp.dest( config.outputDir ) // Create the .devel.js ) .pipe( streamify( jsmin() ) ) .pipe( rename( config.outputFileMin ) ) .pipe( gulp.dest( config.outputDir ) // Create the .min.js ) .pipe( streamify( gzip() ) ) .pipe( rename( config.outputFileMinGz ) ) .pipe( gulp.dest( config.outputDir ) // Create the .min.gz ); }
javascript
{ "resource": "" }
q10652
GhPolyglot
train
function GhPolyglot (input, token, host) { var splits = input.split("/"); this.user = splits[0]; this.repo = splits[1]; this.full_name = input; this.gh = new GitHub({ token: token, host: host }); }
javascript
{ "resource": "" }
q10653
getInnerLimit
train
function getInnerLimit() { var items = getItems(); var notInDeck = 0; if (items.length) { do { notInDeck = notInDeck + 1; var cont = false; var item = items[items.length - notInDeck]; if (item) { var area = getArea(item); if (ctrl.horizontal) { cont = area.right > getEltArea().right; } else { cont = area.bottom > getEltArea().bottom; } if (!cont) { notInDeck--; } } } while (cont); } else { notInDeck = 1; } var fix = ($scope.ngLimit - items.length) + notInDeck; return $scope.max ? $scope.ngLimit : $scope.ngLimit - fix; }
javascript
{ "resource": "" }
q10654
addEventListeners
train
function addEventListeners() { ctrl.ngelt.on('wheel', wheelOnElt); ctrl.ngelt.on('computegrabbersizes', ctrl.updateSize); // ctrl.elt.addEventListener("wheel", function (event) { // boxesScrollServices.execAndApplyIfScrollable($scope, this, wheel, [event]); // }, {passive: true, capture: true}); ctrl.ngsb.on("mouseout", mouseoutOnSb); ctrl.ngsb.on("mousedown", mousedownOnSb); // sur le mousedown, si dans le grabber, on init le mode drag, sinon on inc/dec les pages tant que l'on est appuyé ctrl.ngsb.on("mouseup", mouseup); // on stop l'inc/dec des pages ctrl.ngsb.on("click", boxesScrollServices.stopEvent); // desactive la propagation entre autrepour eviter la fermeture des popup ctrl.ngelt.on("mousemove", mousemoveOnElt); // on définit la couleur du grabber if (!ctrl.ngelt.css('display') !== 'none') { // si c'est une popup, le resize de l'ecran ne joue pas ng.element($window).on("resize", updateSize); } $document.on("mousedown", mousedownOnDoc); $document.on("keydown", keydownOnOnDoc); $document.on("scroll", invalidSizes); }
javascript
{ "resource": "" }
q10655
keydown
train
function keydown(event) { var inc = 0; if (ctrl.horizontal) { if (event.which === 37) { // LEFT inc = -1; } else if (event.which === 39) { // RIGHT inc = 1; } } else { var innerLimit = ctrl.getInnerLimit(); if (event.which === 38) { // UP inc = -1; } else if (event.which === 40) { // DOWN inc = 1; } else if (event.which === 33) { // PAGEUP inc = -innerLimit; } else if (event.which === 34) { // PAGEDOWN inc = innerLimit; } else if (event.which === 35) { // END inc = $scope.total - $scope.ngBegin - innerLimit; } else if (event.which === 36) { // HOME inc = -$scope.ngBegin; } } if (inc !== 0) { boxesScrollServices.stopEvent(event); $scope.ngBegin = $scope.ngBegin + inc; } }
javascript
{ "resource": "" }
q10656
isScrollbarOver
train
function isScrollbarOver(m) { return document.elementFromPoint(m.x, m.y) === ctrl.sb; }
javascript
{ "resource": "" }
q10657
updateGrabberSizes
train
function updateGrabberSizes() { if (ctrl.horizontal !== undefined) { var bgSizeElt = ctrl.ngelt.css('background-size'); var bgSizeSb = ctrl.ngsb.css('background-size'); var grabbersizePixel = '100%'; if(getInnerLimit() !== $scope.total) { grabbersizePixel = getGrabberSizePixelFromPercent(getGrabberSizePercentFromScopeValues())+'px'; } if (ctrl.horizontal) { bgSizeElt = bgSizeElt.replace(/.*\s+/, grabbersizePixel + ' '); bgSizeSb = bgSizeSb.replace(/.*\s+/, grabbersizePixel + ' '); } else { bgSizeElt = bgSizeElt.replace(/px\s+\d+(\.\d+)*.*/, 'px ' + grabbersizePixel); bgSizeSb = bgSizeSb.replace(/px\s+\d+(\.\d+)*.*/, 'px ' + grabbersizePixel); } ctrl.ngelt.css({'background-size': bgSizeElt}); ctrl.ngsb.css({'background-size': bgSizeSb}); } }
javascript
{ "resource": "" }
q10658
getGrabberOffsetPixelFromPercent
train
function getGrabberOffsetPixelFromPercent(percentOffset) { var sbLenght = getHeightArea(); // Longueur de la scrollbar var grabberOffsetPixel = sbLenght * percentOffset / 100; return Math.max(grabberOffsetPixel, 0); }
javascript
{ "resource": "" }
q10659
getOffsetPixelContainerBeforeItem
train
function getOffsetPixelContainerBeforeItem(item) { if (ctrl.horizontal) { return getArea(item).left - getEltArea().left; } else { return getArea(item).top - getEltArea().top; } }
javascript
{ "resource": "" }
q10660
train
function(file, enc, cb) { if ( !file.isNull() && !file.isDirectory() && options.extensions.some(function(ext) { return path.extname(file.path).substr(1).toLowerCase() === ext; }) ) { file = retina.tapFile(file, cb); } else { cb(); } // Push only if file is returned by retina (otherwise it is dropped from stream) if (file) this.push(file); }
javascript
{ "resource": "" }
q10661
joinParts
train
function joinParts(entrances) { var parts = []; parts.push(Buffer(content.substring(0, matches.index))); parts.push(Buffer('styles: [`')); for (var i=0; i<entrances.length; i++) { parts.push(Buffer(entrances[i].replace(/\n/g, ''))); if (i < entrances.length - 1) { parts.push(Buffer('`, `')); } } parts.push(Buffer('`]')); parts.push(Buffer(content.substr(matches.index + matches[0].length))); return Buffer.concat(parts); }
javascript
{ "resource": "" }
q10662
train
function (subject) { var t = kb.findTypeURIs(subject) if (t[ns.vcard('Individual').uri]) return 'Contact' if (t[ns.vcard('Organization').uri]) return 'contact' if (t[ns.foaf('Person').uri]) return 'Person' if (t[ns.schema('Person').uri]) return 'Person' if (t[ns.vcard('Group').uri]) return 'Group' if (t[ns.vcard('AddressBook').uri]) return 'Address book' return null // No under other circumstances }
javascript
{ "resource": "" }
q10663
train
function (books, context, options) { kb.fetcher.load(books).then(function (xhr) { renderThreeColumnBrowser2(books, context, options) }).catch(function (err) { complain(err) }) }
javascript
{ "resource": "" }
q10664
findBookFromGroups
train
function findBookFromGroups (book) { if (book) { return book } var g for (let gu in selectedGroups) { g = kb.sym(gu) let b = kb.any(undefined, ns.vcard('includesGroup'), g) if (b) return b } throw new Error('findBookFromGroups: Cant find address book which this group is part of') }
javascript
{ "resource": "" }
q10665
train
function (book, name, selectedGroups, callbackFunction) { book = findBookFromGroups(book) var nameEmailIndex = kb.any(book, ns.vcard('nameEmailIndex')) var uuid = UI.utils.genUuid() var person = kb.sym(book.dir().uri + 'Person/' + uuid + '/index.ttl#this') var doc = person.doc() // Sets of statements to different files var agenda = [ // Patch the main index to add the person [ $rdf.st(person, ns.vcard('inAddressBook'), book, nameEmailIndex), // The people index $rdf.st(person, ns.vcard('fn'), name, nameEmailIndex) ] ] // @@ May be missing email - sync that differently // sts.push(new $rdf.Statement(person, DCT('created'), new Date(), doc)); ??? include this? for (var gu in selectedGroups) { var g = kb.sym(gu) var gd = g.doc() agenda.push([ $rdf.st(g, ns.vcard('hasMember'), person, gd), $rdf.st(person, ns.vcard('fn'), name, gd) ]) } var updateCallback = function (uri, success, body) { if (!success) { console.log("Error: can't update " + uri + ' for new contact:' + body + '\n') callbackFunction(false, "Error: can't update " + uri + ' for new contact:' + body) } else { if (agenda.length > 0) { console.log('Patching ' + agenda[0] + '\n') updater.update([], agenda.shift(), updateCallback) } else { // done! console.log('Done patching. Now reading back in.\n') UI.store.fetcher.nowOrWhenFetched(doc, undefined, function (ok, body) { if (ok) { console.log('Read back in OK.\n') callbackFunction(true, person) } else { console.log('Read back in FAILED: ' + body + '\n') callbackFunction(false, body) } }) } } } UI.store.fetcher.nowOrWhenFetched(nameEmailIndex, undefined, function (ok, message) { if (ok) { console.log(' People index must be loaded\n') updater.put(doc, [ $rdf.st(person, ns.vcard('fn'), name, doc), $rdf.st(person, ns.rdf('type'), ns.vcard('Individual'), doc) ], 'text/turtle', updateCallback) } else { console.log('Error loading people index!' + nameEmailIndex.uri + ': ' + message) callbackFunction(false, 'Error loading people index!' + nameEmailIndex.uri + ': ' + message + '\n') } }) }
javascript
{ "resource": "" }
q10666
train
function (book, name, callbackFunction) { var gix = kb.any(book, ns.vcard('groupIndex')) var x = book.uri.split('#')[0] var gname = name.replace(' ', '_') var doc = kb.sym(x.slice(0, x.lastIndexOf('/') + 1) + 'Group/' + gname + '.ttl') var group = kb.sym(doc.uri + '#this') console.log(' New group will be: ' + group + '\n') UI.store.fetcher.nowOrWhenFetched(gix, function (ok, message) { if (ok) { console.log(' Group index must be loaded\n') var insertTriples = [ $rdf.st(book, ns.vcard('includesGroup'), group, gix), $rdf.st(group, ns.rdf('type'), ns.vcard('Group'), gix), $rdf.st(group, ns.vcard('fn'), name, gix) ] updater.update([], insertTriples, function (uri, success, body) { if (ok) { var triples = [ $rdf.st(book, ns.vcard('includesGroup'), group, gix), // Pointer back to book $rdf.st(group, ns.rdf('type'), ns.vcard('Group'), doc), $rdf.st(group, ns.vcard('fn'), name, doc) ] updater.put(doc, triples, 'text/turtle', function (uri, ok, body) { callbackFunction(ok, ok ? group : "Can't save new group file " + doc + body) }) } else { callbackFunction(ok, 'Could not update group index ' + body) // fail } }) } else { console.log('Error loading people index!' + gix.uri + ': ' + message) callbackFunction(false, 'Error loading people index!' + gix.uri + ': ' + message + '\n') } }) }
javascript
{ "resource": "" }
q10667
train
function (x) { var name = kb.any(x, ns.vcard('fn')) || kb.any(x, ns.foaf('name')) || kb.any(x, ns.vcard('organization-name')) return name ? name.value : '???' }
javascript
{ "resource": "" }
q10668
deleteThing
train
function deleteThing (x) { console.log('deleteThing: ' + x) var ds = kb.statementsMatching(x).concat(kb.statementsMatching(undefined, undefined, x)) var targets = {} ds.map(function (st) { targets[st.why.uri] = st }) var agenda = [] // sets of statements of same dcoument to delete for (var target in targets) { agenda.push(ds.filter(function (st) { return st.why.uri === target })) console.log(' Deleting ' + agenda[agenda.length - 1].length + ' triples from ' + target) } function nextOne () { if (agenda.length > 0) { updater.update(agenda.shift(), [], function (uri, ok, body) { if (!ok) { complain('Error deleting all trace of: ' + x + ': ' + body) return } nextOne() }) } else { console.log('Deleting resoure ' + x.doc()) kb.fetcher.delete(x.doc()) .then(function () { console.log('Delete thing ' + x + ': complete.') }) .catch(function (e) { complain('Error deleting thing ' + x + ': ' + e) }) } } nextOne() }
javascript
{ "resource": "" }
q10669
deleteRecursive
train
function deleteRecursive (kb, folder) { return new Promise(function (resolve, reject) { kb.fetcher.load(folder).then(function () { let promises = kb.each(folder, ns.ldp('contains')).map(file => { if (kb.holds(file, ns.rdf('type'), ns.ldp('BasicContainer'))) { return deleteRecursive(kb, file) } else { console.log('deleteRecirsive file: ' + file) if (!confirm(' Really DELETE File ' + file)) { throw new Error('User aborted delete file') } return kb.fetcher.webOperation('DELETE', file.uri) } }) console.log('deleteRecirsive folder: ' + folder) if (!confirm(' Really DELETE folder ' + folder)) { throw new Error('User aborted delete file') } promises.push(kb.fetcher.webOperation('DELETE', folder.uri)) Promise.all(promises).then(res => { resolve() }) }) }) }
javascript
{ "resource": "" }
q10670
train
function (uris) { uris.forEach(function (u) { console.log('Dropped on group: ' + u) var thing = kb.sym(u) var toBeFetched = [thing.doc(), group.doc()] kb.fetcher.load(toBeFetched).then(function (xhrs) { var types = kb.findTypeURIs(thing) for (var ty in types) { console.log(' drop object type includes: ' + ty) // @@ Allow email addresses and phone numbers to be dropped? } if (ns.vcard('Individual').uri in types || ns.vcard('Organization').uri in types) { var pname = kb.any(thing, ns.vcard('fn')) if (!pname) return alert('No vcard name known for ' + thing) var already = kb.holds(group, ns.vcard('hasMember'), thing, group.doc()) if (already) return alert('ALREADY added ' + pname + ' to group ' + name) var message = 'Add ' + pname + ' to group ' + name + '?' if (confirm(message)) { var ins = [ $rdf.st(group, ns.vcard('hasMember'), thing, group.doc()), $rdf.st(thing, ns.vcard('fn'), pname, group.doc())] kb.updater.update([], ins, function (uri, ok, err) { if (!ok) return complain('Error adding member to group ' + group + ': ' + err) console.log('Added ' + pname + ' to group ' + name) // @@ refresh UI }) } } }).catch(function (e) { complain('Error looking up dropped thing ' + thing + ' and group: ' + e) }) }) }
javascript
{ "resource": "" }
q10671
train
function (uris) { uris.map(function (u) { var thing = $rdf.sym(u) // Attachment needs text label to disinguish I think not icon. console.log('Dropped on mugshot thing ' + thing) // icon was: UI.icons.iconBase + 'noun_25830.svg' if (u.startsWith('http') && u.indexOf('#') < 0) { // Plain document // Take a copy of a photo on the web: kb.fetcher.webOperation('GET', thing.uri).then(result => { let contentType = result.headers.get('Content-Type') // let data = result.responseText let pathEnd = thing.uri.split('/').slice(-1)[0] // last segment as putative filename pathEnd = pathEnd.split('?')[0] // chop off any query params result.arrayBuffer().then(function (data) { // read text stream if (!result.ok) { complain('Error downloading ' + thing + ':' + result.status) return } uploadFileToContact(pathEnd, contentType, data) }) }) return } else { console.log('Not a web document URI, cannot copy as picture: ' + thing) } handleDroppedThing(thing) }) }
javascript
{ "resource": "" }
q10672
train
function (files) { for (var i = 0; i < files.length; i++) { let f = files[i] console.log(' meeting: Filename: ' + f.name + ', type: ' + (f.type || 'n/a') + ' size: ' + f.size + ' bytes, last modified: ' + (f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a') ) // See e.g. https://www.html5rocks.com/en/tutorials/file/dndfiles/ // @@ Add: progress bar(s) var reader = new FileReader() reader.onload = (function (theFile) { return function (e) { var data = e.target.result console.log(' File read byteLength : ' + data.byteLength) var filename = encodeURIComponent(theFile.name) var contentType = theFile.type uploadFileToContact(filename, contentType, data) } })(f) reader.readAsArrayBuffer(f) } }
javascript
{ "resource": "" }
q10673
train
function (thing, group) { var pname = kb.any(thing, ns.vcard('fn')) var gname = kb.any(group, ns.vcard('fn')) var groups = kb.each(null, ns.vcard('hasMember'), thing) if (groups.length < 2) { alert('Must be a member of at least one group. Add to another group first.') return } var message = 'Remove ' + pname + ' from group ' + gname + '?' if (confirm(message)) { var del = [ $rdf.st(group, ns.vcard('hasMember'), thing, group.doc()), $rdf.st(thing, ns.vcard('fn'), pname, group.doc())] kb.updater.update(del, [], function (uri, ok, err) { if (!ok) return complain('Error removing member from group ' + group + ': ' + err) console.log('Removed ' + pname + ' from group ' + gname) syncGroupList() }) } }
javascript
{ "resource": "" }
q10674
diff
train
function diff( a, b ) { let i, j, found = false, result = []; for ( i = 0; i < a.length; i++ ) { found = false; for ( j = 0; j < b.length; j++ ) { if ( a[ i ] === b[ j ] ) { found = true; break; } } if ( !found ) { result.push( a[ i ] ); } } return result; }
javascript
{ "resource": "" }
q10675
train
function(thingy) { // simple DOM lookup utility function if (typeof(thingy) == 'string') { thingy = document.getElementById(thingy); } if (!thingy.addClass) { // extend element with a few useful methods thingy.hide = function() { this.style.display = 'none'; }; thingy.show = function() { this.style.display = ''; }; thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; }; thingy.removeClass = function(name) { this.className = this.className.replace( new RegExp("\\s*" + name + "\\s*"), " ").replace(/^\s+/, '').replace(/\s+$/, ''); }; thingy.hasClass = function(name) { return !!this.className.match( new RegExp("\\s*" + name + "\\s*") ); }; } return thingy; }
javascript
{ "resource": "" }
q10676
train
function ( filtered ) { var out = [], data = this.s.dt.aoData, displayed = this.s.dt.aiDisplay, i, iLen; if ( filtered ) { // Only consider filtered rows for ( i=0, iLen=displayed.length ; i<iLen ; i++ ) { if ( data[ displayed[i] ]._DTTT_selected ) { out.push( displayed[i] ); } } } else { // Use all rows for ( i=0, iLen=data.length ; i<iLen ; i++ ) { if ( data[i]._DTTT_selected ) { out.push( i ); } } } return out; }
javascript
{ "resource": "" }
q10677
train
function ( n ) { var pos = this.s.dt.oInstance.fnGetPosition( n ); return (this.s.dt.aoData[pos]._DTTT_selected===true) ? true : false; }
javascript
{ "resource": "" }
q10678
train
function( oConfig ) { var sTitle = ""; if ( typeof oConfig.sTitle != 'undefined' && oConfig.sTitle !== "" ) { sTitle = oConfig.sTitle; } else { var anTitle = document.getElementsByTagName('title'); if ( anTitle.length > 0 ) { sTitle = anTitle[0].innerHTML; } } /* Strip characters which the OS will object to - checking for UTF8 support in the scripting * engine */ if ( "\u00A1".toString().length < 4 ) { return sTitle.replace(/[^a-zA-Z0-9_\u00A1-\uFFFF\.,\-_ !\(\)]/g, ""); } else { return sTitle.replace(/[^a-zA-Z0-9_\.,\-_ !\(\)]/g, ""); } }
javascript
{ "resource": "" }
q10679
train
function ( oConfig ) { var aoCols = this.s.dt.aoColumns, aColumnsInc = this._fnColumnTargets( oConfig.mColumns ), aColWidths = [], iWidth = 0, iTotal = 0, i, iLen; for ( i=0, iLen=aColumnsInc.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { iWidth = aoCols[i].nTh.offsetWidth; iTotal += iWidth; aColWidths.push( iWidth ); } } for ( i=0, iLen=aColWidths.length ; i<iLen ; i++ ) { aColWidths[i] = aColWidths[i] / iTotal; } return aColWidths.join('\t'); }
javascript
{ "resource": "" }
q10680
train
function () { for ( var cli in ZeroClipboard_TableTools.clients ) { if ( cli ) { var client = ZeroClipboard_TableTools.clients[cli]; if ( typeof client.domElement != 'undefined' && client.domElement.parentNode == this.dom.container && client.sized === false ) { return true; } } } return false; }
javascript
{ "resource": "" }
q10681
train
function ( bView, oConfig ) { if ( oConfig === undefined ) { oConfig = {}; } if ( bView === undefined || bView ) { this._fnPrintStart( oConfig ); } else { this._fnPrintEnd(); } }
javascript
{ "resource": "" }
q10682
train
function ( message, time ) { var info = $('<div/>') .addClass( this.classes.print.info ) .html( message ) .appendTo( 'body' ); setTimeout( function() { info.fadeOut( "normal", function() { info.remove(); } ); }, time ); }
javascript
{ "resource": "" }
q10683
train
function ( oOpts ) { /* Is this the master control instance or not? */ if ( typeof this.s.dt._TableToolsInit == 'undefined' ) { this.s.master = true; this.s.dt._TableToolsInit = true; } /* We can use the table node from comparisons to group controls */ this.dom.table = this.s.dt.nTable; /* Clone the defaults and then the user options */ this.s.custom = $.extend( {}, TableTools.DEFAULTS, oOpts ); /* Flash file location */ this.s.swfPath = this.s.custom.sSwfPath; if ( typeof ZeroClipboard_TableTools != 'undefined' ) { ZeroClipboard_TableTools.moviePath = this.s.swfPath; } /* Table row selecting */ this.s.select.type = this.s.custom.sRowSelect; this.s.select.preRowSelect = this.s.custom.fnPreRowSelect; this.s.select.postSelected = this.s.custom.fnRowSelected; this.s.select.postDeselected = this.s.custom.fnRowDeselected; // Backwards compatibility - allow the user to specify a custom class in the initialiser if ( this.s.custom.sSelectedClass ) { this.classes.select.row = this.s.custom.sSelectedClass; } this.s.tags = this.s.custom.oTags; /* Button set */ this.s.buttonSet = this.s.custom.aButtons; }
javascript
{ "resource": "" }
q10684
train
function ( buttonSet, wrapper ) { var buttonDef; for ( var i=0, iLen=buttonSet.length ; i<iLen ; i++ ) { if ( typeof buttonSet[i] == "string" ) { if ( typeof TableTools.BUTTONS[ buttonSet[i] ] == 'undefined' ) { alert( "TableTools: Warning - unknown button type: "+buttonSet[i] ); continue; } buttonDef = $.extend( {}, TableTools.BUTTONS[ buttonSet[i] ], true ); } else { if ( typeof TableTools.BUTTONS[ buttonSet[i].sExtends ] == 'undefined' ) { alert( "TableTools: Warning - unknown button type: "+buttonSet[i].sExtends ); continue; } var o = $.extend( {}, TableTools.BUTTONS[ buttonSet[i].sExtends ], true ); buttonDef = $.extend( o, buttonSet[i], true ); } var button = this._fnCreateButton( buttonDef, $(wrapper).hasClass(this.classes.collection.container) ); if ( button ) { wrapper.appendChild( button ); } } }
javascript
{ "resource": "" }
q10685
train
function ( oConfig, bCollectionButton ) { var nButton = this._fnButtonBase( oConfig, bCollectionButton ); if ( oConfig.sAction.match(/flash/) ) { if ( ! this._fnHasFlash() ) { return false; } this._fnFlashConfig( nButton, oConfig ); } else if ( oConfig.sAction == "text" ) { this._fnTextConfig( nButton, oConfig ); } else if ( oConfig.sAction == "div" ) { this._fnTextConfig( nButton, oConfig ); } else if ( oConfig.sAction == "collection" ) { this._fnTextConfig( nButton, oConfig ); this._fnCollectionConfig( nButton, oConfig ); } if ( this.s.dt.iTabIndex !== -1 ) { $(nButton) .attr( 'tabindex', this.s.dt.iTabIndex ) .attr( 'aria-controls', this.s.dt.sTableId ) .on( 'keyup.DTTT', function (e) { // Trigger the click event on return key when focused. // Note that for Flash buttons this has no effect since we // can't programmatically trigger the Flash export if ( e.keyCode === 13 ) { e.stopPropagation(); $(this).trigger( 'click' ); } } ) .on( 'mousedown.DTTT', function (e) { // On mousedown we want to stop the focus occurring on the // button, focus is used only for the keyboard navigation. // But using preventDefault for the flash buttons stops the // flash action. However, it is not the button that gets // focused but the flash element for flash buttons, so this // works if ( ! oConfig.sAction.match(/flash/) ) { e.preventDefault(); } } ); } return nButton; }
javascript
{ "resource": "" }
q10686
train
function ( o, bCollectionButton ) { var sTag, sLiner, sClass; if ( bCollectionButton ) { sTag = o.sTag && o.sTag !== "default" ? o.sTag : this.s.tags.collection.button; sLiner = o.sLinerTag && o.sLinerTag !== "default" ? o.sLiner : this.s.tags.collection.liner; sClass = this.classes.collection.buttons.normal; } else { sTag = o.sTag && o.sTag !== "default" ? o.sTag : this.s.tags.button; sLiner = o.sLinerTag && o.sLinerTag !== "default" ? o.sLiner : this.s.tags.liner; sClass = this.classes.buttons.normal; } var nButton = document.createElement( sTag ), nSpan = document.createElement( sLiner ), masterS = this._fnGetMasterSettings(); nButton.className = sClass+" "+o.sButtonClass; nButton.setAttribute('id', "ToolTables_"+this.s.dt.sInstance+"_"+masterS.buttonCounter ); nButton.appendChild( nSpan ); nSpan.innerHTML = o.sButtonText; masterS.buttonCounter++; return nButton; }
javascript
{ "resource": "" }
q10687
train
function ( nButton, oConfig ) { var that = this, oPos = $(nButton).offset(), nHidden = oConfig._collection, iDivX = oPos.left, iDivY = oPos.top + $(nButton).outerHeight(), iWinHeight = $(window).height(), iDocHeight = $(document).height(), iWinWidth = $(window).width(), iDocWidth = $(document).width(); nHidden.style.position = "absolute"; nHidden.style.left = iDivX+"px"; nHidden.style.top = iDivY+"px"; nHidden.style.display = "block"; $(nHidden).css('opacity',0); var nBackground = document.createElement('div'); nBackground.style.position = "absolute"; nBackground.style.left = "0px"; nBackground.style.top = "0px"; nBackground.style.height = ((iWinHeight>iDocHeight)? iWinHeight : iDocHeight) +"px"; nBackground.style.width = ((iWinWidth>iDocWidth)? iWinWidth : iDocWidth) +"px"; nBackground.className = this.classes.collection.background; $(nBackground).css('opacity',0); document.body.appendChild( nBackground ); document.body.appendChild( nHidden ); /* Visual corrections to try and keep the collection visible */ var iDivWidth = $(nHidden).outerWidth(); var iDivHeight = $(nHidden).outerHeight(); if ( iDivX + iDivWidth > iDocWidth ) { nHidden.style.left = (iDocWidth-iDivWidth)+"px"; } if ( iDivY + iDivHeight > iDocHeight ) { nHidden.style.top = (iDivY-iDivHeight-$(nButton).outerHeight())+"px"; } this.dom.collection.collection = nHidden; this.dom.collection.background = nBackground; /* This results in a very small delay for the end user but it allows the animation to be * much smoother. If you don't want the animation, then the setTimeout can be removed */ setTimeout( function () { $(nHidden).animate({"opacity": 1}, 500); $(nBackground).animate({"opacity": 0.25}, 500); }, 10 ); /* Resize the buttons to the Flash contents fit */ this.fnResizeButtons(); /* Event handler to remove the collection display */ $(nBackground).click( function () { that._fnCollectionHide.call( that, null, null ); } ); }
javascript
{ "resource": "" }
q10688
train
function ( nButton, oConfig ) { if ( oConfig !== null && oConfig.sExtends == 'collection' ) { return; } if ( this.dom.collection.collection !== null ) { $(this.dom.collection.collection).animate({"opacity": 0}, 500, function (e) { this.style.display = "none"; } ); $(this.dom.collection.background).animate({"opacity": 0}, 500, function (e) { this.parentNode.removeChild( this ); } ); this.dom.collection.collection = null; this.dom.collection.background = null; } }
javascript
{ "resource": "" }
q10689
train
function ( src ) { var out = [], pos, i, iLen; if ( src.nodeName ) { // Single node pos = this.s.dt.oInstance.fnGetPosition( src ); out.push( this.s.dt.aoData[pos] ); } else if ( typeof src.length !== 'undefined' ) { // jQuery object or an array of nodes, or aoData points for ( i=0, iLen=src.length ; i<iLen ; i++ ) { if ( src[i].nodeName ) { pos = this.s.dt.oInstance.fnGetPosition( src[i] ); out.push( this.s.dt.aoData[pos] ); } else if ( typeof src[i] === 'number' ) { out.push( this.s.dt.aoData[ src[i] ] ); } else { out.push( src[i] ); } } return out; } else if ( typeof src === 'number' ) { out.push(this.s.dt.aoData[src]); } else { // A single aoData point out.push( src ); } return out; }
javascript
{ "resource": "" }
q10690
train
function ( nButton, oConfig ) { var that = this; var flash = new ZeroClipboard_TableTools.Client(); if ( oConfig.fnInit !== null ) { oConfig.fnInit.call( this, nButton, oConfig ); } flash.setHandCursor( true ); if ( oConfig.sAction == "flash_save" ) { flash.setAction( 'save' ); flash.setCharSet( (oConfig.sCharSet=="utf16le") ? 'UTF16LE' : 'UTF8' ); flash.setBomInc( oConfig.bBomInc ); flash.setFileName( oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)) ); } else if ( oConfig.sAction == "flash_pdf" ) { flash.setAction( 'pdf' ); flash.setFileName( oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)) ); } else { flash.setAction( 'copy' ); } flash.addEventListener('mouseOver', function(client) { if ( oConfig.fnMouseover !== null ) { oConfig.fnMouseover.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('mouseOut', function(client) { if ( oConfig.fnMouseout !== null ) { oConfig.fnMouseout.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('mouseDown', function(client) { if ( oConfig.fnClick !== null ) { oConfig.fnClick.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('complete', function (client, text) { if ( oConfig.fnComplete !== null ) { oConfig.fnComplete.call( that, nButton, oConfig, flash, text ); } that._fnCollectionHide( nButton, oConfig ); } ); if ( oConfig.fnSelect !== null ) { TableTools._fnEventListen( this, 'select', function (n) { oConfig.fnSelect.call( that, nButton, oConfig, n ); } ); } this._fnFlashGlue( flash, nButton, oConfig.sToolTip ); }
javascript
{ "resource": "" }
q10691
train
function ( clip, sData ) { var asData = this._fnChunkData( sData, 8192 ); clip.clearText(); for ( var i=0, iLen=asData.length ; i<iLen ; i++ ) { clip.appendText( asData[i] ); } }
javascript
{ "resource": "" }
q10692
train
function ( sData, sBoundary, regex ) { if ( sBoundary === "" ) { return sData; } else { return sBoundary + sData.replace(regex, sBoundary+sBoundary) + sBoundary; } }
javascript
{ "resource": "" }
q10693
train
function ( sData, iSize ) { var asReturn = []; var iStrlen = sData.length; for ( var i=0 ; i<iStrlen ; i+=iSize ) { if ( i+iSize < iStrlen ) { asReturn.push( sData.substring( i, i+iSize ) ); } else { asReturn.push( sData.substring( i, iStrlen ) ); } } return asReturn; }
javascript
{ "resource": "" }
q10694
train
function ( sData ) { if ( sData.indexOf('&') === -1 ) { return sData; } var n = document.createElement('div'); return sData.replace( /&([^\s]*?);/g, function( match, match2 ) { if ( match.substr(1, 1) === '#' ) { return String.fromCharCode( Number(match2.substr(1)) ); } else { n.innerHTML = match; return n.childNodes[0].nodeValue; } } ); }
javascript
{ "resource": "" }
q10695
train
function ( e ) { var that = this; var oSetDT = this.s.dt; var oSetPrint = this.s.print; var oDomPrint = this.dom.print; /* Show all hidden nodes */ this._fnPrintShowNodes(); /* Restore DataTables' scrolling */ if ( oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "" ) { $(this.s.dt.nTable).unbind('draw.DTTT_Print'); this._fnPrintScrollEnd(); } /* Restore the scroll */ window.scrollTo( 0, oSetPrint.saveScroll ); /* Drop the print message */ $('div.'+this.classes.print.message).remove(); /* Styling class */ $(document.body).removeClass( 'DTTT_Print' ); /* Restore the table length */ oSetDT._iDisplayStart = oSetPrint.saveStart; oSetDT._iDisplayLength = oSetPrint.saveLength; if ( oSetDT.oApi._fnCalculateEnd ) { oSetDT.oApi._fnCalculateEnd( oSetDT ); } oSetDT.oApi._fnDraw( oSetDT ); $(document).unbind( "keydown.DTTT" ); }
javascript
{ "resource": "" }
q10696
train
function () { var oSetDT = this.s.dt, nScrollHeadInner = oSetDT.nScrollHead.getElementsByTagName('div')[0], nScrollHeadTable = nScrollHeadInner.getElementsByTagName('table')[0], nScrollBody = oSetDT.nTable.parentNode, nTheadSize, nTfootSize; /* Copy the header in the thead in the body table, this way we show one single table when * in print view. Note that this section of code is more or less verbatim from DT 1.7.0 */ nTheadSize = oSetDT.nTable.getElementsByTagName('thead'); if ( nTheadSize.length > 0 ) { oSetDT.nTable.removeChild( nTheadSize[0] ); } if ( oSetDT.nTFoot !== null ) { nTfootSize = oSetDT.nTable.getElementsByTagName('tfoot'); if ( nTfootSize.length > 0 ) { oSetDT.nTable.removeChild( nTfootSize[0] ); } } nTheadSize = oSetDT.nTHead.cloneNode(true); oSetDT.nTable.insertBefore( nTheadSize, oSetDT.nTable.childNodes[0] ); if ( oSetDT.nTFoot !== null ) { nTfootSize = oSetDT.nTFoot.cloneNode(true); oSetDT.nTable.insertBefore( nTfootSize, oSetDT.nTable.childNodes[1] ); } /* Now adjust the table's viewport so we can actually see it */ if ( oSetDT.oScroll.sX !== "" ) { oSetDT.nTable.style.width = $(oSetDT.nTable).outerWidth()+"px"; nScrollBody.style.width = $(oSetDT.nTable).outerWidth()+"px"; nScrollBody.style.overflow = "visible"; } if ( oSetDT.oScroll.sY !== "" ) { nScrollBody.style.height = $(oSetDT.nTable).outerHeight()+"px"; nScrollBody.style.overflow = "visible"; } }
javascript
{ "resource": "" }
q10697
train
function () { var oSetDT = this.s.dt, nScrollBody = oSetDT.nTable.parentNode; if ( oSetDT.oScroll.sX !== "" ) { nScrollBody.style.width = oSetDT.oApi._fnStringToCss( oSetDT.oScroll.sX ); nScrollBody.style.overflow = "auto"; } if ( oSetDT.oScroll.sY !== "" ) { nScrollBody.style.height = oSetDT.oApi._fnStringToCss( oSetDT.oScroll.sY ); nScrollBody.style.overflow = "auto"; } }
javascript
{ "resource": "" }
q10698
train
function ( ) { var anHidden = this.dom.print.hidden; for ( var i=0, iLen=anHidden.length ; i<iLen ; i++ ) { anHidden[i].node.style.display = anHidden[i].display; } anHidden.splice( 0, anHidden.length ); }
javascript
{ "resource": "" }
q10699
train
function ( nNode ) { var anHidden = this.dom.print.hidden; var nParent = nNode.parentNode; var nChildren = nParent.childNodes; for ( var i=0, iLen=nChildren.length ; i<iLen ; i++ ) { if ( nChildren[i] != nNode && nChildren[i].nodeType == 1 ) { /* If our node is shown (don't want to show nodes which were previously hidden) */ var sDisplay = $(nChildren[i]).css("display"); if ( sDisplay != "none" ) { /* Cache the node and it's previous state so we can restore it */ anHidden.push( { "node": nChildren[i], "display": sDisplay } ); nChildren[i].style.display = "none"; } } } if ( nParent.nodeName.toUpperCase() != "BODY" ) { this._fnPrintHideNodes( nParent ); } }
javascript
{ "resource": "" }