_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q48700
|
train
|
function(tag, attribs, contents, selfclosing) {
var result = '<' + tag;
if (attribs) {
var i = 0;
var attrib;
while ((attrib = attribs[i]) !== undefined) {
result = result.concat(' ', attrib[0], '="', attrib[1], '"');
i++;
}
}
if (contents) {
result = result.concat('>', contents, '</', tag, '>');
} else if (selfclosing) {
result = result + ' />';
} else {
result = result.concat('></', tag, '>');
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q48701
|
train
|
function(inline) {
var attrs;
switch (inline.t) {
case 'Str':
return this.escape(inline.c);
case 'Softbreak':
return this.softbreak;
case 'Hardbreak':
return inTags('br',[],"",true) + '\n';
case 'Emph':
return inTags('em', [], this.renderInlines(inline.c));
case 'Strong':
return inTags('strong', [], this.renderInlines(inline.c));
case 'Html':
return inline.c;
case 'Entity':
return inline.c;
case 'Link':
attrs = [['href', this.escape(inline.destination, true)]];
if (inline.title) {
attrs.push(['title', this.escape(inline.title, true)]);
}
return inTags('a', attrs, this.renderInlines(inline.label));
case 'Image':
attrs = [['src', this.escape(inline.destination, true)],
['alt', this.escape(this.renderInlines(inline.label))]];
if (inline.title) {
attrs.push(['title', this.escape(inline.title, true)]);
}
return inTags('img', attrs, "", true);
case 'Code':
return inTags('code', [], this.escape(inline.c));
default:
console.log("Uknown inline type " + inline.t);
return "";
}
}
|
javascript
|
{
"resource": ""
}
|
|
q48702
|
train
|
function(inlines) {
var result = '';
for (var i=0; i < inlines.length; i++) {
result = result + this.renderInline(inlines[i]);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q48703
|
train
|
function(block, in_tight_list) {
var tag;
var attr;
var info_words;
switch (block.t) {
case 'Document':
var whole_doc = this.renderBlocks(block.children);
return (whole_doc === '' ? '' : whole_doc + '\n');
case 'Paragraph':
if (in_tight_list) {
return this.renderInlines(block.inline_content);
} else {
return inTags('p', [], this.renderInlines(block.inline_content));
}
break;
case 'BlockQuote':
var filling = this.renderBlocks(block.children);
return inTags('blockquote', [], filling === '' ? this.innersep :
this.innersep + this.renderBlocks(block.children) + this.innersep);
case 'ListItem':
return inTags('li', [], this.renderBlocks(block.children, in_tight_list).trim());
case 'List':
tag = block.list_data.type == 'Bullet' ? 'ul' : 'ol';
attr = (!block.list_data.start || block.list_data.start == 1) ?
[] : [['start', block.list_data.start.toString()]];
return inTags(tag, attr, this.innersep +
this.renderBlocks(block.children, block.tight) +
this.innersep);
case 'ATXHeader':
case 'SetextHeader':
tag = 'h' + block.level;
return inTags(tag, [], this.renderInlines(block.inline_content));
case 'IndentedCode':
return inTags('pre', [],
inTags('code', [], this.escape(block.string_content)));
case 'FencedCode':
info_words = block.info.split(/ +/);
attr = info_words.length === 0 || info_words[0].length === 0 ?
[] : [['class','language-' +
this.escape(info_words[0],true)]];
return inTags('pre', [],
inTags('code', attr, this.escape(block.string_content)));
case 'HtmlBlock':
return block.string_content;
case 'ReferenceDef':
return "";
case 'HorizontalRule':
return inTags('hr',[],"",true);
default:
console.log("Uknown block type " + block.t);
return "";
}
}
|
javascript
|
{
"resource": ""
}
|
|
q48704
|
train
|
function(blocks, in_tight_list) {
var result = [];
for (var i=0; i < blocks.length; i++) {
if (blocks[i].t !== 'ReferenceDef') {
result.push(this.renderBlock(blocks[i], in_tight_list));
}
}
return result.join(this.blocksep);
}
|
javascript
|
{
"resource": ""
}
|
|
q48705
|
HtmlRenderer
|
train
|
function HtmlRenderer(){
return {
// default options:
blocksep: '\n', // space between blocks
innersep: '\n', // space between block container tag and contents
softbreak: '\n', // by default, soft breaks are rendered as newlines in HTML
// set to "<br />" to make them hard breaks
// set to " " if you want to ignore line wrapping in source
escape: function(s, preserve_entities) {
if (preserve_entities) {
return s.replace(/[&](?;|[a-z][a-z0-9]{1,31};)/gi,'&')
.replace(/[<]/g,'<')
.replace(/[>]/g,'>')
.replace(/["]/g,'"');
} else {
return s.replace(/[&]/g,'&')
.replace(/[<]/g,'<')
.replace(/[>]/g,'>')
.replace(/["]/g,'"');
}
},
renderInline: renderInline,
renderInlines: renderInlines,
renderBlock: renderBlock,
renderBlocks: renderBlocks,
render: renderBlock
};
}
|
javascript
|
{
"resource": ""
}
|
q48706
|
typeCreateHandler
|
train
|
function typeCreateHandler(docObject, newScope) {
docObject && addDocObjectToDocMap(docObject, docMap, filename, comment && comment.line);
if (newScope) {
scope = newScope;
}
}
|
javascript
|
{
"resource": ""
}
|
q48707
|
makeDocObject
|
train
|
function makeDocObject(base, line, codeLine){
var docObject = _.extend({}, base);
if(filename) {
docObject.src = filename + "";
}
if (typeof line === 'number') {
docObject.line = line;
}
if (typeof codeLine === 'number') {
docObject.codeLine = codeLine;
}
return docObject;
}
|
javascript
|
{
"resource": ""
}
|
q48708
|
train
|
function(indentationStack, indentation, docObject, keepStack ){
if(!keepStack) {
while(indentationStack.length && _.last(indentationStack).indentation >= indentation) {
var top = indentationStack.pop();
if(top.tag && top.tag.end) {
top.tag.end.call(docObject, top.tagData);
}
}
}
return indentationStack.length ? _.last(indentationStack).tagData : docObject;
}
|
javascript
|
{
"resource": ""
}
|
|
q48709
|
train
|
function(name, title, attrs){
if (!name) return (title || "");
name = name.replace('::', '.prototype.');
if (docMap[name]) {
var attrsArr = [];
for(var prop in attrs){
attrsArr.push(prop+"=\""+attrs[prop]+"\"")
}
return '<a href="' + docsFilename(name, config) + '" '+attrsArr.join(" ")+'>' + (title || name ) + '</a>';
} else {
return title || name || "";
}
}
|
javascript
|
{
"resource": ""
}
|
|
q48710
|
train
|
function(types, options){
if(!Array.isArray(types)) {
return options.inverse(this);
}
var typesWithDescriptions = [];
types.forEach(function( type ){
if(type.description){
typesWithDescriptions.push(type)
}
});
if( !typesWithDescriptions.length ) {
// check the 1st one's options
if(types.length == 1 && types[0].options ) {
types[0].options.forEach(function(option){
typesWithDescriptions.push(option);
});
}
}
if(typesWithDescriptions.length){
return options.fn({types: typesWithDescriptions});
} else {
return options.inverse(this);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q48711
|
train
|
function (element, options) {
this.element = $(element)
this.options = $.extend(true, {}, this.options, options)
this._init()
}
|
javascript
|
{
"resource": ""
}
|
|
q48712
|
stubMethod
|
train
|
function stubMethod(service, method, replacement) {
if (!isStubbed(service)) stubService(service);
if (!replacement) return sinon.stub(getService(service).prototype, method);
return sinon.stub(getService(service).prototype, method).callsFake(function(params, callback) {
var _this = { request: stubRequest(), response: stubResponse() };
replacement.call(_this, params, callback);
return _this.request;
});
}
|
javascript
|
{
"resource": ""
}
|
q48713
|
train
|
function(plugin, message, opt) {
opt = opt || {};
if (typeof plugin === 'object') {
opt = plugin;
} else {
if (message instanceof Error) {
opt.error = message;
} else if (typeof message === 'object') {
opt = message;
} else {
opt.message = message;
}
opt.plugin = plugin;
}
return objectAssign({
showStack: false,
showProperties: true
}, opt);
}
|
javascript
|
{
"resource": ""
}
|
|
q48714
|
makeSafeToCall
|
train
|
function makeSafeToCall(fun) {
if (fun) {
defProp(fun, "call", fun.call);
defProp(fun, "apply", fun.apply);
}
return fun;
}
|
javascript
|
{
"resource": ""
}
|
q48715
|
vault
|
train
|
function vault(key, forget) {
// Only code that has access to the passkey can retrieve (or forget)
// the secret object.
if (key === passkey) {
return forget
? secret = null
: secret || (secret = secretCreatorFn(object));
}
}
|
javascript
|
{
"resource": ""
}
|
q48716
|
newFormat
|
train
|
function newFormat(option) {
//parameter change
var keyAdded = option.keyAdded || [],
json = option.json,
path = option.path,
newJson = option.newJson;
//add to new json
jsonQ.each(json, function(k, val) {
var lvlpath = path ? JSON.parse(JSON.stringify(path)) : [];
lvlpath.push(k);
//to add a new direct access for each key in json so we get the path of that key easily
if (objType(json) == 'object') {
if (keyAdded.indexOf(k) == -1) {
keyAdded.push(k);
newJson.jsonQ_path[k] = [];
}
newJson.jsonQ_path[k].push({
path: lvlpath
});
}
//if value is json or array go to further level
var type = objType(val);
if (type == 'object' || type == 'array') {
newFormat({
'json': val,
'newJson': newJson,
'path': lvlpath,
'keyAdded': keyAdded
});
}
});
return newJson;
}
|
javascript
|
{
"resource": ""
}
|
q48717
|
train
|
function(option) {
var current = this.jsonQ_current,
newObj = this.cloneObj(jsonQ()),
newCurrent = newObj.jsonQ_current = [],
prevPathStr = '',
key = option.key,
method = option.method;
for (var i = 0, ln = current.length; i < ln; i++) {
var pathC = current[i].path,
pathStr,
outofBound = false,
parPath = pathC.concat([]);
//to run callback to apply top traverse logic
if (method == 'parent') {
if (parPath.length === 0) {
outofBound = true;
} else {
parPath.pop();
}
} else {
var keyIndex = parPath.lastIndexOf(key);
if (keyIndex == -1) {
outofBound = true;
} else {
parPath = parPath.slice(0, keyIndex + 1);
}
}
pathStr = JSON.stringify(parPath);
if (prevPathStr != pathStr && !outofBound) {
newCurrent.push({
path: parPath
});
}
prevPathStr = pathStr;
}
//set other definition variables
newObj.length = newCurrent.length;
//to add selector
newObj.selector.push({
method: method,
key: key
});
return newObj;
}
|
javascript
|
{
"resource": ""
}
|
|
q48718
|
train
|
function(option) {
var current = this.jsonQ_current,
newObj = this.cloneObj(jsonQ()),
newCurrent = newObj.jsonQ_current = [],
pathObj = this.jsonQ_path,
//key element (an array of paths with following key)
key = option.key,
//dont work with original object clone it and if undefined than make as empty array
elm = jsonQ.clone(pathObj[key]) || [],
//qualifier
qualifier = option.qualifier,
qType = objType(qualifier),
//travese method
method = option.method,
find = method == "find" ? true : false;
for (var i = 0, ln = current.length; i < ln; i++) {
var pathC = current[i].path,
pathCTemp = [],
found = false;
if (!find) {
//if it is top level continue the loop. This case comes when we do sibling method called on initial object
if (pathC.length === 0) {
continue;
}
pathCTemp = pathC.concat([]);
pathCTemp.pop();
}
//make a loop on element to match the current path and element path
for (var j = 0; j < elm.length; j++) {
var pathE = elm[j].path,
condition;
if (find) {
condition = matchPath(pathC, pathE);
} else {
var pathETemp = pathE.concat([]);
//to pop last element
pathETemp.pop();
condition = pathCTemp.join() == pathETemp.join();
}
if (condition) {
//code to check qualifier need to be written this on is only when quantifier when it is function in other case it will be applied on last
var qTest = tFunc.qTest.call(this, qType, qualifier, pathE, newCurrent);
if (qTest) {
//to remove element which is already added
elm.splice(j, 1);
j--;
}
//make found flag true
found = true;
}
//break if path doesent match in next sequence and for one element is already there.
else if (found) {
break;
}
}
}
//to apply qualifier if it is string . its mainly for array kind of qualifier
if (qType == "string") {
newObj = this.filter.call(newObj, qualifier);
}
//set other defination variables
newObj.length = newObj.jsonQ_current.length;
//to add selector
newObj.selector.push({
method: method,
key: key,
qualifier: qualifier
});
return newObj;
}
|
javascript
|
{
"resource": ""
}
|
|
q48719
|
train
|
function(index, valObj, clone) {
var current = this.jsonQ_current;
//return if incorrect index is given
if (isNaN(index) && index != "first" && index != "last") {
error(index + 'is not a valid index.');
return this;
}
for (var i = 0, ln = current.length; i < ln; i++) {
var pathC = current[i].path.concat([]),
lastKey = pathC.pop(),
parRef = this.pathValue(pathC),
type = objType(parRef[lastKey]),
objLn = parRef[lastKey].length;
//to limit index
var idx = index < 0 || index == "first" ? 0 : index > objLn || index == "last" ? objLn : index;
//if array push
if (type == 'array') {
valObj = clone ? jsonQ.clone(valObj) : valObj;
parRef[lastKey].splice(idx, 0, valObj);
}
//if string concatenate , if number add
else if (type == 'string') {
var str = parRef[lastKey];
parRef[lastKey] = str.substring(0, idx) + valObj + str.substring(idx, objLn);
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q48720
|
train
|
function(key, qualifier) {
return tFunc.qualTrv.call(this, {
method: "find",
key: key,
qualifier: qualifier
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48721
|
train
|
function(key, settings) {
//merge global setting with local setting
settings = jsonQ.merge({}, jsonQ.settings.sort, settings);
var jobj = this.find(key),
current = jobj.clone(),
sortStack = [],
i, ln,
sortedPath = [],
type = objType(jobj.pathValue(current[0].path)),
//function to get value which is an array from pathKey traversing from right.
getClosestArray = function(key) {
while (key.length !== 0) {
var lastKey = key.pop();
if (!isNaN(lastKey)) {
var val = jobj.pathValue(key);
if (objType(val) == 'array') {
return val;
}
}
}
return null;
};
//initialize sort stack
for (i = 0, ln = current.length; i < ln; i++) {
sortStack.push({
pathHolder: current[i].path.concat([]),
current: current[i].path.concat([])
});
}
//to run the loop until all are sorted
var alpha = 0,
// function to remove element if sorting is done for that path
spliceElm = function(i) {
sortStack.splice(i, 1);
return --i;
};
while (sortStack.length !== 0) {
alpha++;
for (i = 0; i < sortStack.length; i++) {
var cur = sortStack[i].current,
pH = sortStack[i].pathHolder,
//to get the closest array in the current path. This will also change value of current path variable.
ary = getClosestArray(cur),
pathStr = cur.join();
//to remove from sort stack if no array is left on key or if that is already sorted
if (cur.length === 0 || sortedPath.indexOf(pathStr) != -1) {
i = spliceElm(i);
}
//to sort if array found
else {
//logic path is path which we add in on condition to find the element value according to which we are sorting
var logicPath = pH.slice(cur.length + 1, pH.length),
logic = function(a) {
var val = jsonQ.pathValue(a, logicPath);
//to convert val to be compared
val = sortFunc.baseConv(type, val, settings);
return settings.logic(val);
};
//to sort the root json
sortFunc.sortAry(ary, logic, settings);
//if multilevel sort is true
if (settings.allLevel) {
//to maintain the path which is already sorted and change pathHolder to point first element of sorted array
pH[cur.length] = 0;
sortedPath.push(pathStr);
} else {
//remove sorted path
i = spliceElm(i);
}
}
}
}
return jsonQ(jobj.jsonQ_root).find(key);
}
|
javascript
|
{
"resource": ""
}
|
|
q48722
|
train
|
function(a) {
var val = jsonQ.pathValue(a, logicPath);
//to convert val to be compared
val = sortFunc.baseConv(type, val, settings);
return settings.logic(val);
}
|
javascript
|
{
"resource": ""
}
|
|
q48723
|
train
|
function(callback) {
var current = this.jsonQ_current;
for (var i = 0, ln = current.length; i < ln; i++) {
callback(i, current[i].path, this.pathValue(current[i].path));
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q48724
|
train
|
function(k, v) {
var type = objType(v),
tarType = objType(target[k]);
if (deep && (type == "array" || type == "object")) {
target[k] = type == tarType && (tarType == "array" || tarType == "object") ? target[k] : type == "array" ? [] : {};
//to merge recursively
jsonQ.merge(deep, target[k], v);
} else {
target[k] = v;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q48725
|
train
|
function(list, elm, isQualifier) {
var type = objType(elm),
ln = list.length,
//check that elm is a object or not that is taken by reference
refObj = type == "object" || type == "array" || type == "function" ? true : false;
//if elm is a function consider it as a qualifier
if (type == "function") {
isQualifier = true;
}
if (refObj && !isQualifier) {
//convert object to string so that they can be compared.
var jsonStr = stringify(jsonQ.order(elm));
}
for (var i = 0; i < ln; i++) {
var cur = list[i];
if (refObj) {
var lType = objType(cur);
if (lType != type && !isQualifier) continue;
//to compare
if (!isQualifier) {
if (stringify(jsonQ.order(cur)) == jsonStr) {
return i;
}
//if element is a qualifier
} else {
var test;
if (type == 'function') {
test = elm.call(cur);
} else if (type == "object" && lType == "object") {
test = jsonQ.checkKeyValue(cur, elm);
} else if (lType == "array") {
if (type == "array") {
for (var j = 0, elmLn = elm.length; j < elmLn; j++) {
test = jsonQ.index(cur, elm[j]) != -1;
if (!test) break;
}
} else {
test = jsonQ.index(cur, elm) != -1;
}
}
//return index if it passes the test
if (test) return i;
}
} else if (elm == cur) {
return i;
}
}
return -1;
}
|
javascript
|
{
"resource": ""
}
|
|
q48726
|
train
|
function(json, keyVal) {
for (var k in keyVal) {
if (keyVal.hasOwnProperty(k))
if (!jsonQ.identical(keyVal[k], json[k])) return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q48727
|
train
|
function(a, b) {
function sort(object) {
if (typeof object !== "object" || object === null) {
return object;
}
return Object.keys(object).sort().map(function(key) {
return {
key: key,
value: sort(object[key])
};
});
}
return JSON.stringify(sort(a)) === JSON.stringify(sort(b));
}
|
javascript
|
{
"resource": ""
}
|
|
q48728
|
train
|
function() {
var arg = arguments,
target = [],
ln = arg.length;
for (var i = 0; i < ln; i++) {
var aryLn = arg[i].length;
for (var j = 0; j < aryLn; j++) {
var itm = arg[i][j];
if (jsonQ.index(target, itm) == -1) {
target.push(itm);
}
}
}
return target;
}
|
javascript
|
{
"resource": ""
}
|
|
q48729
|
train
|
function() {
var arg = arguments,
target = [],
flag,
ln = arg.length;
if (ln == 1) {
target = arg[0];
} else {
for (var j = 0, aryLn = arg[0].length; j < aryLn; j++) {
var elm = arg[0][j];
flag = 1;
for (var i = 1; i < ln; i++) {
if (jsonQ.index(arg[i], elm) == -1) {
flag = 0;
break;
}
}
if (flag == 1) {
target.push(elm);
}
}
}
return target;
}
|
javascript
|
{
"resource": ""
}
|
|
q48730
|
train
|
function(array) {
for (var i = 1, ln = array.length; i < ln; i++) {
var j = Math.floor(Math.random() * (i + 1)),
tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
return array;
}
|
javascript
|
{
"resource": ""
}
|
|
q48731
|
train
|
function(json, path) {
var i = 0,
ln = path.length;
if (json === null) {
return null;
}
while (i < ln) {
if (json[path[i]] === null) {
json = null;
return;
} else {
json = json[path[i]];
}
i = i + 1;
}
return json;
}
|
javascript
|
{
"resource": ""
}
|
|
q48732
|
train
|
function(target, index, val, clone) {
if (isNaN(index) && index != "first" && index != "last") {
error(index + 'is not a valid index.');
return;
}
var type = objType(target),
length = target.length;
//to limit index
var idx = index < 0 || index == "first" ? 0 : index > length || index == "last" ? length : index;
//if array push
if (type == 'array') {
val = clone ? jsonQ.clone(val) : val;
target.splice(idx, 0, val);
}
//if string concatenate , if number add
else if (type == 'string') {
target = target.substring(0, idx) + val + target.substring(idx, length);
}
return target;
}
|
javascript
|
{
"resource": ""
}
|
|
q48733
|
getmain
|
train
|
function getmain(L) {
L.rawgeti(Lua.defines.REGISTRYINDEX, Lua.defines.RIDX_MAINTHREAD);
var _L = L.tothread(-1);
L.pop(1);
return _L;
}
|
javascript
|
{
"resource": ""
}
|
q48734
|
screenshotServiceUrl
|
train
|
function screenshotServiceUrl(siteUrl) {
return url.format({
protocol: 'http',
hostname: DEF_MANET_HOST,
port: DEF_MANET_PORT,
query: {
callback: DEF_CALLBACK,
url: siteUrl,
force: true
}
});
}
|
javascript
|
{
"resource": ""
}
|
q48735
|
captureScreenshot
|
train
|
function captureScreenshot(url) {
const serviceUrl = screenshotServiceUrl(url);
console.log('Sending request to capture screenshot from %s', url);
http.get(serviceUrl, (res) =>
console.log('Screenshot from %s was captured with status %s', url, res.statusCode));
console.log('Request to capture screenshot from %s was sent', url);
}
|
javascript
|
{
"resource": ""
}
|
q48736
|
startPoller
|
train
|
function startPoller() {
setInterval(() => {
for (let i = 0; i < DEF_SITES_URL.length; i++) {
captureScreenshot(DEF_SITES_URL[i]);
}
}, DEF_DELAY);
}
|
javascript
|
{
"resource": ""
}
|
q48737
|
startServer
|
train
|
function startServer() {
http.createServer((req, res) => {
const fileName = __dirname + path.sep + new Date().getTime() + '.png';
req.on('end', () => {
res.writeHead(200);
res.end();
fs.stat(fileName, function(error, stat) {
console.log(
'Stored file ' + fileName +
' with size ' + stat.size +
', headers: ' + JSON.stringify(req.headers)
);
fs.unlinkSync(fileName);
});
});
req.pipe(fs.createWriteStream(fileName));
}).listen(DEF_CLIENT_PORT);
console.log("Client server running on port 8124");
}
|
javascript
|
{
"resource": ""
}
|
q48738
|
getURL
|
train
|
function getURL( repository ) {
var repourl;
if (typeof repository === 'object') {
repourl = repository.url;
} else {
repourl = repository
};
return repourl;
}
|
javascript
|
{
"resource": ""
}
|
q48739
|
train
|
function (levels, fn) {
return function (label, val) {
for (var i = 0; i < levels.length; i++) {
if (levels[i] === exports.level) {
return fn(label, val);
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q48740
|
swaggerSecurity
|
train
|
function swaggerSecurity(context, headers) {
var security = null;
headers.filter(function(header) {
return header.name.toLowerCase() === 'authorization';
}).forEach(function(header) {
if (header.value.match(/^Basic /)) {
if (!security) security = {};
security['basic'] = [];
context.swagger.securityDefinitions['basic'] = { type: 'basic' };
} else if (header.value.match(/^Bearer /)) {
if (!security) security = {};
if (context.options.bearerAsApikey) {
security['bearer'] = [];
context.swagger.securityDefinitions['bearer'] = {
type: 'apiKey', in: 'header', name: 'Authorization'
};
} else {
security['oauth2'] = [];
context.swagger.securityDefinitions['oauth2'] = {
type: 'oauth2', flow: 'accessCode',
authorizationUrl: '', tokenUrl: '', scopes: {} };
}
}
});
return security;
}
|
javascript
|
{
"resource": ""
}
|
q48741
|
expandAliases
|
train
|
function expandAliases(version, methods) {
return _.flatMap(methods, method => expandAlias(version, method))
}
|
javascript
|
{
"resource": ""
}
|
q48742
|
isChainable
|
train
|
function isChainable(version, method) {
const data = getMethodData(version)
return _.get(data, [getMainAlias(version, method), 'chainable'], false)
}
|
javascript
|
{
"resource": ""
}
|
q48743
|
isCollectionMethod
|
train
|
function isCollectionMethod(version, method) {
return methodSupportsShorthand(version, method) || _.includes(expandAliases(version, ['reduce', 'reduceRight']), method)
}
|
javascript
|
{
"resource": ""
}
|
q48744
|
methodSupportsShorthand
|
train
|
function methodSupportsShorthand(version, method, shorthandType) {
const mainAlias = getMainAlias(version, method)
const methodShorthandData = _.get(getMethodData(version), [mainAlias, 'shorthand'])
return _.isObject(methodShorthandData) ? Boolean(shorthandType && methodShorthandData[shorthandType]) : Boolean(methodShorthandData)
}
|
javascript
|
{
"resource": ""
}
|
q48745
|
isAliasOfMethod
|
train
|
function isAliasOfMethod(version, method, suspect) {
return method === suspect || _.includes(_.get(getMethodData(version), [method, 'aliases']), suspect)
}
|
javascript
|
{
"resource": ""
}
|
q48746
|
getMainAlias
|
train
|
function getMainAlias(version, method) {
const data = getMethodData(version)
return data[method] ? method : _.findKey(data, methodData => _.includes(methodData.aliases, method))
}
|
javascript
|
{
"resource": ""
}
|
q48747
|
getIterateeIndex
|
train
|
function getIterateeIndex(version, method) {
const mainAlias = getMainAlias(version, method)
const methodData = getMethodData(version)[mainAlias]
if (_.has(methodData, 'iterateeIndex')) {
return methodData.iterateeIndex
}
if (methodData && methodData.iteratee) {
return 1
}
return -1
}
|
javascript
|
{
"resource": ""
}
|
q48748
|
isMemberExpOf
|
train
|
function isMemberExpOf(node, objectName, {maxLength = Number.MAX_VALUE, allowComputed} = {}) {
if (objectName) {
let curr = node
let depth = maxLength
while (curr && depth) {
if (allowComputed || isPropAccess(curr)) {
if (curr.type === 'MemberExpression' && curr.object.name === objectName) {
return true
}
curr = curr.object
depth--
} else {
return false
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q48749
|
hasOnlyOneStatement
|
train
|
function hasOnlyOneStatement(func) {
if (isFunctionDefinitionWithBlock(func)) {
return _.get(func, 'body.body.length') === 1
}
if (func.type === 'ArrowFunctionExpression') {
return !_.get(func, 'body.body')
}
}
|
javascript
|
{
"resource": ""
}
|
q48750
|
isBinaryExpWithMemberOf
|
train
|
function isBinaryExpWithMemberOf(operator, exp, objectName, {maxLength, allowComputed, onlyLiterals} = {}) {
if (!_.isMatch(exp, {type: 'BinaryExpression', operator})) {
return false
}
const [left, right] = [exp.left, exp.right].map(side => isMemberExpOf(side, objectName, {maxLength, allowComputed}))
return (left === !right) && (!onlyLiterals || isLiteral(exp.left) || isLiteral(exp.right))
}
|
javascript
|
{
"resource": ""
}
|
q48751
|
isNegationOfMemberOf
|
train
|
function isNegationOfMemberOf(exp, objectName, {maxLength} = {}) {
return isNegationExpression(exp) && isMemberExpOf(exp.argument, objectName, {maxLength, allowComputed: false})
}
|
javascript
|
{
"resource": ""
}
|
q48752
|
getValueReturnedInFirstStatement
|
train
|
function getValueReturnedInFirstStatement(func) {
const firstLine = getFirstFunctionLine(func)
if (func) {
if (isFunctionDefinitionWithBlock(func)) {
return isReturnStatement(firstLine) ? firstLine.argument : undefined
}
if (func.type === 'ArrowFunctionExpression') {
return firstLine
}
}
}
|
javascript
|
{
"resource": ""
}
|
q48753
|
isCallFromObject
|
train
|
function isCallFromObject(node, objName) {
return node && objName && node.type === 'CallExpression' && _.get(node, 'callee.object.name') === objName
}
|
javascript
|
{
"resource": ""
}
|
q48754
|
getExpressionComparedToInt
|
train
|
function getExpressionComparedToInt(node, value, checkOver) {
const isValue = getIsValue(value)
if (_.includes(comparisonOperators, node.operator)) {
if (isValue(node.right)) {
return node.left
}
if (isValue(node.left)) {
return node.right
}
}
if (checkOver) {
if (node.operator === '>' && isValue(node.right)) {
return node.left
}
if (node.operator === '<' && isValue(node.left)) {
return node.right
}
const isNext = getIsValue(value + 1)
if ((node.operator === '>=' || node.operator === '<') && isNext(node.right)) {
return node.left
}
if ((node.operator === '<=' || node.operator === '>') && isNext(node.left)) {
return node.right
}
}
}
|
javascript
|
{
"resource": ""
}
|
q48755
|
collectParameterValues
|
train
|
function collectParameterValues(node) {
switch (node && node.type) {
case 'Identifier':
return [node.name]
case 'ObjectPattern':
return _.flatMap(node.properties, prop => collectParameterValues(prop.value))
case 'ArrayPattern':
return _.flatMap(node.elements, collectParameterValues)
default:
return []
}
}
|
javascript
|
{
"resource": ""
}
|
q48756
|
isCallToMethod
|
train
|
function isCallToMethod(node, version, method) {
return methodDataUtil.isAliasOfMethod(version, method, astUtil.getMethodName(node))
}
|
javascript
|
{
"resource": ""
}
|
q48757
|
cordovaCreateLegacyAdapter
|
train
|
function cordovaCreateLegacyAdapter (dir, id, name, cfg, extEvents) {
// Unwrap and shallow-clone that nasty nested config object
const opts = Object.assign({}, ((cfg || {}).lib || {}).www);
if (id) opts.id = id;
if (name) opts.name = name;
if (extEvents) opts.extEvents = extEvents;
return cordovaCreate(dir, opts);
}
|
javascript
|
{
"resource": ""
}
|
q48758
|
createWithMockFetch
|
train
|
function createWithMockFetch (dir, id, name, cfg, events) {
const mockFetchDest = path.join(tmpDir, 'mockFetchDest');
const templateDir = path.dirname(require.resolve('cordova-app-hello-world'));
const fetchSpy = jasmine.createSpy('fetchSpy')
.and.callFake(() => Promise.resolve(mockFetchDest));
fs.copySync(templateDir, mockFetchDest);
return createWith({fetch: fetchSpy})(dir, id, name, cfg, events)
.then(() => fetchSpy);
}
|
javascript
|
{
"resource": ""
}
|
q48759
|
expectRejection
|
train
|
function expectRejection (promise, expectedReason) {
return promise.then(
() => fail('Expected promise to be rejected'),
reason => {
if (expectedReason instanceof Error) {
expect(reason instanceof expectedReason.constructor).toBeTruthy();
expect(reason.message).toContain(expectedReason.message);
} else if (typeof expectedReason === 'function') {
expect(expectedReason(reason)).toBeTruthy();
} else if (expectedReason !== undefined) {
expect(reason).toBe(expectedReason);
} else {
expect().nothing();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q48760
|
checkPackageJson
|
train
|
function checkPackageJson () {
const pkg = requireFresh(path.join(project, 'package.json'));
expect(pkg.name).toEqual(appId);
expect(pkg.displayName).toEqual(appName);
expect(pkg.version).toEqual(appVersion);
}
|
javascript
|
{
"resource": ""
}
|
q48761
|
checkDefaultTemplate
|
train
|
function checkDefaultTemplate () {
const pkg = requireFresh(path.join(project, 'package.json'));
expect(pkg.author).toEqual('Apache Cordova Team');
const configXml = new ConfigParser(path.join(project, 'config.xml'));
expect(configXml.author()).toEqual('Apache Cordova Team');
}
|
javascript
|
{
"resource": ""
}
|
q48762
|
checkNotDefaultTemplate
|
train
|
function checkNotDefaultTemplate () {
const configXml = new ConfigParser(path.join(project, 'config.xml'));
expect(configXml.author()).not.toEqual('Apache Cordova Team');
}
|
javascript
|
{
"resource": ""
}
|
q48763
|
train
|
function(results, run, options, done) {
_.each(results, function(result) {
var pkg = {
name: result.testsuites.$.name,
tests: parse(result.testsuites.$.tests),
failures: parse(result.testsuites.$.failures),
suites: []
};
pkg.isFailure = pkg.failures > 0;
var filename = result.filename;
_.each(result.testsuites.testsuite, function(suiteData) {
var $ = suiteData.$;
var suite = {
name: $.name,
pkgName: $.package,
failures: parse($.failures),
errors: parse($.errors),
skipped: parse($.skipped),
tests: parse($.tests),
cases: []
};
// Sometimes the package name isn't in the
// xml reports...
if (!pkg.name) {
if (result.testsuites.filename) {
pkg.name = result.testsuites.filename;
} else {
pkg.name = suite.pkgName;
}
} else {
if (result.testsuites.filename) {
pkg.name = result.testsuites.filename + '-' + pkg.name;
}
}
suite.passed = suite.tests - suite.errors - suite.failures;
suite.isFailure = suite.errors > 0 || suite.failures > 0;
suite.errmessages = $['system-err'];
pkg.suites.push(suite);
_.each(suiteData.testcase, function(caseData) {
var assert = {
message: caseData.$.name,
time: caseData.$.time,
stacktrace: '',
failure: false,
skipped: false,
screenshots: []
// failure: false or failure message,
// screenshots: ['path/to/screen1', '/path/to/screen2']
};
if (caseData.skipped)
assert.skipped = true;
if (caseData.failure && caseData.failure.length > 0)
assert.failure = caseData.failure[0].$.message;
if (caseData['system-out']) {
var sspaths = getScreenshotPaths(caseData['system-out']);
sspaths.map(function(sspath) {
if (options.relativeScreenshots) {
sspath = getRelativePath(options.fullOutputFilename, sspath);
}
assert.screenshots.push(sspath);
});
}
assert.isFailure = assert.failure;
suite.cases.push(assert);
if (assert.isFailure)
suite.isFailure = true;
});
if (suite.isFailure)
pkg.isFailure = true;
});
run.addPackage(pkg);
});
done(null, run);
}
|
javascript
|
{
"resource": ""
}
|
|
q48764
|
train
|
function(results, run, options, done) {
run.errmessages = concatErrMessages(run.errmessages, results.errmessages);
_.forOwn(results.modules, function(pkg, pkgName) {
var npkg = {
name: pkgName,
suites: [],
tests: pkg.tests,
failures: pkg.failures,
errors: pkg.errors,
isFailure: (pkg.failures !== 0 && pkg.errors !== 0)
};
_.forOwn(pkg.completed, function(suite, suiteName) {
var nsuite = {
name: suiteName,
pkgName: npkg.name,
passed: suite.passed,
failures: suite.failed,
errors: suite.errors,
skipped: suite.skipped,
time: suite.time,
cases: []
};
// Little weird here but the report object
// will not report an error, it will instead
// have X failed and empty assertions array.
if (nsuite.failures > 0 && suite.assertions.length === 0)
nsuite.errors = nsuite.failures;
nsuite.isFailure = nsuite.failures !== 0 || nsuite.errors !== 0;
npkg.suites.push(nsuite);
_.each(suite.assertions, function(assertion) {
var assert = _.clone(assertion, true);
assert.screenshots = assert.screenshots || [];
assert.isFailure = assertion.failure;
nsuite.cases.push(assert);
if (options.relativeScreenshots) {
assert.screenshots = assert.screenshots.map(function(sspath) {
return getRelativePath(options.fullOutputFilename, sspath);
});
}
if (assert.isFailure)
nsuite.isFailure = true;
});
if (nsuite.isFailure)
npkg.isFailure = true;
});
run.addPackage(npkg);
if (npkg.isFailure)
run.isFailure = npkg.isFailure;
});
done(null, run);
}
|
javascript
|
{
"resource": ""
}
|
|
q48765
|
enrollment
|
train
|
function enrollment(data) {
var self = object.create(enrollment.prototype);
self.data = data;
return self;
}
|
javascript
|
{
"resource": ""
}
|
q48766
|
socketClient
|
train
|
function socketClient(serviceUrl) {
var self = object.create(socketClient.prototype);
var urlObject = url.parse(serviceUrl);
// create the url without the path
var socketIoUrl = url.format({
protocol: urlObject.protocol,
hostname: urlObject.hostname
});
var options = {
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 50000,
reconnectionAttempts: 5,
autoConnect: false,
path: url.clearTraliningSlash(urlObject.path) + '/socket.io/'
};
self.socket = io(socketIoUrl, options);
self.opened = false;
return self;
}
|
javascript
|
{
"resource": ""
}
|
q48767
|
enrollmentAttempt
|
train
|
function enrollmentAttempt(data, active) {
var self = object.create(enrollmentAttempt.prototype);
self.data = data;
self.active = active || false;
return self;
}
|
javascript
|
{
"resource": ""
}
|
q48768
|
eventSequencer
|
train
|
function eventSequencer() {
var self = object.create(eventSequencer.prototype);
EventEmitter.call(self);
self.sequences = {};
self.received = {};
self.pipedEmitter = null;
return self;
}
|
javascript
|
{
"resource": ""
}
|
q48769
|
httpClient
|
train
|
function httpClient(baseUrl, globalTrackingId) {
var self = object.create(httpClient.prototype);
self.baseUrl = baseUrl;
self.globalTrackingId = globalTrackingId;
return self;
}
|
javascript
|
{
"resource": ""
}
|
q48770
|
eventListenerHub
|
train
|
function eventListenerHub(emitter, eventName) {
var self = object.create(eventListenerHub.prototype);
self.emitter = emitter;
self.eventName = eventName;
self.handlers = [];
self.defaultHandlerFn = null;
return self;
}
|
javascript
|
{
"resource": ""
}
|
q48771
|
_addToJSON
|
train
|
function _addToJSON(error) {
Object.defineProperty(error, 'toJSON', {
value: function() {
return serializeError(this);
},
configurable: true,
writable: true
});
}
|
javascript
|
{
"resource": ""
}
|
q48772
|
getServerIpAddress
|
train
|
function getServerIpAddress(host, port) {
if (host) {
return `${host}:${port}`
}
if (isAndroid) {
const FINGERPRINT = android.os.Build.FINGERPRINT
if (FINGERPRINT.includes("vbox")) {
// running on genymotion
return `10.0.3.2:${port}`
} else if (FINGERPRINT.includes("generic")) {
// running on android emulator
return `10.0.2.2:${port}`
}
}
// ios simulator uses localhost
return `127.0.0.1:${port}`
}
|
javascript
|
{
"resource": ""
}
|
q48773
|
createQueryAction
|
train
|
function createQueryAction (endpoint, responseAction, errorAction, rewritePayload, postprocess) {
return async function (dispatch, getState) {
const otpState = getState().otp
const api = otpState.config.api
const url = `${api.host}${api.port ? ':' + api.port : ''}${api.path}/${endpoint}`
let payload
try {
const response = await fetch(url)
if (response.status >= 400) {
const error = new Error('Received error from server')
error.response = response
throw error
}
payload = await response.json()
} catch (err) {
return dispatch(errorAction(err))
}
if (typeof rewritePayload === 'function') {
dispatch(responseAction(rewritePayload(payload)))
} else {
dispatch(responseAction(payload))
}
if (typeof postprocess === 'function') {
postprocess(payload, dispatch, getState)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q48774
|
getStatusLabel
|
train
|
function getStatusLabel (delay) {
// late departure
if (delay > 60) {
return (
<div className='status-label' style={{ backgroundColor: '#d9534f' }}>
{formatDuration(delay)} Late
</div>
)
}
// early departure
if (delay < -60) {
return (
<div className='status-label' style={{ backgroundColor: '#337ab7' }}>
{formatDuration(Math.abs(delay))} Early
</div>
)
}
// on-time departure
return (
<div className='status-label' style={{ backgroundColor: '#5cb85c' }}>
On Time
</div>
)
}
|
javascript
|
{
"resource": ""
}
|
q48775
|
mergeTransitiveStyles
|
train
|
function mergeTransitiveStyles (base, extended) {
const styles = Object.assign({}, base)
for (const key in extended) {
if (key in base) styles[key] = Object.assign({}, styles[key], extended[key])
else styles[key] = extended[key]
}
return styles
}
|
javascript
|
{
"resource": ""
}
|
q48776
|
Reporter
|
train
|
function Reporter(MochaReporter, coverage, root, reporterOptions) {
if(typeof MochaReporter === 'string') {
if(mocha.reporters[MochaReporter]) {
MochaReporter = mocha.reporters[MochaReporter];
} else {
try {
MochaReporter = require(MochaReporter);
} catch (e) {
throw new Error('reporter "' + MochaReporter + '" does not exist');
}
}
}
// The event emitter used to emit the final events
var runner = this.runner = new EventEmitter();
// A store (by data GUID) for the Mocha objects we created.
// The handler for buffering simultaneous test runs
this.buffers = new BufferManager(runner);
// The actual (suite and test) objects we can feed to the Mocha runner
this._mochaObjects = {};
// The instantiated Mocha reporter
this.reporter = new MochaReporter(runner, {reporterOptions: reporterOptions});
// This is where we store errors so that we can report them all
// at once at the end
this.errors = [];
// Options for reporting code coverage
this.coverage = coverage;
// Option for root path
this.root = root;
}
|
javascript
|
{
"resource": ""
}
|
q48777
|
train
|
function (data) {
var isSigned = isTokenSigned(data.file);
var isFinished = data.status === 'finished';
var isComplete = isSigned && isFinished;
debug('checking if run', url, 'is finished', isComplete);
if (isComplete) {
testRuns.removeListener('patched', checkIfRunIsFinished);
resolve(data);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q48778
|
checkFileExistsSync
|
train
|
function checkFileExistsSync(filepath){
var flag = true;
try {
fs.accessSync(filepath, fs.F_OK);
} catch(e){
flag = false;
}
return flag;
}
|
javascript
|
{
"resource": ""
}
|
q48779
|
checkMicroserviceHealth
|
train
|
function checkMicroserviceHealth() {
var resolver = Promise.pending();
if (!zoologist.getServiceDiscovery() || !zoologist.getServiceDiscovery().getData()) {
resolver.resolve({
status: (zoologist.getClient().getClient().getState().name === 'SYNC_CONNECTED') ? 'UP' : 'DOWN'
});
return resolver.promise;
}
var health = {
id: zoologist.getServiceDiscovery().getData().id,
status: (zoologist.getClient().getClient().getState().name === 'SYNC_CONNECTED') ? 'UP' : 'DOWN',
name: zoologist.getServiceInstance().getData().name,
basePath: zoologist.getServiceInstance().getData().basePath || DEFAULT_BASE_PATH,
address: zoologist.getServiceInstance().getData().address,
port: zoologist.getServiceInstance().getData().port,
registrationTime: new Date(zoologist.getServiceInstance().getData().registrationTimeUTC)
};
if (health.status === 'UP' && zoologist.getServiceDependencies() && zoologist.getServiceDependencies().length > 0) {
checkDependencies(zoologist.getServiceDependencies(), function(err, dependencies) {
health.dependencies = dependencies;
// If any dependencies have zero count, set service 'DOWN'
Object.keys(dependencies).forEach(function(dependency) {
if (dependencies[dependency] == 0) health.status = 'DOWN';
});
resolver.resolve(health);
});
} else {
resolver.resolve(health);
}
return resolver.promise;
}
|
javascript
|
{
"resource": ""
}
|
q48780
|
checkDependencies
|
train
|
function checkDependencies(dependencies, callback) {
var checkedDependencies = {};
async.each(dependencies, function (dependency, callback) {
zoologist.getServiceDiscovery().queryForInstances(dependency, function(err, instances) {
checkedDependencies[dependency] = ((instances) ? instances.length : 0);
callback(err);
});
}, function(err) {
// Ignore error and just return zero'd counts
callback(null, checkedDependencies);
});
}
|
javascript
|
{
"resource": ""
}
|
q48781
|
train
|
function(options) {
options = options || {};
var config = konfig({ path: options.configPath || process.cwd() + '/config' });
// Default options
options.server = options.server || { port: process.env.PORT };
options.debug = options.debug || false;
options.discoverable = options.discoverable || false;
options.monitorsPath = options.monitorsPath || 'monitors';
options.controllersPath = options.controllersPath || 'controllers';
options.callerPath = options.callerPath || path.dirname(caller(2));
options.serviceName = pkgInfo.name;
options.serviceBasePath = 'services';
options.zookeeper = { connectionString: 'localhost:2181', retry: { count: 5 } };
options.partialResponseQuery = options.partialResponseQuery || 'fields';
options.correlationHeaderName = options.correlationHeaderName || 'X-CorrelationID';
options.validatorOptions = options.validatorOptions || null;
// Feature Flags
options.enableBodyParsing = options.enableBodyParsing || true;
options.enableEtag = options.enableEtag || false;
options.enableRequestTracing = options.enableRequestTracing || false;
// Return now if we have no config
if (!config.app) {
return options;
}
// Overlay config file options
options.server = config.app.server || { port: process.env.PORT };
options.serviceName = config.app.microservice.server.name || pkgInfo.name;
options.serviceBasePath = config.app.microservice.basePath || 'services';
options.networkInterfaces = (config.app.microservice.server.registrationNetworkInterfacePriority) ? config.app.microservice.server.registrationNetworkInterfacePriority : null;
options.serviceDependencies = (config.app.microservice.server.dependencies) ? config.app.microservice.server.dependencies.split(',') : null;
options.zookeeper = config.app.zookeeper || { connectionString: 'localhost:2181', retry: { count: 5 } };
return options;
}
|
javascript
|
{
"resource": ""
}
|
|
q48782
|
ZoologistConfig
|
train
|
function ZoologistConfig() {
this.initialised = false;
this.client = null;
this.serviceInstance = null;
this.serviceDiscovery = null;
this.serviceDependencies = null;
}
|
javascript
|
{
"resource": ""
}
|
q48783
|
describeChangeset
|
train
|
function describeChangeset(cfn, name, changesetId, callback) {
var changesetDescriptions;
var changes = [];
(function callAPI(nextToken, callback) {
cfn.describeChangeSet({ ChangeSetName: changesetId, StackName: name, NextToken: nextToken }, function(err, data) {
if (err) return callback(err);
changesetDescriptions = data;
if (data.Status === 'CREATE_COMPLETE' || data.Status === 'FAILED' || data.status === 'DELETE_COMPLETE') {
changes = changes.concat(data.Changes || []);
if (!data.NextToken) {
if (changes.length) changesetDescriptions.Changes = changes;
return callback(null, changesetDescriptions);
}
}
setTimeout(callAPI, 1000, data.NextToken, callback);
});
})(undefined, callback);
}
|
javascript
|
{
"resource": ""
}
|
q48784
|
stackParameters
|
train
|
function stackParameters(name, changeSetType, templateUrl, parameters) {
return {
StackName: name,
Capabilities: [
'CAPABILITY_IAM',
'CAPABILITY_NAMED_IAM'
],
ChangeSetType: changeSetType,
TemplateURL: templateUrl,
Parameters: Object.keys(parameters).map(function(key) {
return { ParameterKey: key, ParameterValue: parameters[key] };
})
};
}
|
javascript
|
{
"resource": ""
}
|
q48785
|
validateComposeOption
|
train
|
function validateComposeOption(composeTheme) {
if ([ COMPOSE_DEEPLY, COMPOSE_SOFTLY, DONT_COMPOSE ].indexOf(composeTheme) === -1) {
throw new Error(
`Invalid composeTheme option for react-css-themr. Valid composition options\
are ${COMPOSE_DEEPLY}, ${COMPOSE_SOFTLY} and ${DONT_COMPOSE}. The given\
option was ${composeTheme}`
)
}
}
|
javascript
|
{
"resource": ""
}
|
q48786
|
removeNamespace
|
train
|
function removeNamespace(key, themeNamespace) {
const capitalized = key.substr(themeNamespace.length)
return capitalized.slice(0, 1).toLowerCase() + capitalized.slice(1)
}
|
javascript
|
{
"resource": ""
}
|
q48787
|
defaultMapThemrProps
|
train
|
function defaultMapThemrProps(ownProps, theme) {
const {
composeTheme, //eslint-disable-line no-unused-vars
innerRef,
themeNamespace, //eslint-disable-line no-unused-vars
mapThemrProps, //eslint-disable-line no-unused-vars
...rest
} = ownProps
return {
...rest,
ref: innerRef,
theme
}
}
|
javascript
|
{
"resource": ""
}
|
q48788
|
train
|
function (pdf_file, cb) {
var quality = 300;
if (options.hasOwnProperty('quality') && options.quality) {
quality = options.quality;
}
convert(pdf_file.file_path, quality, function (err, tif_path) {
var zeroBasedNumPages = num_pages-1;
self.emit('log', 'converted page to intermediate tiff file, page '+ index+ ' (0-based indexing) of '+ zeroBasedNumPages);
if (err) { return cb(err); }
var ocr_flags = [
'-psm 6'
];
if (options.ocr_flags) {
ocr_flags = options.ocr_flags;
}
ocr(tif_path, ocr_flags, function (err, extract) {
fs.unlink(tif_path, function (tif_cleanup_err, reply) {
if (tif_cleanup_err) {
err += ', error removing temporary tif file: "'+tif_cleanup_err+'"';
}
if (err) { return cb(err); }
var page_number = index+1
self.emit('log', 'raw ocr: page ' + index + ' (0-based indexing) of ' +zeroBasedNumPages + ' complete');
single_page_pdf_file_paths.push(pdf_file.file_path);
self.emit('page', { hash: hash, text: extract, index: index, num_pages: num_pages, pdf_path: pdf_path, single_page_pdf_path: pdf_file.file_path});
text_pages.push(extract);
index++;
cb();
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48789
|
remove_doc_data
|
train
|
function remove_doc_data(callback) {
var folder = path.join(__dirname, '..');
var doc_data_path = path.join(folder, 'doc_data.txt');
fs.exists(doc_data_path, function (exists) {
if (!exists) {
return callback();
}
fs.unlink(doc_data_path, callback);
});
}
|
javascript
|
{
"resource": ""
}
|
q48790
|
cleanup_directory
|
train
|
function cleanup_directory(directory_path, callback) {
// only remove the folder at directory_path if it exists
fs.exists(directory_path, function (exists) {
if (!exists) {
return callback();
}
rimraf(directory_path, callback);
});
}
|
javascript
|
{
"resource": ""
}
|
q48791
|
train
|
async function () {
let redirectURL = ctx.url;
try {
redirectURL = encodeURIComponent(redirectURL);
} catch (e) {
// URIError: URI malformed
// use source url
}
const loginURL = options.loginPath + '?redirect=' + redirectURL;
debug('redirect to %s', loginURL);
redirect(ctx, loginURL);
}
|
javascript
|
{
"resource": ""
}
|
|
q48792
|
redirect
|
train
|
function redirect(ctx, url, status) {
if (ctx.accepts('html', 'json') === 'json') {
ctx.set('Location', url);
ctx.status = 401;
ctx.body = {
error: '401 Unauthorized'
};
return;
}
return ctx.redirect(url, status);
}
|
javascript
|
{
"resource": ""
}
|
q48793
|
login
|
train
|
function login(options) {
const defaultHost = options.host;
return async function loginHandler(ctx) {
const loginCallbackPath = options.loginCallbackPath;
const loginPath = options.loginPath;
// ctx.session should be exists
if (ctx.session) {
ctx.session.userauthLoginReferer = formatReferer(ctx, loginPath, options.rootPath);
debug('set loginReferer into session: %s', ctx.session.userauthLoginReferer);
}
const host = defaultHost || ctx.host;
const protocol = options.protocol || ctx.protocol;
const currentURL = protocol + '://' + host + loginCallbackPath;
const loginURL = options.loginURLFormatter(currentURL, options.rootPath, ctx);
debug('login redrect to loginURL: %s', loginURL);
redirect(ctx, loginURL);
};
}
|
javascript
|
{
"resource": ""
}
|
q48794
|
loginCallback
|
train
|
function loginCallback(options) {
return async function loginCallbackHandler(ctx) {
let referer;
// customize how to get redirect target
if (options.getRedirectTarget) {
referer = options.getRedirectTarget(ctx);
}
if (!referer) referer = ctx.session.userauthLoginReferer || options.rootPath;
debug('loginReferer in session: %j', ctx.session.userauthLoginReferer);
// cleanup the userauthLoginReferer on session
ctx.session.userauthLoginReferer = undefined;
let user = ctx.session[options.userField];
if (user) {
// already login
return redirect(ctx, referer);
}
user = await options.getUser(ctx);
if (!user) {
return redirect(ctx, referer);
}
const res = await options.loginCallback(ctx, user);
const loginUser = res[0];
const redirectURL = res[1];
ctx.session[options.userField] = loginUser;
if (redirectURL) {
referer = redirectURL;
}
redirect(ctx, referer);
};
}
|
javascript
|
{
"resource": ""
}
|
q48795
|
logout
|
train
|
function logout(options) {
return async function logoutHandler(ctx) {
let referer = formatReferer(ctx, options.logoutPath, options.rootPath);
const user = ctx.session[options.userField];
if (!user) {
return redirect(ctx, referer);
}
const redirectURL = await options.logoutCallback(ctx, user);
ctx.session[options.userField] = null;
if (redirectURL) {
referer = redirectURL;
}
redirect(ctx, referer);
};
}
|
javascript
|
{
"resource": ""
}
|
q48796
|
bumpLevel
|
train
|
function bumpLevel(level) {
return gulp.src(config.pkg)
.pipe(bump({type: level}))
.on('error', (e) => log.error(e))
.pipe(gulp.dest(config.root));
}
|
javascript
|
{
"resource": ""
}
|
q48797
|
createReleaseTask
|
train
|
function createReleaseTask(level) {
/**
* Prepare the release: upgrade version number according to
* the specified level.
*
* @return {WritableStream} The stream pipeline.
*/
function prepareRelease() {
return bumpLevel(level);
}
return gulp.series(
prepareRelease,
performRelease,
tagRelease,
prepareNextRelease
);
}
|
javascript
|
{
"resource": ""
}
|
q48798
|
subscribeWhenReady
|
train
|
function subscribeWhenReady(doctype, socket) {
if (socket.readyState === WEBSOCKET_STATE.OPEN) {
try {
socket.send(
JSON.stringify({
method: 'SUBSCRIBE',
payload: {
type: doctype
}
})
)
} catch (error) {
// eslint-disable-next-line no-console
console.warn(`Cannot subscribe to doctype ${doctype}: ${error.message}`)
throw error
}
} else {
setTimeout(() => {
subscribeWhenReady(doctype, socket)
}, 10)
}
}
|
javascript
|
{
"resource": ""
}
|
q48799
|
createTorrent
|
train
|
function createTorrent (input, opts, cb) {
if (typeof opts === 'function') [ opts, cb ] = [ cb, opts ]
opts = opts ? Object.assign({}, opts) : {}
_parseInput(input, opts, (err, files, singleFileTorrent) => {
if (err) return cb(err)
opts.singleFileTorrent = singleFileTorrent
onFiles(files, opts, cb)
})
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.