text
stringlengths 7
3.69M
|
|---|
(function () {
'use strict';
angular.module('workSiteSOP', []);
}());
|
import { setFunctionName } from '../utils/setFunctionName';
import { postForm } from '../utils/postForm';
import { PATHNAME_TEMPLATE, RESOURCE_NAME } from './constants';
/**
* @param {number} websiteId
* @param {Object} formValues
* @return {Promise}
*/
export const post = (websiteId, formValues) =>
postForm(PATHNAME_TEMPLATE, websiteId, formValues);
setFunctionName(post, RESOURCE_NAME);
|
/****************************************************************************************
* LiveZilla ChatServerEvaluationClass.js
*
* Copyright 2013 LiveZilla GmbH
* All rights reserved.
* LiveZilla is a registered trademark.
*
***************************************************************************************/
function ChatServerEvaluationClass(lzm_commonTools, chosenProfile, lzm_chatTimeStamp) {
// load the configuration file
this.lzm_commonConfig = new CommonConfigClass();
this.lzm_commonTools = lzm_commonTools;
this.lzm_chatTimeStamp = lzm_chatTimeStamp;
// variables filled from the server response
this.myName = '';
this.myId = '';
this.myGroup = '';
this.myUserId = '';
this.chosen_profile = {};
this.serverUrl = chosenProfile.server_url;
this.serverProtocol = chosenProfile.server_protocol;
this.loginTime = lzm_chatTimeStamp.getServerTimeString(null, false, 1);
this.permissions = [];
this.global_configuration = {};
this.extForwardIdList = [];
this.external_forwards = [];
this.chats = [];
this.active_chat = '';
this.active_chat_reco = '';
this.external_users = [];
this.newExternalUsers = [];
this.changedExternalUsers = [];
this.tickets = [];
this.ticketGlobalValues = {p: 20, q: 0, t: 0, r: 0, e: 0};
this.ticketFetchTime = 0;
this.login_data = {};
this.extUserIdList = [];
this.global_typing = [];
this.globTypingIdList = [];
this.globalTypingChanges = [];
this.internal_departments = [];
this.internal_users = [];
this.global_errors = [];
this.wps = [];
this.chatIdList = [];
this.chatMessageCounter = 0;
this.browserChatIdList = [];
this.chatObject = {};
this.chatPartners = {};
this.rec_posts = [];
//this.incoming_chats = [];
this.chatArchive = {chats: [], q: '', p: 20, t: 0};
this.archiveFetchTime = 0;
this.fuprs = [];
this.fuprIdList = [];
this.fuprDownloadIdList = [];
this.settingsDialogue = false;
this.resources = [];
this.resourceIdList = [];
this.resourceLastEdited = 0;
this.emails = [];
this.emailCount = 0;
this.filters = new LzmFilters();
this.pollFrequency = 0;
this.timeoutClients = 0;
this.siteName = '';
this.defaultLanguage = '';
this.userLanguage = '';
this.inputList = new LzmCustomInputs();
this.new_ext_u = false;
this.new_ext_f = false;
this.new_ext_c = false;
this.new_usr_p = false;
this.new_int_d = false;
this.new_int_u = false;
this.new_glt = false;
this.new_ev = false;
this.new_dt = false;
this.new_de = false;
this.new_dc = false;
this.new_qrd = false;
this.new_ext_b = false;
this.new_gl_e = false;
}
ChatServerEvaluationClass.prototype.resetWebApp = function() {
this.global_configuration = {};
this.extForwardIdList = [];
this.external_forwards = [];
//this.chats = [];
this.active_chat = '';
this.active_chat_reco = '';
var tmpExternalUsers = [];
var tmpExtUserIdList = [];
for (var i=0; i<this.external_users.length; i++) {
for (var j=0; j<this.external_users[i].b.length; j++)
var tmpChatId = this.external_users[i].id + '~' + this.external_users[i].b[j].id;
if (typeof this.chatObject[tmpChatId] != 'undefined' &&
$.inArray(tmpChatId ,lzm_chatDisplay.closedChats) == -1) {
this.external_users[i].is_active = false;
tmpExternalUsers.push(this.external_users[i]);
tmpExtUserIdList.push(this.external_users[i].id);
}
}
this.external_users = tmpExternalUsers;
this.extUserIdList = tmpExtUserIdList;
this.newExternalUsers = [];
this.changedExternalUsers = [];
this.global_typing = [];
this.globTypingIdList = [];
this.internal_departments = [];
this.internal_users = [];
this.global_errors = [];
this.wps = [];
this.chatPartners = {};
this.rec_posts = [];
this.chatArchive = {chats: [], q: '', p: 20, t: 0};
this.fuprs = [];
this.fuprIdList = [];
this.fuprDownloadIdList = [];
this.settingsDialogue = false;
this.filters.clearFilters();
this.customInput.clearCustomInputs();
this.new_ext_u = true;
this.new_ext_f = true;
this.new_ext_c = true;
this.new_usr_p = true;
this.new_int_d = true;
this.new_int_u = true;
this.new_glt = true;
this.new_ev = true;
this.new_dt = true;
this.new_de = true;
this.new_dc = true;
this.new_qrd = true;
this.new_gl_e = true;
this.new_ext_b = true;
};
/**
* Add a new chat created by a local method to the chats array
* @param new_chat
*/
ChatServerEvaluationClass.prototype.addNewChat = function (new_chat) {
new_chat.text = this.replaceLinks(new_chat.text);
//console.log(new_chat.text);
this.chats.push(new_chat);
return true;
};
/**
* Get the server's response for the login
* @param xmlDoc
*/
ChatServerEvaluationClass.prototype.getLogin = function (xmlDoc) {
var thisClass = this;
$(xmlDoc).find('login').each(function () {
var login = $(this);
login.children('login_return').each(function () {
var myReturn = $(this);
var myAttributes = myReturn[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
thisClass.login_data[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
if (typeof thisClass.login_data.perms != 'undefined' && thisClass.login_data.perms != '') {
thisClass.permissions = thisClass.login_data.perms.split('');
lzm_commonPermissions.getUserPermissions(true);
}
});
thisClass.myName = thisClass.login_data.name;
thisClass.myId = thisClass.login_data.sess;
if (typeof thisClass.login_data != 'undefined' && typeof thisClass.login_data.timediff != 'undefined') {
thisClass.lzm_chatTimeStamp.setTimeDifference(thisClass.login_data.timediff);
}
});
};
/**
* Get the global configuration from the server's response and create an objet with its contents
* @param xmlDoc
*/
ChatServerEvaluationClass.prototype.getGlobalConfiguration = function (xmlDoc) {
var thisClass = this;
var myHash = '';
$(xmlDoc).find('gl_c').each(function () {
//console.log(this);
var gl_c = $(this);
if (typeof thisClass.global_configuration.toplevel == 'undefined') {
thisClass.global_configuration.toplevel = [];
}
if (typeof thisClass.global_configuration.site == 'undefined') {
thisClass.global_configuration.site = {};
}
if (typeof thisClass.global_configuration.php_cfg_vars == 'undefined') {
thisClass.global_configuration.php_cfg_vars = {};
}
$(gl_c).children('conf').each(function () {
var conf = $(this);
var new_conf = {};
new_conf.key = lz_global_base64_url_decode(conf.attr('key'));
new_conf.value = lz_global_base64_url_decode(conf.attr('value'));
new_conf.subkeys = {};
$(conf).find('sub').each(function () {
new_conf.subkeys[lz_global_base64_url_decode($(this).attr('key'))] = lz_global_base64_url_decode($(this).text());
});
thisClass.global_configuration.toplevel.push(new_conf);
});
$(gl_c).children('site').each(function () {
var site = $(this);
var index = lz_global_base64_url_decode(site.attr('index'));
if (typeof thisClass.global_configuration.site[index] == 'undefined') {
thisClass.global_configuration.site[index] = [];
}
$(site).find('conf').each(function () {
var conf = $(this);
var new_conf = {};
new_conf.key = lz_global_base64_url_decode(conf.attr('key'));
new_conf.value = lz_global_base64_url_decode(conf.attr('value'));
new_conf.subkeys = {};
$(conf).find('sub').each(function () {
new_conf.subkeys[lz_global_base64_url_decode($(this).attr('key'))] = lz_global_base64_url_decode($(this).text());
//console.log(lz_global_base64_url_decode($(this).attr('key')) + ' --- ' + lz_global_base64_url_decode($(this).text()));
});
thisClass.global_configuration.site[index].push(new_conf);
});
});
$(gl_c).children('php_cfg_vars').each(function () {
thisClass.global_configuration.php_cfg_vars['post_max_size'] = lz_global_base64_url_decode($(this).attr('post_max_size'));
thisClass.global_configuration.php_cfg_vars['upload_max_filesize'] = lz_global_base64_url_decode($(this).attr('upload_max_filesize'));
});
myHash = lz_global_base64_url_decode(gl_c.attr('h'));
for (var i=0; i<thisClass.global_configuration.site[0].length; i++) {
if (thisClass.global_configuration.site[0][i].key == 'gl_input_list') {
//console.log(thisClass.global_configuration.site[0][i]);
for (var key in thisClass.global_configuration.site[0][i].subkeys) {
if (thisClass.global_configuration.site[0][i].subkeys.hasOwnProperty(key)) {
var customInput = {id: key, value: thisClass.global_configuration.site[0][i].subkeys[key]};
thisClass.inputList.setCustomInput(customInput);
}
}
}
}
thisClass.setConfigValues(thisClass.global_configuration);
});
return myHash;
};
ChatServerEvaluationClass.prototype.setConfigValues = function(global_config) {
for (var i=0; i<global_config.toplevel.length; i++) {
for (var key in global_config.toplevel[i].subkeys) {
if (global_config.toplevel[i].subkeys.hasOwnProperty(key)) {
if (key == 'poll_frequency_clients') {
this.pollFrequency = global_config.toplevel[i].subkeys[key];
//console.log(key + ': ' + global_config.toplevel[i].subkeys[key]);
}
if (key == 'timeout_clients') {
this.timeoutClients = global_config.toplevel[i].subkeys[key];
//console.log(key + ': ' + global_config.toplevel[i].subkeys[key]);
}
if (key == 'gl_site_name') {
this.siteName = global_config.toplevel[i].subkeys[key];
$('title').html(this.siteName);
//console.log(key + ': ' + global_config.toplevel[i].subkeys[key]);
}
if (key == 'gl_default_language') {
this.defaultLanguage = global_config.toplevel[i].subkeys[key];
//console.log(key + ': ' + global_config.toplevel[i].subkeys[key]);
}
}
}
}
};
ChatServerEvaluationClass.prototype.debuggingReadKeyValuePairFromConfig = function(keyPart) {
var i, index;
console.log('Top level');
for (i=0; i<this.global_configuration.toplevel.length; i++) {
if (this.global_configuration.toplevel[i].key.indexOf(keyPart) != -1 && this.global_configuration.toplevel[i].value != '') {
index = this.lzm_commonTools.pad(i, 4, 0);
console.log(index + ' : ' + this.global_configuration.toplevel[i].key + ' - ' + this.global_configuration.toplevel[i].value);
}
}
for (var key in this.global_configuration.site) {
if (this.global_configuration.site.hasOwnProperty(key)) {
console.log('');
console.log('Site ' + key);
for (i=0; i<this.global_configuration.site[key].length; i++) {
index = this.lzm_commonTools.pad(i, 4, 0);
if (this.global_configuration.site[key][i].key.indexOf(keyPart) != -1 && this.global_configuration.site[key][i].value != '') {
console.log(index + ' : ' + this.global_configuration.site[key][i].key + ' - ' + this.global_configuration.site[key][i].value);
}
}
}
}
};
/**
* Get the requests for forwardings of chats from the server's xml response
* @param xmlDoc
*/
ChatServerEvaluationClass.prototype.getExternalForward = function (xmlDoc) {
var thisClass = this;
var myHash = '';
$(xmlDoc).find('ext_f').each(function () {
//console.log(this);
thisClass.new_ext_f = true;
var ext_f = $(this);
$(ext_f).find('fw').each(function () {
var fw = $(this);
var new_forward = {};
var myAttributes = fw[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
new_forward[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
if ($.inArray(new_forward.id, thisClass.extForwardIdList) == -1) {
thisClass.extForwardIdList.push(new_forward.id);
thisClass.external_forwards.push(new_forward);
var fwdByName = new_forward.i;
var fwdFromName = new_forward.s;
var fwdToName = new_forward.r;
for (var intUserIndex=0; intUserIndex< thisClass.internal_users.length; intUserIndex++) {
if (new_forward.i == thisClass.internal_users[intUserIndex].id) {
fwdByName = thisClass.internal_users[intUserIndex].name;
}
if (new_forward.s == thisClass.internal_users[intUserIndex].id) {
fwdFromName = thisClass.internal_users[intUserIndex].name;
}
if (new_forward.r == thisClass.internal_users[intUserIndex].id) {
fwdToName = thisClass.internal_users[intUserIndex].name;
}
}
var extUserId = new_forward.u.split('~')[0];
var extUserBId = new_forward.u.split('~')[1];
var extUserName = '';
for (var extUserIndex=0; extUserIndex<thisClass.external_users.length; extUserIndex++) {
if (thisClass.external_users[extUserIndex].id == extUserId) {
for (var browserIndex=0; browserIndex<thisClass.external_users[extUserIndex].b.length; browserIndex++) {
if (thisClass.external_users[extUserIndex].b[browserIndex].id == extUserBId) {
extUserName = (thisClass.external_users[extUserIndex].b[browserIndex].cname != '') ?
thisClass.external_users[extUserIndex].b[browserIndex].cname :
thisClass.external_users[extUserIndex].unique_name;
break;
}
}
break;
}
}
extUserName = lzm_commonTools.htmlEntities(extUserName);
var chatText = t('<!--visitor_name--> was forwarded by <!--fwd_by_name--> from <!--fwd_from_name--> to <!--my_name-->.',
[['<!--visitor_name-->','<b>'+extUserName+'</b>'],['<!--fwd_by_name-->','<b>'+fwdByName+'</b>'],
['<!--fwd_from_name-->','<b>'+fwdFromName+'</b>'],['<!--my_name-->','<b>'+fwdToName+'</b>']]);
if (new_forward.s == '') {
chatText = t('<!--visitor_name--> was forwarded by <!--fwd_by_name--> to <!--my_name-->.',
[['<!--visitor_name-->','<b>'+extUserName+'</b>'],['<!--fwd_by_name-->','<b>'+fwdByName+'</b>'],
['<!--fwd_from_name-->','<b>'+fwdFromName+'</b>'],['<!--my_name-->','<b>'+fwdToName+'</b>']]);
}
if (new_forward.t != '' && new_forward.r == thisClass.myId) {
chatText += ' ' + t(' Additional comment: <!--fwd_comment-->', [['<!--fwd_comment-->', '<b>'+new_forward.t+'</b>']]);
}
var new_chat = {};
new_chat.id = md5(String(Math.random())).substr(0, 32);
new_chat.rp = '';
new_chat.sen = '0000000';
new_chat.rec = '';
new_chat.reco = new_forward.u;
var tmpdate = lzm_chatTimeStamp.getLocalTimeObject();
new_chat.date = lzm_chatTimeStamp.getServerTimeString(tmpdate, true);
new_chat.cmc = thisClass.chatMessageCounter++;
thisClass.chatMessageCounter++;
new_chat.date_human = lzm_commonTools.getHumanDate(tmpdate, 'date', thisClass.userLanguage);
new_chat.time_human = lzm_commonTools.getHumanDate(tmpdate, 'time', thisClass.userLanguage);
new_chat.text = chatText;
thisClass.addNewChat(new_chat);
} else {
for (var i = 0; i < thisClass.external_forwards.length; i++) {
for (var key in thisClass.external_forwards[i]) {
if (thisClass.external_forwards[i].hasOwnProperty(key)) {
if (new_forward[key] != '' && typeof new_forward[key] != 'undefined') {
thisClass.external_forwards[i][key] = new_forward[key];
}
}
}
}
}
//console.log(new_forward.r, new_forward.u);
//console.log(thisClass.chatObject[new_forward.u]);
for (var chatIndex = 0; chatIndex < thisClass.chats.length; chatIndex++) {
if (new_forward.r == thisClass.myId && (thisClass.chats[chatIndex].sen == new_forward.u ||
thisClass.chats[chatIndex].reco == new_forward.u)) {
//console.log(thisClass.chats[chatIndex]);
//if (thisClass.settingsDialogue || thisClass.chats[chatIndex].sen_id != thisClass.active_chat) {
if (thisClass.chats[chatIndex].sen != '0000000' &&
thisClass.chats[chatIndex].sen != thisClass.myId &&
(thisClass.chats[chatIndex].sen.indexOf('~') != -1)) {
if (typeof thisClass.chatObject[thisClass.chats[chatIndex].sen] == 'undefined') {
thisClass.chatObject[thisClass.chats[chatIndex].sen] = {
status: 'new', type: 'external', data: [], id: thisClass.chats[chatIndex].sen_id, b_id: thisClass.chats[chatIndex].sen_b_id
};
//logit(thisClass.chatObject[thisClass.chats[chatIndex].sen]);
}
//console.log('New here');
thisClass.chatObject[thisClass.chats[chatIndex].sen]['data'].push(thisClass.chats[chatIndex]);
}
//}
}
}
});
myHash = lz_global_base64_url_decode(ext_f.attr('h'));
});
return myHash;
};
/**
* Get the external users from the server's xml response
* @param xmlDoc
*/
ChatServerEvaluationClass.prototype.getExternalUsers = function (xmlDoc) {
var thisClass = this;
var myHash = '';
var tmpExtUsers = [];
var tmpExtUserIdList = [];
for (var i=0; i<thisClass.external_users.length; i++) {
//console.log('Checking user ' + thisClass.external_users[i].id);
//console.log(thisClass.external_users[i].is_active);
if (thisClass.external_users[i].is_active || isVisitorNeededInGui(thisClass.external_users[i].id)) {
tmpExtUsers.push(thisClass.external_users[i]);
tmpExtUserIdList.push(thisClass.external_users[i].id);
//console.log('Keep user ' + thisClass.external_users[i].id);
} else {
//console.log('Remove user ' + thisClass.external_users[i].id);
}
}
thisClass.external_users = tmpExtUsers;
thisClass.extUserIdList = tmpExtUserIdList;
$(xmlDoc).find('ext_u').each(function () {
//logit(this);
var ext_u = $(this);
thisClass.new_ext_u = true;
// Get the user data
$(ext_u).find('v').each(function () {
var v = $(this);
thisClass.addExtUserV(v);
});
$(ext_u).find('cd').each(function () {
var cd = $(this);
thisClass.addExtUserCd(cd);
});
myHash = lz_global_base64_url_decode(ext_u.attr('h'));
});
return myHash;
};
ChatServerEvaluationClass.prototype.getGlobalTyping = function(xmlDoc) {
var thisClass = this;
var myHash = '', oldTypingIdList = [];
$(xmlDoc).find('gl_typ').each(function () {
thisClass.new_glt = true;
oldTypingIdList = thisClass.globTypingIdList;
thisClass.global_typing = [];
thisClass.globTypingIdList = [];
var gl_typ = $(this);
$(gl_typ).find('v').each(function() {
var thisGlTyp = {
id: lz_global_base64_url_decode($(this).attr('id')),
tp: lz_global_base64_url_decode($(this).attr('tp'))
};
thisClass.global_typing.push(thisGlTyp);
thisClass.globTypingIdList.push(thisGlTyp.id);
if (thisGlTyp.id.indexOf('~') != -1) {
if ($.inArray(thisGlTyp.id, oldTypingIdList) == -1) {
thisClass.globalTypingChanges.push(thisGlTyp.id.split('~')[0]);
//console.log('Add ' + thisGlTyp.id + ' to changes list, because it was not in old');
}
}
});
for (var i=0; i<oldTypingIdList.length; i++) {
if (oldTypingIdList[i].indexOf('~') != -1) {
if ($.inArray(oldTypingIdList[i], thisClass.globTypingIdList) == -1) {
thisClass.globalTypingChanges.push(oldTypingIdList[i].split('~')[0]);
//console.log('Add ' + oldTypingIdList[i] + ' to changes list, because it is not in new');
}
}
}
myHash = lz_global_base64_url_decode(gl_typ.attr('h'));
});
return myHash;
};
/**
* Add the external user's cd value
* @param cd
*/
ChatServerEvaluationClass.prototype.addExtUserCd = function (cd) {
var thisClass = this;
var cdId = lz_global_base64_url_decode(cd.attr('id'));
var externalUserIndex = 0;
var i = 0;
for (i = 0; i < thisClass.external_users.length; i++) {
if (thisClass.external_users[i].id == cdId) {
externalUserIndex = i;
break;
}
}
var bdExists = false;
$(cd).find('bd').each(function () {
var bd = $(this);
thisClass.addExtUserCdBd(bd, externalUserIndex, cdId);
bdExists = bdExists || true;
});
var userIsActive = false;
if (cdId == thisClass.external_users[externalUserIndex].id && bdExists) {
for (i = 0; i < thisClass.external_users[externalUserIndex].b.length; i++) {
userIsActive = userIsActive || thisClass.external_users[externalUserIndex].b[i].is_active;
if (typeof thisClass.chatObject[thisClass.external_users[externalUserIndex].id + '~' + thisClass.external_users[externalUserIndex].b[i].id] != 'undefined') {
if (!thisClass.external_users[externalUserIndex].b[i].is_active) {
markVisitorAsLeft(thisClass.external_users[externalUserIndex].id, thisClass.external_users[externalUserIndex].b[i].id);
try {
//console.log('Left in add cd');
//console.log('This chat\'s browser is inactive');
} catch(ex) {
// Do nothing!
}
}
}
}
}
thisClass.external_users[externalUserIndex].is_active = userIsActive;
if (!userIsActive) {
var matchString = new RegExp('^' + cdId + '~');
//console.log(matchString);
for (var sender in thisClass.chatObject) {
if (thisClass.chatObject.hasOwnProperty(sender)) {
if (sender.match(matchString) != null) {
markVisitorAsLeft(sender.split('~')[0], sender.split('~')[1])
}
}
}
if (cdId == thisClass.external_users[externalUserIndex].id) {
try {
//console.log(cdId + ' --- ' + thisClass.external_users[externalUserIndex].id);
//console.log('Left in add cd');
//console.log('The user is inactive');
} catch(ex) {
// Do nothing!
}
for (i=0; i<thisClass.external_users[externalUserIndex].b.length; i++) {
//console.log(thisClass.external_users[externalUserIndex].b[i].id + ' --- ' + thisClass.external_users[externalUserIndex].b[i].is_active);
if (thisClass.external_users[externalUserIndex].b[i].is_active) {
thisClass.external_users[externalUserIndex].b[i].is_active = false;
var historyLength = thisClass.external_users[externalUserIndex].b[i].h2.length;
thisClass.external_users[externalUserIndex].b[i].h2[historyLength - 1].time2 = lzm_chatTimeStamp.getServerTimeString();
}
//console.log(thisClass.external_users[externalUserIndex].b[i].id + ' --- ' + thisClass.external_users[externalUserIndex].b[i].is_active);
}
}
}
};
/**
* Add the external user's bd value to its cd
* @param bd
*/
ChatServerEvaluationClass.prototype.addExtUserCdBd = function (bd, externalUserIndex, cdId) {
var thisClass = this;
var bdId = lz_global_base64_url_decode(bd.attr('id'));
for (var i = 0; i < thisClass.external_users[externalUserIndex].b.length; i++) {
if (thisClass.external_users[externalUserIndex].b[i].id == bdId) {
thisClass.external_users[externalUserIndex].b[i].is_active = false;
var historyLength = thisClass.external_users[externalUserIndex].b[i].h2.length;
thisClass.external_users[externalUserIndex].b[i].h2[historyLength - 1].time2 = lzm_chatTimeStamp.getServerTimeString();
//console.log(thisClass.external_users[externalUserIndex].id + '~' + bdId + ' has left!');
if (typeof thisClass.chatObject[thisClass.external_users[externalUserIndex].id + '~' + bdId] != 'undefined') {
markVisitorAsLeft(thisClass.external_users[externalUserIndex].id, bdId);
try {
//console.log('Left in add bd');
} catch(ex) {
// Do nothing!
}
}
break;
}
}
};
ChatServerEvaluationClass.prototype.addExtUserR = function(r) {
var new_r = {};
var myAttributes = r[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
new_r[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
new_r.text = lz_global_base64_url_decode(r.text());
return new_r;
};
ChatServerEvaluationClass.prototype.addExtUserC = function(c) {
var new_c = {};
var myAttributes = c[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
new_c[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
new_c.text = lz_global_base64_url_decode(c.text());
return new_c;
};
/**
* Add the values of the b object to the external user
* @param b
* @return {Object}
*/
ChatServerEvaluationClass.prototype.addExtUserVB = function (b, id, unique_name) {
var thisClass = this;
var new_b = {};
var myAttributes = b[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
new_b[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
//console.log(new_b.id + ': ' + JSON.stringify(new_b));
new_b.h = {time: '', url: '', title: '', code: '', cp: ''};
new_b.h2 = [];
new_b.fupr = {};
new_b.is_active = true;
new_b.chat = {id: ''};
$(b).find('h').each(function () {
var h = $(this);
new_b.h = thisClass.addExtUserVBH(h);
new_b.h2.push(thisClass.addExtUserVBH(h));
});
$(b).find('chat').each(function () {
var chat = $(this);
new_b.chat = thisClass.addExtUserVBChat(chat, id, new_b.id);
});
//console.log(new_b.id + ' --- ' + new_b.chat.id);
$(b).find('fupr').each(function () {
var fupr = $(this);
var name = (new_b.cname != '') ? new_b.cname : unique_name;
thisClass.addExtUserVBFupr(fupr, id, new_b.id, name, new_b.chat.id);
});
return new_b;
};
/**
* Add the chat object to the external user's b data
* @param chat
* @param id
* @param b_id
* @return {Object}
*/
ChatServerEvaluationClass.prototype.addExtUserVBChat = function (chat, id, b_id) {
var new_chat = {};
var myAttributes = chat[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
new_chat[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
new_chat.pn = {acc: '', member: {}};
new_chat.cf = {};
$(chat).find('pn').each(function () {
//console.log(this);
new_chat.pn.acc = lz_global_base64_url_decode($(this).attr('acc'));
new_chat.pn.member = [];
new_chat.pn.memberIdList = [];
$(this).find('member').each(function () {
var myAttributes = $(this)[0].attributes;
var new_member = {};
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
new_member[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
//console.log(new_member);
new_chat.pn.member.push(new_member);
new_chat.pn.memberIdList.push(new_member.id);
});
});
$(chat).find('cf').each(function () {
new_chat.cf[lz_global_base64_url_decode($(this).attr('index'))] = lz_global_base64_url_decode($(this).text());
});
return new_chat;
};
ChatServerEvaluationClass.prototype.addExtUserVBFupr = function (fupr, id, b_id, name, chat_id) {
var new_fupr = {};
var myAttributes = fupr[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
new_fupr[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
var fuprIndex = $.inArray(new_fupr.id, this.fuprIdList);
var date = lzm_chatTimeStamp.getServerTimeString(null, true);
var tmpdate = lzm_chatTimeStamp.getLocalTimeObject(date, true);
var new_chat;
var fuprName = this.lzm_commonTools.htmlEntities(new_fupr.fn);
if (fuprIndex == -1) {
this.fuprs.push(new_fupr);
this.fuprIdList.push(new_fupr.id);
new_chat = {id: md5(String(Math.random())).substr(0, 32),
date: date,
cmc: this.chatMessageCounter,
date_human: this.lzm_commonTools.getHumanDate(tmpdate, 'date', this.userLanguage),
time_human: this.lzm_commonTools.getHumanDate(tmpdate, 'time', this.userLanguage),
rec: '', rp: '', sen: '0000000',
text: t('The visitor requested to upload the file <!--request_upload_this-->.',
[['<!--request_upload_this-->','<b>' + this.lzm_commonTools.htmlEntities(new_fupr.fn) + '</b>']]) + '<br>' +
t('Do you want to allow this?') + ' '+
'<a class="lz_chat_accept" href="#" id="allow-upload" ' +
'onclick="handleUploadRequest(\'' + new_fupr.id + '\', \''+ fuprName +'\', \''+ id +'\', \''+ b_id +'\', \'allow\', \'' + chat_id + '\')">' +
t('Accept') + '</a> ' +
'<a class="lz_chat_decline" href="#" id="deny-upload" ' +
'onclick="handleUploadRequest(\'' + new_fupr.id + '\', \''+ fuprName +'\', \''+ id +'\', \''+ b_id +'\', \'deny\', \'' + chat_id + '\')">' +
t('Decline') + '</a>',
reco: id + '~' + b_id};
this.chatMessageCounter++;
this.chats.push(new_chat);
} else {
this.fuprs[fuprIndex] = new_fupr;
if (typeof new_fupr.download != 'undefined' && new_fupr.download == '1' &&
$.inArray(new_fupr.id, this.fuprDownloadIdList) == -1) {
this.fuprDownloadIdList.push(new_fupr.id);
var downloadLink = '<a class="lz_chat_file" target="_blank" href="' + this.serverProtocol + this.serverUrl + '/getfile.php?' +
'acid=' + this.lzm_commonTools.pad(Math.floor(Math.random() * 1048575).toString(16), 5) +
'&id=' + new_fupr.fid + '">';
new_chat = {id: md5(String(Math.random())).substr(0, 32),
date: date,
cmc: this.chatMessageCounter,
date_human: this.lzm_commonTools.getHumanDate(tmpdate, 'date', this.userLanguage),
time_human: this.lzm_commonTools.getHumanDate(tmpdate, 'time', this.userLanguage),
rec: '', rp: '', sen: '0000000',
text: t('You can download the file <!--download_file_name--> provided by the visitor <!--download_link_begin-->here<!--download_link_end-->.',
[['<!--download_file_name-->','<b>' + fuprName + '</b>'],
['<!--download_link_begin-->',downloadLink],['<!--download_link_end-->','</a>']]),
reco: id + '~' + b_id};
this.chatMessageCounter++;
this.chats.push(new_chat);
}
}
};
/**
* Add the values of the h object to the external user
* @param h
* @return {Object}
*/
ChatServerEvaluationClass.prototype.addExtUserVBH = function (h) {
var new_h = {};
var myAttributes = h[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
new_h[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
return new_h;
};
ChatServerEvaluationClass.prototype.checkIfBExists = function (id, b_id) {
var returnValue = false;
var thisVisitor = {};
if (this.external_users.length > 0) {
for (var i = 0; i < this.external_users.length; i++) {
if (id == this.external_users[i].id) {
thisVisitor = this.external_users[i];
break;
}
}
if (thisVisitor.b.length > 0) {
for (var j = 0; j < thisVisitor.b.length; j++) {
if (b_id == thisVisitor.b[j].id) {
returnValue = true;
break;
}
}
}
}
//console.log(id + '~' + b_id + ' --- ' + returnValue);
return returnValue;
};
ChatServerEvaluationClass.prototype.updateB = function (existingBs, newB) {
//console.log(newB);
for (var i = 0; i < existingBs.length; i++) {
if (newB.id == existingBs[i].id) {
newB.hasChanged = false;
//console.log(newB);
for (var key in newB) {
if (newB.hasOwnProperty(key)) {
if (key == 'chat' && (newB[key].id == existingBs[i][key].id)) {
var newChat = {};
for (var chatKey in newB[key]) {
if (newB[key].hasOwnProperty(chatKey)) {
if (chatKey == 'pn') {
//console.log(newB[key][chatKey]);
newChat[chatKey] = {};
newChat[chatKey].acc = newB[key][chatKey].acc;
//console.log(newB[key][chatKey].member);
if (typeof existingBs[i][key][chatKey] != 'undefined') {
newChat[chatKey].oldMember = existingBs[i][key][chatKey].member;
newChat[chatKey].oldMemberIdList = existingBs[i][key][chatKey].memberIdList;
newChat[chatKey].member = newB[key][chatKey].member;
newChat[chatKey].memberIdList = newB[key][chatKey].memberIdList;
} else {
newChat[chatKey] = newB[key][chatKey];
}
} else {
newChat[chatKey] = newB[key][chatKey];
}
}
}
existingBs[i][key] = newChat;
} else {
if ((typeof newB[key] == 'string' && newB[key] != '') ||
(typeof newB[key] == 'object' && newB[key] instanceof Array && newB[key].length != 0) ||
(typeof newB[key] == 'boolean') ||
(typeof newB[key] == 'object' && !(newB[key] instanceof Array)) && !$.isEmptyObject(newB[key])) {
existingBs[i][key] = newB[key];
existingBs[i].hasChanged = true;
}
}
}
}
break;
}
}
//console.log(existingBs);
return existingBs;
};
ChatServerEvaluationClass.prototype.createUniqueName = function(idString) {
//console.log(idString);
var mod = 111;
var digit;
for (var i=0; i<idString.length; i++) {
digit = 0;
if (!isNaN(parseInt(idString.substr(i,1)))) {
digit = parseInt(idString.substr(i,1));
//console.log(i + ' --- ' + digit);
mod = (mod + (mod* (16+digit)) % 1000);
if (mod % 10 == 0) {
mod += 1;
}
}
}
var result = String(mod).substr(String(mod).length-4,4);
//console.log(result);
return result;
};
ChatServerEvaluationClass.prototype.setExternalUserList = function(type, list) {
if (type == 'changed') {
this.changedExternalUsers = list;
} else if (type == 'new') {
this.newExternalUsers = list;
}
};
ChatServerEvaluationClass.prototype.getExternalUserList = function(type) {
var list;
if (type == 'changed') {
list = this.changedExternalUsers;
} else if (type == 'new') {
list = this.newExternalUsers;
}
return list;
};
/**
* Add an external user to the users array
* @param v
*/
ChatServerEvaluationClass.prototype.addExtUserV = function (v) {
var thisClass = this;
var new_user = {}, userLangString = '';
var md5Test = md5((new XMLSerializer()).serializeToString(v[0]).replace(/\r/g, '').replace(/\n/g, ''));
var md5Empty = md5('<v id="' + v.attr('id') + '"></v>');
if (md5Test != md5Empty) {
new_user.md5 = md5Test;
//console.log((new XMLSerializer()).serializeToString(v[0]).replace(/\r/g, '').replace(/\n/g, ''));
}
var bIndex;
var myAttributes = v[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
new_user[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
//console.log(myAttributes[attrIndex].nodeName + ' --- ' + lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue));
}
if ((typeof new_user.ctryi2 == 'undefined' || new_user.ctryi2 == '') && (typeof new_user.lang != 'undefined' && new_user.lang != '')) {
new_user.ctryi2 = new_user.lang;
}
var b_stringEntries = ['b_id', 'b_ol', 'b_olc', 'b_ss', 'b_ka', 'b_ref', 'b_cname', 'b_cemail', 'b_cphone', 'b_ccompany',
'b_h_time', 'b_h_url', 'b_h_title', 'b_h_code', 'b_h_cp'];
for (bIndex = 0; bIndex < b_stringEntries.length; bIndex++) {
new_user[b_stringEntries[bIndex]] = '';
}
if (typeof new_user.ip != 'undefined') {
new_user.unique_name = t('Visitor <!--visitor_number-->',[['<!--visitor_number-->',thisClass.createUniqueName(new_user.id + new_user.ip)]]);
}
new_user.b = [];
var b_idList = [];
new_user.b_chat = {id: ''};
new_user.is_active = true;
//console.log('');
//console.log('Found the following browsers:');
$(v).find('b').each(function () {
var b = $(this);
var tmp_b = thisClass.addExtUserVB(b, new_user.id, new_user.unique_name);
//console.log(this);
// Deprecated (but still used) old ext user b variant
new_user.b_id = tmp_b.id;
new_user.b_ol = tmp_b.ol;
new_user.b_olc = tmp_b.olc;
new_user.b_ss = tmp_b.ss;
new_user.b_ka = tmp_b.ka;
new_user.b_ref = tmp_b.ref;
new_user.b_cname = tmp_b.cname;
new_user.b_cemail = tmp_b.cemail;
new_user.b_cphone = tmp_b.cphone;
new_user.b_ccompany = tmp_b.ccompany;
new_user.b_chat = tmp_b.chat;
new_user.b_h_time = tmp_b.h.time;
new_user.b_h_url = tmp_b.h.url;
new_user.b_h_title = tmp_b.h.title;
new_user.b_h_code = tmp_b.h.code;
new_user.b_h_cp = tmp_b.h.cp;
new_user.b.push(tmp_b);
b_idList.push(tmp_b.id);
//console.log('Tmp : ' + tmp_b.id);
//console.log(new_user.id + '~' + tmp_b.id + ' --- ' + tmp_b.chat.id);
});
new_user.r = [];
new_user.rIdList = [];
$(v).find('r').each(function () {
var r = $(this);
var tmp_r = thisClass.addExtUserR(r);
if ($.inArray(tmp_r.i, new_user.rIdList)) {
new_user.rIdList.push(tmp_r.i);
new_user.r.push(tmp_r);
} else {
for (var rNo=0; rNo<new_user.r.length; rNo++) {
if (new_user.r[rNo].i == tmp_r.i) {
//console.log('Update new user r');
new_user.r[rNo] = tmp_r;
}
}
}
});
new_user.c = [];
new_user.cIdList = [];
$(v).find('c').each(function () {
var c = $(this);
var tmp_c = thisClass.addExtUserC(c);
if ($.inArray(tmp_c.id, new_user.cIdList)) {
new_user.cIdList.push(tmp_c.id);
new_user.c.push(tmp_c);
} else {
for (var cNo=0; cNo<new_user.c.length; cNo++) {
if (new_user.c[cNo].id == tmp_c.id) {
//console.log('Update new user c');
new_user.c[cNo] = tmp_c;
}
}
}
});
var externalUserId = new_user.id;
// check if it's a new user. if yes add him if no update the user's data
if ($.inArray(externalUserId, thisClass.extUserIdList) == -1) {
thisClass.extUserIdList.push(externalUserId);
thisClass.external_users.push(new_user);
thisClass.newExternalUsers.push(externalUserId);
userLangString = new_user.lang;
} else {
var userHasChanged = false;
for (var i = 0; i < thisClass.external_users.length; i++) {
if (thisClass.external_users[i].id == externalUserId) {
userLangString = thisClass.external_users[i].lang;
userHasChanged = userHasChanged || thisClass.updateUserValues(new_user);
if (new_user.b_chat.id != '') {
thisClass.external_users[i].b_chat = new_user.b_chat;
}
if (typeof thisClass.external_users[i].b == 'undefined') {
thisClass.external_users[i].b = [];
}
if (new_user.b.length > 0) {
for (var j = 0; j < new_user.b.length; j++) {
if (thisClass.checkIfBExists(new_user.id, new_user.b[j].id) == false) {
thisClass.external_users[i].b.push(new_user.b[j]);
userHasChanged = true;
} else {
thisClass.external_users[i].b = thisClass.updateB(thisClass.external_users[i].b, new_user.b[j]);
if (thisClass.external_users[i].b.hasChanged) {
userHasChanged = true;
}
}
}
}
new_user.b = thisClass.external_users[i].b;
break;
}
}
if (userHasChanged) {
thisClass.changedExternalUsers.push(externalUserId);
}
}
if (new_user.b.length > 0) {
for (bIndex=0; bIndex<new_user.b.length; bIndex++) {
if (typeof new_user.b[bIndex].chat != 'undefined' && new_user.b[bIndex].chat.id != '' &&
typeof thisClass.chatObject[new_user.id + '~' + new_user.b[bIndex].id] == 'undefined') {
var chatNotDeclined = true;
for (var l=0; l<new_user.b[bIndex].chat.pn.member.length; l++) {
if (new_user.b[bIndex].chat.pn.member[l].id == thisClass.myId && new_user.b[bIndex].chat.pn.member[l].dec == 1) {
chatNotDeclined = false;
}
}
if ((new_user.b[bIndex].chat.at == 0 || (new_user.b[bIndex].chat.at * 1000) > thisClass.loginTime) &&
$.inArray(thisClass.myId, new_user.b[bIndex].chat.pn.memberIdList) != -1 &&
chatNotDeclined) {
thisClass.chatObject[new_user.id + '~' + new_user.b[bIndex].id] = {
status: 'new', type: 'external', data: [], id: new_user.id, b_id: new_user.b[bIndex].id
};
//logit(thisClass.chatObject[new_user.id + '~' + new_user.b[bIndex].id]);
addChatInfoBlock(new_user.id, new_user.b[bIndex].id);
thisClass.browserChatIdList.push(new_user.b[bIndex].chat.id);
if (isAutoAcceptActive()) {
lzm_chatUserActions.acceptChat(new_user.id, new_user.b[bIndex].id, new_user.b[bIndex].chat.id,
new_user.id + '~' + new_user.b[bIndex].id, userLangString);
}
}
}
if (typeof thisClass.chatObject[new_user.id + '~' + new_user.b[bIndex].id] != 'undefined' &&
typeof new_user.b[bIndex].chat != 'undefined' &&
(typeof thisClass.chatObject[new_user.id + '~' + new_user.b[bIndex].id].chat_id == 'undefined' ||
thisClass.chatObject[new_user.id + '~' + new_user.b[bIndex].id].chat_id == '')) {
//console.log('Set chat id of chat object ' + new_user.id + '~' + new_user.b[bIndex].id + ' to ' + new_user.b[bIndex].chat.id);
thisClass.chatObject[new_user.id + '~' + new_user.b[bIndex].id].chat_id = new_user.b[bIndex].chat.id;
}
if (typeof thisClass.chatObject[new_user.id + '~' + new_user.b[bIndex].id] != 'undefined' && typeof new_user.b[bIndex].chat.pn != 'undefined' &&
new_user.b[bIndex].chat.pn.acc == 1) {
//console.log (new_user.b[bIndex].chat.pn);
for (var n=0; n<new_user.b[bIndex].chat.pn.member.length; n++) {
if (new_user.b[bIndex].chat.pn.member[n].id != thisClass.myId && new_user.b[bIndex].chat.pn.member[n].st == 0) {
removeFromOpenChats(new_user.id + '~' + new_user.b[bIndex].id, true, true, new_user.b[bIndex].chat.pn.member, 'addExtUserV');
break;
} else if (new_user.b[bIndex].chat.pn.member[n].id == thisClass.myId && new_user.b[bIndex].chat.pn.member[n].st == 0) {
addOpLeftMessageToChat(new_user.id + '~' + new_user.b[bIndex].id, new_user.b[bIndex].chat.pn.oldMember, new_user.b[bIndex].chat.pn.memberIdList);
}
}
}
if (typeof new_user.b[bIndex].chat.pn != 'undefined' && typeof new_user.b[bIndex].chat.pn.member != 'undefined' &&
(typeof new_user.b[bIndex].chat.pn.memberIdList != 'undefined' && $.inArray(thisClass.myId, new_user.b[bIndex].chat.pn.memberIdList) != -1)) {
if (typeof thisClass.chatPartners[new_user.id + '~' + new_user.b[bIndex].id] == 'undefined') {
thisClass.chatPartners[new_user.id + '~' + new_user.b[bIndex].id] = {past: [], present: []};
}
thisClass.chatPartners[new_user.id + '~' + new_user.b[bIndex].id].past = thisClass.chatPartners[new_user.id + '~' + new_user.b[bIndex].id].present;
thisClass.chatPartners[new_user.id + '~' + new_user.b[bIndex].id].present = [];
var tmpPast = [];
for (var m=0; m<new_user.b[bIndex].chat.pn.member.length; m++) {
if ($.inArray(new_user.b[bIndex].chat.pn.member[m].id, thisClass.chatPartners[new_user.id + '~' + new_user.b[bIndex].id].past) != -1) {
tmpPast.push(new_user.b[bIndex].chat.pn.member[m].id);
}
//console.log(new_member.dec + ' - ' + new_member.id);
if (new_user.b[bIndex].chat.pn.member[m].dec == 0) {
thisClass.chatPartners[new_user.id + '~' + new_user.b[bIndex].id].present.push(new_user.b[bIndex].chat.pn.member[m].id);
}
}
thisClass.chatPartners[new_user.id + '~' + new_user.b[bIndex].id].past = tmpPast;
addDeclinedMessageToChat(new_user.id , new_user.b[bIndex].id, thisClass.chatPartners[new_user.id + '~' + new_user.b[bIndex].id]);
}
}
for (bIndex=0; bIndex<new_user.b.length; bIndex++) {
if (typeof thisClass.chatObject[new_user.id + '~' + new_user.b[bIndex].id] != 'undefined') {
if (typeof new_user.b[bIndex].chat != 'undefined' && typeof new_user.b[bIndex].chat.eq != 'undefined') {
thisClass.chatObject[new_user.id + '~' + new_user.b[bIndex].id].eq = new_user.b[bIndex].chat.eq;
}
if (typeof new_user.b[bIndex].cname != 'undefined') {
thisClass.chatObject[new_user.id + '~' + new_user.b[bIndex].id].name = new_user.b[bIndex].cname;
}
if ((new_user.b[bIndex].chat == 'undefined' || new_user.b[bIndex].chat.id == '') &&
typeof thisClass.chatObject[new_user.id + '~' + new_user.b[bIndex].id] != 'undefined' &&
thisClass.chatObject[new_user.id + '~' + new_user.b[bIndex].id].status != 'left') {
markVisitorAsLeft(new_user.id, new_user.b[bIndex].id);
try {
//console.log('Left in add ext user v because of missing chat or empty chat id');
//console.log(JSON.stringify(new_user.b));
} catch(ex) {
// Do nothing!
}
}
}
}
//console.log(thisClass.globTypingIdList);
for (var k=0; k<new_user.b.length; k++) {
//console.log(new_user.b[k].chat.id);
if (new_user.b[k].chat.id != '' && $.inArray(new_user.b[k].chat.id, thisClass.browserChatIdList) == -1 &&
typeof thisClass.chatObject[new_user.id + '~' + new_user.b[k].id] != 'undefined') {
var member = [];
if (typeof new_user.b[k].chat.pn != 'undefined') {
member = new_user.b[k].chat.pn.member;
}
//console.log('********** ' + new_user.b[k].chat.f + ' **********');
markVisitorAsBack(new_user.id, new_user.b[k].id, new_user.b[k].chat.id, member);
}
if ($.inArray(new_user.id + '~' + new_user.b[k].id, thisClass.globTypingIdList) == -1 &&
typeof thisClass.chatObject[new_user.id + '~' + new_user.b[k].id] != 'undefined' &&
thisClass.chatObject[new_user.id + '~' + new_user.b[k].id].status != 'left') {
//console.log('Remove: ' + new_user.id + '~' + new_user.b[k].id);
markVisitorAsLeft(new_user.id, new_user.b[k].id);
try {
//console.log('Left in add ext user v because of missing gl_typ entry');
//console.log(new_user.id + JSON.stringify(new_user.b[k].id));
//console.log(JSON.stringify(thisClass.global_typing));
} catch(ex) {
// Do nothing!
}
}
}
}
};
ChatServerEvaluationClass.prototype.updateUserValues = function (new_user) {
var rtValue = false;
if (typeof new_user.id != 'undefined' && new_user.id != '') {
for (var i=0; i<this.external_users.length; i++) {
if (this.external_users[i].id == new_user.id) {
for (var key in new_user) {
if (new_user.hasOwnProperty(key)) {
if (key != 'b_chat' && key != 'b' && typeof new_user[key] != 'undefined' && new_user[key] != '') {
//console.log(key + ' --- ' + new_user[key]);
this.external_users[i][key] = new_user[key];
rtValue = true;
}
}
}
break;
}
}
}
return rtValue;
};
/**
* Get validation errors from the server response. If there are any, log out.
* @param xmlDoc
*/
ChatServerEvaluationClass.prototype.getValidationError = function (xmlDoc) {
var error_value = -1;
$(xmlDoc).find('validation_error').each(function () {
if (error_value == -1) {
error_value = lz_global_base64_url_decode($(this).attr('value'));
}
});
return error_value;
};
/**
* Get the ext_c values from the server's xml report
* @param xmlDoc
*/
ChatServerEvaluationClass.prototype.getChats = function (xmlDoc) {
var thisClass = this;
var chatReturn = {dut: ''};
$(xmlDoc).find('ext_c').each(function () {
//console.log('Get chat archive');
var ext_c = $(this);
$(ext_c).children('dc').each(function () {
thisClass.chatArchive = {chats: [], q: '', p: 20, t: 0};
var myAttributes = $(this)[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
//console.log(myAttributes[attrIndex].nodeName + ' --- ' + lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue));
if (myAttributes[attrIndex].nodeName == 'dut') {
chatReturn['dut'] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
thisClass.chatArchive[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
//thisClass.chatArchive.chats = [];
$(this).children('c').each(function () {
var c = $(this);
thisClass.chatArchive.chats.push(thisClass.addArchivedChat(c));
});
thisClass.new_dc = true;
});
});
thisClass.archiveFetchTime = lzm_chatTimeStamp.getServerTimeString(null, false, 1);
return chatReturn;
};
ChatServerEvaluationClass.prototype.addArchivedChat = function(c) {
var thisClass= this;
var new_c = {cc: []};
var myAttributes = c[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
//console.log(myAttributes[attrIndex].nodeName + ' --- ' + lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue));
new_c[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
c.children('chtml').each(function() {
new_c.chtml = thisClass.replaceLinks(lz_global_base64_url_decode($(this).text()));
//console.log(new_c.chtml);
});
c.children('cplain').each(function() {
new_c.cplain = lz_global_base64_url_decode($(this).text());
//console.log(new_c.cplain);
});
c.children('cc').each(function() {
var new_cc = {cuid: lz_global_base64_url_decode($(this).attr('cuid')), text: lz_global_base64_url_decode($(this).text())};
new_c.cc.push(new_cc);
});
return new_c;
};
ChatServerEvaluationClass.prototype.getResources = function (xmlDoc) {
var thisClass = this;
if ($.inArray('1', thisClass.resourceIdList) == -1) {
var publicFolder = {
di: "0",
ed: "0",
eid: "0000000",
oid: "0000000",
pid: "0",
ra: "0",
rid: "1",
si: "6",
t: "",
text: t('Public'),
ti: t('Public'),
ty: "0"
};
thisClass.resources.push(publicFolder);
thisClass.resourceIdList.push('1');
}
$(xmlDoc).find('ext_res').each(function() {
//console.log(this);
var ext_res = $(this);
$(ext_res).find('r').each(function () {
//console.log('');
//console.log('');
//console.log('Get resource ' + $(this).attr('rid'));
//console.log('');
thisClass.new_qrd = true;
var new_r = {};
var myAttributes = $(this)[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
//console.log(myAttributes[attrIndex].nodeName + ' --- ' + lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue));
new_r[myAttributes[attrIndex].nodeName] = lz_global_base64_decode(myAttributes[attrIndex].nodeValue);
}
//console.log($(this).text());
new_r.text = lz_global_base64_decode($(this).text());
var foo = (new XMLSerializer()).serializeToString(this);
new_r.md5 = md5(foo);
if ($.inArray(new_r.rid, thisClass.resourceIdList) == -1) {
if (new_r.di == 0) {
thisClass.resources.push(new_r);
thisClass.resourceIdList.push(new_r.rid);
//console.log('New resource --- ' + new_r.rid);
}
} else {
var deleteResource;
var tmpResources = [], tmpResourceIdList = [];
for (var i = 0; i<thisClass.resources.length; i++) {
deleteResource = false;
if (new_r.rid == thisClass.resources[i].rid) {
if (new_r.di == 0) {
thisClass.resources[i] = new_r;
//console.log('Changed resource --- ' + new_r.rid);
//console.log(new_r);
} else if(new_r.disc == 0) {
//console.log('Do nothing');
//console.log(new_r);
} else {
//console.log('Deleted resource --- ' + new_r.rid);
//console.log(new_r);
deleteResource = true;
}
}
if (!deleteResource) {
tmpResources.push(thisClass.resources[i]);
tmpResourceIdList.push(thisClass.resources[i].rid);
}
if (thisClass.resources[i].di == 1) {
//console.log(thisClass.resources[i]);
}
}
thisClass.resources = tmpResources;
thisClass.resourceIdList = tmpResourceIdList;
}
var editedTime = (typeof new_r.ed != 'undefined') ? new_r.ed : 0;
thisClass.resourceLastEdited = Math.max(thisClass.resourceLastEdited, editedTime);
});
});
return thisClass.resourceLastEdited;
};
ChatServerEvaluationClass.prototype.debuggingGetResourceByTitle = function(title, tag) {
tag = (typeof tag != 'undefined') ? tag : 'ti';
var bar = [];
for (var i=0; i<lzm_chatServerEvaluation.resources.length; i++) {
if (lzm_chatServerEvaluation.resources[i][tag] == title) {
bar.push(lzm_chatServerEvaluation.resources[i]);
}
}
return bar;
};
ChatServerEvaluationClass.prototype.debuggingSearchForId = function(type, id) {
var returnArray = [];
for (var i=0; i<this.resources.length; i++) {
if (this.resources[i][type] == id) {
returnArray.push(this.resources[i]);
}
}
return returnArray;
};
/**
* Get the usr_p values (aka chats) from the server response
* @param xmlDoc
*/
ChatServerEvaluationClass.prototype.getUsrP = function (xmlDoc) {
var thisClass = this;
$(xmlDoc).find('usr_p').each(function () {
//console.log(this);
thisClass.new_usr_p = true;
var usr_p = $(this);
$(usr_p).find('val').each(function () {
var val = $(this);
thisClass.addUsrP(val);
});
});
};
/**
* Get the departments from the server response
* @param xmlDoc
*/
ChatServerEvaluationClass.prototype.getDepartments = function (xmlDoc) {
var thisClass = this;
var myHash = '';
$(xmlDoc).find('int_d').each(function () {
thisClass.new_int_d = true;
var int_d = $(this);
thisClass.internal_departments = [];
$(int_d).find('v').each(function () {
try {
var v = $(this);
thisClass.internal_departments.push(thisClass.addDepartment(v));
} catch(e) {}
});
myHash = lz_global_base64_url_decode(int_d.attr('h'));
});
return myHash;
};
/**
* Get the internal users from the server response
* @param xmlDoc
*/
ChatServerEvaluationClass.prototype.getInternalUsers = function (xmlDoc) {
var thisClass = this;
var myHash = '';
$(xmlDoc).find('int_r').each(function () {
thisClass.new_int_u = true;
var int_r = $(this);
thisClass.internal_users = [];
$(int_r).find('v').each(function () {
//console.log(this);
var v = $(this);
thisClass.internal_users.push(thisClass.addInternalUser(v));
});
myHash = lz_global_base64_url_decode(int_r.attr('h'));
});
return myHash;
};
/**
* Get the global errors from the server response
* @param xmlDoc
*/
ChatServerEvaluationClass.prototype.getGlobalErrors = function (xmlDoc) {
var thisClass = this;
var myHash = '';
$(xmlDoc).find('gl_e').each(function () {
thisClass.new_gl_e = true;
var gl_e = $(this);
thisClass.global_errors = [];
$(gl_e).find('val').each(function () {
var val = $(this);
thisClass.global_errors.push(lz_global_base64_url_decode(val.attr('err')));
});
myHash = lz_global_base64_url_decode(gl_e.attr('h'));
});
return myHash;
};
/**
* Get the internal wp from the server response
*
* What is WP?
*
* @param xmlDoc
*/
ChatServerEvaluationClass.prototype.getIntWp = function (xmlDoc) {
var thisClass = this;
var myHash = '';
$(xmlDoc).find('int_wp').each(function () {
var int_wp = $(this);
thisClass.wps = [];
$(int_wp).find('v').each(function () {
var v = $(this);
thisClass.wps.push(thisClass.addWP(v));
});
myHash = lz_global_base64_url_decode(int_wp.attr('h'));
});
return myHash;
};
/**
* Add a wp to the array
*
* What is WP?
*
* @param v
*/
ChatServerEvaluationClass.prototype.addWP = function (v) {
var new_wp = {};
var myAttributes = v[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
new_wp[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue)
}
return new_wp;
};
/**
* add a usrP (aka chat) to the arrays
* @param val
*/
ChatServerEvaluationClass.prototype.addUsrP = function (val) {
var thisClass = this;
var new_chat = {};
var myAttributes = val[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
new_chat[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
new_chat.cmc = thisClass.chatMessageCounter;
thisClass.chatMessageCounter++;
var tmpdate = lzm_chatTimeStamp.getLocalTimeObject(new_chat.date * 1000, true);
new_chat.date_human = lzm_commonTools.getHumanDate(tmpdate, 'date', thisClass.userLanguage);
new_chat.time_human = lzm_commonTools.getHumanDate(tmpdate, 'time', thisClass.userLanguage);
new_chat.dateObject = {
day: lzm_commonTools.pad(tmpdate.getDate(), 2),
month: lzm_commonTools.pad((tmpdate.getMonth() + 1), 2),
year: lzm_commonTools.pad(tmpdate.getFullYear() ,4)
};
if (new_chat.sen.indexOf('~') != -1) {
new_chat.sen_id = new_chat.sen.split('~')[0];
new_chat.sen_b_id = new_chat.sen.split('~')[1];
} else {
new_chat.sen_id = new_chat.sen;
new_chat.sen_b_id = '';
}
if (new_chat.rec != '' && new_chat.rec != new_chat.sen && new_chat.rec != new_chat.reco) {
new_chat.sen_id = new_chat.rec;
new_chat.sen_b_id = '';
}
var thisText = lz_global_base64_url_decode(val.text());
if (new_chat.sen_b_id != '') {
thisText = thisClass.addLinks(thisClass.escapeHtml(thisText));
} else {
//console.log(thisText);
thisText = thisClass.replaceLinks(thisText);
}
new_chat.text = thisText;
//console.log(new_chat.cmc + ' --- ' + new_chat.text);
if ($.inArray(new_chat.id, thisClass.chatIdList) == -1) {
//console.log(new_chat.id + ' --- ' + new_chat.text);
thisClass.chatIdList.push(new_chat.id);
thisClass.chats.push(new_chat);
var thisSen;
//console.log(thisClass.myId);
//console.log(extUserBChatPnMemberIdList);
if (new_chat.reco == thisClass.myId) {
if (new_chat.sen != '0000000' && new_chat.sen != thisClass.myId) {
thisSen = new_chat.sen;
if (new_chat.rec != '' && new_chat.rec != new_chat.sen) {
thisSen = new_chat.rec;
}
if (typeof thisClass.chatObject[thisSen] == 'undefined') {
if (new_chat.sen.indexOf('~') == -1) {
thisClass.chatObject[thisSen] = {
status: 'new', data: [], id: new_chat.sen_id, b_id: new_chat.sen_b_id
};
//logit(thisClass.chatObject[thisSen]);
//console.log('Chat object ' + thisSen + ' due to new usr_p');
//console.log (thisClass.chatObject[thisSen]);
thisClass.chatObject[thisSen]['type'] = 'internal';
}
} else {
thisClass.chatObject[thisSen]['data'].push(new_chat);
}
if (typeof thisClass.chatObject[thisSen] != 'undefined') {
if ((thisClass.settingsDialogue || new_chat.sen != thisClass.active_chat_reco || lzm_chatDisplay.selected_view != 'mychats') && new_chat.rp != 1) {
//console.log('Set chat status to new');
//console.log('Dialog: ' + thisClass.settingsDialogue + ' Active Chat: ' + new_chat.sen + ' - ' + thisClass.active_chat_reco + ' View: ' + lzm_chatDisplay.selected_view);
thisClass.chatObject[thisSen]['status'] = 'new';
if ($.inArray(new_chat.sen, lzm_chatUserActions.open_chats) == -1 &&
isAutoAcceptActive()) {
var chatId = '', chatLang = '';
for (var i=0; i<thisClass.external_users.length; i++) {
if (thisClass.external_users[i].id == new_chat.sen_id) {
for (var j=0; j<thisClass.external_users[i].b.length; j++) {
if (thisClass.external_users[i].b[j].id == new_chat.sen_b_id) {
chatId = thisClass.external_users[i].b[j].chat.id;
}
}
chatLang = thisClass.external_users[i].lang;
break;
}
}
lzm_chatUserActions.acceptChat(new_chat.sen_id, new_chat.sen_b_id, chatId, new_chat.sen, chatLang);
}
}
}
}
}
if (new_chat.reco == thisClass.myId && new_chat.rp != 1 && (typeof thisClass.chatObject[thisSen] != 'undefined' || isAutoAcceptActive())) {
//console.log(new_chat);
playIncomingMessageSound(new_chat.sen, new_chat.rec, new_chat.id, new_chat.text);
}
thisClass.rec_posts.push(new_chat.id);
}
};
ChatServerEvaluationClass.prototype.setChatAccepted = function(objId, accepted) {
var rtValue = '';
if (!accepted) {
try {
delete this.chatObject[objId].accepted;
rtValue = objId + ' not accepted';
} catch(e) {}
} else {
this.chatObject[objId].accepted = true;
rtValue = objId + ' accepted';
}
return rtValue;
};
/**
* add hyperlinks to urls and mailadresses found in chat posts
* @param myText
* @returns {*}
*/
ChatServerEvaluationClass.prototype.addLinks = function(myText) {
var i, j, replacement;
var webSites = myText.match(/(www\.|(http|https):\/\/)[.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|'|# |!|\(|?|,| |>|<|;|\)]/gi);
//var existingLinks = myText.match(/(<[aA] href.*?onclick.*?openLink.*?<\/[aA]>|<[aA] href.*?getfile.php.*?<\/[aA]>|<[aA] href.*?lz_chat_link.*?<\/[aA]>|<[aA].*?lz_chat_link.*?href.*?<\/[aA]>)/);
var existingLinks = myText.match(/<a.*?href.*?>.*?<\/a>/gi);
//console.log(existingLinks);
if (typeof webSites != 'undefined' && webSites != null) {
for (i=0; i<webSites.length; i++) {
var replaceLink = true;
if (typeof existingLinks != 'undefined' && existingLinks != null) {
for (j=0;j<existingLinks.length; j++) {
if (existingLinks[j].indexOf(webSites[i])) {
replaceLink = false;
}
}
}
if (replaceLink) {
if (webSites[i].toLowerCase().indexOf('http') != 0) {
replacement = '<a class="lz_chat_link" href="#" onclick="openLink(\'http://' + webSites[i] + '\')">' + webSites[i] + '</a>';
} else {
replacement = '<a class="lz_chat_link" href="#" onclick="openLink(\'' + webSites[i] + '\')">' + webSites[i] + '</a>';
}
myText = myText.replace(webSites[i], replacement);
}
}
}
var mailAddresses = myText.match(/[\w\.-]{1,}@[\w\.-]{2,}\.\w{2,3}/gi);
if (typeof mailAddresses != 'undefined' && mailAddresses != null) {
for (i=0; i<mailAddresses.length; i++) {
//replacement = '<a class="lz_chat_mail" href="mailto:' + mailAddresses[i] + '">' + mailAddresses[i] + '</a>';
replacement = '<a class="lz_chat_mail" href="#" onclick="openLink(\'mailto:' + mailAddresses[i] + '\')">' + mailAddresses[i] + '</a>';
myText = myText.replace(mailAddresses[i], replacement);
}
}
return myText;
};
ChatServerEvaluationClass.prototype.replaceLinks = function(myText) {
var i, replacement;
var links = myText.match(/<[aA].*?href.*?<\/[aA]>/);
if (typeof links != 'undefined' && links != null) {
for (i=0; i<links.length; i++) {
//console.log(links[i]);
var address, shownText;
if (links[i].indexOf('mailto:') == -1) {
address = links[i].match(/href=".*?"/);
if (typeof address == 'undefined' || address == null) {
address = links[i].match(/href='.*?'/)[0].replace(/^href='/,'').replace(/'$/, '');
} else {
address = address[0].replace(/^href="/,'').replace(/"$/, '');
}
address = address.replace(/ *$/,'').replace(/"*$/,'');
shownText = links[i].match(/>.*?<\/[aA]>/);
if (typeof shownText == 'undefined' || shownText == null) {
shownText = links[i].match(/href='.*?'/);
}
shownText = shownText[0].replace(/^>/,'').replace(/<\/[aA]>$/,'');
if (links[i].indexOf('lz_chat_file') == -1) {
replacement = '<a data-role="none" class="lz_chat_link" href="#" onclick="openLink(\'' + address + '\')">' + shownText + '</a>';
} else {
replacement = '<a data-role="none" class="lz_chat_file" href="#" onclick="downloadFile(\'' + address + '\')">' + shownText + '</a>';
}
if (address != '#') {
myText = myText.replace(links[i], replacement);
}
} else {
//console.log(myText);
//console.log(links[i]);
var address2 = links[i].match(/href=".*?"/);
var address1 = links[i].match(/href='.*?'/);
var address0 = links[i].match(/href=.*? /);
if ((typeof address2 == 'undefined' || address2 == null) && (typeof address1 == 'undefined' || address1 == null)) {
//console.log('No " or \' - ' + address0);
address = address0[0].replace(/^href=/,'').replace(/ $/, '');
} else if (typeof address2 == 'undefined' || address2 == null) {
//console.log('\' - ' + address1);
address = address1[0].replace(/^href='/,'').replace(/'$/, '');
} else {
//console.log('" - ' + address2);
address = address2[0].replace(/^href="/,'').replace(/"$/, '');
}
address = address.replace(/ *$/,'').replace(/"*$/,'');
shownText = links[i].match(/>.*?<\/[aA]>/);
if (typeof shownText == 'undefined' || shownText == null) {
shownText = links[i].match(/href='.*?'/);
}
shownText = shownText[0].replace(/^>/,'').replace(/<\/[aA]>$/,'');
replacement = '<a data-role="none" class="lz_chat_mail" href="#" onclick="openLink(\'' + address + '\')">' + shownText + '</a>';
if (address != '#') {
myText = myText.replace(links[i], replacement);
}
}
}
}
return myText;
};
/**
* Escape html included in chat posts as a security meassure
* @param myText
* @returns {XML}
*/
ChatServerEvaluationClass.prototype.escapeHtml = function(myText) {
// Replace surrounding font tags as the Windows client sends those
myText = myText.replace(/^<font.*?>/g,'').replace(/<\/font>$/,'');
// replace < and > by their html entities
myText = myText.replace(/</g,'<').replace(/>/g,'>');
// replace line endings by their html equivalents
myText = myText.replace(/\n/g, '').replace(/\r/, '');
myText = myText.replace(/<br \/>/g, '<br />');
return myText;
};
/**
* add a department to the array
* @param v
*/
ChatServerEvaluationClass.prototype.addDepartment = function (v) {
var thisClass = this;
var new_department = {};
var myAttributes = v[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
new_department[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue)
}
new_department.logo = 'img/lz_group.png';
new_department.status_logo = new_department.logo;
new_department.is_active = true;
new_department.pm = [];
new_department.sig = [];
if (typeof new_department.id != 'undefined') {
new_department.humanReadableDescription = thisClass.getHumanReadableDepartmentDescriptions(new_department.desc);
new_department.name = (typeof new_department.humanReadableDescription[thisClass.userLanguage] != 'undefined') ?
new_department.humanReadableDescription[thisClass.userLanguage] :
new_department.humanReadableDescription[thisClass.defaultLanguage];
} else {
new_department.humanReadableDescription = {};
new_department.humanReadableDescription[thisClass.userLanguage] = new_department.n;
new_department.humanReadableDescription[thisClass.defaultLanguage] = new_department.n;
new_department.name = new_department.n;
new_department.id = new_department.i;
}
$(v).find('pm').each(function () {
var pm = $(this);
new_department.pm.push(thisClass.addPM(pm));
});
$(v).find('sig').each(function () {
var sig = $(this);
new_department.sig.push(thisClass.addSignature(sig));
});
return new_department;
};
ChatServerEvaluationClass.prototype.getHumanReadableDepartmentDescriptions = function(desc) {
var tmpArray = desc.split('{')[1].split('}')[0].replace(/;$/, '').split(';');
var descriptionObject = {};
for (var i=0; i<(tmpArray.length / 2); i++) {
var descLanguage = tmpArray[2*i].split('"')[1].toLowerCase();
var description = lz_global_base64_decode(tmpArray[2*i+1].split('"')[1]);
descriptionObject[descLanguage] = description;
}
return descriptionObject;
};
/**
* Add an internal user to the array
* @param v
*/
ChatServerEvaluationClass.prototype.addInternalUser = function (v) {
var thisClass = this;
var new_user = {};
var myAttributes = v[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
new_user[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue)
}
var userStatusIndex = 0;
for (var i=0; i<thisClass.lzm_commonConfig.lz_user_states.length; i++) {
if (thisClass.lzm_commonConfig.lz_user_states[i].index == new_user.status) {
userStatusIndex = i;
break;
}
}
new_user.logo = thisClass.lzm_commonConfig.lz_user_states[userStatusIndex].icon14;
if (typeof new_user.isbot != 'undefined' && new_user.isbot == 1) {
new_user.logo = 'img/643-ic.png';
}
new_user.status_logo = new_user.logo;
new_user.groups = [];
new_user.is_active = true;
new_user.sig = [];
new_user.clientWeb = false;
new_user.clientMobile = false;
new_user.mobileAccount = false;
new_user.mobileAlternatives = [];
$(v).find('gr').each(function () {
var gr = $(this);
new_user.groups.push(lz_global_base64_url_decode(gr.text()));
});
$(v).find('pm').each(function () {
var pm = $(this);
if (typeof new_user.pm == 'undefined') {
new_user.pm = [];
}
new_user.pm.push(thisClass.addPM(pm));
});
$(v).find('pp').each(function () {
var pp = $(this);
new_user.pp = pp.text();
});
$(v).find('sig').each(function () {
var sig = $(this);
new_user.sig.push(thisClass.addSignature(sig));
});
$(v).find('cw').each(function () {
new_user.clientWeb = true;
});
$(v).find('cm').each(function () {
new_user.clientMobile = true;
});
$(v).find('me').each(function() {
var me = $(this);
new_user.mobileAlternatives.push(lz_global_base64_url_decode(me.text()));
new_user.mobileAccount = true;
});
// set the values for the logged in user
if (new_user.userid == thisClass.chosen_profile.login_name) {
thisClass.myGroup = new_user.groups[0];
}
return new_user;
};
/**
* Add the predefined messages to the internal departments or internal users
*
* @param pm
*/
ChatServerEvaluationClass.prototype.addPM = function (pm) {
var newPm = {};
var myAttributes = pm[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
newPm[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue)
}
return newPm;
};
ChatServerEvaluationClass.prototype.addSignature = function (sig) {
var newSig = {};
var myAttributes = sig[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
newSig[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue)
}
newSig.text = lz_global_base64_url_decode($(sig).text());
return newSig;
};
/**
* Delete a property from the chat object
* @param propertyName
*/
ChatServerEvaluationClass.prototype.deletePropertyFromChatObject = function (propertyName) {
delete this.chatObject[propertyName];
};
ChatServerEvaluationClass.prototype.getFilters = function(xmlDoc) {
var thisClass = this;
var filterHash = '';
$(xmlDoc).find('ext_b').each(function() {
//console.log(this);
var ext_b = $(this);
filterHash = lz_global_base64_url_decode(ext_b.attr('h'));
thisClass.filters.clearFilters();
ext_b.find('val').each(function() {
var foo = thisClass.addFilter($(this));
thisClass.filters.setFilter(foo);
});
});
return filterHash;
};
ChatServerEvaluationClass.prototype.addFilter = function(val) {
var newFilter = {};
var myAttributes = val[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
newFilter[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
return newFilter;
};
ChatServerEvaluationClass.prototype.getEvents = function(xmlDoc) {
var thisClass = this;
var myEventDut = '';
$(xmlDoc).find('listen').each(function() {
var listen = $(this);
listen.children('ev').each(function() {
thisClass.new_ev = true;
var ev = $(this);
myEventDut = lz_global_base64_url_decode(ev.attr('dut'));
});
});
return {'event-dut': myEventDut};
};
ChatServerEvaluationClass.prototype.getTickets = function(xmlDoc, maxRead) {
var thisClass = this;
var myHash = '', myTicketDut = '', myEmailDut = '';
var lmc = (typeof thisClass.ticketGlobalValues['lmc'] != 'undefined' && thisClass.ticketGlobalValues['lmc'] != '') ?
thisClass.ticketGlobalValues['lmc'] : 0;
thisClass.ticketGlobalValues['updating'] = false;
thisClass.ticketGlobalValues['no_update'] = false;
thisClass.ticketGlobalValues['mr'] = maxRead;
$(xmlDoc).find('dt').each(function () {
thisClass.new_dt = true;
var dt = $(this);
$(dt).find('no_update').each(function() {
thisClass.ticketGlobalValues['no_update'] = true;
});
var globValues = {
q: lz_global_base64_url_decode(dt.attr('q')),
r: lz_global_base64_url_decode(dt.attr('r')),
t: lz_global_base64_url_decode(dt.attr('t')),
p: lz_global_base64_url_decode(dt.attr('p'))
};
lmc = (parseInt(lz_global_base64_url_decode(dt.attr('lmc'))) > lmc) ? parseInt(lz_global_base64_url_decode(dt.attr('lmc'))) : lmc;
if (!thisClass.ticketGlobalValues['no_update']) {
thisClass.tickets = [];
$(dt).find('updating').each(function() {
thisClass.ticketGlobalValues['updating'] = true;
});
thisClass.ticketGlobalValues['t'] = (globValues['t'] != '' || typeof thisClass.ticketGlobalValues['t'] == 'undefined') ?
globValues['t'] : thisClass.ticketGlobalValues['t'];
thisClass.ticketGlobalValues['r'] = (globValues['r'] != '' || typeof thisClass.ticketGlobalValues['r'] == 'undefined') ?
globValues['r'] : thisClass.ticketGlobalValues['r'];
thisClass.ticketGlobalValues['q'] = (globValues['q'] != '' || typeof thisClass.ticketGlobalValues['q'] == 'undefined') ?
globValues['q'] : thisClass.ticketGlobalValues['q'];
thisClass.ticketGlobalValues['p'] = (globValues['p'] != '' || typeof thisClass.ticketGlobalValues['p'] == 'undefined') ?
globValues['p'] : thisClass.ticketGlobalValues['p'];
$(dt).find('val').each(function () {
var thisTicketHash = md5((new XMLSerializer()).serializeToString(this));
var val = $(this);
var thisTicket = thisClass.addTicket(val);
thisTicket.md5 = thisTicketHash;
thisClass.tickets.push(thisTicket);
});
//console.log(thisClass.tickets);
}
myHash = lz_global_base64_url_decode(dt.attr('h'));
myTicketDut = lz_global_base64_url_decode(dt.attr('dut'));
//console.log(myTicketDut);
thisClass.ticketGlobalValues['h'] = myHash;
thisClass.ticketGlobalValues['dut'] = myTicketDut;
//console.log(this);
});
$(xmlDoc).find('de').each(function () {
thisClass.new_de = true;
var de = $(this);
thisClass.emails = [];
//console.log(thisClass.emailCount);
$(de).find('e').each(function () {
var e = $(this);
thisClass.emails.push(thisClass.addEmail(e));
});
lmc = (parseInt(lz_global_base64_url_decode(de.attr('lmc'))) > lmc) ? parseInt(lz_global_base64_url_decode(de.attr('lmc'))) : lmc;
myEmailDut = lz_global_base64_url_decode(de.attr('dut'));
thisClass.emailCount = lz_global_base64_url_decode(de.attr('c'));
thisClass.ticketGlobalValues['e'] = (thisClass.emailCount !== '') ? thisClass.emailCount : thisClass.ticketGlobalValues['e'];
thisClass.emails.sort(lzm_commonTools.sortEmails);
});
//console.log('Got tickets: ' + myHash + ' --- ' + maxRead);
//console.log(myTicketDut);
thisClass.ticketGlobalValues['lmc'] = lmc;
thisClass.ticketFetchTime = lzm_chatTimeStamp.getServerTimeString(null, false, 1);
return {hash: myHash, 'ticket-dut': myTicketDut, 'email-dut': myEmailDut};
};
ChatServerEvaluationClass.prototype.addTicket = function(val) {
var thisClass = this;
var newTicket = {};
var myAttributes = val[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
newTicket[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
newTicket.messages = [];
$(val).find('m').each(function(){
var m = $(this);
newTicket.messages.push(thisClass.addTicketMessage(m));
});
newTicket.editor = false;
$(val).find('cl').each(function() {
var cl = $(this);
newTicket.editor = thisClass.addTicketEditor(cl);
});
return newTicket;
};
ChatServerEvaluationClass.prototype.addEmail = function(e) {
var thisClass = this;
var newEmail = {text: '', attachment: []};
var myAttributes = e[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
newEmail[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
$(e).find('c').each(function() {
newEmail.text = lz_global_base64_url_decode($(this).text());
});
$(e).find('a').each(function() {
var a = $(this);
newEmail.attachment.push(thisClass.addEmailAttachment(a));
});
//console.log(newEmail);
return newEmail;
};
ChatServerEvaluationClass.prototype.addEmailAttachment = function (a) {
var newAttachment = {};
var myAttributes = a[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
newAttachment[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
newAttachment.id = lz_global_base64_url_decode(a.text());
return newAttachment;
};
ChatServerEvaluationClass.prototype.addTicketMessage = function(m) {
var thisClass = this;
//console.log(m);
var newMessage = {attachment: [], comment: [], customInput: []};
var myAttributes = m[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
newMessage[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
$(m).find('c').each(function() {
var c = $(this);
newMessage.customInput.push(thisClass.addTicketMessageCustomInput(c));
});
$(m).find('a').each(function() {
var a = $(this);
newMessage.attachment.push(thisClass.addTicketMessageAttachment(a));
});
$(m).find('co').each(function() {
var co = $(this);
newMessage.comment.push(thisClass.addTicketMessageComment(co));
});
//console.log(newMessage);
return newMessage;
};
ChatServerEvaluationClass.prototype.addTicketMessageAttachment = function (a) {
var newAttachment = {};
var myAttributes = a[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
newAttachment[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
newAttachment.n = lz_global_base64_url_decode(a.text());
return newAttachment;
};
ChatServerEvaluationClass.prototype.addTicketMessageComment = function (co) {
var newComment = {};
var myAttributes = co[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
newComment[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
newComment.text = lz_global_base64_url_decode(co.text());
return newComment;
};
ChatServerEvaluationClass.prototype.addTicketMessageCustomInput = function (c) {
var newCustomInput = {};
var myAttributes = c[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
newCustomInput[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
newCustomInput.text = lz_global_base64_url_decode(c.text());
return newCustomInput;
};
ChatServerEvaluationClass.prototype.addTicketEditor = function (cl) {
var newEditor = {};
var myAttributes = cl[0].attributes;
for (var attrIndex = 0; attrIndex < myAttributes.length; attrIndex++) {
newEditor[myAttributes[attrIndex].nodeName] = lz_global_base64_url_decode(myAttributes[attrIndex].nodeValue);
}
return newEditor;
};
/**
* Timestamp class, adding or substracting the time difference between client and server
* @param timeDifference
* @constructor
*/
function ChatTimestampClass(timeDifference) {
//console.log(timeDifference);
this.timeDifference = timeDifference * 1000;
//console.log('Timestamp object created - time diff is ' + this.timeDifference);
}
ChatTimestampClass.prototype.logTimeDifference = function() {
try {
console.log('Timestamp object present - time diff is ' + this.timeDifference);
} catch(e) {}
};
ChatTimestampClass.prototype.setTimeDifference = function(timeDifference) {
this.timeDifference = timeDifference * 1000;
};
ChatTimestampClass.prototype.getLocalTimeObject = function(timeStamp, doCalcTimeDiff) {
timeStamp = (typeof timeStamp != 'undefined' && timeStamp != null) ? timeStamp : $.now();
doCalcTimeDiff = (typeof doCalcTimeDiff != 'undefined') ? doCalcTimeDiff : false;
var calculatedTimeStamp = (doCalcTimeDiff) ? parseInt(timeStamp) - parseInt(this.timeDifference) : parseInt(timeStamp);
var tmpDateObject = new Date(calculatedTimeStamp);
return tmpDateObject;
};
ChatTimestampClass.prototype.getServerTimeString = function(dateObject, doCalcTimeDiff, divideBy) {
dateObject = (typeof dateObject != 'undefined' && dateObject != null) ? dateObject : new Date();
doCalcTimeDiff = (typeof doCalcTimeDiff != 'undefined') ? doCalcTimeDiff : false;
divideBy = (typeof divideBy != 'undefined') ? divideBy : 1000;
var calculatedTimeString = (doCalcTimeDiff) ? dateObject.getTime() + parseInt(this.timeDifference) : dateObject.getTime();
return Math.floor(calculatedTimeString / divideBy);
};
function LzmFilters() {
this.idList = [];
this.objects = {};
}
LzmFilters.prototype.setFilter = function(filter) {
if ($.inArray(filter.filterid, this.idList) == -1) {
this.idList.push(filter.filterid);
}
this.objects[filter.filterid] = filter;
};
LzmFilters.prototype.getFilter = function(filterId) {
return this.objects[filterId];
};
LzmFilters.prototype.removeFilter = function(filterId) {
var tmpArray = [];
for (var i=0; i<this.idList; i++) {
if (this.idList[i] != filterId) {
tmpArray.push(this.idList[i]);
}
}
this.idList = tmpArray;
delete this.objects[filterId];
};
LzmFilters.prototype.clearFilters = function() {
this.idList = [];
this.objects = {};
};
function LzmCustomInputs() {
this.idList = [];
this.objects = {};
this.nameList = {};
}
LzmCustomInputs.prototype.setCustomInput = function(customInput) {
if ($.inArray(customInput.id, this.idList) == -1) {
this.idList.push(customInput.id);
}
if (typeof customInput.value == 'string') {
customInput.value = this.parseInputValue(customInput.value);
}
this.objects[customInput.id] = customInput.value;
if (customInput.value.name != '')
this.nameList[customInput.value.name] = customInput.id;
};
LzmCustomInputs.prototype.getCustomInput = function(id, searchBy) {
searchBy = (typeof searchBy != 'undefined') ? searchBy : 'id';
if (searchBy == 'id') {
return this.objects[id];
} else if (searchBy == 'name') {
return this.objects[this.nameList[id]];
} else {
return null;
}
};
LzmCustomInputs.prototype.clearCustomInputs = function() {
this.idList = [];
this.objects = {};
this.nameList = {};
};
LzmCustomInputs.prototype.parseInputValue = function(value) {
value = lz_global_base64_url_decode(value);
value = lzm_commonTools.phpUnserialize(value);
var customValue = value[7];
if (value[3] == 'ComboBox') {
customValue = (value[7].indexOf(';') != -1) ? value[7].split(';') : [value[7]];
}
var valueObject = {id: value[0], /*title: value[1],*/ name: value[2],type: value[3], active: value[4], /*cookie: value[5], position: value[6],*/
value: customValue};
//console.log(value);
//console.log(valueObject);
return valueObject;
};
|
import store from 'store';
import { storeWatcher } from 'store/storeWatcher.js';
/**
* Component: Defines a component with basic methods
* @constructor
*/
class Base {
set promises(newPromises) {
if (!this._promises) this._promises = {};
for (const promise in newPromises) {
if ({}.hasOwnProperty.call(newPromises, promise)) {
this._promises[promise] = newPromises[promise];
}
}
}
get promises() {
return this._promises;
}
set state(state) {
if (!this._state) this._state = {};
for (const subState in state) {
if ({}.hasOwnProperty.call(state, subState)) {
this._state[subState] = state[subState];
}
}
}
get state() {
return this._state;
}
set storeEvents(storeEvents) {
for (const objectPath in storeEvents) {
if (!storeEvents[objectPath]) continue;
this._storeEvents[objectPath] = storeEvents[objectPath];
}
this.subscribe();
}
get storeEvents() {
return this._storeEvents;
}
constructor() {
/**
* Object as associative array of all the <promises> objects
* @type {Object}
*/
this._promises = {};
/**
* Object as associative array of all <watcher> objects
* @type {Object}
*/
this._storeEvents = {};
/**
* Object as associative array of all <subscriptions> objects
* @type {Object}
*/
this.subscriptions = {};
this.promises = {
init: {
resolve: null,
reject: null,
},
};
this.state = {
isInit: false,
};
}
/**
* Init
* @return {Promise} A Promise the component is init
*/
init() {
return new Promise((resolve, reject) => {
this.promises.init.resolve = resolve;
this.promises.init.reject = reject;
const { isInit } = this.state;
if (isInit) {
this.promises.init.reject();
return;
}
this.initComponent();
});
}
initComponent() {
this.onInit();
}
/**
* Once the component is init
*/
onInit() {
this.setState({ isInit: true });
this.promises.init.resolve();
}
setState(partialState = {}, callback, needRender = false) {
if (typeof partialState !== 'object' && typeof partialState !== 'function' && partialState !== null) {
console.error(
'setState(...): takes an object of state variables to update or a ' +
'function which returns an object of state variables.'
);
return;
}
const prevState = Object.assign({}, this.state);
this.state = { ...this.state, ...partialState };
if (callback) callback();
if (needRender) this.render();
this.stateDidUpdate(this.state, prevState);
}
stateDidUpdate(state, oldState) {}
subscribe(o) {
// When an object is givin for a specific subscription
if (o) {
if (this.subscriptions[o.path]) {
// To unsubscribe the change listener, invoke the function returned by subscribe.
this.subscriptions[o.path]();
}
let method = o.cb;
if (typeof method !== 'function') method = this[method];
if (!method) return;
this._storeEvents[o.path] = method;
const watcher = storeWatcher(store.getState, path);
this.subscriptions[path] = store.subscribe(() => watcher(method));
return;
}
for (const path in this.storeEvents) {
if ({}.hasOwnProperty.call(this.storeEvents, path)) {
if (!this.storeEvents[path]) continue;
// To unsubscribe the change listener, invoke the function returned by subscribe.
if (this.subscriptions[path]) this.subscriptions[path]();
let method = this.storeEvents[path];
if (typeof method !== 'function') method = this[method];
if (!method) continue;
const watcher = storeWatcher(store.getState, path);
this.subscriptions[path] = store.subscribe(watcher(method));
}
}
}
unsubscribe(path_ = null) {
if (path_) {
if (this.subscriptions[path_]) {
this.subscriptions[path_]();
delete this.subscriptions[path_];
}
return;
}
for (const path in this.subscriptions) {
if (!this.subscriptions[path]) continue;
// To unsubscribe the change listener, invoke the function returned by subscribe.
// Ex : let unsubscribe = store.subscribe(handleChange)
this.subscriptions[path]();
}
this.subscriptions = {};
}
dispatch(action) {
store.dispatch(action);
}
dispose() {
this.unsubscribe();
}
resize() {}
}
export default Base;
|
import React,{Component} from 'react';
import { Button, View , Platform , Text,StyleSheet } from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import ModalScreen from './Modal'
import Icon from './Icon'
class ContactPage extends Component{
state = {
count: 0,
};
_increaseCount = () => {
this.setState({ count: this.state.count + 1 });
};
componentWillMount() {
this.props.navigation.setParams({ increaseCount: this._increaseCount });
}
// static navigationOptions = {
static navigationOptions = ({ navigation }) => {
return {
title: 'contacts',
// headerStyle: { marginTop: 24 },
// headerTitle : <Icon />,
headerStyle: {
backgroundColor: '#ffe6e6',
},
headerTintColor: '#999999',
headerTitleStyle: {
fontWeight: 'bold',
},
headerRight: (
<Button
// onPress={() => alert('This is a button!')}
// title="Info"
// color='#ffe6e6'
onPress={navigation.getParam('increaseCount')}
title="+1"
color={Platform.OS === 'ios' ? '#fff' : '#e6e6e6'}
/>
),
headerLeft: (
<Button
onPress={() => navigation.navigate('MyModal')}
title="Info"
color="#e6e6e6"
/>
),
}
};
render(){
const { navigation } = this.props;
const otherParam = navigation.getParam('otherParam','NO-ID');
return(
<View style = {styles.container}>
<Text>Contacts</Text>
<Text>Count: {this.state.count}</Text>
{/* <Text>{JSON.stringify(otherParam)}</Text> */}
</View>
)
}
}
const RootStack = createStackNavigator(
{
Home: ContactPage ,
MyModal : ModalScreen
},
{
initialRouteName: 'Home',
}
);
const AppContainer = createAppContainer(RootStack);
export default class App extends Component {
render() {
return <AppContainer />;
}
}
const styles = StyleSheet.create({
container :{
flex : 1 ,
alignItems: 'center',
justifyContent: 'center' ,
backgroundColor :'#ffcccc'
},
})
|
import React, { useState, Fragment } from "react";
import SignupForm from "./SignupForm";
import MetaMask from "./MetaMask";
export default function SignupOptions() {
const [isSuccess, setIsSuccess] = useState(false);
return (
<div className="sign-up-options__wrapper">
{isSuccess ? (
<Fragment>
<p className="app__success-message">
Thanks for signing up! Last step is to check the email we just sent
you and follow the instructions to confirm your identity
</p>
</Fragment>
) : (
<SignupForm setIsSuccess={setIsSuccess} />
)}
<div className="sign-up-options__metamask-button-wrapper app__hide-on-mobile">
<React.Fragment>
<p className="sign-up-options__metamask-button-wrapper-text">Or:</p>
<MetaMask buttonText={"Sign up with MetaMask"} />
</React.Fragment>
</div>
</div>
);
}
|
/**
*
* detector.
*
* @project imgPano
* @datetime 21:27 - 15/11/5
* @author Thonatos.Yang <thonatos.yang@gmail.com>
* @copyright Thonatos.Yang <https://www.thonatos.com>
*
*/
exports.detector = {
canvas: !! window.CanvasRenderingContext2D,
webgl: (function() {
try {
var canvas = document.createElement('canvas');
return !!(window.WebGLRenderingContext && (canvas.getContext('webgl') || canvas.getContext('experimental-webgl')));
} catch (e) {
return false;
}
})(),
workers: !! window.Worker,
fileapi: window.File && window.FileReader && window.FileList && window.Blob
};
|
//The Particle class
function Particle(){
//particle position
this.x = 0;
this.y = 0;
//particle velocity
this.vx = 0;
this.vy = 0;
this.time = 0; //the time elapsed since the particle was created
this.life = 0; //the amount of time the particle is going to live
this.color = "#000000";
this.setValues = function(x, y, vx, vy){
this.x=x; this.y=y;
this.vx=vx; this.vy=vy;
this.time=0;
this.life = Math.floor(Math.random()*500);
}
this.setColor = function(color){
this.color = color;
}
// renders the particle using the canvas element
this.render = function(){
ctx.save();
ctx.fillStyle = this.color;
ctx.translate(this.x, this.y);
ctx.beginPath();
ctx.arc(0,0,10,0,Math.PI*2,true); // draw a circle
ctx.fill();
ctx.restore();
}
}
// RainParticle inherits from Particle and overloads the render function to draw a drop instead of a circle
function RainParticle(){
this.render = function(){
var m=0.4;
ctx.save();
ctx.fillStyle = this.color;
ctx.translate(this.x, this.y);
ctx.beginPath();
ctx.moveTo(0,0);
ctx.arc(0,0,1,0,Math.PI*2,true);
// ctx.bezierCurveTo(0*m,5*m,0*m,10*m,5*m,15*m);
// ctx.bezierCurveTo(10*m,20*m,12*m,26*m,10*m,30*m);
// ctx.bezierCurveTo(6*m,40*m,-6*m,40*m,-10*m,30*m);
// ctx.bezierCurveTo(-12*m,26*m,-10*m,20*m,-5*m,15*m);
// ctx.bezierCurveTo(0*m,10*m,0*m,5*m,0*m,0*m);
ctx.fill();
ctx.restore();
}
}
RainParticle.prototype = new Particle; //inherit from Particle
//ParticleSystem creates an array of RainParticles and updates their attributes
function ParticleSystem(){
//origin rectangle of the this.particles
this.x0;
this.y0;
this.x1;
this.y1;
this.n = 0;
this.particles = [];
this.gravity = 0.01;
this.init = function(n, x0, y0, x1, y1){
this.n = n;
this.x0=x0;this.y0=y0;
this.x1=x1;this.y1=y1;
this.gravity = 1;
for(var i=0; i<n; i++){
this.particles.push(new RainParticle());
this.particles[i].setValues(Math.floor(Math.random()*this.x1)+this.x0,Math.floor(Math.random()*this.y1)+this.y0,0,1)
}
}
this.setParticlesColor = function(color){
for(var i=0; i<this.particles.length; i++)this.particles[i].setColor(color);
}
//update the attributes of every particle
this.update = function(){
for(var i=0; i<this.particles.length; i++){
if(this.particles[i].time < this.particles[i].life){
//this.particles[i].vy = this.particles[i].vy + this.gravity;
this.particles[i].x = this.particles[i].x + this.particles[i].vx;
this.particles[i].y = this.particles[i].y + this.particles[i].vy;
this.particles[i].time += 1;
}
else{
this.particles[i].setValues(Math.floor(Math.random()*this.x1)+this.x0,Math.floor(Math.random()*this.y1)+this.y0,0,1);
}
}
}
this.render = function(){
for(var i=0; i<this.particles.length; i++)this.particles[i].render();
}
};
function init()
{
ctx = document.getElementById("myCanvas").getContext("2d");
setInterval(draw,10);
ps = new ParticleSystem();
ps.init(150,100,100,(document.body.offsetWidth - 200),(document.body.offsetHeight - 150));
ps.setParticlesColor("#ffffff");
}
function draw(){
//ctx.clearRect(0,0,800,600);
ctx.beginPath();
ctx.canvas.width = window.innerWidth-50;
ctx.canvas.height = window.innerHeight-50;
ctx.fillStyle = "#111000";
ctx.fillRect(100,100,(document.body.offsetWidth - 200),(document.body.offsetHeight - 200));
ctx.strokeRect(100,100,(document.body.offsetWidth - 200),(document.body.offsetHeight - 200));
ctx.fill();
ps.update();
ps.render();
}
|
const fs = require('fs');
const os = require('os');
const path = require('path');
function logLineAsync(logFilePath,logLine) {
return new Promise( (resolve,reject) => {
const logDT=new Date();
let time=logDT.toLocaleDateString()+" "+logDT.toLocaleTimeString();
let fullLogLine=time+" "+logLine;
console.log(fullLogLine); // выводим сообщение в консоль
fs.open(logFilePath, 'a+', (err,logFd) => {
if ( err )
reject(err);
else
fs.write(logFd, fullLogLine + os.EOL, (err) => {
if ( err )
reject(err);
else
fs.close(logFd, (err) =>{
if ( err )
reject(err);
else
resolve();
});
});
});
} );
}
module.exports={
logLineAsync,
};
|
const CleAPI = 'f746b43b8956d7b9e269c7c4cf790acc'; // On utilise notre propre clé d'API https://openweathermap.org/
let resultatsAPI;
const localisation = document.querySelector('.localisation');
const temperature = document.querySelector('.temperature');
const temps = document.querySelector('.temps');
const pression = document.querySelector('.pression');
const humidite = document.querySelector('.humidite');
const heures = document.querySelectorAll('.heure-prevision');
const temperatures = document.querySelectorAll('.valeur-prevision');
const jours = document.querySelectorAll('.jour-prevision');
const tempJours = document.querySelectorAll('.temp-prevision');
const imgIcone = document.querySelector('.logo-meteo');
const blocIcon = document.querySelectorAll('.bloc-icon');
const chargementContainer = document.querySelector('.icone-chargement');
const imgChargementContainer = document.querySelector('.image-chargement');
chargeImg()
submitForm()
///////////animation input///////////////
const rechercheInput = document.querySelector('#recherche');
rechercheInput.addEventListener('input', function (ev) {
if(ev.target.value !== "") {
ev.target.parentNode.classList.add('active-input');
} else if (ev.target.value === "") {
ev.target.parentNode.classList.remove('active-input');
}
})
////////////////////////////////////////
function submitForm() {
document.querySelector('#form').addEventListener('submit', (ev) => {
ev.preventDefault()
cityAppelAPI(document.querySelector('#recherche').value)
})
}
function cityAppelAPI() {
let city = document.querySelector('#recherche').value
fetch(`https://api.openweathermap.org/data/2.5/weather?exclude=minutely&units=metric&lang=fr&q=${city}&appid=${CleAPI}`)
.then(reponse => reponse.json())
.then((data) => {
console.log(data);
/*{coord: {…}, weather: Array(1), base: "stations", main: {…}, visibility: 10000, …}
base: "stations"
clouds: {all: 75}
cod: 200
coord: {lon: 5.5, lat: 43.3333}
dt: 1613251333
id: 2995468
main: {temp: 6.51, feels_like: 3.11, temp_min: 3, temp_max: 8.89, pressure: 1029, …}
name: "Marseille"
sys: {type: 1, id: 6512, country: "FR", sunrise: 1613198341, sunset: 1613235936}
timezone: 3600
visibility: 10000
weather: [{…}]
wind: {speed: 2.57, deg: 320}
__proto__: Object*/
resultatsAPI = data;
localisation.innerText = resultatsAPI.name;
temperature.innerText = `${Math.trunc(resultatsAPI.main.temp)} c°`
temps.innerText = resultatsAPI.weather[0].description;
pression.innerText = `${resultatsAPI.main.pressure} hPa`;
humidite.innerText = `${resultatsAPI.main.humidity} %`;
let lon = resultatsAPI.coord.lon;
let lat = resultatsAPI.coord.lat;
appelAPI(lon, lat)
})
}
function appelAPI(lon, lat) {
fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&exclude=minutely&units=metric&lang=fr&appid=${CleAPI}`)
.then(reponse => reponse.json())
.then((data) => {
console.log(data);
resultatsAPI = data;
let heureActuelle = new Date().getHours();
for(let i = 0; i < heures.length; i++) {
let heureIncr = heureActuelle + i * 2;
if(heureIncr > 24) {
heures[i].innerText = `${heureIncr - 24} h`;
} else if(heureIncr === 24) {
heures[i].innerText = "00 h"
} else {
heures[i].innerText = `${heureIncr} h`;
}
}
for(let j = 0; j < temperatures.length; j++) {
temperatures[j].innerText = `${Math.trunc(resultatsAPI.hourly[j * 2].temp)} c°`
}
// Les jours de la semaine et temperature pour 7 jours
for(let k = 0; k < joursEnOrdre.length; k++) {
jours[k].innerText = joursEnOrdre[k].slice(0,3);
}
for(let m = 0; m < 7; m ++) {
tempJours[m].innerText = `${Math.trunc(resultatsAPI.daily[m + 1].temp.day)} c°`
blocIcon[m].src = `ressources/${resultatsAPI.daily[m + 1].weather[0].icon}.svg`
}
imgIcone.src = `ressources/${resultatsAPI.current.weather[0].icon}.svg`
chargementContainer.classList.add('disparition');
})
}
/////////////animation image/////////////
function chargeImg() {
let heureActuelle = new Date().getHours();
if(heureActuelle >= 11 && heureActuelle < 16) {
imgChargementContainer.src = `ressources/ciel-jour.jpg`;
console.log(imgChargementContainer);
} else if((heureActuelle >= 6 && heureActuelle < 11) || (heureActuelle >= 16 && heureActuelle < 19)) {
imgChargementContainer.src = `ressources/ciel.jpg`;
console.log(imgChargementContainer);
} else {
imgChargementContainer.src = `ressources/ciel-nuit.jpg`;
console.log(imgChargementContainer);
}
}
//////////////////////////////////////////
const joursSemaine = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche']; // On définit un constant et sa valeur est tableau qui contient les jours de la semaine
let aujourdhui = new Date(); // On déclare un variable et sa valeur est la date actuelle (constucteur new Date)
let options = {weekday: 'long'}; // On déclare un variable qui contient un objet (les jours de week-end)
let jourActuel = aujourdhui.toLocaleDateString('fr-FR', options); // On demande le jour actuelle entier (en obsion long) en langue français. La méthode toLocaleDateString() renvoie une chaine de caractères correspondant à la date (le fragment de l'objet qui correspond à la date : jour, mois, année) exprimée selon une locale.
//console.log(jourActuel, aujourdui); // jeudi Thu Dec 17 2020 17:29:11 GMT+0100 (heure normale d’Europe centrale)
jourActuel = jourActuel.charAt(0).toUpperCase() + jourActuel.slice(1); //On affiche en majuscule premier lettre (0) de chaque jour et on lui ajoute le reste de mot (L + undi)
// La méthode charAt() renvoie une nouvelle chaîne contenant le caractère à la position indiquée en argument.
// La méthode toUpperCase() retourne la valeur de la chaîne courante, convertie en majuscules.
// La méthode slice() renvoie un objet tableau, contenant une copie superficielle d'une portion du tableau d'origine, la portion est définie par un indice de début et un indice de fin. Le tableau original ne sera pas modifié.
//console.log(jourActuel);
let joursEnOrdre = joursSemaine.slice(joursSemaine.indexOf(jourActuel)).concat(joursSemaine.slice(0, joursSemaine.indexOf(jourActuel)));
/* Avec slice on va découper notre tableau qui contient les jours de la semaine, il nous faut un debut et une fin,
le debut est l'index de joursActuel, puis on va concaténer avec nouveau tableau jusqu'à jour actuel, example : si on est mercredi,
avec slice on découpe notre tableau qui contient les jours de la semaine mais par ordre (lun, mar, mer, jeu, ven, sam, dim),
joursSemaine.indexOf(jourActuel) nous retourne mercredi, jeudi, vendredi, samedi et dimanche, on rajoute avec concat nouveau tableau,
des le premier element (0) jusqu'à jour actuel, donc lundi et mardi */
//console.log(joursEnOrdre);
|
const currentInputValues = {
firstName: 'S', // Must be at least 2 characters
lastName: '', // Must be at least than 2 characters
zipCode: '12345', // Must be exactly 5 characters
state: '', // Must be exactly 2 characters
}
const inputCriteria = {
firstName: [
value => value.length >= 2 ? '': 'First name must be at least 2 characters'
],
lastName: [],
zipCode: [],
state: [],
};
const getErrorMessages = (inputs, criteria) => {
let inputsArray = Object.keys(inputs);
return inputsArray.reduce((acc, fieldName)=>[...acc, ...criteria[fieldName].map(test=>test(inputs[fieldName]))].filter(message=> message),[]);
}
console.log(getErrorMessages(currentInputValues, inputCriteria));
/*
Expected Output: [
'First name must be at least 2 characters',
'Last name must be at least 2 characters',
'Zip code must be exactly 5 characters',
'State must be exactly 2 characters',
]
*/
|
import React, { Component } from 'react';
export default class MyComponent extends Component {
constructor(props) {
super(props);
}
render() {
console.log('in the thing', this.props);
return (
<div>
<h1>Hello, React!</h1>
<p>Count: {this.props.count}</p>
</div>
)
}
}
|
const mongoose = require('mongoose');
const albumSchema = new mongoose.Schema({
band: {
type: String,
required: true
},
albumName: {
type: String,
required: true
},
genre: {
type: String,
required: true,
enum: ['Rock', 'Jazz', 'Classical', 'Electronic', 'Hip-Hop', 'Country', 'Folk', 'Latin', 'Other']
},
productionDetails: {
producer: String,
label: String,
releaseDate: Date
}
});
const Album = mongoose.model('Album', albumSchema);
module.exports = Album;
|
function testMapObj() {
let phonebook = new Map();
phonebook.set("Ivan", 3596526826654);
phonebook.set("Petyo", 35956565656656);
phonebook.set("Ivan", 091510);
// Convert Map Object to Array and print
[...phonebook].forEach(([name, number]) => console.log(number));
}
testMapObj();
|
import React from 'react'
const PageSection = (props) => {
return (
<div className={`page-section ${props.extraStyles}`}>
<div className="ps-title"><b>{props.title}</b></div>
</div>
)
}
export default PageSection
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Event = require('./Event');
const reviewSchema = require('./review');
const venueSchema = Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
location: {
type: String,
required: true,
},
contact: {
name: String,
phone: String,
email: String,
},
website: String,
photo: String,
reviews: [reviewSchema],
createdBy: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
},
});
// venueSchema.pre('remove', async (next) => {
// await Event.deleteMany({ venue: this._id });
// next();
// });
module.exports = mongoose.model('Venue', venueSchema);
|
const fs = require('fs');
const jsonld = require('jsonld');
var Ajv = require('ajv');
var path = require('path');
// Takes the second argument as the TD to validate
var storedTdAddress;
const schemaLocation = path.join(__dirname, '..', 'WebContent', 'td-schema.json');
const draftLocation = path.join(__dirname, '..', 'WebContent', 'json-schema-draft-07.json');
//console.log("argv is ", process.argv);
if (process.argv[2]) {
//console.log("there is second arg");
if (typeof process.argv[2] === "string") {
console.log("Taking TD found at ", process.argv[2], " for validation");
storedTdAddress = process.argv[2];
} else {
console.error("Second argument should be string");
throw "Argument error";
}
} else {
console.error("There is NO second argument, put the location of the TD after the script call");
throw "Argument error";
}
fs.readFile(storedTdAddress, (err, tdData) => {
if (err) {
console.error("Thing Description could not be found at ", storedTdAddress);
throw err;
};
try {
var tdJson = JSON.parse(tdData);
console.log('JSON validation... OK');
} catch (err) {
console.error('X JSON validation... KO:');
console.error('> ' + err.message);
throw err;
}
//console.log(td);
fs.readFile(schemaLocation, (err, schemaData) => {
if (err) {
console.error("JSON Schema could not be found at ", schemaLocation);
throw err;
};
console.log("Taking Schema found at ", schemaLocation);
var schema = JSON.parse(schemaData);
fs.readFile(draftLocation, (err, draftData) => {
if (err) {
console.error("JSON Schema Draft could not be found at ", draftLocation);
throw err;
};
console.log("Taking Schema Draft found at ", draftLocation);
var draft = JSON.parse(draftData);
var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true}
// ajv.addMetaSchema(draft);
ajv.addSchema(schema, 'td');
// schema validation
if (tdJson.hasOwnProperty('properties') || tdJson.hasOwnProperty('actions') || tdJson.hasOwnProperty('events')) {
if (!tdJson.hasOwnProperty('base')) {
//no need to do something. Each href should be absolute
console.log(':) Tip: Without base, each href should be an absolute URL');
}
}
var valid = ajv.validate('td', tdJson);
//used to be var valid = ajv.validate('td', e.detail);
if (valid) {
console.log('JSON Schema validation... OK');
checkEnumConst(tdJson);
checkPropItems(tdJson);
checkInteractions(tdJson);
checkSecurity(tdJson);
// checkUniqueness(tdJson);
} else {
console.log('X JSON Schema validation... KO:');
//console.log(ajv.errors);
//TODO: Handle long error messages in case of oneOf
console.log('> ' + ajv.errorsText());
}
//json ld validation
jsonld.toRDF(tdJson, {
format: 'application/nquads'
}, function (err, triples) {
if (!err) {
console.log('JSON-LD validation... OK');
} else {
console.log('X JSON-LD validation... KO:');
console.log('> ' + err);
}
});
});
});
});
function ValidURL(str) {
var localAjv = Ajv();
localAjv.addSchema({
"type": "string",
"format": "uri",
"pattern": "(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(([^#]*))?(#(.*))?"
}, 'url');
return localAjv.validate('url', str);
}
//checking whether a data schema has enum and const at the same and displaying a warning in case there are
function checkEnumConst(td) {
if (td.hasOwnProperty("properties")) {
//checking properties
tdProperties = Object.keys(td.properties);
for (var i = 0; i < tdProperties.length; i++) {
var curPropertyName = tdProperties[i];
var curProperty = td.properties[curPropertyName];
if (curProperty.hasOwnProperty("enum") && curProperty.hasOwnProperty("const")) {
console.log('! Warning: In property ' + curPropertyName + ' enum and const are used at the same time, the values in enum can never be valid in the received JSON value');
}
}
}
//checking actions
if (td.hasOwnProperty("actions")) {
tdActions = Object.keys(td.actions);
for (var i = 0; i < tdActions.length; i++) {
var curActionName = tdActions[i];
var curAction = td.actions[curActionName];
if (curAction.hasOwnProperty("input")) {
var curInput = curAction.input;
if (curInput.hasOwnProperty("enum") && curInput.hasOwnProperty("const")) {
console.log('! Warning: In the input of action ' + curActionName + ' enum and const are used at the same time, the values in enum can never be valid in the received JSON value');
}
}
if (curAction.hasOwnProperty("output")) {
var curOutput = curAction.output;
if (curOutput.hasOwnProperty("enum") && curOutput.hasOwnProperty("const")) {
console.warn('! Warning: In the output of action ' + curActionName + ' enum and const are used at the same time, the values in enum can never be valid in the received JSON value');
}
}
}
}
//checking events
if (td.hasOwnProperty("events")) {
tdEvents = Object.keys(td.events);
for (var i = 0; i < tdEvents.length; i++) {
var curEventName = tdEvents[i];
var curEvent = td.events[curEventName];
if (curEvent.hasOwnProperty("enum") && curEvent.hasOwnProperty("const")) {
console.log('! Warning: In event ' + curEventName + ' enum and const are used at the same time, the values in enum can never be valid in the received JSON value');
}
}
}
return;
}
//checking whether a data schema has object but not properties, array but no items
function checkPropItems(td) {
if (td.hasOwnProperty("properties")) {
//checking properties
tdProperties = Object.keys(td.properties);
for (var i = 0; i < tdProperties.length; i++) {
var curPropertyName = tdProperties[i];
var curProperty = td.properties[curPropertyName];
if (curProperty.hasOwnProperty("type")) {
if ((curProperty.type == "object") && !(curProperty.hasOwnProperty("properties"))) {
console.log('! Warning: In property ' + curPropertyName + ', the type is object but its properties are not specified');
}
if ((curProperty.type == "array") && !(curProperty.hasOwnProperty("items"))) {
console.log('! Warning: In property ' + curPropertyName + ', the type is array but its items are not specified');
}
}
}
}
//checking actions
if (td.hasOwnProperty("actions")) {
tdActions = Object.keys(td.actions);
for (var i = 0; i < tdActions.length; i++) {
var curActionName = tdActions[i];
var curAction = td.actions[curActionName];
if (curAction.hasOwnProperty("input")) {
var curInput = curAction.input;
if (curInput.hasOwnProperty("type")) {
if ((curInput.type == "object") && !(curInput.hasOwnProperty("properties"))) {
console.log('! Warning: In the input of action ' + curActionName + ', the type is object but its properties are not specified');
}
if ((curInput.type == "array") && !(curInput.hasOwnProperty("items"))) {
console.log('! Warning: In the output of action ' + curActionName + ', the type is array but its items are not specified');
}
}
}
if (curAction.hasOwnProperty("output")) {
var curOutput = curAction.output;
if (curOutput.hasOwnProperty("type")) {
if ((curOutput.type == "object") && !(curOutput.hasOwnProperty("properties"))) {
console.log('! Warning: In the output of action ' + curActionName + ', the type is object but its properties are not specified');
}
if ((curOutput.type == "array") && !(curOutput.hasOwnProperty("items"))) {
console.log('! Warning: In the output of action ' + curActionName + ', the type is array but its items are not specified');
}
}
}
}
}
//checking events
if (td.hasOwnProperty("events")) {
tdEvents = Object.keys(td.events);
for (var i = 0; i < tdEvents.length; i++) {
var curEventName = tdEvents[i];
var curEvent = td.events[curEventName];
if (curEvent.hasOwnProperty("type")) {
if ((curEvent.type == "object") && !(curEvent.hasOwnProperty("properties"))) {
console.log('! In event ' + curEventName + ', the type is object but its properties are not specified');
}
if ((curEvent.type == "array") && !(curEvent.hasOwnProperty("items"))) {
console.log('! In event ' + curEventName + ', the type is array but its items are not specified');
}
}
}
}
return;
}
//checking whether the td contains interactions field that is remaining from the previous spec
function checkInteractions(td) {
if (td.hasOwnProperty("interactions")) {
console.log('! Warning: interactions are from the previous TD Specification, please use properties, actions, events instead');
}
if (td.hasOwnProperty("interaction")) {
console.log('! Warning: interaction are from the previous TD Specification, please use properties, actions, events instead');
}
return;
}
function securityContains(parent, child) {
//security anywhere could be a string or array. Convert string to array
if (typeof child=="string"){
child=[child];
}
return child.every(elem => parent.indexOf(elem) > -1);
}
function checkSecurity(td) {
if (td.hasOwnProperty("securityDefinitions")) {
var securityDefinitionsObject = td.securityDefinitions;
var securityDefinitions = Object.keys(securityDefinitionsObject);
var rootSecurity = td.security;
if (securityContains(securityDefinitions, rootSecurity)) {
// all good
} else {
console.log('KO Error: Security key in the root of the TD has security schemes not defined by the securityDefinitions');
}
if (td.hasOwnProperty("properties")) {
//checking security in property level
tdProperties = Object.keys(td.properties);
for (var i = 0; i < tdProperties.length; i++) {
var curPropertyName = tdProperties[i];
var curProperty = td.properties[curPropertyName];
// checking security in forms level
var curForms = curProperty.forms;
for (var j = 0; j < curForms.length; j++) {
var curForm = curForms[j];
if (curForm.hasOwnProperty("security")) {
var curSecurity = curForm.security;
if (securityContains(securityDefinitions, curSecurity)) {
// all good
} else {
console.log('KO Error: Security key in form ' + j + ' in property ' + curPropertyName + ' has security schemes not defined by the securityDefinitions');
}
}
}
}
}
if (td.hasOwnProperty("actions")) {
//checking security in action level
tdActions = Object.keys(td.actions);
for (var i = 0; i < tdActions.length; i++) {
var curActionName = tdActions[i];
var curAction = td.actions[curActionName];
// checking security in forms level
var curForms = curAction.forms;
for (var j = 0; j < curForms.length; j++) {
var curForm = curForms[j];
if (curForm.hasOwnProperty("security")) {
var curSecurity = curForm.security;
if (securityContains(securityDefinitions, curSecurity)) {
// all good
} else {
console.log('KO Error: Security key in form ' + j + ' in action ' + curActionName + ' has security schemes not defined by the securityDefinitions');
}
}
}
}
}
if (td.hasOwnProperty("events")) {
//checking security in event level
tdEvents = Object.keys(td.events);
for (var i = 0; i < tdEvents.length; i++) {
var curEventName = tdEvents[i];
var curEvent = td.events[curEventName];
// checking security in forms level
var curForms = curEvent.forms;
for (var j = 0; j < curForms.length; j++) {
var curForm = curForms[j];
if (curForm.hasOwnProperty("security")) {
var curSecurity = curForm.security;
if (securityContains(securityDefinitions, curSecurity)) {
// all good
} else {
console.log('KO Error: Security key in form ' + j + ' in event ' + curEventName + ' has security schemes not defined by the securityDefinitions');
}
}
}
}
}
} else {
console.log('KO Error: securityDefinitions is mandatory');
}
return;
}
function checkUniqueness(td) {
// building the interaction name array
var tdInteractions = [];
if (td.hasOwnProperty("properties")) {
tdInteractions = tdInteractions.concat(Object.keys(td.properties));
}
if (td.hasOwnProperty("actions")) {
tdInteractions = tdInteractions.concat(Object.keys(td.actions));
}
if (td.hasOwnProperty("events")) {
tdInteractions = tdInteractions.concat(Object.keys(td.events));
}
// checking uniqueness
isDuplicate = (new Set(tdInteractions)).size !== tdInteractions.length;
console.log(isDuplicate);
if (isDuplicate) {
console.log('KO Error: Duplicate names are not allowed in Interactions');
}
return;
}
|
/*@ngInject*/
module.exports = function ($resource) {
return $resource('/api/config', {}, {
getInterval: {
method: 'GET',
url: '/api/interval'
},
getNotice: {
method: 'GET',
url: '/api/notice'
},
getLanguage: {
method: 'GET',
url: '/api/language'
}
});
};
|
import React from "react";
import PropTypes from "prop-types";
import "./button-group.css";
const Group = props => (
<div
className="ui btn-group">
{ // set the color prop for all children if props.color is present
props.color ? (
props.children.map(child => React.cloneElement(child, {color: props.color}))
) : (
props.children
)}
</div>
);
Group.propTypes = {
children: PropTypes.node,
color: PropTypes.string,
};
export default Group;
|
import React, { Component } from 'react';
import scss from './TableHeader.module.scss';
import PropTypes from 'prop-types';
import classNames from 'classnames';
class TableHeader extends Component {
state = {
headers: this.props.headers,
totalColumns: this.props.totalColumns,
prevX: 0
};
handleHeaderDragStart = (event, col, index) => {
this.props.handleHeaderDragStart(event, col, index);
}
handleHeaderDragStop = (event, col, index) => {
this.props.handleHeaderDragStop(event, col, index);
}
render () {
let height = 48;
let widthAdditions = 0;
let resizeHandleStyles = {
resizeHandleStyle: {
height: height,
position: 'absolute',
width: 7,
cursor: 'ew-resize',
marginLeft: -3,
zIndex: 2,
MozBoxSizing: 'border-box',
boxSizing: 'border-box'
},
};
let handles = this.state.headers.map((col, index) => {
//determining position of resize handles
widthAdditions = widthAdditions + col.width;
resizeHandleStyles.leftPos = {left: widthAdditions};
let curStyle = (index < (this.state.totalColumns)) ? resizeHandleStyles.resizeHandleStyle : null;
curStyle = {...curStyle,...resizeHandleStyles.leftPos}
return (
<div key={col.name} style={curStyle}
data_index={index}
draggable="true"
onDragStart={(event) => this.handleHeaderDragStart(event, col, index)}
onDragEnd={(event) => this.handleHeaderDragStop(event, col, index)}>
</div>
);
});
let headers = this.state.headers.map((header,index) => {
let click = null;
let ttl = null;
switch (index) {
case 0:
click = this.props.level1HeaderClick;
ttl = this.props.ttlPub;
break;
case 1:
click = this.props.level2HeaderClick;
ttl = this.props.ttlPla;
break;
case 4:
click = this.props.level3HeaderClick;
ttl = this.props.ttlCre;
break;
default:
break;
}
return (
<div
onClick={click}
key={header.name}
style={{width:header.width+'px'}}
className={classNames(scss.TrafficHeader, "TrafficHeader")}
>
<span className={ttl > 0 ? scss.trafficHeaderLbl:null}>{header.name}</span>
{ttl > 0 ? <span className={scss.TrafficHeaderTtl}>{ttl}</span>:null}
</div>
)
});
return (
<React.Fragment>
<div className={scss.resize_container}>
{handles}
</div>
<div className={scss.TrafficHeaderContainer}>
{headers}
</div>
</React.Fragment>
)
}
}
TableHeader.propTypes = {
handleHeaderDragStart: PropTypes.func.isRequired,
handleHeaderDragStop: PropTypes.func.isRequired,
headers: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string.isRequired,
width: PropTypes.number.isRequired,
key: PropTypes.string.isRequired
})).isRequired,
totalColumns: PropTypes.number.isRequired,
level1HeaderClick: PropTypes.func,
level2HeaderClick: PropTypes.func,
level3HeaderClick: PropTypes.func,
ttlPub: PropTypes.number,
ttlPla: PropTypes.number,
ttlcre: PropTypes.number
};
export default TableHeader;
|
import ProductCard from "./ProductCard";
function Snakes() {
return (
<div className="row">
<ProductCard img="https://jagdishfarshan.com/Upload/Product/1334/dd0beaf14bec4a0a9a81d389b8c9410d.jpg" name="Lilo Chevdo" price="₹ 210.00 / 500gm"/>
<ProductCard img="https://jagdishfarshan.com/Upload/Product/1347/ba76e90988fa459a93b84addb8768199.jpg" name="Lilo Chevdo" price="₹ 210.00 / 500gm"/>
<ProductCard img="https://jagdishfarshan.com/Upload/Product/207/a15cc313aceb4e5eb34d0e156e374a31.jpg" name="Lilo Chevdo" price="₹ 210.00 / 500gm"/>
</div>
);
}
export default Snakes;
|
angular.module('auth', [
'ng', //$http
'ui.bootstrap', //dialog
'http-auth-interceptor', //401 capture
'ngResource', //$resource
'cache', //CacheBuilder
'sockjs', //sock for comment cache
'alerts' //Alerter
])
.config(function(authServiceProvider) {
authServiceProvider.addIgnoreUrlExpression(function (response) {
return response.config.url === "/auth";
});
})
.factory('UserResource', function ($resource) {
var UserResource = $resource(
'/1.0/users/:Username',
{},
{}
);
return UserResource;
})
.factory('UserDirectionResource', function ($resource) {
var UserDirectionResource = $resource(
'/1.0/users/:Username/direction',
{ Username: '@Username' },
{
update: { method: 'PUT' }
}
);
return UserDirectionResource;
})
.factory('UserDirectionCache', function($rootScope, SockJS, UserDirectionResource) {
function UserDirectionCache(username) {
var self = this;
this.direction = {
Username: username,
Heading: 0
};
this.stream = new SockJS('/1.0/streaming/users/'+this.direction.Username+'/direction');
function updateDirection(newDirection) {
for(var key in newDirection) {
self.direction[key] = newDirection[key];
}
}
this.stream.onopen = function() {
};
this.stream.onmessage = function(e) {
var bundle = e.data;
if(bundle.Action == "update") {
//Often if the user created the item, it will already be in place so treat as an update
updateDirection(bundle.Val);
}
$rootScope.$digest();
};
this.stream.onclose = function() {
};
this.init = function() {
UserDirectionResource.get(
this.direction,
function(direction) {
updateDirection(direction);
},
function(e) {
console.log(e);
}
);
};
this.close = function() {
this.stream.close();
}
this.init();
this.update = function(direction, sucess, failure) {
UserDirectionResource.update(
direction,
function() {
//Success do nothing!
if(angular.isFunction(sucess)) sucess();
},
function(e) {
if(e.status != 304) {
Alerter.error("There was a problem updating the ranking. "+"Status:"+e.status+". Reply Body:"+e.data);
console.log(e);
}
if(angular.isFunction(failure)) failure(e);
}
);
};
}
return UserDirectionCache;
})
.controller('LoginPanelCtrl', function($scope, $http, authService, UserResource, Alerter) {
$scope.login = function() {
$http.post("/auth", {Username: $scope.username, Password: $scope.password})
.success(function(data, status, headers) {
$scope.cancel('success');
authService.loginConfirmed();
})
.error(function(data, status, headers) {
$scope.failedLogin = true;
console.log("Login Problem", data, status);
Alerter.error("Invalid login credentials.", 2000);
});
};
$scope.signup = function() {
UserResource.save(
{Username: $scope.username, Password: $scope.password},
function() {
Alerter.success("User "+$scope.username+" created!", 2000);
},
function(e) {
Alerter.error(e.data, 2000);
console.log(e);
}
);
};
$scope.cancel = function(result) {
if($scope.dialog !== undefined) {
$scope.dialog.close(result);
}
};
})
.directive('loginPanel', function(authService) {
return {
restrict: 'E',
scope: {
dialog: "="
},
templateUrl: '/template/auth/login-panel.html',
controller: 'LoginPanelCtrl',
link: function(scope, element, attrs) {
}
};
})
.controller('LoginDialogCtrl', function($scope, dialog) {
$scope.dialog = dialog;
})
.factory('LoginDialog', function ($dialog) {
return {
open: function(item) {
var d = $dialog.dialog({
modalFade: false,
backdrop: true,
keyboard: true,
backdropClick: false,
dialogClass: 'modal login-modal',
resolve: {item: function() { return item; }},
templateUrl: '/template/auth/login-panel-dialog.html',
controller: 'LoginDialogCtrl'
});
return d.open();
}
};
});
|
'use strict';
var MockFirestoreDeltaDocumentSnapshot = require('./firestore-delta-document-snapshot');
exports.MockFirebase = require('./firebase');
exports.MockFirebaseSdk = require('./sdk');
exports.MockFirestore = require('./firestore');
exports.DeltaDocumentSnapshot = MockFirestoreDeltaDocumentSnapshot.create;
/** @deprecated */
exports.MockFirebaseSimpleLogin = require('./login');
|
P.views.calendar = {};
|
module.exports = {
siteMetadata: {
title: `Elliot Evans Site`,
description: `Elliot Evans's personal Portfolio / Blog site`,
author: `Elliot Evans`,
siteUrl: `https://elliotevans.site`,
},
plugins: [
{
resolve: `gatsby-transformer-json`,
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `posts`,
path: `${__dirname}/src/data/posts`,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `site`,
path: `${__dirname}/src/data/site`,
},
},
`gatsby-transformer-remark`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: 'icons',
path: `${__dirname}/src/assets/icons`,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: 'images',
path: `${__dirname}/src/assets/images`,
},
},
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`,
`gatsby-plugin-typescript`,
`gatsby-plugin-react-helmet`,
`gatsby-plugin-emotion`,
`gatsby-transformer-remark`,
`gatsby-plugin-offline`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `Elliot Evans' Blog`,
short_name: `Elliot Evans Blog`,
lang: "en",
description: "Elliot Evans' blog",
start_url: `/`,
background_color: `#252525`,
theme_color: `#C85127`,
display: `standalone`,
icon: `src/assets/images/header-icon.webp`,
legacy: false,
},
},
{
resolve: "gatsby-plugin-svgr-loader",
options: {
rule: {
include: /assets/
}
}
},
`gatsby-plugin-feed`,
`gatsby-plugin-sitemap`,
],
};
|
class lap {
constructor(no,co,x,y,an,la,gro,ba){
this.nombre = no;
this.color = co;
this.X = x;
this.Y = y;
this.ancho = an;
this.largo = la;
this.grosor = gro;
this.banda = ba;
}
Dibujar(context){
//parte de arriba
context.beginPath();
context.fillStyle = this.color;
context.rect(this.X, this.Y, this.ancho, this.largo);
context.fill();
context.stroke();
//pantalla
context.beginPath();
context.fillStyle = "grey";
context.rect(this.X+this.banda, this.Y+this.banda, this.ancho-2*(this.banda), this.largo-2*(this.banda));
context.fill();
context.stroke();
//parte de ancho
context.beginPath();
context.fillStyle = "grey";
context.moveTo(this.X, this.Y+this.largo+this.grosor/2);
context.lineTo(this.X+(this.ancho*Math.cos(20)), this.largo+this.Y+ (this.largo*Math.cos(20))+this.grosor);
context.lineTo(this.X+(this.ancho*Math.cos(20))+this.ancho, this.largo+this.Y+ (this.largo*Math.cos(20))+this.grosor);
context.lineTo(this.X+this.ancho+this.grosor, this.Y+this.largo+this.grosor);
context.closePath();
context.fill();
//parte de abajo
context.beginPath();
context.fillStyle = this.color;
context.moveTo(this.X, this.Y+this.largo);
context.lineTo(this.X+(this.ancho*Math.cos(20)), this.largo+this.Y+ (this.largo*Math.cos(20)));
context.lineTo(this.X+(this.ancho*Math.cos(20))+this.ancho, this.largo+this.Y+ (this.largo*Math.cos(20)));
context.lineTo(this.X+this.ancho, this.Y+this.largo);
context.closePath();
context.fill();
//teclado
context.beginPath();
context.fillStyle = "black";
context.moveTo(this.X+(this.ancho*Math.cos(30)), this.Y+this.largo+this.grosor);
context.lineTo(this.X+(this.ancho*Math.cos(20))+this.grosor, this.largo+this.Y+ (this.largo*Math.cos(20))-this.grosor);
context.lineTo(this.X+(this.ancho*Math.cos(20))+0.8*this.ancho, this.largo+this.Y+ (this.largo*Math.cos(20))-this.grosor);
context.lineTo(this.X+this.ancho-this.grosor, this.Y+this.largo+this.grosor);
context.closePath();
context.fill();
context.stroke();
}
}
|
var http = require('http');
var apiHost = 'localhost';
var apiPort = 8002;
var apiKey = 'special-key';
var gToken = null;
function createUser(test, uName, uMail, uPass, resErr, resName) {
test.expect(2);
var post_data = 'data=' + JSON.stringify({"name": uName,"password": uPass,"mail": uMail});
var post_options = {
host: apiHost,
port: apiPort,
path: '/user.json?api_key=' + apiKey,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
};
// Set up the request
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
try {
var re = JSON.parse(chunk);
test.equal(re.code, resErr, "error must not be set");
test.equal(re.name, resName, "user not created");
test.done();
} catch (e) {
test.done();
}
});
});
post_req.write(post_data);
post_req.end();
}
function deleteUser(test, uName, uPass, resErr, resName) {
test.expect(2);
var post_data = 'name=' + uName + "&password=" + uPass;
var post_options = {
host: apiHost,
port: apiPort,
path: '/user.json?api_key=' + apiKey,
method: 'DELETE',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
};
// Set up the request
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
try {
var re = JSON.parse(chunk);
test.equal(re.code, resErr, "error must not be set");
test.equal(re.name, resName, "user not removed");
test.done();
} catch (e) {
test.done();
}
});
});
post_req.write(post_data);
post_req.end();
}
exports['Block user names < 4 chars '] = function(test) {
createUser(test, 'us1', "lorem@example.com", 'lorem123', 400, undefined);
};
exports['Block malformed user name'] = function(test) {
createUser(test, 'lorem ipsum', "lorem@example.com", 'lorem123', 400, undefined);
};
exports['Block missing email address'] = function(test) {
createUser(test, 'user1', "", 'lorem123', 400, undefined);
};
exports['Block malformed email address'] = function(test) {
createUser(test, 'user1', "()@example.com", 'lorem123', 400, undefined);
};
exports['Create User'] = function(test) {
createUser(test, 'user1', "lorem@example.com", 'lorem123', undefined, 'user1');
};
exports['Block Re-Creation of User'] = function(test) {
createUser(test, 'user1', "lorem@example.com", 'lorem123', 400, undefined);
};
exports['Delete User'] = function(test) {
deleteUser(test, 'user1', 'lorem123', undefined, 'user1');
};
exports['Re-Create User'] = function(test) {
createUser(test, 'user1', "lorem@example.com", 'lorem123', undefined, 'user1');
};
exports['Create Token for User'] = function(test) {
test.expect(2);
var post_data = "name=user1&password=lorem123";
var post_options = {
host: apiHost,
port: apiPort,
path: '/user.json/session?api_key=' + apiKey,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
};
// Set up the request
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
try {
var re = JSON.parse(chunk);
test.equal(re.code, undefined, "error must not be set");
test.notEqual(re.token, undefined, "token must be received");
gToken = re.token;
test.done();
} catch (e) {
test.done();
}
});
});
post_req.write(post_data);
post_req.end();
};
exports['Check User Token'] = function(test) {
test.expect(2);
var post_options = {
host: apiHost,
port: apiPort,
path: '/user.json/session/' + gToken + '?api_key=' + apiKey,
method: 'GET'
};
// Set up the request
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
try {
var re = JSON.parse(chunk);
test.equal(re.code, undefined, "error must not be set");
test.equal(re.token, gToken, "token must be received");
test.done();
} catch (e) {
test.done();
}
});
});
post_req.end();
};
exports['Get User Details'] = function(test) {
test.expect(2);
var post_options = {
host: apiHost,
port: apiPort,
path: '/user.json/user1?api_key=' + apiKey,
method: 'GET'
};
// Set up the request
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
try {
var re = JSON.parse(chunk);
test.equal(re.code, undefined, "error must not be set");
test.equal(re.name, 'user1', "token must be received");
test.done();
} catch (e) {
test.done();
}
});
});
post_req.end();
};
exports['Delete User again'] = function(test) {
deleteUser(test, 'user1', 'lorem123', undefined, 'user1');
};
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var selectedPerspectiveView = "member";
var selectedMemberViewOption = "default";
var selectedViewTypeDefault = ""; //"rgraph";
var selectedViewTypeSG = "treemap";
var selectedViewTypeRZ = "treemap";
var selectedViewTypeData = "treemap";
var gblClusterMembers = null;
/**
* This JS File is used for Cluster Details screen
*
*/
// This function is the initialization function for Cluster Details screen. It
// is
// making call to functions defined for different widgets used on this screen
$(document).ready(function() {
// Load Notification HTML
generateNotificationsPanel();
// modify UI text as per requirement
customizeUI();
alterHtmlContainer(CONST_BACKEND_PRODUCT_GEMFIRE);
// "ClusterDetails" service callback handler
getClusterDetailsBack = getClusterDetailsGemfireBack;
// "ClusterKeyStatistics" service callback handler
getClusterKeyStatisticsBack = getClusterKeyStatisticsGemfireBack;
// Add hostspot attributes
hotspotAttributes = [];
hotspotAttributes.push({"id":"currentHeapUsage", "name":"Heap Usage"});
hotspotAttributes.push({"id":"cpuUsage", "name":"CPU Usage"});
// Initialize set up for hotspot
initHotspotDropDown();
scanPageForWidgets();
// Default view - creating blank cluster members tree map
createMembersTreeMapDefault();
$('#default_treemap_block').hide();
// Default view - creating blank cluster members grid
createMemberGridDefault();
// Default view - creating blank R Graph for all members associated with defined cluster
createClusteRGraph();
// Server Groups view - creating blank cluster members tree map
createMembersTreeMapSG();
$('#servergroups_treemap_block').hide();
// Server Groups view - creating blank cluster members grid
createMemberGridSG();
// Redundancy Zones view - creating blank cluster members tree map
createMembersTreeMapRZ();
$('#redundancyzones_treemap_block').hide();
// Redundancy Zones view - creating blank cluster members grid
createMemberGridRZ();
// Data view - creating blank cluster data/regions tree map
createRegionsTreeMapDefault();
$('#data_treemap_block').hide();
// Data view - creating blank cluster data/regions grid
createRegionsGridDefault();
$.ajaxSetup({
cache : false
});
});
/*
* Function to show and hide html elements/components based upon whether product
* is sqlfire or gemfire
*/
function alterHtmlContainer(prodname){
// Hide HTML for following
$('#subTabQueryStatistics').hide();
$('#TxnCommittedContainer').hide();
$('#TxnRollbackContainer').hide();
// Show HTML for following
$('#clusterUniqueCQsContainer').show();
$('#SubscriptionsContainer').show();
$('#queriesPerSecContainer').show();
}
// Function called when Hotspot is changed
function applyHotspot(){
var data = {};
data.members = gblClusterMembers;
if (flagActiveTab == "MEM_TREE_MAP_DEF") {
updateClusterMembersTreeMapDefault(data);
} else if (flagActiveTab == "MEM_TREE_MAP_SG") {
updateClusterMembersTreeMapSG(data);
} else if (flagActiveTab == "MEM_TREE_MAP_RZ") {
updateClusterMembersTreeMapRZ(data);
}
}
function translateGetClusterMemberBack(data) {
getClusterMembersBack(data.ClusterMembers);
}
function translateGetClusterMemberRGraphBack(data) {
getClusterMembersRGraphBack(data.ClusterMembersRGraph);
}
function translateGetClusterRegionsBack(data) {
getClusterRegionsBack(data.ClusterRegions);
}
// function used for creating blank TreeMap for member's on Cluster Details
// Screen
function createMembersTreeMapDefault() {
var dataVal = {
"$area" : 1,
"initial" : true
};
var json = {
"children" : {},
"data" : dataVal,
"id" : "root",
"name" : "Members"
};
clusterMemberTreeMap = new $jit.TM.Squarified(
{
injectInto : 'GraphTreeMap',
levelsToShow : 1,
titleHeight : 0,
background : '#a0c44a',
offset : 2,
Label : {
type : 'HTML',
size : 1
},
Node : {
CanvasStyles : {
shadowBlur : 0
}
},
Events : {
enable : true,
onMouseEnter : function(node, eventInfo) {
if (node) {
node.setCanvasStyle('shadowBlur', 7);
node.setData('border', '#ffffff');
clusterMemberTreeMap.fx.plotNode(node,
clusterMemberTreeMap.canvas);
clusterMemberTreeMap.labels.plotLabel(
clusterMemberTreeMap.canvas, node);
}
},
onMouseLeave : function(node) {
if (node) {
node.removeData('border', '#ffffff');
node.removeCanvasStyle('shadowBlur');
clusterMemberTreeMap.plot();
}
},
onClick : function(node) {
if (!node.data.initial) {
location.href = 'memberDetails.html?member=' + node.id
+ '&memberName=' + node.name;
}
}
},
Tips : {
enable : true,
offsetX : 5,
offsetY : 5,
onShow : function(tip, node, isLeaf, domElement) {
var html = "";
var data = node.data;
if (!data.initial) {
html = "<div class=\"tip-title\"><div><div class='popupHeading'>"
+ node.name
+ "</div>"
+ "<div class='popupFirstRow'><div class='popupRowBorder borderBottomZero'>"
+ "<div class='labeltext left display-block width-70'><span class='left'>CPU Usage</span></div><div class='right width-30'>"
+ "<div class='color-d2d5d7 font-size14'>"
+ data.cpuUsage
+ "<span class='fontSize15'>%</span></span></div>"
+ "</div></div>"
+ "<div class='popupRowBorder borderBottomZero'><div class='labeltext left display-block width-70'>"
+ "<span class='left'>Memory Usage</span></div><div class='right width-30'>"
+ "<div class='color-d2d5d7 font-size14'>"
+ data.heapUsage
+ "<span class='font-size15 paddingL5'>MB</span>"
+ "</div></div></div>"
+ "<div class='popupRowBorder borderBottomZero'><div class='labeltext left display-block width-70'>"
+ "<span class='left'>Load Avg.</span></div><div class='right width-30'>"
+ "<div class='color-d2d5d7 font-size14'>"
+ applyNotApplicableCheck(data.loadAvg)
+ "</div></div></div><div class='popupRowBorder borderBottomZero'><div class='labeltext left display-block width-70'>"
+ "<span class='left'>Threads</span></div><div class='right width-30'>"
+ "<div class='color-d2d5d7 font-size14'>"
+ data.threads
+ "</div></div></div><div class='popupRowBorder borderBottomZero'><div class='labeltext left display-block width-70'>"
+ "<span class='left'>Sockets</span></div><div class='right width-30'>"
+ "<div class='color-d2d5d7 font-size14'>"
+ applyNotApplicableCheck(data.sockets)
+ "</div></div></div><div class='popupRowBorder borderBottomZero'>"
+ "<div class='labeltext left display-block width-70'><span class='left'>Geode Version</span>"
+ "</div><div class='right width-30'><div class='color-d2d5d7 font-size14'>"
+ data.gemfireVersion + "</div></div>" + "</div>" + ""
+ "</div></div>" + "</div>";
} else {
html = "<div class=\"tip-title\"><div><div class='popupHeading'>Loading</div>";
}
tip.innerHTML = html;
}
},
onCreateLabel : function(domElement, node) {
//domElement.style.opacity = 0.01;
if(node.id == "root"){
domElement.innerHTML = "<div class='treemapRootNodeLabeltext'> </div>";
}else{
domElement.innerHTML = "<div class='treemapNodeLabeltext'>"+node.name+"</div>";
var style = domElement.style;
style.display = '';
style.border = '1px solid transparent';
domElement.onmouseover = function() {
style.border = '1px solid #ffffff';
};
domElement.onmouseout = function() {
style.border = '1px solid transparent';
};
}
}
});
clusterMemberTreeMap.loadJSON(json);
clusterMemberTreeMap.refresh();
}
//function used for creating blank TreeMap for member's on Servre Groups View
function createMembersTreeMapSG(){
var dataVal = {
"$area" : 1,
"initial" : true
};
var json = {
"children" : {},
"data" : dataVal,
"id" : "root",
"name" : "sgMembers"
};
clusterSGMemberTreeMap = new $jit.TM.Squarified(
{
injectInto : 'GraphTreeMapSG',
//levelsToShow : 1,
titleHeight : 15,
background : '#a0c44a',
offset : 1,
userData : {
isNodeEntered : false
},
Label : {
type : 'HTML',
size : 9
},
Node : {
CanvasStyles : {
shadowBlur : 0
}
},
Events : {
enable : true,
onMouseEnter : function(node, eventInfo) {
if (node && node.id != "root") {
node.setCanvasStyle('shadowBlur', 7);
node.setData('border', '#ffffff');
clusterSGMemberTreeMap.fx.plotNode(node,
clusterSGMemberTreeMap.canvas);
clusterSGMemberTreeMap.labels.plotLabel(
clusterSGMemberTreeMap.canvas, node);
}
},
onMouseLeave : function(node) {
if (node && node.id != "root") {
node.removeData('border', '#ffffff');
node.removeCanvasStyle('shadowBlur');
clusterSGMemberTreeMap.plot();
}
},
onClick : function(node) {
if (node) {
if(node._depth == 1){
var isSGNodeEntered = clusterSGMemberTreeMap.config.userData.isNodeEntered;
if(!isSGNodeEntered){
clusterSGMemberTreeMap.config.userData.isNodeEntered = true;
clusterSGMemberTreeMap.enter(node);
}else{
clusterSGMemberTreeMap.config.userData.isNodeEntered = false;
clusterSGMemberTreeMap.out();
}
} else if(node._depth == 2 && (!node.data.initial)){
location.href = 'memberDetails.html?member=' + node.data.id
+ '&memberName=' + node.data.name;
}
}
},
onRightClick: function() {
clusterSGMemberTreeMap.out();
}
},
Tips : {
enable : true,
offsetX : 5,
offsetY : 5,
onShow : function(tip, node, isLeaf, domElement) {
var html = "";
if(node && node.id != "root"){
var data = node.data;
if (!data.initial) {
if(node._depth == 1){
html = "<div class=\"tip-title\"><div><div class='popupHeading'>" + node.name + "</div>";
}else if(node._depth == 2){
html = "<div class=\"tip-title\"><div><div class='popupHeading'>"
+ node.name
+ "</div>"
+ "<div class='popupFirstRow'><div class='popupRowBorder borderBottomZero'>"
+ "<div class='labeltext left display-block width-70'><span class='left'>CPU Usage</span></div><div class='right width-30'>"
+ "<div class='color-d2d5d7 font-size14'>"
+ data.cpuUsage
+ "<span class='fontSize15'>%</span></span></div>"
+ "</div></div>"
+ "<div class='popupRowBorder borderBottomZero'><div class='labeltext left display-block width-70'>"
+ "<span class='left'>Memory Usage</span></div><div class='right width-30'>"
+ "<div class='color-d2d5d7 font-size14'>"
+ data.heapUsage
+ "<span class='font-size15 paddingL5'>MB</span>"
+ "</div></div></div>"
+ "<div class='popupRowBorder borderBottomZero'><div class='labeltext left display-block width-70'>"
+ "<span class='left'>Load Avg.</span></div><div class='right width-30'>"
+ "<div class='color-d2d5d7 font-size14'>"
+ applyNotApplicableCheck(data.loadAvg)
+ "</div></div></div><div class='popupRowBorder borderBottomZero'><div class='labeltext left display-block width-70'>"
+ "<span class='left'>Threads</span></div><div class='right width-30'>"
+ "<div class='color-d2d5d7 font-size14'>"
+ data.threads
+ "</div></div></div><div class='popupRowBorder borderBottomZero'><div class='labeltext left display-block width-70'>"
+ "<span class='left'>Sockets</span></div><div class='right width-30'>"
+ "<div class='color-d2d5d7 font-size14'>"
+ applyNotApplicableCheck(data.sockets)
+ "</div></div></div><div class='popupRowBorder borderBottomZero'>"
+ "<div class='labeltext left display-block width-70'><span class='left'>Geode Version</span>"
+ "</div><div class='right width-30'><div class='color-d2d5d7 font-size14'>"
+ data.gemfireVersion + "</div></div>" + "</div>" + ""
+ "</div></div>" + "</div>";
}
}else{
html = "<div class=\"tip-title\"><div><div class='popupHeading'>Loading Server Groups and Members</div>";
}
}else{
html = "<div class=\"tip-title\"><div><div class='popupHeading'>Cluster's Server Groups and Members</div>";
}
tip.innerHTML = html;
}
},
onBeforePlotNode: function(node) {
if(node._depth == 0) {
// Hide root node title bar
node.setData('color', '#132634');
} else if(node._depth == 1) {
node.setData('color', '#506D94');
}
},
onCreateLabel : function(domElement, node) {
//domElement.style.opacity = 0.01;
if(node._depth != 0){
domElement.innerHTML = "<div class='treemapNodeLabeltext'>"+node.name+"</div>";
var style = domElement.style;
style.display = '';
style.border = '1px solid transparent';
domElement.onmouseover = function() {
style.border = '1px solid #ffffff';
// Highlight this member in all server groups
if(this.id.indexOf("(!)") != -1){
var currSGMemberId = this.id.substring(this.id.indexOf("(!)")+3);
var sgMembersDOM = $("div[id$='"+currSGMemberId+"']");
for(var cntr=0; cntr<sgMembersDOM.length; cntr++){
sgMembersDOM[cntr].style.border = '1px solid #ffffff';
}
}
};
domElement.onmouseout = function() {
style.border = '1px solid transparent';
// Remove Highlighting of this member in all server groups
if(this.id.indexOf("(!)") != -1){
var currSGMemberId = this.id.substring(this.id.indexOf("(!)")+3);
var sgMembersDOM = $("div[id$='"+currSGMemberId+"']");
for(var cntr=0; cntr<sgMembersDOM.length; cntr++){
sgMembersDOM[cntr].style.border = '1px solid transparent';
}
}
};
}
}
});
clusterSGMemberTreeMap.loadJSON(json);
clusterSGMemberTreeMap.refresh();
}
//function used for creating blank TreeMap for member's on Redundancy Zones View
function createMembersTreeMapRZ(){
var dataVal = {
"$area" : 1,
"initial" : true
};
var json = {
"children" : {},
"data" : dataVal,
"id" : "root",
"name" : "rzMembers"
};
clusterRZMemberTreeMap = new $jit.TM.Squarified(
{
injectInto : 'GraphTreeMapRZ',
//levelsToShow : 1,
titleHeight : 15,
background : '#a0c44a',
offset : 1,
userData : {
isNodeEntered : false
},
Label : {
type : 'HTML',
size : 9
},
Node : {
CanvasStyles : {
shadowBlur : 0
}
},
Events : {
enable : true,
onMouseEnter : function(node, eventInfo) {
if (node && node.id != "root") {
node.setCanvasStyle('shadowBlur', 7);
node.setData('border', '#ffffff');
clusterRZMemberTreeMap.fx.plotNode(node,
clusterRZMemberTreeMap.canvas);
clusterRZMemberTreeMap.labels.plotLabel(
clusterRZMemberTreeMap.canvas, node);
}
},
onMouseLeave : function(node) {
if (node && node.id != "root") {
node.removeData('border', '#ffffff');
node.removeCanvasStyle('shadowBlur');
clusterRZMemberTreeMap.plot();
}
},
onClick : function(node) {
if (node) {
if(node._depth == 1){
var isRZNodeEntered = clusterRZMemberTreeMap.config.userData.isNodeEntered;
if(!isRZNodeEntered){
clusterRZMemberTreeMap.config.userData.isNodeEntered = true;
clusterRZMemberTreeMap.enter(node);
}else{
clusterRZMemberTreeMap.config.userData.isNodeEntered = false;
clusterRZMemberTreeMap.out();
}
} else if(node._depth == 2 && (!node.data.initial)){
location.href = 'memberDetails.html?member=' + node.data.id
+ '&memberName=' + node.data.name;
}
}
},
onRightClick: function() {
clusterRZMemberTreeMap.out();
}
},
Tips : {
enable : true,
offsetX : 5,
offsetY : 5,
onShow : function(tip, node, isLeaf, domElement) {
var html = "";
if(node && node.id != "root"){
var data = node.data;
if (!data.initial) {
if(node._depth == 1){
html = "<div class=\"tip-title\"><div><div class='popupHeading'>" + node.name + "</div>";
}else if(node._depth == 2){
html = "<div class=\"tip-title\"><div><div class='popupHeading'>"
+ node.name
+ "</div>"
+ "<div class='popupFirstRow'><div class='popupRowBorder borderBottomZero'>"
+ "<div class='labeltext left display-block width-70'><span class='left'>CPU Usage</span></div><div class='right width-30'>"
+ "<div class='color-d2d5d7 font-size14'>"
+ data.cpuUsage
+ "<span class='fontSize15'>%</span></span></div>"
+ "</div></div>"
+ "<div class='popupRowBorder borderBottomZero'><div class='labeltext left display-block width-70'>"
+ "<span class='left'>Memory Usage</span></div><div class='right width-30'>"
+ "<div class='color-d2d5d7 font-size14'>"
+ data.heapUsage
+ "<span class='font-size15 paddingL5'>MB</span>"
+ "</div></div></div>"
+ "<div class='popupRowBorder borderBottomZero'><div class='labeltext left display-block width-70'>"
+ "<span class='left'>Load Avg.</span></div><div class='right width-30'>"
+ "<div class='color-d2d5d7 font-size14'>"
+ applyNotApplicableCheck(data.loadAvg)
+ "</div></div></div><div class='popupRowBorder borderBottomZero'><div class='labeltext left display-block width-70'>"
+ "<span class='left'>Threads</span></div><div class='right width-30'>"
+ "<div class='color-d2d5d7 font-size14'>"
+ data.threads
+ "</div></div></div><div class='popupRowBorder borderBottomZero'><div class='labeltext left display-block width-70'>"
+ "<span class='left'>Sockets</span></div><div class='right width-30'>"
+ "<div class='color-d2d5d7 font-size14'>"
+ applyNotApplicableCheck(data.sockets)
+ "</div></div></div><div class='popupRowBorder borderBottomZero'>"
+ "<div class='labeltext left display-block width-70'><span class='left'>Geode Version</span>"
+ "</div><div class='right width-30'><div class='color-d2d5d7 font-size14'>"
+ data.gemfireVersion + "</div></div>" + "</div>" + ""
+ "</div></div>" + "</div>";
}
}else{
html = "<div class=\"tip-title\"><div><div class='popupHeading'>Loading Server Groups and Members</div>";
}
}else{
html = "<div class=\"tip-title\"><div><div class='popupHeading'>Cluster's Server Groups and Members</div>";
}
tip.innerHTML = html;
}
},
onBeforePlotNode: function(node) {
if(node._depth == 0) {
// Hide root node title bar
node.setData('color', '#132634');
} else if(node._depth == 1) {
node.setData('color', '#506D94');
}
},
onCreateLabel : function(domElement, node) {
//domElement.style.opacity = 0.01;
if(node._depth != 0){
domElement.innerHTML = "<div class='treemapNodeLabeltext'>"+node.name+"</div>";
var style = domElement.style;
style.display = '';
style.border = '1px solid transparent';
domElement.onmouseover = function() {
style.border = '1px solid #ffffff';
// Highlight this member in all redundancy zones
if(this.id.indexOf("(!)") != -1){
var currRZMemberId = this.id.substring(this.id.indexOf("(!)")+3);
var rzMembersDOM = $("div[id$='"+currRZMemberId+"']");
for(var cntr=0; cntr<rzMembersDOM.length; cntr++){
rzMembersDOM[cntr].style.border = '1px solid #ffffff';
}
}
};
domElement.onmouseout = function() {
style.border = '1px solid transparent';
// Remove Highlighting of this member in all redundancy zones
if(this.id.indexOf("(!)") != -1){
var currRZMemberId = this.id.substring(this.id.indexOf("(!)")+3);
var rzMembersDOM = $("div[id$='"+currRZMemberId+"']");
for(var cntr=0; cntr<rzMembersDOM.length; cntr++){
rzMembersDOM[cntr].style.border = '1px solid transparent';
}
}
};
}
}
});
clusterRZMemberTreeMap.loadJSON(json);
clusterRZMemberTreeMap.refresh();
}
//function used for creating blank TreeMap for cluster's regions on Data View
function createRegionsTreeMapDefault(){
var dataVal = {
"$area" : 1
};
var json = {
"children" : {},
"data" : dataVal,
"id" : "root",
"name" : "Regions"
};
clusterRegionsTreeMap = new $jit.TM.Squarified(
{
injectInto : 'GraphTreeMapClusterData',
levelsToShow : 1,
titleHeight : 0,
background : '#8c9aab',
offset : 2,
Label : {
type : 'Native',//HTML
size : 9
},
Node : {
CanvasStyles : {
shadowBlur : 0
}
},
Events : {
enable : true,
onMouseEnter : function(node, eventInfo) {
if (node && node.id != "root") {
node.setCanvasStyle('shadowBlur', 7);
node.setData('border', '#ffffff');
clusterRegionsTreeMap.fx.plotNode(node, clusterRegionsTreeMap.canvas);
clusterRegionsTreeMap.labels.plotLabel(clusterRegionsTreeMap.canvas, node);
}
},
onMouseLeave : function(node) {
if (node && node.id != "root") {
node.removeData('border', '#ffffff');
node.removeCanvasStyle('shadowBlur');
clusterRegionsTreeMap.plot();
}
},
onClick : function(node) {
if (node.id != "root") {
location.href ='regionDetail.html?regionFullPath='+node.data.regionPath;
}
}
},
Tips : {
enable : true,
offsetX : 5,
offsetY : 5,
onShow : function(tip, node, isLeaf, domElement) {
var data = node.data;
var html = "";
if (data.type) {
html = "<div class=\"tip-title\"><div><div class='popupHeading'>"
+ node.id
+ "</div>"
+ "<div class='popupFirstRow'><div class='popupRowBorder borderBottomZero'>"
+ "<div class='labeltext left display-block width-45'><span class='left'>"
+ "Type</span></div><div class='right width-55'>"
+ "<div class='color-d2d5d7 font-size14 popInnerBlockEllipsis'>"
+ data.type
+ "</div>"
+ "</div></div><div class='popupRowBorder borderBottomZero'><div class='labeltext left display-block width-45'>"
+ "<span class='left'>" + jQuery.i18n.prop('pulse-entrycount-custom') + "</span></div><div class='right width-55'>"
+ "<div class='color-d2d5d7 font-size14'>"
+ data.systemRegionEntryCount
+ "</div>"
+ "</div></div><div class='popupRowBorder borderBottomZero'><div class='labeltext left display-block width-45'>"
+ "<span class='left'>" + jQuery.i18n.prop('pulse-entrysize-custom') + "</span></div><div class='right width-55'>"
+ "<div class='color-d2d5d7 font-size14'>"
+ data.entrySize
+ "</div>"
/*+ "</div></div><div class='popupRowBorder borderBottomZero'><div class='labeltext left display-block width-45'>"
+ "<span class='left'>Compression Codec</span></div><div class='right width-55'>"
+ "<div class='color-d2d5d7 font-size14'>"
+ data.compressionCodec
+ "</div>"*/
+ "</div></div></div></div>" + "</div>";
} else {
html = "<div class=\"tip-title\"><div><div class='popupHeading'>No " + jQuery.i18n.prop('pulse-regiontabletooltip-custom') + " Found</div>";
}
tip.innerHTML = html;
}
},
onCreateLabel : function(domElement, node) {
domElement.innerHTML = node.name;
var style = domElement.style;
style.cursor = 'default';
style.border = '1px solid';
style.background = 'none repeat scroll 0 0 #606060';
domElement.onmouseover = function() {
style.border = '1px solid #9FD4FF';
style.background = 'none repeat scroll 0 0 #9FD4FF';
};
domElement.onmouseout = function() {
style.border = '1px solid';
style.background = 'none repeat scroll 0 0 #606060';
};
}
});
clusterRegionsTreeMap.loadJSON(json);
clusterRegionsTreeMap.refresh();
}
// function used for creating blank grids for member list for Cluster Details
// Screen
function createMemberGridDefault() {
jQuery("#memberList").jqGrid(
{
datatype : "local",
height : 360,
width : 740,
rowNum : 200,
shrinkToFit : false,
colNames : [ 'ID', 'Name', 'Host', 'Hostname For Clients', 'Heap Usage (MB)', 'CPU Usage (%)',
'Uptime', 'Clients', 'CurrentHeapSize', 'Load Avg', 'Threads',
'Sockets'],
colModel : [
{
name : 'memberId',
index : 'memberId',
width : 150,
sorttype : "string",
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject) ;
},
sortable : true
},
{
name : 'name',
index : 'name',
width : 120,
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "string"
},
{
name : 'host',
index : 'host',
width : 80,
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "string"
},
{
name : 'hostnameForClients',
index : 'hostnameForClients',
width : 90,
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "string"
},
{
name : 'currentHeapUsage',
index : 'currentHeapUsage',
width : 100,
align : 'right',
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "float"
},
{
name : 'cpuUsage',
index : 'cpuUsage',
align : 'right',
width : 100,
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "float"
},
{
name : 'uptime',
index : 'uptime',
width : 100,
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "int"
},
{
name : 'clients',
index : 'clients',
width : 100,
align : 'right',
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "int"
}, {
name : 'currentHeapUsage',
index : 'currentHeapUsage',
align : 'center',
width : 0,
hidden : true
}, {
name : 'loadAvg',
index : 'loadAvg',
align : 'center',
width : 0,
hidden : true
}, {
name : 'threads',
index : 'threads',
align : 'center',
width : 0,
hidden : true
}, {
name : 'sockets',
index : 'sockets',
align : 'center',
width : 0,
hidden : true
} ],
userData : {
"sortOrder" : "asc",
"sortColName" : "name"
},
onSortCol : function(columnName, columnIndex, sortorder) {
// Set sort order and sort column in user variables so that
// periodical updates can maintain the same
var gridUserData = jQuery("#memberList").getGridParam('userData');
gridUserData.sortColName = columnName;
gridUserData.sortOrder = sortorder;
},
onSelectRow : function(rowid, status, event) {
if (!event || event.which == 1) { // mouse left button click
var member = rowid.split("&");
location.href = 'memberDetails.html?member=' + member[0]
+ '&memberName=' + member[1];
}
},
resizeStop : function(width, index) {
var memberRegionsList = $('#gview_memberList');
var memberRegionsListChild = memberRegionsList
.children('.ui-jqgrid-bdiv');
var api = memberRegionsListChild.data('jsp');
api.reinitialise();
memberRegionsList = $('#gview_memberList');
memberRegionsListChild = memberRegionsList
.children('.ui-jqgrid-bdiv');
memberRegionsListChild.unbind('jsp-scroll-x');
memberRegionsListChild.bind('jsp-scroll-x', function(event,
scrollPositionX, isAtLeft, isAtRight) {
var mRList = $('#gview_memberList');
var mRLC = mRList.children('.ui-jqgrid-hdiv').children(
'.ui-jqgrid-hbox');
mRLC.css("position", "relative");
mRLC.css('right', scrollPositionX);
});
$('#default_grid_button').click();
refreshTheGrid($('#default_grid_button'));
},
gridComplete : function() {
$(".jqgrow").css({
cursor : 'default'
});
var memberRegionsList = $('#gview_memberList');
var memberRegionsListChild = memberRegionsList
.children('.ui-jqgrid-bdiv');
memberRegionsListChild.unbind('jsp-scroll-x');
memberRegionsListChild.bind('jsp-scroll-x', function(event,
scrollPositionX, isAtLeft, isAtRight) {
var mRList = $('#gview_memberList');
var mRLC = mRList.children('.ui-jqgrid-hdiv').children(
'.ui-jqgrid-hbox');
mRLC.css("position", "relative");
mRLC.css('right', scrollPositionX);
});
}
});
}
function createMemberGridSG() {
jQuery("#memberListSG").jqGrid(
{
datatype : "local",
height : 360,
width : 740,
rowNum : 200,
shrinkToFit : false,
colNames : [ 'Server Group','ID', 'Name', 'Host', 'Heap Usage (MB)', 'CPU Usage (%)',
'Uptime', 'Clients', 'CurrentHeapSize', 'Load Avg', 'Threads',
'Sockets'],
colModel : [
{
name : 'serverGroup',
index : 'serverGroup',
width : 170,
sorttype : "string",
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true
},
{
name : 'memberId',
index : 'memberId',
width : 170,
sorttype : "string",
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true
},
{
name : 'name',
index : 'name',
width : 150,
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "string"
},
{
name : 'host',
index : 'host',
width : 100,
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "string"
},
{
name : 'currentHeapUsage',
index : 'currentHeapUsage',
width : 110,
align : 'right',
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "float"
},
{
name : 'cpuUsage',
index : 'cpuUsage',
align : 'right',
width : 100,
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "float"
},
{
name : 'uptime',
index : 'uptime',
width : 100,
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "int"
},
{
name : 'clients',
index : 'clients',
width : 100,
align : 'right',
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "int"
}, {
name : 'currentHeapUsage',
index : 'currentHeapUsage',
align : 'center',
width : 0,
hidden : true
}, {
name : 'loadAvg',
index : 'loadAvg',
align : 'center',
width : 0,
hidden : true
}, {
name : 'threads',
index : 'threads',
align : 'center',
width : 0,
hidden : true
}, {
name : 'sockets',
index : 'sockets',
align : 'center',
width : 0,
hidden : true
} ],
userData : {
"sortOrder" : "asc",
"sortColName" : "serverGroup"
},
onSortCol : function(columnName, columnIndex, sortorder) {
// Set sort order and sort column in user variables so that
// periodical updates can maintain the same
var gridUserData = jQuery("#memberListSG").getGridParam('userData');
gridUserData.sortColName = columnName;
gridUserData.sortOrder = sortorder;
},
onSelectRow : function(rowid, status, event) {
if (!event || event.which == 1) { // mouse left button click
var member = rowid.split("&");
location.href = 'memberDetails.html?member=' + member[0]
+ '&memberName=' + member[1];
}
},
resizeStop : function(width, index) {
var memberRegionsList = $('#gview_memberListSG');
var memberRegionsListChild = memberRegionsList
.children('.ui-jqgrid-bdiv');
var api = memberRegionsListChild.data('jsp');
api.reinitialise();
memberRegionsList = $('#gview_memberListSG');
memberRegionsListChild = memberRegionsList
.children('.ui-jqgrid-bdiv');
memberRegionsListChild.unbind('jsp-scroll-x');
memberRegionsListChild.bind('jsp-scroll-x', function(event,
scrollPositionX, isAtLeft, isAtRight) {
var mRList = $('#gview_memberListSG');
var mRLC = mRList.children('.ui-jqgrid-hdiv').children(
'.ui-jqgrid-hbox');
mRLC.css("position", "relative");
mRLC.css('right', scrollPositionX);
});
$('#servergroups_grid_button').click();
refreshTheGrid($('#servergroups_grid_button'));
},
gridComplete : function() {
$(".jqgrow").css({
cursor : 'default'
});
var memberRegionsList = $('#gview_memberListSG');
var memberRegionsListChild = memberRegionsList
.children('.ui-jqgrid-bdiv');
memberRegionsListChild.unbind('jsp-scroll-x');
memberRegionsListChild.bind('jsp-scroll-x', function(event,
scrollPositionX, isAtLeft, isAtRight) {
var mRList = $('#gview_memberListSG');
var mRLC = mRList.children('.ui-jqgrid-hdiv').children(
'.ui-jqgrid-hbox');
mRLC.css("position", "relative");
mRLC.css('right', scrollPositionX);
});
}
});
}
function createMemberGridRZ() {
jQuery("#memberListRZ").jqGrid(
{
datatype : "local",
height : 360,
width : 740,
rowNum : 200,
shrinkToFit : false,
colNames : [ 'Redundancy Zone','ID', 'Name', 'Host', 'Heap Usage (MB)', 'CPU Usage (%)',
'Uptime', 'Clients', 'CurrentHeapSize', 'Load Avg', 'Threads',
'Sockets'],
colModel : [
{
name : 'redundancyZone',
index : 'redundancyZone',
width : 170,
sorttype : "string",
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true
},
{
name : 'memberId',
index : 'memberId',
width : 170,
sorttype : "string",
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true
},
{
name : 'name',
index : 'name',
width : 150,
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "string"
},
{
name : 'host',
index : 'host',
width : 100,
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "string"
},
{
name : 'currentHeapUsage',
index : 'currentHeapUsage',
width : 110,
align : 'right',
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "float"
},
{
name : 'cpuUsage',
index : 'cpuUsage',
align : 'right',
width : 100,
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "float"
},
{
name : 'uptime',
index : 'uptime',
width : 100,
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "int"
},
{
name : 'clients',
index : 'clients',
width : 100,
align : 'right',
cellattr : function(rowId, val, rawObject, cm, rdata) {
return formMemberGridToolTip(val, rawObject);
},
sortable : true,
sorttype : "int"
}, {
name : 'currentHeapUsage',
index : 'currentHeapUsage',
align : 'center',
width : 0,
hidden : true
}, {
name : 'loadAvg',
index : 'loadAvg',
align : 'center',
width : 0,
hidden : true
}, {
name : 'threads',
index : 'threads',
align : 'center',
width : 0,
hidden : true
}, {
name : 'sockets',
index : 'sockets',
align : 'center',
width : 0,
hidden : true
} ],
userData : {
"sortOrder" : "asc",
"sortColName" : "redundancyZone"
},
onSortCol : function(columnName, columnIndex, sortorder) {
// Set sort order and sort column in user variables so that
// periodical updates can maintain the same
var gridUserData = jQuery("#memberListRZ").getGridParam('userData');
gridUserData.sortColName = columnName;
gridUserData.sortOrder = sortorder;
},
onSelectRow : function(rowid, status, event) {
if (!event || event.which == 1) { // mouse left button click
var member = rowid.split("&");
location.href = 'memberDetails.html?member=' + member[0]
+ '&memberName=' + member[1];
}
},
resizeStop : function(width, index) {
var memberRegionsList = $('#gview_memberListRZ');
var memberRegionsListChild = memberRegionsList
.children('.ui-jqgrid-bdiv');
var api = memberRegionsListChild.data('jsp');
api.reinitialise();
memberRegionsList = $('#gview_memberListRZ');
memberRegionsListChild = memberRegionsList
.children('.ui-jqgrid-bdiv');
memberRegionsListChild.unbind('jsp-scroll-x');
memberRegionsListChild.bind('jsp-scroll-x', function(event,
scrollPositionX, isAtLeft, isAtRight) {
var mRList = $('#gview_memberListRZ');
var mRLC = mRList.children('.ui-jqgrid-hdiv').children(
'.ui-jqgrid-hbox');
mRLC.css("position", "relative");
mRLC.css('right', scrollPositionX);
});
$('#redundancyzones_grid_button').click();
refreshTheGrid($('#redundancyzones_grid_button'));
},
gridComplete : function() {
$(".jqgrow").css({
cursor : 'default'
});
var memberRegionsList = $('#gview_memberListRZ');
var memberRegionsListChild = memberRegionsList
.children('.ui-jqgrid-bdiv');
memberRegionsListChild.unbind('jsp-scroll-x');
memberRegionsListChild.bind('jsp-scroll-x', function(event,
scrollPositionX, isAtLeft, isAtRight) {
var mRList = $('#gview_memberListRZ');
var mRLC = mRList.children('.ui-jqgrid-hdiv').children(
'.ui-jqgrid-hbox');
mRLC.css("position", "relative");
mRLC.css('right', scrollPositionX);
});
}
});
}
function createRegionsGridDefault() {
jQuery("#regionsList").jqGrid(
{
datatype : "local",
height : 360,
width : 740,
rowNum : 200,
shrinkToFit : false,
colNames : [ 'Region Name', 'Type', 'Entry Count', 'Entry Size',
'Region Path', 'Member Count', 'Read Rates', 'Write Rates',
'Persistence', 'Entry Count', 'Empty Nodes', 'Data Usage',
'Total Data Usage', 'Memory Usage', 'Total Memory',
'Member Names', 'Writes', 'Reads','Off Heap Enabled',
'Compression Codec' ],
colModel : [ {
name : 'name',
index : 'name',
width : 120,
sortable : true,
sorttype : "string"
}, {
name : 'type',
index : 'type',
width : 130,
sortable : true,
sorttype : "string"
}, {
name : 'systemRegionEntryCount',
index : 'systemRegionEntryCount',
width : 100,
align : 'right',
sortable : true,
sorttype : "int"
}, {
name : 'entrySize',
index : 'entrySize',
width : 100,
align : 'right',
sortable : true,
sorttype : "int"
}, {
name : 'regionPath',
index : 'regionPath',
//hidden : true,
width : 130,
sortable : true,
sorttype : "string"
}, {
name : 'memberCount',
index : 'memberCount',
hidden : true
}, {
name : 'getsRate',
index : 'getsRate',
hidden : true
}, {
name : 'putsRate',
index : 'putsRate',
hidden : true
}, {
name : 'persistence',
index : 'persistence',
//hidden : true,
width : 100,
sortable : true,
sorttype : "string"
}, {
name : 'systemRegionEntryCount',
index : 'systemRegionEntryCount',
hidden : true
}, {
name : 'emptyNodes',
index : 'emptyNodes',
hidden : true
}, {
name : 'dataUsage',
index : 'dataUsage',
hidden : true
}, {
name : 'totalDataUsage',
index : 'totalDataUsage',
hidden : true
}, {
name : 'memoryUsage',
index : 'memoryUsage',
hidden : true
}, {
name : 'totalMemory',
index : 'totalMemory',
hidden : true
}, {
name : 'memberNames',
index : 'memberNames',
hidden : true
}, {
name : 'writes',
index : 'writes',
hidden : true
}, {
name : 'reads',
index : 'reads',
hidden : true
}, {
name : 'isEnableOffHeapMemory',
index : 'isEnableOffHeapMemory',
hidden : true,
width : 120,
sortable : true,
sorttype : "string"
}, {
name : 'compressionCodec',
index : 'compressionCodec',
hidden : true
}],
userData : {
"sortOrder" : "asc",
"sortColName" : "name"
},
onSortCol : function(columnName, columnIndex, sortorder) {
// Set sort order and sort column in user variables so that
// periodical updates can maintain the same
var gridUserData = jQuery("#regionsList").getGridParam('userData');
gridUserData.sortColName = columnName;
gridUserData.sortOrder = sortorder;
},
onSelectRow : function(rowid, status, event) {
if (!event || event.which == 1) { // mouse left button click
var region = rowid.split("&");
location.href = 'regionDetail.html?regionFullPath=' + region[0];
}
},
resizeStop : function(width, index) {
var clusterRegionsList = $('#gview_regionsList');
var clusterRegionsListChild = clusterRegionsList
.children('.ui-jqgrid-bdiv');
var api = clusterRegionsListChild.data('jsp');
api.reinitialise();
/*memberRegionsList = $('#gview_regionsList');
memberRegionsListChild = memberRegionsList
.children('.ui-jqgrid-bdiv');
memberRegionsListChild.unbind('jsp-scroll-x');
memberRegionsListChild.bind('jsp-scroll-x', function(event,
scrollPositionX, isAtLeft, isAtRight) {
var mRList = $('#gview_regionsList');
var mRLC = mRList.children('.ui-jqgrid-hdiv').children(
'.ui-jqgrid-hbox');
mRLC.css("position", "relative");
mRLC.css('right', scrollPositionX);
});*/
$('#data_grid_button').click();
refreshTheGrid($('#data_grid_button'));
},
gridComplete : function() {
$(".jqgrow").css({
cursor : 'default'
});
var memberRegionsList = $('#gview_regionsList');
var memberRegionsListChild = memberRegionsList
.children('.ui-jqgrid-bdiv');
memberRegionsListChild.unbind('jsp-scroll-x');
memberRegionsListChild.bind('jsp-scroll-x', function(event,
scrollPositionX, isAtLeft, isAtRight) {
var mRList = $('#gview_regionsList');
var mRLC = mRList.children('.ui-jqgrid-hdiv').children(
'.ui-jqgrid-hbox');
mRLC.css("position", "relative");
mRLC.css('right', scrollPositionX);
});
}
});
}
/* builds and returns json from given members details sent by server */
function buildDefaultMembersTreeMapData(members) {
var childerensVal = [];
for ( var i = 0; i < members.length; i++) {
var color = "#a0c44a";
// setting node color according to the status of member
// like if member has severe notification then the node color will be
// '#ebbf0f'
for ( var j = 0; j < warningAlerts.length; j++) {
if (members[i].name == warningAlerts[j].memberName) {
color = '#ebbf0f';
break;
}
}
// if member has severe notification then the node color will be
// '#de5a25'
for ( var j = 0; j < errorAlerts.length; j++) {
if (members[i].name == errorAlerts[j].memberName) {
color = '#de5a25';
break;
}
}
// if member has severe notification then the node color will be
// '#b82811'
for ( var j = 0; j < severAlerts.length; j++) {
if (members[i].name == severAlerts[j].memberName) {
color = '#b82811';
break;
}
}
var heapSize = members[i][currentHotspotAttribiute];
// if (heapSize == 0)
// heapSize = 1;
var name = "";
name = members[i].name;
var id = "";
id = members[i].memberId;
// passing all the required information of member to tooltip
var dataVal = {
"name" : name,
"id" : id,
"$color" : color,
"$area" : heapSize,
"cpuUsage" : members[i].cpuUsage,
"heapUsage" : members[i].currentHeapUsage,
"loadAvg" : members[i].loadAvg,
"threads" : members[i].threads,
"sockets" : members[i].sockets,
"gemfireVersion" : members[i].gemfireVersion,
"initial" : false
};
var childrenVal = {
"children" : [],
"data" : dataVal,
"id" : id,
"name" : name
};
childerensVal[i] = childrenVal;
}
var localjson = {
"children" : childerensVal,
"data" : {},
"id" : "root",
"name" : "Members"
};
return localjson;
}
/* builds treemap json for Server Groups */
function buildSGMembersTreeMapData(members) {
// Server Groups
var serverGroups = [];
var sgChildren = [];
for ( var i = 0; i < members.length; i++) {
// add Server Group if not present
var memServerGroups = members[i].serverGroups;
for ( var cntr = 0; cntr < memServerGroups.length; cntr++) {
if ($.inArray(memServerGroups[cntr], serverGroups) == -1) {
serverGroups.push(memServerGroups[cntr]);
var sgChild = {
"children" : [],
"data" : {
"$area" : 1,
"initial" : false
},
"id" : memServerGroups[cntr],
"name" : memServerGroups[cntr]
};
sgChildren.push(sgChild);
}
}
}
var localjson = {
"children" : sgChildren,
"data" : {},
"id" : "root",
"name" : "sgMembers"
};
for ( var i = 0; i < members.length; i++) {
var color = "#a0c44a";
// setting node color according to the status of member
// like if member has severe notification then the node color will be
// '#ebbf0f'
for ( var j = 0; j < warningAlerts.length; j++) {
if (members[i].name == warningAlerts[j].memberName) {
color = '#ebbf0f';
break;
}
}
// if member has severe notification then the node color will be
// '#de5a25'
for ( var j = 0; j < errorAlerts.length; j++) {
if (members[i].name == errorAlerts[j].memberName) {
color = '#de5a25';
break;
}
}
// if member has severe notification then the node color will be
// '#b82811'
for ( var j = 0; j < severAlerts.length; j++) {
if (members[i].name == severAlerts[j].memberName) {
color = '#b82811';
break;
}
}
var heapSize = members[i][currentHotspotAttribiute];
// if (heapSize == 0)
// heapSize = 1;
var name = "";
name = members[i].name;
var id = "";
id = members[i].memberId;
// passing all the required information of member to tooltip
var dataVal = {
"name" : name,
"id" : id,
"$color" : color,
"$area" : heapSize,
"cpuUsage" : members[i].cpuUsage,
"heapUsage" : members[i].currentHeapUsage,
"loadAvg" : members[i].loadAvg,
"threads" : members[i].threads,
"sockets" : members[i].sockets,
"gemfireVersion" : members[i].gemfireVersion,
"initial" : false
};
var childrenVal = {
"children" : [],
"data" : dataVal,
"id" : id,
"name" : name
};
var memServerGroups = members[i].serverGroups;
for(var k=0; k<memServerGroups.length; k++){
var localJsonChildren = localjson.children;
for(var l=0; l<localJsonChildren.length; l++){
if(localJsonChildren[l].name == memServerGroups[k]){
// create copy of member treemap child for the current server group
var copyOFChildren = jQuery.extend(true, {}, childrenVal);
copyOFChildren.id = memServerGroups[k]+"(!)"+childrenVal.id;
// Add member child in server group treemap object
localJsonChildren[l].children.push(copyOFChildren);
}
}
}
}
return localjson;
}
/* builds treemap json for Redundancy Zones */
function buildRZMembersTreeMapData(members) {
// Redundancy Zones
var redundancyZones = [];
var rzChildren = [];
for ( var i = 0; i < members.length; i++) {
// add redundancy zones if not present
var memRedundancyZones = members[i].redundancyZones;
for ( var cntr = 0; cntr < memRedundancyZones.length; cntr++) {
if ($.inArray(memRedundancyZones[cntr], redundancyZones) == -1) {
redundancyZones.push(memRedundancyZones[cntr]);
var rzChild = {
"children" : [],
"data" : {
"$area" : 1,
"initial" : false
},
"id" : memRedundancyZones[cntr],
"name" : memRedundancyZones[cntr]
};
rzChildren.push(rzChild);
}
}
}
var localjson = {
"children" : rzChildren,
"data" : {},
"id" : "root",
"name" : "rzMembers"
};
for ( var i = 0; i < members.length; i++) {
var color = "#a0c44a";
// setting node color according to the status of member
// like if member has severe notification then the node color will be
// '#ebbf0f'
for ( var j = 0; j < warningAlerts.length; j++) {
if (members[i].name == warningAlerts[j].memberName) {
color = '#ebbf0f';
break;
}
}
// if member has severe notification then the node color will be
// '#de5a25'
for ( var j = 0; j < errorAlerts.length; j++) {
if (members[i].name == errorAlerts[j].memberName) {
color = '#de5a25';
break;
}
}
// if member has severe notification then the node color will be
// '#b82811'
for ( var j = 0; j < severAlerts.length; j++) {
if (members[i].name == severAlerts[j].memberName) {
color = '#b82811';
break;
}
}
var heapSize = members[i][currentHotspotAttribiute];
// if (heapSize == 0)
// heapSize = 1;
var name = "";
name = members[i].name;
var id = "";
id = members[i].memberId;
// passing all the required information of member to tooltip
var dataVal = {
"name" : name,
"id" : id,
"$color" : color,
"$area" : heapSize,
"cpuUsage" : members[i].cpuUsage,
"heapUsage" : members[i].currentHeapUsage,
"loadAvg" : members[i].loadAvg,
"threads" : members[i].threads,
"sockets" : members[i].sockets,
"gemfireVersion" : members[i].gemfireVersion,
"initial" : false
};
var childrenVal = {
"children" : [],
"data" : dataVal,
"id" : id,
"name" : name
};
var memRedundancyZones = members[i].redundancyZones;
for(var k=0; k<memRedundancyZones.length; k++){
var localJsonChildren = localjson.children;
for(var l=0; l<localJsonChildren.length; l++){
if(localJsonChildren[l].name == memRedundancyZones[k]){
// create copy of member treemap child for the current redundancy zone
var copyOFChildren = jQuery.extend(true, {}, childrenVal);
copyOFChildren.id = memRedundancyZones[k]+"(!)"+childrenVal.id;
// Add member child in reduadancy zone treemap object
localJsonChildren[l].children.push(copyOFChildren);
}
}
}
}
return localjson;
}
/* builds treemap json for Cluster Regions */
function buildRegionsTreeMapData(clusterRegions) {
// variable to store value of total of entry counts of all regions
var totalOfEntryCounts = 0;
// flag to determine if all regions are having entry count = 0
var flagSetEntryCountsToZero = false;
// Calculate the total of all regions entry counts
for ( var i = 0; i < clusterRegions.length; i++) {
totalOfEntryCounts += clusterRegions[i].entryCount;
}
// If totalOfEntryCounts is zero and at least one region is present
// then set flagSetEntryCountsToZero to avoid displaying circles
// in treemap as all valid regions are zero area regions and also display
// all regions with evenly placement of blocks
if (totalOfEntryCounts == 0 && clusterRegions.length > 0) {
flagSetEntryCountsToZero = true;
}
var childerensVal = [];
for ( var i = 0; i < clusterRegions.length; i++) {
var entryCount = clusterRegions[i].systemRegionEntryCount;
// If flagSetEntryCountsToZero is true then set entry count to
// display all
// regions with evenly placement of blocks
if (flagSetEntryCountsToZero && entryCount == 0) {
entryCount = 1;
}
var color = colorCodeForRegions;
if(clusterRegions[i].systemRegionEntryCount == 0){
color = colorCodeForZeroEntryCountRegions;
}
var wanEnabled = clusterRegions[i].wanEnabled;
var wanEnabledtxt = "";
if (wanEnabled == true)
wanEnabledtxt = "WAN Enabled";
// if (entryCount == 0)
// entryCount = 1;
var dataVal = {
"name" : clusterRegions[i].name,
"id" : clusterRegions[i].regionPath,
"$color" : color,
"$area" : entryCount,
"systemRegionEntryCount" : clusterRegions[i].systemRegionEntryCount,
"type" : clusterRegions[i].type,
"regionPath" : clusterRegions[i].regionPath,
"entrySize" : clusterRegions[i].entrySize,
"memberCount" : clusterRegions[i].memberCount,
"writes" : clusterRegions[i].putsRate,
"reads" : clusterRegions[i].getsRate,
"emptyNodes" : clusterRegions[i].emptyNodes,
"persistence" : clusterRegions[i].persistence,
"isEnableOffHeapMemory" : clusterRegions[i].isEnableOffHeapMemory,
"compressionCodec" : clusterRegions[i].compressionCodec,
"memberNames" : clusterRegions[i].memberNames,
"memoryWritesTrend" : clusterRegions[i].memoryWritesTrend,
"memoryReadsTrend" : clusterRegions[i].memoryReadsTrend,
"diskWritesTrend" : clusterRegions[i].diskWritesTrend,
"diskReadsTrend" : clusterRegions[i].diskReadsTrend,
"memoryUsage" : clusterRegions[i].memoryUsage,
"dataUsage" : clusterRegions[i].dataUsage,
"totalDataUsage" : clusterRegions[i].totalDataUsage,
"totalMemory" : clusterRegions[i].totalMemory
};
var childrenVal = {
"children" : [],
"data" : dataVal,
"id" : clusterRegions[i].regionPath,
"name" : wanEnabledtxt
};
childerensVal[i] = childrenVal;
}
var json = {
"children" : childerensVal,
"data" : {},
"id" : "root",
"name" : "Regions"
};
return json;
}
/* builds grid data for Server Groups */
function buildSGMembersGridData(members) {
var sgMembersGridData = [];
// Server Groups
var serverGroups = [];
for ( var i = 0; i < members.length; i++) {
// add Server Group if not present
var memServerGroups = members[i].serverGroups;
for ( var cntr = 0; cntr < memServerGroups.length; cntr++) {
if ($.inArray(memServerGroups[cntr], serverGroups) == -1) {
serverGroups.push(memServerGroups[cntr]);
}
}
}
for(var i=0; i<serverGroups.length; i++){
var serverGroup = serverGroups[i];
for(var j=0; j<members.length; j++){
if ($.inArray(serverGroup, members[j].serverGroups) > -1) {
var memberObjectNew = jQuery.extend({}, members[j]);
memberObjectNew.serverGroup = serverGroup;
sgMembersGridData.push(memberObjectNew);
}
}
}
return sgMembersGridData;
}
/* builds grid data for Redundancy Zones */
function buildRZMembersGridData(members) {
var rzMembersGridData = [];
// Server Groups
var redundancyZones = [];
for ( var i = 0; i < members.length; i++) {
// add Redundancy Zones if not present
var memRedundancyZones = members[i].redundancyZones;
for ( var cntr = 0; cntr < memRedundancyZones.length; cntr++) {
if ($.inArray(memRedundancyZones[cntr], redundancyZones) == -1) {
redundancyZones.push(memRedundancyZones[cntr]);
}
}
}
for(var i=0; i<redundancyZones.length; i++){
var redundancyZone = redundancyZones[i];
for(var j=0; j<members.length; j++){
if ($.inArray(redundancyZone, members[j].redundancyZones) > -1) {
var memberObjectNew = jQuery.extend({}, members[j]);
memberObjectNew.redundancyZone = redundancyZone;
rzMembersGridData.push(memberObjectNew);
}
}
}
return rzMembersGridData;
}
// Tool tip for members in grid
function formMemberGridToolTip(detail, rawObject) {
return 'title="'+detail+ ', CPU Usage: '
+ rawObject.cpuUsage + '% , Heap Usage: '
+ rawObject.currentHeapUsage + 'MB , Load Avg.: '
+ rawObject.loadAvg + ' , Threads: ' + rawObject.threads
+ ' , Sockets: ' + rawObject.sockets + '"';
}
function refreshTheGrid(gridDiv) {
setTimeout(function(){gridDiv.click();}, 300);
}
/*
* Show/Hide panels in Widget for Cluster Member's and Data
* Function to be called on click of visualization tab icons
*/
// function openTabViewPanel(dataPerspective, viewOption, viewType)
function openTabViewPanel(thisitem){
//alert(thisitem.id+" : "+thisitem.dataset.perspective +" | "+thisitem.dataset.view+" | "+thisitem.dataset.viewoption);
var viewPanelBlock = thisitem.dataset.view+"_"+thisitem.dataset.viewoption+"_block";
$('#'+viewPanelBlock).siblings().hide();
$('#'+viewPanelBlock).show();
$(thisitem).siblings().removeClass('active');
$(thisitem).addClass('active');
}
//Start: Widget for Cluster Members and Data
//Show Members Default/Topology R-Graph View and hide rest
function showMembersDefaultRgraphPanel() {
flagActiveTab = "MEM_R_GRAPH_DEF";
updateRGraphFlags();
// populateMemberRGraph using pulseUpdate
var pulseData = {};
pulseData.ClusterMembersRGraph = "";
ajaxPost("pulseUpdate", pulseData, translateGetClusterMemberRGraphBack);
}
//Show Members Default/Topology Treemap View and hide rest
function showMembersDefaultTreemapPanel() {
flagActiveTab = "MEM_TREE_MAP_DEF";
// populate Member TreeMap using pulseUpdate
var pulseData = {};
pulseData.ClusterMembers = "";
ajaxPost("pulseUpdate", pulseData, translateGetClusterMemberBack);
}
//Show Members Default/Topology Grid View and hide rest
function showMembersDefaultGridPanel() {
flagActiveTab = "MEM_GRID_DEF";
// populate Member Grid using pulseUpdate
var pulseData = {};
pulseData.ClusterMembers = ""; // getClusterMembersBack
ajaxPost("pulseUpdate", pulseData, translateGetClusterMemberBack);
$('#default_grid_block').hide();
destroyScrollPane('gview_memberList');
$('#default_grid_block').show();
/* Custom scroll */
$('.ui-jqgrid-bdiv').each(function(index) {
var tempName = $(this).parent().attr('id');
if (tempName == 'gview_memberList') {
$(this).jScrollPane({maintainPosition : true, stickToRight : true});
}
});
}
//Show Members Server Groups Treemap View and hide rest
function showMembersSGTreemapPanel() {
flagActiveTab = "MEM_TREE_MAP_SG";
// populate Member TreeMap using pulseUpdate
var pulseData = {};
pulseData.ClusterMembers = "";
ajaxPost("pulseUpdate", pulseData, translateGetClusterMemberBack);
}
//Show Members Server Groups Grid View and hide rest
function showMembersSGGridPanel() {
flagActiveTab = "MEM_GRID_SG";
// populate Member Grid using pulseUpdate
var pulseData = {};
pulseData.ClusterMembers = ""; // getClusterMembersBack
ajaxPost("pulseUpdate", pulseData, translateGetClusterMemberBack);
$('#servergroups_grid_block').hide();
destroyScrollPane('gview_memberListSG');
$('#servergroups_grid_block').show();
/* Custom scroll */
$('.ui-jqgrid-bdiv').each(function(index) {
var tempName = $(this).parent().attr('id');
if (tempName == 'gview_memberListSG') {
$(this).jScrollPane({maintainPosition : true, stickToRight : true});
}
});
}
//Show Members Redundancy Zones Treemap View and hide rest
function showMembersRZTreemapPanel() {
flagActiveTab = "MEM_TREE_MAP_RZ";
// populate Member TreeMap using pulseUpdate
var pulseData = {};
pulseData.ClusterMembers = "";
ajaxPost("pulseUpdate", pulseData, translateGetClusterMemberBack);
}
//Show Members Redundancy Zones Grid View and hide rest
function showMembersRZGridPanel() {
flagActiveTab = "MEM_GRID_RZ";
// populate Member Grid using pulseUpdate
var pulseData = {};
pulseData.ClusterMembers = "";
ajaxPost("pulseUpdate", pulseData, translateGetClusterMemberBack);
$('#redundancyzones_grid_block').hide();
destroyScrollPane('gview_memberListRZ');
$('#redundancyzones_grid_block').show();
/* Custom scroll */
$('.ui-jqgrid-bdiv').each(function(index) {
var tempName = $(this).parent().attr('id');
if (tempName == 'gview_memberListRZ') {
$(this).jScrollPane({maintainPosition : true, stickToRight : true});
}
});
}
//Show Data Treemap View and hide rest
function showDataTreemapPanel() {
flagActiveTab = "DATA_TREE_MAP_DEF";
// populate Region TreeMap using pulseUpdate
var pulseData = {};
pulseData.ClusterRegions = "";
ajaxPost("pulseUpdate", pulseData, translateGetClusterRegionsBack);
}
//Show Data Grid View and hide rest
function showDataGridPanel() {
flagActiveTab = "DATA_GRID_DEF";
// populate Regions Grid using pulseUpdate
var pulseData = {};
pulseData.ClusterRegions = "";
ajaxPost("pulseUpdate", pulseData, translateGetClusterRegionsBack);
$('#data_grid_block').hide();
destroyScrollPane('gview_regionsList');
$('#data_grid_block').show();
/* Custom scroll */
$('.ui-jqgrid-bdiv').each(function(index) {
var tempName = $(this).parent().attr('id');
if (tempName == 'gview_regionsList') {
$(this).jScrollPane({maintainPosition : true, stickToRight : true});
}
});
}
// Function to be called on click of visualization tab icons
function openViewPanel(dataPerspective, dataView, dataViewOption){
// Display Loading/Busy symbol
$("#loadingSymbol").show();
selectedPerspectiveView = dataPerspective;
var viewPanelBlock = dataView+"_"+dataViewOption+"_block";
var viewPanelButton = dataView+"_"+dataViewOption+"_button";
// Display tab panel
$('#'+viewPanelBlock).siblings().hide();
$('#'+viewPanelBlock).show();
// activate tab button
var thisitem = $('#'+viewPanelButton);
$(thisitem).siblings().removeClass('active');
$(thisitem).addClass('active');
if('member' == dataPerspective){
selectedMemberViewOption = dataView;
if('servergroups' == dataView){ // Server Groups view
selectedViewTypeSG = dataViewOption;
if('treemap' == dataViewOption){ // Treemap
showMembersSGTreemapPanel();
}else { // Grid
showMembersSGGridPanel();
}
}else if('redundancyzones' == dataView){ // Redundancy Zones view
selectedViewTypeRZ = dataViewOption;
if('treemap' == dataViewOption){ // Treemap
showMembersRZTreemapPanel();
}else { // Grid
showMembersRZGridPanel();
}
}else { // default view
selectedViewTypeDefault = dataViewOption;
if('treemap' == dataViewOption){ // Treemap
showMembersDefaultTreemapPanel();
}else if('grid' == dataViewOption){ // Grid
showMembersDefaultGridPanel();
}else{ // R-Graph
showMembersDefaultRgraphPanel();
}
}
// Show/hide hotspot dropdown
if('treemap' == dataViewOption){
$("#hotspotParentContainer").show();
}else{
$("#hotspotParentContainer").hide();
}
}else{ // 'data' == dataPerspective
selectedViewTypeData = dataViewOption;
if('treemap' == dataViewOption){ // Treemap
showDataTreemapPanel();
}else if('grid' == dataViewOption){ // Grid
showDataGridPanel();
}
}
// Hide Loading/Busy symbol
$("#loadingSymbol").hide();
}
//Function to be called on click of cluster perspective drop down list
function onChangeClusterPerspective(n) {
for(var i=1;i<=$(".members_data ul li").length;i++){
$("#members_data"+i).removeClass("selected");
}
$("#members_data"+n).addClass("selected");
if (n == 1) { // Members Perspective
$("#member_view_options").show();
$("#icons_data_view").hide();
$("#icons_member_view_option_default").hide();
$("#icons_member_view_option_servergroups").hide();
$("#icons_member_view_option_redundancyzones").hide();
// Check last selected member view option
for ( var i = 0; i < $("#member_view_options ul li").length; i++) {
var idname = $('#member_view_options ul li').get(i).id;
if ($("#" + idname).children("label").hasClass("r_on")) {
var iconsbox = "icons_"+idname;
$("#" + iconsbox).show();
}
}
selectedPerspectiveView = "member";
} else if (n == 2) { // Data Perspective
$("#hotspotParentContainer").hide();
$("#member_view_options").hide();
$("#icons_data_view").show();
$("#icons_member_view_option_default").hide();
$("#icons_member_view_option_servergroups").hide();
$("#icons_member_view_option_redundancyzones").hide();
selectedPerspectiveView = "data";
}
// display visualization
if("member" == selectedPerspectiveView){
// Member perspective
if("default" == selectedMemberViewOption){
if("rgraph" == selectedViewTypeDefault){
openViewPanel('member', 'default','rgraph');
}else if("treemap" == selectedViewTypeDefault){
openViewPanel('member', 'default','treemap');
}else{
openViewPanel('member', 'default','grid');
}
}else if("servergroups" == selectedMemberViewOption){
if("treemap" == selectedViewTypeSG){
openViewPanel('member', 'servergroups','treemap');
}else{
openViewPanel('member', 'servergroups','grid');
}
}else{ // redundancyzones
if("treemap" == selectedViewTypeRZ){
openViewPanel('member', 'redundancyzones','treemap');
}else{
openViewPanel('member', 'redundancyzones','grid');
}
}
}else{
// Data perspective
if("treemap" == selectedViewTypeData){
openViewPanel('data', 'data', 'treemap');
}else{
openViewPanel('data', 'data', 'grid');
}
}
}
function displayClusterPerspective(perspView){
}
$(document).ready(function(e) {
// Attach click event on outside of the drop down list control.
addEventsForMembersOptions();
});
/*
Function to attach click event on outside of the drop down list control.
*/
function addEventsForMembersOptions() {
// Attach click event for radio butons on Memebrs perspective view
$(".label_radio input").unbind("click").click(memberOptionSelectionHandler);
}
// handler to be called on selection of radio options of Member Views
var memberOptionSelectionHandler = function(){
$(".label_radio").removeClass("r_on");
if ($(this).is(":checked")) {
$(this).parent('label').addClass("r_on");
} else {
$(this).parent('label').removeClass("r_on");
}
var viewOptionId;
if('radio-servergroups' == this.id){
viewOptionId = 'member_view_option_servergroups';
selectedMemberViewOption = "servergroups";
if("treemap" == selectedViewTypeSG){
openViewPanel('member', 'servergroups','treemap');
}else{
openViewPanel('member', 'servergroups','grid');
}
}else if('radio-redundancyzones' == this.id){
viewOptionId = 'member_view_option_redundancyzones';
selectedMemberViewOption = "redundancyzones";
if("treemap" == selectedViewTypeRZ){
openViewPanel('member', 'redundancyzones','treemap');
}else{
openViewPanel('member', 'redundancyzones','grid');
}
}else{//radio-default
viewOptionId = 'member_view_option_default';
selectedMemberViewOption = "default";
if("rgraph" == selectedViewTypeDefault){
openViewPanel('member', 'default','rgraph');
}else if("treemap" == selectedViewTypeDefault){
openViewPanel('member', 'default','treemap');
}else{
openViewPanel('member', 'default','grid');
}
}
// set radio selection
$('#'+viewOptionId).siblings().removeClass('selected');
$('#'+viewOptionId).addClass("selected");
//selectedsubview = id;
// Show/Hide Tab buttons
$('#'+'icons_'+viewOptionId).show();
$('#'+'icons_'+viewOptionId).siblings().hide();
};
var selectedsubview;
var viewtypegridtreemap;
/************ on Click Out Side **************************/
(function(jQuery) {
jQuery.fn.clickoutside = function(callback) {
var outside = 1, self = $(this);
self.cb = callback;
this.click(function() {
outside = 0;
});
$(document).click(function() {
outside && self.cb();
outside = 1;
});
return $(this);
};
})(jQuery);
// End: Widget for Cluster Members and Data
|
import {ACTIONS} from "../common/constants";
const initialState = {
employee: {}
};
const employeeReducer = (state = initialState, action) => {
switch (action.type) {
case ACTIONS.ADD_EMPLOYEE: {
const newState = {...state, employee: action.payload};
return newState; }
default:
return state;
}
};
export default employeeReducer;
|
import Home from './screens/Home';
import Account from './screens/Account';
import AccountDelete from './screens/AccountDelete';
import AccountDeleted from './screens/AccountDeleted';
import Questionnaire from './screens/Questionnaire';
import ResultSC from './screens/ResultSC';
import FHEKeyGen from './screens/FHEKeyGen';
/* =============================================================================
Screen Names:
============================================================================= */
const SCREEN_NAMES = {
HOME: "HOME",
ACCOUNT: "ACCOUNT",
ACCOUNT_DELETE: "ACCOUNT_DELETE",
ACCOUNT_DELETED: "ACCOUNT_DELETED",
QUESTIONNAIRE: "QUESTIONNAIRE",
RESULT_SC: "RESULT_SC",
FHE_GEN: "FHE_GEN"
};
/* =============================================================================
React Navigation Route Config
============================================================================= */
const AppRouteConfig = {
[SCREEN_NAMES.ACCOUNT]: {
screen: Account,
navigationOptions: {}
},
[SCREEN_NAMES.ACCOUNT_DELETE]: {
screen: AccountDelete,
navigationOptions: {}
},
[SCREEN_NAMES.ACCOUNT_DELETED]: {
screen: AccountDeleted,
navigationOptions: {}
},
[SCREEN_NAMES.FHE_GEN]: {
screen: FHEKeyGen,
navigationOptions: {}
},
[SCREEN_NAMES.QUESTIONNAIRE]: {
screen: Questionnaire,
navigationOptions: {}
},
[SCREEN_NAMES.RESULT_SC]: {
screen: ResultSC,
navigationOptions: {}
},
};
/* =============================================================================
Export
============================================================================= */
export { SCREEN_NAMES };
export default AppRouteConfig;
|
import { Container, Button } from './styles';
export default function LoadPage({ children, ...props }) {
return <Container {...props}>{children}</Container>;
}
LoadPage.Button = function LoadPageButton({ children, ...props }) {
return <Button {...props}>{children}</Button>;
};
|
import React from 'react';
// Classes:
// .form-check
// .form-check-input
// .form-check-label
const Checkbox = () =>
<div className="form-check">
<input className="form-check-input" type="checkbox" value="Checkbox option" id="defaultCheck" />
<label className="form-check-label" htmlFor="defaultCheck">Checkbox option</label>
</div>
export default Checkbox;
|
const Discord = require("discord.js");
module.exports = {
name: 'rules',
description: "Rules Of Server!",
execute(message, args, client) {
let embed = new Discord.MessageEmbed()
.setColor("RANDOM")
.setTitle("Rules")
.setImage(message.guild.iconURL)
.setDescription(`${message.guild}'s information`)
.addField('1. Follow Discord TOS', 'Follow The TOS')
.addField("2. No Spamming", 'Please Dont Spam')
.addField("3. No pinging Admin or higher role more than once", 'Please Follow')
.addField("4. No Advertising in channels other than 🎈advertising", 'Follow To U Get Warned')
.addField("5. Don't use all CAPS", 'No One Wants You To Use CAPS')
.addField("6. No NSFW Content", "Do This And You Get BANNED")
message.channel.send(embed)
}
}
|
const express = require('express');
const path = require('path');
const request = require('request');
const app = express();
app.use('/', express.static(path.join('app')));
app.get('/api/get-data', (req, res) => {
request('http://sherwin.retailscience.ca:5000/', (err, response, body) => {
try {
res.json({
recordset: JSON.parse(body).recordset
});
} catch (e) {
console.error(e);
res.status(409).json({ msg: 'Cannot get data' });
}
});
});
app.listen(4001, () => {
console.log('server is started at port 4001');
});
|
var source = Rx.Observable.interval(500);
var subject = new Rx.Subject();
// RECORDAR QUE "source.multicast(subject)" DEVUELVE UN "ConnectableObservable"
//retorna un Observable, no otro ConnectableObservable.
//retorna un Observable que registra cuántos suscriptores tiene.
var refCounted = source.multicast(subject).refCount();
var subscription1, subscription2, subscriptionConnect;
//nOTA: "refCount" Hace que el Multicasted Observable comience(start) automáticamente a ejecutarse cuando llegue el primer subscribe
// y para(STOP) la ejecución cuando el último subscribe se vaya.
console.log('ObserverA subscribed');
subscription1 = refCounted.subscribe({
next: (v) => console.log('ObserverA: ' + v)
});
setTimeout(()=>{
console.log('ObserverB subscribe');
subscription2 = refCounted.subscribe({
next: (v) => console.log('ObserverB: '+ v)
})
}, 600);
setTimeout(()=>{
console.log('Observer a unsubscribed');
subscription1.unsubscribe();
}, 1200);
setTimeout(()=>{
console.log('observerB unsubscribed');
subscription2.unsubscribe();
},2000);
|
module.exports = require('request').defaults({rejectUnauthorized: false});
|
'use strict'
const jwt = requireRoot('services/auth/jwt')
const User = requireRoot('./appManager').models.User
const exception = requireRoot('services/customExceptions')
module.exports = {
async login (email, username, password, device) {
validateLogin(email, username, password)
let query
if (email) { query = { where: { email } } } else if (username) { query = { where: { username } } }
let user = await User.findOne(query)
if (!user || !await user.comparePassword(password)) {
throw new exception.ValidationLogin({
error: 'Your login details could not be verified. Please try again.'
})
}
// generate Token
const token = jwt.generateAccessToken(user, device)
user.addToken(token, device)
return {
token: token,
user: user.getPublicInfo()
}
},
async register (email, password, username, device) {
validateRegistration(email, password, username)
// check if email exists
let existingUser = await User.findOne({
where: { email }
})
if (existingUser) {
throw new exception.ValidationRegistration({
error: 'That email address is already in use.'
})
}
// check if username exists
existingUser = await User.findOne({
where: { username }
})
if (existingUser) {
throw new exception.ValidationRegistration({
error: 'That username is already in use.'
})
}
// valid user
let user = new User({
email,
password,
username
})
user = await user.save()
const token = jwt.generateAccessToken(user, device)
user.addToken(token, device)
return {
token: token,
user: user.getPublicInfo()
}
},
async changePassword (email, password, newPassword, device) {
validateChangePassword(email, password, newPassword)
let user = await User.findOne({
where: { email }
})
if (!user || !await user.comparePassword(password)) {
throw new exception.ValidationChangePassword({
error: 'Your login details could not be verified. Please try again.'
})
}
// set new password
user.setPassword(newPassword)
await user.save()
// remove all user tokens
user.removeAllTokens()
// generate a new token
let token = jwt.generateAccessToken(user, device)
user.addToken(token, device)
return {
token: token,
user: user.getPublicInfo()
}
}
}
function validateRegistration (email, password, username) {
if (!email || !password || !username) {
throw new exception.ValidationRegistration({
error: 'You must set email, password and username.'
})
}
validateEmail(email)
validateUsername(username)
validatePassword(password)
}
function validateLogin (email, username, password) {
if ((!email && !username) || !password) {
throw new exception.ValidationLogin({
error: 'Your login details could not be verified. Please try again.'
})
}
if (email) { validateEmail(email) } else if (username) { validateUsername(username) }
validatePassword(password)
}
function validateChangePassword (email, password, newPassword) {
if (!email || !password || !newPassword) {
throw new exception.ValidationChangePassword({
error: 'Your login details could not be verified. Please try again.'
})
}
validateEmail(email)
validatePassword(password)
validatePassword(newPassword)
}
function validateEmail (email) {
if (!(/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(.\w{2,3})+$/.test(email))) { throw new exception.ValidationEmail() }
}
function validateUsername (username) {
if (username.length < 4) {
throw new exception.ValidationUsername({
error: 'You must set 3 or more characters for username.'
})
}
if (!(/^([a-zA-Z0-9_.-]+)$/.test(username))) {
throw new exception.ValidationUsername({
error: "The username must have numbers, letters, '-', '.' and '_'"
})
}
}
function validatePassword (password) {
if (password.length < 8) {
throw new exception.ValidationPassword({
error: 'You must set 8 or more characters for password.'
})
}
}
|
import {createAsyncThunk, createSlice} from '@reduxjs/toolkit'
import { db} from '../../firebase/config';
const dt = new Date()
export const addmember = createAsyncThunk(
"storage/addmember",
async ({formdata,url})=>{
const imageurl = await url
await db.collection('members').add({
addedDate:`${dt.getDate()}-${dt.getMonth()}-${dt.getFullYear()} ${dt.getHours()}:${dt.getMinutes()}`,
memberid:formdata.memberid,
name:formdata.name,
parents:formdata.parents,
age:formdata.age,
gender:formdata.gender,
post:formdata.post,
village:formdata.village,
district:formdata.district,
pincode:formdata.pincode,
state:formdata.state,
imageurl
}).catch(err=>{
console.log(err)
})
return;
}
)
const storageSlice = createSlice({
name:'storage',
initialState:{
loading:false,
member:[]
},
reducers:{
addnews:(state,action)=>{
},
},
extraReducers:{
[addmember.pending]:(state)=>{
state.loading=true
},
[addmember.fulfilled]:(state)=>{
state.loading =false
},
[addmember.rejected]:(state,action)=>{
state.loading=false
}
}
})
export default storageSlice.reducer;
export const {addnews} =storageSlice.actions
|
var changecontent_ajax_msg='<em>Loading Ajax content...</em>'
var changecontent_ajax_bustcache=true
function changecontent(className, filtertag){
this.className=className
this.collapsePrev=false
this.persistType="none"
this.filter_content_tag=(typeof filtertag!="undefined")? filtertag.toLowerCase() : ""
this.ajaxheaders={}
}
changecontent.prototype.setStatus=function(openHTML, closeHTML){
this.statusOpen=openHTML
this.statusClosed=closeHTML
}
changecontent.prototype.setColor=function(openColor, closeColor){
this.colorOpen=openColor
this.colorClosed=closeColor
}
changecontent.prototype.setPersist=function(bool, days){
if (bool==true){
if (typeof days=="undefined")
this.persistType="session"
else{
this.persistType="days"
this.persistDays=parseInt(days)
}
}
else
this.persistType="none"
}
changecontent.prototype.collapsePrevious=function(bool){
this.collapsePrev=bool
}
changecontent.prototype.setContent=function(index, filepath){
this.ajaxheaders["header"+index]=filepath
}
changecontent.prototype.sweepToggle=function(setting){
if (typeof this.headers!="undefined" && this.headers.length>0){
for (var i=0; i<this.headers.length; i++){
if (setting=="expand")
this.expandcontent(this.headers[i])
else if (setting=="contract")
this.contractcontent(this.headers[i])
}
}
}
changecontent.prototype.defaultExpanded=function(){
var expandedindices=[]
for (var i=0; (!this.collapsePrev && i<arguments.length) || (this.collapsePrev && i==0); i++)
expandedindices[expandedindices.length]=arguments[i]
this.expandedindices=expandedindices.join(",")
}
changecontent.prototype.togglecolor=function(header, status){
if (typeof this.colorOpen!="undefined")
header.style.color=status
}
changecontent.prototype.togglestatus=function(header, status){
if (typeof this.statusOpen!="undefined")
header.firstChild.innerHTML=status
}
changecontent.prototype.contractcontent=function(header){
var innercontent=document.getElementById(header.id.replace("-title", ""))
innercontent.style.display="none"
this.togglestatus(header, this.statusClosed)
this.togglecolor(header, this.colorClosed)
}
changecontent.prototype.expandcontent=function(header){
var innercontent=document.getElementById(header.id.replace("-title", ""))
if (header.ajaxstatus=="waiting"){
changecontent.connect(header.ajaxfile, header)
}
innercontent.style.display="block"
this.togglestatus(header, this.statusOpen)
this.togglecolor(header, this.colorOpen)
}
changecontent.prototype.toggledisplay=function(header){
var innercontent=document.getElementById(header.id.replace("-title", ""))
if (innercontent.style.display=="block")
this.contractcontent(header)
else{
this.expandcontent(header)
if (this.collapsePrev && typeof this.prevHeader!="undefined" && this.prevHeader.id!=header.id)
this.contractcontent(this.prevHeader)
}
if (this.collapsePrev)
this.prevHeader=header
}
changecontent.prototype.collectElementbyClass=function(classname){
var classnameRE=new RegExp("(^|\\s+)"+classname+"($|\\s+)", "i")
this.headers=[], this.innercontents=[]
if (this.filter_content_tag!="")
var allelements=document.getElementsByTagName(this.filter_content_tag)
else
var allelements=document.all? document.all : document.getElementsByTagName("*")
for (var i=0; i<allelements.length; i++){
if (typeof allelements[i].className=="string" && allelements[i].className.search(classnameRE)!=-1){
if (document.getElementById(allelements[i].id+"-title")!=null){
this.headers[this.headers.length]=document.getElementById(allelements[i].id+"-title")
this.innercontents[this.innercontents.length]=allelements[i]
}
}
}
}
changecontent.prototype.init=function(){
var instanceOf=this
this.collectElementbyClass(this.className)
if (this.headers.length==0)
return
if (this.persistType=="days" && (parseInt(changecontent.getCookie(this.className+"_dtrack"))!=this.persistDays))
changecontent.setCookie(this.className+"_d", "", -1)
var opencontents_ids=(this.persistType=="session" && changecontent.getCookie(this.className)!="")? ','+changecontent.getCookie(this.className)+',' : (this.persistType=="days" && changecontent.getCookie(this.className+"_d")!="")? ','+changecontent.getCookie(this.className+"_d")+',' : (this.expandedindices)? ','+this.expandedindices+',' : ""
for (var i=0; i<this.headers.length; i++){
if (typeof this.ajaxheaders["header"+i]!="undefined"){
this.headers[i].ajaxstatus='waiting'
this.headers[i].ajaxfile=this.ajaxheaders["header"+i]
}
if (typeof this.statusOpen!="undefined")
this.headers[i].innerHTML='<span class="status"></span>'+this.headers[i].innerHTML
if (opencontents_ids.indexOf(','+i+',')!=-1){
this.expandcontent(this.headers[i])
if (this.collapsePrev)
this.prevHeader=this.headers[i]
}
else
this.contractcontent(this.headers[i])
this.headers[i].onclick=function(){instanceOf.toggledisplay(this)}
}
changecontent.dotask(window, function(){instanceOf.rememberpluscleanup()}, "unload")
}
changecontent.prototype.rememberpluscleanup=function(){
var opencontents=new Array("none")
for (var i=0; i<this.innercontents.length; i++){
if (this.persistType!="none" && this.innercontents[i].style.display=="block" && (!this.collapsePrev || (this.collapsePrev && opencontents.length<2)))
opencontents[opencontents.length]=i
this.headers[i].onclick=null
}
if (opencontents.length>1)
opencontents.shift()
if (typeof this.statusOpen!="undefined")
this.statusOpen=this.statusClosed=null
if (this.persistType=="session")
changecontent.setCookie(this.className, opencontents.join(","))
else if (this.persistType=="days" && typeof this.persistDays=="number"){
changecontent.setCookie(this.className+"_d", opencontents.join(","), this.persistDays)
changecontent.setCookie(this.className+"_dtrack", this.persistDays, this.persistDays)
}
}
changecontent.dotask=function(target, functionref, tasktype){
var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
if (target.addEventListener)
target.addEventListener(tasktype, functionref, false)
else if (target.attachEvent)
target.attachEvent(tasktype, functionref)
}
changecontent.connect=function(pageurl, header){
var page_request = false
var bustcacheparameter=""
if (window.ActiveXObject){
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else if (window.XMLHttpRequest)
page_request = new XMLHttpRequest()
else
return false
page_request.onreadystatechange=function(){changecontent.loadpage(page_request, header)}
if (changecontent_ajax_bustcache)
bustcacheparameter=(pageurl.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', pageurl+bustcacheparameter, true)
page_request.send(null)
}
changecontent.loadpage=function(page_request, header){
var innercontent=document.getElementById(header.id.replace("-title", ""))
innercontent.innerHTML=changecontent_ajax_msg
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
innercontent.innerHTML=page_request.responseText
header.ajaxstatus="loaded"
}
}
changecontent.getCookie=function(Name){
var re=new RegExp(Name+"=[^;]+", "i");
if (document.cookie.match(re))
return document.cookie.match(re)[0].split("=")[1]
return ""
}
changecontent.setCookie=function(name, value, days){
if (typeof days!="undefined"){
var expireDate = new Date()
var expstring=expireDate.setDate(expireDate.getDate()+days)
document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()
}
else
document.cookie = name+"="+value
}
|
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt-nodejs');
const validator = require('validator');
const nodemailer = require("nodemailer");
const moment = require('moment');
const config = require('../../config');
var models = require('../models');
var Users = models.users;
module.exports = {
login: function (req, res, next) {
var username = req.body.username;
var password = req.body.password;
const validateResult = validateLoginFormBody(req.body); // { username, password}
if (!validateResult.success) {
return res.status(400).json({
success: false,
message: validateResult.message,
errors: validateResult.errors
}).end();
}
Users.findOne({ where: { username: username } })
.then(function(user) {
if (!user) {
res.status(400).send({ success: false, message: 'Authentication failed. User not found.' });
} else if (user) {
if (!user.status) {
res.status(400).send({ success: false, message: 'Authentication failed. User has been deactived by admin.' });
}
else if (!bcrypt.compareSync(req.body.password, user.hashed_password)) {
res.status(400).json({ success: false, message: 'Authentication failed. Wrong Password.' });
} else {
var payload = { user };
var token = jwt.sign(payload, req.app.get('superSecret'), {
expiresIn: '72h' // expires in 24 hours
});
res.status(200).json({ success: true, message: 'Enjoy Your Token.', token: token });
}
}
})
.catch(function(err) {
return res.status(500).json({ success: false, message: "Internal Server Error" }).end();
})
},
signup: function (req, res, next) {
const validateResult = validateSignupFormBody(req.body);
if (!validateResult.success) {
return res.status(400).json({
success: false,
message: validateResult.message,
errors: validateResult.errors
}).end();
}
var user = {
username: req.body.username,
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
hashed_password: bcrypt.hashSync(req.body.password),
};
Users.findAll({
where: {
username: user.username
}
})
.then((data) => {
if (data.length > 0) {
let errors = {};
errors.username = 'Username Already Exists';
let message = 'Check form for errors';
return res.status(400).json({ success: false, message: message, errors: errors }).end();
} else {
return Users.create(user)
}
})
.then((data) => {
if (!data) {
res.status(400).send({ success: false, message: 'User was not created.' });
} else if (data) {
return res.status(200).json({ success: true, message: 'Succesfully created account', user: data }).end();
}
})
.catch((err) => {
return res.status(500).json({ success: false, message: "Internal Server Error" }).end();
})
},
contact: function (req, res, next) {
const validateResult = validateContactForm(req.body);
if (!validateResult.success) {
return res.status(400).json({
success: false,
message: validateResult.message,
errors: validateResult.errors
}).end();
}
let person_name = req.body.person_name;
let email = req.body.email;
let message = req.body.message;
let createdAtDate = moment().format('MMMM Do YYYY, h:mm:ss a');
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport(config.emailConnection);
// setup e-mail data with unicode symbols
var mailOptions = {
from: '"STSATH 👥" <stsathdemo@gmail.com>', // sender address
to: `adeelimranr@gmail.com, ${email}`, // list of receivers
subject: 'Get In Touch', // Subject line
html: `
<p>
Dear ${person_name}, thanks for getting in touch with STSATH team. One of our
representative will get in touch with you shortly.
</p>
<p>
Email Details (Copy)<br/>
Name: ${person_name}<br/>
Email: ${email}<br/>
Message: ${message}<br/>
Message Sent At: ${createdAtDate}<br/>
<br/><br/><br/>
With Love,
The <a href="http://localhost:3000/">STSATH</a> Team<br/>
</p>
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "EmailMessage",
"potentialAction": {
"@type": "ViewAction",
"url": "https://google.com",
"name": "Go to Google"
},
"description": "Search for something from Google"
}
</script>`
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if (error) {
return res.status(500).json({ success: false, message: 'Internal Server Issue', errors: error }).end();
}
res.status(200).send({ success: true, message: 'Message Sent Succedfully' });
});
},
}
function validateLoginFormBody(payload) {
const errors = {};
let isFormValid = true;
let message = '';
if (!payload || typeof payload.username !== 'string' || payload.username.trim().length === 0) {
isFormValid = false;
errors.username = 'Please provide your username';
}
if (!payload || typeof payload.password !== 'string' || payload.password.trim().length === 0) {
isFormValid = false;
errors.password = 'Please provide your password';
}
if (!isFormValid) {
message = 'Check the form for errors';
}
return {
success: isFormValid,
message,
errors
}
}
function validateSignupFormBody(payload) {
const errors = {};
let isFormValid = true;
let message = '';
if (!payload || typeof payload.username !== 'string' || payload.username.trim().length === 0) {
isFormValid = false;
errors.username = 'Please provide your Username';
}
if (!payload || typeof payload.first_name !== 'string' || payload.first_name.trim().length === 0) {
isFormValid = false;
errors.first_name = 'Please provide your First Name';
}
if (!payload || typeof payload.last_name !== 'string' || payload.last_name.trim().length === 0) {
isFormValid = false;
errors.last_name = 'Please provide your Last Name';
}
if (!payload || typeof payload.email !== 'string' || !validator.isEmail(payload.email) ) {
isFormValid = false;
errors.email = 'Please provide your Email';
}
if (!payload || typeof payload.password !== 'string' || payload.password.trim().length === 0) {
isFormValid = false;
errors.password = 'Please provide your Password';
}
if (!payload || typeof payload.confirmPassword !== 'string' || payload.password.trim().length === 0 || !validator.equals(payload.password, payload.confirmPassword)) {
isFormValid = false;
errors.confirmPassword = 'Password & Confirm Password Do Not Match';
}
if (!isFormValid) {
message = 'Check the form for errors';
}
return {
success: isFormValid,
message,
errors
}
}
function validateContactForm(payload) {
const errors = {};
let isFormValid = true;
let message = '';
if (!payload || typeof payload.person_name !== 'string' || payload.person_name.trim().length === 0) {
isFormValid = false;
errors.person_name = 'Name field is required';
}
if (!payload || typeof payload.email !== 'string' || !validator.isEmail(payload.email)) {
isFormValid = false;
errors.email = 'Please provide a valid email address';
}
if (!payload || typeof payload.message !== 'string' || payload.message.trim().length === 0) {
isFormValid = false;
errors.message = 'Message field is required';
}
if (!isFormValid) {
message= 'Check the form for errors';
}
return {
success: isFormValid,
message,
errors
};
}
|
'use strict';
require("@babel/polyfill");
const _ = require('underscore');
const bcrypt = require('bcrypt');
const createError = require('http-errors');
/**
* @fileOverview contains types and functions used to perform queries on the database.
*
* @author Gustavo Amaral
*
* @requires NPM:pg
* @requires NPM:joi
* @requires NPM:./database_queries.js
*/
const { Database } = require('../configs.js');
const Joi = require('joi');
const uuidv4 = require('uuid/v4');
const pool = Database.pool();
const createClient = Database.createClient;
const { createUserTableSQL,
deleteUserTableSQL,
addUserSQL,
getUserSQL,
authUserSQL,
} = require('./database_queries.js');
/**
* Entity used to hold user's data and do the validation of that data
* when handling the database. It's also a namespace that contains
* functions related directly to the user.
*
* When creating a new user you can omit the user's id. If you do that
* or set to `undefined`, this property will setted to `null`.
*
* @class
*
* @constructor
* @param {number} id user's unique id. Example: 3.
* @param {string} name user's name. Example: Paulo Costa.
* @param {string} email user's email. Example: paulo@gmail.com.
* @param {string} password hashed user's password.
*
* @property id user's name. Example: 1.
* @property name user's name. Example: Gustavo Amaral
* @property email user's email. Example: almeidaws@outlook.com
* @property password user's password. This password isn't stored as a plain
* string, but it's a hash value when storing and retrieving from database.
*/
class User {
constructor(id, name, email, password) {
if (_.isString(id)) {
password = email;
email = name;
name = id;
id = null;
}
if (id === undefined) id = null;
this.id = id;
this.name = name;
this.email = email;
this.password = password;
}
/**
* @typedef {Object} ValidationResult
* @prop {User} value the successful validated user.
* @prop {Error} error if the user's data is invalid, this property contais the error with
* the invalid data description.
*/
/**
* Checks the the user's fields are valid to be added to the
* database or not.
*
* @returns {ValidationResult}
*/
validate() {
const scheme = {
id: Joi.number().integer().min(1).allow(null).required(),
name: Joi.string().min(3).max(30).required(),
email: Joi.string().email().required(),
password: Joi.string().required()
};
return Joi.validate(this, scheme);
}
/**
* Returns a promises whose result is a hashed password that can be stored on be password.
*
* You must to hash the password before saving it to the database for security reasons.
*
* @param {string} password user's plain password.
* @returns {string} hashed password.
*/
static async hashPassword(password) { return await bcrypt.hash(password, 10) }
/**
* Returns `true` if the a plain password is equal to its hashed version or `false` otherwise.
*
* You should't compares two hashed password, instead this function should be used to successfully
* compared a plain text password with a hashed one.
*
* @param {string} plainPassword plain text password received from client.
* @param {string} hashedPassword password retrieved from database.
*/
static async comparePasswords(plainPassword, hashedPassword) { return await bcrypt.compare(plainPassword, hashedPassword) }
}
/** Adds a user of type {@link User} to the data base with an autogenerated
* number ID for that user.
*
* The data is validate before adding to the database.
*
* @param {User} user the user to be added to the database persistently.
* @returns {Promise} the promise's result is an new User with the autogenerated ID.
*/
const addUser = async (user) => {
const { error, validatedUser } = user.validate();
if (error) return Promise.reject(error);
const client = createClient();
await client.connect();
const repeatedUser = await findUser(user.email);
if (repeatedUser) {
const error = createError(409, 'An user with this email already exists');
return Promise.reject(error);
}
const encryptedPassword = await User.hashPassword(user.password);
const addUserConfig = {
text: addUserSQL,
values: [user.name, user.email, encryptedPassword],
};
const promise = await client.query(addUserConfig)
.then(result => {
const copy = _.clone(user);
copy.id = result.rows[0].id;
copy.password = encryptedPassword;
return copy;
});
await client.end();
return promise;
};
/**
* Retrieves a new user from the database based on its ID.
*
* @param {number} id user's valid id.
* @returns {Promise} the promise's result is the retrieved result. If there's
* no user, the promise is rejected.
*/
const getUser = async id => {
const query = {
text: getUserSQL,
values: [id],
};
const client = createClient();
await client.connect();
const promise = await client.query(query)
.then(result => {
if (result.rows.length != 1) {
const message = "There's no User with ID '" + id + "'.";
return Promise.reject(new Error(message));
}
const user = result.rows[0];
return new User(id, user.name, user.email, user.password);
});
await client.end();
return promise;
};
/**
* Returns the authenticated user or throw an HTTP error if there's an error
* with inexistent user or wrong email and password combination.
*
* This function queries the dabatase for a use using its email and checks
* if the give password for that email is correct.
*
* @param {string} email user's email. The email search is case insensitive.
* @param {string} password user's password as plain text.
* @returns a primise whose result is a boolean value.
*/
const authUser = async (email, password) => {
const client = createClient();
await client.connect();
const user = await findUser(email);
if (user === null || !(await User.comparePasswords(password, user.password))) {
throw createError(401, 'Incorrect email or password');
}
await client.end();
return user;
}
/**
* Returns the first user with a given email.
* @param {string} email user's email.
* @param {Promise} found user.
*/
const findUser = async email => {
const query = {
text: authUserSQL,
values: [email.toLowerCase()],
};
const client = createClient();
await client.connect();
const result = await client.query(query);
await client.end();
if (result.rows.length != 1) return null;
const { id, name, password } = result.rows[0];
return new User(id, name, email, password);
}
/**
* @typedef {Object} Connection
* @property {addUser} addUser used to inserts a new user into database.
*/
/**
* @typedef {Object} Database
* @property {User} User class used as entity to handle CRUD related to the user.
* @property {Connect
*/
/**
* Establishes a connection to the database that can be used to perform queries.
*
* The returned valued from promise is a {@link Connection}.
*
* @returns {Promise} the promise's result is an object with queries that can be used to
* communicates with the database.
*/
const connect = async () => {
const queries = {
addUser,
getUser,
authUser,
};
return queries;
};
const disconnect = async () => {
await pool.end();
}
const createUserTable = async () => await pool.query(createUserTableSQL);
const deleteUserTable = async () => await pool.query(deleteUserTableSQL);
/**
* Exports an object that currently can be used to constructs users and establishes
* a connection with the database.
* @module DatabaseModule
* @exports DatabaseModule
*/
module.exports = {
User,
connect,
disconnect,
DDL: {
createUserTable,
deleteUserTable,
},
};
|
const mysqlclient = require('mysql2');
var dbConnection = require('../GlobalConfig/mysqlDB');
class dbmysql {
constructor(dbId = "0") {
var db=dbConnection[dbId];
db.waitForConnections=true;
this.pool = mysqlclient.createPool(db);
}
async Query(query, binds=[]) {
const promisePool = this.pool.promise();
var result =await promisePool.query(query, binds);
return result? result[0]:null;
}
}
const dbmysqlInst=new dbmysql("0");
class dbInstance {
getDbClient(config = { dbId :"0", db: "mysql" }) {
if (config.db == "mysql")
return dbmysqlInst
else
return null;
}
}
const instance=new dbInstance();
module.exports = instance;
|
/* Your Code Here */
/*
We're giving you this function. Take a look at it, you might see some usage
that's new and different. That's because we're avoiding a well-known, but
sneaky bug that we'll cover in the next few lessons!
As a result, the lessons for this function will pass *and* it will be available
for you to use if you need it!
*/
let createEmployeeRecord = employeeData => {
return {
firstName: employeeData[0],
familyName: employeeData[1],
title: employeeData[2],
payPerHour: employeeData[3],
timeInEvents: [],
timeOutEvents: []
}
}
let createEmployees = employeesData => {
return employeesData.map(employee => createEmployeeRecord(employee));
}
let createTimeInEvent = function(dateStamp) {
let [date, hour] = dateStamp.split(" ");
this.timeInEvents.push({
type: "TimeIn",
hour: parseInt(hour, 10),
date
})
return this
}
let createTimeOutEvent = function(dateStamp) {
let [date, hour] = dateStamp.split(" ");
this.timeOutEvents.push({
type: "TimeOut",
hour: parseInt(hour, 10),
date
})
return this
}
let hoursWorkedOnDate = function(date) {
let timeIn = this.timeInEvents.find(e => e.date === date);
let timeOut = this.timeOutEvents.find(e => e.date === date);
let hoursWorked = (timeOut.hour - timeIn.hour)/100;
return hoursWorked;
}
let wagesEarnedOnDate = function(date) {
return (hoursWorkedOnDate.call(this,date) * this.payPerHour);
}
let allWagesFor = function () {
let eligibleDates = this.timeInEvents.map(function (e) {
return e.date
})
let payable = eligibleDates.reduce(function (memo, d) {
return memo + wagesEarnedOnDate.call(this, d)
}.bind(this), 0) // <== Hm, why did we need to add bind() there? We'll discuss soon!
return payable
}
const calculatePayroll = employees => {
let employeeTotalWages = employees.map(employee => allWagesFor.call(employee));
let totalPayroll = employeeTotalWages.reduce((acc, curr) => acc + curr, 0);
return totalPayroll;
}
const createEmployeeRecords = arr => arr.map(employee => createEmployeeRecord(employee));
const findEmployeebyFirstName = (arr, firstName) => arr.find(employee => employee.firstName === firstName);
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 5);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
// removed by extract-text-webpack-plugin
/***/ }),
/* 1 */
/***/ (function(module, exports) {
// removed by extract-text-webpack-plugin
/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
let wrapInitDay = document.createElement('div');
function setElem(wrap, count, opas) {
let htmlDay = document.createElement('span');
htmlDay.innerHTML = count;
wrap.appendChild(htmlDay);
if (opas) {
htmlDay.classList.add(opas);
}
}
/* harmony default export */ __webpack_exports__["a"] = ((year, month)=> {
wrapInitDay.innerHTML="";
let countDay = (32 - new Date(year, month, 32).getDate());
let preCountDay = (32 - new Date(year, month - 1, 32).getDate());
let firstDay = new Date(year, month, 1).getDay();
let lastDay = new Date(year, month, countDay).getDay()+1;
for (let i = firstDay-1; i >= 0; i--) {
if(firstDay<=6){setElem(wrapInitDay, preCountDay - i, "opasDay");}
}
for (let i = 1; i <= countDay; i++) {
setElem(wrapInitDay, i);
}
let y = 1;
for (let i = lastDay; lastDay<=6; lastDay++) {
setElem(wrapInitDay, y++,"opasDay");
}
return wrapInitDay;
});
/***/ }),
/* 3 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
let arrMonth = ['January','February','March','April','May','June','July','August','September','October','November','December'];
/* harmony default export */ __webpack_exports__["a"] = (( month,wrap)=>{
return arrMonth[month];
});
/***/ }),
/* 4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__ajax__ = __webpack_require__(6);
/* harmony default export */ __webpack_exports__["a"] = (function() {
let result = null;
__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__ajax__["a" /* default */])('GET','https://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=5').then((e)=> {
result = JSON.parse(e);
},(e)=>{
result = e;
});
return result;
});
/***/ }),
/* 5 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__modules_days__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__modules_month__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__modules_set_data__ = __webpack_require__(4);
__webpack_require__(0);
__webpack_require__(1);
// variables
let date = new Date();
let nowYear = date.getFullYear();
let nowMonth = date.getMonth();
// block
let daysBlock = document.querySelector('.days');
let monthBlock = document.querySelector('.month');
let yearBlock = document.querySelector('.year');
// button month
let btnMonPre = document.querySelector('.pre_month');
let btnMonNext = document.querySelector('.next_month');
// default init data
daysBlock.appendChild(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__modules_days__["a" /* default */])(nowYear, nowMonth));
monthBlock.innerHTML = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__modules_month__["a" /* default */])(nowMonth);
yearBlock.innerHTML = nowYear;
btnMonPre.addEventListener('click', () => {
// set days
if (nowMonth == 0) {
nowMonth = 12;
daysBlock.appendChild(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__modules_days__["a" /* default */])(--nowYear, nowMonth));
yearBlock.innerHTML = nowYear;
}
daysBlock.appendChild(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__modules_days__["a" /* default */])(nowYear, --nowMonth));
// set month
monthBlock.innerHTML = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__modules_month__["a" /* default */])(nowMonth);
})
btnMonNext.addEventListener('click', () => {
// set days
if (nowMonth == 11) {
nowMonth = 0;
daysBlock.appendChild(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__modules_days__["a" /* default */])(++nowYear, nowMonth));
yearBlock.innerHTML = nowYear;
}
daysBlock.appendChild(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__modules_days__["a" /* default */])(nowYear, ++nowMonth));
// set month
monthBlock.innerHTML = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__modules_month__["a" /* default */])(nowMonth);
})
// plus zero
function setZero(number) {
return + number > 9
? number
: '0' + number;
}
console.log(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__modules_set_data__["a" /* default */])());
/***/ }),
/* 6 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony default export */ __webpack_exports__["a"] = ((meth, url)=>{
return new Promise((resolve, reject)=>{
let xhr = new XMLHttpRequest();
xhr.open(meth,url);
xhr.addEventListener('load',()=>{
resolve(xhr.responseText);
});
xhr.addEventListener('error',()=>{
reject(xhr.statusText);
})
xhr.send();
});
});
/***/ })
/******/ ]);
|
import React, { useEffect, useState } from 'react'
import { useData, useHub } from '@sporttotal/hub'
export default ({ dark }) => {
const overlay = useData('device.overlay')
const hub = useHub()
const [visible, setVisible] = useState(false)
useEffect(() => {
setVisible(!!overlay)
}, [overlay])
useEffect(() => {
const esc = e => {
if (e.keyCode === 27) {
hub.set('device.overlay', false)
}
}
document.addEventListener('keydown', esc)
return () => {
document.removeEventListener('keydown', esc)
}
})
if (overlay) {
const { component, fade } = overlay
const close = (
<div
onClick={() => {
hub.set('device.overlay', false)
}}
style={{
top: 0,
left: 0,
right: 0,
bottom: 0,
zIndex: -1,
height: '100vh',
width: '100vw',
position: 'absolute'
}}
/>
)
// position
return (
<div
style={{
position: 'fixed',
top: 0,
left: 0,
height: '100vh',
width: '100vw',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
transition: 'background 0.15s',
// backgroundColor: hub.get('device.overlay').backgroundColor || 'rgb(250,251,252)',
backgroundColor: dark
? fade && visible
? 'rgba(10,11,12, 0.75)'
: 'rgba(10,11,12, 0)'
: fade && visible
? 'rgba(250,251,252, 0.75)'
: 'rgba(250,251,252, 0)'
}}
>
{close}
{component}
</div>
)
}
return null
}
|
module.exports = {
validate: {
params: {
optimizationGoal: 'APP_INSTALLS',
billingEvent: 'OFFER_CLAIMS',
},
response: false,
},
map: {
params: {
optimizationGoal: 'APP_INSTALLS',
},
response: ["IMPRESSIONS"]
}
}
|
/* eslint-disable jsx-a11y/click-events-have-key-events */
/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
/* eslint-disable react/prop-types */
import React from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { setItem, unsetItem } from '../actions/foodCardActions';
import './styles/FoodCardSimp.css';
import circleRight from '../assets/SVG/circle-right.svg';
import plusIcon from '../assets/SVG/plus.svg';
import check from '../assets/SVG/checkmark.svg';
const FoodCardSimp = (props) => {
const { name, id, selectedItems, type } = props;
const handleClick = () => {
if (!selected) {
props.setItem({ id, amount: 100 });
} else {
props.unsetItem(id);
}
};
let selectedArray = [];
if (selectedItems.length > 0) {
selectedArray = selectedItems.filter((item) => item.id === id);
if (!(selectedArray.length > 0)) {
selectedArray = [{ id: 0 }];
}
} else {
selectedArray = [{ id: 0 }];
}
const selected = selectedArray[0].id === id;
return (
<div className="FoodCardSimp">
<h3>{name} ({type})</h3>
<div className="icons">
{ selected
? (
<img
src={check}
alt="checkIcon"
className="checkIcon"
onClick={() => handleClick()}
/>
)
: (
<img
src={plusIcon}
alt="plusIcon"
className="plusIcon"
onClick={() => handleClick()}
/>
)}
<Link to={`Search/${id}`}>
<img src={circleRight} alt="" />
</Link>
</div>
</div>
);
};
const mapStateToProps = (state) => ({
selectedItems: state.selectedItems,
});
const mapDispatchToProps = {
setItem,
unsetItem,
};
export default connect(mapStateToProps, mapDispatchToProps)(FoodCardSimp);
|
const router = require( 'express' ).Router() ;
const item = require( './item.controller' ) ;
const { validator } = require( "../../middleware/validator" ) ;
router.get( '/' , validator.item.search , item.search ) ;
router.get( '/sales' , validator.item.sales , item.sales ) ;
router.get( '/stock' , validator.item.stock , item.stock ) ;
router.get( '/detail' , validator.item.detail , item.detail ) ;
router.get( '/purchases' , validator.item.purchases , item.purchases ) ;
router.post( '/add' , validator.item.add , item.add ) ;
router.post( '/update' , validator.item.update , item.update ) ;
module.exports.router = router
|
import React, { useEffect } from "react";
import { connect } from "react-redux";
import { fetchProducts } from "../redux/products/productActions";
import { addToCart } from "../redux/cart/cartActions";
import Product from "./Product";
import Load from "./Loader";
import Navigation from "./Navigation";
function Products({ productData, fetchProducts, addToCart, cart }) {
useEffect(() => {
fetchProducts();
}, []);
const handleChange = (e, product) => {
e.preventDefault();
addToCart(product);
};
return productData.loading ? (
<Load />
) : productData.error ? (
<h2>{productData.error}</h2>
) : (
<div>
<Navigation />
<h2>Available Products</h2>
<div>
{productData &&
productData.products &&
productData.products.map(product => {
return (
<>
<Product product={product} />
<button onClick={e => handleChange(e, product)}>
Add To Cart
</button>
</>
);
})}
{console.log(cart)}
</div>
</div>
);
}
const mapStateToProps = state => {
return {
productData: state.product,
cart: state.cart
};
};
const mapDispatchToProps = dispatch => {
return {
fetchProducts: () => dispatch(fetchProducts()),
addToCart: product => dispatch(addToCart(product))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Products);
|
import React from 'react';
import { shallow } from 'enzyme';
import Button from '../index';
const props = {
onClick: jest.fn(),
children: 'Calculate'
}
let wrapper;
beforeEach(() => {
wrapper = shallow(<Button {...props}/>);
});
test('Should render correctly', () => {
const button = wrapper.find('button');
expect(button.length).toEqual(1);
expect(button.text()).toEqual('Calculate');
});
test('Should invoke correct function when clicked', () => {
const spy = jest.spyOn(wrapper.props(), 'onClick');
const button = wrapper.find('button');
button.simulate('click');
expect(spy).toHaveBeenCalled();
});
|
let memberArray = ['egoing', 'graphittie', 'leezhce'];
console.log("memberArray[2] : ", memberArray[2]);
let memberObject = {
manager: 'egoing',
developer: 'graphittie',
designer: 'leezhce'
}
memberObject.designer = 'leezche';
console.log("memberObject.designer : ", memberObject.designer);
delete memberObject.manager
console.log("memberObject.manager: ", memberObject.manager);
|
$(document).ready(function() {
$.ajax({
url:"http://m.koudaikj.com/channel-cpa/check-login",
data:"",
dataType:'jsonp',
success:function(data) {
if (data.is_login == 0) {
window.location.href = "http://m.koudaikj.com/channel-cpa/login";
}
}
});
});
|
import gql from 'graphql-tag';
export const getAllPaintings = gql`{
paintings {
_id
name
picture
date
}
}`
export const getAllMovements = gql`{
movements {
_id
name
picture
}
}`
export const getAllArtists = gql`{
artists
{
_id
name
picture
born {
date
}
died {
date
}
}
}`
export const getMovementPicture = (movementId) => {
return gql`{
paintings(movementId: "${movementId}")
{
picture
}
}`
};
export const getArtist = (artistId) => {
return gql`{
artist(_id: "${artistId}")
{
_id
name
picture
born {
date
}
died
{
date
}
description
}
}`
};
export const getArtistsByMovement = (movementId) => {
return gql`{
artists(movementId: "${movementId}")
{
_id
name
picture
born {
date
}
died{
date
}
description
}
}`
};
export const getPainting = (paintingId) => {
return gql`{
painting(_id: "${paintingId}")
{
_id
name
date
picture
artist {
name
}
genre
location {
country
city
museum
}
movement {
name
}
dimensions {
width
height
unit
}
}
}`
};
export const getPaintingsByArtist = (artistId) => {
return gql`{
paintings(artistId:"${artistId}")
{
_id
name
date
picture
}
}`
};
export const getMovement = (movementID) => {
return gql`{
movement(_id: "${movementID}")
{
name
description
}
}`
};
|
/* jshint esversion: 6 */
var fs = require('fs');
var shell = require('shelljs');
var path = require('path');
var config = require('./defaultWebdriverConfig');
var RandomtestError = require('./models/random-test').RandomTestError;
var newLine = '\n';
var public = {};
public.runTests = function (application, tests) {
setup(application);
tests.forEach(function (test) {
var runs = test.numRuns || 1;
for (i = 0; i < runs; i++) {
//TODO improve the way the random seed is generated
var seed = Math.floor(Math.random() * Math.floor(10000));
testTranslate(application._id, test);
var dir = `tests/random/${application._id}`;
var wdio = path.normalize('./node_modules/.bin/wdio');
var conf = path.normalize(`${dir}/wdio.conf.js`);
var result = shell.exec(`${wdio} ${conf}`).code;
if (result != 0) {
var error = new RandomtestError({
application: application._id,
test: test._id,
seed: seed,
});
error.save();
}
shell.rm('-rf', `tests/random/${application._id}/scripts/${test._id}.spec.js`);
}
});
};
public.getTestScriptPath = function (test) {
return `tests/random/${test.application}/scripts/${test._id}-gremlins-test.js`;
};
public.testsToScripts = function (application, tests) {
setup(application);
tests.forEach(function(test) {
testTranslate(application._id, test);
});
};
public.runScripts = function (appId) {
var dir = `tests/random/${appId}`;
if (shell.test('-d', dir) && shell.ls(dir + '/scripts').length !== 0) {
var dir1 = path.normalize('./node_modules/.bin/wdio');
var dir2 = path.normalize(`${dir}/wdio.conf.js`);
shell.exec(dir1 + ' ' + dir2, function (code) {
if (code === 0) {
console.log("Success");
} else {
console.log("fail");
}
});
return true;
} else {
return false;
}
};
var testTranslate = function (appId, test, seed) {
var resultFile = {};
resultFile.name = test.name;
seed = seed || 1234;
var data = "var assert = require('assert');" + newLine;
data += "function loadScript(callback) {" + newLine;
data += " var s = document.createElement('script');" + newLine;
data += " s.src = 'https://rawgithub.com/marmelab/gremlins.js/master/gremlins.min.js';" + newLine;
data += " if (s.addEventListener) {" + newLine;
data += " s.addEventListener('load', callback, false);" + newLine;
data += " } else if (s.readyState) {" + newLine;
data += " s.onreadystatechange = callback;" + newLine;
data += " }" + newLine;
data += " document.body.appendChild(s);" + newLine;
data += "}" + newLine;
data += newLine;
data += "function unleashGremlins(ttl, callback) {" + newLine;
data += " function stop() {" + newLine;
data += " horde.stop();" + newLine;
data += " callback();" + newLine;
data += " }" + newLine;
data += " var horde = window.gremlins.createHorde();" + newLine;
data += ` horde.seed(${seed});` + newLine;
data += " horde.after(callback);" + newLine;
data += " window.onbeforeunload = stop;" + newLine;
data += " setTimeout(stop, ttl);" + newLine;
data += ` horde.unleash({nb: ${test.numGremlins}});` + newLine;
data += "}" + newLine;
data += `describe('${test.name}', function() {` + newLine;
data += ` it('${test.description}', function() {` + newLine;
data += ` browser.url('${test.startUrl}');` + newLine;
data += " browser.timeoutsAsyncScript(60000);" + newLine;
data += " browser.executeAsync(loadScript);" + newLine;
data += " browser.timeoutsAsyncScript(60000);" + newLine;
data += ` browser.executeAsync(unleashGremlins, 50*1000);` + newLine;
data += " });" + newLine;
data += " afterAll(function() {" + newLine;
data += " browser.log('browser').value.forEach(function(log) {" + newLine;
data += " browser.logger.info(log.message.split(' ')[2]);" + newLine;
data += " });" + newLine;
data += " });" + newLine;
data += "});" + newLine;
fs.writeFileSync(`tests/random/${appId}/scripts/${test._id}.spec.js`, data);
return data;
};
function createTestsDirs(appId) {
// Rethink the directories considering the fleeting nature of tests
var dir = 'tests/random/' + appId;
var dirs = [dir + '/scripts', dir + '/reports'];
shell.mkdir('-p', dirs);
}
function setup(application) {
createTestsDirs(application._id);
config.writeConfig(application);
}
module.exports = public;
|
export function Navigation(theme, drawerWidth) {
return {
drawerPaper: {
position: 'relative',
whiteSpace: 'nowrap',
width: drawerWidth,
height: "100vh",
},
drawerPaperClose: {
overflowX: 'hidden',
width: theme.spacing(1),
},
fixedHeight: {
height: 240,
},
}
}
|
define(['apps/base/base.directive', 'jstree'],
function (app) {
app.directive('tree', ['$parse', function ($parse) {
var treeDir = {
restrict: 'EA',
fetchResource: function ($scope, cb) {
return $scope.load({ $call: cb });
},
manageEvents: function (s, e, a) {
if (a.changed) {
treeDir.tree.on('changed.jstree', function (e, data) {
if (typeof (s[a.changed]) == "function") {
s[a.changed](e, data);
} else {
var parseFunc = $parse(a.changed);
parseFunc(s);
}
});
}
if (a.ready) {
treeDir.tree.on('ready.jstree', function (e, data) {
if (typeof (s[a.ready]) == "function") {
s[a.ready](e, data);
} else {
var parseFunc = $parse(a.ready);
parseFunc(s);
}
});
}
},
managePlugins: function (s, e, a, config) {
if (a.treePlugins) {
config.plugins = a.treePlugins.split(',');
config.core = config.core || {};
config.core.check_callback = config.core.check_callback || true;
if (config.plugins.indexOf('state') >= 0) {
config.state = config.state || {};
config.state.key = a.treeStateKey;
}
if (config.plugins.indexOf('search') >= 0) {
if (a.search) {
s.$watch(a.search, function (newVal, oldVal) {
if (newVal) {
treeDir.tree.jstree(true).search(newVal, false, true);
} else {
treeDir.tree.jstree(true).clear_search();
}
});
}
}
if (config.plugins.indexOf('checkbox') >= 0) {
config.checkbox = config.checkbox || {};
config.checkbox.keep_selected_style = false;
config.checkbox.three_state = false;
if (a.threeState == "true") {
config.checkbox.three_state = true;
}
}
if (config.plugins.indexOf('contextmenu') >= 0) {
if (s.treeContextmenu) {
config.contextmenu = config.contextmenu || {};
config.contextmenu.items = function (data) {
return s.treeContextmenu(data);
}
}
}
if (config.plugins.indexOf('types') >= 0) {
if (a.treeTypes) {
config.types = s[a.treeTypes];
//console.log(config);
}
config.types = {
"disabled":{
"icon": "fa fa-ban"
},
"folder": {
"icon": "icon-folder"
},
"file": {
"icon": "fa fa-file-text"
},
"user": {
"icon": "icon-user"
},
"users": {
"icon": "icon-users"
},
"cube": {
"icon": "fa fa-cube"
},
"cubes": {
"icon": "fa fa-cubes"
},
"star": {
"icon": "fa fa-star"
},
"edit": {
"icon": "fa fa-edit"
},
"database": {
"icon": "fa fa-database"
},
"cloud": {
"icon": "fa fa-cloud"
},
"filter": {
"icon": "fa fa-filter"
},
"circle": {
"icon": "fa fa-circle-o"
},
"list": {
"icon": "fa fa-th-list"
}
}
}
if (config.plugins.indexOf('themes') >= 0) {
config.themes = {
"theme": "classic",
"dots": false,
"icons": true
}
}
if (config.plugins.indexOf('dnd') >= 0) {
if (a.treeDnd) {
config.dnd = s[a.treeDnd];
//console.log(config);
}
}
}
return config;
},
link: function (s, e, a) { // scope, element, attribute \O/
$(function () {
var config = {};
// users can define 'core'
config.core = {};
if (a.treeCore) {
config.core = $.extend(config.core, s[a.treeCore]);
}
// clean Case
a.treeData = a.treeData ? a.treeData.toLowerCase() : '';
a.treeSrc = a.treeSrc ? a.treeSrc.toLowerCase() : '';
if (a.treeData == 'html') {
treeDir.fetchResource(s, function (data) {
e.html(data);
treeDir.init(s, e, a, config);
});
} else if (a.treeData == 'json') {
treeDir.fetchResource(s, function (data) {
config.core.data = data;
treeDir.init(s, e, a, config);
});
} else if (a.treeData == 'scope') {
s.$watch(a.treeModel, function (n, o) {
if (n) {
config.core.data = s[a.treeModel];
$(e).jstree('destroy');
treeDir.init(s, e, a, config);
}
}, true);
// Trigger it initally
// Fix issue #13
//config.core.data = s[a.treeModel];
//treeDir.init(s, e, a, config);
} else if (a.treeAjax) {
config.core.data = {
'url': a.treeAjax,
'data': function (node) {
return {
'id': node.id != '#' ? node.id : 1
};
}
};
treeDir.init(s, e, a, config);
}
});
},
init: function (s, e, a, config) {
treeDir.managePlugins(s, e, a, config);
this.tree = $(e).jstree(config);
if (a.treeApi) {
if (typeof (s[a.treeApi]) == "function") {
s.setTreeApi($(e).jstree(true));
} else {
s[a.treeApi] = $(e).jstree(true);
}
}
treeDir.manageEvents(s, e, a);
}
};
return treeDir;
}]);
});
|
/**
* React App SDK (https://github.com/kriasoft/react-app)
*
* Copyright © 2015-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import { createStore, applyMiddleware } from 'redux';
/** Middleware */
import thunk from 'redux-thunk'
import promise from 'redux-promise'
/** Reducers */
import Reducers from './reducers'
// devTools connection
const devTools = window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
// Centralized application state
// For more information visit http://redux.js.org/
// import Reducers from reducers a include him here
const store = applyMiddleware(thunk, promise)(createStore)(Reducers, devTools)
export default store;
|
import React, { useState, useCallback } from 'react';
import { useDispatch } from 'react-redux'
import { deleteInteraction, toggleModal } from '../../../actions'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faCircle, faPencilAlt, faTimesCircle } from '@fortawesome/free-solid-svg-icons'
import { SlideDown } from 'react-slidedown'
import "../../../../node_modules/react-slidedown/lib/slidedown.css"
export default function TimelineEvent(props) {
let id, application, ref, order, interaction
const [showNotes, setShowNotes] = useState(false)
const dispatch = useDispatch()
const deleteThisInteraction = useCallback(
(id, application, ref) => {dispatch(deleteInteraction(id, application, ref))},
[dispatch, id, application, ref]
)
const toggleModal = useCallback(
(order, interaction) => {dispatch(toggleModal(false, order, null, interaction))},
[dispatch, order, interaction]
)
const deleteEvent = () => {
const { deleteThisInteraction } = this.props
let id = props.userId
let application = props.jobId
let ref = props.reference
let c = window.confirm('Delete this interaction?')
if (c === true) deleteThisInteraction(id, application, ref)
}
const edit = () => {
const { toggleModal } = this.props
let ourInteraction = {}
ourInteraction['type'] = props.type
ourInteraction['date'] = props.date
ourInteraction['notes'] = props.notes
ourInteraction['userId'] = props.userId
ourInteraction['jobId'] = props.jobId
ourInteraction['ref'] = props.reference
toggleModal(true, ourInteraction)
}
return (
<div className="job-timeline-entry">
<span className="timeline-dot">
<FontAwesomeIcon icon={faCircle} />
</span>
<ul className="timeline-basics"
onClick={setShowNotes(!showNotes)}>
<li>{props.type}</li>
<li className="timeline-divider"> — </li>
<li className="timeline-date">{props.date}</li>
{props.type !== "Submitted application" && <li className="timeline-cntrls">
<span className="timeline-cntrl"
onClick={edit}>
<FontAwesomeIcon icon={faPencilAlt} />
</span>
<span className="timeline-cntrl"
onClick={deleteEvent}>
<FontAwesomeIcon icon={faTimesCircle} />
</span>
</li>}
</ul>
<SlideDown className="job-app-slidedown">
{showNotes && <div>
<div className="timeline-notes">{props.notes}</div>
{props.type !== "Submitted application" && <li className="timeline-cntrls cntrls-mobile">
<span className="timeline-cntrl"
onClick={edit}>
<FontAwesomeIcon icon={faPencilAlt} />
</span>
<span className="timeline-cntrl"
onClick={deleteEvent}>
<FontAwesomeIcon icon={faTimesCircle} />
</span>
</li>}
</div>}
</SlideDown>
</div>
)
}
|
// JavaScript Document
Vue.component('headline', {
template: `
<div class="gh">
<transition appear appear-class="gh-text-appear" appear-active-class="gh-text-appear-active">
<div class="gh-container">
<span class="gh-text">历史记忆</span>
</div>
</transition>
</div>
`
});
var app_content = new Vue({
el: '#content',
data: {
intros: [
{id: 1, img: 'intro-backgroud-img-figure', en: 'intro-text-color-Firebrick-en', cn: 'intro-text-color-DarkGoldenrod-cn', texten: 'Figure', textcn: '历史名家', url: 'figure.html', btntext: '名家'},
{id: 2, img: 'intro-backgroud-img-poi', en: 'intro-text-color-Firebrick-en', cn: 'intro-text-color-DarkGoldenrod-cn', texten: 'Poi', textcn: '名胜遗迹', url: 'poi.html', btntext: '名胜'}
]
},
components: {
intro: intro
}
});
|
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/1', function (req, res) {
var xinti = new Array
console.log('wo')
global.db.query(
"SELECT * FROM dongtaitable1 "
+ "WHERE kind = '论坛1'",
function S1(err, rows, fields) {
if (err) throw err;
console.log(rows)
for(i=0;i<rows.length;i++){
xinti.push(rows[i])
}
res.render('pinglun', { title:'Express',xinti1:xinti});
})
})
router.get('/2', function (req, res) {
var xinti= new Array
global.db.query(
"SELECT * FROM dongtaitable1 "
+ "WHERE kind = '论坛2'",
function S1(err, rows, fields) {
if (err) throw err;
for(i=0;;i++){
if(typeof(rows[i]=="undefined"))break
xinti.push(rows[i])
}
res.render('pinglun', { title:'Express',xinti1:xinti});
})
})
router.get('/3', function (req, res) {
var xinti= new Array
global.db.query(
"SELECT * FROM dongtaitable1 "
+ "WHERE kind = '论坛3'",
function S1(err, rows, fields) {
if (err) throw err;
for(i=0;;i++){
if(typeof(rows[i]=="undefined"))break
xinti.push(rows[i])
}
res.render('pinglun', { title:'Express',xinti1:xinti});
})
})
router.get('/4', function (req, res) {
var xinti= new Array
global.db.query(
"SELECT * FROM dongtaitable1 "
+ "WHERE kind = '论坛4'",
function S1(err, rows, fields) {
if (err) throw err;
for(i=0;;i++){
if(typeof(rows[i]=="undefined"))break
xinti.push(rows[i])
}
res.render('pinglun', { title:'Express',xinti1:xinti});
})
})
router.get('/5', function (req, res) {
var xinti= new Array
global.db.query(
"SELECT * FROM dongtaitable1 "
+ "WHERE kind = '论坛5'",
function S1(err, rows, fields) {
if (err) throw err;
for(i=0;;i++){
if(typeof(rows[i]=="undefined"))break
xinti.push(rows[i])
}
res.render('pinglun', { title:'Express',xinti1:xinti});
})
})
router.get('/6', function (req, res) {
var xinti= new Array
global.db.query(
"SELECT * FROM dongtaitable1 "
+ "WHERE kind = '论坛6'",
function S1(err, rows, fields) {
if (err) throw err;
for(i=0;;i++){
if(typeof(rows[i]=="undefined"))break
xinti.push(rows[i])
}
res.render('pinglun', { title:'Express',xinti1:xinti});
})
})
router.get('/7', function (req, res) {
var xinti= new Array
global.db.query(
"SELECT * FROM dongtaitable1 "
+ "WHERE kind = '论坛7'",
function S1(err, rows, fields) {
if (err) throw err;
for(i=0;;i++){
if(typeof(rows[i]=="undefined"))break
xinti.push(rows[i])
}
res.render('pinglun', { title:'Express',xinti1:xinti});
})
})
router.post('/1', function (req, res) {
var bb = req.body.idd
var tmp2 = req.session
tmp2.text = bb
res.redirect('/dongtai')
})
router.post('/2', function (req, res) {
var bb = req.body.idd
var tmp2 = req.session
tmp2.text = bb
res.redirect('/dongtai')
})
router.post('/3', function (req, res) {
var bb = req.body.idd
var tmp2 = req.session
tmp2.text = bb
res.redirect('/dongtai')
})
router.post('/4', function (req, res) {
var bb = req.body.idd
var tmp2 = req.session
tmp2.text = bb
res.redirect('/dongtai')
})
router.post('/5', function (req, res) {
var bb = req.body.idd
var tmp2 = req.session
tmp2.text = bb
res.redirect('/dongtai')
})
router.post('/6', function (req, res) {
var bb = req.body.idd
var tmp2 = req.session
tmp2.text = bb
res.redirect('/dongtai')
})
router.post('/7', function (req, res) {
var bb = req.body.idd
var tmp2 = req.session
tmp2.text = bb
res.redirect('/dongtai')
})
router.post('/8', function (req, res) {
var bb = req.body.idd
var tmp2 = req.session
tmp2.text = bb
res.redirect('/dongtai')
})
module.exports = router;
|
import fetch from 'isomorphic-fetch'
import { polyfill } from 'es6-promise'
export function checkStatus (response) {
if (response.status >= 200 && response.status < 300) {
return response
} else {
let error = new Error(response.statusText)
error.response = response
throw error
}
}
export function parseJSON (res) {
return res.json()
}
export function httpRequest (method, url, data) {
const headers = {
Authorization: localStorage.getItem('rekrewtorAuthToken'),
Accept: 'application/json',
'Content-Type': 'application/json'
}
const body = data
? JSON.stringify(data)
: null
return fetch(url, {
method,
headers,
body
})
.then(checkStatus)
.then(parseJSON)
}
export function get (url, data) {
return httpRequest('get', url, data)
}
export function post (url, data) {
return httpRequest('post', url, data)
}
export function del (url, data) {
return httpRequest('delete', url, data)
}
|
import React, { Component, useState } from 'react';
import { FaAngleLeft, FaAngleRight } from 'react-icons/fa';
import Card from './Card';
export class Slideshow extends Component {
render() {
let [cardIndex, setCardIndex] = useState(0);
let cards = this.props.cardList
.map(card =>
<Card
pic={card.pic}
discription={card.discription}
/>
);
const handleCarouselButton = (direction) => {
if(direction === -1){
if(cardIndex <= 0 ){
setCardIndex(cards.length)}
else{setCardIndex(cardIndex => cardIndex += direction)}
}
else if(direction === 1){
if(cardIndex >= 0){
setCardIndex(cards.length)}
}
else{setCardIndex(cardIndex => cardIndex += direction)}
}
return (
<div className='slideshow-container'>
<button className='slide-left slideshow-button' onClick={handleCarouselButton(-1)}><FaAngleLeft /></button>
<div className='slide-cards'>{cards}</div>
<button className='slide-right slideshow-button' onClick={handleCarouselButton(1)}><FaAngleRight /></button>
</div>
)
}
}
export default Slideshow
|
import { select, easeSin, easeElasticInOut } from "d3v4";
import * as d3 from "d3v4"
export default function dab(config) {
const { setEyes, rightHand, leftHand, handRaise, closedHandPath, openHandPath } = config;
setEyes("default", "default");
const object = {
rightHad: handRaise(rightHand, closedHandPath, openHandPath, easeSin, 600, -50, -50, -1, -1, 10, 900, 0, 0, 1, 1, 90),
leftHand: handRaise(leftHand, closedHandPath, openHandPath, easeSin, 600, -50, 0, -1, -1, 40, 900, 0, 0, 1, 1, 90)
}
return object
}
|
import React from 'react';
import Todo from './Todo'; // todo element or component
// everything in {} means js code n
export default function TodoList( { todos, toggleTodo }) {
return (
todos.map(todo => {
// we are using a key to let react know just to render the one that had changes.
// react don't render all everything single time
return <Todo key={ todo.id } toggleTodo={toggleTodo} todo = {todo} />
})
)
}
|
const mongoose = require("mongoose");
const shortid = require("shortid");
const UserModel = mongoose.Schema(
{
username: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
instockItems: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "InstockItem",
},
],
tobuyItems: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "ToBuyItem",
},
],
uniqueId: {
type: String,
},
},
{
timestamps: true,
}
);
UserModel.pre("save", async function (next) {
this.uniqueId = await shortid.generate();
next();
});
module.exports = mongoose.model("User", UserModel);
|
var elmAppElement = document.getElementById('elmApp');
var elm = Elm.embed(Elm.Main, elmAppElement);
elm.ports.notesPlaying.subscribe(function(data) {
playNotes(data);
});
elm.ports.notesConsole.subscribe(function(data) {
output(data);
});
elm.ports.keysDownConsole.subscribe(function(data) {
output(data);
});
function output(data) {
if (data.length > 0) { console.log(data); }
}
|
const myObject = {
doSomething() {
console.log('does something');
}
};
test('jest.fn().not.toBeCalled()/toHaveBeenCalled()', () => {
const stub = jest.fn();
expect(stub).not.toBeCalled();
expect(stub).not.toHaveBeenCalled();
});
test('jest.spyOn().not.toBeCalled()/toHaveBeenCalled()', () => {
const somethingSpy = jest.spyOn(myObject, 'doSomething').mockReturnValue();
expect(somethingSpy).not.toBeCalled();
expect(somethingSpy).not.toHaveBeenCalled();
});
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const moment = require("moment");
class DateHelper {
static addSeconds(date, seconds) {
date.setSeconds(date.getSeconds() + seconds);
return date;
}
static addMinutes(date, minutes) {
date.setMinutes(date.getMinutes() + minutes);
return date;
}
static addHours(date, hours) {
date.setHours(date.getHours() + hours);
return date;
}
static addDays(date, days) {
date.setDate(date.getDate() + days);
return date;
}
static addMonths(date, months) {
date.setMonth(date.getMonth() + months);
return date;
}
static addYears(date, years) {
date.setFullYear(date.getFullYear() + years);
return date;
}
static getDateEndMonth(month, year) {
const date = moment([year, month - 1]);
return Number(date.endOf('month').format('D'));
}
}
exports.default = DateHelper;
|
/* global _ */
!(function() {
const _ = function(sel) {
return new DOMLang(sel);
};
// Establish the root object, `window` (`self`) in the browser, `global`
// on the server, or `this` in some virtual machines. We use `self`
// instead of `window` for `WebWorker` support.
const root = typeof self == 'object' && self.self === self && self ||
typeof global == 'object' && global.global === global && global ||
this ||
{};
const previousDomLang = root._;
// Export the DOMLang object for **Node.js**, with
// backwards-compatibility for their old module API. If we're in
// the browser, add `_` as a global object.
// (`nodeType` is checked to ensure that `module`
// and `exports` are not HTML elements.)
if (typeof exports != 'undefined' && !exports.nodeType) {
if (typeof module != 'undefined' && !module.nodeType && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// List of HTML entities for escaping.
const escapeMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'`': '`'
};
_.toObject = function(jsonString) {
return JSON.parse(jsonString);
};
_.toJson = function(collec) {
return JSON.stringify(collec);
};
_.toNum = _.toNumber = function(s) {
return Number(s);
};
_.toString = function(collec) {
return _.isLoopable(collec) ? JSON.stringify(collec) : collec.toString();
};
_.toArray = function(o) {
const newArray = [];
loop(o, function() {
newArray.push(this);
});
return newArray;
}
_.isArray = function(o) {
return (o.constructor.name === "HTMLCollection" || o.constructor.name === "NodeList" || Array.isArray(o));
};
_.isElement = function(o) {
try {
//Using W3 DOM2 (works for FF, Opera and Chrome)
return o instanceof HTMLElement;
}
catch(e){
//Browsers not supporting W3 DOM2 don't have HTMLElement and
//an exception is thrown and we end up here. Testing some
//properties that all elements have (works on IE7)
return (typeof o==="object") &&
(o.nodeType===1) && (typeof o.style === "object") &&
(typeof o.ownerDocument ==="object");
}
};
_.isString = function(o) {
return typeof o === "string";
};
_.isNumber = _.isNum = function(num) {
return typeof num === "number";
};
_.isEmpty = function(o) {
return _.keys(o).length === 0;
};
_.isEqual = function(o1, o2) {
return JSON.stringify(o1) == JSON.stringify((o2));
};
_.isFunction = function(method) {
return method && {}.toString.call(method) === '[object Function]';
};
_.isLoopable = _.isIterable = function(o) {
return !_.isEmpty(o);
};
_.isSame = function(o1, o2) {
return (_.isElement(o1) && _.isElement(o2)) ? o1.isSameNode(o2) : o1 == o2;
};
_.escape = function(s) {
let newS = s;
loop(escapeMap, function(key) {
newS = newS.replace(new RegExp(key, "g"), this);
});
return newS;
};
_.unescape = function(s) {
let newS = s;
loop(escapeMap, function(key) {
newS = newS.replace(new RegExp(this, "g"), key);
});
return newS;
};
_.keys = function(o) {
return Object.keys(o);
};
_.values = function(o) {
let vals = [];
let keys = _.keys(o);
for (let i = 0; i < keys.length; i++) {
vals.push(o[keys[i]]);
}
return vals;
};
_.isContains = function(arr, o) {
let ret = false;
loop(arr, function() {
if(_.isSame(this, o)) {
ret = true;
return true;
}
});
return ret;
};
_.ready = function(callback) {
window.addEventListener("DOMContentLoaded", callback, false);
};
_.random = function(min, max=null) {
if (_.isArray(min)) {
let rand = 0 + Math.floor(Math.random() * (min.length));
return min[rand];
}
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
_.range = function(min, max=null) {
const rng = [];
if (_.isString(min)) {
min = min.charCodeAt(0);
max = max.charCodeAt(0);
for (let i = min; i <= max; i++) {
rng.push(String.fromCharCode(i));
}
return rng;
}
if (max == null) {
max = min;
min = 0;
}
for (let i = min; i <= max; i++) {
rng.push(i);
}
return rng;
};
_.map = function(collec, callback, context) {
let newCollec = Object.assign({}, collec);
let keys = _.keys(collec);
if (context !== null || context !== undefined) {
for (let i = 0; i < keys.length; i++) {
newCollec[keys[i]] = callback.call(context, keys[i], collec[keys[i]], collec);
}
} else {
for (let i = 0; i < keys.length; i++) {
newCollec[keys[i]] = callback.call(collec[keys[i]], keys[i], collec);
}
}
return newCollec;
};
_.reduce = _.foldl = function(collec, callback, context) {
let keys = _.keys(collec);
let startValue = collec[keys[0]];
for (let i = 1; i < keys.length; i++) {
startValue = callback(startValue, collec[keys[i]], collec);
}
return startValue;
};
_.reduceRight = _.foldr = function(collec, callback, context) {
let keys = _.keys(collec);
let startValue = collec[keys[keys.length - 1]];
for (let i = keys.length - 2; i >= 0; i--) {
startValue = callback(startValue, collec[keys[i]], collec);
}
return startValue;
};
_.find = function(collec, callback) {
let retValue = null;
_.each(collec, function(key) {
let ret = callback(key, this, collec);
if (ret) {
retValue = this;
return true;
}
});
return retValue;
};
_.filter = function(arr, callback) {
let newArr = [];
_.each(arr, function(key) {
let ret = callback(key, this, arr);
if (ret) {
newArr.push(this);
}
});
return newArr;
};
_.where = function(arr, obj) {
let newArr = [];
let keys = _.keys(obj);
_.each(arr, function(key) {
let canIAdd = true;
for (let i = 0; i < keys.length; i++) {
if (this[keys[i]] !== obj[keys[i]]) {
canIAdd = false;
break;
}
}
if (canIAdd) {
newArr.push(this);
}
});
return newArr;
};
_.reject = function(arr, callback) {
let newArr = [];
_.each(arr, function(key) {
let ret = callback(key, this, arr);
if (!ret) {
newArr.push(this);
}
});
return newArr;
};
_.all = _.every = function(arr, callback) {
let isAllOk = true;
loop(arr, function(i) {
let ret = callback(i, this, arr);
if (!ret) {
isAllOk = false;
return true;
}
});
return isAllOk;
};
_.any = _.some = function(arr, callback) {
let isAllOk = false;
loop(arr, function(i) {
let ret = callback(i, this, arr);
if (ret) {
isAllOk = true;
return true;
}
});
return isAllOk;
};
_.invoke = function() {
let args = arguments;
let arr = args[0];
_.each(arr, function(index) {
for (let i = 1; i < args.length; i++) {
arr[index] = this[args[i]]();
}
});
return arr;
};
_.extend = function() {
let newArr = [];
for (let i = 0; i < arguments.length; i++) {
newArr = newArr.concat(arguments[i])
}
return newArr;
};
_.clone = function(collec) {
return _.isArray(collec) ? [].concat(collec) : Object.assign({}, collec);
};
_.has = function(collec, key) {
return _.isContains(_.keys(collec), key);
};
_.each = _.forEach = function(o, callback, context) {
if (_.isArray(o)) {
for (let i = 0; i < o.length; i++) {
let ret = false;
if (context === undefined || context === null) {
ret = callback.call(o[i], i, o);
} else {
ret = callback.call(context, o[i], i, o);
}
if (ret === true) break;
}
}else if (_.isIterable(o)) {
let keys = _.keys(o);
for (let i = 0; i < keys.length; i++) {
let ret = false;
if (context === undefined || context === null) {
ret = callback.call(o[keys[i]], keys[i], o);
} else {
ret = callback.call(context, keys[i], o[keys[i]], o);
}
if (ret === true) break;
}
}
};
function loop(arr, callback) {
for (let i = 0; i < arr.length; i++) {
callback.call(arr[i], i);
}
}
function drop(o, num, isEnd=false) {
let arr;
let itWasString = false;
if (_.isString(o)) {
itWasString = true;
arr = o.split("");
} else {
arr = o;
}
isEnd ? arr.splice(arr.length - num, num) : arr.splice(0, num);
return itWasString ? arr.join("") : arr;
}
_.dropLast = function(o, num=1) {
return drop(o, num, true);
};
_.dropFirst = function(o, num=1) {
return drop(o, num, false);
};
// TODO: implement, http and fetch method
_.fetch = function(url, args={}) {
const promise = new Promise((resolve, reject) => {
let xhr;
if (window.XMLHttpRequest) {
// code for modern browsers
xhr = new XMLHttpRequest();
} else {
// code for old IE browsers
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.statusText == "OK") {
resolve(this);
} else {
reject(this);
}
}
};
let params = "";
if (_.has(args, "params")) {
params += "?";
_.each(args.params, function(key) {
params += (key + "=" + this + "&")
});
params = _.dropLast(params, 1);
}
xhr.open("GET", url + params, true);
if (_.has(args, "headers")) {
_.each(args.headers, function(key) {
xhr.setRequestHeader(key, this);
});
}
xhr.send();
});
return promise;
}
_.post = function(url, args={}) {
const promise = new Promise((resolve, reject) => {
let xhr;
if (window.XMLHttpRequest) {
// code for modern browsers
xhr = new XMLHttpRequest();
} else {
// code for old IE browsers
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.statusText == "OK") {
resolve(this);
} else {
reject(this);
}
}
};
let params = "";
if (_.has(args, "params")) {
params += "?";
_.each(args.params, function(key) {
params += (key + "=" + this + "&")
});
params = _.dropLast(params, 1);
}
let form = "";
if (_.has(args, "form")) {
form += "?";
_.each(args.form, function(key) {
form += (key + "=" + this + "&")
});
form = _.dropLast(form, 1);
}
xhr.open("POST", url + params, true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
if (_.has(args, "headers")) {
_.each(args.headers, function(key) {
xhr.setRequestHeader(key, this);
});
}
form = _.dropFirst(form, 1);
xhr.send(form);
});
return promise;
};
_.upload = function() {
console.warn("_.upload() not implemented yet!");
};
_.eventStack = [];
_.doms = [];
_.extension = function(name, callback) {
if (_.has(_, name)) {
throw "The extension name '" + name + "' already exist."
}
_[name] = callback;
};
_.attrs = function(el) {
return Array.from(el.attributes);
};
function getAttrs(el) {
let attrs = {};
loop(_.attrs(el), function() {
attrs[this] = el.getAttribute(this);
});
return attrs;
}
class DOMLang {
constructor(sel) {
let self = this;
if (sel === undefined || sel === null) {
} else if (_.isString(sel)) {
if (/<[a-z][\s\S]*>/i.test(sel)) {
let el = document.createElement("div");
el.innerHTML = sel;
loop(el.children, function() {
self.push(this);
});
} else {
loop(document.querySelectorAll(sel), function() {
if (!_.isContains(self, this)) {
self.push(this);
}
});
}
} else if (_.isElement(sel)) {
if (!_.isContains(self, sel)) {
self.push(sel);
}
} else if (_.isIterable(sel)) {
loop(sel, function() {
if (_.isElement(this) && !_.isContains(self, this)) self.push(this);
});
}
}
extend() {
let self = this;
for (let i = 0; i < arguments.length; i++) {
let sel = arguments[i];
if (_.isElement(sel)) {
if (!_.isContains(this, sel)) this.push(sel);
} else if (typeof sel === "string") {
loop(document.querySelectorAll(sel), function() {
if (!_.isContains(self, this)) self.push(this);
});
} else {
loop(sel, function() {
if (!_.isContains(self, this)) self.push(this);
});
}
}
return this;
}
addClass(s) {
let cls = s.split(" ");
loop(this, function() {
for (let i = 0; i < cls.length; i++) {
this.classList.add(cls[i].trim());
}
});
return this;
}
removeClass(s) {
let cls = s.split(" ");
loop(this, function() {
for (let i = 0; i < cls.length; i++) {
this.classList.remove(cls[i].trim());
}
});
return this;
}
also(callback) {
callback.call(_(this[0]));
}
each(callback, context) {
if (context === undefined || context === null) {
for (let i = 0; i < this.length; i++) {
callback.call(_(this[i]), i, this);
}
} else {
for (let i = 0; i < this.length; i++) {
callback.call(context, i, _(this[i]), this);
}
}
return this;
}
toggleClass(s) {
let cls = s.split(" ");
loop(this, function() {
for (let i = 0; i < cls.length; i++) {
let cl = cls[i].trim();
if (this.classList.contains(cl)) {
this.classList.remove(cl);
} else {
this.classList.add(cl);
}
}
});
return this;
}
append() {
for (let k = 0; k < arguments.length; k++) {
let sel = arguments[k];
if (_.isString(sel)) {
let elements = _(sel);
for (let i = 0; i < elements.length; i++) {
for (let j = 0; j < this.length; j++) {
this[j].appendChild(elements[i]);
}
}
} else if (_.isElement(sel)) {
for (let i = 0; i < this.length; i++) {
this[i].appendChild(sel);
}
} else if (_.isIterable(sel) || _.isArray(sel)) {
for (let i = 0; i < sel.length; i++) {
if (_.isElement(sel[i])) {
for (let j = 0; j < this.length; j++) {
this[j].appendChild(sel[i]);
}
}
}
}
}
return this;
}
prepend() {
let self = this;
for (let k = 0; k < arguments.length; k++) {
let sel = arguments[k];
if (_.isString(sel)) {
loop(_(sel), function() {
let el = this;
loop(self, function() {
this.insertBefore(el, this.childNodes[0]);
});
});
} else if (_.isElement(sel)) {
loop(this, function() {
this.insertBefore(sel, this.childNodes[0]);
});
} else if (_.isIterable(sel)) {
loop(sel, function() {
let el = this;
if (_.isElement(el)) {
loop(self, function() {
this.insertBefore(el, this.childNodes[0]);
});
}
});
}
}
return this;
}
render(s) {
loop(this, function() {
_.render(this, s);
});
return this;
}
html(s) {
if (s === undefined || s === null) return this[0].innerHTML;
for (let i = 0; i < this.length; i++) {
this[i].innerHTML = s;
}
return this;
}
text(s) {
if (s === undefined || s === null) return this[0].textContent;
for (let i = 0; i < this.length; i++) {
this[i].innerHTML = _.escape(s);
}
return this;
}
attr(key, val) {
if (val === undefined || val === null) {
return this[0].getAttribute(key);
}
loop(this, function() {
this.setAttribute(key, val);
});
return this;
}
prop(key, val) {
return this.attr(key, val);
}
on(event, callback) {
return this.bind(event, callback);
}
bind(event, callback) {
let events = event.split(" ");
loop(this, function() {
_.eventStack.push({
"element": this,
"callback": callback,
"event": event
});
for (let j = 0; j < events.length; j++) {
this.addEventListener(events[j].trim(), function() {
callback.call(_(this));
}, false);
}
});
return this;
}
unbind(event) {
let self = this;
let events = event.split(" ");
let toRemoveEvent = [];
loop(this, function() {
let el = this;
for (let j = 0; j < events.length; j++) {
loop(_.eventStack, function(i) {
if (_.isSame(el, this["element"]) && events[j] === this["event"]) {
el.removeEventListener(events[j], this["callback"]);
toRemoveEvent.push(i);
}
});
}
});
loop(toRemoveEvent, function() {
_.eventStack.splice(this, 1);
});
return this;
}
select(sel) {
let dom = new DOMLang();
loop(this[0].querySelectorAll(sel), function() {
dom.push(this);
});
return dom;
}
clear() {
let toRemoveEvent = [];
loop(this, function() {
let el = this;
loop(_.eventStack, function(i) {
if (_.isSame(el, this["element"])) {
el.removeEventListener(event, this["callback"]);
toRemoveEvent.push(i);
}
});
});
loop(toRemoveEvent, function() {
_.eventStack.splice(this, 1);
});
return this;
}
disable() {
loop(this, function() {
this.disabled = true;
});
return this;
}
enable() {
loop(this, function() {
this.disabled = false;
});
return this;
}
isDisabled() {
return this[0].disabled
}
children(includeAll=false) {
return includeAll ? this[0].childNodes : this[0].children;
}
click(callback) {
return this.bind("click", callback);
}
css(style, val) {
let self = this;
if (val === null || val === undefined) {
loop(_.keys(style), function() {
let key = this;
let value = style[key];
loop(self, function() {
this.style[key] = value;
});
});
} else {
loop(this, function() {
this.style[style] = val;
});
}
return this;
}
siblings() {
let sibs = [];
let currentElement = this[0];
loop(currentElement.parentNode.children, function() {
if (!_.isSame(this, currentElement)) {
sibs.push(this);
}
});
return _(sibs);
}
first() {
return _(this[0]);
}
last() {
return _(this[this.length - 1]);
}
filter(sel) {
let container = document.createElement("div");
let newElements = [];
loop(this, function() {
container.innerHTML = "";
container.appendChild(this.cloneNode());
if (container.querySelector(sel) === null) {
newElements.push(this);
}
});
return _(newElements);
}
height(val) {
if (val === undefined || val === null || !_.isNumber(val)) return this[0].offsetHeight;
this.css("height", val + "px");
return this;
}
width(val) {
if (val === undefined || val === null || !_.isNumber(val)) return this[0].offsetWidth;
this.css("width", val + "px");
return this;
}
innerHeight() {
return this[0].clientHeight;
}
innerWidth() {
return this[0].clientWidth;
}
hide() {
loop(this, function() {
this.style.visibility = "hidden";
});
return this;
}
show() {
loop(this, function() {
this.style.visibility = "visible";
});
return this;
}
offset() {
let el = this[0];
let _x = 0;
let _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x, x: _x, y: _y };
}
parent() {
return this[0].parentNode;
}
parents() {
let ps = [];
loop(this, function() {
if (!_.isContains(ps, this.parentNode)) {
ps.push(this.parentNode);
}
});
return _(ps);
}
removeAttr(key) {
loop(this, function() {
this.removeAttribute(key);
});
return this;
}
remove() {
loop(this, function() {
this.remove();
});
return this;
}
val() {
return this[0].value;
}
}
DOMLang.prototype.push = Array.prototype.push;
DOMLang.prototype.pop = Array.prototype.pop;
DOMLang.prototype.splice = Array.prototype.splice;
DOMLang.prototype.get = function(index) {
return _(this[index]);
};
_.plugin = function(name, callback) {
DOMLang.prototype[name] = callback;
};
})();
|
import axios from 'axios';
import qs from 'qs';
var PMT = {
getAll: function(){
return axios.get(window.apiDomainUrl+'/payment-type/get-all', qs.stringify({}))
},
};
export function PaymentTypeManager() {
return PMT;
}
|
import React from 'react';
import Todos from './components/Todos'
import ToggleButton from './components/ToggleButton'
class App extends React.Component {
render() {
return (
<div>
<a href="https://www.quest-global.com/"><h2 className="Titlecentered ">Digital Campaign</h2></a>
<Todos/>
<ToggleButton/>
</div>
);
}
} export default App;
|
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "0f909c77ba04ebf01e6202f022d72d75",
"url": "/index.html"
},
{
"revision": "84f3f957dc8894f9faa6",
"url": "/static/css/main.d5cd5a1d.chunk.css"
},
{
"revision": "7f929ac5ca6c5a83872c",
"url": "/static/js/2.029fe90b.chunk.js"
},
{
"revision": "84f3f957dc8894f9faa6",
"url": "/static/js/main.3509d872.chunk.js"
},
{
"revision": "7565c46f720b3eaaabbd",
"url": "/static/js/runtime-main.e695090d.js"
},
{
"revision": "8446a5a823ba743fdbb005c1b44ac007",
"url": "/static/media/background.8446a5a8.jpg"
},
{
"revision": "75343b24cff351df82b7280181019a2a",
"url": "/static/media/cekongkir-min.75343b24.png"
},
{
"revision": "cf3f11fd5a8eb65dc3a0a7f90db3fe46",
"url": "/static/media/cekresi-min.cf3f11fd.png"
},
{
"revision": "0acd2469b770a49bc28175b906cfbdb0",
"url": "/static/media/demandAIimg1.0acd2469.png"
},
{
"revision": "ca553a33554577f3365c4aed608e8e91",
"url": "/static/media/demandAIimg2.ca553a33.png"
},
{
"revision": "a67452198af044fa4f33142681e54df7",
"url": "/static/media/foto.a6745219.jpg"
},
{
"revision": "d68e132bef944419aed1d1f53b13c40c",
"url": "/static/media/melisa-cover.d68e132b.jpg"
},
{
"revision": "ca79cee24299fb779ffb2b47f9faed74",
"url": "/static/media/melisa2-min.ca79cee2.png"
},
{
"revision": "dc7c6efebe8f231281081fb1ac7b93f4",
"url": "/static/media/melisa3-min.dc7c6efe.png"
},
{
"revision": "f4064e21faba56eac0ca4b17e4b3ca0c",
"url": "/static/media/melisa4-min.f4064e21.png"
},
{
"revision": "6262e449160564619cd7f4e7601b4d98",
"url": "/static/media/melisa5-min.6262e449.png"
},
{
"revision": "2766b32aa2ec96a90a196c92c41d47f7",
"url": "/static/media/melisa6-min.2766b32a.png"
},
{
"revision": "4a7e0dc996041881755ad3f6459868a0",
"url": "/static/media/melisa7-min.4a7e0dc9.png"
}
]);
|
Ext.define('App.view.SearchPanel', {
extend: 'Ext.Container',
alias : 'widget.searchPanel',
id:'searchPanel',
config: {
items: [
{
layout:'hbox',
items: [
{
cls: 'searchfield-stations',
xtype: 'searchfield',
placeHolder: 'search by address, city or zip',
itemId: 'searchBox',
id:'pac-input',
listeners: {
blur: function( e ) {
var val = e.getValue();
setTimeout(function() {
document.getElementById('pac-input').getElementsByTagName('input')[0].value = val;
},10);
}
}
},{
style:'cursor:pointer;',
html:'<img id="searchBtn" src="img/main-page-toolbar-search-btn.png" style="width:44px;height:52px;">',
listeners: {
tap: {
fn: function( e, node ) {
Ext.getCmp("mapPanel").startGeocoderPosition();
Ext.getCmp('searchPanel').hideSearchResult();
},
element: 'element'
}
}
}
]
},{
id:'searchList',
xtype: 'list',
style:"background-color: rgba(255,255,255,.8);font-size:65%;margin-left:10px;",
width:'295px',
store : 'StationStore',
itemTpl: '<div><b>{name}</b>, {country}</div>'
+'<div>{zip}, {state}, {city}, {address}</div>',
emptyText: '<div class="myContent"></div>',
listeners: {
tap: {
fn: function( e, node ) {
Ext.getCmp('searchPanel').hideSearchResult();
},
element: 'element'
}
}
}
]
},
initialize: function(me, eOpts) {
this.hideSearchResult();
},
showSearchResult: function() {
// Ext.getCmp('searchList').setStyle('width:100%;height:300px');
// Ext.getCmp('searchList').show();
},
hideSearchResult: function() {
Ext.getCmp('searchList').hide();
Ext.getCmp('searchList').setStyle('width:0px;height:0px');
}
});
|
var searchData=
[
['server_2ec',['server.c',['../server_8c.html',1,'']]],
['sockets_2eh',['Sockets.h',['../_sockets_8h.html',1,'']]]
];
|
var prompt = require('prompt');
var request = require('request');
var schedule = require('node-schedule');
var credentials = { username : '', password : '' };
var lastIp;
var getIp = function (callback) {
request(
'http://fugal.net/ip.cgi',
function (error, response, body) {
if (!error && response.statusCode == 200) {
var ipAddress = body.trim();
console.log('Current IP Address: ' + ipAddress);
callback(ipAddress);
return;
}
console.log(error);
if (!!body) console.log('Response: ' + body);
});
}
var unblockUs = function (ipAddress) {
if (lastIp == ipAddress) {
console.log('No update.');
return;
}
console.log('Updating unblock-us...');
request(
'https://api.unblock-us.com/login?' + credentials.username + ':' + credentials.password,
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('Response: ' + body);
lastIp = ipAddress;
return;
}
console.log(error);
if (!!body) console.log('Response: ' + body);
});
}
var job = function() {
console.log('Running at ' + new Date() + '...');
getIp(unblockUs);
};
var scheduleJob = function () {
var j = schedule.scheduleJob('10 * * * *', job);
console.log('Job scheduled to run every 10 minutes');
};
var promptProperties = [{ name: 'username' }, { name: 'password', hidden: true }];
prompt.start();
prompt.get(promptProperties, function (err, result) {
if (err) { throw err; }
credentials.username = result.username;
credentials.password = result.password;
scheduleJob();
});
|
//click button for result
const mrButton = document.getElementById('gimmePhrase');
const printedOutput = document.querySelector('.output');
mrButton.addEventListener('click', thePhrase);
// let sentence1;
// let sentence2;
// let sentence3;
// let sentence4;
// var items = [1,2,3,4];
// var index = Math.floor(Math.random() * items.length);
// items[index] = whatever;
function thePhrase() {
const randomDowner = downer[Math.floor(Math.random()*downer.length)];
const randomFirstName = firstName[Math.floor(Math.random()*firstName.length)];
const randomLastName = lastName[Math.floor(Math.random()*lastName.length)];
const randomRealName = realName[Math.floor(Math.random()*realName.length)];
const randomPeriod = period[Math.floor(Math.random()*period.length)];
const randomRelation = relation[Math.floor(Math.random()*relation.length)];
const randomEra = era[Math.floor(Math.random()*era.length)];
const randomRegion = region[Math.floor(Math.random()*region.length)];
const randomGenre = genre[Math.floor(Math.random()*genre.length)];
const randomMedium = medium[Math.floor(Math.random()*medium.length)];
const randomPrefix = prefix[Math.floor(Math.random()*prefix.length)];
const randomSubEra = subEra[Math.floor(Math.random()*subEra.length)];
//sentences
const sentence1 = `1) “Yeah that’s pretty good I guess, for me perhaps a bit on the ${randomDowner} side. I can’t believe you’re not familiar with ${randomFirstName} ${randomLastName} though. For ${randomRegion} ${randomMedium} it's pretty heady stuff, definitely not for everyone. If you can jump right in to their ${randomPeriod} period, you’ll be blown away. <br> <br> Optional coup de grace: “You know the crazy thing is that ${randomLastName} was ${randomRealName}’s ${randomRelation}?"`;
const sentence2 = `<p>2) Everything changed for me when I found ${randomSubEra}-${randomEra} ${randomRegion} ${randomPrefix}-${randomGenre} ${randomMedium}. My favorite artist is probably ${randomFirstName} ${randomLastName}.</p>`;
const sentence3 = `<p>3) That was my thing for so long, then I found ${randomFirstName} ${randomLastName}. Game changer! While their most popular stuff is decent, albeit occasionally ${randomDowner}, you really need to check out the ${randomMedium} work from their ${randomPeriod} period. They actually had a massive influence on ${randomRealName}.</p>`;
const sentence4 = `<p>4) Oh if you like them you definitely know ${randomFirstName} ${randomLastName} right? No?! Wow well forget everything you thought you knew about ${randomSubEra}-${randomEra} ${randomRegion} ${randomPrefix}-${randomGenre}.</p>`;
const sentences = [
sentence1,
sentence2,
sentence3,
sentence4,
];
const sentenceIndex = Math.floor(Math.random() * sentences.length);
// printedOutput.innerHTML = `hey chief`;
printedOutput.innerHTML = sentences[sentenceIndex];
}
// `<p>1) “Yeah that’s pretty good I guess, for me perhaps a bit on the ${randomDowner} side. I can’t believe you’re not familiar with ${randomFirstName} ${randomLastName} though. For ${randomRegion} ${randomMedium} it's pretty heady stuff, definitely not for everyone. If you can jump right in to their ${randomPeriod} period, you’ll be blown away.</p>
// <p>Optional coup de grace: “You know the crazy thing is that ${randomLastName} was ${randomRealName}’s ${randomRelation}?"</p>
// <p>2) Everything changed for me when I found ${randomSubEra}-${randomEra} ${randomRegion} ${randomPrefix}-${randomGenre} ${randomMedium}. My favorite artist is probably ${randomFirstName} ${randomLastName}.</p>
// <p>3) That was my thing for so long, then I found ${randomFirstName} ${randomLastName}. Game changer! While their most popular stuff is decent, albeit occasionally ${randomDowner}, you really need to check out the ${randomMedium} work from their ${randomPeriod} period. They actually had a massive influence on ${randomRealName}.</p>
// <p>4) Oh if you like them you definitely know ${randomFirstName} ${randomLastName} right? No?! Wow well forget everything you thought you knew about ${randomSubEra}-${randomEra} ${randomRegion} ${randomPrefix}-${randomGenre}.</p>`
const firstName = [
'Checo',
'Claus',
'Valteri',
'Nico',
'Etta',
'Geraldo',
'Christo',
'Anselm',
'Blake',
'Kevin',
'Willem',
'Atticus',
'Daphne',
'Imogen',
'Liv',
'Boris',
'Simon',
'Nile',
'Alomar',
'Robert',
'Hedi',
'Karin',
'Maryam',
'Adena',
'Bella',
'Halla',
'Rami',
'Jesper',
]
const lastName = [
'Saussure',
'Kinski',
'Pinkham',
'Ronson',
'Esperanza-Sainz',
'Venturi',
'Weston',
'Frakes',
'Tolliver',
'Smithson',
'Edelbright',
'Leclerc',
'Svenson',
'Leander',
'Elbrecht',
'Yorke',
'Gallup',
'Sumner',
'Gahan',
'Bond',
'Visconti',
'Dreijer',
'Pareski',
]
const realName = [
'Jean Paul Sartre',
'Albert Camus',
'Jean-Luc Godard',
'Henri Cartier-Bresson',
'Guy Dubord',
'Jean Baudrillard',
'Roland Barthes',
'Lazlo Moholy-Nagy',
'Umberto Eco',
'Susan Sontag',
'Victor Burgin',
'David Bowie',
'Graham Parson',
'Todd Rundgren',
]
const downer = [
'plebian',
'vapid',
'pedestrian',
'insipid',
'hacky',
'banal',
'anemic',
'kitsch',
'cliche',
'lowbrow',
'boorish',
'provincial',
'tawdry',
'bland',
'unpalatable',
'MoR',
'flat',
'jejune',
'simplistic',
'quotidian',
'prosaic',
];
const prefix = [
'post',
'post-post',
// 'sub',
'pre',
'proto',
'proto',
'pseudo',
'pseudo',
]
const genre = [
'Vaporwave',
'Hypnagogic',
'Chillwave',
'Post-Punk',
'Noise',
'C86',
'Cold Wave',
'Dance Punk',
'DFA',
'Dream-Pop',
'Shoegaze',
'Brit-Pop',
'Electroclash',
'Freak Folk',
'Garage',
'Yacht Rock',
'Trap',
'Witch House',
'Outsider Folk',
]
const medium = [
'comics',
'music',
'painting',
'photography',
'sculpture',
'typography',
'graphic design',
'performance art',
]
const period = [
'post-colonial',
'crimson',
'soft-focus',
'Berlin',
'neo-athletic',
'late',
'early',
'plein air',
'vampiric',
'riot grrl',
]
const era = [
'1950\'s',
'1970\'s',
'1980\'s',
'1960\'s',
'1990\'s',
]
const subEra = [
'late',
'early',
'mid',
]
const region = [
'Balearic',
'Jamaican',
'Michigander',
'Mexican',
'Thai',
'Bi-coastal',
'Trans-Atlantic',
'north country',
'Mancunian',
'Liverpudlian',
'Glaswegian',
'Cockney',
]
const relation = [
'cousin',
'third cousin',
'neighbor',
'bowling partner',
'surfing buddy',
'golf caddy',
'personal shopper',
'roommate',
'pen pal',
]
|
/**
* @module hubiquitus core library
*/
var app = require('./lib/application');
app.logger = require('./lib/logger');
app.monitoring = require('./lib/monitoring');
app.properties = require('./lib/properties');
app.utils = {
ip: require('./lib/utils/ip'),
uuid: require('./lib/utils/uuid')
};
module.exports = app;
|
function onclickTopView(e){
let title = document.getElementById("Protein-Spectrum-Match-Id-SpecId").innerHTML;
//let specID = title.split("#").pop();
let specID = e.currentTarget.getAttribute('specid');
let folderName = "../../topfd";
folderName = folderName.split("&")[0];
let script= document.createElement('script');
let body = document.getElementsByTagName('body')[0];
let fileName = folderName+"/ms2_json/spectrum"+specID+".js";
let massAndIntensityList = [];
script.src = fileName;
body.append(script);
script.onload = function(){
let peakAndIntensityList = getDataFromPRSMtoSpectralView(ms2_data);
let ionList = [];
ionList.push(ms2_data.n_ion_type);
ionList.push(ms2_data.c_ion_type);
//console.log(ionList);
massAndIntensityList = getMassAndIntensityData(specID);
//console.log(prsmGraph.data.proteoform);
let sequence = prsmGraph.data.proteoform.getSeq();
//remove skipped residue
sequence = sequence.slice(prsmGraph.data.proteoform.getFirstPos());
sequence = sequence.slice(0, prsmGraph.data.proteoform.getLastPos() + 1 - prsmGraph.data.proteoform.getFirstPos());
let fixedPtmList = prsmGraph.data.proteoform.getFixedPtm();
//prsmGraph.data.proteoform.compMassShiftList();//recalculate mass shifts
let unknownMassShiftList = prsmGraph.data.proteoform.getUnknownMassShiftAndVarPtm();
//console.log(unknownMassShiftList);
let precursorMass = prsm_data.prsm.ms.ms_header.precursor_mono_mass;
// Stores all the data in the variables respectively
window.localStorage.setItem('peakAndIntensityList', JSON.stringify(peakAndIntensityList));
window.localStorage.setItem('massAndIntensityList', JSON.stringify(massAndIntensityList));
window.localStorage.setItem('ionType', ionList);
window.localStorage.setItem('sequence', JSON.stringify(sequence));
window.localStorage.setItem('fixedPtmList', JSON.stringify(fixedPtmList));
window.localStorage.setItem('protVarPtmsList', JSON.stringify([]));
window.localStorage.setItem('variablePtmsList', JSON.stringify([]));
window.localStorage.setItem('unknownMassShiftList', JSON.stringify(unknownMassShiftList));
window.localStorage.setItem('precursorMass', JSON.stringify(precursorMass));
window.open("../inspect/spectrum.html");
}
}
/**
* Get the peaklist from respective spectrum.js to set the data for inspect page
* @param {object} ms2_data - json object with complete data spectrum for corresponding scan Id
*/
function getDataFromPRSMtoSpectralView(ms2_data){
let peakAndIntensity = [];
ms2_data.peaks.forEach(function(eachrow){
let tempObj = eachrow.mz + " " + eachrow.intensity;
peakAndIntensity.push(tempObj);
})
return peakAndIntensity;
}
/**
* Get the masslist from respective prsm.js to set the data for inspect page
* @param {Integer} specId - Contians spec Id to get the data of corrsponding mass list
*/
function getMassAndIntensityData(specId){
let massAndIntensityList = [];
prsm_data.prsm.ms.peaks.peak.forEach(function(eachPeak,i){
if (eachPeak.spec_id == specId) {
let tempObj = eachPeak.monoisotopic_mass + " "+eachPeak.intensity+ " "+eachPeak.charge;
massAndIntensityList.push(tempObj);
}
})
return massAndIntensityList;
}
/**
* Create HTML dropdown buttons based on the scan list
* @param {Array} scanIdList - Contains Scan id numbers
* @param {Array} specIdList - Contains Spec Id numbers
*/
function setDropDownItemsForInspectButton(scanIdList,specIdList){
let dropdown_menu = $(".dropdownscanlist .dropdown-menu");
let len = scanIdList.length;
for(let i=0; i<len;i++)
{
let value = scanIdList[i];
let specId = specIdList[i];
let id = "scan_"+ value ;
let a = document.createElement("a");
a.setAttribute("class","dropdown-item");
a.setAttribute("href","#!");
a.setAttribute("id",id);
a.setAttribute("value",value);
a.setAttribute("specid", specId);
a.innerHTML = "Scan "+value;
dropdown_menu.append(a);
}
}
/**
* Onclick function, invoked on click of the inspect scn button
*/
function onClickToInspect(){
$(".dropdownscanlist .dropdown-item ").click(function(e){
onclickTopView(e);
});
}
|
context('CEP', () => {
before(() => {
cy.visit('http://localhost:3000/form-cep')
})
it('should return cep', () => {
addressRequest()
cy.get('[data-testid="cep"]').type('01508010')
cy.wait('@resAddress')
cy.get('[data-testid="bairro"]').should('have.value', 'Jardim das rosas')
cy.get('[data-testid="logradouro"]').should('have.value', 'Rua Julieta')
})
})
const addressRequest = () => {
cy.server()
cy.route({
method: 'GET',
url: `https://viacep.com.br/ws/01508010/json`,
response: 'fixture:address.json'
}).as('resAddress')
}
|
import styled from "styled-components";
export const Container = styled.section`
grid-area: main;
justify-self: center;
align-self: center;
width: 90%;
height: 90%;
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 3rem;
padding-bottom: 5rem;
grid-template-areas:
"title title"
"image form"
"image form";
form {
grid-area: form;
width: 90%;
justify-self: center;
justify-content: space-evenly;
display: flex;
flex-direction: column;
}
`;
export const Field = styled.div`
display: flex;
flex-direction: column;
width: 100%;
`;
export const Image = styled.img`
grid-area: image;
width: 100%;
box-shadow: -10px 10px var(--green-50);
align-self: center;
`;
|
//Close navbar on click
$('.navbar-collapse a').click(function(){
$(".navbar-collapse").collapse('hide');
});
//Typing Text Animation
var text = "I'm Kathir.";
var textArr = text.split("");
var loopTimer;
var span = document.getElementById("type_text").innerHTML;
var message = "<span class='cursor-done'>|</span>";
function frameLooper(){
if (textArr.length> 0){
var nextChar = textArr.shift();
document.getElementById("type_text").innerHTML = message + nextChar + span;
message += nextChar;
} else {
setTimeout(() => {document.getElementById('type_text').innerHTML = message+"<span class='cursor-done'>|</span>"}, 10000);
clearTimeout(loopTimer);
return false;
}
loopTimer = setTimeout('frameLooper()', 100);
}
setTimeout('frameLooper()', 2000);
//Dimming Card When Hovering
const workItems = document.querySelectorAll('.card');
workItems.forEach(workItem => {
workItem.addEventListener('mouseover', () => {
workItem.childNodes[1].childNodes[0].classList.add('img-darken');
});
workItem.addEventListener('mouseout', () => {
workItem.childNodes[1].childNodes[0].classList.remove('img-darken');
});
})
//Email Popover
$(document).ready(function(){
$('[data-toggle="popover"]').popover();
});
//Keyboard animation
var playPause = anime({
targets: ['div.key', 'div.space', 'div.entershift', 'div.caps', 'div.tab', 'div.shift', 'div.backspace'],
translateY: [
{ value: 150, duration: 10000 },
{ value: 0, duration: 10000 }
],
rotate:{
value: '2turn',
easing: 'easeInOutQuad'
},
duration: 20000,
autoplay:true,
loop:true,
delay: function(el, i, l){ return i * 100},
});
jQuery(window).scroll(function() {
playPause.play;
});
|
$(document).ready(function () {
Metronic.init(); // init metronic core components
Layout.init(); // init current layout
QuickSidebar.init(); // init quick sidebar
/*Demo.init();*/ // init demo features
InitTouchspin();
//InitToastr();
InitDatePicker();
});
function InitDatePicker() {
$('.date-picker').datepicker({
rtl: Metronic.isRTL(),
orientation: "left",
autoclose: true,
format: 'dd/mm/yyyy',
});
}
function InitTouchspin() {
$(".touchspin_number").TouchSpin({
buttondown_class: 'btn defualt',
buttonup_class: 'btn defualt',
min: 0,
max: 1000000000,
stepinterval: 50,
maxboostedstep: 10000000
});
}
function loadingButton(btn) {
var $this = btn;
var btnText = $this.html();
$this.prop('disabled', true);
var loadingText = " <span class='fa fa-spinner fa-spin'></span> ";
$this.append(loadingText);
//if ($this.html() !== loadingText) {
// //$this.html(loadingText);
//}
}
function removeLoadingButton(btn) {
debugger;
var $this = btn;
$this.prop('disabled', false);
$this.children('span').remove();
}
function onFormBegin() {
loadingButton($('input[type="submit"],button[type="submit"],.submit'));
}
function showConfim(title,text,confirmText,closeText)
{
swal({
title: title,
text: text,
icon: "warning",
buttons: true,
dangerMode: true,
buttons: [closeText, confirmText],
})
.then((yes) => {
if (yes) {
return true;
} else {
return false;
}
});
}
function showFailDialog(title, text, closeText) {
var stringTohtml = document.createElement("div");
stringTohtml.innerHTML = text;
swal({
title: title,
content: stringTohtml,
icon: "error",
html: true,
buttons: {
close: {
text: closeText
}
}
});
removeLoadingButton($('input[type="submit"],button[type="submit"],.submit'));
}
function onFormComplete(data) {
removeLoadingButton($('input[type="submit"]>.fa-spinner,button[type="submit"]>.fa-spinner'));
removeLoadingButton($(".submit"));
if (data.success === true)
{
showResultDialog(successTitle, successText, successOkButton, returnUrl);
return;
}
if (data.responseJSON !== undefined || data.result === true || data === true) {
if (data.responseJSON && data.responseJSON.success === true) {
if (data.responseJSON.refNo) {
successText = data.responseJSON.refNo;
}
showResultDialog(successTitle, successText, successOkButton, returnUrl);
$(this).closest('form').find("input[type=text], textarea").val("");
$(this).closest('form').find("select").val("");
}
else {
if (data.responseJSON.ErrorsList) {
unsuccessText = data.responseJSON.ErrorsList.join(" \r\n ");
}
showFailDialog(unsuccessTitle, unsuccessText, unsuccessOkButton);
}
} else {
//error page
showFailDialog(unsuccessTitle, data.responseText, unsuccessOkButton);
}
}
function showResultDialog(title, text, closeText, returnUrl) {
swal({
title: title,
icon: "success",
html: text,
buttons: {
close: {
text: closeText
}
}
}).then((value) => {
window.location.href = returnUrl;
});
}
// cancel button function
function cancel() {
var cancelPage = returnUrl.trim();
window.open(cancelPage, "_self");
}
$('body').on('click', '.cancel-button', function () {
cancel();
});
function OperationError() {
showFailDialog(unsuccessTitle, unsuccessText, unsuccessOkButton);
}
function onDeleteComplete(data) {
debugger;
if (data && data.success === true) {
showDeleteSuccess(successDelete, '', successOkButton);
} else if (data && data.success === false) {
var unsuccessText = data.ErrorsList;
showFailDialog(unsuccessDelete, unsuccessText, unsuccessOkButton);
}
else {
showFailDialog(unsuccessDelete, data, unsuccessOkButton);
}
}
function showDeleteSuccess(title, text, closeText) {
swal({
title: title,
icon: "success",
html: text,
buttons: {
close: {
text: closeText
}
}
});
}
// common functions
function isNullOrUndefined(obj) {
return typeof obj === "undefined" || obj === null;
}
function isNullOrWhiteSpace(str) {
if (isNullOrUndefined(str))
return true;
if (typeof (str) !== 'string')
return true;
if (str.length == 0)
return true;
return false;
}
$('.prevent-paste').on("paste", function (e) {
e.preventDefault();
});
//attachments
$("#add-attachment").click(function () {
var templ = $("#attachmentTemplate").tmpl();
templ.attr('style', 'display:none;');
templ.appendTo("#attachment-template-container");
templ.show('fast', function () {
renameFileInputs();
});
});
$("#delete-attachment").click(function () {
var element = $(this);
loadingButton(element);
var fieldId = this.dataset["fieldid"];
$.ajax({
url: baseUrl + "/Attachment/DeleteAttachment",
type: 'post',
data: { fileId: fieldId },
dataType: 'json',
success: function (response) {
if (response.success) {
successNotification(successTitle, successOkButton);
window.location.reload();
}
removeLoadingButton(element);
},
fail: function () {
failNotificatiaon(unsuccessTitle, unsuccessOkButton);
removeLoadingButton(element);
}
});
});
function showAttachmentDeleteButton() {
$(".del-att").show();
}
var renameFileInputs = function () {
var index = 0;
$("#attachment-template-container .filebase").each(function (e) {
$(this).closest(".row").find(".filename").attr("name", "Attachments[" + index + "].FileDescription");
$(this).attr("name", "Attachments[" + index + "].File");
$('input[name="Attachments[' + index + '].File"]').uniform({
fileButtonHtml: "اختر ملف"
});
index++;
});
};
var removeFile = function (element) {
var element = $(element).closest(".row");
element.hide('fast', function () {
element.remove();
renameFileInputs();
handleSingleFileSelect();
});
}
function handleSingleFileSelect(element) {
let totalSize = 0;
$("input[type='file'].filebase").each(function () {
var file = this.files[0];
if (typeof (file) !== 'undefined') {
totalSize += parseInt(file.size);
}
});
var fileSizeTotalProp = $("#TotalFileSize")[0];
if (typeof (fileSizeTotalProp) !== 'undefined') {
$("#TotalFileSize + span.size").remove();
fileSizeTotalProp.value = totalSize;
$('<span class="size"> ( ' + bytesToSize(totalSize) + ' ) </span>').insertAfter(fileSizeTotalProp)
//raise change event
$(fileSizeTotalProp).change();
$(fileSizeTotalProp).blur();
}
if (typeof (element) === 'undefined')
return {}
var file = element.files[0];
if (typeof (file) === 'undefined')
return {}
return {
fileName: file.name,
fileType: file.type,
fileLastModifiedDate: file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() : 'n/a',
}
}
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Byte';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
|
import React, { Component } from "react";
import Header from "./Header";
import BannerInner from "./BannerInner";
import Navbar from "./Navbar";
import Footer from "./Footer";
import { Link } from "react-router-dom";
import { Redirect } from 'react-router-dom';
import axios from 'axios';
import Cookies from 'universal-cookie';
const cookies = new Cookies();
export default class Login extends Component {
constructor(){
super();
this.state ={
login: false,
userId: 0
};
}
componentWillMount(){
let jwtToken = cookies.get('jwtToken');
if (jwtToken !== undefined){
this.setState({
login: true
})
}
}
post(refs){
var self = this;
axios.post('http://localhost:3002/login', {
email: refs.email.value,
password: refs.password.value
}).then(function(response){
console.log(response);
if (response.data.success && response.data.token != undefined){
cookies.set('jwtToken', response.data.token, { path: '/' });
cookies.set('user_id', response.data.id, { path: '/' });
console.log(response.data.id)
self.setState({
userId: response.data.id,
login: true
})
this.state.login = true;
}
}).catch(function(err){
console.log(err);
});
}
render() {
if (this.state.login === true) {
return <Redirect to='/' />
}
return (
<div>
<Header />
<BannerInner />
<Navbar />
<section className="banner-bottom">
<div className="container">
<h3 className="tittle">Sign In Now</h3>
<div className="row inner-sec">
<div className="login p-5 bg-dark mx-auto mw-100">
<form action="#">
<div className="form-group">
<label htmlFor="exampleInputEmail1 mb-2">
Email address
</label>
<input
type="email"
className="form-control"
id="exampleInputEmail1"
aria-describedby="emailHelp"
ref="email"
placeholder
required
/>
<small id="emailHelp" className="form-text text-muted">
We'll never share your email with anyone else.
</small>
</div>
<div className="form-group">
<label htmlFor="exampleInputPassword1 mb-2">Password</label>
<input
type="password"
className="form-control"
id="exampleInputPassword1"
ref="password"
placeholder
required
/>
</div>
<div className="form-check mb-2">
<input
type="checkbox"
className="form-check-input"
id="exampleCheck1"
/>
<label className="form-check-label" htmlFor="exampleCheck1">
Check me out
</label>
</div>
<button input type="button" onClick={() => this.post(this.refs)} value="Sign In" className="btn btn-primary submit mb-4">
Sign In
</button>
<p>
<Link to="/register"> Don't have an account?</Link>
</p>
</form>
</div>
</div>
</div>
</section>
<Footer />
</div>
);
}
}
|
module.exports = {
development: {
use_env_variable: "DATABASE_URL"
},
test: {
username: "quickfit_adminFinder",
password: "HOO121p1364",
database: "quickfit_finder",
host: "decarie.web-dns1.com",
dialect: "mysql"
},
production: {
use_env_variable: "DATABASE_URL"
}
}
|
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
const set = new Set(A);
const size = set.size;
for(let i=1; i<=size; i++){
if(!set.has(i)){
return i;
}
continue;
}
return size+1;
}
|
import { useData } from "../context/DataContext";
const Blog = () => {
const { blog } = useData();
return (
<>
{blog.map((data) => {
return (
<a
key={data._id}
href={data.link}
className="rounded-lg w-[95%] sm:w-[90%] md:w-[620px] lg:w-[780px] xl:w-[880px] cursor-pointer bg-hLight dark:bg-hDark border-2 border-hLight dark:border-hDark duration-200 p-4 md:p-5"
target="_blank"
rel="noreferrer"
>
<p className=" flex justify-between items-center">
<span className="text-sm lg:text-[16px] font-medium">
Web Dev
</span>
<span className="text-xs">
{new Date(data.publishedAt).toLocaleString()}
</span>
</p>
<h3 className="truncate font-medium text-sm md:text[16px] lg:text-xl mt-3 mb-4 lg:mb-5 capitalize h-auto">
{data.title}
</h3>
<p className="text-xs lg:text-sm h-7 md:h-auto overflow-hidden">
{data.description}
</p>
</a>
);
})}
</>
);
};
export default Blog;
|
(function(){
'use strict';
angular.module('app')
.controller('TestsController', TestsController);
TestsController.$inject = ['$q', 'testDetailsService', 'questionsService', 'testService', 'subjectService', 'scheduleService', 'testPlayerService',
'loginService', '$state','$stateParams', '$uibModal', '$filter'];
function TestsController ($q, testDetailsService, questionsService, testService, subjectService, scheduleService,testPlayerService,
loginService, $state , $stateParams, $uibModal, $filter) {
var self = this;
//variables
self.status = ["Недоступно", "Доступно"];
self.currenSubjectName = '';
self.showMessageNoEntity = true;
self.group_id = $stateParams.groupId;
self.currentQuestionsId = [];
self.currentTestId = 0;
self.listOfEvents = [];
self.listOfTests = [];
self.currentTests = {};
self.checked;
self.user_id = 0;
self.current_date;
//methods
self.getTestBySubjectId = getTestBySubjectId;
self.getOneSubject = getOneSubject;
self.testPlayerPreparation = testPlayerPreparation;
activate();
function activate() {
isLogged();
getServerTime().then(getScheduleForGroup);
}
function getScheduleForGroup() {
return scheduleService.getScheduleForGroup(self.group_id).then(function (response) {
self.listOfEvents = response.data;
angular.forEach(self.listOfEvents, function (event) {
getOneSubject(event.subject_id).then(function (response) {
getTestBySubjectId(event.subject_id).then(function () {
angular.forEach(self.currentTests, function (test) {
var current_date = $filter('date')(self.current_date, 'yyyy-MM-dd');
if(test != 'no records') {
test.subject_name = response;
test.date = event.event_date;
test.date_enabled = test.date === current_date;
self.listOfTests.push(test);
self.showMessageNoEntity = false;
}
});
});
});
});
});
}
function getServerTime() {
return testPlayerService.getServerTime()
.then(function (response) {
self.current_date = response.data.unix_timestamp * 1000;
});
}
function getOneSubject(id) {
return subjectService.getOneSubject(id).then(function(response) {
return response.data[0].subject_name;
})
}
//this method return an array of tests for subject if they exist
function getTestBySubjectId(subjectId) {
return testService.getTestBySubjectId(subjectId).then(function(response) {
self.currentTests = response.data;
})
}
function isLogged() {
return loginService.isLogged().then(function(response) {
self.user_id = response.data.id;
});
}
function testPlayerPreparation(currentTest){
self.rateByLevels = [];
var rateByQuestionsId = [];
self.showMessageNotEnoughQuestion = true;
self.currentTestId = currentTest.test_id;
testPlayerService.checkAttemptsOfUser(self.user_id, currentTest)
.then(function(response) {
self.checked = response;
if(self.checked){
$uibModal.open({
templateUrl: 'app/modal/templates/no-more-attempts.html',
controller: 'modalController as modal',
backdrop: true
});
} else {
localStorage.setItem("currentTest", JSON.stringify(currentTest));
getTestDetailsByTest().then(function(response) {
// we'll use variable <rateByQuestionsId> for calculating summary score of the test after test has finished
angular.forEach(response, function(question) {
rateByQuestionsId[question.question_id] = self.rateByLevels[question.level]
});
var notEnoughQuestions = response.filter(function(question) {
return question.response === "Not enough number of questions for quiz";
});
var questionsId = response.map(function(question){
return {question_id: question.question_id, "answer_ids":[]};
});
if(notEnoughQuestions.length === 0 && response.length == currentTest.tasks) {
var endTime = new Date().valueOf()+ (currentTest.time_for_test * 60000);
localStorage.setItem("currentQuestionsId", angular.toJson(questionsId));
localStorage.setItem("endTime", angular.toJson(endTime));
testPlayerService.setServerEndTime(currentTest.time_for_test * 60000)
.then(function () {
testPlayerService.setRateOfQuestion(rateByQuestionsId);
});
testPlayerService.startTestInfoInLog(self.user_id,currentTest.test_id)
.then(function (response) {
if(response.data.response =="Error. User made test recently"){
$uibModal.open({
templateUrl: 'app/modal/templates/forbidden-time-reason.html',
controller: 'modalController as modal',
backdrop: true
})
}
else
{
testPlayerService.getServerTime()
.then(function (response) {
localStorage.setItem("startTime", angular.toJson(response.data.unix_timestamp));
});
$state.go("test", {questionIndex:0});
}
});
}
else {
$uibModal.open({
templateUrl: 'app/modal/templates/attention-noquestions-dialog.html',
controller: 'modalController as modal',
backdrop: true
});
}
})
}
});
}
function getTestDetailsByTest() {
return testDetailsService.getTestDetailsByTest(self.currentTestId).then(getTestDetailsByTestComplete)
}
function getTestDetailsByTestComplete(response) {
angular.forEach(response.data, function(testDetail) {
self.rateByLevels[testDetail.level] = testDetail.rate
});
var promises = response.data.map(function(testDetail) {
return questionsService.getQuestionsByLevelRand(self.currentTestId, testDetail.level, testDetail.tasks);
});
return $q.all(promises).then(
function(response) {
var questionsList = [];
angular.forEach(response, function (response) {
questionsList = questionsList.concat(response.data);
});
return questionsList;
},
function (response) {
return response
}
);
}
}
}());
|
/* eslint-disable camelcase */
var Promise = require('bluebird');
var Sequelize = require('sequelize');
var db = require('./_db');
var Hotel = require('./hotel');
var Restaurant = require('./restaurant');
var Activity = require('./activity');
var Day = db.define('day', {
number: {
type: Sequelize.INTEGER,
unique: true,
allowNull: false,
}
});
Day.hook('afterDestroy', (destroyedDay) => {
Day.findAll({
where: { number: { $gt: destroyedDay.number } }
})
.then(days => {
// return days.forEach(decrementBy1) // FIXME: remove if working without ti
return safeDecrementEachBy1(days)
})
.catch(console.error.bind(console))
})
Day.destroyById = function (id) { //FIXME: need to get this working
return Day.findById(id)
.then(day => {
const copy = JSON.parse(JSON.stringify(day))
day.destroy()
return copy
})
.catch(console.error.bind(console))
}
function decrementBy1 (day) {
const pre = day.number
// return day.decrement('number', { by: 1 }) //FIXME: original, keep this
return day.decrement('number', { by: 1 })
.then((day) => {
const post = day.number
console.log('Day ' + pre + ' is now ' + post);
})
.catch(console.error.bind(console))
}
function safeDecrementEachBy1 (days, idx) {
idx = idx || 0
if (idx >= days.length) return
return decrementBy1(days[ idx ])
.then(() => {
return safeDecrementEachBy1(days, idx + 1)
})
.catch(console.error.bind(console))
}
module.exports = Day;
|
$(document).ready(function() {
function a() {
$(".form_del_wan_redir").rpcform({
success: function(b) {
sbar.text("Redirection supprimée");
$(this).parent().parent().remove()
},
error: function(b) {
sbar.error(null, b.error)
}
})
}
a();
$("#redirs_list tbody").dynamiclist({
jsonrpc: {
method: "fw.wan_redirs_get"
},
ejs: {
url: "tpl/fw_wan_redir.ejs",
data: function(b) {
return {
v: b
}
}
},
key: "id",
jsonfield: function(b) {
return b
},
interval: 0
}).bind("dynamiclist.new", function() {
a()
});
$("#form_add_wan_redir").rpcform({
beforeSubmit: function(d, b) {
var c = b[0];
if (!check_ipv4(c.lan_ip.value)) {
sbar.error(null, "Adresse IP incorrecte");
return false
}
if (!check_port(c.wan_port.value)) {
sbar.error(null, "Port externe incorrect");
return false
}
if (!check_port(c.lan_port.value)) {
sbar.error(null, "Port interne incorrect");
return false
}
if (!check_ipv4_in_network(c.lan_ip.value, c.network.value, "255.255.255.0")) {
sbar.error(null, "L'adresse IP n'est pas dans votre réseau");
return false
}
if (c.comment.value.length > 63) {
sbar.error(null, "Commentaire trop long");
return false
}
return true
},
success: function(b) {
$(this).clearForm();
sbar.text("Redirection ajoutée");
$("#redirs_list tbody").dynamiclist("refresh")
},
error: function(b) {
sbar.error(null, b.error)
}
})
});
|
/*
* Copyright 2019 ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
/**
* Check that all of the things that can be voted on work.
*
*/
// var Web3 = require('web3');
// var web3 = new Web3();
const VotingAlgMajority = artifacts.require("./VotingAlgMajority.sol");
contract("Public Keys:", function (accounts) {
let common = require("./common");
const A_BLOCKCHAIN_ID =
"0x0000000000000000000000000000000000000000000000000000000000000002";
async function addBlockchain(coordInterface) {
await coordInterface.addBlockchain(
A_BLOCKCHAIN_ID,
(await VotingAlgMajority.deployed()).address,
common.VOTING_PERIOD
);
}
it("public key decode", async function () {
let coordInterface = await common.getNewCrosschainCoordination();
await addBlockchain(coordInterface);
let keyVersion = "1";
let targetOfVoteIsNone = "0";
await coordInterface.proposeVote(
A_BLOCKCHAIN_ID,
common.VOTE_CHANGE_PUBLIC_KEY,
targetOfVoteIsNone,
keyVersion,
common.PUBLIC_KEY
);
await common.mineBlocks(parseInt(common.VOTING_PERIOD));
let actionResult = await coordInterface.actionVotes(
A_BLOCKCHAIN_ID,
targetOfVoteIsNone
);
const result = await common.checkVotingResult(actionResult.logs);
assert.equal(true, result, "incorrect result reported in event");
let exists = await coordInterface.publicKeyExists(
A_BLOCKCHAIN_ID,
keyVersion
);
assert.equal(true, exists, "unexpectedly, the key is not in the contract.");
var { blockNumber, algorithm, key } = await coordInterface.getPublicKey(
A_BLOCKCHAIN_ID,
keyVersion
);
//console.log("block number: " + blockNumber);
//console.log("algorithm: " + algorithm);
//console.log("key: " + key);
// These values are decimal equivalents to the hexadecimal public key values in common.PUBLIC_KEY
assert.equal(
key[0],
"15708193363243225275616394410035962949243193317474330111734786682038951469099",
"key[0] incorrect"
);
assert.equal(
key[1],
"1188331353279655925534827725772442412689505989247595413767014200443655972901",
"key[1] incorrect"
);
assert.equal(
key[2],
"190304280072117358474082803523199131933615869822817420523710391421051176208",
"key[2] incorrect"
);
assert.equal(
key[3],
"17678420073345995323628877228661749409444380174258249952808734399169055452901",
"key[3] incorrect"
);
assert.equal(algorithm, "1", "Algorithm should be 1");
});
});
|
const mongoose = require('mongoose');
const aleTransactionsSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
walletAddress: {
type: String,
required: true
},
walletDestination: {
type: String,
required: true
},
count: {
type: Number,
required: true
},
timestamp: {
type: Number,
required: true
},
balanceInfo: {
before: Number,
after: Number
},
balanceInfoDest: {
before: Number,
after: Number
},
__v: {
type: Number,
select: false
}
});
module.exports = mongoose.model('Aletransactions', aleTransactionsSchema)
|
import React, { Component } from 'react'
import './index.css'
import TemplateSort from './TemplateSort'
export default class AccuratePhone extends Component {
constructor() {
super();
this.state = {
}
}
render() {
let {params,sortItemHandle,selectEditItem,selectItem} = this.props
let templateItems = params.template.templateItems
let templateId = params.template.id
let _DESCRIPTION = templateItems.find(v => v.code =='DESCRIPTION') //活动说明
let _H5_FORM_TITLE = templateItems.find(v => v.code =='H5_FORM_TITLE') //标题
let _SUBMIT = templateItems.find(v => v.code =='SUBMIT') //提交按钮
let _TERMS = templateItems.find(v => v.code == 'TERMS') //协议
return (
< div className="gi-accurate-step2-left" >
<h1 className="gi-accurate-step2-left-title">页面预览</h1>
<div className="gi-accurate-step2-left-content">
<div className='contentBox' style={{background: `url(${params.backgroundPicUrl}) no-repeat center/cover`}}>
<div className='contentBg'></div>
<div className='activityRule-row' >
{
//活动说明
_DESCRIPTION
?<div className={selectItem.code=='DESCRIPTION'?"shape-control shape-control-select":"shape-control"}>
<div className="activityRule" onClick={()=>{selectEditItem(_DESCRIPTION)}}>
{_DESCRIPTION.label}>
</div>
<div className="shape-control-rect shape-control-rect-left-top"></div>
<div className="shape-control-rect shape-control-rect-top"></div>
<div className="shape-control-rect shape-control-rect-right-top"></div>
<div className="shape-control-rect shape-control-rect-right"></div>
<div className="shape-control-rect shape-control-rect-right-bottom"></div>
<div className="shape-control-rect shape-control-rect-bottom"></div>
<div className="shape-control-rect shape-control-rect-left-bottom"></div>
<div className="shape-control-rect shape-control-rect-left"></div>
</div>
: ''
}
</div>
<div className="activityName-row">
{
//标题
_H5_FORM_TITLE
?<div className={selectItem.code=='H5_FORM_TITLE'?"shape-control shape-control-select":"shape-control"}>
<div className="activityName" style={eval('('+_H5_FORM_TITLE.css+')')} onClick={()=>{selectEditItem(_H5_FORM_TITLE)}}>
{_H5_FORM_TITLE.label}
</div>
<div className="shape-control-rect shape-control-rect-left-top"></div>
<div className="shape-control-rect shape-control-rect-top"></div>
<div className="shape-control-rect shape-control-rect-right-top"></div>
<div className="shape-control-rect shape-control-rect-right"></div>
<div className="shape-control-rect shape-control-rect-right-bottom"></div>
<div className="shape-control-rect shape-control-rect-bottom"></div>
<div className="shape-control-rect shape-control-rect-left-bottom"></div>
<div className="shape-control-rect shape-control-rect-left"></div>
</div>
:''
}
</div>
<TemplateSort templateId={templateId} templateItems={templateItems} clickHandle={(item)=>{selectEditItem(item)}} sortItemHandle={sortItemHandle} selectItem={selectItem}/>
<div className="row-agreement" >
{
//用户协议
_TERMS
?<div className={selectItem.code=='TERMS'?"shape-control shape-control-select":"shape-control"}>
<div style={{ display: 'flex', alignItems: 'center' }} onClick={()=>{selectEditItem(_TERMS)}}>
<span className='row-agreement-icon'></span>
{_TERMS.label}
</div>
<div className="shape-control-rect shape-control-rect-left-top"></div>
<div className="shape-control-rect shape-control-rect-top"></div>
<div className="shape-control-rect shape-control-rect-right-top"></div>
<div className="shape-control-rect shape-control-rect-right"></div>
<div className="shape-control-rect shape-control-rect-right-bottom"></div>
<div className="shape-control-rect shape-control-rect-bottom"></div>
<div className="shape-control-rect shape-control-rect-left-bottom"></div>
<div className="shape-control-rect shape-control-rect-left"></div>
</div>
: ''
}
</div>
{
// 提交按钮
_SUBMIT
?<div className="row-confirm" onClick={()=>{selectEditItem(_SUBMIT)}}>
<div className={selectItem.code=='SUBMIT'?"shape-control shape-control-select":"shape-control"}>
<div className='confrim' style={eval('('+_SUBMIT.css+')')}>
{_SUBMIT.label}
</div>
<div className="shape-control-rect shape-control-rect-left-top"></div>
<div className="shape-control-rect shape-control-rect-top"></div>
<div className="shape-control-rect shape-control-rect-right-top"></div>
<div className="shape-control-rect shape-control-rect-right"></div>
<div className="shape-control-rect shape-control-rect-right-bottom"></div>
<div className="shape-control-rect shape-control-rect-bottom"></div>
<div className="shape-control-rect shape-control-rect-left-bottom"></div>
<div className="shape-control-rect shape-control-rect-left"></div>
</div>
</div>
: ""
}
</div>
</div>
</div >
)
}
}
|
(function (){
const ENTER_KEY = 13;
const ESCAPE_KEY = 27;
const TAB_KEY = 9;
var util = {
uuid: function(){
var i, random;
var uuid = '';
for (i = 0; i < 32; i++){
random = Math.random() * 16 | 0;
if (i === 8 || i === 12 || i === 16 || i === 20){
uuid += '-';
}
uuid += (i === 12 ? 4 : (i === 16 ? (random & 3 | 8) : random)).toString(16);
}
return uuid;
},
store: function (namespace, data) {
if (arguments.length > 1) {
return localStorage.setItem(namespace, JSON.stringify(data));
} else {
var store = localStorage.getItem(namespace);
return (store && JSON.parse(store)) || [];
}
}
};
var App = {
init: function (){
this.todos = util.store('todos');
if (this.todos.length === 0){
this.todos.push({
uuid: util.uuid(),
title: '',
level: 0,
completed: false,
subTodos: []
});
}
this.render();
this.bindEvents();
},
render: function (){
var builtList;
if (document.getElementById('filter-toggle').checked){
builtList = this.buildActiveList(this.todos);
document.getElementById('app-container').innerHTML = builtList;
} else {
builtList = this.buildList(this.todos);
document.getElementById('app-container').innerHTML = '';
document.getElementById('app-container').innerHTML = builtList;
}
},
buildActiveList: function(array){
var ul = document.createElement('ul');
var todoLi;
var subTodos;
var completeClass = '';
var checked = '';
array.forEach(function (element){
if (!element.completed){
todoLi = document.createElement('li');
todoLi.setAttribute('data-id', element.uuid);
if (element.subTodos.length > 0){
subTodos = App.buildActiveList(element.subTodos);
} else {
subTodos = '';
}
todoLi.innerHTML = `<div>
<label class= "toggleCheckbox">
<input class= "toggle" type= "checkbox" ${checked}>
<span class= "checkmark"></span>
</label>
<button class= "delete">✕</button>
<input class= "edit ${completeClass}" value= "${element.title}">
</div>
${subTodos}`
ul.appendChild(todoLi);
}
});
return ul.outerHTML;
},
buildList: function(array){
var ul = document.createElement('ul');
var todoLi;
var subTodos;
var completeClass = '';
var checked = '';
array.forEach(function (element){
todoLi = document.createElement('li');
todoLi.setAttribute('data-id', element.uuid);
if (element.subTodos.length > 0){
subTodos = App.buildList(element.subTodos);
} else {
subTodos = '';
}
if (element.completed){
completeClass = 'complete';
checked = 'checked';
} else {
completeClass = '';
checked = '';
}
todoLi.innerHTML = `<div>
<label class= "toggleCheckbox">
<input class= "toggle" type= "checkbox" ${checked}>
<span class= "checkmark"></span>
</label>
<button class= "delete">✕</button>
<input class= "edit ${completeClass}" value= "${element.title}">
</div>
${subTodos}`
ul.appendChild(todoLi);
});
return ul.outerHTML;
},
getPrevElement: function(event){
var element = event.target;
var sourceTodo = this.getTodo(element, this.todos);
var prevElement = sourceTodo.array[sourceTodo.position - 1];
if (prevElement){
return prevElement
} else {
return null;
}
},
getParentElement: function(element, array){
var parentElement = element.closest('li').closest('ul').closest('li');
var parentTodo = this.getTodo(parentElement, array);
if (parentTodo){
return parentTodo;
} else {
return null;
}
},
createWithEnter: function(event){
var element = event.target;
var sourceTodo = this.getTodo(element, this.todos);
var uuid = util.uuid();
var val = element.value;
if (val){
sourceTodo.array.splice(sourceTodo.position + 1, 0, {
uuid: uuid,
title: '',
level: sourceTodo.todo.level,
completed: false,
subTodos: []
});
element.blur();
util.store('todos', this.todos);
this.render();
document.querySelector(`[data-id="${uuid}"]`).childNodes[0].getElementsByClassName('edit')[0].focus();
}
},
createSubWithTab: function(event){
this.update(event);
var prevElement = this.getPrevElement(event);
var element = event.target;
var sourceTodo = this.getTodo(element, this.todos);
var movedTodo;
if (prevElement) {
sourceTodo.todo.level = prevElement.level + 1;
movedTodo = JSON.parse(JSON.stringify(sourceTodo.todo));
this.destroyWithButton(event);
prevElement.subTodos.push(movedTodo);
var uuid = prevElement.subTodos[prevElement.subTodos.indexOf(movedTodo)].uuid;
util.store('todos', this.todos);
this.render();
var input = document.querySelector(`[data-id="${uuid}"]`).childNodes[0].getElementsByClassName('edit')[0];
input.focus();
var temp = input.value;
input.value = '';
input.value = temp;
}
},
promoteTask: function(event){
this.update(event);
var element = event.target;
var sourceTodo = this.getTodo(element, this.todos);
var parentTodo = this.getParentElement(element, this.todos)
var movedTodo;
if (parentTodo){
sourceTodo.todo.level = parentTodo.todo.level;
movedTodo = JSON.parse(JSON.stringify(sourceTodo.todo));
this.destroyWithButton(event);
parentTodo.array.splice(parentTodo.position + 1, 0, movedTodo);
var uuid = parentTodo.array[parentTodo.array.indexOf(movedTodo)].uuid;
util.store('todos', this.todos);
this.render();
var input = document.querySelector(`[data-id="${uuid}"]`).childNodes[0].getElementsByClassName('edit')[0];
input.focus();
var temp = input.value;
input.value = '';
input.value = temp;
}
},
update: function(event){
var element = event.target;
var sourceTodo = this.getTodo(element, this.todos);
if (sourceTodo){
var uuid = sourceTodo.todo.uuid;
if (element.getAttribute('abort') == 'true'){
if (element.value.trim()){
element.value = sourceTodo.todo.title;
element.setAttribute('abort', false);
element.focus();
} else {
this.destroyWithButton(event);
}
} else {
if (element.value.trim()){
sourceTodo.array[sourceTodo.position].title = element.value.trim();
this.render();
}
}
}
},
editKeyUp: function(event){
if (event.which === ENTER_KEY){
this.createWithEnter(event);
}
if (event.which === TAB_KEY){
if (event.shiftKey){
event.preventDefault();
this.promoteTask(event);
} else {
event.preventDefault();
this.createSubWithTab(event);
}
}
if (event.which === ESCAPE_KEY){
event.target.setAttribute('abort', true);
this.update(event);
}
},
getTodo: function (element, array){
if (element){
var id = element.closest('li').getAttribute('data-id');
for (var i = 0; i < array.length; i++){
if (array[i].uuid === id){
return {
todo: array[i],
position: i,
array: array
}
} else {
if (array[i].subTodos.length > 0){
var foundInSubTodo = this.getTodo(element, array[i].subTodos);
if (foundInSubTodo){
return foundInSubTodo;
}
}
}
}
} else {
return null;
}
},
bindEvents: function(){
document.getElementById('app-container').addEventListener('keydown', function(event){
this.editKeyUp.call(this, event);
}.bind(this));
document.getElementById('app-container').addEventListener('focusout', function(event){
if (event.target.classList.contains('edit')){
this.update.call(this, event);
}
}.bind(this));
document.getElementById('app-container').addEventListener('click', function(event){
if (event.target.classList.contains('delete')){
this.destroyWithButton.call(this, event);
}
if (event.target.classList.contains('toggle')){
this.toggleComplete.call(this, event);
}
}.bind(this));
document.getElementById('filter-toggle').addEventListener('change', function(){
this.render(this.todos);
}.bind(this));
},
destroyWithButton: function(event){
var element = event.target;
var sourceTodo = this.getTodo(element, this.todos);
sourceTodo.array.splice(sourceTodo.position, 1);
util.store('todos', this.todos);
this.render();
},
toggleComplete: function (event, array, completedBool){
if (arguments.length === 1){
var element = event.target;
var sourceTodo = this.getTodo(element, this.todos);
completedBool = !sourceTodo.array[sourceTodo.position].completed;
sourceTodo.array[sourceTodo.position].completed = completedBool;
if (sourceTodo.array[sourceTodo.position].subTodos.length > 0){
this.toggleComplete(event, sourceTodo.array[sourceTodo.position].subTodos, completedBool);
}
} else {
for (var i = 0; i < array.length; i++){
array[i].completed = completedBool;
if (array[i].subTodos.length > 0){
this.toggleComplete(event, array[i].subTodos, completedBool);
}
}
}
this.render();
}
}
App.init();
})();
|
import React, {Component} from 'react';
import {Tooltip} from 'reactstrap';
import Highlighter from 'react-highlight-words'
class TooltipItem extends Component {
constructor(props){
super(props);
this.state = {
tooltipOpen: false
};
}
toggle() {
this.setState({
tooltipOpen: !this.state.tooltipOpen,
});
}
_getTooltipData(){
const keys = Object.keys(this.props.option);
return keys.map((key,index) => {
let data ="";
const property = this.props.option[key];
if (Array.isArray(property)){
data = property.length.toString();
data += (property.length === 1)? ' record': ' records'
} else{
data = JSON.stringify(property);
}
return (<div key={index}><b>{key}: </b> {data} </div>)
});
}
render() {
return (
<div id={'Tooltip-' + this.props.id} className={"result-item"} onClick={this.props.onClick} >
<Highlighter
highlightClassName='highlighted'
searchWords={[this.props.searchString]}
autoEscape={false}
textToHighlight={this.props.label}
highlightTag={"span"}
/>
{this.props.hoverActive &&
<Tooltip innerClassName={"VirtualizedTreeSelectTooltip"}
style={{left: "400px!important"}}
placement={'left'} isOpen={this.state.tooltipOpen}
target={'Tooltip-' + this.props.id} autohide={false}
toggle={() => this.toggle()} delay={{"show": 300, "hide": 0}}
modifiers={{
preventOverflow: {
escapeWithReference: false,
},
}}
>
{this._getTooltipData()}
</Tooltip>
}
</div>
);
}
}
export default TooltipItem;
|
import React, { useState } from 'react'
import { useAuth } from "../contexts/AuthContext"
import { Link, useHistory } from "react-router-dom"
import Button from "@material-ui/core/Button";
import { createStyles, makeStyles, Theme } from "@material-ui/core/styles";
const useStyles = makeStyles((theme: Theme) =>
createStyles({
container: {
display: "flex",
flexWrap: "wrap",
width: 400,
margin: `${theme.spacing(0)} auto`
},
logoutBtn: {
margin: theme.spacing(2),
flexGrow: 1
},
header: {
textAlign: "center",
background: "#212121",
color: "#fff"
},
card: {
marginTop: theme.spacing(10)
}
})
);
const Dashboard = () => {
const classes = useStyles();
const [error, setError] = useState("")
const { currentUser, logout } = useAuth()
const history = useHistory()
async function handleLogout() {
setError("")
try {
await logout()
history.push("/")
} catch {
setError("Failed to log out")
}
}
return (
<div>
Dashboard
テスト用のリンク(あとで治す)
{error && <div style={{ color: "red" }}>{error}</div>}
<div>
<strong>Email:</strong> {currentUser.email}
</div>
<div>
<strong>ハンドル名:</strong> {currentUser.displayName}
</div>
<h2>
<Link to="/UpdateProfile">UpdateProfile</Link>
</h2>
<h2>
<Link to="/upLoadTest">upLoadTest</Link>
</h2>
<h2>
<Link to="/chat/index">chat</Link>
</h2>
<div>
<Button
variant="contained"
size="large"
color="secondary"
className={classes.logoutBtn}
onClick={handleLogout}
>
Logout
</Button>
</div>
</div>
)
}
export default Dashboard
|
import { DeviceEventEmitter } from 'react-native';
import MusicControl from 'react-native-music-control';
import { search, streamUrl } from './soundcloudHelper';
export const playingGenre = (genre) => ({
type: 'PLAYING_GENRE',
genre
});
export const playGenre = (genre) => {
return function (dispatch) {
dispatch(playingGenre(genre));
search(genre.name)
.then(result => {
dispatch(foundSongs(result.collection, genre));
dispatch(setCurrentSong(0));
dispatch(playCurrentSong());
});
}
};
export const foundSongs = (songs, genre) => ({
type: 'FOUND_SONGS',
songs,
genre
});
export const setCurrentSong = (index) => ({
type: 'SET_CURRENT_SONG',
index
});
export const playCurrentSong = () => {
return function (dispatch, getState) {
const { songs, currentlyPlaying } = getState();
let song = null;
if (currentlyPlaying.genre && currentlyPlaying.songIndex >= 0) {
if (songs[currentlyPlaying.genre.id]) {
song = songs[currentlyPlaying.genre.id][currentlyPlaying.songIndex];
}
}
MusicControl.enableControl('seekForward', false);
MusicControl.enableControl('seekBackward', false);
MusicControl.enableControl('skipForward', false);
MusicControl.enableControl('skipBackward', false);
MusicControl.enableBackgroundMode(true);
MusicControl.on('play', () => dispatch(playCurrentSong()));
MusicControl.on('pause', () => dispatch(pauseCurrentSong()));
MusicControl.on('nextTrack', () => dispatch(playNextSong()));
MusicControl.on('previousTrack', () => dispatch(playPreviousSong()));
if (song) {
MusicControl.setNowPlaying({
title: song.title || "",
artwork: song.artwork_url || "",
artist: song.user.username || "",
genre: song.genre || "",
duration: song.duration/1000,
description: song.description || "",
color: 0xFFFFFFF,
date: song.created_at,
rating: true
});
MusicControl.updatePlayback({
state: MusicControl.STATE_PLAYING
});
}
dispatch(_updatePaused(false));
}
};
export const pauseCurrentSong = () => {
return function (dispatch) {
MusicControl.updatePlayback({
state: MusicControl.STATE_PAUSED
});
dispatch(_updatePaused(true));
}
};
const _updatePaused = (paused) => ({
type: 'UPDATE_PAUSED',
paused
});
export const playNextSong = () => {
return function (dispatch, getState) {
const { songIndex, genre } = getState().currentlyPlaying,
songs = getState().songs[genre.id];
dispatch(setCurrentSong((songIndex+1)%songs.length));
dispatch(playCurrentSong());
}
};
export const playPreviousSong = () => {
return function (dispatch, getState) {
const { songIndex } = getState().currentlyPlaying,
newIndex = songIndex - 1;
dispatch(setCurrentSong(newIndex < 0 ? 0 : newIndex));
dispatch(playCurrentSong());
}
}
export const updatePlayTime = (currentTime) => {
return function (dispatch) {
MusicControl.updatePlayback({
state: MusicControl.STATE_PLAYING,
elapsedTime: currentTime
});
dispatch(_setPlayTime(currentTime));
}
}
const _setPlayTime = (currentTime) => ({
type: 'SET_PLAY_TIME',
currentTime
});
|
// node genOPDS.js idpf_samples.opds IDPF epub3-samples master 30
// node genOPDS.js epub_testsuite.opds IDPF epub-testsuite master content/30
// node genOPDS.js epub_tests_a11y.opds daisy epub-accessibility-tests master content
var fs = require('fs');
var path = require('path');
//var http = require('http');
var https = require('https');
var parseString = require('xml2js').parseString;
// var git = require('gift');
// var glob = require('glob');
// var exec = require('child_process').exec;
// fs.existsSync is marked as deprecated, so accessSync is used instead (if it's available in the running version of Node).
function doesFileExist(path) {
var exists;
if (fs.accessSync) {
try {
fs.accessSync(path);
exists = true;
} catch (ex) {
exists = false;
}
} else {
exists = fs.existsSync(path);
}
return exists;
}
function escapeMarkupEntitiesInUrl(url) {
return url
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
var datetime = new Date().toISOString();
//2016-02-12T00:00:00Z
//https://github.com/blog/1509-personal-api-tokens
//https://github.com/settings/tokens
//var ACCESSTOKEN = "fb424e90e36242ab9603034ea906a070c9ce2646";
var USERAGENT = "Readium-GitHub";
var args = process.argv.splice(2);
var browserURL = "https://github.com/"+args[1]+"/"+args[2]+"/tree/"+args[3]+args[4];
console.log("=== gen OPDS [" + args[0] + "] from [" + browserURL + "] ...");
var rootPath = process.cwd();
console.log(rootPath);
var opdsPath = path.join(rootPath, args[0]);
console.log(opdsPath);
if (doesFileExist(opdsPath)) {
//console.log("~~ delete: " + opdsPath);
//fs.unlinkSync(opdsPath);
// var opdsXml = fs.readFileSync(opdsPath, 'utf8');
// fs.writeFileSync(opdsPath, opdsXml, 'utf8');
}
var opdsXml = "";
if (!args[5] || args[5] === "FIRST") {
opdsXml += '<feed xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:odl="http://opds-spec.org/odl" xml:lang="en" xmlns:dcterms="http://purl.org/dc/terms/" xmlns="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:opds="http://opds-spec.org/2010/catalog">';
opdsXml += '\n';
opdsXml += '<updated>'+datetime+'</updated>';
opdsXml += '\n';
opdsXml += '<id>READIUM_OPDS_'+browserURL.replace(/[\/:]/g,"_")+'</id>';
opdsXml += '\n';
opdsXml += '<title>Readium CloudReader OPDS feed for [ '+browserURL+' ]</title>';
opdsXml += '\n';
opdsXml += '<link rel="self" href="'+args[0]+'" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>';
opdsXml += '\n';
opdsXml += '<link rel="start" href="'+args[0]+'" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>';
opdsXml += '\n';
opdsXml += '\n';
}
var processListItem = function(list, i) {
if (i >= list.length) {
if (!args[5] || args[5] === "LAST") {
opdsXml += '</feed>';
opdsXml += '\n';
}
if (args[5] === "APPEND" || args[5] === "LAST") {
fs.appendFileSync(opdsPath, opdsXml, 'utf8');
} else {
fs.writeFileSync(opdsPath, opdsXml, 'utf8');
}
return;
}
var listItem = list[i];
if (listItem.type !== "dir") {
console.log("Skipping non-directory path: " + listItem.path);
processListItem(list, ++i);
return;
}
console.log(listItem.path);
var urlContainerXmlPath = "/"+args[1]+"/"+args[2]+"/"+args[3]+"/"+listItem.path+"/META-INF/container.xml";
var urlContainerXml = {
hostname: 'raw.githubusercontent.com',
port: 443,
path: urlContainerXmlPath,
method: 'GET',
headers: {
"User-Agent": USERAGENT
}
};
console.log("https://" + urlContainerXml.hostname + urlContainerXml.path);
https.get(urlContainerXml, function(response) {
// console.log("statusCode: ", response.statusCode);
// console.log("headers: ", response.headers);
response.setEncoding('utf8');
response.on('error', function(error) {
console.log("ERROR container XML: " + error);
processListItem(list, ++i);
});
var allData = ''
response.on('data', function(data) {
allData += data;
});
response.on('end', function() {
//console.log(allData);
if (response.statusCode !== 200) {
console.log("ERROR container XML HTTP: " + response.statusCode);
console.log(response.statusMessage);
processListItem(list, ++i);
return;
}
var regexp = /full-path="([^"]+)"/g;
var match = allData.match(regexp);
if (!match) {
console.log("ERROR container XML rootfile full-path.");
processListItem(list, ++i);
return;
}
if (match.length) {
//console.log(match);
var opfPath = match[0].replace(regexp, "$1");
console.log(opfPath);
var urlOpfPath = "/"+args[1]+"/"+args[2]+"/"+args[3]+"/"+listItem.path+"/"+opfPath;
var urlOpf = {
hostname: 'raw.githubusercontent.com',
port: 443,
path: urlOpfPath,
method: 'GET',
headers: {
"User-Agent": USERAGENT
}
};
console.log("https://" + urlOpf.hostname + urlOpf.path);
https.get(urlOpf, function(response) {
// console.log("statusCode: ", response.statusCode);
// console.log("headers: ", response.headers);
response.setEncoding('utf8');
response.on('error', function(error) {
console.log("ERROR package OPF: " + error);
processListItem(list, ++i);
});
var allData = ''
response.on('data', function(data) {
allData += data;
});
response.on('end', function() {
//console.log(allData);
if (response.statusCode !== 200) {
console.log("ERROR package OPF HTTP: " + response.statusCode);
console.log(response.statusMessage);
processListItem(list, ++i);
return;
}
parseString(allData,
{ explicitArray: false, ignoreAttrs: false },
function (err, json) {
if (err) {
console.log("ERROR package OPF parseXML: " + err);
console.log(json);
console.log(allData);
processListItem(list, ++i);
return;
}
var coverHref = undefined;
var bookTitle = undefined;
var _package = undefined;
if (json) {
_package = json.package;
if (!_package) {
_package = json["opf:package"];
}
}
if (_package) {
var coverID = undefined;
var _metadata = _package.metadata;
if (!_metadata) {
_metadata = _package["opf:metadata"];
}
if (_metadata) {
var _meta = _metadata.meta;
if (!_meta) {
_meta = _metadata["opf:meta"];
}
if (_meta) {
var metas = Array.isArray(_meta) ? _meta : [_meta];
for (var j = 0; j < metas.length; j++) {
var meta = metas[j];
for (var key in meta.$) {
// console.log(key);
// console.log(meta.$[key]);
if (key === "name" && meta.$[key] === "cover") {
var id = meta.$["content"];
if (id) {
coverID = id;
break;
}
}
}
if (coverID) break;
}
}
if (_metadata["dc:title"]) {
var titles = Array.isArray(_metadata["dc:title"]) ? _metadata["dc:title"] : [_metadata["dc:title"]];
for (var j = 0; j < titles.length; j++) {
var title = titles[j];
bookTitle = title._ ? title._ : title;
console.log("==========> TITLE: " + bookTitle);
break;
}
}
}
var _manifest = _package.manifest;
if (!_manifest) {
_manifest = _package["opf:manifest"];
}
var _manifestItem = undefined;
if (_manifest) {
_manifestItem = _manifest.item;
if (!_manifestItem) {
_manifestItem = _manifest["opf:item"];
}
}
if (_manifestItem) {
var items = Array.isArray(_manifestItem) ? _manifestItem : [_manifestItem];
for (var j = 0; j < items.length; j++) {
var item = items[j];
var href = undefined;
var match = false;
for (var key in item.$) {
// console.log(key);
// console.log(meta.$[key]);
if (coverID && key === "id" && item.$[key] === coverID) {
match = true;
if (href) {
coverHref = href;
break;
}
}
if (!coverID && key === "properties" && item.$[key].indexOf("cover-image") >= 0) {
match = true;
if (href) {
coverHref = href;
break;
}
}
if (key === "href") {
href = item.$[key];
if (match) {
coverHref = href;
break;
}
}
}
if (coverHref) break;
}
if (coverHref) {
console.log("==========> COVER: " + coverHref);
}
}
}
if (!bookTitle) {
console.log("==========> NO TITLE ?!");
}
opdsXml += '<entry>';
opdsXml += '\n';
opdsXml += '<title>' + escapeMarkupEntitiesInUrl(bookTitle) + '</title>';
opdsXml += '\n';
opdsXml += '<author>';
opdsXml += '\n';
var entryName = args[1]+"/"+args[2]+" ("+args[3]+") - "+ listItem.path;
opdsXml += ' <name>' + escapeMarkupEntitiesInUrl(entryName) + '</name>';
opdsXml += '\n';
opdsXml += '</author>';
opdsXml += '\n';
var fullUrl = 'https://cdn.statically.io/gh/'+args[1]+'/'+args[2]+'/'+args[3]+'/'+listItem.path;
var escapedURL = encodeURI(escapeMarkupEntitiesInUrl(fullUrl));
opdsXml += '<link type="application/epub" href="'+escapedURL+'" rel="http://opds-spec.org/acquisition"/>';
opdsXml += '\n';
if (coverHref) {
var contentType = "image/jpeg";
var coverHref_low = coverHref.toLowerCase();
if (coverHref_low.indexOf(".png") == (coverHref_low.length-4)) {
contentType = "image/png";
}
else if (coverHref_low.indexOf(".gif") == (coverHref_low.length-4)) {
contentType = "image/gif";
}
else if (coverHref_low.indexOf(".jpg") == (coverHref_low.length-4)) {
contentType = "image/jpg";
}
var coverUrl = fullUrl + "/" + opfPath + "/../" + coverHref;
opdsXml += '<link type="'+contentType+'" href="'+encodeURI(escapeMarkupEntitiesInUrl(coverUrl))+'" rel="http://opds-spec.org/image/thumbnail"/>';
opdsXml += '\n';
}
opdsXml += '<updated>'+datetime+'</updated>';
opdsXml += '\n';
opdsXml += '<id>READIUM_OPDS_'+escapedURL.replace(/[\/:]/g,"_")+'</id>';
opdsXml += '\n';
opdsXml += '</entry>';
opdsXml += '\n';
processListItem(list, ++i);
}); //parseString
});
});
}
});
});
};
var urlPath = "/repos/"+args[1]+"/"+args[2]+"/contents"+args[4]+"?ref="+args[3];
var url = {
hostname: 'api.github.com',
port: 443,
path: urlPath,
method: 'GET',
headers: {
"User-Agent": USERAGENT
}
};
console.log("https://" + url.hostname + url.path);
https.get(url, function(response) {
// console.log("statusCode: ", response.statusCode);
// console.log("headers: ", response.headers);
response.setEncoding('utf8');
response.on('error', function(error) {
console.log(error);
});
var allData = ''
response.on('data', function(data) {
allData += data;
});
response.on('end', function() {
//console.log(allData);
var list = JSON.parse(allData);
if (list.length) {
processListItem(list, 0);
}
});
});
|
import { connect } from "react-redux";
import Board from "./Board";
import { bindActionCreators } from "redux";
import { addNote } from "../../actions/board";
const mapStateToProps = ({ board }) => ({
notes: board.notes,
selectedNotes: board.selectedNotes
});
const mapDispatchToProps = dispatch => ({
actions: bindActionCreators({ addNote }, dispatch)
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Board);
|
import React, {Component} from 'react';
import {getColumnsforSorting} from '../common/tableUtil';
import {filter, sort} from '../common/tableUtil';
import {getInitialData} from '../actions/tableActions';
import { connect } from "react-redux"
class ActionsComponent extends Component
{
constructor(props)
{
super(props);
this.state={
searchStr:"",
sortOrder:"ASC",
sortColumn:"gender"
}
this.handleSearch=this.handleSearch.bind(this);
this.handleSortColumn=this.handleSortColumn.bind(this);
this.handleSortOrder=this.handleSortOrder.bind(this);
}
componentWillMount()
{
getInitialData();
}
componentWillReceiveProps(nextProps)
{
this.initialData=nextProps.initialData;
// alert("iniital"+nextProps.initialData.length)
// let data=nextProps.initialData;
// let newData=[];
// data.map((item, index)=>{
// let obj={};
// obj.SLNo=index+1;
// obj.picture=item.picture.thumbnail;
// obj.name={};
// obj.name.first=item.name.first;
// obj.name.last=item.name.last;
// obj.gender=item.gender;
// obj.address={};
// obj.address.street=item.location.street;
// obj.address.city=item.location.city;
// obj.address.state=item.location.state;
// obj.address.postcode=item.location.postcode;
// obj.email=item.email;
// obj.phone=item.phone;
// newData.push(obj);
// })
// console.log("NewData"+JSON.stringify(newData))
}
handleSearch(event)
{
this.setState({searchStr:event.target.value});
filter(this.initialData, event.target.value);
}
handleSortColumn(event)
{
this.setState({sortColumn:event.target.value})
sort(this.initialData, event.target.value, this.state.sortOrder);
}
handleSortOrder(event)
{
this.setState({sortOrder:event.target.value})
sort(this.initialData, this.state.sortColumn, event.target.value);
}
render()
{
let obj={};
if(this.initialData!=undefined)
obj=this.initialData[0];
let sortColumns=getColumnsforSorting(obj)
return(<div className="table-actions row">
<div className="search-action">
<span>Search:</span>
<input type="text" value={this.state.searchStr} onChange={this.handleSearch}/>
</div>
<div className="sort-action">
<span>Sort:</span>
<select onChange={this.handleSortColumn}>
{sortColumns}
</select>
<select onChange={this.handleSortOrder}>
<option>ASC</option>
<option>DESC</option>
</select>
</div>
</div>)
}
}
export default connect(state => (
{
initialData: state.tableReducer.initialData
}
))(ActionsComponent);
|
/**
* Course: COMP 426
* Assignment: a04
* Author: <type your name here>
*
* This script uses jQuery to build an HTML page with content taken from the
* data defined in data.js.
*/
/**
* Given a hero object (see data.js), this function generates a "card" showing
* the hero's name, information, and colors.
* @param hero A hero object (see data.js)
*/
export const renderHeroCard = function(hero) {
// TODO: Generate HTML elements to represent the hero
// TODO: Return these elements as a string, HTMLElement, or jQuery object
// Example: return `<div>${hero.name}</div>`;
var create_hero = `
<div class="card">
<div class="hero" style="height: 100%; background-color: ${hero.backgroundColor}">
<div class="container">
<figure class="image is-110x110">
<img src=${hero.img} alt=${hero.name}>
</figure>
<div class="description">
<p class="title has-text-weight-bold has-text-centered" style="color: ${hero.color}">${hero.name}</p>
<p class="subtitle has-text-grey has-text-weight-bold has-text-centered" style="color: ${hero.color}"> ${hero.first + ' ' + hero.last}</p>
<div class="content has-text-centered" style="color: ${hero.color}"; overflow-y: scroll">
<span>${hero.firstSeen.getMonth() + '/19' + hero.firstSeen.getYear()}</span>
<p>${hero.description}</p>
</div>
<button class="button is-dark">Edit</button>
</div>
</div>
</div>
</div>`
return create_hero;
};
/**
* Given a hero object, this function generates a <form> which allows the
* user to edit the fields of the hero. The form inputs should be
* pre-populated with the initial values of the hero.
* @param hero The hero object to edit (see data.js)
*/
export const renderHeroEditForm = function(hero) {
// TODO: Generate HTML elements to represent the hero edit form
// TODO: Return these elements as a string, HTMLElement, or jQuery object
// Example: return `<form>${hero.name}</form>`;
return `
<div class="modal-content">
<div class="modal-card">
<header class="modal-card-head">
<p class="modal-card-title has-text-weight-bold has-text-centered">Edit Hero: ${hero.name}</p>
</header>
<section class="modal-card-body">
<form>
<div class="field">
<label class="label">Hero Name</label>
<div class="control">
<input class="input" type="text" value="${hero.name}">
</div>
</div>
<div class="field">
<label class="label">First Name</label>
<div class="control">
<input class="input" type="text" value="${hero.first}">
</div>
</div>
<div class="field">
<label class="label">Last Name</label>
<div class="control">
<input class="input" type="text" value="${hero.last}">
</div>
</div>
<div class="field">
<label class="label">Description</label>
<div class="control">
<textarea class="textarea">${hero.description}</textarea>
</div>
</div>
<div class="field">
<label class="label">First Seen</label>
<div class="control">
<input class="input" type="date" value="19${hero.firstSeen.getYear()}-0${hero.firstSeen.getMonth()}-01" min="1900-01-01" max="3000-12-31">
</div>
</div>
<footer class="modal-card-foot">
<button class="button is-dark" type="submit">Save</button>
<button class="button">Cancel</button>
</footer>
</form>
</section>
</div>
</div>
`
};
/**
* Given an array of hero objects, this function converts the data into HTML and
* loads it into the DOM.
* @param heroes An array of hero objects to load (see data.js)
*/
export const loadHeroesIntoDOM = function(heroes) {
// Grab a jQuery reference to the root HTML element
const $root = $('#root');
// TODO: Generate the heroes using renderHeroCard()
let herocards = $('<div class="columns is-multiline is-centered" />')
for (let i=0; i<heroes.length; i++) {
herocards.append(renderHeroCard(heroes[i]));
}
$root.addClass('container hero is-dark is-fullheight').append(herocards);
// TODO: Append the hero cards to the $root element
// Pick a hero from the list at random
const randomHero = heroes[Math.floor(Math.random() * heroes.length)];
// TODO: Generate the hero edit form using renderHeroEditForm()
var edithero = renderHeroEditForm(randomHero);
// TODO: Append the hero edit form to the $root element
$root.append(edithero);
};
/**
* Use jQuery to execute the loadHeroesIntoDOM function after the page loads
*/
$(function() {
loadHeroesIntoDOM(heroicData);
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.