_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q9900
|
train
|
function(options) {
options = options || {};
return this.append([
'thumbnail:width=' + (options.width || 50),
'height=' + (options.height || 50),
'fit=' + (options.fit || 'outbound')
].join(','));
}
|
javascript
|
{
"resource": ""
}
|
|
q9901
|
train
|
function(options) {
options = options || {};
var params = [
'position=' + (options.position || 'top-left'),
'x=' + toInt(options.x || 0),
'y=' + toInt(options.y || 0)
];
if (options.imageIdentifier) {
params.push('img=' + options.imageIdentifier);
}
if (options.width > 0) {
params.push('width=' + toInt(options.width));
}
if (options.height > 0) {
params.push('height=' + toInt(options.height));
}
return this.append('watermark:' + params.join(','));
}
|
javascript
|
{
"resource": ""
}
|
|
q9902
|
train
|
function() {
return new ImageUrl({
transformations: this.transformations.slice(0),
baseUrl: this.rootUrl,
user: this.user,
publicKey: this.publicKey,
privateKey: this.privateKey,
imageIdentifier: this.imageIdentifier,
extension: this.extension,
queryString: this.queryString,
path: this.path
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9903
|
train
|
function(encode) {
var query = this.queryString || '',
transformations = this.transformations,
transformationKey = encode ? 't%5B%5D=' : 't[]=';
if (encode) {
transformations = transformations.map(encodeURIComponent);
}
if (this.transformations.length) {
query += query.length ? '&' : '';
query += transformationKey + transformations.join('&' + transformationKey);
}
return query;
}
|
javascript
|
{
"resource": ""
}
|
|
q9904
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Identifiers)){
return new Identifiers(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Identifiers.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9905
|
train
|
function ( value ) {
if ( this.isObject(value) ) {
//$('.touch_area').get(0).constructor.toString()
return !!( value && value.nodeType === 1 && value.nodeName );
} else {
return /HTML(?:.*)Element/.test( Object.prototype.toString.call(value) );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9906
|
train
|
function ( type ) {
if ( /pointerdown/i.test(type) ) {
type = 'touchstart';
} else if ( /pointermove/i.test(type) ) {
type = 'touchmove';
} else if ( /pointerup/i.test(type) ) {
type = 'touchend';
} else if ( /pointercancel/i.test(type) ) {
type = 'touchcancel';
}
return type;
}
|
javascript
|
{
"resource": ""
}
|
|
q9907
|
train
|
function(anyConfig) {
var result = {};
result.userName = anyConfig.user || anyConfig.userName || defaultConfig.userName;
result.password = anyConfig.password || defaultConfig.password;
result.server = anyConfig.host || anyConfig.server || defaultConfig.host;
result.options = anyConfig.options || {};
result.options.database = anyConfig.database || result.options.database || defaultConfig.options.database;
if (anyConfig.instanceName || result.options.instanceName) {
result.options.instanceName = anyConfig.instanceName || result.options.instanceName;
result.options.port = false;
}
else {
result.options.port = anyConfig.port || result.options.port || defaultConfig.options.port;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q9908
|
train
|
function(request, parameters) {
if (!parameters) {
return;
}
var keys = Object.keys(parameters);
var type = false;
var value = null;
var options = null;
for (var i = keys.length - 1; i >= 0; i--) {
value = parameters[keys[i]];
options = null;
if (value instanceof Object && value.type && value.hasOwnProperty('value')) {
if (value.hasOwnProperty('options')) {
options = value.options;
}
type = value.type;
value = value.value;
}
else {
type = exports.detectParameterType(value);
}
if (!(value instanceof Array)) {
request.addParameter(keys[i], type, value, options);
continue;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9909
|
train
|
function(target) {
target.adapter = exports;
target.query = execQuery.bind(target);
// Tedious cannot execute more than one query at a time, so we have to
// implement a queue for queries, just in case someone tries to set
// multiple queries in a row (like node-any-db-adapter-spec tests do).
target._queue = [];
target._waitingForQueryToFinish = false;
var _execNextInQueue = function(){
if (target._waitingForQueryToFinish) {
return;
}
var query = target._queue.shift();
if (query) {
target._waitingForQueryToFinish = true;
target.emit('query', query);
query.once('close', function(){
target._waitingForQueryToFinish = false;
target.execNextInQueue();
});
target.execSql(query._request);
}
};
target.execNextInQueue = function(query){
if (query) {
target._queue.push(query);
}
if (target._isConnected) {
process.nextTick(_execNextInQueue);
}
};
return target;
}
|
javascript
|
{
"resource": ""
}
|
|
q9910
|
htmlCloseError
|
train
|
function htmlCloseError(options) {
options = options || {};
options.debugLocalNetwork = options.debugLocalNetwork == null ? true : options.debugLocalNetwork;
return function (err, req, res, next) {
var msg = err.message || err.code;
res.statusCode = err.status || err.statusCode || 500;
res.statusMessage = msg;
res.setHeader('Content-Type', 'text/html');
if (msg)
res.setHeader('message', cleanStatusMessage(msg));
var output = '<h3>' + msg + '</h3>'; //message meat
var isDebug = options.debug || (options.debugLocalNetwork && ack.reqres(req, res).req.isLocalNetwork());
var dump = null;
if (isDebug) {
dump = { Error: err };
var jErr = ack.error(err);
if (err.stack) {
output += jErr.getFirstTrace();
dump.stack = jErr.getStackArray();
}
}
else {
dump = err;
}
output += ack(dump).dump('html');
res.end(output);
};
}
|
javascript
|
{
"resource": ""
}
|
q9911
|
jsonCloseError
|
train
|
function jsonCloseError(options) {
if (options === void 0) { options = {}; }
options.debugLocalNetwork = options.debugLocalNetwork == null ? true : options.debugLocalNetwork;
return function (err, req, res, next) {
try {
err = toError(err);
var statusMessage = err.message || err.code;
var statusCode = err.status || err.statusCode || 500;
statusMessage = cleanStatusMessage(statusMessage);
statusCode = statusCode.toString().replace(/[^0-9]/g, '');
res.statusMessage = statusMessage;
res.statusCode = statusCode;
var rtn = {
error: {
message: statusMessage,
code: statusCode,
"debug": {
"stack": err.stack
}
}
};
var isDebug = err.stack && (options.debug || (options.debugLocalNetwork && ack.reqres(req, res).req.isLocalNetwork()));
if (isDebug) {
rtn.error["stack"] = err.stack; //debug requests will get stack traces
}
/*
if(res.json){
res.json(rtn)
}else{
var output = JSON.stringify(rtn)
res.setHeader('message', statusMessage)
res.setHeader('Content-Type','application/json')
res.setHeader('Content-Length', output.length.toString())
res.end( output );
}
*/
var output = JSON.stringify(rtn);
res.setHeader('message', statusMessage);
res.setHeader('Content-Type', 'application/json');
res.setHeader('Content-Length', output.length.toString());
res.end(output);
}
catch (e) {
console.error('ack/modules/reqres/res.js jsonCloseError failed hard');
console.error(e);
console.error('------ original error ------', statusMessage);
console.error(err);
if (next) {
next(err);
}
else {
throw err;
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
q9912
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Attribution)){
return new Attribution(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Attribution.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9913
|
adaptModulePath
|
train
|
function adaptModulePath(modulePath, state) {
// const fileName = state.file.opts.filename;
const options = getStateOptions(state);
const filesMap = createFilesMap(options);
const rootPath = getRootPath(options);
let module = determineContext(modulePath, options);
// Do not generate infinite cyrcular references on empty nodes
if (!module.file) {
return null;
}
// Safeguard against circular calls
if (lastIn === lastOut) {
return null;
}
// Remove relative path prefix before replace
const absoluteModule = path.isAbsolute(module.file);
// Try to replace aliased module
let found = false;
let constantModulePart;
filesMap.keys.filter((k) => {
const d = filesMap.contents[k];
let idx = module.file.search(d.regexp);
if (!found && idx > -1) {
// throw `Found ${d} in ${module.file}`
// constantModulePart = module.file.slice(0, idx) || './';
constantModulePart = './';
if (module.file[idx] === '/') {
idx += 1;
}
const value = d.value[0] === '.' && idx > 0 ? d.value.slice(2) : d.value;
// const value = d.value;
// Replace the alias with it's path and continue
module.file = `${module.file.slice(0, idx) || ''}${value}${module.file.slice(idx + d.expose.length) || ''}`;
found = true;
// Revaluate npm and react flags based on the new mapping
module = determineContext(module.file, options);
return true;
}
return false;
});
// Leave NPM modules as resolved, do not remap and ignore wrongfully formatted strings of form require('npm:')
if (module.npm) {
return module.file || null;
}
// Do not touch direct requires to npm modules (non annotated)
if (module.file.indexOf('./') !== 0 && module.file.indexOf('/') !== 0) {
return null;
}
// Check if any substitution took place
if (found) {
// Module alias substituted
if (!path.isAbsolute(module.file)) {
if (!absoluteModule && module.file[0] !== '.') {
// Add the relative notation back
module.file = `./${module.file}`;
}
}
}
// Do not break node_modules required by name
if (!found && module.file[0] !== '.') {
if (reactOsFileInfer(options)) {
const aux2 = mapForReact(module.file);
if (aux2 !== module.file) {
return aux2;
}
}
return null;
}
// Enforce absolute paths on absolute mode
if (rootPath) {
if (!path.isAbsolute(module.file)) {
module.file = path.join(rootPath, module.file);
if (reactOsFileInfer(options)) {
return mapForReact(module.file);
}
return module.file;
}
// After the node is replaced the visitor will be called again.
// Without this condition these functions will generate a circular loop.
return null;
}
// throw `Gets here: ${JSON.stringify(module.file)}`;
// Do not bother with relative paths that are not aliased
if (!found) {
return null;
}
let moduleMapped = mapToRelative(module.file, constantModulePart, options);
if (moduleMapped.indexOf('./') !== 0) {
moduleMapped = `./${moduleMapped}`;
}
// throw JSON.stringify({
// moduleMapped, modulePath, module, constantModulePart
// }, null, 2);
return moduleMapped !== modulePath ? moduleMapped : null;
}
|
javascript
|
{
"resource": ""
}
|
q9914
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Conclusion)){
return new Conclusion(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Conclusion.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9915
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof EventRole)){
return new EventRole(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(GedcomX.Conclusion.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9916
|
train
|
function(finishedCallback){
self.getUARTProtocolVersion(function(data,error){
self.deviceData.uartProtocolVersion = data;
finishedCallback(error);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9917
|
train
|
function(finishedCallback){
self.getHardwareModel(function(data,error){
self.deviceData.hardwareModel = data;
finishedCallback(error);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9918
|
train
|
function(finishedCallback){
self.getHardwareVersion(function(data,error){
self.deviceData.hardwareVersion = data;
finishedCallback(error);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9919
|
train
|
function(finishedCallback){
self.getFirmwareVersion(function(data,error){
self.deviceData.firmwareVersion = data;
finishedCallback(error);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9920
|
train
|
function (path) {
if (fs.existsSync(path) && fs.statSync(path).isDirectory()) {
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q9921
|
needFix
|
train
|
function needFix (stylecowSupport, task, method) {
const taskSupport = task[method];
if (!taskSupport || !stylecowSupport) {
return true;
}
for (let browser in taskSupport) {
if (stylecowSupport[browser] === false) {
continue;
}
if (method === 'forBrowsersLowerThan' && (taskSupport[browser] === false || stylecowSupport[browser] < taskSupport[browser])) {
return true;
}
if (method === 'forBrowsersUpperOrEqualTo') {
if (taskSupport[browser] === false) {
return false;
}
if (stylecowSupport[browser] >= taskSupport[browser]) {
return true;
}
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q9922
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof AtomSource)){
return new AtomSource(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(AtomSource.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9923
|
transformPropertiesToCamelCase
|
train
|
function transformPropertiesToCamelCase (object) {
var output = {}
for (var _key in object) {
if (typeof object === 'string') { return object.replace(' !important', '') }
var key = _key
var value = object[_key]
if (~key.indexOf('-')) {
var splittedKeys = key.split('-')
splittedKeys = splittedKeys.map(function (v, i) {
return i > 0
// UCFIRST if ! first element
? v.charAt(0).toUpperCase() + v.substr(1) : v
})
key = splittedKeys.join('')
}
output[key] = transformPropertiesToCamelCase(value)
}
return output
}
|
javascript
|
{
"resource": ""
}
|
q9924
|
Item
|
train
|
function Item(jid, node, name) {
Element.call(this, 'item', 'http://jabber.org/protocol/disco#items');
this.jid = jid;
this.node = node;
this.displayName = name;
}
|
javascript
|
{
"resource": ""
}
|
q9925
|
copyIcon
|
train
|
function copyIcon() {
var dest = path.join(process.env.PWD, 'res');
// Make sure the destination exists
mkdir(dest);
return pify(fs.copy.bind(fs), Promise)(src, path.join(dest, 'icon.' + mime.extension(mimetype)));
}
|
javascript
|
{
"resource": ""
}
|
q9926
|
copyHooks
|
train
|
function copyHooks() {
var src = path.join(__dirname, 'hooks');
var dest = path.join(process.env.PWD, 'hooks');
return pify(fs.copy.bind(fs), Promise)(path.join(__dirname, 'platforms.json'), path.join(dest, 'platforms.json'))
.then(function () {
memFsEditor.copyTpl(src, dest, options);
return pify(memFsEditor.commit.bind(memFsEditor))();
})
.then(function () {
// Make all the scripts executable in the Cordova project
fs.readdirSync(src).forEach(function (hook) {
var hookPath = path.join(dest, hook);
fs.readdirSync(hookPath).forEach(function (script) {
fs.chmodSync(path.join(hookPath, script), '755');
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q9927
|
installHookDependencies
|
train
|
function installHookDependencies() {
return Promise.all(hookDependencies.map(function (dependency) {
return pify(npmi, Promise)({name: dependency, path: path.join(process.env.PWD, 'hooks')});
}));
}
|
javascript
|
{
"resource": ""
}
|
q9928
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Note)){
return new Note(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Note.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9929
|
makeWorker
|
train
|
function makeWorker(worker) {
return {
seneca: Seneca().client(worker),
id: worker.id,
up: undefined,
lastCallDuration: -1,
meanCallDuration: -1,
host: worker.host,
port: worker.port,
type: worker.type
}
}
|
javascript
|
{
"resource": ""
}
|
q9930
|
nextWorker
|
train
|
function nextWorker(cb) {
seneca.act('role:loadbalance,hook:balance', {
workers: workers,
lastWorker: lastWorker
}, function (err, worker) {
if (!worker) return cb(new Error('No up backend found'))
lastWorker = worker
cb(null, worker)
})
}
|
javascript
|
{
"resource": ""
}
|
q9931
|
addWorker
|
train
|
function addWorker(worker, cb) {
function ping() {
// A thing to keep in mind that right now it can take very long
// (I think default is 22222 ms) for a request to time out, even
// in scenarios like remote side breaking the connection and
// ECONNREFUSED on reconnect.
madeWorker.seneca.act({ role: 'transport', cmd: 'ping' }, function (err) {
worker.up = !isTaskTimeout(err)
})
}
if (!worker.id) worker.id = nid()
var madeWorker = makeWorker(worker)
madeWorker.pingInterval = setInterval(ping, opts.pingInterval || 1000)
ping()
workers.push(madeWorker)
cb(null, madeWorker)
}
|
javascript
|
{
"resource": ""
}
|
q9932
|
getSubtitlesByFilename
|
train
|
async function getSubtitlesByFilename (filename) {
// TODO: revamp this + add unit tests
return getSubtitlesList(filename)
.then(parseSearchResults)
.then(getBestSearchResult(filename))
.then(getSubtitlesPage)
.then(parseDownloadLink)
.then(downloadZip)
.then(extractSrt)
}
|
javascript
|
{
"resource": ""
}
|
q9933
|
getSubtitlesList
|
train
|
async function getSubtitlesList (filename) {
return request({
method: 'GET',
uri: SUBSCENE_URL + '/subtitles/release',
qs: {
q: filename, // search query
l: '', // language (english)
r: true // released or whatever
}
})
}
|
javascript
|
{
"resource": ""
}
|
q9934
|
parseSearchResults
|
train
|
function parseSearchResults (html) {
const $ = cheerio.load(html)
return $('a')
.filter(function (index, element) {
const spans = $(element).find('span')
return spans.length === 2 && spans.eq(0).text().trim() === 'English'
})
.map(function (index, element) {
const title = $(element).find('span').eq(1).text().trim()
const url = $(element).attr('href')
return new SearchResult({
title: title,
url: url
})
})
.get()
}
|
javascript
|
{
"resource": ""
}
|
q9935
|
downloadZip
|
train
|
async function downloadZip (href) {
return request({
method: 'GET',
uri: SUBSCENE_URL + href,
encoding: null
})
}
|
javascript
|
{
"resource": ""
}
|
q9936
|
extractSrt
|
train
|
function extractSrt (buffer) {
const zip = new AdmZip(buffer)
const srtZipEntry = zip
.getEntries()
.find(zipEntry =>
zipEntry.entryName.endsWith('.srt')
)
return zip.readAsText(srtZipEntry)
}
|
javascript
|
{
"resource": ""
}
|
q9937
|
train
|
function (e) {
var self = this;
if (e) {
self.stopPropagation(e);
}
// Get current filter
var currentFilter = self.filterStateModel.getActiveFilter();
if (currentFilter !== self.filter) {
self.filterStateModel.setActiveFilter(self.filter);
self.filterStateModel.trigger("filter:loaded");
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9938
|
train
|
function (e) {
var self = this;
if (self.isOpen !== true) {
self.open(e);
}
else {
self.close(e);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9939
|
train
|
function (e) {
var self = this;
clearTimeout(self.closeTimeout);
clearTimeout(self.deferCloseTimeout);
if (e) {
if (e.stopPropagation) {
e.stopPropagation();
}
if (e.preventDefault) {
e.preventDefault();
}
e.cancelBubble = true;
}
// Don't do anything if already open
if (self.isOpen) {
return;
}
self.isOpen = true;
self.$el.addClass("open");
// Notify child view
self.dropdownContainerView.open();
}
|
javascript
|
{
"resource": ""
}
|
|
q9940
|
train
|
function (e) {
var self = this;
// Don't do anything if already closed
if (!self.isOpen) {
return;
}
self.isOpen = false;
self.$el.removeClass("open");
// Notify child view
self.dropdownContainerView.close();
}
|
javascript
|
{
"resource": ""
}
|
|
q9941
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Address)){
return new Address(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Address.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9942
|
train
|
function(...path) {
path = pathify(path);
return noUndef(path)
? model.getValueSync(path)
: undefined;
}
|
javascript
|
{
"resource": ""
}
|
|
q9943
|
train
|
function(params) {
/**
* Reckon version
* @type {String}
*/
this.version = '0.1.0';
/**
* Define delimiter that marks beginning of interpolation
* @type {String}
*/
this.delimStart = settings.delimStart;
/**
* Define delimiter that marks end of interpolation
* @type {String}
*/
this.delimEnd = settings.delimEnd;
/**
* Get the text from params
* @type {String}
*/
this.text = typeof params !=="undefined" && params.text !== "undefined" ? params.text : '';
/**
* Get the scope from the params and ensure its an array, if not, make it one
* @type {Array}
*/
this.scopes = typeof params !=="undefined" && typeof params.scope !== "undefined" ? [].concat(params.scope) : [];
/**
* Check if config needs to be applied from the global settings
*/
this.applyConfig();
/**
* Compile the initial input
*/
if (typeof params !=="undefined" && typeof params.text !== "undefined")
this.compile();
}
|
javascript
|
{
"resource": ""
}
|
|
q9944
|
train
|
function(param) {
/**
* Reference the instance
*/
var rInstance = this;
if (typeof param !== "undefined") {
rInstance.text = param.text;
rInstance.scopes = [].concat(param.scope);
}
/**
* The required regexp computed using delims in settings
* @type {RegExp}
*/
var re = new RegExp(['{%(.+?)%}|', this.delimStart, '(.+?)', this.delimEnd].join(''), 'g');
/**
* Save the raw text
* @type {String}
*/
rInstance.raw = rInstance.text;
/**
* Compute and assign to compiledText property of the same object
* @param {String} _ Matched string
* @param {String} $1 Content of first match group
* @param {String} $2 Content of second match group
* @return {String} Interpolated string
*/
rInstance.text = rInstance.text.replace(re, function(_, $1, $2) {
var computed;
/**
* If escaped value is found, interpolation will not happen
*/
if ($1) {
computed = $1;
}
/**
* Matched content, let's interpolate
*/
if ($2) {
/**
* Break out scope variables out of scope's box and evaluate the expr expression
*/
var scopeBox = function(expr, localScope) {
var variables = '';
/**
* If scope is a window object, no need to scopebox it
*/
if (typeof window !== "undefined" ? localScope !== window : true) {
for(var i in localScope) {
variables += 'var ' + i + ' = localScope.' + i + '; ';
}
}
var unbox = '(function() { ' + variables + ' try { return eval(expr);} catch(e) {} })()';
return eval(unbox);
};
if (rInstance.scopes.length) {
var numScopes = rInstance.scopes.length;
for (var i=0;i<numScopes;i++) {
/**
* Current Scope
* @type {String}
*/
var scope = rInstance.scopes[i];
/**
* Get the computation
* @type {Any}
*/
computed = scopeBox($2, scope);
/**
* If the computed property is a function, execute it in the context of the current scope
* @type {Unknown}
*/
if (typeof computed === "function") {
computed = computed.call(scope);
}
/**
* If the computed property is an object, get the string
*/
if (typeof computed === "object") {
computed = computed.toString();
}
/**
* Found what we were looking for, now break the loop
*/
if (computed !== undefined)
break;
}
} else {
/**
* If no scope is passed, let us assume the global scope
* @type {Any}
*/
computed = scopeBox($2, (typeof window !== "undefined" ? window : {}));
}
/**
* If no computations were found, we return the raw matched value back
* @type {String}
*/
computed = computed !== undefined ? computed : _;
}
/**
* Final computed value returned
*/
return computed;
});
/**
* Return self for chaining
*/
return rInstance;
}
|
javascript
|
{
"resource": ""
}
|
|
q9945
|
train
|
function(expr, localScope) {
var variables = '';
/**
* If scope is a window object, no need to scopebox it
*/
if (typeof window !== "undefined" ? localScope !== window : true) {
for(var i in localScope) {
variables += 'var ' + i + ' = localScope.' + i + '; ';
}
}
var unbox = '(function() { ' + variables + ' try { return eval(expr);} catch(e) {} })()';
return eval(unbox);
}
|
javascript
|
{
"resource": ""
}
|
|
q9946
|
train
|
function(setting) {
if (typeof setting === "undefined") {
if (typeof window !== "undefined") {
if (typeof window.reckonSettings !== "undefined") {
if (typeof window.reckonSettings.delimStart) {
settings.delimStart = window.reckonSettings.delimStart;
}
if (typeof window.reckonSettings.delimEnd) {
settings.delimEnd = window.reckonSettings.delimEnd;
}
}
}
} else {
if (typeof setting.delimStart) {
settings.delimStart = setting.delimStart;
}
if (typeof setting.delimEnd) {
settings.delimEnd = setting.delimEnd;
}
}
this.delimStart = settings.delimStart;
this.delimEnd = settings.delimEnd;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9947
|
hash
|
train
|
async function hash (file) {
const filesize = await fileUtil.getFileSize(file)
const chunkSize = 64 * 1024
const firstBytesPromise = fileUtil.readBytes({
file,
chunkSize,
start: 0
})
const lastBytesPromise = fileUtil.readBytes({
file,
chunkSize,
start: filesize - chunkSize
})
const [ firstBytes, lastBytes ] = await Promise.all([firstBytesPromise, lastBytesPromise])
return crypto
.createHash('md5')
.update(firstBytes)
.update(lastBytes)
.digest('hex')
}
|
javascript
|
{
"resource": ""
}
|
q9948
|
controllerTemplateRouteResponse
|
train
|
function controllerTemplateRouteResponse() {
if (this.template) {
let match = this.template.toString().match(/!doctype ([a-z]+)/i),
mime;
// In the context where MIME type is not set, but we have a
// DOCTYPE tag, we can force set the MIME
// We want this here instead of the explicit template definition
// in case the MIME failed earlier
if (match && !this.response.$headers.hasOwnProperty('Content-Type')) {
mime = this.response.$headers[ 'Content-Type' ] =
$MimeType.$$(match[1].toLowerCase());
}
// Check to see if this is an HTML template and has a DOCTYPE
// and that the proper configuration options are set
if (
mime === 'text/html' &&
config.loadDefaultScriptFile &&
(
this.route.hasOwnProperty('useDefaultScriptFile') ||
this.route.useDefaultScriptFile !== false
)
) {
// Check that option is not true
let scriptFile = config.loadDefaultScriptFile === true ?
'application.js' : config.loadDefaultScriptFile;
$resourceLoader(scriptFile);
}
// Pull the response back in from wherever it was before
this.content = this.response.content;
// Render the template into the resoponse
let me = this;
return new Promise(function(resolve) {
// $Compile to parse template strings and app.directives
return $compile(me.template)(
// In the context of the scope
me.$scope
).then(function(template) {
resolve(template);
});
}).then(function(template) {
me.response.content = me.content += template;
me.response.write(me.content);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q9949
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof GDate)){
return new GDate(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(GDate.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9950
|
loadProjectName
|
train
|
function loadProjectName(callback) {
try {
var contents = fs.readFileSync(path.join(__dirname, '../../config.xml'), 'utf-8');
if (contents) {
// Windows is the BOM. Skip the Byte Order Mark.
contents = contents.substring(contents.indexOf('<'));
}
var doc = new et.ElementTree(et.XML(contents));
var root = doc.getroot();
if (root.tag !== 'widget') {
throw new Error('config.xml has incorrect root node name (expected "widget", was "' + root.tag + '")');
}
var tag = root.find('./name');
if (!tag) {
throw new Error('config.xml has no name tag.');
}
return tag.text;
} catch (e) {
console.error('Could not loading config.xml');
throw e;
}
}
|
javascript
|
{
"resource": ""
}
|
q9951
|
updateConfig
|
train
|
function updateConfig(target) {
try {
var contents = fs.readFileSync(path.join(__dirname, '../../config.xml'), 'utf-8');
if (contents) {
// Windows is the BOM. Skip the Byte Order Mark.
contents = contents.substring(contents.indexOf('<'));
}
var doc = new et.ElementTree(et.XML(contents));
var root = doc.getroot();
if (root.tag !== 'widget') {
throw new Error('config.xml has incorrect root node name (expected "widget", was "' + root.tag + '")');
}
var platformElement = doc.find('./platform/[@name="' + target + '"]');
if (platformElement) {
var icons = platformElement.findall('./icon');
for (var i=0; i<icons.length; i++) {
platformElement.remove(icons[i]);
}
} else {
platformElement = new et.Element('platform');
platformElement.attrib.name = target;
doc.getroot().append(platformElement);
}
// Add all the icons
for(var i=0; i<platforms[target].icons.length; i++) {
var iconElement = new et.Element('icon');
iconElement.attrib = {
...platforms[target].icons[i].attributes,
src: 'res/' + target + '/' + platforms[target].icons[i].file
};
platformElement.append(iconElement);
}
fs.writeFileSync(path.join(__dirname, '../../config.xml'), doc.write({indent: 4}), 'utf-8');
} catch (e) {
console.error('Could not load config.xml');
throw e;
}
}
|
javascript
|
{
"resource": ""
}
|
q9952
|
train
|
function (cb) {
// If the hook has been deactivated, just return
if (!sails.config[this.configKey].check) {
sails.log.verbose('Eslint hook deactivated.');
return cb();
} else {
var format = sails.config[this.configKey].formatter || 'stylish';
var patterns = sails.config[this.configKey].patterns || ['api', 'config'];
patterns.forEach(function (pattern) {
if (glob.hasMagic(pattern)) {
glob.sync(pattern).forEach(function (file) {
runLint(file, format);
});
} else {
runLint(pattern, format);
}
});
return cb();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9953
|
getParamAccessor
|
train
|
function getParamAccessor(id, params) {
// easy access
var paramGet = function (prop, alt, required) {
if (arguments.length < 1) {
throw (new Error('expected at least 1 argument'));
}
if (arguments.length < 2) {
required = true;
}
if (params && hasOwnProp(params, prop)) {
return params[prop];
}
if (required) {
if (!params) {
throw (new Error('no params supplied for: ' + id));
}
throw (new Error('missing param property: ' + prop + ' in: ' + id));
}
return alt;
};
paramGet.raw = params;
return paramGet;
}
|
javascript
|
{
"resource": ""
}
|
q9954
|
train
|
function(inDir, outDir){
var name = this.bundleOptions.name;
var opts = this._generateEsperantoOptions(name);
var transpilerName = formatToFunctionName[this.format];
var targetExtension = this.targetExtension;
return esperanto.bundle({
base: inDir,
entry: this.bundleOptions.entry
}).then(function(bundle) {
var compiledModule = bundle[transpilerName](opts);
var fullOutputPath = path.join(outDir, name + '.' + targetExtension);
return writeFile(fullOutputPath, compiledModule.code);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9955
|
train
|
function(inDir, outDir, relativePath, newCache) {
var ext = this._matchingFileExtension(relativePath);
var moduleName = relativePath.slice(0, relativePath.length - (ext.length + 1));
var fullInputPath = path.join(inDir, relativePath);
var fullOutputPath = path.join(outDir, moduleName + '.' + this.targetExtension);
var entry = this._transpileThroughCache(
moduleName,
fs.readFileSync(fullInputPath, 'utf-8'),
newCache
);
mkdirp.sync(path.dirname(fullOutputPath));
fs.writeFileSync(fullOutputPath, entry.output);
}
|
javascript
|
{
"resource": ""
}
|
|
q9956
|
train
|
function(moduleName, source, newCache) {
var key = helpers.hashStrings([moduleName, source]);
var entry = this._transpilerCache[key];
if (entry) {
return newCache[key] = entry;
}
try {
return newCache[key] = {
output: this.toFormat(
source,
this._generateEsperantoOptions(moduleName)
).code
};
} catch(err) {
err.file = moduleName;
throw err;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9957
|
train
|
function () {
var me = this;
me.callParent.apply(me, arguments);
me.entity = me.entity || 'Someone';
}
|
javascript
|
{
"resource": ""
}
|
|
q9958
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof TextValue)){
return new TextValue(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(TextValue.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9959
|
runProc
|
train
|
function runProc(args, cb) {
var stoutBuffer = '',
sterrBuffer = '';
var proc = cp.spawn('java', args, {
cwd: config.rootDir + '/bin'
});
proc.stdout.on('data', function(data) {
stoutBuffer += data;
});
proc.stderr.on('data', function(data) {
sterrBuffer += data;
});
proc.on('close', function(code) {
if (code === null) {
cb(code);
} else {
cb(null, stoutBuffer, sterrBuffer);
}
running--;
});
}
|
javascript
|
{
"resource": ""
}
|
q9960
|
runCMD
|
train
|
function runCMD(options, cb) {
if (options.cb) {
cb = options.cb;
}
var args = ["-cp", ".", "-XX:+TieredCompilation", "-XX:TieredStopAtLevel=1", "TerminalRunner"];
args.push(options.name);
args.push(options.program);
args.push(options.timeLimit);
args.push(options.input);
runProc(args, function() {
observer.emit("runner.finished", options);
cb.apply(this, arguments);
});
}
|
javascript
|
{
"resource": ""
}
|
q9961
|
runInServlet
|
train
|
function runInServlet(request, cb) {
// log("waitingQueue:"+waitingQueue.length+", runningQueue:"+runningQueue.length);
// log("pushed into running");
if (request.cb) {
cb = request.cb;
}
// program to run
var post_data = querystring.stringify({
'name': request.name,
'code': request.program,
'input': request.input,
'timeLimit': request.timeLimit
});
// An object of request to indicate where to post to
var post_options = {
host: '127.0.0.1',
port: server.getPort(),
path: '',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
};
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
var responseString = '';
res.on('data', function(data) {
// clearTimeout(request.timer);
// log(data);
// debugger;
if (/An exception has occurred in the compiler/.test(data) || /RuntimeError: java.lang.ThreadDeath/.test(data)) {
// log("ReWrote the folwoing as timout exception "+data);
// queue.checkQueues();
request.timeOut();
} else {
data = JSON.parse(data);
request.setToDone();
observer.emit("runner.finished", request);
// queue.clearRunning();
// queue.checkQueues();
cb(null, data.stout, data.sterr);
}
// log("finished with one");
});
// res.on('end', function() {
// log('::-----end-----::');
// var data = JSON.parse(responseString);
// log(responseString);
// log('::-----end-----::');
// cb(null, data.stout, data.sterr);
// });
});
post_req.on('error', function(e) {
log("Error while waiting for server response ", e);
request.timeOut();
// cb(e);
});
// request.timer = setTimeout(function () {
// cb(null, "","TimeoutException: Your program ran for more than "+timeLimit+"ms");
// },timeLimit+200);
post_req.write(post_data);
post_req.end();
}
|
javascript
|
{
"resource": ""
}
|
q9962
|
classCase
|
train
|
function classCase(input) {
return input.toUpperCase().replace(/[\-\s](.)/g, function(match, group1) {
return group1.toUpperCase();
});
}
|
javascript
|
{
"resource": ""
}
|
q9963
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Base)){
return new Base(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Base.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9964
|
enter
|
train
|
function enter(path, state) {
regex = state.opts.regex;
if (!regex) {
throw new TypeError("A regex option is required.");
}
pure = function pure(n) {
return (0, _sideEffectsSafe.pureBabylon)(n, state.opts);
};
}
|
javascript
|
{
"resource": ""
}
|
q9965
|
train
|
function(realm, key, ssl) {
// Initialize with a specified realm, key, and a boolean indicating wther
// SSL should be enabled or disabled.
var scheme = 'https';
if (typeof ssl !== 'undefined' && !ssl) {
scheme = 'http';
}
var uri = scheme + '://api.fanout.io/realm/' + realm;
var pubControl = new pubcontrol.PubControlClient(uri);
pubControl.setAuthJwt({'iss': realm}, new Buffer(key, 'base64'));
this.pubControl = pubControl;
}
|
javascript
|
{
"resource": ""
}
|
|
q9966
|
buildOrigin
|
train
|
function buildOrigin(src, href) {
try {
const url = new URL(src, href || location.href);
return url.origin;
} catch (error) {
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
q9967
|
checkOlderIE
|
train
|
function checkOlderIE() {
const ua = navigator.userAgent;
const isIE = ua.indexOf('MSIE') !== -1 || ua.indexOf('Trident') !== -1;
if (!isIE) {
return false;
}
const version = ua.match(/(MSIE\s|Trident.*rv:)([\w.]+)/)[2];
const versionNumber = parseFloat(version);
if (versionNumber < 10) {
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q9968
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof AtomPerson)){
return new AtomPerson(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(AtomPerson.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9969
|
polygonToPSLG
|
train
|
function polygonToPSLG(loops, options) {
if(!Array.isArray(loops)) {
throw new Error('poly-to-pslg: Error, invalid polygon')
}
if(loops.length === 0) {
return {
points: [],
edges: []
}
}
options = options || {}
var nested = true
if('nested' in options) {
nested = !!options.nested
} else if(loops[0].length === 2 && typeof loops[0][0] === 'number') {
//Hack: If use doesn't pass in a loop, then try to guess if it is nested
nested = false
}
if(!nested) {
loops = [loops]
}
//First we just unroll all the points in the dumb/obvious way
var points = []
var edges = []
for(var i=0; i<loops.length; ++i) {
var loop = loops[i]
var offset = points.length
for(var j=0; j<loop.length; ++j) {
points.push(loop[j])
edges.push([ offset+j, offset+(j+1)%loop.length ])
}
}
//Then we run snap rounding to clean up self intersections and duplicate verts
var clean = 'clean' in options ? true : !!options.clean
if(clean) {
cleanPSLG(points, edges)
}
//Finally, we return the resulting PSLG
return {
points: points,
edges: edges
}
}
|
javascript
|
{
"resource": ""
}
|
q9970
|
sourcemapify
|
train
|
function sourcemapify (browserify, options) {
options = options || browserify._options || {};
function write (data) {
if (options.base) {
// Determine the relative path
// from the bundle file's directory to the source file
let base = path.resolve(process.cwd(), options.base);
data.sourceFile = path.relative(base, data.file);
}
if (options.root) {
// Prepend the root path to the file path
data.sourceFile = joinURL(options.root, data.sourceFile);
}
// Output normalized URL paths
data.sourceFile = normalizeSeparators(data.sourceFile);
this.queue(data);
}
// Add our transform stream to Browserify's "debug" pipeline
// https://github.com/substack/node-browserify#bpipeline
configurePipeline();
browserify.on("reset", configurePipeline);
function configurePipeline () {
browserify.pipeline.get("debug").push(new Through(write));
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q9971
|
joinURL
|
train
|
function joinURL (urlA, urlB) {
urlA = urlA || "";
urlB = urlB || "";
let endsWithASlash = urlA.substr(-1) === "/" || urlA.substr(-1) === "\\";
let startsWithASlash = urlB[0] === "/" || urlB[0] === "\\";
if (endsWithASlash || startsWithASlash) {
return urlA + urlB;
}
else {
return urlA + "/" + urlB;
}
}
|
javascript
|
{
"resource": ""
}
|
q9972
|
ToggleAnimation
|
train
|
function ToggleAnimation(target, animation) {
var preset = {
hide: {
hide: 'hide',
focus: 'show',
restore: 'show',
blur: 'hide'
},
scale: {
hide: 'minimize',
focus: 'focus',
restore: 'restore',
}
};
this._preset = preset[animation];
this._target = target;
if (!this._target) {
throw new Error('Invalid BrowserWindow instance');
} else if (!this._preset) {
throw new Error('Unknown type of animation for toggle');
}
}
|
javascript
|
{
"resource": ""
}
|
q9973
|
togglify
|
train
|
function togglify(win, opts) {
// extend options for toggle window
opts = oassign({
animation: 'hide'
}, opts);
win._toggleAction = new ToggleAnimation(win, opts.animation);
// patch toggle function to window
win.toggle = function () {
if (this.isVisible() && this.isFocused()) {
this._toggleAction.hide();
} else if (this.isVisible() && !this.isFocused()) {
this._toggleAction.focus();
} else if (this.isMinimized() || !this.isVisible()) {
this._toggleAction.restore();
}
};
// bind event for default action
win.on('blur', function () {
if (win.isVisible()) {
this._toggleAction.blur();
}
});
return win;
}
|
javascript
|
{
"resource": ""
}
|
q9974
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof SourceCitation)){
return new SourceCitation(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(SourceCitation.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q9975
|
wrapper
|
train
|
function wrapper(matcherName, legacyMatcher){
return function(util, customEqualityTesters){
return {
compare: function(actual, expected){
var scope = {actual: actual}, message, result;
result = legacyMatcher.call(scope, expected)
message = scope.message && scope.message()[result ? 1 : 0];
return {
pass:result,
message : message
}
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q9976
|
applySuperMethod
|
train
|
function applySuperMethod (fn, sup) {
return function () {
var prev, result;
prev = this.sup;
this.sup = sup;
result = fn.apply(this, arguments);
this.sup = prev;
if (typeof this.sup === 'undefined') {
delete this.sup;
}
return result;
};
}
|
javascript
|
{
"resource": ""
}
|
q9977
|
parseCommandLine
|
train
|
function parseCommandLine(args) {
var parsed_cmds = [];
if (args.length <= 2) {
parsed_cmds.push(defaultCommand());
} else {
var cli = args.slice(2);
var pos = 0;
var cmd;
cli.forEach(function(element, index, array) {
//replace alias name with real name.
if (element.indexOf('--') === -1 && element.indexOf('-') === 0) {
cli[index] = alias_map[element];
}
//parse command and args
if (cli[index].indexOf('--') === -1) {
cmd.args.push(cli[index]);
} else {
if (keys[cli[index]] == "undefined") {
throw new Error("not support command:" + cli[index]);
};
pos = index;
cmd = commands[cli[index]];
if (typeof cmd.args == 'undefined') {
cmd.args = [];
};
parsed_cmds.push(cmd);
}
});
};
return parsed_cmds;
}
|
javascript
|
{
"resource": ""
}
|
q9978
|
defaultCommand
|
train
|
function defaultCommand() {
if (keys.length <= 0) {
throw new Error("Error: there is no command at all!");
};
for (var p in commands) {
if (commands[p]["default"]) {
return commands[p];
};
};
if (keys["--help"]) {
return commands["--help"];
} else {
return commands[keys[0]];
};
}
|
javascript
|
{
"resource": ""
}
|
q9979
|
Entry
|
train
|
function Entry(key, val, index) {
this.key = key;
this.val = val;
this.index = index;
}
|
javascript
|
{
"resource": ""
}
|
q9980
|
train
|
function (key, val) {
var entry = this._byKey.get(key);
// reuse entry if the key exists
if (entry) {
this._touch(entry);
entry.val = val;
return;
}
entry = new Entry(key, val, this._head++);
this._byKey.set(key, entry);
this._byOrder[entry.index] = entry;
this._len++;
this._trim();
}
|
javascript
|
{
"resource": ""
}
|
|
q9981
|
train
|
function (key) {
var entry = this._byKey.del(key);
if (!entry) return;
delete this._byOrder[entry.index];
this._len--;
if (this._len === 0) {
this._head = this._tail = 0;
} else {
// update most index if it was most lecently used entry
if (entry.index === this._head - 1) this._pop();
// update least index if it was least lecently used entry
if (entry.index === this._tail) this._shift();
}
return entry.val;
}
|
javascript
|
{
"resource": ""
}
|
|
q9982
|
train
|
function (key) {
var entry = this._byKey.get(key);
if (entry) {
this._touch(entry);
return entry.val;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9983
|
train
|
function (max) {
if (typeof max !== 'number') return this._max;
if (max < 1) throw new TypeError('max should be a positive number');
var shrink = (this._max || 0) > max;
this._max = max;
if (shrink) this._trim();
}
|
javascript
|
{
"resource": ""
}
|
|
q9984
|
train
|
function () {
var count = 0
, tail = this._tail
, head = this._head
, keys = new Array(this._len);
for (var i = tail; i < head; i++) {
var entry = this._byOrder[i];
if (entry) keys[count++] = entry.key;
}
return keys;
}
|
javascript
|
{
"resource": ""
}
|
|
q9985
|
train
|
function (entry) {
// update most number to key
if (entry.index !== this._head - 1) {
var isTail = entry.index === this._tail;
delete this._byOrder[entry.index];
entry.index = this._head++;
this._byOrder[entry.index] = entry;
if (isTail) this._shift();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9986
|
train
|
function () {
var tail = this._tail
, head = this._head;
for (var i = tail; i < head; i++) {
var entry = this._byOrder[i];
if (entry) {
this._tail = i;
return entry;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9987
|
train
|
function () {
var tail = this._tail
, head = this._head;
for (var i = head - 1; i >= tail; i--) {
var headEntry = this._byOrder[i];
if (headEntry) {
this._head = i + 1;
return headEntry;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9988
|
generateMachineKey
|
train
|
async function generateMachineKey () {
let parts = await Promise.all([
randomHex(8),
randomHex(4),
randomHex(4),
randomHex(4),
randomHex(12)
])
return `${parts[0]}-${parts[1]}-${parts[2]}-${parts[3]}-${parts[4]}`
}
|
javascript
|
{
"resource": ""
}
|
q9989
|
train
|
function() {
if (typeof window.Worker === 'undefined' || typeof window.URL === 'undefined') {
return false;
}
try {
/* eslint-disable no-new */
new Worker(window.URL.createObjectURL(
new Blob([''], { type: 'text/javascript' })
));
/* eslint-enable no-new */
} catch (e) {
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q9990
|
train
|
function(buffer, callback) {
if (supportsWorkers) {
// We have a worker queue, push an item into it and start processing
workerQueue.push({ buffer: buffer, callback: callback });
nextMd5Task();
} else {
// We don't have any Web Worker support,
// queue an MD5 operation on the next tick
process.nextTick(function() {
callback(null, md5.ArrayBuffer.hash(buffer));
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9991
|
train
|
function(key, data) {
var shaObj = new Sha('SHA-256', 'TEXT');
shaObj.setHMACKey(key, 'TEXT');
shaObj.update(data);
return shaObj.getHMAC('HEX');
}
|
javascript
|
{
"resource": ""
}
|
|
q9992
|
train
|
function(buffer, callback, options) {
if (options && options.type === 'url') {
readers.getContentsFromUrl(buffer, function(err, data) {
if (err) {
return callback(err);
}
module.exports.md5(data, callback, { binary: true });
});
} else if (buffer instanceof window.File) {
readers.getContentsFromFile(buffer, function(err, data) {
if (err) {
return callback(err);
}
module.exports.md5(data, callback, { binary: true });
});
} else {
// ArrayBuffer, then.
process.nextTick(function() {
addMd5Task(buffer, callback);
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9993
|
template
|
train
|
function template(pattern) {
return app.src(pattern, { cwd: path.join(__dirname, 'templates') })
.pipe(app.renderFile('*')).on('error', console.error)
.pipe(app.conflicts(app.cwd))
.pipe(app.dest(app.options.dest || app.cwd));
}
|
javascript
|
{
"resource": ""
}
|
q9994
|
$$safeEvalFn
|
train
|
function $$safeEvalFn(str) {
let keyStr = '';
// Perform any parsing that needs to be performed on the scope value
for (let key in this) {
let val = this[ key ];
if (!val && val !== 0 && val !== '') {
continue;
} else if (
typeof val === 'symbol' ||
typeof val === 'string'
) {
val = `"${val}"`;
} else if (typeof val === 'object') {
val = JSON.stringify(val);
}
// I don't like having to use var here
keyStr += `var ${key}=${val};`;
}
// Literal eval is executed in its own context here to reduce security issues
/* eslint-disable */
return eval([ keyStr, str ].join(''));
/* eslint-enable */
}
|
javascript
|
{
"resource": ""
}
|
q9995
|
train
|
function(callback){
var msg = ubeacon.getCommandString( false, ubeacon.uartCmd.led, new Buffer('03','hex') , false );
ubeacon.sendMeshRemoteManagementMessage( program.destinationAddress, msg.toString(), null);
setTimeout(callback, 2000);
}
|
javascript
|
{
"resource": ""
}
|
|
q9996
|
train
|
function(org) {
var url = decodeURIComponent(org.toString());
urlOutput.empty().attr('href', url);
url = url.replace(/.*?\/users\//g, '/users/');
url = url.replace(/Token=(.{10}).*/g, 'Token=$1...');
var parts = url.split('?'), param;
var params = parts[1].replace(/t\[\]=maxSize.*?&/g, '').split('&');
// Base url
$('<div />').text(parts[0]).appendTo(urlOutput);
for (var i = 0, prefix; i < params.length; i++) {
prefix = i > 0 ? '&' : '?';
parts = params[i].split(/t\[\]=/);
param = prefix + parts[0];
if (parts.length > 1) {
var args = [], trans = parts[1].split(':');
param = prefix + 't[]=<span class="transformation">' + trans[0] + '</span>';
if (trans.length > 1) {
var items = trans[1].split(',');
for (var t = 0; t < items.length; t++) {
var c = items[t].split('='), x = '';
x += '<span class="param">' + c[0] + '</span>=';
x += '<span class="value">' + c[1] + '</span>';
args.push(x);
}
param += ':' + args.join(',');
}
}
param = param.replace(/(.*?=)/, '<strong>$1</strong>');
$('<div />').html(param).appendTo(urlOutput);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9997
|
train
|
function(err, imageIdentifier, res) {
// Remove progress bar
bar.css('width', '100%');
progress.animate({ opacity: 0}, {
duration: 1000,
complete: function() {
$(this).remove();
}
});
// Check for any XHR errors (200 means image already exists)
if (err && res && res.headers && res.headers['X-Imbo-Error-Internalcode'] !== 200) {
if (err === 'Signature mismatch') {
err += ' (probably incorrect private key)';
}
/* eslint no-alert: 0 */
return window.alert(err);
} else if (err) {
return window.alert(err);
}
// Build an Imbo-url
var result = $('#result').removeClass('hidden');
var url = client.getImageUrl(imageIdentifier);
$('#image-identifier').text(imageIdentifier).attr('href', url.toString());
result.find('img').attr('src', url.maxSize({ width: result.width() }).toString());
updateUrl(url);
if (!active) {
$('#controls [data-transformation="border"]').on('click', function() {
url.border({ color: 'bf1942', width: 5, height: 5 });
});
$('#controls button').on('click', function() {
var btn = $(this),
transformation = btn.data('transformation'),
args = btn.data('args'),
pass = args ? (args + '').split(',') : [];
url[transformation].apply(url, pass);
if (transformation === 'reset') {
url.maxSize({ width: result.width() });
}
updateUrl(url);
result.find('img').attr('src', url.toString());
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9998
|
train
|
function(data, callback) {
var set = _assembleTask(data, workFlow[meth][url].merg);
if (set.err) throw new Error('Invalid workflow: ' + set.tasks);
async.series(set.tasks, function(err, results) {
return callback(err, {
'sync': data.sync,
'async': data.async,
'merg': results
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9999
|
render
|
train
|
function render(view, options) {
var self = this;
options = options || {};
for (var name in settings._filters) {
options[name] = settings._filters[name];
}
if (settings.helpers) {
for (var k in settings.helpers) {
var helper = settings.helpers[k];
if (typeof helper === 'function') {
helper = helper(self.req, self);
}
if (!options.hasOwnProperty(k)) {
options[k] = helper;
}
}
}
if (settings.filters) {
for (var name in settings.filters) {
options[name] = settings.filters[name];
}
}
// add request to options
if (!options.request) {
options.request = self.req;
}
// render view template
_render(view, options, function (err, str) {
if (err) {
return self.req.next(err);
}
var layout = typeof options.layout === 'string' ? options.layout : settings.layout;
if (options.layout === false || !layout) {
return send(self, str);
}
// render layout template, add view str to layout's locals.body;
options.body = str;
_render(layout, options, function (err, str) {
if (err) {
return self.req.next(err);
}
send(self, str);
});
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.