_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q52400
|
buildLogBucketPolicy
|
train
|
function buildLogBucketPolicy() {
return {
LogBucketPolicy: {
Type: 'AWS::S3::BucketPolicy',
Properties: {
Bucket: {
Ref: 'LogBucket',
},
PolicyDocument: {
Version: '2012-10-17',
Statement: [
{
Sid: 'AWSLogDeliveryAclCheck',
Effect: 'Allow',
Principal: {
Service: 'delivery.logs.amazonaws.com',
},
Action: 's3:GetBucketAcl',
Resource: {
'Fn::GetAtt': ['LogBucket', 'Arn'],
},
},
{
Sid: 'AWSLogDeliveryWrite',
Effect: 'Allow',
Principal: {
Service: 'delivery.logs.amazonaws.com',
},
Action: 's3:PutObject',
Resource: {
'Fn::Join': [
'',
[
'arn:aws:s3:::',
{ Ref: 'LogBucket' },
'/AWSLogs/',
{ Ref: 'AWS::AccountId' },
'/*',
],
],
},
Condition: {
StringEquals: {
's3:x-amz-acl': 'bucket-owner-full-control',
},
},
},
],
},
},
},
};
}
|
javascript
|
{
"resource": ""
}
|
q52401
|
buildVpcFlowLogs
|
train
|
function buildVpcFlowLogs({ name = 'S3FlowLog' } = {}) {
return {
[name]: {
Type: 'AWS::EC2::FlowLog',
DependsOn: 'LogBucketPolicy',
Properties: {
LogDestinationType: 's3',
LogDestination: {
'Fn::GetAtt': ['LogBucket', 'Arn'],
},
ResourceId: {
Ref: 'VPC',
},
ResourceType: 'VPC',
TrafficType: 'ALL',
},
},
};
}
|
javascript
|
{
"resource": ""
}
|
q52402
|
buildNetworkAclEntry
|
train
|
function buildNetworkAclEntry(
name,
CidrBlock,
{ Egress = false, Protocol = -1, RuleAction = 'allow', RuleNumber = 100 } = {},
) {
const direction = Egress ? 'Egress' : 'Ingress';
const cfName = `${name}${direction}${RuleNumber}`;
return {
[cfName]: {
Type: 'AWS::EC2::NetworkAclEntry',
Properties: {
CidrBlock,
NetworkAclId: {
Ref: name,
},
Egress,
Protocol,
RuleAction,
RuleNumber,
},
},
};
}
|
javascript
|
{
"resource": ""
}
|
q52403
|
buildNetworkAclAssociation
|
train
|
function buildNetworkAclAssociation(name, position) {
const cfName = `${name}SubnetNetworkAclAssociation${position}`;
return {
[cfName]: {
Type: 'AWS::EC2::SubnetNetworkAclAssociation',
Properties: {
SubnetId: {
Ref: `${name}Subnet${position}`,
},
NetworkAclId: {
Ref: `${name}NetworkAcl`,
},
},
},
};
}
|
javascript
|
{
"resource": ""
}
|
q52404
|
buildPublicNetworkAcl
|
train
|
function buildPublicNetworkAcl(numZones = 0) {
if (numZones < 1) {
return {};
}
const resources = {};
Object.assign(
resources,
buildNetworkAcl(PUBLIC_SUBNET),
buildNetworkAclEntry(`${PUBLIC_SUBNET}NetworkAcl`, '0.0.0.0/0'),
buildNetworkAclEntry(`${PUBLIC_SUBNET}NetworkAcl`, '0.0.0.0/0', {
Egress: true,
}),
);
for (let i = 1; i <= numZones; i += 1) {
Object.assign(resources, buildNetworkAclAssociation(PUBLIC_SUBNET, i));
}
return resources;
}
|
javascript
|
{
"resource": ""
}
|
q52405
|
buildAppNetworkAcl
|
train
|
function buildAppNetworkAcl(numZones = 0) {
if (numZones < 1) {
return {};
}
const resources = {};
Object.assign(
resources,
buildNetworkAcl(APP_SUBNET),
buildNetworkAclEntry(`${APP_SUBNET}NetworkAcl`, '0.0.0.0/0'),
buildNetworkAclEntry(`${APP_SUBNET}NetworkAcl`, '0.0.0.0/0', {
Egress: true,
}),
);
for (let i = 1; i <= numZones; i += 1) {
Object.assign(resources, buildNetworkAclAssociation(APP_SUBNET, i));
}
return resources;
}
|
javascript
|
{
"resource": ""
}
|
q52406
|
buildDBNetworkAcl
|
train
|
function buildDBNetworkAcl(appSubnets = []) {
if (!Array.isArray(appSubnets) || appSubnets.length < 1) {
return {};
}
const resources = buildNetworkAcl(DB_SUBNET);
appSubnets.forEach((subnet, index) => {
Object.assign(
resources,
buildNetworkAclEntry(`${DB_SUBNET}NetworkAcl`, subnet, {
RuleNumber: 100 + index,
}),
buildNetworkAclEntry(`${DB_SUBNET}NetworkAcl`, subnet, {
RuleNumber: 100 + index,
Egress: true,
}),
buildNetworkAclAssociation(DB_SUBNET, index + 1),
);
});
return resources;
}
|
javascript
|
{
"resource": ""
}
|
q52407
|
buildVPCEndpoint
|
train
|
function buildVPCEndpoint(service, { routeTableIds = [], subnetIds = [] } = {}) {
const endpoint = {
Type: 'AWS::EC2::VPCEndpoint',
Properties: {
ServiceName: {
'Fn::Join': [
'.',
[
'com.amazonaws',
{
Ref: 'AWS::Region',
},
service,
],
],
},
VpcId: {
Ref: 'VPC',
},
},
};
// @see https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints.html
if (service === 's3' || service === 'dynamodb') {
endpoint.Properties.VpcEndpointType = 'Gateway';
endpoint.Properties.RouteTableIds = routeTableIds;
endpoint.Properties.PolicyDocument = {
Statement: [
{
Effect: 'Allow',
/*
TODO 11/21: We should restrict the VPC Endpoint to only the Lambda
IAM role, but this doesn't work.
Principal: {
AWS: {
'Fn::GetAtt': [
'IamRoleLambdaExecution',
'Arn',
],
},
}, */
Principal: '*',
Resource: '*',
},
],
};
if (service === 's3') {
endpoint.Properties.PolicyDocument.Statement[0].Action = 's3:*';
} else if (service === 'dynamodb') {
endpoint.Properties.PolicyDocument.Statement[0].Action = 'dynamodb:*';
}
} else {
endpoint.Properties.VpcEndpointType = 'Interface';
endpoint.Properties.SubnetIds = subnetIds;
endpoint.Properties.PrivateDnsEnabled = true;
endpoint.Properties.SecurityGroupIds = [
{
Ref: 'LambdaEndpointSecurityGroup',
},
];
}
const parts = service.split(/[-_.]/g);
parts.push('VPCEndpoint');
const cfName = parts.map(part => part.charAt(0).toUpperCase() + part.slice(1)).join('');
return {
[cfName]: endpoint,
};
}
|
javascript
|
{
"resource": ""
}
|
q52408
|
buildEndpointServices
|
train
|
function buildEndpointServices(services = [], numZones = 0) {
if (!Array.isArray(services) || services.length < 1) {
return {};
}
if (numZones < 1) {
return {};
}
const subnetIds = [];
const routeTableIds = [];
for (let i = 1; i <= numZones; i += 1) {
subnetIds.push({ Ref: `${APP_SUBNET}Subnet${i}` });
routeTableIds.push({ Ref: `${APP_SUBNET}RouteTable${i}` });
}
const resources = {};
services.forEach(service => {
Object.assign(resources, buildVPCEndpoint(service, { routeTableIds, subnetIds }));
});
return resources;
}
|
javascript
|
{
"resource": ""
}
|
q52409
|
buildLambdaVPCEndpointSecurityGroup
|
train
|
function buildLambdaVPCEndpointSecurityGroup({ name = 'LambdaEndpointSecurityGroup' } = {}) {
return {
[name]: {
Type: 'AWS::EC2::SecurityGroup',
Properties: {
GroupDescription: 'Lambda access to VPC endpoints',
VpcId: {
Ref: 'VPC',
},
SecurityGroupIngress: [
{
SourceSecurityGroupId: {
Ref: 'LambdaExecutionSecurityGroup',
},
Description: 'Allow inbound HTTPS traffic from LambdaExecutionSecurityGroup',
IpProtocol: 'tcp',
FromPort: 443,
ToPort: 443,
},
],
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
'lambda-endpoint',
],
],
},
},
],
},
},
};
}
|
javascript
|
{
"resource": ""
}
|
q52410
|
buildOutputs
|
train
|
function buildOutputs(createBastionHost = false) {
const outputs = {
VPC: {
Description: 'VPC logical resource ID',
Value: {
Ref: 'VPC',
},
},
LambdaExecutionSecurityGroupId: {
Description:
'Security Group logical resource ID that the Lambda functions use when executing within the VPC',
Value: {
Ref: 'LambdaExecutionSecurityGroup',
},
},
};
if (createBastionHost) {
outputs.BastionSSHUser = {
Description: 'SSH username for the Bastion host',
Value: 'ec2-user',
};
outputs.BastionEIP = {
Description: 'Public IP of Bastion host',
Value: {
Ref: 'BastionEIP',
},
};
}
return outputs;
}
|
javascript
|
{
"resource": ""
}
|
q52411
|
processNestedOperator
|
train
|
function processNestedOperator( path, operand ) {
var opKeys = Object.keys( operand );
return {
operation : opKeys[ 0 ],
operands : [operand[ opKeys[ 0 ] ]],
path : path
};
}
|
javascript
|
{
"resource": ""
}
|
q52412
|
processExpressionObject
|
train
|
function processExpressionObject( val, key ) {
var operator;
if ( sys.isObject( val ) ) {
var opKeys = Object.keys( val );
var op = opKeys[ 0 ];
if ( sys.indexOf( nestedOps, op ) > -1 ) {
operator = processNestedOperator( key, val );
} else if ( sys.indexOf( prefixOps, key ) > -1 ) {
operator = processPrefixOperator( key, val );
} else if ( op === "$regex" ) {
// special handling for regex options
operator = processNestedOperator( key, val );
} else if ( op === "$elemMatch" ) {
// elemMatch is just a weird duck
operator = {
path : key,
operation : op,
operands : []
};
sys.each( val[ op ], function ( entry ) {
operator.operands = parseQueryExpression( entry );
} );
}
else {
throw new Error( "Unrecognized operator" );
}
} else {
operator = processNestedOperator( key, { $eq : val } );
}
return operator;
}
|
javascript
|
{
"resource": ""
}
|
q52413
|
processPrefixOperator
|
train
|
function processPrefixOperator( operation, operand ) {
var component = {
operation : operation,
path : null,
operands : []
};
if ( sys.isArray( operand ) ) {
//if it is an array we need to loop through the array and parse each operand
//if it is an array we need to loop through the array and parse each operand
sys.each( operand, function ( obj ) {
sys.each( obj, function ( val, key ) {
component.operands.push( processExpressionObject( val, key ) );
} );
} );
} else {
//otherwise it is an object and we can parse it directly
sys.each( operand, function ( val, key ) {
component.operands.push( processExpressionObject( val, key ) );
} );
}
return component;
}
|
javascript
|
{
"resource": ""
}
|
q52414
|
parseQueryExpression
|
train
|
function parseQueryExpression( obj ) {
if ( sys.size( obj ) > 1 ) {
var arr = sys.map( obj, function ( v, k ) {
var entry = {};
entry[k] = v;
return entry;
} );
obj = {
$and : arr
};
}
var payload = [];
sys.each( obj, function ( val, key ) {
var exprObj = processExpressionObject( val, key );
if ( exprObj.operation === "$regex" ) {
exprObj.options = val.$options;
}
payload.push( exprObj );
} );
return payload;
}
|
javascript
|
{
"resource": ""
}
|
q52415
|
reachin
|
train
|
function reachin( path, record ) {
var context = record;
var part;
var _i;
var _len;
for ( _i = 0, _len = path.length; _i < _len; _i++ ) {
part = path[_i];
context = context[part];
if ( sys.isNull( context ) || sys.isUndefined( context ) ) {
break;
}
}
return context;
}
|
javascript
|
{
"resource": ""
}
|
q52416
|
execQuery
|
train
|
function execQuery( obj, qu, shortCircuit, stopOnFirst ) {
var arrayResults = [];
var keyResults = [];
sys.each( obj, function ( record, key ) {
var expr, result, test, _i, _len;
for ( _i = 0, _len = qu.length; _i < _len; _i++ ) {
expr = qu[_i];
if ( expr.splitPath ) {
test = reachin( expr.splitPath, record, expr.operation );
}
result = operations[expr.operation]( expr, test, record );
if ( result ) {
arrayResults.push( record );
keyResults.push( key );
}
if ( !result && shortCircuit ) {
break;
}
}
if ( arrayResults.length > 0 && stopOnFirst ) {
return false;
}
} );
return {
arrayResults : arrayResults,
keyResults : keyResults
};
}
|
javascript
|
{
"resource": ""
}
|
q52417
|
categorizeCommits
|
train
|
function categorizeCommits(rawCommits) {
const categorizedCommits = {};
// create a bucket of rawCommits by type:
// { fixes: [], upgrades: [], breaking: [] }
rawCommits.forEach(function(commit) {
const capType = capitalize(commit.type);
if (!categorizedCommits.hasOwnProperty(capType)) {
categorizedCommits[capType] = [];
}
categorizedCommits[capType].push(commit);
});
return categorizedCommits;
}
|
javascript
|
{
"resource": ""
}
|
q52418
|
createStringifyStream
|
train
|
function createStringifyStream(opts) {
assert.object(opts, 'opts');
assert.ok(Array.isArray(opts.body) || typeof opts.body === 'object',
'opts.body must be an array or object');
return stringifyStreamFactory(opts.body, null, null, true);
}
|
javascript
|
{
"resource": ""
}
|
q52419
|
parse
|
train
|
function parse(opts, callback) {
assert.object(opts, 'opts');
assert.string(opts.body, 'opts.body');
assert.func(callback, 'callback');
const sourceStream = intoStream(opts.body);
const parseStream = createParseStream();
const cb = once(callback);
parseStream.on('data', function(data) {
return cb(null, data);
});
parseStream.on('error', function(err) {
return cb(err);
});
sourceStream.pipe(parseStream);
}
|
javascript
|
{
"resource": ""
}
|
q52420
|
stringify
|
train
|
function stringify(opts, callback) {
assert.object(opts, 'opts');
assert.func(callback, 'callback');
let stringified = '';
const stringifyStream = createStringifyStream(opts);
const passthroughStream = new stream.PassThrough();
const cb = once(callback);
// setup the passthrough stream as a sink
passthroughStream.on('data', function(chunk) {
stringified += chunk;
});
passthroughStream.on('end', function() {
return cb(null, stringified);
});
// don't know what errors stringify stream may emit, but pass them back
// up.
stringifyStream.on('error', function(err) {
return cb(err);
});
stringifyStream.pipe(passthroughStream);
}
|
javascript
|
{
"resource": ""
}
|
q52421
|
read
|
train
|
function read(cb) {
return function (name, args) {
function resultCb(result) {
var status = util.statusByColor(result.color);
var color = util.colorByStatus(status, result.color);
console.log('%s | %s', name, text.__(status)[color]);
result.healthReport.forEach(function (report) {
console.log(' - %s', report.description);
});
}
function jenkinsCb(jenkins) {
jenkins.readJob(name, cli.exitCb(null, resultCb));
}
cb(args, jenkinsCb);
};
}
|
javascript
|
{
"resource": ""
}
|
q52422
|
update
|
train
|
function update(cb) {
return function (name, configFile, args) {
function resultCb(result) {
console.log(text.__('Job %s was updated successfully'), name);
}
function jenkinsCb(jenkins) {
var config = fs.readFileSync(configFile).toString();
jenkins.updateJob(name, config, cli.exitCb(null, resultCb));
}
cb(args, jenkinsCb);
};
}
|
javascript
|
{
"resource": ""
}
|
q52423
|
_console
|
train
|
function _console(cb) {
return function (name, buildNumber, args) {
if (!args) {
args = buildNumber;
buildNumber = null;
}
function jenkinsCb(jenkins) {
// console does not trigger any build, interval is set to 0 (no-pending delay time)
var interval = 0;
var stream = jenkins.streamJobConsole(name, buildNumber, interval, cli.exit);
stream.pipe(process.stdout, { end: false });
}
cb(args, jenkinsCb);
};
}
|
javascript
|
{
"resource": ""
}
|
q52424
|
enable
|
train
|
function enable(cb) {
return function (name, args) {
function resultCb(result) {
console.log(text.__('Job %s was enabled successfully'), name);
}
function jenkinsCb(jenkins) {
jenkins.enableJob(name, cli.exitCb(null, resultCb));
}
cb(args, jenkinsCb);
};
}
|
javascript
|
{
"resource": ""
}
|
q52425
|
copy
|
train
|
function copy(cb) {
return function (existingName, newName, args) {
function resultCb(result) {
console.log(text.__('Job %s was copied to job %s'), existingName, newName);
}
function jenkinsCb(jenkins) {
jenkins.copyJob(existingName, newName, cli.exitCb(null, resultCb));
}
cb(args, jenkinsCb);
};
}
|
javascript
|
{
"resource": ""
}
|
q52426
|
fetchConfig
|
train
|
function fetchConfig(cb) {
return function (name, args) {
function resultCb(result) {
console.log(result);
}
function jenkinsCb(jenkins) {
jenkins.fetchViewConfig(name, cli.exitCb(null, resultCb));
}
cb(args, jenkinsCb);
};
}
|
javascript
|
{
"resource": ""
}
|
q52427
|
update
|
train
|
function update(name, config, cb) {
this.remoteAccessApi.postViewConfig(name, config, this.opts.headers, cb);
}
|
javascript
|
{
"resource": ""
}
|
q52428
|
discover
|
train
|
function discover(host, cb) {
const TIMEOUT = 5000;
var socket = dgram.createSocket('udp4');
var buffer = new Buffer(text.__('Long live Jenkins!'));
var parser = new xml2js.Parser();
socket.on('error', function (err) {
socket.close();
cb(err);
});
socket.on('message', function (result) {
socket.close();
parser.addListener('end', function (result) {
cb(null, result);
});
parser.parseString(result);
});
socket.send(buffer, 0, buffer.length, 33848, host, function (err, result) {
if (err) {
socket.close();
cb(err);
}
});
setTimeout(function () {
cb(new Error(text.__('Unable to find any Jenkins instance on %s', host)));
}, TIMEOUT);
}
|
javascript
|
{
"resource": ""
}
|
q52429
|
version
|
train
|
function version(cb) {
function _cb(err, result, response) {
if (err) {
cb(err);
} else if (response.headers['x-jenkins']) {
cb(null, response.headers['x-jenkins']);
} else {
cb(new Error(text.__('Not a Jenkins server')));
}
}
this.remoteAccessApi.headJenkins(_cb);
}
|
javascript
|
{
"resource": ""
}
|
q52430
|
executorSummary
|
train
|
function executorSummary(computers) {
var data = {};
computers.forEach(function (computer) {
var idleCount = 0;
var activeCount = 0;
data[computer.displayName] = { executors: [] };
computer.executors.forEach(function (executor) {
data[computer.displayName].executors.push({
idle: executor.idle,
stuck: executor.likelyStuck,
progress: executor.progress,
name: (!executor.idle && executor.currentExecutable.url) ?
executor.currentExecutable.url.replace(/.*\/job\//, '').replace(/\/.*/, '') :
undefined
});
if (executor.idle) {
idleCount += 1;
} else {
activeCount += 1;
}
});
var summary = [];
if (activeCount > 0) {
summary.push(text.__('%d active', activeCount));
}
if (idleCount > 0) {
summary.push(text.__('%d idle', idleCount));
}
data[computer.displayName].summary = summary.join(', ');
});
return data;
}
|
javascript
|
{
"resource": ""
}
|
q52431
|
monitor
|
train
|
function monitor(opts, cb) {
var self = this;
function singleJobResultCb(err, result) {
if (!err) {
result = util.statusByColor(result.color);
}
cb(err, result);
}
// when there are multiple jobs, status is derived following these rules:
// - fail if any job has Jenkins color red
// - warn if any job has Jenkins color yellow but no red
// - non-success (e.g. notbuilt) if any job has Jenkins color status but no red and yellow
// - success only if all jobs are either blue or green
function multiJobsResultCb(err, result) {
if (!err) {
var hasRed = false;
var hasYellow = false;
var hasNonSuccess = false;
var hasSuccess = false;
var successColor;
var nonSuccessColor;
result.jobs.forEach(function (job) {
if (job.color === 'red') {
hasRed = true;
}
if (job.color === 'yellow') {
hasYellow = true;
}
if (['red', 'yellow', 'blue', 'green'].indexOf(job.color) === -1) {
hasNonSuccess = true;
nonSuccessColor = job.color;
}
if (job.color === 'blue' || job.color === 'green') {
hasSuccess = true;
successColor = job.color;
}
});
var resultColor;
if (hasRed) {
resultColor = 'red';
} else if (hasYellow) {
resultColor = 'yellow';
} else if (hasNonSuccess) {
resultColor = nonSuccessColor;
} else {
resultColor = successColor;
}
result = util.statusByColor(resultColor);
}
cb(err, result);
}
function _notify() {
if (opts.job) {
self.readJob(opts.job, singleJobResultCb);
} else if (opts.view) {
self.readView(opts.view, multiJobsResultCb);
} else {
self.info(multiJobsResultCb);
}
}
_notify();
new cron.CronJob(opts.schedule || '0 * * * * *', _notify).start();
}
|
javascript
|
{
"resource": ""
}
|
q52432
|
htmlError
|
train
|
function htmlError(result, cb) {
var message = result.body
.match(/<h1>Error<\/h1>.+<\/p>/).toString()
.replace(/<h1>Error<\/h1>/, '')
.replace(/<\/?p>/g, '');
cb(new Error(message));
}
|
javascript
|
{
"resource": ""
}
|
q52433
|
jobBuildNotFoundError
|
train
|
function jobBuildNotFoundError(name, buildNumber) {
return function (result, cb) {
cb(new Error(text.__('Job %s build %d does not exist', name, buildNumber)));
};
}
|
javascript
|
{
"resource": ""
}
|
q52434
|
create
|
train
|
function create(name, config, cb) {
var opts = {
body: config,
contentType: 'application/xml',
};
this.remoteAccessApi.postCreateItem(name, _.merge(opts, this.opts.headers), cb);
}
|
javascript
|
{
"resource": ""
}
|
q52435
|
update
|
train
|
function update(name, config, cb) {
this.remoteAccessApi.postJobConfig(name, config, this.opts.headers, cb);
}
|
javascript
|
{
"resource": ""
}
|
q52436
|
build
|
train
|
function build(name, params, cb) {
var body = { parameter: [] } ;
_.keys(params).forEach(function (key) {
body.parameter.push({ name: key, value: params[key] });
});
var opts = {
token: 'nestor'
};
this.remoteAccessApi.postJobBuild(name, JSON.stringify(body), _.merge(opts, this.opts.headers), cb);
}
|
javascript
|
{
"resource": ""
}
|
q52437
|
copy
|
train
|
function copy(existingName, newName, cb) {
var opts = {
mode: 'copy',
from: existingName,
contentType: 'text/plain',
};
this.remoteAccessApi.postCreateItem(newName, _.merge(opts, this.opts.headers), cb);
}
|
javascript
|
{
"resource": ""
}
|
q52438
|
dashboard
|
train
|
function dashboard(cb) {
return function (args) {
function resultCb(result) {
var jobs = result.jobs;
if (_.isEmpty(jobs)) {
console.log(text.__('Jobless Jenkins'));
} else {
jobs.forEach(function (job) {
var status = util.statusByColor(job.color);
var color = util.colorByStatus(status, job.color);
console.log('%s - %s', text.__(status)[color], job.name);
});
}
}
function jenkinsCb(jenkins) {
jenkins.info(cli.exitCb(null, resultCb));
}
cb(args, jenkinsCb);
};
}
|
javascript
|
{
"resource": ""
}
|
q52439
|
discover
|
train
|
function discover(cb) {
return function (host, args) {
if (!args) {
args = host || {};
host = 'localhost';
}
function resultCb(result) {
console.log(text.__('Jenkins ver. %s is running on %s'),
result.hudson.version[0],
(result.hudson.url && result.hudson.url[0]) ? result.hudson.url[0] : host);
}
function jenkinsCb(jenkins) {
jenkins.discover(host, cli.exitCb(null, resultCb));
}
cb(args, jenkinsCb);
};
}
|
javascript
|
{
"resource": ""
}
|
q52440
|
executor
|
train
|
function executor(cb) {
return function (args) {
function resultCb(result) {
var computers = result.computer;
if (_.isEmpty(computers)) {
console.log(text.__('No executor found'));
} else {
var data = Jenkins.executorSummary(computers);
_.keys(data).forEach(function (computer) {
console.log('+ %s | %s', computer, data[computer].summary);
data[computer].executors.forEach(function (executor) {
if (!executor.idle) {
console.log(' - %s | %s%%s', executor.name, executor.progress, (executor.stuck) ? text.__(' stuck!') : '');
}
});
});
}
}
function jenkinsCb(jenkins) {
jenkins.computer(cli.exitCb(null, resultCb));
}
cb(args, jenkinsCb);
};
}
|
javascript
|
{
"resource": ""
}
|
q52441
|
feed
|
train
|
function feed(cb) {
return function (args) {
function resultCb(result) {
result.forEach(function (article) {
console.log(article.title);
});
}
function jenkinsCb(jenkins) {
if (args.job) {
jenkins.parseJobFeed(args.job, cli.exitCb(null, resultCb));
} else if (args.view) {
jenkins.parseViewFeed(args.view, cli.exitCb(null, resultCb));
} else {
jenkins.parseFeed(cli.exitCb(null, resultCb));
}
}
cb(args, jenkinsCb);
};
}
|
javascript
|
{
"resource": ""
}
|
q52442
|
colorByStatus
|
train
|
function colorByStatus(status, jenkinsColor) {
var color;
if (jenkinsColor) {
// Jenkins color value can contain either a color, color_anime, or status in job.color field,
// hence to get color/status value out of the mix we need to remove the postfix _anime,
// _anime postfix only exists on a job currently being built
jenkinsColor = jenkinsColor.replace(/_anime$/, '');
color = (COLOR_STATUS[jenkinsColor] && COLOR_STATUS[jenkinsColor][0]) ? jenkinsColor : 'grey';
} else {
color = 'grey';
_.keys(COLOR_STATUS).forEach(function (_color) {
COLOR_STATUS[_color].forEach(function (_status) {
if (_status === status) {
color = _color;
}
});
});
}
return color;
}
|
javascript
|
{
"resource": ""
}
|
q52443
|
statusByColor
|
train
|
function statusByColor(jenkinsColor) {
if (jenkinsColor) {
// Jenkins color value can contain either a color, color_anime, or status in job.color field,
// hence to get color/status value out of the mix we need to remove the postfix _anime,
// _anime postfix only exists on a job currently being built
jenkinsColor = jenkinsColor.replace(/_anime$/, '');
status = (COLOR_STATUS[jenkinsColor]) ? COLOR_STATUS[jenkinsColor][0] : jenkinsColor;
} else {
status = 'unknown';
}
return status;
}
|
javascript
|
{
"resource": ""
}
|
q52444
|
parsePart
|
train
|
function parsePart () {
chars = true;
parseTag();
var same = html === last;
last = html;
if (same) { // discard, because it's invalid
html = '';
}
}
|
javascript
|
{
"resource": ""
}
|
q52445
|
build
|
train
|
function build(outputDir) {
let exec = require("child_process").exec;
let elmFile = path.join(argv.src, argv.elmFile);
let cmd = "elm-make " + elmFile + " --yes --output " + argv.output + "/" + argv.language + ".js";
console.log(cmd);
exec(cmd, (err, stdout, stderr) => {
if(err) {
console.error(err);
return;
}
console.log(stdout);
});
}
|
javascript
|
{
"resource": ""
}
|
q52446
|
handleExport
|
train
|
function handleExport(resultString) {
if (resultString === "") {
process.exit(500);
}
let targetPath = path.join(currentDir, argv.exportOutput);
fs.writeFileSync(targetPath, resultString);
console.log("Finished writing csv file to:", targetPath);
}
|
javascript
|
{
"resource": ""
}
|
q52447
|
htmlToProgram
|
train
|
function htmlToProgram(vnode)
{
var emptyBag = batch(_elm_lang$core$Native_List.Nil);
var noChange = _elm_lang$core$Native_Utils.Tuple2(
_elm_lang$core$Native_Utils.Tuple0,
emptyBag
);
return _elm_lang$virtual_dom$VirtualDom$program({
init: noChange,
view: function(model) { return main; },
update: F2(function(msg, model) { return noChange; }),
subscriptions: function (model) { return emptyBag; }
});
}
|
javascript
|
{
"resource": ""
}
|
q52448
|
spawnLoop
|
train
|
function spawnLoop(init, onMessage)
{
var andThen = _elm_lang$core$Native_Scheduler.andThen;
function loop(state)
{
var handleMsg = _elm_lang$core$Native_Scheduler.receive(function(msg) {
return onMessage(msg, state);
});
return A2(andThen, loop, handleMsg);
}
var task = A2(andThen, loop, init);
return _elm_lang$core$Native_Scheduler.rawSpawn(task);
}
|
javascript
|
{
"resource": ""
}
|
q52449
|
createPageHandler
|
train
|
function createPageHandler(page) {
if (DEBUG && !page.phantom) inspectArgs("createPageHandler: ", page);
phPage = page;
var matches;
if (option.viewportsize) {
matches = option.viewportsize.match(/^(\d+)x(\d+)$/);
if (matches !== null) {
page.property("viewportSize", {width: matches[1], height: matches[2]});
}
}
if (option.cliprect) {
matches = option.cliprect.match(/^(\d+)x(\d+)x(\d+)x(\d+)$/);
if (matches !== null) {
page.setting("clipRect", {top: matches[1], left: matches[2],
width: matches[3], height: matches[4]});
}
}
if (option["user-agent"]) {
page.setting("userAgent", option["user-agent"]);
}
if (option.zoomfactor) {
page.setting("zoomFactor", parseFloat(option.zoomfactor));
}
if (option.timeout) {
timer = setTimeout(function () {
var err = `capturejs: cannot access ${option.uri}: request timed out`;
console.error(err);
phInstance.exit();
process.nextTick(function () { callback(err) });
}, +option.timeout);
}
return page.open(option.uri);
}
|
javascript
|
{
"resource": ""
}
|
q52450
|
reportStatus
|
train
|
function reportStatus(status) {
if (DEBUG && status !== "success") inspectArgs("reportStatus: ", status);
if (status === "fail") {
var err = `capturejs: cannot access ${option.uri}: failed to open page`;
console.error(err);
phInstance.exit();
process.nextTick(callback, err);
} else {
return phPage;
}
}
|
javascript
|
{
"resource": ""
}
|
q52451
|
manipulatePage
|
train
|
function manipulatePage(page) {
if (DEBUG && !page.phantom) inspectArgs("manipulatePage: ", page);
if (timer !== undefined) {
clearTimeout(timer);
}
// Inject an external script file.
if (option["javascript-file"]) {
page.injectJs(option["javascript-file"]);
}
// Inject an in-line script from the command line.
if (option["inject-script"]) {
var injectScript = option["inject-script"];
injectScript = (typeof injectScript === "function") ?
injectScript.toString() : `function() { ${injectScript} }`;
page.evaluateJavaScript(injectScript);
}
if (option.waitcapturedelay) {
setTimeout(function () { return page }, +option.waitcapturedelay);
} else {
return page;
}
}
|
javascript
|
{
"resource": ""
}
|
q52452
|
captureImage
|
train
|
function captureImage(page) {
if (DEBUG && !page.phantom) inspectArgs("captureImage: ", page);
if (option.selector) {
let getElement = [ "function () {",
, "document.body.bgColor = 'white';"
, `var elem = document.querySelector('${option.selector}');`
, "return (elem !== null) ? elem.getBoundingClientRect() : null; };"
].join("");
return page.evaluateJavaScript(getElement);
}
}
|
javascript
|
{
"resource": ""
}
|
q52453
|
saveImage
|
train
|
function saveImage(rect) {
if (DEBUG && rect && !rect.bottom) inspectArgs("saveImage: ", rect);
if (rect && typeof rect.bottom === "number") {
phPage.property("clipRect", rect);
}
// Set a timeout to give the page a chance to render.
setTimeout(function () {
phPage.render(option.output)
.then(function () {
phInstance.exit();
// process.removeListener("uncaughtException", onUncaughtException);
process.nextTick(callback);
});
}, option.renderdelay || 250);
}
|
javascript
|
{
"resource": ""
}
|
q52454
|
ajax
|
train
|
function ajax(url, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
callback = callback || function () {};
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status >= 400) {
return callback(new Error(xhr.responseText || xhr.statusText));
}
try {
return callback(null, JSON.parse(xhr.responseText));
} catch (e) {
return callback(new Error('invalid_response'));
}
};
xhr.onerror = function (err) {
return callback(err);
};
xhr.open('GET', url);
xhr.send();
}
|
javascript
|
{
"resource": ""
}
|
q52455
|
relative_px
|
train
|
function relative_px(type, value) {
var w = window,
d = document,
e = d.documentElement,
g = d.body,
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight || e.clientHeight || g.clientHeight;
if (type === 'vw') {
return (x * parseFloat(value)) / 100;
} else if (type === 'vh') {
return (y * parseFloat(value)) / 100;
} else {
return undefined;
}
}
|
javascript
|
{
"resource": ""
}
|
q52456
|
percent_px
|
train
|
function percent_px(el, prop, percent) {
var parent_width = Embedo.utils.compute(el.parentNode, prop, true);
percent = parseFloat(percent);
return parent_width * (percent / 100);
}
|
javascript
|
{
"resource": ""
}
|
q52457
|
_iniBtnWrapper
|
train
|
function _iniBtnWrapper() {
var $wrapper = gearbox.dom.$body || gearbox.dom.$root
$wrapper.on('click', function (ev) {
var $target = gearbox.$(ev.target)
if ($target.hasClass(CLS_BTN_WRAPPER) && !$target.hasClass(CLS_BTN_DISABLED)) {
var $btnWrapper = $target
var selBtn = ([].concat('.' + CLS_BTN, BTN_ELEM_TAGS)).join(', ')
var $btn = $btnWrapper.find(selBtn).first()
if (!$btn.hasClass(CLS_BTN_DISABLED)) {
$btn.trigger('click')
}
}
})
}
|
javascript
|
{
"resource": ""
}
|
q52458
|
renderNode
|
train
|
function renderNode(rootNode) {
let createdPromises = [];
var document = getDocument(rootNode);
recurseTree(rootNode, (foundNode) => {
if (foundNode.tagName) {
let nodeType = foundNode.tagName.toLowerCase();
let customElement = registeredElements[nodeType];
if (customElement) {
// TODO: Should probably clone node, not change prototype, for performance
Object.setPrototypeOf(foundNode, customElement);
if (customElement.createdCallback) {
createdPromises.push(new Promise((resolve) => {
resolve(customElement.createdCallback.call(foundNode, document));
}));
}
}
}
});
return Promise.all(createdPromises).then(() => rootNode);
}
|
javascript
|
{
"resource": ""
}
|
q52459
|
format
|
train
|
function format(template, values) {
return Object
.entries(values)
.filter(
([key]) => /^[a-z0-9_-]+$/gi.test(key)
)
.map(
([key, value]) =>
[new RegExp(`([^{]|^){${key}}([^}]|$)`,'g'), `$1${value}$2`]
)
.reduce(
(str, [regexp, replacement]) => {
return str.replace(regexp, replacement)
}, template
)
.replace(/({|}){2}/g, '$1')
}
|
javascript
|
{
"resource": ""
}
|
q52460
|
filterConfig
|
train
|
function filterConfig(config) {
return Object
.entries(config)
.filter(
([key, value]) =>
typeof value === typeof DEFAULT_CONFIG[key]
)
.reduce(
(obj, [key, value]) => {
obj[key] = value
return obj
}, {}
)
}
|
javascript
|
{
"resource": ""
}
|
q52461
|
downloadString
|
train
|
function downloadString(url, {userAgent}) {
let deferred = Q.defer()
let startTime = Date.now()
let data = ''
request({
method: 'GET',
url: url,
headers: {
'User-Agent': userAgent
}
}, function(error, response, body) {
if(error) {
deferred.reject(new Error(error))
return;
}
deferred.resolve({
time: Date.now() - startTime,
result: body,
statusCode: response.statusCode
})
})
return deferred.promise
}
|
javascript
|
{
"resource": ""
}
|
q52462
|
arrayFrom
|
train
|
function arrayFrom(arrayLike, delimiter=',') {
if(typeof arrayLike === 'string')
return arrayLike.split(delimiter)
return Array.from(arrayLike)
}
|
javascript
|
{
"resource": ""
}
|
q52463
|
repairUrl
|
train
|
function repairUrl(url) {
return normalizeUrl(url
.replace(/&/gi, '&')
.replace(/</gi, '<')
.replace(/>/gi, '>')
.replace(/"/gi, '"')
.replace(/'/gi, '\'')
)
.trim()
.replace(/\s+/g,'+')
}
|
javascript
|
{
"resource": ""
}
|
q52464
|
extend
|
train
|
function extend(o) {
if (typeOf(o) !== 'object') { return {}; }
var args = arguments;
var len = args.length - 1;
for (var i = 0; i < len; i++) {
var obj = args[i + 1];
if (typeOf(obj) === 'object' && typeOf(obj) !== 'regexp') {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
o[key] = obj[key];
}
}
}
}
return o;
}
|
javascript
|
{
"resource": ""
}
|
q52465
|
train
|
function (id) {
if (!paths.has(id)) {
return;
}
var code = [
`import shimWorker from 'rollup-plugin-bundle-worker';`,
`export default new shimWorker(${JSON.stringify(paths.get(id))}, function (window, document) {`,
`var self = this;`,
fs.readFileSync(id, 'utf-8'),
`\n});`
].join('\n');
return code;
}
|
javascript
|
{
"resource": ""
}
|
|
q52466
|
getCriticalFromAtRule
|
train
|
function getCriticalFromAtRule(args) {
var result = {};
var options = _extends({
defaultDest: 'critical.css',
css: _postcss2.default.root()
}, args);
options.css.walkAtRules('critical', function (atRule) {
var name = atRule.params ? atRule.params : options.defaultDest;
// If rule has no nodes, all the nodes of the parent will be critical.
var rule = atRule;
if (!atRule.nodes) {
rule = atRule.root();
}
rule.clone().each(function (node) {
if (node.name !== 'critical') {
result[name] = result[name] ? result[name].append(node) : _postcss2.default.root().append(node);
}
});
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q52467
|
dryRunOrWriteFile
|
train
|
function dryRunOrWriteFile(dryRun, filePath, result) {
var css = result.css;
return new Promise(function (resolve) {
return resolve(dryRun ? doDryRun(css) : writeCriticalFile(filePath, css));
});
}
|
javascript
|
{
"resource": ""
}
|
q52468
|
hasNoOtherChildNodes
|
train
|
function hasNoOtherChildNodes() {
var nodes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var node = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _postcss2.default.root();
return nodes.filter(function (child) {
return child !== node;
}).length === 0;
}
|
javascript
|
{
"resource": ""
}
|
q52469
|
writeCriticalFile
|
train
|
function writeCriticalFile(filePath, css) {
_fs2.default.writeFile(filePath, css, { flag: append ? 'a' : 'w' }, function (err) {
append = true;
if (err) {
console.error(err);
process.exit(1);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q52470
|
buildCritical
|
train
|
function buildCritical() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var filteredOptions = Object.keys(options).reduce(function (acc, key) {
return typeof options[key] !== 'undefined' ? _extends({}, acc, _defineProperty({}, key, options[key])) : acc;
}, {});
var args = _extends({
outputPath: process.cwd(),
outputDest: 'critical.css',
preserve: true,
minify: true,
dryRun: false
}, filteredOptions);
append = false;
return function (css) {
var dryRun = args.dryRun,
preserve = args.preserve,
minify = args.minify,
outputPath = args.outputPath,
outputDest = args.outputDest;
var criticalOutput = (0, _getCriticalRules.getCriticalRules)(css, outputDest);
return Object.keys(criticalOutput).reduce(function (init, cur) {
var criticalCSS = _postcss2.default.root();
var filePath = _path2.default.join(outputPath, cur);
criticalOutput[cur].each(function (rule) {
return criticalCSS.append(rule.clone());
});
return (0, _postcss2.default)(minify ? [_cssnano2.default] : [])
// @TODO Use from/to correctly.
.process(criticalCSS, {
from: undefined
}).then(dryRunOrWriteFile.bind(null, dryRun, filePath)).then(clean.bind(null, css, preserve));
}, {});
};
}
|
javascript
|
{
"resource": ""
}
|
q52471
|
clean
|
train
|
function clean(root) {
var test = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'critical-selector';
var clone = root.clone();
if (clone.type === 'decl') {
clone.remove();
} else {
clone.walkDecls(test, function (decl) {
decl.remove();
});
}
return clone;
}
|
javascript
|
{
"resource": ""
}
|
q52472
|
correctSourceOrder
|
train
|
function correctSourceOrder(root) {
var sortedRoot = _postcss2.default.root();
var clone = root.clone();
clone.walkRules(function (rule) {
var start = rule.source.start.line;
if (rule.parent.type === 'atrule') {
var child = rule;
rule = _postcss2.default.atRule({
name: rule.parent.name,
params: rule.parent.params
}).append(rule.clone());
rule.source = child.source;
start = child.source.start.line;
}
if (sortedRoot.nodes.length === 0 || sortedRoot.last && sortedRoot.last.source.start.line > start) {
sortedRoot.prepend(rule);
} else {
sortedRoot.append(rule);
}
});
return sortedRoot;
}
|
javascript
|
{
"resource": ""
}
|
q52473
|
establishContainer
|
train
|
function establishContainer(node) {
return node.parent.type === 'atrule' && node.parent.name !== 'critical' ? _postcss2.default.atRule({
name: node.parent.name,
type: node.parent.type,
params: node.parent.params,
nodes: [node]
}) : node.clone();
}
|
javascript
|
{
"resource": ""
}
|
q52474
|
updateCritical
|
train
|
function updateCritical(root, update) {
var clonedRoot = root.clone();
if (update.type === 'rule') {
clonedRoot.append(clean(update.clone()));
} else {
update.clone().each(function (rule) {
clonedRoot.append(clean(rule.root()));
});
}
return clonedRoot;
}
|
javascript
|
{
"resource": ""
}
|
q52475
|
getCriticalDestination
|
train
|
function getCriticalDestination(rule, dest) {
rule.walkDecls('critical-filename', function (decl) {
dest = decl.value.replace(/['"]*/g, '');
decl.remove();
});
return dest;
}
|
javascript
|
{
"resource": ""
}
|
q52476
|
spreadAttributeAST
|
train
|
function spreadAttributeAST(plugin, ref, deps) {
const { hasOwn } = deps;
const spread = t.identifier("spread");
const prop = t.identifier("prop");
/**
* function _spreadAttribute(spread) {
* for (var prop in spread) {
* if (_hasOwn.call(spread, prop)) {
* attr(prop, spread[prop]);
* }
* }
* }
*/
return t.functionExpression(
ref,
[spread],
t.blockStatement([
t.forInStatement(
t.variableDeclaration("var", [t.variableDeclarator(prop)]),
spread,
t.ifStatement(
toFunctionCall(t.memberExpression(
hasOwn,
t.identifier("call")
), [spread, prop]),
t.expressionStatement(toFunctionCall(iDOMMethod("attr", plugin), [
prop,
t.memberExpression(spread, prop, true)
]))
)
)
])
);
}
|
javascript
|
{
"resource": ""
}
|
q52477
|
inPatchRoot
|
train
|
function inPatchRoot(path, plugin) {
const { opts } = plugin;
if (useFastRoot(path, opts)) {
return true;
}
const roots = patchRoots(plugin)
return !roots.length || path.findParent((parent) => {
return roots.indexOf(parent) > -1;
});
}
|
javascript
|
{
"resource": ""
}
|
q52478
|
isArray
|
train
|
function isArray(value) {
return toFunctionCall(
t.memberExpression(
t.identifier("Array"),
t.identifier("isArray")
),
[value]
);
}
|
javascript
|
{
"resource": ""
}
|
q52479
|
isPlainObject
|
train
|
function isPlainObject(value) {
return t.binaryExpression(
"===",
toFunctionCall(t.identifier("String"), [value]),
t.stringLiteral("[object Object]")
);
}
|
javascript
|
{
"resource": ""
}
|
q52480
|
renderArbitraryAST
|
train
|
function renderArbitraryAST(plugin, ref, deps) {
const { hasOwn } = deps;
const child = t.identifier("child");
const type = t.identifier("type");
const func = t.identifier("func");
const args = t.identifier("args");
const i = t.identifier("i");
const prop = t.identifier("prop");
/**
* function _renderArbitrary(child) {
* var type = typeof child;
* if (type === "number" || (type === string || type === 'object' && child instanceof String)) {
* text(child);
* } else if (Array.isArray(child)) {
* for (var i = 0; i < child.length; i++) {
* _renderArbitrary(child[i]);
* }
* } else if (type === "object") {
* if (child.__jsxDOMWrapper) {
* var func = child.func, args = child.args;
* if (args) {
* func.apply(this, args);
* } else {
* func();
* }
* } else if (String(child) === "[object Object]") {
* for (var prop in child) {
* if (_hasOwn.call(child, prop)) {
* renderArbitrary(child[prop])
* }
* }
* }
* }
* }
*/
return t.functionExpression(
ref,
[child],
t.blockStatement([
t.variableDeclaration("var", [
t.variableDeclarator(
type,
t.unaryExpression("typeof", child)
)
]),
t.IfStatement(
isTextual(type, child),
t.blockStatement([
t.expressionStatement(toFunctionCall(iDOMMethod("text", plugin), [child]))
]),
t.ifStatement(
isArray(child),
t.blockStatement([
t.forStatement(
t.variableDeclaration("var", [t.variableDeclarator(i, t.numericLiteral(0))]),
t.binaryExpression("<", i, t.memberExpression(child, t.identifier("length"))),
t.updateExpression("++", i),
t.expressionStatement(toFunctionCall(ref, [
t.memberExpression(child, i, true)
]))
)
]),
t.ifStatement(
isObject(type),
t.blockStatement([
t.ifStatement(
isDOMWrapper(child),
t.blockStatement([
t.variableDeclaration("var", [
t.variableDeclarator(func, t.memberExpression(child, func)),
t.variableDeclarator(args, t.memberExpression(child, args))
]),
t.ifStatement(
args,
t.blockStatement([
t.expressionStatement(
toFunctionCall(t.memberExpression(func, t.identifier("apply")), [t.thisExpression(), args]),
)
]),
t.blockStatement([
t.expressionStatement(toFunctionCall(func, [])),
]),
)
]),
t.ifStatement(
isPlainObject(child),
t.blockStatement([
t.forInStatement(
t.variableDeclaration("var", [t.variableDeclarator(prop)]),
child,
t.ifStatement(
toFunctionCall(t.memberExpression(
hasOwn,
t.identifier("call")
), [child, i]),
t.expressionStatement(toFunctionCall(ref, [
t.memberExpression(child, i, true)
]))
)
)
])
)
)
])
)
)
)
])
);
}
|
javascript
|
{
"resource": ""
}
|
q52481
|
generateHoistNameBasedOn
|
train
|
function generateHoistNameBasedOn(path, suffix = "") {
const names = [];
if (suffix) {
names.push(suffix);
}
let current = path;
while (!(current.isIdentifier() || current.isJSXIdentifier())) {
names.push(current.node.property.name);
current = current.get("object");
}
names.push(current.node.name);
return path.scope.generateUidIdentifier(names.reverse().join("$"));
}
|
javascript
|
{
"resource": ""
}
|
q52482
|
isStringConcatenation
|
train
|
function isStringConcatenation(path) {
if (!(path.isBinaryExpression() && path.node.operator === "+")) {
return false;
}
const left = path.get("left");
const right = path.get("right");
return left.isStringLiteral() ||
right.isStringLiteral() ||
isStringConcatenation(left) ||
isStringConcatenation(right);
}
|
javascript
|
{
"resource": ""
}
|
q52483
|
beforeJvm
|
train
|
function beforeJvm() {
var moduleJars = ['target/ts-tinkerpop-3.0.1.GA.0.jar', 'target/dependency/commons-configuration-1.10.jar', 'target/dependency/commons-lang-2.6.jar', 'target/dependency/commons-lang3-3.3.1.jar', 'target/dependency/gremlin-core-3.0.1-incubating.jar', 'target/dependency/gremlin-groovy-3.0.1-incubating.jar', 'target/dependency/gremlin-shaded-3.0.1-incubating.jar', 'target/dependency/groovy-2.4.1-indy.jar', 'target/dependency/groovy-2.4.1.jar', 'target/dependency/groovy-console-2.4.1.jar', 'target/dependency/groovy-groovysh-2.4.1-indy.jar', 'target/dependency/groovy-json-2.4.1-indy.jar', 'target/dependency/groovy-jsr223-2.4.1-indy.jar', 'target/dependency/groovy-swing-2.4.1.jar', 'target/dependency/groovy-templates-2.4.1.jar', 'target/dependency/groovy-xml-2.4.1.jar', 'target/dependency/hamcrest-core-1.3.jar', 'target/dependency/hppc-0.7.1.jar', 'target/dependency/ivy-2.3.0.jar', 'target/dependency/jackson-annotations-2.5.0.jar', 'target/dependency/jackson-core-2.5.3.jar', 'target/dependency/jackson-databind-2.5.3.jar', 'target/dependency/javatuples-1.2.jar', 'target/dependency/jbcrypt-0.3m.jar', 'target/dependency/jcabi-log-0.14.jar', 'target/dependency/jcabi-manifests-1.1.jar', 'target/dependency/jcl-over-slf4j-1.7.12.jar', 'target/dependency/jline-2.12.jar', 'target/dependency/junit-4.11.jar', 'target/dependency/log4j-1.2.17.jar', 'target/dependency/slf4j-api-1.7.12.jar', 'target/dependency/slf4j-log4j12-1.7.12.jar', 'target/dependency/snakeyaml-1.15.jar', 'target/dependency/tinkergraph-gremlin-3.0.1-incubating.jar', 'target/ts-tinkerpop-3.0.1.GA.0.jar'];
moduleJars.forEach(function (jarPath) {
var fullJarPath = path.join(__dirname, '..', jarPath);
dlog('Adding to classpath:', fullJarPath);
_java.classpath.push(fullJarPath);
});
return BluePromise.resolve();
}
|
javascript
|
{
"resource": ""
}
|
q52484
|
instanceOf
|
train
|
function instanceOf(javaObject, className) {
var fullName = fullyQualifiedName(className) || className;
return smellsLikeJavaObject(javaObject) && _java.instanceOf(javaObject, fullName);
}
|
javascript
|
{
"resource": ""
}
|
q52485
|
train
|
function() {
if (insertCounter === 3) {
insertBtn.disabled = true;
}
else {
insertBtn.disabled = false;
}
if (insertCounter === -3) {
removeBtn.disabled = true;
}
else {
removeBtn.disabled = false;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52486
|
prepare
|
train
|
function prepare(config) {
config = config || {};
var settings = config.settings && config.settings[constants.PLUGIN_NAME] || {};
// Set paths, convert string values to array
settings.paths = objValuesToArray(settings.paths || {});
// Set allExceptPaths, convert string values to array
settings.allExceptPaths = objValuesToArray(settings.allExceptPaths || {});
// Set options for multimatch module
settings.pathsOptions = settings.pathsOptions || defaults.pathsOptions;
// Forward plugins from config or use custom ones, remove current plugin
settings.plugins = toArray(settings.plugins || config.plugins || []);
var index = settings.plugins.indexOf(constants.PLUGIN_NAME_SHORT);
if (index > -1) {
settings.plugins.splice(index, 1);
}
settings.cliArgs = settings.cliArgs || [];
return settings;
}
|
javascript
|
{
"resource": ""
}
|
q52487
|
subscribe
|
train
|
function subscribe(subscriber, immediate) {
if (!~subscribers.indexOf(subscriber)) {
subscribers.push(subscriber);
}
if (immediate) {
subscriber(value);
}
}
|
javascript
|
{
"resource": ""
}
|
q52488
|
load
|
train
|
function load() {
return new Promise(function (resolve) {
if (emojis) return resolve(emojis);
return fetch(enpoint).then(function (r) {
return r.json();
}).then(function (response) {
emojis = response;
resolve(emojis);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q52489
|
parse
|
train
|
function parse(text) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var output = '';
var customClassNames = options.classNames ? options.classNames.trim().split(/\s+/) : '';
output += text.replace(delimiterRegex, function (match) {
var name = match.replace(/:/g, '');
var classNames = ['gh-emoji', 'gh-emoji-' + name];
if (!exist(name)) {
return match;
}
if (customClassNames) {
classNames.push.apply(classNames, _toConsumableArray(customClassNames));
}
var imageSrc = getUrl(name);
var imageClass = classNames.join(' ');
var imageAlt = name;
return '<img src="' + imageSrc + '" class="' + imageClass + '" alt="' + imageAlt + '" />';
});
return output;
}
|
javascript
|
{
"resource": ""
}
|
q52490
|
buildUrl
|
train
|
function buildUrl(value, options, file) {
const [gist] = value.split(/[?#]/);
const [inlineUsername, id] =
gist.indexOf("/") > 0 ? gist.split("/") : [null, gist];
// username can come from inline code or options
const username = inlineUsername || options.username;
// checks for a valid username
if (username == null || username.trim().length === 0) {
throw new Error("Missing username information");
}
// checks for a valid id
if (id == null || id.trim().length === 0) {
throw new Error("Missing gist id information");
}
// builds the url and completes it with the file if any
let url = `${baseUrl}/${username}/${id}.json`;
if (file != null) {
url += `?file=${file}`;
}
return url;
}
|
javascript
|
{
"resource": ""
}
|
q52491
|
fromNumber
|
train
|
function fromNumber(num){
return Lam(Lam((function go(n){return n===0?Var(0):App(Var(1),go(n-1))})(num)));
}
|
javascript
|
{
"resource": ""
}
|
q52492
|
toFunction
|
train
|
function toFunction(term){
return eval(transmogrify(
function(varName, body){ return "(function("+varName+"){return "+body+"})"; },
function(fun, arg){ return fun+"("+arg+")"; })
(term));
}
|
javascript
|
{
"resource": ""
}
|
q52493
|
fromBLC
|
train
|
function fromBLC(source){
var index = 0;
return (function go(){
if (source[index] === "0")
return source[index+1] === "0"
? (index+=2, Lam(go()))
: (index+=2, App(go(), go()));
for (var i=0; source[index]!=="0"; ++i)
++index;
return (++index, Var(i-1));
})();
}
|
javascript
|
{
"resource": ""
}
|
q52494
|
fromBLC64
|
train
|
function fromBLC64(digits){
var blc = "";
for (var d=0, l=digits.length; d<l; ++d){
var bits = base64Table[digits[d]];
blc += d === 0 ? bits.slice(bits.indexOf("1")+1) : bits;
};
return fromBLC(blc);
}
|
javascript
|
{
"resource": ""
}
|
q52495
|
toBLC64
|
train
|
function toBLC64(term){
var blc = toBLC(term);
var digits = "";
for (var d=0, l=blc.length; d<=l/6; ++d){
var i = l - d*6 - 6;
var bits = i < 0
? ("000001"+blc.slice(0, i+6)).slice(-6)
: blc.slice(i, i+6);
digits = base64Table[bits] + digits;
};
return digits;
}
|
javascript
|
{
"resource": ""
}
|
q52496
|
createDryReplacer
|
train
|
function createDryReplacer(root, replacer) {
var value_paths = new WeakMap(),
seen_path,
flags = {is_root: true},
chain = [],
path = [],
temp,
last,
len;
return function dryReplacer(holder, key, value) {
// Process the value to a possible given replacer function
if (replacer != null) {
value = replacer.call(holder, key, value);
}
// All falsy values can be returned as-is
if (!value) {
return value;
}
let is_wrap;
// An explicitly false key means this dryReplaced was
// recursively called with a replacement object
if (key === false) {
key = '';
is_wrap = true;
// Wrappers get added to the object chain, but not the path
// We need to be able to identify them later on
holder.__is_wrap = true;
// See if the wrapped value is an object
if (holder[''] != null && typeof holder[''] === 'object') {
holder.__is_object = true;
}
}
switch (typeof value) {
case 'function':
// If no drier is created, return now.
// Else: fall through
if (!driers.Function) {
return;
}
case 'object':
value = replaceObject(dryReplacer, value, chain, flags, is_wrap, holder, path, value_paths, key);
break;
case 'string':
// Make sure regular strings don't start with the path delimiter
if (!flags.is_root && value[0] == '~') {
value = safe_special_char + value.slice(1);
}
break;
case 'number':
// Allow infinite values
if (value && !isFinite(value)) {
if (value > 0) {
value = {dry: '+Infinity'};
} else {
value = {dry: '-Infinity'};
}
}
break;
}
return value;
}
}
|
javascript
|
{
"resource": ""
}
|
q52497
|
recurseGeneralObject
|
train
|
function recurseGeneralObject(dryReplacer, value) {
var new_value = {},
keys = Object.keys(value),
key,
i;
for (i = 0; i < keys.length; i++) {
key = keys[i];
new_value[key] = dryReplacer(value, key, value[key]);
}
return new_value;
}
|
javascript
|
{
"resource": ""
}
|
q52498
|
generateReviver
|
train
|
function generateReviver(reviver, undry_paths) {
return function dryReviver(key, value) {
var val_type = typeof value,
constructor,
temp;
if (val_type === 'string') {
if (value[0] === special_char) {
// This is actually a path that needs to be replaced.
// Put in a String object for now
return new String(value.slice(1));
} else if (value[0] == '\\' && value[1] == 'x' && value[2] == '7' && value[3] == 'e') {
value = special_char + value.slice(4);
}
} else if (value && value.dry != null) {
switch (value.dry) {
case 'date':
if (value.value) {
return new Date(value.value);
}
break;
case 'regexp':
if (value.value) {
return RegExp.apply(undefined, get_regex.exec(value.value).slice(1));
}
break;
case '+Infinity':
return Infinity;
case '-Infinity':
return -Infinity;
case 'toDry':
constructor = findClass(value);
// Undry this element, but don't put it in the parsed object yet
if (constructor && typeof constructor.unDry === 'function') {
value.unDryConstructor = constructor;
} else {
value.undried = value.value;
}
if (value.drypath) {
undry_paths.set(value.drypath.join(special_char), value);
} else {
return value.undried;
}
break;
default:
if (typeof value.value !== 'undefined') {
if (undriers[value.dry]) {
value.unDryFunction = undriers[value.dry].fnc;
if (!value.drypath) {
// No path given? Then do the undrying right now
value.undried = value.unDryFunction(this, key, value.value)
}
} else {
value.undried = value.value;
}
if (value.drypath) {
undry_paths.set(value.drypath.join(special_char), value);
} else {
return value.undried;
}
}
}
}
if (reviver == null) {
return value;
}
return reviver.call(this, key, value);
};
}
|
javascript
|
{
"resource": ""
}
|
q52499
|
registerDrier
|
train
|
function registerDrier(constructor, fnc, options) {
var path;
if (typeof constructor == 'function') {
path = constructor.name;
} else {
path = constructor;
}
driers[path] = {
fnc : fnc,
options : options || {}
};
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.