repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
soajs/soajs.core.drivers | infra/google/kubernetes/index.js | getClusterVersion | function getClusterVersion(request, mCb) {
delete request.project;
v1Container().projects.zones.getServerconfig(request, function (err, response) {
if (err) {
return mCb(err);
}
let version;
if (response && response.validMasterVersions && Array.isArray(response.validMasterVersions)
&& response.validMasterVersions.length > 0) {
response.validMasterVersions.forEach(function (oneVersion) {
if (oneVersion.substring(0, 3) === "1.7") {
version = oneVersion;
options.soajs.log.debug("Initial Cluster version set to :", version);
}
});
} else if (response && response.defaultClusterVersion && !version) {
version = response.defaultClusterVersion;
options.soajs.log.debug("Initial Cluster version set to default version :", version);
} else {
return mCb({"code": 410, "msg": "Invalid or no kubernetes cluster version found!"})
}
return mCb(null, version);
});
} | javascript | function getClusterVersion(request, mCb) {
delete request.project;
v1Container().projects.zones.getServerconfig(request, function (err, response) {
if (err) {
return mCb(err);
}
let version;
if (response && response.validMasterVersions && Array.isArray(response.validMasterVersions)
&& response.validMasterVersions.length > 0) {
response.validMasterVersions.forEach(function (oneVersion) {
if (oneVersion.substring(0, 3) === "1.7") {
version = oneVersion;
options.soajs.log.debug("Initial Cluster version set to :", version);
}
});
} else if (response && response.defaultClusterVersion && !version) {
version = response.defaultClusterVersion;
options.soajs.log.debug("Initial Cluster version set to default version :", version);
} else {
return mCb({"code": 410, "msg": "Invalid or no kubernetes cluster version found!"})
}
return mCb(null, version);
});
} | [
"function",
"getClusterVersion",
"(",
"request",
",",
"mCb",
")",
"{",
"delete",
"request",
".",
"project",
";",
"v1Container",
"(",
")",
".",
"projects",
".",
"zones",
".",
"getServerconfig",
"(",
"request",
",",
"function",
"(",
"err",
",",
"response",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"mCb",
"(",
"err",
")",
";",
"}",
"let",
"version",
";",
"if",
"(",
"response",
"&&",
"response",
".",
"validMasterVersions",
"&&",
"Array",
".",
"isArray",
"(",
"response",
".",
"validMasterVersions",
")",
"&&",
"response",
".",
"validMasterVersions",
".",
"length",
">",
"0",
")",
"{",
"response",
".",
"validMasterVersions",
".",
"forEach",
"(",
"function",
"(",
"oneVersion",
")",
"{",
"if",
"(",
"oneVersion",
".",
"substring",
"(",
"0",
",",
"3",
")",
"===",
"\"1.7\"",
")",
"{",
"version",
"=",
"oneVersion",
";",
"options",
".",
"soajs",
".",
"log",
".",
"debug",
"(",
"\"Initial Cluster version set to :\"",
",",
"version",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"if",
"(",
"response",
"&&",
"response",
".",
"defaultClusterVersion",
"&&",
"!",
"version",
")",
"{",
"version",
"=",
"response",
".",
"defaultClusterVersion",
";",
"options",
".",
"soajs",
".",
"log",
".",
"debug",
"(",
"\"Initial Cluster version set to default version :\"",
",",
"version",
")",
";",
"}",
"else",
"{",
"return",
"mCb",
"(",
"{",
"\"code\"",
":",
"410",
",",
"\"msg\"",
":",
"\"Invalid or no kubernetes cluster version found!\"",
"}",
")",
"}",
"return",
"mCb",
"(",
"null",
",",
"version",
")",
";",
"}",
")",
";",
"}"
] | method used to get cluster version
@returns {*} | [
"method",
"used",
"to",
"get",
"cluster",
"version"
] | 545891509a47e16d9d2f40515e81bb1f4f3d8165 | https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/google/kubernetes/index.js#L292-L316 | train |
soajs/soajs.core.drivers | infra/google/kubernetes/index.js | deleteNetwork | function deleteNetwork() {
setTimeout(function () {
//cluster failed, delete network if it was not provided by the user
let networksOptions = Object.assign({}, options);
networksOptions.params = {name: oneDeployment.options.network};
networks.delete(networksOptions, (error) => {
if (error) {
options.soajs.log.error(error);
} else {
options.soajs.log.debug("VPC Network Deleted Successfully.");
}
});
}, (process.env.SOAJS_CLOOSTRO_TEST) ? 1 : 5 * 60 * 1000);
} | javascript | function deleteNetwork() {
setTimeout(function () {
//cluster failed, delete network if it was not provided by the user
let networksOptions = Object.assign({}, options);
networksOptions.params = {name: oneDeployment.options.network};
networks.delete(networksOptions, (error) => {
if (error) {
options.soajs.log.error(error);
} else {
options.soajs.log.debug("VPC Network Deleted Successfully.");
}
});
}, (process.env.SOAJS_CLOOSTRO_TEST) ? 1 : 5 * 60 * 1000);
} | [
"function",
"deleteNetwork",
"(",
")",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"let",
"networksOptions",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"options",
")",
";",
"networksOptions",
".",
"params",
"=",
"{",
"name",
":",
"oneDeployment",
".",
"options",
".",
"network",
"}",
";",
"networks",
".",
"delete",
"(",
"networksOptions",
",",
"(",
"error",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"options",
".",
"soajs",
".",
"log",
".",
"error",
"(",
"error",
")",
";",
"}",
"else",
"{",
"options",
".",
"soajs",
".",
"log",
".",
"debug",
"(",
"\"VPC Network Deleted Successfully.\"",
")",
";",
"}",
"}",
")",
";",
"}",
",",
"(",
"process",
".",
"env",
".",
"SOAJS_CLOOSTRO_TEST",
")",
"?",
"1",
":",
"5",
"*",
"60",
"*",
"1000",
")",
";",
"}"
] | delete vpc Network after a certain timeout
@returns {*} | [
"delete",
"vpc",
"Network",
"after",
"a",
"certain",
"timeout"
] | 545891509a47e16d9d2f40515e81bb1f4f3d8165 | https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/google/kubernetes/index.js#L322-L335 | train |
soajs/soajs.core.drivers | infra/google/kubernetes/index.js | function (options, region, verbose, mCb) {
infraExtras.getRegion(options, region, verbose, (err, resR) => {
if (err) {
infraExtras.getZone(options, region, verbose, (err, resZ) => {
if (err) {
return mCb(err);
} else {
return mCb(null, resZ);
}
});
} else {
return mCb(null, resR);
}
});
} | javascript | function (options, region, verbose, mCb) {
infraExtras.getRegion(options, region, verbose, (err, resR) => {
if (err) {
infraExtras.getZone(options, region, verbose, (err, resZ) => {
if (err) {
return mCb(err);
} else {
return mCb(null, resZ);
}
});
} else {
return mCb(null, resR);
}
});
} | [
"function",
"(",
"options",
",",
"region",
",",
"verbose",
",",
"mCb",
")",
"{",
"infraExtras",
".",
"getRegion",
"(",
"options",
",",
"region",
",",
"verbose",
",",
"(",
"err",
",",
"resR",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"infraExtras",
".",
"getZone",
"(",
"options",
",",
"region",
",",
"verbose",
",",
"(",
"err",
",",
"resZ",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"mCb",
"(",
"err",
")",
";",
"}",
"else",
"{",
"return",
"mCb",
"(",
"null",
",",
"resZ",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"return",
"mCb",
"(",
"null",
",",
"resR",
")",
";",
"}",
"}",
")",
";",
"}"
] | This method checks tif the cluster is zonal or regional
@param options
@param region
@param verbose
@param mCb
@returns {*} | [
"This",
"method",
"checks",
"tif",
"the",
"cluster",
"is",
"zonal",
"or",
"regional"
] | 545891509a47e16d9d2f40515e81bb1f4f3d8165 | https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/google/kubernetes/index.js#L466-L480 | train |
|
soajs/soajs.core.drivers | infra/google/kubernetes/index.js | function (options, cb) {
//call google api and get the machines
let cluster = options.infra.stack;
//Ref: https://cloud.google.com/compute/docs/reference/latest/instances/list
let request = getConnector(options.infra.api);
request.clusterId = cluster.id;
request.filter = "name eq gke-" + cluster.id.substring(0, 19) + "-" + cluster.options.nodePoolId + "-.*";
let response = {
"env": options.soajs.registry.code,
"stackId": cluster.id,
"stackName": cluster.id,
"templateProperties": {
"region": cluster.options.zone
//"keyPair": "keyPair" //todo: what is this for ????
},
"machines": [],
};
driver.checkZoneRegion(options, cluster.options.zone, true, (err, zones) => {
if (err) {
return cb(err)
}
//loop over all the zone ang get the ip of each location found in the zone
//if zonal we only have to loop once
async.each(zones, function (oneZone, callback) {
request.zone = oneZone;
v1Compute().instances.list(request, (error, instances) => {
if (error) {
return callback(error);
}
if (instances && instances.items) {
//extract name and ip from response
instances.items.forEach((oneInstance) => {
let machineIP;
oneInstance.networkInterfaces.forEach((oneNetInterface) => {
if (oneNetInterface.accessConfigs) {
oneNetInterface.accessConfigs.forEach((oneAC) => {
if (oneAC.name === 'external-nat') {
machineIP = oneAC.natIP;
}
});
}
});
if (machineIP) {
response.machines.push({
"name": oneInstance.name,
"ip": machineIP,
"zone": oneZone
});
}
});
}
callback();
});
}, function (err) {
if (err) {
return cb(err)
} else {
return cb(null, response);
}
});
});
} | javascript | function (options, cb) {
//call google api and get the machines
let cluster = options.infra.stack;
//Ref: https://cloud.google.com/compute/docs/reference/latest/instances/list
let request = getConnector(options.infra.api);
request.clusterId = cluster.id;
request.filter = "name eq gke-" + cluster.id.substring(0, 19) + "-" + cluster.options.nodePoolId + "-.*";
let response = {
"env": options.soajs.registry.code,
"stackId": cluster.id,
"stackName": cluster.id,
"templateProperties": {
"region": cluster.options.zone
//"keyPair": "keyPair" //todo: what is this for ????
},
"machines": [],
};
driver.checkZoneRegion(options, cluster.options.zone, true, (err, zones) => {
if (err) {
return cb(err)
}
//loop over all the zone ang get the ip of each location found in the zone
//if zonal we only have to loop once
async.each(zones, function (oneZone, callback) {
request.zone = oneZone;
v1Compute().instances.list(request, (error, instances) => {
if (error) {
return callback(error);
}
if (instances && instances.items) {
//extract name and ip from response
instances.items.forEach((oneInstance) => {
let machineIP;
oneInstance.networkInterfaces.forEach((oneNetInterface) => {
if (oneNetInterface.accessConfigs) {
oneNetInterface.accessConfigs.forEach((oneAC) => {
if (oneAC.name === 'external-nat') {
machineIP = oneAC.natIP;
}
});
}
});
if (machineIP) {
response.machines.push({
"name": oneInstance.name,
"ip": machineIP,
"zone": oneZone
});
}
});
}
callback();
});
}, function (err) {
if (err) {
return cb(err)
} else {
return cb(null, response);
}
});
});
} | [
"function",
"(",
"options",
",",
"cb",
")",
"{",
"let",
"cluster",
"=",
"options",
".",
"infra",
".",
"stack",
";",
"let",
"request",
"=",
"getConnector",
"(",
"options",
".",
"infra",
".",
"api",
")",
";",
"request",
".",
"clusterId",
"=",
"cluster",
".",
"id",
";",
"request",
".",
"filter",
"=",
"\"name eq gke-\"",
"+",
"cluster",
".",
"id",
".",
"substring",
"(",
"0",
",",
"19",
")",
"+",
"\"-\"",
"+",
"cluster",
".",
"options",
".",
"nodePoolId",
"+",
"\"-.*\"",
";",
"let",
"response",
"=",
"{",
"\"env\"",
":",
"options",
".",
"soajs",
".",
"registry",
".",
"code",
",",
"\"stackId\"",
":",
"cluster",
".",
"id",
",",
"\"stackName\"",
":",
"cluster",
".",
"id",
",",
"\"templateProperties\"",
":",
"{",
"\"region\"",
":",
"cluster",
".",
"options",
".",
"zone",
"}",
",",
"\"machines\"",
":",
"[",
"]",
",",
"}",
";",
"driver",
".",
"checkZoneRegion",
"(",
"options",
",",
"cluster",
".",
"options",
".",
"zone",
",",
"true",
",",
"(",
"err",
",",
"zones",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
"}",
"async",
".",
"each",
"(",
"zones",
",",
"function",
"(",
"oneZone",
",",
"callback",
")",
"{",
"request",
".",
"zone",
"=",
"oneZone",
";",
"v1Compute",
"(",
")",
".",
"instances",
".",
"list",
"(",
"request",
",",
"(",
"error",
",",
"instances",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"callback",
"(",
"error",
")",
";",
"}",
"if",
"(",
"instances",
"&&",
"instances",
".",
"items",
")",
"{",
"instances",
".",
"items",
".",
"forEach",
"(",
"(",
"oneInstance",
")",
"=>",
"{",
"let",
"machineIP",
";",
"oneInstance",
".",
"networkInterfaces",
".",
"forEach",
"(",
"(",
"oneNetInterface",
")",
"=>",
"{",
"if",
"(",
"oneNetInterface",
".",
"accessConfigs",
")",
"{",
"oneNetInterface",
".",
"accessConfigs",
".",
"forEach",
"(",
"(",
"oneAC",
")",
"=>",
"{",
"if",
"(",
"oneAC",
".",
"name",
"===",
"'external-nat'",
")",
"{",
"machineIP",
"=",
"oneAC",
".",
"natIP",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"machineIP",
")",
"{",
"response",
".",
"machines",
".",
"push",
"(",
"{",
"\"name\"",
":",
"oneInstance",
".",
"name",
",",
"\"ip\"",
":",
"machineIP",
",",
"\"zone\"",
":",
"oneZone",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"callback",
"(",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
"}",
"else",
"{",
"return",
"cb",
"(",
"null",
",",
"response",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] | This method returns the project cluster id and zone that was used to create a deployment at the google.
@param options
@param cb | [
"This",
"method",
"returns",
"the",
"project",
"cluster",
"id",
"and",
"zone",
"that",
"was",
"used",
"to",
"create",
"a",
"deployment",
"at",
"the",
"google",
"."
] | 545891509a47e16d9d2f40515e81bb1f4f3d8165 | https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/google/kubernetes/index.js#L1020-L1084 | train |
|
soajs/soajs.core.drivers | infra/aws/index.js | function (options, cb) {
options.soajs.log.debug("Checking if Cluster is healthy ...");
let stack = options.infra.stack;
let containerOptions = Object.assign({}, options);
containerOptions.technology = (containerOptions && containerOptions.params && containerOptions.params.technology) ? containerOptions.params.technology : defaultDriver;
//get the environment record
if (options.soajs.registry.deployer.container[stack.technology].remote.nodes && options.soajs.registry.deployer.container[stack.technology].remote.nodes !== '') {
let machineIp = options.soajs.registry.deployer.container[stack.technology].remote.nodes;
return cb(null, machineIp);
}
else {
let out = false;
async.series({
"pre": (mCb) => {
runCorrespondingDriver('getDeployClusterStatusPre', containerOptions, mCb);
},
"exec": (mCb) => {
ClusterDriver.getDeployClusterStatus(options, (error, response) => {
if (response) {
out = response;
containerOptions.out = out;
}
return mCb(error, response);
});
},
"post": (mCb) => {
if (out) {
runCorrespondingDriver('getDeployClusterStatusPost', containerOptions, mCb);
}
else {
return mCb();
}
}
}, (error) => {
return cb(error, out);
});
}
} | javascript | function (options, cb) {
options.soajs.log.debug("Checking if Cluster is healthy ...");
let stack = options.infra.stack;
let containerOptions = Object.assign({}, options);
containerOptions.technology = (containerOptions && containerOptions.params && containerOptions.params.technology) ? containerOptions.params.technology : defaultDriver;
//get the environment record
if (options.soajs.registry.deployer.container[stack.technology].remote.nodes && options.soajs.registry.deployer.container[stack.technology].remote.nodes !== '') {
let machineIp = options.soajs.registry.deployer.container[stack.technology].remote.nodes;
return cb(null, machineIp);
}
else {
let out = false;
async.series({
"pre": (mCb) => {
runCorrespondingDriver('getDeployClusterStatusPre', containerOptions, mCb);
},
"exec": (mCb) => {
ClusterDriver.getDeployClusterStatus(options, (error, response) => {
if (response) {
out = response;
containerOptions.out = out;
}
return mCb(error, response);
});
},
"post": (mCb) => {
if (out) {
runCorrespondingDriver('getDeployClusterStatusPost', containerOptions, mCb);
}
else {
return mCb();
}
}
}, (error) => {
return cb(error, out);
});
}
} | [
"function",
"(",
"options",
",",
"cb",
")",
"{",
"options",
".",
"soajs",
".",
"log",
".",
"debug",
"(",
"\"Checking if Cluster is healthy ...\"",
")",
";",
"let",
"stack",
"=",
"options",
".",
"infra",
".",
"stack",
";",
"let",
"containerOptions",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"options",
")",
";",
"containerOptions",
".",
"technology",
"=",
"(",
"containerOptions",
"&&",
"containerOptions",
".",
"params",
"&&",
"containerOptions",
".",
"params",
".",
"technology",
")",
"?",
"containerOptions",
".",
"params",
".",
"technology",
":",
"defaultDriver",
";",
"if",
"(",
"options",
".",
"soajs",
".",
"registry",
".",
"deployer",
".",
"container",
"[",
"stack",
".",
"technology",
"]",
".",
"remote",
".",
"nodes",
"&&",
"options",
".",
"soajs",
".",
"registry",
".",
"deployer",
".",
"container",
"[",
"stack",
".",
"technology",
"]",
".",
"remote",
".",
"nodes",
"!==",
"''",
")",
"{",
"let",
"machineIp",
"=",
"options",
".",
"soajs",
".",
"registry",
".",
"deployer",
".",
"container",
"[",
"stack",
".",
"technology",
"]",
".",
"remote",
".",
"nodes",
";",
"return",
"cb",
"(",
"null",
",",
"machineIp",
")",
";",
"}",
"else",
"{",
"let",
"out",
"=",
"false",
";",
"async",
".",
"series",
"(",
"{",
"\"pre\"",
":",
"(",
"mCb",
")",
"=>",
"{",
"runCorrespondingDriver",
"(",
"'getDeployClusterStatusPre'",
",",
"containerOptions",
",",
"mCb",
")",
";",
"}",
",",
"\"exec\"",
":",
"(",
"mCb",
")",
"=>",
"{",
"ClusterDriver",
".",
"getDeployClusterStatus",
"(",
"options",
",",
"(",
"error",
",",
"response",
")",
"=>",
"{",
"if",
"(",
"response",
")",
"{",
"out",
"=",
"response",
";",
"containerOptions",
".",
"out",
"=",
"out",
";",
"}",
"return",
"mCb",
"(",
"error",
",",
"response",
")",
";",
"}",
")",
";",
"}",
",",
"\"post\"",
":",
"(",
"mCb",
")",
"=>",
"{",
"if",
"(",
"out",
")",
"{",
"runCorrespondingDriver",
"(",
"'getDeployClusterStatusPost'",
",",
"containerOptions",
",",
"mCb",
")",
";",
"}",
"else",
"{",
"return",
"mCb",
"(",
")",
";",
"}",
"}",
"}",
",",
"(",
"error",
")",
"=>",
"{",
"return",
"cb",
"(",
"error",
",",
"out",
")",
";",
"}",
")",
";",
"}",
"}"
] | This method takes the id of the stack as an input and check if the stack has been deployed
it returns the ip that can be used to access the machine
@param options
@param cb
@returns {*} | [
"This",
"method",
"takes",
"the",
"id",
"of",
"the",
"stack",
"as",
"an",
"input",
"and",
"check",
"if",
"the",
"stack",
"has",
"been",
"deployed",
"it",
"returns",
"the",
"ip",
"that",
"can",
"be",
"used",
"to",
"access",
"the",
"machine"
] | 545891509a47e16d9d2f40515e81bb1f4f3d8165 | https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/aws/index.js#L74-L113 | train |
|
digitalbazaar/http-signature-middleware | lib/Middleware.js | _timestampBeforeNow | function _timestampBeforeNow(timestamp) {
if(!(typeof timestamp === 'string' && dateRegEx.test(timestamp))) {
throw new TypeError('`revoked` timestamp must be a string.');
}
const now = new Date();
const tsDate = new Date(timestamp);
return tsDate < now;
} | javascript | function _timestampBeforeNow(timestamp) {
if(!(typeof timestamp === 'string' && dateRegEx.test(timestamp))) {
throw new TypeError('`revoked` timestamp must be a string.');
}
const now = new Date();
const tsDate = new Date(timestamp);
return tsDate < now;
} | [
"function",
"_timestampBeforeNow",
"(",
"timestamp",
")",
"{",
"if",
"(",
"!",
"(",
"typeof",
"timestamp",
"===",
"'string'",
"&&",
"dateRegEx",
".",
"test",
"(",
"timestamp",
")",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'`revoked` timestamp must be a string.'",
")",
";",
"}",
"const",
"now",
"=",
"new",
"Date",
"(",
")",
";",
"const",
"tsDate",
"=",
"new",
"Date",
"(",
"timestamp",
")",
";",
"return",
"tsDate",
"<",
"now",
";",
"}"
] | returns true if the given timestamp is before the current time | [
"returns",
"true",
"if",
"the",
"given",
"timestamp",
"is",
"before",
"the",
"current",
"time"
] | 993b7d4f19d73b4fe79a0b4e4f5dc850316195de | https://github.com/digitalbazaar/http-signature-middleware/blob/993b7d4f19d73b4fe79a0b4e4f5dc850316195de/lib/Middleware.js#L155-L162 | train |
Incroud/cassanova | index.js | Cassanova | function Cassanova(){
this.tables = {};
this.models = {};
this.schemas = {};
this.client = null;
this.options = null;
EventEmitter.call(this);
} | javascript | function Cassanova(){
this.tables = {};
this.models = {};
this.schemas = {};
this.client = null;
this.options = null;
EventEmitter.call(this);
} | [
"function",
"Cassanova",
"(",
")",
"{",
"this",
".",
"tables",
"=",
"{",
"}",
";",
"this",
".",
"models",
"=",
"{",
"}",
";",
"this",
".",
"schemas",
"=",
"{",
"}",
";",
"this",
".",
"client",
"=",
"null",
";",
"this",
".",
"options",
"=",
"null",
";",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"}"
] | Cassanova. An object modeler for Cassandra CQL built upon the node-cassandra-cql driver. | [
"Cassanova",
".",
"An",
"object",
"modeler",
"for",
"Cassandra",
"CQL",
"built",
"upon",
"the",
"node",
"-",
"cassandra",
"-",
"cql",
"driver",
"."
] | 49c5ce2e1bc6b19d25e8223e88df45c113c36b68 | https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/index.js#L15-L23 | train |
Incroud/cassanova | CQL.js | function(callback){
var filePath;
output("Processing arguments...");
if(program.cql){
batchQueries.push(program.cql.toString().trim());
}
if((!program.keyspace || program.keyspace.length === 0)){
output("A keyspace has not been defined. CQL will fail if the keyspace is not defined in the statement.");
}
if((!program.files || program.files.length === 0) && (!program.cql || program.cql.length === 0)){
return callback("Need a file to load or cql to run. Use -f=filename or --files=filename,filename or -cql='someCQLStatement;' or --cql='someCQLStatement;'. Run node CQL --help for mode information.", false);
}else if(process.env.NODE_ENV === 'production' && !program.production){
return callback("CQL cannot be run while the NODE_ENV is set to production.", false);
}else if(program.production && process.env.NODE_ENV === 'production'){
output("***** Preparing to run scripts in production mode *****");
output("***** You have " + productionRunDelay + " seconds to think about what your doing before the scripts will execute. *****");
output("***** CTRL+C to Exit *****");
barTimer = setInterval(function () {
bar.tick();
if (bar.complete) {
output("***** OK! Here we go... *****");
output("***** Running scripts in production mode *****");
clearInterval(barTimer);
return callback(null, true);
}
}, 1000);
return;
}else if(program.production && process.env.NODE_ENV !== 'production'){
return callback("NODE_ENV is set not set to production, but you attempted to run in production mode.", false);
}
callback(null, true);
} | javascript | function(callback){
var filePath;
output("Processing arguments...");
if(program.cql){
batchQueries.push(program.cql.toString().trim());
}
if((!program.keyspace || program.keyspace.length === 0)){
output("A keyspace has not been defined. CQL will fail if the keyspace is not defined in the statement.");
}
if((!program.files || program.files.length === 0) && (!program.cql || program.cql.length === 0)){
return callback("Need a file to load or cql to run. Use -f=filename or --files=filename,filename or -cql='someCQLStatement;' or --cql='someCQLStatement;'. Run node CQL --help for mode information.", false);
}else if(process.env.NODE_ENV === 'production' && !program.production){
return callback("CQL cannot be run while the NODE_ENV is set to production.", false);
}else if(program.production && process.env.NODE_ENV === 'production'){
output("***** Preparing to run scripts in production mode *****");
output("***** You have " + productionRunDelay + " seconds to think about what your doing before the scripts will execute. *****");
output("***** CTRL+C to Exit *****");
barTimer = setInterval(function () {
bar.tick();
if (bar.complete) {
output("***** OK! Here we go... *****");
output("***** Running scripts in production mode *****");
clearInterval(barTimer);
return callback(null, true);
}
}, 1000);
return;
}else if(program.production && process.env.NODE_ENV !== 'production'){
return callback("NODE_ENV is set not set to production, but you attempted to run in production mode.", false);
}
callback(null, true);
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"filePath",
";",
"output",
"(",
"\"Processing arguments...\"",
")",
";",
"if",
"(",
"program",
".",
"cql",
")",
"{",
"batchQueries",
".",
"push",
"(",
"program",
".",
"cql",
".",
"toString",
"(",
")",
".",
"trim",
"(",
")",
")",
";",
"}",
"if",
"(",
"(",
"!",
"program",
".",
"keyspace",
"||",
"program",
".",
"keyspace",
".",
"length",
"===",
"0",
")",
")",
"{",
"output",
"(",
"\"A keyspace has not been defined. CQL will fail if the keyspace is not defined in the statement.\"",
")",
";",
"}",
"if",
"(",
"(",
"!",
"program",
".",
"files",
"||",
"program",
".",
"files",
".",
"length",
"===",
"0",
")",
"&&",
"(",
"!",
"program",
".",
"cql",
"||",
"program",
".",
"cql",
".",
"length",
"===",
"0",
")",
")",
"{",
"return",
"callback",
"(",
"\"Need a file to load or cql to run. Use -f=filename or --files=filename,filename or -cql='someCQLStatement;' or --cql='someCQLStatement;'. Run node CQL --help for mode information.\"",
",",
"false",
")",
";",
"}",
"else",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"===",
"'production'",
"&&",
"!",
"program",
".",
"production",
")",
"{",
"return",
"callback",
"(",
"\"CQL cannot be run while the NODE_ENV is set to production.\"",
",",
"false",
")",
";",
"}",
"else",
"if",
"(",
"program",
".",
"production",
"&&",
"process",
".",
"env",
".",
"NODE_ENV",
"===",
"'production'",
")",
"{",
"output",
"(",
"\"***** Preparing to run scripts in production mode *****\"",
")",
";",
"output",
"(",
"\"***** You have \"",
"+",
"productionRunDelay",
"+",
"\" seconds to think about what your doing before the scripts will execute. *****\"",
")",
";",
"output",
"(",
"\"***** CTRL+C to Exit *****\"",
")",
";",
"barTimer",
"=",
"setInterval",
"(",
"function",
"(",
")",
"{",
"bar",
".",
"tick",
"(",
")",
";",
"if",
"(",
"bar",
".",
"complete",
")",
"{",
"output",
"(",
"\"***** OK! Here we go... *****\"",
")",
";",
"output",
"(",
"\"***** Running scripts in production mode *****\"",
")",
";",
"clearInterval",
"(",
"barTimer",
")",
";",
"return",
"callback",
"(",
"null",
",",
"true",
")",
";",
"}",
"}",
",",
"1000",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"program",
".",
"production",
"&&",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
")",
"{",
"return",
"callback",
"(",
"\"NODE_ENV is set not set to production, but you attempted to run in production mode.\"",
",",
"false",
")",
";",
"}",
"callback",
"(",
"null",
",",
"true",
")",
";",
"}"
] | Verifies the arguments are valid and ant require arguments are handled.
@param {Function} callback Callback to async with error or success | [
"Verifies",
"the",
"arguments",
"are",
"valid",
"and",
"ant",
"require",
"arguments",
"are",
"handled",
"."
] | 49c5ce2e1bc6b19d25e8223e88df45c113c36b68 | https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/CQL.js#L61-L100 | train |
|
Incroud/cassanova | CQL.js | function(callback){
var opts = {};
output("Connecting to database...");
//We need to be able to do anything with any keyspace. We just need a db connection. Just send
//in the hosts, username and password, stripping the keyspace.
opts.username = process.env.CASS_USER || config.db.username;
opts.password = process.env.CASS_PASS || config.db.password;
opts.hosts = config.db.hosts;
opts.port = config.db.port;
Cassanova.connect(opts, function(err, result){
if(err){
err.hosts = opts.hosts;
}
callback(err, result);
});
} | javascript | function(callback){
var opts = {};
output("Connecting to database...");
//We need to be able to do anything with any keyspace. We just need a db connection. Just send
//in the hosts, username and password, stripping the keyspace.
opts.username = process.env.CASS_USER || config.db.username;
opts.password = process.env.CASS_PASS || config.db.password;
opts.hosts = config.db.hosts;
opts.port = config.db.port;
Cassanova.connect(opts, function(err, result){
if(err){
err.hosts = opts.hosts;
}
callback(err, result);
});
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"opts",
"=",
"{",
"}",
";",
"output",
"(",
"\"Connecting to database...\"",
")",
";",
"opts",
".",
"username",
"=",
"process",
".",
"env",
".",
"CASS_USER",
"||",
"config",
".",
"db",
".",
"username",
";",
"opts",
".",
"password",
"=",
"process",
".",
"env",
".",
"CASS_PASS",
"||",
"config",
".",
"db",
".",
"password",
";",
"opts",
".",
"hosts",
"=",
"config",
".",
"db",
".",
"hosts",
";",
"opts",
".",
"port",
"=",
"config",
".",
"db",
".",
"port",
";",
"Cassanova",
".",
"connect",
"(",
"opts",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"{",
"err",
".",
"hosts",
"=",
"opts",
".",
"hosts",
";",
"}",
"callback",
"(",
"err",
",",
"result",
")",
";",
"}",
")",
";",
"}"
] | Starts Cassanova.
@param {Function} callback Callback to async with error or success | [
"Starts",
"Cassanova",
"."
] | 49c5ce2e1bc6b19d25e8223e88df45c113c36b68 | https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/CQL.js#L137-L153 | train |
|
Incroud/cassanova | CQL.js | function(callback){
var result,
i;
if(!files || files.length === 0){
return callback(null, true);
}
output("Processing queries...");
for(i=0; i<files.length; i++){
while((result = cqlRegex.exec(files[i])) !== null) {
batchQueries.push(result[1].replace(/\s+/g, ' ').trim());
}
}
callback(null, true);
} | javascript | function(callback){
var result,
i;
if(!files || files.length === 0){
return callback(null, true);
}
output("Processing queries...");
for(i=0; i<files.length; i++){
while((result = cqlRegex.exec(files[i])) !== null) {
batchQueries.push(result[1].replace(/\s+/g, ' ').trim());
}
}
callback(null, true);
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"result",
",",
"i",
";",
"if",
"(",
"!",
"files",
"||",
"files",
".",
"length",
"===",
"0",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"true",
")",
";",
"}",
"output",
"(",
"\"Processing queries...\"",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"files",
".",
"length",
";",
"i",
"++",
")",
"{",
"while",
"(",
"(",
"result",
"=",
"cqlRegex",
".",
"exec",
"(",
"files",
"[",
"i",
"]",
")",
")",
"!==",
"null",
")",
"{",
"batchQueries",
".",
"push",
"(",
"result",
"[",
"1",
"]",
".",
"replace",
"(",
"/",
"\\s+",
"/",
"g",
",",
"' '",
")",
".",
"trim",
"(",
")",
")",
";",
"}",
"}",
"callback",
"(",
"null",
",",
"true",
")",
";",
"}"
] | Processes the queries from the files loaded and builds the batch of individual statements to run.
@param {Function} callback Callback to async with error or success | [
"Processes",
"the",
"queries",
"from",
"the",
"files",
"loaded",
"and",
"builds",
"the",
"batch",
"of",
"individual",
"statements",
"to",
"run",
"."
] | 49c5ce2e1bc6b19d25e8223e88df45c113c36b68 | https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/CQL.js#L159-L176 | train |
|
Incroud/cassanova | CQL.js | function(callback){
output("Initializing queries...");
if(program.keyspace){
batchQueries.unshift("USE " + program.keyspace + ";");
}
if(batchQueries && batchQueries.length > 0){
output("Running queries...");
executeQuery(batchQueries.shift(), callback);
}else{
callback("No queries to run.", null);
}
} | javascript | function(callback){
output("Initializing queries...");
if(program.keyspace){
batchQueries.unshift("USE " + program.keyspace + ";");
}
if(batchQueries && batchQueries.length > 0){
output("Running queries...");
executeQuery(batchQueries.shift(), callback);
}else{
callback("No queries to run.", null);
}
} | [
"function",
"(",
"callback",
")",
"{",
"output",
"(",
"\"Initializing queries...\"",
")",
";",
"if",
"(",
"program",
".",
"keyspace",
")",
"{",
"batchQueries",
".",
"unshift",
"(",
"\"USE \"",
"+",
"program",
".",
"keyspace",
"+",
"\";\"",
")",
";",
"}",
"if",
"(",
"batchQueries",
"&&",
"batchQueries",
".",
"length",
">",
"0",
")",
"{",
"output",
"(",
"\"Running queries...\"",
")",
";",
"executeQuery",
"(",
"batchQueries",
".",
"shift",
"(",
")",
",",
"callback",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"\"No queries to run.\"",
",",
"null",
")",
";",
"}",
"}"
] | Initializes the query batch to execute.
@param {Function} callback Callback to async with error or success | [
"Initializes",
"the",
"query",
"batch",
"to",
"execute",
"."
] | 49c5ce2e1bc6b19d25e8223e88df45c113c36b68 | https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/CQL.js#L182-L196 | train |
|
Incroud/cassanova | CQL.js | function(eQuery, callback){
output("Executing:\t\t" + eQuery);
Cassanova.execute(eQuery, function(err) {
if (err){
return callback(err, null);
} else {
if(batchQueries.length > 0){
executeQuery(batchQueries.shift(), callback);
}else{
callback(null, true);
process.nextTick(function(){
process.exit(1);
});
}
}
});
} | javascript | function(eQuery, callback){
output("Executing:\t\t" + eQuery);
Cassanova.execute(eQuery, function(err) {
if (err){
return callback(err, null);
} else {
if(batchQueries.length > 0){
executeQuery(batchQueries.shift(), callback);
}else{
callback(null, true);
process.nextTick(function(){
process.exit(1);
});
}
}
});
} | [
"function",
"(",
"eQuery",
",",
"callback",
")",
"{",
"output",
"(",
"\"Executing:\\t\\t\"",
"+",
"\\t",
")",
";",
"\\t",
"}"
] | A recursive method, that executes each query.
@param {String} eQuery The cql string to be executed.
@param {Function} callback Callback to async with error or success | [
"A",
"recursive",
"method",
"that",
"executes",
"each",
"query",
"."
] | 49c5ce2e1bc6b19d25e8223e88df45c113c36b68 | https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/CQL.js#L203-L222 | train |
|
pex-gl/pex-sys | Event.js | Event | function Event(type, data){
this._sender = null;
this._type = type;
this._data = data;
for(var prop in data) {
this[prop] = data[prop];
}
this._stopPropagation = false;
} | javascript | function Event(type, data){
this._sender = null;
this._type = type;
this._data = data;
for(var prop in data) {
this[prop] = data[prop];
}
this._stopPropagation = false;
} | [
"function",
"Event",
"(",
"type",
",",
"data",
")",
"{",
"this",
".",
"_sender",
"=",
"null",
";",
"this",
".",
"_type",
"=",
"type",
";",
"this",
".",
"_data",
"=",
"data",
";",
"for",
"(",
"var",
"prop",
"in",
"data",
")",
"{",
"this",
"[",
"prop",
"]",
"=",
"data",
"[",
"prop",
"]",
";",
"}",
"this",
".",
"_stopPropagation",
"=",
"false",
";",
"}"
] | Base Event class.
@param {String} type - The type
@param {Object} [data] - The data
@constructor
@class | [
"Base",
"Event",
"class",
"."
] | 1a2f4f01b6ce5966aee42716355e2888159501dd | https://github.com/pex-gl/pex-sys/blob/1a2f4f01b6ce5966aee42716355e2888159501dd/Event.js#L8-L18 | train |
soajs/soajs.core.drivers | Gruntfile.js | function () {
var cwd = process.cwd();
var rootPath = cwd;
var newRootPath = null;
while (!fs.existsSync(path.join(process.cwd(), "node_modules/grunt"))) {
process.chdir("..");
newRootPath = process.cwd();
if (newRootPath === rootPath) {
return;
}
rootPath = newRootPath;
}
process.chdir(cwd);
return rootPath;
} | javascript | function () {
var cwd = process.cwd();
var rootPath = cwd;
var newRootPath = null;
while (!fs.existsSync(path.join(process.cwd(), "node_modules/grunt"))) {
process.chdir("..");
newRootPath = process.cwd();
if (newRootPath === rootPath) {
return;
}
rootPath = newRootPath;
}
process.chdir(cwd);
return rootPath;
} | [
"function",
"(",
")",
"{",
"var",
"cwd",
"=",
"process",
".",
"cwd",
"(",
")",
";",
"var",
"rootPath",
"=",
"cwd",
";",
"var",
"newRootPath",
"=",
"null",
";",
"while",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"\"node_modules/grunt\"",
")",
")",
")",
"{",
"process",
".",
"chdir",
"(",
"\"..\"",
")",
";",
"newRootPath",
"=",
"process",
".",
"cwd",
"(",
")",
";",
"if",
"(",
"newRootPath",
"===",
"rootPath",
")",
"{",
"return",
";",
"}",
"rootPath",
"=",
"newRootPath",
";",
"}",
"process",
".",
"chdir",
"(",
"cwd",
")",
";",
"return",
"rootPath",
";",
"}"
] | Function that find the root path where grunt plugins are installed.
@method findRoot
@return String rootPath | [
"Function",
"that",
"find",
"the",
"root",
"path",
"where",
"grunt",
"plugins",
"are",
"installed",
"."
] | 545891509a47e16d9d2f40515e81bb1f4f3d8165 | https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/Gruntfile.js#L14-L28 | train |
|
soajs/soajs.core.drivers | Gruntfile.js | function (grunt, rootPath, tasks) {
tasks.forEach(function (name) {
if (name === 'grunt-cli') return;
var cwd = process.cwd();
process.chdir(rootPath); // load files from proper root, I don't want to install everything locally per module!
grunt.loadNpmTasks(name);
process.chdir(cwd);
});
} | javascript | function (grunt, rootPath, tasks) {
tasks.forEach(function (name) {
if (name === 'grunt-cli') return;
var cwd = process.cwd();
process.chdir(rootPath); // load files from proper root, I don't want to install everything locally per module!
grunt.loadNpmTasks(name);
process.chdir(cwd);
});
} | [
"function",
"(",
"grunt",
",",
"rootPath",
",",
"tasks",
")",
"{",
"tasks",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"if",
"(",
"name",
"===",
"'grunt-cli'",
")",
"return",
";",
"var",
"cwd",
"=",
"process",
".",
"cwd",
"(",
")",
";",
"process",
".",
"chdir",
"(",
"rootPath",
")",
";",
"grunt",
".",
"loadNpmTasks",
"(",
"name",
")",
";",
"process",
".",
"chdir",
"(",
"cwd",
")",
";",
"}",
")",
";",
"}"
] | Function load the npm tasks from the root path
@method loadTasks
@param grunt {Object} The grunt instance
@param tasks {Array} Array of tasks as string | [
"Function",
"load",
"the",
"npm",
"tasks",
"from",
"the",
"root",
"path"
] | 545891509a47e16d9d2f40515e81bb1f4f3d8165 | https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/Gruntfile.js#L36-L44 | train |
|
SonoIo/node-eve | lib/build.js | function (next) {
minify(
outputCommonsJsFile,
_.extend({optimize: true},uglifyOptions),
function(err){
if ( err ){
return next(err);
}
return next();
}
);
} | javascript | function (next) {
minify(
outputCommonsJsFile,
_.extend({optimize: true},uglifyOptions),
function(err){
if ( err ){
return next(err);
}
return next();
}
);
} | [
"function",
"(",
"next",
")",
"{",
"minify",
"(",
"outputCommonsJsFile",
",",
"_",
".",
"extend",
"(",
"{",
"optimize",
":",
"true",
"}",
",",
"uglifyOptions",
")",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
";",
"}",
"return",
"next",
"(",
")",
";",
"}",
")",
";",
"}"
] | Minify commons components | [
"Minify",
"commons",
"components"
] | 6b7cefecdcf425f30e888ede9e71908850b5447d | https://github.com/SonoIo/node-eve/blob/6b7cefecdcf425f30e888ede9e71908850b5447d/lib/build.js#L347-L360 | train |
|
SonoIo/node-eve | lib/build.js | function (next) {
minify(
outputJsFile,
_.extend({optimize: true},uglifyOptions),
function(err){
if ( err ){
return next(err);
}
if ( isForPublish ){
publisher(
outputJsFile,
function (err) {
return next(err);
},
options.forceminified
);
}else {
return next();
}
}
);
} | javascript | function (next) {
minify(
outputJsFile,
_.extend({optimize: true},uglifyOptions),
function(err){
if ( err ){
return next(err);
}
if ( isForPublish ){
publisher(
outputJsFile,
function (err) {
return next(err);
},
options.forceminified
);
}else {
return next();
}
}
);
} | [
"function",
"(",
"next",
")",
"{",
"minify",
"(",
"outputJsFile",
",",
"_",
".",
"extend",
"(",
"{",
"optimize",
":",
"true",
"}",
",",
"uglifyOptions",
")",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
";",
"}",
"if",
"(",
"isForPublish",
")",
"{",
"publisher",
"(",
"outputJsFile",
",",
"function",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
";",
"}",
",",
"options",
".",
"forceminified",
")",
";",
"}",
"else",
"{",
"return",
"next",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Minify bundle app | [
"Minify",
"bundle",
"app"
] | 6b7cefecdcf425f30e888ede9e71908850b5447d | https://github.com/SonoIo/node-eve/blob/6b7cefecdcf425f30e888ede9e71908850b5447d/lib/build.js#L362-L387 | train |
|
SonoIo/node-eve | lib/build.js | function (next) {
for (var i = 0; i < mapFiles.length; i++) {
fs.unlinkSync(mapFiles[i]);
// console.log( path.resolve(mapFiles[i]) );
}
return next();
} | javascript | function (next) {
for (var i = 0; i < mapFiles.length; i++) {
fs.unlinkSync(mapFiles[i]);
// console.log( path.resolve(mapFiles[i]) );
}
return next();
} | [
"function",
"(",
"next",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"mapFiles",
".",
"length",
";",
"i",
"++",
")",
"{",
"fs",
".",
"unlinkSync",
"(",
"mapFiles",
"[",
"i",
"]",
")",
";",
"}",
"return",
"next",
"(",
")",
";",
"}"
] | Remove source map files | [
"Remove",
"source",
"map",
"files"
] | 6b7cefecdcf425f30e888ede9e71908850b5447d | https://github.com/SonoIo/node-eve/blob/6b7cefecdcf425f30e888ede9e71908850b5447d/lib/build.js#L389-L395 | train |
|
SonoIo/node-eve | lib/build.js | minify | function minify( file, options, done ){
if (_.isFunction(options)){
done = options;
options = {};
}
if (!_.isObject(options))
options = {};
if (!_.isFunction(done))
done = function(){};
const canOptimize = options.optimize;
delete options.optimize;
console.log(" minify file %s...".grey, file);
try {
var code = fs.readFileSync( file, {encoding: 'utf8'} );
var minify = UglifyJS.minify( code, options );
} catch (e) {
return done( new Error(`Error on parse file ${e.filename}`) );
}
if ( !minify || minify.error ) {
if ( minify && minify.error )
return done( new Error(minify.error.message) );
return done(new Error('Minify error bundle.js') );
}
try{
if ( canOptimize ){
console.log(" optimize file %s...".grey, file );
code = optimizeJs(minify.code);
}else{
code = minify.code;
}
}catch(e){
console.error("Error on parse file %s", e.filename);
return next(e);
}
fs.writeFile(
file,
code,
function (err) {
if ( err )
return done(err);
return done();
}
);
} | javascript | function minify( file, options, done ){
if (_.isFunction(options)){
done = options;
options = {};
}
if (!_.isObject(options))
options = {};
if (!_.isFunction(done))
done = function(){};
const canOptimize = options.optimize;
delete options.optimize;
console.log(" minify file %s...".grey, file);
try {
var code = fs.readFileSync( file, {encoding: 'utf8'} );
var minify = UglifyJS.minify( code, options );
} catch (e) {
return done( new Error(`Error on parse file ${e.filename}`) );
}
if ( !minify || minify.error ) {
if ( minify && minify.error )
return done( new Error(minify.error.message) );
return done(new Error('Minify error bundle.js') );
}
try{
if ( canOptimize ){
console.log(" optimize file %s...".grey, file );
code = optimizeJs(minify.code);
}else{
code = minify.code;
}
}catch(e){
console.error("Error on parse file %s", e.filename);
return next(e);
}
fs.writeFile(
file,
code,
function (err) {
if ( err )
return done(err);
return done();
}
);
} | [
"function",
"minify",
"(",
"file",
",",
"options",
",",
"done",
")",
"{",
"if",
"(",
"_",
".",
"isFunction",
"(",
"options",
")",
")",
"{",
"done",
"=",
"options",
";",
"options",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"!",
"_",
".",
"isObject",
"(",
"options",
")",
")",
"options",
"=",
"{",
"}",
";",
"if",
"(",
"!",
"_",
".",
"isFunction",
"(",
"done",
")",
")",
"done",
"=",
"function",
"(",
")",
"{",
"}",
";",
"const",
"canOptimize",
"=",
"options",
".",
"optimize",
";",
"delete",
"options",
".",
"optimize",
";",
"console",
".",
"log",
"(",
"\" minify file %s...\"",
".",
"grey",
",",
"file",
")",
";",
"try",
"{",
"var",
"code",
"=",
"fs",
".",
"readFileSync",
"(",
"file",
",",
"{",
"encoding",
":",
"'utf8'",
"}",
")",
";",
"var",
"minify",
"=",
"UglifyJS",
".",
"minify",
"(",
"code",
",",
"options",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"done",
"(",
"new",
"Error",
"(",
"`",
"${",
"e",
".",
"filename",
"}",
"`",
")",
")",
";",
"}",
"if",
"(",
"!",
"minify",
"||",
"minify",
".",
"error",
")",
"{",
"if",
"(",
"minify",
"&&",
"minify",
".",
"error",
")",
"return",
"done",
"(",
"new",
"Error",
"(",
"minify",
".",
"error",
".",
"message",
")",
")",
";",
"return",
"done",
"(",
"new",
"Error",
"(",
"'Minify error bundle.js'",
")",
")",
";",
"}",
"try",
"{",
"if",
"(",
"canOptimize",
")",
"{",
"console",
".",
"log",
"(",
"\" optimize file %s...\"",
".",
"grey",
",",
"file",
")",
";",
"code",
"=",
"optimizeJs",
"(",
"minify",
".",
"code",
")",
";",
"}",
"else",
"{",
"code",
"=",
"minify",
".",
"code",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"error",
"(",
"\"Error on parse file %s\"",
",",
"e",
".",
"filename",
")",
";",
"return",
"next",
"(",
"e",
")",
";",
"}",
"fs",
".",
"writeFile",
"(",
"file",
",",
"code",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"done",
"(",
"err",
")",
";",
"return",
"done",
"(",
")",
";",
"}",
")",
";",
"}"
] | End bundle Function for minified | [
"End",
"bundle",
"Function",
"for",
"minified"
] | 6b7cefecdcf425f30e888ede9e71908850b5447d | https://github.com/SonoIo/node-eve/blob/6b7cefecdcf425f30e888ede9e71908850b5447d/lib/build.js#L427-L477 | train |
SonoIo/node-eve | lib/build.js | publisher | function publisher(outputJsFile, done, forceMinified){
// Check if JSCrambler configs file exist
const time = process.hrtime();
const jscramblerConfigs = path.resolve('jscrambler.json');
fs.stat( jscramblerConfigs, function (err) {
if ( err ){
let newTime =
console.log(' obfuscating code with jScrambler was not executed, because the configs file `jscrambler.json` is not present into project\'s directory.'.yellow);
console.log('Publication finished!'.gray); // +beautifyTime( process.hrtime(time) ).green + '\u0007'
return done(err);
}
console.log(' obfuscating code with jScrambler...'.gray);
try {
var configs = require(jscramblerConfigs);
} catch (e) {
return done(' Error on obfuscation! The file configs is not a valid JSON'.red);
}
if ( !_.isObject(configs.keys) ||
_.isEmpty(configs.keys.accessKey) ||
_.isEmpty(configs.keys.secretKey) ||
_.isEmpty(configs.applicationId)
){
return done( new Error(' Error on obfuscation! Jcrambler\'s configs missed. Ex.: accessKey, secretKey or applicationId.') );
}
// Set the file for obfuscation
if ( !_.isArray(configs.filesSrc) )
configs.filesSrc = [];
if ( configs.filesSrc.indexOf(outputJsFile) == -1 )
configs.filesSrc.push(outputJsFile);
configs.filesDest = path.dirname( packageJSONFile ); // The project's dirname
/*
{
keys: {
accessKey: 'YOUR_JSCRAMBLER_ACCESS_KEY',
secretKey: 'YOUR_JSCRAMBLER_SECRET_KEY'
},
host: 'api4.jscrambler.com',
port: 443,
applicationId: 'YOUR_APPLICATION_ID',
filesSrc: [
'/path/to/src/*.html',
'/path/to/src/*.js'
],
filesDest: '/path/to/destDir/',
params: {
stringSplitting: {
chunk: 1
}
}
}
*/
const symbolTable = path.join( configs.filesDest, "symbolTable.json");
jscrambler
.protectAndDownload(configs)
.then(function () {
try{
const st = fs.statSync( symbolTable );
fs.unlinkSync(symbolTable);
}catch(e){}
if ( !forceMinified ){
console.log('Publication finished in '.gray+beautifyTime( process.hrtime(time) ).green + '\u0007');
return done();
}
minify(outputJsFile,{},function(err){
if (err){
return done(err);
}
console.log('Publication finished in '.gray+beautifyTime( process.hrtime(time) ).green + '\u0007');
return done();
});
})
.catch(function (err) {
let message = ' Error on obfuscation! Error while obfuscating the code with jScrambler';
if ( err && err.message )
message = ` Error on obfuscation! jScrambler: ${err.message}`;
done( new Error(message) );
});
});
} | javascript | function publisher(outputJsFile, done, forceMinified){
// Check if JSCrambler configs file exist
const time = process.hrtime();
const jscramblerConfigs = path.resolve('jscrambler.json');
fs.stat( jscramblerConfigs, function (err) {
if ( err ){
let newTime =
console.log(' obfuscating code with jScrambler was not executed, because the configs file `jscrambler.json` is not present into project\'s directory.'.yellow);
console.log('Publication finished!'.gray); // +beautifyTime( process.hrtime(time) ).green + '\u0007'
return done(err);
}
console.log(' obfuscating code with jScrambler...'.gray);
try {
var configs = require(jscramblerConfigs);
} catch (e) {
return done(' Error on obfuscation! The file configs is not a valid JSON'.red);
}
if ( !_.isObject(configs.keys) ||
_.isEmpty(configs.keys.accessKey) ||
_.isEmpty(configs.keys.secretKey) ||
_.isEmpty(configs.applicationId)
){
return done( new Error(' Error on obfuscation! Jcrambler\'s configs missed. Ex.: accessKey, secretKey or applicationId.') );
}
// Set the file for obfuscation
if ( !_.isArray(configs.filesSrc) )
configs.filesSrc = [];
if ( configs.filesSrc.indexOf(outputJsFile) == -1 )
configs.filesSrc.push(outputJsFile);
configs.filesDest = path.dirname( packageJSONFile ); // The project's dirname
/*
{
keys: {
accessKey: 'YOUR_JSCRAMBLER_ACCESS_KEY',
secretKey: 'YOUR_JSCRAMBLER_SECRET_KEY'
},
host: 'api4.jscrambler.com',
port: 443,
applicationId: 'YOUR_APPLICATION_ID',
filesSrc: [
'/path/to/src/*.html',
'/path/to/src/*.js'
],
filesDest: '/path/to/destDir/',
params: {
stringSplitting: {
chunk: 1
}
}
}
*/
const symbolTable = path.join( configs.filesDest, "symbolTable.json");
jscrambler
.protectAndDownload(configs)
.then(function () {
try{
const st = fs.statSync( symbolTable );
fs.unlinkSync(symbolTable);
}catch(e){}
if ( !forceMinified ){
console.log('Publication finished in '.gray+beautifyTime( process.hrtime(time) ).green + '\u0007');
return done();
}
minify(outputJsFile,{},function(err){
if (err){
return done(err);
}
console.log('Publication finished in '.gray+beautifyTime( process.hrtime(time) ).green + '\u0007');
return done();
});
})
.catch(function (err) {
let message = ' Error on obfuscation! Error while obfuscating the code with jScrambler';
if ( err && err.message )
message = ` Error on obfuscation! jScrambler: ${err.message}`;
done( new Error(message) );
});
});
} | [
"function",
"publisher",
"(",
"outputJsFile",
",",
"done",
",",
"forceMinified",
")",
"{",
"const",
"time",
"=",
"process",
".",
"hrtime",
"(",
")",
";",
"const",
"jscramblerConfigs",
"=",
"path",
".",
"resolve",
"(",
"'jscrambler.json'",
")",
";",
"fs",
".",
"stat",
"(",
"jscramblerConfigs",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"let",
"newTime",
"=",
"console",
".",
"log",
"(",
"' obfuscating code with jScrambler was not executed, because the configs file `jscrambler.json` is not present into project\\'s directory.'",
".",
"\\'",
")",
";",
"yellow",
"console",
".",
"log",
"(",
"'Publication finished!'",
".",
"gray",
")",
";",
"}",
"return",
"done",
"(",
"err",
")",
";",
"console",
".",
"log",
"(",
"' obfuscating code with jScrambler...'",
".",
"gray",
")",
";",
"try",
"{",
"var",
"configs",
"=",
"require",
"(",
"jscramblerConfigs",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"done",
"(",
"' Error on obfuscation! The file configs is not a valid JSON'",
".",
"red",
")",
";",
"}",
"if",
"(",
"!",
"_",
".",
"isObject",
"(",
"configs",
".",
"keys",
")",
"||",
"_",
".",
"isEmpty",
"(",
"configs",
".",
"keys",
".",
"accessKey",
")",
"||",
"_",
".",
"isEmpty",
"(",
"configs",
".",
"keys",
".",
"secretKey",
")",
"||",
"_",
".",
"isEmpty",
"(",
"configs",
".",
"applicationId",
")",
")",
"{",
"return",
"done",
"(",
"new",
"Error",
"(",
"' Error on obfuscation! Jcrambler\\'s configs missed. Ex.: accessKey, secretKey or applicationId.'",
")",
")",
";",
"}",
"\\'",
"if",
"(",
"!",
"_",
".",
"isArray",
"(",
"configs",
".",
"filesSrc",
")",
")",
"configs",
".",
"filesSrc",
"=",
"[",
"]",
";",
"if",
"(",
"configs",
".",
"filesSrc",
".",
"indexOf",
"(",
"outputJsFile",
")",
"==",
"-",
"1",
")",
"configs",
".",
"filesSrc",
".",
"push",
"(",
"outputJsFile",
")",
";",
"configs",
".",
"filesDest",
"=",
"path",
".",
"dirname",
"(",
"packageJSONFile",
")",
";",
"}",
")",
";",
"}"
] | Function for publisher and obfuscation method | [
"Function",
"for",
"publisher",
"and",
"obfuscation",
"method"
] | 6b7cefecdcf425f30e888ede9e71908850b5447d | https://github.com/SonoIo/node-eve/blob/6b7cefecdcf425f30e888ede9e71908850b5447d/lib/build.js#L481-L574 | train |
Pinoccio/client-node-pinoccio | lib/api.js | function(token,options){
options = options||{};
options.token = token;
var obj = {
type:"rest"
,args:{
url: '/v1/sync',
data: options,
method: 'get'
}
};
var s = through();
repipe(s,function(err,last,done){
o.log('repipe got error? ',err,' should i repipe?');
if(err && err.code != 'E_MDM') return done(err);
getConnection(function(err,con){
if(err) return done(err);
var dbstream = con.mdm.createReadStream(obj);
var noendstream = dbstream.pipe(through(function(data){
this.queue(data);
},function(){
if(options.tail || options.tail == undefined) {
// repipe resumes the stream on error events!
var error = new Error("never end bro!");
error.code = "E_MDM";
this.emit("error",error);
} else {
this.queue(null);
}
}));
dbstream.on('error',function(err){
noendstream.emit("error",err)
});
done(false,noendstream);
});
});
s.on('data',function(d){
// on reconnect start sync from where i left off.
obj.args.data.start = d.time;
})
return s;
} | javascript | function(token,options){
options = options||{};
options.token = token;
var obj = {
type:"rest"
,args:{
url: '/v1/sync',
data: options,
method: 'get'
}
};
var s = through();
repipe(s,function(err,last,done){
o.log('repipe got error? ',err,' should i repipe?');
if(err && err.code != 'E_MDM') return done(err);
getConnection(function(err,con){
if(err) return done(err);
var dbstream = con.mdm.createReadStream(obj);
var noendstream = dbstream.pipe(through(function(data){
this.queue(data);
},function(){
if(options.tail || options.tail == undefined) {
// repipe resumes the stream on error events!
var error = new Error("never end bro!");
error.code = "E_MDM";
this.emit("error",error);
} else {
this.queue(null);
}
}));
dbstream.on('error',function(err){
noendstream.emit("error",err)
});
done(false,noendstream);
});
});
s.on('data',function(d){
// on reconnect start sync from where i left off.
obj.args.data.start = d.time;
})
return s;
} | [
"function",
"(",
"token",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"options",
".",
"token",
"=",
"token",
";",
"var",
"obj",
"=",
"{",
"type",
":",
"\"rest\"",
",",
"args",
":",
"{",
"url",
":",
"'/v1/sync'",
",",
"data",
":",
"options",
",",
"method",
":",
"'get'",
"}",
"}",
";",
"var",
"s",
"=",
"through",
"(",
")",
";",
"repipe",
"(",
"s",
",",
"function",
"(",
"err",
",",
"last",
",",
"done",
")",
"{",
"o",
".",
"log",
"(",
"'repipe got error? '",
",",
"err",
",",
"' should i repipe?'",
")",
";",
"if",
"(",
"err",
"&&",
"err",
".",
"code",
"!=",
"'E_MDM'",
")",
"return",
"done",
"(",
"err",
")",
";",
"getConnection",
"(",
"function",
"(",
"err",
",",
"con",
")",
"{",
"if",
"(",
"err",
")",
"return",
"done",
"(",
"err",
")",
";",
"var",
"dbstream",
"=",
"con",
".",
"mdm",
".",
"createReadStream",
"(",
"obj",
")",
";",
"var",
"noendstream",
"=",
"dbstream",
".",
"pipe",
"(",
"through",
"(",
"function",
"(",
"data",
")",
"{",
"this",
".",
"queue",
"(",
"data",
")",
";",
"}",
",",
"function",
"(",
")",
"{",
"if",
"(",
"options",
".",
"tail",
"||",
"options",
".",
"tail",
"==",
"undefined",
")",
"{",
"var",
"error",
"=",
"new",
"Error",
"(",
"\"never end bro!\"",
")",
";",
"error",
".",
"code",
"=",
"\"E_MDM\"",
";",
"this",
".",
"emit",
"(",
"\"error\"",
",",
"error",
")",
";",
"}",
"else",
"{",
"this",
".",
"queue",
"(",
"null",
")",
";",
"}",
"}",
")",
")",
";",
"dbstream",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"noendstream",
".",
"emit",
"(",
"\"error\"",
",",
"err",
")",
"}",
")",
";",
"done",
"(",
"false",
",",
"noendstream",
")",
";",
"}",
")",
";",
"}",
")",
";",
"s",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"d",
")",
"{",
"obj",
".",
"args",
".",
"data",
".",
"start",
"=",
"d",
".",
"time",
";",
"}",
")",
"return",
"s",
";",
"}"
] | sync the account's data in realtime | [
"sync",
"the",
"account",
"s",
"data",
"in",
"realtime"
] | 9ee7b254639190a228dce6a4db9680f2c1bf1ca5 | https://github.com/Pinoccio/client-node-pinoccio/blob/9ee7b254639190a228dce6a4db9680f2c1bf1ca5/lib/api.js#L60-L110 | train |
|
Pinoccio/client-node-pinoccio | lib/api.js | function(token,o){
/*
o.troop
o.scout
o.reports = [led,..]
o.start = now
o.end = then
o.tail defaults true with no end
*/
o.token = token;
var obj = {
type:"rest"
,args:{
url: '/v1/stats',
data: o,
method: 'get'
}
};
var s = through();
repipe(s,function(err,last,done){
if(err && err.code != 'E_MDM') return done(err);
if(last) o.start = last.key;
getConnection(function(err,con){
if(err) return done(err);
done(false,con.mdm.createReadStream(obj));
});
});
return s; // resume!
} | javascript | function(token,o){
/*
o.troop
o.scout
o.reports = [led,..]
o.start = now
o.end = then
o.tail defaults true with no end
*/
o.token = token;
var obj = {
type:"rest"
,args:{
url: '/v1/stats',
data: o,
method: 'get'
}
};
var s = through();
repipe(s,function(err,last,done){
if(err && err.code != 'E_MDM') return done(err);
if(last) o.start = last.key;
getConnection(function(err,con){
if(err) return done(err);
done(false,con.mdm.createReadStream(obj));
});
});
return s; // resume!
} | [
"function",
"(",
"token",
",",
"o",
")",
"{",
"o",
".",
"token",
"=",
"token",
";",
"var",
"obj",
"=",
"{",
"type",
":",
"\"rest\"",
",",
"args",
":",
"{",
"url",
":",
"'/v1/stats'",
",",
"data",
":",
"o",
",",
"method",
":",
"'get'",
"}",
"}",
";",
"var",
"s",
"=",
"through",
"(",
")",
";",
"repipe",
"(",
"s",
",",
"function",
"(",
"err",
",",
"last",
",",
"done",
")",
"{",
"if",
"(",
"err",
"&&",
"err",
".",
"code",
"!=",
"'E_MDM'",
")",
"return",
"done",
"(",
"err",
")",
";",
"if",
"(",
"last",
")",
"o",
".",
"start",
"=",
"last",
".",
"key",
";",
"getConnection",
"(",
"function",
"(",
"err",
",",
"con",
")",
"{",
"if",
"(",
"err",
")",
"return",
"done",
"(",
"err",
")",
";",
"done",
"(",
"false",
",",
"con",
".",
"mdm",
".",
"createReadStream",
"(",
"obj",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"s",
";",
"}"
] | stream stats data | [
"stream",
"stats",
"data"
] | 9ee7b254639190a228dce6a4db9680f2c1bf1ca5 | https://github.com/Pinoccio/client-node-pinoccio/blob/9ee7b254639190a228dce6a4db9680f2c1bf1ca5/lib/api.js#L112-L145 | train |
|
lddubeau/karma-typescript-agile-preprocessor | index.js | _serveFile | function _serveFile(requestedFile, done) {
requestedFile.path = transformPath(requestedFile.path);
log.debug(`Fetching ${requestedFile.path} from buffer`);
// We get a requestedFile with an sha when Karma is watching files on
// disk, and the file requested changed. When this happens, we need to
// recompile the whole lot.
if (requestedFile.sha) {
delete requestedFile.sha; // Hack used to prevent infinite loop.
enqueueForServing(requestedFile, done);
// eslint-disable-next-line no-use-before-define
compile();
return;
}
const normalized = _normalize(requestedFile.path);
const compiled = compilationResults[normalized];
if (compiled) {
delete compilationResults[normalized];
done(null, compiled.contents.toString());
return;
}
// If the file was not found in the stream, then maybe it is not compiled
// or it is a definition file.
log.debug(`${requestedFile.originalPath} was not found. Maybe it was \
not compiled or it is a definition file.`);
done(null, dummyFile("This file was not compiled"));
} | javascript | function _serveFile(requestedFile, done) {
requestedFile.path = transformPath(requestedFile.path);
log.debug(`Fetching ${requestedFile.path} from buffer`);
// We get a requestedFile with an sha when Karma is watching files on
// disk, and the file requested changed. When this happens, we need to
// recompile the whole lot.
if (requestedFile.sha) {
delete requestedFile.sha; // Hack used to prevent infinite loop.
enqueueForServing(requestedFile, done);
// eslint-disable-next-line no-use-before-define
compile();
return;
}
const normalized = _normalize(requestedFile.path);
const compiled = compilationResults[normalized];
if (compiled) {
delete compilationResults[normalized];
done(null, compiled.contents.toString());
return;
}
// If the file was not found in the stream, then maybe it is not compiled
// or it is a definition file.
log.debug(`${requestedFile.originalPath} was not found. Maybe it was \
not compiled or it is a definition file.`);
done(null, dummyFile("This file was not compiled"));
} | [
"function",
"_serveFile",
"(",
"requestedFile",
",",
"done",
")",
"{",
"requestedFile",
".",
"path",
"=",
"transformPath",
"(",
"requestedFile",
".",
"path",
")",
";",
"log",
".",
"debug",
"(",
"`",
"${",
"requestedFile",
".",
"path",
"}",
"`",
")",
";",
"if",
"(",
"requestedFile",
".",
"sha",
")",
"{",
"delete",
"requestedFile",
".",
"sha",
";",
"enqueueForServing",
"(",
"requestedFile",
",",
"done",
")",
";",
"compile",
"(",
")",
";",
"return",
";",
"}",
"const",
"normalized",
"=",
"_normalize",
"(",
"requestedFile",
".",
"path",
")",
";",
"const",
"compiled",
"=",
"compilationResults",
"[",
"normalized",
"]",
";",
"if",
"(",
"compiled",
")",
"{",
"delete",
"compilationResults",
"[",
"normalized",
"]",
";",
"done",
"(",
"null",
",",
"compiled",
".",
"contents",
".",
"toString",
"(",
")",
")",
";",
"return",
";",
"}",
"log",
".",
"debug",
"(",
"`",
"${",
"requestedFile",
".",
"originalPath",
"}",
"\\",
"`",
")",
";",
"done",
"(",
"null",
",",
"dummyFile",
"(",
"\"This file was not compiled\"",
")",
")",
";",
"}"
] | Used to fetch files from buffer. | [
"Used",
"to",
"fetch",
"files",
"from",
"buffer",
"."
] | c80eb2ab72bd46f227d1df2bca8da5fbbb5960ba | https://github.com/lddubeau/karma-typescript-agile-preprocessor/blob/c80eb2ab72bd46f227d1df2bca8da5fbbb5960ba/index.js#L80-L109 | train |
lddubeau/karma-typescript-agile-preprocessor | index.js | processServeQueue | function processServeQueue() {
while (serveQueue.length) {
const item = serveQueue.shift();
_serveFile(item.file, item.done);
// It is possible start compiling while in release.
if (state.compilationCompleted !== _currentState) {
break;
}
}
} | javascript | function processServeQueue() {
while (serveQueue.length) {
const item = serveQueue.shift();
_serveFile(item.file, item.done);
// It is possible start compiling while in release.
if (state.compilationCompleted !== _currentState) {
break;
}
}
} | [
"function",
"processServeQueue",
"(",
")",
"{",
"while",
"(",
"serveQueue",
".",
"length",
")",
"{",
"const",
"item",
"=",
"serveQueue",
".",
"shift",
"(",
")",
";",
"_serveFile",
"(",
"item",
".",
"file",
",",
"item",
".",
"done",
")",
";",
"if",
"(",
"state",
".",
"compilationCompleted",
"!==",
"_currentState",
")",
"{",
"break",
";",
"}",
"}",
"}"
] | Responsible for flushing the cache and notifying karma. | [
"Responsible",
"for",
"flushing",
"the",
"cache",
"and",
"notifying",
"karma",
"."
] | c80eb2ab72bd46f227d1df2bca8da5fbbb5960ba | https://github.com/lddubeau/karma-typescript-agile-preprocessor/blob/c80eb2ab72bd46f227d1df2bca8da5fbbb5960ba/index.js#L112-L121 | train |
bem-contrib/md-to-bemjson | packages/mdast-util-to-bemjson/lib/traverse.js | traverse | function traverse(transform, node, parent) {
const type = node && node.type;
assert(type, `Expected node, got '${node}'`);
const baseHandler = transform.handlers[type] || transform.handlers.default;
const userHandler = transform.userHandlers[type] || transform.userHandlers.default;
const starHandler = transform.userHandlers['*'];
const userBaseHandler = userHandler ? userHandler.bind({ __base: baseHandler }) : baseHandler;
const handler = starHandler ? starHandler.bind({ __base: userBaseHandler }) : userBaseHandler;
return handler(transform, node, parent);
} | javascript | function traverse(transform, node, parent) {
const type = node && node.type;
assert(type, `Expected node, got '${node}'`);
const baseHandler = transform.handlers[type] || transform.handlers.default;
const userHandler = transform.userHandlers[type] || transform.userHandlers.default;
const starHandler = transform.userHandlers['*'];
const userBaseHandler = userHandler ? userHandler.bind({ __base: baseHandler }) : baseHandler;
const handler = starHandler ? starHandler.bind({ __base: userBaseHandler }) : userBaseHandler;
return handler(transform, node, parent);
} | [
"function",
"traverse",
"(",
"transform",
",",
"node",
",",
"parent",
")",
"{",
"const",
"type",
"=",
"node",
"&&",
"node",
".",
"type",
";",
"assert",
"(",
"type",
",",
"`",
"${",
"node",
"}",
"`",
")",
";",
"const",
"baseHandler",
"=",
"transform",
".",
"handlers",
"[",
"type",
"]",
"||",
"transform",
".",
"handlers",
".",
"default",
";",
"const",
"userHandler",
"=",
"transform",
".",
"userHandlers",
"[",
"type",
"]",
"||",
"transform",
".",
"userHandlers",
".",
"default",
";",
"const",
"starHandler",
"=",
"transform",
".",
"userHandlers",
"[",
"'*'",
"]",
";",
"const",
"userBaseHandler",
"=",
"userHandler",
"?",
"userHandler",
".",
"bind",
"(",
"{",
"__base",
":",
"baseHandler",
"}",
")",
":",
"baseHandler",
";",
"const",
"handler",
"=",
"starHandler",
"?",
"starHandler",
".",
"bind",
"(",
"{",
"__base",
":",
"userBaseHandler",
"}",
")",
":",
"userBaseHandler",
";",
"return",
"handler",
"(",
"transform",
",",
"node",
",",
"parent",
")",
";",
"}"
] | Traverse MDAST tree
@param {*} transform - transform function
@param {Object} node - MDAST node
@param {Object} [parent] - MDAST parent node
@returns {*} | [
"Traverse",
"MDAST",
"tree"
] | 047ab80c681073c7c92aecee754bcf46956507a9 | https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/mdast-util-to-bemjson/lib/traverse.js#L13-L25 | train |
Incroud/cassanova | lib/table.js | Table | function Table(name, schema){
if(!name || typeof name !== "string"){
throw new Error("Attempting to instantiate a table without a valid name.");
}
if(!schema || !(schema instanceof Schema)){
throw new Error("Attempting to instantiate a table without a valid schema.");
}
this.name = name;
this.schema = schema;
} | javascript | function Table(name, schema){
if(!name || typeof name !== "string"){
throw new Error("Attempting to instantiate a table without a valid name.");
}
if(!schema || !(schema instanceof Schema)){
throw new Error("Attempting to instantiate a table without a valid schema.");
}
this.name = name;
this.schema = schema;
} | [
"function",
"Table",
"(",
"name",
",",
"schema",
")",
"{",
"if",
"(",
"!",
"name",
"||",
"typeof",
"name",
"!==",
"\"string\"",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Attempting to instantiate a table without a valid name.\"",
")",
";",
"}",
"if",
"(",
"!",
"schema",
"||",
"!",
"(",
"schema",
"instanceof",
"Schema",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Attempting to instantiate a table without a valid schema.\"",
")",
";",
"}",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"schema",
"=",
"schema",
";",
"}"
] | Cassanova.Table
@param {String} name The name of the table. Must match the name of the table in Cassandra
@param {Schema} schema The table associated with the model. | [
"Cassanova",
".",
"Table"
] | 49c5ce2e1bc6b19d25e8223e88df45c113c36b68 | https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/lib/table.js#L10-L20 | train |
hoodiehq/pouchdb-hoodie-sync | lib/connect.js | connect | function connect (state) {
return Promise.resolve(state.remote)
.then(function (remote) {
if (state.replication) {
return
}
state.replication = state.db.sync(remote, {
create_target: true,
live: true,
retry: true
})
state.replication.on('error', function (error) {
state.emitter.emit('error', error)
})
state.replication.on('change', function (change) {
for (var i = 0; i < change.change.docs.length; i++) {
state.emitter.emit(change.direction, change.change.docs[i])
}
})
state.emitter.emit('connect')
})
} | javascript | function connect (state) {
return Promise.resolve(state.remote)
.then(function (remote) {
if (state.replication) {
return
}
state.replication = state.db.sync(remote, {
create_target: true,
live: true,
retry: true
})
state.replication.on('error', function (error) {
state.emitter.emit('error', error)
})
state.replication.on('change', function (change) {
for (var i = 0; i < change.change.docs.length; i++) {
state.emitter.emit(change.direction, change.change.docs[i])
}
})
state.emitter.emit('connect')
})
} | [
"function",
"connect",
"(",
"state",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"state",
".",
"remote",
")",
".",
"then",
"(",
"function",
"(",
"remote",
")",
"{",
"if",
"(",
"state",
".",
"replication",
")",
"{",
"return",
"}",
"state",
".",
"replication",
"=",
"state",
".",
"db",
".",
"sync",
"(",
"remote",
",",
"{",
"create_target",
":",
"true",
",",
"live",
":",
"true",
",",
"retry",
":",
"true",
"}",
")",
"state",
".",
"replication",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"error",
")",
"{",
"state",
".",
"emitter",
".",
"emit",
"(",
"'error'",
",",
"error",
")",
"}",
")",
"state",
".",
"replication",
".",
"on",
"(",
"'change'",
",",
"function",
"(",
"change",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"change",
".",
"change",
".",
"docs",
".",
"length",
";",
"i",
"++",
")",
"{",
"state",
".",
"emitter",
".",
"emit",
"(",
"change",
".",
"direction",
",",
"change",
".",
"change",
".",
"docs",
"[",
"i",
"]",
")",
"}",
"}",
")",
"state",
".",
"emitter",
".",
"emit",
"(",
"'connect'",
")",
"}",
")",
"}"
] | connects local and remote database
@return {Promise} | [
"connects",
"local",
"and",
"remote",
"database"
] | c489baf813020c7f0cbd111224432cb6718c90de | https://github.com/hoodiehq/pouchdb-hoodie-sync/blob/c489baf813020c7f0cbd111224432cb6718c90de/lib/connect.js#L10-L36 | train |
soajs/soajs.core.drivers | infra/aws/docker/index.js | function (options, cb) {
options.soajs.log.debug("Generating docker token");
crypto.randomBytes(1024, function (err, buffer) {
if (err) {
return cb(err);
}
options.soajs.registry.deployer.container.docker.remote.apiProtocol = 'https';
options.soajs.registry.deployer.container.docker.remote.apiPort = 32376;
options.soajs.registry.deployer.container.docker.remote.auth = {
token: buffer.toString('hex')
};
return cb(null, true);
});
} | javascript | function (options, cb) {
options.soajs.log.debug("Generating docker token");
crypto.randomBytes(1024, function (err, buffer) {
if (err) {
return cb(err);
}
options.soajs.registry.deployer.container.docker.remote.apiProtocol = 'https';
options.soajs.registry.deployer.container.docker.remote.apiPort = 32376;
options.soajs.registry.deployer.container.docker.remote.auth = {
token: buffer.toString('hex')
};
return cb(null, true);
});
} | [
"function",
"(",
"options",
",",
"cb",
")",
"{",
"options",
".",
"soajs",
".",
"log",
".",
"debug",
"(",
"\"Generating docker token\"",
")",
";",
"crypto",
".",
"randomBytes",
"(",
"1024",
",",
"function",
"(",
"err",
",",
"buffer",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"options",
".",
"soajs",
".",
"registry",
".",
"deployer",
".",
"container",
".",
"docker",
".",
"remote",
".",
"apiProtocol",
"=",
"'https'",
";",
"options",
".",
"soajs",
".",
"registry",
".",
"deployer",
".",
"container",
".",
"docker",
".",
"remote",
".",
"apiPort",
"=",
"32376",
";",
"options",
".",
"soajs",
".",
"registry",
".",
"deployer",
".",
"container",
".",
"docker",
".",
"remote",
".",
"auth",
"=",
"{",
"token",
":",
"buffer",
".",
"toString",
"(",
"'hex'",
")",
"}",
";",
"return",
"cb",
"(",
"null",
",",
"true",
")",
";",
"}",
")",
";",
"}"
] | Execute Deploy Cluster Pre Operation
@param options
@param cb
@returns {*} | [
"Execute",
"Deploy",
"Cluster",
"Pre",
"Operation"
] | 545891509a47e16d9d2f40515e81bb1f4f3d8165 | https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/aws/docker/index.js#L23-L37 | train |
|
soajs/soajs.core.drivers | infra/aws/docker/index.js | function (options, cb) {
let outIP = options.out;
let stack = options.infra.stack;
if (outIP && stack.options.ElbName) {
options.soajs.log.debug("Creating SOAJS network.");
dockerUtils.getDeployer(options, (error, deployer) => {
if(error){
return cb(error);
}
deployer.listNetworks({}, (err, networks) => {
if (err) {
return cb(err);
}
let found = false;
networks.forEach((oneNetwork) => {
if (oneNetwork.Name === 'soajsnet') {
found = true;
}
});
if(found){
return cb(null, true);
}
else{
let networkParams = {
Name: 'soajsnet',
Driver: 'overlay',
Internal: false,
Attachable: true,
CheckDuplicate: true,
EnableIPv6: false,
IPAM: {
Driver: 'default'
}
};
deployer.createNetwork(networkParams, (err) => {
return cb(err, true);
});
}
});
});
}
else {
return cb(null, false);
}
} | javascript | function (options, cb) {
let outIP = options.out;
let stack = options.infra.stack;
if (outIP && stack.options.ElbName) {
options.soajs.log.debug("Creating SOAJS network.");
dockerUtils.getDeployer(options, (error, deployer) => {
if(error){
return cb(error);
}
deployer.listNetworks({}, (err, networks) => {
if (err) {
return cb(err);
}
let found = false;
networks.forEach((oneNetwork) => {
if (oneNetwork.Name === 'soajsnet') {
found = true;
}
});
if(found){
return cb(null, true);
}
else{
let networkParams = {
Name: 'soajsnet',
Driver: 'overlay',
Internal: false,
Attachable: true,
CheckDuplicate: true,
EnableIPv6: false,
IPAM: {
Driver: 'default'
}
};
deployer.createNetwork(networkParams, (err) => {
return cb(err, true);
});
}
});
});
}
else {
return cb(null, false);
}
} | [
"function",
"(",
"options",
",",
"cb",
")",
"{",
"let",
"outIP",
"=",
"options",
".",
"out",
";",
"let",
"stack",
"=",
"options",
".",
"infra",
".",
"stack",
";",
"if",
"(",
"outIP",
"&&",
"stack",
".",
"options",
".",
"ElbName",
")",
"{",
"options",
".",
"soajs",
".",
"log",
".",
"debug",
"(",
"\"Creating SOAJS network.\"",
")",
";",
"dockerUtils",
".",
"getDeployer",
"(",
"options",
",",
"(",
"error",
",",
"deployer",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"cb",
"(",
"error",
")",
";",
"}",
"deployer",
".",
"listNetworks",
"(",
"{",
"}",
",",
"(",
"err",
",",
"networks",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"let",
"found",
"=",
"false",
";",
"networks",
".",
"forEach",
"(",
"(",
"oneNetwork",
")",
"=>",
"{",
"if",
"(",
"oneNetwork",
".",
"Name",
"===",
"'soajsnet'",
")",
"{",
"found",
"=",
"true",
";",
"}",
"}",
")",
";",
"if",
"(",
"found",
")",
"{",
"return",
"cb",
"(",
"null",
",",
"true",
")",
";",
"}",
"else",
"{",
"let",
"networkParams",
"=",
"{",
"Name",
":",
"'soajsnet'",
",",
"Driver",
":",
"'overlay'",
",",
"Internal",
":",
"false",
",",
"Attachable",
":",
"true",
",",
"CheckDuplicate",
":",
"true",
",",
"EnableIPv6",
":",
"false",
",",
"IPAM",
":",
"{",
"Driver",
":",
"'default'",
"}",
"}",
";",
"deployer",
".",
"createNetwork",
"(",
"networkParams",
",",
"(",
"err",
")",
"=>",
"{",
"return",
"cb",
"(",
"err",
",",
"true",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"return",
"cb",
"(",
"null",
",",
"false",
")",
";",
"}",
"}"
] | This method deploys the default soajsnet for docker
@param options
@param cb
@returns {*} | [
"This",
"method",
"deploys",
"the",
"default",
"soajsnet",
"for",
"docker"
] | 545891509a47e16d9d2f40515e81bb1f4f3d8165 | https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/aws/docker/index.js#L64-L114 | train |
|
hoodiehq/pouchdb-hoodie-sync | lib/disconnect.js | disconnect | function disconnect (state) {
if (state.replication) {
state.replication.cancel()
delete state.replication
state.emitter.emit('disconnect')
}
return Promise.resolve()
} | javascript | function disconnect (state) {
if (state.replication) {
state.replication.cancel()
delete state.replication
state.emitter.emit('disconnect')
}
return Promise.resolve()
} | [
"function",
"disconnect",
"(",
"state",
")",
"{",
"if",
"(",
"state",
".",
"replication",
")",
"{",
"state",
".",
"replication",
".",
"cancel",
"(",
")",
"delete",
"state",
".",
"replication",
"state",
".",
"emitter",
".",
"emit",
"(",
"'disconnect'",
")",
"}",
"return",
"Promise",
".",
"resolve",
"(",
")",
"}"
] | disconnects local and remote database
@return {Promise} | [
"disconnects",
"local",
"and",
"remote",
"database"
] | c489baf813020c7f0cbd111224432cb6718c90de | https://github.com/hoodiehq/pouchdb-hoodie-sync/blob/c489baf813020c7f0cbd111224432cb6718c90de/lib/disconnect.js#L10-L18 | train |
rangle/koast | lib/authentication/maintenance.js | addJwtHandling | function addJwtHandling(secrets, app) {
if (!secrets.authTokenSecret) {
log.error(
'Cannot setup token authentication because token secret is not configured.'
);
return;
}
app.use(expressJwt({
secret: secrets.authTokenSecret
}));
app.use(function (req, res, next) {
if (req.user && req.user.data) {
req.user.isAuthenticated = true;
req.user.meta = req.user.meta || {};
}
next();
});
app.use(function (err, req, res, next) {
if (err.name === 'UnauthorizedError') {
if (err.code === 'credentials_required') {
// If the caller did not provide credentials, we'll just consider this
// an unauthenticated request.
next();
} else {
res.status(401).send('Invalid token: ' + err.message);
}
}
});
} | javascript | function addJwtHandling(secrets, app) {
if (!secrets.authTokenSecret) {
log.error(
'Cannot setup token authentication because token secret is not configured.'
);
return;
}
app.use(expressJwt({
secret: secrets.authTokenSecret
}));
app.use(function (req, res, next) {
if (req.user && req.user.data) {
req.user.isAuthenticated = true;
req.user.meta = req.user.meta || {};
}
next();
});
app.use(function (err, req, res, next) {
if (err.name === 'UnauthorizedError') {
if (err.code === 'credentials_required') {
// If the caller did not provide credentials, we'll just consider this
// an unauthenticated request.
next();
} else {
res.status(401).send('Invalid token: ' + err.message);
}
}
});
} | [
"function",
"addJwtHandling",
"(",
"secrets",
",",
"app",
")",
"{",
"if",
"(",
"!",
"secrets",
".",
"authTokenSecret",
")",
"{",
"log",
".",
"error",
"(",
"'Cannot setup token authentication because token secret is not configured.'",
")",
";",
"return",
";",
"}",
"app",
".",
"use",
"(",
"expressJwt",
"(",
"{",
"secret",
":",
"secrets",
".",
"authTokenSecret",
"}",
")",
")",
";",
"app",
".",
"use",
"(",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"req",
".",
"user",
"&&",
"req",
".",
"user",
".",
"data",
")",
"{",
"req",
".",
"user",
".",
"isAuthenticated",
"=",
"true",
";",
"req",
".",
"user",
".",
"meta",
"=",
"req",
".",
"user",
".",
"meta",
"||",
"{",
"}",
";",
"}",
"next",
"(",
")",
";",
"}",
")",
";",
"app",
".",
"use",
"(",
"function",
"(",
"err",
",",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"err",
".",
"name",
"===",
"'UnauthorizedError'",
")",
"{",
"if",
"(",
"err",
".",
"code",
"===",
"'credentials_required'",
")",
"{",
"next",
"(",
")",
";",
"}",
"else",
"{",
"res",
".",
"status",
"(",
"401",
")",
".",
"send",
"(",
"'Invalid token: '",
"+",
"err",
".",
"message",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] | Adds the handling of Json Web Tokens. If a request comes with a JWT, we set the user accordingly. Improper or expired JWT results in a 401. If no JWT is submitted, however, we let this through, just without setting the user field on the request. | [
"Adds",
"the",
"handling",
"of",
"Json",
"Web",
"Tokens",
".",
"If",
"a",
"request",
"comes",
"with",
"a",
"JWT",
"we",
"set",
"the",
"user",
"accordingly",
".",
"Improper",
"or",
"expired",
"JWT",
"results",
"in",
"a",
"401",
".",
"If",
"no",
"JWT",
"is",
"submitted",
"however",
"we",
"let",
"this",
"through",
"just",
"without",
"setting",
"the",
"user",
"field",
"on",
"the",
"request",
"."
] | 446dfaba7f80c03ae17d86b34dfafd6328be1ba6 | https://github.com/rangle/koast/blob/446dfaba7f80c03ae17d86b34dfafd6328be1ba6/lib/authentication/maintenance.js#L25-L58 | train |
rangle/koast | lib/authentication/maintenance.js | addSessionHandling | function addSessionHandling(secrets, app) {
var connection = dbUtils.getConnectionNow();
var sessionStore = new MongoStore({
db: connection.db
});
app.use(cookieParser());
app.use(session({
secret: secrets.cookieSecret,
maxAge: 3600000, // 1 hour
store: sessionStore
}));
app.use(passport.initialize());
exports.usingSessions = true;
app.use(passport.session());
passport.serializeUser(function (user, done) {
var data = user.data || user;
done(null, {
data: data,
isAuthenticated: true,
meta: {}
});
});
passport.deserializeUser(function (obj, done) {
done(null, obj);
});
} | javascript | function addSessionHandling(secrets, app) {
var connection = dbUtils.getConnectionNow();
var sessionStore = new MongoStore({
db: connection.db
});
app.use(cookieParser());
app.use(session({
secret: secrets.cookieSecret,
maxAge: 3600000, // 1 hour
store: sessionStore
}));
app.use(passport.initialize());
exports.usingSessions = true;
app.use(passport.session());
passport.serializeUser(function (user, done) {
var data = user.data || user;
done(null, {
data: data,
isAuthenticated: true,
meta: {}
});
});
passport.deserializeUser(function (obj, done) {
done(null, obj);
});
} | [
"function",
"addSessionHandling",
"(",
"secrets",
",",
"app",
")",
"{",
"var",
"connection",
"=",
"dbUtils",
".",
"getConnectionNow",
"(",
")",
";",
"var",
"sessionStore",
"=",
"new",
"MongoStore",
"(",
"{",
"db",
":",
"connection",
".",
"db",
"}",
")",
";",
"app",
".",
"use",
"(",
"cookieParser",
"(",
")",
")",
";",
"app",
".",
"use",
"(",
"session",
"(",
"{",
"secret",
":",
"secrets",
".",
"cookieSecret",
",",
"maxAge",
":",
"3600000",
",",
"store",
":",
"sessionStore",
"}",
")",
")",
";",
"app",
".",
"use",
"(",
"passport",
".",
"initialize",
"(",
")",
")",
";",
"exports",
".",
"usingSessions",
"=",
"true",
";",
"app",
".",
"use",
"(",
"passport",
".",
"session",
"(",
")",
")",
";",
"passport",
".",
"serializeUser",
"(",
"function",
"(",
"user",
",",
"done",
")",
"{",
"var",
"data",
"=",
"user",
".",
"data",
"||",
"user",
";",
"done",
"(",
"null",
",",
"{",
"data",
":",
"data",
",",
"isAuthenticated",
":",
"true",
",",
"meta",
":",
"{",
"}",
"}",
")",
";",
"}",
")",
";",
"passport",
".",
"deserializeUser",
"(",
"function",
"(",
"obj",
",",
"done",
")",
"{",
"done",
"(",
"null",
",",
"obj",
")",
";",
"}",
")",
";",
"}"
] | Adds the handling of session cookies. | [
"Adds",
"the",
"handling",
"of",
"session",
"cookies",
"."
] | 446dfaba7f80c03ae17d86b34dfafd6328be1ba6 | https://github.com/rangle/koast/blob/446dfaba7f80c03ae17d86b34dfafd6328be1ba6/lib/authentication/maintenance.js#L61-L91 | train |
zillow/mustache-wax | lib/mustache-wax.js | mix | function mix(receiver, supplier, overwrite) {
var key;
if (!receiver || !supplier) {
return receiver || {};
}
for (key in supplier) {
if (supplier.hasOwnProperty(key)) {
if (overwrite || !receiver.hasOwnProperty(key)) {
receiver[key] = supplier[key];
}
}
}
return receiver;
} | javascript | function mix(receiver, supplier, overwrite) {
var key;
if (!receiver || !supplier) {
return receiver || {};
}
for (key in supplier) {
if (supplier.hasOwnProperty(key)) {
if (overwrite || !receiver.hasOwnProperty(key)) {
receiver[key] = supplier[key];
}
}
}
return receiver;
} | [
"function",
"mix",
"(",
"receiver",
",",
"supplier",
",",
"overwrite",
")",
"{",
"var",
"key",
";",
"if",
"(",
"!",
"receiver",
"||",
"!",
"supplier",
")",
"{",
"return",
"receiver",
"||",
"{",
"}",
";",
"}",
"for",
"(",
"key",
"in",
"supplier",
")",
"{",
"if",
"(",
"supplier",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"if",
"(",
"overwrite",
"||",
"!",
"receiver",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"receiver",
"[",
"key",
"]",
"=",
"supplier",
"[",
"key",
"]",
";",
"}",
"}",
"}",
"return",
"receiver",
";",
"}"
] | mix & merge lifted from yui-base, simplified | [
"mix",
"&",
"merge",
"lifted",
"from",
"yui",
"-",
"base",
"simplified"
] | 7e10cadba9c14c3b138ed568eebad16ea5d3b62c | https://github.com/zillow/mustache-wax/blob/7e10cadba9c14c3b138ed568eebad16ea5d3b62c/lib/mustache-wax.js#L284-L300 | train |
RavelLaw/e3 | addon/utils/shadow/scales/ordinal.js | function(val) {
let guid = guidFor(val);
if(guid in map) {
return map[guid];
} else if(sort) {
let sibiling = calculateMissingPosition(val, domain, sort);
return map[guidFor(sibiling)];
} else {
return r0;
}
} | javascript | function(val) {
let guid = guidFor(val);
if(guid in map) {
return map[guid];
} else if(sort) {
let sibiling = calculateMissingPosition(val, domain, sort);
return map[guidFor(sibiling)];
} else {
return r0;
}
} | [
"function",
"(",
"val",
")",
"{",
"let",
"guid",
"=",
"guidFor",
"(",
"val",
")",
";",
"if",
"(",
"guid",
"in",
"map",
")",
"{",
"return",
"map",
"[",
"guid",
"]",
";",
"}",
"else",
"if",
"(",
"sort",
")",
"{",
"let",
"sibiling",
"=",
"calculateMissingPosition",
"(",
"val",
",",
"domain",
",",
"sort",
")",
";",
"return",
"map",
"[",
"guidFor",
"(",
"sibiling",
")",
"]",
";",
"}",
"else",
"{",
"return",
"r0",
";",
"}",
"}"
] | Create the closure that will return the matched value. | [
"Create",
"the",
"closure",
"that",
"will",
"return",
"the",
"matched",
"value",
"."
] | 7149b2a9ebddd5c512132a41f7ae7c3a2235ac0d | https://github.com/RavelLaw/e3/blob/7149b2a9ebddd5c512132a41f7ae7c3a2235ac0d/addon/utils/shadow/scales/ordinal.js#L61-L71 | train |
|
rangle/koast | lib/admin-api/backup/backup.js | restoreBackup | function restoreBackup(backupRecord, mongoUri) {
var receipts = backupRecord.receipts;
var handler = getHandler(backupRecord.type);
var restorePromises = receipts.map(function (receipt) {
var tmpfile = util.getTempFileName() + '.bson';
return R.pPipe(
handler.restore.bind(handler),
R.curry(R.flip(mds.dump.fs.file))(tmpfile),
R.curryN(4, mongoRestoreFromFile)(tmpfile, mongoUri, receipt.collection)
)(receipt.data);
});
return q.all(restorePromises).thenResolve('done');
} | javascript | function restoreBackup(backupRecord, mongoUri) {
var receipts = backupRecord.receipts;
var handler = getHandler(backupRecord.type);
var restorePromises = receipts.map(function (receipt) {
var tmpfile = util.getTempFileName() + '.bson';
return R.pPipe(
handler.restore.bind(handler),
R.curry(R.flip(mds.dump.fs.file))(tmpfile),
R.curryN(4, mongoRestoreFromFile)(tmpfile, mongoUri, receipt.collection)
)(receipt.data);
});
return q.all(restorePromises).thenResolve('done');
} | [
"function",
"restoreBackup",
"(",
"backupRecord",
",",
"mongoUri",
")",
"{",
"var",
"receipts",
"=",
"backupRecord",
".",
"receipts",
";",
"var",
"handler",
"=",
"getHandler",
"(",
"backupRecord",
".",
"type",
")",
";",
"var",
"restorePromises",
"=",
"receipts",
".",
"map",
"(",
"function",
"(",
"receipt",
")",
"{",
"var",
"tmpfile",
"=",
"util",
".",
"getTempFileName",
"(",
")",
"+",
"'.bson'",
";",
"return",
"R",
".",
"pPipe",
"(",
"handler",
".",
"restore",
".",
"bind",
"(",
"handler",
")",
",",
"R",
".",
"curry",
"(",
"R",
".",
"flip",
"(",
"mds",
".",
"dump",
".",
"fs",
".",
"file",
")",
")",
"(",
"tmpfile",
")",
",",
"R",
".",
"curryN",
"(",
"4",
",",
"mongoRestoreFromFile",
")",
"(",
"tmpfile",
",",
"mongoUri",
",",
"receipt",
".",
"collection",
")",
")",
"(",
"receipt",
".",
"data",
")",
";",
"}",
")",
";",
"return",
"q",
".",
"all",
"(",
"restorePromises",
")",
".",
"thenResolve",
"(",
"'done'",
")",
";",
"}"
] | Consumes a backupRecord produced by createBackup and a mongoUri and restores the information contained in the record to the database described the mongoUri. | [
"Consumes",
"a",
"backupRecord",
"produced",
"by",
"createBackup",
"and",
"a",
"mongoUri",
"and",
"restores",
"the",
"information",
"contained",
"in",
"the",
"record",
"to",
"the",
"database",
"described",
"the",
"mongoUri",
"."
] | 446dfaba7f80c03ae17d86b34dfafd6328be1ba6 | https://github.com/rangle/koast/blob/446dfaba7f80c03ae17d86b34dfafd6328be1ba6/lib/admin-api/backup/backup.js#L104-L118 | train |
radify/angular-model | src/angular-model.js | autoBox | function autoBox(object, model, data) {
if (!object) {
return isArray(data) ? model.collection(data, true) : model.instance(data);
}
if (isArray(data) && isArray(object)) {
return model.collection(data, true);
}
if (data && JSON.stringify(data).length > 3) {
deepExtend(object, data);
object.$original.sync(data);
}
return object;
} | javascript | function autoBox(object, model, data) {
if (!object) {
return isArray(data) ? model.collection(data, true) : model.instance(data);
}
if (isArray(data) && isArray(object)) {
return model.collection(data, true);
}
if (data && JSON.stringify(data).length > 3) {
deepExtend(object, data);
object.$original.sync(data);
}
return object;
} | [
"function",
"autoBox",
"(",
"object",
",",
"model",
",",
"data",
")",
"{",
"if",
"(",
"!",
"object",
")",
"{",
"return",
"isArray",
"(",
"data",
")",
"?",
"model",
".",
"collection",
"(",
"data",
",",
"true",
")",
":",
"model",
".",
"instance",
"(",
"data",
")",
";",
"}",
"if",
"(",
"isArray",
"(",
"data",
")",
"&&",
"isArray",
"(",
"object",
")",
")",
"{",
"return",
"model",
".",
"collection",
"(",
"data",
",",
"true",
")",
";",
"}",
"if",
"(",
"data",
"&&",
"JSON",
".",
"stringify",
"(",
"data",
")",
".",
"length",
">",
"3",
")",
"{",
"deepExtend",
"(",
"object",
",",
"data",
")",
";",
"object",
".",
"$original",
".",
"sync",
"(",
"data",
")",
";",
"}",
"return",
"object",
";",
"}"
] | 'Box' an object value in a model instance if it is present. Otherwise, return an empty model object. | [
"Box",
"an",
"object",
"value",
"in",
"a",
"model",
"instance",
"if",
"it",
"is",
"present",
".",
"Otherwise",
"return",
"an",
"empty",
"model",
"object",
"."
] | e7afc0e4ca1504195adb63578d0290fc8f7af683 | https://github.com/radify/angular-model/blob/e7afc0e4ca1504195adb63578d0290fc8f7af683/src/angular-model.js#L118-L130 | train |
radify/angular-model | src/angular-model.js | function(object) {
if (object instanceof ModelClass) {
return object.url();
}
if (object instanceof ModelInstance || isFunc(object.$model)) {
var model = object.$model();
return expr(object, model.$config().identity + '.href').get() || model.url();
}
throw new Error('Could not get URL for ' + typeof object);
} | javascript | function(object) {
if (object instanceof ModelClass) {
return object.url();
}
if (object instanceof ModelInstance || isFunc(object.$model)) {
var model = object.$model();
return expr(object, model.$config().identity + '.href').get() || model.url();
}
throw new Error('Could not get URL for ' + typeof object);
} | [
"function",
"(",
"object",
")",
"{",
"if",
"(",
"object",
"instanceof",
"ModelClass",
")",
"{",
"return",
"object",
".",
"url",
"(",
")",
";",
"}",
"if",
"(",
"object",
"instanceof",
"ModelInstance",
"||",
"isFunc",
"(",
"object",
".",
"$model",
")",
")",
"{",
"var",
"model",
"=",
"object",
".",
"$model",
"(",
")",
";",
"return",
"expr",
"(",
"object",
",",
"model",
".",
"$config",
"(",
")",
".",
"identity",
"+",
"'.href'",
")",
".",
"get",
"(",
")",
"||",
"model",
".",
"url",
"(",
")",
";",
"}",
"throw",
"new",
"Error",
"(",
"'Could not get URL for '",
"+",
"typeof",
"object",
")",
";",
"}"
] | Extract URL from object, or use default URL | [
"Extract",
"URL",
"from",
"object",
"or",
"use",
"default",
"URL"
] | e7afc0e4ca1504195adb63578d0290fc8f7af683 | https://github.com/radify/angular-model/blob/e7afc0e4ca1504195adb63578d0290fc8f7af683/src/angular-model.js#L139-L148 | train |
|
radify/angular-model | src/angular-model.js | config | function config(name, options) {
if (isObject(name)) {
extend(global, name);
return;
}
var previous = (registry[name] && registry[name].$config) ? registry[name].$config() : null,
base = extend({}, previous ? extend({}, previous) : extend({}, DEFAULTS, DEFAULT_METHODS));
options = deepExtend(copy(base), options);
if (!options.url) {
options.url = global.base.replace(/\/$/, '') + '/' + hyphenate(name);
}
registry[name] = new ModelClass(options);
} | javascript | function config(name, options) {
if (isObject(name)) {
extend(global, name);
return;
}
var previous = (registry[name] && registry[name].$config) ? registry[name].$config() : null,
base = extend({}, previous ? extend({}, previous) : extend({}, DEFAULTS, DEFAULT_METHODS));
options = deepExtend(copy(base), options);
if (!options.url) {
options.url = global.base.replace(/\/$/, '') + '/' + hyphenate(name);
}
registry[name] = new ModelClass(options);
} | [
"function",
"config",
"(",
"name",
",",
"options",
")",
"{",
"if",
"(",
"isObject",
"(",
"name",
")",
")",
"{",
"extend",
"(",
"global",
",",
"name",
")",
";",
"return",
";",
"}",
"var",
"previous",
"=",
"(",
"registry",
"[",
"name",
"]",
"&&",
"registry",
"[",
"name",
"]",
".",
"$config",
")",
"?",
"registry",
"[",
"name",
"]",
".",
"$config",
"(",
")",
":",
"null",
",",
"base",
"=",
"extend",
"(",
"{",
"}",
",",
"previous",
"?",
"extend",
"(",
"{",
"}",
",",
"previous",
")",
":",
"extend",
"(",
"{",
"}",
",",
"DEFAULTS",
",",
"DEFAULT_METHODS",
")",
")",
";",
"options",
"=",
"deepExtend",
"(",
"copy",
"(",
"base",
")",
",",
"options",
")",
";",
"if",
"(",
"!",
"options",
".",
"url",
")",
"{",
"options",
".",
"url",
"=",
"global",
".",
"base",
".",
"replace",
"(",
"/",
"\\/$",
"/",
",",
"''",
")",
"+",
"'/'",
"+",
"hyphenate",
"(",
"name",
")",
";",
"}",
"registry",
"[",
"name",
"]",
"=",
"new",
"ModelClass",
"(",
"options",
")",
";",
"}"
] | Configures a new model, updates an existing model's settings, or updates global settings | [
"Configures",
"a",
"new",
"model",
"updates",
"an",
"existing",
"model",
"s",
"settings",
"or",
"updates",
"global",
"settings"
] | e7afc0e4ca1504195adb63578d0290fc8f7af683 | https://github.com/radify/angular-model/blob/e7afc0e4ca1504195adb63578d0290fc8f7af683/src/angular-model.js#L588-L602 | train |
radify/angular-model | src/angular-model.js | ModelClassFactory | function ModelClassFactory(name, options) {
if (!isUndef(options)) {
return config(name, options);
}
return registry[name] || undefined;
} | javascript | function ModelClassFactory(name, options) {
if (!isUndef(options)) {
return config(name, options);
}
return registry[name] || undefined;
} | [
"function",
"ModelClassFactory",
"(",
"name",
",",
"options",
")",
"{",
"if",
"(",
"!",
"isUndef",
"(",
"options",
")",
")",
"{",
"return",
"config",
"(",
"name",
",",
"options",
")",
";",
"}",
"return",
"registry",
"[",
"name",
"]",
"||",
"undefined",
";",
"}"
] | Adds, gets, or updates a named model configuration | [
"Adds",
"gets",
"or",
"updates",
"a",
"named",
"model",
"configuration"
] | e7afc0e4ca1504195adb63578d0290fc8f7af683 | https://github.com/radify/angular-model/blob/e7afc0e4ca1504195adb63578d0290fc8f7af683/src/angular-model.js#L664-L669 | train |
soajs/soajs.core.drivers | infra/aws/cluster/lb.js | function (options, mCb) {
const aws = options.infra.api;
getElbMethod(options.params.elbType || 'classic', 'list', (elbResponse) => {
const elb = getConnector({
api: elbResponse.api,
region: options.params.region,
keyId: aws.keyId,
secretAccessKey: aws.secretAccessKey
});
const ec2 = getConnector({
api: 'ec2',
region: options.params.region,
keyId: aws.keyId,
secretAccessKey: aws.secretAccessKey
});
elb[elbResponse.method]({}, function (err, response) {
if (err) {
return mCb(err);
}
async.map(response.LoadBalancerDescriptions, function (lb, callback) {
async.parallel({
subnets: function (callback) {
if (lb && lb.Subnets && Array.isArray(lb.Subnets) && lb.Subnets.length > 0) {
let sParams = {SubnetIds: lb.Subnets};
ec2.describeSubnets(sParams, callback);
}
else {
return callback(null, null);
}
},
instances: function (callback) {
let iParams = {LoadBalancerName: lb.LoadBalancerName};
elb.describeInstanceHealth(iParams, callback);
}
}, function (err, results) {
return callback(err, helper[elbResponse.helper]({
lb,
region: options.params.region,
subnets: results.subnets ? results.subnets.Subnets : [],
instances: results.instances ? results.instances.InstanceStates : []
}));
});
}, mCb);
});
});
} | javascript | function (options, mCb) {
const aws = options.infra.api;
getElbMethod(options.params.elbType || 'classic', 'list', (elbResponse) => {
const elb = getConnector({
api: elbResponse.api,
region: options.params.region,
keyId: aws.keyId,
secretAccessKey: aws.secretAccessKey
});
const ec2 = getConnector({
api: 'ec2',
region: options.params.region,
keyId: aws.keyId,
secretAccessKey: aws.secretAccessKey
});
elb[elbResponse.method]({}, function (err, response) {
if (err) {
return mCb(err);
}
async.map(response.LoadBalancerDescriptions, function (lb, callback) {
async.parallel({
subnets: function (callback) {
if (lb && lb.Subnets && Array.isArray(lb.Subnets) && lb.Subnets.length > 0) {
let sParams = {SubnetIds: lb.Subnets};
ec2.describeSubnets(sParams, callback);
}
else {
return callback(null, null);
}
},
instances: function (callback) {
let iParams = {LoadBalancerName: lb.LoadBalancerName};
elb.describeInstanceHealth(iParams, callback);
}
}, function (err, results) {
return callback(err, helper[elbResponse.helper]({
lb,
region: options.params.region,
subnets: results.subnets ? results.subnets.Subnets : [],
instances: results.instances ? results.instances.InstanceStates : []
}));
});
}, mCb);
});
});
} | [
"function",
"(",
"options",
",",
"mCb",
")",
"{",
"const",
"aws",
"=",
"options",
".",
"infra",
".",
"api",
";",
"getElbMethod",
"(",
"options",
".",
"params",
".",
"elbType",
"||",
"'classic'",
",",
"'list'",
",",
"(",
"elbResponse",
")",
"=>",
"{",
"const",
"elb",
"=",
"getConnector",
"(",
"{",
"api",
":",
"elbResponse",
".",
"api",
",",
"region",
":",
"options",
".",
"params",
".",
"region",
",",
"keyId",
":",
"aws",
".",
"keyId",
",",
"secretAccessKey",
":",
"aws",
".",
"secretAccessKey",
"}",
")",
";",
"const",
"ec2",
"=",
"getConnector",
"(",
"{",
"api",
":",
"'ec2'",
",",
"region",
":",
"options",
".",
"params",
".",
"region",
",",
"keyId",
":",
"aws",
".",
"keyId",
",",
"secretAccessKey",
":",
"aws",
".",
"secretAccessKey",
"}",
")",
";",
"elb",
"[",
"elbResponse",
".",
"method",
"]",
"(",
"{",
"}",
",",
"function",
"(",
"err",
",",
"response",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"mCb",
"(",
"err",
")",
";",
"}",
"async",
".",
"map",
"(",
"response",
".",
"LoadBalancerDescriptions",
",",
"function",
"(",
"lb",
",",
"callback",
")",
"{",
"async",
".",
"parallel",
"(",
"{",
"subnets",
":",
"function",
"(",
"callback",
")",
"{",
"if",
"(",
"lb",
"&&",
"lb",
".",
"Subnets",
"&&",
"Array",
".",
"isArray",
"(",
"lb",
".",
"Subnets",
")",
"&&",
"lb",
".",
"Subnets",
".",
"length",
">",
"0",
")",
"{",
"let",
"sParams",
"=",
"{",
"SubnetIds",
":",
"lb",
".",
"Subnets",
"}",
";",
"ec2",
".",
"describeSubnets",
"(",
"sParams",
",",
"callback",
")",
";",
"}",
"else",
"{",
"return",
"callback",
"(",
"null",
",",
"null",
")",
";",
"}",
"}",
",",
"instances",
":",
"function",
"(",
"callback",
")",
"{",
"let",
"iParams",
"=",
"{",
"LoadBalancerName",
":",
"lb",
".",
"LoadBalancerName",
"}",
";",
"elb",
".",
"describeInstanceHealth",
"(",
"iParams",
",",
"callback",
")",
";",
"}",
"}",
",",
"function",
"(",
"err",
",",
"results",
")",
"{",
"return",
"callback",
"(",
"err",
",",
"helper",
"[",
"elbResponse",
".",
"helper",
"]",
"(",
"{",
"lb",
",",
"region",
":",
"options",
".",
"params",
".",
"region",
",",
"subnets",
":",
"results",
".",
"subnets",
"?",
"results",
".",
"subnets",
".",
"Subnets",
":",
"[",
"]",
",",
"instances",
":",
"results",
".",
"instances",
"?",
"results",
".",
"instances",
".",
"InstanceStates",
":",
"[",
"]",
"}",
")",
")",
";",
"}",
")",
";",
"}",
",",
"mCb",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | This method return a list of Load Balancers
@param options
@param mCb | [
"This",
"method",
"return",
"a",
"list",
"of",
"Load",
"Balancers"
] | 545891509a47e16d9d2f40515e81bb1f4f3d8165 | https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/aws/cluster/lb.js#L50-L95 | train |
|
soajs/soajs.core.drivers | infra/aws/cluster/lb.js | function (options, mCb) {
getElbMethod(options.params.elbType || 'classic', 'delete', (elbResponse) => {
const aws = options.infra.api;
const elb = getConnector({
api: elbResponse.api,
region: options.params.region,
keyId: aws.keyId,
secretAccessKey: aws.secretAccessKey
});
let params = {
LoadBalancerName: options.params.name
};
options.soajs.log.debug(params);
elb[elbResponse.method](params, mCb);
});
} | javascript | function (options, mCb) {
getElbMethod(options.params.elbType || 'classic', 'delete', (elbResponse) => {
const aws = options.infra.api;
const elb = getConnector({
api: elbResponse.api,
region: options.params.region,
keyId: aws.keyId,
secretAccessKey: aws.secretAccessKey
});
let params = {
LoadBalancerName: options.params.name
};
options.soajs.log.debug(params);
elb[elbResponse.method](params, mCb);
});
} | [
"function",
"(",
"options",
",",
"mCb",
")",
"{",
"getElbMethod",
"(",
"options",
".",
"params",
".",
"elbType",
"||",
"'classic'",
",",
"'delete'",
",",
"(",
"elbResponse",
")",
"=>",
"{",
"const",
"aws",
"=",
"options",
".",
"infra",
".",
"api",
";",
"const",
"elb",
"=",
"getConnector",
"(",
"{",
"api",
":",
"elbResponse",
".",
"api",
",",
"region",
":",
"options",
".",
"params",
".",
"region",
",",
"keyId",
":",
"aws",
".",
"keyId",
",",
"secretAccessKey",
":",
"aws",
".",
"secretAccessKey",
"}",
")",
";",
"let",
"params",
"=",
"{",
"LoadBalancerName",
":",
"options",
".",
"params",
".",
"name",
"}",
";",
"options",
".",
"soajs",
".",
"log",
".",
"debug",
"(",
"params",
")",
";",
"elb",
"[",
"elbResponse",
".",
"method",
"]",
"(",
"params",
",",
"mCb",
")",
";",
"}",
")",
";",
"}"
] | This method deletes a load balancer
@param options
@param mCb
@returns {*} | [
"This",
"method",
"deletes",
"a",
"load",
"balancer"
] | 545891509a47e16d9d2f40515e81bb1f4f3d8165 | https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/aws/cluster/lb.js#L850-L865 | train |
|
suguru/node-stat | plugins/stat.js | initcpurow | function initcpurow() {
return {
user: 0,
nice: 0,
system: 0,
iowait: 0,
idle: 0,
irq: 0,
softirq: 0,
steal: 0,
guest: 0,
guest_nice: 0
};
} | javascript | function initcpurow() {
return {
user: 0,
nice: 0,
system: 0,
iowait: 0,
idle: 0,
irq: 0,
softirq: 0,
steal: 0,
guest: 0,
guest_nice: 0
};
} | [
"function",
"initcpurow",
"(",
")",
"{",
"return",
"{",
"user",
":",
"0",
",",
"nice",
":",
"0",
",",
"system",
":",
"0",
",",
"iowait",
":",
"0",
",",
"idle",
":",
"0",
",",
"irq",
":",
"0",
",",
"softirq",
":",
"0",
",",
"steal",
":",
"0",
",",
"guest",
":",
"0",
",",
"guest_nice",
":",
"0",
"}",
";",
"}"
] | init cpu row | [
"init",
"cpu",
"row"
] | 0e8eb98307e7cb1bb735a46b82b08b3530660b4f | https://github.com/suguru/node-stat/blob/0e8eb98307e7cb1bb735a46b82b08b3530660b4f/plugins/stat.js#L32-L45 | train |
profitbricks/profitbricks-sdk-nodejs | examples/findserverbyname.js | findname | function findname(error, response, body) {
if (error){
return error
}
if (body){
try{
var info = JSON.parse(body)
}
catch(err){
console.log(body)
return
}
if (info.items){
var ilen=info.items.length
while(ilen--){
var it=info.items[ilen]
var thename=it['properties']['name']
if (thename.match(srchfor)){
console.log(it) // <---- print json for server(s) that match srchfor
}
}
}
}
} | javascript | function findname(error, response, body) {
if (error){
return error
}
if (body){
try{
var info = JSON.parse(body)
}
catch(err){
console.log(body)
return
}
if (info.items){
var ilen=info.items.length
while(ilen--){
var it=info.items[ilen]
var thename=it['properties']['name']
if (thename.match(srchfor)){
console.log(it) // <---- print json for server(s) that match srchfor
}
}
}
}
} | [
"function",
"findname",
"(",
"error",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"error",
"}",
"if",
"(",
"body",
")",
"{",
"try",
"{",
"var",
"info",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"body",
")",
"return",
"}",
"if",
"(",
"info",
".",
"items",
")",
"{",
"var",
"ilen",
"=",
"info",
".",
"items",
".",
"length",
"while",
"(",
"ilen",
"--",
")",
"{",
"var",
"it",
"=",
"info",
".",
"items",
"[",
"ilen",
"]",
"var",
"thename",
"=",
"it",
"[",
"'properties'",
"]",
"[",
"'name'",
"]",
"if",
"(",
"thename",
".",
"match",
"(",
"srchfor",
")",
")",
"{",
"console",
".",
"log",
"(",
"it",
")",
"}",
"}",
"}",
"}",
"}"
] | findname will be our callback | [
"findname",
"will",
"be",
"our",
"callback"
] | 861ff9daf7a30cfb84b2be0a02fed67369fea964 | https://github.com/profitbricks/profitbricks-sdk-nodejs/blob/861ff9daf7a30cfb84b2be0a02fed67369fea964/examples/findserverbyname.js#L19-L42 | train |
bigpipe/temper | index.js | Temper | function Temper(options) {
if (!this) return new Temper(options);
options = options || {};
//
// We only want to cache the templates in production as it's so we can easily
// change templates when we're developing.
//
options.cache = 'cache' in options
? options.cache
: process.env.NODE_ENV !== 'production';
this.installed = Object.create(null); // Installed module for extension cache.
this.required = Object.create(null); // Template engine require cache.
this.compiled = Object.create(null); // Compiled template cache.
this.timers = new TickTock(this); // Keep track of timeouts.
this.file = Object.create(null); // File lookup cache.
this.cache = options.cache; // Cache compiled templates.
} | javascript | function Temper(options) {
if (!this) return new Temper(options);
options = options || {};
//
// We only want to cache the templates in production as it's so we can easily
// change templates when we're developing.
//
options.cache = 'cache' in options
? options.cache
: process.env.NODE_ENV !== 'production';
this.installed = Object.create(null); // Installed module for extension cache.
this.required = Object.create(null); // Template engine require cache.
this.compiled = Object.create(null); // Compiled template cache.
this.timers = new TickTock(this); // Keep track of timeouts.
this.file = Object.create(null); // File lookup cache.
this.cache = options.cache; // Cache compiled templates.
} | [
"function",
"Temper",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"this",
")",
"return",
"new",
"Temper",
"(",
"options",
")",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"options",
".",
"cache",
"=",
"'cache'",
"in",
"options",
"?",
"options",
".",
"cache",
":",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
";",
"this",
".",
"installed",
"=",
"Object",
".",
"create",
"(",
"null",
")",
";",
"this",
".",
"required",
"=",
"Object",
".",
"create",
"(",
"null",
")",
";",
"this",
".",
"compiled",
"=",
"Object",
".",
"create",
"(",
"null",
")",
";",
"this",
".",
"timers",
"=",
"new",
"TickTock",
"(",
"this",
")",
";",
"this",
".",
"file",
"=",
"Object",
".",
"create",
"(",
"null",
")",
";",
"this",
".",
"cache",
"=",
"options",
".",
"cache",
";",
"}"
] | Temper compiles templates to client-side compatible templates as well as it's
server side equivalents.
@constructor
@param {Object} options Temper configuration.
@api public | [
"Temper",
"compiles",
"templates",
"to",
"client",
"-",
"side",
"compatible",
"templates",
"as",
"well",
"as",
"it",
"s",
"server",
"side",
"equivalents",
"."
] | a658d4a0e96d2cf5f001768ed36dd90d2adb8183 | https://github.com/bigpipe/temper/blob/a658d4a0e96d2cf5f001768ed36dd90d2adb8183/index.js#L18-L36 | train |
bem-contrib/md-to-bemjson | packages/remark-bemjson/lib/index.js | plugin | function plugin(options) {
options = defaultsDeep({}, options, defaults);
this.Compiler = compiler;
function compiler(node, file) {
const root = node && node.type && node.type === 'root';
const bemjson = toBemjson(node, { augment: options.augment });
const bjsonString = options.export ? JSON.stringify(bemjson, null, 4) : '';
if (file.extname) {
file.extname = '.js';
}
if (file.stem) {
file.stem = file.stem + '.bemjson';
}
file.data = bemjson;
return root ? createExport({ type: options.exportType, name: options.exportName }, bjsonString) : bjsonString;
}
} | javascript | function plugin(options) {
options = defaultsDeep({}, options, defaults);
this.Compiler = compiler;
function compiler(node, file) {
const root = node && node.type && node.type === 'root';
const bemjson = toBemjson(node, { augment: options.augment });
const bjsonString = options.export ? JSON.stringify(bemjson, null, 4) : '';
if (file.extname) {
file.extname = '.js';
}
if (file.stem) {
file.stem = file.stem + '.bemjson';
}
file.data = bemjson;
return root ? createExport({ type: options.exportType, name: options.exportName }, bjsonString) : bjsonString;
}
} | [
"function",
"plugin",
"(",
"options",
")",
"{",
"options",
"=",
"defaultsDeep",
"(",
"{",
"}",
",",
"options",
",",
"defaults",
")",
";",
"this",
".",
"Compiler",
"=",
"compiler",
";",
"function",
"compiler",
"(",
"node",
",",
"file",
")",
"{",
"const",
"root",
"=",
"node",
"&&",
"node",
".",
"type",
"&&",
"node",
".",
"type",
"===",
"'root'",
";",
"const",
"bemjson",
"=",
"toBemjson",
"(",
"node",
",",
"{",
"augment",
":",
"options",
".",
"augment",
"}",
")",
";",
"const",
"bjsonString",
"=",
"options",
".",
"export",
"?",
"JSON",
".",
"stringify",
"(",
"bemjson",
",",
"null",
",",
"4",
")",
":",
"''",
";",
"if",
"(",
"file",
".",
"extname",
")",
"{",
"file",
".",
"extname",
"=",
"'.js'",
";",
"}",
"if",
"(",
"file",
".",
"stem",
")",
"{",
"file",
".",
"stem",
"=",
"file",
".",
"stem",
"+",
"'.bemjson'",
";",
"}",
"file",
".",
"data",
"=",
"bemjson",
";",
"return",
"root",
"?",
"createExport",
"(",
"{",
"type",
":",
"options",
".",
"exportType",
",",
"name",
":",
"options",
".",
"exportName",
"}",
",",
"bjsonString",
")",
":",
"bjsonString",
";",
"}",
"}"
] | remark bemjson compiler plugin
@param {Object} options - plugin options
@param {ExportType} [options.exportType=commonJS] - export type.
@param {string} [options.exportName] - if export to browser requires name.
@param {Function} [options.augment] - transform callback. | [
"remark",
"bemjson",
"compiler",
"plugin"
] | 047ab80c681073c7c92aecee754bcf46956507a9 | https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/remark-bemjson/lib/index.js#L17-L40 | train |
rangle/koast | lib/authentication/authentication.js | handleLogin | function handleLogin(user, req, res, next) {
var token;
var profile;
var tokenExpiresInMinutes;
var envelope = {
data: user,
isAuthenticated: true,
meta: {}
};
// First handle the case where the user was not logged in.
if (!user) {
if (authConfig.maintenance === 'cookie') {
req.logout();
}
return res.status(401).send('Wrong password or no such user.');
}
// user_id is how it is in the schema
/* jshint ignore:start */
// Now handle the case where we did get a user record.
if (authConfig.maintenance === 'token') {
// For token authentication we want to add a token.
profile = {
username: user.username,
email: user.email,
userdata_id: user.userdata_id
};
/* jshint ignore:end */
tokenExpiresInMinutes = authConfig.expiresInMinutes || 60;
envelope.meta.token = generateToken(profile, tokenExpiresInMinutes,
secrets.authTokenSecret);
envelope.meta.expires = getExpirationTime(tokenExpiresInMinutes);
return res.status(200).send(envelope);
} else if (authConfig.maintenance === 'cookie') {
// For cookie authentication we want to login the user.
req.login(user, function (err) {
if (err) {
return next(err);
} else {
return res.status(200).send(envelope);
}
});
}
} | javascript | function handleLogin(user, req, res, next) {
var token;
var profile;
var tokenExpiresInMinutes;
var envelope = {
data: user,
isAuthenticated: true,
meta: {}
};
// First handle the case where the user was not logged in.
if (!user) {
if (authConfig.maintenance === 'cookie') {
req.logout();
}
return res.status(401).send('Wrong password or no such user.');
}
// user_id is how it is in the schema
/* jshint ignore:start */
// Now handle the case where we did get a user record.
if (authConfig.maintenance === 'token') {
// For token authentication we want to add a token.
profile = {
username: user.username,
email: user.email,
userdata_id: user.userdata_id
};
/* jshint ignore:end */
tokenExpiresInMinutes = authConfig.expiresInMinutes || 60;
envelope.meta.token = generateToken(profile, tokenExpiresInMinutes,
secrets.authTokenSecret);
envelope.meta.expires = getExpirationTime(tokenExpiresInMinutes);
return res.status(200).send(envelope);
} else if (authConfig.maintenance === 'cookie') {
// For cookie authentication we want to login the user.
req.login(user, function (err) {
if (err) {
return next(err);
} else {
return res.status(200).send(envelope);
}
});
}
} | [
"function",
"handleLogin",
"(",
"user",
",",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"token",
";",
"var",
"profile",
";",
"var",
"tokenExpiresInMinutes",
";",
"var",
"envelope",
"=",
"{",
"data",
":",
"user",
",",
"isAuthenticated",
":",
"true",
",",
"meta",
":",
"{",
"}",
"}",
";",
"if",
"(",
"!",
"user",
")",
"{",
"if",
"(",
"authConfig",
".",
"maintenance",
"===",
"'cookie'",
")",
"{",
"req",
".",
"logout",
"(",
")",
";",
"}",
"return",
"res",
".",
"status",
"(",
"401",
")",
".",
"send",
"(",
"'Wrong password or no such user.'",
")",
";",
"}",
"if",
"(",
"authConfig",
".",
"maintenance",
"===",
"'token'",
")",
"{",
"profile",
"=",
"{",
"username",
":",
"user",
".",
"username",
",",
"email",
":",
"user",
".",
"email",
",",
"userdata_id",
":",
"user",
".",
"userdata_id",
"}",
";",
"tokenExpiresInMinutes",
"=",
"authConfig",
".",
"expiresInMinutes",
"||",
"60",
";",
"envelope",
".",
"meta",
".",
"token",
"=",
"generateToken",
"(",
"profile",
",",
"tokenExpiresInMinutes",
",",
"secrets",
".",
"authTokenSecret",
")",
";",
"envelope",
".",
"meta",
".",
"expires",
"=",
"getExpirationTime",
"(",
"tokenExpiresInMinutes",
")",
";",
"return",
"res",
".",
"status",
"(",
"200",
")",
".",
"send",
"(",
"envelope",
")",
";",
"}",
"else",
"if",
"(",
"authConfig",
".",
"maintenance",
"===",
"'cookie'",
")",
"{",
"req",
".",
"login",
"(",
"user",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
";",
"}",
"else",
"{",
"return",
"res",
".",
"status",
"(",
"200",
")",
".",
"send",
"(",
"envelope",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] | depends on auth config | [
"depends",
"on",
"auth",
"config"
] | 446dfaba7f80c03ae17d86b34dfafd6328be1ba6 | https://github.com/rangle/koast/blob/446dfaba7f80c03ae17d86b34dfafd6328be1ba6/lib/authentication/authentication.js#L86-L132 | train |
IonicaBizau/deffy | lib/index.js | Deffy | function Deffy(input, def, options) {
// Default is a function
if (typeof def === "function") {
return def(input);
}
options = Typpy(options) === "boolean" ? {
empty: options
} : {
empty: false
};
// Handle empty
if (options.empty) {
return input || def;
}
// Return input
if (Typpy(input) === Typpy(def)) {
return input;
}
// Return the default
return def;
} | javascript | function Deffy(input, def, options) {
// Default is a function
if (typeof def === "function") {
return def(input);
}
options = Typpy(options) === "boolean" ? {
empty: options
} : {
empty: false
};
// Handle empty
if (options.empty) {
return input || def;
}
// Return input
if (Typpy(input) === Typpy(def)) {
return input;
}
// Return the default
return def;
} | [
"function",
"Deffy",
"(",
"input",
",",
"def",
",",
"options",
")",
"{",
"if",
"(",
"typeof",
"def",
"===",
"\"function\"",
")",
"{",
"return",
"def",
"(",
"input",
")",
";",
"}",
"options",
"=",
"Typpy",
"(",
"options",
")",
"===",
"\"boolean\"",
"?",
"{",
"empty",
":",
"options",
"}",
":",
"{",
"empty",
":",
"false",
"}",
";",
"if",
"(",
"options",
".",
"empty",
")",
"{",
"return",
"input",
"||",
"def",
";",
"}",
"if",
"(",
"Typpy",
"(",
"input",
")",
"===",
"Typpy",
"(",
"def",
")",
")",
"{",
"return",
"input",
";",
"}",
"return",
"def",
";",
"}"
] | Deffy
Computes a final value by providing the input and default values.
@name Deffy
@function
@param {Anything} input The input value.
@param {Anything|Function} def The default value or a function getting the
input value as first argument.
@param {Object|Boolean} options The `empty` value or an object containing
the following fields:
- `empty` (Boolean): Handles the input value as empty field (`input || default`). Default is `false`.
@return {Anything} The computed value. | [
"Deffy",
"Computes",
"a",
"final",
"value",
"by",
"providing",
"the",
"input",
"and",
"default",
"values",
"."
] | 979c50f40c07d00e6456ef2568344723d7b39042 | https://github.com/IonicaBizau/deffy/blob/979c50f40c07d00e6456ef2568344723d7b39042/lib/index.js#L20-L45 | train |
fnogatz/transportation | lib/list.js | generateRandomId | function generateRandomId (length) {
var str = ''
length = length || 6
while (str.length < length) {
str += (((1 + Math.random()) * 0x10000) | 0).toString(16)
}
return str.substring(str.length - length, str.length)
} | javascript | function generateRandomId (length) {
var str = ''
length = length || 6
while (str.length < length) {
str += (((1 + Math.random()) * 0x10000) | 0).toString(16)
}
return str.substring(str.length - length, str.length)
} | [
"function",
"generateRandomId",
"(",
"length",
")",
"{",
"var",
"str",
"=",
"''",
"length",
"=",
"length",
"||",
"6",
"while",
"(",
"str",
".",
"length",
"<",
"length",
")",
"{",
"str",
"+=",
"(",
"(",
"(",
"1",
"+",
"Math",
".",
"random",
"(",
")",
")",
"*",
"0x10000",
")",
"|",
"0",
")",
".",
"toString",
"(",
"16",
")",
"}",
"return",
"str",
".",
"substring",
"(",
"str",
".",
"length",
"-",
"length",
",",
"str",
".",
"length",
")",
"}"
] | Generate an alphanumeric ID with the given length.
@param {Integer} length
@return {String} ID | [
"Generate",
"an",
"alphanumeric",
"ID",
"with",
"the",
"given",
"length",
"."
] | 4d967d99bc564827ee3c4c122c967dc65d947874 | https://github.com/fnogatz/transportation/blob/4d967d99bc564827ee3c4c122c967dc65d947874/lib/list.js#L165-L172 | train |
gbv/jskos-tools | lib/object-types.js | guessObjectType | function guessObjectType(obj, shortname=false) {
var type
if (typeof obj === "string" && obj) {
if (obj in objectTypeUris) {
// given by URI
type = objectTypeUris[obj]
} else {
// given by name
obj = obj.toLowerCase().replace(/s$/,"")
type = Object.keys(objectTypes).find(name => {
const lowercase = name.toLowerCase()
if (lowercase === obj || lowercase === "concept" + obj) {
return true
}
})
}
} else if (typeof obj === "object") {
if (obj.type) {
let types = Array.isArray(obj.type) ? obj.type : [obj.type]
for (let uri of types) {
if (uri in objectTypeUris) {
type = objectTypeUris[uri]
break
}
}
}
}
return (shortname && type) ? type.toLowerCase().replace(/^concept(.+)/, "$1") : type
} | javascript | function guessObjectType(obj, shortname=false) {
var type
if (typeof obj === "string" && obj) {
if (obj in objectTypeUris) {
// given by URI
type = objectTypeUris[obj]
} else {
// given by name
obj = obj.toLowerCase().replace(/s$/,"")
type = Object.keys(objectTypes).find(name => {
const lowercase = name.toLowerCase()
if (lowercase === obj || lowercase === "concept" + obj) {
return true
}
})
}
} else if (typeof obj === "object") {
if (obj.type) {
let types = Array.isArray(obj.type) ? obj.type : [obj.type]
for (let uri of types) {
if (uri in objectTypeUris) {
type = objectTypeUris[uri]
break
}
}
}
}
return (shortname && type) ? type.toLowerCase().replace(/^concept(.+)/, "$1") : type
} | [
"function",
"guessObjectType",
"(",
"obj",
",",
"shortname",
"=",
"false",
")",
"{",
"var",
"type",
"if",
"(",
"typeof",
"obj",
"===",
"\"string\"",
"&&",
"obj",
")",
"{",
"if",
"(",
"obj",
"in",
"objectTypeUris",
")",
"{",
"type",
"=",
"objectTypeUris",
"[",
"obj",
"]",
"}",
"else",
"{",
"obj",
"=",
"obj",
".",
"toLowerCase",
"(",
")",
".",
"replace",
"(",
"/",
"s$",
"/",
",",
"\"\"",
")",
"type",
"=",
"Object",
".",
"keys",
"(",
"objectTypes",
")",
".",
"find",
"(",
"name",
"=>",
"{",
"const",
"lowercase",
"=",
"name",
".",
"toLowerCase",
"(",
")",
"if",
"(",
"lowercase",
"===",
"obj",
"||",
"lowercase",
"===",
"\"concept\"",
"+",
"obj",
")",
"{",
"return",
"true",
"}",
"}",
")",
"}",
"}",
"else",
"if",
"(",
"typeof",
"obj",
"===",
"\"object\"",
")",
"{",
"if",
"(",
"obj",
".",
"type",
")",
"{",
"let",
"types",
"=",
"Array",
".",
"isArray",
"(",
"obj",
".",
"type",
")",
"?",
"obj",
".",
"type",
":",
"[",
"obj",
".",
"type",
"]",
"for",
"(",
"let",
"uri",
"of",
"types",
")",
"{",
"if",
"(",
"uri",
"in",
"objectTypeUris",
")",
"{",
"type",
"=",
"objectTypeUris",
"[",
"uri",
"]",
"break",
"}",
"}",
"}",
"}",
"return",
"(",
"shortname",
"&&",
"type",
")",
"?",
"type",
".",
"toLowerCase",
"(",
")",
".",
"replace",
"(",
"/",
"^concept(.+)",
"/",
",",
"\"$1\"",
")",
":",
"type",
"}"
] | Guess the JSKOS Concept Type name from an object or name.
@memberof module:jskos-tools
@param {object|string} jskos|name|uri object or string to guess from
@param {boolean} shortname return short name if enabled (false by default) | [
"Guess",
"the",
"JSKOS",
"Concept",
"Type",
"name",
"from",
"an",
"object",
"or",
"name",
"."
] | da8672203362ea874f4ab9cdd34b990369987075 | https://github.com/gbv/jskos-tools/blob/da8672203362ea874f4ab9cdd34b990369987075/lib/object-types.js#L62-L90 | train |
storj/mongodb-adapter | lib/adapter.js | MongoAdapter | function MongoAdapter(mongooseConnection) {
if (!(this instanceof MongoAdapter)) {
return new MongoAdapter(mongooseConnection);
}
storj.StorageAdapter.call(this);
if (mongooseConnection instanceof Storage) {
this._model = mongooseConnection.models.Shard;
} else {
this._model = Shard(mongooseConnection);
}
} | javascript | function MongoAdapter(mongooseConnection) {
if (!(this instanceof MongoAdapter)) {
return new MongoAdapter(mongooseConnection);
}
storj.StorageAdapter.call(this);
if (mongooseConnection instanceof Storage) {
this._model = mongooseConnection.models.Shard;
} else {
this._model = Shard(mongooseConnection);
}
} | [
"function",
"MongoAdapter",
"(",
"mongooseConnection",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"MongoAdapter",
")",
")",
"{",
"return",
"new",
"MongoAdapter",
"(",
"mongooseConnection",
")",
";",
"}",
"storj",
".",
"StorageAdapter",
".",
"call",
"(",
"this",
")",
";",
"if",
"(",
"mongooseConnection",
"instanceof",
"Storage",
")",
"{",
"this",
".",
"_model",
"=",
"mongooseConnection",
".",
"models",
".",
"Shard",
";",
"}",
"else",
"{",
"this",
".",
"_model",
"=",
"Shard",
"(",
"mongooseConnection",
")",
";",
"}",
"}"
] | Implements a MongoDB storage adapter for contract and audit management
@constructor
@extends {storj.StorageAdapter}
@param {Storage} mongooseConnection - The connection object from mongoose | [
"Implements",
"a",
"MongoDB",
"storage",
"adapter",
"for",
"contract",
"and",
"audit",
"management"
] | a31dab5c669d9ee7c9c96f2ee094bf28d0f3b1c7 | https://github.com/storj/mongodb-adapter/blob/a31dab5c669d9ee7c9c96f2ee094bf28d0f3b1c7/lib/adapter.js#L17-L29 | train |
fissionjs/fission | lib/util/ensureInstance.js | constructModel | function constructModel(Model, options) {
return construct({
input: Model,
expected: AmpersandModel,
createConstructor: model,
options: options
});
} | javascript | function constructModel(Model, options) {
return construct({
input: Model,
expected: AmpersandModel,
createConstructor: model,
options: options
});
} | [
"function",
"constructModel",
"(",
"Model",
",",
"options",
")",
"{",
"return",
"construct",
"(",
"{",
"input",
":",
"Model",
",",
"expected",
":",
"AmpersandModel",
",",
"createConstructor",
":",
"model",
",",
"options",
":",
"options",
"}",
")",
";",
"}"
] | Model = either a Model constructor, a Model instance, or an object to create a Model constructor options = construction options | [
"Model",
"=",
"either",
"a",
"Model",
"constructor",
"a",
"Model",
"instance",
"or",
"an",
"object",
"to",
"create",
"a",
"Model",
"constructor",
"options",
"=",
"construction",
"options"
] | e34eed78ed2386bb7934a69214e13f17fcd311c3 | https://github.com/fissionjs/fission/blob/e34eed78ed2386bb7934a69214e13f17fcd311c3/lib/util/ensureInstance.js#L68-L75 | train |
fissionjs/fission | lib/util/ensureInstance.js | constructCollection | function constructCollection(Collection, options) {
return construct({
input: Collection,
expected: AmpersandCollection,
createConstructor: collection,
options: options
});
} | javascript | function constructCollection(Collection, options) {
return construct({
input: Collection,
expected: AmpersandCollection,
createConstructor: collection,
options: options
});
} | [
"function",
"constructCollection",
"(",
"Collection",
",",
"options",
")",
"{",
"return",
"construct",
"(",
"{",
"input",
":",
"Collection",
",",
"expected",
":",
"AmpersandCollection",
",",
"createConstructor",
":",
"collection",
",",
"options",
":",
"options",
"}",
")",
";",
"}"
] | Collection = either a Collection constructor, a Collection instance, or an object to create a Collection constructor options = construction options | [
"Collection",
"=",
"either",
"a",
"Collection",
"constructor",
"a",
"Collection",
"instance",
"or",
"an",
"object",
"to",
"create",
"a",
"Collection",
"constructor",
"options",
"=",
"construction",
"options"
] | e34eed78ed2386bb7934a69214e13f17fcd311c3 | https://github.com/fissionjs/fission/blob/e34eed78ed2386bb7934a69214e13f17fcd311c3/lib/util/ensureInstance.js#L80-L87 | train |
soajs/soajs.core.drivers | lib/terraform/index.js | function(options, cb) {
let template, render;
if(!options.params || !options.params.template || !options.params.template.content) {
return utils.checkError('Missing template content', 727, cb);
}
try {
template = handlebars.compile(options.params.template.content);
if(options.params.template._id){
if(!options.params.input.tags){
options.params.input.tags = {};
}
options.params.input.tags['soajs.template.id'] = options.params.template._id.toString();
}
render = template(options.params.input);
}
catch(e) {
return utils.checkError(e, 727, cb);
}
return cb(null, { render });
} | javascript | function(options, cb) {
let template, render;
if(!options.params || !options.params.template || !options.params.template.content) {
return utils.checkError('Missing template content', 727, cb);
}
try {
template = handlebars.compile(options.params.template.content);
if(options.params.template._id){
if(!options.params.input.tags){
options.params.input.tags = {};
}
options.params.input.tags['soajs.template.id'] = options.params.template._id.toString();
}
render = template(options.params.input);
}
catch(e) {
return utils.checkError(e, 727, cb);
}
return cb(null, { render });
} | [
"function",
"(",
"options",
",",
"cb",
")",
"{",
"let",
"template",
",",
"render",
";",
"if",
"(",
"!",
"options",
".",
"params",
"||",
"!",
"options",
".",
"params",
".",
"template",
"||",
"!",
"options",
".",
"params",
".",
"template",
".",
"content",
")",
"{",
"return",
"utils",
".",
"checkError",
"(",
"'Missing template content'",
",",
"727",
",",
"cb",
")",
";",
"}",
"try",
"{",
"template",
"=",
"handlebars",
".",
"compile",
"(",
"options",
".",
"params",
".",
"template",
".",
"content",
")",
";",
"if",
"(",
"options",
".",
"params",
".",
"template",
".",
"_id",
")",
"{",
"if",
"(",
"!",
"options",
".",
"params",
".",
"input",
".",
"tags",
")",
"{",
"options",
".",
"params",
".",
"input",
".",
"tags",
"=",
"{",
"}",
";",
"}",
"options",
".",
"params",
".",
"input",
".",
"tags",
"[",
"'soajs.template.id'",
"]",
"=",
"options",
".",
"params",
".",
"template",
".",
"_id",
".",
"toString",
"(",
")",
";",
"}",
"render",
"=",
"template",
"(",
"options",
".",
"params",
".",
"input",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"utils",
".",
"checkError",
"(",
"e",
",",
"727",
",",
"cb",
")",
";",
"}",
"return",
"cb",
"(",
"null",
",",
"{",
"render",
"}",
")",
";",
"}"
] | Render a terraform dynamic template and return output
@param {Object} options Data passed to function as params
@param {Function} cb Callback function
@return {void} | [
"Render",
"a",
"terraform",
"dynamic",
"template",
"and",
"return",
"output"
] | 545891509a47e16d9d2f40515e81bb1f4f3d8165 | https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/lib/terraform/index.js#L34-L55 | train |
|
Incroud/cassanova | lib/schemaType.js | SchemaType | function SchemaType(type, validation, wrapper, params){
this.type = type;
this.validate = validation;
this.wrapper = wrapper;
this.parameters = params;
this.isPrimary = false;
chainPrimaryKey();
} | javascript | function SchemaType(type, validation, wrapper, params){
this.type = type;
this.validate = validation;
this.wrapper = wrapper;
this.parameters = params;
this.isPrimary = false;
chainPrimaryKey();
} | [
"function",
"SchemaType",
"(",
"type",
",",
"validation",
",",
"wrapper",
",",
"params",
")",
"{",
"this",
".",
"type",
"=",
"type",
";",
"this",
".",
"validate",
"=",
"validation",
";",
"this",
".",
"wrapper",
"=",
"wrapper",
";",
"this",
".",
"parameters",
"=",
"params",
";",
"this",
".",
"isPrimary",
"=",
"false",
";",
"chainPrimaryKey",
"(",
")",
";",
"}"
] | A schema data type for use with Cassandra
@param {String} type The data type associated with Cassandra
@param {Function} validation A function to validate that the value associated matches the type.
@param {Object} wrapper Wraps the schema value if necessary
@param {Object} params Additional parameters that the schema type may need.
@return {[type]} [description] | [
"A",
"schema",
"data",
"type",
"for",
"use",
"with",
"Cassandra"
] | 49c5ce2e1bc6b19d25e8223e88df45c113c36b68 | https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/lib/schemaType.js#L9-L17 | train |
bem-contrib/md-to-bemjson | packages/mdast-util-to-bemjson/lib/transform.js | function(node, entity, props, content) {
const hasContent = (!entity || entity.content !== null) && content !== null;
const entityContent = hasContent ?
((entity && entity.content) || content || traverse.children(transform, node)) :
null;
const block = parseBemNode(entity);
const bemNode = build(block, props, entityContent);
// Extend blocks context with external plugins hContext
if (node.data) {
node.data.htmlAttributes && (bemNode.attrs = Object.assign({}, bemNode.attrs, node.data.htmlAttributes));
node.data.hProperties && (bemNode.hProps = node.data.hProperties);
}
return transform.augment(bemNode);
} | javascript | function(node, entity, props, content) {
const hasContent = (!entity || entity.content !== null) && content !== null;
const entityContent = hasContent ?
((entity && entity.content) || content || traverse.children(transform, node)) :
null;
const block = parseBemNode(entity);
const bemNode = build(block, props, entityContent);
// Extend blocks context with external plugins hContext
if (node.data) {
node.data.htmlAttributes && (bemNode.attrs = Object.assign({}, bemNode.attrs, node.data.htmlAttributes));
node.data.hProperties && (bemNode.hProps = node.data.hProperties);
}
return transform.augment(bemNode);
} | [
"function",
"(",
"node",
",",
"entity",
",",
"props",
",",
"content",
")",
"{",
"const",
"hasContent",
"=",
"(",
"!",
"entity",
"||",
"entity",
".",
"content",
"!==",
"null",
")",
"&&",
"content",
"!==",
"null",
";",
"const",
"entityContent",
"=",
"hasContent",
"?",
"(",
"(",
"entity",
"&&",
"entity",
".",
"content",
")",
"||",
"content",
"||",
"traverse",
".",
"children",
"(",
"transform",
",",
"node",
")",
")",
":",
"null",
";",
"const",
"block",
"=",
"parseBemNode",
"(",
"entity",
")",
";",
"const",
"bemNode",
"=",
"build",
"(",
"block",
",",
"props",
",",
"entityContent",
")",
";",
"if",
"(",
"node",
".",
"data",
")",
"{",
"node",
".",
"data",
".",
"htmlAttributes",
"&&",
"(",
"bemNode",
".",
"attrs",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"bemNode",
".",
"attrs",
",",
"node",
".",
"data",
".",
"htmlAttributes",
")",
")",
";",
"node",
".",
"data",
".",
"hProperties",
"&&",
"(",
"bemNode",
".",
"hProps",
"=",
"node",
".",
"data",
".",
"hProperties",
")",
";",
"}",
"return",
"transform",
".",
"augment",
"(",
"bemNode",
")",
";",
"}"
] | Transform MDAST node to bemNode
@param {Object} node - MDAST node
@param {Object} entity - bem entity, partial representation of bemNode
@param {Object} [props] - bemNode properties
@param {Object|Array|String} [content] - bemNode content
@returns {Object} bemNode | [
"Transform",
"MDAST",
"node",
"to",
"bemNode"
] | 047ab80c681073c7c92aecee754bcf46956507a9 | https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/mdast-util-to-bemjson/lib/transform.js#L41-L56 | train |
|
bem-contrib/md-to-bemjson | packages/mdast-util-to-bemjson/lib/transform.js | augmentFactory | function augmentFactory(augmentFunction) {
/**
* Apply custom augmentation and insert back to subtree
*
* @function AugmentFunction
* @param {Object} bemNode - representation of bem entity
* @returns {Object} bemNode
*/
function augment(bemNode) {
const hasChildren = _hasChildren(bemNode.content);
const bemNodeClone = hasChildren ? omit(bemNode, ['content']) : cloneDeep(bemNode);
const augmentedBemNode = augmentFunction(bemNodeClone);
/* Check that if we has children augmentation doesn't modify content */
assert(
!hasChildren || !augmentedBemNode.content,
'You are not allow to modify subtree of bemNode. To do that please use bem-xjst@'
);
if (hasChildren) {
augmentedBemNode.content = bemNode.content;
}
return augmentedBemNode;
}
return augment;
} | javascript | function augmentFactory(augmentFunction) {
/**
* Apply custom augmentation and insert back to subtree
*
* @function AugmentFunction
* @param {Object} bemNode - representation of bem entity
* @returns {Object} bemNode
*/
function augment(bemNode) {
const hasChildren = _hasChildren(bemNode.content);
const bemNodeClone = hasChildren ? omit(bemNode, ['content']) : cloneDeep(bemNode);
const augmentedBemNode = augmentFunction(bemNodeClone);
/* Check that if we has children augmentation doesn't modify content */
assert(
!hasChildren || !augmentedBemNode.content,
'You are not allow to modify subtree of bemNode. To do that please use bem-xjst@'
);
if (hasChildren) {
augmentedBemNode.content = bemNode.content;
}
return augmentedBemNode;
}
return augment;
} | [
"function",
"augmentFactory",
"(",
"augmentFunction",
")",
"{",
"function",
"augment",
"(",
"bemNode",
")",
"{",
"const",
"hasChildren",
"=",
"_hasChildren",
"(",
"bemNode",
".",
"content",
")",
";",
"const",
"bemNodeClone",
"=",
"hasChildren",
"?",
"omit",
"(",
"bemNode",
",",
"[",
"'content'",
"]",
")",
":",
"cloneDeep",
"(",
"bemNode",
")",
";",
"const",
"augmentedBemNode",
"=",
"augmentFunction",
"(",
"bemNodeClone",
")",
";",
"assert",
"(",
"!",
"hasChildren",
"||",
"!",
"augmentedBemNode",
".",
"content",
",",
"'You are not allow to modify subtree of bemNode. To do that please use bem-xjst@'",
")",
";",
"if",
"(",
"hasChildren",
")",
"{",
"augmentedBemNode",
".",
"content",
"=",
"bemNode",
".",
"content",
";",
"}",
"return",
"augmentedBemNode",
";",
"}",
"return",
"augment",
";",
"}"
] | Create augment function, for apply custom transformations
@param {BjsonConverter~augmentCallback} augmentFunction - callback with custom augmentation
@returns {BjsonConverter~augment} | [
"Create",
"augment",
"function",
"for",
"apply",
"custom",
"transformations"
] | 047ab80c681073c7c92aecee754bcf46956507a9 | https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/mdast-util-to-bemjson/lib/transform.js#L70-L98 | train |
bem-contrib/md-to-bemjson | packages/mdast-util-to-bemjson/lib/transform.js | _hasChildren | function _hasChildren(content) {
if (!content) return false;
if (typeof content === 'object') return true;
if (Array.isArray(content) && content.every(item => typeof item === 'string')) return false;
return false;
} | javascript | function _hasChildren(content) {
if (!content) return false;
if (typeof content === 'object') return true;
if (Array.isArray(content) && content.every(item => typeof item === 'string')) return false;
return false;
} | [
"function",
"_hasChildren",
"(",
"content",
")",
"{",
"if",
"(",
"!",
"content",
")",
"return",
"false",
";",
"if",
"(",
"typeof",
"content",
"===",
"'object'",
")",
"return",
"true",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"content",
")",
"&&",
"content",
".",
"every",
"(",
"item",
"=>",
"typeof",
"item",
"===",
"'string'",
")",
")",
"return",
"false",
";",
"return",
"false",
";",
"}"
] | Check is content of bemNode value, or children
@param {Object|Array|String|undefined} content - bemNode content
@returns {Boolean} is content of bemNode are children
@private | [
"Check",
"is",
"content",
"of",
"bemNode",
"value",
"or",
"children"
] | 047ab80c681073c7c92aecee754bcf46956507a9 | https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/mdast-util-to-bemjson/lib/transform.js#L110-L115 | train |
canjs/can-react | extensions/can-simple-dom.js | reindexNodes | function reindexNodes () {
var child = this.node.firstChild;
this._length = 0;
while (child) {
this[this._length++] = child;
child = child.nextSibling;
}
} | javascript | function reindexNodes () {
var child = this.node.firstChild;
this._length = 0;
while (child) {
this[this._length++] = child;
child = child.nextSibling;
}
} | [
"function",
"reindexNodes",
"(",
")",
"{",
"var",
"child",
"=",
"this",
".",
"node",
".",
"firstChild",
";",
"this",
".",
"_length",
"=",
"0",
";",
"while",
"(",
"child",
")",
"{",
"this",
"[",
"this",
".",
"_length",
"++",
"]",
"=",
"child",
";",
"child",
"=",
"child",
".",
"nextSibling",
";",
"}",
"}"
] | Bind or call this method against a childNodes property | [
"Bind",
"or",
"call",
"this",
"method",
"against",
"a",
"childNodes",
"property"
] | 87aaaff9858cec0629ed83f4f54596cc3c20903a | https://github.com/canjs/can-react/blob/87aaaff9858cec0629ed83f4f54596cc3c20903a/extensions/can-simple-dom.js#L94-L102 | train |
davedoesdev/qlobber | lib/qlobber.js | Qlobber | function Qlobber (options)
{
options = options || {};
this._separator = options.separator || '.';
this._wildcard_one = options.wildcard_one || '*';
this._wildcard_some = options.wildcard_some || '#';
this._trie = new Map();
if (options.cache_adds instanceof Map)
{
this._shortcuts = options.cache_adds;
}
else if (options.cache_adds)
{
this._shortcuts = new Map();
}
} | javascript | function Qlobber (options)
{
options = options || {};
this._separator = options.separator || '.';
this._wildcard_one = options.wildcard_one || '*';
this._wildcard_some = options.wildcard_some || '#';
this._trie = new Map();
if (options.cache_adds instanceof Map)
{
this._shortcuts = options.cache_adds;
}
else if (options.cache_adds)
{
this._shortcuts = new Map();
}
} | [
"function",
"Qlobber",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"_separator",
"=",
"options",
".",
"separator",
"||",
"'.'",
";",
"this",
".",
"_wildcard_one",
"=",
"options",
".",
"wildcard_one",
"||",
"'*'",
";",
"this",
".",
"_wildcard_some",
"=",
"options",
".",
"wildcard_some",
"||",
"'#'",
";",
"this",
".",
"_trie",
"=",
"new",
"Map",
"(",
")",
";",
"if",
"(",
"options",
".",
"cache_adds",
"instanceof",
"Map",
")",
"{",
"this",
".",
"_shortcuts",
"=",
"options",
".",
"cache_adds",
";",
"}",
"else",
"if",
"(",
"options",
".",
"cache_adds",
")",
"{",
"this",
".",
"_shortcuts",
"=",
"new",
"Map",
"(",
")",
";",
"}",
"}"
] | Creates a new qlobber.
@constructor
@param {Object} [options] Configures the qlobber. Use the following properties:
- `{String} separator` The character to use for separating words in topics. Defaults to '.'. MQTT uses '/' as the separator, for example.
- `{String} wildcard_one` The character to use for matching exactly one word in a topic. Defaults to '*'. MQTT uses '+', for example.
- `{String} wildcard_some` The character to use for matching zero or more words in a topic. Defaults to '#'. MQTT uses '#' too.
- `{Boolean|Map} cache_adds` Whether to cache topics when adding topic matchers. This will make adding multiple matchers for the same topic faster at the cost of extra memory usage. Defaults to `false`. If you supply a `Map` then it will be used to cache the topics (use this to enumerate all the topics in the qlobber). | [
"Creates",
"a",
"new",
"qlobber",
"."
] | 95d68c17658f24999733e4f8f6d35e01d82fa665 | https://github.com/davedoesdev/qlobber/blob/95d68c17658f24999733e4f8f6d35e01d82fa665/lib/qlobber.js#L117-L133 | train |
canjs/can-stache-key | can-stache-key.js | function(value, i, reads, options) {
return value && value[getValueSymbol] && value[isValueLikeSymbol] !== false && (options.foundAt || !isAt(i, reads) );
} | javascript | function(value, i, reads, options) {
return value && value[getValueSymbol] && value[isValueLikeSymbol] !== false && (options.foundAt || !isAt(i, reads) );
} | [
"function",
"(",
"value",
",",
"i",
",",
"reads",
",",
"options",
")",
"{",
"return",
"value",
"&&",
"value",
"[",
"getValueSymbol",
"]",
"&&",
"value",
"[",
"isValueLikeSymbol",
"]",
"!==",
"false",
"&&",
"(",
"options",
".",
"foundAt",
"||",
"!",
"isAt",
"(",
"i",
",",
"reads",
")",
")",
";",
"}"
] | compute value reader | [
"compute",
"value",
"reader"
] | 909fd944f108f754b63c5e4a3f3021db0e6e6c60 | https://github.com/canjs/can-stache-key/blob/909fd944f108f754b63c5e4a3f3021db0e6e6c60/can-stache-key.js#L185-L187 | train |
|
canjs/can-stache-key | can-stache-key.js | function(parent, key, value, options) {
var keys = typeof key === "string" ? observeReader.reads(key) : key;
var last;
options = options || {};
if(keys.length > 1) {
last = keys.pop();
parent = observeReader.read(parent, keys, options).value;
keys.push(last);
} else {
last = keys[0];
}
if(!parent) {
return;
}
var keyValue = peek(parent, last.key);
// here's where we need to figure out the best way to write
// if property being set points at a compute, set the compute
if( observeReader.valueReadersMap.isValueLike.test(keyValue, keys.length - 1, keys, options) ) {
observeReader.valueReadersMap.isValueLike.write(keyValue, value, options);
} else {
if(observeReader.valueReadersMap.isValueLike.test(parent, keys.length - 1, keys, options) ) {
parent = parent[getValueSymbol]();
}
if(observeReader.propertyReadersMap.map.test(parent)) {
observeReader.propertyReadersMap.map.write(parent, last.key, value, options);
}
else if(observeReader.propertyReadersMap.object.test(parent)) {
observeReader.propertyReadersMap.object.write(parent, last.key, value, options);
if(options.observation) {
options.observation.update();
}
}
}
} | javascript | function(parent, key, value, options) {
var keys = typeof key === "string" ? observeReader.reads(key) : key;
var last;
options = options || {};
if(keys.length > 1) {
last = keys.pop();
parent = observeReader.read(parent, keys, options).value;
keys.push(last);
} else {
last = keys[0];
}
if(!parent) {
return;
}
var keyValue = peek(parent, last.key);
// here's where we need to figure out the best way to write
// if property being set points at a compute, set the compute
if( observeReader.valueReadersMap.isValueLike.test(keyValue, keys.length - 1, keys, options) ) {
observeReader.valueReadersMap.isValueLike.write(keyValue, value, options);
} else {
if(observeReader.valueReadersMap.isValueLike.test(parent, keys.length - 1, keys, options) ) {
parent = parent[getValueSymbol]();
}
if(observeReader.propertyReadersMap.map.test(parent)) {
observeReader.propertyReadersMap.map.write(parent, last.key, value, options);
}
else if(observeReader.propertyReadersMap.object.test(parent)) {
observeReader.propertyReadersMap.object.write(parent, last.key, value, options);
if(options.observation) {
options.observation.update();
}
}
}
} | [
"function",
"(",
"parent",
",",
"key",
",",
"value",
",",
"options",
")",
"{",
"var",
"keys",
"=",
"typeof",
"key",
"===",
"\"string\"",
"?",
"observeReader",
".",
"reads",
"(",
"key",
")",
":",
"key",
";",
"var",
"last",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"if",
"(",
"keys",
".",
"length",
">",
"1",
")",
"{",
"last",
"=",
"keys",
".",
"pop",
"(",
")",
";",
"parent",
"=",
"observeReader",
".",
"read",
"(",
"parent",
",",
"keys",
",",
"options",
")",
".",
"value",
";",
"keys",
".",
"push",
"(",
"last",
")",
";",
"}",
"else",
"{",
"last",
"=",
"keys",
"[",
"0",
"]",
";",
"}",
"if",
"(",
"!",
"parent",
")",
"{",
"return",
";",
"}",
"var",
"keyValue",
"=",
"peek",
"(",
"parent",
",",
"last",
".",
"key",
")",
";",
"if",
"(",
"observeReader",
".",
"valueReadersMap",
".",
"isValueLike",
".",
"test",
"(",
"keyValue",
",",
"keys",
".",
"length",
"-",
"1",
",",
"keys",
",",
"options",
")",
")",
"{",
"observeReader",
".",
"valueReadersMap",
".",
"isValueLike",
".",
"write",
"(",
"keyValue",
",",
"value",
",",
"options",
")",
";",
"}",
"else",
"{",
"if",
"(",
"observeReader",
".",
"valueReadersMap",
".",
"isValueLike",
".",
"test",
"(",
"parent",
",",
"keys",
".",
"length",
"-",
"1",
",",
"keys",
",",
"options",
")",
")",
"{",
"parent",
"=",
"parent",
"[",
"getValueSymbol",
"]",
"(",
")",
";",
"}",
"if",
"(",
"observeReader",
".",
"propertyReadersMap",
".",
"map",
".",
"test",
"(",
"parent",
")",
")",
"{",
"observeReader",
".",
"propertyReadersMap",
".",
"map",
".",
"write",
"(",
"parent",
",",
"last",
".",
"key",
",",
"value",
",",
"options",
")",
";",
"}",
"else",
"if",
"(",
"observeReader",
".",
"propertyReadersMap",
".",
"object",
".",
"test",
"(",
"parent",
")",
")",
"{",
"observeReader",
".",
"propertyReadersMap",
".",
"object",
".",
"write",
"(",
"parent",
",",
"last",
".",
"key",
",",
"value",
",",
"options",
")",
";",
"if",
"(",
"options",
".",
"observation",
")",
"{",
"options",
".",
"observation",
".",
"update",
"(",
")",
";",
"}",
"}",
"}",
"}"
] | This should be able to set a property similar to how read works. | [
"This",
"should",
"be",
"able",
"to",
"set",
"a",
"property",
"similar",
"to",
"how",
"read",
"works",
"."
] | 909fd944f108f754b63c5e4a3f3021db0e6e6c60 | https://github.com/canjs/can-stache-key/blob/909fd944f108f754b63c5e4a3f3021db0e6e6c60/can-stache-key.js#L306-L341 | train |
|
kalamuna/metalsmith-assets-convention | index.js | assetFile | function assetFile(filename, callback) {
const data = {
source: files[filename].source,
destination: files[filename].destination || path.join(path.dirname(filename), '.')
}
delete files[filename]
metalsmithAssets(data)(files, metalsmith, callback)
} | javascript | function assetFile(filename, callback) {
const data = {
source: files[filename].source,
destination: files[filename].destination || path.join(path.dirname(filename), '.')
}
delete files[filename]
metalsmithAssets(data)(files, metalsmith, callback)
} | [
"function",
"assetFile",
"(",
"filename",
",",
"callback",
")",
"{",
"const",
"data",
"=",
"{",
"source",
":",
"files",
"[",
"filename",
"]",
".",
"source",
",",
"destination",
":",
"files",
"[",
"filename",
"]",
".",
"destination",
"||",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"filename",
")",
",",
"'.'",
")",
"}",
"delete",
"files",
"[",
"filename",
"]",
"metalsmithAssets",
"(",
"data",
")",
"(",
"files",
",",
"metalsmith",
",",
"callback",
")",
"}"
] | Tell Metalsmith Assets to process the data.
@param {string} filename The file to filter on.
@param {function} callback A asyncronous callback that's made once the processing is complete. | [
"Tell",
"Metalsmith",
"Assets",
"to",
"process",
"the",
"data",
"."
] | 8e23ae8e96fb26c446d1989a84be8469c266580e | https://github.com/kalamuna/metalsmith-assets-convention/blob/8e23ae8e96fb26c446d1989a84be8469c266580e/index.js#L36-L43 | train |
bigchaindb/js-utility-belt | src/safe_merge.js | doesObjectListHaveDuplicates | function doesObjectListHaveDuplicates(l) {
const mergedList = l.reduce((merged, obj) => (
obj ? merged.concat(Object.keys(obj)) : merged
), []);
// Taken from: http://stackoverflow.com/a/7376645/1263876
// By casting the array to a Set, and then checking if the size of the array
// shrunk in the process of casting, we can check if there were any duplicates
return new Set(mergedList).size !== mergedList.length;
} | javascript | function doesObjectListHaveDuplicates(l) {
const mergedList = l.reduce((merged, obj) => (
obj ? merged.concat(Object.keys(obj)) : merged
), []);
// Taken from: http://stackoverflow.com/a/7376645/1263876
// By casting the array to a Set, and then checking if the size of the array
// shrunk in the process of casting, we can check if there were any duplicates
return new Set(mergedList).size !== mergedList.length;
} | [
"function",
"doesObjectListHaveDuplicates",
"(",
"l",
")",
"{",
"const",
"mergedList",
"=",
"l",
".",
"reduce",
"(",
"(",
"merged",
",",
"obj",
")",
"=>",
"(",
"obj",
"?",
"merged",
".",
"concat",
"(",
"Object",
".",
"keys",
"(",
"obj",
")",
")",
":",
"merged",
")",
",",
"[",
"]",
")",
";",
"return",
"new",
"Set",
"(",
"mergedList",
")",
".",
"size",
"!==",
"mergedList",
".",
"length",
";",
"}"
] | Checks a list of objects for key duplicates and returns a boolean | [
"Checks",
"a",
"list",
"of",
"objects",
"for",
"key",
"duplicates",
"and",
"returns",
"a",
"boolean"
] | 765cd85bb6d811fa3892c4e89752bfab1f1b825c | https://github.com/bigchaindb/js-utility-belt/blob/765cd85bb6d811fa3892c4e89752bfab1f1b825c/src/safe_merge.js#L21-L30 | train |
bigchaindb/js-utility-belt | src/safe_invoke.js | safeInvokeForConfig | function safeInvokeForConfig({ fn, context, params, onNotInvoked }) {
if (typeof fn === 'function') {
let fnParams = params;
if (typeof params === 'function') {
fnParams = params();
}
// Warn if params or lazily evaluated params were given but not in an array
if (fnParams != null && !Array.isArray(fnParams)) {
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line no-console
console.warn("Params to pass into safeInvoke's fn is not an array. Ignoring...",
fnParams);
}
fnParams = null;
}
return {
invoked: true,
result: fn.apply(context, fnParams)
};
} else {
if (typeof onNotInvoked === 'function') {
onNotInvoked();
}
return { invoked: false };
}
} | javascript | function safeInvokeForConfig({ fn, context, params, onNotInvoked }) {
if (typeof fn === 'function') {
let fnParams = params;
if (typeof params === 'function') {
fnParams = params();
}
// Warn if params or lazily evaluated params were given but not in an array
if (fnParams != null && !Array.isArray(fnParams)) {
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line no-console
console.warn("Params to pass into safeInvoke's fn is not an array. Ignoring...",
fnParams);
}
fnParams = null;
}
return {
invoked: true,
result: fn.apply(context, fnParams)
};
} else {
if (typeof onNotInvoked === 'function') {
onNotInvoked();
}
return { invoked: false };
}
} | [
"function",
"safeInvokeForConfig",
"(",
"{",
"fn",
",",
"context",
",",
"params",
",",
"onNotInvoked",
"}",
")",
"{",
"if",
"(",
"typeof",
"fn",
"===",
"'function'",
")",
"{",
"let",
"fnParams",
"=",
"params",
";",
"if",
"(",
"typeof",
"params",
"===",
"'function'",
")",
"{",
"fnParams",
"=",
"params",
"(",
")",
";",
"}",
"if",
"(",
"fnParams",
"!=",
"null",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"fnParams",
")",
")",
"{",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
")",
"{",
"console",
".",
"warn",
"(",
"\"Params to pass into safeInvoke's fn is not an array. Ignoring...\"",
",",
"fnParams",
")",
";",
"}",
"fnParams",
"=",
"null",
";",
"}",
"return",
"{",
"invoked",
":",
"true",
",",
"result",
":",
"fn",
".",
"apply",
"(",
"context",
",",
"fnParams",
")",
"}",
";",
"}",
"else",
"{",
"if",
"(",
"typeof",
"onNotInvoked",
"===",
"'function'",
")",
"{",
"onNotInvoked",
"(",
")",
";",
"}",
"return",
"{",
"invoked",
":",
"false",
"}",
";",
"}",
"}"
] | Abstraction for safeInvoke's two call signatures | [
"Abstraction",
"for",
"safeInvoke",
"s",
"two",
"call",
"signatures"
] | 765cd85bb6d811fa3892c4e89752bfab1f1b825c | https://github.com/bigchaindb/js-utility-belt/blob/765cd85bb6d811fa3892c4e89752bfab1f1b825c/src/safe_invoke.js#L52-L81 | train |
gdbots/pbj-js | src/Message.js | populateDefault | function populateDefault(message, field) {
const fieldName = field.getName();
if (message.has(fieldName)) {
return true;
}
const defaultValue = field.getDefault(message);
if (defaultValue === null) {
return false;
}
const msg = msgs.get(message);
if (field.isASingleValue()) {
msg.data.set(fieldName, defaultValue);
msg.clearedFields.delete(fieldName);
return true;
}
if (isEmpty(defaultValue)) {
return false;
}
if (field.isASet()) {
message.addToSet(fieldName, Array.from(defaultValue));
return true;
}
msg.data.set(fieldName, defaultValue);
msg.clearedFields.delete(fieldName);
return true;
} | javascript | function populateDefault(message, field) {
const fieldName = field.getName();
if (message.has(fieldName)) {
return true;
}
const defaultValue = field.getDefault(message);
if (defaultValue === null) {
return false;
}
const msg = msgs.get(message);
if (field.isASingleValue()) {
msg.data.set(fieldName, defaultValue);
msg.clearedFields.delete(fieldName);
return true;
}
if (isEmpty(defaultValue)) {
return false;
}
if (field.isASet()) {
message.addToSet(fieldName, Array.from(defaultValue));
return true;
}
msg.data.set(fieldName, defaultValue);
msg.clearedFields.delete(fieldName);
return true;
} | [
"function",
"populateDefault",
"(",
"message",
",",
"field",
")",
"{",
"const",
"fieldName",
"=",
"field",
".",
"getName",
"(",
")",
";",
"if",
"(",
"message",
".",
"has",
"(",
"fieldName",
")",
")",
"{",
"return",
"true",
";",
"}",
"const",
"defaultValue",
"=",
"field",
".",
"getDefault",
"(",
"message",
")",
";",
"if",
"(",
"defaultValue",
"===",
"null",
")",
"{",
"return",
"false",
";",
"}",
"const",
"msg",
"=",
"msgs",
".",
"get",
"(",
"message",
")",
";",
"if",
"(",
"field",
".",
"isASingleValue",
"(",
")",
")",
"{",
"msg",
".",
"data",
".",
"set",
"(",
"fieldName",
",",
"defaultValue",
")",
";",
"msg",
".",
"clearedFields",
".",
"delete",
"(",
"fieldName",
")",
";",
"return",
"true",
";",
"}",
"if",
"(",
"isEmpty",
"(",
"defaultValue",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"field",
".",
"isASet",
"(",
")",
")",
"{",
"message",
".",
"addToSet",
"(",
"fieldName",
",",
"Array",
".",
"from",
"(",
"defaultValue",
")",
")",
";",
"return",
"true",
";",
"}",
"msg",
".",
"data",
".",
"set",
"(",
"fieldName",
",",
"defaultValue",
")",
";",
"msg",
".",
"clearedFields",
".",
"delete",
"(",
"fieldName",
")",
";",
"return",
"true",
";",
"}"
] | Populates the default on a single field if it's not already set
and the default generated is not a null value or empty array.
@param {Message} message
@param {Field} field
@returns {boolean} Returns true if a non null/empty default was applied or already present. | [
"Populates",
"the",
"default",
"on",
"a",
"single",
"field",
"if",
"it",
"s",
"not",
"already",
"set",
"and",
"the",
"default",
"generated",
"is",
"not",
"a",
"null",
"value",
"or",
"empty",
"array",
"."
] | 729db944d45d170cd32814f7c18d914072d8e21d | https://github.com/gdbots/pbj-js/blob/729db944d45d170cd32814f7c18d914072d8e21d/src/Message.js#L58-L89 | train |
steelbrain/jasmine-fix | index.js | resetClock | function resetClock() {
for (const key in jasmine.Clock.real) {
if (jasmine.Clock.real.hasOwnProperty(key)) {
window[key] = jasmine.Clock.real[key]
}
}
} | javascript | function resetClock() {
for (const key in jasmine.Clock.real) {
if (jasmine.Clock.real.hasOwnProperty(key)) {
window[key] = jasmine.Clock.real[key]
}
}
} | [
"function",
"resetClock",
"(",
")",
"{",
"for",
"(",
"const",
"key",
"in",
"jasmine",
".",
"Clock",
".",
"real",
")",
"{",
"if",
"(",
"jasmine",
".",
"Clock",
".",
"real",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"window",
"[",
"key",
"]",
"=",
"jasmine",
".",
"Clock",
".",
"real",
"[",
"key",
"]",
"}",
"}",
"}"
] | Jasmine 1.3.x has no sane way of resetting to native clocks, and since we're gonna test promises and such, we're gonna need it | [
"Jasmine",
"1",
".",
"3",
".",
"x",
"has",
"no",
"sane",
"way",
"of",
"resetting",
"to",
"native",
"clocks",
"and",
"since",
"we",
"re",
"gonna",
"test",
"promises",
"and",
"such",
"we",
"re",
"gonna",
"need",
"it"
] | c7bc55cc9d6de1f4493f3f7a1930c60b80c00557 | https://github.com/steelbrain/jasmine-fix/blob/c7bc55cc9d6de1f4493f3f7a1930c60b80c00557/index.js#L17-L23 | train |
nzakas/cssurl | Makefile.js | nodeExec | function nodeExec() {
var exitCode = nodeCLI.exec.apply(nodeCLI, arguments).code;
if (exitCode > 0) {
exit(1);
}
} | javascript | function nodeExec() {
var exitCode = nodeCLI.exec.apply(nodeCLI, arguments).code;
if (exitCode > 0) {
exit(1);
}
} | [
"function",
"nodeExec",
"(",
")",
"{",
"var",
"exitCode",
"=",
"nodeCLI",
".",
"exec",
".",
"apply",
"(",
"nodeCLI",
",",
"arguments",
")",
".",
"code",
";",
"if",
"(",
"exitCode",
">",
"0",
")",
"{",
"exit",
"(",
"1",
")",
";",
"}",
"}"
] | Executes a Node command and exits if the exit code isn't 0.
@returns {void}
@private | [
"Executes",
"a",
"Node",
"command",
"and",
"exits",
"if",
"the",
"exit",
"code",
"isn",
"t",
"0",
"."
] | ee60a35eb5db0749d7ae75a7e7b8f3fcb2953dc2 | https://github.com/nzakas/cssurl/blob/ee60a35eb5db0749d7ae75a7e7b8f3fcb2953dc2/Makefile.js#L55-L60 | train |
nzakas/cssurl | lib/url-translator.js | function(url, fromFilename, toFilename) {
if (!SKIP_URLS.test(url)) {
var fromDirname = path.dirname(fromFilename),
toDirname = path.dirname(toFilename),
fromPath = path.resolve(fromDirname, url),
toPath = path.resolve(toDirname);
return path.relative(toPath, fromPath).replace(/\\/g, "/");
} else {
return url;
}
} | javascript | function(url, fromFilename, toFilename) {
if (!SKIP_URLS.test(url)) {
var fromDirname = path.dirname(fromFilename),
toDirname = path.dirname(toFilename),
fromPath = path.resolve(fromDirname, url),
toPath = path.resolve(toDirname);
return path.relative(toPath, fromPath).replace(/\\/g, "/");
} else {
return url;
}
} | [
"function",
"(",
"url",
",",
"fromFilename",
",",
"toFilename",
")",
"{",
"if",
"(",
"!",
"SKIP_URLS",
".",
"test",
"(",
"url",
")",
")",
"{",
"var",
"fromDirname",
"=",
"path",
".",
"dirname",
"(",
"fromFilename",
")",
",",
"toDirname",
"=",
"path",
".",
"dirname",
"(",
"toFilename",
")",
",",
"fromPath",
"=",
"path",
".",
"resolve",
"(",
"fromDirname",
",",
"url",
")",
",",
"toPath",
"=",
"path",
".",
"resolve",
"(",
"toDirname",
")",
";",
"return",
"path",
".",
"relative",
"(",
"toPath",
",",
"fromPath",
")",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"\"/\"",
")",
";",
"}",
"else",
"{",
"return",
"url",
";",
"}",
"}"
] | Translates a given relative URL with consideration that the reference is
relative to a specific CSS file, and that CSS file location is changing.
@param {string} url The URL to translate.
@param {string} fromFilename The original filename for the CSS.
@param {string} toFilename The new filename for the CSS.
@returns {string} The CSS code with the URLs translated. | [
"Translates",
"a",
"given",
"relative",
"URL",
"with",
"consideration",
"that",
"the",
"reference",
"is",
"relative",
"to",
"a",
"specific",
"CSS",
"file",
"and",
"that",
"CSS",
"file",
"location",
"is",
"changing",
"."
] | ee60a35eb5db0749d7ae75a7e7b8f3fcb2953dc2 | https://github.com/nzakas/cssurl/blob/ee60a35eb5db0749d7ae75a7e7b8f3fcb2953dc2/lib/url-translator.js#L41-L54 | train |
|
nzakas/cssurl | lib/url-rewriter.js | function(code) {
var tokens = new TokenStream(code),
hasCRLF = code.indexOf("\r") > -1,
lines = code.split(/\r?\n/),
line,
token,
tt,
replacement,
colAdjust = 0,
lastLine = 0;
while ((tt = tokens.get()) !== 0) {
token = tokens.token();
if (tt === Tokens.URI) { // URI
if (lastLine !== token.startLine) {
colAdjust = 0;
lastLine = token.startLine;
}
replacement = this.replacer(token.value.replace(URL_PARENS, ""));
// 5 is for url() characters
line = lines[token.startLine - 1];
lines[token.startLine - 1] = line.substring(0, token.startCol + colAdjust - 1) +
"url(" + replacement + ")" + line.substring(token.endCol + colAdjust - 1);
colAdjust += ((replacement.length + 5) - token.value.length);
}
}
return lines.join(hasCRLF ? "\r\n" : "\n");
} | javascript | function(code) {
var tokens = new TokenStream(code),
hasCRLF = code.indexOf("\r") > -1,
lines = code.split(/\r?\n/),
line,
token,
tt,
replacement,
colAdjust = 0,
lastLine = 0;
while ((tt = tokens.get()) !== 0) {
token = tokens.token();
if (tt === Tokens.URI) { // URI
if (lastLine !== token.startLine) {
colAdjust = 0;
lastLine = token.startLine;
}
replacement = this.replacer(token.value.replace(URL_PARENS, ""));
// 5 is for url() characters
line = lines[token.startLine - 1];
lines[token.startLine - 1] = line.substring(0, token.startCol + colAdjust - 1) +
"url(" + replacement + ")" + line.substring(token.endCol + colAdjust - 1);
colAdjust += ((replacement.length + 5) - token.value.length);
}
}
return lines.join(hasCRLF ? "\r\n" : "\n");
} | [
"function",
"(",
"code",
")",
"{",
"var",
"tokens",
"=",
"new",
"TokenStream",
"(",
"code",
")",
",",
"hasCRLF",
"=",
"code",
".",
"indexOf",
"(",
"\"\\r\"",
")",
">",
"\\r",
",",
"-",
"1",
",",
"lines",
"=",
"code",
".",
"split",
"(",
"/",
"\\r?\\n",
"/",
")",
",",
"line",
",",
"token",
",",
"tt",
",",
"replacement",
",",
"colAdjust",
"=",
"0",
";",
"lastLine",
"=",
"0",
"while",
"(",
"(",
"tt",
"=",
"tokens",
".",
"get",
"(",
")",
")",
"!==",
"0",
")",
"{",
"token",
"=",
"tokens",
".",
"token",
"(",
")",
";",
"if",
"(",
"tt",
"===",
"Tokens",
".",
"URI",
")",
"{",
"if",
"(",
"lastLine",
"!==",
"token",
".",
"startLine",
")",
"{",
"colAdjust",
"=",
"0",
";",
"lastLine",
"=",
"token",
".",
"startLine",
";",
"}",
"replacement",
"=",
"this",
".",
"replacer",
"(",
"token",
".",
"value",
".",
"replace",
"(",
"URL_PARENS",
",",
"\"\"",
")",
")",
";",
"line",
"=",
"lines",
"[",
"token",
".",
"startLine",
"-",
"1",
"]",
";",
"lines",
"[",
"token",
".",
"startLine",
"-",
"1",
"]",
"=",
"line",
".",
"substring",
"(",
"0",
",",
"token",
".",
"startCol",
"+",
"colAdjust",
"-",
"1",
")",
"+",
"\"url(\"",
"+",
"replacement",
"+",
"\")\"",
"+",
"line",
".",
"substring",
"(",
"token",
".",
"endCol",
"+",
"colAdjust",
"-",
"1",
")",
";",
"colAdjust",
"+=",
"(",
"(",
"replacement",
".",
"length",
"+",
"5",
")",
"-",
"token",
".",
"value",
".",
"length",
")",
";",
"}",
"}",
"}"
] | Rewrites the given CSS code using the replacer.
@param {string} code The CSS code to rewrite.
@returns {string} The CSS code with the URLs replaced. | [
"Rewrites",
"the",
"given",
"CSS",
"code",
"using",
"the",
"replacer",
"."
] | ee60a35eb5db0749d7ae75a7e7b8f3fcb2953dc2 | https://github.com/nzakas/cssurl/blob/ee60a35eb5db0749d7ae75a7e7b8f3fcb2953dc2/lib/url-rewriter.js#L51-L84 | train |
|
justan/twei | lib/util.js | open | function open(url, callback){
var cmd, exec = require('child_process').exec;
switch(process.platform){
case 'darwin':
cmd = 'open';
break;
case 'win32':
case 'win64':
cmd = 'start ""';//加空的双引号可以打开带有 "&" 的地址
break;
case 'cygwin':
cmd = 'cygstart';
break;
default:
cmd = 'xdg-open';
break;
}
cmd = cmd + ' ' + url + '';
return exec(cmd, callback);
} | javascript | function open(url, callback){
var cmd, exec = require('child_process').exec;
switch(process.platform){
case 'darwin':
cmd = 'open';
break;
case 'win32':
case 'win64':
cmd = 'start ""';//加空的双引号可以打开带有 "&" 的地址
break;
case 'cygwin':
cmd = 'cygstart';
break;
default:
cmd = 'xdg-open';
break;
}
cmd = cmd + ' ' + url + '';
return exec(cmd, callback);
} | [
"function",
"open",
"(",
"url",
",",
"callback",
")",
"{",
"var",
"cmd",
",",
"exec",
"=",
"require",
"(",
"'child_process'",
")",
".",
"exec",
";",
"switch",
"(",
"process",
".",
"platform",
")",
"{",
"case",
"'darwin'",
":",
"cmd",
"=",
"'open'",
";",
"break",
";",
"case",
"'win32'",
":",
"case",
"'win64'",
":",
"cmd",
"=",
"'start \"\"'",
";",
"break",
";",
"case",
"'cygwin'",
":",
"cmd",
"=",
"'cygstart'",
";",
"break",
";",
"default",
":",
"cmd",
"=",
"'xdg-open'",
";",
"break",
";",
"}",
"cmd",
"=",
"cmd",
"+",
"' '",
"+",
"url",
"+",
"''",
";",
"return",
"exec",
"(",
"cmd",
",",
"callback",
")",
";",
"}"
] | open a url | [
"open",
"a",
"url"
] | ebc55e78dc315db49cc7d8fe924e68bdea0169f3 | https://github.com/justan/twei/blob/ebc55e78dc315db49cc7d8fe924e68bdea0169f3/lib/util.js#L249-L268 | train |
justan/twei | lib/alias.js | aliasExpand | function aliasExpand(cmdmap){
var cmds = {}
, twei = require('../')
, alias, apiGroup
;
for(var key in cmdmap){
alias = cmdmap[key];
if(alias.alias){
if(Array.isArray(alias.alias)){
for(var i = 0, l = alias.alias.length; i < l; i++){
cmds[alias.alias[i]] = cmdmap[key].cmd;
}
}else{
cmds[alias.alias] = cmdmap[key].cmd;
}
cmds[key] = cmdmap[key].cmd;
delete alias.alias;
}else{
cmds[key] = cmdmap[key].cmd || cmdmap[key];
}
if(alias.apis && typeof (apiGroup = twei.getApiGroup(alias.apis)) == 'object'){
for(var apiName in apiGroup){
if(!cmds[key + '.' + apiName]){
cmds[key + '.' + apiName] = 'execute ' + alias.apis + '.' + apiName;
}
}
}
}
//console.log(cmds);
return cmds;
} | javascript | function aliasExpand(cmdmap){
var cmds = {}
, twei = require('../')
, alias, apiGroup
;
for(var key in cmdmap){
alias = cmdmap[key];
if(alias.alias){
if(Array.isArray(alias.alias)){
for(var i = 0, l = alias.alias.length; i < l; i++){
cmds[alias.alias[i]] = cmdmap[key].cmd;
}
}else{
cmds[alias.alias] = cmdmap[key].cmd;
}
cmds[key] = cmdmap[key].cmd;
delete alias.alias;
}else{
cmds[key] = cmdmap[key].cmd || cmdmap[key];
}
if(alias.apis && typeof (apiGroup = twei.getApiGroup(alias.apis)) == 'object'){
for(var apiName in apiGroup){
if(!cmds[key + '.' + apiName]){
cmds[key + '.' + apiName] = 'execute ' + alias.apis + '.' + apiName;
}
}
}
}
//console.log(cmds);
return cmds;
} | [
"function",
"aliasExpand",
"(",
"cmdmap",
")",
"{",
"var",
"cmds",
"=",
"{",
"}",
",",
"twei",
"=",
"require",
"(",
"'../'",
")",
",",
"alias",
",",
"apiGroup",
";",
"for",
"(",
"var",
"key",
"in",
"cmdmap",
")",
"{",
"alias",
"=",
"cmdmap",
"[",
"key",
"]",
";",
"if",
"(",
"alias",
".",
"alias",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"alias",
".",
"alias",
")",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"alias",
".",
"alias",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"cmds",
"[",
"alias",
".",
"alias",
"[",
"i",
"]",
"]",
"=",
"cmdmap",
"[",
"key",
"]",
".",
"cmd",
";",
"}",
"}",
"else",
"{",
"cmds",
"[",
"alias",
".",
"alias",
"]",
"=",
"cmdmap",
"[",
"key",
"]",
".",
"cmd",
";",
"}",
"cmds",
"[",
"key",
"]",
"=",
"cmdmap",
"[",
"key",
"]",
".",
"cmd",
";",
"delete",
"alias",
".",
"alias",
";",
"}",
"else",
"{",
"cmds",
"[",
"key",
"]",
"=",
"cmdmap",
"[",
"key",
"]",
".",
"cmd",
"||",
"cmdmap",
"[",
"key",
"]",
";",
"}",
"if",
"(",
"alias",
".",
"apis",
"&&",
"typeof",
"(",
"apiGroup",
"=",
"twei",
".",
"getApiGroup",
"(",
"alias",
".",
"apis",
")",
")",
"==",
"'object'",
")",
"{",
"for",
"(",
"var",
"apiName",
"in",
"apiGroup",
")",
"{",
"if",
"(",
"!",
"cmds",
"[",
"key",
"+",
"'.'",
"+",
"apiName",
"]",
")",
"{",
"cmds",
"[",
"key",
"+",
"'.'",
"+",
"apiName",
"]",
"=",
"'execute '",
"+",
"alias",
".",
"apis",
"+",
"'.'",
"+",
"apiName",
";",
"}",
"}",
"}",
"}",
"return",
"cmds",
";",
"}"
] | restore alias to core command
@param {Object} cmdmap aliasmap
@return {Object} 返回完整的 名称:命令 对象
Example:
{
update: ''execute status.update''
, user: 'execute user.show'
, whois: 'execute user.show'
} | [
"restore",
"alias",
"to",
"core",
"command"
] | ebc55e78dc315db49cc7d8fe924e68bdea0169f3 | https://github.com/justan/twei/blob/ebc55e78dc315db49cc7d8fe924e68bdea0169f3/lib/alias.js#L84-L116 | train |
thlorenz/spok | spok.js | needRecurseArray | function needRecurseArray(arr) {
for (var i = 0; i < arr.length; i++) {
var el = arr[i]
if (typeof el !== 'number' && typeof el !== 'string' && el != null) return true
}
return false
} | javascript | function needRecurseArray(arr) {
for (var i = 0; i < arr.length; i++) {
var el = arr[i]
if (typeof el !== 'number' && typeof el !== 'string' && el != null) return true
}
return false
} | [
"function",
"needRecurseArray",
"(",
"arr",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"arr",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"el",
"=",
"arr",
"[",
"i",
"]",
"if",
"(",
"typeof",
"el",
"!==",
"'number'",
"&&",
"typeof",
"el",
"!==",
"'string'",
"&&",
"el",
"!=",
"null",
")",
"return",
"true",
"}",
"return",
"false",
"}"
] | only recurse into arrays if they contain actual specs or objects | [
"only",
"recurse",
"into",
"arrays",
"if",
"they",
"contain",
"actual",
"specs",
"or",
"objects"
] | f1da9034d4f186bd0a23b0562a8843a343dd81fe | https://github.com/thlorenz/spok/blob/f1da9034d4f186bd0a23b0562a8843a343dd81fe/spok.js#L6-L12 | train |
eladnava/material-letter-icons | lib/generator.js | generateLetterIcon | function generateLetterIcon(letter, cb) {
// Derive SVG from base letter SVG
var letterSVG = baseSVG;
// Get a random Material Design color
var color = getRandomLetterColor();
// Substitude placeholders for color and letter
letterSVG = letterSVG.replace('{c}', color);
letterSVG = letterSVG.replace('{x}', letter);
// Get filesystem-friendly file name for letter
var fileName = getIconFilename(letter);
// Define SVG/PNG output path
var outputSVGPath = rootDir + config.dist.path + config.dist.svg.outputPath + fileName + '.svg';
var outputPNGPath = rootDir + config.dist.path + config.dist.png.outputPath + fileName + '.png';
// Export the letter as an SVG file
fs.writeFileSync(outputSVGPath, letterSVG);
// Convert the SVG file into a PNG file using svg2png
svg2png(new Buffer(letterSVG), config.dist.png.dimensions)
.then(function (buffer) {
// Write to disk
fs.writeFileSync(outputPNGPath, buffer);
// Success
cb();
}).catch(function (err) {
// Report error
return cb(err);
});
} | javascript | function generateLetterIcon(letter, cb) {
// Derive SVG from base letter SVG
var letterSVG = baseSVG;
// Get a random Material Design color
var color = getRandomLetterColor();
// Substitude placeholders for color and letter
letterSVG = letterSVG.replace('{c}', color);
letterSVG = letterSVG.replace('{x}', letter);
// Get filesystem-friendly file name for letter
var fileName = getIconFilename(letter);
// Define SVG/PNG output path
var outputSVGPath = rootDir + config.dist.path + config.dist.svg.outputPath + fileName + '.svg';
var outputPNGPath = rootDir + config.dist.path + config.dist.png.outputPath + fileName + '.png';
// Export the letter as an SVG file
fs.writeFileSync(outputSVGPath, letterSVG);
// Convert the SVG file into a PNG file using svg2png
svg2png(new Buffer(letterSVG), config.dist.png.dimensions)
.then(function (buffer) {
// Write to disk
fs.writeFileSync(outputPNGPath, buffer);
// Success
cb();
}).catch(function (err) {
// Report error
return cb(err);
});
} | [
"function",
"generateLetterIcon",
"(",
"letter",
",",
"cb",
")",
"{",
"var",
"letterSVG",
"=",
"baseSVG",
";",
"var",
"color",
"=",
"getRandomLetterColor",
"(",
")",
";",
"letterSVG",
"=",
"letterSVG",
".",
"replace",
"(",
"'{c}'",
",",
"color",
")",
";",
"letterSVG",
"=",
"letterSVG",
".",
"replace",
"(",
"'{x}'",
",",
"letter",
")",
";",
"var",
"fileName",
"=",
"getIconFilename",
"(",
"letter",
")",
";",
"var",
"outputSVGPath",
"=",
"rootDir",
"+",
"config",
".",
"dist",
".",
"path",
"+",
"config",
".",
"dist",
".",
"svg",
".",
"outputPath",
"+",
"fileName",
"+",
"'.svg'",
";",
"var",
"outputPNGPath",
"=",
"rootDir",
"+",
"config",
".",
"dist",
".",
"path",
"+",
"config",
".",
"dist",
".",
"png",
".",
"outputPath",
"+",
"fileName",
"+",
"'.png'",
";",
"fs",
".",
"writeFileSync",
"(",
"outputSVGPath",
",",
"letterSVG",
")",
";",
"svg2png",
"(",
"new",
"Buffer",
"(",
"letterSVG",
")",
",",
"config",
".",
"dist",
".",
"png",
".",
"dimensions",
")",
".",
"then",
"(",
"function",
"(",
"buffer",
")",
"{",
"fs",
".",
"writeFileSync",
"(",
"outputPNGPath",
",",
"buffer",
")",
";",
"cb",
"(",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
")",
";",
"}"
] | Generates icons for a single letter | [
"Generates",
"icons",
"for",
"a",
"single",
"letter"
] | f425b38e81a570795a78b7baa3638100be2c0edb | https://github.com/eladnava/material-letter-icons/blob/f425b38e81a570795a78b7baa3638100be2c0edb/lib/generator.js#L60-L93 | train |
eladnava/material-letter-icons | lib/generator.js | getRandomLetterColor | function getRandomLetterColor() {
// Reset index if we're at the end of the array
if (currentColorIndex >= colorKeys.length) {
currentColorIndex = 0;
}
// Get current color and increment index for next time
var currentColorKey = colorKeys[currentColorIndex++];
// Return most satured color hex (a700 or 900)
var color = colors[currentColorKey]['a700'] || colors[currentColorKey]['900'];
// Invalid color saturation value?
if (color == undefined) {
// No saturation for black or white,
// so return the next random color instead
return getRandomLetterColor();
}
// Return current color hex
return color;
} | javascript | function getRandomLetterColor() {
// Reset index if we're at the end of the array
if (currentColorIndex >= colorKeys.length) {
currentColorIndex = 0;
}
// Get current color and increment index for next time
var currentColorKey = colorKeys[currentColorIndex++];
// Return most satured color hex (a700 or 900)
var color = colors[currentColorKey]['a700'] || colors[currentColorKey]['900'];
// Invalid color saturation value?
if (color == undefined) {
// No saturation for black or white,
// so return the next random color instead
return getRandomLetterColor();
}
// Return current color hex
return color;
} | [
"function",
"getRandomLetterColor",
"(",
")",
"{",
"if",
"(",
"currentColorIndex",
">=",
"colorKeys",
".",
"length",
")",
"{",
"currentColorIndex",
"=",
"0",
";",
"}",
"var",
"currentColorKey",
"=",
"colorKeys",
"[",
"currentColorIndex",
"++",
"]",
";",
"var",
"color",
"=",
"colors",
"[",
"currentColorKey",
"]",
"[",
"'a700'",
"]",
"||",
"colors",
"[",
"currentColorKey",
"]",
"[",
"'900'",
"]",
";",
"if",
"(",
"color",
"==",
"undefined",
")",
"{",
"return",
"getRandomLetterColor",
"(",
")",
";",
"}",
"return",
"color",
";",
"}"
] | Returns the next Material Design color for the icon background | [
"Returns",
"the",
"next",
"Material",
"Design",
"color",
"for",
"the",
"icon",
"background"
] | f425b38e81a570795a78b7baa3638100be2c0edb | https://github.com/eladnava/material-letter-icons/blob/f425b38e81a570795a78b7baa3638100be2c0edb/lib/generator.js#L108-L129 | train |
TechGapItalia/angular-vertical-timeline | gulpfile.js | compileSass | function compileSass(path, ext, file, callback) {
let compiledCss = sass.renderSync({
file: path,
outputStyle: 'compressed',
});
callback(null, compiledCss.css);
} | javascript | function compileSass(path, ext, file, callback) {
let compiledCss = sass.renderSync({
file: path,
outputStyle: 'compressed',
});
callback(null, compiledCss.css);
} | [
"function",
"compileSass",
"(",
"path",
",",
"ext",
",",
"file",
",",
"callback",
")",
"{",
"let",
"compiledCss",
"=",
"sass",
".",
"renderSync",
"(",
"{",
"file",
":",
"path",
",",
"outputStyle",
":",
"'compressed'",
",",
"}",
")",
";",
"callback",
"(",
"null",
",",
"compiledCss",
".",
"css",
")",
";",
"}"
] | Compile SASS to CSS.
@see https://github.com/ludohenin/gulp-inline-ng2-template
@see https://github.com/sass/node-sass | [
"Compile",
"SASS",
"to",
"CSS",
"."
] | b1dfaea814b6ff3302efd9d9f85ece6cbcceb6fa | https://github.com/TechGapItalia/angular-vertical-timeline/blob/b1dfaea814b6ff3302efd9d9f85ece6cbcceb6fa/gulpfile.js#L69-L75 | train |
anvaka/rafor | index.js | asyncFor | function asyncFor(array, visitCallback, doneCallback, options) {
var start = 0;
var elapsed = 0;
options = options || {};
var step = options.step || 1;
var maxTimeMS = options.maxTimeMS || 8;
var pointsPerLoopCycle = options.probeElements || 5000;
// we should never block main thread for too long...
setTimeout(processSubset, 0);
function processSubset() {
var finish = Math.min(array.length, start + pointsPerLoopCycle);
var i = start;
var timeStart = new Date();
for (i = start; i < finish; i += step) {
visitCallback(array[i], i, array);
}
if (i < array.length) {
elapsed += (new Date() - timeStart);
start = i;
pointsPerLoopCycle = Math.round(start * maxTimeMS/elapsed);
setTimeout(processSubset, 0);
} else {
doneCallback(array);
}
}
} | javascript | function asyncFor(array, visitCallback, doneCallback, options) {
var start = 0;
var elapsed = 0;
options = options || {};
var step = options.step || 1;
var maxTimeMS = options.maxTimeMS || 8;
var pointsPerLoopCycle = options.probeElements || 5000;
// we should never block main thread for too long...
setTimeout(processSubset, 0);
function processSubset() {
var finish = Math.min(array.length, start + pointsPerLoopCycle);
var i = start;
var timeStart = new Date();
for (i = start; i < finish; i += step) {
visitCallback(array[i], i, array);
}
if (i < array.length) {
elapsed += (new Date() - timeStart);
start = i;
pointsPerLoopCycle = Math.round(start * maxTimeMS/elapsed);
setTimeout(processSubset, 0);
} else {
doneCallback(array);
}
}
} | [
"function",
"asyncFor",
"(",
"array",
",",
"visitCallback",
",",
"doneCallback",
",",
"options",
")",
"{",
"var",
"start",
"=",
"0",
";",
"var",
"elapsed",
"=",
"0",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"step",
"=",
"options",
".",
"step",
"||",
"1",
";",
"var",
"maxTimeMS",
"=",
"options",
".",
"maxTimeMS",
"||",
"8",
";",
"var",
"pointsPerLoopCycle",
"=",
"options",
".",
"probeElements",
"||",
"5000",
";",
"setTimeout",
"(",
"processSubset",
",",
"0",
")",
";",
"function",
"processSubset",
"(",
")",
"{",
"var",
"finish",
"=",
"Math",
".",
"min",
"(",
"array",
".",
"length",
",",
"start",
"+",
"pointsPerLoopCycle",
")",
";",
"var",
"i",
"=",
"start",
";",
"var",
"timeStart",
"=",
"new",
"Date",
"(",
")",
";",
"for",
"(",
"i",
"=",
"start",
";",
"i",
"<",
"finish",
";",
"i",
"+=",
"step",
")",
"{",
"visitCallback",
"(",
"array",
"[",
"i",
"]",
",",
"i",
",",
"array",
")",
";",
"}",
"if",
"(",
"i",
"<",
"array",
".",
"length",
")",
"{",
"elapsed",
"+=",
"(",
"new",
"Date",
"(",
")",
"-",
"timeStart",
")",
";",
"start",
"=",
"i",
";",
"pointsPerLoopCycle",
"=",
"Math",
".",
"round",
"(",
"start",
"*",
"maxTimeMS",
"/",
"elapsed",
")",
";",
"setTimeout",
"(",
"processSubset",
",",
"0",
")",
";",
"}",
"else",
"{",
"doneCallback",
"(",
"array",
")",
";",
"}",
"}",
"}"
] | Iterates over array in async manner. This function attempts to maximize
number of elements visited within single event loop cycle, while at the
same time tries to not exceed a time threshold allowed to stay within
event loop.
@param {Array} array which needs to be iterated. Array-like objects are OK too.
@param {VisitCalback} visitCallback called for every element within for loop.
@param {DoneCallback} doneCallback called when iterator has reached end of array.
@param {Object=} options - additional configuration:
@param {number} [options.step=1] - default iteration step
@param {number} [options.maxTimeMS=8] - maximum time (in milliseconds) which
iterator should spend within single event loop.
@param {number} [options.probeElements=5000] - how many elements should iterator
visit to measure its iteration speed. | [
"Iterates",
"over",
"array",
"in",
"async",
"manner",
".",
"This",
"function",
"attempts",
"to",
"maximize",
"number",
"of",
"elements",
"visited",
"within",
"single",
"event",
"loop",
"cycle",
"while",
"at",
"the",
"same",
"time",
"tries",
"to",
"not",
"exceed",
"a",
"time",
"threshold",
"allowed",
"to",
"stay",
"within",
"event",
"loop",
"."
] | b322a2842a07fadcb993d5d37cbe3880fe4de715 | https://github.com/anvaka/rafor/blob/b322a2842a07fadcb993d5d37cbe3880fe4de715/index.js#L19-L46 | train |
ursudio/leaflet-webgl-heatmap | src/leaflet-webgl-heatmap.js | function () {
delete this.gl;
L.DomUtil.remove(this._container);
L.DomEvent.off(this._container);
delete this._container;
} | javascript | function () {
delete this.gl;
L.DomUtil.remove(this._container);
L.DomEvent.off(this._container);
delete this._container;
} | [
"function",
"(",
")",
"{",
"delete",
"this",
".",
"gl",
";",
"L",
".",
"DomUtil",
".",
"remove",
"(",
"this",
".",
"_container",
")",
";",
"L",
".",
"DomEvent",
".",
"off",
"(",
"this",
".",
"_container",
")",
";",
"delete",
"this",
".",
"_container",
";",
"}"
] | onRemove-ish | [
"onRemove",
"-",
"ish"
] | 52f954982b4289cbba3c6cd2cf4e373fcb4584b7 | https://github.com/ursudio/leaflet-webgl-heatmap/blob/52f954982b4289cbba3c6cd2cf4e373fcb4584b7/src/leaflet-webgl-heatmap.js#L68-L73 | train |
|
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | Container | function Container(parent) {
this.parent = parent;
this.children = [];
this.resolver = parent && parent.resolver || function() {};
this.registry = dictionary(parent ? parent.registry : null);
this.cache = dictionary(parent ? parent.cache : null);
this.factoryCache = dictionary(parent ? parent.factoryCache : null);
this.resolveCache = dictionary(parent ? parent.resolveCache : null);
this.typeInjections = dictionary(parent ? parent.typeInjections : null);
this.injections = dictionary(null);
this.normalizeCache = dictionary(null);
this.factoryTypeInjections = dictionary(parent ? parent.factoryTypeInjections : null);
this.factoryInjections = dictionary(null);
this._options = dictionary(parent ? parent._options : null);
this._typeOptions = dictionary(parent ? parent._typeOptions : null);
} | javascript | function Container(parent) {
this.parent = parent;
this.children = [];
this.resolver = parent && parent.resolver || function() {};
this.registry = dictionary(parent ? parent.registry : null);
this.cache = dictionary(parent ? parent.cache : null);
this.factoryCache = dictionary(parent ? parent.factoryCache : null);
this.resolveCache = dictionary(parent ? parent.resolveCache : null);
this.typeInjections = dictionary(parent ? parent.typeInjections : null);
this.injections = dictionary(null);
this.normalizeCache = dictionary(null);
this.factoryTypeInjections = dictionary(parent ? parent.factoryTypeInjections : null);
this.factoryInjections = dictionary(null);
this._options = dictionary(parent ? parent._options : null);
this._typeOptions = dictionary(parent ? parent._typeOptions : null);
} | [
"function",
"Container",
"(",
"parent",
")",
"{",
"this",
".",
"parent",
"=",
"parent",
";",
"this",
".",
"children",
"=",
"[",
"]",
";",
"this",
".",
"resolver",
"=",
"parent",
"&&",
"parent",
".",
"resolver",
"||",
"function",
"(",
")",
"{",
"}",
";",
"this",
".",
"registry",
"=",
"dictionary",
"(",
"parent",
"?",
"parent",
".",
"registry",
":",
"null",
")",
";",
"this",
".",
"cache",
"=",
"dictionary",
"(",
"parent",
"?",
"parent",
".",
"cache",
":",
"null",
")",
";",
"this",
".",
"factoryCache",
"=",
"dictionary",
"(",
"parent",
"?",
"parent",
".",
"factoryCache",
":",
"null",
")",
";",
"this",
".",
"resolveCache",
"=",
"dictionary",
"(",
"parent",
"?",
"parent",
".",
"resolveCache",
":",
"null",
")",
";",
"this",
".",
"typeInjections",
"=",
"dictionary",
"(",
"parent",
"?",
"parent",
".",
"typeInjections",
":",
"null",
")",
";",
"this",
".",
"injections",
"=",
"dictionary",
"(",
"null",
")",
";",
"this",
".",
"normalizeCache",
"=",
"dictionary",
"(",
"null",
")",
";",
"this",
".",
"factoryTypeInjections",
"=",
"dictionary",
"(",
"parent",
"?",
"parent",
".",
"factoryTypeInjections",
":",
"null",
")",
";",
"this",
".",
"factoryInjections",
"=",
"dictionary",
"(",
"null",
")",
";",
"this",
".",
"_options",
"=",
"dictionary",
"(",
"parent",
"?",
"parent",
".",
"_options",
":",
"null",
")",
";",
"this",
".",
"_typeOptions",
"=",
"dictionary",
"(",
"parent",
"?",
"parent",
".",
"_typeOptions",
":",
"null",
")",
";",
"}"
] | A lightweight container that helps to assemble and decouple components. Public api for the container is still in flux. The public api, specified on the application namespace should be considered the stable api. | [
"A",
"lightweight",
"container",
"that",
"helps",
"to",
"assemble",
"and",
"decouple",
"components",
".",
"Public",
"api",
"for",
"the",
"container",
"is",
"still",
"in",
"flux",
".",
"The",
"public",
"api",
"specified",
"on",
"the",
"application",
"namespace",
"should",
"be",
"considered",
"the",
"stable",
"api",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L1127-L1146 | train |
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | function(fullName, factory, options) {
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
if (factory === undefined) {
throw new TypeError('Attempting to register an unknown factory: `' + fullName + '`');
}
var normalizedName = this.normalize(fullName);
if (normalizedName in this.cache) {
throw new Error('Cannot re-register: `' + fullName +'`, as it has already been looked up.');
}
this.registry[normalizedName] = factory;
this._options[normalizedName] = (options || {});
} | javascript | function(fullName, factory, options) {
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
if (factory === undefined) {
throw new TypeError('Attempting to register an unknown factory: `' + fullName + '`');
}
var normalizedName = this.normalize(fullName);
if (normalizedName in this.cache) {
throw new Error('Cannot re-register: `' + fullName +'`, as it has already been looked up.');
}
this.registry[normalizedName] = factory;
this._options[normalizedName] = (options || {});
} | [
"function",
"(",
"fullName",
",",
"factory",
",",
"options",
")",
"{",
"Ember",
".",
"assert",
"(",
"'fullName must be a proper full name'",
",",
"validateFullName",
"(",
"fullName",
")",
")",
";",
"if",
"(",
"factory",
"===",
"undefined",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Attempting to register an unknown factory: `'",
"+",
"fullName",
"+",
"'`'",
")",
";",
"}",
"var",
"normalizedName",
"=",
"this",
".",
"normalize",
"(",
"fullName",
")",
";",
"if",
"(",
"normalizedName",
"in",
"this",
".",
"cache",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Cannot re-register: `'",
"+",
"fullName",
"+",
"'`, as it has already been looked up.'",
")",
";",
"}",
"this",
".",
"registry",
"[",
"normalizedName",
"]",
"=",
"factory",
";",
"this",
".",
"_options",
"[",
"normalizedName",
"]",
"=",
"(",
"options",
"||",
"{",
"}",
")",
";",
"}"
] | Registers a factory for later injection.
Example:
```javascript
var container = new Container();
container.register('model:user', Person, {singleton: false });
container.register('fruit:favorite', Orange);
container.register('communication:main', Email, {singleton: false});
```
@method register
@param {String} fullName
@param {Function} factory
@param {Object} options | [
"Registers",
"a",
"factory",
"for",
"later",
"injection",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L1257-L1272 | train |
|
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | function(fullName) {
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
var normalizedName = this.normalize(fullName);
delete this.registry[normalizedName];
delete this.cache[normalizedName];
delete this.factoryCache[normalizedName];
delete this.resolveCache[normalizedName];
delete this._options[normalizedName];
} | javascript | function(fullName) {
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
var normalizedName = this.normalize(fullName);
delete this.registry[normalizedName];
delete this.cache[normalizedName];
delete this.factoryCache[normalizedName];
delete this.resolveCache[normalizedName];
delete this._options[normalizedName];
} | [
"function",
"(",
"fullName",
")",
"{",
"Ember",
".",
"assert",
"(",
"'fullName must be a proper full name'",
",",
"validateFullName",
"(",
"fullName",
")",
")",
";",
"var",
"normalizedName",
"=",
"this",
".",
"normalize",
"(",
"fullName",
")",
";",
"delete",
"this",
".",
"registry",
"[",
"normalizedName",
"]",
";",
"delete",
"this",
".",
"cache",
"[",
"normalizedName",
"]",
";",
"delete",
"this",
".",
"factoryCache",
"[",
"normalizedName",
"]",
";",
"delete",
"this",
".",
"resolveCache",
"[",
"normalizedName",
"]",
";",
"delete",
"this",
".",
"_options",
"[",
"normalizedName",
"]",
";",
"}"
] | Unregister a fullName
```javascript
var container = new Container();
container.register('model:user', User);
container.lookup('model:user') instanceof User //=> true
container.unregister('model:user')
container.lookup('model:user') === undefined //=> true
```
@method unregister
@param {String} fullName | [
"Unregister",
"a",
"fullName"
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L1290-L1300 | train |
|
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | function(fullName, options) {
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
return lookup(this, this.normalize(fullName), options);
} | javascript | function(fullName, options) {
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
return lookup(this, this.normalize(fullName), options);
} | [
"function",
"(",
"fullName",
",",
"options",
")",
"{",
"Ember",
".",
"assert",
"(",
"'fullName must be a proper full name'",
",",
"validateFullName",
"(",
"fullName",
")",
")",
";",
"return",
"lookup",
"(",
"this",
",",
"this",
".",
"normalize",
"(",
"fullName",
")",
",",
"options",
")",
";",
"}"
] | Given a fullName return a corresponding instance.
The default behaviour is for lookup to return a singleton instance.
The singleton is scoped to the container, allowing multiple containers
to all have their own locally scoped singletons.
```javascript
var container = new Container();
container.register('api:twitter', Twitter);
var twitter = container.lookup('api:twitter');
twitter instanceof Twitter; // => true
by default the container will return singletons
var twitter2 = container.lookup('api:twitter');
twitter2 instanceof Twitter; // => true
twitter === twitter2; //=> true
```
If singletons are not wanted an optional flag can be provided at lookup.
```javascript
var container = new Container();
container.register('api:twitter', Twitter);
var twitter = container.lookup('api:twitter', { singleton: false });
var twitter2 = container.lookup('api:twitter', { singleton: false });
twitter === twitter2; //=> false
```
@method lookup
@param {String} fullName
@param {Object} options
@return {any} | [
"Given",
"a",
"fullName",
"return",
"a",
"corresponding",
"instance",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L1429-L1432 | train |
|
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | function(type, property, fullName) {
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
if (this.parent) { illegalChildOperation('typeInjection'); }
var fullNameType = fullName.split(':')[0];
if (fullNameType === type) {
throw new Error('Cannot inject a `' + fullName + '` on other ' + type + '(s). Register the `' + fullName + '` as a different type and perform the typeInjection.');
}
addTypeInjection(this.typeInjections, type, property, fullName);
} | javascript | function(type, property, fullName) {
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
if (this.parent) { illegalChildOperation('typeInjection'); }
var fullNameType = fullName.split(':')[0];
if (fullNameType === type) {
throw new Error('Cannot inject a `' + fullName + '` on other ' + type + '(s). Register the `' + fullName + '` as a different type and perform the typeInjection.');
}
addTypeInjection(this.typeInjections, type, property, fullName);
} | [
"function",
"(",
"type",
",",
"property",
",",
"fullName",
")",
"{",
"Ember",
".",
"assert",
"(",
"'fullName must be a proper full name'",
",",
"validateFullName",
"(",
"fullName",
")",
")",
";",
"if",
"(",
"this",
".",
"parent",
")",
"{",
"illegalChildOperation",
"(",
"'typeInjection'",
")",
";",
"}",
"var",
"fullNameType",
"=",
"fullName",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
";",
"if",
"(",
"fullNameType",
"===",
"type",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Cannot inject a `'",
"+",
"fullName",
"+",
"'` on other '",
"+",
"type",
"+",
"'(s). Register the `'",
"+",
"fullName",
"+",
"'` as a different type and perform the typeInjection.'",
")",
";",
"}",
"addTypeInjection",
"(",
"this",
".",
"typeInjections",
",",
"type",
",",
"property",
",",
"fullName",
")",
";",
"}"
] | Used only via `injection`.
Provides a specialized form of injection, specifically enabling
all objects of one type to be injected with a reference to another
object.
For example, provided each object of type `controller` needed a `router`.
one would do the following:
```javascript
var container = new Container();
container.register('router:main', Router);
container.register('controller:user', UserController);
container.register('controller:post', PostController);
container.typeInjection('controller', 'router', 'router:main');
var user = container.lookup('controller:user');
var post = container.lookup('controller:post');
user.router instanceof Router; //=> true
post.router instanceof Router; //=> true
both controllers share the same router
user.router === post.router; //=> true
```
@private
@method typeInjection
@param {String} type
@param {String} property
@param {String} fullName | [
"Used",
"only",
"via",
"injection",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L1536-L1547 | train |
|
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | function(fullName, property, injectionName) {
if (this.parent) { illegalChildOperation('injection'); }
var normalizedName = this.normalize(fullName);
var normalizedInjectionName = this.normalize(injectionName);
validateFullName(injectionName);
if (fullName.indexOf(':') === -1) {
return this.factoryTypeInjection(normalizedName, property, normalizedInjectionName);
}
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
if (this.factoryCache[normalizedName]) {
throw new Error('Attempted to register a factoryInjection for a type that has already ' +
'been looked up. (\'' + normalizedName + '\', \'' + property + '\', \'' + injectionName + '\')');
}
addInjection(this.factoryInjections, normalizedName, property, normalizedInjectionName);
} | javascript | function(fullName, property, injectionName) {
if (this.parent) { illegalChildOperation('injection'); }
var normalizedName = this.normalize(fullName);
var normalizedInjectionName = this.normalize(injectionName);
validateFullName(injectionName);
if (fullName.indexOf(':') === -1) {
return this.factoryTypeInjection(normalizedName, property, normalizedInjectionName);
}
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
if (this.factoryCache[normalizedName]) {
throw new Error('Attempted to register a factoryInjection for a type that has already ' +
'been looked up. (\'' + normalizedName + '\', \'' + property + '\', \'' + injectionName + '\')');
}
addInjection(this.factoryInjections, normalizedName, property, normalizedInjectionName);
} | [
"function",
"(",
"fullName",
",",
"property",
",",
"injectionName",
")",
"{",
"if",
"(",
"this",
".",
"parent",
")",
"{",
"illegalChildOperation",
"(",
"'injection'",
")",
";",
"}",
"var",
"normalizedName",
"=",
"this",
".",
"normalize",
"(",
"fullName",
")",
";",
"var",
"normalizedInjectionName",
"=",
"this",
".",
"normalize",
"(",
"injectionName",
")",
";",
"validateFullName",
"(",
"injectionName",
")",
";",
"if",
"(",
"fullName",
".",
"indexOf",
"(",
"':'",
")",
"===",
"-",
"1",
")",
"{",
"return",
"this",
".",
"factoryTypeInjection",
"(",
"normalizedName",
",",
"property",
",",
"normalizedInjectionName",
")",
";",
"}",
"Ember",
".",
"assert",
"(",
"'fullName must be a proper full name'",
",",
"validateFullName",
"(",
"fullName",
")",
")",
";",
"if",
"(",
"this",
".",
"factoryCache",
"[",
"normalizedName",
"]",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Attempted to register a factoryInjection for a type that has already '",
"+",
"'been looked up. (\\''",
"+",
"\\'",
"+",
"normalizedName",
"+",
"'\\', \\''",
"+",
"\\'",
"+",
"\\'",
"+",
"property",
")",
";",
"}",
"'\\', \\''",
"}"
] | Defines factory injection rules.
Similar to regular injection rules, but are run against factories, via
`Container#lookupFactory`.
These rules are used to inject objects onto factories when they
are looked up.
Two forms of injections are possible:
Injecting one fullName on another fullName
Injecting one fullName on a type
Example:
```javascript
var container = new Container();
container.register('store:main', Store);
container.register('store:secondary', OtherStore);
container.register('model:user', User);
container.register('model:post', Post);
injecting one fullName on another type
container.factoryInjection('model', 'store', 'store:main');
injecting one fullName on another fullName
container.factoryInjection('model:post', 'secondaryStore', 'store:secondary');
var UserFactory = container.lookupFactory('model:user');
var PostFactory = container.lookupFactory('model:post');
var store = container.lookup('store:main');
UserFactory.store instanceof Store; //=> true
UserFactory.secondaryStore instanceof OtherStore; //=> false
PostFactory.store instanceof Store; //=> true
PostFactory.secondaryStore instanceof OtherStore; //=> true
and both models share the same source instance
UserFactory.store === PostFactory.store; //=> true
```
@method factoryInjection
@param {String} factoryName
@param {String} property
@param {String} injectionName | [
"Defines",
"factory",
"injection",
"rules",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L1697-L1717 | train |
|
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | function() {
for (var i = 0, length = this.children.length; i < length; i++) {
this.children[i].destroy();
}
this.children = [];
eachDestroyable(this, function(item) {
item.destroy();
});
this.parent = undefined;
this.isDestroyed = true;
} | javascript | function() {
for (var i = 0, length = this.children.length; i < length; i++) {
this.children[i].destroy();
}
this.children = [];
eachDestroyable(this, function(item) {
item.destroy();
});
this.parent = undefined;
this.isDestroyed = true;
} | [
"function",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"length",
"=",
"this",
".",
"children",
".",
"length",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"this",
".",
"children",
"[",
"i",
"]",
".",
"destroy",
"(",
")",
";",
"}",
"this",
".",
"children",
"=",
"[",
"]",
";",
"eachDestroyable",
"(",
"this",
",",
"function",
"(",
"item",
")",
"{",
"item",
".",
"destroy",
"(",
")",
";",
"}",
")",
";",
"this",
".",
"parent",
"=",
"undefined",
";",
"this",
".",
"isDestroyed",
"=",
"true",
";",
"}"
] | A depth first traversal, destroying the container, its descendant containers and all
their managed objects.
@method destroy | [
"A",
"depth",
"first",
"traversal",
"destroying",
"the",
"container",
"its",
"descendant",
"containers",
"and",
"all",
"their",
"managed",
"objects",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L1725-L1738 | train |
|
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | function() {
if (this.isDestroyed) { return; }
// At this point, the App.Router must already be assigned
if (this.Router) {
var container = this.__container__;
container.unregister('router:main');
container.register('router:main', this.Router);
}
this.runInitializers();
runLoadHooks('application', this);
// At this point, any initializers or load hooks that would have wanted
// to defer readiness have fired. In general, advancing readiness here
// will proceed to didBecomeReady.
this.advanceReadiness();
return this;
} | javascript | function() {
if (this.isDestroyed) { return; }
// At this point, the App.Router must already be assigned
if (this.Router) {
var container = this.__container__;
container.unregister('router:main');
container.register('router:main', this.Router);
}
this.runInitializers();
runLoadHooks('application', this);
// At this point, any initializers or load hooks that would have wanted
// to defer readiness have fired. In general, advancing readiness here
// will proceed to didBecomeReady.
this.advanceReadiness();
return this;
} | [
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"isDestroyed",
")",
"{",
"return",
";",
"}",
"if",
"(",
"this",
".",
"Router",
")",
"{",
"var",
"container",
"=",
"this",
".",
"__container__",
";",
"container",
".",
"unregister",
"(",
"'router:main'",
")",
";",
"container",
".",
"register",
"(",
"'router:main'",
",",
"this",
".",
"Router",
")",
";",
"}",
"this",
".",
"runInitializers",
"(",
")",
";",
"runLoadHooks",
"(",
"'application'",
",",
"this",
")",
";",
"this",
".",
"advanceReadiness",
"(",
")",
";",
"return",
"this",
";",
"}"
] | Initialize the application. This happens automatically.
Run any initializers and run the application load hook. These hooks may
choose to defer readiness. For example, an authentication hook might want
to defer readiness until the auth token has been retrieved.
@private
@method _initialize | [
"Initialize",
"the",
"application",
".",
"This",
"happens",
"automatically",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L2733-L2752 | train |
|
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | function(namespace) {
var container = new Container();
container.set = set;
container.resolver = resolverFor(namespace);
container.normalizeFullName = container.resolver.normalize;
container.describe = container.resolver.describe;
container.makeToString = container.resolver.makeToString;
container.optionsForType('component', { singleton: false });
container.optionsForType('view', { singleton: false });
container.optionsForType('template', { instantiate: false });
container.optionsForType('helper', { instantiate: false });
container.register('application:main', namespace, { instantiate: false });
container.register('controller:basic', Controller, { instantiate: false });
container.register('controller:object', ObjectController, { instantiate: false });
container.register('controller:array', ArrayController, { instantiate: false });
container.register('view:select', SelectView);
container.register('route:basic', Route, { instantiate: false });
container.register('event_dispatcher:main', EventDispatcher);
container.register('router:main', Router);
container.injection('router:main', 'namespace', 'application:main');
container.register('location:auto', AutoLocation);
container.register('location:hash', HashLocation);
container.register('location:history', HistoryLocation);
container.register('location:none', NoneLocation);
container.injection('controller', 'target', 'router:main');
container.injection('controller', 'namespace', 'application:main');
container.register('-bucket-cache:main', BucketCache);
container.injection('router', '_bucketCache', '-bucket-cache:main');
container.injection('route', '_bucketCache', '-bucket-cache:main');
container.injection('controller', '_bucketCache', '-bucket-cache:main');
container.injection('route', 'router', 'router:main');
container.injection('location', 'rootURL', '-location-setting:root-url');
// DEBUGGING
container.register('resolver-for-debugging:main', container.resolver.__resolver__, { instantiate: false });
container.injection('container-debug-adapter:main', 'resolver', 'resolver-for-debugging:main');
container.injection('data-adapter:main', 'containerDebugAdapter', 'container-debug-adapter:main');
// Custom resolver authors may want to register their own ContainerDebugAdapter with this key
// ES6TODO: resolve this via import once ember-application package is ES6'ed
if (!ContainerDebugAdapter) { ContainerDebugAdapter = requireModule('ember-extension-support/container_debug_adapter')['default']; }
container.register('container-debug-adapter:main', ContainerDebugAdapter);
return container;
} | javascript | function(namespace) {
var container = new Container();
container.set = set;
container.resolver = resolverFor(namespace);
container.normalizeFullName = container.resolver.normalize;
container.describe = container.resolver.describe;
container.makeToString = container.resolver.makeToString;
container.optionsForType('component', { singleton: false });
container.optionsForType('view', { singleton: false });
container.optionsForType('template', { instantiate: false });
container.optionsForType('helper', { instantiate: false });
container.register('application:main', namespace, { instantiate: false });
container.register('controller:basic', Controller, { instantiate: false });
container.register('controller:object', ObjectController, { instantiate: false });
container.register('controller:array', ArrayController, { instantiate: false });
container.register('view:select', SelectView);
container.register('route:basic', Route, { instantiate: false });
container.register('event_dispatcher:main', EventDispatcher);
container.register('router:main', Router);
container.injection('router:main', 'namespace', 'application:main');
container.register('location:auto', AutoLocation);
container.register('location:hash', HashLocation);
container.register('location:history', HistoryLocation);
container.register('location:none', NoneLocation);
container.injection('controller', 'target', 'router:main');
container.injection('controller', 'namespace', 'application:main');
container.register('-bucket-cache:main', BucketCache);
container.injection('router', '_bucketCache', '-bucket-cache:main');
container.injection('route', '_bucketCache', '-bucket-cache:main');
container.injection('controller', '_bucketCache', '-bucket-cache:main');
container.injection('route', 'router', 'router:main');
container.injection('location', 'rootURL', '-location-setting:root-url');
// DEBUGGING
container.register('resolver-for-debugging:main', container.resolver.__resolver__, { instantiate: false });
container.injection('container-debug-adapter:main', 'resolver', 'resolver-for-debugging:main');
container.injection('data-adapter:main', 'containerDebugAdapter', 'container-debug-adapter:main');
// Custom resolver authors may want to register their own ContainerDebugAdapter with this key
// ES6TODO: resolve this via import once ember-application package is ES6'ed
if (!ContainerDebugAdapter) { ContainerDebugAdapter = requireModule('ember-extension-support/container_debug_adapter')['default']; }
container.register('container-debug-adapter:main', ContainerDebugAdapter);
return container;
} | [
"function",
"(",
"namespace",
")",
"{",
"var",
"container",
"=",
"new",
"Container",
"(",
")",
";",
"container",
".",
"set",
"=",
"set",
";",
"container",
".",
"resolver",
"=",
"resolverFor",
"(",
"namespace",
")",
";",
"container",
".",
"normalizeFullName",
"=",
"container",
".",
"resolver",
".",
"normalize",
";",
"container",
".",
"describe",
"=",
"container",
".",
"resolver",
".",
"describe",
";",
"container",
".",
"makeToString",
"=",
"container",
".",
"resolver",
".",
"makeToString",
";",
"container",
".",
"optionsForType",
"(",
"'component'",
",",
"{",
"singleton",
":",
"false",
"}",
")",
";",
"container",
".",
"optionsForType",
"(",
"'view'",
",",
"{",
"singleton",
":",
"false",
"}",
")",
";",
"container",
".",
"optionsForType",
"(",
"'template'",
",",
"{",
"instantiate",
":",
"false",
"}",
")",
";",
"container",
".",
"optionsForType",
"(",
"'helper'",
",",
"{",
"instantiate",
":",
"false",
"}",
")",
";",
"container",
".",
"register",
"(",
"'application:main'",
",",
"namespace",
",",
"{",
"instantiate",
":",
"false",
"}",
")",
";",
"container",
".",
"register",
"(",
"'controller:basic'",
",",
"Controller",
",",
"{",
"instantiate",
":",
"false",
"}",
")",
";",
"container",
".",
"register",
"(",
"'controller:object'",
",",
"ObjectController",
",",
"{",
"instantiate",
":",
"false",
"}",
")",
";",
"container",
".",
"register",
"(",
"'controller:array'",
",",
"ArrayController",
",",
"{",
"instantiate",
":",
"false",
"}",
")",
";",
"container",
".",
"register",
"(",
"'view:select'",
",",
"SelectView",
")",
";",
"container",
".",
"register",
"(",
"'route:basic'",
",",
"Route",
",",
"{",
"instantiate",
":",
"false",
"}",
")",
";",
"container",
".",
"register",
"(",
"'event_dispatcher:main'",
",",
"EventDispatcher",
")",
";",
"container",
".",
"register",
"(",
"'router:main'",
",",
"Router",
")",
";",
"container",
".",
"injection",
"(",
"'router:main'",
",",
"'namespace'",
",",
"'application:main'",
")",
";",
"container",
".",
"register",
"(",
"'location:auto'",
",",
"AutoLocation",
")",
";",
"container",
".",
"register",
"(",
"'location:hash'",
",",
"HashLocation",
")",
";",
"container",
".",
"register",
"(",
"'location:history'",
",",
"HistoryLocation",
")",
";",
"container",
".",
"register",
"(",
"'location:none'",
",",
"NoneLocation",
")",
";",
"container",
".",
"injection",
"(",
"'controller'",
",",
"'target'",
",",
"'router:main'",
")",
";",
"container",
".",
"injection",
"(",
"'controller'",
",",
"'namespace'",
",",
"'application:main'",
")",
";",
"container",
".",
"register",
"(",
"'-bucket-cache:main'",
",",
"BucketCache",
")",
";",
"container",
".",
"injection",
"(",
"'router'",
",",
"'_bucketCache'",
",",
"'-bucket-cache:main'",
")",
";",
"container",
".",
"injection",
"(",
"'route'",
",",
"'_bucketCache'",
",",
"'-bucket-cache:main'",
")",
";",
"container",
".",
"injection",
"(",
"'controller'",
",",
"'_bucketCache'",
",",
"'-bucket-cache:main'",
")",
";",
"container",
".",
"injection",
"(",
"'route'",
",",
"'router'",
",",
"'router:main'",
")",
";",
"container",
".",
"injection",
"(",
"'location'",
",",
"'rootURL'",
",",
"'-location-setting:root-url'",
")",
";",
"container",
".",
"register",
"(",
"'resolver-for-debugging:main'",
",",
"container",
".",
"resolver",
".",
"__resolver__",
",",
"{",
"instantiate",
":",
"false",
"}",
")",
";",
"container",
".",
"injection",
"(",
"'container-debug-adapter:main'",
",",
"'resolver'",
",",
"'resolver-for-debugging:main'",
")",
";",
"container",
".",
"injection",
"(",
"'data-adapter:main'",
",",
"'containerDebugAdapter'",
",",
"'container-debug-adapter:main'",
")",
";",
"if",
"(",
"!",
"ContainerDebugAdapter",
")",
"{",
"ContainerDebugAdapter",
"=",
"requireModule",
"(",
"'ember-extension-support/container_debug_adapter'",
")",
"[",
"'default'",
"]",
";",
"}",
"container",
".",
"register",
"(",
"'container-debug-adapter:main'",
",",
"ContainerDebugAdapter",
")",
";",
"return",
"container",
";",
"}"
] | This creates a container with the default Ember naming conventions.
It also configures the container:
registered views are created every time they are looked up (they are
not singletons)
registered templates are not factories; the registered value is
returned directly.
the router receives the application as its `namespace` property
all controllers receive the router as their `target` and `controllers`
properties
all controllers receive the application as their `namespace` property
the application view receives the application controller as its
`controller` property
the application view receives the application template as its
`defaultTemplate` property
@private
@method buildContainer
@static
@param {Ember.Application} namespace the application to build the
container for.
@return {Ember.Container} the built container | [
"This",
"creates",
"a",
"container",
"with",
"the",
"default",
"Ember",
"naming",
"conventions",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L3135-L3190 | train |
|
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | function() {
var namespaces = emberA(Namespace.NAMESPACES);
var types = emberA();
var self = this;
namespaces.forEach(function(namespace) {
for (var key in namespace) {
if (!namespace.hasOwnProperty(key)) { continue; }
// Even though we will filter again in `getModelTypes`,
// we should not call `lookupContainer` on non-models
// (especially when `Ember.MODEL_FACTORY_INJECTIONS` is `true`)
if (!self.detect(namespace[key])) { continue; }
var name = dasherize(key);
if (!(namespace instanceof Application) && namespace.toString()) {
name = namespace + '/' + name;
}
types.push(name);
}
});
return types;
} | javascript | function() {
var namespaces = emberA(Namespace.NAMESPACES);
var types = emberA();
var self = this;
namespaces.forEach(function(namespace) {
for (var key in namespace) {
if (!namespace.hasOwnProperty(key)) { continue; }
// Even though we will filter again in `getModelTypes`,
// we should not call `lookupContainer` on non-models
// (especially when `Ember.MODEL_FACTORY_INJECTIONS` is `true`)
if (!self.detect(namespace[key])) { continue; }
var name = dasherize(key);
if (!(namespace instanceof Application) && namespace.toString()) {
name = namespace + '/' + name;
}
types.push(name);
}
});
return types;
} | [
"function",
"(",
")",
"{",
"var",
"namespaces",
"=",
"emberA",
"(",
"Namespace",
".",
"NAMESPACES",
")",
";",
"var",
"types",
"=",
"emberA",
"(",
")",
";",
"var",
"self",
"=",
"this",
";",
"namespaces",
".",
"forEach",
"(",
"function",
"(",
"namespace",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"namespace",
")",
"{",
"if",
"(",
"!",
"namespace",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"!",
"self",
".",
"detect",
"(",
"namespace",
"[",
"key",
"]",
")",
")",
"{",
"continue",
";",
"}",
"var",
"name",
"=",
"dasherize",
"(",
"key",
")",
";",
"if",
"(",
"!",
"(",
"namespace",
"instanceof",
"Application",
")",
"&&",
"namespace",
".",
"toString",
"(",
")",
")",
"{",
"name",
"=",
"namespace",
"+",
"'/'",
"+",
"name",
";",
"}",
"types",
".",
"push",
"(",
"name",
")",
";",
"}",
"}",
")",
";",
"return",
"types",
";",
"}"
] | Loops over all namespaces and all objects
attached to them
@private
@method _getObjectsOnNamespaces
@return {Array} Array of model type strings | [
"Loops",
"over",
"all",
"namespaces",
"and",
"all",
"objects",
"attached",
"to",
"them"
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L4527-L4547 | train |
|
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | handlebarsGet | function handlebarsGet(root, path, options) {
var data = options && options.data;
var normalizedPath = normalizePath(root, path, data);
var value;
// In cases where the path begins with a keyword, change the
// root to the value represented by that keyword, and ensure
// the path is relative to it.
root = normalizedPath.root;
path = normalizedPath.path;
// Ember.get with a null root and GlobalPath will fall back to
// Ember.lookup, which is no longer allowed in templates.
//
// But when outputting a primitive, root will be the primitive
// and path a blank string. These primitives should pass through
// to `get`.
if (root || path === '') {
value = get(root, path);
}
if (detectIsGlobal(path)) {
if (value === undefined && root !== Ember.lookup) {
root = Ember.lookup;
value = get(root, path);
}
if (root === Ember.lookup || root === null) {
Ember.deprecate("Global lookup of "+path+" from a Handlebars template is deprecated.");
}
}
return value;
} | javascript | function handlebarsGet(root, path, options) {
var data = options && options.data;
var normalizedPath = normalizePath(root, path, data);
var value;
// In cases where the path begins with a keyword, change the
// root to the value represented by that keyword, and ensure
// the path is relative to it.
root = normalizedPath.root;
path = normalizedPath.path;
// Ember.get with a null root and GlobalPath will fall back to
// Ember.lookup, which is no longer allowed in templates.
//
// But when outputting a primitive, root will be the primitive
// and path a blank string. These primitives should pass through
// to `get`.
if (root || path === '') {
value = get(root, path);
}
if (detectIsGlobal(path)) {
if (value === undefined && root !== Ember.lookup) {
root = Ember.lookup;
value = get(root, path);
}
if (root === Ember.lookup || root === null) {
Ember.deprecate("Global lookup of "+path+" from a Handlebars template is deprecated.");
}
}
return value;
} | [
"function",
"handlebarsGet",
"(",
"root",
",",
"path",
",",
"options",
")",
"{",
"var",
"data",
"=",
"options",
"&&",
"options",
".",
"data",
";",
"var",
"normalizedPath",
"=",
"normalizePath",
"(",
"root",
",",
"path",
",",
"data",
")",
";",
"var",
"value",
";",
"root",
"=",
"normalizedPath",
".",
"root",
";",
"path",
"=",
"normalizedPath",
".",
"path",
";",
"if",
"(",
"root",
"||",
"path",
"===",
"''",
")",
"{",
"value",
"=",
"get",
"(",
"root",
",",
"path",
")",
";",
"}",
"if",
"(",
"detectIsGlobal",
"(",
"path",
")",
")",
"{",
"if",
"(",
"value",
"===",
"undefined",
"&&",
"root",
"!==",
"Ember",
".",
"lookup",
")",
"{",
"root",
"=",
"Ember",
".",
"lookup",
";",
"value",
"=",
"get",
"(",
"root",
",",
"path",
")",
";",
"}",
"if",
"(",
"root",
"===",
"Ember",
".",
"lookup",
"||",
"root",
"===",
"null",
")",
"{",
"Ember",
".",
"deprecate",
"(",
"\"Global lookup of \"",
"+",
"path",
"+",
"\" from a Handlebars template is deprecated.\"",
")",
";",
"}",
"}",
"return",
"value",
";",
"}"
] | Lookup both on root and on window. If the path starts with
a keyword, the corresponding object will be looked up in the
template's data hash and used to resolve the path.
@method get
@for Ember.Handlebars
@param {Object} root The object to look up the property on
@param {String} path The path to be lookedup
@param {Object} options The template's option hash | [
"Lookup",
"both",
"on",
"root",
"and",
"on",
"window",
".",
"If",
"the",
"path",
"starts",
"with",
"a",
"keyword",
"the",
"corresponding",
"object",
"will",
"be",
"looked",
"up",
"in",
"the",
"template",
"s",
"data",
"hash",
"and",
"used",
"to",
"resolve",
"the",
"path",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L6797-L6829 | train |
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | registerBoundHelper | function registerBoundHelper(name, fn) {
var boundHelperArgs = slice.call(arguments, 1);
var boundFn = makeBoundHelper.apply(this, boundHelperArgs);
EmberHandlebars.registerHelper(name, boundFn);
} | javascript | function registerBoundHelper(name, fn) {
var boundHelperArgs = slice.call(arguments, 1);
var boundFn = makeBoundHelper.apply(this, boundHelperArgs);
EmberHandlebars.registerHelper(name, boundFn);
} | [
"function",
"registerBoundHelper",
"(",
"name",
",",
"fn",
")",
"{",
"var",
"boundHelperArgs",
"=",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"var",
"boundFn",
"=",
"makeBoundHelper",
".",
"apply",
"(",
"this",
",",
"boundHelperArgs",
")",
";",
"EmberHandlebars",
".",
"registerHelper",
"(",
"name",
",",
"boundFn",
")",
";",
"}"
] | Register a bound handlebars helper. Bound helpers behave similarly to regular
handlebars helpers, with the added ability to re-render when the underlying data
changes.
## Simple example
```javascript
Ember.Handlebars.registerBoundHelper('capitalize', function(value) {
return Ember.String.capitalize(value);
});
```
The above bound helper can be used inside of templates as follows:
```handlebars
{{capitalize name}}
```
In this case, when the `name` property of the template's context changes,
the rendered value of the helper will update to reflect this change.
## Example with options
Like normal handlebars helpers, bound helpers have access to the options
passed into the helper call.
```javascript
Ember.Handlebars.registerBoundHelper('repeat', function(value, options) {
var count = options.hash.count;
var a = [];
while(a.length < count) {
a.push(value);
}
return a.join('');
});
```
This helper could be used in a template as follows:
```handlebars
{{repeat text count=3}}
```
## Example with bound options
Bound hash options are also supported. Example:
```handlebars
{{repeat text count=numRepeats}}
```
In this example, count will be bound to the value of
the `numRepeats` property on the context. If that property
changes, the helper will be re-rendered.
## Example with extra dependencies
The `Ember.Handlebars.registerBoundHelper` method takes a variable length
third parameter which indicates extra dependencies on the passed in value.
This allows the handlebars helper to update when these dependencies change.
```javascript
Ember.Handlebars.registerBoundHelper('capitalizeName', function(value) {
return value.get('name').toUpperCase();
}, 'name');
```
## Example with multiple bound properties
`Ember.Handlebars.registerBoundHelper` supports binding to
multiple properties, e.g.:
```javascript
Ember.Handlebars.registerBoundHelper('concatenate', function() {
var values = Array.prototype.slice.call(arguments, 0, -1);
return values.join('||');
});
```
Which allows for template syntax such as `{{concatenate prop1 prop2}}` or
`{{concatenate prop1 prop2 prop3}}`. If any of the properties change,
the helper will re-render. Note that dependency keys cannot be
using in conjunction with multi-property helpers, since it is ambiguous
which property the dependent keys would belong to.
## Use with unbound helper
The `{{unbound}}` helper can be used with bound helper invocations
to render them in their unbound form, e.g.
```handlebars
{{unbound capitalize name}}
```
In this example, if the name property changes, the helper
will not re-render.
## Use with blocks not supported
Bound helpers do not support use with Handlebars blocks or
the addition of child views of any kind.
@method registerBoundHelper
@for Ember.Handlebars
@param {String} name
@param {Function} function
@param {String} dependentKeys* | [
"Register",
"a",
"bound",
"handlebars",
"helper",
".",
"Bound",
"helpers",
"behave",
"similarly",
"to",
"regular",
"handlebars",
"helpers",
"with",
"the",
"added",
"ability",
"to",
"re",
"-",
"render",
"when",
"the",
"underlying",
"data",
"changes",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L7167-L7171 | train |
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | _triageMustacheHelper | function _triageMustacheHelper(property, options) {
Ember.assert("You cannot pass more than one argument to the _triageMustache helper", arguments.length <= 2);
var helper = EmberHandlebars.resolveHelper(options.data.view.container, property);
if (helper) {
return helper.call(this, options);
}
return helpers.bind.call(this, property, options);
} | javascript | function _triageMustacheHelper(property, options) {
Ember.assert("You cannot pass more than one argument to the _triageMustache helper", arguments.length <= 2);
var helper = EmberHandlebars.resolveHelper(options.data.view.container, property);
if (helper) {
return helper.call(this, options);
}
return helpers.bind.call(this, property, options);
} | [
"function",
"_triageMustacheHelper",
"(",
"property",
",",
"options",
")",
"{",
"Ember",
".",
"assert",
"(",
"\"You cannot pass more than one argument to the _triageMustache helper\"",
",",
"arguments",
".",
"length",
"<=",
"2",
")",
";",
"var",
"helper",
"=",
"EmberHandlebars",
".",
"resolveHelper",
"(",
"options",
".",
"data",
".",
"view",
".",
"container",
",",
"property",
")",
";",
"if",
"(",
"helper",
")",
"{",
"return",
"helper",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"}",
"return",
"helpers",
".",
"bind",
".",
"call",
"(",
"this",
",",
"property",
",",
"options",
")",
";",
"}"
] | '_triageMustache' is used internally select between a binding, helper, or component for
the given context. Until this point, it would be hard to determine if the
mustache is a property reference or a regular helper reference. This triage
helper resolves that.
This would not be typically invoked by directly.
@private
@method _triageMustache
@for Ember.Handlebars.helpers
@param {String} property Property/helperID to triage
@param {Object} options hash of template/rendering options
@return {String} HTML string | [
"_triageMustache",
"is",
"used",
"internally",
"select",
"between",
"a",
"binding",
"helper",
"or",
"component",
"for",
"the",
"given",
"context",
".",
"Until",
"this",
"point",
"it",
"would",
"be",
"hard",
"to",
"determine",
"if",
"the",
"mustache",
"is",
"a",
"property",
"reference",
"or",
"a",
"regular",
"helper",
"reference",
".",
"This",
"triage",
"helper",
"resolves",
"that",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L7641-L7650 | train |
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | bindClasses | function bindClasses(context, classBindings, view, bindAttrId, options) {
var ret = [];
var newClass, value, elem;
// Helper method to retrieve the property from the context and
// determine which class string to return, based on whether it is
// a Boolean or not.
var classStringForPath = function(root, parsedPath, options) {
var val;
var path = parsedPath.path;
if (path === 'this') {
val = root;
} else if (path === '') {
val = true;
} else {
val = handlebarsGet(root, path, options);
}
return View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName);
};
// For each property passed, loop through and setup
// an observer.
forEach.call(classBindings.split(' '), function(binding) {
// Variable in which the old class value is saved. The observer function
// closes over this variable, so it knows which string to remove when
// the property changes.
var oldClass;
var observer;
var parsedPath = View._parsePropertyPath(binding);
var path = parsedPath.path;
var pathRoot = context;
var normalized;
if (path !== '' && path !== 'this') {
normalized = normalizePath(context, path, options.data);
pathRoot = normalized.root;
path = normalized.path;
}
// Set up an observer on the context. If the property changes, toggle the
// class name.
observer = function() {
// Get the current value of the property
newClass = classStringForPath(context, parsedPath, options);
elem = bindAttrId ? view.$("[data-bindattr-" + bindAttrId + "='" + bindAttrId + "']") : view.$();
// If we can't find the element anymore, a parent template has been
// re-rendered and we've been nuked. Remove the observer.
if (!elem || elem.length === 0) {
removeObserver(pathRoot, path, observer);
} else {
// If we had previously added a class to the element, remove it.
if (oldClass) {
elem.removeClass(oldClass);
}
// If necessary, add a new class. Make sure we keep track of it so
// it can be removed in the future.
if (newClass) {
elem.addClass(newClass);
oldClass = newClass;
} else {
oldClass = null;
}
}
};
if (path !== '' && path !== 'this') {
view.registerObserver(pathRoot, path, observer);
}
// We've already setup the observer; now we just need to figure out the
// correct behavior right now on the first pass through.
value = classStringForPath(context, parsedPath, options);
if (value) {
ret.push(value);
// Make sure we save the current value so that it can be removed if the
// observer fires.
oldClass = value;
}
});
return ret;
} | javascript | function bindClasses(context, classBindings, view, bindAttrId, options) {
var ret = [];
var newClass, value, elem;
// Helper method to retrieve the property from the context and
// determine which class string to return, based on whether it is
// a Boolean or not.
var classStringForPath = function(root, parsedPath, options) {
var val;
var path = parsedPath.path;
if (path === 'this') {
val = root;
} else if (path === '') {
val = true;
} else {
val = handlebarsGet(root, path, options);
}
return View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName);
};
// For each property passed, loop through and setup
// an observer.
forEach.call(classBindings.split(' '), function(binding) {
// Variable in which the old class value is saved. The observer function
// closes over this variable, so it knows which string to remove when
// the property changes.
var oldClass;
var observer;
var parsedPath = View._parsePropertyPath(binding);
var path = parsedPath.path;
var pathRoot = context;
var normalized;
if (path !== '' && path !== 'this') {
normalized = normalizePath(context, path, options.data);
pathRoot = normalized.root;
path = normalized.path;
}
// Set up an observer on the context. If the property changes, toggle the
// class name.
observer = function() {
// Get the current value of the property
newClass = classStringForPath(context, parsedPath, options);
elem = bindAttrId ? view.$("[data-bindattr-" + bindAttrId + "='" + bindAttrId + "']") : view.$();
// If we can't find the element anymore, a parent template has been
// re-rendered and we've been nuked. Remove the observer.
if (!elem || elem.length === 0) {
removeObserver(pathRoot, path, observer);
} else {
// If we had previously added a class to the element, remove it.
if (oldClass) {
elem.removeClass(oldClass);
}
// If necessary, add a new class. Make sure we keep track of it so
// it can be removed in the future.
if (newClass) {
elem.addClass(newClass);
oldClass = newClass;
} else {
oldClass = null;
}
}
};
if (path !== '' && path !== 'this') {
view.registerObserver(pathRoot, path, observer);
}
// We've already setup the observer; now we just need to figure out the
// correct behavior right now on the first pass through.
value = classStringForPath(context, parsedPath, options);
if (value) {
ret.push(value);
// Make sure we save the current value so that it can be removed if the
// observer fires.
oldClass = value;
}
});
return ret;
} | [
"function",
"bindClasses",
"(",
"context",
",",
"classBindings",
",",
"view",
",",
"bindAttrId",
",",
"options",
")",
"{",
"var",
"ret",
"=",
"[",
"]",
";",
"var",
"newClass",
",",
"value",
",",
"elem",
";",
"var",
"classStringForPath",
"=",
"function",
"(",
"root",
",",
"parsedPath",
",",
"options",
")",
"{",
"var",
"val",
";",
"var",
"path",
"=",
"parsedPath",
".",
"path",
";",
"if",
"(",
"path",
"===",
"'this'",
")",
"{",
"val",
"=",
"root",
";",
"}",
"else",
"if",
"(",
"path",
"===",
"''",
")",
"{",
"val",
"=",
"true",
";",
"}",
"else",
"{",
"val",
"=",
"handlebarsGet",
"(",
"root",
",",
"path",
",",
"options",
")",
";",
"}",
"return",
"View",
".",
"_classStringForValue",
"(",
"path",
",",
"val",
",",
"parsedPath",
".",
"className",
",",
"parsedPath",
".",
"falsyClassName",
")",
";",
"}",
";",
"forEach",
".",
"call",
"(",
"classBindings",
".",
"split",
"(",
"' '",
")",
",",
"function",
"(",
"binding",
")",
"{",
"var",
"oldClass",
";",
"var",
"observer",
";",
"var",
"parsedPath",
"=",
"View",
".",
"_parsePropertyPath",
"(",
"binding",
")",
";",
"var",
"path",
"=",
"parsedPath",
".",
"path",
";",
"var",
"pathRoot",
"=",
"context",
";",
"var",
"normalized",
";",
"if",
"(",
"path",
"!==",
"''",
"&&",
"path",
"!==",
"'this'",
")",
"{",
"normalized",
"=",
"normalizePath",
"(",
"context",
",",
"path",
",",
"options",
".",
"data",
")",
";",
"pathRoot",
"=",
"normalized",
".",
"root",
";",
"path",
"=",
"normalized",
".",
"path",
";",
"}",
"observer",
"=",
"function",
"(",
")",
"{",
"newClass",
"=",
"classStringForPath",
"(",
"context",
",",
"parsedPath",
",",
"options",
")",
";",
"elem",
"=",
"bindAttrId",
"?",
"view",
".",
"$",
"(",
"\"[data-bindattr-\"",
"+",
"bindAttrId",
"+",
"\"='\"",
"+",
"bindAttrId",
"+",
"\"']\"",
")",
":",
"view",
".",
"$",
"(",
")",
";",
"if",
"(",
"!",
"elem",
"||",
"elem",
".",
"length",
"===",
"0",
")",
"{",
"removeObserver",
"(",
"pathRoot",
",",
"path",
",",
"observer",
")",
";",
"}",
"else",
"{",
"if",
"(",
"oldClass",
")",
"{",
"elem",
".",
"removeClass",
"(",
"oldClass",
")",
";",
"}",
"if",
"(",
"newClass",
")",
"{",
"elem",
".",
"addClass",
"(",
"newClass",
")",
";",
"oldClass",
"=",
"newClass",
";",
"}",
"else",
"{",
"oldClass",
"=",
"null",
";",
"}",
"}",
"}",
";",
"if",
"(",
"path",
"!==",
"''",
"&&",
"path",
"!==",
"'this'",
")",
"{",
"view",
".",
"registerObserver",
"(",
"pathRoot",
",",
"path",
",",
"observer",
")",
";",
"}",
"value",
"=",
"classStringForPath",
"(",
"context",
",",
"parsedPath",
",",
"options",
")",
";",
"if",
"(",
"value",
")",
"{",
"ret",
".",
"push",
"(",
"value",
")",
";",
"oldClass",
"=",
"value",
";",
"}",
"}",
")",
";",
"return",
"ret",
";",
"}"
] | Helper that, given a space-separated string of property paths and a context,
returns an array of class names. Calling this method also has the side
effect of setting up observers at those property paths, such that if they
change, the correct class name will be reapplied to the DOM element.
For example, if you pass the string "fooBar", it will first look up the
"fooBar" value of the context. If that value is true, it will add the
"foo-bar" class to the current element (i.e., the dasherized form of
"fooBar"). If the value is a string, it will add that string as the class.
Otherwise, it will not add any new class name.
@private
@method bindClasses
@for Ember.Handlebars
@param {Ember.Object} context The context from which to lookup properties
@param {String} classBindings A string, space-separated, of class bindings
to use
@param {View} view The view in which observers should look for the
element to update
@param {Srting} bindAttrId Optional bindAttr id used to lookup elements
@return {Array} An array of class names to add | [
"Helper",
"that",
"given",
"a",
"space",
"-",
"separated",
"string",
"of",
"property",
"paths",
"and",
"a",
"context",
"returns",
"an",
"array",
"of",
"class",
"names",
".",
"Calling",
"this",
"method",
"also",
"has",
"the",
"side",
"effect",
"of",
"setting",
"up",
"observers",
"at",
"those",
"property",
"paths",
"such",
"that",
"if",
"they",
"change",
"the",
"correct",
"class",
"name",
"will",
"be",
"reapplied",
"to",
"the",
"DOM",
"element",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L8234-L8323 | train |
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | function(buffer) {
// If not invoked via a triple-mustache ({{{foo}}}), escape
// the content of the template.
var escape = get(this, 'isEscaped');
var shouldDisplay = get(this, 'shouldDisplayFunc');
var preserveContext = get(this, 'preserveContext');
var context = get(this, 'previousContext');
var inverseTemplate = get(this, 'inverseTemplate');
var displayTemplate = get(this, 'displayTemplate');
var result = this.normalizedValue();
this._lastNormalizedValue = result;
// First, test the conditional to see if we should
// render the template or not.
if (shouldDisplay(result)) {
set(this, 'template', displayTemplate);
// If we are preserving the context (for example, if this
// is an #if block, call the template with the same object.
if (preserveContext) {
set(this, '_context', context);
} else {
// Otherwise, determine if this is a block bind or not.
// If so, pass the specified object to the template
if (displayTemplate) {
set(this, '_context', result);
} else {
// This is not a bind block, just push the result of the
// expression to the render context and return.
if (result === null || result === undefined) {
result = "";
} else if (!(result instanceof SafeString)) {
result = String(result);
}
if (escape) { result = Handlebars.Utils.escapeExpression(result); }
buffer.push(result);
return;
}
}
} else if (inverseTemplate) {
set(this, 'template', inverseTemplate);
if (preserveContext) {
set(this, '_context', context);
} else {
set(this, '_context', result);
}
} else {
set(this, 'template', function() { return ''; });
}
return this._super(buffer);
} | javascript | function(buffer) {
// If not invoked via a triple-mustache ({{{foo}}}), escape
// the content of the template.
var escape = get(this, 'isEscaped');
var shouldDisplay = get(this, 'shouldDisplayFunc');
var preserveContext = get(this, 'preserveContext');
var context = get(this, 'previousContext');
var inverseTemplate = get(this, 'inverseTemplate');
var displayTemplate = get(this, 'displayTemplate');
var result = this.normalizedValue();
this._lastNormalizedValue = result;
// First, test the conditional to see if we should
// render the template or not.
if (shouldDisplay(result)) {
set(this, 'template', displayTemplate);
// If we are preserving the context (for example, if this
// is an #if block, call the template with the same object.
if (preserveContext) {
set(this, '_context', context);
} else {
// Otherwise, determine if this is a block bind or not.
// If so, pass the specified object to the template
if (displayTemplate) {
set(this, '_context', result);
} else {
// This is not a bind block, just push the result of the
// expression to the render context and return.
if (result === null || result === undefined) {
result = "";
} else if (!(result instanceof SafeString)) {
result = String(result);
}
if (escape) { result = Handlebars.Utils.escapeExpression(result); }
buffer.push(result);
return;
}
}
} else if (inverseTemplate) {
set(this, 'template', inverseTemplate);
if (preserveContext) {
set(this, '_context', context);
} else {
set(this, '_context', result);
}
} else {
set(this, 'template', function() { return ''; });
}
return this._super(buffer);
} | [
"function",
"(",
"buffer",
")",
"{",
"var",
"escape",
"=",
"get",
"(",
"this",
",",
"'isEscaped'",
")",
";",
"var",
"shouldDisplay",
"=",
"get",
"(",
"this",
",",
"'shouldDisplayFunc'",
")",
";",
"var",
"preserveContext",
"=",
"get",
"(",
"this",
",",
"'preserveContext'",
")",
";",
"var",
"context",
"=",
"get",
"(",
"this",
",",
"'previousContext'",
")",
";",
"var",
"inverseTemplate",
"=",
"get",
"(",
"this",
",",
"'inverseTemplate'",
")",
";",
"var",
"displayTemplate",
"=",
"get",
"(",
"this",
",",
"'displayTemplate'",
")",
";",
"var",
"result",
"=",
"this",
".",
"normalizedValue",
"(",
")",
";",
"this",
".",
"_lastNormalizedValue",
"=",
"result",
";",
"if",
"(",
"shouldDisplay",
"(",
"result",
")",
")",
"{",
"set",
"(",
"this",
",",
"'template'",
",",
"displayTemplate",
")",
";",
"if",
"(",
"preserveContext",
")",
"{",
"set",
"(",
"this",
",",
"'_context'",
",",
"context",
")",
";",
"}",
"else",
"{",
"if",
"(",
"displayTemplate",
")",
"{",
"set",
"(",
"this",
",",
"'_context'",
",",
"result",
")",
";",
"}",
"else",
"{",
"if",
"(",
"result",
"===",
"null",
"||",
"result",
"===",
"undefined",
")",
"{",
"result",
"=",
"\"\"",
";",
"}",
"else",
"if",
"(",
"!",
"(",
"result",
"instanceof",
"SafeString",
")",
")",
"{",
"result",
"=",
"String",
"(",
"result",
")",
";",
"}",
"if",
"(",
"escape",
")",
"{",
"result",
"=",
"Handlebars",
".",
"Utils",
".",
"escapeExpression",
"(",
"result",
")",
";",
"}",
"buffer",
".",
"push",
"(",
"result",
")",
";",
"return",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"inverseTemplate",
")",
"{",
"set",
"(",
"this",
",",
"'template'",
",",
"inverseTemplate",
")",
";",
"if",
"(",
"preserveContext",
")",
"{",
"set",
"(",
"this",
",",
"'_context'",
",",
"context",
")",
";",
"}",
"else",
"{",
"set",
"(",
"this",
",",
"'_context'",
",",
"result",
")",
";",
"}",
"}",
"else",
"{",
"set",
"(",
"this",
",",
"'template'",
",",
"function",
"(",
")",
"{",
"return",
"''",
";",
"}",
")",
";",
"}",
"return",
"this",
".",
"_super",
"(",
"buffer",
")",
";",
"}"
] | Determines which template to invoke, sets up the correct state based on
that logic, then invokes the default `Ember.View` `render` implementation.
This method will first look up the `path` key on `pathRoot`,
then pass that value to the `shouldDisplayFunc` function. If that returns
`true,` the `displayTemplate` function will be rendered to DOM. Otherwise,
`inverseTemplate`, if specified, will be rendered.
For example, if this `Ember._HandlebarsBoundView` represented the `{{#with
foo}}` helper, it would look up the `foo` property of its context, and
`shouldDisplayFunc` would always return true. The object found by looking
up `foo` would be passed to `displayTemplate`.
@method render
@param {Ember.RenderBuffer} buffer | [
"Determines",
"which",
"template",
"to",
"invoke",
"sets",
"up",
"the",
"correct",
"state",
"based",
"on",
"that",
"logic",
"then",
"invokes",
"the",
"default",
"Ember",
".",
"View",
"render",
"implementation",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L10427-L10484 | train |
|
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | flushPendingChains | function flushPendingChains() {
if (pendingQueue.length === 0) { return; } // nothing to do
var queue = pendingQueue;
pendingQueue = [];
forEach.call(queue, function(q) { q[0].add(q[1]); });
warn('Watching an undefined global, Ember expects watched globals to be setup by the time the run loop is flushed, check for typos', pendingQueue.length === 0);
} | javascript | function flushPendingChains() {
if (pendingQueue.length === 0) { return; } // nothing to do
var queue = pendingQueue;
pendingQueue = [];
forEach.call(queue, function(q) { q[0].add(q[1]); });
warn('Watching an undefined global, Ember expects watched globals to be setup by the time the run loop is flushed, check for typos', pendingQueue.length === 0);
} | [
"function",
"flushPendingChains",
"(",
")",
"{",
"if",
"(",
"pendingQueue",
".",
"length",
"===",
"0",
")",
"{",
"return",
";",
"}",
"var",
"queue",
"=",
"pendingQueue",
";",
"pendingQueue",
"=",
"[",
"]",
";",
"forEach",
".",
"call",
"(",
"queue",
",",
"function",
"(",
"q",
")",
"{",
"q",
"[",
"0",
"]",
".",
"add",
"(",
"q",
"[",
"1",
"]",
")",
";",
"}",
")",
";",
"warn",
"(",
"'Watching an undefined global, Ember expects watched globals to be setup by the time the run loop is flushed, check for typos'",
",",
"pendingQueue",
".",
"length",
"===",
"0",
")",
";",
"}"
] | attempts to add the pendingQueue chains again. If some of them end up back in the queue and reschedule is true, schedules a timeout to try again. | [
"attempts",
"to",
"add",
"the",
"pendingQueue",
"chains",
"again",
".",
"If",
"some",
"of",
"them",
"end",
"up",
"back",
"in",
"the",
"queue",
"and",
"reschedule",
"is",
"true",
"schedules",
"a",
"timeout",
"to",
"try",
"again",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L11972-L11981 | train |
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | deprecateProperty | function deprecateProperty(object, deprecatedKey, newKey) {
function deprecate() {
Ember.deprecate('Usage of `' + deprecatedKey + '` is deprecated, use `' + newKey + '` instead.');
}
if (hasPropertyAccessors) {
defineProperty(object, deprecatedKey, {
configurable: true,
enumerable: false,
set: function(value) { deprecate(); set(this, newKey, value); },
get: function() { deprecate(); return get(this, newKey); }
});
}
} | javascript | function deprecateProperty(object, deprecatedKey, newKey) {
function deprecate() {
Ember.deprecate('Usage of `' + deprecatedKey + '` is deprecated, use `' + newKey + '` instead.');
}
if (hasPropertyAccessors) {
defineProperty(object, deprecatedKey, {
configurable: true,
enumerable: false,
set: function(value) { deprecate(); set(this, newKey, value); },
get: function() { deprecate(); return get(this, newKey); }
});
}
} | [
"function",
"deprecateProperty",
"(",
"object",
",",
"deprecatedKey",
",",
"newKey",
")",
"{",
"function",
"deprecate",
"(",
")",
"{",
"Ember",
".",
"deprecate",
"(",
"'Usage of `'",
"+",
"deprecatedKey",
"+",
"'` is deprecated, use `'",
"+",
"newKey",
"+",
"'` instead.'",
")",
";",
"}",
"if",
"(",
"hasPropertyAccessors",
")",
"{",
"defineProperty",
"(",
"object",
",",
"deprecatedKey",
",",
"{",
"configurable",
":",
"true",
",",
"enumerable",
":",
"false",
",",
"set",
":",
"function",
"(",
"value",
")",
"{",
"deprecate",
"(",
")",
";",
"set",
"(",
"this",
",",
"newKey",
",",
"value",
")",
";",
"}",
",",
"get",
":",
"function",
"(",
")",
"{",
"deprecate",
"(",
")",
";",
"return",
"get",
"(",
"this",
",",
"newKey",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] | Used internally to allow changing properties in a backwards compatible way, and print a helpful
deprecation warning.
@method deprecateProperty
@param {Object} object The object to add the deprecated property to.
@param {String} deprecatedKey The property to add (and print deprecation warnings upon accessing).
@param {String} newKey The property that will be aliased.
@private
@since 1.7.0 | [
"Used",
"internally",
"to",
"allow",
"changing",
"properties",
"in",
"a",
"backwards",
"compatible",
"way",
"and",
"print",
"a",
"helpful",
"deprecation",
"warning",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L13951-L13964 | train |
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | indexOf | function indexOf(obj, element, index) {
return obj.indexOf ? obj.indexOf(element, index) : _indexOf.call(obj, element, index);
} | javascript | function indexOf(obj, element, index) {
return obj.indexOf ? obj.indexOf(element, index) : _indexOf.call(obj, element, index);
} | [
"function",
"indexOf",
"(",
"obj",
",",
"element",
",",
"index",
")",
"{",
"return",
"obj",
".",
"indexOf",
"?",
"obj",
".",
"indexOf",
"(",
"element",
",",
"index",
")",
":",
"_indexOf",
".",
"call",
"(",
"obj",
",",
"element",
",",
"index",
")",
";",
"}"
] | Calls the indexOf function on the passed object with a specified callback. This
uses `Ember.ArrayPolyfill`'s-indexOf method when necessary.
@method indexOf
@param {Object} obj The object to call indexOn on
@param {Function} callback The callback to execute
@param {Object} index The index to start searching from | [
"Calls",
"the",
"indexOf",
"function",
"on",
"the",
"passed",
"object",
"with",
"a",
"specified",
"callback",
".",
"This",
"uses",
"Ember",
".",
"ArrayPolyfill",
"s",
"-",
"indexOf",
"method",
"when",
"necessary",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L14061-L14063 | train |
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | indexesOf | function indexesOf(obj, elements) {
return elements === undefined ? [] : map(elements, function(item) {
return indexOf(obj, item);
});
} | javascript | function indexesOf(obj, elements) {
return elements === undefined ? [] : map(elements, function(item) {
return indexOf(obj, item);
});
} | [
"function",
"indexesOf",
"(",
"obj",
",",
"elements",
")",
"{",
"return",
"elements",
"===",
"undefined",
"?",
"[",
"]",
":",
"map",
"(",
"elements",
",",
"function",
"(",
"item",
")",
"{",
"return",
"indexOf",
"(",
"obj",
",",
"item",
")",
";",
"}",
")",
";",
"}"
] | Returns an array of indexes of the first occurrences of the passed elements
on the passed object.
```javascript
var array = [1, 2, 3, 4, 5];
Ember.EnumerableUtils.indexesOf(array, [2, 5]); // [1, 4]
var fubar = "Fubarr";
Ember.EnumerableUtils.indexesOf(fubar, ['b', 'r']); // [2, 4]
```
@method indexesOf
@param {Object} obj The object to check for element indexes
@param {Array} elements The elements to search for on *obj*
@return {Array} An array of indexes. | [
"Returns",
"an",
"array",
"of",
"indexes",
"of",
"the",
"first",
"occurrences",
"of",
"the",
"passed",
"elements",
"on",
"the",
"passed",
"object",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L14084-L14088 | train |
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | addObject | function addObject(array, item) {
var index = indexOf(array, item);
if (index === -1) { array.push(item); }
} | javascript | function addObject(array, item) {
var index = indexOf(array, item);
if (index === -1) { array.push(item); }
} | [
"function",
"addObject",
"(",
"array",
",",
"item",
")",
"{",
"var",
"index",
"=",
"indexOf",
"(",
"array",
",",
"item",
")",
";",
"if",
"(",
"index",
"===",
"-",
"1",
")",
"{",
"array",
".",
"push",
"(",
"item",
")",
";",
"}",
"}"
] | Adds an object to an array. If the array already includes the object this
method has no effect.
@method addObject
@param {Array} array The array the passed item should be added to
@param {Object} item The item to add to the passed array
@return 'undefined' | [
"Adds",
"an",
"object",
"to",
"an",
"array",
".",
"If",
"the",
"array",
"already",
"includes",
"the",
"object",
"this",
"method",
"has",
"no",
"effect",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L14100-L14103 | train |
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | intersection | function intersection(array1, array2) {
var result = [];
forEach(array1, function(element) {
if (indexOf(array2, element) >= 0) {
result.push(element);
}
});
return result;
} | javascript | function intersection(array1, array2) {
var result = [];
forEach(array1, function(element) {
if (indexOf(array2, element) >= 0) {
result.push(element);
}
});
return result;
} | [
"function",
"intersection",
"(",
"array1",
",",
"array2",
")",
"{",
"var",
"result",
"=",
"[",
"]",
";",
"forEach",
"(",
"array1",
",",
"function",
"(",
"element",
")",
"{",
"if",
"(",
"indexOf",
"(",
"array2",
",",
"element",
")",
">=",
"0",
")",
"{",
"result",
".",
"push",
"(",
"element",
")",
";",
"}",
"}",
")",
";",
"return",
"result",
";",
"}"
] | Calculates the intersection of two arrays. This method returns a new array
filled with the records that the two passed arrays share with each other.
If there is no intersection, an empty array will be returned.
```javascript
var array1 = [1, 2, 3, 4, 5];
var array2 = [1, 3, 5, 6, 7];
Ember.EnumerableUtils.intersection(array1, array2); // [1, 3, 5]
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
Ember.EnumerableUtils.intersection(array1, array2); // []
```
@method intersection
@param {Array} array1 The first array
@param {Array} array2 The second array
@return {Array} The intersection of the two passed arrays. | [
"Calculates",
"the",
"intersection",
"of",
"two",
"arrays",
".",
"This",
"method",
"returns",
"a",
"new",
"array",
"filled",
"with",
"the",
"records",
"that",
"the",
"two",
"passed",
"arrays",
"share",
"with",
"each",
"other",
".",
"If",
"there",
"is",
"no",
"intersection",
"an",
"empty",
"array",
"will",
"be",
"returned",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L14200-L14209 | train |
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | watchedEvents | function watchedEvents(obj) {
var listeners = obj['__ember_meta__'].listeners, ret = [];
if (listeners) {
for(var eventName in listeners) {
if (listeners[eventName]) { ret.push(eventName); }
}
}
return ret;
} | javascript | function watchedEvents(obj) {
var listeners = obj['__ember_meta__'].listeners, ret = [];
if (listeners) {
for(var eventName in listeners) {
if (listeners[eventName]) { ret.push(eventName); }
}
}
return ret;
} | [
"function",
"watchedEvents",
"(",
"obj",
")",
"{",
"var",
"listeners",
"=",
"obj",
"[",
"'__ember_meta__'",
"]",
".",
"listeners",
",",
"ret",
"=",
"[",
"]",
";",
"if",
"(",
"listeners",
")",
"{",
"for",
"(",
"var",
"eventName",
"in",
"listeners",
")",
"{",
"if",
"(",
"listeners",
"[",
"eventName",
"]",
")",
"{",
"ret",
".",
"push",
"(",
"eventName",
")",
";",
"}",
"}",
"}",
"return",
"ret",
";",
"}"
] | Return a list of currently watched events
@private
@method watchedEvents
@for Ember
@param obj | [
"Return",
"a",
"list",
"of",
"currently",
"watched",
"events"
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L14564-L14573 | train |
appiphony/appiphony-lightning-js | public/lib/emberjs/ember.js | isEmpty | function isEmpty(obj) {
var none = isNone(obj);
if (none) {
return none;
}
if (typeof obj.size === 'number') {
return !obj.size;
}
var objectType = typeof obj;
if (objectType === 'object') {
var size = get(obj, 'size');
if (typeof size === 'number') {
return !size;
}
}
if (typeof obj.length === 'number' && objectType !== 'function') {
return !obj.length;
}
if (objectType === 'object') {
var length = get(obj, 'length');
if (typeof length === 'number') {
return !length;
}
}
return false;
} | javascript | function isEmpty(obj) {
var none = isNone(obj);
if (none) {
return none;
}
if (typeof obj.size === 'number') {
return !obj.size;
}
var objectType = typeof obj;
if (objectType === 'object') {
var size = get(obj, 'size');
if (typeof size === 'number') {
return !size;
}
}
if (typeof obj.length === 'number' && objectType !== 'function') {
return !obj.length;
}
if (objectType === 'object') {
var length = get(obj, 'length');
if (typeof length === 'number') {
return !length;
}
}
return false;
} | [
"function",
"isEmpty",
"(",
"obj",
")",
"{",
"var",
"none",
"=",
"isNone",
"(",
"obj",
")",
";",
"if",
"(",
"none",
")",
"{",
"return",
"none",
";",
"}",
"if",
"(",
"typeof",
"obj",
".",
"size",
"===",
"'number'",
")",
"{",
"return",
"!",
"obj",
".",
"size",
";",
"}",
"var",
"objectType",
"=",
"typeof",
"obj",
";",
"if",
"(",
"objectType",
"===",
"'object'",
")",
"{",
"var",
"size",
"=",
"get",
"(",
"obj",
",",
"'size'",
")",
";",
"if",
"(",
"typeof",
"size",
"===",
"'number'",
")",
"{",
"return",
"!",
"size",
";",
"}",
"}",
"if",
"(",
"typeof",
"obj",
".",
"length",
"===",
"'number'",
"&&",
"objectType",
"!==",
"'function'",
")",
"{",
"return",
"!",
"obj",
".",
"length",
";",
"}",
"if",
"(",
"objectType",
"===",
"'object'",
")",
"{",
"var",
"length",
"=",
"get",
"(",
"obj",
",",
"'length'",
")",
";",
"if",
"(",
"typeof",
"length",
"===",
"'number'",
")",
"{",
"return",
"!",
"length",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Verifies that a value is `null` or an empty string, empty array,
or empty function.
Constrains the rules on `Ember.isNone` by returning true for empty
string and empty arrays.
```javascript
Ember.isEmpty(); // true
Ember.isEmpty(null); // true
Ember.isEmpty(undefined); // true
Ember.isEmpty(''); // true
Ember.isEmpty([]); // true
Ember.isEmpty('Adam Hawkins'); // false
Ember.isEmpty([0,1,2]); // false
```
@method isEmpty
@for Ember
@param {Object} obj Value to test
@return {Boolean} | [
"Verifies",
"that",
"a",
"value",
"is",
"null",
"or",
"an",
"empty",
"string",
"empty",
"array",
"or",
"empty",
"function",
"."
] | 704953fdc60b62d3073fc5cace716a201d38b36c | https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L15128-L15159 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.