_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q11200
prependToMemberExpression
train
function prependToMemberExpression(member, prepend) { member.object = t.memberExpression(prepend, member.object); return member; }
javascript
{ "resource": "" }
q11201
cloneDeep
train
function cloneDeep(node) { var newNode = {}; for (var key in node) { if (key[0] === "_") continue; var val = node[key]; if (val) { if (val.type) { val = t.cloneDeep(val); } else if (Array.isArray(val)) { val = val.map(t.cloneDeep); } } newNode[key] = val; } return newNode; }
javascript
{ "resource": "" }
q11202
buildMatchMemberExpression
train
function buildMatchMemberExpression(match, allowPartial) { var parts = match.split("."); return function (member) { // not a member expression if (!t.isMemberExpression(member)) return false; var search = [member]; var i = 0; while (search.length) { var node = search.shift(); if (allowPartial && i === parts.length) { return true; } if (t.isIdentifier(node)) { // this part doesn't match if (parts[i] !== node.name) return false; } else if (t.isLiteral(node)) { // this part doesn't match if (parts[i] !== node.value) return false; } else if (t.isMemberExpression(node)) { if (node.computed && !t.isLiteral(node.property)) { // we can't deal with this return false; } else { search.push(node.object); search.push(node.property); continue; } } else { // we can't deal with this return false; } // too many parts if (++i > parts.length) { return false; } } return true; }; }
javascript
{ "resource": "" }
q11203
removeComments
train
function removeComments(node) { var _arr3 = COMMENT_KEYS; for (var _i3 = 0; _i3 < _arr3.length; _i3++) { var key = _arr3[_i3]; delete node[key]; } return node; }
javascript
{ "resource": "" }
q11204
inheritsComments
train
function inheritsComments(child, parent) { inheritTrailingComments(child, parent); inheritLeadingComments(child, parent); inheritInnerComments(child, parent); return child; }
javascript
{ "resource": "" }
q11205
inherits
train
function inherits(child, parent) { if (!child || !parent) return child; var _arr4 = t.INHERIT_KEYS.optional; for (var _i4 = 0; _i4 < _arr4.length; _i4++) { var key = _arr4[_i4]; if (child[key] == null) { child[key] = parent[key]; } } var _arr5 = t.INHERIT_KEYS.force; for (var _i5 = 0; _i5 < _arr5.length; _i5++) { var key = _arr5[_i5]; child[key] = parent[key]; } t.inheritsComments(child, parent); return child; }
javascript
{ "resource": "" }
q11206
getExclusionMatcher
train
function getExclusionMatcher(rules, defaultIsExclude) { return function isExcluded(name, ofType) { var index, include, pattern, rule, type, matchedRule, ret = null; if (!(ofType === 'file' || ofType === 'dir')) { throw new Error( 'Internal error: file type was not provided, was [' + ofType + ']' ); } /* check if there are any rules */ if (rules.length < 1) { throw new Error('No rules specified'); } // console.log('checking ' + name + '...'); for (index in rules) { // console.log('\t against ' + excludes[regex] + ': ' + // name.search(excludes[regex])); if (rules.hasOwnProperty(index)) { rule = rules[index]; if (rule instanceof RegExp) { pattern = rule; include = false; type = 'any'; } else { pattern = rule.pattern; include = !!rule.include; type = rule.type || 'any'; } if (!(type === 'file' || type === 'dir' || type === 'any')) { throw new Error('Invalid type for match [' + type + ']'); } if (!(pattern instanceof RegExp)) { console.log(rule); throw new Error('Pattern was not a regexp for rule'); } if (name.search(pattern) !== -1 && (type === 'any' || type === ofType)) { matchedRule = rule; ret = !include; break; } } } ret = ret === null ? !!defaultIsExclude : ret; //console.log('Match [' + name + '], Exclude= [' + ret + ']'); //console.log('Used rule'); //console.log(matchedRule); return ret; }; }
javascript
{ "resource": "" }
q11207
copyUsingMatcher
train
function copyUsingMatcher(src, dest, excludeMatcher) { var filenames, basedir, i, name, file, newdest, type; //console.log('copying ' + src + ' to ' + dest); /* check if source path exists */ if (!exists(src)) { throw new Error(src + ' does not exist'); } /* check if source is a directory */ if (!fs.statSync(src).isDirectory()) { throw new Error(src + ' must be a directory'); } /* get the names of all files and directories under source in an array */ filenames = fs.readdirSync(src); basedir = src; /* check if destination directory exists */ if (!exists(dest)) { fs.mkdirSync(dest, parseInt('755', 8)); } for (i = 0; i < filenames.length; i += 1) { name = filenames[i]; file = basedir + '/' + name; type = fs.statSync(file).isDirectory() ? 'dir' : 'file'; newdest = dest + '/' + name; if (!excludeMatcher(file, type)) { //console.log('Copy ' + file + ' as ' + newdest); if (type === 'dir') { copyUsingMatcher(file, newdest, excludeMatcher); } else { copyFile(file, newdest); } } } }
javascript
{ "resource": "" }
q11208
train
function (method, context) { return function () { var args = Array.prototype.slice.call(arguments); var lastIndex = args.length - 1; var lastArg = args && args.length > 0 ? args[lastIndex] : null; var cb = typeof lastArg === 'function' ? lastArg : null; if (cb) { return method.apply(context, args); } return new Promise(function (resolve, reject) { args.push(function (err, val) { if (err) return reject(err); resolve(val); }); method.apply(context, args); }); }; }
javascript
{ "resource": "" }
q11209
readdirPlus
train
function readdirPlus(path, userOptions, callback) { if (libTools.isFunction(userOptions)) { callback = userOptions; userOptions = null; } var options = libTools.merge(libVars.DEFAULT_OPTIONS); if (userOptions) { userOptions.stat = normalizeSection(userOptions.stat); userOptions.content = normalizeSection(userOptions.content); if (userOptions.content) { normalizeArray(userOptions.content, options.content, "asText"); normalizeArray(userOptions.content, options.content, "asBinary"); } libTools.merge(userOptions, options); } if (path[path.length - 1] !== libPath.sep) { path += libPath.sep; } setupFn(options.readdir); setupFn(options.stat); setupFn(options.content); return doReadDir(path, options, function (err, results) { if (err) { return callback && callback(err); } return callback && callback(null, results); }); function normalizeSection(section) { if (libTools.isBoolean(section)) { return { enabled: section }; } if (libTools.isAnonObject(section) && !libTools.isBoolean(section.enabled)) { section.enabled = true; } return section; } function setupFn(opts) { if (!opts.fn) { opts.fn = options.sync ? opts.fnSync : opts.fnAsync; } if (options.sync) { opts.fn = libTools.syncWrapper(opts.fn); } } function normalizeArray(target, source, property) { if (!target[property] || target[property] === true) { return; } if (!libTools.isArray(target[property])) { target[property] = [target[property]]; } else if (target[property].length === 1 && libTools.isArray(target[property][0])) { // array wrapped in array, replaces source value target[property] = target[property][0]; } else { target[property] = source[property].concat(target[property]); } } }
javascript
{ "resource": "" }
q11210
parse
train
function parse(c) { let ret = []; // replace windows line breaks with linux line breaks let c1 = c.replace(new RegExp('[\r][\n]', 'g'), '\n'); // split string to line array let c2 = c1.split('\n'); for (let i = 0; i < c2.length; i++) { //line object let lo = {}; // line let l = c2[i]; // trim line let l1 = l.trim(); // set line number lo.num = i + 1; // set original line lo.content = l1; // check empty line if (l1 === '') { lo.isEmpty = true; } else { lo.isEmpty = false; // check line comment if (l1.startsWith('#')) { lo.isComment = true; lo.comment = lo.content.substring(1,lo.content.length).trim(); } else { lo.isComment = false; // Check included comments lo = Object.assign(lo, checkComment(l1)); // check key value lo = Object.assign(lo, checkKeyValue(lo.contentWithoutComment)); // check block key lo = Object.assign(lo, checkBlockKey(lo)); } } //console.log(lo); ret.push(lo); } checkBlockEndSum(ret); determineDepth(ret); return ret; }
javascript
{ "resource": "" }
q11211
build
train
function build(obj, options) { // options let opt = Object.assign(defaultOptions, options); // mapfile content let map = ''; // determine one tab with spaces let tab = ''; for (let i = 0; i < opt.tabSize; i++) { tab += ' '; } //determine key-value-spaces determineKeyValueSpaces(obj, opt.tabSize); //iterate over all lines obj.forEach((line) => { //Add empty lines if (line.isEmpty) { if (opt.emptyLines) { map += opt.lineBreak; } } else { //Add comment lines if (line.isComment) { if (opt.comments) { map += determineTabs(line, tab) + '#' + opt.commentPrefix + line.comment + opt.lineBreak; } } else { //Add key if (line.key) { //Key only if (line.isKeyOnly) { map += determineTabs(line, tab) + line.key + opt.lineBreak; } else { //Key with value map += determineTabs(line, tab) + line.key; //Add value if (line.value) { if (line.includesComment) { //Add comment map += line.keyValueSpaces + line.value; if (opt.comments) { if (line.comment) { map += tab + '#' + opt.commentPrefix + line.comment + opt.lineBreak; } else { map += opt.lineBreak; } } else { map += opt.lineBreak; } } else { //Without comments map += line.keyValueSpaces + line.value + opt.lineBreak; } } } } } } }); return map; }
javascript
{ "resource": "" }
q11212
mothership
train
function mothership(start, ismothership, cb) { (function findShip (root) { findParentDir(root, 'package.json', function (err, packageDir) { if (err) return cb(err); if (!packageDir) return cb(); var pack; try { pack = require(path.join(packageDir, 'package.json')); if (ismothership(pack)) return cb(null, { path: path.join(packageDir, 'package.json'), pack: pack }); findShip(path.resolve(root, '..')); } catch (e) { cb(e); } }); })(start); }
javascript
{ "resource": "" }
q11213
train
function (horizontalPadding) { var de = document.documentElement, body = document.body, el, initData; // Create a div to figure out the size of the view-port across browsers el = document.createElement('div'); el.style.position = "fixed"; el.style.top = 0; el.style.left = 0; el.style.bottom = 0; el.style.right = 0; de.insertBefore(el, de.firstChild); initData = { bodyOverflow: body.style.overflow, bodyWidth: body.style.width, bodyHeight: body.style.height, viewPortWidth: el.offsetWidth, horizontalPadding: horizontalPadding }; de.removeChild(el); // Remove scrollbars body.style.overflow = 'hidden'; // Make document only one pixel height and twice wide as the view-port body.style.width = ((initData.viewPortWidth - horizontalPadding) * 2) + 'px'; body.style.height = '1px'; return JSON.stringify(initData); }
javascript
{ "resource": "" }
q11214
train
function (initData) { var body = document.body; body.style.overflow = initData.bodyOverflow; body.style.width = initData.bodyWidth; body.style.height = initData.bodyHeight; }
javascript
{ "resource": "" }
q11215
buildKssCmd
train
function buildKssCmd(node, kssNpmPath, options, files) { var cmd = [ node, kssNpmPath ], options; for (var optionName in options) { if (options.hasOwnProperty(optionName)) { grunt.log.debug('Reading option: ' + optionName); var values = options[optionName]; if (!Array.isArray(values)) { values = [values]; } for (var i = 0; i < values.length; i++) { if (values[i] && typeof values[i] === 'boolean') { grunt.log.debug(' > TRUE'); cmd.push('--' + optionName); } else if (typeof values[i] === 'string') { cmd.push('--' + optionName, values[i]); grunt.log.debug(' > ' + values[i]); } } } } files.forEach(function parseDestinationsFile(file) { if (file.src.length === 0) { grunt.log.error('No source files found'); grunt.fail.warn('Wrong configuration', 1); } cmd.push('--destination', '"' + file.dest + '"'); for (var i = 0; i < file.src.length; i++) { cmd.push('--source', '"' + file.src[i] + '"'); } dest = file.dest; }); return cmd; }
javascript
{ "resource": "" }
q11216
getKssNode
train
function getKssNode(baseKssPath, currentPath) { var kss = null; var localKss = currentPath + '/node_modules/' + baseKssPath; if (grunt.file.exists(localKss)) { return localKss; } var projektPath = path.dirname(currentPath); var projectKss = projektPath + '/' + baseKssPath; if (grunt.file.exists(projectKss)) { return projectKss; } else { grunt.log.error('Kss-node not found, please install kss!'); grunt.fail.warn('Wrong installation/environnement', 1); } }
javascript
{ "resource": "" }
q11217
waitObj
train
function waitObj(stream, onEnd) { var data = []; /** * Send the correct data to the onEnd callback. * * @private * @param {Error} [err] - Optional error. * @returns {undefined} */ var done = _.once(function (err) { if (err) { return onEnd(err); } return onEnd(null, data); }); stream.on('data', function (chunk) { data.push(chunk); }); stream.on('error', done); stream.on('end', done); }
javascript
{ "resource": "" }
q11218
wait
train
function wait(stream, onEnd) { waitObj(stream, function (err, data) { if (err) { return onEnd(err); } return onEnd(null, Buffer.concat(data.map(function (item) { return new Buffer(item); }))); }); }
javascript
{ "resource": "" }
q11219
waitJson
train
function waitJson(stream, onEnd) { wait(stream, function (err, data) { if (err) { return onEnd(err); } return parse(data, onEnd); }); }
javascript
{ "resource": "" }
q11220
pipeline
train
function pipeline() { var streams = getArgs(arguments); // When given no arguments, we should still return a stream if (streams.length === 0) { return new PassThrough(); } // Since a duplex requires at least two streams, we return single streams if (streams.length === 1) { return streams[0]; } return pump(streams); }
javascript
{ "resource": "" }
q11221
pipelineObj
train
function pipelineObj() { var streams = getArgs(arguments); // When given no arguments, we should still return a stream if (streams.length === 0) { return new PassThrough({ objectMode: true }); } // Since a duplex requires at least two streams, we return single streams if (streams.length === 1) { return streams[0]; } return pumpObj(streams); }
javascript
{ "resource": "" }
q11222
train
function(dir, files){ fs.readdirSync(dir).forEach(function(file){ try{ var current = path.join(dir, file); var stat = fs.statSync(current); if (stat && stat.isDirectory()) { getAllFiles(current, files); }else { files.push(current); } }catch(e){ console.error(e); } }); }
javascript
{ "resource": "" }
q11223
add
train
function add(x, y) { if (!retTable[x + "," + y]) { retTable[x + "," + y] = true; retArray.push([x, y]); } }
javascript
{ "resource": "" }
q11224
ParseArray
train
function ParseArray(array, encoding, obj) { for (var n = 0; n < encoding.length; ++n) { var value = array[n]; if (!value) continue; var field = encoding[n]; var fieldAlpha = field.replace(NON_ALPHA_CHARS, ""); if (field != fieldAlpha) value = new RegExp(field.replace(fieldAlpha, value)); obj[fieldAlpha] = value; } return obj; }
javascript
{ "resource": "" }
q11225
ParseMetaData
train
function ParseMetaData(countryCode, md) { var array = eval(md.replace(BACKSLASH, "\\\\")); md = ParseArray(array, META_DATA_ENCODING, { countryCode: countryCode }); regionCache[md.region] = md; return md; }
javascript
{ "resource": "" }
q11226
ParseFormat
train
function ParseFormat(md) { var formats = md.formats; if (!formats) { return null; } // Bail if we already parsed the format definitions. if (!(Array.isArray(formats[0]))) return; for (var n = 0; n < formats.length; ++n) { formats[n] = ParseArray(formats[n], FORMAT_ENCODING, {}); } }
javascript
{ "resource": "" }
q11227
FormatNumber
train
function FormatNumber(regionMetaData, number, intl) { // We lazily parse the format description in the meta data for the region, // so make sure to parse it now if we haven't already done so. ParseFormat(regionMetaData); var formats = regionMetaData.formats; if (!formats) { return null; } for (var n = 0; n < formats.length; ++n) { var format = formats[n]; // The leading digits field is optional. If we don't have it, just // use the matching pattern to qualify numbers. if (format.leadingDigits && !format.leadingDigits.test(number)) continue; if (!format.pattern.test(number)) continue; if (intl) { // If there is no international format, just fall back to the national // format. var internationalFormat = format.internationalFormat; if (!internationalFormat) internationalFormat = format.nationalFormat; // Some regions have numbers that can't be dialed from outside the // country, indicated by "NA" for the international format of that // number format pattern. if (internationalFormat == "NA") return null; // Prepend "+" and the country code. number = "+" + regionMetaData.countryCode + " " + number.replace(format.pattern, internationalFormat); } else { number = number.replace(format.pattern, format.nationalFormat); // The region has a national prefix formatting rule, and it can be overwritten // by each actual number format rule. var nationalPrefixFormattingRule = regionMetaData.nationalPrefixFormattingRule; if (format.nationalPrefixFormattingRule) nationalPrefixFormattingRule = format.nationalPrefixFormattingRule; if (nationalPrefixFormattingRule) { // The prefix formatting rule contains two magic markers, "$NP" and "$FG". // "$NP" will be replaced by the national prefix, and "$FG" with the // first group of numbers. var match = number.match(SPLIT_FIRST_GROUP); if (match) { var firstGroup = match[1]; var rest = match[2]; var prefix = nationalPrefixFormattingRule; prefix = prefix.replace("$NP", regionMetaData.nationalPrefix); prefix = prefix.replace("$FG", firstGroup); number = prefix + rest; } } } return (number == "NA") ? null : number; } return null; }
javascript
{ "resource": "" }
q11228
IsNationalNumber
train
function IsNationalNumber(number, md) { return IsValidNumber(number, md) && md.nationalPattern.test(number); }
javascript
{ "resource": "" }
q11229
ParseCountryCode
train
function ParseCountryCode(number) { for (var n = 1; n <= 3; ++n) { var cc = number.substr(0,n); if (dataBase[cc]) return cc; } return null; }
javascript
{ "resource": "" }
q11230
ParseInternationalNumber
train
function ParseInternationalNumber(number) { var ret; // Parse and strip the country code. var countryCode = ParseCountryCode(number); if (!countryCode) return null; number = number.substr(countryCode.length); // Lookup the meta data for the region (or regions) and if the rest of // the number parses for that region, return the parsed number. var entry = dataBase[countryCode]; if (Array.isArray(entry)) { for (var n = 0; n < entry.length; ++n) { if (typeof entry[n] == "string") entry[n] = ParseMetaData(countryCode, entry[n]); if (n > 0) entry[n].formats = entry[0].formats; ret = ParseNationalNumber(number, entry[n]) if (ret) return ret; } return null; } if (typeof entry == "string") entry = dataBase[countryCode] = ParseMetaData(countryCode, entry); return ParseNationalNumber(number, entry); }
javascript
{ "resource": "" }
q11231
ParseNumber
train
function ParseNumber(number, defaultRegion) { var ret; // Remove formating characters and whitespace. number = PhoneNumberNormalizer.Normalize(number); // If there is no defaultRegion, we can't parse international access codes. if (!defaultRegion && number[0] !== '+') return null; // Detect and strip leading '+'. if (number[0] === '+') return ParseInternationalNumber(number.replace(LEADING_PLUS_CHARS_PATTERN, "")); // Lookup the meta data for the given region. var md = FindMetaDataForRegion(defaultRegion.toUpperCase()); // See if the number starts with an international prefix, and if the // number resulting from stripping the code is valid, then remove the // prefix and flag the number as international. if (md.internationalPrefix.test(number)) { var possibleNumber = number.replace(md.internationalPrefix, ""); ret = ParseInternationalNumber(possibleNumber) if (ret) return ret; } // This is not an international number. See if its a national one for // the current region. National numbers can start with the national // prefix, or without. if (md.nationalPrefixForParsing) { // Some regions have specific national prefix parse rules. Apply those. var withoutPrefix = number.replace(md.nationalPrefixForParsing, md.nationalPrefixTransformRule || ''); ret = ParseNationalNumber(withoutPrefix, md) if (ret) return ret; } else { // If there is no specific national prefix rule, just strip off the // national prefix from the beginning of the number (if there is one). var nationalPrefix = md.nationalPrefix; if (nationalPrefix && number.indexOf(nationalPrefix) == 0 && (ret = ParseNationalNumber(number.substr(nationalPrefix.length), md))) { return ret; } } ret = ParseNationalNumber(number, md) if (ret) return ret; // Now lets see if maybe its an international number after all, but // without '+' or the international prefix. ret = ParseInternationalNumber(number) if (ret) return ret; // If the number matches the possible numbers of the current region, // return it as a possible number. if (md.possiblePattern.test(number)) return new NationalNumber(md, number); // We couldn't parse the number at all. return null; }
javascript
{ "resource": "" }
q11232
translateOptions
train
function translateOptions(cliOptions) { return { config: cliOptions.config, output: cliOptions.output, watch : cliOptions.watch }; }
javascript
{ "resource": "" }
q11233
buildJSXOpeningElementAttributes
train
function buildJSXOpeningElementAttributes(attribs, file) { var _props = []; var objs = []; var pushProps = function pushProps() { if (!_props.length) return; objs.push(t.objectExpression(_props)); _props = []; }; while (attribs.length) { var prop = attribs.shift(); if (t.isJSXSpreadAttribute(prop)) { pushProps(); objs.push(prop.argument); } else { _props.push(prop); } } pushProps(); if (objs.length === 1) { // only one object attribs = objs[0]; } else { // looks like we have multiple objects if (!t.isObjectExpression(objs[0])) { objs.unshift(t.objectExpression([])); } // spread it attribs = t.callExpression(file.addHelper("extends"), objs); } return attribs; }
javascript
{ "resource": "" }
q11234
requireOrThrow
train
function requireOrThrow(name) { try { return require(name); } catch (error) { log.fail('reshape-tape', `${name} failed to load`); return process.exit(1); } }
javascript
{ "resource": "" }
q11235
readFile
train
function readFile(filename) { return new Promise( (resolve, reject) => fs.readFile(filename, 'utf8', (error, data) => error ? reject(error) : resolve(data) ) ); }
javascript
{ "resource": "" }
q11236
writeFile
train
function writeFile(filename, data) { return new Promise( (resolve, reject) => fs.writeFile(filename, data, (error) => error ? reject(error) : resolve() ) ); }
javascript
{ "resource": "" }
q11237
defer
train
function defer(cb) { if (storage.LATENCY === 0 && typeof process !== 'undefined') { process.nextTick(cb); } else { setTimeout(cb, storage.LATENCY); } }
javascript
{ "resource": "" }
q11238
getSource
train
function getSource() { var node = this.node; if (node.end) { return this.hub.file.code.slice(node.start, node.end); } else { return ""; } }
javascript
{ "resource": "" }
q11239
_guessExecutionStatusRelativeTo
train
function _guessExecutionStatusRelativeTo(target) { // check if the two paths are in different functions, we can't track execution of these var targetFuncParent = target.scope.getFunctionParent(); var selfFuncParent = this.scope.getFunctionParent(); if (targetFuncParent !== selfFuncParent) { return "function"; } var targetPaths = target.getAncestry(); //if (targetPaths.indexOf(this) >= 0) return "after"; var selfPaths = this.getAncestry(); // get ancestor where the branches intersect var commonPath; var targetIndex; var selfIndex; for (selfIndex = 0; selfIndex < selfPaths.length; selfIndex++) { var selfPath = selfPaths[selfIndex]; targetIndex = targetPaths.indexOf(selfPath); if (targetIndex >= 0) { commonPath = selfPath; break; } } if (!commonPath) { return "before"; } // get the relationship paths that associate these nodes to their common ancestor var targetRelationship = targetPaths[targetIndex - 1]; var selfRelationship = selfPaths[selfIndex - 1]; if (!targetRelationship || !selfRelationship) { return "before"; } // container list so let's see which one is after the other if (targetRelationship.listKey && targetRelationship.container === selfRelationship.container) { return targetRelationship.key > selfRelationship.key ? "before" : "after"; } // otherwise we're associated by a parent node, check which key comes before the other var targetKeyPosition = t.VISITOR_KEYS[targetRelationship.type].indexOf(targetRelationship.key); var selfKeyPosition = t.VISITOR_KEYS[selfRelationship.type].indexOf(selfRelationship.key); return targetKeyPosition > selfKeyPosition ? "before" : "after"; }
javascript
{ "resource": "" }
q11240
train
function(item) { var result = {}; _.each(item, function(value, key) { if (fix[key]) { result[key] = parseItem(fix[key](value)); } else if (key === 'Tags') { result[key] = parseTags(value); } else { result[key] = parseItem(value); } }); return result; }
javascript
{ "resource": "" }
q11241
train
function(item) { var result; if (_.isArray(item)) { result = []; _.each(item, function(value) { result.push(parseItem(value)); }); return result; } /* otherwise */ if (_.isObject(item)) { return parseObject(item); } /* otherwise -- just a normal (non-compound) item */ return item; }
javascript
{ "resource": "" }
q11242
iterate
train
function iterate(iterator, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.openCursor(); req.onsuccess = function() { var cursor = req.result; if (cursor) { var result = iterator(cursor.value, cursor.key); if (result !== void(0)) { resolve(result); } else { cursor["continue"](); } } else { resolve(); } }; req.onerror = function() { reject(req.error); }; })["catch"](reject); }); executeDeferedCallback(promise, callback); return promise; }
javascript
{ "resource": "" }
q11243
train
function (config) { events.EventEmitter.call(this); this.config = config; this.ignoreFiles = config.ignoreFiles || ['.codiusignore']; this._filesystem = Compiler.RealFilesystem; }
javascript
{ "resource": "" }
q11244
forEachObj
train
function forEachObj(stream, onData, onEnd) { var done = _.once(onEnd); stream.on('data', onData); stream.on('error', done); stream.on('end', done); }
javascript
{ "resource": "" }
q11245
forEach
train
function forEach(stream, onData, onEnd) { forEachObj(stream, function (chunk) { onData(new Buffer(chunk)); }, onEnd); }
javascript
{ "resource": "" }
q11246
forEachJson
train
function forEachJson(stream, onData, onEnd) { forEach(stream, function (chunk) { var parsed; try { parsed = JSON.parse(chunk); } catch (e) { return stream.emit('error', e); } return onData(parsed); }, onEnd); }
javascript
{ "resource": "" }
q11247
sort
train
function sort(compareFunction) { return pipeline.obj( // collect all items into an array wait.obj(), // sort the array map(function (chunk, next) { // compareFunction can be null, undefined or a Function if (!_.isNil(compareFunction) && !_.isFunction(compareFunction)) { return next(new TypeError('Expected `compareFunction` to be a function.')); } return next(null, chunk.sort(compareFunction)); }), // expand the array so all input items are re-emitted through.obj(function Transform(chunk, enc, next) { var self = this; var len = chunk.length; // recursively add array items to the stream asynchronously (function emitNextItem(i) { setImmediate(function () { self.push(chunk[i]); // keep pushing items to the stream if more items are available if (i < len - 1) { emitNextItem(i + 1); return; } // the array has been depleted next(); }); }(0)); }) ); }
javascript
{ "resource": "" }
q11248
train
function(href, obj) { for (var j in obj) { if (obj.hasOwnProperty(j)) { href.obj[j] = obj[j]; } } }
javascript
{ "resource": "" }
q11249
getDecimal
train
function getDecimal(value) { if (!value) { return 0; } var num = value; if (!_.isNumber(value)) { var isNeg = ('-' && _.includes(value, '-')); var regExp = '[^0-9.]'; var numString = value.toString().replace(new RegExp(regExp, 'g'), ''); var numList = numString.split('.'); // numList will always have at least one value in array because we checked for an empty string earlier. numList[0] += '.'; numString = numList.join(''); num = parseFloat(numString); if (!num) { num = 0; } else if (isNeg) { num *= -1; } } return num; }
javascript
{ "resource": "" }
q11250
intersperse
train
function intersperse(value) { var first = true; return through.obj(function Transform(chunk, enc, next) { // Emit the value for everything but the first item if (first) { first = false; } else { this.push(value); } // Forward the original data next(null, chunk); }); }
javascript
{ "resource": "" }
q11251
Pool
train
function Pool(options, fn) { if (typeof options == 'function') { fn = options; options = {}; } options = options || {}; if (!fn) { throw new Error('Pool requires a worker function') }; if (fn.length < 1) { throw new Error('Pool worker function must accept done callback as an argument') }; EventEmitter.call(this); this._fn = fn; this._workers = this._createWorkers(options.size || 5); this._working = 0; this._queue = []; var self = this; this.on('task', function() { if (self._workers.length == self._working) { return; } self._dispatch(); }); this.on('done', function() { // TODO: emit a `drain` event if the pool was previously queuing, and now // has slots available if (self._working == 0 && self._queue.length == 0) { self.emit('idle'); } if (self._queue.length == 0) { return; } self._dispatch(); }) }
javascript
{ "resource": "" }
q11252
_go
train
function _go() { if(workers < concurrency) { var job = queue.shift(); if(job !== undefined) { var worker = job.shift(); job.push(over); workers++; process.nextTick(function nextTickWorker() { worker.apply(null, job); }); return true; } } return false; }
javascript
{ "resource": "" }
q11253
train
function (credentials) { return function () { return this.thenOpen(globals.adminUrl).then(function () { this.fill('#login-form', credentials || globals.credentials, true); }).waitForResource(/login/).thenEvaluate(function () { localStorage.clear(); }); }; }
javascript
{ "resource": "" }
q11254
train
function (opts) { var that = this; return function () { return this.thenOpen(globals.adminPagesUrl) .waitUntilVisible('.js-cms-pagetree-options') .then(that.expandPageTree()) .then(function () { var pageId; var pageNodeId; var data = ''; var href = ''; if (opts && opts.title) { pageId = that.getPageId(opts.title); pageNodeId = that.getPageNodeId(opts.title); } if (pageId) { data = '[data-node-id="' + pageNodeId + '"]'; href = '[href*="' + pageId + '"]'; } return this.then(function () { this.click('.cms-pagetree-jstree .js-cms-pagetree-options' + data); }) .then(that.waitUntilActionsDropdownLoaded()) .then(function () { this.click('.cms-pagetree-jstree [href*="delete"]' + href); }); }) .waitForUrl(/delete/) .waitUntilVisible('input[type=submit]') .then(function () { this.click('input[type=submit]'); }) .wait(1000) .then(that.waitUntilAllAjaxCallsFinish()); }; }
javascript
{ "resource": "" }
q11255
train
function (opts) { var that = this; return function () { return this.then(function () { this.click('.js-cms-pagetree-options[data-node-id="' + opts.page + '"]'); }) .then(that.waitUntilActionsDropdownLoaded()) .then(function () { this.mouse.click('.js-cms-tree-item-copy[data-node-id="' + opts.page + '"]'); }) .wait(100); }; }
javascript
{ "resource": "" }
q11256
train
function (view) { return function () { if ( view === 'structure' && this.exists('.cms-toolbar-item-cms-mode-switcher .cms-btn-active') || view === 'content' && !this.exists('.cms-toolbar-item-cms-mode-switcher .cms-btn-active') ) { return this.wait(100); } return this.waitForSelector('.cms-toolbar-expanded') .then(function () { return this.click('.cms-toolbar-item-cms-mode-switcher .cms-btn'); }) .then(function () { if (view === 'structure') { return this.waitForSelector('.cms-structure-content .cms-dragarea'); } else if (view === 'content') { return this.waitWhileSelector('.cms-structure-mode-structure'); } throw new Error( 'Invalid arguments passed to cms.switchTo, should be either "structure" or "content"' ); }); }; }
javascript
{ "resource": "" }
q11257
train
function (selector) { return function () { return this.then(function () { // if "Expand all" is visible then if (this.visible(selector + ' .cms-dragbar-expand-all')) { this.click(selector + ' .cms-dragbar-expand-all'); } else if (this.visible(selector + ' .cms-dragbar-collapse-all')) { // if not visible, then first "Collapse all" this.click(selector + ' .cms-dragbar-collapse-all'); this.wait(100); this.click(selector + ' .cms-dragbar-expand-all'); } else { throw new Error('Given placeholder has no plugins'); } }); }; }
javascript
{ "resource": "" }
q11258
train
function () { var that = this; return function () { return this.then(function () { if (this.visible('.jstree-closed')) { this.click('.jstree-closed > .jstree-ocl'); // there's no clear way to check if the page was loading // or was already in the DOM return casper .then(that.waitUntilAllAjaxCallsFinish()) .then(that.expandPageTree()); } return casper.wait(1000) .then(that.waitUntilAllAjaxCallsFinish()); }); }; }
javascript
{ "resource": "" }
q11259
train
function (title) { // important to pass single param, because casper acts // weirdly with single key objects https://github.com/n1k0/casperjs/issues/353 return casper.evaluate(function (anchorTitle) { return CMS.$('.jstree-anchor').map(function () { var anchor = CMS.$(this); if (anchor.text().trim() === anchorTitle) { return anchor.parent().data('nodeId'); } }).toArray(); }, title); }
javascript
{ "resource": "" }
q11260
getXPathForAdminSection
train
function getXPathForAdminSection(options) { var xpath = '//div[.//caption/a[contains(text(), "' + options.section + '")]]'; if (options.link) { xpath += '//th[./a[contains(text(), "' + options.row + '")]]'; xpath += '/following-sibling::td/a[contains(text(), "' + options.link + '")]'; } else { xpath += '//th/a[contains(text(), "' + options.row + '")]'; } return xpath; }
javascript
{ "resource": "" }
q11261
workerMessageHandler
train
function workerMessageHandler(e) { const msg = e.data; var cb; SHOULD_LOG && console.log("Worker received message: " + JSON.stringify(msg)); switch (msg.event) { case "connInit": workerInitialized = true; workerQueue.forEach(workerInvoke); workerQueue = []; break; case "connStatus": const response = msg.data || {}; const statusCode = response.status; if (connStatus[msg.conn]) { switch (statusCode) { case 200: connStatus[msg.conn].ready = true; break; case 401: // authorization error, need to log in connStatus[msg.conn].ready = false; connStatus[msg.conn].user = null; connStatus[msg.conn].anonymous = true; break; default: console.warn("Invalid connection response status: " + JSON.stringify(response)); break; } } break; case "connClosed": cb = callbackRegistry[msg.ref]; if (cb) { delete callbackRegistry[msg.ref]; cb(msg.data); } break; case "connLogout": cb = callbackRegistry[msg.ref]; if (cb) { delete callbackRegistry[msg.ref]; cb(msg.data); } break; case "setState": const comp = componentIdx[msg.ref]; if (comp) { comp.setState(msg.data); } else { SHOULD_LOG && console.warn("Component no longer registered: " + msg.ref); } break; case "remoteInvoke": // check for a callback cb = callbackRegistry[msg.ref]; if (cb) { delete callbackRegistry[msg.ref]; cb(msg.data); } break; case "login": // if login successful, update conn's connStatus if (msg.data.status === 200) { connStatus[msg.conn].token = msg.data.body.token; connStatus[msg.conn].user = msg.data.body.user; connStatus[msg.conn].anonymous = msg.data.body.anonymous; } // if there was a callback passed to login(), execute cb = callbackRegistry[msg.ref]; if (cb) { delete callbackRegistry[msg.ref]; cb(msg.data); } break; default: SHOULD_LOG && console.warn("Unreconized event from worker: " + msg.event + ". Full message: " + JSON.stringify(msg)); break; } return; }
javascript
{ "resource": "" }
q11262
isClosed
train
function isClosed(connId) { const connObj = connStatus[connId]; return (connObj && Object.keys(connObj).length === 0); }
javascript
{ "resource": "" }
q11263
getMissingVars
train
function getMissingVars(flurQL, opts) { const vars = flurQL.vars; if (!vars || !Array.isArray(vars)) { return []; } if (opts && opts.vars) { return vars.filter((v) => { return !opts.vars[v]; }); } else { return vars; } }
javascript
{ "resource": "" }
q11264
fillDefaultResult
train
function fillDefaultResult(query) { if (!query) return {}; const graph = query.graph || query; if (!Array.isArray(graph)) { // invalid graph return; } var defaultResult = {}; graph.map(([stream, opts]) => { if (opts.as) { defaultResult[opts.as] = null; } else { defaultResult[stream] = null; } }); return defaultResult; }
javascript
{ "resource": "" }
q11265
loadConfigCore
train
function loadConfigCore(configItem) { if (typeof configItem === "string") { configItem = fs.readFileSync(configItem, "utf8"); } else if (typeof configItem === "object") { // do nothing } else { throw new Error("Unexpected config item type."); } return configItem; }
javascript
{ "resource": "" }
q11266
parseConfigCore
train
function parseConfigCore(configItem) { if (isObject(configItem) || isJSON(configItem)) { try { configItem = JSON.parse(configItem); } catch (err) { // configItem is Object. if (/^Unexpected token.*/.test(err.message)) { return configItem; } } return configItem; } }
javascript
{ "resource": "" }
q11267
findBlogs
train
function findBlogs (pRequest, pResponse) { var query = pRequest.params.query, posts = cache.get('posts') || {}; var blogsToSend = []; for (var key in posts) { var post = new Post(posts[key]); if (post.containsQuery(query)) { blogsToSend.push(posts[key]); } } return pResponse.status(201).send(blogsToSend).end(); }
javascript
{ "resource": "" }
q11268
registerModules
train
function registerModules() { // Dynamic module loading is no longer supported for simplicity. // Module is free to load any of its resources dynamically. // Or an extension can provide dynamic module loading capabilities as needed. if (_scalejs2.default.isApplicationRunning()) { throw new Error('Can\'t register module since the application is already running.', 'Dynamic module loading is not supported.'); } Array.prototype.push.apply(moduleRegistrations, toArray(arguments).filter(function (m) { return m; })); }
javascript
{ "resource": "" }
q11269
take
train
function take(n) { var idx = 0; return map(function (chunk, next) { idx += 1; if (!_.isInteger(n)) { return next(new TypeError('Expected `n` to be an integer.')); } // take n items from the source stream if (idx <= n) { return next(null, chunk); } // drop all other items return next(); }); }
javascript
{ "resource": "" }
q11270
flatten
train
function flatten() { return through.obj(function Transform(data, enc, cb) { var self = this; if (!_.isArray(data)) { return cb(null, data); } data.forEach(function (val) { self.push(val); }); return cb(); }); }
javascript
{ "resource": "" }
q11271
createHopStream
train
function createHopStream(frame_size, hop_size, onFrame, max_data_size) { if(hop_size > frame_size) { throw new Error("Hop size must be smaller than frame size") } max_data_size = max_data_size || frame_size var buffer = new Float32Array(2*frame_size + max_data_size) var ptr = 0 var frame_slices = [] for(var j=0; j+frame_size<=buffer.length; j+=hop_size) { frame_slices.push(buffer.subarray(j, j+frame_size)) } return function processHopData(data) { var i, j, k buffer.set(data, ptr) ptr += data.length for(i=0, j=0; j+frame_size<=ptr; ++i, j+=hop_size) { onFrame(frame_slices[i]) } for(k=0; j<ptr; ) { buffer.set(frame_slices[i], k) var nhops = Math.ceil((k+frame_size) / hop_size)|0 var nptr = nhops * hop_size if(nptr !== k+frame_size) { nhops -= 1 nptr -= hop_size } i += nhops j += (nptr - k) k = nptr } ptr += k - j } }
javascript
{ "resource": "" }
q11272
train
function(file, tasks, options) { /** skip if no tasks or checking Gruntfile */ if (!tasks.length || file && file === 'Gruntfile.js') { return ''; } var result = '* ' + file + ' (' + tasks.length + ')\n\n'; /** iterate over tasks, add data */ tasks.forEach(function(task) { result += ' [' + task.lineNumber + ' - ' + task.priority + '] ' + task.line.trim() + '\n'; result += '\n'; }); return result; }
javascript
{ "resource": "" }
q11273
Client
train
function Client(uri, options) { if (!(this instanceof Client)) { return new Client(uri, options); } this._options = options || {}; this._options.baseURI = uri || 'https://api.storj.io'; }
javascript
{ "resource": "" }
q11274
update
train
function update (data) { this.bind() this.length = data.length this.byteLength = this.length * data.BYTES_PER_ELEMENT this.gl.bufferData(this.type, data, this.usage) }
javascript
{ "resource": "" }
q11275
train
function() { if (arguments.length === 0) return this.__attributes[propname]; var newval = arguments[0]; this.__attributes[propname] = newval; this.emit('change.' + propname, newval); }
javascript
{ "resource": "" }
q11276
errHandler
train
function errHandler(err) { process.stderr.write(chalk.red('Model generation failed!') + '\n'); switch (err.code) { default: case 'PARSE_FAIL': if (!quiet) { process.stderr.write('\n' + err.stack + '\n'); } break; case 'ENOENT': if (!quiet) { process.stderr.write('\n' + err.stack.replace('ENOENT, lstat ', 'unable to find ') + '\n'); } break; } callback(err); }
javascript
{ "resource": "" }
q11277
adjoint
train
function adjoint(out, a) { // Caching this value is nessecary if out == a var a0 = a[0] out[0] = a[3] out[1] = -a[1] out[2] = -a[2] out[3] = a0 return out }
javascript
{ "resource": "" }
q11278
stripColon
train
function stripColon(text) { var i = text.indexOf(":"); if (i >= 0) { text = text.substr(i).trim(); if (text[1] == " ") { text = text.substr(1).trim(); } } return text; }
javascript
{ "resource": "" }
q11279
splitLabel
train
function splitLabel(text) { var label = "", right = ""; var i = text.lastIndexOf(":"); if (i >= 0) { right = text.substr(i + 1).trim(); if (right) { text = text.substr(0, i); i = text.lastIndexOf(" "); if (i >= 0) { label = text.substr(i + 1); if (label) { text = text.substr(0, i); } } } } return [text, label, right]; }
javascript
{ "resource": "" }
q11280
makeHead
train
function makeHead(lLabel, lText, rLabel, rText) { if (!lText) { return ""; } var fillSpace = 78, result = "<div class='line'>"; fillSpace -= 2 + lLabel.length + 1 + lText.length; if (rText) { fillSpace -= 2 + rLabel.length + 2 + rText.length; } if (fillSpace < 0) { fillSpace = 0; } var span = new Span(4, 7, false); span.text = " " + lLabel + " "; result += span.toString(); span.f = 7; span.b = 4; span.text = " " + lText + " ".repeat(fillSpace); result += span.toString(); // result += makeSpan({f:4,b:7,text:" "+lLabel+" "}) + makeSpan({f:7,b:4,text:" "+lText+" ".repeat(fillSpace)}); if (rText) { span.f = 4; span.b = 7; span.text = " " + rLabel + " "; result += span.toString(); span.f = 7; span.b = 4; span.text = " " + rText + " "; result += span.toString(); // result += makeSpan({f:4,b:7,text:" "+rLabel+" "}) + makeSpan({f:7,b:4,text:" "+rText+" "}); } result += "</div>"; return result; }
javascript
{ "resource": "" }
q11281
extractColor
train
function extractColor(text, i, color) { var matches = [], match; text = text.slice(i); while ((match = text.match(/^\x1b\[([\d;]*)m/))) { matches.push(match); text = text.slice(match[0].length); i += match[0].length; } if (!matches.length) { return null; } var tokens = matches.map(function(match){ return match[1].split(";"); }); tokens = Array.prototype.concat.apply([], tokens); var span = color.copy(); span.i = i; var code; for (i = 0; i < tokens.length; i++) { code = +tokens[i]; if (code == 0) { span.reset(); } else if (code == 1) { span.l = true; } else if (code == 5) { span.flash = true; } else if (code == 7) { var t = span.f; span.f = span.b; span.b = t; } else if (code < 40) { span.f = code - 30; } else if (code < 50) { span.b = code - 40; } } return span; }
javascript
{ "resource": "" }
q11282
bbsReader
train
function bbsReader(data) { var i = 0, match, result = ""; var author, title, time, label, board; if ((match = /^(\xa7@\xaa\xcc:.*)\n(.*)\n(.*)\n/.exec(data))) { // draw header author = stripColon(match[1]); title = stripColon(match[2]); time = stripColon(match[3]); // find board var t = splitLabel(author); author = t[0]; label = t[1]; board = t[2]; // 作者 result += makeHead("\xa7@\xaa\xcc", author, label, board); // 標題 result += makeHead("\xbc\xd0\xc3D", title); // 時間 result += makeHead("\xae\xc9\xb6\xa1", time); // ─ result += "<div class='line'><span class='f6'>" + "\xa2w".repeat(39) + "</span></div>"; i += match[0].length; } var span = new Span(7, 0, false), pos = 0, cleanLine = false, cjk = false; result += "<div class='line'>"; for (; i < data.length; i++) { // Special color if (pos == 0) { var ch = data.substr(i, 2); if (ch == "\xa1\xb0") { // ※ cleanLine = true; span.reset(); span.f = 2; } else if (ch == ": ") { // : cleanLine = true; span.reset(); span.f = 6; } } if (data[i] == "\x1b") { // ESC var span2 = extractColor(data, i, span); if (!span2) { span.text += data[i]; pos++; } else if (cjk && data[span2.i] != "\n") { span.text += data[span2.i]; span.halfEnd = true; result += span.toString(); span2.text += span.text.substring(span.text.length - 2); span2.halfStart = true; pos++; i = span2.i; span = span2; cjk = false; } else { cjk = false; result += span.toString(); if (span2.i <= i) { throw new Error("bbs-reader crashed! infinite loop"); } i = span2.i - 1; span = span2; } } else if (data[i] == "\r" && data[i + 1] == "\n") { continue; } else if (data[i] == "\r" || data[i] == "\n") { result += span.toString() + "</div><div class='line'>"; span.text = ""; span.halfStart = false; span.halfEnd = false; cjk = false; if (cleanLine) { span.reset(); cleanLine = false; } pos = 0; } else { if (cjk) { cjk = false; } else if (data.charCodeAt(i) & 0x80) { cjk = true; } span.text += data[i]; pos++; } } result += span.toString() + "</div>"; return { html: result, title: title, author: author, time: time }; }
javascript
{ "resource": "" }
q11283
forEach
train
function forEach(data, task, callback) { var wrapTask, isArray, subject, test, len, i; isArray = Array.isArray(data); i = -1; if (isArray) { subject = data; wrapTask = function wrapTask(next) { task(subject[i], i, next); }; } else { subject = Bound.Object.dissect(data); wrapTask = function wrapTask(next) { task(subject[i].value, subject[i].key, next); }; } len = subject.length; test = function test() { return ++i < len; }; return Blast.Collection.Function['while'](test, wrapTask, callback); }
javascript
{ "resource": "" }
q11284
train
function($, times, N) { N = typeof N === 'undefined' ? 24 : N; return _.chain(times).map(function(time){ // map to back to cheerio'fied object so we can read attr() return $(time); }).filter(function(time){ // filter by instantaneous forecasts only return time.attr("from") == time.attr("to"); }).sortBy(function(time){ // sort by closest to most distant time var from = new Date(time.attr("from")); return Math.abs((new Date()).getTime() - from.getTime()); }).first(N).value(); }
javascript
{ "resource": "" }
q11285
train
function(time){ var tempC = parseFloat(time.find('temperature').eq(0).attr('value')); return { hoursFromNow: Math.ceil(((new Date(time.attr("from"))).getTime() - (new Date()).getTime()) / 1000 / 60 / 60), // Celcius is kept decimal since met.no returns a pleasant formatted value. // Fahrenheit is rounded for reasons of laziness. // TODO: format Fahrenheit value. tempC: tempC, tempF: Math.round((9 / 5 * tempC) + 32) }; }
javascript
{ "resource": "" }
q11286
train
function(lat, lon, done){ var url = "http://api.met.no/weatherapi/locationforecast/1.8/?lat=" + lat + ";lon=" + lon; request(url, function(error, response, body) { if (!error && response.statusCode < 400) { var $ = cheerio.load(body); var nearbyForecasts = closestInstantForecasts($, $("product time"), FORECASTS_COUNT); done(nearbyForecasts.map(createForecastItem)); } else { console.error("error requesting met.no forecast"); done(); } }); }
javascript
{ "resource": "" }
q11287
train
function(visible) { var e = document.getElementById('imc_loading'); if (typeof visible == 'undefined') { return e.classList.contains('loading'); } if (visible) { e.classList.add('loading'); } else { e.classList.remove('loading'); } return visible; }
javascript
{ "resource": "" }
q11288
train
function (crop, setAsCurrent) { var _this = this; // Create image container element var pvDivOuter = document.createElement('div'); pvDivOuter.id = this._image.id + '_' + crop.id; pvDivOuter.classList.add('imc_preview_image_container'); if (setAsCurrent) { pvDivOuter.classList.add('active'); } pvDivOuter.addEventListener( 'click', function () { _this.setActiveCrop(crop); } ); // Create inner container element var pvDivInner = document.createElement('div'); pvDivInner.classList.add('imc_preview_image'); var previewHeight = 90; // Dummy default, will be overriden in _renderUpdatedPreview var previewWidth = IMSoftcrop.Ratio.width(previewHeight, crop.ratio.f); pvDivInner.style.width = IMSoftcrop.Ratio.width(previewHeight, crop.ratio.f) + 'px'; // Create span (title) element, including warning element var pvSpan = document.createElement('span'); var pvSpanEm = document.createElement('em'); var pvWarning = document.createElement('i'); pvWarning.className = 'fa fa-warning'; var pvUsed = document.createElement('b'); var pvUsedCrop = crop; pvUsed.className = 'fa fa-check'; pvUsed.addEventListener( 'click', function(e) { _this.toggleCropUsable(pvUsedCrop) e.preventDefault(); e.stopPropagation(); return false; } ) pvSpanEm.appendChild(document.createTextNode(crop.id)) pvSpan.appendChild(pvUsed); pvSpan.appendChild(pvSpanEm); pvSpan.appendChild(pvWarning); // Create image element var pvImg = document.createElement('img'); pvImg.src = this._image.src; // Put it together pvDivInner.appendChild(pvImg); pvDivInner.appendChild(pvSpan); pvDivOuter.appendChild(pvDivInner); this._previewContainer.appendChild(pvDivOuter); // Render update this._renderUpdatedPreview(crop); }
javascript
{ "resource": "" }
q11289
train
function (crop) { var pvDiv = document.getElementById(this._image.id + '_' + crop.id); if (pvDiv == null || typeof pvDiv != 'object') { return; } var pvDivInner = pvDiv.getElementsByTagName('DIV')[0] var pvImg = pvDiv.getElementsByTagName('IMG')[0]; var previewHeight = window.getComputedStyle(pvDivInner).height.slice(0, -2) var imgDim = this._image.getDimensions(); var previewWidth = IMSoftcrop.Ratio.width(previewHeight, crop.ratio.f); pvDivInner.style.width = previewWidth + 'px'; var cropDim = crop.getDimensions(); var cropRatio = previewWidth / cropDim.w; pvImg.style.height = imgDim.h * cropRatio + 'px'; pvImg.style.marginTop = '-' + cropDim.y * cropRatio + 'px'; pvImg.style.marginLeft = '-' + cropDim.x * cropRatio + 'px'; if (crop.autoCropWarning == true) { pvDiv.classList.add('warning'); } else { pvDiv.classList.remove('warning'); } if (crop.usable == true) { pvDiv.classList.add('usable'); pvDiv.classList.remove('unusable'); } else { pvDiv.classList.add('unusable'); pvDiv.classList.remove('usable'); } }
javascript
{ "resource": "" }
q11290
train
function (canvas) { var c = canvas || this._canvas; var ctx = c.getContext('2d'); var devicePixelRatio = window.devicePixelRatio || 1; var backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1; var ratio = devicePixelRatio / backingStoreRatio; if (devicePixelRatio !== backingStoreRatio) { var oldWidth = this._container.clientWidth; var oldHeight = this._container.clientHeight; c.width = oldWidth * ratio; c.height = oldHeight * ratio; c.style.width = oldWidth + 'px'; c.style.height = oldHeight + 'px'; // now scale the context to counter the fact that we've // manually scaled our canvas element ctx.scale(ratio, ratio); this._scale = ratio; } else { c.width = this._container.clientWidth; c.height = this._container.clientHeight; } }
javascript
{ "resource": "" }
q11291
train
function (url, onImageReady, applyAutocrop) { var _this = this; this.toggleLoadingImage(true); this.clear(); this._applyAutocrop = (applyAutocrop !== false); this._image = new IMSoftcrop.Image( IMSoftcrop.Ratio.hashFnv32a(url), this ); this._image.load( url, function () { _this.setZoomToImage(false); _this.centerImage(false); _this.updateImageInfo(false); if (_this._autocrop) { _this.detectDetails(); _this.detectFaces(); } else { _this.toggleLoadingImage(false); } _this.applySoftcrops(); _this.redraw(); if (typeof onImageReady === 'function') { onImageReady.call(_this, _this._image); } } ); }
javascript
{ "resource": "" }
q11292
train
function() { var data = { src: this._image.src, width: this._image.w, height: this._image.h, crops: [] }; for(var n = 0; n < this._image.crops.length; n++) { data.crops.push({ id: this._image.crops[n].id, x: Math.round(this._image.crops[n].x), y: Math.round(this._image.crops[n].y), width: Math.round(this._image.crops[n].w), height: Math.round(this._image.crops[n].h), usable: this._image.crops[n].usable }); } return data; }
javascript
{ "resource": "" }
q11293
train
function() { if (this._image instanceof IMSoftcrop.Image == false || !this._image.ready) { return; } // Always make sure all crops are added for(var n = 0; n < this._crops.length; n++) { var crop = this._image.getSoftcrop(this._crops[n].id); if (crop == null) { var crop = this._image.addSoftcrop( this._crops[n].id, this._crops[n].setAsCurrent, this._crops[n].hRatio, this._crops[n].vRatio, this._crops[n].x, this._crops[n].y, this._crops[n].exact, this._crops[n].usable ); if (this._autocrop) { this._image.autocrop(); } this._renderNewCropPreview(crop, this._crops[n].setAsCurrent); } if (this._crops[n].setAsCurrent) { this.setActiveCrop(crop); } } }
javascript
{ "resource": "" }
q11294
train
function (crop) { if (crop instanceof IMSoftcrop.Softcrop !== true) { return; } var div = document.getElementById(this._image.id + '_' + crop.id); var divs = this._previewContainer.getElementsByClassName('imc_preview_image_container'); for (var n = 0; n < divs.length; n++) { divs[n].classList.remove('active'); } div.classList.add('active'); this._crop = crop; this._image.setActiveCrop(crop); this._cropLockedToggle.on = crop.locked; this._cropUsableToggle.on = crop.usable; this.redraw(); this.updateImageInfo(true); }
javascript
{ "resource": "" }
q11295
train
function(crop) { if(typeof crop === 'undefined') { crop = this._crop; } crop.usable = !crop.usable; this._renderUpdatedPreview(crop); if (crop.id === this._crop.id) { this._cropUsableToggle.on = crop.usable; } }
javascript
{ "resource": "" }
q11296
train
function() { if (this._image instanceof IMSoftcrop.Image == false) { return; } this._image.clear(); this._crops = []; this._crop = undefined; this._image = undefined; this._previewContainer.innerHTML = ''; this.redraw(); }
javascript
{ "resource": "" }
q11297
train
function() { if (this._autocrop && this._applyAutocrop) { if (!this.toggleLoadingImage()) { this.toggleLoadingImage(true) } if (this._image.autocrop()) { this.redraw(); } } if (this._waitForWorkers == 0) { this.toggleLoadingImage(false); } }
javascript
{ "resource": "" }
q11298
train
function() { if (!this._image instanceof IMSoftcrop.Image || !this._image.ready) { return; } var body = document.getElementsByTagName('body'); var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); canvas.style.display = 'none'; body[0].appendChild(canvas); canvas.width = this._image.w; canvas.height = this._image.h; canvas.style.width = this._image.w + 'px'; canvas.style.height = this._image.h + 'px'; ctx.drawImage( this._image.image, 0, 0, this._image.w, this._image.h ); var imageData = ctx.getImageData(0, 0, this._image.w, this._image.h); // Cleanup references ctx = null; body[0].removeChild(canvas); canvas = null; body[0] = null; body = null; return imageData; }
javascript
{ "resource": "" }
q11299
train
function() { if (!this._image instanceof IMSoftcrop.Image || !this._image.ready) { return; } var _this = this, imageData = this.getImageData(); this._waitForWorkers++; if (window.Worker) { // If workers are available, thread detection of faces var detectWorker = new Worker(this._detectWorkerUrl); detectWorker.postMessage([ 'details', imageData, this._image.w, this._image.h, this._detectThreshold ]); detectWorker.onmessage = function(e) { _this.addDetectedDetails(e.data); _this._waitForWorkers--; _this.autocropImages(); }; } else { // Fallback to non threaded var data = tracking.Fast.findCorners( tracking.Image.grayscale( imageData.data, this._image.w, this._image.h ), this._image.w, this._image.h, this._detectThreshold ); this.addDetectedDetails(data); this._waitForWorkers--; this.autocropImages(); } }
javascript
{ "resource": "" }