language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | onDrop() {
let recordIDs = [],
e,
allEntries = document.querySelectorAll(".player-list-entry");
allEntries.forEach(entryView => {
recordIDs.push(entryView.getAttribute("data-id"));
});
e = new Event("on-record-list-changed", recordIDs);
this.notifyAll(e);
} | onDrop() {
let recordIDs = [],
e,
allEntries = document.querySelectorAll(".player-list-entry");
allEntries.forEach(entryView => {
recordIDs.push(entryView.getAttribute("data-id"));
});
e = new Event("on-record-list-changed", recordIDs);
this.notifyAll(e);
} |
JavaScript | endPlayedEntry(event) {
let entry = this.getEntryById(event.data.id);
if (entry !== undefined && entry !== null) {
entry.stopPlay();
}
} | endPlayedEntry(event) {
let entry = this.getEntryById(event.data.id);
if (entry !== undefined && entry !== null) {
entry.stopPlay();
}
} |
JavaScript | onMouseOverMarking(event) {
let id = event.data,
entry = this.getEntryById(id);
entry.showEntryHighlight();
this.notifyAll(new Event("mouse-over-player-entry", id));
} | onMouseOverMarking(event) {
let id = event.data,
entry = this.getEntryById(id);
entry.showEntryHighlight();
this.notifyAll(new Event("mouse-over-player-entry", id));
} |
JavaScript | onMouseOutMarking(event) {
let id = event.data,
entry = this.getEntryById(id);
entry.deleteEntryHighlight();
this.notifyAll(new Event("mouse-out-player-entry", id));
} | onMouseOutMarking(event) {
let id = event.data,
entry = this.getEntryById(id);
entry.deleteEntryHighlight();
this.notifyAll(new Event("mouse-out-player-entry", id));
} |
JavaScript | onSubmit(){
// Data as JSON object stores email and password and the username
let data = {
email: this.viewEmail.value,
password: this.viewPassword.value,
username: this.viewUsername.value,
},
// Data is send with an new account-submit event
event = new Event("account-submit",data);
this.notifyAll(event);
} | onSubmit(){
// Data as JSON object stores email and password and the username
let data = {
email: this.viewEmail.value,
password: this.viewPassword.value,
username: this.viewUsername.value,
},
// Data is send with an new account-submit event
event = new Event("account-submit",data);
this.notifyAll(event);
} |
JavaScript | onFileDropped(file) {
this.showButton();
this.dropZone.onFileDropped(file);
this.currentFile = file;
} | onFileDropped(file) {
this.showButton();
this.dropZone.onFileDropped(file);
this.currentFile = file;
} |
JavaScript | async createSession(email, password) {
let promise = createSession(email, password),
res = await computePromise(promise),
// res is either true or false and is passed to the controller
event = new Event("login-result", res);
this.notifyAll(event);
} | async createSession(email, password) {
let promise = createSession(email, password),
res = await computePromise(promise),
// res is either true or false and is passed to the controller
event = new Event("login-result", res);
this.notifyAll(event);
} |
JavaScript | async function computePromise(promise) {
let res = await promise.then((res) => {
return {
login: true,
answer: res,
};
}, (error) => {
return {
login: false,
answer: error,
};
});
return res;
} | async function computePromise(promise) {
let res = await promise.then((res) => {
return {
login: true,
answer: res,
};
}, (error) => {
return {
login: false,
answer: error,
};
});
return res;
} |
JavaScript | pushRoute(event) {
event.preventDefault();
let url = event.target.href;
history.pushState(null, null, url);
// Push state does not fire hashchange -> dispatch the event on the window
window.dispatchEvent(new HashChangeEvent("hashchange"));
} | pushRoute(event) {
event.preventDefault();
let url = event.target.href;
history.pushState(null, null, url);
// Push state does not fire hashchange -> dispatch the event on the window
window.dispatchEvent(new HashChangeEvent("hashchange"));
} |
JavaScript | onHashChanged() {
let hash = window.location.hash,
route = ROUTES[hash] || ROUTES[404];
if (this.isDynamicShareRoute(window.location.hash)) {
hash = "#/share/:id";
route = ROUTES[hash];
} else if (this.isDynamicCreateRoute(window.location.hash)) {
hash = "#create";
route = ROUTES[hash];
}
fetch(route).then(res => {
let data = res.text();
data.then(res => {
let template = {
route: hash,
template: res,
},
event = new Event("template-ready", template);
this.notifyAll(event);
});
});
} | onHashChanged() {
let hash = window.location.hash,
route = ROUTES[hash] || ROUTES[404];
if (this.isDynamicShareRoute(window.location.hash)) {
hash = "#/share/:id";
route = ROUTES[hash];
} else if (this.isDynamicCreateRoute(window.location.hash)) {
hash = "#create";
route = ROUTES[hash];
}
fetch(route).then(res => {
let data = res.text();
data.then(res => {
let template = {
route: hash,
template: res,
},
event = new Event("template-ready", template);
this.notifyAll(event);
});
});
} |
JavaScript | onAudioFileRecorded(event) {
if (event.data) {
this.currentRecord.setAudio(event.data);
let ev = new Event("audio-recorded", this.currentRecord);
this.notifyAll(ev);
}
} | onAudioFileRecorded(event) {
if (event.data) {
this.currentRecord.setAudio(event.data);
let ev = new Event("audio-recorded", this.currentRecord);
this.notifyAll(ev);
}
} |
JavaScript | async function saveCast(title, codeHTML, self) {
let user = await getUser(),
castDocumentJSON,
records,
doesCastExistInCloud;
if (self.cast.castServerID) {
doesCastExistInCloud = true;
} else {
doesCastExistInCloud = false;
}
if (!self.cast.codeFileID) {
setNewCodeFileID(self);
}
deleteFile(self.cast.codeFileID).then();
setNewCodeFileID(self);
saveCodeAsFileToServer(codeHTML, self).then();
records = await recordManager.createDBRecord();
self.cast.setRecords(records);
castDocumentJSON = self.cast.getJSON(user);
if (doesCastExistInCloud) { //if the cast was already once saved in the cloud then update and don't create a new one
await updateDocument(Config.CAST_COLLECTION_ID, self.cast.castServerID, castDocumentJSON)
.then(self.notifyAll(new Event("cast-reached-cloud","cast reached cloud")));
} else { //create a new castDocument on the server
await createDocument(Config.CAST_COLLECTION_ID, castDocumentJSON)
.then(self.notifyAll(new Event("cast-reached-cloud","cast reached cloud")));
}
} | async function saveCast(title, codeHTML, self) {
let user = await getUser(),
castDocumentJSON,
records,
doesCastExistInCloud;
if (self.cast.castServerID) {
doesCastExistInCloud = true;
} else {
doesCastExistInCloud = false;
}
if (!self.cast.codeFileID) {
setNewCodeFileID(self);
}
deleteFile(self.cast.codeFileID).then();
setNewCodeFileID(self);
saveCodeAsFileToServer(codeHTML, self).then();
records = await recordManager.createDBRecord();
self.cast.setRecords(records);
castDocumentJSON = self.cast.getJSON(user);
if (doesCastExistInCloud) { //if the cast was already once saved in the cloud then update and don't create a new one
await updateDocument(Config.CAST_COLLECTION_ID, self.cast.castServerID, castDocumentJSON)
.then(self.notifyAll(new Event("cast-reached-cloud","cast reached cloud")));
} else { //create a new castDocument on the server
await createDocument(Config.CAST_COLLECTION_ID, castDocumentJSON)
.then(self.notifyAll(new Event("cast-reached-cloud","cast reached cloud")));
}
} |
JavaScript | async deleteCast(castID){
let cast = await getDocument(Config.CAST_COLLECTION_ID, castID),
codeFileID = cast.codeFileID,
records = cast.records;
await deleteFile(codeFileID);
for(let record of records){
let json= JSON.parse(record);
await deleteFile(json.id);
}
await deleteDocument(Config.CAST_COLLECTION_ID ,castID);
} | async deleteCast(castID){
let cast = await getDocument(Config.CAST_COLLECTION_ID, castID),
codeFileID = cast.codeFileID,
records = cast.records;
await deleteFile(codeFileID);
for(let record of records){
let json= JSON.parse(record);
await deleteFile(json.id);
}
await deleteDocument(Config.CAST_COLLECTION_ID ,castID);
} |
JavaScript | playAudio() {
let audio = new Audio(),
event = new Event("audio-play", this);
audio.src = this.audioFile;
audio.load();
audio.onloadeddata = () => audio.play();
audio.onended = () => onAudioEnd(this);
this.notifyAll(event);
this.currentAudio = audio;
} | playAudio() {
let audio = new Audio(),
event = new Event("audio-play", this);
audio.src = this.audioFile;
audio.load();
audio.onloadeddata = () => audio.play();
audio.onended = () => onAudioEnd(this);
this.notifyAll(event);
this.currentAudio = audio;
} |
JavaScript | function checkFile(event){
let res = "NOT A VALID FILE";
if(event.dataTransfer.items) {
// Check if dataTransfer is a file
if(event.dataTransfer.items[0].kind === "file"){
res = event.dataTransfer.items[0].getAsFile();
// Check if the file is a valid type (e.g. java, txt, js)
if (checkValidFileType(res)){
return res;
}
}
}
// No valid file
res = null;
return res;
} | function checkFile(event){
let res = "NOT A VALID FILE";
if(event.dataTransfer.items) {
// Check if dataTransfer is a file
if(event.dataTransfer.items[0].kind === "file"){
res = event.dataTransfer.items[0].getAsFile();
// Check if the file is a valid type (e.g. java, txt, js)
if (checkValidFileType(res)){
return res;
}
}
}
// No valid file
res = null;
return res;
} |
JavaScript | function checkValidFileType(file){
let boolean = false;
VALID_FILES.forEach((element) => {
// Checks if filename e.g. main.java includes a valid file type (String is in the file name -> valid)
if (file.name.includes(element)) {
boolean = true;
}
});
return boolean;
} | function checkValidFileType(file){
let boolean = false;
VALID_FILES.forEach((element) => {
// Checks if filename e.g. main.java includes a valid file type (String is in the file name -> valid)
if (file.name.includes(element)) {
boolean = true;
}
});
return boolean;
} |
JavaScript | onSubmit(event) {
let email = event.data.email,
password = event.data.password;
this.loginManager.createSession(email, password);
} | onSubmit(event) {
let email = event.data.email,
password = event.data.password;
this.loginManager.createSession(email, password);
} |
JavaScript | onLoginResult(event) {
let bool = event.data.login;
if (bool) {
window.location.hash = "home";
this.navView.showNavView();
} else {
this.loginView.clearInputs();
this.loginView.setServerAnswer(event.data.answer.message);
}
} | onLoginResult(event) {
let bool = event.data.login;
if (bool) {
window.location.hash = "home";
this.navView.showNavView();
} else {
this.loginView.clearInputs();
this.loginView.setServerAnswer(event.data.answer.message);
}
} |
JavaScript | assignNewMarkings(id) {
let newMarkings = document.querySelectorAll("mark");
if (newMarkings) {
for (let i = 0; i < newMarkings.length; i++) {
if (!newMarkings[i].hasAttribute("data-id")) {
newMarkings[i].setAttribute("data-id", id);
newMarkings[i].addEventListener("mouseover", this.onMouseOverMarking.bind(this, id));
newMarkings[i].addEventListener("mouseout", this.onMouseOutMarking.bind(this, id));
}
}
}
} | assignNewMarkings(id) {
let newMarkings = document.querySelectorAll("mark");
if (newMarkings) {
for (let i = 0; i < newMarkings.length; i++) {
if (!newMarkings[i].hasAttribute("data-id")) {
newMarkings[i].setAttribute("data-id", id);
newMarkings[i].addEventListener("mouseover", this.onMouseOverMarking.bind(this, id));
newMarkings[i].addEventListener("mouseout", this.onMouseOutMarking.bind(this, id));
}
}
}
} |
JavaScript | removeUnconnectedMarkings() {
let markings = document.querySelectorAll("mark");
markings.forEach(el => {
if (!el.hasAttribute("data-id")) {
let innerEls = [];
el.childNodes.forEach(node => {
let el = node;
innerEls.push(el);
});
replaceElement(el, innerEls);
}
});
} | removeUnconnectedMarkings() {
let markings = document.querySelectorAll("mark");
markings.forEach(el => {
if (!el.hasAttribute("data-id")) {
let innerEls = [];
el.childNodes.forEach(node => {
let el = node;
innerEls.push(el);
});
replaceElement(el, innerEls);
}
});
} |
JavaScript | removeInnerMarks(){
let marksIn;
marksIn = document.querySelectorAll("span > mark");
marksIn.forEach(mark => {
let parentCopy = document.createElement("span"),
classlist = mark.parentNode.classList,
newElements = [];
parentCopy.innerHTML = mark.parentNode.innerHTML;
parentCopy.childNodes.forEach(node => {
let el = node;
if(node.nodeType === Node.TEXT_NODE){
el = document.createElement("span");
el.innerHTML = node.data;
}
if(el.tagName !== "MARK"){
if(el.classList.length === 0 && classlist.length !== 0){
el.classList = classlist;
}
}else{
let inner = el.innerHTML,
newInner = document.createElement("span");
newInner.innerHTML = inner;
if(classlist.length !== 0){
newInner.classList = classlist;
}
el.innerHTML = "";
el.appendChild(newInner);
}
newElements.push(el);
});
replaceElement(mark.parentNode, newElements);
});
} | removeInnerMarks(){
let marksIn;
marksIn = document.querySelectorAll("span > mark");
marksIn.forEach(mark => {
let parentCopy = document.createElement("span"),
classlist = mark.parentNode.classList,
newElements = [];
parentCopy.innerHTML = mark.parentNode.innerHTML;
parentCopy.childNodes.forEach(node => {
let el = node;
if(node.nodeType === Node.TEXT_NODE){
el = document.createElement("span");
el.innerHTML = node.data;
}
if(el.tagName !== "MARK"){
if(el.classList.length === 0 && classlist.length !== 0){
el.classList = classlist;
}
}else{
let inner = el.innerHTML,
newInner = document.createElement("span");
newInner.innerHTML = inner;
if(classlist.length !== 0){
newInner.classList = classlist;
}
el.innerHTML = "";
el.appendChild(newInner);
}
newElements.push(el);
});
replaceElement(mark.parentNode, newElements);
});
} |
JavaScript | function replaceElement(elementRep, list){
for(let el of list){
elementRep.parentNode.insertBefore(el, elementRep);
}
elementRep.parentNode.removeChild(elementRep);
} | function replaceElement(elementRep, list){
for(let el of list){
elementRep.parentNode.insertBefore(el, elementRep);
}
elementRep.parentNode.removeChild(elementRep);
} |
JavaScript | function connectSpans(mark){
let elements = mark.childNodes,
prevEl = elements[0];
for (let i = 1; i < elements.length; i++) {
if (prevEl.tagName === "SPAN" && elements[i].tagName === "SPAN") {
// How to compare two arrays, retrieved from https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript on 10.04.22
if (compareClassLists(Array.from(prevEl.classList),Array.from(elements[i].classList))) {
let newSpan = document.createElement("span");
newSpan.classList = prevEl.classList;
newSpan.innerHTML = prevEl.innerHTML + elements[i].innerHTML;
prevEl.parentNode.insertBefore(newSpan, prevEl);
prevEl.parentNode.removeChild(prevEl);
elements[i].parentNode.removeChild(elements[i]);
i -=1;
prevEl = elements[i];
} else {
prevEl = elements[i];
}
} else {
prevEl = elements[i];
}
}
} | function connectSpans(mark){
let elements = mark.childNodes,
prevEl = elements[0];
for (let i = 1; i < elements.length; i++) {
if (prevEl.tagName === "SPAN" && elements[i].tagName === "SPAN") {
// How to compare two arrays, retrieved from https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript on 10.04.22
if (compareClassLists(Array.from(prevEl.classList),Array.from(elements[i].classList))) {
let newSpan = document.createElement("span");
newSpan.classList = prevEl.classList;
newSpan.innerHTML = prevEl.innerHTML + elements[i].innerHTML;
prevEl.parentNode.insertBefore(newSpan, prevEl);
prevEl.parentNode.removeChild(prevEl);
elements[i].parentNode.removeChild(elements[i]);
i -=1;
prevEl = elements[i];
} else {
prevEl = elements[i];
}
} else {
prevEl = elements[i];
}
}
} |
JavaScript | function convertTextToSpans(nodes){
for (let node of nodes){
if(node.nodeType === Node.TEXT_NODE){
let span = document.createElement("span");
span.innerText = node.data;
node.replaceWith(span);
}
}
} | function convertTextToSpans(nodes){
for (let node of nodes){
if(node.nodeType === Node.TEXT_NODE){
let span = document.createElement("span");
span.innerText = node.data;
node.replaceWith(span);
}
}
} |
JavaScript | function compareClassLists(list1, list2){
if(list1.length !== list2.length || list1.length === 0){
return false;
}
for(let i = 0; i < list1.length; i++){
if(list1[i] !== list2[i]){
return false;
}
}
return true;
} | function compareClassLists(list1, list2){
if(list1.length !== list2.length || list1.length === 0){
return false;
}
for(let i = 0; i < list1.length; i++){
if(list1[i] !== list2[i]){
return false;
}
}
return true;
} |
JavaScript | async createUser(email, password, username){
let promise = createUser(email,password, username),
res = await computePromise(promise),
event = new Event("account-result", res);
this.notifyAll(event);
} | async createUser(email, password, username){
let promise = createUser(email,password, username),
res = await computePromise(promise),
event = new Event("account-result", res);
this.notifyAll(event);
} |
JavaScript | async function computePromise(promise){
let res = await promise.then((res) => {
return {
register: true,
answer: res,
};
}, (error) => {
return {
register: false,
answer: error,
};
});
return res;
} | async function computePromise(promise){
let res = await promise.then((res) => {
return {
register: true,
answer: res,
};
}, (error) => {
return {
register: false,
answer: error,
};
});
return res;
} |
JavaScript | fillUserData(accountData) {
let username = accountData.user.name,
email = accountData.user.email;
this.accountManager.currentUsername = username;
this.accountManager.currentEmail = email;
this.accountView.setUsername(username);
this.accountView.setEmail(email);
} | fillUserData(accountData) {
let username = accountData.user.name,
email = accountData.user.email;
this.accountManager.currentUsername = username;
this.accountManager.currentEmail = email;
this.accountView.setUsername(username);
this.accountView.setEmail(email);
} |
JavaScript | onAccountSubmit(event) {
let username = event.data.username,
email = event.data.email,
password = event.data.password;
if (username.trim() === "") {
username = email;
}
this.accountManager.onAccountSubmit(username, email, password);
} | onAccountSubmit(event) {
let username = event.data.username,
email = event.data.email,
password = event.data.password;
if (username.trim() === "") {
username = email;
}
this.accountManager.onAccountSubmit(username, email, password);
} |
JavaScript | onUpdateError(event) {
this.accountView.setUsername(this.accountManager.currentUsername);
this.accountView.setEmail(this.accountManager.currentEmail);
this.accountView.clearPassword();
this.accountView.setError(event.data);
} | onUpdateError(event) {
this.accountView.setUsername(this.accountManager.currentUsername);
this.accountView.setEmail(this.accountManager.currentEmail);
this.accountView.clearPassword();
this.accountView.setError(event.data);
} |
JavaScript | initDragAndDrop() {
this.view.setAttribute("draggable", true);
this.view.addEventListener("dragstart", this.onDrag.bind(this));
this.view.addEventListener("dragover", this.onDragOver.bind(this));
this.view.addEventListener("dragend", this.onDragEnd.bind(this));
} | initDragAndDrop() {
this.view.setAttribute("draggable", true);
this.view.addEventListener("dragstart", this.onDrag.bind(this));
this.view.addEventListener("dragover", this.onDragOver.bind(this));
this.view.addEventListener("dragend", this.onDragEnd.bind(this));
} |
JavaScript | onDragOver(event) {
let droppedPlace = event.currentTarget,
e = new Event("drag-over", {
id: this.view.getAttribute("data-id"),
placeId: droppedPlace.getAttribute("data-id"),
});
event.preventDefault();
this.notifyAll(e);
} | onDragOver(event) {
let droppedPlace = event.currentTarget,
e = new Event("drag-over", {
id: this.view.getAttribute("data-id"),
placeId: droppedPlace.getAttribute("data-id"),
});
event.preventDefault();
this.notifyAll(e);
} |
JavaScript | createPlayerEntry() {
let view = document.createElement("div");
view.innerHTML = TEMPLATE;
return view.firstChild;
} | createPlayerEntry() {
let view = document.createElement("div");
view.innerHTML = TEMPLATE;
return view.firstChild;
} |
JavaScript | showPlay() {
let audioLength,
startTime = Date.now();
this.view.classList.add("player-list-entry-mark");
this.timerInterval = setInterval(() => {
let currentTime = Date.now(),
formatter = new Intl.NumberFormat("de-DE", { minimumIntegerDigits: 2 }),
minutes,
seconds;
audioLength = Math.floor((currentTime - startTime) / Config.MS_OF_SEC);
minutes = formatter.format(Math.floor(audioLength / Config.SEC_OF_MIN));
seconds = formatter.format(audioLength % Config.SEC_OF_MIN);
audioLength = minutes + ":" + seconds;
this.setTimeView(audioLength);
}, Config.INTERVAL_REFRESH_RATE);
this.playIcon.classList.add("hidden");
this.stopIcon.classList.remove("hidden");
} | showPlay() {
let audioLength,
startTime = Date.now();
this.view.classList.add("player-list-entry-mark");
this.timerInterval = setInterval(() => {
let currentTime = Date.now(),
formatter = new Intl.NumberFormat("de-DE", { minimumIntegerDigits: 2 }),
minutes,
seconds;
audioLength = Math.floor((currentTime - startTime) / Config.MS_OF_SEC);
minutes = formatter.format(Math.floor(audioLength / Config.SEC_OF_MIN));
seconds = formatter.format(audioLength % Config.SEC_OF_MIN);
audioLength = minutes + ":" + seconds;
this.setTimeView(audioLength);
}, Config.INTERVAL_REFRESH_RATE);
this.playIcon.classList.add("hidden");
this.stopIcon.classList.remove("hidden");
} |
JavaScript | stopPlay() {
this.view.classList.remove("player-list-entry-mark");
clearInterval(this.timerInterval);
this.setTimeView("00:00");
this.playIcon.classList.remove("hidden");
this.stopIcon.classList.add("hidden");
} | stopPlay() {
this.view.classList.remove("player-list-entry-mark");
clearInterval(this.timerInterval);
this.setTimeView("00:00");
this.playIcon.classList.remove("hidden");
this.stopIcon.classList.add("hidden");
} |
JavaScript | notifyAll(event) {
if (this.listener[event.type] !== undefined) {
for (let i = 0; i < this.listener[event.type].length; i++) {
this.listener[event.type][i](event);
}
}
} | notifyAll(event) {
if (this.listener[event.type] !== undefined) {
for (let i = 0; i < this.listener[event.type].length; i++) {
this.listener[event.type][i](event);
}
}
} |
JavaScript | onCastsRetrieved(event) {
let data = event.data;
getUser().then(res => {
let user = res;
data.documents.forEach(document => {
// Hand document
if (document.userID === user.$id) {
let title = document.title,
id = document.$id,
link = "https://coderse.software-engineering.education/#/share/" + id;
this.homeView.addElement(title, id, link);
}
});
});
} | onCastsRetrieved(event) {
let data = event.data;
getUser().then(res => {
let user = res;
data.documents.forEach(document => {
// Hand document
if (document.userID === user.$id) {
let title = document.title,
id = document.$id,
link = "https://coderse.software-engineering.education/#/share/" + id;
this.homeView.addElement(title, id, link);
}
});
});
} |
JavaScript | showTutorial() {
introJs().setOptions({
steps: [{
title: "Welcome to CODERSE!",
intro: "Hey you! This is your place to comment your code with audio-records and spread it to the world. ",
}, {
title: "Home",
intro: "This is your <strong>homescreen</strong>! You can see you saved pod ... eh codecasts. You can share or delete every cast. To edit a cast just click on it.",
element: document.querySelector("#cast-list"),
}, {
title: "Account",
intro: "View your <strong>account settings</strong> or <strong>logout</strong> by clicking on your username.",
element: document.querySelector("#user-dropdown"),
}, {
title: "Create cast",
intro: "Let's create a new cast!",
element: document.querySelector(".fab-create-cast"),
}],
tooltipClass: "custom-tooltip",
}).start();
} | showTutorial() {
introJs().setOptions({
steps: [{
title: "Welcome to CODERSE!",
intro: "Hey you! This is your place to comment your code with audio-records and spread it to the world. ",
}, {
title: "Home",
intro: "This is your <strong>homescreen</strong>! You can see you saved pod ... eh codecasts. You can share or delete every cast. To edit a cast just click on it.",
element: document.querySelector("#cast-list"),
}, {
title: "Account",
intro: "View your <strong>account settings</strong> or <strong>logout</strong> by clicking on your username.",
element: document.querySelector("#user-dropdown"),
}, {
title: "Create cast",
intro: "Let's create a new cast!",
element: document.querySelector(".fab-create-cast"),
}],
tooltipClass: "custom-tooltip",
}).start();
} |
JavaScript | castSafe() {
let title = this.castTitle.value,
event = new Event("cast-safe", title);
this.showLoadingAnimation();
this.notifyAll(event);
} | castSafe() {
let title = this.castTitle.value,
event = new Event("cast-safe", title);
this.showLoadingAnimation();
this.notifyAll(event);
} |
JavaScript | async createDBRecord() {
let files = await this.getRecords(),
results = [],
records = [];
// Deleting all the files from records that did get deleted from the Cast, but still have files on the server
for (let fileID of this.deletedFiles) {
await deleteFile(fileID);
}
files.forEach(async (file) => {
deleteFile(file.name)
.then(async () => await createFile(file.name, file))
.catch(async () => await createFile(file.name, file));
results.push(file.name);
});
for (let result of results) {
records.push(JSON.stringify({
id: result,
title: this.data.filter(entry => entry.getID() === result)[0].getTitle(),
time: this.data.filter(entry => entry.getID() === result)[0].getTime(),
}));
}
return records;
} | async createDBRecord() {
let files = await this.getRecords(),
results = [],
records = [];
// Deleting all the files from records that did get deleted from the Cast, but still have files on the server
for (let fileID of this.deletedFiles) {
await deleteFile(fileID);
}
files.forEach(async (file) => {
deleteFile(file.name)
.then(async () => await createFile(file.name, file))
.catch(async () => await createFile(file.name, file));
results.push(file.name);
});
for (let result of results) {
records.push(JSON.stringify({
id: result,
title: this.data.filter(entry => entry.getID() === result)[0].getTitle(),
time: this.data.filter(entry => entry.getID() === result)[0].getTime(),
}));
}
return records;
} |
JavaScript | deleteRecord(id) {
let recordToDelete = this.data.filter(entry => entry.getID() === id)[0],
deletedIndex = this.getIndexFromRecord(recordToDelete);
if (this.data[this.index] !== null && this.data[this.index] !== undefined) {
if (this.data[this.index].getID() === id) {
this.data[this.index].stopAudio();
if (this.playAllActive) {
this.playCast(this.index + 1);
}
}
}
this.data = this.data.filter(entry => entry.getID() !== id);
if (this.index > deletedIndex) {
this.index--;
}
// We keep track of the deleted file IDs so when the cast is saved (from an edit point of view)
// we have to delete these files, because they would be staying on the DB Storage otherwise
this.deletedFiles.push(id);
} | deleteRecord(id) {
let recordToDelete = this.data.filter(entry => entry.getID() === id)[0],
deletedIndex = this.getIndexFromRecord(recordToDelete);
if (this.data[this.index] !== null && this.data[this.index] !== undefined) {
if (this.data[this.index].getID() === id) {
this.data[this.index].stopAudio();
if (this.playAllActive) {
this.playCast(this.index + 1);
}
}
}
this.data = this.data.filter(entry => entry.getID() !== id);
if (this.index > deletedIndex) {
this.index--;
}
// We keep track of the deleted file IDs so when the cast is saved (from an edit point of view)
// we have to delete these files, because they would be staying on the DB Storage otherwise
this.deletedFiles.push(id);
} |
JavaScript | playRecord(id) {
let record = this.data.filter(entry => entry.getID() === id)[0];
if (this.data[this.index] !== null && this.data[this.index] !== undefined) {
if (this.data[this.index].getID() !== id) {
this.onAudioEnd(this.data[this.index]);
}
}
this.onAudioPlayed(record);
this.index = this.getIndexFromRecord(record);
record.playAudio();
} | playRecord(id) {
let record = this.data.filter(entry => entry.getID() === id)[0];
if (this.data[this.index] !== null && this.data[this.index] !== undefined) {
if (this.data[this.index].getID() !== id) {
this.onAudioEnd(this.data[this.index]);
}
}
this.onAudioPlayed(record);
this.index = this.getIndexFromRecord(record);
record.playAudio();
} |
JavaScript | onRecordEnd(event) {
if (this.playAllActive) {
this.playCast(this.index + 1);
}
this.notifyAll(event);
} | onRecordEnd(event) {
if (this.playAllActive) {
this.playCast(this.index + 1);
}
this.notifyAll(event);
} |
JavaScript | onNextRecord() {
this.onAudioEnd(this.data[this.index]);
if (this.index + 1 < this.data.length) {
this.index++;
this.data[this.index].playAudio();
// Event to tell UI that this element is done playing
this.onAudioPlayed(this.data[this.index]);
} else {
this.onEndOfAutoplay();
}
} | onNextRecord() {
this.onAudioEnd(this.data[this.index]);
if (this.index + 1 < this.data.length) {
this.index++;
this.data[this.index].playAudio();
// Event to tell UI that this element is done playing
this.onAudioPlayed(this.data[this.index]);
} else {
this.onEndOfAutoplay();
}
} |
JavaScript | onPreviousRecord() {
if (this.data[this.index] !== undefined && this.data[this.index] !== null) {
this.onAudioEnd(this.data[this.index]);
if (this.index - 1 >= 0) {
this.index--;
this.data[this.index].playAudio();
this.onAudioPlayed(this.data[this.index]);
} else {
this.onEndOfAutoplay();
}
}
} | onPreviousRecord() {
if (this.data[this.index] !== undefined && this.data[this.index] !== null) {
this.onAudioEnd(this.data[this.index]);
if (this.index - 1 >= 0) {
this.index--;
this.data[this.index].playAudio();
this.onAudioPlayed(this.data[this.index]);
} else {
this.onEndOfAutoplay();
}
}
} |
JavaScript | onAudioEnd(record) {
record.stopAudio();
let event = new Event("audio-end", record);
this.notifyAll(event);
} | onAudioEnd(record) {
record.stopAudio();
let event = new Event("audio-end", record);
this.notifyAll(event);
} |
JavaScript | onRecordListChanged(recordIDs) {
let records = [];
recordIDs.forEach(recordID => {
let record = this.data.filter(entry => entry.getID() === recordID)[0];
records.push(record);
});
this.data = records;
} | onRecordListChanged(recordIDs) {
let records = [];
recordIDs.forEach(recordID => {
let record = this.data.filter(entry => entry.getID() === recordID)[0];
records.push(record);
});
this.data = records;
} |
JavaScript | onSubmit(event) {
let email = event.data.email,
password = event.data.password,
username = event.data.username;
if (username.trim() === "") {
username = email;
}
this.registerManager.createUser(email, password, username);
} | onSubmit(event) {
let email = event.data.email,
password = event.data.password,
username = event.data.username;
if (username.trim() === "") {
username = email;
}
this.registerManager.createUser(email, password, username);
} |
JavaScript | onAccountResult(event) {
let bool = event.data.register;
if (bool) {
// Instead of creating a session for the new user, we redirect to the login page
// where he can login
window.location.hash = "login";
}
this.registerView.setServerAnswer(event.data.answer.message);
} | onAccountResult(event) {
let bool = event.data.register;
if (bool) {
// Instead of creating a session for the new user, we redirect to the login page
// where he can login
window.location.hash = "login";
}
this.registerView.setServerAnswer(event.data.answer.message);
} |
JavaScript | onHelpClicked() {
LocalStorageProvider.setCreateCastOnBoarding("start");
if (this.dropView.hidden) {
LocalStorageProvider.setCreateCastOnBoarding("drag-done");
this.showAdvancedIntro();
} else {
this.computeOnboarding(false);
}
} | onHelpClicked() {
LocalStorageProvider.setCreateCastOnBoarding("start");
if (this.dropView.hidden) {
LocalStorageProvider.setCreateCastOnBoarding("drag-done");
this.showAdvancedIntro();
} else {
this.computeOnboarding(false);
}
} |
JavaScript | computeOnboarding(id) {
// If it is a share screen, onboarding is not needed
if (id) {
LocalStorageProvider.setCreateCastOnBoarding("done");
}
let onBoardingDone = LocalStorageProvider.getCreateCastOnBoarding();
if (onBoardingDone === null || onBoardingDone === "start") {
introJs().setOptions({
steps: [{
title: "Load your code!",
intro: "Start your cast by choosing a file you'd like to describe and share. You can either <strong>drag and drop</strong> or <strong>load</strong> your code-file from your explorer.",
element: document.querySelector(".main-right-drag-drop-container"),
}],
tooltipClass: "custom-tooltip",
}).start();
LocalStorageProvider.setCreateCastOnBoarding("drag-done");
}
} | computeOnboarding(id) {
// If it is a share screen, onboarding is not needed
if (id) {
LocalStorageProvider.setCreateCastOnBoarding("done");
}
let onBoardingDone = LocalStorageProvider.getCreateCastOnBoarding();
if (onBoardingDone === null || onBoardingDone === "start") {
introJs().setOptions({
steps: [{
title: "Load your code!",
intro: "Start your cast by choosing a file you'd like to describe and share. You can either <strong>drag and drop</strong> or <strong>load</strong> your code-file from your explorer.",
element: document.querySelector(".main-right-drag-drop-container"),
}],
tooltipClass: "custom-tooltip",
}).start();
LocalStorageProvider.setCreateCastOnBoarding("drag-done");
}
} |
JavaScript | showAdvancedIntro() {
let onBoardingDone = LocalStorageProvider.getCreateCastOnBoarding();
if (onBoardingDone === "drag-done") {
LocalStorageProvider.setCreateCastOnBoarding("done");
introJs().setOptions({
steps: [{
title: "Cast title",
intro: "How would you like to name your codecast?",
element: document.querySelector(".code-cast-title"),
}, {
title: "Code markings",
intro: "Select ranges of code you want to describe by audio recordings. Selected codeparts are lightblue.",
element: document.querySelector(".main-right"),
}, {
title: "Add voice recordings",
intro: "Over here you can make a <strong>voice recording</strong>. If you've marked code, the audio will be connected to it after you saved it. Before saving the audio, you can still make further markings that will be added. Additionally you can customize the audio title.",
element: document.querySelector(".bottom-right"),
}, {
title: "Edit your recordings!",
intro: "Hover over audios to see which marked code snippet belongs to it. Listen to your records, change their title or delete them. Grab one to change the order.",
element: document.querySelector(".main-left"),
}, {
title: "Listen to your cast!",
intro: "Listen through all your records, and navigate between them.",
element: document.querySelector(".bottom-left"),
}, {
title: "Save your cast!",
intro: "Click this button to save your cast. </br> You can still come back later to edit this cast.",
element: document.querySelector(".button-save"),
}],
tooltipClass: "custom-tooltip",
}).start();
}
} | showAdvancedIntro() {
let onBoardingDone = LocalStorageProvider.getCreateCastOnBoarding();
if (onBoardingDone === "drag-done") {
LocalStorageProvider.setCreateCastOnBoarding("done");
introJs().setOptions({
steps: [{
title: "Cast title",
intro: "How would you like to name your codecast?",
element: document.querySelector(".code-cast-title"),
}, {
title: "Code markings",
intro: "Select ranges of code you want to describe by audio recordings. Selected codeparts are lightblue.",
element: document.querySelector(".main-right"),
}, {
title: "Add voice recordings",
intro: "Over here you can make a <strong>voice recording</strong>. If you've marked code, the audio will be connected to it after you saved it. Before saving the audio, you can still make further markings that will be added. Additionally you can customize the audio title.",
element: document.querySelector(".bottom-right"),
}, {
title: "Edit your recordings!",
intro: "Hover over audios to see which marked code snippet belongs to it. Listen to your records, change their title or delete them. Grab one to change the order.",
element: document.querySelector(".main-left"),
}, {
title: "Listen to your cast!",
intro: "Listen through all your records, and navigate between them.",
element: document.querySelector(".bottom-left"),
}, {
title: "Save your cast!",
intro: "Click this button to save your cast. </br> You can still come back later to edit this cast.",
element: document.querySelector(".button-save"),
}],
tooltipClass: "custom-tooltip",
}).start();
}
} |
JavaScript | onCastDownloaded(event) {
let castJSON = event.data,
cast = new Cast(castJSON.title);
cast.codeFileID = castJSON.codeFileID;
cast.castServerID = castJSON.$id;
cast.records = castJSON.records;
castManager.onCastDownloaded(cast);
this.navView.showTitle(castJSON.title);
this.dropView.hide();
} | onCastDownloaded(event) {
let castJSON = event.data,
cast = new Cast(castJSON.title);
cast.codeFileID = castJSON.codeFileID;
cast.castServerID = castJSON.$id;
cast.records = castJSON.records;
castManager.onCastDownloaded(cast);
this.navView.showTitle(castJSON.title);
this.dropView.hide();
} |
JavaScript | onAudioDownloaded(event) {
let recordData = event.data;
for (let record of recordData) {
castManager.addRecord(record);
}
this.notifyAll(new Event("content-load", "content loaded"));
} | onAudioDownloaded(event) {
let recordData = event.data;
for (let record of recordData) {
castManager.addRecord(record);
}
this.notifyAll(new Event("content-load", "content loaded"));
} |
JavaScript | onEntryDelete(event) {
let entryID = event.data.data.attributes[1].value;
castManager.deleteRecord(entryID);
this.codeView.removeMarkingsById(entryID);
} | onEntryDelete(event) {
let entryID = event.data.data.attributes[1].value;
castManager.deleteRecord(entryID);
this.codeView.removeMarkingsById(entryID);
} |
JavaScript | onEntryPlay(event) {
let entryID = event.data;
castManager.playRecord(entryID);
this.codeView.highlightPlayMarking(entryID);
} | onEntryPlay(event) {
let entryID = event.data;
castManager.playRecord(entryID);
this.codeView.highlightPlayMarking(entryID);
} |
JavaScript | onEntryStop(event) {
let entryID = event.data;
castManager.stopPlayRecord(entryID);
this.playerControls.resetIcons();
this.codeView.resetPlayMarking(entryID);
} | onEntryStop(event) {
let entryID = event.data;
castManager.stopPlayRecord(entryID);
this.playerControls.resetIcons();
this.codeView.resetPlayMarking(entryID);
} |
JavaScript | onPlayRecords() {
if (this.playerList.hasNoEntries()) {
this.playerControls.resetIcons();
} else {
castManager.playCast();
}
} | onPlayRecords() {
if (this.playerList.hasNoEntries()) {
this.playerControls.resetIcons();
} else {
castManager.playCast();
}
} |
JavaScript | async onAccountDelete(password){
let user = await getUser(),
docs = await listDocuments(Config.CAST_COLLECTION_ID),
userDocs = docs.documents.filter( doc => doc.userID === user.$id),
checkPassword = await this.checkPassword(user.email, password);
if(!checkPassword.value){
this.notifyAll(new Event("update-error", "To delete your account, you have to pass your accounts password: " + checkPassword.error.message));
return;
}
for(let doc of userDocs){
let castId = doc.$id,
codeFileId = doc.codeFileID,
records = doc.records;
await deleteFile(codeFileId);
for(let record of records){
let recordId = JSON.parse(record).id;
await deleteFile(recordId);
}
await deleteDocument(Config.CAST_COLLECTION_ID,castId);
}
await deleteUser();
await deleteSession();
} | async onAccountDelete(password){
let user = await getUser(),
docs = await listDocuments(Config.CAST_COLLECTION_ID),
userDocs = docs.documents.filter( doc => doc.userID === user.$id),
checkPassword = await this.checkPassword(user.email, password);
if(!checkPassword.value){
this.notifyAll(new Event("update-error", "To delete your account, you have to pass your accounts password: " + checkPassword.error.message));
return;
}
for(let doc of userDocs){
let castId = doc.$id,
codeFileId = doc.codeFileID,
records = doc.records;
await deleteFile(codeFileId);
for(let record of records){
let recordId = JSON.parse(record).id;
await deleteFile(recordId);
}
await deleteDocument(Config.CAST_COLLECTION_ID,castId);
}
await deleteUser();
await deleteSession();
} |
JavaScript | async checkPassword(email, password){
let res = {
error: "error",
value: true,
};
await updateEmail(email, password).catch(e => res.error = e);
if(Config.PW_ERRORCODES.includes(res.error.code.toString())){
res.value = false;
}
return res;
} | async checkPassword(email, password){
let res = {
error: "error",
value: true,
};
await updateEmail(email, password).catch(e => res.error = e);
if(Config.PW_ERRORCODES.includes(res.error.code.toString())){
res.value = false;
}
return res;
} |
JavaScript | function createModal() {
let view = document.createElement("div");
view.innerHTML = TEMPLATE;
return view.firstChild;
} | function createModal() {
let view = document.createElement("div");
view.innerHTML = TEMPLATE;
return view.firstChild;
} |
JavaScript | onHashChanged(event) {
getAuth().then(res => {
// The case we have a good result
// Now we have to test if a user is logged in or not
let logged = res.login;
if (logged) {
this.navView.setCurrentlyLoggedInUser(res.user.name);
}
this.computeCurrentPage(event, logged);
});
} | onHashChanged(event) {
getAuth().then(res => {
// The case we have a good result
// Now we have to test if a user is logged in or not
let logged = res.login;
if (logged) {
this.navView.setCurrentlyLoggedInUser(res.user.name);
}
this.computeCurrentPage(event, logged);
});
} |
JavaScript | computeCurrentPage(event, loggedIn) {
let currentHash = window.location.hash;
// If a user is logged in, he should not be able to view login and register page
// FROM HERE
// If a user starts the app
if (currentHash === "") {
this.setHash("login");
}
if (!this.router.isDynamicShareRoute(currentHash)) {
if (loggedIn) {
if (currentHash === "#login" || currentHash === "#register") {
this.setHash("home");
}
} else {
if (currentHash !== "#login" && currentHash !== "#register" && currentHash !== "#impressum" &&
currentHash !== "#datenschutz") {
this.setHash("landing");
}
}
}
// TO HERE
this.router.onHashChanged(event);
} | computeCurrentPage(event, loggedIn) {
let currentHash = window.location.hash;
// If a user is logged in, he should not be able to view login and register page
// FROM HERE
// If a user starts the app
if (currentHash === "") {
this.setHash("login");
}
if (!this.router.isDynamicShareRoute(currentHash)) {
if (loggedIn) {
if (currentHash === "#login" || currentHash === "#register") {
this.setHash("home");
}
} else {
if (currentHash !== "#login" && currentHash !== "#register" && currentHash !== "#impressum" &&
currentHash !== "#datenschutz") {
this.setHash("landing");
}
}
}
// TO HERE
this.router.onHashChanged(event);
} |
JavaScript | async computeShareScreen() {
let id = window.location.hash.substring(Config.URL_SUBSTRING_START),
// If there is a document with the id of the url -> the cast will be displayed
castExists = await getDocument(Config.CAST_COLLECTION_ID, id).then(res => {
let data = {
state: true,
answer: res,
};
return data;
}, () => {
this.setHash("error/404");
return false;
});
return castExists;
} | async computeShareScreen() {
let id = window.location.hash.substring(Config.URL_SUBSTRING_START),
// If there is a document with the id of the url -> the cast will be displayed
castExists = await getDocument(Config.CAST_COLLECTION_ID, id).then(res => {
let data = {
state: true,
answer: res,
};
return data;
}, () => {
this.setHash("error/404");
return false;
});
return castExists;
} |
JavaScript | function resolveVariant(owner, fullName, candidates) {
assert(
'expected owner to be an object',
owner !== null && typeof owner === 'object'
);
assert(
'expected owner.hasRegistration to be a function',
typeof owner.hasRegistration === 'function'
);
assert(
'expected owner.factoryFor to be a function',
typeof owner.factoryFor === 'function'
);
assert(
`expected '${fullName}' to be a service name`,
typeof fullName === 'string' && fullName.startsWith('service:')
);
assert(
`expected '${fullName}' to be registered`,
owner.hasRegistration(fullName)
);
assert(
'expected candidates to be an array of strings',
Array.isArray(candidates) && candidates.every((c) => typeof c === 'string')
);
for (let candidate of candidates) {
let parts = candidate.split('/');
parts.push(`-${parts.pop()}`);
let candidateFullName = `${fullName}/${parts.join('/')}`;
if (owner.hasRegistration(candidateFullName)) {
let factory = owner.factoryFor(candidateFullName);
assert(
`expected '${candidateFullName}' to be a valid factory`,
factory !== null &&
typeof factory === 'object' &&
typeof factory.class === 'function'
);
return factory.class;
}
}
return null;
} | function resolveVariant(owner, fullName, candidates) {
assert(
'expected owner to be an object',
owner !== null && typeof owner === 'object'
);
assert(
'expected owner.hasRegistration to be a function',
typeof owner.hasRegistration === 'function'
);
assert(
'expected owner.factoryFor to be a function',
typeof owner.factoryFor === 'function'
);
assert(
`expected '${fullName}' to be a service name`,
typeof fullName === 'string' && fullName.startsWith('service:')
);
assert(
`expected '${fullName}' to be registered`,
owner.hasRegistration(fullName)
);
assert(
'expected candidates to be an array of strings',
Array.isArray(candidates) && candidates.every((c) => typeof c === 'string')
);
for (let candidate of candidates) {
let parts = candidate.split('/');
parts.push(`-${parts.pop()}`);
let candidateFullName = `${fullName}/${parts.join('/')}`;
if (owner.hasRegistration(candidateFullName)) {
let factory = owner.factoryFor(candidateFullName);
assert(
`expected '${candidateFullName}' to be a valid factory`,
factory !== null &&
typeof factory === 'object' &&
typeof factory.class === 'function'
);
return factory.class;
}
}
return null;
} |
JavaScript | function sendCommand(input) {
let userid = $("#user-id").data('user-id');
roomChannel.send({ type: "gamecontrol", command: input, id: userid });
var btn = $(this);
btn.prop('disabled', true);
setTimeout(function() {
btn.prop('disabled', false) }, 1000);
} | function sendCommand(input) {
let userid = $("#user-id").data('user-id');
roomChannel.send({ type: "gamecontrol", command: input, id: userid });
var btn = $(this);
btn.prop('disabled', true);
setTimeout(function() {
btn.prop('disabled', false) }, 1000);
} |
JavaScript | function bindEvent(element, name, func) {
if (element.addEventListener) { // W3C
element.addEventListener(name, func, false);
} else if (element.attachEvent) { // IE
element.attachEvent('on' + name, func);
}
} | function bindEvent(element, name, func) {
if (element.addEventListener) { // W3C
element.addEventListener(name, func, false);
} else if (element.attachEvent) { // IE
element.attachEvent('on' + name, func);
}
} |
JavaScript | function backup_blocks() {
console.log('backup');
if ('localStorage' in window) {
var xml = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
console.log(xml);
window.localStorage.setItem('arenomat', Blockly.Xml.domToText(xml));
}
} | function backup_blocks() {
console.log('backup');
if ('localStorage' in window) {
var xml = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
console.log(xml);
window.localStorage.setItem('arenomat', Blockly.Xml.domToText(xml));
}
} |
JavaScript | function restore_blocks() {
if ('localStorage' in window && window.localStorage.arenomat) {
var xml = Blockly.Xml.textToDom(window.localStorage.arenomat);
Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xml);
}
} | function restore_blocks() {
if ('localStorage' in window && window.localStorage.arenomat) {
var xml = Blockly.Xml.textToDom(window.localStorage.arenomat);
Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xml);
}
} |
JavaScript | normalizeConfig (config) {
config = config.server || config
const headers = getHeadersToRecord(config)
const validateStatus = getStatusValidator(config)
const hooks = getHooks(config)
const filter = urlFilter.getFilter(config)
const expandRouteParameters = getExpandRouteParameters(config)
const synthesizeRequestingContext = getSynthesizeRequestingContext(config)
return Object.assign({}, config, {
headers,
validateStatus,
hooks,
filter,
expandRouteParameters,
synthesizeRequestingContext
})
} | normalizeConfig (config) {
config = config.server || config
const headers = getHeadersToRecord(config)
const validateStatus = getStatusValidator(config)
const hooks = getHooks(config)
const filter = urlFilter.getFilter(config)
const expandRouteParameters = getExpandRouteParameters(config)
const synthesizeRequestingContext = getSynthesizeRequestingContext(config)
return Object.assign({}, config, {
headers,
validateStatus,
hooks,
filter,
expandRouteParameters,
synthesizeRequestingContext
})
} |
JavaScript | instrument (tracer, config, req, res, name, callback) {
this.patch(req)
const span = startSpan(tracer, config, req, res, name)
// TODO: replace this with a REFERENCE_NOOP after we split http/express/etc
if (!config.filter(req.url)) {
span.context()._sampling.drop = true
}
if (config.service) {
span.setTag(SERVICE_NAME, config.service)
}
analyticsSampler.sample(span, config.analytics, true)
wrapEnd(req)
wrapEvents(req)
if (config.enableServerTiming) {
if (!res._sfx_serverTimingAdded) {
res.setHeader('Server-Timing', traceParentHeader(span.context()))
res.setHeader('Access-Control-Expose-Headers', 'Server-Timing')
Object.defineProperty(res, '_sfx_serverTimingAdded', { value: true })
}
}
return callback && tracer.scope().activate(span, () => callback(span))
} | instrument (tracer, config, req, res, name, callback) {
this.patch(req)
const span = startSpan(tracer, config, req, res, name)
// TODO: replace this with a REFERENCE_NOOP after we split http/express/etc
if (!config.filter(req.url)) {
span.context()._sampling.drop = true
}
if (config.service) {
span.setTag(SERVICE_NAME, config.service)
}
analyticsSampler.sample(span, config.analytics, true)
wrapEnd(req)
wrapEvents(req)
if (config.enableServerTiming) {
if (!res._sfx_serverTimingAdded) {
res.setHeader('Server-Timing', traceParentHeader(span.context()))
res.setHeader('Access-Control-Expose-Headers', 'Server-Timing')
Object.defineProperty(res, '_sfx_serverTimingAdded', { value: true })
}
}
return callback && tracer.scope().activate(span, () => callback(span))
} |
JavaScript | finish (req, error) {
if (!this.active(req)) return
const span = req._datadog.middleware.pop()
if (span) {
if (error) {
span.addTags({
'sfx.error.kind': error.name,
'sfx.error.message': error.message,
'sfx.error.stack': error.stack
})
}
span.finish()
}
} | finish (req, error) {
if (!this.active(req)) return
const span = req._datadog.middleware.pop()
if (span) {
if (error) {
span.addTags({
'sfx.error.kind': error.name,
'sfx.error.message': error.message,
'sfx.error.stack': error.stack
})
}
span.finish()
}
} |
JavaScript | patch (req) {
if (req._datadog) return
Object.defineProperty(req, '_datadog', {
value: {
span: null,
paths: [],
middleware: [],
beforeEnd: [],
childOfRequestingContext: false
}
})
} | patch (req) {
if (req._datadog) return
Object.defineProperty(req, '_datadog', {
value: {
span: null,
paths: [],
middleware: [],
beforeEnd: [],
childOfRequestingContext: false
}
})
} |
JavaScript | function expandRouteParameters (httpRoute, req) {
let expandedPath = httpRoute // default w/o expansion
const expansionRules = req._datadog.config.expandRouteParameters[httpRoute]
if (expansionRules === undefined) {
return expandedPath
}
const keys = []
const re = pathToRegexp(httpRoute, keys)
// Account for routing-reduced paths
const path = req.originalUrl.substring(0, req.originalUrl.indexOf(req.path) + req.path.length)
const matches = re.exec(path)
if (matches === null) {
return expandedPath
}
const hits = matches.slice(1, keys.length + 1)
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
if (expansionRules[key.name] === true) {
const replacePattern = `:${key.name}`
const patternIndex = expandedPath.indexOf(replacePattern)
// get substrings before and after :key.name
const before = expandedPath.substring(0, patternIndex)
let after = expandedPath.substring(patternIndex + replacePattern.length)
// remove immediate capture group from after substring
let capGroupMatches
try {
capGroupMatches = xregexp.matchRecursive(after, '\\(', '\\)')
} catch (err) { // will throw if unbalanced parens in data (nothing we can do)
capGroupMatches = []
}
if (capGroupMatches.length >= 1) {
// replace stripped outer parens from recursive match and remove from after substring
const replacedGroup = `(${capGroupMatches[0]})`
const replacedGroupIndex = after.indexOf(replacedGroup)
after = after.substring(replacedGroupIndex + replacedGroup.length)
}
// recreate expanded path with truncated substring
// set expandedPath to be replaced :key.name w/ value
expandedPath = before + hits[i] + after
}
}
return expandedPath
} | function expandRouteParameters (httpRoute, req) {
let expandedPath = httpRoute // default w/o expansion
const expansionRules = req._datadog.config.expandRouteParameters[httpRoute]
if (expansionRules === undefined) {
return expandedPath
}
const keys = []
const re = pathToRegexp(httpRoute, keys)
// Account for routing-reduced paths
const path = req.originalUrl.substring(0, req.originalUrl.indexOf(req.path) + req.path.length)
const matches = re.exec(path)
if (matches === null) {
return expandedPath
}
const hits = matches.slice(1, keys.length + 1)
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
if (expansionRules[key.name] === true) {
const replacePattern = `:${key.name}`
const patternIndex = expandedPath.indexOf(replacePattern)
// get substrings before and after :key.name
const before = expandedPath.substring(0, patternIndex)
let after = expandedPath.substring(patternIndex + replacePattern.length)
// remove immediate capture group from after substring
let capGroupMatches
try {
capGroupMatches = xregexp.matchRecursive(after, '\\(', '\\)')
} catch (err) { // will throw if unbalanced parens in data (nothing we can do)
capGroupMatches = []
}
if (capGroupMatches.length >= 1) {
// replace stripped outer parens from recursive match and remove from after substring
const replacedGroup = `(${capGroupMatches[0]})`
const replacedGroupIndex = after.indexOf(replacedGroup)
after = after.substring(replacedGroupIndex + replacedGroup.length)
}
// recreate expanded path with truncated substring
// set expandedPath to be replaced :key.name w/ value
expandedPath = before + hits[i] + after
}
}
return expandedPath
} |
JavaScript | callCollectionAction(method, name, action, data = {}) {
// get adapter
let adapter = this.adapterFor(name, action);
// build url
let url = `${adapter.buildURL(name)}/${action}`;
// make request
return adapter.ajax(url, method, {
data,
});
} | callCollectionAction(method, name, action, data = {}) {
// get adapter
let adapter = this.adapterFor(name, action);
// build url
let url = `${adapter.buildURL(name)}/${action}`;
// make request
return adapter.ajax(url, method, {
data,
});
} |
JavaScript | callResourceAction(method, name, id, action, data = {}) {
// get adapter
let adapter = this.adapterFor(name, action);
// build url
let url = `${adapter.buildURL(name, id)}/${action}`;
// make request
return adapter.ajax(url, method, {
data,
});
} | callResourceAction(method, name, id, action, data = {}) {
// get adapter
let adapter = this.adapterFor(name, action);
// build url
let url = `${adapter.buildURL(name, id)}/${action}`;
// make request
return adapter.ajax(url, method, {
data,
});
} |
JavaScript | @action
async upload(model, field, multiple, file) {
// get access token
let { access_token } = this.session.data.authenticated;
try {
// upload file
const res = await file.uploadBinary(this.uploadURL, {
contentType: file.blob.type,
headers: {
Authorization: `Bearer ${access_token}`,
'Content-Disposition': `attachment; filename="${file.blob.name}"`,
},
});
// get key
let {
keys: [key],
} = JSON.parse(res.body);
// read as url for preview
const buf = await file.readAsArrayBuffer();
// create blob url
let url = URL.createObjectURL(new Blob([buf], { type: file.blob.type }));
// create link
let link = this.factory(makeRef(), file.blob.name, file.blob.type, file.blob.size, key, '');
link.preview = url;
// set link
if (multiple) {
// get list
let list = [];
if (model.get(field)) {
list = model.get(field).toArray();
}
// add link
model.set(field, A(list.concat([link])));
} else {
// set link
model.set(field, link);
}
} catch (err) {
// remove from queue
file.queue.remove(file);
// rethrow
throw err;
}
} | @action
async upload(model, field, multiple, file) {
// get access token
let { access_token } = this.session.data.authenticated;
try {
// upload file
const res = await file.uploadBinary(this.uploadURL, {
contentType: file.blob.type,
headers: {
Authorization: `Bearer ${access_token}`,
'Content-Disposition': `attachment; filename="${file.blob.name}"`,
},
});
// get key
let {
keys: [key],
} = JSON.parse(res.body);
// read as url for preview
const buf = await file.readAsArrayBuffer();
// create blob url
let url = URL.createObjectURL(new Blob([buf], { type: file.blob.type }));
// create link
let link = this.factory(makeRef(), file.blob.name, file.blob.type, file.blob.size, key, '');
link.preview = url;
// set link
if (multiple) {
// get list
let list = [];
if (model.get(field)) {
list = model.get(field).toArray();
}
// add link
model.set(field, A(list.concat([link])));
} else {
// set link
model.set(field, link);
}
} catch (err) {
// remove from queue
file.queue.remove(file);
// rethrow
throw err;
}
} |
JavaScript | @action
remove(model, field, link) {
// remove link
model.set(field, model.get(field).without(link));
} | @action
remove(model, field, link) {
// remove link
model.set(field, model.get(field).without(link));
} |
JavaScript | @computed('data', 'userModel', 'dataKey')
get model() {
// check existence
if (!this.data) {
return Promise.reject();
}
// find user
return this.store.findRecord(this.userModel, this.data.get(this.dataKey));
} | @computed('data', 'userModel', 'dataKey')
get model() {
// check existence
if (!this.data) {
return Promise.reject();
}
// find user
return this.store.findRecord(this.userModel, this.data.get(this.dataKey));
} |
JavaScript | handleDirtyUpdate(model) {
// ask to continue
alert('This model has been updated.\nWe will now reset it to reflect the latest changes.');
// rollback and reload
model.rollbackAttributes();
model.reload();
} | handleDirtyUpdate(model) {
// ask to continue
alert('This model has been updated.\nWe will now reset it to reflect the latest changes.');
// rollback and reload
model.rollbackAttributes();
model.reload();
} |
JavaScript | handleDirtyDelete(model) {
// inform
alert('This model has been deleted.\nWe will remove it to reflect the latest changes.');
// rollback and unload
model.rollbackAttributes();
model.deleteRecord();
model.unloadRecord();
// transition to root
this.routing.transitionTo('application');
} | handleDirtyDelete(model) {
// inform
alert('This model has been deleted.\nWe will remove it to reflect the latest changes.');
// rollback and unload
model.rollbackAttributes();
model.deleteRecord();
model.unloadRecord();
// transition to root
this.routing.transitionTo('application');
} |
JavaScript | subscribe(name, data = {}, replace = true) {
// return if subscription exists and should not be replaced
if (!replace && this.subscriptions[name]) {
return;
}
// store subscription
this.subscriptions[name] = data;
// return if not connected
if (!this.connected) {
return;
}
// prepare command
let cmd = {
subscribe: {
[name]: data,
},
};
// send command
this.websocket.send(JSON.stringify(cmd));
} | subscribe(name, data = {}, replace = true) {
// return if subscription exists and should not be replaced
if (!replace && this.subscriptions[name]) {
return;
}
// store subscription
this.subscriptions[name] = data;
// return if not connected
if (!this.connected) {
return;
}
// prepare command
let cmd = {
subscribe: {
[name]: data,
},
};
// send command
this.websocket.send(JSON.stringify(cmd));
} |
JavaScript | unsubscribe(name) {
// delete subscription
delete this.subscriptions[name];
// return if not connected
if (!this.connected) {
return;
}
// prepare command
let cmd = {
unsubscribe: [name],
};
// send command
this.websocket.send(JSON.stringify(cmd));
} | unsubscribe(name) {
// delete subscription
delete this.subscriptions[name];
// return if not connected
if (!this.connected) {
return;
}
// prepare command
let cmd = {
unsubscribe: [name],
};
// send command
this.websocket.send(JSON.stringify(cmd));
} |
JavaScript | function caption(caption, imageURL=IMAGE_URL, tags="mockery"){
return new Promise((resolve, reject) => {
const options =
{
tag: tags,
transformation:
[{
width: 400,
overlay:
{
font_family: "Times",
font_size: 64,
text: caption
},
gravity: "south",
y: 20,
color: "white",
crop: "fit"
}]
}
cloudinary.uploader.upload(imageURL, options)
.then(image => {
console.log("* " + image.public_id);
console.log("* " + image.url);
resolve({
url:image.url,
id:image.public_id
});
})
.catch(error => {if (error) throw error});
});
} | function caption(caption, imageURL=IMAGE_URL, tags="mockery"){
return new Promise((resolve, reject) => {
const options =
{
tag: tags,
transformation:
[{
width: 400,
overlay:
{
font_family: "Times",
font_size: 64,
text: caption
},
gravity: "south",
y: 20,
color: "white",
crop: "fit"
}]
}
cloudinary.uploader.upload(imageURL, options)
.then(image => {
console.log("* " + image.public_id);
console.log("* " + image.url);
resolve({
url:image.url,
id:image.public_id
});
})
.catch(error => {if (error) throw error});
});
} |
JavaScript | function remove(publicID){
cloudinary.uploader.destroy(publicID)
.then(response => {
console.log(response);
})
.catch(error => {if (error) throw error});
} | function remove(publicID){
cloudinary.uploader.destroy(publicID)
.then(response => {
console.log(response);
})
.catch(error => {if (error) throw error});
} |
JavaScript | function respond() {
const request = JSON.parse(this.request.chunks[0]),
nameCheck = new RegExp("@" + BOTNAME, 'im');
let botResponse = "come again?";
// if bot is mentioned
if (request.text.match(nameCheck)) {
if (request.text.match(COMMANDS[0])) {
// sanitize the incoming message and use it as a response
botResponse = request.text.replace(nameCheck, '')
.replace(COMMANDS[0], '');
this.response.writeHead(200);
utils.sendMessage("Aight Chief");
// caption an image with the text and post it
mock(botResponse, () => {
this.response.end();
});
} else {
this.response.writeHead(200);
this.response.end();
}
}
} | function respond() {
const request = JSON.parse(this.request.chunks[0]),
nameCheck = new RegExp("@" + BOTNAME, 'im');
let botResponse = "come again?";
// if bot is mentioned
if (request.text.match(nameCheck)) {
if (request.text.match(COMMANDS[0])) {
// sanitize the incoming message and use it as a response
botResponse = request.text.replace(nameCheck, '')
.replace(COMMANDS[0], '');
this.response.writeHead(200);
utils.sendMessage("Aight Chief");
// caption an image with the text and post it
mock(botResponse, () => {
this.response.end();
});
} else {
this.response.writeHead(200);
this.response.end();
}
}
} |
JavaScript | function mock(text) {
// randomize capitaliztion
let newChar, i, coinFace,
captionText = text.toLowerCase();
for (i = 0; i < text.length; i++) {
newChar = text.substr(i, 1);
coinFace = Math.round(Math.random());
if (coinFace) {
newChar = newChar.toUpperCase();
}
captionText = captionText.substring(0, i);
captionText += newChar;
captionText += text.substring(i + 1);
}
// overlay the text over the image
caption(captionText)
// upload image to groupme server
.then(image => {
// cloudinary returns http link and groupme only accepts https
// so change from http to https
image.url = image.url.replace(/^http/,'https');
utils.getImageURL(image.url)
.then((groupmeURL) => {
return utils.postImage(groupmeURL, "Here you go little feller");
})
.then((statusCode) => {
if(statusCode == 202){
remove(image.id, (error, result) => {
if (error) throw error;
return result;
});
}
})
.catch((error) => {if(error) throw error});
})
.catch((error) => {if(error) throw error});
} | function mock(text) {
// randomize capitaliztion
let newChar, i, coinFace,
captionText = text.toLowerCase();
for (i = 0; i < text.length; i++) {
newChar = text.substr(i, 1);
coinFace = Math.round(Math.random());
if (coinFace) {
newChar = newChar.toUpperCase();
}
captionText = captionText.substring(0, i);
captionText += newChar;
captionText += text.substring(i + 1);
}
// overlay the text over the image
caption(captionText)
// upload image to groupme server
.then(image => {
// cloudinary returns http link and groupme only accepts https
// so change from http to https
image.url = image.url.replace(/^http/,'https');
utils.getImageURL(image.url)
.then((groupmeURL) => {
return utils.postImage(groupmeURL, "Here you go little feller");
})
.then((statusCode) => {
if(statusCode == 202){
remove(image.id, (error, result) => {
if (error) throw error;
return result;
});
}
})
.catch((error) => {if(error) throw error});
})
.catch((error) => {if(error) throw error});
} |
JavaScript | function update() {
// if popper is destroyed, don't perform any further update
if (this.state.isDestroyed) {
return;
}
var data = {
instance: this,
styles: {},
arrowStyles: {},
attributes: {},
flipped: false,
offsets: {}
};
// compute reference element offsets
data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference);
// compute auto placement, store placement inside the data object,
// modifiers will be able to edit `placement` if needed
// and refer to originalPlacement to know the original value
data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding);
// store the computed placement inside `originalPlacement`
data.originalPlacement = data.placement;
// compute the popper offsets
data.offsets.popper = getPopperOffsets(this.popper, data.offsets.reference, data.placement);
data.offsets.popper.position = 'absolute';
// run the modifiers
data = runModifiers(this.modifiers, data);
// the first `update` will call `onCreate` callback
// the other ones will call `onUpdate` callback
if (!this.state.isCreated) {
this.state.isCreated = true;
this.options.onCreate(data);
} else {
this.options.onUpdate(data);
}
} | function update() {
// if popper is destroyed, don't perform any further update
if (this.state.isDestroyed) {
return;
}
var data = {
instance: this,
styles: {},
arrowStyles: {},
attributes: {},
flipped: false,
offsets: {}
};
// compute reference element offsets
data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference);
// compute auto placement, store placement inside the data object,
// modifiers will be able to edit `placement` if needed
// and refer to originalPlacement to know the original value
data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding);
// store the computed placement inside `originalPlacement`
data.originalPlacement = data.placement;
// compute the popper offsets
data.offsets.popper = getPopperOffsets(this.popper, data.offsets.reference, data.placement);
data.offsets.popper.position = 'absolute';
// run the modifiers
data = runModifiers(this.modifiers, data);
// the first `update` will call `onCreate` callback
// the other ones will call `onUpdate` callback
if (!this.state.isCreated) {
this.state.isCreated = true;
this.options.onCreate(data);
} else {
this.options.onUpdate(data);
}
} |
JavaScript | function disableEventListeners() {
if (this.state.eventsEnabled) {
window.cancelAnimationFrame(this.scheduleUpdate);
this.state = removeEventListeners(this.reference, this.state);
}
} | function disableEventListeners() {
if (this.state.eventsEnabled) {
window.cancelAnimationFrame(this.scheduleUpdate);
this.state = removeEventListeners(this.reference, this.state);
}
} |
JavaScript | function applyStyleOnLoad(reference, popper, options, modifierOptions, state) {
// compute reference element offsets
var referenceOffsets = getReferenceOffsets(state, popper, reference);
// compute auto placement, store placement inside the data object,
// modifiers will be able to edit `placement` if needed
// and refer to originalPlacement to know the original value
var placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding);
popper.setAttribute('x-placement', placement);
// Apply `position` to popper before anything else because
// without the position applied we can't guarantee correct computations
setStyles(popper, { position: 'absolute' });
return options;
} | function applyStyleOnLoad(reference, popper, options, modifierOptions, state) {
// compute reference element offsets
var referenceOffsets = getReferenceOffsets(state, popper, reference);
// compute auto placement, store placement inside the data object,
// modifiers will be able to edit `placement` if needed
// and refer to originalPlacement to know the original value
var placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding);
popper.setAttribute('x-placement', placement);
// Apply `position` to popper before anything else because
// without the position applied we can't guarantee correct computations
setStyles(popper, { position: 'absolute' });
return options;
} |
JavaScript | function PrivateRoute({ component: Component, ...rest }) {
const { currentUser } = useAuth();
return (
<Route
{...rest}
render={props => {
return currentUser
? <Component {...props} />
: <Redirect to="/" />
}}
></Route>
);
} | function PrivateRoute({ component: Component, ...rest }) {
const { currentUser } = useAuth();
return (
<Route
{...rest}
render={props => {
return currentUser
? <Component {...props} />
: <Redirect to="/" />
}}
></Route>
);
} |
JavaScript | function addCallback (thisArg, callback) {
if (this._getIndexOf(thisArg,callback) === undefined) {
this._callbacks.push([thisArg, callback]);
}
} | function addCallback (thisArg, callback) {
if (this._getIndexOf(thisArg,callback) === undefined) {
this._callbacks.push([thisArg, callback]);
}
} |
JavaScript | function removeCallback (thisArg, callback) {
var foundIndex = this._getIndexOf(thisArg,callback);
if (foundIndex !== undefined) {
this._callbacks.splice(foundIndex, 1);
}
} | function removeCallback (thisArg, callback) {
var foundIndex = this._getIndexOf(thisArg,callback);
if (foundIndex !== undefined) {
this._callbacks.splice(foundIndex, 1);
}
} |
JavaScript | function callAll () {
// Convert arguments object to args array.
var args = Array.prototype.slice.call(arguments);
for (var i = 0; i < this._callbacks.length; i++) {
var thisArg = this._callbacks[i][0];
var callback = this._callbacks[i][1];
callback.apply(thisArg, args);
}
} | function callAll () {
// Convert arguments object to args array.
var args = Array.prototype.slice.call(arguments);
for (var i = 0; i < this._callbacks.length; i++) {
var thisArg = this._callbacks[i][0];
var callback = this._callbacks[i][1];
callback.apply(thisArg, args);
}
} |
JavaScript | function loadAuthenticatedURL (url, opts) {
var collectedContentDocument = '';
var collectedBytes = 0;
var messageSize = 0;
var self = this;
function handleResponseChunk(response) {
messageSize = parseInt(response.messageSize, 10);
collectedContentDocument += response.contentDocument;
collectedBytes += parseInt(response.chunkSize, 10);
if(collectedBytes < messageSize) {
return;
}
// Timeout already occurred - bail
if(!timeoutHandle) {
return;
}
window.clearTimeout(timeoutHandle);
self.removeNativeEventListener('getContentParameters', handleResponseChunk);
function decodeHTML(str) {
var e = document.createElement('div');
e.innerHTML = str;
return e.innerText;
}
if(response.status === 'ok') {
opts.onLoad(decodeHTML(collectedContentDocument));
} else {
opts.onError(decodeHTML(collectedContentDocument));
}
}
var timeoutHandle = window.setTimeout(function() {
timeoutHandle = 0;
opts.onError('timeout');
self.removeNativeEventListener('getContentParameters', handleResponseChunk);
}, opts.timeout || 10000);
this.addNativeEventListener('getContentParameters', handleResponseChunk);
this.nativeCommand('getContentParameters', {parameterUrl: url});
} | function loadAuthenticatedURL (url, opts) {
var collectedContentDocument = '';
var collectedBytes = 0;
var messageSize = 0;
var self = this;
function handleResponseChunk(response) {
messageSize = parseInt(response.messageSize, 10);
collectedContentDocument += response.contentDocument;
collectedBytes += parseInt(response.chunkSize, 10);
if(collectedBytes < messageSize) {
return;
}
// Timeout already occurred - bail
if(!timeoutHandle) {
return;
}
window.clearTimeout(timeoutHandle);
self.removeNativeEventListener('getContentParameters', handleResponseChunk);
function decodeHTML(str) {
var e = document.createElement('div');
e.innerHTML = str;
return e.innerText;
}
if(response.status === 'ok') {
opts.onLoad(decodeHTML(collectedContentDocument));
} else {
opts.onError(decodeHTML(collectedContentDocument));
}
}
var timeoutHandle = window.setTimeout(function() {
timeoutHandle = 0;
opts.onError('timeout');
self.removeNativeEventListener('getContentParameters', handleResponseChunk);
}, opts.timeout || 10000);
this.addNativeEventListener('getContentParameters', handleResponseChunk);
this.nativeCommand('getContentParameters', {parameterUrl: url});
} |
JavaScript | function _assertNoSideEffects(device, optionsParamFunction) {
var div, options1, options2, onComplete;
div = _createScrollableDiv(device);
// Create two options objects - one to pass to the styletopleft method, one for reference
options1 = _createStandardOptionsForElement(div);
options2 = _createStandardOptionsForElement(div);
// Ensure that options1 is the same as options2 after the call to styletopleft.
// (assertEquals does a deep comparison)
onComplete = function() {
assertEquals('Options is the same after tween has completed', options1, options2);
};
// Configure onComplete method on options object.
options1.onComplete = onComplete;
options2.onComplete = onComplete;
// Perform the styletopleft method.
optionsParamFunction.call(device, options1);
} | function _assertNoSideEffects(device, optionsParamFunction) {
var div, options1, options2, onComplete;
div = _createScrollableDiv(device);
// Create two options objects - one to pass to the styletopleft method, one for reference
options1 = _createStandardOptionsForElement(div);
options2 = _createStandardOptionsForElement(div);
// Ensure that options1 is the same as options2 after the call to styletopleft.
// (assertEquals does a deep comparison)
onComplete = function() {
assertEquals('Options is the same after tween has completed', options1, options2);
};
// Configure onComplete method on options object.
options1.onComplete = onComplete;
options2.onComplete = onComplete;
// Perform the styletopleft method.
optionsParamFunction.call(device, options1);
} |
JavaScript | function _createScrollableDiv(device) {
var div = device.createContainer('id_mask'),
inner = device.createContainer('id');
device.appendChildElement(div, inner);
return div;
} | function _createScrollableDiv(device) {
var div = device.createContainer('id_mask'),
inner = device.createContainer('id');
device.appendChildElement(div, inner);
return div;
} |
JavaScript | function _createStandardOptionsForElement(element) {
return {
el: element,
from: {
opacity: 0,
top: 0,
left: 0
},
to: {
opacity: 1,
top: 100,
left: 100
},
fps: 25,
duration: 10,
easing: 'linear',
skipAnim: true
};
} | function _createStandardOptionsForElement(element) {
return {
el: element,
from: {
opacity: 0,
top: 0,
left: 0
},
to: {
opacity: 1,
top: 100,
left: 100
},
fps: 25,
duration: 10,
easing: 'linear',
skipAnim: true
};
} |
JavaScript | function appendChildWidget (widget) {
if ((this._renderMode === List.RENDER_MODE_LIST) && !(widget instanceof ListItem)) {
var li = new ListItem();
li.appendChildWidget(widget);
li.setDataItem(widget.getDataItem());
appendChildWidget.base.call(this, li);
return li;
} else {
widget.addClass('listitem');
appendChildWidget.base.call(this, widget);
return widget;
}
} | function appendChildWidget (widget) {
if ((this._renderMode === List.RENDER_MODE_LIST) && !(widget instanceof ListItem)) {
var li = new ListItem();
li.appendChildWidget(widget);
li.setDataItem(widget.getDataItem());
appendChildWidget.base.call(this, li);
return li;
} else {
widget.addClass('listitem');
appendChildWidget.base.call(this, widget);
return widget;
}
} |
JavaScript | function insertChildWidget (index, widget) {
var w;
if ((this._renderMode === List.RENDER_MODE_LIST) && !(widget instanceof ListItem)) {
w = new ListItem();
w.appendChildWidget(widget);
w.setDataItem(widget.getDataItem());
insertChildWidget.base.call(this, index, w);
} else {
widget.addClass('listitem');
insertChildWidget.base.call(this, index, widget);
w = widget;
}
if (index <= this._selectedIndex &&
(( this._selectedIndex + 1 ) < this.getChildWidgetCount())) {
this._selectedIndex++;
}
return widget;
} | function insertChildWidget (index, widget) {
var w;
if ((this._renderMode === List.RENDER_MODE_LIST) && !(widget instanceof ListItem)) {
w = new ListItem();
w.appendChildWidget(widget);
w.setDataItem(widget.getDataItem());
insertChildWidget.base.call(this, index, w);
} else {
widget.addClass('listitem');
insertChildWidget.base.call(this, index, widget);
w = widget;
}
if (index <= this._selectedIndex &&
(( this._selectedIndex + 1 ) < this.getChildWidgetCount())) {
this._selectedIndex++;
}
return widget;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.