language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript
|
function escribeTotales(paramCallback,respuesta)
{
if (respuesta != 0) {
//obetenemos los datos del controlador en formato json
var datos = JSON.parse(respuesta);
$("#ventaSubtotal").html('<b>$ ' + parseFloat(datos.ventaSubtotal).toFixed(2) + '</b>');
$("#ventaIVA").html('<b>$ ' + parseFloat(datos.ventaIVA).toFixed(2) + '</b>');
$("#ventaTotal").html('<b>$ ' + parseFloat(datos.ventaTotal).toFixed(2) + '</b>');
}
}
|
function escribeTotales(paramCallback,respuesta)
{
if (respuesta != 0) {
//obetenemos los datos del controlador en formato json
var datos = JSON.parse(respuesta);
$("#ventaSubtotal").html('<b>$ ' + parseFloat(datos.ventaSubtotal).toFixed(2) + '</b>');
$("#ventaIVA").html('<b>$ ' + parseFloat(datos.ventaIVA).toFixed(2) + '</b>');
$("#ventaTotal").html('<b>$ ' + parseFloat(datos.ventaTotal).toFixed(2) + '</b>');
}
}
|
JavaScript
|
function cambiaStatusVenta(ventaID,statusNuevo)
{
var ruta = baseUrl + "cambiaStatusVenta";
var modulo = baseUrl + "controlpedidos/verventa/" + ventaID;
var info = new Object();
info.ventaID = ventaID;
info.statusNuevo = statusNuevo;
ejecutaProceso(ruta,info,"",rCambiaStatusVenta,modulo);
}
|
function cambiaStatusVenta(ventaID,statusNuevo)
{
var ruta = baseUrl + "cambiaStatusVenta";
var modulo = baseUrl + "controlpedidos/verventa/" + ventaID;
var info = new Object();
info.ventaID = ventaID;
info.statusNuevo = statusNuevo;
ejecutaProceso(ruta,info,"",rCambiaStatusVenta,modulo);
}
|
JavaScript
|
function abreDetallesPartida(partidaID)
{
var ruta = baseUrl + "detallesPartidaVenta";
var info = new Object();
info.partidaID = partidaID;
ejecutaProceso(ruta,info,"",muestraDetallesPartida,"");
}
|
function abreDetallesPartida(partidaID)
{
var ruta = baseUrl + "detallesPartidaVenta";
var info = new Object();
info.partidaID = partidaID;
ejecutaProceso(ruta,info,"",muestraDetallesPartida,"");
}
|
JavaScript
|
function almacenSeleccionado(paramCallback,respuesta)
{
if (respuesta == 1) {
//recorremos la tabla de las partidas del pedido
$("#partidasPedido tbody tr").each(function(index){
var codigoBarras;
$(this).children("td").each(function(index2){
switch(index2){
case 0:
codigoBarras = $(this).text();
break;
case 4:
// == traemos la existencia del producto == //
var ruta = baseUrl + "traerExistenciaProducto";
var info = new Object();
info.almacenID = paramCallback;
info.codigoBarras = codigoBarras;
var objeto = $(this);
ejecutaProceso(ruta,info,"",escribeExistencia,objeto);
// ======================================== //
break;
}
});
});
}else{
mensajeWarning("Error","No se puede cambiar el Almacen");
}
}
|
function almacenSeleccionado(paramCallback,respuesta)
{
if (respuesta == 1) {
//recorremos la tabla de las partidas del pedido
$("#partidasPedido tbody tr").each(function(index){
var codigoBarras;
$(this).children("td").each(function(index2){
switch(index2){
case 0:
codigoBarras = $(this).text();
break;
case 4:
// == traemos la existencia del producto == //
var ruta = baseUrl + "traerExistenciaProducto";
var info = new Object();
info.almacenID = paramCallback;
info.codigoBarras = codigoBarras;
var objeto = $(this);
ejecutaProceso(ruta,info,"",escribeExistencia,objeto);
// ======================================== //
break;
}
});
});
}else{
mensajeWarning("Error","No se puede cambiar el Almacen");
}
}
|
JavaScript
|
function Favourites(props) {
//Declare variables
let initialArray = [];
let array = [];
// Only create divs/lists to display favourites if there actually are favourites in array
if (props.newFavourite.length !== 0) {
initialArray = props.newFavourite;
// For loop to store divs/lists in an array to be displayed
for (let i = 0; i <= initialArray.length - 1; i++) {
array.push(
<div className="faveDiv" key={i}>
<div className="deleteButtonDiv">
{/* Delete favourite button (red cross at top right of each favourite) */}
<button
type="button"
variant="primary"
onClick={() => props.deleteFavourite(i)}
>
</button>
</div>
<ul key={i}>
<li>Track Name: {initialArray[i].track}</li>
<li>Artist Name: {initialArray[i].artist}</li>
<li>Collection: {initialArray[i].collection}</li>
<li>Media Type: {initialArray[i].kindOfMedia}</li>
</ul>
{/* Numbering for each favourite. Number on bottom right corder of favourite box */}
<div className="faveNum">{i + 1}</div>
</div>
);
// End of for loop to add favourites divs to array
}
// If there are no favourites saved yet, display message
} else {
array = (
<p className="bluePara">No favourites yet. Why don't you choose some?</p>
);
}
return (
<div className="favourites">
<div className="faveTitle">
<h2>Favourites</h2>
<img className="starImg" src={star} alt="star" />
</div>
{/* Display favourites stored in array */}
{array}
</div>
);
}
|
function Favourites(props) {
//Declare variables
let initialArray = [];
let array = [];
// Only create divs/lists to display favourites if there actually are favourites in array
if (props.newFavourite.length !== 0) {
initialArray = props.newFavourite;
// For loop to store divs/lists in an array to be displayed
for (let i = 0; i <= initialArray.length - 1; i++) {
array.push(
<div className="faveDiv" key={i}>
<div className="deleteButtonDiv">
{/* Delete favourite button (red cross at top right of each favourite) */}
<button
type="button"
variant="primary"
onClick={() => props.deleteFavourite(i)}
>
</button>
</div>
<ul key={i}>
<li>Track Name: {initialArray[i].track}</li>
<li>Artist Name: {initialArray[i].artist}</li>
<li>Collection: {initialArray[i].collection}</li>
<li>Media Type: {initialArray[i].kindOfMedia}</li>
</ul>
{/* Numbering for each favourite. Number on bottom right corder of favourite box */}
<div className="faveNum">{i + 1}</div>
</div>
);
// End of for loop to add favourites divs to array
}
// If there are no favourites saved yet, display message
} else {
array = (
<p className="bluePara">No favourites yet. Why don't you choose some?</p>
);
}
return (
<div className="favourites">
<div className="faveTitle">
<h2>Favourites</h2>
<img className="starImg" src={star} alt="star" />
</div>
{/* Display favourites stored in array */}
{array}
</div>
);
}
|
JavaScript
|
function Header(props) {
return (
<header className="header">
<img src={logo} className="logo" alt="logo" />
<h1>iTunes</h1>
{/* Display Search Form component */}
<SearchForm
handleSubmit={props.handleSubmit}
handleChangeSearchTerm={props.handleChangeSearchTerm}
handleChangeMediaType={props.handleChangeMediaType}
/>
</header>
);
}
|
function Header(props) {
return (
<header className="header">
<img src={logo} className="logo" alt="logo" />
<h1>iTunes</h1>
{/* Display Search Form component */}
<SearchForm
handleSubmit={props.handleSubmit}
handleChangeSearchTerm={props.handleChangeSearchTerm}
handleChangeMediaType={props.handleChangeMediaType}
/>
</header>
);
}
|
JavaScript
|
function DisplayResults(props) {
return (
<div className="output">
<h2>Search Results</h2>
<p>
Search term: <b>{props.searchTerm}</b>, Media type:{" "}
<b>{props.mediaType}</b>
</p>
{props.resultsArray}
</div>
);
}
|
function DisplayResults(props) {
return (
<div className="output">
<h2>Search Results</h2>
<p>
Search term: <b>{props.searchTerm}</b>, Media type:{" "}
<b>{props.mediaType}</b>
</p>
{props.resultsArray}
</div>
);
}
|
JavaScript
|
async function createMaodouCourse(title, start_time, location, notes, createMaodouCourseCallback) {
debug('createCourse params:', {title}, {start_time}, {location}, {notes})
let path = '/courses'
let postBody = {
"title": title,
"start_time": start_time,
"location": location,
"duration": 3600,
"count": 1,
"freq": "NONE",
"alerts": [
// {
// at: -3600, //单位s
// by: 'sms',
// },
{
at: -1800,
by: 'wxmsg',
},
{
at: -900,
by: 'call',
},
],
"notes": notes
}
// call maodou api
await fetchMaodouAPI(path, postBody, createMaodouCourseCallback)
return
}
|
async function createMaodouCourse(title, start_time, location, notes, createMaodouCourseCallback) {
debug('createCourse params:', {title}, {start_time}, {location}, {notes})
let path = '/courses'
let postBody = {
"title": title,
"start_time": start_time,
"location": location,
"duration": 3600,
"count": 1,
"freq": "NONE",
"alerts": [
// {
// at: -3600, //单位s
// by: 'sms',
// },
{
at: -1800,
by: 'wxmsg',
},
{
at: -900,
by: 'call',
},
],
"notes": notes
}
// call maodou api
await fetchMaodouAPI(path, postBody, createMaodouCourseCallback)
return
}
|
JavaScript
|
async function fetchMaodouAPI(path, postBody, fetchCallback) {
let resText = null
const url = 'https://api.maodouketang.com/api/v1' + path
const options = {
method: "POST",
body: JSON.stringify(postBody), // put keywords and token in the body
// If you want to get alert by your own phone, replace with your own 'authorization'
// To get your own 'authorization', please see it in README.md
headers: {
'Content-Type': 'application/json',
'authorization': "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1ZDA5ZjcxYTQyOTg4YjAwMTI2ZmYxYmMiLCJvcGVuSWQiOiJvRHprWTBUTjlfTmNLdXZCYVo1SzhzeE1NZHNzIiwiaWF0IjoxNTYwOTM0MTcwLCJleHAiOjE1NjYxMTgxNzB9.-NtfK62Y1S_EHAkA2Y0j5BW4qtb7IdH2mpq85NUqPuA"
}
}
debug('fetchMaodouAPI: ', {url}, {options})
try {
let resp = await fetch( url, options )
let resp_json = await resp.json()
if (resp.ok) {
// status code = 200, we got it!
debug('[resp_json.data]', resp_json['data'])
resText = fetchCallback(resp_json['data'])
} else {
// status code = 4XX/5XX, sth wrong with API
debug('[resp_json.msg]', resp_json['msg'])
resText = 'API ERROR: ' + resp_json['msg']
}
} catch (err) {
debug('[err]', err)
resText = 'NETWORK ERROR: ' + err
}
return resText
}
|
async function fetchMaodouAPI(path, postBody, fetchCallback) {
let resText = null
const url = 'https://api.maodouketang.com/api/v1' + path
const options = {
method: "POST",
body: JSON.stringify(postBody), // put keywords and token in the body
// If you want to get alert by your own phone, replace with your own 'authorization'
// To get your own 'authorization', please see it in README.md
headers: {
'Content-Type': 'application/json',
'authorization': "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1ZDA5ZjcxYTQyOTg4YjAwMTI2ZmYxYmMiLCJvcGVuSWQiOiJvRHprWTBUTjlfTmNLdXZCYVo1SzhzeE1NZHNzIiwiaWF0IjoxNTYwOTM0MTcwLCJleHAiOjE1NjYxMTgxNzB9.-NtfK62Y1S_EHAkA2Y0j5BW4qtb7IdH2mpq85NUqPuA"
}
}
debug('fetchMaodouAPI: ', {url}, {options})
try {
let resp = await fetch( url, options )
let resp_json = await resp.json()
if (resp.ok) {
// status code = 200, we got it!
debug('[resp_json.data]', resp_json['data'])
resText = fetchCallback(resp_json['data'])
} else {
// status code = 4XX/5XX, sth wrong with API
debug('[resp_json.msg]', resp_json['msg'])
resText = 'API ERROR: ' + resp_json['msg']
}
} catch (err) {
debug('[err]', err)
resText = 'NETWORK ERROR: ' + err
}
return resText
}
|
JavaScript
|
async function onMessage (message) {
/**
* We can get the Wechaty bot instance from this:
* `const wechaty = this`
* Or use `this` directly:
* `console.info(this.userSelf())`
*/
console.log(`Received message: ${message}`)
}
|
async function onMessage (message) {
/**
* We can get the Wechaty bot instance from this:
* `const wechaty = this`
* Or use `this` directly:
* `console.info(this.userSelf())`
*/
console.log(`Received message: ${message}`)
}
|
JavaScript
|
async function onFriend (contact, request) {
/**
* We can get the Wechaty bot instance from this:
* `const wechaty = this`
* Or use `this` directly:
* `console.info(this.userSelf())`
*/
if(request){
let name = contact.name()
// await request.accept()
console.log(`Contact: ${name} send request ${request.hello()}`)
}
}
|
async function onFriend (contact, request) {
/**
* We can get the Wechaty bot instance from this:
* `const wechaty = this`
* Or use `this` directly:
* `console.info(this.userSelf())`
*/
if(request){
let name = contact.name()
// await request.accept()
console.log(`Contact: ${name} send request ${request.hello()}`)
}
}
|
JavaScript
|
async function onLogin (user) {
/**
* We can get the Wechaty bot instance from this:
* `const wechaty = this`
* Or use `this` directly:
* `console.info(this.userSelf())`
*/
console.log(`${user} login`)
}
|
async function onLogin (user) {
/**
* We can get the Wechaty bot instance from this:
* `const wechaty = this`
* Or use `this` directly:
* `console.info(this.userSelf())`
*/
console.log(`${user} login`)
}
|
JavaScript
|
function create_table() {
var emotes_name = Object.keys(emotes);
var emotes_list = [];
var emotes_group_list = [];
var len = emotes_name.length;
for (var i = 0; i < len; i++) {
emotes_list.push('<td>' +
'<img src="' + emotes[emotes_name[i]] + '" title="' + emotes_name[i] + '">' +
emotes_name[i] + '</td>');
}
var emotes_list_right = emotes_list.splice(len / 2, len / 2);
for (i = 0; i < len / 2; i++) {
var emote1 = emotes_list[i],
emote2 = emotes_list_right[i];
if (emote2) {
emotes_group_list.push('<tr>' + emote1 + emote2 + '</tr>');
} else {
emotes_group_list.push('<tr>' + emote1 + '</tr>');
}
}
return '<center><b><u>List of Emoticons</u></b></center>' + '<table border="1" cellspacing="0" cellpadding="5" width="100%">' + '<tbody>' + emotes_group_list.join('') + '</tbody>' + '</table>';
}
|
function create_table() {
var emotes_name = Object.keys(emotes);
var emotes_list = [];
var emotes_group_list = [];
var len = emotes_name.length;
for (var i = 0; i < len; i++) {
emotes_list.push('<td>' +
'<img src="' + emotes[emotes_name[i]] + '" title="' + emotes_name[i] + '">' +
emotes_name[i] + '</td>');
}
var emotes_list_right = emotes_list.splice(len / 2, len / 2);
for (i = 0; i < len / 2; i++) {
var emote1 = emotes_list[i],
emote2 = emotes_list_right[i];
if (emote2) {
emotes_group_list.push('<tr>' + emote1 + emote2 + '</tr>');
} else {
emotes_group_list.push('<tr>' + emote1 + '</tr>');
}
}
return '<center><b><u>List of Emoticons</u></b></center>' + '<table border="1" cellspacing="0" cellpadding="5" width="100%">' + '<tbody>' + emotes_group_list.join('') + '</tbody>' + '</table>';
}
|
JavaScript
|
function canTalk(user, room, connection, message) {
if (!user.named) {
connection.popup("You must choose a name before you can talk.");
return false;
}
if (room && user.locked) {
connection.sendTo(room, "You are locked from talking in chat.");
return false;
}
if (room && user.mutedRooms[room.id]) {
connection.sendTo(room, "You are muted and cannot talk in this room.");
return false;
}
if (room && room.modchat) {
if (room.modchat === 'crash') {
if (!user.can('ignorelimits')) {
connection.sendTo(room, "Because the server has crashed, you cannot speak in lobby chat.");
return false;
}
} else {
var userGroup = user.group;
if (room.auth) {
if (room.auth[user.userid]) {
userGroup = room.auth[user.userid];
} else if (room.isPrivate === true) {
userGroup = ' ';
}
}
if (!user.autoconfirmed && (room.auth && room.auth[user.userid] || user.group) === ' ' && room.modchat === 'autoconfirmed') {
connection.sendTo(room, "Because moderated chat is set, your account must be at least one week old and you must have won at least one ladder game to speak in this room.");
return false;
} else if (Config.groupsranking.indexOf(userGroup) < Config.groupsranking.indexOf(room.modchat)) {
var groupName = Config.groups[room.modchat].name || room.modchat;
connection.sendTo(room, "Because moderated chat is set, you must be of rank " + groupName + " or higher to speak in this room.");
return false;
}
}
}
if (room && !(user.userid in room.users)) {
connection.popup("You can't send a message to this room without being in it.");
return false;
}
if (typeof message === 'string') {
if (!message) {
connection.popup("Your message can't be blank.");
return false;
}
if (message.length > MAX_MESSAGE_LENGTH && !user.can('ignorelimits')) {
connection.popup("Your message is too long:\n\n" + message);
return false;
}
// remove zalgo
message = message.replace(/[\u0300-\u036f\u0483-\u0489\u064b-\u065f\u0670\u0E31\u0E34-\u0E3A\u0E47-\u0E4E]{3,}/g, '');
if (room && room.id === 'lobby') {
var normalized = message.trim();
if ((normalized === user.lastMessage) &&
((Date.now() - user.lastMessageTime) < MESSAGE_COOLDOWN)) {
connection.popup("You can't send the same message again so soon.");
return false;
}
user.lastMessage = message;
user.lastMessageTime = Date.now();
}
if (Config.chatfilter) {
return Config.chatfilter(message, user, room, connection);
}
return message;
}
return true;
}
|
function canTalk(user, room, connection, message) {
if (!user.named) {
connection.popup("You must choose a name before you can talk.");
return false;
}
if (room && user.locked) {
connection.sendTo(room, "You are locked from talking in chat.");
return false;
}
if (room && user.mutedRooms[room.id]) {
connection.sendTo(room, "You are muted and cannot talk in this room.");
return false;
}
if (room && room.modchat) {
if (room.modchat === 'crash') {
if (!user.can('ignorelimits')) {
connection.sendTo(room, "Because the server has crashed, you cannot speak in lobby chat.");
return false;
}
} else {
var userGroup = user.group;
if (room.auth) {
if (room.auth[user.userid]) {
userGroup = room.auth[user.userid];
} else if (room.isPrivate === true) {
userGroup = ' ';
}
}
if (!user.autoconfirmed && (room.auth && room.auth[user.userid] || user.group) === ' ' && room.modchat === 'autoconfirmed') {
connection.sendTo(room, "Because moderated chat is set, your account must be at least one week old and you must have won at least one ladder game to speak in this room.");
return false;
} else if (Config.groupsranking.indexOf(userGroup) < Config.groupsranking.indexOf(room.modchat)) {
var groupName = Config.groups[room.modchat].name || room.modchat;
connection.sendTo(room, "Because moderated chat is set, you must be of rank " + groupName + " or higher to speak in this room.");
return false;
}
}
}
if (room && !(user.userid in room.users)) {
connection.popup("You can't send a message to this room without being in it.");
return false;
}
if (typeof message === 'string') {
if (!message) {
connection.popup("Your message can't be blank.");
return false;
}
if (message.length > MAX_MESSAGE_LENGTH && !user.can('ignorelimits')) {
connection.popup("Your message is too long:\n\n" + message);
return false;
}
// remove zalgo
message = message.replace(/[\u0300-\u036f\u0483-\u0489\u064b-\u065f\u0670\u0E31\u0E34-\u0E3A\u0E47-\u0E4E]{3,}/g, '');
if (room && room.id === 'lobby') {
var normalized = message.trim();
if ((normalized === user.lastMessage) &&
((Date.now() - user.lastMessageTime) < MESSAGE_COOLDOWN)) {
connection.popup("You can't send the same message again so soon.");
return false;
}
user.lastMessage = message;
user.lastMessageTime = Date.now();
}
if (Config.chatfilter) {
return Config.chatfilter(message, user, room, connection);
}
return message;
}
return true;
}
|
JavaScript
|
function localStorageIsAvailable () {
try {
let storage = window.localStorage
let x = '__storage_test__'
storage.setItem(x, x)
storage.removeItem(x)
return true
} catch (error) {
return error instanceof DOMException && (
// everything except Firefox
error.code === 22 ||
// Firefox
error.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
error.name === 'QuotaExceededError' ||
// Firefox
error.name === 'NS_ERROR_DOM_QUOTA_REACHED')
}
}
|
function localStorageIsAvailable () {
try {
let storage = window.localStorage
let x = '__storage_test__'
storage.setItem(x, x)
storage.removeItem(x)
return true
} catch (error) {
return error instanceof DOMException && (
// everything except Firefox
error.code === 22 ||
// Firefox
error.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
error.name === 'QuotaExceededError' ||
// Firefox
error.name === 'NS_ERROR_DOM_QUOTA_REACHED')
}
}
|
JavaScript
|
function simplifyString(s) {
let output = '';
let previousWhite = false;
for (let i = 0; i < s.length; i++) {
let c = s[i];
let isWhite = isWhiteSpace(c);
if (previousWhite && isWhite) {
// skip
} else {
output += c;
}
previousWhite = isWhite;
}
while (output.length && isWhiteSpace(output[0])) output = output.substr(1);
while (output.length && isWhiteSpace(output[output.length - 1])) output = output.substr(0, output.length - 1);
return output;
}
|
function simplifyString(s) {
let output = '';
let previousWhite = false;
for (let i = 0; i < s.length; i++) {
let c = s[i];
let isWhite = isWhiteSpace(c);
if (previousWhite && isWhite) {
// skip
} else {
output += c;
}
previousWhite = isWhite;
}
while (output.length && isWhiteSpace(output[0])) output = output.substr(1);
while (output.length && isWhiteSpace(output[output.length - 1])) output = output.substr(0, output.length - 1);
return output;
}
|
JavaScript
|
function drawTable(table) {
// | First Header | Second Header |
// | ------------- | ------------- |
// | Content Cell | Content Cell |
// | Content Cell | Content Cell |
// There must be at least 3 dashes separating each header cell.
// https://gist.github.com/IanWang/28965e13cdafdef4e11dc91f578d160d#tables
const flatRender = tableHasSubTables(table); // Render the table has regular text
const minColWidth = 3;
let lines = [];
lines.push(BLOCK_OPEN);
let headerDone = false;
for (let trIndex = 0; trIndex < table.lines.length; trIndex++) {
const tr = table.lines[trIndex];
const isHeader = tr.isHeader;
let line = [];
let headerLine = [];
let emptyHeader = null;
for (let tdIndex = 0; tdIndex < tr.lines.length; tdIndex++) {
const td = tr.lines[tdIndex];
if (flatRender) {
line.push(BLOCK_OPEN);
let currentCells = [];
const renderCurrentCells = () => {
if (!currentCells.length) return;
const cellText = processMdArrayNewLines(currentCells);
line.push(cellText);
currentCells = [];
}
// In here, recursively render the tables
for (let i = 0; i < td.lines.length; i++) {
const c = td.lines[i];
if (typeof c === 'object') { // This is a table
renderCurrentCells();
currentCells = currentCells.concat(drawTable(c));
} else { // This is plain text
currentCells.push(c);
}
}
renderCurrentCells();
line.push(BLOCK_CLOSE);
} else { // Regular table rendering
// A cell in a Markdown table cannot have new lines so remove them
const cellText = removeTableCellNewLines(processMdArrayNewLines(td.lines));
const width = Math.max(cellText.length, 3);
line.push(stringPadding(cellText, width, ' ', stringPadding.RIGHT));
if (!headerDone) {
if (!isHeader) {
if (!emptyHeader) emptyHeader = [];
let h = stringPadding(' ', width, ' ', stringPadding.RIGHT);
emptyHeader.push(h);
}
headerLine.push('-'.repeat(width));
}
}
}
if (flatRender) {
headerDone = true;
lines.push(BLOCK_OPEN);
lines = lines.concat(line);
lines.push(BLOCK_CLOSE);
} else {
if (emptyHeader) {
lines.push('| ' + emptyHeader.join(' | ') + ' |');
lines.push('| ' + headerLine.join(' | ') + ' |');
headerDone = true;
}
lines.push('| ' + line.join(' | ') + ' |');
if (!headerDone) {
lines.push('| ' + headerLine.join(' | ') + ' |');
headerDone = true;
}
}
}
lines.push(BLOCK_CLOSE);
return flatRender ? lines : lines.join('<<<<:D>>>>' + NEWLINE + '<<<<:D>>>>').split('<<<<:D>>>>');
}
|
function drawTable(table) {
// | First Header | Second Header |
// | ------------- | ------------- |
// | Content Cell | Content Cell |
// | Content Cell | Content Cell |
// There must be at least 3 dashes separating each header cell.
// https://gist.github.com/IanWang/28965e13cdafdef4e11dc91f578d160d#tables
const flatRender = tableHasSubTables(table); // Render the table has regular text
const minColWidth = 3;
let lines = [];
lines.push(BLOCK_OPEN);
let headerDone = false;
for (let trIndex = 0; trIndex < table.lines.length; trIndex++) {
const tr = table.lines[trIndex];
const isHeader = tr.isHeader;
let line = [];
let headerLine = [];
let emptyHeader = null;
for (let tdIndex = 0; tdIndex < tr.lines.length; tdIndex++) {
const td = tr.lines[tdIndex];
if (flatRender) {
line.push(BLOCK_OPEN);
let currentCells = [];
const renderCurrentCells = () => {
if (!currentCells.length) return;
const cellText = processMdArrayNewLines(currentCells);
line.push(cellText);
currentCells = [];
}
// In here, recursively render the tables
for (let i = 0; i < td.lines.length; i++) {
const c = td.lines[i];
if (typeof c === 'object') { // This is a table
renderCurrentCells();
currentCells = currentCells.concat(drawTable(c));
} else { // This is plain text
currentCells.push(c);
}
}
renderCurrentCells();
line.push(BLOCK_CLOSE);
} else { // Regular table rendering
// A cell in a Markdown table cannot have new lines so remove them
const cellText = removeTableCellNewLines(processMdArrayNewLines(td.lines));
const width = Math.max(cellText.length, 3);
line.push(stringPadding(cellText, width, ' ', stringPadding.RIGHT));
if (!headerDone) {
if (!isHeader) {
if (!emptyHeader) emptyHeader = [];
let h = stringPadding(' ', width, ' ', stringPadding.RIGHT);
emptyHeader.push(h);
}
headerLine.push('-'.repeat(width));
}
}
}
if (flatRender) {
headerDone = true;
lines.push(BLOCK_OPEN);
lines = lines.concat(line);
lines.push(BLOCK_CLOSE);
} else {
if (emptyHeader) {
lines.push('| ' + emptyHeader.join(' | ') + ' |');
lines.push('| ' + headerLine.join(' | ') + ' |');
headerDone = true;
}
lines.push('| ' + line.join(' | ') + ' |');
if (!headerDone) {
lines.push('| ' + headerLine.join(' | ') + ' |');
headerDone = true;
}
}
}
lines.push(BLOCK_CLOSE);
return flatRender ? lines : lines.join('<<<<:D>>>>' + NEWLINE + '<<<<:D>>>>').split('<<<<:D>>>>');
}
|
JavaScript
|
function fetchRequestCanBeRetried(error) {
if (!error) return false;
// Unfortunately the error 'Network request failed' doesn't have a type
// or error code, so hopefully that message won't change and is not localized
if (error.message == 'Network request failed') return true;
// request to https://public-ch3302....1fab24cb1bd5f.md failed, reason: socket hang up"
if (error.code == 'ECONNRESET') return true;
// OneDrive (or Node?) sometimes sends back a "not found" error for resources
// that definitely exist and in this case repeating the request works.
// Error is:
// request to https://graph.microsoft.com/v1.0/drive/special/approot failed, reason: getaddrinfo ENOTFOUND graph.microsoft.com graph.microsoft.com:443
if (error.code == 'ENOTFOUND') return true;
// network timeout at: https://public-ch3302...859f9b0e3ab.md
if (error.message && error.message.indexOf('network timeout') === 0) return true;
// name: 'FetchError',
// message: 'request to https://api.ipify.org/?format=json failed, reason: getaddrinfo EAI_AGAIN api.ipify.org:443',
// type: 'system',
// errno: 'EAI_AGAIN',
// code: 'EAI_AGAIN' } } reason: { FetchError: request to https://api.ipify.org/?format=json failed, reason: getaddrinfo EAI_AGAIN api.ipify.org:443
//
// It's a Microsoft error: "A temporary failure in name resolution occurred."
if (error.code == 'EAI_AGAIN') return true;
// request to https://public-...8fd8bc6bb68e9c4d17a.md failed, reason: connect ETIMEDOUT 204.79.197.213:443
// Code: ETIMEDOUT
if (error.code === 'ETIMEDOUT') return true;
return false;
}
|
function fetchRequestCanBeRetried(error) {
if (!error) return false;
// Unfortunately the error 'Network request failed' doesn't have a type
// or error code, so hopefully that message won't change and is not localized
if (error.message == 'Network request failed') return true;
// request to https://public-ch3302....1fab24cb1bd5f.md failed, reason: socket hang up"
if (error.code == 'ECONNRESET') return true;
// OneDrive (or Node?) sometimes sends back a "not found" error for resources
// that definitely exist and in this case repeating the request works.
// Error is:
// request to https://graph.microsoft.com/v1.0/drive/special/approot failed, reason: getaddrinfo ENOTFOUND graph.microsoft.com graph.microsoft.com:443
if (error.code == 'ENOTFOUND') return true;
// network timeout at: https://public-ch3302...859f9b0e3ab.md
if (error.message && error.message.indexOf('network timeout') === 0) return true;
// name: 'FetchError',
// message: 'request to https://api.ipify.org/?format=json failed, reason: getaddrinfo EAI_AGAIN api.ipify.org:443',
// type: 'system',
// errno: 'EAI_AGAIN',
// code: 'EAI_AGAIN' } } reason: { FetchError: request to https://api.ipify.org/?format=json failed, reason: getaddrinfo EAI_AGAIN api.ipify.org:443
//
// It's a Microsoft error: "A temporary failure in name resolution occurred."
if (error.code == 'EAI_AGAIN') return true;
// request to https://public-...8fd8bc6bb68e9c4d17a.md failed, reason: connect ETIMEDOUT 204.79.197.213:443
// Code: ETIMEDOUT
if (error.code === 'ETIMEDOUT') return true;
return false;
}
|
JavaScript
|
static object(key) {
let output = {};
let keys = this.keys();
for (let i = 0; i < keys.length; i++) {
let k = keys[i].split('.');
if (k[0] == key) {
output[k[1]] = this.value(keys[i]);
}
}
return output;
}
|
static object(key) {
let output = {};
let keys = this.keys();
for (let i = 0; i < keys.length; i++) {
let k = keys[i].split('.');
if (k[0] == key) {
output[k[1]] = this.value(keys[i]);
}
}
return output;
}
|
JavaScript
|
static async untagAll(tagId) {
const noteTags = await NoteTag.modelSelectAll('SELECT id FROM note_tags WHERE tag_id = ?', [tagId]);
for (let i = 0; i < noteTags.length; i++) {
await NoteTag.delete(noteTags[i].id);
}
await Tag.delete(tagId);
}
|
static async untagAll(tagId) {
const noteTags = await NoteTag.modelSelectAll('SELECT id FROM note_tags WHERE tag_id = ?', [tagId]);
for (let i = 0; i < noteTags.length; i++) {
await NoteTag.delete(noteTags[i].id);
}
await Tag.delete(tagId);
}
|
JavaScript
|
list(path = '', options = null) {
if (!options) options = {};
if (!('includeHidden' in options)) options.includeHidden = false;
if (!('context' in options)) options.context = null;
this.logger().debug('list ' + this.baseDir_);
return this.driver_.list(this.baseDir_, options).then((result) => {
if (!options.includeHidden) {
let temp = [];
for (let i = 0; i < result.items.length; i++) {
if (!isHidden(result.items[i].path)) temp.push(result.items[i]);
}
result.items = temp;
}
return result;
});
}
|
list(path = '', options = null) {
if (!options) options = {};
if (!('includeHidden' in options)) options.includeHidden = false;
if (!('context' in options)) options.context = null;
this.logger().debug('list ' + this.baseDir_);
return this.driver_.list(this.baseDir_, options).then((result) => {
if (!options.includeHidden) {
let temp = [];
for (let i = 0; i < result.items.length; i++) {
if (!isHidden(result.items[i].path)) temp.push(result.items[i]);
}
result.items = temp;
}
return result;
});
}
|
JavaScript
|
static async save(o, options = null) {
if (!options) options = {};
if (options.userSideValidation === true) {
if (!('duplicateCheck' in options)) options.duplicateCheck = true;
if (!('reservedTitleCheck' in options)) options.reservedTitleCheck = true;
if (!('stripLeftSlashes' in options)) options.stripLeftSlashes = true;
}
if (options.stripLeftSlashes === true && o.title) {
while (o.title.length && (o.title[0] == '/' || o.title[0] == "\\")) {
o.title = o.title.substr(1);
}
}
if (options.duplicateCheck === true && o.title) {
let existingFolder = await Folder.loadByTitle(o.title);
if (existingFolder && existingFolder.id != o.id) throw new Error(_('A notebook with this title already exists: "%s"', o.title));
}
if (options.reservedTitleCheck === true && o.title) {
if (o.title == Folder.conflictFolderTitle()) throw new Error(_('Notebooks cannot be named "%s", which is a reserved title.', o.title));
}
return super.save(o, options).then((folder) => {
this.dispatch({
type: 'FOLDER_UPDATE_ONE',
folder: folder,
});
return folder;
});
}
|
static async save(o, options = null) {
if (!options) options = {};
if (options.userSideValidation === true) {
if (!('duplicateCheck' in options)) options.duplicateCheck = true;
if (!('reservedTitleCheck' in options)) options.reservedTitleCheck = true;
if (!('stripLeftSlashes' in options)) options.stripLeftSlashes = true;
}
if (options.stripLeftSlashes === true && o.title) {
while (o.title.length && (o.title[0] == '/' || o.title[0] == "\\")) {
o.title = o.title.substr(1);
}
}
if (options.duplicateCheck === true && o.title) {
let existingFolder = await Folder.loadByTitle(o.title);
if (existingFolder && existingFolder.id != o.id) throw new Error(_('A notebook with this title already exists: "%s"', o.title));
}
if (options.reservedTitleCheck === true && o.title) {
if (o.title == Folder.conflictFolderTitle()) throw new Error(_('Notebooks cannot be named "%s", which is a reserved title.', o.title));
}
return super.save(o, options).then((folder) => {
this.dispatch({
type: 'FOLDER_UPDATE_ONE',
folder: folder,
});
return folder;
});
}
|
JavaScript
|
static mustHandleConflict(localNote, remoteNote) {
// That shouldn't happen so throw an exception
if (localNote.id !== remoteNote.id) throw new Error('Cannot handle conflict for two different notes');
if (localNote.title !== remoteNote.title) return true;
if (localNote.body !== remoteNote.body) return true;
return false;
}
|
static mustHandleConflict(localNote, remoteNote) {
// That shouldn't happen so throw an exception
if (localNote.id !== remoteNote.id) throw new Error('Cannot handle conflict for two different notes');
if (localNote.title !== remoteNote.title) return true;
if (localNote.body !== remoteNote.body) return true;
return false;
}
|
JavaScript
|
function init () {
startup();
globals();
program.run();
}
|
function init () {
startup();
globals();
program.run();
}
|
JavaScript
|
async send(message) {
let self = this;
let sender = new Promise((resolve) =>
{
setTimeout(() =>
{
resolve(self.validate(message));
}, self.configuration.delay)
});
try {
let message = await sender;
return message;
} catch (error) {
console.log(error);
}
}
|
async send(message) {
let self = this;
let sender = new Promise((resolve) =>
{
setTimeout(() =>
{
resolve(self.validate(message));
}, self.configuration.delay)
});
try {
let message = await sender;
return message;
} catch (error) {
console.log(error);
}
}
|
JavaScript
|
async execute(azcontext) {
try {
await this.bootstrap(azcontext);
if((typeof this._context !== "undefined") && this._context != null) {
await this.initialize(this._context);
this._context.subject = await this.authenticate(this._context);
await this.authorize(this._context);
await this.validate(this._context);
await this.load(this._context);
if (this._context.isMonitorInvocation)
await this.monitor(this._context);
else
await this.process(this._context);
await this.save(this._context);
}
else {
azcontext.log.error("[" + azcontext.bindingData.invocationId + "][BaseFunction.execute(azcontext)]: Catostrophic Error! Context was null after bootstrap, skipping all other life-cycles.");
throw CelastrinaError.newError("Catostrophic Error! Context null.");
}
}
catch(exception) {
try {
if((typeof this._context !== "undefined") && this._context != null)
await this.exception(this._context, exception);
else
azcontext.log.error("[" + azcontext.bindingData.invocationId + "][BaseFunction.execute(azcontext)]: Catostrophic Error! Context was null, skipping exception life-cycle.");
}
catch(_exception) {
let _ex = this._unhandled(azcontext, _exception);
azcontext.log.error("[" + azcontext.bindingData.invocationId + "][BaseFunction.execute(azcontext)]: Exception thrown from Exception life-cycle: " +
_ex + ", caused by " + exception + ". ");
}
}
finally {
try {
if((typeof this._context !== "undefined") && this._context != null) {
await this.terminate(this._context);
if (this._context.result == null)
azcontext.done();
else
azcontext.done(this._context.result);
}
else {
azcontext.log.error("[" + azcontext.bindingData.invocationId + "][BaseFunction.execute(azcontext)]: Catostrophic Error! Context was null, skipping terminate life-cycle.");
throw CelastrinaError.newError("Catostrophic Error! Context null.");
}
}
catch(exception) {
let _ex = this._unhandled(azcontext, exception);
azcontext.log.error("[" + azcontext.bindingData.invocationId + "][BaseFunction.execute(azcontext)]: Exception thrown from Terminate life-cycle: " +
_ex);
azcontext.res.status = _ex.code;
azcontext.done(_ex);
}
}
}
|
async execute(azcontext) {
try {
await this.bootstrap(azcontext);
if((typeof this._context !== "undefined") && this._context != null) {
await this.initialize(this._context);
this._context.subject = await this.authenticate(this._context);
await this.authorize(this._context);
await this.validate(this._context);
await this.load(this._context);
if (this._context.isMonitorInvocation)
await this.monitor(this._context);
else
await this.process(this._context);
await this.save(this._context);
}
else {
azcontext.log.error("[" + azcontext.bindingData.invocationId + "][BaseFunction.execute(azcontext)]: Catostrophic Error! Context was null after bootstrap, skipping all other life-cycles.");
throw CelastrinaError.newError("Catostrophic Error! Context null.");
}
}
catch(exception) {
try {
if((typeof this._context !== "undefined") && this._context != null)
await this.exception(this._context, exception);
else
azcontext.log.error("[" + azcontext.bindingData.invocationId + "][BaseFunction.execute(azcontext)]: Catostrophic Error! Context was null, skipping exception life-cycle.");
}
catch(_exception) {
let _ex = this._unhandled(azcontext, _exception);
azcontext.log.error("[" + azcontext.bindingData.invocationId + "][BaseFunction.execute(azcontext)]: Exception thrown from Exception life-cycle: " +
_ex + ", caused by " + exception + ". ");
}
}
finally {
try {
if((typeof this._context !== "undefined") && this._context != null) {
await this.terminate(this._context);
if (this._context.result == null)
azcontext.done();
else
azcontext.done(this._context.result);
}
else {
azcontext.log.error("[" + azcontext.bindingData.invocationId + "][BaseFunction.execute(azcontext)]: Catostrophic Error! Context was null, skipping terminate life-cycle.");
throw CelastrinaError.newError("Catostrophic Error! Context null.");
}
}
catch(exception) {
let _ex = this._unhandled(azcontext, exception);
azcontext.log.error("[" + azcontext.bindingData.invocationId + "][BaseFunction.execute(azcontext)]: Exception thrown from Terminate life-cycle: " +
_ex);
azcontext.res.status = _ex.code;
azcontext.done(_ex);
}
}
}
|
JavaScript
|
function sumarNumeros(numeroInicial) {
var numerosASumar = [];
for (var _i = 1; _i < arguments.length; _i++) {
numerosASumar[_i - 1] = arguments[_i];
}
return numeroInicial;
}
|
function sumarNumeros(numeroInicial) {
var numerosASumar = [];
for (var _i = 1; _i < arguments.length; _i++) {
numerosASumar[_i - 1] = arguments[_i];
}
return numeroInicial;
}
|
JavaScript
|
async function ejercicio() {
console.log('1');
try{
console.log('2');
const contenidoArchivoActual = await promesaLeerArchivo();
console.log(contenidoArchivoActual)
console.log('3');
await promesaEscribirArchivo();
console.log('4');
const nuevoContenido = await promesaLeerArchivo();
console.log(nuevoContenido);
console.log('5');
}catch (error) {
console.error(error);
}
console.log('6');
console.log('7');
}
|
async function ejercicio() {
console.log('1');
try{
console.log('2');
const contenidoArchivoActual = await promesaLeerArchivo();
console.log(contenidoArchivoActual)
console.log('3');
await promesaEscribirArchivo();
console.log('4');
const nuevoContenido = await promesaLeerArchivo();
console.log(nuevoContenido);
console.log('5');
}catch (error) {
console.error(error);
}
console.log('6');
console.log('7');
}
|
JavaScript
|
function Log(props) {
return(
<List component = "nav">
<ListItem>
<Typography component = "div">
{props.messages.map((item, index) => (
<Message key = {index} user = {item.user} text = {item.text}/>
))}
</Typography>
</ListItem>
</List>
)
}
|
function Log(props) {
return(
<List component = "nav">
<ListItem>
<Typography component = "div">
{props.messages.map((item, index) => (
<Message key = {index} user = {item.user} text = {item.text}/>
))}
</Typography>
</ListItem>
</List>
)
}
|
JavaScript
|
function Message(props) {
return(
<div>
{ props.user } : { props.text }
</div>
);
}
|
function Message(props) {
return(
<div>
{ props.user } : { props.text }
</div>
);
}
|
JavaScript
|
function addToAPIObject(
routes,
model,
{ operation, path, type, params, object }
) {
let name = model.toLowerCase();
if (!routes[name]) routes[name] = [];
let result = operation + ": (";
if (params) result += params.join(", ");
if (params && object) result += ", ";
if (object) result += object.join(", ");
result += ") => axios." + type + '("' + path + '"';
if (params) result += ", " + params.join(", ");
if (object) result += ", " + object.join(", ");
result += ")";
routes[name].push(result);
return routes;
}
|
function addToAPIObject(
routes,
model,
{ operation, path, type, params, object }
) {
let name = model.toLowerCase();
if (!routes[name]) routes[name] = [];
let result = operation + ": (";
if (params) result += params.join(", ");
if (params && object) result += ", ";
if (object) result += object.join(", ");
result += ") => axios." + type + '("' + path + '"';
if (params) result += ", " + params.join(", ");
if (object) result += ", " + object.join(", ");
result += ")";
routes[name].push(result);
return routes;
}
|
JavaScript
|
function activateNavbarState() {
var container = $( "#container" );
// Bind listener to left toggle action
$( "#toggle-left" ).bind( "click", function( e ) {
// Verify window size, do not store if in mobile mode
if ( $( window ).width() > 768 ) {
// Are we opened or closed?
sidemenuCollapse = ( container.hasClass( "sidebar-mini" ) ? "no" : "yes" );
// Call change user editor preference
$.ajax( {
url : $( "body" ).attr( "data-preferenceURL" ),
data : { value: sidemenuCollapse, preference: "sidemenuCollapse" },
async : true
} );
}
} );
}
|
function activateNavbarState() {
var container = $( "#container" );
// Bind listener to left toggle action
$( "#toggle-left" ).bind( "click", function( e ) {
// Verify window size, do not store if in mobile mode
if ( $( window ).width() > 768 ) {
// Are we opened or closed?
sidemenuCollapse = ( container.hasClass( "sidebar-mini" ) ? "no" : "yes" );
// Call change user editor preference
$.ajax( {
url : $( "body" ).attr( "data-preferenceURL" ),
data : { value: sidemenuCollapse, preference: "sidemenuCollapse" },
async : true
} );
}
} );
}
|
JavaScript
|
function toggleSidebar() {
var sidebar = $( "#main-content-sidebar" );
var type = sidebar.css( "display" );
var sidebarState = false;
// nosidebar exit
if ( type === undefined ) { return; }
// toggles
if ( type === "block" ) {
sidebar.fadeOut();
$( "#main-content-sidebar-trigger i" )
.removeClass( "fa-minus-square" )
.addClass( "fa-plus-square" );
$( "#main-content-slot" )
.removeClass( "col-md-8" )
.addClass( "col-md-12" );
} else {
$( "#main-content-sidebar-trigger i" )
.removeClass( "fa-plus-square" )
.addClass( "fa-minus-square" );
sidebar.fadeIn();
$( "#main-content-slot" )
.removeClass( "col-md-12" )
.addClass( "col-md-8" );
sidebarState = true;
}
// Call change user editor preference
$.ajax( {
url : $( "body" ).attr( "data-preferenceURL" ),
data : { value: sidebarState, preference: "sidebarstate" },
async : true
} );
}
|
function toggleSidebar() {
var sidebar = $( "#main-content-sidebar" );
var type = sidebar.css( "display" );
var sidebarState = false;
// nosidebar exit
if ( type === undefined ) { return; }
// toggles
if ( type === "block" ) {
sidebar.fadeOut();
$( "#main-content-sidebar-trigger i" )
.removeClass( "fa-minus-square" )
.addClass( "fa-plus-square" );
$( "#main-content-slot" )
.removeClass( "col-md-8" )
.addClass( "col-md-12" );
} else {
$( "#main-content-sidebar-trigger i" )
.removeClass( "fa-plus-square" )
.addClass( "fa-minus-square" );
sidebar.fadeIn();
$( "#main-content-slot" )
.removeClass( "col-md-12" )
.addClass( "col-md-8" );
sidebarState = true;
}
// Call change user editor preference
$.ajax( {
url : $( "body" ).attr( "data-preferenceURL" ),
data : { value: sidebarState, preference: "sidebarstate" },
async : true
} );
}
|
JavaScript
|
function adminAction( action, actionURL ) {
if ( action != "null" ) {
$( "#adminActionsIcon" ).addClass( "fa-spin textOrange" );
// Run Action Dispatch
$.post( actionURL, { targetModule: action }, function( data ) {
if ( data.ERROR ) {
adminNotifier( "error", "<i class='fa-exclamation-sign'></i> <strong>Error running action, check logs!</strong>" );
} else {
adminNotifier( "info", "<i class='fa-exclamation-sign'></i> <strong>Action Ran, Booya!</strong>" );
}
$( "#adminActionsIcon" ).removeClass( "fa-spin textOrange" );
} );
}
}
|
function adminAction( action, actionURL ) {
if ( action != "null" ) {
$( "#adminActionsIcon" ).addClass( "fa-spin textOrange" );
// Run Action Dispatch
$.post( actionURL, { targetModule: action }, function( data ) {
if ( data.ERROR ) {
adminNotifier( "error", "<i class='fa-exclamation-sign'></i> <strong>Error running action, check logs!</strong>" );
} else {
adminNotifier( "info", "<i class='fa-exclamation-sign'></i> <strong>Action Ran, Booya!</strong>" );
}
$( "#adminActionsIcon" ).removeClass( "fa-spin textOrange" );
} );
}
}
|
JavaScript
|
function adminNotifier( type, message, delay ) {
toastr.options = {
"closeButton" : true,
"preventDuplicates" : true,
"progressBar" : true,
"showDuration" : "300",
"timeOut" : "2000",
"positionClass" : "toast-top-center"
};
switch ( type ) {
case "info":
{ toastr.info( message ); break; }
case "error":
{ toastr.error( message ); break; }
case "success":
{ toastr.success( message ); break; }
case "warning":
{ toastr.warning( message ); break; }
default:
{
toastr.info( message );
break;
}
}
}
|
function adminNotifier( type, message, delay ) {
toastr.options = {
"closeButton" : true,
"preventDuplicates" : true,
"progressBar" : true,
"showDuration" : "300",
"timeOut" : "2000",
"positionClass" : "toast-top-center"
};
switch ( type ) {
case "info":
{ toastr.info( message ); break; }
case "error":
{ toastr.error( message ); break; }
case "success":
{ toastr.success( message ); break; }
case "warning":
{ toastr.warning( message ); break; }
default:
{
toastr.info( message );
break;
}
}
}
|
JavaScript
|
function resetContainerForms( container ) {
// Clears a form in the div element, usually to reset forms in dialogs.
var frm = container.find( "form" );
if ( frm.length ) {
$( frm[0] ).clearForm();
}
}
|
function resetContainerForms( container ) {
// Clears a form in the div element, usually to reset forms in dialogs.
var frm = container.find( "form" );
if ( frm.length ) {
$( frm[0] ).clearForm();
}
}
|
JavaScript
|
function openModal( div, w, h ) {
// Open the modal
div.modal();
// attach a listener to clear form when modal closes
$( div ).on( "hidden.bs.modal", function() {
resetContainerForms( $( this ) );
} );
}
|
function openModal( div, w, h ) {
// Open the modal
div.modal();
// attach a listener to clear form when modal closes
$( div ).on( "hidden.bs.modal", function() {
resetContainerForms( $( this ) );
} );
}
|
JavaScript
|
function openRemoteModal( url, params, w, h, delay ) {
// if no URL, set warning and exit
if ( !url ) {
console.log( "URL needed" );
return;
}
var modal = $remoteModal;
var args = {};
var maxHeight = ( $( window ).height() - 200 );
var maxWidth = ( $( window ).width() * 0.85 );
// Set default values for modal data elements
modal.data( "url", url );
modal.data( "params", params );
modal.data( "width", w !== undefined ? w : maxWidth );
modal.data( "height", h !== undefined ? h : maxHeight );
// convert height percentage to a numeric value
var height = modal.data( "height" );
if ( height.search && height.search( "%" ) !== -1 ) {
height = height.replace( "%", "" ) / 100.00;
height = $( window ).height() * height;
}
// Check max heights conditions
if ( height > maxHeight ) {
height = maxHeight;
}
modal.data( "height", height );
// in delay mode, we'll create a modal and then load the data (seems to be necessary for iframes to load correctly)
if ( delay ) {
modal.data( "delay", true );
modal.modal();
}
// otherwise, front-load the request and then create modal
else {
// load request for content modal
modal.load( url, params, function() {
// Show modal, once content has being retrieved
modal.modal();
} );
}
return;
}
|
function openRemoteModal( url, params, w, h, delay ) {
// if no URL, set warning and exit
if ( !url ) {
console.log( "URL needed" );
return;
}
var modal = $remoteModal;
var args = {};
var maxHeight = ( $( window ).height() - 200 );
var maxWidth = ( $( window ).width() * 0.85 );
// Set default values for modal data elements
modal.data( "url", url );
modal.data( "params", params );
modal.data( "width", w !== undefined ? w : maxWidth );
modal.data( "height", h !== undefined ? h : maxHeight );
// convert height percentage to a numeric value
var height = modal.data( "height" );
if ( height.search && height.search( "%" ) !== -1 ) {
height = height.replace( "%", "" ) / 100.00;
height = $( window ).height() * height;
}
// Check max heights conditions
if ( height > maxHeight ) {
height = maxHeight;
}
modal.data( "height", height );
// in delay mode, we'll create a modal and then load the data (seems to be necessary for iframes to load correctly)
if ( delay ) {
modal.data( "delay", true );
modal.modal();
}
// otherwise, front-load the request and then create modal
else {
// load request for content modal
modal.load( url, params, function() {
// Show modal, once content has being retrieved
modal.modal();
} );
}
return;
}
|
JavaScript
|
function attachModalListeners() {
// Remote show event: Usually we resize the window here.
$remoteModal.on( "show.bs.modal", function() {
var modal = $remoteModal;
modal.find( ".modal-dialog" ).css( {
width : modal.data( "width" ),
height : modal.data( "height" )
} );
} );
// Remote shown event: Delayed loading of content
$remoteModal.on( "shown.bs.modal", function() {
var modal = $remoteModal;
// only run if modal is in delayed mode
if ( modal.data( "delay" ) ) {
modal.load( modal.data( "url" ), modal.data( "params" ), function() {
modal.find( ".modal-dialog" ).css( {
width : modal.data( "width" ),
height : modal.data( "height" )
} );
} );
}
} );
// Remote hidden event: Reset loader
$remoteModal.on( "hidden.bs.modal", function() {
var modal = $remoteModal;
// reset modal html
modal.html( "<div class=\"modal-header\"><h3>Loading...</h3></div><div class=\"modal-body\" id=\"removeModelContent\"><i class=\"fa fa-spinner fa-spin fa-lg fa-4x\"></i></div>" );
// reset container forms
resetContainerForms( modal );
} );
}
|
function attachModalListeners() {
// Remote show event: Usually we resize the window here.
$remoteModal.on( "show.bs.modal", function() {
var modal = $remoteModal;
modal.find( ".modal-dialog" ).css( {
width : modal.data( "width" ),
height : modal.data( "height" )
} );
} );
// Remote shown event: Delayed loading of content
$remoteModal.on( "shown.bs.modal", function() {
var modal = $remoteModal;
// only run if modal is in delayed mode
if ( modal.data( "delay" ) ) {
modal.load( modal.data( "url" ), modal.data( "params" ), function() {
modal.find( ".modal-dialog" ).css( {
width : modal.data( "width" ),
height : modal.data( "height" )
} );
} );
}
} );
// Remote hidden event: Reset loader
$remoteModal.on( "hidden.bs.modal", function() {
var modal = $remoteModal;
// reset modal html
modal.html( "<div class=\"modal-header\"><h3>Loading...</h3></div><div class=\"modal-body\" id=\"removeModelContent\"><i class=\"fa fa-spinner fa-spin fa-lg fa-4x\"></i></div>" );
// reset container forms
resetContainerForms( modal );
} );
}
|
JavaScript
|
function checkAll( checked, id ) {
$( "input[name='" + id + "']" ).each( function() {
this.checked = checked;
} );
}
|
function checkAll( checked, id ) {
$( "input[name='" + id + "']" ).each( function() {
this.checked = checked;
} );
}
|
JavaScript
|
function importContent(){
// local id's
var $importForm = $( "#importForm" );
// open modal for cloning options
openModal( $importDialog, 500, 350 );
// form validator button bar loader
$importForm.validate( {
submitHandler : function( form ){
$importForm.find( "#importButtonBar" ).slideUp();
$importForm.find( "#importBarLoader" ).slideDown();
form.submit();
}
} );
// close button
$importForm.find( "#closeButton" ).click( function( e ){
closeModal( $importDialog );
return false;
} );
// clone button
$importForm.find( "#importButton" ).click( function( e ){
$importForm.submit();
} );
}
|
function importContent(){
// local id's
var $importForm = $( "#importForm" );
// open modal for cloning options
openModal( $importDialog, 500, 350 );
// form validator button bar loader
$importForm.validate( {
submitHandler : function( form ){
$importForm.find( "#importButtonBar" ).slideUp();
$importForm.find( "#importBarLoader" ).slideDown();
form.submit();
}
} );
// close button
$importForm.find( "#closeButton" ).click( function( e ){
closeModal( $importDialog );
return false;
} );
// clone button
$importForm.find( "#importButton" ).click( function( e ){
$importForm.submit();
} );
}
|
JavaScript
|
function passwordMeter( event ) {
var value = $( this ).val();
//console.log( value );
// Counter bind
$( "#pw_rule_count" ).html( value.length );
var minLength = $( "#passwordRules" ).data( "min-length" );
// Rule Checks
var rules = {
lower : REGEX_LOWER.test( value ),
upper : REGEX_UPPER.test( value ),
digit : REGEX_DIGIT.test( value ),
special : REGEX_SPECIAL.test( value )
};
// Counter
if ( value.length >= minLength ) {
$( "#pw_rule_count" ).addClass( "badge-success" );
} else {
$( "#pw_rule_count" ).removeClass( "badge-success" );
}
// Iterate and test rules
for ( var key in rules ) {
if ( rules[key] ) {
$( "#pw_rule_" + key ).addClass( "badge-success" );
} else {
$( "#pw_rule_" + key ).removeClass( "badge-success" );
}
}
}
|
function passwordMeter( event ) {
var value = $( this ).val();
//console.log( value );
// Counter bind
$( "#pw_rule_count" ).html( value.length );
var minLength = $( "#passwordRules" ).data( "min-length" );
// Rule Checks
var rules = {
lower : REGEX_LOWER.test( value ),
upper : REGEX_UPPER.test( value ),
digit : REGEX_DIGIT.test( value ),
special : REGEX_SPECIAL.test( value )
};
// Counter
if ( value.length >= minLength ) {
$( "#pw_rule_count" ).addClass( "badge-success" );
} else {
$( "#pw_rule_count" ).removeClass( "badge-success" );
}
// Iterate and test rules
for ( var key in rules ) {
if ( rules[key] ) {
$( "#pw_rule_" + key ).addClass( "badge-success" );
} else {
$( "#pw_rule_" + key ).removeClass( "badge-success" );
}
}
}
|
JavaScript
|
function passwordValidator( value ) {
var minLength = $( "#passwordRules" ).data( "min-length" );
var lower = REGEX_LOWER.test( value ),
upper = REGEX_UPPER.test( value ),
digit = REGEX_DIGIT.test( value ),
digits = REGEX_DIGITS.test( value ),
special = REGEX_SPECIAL.test( value );
return lower // has a lowercase letter
&&
upper // has an uppercase letter
&&
digit // has at least one digit
&&
special // has special chars
&&
value.length >= minLength; // at least characters
}
|
function passwordValidator( value ) {
var minLength = $( "#passwordRules" ).data( "min-length" );
var lower = REGEX_LOWER.test( value ),
upper = REGEX_UPPER.test( value ),
digit = REGEX_DIGIT.test( value ),
digits = REGEX_DIGITS.test( value ),
special = REGEX_SPECIAL.test( value );
return lower // has a lowercase letter
&&
upper // has an uppercase letter
&&
digit // has at least one digit
&&
special // has special chars
&&
value.length >= minLength; // at least characters
}
|
JavaScript
|
function switchEditor( editorType ){
// Save work
if ( confirm( "Would you like to save your work before switching editors?" ) ){
$changelog.val( "Editor Change Quick Save" );
quickSave();
}
// Call change user editor preference
$.ajax( {
url : getAuthorEditorPreferenceURL(),
data : { editor: editorType },
async : false,
success : function( data ){
location.reload();
}
} );
}
|
function switchEditor( editorType ){
// Save work
if ( confirm( "Would you like to save your work before switching editors?" ) ){
$changelog.val( "Editor Change Quick Save" );
quickSave();
}
// Call change user editor preference
$.ajax( {
url : getAuthorEditorPreferenceURL(),
data : { editor: editorType },
async : false,
success : function( data ){
location.reload();
}
} );
}
|
JavaScript
|
function shouldPublish(){
// Confirm if you really want to quick save if content is published already
if ( $contentID.val().length && $isPublished.val() == "true" ){
return confirm(
"Your content is published already, quick saving it will draft it and unpublish it." +
"If you want to re-publish, just hit Publish again." +
"Are you sure you want to draft the content?"
);
}
return true;
}
|
function shouldPublish(){
// Confirm if you really want to quick save if content is published already
if ( $contentID.val().length && $isPublished.val() == "true" ){
return confirm(
"Your content is published already, quick saving it will draft it and unpublish it." +
"If you want to re-publish, just hit Publish again." +
"Are you sure you want to draft the content?"
);
}
return true;
}
|
JavaScript
|
function publishNow(){
var fullDate = new Date();
$( "#publishedDate" ).val( getToday() );
$( "#publishedHour" ).val( fullDate.getHours() );
$( "#publishedMinute" ).val( fullDate.getMinutes() );
}
|
function publishNow(){
var fullDate = new Date();
$( "#publishedDate" ).val( getToday() );
$( "#publishedHour" ).val( fullDate.getHours() );
$( "#publishedMinute" ).val( fullDate.getMinutes() );
}
|
JavaScript
|
function askLeaveConfirmation(){
if ( checkIsDirty() && !$wasSubmitted ){
return "You have unsaved changes.";
}
}
|
function askLeaveConfirmation(){
if ( checkIsDirty() && !$wasSubmitted ){
return "You have unsaved changes.";
}
}
|
JavaScript
|
function permalinkUniqueCheck( linkToUse ){
linkToUse = linkToUse || $slug.val();
linkToUse = $.trim( linkToUse ); //slugify still appends a space at the end of the string, so trim here for check uniqueness
if ( !linkToUse.length ){ return; }
// Verify unique
$.getJSON(
$cbEditorConfig.slugCheckURL,
{
slug : linkToUse,
contentID : $( "#contentID" ).val(),
contentType : $( "#contentType" ).val()
},
function( data ){
if ( !data.UNIQUE ){
$( "#slugCheckErrors" )
.html( "The permalink slug you entered is already in use, please enter another one or modify it." )
.addClass( "alert alert-danger" );
} else {
$( "#slugCheckErrors" )
.html( "" )
.removeClass( "alert alert-danger" );
}
}
);
}
|
function permalinkUniqueCheck( linkToUse ){
linkToUse = linkToUse || $slug.val();
linkToUse = $.trim( linkToUse ); //slugify still appends a space at the end of the string, so trim here for check uniqueness
if ( !linkToUse.length ){ return; }
// Verify unique
$.getJSON(
$cbEditorConfig.slugCheckURL,
{
slug : linkToUse,
contentID : $( "#contentID" ).val(),
contentType : $( "#contentType" ).val()
},
function( data ){
if ( !data.UNIQUE ){
$( "#slugCheckErrors" )
.html( "The permalink slug you entered is already in use, please enter another one or modify it." )
.addClass( "alert alert-danger" );
} else {
$( "#slugCheckErrors" )
.html( "" )
.removeClass( "alert alert-danger" );
}
}
);
}
|
JavaScript
|
function toggleDraft(){
// Confirm if you really want to quick save if content is published already
if ( !shouldPublish() ){
return false;
}
// set published bit to false
$isPublished.val( "false" );
// record we are submitting
setWasSubmitted();
return true;
}
|
function toggleDraft(){
// Confirm if you really want to quick save if content is published already
if ( !shouldPublish() ){
return false;
}
// set published bit to false
$isPublished.val( "false" );
// record we are submitting
setWasSubmitted();
return true;
}
|
JavaScript
|
function quickPublish( isDraft ){
if ( isDraft ){
// verify we can draft this content
if ( !toggleDraft() ){
return;
}
} else {
// set published bit
$isPublished.val( "true" );
// set was submitted
setWasSubmitted();
}
// Verify changelogs and open sidebar if closed:
if ( $cbEditorConfig.changelogMandatory && !isMainSidebarOpen() ){
toggleSidebar();
}
// submit form
$targetEditorForm.submit();
}
|
function quickPublish( isDraft ){
if ( isDraft ){
// verify we can draft this content
if ( !toggleDraft() ){
return;
}
} else {
// set published bit
$isPublished.val( "true" );
// set was submitted
setWasSubmitted();
}
// Verify changelogs and open sidebar if closed:
if ( $cbEditorConfig.changelogMandatory && !isMainSidebarOpen() ){
toggleSidebar();
}
// submit form
$targetEditorForm.submit();
}
|
JavaScript
|
function featuredImageCallback( filePath, fileURL, fileType ){
if ( $( "#featuredImage" ).val().length ){ cancelFeaturedImage(); }
$( "#featuredImageControls" ).toggleClass( "hide" );
$( "#featuredImage" ).val( filePath );
$( "#featuredImageURL" ).val( fileURL );
$( "#featuredImagePreview" ).attr( "src", fileURL );
closeRemoteModal();
}
|
function featuredImageCallback( filePath, fileURL, fileType ){
if ( $( "#featuredImage" ).val().length ){ cancelFeaturedImage(); }
$( "#featuredImageControls" ).toggleClass( "hide" );
$( "#featuredImage" ).val( filePath );
$( "#featuredImageURL" ).val( fileURL );
$( "#featuredImagePreview" ).attr( "src", fileURL );
closeRemoteModal();
}
|
JavaScript
|
function ApplyBold(vCustomAttributes,vCustomComas){
var vPuntoComa = '';
if (vCustomComas>0) {
vPuntoComa = ';';
}
switch (vCustomAttributes)
{
case '<bold>':
StyleTags += vPuntoComa + 'font-weight:bold';
vGlobalComas = 1;
vGlobalComas2 = 1;
break;
default:
StyleTags += '';
break;
}
}
|
function ApplyBold(vCustomAttributes,vCustomComas){
var vPuntoComa = '';
if (vCustomComas>0) {
vPuntoComa = ';';
}
switch (vCustomAttributes)
{
case '<bold>':
StyleTags += vPuntoComa + 'font-weight:bold';
vGlobalComas = 1;
vGlobalComas2 = 1;
break;
default:
StyleTags += '';
break;
}
}
|
JavaScript
|
function buildUrl(base, params = {}) {
const { path = {}, query } = params;
let url = base;
// First do token-substitution in the given base:
url = XRegExp.replace(url, expandUrlTokens, (...args) => {
const groups = args.pop();
if (!path[groups.ident]) {
throw new Error(`No value given for URL token: ${groups.ident}`);
}
return path[groups.ident];
});
// Next append any query parameters:
if (query) {
const queryValues = [];
const entries = Object.entries(query).sort((a, b) =>
b[0].localeCompare(a[0])
);
for (const [key, value] of entries) {
if (Array.isArray(value)) {
value.forEach((val) => queryValues.push(`${key}=${val}`));
} else {
queryValues.push(`${key}=${value}`);
}
}
url = `${url}?${queryValues.join("&")}`;
}
return `/api${url}`;
}
|
function buildUrl(base, params = {}) {
const { path = {}, query } = params;
let url = base;
// First do token-substitution in the given base:
url = XRegExp.replace(url, expandUrlTokens, (...args) => {
const groups = args.pop();
if (!path[groups.ident]) {
throw new Error(`No value given for URL token: ${groups.ident}`);
}
return path[groups.ident];
});
// Next append any query parameters:
if (query) {
const queryValues = [];
const entries = Object.entries(query).sort((a, b) =>
b[0].localeCompare(a[0])
);
for (const [key, value] of entries) {
if (Array.isArray(value)) {
value.forEach((val) => queryValues.push(`${key}=${val}`));
} else {
queryValues.push(`${key}=${value}`);
}
}
url = `${url}?${queryValues.join("&")}`;
}
return `/api${url}`;
}
|
JavaScript
|
function createMagazine(context) {
const { res, requestBody } = context;
return Magazines.createMagazine(requestBody)
.then((magazine) => {
res.status(201).pureJson({ magazine });
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
function createMagazine(context) {
const { res, requestBody } = context;
return Magazines.createMagazine(requestBody)
.then((magazine) => {
res.status(201).pureJson({ magazine });
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
JavaScript
|
function updateMagazineById(context) {
const { id } = context.params.path;
const { res, requestBody } = context;
return Magazines.updateMagazine(id, requestBody)
.then((magazine) => {
if (magazine) {
res.status(200).pureJson({ magazine });
} else {
res.status(404).pureJson({
error: {
summary: "Not found",
description: `No magazine with this ID (${id}) found`,
},
});
}
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
function updateMagazineById(context) {
const { id } = context.params.path;
const { res, requestBody } = context;
return Magazines.updateMagazine(id, requestBody)
.then((magazine) => {
if (magazine) {
res.status(200).pureJson({ magazine });
} else {
res.status(404).pureJson({
error: {
summary: "Not found",
description: `No magazine with this ID (${id}) found`,
},
});
}
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
JavaScript
|
function deleteMagazineById(context) {
const { id } = context.params.path;
const { res } = context;
return Magazines.deleteMagazine(id)
.then((number) => {
if (number) {
res.status(200).set("content-type", "text/plain");
} else {
res.status(404).pureJson({
error: {
summary: "Not found",
description: `No magazine with this ID (${id}) found`,
},
});
}
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
function deleteMagazineById(context) {
const { id } = context.params.path;
const { res } = context;
return Magazines.deleteMagazine(id)
.then((number) => {
if (number) {
res.status(200).set("content-type", "text/plain");
} else {
res.status(404).pureJson({
error: {
summary: "Not found",
description: `No magazine with this ID (${id}) found`,
},
});
}
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
JavaScript
|
function createMagazineIssue(context) {
const { res, requestBody } = context;
return Magazines.createMagazineIssue(requestBody)
.then((magazineissue) => {
res.status(201).pureJson({ magazineissue });
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
function createMagazineIssue(context) {
const { res, requestBody } = context;
return Magazines.createMagazineIssue(requestBody)
.then((magazineissue) => {
res.status(201).pureJson({ magazineissue });
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
JavaScript
|
function updateMagazineIssueById(context) {
const { id } = context.params.path;
const { res, requestBody } = context;
return Magazines.updateMagazineIssue(id, requestBody)
.then((magazineissue) => {
if (magazineissue) {
res.status(200).pureJson({ magazineissue });
} else {
res.status(404).pureJson({
error: {
summary: "Not found",
description: `No issue with this ID (${id}) found`,
},
});
}
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
function updateMagazineIssueById(context) {
const { id } = context.params.path;
const { res, requestBody } = context;
return Magazines.updateMagazineIssue(id, requestBody)
.then((magazineissue) => {
if (magazineissue) {
res.status(200).pureJson({ magazineissue });
} else {
res.status(404).pureJson({
error: {
summary: "Not found",
description: `No issue with this ID (${id}) found`,
},
});
}
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
JavaScript
|
function deleteMagazineIssueById(context) {
const { id } = context.params.path;
const { res } = context;
return Magazines.deleteMagazineIssue(id)
.then((number) => {
if (number) {
res.status(200).set("content-type", "text/plain");
} else {
res.status(404).pureJson({
error: {
summary: "Not found",
description: `No issue with this ID (${id}) found`,
},
});
}
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
function deleteMagazineIssueById(context) {
const { id } = context.params.path;
const { res } = context;
return Magazines.deleteMagazineIssue(id)
.then((number) => {
if (number) {
res.status(200).set("content-type", "text/plain");
} else {
res.status(404).pureJson({
error: {
summary: "Not found",
description: `No issue with this ID (${id}) found`,
},
});
}
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
JavaScript
|
function cleanReference(referenceIn) {
const reference = referenceIn.get();
if (reference.Authors) {
reference.authors = reference.Authors.map((authIn) => {
const author = authIn.get();
delete author.AuthorsReferences;
return author;
});
delete reference.Authors;
}
if (reference.Tags) {
reference.tags = reference.Tags.map((tagIn) => {
const tag = tagIn.get();
delete tag.TagsReferences;
return tag;
});
delete reference.Tags;
delete reference.TagsReferences;
}
if (reference.MagazineIssue) {
reference.Magazine = reference.MagazineIssue.Magazine.get();
reference.MagazineIssue = reference.MagazineIssue.get();
delete reference.MagazineIssue.Magazine;
}
reference.RecordType = reference.RecordType.get();
return reference;
}
|
function cleanReference(referenceIn) {
const reference = referenceIn.get();
if (reference.Authors) {
reference.authors = reference.Authors.map((authIn) => {
const author = authIn.get();
delete author.AuthorsReferences;
return author;
});
delete reference.Authors;
}
if (reference.Tags) {
reference.tags = reference.Tags.map((tagIn) => {
const tag = tagIn.get();
delete tag.TagsReferences;
return tag;
});
delete reference.Tags;
delete reference.TagsReferences;
}
if (reference.MagazineIssue) {
reference.Magazine = reference.MagazineIssue.Magazine.get();
reference.MagazineIssue = reference.MagazineIssue.get();
delete reference.MagazineIssue.Magazine;
}
reference.RecordType = reference.RecordType.get();
return reference;
}
|
JavaScript
|
function quickSearchName(context) {
const { query, count } = context.params.query;
const { res } = context;
return quickSearchByName(query, count)
.then((matches) => {
res.status(200).pureJson({ matches });
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
function quickSearchName(context) {
const { query, count } = context.params.query;
const { res } = context;
return quickSearchByName(query, count)
.then((matches) => {
res.status(200).pureJson({ matches });
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
JavaScript
|
function createAuthor(context) {
const { res, requestBody } = context;
return Authors.createAuthor(requestBody)
.then((author) => {
res.status(201).pureJson({ author });
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
function createAuthor(context) {
const { res, requestBody } = context;
return Authors.createAuthor(requestBody)
.then((author) => {
res.status(201).pureJson({ author });
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
JavaScript
|
function updateAuthorById(context) {
const { id } = context.params.path;
const { res, requestBody } = context;
return Authors.updateAuthor(id, requestBody)
.then((author) => {
if (author) {
res.status(200).pureJson({ author });
} else {
res.status(404).pureJson({
error: {
summary: "Not found",
description: `No author with this ID (${id}) found`,
},
});
}
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
function updateAuthorById(context) {
const { id } = context.params.path;
const { res, requestBody } = context;
return Authors.updateAuthor(id, requestBody)
.then((author) => {
if (author) {
res.status(200).pureJson({ author });
} else {
res.status(404).pureJson({
error: {
summary: "Not found",
description: `No author with this ID (${id}) found`,
},
});
}
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
JavaScript
|
function deleteAuthorById(context) {
const { id } = context.params.path;
const { res } = context;
return Authors.deleteAuthor(id)
.then((number) => {
if (number) {
res.status(200).set("content-type", "text/plain");
} else {
res.status(404).pureJson({
error: {
summary: "Not found",
description: `No author with this ID (${id}) found`,
},
});
}
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
function deleteAuthorById(context) {
const { id } = context.params.path;
const { res } = context;
return Authors.deleteAuthor(id)
.then((number) => {
if (number) {
res.status(200).set("content-type", "text/plain");
} else {
res.status(404).pureJson({
error: {
summary: "Not found",
description: `No author with this ID (${id}) found`,
},
});
}
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
JavaScript
|
function createReference(context) {
const { res, requestBody } = context;
return References.createReference(requestBody)
.then((response) => {
res.status(201).pureJson(response);
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
function createReference(context) {
const { res, requestBody } = context;
return References.createReference(requestBody)
.then((response) => {
res.status(201).pureJson(response);
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
JavaScript
|
function updateReferenceById(context) {
const { id } = context.params.path;
const { res, requestBody } = context;
return References.updateReference(id, requestBody)
.then((reference) => {
if (reference) {
res.status(200).pureJson({ reference });
} else {
res.status(404).pureJson({
error: {
summary: "Not found",
description: `No reference with this ID (${id}) found`,
},
});
}
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
function updateReferenceById(context) {
const { id } = context.params.path;
const { res, requestBody } = context;
return References.updateReference(id, requestBody)
.then((reference) => {
if (reference) {
res.status(200).pureJson({ reference });
} else {
res.status(404).pureJson({
error: {
summary: "Not found",
description: `No reference with this ID (${id}) found`,
},
});
}
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
JavaScript
|
function deleteReferenceById(context) {
const { id } = context.params.path;
const { res } = context;
return References.deleteReference(id)
.then((number) => {
if (number) {
res.status(200).set("content-type", "text/plain");
} else {
res.status(404).pureJson({
error: {
summary: "Not found",
description: `No reference with this ID (${id}) found`,
},
});
}
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
function deleteReferenceById(context) {
const { id } = context.params.path;
const { res } = context;
return References.deleteReference(id)
.then((number) => {
if (number) {
res.status(200).set("content-type", "text/plain");
} else {
res.status(404).pureJson({
error: {
summary: "Not found",
description: `No reference with this ID (${id}) found`,
},
});
}
})
.catch((error) => {
res.status(500).pureJson({
error: {
summary: error.name,
description: error.message,
},
});
});
}
|
JavaScript
|
function autoExit() {
var interval = 3000;
var aliveInterval = interval * 1.5;
setTimeout(function () {
var alive = false
var aliveTimer = setTimeout(function () {
if (!alive) {
console.error('PM2 Daemon is dead');
process.exit(1);
}
}, aliveInterval);
pm2.list(function (err, apps) {
if (err) {
console.log('pm2.list got error')
console.error(err);
exitPM2();
}
clearTimeout(aliveTimer);
alive = true;
var appOnline = 0;
apps.forEach(function (app) {
if (app.pm2_env.status === cst.ONLINE_STATUS ||
app.pm2_env.status === cst.LAUNCHING_STATUS) {
appOnline++;
}
});
if (appOnline === 0) {
console.log('0 application online, exiting');
exitPM2();
}
autoExit();
});
}, interval);
}
|
function autoExit() {
var interval = 3000;
var aliveInterval = interval * 1.5;
setTimeout(function () {
var alive = false
var aliveTimer = setTimeout(function () {
if (!alive) {
console.error('PM2 Daemon is dead');
process.exit(1);
}
}, aliveInterval);
pm2.list(function (err, apps) {
if (err) {
console.log('pm2.list got error')
console.error(err);
exitPM2();
}
clearTimeout(aliveTimer);
alive = true;
var appOnline = 0;
apps.forEach(function (app) {
if (app.pm2_env.status === cst.ONLINE_STATUS ||
app.pm2_env.status === cst.LAUNCHING_STATUS) {
appOnline++;
}
});
if (appOnline === 0) {
console.log('0 application online, exiting');
exitPM2();
}
autoExit();
});
}, interval);
}
|
JavaScript
|
function loginPrompt(cb) {
console.log(chalk.bold('Log in to Keymetrics'));
(function retry() {
promptly.prompt('Username or Email: ', function(err, username) {
promptly.password('Password: ', { replace : '*' }, function(err, password) {
KM.loginAndGetAccessToken({ username : username, password: password }, function(err) {
if (err) {
console.error(chalk.red.bold(err) + '\n');
return retry();
}
KM.getBuckets(function(err, buckets) {
if (err) {
console.error(chalk.red.bold(err) + '\n');
return retry();
}
if (buckets.length > 1) {
console.log(chalk.bold('Bucket list'));
var table = new Table({
style : {'padding-left' : 1, head : ['cyan', 'bold'], compact : true},
head : ['Bucket name', 'Plan type']
});
buckets.forEach(function(bucket) {
table.push([bucket.name, bucket.credits.offer_type]);
});
console.log(table.toString());
(function retryInsertion() {
promptly.prompt('Type the bucket you want to link to: ', function(err, bucket_name) {
var target_bucket = null;
buckets.some(function(bucket) {
if (bucket.name == bucket_name) {
target_bucket = bucket;
return true;
}
});
if (target_bucket == null)
return retryInsertion();
linkOpenExit(target_bucket);
});
})();
}
else {
var target_bucket = buckets[0];
console.log('Connecting local PM2 to Keymetrics Bucket [%s]', target_bucket.name);
KMDaemon.launchAndInteract(cst, {
public_key : target_bucket.public_id,
secret_key : target_bucket.secret_id
}, function(err, dt) {
linkOpenExit(target_bucket);
});
}
});
});
});
})
})()
}
|
function loginPrompt(cb) {
console.log(chalk.bold('Log in to Keymetrics'));
(function retry() {
promptly.prompt('Username or Email: ', function(err, username) {
promptly.password('Password: ', { replace : '*' }, function(err, password) {
KM.loginAndGetAccessToken({ username : username, password: password }, function(err) {
if (err) {
console.error(chalk.red.bold(err) + '\n');
return retry();
}
KM.getBuckets(function(err, buckets) {
if (err) {
console.error(chalk.red.bold(err) + '\n');
return retry();
}
if (buckets.length > 1) {
console.log(chalk.bold('Bucket list'));
var table = new Table({
style : {'padding-left' : 1, head : ['cyan', 'bold'], compact : true},
head : ['Bucket name', 'Plan type']
});
buckets.forEach(function(bucket) {
table.push([bucket.name, bucket.credits.offer_type]);
});
console.log(table.toString());
(function retryInsertion() {
promptly.prompt('Type the bucket you want to link to: ', function(err, bucket_name) {
var target_bucket = null;
buckets.some(function(bucket) {
if (bucket.name == bucket_name) {
target_bucket = bucket;
return true;
}
});
if (target_bucket == null)
return retryInsertion();
linkOpenExit(target_bucket);
});
})();
}
else {
var target_bucket = buckets[0];
console.log('Connecting local PM2 to Keymetrics Bucket [%s]', target_bucket.name);
KMDaemon.launchAndInteract(cst, {
public_key : target_bucket.public_id,
secret_key : target_bucket.secret_id
}, function(err, dt) {
linkOpenExit(target_bucket);
});
}
});
});
});
})
})()
}
|
JavaScript
|
function registerPrompt() {
console.log(chalk.bold('Now registering to Keymetrics'));
promptly.prompt('Username: ', {
validator : validateUsername,
retry : true
}, function(err, username) {
promptly.prompt('Email: ', {
validator : validateEmail,
retry : true
}, function(err, email) {
promptly.password('Password: ', { replace : '*' }, function(err, password) {
process.stdout.write(chalk.bold('Creating account on Keymetrics..'));
var inter = setInterval(function() {
process.stdout.write('.');
}, 300);
KM.fullCreationFlow({
email : email,
password : password,
username : username
}, function(err, target_bucket) {
clearInterval(inter);
if (err) {
console.error('\n' + chalk.red.bold(err) + '\n');
return registerPrompt();
}
linkOpenExit(target_bucket);
});
});
});
})
}
|
function registerPrompt() {
console.log(chalk.bold('Now registering to Keymetrics'));
promptly.prompt('Username: ', {
validator : validateUsername,
retry : true
}, function(err, username) {
promptly.prompt('Email: ', {
validator : validateEmail,
retry : true
}, function(err, email) {
promptly.password('Password: ', { replace : '*' }, function(err, password) {
process.stdout.write(chalk.bold('Creating account on Keymetrics..'));
var inter = setInterval(function() {
process.stdout.write('.');
}, 300);
KM.fullCreationFlow({
email : email,
password : password,
username : username
}, function(err, target_bucket) {
clearInterval(inter);
if (err) {
console.error('\n' + chalk.red.bold(err) + '\n');
return registerPrompt();
}
linkOpenExit(target_bucket);
});
});
});
})
}
|
JavaScript
|
function buildMetaData(sample) {
d3.json("samples.json").then(function(data) {
var metadata = data.metadata;
var resultsArr = metadata.filter(function(data) {
return data.id == sample;
})
var result = resultsArr[0];
var panel = d3.select("#sample-metadata");
// Reset data to empty
panel.html("");
Object.entries(result).forEach(function([key, value]) {
panel.append("h6").text(`${key.toUpperCase()}: ${value}`);
})
console.log(result.wfreq);
// For bonus
buildGauge(result.wfreq);
})
}
|
function buildMetaData(sample) {
d3.json("samples.json").then(function(data) {
var metadata = data.metadata;
var resultsArr = metadata.filter(function(data) {
return data.id == sample;
})
var result = resultsArr[0];
var panel = d3.select("#sample-metadata");
// Reset data to empty
panel.html("");
Object.entries(result).forEach(function([key, value]) {
panel.append("h6").text(`${key.toUpperCase()}: ${value}`);
})
console.log(result.wfreq);
// For bonus
buildGauge(result.wfreq);
})
}
|
JavaScript
|
function buildChart(sample) {
d3.json("samples.json").then(function(data){
var samples = data.samples;
var resultsArray = samples.filter(function(data){
return data.id === sample;
})
var result = resultsArray[0];
// Grabbing the bacterial species id number, name, and quantity
var otu_ids = result["otu_ids"];
var otu_labels = result["otu_labels"];
var sample_values = result["sample_values"];
console.log(otu_ids);
console.log(otu_labels);
console.log(sample_values);
// Building the bubble chart
var bubbleLayout = {
title: "Bacterial Cultures Per Sample",
hovermode: "closest",
xaxis: { title: "OTU ID"},
margin: {t: 30}
}
var bubbleData = [
{
x: otu_ids,
y: sample_values,
text: otu_labels,
mode: "markers",
marker: {
size: sample_values,
color: otu_ids,
colorscale: "sunset"
}
}
];
Plotly.newPlot("bubble", bubbleData, bubbleLayout);
// First 10 OTU IDs for Horizontal Bar Chart
var yticks = otu_ids.slice(0,10)
.map(function(otuID) {
return `OTU ${otuID}`;
}).reverse();
var barData = [
{
y: yticks,
x: sample_values.slice(0,10).reverse(),
text: otu_labels.slice(0,10).reverse(),
type: "bar",
orientation: "h"
}
];
var barLayout = {
title: "Top 10 Most Common Bacteria",
margin: {t: 30, l: 150}
};
Plotly.newPlot("bar", barData, barLayout);
})
}
|
function buildChart(sample) {
d3.json("samples.json").then(function(data){
var samples = data.samples;
var resultsArray = samples.filter(function(data){
return data.id === sample;
})
var result = resultsArray[0];
// Grabbing the bacterial species id number, name, and quantity
var otu_ids = result["otu_ids"];
var otu_labels = result["otu_labels"];
var sample_values = result["sample_values"];
console.log(otu_ids);
console.log(otu_labels);
console.log(sample_values);
// Building the bubble chart
var bubbleLayout = {
title: "Bacterial Cultures Per Sample",
hovermode: "closest",
xaxis: { title: "OTU ID"},
margin: {t: 30}
}
var bubbleData = [
{
x: otu_ids,
y: sample_values,
text: otu_labels,
mode: "markers",
marker: {
size: sample_values,
color: otu_ids,
colorscale: "sunset"
}
}
];
Plotly.newPlot("bubble", bubbleData, bubbleLayout);
// First 10 OTU IDs for Horizontal Bar Chart
var yticks = otu_ids.slice(0,10)
.map(function(otuID) {
return `OTU ${otuID}`;
}).reverse();
var barData = [
{
y: yticks,
x: sample_values.slice(0,10).reverse(),
text: otu_labels.slice(0,10).reverse(),
type: "bar",
orientation: "h"
}
];
var barLayout = {
title: "Top 10 Most Common Bacteria",
margin: {t: 30, l: 150}
};
Plotly.newPlot("bar", barData, barLayout);
})
}
|
JavaScript
|
function generateLoaders(loader, loaderOptions) {
// 扩展流程
if (cml.config.get().extPlatform && ~Object.keys(cml.config.get().extPlatform).indexOf(options.type)) {
let extLoaders = [
{
loader: 'mvvm-style-loader'
},
getPostCssLoader('extend')
]
if (loader) {
extLoaders.push(
{
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: false
})
}
)
}
addMediaLoader(extLoaders, options.type);
return extLoaders;
}
var loaders = [cssLoader];
let result = [];
if (options.type === 'web') {
// 把chameleon-css-loader需要在postcssloader之后处理,postcssloader先处理@import,否则@import文件中的内容不经过chameleon-css-loader
// chameleon-css-loader需要再最后处理,需要标准的css格式
loaders.push({
loader: 'chameleon-css-loader',
options: {
platform: 'web',
...cml.config.get().cmss
}
})
loaders.push(getPostCssLoader('web'))
}
if (~['wx', 'alipay', 'baidu', 'qq', 'tt'].indexOf(options.type)) {
loaders = loaders.concat(getMiniappLoader(options.type))
}
if (options.type === 'weex') {
// 把wchameleon-css-loader需要在postcssloader之后处理,postcssloader先处理@import,否则@import文件中的内容不经过chameleon-css-loader
// weex不能使用css-loader css-loader就开始添加module.exports模块化代码,而weex-vue-loader中内部会处理css字符串为对象
loaders = [
{
loader: 'chameleon-css-loader',
options: {
platform: 'weex'
}
},
getPostCssLoader('weex')
];
}
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: false
})
})
}
if (options.media === 'export' && options.type !== 'wx' && options.mode !== 'production') {
loaders.push(getPostCssLoader('export'));
}
if (options.type === 'weex') {
result = loaders;
} else {
if (options.extract) {
result = ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else {
result = ['vue-style-loader'].concat(loaders)
}
}
addMediaLoader(result, options.type);
return result;
}
|
function generateLoaders(loader, loaderOptions) {
// 扩展流程
if (cml.config.get().extPlatform && ~Object.keys(cml.config.get().extPlatform).indexOf(options.type)) {
let extLoaders = [
{
loader: 'mvvm-style-loader'
},
getPostCssLoader('extend')
]
if (loader) {
extLoaders.push(
{
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: false
})
}
)
}
addMediaLoader(extLoaders, options.type);
return extLoaders;
}
var loaders = [cssLoader];
let result = [];
if (options.type === 'web') {
// 把chameleon-css-loader需要在postcssloader之后处理,postcssloader先处理@import,否则@import文件中的内容不经过chameleon-css-loader
// chameleon-css-loader需要再最后处理,需要标准的css格式
loaders.push({
loader: 'chameleon-css-loader',
options: {
platform: 'web',
...cml.config.get().cmss
}
})
loaders.push(getPostCssLoader('web'))
}
if (~['wx', 'alipay', 'baidu', 'qq', 'tt'].indexOf(options.type)) {
loaders = loaders.concat(getMiniappLoader(options.type))
}
if (options.type === 'weex') {
// 把wchameleon-css-loader需要在postcssloader之后处理,postcssloader先处理@import,否则@import文件中的内容不经过chameleon-css-loader
// weex不能使用css-loader css-loader就开始添加module.exports模块化代码,而weex-vue-loader中内部会处理css字符串为对象
loaders = [
{
loader: 'chameleon-css-loader',
options: {
platform: 'weex'
}
},
getPostCssLoader('weex')
];
}
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: false
})
})
}
if (options.media === 'export' && options.type !== 'wx' && options.mode !== 'production') {
loaders.push(getPostCssLoader('export'));
}
if (options.type === 'weex') {
result = loaders;
} else {
if (options.extract) {
result = ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else {
result = ['vue-style-loader'].concat(loaders)
}
}
addMediaLoader(result, options.type);
return result;
}
|
JavaScript
|
function toAsync(fn) {
return function (...args) {
// make sure the returned function works as a method as well:
// bind the function before using it in the promise
const bound_fn = fn.bind(this);
return new Promise((resolve, reject) =>
bound_fn(...args, (err, ok) => err ? reject (err) : resolve(ok)));
};
}
|
function toAsync(fn) {
return function (...args) {
// make sure the returned function works as a method as well:
// bind the function before using it in the promise
const bound_fn = fn.bind(this);
return new Promise((resolve, reject) =>
bound_fn(...args, (err, ok) => err ? reject (err) : resolve(ok)));
};
}
|
JavaScript
|
function adjustPlayerHeights(){
if( Foundation.MediaQuery.atLeast('medium') ) {
var left = $('div#amplitude-left').width();
var bottom = $('div#player-left-bottom').outerHeight();
$('#amplitude-right').css('height', ( left + bottom )+'px');
}else{
$('#amplitude-right').css('height', 'initial');
}
}
|
function adjustPlayerHeights(){
if( Foundation.MediaQuery.atLeast('medium') ) {
var left = $('div#amplitude-left').width();
var bottom = $('div#player-left-bottom').outerHeight();
$('#amplitude-right').css('height', ( left + bottom )+'px');
}else{
$('#amplitude-right').css('height', 'initial');
}
}
|
JavaScript
|
tokenize(query, respect_word_boundaries, weights) {
if (!query || !query.length) return [];
const tokens = [];
const words = query.split(/\s+/);
var field_regex;
if (weights) {
field_regex = new RegExp('^(' + Object.keys(weights).map(escape_regex).join('|') + ')\:(.*)$');
}
words.forEach(word => {
let field_match;
let field = null;
let regex = null; // look for "field:query" tokens
if (field_regex && (field_match = word.match(field_regex))) {
field = field_match[1];
word = field_match[2];
}
if (word.length > 0) {
regex = escape_regex(word);
if (this.settings.diacritics) {
regex = diacriticRegexPoints(regex);
}
if (respect_word_boundaries) regex = "\\b" + regex;
}
tokens.push({
string: word,
regex: regex ? new RegExp(regex, 'iu') : null,
field: field
});
});
return tokens;
}
|
tokenize(query, respect_word_boundaries, weights) {
if (!query || !query.length) return [];
const tokens = [];
const words = query.split(/\s+/);
var field_regex;
if (weights) {
field_regex = new RegExp('^(' + Object.keys(weights).map(escape_regex).join('|') + ')\:(.*)$');
}
words.forEach(word => {
let field_match;
let field = null;
let regex = null; // look for "field:query" tokens
if (field_regex && (field_match = word.match(field_regex))) {
field = field_match[1];
word = field_match[2];
}
if (word.length > 0) {
regex = escape_regex(word);
if (this.settings.diacritics) {
regex = diacriticRegexPoints(regex);
}
if (respect_word_boundaries) regex = "\\b" + regex;
}
tokens.push({
string: word,
regex: regex ? new RegExp(regex, 'iu') : null,
field: field
});
});
return tokens;
}
|
JavaScript
|
prepareSearch(query, optsUser) {
const weights = {};
var options = Object.assign({}, optsUser);
propToArray(options, 'sort');
propToArray(options, 'sort_empty'); // convert fields to new format
if (options.fields) {
propToArray(options, 'fields');
const fields = [];
options.fields.forEach(field => {
if (typeof field == 'string') {
field = {
field: field,
weight: 1
};
}
fields.push(field);
weights[field.field] = 'weight' in field ? field.weight : 1;
});
options.fields = fields;
}
return {
options: options,
query: query.toLowerCase().trim(),
tokens: this.tokenize(query, options.respect_word_boundaries, weights),
total: 0,
items: [],
weights: weights,
getAttrFn: options.nesting ? getAttrNesting : getAttr
};
}
|
prepareSearch(query, optsUser) {
const weights = {};
var options = Object.assign({}, optsUser);
propToArray(options, 'sort');
propToArray(options, 'sort_empty'); // convert fields to new format
if (options.fields) {
propToArray(options, 'fields');
const fields = [];
options.fields.forEach(field => {
if (typeof field == 'string') {
field = {
field: field,
weight: 1
};
}
fields.push(field);
weights[field.field] = 'weight' in field ? field.weight : 1;
});
options.fields = fields;
}
return {
options: options,
query: query.toLowerCase().trim(),
tokens: this.tokenize(query, options.respect_word_boundaries, weights),
total: 0,
items: [],
weights: weights,
getAttrFn: options.nesting ? getAttrNesting : getAttr
};
}
|
JavaScript
|
updateOriginalInput(opts = {}) {
const self = this;
var i, value, option, option_el, label;
if (self.is_select_tag) {
const selected = [];
function AddSelected(option_el, value, label) {
if (!option_el) {
option_el = getDom('<option value="' + escape_html(value) + '">' + escape_html(label) + '</option>');
}
self.input.prepend(option_el);
selected.push(option_el);
setAttr(option_el, {
selected: 'true'
});
option_el.selected = true;
return option_el;
} // unselect all selected options
self.input.querySelectorAll('option[selected]').forEach(option_el => {
setAttr(option_el, {
selected: null
});
option_el.selected = false;
}); // nothing selected?
if (self.items.length == 0 && self.settings.mode == 'single' && !self.isRequired) {
option_el = self.input.querySelector('option[value=""]');
AddSelected(option_el, "", ""); // order selected <option> tags for values in self.items
} else {
for (i = self.items.length - 1; i >= 0; i--) {
value = self.items[i];
option = self.options[value];
label = option[self.settings.labelField] || '';
if (selected.includes(option.$option)) {
const reuse_opt = self.input.querySelector(`option[value="${addSlashes(value)}"]:not([selected])`);
AddSelected(reuse_opt, value, label);
} else {
option.$option = AddSelected(option.$option, value, label);
}
}
}
} else {
self.input.value = self.getValue();
}
if (self.isSetup) {
if (!opts.silent) {
self.trigger('change', self.getValue());
}
}
}
|
updateOriginalInput(opts = {}) {
const self = this;
var i, value, option, option_el, label;
if (self.is_select_tag) {
const selected = [];
function AddSelected(option_el, value, label) {
if (!option_el) {
option_el = getDom('<option value="' + escape_html(value) + '">' + escape_html(label) + '</option>');
}
self.input.prepend(option_el);
selected.push(option_el);
setAttr(option_el, {
selected: 'true'
});
option_el.selected = true;
return option_el;
} // unselect all selected options
self.input.querySelectorAll('option[selected]').forEach(option_el => {
setAttr(option_el, {
selected: null
});
option_el.selected = false;
}); // nothing selected?
if (self.items.length == 0 && self.settings.mode == 'single' && !self.isRequired) {
option_el = self.input.querySelector('option[value=""]');
AddSelected(option_el, "", ""); // order selected <option> tags for values in self.items
} else {
for (i = self.items.length - 1; i >= 0; i--) {
value = self.items[i];
option = self.options[value];
label = option[self.settings.labelField] || '';
if (selected.includes(option.$option)) {
const reuse_opt = self.input.querySelector(`option[value="${addSlashes(value)}"]:not([selected])`);
AddSelected(reuse_opt, value, label);
} else {
option.$option = AddSelected(option.$option, value, label);
}
}
}
} else {
self.input.value = self.getValue();
}
if (self.isSetup) {
if (!opts.silent) {
self.trigger('change', self.getValue());
}
}
}
|
JavaScript
|
clear(silent) {
var self = this;
if (!self.items.length) return;
var items = self.controlChildren();
for (const item of items) {
self.removeItem(item, true);
}
self.showInput();
if (!silent) self.updateOriginalInput();
self.trigger('clear');
}
|
clear(silent) {
var self = this;
if (!self.items.length) return;
var items = self.controlChildren();
for (const item of items) {
self.removeItem(item, true);
}
self.showInput();
if (!silent) self.updateOriginalInput();
self.trigger('clear');
}
|
JavaScript
|
async trainBatch(dataset) {
const datasetMap = {};
dataset.forEach(item => this.addTrainer(item.output));
dataset.forEach(item => {
this.labels.forEach(label => {
if (!datasetMap[label]) {
datasetMap[label] = [];
}
datasetMap[label].push({
input: item.input,
output: [item.output === label ? 1 : 0],
});
});
});
const promises = [];
Object.keys(datasetMap).forEach(label => {
promises.push(this.classifierMap[label].train(datasetMap[label]));
});
return Promise.all(promises);
}
|
async trainBatch(dataset) {
const datasetMap = {};
dataset.forEach(item => this.addTrainer(item.output));
dataset.forEach(item => {
this.labels.forEach(label => {
if (!datasetMap[label]) {
datasetMap[label] = [];
}
datasetMap[label].push({
input: item.input,
output: [item.output === label ? 1 : 0],
});
});
});
const promises = [];
Object.keys(datasetMap).forEach(label => {
promises.push(this.classifierMap[label].train(datasetMap[label]));
});
return Promise.all(promises);
}
|
JavaScript
|
parseWord(word) {
let letterArray = [];
for (const letter of word) {
letterArray.push(new Letter(letter));
}
return letterArray;
}
|
parseWord(word) {
let letterArray = [];
for (const letter of word) {
letterArray.push(new Letter(letter));
}
return letterArray;
}
|
JavaScript
|
displayWord() {
let toBeDisplayed = "";
this.lettersLeft = this.characters.length;
this.characters.forEach(letter => {
if (letter.guessed) {
toBeDisplayed += letter.letter + " ";
this.lettersLeft--;
} else {
toBeDisplayed += "_ ";
}
});
if (this.score <= 0) {
this.gameDone = true;
let loseWord = "";
this.characters.forEach(letter => (loseWord += letter.letter));
return loseWord;
} else {
this.gameDone = this.wholeWordGuessed();
return toBeDisplayed;
}
}
|
displayWord() {
let toBeDisplayed = "";
this.lettersLeft = this.characters.length;
this.characters.forEach(letter => {
if (letter.guessed) {
toBeDisplayed += letter.letter + " ";
this.lettersLeft--;
} else {
toBeDisplayed += "_ ";
}
});
if (this.score <= 0) {
this.gameDone = true;
let loseWord = "";
this.characters.forEach(letter => (loseWord += letter.letter));
return loseWord;
} else {
this.gameDone = this.wholeWordGuessed();
return toBeDisplayed;
}
}
|
JavaScript
|
checkGuess(guess) {
// if guess has been made before tell the user
if (this.pastGuesses.includes(guess)) {
return `${this.displayWord()}\n${warning(
`You've already guessed that letter`
)}`;
} else {
// boolean for if guess is in word
let inWord = this.characters.some(l => l.letter == guess);
// push guess to past guesses array
this.pastGuesses.push(guess);
// run checkGuess() method from Letter on each letter
this.characters.forEach(letter => {
letter.checkGuess(guess);
});
// if the guess isn't in the word lower the score
if (!inWord) {
this.score--;
return `${this.displayWord()}\n${lose(`That's incorrect`)}`;
} else {
return `${this.displayWord()}\n${win(`That's correct`)}`;
}
}
}
|
checkGuess(guess) {
// if guess has been made before tell the user
if (this.pastGuesses.includes(guess)) {
return `${this.displayWord()}\n${warning(
`You've already guessed that letter`
)}`;
} else {
// boolean for if guess is in word
let inWord = this.characters.some(l => l.letter == guess);
// push guess to past guesses array
this.pastGuesses.push(guess);
// run checkGuess() method from Letter on each letter
this.characters.forEach(letter => {
letter.checkGuess(guess);
});
// if the guess isn't in the word lower the score
if (!inWord) {
this.score--;
return `${this.displayWord()}\n${lose(`That's incorrect`)}`;
} else {
return `${this.displayWord()}\n${win(`That's correct`)}`;
}
}
}
|
JavaScript
|
function Tooltip(_reference, _options) {
var _this = this;
_classCallCheck(this, Tooltip);
_defineProperty(this, "_events", []);
_defineProperty(this, "_setTooltipNodeEvent", function (evt, reference, delay, options) {
var relatedreference = evt.relatedreference || evt.toElement || evt.relatedTarget;
var callback = function callback(evt2) {
var relatedreference2 = evt2.relatedreference || evt2.toElement || evt2.relatedTarget; // Remove event listener after call
_this._tooltipNode.removeEventListener(evt.type, callback); // If the new reference is not the reference element
if (!reference.contains(relatedreference2)) {
// Schedule to hide tooltip
_this._scheduleHide(reference, options.delay, options, evt2);
}
};
if (_this._tooltipNode.contains(relatedreference)) {
// listen to mouseleave on the tooltip element to be able to hide the tooltip
_this._tooltipNode.addEventListener(evt.type, callback);
return true;
}
return false;
});
// apply user options over default ones
_options = _objectSpread({}, DEFAULT_OPTIONS, _options);
_reference.jquery && (_reference = _reference[0]);
this.show = this.show.bind(this);
this.hide = this.hide.bind(this); // cache reference and options
this.reference = _reference;
this.options = _options; // set initial state
this._isOpen = false;
this._init();
} //
|
function Tooltip(_reference, _options) {
var _this = this;
_classCallCheck(this, Tooltip);
_defineProperty(this, "_events", []);
_defineProperty(this, "_setTooltipNodeEvent", function (evt, reference, delay, options) {
var relatedreference = evt.relatedreference || evt.toElement || evt.relatedTarget;
var callback = function callback(evt2) {
var relatedreference2 = evt2.relatedreference || evt2.toElement || evt2.relatedTarget; // Remove event listener after call
_this._tooltipNode.removeEventListener(evt.type, callback); // If the new reference is not the reference element
if (!reference.contains(relatedreference2)) {
// Schedule to hide tooltip
_this._scheduleHide(reference, options.delay, options, evt2);
}
};
if (_this._tooltipNode.contains(relatedreference)) {
// listen to mouseleave on the tooltip element to be able to hide the tooltip
_this._tooltipNode.addEventListener(evt.type, callback);
return true;
}
return false;
});
// apply user options over default ones
_options = _objectSpread({}, DEFAULT_OPTIONS, _options);
_reference.jquery && (_reference = _reference[0]);
this.show = this.show.bind(this);
this.hide = this.hide.bind(this); // cache reference and options
this.reference = _reference;
this.options = _options; // set initial state
this._isOpen = false;
this._init();
} //
|
JavaScript
|
function Tooltip(_reference, _options) {
var _this = this;
_classCallCheck(this, Tooltip);
_defineProperty(this, "_events", []);
_defineProperty(this, "_setTooltipNodeEvent", function (evt, reference, delay, options) {
var relatedreference = evt.relatedreference || evt.toElement || evt.relatedTarget;
var callback = function callback(evt2) {
var relatedreference2 = evt2.relatedreference || evt2.toElement || evt2.relatedTarget; // Remove event listener after call
_this._tooltipNode.removeEventListener(evt.type, callback); // If the new reference is not the reference element
if (!reference.contains(relatedreference2)) {
// Schedule to hide tooltip
_this._scheduleHide(reference, options.delay, options, evt2);
}
};
if (_this._tooltipNode.contains(relatedreference)) {
// listen to mouseleave on the tooltip element to be able to hide the tooltip
_this._tooltipNode.addEventListener(evt.type, callback);
return true;
}
return false;
});
// apply user options over default ones
_options = _objectSpread({}, DEFAULT_OPTIONS, _options);
_reference.jquery && (_reference = _reference[0]);
this.show = this.show.bind(this);
this.hide = this.hide.bind(this); // cache reference and options
this.reference = _reference;
this.options = _options; // set initial state
this._isOpen = false;
this._init();
} //
|
function Tooltip(_reference, _options) {
var _this = this;
_classCallCheck(this, Tooltip);
_defineProperty(this, "_events", []);
_defineProperty(this, "_setTooltipNodeEvent", function (evt, reference, delay, options) {
var relatedreference = evt.relatedreference || evt.toElement || evt.relatedTarget;
var callback = function callback(evt2) {
var relatedreference2 = evt2.relatedreference || evt2.toElement || evt2.relatedTarget; // Remove event listener after call
_this._tooltipNode.removeEventListener(evt.type, callback); // If the new reference is not the reference element
if (!reference.contains(relatedreference2)) {
// Schedule to hide tooltip
_this._scheduleHide(reference, options.delay, options, evt2);
}
};
if (_this._tooltipNode.contains(relatedreference)) {
// listen to mouseleave on the tooltip element to be able to hide the tooltip
_this._tooltipNode.addEventListener(evt.type, callback);
return true;
}
return false;
});
// apply user options over default ones
_options = _objectSpread({}, DEFAULT_OPTIONS, _options);
_reference.jquery && (_reference = _reference[0]);
this.show = this.show.bind(this);
this.hide = this.hide.bind(this); // cache reference and options
this.reference = _reference;
this.options = _options; // set initial state
this._isOpen = false;
this._init();
} //
|
JavaScript
|
resetInstanceRenderersFor(objectName) {
for (let i in this.renderedInstances) {
if (this.renderedInstances.hasOwnProperty(i)) {
const renderedInstance = this.renderedInstances[i];
if (renderedInstance.getInstance().getObjectName() === objectName) {
renderedInstance.onRemovedFromScene();
delete this.renderedInstances[i];
}
}
}
}
|
resetInstanceRenderersFor(objectName) {
for (let i in this.renderedInstances) {
if (this.renderedInstances.hasOwnProperty(i)) {
const renderedInstance = this.renderedInstances[i];
if (renderedInstance.getInstance().getObjectName() === objectName) {
renderedInstance.onRemovedFromScene();
delete this.renderedInstances[i];
}
}
}
}
|
JavaScript
|
_destroyUnusedInstanceRenderers() {
for (let i in this.renderedInstances) {
if (this.renderedInstances.hasOwnProperty(i)) {
const renderedInstance = this.renderedInstances[i];
if (!renderedInstance.wasUsed) {
renderedInstance.onRemovedFromScene();
delete this.renderedInstances[i];
} else renderedInstance.wasUsed = false;
}
}
}
|
_destroyUnusedInstanceRenderers() {
for (let i in this.renderedInstances) {
if (this.renderedInstances.hasOwnProperty(i)) {
const renderedInstance = this.renderedInstances[i];
if (!renderedInstance.wasUsed) {
renderedInstance.onRemovedFromScene();
delete this.renderedInstances[i];
} else renderedInstance.wasUsed = false;
}
}
}
|
JavaScript
|
toggle() {
this.save({
completed: !this.get('completed')
});
}
|
toggle() {
this.save({
completed: !this.get('completed')
});
}
|
JavaScript
|
function offsetToPercentage(g, offsetX) {
// This is calculating the pixel offset of the leftmost date.
var xOffset = g.toDomCoords(g.xAxisRange()[0], null)[0];
// x y w and h are relative to the corner of the drawing area,
// so that the upper corner of the drawing area is (0, 0).
var x = offsetX - xOffset;
// This is computing the rightmost pixel, effectively defining the
// width.
var w = g.toDomCoords(g.xAxisRange()[1], null)[0] - xOffset;
// Percentage from the left.
var xPct = w == 0 ? 0 : (x / w);
// The (1-) part below changes it from "% distance down from the top"
// to "% distance up from the bottom".
return xPct;
}
|
function offsetToPercentage(g, offsetX) {
// This is calculating the pixel offset of the leftmost date.
var xOffset = g.toDomCoords(g.xAxisRange()[0], null)[0];
// x y w and h are relative to the corner of the drawing area,
// so that the upper corner of the drawing area is (0, 0).
var x = offsetX - xOffset;
// This is computing the rightmost pixel, effectively defining the
// width.
var w = g.toDomCoords(g.xAxisRange()[1], null)[0] - xOffset;
// Percentage from the left.
var xPct = w == 0 ? 0 : (x / w);
// The (1-) part below changes it from "% distance down from the top"
// to "% distance up from the bottom".
return xPct;
}
|
JavaScript
|
function zoom(g, zoomInPercentage, xBias) {
xBias = xBias || 0.5;
function adjustAxis(axis, zoomInPercentage, bias) {
var delta = axis[1] - axis[0];
var increment = delta * zoomInPercentage;
var foo = [increment * bias, increment * (1-bias)];
return [ axis[0] + foo[0], axis[1] - foo[1] ];
}
var newWindow = adjustAxis(g.xAxisRange(), zoomInPercentage, xBias);
var windowLimits = g.getOption('dateWindowLimits') || g.xAxisExtremes();
if (newWindow[0] < windowLimits[0]) {
newWindow[0] = windowLimits[0];
}
if (newWindow[1] > windowLimits[1]) {
newWindow[1] = windowLimits[1];
}
g.updateOptions({
dateWindow: newWindow
});
}
|
function zoom(g, zoomInPercentage, xBias) {
xBias = xBias || 0.5;
function adjustAxis(axis, zoomInPercentage, bias) {
var delta = axis[1] - axis[0];
var increment = delta * zoomInPercentage;
var foo = [increment * bias, increment * (1-bias)];
return [ axis[0] + foo[0], axis[1] - foo[1] ];
}
var newWindow = adjustAxis(g.xAxisRange(), zoomInPercentage, xBias);
var windowLimits = g.getOption('dateWindowLimits') || g.xAxisExtremes();
if (newWindow[0] < windowLimits[0]) {
newWindow[0] = windowLimits[0];
}
if (newWindow[1] > windowLimits[1]) {
newWindow[1] = windowLimits[1];
}
g.updateOptions({
dateWindow: newWindow
});
}
|
JavaScript
|
function checkFlexGap() {
var flex = document.createElement("div");
flex.style.display = "flex";
flex.style.flexDirection = "column";
flex.style.rowGap = "1px";
flex.appendChild(document.createElement("div"));
flex.appendChild(document.createElement("div"));
document.body.appendChild(flex);
var isSupported = flex.scrollHeight === 1;
flex.parentNode.removeChild(flex);
console.log(isSupported);
if (!isSupported) document.body.classList.add("no-flexbox-gap");
}
|
function checkFlexGap() {
var flex = document.createElement("div");
flex.style.display = "flex";
flex.style.flexDirection = "column";
flex.style.rowGap = "1px";
flex.appendChild(document.createElement("div"));
flex.appendChild(document.createElement("div"));
document.body.appendChild(flex);
var isSupported = flex.scrollHeight === 1;
flex.parentNode.removeChild(flex);
console.log(isSupported);
if (!isSupported) document.body.classList.add("no-flexbox-gap");
}
|
JavaScript
|
commit_msg(messageFileName) {
const branchName = this.git.currentBranchName();
const issue = this.isIssueBranch(branchName);
if (issue) {
this.fs.appendFileSync(messageFileName, `\nrefs #${issue.id}`);
}
}
|
commit_msg(messageFileName) {
const branchName = this.git.currentBranchName();
const issue = this.isIssueBranch(branchName);
if (issue) {
this.fs.appendFileSync(messageFileName, `\nrefs #${issue.id}`);
}
}
|
JavaScript
|
leaveIssueBranch(issue, branchName) {
if (this.config.autoLogTime) {
const checkedout = new Date(this.getCheckoutTime(branchName)).getTime();
if (checkedout) {
const now = new Date().getTime();
const delta = this.getTimeDelta(checkedout, now);
const logTime = delta.toFixed(2);
const spentOn = new Date().toISOString().split('T')[0];
if (this.config.isTTY) {
console.log(`Zeit auf #${issue.id}: ${logTime}h`);
}
if (logTime != '0.00') {
this.logTime(issue.id, logTime, this.getActivityId(issue.type), spentOn);
}
}
}
}
|
leaveIssueBranch(issue, branchName) {
if (this.config.autoLogTime) {
const checkedout = new Date(this.getCheckoutTime(branchName)).getTime();
if (checkedout) {
const now = new Date().getTime();
const delta = this.getTimeDelta(checkedout, now);
const logTime = delta.toFixed(2);
const spentOn = new Date().toISOString().split('T')[0];
if (this.config.isTTY) {
console.log(`Zeit auf #${issue.id}: ${logTime}h`);
}
if (logTime != '0.00') {
this.logTime(issue.id, logTime, this.getActivityId(issue.type), spentOn);
}
}
}
}
|
JavaScript
|
tabular(issue, specs) {
return [
(i, p) => this.pad(i.id.toString(), p),
(i, p) => this.pad(i.priority.name, p),
(i, p) => this.pad(i.tracker.name, p),
(i, p) => this.pad(i.status.name, p),
(i, p) => colors.green(i.subject),
]
.map((getter, idx) => getter(issue, specs[idx]))
.join(' | ');
}
|
tabular(issue, specs) {
return [
(i, p) => this.pad(i.id.toString(), p),
(i, p) => this.pad(i.priority.name, p),
(i, p) => this.pad(i.tracker.name, p),
(i, p) => this.pad(i.status.name, p),
(i, p) => colors.green(i.subject),
]
.map((getter, idx) => getter(issue, specs[idx]))
.join(' | ');
}
|
JavaScript
|
addAudio (newMusic) {
this.events.trigger('addaudio', newMusic);
const wasSingle = !this.isMultiple();
this.options.audio = this.options.audio.concat(newMusic);
let newItemHTML = ``;
for (let i = 0; i < newMusic.length; i++) {
newItemHTML += `
<li>
<span class="aplayer-list-cur" style="background: ${newMusic[i].theme || this.options.theme};"></span>
<span class="aplayer-list-index">${this.options.audio.length - newMusic.length + i + 1}</span>
<span class="aplayer-list-title">${newMusic[i].name}</span>
<span class="aplayer-list-author">${newMusic[i].artist}</span>
</li>`;
}
this.template.listOl.innerHTML += newItemHTML;
if (wasSingle && this.isMultiple()) {
this.container.classList.add('aplayer-withlist');
this.audio.loop = false;
}
this.template.list.style.height = this.options.audio.length * 33 - 1 + 'px';
this.template.listOl.style.height = this.options.audio.length * 33 - 1 + 'px';
this.randomOrder = utils.randomOrder(this.options.audio.length);
this.template.listCurs = this.container.querySelectorAll('.aplayer-list-cur');
}
|
addAudio (newMusic) {
this.events.trigger('addaudio', newMusic);
const wasSingle = !this.isMultiple();
this.options.audio = this.options.audio.concat(newMusic);
let newItemHTML = ``;
for (let i = 0; i < newMusic.length; i++) {
newItemHTML += `
<li>
<span class="aplayer-list-cur" style="background: ${newMusic[i].theme || this.options.theme};"></span>
<span class="aplayer-list-index">${this.options.audio.length - newMusic.length + i + 1}</span>
<span class="aplayer-list-title">${newMusic[i].name}</span>
<span class="aplayer-list-author">${newMusic[i].artist}</span>
</li>`;
}
this.template.listOl.innerHTML += newItemHTML;
if (wasSingle && this.isMultiple()) {
this.container.classList.add('aplayer-withlist');
this.audio.loop = false;
}
this.template.list.style.height = this.options.audio.length * 33 - 1 + 'px';
this.template.listOl.style.height = this.options.audio.length * 33 - 1 + 'px';
this.randomOrder = utils.randomOrder(this.options.audio.length);
this.template.listCurs = this.container.querySelectorAll('.aplayer-list-cur');
}
|
JavaScript
|
function updatePosition(str) {
var lines = str.match(/\n/g);
if (lines) lineno += lines.length;
var i = str.lastIndexOf('\n');
column = ~i ? str.length - i : column + str.length;
}
|
function updatePosition(str) {
var lines = str.match(/\n/g);
if (lines) lineno += lines.length;
var i = str.lastIndexOf('\n');
column = ~i ? str.length - i : column + str.length;
}
|
JavaScript
|
function Position(start) {
this.start = start;
this.end = { line: lineno, column: column };
this.source = options.source;
}
|
function Position(start) {
this.start = start;
this.end = { line: lineno, column: column };
this.source = options.source;
}
|
JavaScript
|
function _compileAtrule(name) {
var re = new RegExp('^@' + name + '\\s*([^;]+);');
return function() {
var pos = position();
var m = match(re);
if (!m) return;
var ret = { type: name };
ret[name] = m[1].trim();
return pos(ret);
}
}
|
function _compileAtrule(name) {
var re = new RegExp('^@' + name + '\\s*([^;]+);');
return function() {
var pos = position();
var m = match(re);
if (!m) return;
var ret = { type: name };
ret[name] = m[1].trim();
return pos(ret);
}
}
|
JavaScript
|
function addParent(obj, parent) {
var isNode = obj && typeof obj.type === 'string';
var childParent = isNode ? obj : parent;
for (var k in obj) {
var value = obj[k];
if (Array.isArray(value)) {
value.forEach(function(v) { addParent(v, childParent); });
} else if (value && typeof value === 'object') {
addParent(value, childParent);
}
}
if (isNode) {
Object.defineProperty(obj, 'parent', {
configurable: true,
writable: true,
enumerable: false,
value: parent || null
});
}
return obj;
}
|
function addParent(obj, parent) {
var isNode = obj && typeof obj.type === 'string';
var childParent = isNode ? obj : parent;
for (var k in obj) {
var value = obj[k];
if (Array.isArray(value)) {
value.forEach(function(v) { addParent(v, childParent); });
} else if (value && typeof value === 'object') {
addParent(value, childParent);
}
}
if (isNode) {
Object.defineProperty(obj, 'parent', {
configurable: true,
writable: true,
enumerable: false,
value: parent || null
});
}
return obj;
}
|
JavaScript
|
function SourceMapGenerator(aArgs) {
if (!aArgs) {
aArgs = {};
}
this._file = util.getArg(aArgs, 'file', null);
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = new MappingList();
this._sourcesContents = null;
}
|
function SourceMapGenerator(aArgs) {
if (!aArgs) {
aArgs = {};
}
this._file = util.getArg(aArgs, 'file', null);
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = new MappingList();
this._sourcesContents = null;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.