language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | set description(aValue)
{
if (this._descriptionNode) {
this._descriptionNode.setAttribute("value", aValue);
this._descriptionNode.setAttribute("tooltiptext", aValue);
}
return aValue;
} | set description(aValue)
{
if (this._descriptionNode) {
this._descriptionNode.setAttribute("value", aValue);
this._descriptionNode.setAttribute("tooltiptext", aValue);
}
return aValue;
} |
JavaScript | set details(aValue)
{
if (this._detailsNode) {
this._detailsNode.setAttribute("value", aValue);
this._detailsNode.setAttribute("tooltiptext", aValue);
}
return aValue;
} | set details(aValue)
{
if (this._detailsNode) {
this._detailsNode.setAttribute("value", aValue);
this._detailsNode.setAttribute("tooltiptext", aValue);
}
return aValue;
} |
JavaScript | get _summaryNode()
{
let node = document.getElementById("downloadsSummary");
if (!node) {
return null;
}
delete this._summaryNode;
return this._summaryNode = node;
} | get _summaryNode()
{
let node = document.getElementById("downloadsSummary");
if (!node) {
return null;
}
delete this._summaryNode;
return this._summaryNode = node;
} |
JavaScript | get _progressNode()
{
let node = document.getElementById("downloadsSummaryProgress");
if (!node) {
return null;
}
delete this._progressNode;
return this._progressNode = node;
} | get _progressNode()
{
let node = document.getElementById("downloadsSummaryProgress");
if (!node) {
return null;
}
delete this._progressNode;
return this._progressNode = node;
} |
JavaScript | get _descriptionNode()
{
let node = document.getElementById("downloadsSummaryDescription");
if (!node) {
return null;
}
delete this._descriptionNode;
return this._descriptionNode = node;
} | get _descriptionNode()
{
let node = document.getElementById("downloadsSummaryDescription");
if (!node) {
return null;
}
delete this._descriptionNode;
return this._descriptionNode = node;
} |
JavaScript | get _detailsNode()
{
let node = document.getElementById("downloadsSummaryDetails");
if (!node) {
return null;
}
delete this._detailsNode;
return this._detailsNode = node;
} | get _detailsNode()
{
let node = document.getElementById("downloadsSummaryDetails");
if (!node) {
return null;
}
delete this._detailsNode;
return this._detailsNode = node;
} |
JavaScript | set showingSummary(aValue)
{
if (this._footerNode) {
if (aValue) {
this._footerNode.setAttribute("showingsummary", "true");
} else {
this._footerNode.removeAttribute("showingsummary");
}
this._showingSummary = aValue;
}
return aValue;
} | set showingSummary(aValue)
{
if (this._footerNode) {
if (aValue) {
this._footerNode.setAttribute("showingsummary", "true");
} else {
this._footerNode.removeAttribute("showingsummary");
}
this._showingSummary = aValue;
}
return aValue;
} |
JavaScript | get _footerNode()
{
let node = document.getElementById("downloadsFooter");
if (!node) {
return null;
}
delete this._footerNode;
return this._footerNode = node;
} | get _footerNode()
{
let node = document.getElementById("downloadsFooter");
if (!node) {
return null;
}
delete this._footerNode;
return this._footerNode = node;
} |
JavaScript | get willOverrideHomepage() {
if (this._initialState && this._willRestore()) {
let windows = this._initialState.windows || null;
// If there are valid windows with not only pinned tabs, signal that we
// will override the default homepage by restoring a session.
return windows && windows.some(w => w.tabs.some(t => !t.pinned));
}
return false;
} | get willOverrideHomepage() {
if (this._initialState && this._willRestore()) {
let windows = this._initialState.windows || null;
// If there are valid windows with not only pinned tabs, signal that we
// will override the default homepage by restoring a session.
return windows && windows.some(w => w.tabs.some(t => !t.pinned));
}
return false;
} |
JavaScript | get strings()
{
let strings = {};
let sb = Services.strings.createBundle(kDownloadsStringBundleUrl);
let enumerator = sb.getSimpleEnumeration();
while (enumerator.hasMoreElements()) {
let string = enumerator.getNext().QueryInterface(Ci.nsIPropertyElement);
let stringName = string.key;
if (stringName in kDownloadsStringsRequiringFormatting) {
strings[stringName] = function() {
// Convert "arguments" to a real array before calling into XPCOM.
return sb.formatStringFromName(stringName,
Array.slice(arguments, 0),
arguments.length);
};
} else if (stringName in kDownloadsStringsRequiringPluralForm) {
strings[stringName] = function(aCount) {
// Convert "arguments" to a real array before calling into XPCOM.
let formattedString = sb.formatStringFromName(stringName,
Array.slice(arguments, 0),
arguments.length);
return PluralForm.get(aCount, formattedString);
};
} else {
strings[stringName] = string.value;
}
}
delete this.strings;
return this.strings = strings;
} | get strings()
{
let strings = {};
let sb = Services.strings.createBundle(kDownloadsStringBundleUrl);
let enumerator = sb.getSimpleEnumeration();
while (enumerator.hasMoreElements()) {
let string = enumerator.getNext().QueryInterface(Ci.nsIPropertyElement);
let stringName = string.key;
if (stringName in kDownloadsStringsRequiringFormatting) {
strings[stringName] = function() {
// Convert "arguments" to a real array before calling into XPCOM.
return sb.formatStringFromName(stringName,
Array.slice(arguments, 0),
arguments.length);
};
} else if (stringName in kDownloadsStringsRequiringPluralForm) {
strings[stringName] = function(aCount) {
// Convert "arguments" to a real array before calling into XPCOM.
let formattedString = sb.formatStringFromName(stringName,
Array.slice(arguments, 0),
arguments.length);
return PluralForm.get(aCount, formattedString);
};
} else {
strings[stringName] = string.value;
}
}
delete this.strings;
return this.strings = strings;
} |
JavaScript | get useToolkitUI()
{
/* Toolkit UI is currently incompatible.
* FIXME: Either fix the toolkitUI (make DBConnection work) or remove
* the unused code altogether
*/
//try {
// return Services.prefs.getBoolPref("browser.download.useToolkitUI");
//} catch (ex) { }
return false;
} | get useToolkitUI()
{
/* Toolkit UI is currently incompatible.
* FIXME: Either fix the toolkitUI (make DBConnection work) or remove
* the unused code altogether
*/
//try {
// return Services.prefs.getBoolPref("browser.download.useToolkitUI");
//} catch (ex) { }
return false;
} |
JavaScript | stateOfDownload(download) {
// Collapse state using the correct priority.
if (!download.stopped) {
return nsIDM.DOWNLOAD_DOWNLOADING;
}
if (download.succeeded) {
return nsIDM.DOWNLOAD_FINISHED;
}
if (download.error) {
if (download.error.becauseBlockedByParentalControls) {
return nsIDM.DOWNLOAD_BLOCKED_PARENTAL;
}
if (download.error.becauseBlockedByReputationCheck) {
return nsIDM.DOWNLOAD_DIRTY;
}
return nsIDM.DOWNLOAD_FAILED;
}
if (download.canceled) {
if (download.hasPartialData) {
return nsIDM.DOWNLOAD_PAUSED;
}
return nsIDM.DOWNLOAD_CANCELED;
}
return nsIDM.DOWNLOAD_NOTSTARTED;
} | stateOfDownload(download) {
// Collapse state using the correct priority.
if (!download.stopped) {
return nsIDM.DOWNLOAD_DOWNLOADING;
}
if (download.succeeded) {
return nsIDM.DOWNLOAD_FINISHED;
}
if (download.error) {
if (download.error.becauseBlockedByParentalControls) {
return nsIDM.DOWNLOAD_BLOCKED_PARENTAL;
}
if (download.error.becauseBlockedByReputationCheck) {
return nsIDM.DOWNLOAD_DIRTY;
}
return nsIDM.DOWNLOAD_FAILED;
}
if (download.canceled) {
if (download.hasPartialData) {
return nsIDM.DOWNLOAD_PAUSED;
}
return nsIDM.DOWNLOAD_CANCELED;
}
return nsIDM.DOWNLOAD_NOTSTARTED;
} |
JavaScript | removeAndFinalizeDownload(download) {
Downloads.getList(Downloads.ALL)
.then(list => list.remove(download))
.then(() => download.finalize(true))
.catch(Cu.reportError);
} | removeAndFinalizeDownload(download) {
Downloads.getList(Downloads.ALL)
.then(list => list.remove(download))
.then(() => download.finalize(true))
.catch(Cu.reportError);
} |
JavaScript | summarizeDownloads(downloads) {
let summary = {
numActive: 0,
numPaused: 0,
numDownloading: 0,
totalSize: 0,
totalTransferred: 0,
// slowestSpeed is Infinity so that we can use Math.min to
// find the slowest speed. We'll set this to 0 afterwards if
// it's still at Infinity by the time we're done iterating all
// download.
slowestSpeed: Infinity,
rawTimeLeft: -1,
percentComplete: -1
}
for (let download of downloads) {
summary.numActive++;
if (!download.stopped) {
summary.numDownloading++;
if (download.hasProgress && download.speed > 0) {
let sizeLeft = download.totalBytes - download.currentBytes;
summary.rawTimeLeft = Math.max(summary.rawTimeLeft,
sizeLeft / download.speed);
summary.slowestSpeed = Math.min(summary.slowestSpeed,
download.speed);
}
} else if (download.canceled && download.hasPartialData) {
summary.numPaused++;
}
// Only add to total values if we actually know the download size.
if (download.succeeded) {
summary.totalSize += download.target.size;
summary.totalTransferred += download.target.size;
} else if (download.hasProgress) {
summary.totalSize += download.totalBytes;
summary.totalTransferred += download.currentBytes;
}
}
if (summary.totalSize != 0) {
summary.percentComplete = (summary.totalTransferred /
summary.totalSize) * 100;
}
if (summary.slowestSpeed == Infinity) {
summary.slowestSpeed = 0;
}
return summary;
} | summarizeDownloads(downloads) {
let summary = {
numActive: 0,
numPaused: 0,
numDownloading: 0,
totalSize: 0,
totalTransferred: 0,
// slowestSpeed is Infinity so that we can use Math.min to
// find the slowest speed. We'll set this to 0 afterwards if
// it's still at Infinity by the time we're done iterating all
// download.
slowestSpeed: Infinity,
rawTimeLeft: -1,
percentComplete: -1
}
for (let download of downloads) {
summary.numActive++;
if (!download.stopped) {
summary.numDownloading++;
if (download.hasProgress && download.speed > 0) {
let sizeLeft = download.totalBytes - download.currentBytes;
summary.rawTimeLeft = Math.max(summary.rawTimeLeft,
sizeLeft / download.speed);
summary.slowestSpeed = Math.min(summary.slowestSpeed,
download.speed);
}
} else if (download.canceled && download.hasPartialData) {
summary.numPaused++;
}
// Only add to total values if we actually know the download size.
if (download.succeeded) {
summary.totalSize += download.target.size;
summary.totalTransferred += download.target.size;
} else if (download.hasProgress) {
summary.totalSize += download.totalBytes;
summary.totalTransferred += download.currentBytes;
}
}
if (summary.totalSize != 0) {
summary.percentComplete = (summary.totalTransferred /
summary.totalSize) * 100;
}
if (summary.slowestSpeed == Infinity) {
summary.slowestSpeed = 0;
}
return summary;
} |
JavaScript | function DownloadsDataCtor(aPrivate) {
this._isPrivate = aPrivate;
// Contains all the available Download objects and their integer state.
this.oldDownloadStates = new Map();
// Array of view objects that should be notified when the available download
// data changes.
this._views = [];
} | function DownloadsDataCtor(aPrivate) {
this._isPrivate = aPrivate;
// Contains all the available Download objects and their integer state.
this.oldDownloadStates = new Map();
// Array of view objects that should be notified when the available download
// data changes.
this._views = [];
} |
JavaScript | initializeDataLink() {
if (!this._dataLinkInitialized) {
let promiseList = Downloads.getList(this._isPrivate ? Downloads.PRIVATE
: Downloads.PUBLIC);
promiseList.then(list => list.addView(this)).then(null, Cu.reportError);
this._dataLinkInitialized = true;
}
} | initializeDataLink() {
if (!this._dataLinkInitialized) {
let promiseList = Downloads.getList(this._isPrivate ? Downloads.PRIVATE
: Downloads.PUBLIC);
promiseList.then(list => list.addView(this)).then(null, Cu.reportError);
this._dataLinkInitialized = true;
}
} |
JavaScript | get canRemoveFinished()
{
for (let download of this.downloads) {
// Stopped, paused, and failed downloads with partial data are removed.
if (download.stopped && !(download.canceled && download.hasPartialData)) {
return true;
}
}
return false;
} | get canRemoveFinished()
{
for (let download of this.downloads) {
// Stopped, paused, and failed downloads with partial data are removed.
if (download.stopped && !(download.canceled && download.hasPartialData)) {
return true;
}
}
return false;
} |
JavaScript | onDownloadAdded(download) {
// Download objects do not store the end time of downloads, as the Downloads
// API does not need to persist this information for all platforms. Once a
// download terminates on a Desktop browser, it becomes a history download,
// for which the end time is stored differently, as a Places annotation.
download.endTime = Date.now();
this.oldDownloadStates.set(download,
DownloadsCommon.stateOfDownload(download));
for (let view of this._views) {
view.onDownloadAdded(download, true);
}
} | onDownloadAdded(download) {
// Download objects do not store the end time of downloads, as the Downloads
// API does not need to persist this information for all platforms. Once a
// download terminates on a Desktop browser, it becomes a history download,
// for which the end time is stored differently, as a Places annotation.
download.endTime = Date.now();
this.oldDownloadStates.set(download,
DownloadsCommon.stateOfDownload(download));
for (let view of this._views) {
view.onDownloadAdded(download, true);
}
} |
JavaScript | get panelHasShownBefore() {
try {
return Services.prefs.getBoolPref("browser.download.panel.shown");
} catch (ex) { }
return false;
} | get panelHasShownBefore() {
try {
return Services.prefs.getBoolPref("browser.download.panel.shown");
} catch (ex) { }
return false;
} |
JavaScript | * _activeDownloads() {
let downloads = this._isPrivate ? PrivateDownloadsData.downloads
: DownloadsData.downloads;
for (let download of downloads) {
if (!download.stopped || (download.canceled && download.hasPartialData)) {
yield download;
}
}
} | * _activeDownloads() {
let downloads = this._isPrivate ? PrivateDownloadsData.downloads
: DownloadsData.downloads;
for (let download of downloads) {
if (!download.stopped || (download.canceled && download.hasPartialData)) {
yield download;
}
}
} |
JavaScript | function DownloadsSummaryData(aIsPrivate, aNumToExclude) {
this._numToExclude = aNumToExclude;
// Since we can have multiple instances of DownloadsSummaryData, we
// override these values from the prototype so that each instance can be
// completely separated from one another.
this._loading = false;
this._downloads = [];
// Floating point value indicating the last number of seconds estimated until
// the longest download will finish. We need to store this value so that we
// don't continuously apply smoothing if the actual download state has not
// changed. This is set to -1 if the previous value is unknown.
this._lastRawTimeLeft = -1;
// Last number of seconds estimated until all in-progress downloads with a
// known size and speed will finish. This value is stored to allow smoothing
// in case of small variations. This is set to -1 if the previous value is
// unknown.
this._lastTimeLeft = -1;
// The following properties are updated by _refreshProperties and are then
// propagated to the views.
this._showingProgress = false;
this._details = "";
this._description = "";
this._numActive = 0;
this._percentComplete = -1;
this._isPrivate = aIsPrivate;
this._views = [];
} | function DownloadsSummaryData(aIsPrivate, aNumToExclude) {
this._numToExclude = aNumToExclude;
// Since we can have multiple instances of DownloadsSummaryData, we
// override these values from the prototype so that each instance can be
// completely separated from one another.
this._loading = false;
this._downloads = [];
// Floating point value indicating the last number of seconds estimated until
// the longest download will finish. We need to store this value so that we
// don't continuously apply smoothing if the actual download state has not
// changed. This is set to -1 if the previous value is unknown.
this._lastRawTimeLeft = -1;
// Last number of seconds estimated until all in-progress downloads with a
// known size and speed will finish. This value is stored to allow smoothing
// in case of small variations. This is set to -1 if the previous value is
// unknown.
this._lastTimeLeft = -1;
// The following properties are updated by _refreshProperties and are then
// propagated to the views.
this._showingProgress = false;
this._details = "";
this._description = "";
this._numActive = 0;
this._percentComplete = -1;
this._isPrivate = aIsPrivate;
this._views = [];
} |
JavaScript | * _downloadsForSummary() {
if (this._downloads.length > 0) {
for (let i = this._numToExclude; i < this._downloads.length; ++i) {
yield this._downloads[i];
}
}
} | * _downloadsForSummary() {
if (this._downloads.length > 0) {
for (let i = this._numToExclude; i < this._downloads.length; ++i) {
yield this._downloads[i];
}
}
} |
JavaScript | get currentViewOptions() {
// Use ContentTree options as default.
let viewOptions = ContentTree.viewOptions;
if (this._specialViews.has(this.currentPlace)) {
let { view, options } = this._specialViews.get(this.currentPlace);
for (let option in options) {
viewOptions[option] = options[option];
}
}
return viewOptions;
} | get currentViewOptions() {
// Use ContentTree options as default.
let viewOptions = ContentTree.viewOptions;
if (this._specialViews.has(this.currentPlace)) {
let { view, options } = this._specialViews.get(this.currentPlace);
for (let option in options) {
viewOptions[option] = options[option];
}
}
return viewOptions;
} |
JavaScript | function addMail(localpart){
var data = {
"email": localpart,
"full_name": "Trash User",
"domain": domain,
"password": "trash_user"
};
// Send email url
$http.post(apiUrl + 'email', data).then(function(response) {
switch (response.data.message.code){
case 10: //Email created
popupShow(response.data.message.str, 1);
break;
case 11: //Email exist
popupShow(response.data.message.str, 2);
break;
default:
break;
}
// Redirect if email has been created or aleady exist
if(IsInArray(response.data.message.code, [10, 11])){
local = localpart;
//redirect to webmail
$location.path(`/webmail/${localpart}@${domain}`)
}
});
} | function addMail(localpart){
var data = {
"email": localpart,
"full_name": "Trash User",
"domain": domain,
"password": "trash_user"
};
// Send email url
$http.post(apiUrl + 'email', data).then(function(response) {
switch (response.data.message.code){
case 10: //Email created
popupShow(response.data.message.str, 1);
break;
case 11: //Email exist
popupShow(response.data.message.str, 2);
break;
default:
break;
}
// Redirect if email has been created or aleady exist
if(IsInArray(response.data.message.code, [10, 11])){
local = localpart;
//redirect to webmail
$location.path(`/webmail/${localpart}@${domain}`)
}
});
} |
JavaScript | function popupShow(message, type, buttonText, buttonFunction){
$scope.popupShow = true; //show popup
$scope.popupMessage = message; //set message
$scope.buttonShow = false; //Hide button. by default
//if buttonText defined show button
if(typeof buttonText != 'undefined'){
$scope.buttonShow = true;
$scope.buttonText = buttonText;
$scope.buttonFunction = buttonFunction;
}
// Set popup style
switch (type){
case 1:
$scope.popupStyle = "ok";
break;
case 2:
$scope.popupStyle = "error";
break;
}
} | function popupShow(message, type, buttonText, buttonFunction){
$scope.popupShow = true; //show popup
$scope.popupMessage = message; //set message
$scope.buttonShow = false; //Hide button. by default
//if buttonText defined show button
if(typeof buttonText != 'undefined'){
$scope.buttonShow = true;
$scope.buttonText = buttonText;
$scope.buttonFunction = buttonFunction;
}
// Set popup style
switch (type){
case 1:
$scope.popupStyle = "ok";
break;
case 2:
$scope.popupStyle = "error";
break;
}
} |
JavaScript | function crons(){
// Execute cron every 5 minutes
var deleteMail = schedule.scheduleJob('*/5 * * * *', function(){
title("Start deleting");
email.setDomain('maily.ovh');
email.list(function(emails){
for(var i = 0, len = emails.data.length; i < len; i++){
//Email address informations
var data = emails.data[i];
//Number of days since created
var oneDay = 24*60*60*1000;
var d = new Date(data.created);
var deltaDays = Math.round((Date.now() - d)/oneDay);
//If days before delete has been reached and the name is in the allowed names
if(deltaDays > config.main.daysBeforeDelete.address
&& isInArray(data.name, config.main.nameToDelete)){
//Allow to use data in callback. self-executing anonymous function;
(function(actData) {
mailFolderEmpty(actData.local_part, actData.domain, function(isEmpty){
if(isEmpty){
console.log(hourPrefixer(actData.username));
email.remove(actData.local_part, function(){
//TODO implement delete
});
}
});
})(data);
}
}
});
});
} | function crons(){
// Execute cron every 5 minutes
var deleteMail = schedule.scheduleJob('*/5 * * * *', function(){
title("Start deleting");
email.setDomain('maily.ovh');
email.list(function(emails){
for(var i = 0, len = emails.data.length; i < len; i++){
//Email address informations
var data = emails.data[i];
//Number of days since created
var oneDay = 24*60*60*1000;
var d = new Date(data.created);
var deltaDays = Math.round((Date.now() - d)/oneDay);
//If days before delete has been reached and the name is in the allowed names
if(deltaDays > config.main.daysBeforeDelete.address
&& isInArray(data.name, config.main.nameToDelete)){
//Allow to use data in callback. self-executing anonymous function;
(function(actData) {
mailFolderEmpty(actData.local_part, actData.domain, function(isEmpty){
if(isEmpty){
console.log(hourPrefixer(actData.username));
email.remove(actData.local_part, function(){
//TODO implement delete
});
}
});
})(data);
}
}
});
});
} |
JavaScript | function title(string){
console.log();
console.log();
console.log(hourPrefixer(`►▬▬▬▬ ${string} ▬▬▬▬◄`));
} | function title(string){
console.log();
console.log();
console.log(hourPrefixer(`►▬▬▬▬ ${string} ▬▬▬▬◄`));
} |
JavaScript | function mailFolderEmpty(localPart, domain, Callback){
//Count emails
dovetail.countEmail(localPart, domain, function(count){
if(count != 0)
Callback(false);
else
Callback(true);
});
} | function mailFolderEmpty(localPart, domain, Callback){
//Count emails
dovetail.countEmail(localPart, domain, function(count){
if(count != 0)
Callback(false);
else
Callback(true);
});
} |
JavaScript | function fromDoc(code, headingsLevel, fnAddTagsMarkdown) {
var i,
out,
sections;
// get all documentation sections from code
sections = getSections(code);
// initialize a string buffer
out = [];
//out.push("=".repeat(headingsLevel)+" Documentation"+"=".repeat(headingsLevel));
for (i = 0; i < sections.length; i++) {
out.push(fromSection(sections[i], headingsLevel, fnAddTagsMarkdown));
}
// return the contents of the string buffer and add a trailing newline
return out.join("")+"\n";
} | function fromDoc(code, headingsLevel, fnAddTagsMarkdown) {
var i,
out,
sections;
// get all documentation sections from code
sections = getSections(code);
// initialize a string buffer
out = [];
//out.push("=".repeat(headingsLevel)+" Documentation"+"=".repeat(headingsLevel));
for (i = 0; i < sections.length; i++) {
out.push(fromSection(sections[i], headingsLevel, fnAddTagsMarkdown));
}
// return the contents of the string buffer and add a trailing newline
return out.join("")+"\n";
} |
JavaScript | function fromSection(section, headingsLevel, fnAddTagsMarkdown) {
var assocBuffer,
description,
field,
out,
p,
t,
tags;
// initialize a string buffer
out = [];
// first get the field that we want to describe
field = getFieldDeclaration(section.line);
// if there is no field to describe
if (!field) {
// do not return any documentation
return "";
}
out.push("\n\n");
out.push("-".repeat(80));
out.push("\n\n");
out.push("=".repeat(5 - headingsLevel)+" "+field+" "+"=".repeat(5 - headingsLevel));
description = getDocDescription(section.doc);
if (description.length) {
out.push("\n\n");
out.push(description);
}
tags = getDocTags(section.doc);
if (tags.length) {
out.push("\n");
assocBuffer = {};
for (t = 0; t < tags.length; t++) {
fnAddTagsMarkdown(tags[t], assocBuffer);
}
for (p in assocBuffer) {
if (assocBuffer.hasOwnProperty(p)) {
out.push(fromTagGroup(p, assocBuffer[p]));
}
}
}
// return the contents of the string buffer
return out.join("");
} | function fromSection(section, headingsLevel, fnAddTagsMarkdown) {
var assocBuffer,
description,
field,
out,
p,
t,
tags;
// initialize a string buffer
out = [];
// first get the field that we want to describe
field = getFieldDeclaration(section.line);
// if there is no field to describe
if (!field) {
// do not return any documentation
return "";
}
out.push("\n\n");
out.push("-".repeat(80));
out.push("\n\n");
out.push("=".repeat(5 - headingsLevel)+" "+field+" "+"=".repeat(5 - headingsLevel));
description = getDocDescription(section.doc);
if (description.length) {
out.push("\n\n");
out.push(description);
}
tags = getDocTags(section.doc);
if (tags.length) {
out.push("\n");
assocBuffer = {};
for (t = 0; t < tags.length; t++) {
fnAddTagsMarkdown(tags[t], assocBuffer);
}
for (p in assocBuffer) {
if (assocBuffer.hasOwnProperty(p)) {
out.push(fromTagGroup(p, assocBuffer[p]));
}
}
}
// return the contents of the string buffer
return out.join("");
} |
JavaScript | function camelCase(str){
str = replaceAccents(str);
str = removeNonWord(str)
.replace(/\-/g, ' ') //convert all hyphens to spaces
.replace(/\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE
.replace(/\s+/g, '') //remove spaces
.replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase
return str;
} | function camelCase(str){
str = replaceAccents(str);
str = removeNonWord(str)
.replace(/\-/g, ' ') //convert all hyphens to spaces
.replace(/\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE
.replace(/\s+/g, '') //remove spaces
.replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase
return str;
} |
JavaScript | function unCamelCase(str){
str = str.replace(/([a-z\xE0-\xFF])([A-Z\xC0\xDF])/g, '$1 $2');
str = str.toLowerCase(); //add space between camelCase text
return str;
} | function unCamelCase(str){
str = str.replace(/([a-z\xE0-\xFF])([A-Z\xC0\xDF])/g, '$1 $2');
str = str.toLowerCase(); //add space between camelCase text
return str;
} |
JavaScript | function sentenceCase(str){
// Replace first char of each sentence (new line or after '.\s+') to
// UPPERCASE
return lowerCase(str).replace(/(^\w)|\.\s+(\w)/gm, upperCase);
} | function sentenceCase(str){
// Replace first char of each sentence (new line or after '.\s+') to
// UPPERCASE
return lowerCase(str).replace(/(^\w)|\.\s+(\w)/gm, upperCase);
} |
JavaScript | function slugify(str, delimeter){
if (delimeter == null) {
delimeter = "-";
}
str = replaceAccents(str);
str = removeNonWord(str);
str = trim(str) //should come after removeNonWord
.replace(/ +/g, delimeter) //replace spaces with delimeter
.toLowerCase();
return str;
} | function slugify(str, delimeter){
if (delimeter == null) {
delimeter = "-";
}
str = replaceAccents(str);
str = removeNonWord(str);
str = trim(str) //should come after removeNonWord
.replace(/ +/g, delimeter) //replace spaces with delimeter
.toLowerCase();
return str;
} |
JavaScript | function normalizeLineBreaks(str, lineEnd) {
lineEnd = lineEnd || '\n';
return str
.replace(/\r\n/g, lineEnd) // DOS
.replace(/\r/g, lineEnd) // Mac
.replace(/\n/g, lineEnd); // Unix
} | function normalizeLineBreaks(str, lineEnd) {
lineEnd = lineEnd || '\n';
return str
.replace(/\r\n/g, lineEnd) // DOS
.replace(/\r/g, lineEnd) // Mac
.replace(/\n/g, lineEnd); // Unix
} |
JavaScript | function replaceAccents(str){
// verifies if the String has accents and replace them
if (str.search(/[\xC0-\xFF]/g) > -1) {
str = str
.replace(/[\xC0-\xC5]/g, "A")
.replace(/[\xC6]/g, "AE")
.replace(/[\xC7]/g, "C")
.replace(/[\xC8-\xCB]/g, "E")
.replace(/[\xCC-\xCF]/g, "I")
.replace(/[\xD0]/g, "D")
.replace(/[\xD1]/g, "N")
.replace(/[\xD2-\xD6\xD8]/g, "O")
.replace(/[\xD9-\xDC]/g, "U")
.replace(/[\xDD]/g, "Y")
.replace(/[\xDE]/g, "P")
.replace(/[\xE0-\xE5]/g, "a")
.replace(/[\xE6]/g, "ae")
.replace(/[\xE7]/g, "c")
.replace(/[\xE8-\xEB]/g, "e")
.replace(/[\xEC-\xEF]/g, "i")
.replace(/[\xF1]/g, "n")
.replace(/[\xF2-\xF6\xF8]/g, "o")
.replace(/[\xF9-\xFC]/g, "u")
.replace(/[\xFE]/g, "p")
.replace(/[\xFD\xFF]/g, "y");
}
return str;
} | function replaceAccents(str){
// verifies if the String has accents and replace them
if (str.search(/[\xC0-\xFF]/g) > -1) {
str = str
.replace(/[\xC0-\xC5]/g, "A")
.replace(/[\xC6]/g, "AE")
.replace(/[\xC7]/g, "C")
.replace(/[\xC8-\xCB]/g, "E")
.replace(/[\xCC-\xCF]/g, "I")
.replace(/[\xD0]/g, "D")
.replace(/[\xD1]/g, "N")
.replace(/[\xD2-\xD6\xD8]/g, "O")
.replace(/[\xD9-\xDC]/g, "U")
.replace(/[\xDD]/g, "Y")
.replace(/[\xDE]/g, "P")
.replace(/[\xE0-\xE5]/g, "a")
.replace(/[\xE6]/g, "ae")
.replace(/[\xE7]/g, "c")
.replace(/[\xE8-\xEB]/g, "e")
.replace(/[\xEC-\xEF]/g, "i")
.replace(/[\xF1]/g, "n")
.replace(/[\xF2-\xF6\xF8]/g, "o")
.replace(/[\xF9-\xFC]/g, "u")
.replace(/[\xFE]/g, "p")
.replace(/[\xFD\xFF]/g, "y");
}
return str;
} |
JavaScript | function escapeHtml(str){
str = str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"');
return str;
} | function escapeHtml(str){
str = str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"');
return str;
} |
JavaScript | function removeNonASCII(str){
// Matches non-printable ASCII chars -
// http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters
return str.replace(/[^\x20-\x7E]/g, '');
} | function removeNonASCII(str){
// Matches non-printable ASCII chars -
// http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters
return str.replace(/[^\x20-\x7E]/g, '');
} |
JavaScript | function lpad(str, minLen, ch) {
ch = ch || ' ';
return ((str.length < minLen)
? repeat(ch, minLen - str.length) + str : str);
} | function lpad(str, minLen, ch) {
ch = ch || ' ';
return ((str.length < minLen)
? repeat(ch, minLen - str.length) + str : str);
} |
JavaScript | function ltrim(str, chars) {
chars = chars || WHITE_SPACES;
var start = 0,
len = str.length,
charLen = chars.length,
found = true,
i, c;
while (found && start < len) {
found = false;
i = -1;
c = str.charAt(start);
while (++i < charLen) {
if (c === chars[i]) {
found = true;
start++;
break;
}
}
}
return (start >= len) ? '' : str.substr(start, len);
} | function ltrim(str, chars) {
chars = chars || WHITE_SPACES;
var start = 0,
len = str.length,
charLen = chars.length,
found = true,
i, c;
while (found && start < len) {
found = false;
i = -1;
c = str.charAt(start);
while (++i < charLen) {
if (c === chars[i]) {
found = true;
start++;
break;
}
}
}
return (start >= len) ? '' : str.substr(start, len);
} |
JavaScript | function rtrim(str, chars) {
chars = chars || WHITE_SPACES;
var end = str.length - 1,
charLen = chars.length,
found = true,
i, c;
while (found && end >= 0) {
found = false;
i = -1;
c = str.charAt(end);
while (++i < charLen) {
if (c === chars[i]) {
found = true;
end--;
break;
}
}
}
return (end >= 0) ? str.substring(0, end + 1) : '';
} | function rtrim(str, chars) {
chars = chars || WHITE_SPACES;
var end = str.length - 1,
charLen = chars.length,
found = true,
i, c;
while (found && end >= 0) {
found = false;
i = -1;
c = str.charAt(end);
while (++i < charLen) {
if (c === chars[i]) {
found = true;
end--;
break;
}
}
}
return (end >= 0) ? str.substring(0, end + 1) : '';
} |
JavaScript | hasRead ({ state, commit }, { msg_id }) {
return new Promise((resolve, reject) => {
hasRead(msg_id).then(() => {
commit('moveMsg', {
from: 'messageUnreadList',
to: 'messageReadedList',
msg_id
})
commit('setMessageCount', state.unreadCount - 1)
resolve()
}).catch(error => {
reject(error)
})
})
} | hasRead ({ state, commit }, { msg_id }) {
return new Promise((resolve, reject) => {
hasRead(msg_id).then(() => {
commit('moveMsg', {
from: 'messageUnreadList',
to: 'messageReadedList',
msg_id
})
commit('setMessageCount', state.unreadCount - 1)
resolve()
}).catch(error => {
reject(error)
})
})
} |
JavaScript | removeReaded ({ commit }, { msg_id }) {
return new Promise((resolve, reject) => {
removeReaded(msg_id).then(() => {
commit('moveMsg', {
from: 'messageReadedList',
to: 'messageTrashList',
msg_id
})
resolve()
}).catch(error => {
reject(error)
})
})
} | removeReaded ({ commit }, { msg_id }) {
return new Promise((resolve, reject) => {
removeReaded(msg_id).then(() => {
commit('moveMsg', {
from: 'messageReadedList',
to: 'messageTrashList',
msg_id
})
resolve()
}).catch(error => {
reject(error)
})
})
} |
JavaScript | restoreTrash ({ commit }, { msg_id }) {
return new Promise((resolve, reject) => {
restoreTrash(msg_id).then(() => {
commit('moveMsg', {
from: 'messageTrashList',
to: 'messageReadedList',
msg_id
})
resolve()
}).catch(error => {
reject(error)
})
})
} | restoreTrash ({ commit }, { msg_id }) {
return new Promise((resolve, reject) => {
restoreTrash(msg_id).then(() => {
commit('moveMsg', {
from: 'messageTrashList',
to: 'messageReadedList',
msg_id
})
resolve()
}).catch(error => {
reject(error)
})
})
} |
JavaScript | function _couchdb_get_view(opts,cb){
var c = {}
_.assign(c,config.couchdb,opts)
var db = c.db
var view = opts.view || '_all_docs'
var key = opts.key
var keys = opts.keys
var startkey = opts.startkey
var endkey = opts.endkey
var reduce = opts.reduce
var group = opts.group
var group_level = opts.group_level
var include_docs = opts.include_docs
var limit = opts.limit
var descending = opts.descending
if(opts.couchdb !== undefined){
throw new Error('hey, you are using an old way of doing this')
}
var cdb = c.host || '127.0.0.1'
var cport = c.port || 5984
cdb = cdb+':'+cport
if(! /http/.test(cdb)){
cdb = 'http://'+cdb
}
var query = {}
if(startkey !== undefined) query.startkey = startkey
if(endkey !== undefined) query.endkey = endkey
if(key !== undefined) query.key = key
if(keys !== undefined) query.keys = keys
if(reduce !== undefined) query.reduce = reduce
if(group !== undefined) query.group = group
if(group_level !== undefined) query.group_level = group_level
if(include_docs !== undefined) query.include_docs=include_docs
if(limit !== undefined) query.limit=limit
if(descending !== undefined) query.descending=descending
var qstring = toQuery(query)
var uri = cdb +'/' + db + '/' + view + '?' + qstring
superagent
.get(uri)
.set('accept','application/json')
.set('followRedirect',true)
.end(function(err,res){
if(err) return cb(err)
return cb(null, res.body)
})
} | function _couchdb_get_view(opts,cb){
var c = {}
_.assign(c,config.couchdb,opts)
var db = c.db
var view = opts.view || '_all_docs'
var key = opts.key
var keys = opts.keys
var startkey = opts.startkey
var endkey = opts.endkey
var reduce = opts.reduce
var group = opts.group
var group_level = opts.group_level
var include_docs = opts.include_docs
var limit = opts.limit
var descending = opts.descending
if(opts.couchdb !== undefined){
throw new Error('hey, you are using an old way of doing this')
}
var cdb = c.host || '127.0.0.1'
var cport = c.port || 5984
cdb = cdb+':'+cport
if(! /http/.test(cdb)){
cdb = 'http://'+cdb
}
var query = {}
if(startkey !== undefined) query.startkey = startkey
if(endkey !== undefined) query.endkey = endkey
if(key !== undefined) query.key = key
if(keys !== undefined) query.keys = keys
if(reduce !== undefined) query.reduce = reduce
if(group !== undefined) query.group = group
if(group_level !== undefined) query.group_level = group_level
if(include_docs !== undefined) query.include_docs=include_docs
if(limit !== undefined) query.limit=limit
if(descending !== undefined) query.descending=descending
var qstring = toQuery(query)
var uri = cdb +'/' + db + '/' + view + '?' + qstring
superagent
.get(uri)
.set('accept','application/json')
.set('followRedirect',true)
.end(function(err,res){
if(err) return cb(err)
return cb(null, res.body)
})
} |
JavaScript | function TestHandler(testId,t) {
var self = this,
conf = t.conf,
taskList = t.taskList,
workers = [],
iterCount = 1,
completeWorkerCount = 0;
function runTest () {
workers = [];
completeWorkerCount = 0;
for (var i = conf.tpn - 1; i >= 0; i--) {
var worker = new Worker('testhandler.js');
worker.addEventListener('message', function (e) {
if(e.data.event == 'result'){
console.log('TestHandler: ' + JSON.stringify(e.data.result));
e.data.result.push(BrowserInfo.countryCode);
e.data.result.push(BrowserInfo.browser);
self.rc.send(JSON.stringify({
'event': 'test_result',
'tid': testId,
'result': e.data.result
}));
} else if(e.data.event == 'finish'){
completeWorkerCount++;
}
if(workers.length == completeWorkerCount && iterCount != conf.loopCount) {
iterCount++;
runTest();
} else if(workers.length == completeWorkerCount && iterCount == conf.loopCount) {
this.terminate();
}
}, false);
workers.push(worker);
};
for (var j = conf.tpn - 1; j >= 0; j--) {
setTimeout(function (index) {
workers[index].postMessage({'cmd': 'start', 'taskList': taskList, 'timer': conf.timer, 'timeOffset': ServerDate.getOffset()});
}, Math.random()*1000*conf.activatePeriod, j);
};
}
function designatedTimer (designatedTime) {
if (designatedTime.getTime() <= new Date().getTime()) {
console.log('TestHandler: Test start');
runTest();
return;
}
setTimeout(arguments.callee,1000,designatedTime);
}
this.testStart = function (rc) { // report channel
self.rc = rc;
designatedTimer(new Date(conf.startTime));
};
} | function TestHandler(testId,t) {
var self = this,
conf = t.conf,
taskList = t.taskList,
workers = [],
iterCount = 1,
completeWorkerCount = 0;
function runTest () {
workers = [];
completeWorkerCount = 0;
for (var i = conf.tpn - 1; i >= 0; i--) {
var worker = new Worker('testhandler.js');
worker.addEventListener('message', function (e) {
if(e.data.event == 'result'){
console.log('TestHandler: ' + JSON.stringify(e.data.result));
e.data.result.push(BrowserInfo.countryCode);
e.data.result.push(BrowserInfo.browser);
self.rc.send(JSON.stringify({
'event': 'test_result',
'tid': testId,
'result': e.data.result
}));
} else if(e.data.event == 'finish'){
completeWorkerCount++;
}
if(workers.length == completeWorkerCount && iterCount != conf.loopCount) {
iterCount++;
runTest();
} else if(workers.length == completeWorkerCount && iterCount == conf.loopCount) {
this.terminate();
}
}, false);
workers.push(worker);
};
for (var j = conf.tpn - 1; j >= 0; j--) {
setTimeout(function (index) {
workers[index].postMessage({'cmd': 'start', 'taskList': taskList, 'timer': conf.timer, 'timeOffset': ServerDate.getOffset()});
}, Math.random()*1000*conf.activatePeriod, j);
};
}
function designatedTimer (designatedTime) {
if (designatedTime.getTime() <= new Date().getTime()) {
console.log('TestHandler: Test start');
runTest();
return;
}
setTimeout(arguments.callee,1000,designatedTime);
}
this.testStart = function (rc) { // report channel
self.rc = rc;
designatedTimer(new Date(conf.startTime));
};
} |
JavaScript | function TestManager() {
var testList = {};
this.addTest = function (t) {
testList[t.getTest().info.tid] = t;
};
this.getTest = function (tid) {
return testList[tid];
};
} | function TestManager() {
var testList = {};
this.addTest = function (t) {
testList[t.getTest().info.tid] = t;
};
this.getTest = function (tid) {
return testList[tid];
};
} |
JavaScript | function Test(t,l) {
var bucket = [],
bucketCapacity = t.conf.nodeNum * t.conf.tpn * t.conf.loopCount * t.taskList.length,
test = t;
var latencyMin = 10000000,
latencyMax = 0,
latencySum = 0,
rtMin = 10000000,
rtMax = 0,
rtSum = 0,
ptMin = 10000000,
ptMax = 0,
ptSum = 0,
dataSizeSum = 0;
this.nodeList = l;
this.putResult = function (result) {
if(result[1] < latencyMin) latencyMin = result[1];
if(result[1] > latencyMax) latencyMax = result[1];
if(result[2] < rtMin) rtMin = result[2];
if(result[2] > rtMax) rtMax = result[2];
if(result[2]-result[1] < ptMin) ptMin = result[2]-result[1];
if(result[2]-result[1] > ptMax) ptMax = result[2]-result[1];
latencySum += result[1];
rtSum += result[2];
ptSum += (result[2]-result[1]);
dataSizeSum += result[4];
bucket.push(result);
return (bucketCapacity == bucket.length);
};
this.getResult = function () {
return bucket;
};
this.getAggregate = function () {
return [ bucketCapacity, latencyMin, latencyMax, latencySum/bucket.length, rtMin, rtMax, rtSum/bucket.length, ptMin, ptMax, ptSum/bucket.length, dataSizeSum ];
}
this.getTest = function () {
return test;
}
} | function Test(t,l) {
var bucket = [],
bucketCapacity = t.conf.nodeNum * t.conf.tpn * t.conf.loopCount * t.taskList.length,
test = t;
var latencyMin = 10000000,
latencyMax = 0,
latencySum = 0,
rtMin = 10000000,
rtMax = 0,
rtSum = 0,
ptMin = 10000000,
ptMax = 0,
ptSum = 0,
dataSizeSum = 0;
this.nodeList = l;
this.putResult = function (result) {
if(result[1] < latencyMin) latencyMin = result[1];
if(result[1] > latencyMax) latencyMax = result[1];
if(result[2] < rtMin) rtMin = result[2];
if(result[2] > rtMax) rtMax = result[2];
if(result[2]-result[1] < ptMin) ptMin = result[2]-result[1];
if(result[2]-result[1] > ptMax) ptMax = result[2]-result[1];
latencySum += result[1];
rtSum += result[2];
ptSum += (result[2]-result[1]);
dataSizeSum += result[4];
bucket.push(result);
return (bucketCapacity == bucket.length);
};
this.getResult = function () {
return bucket;
};
this.getAggregate = function () {
return [ bucketCapacity, latencyMin, latencyMax, latencySum/bucket.length, rtMin, rtMax, rtSum/bucket.length, ptMin, ptMax, ptSum/bucket.length, dataSizeSum ];
}
this.getTest = function () {
return test;
}
} |
JavaScript | function RTCManager() {
var rtcList = {};
this.addRTC = function (id,rtc) {
rtcList[id] = rtc;
};
this.updateRTC = function (id,npc,ndc) {
if(rtcList[id]){
if(npc) rtcList[id].pc = npc;
if(ndc) rtcList[id].dc = ndc;
}
}
this.removeRTC = function (id) {
rtcList[id] = null;
};
this.clearRTC = function () {
rtcList = {};
};
this.getPC = function (id) {
if(rtcList[id]) { return rtcList[id].pc; }
else { return null; }
};
this.getDC = function (id) {
if(rtcList[id]) { return rtcList[id].dc; }
else { return null; }
};
} | function RTCManager() {
var rtcList = {};
this.addRTC = function (id,rtc) {
rtcList[id] = rtc;
};
this.updateRTC = function (id,npc,ndc) {
if(rtcList[id]){
if(npc) rtcList[id].pc = npc;
if(ndc) rtcList[id].dc = ndc;
}
}
this.removeRTC = function (id) {
rtcList[id] = null;
};
this.clearRTC = function () {
rtcList = {};
};
this.getPC = function (id) {
if(rtcList[id]) { return rtcList[id].pc; }
else { return null; }
};
this.getDC = function (id) {
if(rtcList[id]) { return rtcList[id].dc; }
else { return null; }
};
} |
JavaScript | function createMultipleRTC() {
for (var i = currentTest.nodeList.length - 1; i >= 0; i--) {
rtcManager.addRTC(currentTest.nodeList[i],RTC('offerer','',currentTest.nodeList[i]));
}
} | function createMultipleRTC() {
for (var i = currentTest.nodeList.length - 1; i >= 0; i--) {
rtcManager.addRTC(currentTest.nodeList[i],RTC('offerer','',currentTest.nodeList[i]));
}
} |
JavaScript | function RTCForChrome(role, json, targetid) {
var iceServers = {
iceServers: [{
url: 'stun:stun.l.google.com:19302'
}]
},
optionalRtpDataChannels = {
optional: [{
RtpDataChannels: true
}]
},
mediaConstraints = {
optional: [],
mandatory: {
OfferToReceiveAudio: false,
OfferToReceiveVideo: false
}
},
rtcPeerConnection = new webkitRTCPeerConnection(iceServers, optionalRtpDataChannels),
rtcDataChannel = rtcPeerConnection.createDataChannel('RTCDataChannel', {});
if(role == 'answerer') {
offerSDP = new RTCSessionDescription(json.sdp);
rtcPeerConnection.setRemoteDescription(offerSDP);
rtcPeerConnection.createAnswer(function (sessionDescription) {
rtcPeerConnection.setLocalDescription(sessionDescription);
ws.send(JSON.stringify({
'event': 'send_answer',
'to': json.from,
'sdp': sessionDescription
}));
}, null, mediaConstraints);
} else {
rtcPeerConnection.createOffer(function (sessionDescription) {
rtcPeerConnection.setLocalDescription(sessionDescription);
ws.send(JSON.stringify({
'event': 'send_offer',
'to': targetid,
'sdp': sessionDescription
}));
}, null, mediaConstraints);
}
rtcPeerConnection.onicecandidate = function (event) {
if (!event || !event.candidate) { return; }
console.log('rtc: onicecandidate');
ws.send(JSON.stringify({
'event': 'send_ice_candidate',
'to': targetid,
'candidate': event.candidate
}));
this.onicecandidate = null;
};
rtcPeerConnection.ondatachannel = function (event) {
console.log('rtc: data channel is connecting...');
};
rtcDataChannel.onopen = function () {
console.log('rtc: data channel has opened');
if(role == 'offerer') { // only test manager can be offerer, not test client
this.send(JSON.stringify({
'event': 'test_assign',
'test': currentTest.getTest()
}));
}
};
rtcDataChannel.onclose = function () { // seems to be useless
console.log('rtc: data channel has closed');
this.send(selfId + ' has leaved the chat');
};
rtcDataChannel.onmessage = function (event) {
var json = JSON.parse(event.data);
console.log('rtc: receive message: '+json.event);
if(json.event == 'test_assign') {
testHandler = new TestHandler('',json.test);
testHandler.testStart(this);
} else if(json.event == 'test_result') {
if (currentTest.putResult(json.result)) {
atp.notifyUI('test_complete',currentTest.getTest());
}
} else if(json.event == 'node_leaving') {
rtcManager.removeRTC(json.nodeId);
currentTest.nodeList.splice(currentTest.nodeList.indexOf(json.nodeId),1);
}
};
return {
'pc': rtcPeerConnection,
'dc': rtcDataChannel
};
} | function RTCForChrome(role, json, targetid) {
var iceServers = {
iceServers: [{
url: 'stun:stun.l.google.com:19302'
}]
},
optionalRtpDataChannels = {
optional: [{
RtpDataChannels: true
}]
},
mediaConstraints = {
optional: [],
mandatory: {
OfferToReceiveAudio: false,
OfferToReceiveVideo: false
}
},
rtcPeerConnection = new webkitRTCPeerConnection(iceServers, optionalRtpDataChannels),
rtcDataChannel = rtcPeerConnection.createDataChannel('RTCDataChannel', {});
if(role == 'answerer') {
offerSDP = new RTCSessionDescription(json.sdp);
rtcPeerConnection.setRemoteDescription(offerSDP);
rtcPeerConnection.createAnswer(function (sessionDescription) {
rtcPeerConnection.setLocalDescription(sessionDescription);
ws.send(JSON.stringify({
'event': 'send_answer',
'to': json.from,
'sdp': sessionDescription
}));
}, null, mediaConstraints);
} else {
rtcPeerConnection.createOffer(function (sessionDescription) {
rtcPeerConnection.setLocalDescription(sessionDescription);
ws.send(JSON.stringify({
'event': 'send_offer',
'to': targetid,
'sdp': sessionDescription
}));
}, null, mediaConstraints);
}
rtcPeerConnection.onicecandidate = function (event) {
if (!event || !event.candidate) { return; }
console.log('rtc: onicecandidate');
ws.send(JSON.stringify({
'event': 'send_ice_candidate',
'to': targetid,
'candidate': event.candidate
}));
this.onicecandidate = null;
};
rtcPeerConnection.ondatachannel = function (event) {
console.log('rtc: data channel is connecting...');
};
rtcDataChannel.onopen = function () {
console.log('rtc: data channel has opened');
if(role == 'offerer') { // only test manager can be offerer, not test client
this.send(JSON.stringify({
'event': 'test_assign',
'test': currentTest.getTest()
}));
}
};
rtcDataChannel.onclose = function () { // seems to be useless
console.log('rtc: data channel has closed');
this.send(selfId + ' has leaved the chat');
};
rtcDataChannel.onmessage = function (event) {
var json = JSON.parse(event.data);
console.log('rtc: receive message: '+json.event);
if(json.event == 'test_assign') {
testHandler = new TestHandler('',json.test);
testHandler.testStart(this);
} else if(json.event == 'test_result') {
if (currentTest.putResult(json.result)) {
atp.notifyUI('test_complete',currentTest.getTest());
}
} else if(json.event == 'node_leaving') {
rtcManager.removeRTC(json.nodeId);
currentTest.nodeList.splice(currentTest.nodeList.indexOf(json.nodeId),1);
}
};
return {
'pc': rtcPeerConnection,
'dc': rtcDataChannel
};
} |
JavaScript | function RTCForFirefox(role, json, targetid) {
var iceServers = {
iceServers: [{
url: 'stun:23.21.150.121'
}]
},
mediaConstraints = {
optional: [],
mandatory: {
OfferToReceiveAudio: false,
OfferToReceiveVideo: false
}
},
rtcPeerConnection = new mozRTCPeerConnection(iceServers),
rtcDataChannel;
if(role == 'answerer') {
offerSDP = new mozRTCSessionDescription(json.sdp);
rtcPeerConnection.setRemoteDescription(offerSDP);
rtcPeerConnection.createAnswer(function (sessionDescription) {
rtcPeerConnection.setLocalDescription(sessionDescription);
ws.send(JSON.stringify({
'event': 'send_answer',
'to': json.from,
'sdp': sessionDescription
}));
}, useless, mediaConstraints);
} else {
rtcDataChannel = rtcPeerConnection.createDataChannel('RTCDataChannel', {});
//rtcDataChannel.binaryType = 'blob';
rtcPeerConnection.createOffer(function (sessionDescription) {
rtcPeerConnection.setLocalDescription(sessionDescription);
ws.send(JSON.stringify({
'event': 'send_offer',
'to': targetid,
'sdp': sessionDescription
}));
}, useless, mediaConstraints);
setupRTCDataChannel();
}
rtcPeerConnection.onicecandidate = function (event) {
console.log('rtc: onicecandidate');
};
rtcPeerConnection.ondatachannel = function (event) {
console.log('rtc: data channel is connecting...');
if(role == 'answerer'){
rtcDataChannel = event.channel;
//rtcDataChannel.binaryType = 'blob';
rtcManager.updateRTC(targetid,null,rtcDataChannel);
setupRTCDataChannel();
}
};
function setupRTCDataChannel(){
rtcDataChannel.onopen = function () {
console.log('rtc: data channel has opened');
if(role == 'offerer') { // only test manager can be offerer, not test client
this.send(JSON.stringify({
'event': 'test_assign',
'test': currentTest.getTest()
}));
}
};
rtcDataChannel.onclose = function () { // seems to be useless
console.log('rtc: data channel has closed');
this.send(selfId + ' has leaved the chat');
};
rtcDataChannel.onmessage = function (event) {
var json = JSON.parse(event.data);
console.log('rtc: receive message: '+json.event);
if(json.event == 'test_assign') {
testHandler = new TestHandler('',json.test);
testHandler.testStart(this);
} else if(json.event == 'test_result') {
if (currentTest.putResult(json.result)) {
atp.notifyUI('test_complete',currentTest.getTest());
}
} else if(json.event == 'node_leaving') {
rtcManager.removeRTC(json.nodeId);
currentTest.nodeList.splice(currentTest.nodeList.indexOf(json.nodeId),1);
}
};
}
function useless() {}
return {
'pc': rtcPeerConnection,
'dc': rtcDataChannel
};
} | function RTCForFirefox(role, json, targetid) {
var iceServers = {
iceServers: [{
url: 'stun:23.21.150.121'
}]
},
mediaConstraints = {
optional: [],
mandatory: {
OfferToReceiveAudio: false,
OfferToReceiveVideo: false
}
},
rtcPeerConnection = new mozRTCPeerConnection(iceServers),
rtcDataChannel;
if(role == 'answerer') {
offerSDP = new mozRTCSessionDescription(json.sdp);
rtcPeerConnection.setRemoteDescription(offerSDP);
rtcPeerConnection.createAnswer(function (sessionDescription) {
rtcPeerConnection.setLocalDescription(sessionDescription);
ws.send(JSON.stringify({
'event': 'send_answer',
'to': json.from,
'sdp': sessionDescription
}));
}, useless, mediaConstraints);
} else {
rtcDataChannel = rtcPeerConnection.createDataChannel('RTCDataChannel', {});
//rtcDataChannel.binaryType = 'blob';
rtcPeerConnection.createOffer(function (sessionDescription) {
rtcPeerConnection.setLocalDescription(sessionDescription);
ws.send(JSON.stringify({
'event': 'send_offer',
'to': targetid,
'sdp': sessionDescription
}));
}, useless, mediaConstraints);
setupRTCDataChannel();
}
rtcPeerConnection.onicecandidate = function (event) {
console.log('rtc: onicecandidate');
};
rtcPeerConnection.ondatachannel = function (event) {
console.log('rtc: data channel is connecting...');
if(role == 'answerer'){
rtcDataChannel = event.channel;
//rtcDataChannel.binaryType = 'blob';
rtcManager.updateRTC(targetid,null,rtcDataChannel);
setupRTCDataChannel();
}
};
function setupRTCDataChannel(){
rtcDataChannel.onopen = function () {
console.log('rtc: data channel has opened');
if(role == 'offerer') { // only test manager can be offerer, not test client
this.send(JSON.stringify({
'event': 'test_assign',
'test': currentTest.getTest()
}));
}
};
rtcDataChannel.onclose = function () { // seems to be useless
console.log('rtc: data channel has closed');
this.send(selfId + ' has leaved the chat');
};
rtcDataChannel.onmessage = function (event) {
var json = JSON.parse(event.data);
console.log('rtc: receive message: '+json.event);
if(json.event == 'test_assign') {
testHandler = new TestHandler('',json.test);
testHandler.testStart(this);
} else if(json.event == 'test_result') {
if (currentTest.putResult(json.result)) {
atp.notifyUI('test_complete',currentTest.getTest());
}
} else if(json.event == 'node_leaving') {
rtcManager.removeRTC(json.nodeId);
currentTest.nodeList.splice(currentTest.nodeList.indexOf(json.nodeId),1);
}
};
}
function useless() {}
return {
'pc': rtcPeerConnection,
'dc': rtcDataChannel
};
} |
JavaScript | function Logger() {
var stdin = process.stdin,
stdout = process.stdout,
showTime = true;
stdin.on('data', function (data) {
var input = data.toString().trim();
if (input) {
switch (input) {
case 'nodelist':
db.nodeInfo.find().toArray(function (err,docs) {
var string = '';
for (var i = docs.length - 1; i >= 0; i--) {
string += docs[i]['id'] + ' ' + docs[i]['browser'] + ' ' + docs[i]['countryCode'] + '\n';
};
logger.print('Tester Number: '+docs.length);
logger.print(string);
});
break;
case 'testlist':
db.testList.find().toArray(function (err,docs) {
logger.print(docs);
});
break;
case 'testresult':
db.testResult.find().toArray(function (err,docs) {
logger.print(docs);
});
break;
case 'showtime':
showTime = ~showTime;
break;
case 'check':
nodeManager.broadcast({
'event': 'check_connection'
});
break;
case 'exit':
nodeManager.broadcast({
'event': 'server_restart'
});
setTimeout(function(){
var d = new Date();
fs.appendFileSync('./log.txt', '['+d.toISOString().substring(0,10)+'-'+d.toTimeString().substring(0,8)+'] : Server Exit.\r\n===\r\n');
console.log('Server Exit');
process.exit(0);
}, 5000);
break;
default:
logger.print(input);
break;
}
}
});
this.log = function() {
if(typeof arguments['0'] == 'object') arguments['0'] = JSON.stringify(arguments['0']);
if(showTime){
var d = new Date();
arguments['0'] = '['+d.toISOString().substring(0,10)+'-'+d.toTimeString().substring(0,8)+'] : '+arguments['0'];
}
console.log.apply(null,arguments);
fs.appendFile('./log.txt', util.format.apply(this, arguments)+'\r\n', function (err) {
if (err) throw err;
});
};
this.print = function() {
if(typeof arguments['0'] == 'object') arguments['0'] = JSON.stringify(arguments['0']);
console.log.apply(null,arguments);
};
stdin.resume();
} | function Logger() {
var stdin = process.stdin,
stdout = process.stdout,
showTime = true;
stdin.on('data', function (data) {
var input = data.toString().trim();
if (input) {
switch (input) {
case 'nodelist':
db.nodeInfo.find().toArray(function (err,docs) {
var string = '';
for (var i = docs.length - 1; i >= 0; i--) {
string += docs[i]['id'] + ' ' + docs[i]['browser'] + ' ' + docs[i]['countryCode'] + '\n';
};
logger.print('Tester Number: '+docs.length);
logger.print(string);
});
break;
case 'testlist':
db.testList.find().toArray(function (err,docs) {
logger.print(docs);
});
break;
case 'testresult':
db.testResult.find().toArray(function (err,docs) {
logger.print(docs);
});
break;
case 'showtime':
showTime = ~showTime;
break;
case 'check':
nodeManager.broadcast({
'event': 'check_connection'
});
break;
case 'exit':
nodeManager.broadcast({
'event': 'server_restart'
});
setTimeout(function(){
var d = new Date();
fs.appendFileSync('./log.txt', '['+d.toISOString().substring(0,10)+'-'+d.toTimeString().substring(0,8)+'] : Server Exit.\r\n===\r\n');
console.log('Server Exit');
process.exit(0);
}, 5000);
break;
default:
logger.print(input);
break;
}
}
});
this.log = function() {
if(typeof arguments['0'] == 'object') arguments['0'] = JSON.stringify(arguments['0']);
if(showTime){
var d = new Date();
arguments['0'] = '['+d.toISOString().substring(0,10)+'-'+d.toTimeString().substring(0,8)+'] : '+arguments['0'];
}
console.log.apply(null,arguments);
fs.appendFile('./log.txt', util.format.apply(this, arguments)+'\r\n', function (err) {
if (err) throw err;
});
};
this.print = function() {
if(typeof arguments['0'] == 'object') arguments['0'] = JSON.stringify(arguments['0']);
console.log.apply(null,arguments);
};
stdin.resume();
} |
JavaScript | function EventHandler(s) {
var events = {},
server = s;
this.on = function (eventName, callback) {
events[eventName] = callback;
};
this.fire = function (eventName, _) {
var evt = events[eventName],
args = Array.prototype.slice.call(arguments, 1);
if (!evt) { return; }
evt.apply(server, args);
};
} | function EventHandler(s) {
var events = {},
server = s;
this.on = function (eventName, callback) {
events[eventName] = callback;
};
this.fire = function (eventName, _) {
var evt = events[eventName],
args = Array.prototype.slice.call(arguments, 1);
if (!evt) { return; }
evt.apply(server, args);
};
} |
JavaScript | function NodeManager() {
var self = this,
socketList = {},
nodeList = {},
idList = [],
idcounter = 0;
this.init = function (count) {
idcounter = count;
};
this.getNewId = function () {
var id = idcounter;
idcounter++;
return id;
};
this.createNode = function (socket, id) {
idList.push(id);
socketList[id] = socket;
};
this.addNodeInfo = function (id,info) {
nodeList[id] = info;
db.nodeInfo.insert(info, function (err, inserted) {
if (err) { logger.log('Mongodb: Error while collection.insert: ',err,inserted); }
});
};
this.deleteNode = function (id) {
idList.splice(idList.indexOf(id),1);
delete socketList[id];
nodeList[id] = null; //delete nodeList[id];
db.nodeInfo.remove({'id': id}, {'single': 1}, function (err, numberOfRemovedDocs) {
if (err) { logger.log('Mongodb: Error while collection.remove: ',err); }
});
};
this.getIdList = function (selfId,test,directFunc,mixFunc) {
var criteria = (test.conf.criteria)? test.conf.criteria:{},
list = [];
criteria.id = {'$ne':selfId};
//criteria.bandwidth = {'$gt':5};
criteria.browser = {'$ne': 'Firefox'};
db.nodeInfo.find(criteria, {'_id': 0,'id': 1}, {'limit': test.conf.nodeNum}).toArray(function (err,docs) {
if (err) {
logger.log('Mongodb: Error while collection.find: ',err);
return;
}
if(docs.length == test.conf.nodeNum) {
for (var i = docs.length - 1; i >= 0; i--) {
list.push(docs[i]['id']);
}
directFunc(list,test,'direct');
} else if(test.conf.allowMixMode == 'true') {
var remainder = test.conf.nodeNum-docs.length;
for (var i = docs.length - 1; i >= 0; i--) {
list.push(docs[i]['id']);
}
db.nodeInfo.find({'id': {'$nin': list, '$ne':selfId}}, {'_id': 0,'id': 1}, {'limit': remainder}).toArray(function (err,docs) {
if (err) {
logger.log('Mongodb: Error while collection.find: ',err);
return;
}
if(docs.length == remainder) {
var list2 = [];
for (var i = docs.length - 1; i >= 0; i--) {
list2.push(socketList[docs[i]['id']]);
}
mixFunc(list,list2,test);
} else {
errorManager.send(selfId,errorManager.INSUFFICIENT_TEST_NODE);
}
});
} else {
errorManager.send(selfId,errorManager.INSUFFICIENT_TEST_NODE);
}
});
};
this.getSocket = function (id) {
return socketList[id];
};
this.getSocketList = function (selfId,test,indirectFunc) {
var criteria = (test.conf.criteria)? test.conf.criteria:{};
criteria.id = {'$ne':selfId};
//criteria.bandwidth = {'$gt':5};
db.nodeInfo.find(criteria, {'_id': 0,'id': 1}, {'limit': test.conf.nodeNum}).toArray(function (err,docs) {
if (err) {
logger.log('Mongodb: Error while collection.find: ',err);
return;
}
if(docs.length == test.conf.nodeNum) {
var list = [];
for (var i = docs.length - 1; i >= 0; i--) {
list.push(socketList[docs[i]['id']]);
}
indirectFunc(list,test);
} else {
errorManager.send(selfId,errorManager.INSUFFICIENT_TEST_NODE);
}
});
};
this.broadcast = function (msg) {
for (var i = idList.length - 1; i >= 0; i--) {
socketList[idList[i]].send(JSON.stringify(msg));
};
};
} | function NodeManager() {
var self = this,
socketList = {},
nodeList = {},
idList = [],
idcounter = 0;
this.init = function (count) {
idcounter = count;
};
this.getNewId = function () {
var id = idcounter;
idcounter++;
return id;
};
this.createNode = function (socket, id) {
idList.push(id);
socketList[id] = socket;
};
this.addNodeInfo = function (id,info) {
nodeList[id] = info;
db.nodeInfo.insert(info, function (err, inserted) {
if (err) { logger.log('Mongodb: Error while collection.insert: ',err,inserted); }
});
};
this.deleteNode = function (id) {
idList.splice(idList.indexOf(id),1);
delete socketList[id];
nodeList[id] = null; //delete nodeList[id];
db.nodeInfo.remove({'id': id}, {'single': 1}, function (err, numberOfRemovedDocs) {
if (err) { logger.log('Mongodb: Error while collection.remove: ',err); }
});
};
this.getIdList = function (selfId,test,directFunc,mixFunc) {
var criteria = (test.conf.criteria)? test.conf.criteria:{},
list = [];
criteria.id = {'$ne':selfId};
//criteria.bandwidth = {'$gt':5};
criteria.browser = {'$ne': 'Firefox'};
db.nodeInfo.find(criteria, {'_id': 0,'id': 1}, {'limit': test.conf.nodeNum}).toArray(function (err,docs) {
if (err) {
logger.log('Mongodb: Error while collection.find: ',err);
return;
}
if(docs.length == test.conf.nodeNum) {
for (var i = docs.length - 1; i >= 0; i--) {
list.push(docs[i]['id']);
}
directFunc(list,test,'direct');
} else if(test.conf.allowMixMode == 'true') {
var remainder = test.conf.nodeNum-docs.length;
for (var i = docs.length - 1; i >= 0; i--) {
list.push(docs[i]['id']);
}
db.nodeInfo.find({'id': {'$nin': list, '$ne':selfId}}, {'_id': 0,'id': 1}, {'limit': remainder}).toArray(function (err,docs) {
if (err) {
logger.log('Mongodb: Error while collection.find: ',err);
return;
}
if(docs.length == remainder) {
var list2 = [];
for (var i = docs.length - 1; i >= 0; i--) {
list2.push(socketList[docs[i]['id']]);
}
mixFunc(list,list2,test);
} else {
errorManager.send(selfId,errorManager.INSUFFICIENT_TEST_NODE);
}
});
} else {
errorManager.send(selfId,errorManager.INSUFFICIENT_TEST_NODE);
}
});
};
this.getSocket = function (id) {
return socketList[id];
};
this.getSocketList = function (selfId,test,indirectFunc) {
var criteria = (test.conf.criteria)? test.conf.criteria:{};
criteria.id = {'$ne':selfId};
//criteria.bandwidth = {'$gt':5};
db.nodeInfo.find(criteria, {'_id': 0,'id': 1}, {'limit': test.conf.nodeNum}).toArray(function (err,docs) {
if (err) {
logger.log('Mongodb: Error while collection.find: ',err);
return;
}
if(docs.length == test.conf.nodeNum) {
var list = [];
for (var i = docs.length - 1; i >= 0; i--) {
list.push(socketList[docs[i]['id']]);
}
indirectFunc(list,test);
} else {
errorManager.send(selfId,errorManager.INSUFFICIENT_TEST_NODE);
}
});
};
this.broadcast = function (msg) {
for (var i = idList.length - 1; i >= 0; i--) {
socketList[idList[i]].send(JSON.stringify(msg));
};
};
} |
JavaScript | function TestManager() {
var testList = {},
testId = 0;
var generateTestId = function () {
var ret = testId;
testId++;
return ret;
};
this.init = function (count) {
testId = count;
};
this.addTest = function (t) {
var tid = generateTestId(),
test = t.getTest();
test.info = {
'tid': tid
};
testList[tid] = t;
test.conf.criteria = JSON.stringify(test.conf.criteria);
db.testList.insert(test, function (err, inserted) {
if (err) { logger.log('Mongodb: Error while collection.insert(addTest): ',err,inserted); }
});
};
this.getTest = function (id) {
return testList[id];
};
} | function TestManager() {
var testList = {},
testId = 0;
var generateTestId = function () {
var ret = testId;
testId++;
return ret;
};
this.init = function (count) {
testId = count;
};
this.addTest = function (t) {
var tid = generateTestId(),
test = t.getTest();
test.info = {
'tid': tid
};
testList[tid] = t;
test.conf.criteria = JSON.stringify(test.conf.criteria);
db.testList.insert(test, function (err, inserted) {
if (err) { logger.log('Mongodb: Error while collection.insert(addTest): ',err,inserted); }
});
};
this.getTest = function (id) {
return testList[id];
};
} |
JavaScript | function ErrorManager () {
this.INSUFFICIENT_TEST_NODE = {v: 0, n:'Insufficient test node'};
this.send = function (id,error) {
nodeManager.getSocket(id).send(JSON.stringify({
'event': 'test_request_ack',
'status': 'error',
'errorCode': error
}));
};
} | function ErrorManager () {
this.INSUFFICIENT_TEST_NODE = {v: 0, n:'Insufficient test node'};
this.send = function (id,error) {
nodeManager.getSocket(id).send(JSON.stringify({
'event': 'test_request_ack',
'status': 'error',
'errorCode': error
}));
};
} |
JavaScript | function RTCForChrome(role, json, targetid) {
var iceServers = {
iceServers: [{
url: 'stun:stun.l.google.com:19302'
}]
},
optionalRtpDataChannels = {
optional: [{
RtpDataChannels: true
}]
},
mediaConstraints = {
optional: [],
mandatory: {
OfferToReceiveAudio: false,
OfferToReceiveVideo: false
}
},
rtcPeerConnection = new webkitRTCPeerConnection(iceServers, optionalRtpDataChannels),
rtcDataChannel = rtcPeerConnection.createDataChannel('RTCDataChannel', {});
if(role == 'answerer') {
offerSDP = new RTCSessionDescription(json.sdp);
rtcPeerConnection.setRemoteDescription(offerSDP);
rtcPeerConnection.createAnswer(function (sessionDescription) {
rtcPeerConnection.setLocalDescription(sessionDescription);
ws.send(JSON.stringify({
'event': 'send_answer',
'to': json.from,
'sdp': sessionDescription
}));
}, null, mediaConstraints);
} else {
rtcPeerConnection.createOffer(function (sessionDescription) {
rtcPeerConnection.setLocalDescription(sessionDescription);
ws.send(JSON.stringify({
'event': 'send_offer',
'to': targetid,
'sdp': sessionDescription
}));
}, null, mediaConstraints);
}
rtcPeerConnection.onicecandidate = function (event) {
if (!event || !event.candidate) { return; }
console.log('rtc: onicecandidate');
ws.send(JSON.stringify({
'event': 'send_ice_candidate',
'to': targetid,
'candidate': event.candidate
}));
this.onicecandidate = null;
};
rtcPeerConnection.ondatachannel = function (event) {
console.log('rtc: data channel is connecting...');
};
rtcDataChannel.onopen = function () {
console.log('rtc: data channel has opened');
};
rtcDataChannel.onclose = function () { // seems to be useless
console.log('rtc: data channel has closed');
this.send(selfId + ' has leaved the chat');
};
rtcDataChannel.onmessage = function (event) {
var json = JSON.parse(event.data);
console.log('rtc: receive message: '+json.event);
if(json.event == 'test_assign') {
testHandler = new TestHandler('',json.test);
testHandler.testStart(this);
}
};
return {
'pc': rtcPeerConnection,
'dc': rtcDataChannel
};
} | function RTCForChrome(role, json, targetid) {
var iceServers = {
iceServers: [{
url: 'stun:stun.l.google.com:19302'
}]
},
optionalRtpDataChannels = {
optional: [{
RtpDataChannels: true
}]
},
mediaConstraints = {
optional: [],
mandatory: {
OfferToReceiveAudio: false,
OfferToReceiveVideo: false
}
},
rtcPeerConnection = new webkitRTCPeerConnection(iceServers, optionalRtpDataChannels),
rtcDataChannel = rtcPeerConnection.createDataChannel('RTCDataChannel', {});
if(role == 'answerer') {
offerSDP = new RTCSessionDescription(json.sdp);
rtcPeerConnection.setRemoteDescription(offerSDP);
rtcPeerConnection.createAnswer(function (sessionDescription) {
rtcPeerConnection.setLocalDescription(sessionDescription);
ws.send(JSON.stringify({
'event': 'send_answer',
'to': json.from,
'sdp': sessionDescription
}));
}, null, mediaConstraints);
} else {
rtcPeerConnection.createOffer(function (sessionDescription) {
rtcPeerConnection.setLocalDescription(sessionDescription);
ws.send(JSON.stringify({
'event': 'send_offer',
'to': targetid,
'sdp': sessionDescription
}));
}, null, mediaConstraints);
}
rtcPeerConnection.onicecandidate = function (event) {
if (!event || !event.candidate) { return; }
console.log('rtc: onicecandidate');
ws.send(JSON.stringify({
'event': 'send_ice_candidate',
'to': targetid,
'candidate': event.candidate
}));
this.onicecandidate = null;
};
rtcPeerConnection.ondatachannel = function (event) {
console.log('rtc: data channel is connecting...');
};
rtcDataChannel.onopen = function () {
console.log('rtc: data channel has opened');
};
rtcDataChannel.onclose = function () { // seems to be useless
console.log('rtc: data channel has closed');
this.send(selfId + ' has leaved the chat');
};
rtcDataChannel.onmessage = function (event) {
var json = JSON.parse(event.data);
console.log('rtc: receive message: '+json.event);
if(json.event == 'test_assign') {
testHandler = new TestHandler('',json.test);
testHandler.testStart(this);
}
};
return {
'pc': rtcPeerConnection,
'dc': rtcDataChannel
};
} |
JavaScript | function RTCForFirefox(role, json, targetid) {
var iceServers = {
iceServers: [{
url: 'stun:23.21.150.121'
}]
},
mediaConstraints = {
optional: [],
mandatory: {
OfferToReceiveAudio: false,
OfferToReceiveVideo: false
}
},
rtcPeerConnection = new mozRTCPeerConnection(iceServers),
rtcDataChannel;
if(role == 'answerer') {
offerSDP = new mozRTCSessionDescription(json.sdp);
rtcPeerConnection.setRemoteDescription(offerSDP);
rtcPeerConnection.createAnswer(function (sessionDescription) {
rtcPeerConnection.setLocalDescription(sessionDescription);
ws.send(JSON.stringify({
'event': 'send_answer',
'to': json.from,
'sdp': sessionDescription
}));
}, useless, mediaConstraints);
} else {
rtcDataChannel = rtcPeerConnection.createDataChannel('RTCDataChannel', {});
rtcPeerConnection.createOffer(function (sessionDescription) {
rtcPeerConnection.setLocalDescription(sessionDescription);
ws.send(JSON.stringify({
'event': 'send_offer',
'to': targetid,
'sdp': sessionDescription
}));
}, useless, mediaConstraints);
setupRTCDataChannel();
}
rtcPeerConnection.onicecandidate = function (event) {
console.log('rtc: onicecandidate');
};
rtcPeerConnection.ondatachannel = function (event) {
console.log('rtc: data channel is connecting...');
if(role == 'answerer'){
rtcDataChannel = event.channel;
//rtcDataChannel.binaryType = 'blob';
rtcManager.updateRTC(targetid,null,rtcDataChannel);
setupRTCDataChannel();
}
};
function setupRTCDataChannel(){
rtcDataChannel.onopen = function () {
console.log('rtc: data channel has opened');
};
rtcDataChannel.onclose = function () { // seems to be useless
console.log('rtc: data channel has closed');
this.send(selfId + ' has leaved the chat');
};
rtcDataChannel.onmessage = function (event) {
var json = JSON.parse(event.data);
console.log('rtc: receive message: '+json.event);
if(json.event == 'test_assign') {
testHandler = new TestHandler('',json.test);
testHandler.testStart(this);
}
};
}
function useless() {}
return {
'pc': rtcPeerConnection,
'dc': rtcDataChannel
};
} | function RTCForFirefox(role, json, targetid) {
var iceServers = {
iceServers: [{
url: 'stun:23.21.150.121'
}]
},
mediaConstraints = {
optional: [],
mandatory: {
OfferToReceiveAudio: false,
OfferToReceiveVideo: false
}
},
rtcPeerConnection = new mozRTCPeerConnection(iceServers),
rtcDataChannel;
if(role == 'answerer') {
offerSDP = new mozRTCSessionDescription(json.sdp);
rtcPeerConnection.setRemoteDescription(offerSDP);
rtcPeerConnection.createAnswer(function (sessionDescription) {
rtcPeerConnection.setLocalDescription(sessionDescription);
ws.send(JSON.stringify({
'event': 'send_answer',
'to': json.from,
'sdp': sessionDescription
}));
}, useless, mediaConstraints);
} else {
rtcDataChannel = rtcPeerConnection.createDataChannel('RTCDataChannel', {});
rtcPeerConnection.createOffer(function (sessionDescription) {
rtcPeerConnection.setLocalDescription(sessionDescription);
ws.send(JSON.stringify({
'event': 'send_offer',
'to': targetid,
'sdp': sessionDescription
}));
}, useless, mediaConstraints);
setupRTCDataChannel();
}
rtcPeerConnection.onicecandidate = function (event) {
console.log('rtc: onicecandidate');
};
rtcPeerConnection.ondatachannel = function (event) {
console.log('rtc: data channel is connecting...');
if(role == 'answerer'){
rtcDataChannel = event.channel;
//rtcDataChannel.binaryType = 'blob';
rtcManager.updateRTC(targetid,null,rtcDataChannel);
setupRTCDataChannel();
}
};
function setupRTCDataChannel(){
rtcDataChannel.onopen = function () {
console.log('rtc: data channel has opened');
};
rtcDataChannel.onclose = function () { // seems to be useless
console.log('rtc: data channel has closed');
this.send(selfId + ' has leaved the chat');
};
rtcDataChannel.onmessage = function (event) {
var json = JSON.parse(event.data);
console.log('rtc: receive message: '+json.event);
if(json.event == 'test_assign') {
testHandler = new TestHandler('',json.test);
testHandler.testStart(this);
}
};
}
function useless() {}
return {
'pc': rtcPeerConnection,
'dc': rtcDataChannel
};
} |
JavaScript | createAccount () {
TransactionDispatcher.dispatch({
type: TransactionConstants.CREATED_ACCOUNT,
amount: 0
});
} | createAccount () {
TransactionDispatcher.dispatch({
type: TransactionConstants.CREATED_ACCOUNT,
amount: 0
});
} |
JavaScript | depositIntoAccount (amount) {
TransactionDispatcher.dispatch({
type: TransactionConstants.DEPOSITED_INTO_ACCOUNT,
amount: amount
});
} | depositIntoAccount (amount) {
TransactionDispatcher.dispatch({
type: TransactionConstants.DEPOSITED_INTO_ACCOUNT,
amount: amount
});
} |
JavaScript | withdrawFromAccount (amount) {
TransactionDispatcher.dispatch({
type: TransactionConstants.WITHDREW_FROM_ACCOUNT,
amount: amount
});
} | withdrawFromAccount (amount) {
TransactionDispatcher.dispatch({
type: TransactionConstants.WITHDREW_FROM_ACCOUNT,
amount: amount
});
} |
JavaScript | _handleChange (evt) {
if (evt.key === 'Enter') {
// Create a new item and set the current time as it's id
const newItem = {
id: Date.now(),
name: evt.target.value
};
// Create a new array with the previous items plus the value the user typed
const newItems = this.state.items.concat(newItem);
// Clear the text field
evt.target.value = '';
// Set the new state
this.setState({items: newItems});
}
} | _handleChange (evt) {
if (evt.key === 'Enter') {
// Create a new item and set the current time as it's id
const newItem = {
id: Date.now(),
name: evt.target.value
};
// Create a new array with the previous items plus the value the user typed
const newItems = this.state.items.concat(newItem);
// Clear the text field
evt.target.value = '';
// Set the new state
this.setState({items: newItems});
}
} |
JavaScript | _handleRemove (evt) {
const pos = evt.target.getAttribute('data-pos');
// Create a new array without the clicked item
const newItems = this.state.items;
newItems.splice(pos, 1);
// Set the new state
this.setState({items: newItems});
} | _handleRemove (evt) {
const pos = evt.target.getAttribute('data-pos');
// Create a new array without the clicked item
const newItems = this.state.items;
newItems.splice(pos, 1);
// Set the new state
this.setState({items: newItems});
} |
JavaScript | function TinyMCE_preview_getControlHTML(control_name) {
switch (control_name) {
case "preview":
return '<img id="{$editor_id}_preview" src="{$pluginurl}/images/preview.gif" title="{$lang_preview_desc}" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');" onclick="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mcePreview\');" />';
}
return "";
} | function TinyMCE_preview_getControlHTML(control_name) {
switch (control_name) {
case "preview":
return '<img id="{$editor_id}_preview" src="{$pluginurl}/images/preview.gif" title="{$lang_preview_desc}" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');" onclick="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mcePreview\');" />';
}
return "";
} |
JavaScript | function TinyMCE_save_getControlHTML(control_name) {
switch (control_name) {
case "save":
return '<img id="{$editor_id}_save" src="{$pluginurl}/images/save.gif" title="{$lang_save_desc}" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.switchClass(this,\'mceButtonNormal\');" onmousedown="tinyMCE.switchClass(this,\'mceButtonDown\');" onclick="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mceSave\');" />';
}
return "";
} | function TinyMCE_save_getControlHTML(control_name) {
switch (control_name) {
case "save":
return '<img id="{$editor_id}_save" src="{$pluginurl}/images/save.gif" title="{$lang_save_desc}" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.switchClass(this,\'mceButtonNormal\');" onmousedown="tinyMCE.switchClass(this,\'mceButtonDown\');" onclick="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mceSave\');" />';
}
return "";
} |
JavaScript | function TinyMCE_searchreplace_execCommand(editor_id, element, command, user_interface, value) {
function defValue(key, default_value) {
value[key] = typeof(value[key]) == "undefined" ? default_value : value[key];
}
function replaceSel(search_str, str) {
// Get current selection
if (!tinyMCE.isMSIE) {
var sel = instance.contentWindow.getSelection();
var rng = sel.getRangeAt(0);
} else {
var rng = instance.contentWindow.document.selection.createRange();
}
// Replace current one
if (!tinyMCE.isMSIE) {
var doc = instance.contentWindow.document;
// This way works when the replace doesn't contain the search string
if (str.indexOf(search_str) == -1) {
rng.deleteContents();
rng.insertNode(rng.createContextualFragment(str));
rng.collapse(false);
} else {
// Insert content ugly way! Needed to move selection to after replace item
doc.execCommand("insertimage", false, "#mce_temp_url#");
var elm = tinyMCE.getElementByAttributeValue(doc.body, "img", "src", "#mce_temp_url#");
elm.parentNode.replaceChild(doc.createTextNode(str), elm);
}
} else {
if (rng.item)
rng.item(0).outerHTML = str;
else
rng.pasteHTML(str);
}
}
var instance = tinyMCE.getInstanceById(editor_id);
if (!value)
value = new Array();
// Setup defualt values
defValue("editor_id", editor_id);
defValue("searchstring", "");
defValue("replacestring", null);
defValue("replacemode", "none");
defValue("casesensitive", false);
defValue("backwards", false);
defValue("wrap", false);
defValue("wholeword", false);
// Handle commands
switch (command) {
case "mceResetSearch":
tinyMCE.lastSearchRng = null;
return true;
case "mceSearch":
if (user_interface) {
// Open search dialog
var template = new Array();
if (value['replacestring'] != null) {
template['file'] = '../../plugins/searchreplace/replace.htm'; // Relative to theme
template['width'] = 310;
template['height'] = 180;
} else {
template['file'] = '../../plugins/searchreplace/search.htm'; // Relative to theme
template['width'] = 280;
template['height'] = 180;
}
tinyMCE.openWindow(template, value);
} else {
var win = tinyMCE.getInstanceById(editor_id).contentWindow;
var doc = tinyMCE.getInstanceById(editor_id).contentWindow.document;
var body = tinyMCE.getInstanceById(editor_id).contentWindow.document.body;
// Whats the point
if (body.innerHTML == "") {
alert(tinyMCE.getLang('lang_searchreplace_notfound'));
return true;
}
// Handle replace current
if (value['replacemode'] == "current") {
replaceSel(value['string'], value['replacestring']);
// Search next one
value['replacemode'] = "none";
tinyMCE.execInstanceCommand(editor_id, 'mceSearch', user_interface, value, false);
return true;
}
if (tinyMCE.isMSIE) {
var rng = tinyMCE.lastSearchRng ? tinyMCE.lastSearchRng : doc.selection.createRange();
var flags = 0;
if (value['wholeword'])
flags = flags | 2;
if (value['casesensitive'])
flags = flags | 4;
// Handle replace all mode
if (value['replacemode'] == "all") {
while (rng.findText(value['string'], value['backwards'] ? -1 : 1, flags)) {
rng.scrollIntoView();
rng.select();
rng.collapse(false);
replaceSel(value['string'], value['replacestring']);
}
alert(tinyMCE.getLang('lang_searchreplace_allreplaced'));
return true;
}
if (rng.findText(value['string'], value['backwards'] ? -1 : 1, flags)) {
rng.scrollIntoView();
rng.select();
rng.collapse(value['backwards']);
tinyMCE.lastSearchRng = rng;
} else
alert(tinyMCE.getLang('lang_searchreplace_notfound'));
} else {
if (value['replacemode'] == "all") {
while (win.find(value['string'], value['casesensitive'], value['backwards'], value['wrap'], value['wholeword'], false, false))
replaceSel(value['string'], value['replacestring']);
alert(tinyMCE.getLang('lang_searchreplace_allreplaced'));
return true;
}
if (!win.find(value['string'], value['casesensitive'], value['backwards'], value['wrap'], value['wholeword'], false, false))
alert(tinyMCE.getLang('lang_searchreplace_notfound'));
}
}
return true;
case "mceSearchReplace":
value['replacestring'] = "";
tinyMCE.execInstanceCommand(editor_id, 'mceSearch', user_interface, value, false);
return true;
}
// Pass to next handler in chain
return false;
} | function TinyMCE_searchreplace_execCommand(editor_id, element, command, user_interface, value) {
function defValue(key, default_value) {
value[key] = typeof(value[key]) == "undefined" ? default_value : value[key];
}
function replaceSel(search_str, str) {
// Get current selection
if (!tinyMCE.isMSIE) {
var sel = instance.contentWindow.getSelection();
var rng = sel.getRangeAt(0);
} else {
var rng = instance.contentWindow.document.selection.createRange();
}
// Replace current one
if (!tinyMCE.isMSIE) {
var doc = instance.contentWindow.document;
// This way works when the replace doesn't contain the search string
if (str.indexOf(search_str) == -1) {
rng.deleteContents();
rng.insertNode(rng.createContextualFragment(str));
rng.collapse(false);
} else {
// Insert content ugly way! Needed to move selection to after replace item
doc.execCommand("insertimage", false, "#mce_temp_url#");
var elm = tinyMCE.getElementByAttributeValue(doc.body, "img", "src", "#mce_temp_url#");
elm.parentNode.replaceChild(doc.createTextNode(str), elm);
}
} else {
if (rng.item)
rng.item(0).outerHTML = str;
else
rng.pasteHTML(str);
}
}
var instance = tinyMCE.getInstanceById(editor_id);
if (!value)
value = new Array();
// Setup defualt values
defValue("editor_id", editor_id);
defValue("searchstring", "");
defValue("replacestring", null);
defValue("replacemode", "none");
defValue("casesensitive", false);
defValue("backwards", false);
defValue("wrap", false);
defValue("wholeword", false);
// Handle commands
switch (command) {
case "mceResetSearch":
tinyMCE.lastSearchRng = null;
return true;
case "mceSearch":
if (user_interface) {
// Open search dialog
var template = new Array();
if (value['replacestring'] != null) {
template['file'] = '../../plugins/searchreplace/replace.htm'; // Relative to theme
template['width'] = 310;
template['height'] = 180;
} else {
template['file'] = '../../plugins/searchreplace/search.htm'; // Relative to theme
template['width'] = 280;
template['height'] = 180;
}
tinyMCE.openWindow(template, value);
} else {
var win = tinyMCE.getInstanceById(editor_id).contentWindow;
var doc = tinyMCE.getInstanceById(editor_id).contentWindow.document;
var body = tinyMCE.getInstanceById(editor_id).contentWindow.document.body;
// Whats the point
if (body.innerHTML == "") {
alert(tinyMCE.getLang('lang_searchreplace_notfound'));
return true;
}
// Handle replace current
if (value['replacemode'] == "current") {
replaceSel(value['string'], value['replacestring']);
// Search next one
value['replacemode'] = "none";
tinyMCE.execInstanceCommand(editor_id, 'mceSearch', user_interface, value, false);
return true;
}
if (tinyMCE.isMSIE) {
var rng = tinyMCE.lastSearchRng ? tinyMCE.lastSearchRng : doc.selection.createRange();
var flags = 0;
if (value['wholeword'])
flags = flags | 2;
if (value['casesensitive'])
flags = flags | 4;
// Handle replace all mode
if (value['replacemode'] == "all") {
while (rng.findText(value['string'], value['backwards'] ? -1 : 1, flags)) {
rng.scrollIntoView();
rng.select();
rng.collapse(false);
replaceSel(value['string'], value['replacestring']);
}
alert(tinyMCE.getLang('lang_searchreplace_allreplaced'));
return true;
}
if (rng.findText(value['string'], value['backwards'] ? -1 : 1, flags)) {
rng.scrollIntoView();
rng.select();
rng.collapse(value['backwards']);
tinyMCE.lastSearchRng = rng;
} else
alert(tinyMCE.getLang('lang_searchreplace_notfound'));
} else {
if (value['replacemode'] == "all") {
while (win.find(value['string'], value['casesensitive'], value['backwards'], value['wrap'], value['wholeword'], false, false))
replaceSel(value['string'], value['replacestring']);
alert(tinyMCE.getLang('lang_searchreplace_allreplaced'));
return true;
}
if (!win.find(value['string'], value['casesensitive'], value['backwards'], value['wrap'], value['wholeword'], false, false))
alert(tinyMCE.getLang('lang_searchreplace_notfound'));
}
}
return true;
case "mceSearchReplace":
value['replacestring'] = "";
tinyMCE.execInstanceCommand(editor_id, 'mceSearch', user_interface, value, false);
return true;
}
// Pass to next handler in chain
return false;
} |
JavaScript | function TinyMCE_template_getControlHTML(control_name) {
switch (control_name) {
case "template":
return '<img id="{$editor_id}_template" src="{$pluginurl}/images/template.gif" title="{$lang_template_desc}" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mceTemplate\', true);" />';
}
return "";
} | function TinyMCE_template_getControlHTML(control_name) {
switch (control_name) {
case "template":
return '<img id="{$editor_id}_template" src="{$pluginurl}/images/template.gif" title="{$lang_template_desc}" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mceTemplate\', true);" />';
}
return "";
} |
JavaScript | function TinyMCE_template_execCommand(editor_id, element, command, user_interface, value) {
// Handle commands
switch (command) {
// Remember to have the "mce" prefix for commands so they don't intersect with built in ones in the browser.
case "mceTemplate":
// Show UI/Popup
if (user_interface) {
// Open a popup window and send in some custom data in a window argument
var template = new Array();
template['file'] = '../../plugins/template/popup.htm'; // Relative to theme
template['width'] = 150;
template['height'] = 180;
tinyMCE.openWindow(template, {editor_id : editor_id, some_custom_arg : "somecustomdata"});
// Let TinyMCE know that something was modified
tinyMCE.triggerNodeChange(false);
} else {
// Do a command this gets called from the template popup
alert("execCommand: mceTemplate gets called from popup.");
}
return true;
}
// Pass to next handler in chain
return false;
} | function TinyMCE_template_execCommand(editor_id, element, command, user_interface, value) {
// Handle commands
switch (command) {
// Remember to have the "mce" prefix for commands so they don't intersect with built in ones in the browser.
case "mceTemplate":
// Show UI/Popup
if (user_interface) {
// Open a popup window and send in some custom data in a window argument
var template = new Array();
template['file'] = '../../plugins/template/popup.htm'; // Relative to theme
template['width'] = 150;
template['height'] = 180;
tinyMCE.openWindow(template, {editor_id : editor_id, some_custom_arg : "somecustomdata"});
// Let TinyMCE know that something was modified
tinyMCE.triggerNodeChange(false);
} else {
// Do a command this gets called from the template popup
alert("execCommand: mceTemplate gets called from popup.");
}
return true;
}
// Pass to next handler in chain
return false;
} |
JavaScript | function TinyMCE_template_handleNodeChange(editor_id, node, undo_index, undo_levels, visual_aid, any_selection) {
// Deselect template button
tinyMCE.switchClassSticky(editor_id + '_template', 'mceButtonNormal');
// Select template button if parent node is a strong or b
if (node.parentNode.nodeName == "STRONG" || node.parentNode.nodeName == "B")
tinyMCE.switchClassSticky(editor_id + '_template', 'mceButtonSelected');
return true;
} | function TinyMCE_template_handleNodeChange(editor_id, node, undo_index, undo_levels, visual_aid, any_selection) {
// Deselect template button
tinyMCE.switchClassSticky(editor_id + '_template', 'mceButtonNormal');
// Select template button if parent node is a strong or b
if (node.parentNode.nodeName == "STRONG" || node.parentNode.nodeName == "B")
tinyMCE.switchClassSticky(editor_id + '_template', 'mceButtonSelected');
return true;
} |
JavaScript | function TinyMCE_template_cleanup(type, content) {
switch (type) {
case "get_from_editor":
alert("[FROM] Value HTML string: " + content);
// Do custom cleanup code here
break;
case "insert_to_editor":
alert("[TO] Value HTML string: " + content);
// Do custom cleanup code here
break;
case "get_from_editor_dom":
alert("[FROM] Value DOM Element " + content.innerHTML);
// Do custom cleanup code here
break;
case "insert_to_editor_dom":
alert("[TO] Value DOM Element: " + content.innerHTML);
// Do custom cleanup code here
break;
}
return content;
} | function TinyMCE_template_cleanup(type, content) {
switch (type) {
case "get_from_editor":
alert("[FROM] Value HTML string: " + content);
// Do custom cleanup code here
break;
case "insert_to_editor":
alert("[TO] Value HTML string: " + content);
// Do custom cleanup code here
break;
case "get_from_editor_dom":
alert("[FROM] Value DOM Element " + content.innerHTML);
// Do custom cleanup code here
break;
case "insert_to_editor_dom":
alert("[TO] Value DOM Element: " + content.innerHTML);
// Do custom cleanup code here
break;
}
return content;
} |
JavaScript | function TinyMCE_print_execCommand(editor_id, element, command, user_interface, value) {
// Handle commands
switch (command) {
case "mcePrint":
tinyMCE.getInstanceById(editor_id).contentWindow.print();
return true;
}
// Pass to next handler in chain
return false;
} | function TinyMCE_print_execCommand(editor_id, element, command, user_interface, value) {
// Handle commands
switch (command) {
case "mcePrint":
tinyMCE.getInstanceById(editor_id).contentWindow.print();
return true;
}
// Pass to next handler in chain
return false;
} |
JavaScript | function TinyMCE_insertdatetime_getControlHTML(control_name) {
var safariPatch = '" onclick="';
if (tinyMCE.isSafari)
safariPatch = "";
switch (control_name) {
case "insertdate":
return '<img id="{$editor_id}_insertdate" src="{$pluginurl}/images/insertdate.gif" title="{$lang_insertdate_desc}" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');' + safariPatch + 'tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mceInsertDate\');">';
case "inserttime":
return '<img id="{$editor_id}_inserttime" src="{$pluginurl}/images/inserttime.gif" title="{$lang_inserttime_desc}" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');' + safariPatch + 'tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mceInsertTime\');">';
}
return "";
} | function TinyMCE_insertdatetime_getControlHTML(control_name) {
var safariPatch = '" onclick="';
if (tinyMCE.isSafari)
safariPatch = "";
switch (control_name) {
case "insertdate":
return '<img id="{$editor_id}_insertdate" src="{$pluginurl}/images/insertdate.gif" title="{$lang_insertdate_desc}" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');' + safariPatch + 'tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mceInsertDate\');">';
case "inserttime":
return '<img id="{$editor_id}_inserttime" src="{$pluginurl}/images/inserttime.gif" title="{$lang_inserttime_desc}" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');' + safariPatch + 'tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mceInsertTime\');">';
}
return "";
} |
JavaScript | function TinyMCE_table_getControlHTML(control_name) {
var controls = new Array(
['table', 'table.gif', '{$lang_table_desc}', 'mceInsertTable', true],
['delete_col', 'table_delete_col.gif', '{$lang_table_delete_col_desc}', 'mceTableDeleteCol'],
['delete_row', 'table_delete_row.gif', '{$lang_table_delete_row_desc}', 'mceTableDeleteRow'],
['col_after', 'table_insert_col_after.gif', '{$lang_table_insert_col_after_desc}', 'mceTableInsertColAfter'],
['col_before', 'table_insert_col_before.gif', '{$lang_table_insert_col_before_desc}', 'mceTableInsertColBefore'],
['row_after', 'table_insert_row_after.gif', '{$lang_table_insert_row_after_desc}', 'mceTableInsertRowAfter'],
['row_before', 'table_insert_row_before.gif', '{$lang_table_insert_row_before_desc}', 'mceTableInsertRowBefore'],
['row_props', 'table_row_props.gif', '{$lang_table_row_desc}', 'mceTableRowProps', true],
['cell_props', 'table_cell_props.gif', '{$lang_table_cell_desc}', 'mceTableCellProps', true],
['split_cells', 'table_split_cells.gif', '{$lang_table_split_cells_desc}', 'mceTableSplitCells', true],
['merge_cells', 'table_merge_cells.gif', '{$lang_table_merge_cells_desc}', 'mceTableMergeCells', true]);
// Render table control
for (var i=0; i<controls.length; i++) {
var but = controls[i];
var safariPatch = '" onclick="';
if (tinyMCE.isSafari)
safariPatch = "";
if (but[0] == control_name && (tinyMCE.isMSIE || !tinyMCE.settings['button_tile_map']))
return '<img id="{$editor_id}_' + but[0] + '" src="{$pluginurl}/images/' + but[1] + '" title="' + but[2] + '" width="20" height="20" class="mceButtonDisabled" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');' + safariPatch + 'tinyMCE.execInstanceCommand(\'{$editor_id}\',\'' + but[3] + '\', ' + (but.length > 4 ? but[4] : false) + (but.length > 5 ? ', \'' + but[5] + '\'' : '') + ')">';
else if (but[0] == control_name)
return '<img id="{$editor_id}_' + but[0] + '" src="{$themeurl}/images/spacer.gif" style="background-image:url({$pluginurl}/images/buttons.gif); background-position: ' + (0-(i*20)) + 'px 0px" title="' + but[2] + '" width="20" height="20" class="mceButtonDisabled" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');' + safariPatch + 'tinyMCE.execInstanceCommand(\'{$editor_id}\',\'' + but[3] + '\', ' + (but.length > 4 ? but[4] : false) + (but.length > 5 ? ', \'' + but[5] + '\'' : '') + ')">';
}
// Special tablecontrols
if (control_name == "tablecontrols") {
var html = "";
html += tinyMCE.getControlHTML("table");
html += tinyMCE.getControlHTML("separator");
html += tinyMCE.getControlHTML("row_props");
html += tinyMCE.getControlHTML("cell_props");
html += tinyMCE.getControlHTML("separator");
html += tinyMCE.getControlHTML("row_before");
html += tinyMCE.getControlHTML("row_after");
html += tinyMCE.getControlHTML("delete_row");
html += tinyMCE.getControlHTML("separator");
html += tinyMCE.getControlHTML("col_before");
html += tinyMCE.getControlHTML("col_after");
html += tinyMCE.getControlHTML("delete_col");
html += tinyMCE.getControlHTML("separator");
html += tinyMCE.getControlHTML("split_cells");
html += tinyMCE.getControlHTML("merge_cells");
return html;
}
return "";
} | function TinyMCE_table_getControlHTML(control_name) {
var controls = new Array(
['table', 'table.gif', '{$lang_table_desc}', 'mceInsertTable', true],
['delete_col', 'table_delete_col.gif', '{$lang_table_delete_col_desc}', 'mceTableDeleteCol'],
['delete_row', 'table_delete_row.gif', '{$lang_table_delete_row_desc}', 'mceTableDeleteRow'],
['col_after', 'table_insert_col_after.gif', '{$lang_table_insert_col_after_desc}', 'mceTableInsertColAfter'],
['col_before', 'table_insert_col_before.gif', '{$lang_table_insert_col_before_desc}', 'mceTableInsertColBefore'],
['row_after', 'table_insert_row_after.gif', '{$lang_table_insert_row_after_desc}', 'mceTableInsertRowAfter'],
['row_before', 'table_insert_row_before.gif', '{$lang_table_insert_row_before_desc}', 'mceTableInsertRowBefore'],
['row_props', 'table_row_props.gif', '{$lang_table_row_desc}', 'mceTableRowProps', true],
['cell_props', 'table_cell_props.gif', '{$lang_table_cell_desc}', 'mceTableCellProps', true],
['split_cells', 'table_split_cells.gif', '{$lang_table_split_cells_desc}', 'mceTableSplitCells', true],
['merge_cells', 'table_merge_cells.gif', '{$lang_table_merge_cells_desc}', 'mceTableMergeCells', true]);
// Render table control
for (var i=0; i<controls.length; i++) {
var but = controls[i];
var safariPatch = '" onclick="';
if (tinyMCE.isSafari)
safariPatch = "";
if (but[0] == control_name && (tinyMCE.isMSIE || !tinyMCE.settings['button_tile_map']))
return '<img id="{$editor_id}_' + but[0] + '" src="{$pluginurl}/images/' + but[1] + '" title="' + but[2] + '" width="20" height="20" class="mceButtonDisabled" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');' + safariPatch + 'tinyMCE.execInstanceCommand(\'{$editor_id}\',\'' + but[3] + '\', ' + (but.length > 4 ? but[4] : false) + (but.length > 5 ? ', \'' + but[5] + '\'' : '') + ')">';
else if (but[0] == control_name)
return '<img id="{$editor_id}_' + but[0] + '" src="{$themeurl}/images/spacer.gif" style="background-image:url({$pluginurl}/images/buttons.gif); background-position: ' + (0-(i*20)) + 'px 0px" title="' + but[2] + '" width="20" height="20" class="mceButtonDisabled" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');' + safariPatch + 'tinyMCE.execInstanceCommand(\'{$editor_id}\',\'' + but[3] + '\', ' + (but.length > 4 ? but[4] : false) + (but.length > 5 ? ', \'' + but[5] + '\'' : '') + ')">';
}
// Special tablecontrols
if (control_name == "tablecontrols") {
var html = "";
html += tinyMCE.getControlHTML("table");
html += tinyMCE.getControlHTML("separator");
html += tinyMCE.getControlHTML("row_props");
html += tinyMCE.getControlHTML("cell_props");
html += tinyMCE.getControlHTML("separator");
html += tinyMCE.getControlHTML("row_before");
html += tinyMCE.getControlHTML("row_after");
html += tinyMCE.getControlHTML("delete_row");
html += tinyMCE.getControlHTML("separator");
html += tinyMCE.getControlHTML("col_before");
html += tinyMCE.getControlHTML("col_after");
html += tinyMCE.getControlHTML("delete_col");
html += tinyMCE.getControlHTML("separator");
html += tinyMCE.getControlHTML("split_cells");
html += tinyMCE.getControlHTML("merge_cells");
return html;
}
return "";
} |
JavaScript | function TinyMCE_iespell_getControlHTML(control_name) {
// Is it the iespell control and is the brower MSIE.
if (control_name == "iespell" && tinyMCE.isMSIE)
return '<img id="{$editor_id}_iespell" src="{$pluginurl}/images/iespell.gif" title="{$lang_iespell_desc}" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');" onclick="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mceIESpell\');">';
return "";
} | function TinyMCE_iespell_getControlHTML(control_name) {
// Is it the iespell control and is the brower MSIE.
if (control_name == "iespell" && tinyMCE.isMSIE)
return '<img id="{$editor_id}_iespell" src="{$pluginurl}/images/iespell.gif" title="{$lang_iespell_desc}" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');" onclick="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mceIESpell\');">';
return "";
} |
JavaScript | function TinyMCE_emotions_getControlHTML(control_name) {
switch (control_name) {
case "emotions":
return '<img id="{$editor_id}_emotions" src="{$pluginurl}/images/emotions.gif" title="{$lang_emotions_desc}" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mceEmotion\');">';
}
return "";
} | function TinyMCE_emotions_getControlHTML(control_name) {
switch (control_name) {
case "emotions":
return '<img id="{$editor_id}_emotions" src="{$pluginurl}/images/emotions.gif" title="{$lang_emotions_desc}" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mceEmotion\');">';
}
return "";
} |
JavaScript | function TinyMCE_advanced_getControlHTML(button_name)
{
var buttonTileMap = new Array('anchor.gif','backcolor.gif','bullist.gif','center.gif',
'charmap.gif','cleanup.gif','code.gif','copy.gif','custom_1.gif',
'cut.gif','forecolor.gif','full.gif','help.gif','hr.gif',
'image.gif','indent.gif','left.gif','link.gif','attachment.gif','numlist.gif',
'outdent.gif','paste.gif','redo.gif','removeformat.gif',
'right.gif','strikethrough.gif','sub.gif','sup.gif','undo.gif',
'unlink.gif','visualaid.gif');
// Lookup button in button list
for (var i=0; i<TinyMCE_advanced_buttons.length; i++)
{
var but = TinyMCE_advanced_buttons[i];
if (but[0] == button_name)
{
// Check for it in tilemap
if (tinyMCE.settings['button_tile_map'])
{
for (var x=0; !tinyMCE.isMSIE && x<buttonTileMap.length; x++)
{
if (buttonTileMap[x] == but[1])
{
return '<img id="{$editor_id}_' + but[0] +'" src="{$themeurl}/images/spacer.gif" style="background-image:url({$themeurl}/images/buttons.gif); background-position: ' + (0-(x*20)) + 'px 0px" title="' + but[2] + '" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');" onclick="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'' + but[3] + '\', ' + (but.length > 4 ? but[4] : false) + (but.length > 5 ? ', \'' + but[5] + '\'' : '') + ')">';
}
}
}
// Old style
return '<img id="{$editor_id}_' + but[0] + '" src="{$themeurl}/images/' + but[1] + '" title="' + but[2] + '" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');" onclick="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'' + but[3] + '\', ' + (but.length > 4 ? but[4] : false) + (but.length > 5 ? ', \'' + but[5] + '\'' : '') + ')">';
}
}
// Custom controlls other than buttons
switch (button_name)
{
case "formatselect":
var html = '<select id="{$editor_id}_formatSelect" name="{$editor_id}_formatSelect" onchange="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'FormatBlock\',false,this.options[this.selectedIndex].value);" class="mceSelectList">';
var formats = tinyMCE.getParam("theme_advanced_blockformats", "p,address,pre,h1,h2,h3,h4,h5,h6", true).split(',');
var lookup = [
['p', '{$lang_theme_paragraph}'],
['address', '{$lang_theme_address}'],
['pre', '{$lang_theme_pre}'],
['h1', '{$lang_theme_h1}'],
['h2', '{$lang_theme_h2}'],
['h3', '{$lang_theme_h3}'],
['h4', '{$lang_theme_h4}'],
['h5', '{$lang_theme_h5}'],
['h6', '{$lang_theme_h6}']
];
html += '<option value="">{$lang_theme_block}</option>';
// Build format select
for (var i=0; i<formats.length; i++)
{
for (var x=0; x<lookup.length; x++)
{
if (formats[i] == lookup[x][0])
{
html += '<option value="<' + lookup[x][0] + '>">' + lookup[x][1] + '</option>';
}
}
}
html += '</select>';
//formatselect
return html;
case "styleselect":
//styleselect
return '<select id="{$editor_id}_styleSelect" onmousedown="TinyMCE_advanced_setupCSSClasses(\'{$editor_id}\');" name="{$editor_id}_styleSelect" onchange="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mceSetCSSClass\',false,this.options[this.selectedIndex].value);" class="mceSelectList">{$style_select_options}</select>';
case "fontselect":
//fontselect
return '<select id="{$editor_id}_fontNameSelect" name="{$editor_id}_fontNameSelect" onchange="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'FontName\',false,this.options[this.selectedIndex].value);" class="mceSelectList">\
<option value="">{$lang_theme_fontdefault}</option>\
<option value="andale mono,times">Andale Mono</option>\
<option value="arial,helvetica">Arial</option>\
<option value="arial black,avant garde">Arial Black</option>\
<option value="book antiqua,palatino">Book Antiqua</option>\
<option value="comic sans ms,sand">Comic Sans MS</option>\
<option value="courier new,courier">Courier New</option>\
<option value="georgia,palatino">Georgia</option>\
<option value="helvetica">Helvetica</option>\
<option value="impact,chicago">Impact</option>\
<option value="symbol">Symbol</option>\
<option value="terminal,monaco">Terminal</option>\
<option value="times new roman,times">Times New Roman</option>\
<option value="trebuchet ms,geneva">Trebuchet MS</option>\
<option value="verdana,geneva">Verdana</option>\
<option value="webdings">Webdings</option>\
<option value="wingdings,zapf dingbats">Wingdings</option>\
</select>';
case "fontsizeselect":
//fontsizeselect
return '<select id="{$editor_id}_fontSizeSelect" name="{$editor_id}_fontSizeSelect" onchange="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'FontSize\',false,this.options[this.selectedIndex].value);" class="mceSelectList">\
<option value="0">-- {$lang_theme_font_size} --</option>\
<option value="1">1 (8 pt)</option>\
<option value="2">2 (10 pt)</option>\
<option value="3">3 (12 pt)</option>\
<option value="4">4 (14 pt)</option>\
<option value="5">5 (18 pt)</option>\
<option value="6">6 (24 pt)</option>\
<option value="7">7 (36 pt)</option>\
</select>';
case "|":
case "separator":
return '<img src="{$themeurl}/images/spacer.gif" width="1" height="15" class="mceSeparatorLine">';
case "spacer":
return '<img src="{$themeurl}/images/spacer.gif" width="1" height="15" border="0" class="mceSeparatorLine" style="vertical-align: middle" />';
case "rowseparator":
return '<br />';
}
return "";
} | function TinyMCE_advanced_getControlHTML(button_name)
{
var buttonTileMap = new Array('anchor.gif','backcolor.gif','bullist.gif','center.gif',
'charmap.gif','cleanup.gif','code.gif','copy.gif','custom_1.gif',
'cut.gif','forecolor.gif','full.gif','help.gif','hr.gif',
'image.gif','indent.gif','left.gif','link.gif','attachment.gif','numlist.gif',
'outdent.gif','paste.gif','redo.gif','removeformat.gif',
'right.gif','strikethrough.gif','sub.gif','sup.gif','undo.gif',
'unlink.gif','visualaid.gif');
// Lookup button in button list
for (var i=0; i<TinyMCE_advanced_buttons.length; i++)
{
var but = TinyMCE_advanced_buttons[i];
if (but[0] == button_name)
{
// Check for it in tilemap
if (tinyMCE.settings['button_tile_map'])
{
for (var x=0; !tinyMCE.isMSIE && x<buttonTileMap.length; x++)
{
if (buttonTileMap[x] == but[1])
{
return '<img id="{$editor_id}_' + but[0] +'" src="{$themeurl}/images/spacer.gif" style="background-image:url({$themeurl}/images/buttons.gif); background-position: ' + (0-(x*20)) + 'px 0px" title="' + but[2] + '" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');" onclick="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'' + but[3] + '\', ' + (but.length > 4 ? but[4] : false) + (but.length > 5 ? ', \'' + but[5] + '\'' : '') + ')">';
}
}
}
// Old style
return '<img id="{$editor_id}_' + but[0] + '" src="{$themeurl}/images/' + but[1] + '" title="' + but[2] + '" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');" onclick="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'' + but[3] + '\', ' + (but.length > 4 ? but[4] : false) + (but.length > 5 ? ', \'' + but[5] + '\'' : '') + ')">';
}
}
// Custom controlls other than buttons
switch (button_name)
{
case "formatselect":
var html = '<select id="{$editor_id}_formatSelect" name="{$editor_id}_formatSelect" onchange="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'FormatBlock\',false,this.options[this.selectedIndex].value);" class="mceSelectList">';
var formats = tinyMCE.getParam("theme_advanced_blockformats", "p,address,pre,h1,h2,h3,h4,h5,h6", true).split(',');
var lookup = [
['p', '{$lang_theme_paragraph}'],
['address', '{$lang_theme_address}'],
['pre', '{$lang_theme_pre}'],
['h1', '{$lang_theme_h1}'],
['h2', '{$lang_theme_h2}'],
['h3', '{$lang_theme_h3}'],
['h4', '{$lang_theme_h4}'],
['h5', '{$lang_theme_h5}'],
['h6', '{$lang_theme_h6}']
];
html += '<option value="">{$lang_theme_block}</option>';
// Build format select
for (var i=0; i<formats.length; i++)
{
for (var x=0; x<lookup.length; x++)
{
if (formats[i] == lookup[x][0])
{
html += '<option value="<' + lookup[x][0] + '>">' + lookup[x][1] + '</option>';
}
}
}
html += '</select>';
//formatselect
return html;
case "styleselect":
//styleselect
return '<select id="{$editor_id}_styleSelect" onmousedown="TinyMCE_advanced_setupCSSClasses(\'{$editor_id}\');" name="{$editor_id}_styleSelect" onchange="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mceSetCSSClass\',false,this.options[this.selectedIndex].value);" class="mceSelectList">{$style_select_options}</select>';
case "fontselect":
//fontselect
return '<select id="{$editor_id}_fontNameSelect" name="{$editor_id}_fontNameSelect" onchange="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'FontName\',false,this.options[this.selectedIndex].value);" class="mceSelectList">\
<option value="">{$lang_theme_fontdefault}</option>\
<option value="andale mono,times">Andale Mono</option>\
<option value="arial,helvetica">Arial</option>\
<option value="arial black,avant garde">Arial Black</option>\
<option value="book antiqua,palatino">Book Antiqua</option>\
<option value="comic sans ms,sand">Comic Sans MS</option>\
<option value="courier new,courier">Courier New</option>\
<option value="georgia,palatino">Georgia</option>\
<option value="helvetica">Helvetica</option>\
<option value="impact,chicago">Impact</option>\
<option value="symbol">Symbol</option>\
<option value="terminal,monaco">Terminal</option>\
<option value="times new roman,times">Times New Roman</option>\
<option value="trebuchet ms,geneva">Trebuchet MS</option>\
<option value="verdana,geneva">Verdana</option>\
<option value="webdings">Webdings</option>\
<option value="wingdings,zapf dingbats">Wingdings</option>\
</select>';
case "fontsizeselect":
//fontsizeselect
return '<select id="{$editor_id}_fontSizeSelect" name="{$editor_id}_fontSizeSelect" onchange="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'FontSize\',false,this.options[this.selectedIndex].value);" class="mceSelectList">\
<option value="0">-- {$lang_theme_font_size} --</option>\
<option value="1">1 (8 pt)</option>\
<option value="2">2 (10 pt)</option>\
<option value="3">3 (12 pt)</option>\
<option value="4">4 (14 pt)</option>\
<option value="5">5 (18 pt)</option>\
<option value="6">6 (24 pt)</option>\
<option value="7">7 (36 pt)</option>\
</select>';
case "|":
case "separator":
return '<img src="{$themeurl}/images/spacer.gif" width="1" height="15" class="mceSeparatorLine">';
case "spacer":
return '<img src="{$themeurl}/images/spacer.gif" width="1" height="15" border="0" class="mceSeparatorLine" style="vertical-align: middle" />';
case "rowseparator":
return '<br />';
}
return "";
} |
JavaScript | function TinyMCE_advanced_execCommand(editor_id, element, command, user_interface, value)
{
switch (command)
{
case "mceForeColor":
var template = new Array();
var inputColor = TinyMCE_advanced_foreColor;
if (!inputColor)
{
inputColor = "#000000";
}
template['file'] = 'color_picker.htm';
template['width'] = 210;
template['height'] = 200;
tinyMCE.openWindow(template, {editor_id : editor_id, command : "forecolor", input_color : inputColor});
//mceForeColor
return true;
case "mceBackColor":
var template = new Array();
var inputColor = TinyMCE_advanced_foreColor;
if (!inputColor)
{
inputColor = "#000000";
}
template['file'] = 'color_picker.htm';
template['width'] = 210;
template['height'] = 200;
tinyMCE.openWindow(template, {editor_id : editor_id, command : "HiliteColor", input_color : inputColor});
//mceBackColor
return true;
case "mceCodeEditor":
var template = new Array();
template['file'] = 'source_editor.htm';
template['width'] = tinyMCE.getParam("theme_advanced_source_editor_width", 500);
template['height'] = tinyMCE.getParam("theme_advanced_source_editor_height", 400);
tinyMCE.openWindow(template, {editor_id : editor_id, resizable : "yes", scrollbars : "no"});
//mceCodeEditor
return true;
case "mceCharMap":
var template = new Array();
template['file'] = 'charmap.htm';
template['width'] = 550;
template['height'] = 280;
tinyMCE.openWindow(template, {editor_id : editor_id});
//mceCharMap
return true;
case "mceInsertAnchor":
var template = new Array();
template['file'] = 'anchor.htm';
template['width'] = 320;
template['height'] = 130;
tinyMCE.openWindow(template, {editor_id : editor_id, name : TinyMCE_advanced_anchorName, action : (TinyMCE_advanced_anchorName == "" ? "insert" : "update")});
//mceInsertAnchor
return true;
}
// Default behavior
return false;
} | function TinyMCE_advanced_execCommand(editor_id, element, command, user_interface, value)
{
switch (command)
{
case "mceForeColor":
var template = new Array();
var inputColor = TinyMCE_advanced_foreColor;
if (!inputColor)
{
inputColor = "#000000";
}
template['file'] = 'color_picker.htm';
template['width'] = 210;
template['height'] = 200;
tinyMCE.openWindow(template, {editor_id : editor_id, command : "forecolor", input_color : inputColor});
//mceForeColor
return true;
case "mceBackColor":
var template = new Array();
var inputColor = TinyMCE_advanced_foreColor;
if (!inputColor)
{
inputColor = "#000000";
}
template['file'] = 'color_picker.htm';
template['width'] = 210;
template['height'] = 200;
tinyMCE.openWindow(template, {editor_id : editor_id, command : "HiliteColor", input_color : inputColor});
//mceBackColor
return true;
case "mceCodeEditor":
var template = new Array();
template['file'] = 'source_editor.htm';
template['width'] = tinyMCE.getParam("theme_advanced_source_editor_width", 500);
template['height'] = tinyMCE.getParam("theme_advanced_source_editor_height", 400);
tinyMCE.openWindow(template, {editor_id : editor_id, resizable : "yes", scrollbars : "no"});
//mceCodeEditor
return true;
case "mceCharMap":
var template = new Array();
template['file'] = 'charmap.htm';
template['width'] = 550;
template['height'] = 280;
tinyMCE.openWindow(template, {editor_id : editor_id});
//mceCharMap
return true;
case "mceInsertAnchor":
var template = new Array();
template['file'] = 'anchor.htm';
template['width'] = 320;
template['height'] = 130;
tinyMCE.openWindow(template, {editor_id : editor_id, name : TinyMCE_advanced_anchorName, action : (TinyMCE_advanced_anchorName == "" ? "insert" : "update")});
//mceInsertAnchor
return true;
}
// Default behavior
return false;
} |
JavaScript | function TinyMCE_advanced_setupCSSClasses(editor_id)
{
if (!TinyMCE_advanced_autoImportCSSClasses)
{
return;
}
var selectElm = document.getElementById(editor_id + '_styleSelect');
if (selectElm && selectElm.getAttribute('cssImported') != 'true')
{
var csses = tinyMCE.getCSSClasses(editor_id);
if (csses && selectElm)
{
for (var i=0; i<csses.length; i++)
{
selectElm.options[selectElm.length] = new Option(csses[i], csses[i]);
}
}
// Only do this once
if (csses != null && csses.length > 0)
{
selectElm.setAttribute('cssImported', 'true');
}
}
} | function TinyMCE_advanced_setupCSSClasses(editor_id)
{
if (!TinyMCE_advanced_autoImportCSSClasses)
{
return;
}
var selectElm = document.getElementById(editor_id + '_styleSelect');
if (selectElm && selectElm.getAttribute('cssImported') != 'true')
{
var csses = tinyMCE.getCSSClasses(editor_id);
if (csses && selectElm)
{
for (var i=0; i<csses.length; i++)
{
selectElm.options[selectElm.length] = new Option(csses[i], csses[i]);
}
}
// Only do this once
if (csses != null && csses.length > 0)
{
selectElm.setAttribute('cssImported', 'true');
}
}
} |
JavaScript | function TinyMCE_zoom_getControlHTML(control_name) {
if (!tinyMCE.isMSIE || tinyMCE.isMSIE5_0)
return "";
switch (control_name) {
case "zoom":
return '<select id="{$editor_id}_formatSelect" name="{$editor_id}_zoomSelect" onchange="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mceZoom\',false,this.options[this.selectedIndex].value);" class="mceSelectList">\
<option value="100%">+ 100%</option>\
<option value="150%">+ 150%</option>\
<option value="200%">+ 200%</option>\
<option value="250%">+ 250%</option>\
</select>';
}
return "";
} | function TinyMCE_zoom_getControlHTML(control_name) {
if (!tinyMCE.isMSIE || tinyMCE.isMSIE5_0)
return "";
switch (control_name) {
case "zoom":
return '<select id="{$editor_id}_formatSelect" name="{$editor_id}_zoomSelect" onchange="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mceZoom\',false,this.options[this.selectedIndex].value);" class="mceSelectList">\
<option value="100%">+ 100%</option>\
<option value="150%">+ 150%</option>\
<option value="200%">+ 200%</option>\
<option value="250%">+ 250%</option>\
</select>';
}
return "";
} |
JavaScript | function init (model) {
if (model.__ttl) return;
var distinct_ = model.distinct;
model.distinct = function distinct (field, cond, cb) {
applyTTL(cond);
return distinct_.call(model, field, cond, cb);
}
'findOne find count'.split(' ').forEach(function (method) {
var fn = model[method];
model[method] = function (cond, fields, opts, cb) {
if (!cond) {
cond = {};
} else if ('function' == typeof cond) {
cb = cond;
cond = {};
}
applyTTL(cond);
return fn.call(model, cond, fields, opts, cb);
}
});
'where $where'.split(' ').forEach(function (method) {
var fn = model[method];
model[method] = function () {
var query = fn.apply(this, arguments)
, cond = {};
applyTTL(cond);
return query.find(cond);
}
});
if (reap) {
model.startTTLReaper();
}
} | function init (model) {
if (model.__ttl) return;
var distinct_ = model.distinct;
model.distinct = function distinct (field, cond, cb) {
applyTTL(cond);
return distinct_.call(model, field, cond, cb);
}
'findOne find count'.split(' ').forEach(function (method) {
var fn = model[method];
model[method] = function (cond, fields, opts, cb) {
if (!cond) {
cond = {};
} else if ('function' == typeof cond) {
cb = cond;
cond = {};
}
applyTTL(cond);
return fn.call(model, cond, fields, opts, cb);
}
});
'where $where'.split(' ').forEach(function (method) {
var fn = model[method];
model[method] = function () {
var query = fn.apply(this, arguments)
, cond = {};
applyTTL(cond);
return query.find(cond);
}
});
if (reap) {
model.startTTLReaper();
}
} |
JavaScript | function applyTTL (cond) {
if (cond[key]) {
cond.$and || (cond.$and = []);
var a = {};
a[key] = cond[key];
cond.$and.push(a);
var b = {};
b[key] = { $gt: new Date };
cond.$and.push(b);
delete cond[key];
} else {
cond[key] = { $gt: new Date };
}
} | function applyTTL (cond) {
if (cond[key]) {
cond.$and || (cond.$and = []);
var a = {};
a[key] = cond[key];
cond.$and.push(a);
var b = {};
b[key] = { $gt: new Date };
cond.$and.push(b);
delete cond[key];
} else {
cond[key] = { $gt: new Date };
}
} |
JavaScript | function nthIndex(str, pat, n){
var L= str.length, i= -1;
while(n!=0){
i= str.lastIndexOf(pat);
str = str.substring(0, i);
if(str.length>4){
n=0;
}else{
n--;
}
}
return i;
} | function nthIndex(str, pat, n){
var L= str.length, i= -1;
while(n!=0){
i= str.lastIndexOf(pat);
str = str.substring(0, i);
if(str.length>4){
n=0;
}else{
n--;
}
}
return i;
} |
JavaScript | function createObject(result, next){
var new_data = {};
async.forEachOf(result.data, function(value, index, value_cb){
if(Array.isArray(value.value) && value.value.length>1){
new_data[value.name] = {};
async.forEachOf(value.value, function(_value, _index, _cb){
new_data[value.name][_value.name] = _value.value;
_cb();
},function done(){
value_cb();
})
}else{
new_data[value.name] = value.value;
value_cb();
}
},function done(){
result['final_data'] = new_data;
next(null, result);
})
} | function createObject(result, next){
var new_data = {};
async.forEachOf(result.data, function(value, index, value_cb){
if(Array.isArray(value.value) && value.value.length>1){
new_data[value.name] = {};
async.forEachOf(value.value, function(_value, _index, _cb){
new_data[value.name][_value.name] = _value.value;
_cb();
},function done(){
value_cb();
})
}else{
new_data[value.name] = value.value;
value_cb();
}
},function done(){
result['final_data'] = new_data;
next(null, result);
})
} |
JavaScript | function nthIndex(str, pat, n){
var L= str.length, i= -1;
while(n!=0){
i= str.lastIndexOf(pat);
str = str.substring(0, i);
n--;
}
return i;
} | function nthIndex(str, pat, n){
var L= str.length, i= -1;
while(n!=0){
i= str.lastIndexOf(pat);
str = str.substring(0, i);
n--;
}
return i;
} |
JavaScript | static alpha2number(alpha) {
let result = 0;
const alphalength = XTableUtils.alphachars.length;
for (let i = 0, l = alpha.length; i < l; i += 1) {
if (i > 0) {
result += 1;
}
const current = XTableUtils.alphaIndex(alpha[i]);
if (current === -1) {
throw new Error('Invalid alpha');
}
result = result * alphalength + current;
}
return result;
} | static alpha2number(alpha) {
let result = 0;
const alphalength = XTableUtils.alphachars.length;
for (let i = 0, l = alpha.length; i < l; i += 1) {
if (i > 0) {
result += 1;
}
const current = XTableUtils.alphaIndex(alpha[i]);
if (current === -1) {
throw new Error('Invalid alpha');
}
result = result * alphalength + current;
}
return result;
} |
JavaScript | function cloneVNode(vNodeToClone, props) {
var _children = [];
for (var _i = 2; _i < arguments.length; _i++) {
_children[_i - 2] = arguments[_i];
}
var children = _children;
var childrenLen = _children.length;
if (childrenLen > 0 && !inferno_shared_1.isUndefined(_children[0])) {
if (!props) {
props = {};
}
if (childrenLen === 1) {
children = _children[0];
}
if (!inferno_shared_1.isUndefined(children)) {
props.children = children;
}
}
var newVNode;
if (inferno_shared_1.isArray(vNodeToClone)) {
var tmpArray = [];
for (var i = 0, len = vNodeToClone.length; i < len; i++) {
tmpArray.push(directClone(vNodeToClone[i]));
}
newVNode = tmpArray;
}
else {
var flags = vNodeToClone.flags;
var className = vNodeToClone.className || (props && props.className) || null;
var key = !inferno_shared_1.isNullOrUndef(vNodeToClone.key) ? vNodeToClone.key : (props ? props.key : null);
var ref = vNodeToClone.ref || (props ? props.ref : null);
if (flags & 28 /* Component */) {
newVNode = createVNode(flags, vNodeToClone.type, className, null, (!vNodeToClone.props && !props) ? utils_1.EMPTY_OBJ : inferno_shared_1.combineFrom(vNodeToClone.props, props), key, ref, true);
var newProps = newVNode.props;
if (newProps) {
var newChildren = newProps.children;
// we need to also clone component children that are in props
// as the children may also have been hoisted
if (newChildren) {
if (inferno_shared_1.isArray(newChildren)) {
var len = newChildren.length;
if (len > 0) {
var tmpArray = [];
for (var i = 0; i < len; i++) {
var child = newChildren[i];
if (inferno_shared_1.isStringOrNumber(child)) {
tmpArray.push(child);
}
else if (!inferno_shared_1.isInvalid(child) && isVNode(child)) {
tmpArray.push(directClone(child));
}
}
newProps.children = tmpArray;
}
}
else if (isVNode(newChildren)) {
newProps.children = directClone(newChildren);
}
}
}
newVNode.children = null;
}
else if (flags & 3970 /* Element */) {
children = (props && !inferno_shared_1.isUndefined(props.children)) ? props.children : vNodeToClone.children;
newVNode = createVNode(flags, vNodeToClone.type, className, children, (!vNodeToClone.props && !props) ? utils_1.EMPTY_OBJ : inferno_shared_1.combineFrom(vNodeToClone.props, props), key, ref, !children);
}
else if (flags & 1 /* Text */) {
newVNode = createTextVNode(vNodeToClone.children, key);
}
}
return newVNode;
} | function cloneVNode(vNodeToClone, props) {
var _children = [];
for (var _i = 2; _i < arguments.length; _i++) {
_children[_i - 2] = arguments[_i];
}
var children = _children;
var childrenLen = _children.length;
if (childrenLen > 0 && !inferno_shared_1.isUndefined(_children[0])) {
if (!props) {
props = {};
}
if (childrenLen === 1) {
children = _children[0];
}
if (!inferno_shared_1.isUndefined(children)) {
props.children = children;
}
}
var newVNode;
if (inferno_shared_1.isArray(vNodeToClone)) {
var tmpArray = [];
for (var i = 0, len = vNodeToClone.length; i < len; i++) {
tmpArray.push(directClone(vNodeToClone[i]));
}
newVNode = tmpArray;
}
else {
var flags = vNodeToClone.flags;
var className = vNodeToClone.className || (props && props.className) || null;
var key = !inferno_shared_1.isNullOrUndef(vNodeToClone.key) ? vNodeToClone.key : (props ? props.key : null);
var ref = vNodeToClone.ref || (props ? props.ref : null);
if (flags & 28 /* Component */) {
newVNode = createVNode(flags, vNodeToClone.type, className, null, (!vNodeToClone.props && !props) ? utils_1.EMPTY_OBJ : inferno_shared_1.combineFrom(vNodeToClone.props, props), key, ref, true);
var newProps = newVNode.props;
if (newProps) {
var newChildren = newProps.children;
// we need to also clone component children that are in props
// as the children may also have been hoisted
if (newChildren) {
if (inferno_shared_1.isArray(newChildren)) {
var len = newChildren.length;
if (len > 0) {
var tmpArray = [];
for (var i = 0; i < len; i++) {
var child = newChildren[i];
if (inferno_shared_1.isStringOrNumber(child)) {
tmpArray.push(child);
}
else if (!inferno_shared_1.isInvalid(child) && isVNode(child)) {
tmpArray.push(directClone(child));
}
}
newProps.children = tmpArray;
}
}
else if (isVNode(newChildren)) {
newProps.children = directClone(newChildren);
}
}
}
newVNode.children = null;
}
else if (flags & 3970 /* Element */) {
children = (props && !inferno_shared_1.isUndefined(props.children)) ? props.children : vNodeToClone.children;
newVNode = createVNode(flags, vNodeToClone.type, className, children, (!vNodeToClone.props && !props) ? utils_1.EMPTY_OBJ : inferno_shared_1.combineFrom(vNodeToClone.props, props), key, ref, !children);
}
else if (flags & 1 /* Text */) {
newVNode = createTextVNode(vNodeToClone.children, key);
}
}
return newVNode;
} |
JavaScript | function patchStyle(lastAttrValue, nextAttrValue, dom) {
var domStyle = dom.style;
if (inferno_shared_1.isString(nextAttrValue)) {
domStyle.cssText = nextAttrValue;
return;
}
for (var style in nextAttrValue) {
// do not add a hasOwnProperty check here, it affects performance
var value = nextAttrValue[style];
if (!inferno_shared_1.isNumber(value) || style in constants_1.isUnitlessNumber) {
domStyle[style] = value;
}
else {
domStyle[style] = value + 'px';
}
}
if (!inferno_shared_1.isNullOrUndef(lastAttrValue)) {
for (var style in lastAttrValue) {
if (inferno_shared_1.isNullOrUndef(nextAttrValue[style])) {
domStyle[style] = '';
}
}
}
} | function patchStyle(lastAttrValue, nextAttrValue, dom) {
var domStyle = dom.style;
if (inferno_shared_1.isString(nextAttrValue)) {
domStyle.cssText = nextAttrValue;
return;
}
for (var style in nextAttrValue) {
// do not add a hasOwnProperty check here, it affects performance
var value = nextAttrValue[style];
if (!inferno_shared_1.isNumber(value) || style in constants_1.isUnitlessNumber) {
domStyle[style] = value;
}
else {
domStyle[style] = value + 'px';
}
}
if (!inferno_shared_1.isNullOrUndef(lastAttrValue)) {
for (var style in lastAttrValue) {
if (inferno_shared_1.isNullOrUndef(nextAttrValue[style])) {
domStyle[style] = '';
}
}
}
} |
JavaScript | function postLoad(error, svg) {
// Handle Errors
if (error) {
return
}
let paths = svg.getElementsByTagName("path")
// Adds diffrentstyles to svg paths depending on the number of paths
switch (paths.length) {
case 1:
resetClass(paths[0], styles.light_icon_color)
break
case 3:
resetClass(paths[0], styles.icon_stroke_one)
resetClass(paths[1], styles.icon_stroke_two)
resetClass(paths[2], styles.icon_stroke_three)
break
default:
console.log("ERROR NO PATHS. SVG OUTPUT: ", svg)
}
} | function postLoad(error, svg) {
// Handle Errors
if (error) {
return
}
let paths = svg.getElementsByTagName("path")
// Adds diffrentstyles to svg paths depending on the number of paths
switch (paths.length) {
case 1:
resetClass(paths[0], styles.light_icon_color)
break
case 3:
resetClass(paths[0], styles.icon_stroke_one)
resetClass(paths[1], styles.icon_stroke_two)
resetClass(paths[2], styles.icon_stroke_three)
break
default:
console.log("ERROR NO PATHS. SVG OUTPUT: ", svg)
}
} |
JavaScript | function preLoad(svg) {
// console.log("IM BEOFRE", svg) // For Testing
svg.classList.add(styles.icon)
// Make sure svg is set to
svg.setAttribute(`width`, `1em`)
svg.setAttribute(`height`, `1em`)
// Make sure svg scales to the view bounds and not the view box
// Makes sure proportions are kept and font size adjusts icon
svg.setAttribute(`preserveAspectRatio`, `MidYMid meet`)
} | function preLoad(svg) {
// console.log("IM BEOFRE", svg) // For Testing
svg.classList.add(styles.icon)
// Make sure svg is set to
svg.setAttribute(`width`, `1em`)
svg.setAttribute(`height`, `1em`)
// Make sure svg scales to the view bounds and not the view box
// Makes sure proportions are kept and font size adjusts icon
svg.setAttribute(`preserveAspectRatio`, `MidYMid meet`)
} |
JavaScript | function useWindowWidth(screenRes) {
const [windowWidth, setWindowWidth] = useState(isScreenSize(screenRes))
// Only updates every REFRESH_RATE
const throttleHandleWindowResize = throttle(() => {
setWindowWidth(isScreenSize(screenRes))
}, REFRESH_RATE)
// SImilar to componentDidMount and componentDidUpdate
useEffect(() => {
window.addEventListener("resize", throttleHandleWindowResize)
// Specify how to clean up after this effect:
// SImilar to componentWillUnmount
return () =>
window.removeEventListener("resize", throttleHandleWindowResize)
}, [])
return windowWidth
} | function useWindowWidth(screenRes) {
const [windowWidth, setWindowWidth] = useState(isScreenSize(screenRes))
// Only updates every REFRESH_RATE
const throttleHandleWindowResize = throttle(() => {
setWindowWidth(isScreenSize(screenRes))
}, REFRESH_RATE)
// SImilar to componentDidMount and componentDidUpdate
useEffect(() => {
window.addEventListener("resize", throttleHandleWindowResize)
// Specify how to clean up after this effect:
// SImilar to componentWillUnmount
return () =>
window.removeEventListener("resize", throttleHandleWindowResize)
}, [])
return windowWidth
} |
JavaScript | function createSocialIcons(socialIcons) {
let icons = []
socialIcons.forEach((socialIcon, index) => {
icons.push(
<SocialIcon
key={index}
src={socialIcon.icon.filename}
name={socialIcon.name}
profileUrl={socialIcon.link}
size={"32px"}
/>
)
})
return icons
} | function createSocialIcons(socialIcons) {
let icons = []
socialIcons.forEach((socialIcon, index) => {
icons.push(
<SocialIcon
key={index}
src={socialIcon.icon.filename}
name={socialIcon.name}
profileUrl={socialIcon.link}
size={"32px"}
/>
)
})
return icons
} |
JavaScript | handleWireStripClick(prop, wireID, event) {
// event.stopPropagation();
const clickedWireRange = this.props.schema.obj[wireID].parentRange;
this.handlePropModeChange(prop);
this.handleScopeRangeChange(clickedWireRange);
} | handleWireStripClick(prop, wireID, event) {
// event.stopPropagation();
const clickedWireRange = this.props.schema.obj[wireID].parentRange;
this.handlePropModeChange(prop);
this.handleScopeRangeChange(clickedWireRange);
} |
JavaScript | handleMapSchemeSwitchClick(clickedMode) {
this.setState(prevState => {
if (prevState.mode === clickedMode) {
return null;
} else {
return { mode: clickedMode };
}
});
} | handleMapSchemeSwitchClick(clickedMode) {
this.setState(prevState => {
if (prevState.mode === clickedMode) {
return null;
} else {
return { mode: clickedMode };
}
});
} |
JavaScript | async updateState(tsRange, possibleWires) {
console.log(
`%c[CHART] Data update started, revision ${
this.state.revision
}, human range ${displayHuman(tsRange)}`,
'color: darkgreen'
);
const dataArr = formatDataArr(
await readDataByTSRanges(possibleWires, tsRange),
this.props.spanLength,
this.props.fMode,
this.props.iceMode
);
// console.log(`%c[CHART] Max ts in datarr ${displayHuman(freshMaxTS(dataArr))}`,'color: darkgreen');
this.setState(prevState => ({
dataArr: dataArr,
revision: prevState.revision + 1
// isReady: true
}));
// Make parent know that data fetch is finalised and we can show it
this.props.onDataLoaded();
} | async updateState(tsRange, possibleWires) {
console.log(
`%c[CHART] Data update started, revision ${
this.state.revision
}, human range ${displayHuman(tsRange)}`,
'color: darkgreen'
);
const dataArr = formatDataArr(
await readDataByTSRanges(possibleWires, tsRange),
this.props.spanLength,
this.props.fMode,
this.props.iceMode
);
// console.log(`%c[CHART] Max ts in datarr ${displayHuman(freshMaxTS(dataArr))}`,'color: darkgreen');
this.setState(prevState => ({
dataArr: dataArr,
revision: prevState.revision + 1
// isReady: true
}));
// Make parent know that data fetch is finalised and we can show it
this.props.onDataLoaded();
} |
JavaScript | function encrypt(text) {
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv('aes-256-ctr', Buffer.from(PEPPER), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
} | function encrypt(text) {
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv('aes-256-ctr', Buffer.from(PEPPER), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
} |
JavaScript | function autoSave(confirmation, callAfter) {
// Note: TinyMCE coupling
if(typeof tinyMCE != 'undefined') tinyMCE.triggerSave();
var __forms = []
if($('Form_EditForm')) __forms.push($('Form_EditForm'));
if($('Form_SubForm')) __forms.push($('Form_SubForm'));
var __somethingHasChanged = false;
var __callAfter = callAfter;
__forms.each(function(form) {
if(form.isChanged && form.isChanged()) {
__somethingHasChanged = true;
}
});
if(__somethingHasChanged) {
// Note: discard and cancel options are no longer used since switching to confirm dialog.
// save is still used if confirmation = false
var options = {
save: function() {
statusMessage(ss.i18n._t('CMSMAIN.SAVING'), '', true);
var i;
for(i=0;i<__forms.length;i++) {
if(__forms[i].isChanged && __forms[i].isChanged()) {
if(i == 0) __forms[i].save(true, __callAfter);
else __forms[i].save(true);
}
}
},
discard: function() {
__forms.each(function(form) { form.resetElements(false); });
if(__callAfter) __callAfter();
},
cancel: function() {
}
}
if(confirmation ) {
if(confirm(ss.i18n._t('LeftAndMain.CONFIRMUNSAVED')))
{
// OK was pressed, call function for what was clicked on
if(__callAfter) __callAfter();
} else {
// Cancel was pressed, stay on the current page
return false;
}
} else {
options.save();
}
} else {
if(__callAfter) __callAfter();
}
} | function autoSave(confirmation, callAfter) {
// Note: TinyMCE coupling
if(typeof tinyMCE != 'undefined') tinyMCE.triggerSave();
var __forms = []
if($('Form_EditForm')) __forms.push($('Form_EditForm'));
if($('Form_SubForm')) __forms.push($('Form_SubForm'));
var __somethingHasChanged = false;
var __callAfter = callAfter;
__forms.each(function(form) {
if(form.isChanged && form.isChanged()) {
__somethingHasChanged = true;
}
});
if(__somethingHasChanged) {
// Note: discard and cancel options are no longer used since switching to confirm dialog.
// save is still used if confirmation = false
var options = {
save: function() {
statusMessage(ss.i18n._t('CMSMAIN.SAVING'), '', true);
var i;
for(i=0;i<__forms.length;i++) {
if(__forms[i].isChanged && __forms[i].isChanged()) {
if(i == 0) __forms[i].save(true, __callAfter);
else __forms[i].save(true);
}
}
},
discard: function() {
__forms.each(function(form) { form.resetElements(false); });
if(__callAfter) __callAfter();
},
cancel: function() {
}
}
if(confirmation ) {
if(confirm(ss.i18n._t('LeftAndMain.CONFIRMUNSAVED')))
{
// OK was pressed, call function for what was clicked on
if(__callAfter) __callAfter();
} else {
// Cancel was pressed, stay on the current page
return false;
}
} else {
options.save();
}
} else {
if(__callAfter) __callAfter();
}
} |
JavaScript | function tinymce_removeAll() {
if((typeof tinymce != 'undefined') && tinymce.EditorManager) {
var id;
for(id in tinymce.EditorManager.editors) {
tinymce.EditorManager.editors[id].remove();
}
tinymce.EditorManager.editors = {};
}
} | function tinymce_removeAll() {
if((typeof tinymce != 'undefined') && tinymce.EditorManager) {
var id;
for(id in tinymce.EditorManager.editors) {
tinymce.EditorManager.editors[id].remove();
}
tinymce.EditorManager.editors = {};
}
} |
JavaScript | ensureLogIn({ commit }) {
axios.get('/login/whoami').then((response) => {
commit('setLoggedIn', { loggedIn: true, mail: response.data.mail, name: response.data.name });
}).catch((error) => {
console.error(error);
commit('setLoggedIn', { loggedIn: false });
});
} | ensureLogIn({ commit }) {
axios.get('/login/whoami').then((response) => {
commit('setLoggedIn', { loggedIn: true, mail: response.data.mail, name: response.data.name });
}).catch((error) => {
console.error(error);
commit('setLoggedIn', { loggedIn: false });
});
} |
JavaScript | function resolveHostAndPortFromMovedError(movedError) {
// Attempt to resolve the new host & port from the error message
if (isMovedError(movedError)) {
return movedError.message.substring(movedError.message.lastIndexOf(' ') + 1).split(':');
}
throw new Error(`Unexpected redis client "moved" ReplyError - ${movedError}`);
} | function resolveHostAndPortFromMovedError(movedError) {
// Attempt to resolve the new host & port from the error message
if (isMovedError(movedError)) {
return movedError.message.substring(movedError.message.lastIndexOf(' ') + 1).split(':');
}
throw new Error(`Unexpected redis client "moved" ReplyError - ${movedError}`);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.