_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q4400
|
triggerDropdownAutocomplete
|
train
|
function triggerDropdownAutocomplete(){
// First check with the autocomplete words (the ones that are not objects
var autocomplete = [],
suggestions = [],
text = $scope.areaData,
position = getCharacterPosition(),
lastWord = text.substr(0, position).split(/[\s\b{}]/);
// Get the last typed word
lastWord = lastWord[lastWord.length-1];
$scope.areaConfig.autocomplete.forEach(function(autoList){
autoList.words.forEach(function(word){
if(typeof(word) === 'string' && autocomplete.indexOf(word) < 0){
if(lastWord.length > 0 || lastWord.length < 1 && autoList.autocompleteOnSpace){
autocomplete.push(word);
}
}
});
});
if ($scope.areaConfig.dropdown !== undefined){
$scope.areaConfig.dropdown.forEach(function(element){
if(typeof(element.trigger) === 'string' && autocomplete.indexOf(element.trigger) < 0){
autocomplete.push(element.trigger);
}
});
}
// Now with the list, filter and return
autocomplete.forEach(function(word){
if(lastWord.length < word.length && word.toLowerCase().substr(0, lastWord.length) === lastWord.toLowerCase()){
suggestions.push({
display: $sce.trustAsHtml(word),
data: null
});
}
});
$scope.dropdown.customSelect = null;
$scope.dropdown.current = 0;
$scope.dropdown.content = suggestions;
}
|
javascript
|
{
"resource": ""
}
|
q4401
|
smartEmailDetails
|
train
|
function smartEmailDetails(details, callback) {
createsend.get('transactional/smartemail/'+details.smartEmailID, null, null, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
}
|
javascript
|
{
"resource": ""
}
|
q4402
|
sendSmartEmail
|
train
|
function sendSmartEmail(details, callback) {
createsend.post('transactional/smartemail/'+details.smartEmailID+'/send', null, details, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
}
|
javascript
|
{
"resource": ""
}
|
q4403
|
sendClassicEmail
|
train
|
function sendClassicEmail(details, callback) {
deleteNullProperties(details);
createsend.post('transactional/classicEmail/send', details.clientID, details, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
}
|
javascript
|
{
"resource": ""
}
|
q4404
|
classicEmailGroupList
|
train
|
function classicEmailGroupList(details, callback) {
createsend.get('transactional/classicEmail/groups', details, null, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
}
|
javascript
|
{
"resource": ""
}
|
q4405
|
statistics
|
train
|
function statistics(details, callback) {
deleteNullProperties(details);
createsend.get('transactional/statistics', details, null, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
}
|
javascript
|
{
"resource": ""
}
|
q4406
|
messageDetails
|
train
|
function messageDetails(details, callback) {
createsend.get('transactional/messages/'+details.messageID, details, null, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
}
|
javascript
|
{
"resource": ""
}
|
q4407
|
messageResend
|
train
|
function messageResend(details, callback) {
createsend.post('transactional/messages/'+details.messageID+'/resend', null, null, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
}
|
javascript
|
{
"resource": ""
}
|
q4408
|
diff
|
train
|
function diff(a, b, shallow, isOwn) {
if (a === b) {
return equalObj(a);
}
var diffValue = {};
var equal = true;
for (var key in a) {
if ((!isOwn && key in b) || (isOwn && typeof b != 'undefined' && b.hasOwnProperty(key))) {
if (a[key] === b[key]) {
diffValue[key] = equalObj(a[key]);
} else {
if (!shallow && isValidAttr(a[key], b[key])) {
var valueDiff = diff(a[key], b[key], shallow, isOwn);
if (valueDiff.changed == 'equal') {
diffValue[key] = equalObj(a[key]);
} else {
equal = false;
diffValue[key] = valueDiff;
}
} else {
equal = false;
diffValue[key] = {
changed: 'primitive change',
removed: a[key],
added: b[key]
}
}
}
} else {
equal = false;
diffValue[key] = {
changed: 'removed',
value: a[key]
}
}
}
for (key in b) {
if ((!isOwn && !(key in a)) || (isOwn && typeof a != 'undefined' && !a.hasOwnProperty(key))) {
equal = false;
diffValue[key] = {
changed: 'added',
value: b[key]
}
}
}
if (equal) {
return equalObj(a);
} else {
return {
changed: 'object change',
value: diffValue
}
}
}
|
javascript
|
{
"resource": ""
}
|
q4409
|
escape
|
train
|
function escape (script) {
return script.replace(/\\/g, '\\\\').replace(/\n/g, '\\n')
.replace(/\r/g, '\\r').replace(/\t/g, '\\t').replace(/"/g, '\\"')
}
|
javascript
|
{
"resource": ""
}
|
q4410
|
replaceAll
|
train
|
function replaceAll(source, name, oldStr, newStr) {
const transformedSource = new ReplaceSource(source, name);
const reTester = new RegExp(oldStr, 'g');
let reResult = reTester.exec(source.source());
if (reResult == null) {
return source;
}
while (reResult != null) {
transformedSource.replace(
reResult.index,
reTester.lastIndex - 1,
newStr
);
reResult = reTester.exec(source.source());
}
return transformedSource;
}
|
javascript
|
{
"resource": ""
}
|
q4411
|
train
|
function(promise, expectedState, opt_expectedData, opt_util, opt_customEqualityTesters) {
var info = {};
promise.then(
function(data) {
info.actualData = data;
info.actualState = PROMISE_STATE.RESOLVED;
},
function(data) {
info.actualData = data;
info.actualState = PROMISE_STATE.REJECTED;
});
$scope.$apply(); // Trigger Promise resolution
if (!info.actualState) {
// Trigger $httpBackend flush if any requests are pending
if ($httpBackend) {
try {
$httpBackend.flush();
} catch (err) {
if (err.message !== 'No pending request to flush !') {
throw err;
}
}
}
// Trigger $timeout flush if any deferred tasks are pending
if ($timeout) {
try {
$timeout.flush();
} catch (err) {
if (err.message !== 'No deferred tasks to be flushed') {
throw err;
}
}
}
// Trigger $interval flush if any deferred tasks are pending
if ($interval) {
try {
// Flushing $interval requires an amount of time, I believe this number should flush pretty much anything useful...
$interval.flush(100000);
} catch (err) {
if (err.message !== 'No deferred tasks to be flushed') {
throw err;
}
}
}
}
info.message = 'Expected ' + info.actualState + ' to be ' + expectedState;
info.pass = info.actualState === expectedState;
// If resolve/reject expectations have been made, check the data..
if (opt_expectedData !== undefined && info.pass) {
// Jasmine 2
if (opt_util) {
// Detect Jasmine's asymmetric equality matchers and use Jasmine's own equality test for them
// Otherwise use Angular's equality check since it ignores properties that are functions
if (opt_expectedData && opt_expectedData.asymmetricMatch) {
info.pass = opt_util.equals(info.actualData, opt_expectedData, opt_customEqualityTesters);
} else {
info.pass = angular.equals(info.actualData, opt_expectedData);
}
// Jasmine 1.3
} else {
if (opt_expectedData instanceof jasmine.Matchers.Any ||
opt_expectedData instanceof jasmine.Matchers.ObjectContaining) {
info.pass = opt_expectedData.jasmineMatches(info.actualData);
} else {
info.pass = angular.equals(info.actualData, opt_expectedData);
}
}
var actual = jasmine.pp(info.actualData);
var expected = jasmine.pp(opt_expectedData);
info.message = 'Expected ' + actual + ' to be ' + expected;
}
return info;
}
|
javascript
|
{
"resource": ""
}
|
|
q4412
|
listenBeforeLeavingRoute
|
train
|
function listenBeforeLeavingRoute(route, hook) {
// TODO: Warn if they register for a route that isn't currently
// active. They're probably doing something wrong, like re-creating
// route objects on every location change.
const routeID = getRouteID(route)
let hooks = RouteHooks[routeID]
if (!hooks) {
let thereWereNoRouteHooks = !hasAnyProperties(RouteHooks)
RouteHooks[routeID] = [ hook ]
if (thereWereNoRouteHooks) {
// setup transition & beforeunload hooks
unlistenBefore = history.listenBefore(transitionHook)
if (history.listenBeforeUnload)
unlistenBeforeUnload = history.listenBeforeUnload(beforeUnloadHook)
}
} else {
if (hooks.indexOf(hook) === -1) {
warning(
false,
'adding multiple leave hooks for the same route is deprecated; manage multiple confirmations in your own code instead'
)
hooks.push(hook)
}
}
return function () {
const hooks = RouteHooks[routeID]
if (hooks) {
const newHooks = hooks.filter(item => item !== hook)
if (newHooks.length === 0) {
removeListenBeforeHooksForRoute(route)
} else {
RouteHooks[routeID] = newHooks
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q4413
|
listen
|
train
|
function listen(listener) {
// TODO: Only use a single history listener. Otherwise we'll
// end up with multiple concurrent calls to match.
return history.listen(function (location) {
if (state.location === location) {
listener(null, state)
} else {
match(location, function (error, redirectLocation, nextState) {
if (error) {
listener(error)
} else if (redirectLocation) {
history.transitionTo(redirectLocation)
} else if (nextState) {
listener(null, nextState)
} else {
warning(
false,
'Location "%s" did not match any routes',
location.pathname + location.search + location.hash
)
}
})
}
})
}
|
javascript
|
{
"resource": ""
}
|
q4414
|
train
|
function(args) {
args.unshift("convert");
var ret = execute(args.join(" "));
if (ret.code === 127) {
return grunt.warn(
'You need to have ImageMagick installed in your PATH for this task to work.'
);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4415
|
injectModel
|
train
|
function injectModel(name, config, m) {
const modelConfig = app.think.config('model', undefined, m);
const cacheConfig = app.think.config('cache', undefined, m);
config = helper.parseAdapterConfig(modelConfig, config);
const instance = model(name, config, m);
instance._cacheConfig = cacheConfig;
return instance;
}
|
javascript
|
{
"resource": ""
}
|
q4416
|
parse
|
train
|
function parse(topic) {
var tokens = tokenize(topic).map(process_token);
var result = {
regex: make_regex(tokens),
getParams: make_pram_getter(tokens),
topic: make_clean_topic(tokens)
};
result.exec = exec.bind(result);
return result;
}
|
javascript
|
{
"resource": ""
}
|
q4417
|
exec
|
train
|
function exec(topic) {
var regex = this.regex;
var getParams = this.getParams;
var match = regex.exec(topic);
if (match) return getParams(match);
}
|
javascript
|
{
"resource": ""
}
|
q4418
|
process_token
|
train
|
function process_token(token, index, tokens) {
var last = (index === (tokens.length - 1));
if (token[0] === "+") return process_single(token, last);
else if (token[0] === "#") return process_multi(token, last);
else return process_raw(token, last);
}
|
javascript
|
{
"resource": ""
}
|
q4419
|
process_raw
|
train
|
function process_raw(token) {
var token = escapeRegex(token);
return {
type: "raw",
piece: token + "/",
last: token + "/?"
};
}
|
javascript
|
{
"resource": ""
}
|
q4420
|
make_clean_topic
|
train
|
function make_clean_topic(tokens) {
return tokens.map(function (token) {
if (token.type === "raw") return token.piece.slice(0, -1);
else if (token.type === "single") return "+";
else if (token.type === "multi") return "#";
else return ""; // Wat
}).join("/");
}
|
javascript
|
{
"resource": ""
}
|
q4421
|
make_regex
|
train
|
function make_regex(tokens) {
var str = tokens.reduce(function (res, token, index) {
var is_last = (index == (tokens.length - 1));
var before_multi = (index === (tokens.length - 2)) && (last(tokens).type == "multi");
return res + ((is_last || before_multi) ? token.last : token.piece);
},
"");
return new RegExp("^" + str + "$");
}
|
javascript
|
{
"resource": ""
}
|
q4422
|
make_pram_getter
|
train
|
function make_pram_getter(tokens) {
return function (results) {
// Get only the capturing tokens
var capture_tokens = remove_raw(tokens);
var res = {};
// If the regex didn't actually match, just return an empty object
if (!results) return res;
// Remove the first item and iterate through the capture groups
results.slice(1).forEach(function (capture, index) {
// Retreive the token description for the capture group
var token = capture_tokens[index];
var param = capture;
// If the token doesn't have a name, continue to next group
if (!token.name) return;
// If the token is `multi`, split the capture along `/`, remove empty items
if (token.type === "multi") {
param = capture.split("/");
if (!last(param))
param = remove_last(param);
// Otherwise, remove any trailing `/`
} else if (last(capture) === "/")
param = remove_last(capture);
// Set the param on the result object
res[token.name] = param;
});
return res;
}
}
|
javascript
|
{
"resource": ""
}
|
q4423
|
train
|
function () {
//Render the full file
return ejs.renderFile(file, data, options, function (error, content) {
if (error) {
self.emit("error", error);
return callback(-2);
}
//Call the provided callback with the file content
return callback({
"data": new Buffer(content),
"mimeType": "text/html"
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q4424
|
ParsePath
|
train
|
function ParsePath(u) {
//Parse the url
let p = url.parse(u);
//Get the path name
let pname = p.pathname;
//Check for Windows
if( process.platform === "win32") {
//Remove the first / from the path
//https://github.com/jmjuanes/electron-ejs/pull/4#issuecomment-219254028
pname = pname.substr(1);
}
//Sanitize URL. Spaces turn into `%20` symbols in the path and
//throws a `File Not Found Event`. This fix allows folder paths to have
//spaces in the folder name.
//https://github.com/jmjuanes/electron-ejs/pull/9
return pname.replace(/\s/g, " ").replace(/%20/g, " ");
}
|
javascript
|
{
"resource": ""
}
|
q4425
|
linearRegression
|
train
|
function linearRegression(functionValuesX, functionValuesY){
var regression = {}
, x = functionValuesX
, y = functionValuesY
, n = y.length
, sum_x = 0
, sum_y = 0
, sum_xy = 0
, sum_xx = 0
, sum_yy = 0
for (var i = 0; i < y.length; i++) {
sum_x += x[i]
sum_y += y[i]
sum_xy += (x[i]*y[i])
sum_xx += (x[i]*x[i])
sum_yy += (y[i]*y[i])
}
regression.slope = (n * sum_xy - sum_x * sum_y) / (n*sum_xx - sum_x * sum_x)
regression.intercept = (sum_y - regression.slope * sum_x)/n
regression.rSquared = Math.pow((n*sum_xy - sum_x*sum_y)/Math.sqrt((n*sum_xx-sum_x*sum_x)*(n*sum_yy-sum_y*sum_y)),2)
regression.evaluate = function (pointsToEvaluate) {
var x = help.makeItArrayIfItsNot(pointsToEvaluate)
, result = []
, that = this
x.forEach(function (point) {
result.push(that.slope*point + that.intercept)
})
return result
}
return regression
}
|
javascript
|
{
"resource": ""
}
|
q4426
|
shouldProxy
|
train
|
function shouldProxy(hostname, port) {
var NO_PROXY = getEnv('no_proxy').toLowerCase();
if (!NO_PROXY) {
return true; // Always proxy if NO_PROXY is not set.
}
if (NO_PROXY === '*') {
return false; // Never proxy if wildcard is set.
}
return NO_PROXY.split(/[,\s]/).every(function(proxy) {
if (!proxy) {
return true; // Skip zero-length hosts.
}
var parsedProxy = proxy.match(/^(.+):(\d+)$/);
var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy;
var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0;
if (parsedProxyPort && parsedProxyPort !== port) {
return true; // Skip if ports don't match.
}
if (!/^[.*]/.test(parsedProxyHostname)) {
// No wildcards, so stop proxying if there is an exact match.
return hostname !== parsedProxyHostname;
}
if (parsedProxyHostname.charAt(0) === '*') {
// Remove leading wildcard.
parsedProxyHostname = parsedProxyHostname.slice(1);
}
// Stop proxying if the hostname ends with the no_proxy host.
return !stringEndsWith.call(hostname, parsedProxyHostname);
});
}
|
javascript
|
{
"resource": ""
}
|
q4427
|
getEnv
|
train
|
function getEnv(key) {
return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || '';
}
|
javascript
|
{
"resource": ""
}
|
q4428
|
step
|
train
|
function step (pointsToEvaluate, functionValuesX, functionValuesY) {
return help.makeItArrayIfItsNot(pointsToEvaluate).map(function (point) {
return functionValuesY[help.findIntervalLeftBorderIndex(point, functionValuesX)]
})
}
|
javascript
|
{
"resource": ""
}
|
q4429
|
train
|
function (template) {
var tree = this.getTree(template)
var runTimePlugins
// Copy so far runtime plugins were generated.
runTimePlugins = this.runTimePlugins
var blocks = this.blocks
var outerBlocks = this.outerBlocks
this.clear()
// Nope, we do not want to clear the cache.
// Refactor to maintain cache. Until that keep commented.
// this.files = {};
return {
tree: tree,
runTimePlugins: runTimePlugins,
blocks: blocks,
outerBlocks: outerBlocks
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4430
|
train
|
function (expressionClose, expressionOpen, s) {
var sInner = ''
var closeTag = null
var openTag = null
var findIndex = 0
do {
if (closeTag) {
findIndex += closeTag[0].length
}
closeTag = this.findTag(expressionClose, s)
if (!closeTag) {
throw new Error('Unclosed ' + this.ldelim + expressionOpen + this.rdelim)
}
sInner += s.slice(0, closeTag.index)
findIndex += closeTag.index
s = s.slice((closeTag.index + closeTag[0].length))
openTag = this.findTag(expressionOpen, sInner)
if (openTag) {
sInner = sInner.slice((openTag.index + openTag[0].length))
}
} while (openTag)
closeTag.index = findIndex
return closeTag
}
|
javascript
|
{
"resource": ""
}
|
|
q4431
|
train
|
function (s) {
var tree = []
var value = ''
var data
// TODO Refactor, to get this removed.
this.lastTreeInExpression = tree
while (true) {
data = this.lookUp(s.slice(value.length), value)
if (data) {
tree = tree.concat(data.tree)
value = data.value
this.lastTreeInExpression = tree
if (!data.ret) {
break
}
} else {
break
}
}
if (tree.length) {
tree = this.composeExpression(tree)
}
return {tree: tree, value: value}
}
|
javascript
|
{
"resource": ""
}
|
|
q4432
|
train
|
function (text) {
var tree = []
if (this.parseEmbeddedVars) {
var re = /([$][\w@]+)|`([^`]*)`/
for (var found = re.exec(text); found; found = re.exec(text)) {
tree.push({type: 'text', data: text.slice(0, found.index)})
var d = this.parseExpression(found[1] ? found[1] : found[2])
tree.push(d.tree)
text = text.slice(found.index + found[0].length)
}
}
tree.push({type: 'text', data: text})
return tree
}
|
javascript
|
{
"resource": ""
}
|
|
q4433
|
train
|
function (tpl) {
var ldelim = new RegExp(this.ldelim + '\\*')
var rdelim = new RegExp('\\*' + this.rdelim)
var newTpl = ''
for (var openTag = tpl.match(ldelim); openTag; openTag = tpl.match(ldelim)) {
newTpl += tpl.slice(0, openTag.index)
tpl = tpl.slice(openTag.index + openTag[0].length)
var closeTag = tpl.match(rdelim)
if (!closeTag) {
throw new Error('Unclosed ' + ldelim + '*')
}
tpl = tpl.slice(closeTag.index + closeTag[0].length)
}
return newTpl + tpl
}
|
javascript
|
{
"resource": ""
}
|
|
q4434
|
findInArray
|
train
|
function findInArray (arr, val) {
if (Array.prototype.indexOf) {
return arr.indexOf(val)
}
for (var i = 0; i < arr.length; ++i) {
if (arr[i] === val) {
return i
}
}
return -1
}
|
javascript
|
{
"resource": ""
}
|
q4435
|
train
|
function (tree, data) {
// Process the tree and get the output.
var output = this.process(tree, data)
if (this.debugging) {
this.plugins.debug.process([], {
includedTemplates: this.includedTemplates,
assignedVars: data
})
}
this.clear()
return {
output: output.tpl,
smarty: output.smarty
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4436
|
train
|
function (tree, data) {
var res = ''
var s
var node
var tmp
var plugin
for (var i = 0; i < tree.length; ++i) {
node = tree[i]
s = ''
if (node.type === 'text') {
s = node.data
} else if (node.type === 'var') {
s = this.getVarValue(node, data)
} else if (node.type === 'boolean') {
s = !!node.data
} else if (node.type === 'build-in') {
tmp = this.buildInFunctions[node.name].process.call(this, node, data)
if (typeof tmp.tpl !== 'undefined') {
// If tmp is object, which means it has modified, data also
// so copy it back to data.
s = tmp.tpl
data = tmp.data
} else {
// If tmp is string means it has not modified data.
s = tmp
}
} else if (node.type === 'plugin') {
if (this.runTimePlugins[node.name]) {
// Thats call for {function}.
tmp = this.buildInFunctions['function'].process.call(this, node, data)
if (typeof tmp.tpl !== 'undefined') {
// If tmp is object, which means it has modified, data also
// so copy it back to data.
s = tmp.tpl
data = tmp.data
} else {
// If tmp is string means it has not modified data.
s = tmp
}
} else {
plugin = this.plugins[node.name]
if (plugin.type === 'block') {
var repeat = {value: true}
while (repeat.value) {
repeat.value = false
tmp = this.process(node.subTree, data)
if (typeof tmp.tpl !== 'undefined') {
data = tmp.data
tmp = tmp.tpl
}
s += plugin.process.call(
this,
this.getActualParamValues(node.params, data),
tmp,
data,
repeat
)
}
} else if (plugin.type === 'function') {
s = plugin.process.call(this, this.getActualParamValues(node.params, data), data)
}
}
}
if (typeof s === 'boolean' && tree.length !== 1) {
s = s ? '1' : ''
}
if (s === null || s === undefined) {
s = ''
}
if (tree.length === 1) {
return {tpl: s, data: data}
}
res += ((s !== null) ? s : '')
if (data.smarty.continue || data.smarty.break) {
return {tpl: res, data: data}
}
}
return {tpl: res, data: data}
}
|
javascript
|
{
"resource": ""
}
|
|
q4437
|
train
|
function (template, options) {
var parsedTemplate
if (!options) {
options = {}
}
if (options.rdelim) {
// If delimiters are passed locally take them.
this.smarty.rdelim = options.rdelim
} else if (jSmart.prototype.right_delimiter) {
// Backward compatible. Old way to set via prototype.
this.smarty.rdelim = jSmart.prototype.right_delimiter
} else {
// Otherwise default delimiters
this.smarty.rdelim = '}'
}
if (options.ldelim) {
// If delimiters are passed locally take them.
this.smarty.ldelim = options.ldelim
} else if (jSmart.prototype.left_delimiter) {
// Backward compatible. Old way to set via prototype.
this.smarty.ldelim = jSmart.prototype.left_delimiter
} else {
// Otherwise default delimiters
this.smarty.ldelim = '{'
}
if (options.autoLiteral !== undefined) {
// If autoLiteral is passed locally, take it.
this.autoLiteral = options.autoLiteral
} else if (jSmart.prototype.auto_literal !== undefined) {
// Backward compatible. Old way to set via prototype.
this.autoLiteral = jSmart.prototype.auto_literal
}
if (options.debugging !== undefined) {
// If debugging is passed locally, take it.
this.debugging = options.debugging
} else if (jSmart.prototype.debugging !== undefined) {
// Backward compatible. Old way to set via prototype.
this.debugging = jSmart.prototype.debugging
}
if (options.escapeHtml !== undefined) {
// If escapeHtml is passed locally, take it.
this.escapeHtml = options.escapeHtml
} else if (jSmart.prototype.escape_html !== undefined) {
// Backward compatible. Old way to set via prototype.
this.escapeHtml = jSmart.prototype.escape_html
}
// Is template string or at least defined?!
template = String(template || '')
// Generate the tree. We pass delimiters and many config values
// which are needed by parser to parse like delimiters.
jSmartParser.clear()
jSmartParser.rdelim = this.smarty.rdelim
jSmartParser.ldelim = this.smarty.ldelim
jSmartParser.getTemplate = this.getTemplate
jSmartParser.getConfig = this.getConfig
jSmartParser.autoLiteral = this.autoLiteral
jSmartParser.plugins = this.plugins
jSmartParser.preFilters = this.filtersGlobal.pre
// Above parser config are set, lets parse.
parsedTemplate = jSmartParser.getParsed(template)
this.tree = parsedTemplate.tree
this.runTimePlugins = parsedTemplate.runTimePlugins
this.blocks = parsedTemplate.blocks
this.outerBlocks = parsedTemplate.outerBlocks
}
|
javascript
|
{
"resource": ""
}
|
|
q4438
|
train
|
function (data) {
var outputData = ''
if (!(typeof data === 'object')) {
data = {}
}
// Define smarty inside data and copy smarty vars, so one can use $smarty
// vars inside templates.
data.smarty = {}
objectMerge(data.smarty, this.smarty)
// Take default global modifiers, add with local default modifiers.
// Merge them and keep them cached.
this.globalAndDefaultModifiers = jSmart.prototype.defaultModifiersGlobal.concat(this.defaultModifiers)
// Take default global filters, add with local default filters.
// Merge them and keep them cached.
this.globalAndDefaultFilters = jSmart.prototype.filtersGlobal.variable.concat(this.filters.variable)
jSmartProcessor.clear()
jSmartProcessor.plugins = this.plugins
jSmartProcessor.modifiers = this.modifiers
jSmartProcessor.defaultModifiers = this.defaultModifiers
jSmartProcessor.escapeHtml = this.escapeHtml
jSmartProcessor.variableFilters = this.globalAndDefaultFilters
jSmartProcessor.runTimePlugins = this.runTimePlugins
jSmartProcessor.blocks = this.blocks
jSmartProcessor.outerBlocks = this.outerBlocks
jSmartProcessor.debugging = this.debugging
// Capture the output by processing the template.
outputData = jSmartProcessor.getProcessed(this.tree, data, this.smarty)
// Merge back smarty data returned by process to original object.
objectMerge(this.smarty, outputData.smarty)
// Apply post filters to output and return the template data.
return this.applyFilters(jSmart.prototype.filtersGlobal.post.concat(this.filters.post), outputData.output)
}
|
javascript
|
{
"resource": ""
}
|
|
q4439
|
train
|
function (toPrint, indent, indentEnd) {
if (!indent) {
indent = ' '
}
if (!indentEnd) {
indentEnd = ''
}
var s = ''
var name
if (toPrint instanceof Object) {
s = 'Object (\n'
for (name in toPrint) {
if (toPrint.hasOwnProperty(name)) {
s += indent + indent + '[' + name + '] => ' + this.printR(toPrint[name], indent + ' ', indent + indent)
}
}
s += indentEnd + ')\n'
return s
} else if (toPrint instanceof Array) {
s = 'Array (\n'
for (name in toPrint) {
if (toPrint.hasOwnProperty(name)) {
s += indent + indent + '[' + name + '] => ' + this.printR(toPrint[name], indent + ' ', indent + indent)
}
}
s += indentEnd + ')\n'
return s
} else if (toPrint instanceof Boolean) {
var bool = 'false'
if (bool === true) {
bool = 'true'
}
return bool + '\n'
} else {
return (toPrint + '\n')
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4440
|
train
|
function (type, name, callback) {
if (type === 'modifier') {
this.modifiers[name] = callback
} else {
this.plugins[name] = {'type': type, 'process': callback}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4441
|
train
|
function (type, callback) {
(this.tree ? this.filters : jSmart.prototype.filtersGlobal)[((type === 'output') ? 'post' : type)].push(callback)
}
|
javascript
|
{
"resource": ""
}
|
|
q4442
|
train
|
function(el, types, handler, data, selector) {
jBone.setId(el);
var eventHandler = function(e) {
jBone.event.dispatch.call(el, e);
},
events = jBone.getData(el).events,
eventType, t, event;
types = types.split(" ");
t = types.length;
while (t--) {
event = types[t];
eventType = event.split(".")[0];
events[eventType] = events[eventType] || [];
if (events[eventType].length) {
// override with previous event handler
eventHandler = events[eventType][0].fn;
} else {
el.addEventListener && el.addEventListener(eventType, eventHandler, false);
}
events[eventType].push({
namespace: event.split(".").splice(1).join("."),
fn: eventHandler,
selector: selector,
data: data,
originfn: handler
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q4443
|
train
|
function(el, types, handler, selector) {
var removeListener = function(events, eventType, index, el, e) {
var callback;
// get callback
if ((handler && e.originfn === handler) || !handler) {
callback = e.fn;
}
if (events[eventType][index].fn === callback) {
// remove handler from cache
events[eventType].splice(index, 1);
if (!events[eventType].length) {
el.removeEventListener(eventType, callback);
}
}
},
events = jBone.getData(el).events,
l,
eventsByType;
if (!events) {
return;
}
// remove all events
if (!types && events) {
return keys(events).forEach(function(eventType) {
eventsByType = events[eventType];
l = eventsByType.length;
while(l--) {
removeListener(events, eventType, l, el, eventsByType[l]);
}
});
}
types.split(" ").forEach(function(eventName) {
var eventType = eventName.split(".")[0],
namespace = eventName.split(".").splice(1).join("."),
e;
// remove named events
if (events[eventType]) {
eventsByType = events[eventType];
l = eventsByType.length;
while(l--) {
e = eventsByType[l];
if ((!namespace || (namespace && e.namespace === namespace)) &&
(!selector || (selector && e.selector === selector))) {
removeListener(events, eventType, l, el, e);
}
}
}
// remove all namespaced events
else if (namespace) {
keys(events).forEach(function(eventType) {
eventsByType = events[eventType];
l = eventsByType.length;
while(l--) {
e = eventsByType[l];
if (e.namespace.split(".")[0] === namespace.split(".")[0]) {
removeListener(events, eventType, l, el, e);
}
}
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q4444
|
train
|
function(el, event) {
var events = [];
if (isString(event)) {
events = event.split(" ").map(function(event) {
return jBone.Event(event);
});
} else {
event = event instanceof Event ? event : jBone.Event(event);
events = [event];
}
events.forEach(function(event) {
if (!event.type) {
return;
}
el.dispatchEvent && el.dispatchEvent(event);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q4445
|
each
|
train
|
function each(cfg) {
return function(callback) {
return new Promise(function(resolve, reject) {
// create an array to store callbacks
var rl, cbs = [];
// create an interface
try {
rl = readline.createInterface(cfg);
}
catch(err) {
return reject(err);
}
// handle a new line
rl.on('line', function(line) {
cbs.push(callback(line));
});
// handle close
rl.on('close', function() {
Promise.all(cbs).then(function() {
resolve({
lines: cbs.length
});
})
.caught(function(err) {
reject(err);
});
});
});
};
}
|
javascript
|
{
"resource": ""
}
|
q4446
|
train
|
function (message) {
// forward the message to the local promise,
// which will return a response promise
var local = getLocal(message.to).promise;
var response = local.dispatch(message.op, decode(message.args));
var envelope;
// connect the local response promise with the
// remote response promise:
// if the value is ever resolved, send the
// fulfilled value across the wire
response.then(function (resolution) {
try {
resolution = encode(resolution);
} catch (exception) {
try {
resolution = {"!": encode(exception)};
} catch (_exception) {
resolution = {"!": null};
}
}
envelope = JSON.stringify({
"type": "resolve",
"to": message.from,
"resolution": resolution
});
connection.put(envelope);
}, function (reason) {
try {
reason = encode(reason);
} catch (exception) {
try {
reason = encode(exception);
} catch (_exception) {
reason = null;
}
}
envelope = JSON.stringify({
"type": "resolve",
"to": message.from,
"resolution": {"!": reason}
});
connection.put(envelope);
}, function (progress) {
try {
progress = encode(progress);
envelope = JSON.stringify({
"type": "notify",
"to": message.from,
"resolution": progress
});
} catch (exception) {
try {
progress = {"!": encode(exception)};
} catch (_exception) {
progress = {"!": null};
}
envelope = JSON.stringify({
"type": "resolve",
"to": message.from,
"resolution": progress
});
}
connection.put(envelope);
})
.done();
}
|
javascript
|
{
"resource": ""
}
|
|
q4447
|
makeLocal
|
train
|
function makeLocal(id) {
if (hasLocal(id)) {
return getLocal(id).promise;
} else {
var deferred = Q.defer();
locals.set(id, deferred);
return deferred.promise;
}
}
|
javascript
|
{
"resource": ""
}
|
q4448
|
makeRemote
|
train
|
function makeRemote(id) {
var remotePromise = Q.makePromise({
when: function () {
return this;
}
}, function (op, args) {
var localId = makeId();
var response = makeLocal(localId);
_debug("sending:", "R" + JSON.stringify(id), JSON.stringify(op), JSON.stringify(encode(args)));
connection.put(JSON.stringify({
"type": "send",
"to": id,
"from": localId,
"op": op,
"args": encode(args)
}));
return response;
});
remotes.set(r,id);
return remotePromise;
}
|
javascript
|
{
"resource": ""
}
|
q4449
|
create_oauth2_client
|
train
|
function create_oauth2_client () {
var google_client_id = (OPTIONS.GOOGLE_CLIENT_ID) ? OPTIONS.GOOGLE_CLIENT_ID : process.env.GOOGLE_CLIENT_ID;
var google_client_secret = (OPTIONS.GOOGLE_CLIENT_SECRET) ? OPTIONS.GOOGLE_CLIENT_SECRET : process.env.GOOGLE_CLIENT_SECRET;
var base_url = (OPTIONS.BASE_URL) ? OPTIONS.BASE_URL : process.env.BASE_URL;
oauth2_client = new OAuth2Client(
google_client_id,
google_client_secret,
base_url + OPTIONS.REDIRECT_URL
);
return oauth2_client;
}
|
javascript
|
{
"resource": ""
}
|
q4450
|
generate_google_oauth2_url
|
train
|
function generate_google_oauth2_url () {
var access_type = (OPTIONS.access_type) ? OPTIONS.access_type : 'offline';
var approval_prompt = (OPTIONS.approval_prompt) ? OPTIONS.approval_prompt : 'force';
var url = oauth2_client.generateAuthUrl({
access_type: access_type, // set to offline to force a refresh token
approval_prompt: approval_prompt,
scope: OPTIONS.scope // can be a space-delimited string or array of scopes
});
return url;
}
|
javascript
|
{
"resource": ""
}
|
q4451
|
selectionRangesForHTMLNode
|
train
|
function selectionRangesForHTMLNode(node) {
const ranges = [new Range(node.start, node.end)];
if (node.close) {
ranges.push(new Range(node.open.end, node.close.start));
}
return ranges;
}
|
javascript
|
{
"resource": ""
}
|
q4452
|
selectionRangesForCSSNode
|
train
|
function selectionRangesForCSSNode(node) {
const ranges = [new Range(node.start, node.end)];
if (node.type === 'property' && node.valueToken) {
ranges.push(new Range(node.valueToken.start, node.valueToken.end));
} else if (node.type === 'rule' || node.type === 'at-rule') {
ranges.push(new Range(node.contentStartToken.end, node.contentEndToken.start));
}
return ranges;
}
|
javascript
|
{
"resource": ""
}
|
q4453
|
delegateDynamicValidation
|
train
|
function delegateDynamicValidation() {
if (!options.dynamic.settings.trigger) {
return false;
}
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'delegateDynamicValidation()',
'message': 'OK - Dynamic Validation activated on ' + node.length + ' form(s)'
});
// {/debug}
if (!node.find('[' + _data.validation + '],[' + _data.regex + ']')[0]) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'delegateDynamicValidation()',
'arguments': 'node.find([' + _data.validation + '],[' + _data.regex + '])',
'message': 'ERROR - [' + _data.validation + '] not found'
});
// {/debug}
return false;
}
var event = options.dynamic.settings.trigger + delegateSuffix;
if (options.dynamic.settings.trigger !== "focusout") {
event += " change" + delegateSuffix + " paste" + delegateSuffix;
}
$.each(
node.find('[' + _data.validation + '],[' + _data.regex + ']'),
function (index, input) {
$(input).unbind(event).on(event, function (e) {
if ($(this).is(':disabled')) {
return false;
}
//e.preventDefault();
var input = this,
keyCode = e.keyCode || null;
_typeWatch(function () {
if (!validateInput(input)) {
displayOneError(input.name);
_executeCallback(options.dynamic.callback.onError, [node, input, keyCode, errors[input.name]]);
} else {
_executeCallback(options.dynamic.callback.onSuccess, [node, input, keyCode]);
}
_executeCallback(options.dynamic.callback.onComplete, [node, input, keyCode]);
}, options.dynamic.settings.delay);
});
}
);
}
|
javascript
|
{
"resource": ""
}
|
q4454
|
validateForm
|
train
|
function validateForm() {
var isValid = isEmpty(errors);
formData = {};
$.each(
node.find('input:not([type="submit"]), select, textarea').not(':disabled'),
function(index, input) {
input = $(input);
var value = _getInputValue(input[0]),
inputName = input.attr('name');
if (inputName) {
if (/\[]$/.test(inputName)) {
inputName = inputName.replace(/\[]$/, '');
if (!(formData[inputName] instanceof Array)) {
formData[inputName] = [];
}
formData[inputName].push(value)
} else {
formData[inputName] = value;
}
}
if (!!input.attr(_data.validation) || !!input.attr(_data.regex)) {
if (!validateInput(input[0], value)) {
isValid = false;
}
}
}
);
prepareFormData();
return isValid;
}
|
javascript
|
{
"resource": ""
}
|
q4455
|
prepareFormData
|
train
|
function prepareFormData() {
var data = {},
matches,
index;
for (var i in formData) {
if (!formData.hasOwnProperty(i)) continue;
index = 0;
matches = i.split(/\[(.+?)]/g);
var tmpObject = {},
tmpArray = [];
for (var k = matches.length - 1; k >= 0; k--) {
if (matches[k] === "") {
matches.splice(k, 1);
continue;
}
if (tmpArray.length < 1) {
tmpObject[matches[k]] = Number(formData[i]) || formData[i];
} else {
tmpObject = {};
tmpObject[matches[k]] = tmpArray[tmpArray.length - 1];
}
tmpArray.push(tmpObject)
}
data = $.extend(true, data, tmpObject);
}
formData = data;
}
|
javascript
|
{
"resource": ""
}
|
q4456
|
validateInput
|
train
|
function validateInput(input, value) {
var inputName = $(input).attr('name'),
value = value || _getInputValue(input);
if (!inputName) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'validateInput()',
'arguments': '$(input).attr("name")',
'message': 'ERROR - Missing input [name]'
});
// {/debug}
return false;
}
var matches = inputName.replace(/]$/, '').split(/]\[|[[\]]/g),
inputShortName = window.Validation.labels[inputName] ||
options.labels[inputName] ||
$(input).attr(_data.label) ||
matches[matches.length - 1],
validationArray = $(input).attr(_data.validation),
validationMessage = $(input).attr(_data.validationMessage),
validationRegex = $(input).attr(_data.regex),
validationRegexReverse = !($(input).attr(_data.regexReverse) === undefined),
validationRegexMessage = $(input).attr(_data.regexMessage),
validateOnce = false;
if (validationArray) {
validationArray = _api._splitValidation(validationArray);
}
// Validates the "data-validation"
if (validationArray instanceof Array && validationArray.length > 0) {
// "OPTIONAL" input will not be validated if it's empty
if ($.trim(value) === '' && ~validationArray.indexOf('OPTIONAL')) {
return true;
}
$.each(validationArray, function (i, rule) {
if (validateOnce === true) {
return true;
}
try {
validateRule(value, rule);
} catch (error) {
if (validationMessage || !options.submit.settings.allErrors) {
validateOnce = true;
}
error[0] = validationMessage || error[0];
registerError(inputName, error[0].replace('$', inputShortName).replace('%', error[1]));
}
});
}
// Validates the "data-validation-regex"
if (validationRegex) {
var rule = _buildRegexFromString(validationRegex);
// Do not block validation if a regexp is bad, only skip it
if (!(rule instanceof RegExp)) {
return true;
}
try {
validateRule(value, rule, validationRegexReverse);
} catch (error) {
error[0] = validationRegexMessage || error[0];
registerError(inputName, error[0].replace('$', inputShortName));
}
}
return !errors[inputName] || errors[inputName] instanceof Array && errors[inputName].length === 0;
}
|
javascript
|
{
"resource": ""
}
|
q4457
|
validateRule
|
train
|
function validateRule(value, rule, reversed) {
// Validate for "data-validation-regex" and "data-validation-regex-reverse"
if (rule instanceof RegExp) {
var isValid = rule.test(value);
if (reversed) {
isValid = !isValid;
}
if (!isValid) {
throw [options.messages['default'], ''];
}
return;
}
if (options.rules[rule]) {
if (!options.rules[rule].test(value)) {
throw [options.messages[rule], ''];
}
return;
}
// Validate for comparison "data-validation"
var comparison = rule.match(options.rules.COMPARISON);
if (!comparison || comparison.length !== 4) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'validateRule()',
'arguments': 'value: ' + value + ' rule: ' + rule,
'message': 'WARNING - Invalid comparison'
});
// {/debug}
return;
}
var type = comparison[1],
operator = comparison[2],
compared = comparison[3],
comparedValue;
switch (type) {
// Compare input "Length"
case "L":
// Only numeric value for "L" are allowed
if (isNaN(compared)) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'validateRule()',
'arguments': 'compare: ' + compared + ' rule: ' + rule,
'message': 'WARNING - Invalid rule, "L" compare must be numeric'
});
// {/debug}
return false;
} else {
if (!value || eval(value.length + operator + parseFloat(compared)) === false) {
throw [options.messages[operator], compared];
}
}
break;
// Compare input "Value"
case "V":
default:
// Compare Field values
if (isNaN(compared)) {
comparedValue = node.find('[name="' + compared + '"]').val();
if (!comparedValue) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'validateRule()',
'arguments': 'compare: ' + compared + ' rule: ' + rule,
'message': 'WARNING - Unable to find compared field [name="' + compared + '"]'
});
// {/debug}
return false;
}
if (!value || !eval('"' + encodeURIComponent(value) + '"' + operator + '"' + encodeURIComponent(comparedValue) + '"')) {
throw [options.messages[operator].replace(' characters', ''), compared];
}
} else {
// Compare numeric value
if (!value || isNaN(value) || !eval(value + operator + parseFloat(compared))) {
throw [options.messages[operator].replace(' characters', ''), compared];
}
}
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q4458
|
registerError
|
train
|
function registerError(inputName, error) {
if (!errors[inputName]) {
errors[inputName] = [];
}
error = error.capitalize();
var hasError = false;
for (var i = 0; i < errors[inputName].length; i++) {
if (errors[inputName][i] === error) {
hasError = true;
break;
}
}
if (!hasError) {
errors[inputName].push(error);
}
}
|
javascript
|
{
"resource": ""
}
|
q4459
|
resetOneError
|
train
|
function resetOneError(inputName, input, label, container, group) {
delete errors[inputName];
if (container) {
//window.Validation.hasScrolled = false;
if (options.submit.settings.inputContainer) {
(group ? label : input).parentsUntil(node, options.submit.settings.inputContainer).removeClass(options.submit.settings.errorClass);
}
label && label.removeClass(options.submit.settings.errorClass);
input.removeClass(options.submit.settings.errorClass);
if (options.submit.settings.display === 'inline') {
container.find('[' + _data.errorList + ']').remove();
}
} else {
if (!input) {
input = node.find('[name="' + inputName + '"]');
if (!input[0]) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'resetOneError()',
'arguments': '[name="' + inputName + '"]',
'message': 'ERROR - Unable to find input by name "' + inputName + '"'
});
// {/debug}
return false;
}
}
input.trigger('coucou' + resetSuffix);
}
}
|
javascript
|
{
"resource": ""
}
|
q4460
|
destroy
|
train
|
function destroy() {
resetErrors();
node.find('[' + _data.validation + '],[' + _data.regex + ']').off(delegateSuffix + ' ' + resetSuffix);
node.find(options.submit.settings.button).off(delegateSuffix).on('click' + delegateSuffix, function () {
$(this).closest('form')[0].submit();
});
//delete window.Validation.form[node.selector];
return true;
}
|
javascript
|
{
"resource": ""
}
|
q4461
|
train
|
function (node, validation) {
var self = this;
validation = self._splitValidation(validation);
if (!validation) {
return false;
}
return node.each(function () {
var $this = $(this),
validationData = $this.attr(_data.validation),
validationArray = (validationData && validationData.length) ? self._splitValidation(validationData) : [],
oneValidation,
validationIndex;
if (!validationArray.length) {
$this.removeAttr(_data.validation);
return true;
}
for (var i = 0; i < validation.length; i++) {
oneValidation = self._formatValidation(validation[i]);
validationIndex = $.inArray(oneValidation, validationArray);
if (validationIndex !== -1) {
validationArray.splice(validationIndex, 1);
}
}
if (!validationArray.length) {
$this.removeAttr(_data.validation);
return true;
}
$this.attr(_data.validation, self._joinValidation(validationArray));
});
}
|
javascript
|
{
"resource": ""
}
|
|
q4462
|
train
|
function (ruleObj) {
if (!ruleObj.rule || (!ruleObj.regex && !ruleObj.message)) {
// {debug}
window.Debug.log({
'function': '$.alterValidationRules()',
'message': 'ERROR - Missing one or multiple parameter(s) {rule, regex, message}'
});
window.Debug.print();
// {/debug}
return false;
}
ruleObj.rule = ruleObj.rule.toUpperCase();
if (ruleObj.regex) {
var regex = _buildRegexFromString(ruleObj.regex);
if (!(regex instanceof RegExp)) {
// {debug}
window.Debug.log({
'function': '$.alterValidationRules(rule)',
'arguments': regex.toString(),
'message': 'ERROR - Invalid rule'
});
window.Debug.print();
// {/debug}
return false;
}
_rules[ruleObj.rule] = regex;
}
if (ruleObj.message) {
_messages[ruleObj.rule] = ruleObj.message;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q4463
|
findNextNonSpacePoint
|
train
|
function findNextNonSpacePoint(editor, pos) {
const stream = new BufferStreamReader(editor.getBuffer(), pos);
stream.eatWhile(isSpace);
return stream.pos;
}
|
javascript
|
{
"resource": ""
}
|
q4464
|
findPreviousNonSpacePoint
|
train
|
function findPreviousNonSpacePoint(editor, pos) {
const stream = new BufferStreamReader(editor.getBuffer(), pos);
while (!stream.sof()) {
if (!isSpace(stream.backUp(1))) {
stream.next();
break;
}
}
return stream.pos;
}
|
javascript
|
{
"resource": ""
}
|
q4465
|
joinTag
|
train
|
function joinTag(editor, node, syntax) {
// Remove everything between the end of opening tag and the end of closing tag
const open = getText(editor, node.open);
const m = open.match(/\s*>$/);
const start = node.open.end.translate([0, m ? -m[0].length : 0]);
editor.setTextInBufferRange(new Range(start, node.end),
selfClosingStyle[syntax] || selfClosingStyle.xhtml);
}
|
javascript
|
{
"resource": ""
}
|
q4466
|
comment
|
train
|
function comment(editor, range, modelType) {
const commentParts = modelComments[modelType];
editor.setTextInBufferRange(new Range(range.end, range.end), ` ${commentParts.after}`);
editor.setTextInBufferRange(new Range(range.start, range.start), `${commentParts.before} `);
}
|
javascript
|
{
"resource": ""
}
|
q4467
|
uncomment
|
train
|
function uncomment(editor, range, modelType) {
const commentParts = modelComments[modelType];
const stream = new BufferStreamReader(editor.getBuffer(), range.start, range);
// narrow down comment range till meanful content
stream.pos = range.start.translate([0, commentParts.before.length]);
stream.eatWhile(isSpace);
stream.start = stream.pos;
// Make sure comment ends with proper token
stream.pos = range.end.translate([0, -commentParts.after.length]);
if (editor.getTextInBufferRange([stream.pos, range.end]) === commentParts.after) {
while (!stream.sof()) {
if (!isSpace(stream.backUp(1))) {
stream.next();
break;
}
}
} else {
stream.pos = range.end;
}
const start = new Range(range.start, stream.start);
const end = new Range(stream.pos, range.end);
const delta = {
start: editor.getTextInBufferRange(start).length,
end: editor.getTextInBufferRange(end).length
};
editor.setTextInBufferRange(end, '');
editor.setTextInBufferRange(start, '');
return delta;
}
|
javascript
|
{
"resource": ""
}
|
q4468
|
commentsInRange
|
train
|
function commentsInRange(model, range) {
const intersects = token => getRange(token).intersectsWith(range, true);
if (model.type === 'html') {
// in html model, comments are nodes in model
return iterate(model.dom, node => node.type === 'comment' && intersects(node));
}
if (model.type === 'stylesheet') {
// in stylesheet model, comments are stored as separate tokens, they
// can’t be a part of model since they might be a part of selector or
// property value
return model.dom.comments.filter(intersects);
}
return [];
}
|
javascript
|
{
"resource": ""
}
|
q4469
|
resolveRelative
|
train
|
function resolveRelative(base, filePath) {
return getBasePath(base)
.then(basePath => tryFile(path.resolve(basePath, filePath)));
}
|
javascript
|
{
"resource": ""
}
|
q4470
|
getBasePath
|
train
|
function getBasePath(base) {
return new Promise((resolve, reject) => {
if (base && typeof base.getPath === 'function') {
const editorFile = base.getPath();
if (!editorFile) {
return reject(new Error('Unable to get base path: editor contains unsaved file'));
}
base = path.dirname(editorFile);
}
if (!base || typeof base !== 'string') {
reject(new Error(`Unable to get base path from ${base}`));
} else {
resolve(base);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q4471
|
isEmpty
|
train
|
function isEmpty(val) {
if (val === 0 || typeof val === 'boolean') {
return false;
}
if (val == null) {
return true;
}
if (utils.isObject(val)) {
val = Object.keys(val);
}
if (!val.length) {
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q4472
|
getImageSizeFromFile
|
train
|
function getImageSizeFromFile(file) {
return new Promise((resolve, reject) => {
const isDataUrl = file.match(/^data:.+?;base64,/);
if (isDataUrl) {
// NB should use sync version of `sizeOf()` for buffers
try {
const data = Buffer.from(file.slice(isDataUrl[0].length), 'base64');
return resolve(sizeForFileName('', sizeOf(data)));
} catch (err) {
return reject(err);
}
}
sizeOf(file, (err, size) => {
if (err) {
reject(err);
} else {
resolve(sizeForFileName(path.basename(file), size));
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q4473
|
getImageSizeFromURL
|
train
|
function getImageSizeFromURL(url) {
return new Promise((resolve, reject) => {
url = parseUrl(url);
const transport = url.protocol === 'https:' ? https : http;
transport.get(url, resp => {
const chunks = [];
let bufSize = 0;
const trySize = chunks => {
try {
const size = sizeOf(Buffer.concat(chunks, bufSize));
resp.removeListener('data', onData);
resp.destroy(); // no need to read further
resolve(sizeForFileName(path.basename(url.pathname), size));
} catch(err) {
// might not have enough data, skip error
}
};
const onData = chunk => {
bufSize += chunk.length;
chunks.push(chunk);
trySize(chunks);
};
resp
.on('data', onData)
.on('end', () => trySize(chunks))
.once('error', err => {
resp.removeListener('data', onData);
reject(err);
});
})
.once('error', reject);
});
}
|
javascript
|
{
"resource": ""
}
|
q4474
|
sizeForFileName
|
train
|
function sizeForFileName(fileName, size) {
const m = fileName.match(/@(\d+)x\./);
const scale = m ? +m[1] : 1;
return {
realWidth: size.width,
realHeight: size.height,
width: Math.floor(size.width / scale),
height: Math.floor(size.height / scale)
};
}
|
javascript
|
{
"resource": ""
}
|
q4475
|
findTokenForPoint
|
train
|
function findTokenForPoint(parent, point, type) {
if (!parent) {
return null;
}
if (parent.type === type) {
return parent;
}
for (let i = 0, il = parent.size, item; i < il; i++) {
item = parent.item(i);
if (containsPoint(item, point)) {
return findTokenForPoint(item, point, type);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q4476
|
saveAsFile
|
train
|
function saveAsFile(editor, data, range) {
return new Promise((resolve, reject) => {
const fileName = atom.getCurrentWindow().showSaveDialog();
if (!fileName) {
return reject(new Error('User cancelled file dialog'));
}
fs.writeFile(fileName, Buffer.from(data, 'base64'), err => {
if (err) {
return reject(err);
}
const editorPath = editor.getPath();
let displayPath = editorPath
? path.relative(editorPath, fileName)
: `file://${fileName}`;
editor.transact(() => {
// Convert Windows path separators to Unix
editor.setTextInBufferRange(range, displayPath.replace(/\\+/g, '/'));
});
resolve(fileName);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q4477
|
readFile
|
train
|
function readFile(fileName) {
if (/^https?:/.test(fileName)) {
return readFileFromURL(fileName);
}
return new Promise((resolve, reject) => {
fs.readFile(fileName, (err, content) => err ? reject(err) : resolve(content));
});
}
|
javascript
|
{
"resource": ""
}
|
q4478
|
hasScope
|
train
|
function hasScope(descriptor, scope) {
for (let i = 0; i < descriptor.scopes.length; i++) {
if (descriptor.scopes[i].includes(scope)) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q4479
|
insertFormattedLineBreak
|
train
|
function insertFormattedLineBreak(cursor) {
const indent = cursor.editor.getTabText();
const lineIndent = getLineIndent(cursor);
cursor.selection.insertText(`\n${lineIndent}${indent}\n${lineIndent}`, { autoIndent: false });
// Put caret at the end of indented newline
cursor.moveUp();
cursor.moveToEndOfLine();
}
|
javascript
|
{
"resource": ""
}
|
q4480
|
isAtCodePoint
|
train
|
function isAtCodePoint(stream) {
const code = stream.peek();
// between quotes, looks like an empty attribute value
return (isQuote(code) && getPrevCode(stream) === code)
// between tags, e.g. > and <
|| (code === 60 /* < */ && getPrevCode(stream) === 62 /* > */)
// on empty line
|| (isLineBreak(code) && reEmptyLine.test(stream.buffer.lineForRow(stream.pos.row)));
}
|
javascript
|
{
"resource": ""
}
|
q4481
|
getPrevCode
|
train
|
function getPrevCode(stream) {
if (!stream.sof()) {
const code = stream.backUp(1);
stream.next();
return code;
}
}
|
javascript
|
{
"resource": ""
}
|
q4482
|
updateImageSizeHTML
|
train
|
function updateImageSizeHTML(editor, model) {
const pos = editor.getCursorBufferPosition();
const src = getImageSrcHTML( getImageHTMLNode(editor, model, pos) );
if (!src) {
return Promise.reject(new Error('No valid image source'));
}
locateFile(editor, src)
.then(getImageSize)
.then(size => {
// since this action is asynchronous, we have to ensure that editor wasn’t
// changed and user didn’t moved caret outside <img> node
const img = getImageHTMLNode(editor, model, pos);
if (getImageSrcHTML(img) === src) {
updateHTMLTag(editor, img, size.width, size.height);
}
})
.catch(err => console.warn('Error while updating image size:', err));
}
|
javascript
|
{
"resource": ""
}
|
q4483
|
updateImageSizeCSS
|
train
|
function updateImageSizeCSS(editor, model) {
const pos = editor.getCursorBufferPosition();
const property = getImageCSSNode(editor, model, pos);
const urlToken = findUrlToken(property, pos);
const src = urlToken && getImageSrcCSS(urlToken);
if (!src) {
return Promise.reject(new Error('No valid image source'));
}
locateFile(editor, src)
.then(getImageSize)
.then(size => {
// since this action is asynchronous, we have to ensure that editor wasn’t
// changed and user didn’t moved caret outside <img> node
if (getImageCSSNode(editor, model, pos) === property) {
updateCSSNode(editor, property, size.width, size.height);
}
})
.catch(err => console.warn('Error while updating image size:', err));
}
|
javascript
|
{
"resource": ""
}
|
q4484
|
updateHTMLTag
|
train
|
function updateHTMLTag(editor, node, width, height) {
const srcAttr = getAttribute(node, 'src');
const widthAttr = getAttribute(node, 'width');
const heightAttr = getAttribute(node, 'height');
editor.transact(() => {
// apply changes from right to left, first for height, then for width
let point;
const quote = getAttributeQuote(editor, widthAttr || heightAttr || srcAttr);
if (!heightAttr) {
// no `height` attribute, add it right after `width` or `src`
point = widthAttr ? widthAttr.end : srcAttr.end;
editor.setTextInBufferRange([point, point], ` height=${quote}${height}${quote}`);
} else {
editor.setTextInBufferRange(getRange(heightAttr.value), String(height));
}
if (!widthAttr) {
// no `width` attribute, add it right before `height` or after `src`
point = heightAttr ? heightAttr.start : srcAttr.end;
editor.setTextInBufferRange([point, point], `${!heightAttr ? ' ' : ''}width=${quote}${width}${quote}${heightAttr ? ' ' : ''}`);
} else {
editor.setTextInBufferRange(getRange(widthAttr.value), String(width));
}
});
}
|
javascript
|
{
"resource": ""
}
|
q4485
|
updateCSSNode
|
train
|
function updateCSSNode(editor, srcProp, width, height) {
const rule = srcProp.parent;
const widthProp = getProperty(rule, 'width');
const heightProp = getProperty(rule, 'height');
// Detect formatting
const separator = srcProp.separator || ': ';
const before = getBefore(editor, srcProp);
const insertOpt = { autoIndent: false };
editor.transact(() => {
// Apply changes from right to left, first for height, then for width
if (!heightProp) {
// no `height` property, add it right after `width` or source property
editor.setCursorBufferPosition(widthProp ? widthProp.end : srcProp.end);
editor.insertText(`${before}height${separator}${height}px;`, insertOpt);
} else {
editor.setTextInBufferRange(getRange(heightProp.valueToken), `${height}px`);
}
if (!widthProp) {
// no `width` attribute, add it right after `height` or source property
if (heightProp) {
editor.setCursorBufferPosition(heightProp.previousSibling
? heightProp.previousSibling.end
: rule.contentStart.end);
} else {
editor.setCursorBufferPosition(srcProp.end);
}
editor.insertText(`${before}width${separator}${width}px;`, insertOpt);
} else {
editor.setTextInBufferRange(getRange(widthProp.valueToken), `${width}px`);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q4486
|
findUrlToken
|
train
|
function findUrlToken(node, pos) {
for (let i = 0, il = node.parsedValue.length, url; i < il; i++) {
iterateCSSToken(node.parsedValue[i], token => {
if (token.type === 'url' && containsPoint(token, pos)) {
url = token;
return false;
}
});
if (url) {
return url;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q4487
|
getProperty
|
train
|
function getProperty(rule, name) {
return rule.children.find(node => node.type === 'property' && node.name === name);
}
|
javascript
|
{
"resource": ""
}
|
q4488
|
selectItem
|
train
|
function selectItem(editor, model, getItemRange) {
editor.transact(() => {
const selections = editor.getSelectedBufferRanges()
.map(anchor => getItemRange(model, anchor) || anchor);
editor.setSelectedBufferRanges(selections);
});
}
|
javascript
|
{
"resource": ""
}
|
q4489
|
getNextItemRange
|
train
|
function getNextItemRange(model, anchor, getItemRanges) {
// Find HTML node for next selection
let node = nodeForPoint(model, anchor.start, 'next');
let range;
// We might need to narrow down node context to find best token match
while (node && !range) {
range = getNextRange(getItemRanges(node), anchor);
node = node.firstChild || nextSibling(node);
}
return range;
}
|
javascript
|
{
"resource": ""
}
|
q4490
|
getPreviousItemRange
|
train
|
function getPreviousItemRange(model, anchor, getItemRanges) {
// Find HTML node for next selection
let node = nodeForPoint(model, anchor.start, 'previous');
let range;
// We might need to narrow down node context to find best token match
while (node) {
range = getPreviousRange(getItemRanges(node), anchor);
if (range) {
break;
}
node = previousSibling(node) || node.parent;
}
return range;
}
|
javascript
|
{
"resource": ""
}
|
q4491
|
getNextRange
|
train
|
function getNextRange(ranges, anchor) {
for (let i = 0; i < ranges.length; i++) {
if (anchor.isEqual(ranges[i])) {
// NB may return `undefined`, which is totally fine and means that
// we should move to next element
return ranges[i + 1];
}
}
// Keep ranges which are not on the left of given selection
ranges = ranges.filter(r => anchor.end.isLessThanOrEqual(r.start));
return ranges[0];
}
|
javascript
|
{
"resource": ""
}
|
q4492
|
getPreviousRange
|
train
|
function getPreviousRange(ranges, anchor) {
for (let i = 0; i < ranges.length; i++) {
if (anchor.isEqual(ranges[i])) {
// NB may return `undefined`, which is totally fine and means that
// we should move to next element
return ranges[i - 1];
}
}
// Keep ranges which are not on the left of given selection
ranges = ranges.filter(r => r.end.isLessThanOrEqual(anchor.start));
return last(ranges);
}
|
javascript
|
{
"resource": ""
}
|
q4493
|
getRangesFromHTMLNode
|
train
|
function getRangesFromHTMLNode(node) {
if (node.type !== 'tag') {
return [];
}
let ranges = [ getRange(node.open.name) ];
if (node.attributes) {
node.attributes.forEach(attr => {
ranges.push(getRange(attr));
if (!attr.boolean) {
// add attribute value (unquoted) range for non-boolean attributes
ranges.push(getRange(attr.value));
if (attr.name.value.toLowerCase() === 'class') {
// In case of `class` attribute, add each class item
// as selection range, but only if this value is not
// an expression (for example, React expression like
// `class={items.join(' ')}`)
ranges = ranges.concat(attributeValueTokens(attr.value));
}
}
});
}
return uniqueRanges(ranges.filter(Boolean));
}
|
javascript
|
{
"resource": ""
}
|
q4494
|
getRangesFromCSSNode
|
train
|
function getRangesFromCSSNode(node) {
let ranges;
if (node.type === 'rule') {
ranges = [ getRange(node.selectorToken) ].concat(node.parsedSelector.map(getRange));
} else if (node.type === 'at-rule') {
const nameEndToken = node.expressionToken || node.nameToken;
ranges = [
new Range(node.nameToken.start, nameEndToken.end),
getRange(node.nameToken),
getRange(node.expressionToken)
];
node.parsedExpression.forEach(token => {
ranges.push(getRange(token));
iterateCSSToken(token, t => {
if (t.type === 'argument') {
ranges.push(getRange(t));
}
});
});
} else if (node.type === 'property') {
ranges = [
getRange(node),
getRange(node.nameToken),
getRange(node.valueToken)
];
node.parsedValue.forEach(value => {
// parsed value contains a comma-separated list of sub-values,
// each of them, it turn, may contain space-separated parts
ranges.push(getRange(value));
for (let i = 0, il = value.size, token; i < il; i++) {
token = value.item(i);
if (token.type === 'url') {
ranges.push(getRange(token), getRange(token.item(0)));
} else if (token.type !== 'whitespace' && token !== 'comment') {
ranges.push(getRange(token));
iterateCSSToken(token, t => {
if (t.type === 'argument') {
ranges.push(getRange(t));
}
});
}
}
});
}
return ranges ? uniqueRanges(ranges.filter(Boolean)) : [];
}
|
javascript
|
{
"resource": ""
}
|
q4495
|
nodeForPoint
|
train
|
function nodeForPoint(model, point, direction) {
const node = model.nodeForPoint(point);
if (node) {
return node;
}
// Looks like caret is outside of any top-level node.
const topLevelNodes = model.dom.children;
if (direction === 'next') {
// Find next node, which is closest top-level to given position
return topLevelNodes.find(node => node.start.isGreaterThanOrEqual(point));
}
// Find previous node, which is deepest child of closest previous node
for (let i = topLevelNodes.length - 1; i >= 0; i--) {
if (topLevelNodes[i].end.isLessThanOrEqual(point)) {
return deepestChild(topLevelNodes[i]);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q4496
|
nextSibling
|
train
|
function nextSibling(node) {
while (node) {
if (node.nextSibling) {
return node.nextSibling;
}
node = node.parent;
}
}
|
javascript
|
{
"resource": ""
}
|
q4497
|
toggleEditorClass
|
train
|
function toggleEditorClass(editor, enabled) {
const view = atom.views.getView(editor);
if (view) {
view.classList.toggle('has-emmet-abbreviation', enabled);
}
}
|
javascript
|
{
"resource": ""
}
|
q4498
|
allowedForAutoActivation
|
train
|
function allowedForAutoActivation(model) {
const rootNode = model.ast.children[0];
// The very first node should start with alpha character
// Skips falsy activations for something like `$foo` etc.
return rootNode && /^[a-z]/i.test(rootNode.name);
}
|
javascript
|
{
"resource": ""
}
|
q4499
|
getExpandedAbbreviationCompletion
|
train
|
function getExpandedAbbreviationCompletion({editor, bufferPosition, prefix, activatedManually}) {
// We should expand marked abbreviation only.
// If there’s no marked abbreviation, try to mark it but only if
// user invoked automomplete popup manually
let marker = findMarker(editor, bufferPosition);
if (!marker && activatedManually) {
marker = markAbbreviation(editor, bufferPosition, activatedManually);
}
if (marker) {
const snippet = marker.model.snippet;
// For some syntaxes like Pug, it’s possible that extracted abbreviation
// matches prefix itself (e.g. `li.class` expands to `li.class` in Pug)
// In this case skip completion output.
if (removeFields(snippet) === prefix) {
return null;
}
return {
snippet,
marker,
type: 'snippet',
className: `${baseClass} ${getClassModifier(snippet)}`,
replacementPrefix: editor.getTextInBufferRange(marker.getRange())
};
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.