language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function quest_extender(state) {
ConfigManager.isQuestExtended(state);
if (ConfigManager.pan_moon_quest_extend == true) {
return $(".quest_extendable").addClass("squish");
}
return $(".quest_extendable").removeClass("squish");
} | function quest_extender(state) {
ConfigManager.isQuestExtended(state);
if (ConfigManager.pan_moon_quest_extend == true) {
return $(".quest_extendable").addClass("squish");
}
return $(".quest_extendable").removeClass("squish");
} |
JavaScript | function ExpedTabUpdateConfig() {
var conf = ExpedTabValidateConfig();
conf.fleetConf[ selectedFleet ].expedition = selectedExpedition;
conf.expedConf[ selectedExpedition ].greatSuccess = plannerIsGreatSuccess;
localStorage.expedTab = JSON.stringify( conf );
} | function ExpedTabUpdateConfig() {
var conf = ExpedTabValidateConfig();
conf.fleetConf[ selectedFleet ].expedition = selectedExpedition;
conf.expedConf[ selectedExpedition ].greatSuccess = plannerIsGreatSuccess;
localStorage.expedTab = JSON.stringify( conf );
} |
JavaScript | function ExpedTabApplyConfig() {
var conf = ExpedTabValidateConfig();
selectedExpedition = conf.fleetConf[selectedFleet].expedition;
plannerIsGreatSuccess = conf.expedConf[ selectedExpedition ].greatSuccess;
} | function ExpedTabApplyConfig() {
var conf = ExpedTabValidateConfig();
selectedExpedition = conf.fleetConf[selectedFleet].expedition;
plannerIsGreatSuccess = conf.expedConf[ selectedExpedition ].greatSuccess;
} |
JavaScript | init() {
this.defineSorters();
this.sorters = [{name:"repair_docking", reverse:false}];
this.showListRowCallback = this.showShipDockingStatus;
this.pageNo = true;
} | init() {
this.defineSorters();
this.sorters = [{name:"repair_docking", reverse:false}];
this.showListRowCallback = this.showShipDockingStatus;
this.pageNo = true;
} |
JavaScript | reload() {
ConfigManager.load();
// Load latest states of ships and repair docks
PlayerManager.loadFleets();
KC3ShipManager.load();
this.cachedDockingShips = PlayerManager.getCachedDockingShips();
// Prepare damaged ship list
this.prepareShipList(true, this.mapShipDockingStatus,
(shipObj) => shipObj.hp[0] !== shipObj.hp[1]);
// For detecting ships in expedition fleets
this.expeditionFleets = [];
$.each(PlayerManager.fleets, (index, fleet) => {
const missionState = fleet.mission[0];
// this fleet is either on expedition or being forced back
// thus cannot be repaired for now
if (missionState == 1 ||
missionState == 3) {
this.expeditionFleets.push(index);
}
});
// For detecting ships covered by Akashi repairing
this.anchoredShips = this.getAnchoredShips();
} | reload() {
ConfigManager.load();
// Load latest states of ships and repair docks
PlayerManager.loadFleets();
KC3ShipManager.load();
this.cachedDockingShips = PlayerManager.getCachedDockingShips();
// Prepare damaged ship list
this.prepareShipList(true, this.mapShipDockingStatus,
(shipObj) => shipObj.hp[0] !== shipObj.hp[1]);
// For detecting ships in expedition fleets
this.expeditionFleets = [];
$.each(PlayerManager.fleets, (index, fleet) => {
const missionState = fleet.mission[0];
// this fleet is either on expedition or being forced back
// thus cannot be repaired for now
if (missionState == 1 ||
missionState == 3) {
this.expeditionFleets.push(index);
}
});
// For detecting ships covered by Akashi repairing
this.anchoredShips = this.getAnchoredShips();
} |
JavaScript | execute() {
// Get latest data even clicking on tab
this.reload();
this.shipListDiv = $(".tab_docking .ship_list");
this.shipRowTemplateDiv = $(".tab_docking .factory .ship_item");
this.registerShipListHeaderEvent(
$(".tab_docking .ship_header .ship_field.hover")
);
this.showListGrid();
} | execute() {
// Get latest data even clicking on tab
this.reload();
this.shipListDiv = $(".tab_docking .ship_list");
this.shipRowTemplateDiv = $(".tab_docking .factory .ship_item");
this.registerShipListHeaderEvent(
$(".tab_docking .ship_header .ship_field.hover")
);
this.showListGrid();
} |
JavaScript | invalidateResult() {
if ($(".control_box.calc").hasClass("out_of_sync"))
return;
if ($(".tab_expedscorer .results").is(":visible") ) {
$(".control_box.calc").addClass("out_of_sync");
$(".control_box.calc button.calc")
.attr("title","Settings may have been changed, please re-calculate");
}
} | invalidateResult() {
if ($(".control_box.calc").hasClass("out_of_sync"))
return;
if ($(".tab_expedscorer .results").is(":visible") ) {
$(".control_box.calc").addClass("out_of_sync");
$(".control_box.calc button.calc")
.attr("title","Settings may have been changed, please re-calculate");
}
} |
JavaScript | function asyncGenerateConfigFromHistory( onSuccess, baseConfig ) {
let config = {};
let expedIds = allExpedIds;
// "completedFlag[eId-1] = true" means querying for "eId" is done.
let completedFlag = expedIds.map( () => false );
expedIds.map( function(eId) {
// query for most recent 5 records of the current user.
KC3Database.con.expedition
.where("mission").equals(eId)
.and( x => x.hq === PlayerManager.hq.id )
.reverse()
.limit(5)
.toArray(function(xs) {
if (xs.length === 0) {
completedFlag[eId-1] = true;
} else {
let gsCount = xs.filter( x => x.data.api_clear_result === 2).length;
// require great success if over half of the past 5 expeds are GS
// gsCount >= xs.length / 2
// => gsCount * 2 >= xs.length
let needGS = gsCount * 2 >= xs.length;
let countDaihatsu = expedRecord => {
let onlyDaihatsu = x => [68,193].indexOf(x) !== -1;
let ys = Array.isArray(expedRecord.fleet) ?
expedRecord.fleet.map( function(shipRecord) {
let dhtCount = 0;
// Kinu K2
if (shipRecord.mst_id === 487)
dhtCount += 1;
dhtCount += (shipRecord.equip || []).filter( onlyDaihatsu ).length;
return dhtCount;
}) : [];
return ys.reduce( (a,b) => a+b, 0 );
};
let countShips = expedRecord => {
return expedRecord.fleet.length || 0;
};
let daihatsuCountsFromHist = xs.map( countDaihatsu );
let daihatsuCount = saturate( Math.max.apply(undefined,daihatsuCountsFromHist) , 0, 4);
let shipCountsFromHist = xs.map( countShips );
let shipCount = saturate( Math.max.apply(undefined,shipCountsFromHist) , 1, 6);
let minCompo = ExpedMinCompo.getMinimumComposition(eId);
// we don't need to enforce ship count if it's already the minimal requirement
if (shipCount <= minCompo.length)
shipCount = false;
config[eId] = {
modifier: {
type: "normal",
gs: needGS,
daihatsu: daihatsuCount
},
cost: {
type: "costmodel",
wildcard: shipCount === false ? false : "DD",
count: shipCount === false ? 0 : shipCount
}
};
completedFlag[eId-1] = true;
}
if (completedFlag.some( x => x === false ))
return;
// finally fill in missing fields
onSuccess( $.extend( baseConfig, config ) );
});
});
} | function asyncGenerateConfigFromHistory( onSuccess, baseConfig ) {
let config = {};
let expedIds = allExpedIds;
// "completedFlag[eId-1] = true" means querying for "eId" is done.
let completedFlag = expedIds.map( () => false );
expedIds.map( function(eId) {
// query for most recent 5 records of the current user.
KC3Database.con.expedition
.where("mission").equals(eId)
.and( x => x.hq === PlayerManager.hq.id )
.reverse()
.limit(5)
.toArray(function(xs) {
if (xs.length === 0) {
completedFlag[eId-1] = true;
} else {
let gsCount = xs.filter( x => x.data.api_clear_result === 2).length;
// require great success if over half of the past 5 expeds are GS
// gsCount >= xs.length / 2
// => gsCount * 2 >= xs.length
let needGS = gsCount * 2 >= xs.length;
let countDaihatsu = expedRecord => {
let onlyDaihatsu = x => [68,193].indexOf(x) !== -1;
let ys = Array.isArray(expedRecord.fleet) ?
expedRecord.fleet.map( function(shipRecord) {
let dhtCount = 0;
// Kinu K2
if (shipRecord.mst_id === 487)
dhtCount += 1;
dhtCount += (shipRecord.equip || []).filter( onlyDaihatsu ).length;
return dhtCount;
}) : [];
return ys.reduce( (a,b) => a+b, 0 );
};
let countShips = expedRecord => {
return expedRecord.fleet.length || 0;
};
let daihatsuCountsFromHist = xs.map( countDaihatsu );
let daihatsuCount = saturate( Math.max.apply(undefined,daihatsuCountsFromHist) , 0, 4);
let shipCountsFromHist = xs.map( countShips );
let shipCount = saturate( Math.max.apply(undefined,shipCountsFromHist) , 1, 6);
let minCompo = ExpedMinCompo.getMinimumComposition(eId);
// we don't need to enforce ship count if it's already the minimal requirement
if (shipCount <= minCompo.length)
shipCount = false;
config[eId] = {
modifier: {
type: "normal",
gs: needGS,
daihatsu: daihatsuCount
},
cost: {
type: "costmodel",
wildcard: shipCount === false ? false : "DD",
count: shipCount === false ? 0 : shipCount
}
};
completedFlag[eId-1] = true;
}
if (completedFlag.some( x => x === false ))
return;
// finally fill in missing fields
onSuccess( $.extend( baseConfig, config ) );
});
});
} |
JavaScript | collectData(filters){
const DataCollector = new Worker(chrome.runtime.getURL('library/workers/graph-data.js'));
DataCollector.onmessage = (response) => {
if (response.data) {
this.refreshGraph(response.data);
} else {
this.loadingGraph = false;
$(".loading").hide();
$(".graph_title").text("Unable to render");
$(".graph_input").prop("disabled", false);
}
DataCollector.terminate();
};
DataCollector.postMessage(Object.assign({
url: chrome.runtime.getURL(""),
playerId: PlayerManager.hq.id
}, filters));
} | collectData(filters){
const DataCollector = new Worker(chrome.runtime.getURL('library/workers/graph-data.js'));
DataCollector.onmessage = (response) => {
if (response.data) {
this.refreshGraph(response.data);
} else {
this.loadingGraph = false;
$(".loading").hide();
$(".graph_title").text("Unable to render");
$(".graph_input").prop("disabled", false);
}
DataCollector.terminate();
};
DataCollector.postMessage(Object.assign({
url: chrome.runtime.getURL(""),
playerId: PlayerManager.hq.id
}, filters));
} |
JavaScript | refreshGraph(data){
$(".loading").hide();
// Show graph title dates
$(".graph_title").text(
new Date($("#startDate").val()).toLocaleString(this.locale, this.dateOptions)
+" ~ "
+new Date($("#endDate").val() + " 00:00:00").toLocaleString(this.locale, this.dateOptions)
);
// Ability to hide types
this.graphableItems.dbkey.forEach(function(dbkey, ind){
if (!$(".legend_toggle input[data-type=\""+dbkey+"\"]").prop("checked")) {
delete data.datasets[dbkey];
}
});
// New chart JS only accepts an array, not object
data.datasets = Object.keys(data.datasets).map(key => data.datasets[key]);
console.debug("Graph datasets", data.datasets);
// Draw graph
this.ctx = $("#chart").get(0).getContext("2d");
if (this.chart) this.chart.destroy();
this.chart = new Chart(this.ctx, {
type: 'line',
data: data,
options: {
legend: { display: false },
tooltips: {
enabled: $("#showTooltips").prop("checked"),
mode: "index",
intersect: false
},
scales: { yAxes: [{ ticks: { beginAtZero: $("#startZero").prop("checked") } }] }
}
});
// Revert flags and input states
this.loadingGraph = false;
$(".graph_input").prop("disabled", false);
} | refreshGraph(data){
$(".loading").hide();
// Show graph title dates
$(".graph_title").text(
new Date($("#startDate").val()).toLocaleString(this.locale, this.dateOptions)
+" ~ "
+new Date($("#endDate").val() + " 00:00:00").toLocaleString(this.locale, this.dateOptions)
);
// Ability to hide types
this.graphableItems.dbkey.forEach(function(dbkey, ind){
if (!$(".legend_toggle input[data-type=\""+dbkey+"\"]").prop("checked")) {
delete data.datasets[dbkey];
}
});
// New chart JS only accepts an array, not object
data.datasets = Object.keys(data.datasets).map(key => data.datasets[key]);
console.debug("Graph datasets", data.datasets);
// Draw graph
this.ctx = $("#chart").get(0).getContext("2d");
if (this.chart) this.chart.destroy();
this.chart = new Chart(this.ctx, {
type: 'line',
data: data,
options: {
legend: { display: false },
tooltips: {
enabled: $("#showTooltips").prop("checked"),
mode: "index",
intersect: false
},
scales: { yAxes: [{ ticks: { beginAtZero: $("#startZero").prop("checked") } }] }
}
});
// Revert flags and input states
this.loadingGraph = false;
$(".graph_input").prop("disabled", false);
} |
JavaScript | function createPanel( theme ) {
chrome.devtools.panels.create("DevKC3Kai",
"../../assets/img/logo/16.png",
"pages/devtools/themes/" + theme + "/" + theme + ".html",
function(panel){}
);
} | function createPanel( theme ) {
chrome.devtools.panels.create("DevKC3Kai",
"../../assets/img/logo/16.png",
"pages/devtools/themes/" + theme + "/" + theme + ".html",
function(panel){}
);
} |
JavaScript | init() {
this.defaultSorterDefinitions();
this.defineSorter("materials", "Consumptions",
(ls, rs) => (rs.materials.length - rs.materialsUsed)
- (ls.materials.length - ls.materialsUsed)
|| rs.materials.length - ls.materials.length
|| ls.id - rs.id);
this.defineSimpleFilter("materials", [], 0, (fd, ship) => ship.materials.length);
this.defineSimpleFilter("hideUnlock", [], 0, (fd, ship) => !fd.currentIndex || !!ship.locked);
this.defineSimpleFilter("hideDupe", [], 0, (fd, ship) => {
if(!fd.currentIndex) return true;
const dupeShips = this.shipList.filter(s => (
ship.id !== s.id && RemodelDb.originOf(ship.masterId) === RemodelDb.originOf(s.masterId)
));
if(!dupeShips.length) return true;
const dupeRemodelLevels = dupeShips.map(s => RemodelDb.remodelGroup(s.masterId).indexOf(s.masterId));
const thisRemodelLevel = RemodelDb.remodelGroup(ship.masterId).indexOf(ship.masterId);
return thisRemodelLevel >= Math.max(...dupeRemodelLevels);
});
this.defineSimpleFilter("hideCompleted", [], 0, (fd, ship) => {
if(!fd.currentIndex) return true;
return ship.materials.filter(m => !m.used).length > 0;
});
this.showListRowCallback = this.showRemodelMaterials;
this.heartLockMode = 2;
this.viewType = "owned";
this.hideUnlock = false;
this.hideDupe = false;
this.hideCompleted = false;
} | init() {
this.defaultSorterDefinitions();
this.defineSorter("materials", "Consumptions",
(ls, rs) => (rs.materials.length - rs.materialsUsed)
- (ls.materials.length - ls.materialsUsed)
|| rs.materials.length - ls.materials.length
|| ls.id - rs.id);
this.defineSimpleFilter("materials", [], 0, (fd, ship) => ship.materials.length);
this.defineSimpleFilter("hideUnlock", [], 0, (fd, ship) => !fd.currentIndex || !!ship.locked);
this.defineSimpleFilter("hideDupe", [], 0, (fd, ship) => {
if(!fd.currentIndex) return true;
const dupeShips = this.shipList.filter(s => (
ship.id !== s.id && RemodelDb.originOf(ship.masterId) === RemodelDb.originOf(s.masterId)
));
if(!dupeShips.length) return true;
const dupeRemodelLevels = dupeShips.map(s => RemodelDb.remodelGroup(s.masterId).indexOf(s.masterId));
const thisRemodelLevel = RemodelDb.remodelGroup(ship.masterId).indexOf(ship.masterId);
return thisRemodelLevel >= Math.max(...dupeRemodelLevels);
});
this.defineSimpleFilter("hideCompleted", [], 0, (fd, ship) => {
if(!fd.currentIndex) return true;
return ship.materials.filter(m => !m.used).length > 0;
});
this.showListRowCallback = this.showRemodelMaterials;
this.heartLockMode = 2;
this.viewType = "owned";
this.hideUnlock = false;
this.hideDupe = false;
this.hideCompleted = false;
} |
JavaScript | execute() {
const joinPageParams = () => (
[this.viewType,
this.hideUnlock ? "locked" : (this.hideDupe || this.hideCompleted) && "all",
this.hideDupe ? "nodupe" : this.hideCompleted && "all",
this.hideCompleted && "nocompleted"
].filter(v => !!v)
);
$(".tab_blueprints .view_type input[type=radio][name=view_type]").on("change", (e) => {
this.viewType = $(".view_type input[type=radio][name=view_type]:checked").val();
KC3StrategyTabs.gotoTab(undefined, ...joinPageParams());
});
$(".tab_blueprints .view_type input[type=checkbox][name=hide_unlock]").on("change", (e) => {
this.hideUnlock = $(".view_type input[type=checkbox][name=hide_unlock]").prop("checked");
KC3StrategyTabs.gotoTab(undefined, ...joinPageParams());
});
$(".tab_blueprints .view_type input[type=checkbox][name=hide_dupe]").on("change", (e) => {
this.hideDupe = $(".view_type input[type=checkbox][name=hide_dupe]").prop("checked");
KC3StrategyTabs.gotoTab(undefined, ...joinPageParams());
});
$(".tab_blueprints .view_type input[type=checkbox][name=hide_completed]").on("change", (e) => {
this.hideCompleted = $(".view_type input[type=checkbox][name=hide_completed]").prop("checked");
KC3StrategyTabs.gotoTab(undefined, ...joinPageParams());
});
this.shipListDiv = $(".tab_blueprints .ship_list");
this.shipRowTemplateDiv = $(".tab_blueprints .factory .ship_item");
this.registerShipListHeaderEvent(
$(".tab_blueprints .ship_header .ship_field.hover")
);
this.shipListDiv.on("preShow", () => {
$(".tab_blueprints .total").hide();
$(".tab_blueprints .owned").hide();
});
this.shipListDiv.on("postShow", this.showTotalMaterials);
this.loadView(KC3StrategyTabs.pageParams[1],
KC3StrategyTabs.pageParams[2] === "locked",
KC3StrategyTabs.pageParams[3] === "nodupe",
KC3StrategyTabs.pageParams[4] === "nocompleted"
);
} | execute() {
const joinPageParams = () => (
[this.viewType,
this.hideUnlock ? "locked" : (this.hideDupe || this.hideCompleted) && "all",
this.hideDupe ? "nodupe" : this.hideCompleted && "all",
this.hideCompleted && "nocompleted"
].filter(v => !!v)
);
$(".tab_blueprints .view_type input[type=radio][name=view_type]").on("change", (e) => {
this.viewType = $(".view_type input[type=radio][name=view_type]:checked").val();
KC3StrategyTabs.gotoTab(undefined, ...joinPageParams());
});
$(".tab_blueprints .view_type input[type=checkbox][name=hide_unlock]").on("change", (e) => {
this.hideUnlock = $(".view_type input[type=checkbox][name=hide_unlock]").prop("checked");
KC3StrategyTabs.gotoTab(undefined, ...joinPageParams());
});
$(".tab_blueprints .view_type input[type=checkbox][name=hide_dupe]").on("change", (e) => {
this.hideDupe = $(".view_type input[type=checkbox][name=hide_dupe]").prop("checked");
KC3StrategyTabs.gotoTab(undefined, ...joinPageParams());
});
$(".tab_blueprints .view_type input[type=checkbox][name=hide_completed]").on("change", (e) => {
this.hideCompleted = $(".view_type input[type=checkbox][name=hide_completed]").prop("checked");
KC3StrategyTabs.gotoTab(undefined, ...joinPageParams());
});
this.shipListDiv = $(".tab_blueprints .ship_list");
this.shipRowTemplateDiv = $(".tab_blueprints .factory .ship_item");
this.registerShipListHeaderEvent(
$(".tab_blueprints .ship_header .ship_field.hover")
);
this.shipListDiv.on("preShow", () => {
$(".tab_blueprints .total").hide();
$(".tab_blueprints .owned").hide();
});
this.shipListDiv.on("postShow", this.showTotalMaterials);
this.loadView(KC3StrategyTabs.pageParams[1],
KC3StrategyTabs.pageParams[2] === "locked",
KC3StrategyTabs.pageParams[3] === "nodupe",
KC3StrategyTabs.pageParams[4] === "nocompleted"
);
} |
JavaScript | function goalTemplateSwap(index1,index2) {
if (Math.abs(index1 - index2) == 1) {
if (index2 >= 0 && index2 < self.goalTemplates.length) {
// swap data
var tmp = self.goalTemplates[index1];
self.goalTemplates[index1] = self.goalTemplates[index2];
self.goalTemplates[index2] = tmp;
GoalTemplateManager.save( self.goalTemplates );
// setup UI
var cs = $(".box_goal_templates").children();
goalTemplateSetupUI(self.goalTemplates[index1],
$(cs[index1]) );
goalTemplateShow(cs[index1]);
goalTemplateSetupUI(self.goalTemplates[index2],
$(cs[index2]));
goalTemplateShow(cs[index2]);
}
}
} | function goalTemplateSwap(index1,index2) {
if (Math.abs(index1 - index2) == 1) {
if (index2 >= 0 && index2 < self.goalTemplates.length) {
// swap data
var tmp = self.goalTemplates[index1];
self.goalTemplates[index1] = self.goalTemplates[index2];
self.goalTemplates[index2] = tmp;
GoalTemplateManager.save( self.goalTemplates );
// setup UI
var cs = $(".box_goal_templates").children();
goalTemplateSetupUI(self.goalTemplates[index1],
$(cs[index1]) );
goalTemplateShow(cs[index1]);
goalTemplateSetupUI(self.goalTemplates[index2],
$(cs[index2]));
goalTemplateShow(cs[index2]);
}
}
} |
JavaScript | async create (data, params) {
//AUTHORIZATION CHECK
if(params.user.role !== "admin"){
let forbidden = new errors.Forbidden("NOT AUTHORIZED!", {
params: params.user.role
});
return Promise.reject(forbidden);
}
if (Array.isArray(data)) {
return await Promise.all(data.map(current => this.create(current)));
}
let url = this.options.url;
let init = Object.assign({}, this.options.init);
let query = {
"from": _.get(params, "query.from", "none").toLowerCase(),
"to": _.get(params, "query.to", "none").toLowerCase()
};
let statement = "";
let sBuffer = {
match: "",
where: "",
create: "CREATE (n1:node $data) ",
return: "RETURN n1 "
};
if(_.has(data, "label")){
data.name = result.label;
delete result.label;
}
if(query.from !== "none" && query.to !== "none"){
data.to = query.to;
data.from = query.from;
sBuffer.match = "MATCH (n1:node), (n2:node) ";
sBuffer.where = "WHERE n1.id = $data.from AND n2.id = $data.to ";
sBuffer.create = "CREATE (n1)-[r:dependency $data]->(n2) ";
sBuffer.return = "RETURN r";
}else{
data.id = uuidv4();
}
statement = sBuffer.match+sBuffer.where+sBuffer.create+sBuffer.return;
try{
init.body = JSON.stringify({
statements: [{
statement: statement,
parameters: {data: data}
}]
});
}catch(e){
let badRequest = new errors.BadRequest("Invalid JSON", {
params: e
});
return Promise.reject(badRequest);
}
let res = await fetch(url, init);
let resData = await res.json();
if(_.get(resData, "errors", 0).length > 0){
let badRequest = new errors.BadRequest("http 400 bad request", {
params: params.query
});
return Promise.reject(badRequest);
}
let result = _.get(resData, "results[0].data[0].row[0]", {});
if(_.has(result, "name")){
result.label = result.name;
delete result.name;
}
return result;
} | async create (data, params) {
//AUTHORIZATION CHECK
if(params.user.role !== "admin"){
let forbidden = new errors.Forbidden("NOT AUTHORIZED!", {
params: params.user.role
});
return Promise.reject(forbidden);
}
if (Array.isArray(data)) {
return await Promise.all(data.map(current => this.create(current)));
}
let url = this.options.url;
let init = Object.assign({}, this.options.init);
let query = {
"from": _.get(params, "query.from", "none").toLowerCase(),
"to": _.get(params, "query.to", "none").toLowerCase()
};
let statement = "";
let sBuffer = {
match: "",
where: "",
create: "CREATE (n1:node $data) ",
return: "RETURN n1 "
};
if(_.has(data, "label")){
data.name = result.label;
delete result.label;
}
if(query.from !== "none" && query.to !== "none"){
data.to = query.to;
data.from = query.from;
sBuffer.match = "MATCH (n1:node), (n2:node) ";
sBuffer.where = "WHERE n1.id = $data.from AND n2.id = $data.to ";
sBuffer.create = "CREATE (n1)-[r:dependency $data]->(n2) ";
sBuffer.return = "RETURN r";
}else{
data.id = uuidv4();
}
statement = sBuffer.match+sBuffer.where+sBuffer.create+sBuffer.return;
try{
init.body = JSON.stringify({
statements: [{
statement: statement,
parameters: {data: data}
}]
});
}catch(e){
let badRequest = new errors.BadRequest("Invalid JSON", {
params: e
});
return Promise.reject(badRequest);
}
let res = await fetch(url, init);
let resData = await res.json();
if(_.get(resData, "errors", 0).length > 0){
let badRequest = new errors.BadRequest("http 400 bad request", {
params: params.query
});
return Promise.reject(badRequest);
}
let result = _.get(resData, "results[0].data[0].row[0]", {});
if(_.has(result, "name")){
result.label = result.name;
delete result.name;
}
return result;
} |
JavaScript | function generateTests(type, filePath, ast) {
var str = getImportsString(type, filePath);
ast.body.forEach(function(node) {
str += generateUnitTest(type, node.id.name, node.comment.ast.tags);
});
return str;
} | function generateTests(type, filePath, ast) {
var str = getImportsString(type, filePath);
ast.body.forEach(function(node) {
str += generateUnitTest(type, node.id.name, node.comment.ast.tags);
});
return str;
} |
JavaScript | function generateUnitTest(type, name, tags) {
var args = tags.filter(function(tag) {
return tag.title !== 'return';
});
var returnTag = _.find(tags, { title: 'return' });
// TODO remove this once generative testing is more robust
if (_.isUndefined(returnTag)) {
console.warn('~~~ Function ' + name + ' does not return anything. Skipping...');
return '';
}
var data = {
PRIMITIVE_TYPES: coreUtils.PRIMITIVE_TYPES,
name: name,
testImportName: TEST_IMPORT_NAME,
returnType: coreUtils.getTagSchemaType(returnTag, javaScriptSchema),
genTypes: getGenerativeTypesString(args),
paramNames: getNamesString(args),
paramTypes: getTypesString(args)
};
var filePath = '';
var unitTest = '';
switch (type) {
case TEST_FRAMEWORKS.JASMINE:
case TEST_FRAMEWORKS.JEST:
filePath = 'lib/templates/test/bdd-unit-test.ejs';
break;
case TEST_FRAMEWORKS.AVA:
filePath = 'lib/templates/test/ava-unit-test.ejs';
break;
case TEST_FRAMEWORKS.MOCHA:
filePath = 'lib/templates/test/mocha-unit-test.ejs';
break;
default:
throw new Error('Unsupported testing framework ' + type + ' found. Aborting...');
}
ejs.renderFile(filePath, data, null, function(err, str) {
if (err) {
throw new Error(err);
}
unitTest = str;
});
return unitTest;
} | function generateUnitTest(type, name, tags) {
var args = tags.filter(function(tag) {
return tag.title !== 'return';
});
var returnTag = _.find(tags, { title: 'return' });
// TODO remove this once generative testing is more robust
if (_.isUndefined(returnTag)) {
console.warn('~~~ Function ' + name + ' does not return anything. Skipping...');
return '';
}
var data = {
PRIMITIVE_TYPES: coreUtils.PRIMITIVE_TYPES,
name: name,
testImportName: TEST_IMPORT_NAME,
returnType: coreUtils.getTagSchemaType(returnTag, javaScriptSchema),
genTypes: getGenerativeTypesString(args),
paramNames: getNamesString(args),
paramTypes: getTypesString(args)
};
var filePath = '';
var unitTest = '';
switch (type) {
case TEST_FRAMEWORKS.JASMINE:
case TEST_FRAMEWORKS.JEST:
filePath = 'lib/templates/test/bdd-unit-test.ejs';
break;
case TEST_FRAMEWORKS.AVA:
filePath = 'lib/templates/test/ava-unit-test.ejs';
break;
case TEST_FRAMEWORKS.MOCHA:
filePath = 'lib/templates/test/mocha-unit-test.ejs';
break;
default:
throw new Error('Unsupported testing framework ' + type + ' found. Aborting...');
}
ejs.renderFile(filePath, data, null, function(err, str) {
if (err) {
throw new Error(err);
}
unitTest = str;
});
return unitTest;
} |
JavaScript | function ObjectType(tag) {
var str = 'Object';
if (tag.type.expression.type === 'TypeApplication') {
str = 'Array';
}
return str;
} | function ObjectType(tag) {
var str = 'Object';
if (tag.type.expression.type === 'TypeApplication') {
str = 'Array';
}
return str;
} |
JavaScript | function UnionType(tag) {
// TODO recurse through getTestCheckTypeString for possible complex unions
return tag.type.elements.reduce(function(str, element, index) {
if (index === tag.type.elements.length - 1) {
return str + element.name;
} else {
return str + element.name + ', ';
}
}, '');
} | function UnionType(tag) {
// TODO recurse through getTestCheckTypeString for possible complex unions
return tag.type.elements.reduce(function(str, element, index) {
if (index === tag.type.elements.length - 1) {
return str + element.name;
} else {
return str + element.name + ', ';
}
}, '');
} |
JavaScript | function parseComments(comment) {
var ast = doctrine.parse(comment.value, {
sloppy: true,
tags: ALLOWED_TAGS,
unwrap: true
});
// grab all jsDoc object params
var objects = ast.tags.filter(function(tag) {
return getTagSchemaType(tag, isObjectSchema);
});
objects.forEach(function(object) {
var propRegExp = new RegExp(object.name + '(\\[\\])?\\.');
// grab all jsDoc object params with property params
var props = ast.tags.filter(function(tag) {
return tag.name && propRegExp.test(tag.name);
});
ast.tags = _.difference(ast.tags, props);
// remove object name and dot from the @param name
props = props.map(function(tag) {
tag.name = tag.name.replace(propRegExp, '');
return tag;
});
// normalize the object property AST
object.type = {
type: 'ObjectType',
expression: {
type: object.type.type,
name: 'object'
},
applications: props
};
});
return ast;
} | function parseComments(comment) {
var ast = doctrine.parse(comment.value, {
sloppy: true,
tags: ALLOWED_TAGS,
unwrap: true
});
// grab all jsDoc object params
var objects = ast.tags.filter(function(tag) {
return getTagSchemaType(tag, isObjectSchema);
});
objects.forEach(function(object) {
var propRegExp = new RegExp(object.name + '(\\[\\])?\\.');
// grab all jsDoc object params with property params
var props = ast.tags.filter(function(tag) {
return tag.name && propRegExp.test(tag.name);
});
ast.tags = _.difference(ast.tags, props);
// remove object name and dot from the @param name
props = props.map(function(tag) {
tag.name = tag.name.replace(propRegExp, '');
return tag;
});
// normalize the object property AST
object.type = {
type: 'ObjectType',
expression: {
type: object.type.type,
name: 'object'
},
applications: props
};
});
return ast;
} |
JavaScript | function writeFile(filePath, fileStr) {
var dirPath = '';
filePath
.split(path.sep)
.slice(0, -1)
.forEach(function(dir) {
dirPath = path.join(dirPath, dir);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath);
}
});
fs.writeFileSync(filePath, fileStr);
} | function writeFile(filePath, fileStr) {
var dirPath = '';
filePath
.split(path.sep)
.slice(0, -1)
.forEach(function(dir) {
dirPath = path.join(dirPath, dir);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath);
}
});
fs.writeFileSync(filePath, fileStr);
} |
JavaScript | function ObjectType(tag) {
var str = '';
if (tag.type.expression.type === 'OptionalType') {
str = '?'
}
str += ': ';
if (tag.type.expression.type === 'TypeApplication') {
str += 'Array<' + getFlowObjectString(tag) + '>';
} else {
str += getFlowObjectString(tag);
}
return str;
} | function ObjectType(tag) {
var str = '';
if (tag.type.expression.type === 'OptionalType') {
str = '?'
}
str += ': ';
if (tag.type.expression.type === 'TypeApplication') {
str += 'Array<' + getFlowObjectString(tag) + '>';
} else {
str += getFlowObjectString(tag);
}
return str;
} |
JavaScript | function OptionalType(tag) {
var str = '';
// array optional?
// this will never be an object because Gouda creates
// the object AST, and will flag object OptionalTypes
// to be handled as ObjectTypes
if (tag.type.expression.type === 'TypeApplication') {
str = '?: Array<' + tag.type.expression.applications[0].name + '>';
} else {
str = '?: ' + tag.type.expression.name;
}
if (tag.default) {
str += ' = ' + tag.default;
}
return str;
} | function OptionalType(tag) {
var str = '';
// array optional?
// this will never be an object because Gouda creates
// the object AST, and will flag object OptionalTypes
// to be handled as ObjectTypes
if (tag.type.expression.type === 'TypeApplication') {
str = '?: Array<' + tag.type.expression.applications[0].name + '>';
} else {
str = '?: ' + tag.type.expression.name;
}
if (tag.default) {
str += ' = ' + tag.default;
}
return str;
} |
JavaScript | function UnionType(tag) {
return tag.type.elements.reduce(function(str, element, index) {
var name = '';
if (element.type === 'TypeApplication') {
// bit of a hack - re-use the TypeApplication function
// for complex UnionTypes, but remove the unwanted bits
name = TypeApplication({ type: element }).replace(': ', '');
} else {
name = element.name;
}
if (index === tag.type.elements.length - 1) {
return str + name;
} else {
return str + name + ' | ';
}
}, ': ');
} | function UnionType(tag) {
return tag.type.elements.reduce(function(str, element, index) {
var name = '';
if (element.type === 'TypeApplication') {
// bit of a hack - re-use the TypeApplication function
// for complex UnionTypes, but remove the unwanted bits
name = TypeApplication({ type: element }).replace(': ', '');
} else {
name = element.name;
}
if (index === tag.type.elements.length - 1) {
return str + name;
} else {
return str + name + ' | ';
}
}, ': ');
} |
JavaScript | function ObjectType(tag) {
var str = 'object';
if (tag.type.expression.type === 'TypeApplication') {
return 'array of objects';
}
return str;
} | function ObjectType(tag) {
var str = 'object';
if (tag.type.expression.type === 'TypeApplication') {
return 'array of objects';
}
return str;
} |
JavaScript | function UnionType(tag) {
// TODO recurse through getTestCheckTypeString for possible complex unions
return tag.type.elements.reduce(function(str, element, index) {
if (index === tag.type.elements.length - 1) {
return str + element.name;
} else if (index === tag.type.elements.length - 2) {
return str + element.name + ' or ';
} else {
return str + element.name + ', ';
}
}, '');
} | function UnionType(tag) {
// TODO recurse through getTestCheckTypeString for possible complex unions
return tag.type.elements.reduce(function(str, element, index) {
if (index === tag.type.elements.length - 1) {
return str + element.name;
} else if (index === tag.type.elements.length - 2) {
return str + element.name + ' or ';
} else {
return str + element.name + ', ';
}
}, '');
} |
JavaScript | function addFlowTyping(file, ast) {
var typedFile = file;
var offset = 0;
// for each function expression
ast.body.forEach(function(node) {
var end = 0;
// for each jsDoc tag
node.comment.ast.tags.forEach(function(tag) {
// find corresponding ast data on the param
var param = _.find(node.params, { 'name': tag.name });
var tagType = coreUtils.getTagSchemaType(tag, flowSchema);
// set substring marker
if (tag.title === 'return') {
// find the closing parenthesis
end = typedFile.indexOf(')', _.last(node.params).end + offset) + 1;
// end = _.last(node.params).end + offset + 1;
} else {
end = param.end + offset;
}
// add param type
typedFile = typedFile.substr(0, end) + tagType + typedFile.substr(end);
// offset the file string by added param type substring
offset += tagType.length;
});
});
// add flow annotation
return '// @flow\n' + typedFile;
} | function addFlowTyping(file, ast) {
var typedFile = file;
var offset = 0;
// for each function expression
ast.body.forEach(function(node) {
var end = 0;
// for each jsDoc tag
node.comment.ast.tags.forEach(function(tag) {
// find corresponding ast data on the param
var param = _.find(node.params, { 'name': tag.name });
var tagType = coreUtils.getTagSchemaType(tag, flowSchema);
// set substring marker
if (tag.title === 'return') {
// find the closing parenthesis
end = typedFile.indexOf(')', _.last(node.params).end + offset) + 1;
// end = _.last(node.params).end + offset + 1;
} else {
end = param.end + offset;
}
// add param type
typedFile = typedFile.substr(0, end) + tagType + typedFile.substr(end);
// offset the file string by added param type substring
offset += tagType.length;
});
});
// add flow annotation
return '// @flow\n' + typedFile;
} |
JavaScript | function addBlockComments(ast, comments) {
var astClone = _.cloneDeep(ast);
var blockComments = comments.filter(function(comment) { return comment.type === 'Block'; });
astClone.body = astClone.body
.filter(function(node) { return node.type === 'FunctionDeclaration'; })
.filter(function(node) {
var comment = _.find(blockComments, function(comment) { return comment.end === node.start - 1; });
if (comment) {
comment.ast = parseComments(comment);
node.comment = comment;
return true;
}
return false;
});
return astClone;
} | function addBlockComments(ast, comments) {
var astClone = _.cloneDeep(ast);
var blockComments = comments.filter(function(comment) { return comment.type === 'Block'; });
astClone.body = astClone.body
.filter(function(node) { return node.type === 'FunctionDeclaration'; })
.filter(function(node) {
var comment = _.find(blockComments, function(comment) { return comment.end === node.start - 1; });
if (comment) {
comment.ast = parseComments(comment);
node.comment = comment;
return true;
}
return false;
});
return astClone;
} |
JavaScript | function parseComments(comment) {
var ast = doctrine.parse(comment.value, {
sloppy: true,
tags: ALLOWED_TAGS,
unwrap: true
});
var objects = ast.tags.filter(function(tag) {
return tag.type.name && tag.type.name.toLowerCase() === 'object';
});
objects.forEach(function(object) {
var props = ast.tags.filter(function(tag) {
return tag.name.indexOf(object.name + '.') !== -1;
});
ast.tags = _.difference(ast.tags, props);
props = props.map(function(tag) {
tag.name = tag.name.replace(object.name + '.', '');
return tag;
});
object.type = {
type: 'TypeApplication',
expression: {
type: object.type.type,
name: object.type.name
},
applications: props
};
});
return ast;
} | function parseComments(comment) {
var ast = doctrine.parse(comment.value, {
sloppy: true,
tags: ALLOWED_TAGS,
unwrap: true
});
var objects = ast.tags.filter(function(tag) {
return tag.type.name && tag.type.name.toLowerCase() === 'object';
});
objects.forEach(function(object) {
var props = ast.tags.filter(function(tag) {
return tag.name.indexOf(object.name + '.') !== -1;
});
ast.tags = _.difference(ast.tags, props);
props = props.map(function(tag) {
tag.name = tag.name.replace(object.name + '.', '');
return tag;
});
object.type = {
type: 'TypeApplication',
expression: {
type: object.type.type,
name: object.type.name
},
applications: props
};
});
return ast;
} |
JavaScript | function addFlowTyping(file, ast) {
var typedFile = file;
var offset = 0;
ast.body.forEach(function(node) {
var end = 0;
node.comment.ast.tags.forEach(function(tag) {
var param = _.find(node.params, { 'name': tag.name });
var tagType = getTagType(tag);
// set substring marker
if (tag.title === 'return') {
// find the closing parenthesis
end = typedFile.indexOf(')', _.last(node.params).end + offset) + 1;
// end = _.last(node.params).end + offset + 1;
} else {
end = param.end + offset;
}
// add param type
typedFile = typedFile.substr(0, end) + tagType + typedFile.substr(end);
// offset the file string by added param type substring
offset += tagType.length;
});
});
// add flow annotation
return '// @flow\n' + typedFile;
} | function addFlowTyping(file, ast) {
var typedFile = file;
var offset = 0;
ast.body.forEach(function(node) {
var end = 0;
node.comment.ast.tags.forEach(function(tag) {
var param = _.find(node.params, { 'name': tag.name });
var tagType = getTagType(tag);
// set substring marker
if (tag.title === 'return') {
// find the closing parenthesis
end = typedFile.indexOf(')', _.last(node.params).end + offset) + 1;
// end = _.last(node.params).end + offset + 1;
} else {
end = param.end + offset;
}
// add param type
typedFile = typedFile.substr(0, end) + tagType + typedFile.substr(end);
// offset the file string by added param type substring
offset += tagType.length;
});
});
// add flow annotation
return '// @flow\n' + typedFile;
} |
JavaScript | function add_one_to_nine(clicked_id) {
change_font_size_if_over_20();
if (string_to_eval.length > 59) {
return;
}
number_val = clicked_id;
if (last_nums_in_string.charAt(0) === "0" && last_nums_in_string.length === 1) {
last_nums_in_string = "";
string_to_eval = string_to_eval.slice(0, -1);
string_to_eval += number_val;
last_nums_in_string += number_val;
convert_correct_symb();
answer_.innerHTML = answer_html;
//answer_.innerHTML = string_to_eval;
} else {
string_to_eval += number_val;
last_nums_in_string += number_val;
convert_correct_symb();
answer_.innerHTML = answer_html;
//answer_.innerHTML = string_to_eval;
}
} | function add_one_to_nine(clicked_id) {
change_font_size_if_over_20();
if (string_to_eval.length > 59) {
return;
}
number_val = clicked_id;
if (last_nums_in_string.charAt(0) === "0" && last_nums_in_string.length === 1) {
last_nums_in_string = "";
string_to_eval = string_to_eval.slice(0, -1);
string_to_eval += number_val;
last_nums_in_string += number_val;
convert_correct_symb();
answer_.innerHTML = answer_html;
//answer_.innerHTML = string_to_eval;
} else {
string_to_eval += number_val;
last_nums_in_string += number_val;
convert_correct_symb();
answer_.innerHTML = answer_html;
//answer_.innerHTML = string_to_eval;
}
} |
JavaScript | function check_stored_number() {
if (stored_number) {
answer_.innerHTML = "0";
stored_number = "";
} else {
return;
}
convert_correct_symb();
answer_.innerHTML = answer_html;
//answer_.innerHTML = string_to_eval;
} | function check_stored_number() {
if (stored_number) {
answer_.innerHTML = "0";
stored_number = "";
} else {
return;
}
convert_correct_symb();
answer_.innerHTML = answer_html;
//answer_.innerHTML = string_to_eval;
} |
JavaScript | function maybe_add_dot() {
if (string_to_eval.length > 59) {
return;
}
change_font_size_if_over_20();
if (last_nums_in_string.length === 0) {
return;
}
if (last_nums_in_string.indexOf(".") > -1) {
return;
} else {
string_to_eval += ".";
last_nums_in_string += ".";
}
convert_correct_symb();
answer_.innerHTML = answer_html;
//answer_.innerHTML = string_to_eval;
} | function maybe_add_dot() {
if (string_to_eval.length > 59) {
return;
}
change_font_size_if_over_20();
if (last_nums_in_string.length === 0) {
return;
}
if (last_nums_in_string.indexOf(".") > -1) {
return;
} else {
string_to_eval += ".";
last_nums_in_string += ".";
}
convert_correct_symb();
answer_.innerHTML = answer_html;
//answer_.innerHTML = string_to_eval;
} |
JavaScript | function validatorHandler(schema, property) {
return (req, res, next) => {
/**
* req[property] gets the data that is sent depending the kind of request
* it can be body, params or query
*
* {abortEarly: false} let you check the hole error before send it
*/
const data = req[property]
const { error } = schema.validate(data, { abortEarly: false })
if (error) next(boom.badRequest(error))
next()
}
} | function validatorHandler(schema, property) {
return (req, res, next) => {
/**
* req[property] gets the data that is sent depending the kind of request
* it can be body, params or query
*
* {abortEarly: false} let you check the hole error before send it
*/
const data = req[property]
const { error } = schema.validate(data, { abortEarly: false })
if (error) next(boom.badRequest(error))
next()
}
} |
JavaScript | pagination(resPerPage) {
const currentPage = Number(this.queryStr.page) || 1;
const skip = resPerPage * (currentPage - 1);
this.query = this.query.limit(resPerPage).skip(skip);
return this;
} | pagination(resPerPage) {
const currentPage = Number(this.queryStr.page) || 1;
const skip = resPerPage * (currentPage - 1);
this.query = this.query.limit(resPerPage).skip(skip);
return this;
} |
JavaScript | async componentDidMount() {
console.log('StreamMedia', this.stream, this.userId);
let renderer;
const renderStream = async () => {
renderer = new Renderer(this.stream);
const view = await renderer.createView();
document.getElementById(`${this.userId}-${this.stream.type}-${this.stream.id}`).appendChild(view.target);
}
this.stream.on('availabilityChanged', async () => {
console.log(`EVENT, stream=${this.stream.type}, availabilityChanged=${this.stream.isAvailable}`);
if (this.stream.isAvailable) {
this.setState({ isAvailable: true });
await renderStream();
} else {
this.setState({ isAvailable: false });
renderer.dispose();
}
});
if (this.stream.isAvailable) {
this.setState({ isAvailable: true });
await renderStream();
}
} | async componentDidMount() {
console.log('StreamMedia', this.stream, this.userId);
let renderer;
const renderStream = async () => {
renderer = new Renderer(this.stream);
const view = await renderer.createView();
document.getElementById(`${this.userId}-${this.stream.type}-${this.stream.id}`).appendChild(view.target);
}
this.stream.on('availabilityChanged', async () => {
console.log(`EVENT, stream=${this.stream.type}, availabilityChanged=${this.stream.isAvailable}`);
if (this.stream.isAvailable) {
this.setState({ isAvailable: true });
await renderStream();
} else {
this.setState({ isAvailable: false });
renderer.dispose();
}
});
if (this.stream.isAvailable) {
this.setState({ isAvailable: true });
await renderStream();
}
} |
JavaScript | controlGroup(settings) {
const group = $("<div>").addClass("control-group");
if (typeof settings.label === "string") {
group.append($("<label>").text(settings.label));
} else if (settings.label !== undefined) {
group.append($("<label>").append(settings.label));
}
return group;
} | controlGroup(settings) {
const group = $("<div>").addClass("control-group");
if (typeof settings.label === "string") {
group.append($("<label>").text(settings.label));
} else if (settings.label !== undefined) {
group.append($("<label>").append(settings.label));
}
return group;
} |
JavaScript | function Navbar() {
return (
<nav className="navbar navbar-expand-lg sticky-top">
<Link className="navbar-brand" to="/">
MERN Google Books Search
</Link>
<div>
<ul className="navbar-nav">
<li className="nav-item">
<Link
to="/search"
className={window.location.pathname === "/search" ? "nav-link active" : "nav-link"}
>
Search Books
</Link>
</li>
<li className="nav-item">
<Link
to="/saved"
className={window.location.pathname === "/saved" ? "nav-link active" : "nav-link"}
>
Saved
</Link>
</li>
</ul>
</div>
</nav>
);
} | function Navbar() {
return (
<nav className="navbar navbar-expand-lg sticky-top">
<Link className="navbar-brand" to="/">
MERN Google Books Search
</Link>
<div>
<ul className="navbar-nav">
<li className="nav-item">
<Link
to="/search"
className={window.location.pathname === "/search" ? "nav-link active" : "nav-link"}
>
Search Books
</Link>
</li>
<li className="nav-item">
<Link
to="/saved"
className={window.location.pathname === "/saved" ? "nav-link active" : "nav-link"}
>
Saved
</Link>
</li>
</ul>
</div>
</nav>
);
} |
JavaScript | function Card(props) {
return (
<Slide left>
<div className="row mb-5">
<div className="col-lg-12">
{/* map over the books from the books state that was passed down to create cards for each book in the array */}
{props.books.map(book => (
<div className="card mt-4" key={book._id ? book._id : book.googleBookId}>
<div className="card-body">
<h5 className="card-title">{book.title}</h5>
<h6 className="card-subtitle mb-2 text-muted">{book.subtitle}</h6>
<div className="media">
<img src={book.thumbnail} className="align-self-center mr-3" alt="Book cover"/>
<div className="media-body">
<h6 className="mt-0">{book.authors.join(', ')}</h6>
<p className="mb-0">{book.description}</p>
<p className="mb-2">
<small className="text-muted">Published: {book.publishedDate}</small>
</p>
</div>
</div>
<a className="btn btn-info mr-1 mt-2" href={book.link} target="_blank"
rel="noopener noreferrer">View Book</a>
<button className={props.buttonType}
onClick={props.buttonAction}
id={book._id ? book._id : book.googleBookId}
>
{props.buttonText}
</button>
</div>
</div>
))}
</div>
</div>
</Slide>
)
} | function Card(props) {
return (
<Slide left>
<div className="row mb-5">
<div className="col-lg-12">
{/* map over the books from the books state that was passed down to create cards for each book in the array */}
{props.books.map(book => (
<div className="card mt-4" key={book._id ? book._id : book.googleBookId}>
<div className="card-body">
<h5 className="card-title">{book.title}</h5>
<h6 className="card-subtitle mb-2 text-muted">{book.subtitle}</h6>
<div className="media">
<img src={book.thumbnail} className="align-self-center mr-3" alt="Book cover"/>
<div className="media-body">
<h6 className="mt-0">{book.authors.join(', ')}</h6>
<p className="mb-0">{book.description}</p>
<p className="mb-2">
<small className="text-muted">Published: {book.publishedDate}</small>
</p>
</div>
</div>
<a className="btn btn-info mr-1 mt-2" href={book.link} target="_blank"
rel="noopener noreferrer">View Book</a>
<button className={props.buttonType}
onClick={props.buttonAction}
id={book._id ? book._id : book.googleBookId}
>
{props.buttonText}
</button>
</div>
</div>
))}
</div>
</div>
</Slide>
)
} |
JavaScript | function displayCustomGroups () {
if ($everyone[0].checked) {
$custom.fadeOut()
} else {
$custom.fadeIn()
}
} | function displayCustomGroups () {
if ($everyone[0].checked) {
$custom.fadeOut()
} else {
$custom.fadeIn()
}
} |
JavaScript | function displayBlacklist () {
if ($blacklistCheck[0].checked) {
$blacklistForm.fadeIn()
} else {
$blacklistForm.fadeOut()
}
} | function displayBlacklist () {
if ($blacklistCheck[0].checked) {
$blacklistForm.fadeIn()
} else {
$blacklistForm.fadeOut()
}
} |
JavaScript | function headerStyle() {
if($('.header-menu').length){
var windowpos = $(window).scrollTop();
var siteHeader = $('.header-menu');
var sticky_header = $('.fixed-header .sticky-header');
var scrollLink = $('.scroll-to-top');
if (windowpos > 1) {
siteHeader.addClass('fixed-header');
sticky_header.addClass("animated slideInDown")
scrollLink.fadeIn(300);
} else {
siteHeader.removeClass('fixed-header');
sticky_header.removeClass("animated slideInDown")
scrollLink.fadeOut(300);
}
}
} | function headerStyle() {
if($('.header-menu').length){
var windowpos = $(window).scrollTop();
var siteHeader = $('.header-menu');
var sticky_header = $('.fixed-header .sticky-header');
var scrollLink = $('.scroll-to-top');
if (windowpos > 1) {
siteHeader.addClass('fixed-header');
sticky_header.addClass("animated slideInDown")
scrollLink.fadeIn(300);
} else {
siteHeader.removeClass('fixed-header');
sticky_header.removeClass("animated slideInDown")
scrollLink.fadeOut(300);
}
}
} |
JavaScript | function handlePreloader() {
if($('.preloader').length){
$('.preloader').delay(200).fadeOut(500);
}
} | function handlePreloader() {
if($('.preloader').length){
$('.preloader').delay(200).fadeOut(500);
}
} |
JavaScript | function headerStyle() {
if($('.main-header').length){
var windowpos = $(window).scrollTop();
var siteHeader = $('.main-header');
var sticky_header = $('.fixed-header .sticky-header');
var scrollLink = $('.scroll-to-top');
if (windowpos > 1) {
siteHeader.addClass('fixed-header');
sticky_header.addClass("animated slideInDown")
scrollLink.fadeIn(300);
} else {
siteHeader.removeClass('fixed-header');
sticky_header.removeClass("animated slideInDown")
scrollLink.fadeOut(300);
}
}
} | function headerStyle() {
if($('.main-header').length){
var windowpos = $(window).scrollTop();
var siteHeader = $('.main-header');
var sticky_header = $('.fixed-header .sticky-header');
var scrollLink = $('.scroll-to-top');
if (windowpos > 1) {
siteHeader.addClass('fixed-header');
sticky_header.addClass("animated slideInDown")
scrollLink.fadeIn(300);
} else {
siteHeader.removeClass('fixed-header');
sticky_header.removeClass("animated slideInDown")
scrollLink.fadeOut(300);
}
}
} |
JavaScript | function spaceMembershipTests(t, organization, space) {
t.test('Gets spaceMemberships', (t) => {
t.plan(2)
return space.getSpaceMemberships().then((response) => {
t.ok(response.sys, 'sys')
t.ok(response.items, 'fields')
})
})
t.test('Create spaceMembership with id', (t) => {
return organization
.createOrganizationInvitation({
email: '[email protected]',
firstName: 'Test',
lastName: 'User',
role: 'developer',
})
.then((response) => organization.getOrganizationInvitation(response.sys.id))
.then((invitation) =>
organization.getOrganizationMembership(invitation.sys.organizationMembership.sys.id)
)
.then((membership) => {
const id = generateRandomId('spaceMembership')
space.getRoles().then((roles) => {
return space
.createSpaceMembershipWithId(id, {
admin: false,
email: '[email protected]',
roles: [{ sys: { type: 'Link', linkType: 'Role', id: roles.items[0].sys.id } }],
})
.then((spaceMembership) => {
t.equals(spaceMembership.sys.id, id, 'id')
return spaceMembership.delete()
})
.then(() => {
// delete organization membership
membership.delete()
})
})
})
})
t.test('Create spaceMembership', (t) => {
return organization
.createOrganizationInvitation({
email: '[email protected]',
firstName: 'Test',
lastName: 'User',
role: 'developer',
})
.then((response) => organization.getOrganizationInvitation(response.sys.id))
.then((invitation) =>
organization.getOrganizationMembership(invitation.sys.organizationMembership.sys.id)
)
.then((membership) => {
space.getRoles().then((roles) => {
return space
.createSpaceMembership({
admin: false,
email: '[email protected]',
roles: [{ sys: { type: 'Link', linkType: 'Role', id: roles.items[0].sys.id } }],
})
.then((spaceMembership) => {
t.ok(spaceMembership.user, 'user')
t.notOk(spaceMembership.admin, 'admin')
t.equal(spaceMembership.sys.type, 'SpaceMembership', 'type')
return spaceMembership.delete()
})
.then(() => {
// delete organization membership
membership.delete()
})
})
})
})
} | function spaceMembershipTests(t, organization, space) {
t.test('Gets spaceMemberships', (t) => {
t.plan(2)
return space.getSpaceMemberships().then((response) => {
t.ok(response.sys, 'sys')
t.ok(response.items, 'fields')
})
})
t.test('Create spaceMembership with id', (t) => {
return organization
.createOrganizationInvitation({
email: '[email protected]',
firstName: 'Test',
lastName: 'User',
role: 'developer',
})
.then((response) => organization.getOrganizationInvitation(response.sys.id))
.then((invitation) =>
organization.getOrganizationMembership(invitation.sys.organizationMembership.sys.id)
)
.then((membership) => {
const id = generateRandomId('spaceMembership')
space.getRoles().then((roles) => {
return space
.createSpaceMembershipWithId(id, {
admin: false,
email: '[email protected]',
roles: [{ sys: { type: 'Link', linkType: 'Role', id: roles.items[0].sys.id } }],
})
.then((spaceMembership) => {
t.equals(spaceMembership.sys.id, id, 'id')
return spaceMembership.delete()
})
.then(() => {
// delete organization membership
membership.delete()
})
})
})
})
t.test('Create spaceMembership', (t) => {
return organization
.createOrganizationInvitation({
email: '[email protected]',
firstName: 'Test',
lastName: 'User',
role: 'developer',
})
.then((response) => organization.getOrganizationInvitation(response.sys.id))
.then((invitation) =>
organization.getOrganizationMembership(invitation.sys.organizationMembership.sys.id)
)
.then((membership) => {
space.getRoles().then((roles) => {
return space
.createSpaceMembership({
admin: false,
email: '[email protected]',
roles: [{ sys: { type: 'Link', linkType: 'Role', id: roles.items[0].sys.id } }],
})
.then((spaceMembership) => {
t.ok(spaceMembership.user, 'user')
t.notOk(spaceMembership.admin, 'admin')
t.equal(spaceMembership.sys.type, 'SpaceMembership', 'type')
return spaceMembership.delete()
})
.then(() => {
// delete organization membership
membership.delete()
})
})
})
})
} |
JavaScript | function buildCertificateObject(commonName, organization, organizationUnit, countryCode, keyPair) {
var cert = new org.pkijs.simpl.CERT();
setSerialNumber(cert, Date.now());
setSubject(cert, countryCode, organization, organizationUnit, commonName);
setIssuer(cert, countryCode, organization, organizationUnit, commonName);
setValidityPeriod(cert, new Date(), 730); // Good from today for 730 days
setEmptyExtensions(cert);
setCABit(cert, false);
setKeyUsage(cert, true, true, false, false, false, true, true); // digitalSignature, nonRepudiation, keyCertSign, cRLSign
setSignatureAlgorithm(cert, "1.2.840.113549.1.1.11"); // RSA with SHA-256
return setPublicKey(cert, keyPair.publicKey).
then(function() {return signCert(cert, "1.2.840.113549.1.1.11", keyPair.privateKey)}).
then(function() {return cert});
// Helper functions
function setSerialNumber(cert, serialNumber) {
cert.serialNumber = new org.pkijs.asn1.INTEGER({value: serialNumber});;
}
function setSubject(cert, countryCode, organization, organizationUnit, commonName) {
setEntity(cert.subject, countryCode, organization, organizationUnit, commonName);
}
function setIssuer(cert, countryCode, organization, organizationUnit, commonName) {
setEntity(cert.issuer, countryCode, organization, organizationUnit, commonName);
}
function setEntity(entity, countryCode, organization, organizationUnit, commonName) {
if (countryCode) {
entity.types_and_values.push(new org.pkijs.simpl.ATTR_TYPE_AND_VALUE({
type: "2.5.4.6", //countryCode
value: new org.pkijs.asn1.PRINTABLESTRING({value: countryCode})
}));
}
if (organization) {
entity.types_and_values.push(new org.pkijs.simpl.ATTR_TYPE_AND_VALUE({
type: "2.5.4.10", //Organization
value: new org.pkijs.asn1.PRINTABLESTRING({value: organization})
}));
}
if (organizationUnit) {
entity.types_and_values.push(new org.pkijs.simpl.ATTR_TYPE_AND_VALUE({
type: "2.5.4.11", //Organization Unit
value: new org.pkijs.asn1.PRINTABLESTRING({value: organizationUnit})
}));
}
if (commonName) {
entity.types_and_values.push(new org.pkijs.simpl.ATTR_TYPE_AND_VALUE({
type: "2.5.4.3", //commonName
value: new org.pkijs.asn1.PRINTABLESTRING({value: commonName})
}));
}
}
function setValidityPeriod(cert, startDate, durationInDays) {
// Normalize to midnight
var start = new Date(startDate);
start.setHours(0);
start.setMinutes(0);
start.setSeconds(0);
var end = new Date(start.getTime() + durationInDays * 24 * 60 * 60 * 1000);
cert.notBefore.value = start;
cert.notAfter.value = end;
}
function setEmptyExtensions(cert) {
cert.extensions = new Array();
}
function setCABit(cert, isCA) {
var basicConstraints = new org.pkijs.simpl.x509.BasicConstraints({
cA: isCA,
pathLenConstraint: 3
});
cert.extensions.push(new org.pkijs.simpl.EXTENSION({
extnID: "2.5.29.19",
critical: false,
extnValue: basicConstraints.toSchema().toBER(false),
parsedValue: basicConstraints
}));
}
function setKeyUsage(cert, digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement, keyCertSign, cRLSign) {
var keyUsageBits = new ArrayBuffer(1);
var keyUsageBytes = new Uint8Array(keyUsageBits);
keyUsageBytes[0] = 0;
if (digitalSignature) {keyUsageBytes[0] |= 0x80;}
if (nonRepudiation) {keyUsageBytes[0] |= 0x40;}
if (keyEncipherment) {keyUsageBytes[0] |= 0x20;}
if (dataEncipherment) {keyUsageBytes[0] |= 0x10;}
if (keyAgreement) {keyUsageBytes[0] |= 0x08;}
if (keyCertSign) {keyUsageBytes[0] |= 0x04;}
if (cRLSign) {keyUsageBytes[0] |= 0x02;}
var keyUsage = new org.pkijs.asn1.BITSTRING({value_hex: keyUsageBits});
cert.extensions.push(new org.pkijs.simpl.EXTENSION({
extnID: "2.5.29.15",
critical: false,
extnValue: keyUsage.toBER(false),
parsedValue: keyUsage
}));
}
function setSignatureAlgorithm(cert, oid) {
cert.signatureAlgorithm.algorithm_id = oid; // In tbsCert
}
function setPublicKey(cert, publicKey) {
return cert.subjectPublicKeyInfo.importKey(publicKey);
}
function signCert(cert, oid, privateKey) {
cert.signature.algorithm_id = oid; // In actual signature
return cert.sign(privateKey);
}
} | function buildCertificateObject(commonName, organization, organizationUnit, countryCode, keyPair) {
var cert = new org.pkijs.simpl.CERT();
setSerialNumber(cert, Date.now());
setSubject(cert, countryCode, organization, organizationUnit, commonName);
setIssuer(cert, countryCode, organization, organizationUnit, commonName);
setValidityPeriod(cert, new Date(), 730); // Good from today for 730 days
setEmptyExtensions(cert);
setCABit(cert, false);
setKeyUsage(cert, true, true, false, false, false, true, true); // digitalSignature, nonRepudiation, keyCertSign, cRLSign
setSignatureAlgorithm(cert, "1.2.840.113549.1.1.11"); // RSA with SHA-256
return setPublicKey(cert, keyPair.publicKey).
then(function() {return signCert(cert, "1.2.840.113549.1.1.11", keyPair.privateKey)}).
then(function() {return cert});
// Helper functions
function setSerialNumber(cert, serialNumber) {
cert.serialNumber = new org.pkijs.asn1.INTEGER({value: serialNumber});;
}
function setSubject(cert, countryCode, organization, organizationUnit, commonName) {
setEntity(cert.subject, countryCode, organization, organizationUnit, commonName);
}
function setIssuer(cert, countryCode, organization, organizationUnit, commonName) {
setEntity(cert.issuer, countryCode, organization, organizationUnit, commonName);
}
function setEntity(entity, countryCode, organization, organizationUnit, commonName) {
if (countryCode) {
entity.types_and_values.push(new org.pkijs.simpl.ATTR_TYPE_AND_VALUE({
type: "2.5.4.6", //countryCode
value: new org.pkijs.asn1.PRINTABLESTRING({value: countryCode})
}));
}
if (organization) {
entity.types_and_values.push(new org.pkijs.simpl.ATTR_TYPE_AND_VALUE({
type: "2.5.4.10", //Organization
value: new org.pkijs.asn1.PRINTABLESTRING({value: organization})
}));
}
if (organizationUnit) {
entity.types_and_values.push(new org.pkijs.simpl.ATTR_TYPE_AND_VALUE({
type: "2.5.4.11", //Organization Unit
value: new org.pkijs.asn1.PRINTABLESTRING({value: organizationUnit})
}));
}
if (commonName) {
entity.types_and_values.push(new org.pkijs.simpl.ATTR_TYPE_AND_VALUE({
type: "2.5.4.3", //commonName
value: new org.pkijs.asn1.PRINTABLESTRING({value: commonName})
}));
}
}
function setValidityPeriod(cert, startDate, durationInDays) {
// Normalize to midnight
var start = new Date(startDate);
start.setHours(0);
start.setMinutes(0);
start.setSeconds(0);
var end = new Date(start.getTime() + durationInDays * 24 * 60 * 60 * 1000);
cert.notBefore.value = start;
cert.notAfter.value = end;
}
function setEmptyExtensions(cert) {
cert.extensions = new Array();
}
function setCABit(cert, isCA) {
var basicConstraints = new org.pkijs.simpl.x509.BasicConstraints({
cA: isCA,
pathLenConstraint: 3
});
cert.extensions.push(new org.pkijs.simpl.EXTENSION({
extnID: "2.5.29.19",
critical: false,
extnValue: basicConstraints.toSchema().toBER(false),
parsedValue: basicConstraints
}));
}
function setKeyUsage(cert, digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement, keyCertSign, cRLSign) {
var keyUsageBits = new ArrayBuffer(1);
var keyUsageBytes = new Uint8Array(keyUsageBits);
keyUsageBytes[0] = 0;
if (digitalSignature) {keyUsageBytes[0] |= 0x80;}
if (nonRepudiation) {keyUsageBytes[0] |= 0x40;}
if (keyEncipherment) {keyUsageBytes[0] |= 0x20;}
if (dataEncipherment) {keyUsageBytes[0] |= 0x10;}
if (keyAgreement) {keyUsageBytes[0] |= 0x08;}
if (keyCertSign) {keyUsageBytes[0] |= 0x04;}
if (cRLSign) {keyUsageBytes[0] |= 0x02;}
var keyUsage = new org.pkijs.asn1.BITSTRING({value_hex: keyUsageBits});
cert.extensions.push(new org.pkijs.simpl.EXTENSION({
extnID: "2.5.29.15",
critical: false,
extnValue: keyUsage.toBER(false),
parsedValue: keyUsage
}));
}
function setSignatureAlgorithm(cert, oid) {
cert.signatureAlgorithm.algorithm_id = oid; // In tbsCert
}
function setPublicKey(cert, publicKey) {
return cert.subjectPublicKeyInfo.importKey(publicKey);
}
function signCert(cert, oid, privateKey) {
cert.signature.algorithm_id = oid; // In actual signature
return cert.sign(privateKey);
}
} |
JavaScript | triggerSort() {
const logPrefix = 'SortingFilterController.changeOrderBy()\t';
if (_.isEmpty(this.filterSortingList)) {
this.$log.warn(logPrefix + 'please define field "entityListName"');
return;
} else if (_.isEmpty(this.filterSortingField)) {
this.$log.warn(logPrefix + 'please define field "field"');
return;
} else if (_.isUndefined(this.tableCell.tableManager.baseData)) {
this.$log.warn(logPrefix + 'please sorting base data');
return;
}
//TODO: read this data from the state service.
//const sortingOptions = this.tableCell.tableManager.baseData.sorting;
// Entity list or field name has changed -> reset sort order.
if (this.sorting.entityList !== this.filterSortingList || this.sorting.field !== this.filterSortingField) {
this.sorting.order = '';
}
let sortingType = this.filterSortingType;
if (_.isEmpty(sortingType)) {
sortingType = 'string';
}
let options = this.filterSortingOptions;
if (_.isUndefined(options) || _.isPlainObject(options) === false) {
options = {};
}
this.sorting.fnc = sortingType;
this.sorting.entityList = this.filterSortingList;
this.sorting.field = this.filterSortingField;
this.sorting.options = options;
// Swap the sorting order e.g. to start on a numerical sorting column with the largest value.
if (options.swapOrder) {
this.sorting.order = (this.sorting.order === 'desc' ? 'asc' : 'desc');
} else {
this.sorting.order = (this.sorting.order === 'asc' ? 'desc' : 'asc');
}
// Update class attribute onto this filter's table cell element.
if (this.sorting.order === 'asc') {
this.tableCell.$element
.removeClass('desc')
.addClass('asc');
} else {
this.tableCell.$element
.removeClass('asc')
.addClass('desc');
}
// Sort list by defined sort parameters
this.tableCell.tableManager.baseData.data = SortUtils.sortArrayOfLists(
this.tableCell.tableManager.baseData.data,
this.sorting.fnc,
this.sorting.entityList,
this.sorting.field,
this.sorting.order,
this.sorting.options
);
// Trigger a view update to display the new (sorted) data.
this.tableCell.tableManager.updateView();
} | triggerSort() {
const logPrefix = 'SortingFilterController.changeOrderBy()\t';
if (_.isEmpty(this.filterSortingList)) {
this.$log.warn(logPrefix + 'please define field "entityListName"');
return;
} else if (_.isEmpty(this.filterSortingField)) {
this.$log.warn(logPrefix + 'please define field "field"');
return;
} else if (_.isUndefined(this.tableCell.tableManager.baseData)) {
this.$log.warn(logPrefix + 'please sorting base data');
return;
}
//TODO: read this data from the state service.
//const sortingOptions = this.tableCell.tableManager.baseData.sorting;
// Entity list or field name has changed -> reset sort order.
if (this.sorting.entityList !== this.filterSortingList || this.sorting.field !== this.filterSortingField) {
this.sorting.order = '';
}
let sortingType = this.filterSortingType;
if (_.isEmpty(sortingType)) {
sortingType = 'string';
}
let options = this.filterSortingOptions;
if (_.isUndefined(options) || _.isPlainObject(options) === false) {
options = {};
}
this.sorting.fnc = sortingType;
this.sorting.entityList = this.filterSortingList;
this.sorting.field = this.filterSortingField;
this.sorting.options = options;
// Swap the sorting order e.g. to start on a numerical sorting column with the largest value.
if (options.swapOrder) {
this.sorting.order = (this.sorting.order === 'desc' ? 'asc' : 'desc');
} else {
this.sorting.order = (this.sorting.order === 'asc' ? 'desc' : 'asc');
}
// Update class attribute onto this filter's table cell element.
if (this.sorting.order === 'asc') {
this.tableCell.$element
.removeClass('desc')
.addClass('asc');
} else {
this.tableCell.$element
.removeClass('asc')
.addClass('desc');
}
// Sort list by defined sort parameters
this.tableCell.tableManager.baseData.data = SortUtils.sortArrayOfLists(
this.tableCell.tableManager.baseData.data,
this.sorting.fnc,
this.sorting.entityList,
this.sorting.field,
this.sorting.order,
this.sorting.options
);
// Trigger a view update to display the new (sorted) data.
this.tableCell.tableManager.updateView();
} |
JavaScript | addListener(fn) {
// Argument is not a function? Return immediately.
if (_.isFunction(fn) === false) {
return function () {};
}
/**
* Create a random integer.
*
* @type {number}
*/
const id = Math.floor(Math.random() * 10e16);
/**
* Prepare a simple listener object holding the callback listener function and a randomly
* generated number to identify that object.
*
* @type {{fn: Function, id: number}}
*/
const listenerObj = {fn: fn, id: id};
listeners.push(listenerObj);
// Return a method to de-register the newly added listener method.
return function deregisterListener() {
let i = listeners.length;
while (--i >= 0) {
if (listeners[i].id === id) {
// Remove listener object.
listeners.splice(i, 1);
break;
}
}
};
} | addListener(fn) {
// Argument is not a function? Return immediately.
if (_.isFunction(fn) === false) {
return function () {};
}
/**
* Create a random integer.
*
* @type {number}
*/
const id = Math.floor(Math.random() * 10e16);
/**
* Prepare a simple listener object holding the callback listener function and a randomly
* generated number to identify that object.
*
* @type {{fn: Function, id: number}}
*/
const listenerObj = {fn: fn, id: id};
listeners.push(listenerObj);
// Return a method to de-register the newly added listener method.
return function deregisterListener() {
let i = listeners.length;
while (--i >= 0) {
if (listeners[i].id === id) {
// Remove listener object.
listeners.splice(i, 1);
break;
}
}
};
} |
JavaScript | function deregisterListener() {
let i = listeners.length;
while (--i >= 0) {
if (listeners[i].id === id) {
// Remove listener object.
listeners.splice(i, 1);
break;
}
}
} | function deregisterListener() {
let i = listeners.length;
while (--i >= 0) {
if (listeners[i].id === id) {
// Remove listener object.
listeners.splice(i, 1);
break;
}
}
} |
JavaScript | dumpTable() {
console.group('table "%s"', this.tableName);
// Prepare and dump table content
var dumpData = [];
this.rows.forEach(function (row) {
dumpData.push(
row.cells.map(function (cell) {
return cell.$element.text();
})
);
});
console.table(dumpData);
// Dump filter information
this.filterManager.dumpFilters();
// Dump base data
console.log('base data', this.baseData);
console.groupEnd();
} | dumpTable() {
console.group('table "%s"', this.tableName);
// Prepare and dump table content
var dumpData = [];
this.rows.forEach(function (row) {
dumpData.push(
row.cells.map(function (cell) {
return cell.$element.text();
})
);
});
console.table(dumpData);
// Dump filter information
this.filterManager.dumpFilters();
// Dump base data
console.log('base data', this.baseData);
console.groupEnd();
} |
JavaScript | addFilter(filter) {
// Register filter manager itself on the filter for faster access.
filter.filterManager = this;
this._filters.push(filter);
} | addFilter(filter) {
// Register filter manager itself on the filter for faster access.
filter.filterManager = this;
this._filters.push(filter);
} |
JavaScript | dumpFilters() {
console.group('dumpFilters');
let i = this._filters.length;
if (i === 0) {
console.log('none');
} else {
while (--i >= 0) {
console.log(
'filter "%s" on element:',
this._filters[i].name,
this._filters[i].tableCell.$element
);
}
}
console.groupEnd();
} | dumpFilters() {
console.group('dumpFilters');
let i = this._filters.length;
if (i === 0) {
console.log('none');
} else {
while (--i >= 0) {
console.log(
'filter "%s" on element:',
this._filters[i].name,
this._filters[i].tableCell.$element
);
}
}
console.groupEnd();
} |
JavaScript | secret() {
if (!this._secretSeed) {
throw new Error("no secret key available");
}
if (this.type == 'ed25519') {
return StrKey.encodeEd25519SecretSeed(this._secretSeed);
}
throw new Error("Invalid Keypair type");
} | secret() {
if (!this._secretSeed) {
throw new Error("no secret key available");
}
if (this.type == 'ed25519') {
return StrKey.encodeEd25519SecretSeed(this._secretSeed);
}
throw new Error("Invalid Keypair type");
} |
JavaScript | async present() {
if (this.presented) {
return;
}
const container = this.el.querySelector(`.modal-wrapper`);
if (!container) {
throw new Error('container is undefined');
}
const componentProps = Object.assign({}, this.componentProps, { modal: this.el });
this.usersElement = await __chunk_8.attachComponent(this.delegate, container, this.component, ['ion-page'], componentProps);
await __chunk_9.deepReady(this.usersElement);
return __chunk_4.present(this, 'modalEnter', iosEnterAnimation, mdEnterAnimation);
} | async present() {
if (this.presented) {
return;
}
const container = this.el.querySelector(`.modal-wrapper`);
if (!container) {
throw new Error('container is undefined');
}
const componentProps = Object.assign({}, this.componentProps, { modal: this.el });
this.usersElement = await __chunk_8.attachComponent(this.delegate, container, this.component, ['ion-page'], componentProps);
await __chunk_9.deepReady(this.usersElement);
return __chunk_4.present(this, 'modalEnter', iosEnterAnimation, mdEnterAnimation);
} |
JavaScript | async dismiss(data, role) {
const dismissed = await __chunk_4.dismiss(this, data, role, 'modalLeave', iosLeaveAnimation, mdLeaveAnimation);
if (dismissed) {
await __chunk_8.detachComponent(this.delegate, this.usersElement);
}
return dismissed;
} | async dismiss(data, role) {
const dismissed = await __chunk_4.dismiss(this, data, role, 'modalLeave', iosLeaveAnimation, mdLeaveAnimation);
if (dismissed) {
await __chunk_8.detachComponent(this.delegate, this.usersElement);
}
return dismissed;
} |
JavaScript | async present() {
await __chunk_4.present(this, 'loadingEnter', iosEnterAnimation, mdEnterAnimation, undefined);
if (this.duration > 0) {
this.durationTimeout = setTimeout(() => this.dismiss(), this.duration + 10);
}
} | async present() {
await __chunk_4.present(this, 'loadingEnter', iosEnterAnimation, mdEnterAnimation, undefined);
if (this.duration > 0) {
this.durationTimeout = setTimeout(() => this.dismiss(), this.duration + 10);
}
} |
JavaScript | dismiss(data, role) {
if (this.durationTimeout) {
clearTimeout(this.durationTimeout);
}
return __chunk_4.dismiss(this, data, role, 'loadingLeave', iosLeaveAnimation, mdLeaveAnimation);
} | dismiss(data, role) {
if (this.durationTimeout) {
clearTimeout(this.durationTimeout);
}
return __chunk_4.dismiss(this, data, role, 'loadingLeave', iosLeaveAnimation, mdLeaveAnimation);
} |
JavaScript | positionElements() {
const value = this.getValue();
const prevAlignLeft = this.shouldAlignLeft;
const mode = __chunk_1.getIonMode(this);
const shouldAlignLeft = (!this.animated || value.trim() !== '' || !!this.focused);
this.shouldAlignLeft = shouldAlignLeft;
if (mode !== 'ios') {
return;
}
if (prevAlignLeft !== shouldAlignLeft) {
this.positionPlaceholder();
}
if (this.animated) {
this.positionCancelButton();
}
} | positionElements() {
const value = this.getValue();
const prevAlignLeft = this.shouldAlignLeft;
const mode = __chunk_1.getIonMode(this);
const shouldAlignLeft = (!this.animated || value.trim() !== '' || !!this.focused);
this.shouldAlignLeft = shouldAlignLeft;
if (mode !== 'ios') {
return;
}
if (prevAlignLeft !== shouldAlignLeft) {
this.positionPlaceholder();
}
if (this.animated) {
this.positionCancelButton();
}
} |
JavaScript | async present() {
if (this.presented) {
return;
}
const container = this.el.querySelector('.popover-content');
if (!container) {
throw new Error('container is undefined');
}
const data = Object.assign({}, this.componentProps, { popover: this.el });
this.usersElement = await __chunk_8.attachComponent(this.delegate, container, this.component, ['popover-viewport', this.el['s-sc']], data);
await __chunk_9.deepReady(this.usersElement);
return __chunk_4.present(this, 'popoverEnter', iosEnterAnimation, mdEnterAnimation, this.event);
} | async present() {
if (this.presented) {
return;
}
const container = this.el.querySelector('.popover-content');
if (!container) {
throw new Error('container is undefined');
}
const data = Object.assign({}, this.componentProps, { popover: this.el });
this.usersElement = await __chunk_8.attachComponent(this.delegate, container, this.component, ['popover-viewport', this.el['s-sc']], data);
await __chunk_9.deepReady(this.usersElement);
return __chunk_4.present(this, 'popoverEnter', iosEnterAnimation, mdEnterAnimation, this.event);
} |
JavaScript | async dismiss(data, role) {
const shouldDismiss = await __chunk_4.dismiss(this, data, role, 'popoverLeave', iosLeaveAnimation, mdLeaveAnimation, this.event);
if (shouldDismiss) {
await __chunk_8.detachComponent(this.delegate, this.usersElement);
}
return shouldDismiss;
} | async dismiss(data, role) {
const shouldDismiss = await __chunk_4.dismiss(this, data, role, 'popoverLeave', iosLeaveAnimation, mdLeaveAnimation, this.event);
if (shouldDismiss) {
await __chunk_8.detachComponent(this.delegate, this.usersElement);
}
return shouldDismiss;
} |
JavaScript | function waitingTime(tickets, p) {
let totalTime = 0;
for(const [pos, ticket] of tickets.entries()) {
console.log(`before totalTime: ${totalTime}`);
totalTime += Math.min(ticket, tickets[p] - (pos > p));
console.log(`after totalTime: ${totalTime}`);
//console.log(`pos ${pos}, tickets to buy ${ticket}, tickets[p]: ${tickets[p]}, tickets[p] - (pos > p) ${tickets[p] - (pos > p)}`);
}
return totalTime;
} | function waitingTime(tickets, p) {
let totalTime = 0;
for(const [pos, ticket] of tickets.entries()) {
console.log(`before totalTime: ${totalTime}`);
totalTime += Math.min(ticket, tickets[p] - (pos > p));
console.log(`after totalTime: ${totalTime}`);
//console.log(`pos ${pos}, tickets to buy ${ticket}, tickets[p]: ${tickets[p]}, tickets[p] - (pos > p) ${tickets[p] - (pos > p)}`);
}
return totalTime;
} |
JavaScript | function map(arr, callback) {
let resultArr = [];
for (let i = 0; i < arr.length; i++) {
resultArr.push(callback(arr[i]));
}
return resultArr;
} | function map(arr, callback) {
let resultArr = [];
for (let i = 0; i < arr.length; i++) {
resultArr.push(callback(arr[i]));
}
return resultArr;
} |
JavaScript | function every(arr, callback) {
for (let i = 0; i < arr.length; i++) {
if (callback(arr[i]) === false) {
return false;
}
}
return true;
} | function every(arr, callback) {
for (let i = 0; i < arr.length; i++) {
if (callback(arr[i]) === false) {
return false;
}
}
return true;
} |
JavaScript | function fastCache (fn) {
let m = {};
const innerFn = (arg) => {
if (!m[arg]) {
console.log('Not cached!');
m[arg] = fn(arg);
} else {
console.log('caching the call!');
}
return m[arg];
}
return innerFn;
} | function fastCache (fn) {
let m = {};
const innerFn = (arg) => {
if (!m[arg]) {
console.log('Not cached!');
m[arg] = fn(arg);
} else {
console.log('caching the call!');
}
return m[arg];
}
return innerFn;
} |
JavaScript | get authors () {
if (!this._authors) {
const chap = this.chapters[0]
if (chap && (chap.author || chap.authorUrl)) {
this._authors = [{name: chap.author, link: chap.authorUrl}]
} else {
this._authors = [...this.parent.authors.map(_ => Object.assign({}, _))]
}
}
return this._authors
} | get authors () {
if (!this._authors) {
const chap = this.chapters[0]
if (chap && (chap.author || chap.authorUrl)) {
this._authors = [{name: chap.author, link: chap.authorUrl}]
} else {
this._authors = [...this.parent.authors.map(_ => Object.assign({}, _))]
}
}
return this._authors
} |
JavaScript | function fnExcelReport() {
var name = 'Relatorio de ' + $('h3').text();
var tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
tab_text = tab_text + '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';
tab_text = tab_text + '<x:Name>' + name + '</x:Name>';
tab_text = tab_text + '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>';
tab_text = tab_text + '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';
tab_text = tab_text + "<table border='1px'>";
tab_text = tab_text + $('#relatorio').html();
tab_text = tab_text + '</table></body></html>';
var data_type = 'data:application/vnd.ms-excel';
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
if (window.navigator.msSaveBlob) {
var blob = new Blob([tab_text], {
type: "application/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, name + '.xls');
}
} else {
$('#test').attr('href', data_type + ', ' + encodeURIComponent(tab_text));
$('#test').attr('download', name + '.xls');
}
} | function fnExcelReport() {
var name = 'Relatorio de ' + $('h3').text();
var tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
tab_text = tab_text + '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';
tab_text = tab_text + '<x:Name>' + name + '</x:Name>';
tab_text = tab_text + '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>';
tab_text = tab_text + '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';
tab_text = tab_text + "<table border='1px'>";
tab_text = tab_text + $('#relatorio').html();
tab_text = tab_text + '</table></body></html>';
var data_type = 'data:application/vnd.ms-excel';
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
if (window.navigator.msSaveBlob) {
var blob = new Blob([tab_text], {
type: "application/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, name + '.xls');
}
} else {
$('#test').attr('href', data_type + ', ' + encodeURIComponent(tab_text));
$('#test').attr('download', name + '.xls');
}
} |
JavaScript | function loadRepositoryByUser(userId) {
userResource.getRepositoriesByUser(userId)
.then(function (result) {
angular.forEach(result.data, function (repo) {vm.repositories.push(repo)});
})
.catch(function () {
window.alert('It is not possible to retrieve "' + $routeParams.userId + '" repositories.');
});
} | function loadRepositoryByUser(userId) {
userResource.getRepositoriesByUser(userId)
.then(function (result) {
angular.forEach(result.data, function (repo) {vm.repositories.push(repo)});
})
.catch(function () {
window.alert('It is not possible to retrieve "' + $routeParams.userId + '" repositories.');
});
} |
JavaScript | function card() {
return {
restrict: 'E',
templateUrl: 'repository/components/pagination/pagination.html',
scope: {
items: '=',
since: '=',
limit: '@'
},
link: linkFun
};
/**
*
* @param {Object} scope
*/
function linkFun(scope) {
scope.getPages = getPages;
scope.navigateTo = navigateTo;
scope.currentPage = 0;
/**
* @name getPages
* @desc Get the array of pages
* @return {number[]}
*/
function getPages() {
return new Array(Math.ceil(scope.items.length/scope.limit))
}
/**
* @name navigateTo
* @desc Get the array of pages
* @param {number} page - page number
*/
function navigateTo(page) {
if (page >= 0 && page < Math.ceil(scope.items.length/scope.limit)) {
scope.currentPage = page;
scope.since = scope.currentPage * scope.limit;
}
}
}
} | function card() {
return {
restrict: 'E',
templateUrl: 'repository/components/pagination/pagination.html',
scope: {
items: '=',
since: '=',
limit: '@'
},
link: linkFun
};
/**
*
* @param {Object} scope
*/
function linkFun(scope) {
scope.getPages = getPages;
scope.navigateTo = navigateTo;
scope.currentPage = 0;
/**
* @name getPages
* @desc Get the array of pages
* @return {number[]}
*/
function getPages() {
return new Array(Math.ceil(scope.items.length/scope.limit))
}
/**
* @name navigateTo
* @desc Get the array of pages
* @param {number} page - page number
*/
function navigateTo(page) {
if (page >= 0 && page < Math.ceil(scope.items.length/scope.limit)) {
scope.currentPage = page;
scope.since = scope.currentPage * scope.limit;
}
}
}
} |
JavaScript | function userCtrl(userResource) {
var vm = this;
vm.users = [];
vm.loadUsers = loadUsers;
//Load the first 30 users at first time
loadUsers(0);
/**
* @name loadUsers
* @desc Load the github users
* @param {number} since
*/
function loadUsers(since) {
userResource.getUsers(since)
.then(function (result) {
angular.forEach(result.data, function (user) {vm.users.push(user)});
})
.catch(function () {
window.alert('It is not possible to retrieve Github users');
});
}
} | function userCtrl(userResource) {
var vm = this;
vm.users = [];
vm.loadUsers = loadUsers;
//Load the first 30 users at first time
loadUsers(0);
/**
* @name loadUsers
* @desc Load the github users
* @param {number} since
*/
function loadUsers(since) {
userResource.getUsers(since)
.then(function (result) {
angular.forEach(result.data, function (user) {vm.users.push(user)});
})
.catch(function () {
window.alert('It is not possible to retrieve Github users');
});
}
} |
JavaScript | function userResource($http) {
var baseUrl = 'https://api.github.com/';
this.getUsers = getUsers;
this.getRepositoriesByUser = getRepositoriesByUser;
/**
* @name getUsers
* @desc Gets user list
* @param {number} since
* @return {Promise}
*/
function getUsers(since) {
var config = {
params: {since: since}
};
return $http.get(baseUrl + 'users', config);
};
/**
* @name getRepositoriesByUser
* @desc Gets user repositories
* @param {*} since
*/
function getRepositoriesByUser(userId) {
return $http.get(baseUrl + 'users/' + userId + '/repos');
};
} | function userResource($http) {
var baseUrl = 'https://api.github.com/';
this.getUsers = getUsers;
this.getRepositoriesByUser = getRepositoriesByUser;
/**
* @name getUsers
* @desc Gets user list
* @param {number} since
* @return {Promise}
*/
function getUsers(since) {
var config = {
params: {since: since}
};
return $http.get(baseUrl + 'users', config);
};
/**
* @name getRepositoriesByUser
* @desc Gets user repositories
* @param {*} since
*/
function getRepositoriesByUser(userId) {
return $http.get(baseUrl + 'users/' + userId + '/repos');
};
} |
JavaScript | function sorting(input) {
let copyOfArray = input.slice();
copyOfArray.sort((a, b) => a - b);
let length = copyOfArray.length - 1;
let finalArray = [];
for (let i = 0; i <= length; i += 2) {
let biggest = copyOfArray.pop();
let smallest = copyOfArray.shift();
finalArray.push(biggest, smallest);
}
console.log(finalArray.join(' '));
} | function sorting(input) {
let copyOfArray = input.slice();
copyOfArray.sort((a, b) => a - b);
let length = copyOfArray.length - 1;
let finalArray = [];
for (let i = 0; i <= length; i += 2) {
let biggest = copyOfArray.pop();
let smallest = copyOfArray.shift();
finalArray.push(biggest, smallest);
}
console.log(finalArray.join(' '));
} |
JavaScript | function bombNumbers(sequence, bombArr) {
let [bomb, power] = bombArr;
let index = sequence.indexOf(bomb);
while (index != -1) {
let start = index - power < 0 ? 0 : index - power;
sequence.splice(start, power * 2 + 1);
index = sequence.indexOf(bomb);
}
let sum = 0;
for (let i = 0; i < sequence.length; i++) {
sum += sequence[i];
}
return sum;
} | function bombNumbers(sequence, bombArr) {
let [bomb, power] = bombArr;
let index = sequence.indexOf(bomb);
while (index != -1) {
let start = index - power < 0 ? 0 : index - power;
sequence.splice(start, power * 2 + 1);
index = sequence.indexOf(bomb);
}
let sum = 0;
for (let i = 0; i < sequence.length; i++) {
sum += sequence[i];
}
return sum;
} |
JavaScript | function houseParty(input) {
let test = [];
let guests = [];
for (let i = 0; i < input.length; i++) {
let element = input[i].split(' ');
let name = element.shift();
let command = element.join(' ');
if (command === 'is going!') {
let checkAName = checkForAName(name, guests);
if (checkAName) {
test.push(`${name} is already in the list!`);
} else {
guests.push(name);
}
} else if (command === 'is not going!') {
let checkAName = checkForAName(name, guests);
if (checkAName) {
let indexOfName = indexOfAName(name, guests);
guests.splice(indexOfName, 1);
} else {
test.push(`${name} is not in the list!`);
}
}
}
function checkForAName(inputValue, array) {
let isInTheList = false;
for (let i = 0; i < array.length; i++) {
if (inputValue === array[i]) {
return true;
}
}
return isInTheList;
}
function indexOfAName(inputValue, array) {
for (let index in array) {
if (inputValue === array[index]) {
return index;
}
}
}
for (let element of test) {
console.log(element);
}
for (let element of guests) {
console.log(element);
}
} | function houseParty(input) {
let test = [];
let guests = [];
for (let i = 0; i < input.length; i++) {
let element = input[i].split(' ');
let name = element.shift();
let command = element.join(' ');
if (command === 'is going!') {
let checkAName = checkForAName(name, guests);
if (checkAName) {
test.push(`${name} is already in the list!`);
} else {
guests.push(name);
}
} else if (command === 'is not going!') {
let checkAName = checkForAName(name, guests);
if (checkAName) {
let indexOfName = indexOfAName(name, guests);
guests.splice(indexOfName, 1);
} else {
test.push(`${name} is not in the list!`);
}
}
}
function checkForAName(inputValue, array) {
let isInTheList = false;
for (let i = 0; i < array.length; i++) {
if (inputValue === array[i]) {
return true;
}
}
return isInTheList;
}
function indexOfAName(inputValue, array) {
for (let index in array) {
if (inputValue === array[index]) {
return index;
}
}
}
for (let element of test) {
console.log(element);
}
for (let element of guests) {
console.log(element);
}
} |
JavaScript | isAlreadyDefined(command) {
const search = command.toLowerCase().trim();
let exists = false;
this.providedCommands.forEach((cmds) => {
if (cmds.has(search)) {
exists = true;
}
});
return exists;
} | isAlreadyDefined(command) {
const search = command.toLowerCase().trim();
let exists = false;
this.providedCommands.forEach((cmds) => {
if (cmds.has(search)) {
exists = true;
}
});
return exists;
} |
JavaScript | addCommand(appId, command) {
command.command = command.command.toLowerCase().trim();
// Ensure the app can touch this command
if (!this.canCommandBeTouchedBy(appId, command.command)) {
throw new errors_1.CommandHasAlreadyBeenTouchedError(command.command);
}
// Verify the command doesn't exist already
if (this.bridge.doesCommandExist(command.command, appId) || this.isAlreadyDefined(command.command)) {
throw new errors_1.CommandAlreadyExistsError(command.command);
}
const app = this.manager.getOneById(appId);
if (!app) {
throw new Error('App must exist in order for a command to be added.');
}
if (!this.providedCommands.has(appId)) {
this.providedCommands.set(appId, new Map());
}
this.providedCommands.get(appId).set(command.command, new AppSlashCommand_1.AppSlashCommand(app, command));
// The app has now touched the command, so let's set it
this.setAsTouched(appId, command.command);
} | addCommand(appId, command) {
command.command = command.command.toLowerCase().trim();
// Ensure the app can touch this command
if (!this.canCommandBeTouchedBy(appId, command.command)) {
throw new errors_1.CommandHasAlreadyBeenTouchedError(command.command);
}
// Verify the command doesn't exist already
if (this.bridge.doesCommandExist(command.command, appId) || this.isAlreadyDefined(command.command)) {
throw new errors_1.CommandAlreadyExistsError(command.command);
}
const app = this.manager.getOneById(appId);
if (!app) {
throw new Error('App must exist in order for a command to be added.');
}
if (!this.providedCommands.has(appId)) {
this.providedCommands.set(appId, new Map());
}
this.providedCommands.get(appId).set(command.command, new AppSlashCommand_1.AppSlashCommand(app, command));
// The app has now touched the command, so let's set it
this.setAsTouched(appId, command.command);
} |
JavaScript | modifyCommand(appId, command) {
command.command = command.command.toLowerCase().trim();
// Ensure the app can touch this command
if (!this.canCommandBeTouchedBy(appId, command.command)) {
throw new errors_1.CommandHasAlreadyBeenTouchedError(command.command);
}
const app = this.manager.getOneById(appId);
if (!app) {
throw new Error('App must exist in order to modify a command.');
}
const hasNotProvidedIt = !this.providedCommands.has(appId) || !this.providedCommands.get(appId).has(command.command);
// They haven't provided (added) it and the bridged system doesn't have it, error out
if (hasNotProvidedIt && !this.bridge.doesCommandExist(command.command, appId)) {
throw new Error('You must first register a command before you can modify it.');
}
if (hasNotProvidedIt) {
this.bridge.modifyCommand(command, appId);
const regInfo = new AppSlashCommand_1.AppSlashCommand(app, command);
regInfo.isDisabled = false;
regInfo.isEnabled = true;
regInfo.isRegistered = true;
this.modifiedCommands.set(command.command, regInfo);
}
else {
this.providedCommands.get(appId).get(command.command).slashCommand = command;
}
this.setAsTouched(appId, command.command);
} | modifyCommand(appId, command) {
command.command = command.command.toLowerCase().trim();
// Ensure the app can touch this command
if (!this.canCommandBeTouchedBy(appId, command.command)) {
throw new errors_1.CommandHasAlreadyBeenTouchedError(command.command);
}
const app = this.manager.getOneById(appId);
if (!app) {
throw new Error('App must exist in order to modify a command.');
}
const hasNotProvidedIt = !this.providedCommands.has(appId) || !this.providedCommands.get(appId).has(command.command);
// They haven't provided (added) it and the bridged system doesn't have it, error out
if (hasNotProvidedIt && !this.bridge.doesCommandExist(command.command, appId)) {
throw new Error('You must first register a command before you can modify it.');
}
if (hasNotProvidedIt) {
this.bridge.modifyCommand(command, appId);
const regInfo = new AppSlashCommand_1.AppSlashCommand(app, command);
regInfo.isDisabled = false;
regInfo.isEnabled = true;
regInfo.isRegistered = true;
this.modifiedCommands.set(command.command, regInfo);
}
else {
this.providedCommands.get(appId).get(command.command).slashCommand = command;
}
this.setAsTouched(appId, command.command);
} |
JavaScript | enableCommand(appId, command) {
const cmd = command.toLowerCase().trim();
// Ensure the app can touch this command
if (!this.canCommandBeTouchedBy(appId, cmd)) {
throw new errors_1.CommandHasAlreadyBeenTouchedError(cmd);
}
// Handle if the App provided the command fist
if (this.providedCommands.has(appId) && this.providedCommands.get(appId).has(cmd)) {
const cmdInfo = this.providedCommands.get(appId).get(cmd);
// A command marked as disabled can then be "enabled" but not be registered.
// This happens when an App is not enabled and they change the status of
// command based upon a setting they provide which a User can change.
if (!cmdInfo.isRegistered) {
cmdInfo.isDisabled = false;
cmdInfo.isEnabled = true;
}
return;
}
if (!this.bridge.doesCommandExist(cmd, appId)) {
throw new Error(`The command "${cmd}" does not exist to enable.`);
}
this.bridge.enableCommand(cmd, appId);
this.setAsTouched(appId, cmd);
} | enableCommand(appId, command) {
const cmd = command.toLowerCase().trim();
// Ensure the app can touch this command
if (!this.canCommandBeTouchedBy(appId, cmd)) {
throw new errors_1.CommandHasAlreadyBeenTouchedError(cmd);
}
// Handle if the App provided the command fist
if (this.providedCommands.has(appId) && this.providedCommands.get(appId).has(cmd)) {
const cmdInfo = this.providedCommands.get(appId).get(cmd);
// A command marked as disabled can then be "enabled" but not be registered.
// This happens when an App is not enabled and they change the status of
// command based upon a setting they provide which a User can change.
if (!cmdInfo.isRegistered) {
cmdInfo.isDisabled = false;
cmdInfo.isEnabled = true;
}
return;
}
if (!this.bridge.doesCommandExist(cmd, appId)) {
throw new Error(`The command "${cmd}" does not exist to enable.`);
}
this.bridge.enableCommand(cmd, appId);
this.setAsTouched(appId, cmd);
} |
JavaScript | disableCommand(appId, command) {
const cmd = command.toLowerCase().trim();
// Ensure the app can touch this command
if (!this.canCommandBeTouchedBy(appId, cmd)) {
throw new errors_1.CommandHasAlreadyBeenTouchedError(cmd);
}
// Handle if the App provided the command fist
if (this.providedCommands.has(appId) && this.providedCommands.get(appId).has(cmd)) {
const cmdInfo = this.providedCommands.get(appId).get(cmd);
// A command marked as enabled can then be "disabled" but not yet be registered.
// This happens when an App is not enabled and they change the status of
// command based upon a setting they provide which a User can change.
if (!cmdInfo.isRegistered) {
cmdInfo.isDisabled = true;
cmdInfo.isEnabled = false;
}
return;
}
if (!this.bridge.doesCommandExist(cmd, appId)) {
throw new Error(`The command "${cmd}" does not exist to disable.`);
}
this.bridge.disableCommand(cmd, appId);
this.setAsTouched(appId, cmd);
} | disableCommand(appId, command) {
const cmd = command.toLowerCase().trim();
// Ensure the app can touch this command
if (!this.canCommandBeTouchedBy(appId, cmd)) {
throw new errors_1.CommandHasAlreadyBeenTouchedError(cmd);
}
// Handle if the App provided the command fist
if (this.providedCommands.has(appId) && this.providedCommands.get(appId).has(cmd)) {
const cmdInfo = this.providedCommands.get(appId).get(cmd);
// A command marked as enabled can then be "disabled" but not yet be registered.
// This happens when an App is not enabled and they change the status of
// command based upon a setting they provide which a User can change.
if (!cmdInfo.isRegistered) {
cmdInfo.isDisabled = true;
cmdInfo.isEnabled = false;
}
return;
}
if (!this.bridge.doesCommandExist(cmd, appId)) {
throw new Error(`The command "${cmd}" does not exist to disable.`);
}
this.bridge.disableCommand(cmd, appId);
this.setAsTouched(appId, cmd);
} |
JavaScript | registerCommands(appId) {
if (!this.providedCommands.has(appId)) {
return;
}
this.providedCommands.get(appId).forEach((r) => {
if (r.isDisabled) {
return;
}
this.registerCommand(appId, r);
});
} | registerCommands(appId) {
if (!this.providedCommands.has(appId)) {
return;
}
this.providedCommands.get(appId).forEach((r) => {
if (r.isDisabled) {
return;
}
this.registerCommand(appId, r);
});
} |
JavaScript | unregisterCommands(appId) {
if (this.providedCommands.has(appId)) {
this.providedCommands.get(appId).forEach((r) => {
this.bridge.unregisterCommand(r.slashCommand.command, appId);
this.touchedCommandsToApps.delete(r.slashCommand.command);
const ind = this.appsTouchedCommands.get(appId).indexOf(r.slashCommand.command);
this.appsTouchedCommands.get(appId).splice(ind, 1);
r.isRegistered = true;
});
this.providedCommands.delete(appId);
}
if (this.appsTouchedCommands.has(appId)) {
// The commands inside the appsTouchedCommands should now
// only be the ones which the App has enabled, disabled, or modified.
// We call restore to enable the commands provided by the bridged system
// or unmodify the commands modified by the App
this.appsTouchedCommands.get(appId).forEach((cmd) => {
this.bridge.restoreCommand(cmd, appId);
this.modifiedCommands.get(cmd).isRegistered = false;
this.modifiedCommands.delete(cmd);
this.touchedCommandsToApps.delete(cmd);
});
this.appsTouchedCommands.delete(appId);
}
} | unregisterCommands(appId) {
if (this.providedCommands.has(appId)) {
this.providedCommands.get(appId).forEach((r) => {
this.bridge.unregisterCommand(r.slashCommand.command, appId);
this.touchedCommandsToApps.delete(r.slashCommand.command);
const ind = this.appsTouchedCommands.get(appId).indexOf(r.slashCommand.command);
this.appsTouchedCommands.get(appId).splice(ind, 1);
r.isRegistered = true;
});
this.providedCommands.delete(appId);
}
if (this.appsTouchedCommands.has(appId)) {
// The commands inside the appsTouchedCommands should now
// only be the ones which the App has enabled, disabled, or modified.
// We call restore to enable the commands provided by the bridged system
// or unmodify the commands modified by the App
this.appsTouchedCommands.get(appId).forEach((cmd) => {
this.bridge.restoreCommand(cmd, appId);
this.modifiedCommands.get(cmd).isRegistered = false;
this.modifiedCommands.delete(cmd);
this.touchedCommandsToApps.delete(cmd);
});
this.appsTouchedCommands.delete(appId);
}
} |
JavaScript | executeCommand(command, context) {
return __awaiter(this, void 0, void 0, function* () {
const cmd = command.toLowerCase().trim();
if (!this.shouldCommandFunctionsRun(cmd)) {
return;
}
const app = this.manager.getOneById(this.touchedCommandsToApps.get(cmd));
if (!app || AppStatus_1.AppStatusUtils.isDisabled(app.getStatus())) {
// Just in case someone decides to do something they shouldn't
// let's ensure the app actually exists
return;
}
const appCmd = this.retrieveCommandInfo(cmd, app.getID());
yield appCmd.runExecutorOrPreviewer(metadata_1.AppMethod._COMMAND_EXECUTOR, this.ensureContext(context), this.manager.getLogStorage(), this.accessors);
return;
});
} | executeCommand(command, context) {
return __awaiter(this, void 0, void 0, function* () {
const cmd = command.toLowerCase().trim();
if (!this.shouldCommandFunctionsRun(cmd)) {
return;
}
const app = this.manager.getOneById(this.touchedCommandsToApps.get(cmd));
if (!app || AppStatus_1.AppStatusUtils.isDisabled(app.getStatus())) {
// Just in case someone decides to do something they shouldn't
// let's ensure the app actually exists
return;
}
const appCmd = this.retrieveCommandInfo(cmd, app.getID());
yield appCmd.runExecutorOrPreviewer(metadata_1.AppMethod._COMMAND_EXECUTOR, this.ensureContext(context), this.manager.getLogStorage(), this.accessors);
return;
});
} |
JavaScript | shouldCommandFunctionsRun(command) {
// None of the Apps have touched the command to execute,
// thus we don't care so exit out
if (!this.touchedCommandsToApps.has(command)) {
return false;
}
const appId = this.touchedCommandsToApps.get(command);
const cmdInfo = this.retrieveCommandInfo(command, appId);
// Should the command information really not exist
// Or if the command hasn't been registered
// Or the command is disabled on our side
// then let's not execute it, as the App probably doesn't want it yet
if (!cmdInfo || !cmdInfo.isRegistered || cmdInfo.isDisabled) {
return false;
}
return true;
} | shouldCommandFunctionsRun(command) {
// None of the Apps have touched the command to execute,
// thus we don't care so exit out
if (!this.touchedCommandsToApps.has(command)) {
return false;
}
const appId = this.touchedCommandsToApps.get(command);
const cmdInfo = this.retrieveCommandInfo(command, appId);
// Should the command information really not exist
// Or if the command hasn't been registered
// Or the command is disabled on our side
// then let's not execute it, as the App probably doesn't want it yet
if (!cmdInfo || !cmdInfo.isRegistered || cmdInfo.isDisabled) {
return false;
}
return true;
} |
JavaScript | initialize() {
window.addEventListener('message', ({ data, source }) => __awaiter(this, void 0, void 0, function* () {
if (!data.hasOwnProperty(constants_1.MESSAGE_ID)) {
return;
}
this.responseDestination = source;
const { [constants_1.MESSAGE_ID]: { action, id } } = data;
switch (action) {
case definition_1.AppsEngineUIMethods.GET_USER_INFO:
this.handleAction(action, id, yield this.getClientUserInfo());
case definition_1.AppsEngineUIMethods.GET_ROOM_INFO:
this.handleAction(action, id, yield this.getClientRoomInfo());
}
}));
} | initialize() {
window.addEventListener('message', ({ data, source }) => __awaiter(this, void 0, void 0, function* () {
if (!data.hasOwnProperty(constants_1.MESSAGE_ID)) {
return;
}
this.responseDestination = source;
const { [constants_1.MESSAGE_ID]: { action, id } } = data;
switch (action) {
case definition_1.AppsEngineUIMethods.GET_USER_INFO:
this.handleAction(action, id, yield this.getClientUserInfo());
case definition_1.AppsEngineUIMethods.GET_ROOM_INFO:
this.handleAction(action, id, yield this.getClientRoomInfo());
}
}));
} |
JavaScript | handleAction(action, id, data) {
return __awaiter(this, void 0, void 0, function* () {
if ((this.responseDestination instanceof MessagePort) || (this.responseDestination instanceof ServiceWorker)) {
return;
}
this.responseDestination.postMessage({
[constants_1.MESSAGE_ID]: {
id,
action,
payload: data,
},
}, '*');
});
} | handleAction(action, id, data) {
return __awaiter(this, void 0, void 0, function* () {
if ((this.responseDestination instanceof MessagePort) || (this.responseDestination instanceof ServiceWorker)) {
return;
}
this.responseDestination.postMessage({
[constants_1.MESSAGE_ID]: {
id,
action,
payload: data,
},
}, '*');
});
} |
JavaScript | static hasPermission(appId, permission) {
const grantedPermission = AppManager_1.getPermissionsByAppId(appId).find(({ name }) => name === permission.name);
if (!grantedPermission) {
return undefined;
}
return grantedPermission;
} | static hasPermission(appId, permission) {
const grantedPermission = AppManager_1.getPermissionsByAppId(appId).find(({ name }) => name === permission.name);
if (!grantedPermission) {
return undefined;
}
return grantedPermission;
} |
JavaScript | initialize(configurationExtend, environmentRead) {
return __awaiter(this, void 0, void 0, function* () {
yield this.extendConfiguration(configurationExtend, environmentRead);
});
} | initialize(configurationExtend, environmentRead) {
return __awaiter(this, void 0, void 0, function* () {
yield this.extendConfiguration(configurationExtend, environmentRead);
});
} |
JavaScript | onEnable(environment, configurationModify) {
return __awaiter(this, void 0, void 0, function* () {
return true;
});
} | onEnable(environment, configurationModify) {
return __awaiter(this, void 0, void 0, function* () {
return true;
});
} |
JavaScript | onDisable(configurationModify) {
return __awaiter(this, void 0, void 0, function* () {
return;
});
} | onDisable(configurationModify) {
return __awaiter(this, void 0, void 0, function* () {
return;
});
} |
JavaScript | onUninstall(context, read, http, persistence, modify) {
return __awaiter(this, void 0, void 0, function* () {
return;
});
} | onUninstall(context, read, http, persistence, modify) {
return __awaiter(this, void 0, void 0, function* () {
return;
});
} |
JavaScript | onInstall(context, read, http, persistence, modify) {
return __awaiter(this, void 0, void 0, function* () {
return;
});
} | onInstall(context, read, http, persistence, modify) {
return __awaiter(this, void 0, void 0, function* () {
return;
});
} |
JavaScript | onSettingUpdated(setting, configurationModify, read, http) {
return __awaiter(this, void 0, void 0, function* () {
return;
});
} | onSettingUpdated(setting, configurationModify, read, http) {
return __awaiter(this, void 0, void 0, function* () {
return;
});
} |
JavaScript | extendConfiguration(configuration, environmentRead) {
return __awaiter(this, void 0, void 0, function* () {
return;
});
} | extendConfiguration(configuration, environmentRead) {
return __awaiter(this, void 0, void 0, function* () {
return;
});
} |
JavaScript | addApi(appId, api) {
if (api.endpoints.length === 0) {
throw new Error('Invalid Api parameter provided, endpoints must contain, at least, one IApiEndpoint.');
}
const app = this.manager.getOneById(appId);
if (!app) {
throw new Error('App must exist in order for an api to be added.');
}
// Verify the api's path doesn't exist already
if (this.providedApis.get(appId)) {
api.endpoints.forEach((endpoint) => {
if (this.providedApis.get(appId).has(endpoint.path)) {
throw new errors_1.PathAlreadyExistsError(endpoint.path);
}
});
}
if (!this.providedApis.has(appId)) {
this.providedApis.set(appId, new Map());
}
api.endpoints.forEach((endpoint) => {
this.providedApis.get(appId).set(endpoint.path, new AppApi_1.AppApi(app, api, endpoint));
});
} | addApi(appId, api) {
if (api.endpoints.length === 0) {
throw new Error('Invalid Api parameter provided, endpoints must contain, at least, one IApiEndpoint.');
}
const app = this.manager.getOneById(appId);
if (!app) {
throw new Error('App must exist in order for an api to be added.');
}
// Verify the api's path doesn't exist already
if (this.providedApis.get(appId)) {
api.endpoints.forEach((endpoint) => {
if (this.providedApis.get(appId).has(endpoint.path)) {
throw new errors_1.PathAlreadyExistsError(endpoint.path);
}
});
}
if (!this.providedApis.has(appId)) {
this.providedApis.set(appId, new Map());
}
api.endpoints.forEach((endpoint) => {
this.providedApis.get(appId).set(endpoint.path, new AppApi_1.AppApi(app, api, endpoint));
});
} |
JavaScript | registerApis(appId) {
if (!this.providedApis.has(appId)) {
return;
}
this.bridge.unregisterApis(appId);
for (const [, apiapp] of this.providedApis.get(appId).entries()) {
this.registerApi(appId, apiapp);
}
} | registerApis(appId) {
if (!this.providedApis.has(appId)) {
return;
}
this.bridge.unregisterApis(appId);
for (const [, apiapp] of this.providedApis.get(appId).entries()) {
this.registerApi(appId, apiapp);
}
} |
JavaScript | unregisterApis(appId) {
if (this.providedApis.has(appId)) {
this.bridge.unregisterApis(appId);
this.providedApis.delete(appId);
}
} | unregisterApis(appId) {
if (this.providedApis.has(appId)) {
this.bridge.unregisterApis(appId);
this.providedApis.delete(appId);
}
} |
JavaScript | executeApi(appId, path, request) {
return __awaiter(this, void 0, void 0, function* () {
const api = this.providedApis.get(appId).get(path);
if (!api) {
return {
status: accessors_1.HttpStatusCode.NOT_FOUND,
};
}
const app = this.manager.getOneById(appId);
if (!app || AppStatus_1.AppStatusUtils.isDisabled(app.getStatus())) {
// Just in case someone decides to do something they shouldn't
// let's ensure the app actually exists
return {
status: accessors_1.HttpStatusCode.NOT_FOUND,
};
}
return api.runExecutor(request, this.manager.getLogStorage(), this.accessors);
});
} | executeApi(appId, path, request) {
return __awaiter(this, void 0, void 0, function* () {
const api = this.providedApis.get(appId).get(path);
if (!api) {
return {
status: accessors_1.HttpStatusCode.NOT_FOUND,
};
}
const app = this.manager.getOneById(appId);
if (!app || AppStatus_1.AppStatusUtils.isDisabled(app.getStatus())) {
// Just in case someone decides to do something they shouldn't
// let's ensure the app actually exists
return {
status: accessors_1.HttpStatusCode.NOT_FOUND,
};
}
return api.runExecutor(request, this.manager.getLogStorage(), this.accessors);
});
} |
JavaScript | listApis(appId) {
const apis = this.providedApis.get(appId);
if (!apis) {
return [];
}
const result = [];
for (const api of apis.values()) {
const metadata = {
path: api.endpoint.path,
computedPath: api.computedPath,
methods: api.implementedMethods,
examples: api.endpoint.examples || {},
};
result.push(metadata);
}
return result;
} | listApis(appId) {
const apis = this.providedApis.get(appId);
if (!apis) {
return [];
}
const result = [];
for (const api of apis.values()) {
const metadata = {
path: api.endpoint.path,
computedPath: api.computedPath,
methods: api.implementedMethods,
examples: api.endpoint.examples || {},
};
result.push(metadata);
}
return result;
} |
JavaScript | load() {
return __awaiter(this, void 0, void 0, function* () {
// You can not load the AppManager system again
// if it has already been loaded.
if (this.isLoaded) {
return;
}
const items = yield this.storage.retrieveAll();
const affs = new Array();
for (const item of items.values()) {
const aff = new compiler_1.AppFabricationFulfillment();
try {
aff.setAppInfo(item.info);
aff.setImplementedInterfaces(item.implemented);
const app = this.getCompiler().toSandBox(this, item);
this.apps.set(item.id, app);
aff.setApp(app);
}
catch (e) {
console.warn(`Error while compiling the App "${item.info.name} (${item.id})":`);
console.error(e);
const app = DisabledApp_1.DisabledApp.createNew(item.info, AppStatus_1.AppStatus.COMPILER_ERROR_DISABLED);
app.getLogger().error(e);
this.logStorage.storeEntries(app.getID(), app.getLogger());
const prl = new ProxiedApp_1.ProxiedApp(this, item, app, () => '');
this.apps.set(item.id, prl);
aff.setApp(prl);
}
affs.push(aff);
}
// Let's initialize them
for (const rl of this.apps.values()) {
if (AppStatus_1.AppStatusUtils.isDisabled(rl.getStatus())) {
// Usually if an App is disabled before it's initialized,
// then something (such as an error) occured while
// it was compiled or something similar.
continue;
}
yield this.initializeApp(items.get(rl.getID()), rl, false, true).catch(console.error);
}
// Let's ensure the required settings are all set
for (const rl of this.apps.values()) {
if (AppStatus_1.AppStatusUtils.isDisabled(rl.getStatus())) {
continue;
}
if (!this.areRequiredSettingsSet(rl.getStorageItem())) {
yield rl.setStatus(AppStatus_1.AppStatus.INVALID_SETTINGS_DISABLED).catch(console.error);
}
}
// Now let's enable the apps which were once enabled
// but are not currently disabled.
for (const app of this.apps.values()) {
if (!AppStatus_1.AppStatusUtils.isDisabled(app.getStatus()) && AppStatus_1.AppStatusUtils.isEnabled(app.getPreviousStatus())) {
yield this.enableApp(items.get(app.getID()), app, true, app.getPreviousStatus() === AppStatus_1.AppStatus.MANUALLY_ENABLED).catch(console.error);
}
else if (!AppStatus_1.AppStatusUtils.isError(app.getStatus())) {
this.listenerManager.lockEssentialEvents(app);
yield this.schedulerManager.cancelAllJobs(app.getID());
}
}
this.isLoaded = true;
return affs;
});
} | load() {
return __awaiter(this, void 0, void 0, function* () {
// You can not load the AppManager system again
// if it has already been loaded.
if (this.isLoaded) {
return;
}
const items = yield this.storage.retrieveAll();
const affs = new Array();
for (const item of items.values()) {
const aff = new compiler_1.AppFabricationFulfillment();
try {
aff.setAppInfo(item.info);
aff.setImplementedInterfaces(item.implemented);
const app = this.getCompiler().toSandBox(this, item);
this.apps.set(item.id, app);
aff.setApp(app);
}
catch (e) {
console.warn(`Error while compiling the App "${item.info.name} (${item.id})":`);
console.error(e);
const app = DisabledApp_1.DisabledApp.createNew(item.info, AppStatus_1.AppStatus.COMPILER_ERROR_DISABLED);
app.getLogger().error(e);
this.logStorage.storeEntries(app.getID(), app.getLogger());
const prl = new ProxiedApp_1.ProxiedApp(this, item, app, () => '');
this.apps.set(item.id, prl);
aff.setApp(prl);
}
affs.push(aff);
}
// Let's initialize them
for (const rl of this.apps.values()) {
if (AppStatus_1.AppStatusUtils.isDisabled(rl.getStatus())) {
// Usually if an App is disabled before it's initialized,
// then something (such as an error) occured while
// it was compiled or something similar.
continue;
}
yield this.initializeApp(items.get(rl.getID()), rl, false, true).catch(console.error);
}
// Let's ensure the required settings are all set
for (const rl of this.apps.values()) {
if (AppStatus_1.AppStatusUtils.isDisabled(rl.getStatus())) {
continue;
}
if (!this.areRequiredSettingsSet(rl.getStorageItem())) {
yield rl.setStatus(AppStatus_1.AppStatus.INVALID_SETTINGS_DISABLED).catch(console.error);
}
}
// Now let's enable the apps which were once enabled
// but are not currently disabled.
for (const app of this.apps.values()) {
if (!AppStatus_1.AppStatusUtils.isDisabled(app.getStatus()) && AppStatus_1.AppStatusUtils.isEnabled(app.getPreviousStatus())) {
yield this.enableApp(items.get(app.getID()), app, true, app.getPreviousStatus() === AppStatus_1.AppStatus.MANUALLY_ENABLED).catch(console.error);
}
else if (!AppStatus_1.AppStatusUtils.isError(app.getStatus())) {
this.listenerManager.lockEssentialEvents(app);
yield this.schedulerManager.cancelAllJobs(app.getID());
}
}
this.isLoaded = true;
return affs;
});
} |
JavaScript | loadOne(appId) {
return __awaiter(this, void 0, void 0, function* () {
if (this.apps.get(appId)) {
return this.apps.get(appId);
}
const item = yield this.storage.retrieveOne(appId);
if (!item) {
throw new Error(`No App found by the id of: "${appId}"`);
}
this.apps.set(item.id, this.getCompiler().toSandBox(this, item));
const rl = this.apps.get(item.id);
yield this.initializeApp(item, rl, false);
if (!this.areRequiredSettingsSet(item)) {
yield rl.setStatus(AppStatus_1.AppStatus.INVALID_SETTINGS_DISABLED);
}
if (!AppStatus_1.AppStatusUtils.isDisabled(rl.getStatus()) && AppStatus_1.AppStatusUtils.isEnabled(rl.getPreviousStatus())) {
yield this.enableApp(item, rl, false, rl.getPreviousStatus() === AppStatus_1.AppStatus.MANUALLY_ENABLED);
}
return this.apps.get(item.id);
});
} | loadOne(appId) {
return __awaiter(this, void 0, void 0, function* () {
if (this.apps.get(appId)) {
return this.apps.get(appId);
}
const item = yield this.storage.retrieveOne(appId);
if (!item) {
throw new Error(`No App found by the id of: "${appId}"`);
}
this.apps.set(item.id, this.getCompiler().toSandBox(this, item));
const rl = this.apps.get(item.id);
yield this.initializeApp(item, rl, false);
if (!this.areRequiredSettingsSet(item)) {
yield rl.setStatus(AppStatus_1.AppStatus.INVALID_SETTINGS_DISABLED);
}
if (!AppStatus_1.AppStatusUtils.isDisabled(rl.getStatus()) && AppStatus_1.AppStatusUtils.isEnabled(rl.getPreviousStatus())) {
yield this.enableApp(item, rl, false, rl.getPreviousStatus() === AppStatus_1.AppStatus.MANUALLY_ENABLED);
}
return this.apps.get(item.id);
});
} |
JavaScript | function recalculate() {
var amountValue = jQuery("#slider-amount").slider("value");
var termValue = jQuery("#slider-term").slider("value");
var paymentInformation = getPaymentInformation(amountValue, termValue);
//paymentInformation.inspect();
return paymentInformation;
} | function recalculate() {
var amountValue = jQuery("#slider-amount").slider("value");
var termValue = jQuery("#slider-term").slider("value");
var paymentInformation = getPaymentInformation(amountValue, termValue);
//paymentInformation.inspect();
return paymentInformation;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.