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
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
moraispgsi/fsm-core | src/indexOld.js | getInstanceInfo | function getInstanceInfo(machineName, versionKey, instanceKey) {
let route = getInstanceInfoRoute(machineName, versionKey, instanceKey);
return jsonfile.readFileSync(repositoryPath + "/" + route);
} | javascript | function getInstanceInfo(machineName, versionKey, instanceKey) {
let route = getInstanceInfoRoute(machineName, versionKey, instanceKey);
return jsonfile.readFileSync(repositoryPath + "/" + route);
} | [
"function",
"getInstanceInfo",
"(",
"machineName",
",",
"versionKey",
",",
"instanceKey",
")",
"{",
"let",
"route",
"=",
"getInstanceInfoRoute",
"(",
"machineName",
",",
"versionKey",
",",
"instanceKey",
")",
";",
"return",
"jsonfile",
".",
"readFileSync",
"(",
"repositoryPath",
"+",
"\"/\"",
"+",
"route",
")",
";",
"}"
]
| Retrieve the instance's info.json file as a JavasScript Object
@method getInstanceInfo
@param {String} machineName The name of the machine
@param {String} versionKey The key of the version
@param {String} instanceKey The key of the instance
@returns {Object} The info Object | [
"Retrieve",
"the",
"instance",
"s",
"info",
".",
"json",
"file",
"as",
"a",
"JavasScript",
"Object"
]
| c07e7c1509b823d5c438a26b29fbf8f40e1e8be7 | https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L661-L664 | train |
moraispgsi/fsm-core | src/indexOld.js | setInstanceInfo | function setInstanceInfo(machineName, versionKey, instanceKey, info, withCommit, message) {
let route = getInstanceInfoRoute(machineName, versionKey, instanceKey);
jsonfile.writeFileSync(repositoryPath + "/" + route, info, {spaces: 2});
if(withCommit) {
return _commit(null, [route],
message || "Changed the info for the " + instanceKey + " of the " +
versionKey + " of the '" + machineName + "' machine");
}
} | javascript | function setInstanceInfo(machineName, versionKey, instanceKey, info, withCommit, message) {
let route = getInstanceInfoRoute(machineName, versionKey, instanceKey);
jsonfile.writeFileSync(repositoryPath + "/" + route, info, {spaces: 2});
if(withCommit) {
return _commit(null, [route],
message || "Changed the info for the " + instanceKey + " of the " +
versionKey + " of the '" + machineName + "' machine");
}
} | [
"function",
"setInstanceInfo",
"(",
"machineName",
",",
"versionKey",
",",
"instanceKey",
",",
"info",
",",
"withCommit",
",",
"message",
")",
"{",
"let",
"route",
"=",
"getInstanceInfoRoute",
"(",
"machineName",
",",
"versionKey",
",",
"instanceKey",
")",
";",
"jsonfile",
".",
"writeFileSync",
"(",
"repositoryPath",
"+",
"\"/\"",
"+",
"route",
",",
"info",
",",
"{",
"spaces",
":",
"2",
"}",
")",
";",
"if",
"(",
"withCommit",
")",
"{",
"return",
"_commit",
"(",
"null",
",",
"[",
"route",
"]",
",",
"message",
"||",
"\"Changed the info for the \"",
"+",
"instanceKey",
"+",
"\" of the \"",
"+",
"versionKey",
"+",
"\" of the '\"",
"+",
"machineName",
"+",
"\"' machine\"",
")",
";",
"}",
"}"
]
| Update the instance's info.json file using a JavasScript Object
@method setInstanceInfo
@param {String} machineName The name of the machine
@param {String} versionKey The key of the version
@param {String} instanceKey The key of the instance
@param {Object} info The info Object to save
@param {boolean} withCommit If true commits the changes to the repository
@param {String} message If supplied it is used as the message for the commit
@returns {Promise} If withCommit is true, the function returns a Promise | [
"Update",
"the",
"instance",
"s",
"info",
".",
"json",
"file",
"using",
"a",
"JavasScript",
"Object"
]
| c07e7c1509b823d5c438a26b29fbf8f40e1e8be7 | https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L677-L688 | train |
moraispgsi/fsm-core | src/indexOld.js | addInstance | function addInstance(machineName, versionKey) {
return co(function*() {
debug("Adding a new instance to the " + versionKey + " of the '" + machineName + "' machine");
let manifest = getManifest();
let machine = manifest.machines[machineName];
if (!machine) {
throw new Error("Machine does not exists");
}
let version = machine.versions[versionKey];
if (!version) {
throw new Error("Version does not exists");
}
let versionInfo = getVersionInfo(machineName, versionKey);
if(!versionInfo.isSealed) {
throw new Error("The version is not sealed yet");
}
let newInstanceKey = "instance" + (Object.keys(version.instances).length + 1);
let instanceDirPath = version.route + "/instances/" + newInstanceKey;
let instanceSnapshotsDirPath = instanceDirPath + "/snapshots";
version.instances[newInstanceKey] = {
"route": instanceDirPath,
"snapshots": {}
};
let infoFile = instanceDirPath + "/info.json";
debug("Creating the directories");
fs.mkdirSync(repositoryPath + "/" + instanceDirPath);
fs.mkdirSync(repositoryPath + "/" + instanceSnapshotsDirPath);
debug("Creating the instance info.json file");
let info = {
"hasStarted": false,
"hasEnded": false
};
jsonfile.writeFileSync(repositoryPath + "/" + infoFile, info);
debug("Setting the manifest");
setManifest(manifest);
yield _commit(null, ["manifest.json", infoFile],
"Created the "+newInstanceKey+" for the "+versionKey+" of the '" + machineName + "' machine");
return newInstanceKey;
});
} | javascript | function addInstance(machineName, versionKey) {
return co(function*() {
debug("Adding a new instance to the " + versionKey + " of the '" + machineName + "' machine");
let manifest = getManifest();
let machine = manifest.machines[machineName];
if (!machine) {
throw new Error("Machine does not exists");
}
let version = machine.versions[versionKey];
if (!version) {
throw new Error("Version does not exists");
}
let versionInfo = getVersionInfo(machineName, versionKey);
if(!versionInfo.isSealed) {
throw new Error("The version is not sealed yet");
}
let newInstanceKey = "instance" + (Object.keys(version.instances).length + 1);
let instanceDirPath = version.route + "/instances/" + newInstanceKey;
let instanceSnapshotsDirPath = instanceDirPath + "/snapshots";
version.instances[newInstanceKey] = {
"route": instanceDirPath,
"snapshots": {}
};
let infoFile = instanceDirPath + "/info.json";
debug("Creating the directories");
fs.mkdirSync(repositoryPath + "/" + instanceDirPath);
fs.mkdirSync(repositoryPath + "/" + instanceSnapshotsDirPath);
debug("Creating the instance info.json file");
let info = {
"hasStarted": false,
"hasEnded": false
};
jsonfile.writeFileSync(repositoryPath + "/" + infoFile, info);
debug("Setting the manifest");
setManifest(manifest);
yield _commit(null, ["manifest.json", infoFile],
"Created the "+newInstanceKey+" for the "+versionKey+" of the '" + machineName + "' machine");
return newInstanceKey;
});
} | [
"function",
"addInstance",
"(",
"machineName",
",",
"versionKey",
")",
"{",
"return",
"co",
"(",
"function",
"*",
"(",
")",
"{",
"debug",
"(",
"\"Adding a new instance to the \"",
"+",
"versionKey",
"+",
"\" of the '\"",
"+",
"machineName",
"+",
"\"' machine\"",
")",
";",
"let",
"manifest",
"=",
"getManifest",
"(",
")",
";",
"let",
"machine",
"=",
"manifest",
".",
"machines",
"[",
"machineName",
"]",
";",
"if",
"(",
"!",
"machine",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Machine does not exists\"",
")",
";",
"}",
"let",
"version",
"=",
"machine",
".",
"versions",
"[",
"versionKey",
"]",
";",
"if",
"(",
"!",
"version",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Version does not exists\"",
")",
";",
"}",
"let",
"versionInfo",
"=",
"getVersionInfo",
"(",
"machineName",
",",
"versionKey",
")",
";",
"if",
"(",
"!",
"versionInfo",
".",
"isSealed",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"The version is not sealed yet\"",
")",
";",
"}",
"let",
"newInstanceKey",
"=",
"\"instance\"",
"+",
"(",
"Object",
".",
"keys",
"(",
"version",
".",
"instances",
")",
".",
"length",
"+",
"1",
")",
";",
"let",
"instanceDirPath",
"=",
"version",
".",
"route",
"+",
"\"/instances/\"",
"+",
"newInstanceKey",
";",
"let",
"instanceSnapshotsDirPath",
"=",
"instanceDirPath",
"+",
"\"/snapshots\"",
";",
"version",
".",
"instances",
"[",
"newInstanceKey",
"]",
"=",
"{",
"\"route\"",
":",
"instanceDirPath",
",",
"\"snapshots\"",
":",
"{",
"}",
"}",
";",
"let",
"infoFile",
"=",
"instanceDirPath",
"+",
"\"/info.json\"",
";",
"debug",
"(",
"\"Creating the directories\"",
")",
";",
"fs",
".",
"mkdirSync",
"(",
"repositoryPath",
"+",
"\"/\"",
"+",
"instanceDirPath",
")",
";",
"fs",
".",
"mkdirSync",
"(",
"repositoryPath",
"+",
"\"/\"",
"+",
"instanceSnapshotsDirPath",
")",
";",
"debug",
"(",
"\"Creating the instance info.json file\"",
")",
";",
"let",
"info",
"=",
"{",
"\"hasStarted\"",
":",
"false",
",",
"\"hasEnded\"",
":",
"false",
"}",
";",
"jsonfile",
".",
"writeFileSync",
"(",
"repositoryPath",
"+",
"\"/\"",
"+",
"infoFile",
",",
"info",
")",
";",
"debug",
"(",
"\"Setting the manifest\"",
")",
";",
"setManifest",
"(",
"manifest",
")",
";",
"yield",
"_commit",
"(",
"null",
",",
"[",
"\"manifest.json\"",
",",
"infoFile",
"]",
",",
"\"Created the \"",
"+",
"newInstanceKey",
"+",
"\" for the \"",
"+",
"versionKey",
"+",
"\" of the '\"",
"+",
"machineName",
"+",
"\"' machine\"",
")",
";",
"return",
"newInstanceKey",
";",
"}",
")",
";",
"}"
]
| Add a new instance to a version of a machine
@method addInstance
@param {String} machineName The name of the machine
@param {String} versionKey The key of the version
@returns {Promise} The instance key | [
"Add",
"a",
"new",
"instance",
"to",
"a",
"version",
"of",
"a",
"machine"
]
| c07e7c1509b823d5c438a26b29fbf8f40e1e8be7 | https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L697-L746 | train |
moraispgsi/fsm-core | src/indexOld.js | getSnapshotsKeys | function getSnapshotsKeys(machineName, versionKey, instanceKey){
let manifest = getManifest();
let machine = manifest.machines[machineName];
if (!machine) {
throw new Error("Machine does not exists");
}
let version = machine.versions[versionKey];
if (!version) {
throw new Error("Version does not exists");
}
let instance = version.instances[instanceKey];
if (!instance) {
throw new Error("Instance does not exists");
}
return Object.keys(instance.snapshots);
} | javascript | function getSnapshotsKeys(machineName, versionKey, instanceKey){
let manifest = getManifest();
let machine = manifest.machines[machineName];
if (!machine) {
throw new Error("Machine does not exists");
}
let version = machine.versions[versionKey];
if (!version) {
throw new Error("Version does not exists");
}
let instance = version.instances[instanceKey];
if (!instance) {
throw new Error("Instance does not exists");
}
return Object.keys(instance.snapshots);
} | [
"function",
"getSnapshotsKeys",
"(",
"machineName",
",",
"versionKey",
",",
"instanceKey",
")",
"{",
"let",
"manifest",
"=",
"getManifest",
"(",
")",
";",
"let",
"machine",
"=",
"manifest",
".",
"machines",
"[",
"machineName",
"]",
";",
"if",
"(",
"!",
"machine",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Machine does not exists\"",
")",
";",
"}",
"let",
"version",
"=",
"machine",
".",
"versions",
"[",
"versionKey",
"]",
";",
"if",
"(",
"!",
"version",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Version does not exists\"",
")",
";",
"}",
"let",
"instance",
"=",
"version",
".",
"instances",
"[",
"instanceKey",
"]",
";",
"if",
"(",
"!",
"instance",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Instance does not exists\"",
")",
";",
"}",
"return",
"Object",
".",
"keys",
"(",
"instance",
".",
"snapshots",
")",
";",
"}"
]
| Gets the keys of all of the snapshots of the instance of a version of the machine in the repository
@method getSnapshotsKeys
@param {String} machineName The name of the machine to get the snapshots's keys
@param {String} versionKey The key of the version to get the snapshots's keys
@param {String} instanceKey The key of the instance to get the snapshot's keys
@returns {Array} An array with all the snapshot's keys of the instance | [
"Gets",
"the",
"keys",
"of",
"all",
"of",
"the",
"snapshots",
"of",
"the",
"instance",
"of",
"a",
"version",
"of",
"the",
"machine",
"in",
"the",
"repository"
]
| c07e7c1509b823d5c438a26b29fbf8f40e1e8be7 | https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L756-L776 | train |
moraispgsi/fsm-core | src/indexOld.js | getSnapshotRoute | function getSnapshotRoute(machineName, versionKey, instanceKey, snapshotKey){
let manifest = getManifest();
let machine = manifest.machines[machineName];
if (!machine) {
throw new Error("Machine does not exists");
}
let version = machine.versions[versionKey];
if (!version) {
throw new Error("Version does not exists");
}
let instance = version.instances[instanceKey];
if (!instance) {
throw new Error("Instance does not exists");
}
let snapshot = instance.snapshots[snapshotKey];
if (!snapshot) {
throw new Error("Snapshot does not exists");
}
return snapshot.route;
} | javascript | function getSnapshotRoute(machineName, versionKey, instanceKey, snapshotKey){
let manifest = getManifest();
let machine = manifest.machines[machineName];
if (!machine) {
throw new Error("Machine does not exists");
}
let version = machine.versions[versionKey];
if (!version) {
throw new Error("Version does not exists");
}
let instance = version.instances[instanceKey];
if (!instance) {
throw new Error("Instance does not exists");
}
let snapshot = instance.snapshots[snapshotKey];
if (!snapshot) {
throw new Error("Snapshot does not exists");
}
return snapshot.route;
} | [
"function",
"getSnapshotRoute",
"(",
"machineName",
",",
"versionKey",
",",
"instanceKey",
",",
"snapshotKey",
")",
"{",
"let",
"manifest",
"=",
"getManifest",
"(",
")",
";",
"let",
"machine",
"=",
"manifest",
".",
"machines",
"[",
"machineName",
"]",
";",
"if",
"(",
"!",
"machine",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Machine does not exists\"",
")",
";",
"}",
"let",
"version",
"=",
"machine",
".",
"versions",
"[",
"versionKey",
"]",
";",
"if",
"(",
"!",
"version",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Version does not exists\"",
")",
";",
"}",
"let",
"instance",
"=",
"version",
".",
"instances",
"[",
"instanceKey",
"]",
";",
"if",
"(",
"!",
"instance",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Instance does not exists\"",
")",
";",
"}",
"let",
"snapshot",
"=",
"instance",
".",
"snapshots",
"[",
"snapshotKey",
"]",
";",
"if",
"(",
"!",
"snapshot",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Snapshot does not exists\"",
")",
";",
"}",
"return",
"snapshot",
".",
"route",
";",
"}"
]
| Retrieve the snapshot's directory path
@method getSnapshotRoute
@param {String} machineName The name of the machine
@param {String} versionKey The key of the version
@param {String} instanceKey The key of the instance
@param {String} snapshotKey The key of the snapshot
@returns {String} The route | [
"Retrieve",
"the",
"snapshot",
"s",
"directory",
"path"
]
| c07e7c1509b823d5c438a26b29fbf8f40e1e8be7 | https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L787-L812 | train |
moraispgsi/fsm-core | src/indexOld.js | getSnapshotInfoRoute | function getSnapshotInfoRoute(machineName, versionKey, instanceKey, snapshotKey) {
return getSnapshotRoute(machineName, versionKey, instanceKey, snapshotKey) + "/info.json";
} | javascript | function getSnapshotInfoRoute(machineName, versionKey, instanceKey, snapshotKey) {
return getSnapshotRoute(machineName, versionKey, instanceKey, snapshotKey) + "/info.json";
} | [
"function",
"getSnapshotInfoRoute",
"(",
"machineName",
",",
"versionKey",
",",
"instanceKey",
",",
"snapshotKey",
")",
"{",
"return",
"getSnapshotRoute",
"(",
"machineName",
",",
"versionKey",
",",
"instanceKey",
",",
"snapshotKey",
")",
"+",
"\"/info.json\"",
";",
"}"
]
| Retrieve the snapshot's info.json path
@method getSnapshotInfoRoute
@param {String} machineName The name of the machine
@param {String} versionKey The key of the version
@param {String} instanceKey The key of the instance
@param {String} snapshotKey The key of the snapshot
@returns {String} The route | [
"Retrieve",
"the",
"snapshot",
"s",
"info",
".",
"json",
"path"
]
| c07e7c1509b823d5c438a26b29fbf8f40e1e8be7 | https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L823-L825 | train |
moraispgsi/fsm-core | src/indexOld.js | getSnapshotInfo | function getSnapshotInfo(machineName, versionKey, instanceKey, snapshotKey) {
let route = getSnapshotInfoRoute(machineName, versionKey, instanceKey, snapshotKey);
return jsonfile.readFileSync(repositoryPath + "/" + route);
} | javascript | function getSnapshotInfo(machineName, versionKey, instanceKey, snapshotKey) {
let route = getSnapshotInfoRoute(machineName, versionKey, instanceKey, snapshotKey);
return jsonfile.readFileSync(repositoryPath + "/" + route);
} | [
"function",
"getSnapshotInfo",
"(",
"machineName",
",",
"versionKey",
",",
"instanceKey",
",",
"snapshotKey",
")",
"{",
"let",
"route",
"=",
"getSnapshotInfoRoute",
"(",
"machineName",
",",
"versionKey",
",",
"instanceKey",
",",
"snapshotKey",
")",
";",
"return",
"jsonfile",
".",
"readFileSync",
"(",
"repositoryPath",
"+",
"\"/\"",
"+",
"route",
")",
";",
"}"
]
| Retrieve the snapshot's info.json file as a JavasScript Object
@method getSnapshotInfo
@param {String} machineName The name of the machine
@param {String} versionKey The key of the version
@param {String} instanceKey The key of the instance
@param {String} snapshotKey The key of the snapshot
@returns {Object} The info Object | [
"Retrieve",
"the",
"snapshot",
"s",
"info",
".",
"json",
"file",
"as",
"a",
"JavasScript",
"Object"
]
| c07e7c1509b823d5c438a26b29fbf8f40e1e8be7 | https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L836-L839 | train |
moraispgsi/fsm-core | src/indexOld.js | addSnapshot | function addSnapshot(machineName, versionKey, instanceKey, info) {
return co(function*() {
debug("Adding a new snapshot to the " + instanceKey + " of the " + versionKey + " of the '" + machineName + "' machine");
let manifest = getManifest();
let machine = manifest.machines[machineName];
if (!machine) {
throw new Error("Machine does not exists");
}
let version = machine.versions[versionKey];
if (!version) {
throw new Error("Version does not exists");
}
let instance = version.instances[instanceKey];
if (!instance) {
throw new Error("Instance does not exists");
}
let newSnapshotKey = "snapshot" + (Object.keys(instance.snapshots).length + 1);
let snapshotDirPath = instance.route + "/snapshots/" + newSnapshotKey;
instance.snapshots[newSnapshotKey] = {
"route": snapshotDirPath
};
let infoFile = snapshotDirPath + "/info.json";
debug("Creating the directories");
fs.mkdirSync(repositoryPath + "/" + snapshotDirPath);
debug("Creating the snapshot info.json file");
let info = {
};
jsonfile.writeFileSync(repositoryPath + "/" + infoFile, info);
debug("Setting the manifest");
setManifest(manifest);
yield _commit(null, ["manifest.json", infoFile],
"Created the "+newSnapshotKey+" for the "+instanceKey+" of the "+
versionKey+" of the '" + machineName + "' machine");
return newSnapshotKey;
});
} | javascript | function addSnapshot(machineName, versionKey, instanceKey, info) {
return co(function*() {
debug("Adding a new snapshot to the " + instanceKey + " of the " + versionKey + " of the '" + machineName + "' machine");
let manifest = getManifest();
let machine = manifest.machines[machineName];
if (!machine) {
throw new Error("Machine does not exists");
}
let version = machine.versions[versionKey];
if (!version) {
throw new Error("Version does not exists");
}
let instance = version.instances[instanceKey];
if (!instance) {
throw new Error("Instance does not exists");
}
let newSnapshotKey = "snapshot" + (Object.keys(instance.snapshots).length + 1);
let snapshotDirPath = instance.route + "/snapshots/" + newSnapshotKey;
instance.snapshots[newSnapshotKey] = {
"route": snapshotDirPath
};
let infoFile = snapshotDirPath + "/info.json";
debug("Creating the directories");
fs.mkdirSync(repositoryPath + "/" + snapshotDirPath);
debug("Creating the snapshot info.json file");
let info = {
};
jsonfile.writeFileSync(repositoryPath + "/" + infoFile, info);
debug("Setting the manifest");
setManifest(manifest);
yield _commit(null, ["manifest.json", infoFile],
"Created the "+newSnapshotKey+" for the "+instanceKey+" of the "+
versionKey+" of the '" + machineName + "' machine");
return newSnapshotKey;
});
} | [
"function",
"addSnapshot",
"(",
"machineName",
",",
"versionKey",
",",
"instanceKey",
",",
"info",
")",
"{",
"return",
"co",
"(",
"function",
"*",
"(",
")",
"{",
"debug",
"(",
"\"Adding a new snapshot to the \"",
"+",
"instanceKey",
"+",
"\" of the \"",
"+",
"versionKey",
"+",
"\" of the '\"",
"+",
"machineName",
"+",
"\"' machine\"",
")",
";",
"let",
"manifest",
"=",
"getManifest",
"(",
")",
";",
"let",
"machine",
"=",
"manifest",
".",
"machines",
"[",
"machineName",
"]",
";",
"if",
"(",
"!",
"machine",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Machine does not exists\"",
")",
";",
"}",
"let",
"version",
"=",
"machine",
".",
"versions",
"[",
"versionKey",
"]",
";",
"if",
"(",
"!",
"version",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Version does not exists\"",
")",
";",
"}",
"let",
"instance",
"=",
"version",
".",
"instances",
"[",
"instanceKey",
"]",
";",
"if",
"(",
"!",
"instance",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Instance does not exists\"",
")",
";",
"}",
"let",
"newSnapshotKey",
"=",
"\"snapshot\"",
"+",
"(",
"Object",
".",
"keys",
"(",
"instance",
".",
"snapshots",
")",
".",
"length",
"+",
"1",
")",
";",
"let",
"snapshotDirPath",
"=",
"instance",
".",
"route",
"+",
"\"/snapshots/\"",
"+",
"newSnapshotKey",
";",
"instance",
".",
"snapshots",
"[",
"newSnapshotKey",
"]",
"=",
"{",
"\"route\"",
":",
"snapshotDirPath",
"}",
";",
"let",
"infoFile",
"=",
"snapshotDirPath",
"+",
"\"/info.json\"",
";",
"debug",
"(",
"\"Creating the directories\"",
")",
";",
"fs",
".",
"mkdirSync",
"(",
"repositoryPath",
"+",
"\"/\"",
"+",
"snapshotDirPath",
")",
";",
"debug",
"(",
"\"Creating the snapshot info.json file\"",
")",
";",
"let",
"info",
"=",
"{",
"}",
";",
"jsonfile",
".",
"writeFileSync",
"(",
"repositoryPath",
"+",
"\"/\"",
"+",
"infoFile",
",",
"info",
")",
";",
"debug",
"(",
"\"Setting the manifest\"",
")",
";",
"setManifest",
"(",
"manifest",
")",
";",
"yield",
"_commit",
"(",
"null",
",",
"[",
"\"manifest.json\"",
",",
"infoFile",
"]",
",",
"\"Created the \"",
"+",
"newSnapshotKey",
"+",
"\" for the \"",
"+",
"instanceKey",
"+",
"\" of the \"",
"+",
"versionKey",
"+",
"\" of the '\"",
"+",
"machineName",
"+",
"\"' machine\"",
")",
";",
"return",
"newSnapshotKey",
";",
"}",
")",
";",
"}"
]
| Add a new snapshot to an instance of a version of a machine
@method addSnapshot
@param {String} machineName The name of the machine
@param {String} versionKey The key of the version
@param {String} instanceKey The key of the instance
@param {Object} info The info Object
@returns {Promise} The instance key | [
"Add",
"a",
"new",
"snapshot",
"to",
"an",
"instance",
"of",
"a",
"version",
"of",
"a",
"machine"
]
| c07e7c1509b823d5c438a26b29fbf8f40e1e8be7 | https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L850-L896 | train |
ethul/grunt-roy | tasks/roy.js | writeSourceMap | function writeSourceMap(srcpath, destpath, options, f) {
var path = require('path')
, SourceMapGenerator = require('source-map').SourceMapGenerator
, sourceMap = new SourceMapGenerator({file: path.basename(destpath)})
, sourceMapDest = destpath + '.map'
, sourceMappingUrl = encodeURIComponent(path.basename(sourceMapDest))
, res = f(sourceMap) + (options.sourceMap ?
'//@ sourceMappingURL=' + sourceMappingUrl + '\n' : ''
)
, _ = (function(){
if (options.sourceMap) {
grunt.file.write(sourceMapDest, sourceMap.toString());
grunt.file.copy(srcpath, path.join.apply(path, [
path.dirname(destpath),
path.basename(srcpath)
]));
}
}())
;
return res;
} | javascript | function writeSourceMap(srcpath, destpath, options, f) {
var path = require('path')
, SourceMapGenerator = require('source-map').SourceMapGenerator
, sourceMap = new SourceMapGenerator({file: path.basename(destpath)})
, sourceMapDest = destpath + '.map'
, sourceMappingUrl = encodeURIComponent(path.basename(sourceMapDest))
, res = f(sourceMap) + (options.sourceMap ?
'//@ sourceMappingURL=' + sourceMappingUrl + '\n' : ''
)
, _ = (function(){
if (options.sourceMap) {
grunt.file.write(sourceMapDest, sourceMap.toString());
grunt.file.copy(srcpath, path.join.apply(path, [
path.dirname(destpath),
path.basename(srcpath)
]));
}
}())
;
return res;
} | [
"function",
"writeSourceMap",
"(",
"srcpath",
",",
"destpath",
",",
"options",
",",
"f",
")",
"{",
"var",
"path",
"=",
"require",
"(",
"'path'",
")",
",",
"SourceMapGenerator",
"=",
"require",
"(",
"'source-map'",
")",
".",
"SourceMapGenerator",
",",
"sourceMap",
"=",
"new",
"SourceMapGenerator",
"(",
"{",
"file",
":",
"path",
".",
"basename",
"(",
"destpath",
")",
"}",
")",
",",
"sourceMapDest",
"=",
"destpath",
"+",
"'.map'",
",",
"sourceMappingUrl",
"=",
"encodeURIComponent",
"(",
"path",
".",
"basename",
"(",
"sourceMapDest",
")",
")",
",",
"res",
"=",
"f",
"(",
"sourceMap",
")",
"+",
"(",
"options",
".",
"sourceMap",
"?",
"'//@ sourceMappingURL='",
"+",
"sourceMappingUrl",
"+",
"'\\n'",
":",
"\\n",
")",
",",
"''",
";",
"_",
"=",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"options",
".",
"sourceMap",
")",
"{",
"grunt",
".",
"file",
".",
"write",
"(",
"sourceMapDest",
",",
"sourceMap",
".",
"toString",
"(",
")",
")",
";",
"grunt",
".",
"file",
".",
"copy",
"(",
"srcpath",
",",
"path",
".",
"join",
".",
"apply",
"(",
"path",
",",
"[",
"path",
".",
"dirname",
"(",
"destpath",
")",
",",
"path",
".",
"basename",
"(",
"srcpath",
")",
"]",
")",
")",
";",
"}",
"}",
"(",
")",
")",
"}"
]
| The sources in the source map file are not specified as absolute urls, which means that they will be resolved relative to the location of the source map file. Also, we specify a relative path for the source mapping url, which causes the script source of the JS to be used as the source origin. Also, this url must adhere to RFC3986. | [
"The",
"sources",
"in",
"the",
"source",
"map",
"file",
"are",
"not",
"specified",
"as",
"absolute",
"urls",
"which",
"means",
"that",
"they",
"will",
"be",
"resolved",
"relative",
"to",
"the",
"location",
"of",
"the",
"source",
"map",
"file",
".",
"Also",
"we",
"specify",
"a",
"relative",
"path",
"for",
"the",
"source",
"mapping",
"url",
"which",
"causes",
"the",
"script",
"source",
"of",
"the",
"JS",
"to",
"be",
"used",
"as",
"the",
"source",
"origin",
".",
"Also",
"this",
"url",
"must",
"adhere",
"to",
"RFC3986",
"."
]
| 63df011442f1c53bc3637d8d780db811ee2a8065 | https://github.com/ethul/grunt-roy/blob/63df011442f1c53bc3637d8d780db811ee2a8065/tasks/roy.js#L60-L80 | train |
xat/mutate.js | mutate.js | function (sig, fn) {
var isArr = toType(fn) === 'array';
sig || (sig = []);
map[sig.join('::').toLowerCase()] = {
fn: isArr ? passObject(fn) : fn,
inject: isArr ? true : (fn.length > sig.length)
};
return this;
} | javascript | function (sig, fn) {
var isArr = toType(fn) === 'array';
sig || (sig = []);
map[sig.join('::').toLowerCase()] = {
fn: isArr ? passObject(fn) : fn,
inject: isArr ? true : (fn.length > sig.length)
};
return this;
} | [
"function",
"(",
"sig",
",",
"fn",
")",
"{",
"var",
"isArr",
"=",
"toType",
"(",
"fn",
")",
"===",
"'array'",
";",
"sig",
"||",
"(",
"sig",
"=",
"[",
"]",
")",
";",
"map",
"[",
"sig",
".",
"join",
"(",
"'::'",
")",
".",
"toLowerCase",
"(",
")",
"]",
"=",
"{",
"fn",
":",
"isArr",
"?",
"passObject",
"(",
"fn",
")",
":",
"fn",
",",
"inject",
":",
"isArr",
"?",
"true",
":",
"(",
"fn",
".",
"length",
">",
"sig",
".",
"length",
")",
"}",
";",
"return",
"this",
";",
"}"
]
| add a new method | [
"add",
"a",
"new",
"method"
]
| 4d82c4cd2fe859724a934c9ad4f99ebd58d95d69 | https://github.com/xat/mutate.js/blob/4d82c4cd2fe859724a934c9ad4f99ebd58d95d69/mutate.js#L9-L19 | train |
|
xat/mutate.js | mutate.js | function () {
return function () {
var args = Array.prototype.slice.call(arguments, 0);
var sig = (function () {
var ret = [];
for (var i = 0, len = args.length; i < len; i++) {
ret.push(toType(args[i]));
}
return ret;
})().join('::');
if (map[sig]) {
if (map[sig].inject) args.unshift(input);
return map[sig].fn.apply(ctx || null, args);
}
return input && input.apply(ctx || null, args);
}
} | javascript | function () {
return function () {
var args = Array.prototype.slice.call(arguments, 0);
var sig = (function () {
var ret = [];
for (var i = 0, len = args.length; i < len; i++) {
ret.push(toType(args[i]));
}
return ret;
})().join('::');
if (map[sig]) {
if (map[sig].inject) args.unshift(input);
return map[sig].fn.apply(ctx || null, args);
}
return input && input.apply(ctx || null, args);
}
} | [
"function",
"(",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
";",
"var",
"sig",
"=",
"(",
"function",
"(",
")",
"{",
"var",
"ret",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"args",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"ret",
".",
"push",
"(",
"toType",
"(",
"args",
"[",
"i",
"]",
")",
")",
";",
"}",
"return",
"ret",
";",
"}",
")",
"(",
")",
".",
"join",
"(",
"'::'",
")",
";",
"if",
"(",
"map",
"[",
"sig",
"]",
")",
"{",
"if",
"(",
"map",
"[",
"sig",
"]",
".",
"inject",
")",
"args",
".",
"unshift",
"(",
"input",
")",
";",
"return",
"map",
"[",
"sig",
"]",
".",
"fn",
".",
"apply",
"(",
"ctx",
"||",
"null",
",",
"args",
")",
";",
"}",
"return",
"input",
"&&",
"input",
".",
"apply",
"(",
"ctx",
"||",
"null",
",",
"args",
")",
";",
"}",
"}"
]
| return the composed new function | [
"return",
"the",
"composed",
"new",
"function"
]
| 4d82c4cd2fe859724a934c9ad4f99ebd58d95d69 | https://github.com/xat/mutate.js/blob/4d82c4cd2fe859724a934c9ad4f99ebd58d95d69/mutate.js#L22-L40 | train |
|
restorecommerce/service-config | lib/service_new.js | request | async function request(cb) {
// get name of current service, stop if it's `config-srv` itself
const name = nconf.get('server:name') || 'test-srv';
let data = {};
if (name === 'config-srv') return cb(null, data);
// setup & connect with config-srv on first run
// if (!client && fs.existsSync(fullProtoPath))
const config = _.clone(nconf.get('config-srv'));
let service;
if (config.transports
&& config.transports.grpc
&& config.transports.service) {
client = new grpcClient.Client(config);
service = await co(client.connect());
} else {
throw new Error('Missing configuration details');
}
await co(service.get({
filter: client.toStruct({ name: name })
}));
// TODO: continue
// fetch the latest configuration data if possible
client.get({ field: [{ name }] }, (err, res) => {
if (err) return cb(err, null);
if (res.data) data = res.data;
// update/mutate the nconf store and return
nconf.use('default', data);
return cb(null, nconf);
});
return true;
} | javascript | async function request(cb) {
// get name of current service, stop if it's `config-srv` itself
const name = nconf.get('server:name') || 'test-srv';
let data = {};
if (name === 'config-srv') return cb(null, data);
// setup & connect with config-srv on first run
// if (!client && fs.existsSync(fullProtoPath))
const config = _.clone(nconf.get('config-srv'));
let service;
if (config.transports
&& config.transports.grpc
&& config.transports.service) {
client = new grpcClient.Client(config);
service = await co(client.connect());
} else {
throw new Error('Missing configuration details');
}
await co(service.get({
filter: client.toStruct({ name: name })
}));
// TODO: continue
// fetch the latest configuration data if possible
client.get({ field: [{ name }] }, (err, res) => {
if (err) return cb(err, null);
if (res.data) data = res.data;
// update/mutate the nconf store and return
nconf.use('default', data);
return cb(null, nconf);
});
return true;
} | [
"async",
"function",
"request",
"(",
"cb",
")",
"{",
"const",
"name",
"=",
"nconf",
".",
"get",
"(",
"'server:name'",
")",
"||",
"'test-srv'",
";",
"let",
"data",
"=",
"{",
"}",
";",
"if",
"(",
"name",
"===",
"'config-srv'",
")",
"return",
"cb",
"(",
"null",
",",
"data",
")",
";",
"const",
"config",
"=",
"_",
".",
"clone",
"(",
"nconf",
".",
"get",
"(",
"'config-srv'",
")",
")",
";",
"let",
"service",
";",
"if",
"(",
"config",
".",
"transports",
"&&",
"config",
".",
"transports",
".",
"grpc",
"&&",
"config",
".",
"transports",
".",
"service",
")",
"{",
"client",
"=",
"new",
"grpcClient",
".",
"Client",
"(",
"config",
")",
";",
"service",
"=",
"await",
"co",
"(",
"client",
".",
"connect",
"(",
")",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Missing configuration details'",
")",
";",
"}",
"await",
"co",
"(",
"service",
".",
"get",
"(",
"{",
"filter",
":",
"client",
".",
"toStruct",
"(",
"{",
"name",
":",
"name",
"}",
")",
"}",
")",
")",
";",
"client",
".",
"get",
"(",
"{",
"field",
":",
"[",
"{",
"name",
"}",
"]",
"}",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
",",
"null",
")",
";",
"if",
"(",
"res",
".",
"data",
")",
"data",
"=",
"res",
".",
"data",
";",
"nconf",
".",
"use",
"(",
"'default'",
",",
"data",
")",
";",
"return",
"cb",
"(",
"null",
",",
"nconf",
")",
";",
"}",
")",
";",
"return",
"true",
";",
"}"
]
| function to update the nconf object with data from the
remote `config-srv`. | [
"function",
"to",
"update",
"the",
"nconf",
"object",
"with",
"data",
"from",
"the",
"remote",
"config",
"-",
"srv",
"."
]
| f7ae2183ceaf78e2b6cb9d426c8606b71377ea87 | https://github.com/restorecommerce/service-config/blob/f7ae2183ceaf78e2b6cb9d426c8606b71377ea87/lib/service_new.js#L20-L55 | train |
leolmi/install-here | core.js | function() {
this.force_first = true;
this.relpath = '';
this.root = process.cwd();
this.counters = {
files: 0,
dependencies: 0,
depAddUpd: 0
};
this.error = null;
this.exit = null;
this.temp = '';
this.files = [];
this.dependecies = [];
this.package = null;
this.settings = null;
this.options = null;
} | javascript | function() {
this.force_first = true;
this.relpath = '';
this.root = process.cwd();
this.counters = {
files: 0,
dependencies: 0,
depAddUpd: 0
};
this.error = null;
this.exit = null;
this.temp = '';
this.files = [];
this.dependecies = [];
this.package = null;
this.settings = null;
this.options = null;
} | [
"function",
"(",
")",
"{",
"this",
".",
"force_first",
"=",
"true",
";",
"this",
".",
"relpath",
"=",
"''",
";",
"this",
".",
"root",
"=",
"process",
".",
"cwd",
"(",
")",
";",
"this",
".",
"counters",
"=",
"{",
"files",
":",
"0",
",",
"dependencies",
":",
"0",
",",
"depAddUpd",
":",
"0",
"}",
";",
"this",
".",
"error",
"=",
"null",
";",
"this",
".",
"exit",
"=",
"null",
";",
"this",
".",
"temp",
"=",
"''",
";",
"this",
".",
"files",
"=",
"[",
"]",
";",
"this",
".",
"dependecies",
"=",
"[",
"]",
";",
"this",
".",
"package",
"=",
"null",
";",
"this",
".",
"settings",
"=",
"null",
";",
"this",
".",
"options",
"=",
"null",
";",
"}"
]
| resetta lo stato | [
"resetta",
"lo",
"stato"
]
| ef6532c711737e295753f47b202a5ad3b05b34f3 | https://github.com/leolmi/install-here/blob/ef6532c711737e295753f47b202a5ad3b05b34f3/core.js#L52-L69 | train |
|
leolmi/install-here | core.js | function(xdata, ndata) {
try {
const npkg = JSON.parse(ndata||'{}');
const xpkg = xdata?JSON.parse(xdata):JSON.parse(ndata||'{}');
_managePkg(npkg, xpkg);
_initPkg(xpkg);
xdata = JSON.stringify(xpkg, null, 2);
_log('package.json managed: %s', xdata);
} catch(err){
console.error(err);
}
return xdata;
} | javascript | function(xdata, ndata) {
try {
const npkg = JSON.parse(ndata||'{}');
const xpkg = xdata?JSON.parse(xdata):JSON.parse(ndata||'{}');
_managePkg(npkg, xpkg);
_initPkg(xpkg);
xdata = JSON.stringify(xpkg, null, 2);
_log('package.json managed: %s', xdata);
} catch(err){
console.error(err);
}
return xdata;
} | [
"function",
"(",
"xdata",
",",
"ndata",
")",
"{",
"try",
"{",
"const",
"npkg",
"=",
"JSON",
".",
"parse",
"(",
"ndata",
"||",
"'{}'",
")",
";",
"const",
"xpkg",
"=",
"xdata",
"?",
"JSON",
".",
"parse",
"(",
"xdata",
")",
":",
"JSON",
".",
"parse",
"(",
"ndata",
"||",
"'{}'",
")",
";",
"_managePkg",
"(",
"npkg",
",",
"xpkg",
")",
";",
"_initPkg",
"(",
"xpkg",
")",
";",
"xdata",
"=",
"JSON",
".",
"stringify",
"(",
"xpkg",
",",
"null",
",",
"2",
")",
";",
"_log",
"(",
"'package.json managed: %s'",
",",
"xdata",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"err",
")",
";",
"}",
"return",
"xdata",
";",
"}"
]
| gestisce le modifiche al package.json | [
"gestisce",
"le",
"modifiche",
"al",
"package",
".",
"json"
]
| ef6532c711737e295753f47b202a5ad3b05b34f3 | https://github.com/leolmi/install-here/blob/ef6532c711737e295753f47b202a5ad3b05b34f3/core.js#L74-L86 | train |
|
leolmi/install-here | core.js | _checkPathX | function _checkPathX(relfolder, skipCreation) {
if (!relfolder) return;
const parts = relfolder.split(path.sep);
var checked = _state.root;
var checkedParts = '';
var index = 0;
var skip = false;
do {
checked = path.join(checked, parts[index]);
if (!fs.existsSync(checked)) {
if (!skipCreation) {
fs.mkdirSync(checked);
checkedParts = path.join(checkedParts, parts[index]);
} else {
skip = true;
}
} else {
checkedParts = path.join(checkedParts, parts[index]);
}
index++;
} while (!skip && index < parts.length);
return checkedParts;
} | javascript | function _checkPathX(relfolder, skipCreation) {
if (!relfolder) return;
const parts = relfolder.split(path.sep);
var checked = _state.root;
var checkedParts = '';
var index = 0;
var skip = false;
do {
checked = path.join(checked, parts[index]);
if (!fs.existsSync(checked)) {
if (!skipCreation) {
fs.mkdirSync(checked);
checkedParts = path.join(checkedParts, parts[index]);
} else {
skip = true;
}
} else {
checkedParts = path.join(checkedParts, parts[index]);
}
index++;
} while (!skip && index < parts.length);
return checkedParts;
} | [
"function",
"_checkPathX",
"(",
"relfolder",
",",
"skipCreation",
")",
"{",
"if",
"(",
"!",
"relfolder",
")",
"return",
";",
"const",
"parts",
"=",
"relfolder",
".",
"split",
"(",
"path",
".",
"sep",
")",
";",
"var",
"checked",
"=",
"_state",
".",
"root",
";",
"var",
"checkedParts",
"=",
"''",
";",
"var",
"index",
"=",
"0",
";",
"var",
"skip",
"=",
"false",
";",
"do",
"{",
"checked",
"=",
"path",
".",
"join",
"(",
"checked",
",",
"parts",
"[",
"index",
"]",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"checked",
")",
")",
"{",
"if",
"(",
"!",
"skipCreation",
")",
"{",
"fs",
".",
"mkdirSync",
"(",
"checked",
")",
";",
"checkedParts",
"=",
"path",
".",
"join",
"(",
"checkedParts",
",",
"parts",
"[",
"index",
"]",
")",
";",
"}",
"else",
"{",
"skip",
"=",
"true",
";",
"}",
"}",
"else",
"{",
"checkedParts",
"=",
"path",
".",
"join",
"(",
"checkedParts",
",",
"parts",
"[",
"index",
"]",
")",
";",
"}",
"index",
"++",
";",
"}",
"while",
"(",
"!",
"skip",
"&&",
"index",
"<",
"parts",
".",
"length",
")",
";",
"return",
"checkedParts",
";",
"}"
]
| check the path | [
"check",
"the",
"path"
]
| ef6532c711737e295753f47b202a5ad3b05b34f3 | https://github.com/leolmi/install-here/blob/ef6532c711737e295753f47b202a5ad3b05b34f3/core.js#L492-L514 | train |
angeloocana/joj-core | dist/Score.js | getColorScore | function getColorScore(_ref, positions) {
var startRow = _ref.startRow,
endRow = _ref.endRow;
var score = positions.reduce(function (newScore, p) {
if (p.y === endRow) newScore.winners += 1;else newScore.preWinnersPoints += endRow === 0 ? startRow - p.y : p.y;
return newScore;
}, getInitialColorScore());
score.won = score.winners === positions.length;
return score;
} | javascript | function getColorScore(_ref, positions) {
var startRow = _ref.startRow,
endRow = _ref.endRow;
var score = positions.reduce(function (newScore, p) {
if (p.y === endRow) newScore.winners += 1;else newScore.preWinnersPoints += endRow === 0 ? startRow - p.y : p.y;
return newScore;
}, getInitialColorScore());
score.won = score.winners === positions.length;
return score;
} | [
"function",
"getColorScore",
"(",
"_ref",
",",
"positions",
")",
"{",
"var",
"startRow",
"=",
"_ref",
".",
"startRow",
",",
"endRow",
"=",
"_ref",
".",
"endRow",
";",
"var",
"score",
"=",
"positions",
".",
"reduce",
"(",
"function",
"(",
"newScore",
",",
"p",
")",
"{",
"if",
"(",
"p",
".",
"y",
"===",
"endRow",
")",
"newScore",
".",
"winners",
"+=",
"1",
";",
"else",
"newScore",
".",
"preWinnersPoints",
"+=",
"endRow",
"===",
"0",
"?",
"startRow",
"-",
"p",
".",
"y",
":",
"p",
".",
"y",
";",
"return",
"newScore",
";",
"}",
",",
"getInitialColorScore",
"(",
")",
")",
";",
"score",
".",
"won",
"=",
"score",
".",
"winners",
"===",
"positions",
".",
"length",
";",
"return",
"score",
";",
"}"
]
| Get color score
returns { won, winners, preWinnersPoints } | [
"Get",
"color",
"score"
]
| 14bc7801c004271cefafff6cc0abb0c3173c805a | https://github.com/angeloocana/joj-core/blob/14bc7801c004271cefafff6cc0abb0c3173c805a/dist/Score.js#L33-L43 | train |
angeloocana/joj-core | dist/Score.js | getScore | function getScore(board) {
var pieces = Board.getPiecesFromBoard(board);
var startEndRows = Board.getStartEndRows(board);
var white = getColorScore(startEndRows.white, pieces.white);
var black = getColorScore(startEndRows.black, pieces.black);
return {
ended: white.won || black.won,
white: white,
black: black
};
} | javascript | function getScore(board) {
var pieces = Board.getPiecesFromBoard(board);
var startEndRows = Board.getStartEndRows(board);
var white = getColorScore(startEndRows.white, pieces.white);
var black = getColorScore(startEndRows.black, pieces.black);
return {
ended: white.won || black.won,
white: white,
black: black
};
} | [
"function",
"getScore",
"(",
"board",
")",
"{",
"var",
"pieces",
"=",
"Board",
".",
"getPiecesFromBoard",
"(",
"board",
")",
";",
"var",
"startEndRows",
"=",
"Board",
".",
"getStartEndRows",
"(",
"board",
")",
";",
"var",
"white",
"=",
"getColorScore",
"(",
"startEndRows",
".",
"white",
",",
"pieces",
".",
"white",
")",
";",
"var",
"black",
"=",
"getColorScore",
"(",
"startEndRows",
".",
"black",
",",
"pieces",
".",
"black",
")",
";",
"return",
"{",
"ended",
":",
"white",
".",
"won",
"||",
"black",
".",
"won",
",",
"white",
":",
"white",
",",
"black",
":",
"black",
"}",
";",
"}"
]
| Takes a board and return Score | [
"Takes",
"a",
"board",
"and",
"return",
"Score"
]
| 14bc7801c004271cefafff6cc0abb0c3173c805a | https://github.com/angeloocana/joj-core/blob/14bc7801c004271cefafff6cc0abb0c3173c805a/dist/Score.js#L47-L57 | train |
byu-oit/aws-scatter-gather | bin/aggregator.js | gatherer | function gatherer(received) {
// delete reference from the wait map
const index = missing.indexOf(received.name);
if (index !== -1) missing.splice(index, 1);
// determine if the response was requested
const requested = received.requestId === event.requestId;
// if already resolved or rejected then exit now, also verify that the event is being listened for
if (pending && requested) {
// store response
if (!received.error) {
result[received.name] = received.data;
debug('Received response to request ' + received.requestId + ' from ' + received.name);
if (config.circuitbreaker && received.circuitbreakerSuccess) {
config.circuitbreaker.success();
}
} else if (config.circuitbreaker && received.circuitbreakerFault) {
debug('Received response to request ' + received.requestId + ' from ' + received.name + ' which triggered a circuitbreaker fault with the error: ' + received.error);
config.circuitbreaker.fault();
} else {
debug('Received response to request ' + received.requestId + ' from ' + received.name + ' as an error: ' + received.error);
}
// all expected responses received and min timeout passed, so resolve the deferred promise
if (missing.length === 0) {
clearTimeout(maxTimeoutId);
debug('Received all expected responses for request ' + received.requestId);
if (minTimeoutReached) {
pending = false;
deferred.resolve(result);
}
}
if (config.each) {
const meta = {
active: pending,
minWaitReached: minTimeoutReached,
missing: missing.slice(0)
};
const done = function (err) {
pending = false;
if (err) return deferred.reject(err);
deferred.resolve(result);
};
config.each(received, meta, done);
}
}
} | javascript | function gatherer(received) {
// delete reference from the wait map
const index = missing.indexOf(received.name);
if (index !== -1) missing.splice(index, 1);
// determine if the response was requested
const requested = received.requestId === event.requestId;
// if already resolved or rejected then exit now, also verify that the event is being listened for
if (pending && requested) {
// store response
if (!received.error) {
result[received.name] = received.data;
debug('Received response to request ' + received.requestId + ' from ' + received.name);
if (config.circuitbreaker && received.circuitbreakerSuccess) {
config.circuitbreaker.success();
}
} else if (config.circuitbreaker && received.circuitbreakerFault) {
debug('Received response to request ' + received.requestId + ' from ' + received.name + ' which triggered a circuitbreaker fault with the error: ' + received.error);
config.circuitbreaker.fault();
} else {
debug('Received response to request ' + received.requestId + ' from ' + received.name + ' as an error: ' + received.error);
}
// all expected responses received and min timeout passed, so resolve the deferred promise
if (missing.length === 0) {
clearTimeout(maxTimeoutId);
debug('Received all expected responses for request ' + received.requestId);
if (minTimeoutReached) {
pending = false;
deferred.resolve(result);
}
}
if (config.each) {
const meta = {
active: pending,
minWaitReached: minTimeoutReached,
missing: missing.slice(0)
};
const done = function (err) {
pending = false;
if (err) return deferred.reject(err);
deferred.resolve(result);
};
config.each(received, meta, done);
}
}
} | [
"function",
"gatherer",
"(",
"received",
")",
"{",
"const",
"index",
"=",
"missing",
".",
"indexOf",
"(",
"received",
".",
"name",
")",
";",
"if",
"(",
"index",
"!==",
"-",
"1",
")",
"missing",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"const",
"requested",
"=",
"received",
".",
"requestId",
"===",
"event",
".",
"requestId",
";",
"if",
"(",
"pending",
"&&",
"requested",
")",
"{",
"if",
"(",
"!",
"received",
".",
"error",
")",
"{",
"result",
"[",
"received",
".",
"name",
"]",
"=",
"received",
".",
"data",
";",
"debug",
"(",
"'Received response to request '",
"+",
"received",
".",
"requestId",
"+",
"' from '",
"+",
"received",
".",
"name",
")",
";",
"if",
"(",
"config",
".",
"circuitbreaker",
"&&",
"received",
".",
"circuitbreakerSuccess",
")",
"{",
"config",
".",
"circuitbreaker",
".",
"success",
"(",
")",
";",
"}",
"}",
"else",
"if",
"(",
"config",
".",
"circuitbreaker",
"&&",
"received",
".",
"circuitbreakerFault",
")",
"{",
"debug",
"(",
"'Received response to request '",
"+",
"received",
".",
"requestId",
"+",
"' from '",
"+",
"received",
".",
"name",
"+",
"' which triggered a circuitbreaker fault with the error: '",
"+",
"received",
".",
"error",
")",
";",
"config",
".",
"circuitbreaker",
".",
"fault",
"(",
")",
";",
"}",
"else",
"{",
"debug",
"(",
"'Received response to request '",
"+",
"received",
".",
"requestId",
"+",
"' from '",
"+",
"received",
".",
"name",
"+",
"' as an error: '",
"+",
"received",
".",
"error",
")",
";",
"}",
"if",
"(",
"missing",
".",
"length",
"===",
"0",
")",
"{",
"clearTimeout",
"(",
"maxTimeoutId",
")",
";",
"debug",
"(",
"'Received all expected responses for request '",
"+",
"received",
".",
"requestId",
")",
";",
"if",
"(",
"minTimeoutReached",
")",
"{",
"pending",
"=",
"false",
";",
"deferred",
".",
"resolve",
"(",
"result",
")",
";",
"}",
"}",
"if",
"(",
"config",
".",
"each",
")",
"{",
"const",
"meta",
"=",
"{",
"active",
":",
"pending",
",",
"minWaitReached",
":",
"minTimeoutReached",
",",
"missing",
":",
"missing",
".",
"slice",
"(",
"0",
")",
"}",
";",
"const",
"done",
"=",
"function",
"(",
"err",
")",
"{",
"pending",
"=",
"false",
";",
"if",
"(",
"err",
")",
"return",
"deferred",
".",
"reject",
"(",
"err",
")",
";",
"deferred",
".",
"resolve",
"(",
"result",
")",
";",
"}",
";",
"config",
".",
"each",
"(",
"received",
",",
"meta",
",",
"done",
")",
";",
"}",
"}",
"}"
]
| define the gatherer function | [
"define",
"the",
"gatherer",
"function"
]
| 708e7caa6bea706276d55b3678d8468438d6d163 | https://github.com/byu-oit/aws-scatter-gather/blob/708e7caa6bea706276d55b3678d8468438d6d163/bin/aggregator.js#L63-L114 | train |
RnbWd/parse-browserify | lib/role.js | function(name, acl) {
if (_.isString(name) && (acl instanceof Parse.ACL)) {
Parse.Object.prototype.constructor.call(this, null, null);
this.setName(name);
this.setACL(acl);
} else {
Parse.Object.prototype.constructor.call(this, name, acl);
}
} | javascript | function(name, acl) {
if (_.isString(name) && (acl instanceof Parse.ACL)) {
Parse.Object.prototype.constructor.call(this, null, null);
this.setName(name);
this.setACL(acl);
} else {
Parse.Object.prototype.constructor.call(this, name, acl);
}
} | [
"function",
"(",
"name",
",",
"acl",
")",
"{",
"if",
"(",
"_",
".",
"isString",
"(",
"name",
")",
"&&",
"(",
"acl",
"instanceof",
"Parse",
".",
"ACL",
")",
")",
"{",
"Parse",
".",
"Object",
".",
"prototype",
".",
"constructor",
".",
"call",
"(",
"this",
",",
"null",
",",
"null",
")",
";",
"this",
".",
"setName",
"(",
"name",
")",
";",
"this",
".",
"setACL",
"(",
"acl",
")",
";",
"}",
"else",
"{",
"Parse",
".",
"Object",
".",
"prototype",
".",
"constructor",
".",
"call",
"(",
"this",
",",
"name",
",",
"acl",
")",
";",
"}",
"}"
]
| Instance Methods
Constructs a new ParseRole with the given name and ACL.
@param {String} name The name of the Role to create.
@param {Parse.ACL} acl The ACL for this role. Roles must have an ACL. | [
"Instance",
"Methods",
"Constructs",
"a",
"new",
"ParseRole",
"with",
"the",
"given",
"name",
"and",
"ACL",
"."
]
| c19c1b798e4010a552e130b1a9ce3b5d084dc101 | https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/role.js#L27-L35 | train |
|
silvertoad/color.log.js | loggers.js | MultiLine | function MultiLine()
{
MultiLine.prototype.parse_and_print = function(msg, colour)
{
var out = [];
for (var i = 0; i < msg.length; i++)
{
var msg_item = msg[i];
if (typeof msg_item == 'object')
out.push(colour + RESET + util.inspect(msg_item, false, 50, true) + RESET + colour);
else
out.push(msg_item);
}
this.print(colour + out.join(' ') + colour + " " + RESET);
};
MultiLine.prototype.info = function(msg)
{
this.parse_and_print(msg, GREEN);
};
MultiLine.prototype.mark = function(msg)
{
this.parse_and_print(msg, LIGHT_GREEN);
};
MultiLine.prototype.error = function(msg)
{
this.parse_and_print(msg, RED);
};
MultiLine.prototype.warn = function(msg)
{
this.parse_and_print(msg, YELLOW);
};
MultiLine.prototype.print = function(msg)
{
console.log(msg);
};
} | javascript | function MultiLine()
{
MultiLine.prototype.parse_and_print = function(msg, colour)
{
var out = [];
for (var i = 0; i < msg.length; i++)
{
var msg_item = msg[i];
if (typeof msg_item == 'object')
out.push(colour + RESET + util.inspect(msg_item, false, 50, true) + RESET + colour);
else
out.push(msg_item);
}
this.print(colour + out.join(' ') + colour + " " + RESET);
};
MultiLine.prototype.info = function(msg)
{
this.parse_and_print(msg, GREEN);
};
MultiLine.prototype.mark = function(msg)
{
this.parse_and_print(msg, LIGHT_GREEN);
};
MultiLine.prototype.error = function(msg)
{
this.parse_and_print(msg, RED);
};
MultiLine.prototype.warn = function(msg)
{
this.parse_and_print(msg, YELLOW);
};
MultiLine.prototype.print = function(msg)
{
console.log(msg);
};
} | [
"function",
"MultiLine",
"(",
")",
"{",
"MultiLine",
".",
"prototype",
".",
"parse_and_print",
"=",
"function",
"(",
"msg",
",",
"colour",
")",
"{",
"var",
"out",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"msg",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"msg_item",
"=",
"msg",
"[",
"i",
"]",
";",
"if",
"(",
"typeof",
"msg_item",
"==",
"'object'",
")",
"out",
".",
"push",
"(",
"colour",
"+",
"RESET",
"+",
"util",
".",
"inspect",
"(",
"msg_item",
",",
"false",
",",
"50",
",",
"true",
")",
"+",
"RESET",
"+",
"colour",
")",
";",
"else",
"out",
".",
"push",
"(",
"msg_item",
")",
";",
"}",
"this",
".",
"print",
"(",
"colour",
"+",
"out",
".",
"join",
"(",
"' '",
")",
"+",
"colour",
"+",
"\" \"",
"+",
"RESET",
")",
";",
"}",
";",
"MultiLine",
".",
"prototype",
".",
"info",
"=",
"function",
"(",
"msg",
")",
"{",
"this",
".",
"parse_and_print",
"(",
"msg",
",",
"GREEN",
")",
";",
"}",
";",
"MultiLine",
".",
"prototype",
".",
"mark",
"=",
"function",
"(",
"msg",
")",
"{",
"this",
".",
"parse_and_print",
"(",
"msg",
",",
"LIGHT_GREEN",
")",
";",
"}",
";",
"MultiLine",
".",
"prototype",
".",
"error",
"=",
"function",
"(",
"msg",
")",
"{",
"this",
".",
"parse_and_print",
"(",
"msg",
",",
"RED",
")",
";",
"}",
";",
"MultiLine",
".",
"prototype",
".",
"warn",
"=",
"function",
"(",
"msg",
")",
"{",
"this",
".",
"parse_and_print",
"(",
"msg",
",",
"YELLOW",
")",
";",
"}",
";",
"MultiLine",
".",
"prototype",
".",
"print",
"=",
"function",
"(",
"msg",
")",
"{",
"console",
".",
"log",
"(",
"msg",
")",
";",
"}",
";",
"}"
]
| Print every message in new line
@constructor | [
"Print",
"every",
"message",
"in",
"new",
"line"
]
| 5b9979e26fadb5201db0683207ced0a1fd335ab0 | https://github.com/silvertoad/color.log.js/blob/5b9979e26fadb5201db0683207ced0a1fd335ab0/loggers.js#L14-L55 | train |
silvertoad/color.log.js | loggers.js | SingleLine | function SingleLine()
{
SingleLine.prototype.print = function(msg)
{
var result = check();
if (result.success)
{
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(msg);
}
else
MultiLine.prototype.print('missed method: ' + result.required_method + ' ' + msg);
};
SingleLine.prototype.info = function(msg)
{
this.parse_and_print(arguments, GREEN);
};
SingleLine.prototype.mark = function(msg)
{
this.parse_and_print(arguments, LIGHT_GREEN);
};
SingleLine.prototype.error = function(msg)
{
this.parse_and_print(arguments, RED);
};
SingleLine.prototype.warn = function(msg)
{
this.parse_and_print(arguments, YELLOW);
};
function check()
{
var check = ['clearLine', 'cursorTo', 'write'];
for (var i = 0; i < check.length; i++)
{
var method = check[i];
if (!(method in process.stdout))
return {required_method: method};
}
return {success: true};
}
} | javascript | function SingleLine()
{
SingleLine.prototype.print = function(msg)
{
var result = check();
if (result.success)
{
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(msg);
}
else
MultiLine.prototype.print('missed method: ' + result.required_method + ' ' + msg);
};
SingleLine.prototype.info = function(msg)
{
this.parse_and_print(arguments, GREEN);
};
SingleLine.prototype.mark = function(msg)
{
this.parse_and_print(arguments, LIGHT_GREEN);
};
SingleLine.prototype.error = function(msg)
{
this.parse_and_print(arguments, RED);
};
SingleLine.prototype.warn = function(msg)
{
this.parse_and_print(arguments, YELLOW);
};
function check()
{
var check = ['clearLine', 'cursorTo', 'write'];
for (var i = 0; i < check.length; i++)
{
var method = check[i];
if (!(method in process.stdout))
return {required_method: method};
}
return {success: true};
}
} | [
"function",
"SingleLine",
"(",
")",
"{",
"SingleLine",
".",
"prototype",
".",
"print",
"=",
"function",
"(",
"msg",
")",
"{",
"var",
"result",
"=",
"check",
"(",
")",
";",
"if",
"(",
"result",
".",
"success",
")",
"{",
"process",
".",
"stdout",
".",
"clearLine",
"(",
")",
";",
"process",
".",
"stdout",
".",
"cursorTo",
"(",
"0",
")",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"msg",
")",
";",
"}",
"else",
"MultiLine",
".",
"prototype",
".",
"print",
"(",
"'missed method: '",
"+",
"result",
".",
"required_method",
"+",
"' '",
"+",
"msg",
")",
";",
"}",
";",
"SingleLine",
".",
"prototype",
".",
"info",
"=",
"function",
"(",
"msg",
")",
"{",
"this",
".",
"parse_and_print",
"(",
"arguments",
",",
"GREEN",
")",
";",
"}",
";",
"SingleLine",
".",
"prototype",
".",
"mark",
"=",
"function",
"(",
"msg",
")",
"{",
"this",
".",
"parse_and_print",
"(",
"arguments",
",",
"LIGHT_GREEN",
")",
";",
"}",
";",
"SingleLine",
".",
"prototype",
".",
"error",
"=",
"function",
"(",
"msg",
")",
"{",
"this",
".",
"parse_and_print",
"(",
"arguments",
",",
"RED",
")",
";",
"}",
";",
"SingleLine",
".",
"prototype",
".",
"warn",
"=",
"function",
"(",
"msg",
")",
"{",
"this",
".",
"parse_and_print",
"(",
"arguments",
",",
"YELLOW",
")",
";",
"}",
";",
"function",
"check",
"(",
")",
"{",
"var",
"check",
"=",
"[",
"'clearLine'",
",",
"'cursorTo'",
",",
"'write'",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"check",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"method",
"=",
"check",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"(",
"method",
"in",
"process",
".",
"stdout",
")",
")",
"return",
"{",
"required_method",
":",
"method",
"}",
";",
"}",
"return",
"{",
"success",
":",
"true",
"}",
";",
"}",
"}"
]
| Print every message in single line
@constructor | [
"Print",
"every",
"message",
"in",
"single",
"line"
]
| 5b9979e26fadb5201db0683207ced0a1fd335ab0 | https://github.com/silvertoad/color.log.js/blob/5b9979e26fadb5201db0683207ced0a1fd335ab0/loggers.js#L61-L107 | train |
tether/manner-test | index.js | salute | function salute (cb) {
let value
try {
value = cb()
if (value instanceof Error) value = Promise.reject(value)
} catch (e) {
value = Promise.reject(e)
}
return value
} | javascript | function salute (cb) {
let value
try {
value = cb()
if (value instanceof Error) value = Promise.reject(value)
} catch (e) {
value = Promise.reject(e)
}
return value
} | [
"function",
"salute",
"(",
"cb",
")",
"{",
"let",
"value",
"try",
"{",
"value",
"=",
"cb",
"(",
")",
"if",
"(",
"value",
"instanceof",
"Error",
")",
"value",
"=",
"Promise",
".",
"reject",
"(",
"value",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"value",
"=",
"Promise",
".",
"reject",
"(",
"e",
")",
"}",
"return",
"value",
"}"
]
| Simulate salute behavious.
@param {Function} cb
@see https://github.com/bredele/salute
@api private | [
"Simulate",
"salute",
"behavious",
"."
]
| 8fde3f969325155ffbff54f7c78c7e36f69b1fc2 | https://github.com/tether/manner-test/blob/8fde3f969325155ffbff54f7c78c7e36f69b1fc2/index.js#L76-L85 | train |
paulrayes/gaze-cli | index.js | run | function run(filepath) {
var startTime = process.hrtime();
var uniqueCommand = command.replace('$path', filepath);
if (!argv.silent) {
console.log('>', uniqueCommand);
}
execshell(uniqueCommand);
if (!argv.silent) {
console.log('Finished in', prettyHrtime(process.hrtime(startTime)));
}
} | javascript | function run(filepath) {
var startTime = process.hrtime();
var uniqueCommand = command.replace('$path', filepath);
if (!argv.silent) {
console.log('>', uniqueCommand);
}
execshell(uniqueCommand);
if (!argv.silent) {
console.log('Finished in', prettyHrtime(process.hrtime(startTime)));
}
} | [
"function",
"run",
"(",
"filepath",
")",
"{",
"var",
"startTime",
"=",
"process",
".",
"hrtime",
"(",
")",
";",
"var",
"uniqueCommand",
"=",
"command",
".",
"replace",
"(",
"'$path'",
",",
"filepath",
")",
";",
"if",
"(",
"!",
"argv",
".",
"silent",
")",
"{",
"console",
".",
"log",
"(",
"'>'",
",",
"uniqueCommand",
")",
";",
"}",
"execshell",
"(",
"uniqueCommand",
")",
";",
"if",
"(",
"!",
"argv",
".",
"silent",
")",
"{",
"console",
".",
"log",
"(",
"'Finished in'",
",",
"prettyHrtime",
"(",
"process",
".",
"hrtime",
"(",
"startTime",
")",
")",
")",
";",
"}",
"}"
]
| Function to run when something changes | [
"Function",
"to",
"run",
"when",
"something",
"changes"
]
| 09cbeaaae049e03af62e200631b6d21ac10b1650 | https://github.com/paulrayes/gaze-cli/blob/09cbeaaae049e03af62e200631b6d21ac10b1650/index.js#L82-L92 | train |
oskarhagberg/gbgcity | lib/parking.js | getParkings | function getParkings(latitude, longitude, radius, type, params, callback) {
if(!latitude || !longitude || !radius) {
callback(new Error("Parking.getParkings: latitude, longitude and radius required"));
return;
}
params = params || {};
params.latitude = latitude;
params.longitude = longitude;
params.radius = radius;
var subResource;
switch(type) {
case 'bus': subResource = 'BusParkings';
break;
case 'handicap': subResource = 'HandicapParkings';
break;
case 'mc': subResource = 'MCParkings';
break;
case 'private': subResource = 'PrivateParkings';
break;
case 'publicTime': subResource = 'PublicTimeParkings';
break;
case 'publicToll': subResource = 'PublicTollParkings';
break;
case 'residential': subResource = 'ResidentialParkings';
break;
case 'truck': subResource = 'TruckParkings';
break;
default:
callback(new Error("Parking.getParkings: unknown type: " + type));
}
core.callApi('/ParkingService/v1.0/' + subResource, params, callback);
} | javascript | function getParkings(latitude, longitude, radius, type, params, callback) {
if(!latitude || !longitude || !radius) {
callback(new Error("Parking.getParkings: latitude, longitude and radius required"));
return;
}
params = params || {};
params.latitude = latitude;
params.longitude = longitude;
params.radius = radius;
var subResource;
switch(type) {
case 'bus': subResource = 'BusParkings';
break;
case 'handicap': subResource = 'HandicapParkings';
break;
case 'mc': subResource = 'MCParkings';
break;
case 'private': subResource = 'PrivateParkings';
break;
case 'publicTime': subResource = 'PublicTimeParkings';
break;
case 'publicToll': subResource = 'PublicTollParkings';
break;
case 'residential': subResource = 'ResidentialParkings';
break;
case 'truck': subResource = 'TruckParkings';
break;
default:
callback(new Error("Parking.getParkings: unknown type: " + type));
}
core.callApi('/ParkingService/v1.0/' + subResource, params, callback);
} | [
"function",
"getParkings",
"(",
"latitude",
",",
"longitude",
",",
"radius",
",",
"type",
",",
"params",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"latitude",
"||",
"!",
"longitude",
"||",
"!",
"radius",
")",
"{",
"callback",
"(",
"new",
"Error",
"(",
"\"Parking.getParkings: latitude, longitude and radius required\"",
")",
")",
";",
"return",
";",
"}",
"params",
"=",
"params",
"||",
"{",
"}",
";",
"params",
".",
"latitude",
"=",
"latitude",
";",
"params",
".",
"longitude",
"=",
"longitude",
";",
"params",
".",
"radius",
"=",
"radius",
";",
"var",
"subResource",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"'bus'",
":",
"subResource",
"=",
"'BusParkings'",
";",
"break",
";",
"case",
"'handicap'",
":",
"subResource",
"=",
"'HandicapParkings'",
";",
"break",
";",
"case",
"'mc'",
":",
"subResource",
"=",
"'MCParkings'",
";",
"break",
";",
"case",
"'private'",
":",
"subResource",
"=",
"'PrivateParkings'",
";",
"break",
";",
"case",
"'publicTime'",
":",
"subResource",
"=",
"'PublicTimeParkings'",
";",
"break",
";",
"case",
"'publicToll'",
":",
"subResource",
"=",
"'PublicTollParkings'",
";",
"break",
";",
"case",
"'residential'",
":",
"subResource",
"=",
"'ResidentialParkings'",
";",
"break",
";",
"case",
"'truck'",
":",
"subResource",
"=",
"'TruckParkings'",
";",
"break",
";",
"default",
":",
"callback",
"(",
"new",
"Error",
"(",
"\"Parking.getParkings: unknown type: \"",
"+",
"type",
")",
")",
";",
"}",
"core",
".",
"callApi",
"(",
"'/ParkingService/v1.0/'",
"+",
"subResource",
",",
"params",
",",
"callback",
")",
";",
"}"
]
| Returns all public parkings of the given type.
@memberof module:gbgcity/Parking
@param {String|Number} latitude The latitude of the location around which to explore.
@param {String|Number} longitude The longitude of the location around which to explore.
@param {String|Number} radius The radius of the area to explore.
@param {String} type The parking type. Any of: bus, handicap, mc, private, publicTime, publicToll, residential, truck
@param {Object} [params] An object containing additional parameters.
@param {Function} callback The function to call with results, function({Error} error, {Object} results)/
@see http://data.goteborg.se/ParkingService/v1.0/help/operations/GetBusParkings and similar | [
"Returns",
"all",
"public",
"parkings",
"of",
"the",
"given",
"type",
"."
]
| d2de903b2fba83cc953ae218905380fef080cb2d | https://github.com/oskarhagberg/gbgcity/blob/d2de903b2fba83cc953ae218905380fef080cb2d/lib/parking.js#L17-L48 | train |
oskarhagberg/gbgcity | lib/parking.js | getPublicPayMachines | function getPublicPayMachines(latitude, longitude, radius, params, callback) {
if(!latitude || !longitude || !radius) {
callback(new Error("Parking.getPublicPayMachines: latitude, longitude and radius required"));
return;
}
params = params || {};
params.latitude = latitude;
params.longitude = longitude;
params.radius = radius;
core.callApi('/ParkingService/v1.0/PublicPayMachines', params, callback);
} | javascript | function getPublicPayMachines(latitude, longitude, radius, params, callback) {
if(!latitude || !longitude || !radius) {
callback(new Error("Parking.getPublicPayMachines: latitude, longitude and radius required"));
return;
}
params = params || {};
params.latitude = latitude;
params.longitude = longitude;
params.radius = radius;
core.callApi('/ParkingService/v1.0/PublicPayMachines', params, callback);
} | [
"function",
"getPublicPayMachines",
"(",
"latitude",
",",
"longitude",
",",
"radius",
",",
"params",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"latitude",
"||",
"!",
"longitude",
"||",
"!",
"radius",
")",
"{",
"callback",
"(",
"new",
"Error",
"(",
"\"Parking.getPublicPayMachines: latitude, longitude and radius required\"",
")",
")",
";",
"return",
";",
"}",
"params",
"=",
"params",
"||",
"{",
"}",
";",
"params",
".",
"latitude",
"=",
"latitude",
";",
"params",
".",
"longitude",
"=",
"longitude",
";",
"params",
".",
"radius",
"=",
"radius",
";",
"core",
".",
"callApi",
"(",
"'/ParkingService/v1.0/PublicPayMachines'",
",",
"params",
",",
"callback",
")",
";",
"}"
]
| Returns all public pay machines.
@memberof module:gbgcity/Parking
@param {String|Number} latitude The latitude of the location around which to explore.
@param {String|Number} longitude The longitude of the location around which to explore.
@param {String|Number} radius The radius of the area to explore.
@param {Object} [params] An object containing additional parameters.
@param {Function} callback The function to call with results, function({Error} error, {Object} results)/
@see http://data.goteborg.se/ParkingService/v1.0/help/operations/GetPublicPaymachines | [
"Returns",
"all",
"public",
"pay",
"machines",
"."
]
| d2de903b2fba83cc953ae218905380fef080cb2d | https://github.com/oskarhagberg/gbgcity/blob/d2de903b2fba83cc953ae218905380fef080cb2d/lib/parking.js#L61-L71 | train |
doowb/sessionify | index.js | sessionify | function sessionify (fn, session, context) {
if (!session) {
throw new Error('sessionify expects a session-cache object as `session`');
}
var bind = session.bind;
if (typeof fn === 'object' && fn.on) {
bind = session.bindEmitter;
}
if (context) {
bind.call(session, fn, context);
} else {
bind.call(session, fn);
}
return fn;
} | javascript | function sessionify (fn, session, context) {
if (!session) {
throw new Error('sessionify expects a session-cache object as `session`');
}
var bind = session.bind;
if (typeof fn === 'object' && fn.on) {
bind = session.bindEmitter;
}
if (context) {
bind.call(session, fn, context);
} else {
bind.call(session, fn);
}
return fn;
} | [
"function",
"sessionify",
"(",
"fn",
",",
"session",
",",
"context",
")",
"{",
"if",
"(",
"!",
"session",
")",
"{",
"throw",
"new",
"Error",
"(",
"'sessionify expects a session-cache object as `session`'",
")",
";",
"}",
"var",
"bind",
"=",
"session",
".",
"bind",
";",
"if",
"(",
"typeof",
"fn",
"===",
"'object'",
"&&",
"fn",
".",
"on",
")",
"{",
"bind",
"=",
"session",
".",
"bindEmitter",
";",
"}",
"if",
"(",
"context",
")",
"{",
"bind",
".",
"call",
"(",
"session",
",",
"fn",
",",
"context",
")",
";",
"}",
"else",
"{",
"bind",
".",
"call",
"(",
"session",
",",
"fn",
")",
";",
"}",
"return",
"fn",
";",
"}"
]
| Bind a function, EventEmitter, or Stream to the provided session object
with an optional context.
@param {Function|EventEmitter|Stream} `fn` Object to bind to.
@param {Object} `session` session-cache object to bind with.
@param {Object} `context` Optional context to bind to the sesssion.
@return {*} Bound object
@api public | [
"Bind",
"a",
"function",
"EventEmitter",
"or",
"Stream",
"to",
"the",
"provided",
"session",
"object",
"with",
"an",
"optional",
"context",
"."
]
| 1a49eb39d771cc5e60db4008312edd4792ef6ed8 | https://github.com/doowb/sessionify/blob/1a49eb39d771cc5e60db4008312edd4792ef6ed8/index.js#L23-L39 | train |
tunnckoCore/capture-spawn | index.js | SpawnError | function SpawnError (message, options) {
return errorBase('SpawnError', function (message, options) {
this.name = 'SpawnError'
this.message = message
this.code = options.code
this.buffer = options.buffer
}).call(this, message, options)
} | javascript | function SpawnError (message, options) {
return errorBase('SpawnError', function (message, options) {
this.name = 'SpawnError'
this.message = message
this.code = options.code
this.buffer = options.buffer
}).call(this, message, options)
} | [
"function",
"SpawnError",
"(",
"message",
",",
"options",
")",
"{",
"return",
"errorBase",
"(",
"'SpawnError'",
",",
"function",
"(",
"message",
",",
"options",
")",
"{",
"this",
".",
"name",
"=",
"'SpawnError'",
"this",
".",
"message",
"=",
"message",
"this",
".",
"code",
"=",
"options",
".",
"code",
"this",
".",
"buffer",
"=",
"options",
".",
"buffer",
"}",
")",
".",
"call",
"(",
"this",
",",
"message",
",",
"options",
")",
"}"
]
| > Custom error class that is thrown on error.
@param {String} `message`
@param {Object} `options`
@api private | [
">",
"Custom",
"error",
"class",
"that",
"is",
"thrown",
"on",
"error",
"."
]
| a7253d7b3f1bb74912aec8638b20bad094334dc8 | https://github.com/tunnckoCore/capture-spawn/blob/a7253d7b3f1bb74912aec8638b20bad094334dc8/index.js#L87-L94 | train |
dak0rn/espressojs | lib/utils/handler.js | function(api, handler) {
if( 0 === arguments.length )
throw new Error('utils.handler.register needs arguments');
if( ! _.isObject(api) )
throw new Error('utils.handler.register needs an espressojs API');
if( ! (handler instanceof Handler) )
throw new Error('utils.handler.register needs a Handler');
// Add it to _ids
api._ids[ handler.getPattern().getExpression().toString() ] = handler;
// Add it to _names if any
var name = handler.getOption('name');
if( _.isString(name) && ! _.isEmpty(name) )
api._names[ name ] = handler;
} | javascript | function(api, handler) {
if( 0 === arguments.length )
throw new Error('utils.handler.register needs arguments');
if( ! _.isObject(api) )
throw new Error('utils.handler.register needs an espressojs API');
if( ! (handler instanceof Handler) )
throw new Error('utils.handler.register needs a Handler');
// Add it to _ids
api._ids[ handler.getPattern().getExpression().toString() ] = handler;
// Add it to _names if any
var name = handler.getOption('name');
if( _.isString(name) && ! _.isEmpty(name) )
api._names[ name ] = handler;
} | [
"function",
"(",
"api",
",",
"handler",
")",
"{",
"if",
"(",
"0",
"===",
"arguments",
".",
"length",
")",
"throw",
"new",
"Error",
"(",
"'utils.handler.register needs arguments'",
")",
";",
"if",
"(",
"!",
"_",
".",
"isObject",
"(",
"api",
")",
")",
"throw",
"new",
"Error",
"(",
"'utils.handler.register needs an espressojs API'",
")",
";",
"if",
"(",
"!",
"(",
"handler",
"instanceof",
"Handler",
")",
")",
"throw",
"new",
"Error",
"(",
"'utils.handler.register needs a Handler'",
")",
";",
"api",
".",
"_ids",
"[",
"handler",
".",
"getPattern",
"(",
")",
".",
"getExpression",
"(",
")",
".",
"toString",
"(",
")",
"]",
"=",
"handler",
";",
"var",
"name",
"=",
"handler",
".",
"getOption",
"(",
"'name'",
")",
";",
"if",
"(",
"_",
".",
"isString",
"(",
"name",
")",
"&&",
"!",
"_",
".",
"isEmpty",
"(",
"name",
")",
")",
"api",
".",
"_names",
"[",
"name",
"]",
"=",
"handler",
";",
"}"
]
| Registers a handler in the API | [
"Registers",
"a",
"handler",
"in",
"the",
"API"
]
| 7f8e015f31113215abbe9988ae7f2c7dd5d8572b | https://github.com/dak0rn/espressojs/blob/7f8e015f31113215abbe9988ae7f2c7dd5d8572b/lib/utils/handler.js#L14-L33 | train |
|
dak0rn/espressojs | lib/utils/handler.js | function(api) {
if( ! _.isObject(api) )
throw new Error('utils.handler.buildResourceTable needs an espressojs API');
api._resources = _( api._ids ).values().reject( _.isUndefined ).value();
} | javascript | function(api) {
if( ! _.isObject(api) )
throw new Error('utils.handler.buildResourceTable needs an espressojs API');
api._resources = _( api._ids ).values().reject( _.isUndefined ).value();
} | [
"function",
"(",
"api",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isObject",
"(",
"api",
")",
")",
"throw",
"new",
"Error",
"(",
"'utils.handler.buildResourceTable needs an espressojs API'",
")",
";",
"api",
".",
"_resources",
"=",
"_",
"(",
"api",
".",
"_ids",
")",
".",
"values",
"(",
")",
".",
"reject",
"(",
"_",
".",
"isUndefined",
")",
".",
"value",
"(",
")",
";",
"}"
]
| Builds the APIs resource table | [
"Builds",
"the",
"APIs",
"resource",
"table"
]
| 7f8e015f31113215abbe9988ae7f2c7dd5d8572b | https://github.com/dak0rn/espressojs/blob/7f8e015f31113215abbe9988ae7f2c7dd5d8572b/lib/utils/handler.js#L58-L63 | train |
|
hgoebl/entintar | lib/LineInfoEmitter.js | analyzeLine | function analyzeLine(line, rules) {
var result = {
line: line
};
rules.rules.forEach(function (rule) {
if (rule.re.test(line)) {
line = line.replace(rule.re, rule.replace);
if (rule.emitLevel) {
if (result.emitLevel) {
result.emitLevel = Math.min(result.emitLevel, rule.emitLevel);
}
else {
result.emitLevel = rule.emitLevel;
}
}
}
});
if (!result.emitLevel) {
result.emitLevel = rules.defaultEmitLevel || 5;
}
result.colored = line;
return result;
} | javascript | function analyzeLine(line, rules) {
var result = {
line: line
};
rules.rules.forEach(function (rule) {
if (rule.re.test(line)) {
line = line.replace(rule.re, rule.replace);
if (rule.emitLevel) {
if (result.emitLevel) {
result.emitLevel = Math.min(result.emitLevel, rule.emitLevel);
}
else {
result.emitLevel = rule.emitLevel;
}
}
}
});
if (!result.emitLevel) {
result.emitLevel = rules.defaultEmitLevel || 5;
}
result.colored = line;
return result;
} | [
"function",
"analyzeLine",
"(",
"line",
",",
"rules",
")",
"{",
"var",
"result",
"=",
"{",
"line",
":",
"line",
"}",
";",
"rules",
".",
"rules",
".",
"forEach",
"(",
"function",
"(",
"rule",
")",
"{",
"if",
"(",
"rule",
".",
"re",
".",
"test",
"(",
"line",
")",
")",
"{",
"line",
"=",
"line",
".",
"replace",
"(",
"rule",
".",
"re",
",",
"rule",
".",
"replace",
")",
";",
"if",
"(",
"rule",
".",
"emitLevel",
")",
"{",
"if",
"(",
"result",
".",
"emitLevel",
")",
"{",
"result",
".",
"emitLevel",
"=",
"Math",
".",
"min",
"(",
"result",
".",
"emitLevel",
",",
"rule",
".",
"emitLevel",
")",
";",
"}",
"else",
"{",
"result",
".",
"emitLevel",
"=",
"rule",
".",
"emitLevel",
";",
"}",
"}",
"}",
"}",
")",
";",
"if",
"(",
"!",
"result",
".",
"emitLevel",
")",
"{",
"result",
".",
"emitLevel",
"=",
"rules",
".",
"defaultEmitLevel",
"||",
"5",
";",
"}",
"result",
".",
"colored",
"=",
"line",
";",
"return",
"result",
";",
"}"
]
| Replace color codes in str with real curses colors.
@returns object with following attributes:
colored: the line with color marker e.g. #{c_cyan}
line: the original line coming from the input stream
emitLevel: the minimal level (1=very import, 9=very verbose) | [
"Replace",
"color",
"codes",
"in",
"str",
"with",
"real",
"curses",
"colors",
"."
]
| cc6be17961bebfa25e247992d06af5ffaa618f4e | https://github.com/hgoebl/entintar/blob/cc6be17961bebfa25e247992d06af5ffaa618f4e/lib/LineInfoEmitter.js#L15-L37 | train |
wojtkowiak/meteor-desktop-test-suite | src/suite.js | getNpm | function getNpm() {
let execResult;
let version;
let version3;
let npm;
if (shell.which('npm')) {
execResult = shell.exec('npm --version', { silent: true });
if (execResult.code === 0) {
version = execResult.stdout;
}
}
if (version !== null && semver.satisfies(version, '>= 3.0.0')) {
npm = 'npm';
}
if (!npm) {
if (shell.which('npm3')) {
execResult = shell.exec('npm3 --version', { silent: true });
if (execResult.code === 0) {
version3 = execResult.stdout;
}
}
if (version3 === null) {
npm = 'npm';
} else {
npm = 'npm3';
}
}
return npm;
} | javascript | function getNpm() {
let execResult;
let version;
let version3;
let npm;
if (shell.which('npm')) {
execResult = shell.exec('npm --version', { silent: true });
if (execResult.code === 0) {
version = execResult.stdout;
}
}
if (version !== null && semver.satisfies(version, '>= 3.0.0')) {
npm = 'npm';
}
if (!npm) {
if (shell.which('npm3')) {
execResult = shell.exec('npm3 --version', { silent: true });
if (execResult.code === 0) {
version3 = execResult.stdout;
}
}
if (version3 === null) {
npm = 'npm';
} else {
npm = 'npm3';
}
}
return npm;
} | [
"function",
"getNpm",
"(",
")",
"{",
"let",
"execResult",
";",
"let",
"version",
";",
"let",
"version3",
";",
"let",
"npm",
";",
"if",
"(",
"shell",
".",
"which",
"(",
"'npm'",
")",
")",
"{",
"execResult",
"=",
"shell",
".",
"exec",
"(",
"'npm --version'",
",",
"{",
"silent",
":",
"true",
"}",
")",
";",
"if",
"(",
"execResult",
".",
"code",
"===",
"0",
")",
"{",
"version",
"=",
"execResult",
".",
"stdout",
";",
"}",
"}",
"if",
"(",
"version",
"!==",
"null",
"&&",
"semver",
".",
"satisfies",
"(",
"version",
",",
"'>= 3.0.0'",
")",
")",
"{",
"npm",
"=",
"'npm'",
";",
"}",
"if",
"(",
"!",
"npm",
")",
"{",
"if",
"(",
"shell",
".",
"which",
"(",
"'npm3'",
")",
")",
"{",
"execResult",
"=",
"shell",
".",
"exec",
"(",
"'npm3 --version'",
",",
"{",
"silent",
":",
"true",
"}",
")",
";",
"if",
"(",
"execResult",
".",
"code",
"===",
"0",
")",
"{",
"version3",
"=",
"execResult",
".",
"stdout",
";",
"}",
"}",
"if",
"(",
"version3",
"===",
"null",
")",
"{",
"npm",
"=",
"'npm'",
";",
"}",
"else",
"{",
"npm",
"=",
"'npm3'",
";",
"}",
"}",
"return",
"npm",
";",
"}"
]
| Looks for npm.
@returns {*} | [
"Looks",
"for",
"npm",
"."
]
| 41ac662e5b28890d9c456d48768f04ee388a7b63 | https://github.com/wojtkowiak/meteor-desktop-test-suite/blob/41ac662e5b28890d9c456d48768f04ee388a7b63/src/suite.js#L15-L46 | train |
vtardia/varo-flux | lib/Dispatcher.js | invoke | function invoke(id) {
this.isPending[id] = true;
this.callbacks[id](this.pendingPayload);
this.isHandled[id] = true;
} | javascript | function invoke(id) {
this.isPending[id] = true;
this.callbacks[id](this.pendingPayload);
this.isHandled[id] = true;
} | [
"function",
"invoke",
"(",
"id",
")",
"{",
"this",
".",
"isPending",
"[",
"id",
"]",
"=",
"true",
";",
"this",
".",
"callbacks",
"[",
"id",
"]",
"(",
"this",
".",
"pendingPayload",
")",
";",
"this",
".",
"isHandled",
"[",
"id",
"]",
"=",
"true",
";",
"}"
]
| Invoke a callback | [
"Invoke",
"a",
"callback"
]
| e1b07901f0ac70e09b25a23c14f8e2e796f95e54 | https://github.com/vtardia/varo-flux/blob/e1b07901f0ac70e09b25a23c14f8e2e796f95e54/lib/Dispatcher.js#L26-L30 | train |
vtardia/varo-flux | lib/Dispatcher.js | start | function start(payload) {
for (var id in this.callbacks) {
this.isPending[id] = false;
this.isHandled[id] = false;
}
this.isDispatching = true;
this.pendingPayload = payload;
} | javascript | function start(payload) {
for (var id in this.callbacks) {
this.isPending[id] = false;
this.isHandled[id] = false;
}
this.isDispatching = true;
this.pendingPayload = payload;
} | [
"function",
"start",
"(",
"payload",
")",
"{",
"for",
"(",
"var",
"id",
"in",
"this",
".",
"callbacks",
")",
"{",
"this",
".",
"isPending",
"[",
"id",
"]",
"=",
"false",
";",
"this",
".",
"isHandled",
"[",
"id",
"]",
"=",
"false",
";",
"}",
"this",
".",
"isDispatching",
"=",
"true",
";",
"this",
".",
"pendingPayload",
"=",
"payload",
";",
"}"
]
| Set up dispatch action | [
"Set",
"up",
"dispatch",
"action"
]
| e1b07901f0ac70e09b25a23c14f8e2e796f95e54 | https://github.com/vtardia/varo-flux/blob/e1b07901f0ac70e09b25a23c14f8e2e796f95e54/lib/Dispatcher.js#L35-L42 | train |
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/htmlparser/filter.js | function( rules, options ) {
var priority;
// Backward compatibility.
if ( typeof options == 'number' )
priority = options;
// New version - try reading from options.
else if ( options && ( 'priority' in options ) )
priority = options.priority;
// Defaults.
if ( typeof priority != 'number' )
priority = 10;
if ( typeof options != 'object' )
options = {};
// Add the elementNames.
if ( rules.elementNames )
this.elementNameRules.addMany( rules.elementNames, priority, options );
// Add the attributeNames.
if ( rules.attributeNames )
this.attributeNameRules.addMany( rules.attributeNames, priority, options );
// Add the elements.
if ( rules.elements )
addNamedRules( this.elementsRules, rules.elements, priority, options );
// Add the attributes.
if ( rules.attributes )
addNamedRules( this.attributesRules, rules.attributes, priority, options );
// Add the text.
if ( rules.text )
this.textRules.add( rules.text, priority, options );
// Add the comment.
if ( rules.comment )
this.commentRules.add( rules.comment, priority, options );
// Add root node rules.
if ( rules.root )
this.rootRules.add( rules.root, priority, options );
} | javascript | function( rules, options ) {
var priority;
// Backward compatibility.
if ( typeof options == 'number' )
priority = options;
// New version - try reading from options.
else if ( options && ( 'priority' in options ) )
priority = options.priority;
// Defaults.
if ( typeof priority != 'number' )
priority = 10;
if ( typeof options != 'object' )
options = {};
// Add the elementNames.
if ( rules.elementNames )
this.elementNameRules.addMany( rules.elementNames, priority, options );
// Add the attributeNames.
if ( rules.attributeNames )
this.attributeNameRules.addMany( rules.attributeNames, priority, options );
// Add the elements.
if ( rules.elements )
addNamedRules( this.elementsRules, rules.elements, priority, options );
// Add the attributes.
if ( rules.attributes )
addNamedRules( this.attributesRules, rules.attributes, priority, options );
// Add the text.
if ( rules.text )
this.textRules.add( rules.text, priority, options );
// Add the comment.
if ( rules.comment )
this.commentRules.add( rules.comment, priority, options );
// Add root node rules.
if ( rules.root )
this.rootRules.add( rules.root, priority, options );
} | [
"function",
"(",
"rules",
",",
"options",
")",
"{",
"var",
"priority",
";",
"if",
"(",
"typeof",
"options",
"==",
"'number'",
")",
"priority",
"=",
"options",
";",
"else",
"if",
"(",
"options",
"&&",
"(",
"'priority'",
"in",
"options",
")",
")",
"priority",
"=",
"options",
".",
"priority",
";",
"if",
"(",
"typeof",
"priority",
"!=",
"'number'",
")",
"priority",
"=",
"10",
";",
"if",
"(",
"typeof",
"options",
"!=",
"'object'",
")",
"options",
"=",
"{",
"}",
";",
"if",
"(",
"rules",
".",
"elementNames",
")",
"this",
".",
"elementNameRules",
".",
"addMany",
"(",
"rules",
".",
"elementNames",
",",
"priority",
",",
"options",
")",
";",
"if",
"(",
"rules",
".",
"attributeNames",
")",
"this",
".",
"attributeNameRules",
".",
"addMany",
"(",
"rules",
".",
"attributeNames",
",",
"priority",
",",
"options",
")",
";",
"if",
"(",
"rules",
".",
"elements",
")",
"addNamedRules",
"(",
"this",
".",
"elementsRules",
",",
"rules",
".",
"elements",
",",
"priority",
",",
"options",
")",
";",
"if",
"(",
"rules",
".",
"attributes",
")",
"addNamedRules",
"(",
"this",
".",
"attributesRules",
",",
"rules",
".",
"attributes",
",",
"priority",
",",
"options",
")",
";",
"if",
"(",
"rules",
".",
"text",
")",
"this",
".",
"textRules",
".",
"add",
"(",
"rules",
".",
"text",
",",
"priority",
",",
"options",
")",
";",
"if",
"(",
"rules",
".",
"comment",
")",
"this",
".",
"commentRules",
".",
"add",
"(",
"rules",
".",
"comment",
",",
"priority",
",",
"options",
")",
";",
"if",
"(",
"rules",
".",
"root",
")",
"this",
".",
"rootRules",
".",
"add",
"(",
"rules",
".",
"root",
",",
"priority",
",",
"options",
")",
";",
"}"
]
| Add rules to this filter.
@param {CKEDITOR.htmlParser.filterRulesDefinition} rules Object containing filter rules.
@param {Object/Number} [options] Object containing rules' options or a priority
(for a backward compatibility with CKEditor versions up to 4.2.x).
@param {Number} [options.priority=10] The priority of a rule.
@param {Boolean} [options.applyToAll=false] Whether to apply rule to non-editable
elements and their descendants too. | [
"Add",
"rules",
"to",
"this",
"filter",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmlparser/filter.js#L117-L160 | train |
|
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/htmlparser/filter.js | function( rule, priority, options ) {
this.rules.splice( this.findIndex( priority ), 0, {
value: rule,
priority: priority,
options: options
} );
} | javascript | function( rule, priority, options ) {
this.rules.splice( this.findIndex( priority ), 0, {
value: rule,
priority: priority,
options: options
} );
} | [
"function",
"(",
"rule",
",",
"priority",
",",
"options",
")",
"{",
"this",
".",
"rules",
".",
"splice",
"(",
"this",
".",
"findIndex",
"(",
"priority",
")",
",",
"0",
",",
"{",
"value",
":",
"rule",
",",
"priority",
":",
"priority",
",",
"options",
":",
"options",
"}",
")",
";",
"}"
]
| Adds specified rule to this group.
@param {Function/Array} rule Function for function based rule or [ pattern, replacement ] array for
rule applicable to names.
@param {Number} priority
@param options | [
"Adds",
"specified",
"rule",
"to",
"this",
"group",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmlparser/filter.js#L262-L268 | train |
|
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/htmlparser/filter.js | function( rules, priority, options ) {
var args = [ this.findIndex( priority ), 0 ];
for ( var i = 0, len = rules.length; i < len; i++ ) {
args.push( {
value: rules[ i ],
priority: priority,
options: options
} );
}
this.rules.splice.apply( this.rules, args );
} | javascript | function( rules, priority, options ) {
var args = [ this.findIndex( priority ), 0 ];
for ( var i = 0, len = rules.length; i < len; i++ ) {
args.push( {
value: rules[ i ],
priority: priority,
options: options
} );
}
this.rules.splice.apply( this.rules, args );
} | [
"function",
"(",
"rules",
",",
"priority",
",",
"options",
")",
"{",
"var",
"args",
"=",
"[",
"this",
".",
"findIndex",
"(",
"priority",
")",
",",
"0",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"rules",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"args",
".",
"push",
"(",
"{",
"value",
":",
"rules",
"[",
"i",
"]",
",",
"priority",
":",
"priority",
",",
"options",
":",
"options",
"}",
")",
";",
"}",
"this",
".",
"rules",
".",
"splice",
".",
"apply",
"(",
"this",
".",
"rules",
",",
"args",
")",
";",
"}"
]
| Adds specified rules to this group.
@param {Array} rules Array of rules - see {@link #add}.
@param {Number} priority
@param options | [
"Adds",
"specified",
"rules",
"to",
"this",
"group",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmlparser/filter.js#L277-L289 | train |
|
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/htmlparser/filter.js | function( priority ) {
var rules = this.rules,
len = rules.length,
i = len - 1;
// Search from the end, because usually rules will be added with default priority, so
// we will be able to stop loop quickly.
while ( i >= 0 && priority < rules[ i ].priority )
i--;
return i + 1;
} | javascript | function( priority ) {
var rules = this.rules,
len = rules.length,
i = len - 1;
// Search from the end, because usually rules will be added with default priority, so
// we will be able to stop loop quickly.
while ( i >= 0 && priority < rules[ i ].priority )
i--;
return i + 1;
} | [
"function",
"(",
"priority",
")",
"{",
"var",
"rules",
"=",
"this",
".",
"rules",
",",
"len",
"=",
"rules",
".",
"length",
",",
"i",
"=",
"len",
"-",
"1",
";",
"while",
"(",
"i",
">=",
"0",
"&&",
"priority",
"<",
"rules",
"[",
"i",
"]",
".",
"priority",
")",
"i",
"--",
";",
"return",
"i",
"+",
"1",
";",
"}"
]
| Finds an index at which rule with given priority should be inserted.
@param {Number} priority
@returns {Number} Index. | [
"Finds",
"an",
"index",
"at",
"which",
"rule",
"with",
"given",
"priority",
"should",
"be",
"inserted",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmlparser/filter.js#L297-L308 | train |
|
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/htmlparser/filter.js | function( context, currentValue ) {
var isNode = currentValue instanceof CKEDITOR.htmlParser.node || currentValue instanceof CKEDITOR.htmlParser.fragment,
// Splice '1' to remove context, which we don't want to pass to filter rules.
args = Array.prototype.slice.call( arguments, 1 ),
rules = this.rules,
len = rules.length,
orgType, orgName, ret, i, rule;
for ( i = 0; i < len; i++ ) {
// Backup the node info before filtering.
if ( isNode ) {
orgType = currentValue.type;
orgName = currentValue.name;
}
rule = rules[ i ];
if ( isRuleApplicable( context, rule ) ) {
ret = rule.value.apply( null, args );
if ( ret === false )
return ret;
// We're filtering node (element/fragment).
// No further filtering if it's not anymore fitable for the subsequent filters.
if ( isNode && ret && ( ret.name != orgName || ret.type != orgType ) )
return ret;
// Update currentValue and corresponding argument in args array.
// Updated values will be used in next for-loop step.
if ( ret != null )
args[ 0 ] = currentValue = ret;
// ret == undefined will continue loop as nothing has happened.
}
}
return currentValue;
} | javascript | function( context, currentValue ) {
var isNode = currentValue instanceof CKEDITOR.htmlParser.node || currentValue instanceof CKEDITOR.htmlParser.fragment,
// Splice '1' to remove context, which we don't want to pass to filter rules.
args = Array.prototype.slice.call( arguments, 1 ),
rules = this.rules,
len = rules.length,
orgType, orgName, ret, i, rule;
for ( i = 0; i < len; i++ ) {
// Backup the node info before filtering.
if ( isNode ) {
orgType = currentValue.type;
orgName = currentValue.name;
}
rule = rules[ i ];
if ( isRuleApplicable( context, rule ) ) {
ret = rule.value.apply( null, args );
if ( ret === false )
return ret;
// We're filtering node (element/fragment).
// No further filtering if it's not anymore fitable for the subsequent filters.
if ( isNode && ret && ( ret.name != orgName || ret.type != orgType ) )
return ret;
// Update currentValue and corresponding argument in args array.
// Updated values will be used in next for-loop step.
if ( ret != null )
args[ 0 ] = currentValue = ret;
// ret == undefined will continue loop as nothing has happened.
}
}
return currentValue;
} | [
"function",
"(",
"context",
",",
"currentValue",
")",
"{",
"var",
"isNode",
"=",
"currentValue",
"instanceof",
"CKEDITOR",
".",
"htmlParser",
".",
"node",
"||",
"currentValue",
"instanceof",
"CKEDITOR",
".",
"htmlParser",
".",
"fragment",
",",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
",",
"rules",
"=",
"this",
".",
"rules",
",",
"len",
"=",
"rules",
".",
"length",
",",
"orgType",
",",
"orgName",
",",
"ret",
",",
"i",
",",
"rule",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"isNode",
")",
"{",
"orgType",
"=",
"currentValue",
".",
"type",
";",
"orgName",
"=",
"currentValue",
".",
"name",
";",
"}",
"rule",
"=",
"rules",
"[",
"i",
"]",
";",
"if",
"(",
"isRuleApplicable",
"(",
"context",
",",
"rule",
")",
")",
"{",
"ret",
"=",
"rule",
".",
"value",
".",
"apply",
"(",
"null",
",",
"args",
")",
";",
"if",
"(",
"ret",
"===",
"false",
")",
"return",
"ret",
";",
"if",
"(",
"isNode",
"&&",
"ret",
"&&",
"(",
"ret",
".",
"name",
"!=",
"orgName",
"||",
"ret",
".",
"type",
"!=",
"orgType",
")",
")",
"return",
"ret",
";",
"if",
"(",
"ret",
"!=",
"null",
")",
"args",
"[",
"0",
"]",
"=",
"currentValue",
"=",
"ret",
";",
"}",
"}",
"return",
"currentValue",
";",
"}"
]
| Executes this rules group on given value. Applicable only if function based rules were added.
All arguments passed to this function will be forwarded to rules' functions.
@param {CKEDITOR.htmlParser.node/CKEDITOR.htmlParser.fragment/String} currentValue The value to be filtered.
@returns {CKEDITOR.htmlParser.node/CKEDITOR.htmlParser.fragment/String} Filtered value. | [
"Executes",
"this",
"rules",
"group",
"on",
"given",
"value",
".",
"Applicable",
"only",
"if",
"function",
"based",
"rules",
"were",
"added",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmlparser/filter.js#L318-L355 | train |
|
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/htmlparser/filter.js | function( context, currentName ) {
var i = 0,
rules = this.rules,
len = rules.length,
rule;
for ( ; currentName && i < len; i++ ) {
rule = rules[ i ];
if ( isRuleApplicable( context, rule ) )
currentName = currentName.replace( rule.value[ 0 ], rule.value[ 1 ] );
}
return currentName;
} | javascript | function( context, currentName ) {
var i = 0,
rules = this.rules,
len = rules.length,
rule;
for ( ; currentName && i < len; i++ ) {
rule = rules[ i ];
if ( isRuleApplicable( context, rule ) )
currentName = currentName.replace( rule.value[ 0 ], rule.value[ 1 ] );
}
return currentName;
} | [
"function",
"(",
"context",
",",
"currentName",
")",
"{",
"var",
"i",
"=",
"0",
",",
"rules",
"=",
"this",
".",
"rules",
",",
"len",
"=",
"rules",
".",
"length",
",",
"rule",
";",
"for",
"(",
";",
"currentName",
"&&",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"rule",
"=",
"rules",
"[",
"i",
"]",
";",
"if",
"(",
"isRuleApplicable",
"(",
"context",
",",
"rule",
")",
")",
"currentName",
"=",
"currentName",
".",
"replace",
"(",
"rule",
".",
"value",
"[",
"0",
"]",
",",
"rule",
".",
"value",
"[",
"1",
"]",
")",
";",
"}",
"return",
"currentName",
";",
"}"
]
| Executes this rules group on name. Applicable only if filter rules for names were added.
@param {String} currentName The name to be filtered.
@returns {String} Filtered name. | [
"Executes",
"this",
"rules",
"group",
"on",
"name",
".",
"Applicable",
"only",
"if",
"filter",
"rules",
"for",
"names",
"were",
"added",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmlparser/filter.js#L363-L376 | train |
|
jurca/idb-entity | es2015/utils.js | getField | function getField(object, fieldPath) {
let currentObject = object
for (let fieldName of fieldPath.split(".")) {
if (!currentObject.hasOwnProperty(fieldName)) {
return undefined
}
currentObject = currentObject[fieldName]
}
return currentObject
} | javascript | function getField(object, fieldPath) {
let currentObject = object
for (let fieldName of fieldPath.split(".")) {
if (!currentObject.hasOwnProperty(fieldName)) {
return undefined
}
currentObject = currentObject[fieldName]
}
return currentObject
} | [
"function",
"getField",
"(",
"object",
",",
"fieldPath",
")",
"{",
"let",
"currentObject",
"=",
"object",
"for",
"(",
"let",
"fieldName",
"of",
"fieldPath",
".",
"split",
"(",
"\".\"",
")",
")",
"{",
"if",
"(",
"!",
"currentObject",
".",
"hasOwnProperty",
"(",
"fieldName",
")",
")",
"{",
"return",
"undefined",
"}",
"currentObject",
"=",
"currentObject",
"[",
"fieldName",
"]",
"}",
"return",
"currentObject",
"}"
]
| Returns the value of the field at the specified field path of the provided
object.
@param {Object} object The object from which the field path value should be
extracted.
@param {string} fieldPath The path to the field from which the value should
be returned. The field path must be a sequence of valid ECMAScript
identifiers separated by dots.
@return {*} The value of the field at the specified field path. | [
"Returns",
"the",
"value",
"of",
"the",
"field",
"at",
"the",
"specified",
"field",
"path",
"of",
"the",
"provided",
"object",
"."
]
| 361ef8482872d9fc9a0d83b86970d49d391dc276 | https://github.com/jurca/idb-entity/blob/361ef8482872d9fc9a0d83b86970d49d391dc276/es2015/utils.js#L164-L176 | train |
jurca/idb-entity | es2015/utils.js | setField | function setField(object, fieldPath, value) {
let currentObject = object
let fieldNames = fieldPath.split(".")
for (let fieldName of fieldNames.slice(0, -1)) {
if (!currentObject.hasOwnProperty(fieldName)) {
currentObject[fieldName] = {}
}
currentObject = currentObject[fieldName]
}
currentObject[fieldNames.pop()] = value
} | javascript | function setField(object, fieldPath, value) {
let currentObject = object
let fieldNames = fieldPath.split(".")
for (let fieldName of fieldNames.slice(0, -1)) {
if (!currentObject.hasOwnProperty(fieldName)) {
currentObject[fieldName] = {}
}
currentObject = currentObject[fieldName]
}
currentObject[fieldNames.pop()] = value
} | [
"function",
"setField",
"(",
"object",
",",
"fieldPath",
",",
"value",
")",
"{",
"let",
"currentObject",
"=",
"object",
"let",
"fieldNames",
"=",
"fieldPath",
".",
"split",
"(",
"\".\"",
")",
"for",
"(",
"let",
"fieldName",
"of",
"fieldNames",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
")",
"{",
"if",
"(",
"!",
"currentObject",
".",
"hasOwnProperty",
"(",
"fieldName",
")",
")",
"{",
"currentObject",
"[",
"fieldName",
"]",
"=",
"{",
"}",
"}",
"currentObject",
"=",
"currentObject",
"[",
"fieldName",
"]",
"}",
"currentObject",
"[",
"fieldNames",
".",
"pop",
"(",
")",
"]",
"=",
"value",
"}"
]
| Sets the field at the specified field path to the provided value in the
provided object.
The function creates the field path out of empty plain objects if it does
not already exist.
@param {Object} object The object in which the specified field path should
be set to the provided value.
@param {string} fieldPath The field path at which the value should be set.
The field path must be a sequence of valid ECMAScript identifiers
separated by dots.
@param {*} value The value to set. | [
"Sets",
"the",
"field",
"at",
"the",
"specified",
"field",
"path",
"to",
"the",
"provided",
"value",
"in",
"the",
"provided",
"object",
"."
]
| 361ef8482872d9fc9a0d83b86970d49d391dc276 | https://github.com/jurca/idb-entity/blob/361ef8482872d9fc9a0d83b86970d49d391dc276/es2015/utils.js#L192-L205 | train |
skerit/alchemy-styleboost | public/ckeditor/4.4dev/plugins/removeformat/plugin.js | function( editor, element ) {
// If editor#addRemoveFotmatFilter hasn't been executed yet value is not initialized.
var filters = editor._.removeFormatFilters || [];
for ( var i = 0; i < filters.length; i++ ) {
if ( filters[ i ]( element ) === false )
return false;
}
return true;
} | javascript | function( editor, element ) {
// If editor#addRemoveFotmatFilter hasn't been executed yet value is not initialized.
var filters = editor._.removeFormatFilters || [];
for ( var i = 0; i < filters.length; i++ ) {
if ( filters[ i ]( element ) === false )
return false;
}
return true;
} | [
"function",
"(",
"editor",
",",
"element",
")",
"{",
"var",
"filters",
"=",
"editor",
".",
"_",
".",
"removeFormatFilters",
"||",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"filters",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"filters",
"[",
"i",
"]",
"(",
"element",
")",
"===",
"false",
")",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
]
| Perform the remove format filters on the passed element. @param {CKEDITOR.editor} editor @param {CKEDITOR.dom.element} element | [
"Perform",
"the",
"remove",
"format",
"filters",
"on",
"the",
"passed",
"element",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/removeformat/plugin.js#L131-L139 | train |
|
sourdough-css/preprocessor | bin/logger.js | format | function format (type, msg, typeColor, msgColor) {
type = type || '';
msg = msg || '';
typeColor = typeColor || 'blue';
msgColor = msgColor || 'grey';
type = pad(type, 12);
return type[typeColor] + ' · ' + msg[msgColor];
} | javascript | function format (type, msg, typeColor, msgColor) {
type = type || '';
msg = msg || '';
typeColor = typeColor || 'blue';
msgColor = msgColor || 'grey';
type = pad(type, 12);
return type[typeColor] + ' · ' + msg[msgColor];
} | [
"function",
"format",
"(",
"type",
",",
"msg",
",",
"typeColor",
",",
"msgColor",
")",
"{",
"type",
"=",
"type",
"||",
"''",
";",
"msg",
"=",
"msg",
"||",
"''",
";",
"typeColor",
"=",
"typeColor",
"||",
"'blue'",
";",
"msgColor",
"=",
"msgColor",
"||",
"'grey'",
";",
"type",
"=",
"pad",
"(",
"type",
",",
"12",
")",
";",
"return",
"type",
"[",
"typeColor",
"]",
"+",
"' · ' ",
" ",
" ",
"sg[",
"m",
"sgColor]",
";",
"}"
]
| Format a `type` and `msg` with `typeColor` and `msgColor`.
@param {String} type
@param {String} msg
@param {String} typeColor (optional)
@param {String} msgColor (optional) | [
"Format",
"a",
"type",
"and",
"msg",
"with",
"typeColor",
"and",
"msgColor",
"."
]
| d065000ac3c7c31524058793409de2f78a092d04 | https://github.com/sourdough-css/preprocessor/blob/d065000ac3c7c31524058793409de2f78a092d04/bin/logger.js#L97-L104 | train |
meisterplayer/js-dev | gulp/versioning.js | createBumpVersion | function createBumpVersion(inPath, type) {
if (!inPath) {
throw new Error('Input path(s) argument is required');
}
return function bumpVersion() {
return gulp.src(inPath)
.pipe(bump({ type }))
.pipe(gulp.dest(file => file.base));
};
} | javascript | function createBumpVersion(inPath, type) {
if (!inPath) {
throw new Error('Input path(s) argument is required');
}
return function bumpVersion() {
return gulp.src(inPath)
.pipe(bump({ type }))
.pipe(gulp.dest(file => file.base));
};
} | [
"function",
"createBumpVersion",
"(",
"inPath",
",",
"type",
")",
"{",
"if",
"(",
"!",
"inPath",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Input path(s) argument is required'",
")",
";",
"}",
"return",
"function",
"bumpVersion",
"(",
")",
"{",
"return",
"gulp",
".",
"src",
"(",
"inPath",
")",
".",
"pipe",
"(",
"bump",
"(",
"{",
"type",
"}",
")",
")",
".",
"pipe",
"(",
"gulp",
".",
"dest",
"(",
"file",
"=>",
"file",
".",
"base",
")",
")",
";",
"}",
";",
"}"
]
| Higher order function to create gulp function that bumps the version in the package.json.
@param {string} inPath Path to the project's package.json
@return {function} Function that can be used as a gulp task | [
"Higher",
"order",
"function",
"to",
"create",
"gulp",
"function",
"that",
"bumps",
"the",
"version",
"in",
"the",
"package",
".",
"json",
"."
]
| c2646678c49dcdaa120ba3f24824da52b0c63e31 | https://github.com/meisterplayer/js-dev/blob/c2646678c49dcdaa120ba3f24824da52b0c63e31/gulp/versioning.js#L11-L21 | train |
meisterplayer/js-dev | gulp/versioning.js | createReplaceVersion | function createReplaceVersion(inPath, version, opts = {}) {
if (!inPath) {
throw new Error('Input path(s) argument is required');
}
if (!version) {
throw new Error('Version argument is required');
}
const dropV = !!opts.dropV;
const versionRegex = dropV ? /[0-9]+\.[0-9]+\.[0-9]+\b/g : /v[0-9]+\.[0-9]+\.[0-9]+\b/g;
const versionString = dropV ? version : `v${version}`;
return function updateVersions() {
return gulp.src(inPath)
.pipe(replace(versionRegex, versionString))
.pipe(gulp.dest(file => file.base));
};
} | javascript | function createReplaceVersion(inPath, version, opts = {}) {
if (!inPath) {
throw new Error('Input path(s) argument is required');
}
if (!version) {
throw new Error('Version argument is required');
}
const dropV = !!opts.dropV;
const versionRegex = dropV ? /[0-9]+\.[0-9]+\.[0-9]+\b/g : /v[0-9]+\.[0-9]+\.[0-9]+\b/g;
const versionString = dropV ? version : `v${version}`;
return function updateVersions() {
return gulp.src(inPath)
.pipe(replace(versionRegex, versionString))
.pipe(gulp.dest(file => file.base));
};
} | [
"function",
"createReplaceVersion",
"(",
"inPath",
",",
"version",
",",
"opts",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"!",
"inPath",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Input path(s) argument is required'",
")",
";",
"}",
"if",
"(",
"!",
"version",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Version argument is required'",
")",
";",
"}",
"const",
"dropV",
"=",
"!",
"!",
"opts",
".",
"dropV",
";",
"const",
"versionRegex",
"=",
"dropV",
"?",
"/",
"[0-9]+\\.[0-9]+\\.[0-9]+\\b",
"/",
"g",
":",
"/",
"v[0-9]+\\.[0-9]+\\.[0-9]+\\b",
"/",
"g",
";",
"const",
"versionString",
"=",
"dropV",
"?",
"version",
":",
"`",
"${",
"version",
"}",
"`",
";",
"return",
"function",
"updateVersions",
"(",
")",
"{",
"return",
"gulp",
".",
"src",
"(",
"inPath",
")",
".",
"pipe",
"(",
"replace",
"(",
"versionRegex",
",",
"versionString",
")",
")",
".",
"pipe",
"(",
"gulp",
".",
"dest",
"(",
"file",
"=>",
"file",
".",
"base",
")",
")",
";",
"}",
";",
"}"
]
| Higher order function to create gulp function that replaces instances of the version number
with the new version.
@param {string|string[]} inPath The globs to the files that need to be searched
@param {string} version The version to update to without a leading 'v'
@param {Object} [opts={}] Extra options for replace
@param {string} [opts.dropV=false] Optional flag to search/replace 'X.Y.Z' instead of 'vX.Y.Z'
@return {function} Function that can be used as a gulp task | [
"Higher",
"order",
"function",
"to",
"create",
"gulp",
"function",
"that",
"replaces",
"instances",
"of",
"the",
"version",
"number",
"with",
"the",
"new",
"version",
"."
]
| c2646678c49dcdaa120ba3f24824da52b0c63e31 | https://github.com/meisterplayer/js-dev/blob/c2646678c49dcdaa120ba3f24824da52b0c63e31/gulp/versioning.js#L32-L50 | train |
meisterplayer/js-dev | gulp/versioning.js | extractPackageVersion | function extractPackageVersion(inPath) {
if (!inPath) {
throw new Error('Input path argument is required');
}
// Require here so we have the update version.
const pkg = fs.readFileSync(inPath, 'utf-8');
// index 0 is line that matched, index 1 is first control group (version number in this case)
const matches = /"version": "([0-9]+\.[0-9]+\.[0-9]+)"/.exec(pkg);
const version = matches[1];
return version;
} | javascript | function extractPackageVersion(inPath) {
if (!inPath) {
throw new Error('Input path argument is required');
}
// Require here so we have the update version.
const pkg = fs.readFileSync(inPath, 'utf-8');
// index 0 is line that matched, index 1 is first control group (version number in this case)
const matches = /"version": "([0-9]+\.[0-9]+\.[0-9]+)"/.exec(pkg);
const version = matches[1];
return version;
} | [
"function",
"extractPackageVersion",
"(",
"inPath",
")",
"{",
"if",
"(",
"!",
"inPath",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Input path argument is required'",
")",
";",
"}",
"const",
"pkg",
"=",
"fs",
".",
"readFileSync",
"(",
"inPath",
",",
"'utf-8'",
")",
";",
"const",
"matches",
"=",
"/",
"\"version\": \"([0-9]+\\.[0-9]+\\.[0-9]+)\"",
"/",
".",
"exec",
"(",
"pkg",
")",
";",
"const",
"version",
"=",
"matches",
"[",
"1",
"]",
";",
"return",
"version",
";",
"}"
]
| Sync function that takes a package.json path and extracts the version from it.
@param {string} inPath Path to the project's package.json
@return {string} The extracted version number in the form 'X.Y.Z' | [
"Sync",
"function",
"that",
"takes",
"a",
"package",
".",
"json",
"path",
"and",
"extracts",
"the",
"version",
"from",
"it",
"."
]
| c2646678c49dcdaa120ba3f24824da52b0c63e31 | https://github.com/meisterplayer/js-dev/blob/c2646678c49dcdaa120ba3f24824da52b0c63e31/gulp/versioning.js#L57-L70 | train |
skerit/alchemy-styleboost | public/ckeditor/4.4dev/plugins/dialogadvtab/plugin.js | function( tabConfig ) {
if ( !tabConfig )
tabConfig = defaultTabConfig;
var allowedAttrs = [];
if ( tabConfig.id )
allowedAttrs.push( 'id' );
if ( tabConfig.dir )
allowedAttrs.push( 'dir' );
var allowed = '';
if ( allowedAttrs.length )
allowed += '[' + allowedAttrs.join( ',' ) + ']';
if ( tabConfig.classes )
allowed += '(*)';
if ( tabConfig.styles )
allowed += '{*}';
return allowed;
} | javascript | function( tabConfig ) {
if ( !tabConfig )
tabConfig = defaultTabConfig;
var allowedAttrs = [];
if ( tabConfig.id )
allowedAttrs.push( 'id' );
if ( tabConfig.dir )
allowedAttrs.push( 'dir' );
var allowed = '';
if ( allowedAttrs.length )
allowed += '[' + allowedAttrs.join( ',' ) + ']';
if ( tabConfig.classes )
allowed += '(*)';
if ( tabConfig.styles )
allowed += '{*}';
return allowed;
} | [
"function",
"(",
"tabConfig",
")",
"{",
"if",
"(",
"!",
"tabConfig",
")",
"tabConfig",
"=",
"defaultTabConfig",
";",
"var",
"allowedAttrs",
"=",
"[",
"]",
";",
"if",
"(",
"tabConfig",
".",
"id",
")",
"allowedAttrs",
".",
"push",
"(",
"'id'",
")",
";",
"if",
"(",
"tabConfig",
".",
"dir",
")",
"allowedAttrs",
".",
"push",
"(",
"'dir'",
")",
";",
"var",
"allowed",
"=",
"''",
";",
"if",
"(",
"allowedAttrs",
".",
"length",
")",
"allowed",
"+=",
"'['",
"+",
"allowedAttrs",
".",
"join",
"(",
"','",
")",
"+",
"']'",
";",
"if",
"(",
"tabConfig",
".",
"classes",
")",
"allowed",
"+=",
"'(*)'",
";",
"if",
"(",
"tabConfig",
".",
"styles",
")",
"allowed",
"+=",
"'{*}'",
";",
"return",
"allowed",
";",
"}"
]
| Returns allowed content rule for the content created by this plugin. | [
"Returns",
"allowed",
"content",
"rule",
"for",
"the",
"content",
"created",
"by",
"this",
"plugin",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialogadvtab/plugin.js#L46-L67 | train |
|
fs-utils/download-cache | index.js | download | function download(url) {
if (!validator.isURL(url)) return Promise.reject(error(400, 'Invalid URL: ' + url));
// download in progress
if (progress[sha]) return progress[sha];
var sha = hash(url);
return progress[sha] = cache.access(sha).then(function (filename) {
if (filename) return filename;
return request(url)
.redirects(3)
.agent(false)
.then(function (response) {
assert(response.status < 400, response.status, 'Got status code ' + response.status + ' from ' + url);
assert(response.status === 200, 'Got status code ' + response.status + ' from ' + url);
debug('Downloading %s -> %s', url, sha);
return cache.copy(sha, response.response);
});
}).then(function (filename) {
delete progress[sha];
return filename;
}, /* istanbul ignore next */ function (err) {
delete progress[sha];
throw err;
});
} | javascript | function download(url) {
if (!validator.isURL(url)) return Promise.reject(error(400, 'Invalid URL: ' + url));
// download in progress
if (progress[sha]) return progress[sha];
var sha = hash(url);
return progress[sha] = cache.access(sha).then(function (filename) {
if (filename) return filename;
return request(url)
.redirects(3)
.agent(false)
.then(function (response) {
assert(response.status < 400, response.status, 'Got status code ' + response.status + ' from ' + url);
assert(response.status === 200, 'Got status code ' + response.status + ' from ' + url);
debug('Downloading %s -> %s', url, sha);
return cache.copy(sha, response.response);
});
}).then(function (filename) {
delete progress[sha];
return filename;
}, /* istanbul ignore next */ function (err) {
delete progress[sha];
throw err;
});
} | [
"function",
"download",
"(",
"url",
")",
"{",
"if",
"(",
"!",
"validator",
".",
"isURL",
"(",
"url",
")",
")",
"return",
"Promise",
".",
"reject",
"(",
"error",
"(",
"400",
",",
"'Invalid URL: '",
"+",
"url",
")",
")",
";",
"if",
"(",
"progress",
"[",
"sha",
"]",
")",
"return",
"progress",
"[",
"sha",
"]",
";",
"var",
"sha",
"=",
"hash",
"(",
"url",
")",
";",
"return",
"progress",
"[",
"sha",
"]",
"=",
"cache",
".",
"access",
"(",
"sha",
")",
".",
"then",
"(",
"function",
"(",
"filename",
")",
"{",
"if",
"(",
"filename",
")",
"return",
"filename",
";",
"return",
"request",
"(",
"url",
")",
".",
"redirects",
"(",
"3",
")",
".",
"agent",
"(",
"false",
")",
".",
"then",
"(",
"function",
"(",
"response",
")",
"{",
"assert",
"(",
"response",
".",
"status",
"<",
"400",
",",
"response",
".",
"status",
",",
"'Got status code '",
"+",
"response",
".",
"status",
"+",
"' from '",
"+",
"url",
")",
";",
"assert",
"(",
"response",
".",
"status",
"===",
"200",
",",
"'Got status code '",
"+",
"response",
".",
"status",
"+",
"' from '",
"+",
"url",
")",
";",
"debug",
"(",
"'Downloading %s -> %s'",
",",
"url",
",",
"sha",
")",
";",
"return",
"cache",
".",
"copy",
"(",
"sha",
",",
"response",
".",
"response",
")",
";",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"filename",
")",
"{",
"delete",
"progress",
"[",
"sha",
"]",
";",
"return",
"filename",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"delete",
"progress",
"[",
"sha",
"]",
";",
"throw",
"err",
";",
"}",
")",
";",
"}"
]
| If the locally exists locally, use that.
Otherwise, download it and return the filename.
We cache by the sha of the URL. | [
"If",
"the",
"locally",
"exists",
"locally",
"use",
"that",
".",
"Otherwise",
"download",
"it",
"and",
"return",
"the",
"filename",
".",
"We",
"cache",
"by",
"the",
"sha",
"of",
"the",
"URL",
"."
]
| 67229900608e211082d36d5419fffc6270669dd6 | https://github.com/fs-utils/download-cache/blob/67229900608e211082d36d5419fffc6270669dd6/index.js#L30-L56 | train |
airbrite/muni | adapter.js | function(body) {
if (_.isString(body)) {
return body;
} else if (_.isObject(body) && _.isString(body.error)) {
return body.error;
} else if (_.isObject(body) && _.isString(body.msg)) {
return body.msg;
} else if (_.isObject(body) && _.isObject(body.error)) {
return this._extractError(body.error);
} else if (_.isObject(body) && _.isString(body.message)) {
return body.message;
} else if (_.isObject(body) &&
body.meta &&
_.isString(body.meta.error_message)) {
return body.meta.error_message;
} else {
return 'Unknown Request Error';
}
} | javascript | function(body) {
if (_.isString(body)) {
return body;
} else if (_.isObject(body) && _.isString(body.error)) {
return body.error;
} else if (_.isObject(body) && _.isString(body.msg)) {
return body.msg;
} else if (_.isObject(body) && _.isObject(body.error)) {
return this._extractError(body.error);
} else if (_.isObject(body) && _.isString(body.message)) {
return body.message;
} else if (_.isObject(body) &&
body.meta &&
_.isString(body.meta.error_message)) {
return body.meta.error_message;
} else {
return 'Unknown Request Error';
}
} | [
"function",
"(",
"body",
")",
"{",
"if",
"(",
"_",
".",
"isString",
"(",
"body",
")",
")",
"{",
"return",
"body",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isObject",
"(",
"body",
")",
"&&",
"_",
".",
"isString",
"(",
"body",
".",
"error",
")",
")",
"{",
"return",
"body",
".",
"error",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isObject",
"(",
"body",
")",
"&&",
"_",
".",
"isString",
"(",
"body",
".",
"msg",
")",
")",
"{",
"return",
"body",
".",
"msg",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isObject",
"(",
"body",
")",
"&&",
"_",
".",
"isObject",
"(",
"body",
".",
"error",
")",
")",
"{",
"return",
"this",
".",
"_extractError",
"(",
"body",
".",
"error",
")",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isObject",
"(",
"body",
")",
"&&",
"_",
".",
"isString",
"(",
"body",
".",
"message",
")",
")",
"{",
"return",
"body",
".",
"message",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isObject",
"(",
"body",
")",
"&&",
"body",
".",
"meta",
"&&",
"_",
".",
"isString",
"(",
"body",
".",
"meta",
".",
"error_message",
")",
")",
"{",
"return",
"body",
".",
"meta",
".",
"error_message",
";",
"}",
"else",
"{",
"return",
"'Unknown Request Error'",
";",
"}",
"}"
]
| If there's an error, try your damndest to find it.
APIs hide errors in all sorts of places these days
@param {String|Object} body
@return {String} | [
"If",
"there",
"s",
"an",
"error",
"try",
"your",
"damndest",
"to",
"find",
"it",
".",
"APIs",
"hide",
"errors",
"in",
"all",
"sorts",
"of",
"places",
"these",
"days"
]
| ea8b26aa94836514374907c325a0d79f28838e2e | https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/adapter.js#L23-L41 | train |
|
airbrite/muni | adapter.js | function(options) {
options = options || {};
// Set default path
if (!options.url && !options.path) {
options.path = '';
}
// Prepare the request
var requestOptions = {
method: options.method || 'GET',
url: options.url || this.urlRoot + options.path,
qs: options.qs || {},
headers: options.headers || {},
};
// Add `form`, `body`, or `json` as Request Payload (only one per request)
//
// If `json` is a Boolean,
// Request will set` Content-Type`
// and call `JSON.stringify()` on `body`
if (options.body) {
requestOptions.body = options.body;
requestOptions.json = _.isBoolean(options.json) ? options.json : true;
} else if (options.form) {
requestOptions.form = options.form;
requestOptions.headers['Content-Type'] =
'application/x-www-form-urlencoded; charset=utf-8';
} else if (_.isBoolean(options.json) || _.isObject(options.json)) {
requestOptions.json = options.json;
}
// Basic HTTP Auth
if (options.auth) {
requestOptions.auth = options.auth;
}
// Access Token
var accessToken = options.access_token || this.get('access_token');
if (accessToken) {
_.defaults(requestOptions.headers, {
Authorization: ['Bearer', accessToken].join(' ')
});
}
// OAuth Token
var oauthToken = options.oauth_token || this.get('oauth_token');
if (oauthToken) {
_.defaults(requestOptions.headers, {
Authorization: ['OAuth', oauthToken].join(' ')
});
}
// Authorization Token (No Scheme)
var authorizationToken = options.authorization_token || this.get('authorization_token');
if (authorizationToken) {
_.defaults(requestOptions.headers, {
Authorization: authorizationToken
});
}
return requestOptions;
} | javascript | function(options) {
options = options || {};
// Set default path
if (!options.url && !options.path) {
options.path = '';
}
// Prepare the request
var requestOptions = {
method: options.method || 'GET',
url: options.url || this.urlRoot + options.path,
qs: options.qs || {},
headers: options.headers || {},
};
// Add `form`, `body`, or `json` as Request Payload (only one per request)
//
// If `json` is a Boolean,
// Request will set` Content-Type`
// and call `JSON.stringify()` on `body`
if (options.body) {
requestOptions.body = options.body;
requestOptions.json = _.isBoolean(options.json) ? options.json : true;
} else if (options.form) {
requestOptions.form = options.form;
requestOptions.headers['Content-Type'] =
'application/x-www-form-urlencoded; charset=utf-8';
} else if (_.isBoolean(options.json) || _.isObject(options.json)) {
requestOptions.json = options.json;
}
// Basic HTTP Auth
if (options.auth) {
requestOptions.auth = options.auth;
}
// Access Token
var accessToken = options.access_token || this.get('access_token');
if (accessToken) {
_.defaults(requestOptions.headers, {
Authorization: ['Bearer', accessToken].join(' ')
});
}
// OAuth Token
var oauthToken = options.oauth_token || this.get('oauth_token');
if (oauthToken) {
_.defaults(requestOptions.headers, {
Authorization: ['OAuth', oauthToken].join(' ')
});
}
// Authorization Token (No Scheme)
var authorizationToken = options.authorization_token || this.get('authorization_token');
if (authorizationToken) {
_.defaults(requestOptions.headers, {
Authorization: authorizationToken
});
}
return requestOptions;
} | [
"function",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"if",
"(",
"!",
"options",
".",
"url",
"&&",
"!",
"options",
".",
"path",
")",
"{",
"options",
".",
"path",
"=",
"''",
";",
"}",
"var",
"requestOptions",
"=",
"{",
"method",
":",
"options",
".",
"method",
"||",
"'GET'",
",",
"url",
":",
"options",
".",
"url",
"||",
"this",
".",
"urlRoot",
"+",
"options",
".",
"path",
",",
"qs",
":",
"options",
".",
"qs",
"||",
"{",
"}",
",",
"headers",
":",
"options",
".",
"headers",
"||",
"{",
"}",
",",
"}",
";",
"if",
"(",
"options",
".",
"body",
")",
"{",
"requestOptions",
".",
"body",
"=",
"options",
".",
"body",
";",
"requestOptions",
".",
"json",
"=",
"_",
".",
"isBoolean",
"(",
"options",
".",
"json",
")",
"?",
"options",
".",
"json",
":",
"true",
";",
"}",
"else",
"if",
"(",
"options",
".",
"form",
")",
"{",
"requestOptions",
".",
"form",
"=",
"options",
".",
"form",
";",
"requestOptions",
".",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/x-www-form-urlencoded; charset=utf-8'",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isBoolean",
"(",
"options",
".",
"json",
")",
"||",
"_",
".",
"isObject",
"(",
"options",
".",
"json",
")",
")",
"{",
"requestOptions",
".",
"json",
"=",
"options",
".",
"json",
";",
"}",
"if",
"(",
"options",
".",
"auth",
")",
"{",
"requestOptions",
".",
"auth",
"=",
"options",
".",
"auth",
";",
"}",
"var",
"accessToken",
"=",
"options",
".",
"access_token",
"||",
"this",
".",
"get",
"(",
"'access_token'",
")",
";",
"if",
"(",
"accessToken",
")",
"{",
"_",
".",
"defaults",
"(",
"requestOptions",
".",
"headers",
",",
"{",
"Authorization",
":",
"[",
"'Bearer'",
",",
"accessToken",
"]",
".",
"join",
"(",
"' '",
")",
"}",
")",
";",
"}",
"var",
"oauthToken",
"=",
"options",
".",
"oauth_token",
"||",
"this",
".",
"get",
"(",
"'oauth_token'",
")",
";",
"if",
"(",
"oauthToken",
")",
"{",
"_",
".",
"defaults",
"(",
"requestOptions",
".",
"headers",
",",
"{",
"Authorization",
":",
"[",
"'OAuth'",
",",
"oauthToken",
"]",
".",
"join",
"(",
"' '",
")",
"}",
")",
";",
"}",
"var",
"authorizationToken",
"=",
"options",
".",
"authorization_token",
"||",
"this",
".",
"get",
"(",
"'authorization_token'",
")",
";",
"if",
"(",
"authorizationToken",
")",
"{",
"_",
".",
"defaults",
"(",
"requestOptions",
".",
"headers",
",",
"{",
"Authorization",
":",
"authorizationToken",
"}",
")",
";",
"}",
"return",
"requestOptions",
";",
"}"
]
| Build and configure the request options
@param {Object} options
@param {String} options.url
@param {String} [options.path=]
@param {String} [options.method=GET]
@param {String} [options.qs={}]
@param {String} [options.headers={}]
@param {String} options.json
@param {String} options.form
@param {String} options.body
@param {String} options.access_token
@param {String} options.oauth_token
@param {String} options.authorization_token
@param {String} options.auth
@return {Object} | [
"Build",
"and",
"configure",
"the",
"request",
"options"
]
| ea8b26aa94836514374907c325a0d79f28838e2e | https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/adapter.js#L62-L123 | train |
|
airbrite/muni | adapter.js | function(options, callback) {
// Create a promise to defer to later
var deferred = Bluebird.defer();
// Fire the request
request(this._buildRequestOptions(options), function(err, response, body) {
// Handle Errors
if (err) {
// Usually a connection error (server unresponsive)
err = new MuniError(err.message || 'Internal Server Error', err.code || 500);
} else if (response.statusCode >= 400) {
// Usually an intentional error from the server
err = new MuniError(this._extractError(body), response.statusCode);
}
if (err) {
debug.warn('Adapter Request Error with Code: %d', err.code);
callback && callback(err);
return deferred.reject(err);
}
// Handle Success
debug.info('Adapter Request Sent with code: %d', response.statusCode);
callback && callback(null, body);
return deferred.resolve(body);
}.bind(this));
return deferred.promise;
} | javascript | function(options, callback) {
// Create a promise to defer to later
var deferred = Bluebird.defer();
// Fire the request
request(this._buildRequestOptions(options), function(err, response, body) {
// Handle Errors
if (err) {
// Usually a connection error (server unresponsive)
err = new MuniError(err.message || 'Internal Server Error', err.code || 500);
} else if (response.statusCode >= 400) {
// Usually an intentional error from the server
err = new MuniError(this._extractError(body), response.statusCode);
}
if (err) {
debug.warn('Adapter Request Error with Code: %d', err.code);
callback && callback(err);
return deferred.reject(err);
}
// Handle Success
debug.info('Adapter Request Sent with code: %d', response.statusCode);
callback && callback(null, body);
return deferred.resolve(body);
}.bind(this));
return deferred.promise;
} | [
"function",
"(",
"options",
",",
"callback",
")",
"{",
"var",
"deferred",
"=",
"Bluebird",
".",
"defer",
"(",
")",
";",
"request",
"(",
"this",
".",
"_buildRequestOptions",
"(",
"options",
")",
",",
"function",
"(",
"err",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"{",
"err",
"=",
"new",
"MuniError",
"(",
"err",
".",
"message",
"||",
"'Internal Server Error'",
",",
"err",
".",
"code",
"||",
"500",
")",
";",
"}",
"else",
"if",
"(",
"response",
".",
"statusCode",
">=",
"400",
")",
"{",
"err",
"=",
"new",
"MuniError",
"(",
"this",
".",
"_extractError",
"(",
"body",
")",
",",
"response",
".",
"statusCode",
")",
";",
"}",
"if",
"(",
"err",
")",
"{",
"debug",
".",
"warn",
"(",
"'Adapter Request Error with Code: %d'",
",",
"err",
".",
"code",
")",
";",
"callback",
"&&",
"callback",
"(",
"err",
")",
";",
"return",
"deferred",
".",
"reject",
"(",
"err",
")",
";",
"}",
"debug",
".",
"info",
"(",
"'Adapter Request Sent with code: %d'",
",",
"response",
".",
"statusCode",
")",
";",
"callback",
"&&",
"callback",
"(",
"null",
",",
"body",
")",
";",
"return",
"deferred",
".",
"resolve",
"(",
"body",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
]
| Send an HTTP Request with provided request options
@param {Object} options
@param {Function} callback
@return {Promise} | [
"Send",
"an",
"HTTP",
"Request",
"with",
"provided",
"request",
"options"
]
| ea8b26aa94836514374907c325a0d79f28838e2e | https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/adapter.js#L133-L160 | train |
|
Industryswarm/isnode-mod-data | lib/mongodb/mongodb-core/lib/sdam/monitoring.js | monitorServer | function monitorServer(server) {
// executes a single check of a server
const checkServer = callback => {
let start = process.hrtime();
// emit a signal indicating we have started the heartbeat
server.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(server.name));
server.command(
'admin.$cmd',
{ ismaster: true },
{
monitoring: true,
socketTimeout: server.s.options.connectionTimeout || 2000
},
function(err, result) {
let duration = calculateDurationInMs(start);
if (err) {
server.emit(
'serverHeartbeatFailed',
new ServerHeartbeatFailedEvent(duration, err, server.name)
);
return callback(err, null);
}
const isMaster = result.result;
server.emit(
'serverHeartbeatSucceded',
new ServerHeartbeatSucceededEvent(duration, isMaster, server.name)
);
return callback(null, isMaster);
}
);
};
const successHandler = isMaster => {
server.s.monitoring = false;
// emit an event indicating that our description has changed
server.emit('descriptionReceived', new ServerDescription(server.description.address, isMaster));
// schedule the next monitoring process
server.s.monitorId = setTimeout(
() => monitorServer(server),
server.s.options.heartbeatFrequencyMS
);
};
// run the actual monitoring loop
server.s.monitoring = true;
checkServer((err, isMaster) => {
if (!err) {
successHandler(isMaster);
return;
}
// According to the SDAM specification's "Network error during server check" section, if
// an ismaster call fails we reset the server's pool. If a server was once connected,
// change its type to `Unknown` only after retrying once.
// TODO: we need to reset the pool here
return checkServer((err, isMaster) => {
if (err) {
server.s.monitoring = false;
// revert to `Unknown` by emitting a default description with no isMaster
server.emit('descriptionReceived', new ServerDescription(server.description.address));
// do not reschedule monitoring in this case
return;
}
successHandler(isMaster);
});
});
} | javascript | function monitorServer(server) {
// executes a single check of a server
const checkServer = callback => {
let start = process.hrtime();
// emit a signal indicating we have started the heartbeat
server.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(server.name));
server.command(
'admin.$cmd',
{ ismaster: true },
{
monitoring: true,
socketTimeout: server.s.options.connectionTimeout || 2000
},
function(err, result) {
let duration = calculateDurationInMs(start);
if (err) {
server.emit(
'serverHeartbeatFailed',
new ServerHeartbeatFailedEvent(duration, err, server.name)
);
return callback(err, null);
}
const isMaster = result.result;
server.emit(
'serverHeartbeatSucceded',
new ServerHeartbeatSucceededEvent(duration, isMaster, server.name)
);
return callback(null, isMaster);
}
);
};
const successHandler = isMaster => {
server.s.monitoring = false;
// emit an event indicating that our description has changed
server.emit('descriptionReceived', new ServerDescription(server.description.address, isMaster));
// schedule the next monitoring process
server.s.monitorId = setTimeout(
() => monitorServer(server),
server.s.options.heartbeatFrequencyMS
);
};
// run the actual monitoring loop
server.s.monitoring = true;
checkServer((err, isMaster) => {
if (!err) {
successHandler(isMaster);
return;
}
// According to the SDAM specification's "Network error during server check" section, if
// an ismaster call fails we reset the server's pool. If a server was once connected,
// change its type to `Unknown` only after retrying once.
// TODO: we need to reset the pool here
return checkServer((err, isMaster) => {
if (err) {
server.s.monitoring = false;
// revert to `Unknown` by emitting a default description with no isMaster
server.emit('descriptionReceived', new ServerDescription(server.description.address));
// do not reschedule monitoring in this case
return;
}
successHandler(isMaster);
});
});
} | [
"function",
"monitorServer",
"(",
"server",
")",
"{",
"const",
"checkServer",
"=",
"callback",
"=>",
"{",
"let",
"start",
"=",
"process",
".",
"hrtime",
"(",
")",
";",
"server",
".",
"emit",
"(",
"'serverHeartbeatStarted'",
",",
"new",
"ServerHeartbeatStartedEvent",
"(",
"server",
".",
"name",
")",
")",
";",
"server",
".",
"command",
"(",
"'admin.$cmd'",
",",
"{",
"ismaster",
":",
"true",
"}",
",",
"{",
"monitoring",
":",
"true",
",",
"socketTimeout",
":",
"server",
".",
"s",
".",
"options",
".",
"connectionTimeout",
"||",
"2000",
"}",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"let",
"duration",
"=",
"calculateDurationInMs",
"(",
"start",
")",
";",
"if",
"(",
"err",
")",
"{",
"server",
".",
"emit",
"(",
"'serverHeartbeatFailed'",
",",
"new",
"ServerHeartbeatFailedEvent",
"(",
"duration",
",",
"err",
",",
"server",
".",
"name",
")",
")",
";",
"return",
"callback",
"(",
"err",
",",
"null",
")",
";",
"}",
"const",
"isMaster",
"=",
"result",
".",
"result",
";",
"server",
".",
"emit",
"(",
"'serverHeartbeatSucceded'",
",",
"new",
"ServerHeartbeatSucceededEvent",
"(",
"duration",
",",
"isMaster",
",",
"server",
".",
"name",
")",
")",
";",
"return",
"callback",
"(",
"null",
",",
"isMaster",
")",
";",
"}",
")",
";",
"}",
";",
"const",
"successHandler",
"=",
"isMaster",
"=>",
"{",
"server",
".",
"s",
".",
"monitoring",
"=",
"false",
";",
"server",
".",
"emit",
"(",
"'descriptionReceived'",
",",
"new",
"ServerDescription",
"(",
"server",
".",
"description",
".",
"address",
",",
"isMaster",
")",
")",
";",
"server",
".",
"s",
".",
"monitorId",
"=",
"setTimeout",
"(",
"(",
")",
"=>",
"monitorServer",
"(",
"server",
")",
",",
"server",
".",
"s",
".",
"options",
".",
"heartbeatFrequencyMS",
")",
";",
"}",
";",
"server",
".",
"s",
".",
"monitoring",
"=",
"true",
";",
"checkServer",
"(",
"(",
"err",
",",
"isMaster",
")",
"=>",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"successHandler",
"(",
"isMaster",
")",
";",
"return",
";",
"}",
"return",
"checkServer",
"(",
"(",
"err",
",",
"isMaster",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"server",
".",
"s",
".",
"monitoring",
"=",
"false",
";",
"server",
".",
"emit",
"(",
"'descriptionReceived'",
",",
"new",
"ServerDescription",
"(",
"server",
".",
"description",
".",
"address",
")",
")",
";",
"return",
";",
"}",
"successHandler",
"(",
"isMaster",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Performs a server check as described by the SDAM spec.
NOTE: This method automatically reschedules itself, so that there is always an active
monitoring process
@param {Server} server The server to monitor | [
"Performs",
"a",
"server",
"check",
"as",
"described",
"by",
"the",
"SDAM",
"spec",
"."
]
| 5adc639b88a0d72cbeef23a6b5df7f4540745089 | https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb-core/lib/sdam/monitoring.js#L125-L204 | train |
brettz9/handle-node | src/index.js | handleNode | function handleNode (node, ...extraArgs) {
const cbObj = extraArgs[extraArgs.length - 1];
if (!nodeTypeToMethodMap.has(node.nodeType)) {
throw new TypeError('Not a valid `nodeType` value');
}
const methodName = nodeTypeToMethodMap.get(node.nodeType);
if (!cbObj[methodName]) {
return undefined;
}
return cbObj[methodName](node, ...extraArgs);
} | javascript | function handleNode (node, ...extraArgs) {
const cbObj = extraArgs[extraArgs.length - 1];
if (!nodeTypeToMethodMap.has(node.nodeType)) {
throw new TypeError('Not a valid `nodeType` value');
}
const methodName = nodeTypeToMethodMap.get(node.nodeType);
if (!cbObj[methodName]) {
return undefined;
}
return cbObj[methodName](node, ...extraArgs);
} | [
"function",
"handleNode",
"(",
"node",
",",
"...",
"extraArgs",
")",
"{",
"const",
"cbObj",
"=",
"extraArgs",
"[",
"extraArgs",
".",
"length",
"-",
"1",
"]",
";",
"if",
"(",
"!",
"nodeTypeToMethodMap",
".",
"has",
"(",
"node",
".",
"nodeType",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Not a valid `nodeType` value'",
")",
";",
"}",
"const",
"methodName",
"=",
"nodeTypeToMethodMap",
".",
"get",
"(",
"node",
".",
"nodeType",
")",
";",
"if",
"(",
"!",
"cbObj",
"[",
"methodName",
"]",
")",
"{",
"return",
"undefined",
";",
"}",
"return",
"cbObj",
"[",
"methodName",
"]",
"(",
"node",
",",
"...",
"extraArgs",
")",
";",
"}"
]
| Returns the value from executing a callback on a supplied callback
object according to the type of node supplied.
@param {Node} node An XML or HTML node
@param {Object} extraArgs Callback object whose properties–all optional
(`element`, `attribute`, `text`, `cdata`, `entityReference`, `entity`,
`processingInstruction`, `comment`, `document`, `documentType`,
`documentFragment`, `notation`) are callbacks which will be passed
the supplied arguments
@returns {any|void} The result of calling the relevant callback
(or `undefined` if no handler present) | [
"Returns",
"the",
"value",
"from",
"executing",
"a",
"callback",
"on",
"a",
"supplied",
"callback",
"object",
"according",
"to",
"the",
"type",
"of",
"node",
"supplied",
"."
]
| f8bab328ba1ad3895c5b4761a40cd18ae99a5c51 | https://github.com/brettz9/handle-node/blob/f8bab328ba1ad3895c5b4761a40cd18ae99a5c51/src/index.js#L28-L39 | train |
arnau/stylus-palette | lib/palette.js | parseColor | function parseColor (str) {
if (str.substr(0,1) === '#') {
// Handle color shorthands (like #abc)
var shorthand = str.length === 4,
m = str.match(shorthand ? /\w/g : /\w{2}/g);
if (!m) return;
m = m.map(function(s) { return parseInt(shorthand ? s+s : s, 16) });
return new nodes.RGBA(m[0],m[1],m[2],1);
}
else if (str.substr(0,3) === 'rgb'){
var m = str.match(/([0-9]*\.?[0-9]+)/g);
if (!m) return;
m = m.map(function(s){return parseFloat(s, 10)});
return new nodes.RGBA(m[0], m[1], m[2], m[3] || 1);
}
else {
var rgb = colors[str];
if (!rgb) return;
return new nodes.RGBA(rgb[0], rgb[1], rgb[2], 1);
}
} | javascript | function parseColor (str) {
if (str.substr(0,1) === '#') {
// Handle color shorthands (like #abc)
var shorthand = str.length === 4,
m = str.match(shorthand ? /\w/g : /\w{2}/g);
if (!m) return;
m = m.map(function(s) { return parseInt(shorthand ? s+s : s, 16) });
return new nodes.RGBA(m[0],m[1],m[2],1);
}
else if (str.substr(0,3) === 'rgb'){
var m = str.match(/([0-9]*\.?[0-9]+)/g);
if (!m) return;
m = m.map(function(s){return parseFloat(s, 10)});
return new nodes.RGBA(m[0], m[1], m[2], m[3] || 1);
}
else {
var rgb = colors[str];
if (!rgb) return;
return new nodes.RGBA(rgb[0], rgb[1], rgb[2], 1);
}
} | [
"function",
"parseColor",
"(",
"str",
")",
"{",
"if",
"(",
"str",
".",
"substr",
"(",
"0",
",",
"1",
")",
"===",
"'#'",
")",
"{",
"var",
"shorthand",
"=",
"str",
".",
"length",
"===",
"4",
",",
"m",
"=",
"str",
".",
"match",
"(",
"shorthand",
"?",
"/",
"\\w",
"/",
"g",
":",
"/",
"\\w{2}",
"/",
"g",
")",
";",
"if",
"(",
"!",
"m",
")",
"return",
";",
"m",
"=",
"m",
".",
"map",
"(",
"function",
"(",
"s",
")",
"{",
"return",
"parseInt",
"(",
"shorthand",
"?",
"s",
"+",
"s",
":",
"s",
",",
"16",
")",
"}",
")",
";",
"return",
"new",
"nodes",
".",
"RGBA",
"(",
"m",
"[",
"0",
"]",
",",
"m",
"[",
"1",
"]",
",",
"m",
"[",
"2",
"]",
",",
"1",
")",
";",
"}",
"else",
"if",
"(",
"str",
".",
"substr",
"(",
"0",
",",
"3",
")",
"===",
"'rgb'",
")",
"{",
"var",
"m",
"=",
"str",
".",
"match",
"(",
"/",
"([0-9]*\\.?[0-9]+)",
"/",
"g",
")",
";",
"if",
"(",
"!",
"m",
")",
"return",
";",
"m",
"=",
"m",
".",
"map",
"(",
"function",
"(",
"s",
")",
"{",
"return",
"parseFloat",
"(",
"s",
",",
"10",
")",
"}",
")",
";",
"return",
"new",
"nodes",
".",
"RGBA",
"(",
"m",
"[",
"0",
"]",
",",
"m",
"[",
"1",
"]",
",",
"m",
"[",
"2",
"]",
",",
"m",
"[",
"3",
"]",
"||",
"1",
")",
";",
"}",
"else",
"{",
"var",
"rgb",
"=",
"colors",
"[",
"str",
"]",
";",
"if",
"(",
"!",
"rgb",
")",
"return",
";",
"return",
"new",
"nodes",
".",
"RGBA",
"(",
"rgb",
"[",
"0",
"]",
",",
"rgb",
"[",
"1",
"]",
",",
"rgb",
"[",
"2",
"]",
",",
"1",
")",
";",
"}",
"}"
]
| Attempt to parse color. Copied from Stylus source code.
@param {String} str
@return {RGBA}
@api private | [
"Attempt",
"to",
"parse",
"color",
".",
"Copied",
"from",
"Stylus",
"source",
"code",
"."
]
| 21777ce91dfad3530925cd138d65cd9dc43d91e4 | https://github.com/arnau/stylus-palette/blob/21777ce91dfad3530925cd138d65cd9dc43d91e4/lib/palette.js#L34-L55 | train |
amooj/node-xcheck | benchmark/main.js | profileBlock | function profileBlock(block, repeat){
repeat = repeat || DEFAULT_REPEAT_COUNT;
let start = process.hrtime();
for (let i = 0; i < repeat; ++i){
block();
}
let diff = process.hrtime(start);
return Math.floor(diff[0] + diff[1] / 1e3);
} | javascript | function profileBlock(block, repeat){
repeat = repeat || DEFAULT_REPEAT_COUNT;
let start = process.hrtime();
for (let i = 0; i < repeat; ++i){
block();
}
let diff = process.hrtime(start);
return Math.floor(diff[0] + diff[1] / 1e3);
} | [
"function",
"profileBlock",
"(",
"block",
",",
"repeat",
")",
"{",
"repeat",
"=",
"repeat",
"||",
"DEFAULT_REPEAT_COUNT",
";",
"let",
"start",
"=",
"process",
".",
"hrtime",
"(",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"repeat",
";",
"++",
"i",
")",
"{",
"block",
"(",
")",
";",
"}",
"let",
"diff",
"=",
"process",
".",
"hrtime",
"(",
"start",
")",
";",
"return",
"Math",
".",
"floor",
"(",
"diff",
"[",
"0",
"]",
"+",
"diff",
"[",
"1",
"]",
"/",
"1e3",
")",
";",
"}"
]
| Profile code block.
@param {function} block - code to run.
@param {Number} [repeat] - Number of repeated times
@returns {Number} Total running time in microseconds. | [
"Profile",
"code",
"block",
"."
]
| 33b2b59f7d81a8e0421a468a405f15a19126bedf | https://github.com/amooj/node-xcheck/blob/33b2b59f7d81a8e0421a468a405f15a19126bedf/benchmark/main.js#L13-L21 | train |
dlindahl/zamora | src/luminosity.js | shiftLuminosity | function shiftLuminosity (hue, shiftAmount, huePoints) {
if (hue === 360) {
hue = 0
}
const hueShift = nearestHue(hue, huePoints)
const phi = PHI(hue, hueShift)
if (phi === 0) {
return hue
}
let newHue
if (phi > 0) {
newHue = hue + shiftAmount
} else {
newHue = hue - shiftAmount
}
return limit(newHue, 0, 360)
} | javascript | function shiftLuminosity (hue, shiftAmount, huePoints) {
if (hue === 360) {
hue = 0
}
const hueShift = nearestHue(hue, huePoints)
const phi = PHI(hue, hueShift)
if (phi === 0) {
return hue
}
let newHue
if (phi > 0) {
newHue = hue + shiftAmount
} else {
newHue = hue - shiftAmount
}
return limit(newHue, 0, 360)
} | [
"function",
"shiftLuminosity",
"(",
"hue",
",",
"shiftAmount",
",",
"huePoints",
")",
"{",
"if",
"(",
"hue",
"===",
"360",
")",
"{",
"hue",
"=",
"0",
"}",
"const",
"hueShift",
"=",
"nearestHue",
"(",
"hue",
",",
"huePoints",
")",
"const",
"phi",
"=",
"PHI",
"(",
"hue",
",",
"hueShift",
")",
"if",
"(",
"phi",
"===",
"0",
")",
"{",
"return",
"hue",
"}",
"let",
"newHue",
"if",
"(",
"phi",
">",
"0",
")",
"{",
"newHue",
"=",
"hue",
"+",
"shiftAmount",
"}",
"else",
"{",
"newHue",
"=",
"hue",
"-",
"shiftAmount",
"}",
"return",
"limit",
"(",
"newHue",
",",
"0",
",",
"360",
")",
"}"
]
| Shift perceived luminance towards or away from a specific max hue value | [
"Shift",
"perceived",
"luminance",
"towards",
"or",
"away",
"from",
"a",
"specific",
"max",
"hue",
"value"
]
| 0cf13ddea1c0664f40e8d2234e2f33ad91a8be32 | https://github.com/dlindahl/zamora/blob/0cf13ddea1c0664f40e8d2234e2f33ad91a8be32/src/luminosity.js#L13-L29 | train |
pinyin/outline | vendor/transformation-matrix/applyToPoint.js | applyToPoint | function applyToPoint(matrix, point) {
return {
x: matrix.a * point.x + matrix.c * point.y + matrix.e,
y: matrix.b * point.x + matrix.d * point.y + matrix.f
};
} | javascript | function applyToPoint(matrix, point) {
return {
x: matrix.a * point.x + matrix.c * point.y + matrix.e,
y: matrix.b * point.x + matrix.d * point.y + matrix.f
};
} | [
"function",
"applyToPoint",
"(",
"matrix",
",",
"point",
")",
"{",
"return",
"{",
"x",
":",
"matrix",
".",
"a",
"*",
"point",
".",
"x",
"+",
"matrix",
".",
"c",
"*",
"point",
".",
"y",
"+",
"matrix",
".",
"e",
",",
"y",
":",
"matrix",
".",
"b",
"*",
"point",
".",
"x",
"+",
"matrix",
".",
"d",
"*",
"point",
".",
"y",
"+",
"matrix",
".",
"f",
"}",
";",
"}"
]
| Calculate a point transformed with an affine matrix
@param matrix Affine matrix
@param point Point
@returns {{x: number, y: number}} Point | [
"Calculate",
"a",
"point",
"transformed",
"with",
"an",
"affine",
"matrix"
]
| e49f05d2f8ab384f5b1d71b2b10875cd48d41051 | https://github.com/pinyin/outline/blob/e49f05d2f8ab384f5b1d71b2b10875cd48d41051/vendor/transformation-matrix/applyToPoint.js#L15-L20 | train |
rehabstudio/fe-skeleton-testsuite | src/index.js | function(karmaSettings, resolveFn) {
var testServer = new karma.Server(karmaSettings, function(exitCode) {
if (typeof(resolveFn) === 'function') {
resolveFn(exitCode);
} else {
process.exit(exitCode);
}
});
testServer.start();
} | javascript | function(karmaSettings, resolveFn) {
var testServer = new karma.Server(karmaSettings, function(exitCode) {
if (typeof(resolveFn) === 'function') {
resolveFn(exitCode);
} else {
process.exit(exitCode);
}
});
testServer.start();
} | [
"function",
"(",
"karmaSettings",
",",
"resolveFn",
")",
"{",
"var",
"testServer",
"=",
"new",
"karma",
".",
"Server",
"(",
"karmaSettings",
",",
"function",
"(",
"exitCode",
")",
"{",
"if",
"(",
"typeof",
"(",
"resolveFn",
")",
"===",
"'function'",
")",
"{",
"resolveFn",
"(",
"exitCode",
")",
";",
"}",
"else",
"{",
"process",
".",
"exit",
"(",
"exitCode",
")",
";",
"}",
"}",
")",
";",
"testServer",
".",
"start",
"(",
")",
";",
"}"
]
| Run the test suite with the supplied settings and
callback function.
@param {Object} karmaSettings - Options for Karma.
@param {Function} resolveFn - Gulp async function. | [
"Run",
"the",
"test",
"suite",
"with",
"the",
"supplied",
"settings",
"and",
"callback",
"function",
"."
]
| 20fb80372291d37c6054793d8eae0860f778e13e | https://github.com/rehabstudio/fe-skeleton-testsuite/blob/20fb80372291d37c6054793d8eae0860f778e13e/src/index.js#L14-L24 | train |
|
aronnax/pooling | src/util.js | clearObject | function clearObject(object) {
var key;
for (key in object) {
if (object.hasOwnProperty(key)) {
// Ensures only writable properties are deleted.
try {
delete object[key];
} catch (e) { }
}
}
} | javascript | function clearObject(object) {
var key;
for (key in object) {
if (object.hasOwnProperty(key)) {
// Ensures only writable properties are deleted.
try {
delete object[key];
} catch (e) { }
}
}
} | [
"function",
"clearObject",
"(",
"object",
")",
"{",
"var",
"key",
";",
"for",
"(",
"key",
"in",
"object",
")",
"{",
"if",
"(",
"object",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"try",
"{",
"delete",
"object",
"[",
"key",
"]",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"}",
"}",
"}"
]
| Clear out an object of all properties
@private | [
"Clear",
"out",
"an",
"object",
"of",
"all",
"properties"
]
| 0ea11afdb25abca3e0dc07dcf37fde335533d7d1 | https://github.com/aronnax/pooling/blob/0ea11afdb25abca3e0dc07dcf37fde335533d7d1/src/util.js#L13-L24 | train |
yneves/node-bauer-factory | lib/stub.js | calledWith | function calledWith() {
var calledWithCount = 0;
var args = [];
var argsLength = arguments.length;
for (var i = 0; i < argsLength; i++) {
args[i] = arguments[i];
}
var callsLength = this._calls.length;
CALLS: for (var i = 0; i < callsLength; i++) {
var match = false;
var called = this._calls[i];
var calledLength = called.length;
if (argsLength === 0 && calledLength === 0) {
match = true;
} else {
ARGS: for (var a = 0; a < argsLength; a++) {
match = matchArgs(args[a],called[a]);
if (!match) {
break ARGS;
}
}
}
if (match) {
calledWithCount++;
}
}
return calledWithCount;
} | javascript | function calledWith() {
var calledWithCount = 0;
var args = [];
var argsLength = arguments.length;
for (var i = 0; i < argsLength; i++) {
args[i] = arguments[i];
}
var callsLength = this._calls.length;
CALLS: for (var i = 0; i < callsLength; i++) {
var match = false;
var called = this._calls[i];
var calledLength = called.length;
if (argsLength === 0 && calledLength === 0) {
match = true;
} else {
ARGS: for (var a = 0; a < argsLength; a++) {
match = matchArgs(args[a],called[a]);
if (!match) {
break ARGS;
}
}
}
if (match) {
calledWithCount++;
}
}
return calledWithCount;
} | [
"function",
"calledWith",
"(",
")",
"{",
"var",
"calledWithCount",
"=",
"0",
";",
"var",
"args",
"=",
"[",
"]",
";",
"var",
"argsLength",
"=",
"arguments",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"argsLength",
";",
"i",
"++",
")",
"{",
"args",
"[",
"i",
"]",
"=",
"arguments",
"[",
"i",
"]",
";",
"}",
"var",
"callsLength",
"=",
"this",
".",
"_calls",
".",
"length",
";",
"CALLS",
":",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"callsLength",
";",
"i",
"++",
")",
"{",
"var",
"match",
"=",
"false",
";",
"var",
"called",
"=",
"this",
".",
"_calls",
"[",
"i",
"]",
";",
"var",
"calledLength",
"=",
"called",
".",
"length",
";",
"if",
"(",
"argsLength",
"===",
"0",
"&&",
"calledLength",
"===",
"0",
")",
"{",
"match",
"=",
"true",
";",
"}",
"else",
"{",
"ARGS",
":",
"for",
"(",
"var",
"a",
"=",
"0",
";",
"a",
"<",
"argsLength",
";",
"a",
"++",
")",
"{",
"match",
"=",
"matchArgs",
"(",
"args",
"[",
"a",
"]",
",",
"called",
"[",
"a",
"]",
")",
";",
"if",
"(",
"!",
"match",
")",
"{",
"break",
"ARGS",
";",
"}",
"}",
"}",
"if",
"(",
"match",
")",
"{",
"calledWithCount",
"++",
";",
"}",
"}",
"return",
"calledWithCount",
";",
"}"
]
| Count how many times stub have been called with passed arguments. | [
"Count",
"how",
"many",
"times",
"stub",
"have",
"been",
"called",
"with",
"passed",
"arguments",
"."
]
| 0c54442276e742792e4c737363c1062fd2529877 | https://github.com/yneves/node-bauer-factory/blob/0c54442276e742792e4c737363c1062fd2529877/lib/stub.js#L45-L72 | train |
yneves/node-bauer-factory | lib/stub.js | callbackWith | function callbackWith() {
this._callbackWith = [];
var length = arguments.length;
for (var i = 0; i < length; i++) {
var arg = arguments[i];
this._callbackWith.push(arg);
}
return this;
} | javascript | function callbackWith() {
this._callbackWith = [];
var length = arguments.length;
for (var i = 0; i < length; i++) {
var arg = arguments[i];
this._callbackWith.push(arg);
}
return this;
} | [
"function",
"callbackWith",
"(",
")",
"{",
"this",
".",
"_callbackWith",
"=",
"[",
"]",
";",
"var",
"length",
"=",
"arguments",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"var",
"arg",
"=",
"arguments",
"[",
"i",
"]",
";",
"this",
".",
"_callbackWith",
".",
"push",
"(",
"arg",
")",
";",
"}",
"return",
"this",
";",
"}"
]
| Defines arguments to be used by stub pass to callbacks when called. | [
"Defines",
"arguments",
"to",
"be",
"used",
"by",
"stub",
"pass",
"to",
"callbacks",
"when",
"called",
"."
]
| 0c54442276e742792e4c737363c1062fd2529877 | https://github.com/yneves/node-bauer-factory/blob/0c54442276e742792e4c737363c1062fd2529877/lib/stub.js#L95-L103 | train |
usco/usco-stl-parser | dist/index.js | makeParsedStream | function makeParsedStream() {
var parameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var defaults = {
useWorker: _compositeDetect2.default.isBrowser === true,
concat: true
};
parameters = Object.assign({}, defaults, parameters);
var _parameters = parameters,
useWorker = _parameters.useWorker,
concat = _parameters.concat;
var mainStream = useWorker ? (0, _workerSpawner2.default)() : (0, _through2.default)((0, _parseStream2.default)());
// concatenate result into a single one if needed (still streaming)
var endStream = concat ? (0, _combining2.default)()(mainStream, (0, _concatStream2.default)()) : mainStream;
return endStream;
} | javascript | function makeParsedStream() {
var parameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var defaults = {
useWorker: _compositeDetect2.default.isBrowser === true,
concat: true
};
parameters = Object.assign({}, defaults, parameters);
var _parameters = parameters,
useWorker = _parameters.useWorker,
concat = _parameters.concat;
var mainStream = useWorker ? (0, _workerSpawner2.default)() : (0, _through2.default)((0, _parseStream2.default)());
// concatenate result into a single one if needed (still streaming)
var endStream = concat ? (0, _combining2.default)()(mainStream, (0, _concatStream2.default)()) : mainStream;
return endStream;
} | [
"function",
"makeParsedStream",
"(",
")",
"{",
"var",
"parameters",
"=",
"arguments",
".",
"length",
">",
"0",
"&&",
"arguments",
"[",
"0",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"0",
"]",
":",
"{",
"}",
";",
"var",
"defaults",
"=",
"{",
"useWorker",
":",
"_compositeDetect2",
".",
"default",
".",
"isBrowser",
"===",
"true",
",",
"concat",
":",
"true",
"}",
";",
"parameters",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"defaults",
",",
"parameters",
")",
";",
"var",
"_parameters",
"=",
"parameters",
",",
"useWorker",
"=",
"_parameters",
".",
"useWorker",
",",
"concat",
"=",
"_parameters",
".",
"concat",
";",
"var",
"mainStream",
"=",
"useWorker",
"?",
"(",
"0",
",",
"_workerSpawner2",
".",
"default",
")",
"(",
")",
":",
"(",
"0",
",",
"_through2",
".",
"default",
")",
"(",
"(",
"0",
",",
"_parseStream2",
".",
"default",
")",
"(",
")",
")",
";",
"var",
"endStream",
"=",
"concat",
"?",
"(",
"0",
",",
"_combining2",
".",
"default",
")",
"(",
")",
"(",
"mainStream",
",",
"(",
"0",
",",
"_concatStream2",
".",
"default",
")",
"(",
")",
")",
":",
"mainStream",
";",
"return",
"endStream",
";",
"}"
]
| parses and return a stream of parsed stl data
@param {Object} parameters parameters for the parser
@param {Boolean} parameters.useWorker use web workers (browser only) defaults to true in browser
@param {Boolean} parameters.concat when set to true, stream outputs a single value with all combined data
@return {Object} stream of parsed stl data in the form {positions:TypedArray, normals:TypedArray} | [
"parses",
"and",
"return",
"a",
"stream",
"of",
"parsed",
"stl",
"data"
]
| 49eb402f124723d8f74cc67f24a7017c2b99bca4 | https://github.com/usco/usco-stl-parser/blob/49eb402f124723d8f74cc67f24a7017c2b99bca4/dist/index.js#L49-L67 | train |
BarzinJS/querystring-context | lib/parser.js | function (arr, val) {
debug('Finding all indices...');
debug('Array: %o', arr);
let indexes = [];
for (let i = 0; i < arr.length; i++) {
const
camelCaseVal = camelCase(val),
camelCaseKey = camelCase(arr[i]);
if (arr[i] === val || camelCaseKey === camelCaseVal) {
debug('Matched index: %s', i);
indexes.push(i);
}
}
debug('Found indices: %o', indexes);
return indexes;
} | javascript | function (arr, val) {
debug('Finding all indices...');
debug('Array: %o', arr);
let indexes = [];
for (let i = 0; i < arr.length; i++) {
const
camelCaseVal = camelCase(val),
camelCaseKey = camelCase(arr[i]);
if (arr[i] === val || camelCaseKey === camelCaseVal) {
debug('Matched index: %s', i);
indexes.push(i);
}
}
debug('Found indices: %o', indexes);
return indexes;
} | [
"function",
"(",
"arr",
",",
"val",
")",
"{",
"debug",
"(",
"'Finding all indices...'",
")",
";",
"debug",
"(",
"'Array: %o'",
",",
"arr",
")",
";",
"let",
"indexes",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"arr",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"camelCaseVal",
"=",
"camelCase",
"(",
"val",
")",
",",
"camelCaseKey",
"=",
"camelCase",
"(",
"arr",
"[",
"i",
"]",
")",
";",
"if",
"(",
"arr",
"[",
"i",
"]",
"===",
"val",
"||",
"camelCaseKey",
"===",
"camelCaseVal",
")",
"{",
"debug",
"(",
"'Matched index: %s'",
",",
"i",
")",
";",
"indexes",
".",
"push",
"(",
"i",
")",
";",
"}",
"}",
"debug",
"(",
"'Found indices: %o'",
",",
"indexes",
")",
";",
"return",
"indexes",
";",
"}"
]
| Find all indices of a value in an array
@param {Array<string>} arr Array to search in
@param {string} val Target value
@returns {Array<number>} List of indices | [
"Find",
"all",
"indices",
"of",
"a",
"value",
"in",
"an",
"array"
]
| 9e082778ac484660d159b4687fcf8a012cb9d903 | https://github.com/BarzinJS/querystring-context/blob/9e082778ac484660d159b4687fcf8a012cb9d903/lib/parser.js#L104-L128 | train |
|
BarzinJS/querystring-context | lib/parser.js | function (value) {
if (!Array.isArray(value)) {
// null/undefined or anything else must be safely convert to string
value = value + '';
}
if (Array.isArray(value)) {
// map all values again
value = value.map(v => this.parseValue(v));
} else if (validator.isNumeric(value)) {
value = value * 1; // parse as a number
} else if (validator.isBoolean(value)) {
value = (value === 'true');
} else {
// convert to JS date
const date = validator.toDate(value);
// date is valid, assign
if (date !== null) {
value = date;
}
if (value === 'null') {
value = null;
}
if (value === 'undefined') {
value = undefined;
}
}
return value;
} | javascript | function (value) {
if (!Array.isArray(value)) {
// null/undefined or anything else must be safely convert to string
value = value + '';
}
if (Array.isArray(value)) {
// map all values again
value = value.map(v => this.parseValue(v));
} else if (validator.isNumeric(value)) {
value = value * 1; // parse as a number
} else if (validator.isBoolean(value)) {
value = (value === 'true');
} else {
// convert to JS date
const date = validator.toDate(value);
// date is valid, assign
if (date !== null) {
value = date;
}
if (value === 'null') {
value = null;
}
if (value === 'undefined') {
value = undefined;
}
}
return value;
} | [
"function",
"(",
"value",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"value",
"=",
"value",
"+",
"''",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"value",
"=",
"value",
".",
"map",
"(",
"v",
"=>",
"this",
".",
"parseValue",
"(",
"v",
")",
")",
";",
"}",
"else",
"if",
"(",
"validator",
".",
"isNumeric",
"(",
"value",
")",
")",
"{",
"value",
"=",
"value",
"*",
"1",
";",
"}",
"else",
"if",
"(",
"validator",
".",
"isBoolean",
"(",
"value",
")",
")",
"{",
"value",
"=",
"(",
"value",
"===",
"'true'",
")",
";",
"}",
"else",
"{",
"const",
"date",
"=",
"validator",
".",
"toDate",
"(",
"value",
")",
";",
"if",
"(",
"date",
"!==",
"null",
")",
"{",
"value",
"=",
"date",
";",
"}",
"if",
"(",
"value",
"===",
"'null'",
")",
"{",
"value",
"=",
"null",
";",
"}",
"if",
"(",
"value",
"===",
"'undefined'",
")",
"{",
"value",
"=",
"undefined",
";",
"}",
"}",
"return",
"value",
";",
"}"
]
| Parse string to a parsable type
@param {string} value Value to parse
@returns {string|number|boolean|date} Parsed value | [
"Parse",
"string",
"to",
"a",
"parsable",
"type"
]
| 9e082778ac484660d159b4687fcf8a012cb9d903 | https://github.com/BarzinJS/querystring-context/blob/9e082778ac484660d159b4687fcf8a012cb9d903/lib/parser.js#L201-L246 | train |
|
BarzinJS/querystring-context | lib/parser.js | function (obj, options) {
debug('Parsing properties...');
debug('Object: %o', obj);
Object.keys(obj)
.map(key => {
let value = obj[key];
debug('Value: %o', value);
// parse current value
value = helpers.parseValue(value);
debug('Parsed value: %o', value);
// replace value with the updated one
obj[key] = value;
});
debug('Parsed options: %o', obj);
return obj;
} | javascript | function (obj, options) {
debug('Parsing properties...');
debug('Object: %o', obj);
Object.keys(obj)
.map(key => {
let value = obj[key];
debug('Value: %o', value);
// parse current value
value = helpers.parseValue(value);
debug('Parsed value: %o', value);
// replace value with the updated one
obj[key] = value;
});
debug('Parsed options: %o', obj);
return obj;
} | [
"function",
"(",
"obj",
",",
"options",
")",
"{",
"debug",
"(",
"'Parsing properties...'",
")",
";",
"debug",
"(",
"'Object: %o'",
",",
"obj",
")",
";",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"map",
"(",
"key",
"=>",
"{",
"let",
"value",
"=",
"obj",
"[",
"key",
"]",
";",
"debug",
"(",
"'Value: %o'",
",",
"value",
")",
";",
"value",
"=",
"helpers",
".",
"parseValue",
"(",
"value",
")",
";",
"debug",
"(",
"'Parsed value: %o'",
",",
"value",
")",
";",
"obj",
"[",
"key",
"]",
"=",
"value",
";",
"}",
")",
";",
"debug",
"(",
"'Parsed options: %o'",
",",
"obj",
")",
";",
"return",
"obj",
";",
"}"
]
| Parse properties of an object
@param {any} obj Target object
@param {any} options Parser options
@returns {any} Parsed options | [
"Parse",
"properties",
"of",
"an",
"object"
]
| 9e082778ac484660d159b4687fcf8a012cb9d903 | https://github.com/BarzinJS/querystring-context/blob/9e082778ac484660d159b4687fcf8a012cb9d903/lib/parser.js#L254-L279 | train |
|
skylarkutils/skylark-utils | examples/images/progress/progress.js | onProgress | function onProgress( e ) {
// change class if the image is loaded or broken
e.img.parentNode.className = e.isLoaded ? '' : 'is-broken';
// update progress element
loadedImageCount++;
updateProgress( loadedImageCount );
} | javascript | function onProgress( e ) {
// change class if the image is loaded or broken
e.img.parentNode.className = e.isLoaded ? '' : 'is-broken';
// update progress element
loadedImageCount++;
updateProgress( loadedImageCount );
} | [
"function",
"onProgress",
"(",
"e",
")",
"{",
"e",
".",
"img",
".",
"parentNode",
".",
"className",
"=",
"e",
".",
"isLoaded",
"?",
"''",
":",
"'is-broken'",
";",
"loadedImageCount",
"++",
";",
"updateProgress",
"(",
"loadedImageCount",
")",
";",
"}"
]
| triggered after each item is loaded | [
"triggered",
"after",
"each",
"item",
"is",
"loaded"
]
| ef082bb53b162b4a2c6992ef07a3e32553f6aed5 | https://github.com/skylarkutils/skylark-utils/blob/ef082bb53b162b4a2c6992ef07a3e32553f6aed5/examples/images/progress/progress.js#L100-L106 | train |
lakenen/node-box-view | index.js | determineFilename | function determineFilename(file) {
var filename,
filenameMatch;
if (file.hasOwnProperty('httpVersion')) {
// it's an http response
// first let's check if there's a content-disposition header...
if (file.headers['content-disposition']) {
filenameMatch = /filename=(.*)/.exec(file.headers['content-disposition']);
filename = filenameMatch[1];
}
if (!filename) {
// try to get the path of the request url
filename = path.basename(file.client._httpMessage.path);
}
} else if (file.path) {
// it looks like a file, let's just get the path
filename = path.basename(file.path);
}
return filename || 'untitled document';
} | javascript | function determineFilename(file) {
var filename,
filenameMatch;
if (file.hasOwnProperty('httpVersion')) {
// it's an http response
// first let's check if there's a content-disposition header...
if (file.headers['content-disposition']) {
filenameMatch = /filename=(.*)/.exec(file.headers['content-disposition']);
filename = filenameMatch[1];
}
if (!filename) {
// try to get the path of the request url
filename = path.basename(file.client._httpMessage.path);
}
} else if (file.path) {
// it looks like a file, let's just get the path
filename = path.basename(file.path);
}
return filename || 'untitled document';
} | [
"function",
"determineFilename",
"(",
"file",
")",
"{",
"var",
"filename",
",",
"filenameMatch",
";",
"if",
"(",
"file",
".",
"hasOwnProperty",
"(",
"'httpVersion'",
")",
")",
"{",
"if",
"(",
"file",
".",
"headers",
"[",
"'content-disposition'",
"]",
")",
"{",
"filenameMatch",
"=",
"/",
"filename=(.*)",
"/",
".",
"exec",
"(",
"file",
".",
"headers",
"[",
"'content-disposition'",
"]",
")",
";",
"filename",
"=",
"filenameMatch",
"[",
"1",
"]",
";",
"}",
"if",
"(",
"!",
"filename",
")",
"{",
"filename",
"=",
"path",
".",
"basename",
"(",
"file",
".",
"client",
".",
"_httpMessage",
".",
"path",
")",
";",
"}",
"}",
"else",
"if",
"(",
"file",
".",
"path",
")",
"{",
"filename",
"=",
"path",
".",
"basename",
"(",
"file",
".",
"path",
")",
";",
"}",
"return",
"filename",
"||",
"'untitled document'",
";",
"}"
]
| Try to figure out the filename for the given file
@param {Stream} file The file stream
@returns {string} The guessed filename | [
"Try",
"to",
"figure",
"out",
"the",
"filename",
"for",
"the",
"given",
"file"
]
| 5888e4d60cd6bdc3b656724bee2dd56b6adf32ec | https://github.com/lakenen/node-box-view/blob/5888e4d60cd6bdc3b656724bee2dd56b6adf32ec/index.js#L57-L77 | train |
lakenen/node-box-view | index.js | handleError | function handleError(body, response, callback) {
var error;
if (!body) {
response.pipe(concat(function (body) {
body = parseJSONBody(body);
error = body.message || statusText(response.statusCode);
callback(new Error(error), body, response);
}));
} else {
error = body.message || statusText(response.statusCode);
callback(new Error(error), body, response);
}
} | javascript | function handleError(body, response, callback) {
var error;
if (!body) {
response.pipe(concat(function (body) {
body = parseJSONBody(body);
error = body.message || statusText(response.statusCode);
callback(new Error(error), body, response);
}));
} else {
error = body.message || statusText(response.statusCode);
callback(new Error(error), body, response);
}
} | [
"function",
"handleError",
"(",
"body",
",",
"response",
",",
"callback",
")",
"{",
"var",
"error",
";",
"if",
"(",
"!",
"body",
")",
"{",
"response",
".",
"pipe",
"(",
"concat",
"(",
"function",
"(",
"body",
")",
"{",
"body",
"=",
"parseJSONBody",
"(",
"body",
")",
";",
"error",
"=",
"body",
".",
"message",
"||",
"statusText",
"(",
"response",
".",
"statusCode",
")",
";",
"callback",
"(",
"new",
"Error",
"(",
"error",
")",
",",
"body",
",",
"response",
")",
";",
"}",
")",
")",
";",
"}",
"else",
"{",
"error",
"=",
"body",
".",
"message",
"||",
"statusText",
"(",
"response",
".",
"statusCode",
")",
";",
"callback",
"(",
"new",
"Error",
"(",
"error",
")",
",",
"body",
",",
"response",
")",
";",
"}",
"}"
]
| Create an error object from the response and call the callback function
@param {Object} body The parsed response body (or null if not yet parsed)
@param {Response} response The HTTP response object
@param {Function} callback Function to call with the resulting error object
@returns {void} | [
"Create",
"an",
"error",
"object",
"from",
"the",
"response",
"and",
"call",
"the",
"callback",
"function"
]
| 5888e4d60cd6bdc3b656724bee2dd56b6adf32ec | https://github.com/lakenen/node-box-view/blob/5888e4d60cd6bdc3b656724bee2dd56b6adf32ec/index.js#L117-L129 | train |
lakenen/node-box-view | index.js | createResponseHandler | function createResponseHandler(callback, okStatusCodes, noBuffer, retryFn) {
if (typeof callback !== 'function') {
callback = function () {};
}
if (typeof okStatusCodes === 'function') {
retryFn = okStatusCodes;
okStatusCodes = null;
noBuffer = retryFn;
}
if (typeof noBuffer === 'function') {
retryFn = noBuffer;
noBuffer = false;
}
okStatusCodes = okStatusCodes || [200];
/**
* Retry the request if a retry function and retry-after headers are present
* @param {HTTPResponse} response The response object
* @returns {void}
*/
function retry(response) {
var retryAfter = response.headers['retry-after'];
if (typeof retryFn === 'function' && retryAfter) {
retryAfter = parseInt(retryAfter, 10);
setTimeout(retryFn, retryAfter * 1000);
return true;
}
return false;
}
function handleResponse(response, body) {
var error;
// the handler expects a parsed response body
if (noBuffer !== true && typeof body === 'undefined') {
response.pipe(concat(function (body) {
handleResponse(response, parseJSONBody(body));
}));
return;
}
if (okStatusCodes.indexOf(response.statusCode) > -1) {
if (!retry(response)) {
if (noBuffer) {
callback(null, response);
} else {
callback(null, body, response);
}
}
} else {
if (response.statusCode === 429) {
if (retry(response)) {
return;
}
}
handleError(body, response, callback);
}
}
return function (error, response) {
if (error) {
callback(error, response);
} else {
handleResponse(response);
}
};
} | javascript | function createResponseHandler(callback, okStatusCodes, noBuffer, retryFn) {
if (typeof callback !== 'function') {
callback = function () {};
}
if (typeof okStatusCodes === 'function') {
retryFn = okStatusCodes;
okStatusCodes = null;
noBuffer = retryFn;
}
if (typeof noBuffer === 'function') {
retryFn = noBuffer;
noBuffer = false;
}
okStatusCodes = okStatusCodes || [200];
/**
* Retry the request if a retry function and retry-after headers are present
* @param {HTTPResponse} response The response object
* @returns {void}
*/
function retry(response) {
var retryAfter = response.headers['retry-after'];
if (typeof retryFn === 'function' && retryAfter) {
retryAfter = parseInt(retryAfter, 10);
setTimeout(retryFn, retryAfter * 1000);
return true;
}
return false;
}
function handleResponse(response, body) {
var error;
// the handler expects a parsed response body
if (noBuffer !== true && typeof body === 'undefined') {
response.pipe(concat(function (body) {
handleResponse(response, parseJSONBody(body));
}));
return;
}
if (okStatusCodes.indexOf(response.statusCode) > -1) {
if (!retry(response)) {
if (noBuffer) {
callback(null, response);
} else {
callback(null, body, response);
}
}
} else {
if (response.statusCode === 429) {
if (retry(response)) {
return;
}
}
handleError(body, response, callback);
}
}
return function (error, response) {
if (error) {
callback(error, response);
} else {
handleResponse(response);
}
};
} | [
"function",
"createResponseHandler",
"(",
"callback",
",",
"okStatusCodes",
",",
"noBuffer",
",",
"retryFn",
")",
"{",
"if",
"(",
"typeof",
"callback",
"!==",
"'function'",
")",
"{",
"callback",
"=",
"function",
"(",
")",
"{",
"}",
";",
"}",
"if",
"(",
"typeof",
"okStatusCodes",
"===",
"'function'",
")",
"{",
"retryFn",
"=",
"okStatusCodes",
";",
"okStatusCodes",
"=",
"null",
";",
"noBuffer",
"=",
"retryFn",
";",
"}",
"if",
"(",
"typeof",
"noBuffer",
"===",
"'function'",
")",
"{",
"retryFn",
"=",
"noBuffer",
";",
"noBuffer",
"=",
"false",
";",
"}",
"okStatusCodes",
"=",
"okStatusCodes",
"||",
"[",
"200",
"]",
";",
"function",
"retry",
"(",
"response",
")",
"{",
"var",
"retryAfter",
"=",
"response",
".",
"headers",
"[",
"'retry-after'",
"]",
";",
"if",
"(",
"typeof",
"retryFn",
"===",
"'function'",
"&&",
"retryAfter",
")",
"{",
"retryAfter",
"=",
"parseInt",
"(",
"retryAfter",
",",
"10",
")",
";",
"setTimeout",
"(",
"retryFn",
",",
"retryAfter",
"*",
"1000",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}",
"function",
"handleResponse",
"(",
"response",
",",
"body",
")",
"{",
"var",
"error",
";",
"if",
"(",
"noBuffer",
"!==",
"true",
"&&",
"typeof",
"body",
"===",
"'undefined'",
")",
"{",
"response",
".",
"pipe",
"(",
"concat",
"(",
"function",
"(",
"body",
")",
"{",
"handleResponse",
"(",
"response",
",",
"parseJSONBody",
"(",
"body",
")",
")",
";",
"}",
")",
")",
";",
"return",
";",
"}",
"if",
"(",
"okStatusCodes",
".",
"indexOf",
"(",
"response",
".",
"statusCode",
")",
">",
"-",
"1",
")",
"{",
"if",
"(",
"!",
"retry",
"(",
"response",
")",
")",
"{",
"if",
"(",
"noBuffer",
")",
"{",
"callback",
"(",
"null",
",",
"response",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
",",
"body",
",",
"response",
")",
";",
"}",
"}",
"}",
"else",
"{",
"if",
"(",
"response",
".",
"statusCode",
"===",
"429",
")",
"{",
"if",
"(",
"retry",
"(",
"response",
")",
")",
"{",
"return",
";",
"}",
"}",
"handleError",
"(",
"body",
",",
"response",
",",
"callback",
")",
";",
"}",
"}",
"return",
"function",
"(",
"error",
",",
"response",
")",
"{",
"if",
"(",
"error",
")",
"{",
"callback",
"(",
"error",
",",
"response",
")",
";",
"}",
"else",
"{",
"handleResponse",
"(",
"response",
")",
";",
"}",
"}",
";",
"}"
]
| Return an http response handler for API calls
@param {Function} callback The callback method to call
@param {Array} okStatusCodes (optional) HTTP status codes to use as OK (default: [200])
@param {Boolean} noBuffer (optional) If true, the response will not be buffered and JSON parsed (unless error), default: false
@param {Function} retryFn (optional) If defined, function to call when receiving a Retry-After header
@returns {Function} The response handler | [
"Return",
"an",
"http",
"response",
"handler",
"for",
"API",
"calls"
]
| 5888e4d60cd6bdc3b656724bee2dd56b6adf32ec | https://github.com/lakenen/node-box-view/blob/5888e4d60cd6bdc3b656724bee2dd56b6adf32ec/index.js#L139-L208 | train |
lakenen/node-box-view | index.js | retry | function retry(response) {
var retryAfter = response.headers['retry-after'];
if (typeof retryFn === 'function' && retryAfter) {
retryAfter = parseInt(retryAfter, 10);
setTimeout(retryFn, retryAfter * 1000);
return true;
}
return false;
} | javascript | function retry(response) {
var retryAfter = response.headers['retry-after'];
if (typeof retryFn === 'function' && retryAfter) {
retryAfter = parseInt(retryAfter, 10);
setTimeout(retryFn, retryAfter * 1000);
return true;
}
return false;
} | [
"function",
"retry",
"(",
"response",
")",
"{",
"var",
"retryAfter",
"=",
"response",
".",
"headers",
"[",
"'retry-after'",
"]",
";",
"if",
"(",
"typeof",
"retryFn",
"===",
"'function'",
"&&",
"retryAfter",
")",
"{",
"retryAfter",
"=",
"parseInt",
"(",
"retryAfter",
",",
"10",
")",
";",
"setTimeout",
"(",
"retryFn",
",",
"retryAfter",
"*",
"1000",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
]
| Retry the request if a retry function and retry-after headers are present
@param {HTTPResponse} response The response object
@returns {void} | [
"Retry",
"the",
"request",
"if",
"a",
"retry",
"function",
"and",
"retry",
"-",
"after",
"headers",
"are",
"present"
]
| 5888e4d60cd6bdc3b656724bee2dd56b6adf32ec | https://github.com/lakenen/node-box-view/blob/5888e4d60cd6bdc3b656724bee2dd56b6adf32ec/index.js#L161-L169 | train |
lakenen/node-box-view | index.js | function (options, callback) {
var query,
handler,
retry = false,
params,
args = arguments;
if (typeof options === 'function') {
callback = options;
params = {};
} else {
params = extend({}, options.params);
retry = options.retry;
}
retry = (retry === true) && function () {
this.list.apply(this, args);
}.bind(this);
if (params['created_before']) {
params['created_before'] = getTimestamp(params['created_before']);
}
if (params['created_after']) {
params['created_after'] = getTimestamp(params['created_after']);
}
query = querystring.stringify(params);
if (query) {
query = '?' + query;
}
handler = createResponseHandler(callback, retry);
return req(client.documentsURL + query, handler);
} | javascript | function (options, callback) {
var query,
handler,
retry = false,
params,
args = arguments;
if (typeof options === 'function') {
callback = options;
params = {};
} else {
params = extend({}, options.params);
retry = options.retry;
}
retry = (retry === true) && function () {
this.list.apply(this, args);
}.bind(this);
if (params['created_before']) {
params['created_before'] = getTimestamp(params['created_before']);
}
if (params['created_after']) {
params['created_after'] = getTimestamp(params['created_after']);
}
query = querystring.stringify(params);
if (query) {
query = '?' + query;
}
handler = createResponseHandler(callback, retry);
return req(client.documentsURL + query, handler);
} | [
"function",
"(",
"options",
",",
"callback",
")",
"{",
"var",
"query",
",",
"handler",
",",
"retry",
"=",
"false",
",",
"params",
",",
"args",
"=",
"arguments",
";",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
")",
"{",
"callback",
"=",
"options",
";",
"params",
"=",
"{",
"}",
";",
"}",
"else",
"{",
"params",
"=",
"extend",
"(",
"{",
"}",
",",
"options",
".",
"params",
")",
";",
"retry",
"=",
"options",
".",
"retry",
";",
"}",
"retry",
"=",
"(",
"retry",
"===",
"true",
")",
"&&",
"function",
"(",
")",
"{",
"this",
".",
"list",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
";",
"if",
"(",
"params",
"[",
"'created_before'",
"]",
")",
"{",
"params",
"[",
"'created_before'",
"]",
"=",
"getTimestamp",
"(",
"params",
"[",
"'created_before'",
"]",
")",
";",
"}",
"if",
"(",
"params",
"[",
"'created_after'",
"]",
")",
"{",
"params",
"[",
"'created_after'",
"]",
"=",
"getTimestamp",
"(",
"params",
"[",
"'created_after'",
"]",
")",
";",
"}",
"query",
"=",
"querystring",
".",
"stringify",
"(",
"params",
")",
";",
"if",
"(",
"query",
")",
"{",
"query",
"=",
"'?'",
"+",
"query",
";",
"}",
"handler",
"=",
"createResponseHandler",
"(",
"callback",
",",
"retry",
")",
";",
"return",
"req",
"(",
"client",
".",
"documentsURL",
"+",
"query",
",",
"handler",
")",
";",
"}"
]
| Fetch a list of documents uploaded using this API key
@param {Object} [options] List options
@param {boolean} [options.retry] Whether to retry the request after 'retry-after' seconds if the retry-after header is sent
@param {Object} [options.params] URL parameters
@param {int} [options.params.limit] The number of documents to return (default: 10, max: 50)
@param {Date} [options.params.created_before] An upper limit on the creation timestamps of documents returned (default: now)
@param {Date} [options.params.created_after] A lower limit on the creation timestamps of documents returned
@param {Function} [callback] A callback to call with the response data (or error)
@returns {Request} | [
"Fetch",
"a",
"list",
"of",
"documents",
"uploaded",
"using",
"this",
"API",
"key"
]
| 5888e4d60cd6bdc3b656724bee2dd56b6adf32ec | https://github.com/lakenen/node-box-view/blob/5888e4d60cd6bdc3b656724bee2dd56b6adf32ec/index.js#L241-L276 | train |
|
lakenen/node-box-view | index.js | function (id, options, callback) {
var query = '',
handler,
retry = false,
fields,
args = arguments;
if (typeof options === 'function') {
callback = options;
fields = '';
} else {
options = extend({}, options);
fields = options.fields || '';
retry = options.retry;
}
if (Array.isArray(fields)) {
fields = fields.join(',');
}
retry = (retry === true) && function () {
this.get.apply(this, args);
}.bind(this);
if (fields) {
query = '?' + querystring.stringify({
fields: fields
});
}
handler = createResponseHandler(callback, retry);
return req(client.documentsURL + '/' + id + query, handler);
} | javascript | function (id, options, callback) {
var query = '',
handler,
retry = false,
fields,
args = arguments;
if (typeof options === 'function') {
callback = options;
fields = '';
} else {
options = extend({}, options);
fields = options.fields || '';
retry = options.retry;
}
if (Array.isArray(fields)) {
fields = fields.join(',');
}
retry = (retry === true) && function () {
this.get.apply(this, args);
}.bind(this);
if (fields) {
query = '?' + querystring.stringify({
fields: fields
});
}
handler = createResponseHandler(callback, retry);
return req(client.documentsURL + '/' + id + query, handler);
} | [
"function",
"(",
"id",
",",
"options",
",",
"callback",
")",
"{",
"var",
"query",
"=",
"''",
",",
"handler",
",",
"retry",
"=",
"false",
",",
"fields",
",",
"args",
"=",
"arguments",
";",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
")",
"{",
"callback",
"=",
"options",
";",
"fields",
"=",
"''",
";",
"}",
"else",
"{",
"options",
"=",
"extend",
"(",
"{",
"}",
",",
"options",
")",
";",
"fields",
"=",
"options",
".",
"fields",
"||",
"''",
";",
"retry",
"=",
"options",
".",
"retry",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"fields",
")",
")",
"{",
"fields",
"=",
"fields",
".",
"join",
"(",
"','",
")",
";",
"}",
"retry",
"=",
"(",
"retry",
"===",
"true",
")",
"&&",
"function",
"(",
")",
"{",
"this",
".",
"get",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
";",
"if",
"(",
"fields",
")",
"{",
"query",
"=",
"'?'",
"+",
"querystring",
".",
"stringify",
"(",
"{",
"fields",
":",
"fields",
"}",
")",
";",
"}",
"handler",
"=",
"createResponseHandler",
"(",
"callback",
",",
"retry",
")",
";",
"return",
"req",
"(",
"client",
".",
"documentsURL",
"+",
"'/'",
"+",
"id",
"+",
"query",
",",
"handler",
")",
";",
"}"
]
| Fetch the metadata for a single document
@param {String} id The document uuid
@param {Object} [options] Get options
@param {boolean} [options.retry] Whether to retry the request after 'retry-after' seconds if the retry-after header is sent
@param {String|Array} [options.fields] Array of strings or comma-separated string of fields to return. id and type are always returned.
@param {Function} [callback] A callback to call with the response data (or error)
@returns {Request} | [
"Fetch",
"the",
"metadata",
"for",
"a",
"single",
"document"
]
| 5888e4d60cd6bdc3b656724bee2dd56b6adf32ec | https://github.com/lakenen/node-box-view/blob/5888e4d60cd6bdc3b656724bee2dd56b6adf32ec/index.js#L287-L320 | train |
|
lakenen/node-box-view | index.js | function (id, data, options, callback) {
var args = arguments,
r,
handler,
retry = false,
requestOptions = {
method: 'PUT',
headers: {
'content-type': 'application/json'
}
};
if (typeof options === 'function') {
callback = options;
} else {
options = extend({}, options);
retry = options.retry;
}
retry = (retry === true) && function () {
this.update.apply(this, args);
}.bind(this);
handler = createResponseHandler(callback, retry);
r = req(client.documentsURL + '/' + id, requestOptions, handler);
data = new Buffer(JSON.stringify(data));
r.setHeader('content-length', data.length);
r.end(data);
return r;
} | javascript | function (id, data, options, callback) {
var args = arguments,
r,
handler,
retry = false,
requestOptions = {
method: 'PUT',
headers: {
'content-type': 'application/json'
}
};
if (typeof options === 'function') {
callback = options;
} else {
options = extend({}, options);
retry = options.retry;
}
retry = (retry === true) && function () {
this.update.apply(this, args);
}.bind(this);
handler = createResponseHandler(callback, retry);
r = req(client.documentsURL + '/' + id, requestOptions, handler);
data = new Buffer(JSON.stringify(data));
r.setHeader('content-length', data.length);
r.end(data);
return r;
} | [
"function",
"(",
"id",
",",
"data",
",",
"options",
",",
"callback",
")",
"{",
"var",
"args",
"=",
"arguments",
",",
"r",
",",
"handler",
",",
"retry",
"=",
"false",
",",
"requestOptions",
"=",
"{",
"method",
":",
"'PUT'",
",",
"headers",
":",
"{",
"'content-type'",
":",
"'application/json'",
"}",
"}",
";",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
")",
"{",
"callback",
"=",
"options",
";",
"}",
"else",
"{",
"options",
"=",
"extend",
"(",
"{",
"}",
",",
"options",
")",
";",
"retry",
"=",
"options",
".",
"retry",
";",
"}",
"retry",
"=",
"(",
"retry",
"===",
"true",
")",
"&&",
"function",
"(",
")",
"{",
"this",
".",
"update",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
";",
"handler",
"=",
"createResponseHandler",
"(",
"callback",
",",
"retry",
")",
";",
"r",
"=",
"req",
"(",
"client",
".",
"documentsURL",
"+",
"'/'",
"+",
"id",
",",
"requestOptions",
",",
"handler",
")",
";",
"data",
"=",
"new",
"Buffer",
"(",
"JSON",
".",
"stringify",
"(",
"data",
")",
")",
";",
"r",
".",
"setHeader",
"(",
"'content-length'",
",",
"data",
".",
"length",
")",
";",
"r",
".",
"end",
"(",
"data",
")",
";",
"return",
"r",
";",
"}"
]
| Update the metadata for a single document
@param {String} id The document uuid
@param {Object} data The new metadata
@param {Object} [options] Update options
@param {boolean} [options.retry] Whether to retry the request after 'retry-after' seconds if the retry-after header is sent
@param {Function} [callback] A callback to call with the response data (or error)
@returns {Request} | [
"Update",
"the",
"metadata",
"for",
"a",
"single",
"document"
]
| 5888e4d60cd6bdc3b656724bee2dd56b6adf32ec | https://github.com/lakenen/node-box-view/blob/5888e4d60cd6bdc3b656724bee2dd56b6adf32ec/index.js#L331-L361 | train |
|
lakenen/node-box-view | index.js | function (id, options, callback) {
var args = arguments,
retry = false,
handler;
if (typeof options === 'function') {
callback = options;
} else {
options = extend({}, options);
retry = options.retry;
}
retry = (retry === true) && function () {
this.delete.apply(this, args);
}.bind(this);
handler = createResponseHandler(callback, [204], true, retry);
return req(client.documentsURL + '/' + id, { method: 'DELETE' }, handler);
} | javascript | function (id, options, callback) {
var args = arguments,
retry = false,
handler;
if (typeof options === 'function') {
callback = options;
} else {
options = extend({}, options);
retry = options.retry;
}
retry = (retry === true) && function () {
this.delete.apply(this, args);
}.bind(this);
handler = createResponseHandler(callback, [204], true, retry);
return req(client.documentsURL + '/' + id, { method: 'DELETE' }, handler);
} | [
"function",
"(",
"id",
",",
"options",
",",
"callback",
")",
"{",
"var",
"args",
"=",
"arguments",
",",
"retry",
"=",
"false",
",",
"handler",
";",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
")",
"{",
"callback",
"=",
"options",
";",
"}",
"else",
"{",
"options",
"=",
"extend",
"(",
"{",
"}",
",",
"options",
")",
";",
"retry",
"=",
"options",
".",
"retry",
";",
"}",
"retry",
"=",
"(",
"retry",
"===",
"true",
")",
"&&",
"function",
"(",
")",
"{",
"this",
".",
"delete",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
";",
"handler",
"=",
"createResponseHandler",
"(",
"callback",
",",
"[",
"204",
"]",
",",
"true",
",",
"retry",
")",
";",
"return",
"req",
"(",
"client",
".",
"documentsURL",
"+",
"'/'",
"+",
"id",
",",
"{",
"method",
":",
"'DELETE'",
"}",
",",
"handler",
")",
";",
"}"
]
| Delete a single document
@param {String} id The document uuid
@param {Object} [options] Delete options
@param {boolean} [options.retry] Whether to retry the request after 'retry-after' seconds if the retry-after header is sent
@param {Function} [callback] A callback to call with the response data (or error)
@returns {Request} | [
"Delete",
"a",
"single",
"document"
]
| 5888e4d60cd6bdc3b656724bee2dd56b6adf32ec | https://github.com/lakenen/node-box-view/blob/5888e4d60cd6bdc3b656724bee2dd56b6adf32ec/index.js#L371-L390 | train |
|
lakenen/node-box-view | index.js | function (file, options, callback) {
var args = arguments,
r,
param,
form,
handler,
params,
retry = false,
requestOptions = {
method: 'POST'
};
if (typeof file === 'string') {
file = fs.createReadStream(file);
}
if (typeof options === 'function') {
callback = options;
params = {};
} else {
options = extend({}, options);
params = extend({}, options.params);
retry = options.retry;
}
retry = (retry === true) && function () {
this.uploadFile.apply(this, args);
}.bind(this);
// filename is required for the form to work properly, so try to
// figure out a name...
if (!params.name) {
params.name = determineFilename(file);
}
// if the file is a stream, we cannot retry
if (retry && file.readable) {
throw new Error('Retry option is not supported for streams.');
}
handler = createResponseHandler(callback, [200, 202], retry);
form = new FormData();
for (param in params) {
if (params.hasOwnProperty(param)) {
form.append(param, params[param].toString());
}
}
form.append('file', file, { filename: params.name });
extend(true, requestOptions, {
headers: form.getHeaders()
});
r = req(client.documentsUploadURL, requestOptions, handler);
form.pipe(r);
return r;
} | javascript | function (file, options, callback) {
var args = arguments,
r,
param,
form,
handler,
params,
retry = false,
requestOptions = {
method: 'POST'
};
if (typeof file === 'string') {
file = fs.createReadStream(file);
}
if (typeof options === 'function') {
callback = options;
params = {};
} else {
options = extend({}, options);
params = extend({}, options.params);
retry = options.retry;
}
retry = (retry === true) && function () {
this.uploadFile.apply(this, args);
}.bind(this);
// filename is required for the form to work properly, so try to
// figure out a name...
if (!params.name) {
params.name = determineFilename(file);
}
// if the file is a stream, we cannot retry
if (retry && file.readable) {
throw new Error('Retry option is not supported for streams.');
}
handler = createResponseHandler(callback, [200, 202], retry);
form = new FormData();
for (param in params) {
if (params.hasOwnProperty(param)) {
form.append(param, params[param].toString());
}
}
form.append('file', file, { filename: params.name });
extend(true, requestOptions, {
headers: form.getHeaders()
});
r = req(client.documentsUploadURL, requestOptions, handler);
form.pipe(r);
return r;
} | [
"function",
"(",
"file",
",",
"options",
",",
"callback",
")",
"{",
"var",
"args",
"=",
"arguments",
",",
"r",
",",
"param",
",",
"form",
",",
"handler",
",",
"params",
",",
"retry",
"=",
"false",
",",
"requestOptions",
"=",
"{",
"method",
":",
"'POST'",
"}",
";",
"if",
"(",
"typeof",
"file",
"===",
"'string'",
")",
"{",
"file",
"=",
"fs",
".",
"createReadStream",
"(",
"file",
")",
";",
"}",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
")",
"{",
"callback",
"=",
"options",
";",
"params",
"=",
"{",
"}",
";",
"}",
"else",
"{",
"options",
"=",
"extend",
"(",
"{",
"}",
",",
"options",
")",
";",
"params",
"=",
"extend",
"(",
"{",
"}",
",",
"options",
".",
"params",
")",
";",
"retry",
"=",
"options",
".",
"retry",
";",
"}",
"retry",
"=",
"(",
"retry",
"===",
"true",
")",
"&&",
"function",
"(",
")",
"{",
"this",
".",
"uploadFile",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
";",
"if",
"(",
"!",
"params",
".",
"name",
")",
"{",
"params",
".",
"name",
"=",
"determineFilename",
"(",
"file",
")",
";",
"}",
"if",
"(",
"retry",
"&&",
"file",
".",
"readable",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Retry option is not supported for streams.'",
")",
";",
"}",
"handler",
"=",
"createResponseHandler",
"(",
"callback",
",",
"[",
"200",
",",
"202",
"]",
",",
"retry",
")",
";",
"form",
"=",
"new",
"FormData",
"(",
")",
";",
"for",
"(",
"param",
"in",
"params",
")",
"{",
"if",
"(",
"params",
".",
"hasOwnProperty",
"(",
"param",
")",
")",
"{",
"form",
".",
"append",
"(",
"param",
",",
"params",
"[",
"param",
"]",
".",
"toString",
"(",
")",
")",
";",
"}",
"}",
"form",
".",
"append",
"(",
"'file'",
",",
"file",
",",
"{",
"filename",
":",
"params",
".",
"name",
"}",
")",
";",
"extend",
"(",
"true",
",",
"requestOptions",
",",
"{",
"headers",
":",
"form",
".",
"getHeaders",
"(",
")",
"}",
")",
";",
"r",
"=",
"req",
"(",
"client",
".",
"documentsUploadURL",
",",
"requestOptions",
",",
"handler",
")",
";",
"form",
".",
"pipe",
"(",
"r",
")",
";",
"return",
"r",
";",
"}"
]
| Do a multipart upload from a file path or readable stream
@param {String|Stream|Buffer} file A path to a file to read, a readable stream, or a Buffer
@param {Object} [options] Upload options
@param {boolean} [options.retry] Whether to retry the request after 'retry-after' seconds if the retry-after header is sent
@param {Object} [options.params] Upload parameters
@param {String} [options.params.name] The name of the file
@param {String} [options.params.thumbnails] Comma-separated list of thumbnail dimensions of the format {width}x{height} e.g. 128×128,256×256 – width can be between 16 and 1024, height between 16 and 768
@param {Boolean} [options.params.non_svg] Whether to also create the non-svg version of the document
@param {Function} [callback] A callback to call with the response data (or error)
@returns {Request} | [
"Do",
"a",
"multipart",
"upload",
"from",
"a",
"file",
"path",
"or",
"readable",
"stream"
]
| 5888e4d60cd6bdc3b656724bee2dd56b6adf32ec | https://github.com/lakenen/node-box-view/blob/5888e4d60cd6bdc3b656724bee2dd56b6adf32ec/index.js#L404-L461 | train |
|
lakenen/node-box-view | index.js | function (url, options, callback) {
var args = arguments,
r,
handler,
params,
data = '',
retry = false,
requestOptions = {
method: 'POST',
headers: {
'content-type': 'application/json'
}
};
if (typeof options === 'function') {
callback = options;
params = {};
} else {
options = extend({}, options);
params = extend({}, options.params);
retry = options.retry;
}
retry = (retry === true) && function () {
this.uploadURL.apply(this, args);
}.bind(this);
if (!params.name) {
params.name = path.basename(url);
}
params.url = url;
handler = createResponseHandler(callback, [200, 202], retry);
r = req(client.documentsURL, requestOptions, handler);
data = new Buffer(JSON.stringify(params));
r.setHeader('content-length', data.length);
r.end(data);
return r;
} | javascript | function (url, options, callback) {
var args = arguments,
r,
handler,
params,
data = '',
retry = false,
requestOptions = {
method: 'POST',
headers: {
'content-type': 'application/json'
}
};
if (typeof options === 'function') {
callback = options;
params = {};
} else {
options = extend({}, options);
params = extend({}, options.params);
retry = options.retry;
}
retry = (retry === true) && function () {
this.uploadURL.apply(this, args);
}.bind(this);
if (!params.name) {
params.name = path.basename(url);
}
params.url = url;
handler = createResponseHandler(callback, [200, 202], retry);
r = req(client.documentsURL, requestOptions, handler);
data = new Buffer(JSON.stringify(params));
r.setHeader('content-length', data.length);
r.end(data);
return r;
} | [
"function",
"(",
"url",
",",
"options",
",",
"callback",
")",
"{",
"var",
"args",
"=",
"arguments",
",",
"r",
",",
"handler",
",",
"params",
",",
"data",
"=",
"''",
",",
"retry",
"=",
"false",
",",
"requestOptions",
"=",
"{",
"method",
":",
"'POST'",
",",
"headers",
":",
"{",
"'content-type'",
":",
"'application/json'",
"}",
"}",
";",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
")",
"{",
"callback",
"=",
"options",
";",
"params",
"=",
"{",
"}",
";",
"}",
"else",
"{",
"options",
"=",
"extend",
"(",
"{",
"}",
",",
"options",
")",
";",
"params",
"=",
"extend",
"(",
"{",
"}",
",",
"options",
".",
"params",
")",
";",
"retry",
"=",
"options",
".",
"retry",
";",
"}",
"retry",
"=",
"(",
"retry",
"===",
"true",
")",
"&&",
"function",
"(",
")",
"{",
"this",
".",
"uploadURL",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
";",
"if",
"(",
"!",
"params",
".",
"name",
")",
"{",
"params",
".",
"name",
"=",
"path",
".",
"basename",
"(",
"url",
")",
";",
"}",
"params",
".",
"url",
"=",
"url",
";",
"handler",
"=",
"createResponseHandler",
"(",
"callback",
",",
"[",
"200",
",",
"202",
"]",
",",
"retry",
")",
";",
"r",
"=",
"req",
"(",
"client",
".",
"documentsURL",
",",
"requestOptions",
",",
"handler",
")",
";",
"data",
"=",
"new",
"Buffer",
"(",
"JSON",
".",
"stringify",
"(",
"params",
")",
")",
";",
"r",
".",
"setHeader",
"(",
"'content-length'",
",",
"data",
".",
"length",
")",
";",
"r",
".",
"end",
"(",
"data",
")",
";",
"return",
"r",
";",
"}"
]
| Do a URL upload of a file
@param {String} url A URL to a publicly-accessible file to upload
@param {Object} [options] Upload options
@param {boolean} [options.retry] Whether to retry the request after 'retry-after' seconds if the retry-after header is sent
@param {Object} [options.params] Upload parameters
@param {String} [options.params.name] The name of the file
@param {String} [options.params.thumbnails] Comma-separated list of thumbnail dimensions of the format {width}x{height} e.g. 128×128,256×256 – width can be between 16 and 1024, height between 16 and 768
@param {Boolean} [options.params.non_svg] Whether to also create the non-svg version of the document
@param {Function} [callback] A callback to call with the response data (or error)
@returns {Request} | [
"Do",
"a",
"URL",
"upload",
"of",
"a",
"file"
]
| 5888e4d60cd6bdc3b656724bee2dd56b6adf32ec | https://github.com/lakenen/node-box-view/blob/5888e4d60cd6bdc3b656724bee2dd56b6adf32ec/index.js#L475-L516 | train |
|
lakenen/node-box-view | index.js | function (id, width, height, options, callback) {
var args = arguments,
url,
query,
retry = false,
params,
handler;
if (typeof options === 'function') {
callback = options;
} else {
options = extend({}, options);
retry = options.retry;
}
retry = (retry === true) && function () {
this.getThumbnail.apply(this, args);
}.bind(this);
params = {
width: width,
height: height
};
handler = createResponseHandler(callback, [200, 202], true, retry);
query = querystring.stringify(params);
url = client.documentsURL + '/' + id + '/thumbnail?' + query;
return req(url, handler);
} | javascript | function (id, width, height, options, callback) {
var args = arguments,
url,
query,
retry = false,
params,
handler;
if (typeof options === 'function') {
callback = options;
} else {
options = extend({}, options);
retry = options.retry;
}
retry = (retry === true) && function () {
this.getThumbnail.apply(this, args);
}.bind(this);
params = {
width: width,
height: height
};
handler = createResponseHandler(callback, [200, 202], true, retry);
query = querystring.stringify(params);
url = client.documentsURL + '/' + id + '/thumbnail?' + query;
return req(url, handler);
} | [
"function",
"(",
"id",
",",
"width",
",",
"height",
",",
"options",
",",
"callback",
")",
"{",
"var",
"args",
"=",
"arguments",
",",
"url",
",",
"query",
",",
"retry",
"=",
"false",
",",
"params",
",",
"handler",
";",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
")",
"{",
"callback",
"=",
"options",
";",
"}",
"else",
"{",
"options",
"=",
"extend",
"(",
"{",
"}",
",",
"options",
")",
";",
"retry",
"=",
"options",
".",
"retry",
";",
"}",
"retry",
"=",
"(",
"retry",
"===",
"true",
")",
"&&",
"function",
"(",
")",
"{",
"this",
".",
"getThumbnail",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
";",
"params",
"=",
"{",
"width",
":",
"width",
",",
"height",
":",
"height",
"}",
";",
"handler",
"=",
"createResponseHandler",
"(",
"callback",
",",
"[",
"200",
",",
"202",
"]",
",",
"true",
",",
"retry",
")",
";",
"query",
"=",
"querystring",
".",
"stringify",
"(",
"params",
")",
";",
"url",
"=",
"client",
".",
"documentsURL",
"+",
"'/'",
"+",
"id",
"+",
"'/thumbnail?'",
"+",
"query",
";",
"return",
"req",
"(",
"url",
",",
"handler",
")",
";",
"}"
]
| Fetches a thumbnail for the given document id
@param {string} id The document uuid
@param {int} width The thumbnail width
@param {int} height The thumbnail height
@param {Object} [options] Content options
@param {boolean} [options.retry] Whether to retry the request after 'retry-after' seconds if the retry-after header is sent
@param {Function} [callback] A callback to call with the response (or error)
@returns {Request} | [
"Fetches",
"a",
"thumbnail",
"for",
"the",
"given",
"document",
"id"
]
| 5888e4d60cd6bdc3b656724bee2dd56b6adf32ec | https://github.com/lakenen/node-box-view/blob/5888e4d60cd6bdc3b656724bee2dd56b6adf32ec/index.js#L568-L597 | train |
|
nutella-framework/nutella_lib.js | src/run_net_bin.js | function(main_nutella, net_sub_module) {
// Store a reference to the main module
this.nutella = main_nutella;
this.net = net_sub_module;
this.file_mngr_url = 'http://' + main_nutella.mqtt_client.getHost() + ':57882';
} | javascript | function(main_nutella, net_sub_module) {
// Store a reference to the main module
this.nutella = main_nutella;
this.net = net_sub_module;
this.file_mngr_url = 'http://' + main_nutella.mqtt_client.getHost() + ':57882';
} | [
"function",
"(",
"main_nutella",
",",
"net_sub_module",
")",
"{",
"this",
".",
"nutella",
"=",
"main_nutella",
";",
"this",
".",
"net",
"=",
"net_sub_module",
";",
"this",
".",
"file_mngr_url",
"=",
"'http://'",
"+",
"main_nutella",
".",
"mqtt_client",
".",
"getHost",
"(",
")",
"+",
"':57882'",
";",
"}"
]
| Run-level binary network APIs for nutella
@param main_nutella
@constructor | [
"Run",
"-",
"level",
"binary",
"network",
"APIs",
"for",
"nutella"
]
| b3a3406a407e2a1ada6edcc503b70991f9cb249b | https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/run_net_bin.js#L14-L19 | train |
|
nutella-framework/nutella_lib.js | src/run_net_bin.js | getFileExtension | function getFileExtension(file) {
return file.name.substring(file.name.lastIndexOf('.')+1, file.name.length).toLowerCase()
} | javascript | function getFileExtension(file) {
return file.name.substring(file.name.lastIndexOf('.')+1, file.name.length).toLowerCase()
} | [
"function",
"getFileExtension",
"(",
"file",
")",
"{",
"return",
"file",
".",
"name",
".",
"substring",
"(",
"file",
".",
"name",
".",
"lastIndexOf",
"(",
"'.'",
")",
"+",
"1",
",",
"file",
".",
"name",
".",
"length",
")",
".",
"toLowerCase",
"(",
")",
"}"
]
| Helper function Extracts the extension from a file object | [
"Helper",
"function",
"Extracts",
"the",
"extension",
"from",
"a",
"file",
"object"
]
| b3a3406a407e2a1ada6edcc503b70991f9cb249b | https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/run_net_bin.js#L57-L59 | train |
nutella-framework/nutella_lib.js | src/run_net_bin.js | isAlreadyUploaded | function isAlreadyUploaded(file_mngr_url, filename, file_exists_cb, file_absent_cb) {
var req = new XMLHttpRequest();
req.open("GET", file_mngr_url + "/test/" + filename);
req.onload = function(e) {
var url = JSON.parse(req.response).url;
if (url === undefined)
file_absent_cb();
else
file_exists_cb(url);
};
req.send();
} | javascript | function isAlreadyUploaded(file_mngr_url, filename, file_exists_cb, file_absent_cb) {
var req = new XMLHttpRequest();
req.open("GET", file_mngr_url + "/test/" + filename);
req.onload = function(e) {
var url = JSON.parse(req.response).url;
if (url === undefined)
file_absent_cb();
else
file_exists_cb(url);
};
req.send();
} | [
"function",
"isAlreadyUploaded",
"(",
"file_mngr_url",
",",
"filename",
",",
"file_exists_cb",
",",
"file_absent_cb",
")",
"{",
"var",
"req",
"=",
"new",
"XMLHttpRequest",
"(",
")",
";",
"req",
".",
"open",
"(",
"\"GET\"",
",",
"file_mngr_url",
"+",
"\"/test/\"",
"+",
"filename",
")",
";",
"req",
".",
"onload",
"=",
"function",
"(",
"e",
")",
"{",
"var",
"url",
"=",
"JSON",
".",
"parse",
"(",
"req",
".",
"response",
")",
".",
"url",
";",
"if",
"(",
"url",
"===",
"undefined",
")",
"file_absent_cb",
"(",
")",
";",
"else",
"file_exists_cb",
"(",
"url",
")",
";",
"}",
";",
"req",
".",
"send",
"(",
")",
";",
"}"
]
| Helper function This function checks if a particular filename already exists. If so it executes the first callback that is passed, otherwise the second one | [
"Helper",
"function",
"This",
"function",
"checks",
"if",
"a",
"particular",
"filename",
"already",
"exists",
".",
"If",
"so",
"it",
"executes",
"the",
"first",
"callback",
"that",
"is",
"passed",
"otherwise",
"the",
"second",
"one"
]
| b3a3406a407e2a1ada6edcc503b70991f9cb249b | https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/run_net_bin.js#L68-L79 | train |
nutella-framework/nutella_lib.js | src/run_net_bin.js | upload | function upload(file_mngr_url, file, filename, success, error) {
// Assemble data
var fd = new FormData();
fd.append("filename", filename);
fd.append("file", file);
var req = new XMLHttpRequest();
req.open("POST", file_mngr_url + "/upload");
req.onload = function(e) {
var url = JSON.parse(req.response).url;
if (url === undefined)
error();
else
success(url);
};
req.send(fd);
} | javascript | function upload(file_mngr_url, file, filename, success, error) {
// Assemble data
var fd = new FormData();
fd.append("filename", filename);
fd.append("file", file);
var req = new XMLHttpRequest();
req.open("POST", file_mngr_url + "/upload");
req.onload = function(e) {
var url = JSON.parse(req.response).url;
if (url === undefined)
error();
else
success(url);
};
req.send(fd);
} | [
"function",
"upload",
"(",
"file_mngr_url",
",",
"file",
",",
"filename",
",",
"success",
",",
"error",
")",
"{",
"var",
"fd",
"=",
"new",
"FormData",
"(",
")",
";",
"fd",
".",
"append",
"(",
"\"filename\"",
",",
"filename",
")",
";",
"fd",
".",
"append",
"(",
"\"file\"",
",",
"file",
")",
";",
"var",
"req",
"=",
"new",
"XMLHttpRequest",
"(",
")",
";",
"req",
".",
"open",
"(",
"\"POST\"",
",",
"file_mngr_url",
"+",
"\"/upload\"",
")",
";",
"req",
".",
"onload",
"=",
"function",
"(",
"e",
")",
"{",
"var",
"url",
"=",
"JSON",
".",
"parse",
"(",
"req",
".",
"response",
")",
".",
"url",
";",
"if",
"(",
"url",
"===",
"undefined",
")",
"error",
"(",
")",
";",
"else",
"success",
"(",
"url",
")",
";",
"}",
";",
"req",
".",
"send",
"(",
"fd",
")",
";",
"}"
]
| Helper function This function uploads a file with a certain file name. If the upload is successful the first callback is executed, otherwise the second one is. | [
"Helper",
"function",
"This",
"function",
"uploads",
"a",
"file",
"with",
"a",
"certain",
"file",
"name",
".",
"If",
"the",
"upload",
"is",
"successful",
"the",
"first",
"callback",
"is",
"executed",
"otherwise",
"the",
"second",
"one",
"is",
"."
]
| b3a3406a407e2a1ada6edcc503b70991f9cb249b | https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/run_net_bin.js#L87-L102 | train |
Microsoft/vscode | build/lib/treeshaking.js | discoverAndReadFiles | function discoverAndReadFiles(options) {
const FILES = {};
const in_queue = Object.create(null);
const queue = [];
const enqueue = (moduleId) => {
if (in_queue[moduleId]) {
return;
}
in_queue[moduleId] = true;
queue.push(moduleId);
};
options.entryPoints.forEach((entryPoint) => enqueue(entryPoint));
while (queue.length > 0) {
const moduleId = queue.shift();
const dts_filename = path.join(options.sourcesRoot, moduleId + '.d.ts');
if (fs.existsSync(dts_filename)) {
const dts_filecontents = fs.readFileSync(dts_filename).toString();
FILES[`${moduleId}.d.ts`] = dts_filecontents;
continue;
}
const js_filename = path.join(options.sourcesRoot, moduleId + '.js');
if (fs.existsSync(js_filename)) {
// This is an import for a .js file, so ignore it...
continue;
}
let ts_filename;
if (options.redirects[moduleId]) {
ts_filename = path.join(options.sourcesRoot, options.redirects[moduleId] + '.ts');
}
else {
ts_filename = path.join(options.sourcesRoot, moduleId + '.ts');
}
const ts_filecontents = fs.readFileSync(ts_filename).toString();
const info = ts.preProcessFile(ts_filecontents);
for (let i = info.importedFiles.length - 1; i >= 0; i--) {
const importedFileName = info.importedFiles[i].fileName;
if (options.importIgnorePattern.test(importedFileName)) {
// Ignore vs/css! imports
continue;
}
let importedModuleId = importedFileName;
if (/(^\.\/)|(^\.\.\/)/.test(importedModuleId)) {
importedModuleId = path.join(path.dirname(moduleId), importedModuleId);
}
enqueue(importedModuleId);
}
FILES[`${moduleId}.ts`] = ts_filecontents;
}
return FILES;
} | javascript | function discoverAndReadFiles(options) {
const FILES = {};
const in_queue = Object.create(null);
const queue = [];
const enqueue = (moduleId) => {
if (in_queue[moduleId]) {
return;
}
in_queue[moduleId] = true;
queue.push(moduleId);
};
options.entryPoints.forEach((entryPoint) => enqueue(entryPoint));
while (queue.length > 0) {
const moduleId = queue.shift();
const dts_filename = path.join(options.sourcesRoot, moduleId + '.d.ts');
if (fs.existsSync(dts_filename)) {
const dts_filecontents = fs.readFileSync(dts_filename).toString();
FILES[`${moduleId}.d.ts`] = dts_filecontents;
continue;
}
const js_filename = path.join(options.sourcesRoot, moduleId + '.js');
if (fs.existsSync(js_filename)) {
// This is an import for a .js file, so ignore it...
continue;
}
let ts_filename;
if (options.redirects[moduleId]) {
ts_filename = path.join(options.sourcesRoot, options.redirects[moduleId] + '.ts');
}
else {
ts_filename = path.join(options.sourcesRoot, moduleId + '.ts');
}
const ts_filecontents = fs.readFileSync(ts_filename).toString();
const info = ts.preProcessFile(ts_filecontents);
for (let i = info.importedFiles.length - 1; i >= 0; i--) {
const importedFileName = info.importedFiles[i].fileName;
if (options.importIgnorePattern.test(importedFileName)) {
// Ignore vs/css! imports
continue;
}
let importedModuleId = importedFileName;
if (/(^\.\/)|(^\.\.\/)/.test(importedModuleId)) {
importedModuleId = path.join(path.dirname(moduleId), importedModuleId);
}
enqueue(importedModuleId);
}
FILES[`${moduleId}.ts`] = ts_filecontents;
}
return FILES;
} | [
"function",
"discoverAndReadFiles",
"(",
"options",
")",
"{",
"const",
"FILES",
"=",
"{",
"}",
";",
"const",
"in_queue",
"=",
"Object",
".",
"create",
"(",
"null",
")",
";",
"const",
"queue",
"=",
"[",
"]",
";",
"const",
"enqueue",
"=",
"(",
"moduleId",
")",
"=>",
"{",
"if",
"(",
"in_queue",
"[",
"moduleId",
"]",
")",
"{",
"return",
";",
"}",
"in_queue",
"[",
"moduleId",
"]",
"=",
"true",
";",
"queue",
".",
"push",
"(",
"moduleId",
")",
";",
"}",
";",
"options",
".",
"entryPoints",
".",
"forEach",
"(",
"(",
"entryPoint",
")",
"=>",
"enqueue",
"(",
"entryPoint",
")",
")",
";",
"while",
"(",
"queue",
".",
"length",
">",
"0",
")",
"{",
"const",
"moduleId",
"=",
"queue",
".",
"shift",
"(",
")",
";",
"const",
"dts_filename",
"=",
"path",
".",
"join",
"(",
"options",
".",
"sourcesRoot",
",",
"moduleId",
"+",
"'.d.ts'",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"dts_filename",
")",
")",
"{",
"const",
"dts_filecontents",
"=",
"fs",
".",
"readFileSync",
"(",
"dts_filename",
")",
".",
"toString",
"(",
")",
";",
"FILES",
"[",
"`",
"${",
"moduleId",
"}",
"`",
"]",
"=",
"dts_filecontents",
";",
"continue",
";",
"}",
"const",
"js_filename",
"=",
"path",
".",
"join",
"(",
"options",
".",
"sourcesRoot",
",",
"moduleId",
"+",
"'.js'",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"js_filename",
")",
")",
"{",
"continue",
";",
"}",
"let",
"ts_filename",
";",
"if",
"(",
"options",
".",
"redirects",
"[",
"moduleId",
"]",
")",
"{",
"ts_filename",
"=",
"path",
".",
"join",
"(",
"options",
".",
"sourcesRoot",
",",
"options",
".",
"redirects",
"[",
"moduleId",
"]",
"+",
"'.ts'",
")",
";",
"}",
"else",
"{",
"ts_filename",
"=",
"path",
".",
"join",
"(",
"options",
".",
"sourcesRoot",
",",
"moduleId",
"+",
"'.ts'",
")",
";",
"}",
"const",
"ts_filecontents",
"=",
"fs",
".",
"readFileSync",
"(",
"ts_filename",
")",
".",
"toString",
"(",
")",
";",
"const",
"info",
"=",
"ts",
".",
"preProcessFile",
"(",
"ts_filecontents",
")",
";",
"for",
"(",
"let",
"i",
"=",
"info",
".",
"importedFiles",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"const",
"importedFileName",
"=",
"info",
".",
"importedFiles",
"[",
"i",
"]",
".",
"fileName",
";",
"if",
"(",
"options",
".",
"importIgnorePattern",
".",
"test",
"(",
"importedFileName",
")",
")",
"{",
"continue",
";",
"}",
"let",
"importedModuleId",
"=",
"importedFileName",
";",
"if",
"(",
"/",
"(^\\.\\/)|(^\\.\\.\\/)",
"/",
".",
"test",
"(",
"importedModuleId",
")",
")",
"{",
"importedModuleId",
"=",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"moduleId",
")",
",",
"importedModuleId",
")",
";",
"}",
"enqueue",
"(",
"importedModuleId",
")",
";",
"}",
"FILES",
"[",
"`",
"${",
"moduleId",
"}",
"`",
"]",
"=",
"ts_filecontents",
";",
"}",
"return",
"FILES",
";",
"}"
]
| Read imports and follow them until all files have been handled | [
"Read",
"imports",
"and",
"follow",
"them",
"until",
"all",
"files",
"have",
"been",
"handled"
]
| 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/lib/treeshaking.js#L79-L128 | train |
Microsoft/vscode | build/lib/watch/index.js | handleDeletions | function handleDeletions() {
return es.mapSync(f => {
if (/\.ts$/.test(f.relative) && !f.contents) {
f.contents = Buffer.from('');
f.stat = { mtime: new Date() };
}
return f;
});
} | javascript | function handleDeletions() {
return es.mapSync(f => {
if (/\.ts$/.test(f.relative) && !f.contents) {
f.contents = Buffer.from('');
f.stat = { mtime: new Date() };
}
return f;
});
} | [
"function",
"handleDeletions",
"(",
")",
"{",
"return",
"es",
".",
"mapSync",
"(",
"f",
"=>",
"{",
"if",
"(",
"/",
"\\.ts$",
"/",
".",
"test",
"(",
"f",
".",
"relative",
")",
"&&",
"!",
"f",
".",
"contents",
")",
"{",
"f",
".",
"contents",
"=",
"Buffer",
".",
"from",
"(",
"''",
")",
";",
"f",
".",
"stat",
"=",
"{",
"mtime",
":",
"new",
"Date",
"(",
")",
"}",
";",
"}",
"return",
"f",
";",
"}",
")",
";",
"}"
]
| Ugly hack for gulp-tsb | [
"Ugly",
"hack",
"for",
"gulp",
"-",
"tsb"
]
| 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/lib/watch/index.js#L9-L18 | train |
Microsoft/vscode | build/lib/optimize.js | uglifyWithCopyrights | function uglifyWithCopyrights() {
const preserveComments = (f) => {
return (_node, comment) => {
const text = comment.value;
const type = comment.type;
if (/@minifier_do_not_preserve/.test(text)) {
return false;
}
const isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);
if (isOurCopyright) {
if (f.__hasOurCopyright) {
return false;
}
f.__hasOurCopyright = true;
return true;
}
if ('comment2' === type) {
// check for /*!. Note that text doesn't contain leading /*
return (text.length > 0 && text[0] === '!') || /@preserve|license|@cc_on|copyright/i.test(text);
}
else if ('comment1' === type) {
return /license|copyright/i.test(text);
}
return false;
};
};
const minify = composer(uglifyes);
const input = es.through();
const output = input
.pipe(flatmap((stream, f) => {
return stream.pipe(minify({
output: {
comments: preserveComments(f),
max_line_len: 1024
}
}));
}));
return es.duplex(input, output);
} | javascript | function uglifyWithCopyrights() {
const preserveComments = (f) => {
return (_node, comment) => {
const text = comment.value;
const type = comment.type;
if (/@minifier_do_not_preserve/.test(text)) {
return false;
}
const isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);
if (isOurCopyright) {
if (f.__hasOurCopyright) {
return false;
}
f.__hasOurCopyright = true;
return true;
}
if ('comment2' === type) {
// check for /*!. Note that text doesn't contain leading /*
return (text.length > 0 && text[0] === '!') || /@preserve|license|@cc_on|copyright/i.test(text);
}
else if ('comment1' === type) {
return /license|copyright/i.test(text);
}
return false;
};
};
const minify = composer(uglifyes);
const input = es.through();
const output = input
.pipe(flatmap((stream, f) => {
return stream.pipe(minify({
output: {
comments: preserveComments(f),
max_line_len: 1024
}
}));
}));
return es.duplex(input, output);
} | [
"function",
"uglifyWithCopyrights",
"(",
")",
"{",
"const",
"preserveComments",
"=",
"(",
"f",
")",
"=>",
"{",
"return",
"(",
"_node",
",",
"comment",
")",
"=>",
"{",
"const",
"text",
"=",
"comment",
".",
"value",
";",
"const",
"type",
"=",
"comment",
".",
"type",
";",
"if",
"(",
"/",
"@minifier_do_not_preserve",
"/",
".",
"test",
"(",
"text",
")",
")",
"{",
"return",
"false",
";",
"}",
"const",
"isOurCopyright",
"=",
"IS_OUR_COPYRIGHT_REGEXP",
".",
"test",
"(",
"text",
")",
";",
"if",
"(",
"isOurCopyright",
")",
"{",
"if",
"(",
"f",
".",
"__hasOurCopyright",
")",
"{",
"return",
"false",
";",
"}",
"f",
".",
"__hasOurCopyright",
"=",
"true",
";",
"return",
"true",
";",
"}",
"if",
"(",
"'comment2'",
"===",
"type",
")",
"{",
"return",
"(",
"text",
".",
"length",
">",
"0",
"&&",
"text",
"[",
"0",
"]",
"===",
"'!'",
")",
"||",
"/",
"@preserve|license|@cc_on|copyright",
"/",
"i",
".",
"test",
"(",
"text",
")",
";",
"}",
"else",
"if",
"(",
"'comment1'",
"===",
"type",
")",
"{",
"return",
"/",
"license|copyright",
"/",
"i",
".",
"test",
"(",
"text",
")",
";",
"}",
"return",
"false",
";",
"}",
";",
"}",
";",
"const",
"minify",
"=",
"composer",
"(",
"uglifyes",
")",
";",
"const",
"input",
"=",
"es",
".",
"through",
"(",
")",
";",
"const",
"output",
"=",
"input",
".",
"pipe",
"(",
"flatmap",
"(",
"(",
"stream",
",",
"f",
")",
"=>",
"{",
"return",
"stream",
".",
"pipe",
"(",
"minify",
"(",
"{",
"output",
":",
"{",
"comments",
":",
"preserveComments",
"(",
"f",
")",
",",
"max_line_len",
":",
"1024",
"}",
"}",
")",
")",
";",
"}",
")",
")",
";",
"return",
"es",
".",
"duplex",
"(",
"input",
",",
"output",
")",
";",
"}"
]
| Wrap around uglify and allow the preserveComments function
to have a file "context" to include our copyright only once per file. | [
"Wrap",
"around",
"uglify",
"and",
"allow",
"the",
"preserveComments",
"function",
"to",
"have",
"a",
"file",
"context",
"to",
"include",
"our",
"copyright",
"only",
"once",
"per",
"file",
"."
]
| 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/lib/optimize.js#L169-L207 | train |
Microsoft/vscode | build/lib/extensions.js | sequence | function sequence(streamProviders) {
const result = es.through();
function pop() {
if (streamProviders.length === 0) {
result.emit('end');
}
else {
const fn = streamProviders.shift();
fn()
.on('end', function () { setTimeout(pop, 0); })
.pipe(result, { end: false });
}
}
pop();
return result;
} | javascript | function sequence(streamProviders) {
const result = es.through();
function pop() {
if (streamProviders.length === 0) {
result.emit('end');
}
else {
const fn = streamProviders.shift();
fn()
.on('end', function () { setTimeout(pop, 0); })
.pipe(result, { end: false });
}
}
pop();
return result;
} | [
"function",
"sequence",
"(",
"streamProviders",
")",
"{",
"const",
"result",
"=",
"es",
".",
"through",
"(",
")",
";",
"function",
"pop",
"(",
")",
"{",
"if",
"(",
"streamProviders",
".",
"length",
"===",
"0",
")",
"{",
"result",
".",
"emit",
"(",
"'end'",
")",
";",
"}",
"else",
"{",
"const",
"fn",
"=",
"streamProviders",
".",
"shift",
"(",
")",
";",
"fn",
"(",
")",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"setTimeout",
"(",
"pop",
",",
"0",
")",
";",
"}",
")",
".",
"pipe",
"(",
"result",
",",
"{",
"end",
":",
"false",
"}",
")",
";",
"}",
"}",
"pop",
"(",
")",
";",
"return",
"result",
";",
"}"
]
| We're doing way too much stuff at once, with webpack et al. So much stuff
that while downloading extensions from the marketplace, node js doesn't get enough
stack frames to complete the download in under 2 minutes, at which point the
marketplace server cuts off the http request. So, we sequentialize the extensino tasks. | [
"We",
"re",
"doing",
"way",
"too",
"much",
"stuff",
"at",
"once",
"with",
"webpack",
"et",
"al",
".",
"So",
"much",
"stuff",
"that",
"while",
"downloading",
"extensions",
"from",
"the",
"marketplace",
"node",
"js",
"doesn",
"t",
"get",
"enough",
"stack",
"frames",
"to",
"complete",
"the",
"download",
"in",
"under",
"2",
"minutes",
"at",
"which",
"point",
"the",
"marketplace",
"server",
"cuts",
"off",
"the",
"http",
"request",
".",
"So",
"we",
"sequentialize",
"the",
"extensino",
"tasks",
"."
]
| 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/lib/extensions.js#L194-L209 | train |
Microsoft/vscode | src/vs/loader.js | function (what) {
moduleManager.getRecorder().record(33 /* NodeBeginNativeRequire */, what);
try {
return _nodeRequire_1(what);
}
finally {
moduleManager.getRecorder().record(34 /* NodeEndNativeRequire */, what);
}
} | javascript | function (what) {
moduleManager.getRecorder().record(33 /* NodeBeginNativeRequire */, what);
try {
return _nodeRequire_1(what);
}
finally {
moduleManager.getRecorder().record(34 /* NodeEndNativeRequire */, what);
}
} | [
"function",
"(",
"what",
")",
"{",
"moduleManager",
".",
"getRecorder",
"(",
")",
".",
"record",
"(",
"33",
",",
"what",
")",
";",
"try",
"{",
"return",
"_nodeRequire_1",
"(",
"what",
")",
";",
"}",
"finally",
"{",
"moduleManager",
".",
"getRecorder",
"(",
")",
".",
"record",
"(",
"34",
",",
"what",
")",
";",
"}",
"}"
]
| re-expose node's require function | [
"re",
"-",
"expose",
"node",
"s",
"require",
"function"
]
| 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/src/vs/loader.js#L1705-L1713 | train |
|
Microsoft/vscode | build/lib/nls.js | nls | function nls() {
const input = event_stream_1.through();
const output = input.pipe(event_stream_1.through(function (f) {
if (!f.sourceMap) {
return this.emit('error', new Error(`File ${f.relative} does not have sourcemaps.`));
}
let source = f.sourceMap.sources[0];
if (!source) {
return this.emit('error', new Error(`File ${f.relative} does not have a source in the source map.`));
}
const root = f.sourceMap.sourceRoot;
if (root) {
source = path.join(root, source);
}
const typescript = f.sourceMap.sourcesContent[0];
if (!typescript) {
return this.emit('error', new Error(`File ${f.relative} does not have the original content in the source map.`));
}
nls.patchFiles(f, typescript).forEach(f => this.emit('data', f));
}));
return event_stream_1.duplex(input, output);
} | javascript | function nls() {
const input = event_stream_1.through();
const output = input.pipe(event_stream_1.through(function (f) {
if (!f.sourceMap) {
return this.emit('error', new Error(`File ${f.relative} does not have sourcemaps.`));
}
let source = f.sourceMap.sources[0];
if (!source) {
return this.emit('error', new Error(`File ${f.relative} does not have a source in the source map.`));
}
const root = f.sourceMap.sourceRoot;
if (root) {
source = path.join(root, source);
}
const typescript = f.sourceMap.sourcesContent[0];
if (!typescript) {
return this.emit('error', new Error(`File ${f.relative} does not have the original content in the source map.`));
}
nls.patchFiles(f, typescript).forEach(f => this.emit('data', f));
}));
return event_stream_1.duplex(input, output);
} | [
"function",
"nls",
"(",
")",
"{",
"const",
"input",
"=",
"event_stream_1",
".",
"through",
"(",
")",
";",
"const",
"output",
"=",
"input",
".",
"pipe",
"(",
"event_stream_1",
".",
"through",
"(",
"function",
"(",
"f",
")",
"{",
"if",
"(",
"!",
"f",
".",
"sourceMap",
")",
"{",
"return",
"this",
".",
"emit",
"(",
"'error'",
",",
"new",
"Error",
"(",
"`",
"${",
"f",
".",
"relative",
"}",
"`",
")",
")",
";",
"}",
"let",
"source",
"=",
"f",
".",
"sourceMap",
".",
"sources",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"source",
")",
"{",
"return",
"this",
".",
"emit",
"(",
"'error'",
",",
"new",
"Error",
"(",
"`",
"${",
"f",
".",
"relative",
"}",
"`",
")",
")",
";",
"}",
"const",
"root",
"=",
"f",
".",
"sourceMap",
".",
"sourceRoot",
";",
"if",
"(",
"root",
")",
"{",
"source",
"=",
"path",
".",
"join",
"(",
"root",
",",
"source",
")",
";",
"}",
"const",
"typescript",
"=",
"f",
".",
"sourceMap",
".",
"sourcesContent",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"typescript",
")",
"{",
"return",
"this",
".",
"emit",
"(",
"'error'",
",",
"new",
"Error",
"(",
"`",
"${",
"f",
".",
"relative",
"}",
"`",
")",
")",
";",
"}",
"nls",
".",
"patchFiles",
"(",
"f",
",",
"typescript",
")",
".",
"forEach",
"(",
"f",
"=>",
"this",
".",
"emit",
"(",
"'data'",
",",
"f",
")",
")",
";",
"}",
")",
")",
";",
"return",
"event_stream_1",
".",
"duplex",
"(",
"input",
",",
"output",
")",
";",
"}"
]
| Returns a stream containing the patched JavaScript and source maps. | [
"Returns",
"a",
"stream",
"containing",
"the",
"patched",
"JavaScript",
"and",
"source",
"maps",
"."
]
| 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/lib/nls.js#L54-L75 | train |
Microsoft/vscode | build/lib/bundle.js | bundle | function bundle(entryPoints, config, callback) {
const entryPointsMap = {};
entryPoints.forEach((module) => {
entryPointsMap[module.name] = module;
});
const allMentionedModulesMap = {};
entryPoints.forEach((module) => {
allMentionedModulesMap[module.name] = true;
(module.include || []).forEach(function (includedModule) {
allMentionedModulesMap[includedModule] = true;
});
(module.exclude || []).forEach(function (excludedModule) {
allMentionedModulesMap[excludedModule] = true;
});
});
const code = require('fs').readFileSync(path.join(__dirname, '../../src/vs/loader.js'));
const r = vm.runInThisContext('(function(require, module, exports) { ' + code + '\n});');
const loaderModule = { exports: {} };
r.call({}, require, loaderModule, loaderModule.exports);
const loader = loaderModule.exports;
config.isBuild = true;
config.paths = config.paths || {};
if (!config.paths['vs/nls']) {
config.paths['vs/nls'] = 'out-build/vs/nls.build';
}
if (!config.paths['vs/css']) {
config.paths['vs/css'] = 'out-build/vs/css.build';
}
loader.config(config);
loader(['require'], (localRequire) => {
const resolvePath = (path) => {
const r = localRequire.toUrl(path);
if (!/\.js/.test(r)) {
return r + '.js';
}
return r;
};
for (const moduleId in entryPointsMap) {
const entryPoint = entryPointsMap[moduleId];
if (entryPoint.append) {
entryPoint.append = entryPoint.append.map(resolvePath);
}
if (entryPoint.prepend) {
entryPoint.prepend = entryPoint.prepend.map(resolvePath);
}
}
});
loader(Object.keys(allMentionedModulesMap), () => {
const modules = loader.getBuildInfo();
const partialResult = emitEntryPoints(modules, entryPointsMap);
const cssInlinedResources = loader('vs/css').getInlinedResources();
callback(null, {
files: partialResult.files,
cssInlinedResources: cssInlinedResources,
bundleData: partialResult.bundleData
});
}, (err) => callback(err, null));
} | javascript | function bundle(entryPoints, config, callback) {
const entryPointsMap = {};
entryPoints.forEach((module) => {
entryPointsMap[module.name] = module;
});
const allMentionedModulesMap = {};
entryPoints.forEach((module) => {
allMentionedModulesMap[module.name] = true;
(module.include || []).forEach(function (includedModule) {
allMentionedModulesMap[includedModule] = true;
});
(module.exclude || []).forEach(function (excludedModule) {
allMentionedModulesMap[excludedModule] = true;
});
});
const code = require('fs').readFileSync(path.join(__dirname, '../../src/vs/loader.js'));
const r = vm.runInThisContext('(function(require, module, exports) { ' + code + '\n});');
const loaderModule = { exports: {} };
r.call({}, require, loaderModule, loaderModule.exports);
const loader = loaderModule.exports;
config.isBuild = true;
config.paths = config.paths || {};
if (!config.paths['vs/nls']) {
config.paths['vs/nls'] = 'out-build/vs/nls.build';
}
if (!config.paths['vs/css']) {
config.paths['vs/css'] = 'out-build/vs/css.build';
}
loader.config(config);
loader(['require'], (localRequire) => {
const resolvePath = (path) => {
const r = localRequire.toUrl(path);
if (!/\.js/.test(r)) {
return r + '.js';
}
return r;
};
for (const moduleId in entryPointsMap) {
const entryPoint = entryPointsMap[moduleId];
if (entryPoint.append) {
entryPoint.append = entryPoint.append.map(resolvePath);
}
if (entryPoint.prepend) {
entryPoint.prepend = entryPoint.prepend.map(resolvePath);
}
}
});
loader(Object.keys(allMentionedModulesMap), () => {
const modules = loader.getBuildInfo();
const partialResult = emitEntryPoints(modules, entryPointsMap);
const cssInlinedResources = loader('vs/css').getInlinedResources();
callback(null, {
files: partialResult.files,
cssInlinedResources: cssInlinedResources,
bundleData: partialResult.bundleData
});
}, (err) => callback(err, null));
} | [
"function",
"bundle",
"(",
"entryPoints",
",",
"config",
",",
"callback",
")",
"{",
"const",
"entryPointsMap",
"=",
"{",
"}",
";",
"entryPoints",
".",
"forEach",
"(",
"(",
"module",
")",
"=>",
"{",
"entryPointsMap",
"[",
"module",
".",
"name",
"]",
"=",
"module",
";",
"}",
")",
";",
"const",
"allMentionedModulesMap",
"=",
"{",
"}",
";",
"entryPoints",
".",
"forEach",
"(",
"(",
"module",
")",
"=>",
"{",
"allMentionedModulesMap",
"[",
"module",
".",
"name",
"]",
"=",
"true",
";",
"(",
"module",
".",
"include",
"||",
"[",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"includedModule",
")",
"{",
"allMentionedModulesMap",
"[",
"includedModule",
"]",
"=",
"true",
";",
"}",
")",
";",
"(",
"module",
".",
"exclude",
"||",
"[",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"excludedModule",
")",
"{",
"allMentionedModulesMap",
"[",
"excludedModule",
"]",
"=",
"true",
";",
"}",
")",
";",
"}",
")",
";",
"const",
"code",
"=",
"require",
"(",
"'fs'",
")",
".",
"readFileSync",
"(",
"path",
".",
"join",
"(",
"__dirname",
",",
"'../../src/vs/loader.js'",
")",
")",
";",
"const",
"r",
"=",
"vm",
".",
"runInThisContext",
"(",
"'(function(require, module, exports) { '",
"+",
"code",
"+",
"'\\n});'",
")",
";",
"\\n",
"const",
"loaderModule",
"=",
"{",
"exports",
":",
"{",
"}",
"}",
";",
"r",
".",
"call",
"(",
"{",
"}",
",",
"require",
",",
"loaderModule",
",",
"loaderModule",
".",
"exports",
")",
";",
"const",
"loader",
"=",
"loaderModule",
".",
"exports",
";",
"config",
".",
"isBuild",
"=",
"true",
";",
"config",
".",
"paths",
"=",
"config",
".",
"paths",
"||",
"{",
"}",
";",
"if",
"(",
"!",
"config",
".",
"paths",
"[",
"'vs/nls'",
"]",
")",
"{",
"config",
".",
"paths",
"[",
"'vs/nls'",
"]",
"=",
"'out-build/vs/nls.build'",
";",
"}",
"if",
"(",
"!",
"config",
".",
"paths",
"[",
"'vs/css'",
"]",
")",
"{",
"config",
".",
"paths",
"[",
"'vs/css'",
"]",
"=",
"'out-build/vs/css.build'",
";",
"}",
"loader",
".",
"config",
"(",
"config",
")",
";",
"loader",
"(",
"[",
"'require'",
"]",
",",
"(",
"localRequire",
")",
"=>",
"{",
"const",
"resolvePath",
"=",
"(",
"path",
")",
"=>",
"{",
"const",
"r",
"=",
"localRequire",
".",
"toUrl",
"(",
"path",
")",
";",
"if",
"(",
"!",
"/",
"\\.js",
"/",
".",
"test",
"(",
"r",
")",
")",
"{",
"return",
"r",
"+",
"'.js'",
";",
"}",
"return",
"r",
";",
"}",
";",
"for",
"(",
"const",
"moduleId",
"in",
"entryPointsMap",
")",
"{",
"const",
"entryPoint",
"=",
"entryPointsMap",
"[",
"moduleId",
"]",
";",
"if",
"(",
"entryPoint",
".",
"append",
")",
"{",
"entryPoint",
".",
"append",
"=",
"entryPoint",
".",
"append",
".",
"map",
"(",
"resolvePath",
")",
";",
"}",
"if",
"(",
"entryPoint",
".",
"prepend",
")",
"{",
"entryPoint",
".",
"prepend",
"=",
"entryPoint",
".",
"prepend",
".",
"map",
"(",
"resolvePath",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
]
| Bundle `entryPoints` given config `config`. | [
"Bundle",
"entryPoints",
"given",
"config",
"config",
"."
]
| 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/lib/bundle.js#L13-L70 | train |
Microsoft/vscode | build/lib/bundle.js | visit | function visit(rootNodes, graph) {
const result = {};
const queue = rootNodes;
rootNodes.forEach((node) => {
result[node] = true;
});
while (queue.length > 0) {
const el = queue.shift();
const myEdges = graph[el] || [];
myEdges.forEach((toNode) => {
if (!result[toNode]) {
result[toNode] = true;
queue.push(toNode);
}
});
}
return result;
} | javascript | function visit(rootNodes, graph) {
const result = {};
const queue = rootNodes;
rootNodes.forEach((node) => {
result[node] = true;
});
while (queue.length > 0) {
const el = queue.shift();
const myEdges = graph[el] || [];
myEdges.forEach((toNode) => {
if (!result[toNode]) {
result[toNode] = true;
queue.push(toNode);
}
});
}
return result;
} | [
"function",
"visit",
"(",
"rootNodes",
",",
"graph",
")",
"{",
"const",
"result",
"=",
"{",
"}",
";",
"const",
"queue",
"=",
"rootNodes",
";",
"rootNodes",
".",
"forEach",
"(",
"(",
"node",
")",
"=>",
"{",
"result",
"[",
"node",
"]",
"=",
"true",
";",
"}",
")",
";",
"while",
"(",
"queue",
".",
"length",
">",
"0",
")",
"{",
"const",
"el",
"=",
"queue",
".",
"shift",
"(",
")",
";",
"const",
"myEdges",
"=",
"graph",
"[",
"el",
"]",
"||",
"[",
"]",
";",
"myEdges",
".",
"forEach",
"(",
"(",
"toNode",
")",
"=>",
"{",
"if",
"(",
"!",
"result",
"[",
"toNode",
"]",
")",
"{",
"result",
"[",
"toNode",
"]",
"=",
"true",
";",
"queue",
".",
"push",
"(",
"toNode",
")",
";",
"}",
"}",
")",
";",
"}",
"return",
"result",
";",
"}"
]
| Return a set of reachable nodes in `graph` starting from `rootNodes` | [
"Return",
"a",
"set",
"of",
"reachable",
"nodes",
"in",
"graph",
"starting",
"from",
"rootNodes"
]
| 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/lib/bundle.js#L404-L421 | train |
Microsoft/vscode | build/lib/bundle.js | topologicalSort | function topologicalSort(graph) {
const allNodes = {}, outgoingEdgeCount = {}, inverseEdges = {};
Object.keys(graph).forEach((fromNode) => {
allNodes[fromNode] = true;
outgoingEdgeCount[fromNode] = graph[fromNode].length;
graph[fromNode].forEach((toNode) => {
allNodes[toNode] = true;
outgoingEdgeCount[toNode] = outgoingEdgeCount[toNode] || 0;
inverseEdges[toNode] = inverseEdges[toNode] || [];
inverseEdges[toNode].push(fromNode);
});
});
// https://en.wikipedia.org/wiki/Topological_sorting
const S = [], L = [];
Object.keys(allNodes).forEach((node) => {
if (outgoingEdgeCount[node] === 0) {
delete outgoingEdgeCount[node];
S.push(node);
}
});
while (S.length > 0) {
// Ensure the exact same order all the time with the same inputs
S.sort();
const n = S.shift();
L.push(n);
const myInverseEdges = inverseEdges[n] || [];
myInverseEdges.forEach((m) => {
outgoingEdgeCount[m]--;
if (outgoingEdgeCount[m] === 0) {
delete outgoingEdgeCount[m];
S.push(m);
}
});
}
if (Object.keys(outgoingEdgeCount).length > 0) {
throw new Error('Cannot do topological sort on cyclic graph, remaining nodes: ' + Object.keys(outgoingEdgeCount));
}
return L;
} | javascript | function topologicalSort(graph) {
const allNodes = {}, outgoingEdgeCount = {}, inverseEdges = {};
Object.keys(graph).forEach((fromNode) => {
allNodes[fromNode] = true;
outgoingEdgeCount[fromNode] = graph[fromNode].length;
graph[fromNode].forEach((toNode) => {
allNodes[toNode] = true;
outgoingEdgeCount[toNode] = outgoingEdgeCount[toNode] || 0;
inverseEdges[toNode] = inverseEdges[toNode] || [];
inverseEdges[toNode].push(fromNode);
});
});
// https://en.wikipedia.org/wiki/Topological_sorting
const S = [], L = [];
Object.keys(allNodes).forEach((node) => {
if (outgoingEdgeCount[node] === 0) {
delete outgoingEdgeCount[node];
S.push(node);
}
});
while (S.length > 0) {
// Ensure the exact same order all the time with the same inputs
S.sort();
const n = S.shift();
L.push(n);
const myInverseEdges = inverseEdges[n] || [];
myInverseEdges.forEach((m) => {
outgoingEdgeCount[m]--;
if (outgoingEdgeCount[m] === 0) {
delete outgoingEdgeCount[m];
S.push(m);
}
});
}
if (Object.keys(outgoingEdgeCount).length > 0) {
throw new Error('Cannot do topological sort on cyclic graph, remaining nodes: ' + Object.keys(outgoingEdgeCount));
}
return L;
} | [
"function",
"topologicalSort",
"(",
"graph",
")",
"{",
"const",
"allNodes",
"=",
"{",
"}",
",",
"outgoingEdgeCount",
"=",
"{",
"}",
",",
"inverseEdges",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"graph",
")",
".",
"forEach",
"(",
"(",
"fromNode",
")",
"=>",
"{",
"allNodes",
"[",
"fromNode",
"]",
"=",
"true",
";",
"outgoingEdgeCount",
"[",
"fromNode",
"]",
"=",
"graph",
"[",
"fromNode",
"]",
".",
"length",
";",
"graph",
"[",
"fromNode",
"]",
".",
"forEach",
"(",
"(",
"toNode",
")",
"=>",
"{",
"allNodes",
"[",
"toNode",
"]",
"=",
"true",
";",
"outgoingEdgeCount",
"[",
"toNode",
"]",
"=",
"outgoingEdgeCount",
"[",
"toNode",
"]",
"||",
"0",
";",
"inverseEdges",
"[",
"toNode",
"]",
"=",
"inverseEdges",
"[",
"toNode",
"]",
"||",
"[",
"]",
";",
"inverseEdges",
"[",
"toNode",
"]",
".",
"push",
"(",
"fromNode",
")",
";",
"}",
")",
";",
"}",
")",
";",
"const",
"S",
"=",
"[",
"]",
",",
"L",
"=",
"[",
"]",
";",
"Object",
".",
"keys",
"(",
"allNodes",
")",
".",
"forEach",
"(",
"(",
"node",
")",
"=>",
"{",
"if",
"(",
"outgoingEdgeCount",
"[",
"node",
"]",
"===",
"0",
")",
"{",
"delete",
"outgoingEdgeCount",
"[",
"node",
"]",
";",
"S",
".",
"push",
"(",
"node",
")",
";",
"}",
"}",
")",
";",
"while",
"(",
"S",
".",
"length",
">",
"0",
")",
"{",
"S",
".",
"sort",
"(",
")",
";",
"const",
"n",
"=",
"S",
".",
"shift",
"(",
")",
";",
"L",
".",
"push",
"(",
"n",
")",
";",
"const",
"myInverseEdges",
"=",
"inverseEdges",
"[",
"n",
"]",
"||",
"[",
"]",
";",
"myInverseEdges",
".",
"forEach",
"(",
"(",
"m",
")",
"=>",
"{",
"outgoingEdgeCount",
"[",
"m",
"]",
"--",
";",
"if",
"(",
"outgoingEdgeCount",
"[",
"m",
"]",
"===",
"0",
")",
"{",
"delete",
"outgoingEdgeCount",
"[",
"m",
"]",
";",
"S",
".",
"push",
"(",
"m",
")",
";",
"}",
"}",
")",
";",
"}",
"if",
"(",
"Object",
".",
"keys",
"(",
"outgoingEdgeCount",
")",
".",
"length",
">",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Cannot do topological sort on cyclic graph, remaining nodes: '",
"+",
"Object",
".",
"keys",
"(",
"outgoingEdgeCount",
")",
")",
";",
"}",
"return",
"L",
";",
"}"
]
| Perform a topological sort on `graph` | [
"Perform",
"a",
"topological",
"sort",
"on",
"graph"
]
| 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/lib/bundle.js#L425-L463 | train |
Microsoft/vscode | build/lib/git.js | getVersion | function getVersion(repo) {
const git = path.join(repo, '.git');
const headPath = path.join(git, 'HEAD');
let head;
try {
head = fs.readFileSync(headPath, 'utf8').trim();
}
catch (e) {
return undefined;
}
if (/^[0-9a-f]{40}$/i.test(head)) {
return head;
}
const refMatch = /^ref: (.*)$/.exec(head);
if (!refMatch) {
return undefined;
}
const ref = refMatch[1];
const refPath = path.join(git, ref);
try {
return fs.readFileSync(refPath, 'utf8').trim();
}
catch (e) {
// noop
}
const packedRefsPath = path.join(git, 'packed-refs');
let refsRaw;
try {
refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
}
catch (e) {
return undefined;
}
const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
let refsMatch;
let refs = {};
while (refsMatch = refsRegex.exec(refsRaw)) {
refs[refsMatch[2]] = refsMatch[1];
}
return refs[ref];
} | javascript | function getVersion(repo) {
const git = path.join(repo, '.git');
const headPath = path.join(git, 'HEAD');
let head;
try {
head = fs.readFileSync(headPath, 'utf8').trim();
}
catch (e) {
return undefined;
}
if (/^[0-9a-f]{40}$/i.test(head)) {
return head;
}
const refMatch = /^ref: (.*)$/.exec(head);
if (!refMatch) {
return undefined;
}
const ref = refMatch[1];
const refPath = path.join(git, ref);
try {
return fs.readFileSync(refPath, 'utf8').trim();
}
catch (e) {
// noop
}
const packedRefsPath = path.join(git, 'packed-refs');
let refsRaw;
try {
refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
}
catch (e) {
return undefined;
}
const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
let refsMatch;
let refs = {};
while (refsMatch = refsRegex.exec(refsRaw)) {
refs[refsMatch[2]] = refsMatch[1];
}
return refs[ref];
} | [
"function",
"getVersion",
"(",
"repo",
")",
"{",
"const",
"git",
"=",
"path",
".",
"join",
"(",
"repo",
",",
"'.git'",
")",
";",
"const",
"headPath",
"=",
"path",
".",
"join",
"(",
"git",
",",
"'HEAD'",
")",
";",
"let",
"head",
";",
"try",
"{",
"head",
"=",
"fs",
".",
"readFileSync",
"(",
"headPath",
",",
"'utf8'",
")",
".",
"trim",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"undefined",
";",
"}",
"if",
"(",
"/",
"^[0-9a-f]{40}$",
"/",
"i",
".",
"test",
"(",
"head",
")",
")",
"{",
"return",
"head",
";",
"}",
"const",
"refMatch",
"=",
"/",
"^ref: (.*)$",
"/",
".",
"exec",
"(",
"head",
")",
";",
"if",
"(",
"!",
"refMatch",
")",
"{",
"return",
"undefined",
";",
"}",
"const",
"ref",
"=",
"refMatch",
"[",
"1",
"]",
";",
"const",
"refPath",
"=",
"path",
".",
"join",
"(",
"git",
",",
"ref",
")",
";",
"try",
"{",
"return",
"fs",
".",
"readFileSync",
"(",
"refPath",
",",
"'utf8'",
")",
".",
"trim",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"const",
"packedRefsPath",
"=",
"path",
".",
"join",
"(",
"git",
",",
"'packed-refs'",
")",
";",
"let",
"refsRaw",
";",
"try",
"{",
"refsRaw",
"=",
"fs",
".",
"readFileSync",
"(",
"packedRefsPath",
",",
"'utf8'",
")",
".",
"trim",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"undefined",
";",
"}",
"const",
"refsRegex",
"=",
"/",
"^([0-9a-f]{40})\\s+(.+)$",
"/",
"gm",
";",
"let",
"refsMatch",
";",
"let",
"refs",
"=",
"{",
"}",
";",
"while",
"(",
"refsMatch",
"=",
"refsRegex",
".",
"exec",
"(",
"refsRaw",
")",
")",
"{",
"refs",
"[",
"refsMatch",
"[",
"2",
"]",
"]",
"=",
"refsMatch",
"[",
"1",
"]",
";",
"}",
"return",
"refs",
"[",
"ref",
"]",
";",
"}"
]
| Returns the sha1 commit version of a repository or undefined in case of failure. | [
"Returns",
"the",
"sha1",
"commit",
"version",
"of",
"a",
"repository",
"or",
"undefined",
"in",
"case",
"of",
"failure",
"."
]
| 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/lib/git.js#L12-L52 | train |
Microsoft/vscode | src/bootstrap-fork.js | safeToArray | function safeToArray(args) {
const seen = [];
const argsArray = [];
let res;
// Massage some arguments with special treatment
if (args.length) {
for (let i = 0; i < args.length; i++) {
// Any argument of type 'undefined' needs to be specially treated because
// JSON.stringify will simply ignore those. We replace them with the string
// 'undefined' which is not 100% right, but good enough to be logged to console
if (typeof args[i] === 'undefined') {
args[i] = 'undefined';
}
// Any argument that is an Error will be changed to be just the error stack/message
// itself because currently cannot serialize the error over entirely.
else if (args[i] instanceof Error) {
const errorObj = args[i];
if (errorObj.stack) {
args[i] = errorObj.stack;
} else {
args[i] = errorObj.toString();
}
}
argsArray.push(args[i]);
}
}
// Add the stack trace as payload if we are told so. We remove the message and the 2 top frames
// to start the stacktrace where the console message was being written
if (process.env.VSCODE_LOG_STACK === 'true') {
const stack = new Error().stack;
argsArray.push({ __$stack: stack.split('\n').slice(3).join('\n') });
}
try {
res = JSON.stringify(argsArray, function (key, value) {
// Objects get special treatment to prevent circles
if (isObject(value) || Array.isArray(value)) {
if (seen.indexOf(value) !== -1) {
return '[Circular]';
}
seen.push(value);
}
return value;
});
} catch (error) {
return 'Output omitted for an object that cannot be inspected (' + error.toString() + ')';
}
if (res && res.length > MAX_LENGTH) {
return 'Output omitted for a large object that exceeds the limits';
}
return res;
} | javascript | function safeToArray(args) {
const seen = [];
const argsArray = [];
let res;
// Massage some arguments with special treatment
if (args.length) {
for (let i = 0; i < args.length; i++) {
// Any argument of type 'undefined' needs to be specially treated because
// JSON.stringify will simply ignore those. We replace them with the string
// 'undefined' which is not 100% right, but good enough to be logged to console
if (typeof args[i] === 'undefined') {
args[i] = 'undefined';
}
// Any argument that is an Error will be changed to be just the error stack/message
// itself because currently cannot serialize the error over entirely.
else if (args[i] instanceof Error) {
const errorObj = args[i];
if (errorObj.stack) {
args[i] = errorObj.stack;
} else {
args[i] = errorObj.toString();
}
}
argsArray.push(args[i]);
}
}
// Add the stack trace as payload if we are told so. We remove the message and the 2 top frames
// to start the stacktrace where the console message was being written
if (process.env.VSCODE_LOG_STACK === 'true') {
const stack = new Error().stack;
argsArray.push({ __$stack: stack.split('\n').slice(3).join('\n') });
}
try {
res = JSON.stringify(argsArray, function (key, value) {
// Objects get special treatment to prevent circles
if (isObject(value) || Array.isArray(value)) {
if (seen.indexOf(value) !== -1) {
return '[Circular]';
}
seen.push(value);
}
return value;
});
} catch (error) {
return 'Output omitted for an object that cannot be inspected (' + error.toString() + ')';
}
if (res && res.length > MAX_LENGTH) {
return 'Output omitted for a large object that exceeds the limits';
}
return res;
} | [
"function",
"safeToArray",
"(",
"args",
")",
"{",
"const",
"seen",
"=",
"[",
"]",
";",
"const",
"argsArray",
"=",
"[",
"]",
";",
"let",
"res",
";",
"if",
"(",
"args",
".",
"length",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"args",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"typeof",
"args",
"[",
"i",
"]",
"===",
"'undefined'",
")",
"{",
"args",
"[",
"i",
"]",
"=",
"'undefined'",
";",
"}",
"else",
"if",
"(",
"args",
"[",
"i",
"]",
"instanceof",
"Error",
")",
"{",
"const",
"errorObj",
"=",
"args",
"[",
"i",
"]",
";",
"if",
"(",
"errorObj",
".",
"stack",
")",
"{",
"args",
"[",
"i",
"]",
"=",
"errorObj",
".",
"stack",
";",
"}",
"else",
"{",
"args",
"[",
"i",
"]",
"=",
"errorObj",
".",
"toString",
"(",
")",
";",
"}",
"}",
"argsArray",
".",
"push",
"(",
"args",
"[",
"i",
"]",
")",
";",
"}",
"}",
"if",
"(",
"process",
".",
"env",
".",
"VSCODE_LOG_STACK",
"===",
"'true'",
")",
"{",
"const",
"stack",
"=",
"new",
"Error",
"(",
")",
".",
"stack",
";",
"argsArray",
".",
"push",
"(",
"{",
"__$stack",
":",
"stack",
".",
"split",
"(",
"'\\n'",
")",
".",
"\\n",
"slice",
".",
"(",
"3",
")",
"join",
"}",
")",
";",
"}",
"(",
"'\\n'",
")",
"\\n",
"try",
"{",
"res",
"=",
"JSON",
".",
"stringify",
"(",
"argsArray",
",",
"function",
"(",
"key",
",",
"value",
")",
"{",
"if",
"(",
"isObject",
"(",
"value",
")",
"||",
"Array",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"if",
"(",
"seen",
".",
"indexOf",
"(",
"value",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"'[Circular]'",
";",
"}",
"seen",
".",
"push",
"(",
"value",
")",
";",
"}",
"return",
"value",
";",
"}",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"return",
"'Output omitted for an object that cannot be inspected ('",
"+",
"error",
".",
"toString",
"(",
")",
"+",
"')'",
";",
"}",
"}"
]
| Prevent circular stringify and convert arguments to real array | [
"Prevent",
"circular",
"stringify",
"and",
"convert",
"arguments",
"to",
"real",
"array"
]
| 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/src/bootstrap-fork.js#L50-L112 | train |
Microsoft/vscode | build/gulpfile.vscode.js | computeChecksums | function computeChecksums(out, filenames) {
var result = {};
filenames.forEach(function (filename) {
var fullPath = path.join(process.cwd(), out, filename);
result[filename] = computeChecksum(fullPath);
});
return result;
} | javascript | function computeChecksums(out, filenames) {
var result = {};
filenames.forEach(function (filename) {
var fullPath = path.join(process.cwd(), out, filename);
result[filename] = computeChecksum(fullPath);
});
return result;
} | [
"function",
"computeChecksums",
"(",
"out",
",",
"filenames",
")",
"{",
"var",
"result",
"=",
"{",
"}",
";",
"filenames",
".",
"forEach",
"(",
"function",
"(",
"filename",
")",
"{",
"var",
"fullPath",
"=",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"out",
",",
"filename",
")",
";",
"result",
"[",
"filename",
"]",
"=",
"computeChecksum",
"(",
"fullPath",
")",
";",
"}",
")",
";",
"return",
"result",
";",
"}"
]
| Compute checksums for some files.
@param {string} out The out folder to read the file from.
@param {string[]} filenames The paths to compute a checksum for.
@return {Object} A map of paths to checksums. | [
"Compute",
"checksums",
"for",
"some",
"files",
"."
]
| 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/gulpfile.vscode.js#L230-L237 | train |
Microsoft/vscode | build/gulpfile.vscode.js | computeChecksum | function computeChecksum(filename) {
var contents = fs.readFileSync(filename);
var hash = crypto
.createHash('md5')
.update(contents)
.digest('base64')
.replace(/=+$/, '');
return hash;
} | javascript | function computeChecksum(filename) {
var contents = fs.readFileSync(filename);
var hash = crypto
.createHash('md5')
.update(contents)
.digest('base64')
.replace(/=+$/, '');
return hash;
} | [
"function",
"computeChecksum",
"(",
"filename",
")",
"{",
"var",
"contents",
"=",
"fs",
".",
"readFileSync",
"(",
"filename",
")",
";",
"var",
"hash",
"=",
"crypto",
".",
"createHash",
"(",
"'md5'",
")",
".",
"update",
"(",
"contents",
")",
".",
"digest",
"(",
"'base64'",
")",
".",
"replace",
"(",
"/",
"=+$",
"/",
",",
"''",
")",
";",
"return",
"hash",
";",
"}"
]
| Compute checksum for a file.
@param {string} filename The absolute path to a filename.
@return {string} The checksum for `filename`. | [
"Compute",
"checksum",
"for",
"a",
"file",
"."
]
| 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/gulpfile.vscode.js#L245-L255 | train |
angular/angular | aio/tools/transforms/angular-base-package/rendering/hasValues.js | readProperty | function readProperty(obj, propertySegments, index) {
const value = obj[propertySegments[index]];
return !!value && (index === propertySegments.length - 1 || readProperty(value, propertySegments, index + 1));
} | javascript | function readProperty(obj, propertySegments, index) {
const value = obj[propertySegments[index]];
return !!value && (index === propertySegments.length - 1 || readProperty(value, propertySegments, index + 1));
} | [
"function",
"readProperty",
"(",
"obj",
",",
"propertySegments",
",",
"index",
")",
"{",
"const",
"value",
"=",
"obj",
"[",
"propertySegments",
"[",
"index",
"]",
"]",
";",
"return",
"!",
"!",
"value",
"&&",
"(",
"index",
"===",
"propertySegments",
".",
"length",
"-",
"1",
"||",
"readProperty",
"(",
"value",
",",
"propertySegments",
",",
"index",
"+",
"1",
")",
")",
";",
"}"
]
| Search deeply into an object via a collection of property segments, starting at the
indexed segment.
E.g. if `obj = { a: { b: { c: 10 }}}` then
`readProperty(obj, ['a', 'b', 'c'], 0)` will return true;
but
`readProperty(obj, ['a', 'd'], 0)` will return false; | [
"Search",
"deeply",
"into",
"an",
"object",
"via",
"a",
"collection",
"of",
"property",
"segments",
"starting",
"at",
"the",
"indexed",
"segment",
"."
]
| c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/aio/tools/transforms/angular-base-package/rendering/hasValues.js#L20-L23 | train |
angular/angular | tools/gulp-tasks/cldr/extract.js | generateLocale | function generateLocale(locale, localeData, baseCurrencies) {
// [ localeId, dateTime, number, currency, pluralCase ]
let data = stringify([
locale,
...getDateTimeTranslations(localeData),
...getDateTimeSettings(localeData),
...getNumberSettings(localeData),
...getCurrencySettings(locale, localeData),
generateLocaleCurrencies(localeData, baseCurrencies)
], true)
// We remove "undefined" added by spreading arrays when there is no value
.replace(/undefined/g, 'u');
// adding plural function after, because we don't want it as a string
data = data.substring(0, data.lastIndexOf(']')) + `, plural]`;
return `${HEADER}
const u = undefined;
${getPluralFunction(locale)}
export default ${data};
`;
} | javascript | function generateLocale(locale, localeData, baseCurrencies) {
// [ localeId, dateTime, number, currency, pluralCase ]
let data = stringify([
locale,
...getDateTimeTranslations(localeData),
...getDateTimeSettings(localeData),
...getNumberSettings(localeData),
...getCurrencySettings(locale, localeData),
generateLocaleCurrencies(localeData, baseCurrencies)
], true)
// We remove "undefined" added by spreading arrays when there is no value
.replace(/undefined/g, 'u');
// adding plural function after, because we don't want it as a string
data = data.substring(0, data.lastIndexOf(']')) + `, plural]`;
return `${HEADER}
const u = undefined;
${getPluralFunction(locale)}
export default ${data};
`;
} | [
"function",
"generateLocale",
"(",
"locale",
",",
"localeData",
",",
"baseCurrencies",
")",
"{",
"let",
"data",
"=",
"stringify",
"(",
"[",
"locale",
",",
"...",
"getDateTimeTranslations",
"(",
"localeData",
")",
",",
"...",
"getDateTimeSettings",
"(",
"localeData",
")",
",",
"...",
"getNumberSettings",
"(",
"localeData",
")",
",",
"...",
"getCurrencySettings",
"(",
"locale",
",",
"localeData",
")",
",",
"generateLocaleCurrencies",
"(",
"localeData",
",",
"baseCurrencies",
")",
"]",
",",
"true",
")",
".",
"replace",
"(",
"/",
"undefined",
"/",
"g",
",",
"'u'",
")",
";",
"data",
"=",
"data",
".",
"substring",
"(",
"0",
",",
"data",
".",
"lastIndexOf",
"(",
"']'",
")",
")",
"+",
"`",
"`",
";",
"return",
"`",
"${",
"HEADER",
"}",
"${",
"getPluralFunction",
"(",
"locale",
")",
"}",
"${",
"data",
"}",
"`",
";",
"}"
]
| Generate file that contains basic locale data | [
"Generate",
"file",
"that",
"contains",
"basic",
"locale",
"data"
]
| c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/extract.js#L94-L117 | train |
angular/angular | tools/gulp-tasks/cldr/extract.js | generateLocaleCurrencies | function generateLocaleCurrencies(localeData, baseCurrencies) {
const currenciesData = localeData.main('numbers/currencies');
const currencies = {};
Object.keys(currenciesData).forEach(code => {
let symbolsArray = [];
const symbol = currenciesData[code].symbol;
const symbolNarrow = currenciesData[code]['symbol-alt-narrow'];
if (symbol && symbol !== code) {
symbolsArray.push(symbol);
}
if (symbolNarrow && symbolNarrow !== symbol) {
if (symbolsArray.length > 0) {
symbolsArray.push(symbolNarrow);
} else {
symbolsArray = [undefined, symbolNarrow];
}
}
// if locale data are different, set the value
if ((baseCurrencies[code] || []).toString() !== symbolsArray.toString()) {
currencies[code] = symbolsArray;
}
});
return currencies;
} | javascript | function generateLocaleCurrencies(localeData, baseCurrencies) {
const currenciesData = localeData.main('numbers/currencies');
const currencies = {};
Object.keys(currenciesData).forEach(code => {
let symbolsArray = [];
const symbol = currenciesData[code].symbol;
const symbolNarrow = currenciesData[code]['symbol-alt-narrow'];
if (symbol && symbol !== code) {
symbolsArray.push(symbol);
}
if (symbolNarrow && symbolNarrow !== symbol) {
if (symbolsArray.length > 0) {
symbolsArray.push(symbolNarrow);
} else {
symbolsArray = [undefined, symbolNarrow];
}
}
// if locale data are different, set the value
if ((baseCurrencies[code] || []).toString() !== symbolsArray.toString()) {
currencies[code] = symbolsArray;
}
});
return currencies;
} | [
"function",
"generateLocaleCurrencies",
"(",
"localeData",
",",
"baseCurrencies",
")",
"{",
"const",
"currenciesData",
"=",
"localeData",
".",
"main",
"(",
"'numbers/currencies'",
")",
";",
"const",
"currencies",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"currenciesData",
")",
".",
"forEach",
"(",
"code",
"=>",
"{",
"let",
"symbolsArray",
"=",
"[",
"]",
";",
"const",
"symbol",
"=",
"currenciesData",
"[",
"code",
"]",
".",
"symbol",
";",
"const",
"symbolNarrow",
"=",
"currenciesData",
"[",
"code",
"]",
"[",
"'symbol-alt-narrow'",
"]",
";",
"if",
"(",
"symbol",
"&&",
"symbol",
"!==",
"code",
")",
"{",
"symbolsArray",
".",
"push",
"(",
"symbol",
")",
";",
"}",
"if",
"(",
"symbolNarrow",
"&&",
"symbolNarrow",
"!==",
"symbol",
")",
"{",
"if",
"(",
"symbolsArray",
".",
"length",
">",
"0",
")",
"{",
"symbolsArray",
".",
"push",
"(",
"symbolNarrow",
")",
";",
"}",
"else",
"{",
"symbolsArray",
"=",
"[",
"undefined",
",",
"symbolNarrow",
"]",
";",
"}",
"}",
"if",
"(",
"(",
"baseCurrencies",
"[",
"code",
"]",
"||",
"[",
"]",
")",
".",
"toString",
"(",
")",
"!==",
"symbolsArray",
".",
"toString",
"(",
")",
")",
"{",
"currencies",
"[",
"code",
"]",
"=",
"symbolsArray",
";",
"}",
"}",
")",
";",
"return",
"currencies",
";",
"}"
]
| To minimize the file even more, we only output the differences compared to the base currency | [
"To",
"minimize",
"the",
"file",
"even",
"more",
"we",
"only",
"output",
"the",
"differences",
"compared",
"to",
"the",
"base",
"currency"
]
| c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/extract.js#L201-L225 | train |
angular/angular | tools/gulp-tasks/cldr/extract.js | getDayPeriods | function getDayPeriods(localeData, dayPeriodsList) {
const dayPeriods = localeData.main(`dates/calendars/gregorian/dayPeriods`);
const result = {};
// cleaning up unused keys
Object.keys(dayPeriods).forEach(key1 => { // format / stand-alone
result[key1] = {};
Object.keys(dayPeriods[key1]).forEach(key2 => { // narrow / abbreviated / wide
result[key1][key2] = {};
Object.keys(dayPeriods[key1][key2]).forEach(key3 => {
if (dayPeriodsList.indexOf(key3) !== -1) {
result[key1][key2][key3] = dayPeriods[key1][key2][key3];
}
});
});
});
return result;
} | javascript | function getDayPeriods(localeData, dayPeriodsList) {
const dayPeriods = localeData.main(`dates/calendars/gregorian/dayPeriods`);
const result = {};
// cleaning up unused keys
Object.keys(dayPeriods).forEach(key1 => { // format / stand-alone
result[key1] = {};
Object.keys(dayPeriods[key1]).forEach(key2 => { // narrow / abbreviated / wide
result[key1][key2] = {};
Object.keys(dayPeriods[key1][key2]).forEach(key3 => {
if (dayPeriodsList.indexOf(key3) !== -1) {
result[key1][key2][key3] = dayPeriods[key1][key2][key3];
}
});
});
});
return result;
} | [
"function",
"getDayPeriods",
"(",
"localeData",
",",
"dayPeriodsList",
")",
"{",
"const",
"dayPeriods",
"=",
"localeData",
".",
"main",
"(",
"`",
"`",
")",
";",
"const",
"result",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"dayPeriods",
")",
".",
"forEach",
"(",
"key1",
"=>",
"{",
"result",
"[",
"key1",
"]",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"dayPeriods",
"[",
"key1",
"]",
")",
".",
"forEach",
"(",
"key2",
"=>",
"{",
"result",
"[",
"key1",
"]",
"[",
"key2",
"]",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"dayPeriods",
"[",
"key1",
"]",
"[",
"key2",
"]",
")",
".",
"forEach",
"(",
"key3",
"=>",
"{",
"if",
"(",
"dayPeriodsList",
".",
"indexOf",
"(",
"key3",
")",
"!==",
"-",
"1",
")",
"{",
"result",
"[",
"key1",
"]",
"[",
"key2",
"]",
"[",
"key3",
"]",
"=",
"dayPeriods",
"[",
"key1",
"]",
"[",
"key2",
"]",
"[",
"key3",
"]",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"result",
";",
"}"
]
| Returns data for the chosen day periods
@returns {format: {narrow / abbreviated / wide: [...]}, stand-alone: {narrow / abbreviated / wide: [...]}} | [
"Returns",
"data",
"for",
"the",
"chosen",
"day",
"periods"
]
| c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/extract.js#L245-L262 | train |
angular/angular | tools/gulp-tasks/cldr/extract.js | getDateTimeTranslations | function getDateTimeTranslations(localeData) {
const dayNames = localeData.main(`dates/calendars/gregorian/days`);
const monthNames = localeData.main(`dates/calendars/gregorian/months`);
const erasNames = localeData.main(`dates/calendars/gregorian/eras`);
const dayPeriods = getDayPeriodsAmPm(localeData);
const dayPeriodsFormat = removeDuplicates([
objectValues(dayPeriods.format.narrow),
objectValues(dayPeriods.format.abbreviated),
objectValues(dayPeriods.format.wide)
]);
const dayPeriodsStandalone = removeDuplicates([
objectValues(dayPeriods['stand-alone'].narrow),
objectValues(dayPeriods['stand-alone'].abbreviated),
objectValues(dayPeriods['stand-alone'].wide)
]);
const daysFormat = removeDuplicates([
objectValues(dayNames.format.narrow),
objectValues(dayNames.format.abbreviated),
objectValues(dayNames.format.wide),
objectValues(dayNames.format.short)
]);
const daysStandalone = removeDuplicates([
objectValues(dayNames['stand-alone'].narrow),
objectValues(dayNames['stand-alone'].abbreviated),
objectValues(dayNames['stand-alone'].wide),
objectValues(dayNames['stand-alone'].short)
]);
const monthsFormat = removeDuplicates([
objectValues(monthNames.format.narrow),
objectValues(monthNames.format.abbreviated),
objectValues(monthNames.format.wide)
]);
const monthsStandalone = removeDuplicates([
objectValues(monthNames['stand-alone'].narrow),
objectValues(monthNames['stand-alone'].abbreviated),
objectValues(monthNames['stand-alone'].wide)
]);
const eras = removeDuplicates([
[erasNames.eraNarrow['0'], erasNames.eraNarrow['1']],
[erasNames.eraAbbr['0'], erasNames.eraAbbr['1']],
[erasNames.eraNames['0'], erasNames.eraNames['1']]
]);
const dateTimeTranslations = [
...removeDuplicates([dayPeriodsFormat, dayPeriodsStandalone]),
...removeDuplicates([daysFormat, daysStandalone]),
...removeDuplicates([monthsFormat, monthsStandalone]),
eras
];
return dateTimeTranslations;
} | javascript | function getDateTimeTranslations(localeData) {
const dayNames = localeData.main(`dates/calendars/gregorian/days`);
const monthNames = localeData.main(`dates/calendars/gregorian/months`);
const erasNames = localeData.main(`dates/calendars/gregorian/eras`);
const dayPeriods = getDayPeriodsAmPm(localeData);
const dayPeriodsFormat = removeDuplicates([
objectValues(dayPeriods.format.narrow),
objectValues(dayPeriods.format.abbreviated),
objectValues(dayPeriods.format.wide)
]);
const dayPeriodsStandalone = removeDuplicates([
objectValues(dayPeriods['stand-alone'].narrow),
objectValues(dayPeriods['stand-alone'].abbreviated),
objectValues(dayPeriods['stand-alone'].wide)
]);
const daysFormat = removeDuplicates([
objectValues(dayNames.format.narrow),
objectValues(dayNames.format.abbreviated),
objectValues(dayNames.format.wide),
objectValues(dayNames.format.short)
]);
const daysStandalone = removeDuplicates([
objectValues(dayNames['stand-alone'].narrow),
objectValues(dayNames['stand-alone'].abbreviated),
objectValues(dayNames['stand-alone'].wide),
objectValues(dayNames['stand-alone'].short)
]);
const monthsFormat = removeDuplicates([
objectValues(monthNames.format.narrow),
objectValues(monthNames.format.abbreviated),
objectValues(monthNames.format.wide)
]);
const monthsStandalone = removeDuplicates([
objectValues(monthNames['stand-alone'].narrow),
objectValues(monthNames['stand-alone'].abbreviated),
objectValues(monthNames['stand-alone'].wide)
]);
const eras = removeDuplicates([
[erasNames.eraNarrow['0'], erasNames.eraNarrow['1']],
[erasNames.eraAbbr['0'], erasNames.eraAbbr['1']],
[erasNames.eraNames['0'], erasNames.eraNames['1']]
]);
const dateTimeTranslations = [
...removeDuplicates([dayPeriodsFormat, dayPeriodsStandalone]),
...removeDuplicates([daysFormat, daysStandalone]),
...removeDuplicates([monthsFormat, monthsStandalone]),
eras
];
return dateTimeTranslations;
} | [
"function",
"getDateTimeTranslations",
"(",
"localeData",
")",
"{",
"const",
"dayNames",
"=",
"localeData",
".",
"main",
"(",
"`",
"`",
")",
";",
"const",
"monthNames",
"=",
"localeData",
".",
"main",
"(",
"`",
"`",
")",
";",
"const",
"erasNames",
"=",
"localeData",
".",
"main",
"(",
"`",
"`",
")",
";",
"const",
"dayPeriods",
"=",
"getDayPeriodsAmPm",
"(",
"localeData",
")",
";",
"const",
"dayPeriodsFormat",
"=",
"removeDuplicates",
"(",
"[",
"objectValues",
"(",
"dayPeriods",
".",
"format",
".",
"narrow",
")",
",",
"objectValues",
"(",
"dayPeriods",
".",
"format",
".",
"abbreviated",
")",
",",
"objectValues",
"(",
"dayPeriods",
".",
"format",
".",
"wide",
")",
"]",
")",
";",
"const",
"dayPeriodsStandalone",
"=",
"removeDuplicates",
"(",
"[",
"objectValues",
"(",
"dayPeriods",
"[",
"'stand-alone'",
"]",
".",
"narrow",
")",
",",
"objectValues",
"(",
"dayPeriods",
"[",
"'stand-alone'",
"]",
".",
"abbreviated",
")",
",",
"objectValues",
"(",
"dayPeriods",
"[",
"'stand-alone'",
"]",
".",
"wide",
")",
"]",
")",
";",
"const",
"daysFormat",
"=",
"removeDuplicates",
"(",
"[",
"objectValues",
"(",
"dayNames",
".",
"format",
".",
"narrow",
")",
",",
"objectValues",
"(",
"dayNames",
".",
"format",
".",
"abbreviated",
")",
",",
"objectValues",
"(",
"dayNames",
".",
"format",
".",
"wide",
")",
",",
"objectValues",
"(",
"dayNames",
".",
"format",
".",
"short",
")",
"]",
")",
";",
"const",
"daysStandalone",
"=",
"removeDuplicates",
"(",
"[",
"objectValues",
"(",
"dayNames",
"[",
"'stand-alone'",
"]",
".",
"narrow",
")",
",",
"objectValues",
"(",
"dayNames",
"[",
"'stand-alone'",
"]",
".",
"abbreviated",
")",
",",
"objectValues",
"(",
"dayNames",
"[",
"'stand-alone'",
"]",
".",
"wide",
")",
",",
"objectValues",
"(",
"dayNames",
"[",
"'stand-alone'",
"]",
".",
"short",
")",
"]",
")",
";",
"const",
"monthsFormat",
"=",
"removeDuplicates",
"(",
"[",
"objectValues",
"(",
"monthNames",
".",
"format",
".",
"narrow",
")",
",",
"objectValues",
"(",
"monthNames",
".",
"format",
".",
"abbreviated",
")",
",",
"objectValues",
"(",
"monthNames",
".",
"format",
".",
"wide",
")",
"]",
")",
";",
"const",
"monthsStandalone",
"=",
"removeDuplicates",
"(",
"[",
"objectValues",
"(",
"monthNames",
"[",
"'stand-alone'",
"]",
".",
"narrow",
")",
",",
"objectValues",
"(",
"monthNames",
"[",
"'stand-alone'",
"]",
".",
"abbreviated",
")",
",",
"objectValues",
"(",
"monthNames",
"[",
"'stand-alone'",
"]",
".",
"wide",
")",
"]",
")",
";",
"const",
"eras",
"=",
"removeDuplicates",
"(",
"[",
"[",
"erasNames",
".",
"eraNarrow",
"[",
"'0'",
"]",
",",
"erasNames",
".",
"eraNarrow",
"[",
"'1'",
"]",
"]",
",",
"[",
"erasNames",
".",
"eraAbbr",
"[",
"'0'",
"]",
",",
"erasNames",
".",
"eraAbbr",
"[",
"'1'",
"]",
"]",
",",
"[",
"erasNames",
".",
"eraNames",
"[",
"'0'",
"]",
",",
"erasNames",
".",
"eraNames",
"[",
"'1'",
"]",
"]",
"]",
")",
";",
"const",
"dateTimeTranslations",
"=",
"[",
"...",
"removeDuplicates",
"(",
"[",
"dayPeriodsFormat",
",",
"dayPeriodsStandalone",
"]",
")",
",",
"...",
"removeDuplicates",
"(",
"[",
"daysFormat",
",",
"daysStandalone",
"]",
")",
",",
"...",
"removeDuplicates",
"(",
"[",
"monthsFormat",
",",
"monthsStandalone",
"]",
")",
",",
"eras",
"]",
";",
"return",
"dateTimeTranslations",
";",
"}"
]
| Returns date-related translations for a locale
@returns [ dayPeriodsFormat, dayPeriodsStandalone, daysFormat, dayStandalone, monthsFormat, monthsStandalone, eras ]
each value: [ narrow, abbreviated, wide, short? ] | [
"Returns",
"date",
"-",
"related",
"translations",
"for",
"a",
"locale"
]
| c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/extract.js#L284-L342 | train |
angular/angular | tools/gulp-tasks/cldr/extract.js | getDateTimeFormats | function getDateTimeFormats(localeData) {
function getFormats(data) {
return removeDuplicates([
data.short._value || data.short,
data.medium._value || data.medium,
data.long._value || data.long,
data.full._value || data.full
]);
}
const dateFormats = localeData.main('dates/calendars/gregorian/dateFormats');
const timeFormats = localeData.main('dates/calendars/gregorian/timeFormats');
const dateTimeFormats = localeData.main('dates/calendars/gregorian/dateTimeFormats');
return [
getFormats(dateFormats),
getFormats(timeFormats),
getFormats(dateTimeFormats)
];
} | javascript | function getDateTimeFormats(localeData) {
function getFormats(data) {
return removeDuplicates([
data.short._value || data.short,
data.medium._value || data.medium,
data.long._value || data.long,
data.full._value || data.full
]);
}
const dateFormats = localeData.main('dates/calendars/gregorian/dateFormats');
const timeFormats = localeData.main('dates/calendars/gregorian/timeFormats');
const dateTimeFormats = localeData.main('dates/calendars/gregorian/dateTimeFormats');
return [
getFormats(dateFormats),
getFormats(timeFormats),
getFormats(dateTimeFormats)
];
} | [
"function",
"getDateTimeFormats",
"(",
"localeData",
")",
"{",
"function",
"getFormats",
"(",
"data",
")",
"{",
"return",
"removeDuplicates",
"(",
"[",
"data",
".",
"short",
".",
"_value",
"||",
"data",
".",
"short",
",",
"data",
".",
"medium",
".",
"_value",
"||",
"data",
".",
"medium",
",",
"data",
".",
"long",
".",
"_value",
"||",
"data",
".",
"long",
",",
"data",
".",
"full",
".",
"_value",
"||",
"data",
".",
"full",
"]",
")",
";",
"}",
"const",
"dateFormats",
"=",
"localeData",
".",
"main",
"(",
"'dates/calendars/gregorian/dateFormats'",
")",
";",
"const",
"timeFormats",
"=",
"localeData",
".",
"main",
"(",
"'dates/calendars/gregorian/timeFormats'",
")",
";",
"const",
"dateTimeFormats",
"=",
"localeData",
".",
"main",
"(",
"'dates/calendars/gregorian/dateTimeFormats'",
")",
";",
"return",
"[",
"getFormats",
"(",
"dateFormats",
")",
",",
"getFormats",
"(",
"timeFormats",
")",
",",
"getFormats",
"(",
"dateTimeFormats",
")",
"]",
";",
"}"
]
| Returns date, time and dateTime formats for a locale
@returns [dateFormats, timeFormats, dateTimeFormats]
each format: [ short, medium, long, full ] | [
"Returns",
"date",
"time",
"and",
"dateTime",
"formats",
"for",
"a",
"locale"
]
| c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/extract.js#L349-L368 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.