text
stringlengths 7
3.69M
|
|---|
let express = require('express');
let router = express.Router();
let auth = require('../middleWare/auth');
let models = require('../models');
let multer = require('multer');
var storage = multer.diskStorage({
// 目标路径
destination: function (req, file, cb) {
cb(null, 'public/uploads')
},
//文件名
filename: function (req, file, cb) {
console.log(file);
cb(null,Date.now() + '.' + (file.mimetype.slice(file.mimetype.indexOf('/')+1)));
}
});
var upload = multer({ storage: storage });
router.get('/port',auth.checkLogin, function(req, res, next){
res.render('./article/add',{title: '发表文章'});
});
router.post('/add',auth.checkLogin, upload.single('poster'), function(req,res,next){
let article = req.body;
if (req.file){
article.poster = '/uploads/'+req.file.filename;
}
//把当前登录用户的id赋给user
article.user = req.session.user._id;
models.Article.create(article,function(err,doc){
if (err) {
req.flash('error', '文章发表失败');
} else {
req.flash('success', '文章发表成功');
res.redirect('/');
}
});
});
module.exports = router;
|
/*
* moleculer-cli
* Copyright (c) 2018 MoleculerJS (https://github.com/moleculerjs/moleculer-cli)
* MIT Licensed
*/
const Moleculer = require("moleculer");
/**
* Yargs command
*/
module.exports = {
command: ["start", "*"],
describe: "Start a Moleculer broker locally",
builder(yargs) {
yargs.options({
"ns": {
default: "",
describe: "Namespace",
type: "string"
},
"id": {
default: null,
describe: "NodeID",
type: "string"
},
"metrics": {
alias: "m",
default: false,
describe: "Enable metrics",
type: "boolean"
},
"hot": {
alias: "h",
default: false,
describe: "Enable hot-reload",
type: "boolean"
},
"cb": {
default: false,
describe: "Enable circuit breaker",
type: "boolean"
}
});
},
handler(opts) {
const broker = new Moleculer.ServiceBroker({
namespace: opts.ns,
nodeID: opts.id || null,
transporter: null,
logger: console,
logLevel: "info",
validation: true,
statistics: true,
metrics: opts.metrics,
hotReload: opts.hot,
circuitBreaker: {
enabled: opts.cb
}
});
broker.start().then(() => broker.repl());
}
};
|
function AsyncGetData (label) {
return new Promise(resolve => {
setTimeout(() => {
let output = extra_large_items.filter(obj => {
return obj.label.indexOf(label) > -1;
}).slice(0, 10);
resolve(output);
}, 500);
})
}
window.AsyncFilteringSelect = class extends BaseSelect {
onInput (e) {
// Simple mechanism to prevent race condition
let fetchTime = Date.now();
this.fetchTime = fetchTime;
let value = this.input.value;
if (!value) {
return this.interface.setItems([]);
}
// TODO: Design loader...
AsyncGetData(value).then(items => {
if (fetchTime === this.fetchTime) {
this.interface.setItems(items);
this.interface.showList();
}
});
}
}
|
import config from '../config';
export default function addLegend(parent, {
items, position, unxkcdify, parentWidth, parentHeight, strokeColor, backgroundColor,
}) {
const filter = !unxkcdify ? 'url(#xkcdify)' : null;
const legend = parent.append('svg');
const backgroundLayer = legend.append('svg');
const textLayer = legend.append('svg');
items.forEach((item, i) => {
textLayer.append('rect')
.style('fill', item.color)
.attr('width', 8)
.attr('height', 8)
.attr('rx', 2)
.attr('ry', 2)
.attr('filter', filter)
.attr('x', 15)
.attr('y', 17 + 20 * i);
textLayer.append('text')
.style('font-size', '15')
.style('fill', strokeColor)
.attr('x', 15 + 12)
.attr('y', 17 + 20 * i + 8)
.text(item.text);
});
const bbox = textLayer.node().getBBox();
const backgroundWidth = bbox.width + 15;
const backgroundHeight = bbox.height + 10;
let legendX = 0;
let legendY = 0;
if (
position === config.positionType.downLeft
|| position === config.positionType.downRight
) {
legendY = parentHeight - backgroundHeight - 13;
}
if (
position === config.positionType.upRight
|| position === config.positionType.downRight
) {
legendX = parentWidth - backgroundWidth - 13;
}
// add background
backgroundLayer.append('rect')
.style('fill', backgroundColor)
.attr('fill-opacity', 0.85)
.attr('stroke', strokeColor)
.attr('stroke-width', 2)
.attr('rx', 5)
.attr('ry', 5)
.attr('filter', filter)
.attr('width', backgroundWidth)
.attr('height', backgroundHeight)
.attr('x', 8)
.attr('y', 5);
// get legend
legend
.attr('x', legendX)
.attr('y', legendY);
}
|
const toggleButton = document.getElementsByClassName('toggle-button')[0]
const navbarLinks = document.getElementsByClassName('navbar-links')[0]
toggleButton.addEventListener('click', () => {
navbarLinks.classList.toggle('active')
})
// ICON LIBRARIES SOURCES:
//AWESOME_FONTS
//https://fontawesome.com/v4.7.0/examples/
//OBSERVABLE
//https://observablehq.com/@observablehq/logo
//logo = html`<svg viewBox="-3 0 28 28" height="120" fill="currentColor" color="#000"><svg viewBox="0 0 25 28" width="22" height="28"><path d="M12.5 22.667c-1.154 0-2.154-.252-3-.754a5.091 5.091 0 01-1.945-2.048 10.801 10.801 0 01-.991-2.741A14.747 14.747 0 016.25 14c0-.83.054-1.624.164-2.382.108-.758.309-1.529.602-2.31a7.37 7.37 0 011.129-2.035 5.118 5.118 0 011.807-1.401c.746-.36 1.594-.539 2.548-.539 1.154 0 2.154.252 3 .754.843.501 1.517 1.21 1.945 2.048.452.861.782 1.775.991 2.741.209.965.314 2.007.314 3.124a16.7 16.7 0 01-.163 2.382 10.63 10.63 0 01-.615 2.31c-.302.782-.677 1.46-1.13 2.035-.451.575-1.05 1.042-1.794 1.401-.745.36-1.594.539-2.548.539zm2.206-6.373c.598-.6.93-1.43.919-2.294 0-.893-.299-1.658-.896-2.294-.598-.637-1.34-.956-2.229-.956s-1.631.319-2.23.956A3.236 3.236 0 009.376 14c0 .893.299 1.658.896 2.294.598.637 1.34.956 2.229.956s1.624-.319 2.206-.956zM12.5 27C19.403 27 25 21.18 25 14S19.403 1 12.5 1 0 6.82 0 14s5.597 13 12.5 13z"/></svg></svg>`
//SOCIAL MEDIA
//https://www.w3schools.com/howto/howto_css_social_media_buttons.asp
//GITHUB
//https://github.com/logos
//TABLEAU
//https://icons8.com/icons/set/tableau-icons
//Simple icons
//https://simpleicons.org/
// const f = document.getElementById('navbar-links');
// document.addEventListener('click', function (ev) {
// f.style.transform = 'translateY(' + (ev.clientY - 25) + 'px)';
// f.style.transform += 'translateX(' + (ev.clientX - 25) + 'px)';
// }, false);
//Button source: https://html-online.com/articles/dynamic-scroll-back-top-page-button-javascript/
/*Scroll to top when arrow up clicked BEGIN*/
$(window).scroll(function () {
var height = $(window).scrollTop();
if (height > 100) {
$('#back2Top').fadeIn();
} else {
$('#back2Top').fadeOut();
}
});
$(document).ready(function () {
$("#back2Top").click(function (event) {
event.preventDefault();
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
});
/*Scroll to top when arrow up clicked END*/
const nextSection = d3.select('#second-section')
const projectsButton = d3.select('#projects_button')
projectsButton.on('click', function (d) {
nextSection.transition()
duration(2000)
})
|
// @flow strict
import * as React from 'react';
import { graphql, createFragmentContainer } from '@kiwicom/mobile-relay';
import CityImageContainer from './cityImage/CityImageContainer';
import type { MulticityFlight_booking as MulticityFlightType } from './__generated__/MulticityFlight_booking.graphql';
type Props = {|
imageUrl: string,
type: string,
booking: MulticityFlightType,
|};
const MulticityFlight = (props: Props) => (
<CityImageContainer
image={props.booking}
arrival={props.booking.end}
departure={props.booking.start}
type="MULTICITY"
/>
);
export default createFragmentContainer(
MulticityFlight,
graphql`
fragment MulticityFlight_booking on BookingMulticity {
...CityImageContainer_image
end {
...CityImageContainer_arrival
}
start {
...CityImageContainer_departure
}
}
`,
);
|
import app from 'firebase/app';
import 'firebase/auth'
import 'firebase/firestore'
const firebaseConfig = {
apiKey: process.env.REACT_APP_API_KEY,
authDomain: process.env.REACT_APP_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_DATABASE_URL,
projectId: process.env.REACT_APP_PROJECT_ID,
storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_APP_ID,
measurementId: process.env.REACT_APP_MEASUREMENT_ID,
};
class Firebase {
constructor() {
app.initializeApp(firebaseConfig);
this.auth = app.auth();
this.db = app.firestore()
}
createUserWithEmail = (email, password) =>
this.auth.createUserWithEmailAndPassword(email, password);
signInWithEmail = (email, password) =>
this.auth.signInWithEmailAndPassword(email, password);
signOut = () =>
this.auth.signOut()
resetPassword = (email) =>
this.auth.sendPasswordResetEmail(email)
updatePassword = (password) =>
this.auth.currentUser.updatePassword(password)
sendEmailVerification = () =>
this.auth.currentUser.sendEmailVerification({
url: process.env.REACT_APP_CONFIRMATION_EMAIL_REDIRECT,
});
getPlaidFirebaseDoc = (userId) =>
this.db.collection('plaid').doc(userId).get();
setPlaidFirebaseDoc = (accessToken, itemId, userId) => {
const newDoc = {
accessToken: accessToken,
itemId: itemId
}
this.db.collection('plaid').doc(userId).set(newDoc)
}
getPlaidAccounts = (userId) =>
this.db.collection('plaid').doc(userId).collection('accounts').get()
setPlaidAccount = (userId, account) => {
this.db.collection('plaid').doc(userId).collection('accounts').doc(account.account_id).set(account)
}
getPlaidTransactions = (userId, accountId) =>
this.db.collection('plaid').doc(userId).collection('accounts').doc(accountId).collection('transactions').orderBy('date', 'desc').get()
setPlaidTransactions = (userId, accountId, transactions) => {
const batch = this.db.batch()
for (const transaction of transactions){
const docRef = this.db.collection('plaid').doc(userId).collection('accounts').doc(accountId).collection('transactions').doc(transaction.transaction_id)
batch.set(docRef, transaction)
}
batch.commit()
}
getAccount = (userId, accountId) =>
this.db.collection('plaid').doc(userId).collection('accounts').doc(accountId).get();
}
export default Firebase
|
function baseStorage(key ,value){
uni.setStorage({
key:key,
data:value,
success: () => {
console.log('--->save data success')
},
fail: () => {
console.log('--->save data fail')
}
})
}
function objectStorage(key ,object){
baseStorage(key,JSON.stringify(object))
}
function getStorageValue(key,default = ''){
}
|
/* Copyright (c) 2015 Intel Corporation. All rights reserved.
* Use of this source code is governed by a MIT-style license that can be
* found in the LICENSE file.
*/
/* global process */
/* global console */
/* global __dirname */
/* global module */
/**
*
*/
"use strict";
var path=require("path");
var fs=require("fs");
var cvmFolder=".cvm";
var rimraf=require("rimraf");
var isWin=(process.platform === "win32");
function getUserHome() {
return process.env[isWin ? "USERPROFILE" : "HOME"];
}
function getCVMPath() {
return path.join(getUserHome(),cvmFolder);
}
var CVMPath=getCVMPath();
var CLIBanner=""+
"Cordova Version Manager"+
"\n"+
"Usage: cvm task args\n"+
"============================\n\n";
var cliCommands="Available Tasks:\n\n"+
" list - list available covdova versions installed\n"+
" install [5.1.1] - Install a cordova version\n"+
" uninstall [5.1.1] - Uninstall a cordova version\n"+
" use [5.1.1] - Switch to a specific version of cordova\n"+
" version - Show current version of Cordova\n"+
" remote - List available remote versions of cordova to install\n"+
" \n"+
" --- remember to add the following to your shell profile --\n"+
" export PATH=\"$HOME/.cvm:$PATH\"\n"+
" --- on Windows, add the following to your local PATH --\n"+
" \%HOMEPATH\%\\.cvm";
var CVMCLI = {
run:function(cliArgs){
var version,thePath,exec,child;
//parse the command line arguments
//Check setup
if(!cliArgs||cliArgs.length===0){
return console.log(CLIBanner+cliCommands);
}
else {
var cmd=cliArgs[0].toLowerCase();
if(!this.checkCVMSetup()){
return;
}
if(cmd==="list"){
var items=this.cvminstalls();
if(items.length===0){
console.log("No versions installed");
}
else {
items.forEach(function(version){
console.log(version);
});
}
return;
}
else if(cmd==="install"){
version=cliArgs[1];
if(!version){
return console.log("Please specify Cordova Version");
}
thePath=path.join(CVMPath,version);
if(fs.existsSync(thePath)){
console.log("Version already installed");
return;
}
else {
fs.mkdirSync(thePath);
console.log("Installing Cordova "+version);
exec = require("child_process").exec;
child = exec("npm install cordova@"+version+" --prefix "+thePath ,
function (error, stdout) {
if (error !== null) {
console.log("exec error: " + error);
rimraf(thePath,function(){
console.log("Folder removed");
});
}
else {
console.log("Cordova "+version+" installed");
console.log(stdout);
}
});
}
}
else if(cmd==="uninstall"){
version=cliArgs[1];
thePath=path.join(CVMPath,version);
if(!fs.existsSync(thePath)){
console.log("Version not found");
return;
}
else {
rimraf(thePath,function(){
console.log("Cordova "+version+" uninstalled");
});
}
}
else if(cmd==="use"){
version=cliArgs[1];
//Check if version exists
thePath=path.join(CVMPath,version);
if(version==="system"){
version="";
}
else if(!fs.existsSync(thePath))
{
console.log("Invalid version specificied");
return;
}
fs.writeFileSync(path.join(getUserHome(),".cvmrc"),version);
}
else if(cmd==="version"){
exec = require("child_process").exec;
child = exec("cordova --version" ,
function(error,stdout){
if(error) {
console.log("Error "+error);
}
else {
console.log(stdout);
}
}
);
}
else if(cmd==="remote") {
var filter=cliArgs[1];
exec = require("child_process").exec;
child = exec("npm view cordova versions" ,
function(error,stdout){
if(error){
console.log("Error "+error);
}
else {
console.log("Cordova versions available\n");
var out=stdout.replace("[","").replace("]","");
out=out.replace(/["']/g,"");
out=out.replace(/(\r\n|\n|\r)/gm,"");
out=out.replace(/\ /gm,"");
out=out.split(",");
if(filter){
out = out.filter(function(data){
return data.indexOf(filter)===0;
});
}
console.log(out.join("\n\r"));
}
}
);
}
else {
return console.log(CLIBanner+cliCommands);
}
}
},
checkCVMSetup:function(){
if(!fs.existsSync(CVMPath)){
//create cvm path
fs.mkdirSync(CVMPath);
fs.openSync(path.join(getUserHome(),".cvmrc"),"w");
fs.createReadStream(path.join(__dirname,"..","broker","cordova")).pipe(fs.createWriteStream(path.join(getCVMPath(),"cordova")));
fs.chmodSync(path.join(getCVMPath(),"cordova"), "755");
if(isWin){
//Add the cmd file
fs.createReadStream(path.join(__dirname,"..","broker","cordova.cmd")).pipe(fs.createWriteStream(path.join(getCVMPath(),"cordova.cmd")));
fs.chmodSync(path.join(getCVMPath(),"cordova.cmd"), "755");
}
console.log("cvm system configuration complete");
console.log("Please add the following line to your shell profile");
console.log("export PATH='$HOME/.cvm:$PATH'");
console.log("On Windows, add the following to your local PATH env variable");
console.log("%HOMEPATH%\.cvm");
console.log("After you've updated your path, type 'cvm' on the command-line to get started.");
}
return true;
},
cvminstalls:function(){
return fs.readdirSync(CVMPath).filter(function(file) {
return fs.statSync(path.join(CVMPath, file)).isDirectory();
});
}
};
module.exports=CVMCLI;
|
const test = alert('Выберите верные утверждения:');
let ok = 0;
let cancel = 0;
const question1 = confirm('1. Преобразование Number (“false”) вернет число 0.');
if (question1 === true) {
ok++
} else {
cancel++;
};
const question2 = confirm('2. Значение переменной let нельзя изменить после инициализации.');
if (question2 === false) {
ok++;
} else {
cancel++;
}
const question3 = confirm('3. У объекта Math существует метод для вычисления квадратного корня.');
if (question3 === true) {
ok++;
} else {
cancel++;
}
const question4 = confirm('4. Результат выполнения логической операции - это булево значение.');
if (question4 === true) {
ok++;
} else {
cancel++;
}
const question5 = confirm('5. JS - слишком сложный и ему невозможно научиться.');
if (question5 === false) {
ok++;
} else {
cancel++;
}
alert(`Правильных ответов: ${ ok }, неравильных ответов: ${ cancel }`);
|
(function($) {
/**
* KOR library facade extentions
* shortcut methods off the static KOR namespace for opening and hiding The Login and Detail Dialogs.
*/
/**
* triggers a show event on the dom element anchor of the login dialog.
*/
KOR.showLoginDialog = function() {
$('input[name=LoginForm_Password]').val('').removeClass('kor-error').siblings('span.kor-error').remove();
loginAnchor.trigger('dialog:show');
};
/**
* triggers a hide event on the dom element anchor of the login dialog.
*/
KOR.hideLoginDialog = function() {
loginAnchor.trigger('dialog:hide');
};
/**
* triggers a show event on the dom element anchor of the Detail dialog.
* also sets the title of the dialog and the source url to be used in the detail dialog iframe
*/
KOR.showDetailDialog = function(title, src) {
detailDialog.title = title;
detailDialog.src = "{{}}{{}}DialogMode={{}}".uInject(src, src.indexOf('?') > -1 ? '&' : '?', KOR.SFE.channelID);
detailAnchor.trigger('dialog:show');
};
/**
* triggers a hide event on the dom element anchor of the Detail dialog.
*/
KOR.hideDetailDialog = function() {
detailAnchor.trigger('dialog:hide');
};
/**
* triggers a show event on the dom element anchor of the error dialog.
*/
KOR.showErrorDialog = function() {
errorAnchor.trigger('dialog:show');
};
/**
* triggers a hide event on the dom element anchor of the error dialog.
*/
KOR.hideErrorDialog = function() {
errorAnchor.trigger('dialog:hide');
};
/**
* triggers a show event on the dom element anchor of the creation error/info dialog.
*/
KOR.showCreationErrorDialog = function(errorMessage, error) {
errorCreationAnchor.trigger('dialog:show');
if (!errorMessage) {
errorMessage = $('.sfe-dialog-content').data('default-message');
}
$('.sfe-dialog-content p').html(errorMessage);
$('.sfe-dialog-content').attr('title', error);
// center dialog
errorCreationAnchor.trigger('dialog:show');
};
/**
* triggers a hide event on the dom element anchor of the creation error dialog.
*/
KOR.hideCreationErrorDialog = function() {
errorCreationAnchor.trigger('dialog:hide');
};
/**
* triggers a show event on the dom element anchor of the preview error dialog.
*/
KOR.showErrorPreviewDialog = function() {
errorPreviewAnchor.trigger('dialog:show');
};
/**
* triggers a hide event on the dom element anchor of the preview error dialog.
*/
KOR.hideErrorPreviewDialog = function() {
errorPreviewAnchor.trigger('dialog:hide');
};
/**
* KOR library Data Factory extentions
*/
$.extend(KOR.namespace('KOR.ObjectFactory'), {
/**
* gets externalized string values for a key from the 'KOR.extStrings' object.
* accepts optional arguments that are injected in order into the value string.
* uses uInject methods variable placeholders {{}}
* uses a callback pattern.
*/
getExtString: function() {
args = $.makeArray(arguments);
uri = args.shift();
callback = args.pop();
callback(KOR.extStrings[uri].uInject(
args.length === 1 && $.type(args[0]) === 'array' ? args[0] : args));
},
/**
* gets a template string for a key from the 'KOR.templates' object.
* uses a callback pattern as well as a synchronous retrieval if no callback parameter is present
*/
getTemplate: function(id, callback) {
return callback ? callback(KOR.templates[id]) : KOR.templates[id];
},
/**
* builds the private comments object of Component comments
* sends a complete json object of the page component structure to the callback function
*/
getComponentTree: function(callback) {
var jsonString = [];
$.each(getComments(sitePanel.document), function() {
if (this.data.match(/^sfe\:\{.*\}$/)) {
var obj = $.parseJSON(this.data.replace('sfe:', ''));
this.sfeId = obj.id;
if (comments[obj.id]) {
this.sfeEnd = true;
} else {
this.sfeBegin = true;
comments[obj.id] = [];
}
comments[obj.id].push(this);
if (obj.prefixPayload) jsonString.unshift(obj.prefixPayload);
if (obj.suffixPayload) jsonString.push(obj.suffixPayload);
}
});
jsonString = jsonString.join('');
if ($.trim(jsonString) === '') {
// show error dialog if 'Empty Component Tree'
KOR.showErrorDialog();
return;
}
var json = "";
json = (jsonString.substring(0, jsonString.length - 1));
json = json.replace(/'/g,"\""); // Replace all ' with "
json = json.replace(/(},])/g, '}]'); // Replace all },] with }]
json = "[" + json + "]";
var obj = $.parseJSON(json);
callback(obj);
}
});
/**
* private functions
*
* Event Handlers
*/
function toggleInspectorHandler(ev) {
ev.preventDefault();
if (inInspectorMode) {
exitInspectorMode();
} else {
enterInspectorMode();
}
}
function toggleLayoutMode(event) {
if (event === 'init') {
if ($.cookie('sfe-layout-mode') === 'on') {
$(layoutButtonSelector).addClass('on');
}
} else {
var layoutButton = $(this);
if (layoutButton.hasClass('on')) {
layoutButton.removeClass('on');
$.cookie('sfe-layout-mode', 'off');
$(document).trigger('layoutMode:off');
} else {
layoutButton.addClass('on');
$.cookie('sfe-layout-mode', 'on');
$(document).trigger('layoutMode:on');
}
}
}
function resizeHandler(ev) {
sizeSiteFrame();
sizePalette();
}
function displayViewableArea() {
$('.viewable-area-display').html($(siteContentSelector).width() + " x " + $(siteContentSelector).height());
}
function componentProxyToTreeClickHandler(ev) {
ev.preventDefault();
var link = $(ev.currentTarget);
var params = link.attr('href').split('?')[1].uQueryStringToHash();
$.each(currentTreeNode.next('ul').find('>li>a[data-component-id]'), function() {
var node = $(this);
var compId = node.attr('data-component-id');
var compObj = componentDetailObject[compId];
if (params.AssignmentUUID && compObj.pageletAssignmentUUID && params.AssignmentUUID === compObj.pageletAssignmentUUID) {
currentComponentId = compId;
setOverlay();
setDetail(compId);
return false;
} else if (params.PageletUUID && compObj.id && params.PageletUUID === compObj.id) {
currentComponentId = compId;
setOverlay();
setDetail(compId);
return false;
}
});
currentComponentId = null;
setOverlay();
setDetailByLinkParameters(params);
return false;
}
function stopDraggingHandler(ev) {
$(document).off('mousemove', mouseMovePanelResizeHandler);
siteContentOverlay.hide();
}
function controlPanelSplitHandler(ev) {
$(document).on('mousemove', null, 'control-panel-split', mouseMovePanelResizeHandler);
}
function controlPanelResizeHandler(ev) {
$(document).on('mousemove', null, 'control-panel-height', mouseMovePanelResizeHandler);
}
function paletteResizeHandler(ev) {
$(document).on('mousemove', null, 'palette-width', mouseMovePanelResizeHandler);
}
function mouseMovePanelResizeHandler(ev) {
siteContentOverlay.show(); // prevents interference from the iframe
unFocus(); // prevents text selection
if (ev.data === 'palette-width') {
if ($('#component-palette').width() === 0) {
return;
}
sizePalette(ev.pageX);
displayViewableArea();
initDisplayDevice();
return;
}
if (ev.data === 'control-panel-split') {
if (ev.pageX > 240 && ev.pageX < $(window).width() - 340) {
var width = dividerSelector.parent().width();
var percent = Math.round(ev.pageX / width * 100);
$.cookie('sfe-application-state-ew-percent', percent, {path: KOR.SFE.cookiePath});
setSizeEWPanels(percent);
}
return;
}
if (ev.data === 'control-panel-height') {
showControlPanel();
setControlPanelHeight(KOR.$(controlPanelSelector).height() - (ev.pageY - KOR.$(controlPanelSelector).offset().top) + 20);
sizePalette();
displayViewableArea();
initDisplayDevice();
return;
}
}
// Prevent text selection on mouse drag
function unFocus() {
if (document.selection) {
document.selection.empty();
} else {
window.getSelection().removeAllRanges();
}
}
function loginDialogClickHandler(ev) {
ev.preventDefault();
$('#sfe-login-dialog-form').trigger('focus').trigger('submit');
}
function clickProxyHandler(ev) {
ev.preventDefault();
ev.stopPropagation();
document.getElementById($(ev.target).attr('data-sfe-actionbutton')).click();
}
function formActionClickHandler(ev) {
var field = $(this);
var form = field.closest('form');
var actionField = form.find('.kor-form-action');
if (!actionField.length) {
actionField = $('<input type="hidden" class="kor-form-action" />');
form.append(actionField);
}
if (field.hasClass('sfe-action-inline')) {
form.attr('data-sfe-action', 'inline');
} else if (field.hasClass('sfe-action-dialog')) {
form.attr('data-sfe-action', 'dialog');
}
if (field.hasClass('sfe-layout-change')) {
actionField.addClass('sfe-layout-change');
} else {
actionField.removeClass('sfe-layout-change');
}
actionField.attr('name', field.attr('name')).attr('value', field.attr('value'));
window.saveScrollPosition($(editPanelContainerSelector));
}
function hideControlPanelHandler(ev) {
ev.preventDefault();
setControlPanelHeight(controlPanelCloseHeight);
sizePalette();
}
function showControlPanelHandler(ev) {
ev.preventDefault();
setControlPanelHeight(lastControlPanelHeight || controlPanelDefaultHeight);
sizePalette();
}
function componentClickHandler(ev) {
var compId;
ev.preventDefault();
ev.stopPropagation();
if($(ev.target).attr('data-component-id')) {
compId = $(ev.target).attr('data-component-id');
}
else {
compId = $(ev.target).closest('[data-component-id]').attr('data-component-id');
}
if (compId === currentComponentId && getOverlay().css('display') === 'block') {
compId = null;
}
currentComponentId = compId;
setOverlay(250);
setDetail(compId);
}
function detailFormSubmitHandler(ev) {
var form = $(ev.currentTarget);
//insert hidden field for sfe identification
if (!form.find('input[name=sfe]').length) {
form.append('<input type="hidden" name="sfe" value="true" />');
}
if (form.find('input.kor-form-action[name=Copy]').length) {
updateDetailPanel = false;
}
if (form.attr('data-sfe-action') === 'inline') {
return detailFormInline(form, ev);
} else if (form.attr('data-sfe-action') === 'dialog') {
return detailFormDialog(form, ev);
}
return undefined;
}
function inlineAnchorClickHandler(ev) {
ev.preventDefault();
var url = $(ev.target).attr('href');
showDetailLoader();
$.ajax({
url: url,
complete: function() {
hideDetailLoader();
},
success: function(html) {
KOR.log('section update from anchor');
setDetailCallback(html);
}
});
return false;
}
function dialogAnchorClickHandler(ev) {
ev.preventDefault();
var target = $(ev.target);
var url = target.attr('href');
var title = target.attr('title');
KOR.showDetailDialog(title, url);
return false;
}
function disableClickHandler(ev) {
ev.preventDefault();
return false;
}
function contentPageLoadHandler(ev) {
sizeSiteFrame(ev);
var appurl = sitePanel.location.href;
// test a real URL was loaded in iframe, do nothing for 'about:blank' (initial state of the iframe)
if (/^(https?):\/\//i.test(appurl)) {
// persist the current location to cookie
$.cookie('sfe-application-state-app-url_' + KOR.SFE.contentRepoUUID, appurl, {
path: KOR.SFE.cookiePath
});
//empty dom pointers to previous page
overlay = null;
inspector = null;
comments = {};
componentDetailObject = {};
//check if storefront editing functionality is available
if (KOR.$(controlPanelSelector).length > 0) {
//register events for inspector functionality
$(sitePanel.document).on('click', inspectorClickHandler);
$(sitePanel.document).on('mousemove', moveInspectorHandler);
//build the component tree and set the application state
KOR.ObjectFactory.getComponentTree(setApplicationState);
}
// trigger the custom 'designer:pageContentLoad' event once the iframe content is loaded (the preview content)
$(siteContentSelector).trigger('designer:pageContentLoad');
siteContentOverlay.hide();
}
}
function reloadDetailPanelHandler(ev) {
if ($(ev.target).attr('href') !== undefined) {
ev.preventDefault();
loadDetailPanel($(ev.target).attr('href'));
}
}
function inspectorClickHandler(ev) {
if (inInspectorMode && inspectorPreviewing) {
ev.preventDefault();
currentComponentId = inspectorPreviewing;
setOverlay(250);
setDetail(inspectorPreviewing);
if (ev.target.nodeName == 'VIDEO') {
ev.target.pause();
}
}
}
function moveInspectorHandler(ev) {
if (inInspectorMode) {
var target = ev.target || ev;
if (target.sfeId && target.sfeBegin) {
setInspector(target.sfeId);
} else if (target.previousSibling) {
moveInspectorHandler(target.previousSibling);
} else if (target.parentNode) {
moveInspectorHandler(target.parentNode);
} else {
setInspector();
}
}
}
function applicationResetHandler(ev) {
ev.preventDefault();
window.location = KOR.SFE.URLS.applicationReset;
}
function hideDetailDialogLoader() {
$('#sfe-dialog-iframe').css('display', 'block');
$('.sfe-detail-dialog-loader').css('display', 'none');
}
function showDetailDialogLoader() {
$('#sfe-dialog-iframe').css('display', 'none');
$('.sfe-detail-dialog-loader').css('display', 'block');
}
function detailDialogPopulateHandler(ev) {
var obj = this;
if (!obj._initshow) {
obj._initshow = true;
$('#sfe-dialog-iframe').on('load', function(ev) {
hideDetailDialogLoader();
detailDialogFrameLoadHandler(ev, obj);
});
}
showDetailDialogLoader();
$('.sfe-dialog-loader').css('display', 'block');
$('#sfe-dialog-title').html(obj.title);
$('#sfe-dialog-iframe').attr('src', obj.src);
obj.position(ev);
}
function detailDialogFrameLoadHandler(ev, obj) {
var win = frames['sfe-dialog-iframe'];
var doc = $(win.document.body);
//close dialog and forward content to detail panel
var detailPanelContent = doc.find('#editPanelResponse');
if (detailPanelContent.length) {
KOR.hideDetailDialog();
setDetailPanels(detailPanelContent.parent().html());
updateDetailPanel = false;
sitePanel.location.reload();
return;
}
//resize and position iframe
$(ev.target).css({
height: doc.height()
//width: doc.width()
});
obj.position({
target: detailAnchor
});
$(window).resize();
//cancel botton hijacking in dialog
$('[value=Cancel]', doc).on('click', function(ev) {
ev.preventDefault();
ev.stopPropagation();
KOR.hideDetailDialog();
});
//set frame reload flag for on exit of dialog
doc.on('click', '.sfe-layout-change', function() {
reloadSiteFrameOnWizardExit = true;
});
//dialog hidden field addition
doc.on('submit', 'form', function() {
var form = $(this);
if (!form.find('.sfe-dialog-mode').length) {
form.append('<input type="hidden" class="sfe-dialog-mode" name="DialogMode" value="{{}}" />'.uInject(KOR.SFE.channelID));
}
});
//in dialog link handling
doc.on('click', 'a', function(ev) {
var link = $(this);
if (link.attr('href').indexOf('javascript:') > -1) {} else {
var linkParts = link.attr('href').split("#");
link.attr('href', "{{}}{{}}DialogMode={{}}".uInject(linkParts[0], linkParts[0].indexOf('?') > -1 ? '&' : '?', KOR.SFE.channelID) + ((linkParts[1] !== undefined) ? "#" + linkParts[1] : ""));
}
});
//redefine pop calendar
var cal = win.popUpCalendar;
win.popUpCalendar = function() {
cal.apply(this, arguments);
$('#calendar', doc).position({
my: 'left',
at: 'right',
of: arguments[0],
collision: 'fit'
});
};
}
function detailDialogHideHandler() {
if (reloadSiteFrameOnWizardExit) {
reloadSiteFrameOnWizardExit = false;
sitePanel.location.reload();
}
this._super.apply(this, arguments);
}
function loginIsAjaxSuccessHandler(data) {
return !isLogInMarkup(data);
}
function loginAjaxSuccessHandler() {
this._super();
KOR.hideLoginDialog();
runFailedAuthentationStack();
}
function loginAjaxFailureHandler() {
this._super();
KOR.ObjectFactory.getExtString('fieldFailureInvalidPassword', function(str) {
$('input[name=LoginForm_Password]').addClass('kor-error').after('<span class="kor-error">{{}}</span>'.uInject(str));
});
}
function treeToggleHandler(node, ev) {
ev.preventDefault();
ev.stopPropagation();
$(ev.target).toggleClass('sfe-closed sfe-open');
node.toggle(250, function() {
var nextNode = $(this);
if (nextNode.css('display') === 'block') {
var treeId = nextNode.children('li').children('[data-component-tree-id]').attr('data-component-tree-id');
$.cookie('sfe-application-state-tree-id_' + KOR.SFE.contentRepoUUID, treeId, {
path: KOR.SFE.cookiePath
});
nextNode.children('li').each(function() {
var n = $(this);
if (n.attr('data-type') === 'Slot') {
n.children('[data-component-id]').children('.sfe-closed').trigger('click');
}
});
}
});
}
function treeDropActionHandler(ev) {
var target = this.replacedElement;
if (this.replacedElement && this.dragElement[0] !== this.replacedElement[0]) {
if (target.attr('data-assignment-id')) {
var source = $(ev.target).siblings('.' + this.dragActiveClass);
var url = "{{}}{{}}AssignmentUUID={{}}&TargetAssignmentUUID={{}}".uInject(
KOR.SFE.URLS.moveAssignment,
KOR.SFE.URLS.moveAssignment.indexOf('?') > -1 ? '&' : '?',
source.attr('data-assignment-id'),
target.attr('data-assignment-id')
);
$.get(url, function() {
var treeId = target.find('[data-component-tree-id]').attr('data-component-tree-id');
$.cookie('sfe-application-state-tree-id_' + KOR.SFE.contentRepoUUID, treeId, {
path: KOR.SFE.cookiePath
});
sitePanel.location.reload();
});
}
}
this._super(ev);
}
/**
*private getters
*/
function getComments(el) { // this is the recursive function
var comments = [],
len = el.childNodes.length;
if (len) {
for (var i = 0; i < len; i++) {
comments = comments.concat(getComments(el.childNodes[i]));
}
} else if (el.nodeType === 8) {
comments[len] = el;
}
return comments;
}
function getOverlay() {
overlay = $('.sfe-highlight-overlay', sitePanel.document.body);
if (!overlay.length) {
$(sitePanel.document.body).append(KOR.ObjectFactory.getTemplate(componentOverlayTemplate).uTemplate({}));
overlay = $('.sfe-highlight-overlay', sitePanel.document.body);
overlay.on('click', function(ev) {
currentComponentId = null;
setOverlay(250);
setDetail(null);
});
}
return overlay;
}
function getInspector() {
inspector = $('.sfe-inspector-overlay', sitePanel.document.body);
if (!inspector.length) {
$(sitePanel.document.body).append(KOR.ObjectFactory.getTemplate(componentInspectorTemplate).uTemplate({}));
inspector = $('.sfe-inspector-overlay', sitePanel.document.body);
}
return inspector;
}
function getOverlayDimensions(k) {
k = k || currentComponentId;
var x = [],
y = [],
h = [],
w = [];
getComponentDomArray(k).each(function() {
var node = $(this);
var offset = node.offset();
x.push(offset.left);
y.push(offset.top);
h.push(offset.top + node.outerHeight());
w.push(offset.left + node.outerWidth());
});
return x.length && y.length && w.length && h.length ? {
height: Math.max.apply(this, h) - Math.min.apply(this, y),
width: Math.max.apply(this, w) - Math.min.apply(this, x),
left: Math.min.apply(this, x),
top: Math.min.apply(this, y)
} : undefined;
}
function getComponentDomArray(k) {
k = k || currentComponentId;
var dom = $();
var nodes = comments[k];
if (nodes && nodes.length === 2) {
var node = nodes[0];
while (node) {
if (node.nodeType === 1 && node.tagName.toLowerCase() !== 'script' && $(node).css('display') !== 'none') {
dom = dom.add(node);
} else if (node === nodes[1]) {
return dom;
}
node = node.nextSibling;
}
}
return dom;
}
/**
* Private Setters
*/
function setOverlay(duration) {
//clear all tree highlights
$('[data-component-id]', KOR.$(componentTreeSelector)).removeClass(activeComponentAnchorClass);
$('[data-inspector-opened=true]', KOR.$(componentTreeSelector)).attr('data-inspector-opened', false);
if (currentComponentId) {
//highlight tree node
highlightSelectedComponentInTree();
//set active component location
if (componentDetailObject[currentComponentId]) {
//set the treeId of the current Component
var treeId = componentDetailObject[currentComponentId].treeId;
$.cookie('sfe-application-state-component-id_' + KOR.SFE.contentRepoUUID, treeId, {
path: KOR.SFE.cookiePath
});
}
exitInspectorMode();
positionOverlay(duration);
} else {
$.cookie('sfe-application-state-component-id_' + KOR.SFE.contentRepoUUID, null, {
path: KOR.SFE.cookiePath
});
hideOverlay(duration);
}
}
function setDetailPanels(html) {
// remove any tinyMCE instance before deleting its respective DOM element
tinyMCE.remove();
var dom = document.createElement('div');
dom.innerHTML = html;
dom = $(dom);
dom.find('.sfe-removed').remove();
KOR.$(componentDetailSectionsSelector).html(dom.find('#editTabs').html());
KOR.$(componentDetailLinksSelector).html(dom.find('#editLinks').html());
KOR.$(componentDetailContentSelector).html(dom.find('#editContainer').html());
KOR.$(componentDetailCommandsSelector).html(dom.find('#editControls').html());
//get disable status for revert button in design view from hidden revert button in BO template
if ($(componentDetailContentSelector).find('.cpo-action-start-revert').attr('disabled') === 'disabled') {
KOR.$(componentDetailCommandsSelector).find('a[data-sfe-actionbutton*="sfe-start-revert"]').addClass('disabled-button');
}
$(dom).remove();
loadTinyMCE();
renderDetailTips();
renderDataButtons();
//diable storefront editing if prefernce SFEReadonlyIfFuture is 'true' and preview date is 'Fixed'
var previewReadonly = $('#preview_readonly_if_future').val();
var previewFixedDateFlag = $('.sfe-preview-pca-datetime-make-fixed').is(':checked');
if (previewReadonly === 'true' && previewFixedDateFlag) {
setDisableForEditContainer(componentDetailContentSelector);
setDisableForEditControls(componentDetailCommandsSelector);
switchComponentDragDrop();
}
window.restoreScrollPosition($(editPanelContainerSelector));
}
function setDisableForEditContainer(e) {
$(e + ' :input').attr('disabled', 'disabled');
}
function setDisableForEditControls(e) {
$(e + ' ul li').off('click');
$(e + ' ul li a').addClass('disabled-button');
}
function switchComponentDragDrop() {
$('.sfe-container-tree-level-link').children("span").removeClass('drag-controller');
}
function setSizeEWPanels(percent) {
KOR.$(treePanelSelector).width(percent - 1 + '%');
KOR.$(detailPanelSelector).width(100 - percent + '%');
}
function setUIState() {
//panel size persistance
var ewPercent = $.cookie('sfe-application-state-ew-percent');
if (ewPercent) {
setSizeEWPanels(ewPercent);
}
var nsPx = $.cookie('sfe-application-state-ns-px');
if (nsPx) {
setControlPanelHeight(nsPx);
} else {
sizeComponentTree();
}
sizePalette('init');
toggleLayoutMode('init');
}
function setInspector(k) {
var dims = getOverlayDimensions(k);
var ov = getInspector();
KOR.log('overlay dims: ', dims);
if (k && dims) {
ov.filter('.sfe-inspector-top').css({
top: dims.top,
left: dims.left,
width: dims.width
});
ov.filter('.sfe-inspector-bottom').css({
top: dims.top + dims.height - 2,
left: dims.left,
width: dims.width
});
ov.filter('.sfe-inspector-left').css({
top: dims.top,
left: dims.left,
height: dims.height
});
ov.filter('.sfe-inspector-right').css({
top: dims.top,
left: dims.left + dims.width - 2,
height: dims.height
});
ov.css({
display: 'block'
});
} else {
ov.css({
display: 'none'
});
}
if (inspectorPreviewing !== k) {
setComponentInTree(k);
}
inspectorPreviewing = k;
}
function setDetailByLinkParameters(params) {
if (params) {
var url = "{{}}&type=Pagelet&{{}}".uInject(KOR.SFE.URLS.editing, KOR.toQueryString(params));
loadDetailPanel(url);
} else {
setDetailPanels("");
}
}
function setDetail(detailId) {
KOR.log('loading detail id: ', detailId);
var detailObject = componentDetailObject[detailId];
KOR.log('found detail object: ', detailObject);
if (detailObject) {
var url = "{{}}&{{}}".uInject(KOR.SFE.URLS.editing, KOR.toQueryString(detailObject));
KOR.log('editing url: ', url);
loadDetailPanel(url, function() {
setDetail(detailId);
});
} else {
setDetailPanels("");
}
}
function setDetailCallback(html, failStackFn) {
if (isLogInMarkup(html)) {
handleUnauthorizedState(failStackFn);
return;
}
if (isErrorMessage(html)) {
setDetailPanels('<div><div id="editContainer">' + html + '</div></div>');
return;
}
setDetailPanels(html);
}
function handleUnauthorizedState(failStackFn) {
failedAuthentationStack.push(failStackFn);
KOR.showLoginDialog();
setDetailPanels("");
}
function setControlPanelHeight(n) {
if ($(window).height() - KOR.$(headerPanelSelector).height() - n >= 0) {
$.cookie('sfe-application-state-ns-px', n, {
path: KOR.SFE.cookiePath
});
if (n > controlPanelCloseHeight) {
lastControlPanelHeight = n;
showControlPanel();
} else if (n <= controlPanelCloseHeight) {
n = controlPanelCloseHeight;
hideControlPanel();
}
KOR.$(controlPanelSelector).height(n);
sizeEditingPanel();
sizeComponentTree();
positionOverlay();
}
}
function addLocaleParamToDetailPanelUrl(url) {
if (currentLocale) {
//remove existing LocaleId parameter if present
url = url.replace(/&?LocaleId=.*?(&|$)/, '');
//add new LocaleId parameter
if (url.indexOf('?') > -1) {
url = url.replace('?', '?LocaleId={{}}&'.uInject(currentLocale));
} else {
url += '?LocaleId={{}}'.uInject(currentLocale);
}
}
return url;
}
function setApplicationState(data) {
var compId;
componentTree = data;
//render tree html
renderComponentTree();
// highlight proper component
if ($.cookie('sfe-application-state-new-assignment-id') || $.cookie('sfe-application-state-component-id_' + KOR.SFE.contentRepoUUID)) {
// check if a new component was created that should be selected
if ($.cookie('sfe-application-state-new-assignment-id')) {
currentComponentId = $('[data-assignment-id="' + $.cookie('sfe-application-state-new-assignment-id') + '"] > a').data('component-id');
currentDetailPanelUrl = null;
$.cookie('sfe-application-state-new-assignment-id', null, {path: KOR.SFE.cookiePath});
} else {
compId = $(componentTreeSelector + " [data-component-tree-id='{{}}']".uInject($.cookie('sfe-application-state-component-id_' + KOR.SFE.contentRepoUUID))).attr('data-component-id');
// make sure the component still exists. if not look for its parent slot
if (!compId && currentSlotTreeId) {
compId = $(componentTreeSelector + " [data-component-tree-id='{{}}']".uInject(currentSlotTreeId)).attr('data-component-id');
}
currentComponentId = compId;
}
setOverlay();
if (loadInitDetailPanel) {
loadDetailPanel(loadInitDetailPanel);
} else {
if (updateDetailPanel) {
if (currentDetailPanelUrl && currentComponentId) {
loadDetailPanel(currentDetailPanelUrl);
} else {
setDetail(currentComponentId || componentTree[0].id);
}
}
}
setComponentInTree(currentComponentId);
} else {
currentComponentId = (componentTree && componentTree[0]) ? componentTree[0].id : null;
setOverlay();
if (updateDetailPanel) {
setDetail(currentComponentId);
}
}
//open the tree to the right area
if ($.cookie('sfe-application-state-tree-id_' + KOR.SFE.contentRepoUUID)) {
compId = $(componentTreeSelector + " [data-component-tree-id='{{}}']".uInject($.cookie('sfe-application-state-tree-id_' + KOR.SFE.contentRepoUUID))).attr('data-component-id');
if (!compId && currentSlotTreeId) {
var compTreeNode = $(componentTreeSelector + " [data-component-tree-id='{{}}']".uInject(currentSlotTreeId));
compId = compTreeNode.attr('data-component-id');
var firstChild = compTreeNode.next('ul').find('>li>a[data-component-id]');
if (firstChild.length) {
compId = firstChild.attr('data-component-id');
}
}
setComponentInTree(compId);
}
updateDetailPanel = true;
loadInitDetailPanel = null;
}
function setComponentInTree(k) {
//reset tree
removeInspectorTree();
if (k) {
//display uls up the tree
var anchor = $('[data-component-id="{{}}"]'.uInject(k), KOR.$(componentTreeSelector));
if (inInspectorMode) {
anchor.addClass('sfe-inspector-preview');
}
anchor.parentsUntil(componentTreeSelector).each(function() {
var node = $(this);
if (this.tagName.toLowerCase() === 'ul') {
if (node.css('display') !== 'block') {
node.css({
'display': 'block'
});
if (inInspectorMode) {
node.attr('data-inspector-opened', true);
}
//open the arrow pointers
node.prev('[data-component-id]').children('.sfe-closed').removeClass('sfe-closed').addClass('sfe-open');
}
}
});
//scroll into center of view
KOR.$(componentTreeContainerSelector).scrollTop(0);
KOR.$(componentTreeContainerSelector).scrollLeft(0);
var anchorOffset = anchor.offset();
var treeOffset = KOR.$(componentTreeContainerSelector).offset();
var offsetTop = anchorOffset.top - (treeOffset.top + ((KOR.$(componentTreeContainerSelector).height() / 2) - (anchor.height() / 2)));
var offsetLeft = anchorOffset.left - (treeOffset.left + ((KOR.$(componentTreeContainerSelector).width() / 2) - (anchor.width() / 2)));
KOR.$(componentTreeContainerSelector).scrollTop(offsetTop);
KOR.$(componentTreeContainerSelector).scrollLeft(offsetLeft);
}
}
/**
* private boolean methods
*/
function isLogInMarkup(html) {
return html && html !== '' && html.indexOf(sessionTimeoutMarkupIdentifier) !== -1;
}
function isErrorMessage(html) {
return html && html !== '' && html.indexOf(errorMarkupIdentifier) !== -1;
}
function isFormErrorMessage(html) {
return html && html !== '' && html.indexOf(formErrorMarkupIdentifier) !== -1;
}
/**
* private show methods
*/
function showDetailLoader() {
if (!detailLoader) {
KOR.ObjectFactory.getTemplate(loaderTemplate, function(str) {
detailLoader = $(str);
$(document.body).append(detailLoader);
showDetailLoaderAction();
});
} else {
showDetailLoaderAction();
}
}
function showDetailLoaderAction() {
detailLoader.css({
display: 'block',
visibility: 'hidden'
});
detailLoader.position({
my: 'center center',
at: 'center center',
of: componentDetailSelector
});
detailLoader.css({
display: 'none',
visibility: 'visible'
});
detailLoader.fadeIn(250);
}
function showControlPanel() {
KOR.$(controlPanelCollapseSelector).addClass(openedControlPanelClassName).removeClass(closedControlPanelClassName);
KOR.$(controlPanelHideOnCloseSelector).css('visibility', 'visible');
}
/**
* private hide methods
*/
function hideDetailLoader() {
if (detailLoader) {
detailLoader.fadeOut(250);
}
}
function hideControlPanel() {
KOR.$(controlPanelCollapseSelector).removeClass(openedControlPanelClassName).addClass(closedControlPanelClassName);
KOR.$(controlPanelHideOnCloseSelector).css('visibility', 'hidden');
}
function hideOverlay(duration) {
getOverlay().fadeOut(duration || 0, function() {
$(this).css({
opacity: 0
});
});
}
function togglePaletteHandler(ev) {
ev.preventDefault();
$(this).toggleClass('collapsed');
if ($(this).hasClass('collapsed')) {
sizePalette('hide');
} else {
sizePalette('show');
}
displayViewableArea();
initDisplayDevice();
}
/**
* private render methods
*/
function renderComponentTree() {
KOR.$(componentTreeSelector).html(KOR.ObjectFactory.getTemplate(componentTreeTemplate).uTemplate({
componentTree: componentTree,
componentDetailObject: componentDetailObject,
componentTreeItemTemplate: KOR.ObjectFactory.getTemplate(componentTreeItemTemplate)
}));
}
function renderDetailTips() {
KOR.$(componentDetailContentSelector).find('td.fielditem2').each(function() {
var node = $(this);
var tip = node.next('td').next('td.table_detail');
if (tip.length && $.trim(tip.html()) !== '') {
node.html('<span data-overlay="{{}}" class="sfe-tip">{{}}</span>'.uInject(tip.html(), node.html()));
tip.html('');
}
});
}
function renderDataButtons() {
if (currentTreeNode && componentDetailObject) {
var links = {};
var parentCategory = currentTreeNode.closest('[data-type="Catalog Category"]');
var parentProduct = currentTreeNode.closest('[data-type="Product"]');
if (parentCategory.length) {
var cat = componentDetailObject[parentCategory.find('[data-component-id]').attr('data-component-id')];
if (cat) links.categoryLink = KOR.SFE.URLS.backofficeEditing + '&CatalogCategoryID=' + cat.id;
}
if (parentProduct.length) {
var product = componentDetailObject[parentProduct.find('[data-component-id]').attr('data-component-id')];
if (product) links.productLink = KOR.SFE.URLS.backofficeEditing + '&ProductID=' + product.id;
}
if (links.productLink || links.categoryLink) {
$('.sfe-links').uTemplate(dataLinkTemplate, links);
}
}
}
/**
* private action methods
*/
function enterInspectorMode() {
KOR.$(inspectorButtonSelector).addClass(inspectorButtonOnClassName);
inInspectorMode = true;
}
function exitInspectorMode() {
KOR.$(inspectorButtonSelector).removeClass(inspectorButtonOnClassName);
inInspectorMode = false;
getInspector().css('display', 'none');
removeInspectorTree();
}
function removeInspectorTree() {
$('[data-inspector-opened=true]', KOR.$(componentTreeSelector)).each(function() {
var node = $(this);
node.attr('data-inspector-opened', false).css({
display: 'none'
});
node.prevAll('.sfe-open').removeClass('sfe-open').addClass('sfe-closed');
});
$('.sfe-inspector-preview', KOR.$(componentTreeSelector)).removeClass('sfe-inspector-preview');
}
function sizeEditingPanel() {
KOR.$(editPanelContainerSelector).height(
KOR.$(controlPanelSelector).height() - KOR.$(editPanelContainerSelector).position().top - parseInt(KOR.$(editPanelControlsSelector).css('height'))
);
}
function sizeComponentTree() {
KOR.$(componentTreeSelector).height(
KOR.$(controlPanelSelector).height() - KOR.$(componentTreeSelector).position().top - parseInt(KOR.$(componentTreeSelector).css('padding-bottom'))
);
sizeSiteFrame();
}
function sizePalette(mode) {
var $componentPalette = $('#component-palette'),
paletteDefaultWidth = 400,
paletteMinWidth = 200,
paletteMaxWidth = $(window).width() - 300,
savedWidth = null;
// width handling
if (typeof mode === 'number') {
var width = mode;
if (width < paletteMinWidth) {
width = paletteMinWidth;
}
if (width >= paletteMinWidth && width <= paletteMaxWidth) {
$componentPalette.width(width);
// save the changed palette width to a cookie
$.cookie('sfe-application-state-palette-width', $componentPalette.width(), {path: KOR.SFE.cookiePath});
if (paletteCollapse.hasClass('collapsed')) {
paletteCollapse.removeClass('collapsed');
paletteResizer.removeClass('collapsed');
$.cookie('sfe-application-state-palette-collapsed', null, {path: KOR.SFE.cookiePath});
}
}
} else if (mode === 'init') {
if ($.cookie('sfe-application-state-palette-collapsed') === 'true') {
$componentPalette.width(0);
paletteCollapse.addClass('collapsed');
paletteResizer.addClass('collapsed');
} else {
savedWidth = $.cookie('sfe-application-state-palette-width') || paletteDefaultWidth;
if (savedWidth > paletteMaxWidth) {
savedWidth = paletteMaxWidth;
}
$componentPalette.width(savedWidth);
}
} else if (mode === 'hide') {
paletteResizer.addClass('collapsed');
$componentPalette.width(0);
// save the palette collapse state to a cookie
$.cookie('sfe-application-state-palette-collapsed', true, {path: KOR.SFE.cookiePath});
} else if (mode === 'show') {
paletteResizer.removeClass('collapsed');
savedWidth = $.cookie('sfe-application-state-palette-width') || paletteDefaultWidth;
if (savedWidth > paletteMaxWidth) {
savedWidth = paletteMaxWidth;
}
$componentPalette.width(savedWidth);
// remove the palette collapse state cookie
$.cookie('sfe-application-state-palette-collapsed', null, {path: KOR.SFE.cookiePath});
}
// hide tab title for small sizes
if ($componentPalette.width() < 370) {
$componentPalette.find('.tab-title').hide();
} else {
$componentPalette.find('.tab-title').show();
}
viewableArea.width($(window).width() - $componentPalette.outerWidth(true) - paletteResizer.outerWidth(true) - 1);
// height handling
$componentPalette.height(viewableArea.height());
$('#component-palette-content').height(viewableArea.height() - $('#component-palette-head').outerHeight(true));
paletteResizer.height(viewableArea.height());
}
function sizeSiteFrame(ev) {
var displayDevice = $('#preview_displaydevice_select');
var storefrontIFrame = KOR.$(siteContentSelector);
viewableArea.height($(window).height() - KOR.$(headerPanelSelector).outerHeight() - ((KOR.$(controlPanelSelector).length !== 0) ? KOR.$(controlPanelSelector).outerHeight() : 3));
if (displayDevice.val() === null || displayDevice.val() === 'BROWSER') {
storefrontIFrame.removeClass('nonBrowserDefined');
storefrontIFrame.height(viewableArea.height());
storefrontIFrame.width('100%');
viewableArea.removeClass('nonBrowserDefined');
} else {
storefrontIFrame.addClass('nonBrowserDefined');
storefrontIFrame.width($('#widthbox').val());
storefrontIFrame.height($('#heightbox').val());
viewableArea.addClass('nonBrowserDefined');
}
displayViewableArea();
initDisplayDevice();
sizePreviewLayer();
}
function loadTinyMCE() {
$('textarea.sfe-html-editor').each(function() {
createEditor._config.id = $(this).attr('id');
if (!createEditor._config.id) {
createEditor._config.id = 'sfe-'.uId();
$(this).attr('id', createEditor._config.id);
}
createEditor(createEditor._config);
});
}
function loadDetailPanel(url, failStackFn) {
showDetailLoader();
$.cookie('sfe-application-state-panel-url_' + KOR.SFE.contentRepoUUID, url, {
path: KOR.SFE.cookiePath
});
currentDetailPanelUrl = url;
var urlWithParameters = url.split("?");
var urlString = urlWithParameters[0];
var urlParameters = "";
if (urlWithParameters[1] !== null) {
urlParameters = urlWithParameters[1];
}
$.ajax({
url: addLocaleParamToDetailPanelUrl(urlString),
type: "POST",
data: urlParameters,
complete: function() {
hideDetailLoader();
},
success: function(html) {
KOR.log('section update: ');
setDetailCallback(html, failStackFn);
},
error: function(jqXHR, textStatus, errorThrown) {
if (errorThrown == 'Unauthorized') {
handleUnauthorizedState(failStackFn);
}
}
});
}
function positionOverlay(duration) {
var dims = getOverlayDimensions();
var ov = getOverlay();
if (ov && dims) {
ov.css({
display: 'block'
});
var obj = $.extend(dims, {
opacity: 0.5
});
if (duration) {
ov.animate(obj, duration);
} else {
ov.css(obj);
}
obj = {
scrollTop: dims.top - $(sitePanel).height() / 2 + dims.height / 2,
scrollLeft: dims.left - $(sitePanel).width() / 2 + dims.width / 2
};
if (duration) {
$(sitePanel.document.documentElement).animate(obj, duration);
$(sitePanel.document.body).animate(obj, duration);
} else {
sitePanel.document.documentElement.scrollTop = obj.scrollTop;
sitePanel.document.documentElement.scrollLeft = obj.scrollLeft;
sitePanel.document.body.scrollTop = obj.scrollTop;
sitePanel.document.body.scrollLeft = obj.scrollLeft;
}
} else {
hideOverlay(duration);
}
}
function runFailedAuthentationStack() {
$.each(failedAuthentationStack, function(index, fn) {
fn();
});
failedAuthentationStack = [];
}
function detailFormInline(form, ev) {
ev.preventDefault();
showDetailLoader();
// trigger the tinyMCE value synchronization manually since it is not doing it automatically in some IE versions
if (tinyMCE.isIE) {
tinyMCE.triggerSave();
}
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
complete: function() {
hideDetailLoader();
},
success: function(html) {
KOR.log('section update from form: ');
//reload site frame if no errors and calls for a layout change
if (!isFormErrorMessage(html)) {
if (form.find('.kor-form-action').hasClass('sfe-layout-change')) {
updateDetailPanel = false;
if (currentComponentId !== null) {
$.cookie('sfe-application-state-component-id_' + KOR.SFE.contentRepoUUID, componentDetailObject[currentComponentId].treeId, {
path: KOR.SFE.cookiePath
});
} else {
$.cookie('sfe-application-state-component-id_' + KOR.SFE.contentRepoUUID, null, {
path: KOR.SFE.cookiePath
});
}
sitePanel.location.reload();
}
}
setDetailCallback(html);
}
});
return false;
}
function detailFormDialog(form, ev) {
ev.preventDefault();
var title = $('.kor-form-action').val();
var src = form.attr('action') + '?' + form.serialize();
KOR.showDetailDialog(title, src);
return false;
}
function highlightSelectedComponentInTree() {
if (currentComponentId) {
//set the current tree node
currentTreeNode = $('[data-component-tree-id="{{}}"]'.uInject(componentDetailObject[currentComponentId].treeId), KOR.$(componentTreeSelector));
currentTreeNode.addClass(activeComponentAnchorClass);
//set the current slot treeId that the current component resides in
if (componentDetailObject[currentComponentId].type !== 'Slot') {
var currentSlotTreeNode = currentTreeNode.closest('ul').prev('[data-component-id]');
var compObj = componentDetailObject[currentSlotTreeNode.attr('data-component-id')];
if (compObj && compObj.type === "Slot") {
currentSlotTreeId = compObj.treeId;
} else {
currentSlotTreeId = null;
}
}
}
}
/**
* Preview configuration functionality
*/
function togglePreviewLayer() {
var previewLayer = $('#sfe-configure-layer');
var previewTab = $('#design-preview');
previewLayer.slideToggle();
if (previewTab.hasClass('active')) {
cancelPreviewLayer(previewLayer);
}
previewTab.toggleClass('active');
}
function hidePreviewLayer() {
$('#sfe-configure-layer').css({
display: 'none'
});
$('#design-preview').removeClass('active');
}
function sizePreviewLayer() {
$('#sfe-configure-layer').css('max-height', $(window).height() - $('#masthead-wrapper').height() - 10);
}
function showPreviewLayerLoader() {
$('.sfe-preview-loading').css({
display: 'block'
});
}
function hidePreviewLayerLoader() {
$('.sfe-preview-loading').css({
display: 'none'
});
}
/*
* START: form default reset
*/
function cancelPreviewLayer(previewLayer) {
var form = $('form[data-form-default-check]', previewLayer);
form.each(function() {
this.reset();
});
}
$(document).on('reset', 'form[data-form-default-check]', function(e) {
var form = $(e.currentTarget);
setFormDefault(form);
return false;
});
function setFormDefault(el) {
$('[data-set-form-default-function]', el).each(function() {
var fName = $(this).data("set-form-default-function");
var fn = new Function("term", "return " + fName + "(term);");
fn(el);
});
}
/*
* END: form default reset
*/
/*
* START: system default reset
*/
function getSystemDefaultResetter() {
return $("#sfe-configure-layer-system-default-reset");
}
function updateSystemDefaultResetter(el) {
var systemDefaultResetter = getSystemDefaultResetter();
if (isSystemDefault(el)) {
systemDefaultResetter.attr("disabled", "disabled");
} else {
systemDefaultResetter.removeAttr("disabled");
}
}
function setSystemDefault(el) {
$('[data-set-system-default-function]', el).each(function() {
var fName = $(this).data("set-system-default-function");
var fn = new Function("term", "return " + fName + "(term);");
fn(el);
});
}
function isSystemDefault(el) {
var isSystemDefault = true;
$('[data-is-system-default-function]', el).each(function() {
var fName = $(this).data("is-system-default-function");
var fn = new Function("term", "return " + fName + "(term);");
if (!fn(el)) {
isSystemDefault = false;
}
});
return isSystemDefault;
}
$(document).on('change', 'form[data-system-default-check]', function(e) {
var el = $(e.currentTarget);
updateSystemDefaultResetter(el);
});
$(document).on('click', '#sfe-configure-layer-system-default-reset', function(e) {
var el = $(e.currentTarget);
var form = el.parents('form');
setSystemDefault(form);
form.submit();
});
/*
* END: system default reset
*/
/*
* START: fullsite preview trigger
*/
$(document).on('click', 'a[data-fullsite-preview]', function(e) {
var hrefPreview = $(e.target).attr('data-fullsite-preview');
var currentlyShownHref = document.getElementById("siteContent").contentWindow.location.href;
if ((currentlyShownHref !== null) && (/^(https?):\/\//i.test(currentlyShownHref))) {
hrefPreview = hrefPreview + "&PreviewTargetURL=" + encodeURIComponent(currentlyShownHref);
} else {
hrefPreview = hrefPreview + "&PreviewTargetURL=" + encodeURIComponent($("#sfe-preview-target-url-field").data("default-value"));
}
var viewableAreaHeight = viewableArea.height(); // ??
var viewableAreaWidth = viewableArea.width(); // ??
window.open(hrefPreview, '_blank', 'menubar=1,location=1,resizable=1,scrollbars=1,status=1,toolbar=1, width=' + viewableAreaWidth + ', height=' + viewableAreaHeight);
return false;
});
/*
* END: fullsite preview trigger
*/
function refreshPreviewSummaryLayer() {
var layer = $('#sfe-preview-summary-layer');
var previewSummaryRefreshUrl = layer.data('refreshurl');
if (previewSummaryRefreshUrl !== null) {
$.ajax({
type: 'GET',
url: previewSummaryRefreshUrl,
success: function(html) {
var tmpDOM = document.createElement('div');
tmpDOM.innerHTML = html;
layer.replaceWith($(tmpDOM).find('#sfe-preview-summary-layer'));
},
error: function() {
KOR.showErrorPreviewDialog();
}
});
}
}
function loadPreview(successFct) {
var configurationPreviewURL = $('#sfe-configure-layer-configuration-url').val();
if (configurationPreviewURL !== null) {
$.ajax({
type: 'POST',
url: configurationPreviewURL,
data: $("input[name^='transferablePrefix_']").serialize(),
success: function() {
successFct.call();
refreshPreviewSummaryLayer();
},
error: function() {
KOR.showErrorPreviewDialog();
}
});
} else {
successFct.call();
}
}
// make loadPreview available by event "loadPreview" at the body
$('body').on('loadPreview', function(event, successFct) {
successFct = successFct || $.noop;
loadPreview(successFct);
});
function submitPreviewForm(successFn) {
if (typeof successFn !== 'function') {
successFn = function(html) {
$('#design-preview').removeClass('active');
document.getElementById("siteContent").contentWindow.location.href = $('#sfe-preview-target-url-field').val();
};
}
var form = $('#PreviewWebform');
var layer = $('#sfe-configure-layer');
$('#sfe-preview-target-url-field').val(document.getElementById("siteContent").contentWindow.location.href);
showPreviewLayerLoader();
$.ajax({
type: 'POST',
data: form.serialize(),
url: form.attr('action'),
success: function(html) {
var tmpDOM = document.createElement('div');
tmpDOM.innerHTML = html;
layer.replaceWith($(tmpDOM).find('#sfe-configure-layer'));
if (FormValid) {
currentLocale = $(KOR.SFE.localeSwitchSelector).val();
loadPreview(successFn);
} else if ($('#sfe-configure-layer').is(':hidden')) {
togglePreviewLayer();
if (!$('#design-preview').hasClass('active')) $('#design-preview').addClass('active');
}
},
error: function() {
KOR.showErrorPreviewDialog();
}
});
return false;
}
// make submitPreviewForm available by event "submitPreviewForm" at the body
$('body').on('submitPreviewForm', function(event, successFct) {
submitPreviewForm(successFct);
});
function refreshPreviewForm() {
var form = $(this);
var layer = $('#sfe-configure-layer');
$('#sfe-preview-target-url-field').val(document.getElementById("siteContent").contentWindow.location.href);
var url = form.attr('action').replace("EditView-Update", "EditView-ChangeApplication");
showPreviewLayerLoader();
$.ajax({
type: 'POST',
data: form.serialize(),
url: url,
success: function(html) {
html = $(html);
var div = html.filter('div');
var other = html.not(div);
layer.empty().append(div.children()).append(other);
initDisplayDevice();
if ($('#sfe-configure-layer').is(':hidden')) {
togglePreviewLayer();
}
},
error: function() {
KOR.showErrorPreviewDialog();
}
});
return false;
}
function previewPageVariant() {
var targetUrlField = $('#sfe-preview-target-url-field');
targetUrlField.val(document.getElementById("siteContent").contentWindow.location.href);
$.ajax({
type: 'GET',
url: this.href, //source must be a link
success: function(html) {
$('#sfe-transferable-layer').replaceWith(html);
loadPreview(function(html) {
$('#design-preview').removeClass('active');
document.getElementById("siteContent").contentWindow.location.href = targetUrlField.val();
});
},
error: function() {
KOR.showErrorPreviewDialog();
}
});
return false;
}
/**
* private variables
*
* resizing functionality
*/
//var hash = KOR.getLocationHash(),
var activeComponentAnchorClass = 'sfe-active',
body = $('body'),
closedControlPanelClassName = 'sfe-panel-collapse-closed',
comments = {},
componentDetailObject = {},
componentDetailSelector = '#sfe-panel-edit',
componentDetailSectionsSelector = '#sfe-panel-edit .sfe-tabs',
componentDetailLinksSelector = '#sfe-panel-edit .sfe-links',
componentDetailContentSelector = '#sfe-container-edit .sfe-generic-wrapper',
componentDetailCommandsSelector = '#sfe-panel-edit-controls .sfe-button-bar',
componentTreeSelector = '#sfe-container-tree',
componentTreeContainerSelector = '#sfe-container-tree',
slotOverlayTemplate = 'slotOverlayTemplate',
componentOverlayTemplate = 'componentOverlayTemplate',
componentInspectorTemplate = 'componentInspectorTemplate',
componentTreeTemplate = 'componentTreeTemplate',
componentTreeItemTemplate = 'componentTreeItemTemplate',
componentTree = null,
controlPanelHideOnCloseSelector = '#sfe-panel-edit .sfe-tabs, #sfe-panel-edit .sfe-links, .sfe-control-bar>span',
controlPanelResizer = $('.sfe-control-bar-resizer'),
controlPanelSelector = '#sfe-control-panel',
controlPanelDefaultHeight = 200,
controlPanelCloseHeight = 40,
controlPanelCollapseSelector = '.sfe-panel-collapse-button',
editPanelContainerSelector = '#sfe-container-edit',
editPanelControlsSelector = '#sfe-panel-edit-controls',
currentComponentId = null,
currentTreeNode = null,
currentDetailPanelUrl = null,
currentSlotTreeId = null,
dataLinkTemplate = 'dataLinkTemplate',
detailAnchor = $('<a class="kor-detail-dialog"></a>').appendTo(body),
detailLoader = null,
detailPanelSelector = '#sfe-panel-edit',
dividerSelector = $('#sfe-panel-divider'),
errorMarkupIdentifier = '<!-- BEGIN TEMPLATE application/Error -->',
failedAuthentationStack = [],
formErrorMarkupIdentifier = 'class="error_box',
errorAnchor = $('<a class="kor-error-dialog"></a>').appendTo(body),
errorCreationAnchor = $('<a class="kor-error-creation-dialog"></a>').appendTo(body),
errorPreviewAnchor = $('<a class="kor-error-preview-dialog"></a>').appendTo(body),
headerPanelSelector = '#masthead',
inspector = null,
inInspectorMode = false,
inspectorPreviewing = null,
inspectorButtonOnClassName = 'sfe-inspector-button-on',
inspectorButtonSelector = '.sfe-inspector-button',
layoutButtonSelector = '.sfe-layout-button',
lastControlPanelHeight = null,
lastPaletteWidth = null,
loaderTemplate = 'loaderTemplate',
loadInitDetailPanel = ($.cookie('sfe-application-state-panel-url_' + KOR.SFE.contentRepoUUID) || null),
loginAnchor = $('<a class="kor-login-dialog"></a>').appendTo(body),
openedControlPanelClassName = 'sfe-panel-collapse-opened',
overlay = null,
reloadSiteFrameOnWizardExit = false,
sessionTimeoutMarkupIdentifier = '<div id="login"',
siteContentSelector = '#siteContent',
sitePanel = frames['siteContent'],
viewableArea = $('#viewable-area'),
currentLocale = null,
treePanelSelector = '#sfe-panel-tree',
updateDetailPanel = true,
paletteResizer = $('#palette-resizer'),
paletteCollapse = $('.palette-collapse'),
siteContentOverlay = $('#siteContentOverlay'),
waitingOverlay = $('#waitingOverlay');
/**
* KOR UI Component setup
*/
//editing error dialog
KOR.dialog('.kor-error-dialog', {
modalOpacity: 0.75,
content: null,
modalClose: false,
singletonOverlay: false,
overlayTemplate: 'errorDialogOverlayTemplate'
});
//creation error dialog
KOR.dialog('.kor-error-creation-dialog', {
modalOpacity: 0.75,
content: null,
modalClose: false,
singletonOverlay: false,
overlayTemplate: 'errorCreationDialogOverlayTemplate'
});
//preview error dialog
KOR.dialog('.kor-error-preview-dialog', {
modalOpacity: 0.75,
content: null,
modalClose: false,
singletonOverlay: false,
overlayTemplate: 'errorPreviewDialogOverlayTemplate'
});
//detail dialog
var detailDialog = (KOR.createClass(KOR.Dialog, {
modalOpacity: 0.75,
fixedPosition: false,
singletonOverlay: false,
overlayTemplate: 'dialogIframeOverlayTemplate',
populate: detailDialogPopulateHandler,
hide: detailDialogHideHandler
})).getInstanceOf('.kor-detail-dialog');
//login dialog
KOR.dialog('.kor-login-dialog', {
modalOpacity: 0.75,
content: null,
singletonOverlay: false,
overlayTemplate: 'loginDialogOverlayTemplate'
});
//detail tooltips
KOR.tip('.sfe-tip', {
overlayOffset: "0 -7px"
});
//login validation
KOR.Validator.LogInAjaxForm = KOR.createClass(KOR.Validator.Form, {
ajaxSubmit: true,
isAjaxSuccess: loginIsAjaxSuccessHandler,
ajaxSuccess: loginAjaxSuccessHandler,
ajaxFailure: loginAjaxFailureHandler
});
KOR.validator('#sfe-login-dialog-form', {
formClassObject: 'LogInAjaxForm'
});
//tree ui component
(KOR.createClass(KOR.Treemenu, {
viewSelector: '.sfe-toggle-view',
toggle: treeToggleHandler,
dragSelector: '[data-assignment-id]',
dropAction: treeDropActionHandler
})).getInstanceOf('.sfe-component-tree');
/**
*
*
* Display Device Selection in Preview Configuration Panel
*
*
*/
$(document).on('change', '#preview_displaydevice_select', function(e) {
var selected = $(this).find('option:selected');
var width = selected.data('display-device-width');
var height = selected.data('display-device-height');
if ($(this).val() === "BROWSER") {
$('#widthbox').val(viewableArea.width());
$('#heightbox').val(viewableArea.height());
} else if ($(this).val() === "MANUAL") {
$('#widthbox').val(width);
$('#heightbox').val(height);
} else {
$('#widthbox').val(width);
$('#heightbox').val(height);
}
});
$(document).on('keypress', '#widthbox', function(e) {
$('#preview_displaydevice_select option[value="MANUAL"]').attr("selected", "selected");
});
$(document).on('keypress', '#heightbox', function(e) {
$('#preview_displaydevice_select option[value="MANUAL"]').attr("selected", "selected");
});
function initDisplayDevice() {
if ($('#preview_displaydevice_select').val() === 'BROWSER') {
$('#widthbox').val(viewableArea.width());
$('#heightbox').val(viewableArea.height());
}
}
/**
*
*
* Designer init Setup Section
*
*
*/
$(siteContentSelector).on('load', contentPageLoadHandler);
//load site iframe with site url
loadPreview(function() {
$(siteContentSelector).attr('src', KOR.SFE.URLS.application);
});
//set the initial state for the ui
//check if storefront editing functionality is available
if (KOR.$(controlPanelSelector).length > 0) {
setUIState();
//else fit only the preview iframe size
} else {
sizeSiteFrame();
}
// show the size of the iframe
displayViewableArea();
// set display device to browser size if required
initDisplayDevice();
///**
// * Event Registration
// */
$(window).on('resize', resizeHandler);
$(document).on('mouseup', stopDraggingHandler);
/**
* delegated events that effect ui changes
*/
////toggle control panel events
$(document).on('click', ' .' + closedControlPanelClassName, showControlPanelHandler);
$(document).on('click', ' .' + openedControlPanelClassName, hideControlPanelHandler);
////turns inspector on and off
$(document).on('click', inspectorButtonSelector, toggleInspectorHandler);
// turns layout mode on and off
$(document).on('click', layoutButtonSelector, toggleLayoutMode);
// resize handler
dividerSelector.on('mousedown', controlPanelSplitHandler);
controlPanelResizer.on('mousedown', controlPanelResizeHandler);
// palette handler
paletteResizer.on('mousedown', paletteResizeHandler);
paletteCollapse.on('click', togglePaletteHandler);
//login dialog submit handler
$(document).on('click', '#sfe-login-dialog-button', loginDialogClickHandler);
//enable the revert button for changes in inputs of config params
$(componentDetailCommandsSelector).on("cpo-change", function(){
$('a[data-sfe-actionbutton*="sfe-start-revert"]').removeClass('disabled-button');
});
/**
* preview panel toggle date/time input visbility
*/
$(document).on('change', '.sfe-preview-pca-datetime-make-fixed', function() {
$('.sfe-preview-pca-datetime').show();
$('#fixed_date_time_radio').removeClass("last");
});
$(document).on('change', '.sfe-preview-pca-datetime-make-current', function() {
$('.sfe-preview-pca-datetime').hide();
$('#fixed_date_time_radio').addClass("last");
});
/**
* delegated events that cause ajax events or url reloads
*/
//hijax handler for inline actions
$(document).on('submit', componentDetailContentSelector + ' form', detailFormSubmitHandler);
//anchor hijax for inline links or dialog links
$(document).on('click', 'a.sfe-action-inline', inlineAnchorClickHandler);
$(document).on('click', 'a.sfe-action-dialog', dialogAnchorClickHandler);
$(document).on('click', 'a.sfe-action-disable, button.sfe-action-disable, input.sfe-action-disable', disableClickHandler);
//section a tag hijax
$(document).on('click', componentDetailSectionsSelector, reloadDetailPanelHandler);
//highlights and loads component into details panel
$(document).on('click', '[data-component-id]', componentClickHandler);
//hijack compoment links in slots and open it in the tree
$(document).on('click', '#sfe-container-edit .sfe-action-totree', componentProxyToTreeClickHandler);
//external form action triggers
$(document).on('click', '[data-sfe-actionbutton]', clickProxyHandler);
//form action hidden field for inline and dialog actions
$(document).on('click', 'button.sfe-action-inline, button.sfe-action-dialog, input.sfe-action-inline, input.sfe-action-dialog', formActionClickHandler);
//empty the cookies and reload the application
$(document).on('click', '.sfe-reset-button', applicationResetHandler);
//toggle preview layer
$(document).on('click', '#design-preview', togglePreviewLayer);
//close preview layer
$(document).on('click', '#sfe-configure-layer-cancel', togglePreviewLayer);
//submit preview configuration
$(document).on('submit', '.sfe-configuration-layer-form', submitPreviewForm);
// change preview configuration
$(document).on('refresh', '.sfe-configuration-layer-form', refreshPreviewForm);
//register page variant preview
$(document).on('click', '.sfe-preview-pagelet', previewPageVariant);
})(jQuery);
// legacy Back Office function
function selectAll(formName, partOfFormElementName, selectLayerID, clearLayerID) {
var formElements = document.forms[formName].elements;
var select = true;
if (document.getElementById(selectLayerID).style.display === "none") {
select = false;
}
for (var i = 0; i < formElements.length; i++) {
if ((-1 !== formElements[i].name.indexOf(partOfFormElementName)) &&
(formElements[i].disabled === false) &&
((formElements[i].type === "checkbox") ||
(formElements[i].type === "radio"))) {
formElements[i].checked = select;
}
}
if (select) {
document.getElementById(selectLayerID).style.display = "none";
document.getElementById(clearLayerID).style.display = "block";
} else {
document.getElementById(selectLayerID).style.display = "block";
document.getElementById(clearLayerID).style.display = "none";
}
}
|
module.exports = {
name: 'model',
create: 'each',
dependencies: [],
allowedParents: ['$root'],
allowedChildren: ['field', 'comment'],
autoAddedChildGears: {
'_createdAt.field': {
type: 'date',
'.comment': {text: 'When record got created'}
},
'_createdBy.field': {
type: 'text',
'.comment': {text: 'Username of person who created record'}
},
'_modifiedAt.field': {
type: 'date',
'.comment': {text: 'When record last got modified'}
},
'_modifiedBy.field': {
type: 'text',
'.comment': {text: 'Username of person who last modified record'}
},
"_createdAtIdx#.index": {
"keys": {"_createdAt": 1}
},
"_createdByIdx#.index": {
"keys": {"_createdBy": 1}
},
"_modifiedAtIdx#.index": {
"keys": {"_modifiedAt": 1}
},
"_modifiedByIdx#.index": {
"keys": {"_modifiedBy": 1}
}
}
};
|
const head = require("./config/head.js");
const plugins = require("./config/plugins.js");
const themeConfig = require("./config/themeConfig.js");
const { penName, title } = require("./common/info");
module.exports = {
// 使用npm包主题 vuepress-theme-vdoing
theme: "vdoing",
// 仓库地址
base: "/",
head,
markdown: {
lineNumbers: true, // 显示代码块的行号
extractHeaders: ["h2", "h3", "h4"], // 支持 h2、h3、h4 标题
},
// 多语言支持
locales: {
"/": {
lang: "zh-CN",
title: penName + title,
description:
"无善无恶心之体,有善有恶意之动,知善知恶是良知,为善去恶是格物。",
},
},
plugins,
themeConfig,
};
|
import axios from 'axios';
import { fetchRestaurantById } from './RestaurantActions';
function setFavorites(favorites) {
return {
type: 'SET_FAVORITES',
favorites,
};
}
function appendFavorite(restaurant) {
return {
type: 'APPEND_FAVORITE',
restaurant,
};
}
function removeFavorite(restaurantId) {
return {
type: 'REMOVE_FAVORITE',
restaurantId,
};
}
export const fetchFavorites = () => (dispatch) =>
axios.get('/api/v1/favorite')
.then(
(res) => {
const FavoritesIds = res.data.favorites;
const favoritesPromises = FavoritesIds.map((id) => dispatch(fetchRestaurantById(id))
.then((restaurant) => restaurant));
Promise.all(favoritesPromises)
.then((favorites) => dispatch(setFavorites(favorites)));
}
)
.catch(
);
export const toggleFavorite = (isFavorite, restaurantId) => (dispatch) => {
if (!isFavorite) {
axios.post(`/api/v1/favorite/${restaurantId}`).then(
() => {
dispatch(fetchRestaurantById(restaurantId)).then(
(restaurant) => dispatch(appendFavorite(restaurant))
);
}
);
} else {
axios.delete(`/api/v1/favorite/${restaurantId}`).then(
() => {
dispatch(removeFavorite(restaurantId));
}
);
}
};
|
import { LOAN_REQUEST, LOAN_SUCCESS, LOAN_FAILURE } from './loan-constants';
const initialState = {
isFetching: false,
loanDetails: [],
totalRecords: '',
};
const loan = (state = initialState, action) => {
switch (action.type) {
case LOAN_REQUEST:
return {
...state,
isFetching: true,
loanDetails: [],
};
case LOAN_FAILURE:
return {
...state,
isFetching: false,
loanDetails: [],
};
case LOAN_SUCCESS:
return {
...state,
isFetching: false,
loanDetails: action.data,
totalRecords: action.totalRecords,
};
default:
return state;
}
};
export default loan;
|
//This js file contains functions that use local storage
//This function writes a string to local storage
function writeToStorage(name, value){
localStorage.setItem(name, value);
}
//This function reads a string from local storage
function readFromStorage(name){
//This variable will hold the item retrieved from storage
var storedItem;
storedItem = localStorage.getItem(name);
return (storedItem);
}
//This function removes a value from local storage
function clearStorage(name){
localStorage.removeItem(name);
}
|
window.onload = function(){
/*****************头部****************/
//头部二维码
$(".app_down").hover(function(){
$(".header_code").stop().slideDown();
},function(){
$(".header_code").stop().slideUp();
})
//头部城市选择列表
$(".city_select").hover(function(){
$(".select_city").stop().slideDown();
},function(){
$(".select_city").stop().slideUp();
})
$(".select_city li a").click(function(){
var str = $(".city_select span").html();
$(".city_select span").html($(this).html());
$(this).html(str);
});
//头部消息
$(".message").hover(function(){
$(".header_info").stop().slideDown();
},function(){
$(".header_info").stop().slideUp();
})
//判断用户是否登录
var uname = localStorage.getItem("uname");
if(uname){
$(".login_register .login").css("display","none");
$(".login_register .register").css("display","none");
$(".login_register .myname").html(uname);
//用户
$(".login_register").hover(function(){
$(".login_register ul").stop().slideDown();
},function(){
$(".login_register ul").stop().slideUp();
})
}else{
$(".car_not_pro").css("display","block");
}
$(".login_register ul .exit").click(function(){
$(".login_register .myname").html("");
$(".login_register .login").css("display","inline-block");
$(".login_register .register").css("display","inline-block");
$(".login_register ul").css("display","none");
localStorage.setItem("uname","");
window.location.reload();
});
//添加商品信息
var goodsinfo = localStorage.getItem(uname+"goShopping");
if(goodsinfo){//如果商品信息存在,添加
var str = localStorage.getItem(uname+"goShopping");
if(str != "[]"){
$(".content_box").css("display","block");
$(".total").css("display","block");
}else{
$(".car_not_pro").css("display","block");
$(".content_box").css("display","none");
$(".total").css("dispaly","none");
}
//购物车商品数量的显示
var count = 0;
var goodsArr = JSON.parse(goodsinfo);
if(str=="[]"){
$(".cat span").css("display","none");
}else{
for(var i=0;i<goodsArr.length;i++){
count += parseInt(goodsArr[i].num);
}
$(".cat span").css("display","block");
$(".cat span").html(count);
}
$.ajax({
type:"post",
url:"../php/car.php",
success:function(res){
$arr = JSON.parse(res);
var html = "";
for(var i=0;i<goodsArr.length;i++){
for(var j=0;j<$arr.length;j++){
if(goodsArr[i].name == $arr[j].name){
html+=`<tr>
<td class="goods_img">
<input type="checkbox" class="sel"/>
<a href="#"><img src="../images/${$arr[j].carImg}.jpg"/></a>
</td>
<td class="goods_cake">
<div>
<h4><a href="#">${$arr[j].name}</a></h4>
<span class="spec">规格:<span>2.0磅</span></span>
<span class="goods_laid">
<i></i>
赠送
<ins> 10 </ins>
套餐具
</span>
</div>
</td>
<td class="select_birthday">
<div class="select_card">
<span>选择生日牌</span>
<i></i>
<ul>
<li>国庆节快乐</li>
<li>生日快乐</li>
<li>Happy Birthday</li>
<li>节日快乐</li>
</ul>
</div>
</td>
<td class="cake_price">¥${$arr[j].price}</td>
<td class="cake_num">
<div class="number">
<input type="button" class="reduce"/>
<input type="text" class="tex" value="${goodsArr[i].num}"/>
<input type="button" class="add"/>
</div>
</td>
<td class="money">¥${goodsArr[i].num*$arr[j].price}</td>
<td class="delete_cake">
<a href="javascript:;">
<i></i>
</a>
</td>
</tr>`;
}
}
}
$(".tbody_ul table").html(html);
//点击-的时候数量减一,点击+的时候数量加1(当数量减到1的时候,这个按钮就不能在点击了);后面的总价要跟随着改变,localstorg里面的uname+"shopping"数据也要跟随着改变。购物车的显示也要变化
//点击-的时候数量减1
$(".reduce").click(function(){
var val = $(this).parent().parent().find(".tex").val();
//当数量为1时,不能再继续减
if(val==1){
$(this).parent().parent().find(".tex").val(1);
}else{
//否则,数量就减1
$(this).parent().parent().find(".tex").val(val-1);
}
var sum = $(this).parent().parent().find(".tex").val()*$(this).parent().parent().parent().find(".cake_price").html().split("¥")[1];
var sumStr = "¥"+sum;
$(this).parent().parent().parent().find(".money").html(sumStr);
//localstorage的变化
var nameS = $(this).parent().parent().parent().find("h4 a").html();
var goodsInfo = localStorage.getItem(uname+"goShopping");
goodsArr = JSON.parse(goodsInfo);
for(var i=0;i<goodsArr.length;i++){
if(goodsArr[i].name == nameS){
goodsArr[i].num = $(this).parent().parent().find(".tex").val();
}
}
var goodsStr = JSON.stringify(goodsArr);
localStorage.setItem(uname+"goShopping",goodsStr);
//头部购物车数量的显示
var quantity = 0;
var nowGoods = localStorage.getItem(uname+"goShopping");
var nowGoodsArr = JSON.parse(nowGoods);
if(nowGoods=="[]"){
$(".cat span").css("display","none");
}else{
for(var i=0;i<nowGoodsArr.length;i++){
quantity += parseInt(nowGoodsArr[i].num);
}
$(".cat span").html(quantity);
}
//总金额的改变
var total = 0;
$(".sel").each(function(index,item){
if($(item).prop("checked")==true){
total += parseInt($(item).parent().parent().find(".money").html().split("¥")[1]);
$(".sum_total span").html(total);
}
})
})
//点击+的时候数量要+1
$(".add").click(function(){
var html = parseInt($(this).parent().parent().find(".tex").val());
$(this).parent().parent().find(".tex").val(html+1);
//改变总金额的html
var sumHtml = $(this).parent().parent().find(".tex").val()*$(this).parent().parent().parent().find(".cake_price").html().split("¥")[1];
var sumStr = "¥"+sumHtml;
$(this).parent().parent().parent().find(".money").html(sumStr);
//改变localhost的数据
//获取当前的name
var nameStr = $(this).parent().parent().parent().find("h4 a").html();
var goodInfo = localStorage.getItem(uname+"goShopping");
var goodArr = JSON.parse(goodInfo);
for(var i=0;i<goodArr.length;i++){
if(goodArr[i].name == nameStr){
goodArr[i].num = $(this).parent().parent().find(".tex").val();
}
}
var jsonStr = JSON.stringify(goodArr);
localStorage.setItem(uname+"goShopping",jsonStr);
//头部购物车显示的改变
var goods = localStorage.getItem(uname+"goShopping");
var goodJson = JSON.parse(goods);
if(goods=="[]"){
$(".cat span").css("display","none");
}else{
var numTotal = 0;
for(var i=0;i<goodJson.length;i++){
numTotal += parseInt(goodJson[i].num);
}
$(".cat span").html(numTotal);
}
//总金额的改变
var total = 0;
$(".sel").each(function(index,item){
if($(item).prop("checked")==true){
total += parseInt($(item).parent().parent().find(".money").html().split("¥")[1]);
$(".sum_total span").html(total);
}
})
})
//点击页面中的x的时候整行的数据进行删除,并且数据库里的也要进行删除,然后购物车的显示也要随之改变
$(".delete_cake").click(function(){
var sname = $(this).parent().find("h4 a").html();
//localstorage的数据进行改变
var goodsinfo = localStorage.getItem(uname+"goShopping");
var goodsarr = JSON.parse(goodsinfo);
for(var i=0;i<goodsarr.length;i++){
if(goodsarr[i].name == sname){
goodsarr.splice(sname,1);
}
}
var str = JSON.stringify(goodsarr);
localStorage.setItem(uname+"goShopping",str);
//头部的购物车显示要改变
var goods = localStorage.getItem(uname+"goShopping");
var goodJson = JSON.parse(goods);
if(goods=="[]"){
$(".cat span").css("display","none");
}else{
var numTotal = 0;
for(var i=0;i<goodJson.length;i++){
numTotal += parseInt(goodJson[i].num);
}
$(".cat span").html(numTotal);
}
//整行tr删除
$(this).parent().remove();
var str = localStorage.getItem(uname+"goShopping");
if(str == "[]"){
$(".car_not_pro").css("display","block");
$(".content_box").css("display","none");
$(".total").css("display","none");
}
var sum = 0;
$(".sel").each(function(index,item){
if($(item).prop("checked")==false){
$(".sum_total span").html(0);
}else{
sum += parseInt($(item).parent().parent().find(".money").html().split("¥")[1]);
$(".sum_total span").html(sum);
}
})
})
//点击全部清空,内容全删除
$(".all_empty").click(function(){
$(".tbody_ul table").html("");
localStorage.setItem(uname+"goShopping","");
$(".car_not_pro").css("display","block");
$(".content_box").css("display","none");
$(".total").css("display","none");
//头部的购物车显示要改变
$(".cat span").css("display","none");
})
//选择生日牌
$(".select_card").hover(function(){
$(this).parent().find("ul").css("display","block");
$(this).parent().find("ul li").hover(function(){
$(this).css("color","#684029").siblings().css("color","#D8C3AD");
})
$(this).parent().find("ul li").click(function(){
var str = $(this).html();
$(this).parent().parent().find("span").html(str);
})
},function(){
$(this).parent().find("ul").css("display","none");
})
//实现全选,全不选以及总价的改变
$("#allSel").click(function(){
$(".sel").prop("checked",$(this).prop("checked"));
var flag = true;
var sum = 0;
$(".sel").each(function(index,item){
if($(item).prop("checked")==true){
sum += parseInt($(item).parent().parent().find(".money").html().split("¥")[1]);
$(".sum_total span").html(sum);
}else{
$(".sum_total span").html(0);
}
})
})
$(".sel").click(function(){
var flag = true;
var sum = 0;
$(".sel").each(function(index,item){
if($(item).prop("checked")==false){
flag = false;
$(".sum_total span").html(0);
}else{
sum += parseInt($(item).parent().parent().find(".money").html().split("¥")[1]);
}
$(".sum_total span").html(sum);
})
if(flag){
$("#allSel").prop("checked",true);
}else{
$("#allSel").prop("checked",false);
}
})
}
})
}else{
$(".car_not_pro").css("display","block");
}
}
|
import React, { Component } from 'react';
import Card from "./components/Card";
import Wrapper from "./components/Wrapper";
import Header from "./components/Header";
import Navbar from "./components/Navbar";
import instruments from "./instruments.json";
import './App.css';
class App extends Component {
// Setting this.state.instruments to the instruments json array
state = {
instruments,
score: 0,
highScore: 0
};
gameOver = () => {
if (this.state.score > this.state.highScore) {
this.setState({ highScore: this.state.score}, function() {
console.log(this.state.highScore);
});
}
this.state.instruments.forEach(card => {
card.count = 0;
});
alert(`Game Has Ended! \nscore: ${ this.state.score}`);
this.setState({ score: 0});
return true;
}
clickCount = id => {
this.state.instruments.find((o, i) => {
if(o.id === id) {
if(instruments[i].count === 0) {
instruments[i].count = instruments[i].count + 1;
this.setState({ score: this.state.score + 1}, function() {
console.log(this.state.score);
});
this.state.instruments.sort(() => Math.random() - 0.5)
return true;
} else {
this.gameOver();
}
}
});
}
render() {
return (
<div>
<Navbar
score={ this.state.score}
highScore={ this.state.highScore }
/>
<Header/>
<Wrapper>
{this.state.instruments.map(card => (
<Card
clickCount={ this.clickCount }
id={ card.id }
key={ card.key }
image={card.image}
/>
))}
</Wrapper>
</div>
);
}
};
export default App;
|
import RegionsButton from "./RegionsButton";
export default RegionsButton;
|
/*
* ForumPage Messages
*
* This contains all the text for the ForumPage component.
*/
import { defineMessages } from 'react-intl'
export default defineMessages({
VoterPlaceholder: {
id: 'ProxyPage VoterPlaceholder',
defaultMessage: '请输入您投票的账户名'
},
StatusText: {
id: 'ForumVotePage StatusText',
defaultMessage: '请输入帖子名称'
},
VoterLabel: {
id: 'ProxyPage VoterLabel',
defaultMessage: '投票账户'
},
ForumVoteFirst: {
id: 'ForumVotePage ForumVoteFirst',
defaultMessage: '步骤1/3:论坛投票'
},
ProxyScatterHelp: {
id: 'ProxyPage ProxyScatterHelp',
defaultMessage: '注:使用Scatter将使用已登录的账号签名'
},
LabelApprove: {
id: 'ProxyPage LabelApprove',
defaultMessage: '赞成'
},
LabelAgaist: {
id: 'ProxyPage LabelAgaist',
defaultMessage: '反对'
},
ProposalList: {
id: 'ForumVotePage ProposalList',
defaultMessage: '提案列表'
},
ProposalListFounder: {
id: 'ForumVotePage ProposalListFounder',
defaultMessage: '发起者'
},
ProposalListCreatedTime: {
id: 'ForumVotePage ProposalListCreatedTime',
defaultMessage: '创建时间'
},
ProposalListExpiredTime: {
id: 'ForumVotePage ProposalListExpiredTime',
defaultMessage: '过期时间'
},
ProposalListAgreee: {
id: 'ForumVotePage ProposalListAgreee',
defaultMessage: '赞成'
},
ProposalListVoter: {
id: 'ForumVotePage ProposalListVoter',
defaultMessage: '投票者'
},
ProposalListAginst: {
id: 'ForumVotePage ProposalListAginst',
defaultMessage: '反对'
},
ProposalListVoterQuantity: {
id: 'ForumVotePage ProposalListVoterQuantity',
defaultMessage: '按投票者数量排序'
},
ProposalListExpiredSort: {
id: 'ForumVotePage ProposalListExpiredSort',
defaultMessage: '按过期时间排序'
},
ProposalListCreatedSort: {
id: 'ForumVotePage ProposalListCreatedSort',
defaultMessage: '按创建时间排序'
}
})
|
// #!include Store.js
/********* Devices in a location Store ****/
var LocationDevicesStore = function () {
// NOT tested
ReactStore.call(this);
// @_devices = {'locationId': [<device>] }
this._devices = {};
this._DEVICES_CHANGE = '1';
dispatcher.register(this._pullDevices.bind(this));
};
LocationDevicesStore.prototype = Object.assign({},ReactStore.prototype);
LocationDevicesStore.prototype._generateRequestUrl = function(locationId) {
var url = '/api/location/'+locationId+'/device';
return url;
};
LocationDevicesStore.prototype._pullDevices = function(action) {
var locationId = Actions.extractLocationDevicesActionData(action);
if (locationId == null) {
return ;
}
var url = this._generateRequestUrl(locationId);
var context = {
'locationDevicesStore': this,
'locationId': locationId
};
$.ajax(url, {
'context': context,
'contentType': 'application/json',
'dataType': 'json',
'method': 'GET'
}).done(function(data, textStatus, jqxhr) {
var locationDevicesStore = this['locationDevicesStore'];
var devices = locationDevicesStore._devices;
var locationId = this['locationId'];
if (jqxhr.status == 200) {
devices[locationId] = data['devices'];
locationDevicesStore._notifyCallbacks(locationDevicesStore._DEVICES_CHANGE);// FIX ME
console.log('LocationDevicesStore get data successfully');
} else {
console.log('LocationDevicesStore fail to get data');
}
});
};
LocationDevicesStore.prototype.registerDevicesChangeCallback = function(cb) {
return this._registerCallback(cb, this._DEVICES_CHANGE);
};
LocationDevicesStore.prototype.unregisterDevicesChangeCallback = function(index) {
return this._unregisterCallback(index, this._DEVICES_CHANGE);
};
LocationDevicesStore.prototype.getDevicesByLocationId = function(id) {
var allDevices = this._devices[id];
if (!allDevices) {
return [];
}
var devices = _.map(allDevices, function(dev) {
return _.clone(dev);
});
return devices;
};
var locationDevicesStore = new LocationDevicesStore();
|
import Citas from './classes/citas.js';
import UI from './classes/UI.js';
import {
mascotaInput,
propietarioInput,
telefonoInput,
fechaInput,
horaInput,
sintomasInput,
formulario,
} from './selectores.js'
const administrarCitas = new Citas();
const ui = new UI(administrarCitas);
let editando = false;
export let DB;
const citaObj = {
mascota: '',
propietario: '',
telefono: '',
fecha: '',
hora:'',
sintomas: ''
}
export function datosCita(e) {
// console.log(e.target.name) // Obtener el Input
citaObj[e.target.name] = e.target.value;
}
export function nuevaCita(e) {
e.preventDefault();
const {mascota, propietario, telefono, fecha, hora, sintomas } = citaObj;
// Validar
if( mascota === '' || propietario === '' || telefono === '' || fecha === '' || hora === '' || sintomas === '' ) {
ui.imprimirAlerta('Todos los mensajes son Obligatorios', 'error')
return;
}
if(editando) {
// Estamos editando
administrarCitas.editarCita( {...citaObj} );
// Editar en indexedDB
const transaction = DB.transaction(['citas'],'readwrite');
const objectStore = transaction.objectStore('citas');
objectStore.put(citaObj);
transaction.oncomplete = () =>{
ui.imprimirAlerta('Guardado Correctamente');
formulario.querySelector('button[type="submit"]').textContent = 'Crear Cita';
editando = false;
}
transaction.onerror = ()=>{
console.log('error')
}
} else {
// Nuevo Registro
// Generar un ID único
citaObj.id = Date.now();
// Añade la nueva cita
administrarCitas.agregarCita({...citaObj});
// Insertar registro en IndexedDB
const transaction = DB.transaction(['citas'],'readwrite');
const objectStore = transaction.objectStore('citas');
objectStore.add(citaObj);
transaction.oncomplete = function(){
// Mostrar mensaje de que todo esta bien...
ui.imprimirAlerta('Se agregó correctamente')
}
}
// Imprimir el HTML de citas
ui.imprimirCitas();
// Reinicia el objeto para evitar futuros problemas de validación
reiniciarObjeto();
// Reiniciar Formulario
formulario.reset();
}
export function reiniciarObjeto() {
// Reiniciar el objeto
citaObj.mascota = '';
citaObj.propietario = '';
citaObj.telefono = '';
citaObj.fecha = '';
citaObj.hora = '';
citaObj.sintomas = '';
}
export function eliminarCita(id) {
const transaction = DB.transaction(['citas'],'readwrite');
const objectStore = transaction.objectStore('citas');
objectStore.delete(id);
transaction.oncomplete = () =>{
ui.imprimirCitas()
}
transaction.onerror = () =>{
console.log('error');
}
}
export function cargarEdicion(cita) {
const {mascota, propietario, telefono, fecha, hora, sintomas, id } = cita;
// Reiniciar el objeto
citaObj.mascota = mascota;
citaObj.propietario = propietario;
citaObj.telefono = telefono;
citaObj.fecha = fecha
citaObj.hora = hora;
citaObj.sintomas = sintomas;
citaObj.id = id;
// Llenar los Inputs
mascotaInput.value = mascota;
propietarioInput.value = propietario;
telefonoInput.value = telefono;
fechaInput.value = fecha;
horaInput.value = hora;
sintomasInput.value = sintomas;
formulario.querySelector('button[type="submit"]').textContent = 'Guardar Cambios';
editando = true;
}
export function crearDB(){
const crearDB = window.indexedDB.open('citas',1);
crearDB.onerror = function(){
console.log('Error')
}
crearDB.onsuccess = function(){
console.log('Base de datos Creado')
DB = crearDB.result;
ui.imprimirCitas();
}
crearDB.onupgradeneeded = function(e){
const db = e.target.result;
const objectStore = db.createObjectStore('citas',{
keyPath: 'id',
autoIncrement: true
});
objectStore.createIndex('mascota','mascota',{unique:false});
objectStore.createIndex('propietario','propietario',{unique:false});
objectStore.createIndex('telefono','telefono',{unique:false});
objectStore.createIndex('fecha','fecha',{unique:false});
objectStore.createIndex('hora','hora',{unique:false});
objectStore.createIndex('sintomas','sintomas',{unique:false});
objectStore.createIndex('id','id',{unique:true});
}
}
|
var excelTables = function(config) {
return function (file, filename, done) {
if (typeof file.table === "string"){
for (var i = 0; i < files.length; i++) {
console.log(files[i].filename)
};
/*alasql(makeQry(file.table, file.select, file.additional),
[],function(data){
strTbl = makeArray(data);
strTmp = file.contents.toString();
strTmp += "\n" + strTbl;
file.contents = new Buffer(strTmp);
done();
});*/
}
done();
};
};
|
require('dotenv').config();
const { start, dispatch, stop, spawnStateless, spawn, query, configurePersistence, spawnPersistent } = require("nact");
const { PostgresPersistenceEngine } = require("nact-persistence-postgres");
const system = start(
configurePersistence(
new PostgresPersistenceEngine(
process.env.DB_URL,
)
)
);
const delay = (time) => new Promise((res) => setTimeout(res, time));
// minimal complete verifiable example:
const persistentSum = spawnPersistent(
system,
async (total = 0, num = 0, ctx) => {
console.log(num); // never gets called?
if (!ctx.recovering && ctx.persist) {
await ctx.persist(num);
}
return total + num;
},
"persistentsum", // persistence key
"persistentsum", // actor name
);
for (let num of [1, 2, 3, 4, 5]) {
dispatch(persistentSum, num);
}
(async function() {
// wait for 5 seconds just in case
await delay(5_000);
stop(system);
})();
|
export const REQ_LOADING = 'REQ_LOADING'
export const REQ_SUCCESS = 'REQ_SUCCESS'
export const REQ_FAIL = 'REQ_FAIL'
export const REGISTER_USER = 'REGISTER_USER'
|
"use strict";
var _config = require("./../config");
var _config2 = _interopRequireDefault(_config);
var _path = require("path");
var _path2 = _interopRequireDefault(_path);
var _getTemplate = require("../utils/getTemplate");
var _getTemplate2 = _interopRequireDefault(_getTemplate);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var storePath = _config2.default.absPaths.storePath;
var reducerPath = _config2.default.absPaths.rootReducerPath;
module.exports = {
description: 'Create redux store configuration',
prompts: [],
actions: function actions(data) {
var actions = [];
if (!_config2.default.isDirExist(storePath)) {
data.releativeStoreToReducerPath = _config2.default.prepareRelativePath(_path2.default.relative(storePath, reducerPath));
actions.push({
type: 'add',
path: storePath + 'configure-store.js',
templateFile: (0, _getTemplate2.default)('index', 'store')
});
}
return actions;
}
};
|
// This file is full of stuff that the program needs to know to make a new game
// World (terrain, time, etc)
const blockSizeCm = 50;
const mapCols = 150;
const dirtBlockSoundNames = {
onExcavate : 'gravel'
}
const stoneBlockSoundNames = dirtBlockSoundNames;
const bedrockSoundNames = {
onHit : 'clang'
};
const seaSoundNames = {};
const minTerrainHeight = 20;
const maxTerrainHeight = 27;
const startTerrainHeight = 24;
const startStoneDepth = 11;
const maxStoneDepth = 18;
const minStoneDepth = 4;
const hillyness = 0.3;
const dirtBlockStrength = 15;
const stoneBlockStrength = 30;
const dirtBlockStrengthRechargeRate = 0.1;
const stoneBlockStrengthRechargeRate = 0.1;
const coalChance = 1/10;
const boarChance = 1/15;
const ratChance = 1 / 12;
const gameTimeIncrement = 1/18000;
const gameBgImageNames = 'bgImage';
const gravityStrength = 0.5;
// Character
const characterName = 'Pete';
const characterStartPos = new p5.Vector(0, -startTerrainHeight * blockSizeCm);
const characterSizeCm = new p5.Vector(30, 50);
const characterSpeed = 3;
const characterJumpStrength = 7;
const characterMaxHealth = 100;
const characterHealRate = 0.02;
const characterMaxStamina = 100;
const characterOnDie = () => {
noLoop();
document.write('<h1>R.I.P. You died!');
}
const characterImageNames = {
left : 'characterIdle',
right : 'characterIdle',
up : 'characterIdle',
down : 'characterIdle'};
const characterSoundNames = {
onDamageTaken : 'characterDamageTaken',
onDie : 'sadTrombone'
}
// Wild animals
const wildAnimalSpawnChances = {
'boar' : 1 / (60 * 30),
'rat' : 1 / (60 * 15)
};
const createWildAnimalFunctions = {
'boar' : pos => new Boar(pos, gravityStrength),
'rat' : pos => new Rat(pos, gravityStrength)
};
const maxWildAnimalAmounts = {
'boar' : 25,
'rat' : 50
}
const wildAnimalOnDieFuncs = {
'boar' : () => {},
'rat' : () => {}
}
const oldestCompatibleVersion = 27;
const crntVersion = 27;
const mapSectionWidthCm = 100;
const mapSectionOverlapCm = 100;
const mapSectionXRanges = [];
// Make lower bound
mapSectionXRanges.push(new Range(-10000, 0));
// Generate a bunch of overlapping map sections for collision checking
for (var i = 0; i < mapCols * blockSizeCm / mapSectionWidthCm; i ++) {
mapSectionXRanges.push(new Range(i * mapSectionWidthCm - mapSectionOverlapCm,
(i + 1) * mapSectionWidthCm));
}
// Make upper bound
mapSectionXRanges.push(new Range(i * mapSectionWidthCm - mapSectionOverlapCm,
10000));
function startNewGame() {
var blocks = makeTerrain();
var animals = makeWildAnimals();
var tool = new Tool('Pickaxe', 10, new p5.Vector(30, 30),
'pickaxe', 10, new p5.Vector(30, 10), 30);
var tool2 = new Tool('Sword', 12, new p5.Vector(30, 12),
'sword', 15, new p5.Vector(30, 10), 48)
var inventory = new Inventory(100, 50);
inventory.addItem(tool2);
var character = new Character(characterName, characterStartPos,
characterSizeCm, characterSpeed, characterJumpStrength, gravityStrength, characterImageNames,
characterMaxHealth, characterHealRate, characterMaxStamina, 0,
true, characterOnDie, tool, tool, inventory, characterSoundNames);
game = new Game(gameSaveName, gameBgImageNames, character,
'exitGame()', 'openControlPage()', themeColors.mainBrown, themeColors.secondBrown,
crntVersion, blocks, mapSectionXRanges,
animals, new Range(0, mapCols * blockSizeCm), wildAnimalSpawnChances, createWildAnimalFunctions,
maxWildAnimalAmounts,
gameTimeIncrement);
saveGame(game);
startGame(game);
}
|
import React, { useState, createContext, useContext, useEffect } from 'react';
import { useSocket } from './useSocket';
const ItemModelContext = createContext();
/**
* Contexte permettant d'avoir accès aux fonctions de gestion des modèles d'item
* partout dans le code
*/
export const ItemModelProvider = ({ children }) => {
const [itemModels, setItemModels] = useState([]);
const { socket } = useSocket();
useEffect(() => {
socket.on('getItemModels', (im) => setItemModels(im));
}, []);
return (
<ItemModelContext.Provider value={{ itemModels, setItemModels }}>
{children}
</ItemModelContext.Provider>
);
};
export const useItemModels = () => useContext(ItemModelContext);
|
/** 個人 第二步 填寫會員資料 */
import React,{Component} from 'react'
import{
View,StyleSheet,Switch,
Text,TouchableOpacity,Image,
} from 'react-native'
import {createDateData, currentFullData, createAreaData} from '@/utils/common'
import { colors, scale, width } from '@/utils/device';
import Picker from 'react-native-picker';
import InputView from '@/components/InputView'
import Select from '@/components/Select'
import BtnView from './BtnView'
import {navPage} from '@/utils/common'
import sty from './styles.js';
export default class Person extends Component{
constructor(props){
super(props)
this.state = {
name: '李曼迪',
eName: 'MandyLee',
country:'中國(香港)',
cardId: '',
email: 'mandylee@hotmail.com',
email2: '',
address: '',
birthday: '',
shop: '',
selShop: false,
bank: '',
selBank: '',
bankno: '',
account: '',
district:'',//地區
hasRecomm: false,//是否有推薦人
recommCode:'',
tel: 'MandyLee',
selCountry: false,
gender: '男',
selGender: false,
area: '香港 852',
selArea: false,
currentDate: currentFullData()
}
}
_next(){
navPage(this.props.navigation, 'SetPwd', {category: 1})
}
_pre(){
this.props.navigation.pop();
}
onChangeText(val,type){
let {name,eName,cardId,tel,email,email2,address,bankno,account,recommCode} = this.state
if(type == 'name') name = val
else if(type == 'eName') eName = val
else if(type == 'cardId') cardId = val
else if(type == 'tel') tel = val
else if(type == 'email') email = val
else if(type == 'email2') email2 = val
else if(type == 'address') address = val
else if(type == 'bankno') bankno = val
else if(type == 'account') account = val
else if(type == 'recommCode') recommCode = val
this.setState({
name,
eName,
cardId,
tel,
email,
email2,
address,
bankno,
account,
recommCode
})
}
_recommChange=(value)=>{
this.setState({
hasRecomm:value
})
}
//點擊選擇國籍
_selCountry=(type)=>{
this.setState({
country: type.value,
selCountry: false
})
}
_selBank=(type)=>{
this.setState({
bank: type.value,
selBank: false
})
}
_selGender=(type)=>{
this.setState({
gender: type.value,
selGender: false
})
}
_selArea=(type)=>{
this.setState({
area: type.value,
selArea: false
})
}
_shopChange=(value)=>{
this.setState({
hasShop:value
})
}
_selShop=(type)=>{
this.setState({
shop: type.value,
selShop: false
})
}
//打开日期选择 视图
_showDatePicker() {
var year = ''
var month = ''
var day = ''
var dateStr = this.state.currentDate
day = dateStr.substring(0,2)
month = parseInt(dateStr.substring(3,5))
year = parseInt(dateStr.substring(6,10))
Picker.init({
pickerTitleText:'时间选择',
pickerCancelBtnText:'取消',
pickerConfirmBtnText:'确定',
selectedValue:[year+'年',month+'月',day+'日'],
pickerBg:[255,255,255,1],
pickerData: createDateData(),
pickerFontColor: [33, 33 ,33, 1],
onPickerConfirm: (pickedValue, pickedIndex) => {
var year = pickedValue[0].substring(0,pickedValue[0].length-1)
var month = pickedValue[1].substring(0,pickedValue[1].length-1)
month = month.padStart(2,'0')
var day = pickedValue[2].substring(0,pickedValue[2].length-1)
day = day.padStart(2,'0')
let str = day+'-'+month+'-'+year
this.setState({
birthday:str,
})
},
onPickerCancel: (pickedValue, pickedIndex) => {
//console.log('date', pickedValue, pickedIndex);
},
onPickerSelect: (pickedValue, pickedIndex) => {
//console.log('date', pickedValue, pickedIndex);
}
});
Picker.show();
}
_showAreaPicker() {
//this.setState({showPicker:true});
console.log('_showAreaPicker')
var province = "";
var city = "";
var county = "";
let area = this.state.district
if(area){
province = area.split(' ')[0];
city = area.split(' ')[1];
county = area.split(' ')[2];
}
Picker.init({
pickerData: createAreaData(),
pickerTitleText:'地區選擇',
pickerCancelBtnText:'取消',
pickerConfirmBtnText:'確定',
pickerBg:[255,255,255,1],
selectedValue: [province, city, county],
onPickerConfirm: pickedValue => {
let district = pickedValue[0] + ' ' + pickedValue[1] + ' ' + pickedValue[2];
this.setState({district})
},
onPickerCancel: pickedValue => {
this.setState({showPicker:false});
},
onPickerSelect: pickedValue => {
this.setState({showPicker:false});
}
});
Picker.show();
}
render(){
const {name, eName, country,selCountry, gender, hasRecomm,cardId,bank,selBank,hasShop,shop,selShop,
selGender,area, selArea,tel,email,birthday,address,district} = this.state
const t1 = '請確保填寫正確的電郵地址。您的新科士威會員編號、密碼及戶口的相關資料將發送至此電郵地址。'
const t3 = '只限香港地址,送貨範圍包括香港島、九龍、新界及\n指定離島地區:東涌'
const t4 = '如果您希望將盈利存入您的銀行帳戶,請提供正確的銀行資料。否則盈利將會自動存入您的電子戶口。'
const remark2 = '若您的身份証號碼是A123456(7),\n請輸入A1234567。'
const items = [
{key:'a', value: '中國(香港)'},
{key:'b', value: '中國(澳門)'},
{key:'c', value: '中國'},
]
const shopList = [
{key:'a', value: '蘋果專賣店'},
{key:'b', value: 'HUAWEI 專賣店'},
{key:'c', value: '阿迪達斯專賣店'},
{key:'d', value: '李寧服飾專賣店'},
]
const bankList = [
{key:'a', value: '中國銀行'},
{key:'b', value: '中國工商銀行'},
{key:'c', value: '中國建設銀行'},
{key:'d', value: '中國農業銀行'},
]
const items2 = [
{key:'a', value: '男'},
{key:'b', value: '女'},
]
const items3 = [
{key:'香港 852', value: '香港 852'},
{key:'上海 021', value: '上海 021'},
{key:'杭州 571', value: '杭州 571'},
]
const arrowImage = <Image style={sty.arrowImg} source={require('@/images/set/input_r.png')}/>
return(
<View>
<View style={sty.card1}>
<InputView lab='中文全名' dVal={name} require={true} onChangeText={(val)=>this.onChangeText(val, 'name')}/>
<View style={sty.line2}></View>
<InputView lab='英文全名' dVal={eName} require={true} onChangeText={(val)=>this.onChangeText(val, 'eName')}/>
<View style={sty.line2}></View>
<View style={sty.box3}>
<Text style={sty.textL}><Text style={sty.red}>* </Text>國籍</Text>
<TouchableOpacity style={sty.row0} onPress={()=>this.setState({selCountry:true})}>
<Text style={sty.t5}>{country}</Text>
{arrowImage}
</TouchableOpacity>
<Select
title='選擇國籍'
items={items}
_selItem={this._selCountry}
showModal={selCountry}
hideModal={()=>this.setState({selCountry:false})}/>
</View>
<View style={sty.line2}></View>
<View style={sty.box3}>
<Text style={sty.textL}><Text style={sty.red}>* </Text>出生日期</Text>
<TouchableOpacity style={sty.row0} onPress={()=>this._showDatePicker()}>
<Text style={sty.t2}>{birthday?birthday:'DD-MM-YYYY'}</Text>
{arrowImage}
</TouchableOpacity>
</View>
<View style={sty.line2}></View>
<View style={sty.box3}>
<Text style={sty.textL}><Text style={sty.red}>* </Text>性別</Text>
<TouchableOpacity style={sty.row0} onPress={()=>this.setState({selGender:true})}>
<Text style={sty.t5}>{gender}</Text>
{arrowImage}
</TouchableOpacity>
<Select
title='選擇性別'
items={items2}
_selItem={this._selGender}
showModal={selGender}
hideModal={()=>this.setState({selGender:false})}/>
</View>
<View style={sty.line2}></View>
<InputView lab='身份證號碼' placeholder='請輸入身份證號碼' dVal={cardId} require={true} remark={remark2} onChangeText={(val)=>this.onChangeText(val,'cardId')}/>
<View style={sty.line}></View>
<View style={sty.box3}>
<Text style={sty.textL}><Text style={sty.red}>* </Text>區碼</Text>
<TouchableOpacity style={sty.row0} onPress={()=>this.setState({selArea:true})}>
<Text style={sty.t5}>{area}</Text>
{arrowImage}
</TouchableOpacity>
<Select
title='選擇區碼'
items={items3}
_selItem={this._selArea}
showModal={selArea}
hideModal={()=>this.setState({selArea:false})}/>
</View>
<View style={sty.line2}></View>
<InputView lab='網絡電話號碼' dVal={tel} require={true} onChangeText={(val)=>this.onChangeText(val, 'tel')}/>
<View style={sty.box1}>
<Text style={sty.t1}>{t1}</Text>
</View>
<InputView lab='電郵地址' dVal={email} require={true} onChangeText={(val)=>this.onChangeText(val, 'email')}/>
<View style={sty.line2}></View>
<InputView lab='確認電郵地址' dVal={''} placeholder='請再次輸入電郵地址' require={true} onChangeText={(val)=>this.onChangeText(val, 'email2')}/>
<View style={sty.line}></View>
<InputView lab='通訊地址' remark='請以英文填寫' placeholder='請輸入通訊地址' require={true} onChangeText={(val)=>this.onChangeText(val, 'address')}/>
<View style={sty.line2}></View>
<View>
<View style={sty.box3}>
<Text style={sty.textL}><Text style={sty.red}>* </Text>地區</Text>
<TouchableOpacity style={sty.row0} onPress={()=>this._showAreaPicker()}>
<Text style={sty.t2}>{district?district:'請選擇地區'}</Text>
{arrowImage}
</TouchableOpacity>
</View>
<Text style={sty.tipsText}>{t3}</Text>
</View>
<View style={sty.box1}>
<Text style={sty.t1}>{t4}</Text>
</View>
<View style={sty.box3}>
<Text style={sty.textL}>銀行名稱</Text>
<TouchableOpacity style={sty.row0} onPress={()=>this.setState({selBank:true})}>
<Text style={sty.t2}>{bank?bank:'請選擇銀行'}</Text>
{arrowImage}
</TouchableOpacity>
<Select
title='選擇銀行'
items={bankList}
_selItem={this._selBank}
showModal={selBank}
hideModal={()=>this.setState({selBank:false})}/>
</View>
<InputView lab='銀行編號' dVal={''} placeholder='請輸入銀行編號' onChangeText={(val)=>this.onChangeText(val, 'bankno')}/>
<InputView lab='賬戶號碼' dVal={''} placeholder='請輸入賬戶號碼' onChangeText={(val)=>this.onChangeText(val, 'account')}/>
<View style={sty.line}></View>
<View style={sty.box3}>
<Text style={sty.textL}>是否有推薦人</Text>
<Switch trackColor={{true:'#72AC41',false:'#DEDEDE'}}
//thumbColor='#f0f0f0'
value={hasRecomm} onValueChange={this._recommChange}/>
</View>
<View style={sty.line2}></View>
<InputView lab='推薦人編號' dVal={''} placeholder='請輸入推薦人編號'
remark={remark2}
remarkStyle={{marginLeft:0}}
onChangeText={(val)=>this.onChangeText(val, 'recommCode')}/>
</View>
<View style={sty.line}></View>
<View style={sty.box3}>
<Text style={sty.textL}><Text style={sty.red}>* </Text>登記店鋪</Text>
<Switch trackColor={{true:'#72AC41',false:'#DEDEDE'}}
//thumbColor='#f0f0f0'
value={hasShop} onValueChange={this._shopChange}/>
</View>
<View style={sty.line2}></View>
<View style={sty.box3}>
<Text style={sty.textL}><Text style={sty.red}>* </Text>店鋪</Text>
<TouchableOpacity style={sty.row0} onPress={()=>this.setState({selShop:true})}>
<Text style={sty.t2}>{shop?shop:'請選擇店鋪'}</Text>
{arrowImage}
</TouchableOpacity>
<Select
title='選擇店鋪'
items={shopList}
_selItem={this._selShop}
showModal={selShop}
hideModal={()=>this.setState({selShop:false})}/>
</View>
<BtnView pre={()=>this._pre()} next={()=>this._next()}/>
</View>
)
}
}
|
(function(){
angular
.module('everycent.transactions', ['everycent.common', 'everycent.transactions.importers'])
.config(RouteConfiguration);
RouteConfiguration.$inject = ['$stateProvider'];
function RouteConfiguration($stateProvider){
$stateProvider
.state('transactions', {
url: '/transactions?bank_account&budget',
reloadOnSearch: false,
templateUrl: 'app/transactions/transaction-list.html',
controller: 'TransactionsCtrl as vm',
resolve:{
auth: ['$auth', function($auth){
return $auth.validateUser();
}]
}
})
.state('credit-card-transactions', {
url: '/credit-card-transactions?bank_account',
reloadOnSearch: false,
templateUrl: 'app/transactions/credit-card-transaction-list.html',
controller: 'CreditCardTransactionsCtrl as vm',
resolve:{
auth: ['$auth', function($auth){
return $auth.validateUser();
}]
}
})
;
}
})();
|
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
// action creators
import { searchFocus, searchBlur, fetchSearchResults } from 'search';
import { fetchSeries } from 'series';
// components
import SearchBox from 'search/components/SearchBox';
const Search = ({ results, hasFocus, ...handlers }) => (
<section>
<SearchBox {...handlers} />
<ul>
{results.map((item) => <li key={item.id} onClick={() => handlers.getSeries(item.id)}>{item.seriesName}</li>)}
</ul>
</section>
);
Search.propTypes = {
handleFocus: PropTypes.func.isRequired,
handleBlur: PropTypes.func.isRequired,
hasFocus: PropTypes.bool,
};
const mapStateToProps = state => state.search;
const mapDispatchToProps = (dispatch) => ({
handleFocus: () => dispatch(searchFocus()),
handleBlur: () => dispatch(searchBlur()),
makeRequest: (term) => dispatch(fetchSearchResults(term)),
getSeries: (id) => dispatch(fetchSeries(id)),
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Search);
|
$(function() {
var params = {};
params.categoryType = $("#categoryType").val();
params.masterId = $("#masterId").val();
$("#groupGrid").jqGrid({
url:_requestPath+'/admin/getGroupListData',
datatype:'json',
mtype:'POST',
postData:params,
height: 450,
rowNum:-1,
//width: 800,
//shrinkToFit:false,
jsonReader:{repeatitems: false},
autowidth:true,
colNames:['id','번호','유형', '그룹명', '성별','등록일','수정일','활성','',''],
colModel:[
{name:'id',index:'id', width:30, hidden:true, sortable : false, key:true},
{name:'groupNo',index:'groupNo', width:15, align:"center", sortable : false},//,formatter: customDateFormat ,formatter:'date', formatoptions: { newformat: 'Y/m/d'}
{name:'groupType',index:'groupType', width:50, sortable : false,
formatter: function (cellValue, option) {
var text = "";
$("#groupType option").each(function (){
if($(this).val() == cellValue) {
text = $(this).text();
return false;
}
});
return $.trim(text);
}
},
{name:'title',index:'title', sortable : false, formatter:viewLink},
{name:'gender',index:'gender', width:25, align:"center", sortable : false
/*
,
formatter: function (cellValue, option) {
var ret = "전체";
if(cellValue == "MALE") {
ret = "남성";
} else if(cellValue == "FEMALE") {
ret = "여성";
}
return ret;
}
*/
},
{name:'createDate',index:'createDate', width:35, sortable:false, formatter:customDateFormat, align:"center"},
{name:'updateDate',index:'updateDate', width:35, sortable:false, formatter:customDateFormat, align:"center"},
{name:'active',index:'active', width:20, hidden:true, align:"center", sortable : false},
{name:'act', index:'act', width:45, sortable:false, align:"center"},
{name:'view', index:'view', width:20, sortable:false, align:"center"}
],
gridComplete: function(){
var ids = $("#groupGrid").getDataIDs();
for(var i=0;i<ids.length;i++){
var cl = ids[i];
var be = "<input style='height:22px;width:40px;' type='button' value='Edit' onclick=editRow('"+cl+"'); />";
var se = "";
if(masterStatus != "ACTIVE") {
se = "<input style='height:22px;width:40px;' type='button' value='Del' onclick=deleteRow('"+cl+"'); />";
}
var vi = "<input style='height:22px;width:45px;' type='button' value='View' onclick=viewRow('"+cl+"'); />";
$("#groupGrid").setRowData(ids[i],{act:be+" "+se, view:vi});
}
},
//multiselect: true,
caption: "목록"
});
$( "#dialog-form" ).dialog({
autoOpen: false,
height: 550,
width: 600,
modal: true,
buttons: {
"저장": function() {
$("#categoryTp").val($("#categoryType").val());
$("#questionGroupForm").submit();
},
"닫기": function() {
$( this ).dialog( "close" );
}
},
close: function() {
$("#questionGroupForm").resetForm();
$('#editor').empty();
$("#nurseEditable").attr("checked", false);
}
});
if(masterStatus == "ACTIVE") {
$('.ui-dialog-buttonpane button').eq(0).button('disable');
}
$( "#categoryType" ).change(function() {
gridReLoad();
});
$( "button" ).button().click(function( event ) {
event.preventDefault();
});
$( "#create-questionGroup" ).button().click(function() {
$( "#viewCategory" ).text($("#categoryType :selected").text());
$("#viewFile").empty();
$("#groupId").val('');
createEditor();
$( "#dialog-form" ).dialog( "open" );
});
$('#questionGroupForm').ajaxForm({
dataType:'json',
success : function(result){
var success = result.success;
if(success){
gridReLoad();
$( "#dialog-form" ).dialog( "close" );
}else{
alert(result.msg);
}
},
error : function(response, status, err){
alert(err);
}
});
});
function createEditor() {
$('#editor').append("<textarea name='contents' id='contents' ></textarea>");
$('#contents').jqte();
}
function customDateFormat(cellValue, option) {
if(cellValue){
return $.datepicker.formatDate('yy-mm-dd', new Date(cellValue));
}
return "";
}
function gridReLoad() {
var params = {};
params.categoryType = $("#categoryType").val();
params.masterId = $("#masterId").val();
$('#groupGrid').setGridParam({postData:params});
$("#groupGrid").jqGrid().trigger("reloadGrid");
}
function editRow(id) {
$.ajax({
dataType: 'json',
type : 'POST',
url : _requestPath + '/admin/getQuestionGroup',
//timeout : 5000,
data : {groupId:id},
beforeSubmit : function(){
},
success : function(result){
var success = result.success;
if(success){
setForm(result.group);
$( "#dialog-form" ).dialog( "open" );
}else{
alert(result.msg);
}
},
error : function(response, status, err){
alert(err);
}
});
}
function setForm(data) {
$("#viewFile").empty();
createEditor();
if(data.help != null) {
$("#helpId").val(data.help.id);
$('#editor').empty();
$('#editor').append("<textarea name='contents' id='contents' ></textarea>");
$('#contents').val(data.help.contents);
$('#contents').jqte();
$("#attachFilePath").val(data.help.attachFilePath);
$("#viewFile").append(data.help.attachFilePath);
}
$( "#viewCategory" ).text($("#categoryType :selected").text());
$("#categoryTp").val($("#categoryType").val());
$("#groupId").val(data.id);
$("#groupNo").val(data.groupNo);
$("#groupType").val(data.groupType);
$("#title").val(data.title);
$("#description").val(data.description);
$("#gender").val(data.gender);
$("#thumbnailImage").val(data.thumbnailImage);
if(data.nurseEditable == true) $("#nurseEditable").attr("checked", true);
$("#sortOrder").val(data.sortOrder);
}
function deleteRow(id) {
if(confirm("삭제하시겠습니까?")) {
$.ajax({
dataType: 'json',
type : 'POST',
url : _requestPath + '/admin/questionGroupDelete',
//timeout : 5000,
data : {groupId:id},
beforeSubmit : function(){
},
success : function(result){
var success = result.success;
if(success){
gridReLoad();
$( "#dialog-form" ).dialog( "close" );
}else{
alert(result.msg);
}
},
error : function(response, status, err){
alert(err);
}
});
}
}
function viewRow(id) {
var viewWin = window.open(_requestPath +"/admin/previewQuestionGroup/"+id, "view" , 'top=10, left=10,width=1280,height=768');
viewWin.focus();
}
function viewLink(cellValue, options, rowObject) {
var url = "";
if(cellValue != null) {
url = '<a href="javascript:goQuestion(\''+rowObject.id+'\');"><font color=blue>'+cellValue+'</font></a>';
}
return url;
}
function goQuestion(groupId){
document.location.href = _requestPath + "/admin/questionList?groupId=" + groupId+"&depth=1";
}
|
const Order = require('./model');
const request = require('request');
const config = require('../../config');
const crypto = require('../../utils/crypto');
const fs = require('fs');
module.exports.createOrder = async (order, imageFile) => {
if (imageFile) {
return new Promise((resolve, reject) => {
fs.readFile(imageFile.path, (e, data) => {
if (e) {
reject(e);
} else {
order.image = data;
Order.create(order, (e, order) => {
if (e) {
reject(e);
} else {
delete order._doc.image;
resolve(order);
}
});
}
});
});
}
return Order.create(order);
};
const validateContract = (order, contract, curTime) => {
return contract.garaPubKeyHashes.indexOf(crypto.getPubKeyHash(config.myPrivKey)) >= 0
&& contract.userInfo.licensePlate === order.licensePlate
&& curTime >= contract.expireTime.timeStart && curTime <= contract.expireTime.timeEnd
&& order.insurence.company === contract.plan.company && order.insurence.id === contract.plan.id;
};
const calBalance = (order, contract) => {
let sum = 0;
contract.refunds.forEach(refund => {
sum += refund.refund;
});
let maxRefund = contract.plan.term.maxRefund;
return maxRefund - sum;
};
const orderToRefund = (order, contract, curTime) => {
let balance = calBalance(order, contract);
if (balance > 0) {
return {
total: order.total,
refund: (balance >= order.total * contract.plan.term.percentage) ? order.total * contract.plan.term.percentage : balance,
time: curTime,
garaPubKeyHash: crypto.getPubKeyHash(config.myPrivKey)
};
}
return null;
};
const refundToMsg = (newRefund, contract) => {
return {
type: 'CONTRACT',
ref: {
plan: {
company: contract.plan.company,
id: contract.plan.id
},
userInfo: contract.userInfo,
garaPubKeyHashes: contract.garaPubKeyHashes,
expireTime: contract.expireTime
},
preStateHash: crypto.hash(JSON.stringify(contract.plan.term) + JSON.stringify(contract.refunds)),
action: {
update: {
push: newRefund
}
}
};
};
module.exports.updateOrder = async (id, order) => {
delete order.id;
if (order.status) {
return new Promise((resolve, reject) => {
request(`http://${config.company[order.insurence.company]}/contracts-by-license-plate/${order.licensePlate}`, async (e, res, body) => {
if (e) {
reject(e);
} else {
try {
let curTime = new Date().getTime();
let contracts = JSON.parse(body);
for (let i = 0; i < contracts.length; i++) {
if (validateContract(order, contracts[i], curTime)) {
let newRefund = orderToRefund(order, contracts[i], curTime);
if (newRefund) {
let msg = refundToMsg(newRefund, contracts[i]);
let sign = crypto.sign(msg);
config.defaultNodes.forEach(node => {
request.post({url: `http://${node}/tx`, form: sign}, (e, res, body) => {
if (e) {
console.error(e);
} else {
console.log(JSON.stringify(body.toString()));
}
});
});
order.insurence.refund = newRefund.refund;
order = await Order.findOneAndUpdate({id}, {
$set: {
insurence: order.insurence,
status: true
}
}, {new: true});
return resolve(order);
}
}
}
reject(new Error('Cannot create refund'));
} catch (e) {
reject(e);
}
}
}
);
}
);
}
return await Order.findOneAndUpdate({id}, {$set: order}, '-image');
};
module.exports.getOrders = async () => {
return await Order.find({}, '-image');
};
module.exports.getImage = async id => {
let order = await Order.findOne({id: id}, 'image');
if (order) {
return order.image;
}
return null;
};
|
import { Debug } from '../../core/debug.js';
/**
* Callback used by {@link ResourceLoader#load} when a resource is loaded (or an error occurs).
*
* @callback ResourceLoaderCallback
* @param {string|null} err - The error message in the case where the load fails.
* @param {*} [resource] - The resource that has been successfully loaded.
*/
/**
* Load resource data, potentially from remote sources. Caches resource on load to prevent multiple
* requests. Add ResourceHandlers to handle different types of resources.
*/
class ResourceLoader {
/**
* Create a new ResourceLoader instance.
*
* @param {import('../app-base.js').AppBase} app - The application.
*/
constructor(app) {
this._handlers = {};
this._requests = {};
this._cache = {};
this._app = app;
}
/**
* Add a {@link ResourceHandler} for a resource type. Handler should support at least `load()`
* and `open()`. Handlers can optionally support patch(asset, assets) to handle dependencies on
* other assets.
*
* @param {string} type - The name of the resource type that the handler will be registered
* with. Can be:
*
* - {@link ASSET_ANIMATION}
* - {@link ASSET_AUDIO}
* - {@link ASSET_IMAGE}
* - {@link ASSET_JSON}
* - {@link ASSET_MODEL}
* - {@link ASSET_MATERIAL}
* - {@link ASSET_TEXT}
* - {@link ASSET_TEXTURE}
* - {@link ASSET_CUBEMAP}
* - {@link ASSET_SHADER}
* - {@link ASSET_CSS}
* - {@link ASSET_HTML}
* - {@link ASSET_SCRIPT}
* - {@link ASSET_CONTAINER}
*
* @param {import('./handler.js').ResourceHandler} handler - An instance of a resource handler
* supporting at least `load()` and `open()`.
* @example
* const loader = new ResourceLoader();
* loader.addHandler("json", new pc.JsonHandler());
*/
addHandler(type, handler) {
this._handlers[type] = handler;
handler._loader = this;
}
/**
* Remove a {@link ResourceHandler} for a resource type.
*
* @param {string} type - The name of the type that the handler will be removed.
*/
removeHandler(type) {
delete this._handlers[type];
}
/**
* Get a {@link ResourceHandler} for a resource type.
*
* @param {string} type - The name of the resource type that the handler is registered with.
* @returns {import('./handler.js').ResourceHandler|undefined} The registered handler, or
* undefined if the requested handler is not registered.
*/
getHandler(type) {
return this._handlers[type];
}
static makeKey(url, type) {
return `${url}-${type}`;
}
/**
* Make a request for a resource from a remote URL. Parse the returned data using the handler
* for the specified type. When loaded and parsed, use the callback to return an instance of
* the resource.
*
* @param {string} url - The URL of the resource to load.
* @param {string} type - The type of resource expected.
* @param {ResourceLoaderCallback} callback - The callback used when the resource is loaded or
* an error occurs. Passed (err, resource) where err is null if there are no errors.
* @param {import('../asset/asset.js').Asset} [asset] - Optional asset that is passed into
* handler.
* @example
* app.loader.load("../path/to/texture.png", "texture", function (err, texture) {
* // use texture here
* });
*/
load(url, type, callback, asset) {
const handler = this._handlers[type];
if (!handler) {
const err = `No resource handler for asset type: '${type}' when loading [${url}]`;
Debug.errorOnce(err);
callback(err);
return;
}
// handle requests with null file
if (!url) {
this._loadNull(handler, callback, asset);
return;
}
const key = ResourceLoader.makeKey(url, type);
if (this._cache[key] !== undefined) {
// in cache
callback(null, this._cache[key]);
} else if (this._requests[key]) {
// existing request
this._requests[key].push(callback);
} else {
// new request
this._requests[key] = [callback];
const self = this;
const handleLoad = function (err, urlObj) {
if (err) {
self._onFailure(key, err);
return;
}
handler.load(urlObj, function (err, data, extra) {
// make sure key exists because loader
// might have been destroyed by now
if (!self._requests[key]) {
return;
}
if (err) {
self._onFailure(key, err);
return;
}
try {
self._onSuccess(key, handler.open(urlObj.original, data, asset), extra);
} catch (e) {
self._onFailure(key, e);
}
}, asset);
};
const normalizedUrl = url.split('?')[0];
if (this._app.enableBundles && this._app.bundles.hasUrl(normalizedUrl)) {
if (!this._app.bundles.canLoadUrl(normalizedUrl)) {
handleLoad(`Bundle for ${url} not loaded yet`);
return;
}
this._app.bundles.loadUrl(normalizedUrl, function (err, fileUrlFromBundle) {
handleLoad(err, {
load: fileUrlFromBundle,
original: normalizedUrl
});
});
} else {
handleLoad(null, {
load: url,
original: asset && asset.file.filename || url
});
}
}
}
// load an asset with no url, skipping bundles and caching
_loadNull(handler, callback, asset) {
const onLoad = function (err, data, extra) {
if (err) {
callback(err);
} else {
try {
callback(null, handler.open(null, data, asset), extra);
} catch (e) {
callback(e);
}
}
};
handler.load(null, onLoad, asset);
}
_onSuccess(key, result, extra) {
if (result !== null) {
this._cache[key] = result;
} else {
delete this._cache[key];
}
for (let i = 0; i < this._requests[key].length; i++) {
this._requests[key][i](null, result, extra);
}
delete this._requests[key];
}
_onFailure(key, err) {
console.error(err);
if (this._requests[key]) {
for (let i = 0; i < this._requests[key].length; i++) {
this._requests[key][i](err);
}
delete this._requests[key];
}
}
/**
* Convert raw resource data into a resource instance. E.g. Take 3D model format JSON and
* return a {@link Model}.
*
* @param {string} type - The type of resource.
* @param {*} data - The raw resource data.
* @returns {*} The parsed resource data.
*/
open(type, data) {
const handler = this._handlers[type];
if (!handler) {
console.warn('No resource handler found for: ' + type);
return data;
}
return handler.open(null, data);
}
/**
* Perform any operations on a resource, that requires a dependency on its asset data or any
* other asset data.
*
* @param {import('../asset/asset.js').Asset} asset - The asset to patch.
* @param {import('../asset/asset-registry.js').AssetRegistry} assets - The asset registry.
*/
patch(asset, assets) {
const handler = this._handlers[asset.type];
if (!handler) {
console.warn('No resource handler found for: ' + asset.type);
return;
}
if (handler.patch) {
handler.patch(asset, assets);
}
}
/**
* Remove resource from cache.
*
* @param {string} url - The URL of the resource.
* @param {string} type - The type of resource.
*/
clearCache(url, type) {
const key = ResourceLoader.makeKey(url, type);
delete this._cache[key];
}
/**
* Check cache for resource from a URL. If present, return the cached value.
*
* @param {string} url - The URL of the resource to get from the cache.
* @param {string} type - The type of the resource.
* @returns {*} The resource loaded from the cache.
*/
getFromCache(url, type) {
const key = ResourceLoader.makeKey(url, type);
if (this._cache[key]) {
return this._cache[key];
}
return undefined;
}
/**
* Enables retrying of failed requests when loading assets.
*
* @param {number} maxRetries - The maximum number of times to retry loading an asset. Defaults
* to 5.
* @ignore
*/
enableRetry(maxRetries = 5) {
maxRetries = Math.max(0, maxRetries) || 0;
for (const key in this._handlers) {
this._handlers[key].maxRetries = maxRetries;
}
}
/**
* Disables retrying of failed requests when loading assets.
*
* @ignore
*/
disableRetry() {
for (const key in this._handlers) {
this._handlers[key].maxRetries = 0;
}
}
/**
* Destroys the resource loader.
*/
destroy() {
this._handlers = {};
this._requests = {};
this._cache = {};
}
}
export { ResourceLoader };
|
export const sortBanners = (banners) => {
const mainBanner = banners.find((banner) => banner.isMain);
if (!mainBanner) {
return banners;
}
const resBanners = banners.filter((banner) => banner.id !== mainBanner.id);
return [mainBanner, ...resBanners];
};
export const getLinksFromPath = (path) => {
const links = path.split("/");
links.shift();
return links;
};
|
import React from "react";
// nodejs library that concatenates classes
import classNames from "classnames";
import Header from "../../components/Header/Header";
import Footer from "../../components/Footer/Footer";
// sections for this page
import HeaderLinks from "../../components/Header/HeaderLinks";
import LeftLink from "../../components/Header/LeftLinks";
import Stage from "./Sections/Stage";
import Parallax from "../../components/Parallax/Parallax";
import { getVendors } from "../../actions/actions_front";
import { PageLoader } from "../../components/PageLoader/PageLoader";
import GridContainer from "../../components/Grid/GridContainer";
import GridItem from "../../components/Grid/GridItem";
class Vendor extends React.Component {
constructor(props) {
super(props);
this.state = {
loader: "block",
};
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
componentWillMount() {
const { dispatch } = this.props;
dispatch(getVendors());
// .then(
// () => {
this.setState({ loader: "none" });
// }
// );
}
render() {
const { classes, front, ...rest } = this.props;
document.title = "Vendors @ Bezop Marketplace || Worlds First Decentralized Marketplace";
return (
<div>
<PageLoader display={this.state.loader} />
<Header
brand=""
rightLinks={<HeaderLinks user="customer" />}
leftLinks={<LeftLink user="customer" />}
color="white"
{...rest}
/>
<Parallax
style={{ height: "400px" }}
image="https://images.pexels.com/photos/886465/pexels-photo-886465.jpeg?auto=compress&cs=tinysrgb&h=350"
>
<div style={{
backgroundColor: "rgba(0, 0, 0, 0.5)",
content: "",
display: "block",
height: "100%",
left: 0,
top: 0,
position: "absolute",
width: "100%",
}}
/>
<div className={classes.container}>
<GridContainer>
<GridItem>
<div style={{ textAlign: "center", color: "#ffffff" }}>
<h1 className={classes.title}>
Vendors
</h1>
<h3>
Get connected to trusted vendors.
</h3>
</div>
</GridItem>
</GridContainer>
</div>
</Parallax>
<div className={classNames(classes.main, classes.mainRaised)}>
<Stage vendors={front.vendors} />
</div>
<Footer topFooter />
</div>
);
}
}
export default Vendor;
|
const { body, check } = require("express-validator/check");
const { Todo } = require("../../db/models/todo");
module.exports.addTodo = [
body("title", "Title is invalid")
.exists()
.isLength({ min: 1, max: 150 }),
body("description")
.exists()
.isLength({ min: 1 })
];
module.exports.checklist = [
body("checklist")
.exists()
.withMessage("checklist doesnt exist")
.isArray()
.withMessage("checklist is not an array")
.isLength({ min: 1 })
.withMessage("checklist must be more than 0"),
body("checklist.*.text")
.exists()
.withMessage("text is empty")
.isString()
.withMessage("text must be a string"),
body("checklist.*.completed")
.exists()
.withMessage("completed must exist")
.isBoolean(),
check("todoId")
.isMongoId()
.withMessage("id is incorrect")
.custom((value, { req }) => {
return Todo.findOne({ _id: value }).then(resp => {
if (!resp) {
return Promise.reject("This todo doesn't exist");
}
});
})
];
module.exports.editChecklist = [
body("text", "text is invalid")
.exists()
.isString(),
body("completed","completed field is invalid or not boolean")
.exists()
.isBoolean(),
check("todoId")
.isMongoId()
.withMessage("id is incorrect")
.custom((value, { req }) => {
return Todo.findOne({ _id: value }).then(resp => {
if (!resp) {
return Promise.reject("This todo doesn't exist");
}
});
}),
check("checklistId")
.isMongoId()
.withMessage("checklist id is incorrect")
.custom((value, { req }) => {
return Todo.findOne( { _id: req.params.todoId , "checklist._id" : value} ).then(resp => {
// console.log("checklist",resp);
if (!resp) {
return Promise.reject("This checklist doesn't exist");
}
})})
];
|
export function getGrandchild(obj, ids){
for(var i = 0; i < ids.length; ++i){
var id = ids[i];
for(var j = 0; j < obj.childNodes.length; ++j){
var o = obj.childNodes[j];
if(o.id == id){ obj = o; break; }
}
}
return obj;
}
export function getChild(obj, id){
for(var j = 0; j < obj.childNodes.length; ++j){
var o = obj.childNodes[j];
if(o.id == id){ obj = o; break; }
}
return obj;
}
export function getGrandparent(obj, ids){
for(var i = 0; i < ids.length; ++i){
var id = ids[i];
var o = obj.parentNode;
if(o.id == id){ obj = o; }
else break;
}
return obj;
}
export function getChildPosition(obj, id){
for(var j = 0; j < obj.childNodes.length; ++j){
var o = obj.childNodes[j];
if(o.id == id){ return j; }
}
return -1;
}
function traverseAndGetChildElement(obj, ids){
/*for(var id in ids){
for(var o in obj.childNodes){
if(o.id == id){ obj = o; break; }
}
}*/
for(var i = 0; i < ids.length; ++i){
var id = ids[i];
for(var j = 0; j < obj.childNodes.length; ++j){
var o = obj.childNodes[j];
if(o.id == id){ obj = o; break; }
}
}
return obj;
}
export function getAllByPropertyFrom(obj, func){
let match = [];
let list = [];
let listElementProcessedId = 0;
while(true){
if(func(obj) == true)
match[match.length] = obj;
for(let i = 0; i < obj.childNodes.length; ++i){
let c = obj.childNodes[i];
if(func(c) == true)
match[match.length] = c;
for(let j = 0; j < c.childNodes.length; ++j){
list[list.length] = c.childNodes[j];
}
}
if(listElementProcessedId == list.length)
break;
else{
obj = list[listElementProcessedId];
++listElementProcessedId;
}
}
return match;
}
export function getAllByClassFrom(obj, classId){
return getAllByPropertyFrom(obj, function(o){
return (o.className == classId);
});
}
export function getAllByTagName(obj, tagName){
return getAllByPropertyFrom(obj, function(o){
return (o.tagName == tagName);
});
}
export function getElementsByTagNameImmediate(tag){
var nodes = this.childNodes;
nodes = Array.prototype.slice.call(nodes);
nodes = nodes.filter(function(v, i){
return v.tagName == tag; });
return nodes;
}
|
const express = require('express');
const { log } = require('console');
const app = express();
const PORT = process.env.PORT || 3000;
app
.use(express.static(__dirname + '/public'))
.listen(PORT, () => log(`> http://localhost:${PORT}`));
|
$('a[href*="#"]')
.not('[href="#"]')
.not('[href="#0"]').jQuery.easing();
|
let mongoose = require('mongoose')
const MONGODB_USER = 'icaro'
const MONGODB_PASSWORD = 'adminq1w2e3'
const MONGODB_URI_DEV = 'ds133202.mlab.com:33202'
const MONGODB_DATABASE = 'only-pay-waiter'
var dbURI = `mongodb://${MONGODB_USER}:${MONGODB_PASSWORD}@${MONGODB_URI_DEV}/${MONGODB_DATABASE}`
mongoose.connect(dbURI, { useNewUrlParser: true })
let CostumerSchema = new mongoose.Schema({
nome: { type: String },
tipo: { type: String },
cpf: { type: String },
cnpj: { type: String },
dataNascimento: { type: String },
numeroIdentidade: { type: String },
orgaoExpedidorIdentidade: { type: String },
sexo: { type: String },
unidadeFederativaIdentidade: { type: String },
dataEmissaoIdentidade: { type: String }
})
module.exports = mongoose.model('Customer', CostumerSchema)
|
// action types
// add card
export const addCard = (text, boardIndex) => ({ type: 'ADD_CARD', text, boardIndex });
// remove card
export const removeCard = id => ({ type: 'REMOVE_CARD', id });
// transfer a card
export const transferCard = (id, destinationBoardIndex) => ({ type: 'TRANSFER_CARD', id, destinationBoardIndex });
// add a board on the end
export const addBoard = name => ({ type: 'ADD_BOARD', name });
// remove a board
export const removeBoard = boardIndex => ({ type: 'REMOVE_BOARD', boardIndex });
|
import getQuote from "./coindesk.js";
export default async function main() {
let quote = await getQuote();
let data = JSON.parse(quote);
const coin = {
disclaimer:data.disclaimer,
eur:data.bpi.EUR.rate,
usd:data.bpi.USD.rate,
gbp:data.bpi.GBP.rate
};
console.log("\n******CoinDesk Bitcoin Price Index API******\n" +
"\nDisclaimer: " + coin.disclaimer + "\n"
);
const coinValidation = () =>
process.argv[2] == 'USD' ? console.log("The Bitcoin price in United States Dollar: " + coin.usd + "\n") :
process.argv[2] == "EUR" ? console.log("\nThe Bitcoin price in Euro: " + coin.eur + "\n") :
process.argv[2] == "GBP" ? console.log("\nThe Bitcoin price in British Pound Sterling: " + coin.gbp + "\n") : ""
coinValidation();
}
|
import React, { useState } from "react";
function ItemInput(props) {
const [title, setTitle] = useState();
const [assignee, setAssignee] = useState();
return(
<div>
<h2>Add Item Details</h2>
<form
className="form-style"
onSubmit={(event) => {
props.itemDetail(title, assignee);
event.preventDefault()
}}>
<input
type="text"
className="form-input"
placeholder="Title"
value={title}
onChange={(e) => {setTitle(e.target.value)}}
name="Title"
/>
<input
type="text"
className="form-input"
placeholder="Assignee"
value={assignee}
onChange={(e) => {setAssignee(e.target.value)}}
name="Assignee"
/>
<button type="submit">Submit</button>
</form>
</div>
);
}
export default ItemInput;
|
import React, {Component} from 'react';
import {Table,Button} from 'antd'
import 'antd/dist/antd.css';
import BaseComponent from "../Base/BaseComponent";
import ModalWrapper from "../Base/ModalWrapper";
import JSTemplateGenerator from "./JSTemplateGenerator";
import {Upload} from "antd"
const { clipboard } = window.require('electron');
export default class TemplateUploadBox extends BaseComponent {
componentWillMount() {
}
onFileSelect(file) {
// Template.load(file).then(()=>onTemplate)
const { onSubmit = ()=>{} } = this.props;
let fr = new FileReader();
fr.readAsText(file);
fr.onload = () =>{
let template = fr.result;
onSubmit(template);
}
}
render() {
return (
<Upload.Dragger showUploadList={false} customRequest={e => this.onFileSelect(e.file)}><p style={{lineHeight:"2em"}}>请拖入JS模板</p></Upload.Dragger>
);
}
};
|
const personal = r => require.ensure([], () => r(require('@/views/personal/index')), 'order')
const collection = r => require.ensure([], () => r(require('@/views/personal/collection/index')), 'collection')
const similar = r => require.ensure([], () => r(require('@/views/personal/similar/index')), 'similar')
const discount = r => require.ensure([], () => r(require('@/views/personal/discount/index')), 'discount')
const gcoin = r => require.ensure([], () => r(require('@/views/personal/gcoin/index')), 'gcoin')
const explain = r => require.ensure([], () => r(require('@/views/personal/gcoin/explain/index')), 'explain')
const detail = r => require.ensure([], () => r(require('@/views/personal/gcoin/detail/index')), 'detail')
const redPocket = r => require.ensure([], () => r(require('@/views/personal/gcoin/redPocket/index')), 'redPocket')
export default [
{
path: '/personal',
name: 'personal',
component: personal,
meta: {
title: '斑马会员'
}
},
{
path: '/personal/collection',
name: 'collection',
component: collection,
meta: {
title: '我的收藏'
}
},
{
path: '/personal/similar',
name: 'similar',
component: similar,
meta: {
title: '找相似'
}
},
{
path: '/personal/discount',
name: 'discount',
component: discount,
meta: {
title: '我的优惠券'
}
},
{
path: '/personal/gcoin',
name: 'gcoin',
component: gcoin,
meta: {
title: 'G币'
}
},
{
path: '/personal/gcoin/explain',
name: 'explain',
component: explain,
meta: {
title: 'G币Q&A'
}
},
{
path: '/personal/gcoin/detail',
name: 'detail',
component: detail,
meta: {
title: 'G币明细'
}
},
{
path: '/personal/gcoin/redPocket',
name: 'redPocket',
component: redPocket,
meta: {
title: '斑马红包',
shareType:40
}
}
]
|
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: {
app: './src/app.js',
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '',
filename: '[name].bundle.js',
sourceMapFilename: '[file].map',
devtoolModuleFilenameTemplate: 'webpack:///[resource-path]?[loaders]',
},
devtool: 'source-map',
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'Game of Life',
template: './src/index.ejs',
}),
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
'babel-loader',
'eslint-loader',
],
},
{
test: /\.(glsl|vs|fs)$/,
exclude: /node_modules/,
use: ['raw-loader'],
},
],
},
};
|
import React from "react";
import "./App.css";
import { Route } from "react-router-dom";
import NavBar from "./components/molecules/NavBar";
import HomePage from "./components/organisms/HomePage";
import ShoppingCartPage from "./components/organisms/ShoppingCartPage";
import styled from "styled-components";
import DecoMeshWreathsPage from "./components/organisms/DecoMeshWreathsPage";
import AboutPage from "./components/organisms/AboutPage";
const Container = styled.div`
font-family: "Alegreya", serif;
`;
function App() {
return (
<Container>
<Route exact path="/">
<HomePage />
</Route>
<Route exact path="/cart">
<NavBar solid />
<ShoppingCartPage />
</Route>
<Route exact path="/decowreaths">
<NavBar />
<DecoMeshWreathsPage />
</Route>
<Route exact path="/about">
<NavBar />
<AboutPage />
</Route>
<Route exact path="/category/:categoryId"></Route>
</Container>
);
}
export default App;
|
<Title level={3} style={{ textAlign: 'center' }} editable={() => console.log('asdfasd')}>
{selectedMark.properties.getAll().hintTitle}
</Title>
<Paragraph editable={() => console.log('asdfasd')}>
{selectedMark.properties.getAll().hintContent}
</Paragraph>
<Tabs defaultActiveKey="1" type="card">
<TabPane key="1" tab="Таблица" style={{ background: '#fff' }}>
<Table
columns={COULUMNS}
dataSource={dataTable}
locale={{
emptyText: <Empty description="Справочник отсутствуeт" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
}}
rowClassName={() => 'editable-row'}
bordered
/>
</TabPane>
<TabPane key="2" tab="HTML">
Tab 2
</TabPane>
<TabPane key="3" tab="Изображения">
Tab 2
</TabPane>
<TabPane key="4" tab="Файл">
Tab 2
</TabPane>
</Tabs>
<Space size={20}>
<Button onClick={this.handleAddRow} icon={<PlusOutlined />} shape="round" type="primary">
Добавить телефон
</Button>
</Space>
<Space size={20}>
<Popconfirm
placement="topRight"
title="Вы действительно хотити удалить?"
okText="Да"
onConfirm={this.removeMark.bind(this)}
cancelText="Нет"
>
<Button danger>Удалить</Button>
</Popconfirm>
<Button onClick={() => this.setState({ edit: true })}>Редактировать</Button>
</Space>
|
'use strict';
var app = angular
.module('ngloginApp');
app.controller('RegisterCtrl', ['$rootScope', '$scope', '$log', '$route',
'$location', 'APIConfig', '$http', 'APIService','$timeout','$window','APIFactory',
function ($rootScope, $scope, $log, $route,
$location, APIConfig, $http, APIService,$timeout,$window,APIFactory) {
var api = APIService;
var fac = APIFactory;
$scope.account = APIConfig.account;
$scope.message = "";
$scope.hasError = false;
$scope.clicked = false;
$scope.mailstoneurl = APIConfig.mailstone;
$scope.userid = fac.getCookie('userid');
var clickedcount = 0;
$scope.saveUser = function(isValid){
$scope.clicked = true;
$scope.account.active =0;
if(isValid && clickedcount ===0){
clickedcount++;
if($scope.account.password1 == $scope.account.password2){
$scope.account.password = $scope.account.password1;
if(!$scope.checkEmail($scope.account.username)){
APIConfig.account = $scope.account;
api.service('user').data($scope.account).save().then(function(result){
$location.path('register');
clickedcount = 0;
},function(error){
clickedcount = 0;
if(error.status ==-1){
$location.path('register');
$scope.hasError = false;
}
if(error.status == 422){
$scope.hasError = true;
$scope.message = "Diese E-Mail-Adresse existiert schon";
}
});
}else{
clickedcount = 0;
$scope.hasError = true;
$scope.message = "Bitte geben Sie Ihre Unternehmens-E-Mail-Adresse an. E-Mail-Adressen von Massenmail-Providern wie beispielsweise gmx, icloud oder gmail können leider nicht akzeptiert werden.";
}
}else{
clickedcount = 0;
$scope.hasError = true;
$scope.message = "Die Passwörter Stimmen nicht überein";
}
}
}
$scope.initUser = function(){
if($scope.userid){
$http.get('scripts/settings.json').then(function (response) {
APIConfig.url = response.data.url;
api.service('user').id($scope.userid).get().then(function(user){
$scope.account = user;
},function(error){
$location.path('/');
});
});
}else{
$location.path('/');
}
}
$scope.updateUser = function(isValid){
$scope.clicked = true;
if(isValid){
var data = {
'department': $scope.account.department,
'ust_id' :$scope.account.ust_id,
'street' :$scope.account.street,
'plz' :$scope.account.plz,
'ort' :$scope.account.ort,
'phone' :$scope.account.phone
}
api.service('user').id($scope.userid).data(data).update().then(
function(result){
$window.location.href = fac.getCookie('url');
},function(error){
});
}else{
}
//$window.location.href = APIConfig.mailston;
}
$scope.checkEmail = function(){
var result = false;
var email = $scope.account.username;
for (var i=0; email != undefined && i< APIConfig.b2c_emails.length; i++) {
var em = APIConfig.b2c_emails[i];
if(email.includes("@"+em+"."))
result = true;
}
return result;
}
$scope.goBackTime = function(){
$timeout(function(){
$location.path('/');
}, 5000);
}
$scope.goBack = function(){
$window.history.back();
}
$scope.activate= function(){
$http.get('scripts/settings.json').then(function (response) {
APIConfig.url = response.data.url;
APIConfig.clientID = response.data.clientID;
APIConfig.b2c_emails = response.data.b2c_emails;
$rootScope.settings = response.data;
$rootScope.title = $rootScope.settings.title;
APIConfig.userid = $location.search().userid;
APIConfig.code = $location.search().hash
api.service('usersetting').id(APIConfig.userid).get().then(function(usersetting){
if(usersetting.code == APIConfig.code){
var data = {
'value':'activate',
'code' : APIConfig.code
}
api.service('usersetting').id(APIConfig.userid).data(data).update().then(function(result){
$location.path('activateok');
},function(error){
$location.path('activateerror');
})
}
},function(error){
$scope.hasError = true;
})
});
};
}]);
|
const AreaReducer = (state = {}, action) => {
if(action.type === "addAreaSuccess"){
var areas;
if(state)
areas = Object.assign({}, state);
else {
areas = {};
}
areas[action.area.name] = action.area;
return areas;
} else if(action.type === "gotAreas") {
var areas = {};
action.areas.forEach(area => {
areas[area.name] = area;
});
return areas;
}/* else if(action.type === "TOGGLE_AREA") {
var areas = state.concat();
var admin = false;
areas.forEach(area => {
if(area.name === action.area){
areas.selected = Object.assign({}, area);
return areas;
}
})
return areas;
}*/ else {
//if(state.length === 0) state.selected = null;
return state;
}
}
export default AreaReducer;
|
const fetch = require('node-fetch');
const glitchTextCD = {
list: async function () {
let _a = await global.db.ref('cooldown/glitchtext').get();
let _b = _a.val();
return Object.keys(_b)
},
update: async function (uid, data) {
await global.db.ref(`cooldown/glitchtext/${uid}`).set(data);
}
}
const handler = {
async exec({ m, args, MessageMedia, dbid, usedprefix }) {
let fullText = args.join(' ');
let _ft = fullText.split(' | ')
let cdList = await glitchTextCD.list();
if (!cdList.includes(dbid)) {
if (_ft.length >= 2) {
await glitchTextCD.update(dbid, {is: '1'})
await m.reply('Memproses..\n*Mohon tunggu sekitar 1 menit.*');
// await execute(_ft, messageFrom, filename)
try {
let _fetch = await fetch(`https://${global.API_URL}/glitch-text?text1=${encodeURIComponent(_ft[0])}&text2=${encodeURIComponent(_ft[1])}&fname=${dbid}`,{
mode: 'no-cors',
timeout: 0
})
if (_fetch.status !== 200) {
await glitchTextCD.update(dbid, {})
m.reply('*Gambar tidak dapat terkirim* _( Timeout )_\nMohon coba lagi nanti.');
}
let _res = await _fetch.json();
let mt = _res.results.data.mimetype;
let b64 = _res.results.data.base64;
if (b64.startsWith('/')) {
let media = new MessageMedia(mt, b64, '')
m.reply(media)
setTimeout(async () => {
glitchTextCD.update(dbid, {})
}, 5000);
} else {
await glitchTextCD.update(dbid, {})
m.reply('*Gambar tidak dapat terkirim, karena terjadi kesalahan sistem.*')
setTimeout(async () => {
glitchTextCD.update(dbid, {})
}, 5000);
}
} catch (err) {
m.reply(err)
setTimeout(async () => {
glitchTextCD.update(dbid, {})
}, 5000);
}
} else {
// m.reply('Masukkan format dengan benar\n*Contoh :* #glitchtext Clawbot | GG Gaming')
m.reply(`Masukkan format dengan benar\n*Contoh :* ${usedprefix}glitchtext Clawbot | GG Gaming`)
}
} else {
m.reply('Kamu sedang cooldown, coba lagi nanti!')
}
},
commands: ['glitchtext'],
tag: 'Maker',
help: ['glitchtext'].map(v => v + ' <Teks 1> | <Teks 2>')
}
module.exports = handler
|
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.text === 'get_parent_jira_issue') {
var parentIssue = document.querySelector("a#parent_issue_summary.issue-link")
var parentIssueLink = ""
if (parentIssue)
parentIssueLink = "<a href='" + parentIssue.href + "'>" + parentIssue.text + "</a>"
sendResponse(parentIssueLink);
}
});
|
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import { SET_PAGE_NUMBER } from '../actions/file';
import { selectImageSearchResult } from '../features/searchImage/searchImageSlice';
export const ImageSearchResult = () => {
const results = useSelector(selectImageSearchResult);
const dispatch = useDispatch();
const gotoSearchResult = (r) => {
dispatch({
type: SET_PAGE_NUMBER,
page: r.pageNum,
});
};
if (!results) {
return null;
}
return (
<div style={{ marginRight: '5px', overflow: 'hidden' }}>
<List dense>
{results.map((r, index) => (
// eslint-disable-next-line react/no-array-index-key
<ListItem key={`sr-${index}`} onClick={() => gotoSearchResult(r)}>
<div style={{ whiteSpace: 'nowrap' }}>
<span>
Page {r.pageNum}: x = {r.left}, y = {r.top}
</span>
</div>
</ListItem>
))}
</List>
</div>
);
};
export default ImageSearchResult;
|
'use strict'
const fp = require('fastify-plugin')
const {Sequelize, DataTypes} = require('sequelize');
module.exports = fp(async function (fastify
, opts) {
const sequelize = new Sequelize(opts.db.mysql.database, opts.db.mysql.username, opts.db.mysql.password, {
host: opts.db.mysql.host,
dialect: 'mysql' /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */,
pool: opts.db.mysql.pool,
logging: opts.db.mysql.logging,
dialectOptions: {
dateStrings: true,
typeCast: true
},
timezone: '+08:00',
});
// 映射数据库模型
const Order = sequelize.define('Order', {
// ... (attributes)
id: {type: DataTypes.STRING(40), primaryKey: true},
out_trade_no: DataTypes.STRING,
notify_url: DataTypes.STRING,
return_url: DataTypes.STRING,
type: DataTypes.STRING(10), // alipay weixin
pid: DataTypes.INTEGER,
title: DataTypes.STRING,
money: DataTypes.STRING,
status: DataTypes.INTEGER,
attach:DataTypes.STRING
}, {
tableName: 'gopay_order',
createdAt: true,
updatedAt: true
});
// await sequelize.sync({ after: true });
await sequelize.sync();
fastify.decorate('db', sequelize);
})
|
const Model = require('../models/guias');
const getGuias = async () => {
const guias = await Model.find();
return guias;
}
module.exports = {
list: getGuias,
}
|
Page({
/**
* 页面的初始数据
*/
data: {
currentData: 0,
selectPerson: true,
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let scrollHeight = wx.getSystemInfoSync().windowHeight-32;
this.setData({
scrollHeight: scrollHeight
})
},
//获取当前滑块的index
bindchange: function (e) {
const that = this;
that.setData({
currentData: e.detail.current
})
},
//点击切换,滑块index赋值
checkCurrent: function (e) {
const that = this;
if (that.data.currentData === e.target.dataset.current) {
return false;
} else {
that.setData({
currentData: e.target.dataset.current
})
}
},
addquestion:function(){
wx.navigateTo({
url: './addquestion/addquestion'
})
},
seenews: function () {
wx.navigateTo({
url: './seenews/seenews'
})
}
})
|
const expect = require('chai').expect;
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const spawn = require('cross-spawn');
const utils = require('./utils');
// const template = require('../scripts/inc/template_cg_v5');
const { getGlobalScripts, getCampaignScripts, getVariants } = require('../scripts//inc/generate');
const appDirectory = fs.realpathSync(process.cwd());
const tempDir = path.resolve(appDirectory, 'temp');
describe('generate', function(){
describe('getGlobalScripts', function(){
let dirControl = utils.directoryControl(
tempDir,
'getGlobalScripts'
);
let globalScripts;
before(function(done){
process.chdir(appDirectory);
dirControl.create().then(async function() {
process.chdir(dirControl.dir);
let srcDir = path.resolve(dirControl.dir, 'src');
let subDir = path.resolve(srcDir, 'global');
mkdirp(subDir, async function() {
fs.writeFileSync(path.resolve(subDir, 'global-1.js'), 'const global1 = true;\n\n');
globalScripts = await getGlobalScripts(dirControl.dir, srcDir);
done();
});
});
});
it('should have Global files', function(){
expect(Array.isArray(globalScripts), 'globalScripts is not an Array').to.be.true;
expect(globalScripts.length).to.equal(1, 'globalScripts should have a length of 1');
expect(globalScripts[0]).to.eql(
{
ext: 'js',
filePath: 'src/global/global-1.js',
name: 'global-1'
}
);
});
after(function(done) {
process.chdir(appDirectory);
dirControl.destroy().then(done);
});
});
describe('getCampaignScripts', function(){
let dirControl = utils.directoryControl(
tempDir,
'getCampaignScripts'
);
let campaignScripts;
before(function(done){
process.chdir(appDirectory);
dirControl.create().then(async function() {
process.chdir(dirControl.dir);
let srcDir = path.resolve(dirControl.dir, 'src');
let subDir = path.resolve(srcDir, 'campaignScripts');
mkdirp(subDir, async function() {
fs.writeFileSync(path.resolve(subDir, 'campaign-script-1.js'), 'const campaignScript1 = true;\n\n');
campaignScripts = await getCampaignScripts(dirControl.dir, srcDir);
done();
});
});
});
it('should have Campaign files', function(){
expect(Array.isArray(campaignScripts), 'campaignScripts is not an Array').to.be.true;
expect(campaignScripts.length).to.equal(1, 'campaignScripts should have a length of 1');
expect(campaignScripts[0]).to.eql(
{
ext: 'js',
filePath: 'src/campaignScripts/campaign-script-1.js',
name: 'campaign-script-1'
}
);
});
after(function(done) {
process.chdir(appDirectory);
dirControl.destroy().then(done);
});
});
describe('getVariants', function(){
let dirControl = utils.directoryControl(
tempDir,
'getVariants'
);
let variants;
before(function(done){
process.chdir(appDirectory);
dirControl.create().then(async function() {
process.chdir(dirControl.dir);
let srcDir = path.resolve(dirControl.dir, 'src');
let subDir = path.resolve(srcDir, 'variants');
mkdirp(subDir, async function() {
fs.writeFileSync(path.resolve(subDir, 'variant-1.js'), 'const variant1 = true;\n\n');
fs.writeFileSync(path.resolve(subDir, 'variant-1.scss'), '.variant1 { color: red;}\n\n');
fs.writeFileSync(path.resolve(subDir, 'variant-2.js'), 'const variant2 = true;\n\n');
variants = await getVariants(dirControl.dir, srcDir);
done();
});
});
});
it('should have variant files', function(){
expect(Object.keys(variants)).to.eql(['variant-1', 'variant-2']);
expect(variants).to.eql(
{
'variant-1': [
{ ext: 'scss', filePath: 'src/variants/variant-1.scss' },
{ ext: 'js', filePath: 'src/variants/variant-1.js' }
],
'variant-2': [
{ ext: 'js', filePath: 'src/variants/variant-2.js' }
] }
);
});
it('should have scss before js', function(){
let v = variants['variant-1'];
expect(v[0].ext).to.equal('scss');
expect(v[1].ext).to.equal('js');
});
after(function(done) {
process.chdir(appDirectory);
dirControl.destroy().then(done);
});
});
});
|
let router = require("express").Router();
let mongo = require("../../common/mongo");
router.get("/",(req,res)=>{
let commonDate = {
slides:req.session,
crumb:"首页",
active:"follow",
columnName:req.query.columnName,
'api_name':"product",
q:req.query.q,
time:req.query.time,
start:req.query.start,
rule:req.query.rule,
count:req.query.count,
id:req.query.id
}
mongo({
collection:"column",
callback:(collection,client,ObjectId)=>{
collection.find({}).toArray((err,result)=>{
commonDate.pid = result;
mongo({
collection:req.query.columnName,
callback:(collection,client,ObjectId)=>{
collection.find({
_id:ObjectId(req.query.id)
}).toArray((err,result)=>{
client.close();
// commonDate.pic = result[0].pic;
console.log(result[0].pic)
commonDate.result=result[0];
res.render("product/update",commonDate)
});
}
})
});
}
});
});
module.exports = router;
|
var renderButton;
var resultElement;
var init = function() {
console.log( "ready!" );
renderButton = $('#render')[0];
resultElement = $('#result');
var placeholder = $('#equation').attr('placeholder');
console.log(placeholder);
};
$( document ).ready(function() {
init();
renderButton.addEventListener('click', () => {
var input = $('#equation').val();
$('code').html(input);
$('code').each(function(i, block) {
hljs.highlightBlock(block);
});
console.log("input was: " + input);
$.ajax({
url: '/',
data: JSON.stringify({'input': input}),
contentType: 'application/json;charset=UTF-8',
type: 'POST',
success: function(response) {
var jsonData = JSON.parse(response);
var latex = jsonData.equation;
if(latex == ' ') {
$('#result').html('Something wrong with your python equation');
console.log(response);
} else {
var math = MathJax.Hub.getAllJax('result')[0];
MathJax.Hub.Queue(["Text", math, latex]);
console.log(response);
}
},
error: function(error) {
console.log(error);
var math = MathJax.Hub.getAllJax('result')[0];
MathJax.Hub.Queue(["Text", math, 'something wrong with your python expression']);
}
});
});
});
|
var unitNumPropActivationValues = [25, 50, 100, 250, 500, 1000, 2500, 5000, 10000];
class Achievement{
constructor(name, requiredProperties){
this.Name = name;
this.Props = requiredProperties;
this.Unlocked = false;
}
}
class AchievementController
{
constructor(){
this.Props = {};
this.Achievements = {};
this.getValue = function(PropertyName) {
return this.Props[PropertyName].Value;
};
this.setValue = function(PropertyName, Value){
this.Props[PropertyName].Value = Value;
};
this.checkAchievements = function(){
var aRet = [];
for (var n in this.Achievements) {
var aAchivement = this.Achievements[n];
if (aAchivement.Unlocked == false) {
var aActiveProps = 0;
for (var p = 0; p < aAchivement.Props.length; p++) {
var aProp = this.Props[aAchivement.Props[p]];
if (aProp.isActive()) {
aActiveProps++;
}
}
if (aActiveProps == aAchivement.Props.length) {
aAchivement.Unlocked = true;
aRet.push(aAchivement);
}
}
}
return aRet;
};
}
}
function AchievementInit(){
}
|
function mostrarHola() {
var numer1 = 5;
var numer2 = 7;
var total = numer1 + numer2;
console.log(total);
}
mostrarHola();
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
angular.module('appAnalist').controller('listPesqController',function($scope,$http,$routeParams,NgTableParams){
$scope.user = sessionStorage.userId;
$http({
url:'php/glistPesquisa.php',
method:'POST',
data:$routeParams.id
}).then(function(answer){
// $scope.resultados = answer.data;
var data = answer.data;
$scope.paramsTable = new NgTableParams({
},{
dataset:data
});
});
});
|
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const cors = require("cors");
const { initDB, getRandomQuestions } = require("./DB/Models/Question");
app.use(cors());
initDB();
app.use(express.static("website"));
const port = 4000;
app.listen(port, () => {
console.log(`Server is up and listening on port ${port}`);
});
// Setup Server
//Get all route
app.get("/api/questions/", getData);
async function getData(req, res) {
const questions = await getRandomQuestions();
res.send(questions);
console.log("Sending 5 random questions: \n" + JSON.stringify(questions));
}
|
/**
* application class, cares on initialization and maintenance
* @namespace
* @param {number} id the document id
*/
vonline.Document = function(id) {
this.id = id;
// storage for undo-/redoable actions
this.undoList = [];
this.redoList = [];
// observe if command was executed
var that = this;
vonline.events.bind('commandexec', function(event, command) {
that.undoList.push(command);
that.redoList = [];
that.updateMenu();
that.saveItem.enable();
});
this.transport = new vonline.Transport(this);
// initialization of UI
this.sidebar = new vonline.Sidebar('#sidebar');
// init top menu
this.sidebar.setTopMenu(this.initTopMenu());
this.updateMenu();
this.snapshotHistory = new vonline.SnapshotHistory(this, this.sidebar, this.transport);
// init bottom menu
this.sidebar.setBottomMenu(this.initBottomMenu());
this.loadCategories();
this.canvas = new vonline.Canvas();
vonline.events.bind('drop', function(event, data) {
var command = new vonline.CreateCommand(that.canvas, data);
command.execute();
vonline.events.trigger('commandexec', command);
});
// load latest snapshot
this.loadSnapshot(-1);
}
/**
* initializes the top-menu
* @return {vonline.Menu}
*/
vonline.Document.prototype.initTopMenu = function() {
var that = this, // reference to current context (need to get the correct scope in click-hanlder functions)
topmenu = new vonline.Menu();
topmenu.addItem(new vonline.MenuItem('open an other document', 'images/menu/open_document_view', function() {
that.openDocumentView();
}));
this.undoItem = new vonline.MenuItem('undo last action', 'images/menu/undo', function() {
that.undoCommand();
});
topmenu.addItem(this.undoItem);
this.redoItem = new vonline.MenuItem('redo previous action', 'images/menu/redo', function() {
that.redoCommand();
});
topmenu.addItem(this.redoItem);
this.saveItem = new vonline.MenuItem('save a snapshot of the current document', 'images/menu/save', function() {
that.saveSnapshot();
});
topmenu.addItem(this.saveItem);
topmenu.addItem(new vonline.MenuItem('view the history of the current document', 'images/menu/open_history', function() {
that.snapshotHistory.toggle();
}));
return topmenu;
}
/**
* initializes the bottom-menu
* @return {vonline.Menu}
*/
vonline.Document.prototype.initBottomMenu = function() {
var bottommenu = new vonline.Menu(),
that = this;
bottommenu.addItem(new vonline.MenuItem('edit categories', 'images/menu/open_category_edit_view', function() {
if (that.categoryEditView.toggle()) {
that.transport.saveCategories(that.categoryEditView.getCategories());
}
}));
bottommenu.addItem(new vonline.MenuItem('zoom in', 'images/menu/zoom_in', function() {
var zoom = that.canvas.getZoom();
if (zoom * 2 <= 16) {
that.canvas.setZoom(zoom * 2);
}
}));
bottommenu.addItem(new vonline.MenuItem('zoom out', 'images/menu/zoom_out', function() {
var zoom = that.canvas.getZoom();
if (zoom / 2 >= 0.125) {
that.canvas.setZoom(zoom / 2);
}
}));
bottommenu.addItem(new vonline.MenuItem('zoom to original', 'images/menu/zoom_original', function() {
that.canvas.setZoom(1);
that.canvas.setOffset(0, 0);
}));
bottommenu.addItem(new vonline.MenuItem('zoom fit best', 'images/menu/zoom_fit_best', function() {
that.canvas.setZoom('fit');
}));
return bottommenu;
}
/**
* disable undo/redo-button if there is nothing to undo/redo
*/
vonline.Document.prototype.updateMenu = function() {
if (this.undoList.length == 0) {
this.undoItem.disable();
}
else {
this.undoItem.enable();
}
if (this.redoList.length == 0) {
this.redoItem.disable();
}
else {
this.redoItem.enable();
}
vonline.events.trigger('canvaschanged');
}
/**
* redirect browser to document list
*/
vonline.Document.prototype.openDocumentView = function() {
window.location.href = 'index.php';
}
/**
* undo action (if possible)
*/
vonline.Document.prototype.undoCommand = function() {
if (this.undoList.length > 0) {
var command = this.undoList.pop();
command.undo();
this.redoList.push(command);
this.updateMenu();
}
}
/**
* redo action (if possible)
*/
vonline.Document.prototype.redoCommand = function() {
if (this.redoList.length > 0) {
var command = this.redoList.pop();
command.execute();
this.undoList.push(command);
this.updateMenu();
}
}
/**
* loads specific snapshot and display the corresponding document
* @param {number} id the snapshot id (-1 for latest snapshot)
*/
vonline.Document.prototype.loadSnapshot = function(id) {
var that = this;
this.transport.loadSnapshot(id, function(json) {
// load objects
that.canvas.load(json.objects);
that.undoList = [];
that.redoList = [];
that.updateMenu();
});
}
/**
* save a snapshot of the current document / send document data to server
*/
vonline.Document.prototype.saveSnapshot = function() {
var that = this;
documentData = JSON.stringify({objects: this.canvas.exportJSON()});
// TODO: add other stuff that needs to be saved
this.transport.saveSnapshot(documentData, function(data) {
var status = 'Snapshot saved ' + format_time(new Date());
vonline.notification.add(status);
vonline.events.trigger('snapshotsaved');
});
this.saveItem.disable();
}
/**
* load the categories for the document
*/
vonline.Document.prototype.loadCategories = function() {
var that = this;
this.transport.loadCategories(function(json) {
var visible = [],
notvisible = [];
for (var name in json) {
var category = new vonline.Category(name, json[name].id)
for (var item in json[name].elements) {
category.add(new vonline.CategoryItem(item, json[name].elements[item], that.canvas));
}
if (json[name].show) {
visible.push(category);
that.sidebar.addCategory(category);
}
else {
notvisible.push(category);
}
}
that.categoryEditView = new vonline.CategoryEditView(that.sidebar, visible, notvisible);
});
}
|
import React, { Component } from 'react';
import { Flex } from 'grid-styled';
import axios from 'axios';
import Input from './utilities/Input';
import Button from './utilities/Button';
import Tile from './utilities/Tile';
import Form from './utilities/Form';
export default class extends Component {
constructor(){
super();
this.state = {}
this.submitForm = this.submitForm.bind(this);
}
submitForm(e) {
e.preventDefault();
axios.post('/topUp', this.state)
.then((data) => this.setState({...this.state, topup: data.data}));
}
render() {
return (
<Tile wrap width={1} justify='center'>
<Flex wrap justify='center' mb={3}>
<Flex wrap justify='center'>
<h4> TOP UP </h4>
</Flex>
<Flex width={1}>
<a>This will top up your account by <strong>£10.00</strong></a>
</Flex>
</Flex>
<Flex width={1}>
<Form onSubmit={this.submitForm}>
<Input onChange={(event) => this.setState({...this.state, account: event.target.value})}
placeholder="Enter account ID"/>
<Button type="submit"> Topup </Button>
</Form>
</Flex>
<p> {this.state.topup} </p>
</Tile>
)
}
}
|
import styled, { keyframes } from "styled-components";
const ToRightAnimation = keyframes`
0% {
transform: translateX(-100%);
opacity: 0;
}
100% {
transform: translateX(0);
opacity: 1;
}
`;
const ToBottomAnimation = keyframes`
0% {
transform: translateY(-50%);
opacity: 0;
}
100% {
transform: translateY(0);
opacity: 1;
}
`;
export const AboutContainer = styled.div`
display: flex;
justify-content: center;
align-items: center;
color: grey;
font-size: 30px;
padding: 4%;
position: relative;
top: 20px;
@media (max-width: 768px) {
position: relative;
top: 170px;
font-size: 18px;
}
`;
export const AboutDiv = styled.div``;
export const AboutContentDiv = styled.div`
animation: 1s ease-out 0s 1 ${ToRightAnimation};
`;
export const AboutTextTyperDiv = styled.div``;
export const AboutImg = styled.img`
animation: 1s ease-out 0s 1 ${ToBottomAnimation};
width: 450px;
height: 450px;
@media (max-width: 768px) {
display: none;
}
`;
export const AboutH2 = styled.h2`
margin-top: 4%;
`;
export const AboutP = styled.p`
margin-top: 2%;
max-width: 85%;
`;
export const AboutButton = styled.button`
margin-top: 2%;
`;
|
import SubscriptionReference from './subscription-reference';
export default class CompositeSubscriptionReference extends SubscriptionReference {
add(subscription) {
if(!this._subscription) {
this.pendingAdds = this.pendingAdds || [];
this.pendingAdds.push(subscription);
} else {
this._subscription.add(subscription);
}
}
remove(subscription) {
if(!this._subscription && this.pendingAdds) {
this.pendingAdds.splice(this.pendingAdds.indexOf(subscription), 1);
} else {
this._subscription.remove(subscription);
}
}
setSubscription(subscription) {
if(this.pendingAdds) {
var i, len;
for(i = 0, len = this.pendingAdds.length; i < len; i++) {
subscription.add(this.pendingAdds[i]);
}
this.pendingAdds = null;
}
return SubscriptionReference.prototype.setSubscription.call(this, subscription);
}
}
|
angular.module('softtechApp')
.factory('$dataFactory',function(){
var menuActive = {};
var baseUrl = 'http://127.0.0.1:3000';
var setLogin = function(item){sessionStorage.setItem('loginApp',JSON.stringify(item))};
var getLogin = function(){return JSON.parse(sessionStorage.getItem('loginApp'))};
var logout = function(){sessionStorage.clear()};
var isLogged = function(){
if(sessionStorage.getItem('loginApp')){
return true;
}else{
return false;
}
};
return {
menuActive: menuActive,
baseUrl: baseUrl,
setLogin: setLogin,
getLogin: getLogin,
logout: logout,
isLogged: isLogged
};
})
.factory('uuid', function() {
var svc = {
new: function() {
function _p8(s) {
var p = (Math.random().toString(16)+"000000000").substr(2,8);
return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ;
}
return _p8() + _p8(true) + _p8(true) + _p8();
},
empty: function() {
return '00000000-0000-0000-0000-000000000000';
}
};
return svc;
})
.factory('authInterceptor', function($location, $q, $window, $dataFactory) {
return {
request: function(config) {
config.headers = config.headers || {};
if($dataFactory.isLogged()){
config.headers.Authorization = 'Bearer '+$dataFactory.getLogin().appToken;
}
return config;
}
};
})
|
import { combineReducers } from 'redux'
import auth from 'admin/reducers/AuthentificationReducer'
import { reducer as formReducer } from 'redux-form'
/**
* Insert here any 'static' created reducers
* @param {*} asyncReducers
*/
export const makeRootReducer = (asyncReducers) => {
return combineReducers({
auth,
form: formReducer,
...asyncReducers,
})
}
/**
* Use this function if you wish to insert any reducer to store
* For example in route onEnter function
* @param {*} store
*/
export const injectReducer = (store, { key, reducer }) => {
if (Object.hasOwnProperty.call(store.asyncReducers, key)) return
store.asyncReducers[key] = reducer
store.replaceReducer(makeRootReducer(store.asyncReducers))
}
export default makeRootReducer
|
/*const initialState = {
payload: 'ZENIT'
}*/
const Statenull = (state, action) => {
//let value;
switch (action.type) {
case 'STATE_NULL' :
return Object.assign({}, state, {
value: null
})
default:
return state
}
}
export default Statenull;
/*return
[
...state,
{value: action.value}
]
*/
|
const net = require('net');
const {getRandomBookId} = require('../code');
const socket = new net.Socket();
socket.connect({
host: '127.0.0.1',
port: 3000,
});
/**
* 计数器
* @returns {object}
*/
const count = () => {
let num = 0;
return {
get() {
return num;
},
add() {
num += 1;
}
}
}
// 数据包序号
const currentIndex = count();
/**
* 组装一个二进制包,默认协议内容为:1-2字节为包序号,3-6字节为包长度,后面是包内容
* @returns {buffer}
*/
const encode = () => {
// 内容
const body = Buffer.alloc(2);
const bookId = getRandomBookId();
body.write(bookId);
// 头内容
const header = Buffer.alloc(6);
header.writeInt16BE(currentIndex.get());
header.writeInt32BE(body.length, 2);
// 拼接数据包
const buffer = Buffer.concat([header, body]);
console.log(`包${currentIndex.get()}传输的课程 id 为${bookId}`);
currentIndex.add();
return buffer;
}
/**
* 拆解一个二进制包
* @param {buffer} 二进制数据包
* @returns {object}
*/
const decode = (buffer) => {
if (buffer instanceof Buffer) {
const header = buffer.slice(0, 6);
const body = buffer.slice(6);
const index = header.readUInt16BE();
return {
success: true,
data: {
index,
text: body.toString(),
}
}
}
return {
success: false,
message: '数据包格式不正确',
}
}
/**
* 检查获取一个包的长度,默认公示为:头部长度(6)+ 存储在头部的包长度
* 如果长度小于6,则说明被拆包,需要与下个包数据拼接使用,故返回 0 。
* @param {buffer} buffer
* @returns {number}
*/
const checkBufferLen = (buffer) => {
if (buffer instanceof Buffer) {
// 头部信息不全时,可能是因为内容超长被拆包了
if (buffer.length < 6) {
return 0;
}
const length = 6 + buffer.readInt32BE(2);
return buffer.length >= length ? length : 0;
}
return 0;
}
// 残留的数据
let residualBuffer = null;
socket.on('data', (buffer) => {
// 拼接残留的 buffer
if(residualBuffer) {
buffer = Buffer.concat([residualBuffer, buffer]);
}
let completeLen = 0;
// 分包解析
while(completeLen = checkBufferLen(buffer)) {
const package = buffer.slice(0, completeLen);
buffer = buffer.slice(completeLen);
const res = decode(package);
if (res.success) {
console.log(`包${res.data.index}, 返回值是${res.data.text}`);
}
}
residualBuffer = buffer;
});
// 是否模拟网络波动
const isRandom = true;
// 连续发出 10 个请求
for(let i = 0; i < 10; i++) {
if (isRandom) {
setTimeout(() => {
socket.write(encode());
}, Math.round(Math.random() * 1000));
} else {
socket.write(encode());
}
}
|
import CarsApp from '@/Pages/Cars';
import MotorcyclesApp from '@/Pages/Motorcycles';
import Home from '@/Pages/Home';
const routes = [{
path: '/',
name: 'Home',
component: Home
},
{
path: '/cars',
name: 'Cars',
component: CarsApp
},
{
path: '/motorcycles',
name: 'Motorcycles',
component: MotorcyclesApp
}
];
export default routes;
|
import React, { useState } from "react";
import PropTypes from "prop-types";
import MyCollapse from "../Collapse";
function MultiCollapse(props) {
const { collapseList, isShowTheFirst, isAdmin } = props;
const [activeTab, setActiveTab] = useState(isShowTheFirst ? 0 : 1000);
const handleActiveTab = (tab) => {
if (tab === activeTab) {
setActiveTab(1000);
} else {
setActiveTab(tab);
}
};
return (
<>
{collapseList.map((item, index) => (
<MyCollapse
key={index}
header={item.header}
body={item.body}
isOpen={activeTab === index}
setIsOpen={handleActiveTab}
tab={index}
{...props}
/>
))}
</>
);
}
MultiCollapse.propTypes = {
collapseList: PropTypes.array,
isShowTheFirst: PropTypes.bool,
isAdmin: PropTypes.bool,
};
MultiCollapse.defaultProps = {
collapseList: [],
isShowTheFirst: true,
isAdmin: false,
};
export default MultiCollapse;
|
import React from 'react';
import { extend } from 'underscore';
const TestUtils = React.addons.TestUtils;
function simulate (eventType, node) {
TestUtils.Simulate[eventType](node);
}
module.exports = {
render: (Component, options) => {
extend({}, options);
return TestUtils.renderIntoDocument(Component(options));
},
click: (node) => {
simulate('click', node);
}
};
export const renderedOutput = (elt) => {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(elt);
return shallowRenderer.getRenderOutput();
};
|
import React from 'react';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import Avatar from '@material-ui/core/Avatar';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
// data
import users from 'Assets/data/chat-app/users';
// helpers
import { textTruncate } from 'Helpers/helpers';
const ChatSidebar = () => (
<div className="chat-sidebar rct-customizer">
<AppBar position="static" color="primary">
<Toolbar>
<Typography variant="title" color="inherit">
Chat
</Typography>
</Toolbar>
</AppBar>
<List>
{users.map((user, key) => (
<ListItem key={key} button>
<Avatar src={user.photo_url} />
<ListItemText
primary={user.first_name + ' ' + user.last_name}
secondary={textTruncate(user.last_chat, 16)}
/>
</ListItem>
))}
</List>
</div>
);
export default ChatSidebar;
|
require('/javascripts/jquery.js')
require('/javascripts/core.js')
describe('Ql core', function () {
it("should return a QL object" , function() {
expect(Ql).toBeTypeOf('object');
})
it("should be a Ql object" , function() {
expect(Ql).toBe(window.Ql);
})
describe('Ql helpers', function() {
var testArray = ['a','b','c'],
resultObject = {a:'',b:'',c:''};
it('should find the string in the array', function(){
expect(Ql.helpers.arraySearch(testArray)).toEqual(resultObject);
})
})
})
|
describe('VglGeometry:', function suite() {
const { VglGeometry, VglNamespace } = VueGL;
it('without properties', function test(done) {
const vm = new Vue({
template: '<vgl-namespace><vgl-geometry ref="g" /></vgl-namespace>',
components: { VglGeometry, VglNamespace },
}).$mount();
vm.$nextTick(() => {
try {
const expected = new THREE.BufferGeometry();
expect(expected.toJSON()).to.deep.equal(expected.copy(vm.$refs.g.inst).toJSON());
done();
} catch (e) {
done(e);
}
});
});
it('with properties', function test(done) {
const vm = new Vue({
template: '<vgl-namespace><vgl-geometry position-attribute="3, 1, 2, 2, -5, 6.3" color-attribute="0.8, 0.7, 0.9, 1, 0.1, 0.2" normal-attribute="2, 0, 0, -3, 4, 3" ref="g" /></vgl-namespace>',
components: { VglGeometry, VglNamespace },
}).$mount();
vm.$nextTick(() => {
try {
const expected = new THREE.BufferGeometry();
expected.addAttribute('position', new THREE.BufferAttribute(new Float32Array([3, 1, 2, 2, -5, 6.3]), 3));
expected.addAttribute('color', new THREE.BufferAttribute(new Float32Array([0.8, 0.7, 0.9, 1, 0.1, 0.2]), 3));
expected.addAttribute('normal', new THREE.BufferAttribute(new Float32Array([2, 0, 0, -3, 4, 3]), 3));
expect(expected.toJSON()).to.deep.equal(expected.copy(vm.$refs.g.inst).toJSON());
done();
} catch (e) {
done(e);
}
});
});
it('after properties are changed', function test(done) {
const vm = new Vue({
template: '<vgl-namespace><vgl-geometry :position-attribute="positionAttribute" :color-attribute="colorAttribute" :normal-attribute="normalAttribute" ref="g" /></vgl-namespace>',
components: { VglGeometry, VglNamespace },
data: {
positionAttribute: '3, 1, 2, 2, -5, 6.3',
colorAttribute: '0.8, 0.7, 0.9, 1, 0.1, 0.2',
normalAttribute: '2, 0, 0, -3, 4, 3',
},
}).$mount();
vm.$nextTick(() => {
vm.positionAttribute = '3.21, -1, 2.3, 2.08, -5, 6.3';
vm.colorAttribute = '0.85, 0.7, 0.9, 0.99, 0.11, 0.25';
vm.normalAttribute = '2.2, 0, -10, 3, 4.8, 3';
vm.$nextTick(() => {
try {
const expected = new THREE.BufferGeometry();
expected.addAttribute('position', new THREE.BufferAttribute(new Float32Array([3.21, -1, 2.3, 2.08, -5, 6.3]), 3));
expected.addAttribute('color', new THREE.BufferAttribute(new Float32Array([0.85, 0.7, 0.9, 0.99, 0.11, 0.25]), 3));
expected.addAttribute('normal', new THREE.BufferAttribute(new Float32Array([2.2, 0, -10, 3, 4.8, 3]), 3));
expect(expected.toJSON()).to.deep.equal(expected.copy(vm.$refs.g.inst).toJSON());
done();
} catch (e) {
done(e);
}
});
});
});
it('after attribute lengths are extended', function test(done) {
const vm = new Vue({
template: '<vgl-namespace><vgl-geometry :position-attribute="positionAttribute" :color-attribute="colorAttribute" :normal-attribute="normalAttribute" ref="g" /></vgl-namespace>',
components: { VglGeometry, VglNamespace },
data: {
positionAttribute: '3, 1, 2, 2, -5, 6.3',
colorAttribute: '0.8, 0.7, 0.9, 1, 0.1, 0.2',
normalAttribute: '2.2, 0, -10, 3, 4.8, 3',
},
}).$mount();
vm.$nextTick(() => {
vm.positionAttribute = '3.21, -1, 2.3, 2.08, -5, 6.3, 2.4, 3.1, 1.1';
vm.colorAttribute = '0.85, 0.7, 0.9, 0.99, 0.11, 0.25, 0.1, 0.99, 0.5';
vm.normalAttribute = '-2.2, 0, -10, 3, 4.8, 3, 4, 4, 4';
vm.$nextTick(() => {
try {
const expected = new THREE.BufferGeometry();
expected.addAttribute('position', new THREE.BufferAttribute(new Float32Array([3.21, -1, 2.3, 2.08, -5, 6.3, 2.4, 3.1, 1.1]), 3));
expected.addAttribute('color', new THREE.BufferAttribute(new Float32Array([0.85, 0.7, 0.9, 0.99, 0.11, 0.25, 0.1, 0.99, 0.5]), 3));
expected.addAttribute('normal', new THREE.BufferAttribute(new Float32Array([-2.2, 0, -10, 3, 4.8, 3, 4, 4, 4]), 3));
expect(expected.toJSON()).to.deep.equal(expected.copy(vm.$refs.g.inst).toJSON());
done();
} catch (e) {
done(e);
}
});
});
});
it('after attribute lengths are shortened', function test(done) {
const vm = new Vue({
template: '<vgl-namespace><vgl-geometry :position-attribute="positionAttribute" :color-attribute="colorAttribute" :normal-attribute="normalAttribute" ref="g" /></vgl-namespace>',
components: { VglGeometry, VglNamespace },
data: {
positionAttribute: '3, 1, 2, 2, -5, 6.3',
colorAttribute: '0.8, 0.7, 0.9, 1, 0.1, 0.2',
normalAttribute: '2.2, 0, -10, 3, 4.8, 3',
},
}).$mount();
vm.$nextTick(() => {
vm.positionAttribute = '3.21, -1, 2.3';
vm.colorAttribute = '0.85, 0.7, 0.95';
vm.normalAttribute = '-2, -1.1, 5';
vm.$nextTick(() => {
try {
const expected = new THREE.BufferGeometry();
expected.addAttribute('position', new THREE.BufferAttribute(new Float32Array([3.21, -1, 2.3]), 3));
expected.addAttribute('color', new THREE.BufferAttribute(new Float32Array([0.85, 0.7, 0.95]), 3));
expected.addAttribute('normal', new THREE.BufferAttribute(new Float32Array([-2, -1.1, 5]), 3));
expect(expected.toJSON()).to.deep.equal(expected.copy(vm.$refs.g.inst).toJSON());
done();
} catch (e) {
done(e);
}
});
});
});
});
|
const CPUProfiler = require("./cpu-profiler/app")
const tCPUProfile = require("./cpu-profiler/template")
let Control = function () {
this.elWebView = document.getElementById("web-view")
this.elAddress = document.getElementById("address")
this.elLoadBtn = document.getElementById("load-btn")
this.elRecBtn = document.getElementById("rec-btn")
this.rightPane = document.getElementById("pane-right")
this.cpuProfiler = null
this.elAddress.addEventListener("keydown", (e) => {
if (e.keyCode === 13) // Enter
this.loadUrl()
})
this.elLoadBtn.addEventListener("click", () => {
this.loadUrl()
})
this.elRecBtn.addEventListener("click", () => {
if (this.cpuProfiler) {
if (this.cpuProfiler.isRunning()) {
this.elRecBtn.classList.remove("started")
this.cpuProfiler.stop((data) => {
this.rightPane.innerHTML = tCPUProfile(data.time, data.data)
})
} else {
this.elRecBtn.classList.add("started")
this.cpuProfiler.start()
}
}
})
this.elWebView.addEventListener("will-navigate", (e) => {
this.elAddress.value = e.url
this.elLoadBtn.classList.add("loading")
})
this.elWebView.addEventListener("dom-ready", () => {
this.elLoadBtn.classList.remove("loading")
if (!this.cpuProfiler)
this.cpuProfiler = new CPUProfiler(this.elWebView)
})
}
Control.prototype.loadUrl = function () {
let url = this.elAddress.value
if (url) {
this.elLoadBtn.classList.add("loading")
if (!url.startsWith("http")) {
url = `http://${url}` // try http version if is not in url
this.elAddress.value = url
}
this.elWebView.loadURL(url)
}
}
new Control()
|
function solve(people,groupType,dayOfWeek){
let price;
let totalSum;
if (dayOfWeek === "Friday") {
if (groupType === "Students") {
price = 8.45;
}else if (groupType === "Business") {
price = 10.90;
}else{
price = 15;
}
}else if (dayOfWeek === "Saturday") {
if (groupType === "Students") {
price = 9.80;
}else if (groupType === "Business") {
price = 15.60;
}else{
price = 20;
}
}else if (dayOfWeek === "Sunday"){
if (groupType === "Students") {
price = 10.46;
}else if (groupType === "Business") {
price = 16;
}else{
price = 22.50;
}
}
totalSum = price * people;
if (groupType === "Students" && people >= 30) {
totalSum -= (totalSum * 0.15);
}
if (groupType === "Business" && people >= 100) {
totalSum -= price * 10;
}
if (groupType === "Regular" && (people >= 10 && people <= 20)) {
totalSum -= (totalSum * 0.05);
}
console.log(`Total price: ${totalSum.toFixed(2)}`);
}
solve(105,"Business", "Friday");
|
import React from 'react';
function HSLToRGB(h,s,l,a=1) {
// Must be fractions of 1
s /= 100;
l /= 100;
let c = (1 - Math.abs(2 * l - 1)) * s,
x = c * (1 - Math.abs((h / 60) % 2 - 1)),
m = l - c/2,
r = 0,
g = 0,
b = 0;
if (0 <= h && h < 60) {
r = c; g = x; b = 0;
} else if (60 <= h && h < 120) {
r = x; g = c; b = 0;
} else if (120 <= h && h < 180) {
r = 0; g = c; b = x;
} else if (180 <= h && h < 240) {
r = 0; g = x; b = c;
} else if (240 <= h && h < 300) {
r = x; g = 0; b = c;
} else if (300 <= h && h < 360) {
r = c; g = 0; b = x;
}
r = Math.round((r + m) * 255);
g = Math.round((g + m) * 255);
b = Math.round((b + m) * 255);
console.log("rgba(" + r + "," + g + "," + b + "," + a + ")")
return "rgba(" + r + "," + g + "," + b + "," + a + ")";
}
function convertHSLtoRGB(hsl) {
let hslArr = hsl.split("-");
return HSLToRGB(hslArr[0], hslArr[1], hslArr[2], hslArr[3]);
}
function App() {
return (
<div className="App">
<h1 style={{padding: '20px'}}>Color Pallete Implementation</h1>
<section style={{display: 'flex', flexWrap: 'wrap', width: '100%', height: '100%', alignContent: 'center', alignItems: 'center'}}>
{
colors.map( color => {
return(
<div key={color.tokenName} style={{
width: '300px',
height: '280px',
margin: '10px',
backgroundColor: convertHSLtoRGB(color.hslValue),
boxShadow: '1px 1px 1px 1px rgba(0,0,0,0)',
display: 'flex'
}}>
<h4 style={labelstyles}>{color.tokenName}</h4> <br />
<p style={labelstyles}>{color.colorName}</p>
</div>
)
})
}
</section>
</div>
);
}
const labelstyles = {
margin: 'auto'
}
const colors = [
{
"tokenName": "$ui-background",
"role": "Primary page background",
"colorName": "White",
"hslValue": "0-0-100"
},
{
"tokenName": "$ui-01",
"role": "Container background on $ui-background / Secondary page background",
"colorName": "Gray 90",
"hslValue": "0-0-90"
},
{
"tokenName": "$ui-02",
"role": "Container background on $ui-01",
"colorName": "White",
"hslValue": "0-0-100"
},
{
"tokenName": "$ui-03",
"role": "Subtle borders / Tertiary background",
"colorName": "Gray 80",
"hslValue": "0-0-80"
},
{
"tokenName": "$ui-04",
"role": "Medium contrast border",
"colorName": "Gray 50",
"hslValue": "0-0-50"
},
{
"tokenName": "$ui-05",
"role": "High contrast border/ Emphasis elements",
"colorName": "Gray 10",
"hslValue": "0-0-10"
},
{
"tokenName": "$icon-01",
"role": "Primary icons",
"colorName": "Gray 10",
"hslValue": "0-0-10"
},
{
"tokenName": "$interactive-01",
"role": "Primary interactive color(Active)",
"colorName": "Blue 50",
"hslValue": "220-70-50"
},
{
"tokenName": "$interactive-02",
"role": "Secondary interactive color (Active)",
"colorName": "Gray 20",
"hslValue": "0-0-20"
},
{
"tokenName": "$interactive-03",
"role": "Tertiary button: Text + Icons (Active)",
"colorName": "Blue 50",
"hslValue": "0-0-50"
},
{
"tokenName": "$interactive-04",
"role": "Selected elements / Active elements",
"colorName": "Blue 50",
"hslValue": "0-0-50"
},
{
"tokenName": "$interactive-danger",
"role": "Danger button background",
"colorName": "Red 50",
"hslValue": "357-76-50"
},
{
"tokenName": "$icon-02",
"role": "Secondary icons",
"colorName": "Gray 40",
"hslValue": "0-0-40"
},
{
"tokenName": "$disabled-icon",
"role": "Disabled icons",
"colorName": "Gray 70",
"hslValue": "0-0-70"
},
{
"tokenName": "$field-01",
"role": "Input field for $ui-background",
"colorName": "Gray 90",
"hslValue": "0-0-90"
},
{
"tokenName": "$disabled-01",
"role": "Disabled fields / Disabled fields /",
"colorName": "Gray 90",
"hslValue": "0-0-90"
},
{
"tokenName": "$disabled-02",
"role": "Disabled buttons",
"colorName": "Gray 70",
"hslValue": "0-0-70"
},
{
"tokenName": "$disabled-03",
"role": "Disabled text on $disabled-02 / disabled icons on $disabled-02",
"colorName": "Gray 50",
"hslValue": "0-0-50"
},
{
"tokenName": "$field-02",
"role": "Input field for $ui-01",
"colorName": "White",
"hslValue": "0-0-100"
},
{
"tokenName": "$hover-primary",
"role": "Hover for $interactive-01",
"colorName": "Blue 60",
"hslValue": "220-70-60"
},
{
"tokenName": "$clicked-primary",
"role": "Clicked for $interactive-01",
"colorName": "Blue 40",
"hslValue": "220-70-40"
},
{
"tokenName": "$fdisabled-fields",
"role": "Disabled fileds",
"colorName": "Gray 70",
"hslValue": "0-0-70"
},
{
"tokenName": "$hover-secondary",
"role": "Hover for $interactive-02",
"colorName": "Gray 30",
"hslValue": "0-0-30"
},
{
"tokenName": "$clicked-secondary",
"role": "Clicked for $interactive-02",
"colorName": "Gray 10",
"hslValue": "0-0-10"
},
{
"tokenName": "$link-01",
"role": "Primary links",
"colorName": "Blue 50",
"hslValue": "220-70-50"
},
{
"tokenName": "$hover-tertiary",
"role": "Hover for $interactive-03",
"colorName": "Blue-60",
"hslValue": "220-70-60"
},
{
"tokenName": "$skeleton-01",
"role": "Skeleton text for $ui-background / Skeleton elements foor $ui-background",
"colorName": "Gray 90",
"hslValue": "0-0-90"
},
{
"tokenName": "$visited-link",
"role": "Visited link",
"colorName": "Blue 40",
"hslValue": "220-70-40"
},
{
"tokenName": "$text-01",
"role": "Primary text / Body copy / Headers / Hover text for $text-02",
"colorName": "Gray 10",
"hslValue": "0-0-10"
},
{
"tokenName": "$text-02",
"role": "Secondary text / Input labels",
"colorName": "Gray 30",
"hslValue": "0-0-30"
},
{
"tokenName": "$text-03",
"role": "Placeholder text",
"colorName": "Gray 40",
"hslValue": "0-0-40"
},
{
"tokenName": "$text-04",
"role": "Text on $interactive-01 and its states / Text on $interactive-02 / Text on $interactive-danger",
"colorName": "White",
"hslValue": "0-0-100"
},
{
"tokenName": "$text-05",
"role": "Tertiary text / Help text",
"colorName": "Gray 50",
"hslValue": "0-0-50"
},
{
"tokenName": "$text-error",
"role": "Error message text",
"colorName": "Red 50",
"hslValue": "0-0-50"
},
{
"tokenName": "$disabled-text",
"role": "Disabled text on disabled interactive elements",
"colorName": "Gray 70",
"hslValue": "0-0-70"
},
{
"tokenName": "$link-01",
"role": "Primary links / Ghost buttons",
"colorName": "Blue 50",
"hslValue": "220-70-50"
},
{
"tokenName": "$skeleton-02",
"role": "Skeleton text for $ui-01 / Skeleton elements for $ui-01",
"colorName": "White",
"hslValue": "0-0-100"
},
{
"tokenName": "$field-01",
"role": "Input fields for $ui-background",
"colorName": "Gray 90",
"hslValue": "0-0-90"
},
{
"tokenName": "$field-02",
"role": "Input fields for $ui-01",
"colorName": "White",
"hslValue": "0-0-100"
},
{
"tokenName": "$overlay-01",
"role": "Background overlay",
"colorName": "Gray 10",
"hslValue": "0-0-10-0.5"
},
{
"tokenName": "$highlight-01",
"role": "Selected elements / Active elements",
"colorName": "Blue 50",
"hslValue": "220-70-50"
},
{
"tokenName": "$success-01",
"role": "Indicate success",
"colorName": "Green 60",
"hslValue": "138-64-60"
},
{
"tokenName": "$success-02",
"role": "Indicate success",
"colorName": "Green 40",
"hslValue": "138-64-40"
},
{
"tokenName": "$success-03",
"role": "Indicate success",
"colorName": "Green 20",
"hslValue": "138-64-20"
},
{
"tokenName": "$warning-01",
"role": "Indicate warning",
"colorName": "Yellow 80",
"hslValue": "47-98-80"
},
{
"tokenName": "$warning-02",
"role": "Indicate warning",
"colorName": "Yellow 60",
"hslValue": "47-98-60"
},
{
"tokenName": "$warning-03",
"role": "Indicate warning",
"colorName": "Yellow 40",
"hslValue": "47-98-40"
},
{
"tokenName": "$error-01",
"role": "Indicate error",
"colorName": "Red 70",
"hslValue": "357-76-70"
},
{
"tokenName": "$error-02",
"role": "Indicate error",
"colorName": "Red 50",
"hslValue": "357-76-50"
},
{
"tokenName": "$error-03",
"role": "Indicate error",
"colorName": "Red 30",
"hslValue": "357-76-30"
},
{
"tokenName": "$hover-interactive-o1",
"role": "Hover state for $interactive-01",
"colorName": "Blue 60",
"hslValue": "220-70-40"
},
{
"tokenName": "$clicked-interactive-01",
"role": "Clicked state for $interactive-01",
"colorName": "Blue 40",
"hslValue": "220-70-40"
},
{
"tokenName": "$disabled-interactive-01",
"role": "Disabled state for $interactive-01",
"colorName": "Gray 70",
"hslValue": "0-0-70"
},
{
"tokenName": "$hover-interactive-o2",
"role": "Hover for $interactive-02",
"colorName": "Gray 30",
"hslValue": "0-0-30"
},
{
"tokenName": "$clicked-interactive-02",
"role": "Clicked state for $interactive-02",
"colorName": "Gray 10",
"hslValue": "0-0-10"
},
{
"tokenName": "$disabled-interactive-02",
"role": "Disabled state for $interactive-02",
"colorName": "Gray 70",
"hslValue": "0-0-70"
},
{
"tokenName": "$hover-interactive-03",
"role": "Background on hover state for $interactive-03",
"colorName": "Gray 80",
"hslValue": "0-0-80"
},
{
"tokenName": "$clicked-interactive-03",
"role": "Clicked state for $interactive-03",
"colorName": "Blue 50",
"hslValue": "220-70-50"
},
{
"tokenName": "$disabled-interactive-03",
"role": "Disabled state for $interactive-03",
"colorName": "Gray 70",
"hslValue": "0-0-70"
},
{
"tokenName": "$interactive-danger",
"role": "Danger interactive color (Active)",
"colorName": "Red 50",
"hslValue": "357-76-50"
},
{
"tokenName": "$hover-interactive-danger",
"role": "Hover state for $interactive-danger",
"colorName": "Gray 80",
"hslValue": "0-0-80"
},
{
"tokenName": "$clicked-interactive-danger",
"role": "Clicked state for $interactive-danger",
"colorName": "Red 50",
"hslValue": "357-76-50"
},
{
"tokenName": "$disabled-interactive-danger",
"role": "Disabled state for $interactive-danger",
"colorName": "Gray 70",
"hslValue": "0-0-70"
},
{
"tokenName": "$interactive-focus",
"role": "Focus border / Focus underline",
"colorName": "Blue 50",
"hslValue": "220-70-50"
}
]
export default App;
|
var express = require('express');
var router = express.Router();
var feedmodel = require('../model/feeds');
var commonpage = require('../views/common/template.marko');
var pages = {
"local": require('../views/local/template.marko'),
"international": require('../views/world/template.marko'),
"lifestyle": require('../views/lifestyle/template.marko'),
"technology": require('../views/technology/template.marko'),
"science": require('../views/science/template.marko'),
"entertainment": require('../views/entertainment/template.marko'),
"sports":require('../views/sports/template.marko'),
}
router.get('/:feedkey', function (req, res, next) {
var feedkey = req.params.feedkey;
feedkey = feedkey == "world" ? "international" : feedkey;
console.log("feedkey: "+feedkey)
var _page = pages[feedkey];
console.log(feedkey)
feedmodel.getFeed(feedkey, function (err, success) {
if (err) {
} else {
console.log("feedkey: "+feedkey,success.length)
res.marko(_page,{feed:success})
//res.json(success)
}
})
})
module.exports = router;
|
/****************** firebase references ******************/
var dbRef = firebase.database().ref('user');
var dbCounterRef = firebase.database().ref('counter');
var storageRef = firebase.storage().ref();
/****************** start of signUp Function ******************/
function signUp(){
var signup_username = document.getElementById('signup-username');
var signup_email = document.getElementById('signup-email');
var signup_password = document.getElementById('signup-password');
var signup_rpassword = document.getElementById('signup-rpassword');
if(signup_username.value == "" || signup_email.value == "" || signup_password.value == "" || signup_rpassword.value == "" ){
swal("Warning", "Please fill the form properly!", "warning");
}
else{
if(signup_password.value != signup_rpassword.value){
swal("Warning", "Password and repeat password doesn't match!", "warning");
}
else{
var auth = firebase.auth().createUserWithEmailAndPassword(signup_email.value, signup_password.value);
auth.then(function(){
swal("Congratulations", "You've created your account successfully!", "success").then(function(){
window.location = "login.html";
});
}).catch(function(error){
swal("Error",error.message, "error");
});
}
}
} // end of signUp function
/****************** start of login Function ******************/
function loginAccount(){
var login_email = document.getElementById('login-email');
var login_password = document.getElementById('login-password');
if(login_email.value == "" || login_password.value == ""){
swal("Warning", "Please enter the fields properly.", "warning");
}
else{
var auth = firebase.auth().signInWithEmailAndPassword(login_email.value, login_password.value);
auth.then(function(){
window.location = "dashboard.html";
}).catch(function(error){
swal("Error",error.message, "error");
});
}
} // end of login function
/****************** Password Reset Function ******************/
function resetPassword(){
var email = document.getElementById('login-email');
if(email.value!=""){
swal({
title: "Reset Password!",
text: "Password reset link will be sent to your email address. if the typed address is your correct email address, click OK. ",
icon: "warning",
buttons: true,
})
.then((willSend) => {
if (willSend) {
var sent = firebase.auth().sendPasswordResetEmail(email.value);
sent.then(function(){
swal("Email Sent","Password reset link has been sent to your email address. Kindly check your email account.", {
icon: "success",
});
}).catch(function(error){
swal("Error", error.code + ": "+ error.message,"error");
});
}
});
} // checking for empty email field.
else{
swal("Error","Please enter your email address to get the password reset link.","error");
}
}
/****************** start of logout Function ******************/
function logout(){
var auth = firebase.auth().signOut();
auth.then(function(){
window.location = "login.html";
}).catch(function(error){
swal("Error", error.message, "error");
});
} //End of Logout Function
/****************** authentication checker ******************/
function authenticationChecker(){
firebase.auth().onAuthStateChanged(function(user){
if(user){
console.log("You are Logged In.");
}
else{
swal("Error", "Please Login to your account to access this page","error").then(function(){
window.location = "login.html";
});
}
});
} //End of authentication checker
/****************** Dashboard buttons functionality ******************/
function dashboard(){
var add_btn_dashboard = document.getElementById('add');
var edit_btn_dashboard = document.getElementById('edit');
var delete_btn_dashboard = document.getElementById('delete');
var search_id_btn_dashboard = document.getElementById('byid');
var export_btn_dashboard = document.getElementById('pdf');
var print_btn_dashboard = document.getElementById('print_record');
add_btn_dashboard.onclick = function(){
window.location = "add.html";
}
edit_btn_dashboard.onclick = function(){
window.location = "edit.html";
}
delete_btn_dashboard.onclick = function(){
window.location = "delete.html";
}
search_id_btn_dashboard.onclick = function(){
window.location = "searchById.html";
}
export_btn_dashboard.onclick = function(){
window.location = "export.html";
}
print_btn_dashboard.onclick = function(){
window.location = "print.html";
}
} //End of Dashboard Functionality
/****************** Dashboard Date and Time function ******************/
function dateTime(){
//getting date and time using Date's methods
var today = new Date();
var day =today.getDay();
var date = today.getDate();
//setting date to display two digits
date = date<10 ? "0"+date : date;
var month = today.getMonth();
var year = today.getFullYear();
var hours = today.getHours();
var minutes = today.getMinutes();
//setting minutes to display two digits
minutes = minutes<10 ? "0"+minutes : minutes;
var seconds = today.getSeconds();
//setting seconds to display two digits
seconds = seconds<10 ? "0"+seconds : seconds;
//setting hours to display 12 instead of 0
hours = hours == 00 ? 12 : hours;
//getting AM or PM
var AmPm = hours >= 12 ? "PM" : "AM";
//converting 24 hours time format into 12 hours time format
hours = hours>12 ? hours - 12 : hours;
//setting hours to display two digits
hours = hours<10 ? "0"+hours : hours;
var data;
return data = [day,date, month, year, hours, minutes, seconds, AmPm ];
}
function dashboardDateTime(element){
var el = document.getElementById(element); //element for the date and time
setInterval(function(){
var data = dateTime();
//array for days
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday", "Saturday"];
var months = ["Jan","Feb", "Mar","Apr","May","June","Jul","Aug","Sep","Oct","Nov","Dec"];
el.innerHTML = `
<span><b>${days[data[0]]}</b>, ${months[data[2]]},${data[1]} ${data[3]} ${data[4]}:${data[5]}:${data[6]} ${data[7]}</span>
`;
},1000);
}
/****************** Capitalize Each Word -- Helper Function ******************/
function capitalize(name){
var fullName = name.split(" ");
var capitalizeName="";
for(key in fullName){
capitalizeName += fullName[key].charAt(0).toUpperCase()+fullName[key].slice(1).toLowerCase()+" ";
}
return capitalizeName;
}
/****************** Inserting Add Form Data to the Firebase Database ******************/
//reading current counter value
var counter_value;
function counterValue(){
add_form_id = document.getElementById('add-id');
dbCounterRef.on('value',function(snapshot){
var snap = snapshot.val();
counter_value = snap.counter_val;
add_form_id.value = counter_value;
});
}
function addData(){ //addData() Function
var add_form_id = document.getElementById('add-id');
var add_form_name = document.getElementById('add-name');
var add_form_age = document.getElementById('add-age');
var add_form_date = document.getElementById('add-date');
var add_form_disease = document.getElementById('add-disease');
var add_form_medications = document.getElementById('add-medications');
var add_form_weight = document.getElementById('add-weight');
var add_form_growth = document.getElementById('add-growth');
var add_form_blood = document.getElementById('add-blood');
var add_form_blood_pressure = document.getElementById('add-blood-pressure');
var add_form_pulse_rate = document.getElementById('add-pulse-rate');
var add_form_sugar = document.getElementById('add-sugar');
var add_form_doctor = document.getElementById('add-doctor');
var add_form_photo = document.getElementById('add-photo');
if(add_form_id.value !="" && add_form_name.value !="" && add_form_age.value !="" && add_form_date.value!="" && add_form_disease.value !="" && add_form_medications.value!="" && add_form_weight.value !="" && add_form_growth.value !="" && add_form_blood.value !="" && add_form_blood_pressure.value !="" && add_form_pulse_rate.value !="" && add_form_sugar.value !="" && add_form_doctor.value !="" ) {
if(add_form_photo.files[0]){
var add_form_data = { //Patient data object
p_id: add_form_id.value,
p_name: capitalize(add_form_name.value),
p_age: add_form_age.value,
p_date: add_form_date.value,
p_disease: capitalize(add_form_disease.value),
p_medications: capitalize(add_form_medications.value),
p_weight: add_form_weight.value,
p_growth: add_form_growth.value,
p_blood: add_form_blood.value,
p_blood_pressure: add_form_blood_pressure.value,
p_pulse_rate: add_form_pulse_rate.value,
p_sugar: add_form_sugar.value,
p_doctor: capitalize(add_form_doctor.value)
}
//Checking Uploading Status
var taskUpload = storageRef.child(counter_value.toString()).put(add_form_photo.files[0]);
taskUpload.on("state_changed",function(snapshot){
var status = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
swal(`upload Status: ${Math.round(status)}%`,"Please Wait. Do not Close this notification otherwise your upload will be cancelled.",'warning').then(function(value){
if((value==null || value==true) && status!=100){
taskUpload.cancel();
}
});
},function(){
swal('Error','Data Uploading Failed due to action performed by the User.','error');
},function(){
dbRef.child(counter_value).set(add_form_data);
counter_value++;
dbCounterRef.update({
counter_val: counter_value
});
//Success Message
alertify.notify('Add Successful', 'custom', 2);
});
//Clear Form Data
clearData();
//Reading Counter Value
counterValue();
//setting focus to Product name Field
add_form_name.focus();
} //end of condition for Photo Validation
else{
swal("OOPS", "Please Select Patient Photo.", "warning");
}
} // End of condition for validation
else{
swal("OOPS!","Please enter the form properly.","warning");
}
} //End of Add Data Function
/****************** Add Form Photo Preview after selecting Photo ******************/
function previewImage(){
var add_form_photo = document.getElementById('add-photo');
var dataURL;
if(add_form_photo.value!=""){
var reader = new FileReader();
reader.onload = function(){
dataURL = reader.result;
swal("Preview Photo","",{
className:"sweet-alert-img",
icon: dataURL
});
}
reader.readAsDataURL(add_form_photo.files[0]);
}
else{
swal("OOPs","Please select Photo.","warning");
}
}
/****************** Clear Form Data ******************/
function clearData(){
var add_form_name = document.getElementById('add-name');
var add_form_age = document.getElementById('add-age');
var add_form_date = document.getElementById('add-date');
var add_form_disease = document.getElementById('add-disease');
var add_form_medications = document.getElementById('add-medications');
var add_form_weight = document.getElementById('add-weight');
var add_form_growth = document.getElementById('add-growth');
var add_form_blood = document.getElementById('add-blood');
var add_form_blood_pressure = document.getElementById('add-blood-pressure');
var add_form_pulse_rate = document.getElementById('add-pulse-rate');
var add_form_sugar = document.getElementById('add-sugar');
var add_form_doctor = document.getElementById('add-doctor');
var add_form_photo = document.getElementById('add-photo');
add_form_name.value = "";
add_form_age.value = "";
add_form_date.value = "";
add_form_disease.value = "";
add_form_medications.value = "";
add_form_weight.value = "";
add_form_growth.value = "";
add_form_blood.value = "Select";
add_form_blood_pressure.value = "";
add_form_pulse_rate.value = "";
add_form_sugar.value = "";
add_form_doctor.value = "";
add_form_photo.value = "";
} //End of clear Form data function
/****************** Fetching Data from the Firebase Database and displaying them into fields******************/
var urlForUpdate;
function loadData(){
var edit_form_id = document.getElementById('edit-id');
var edit_form_name = document.getElementById('edit-name');
var edit_form_age = document.getElementById('edit-age');
var edit_form_date = document.getElementById('edit-date');
var edit_form_disease = document.getElementById('edit-disease');
var edit_form_medications = document.getElementById('edit-medications');
var edit_form_weight = document.getElementById('edit-weight');
var edit_form_growth = document.getElementById('edit-growth');
var edit_form_blood = document.getElementById('edit-blood');
var edit_form_blood_pressure = document.getElementById('edit-blood-pressure');
var edit_form_pulse_rate = document.getElementById('edit-pulse-rate');
var edit_form_sugar = document.getElementById('edit-sugar');
var edit_form_doctor = document.getElementById('edit-doctor');
var edit_form_photo = document.getElementById('edit-photo');
var edit_preview_btn = document.getElementById('edit-preview');
if(edit_form_id.value!=""){ //Checking for Patient ID
var recordFound = false;
//fetching Patient IDs from database
dbRef.on("value",function(snapshot){
var snap = snapshot.val();
for(user in snap){
if(snap[user].p_id == edit_form_id.value){
recordFound = true;
}
}
if(recordFound){ //Checking for records
dbRef.child(edit_form_id.value).on('value',function(snapshot){
var snap = snapshot.val();
edit_form_name.value = snap.p_name;
edit_form_age.value = snap.p_age;
edit_form_date.value = snap.p_date;
edit_form_disease.value = snap.p_disease;
edit_form_medications.value = snap.p_medications;
edit_form_weight.value = snap.p_weight;
edit_form_growth.value = snap.p_growth;
edit_form_blood.value = snap.p_blood;
edit_form_blood_pressure.value = snap.p_blood_pressure;
edit_form_pulse_rate.value = snap.p_pulse_rate;
edit_form_sugar.value = snap.p_sugar;
edit_form_doctor.value = snap.p_doctor;
});
var id = edit_form_id.value;
function edit_previewImage(){
var url = storageRef.child(id).getDownloadURL();
url.then(function(url){
if(edit_form_photo.files[0]){
var reader = new FileReader();
reader.onload = function(){
dataURL = reader.result;
swal("Preview Photo","",{
className:"sweet-alert-img",
icon: dataURL
});
}
reader.readAsDataURL(edit_form_photo.files[0]);
}
else{
swal("Preview Photo","",{
className:"sweet-alert-img",
icon:url
});
}
var urlForUpdate = url;
});
}
edit_preview_btn.disabled = false;
edit_preview_btn.onclick = edit_previewImage;
} //End of Checking records
else{
editClearData();
swal("OOPs", "Record Not Found! Please enter a valid Patient ID.","error");
}
});
} //End of checking for patient ID
else{
editClearData();
swal("OOPS","Please enter a valid Patient ID.","error");
}
} //End of Load Data Function
/****************** Edit Clear Form Data ******************/
function editClearData(){
var edit_form_id = document.getElementById('edit-id');
var edit_form_name = document.getElementById('edit-name');
var edit_form_age = document.getElementById('edit-age');
var edit_form_date = document.getElementById('edit-date');
var edit_form_disease = document.getElementById('edit-disease');
var edit_form_medications = document.getElementById('edit-medications');
var edit_form_weight = document.getElementById('edit-weight');
var edit_form_growth = document.getElementById('edit-growth');
var edit_form_blood = document.getElementById('edit-blood');
var edit_form_blood_pressure = document.getElementById('edit-blood-pressure');
var edit_form_pulse_rate = document.getElementById('edit-pulse-rate');
var edit_form_sugar = document.getElementById('edit-sugar');
var edit_form_doctor = document.getElementById('edit-doctor');
var edit_form_photo = document.getElementById('edit-photo');
var edit_preview_btn = document.getElementById('edit-preview');
edit_form_id.value = "";
edit_form_name.value = "";
edit_form_age.value = "";
edit_form_date.value = "";
edit_form_disease.value = "";
edit_form_medications.value = "";
edit_form_weight.value = "";
edit_form_growth.value = "";
edit_form_blood.value = "Select";
edit_form_blood_pressure.value = "";
edit_form_pulse_rate.value = "";
edit_form_sugar.value = "";
edit_form_doctor.value = "";
edit_form_photo.value = "";
edit_preview_btn.disabled = true;
} //End of Edit clear Form data function
/****************** Update Edit Form Data ******************/
function updateData(){
var edit_form_id = document.getElementById('edit-id');
var edit_form_name = document.getElementById('edit-name');
var edit_form_age = document.getElementById('edit-age');
var edit_form_date = document.getElementById('edit-date');
var edit_form_disease = document.getElementById('edit-disease');
var edit_form_medications = document.getElementById('edit-medications');
var edit_form_weight = document.getElementById('edit-weight');
var edit_form_growth = document.getElementById('edit-growth');
var edit_form_blood = document.getElementById('edit-blood');
var edit_form_blood_pressure = document.getElementById('edit-blood-pressure');
var edit_form_pulse_rate = document.getElementById('edit-pulse-rate');
var edit_form_sugar = document.getElementById('edit-sugar');
var edit_form_doctor = document.getElementById('edit-doctor');
var edit_form_photo = document.getElementById('edit-photo');
var edit_preview_btn = document.getElementById('edit-preview');
if(edit_form_id.value !="" && edit_form_name.value !="" && edit_form_age.value !="" && edit_form_date.value!="" && edit_form_disease.value !="" && edit_form_medications.value!="" && edit_form_weight.value !="" && edit_form_growth.value !="" && edit_form_blood.value !="" && edit_form_blood_pressure.value !="" && edit_form_pulse_rate.value !="" && edit_form_sugar.value !="" && edit_form_doctor.value !="" ) {
if(edit_form_photo.files[0]|| urlForUpdate!= ""){
//Updated data Object
var updatedData = {
p_name: capitalize(edit_form_name.value),
p_age: edit_form_age.value,
p_date: edit_form_date.value,
p_disease: capitalize(edit_form_disease.value),
p_medications: capitalize(edit_form_medications.value),
p_weight: edit_form_weight.value,
p_growth: edit_form_growth.value,
p_blood: edit_form_blood.value,
p_blood_pressure: edit_form_blood_pressure.value,
p_pulse_rate: edit_form_pulse_rate.value,
p_sugar: edit_form_sugar.value,
p_doctor: capitalize(edit_form_doctor.value)
};
if(edit_form_photo.files[0]){
var taskUpload = storageRef.child(edit_form_id.value).put(edit_form_photo.files[0]);
taskUpload.on('state_changed',function(snapshot){
var status = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
swal(`Upload Status: ${Math.round(status)}%`,"Please Wait. Do not Close this notification otherwise your upload will be cancelled.",'warning').then(function(value){
if((value==true || value==null) && status!=100 ){
taskUpload.cancel();
}
});
},function(){
swal('Error','Data Uploading Failed due to action performed by the User.','error');
},function(){
dbRef.child(edit_form_id.value).update(updatedData);
//Success Message
alertify.notify('Update Successful', 'custom', 2);
editClearData();
});
}
else{
dbRef.child(edit_form_id.value).update(updatedData);
//Success Message
alertify.notify('Update Successful', 'custom', 2);
editClearData();
}
} //Checking for selected Photo
else{
swal('Error',"Please select Photo.","error");
}
} //Checking for fields
else{
swal("Error","Please enter the fields properly.","error");
}
} // End of Update Data
/****************** Deleting Record-------Search By Patient ID ******************/
var refForImageAndDelete;
function searchById(){
var p_id = document.getElementById('delete-patient-id');
var data_table = document.getElementById('data-table');
var button_part = document.getElementById('button-part');
if(p_id.value!=""){
dbRef.child(p_id.value).once("value",function(snapshot){
var snap = snapshot.val();
if(snap){
data_table.innerHTML = `
<table class="table table-bordered table-striped table-responsive animated fadeIn">
<tr>
<td colspan=4 align=center><h4>Patient Record - ID # ${snap.p_id}</h4> </td>
</tr>
<tr>
<td><b>Patient Name</b></td>
<td>${snap.p_name}</td>
</tr>
<tr>
<td><b>Patient Age</b></td>
<td>${snap.p_age}</td>
</tr>
<tr>
<td><b>Appointment Date</b></td>
<td>${snap.p_date}</td>
</tr>
<tr>
<td><b>Disease<b></td>
<td>${snap.p_disease}</td>
</tr>
<tr>
<td><b>Medications<b></td>
<td>${snap.p_medications}</td>
</tr>
<tr>
<td><b>Weight (in KG)<b></td>
<td>${snap.p_weight}</td>
</tr>
<tr>
<td><b>Growth<b></td>
<td>${snap.p_growth}</td>
</tr>
<tr>
<td><b>Blood Group<b></td>
<td>${snap.p_blood}</td>
</tr>
<tr>
<td><b>Blood Pressure<b></td>
<td>${snap.p_blood_pressure}</td>
</tr>
<tr>
<td><b>Pulse Rate<b></td>
<td>${snap.p_pulse_rate}</td>
</tr>
<tr>
<td><b>Sugar<b></td>
<td>${snap.p_sugar}</td>
</tr>
<tr>
<td><b>Doctor Assigned<b></td>
<td>${snap.p_doctor}</td>
</tr>
</table>
`;
button_part.innerHTML = `
<div class='col-sm-6' style='margin-bottom:10px; padding:3px;' >
<button type='button' class='btn btn-danger btn-block' onclick='deleteRecord()'/><span class='glyphicon glyphicon-trash'></span> Delete Record</button>
</div>
<div class='col-sm-6' style=' padding:3px;'>
<button type=button class='btn btn-success btn-block' onclick='viewPhoto()' /><span class='glyphicon glyphicon-picture'></span> View Patient Photo</button>
</div>
`;
refForImageAndDelete = p_id.value;
}
else{
swal("OOPs","Record Not Found! Please enter a valid Patient ID.","error");
}
});
}
else{
swal("OOPs","Please enter a Patient ID.", 'error');
}
}
//View Photo Function
function viewPhoto(){
url = storageRef.child(refForImageAndDelete).getDownloadURL();
url.then(function(url){
swal("Preview Photo","",{
className:'sweet-alert-img',
icon:url
});
});
}
//Delete Record Function
function deleteRecord(){
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this Record!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
var p_id = document.getElementById('delete-patient-id');
var table_data = document.getElementById('data-table');
var button_part = document.getElementById('button-part');
p_id.value="";
table_data.innerHTML = "";
button_part.innerHTML = "";
p_id.focus();
dbRef.child(refForImageAndDelete).remove();
storageRef.child(refForImageAndDelete).delete();
alertify.notify("Delete Successful","custom",2)
}
});
}
/******************Search Interface Programming ******************/
function searchCriteria(){
var search = document.getElementById('search');
var search_criteria = document.getElementById('search-criteria');
var data = document.getElementById('data');
if(search.selectedIndex == 0){
data.innerHTML = "";
search_criteria.innerHTML = "";
}
if(search.selectedIndex == 1){
data.innerHTML = "";
search_criteria.innerHTML = `<div class='input-group'>
<input type='number' class='form-control' id='search-patient-id' placeholder='Please Enter Patient ID'/>
<span class='input-group-btn animated fadeIn'><button type='button' class='btn btn-default' onclick='searchRecordById()'><span class='glyphicon glyphicon-search' aria-hidden='true'></span></button></span>
</div>
`;
}
else if(search.selectedIndex == 2){
data.innerHTML = "";
search_criteria.innerHTML = `<div class='input-group'>
<input type='search' class='form-control' id='search-patient-name' placeholder='Please Enter Patient Name'/>
<span class='input-group-btn animated fadeIn'><button type='button' class='btn btn-default' onclick='searchByNameAndDate("search-patient-name")'><span class='glyphicon glyphicon-search' aria-hidden='true'></span></button></span>
</div>
`;
}
if(search.selectedIndex == 3){
data.innerHTML = "";
search_criteria.innerHTML = `<div class="row">
<div class="col-sm-12" style='margin-top:5px'>
<div class='input-group'>
<input type='date' class='form-control' id='search-date'/>
<span class='input-group-btn animated fadeIn'><button type='button' class='btn btn-default' onclick='searchByNameAndDate("search-date")'><span class='glyphicon glyphicon-search' aria-hidden='true'></span></button></span>
</div>
</div>
</div>
`;
}
}
/******************Search Record By Patient ID ******************/
function searchRecordById(){
var patient_id = document.getElementById('search-patient-id');
var data = document.getElementById('data');
if(patient_id.value !=""){
dbRef.child(patient_id.value).on('value',function(snapshot){
var snap = snapshot.val();
if(snap){
data.innerHTML = `<table class="table table-bordered table-striped table-responsive animated fadeIn" id="data-table">
<tr>
<td class='text-center' colspan='2'><h4>Patient History</h4></td>
</tr>
<tr>
<td colspan='2'><center><img src='icons/patient.jpg' alt='Patient Preview' id='patient-image' class='img-responsive img-thumbnail' height='180' width='150'/></center></td>
</tr>
<tr>
<td><b>Patient ID</b></td>
<td>${snap.p_id}</td>
</tr>
<tr>
<td><b>Patient Name</b></td>
<td>${snap.p_name}</td>
</tr>
<tr>
<td><b>Patient's Age</b></td>
<td>${snap.p_age}</td>
</tr>
<tr>
<td><b>Appointment Date</b></td>
<td>${snap.p_date}</td>
</tr>
<tr>
<td><b>Disease</b></td>
<td>${snap.p_disease}</td>
</tr>
<tr>
<td><b>Medications</b></td>
<td>${snap.p_medications}</td>
</tr>
<tr>
<td><b>Weight (in KG)</b></td>
<td>${snap.p_weight}</td>
</tr>
<tr>
<td><b>Growth</b></td>
<td>${snap.p_growth}</td>
</tr>
<tr>
<td><b>Blood Group</b></td>
<td>${snap.p_blood}</td>
</tr>
<tr>
<td><b>Blood Pressure</b></td>
<td>${snap.p_blood_pressure}</td>
</tr>
<tr>
<td><b>Pulse Rate</b></td>
<td>${snap.p_pulse_rate}</td>
</tr>
<tr>
<td><b>Sugar</b></td>
<td>${snap.p_sugar}</td>
</tr>
<tr>
<td><b>Doctor Assigned</b></td>
<td>${snap.p_doctor}</td>
</tr>
</table>
`;
var url = storageRef.child(patient_id.value).getDownloadURL();
url.then(function(url){
var patient_image = document.getElementById('patient-image');
patient_image.src = url;
});
}
else{
swal("Error","Record Not Found! Please enter a valid Patient ID.","error");
}
});
}
else{
swal("Error","Please enter a valid Patient ID.","error");
}
}
/******************Search Record By Patient Name And Appointment Date ******************/
function searchByNameAndDate(el){
var data = document.getElementById('data');
var selectedElement = document.getElementById(el);
if(selectedElement.value != ""){ //checking for empty field
data.innerHTML = "";
recordFound = false;
dbRef.on("value",function(snapshot){
var snappy = snapshot.val();
for(key in snappy){
if( (snappy[key].p_name.toLowerCase().indexOf(selectedElement.value) != -1) || (snappy[key].p_date.toLowerCase().indexOf(selectedElement.value) != -1) ){
recordFound = true;
break;
}
}
if(recordFound){
dbRef.on("child_added",function(snapshot){
var snap = snapshot.val();
if((snap.p_name.toLowerCase().indexOf(selectedElement.value.toLowerCase()) != -1)||(snap.p_date.toLowerCase().indexOf(selectedElement.value.toLowerCase()) != -1)){ //checking for name in the database
data.innerHTML +=`
<div class="panel animated fadeIn">
<div class="panel-heading" onclick=viewPatientPhoto(${snap.p_id},${snap.p_id}) style="background:#1bbc9b;">
<a href="#p${snap.p_id}" data-toggle="collapse" style="color:white !important;">${snap.p_name} - ${snap.p_id}</a>
</div>
<div id = p${snap.p_id} class="collapse">
<div class="panel-body">
<table class='table table-bordered table-striped table-responsive'>
<tr>
<td colspan="2" class='text-center'><h3>Patient Record - ${snap.p_id}</h3></td>
</tr>
<tr>
<td class="text-center" colspan="2"><img src="icons/patient.jpg" alt=${snap.p_id} id =${snap.p_id} height="150" width="130" class="img-responsive img-thumbnail" /></td>
</tr>
<tr>
<td><b>Patient Name</b></td>
<td>${snap.p_name}</td>
</tr>
<tr>
<td><b>Patient Age</b></td>
<td>${snap.p_age}</b></td>
</tr>
<tr>
<td><b>Appointment Date</b></td>
<td>${snap.p_date}</td>
</tr>
<tr>
<td><b>Disease</b></td>
<td>${snap.p_disease}</td>
</tr>
<tr>
<td><b>Medications</b></td>
<td>${snap.p_medications}</td>
</tr>
<tr>
<td><b>Weight (in KG)</b></td>
<td>${snap.p_weight}</td>
</tr>
<tr>
<td><b>Growth</b></td>
<td>${snap.p_growth}</td>
</tr>
<tr>
<td><b>Blood Group</b></td>
<td>${snap.p_blood}</td>
</tr>
<tr>
<td><b>Blood Pressure<b></td>
<td>${snap.p_blood_pressure}</td>
</tr>
<tr>
<td><b>Pulse Rate</b></td>
<td>${snap.p_pulse_rate}</td>
</tr>
<tr>
<td><b>Sugar</b></td>
<td>${snap.p_sugar}</td>
</tr>
<tr>
<td><b>Doctor Assigned</b></td>
<td>${snap.p_doctor}</td>
</tr>
</table>
</div>
</div>
</div>
`;
}//end of checking for name in the database
} // on child_added function
); // end of 'dbRef.on' method
}
else{
swal("Error", "Record Not Found.", "error");
}
});
} //end of checking for empty field - if statement
else{
swal("Error","Please enter a valid Patient Name","error");
} //end of checking for empty field - else statement
} //end of searchByName() function
function viewPatientPhoto(img_el, p_id){
var img = document.getElementById(img_el);
var imgRef = storageRef.child(p_id.toString()).getDownloadURL();
imgRef.then(function(url){
img.src = url;
});
}
/******************Export As PDF or JPEG ******************/
var refForPdf;
function searchRecordForExport(){
var patient_id = document.getElementById('export-patient-id');
var data_table = document.getElementById('export-data-table');
var button_part = document.getElementById('export-button-part');
if(patient_id.value!=""){
dbRef.child(patient_id.value).on("value",function(snapshot){
var snap = snapshot.val();
if(snap){
data_table.innerHTML = `<table class="table table-bordered table-striped table-responsive animated fadeIn">
<tr>
<td colspan='4' align='center'><h4>Patient Record - ID # ${snap.p_id}</h4></td>
</tr>
<tr>
<td><b>Patient Name</b></td>
<td>${snap.p_name}</td>
</tr>
<tr>
<td><b>Patient's Age</b></td>
<td>${snap.p_age}</td>
</tr>
<tr>
<td><b>Appointment Date</b></td>
<td>${snap.p_date}</td>
</tr>
<tr>
<td><b>Disease</b></td>
<td>${snap.p_disease}</td>
</tr>
<tr>
<td><b>Medications</b></td>
<td>${snap.p_medications}</td>
</tr>
<tr>
<td><b>Weight (in KG)</b></td>
<td>${snap.p_weight}</td>
</tr>
<tr>
<td><b>Growth</b></td>
<td>${snap.p_growth}</td>
</tr>
<tr>
<td><b>Blood Group</b></td>
<td>${snap.p_blood}</td>
</tr>
<tr>
<td><b>Blood Pressure</b></td>
<td>${snap.p_blood_pressure}</td>
</tr>
<td><b>Pulse Rate</b></td>
<td>${snap.p_pulse_rate}</td>
</tr>
<tr>
<td><b>Sugar</b></td>
<td>${snap.p_sugar}</td>
</tr>
<td><b>Doctor Assigned</b></td>
<td>${snap.p_doctor}</td>
</tr>
</table>
`;
button_part.innerHTML = `
<div class='row animated fadeIn'>
<div class='cotainer-fluid'>
<div class="col-sm-6">
<button type='button' class='btn btn-danger btn-block' onclick='exportPdf()'style='margin-top:10px;'> <span class='glyphicon glyphicon-save-file'></span> Export as PDF</button>
</div>
<div class="col-sm-6">
<a onclick='getPng()' id = 'export-png-btn' class='btn btn-success btn-block' style='margin-top:10px;'> <span class='glyphicon glyphicon-export'></span> Export as PNG</a>
</div>
</div>
</div>
`;
refForPdf = snap.p_id;
}
else{
swal('Error','Record Not Found! Please enter a valid Patient ID.','error');
}
});
}
else{
swal('Error',"Please enter a valid Patient ID.","error")
}
}
//exportPdf function to generate Pdf
function exportPdf(){
//calling function dateTime to get the current date and time
var data = dateTime();
//arrays for days
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday", "Saturday"];
//arrays for month
var months = ["Jan","Feb", "Mar","Apr","May","June","Jul","Aug","Sep","Oct","Nov","Dec"];
//fetching patient's records from the database and writing on the PDF using jsPDF library
dbRef.child(refForPdf).on("value",function(snapshot){
var snap = snapshot.val();
var doc = new jsPDF();
doc.setFontSize(26);
doc.setFont("times","roman");
doc.text(75, 20, 'Patient Tracker');
doc.setFontSize(16);
doc.text(60, 28, "Maintain patients' record on a single click");
doc.text(65, 40, `${days[data[0]]}, ${months[data[2]]} ${data[1]} ${data[3]} ${data[4]}:${data[5]}:${data[6]} ${data[7]}`);
doc.setFont("courier","roman");
doc.text(41, 55, `Patient ID`);
doc.text(120, 55, `${snap.p_id}`);
doc.text(41, 68, `Patient Name`);
doc.text(120, 68, `${snap.p_name}`);
doc.text(41, 81, `Patient Age`);
doc.text(120, 81, `${snap.p_age}`);
doc.text(41, 94, `Appointment Date`);
doc.text(120, 94, `${snap.p_date}`);
doc.text(41, 107, `Disease`);
doc.text(120, 107, `${snap.p_disease}`);
doc.text(41, 120, `Medications`);
doc.text(120, 120, `${snap.p_medications}`);
doc.text(41, 133, `Weight (in KG)`);
doc.text(120, 133, `${snap.p_weight}`);
doc.text(41, 146, `Growth`);
doc.text(120, 146, `${snap.p_growth}`);
doc.text(41, 159, `Blood Group`);
doc.text(120, 159, `${snap.p_blood}`);
doc.text(41, 172, `Blood Pressure`);
doc.text(120, 172, `${snap.p_blood_pressure}`);
doc.text(41, 185, `Pulse Rate`);
doc.text(120, 185,`${snap.p_pulse_rate}`);
doc.text(41, 198, `Sugar`);
doc.text(120, 198,`${snap.p_sugar}`);
doc.text(41, 211, `Doctor Assigned`);
doc.text(120, 211, `${snap.p_doctor}`);
doc.text(45, 231, "This is a system generated report without any error.");
doc.save(refForPdf);
});
}
function getPng(){
var val = 0;
var export_data_table = document.getElementById('export-data-table');
var export_png_btn = document.getElementById('export-png-btn');
html2canvas(export_data_table,{
onrendered:function(canvas){
export_png_btn.setAttribute('download',refForPdf);
imgUrl = canvas.toDataURL('image/png');
export_png_btn.setAttribute('href',imgUrl);
}
});
}
/******************Printing Patient's Record ******************/
// Fetching records from database for Printing
var refForPrinting;
function searchRecordForPrinting(){
var patient_id = document.getElementById('print-patient-id');
var data_table = document.getElementById('data-table');
var button_part = document.getElementById('button-part');
if(patient_id.value!=""){
dbRef.child(patient_id.value).on("value",function(snapshot){
var snap = snapshot.val();
if(snap){
data_table.innerHTML = `<table class="table table-bordered table-striped table-responsive animated fadeIn">
<tr>
<td colspan='4' align='center'><h4>Patient Record - ID # ${snap.p_id}</h4></td>
</tr>
<tr>
<td><b>Patient Name</b></td>
<td>${snap.p_name}</td>
</tr>
<tr>
<td><b>Patient's Age</b></td>
<td>${snap.p_age}</td>
</tr>
<tr>
<td><b>Appointment Date</b></td>
<td>${snap.p_date}</td>
</tr>
<tr>
<td><b>Disease</b></td>
<td>${snap.p_disease}</td>
</tr>
<tr>
<td><b>Medications</b></td>
<td>${snap.p_medications}</td>
</tr>
<tr>
<td><b>Weight (in KG)</b></td>
<td>${snap.p_weight}</td>
</tr>
<tr>
<td><b>Growth</b></td>
<td>${snap.p_growth}</td>
</tr>
<tr>
<td><b>Blood Group</b></td>
<td>${snap.p_blood}</td>
</tr>
<tr>
<td><b>Blood Pressure</b></td>
<td>${snap.p_blood_pressure}</td>
</tr>
<td><b>Pulse Rate</b></td>
<td>${snap.p_pulse_rate}</td>
</tr>
<tr>
<td><b>Sugar</b></td>
<td>${snap.p_sugar}</td>
</tr>
<td><b>Doctor Assigned</b></td>
<td>${snap.p_doctor}</td>
</tr>
</table>
`;
button_part.innerHTML = `
<button type='button' class='btn btn-success btn-block animated fadeIn' onclick='printRecord()'> <span class='glyphicon glyphicon-print'></span> Print Patient's Record</button>
`;
refForPrinting = patient_id.value;
}
else{
swal('Error','Record Not Found! Please enter a valid Patient ID.','error');
}
});
}
else{
swal('Error',"Please enter a valid Patient ID.","error")
}
}
function printRecord(){
//storing the original layout of a webpage
var restorePage = document.body.innerHTML;
//fetching data from the database which is to be printed.
dbRef.child(refForPrinting).on("value",function(snapshot){
var snap = snapshot.val();
//layout of a report for printing
var html = `
<h2 style="text-align:center;" class="app-heading">Patient Tracker</h2>
<p class="printing-paragraph">Maintain Patients' Record on a single click</p>
<table border="1" class = "table-printing table table-bordered" style="width:700px;">
<tr>
<td colspan="2" align="center"><h3 class="printing-heading">Patient History</h3></td>
</tr>
<tr>
<th>Patient ID</th>
<td>${snap.p_id}</td>
</tr>
<tr>
<th>Patient Name</th>
<td> ${snap.p_name}</td>
</tr>
<tr>
<th>Patient's Age</th>
<td> ${snap.p_age}</td>
</tr>
<tr>
<th>Appointment Date</th>
<td> ${snap.p_date}</td>
</tr>
<tr>
<th>Disease</th>
<td> ${snap.p_disease}</td>
</tr>
<tr>
<th>Medications</th>
<td> ${snap.p_medications}</td>
</tr>
<tr>
<th>Weight (in KG)</th>
<td> ${snap.p_disease}</td>
</tr>
<tr>
<th>Growth</th>
<td> ${snap.p_growth}</td>
</tr>
<tr>
<th>Blood Group</th>
<td> ${snap.p_blood}</td>
</tr>
<tr>
<th>Blood Pressure</th>
<td> ${snap.p_blood_pressure}</td>
</tr>
<tr>
<th>Pulse Rate</th>
<td> ${snap.p_pulse_rate}</td>
</tr>
<tr>
<th>Sugar</th>
<td> ${snap.p_sugar}</td>
</tr>
<tr>
<th>Doctor Assigned</th>
<td> ${snap.p_doctor}</td>
</tr>
</table>
<p class='printing-paragraph'>This is a system generated report of a patient without any error</p>`
;
//temporarily rendering the report on the real page.
document.body.innerHTML = html;
window.print();
//page will be restored to its original state after printing
document.body.innerHTML = restorePage;
});
}
function aboutUs(){
swal("Patient Tracker v1.0","This App will help the doctors or staff members to perform all the necessary tasks related to patient. You can easily maintain patients' records. This App is developed by S.M.Rizwan.\n\n Contact: +92331-2278339\n E-mail:smrizwan54@gmail.com",{
className:"sweet-alert-icon",
icon: "icons/patient_icon.png"
});
}
|
import styled, { css } from "styled-components";
import { device } from "../../device";
const buttonStyles = css`
@media ${device.mobileS} {
height: 50px;
line-height: 50px;
font-size: 15px;
padding: 0 10px;
text-transform: uppercase;
font-family: "Raleway", sans-serif;
font-weight: bolder;
border: none;
outline: none;
}
@media ${device.laptop} {
transition: all 0.3s ease;
cursor: pointer;
}
`;
const blackButtonStyles = css`
width: ${({ width }) => (width ? `${width}%` : "70%")};
/* min-width: 200px; */
color: white;
background-color: black;
&:hover {
background-color: rgba(142, 115, 41, 1);
}
`;
const whiteButtonStyles = css`
background-color: rgba(255, 255, 255, 0.8);
&:hover {
color: white;
background-color: black;
}
`;
export const CustomButtonContainer = styled.button`
${buttonStyles}
${({ blackButton }) => (blackButton ? blackButtonStyles : "")}
${({ whiteButton }) => (whiteButton ? whiteButtonStyles : "")}
`;
|
import {TableRow} from "./index"
import './Table.css'
export default function RataCompositionTable(props) {
let table = []
props.rows.forEach((row, index) => {
// if (row.stopping === true || showAll === true) {
// let arrivalData = "-"
// let departureData = "-"
// let style = {}
//
// if (row.arr) {
// if (row.arr.actTime) {
// style = {color: "#727171"}
// }
// arrivalData = timeCell(row.arr)
// }
// if (row.dep) {
// if (row.dep.actTime) {
// style = {color: "#727171"}
// }
// departureData = timeCell(row.dep)
// }
//
// table.push({style: style, line: [arrivalData,
// <span>{RataStations(row.stationShortCode)}<br/>{row.track ? <span>Raide: {row.track}</span> : null}</span>,
// departureData]})
// }
let location = index + 1
let type = row.type
let saleNumber = row.salesNumber
table.push({style: {}, line: [location, type, saleNumber]})
})
return (
<table className={"Table"}>
<TableRow
line={["Sijainti", "Tyyppi", "Vaununumero"]}
header={true}
/>
{table.map(item =>
<TableRow
lineStyle={item.style}
line={item.line}
/>
)}
</table>
)
}
|
import test from 'ava';
import * as my_test from '../../dist/ava/date-trans';
/**
*测试是不是闰年
*/
test("is_leapyear_pass_1", async (t) => {
t.is(my_test.is_leapyear(2000), true);
});
test("is_leapyear_pass_2", async (t) => {
t.is(my_test.is_leapyear(2001), false);
});
/**
* new Date()传入毫秒数, 获取年份
*/
test("get_year_pass", async (t) => {
t.is(my_test.get_year(1507770062942), 2017);
});
test("get_year_false", async (t) => {
t.is(my_test.get_year(1507770062942), 1970);
});
test("get_year_false_beyond", async (t) => {
t.is(my_test.get_year(150777006294213123131), 150777006294213123131);
});
/**
* 获取两个日期相距的毫秒数
*/
test("set_year_pass", async (t) => {
t.is(my_test.set_year(1000, 2017), 1483228801000);
});
test("set_year_false", async (t) => {
t.is(my_test.set_year(1000, 2017), 1507778000854);
});
test("get_month_pass", async (t) => {
t.is(my_test.get_month(1507778000854), 10);
});
test("get_month_false", async (t) => {
t.is(my_test.get_month(1507778000854), 10);
});
test("set_month", async (t) => {
t.is(my_test.set_month(1507778000854, 8), 1502507600854);
console.log(new Date(my_test.set_month(1507778000854, 8)).getTime());
});
test("get_day_of_month", async (t) => {
t.is(my_test.get_day_of_month(1507778000854), 12)
});
test("set_day_of_month", async (t) => {
t.is(my_test.set_day_of_month(1507778000854, 1), 1506827600854)
});
test("set_day_of_month_false_beyond", async (t) => {
t.is(my_test.set_day_of_month(1507778000854, 19), 1506827600854)
});
test("get_hours", async (t) => {
t.is(my_test.get_hours(1507778000854), 11);
});
test("set_hours_pass", async (t) => {
t.is(my_test.set_hours(1507778000854, 10), 1507774400854);
});
test("set_hours_false", async (t) => {
t.is(my_test.set_hours(1507778000854, 10), 1507774400850);
});
test("set_hours_false_beyond", async (t) => {
t.is(my_test.set_hours(1507778000854, 25), 1507774400850); // 25 相当于 1
});
test("get_minutes", async (t) => {
t.is(my_test.get_minutes(1507778000854), 13)
});
test("set_minutes", async (t) => {
t.is(my_test.set_minutes(1507778000854, 1), 1507777280854) //61相当于1
console.log(new Date(my_test.set_minutes(1507778000854, 61)).getMinutes());
});
test("get_seconds", async (t) => {
t.is(my_test.get_seconds(1507778000854), 20)
});
test("set_seconds", async (t) => {
t.is(my_test.set_seconds(1507778000854, 1), 1507777981854) //61相当于1
console.log(new Date(my_test.set_seconds(1507778000854, 61)).getSeconds());
});
test("get_milliseconds", async (t) => {
t.is(my_test.get_milliseconds(1507778000854), 854);
});
test("set_milliseconds", async (t) => {
t.is(my_test.set_milliseconds(1507778000854, 1), 1507778000001); //61相当于1
console.log(new Date(my_test.set_milliseconds(1507778000854, 9999999))); //2017-10-12T05:59:59.999Z
console.log(new Date(1507778000854)); //2017-10-12T03:13:20.854Z
});
test("get_dayOfWeek", async (t) => {
t.is(my_test.get_dayOfWeek(1507778000854), 4);
});
test("get_days_in_month", async (t) => {
t.is(my_test.get_days_in_month(0), 31);
});
test("parse", async (t) => {
t.is(my_test.parse("Thu Oct 12 2017 13:02:40 GMT+0800 (中国标准时间)"), 1507784560000);
});
test("now", async (t) => {
t.is(my_test.now(), 1507784560000);
});
test("get_day_of_week", async (t) => {
t.is(my_test.get_day_of_week(1507784560000), 4);
});
test("get_timezone_offset", async (t) => {
t.is(my_test.get_timezone_offset(1507784560000), -480);
});
test("tm2str", async (t) => {
t.is(my_test.tm2str(1507784560000), "Thu Oct 12 2017 13:02:40 GMT+0800 (中国标准时间)");
});
test("tm2tmstr", async (t) => {
t.is(my_test.tm2tmstr(1507784560000), "13:02:40 GMT+0800 (中国标准时间)");
});
test("tm2local_str", async (t) => {
t.is(my_test.tm2local_str(1507784560000), "2017-10-12 13:02:40");
});
test("tm2local_tmstr", async (t) => {
t.is(my_test.tm2local_tmstr(1507784560000), "13:02:40");
});
test("tm2isostr", async (t) => {
t.is(my_test.tm2isostr(1507784560000), "2017-10-12T05:02:40.000Z");
});
test("tm2json", async (t) => {
t.is(my_test.tm2json(1507784560000), "2017-10-12T05:02:40.000Z");
});
test("tm2json2", async (t) => {
t.is(my_test.tm2json(1507784560000, "time"), "2017-10-12T05:02:40.000Z");
});
test("valueof", async (t) => {
t.is(my_test.valueof(1507784560000), 1507784560000)
});
|
var mainModule = angular.module('mainModule', ['ngRoute', 'ui.bootstrap']);
mainModule.config(function ($routeProvider) {
$routeProvider
.when('/',{
templateUrl: 'partials/defaultPartial.html'
})
.when('/secondPartial', {
templateUrl: 'partials/secondaryDefaultPartial.html'
})
.otherwise({
redirectTo: '/'
});
});
|
import React,{Component} from 'react';
import {NavLink} from 'react-router-dom';
class TopNavigation extends Component{
render(){
let nav=null;
if(this.props.enabled)
{
nav=(<div>
<NavLink className="menu-link is-active notify" to="/" activeClassName="notify" exact>Overview</NavLink>
<NavLink className="menu-link" to="/reports"
activeClassName="notify">Reports</NavLink>
<NavLink className="menu-link" to="/precriptions"
activeClassName="notify">Prescriptions</NavLink>
</div>);
}
return (
<div className="header">
<div className="menu-circle"><img src="http://localhost:3000/3dlogo.png" className='logo-image' />
</div>
<div className="header-menu">
{nav}
</div>
<div className="search-bar">
<input type="text" placeholder="Search" />
</div>
<div className="header-profile">
<div className="notification">
<span className="notification-number">3</span>
<svg viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="feather feather-bell">
<path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9M13.73 21a2 2 0 01-3.46 0" />
</svg>
</div>
<NavLink className="log" to="/logout"><img className="profile-img" src="https://images.unsplash.com/photo-1600353068440-6361ef3a86e8?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80" alt="" />
<div className="logout">Logout</div></NavLink>
</div>
</div>
);
}
}
export default TopNavigation;
|
'use strict';
/**
* @ngdoc overview
* @name yapp
* @description
* # yapp
*
* Main module of the application.
*/
var states = [
{ name: 'base', state: { abstract: true, url: '', templateUrl: 'views/base.html', data: {text: "Base", visible: false, admin: false } } },
{ name: 'login', state: { url: '/login', parent: 'base', templateUrl: 'views/login.html', controller: 'LoginCtrl', data: {text: "Login", visible: false, admin: false } } },
{ name: 'dashboard', state: { url: '/dashboard', parent: 'base', templateUrl: 'views/dashboard.html', controller: 'DashboardCtrl', data: {text: "Dashboard", visible: false, admin: false } } },
{ name: 'overview', state: { url: '/overview', parent: 'dashboard', templateUrl: 'views/dashboard/overview.html', data: {text: "Overview", visible: false, admin: false } } },
{ name: 'lists', state: { url: '/lists', parent: 'dashboard', templateUrl: 'views/dashboard/lists.html', data: {text: "Lists", visible: true, admin: false } } },
{ name: 'new-list', state: { url: '/new-list', parent: 'dashboard', templateUrl: 'views/dashboard/new-list.html', data: {text: "New List", visible: false, admin: true } } },
{ name: 'events', state: { url: '/events', parent: 'dashboard', templateUrl: 'views/dashboard/events.html', data: {text: "Events", visible: true, admin: false } } },
{ name: 'new-interaction', state: { url: '/new-interaction', parent: 'dashboard', templateUrl: 'views/dashboard/new-interaction.html', data: {text: "New Interaction", visible: false, admin: false } } },
{ name: 'new-event', state: { url: '/new-event', parent: 'dashboard', templateUrl: 'views/dashboard/new-event.html', data: {text: "New Event", visible: false, admin: true } } },
{ name: 'active-votes', state: { url: '/active-votes', parent: 'dashboard', templateUrl: 'views/dashboard/active-votes.html', data: {text: "Active Votes", visible: true , admin: false } } },
{ name: 'vote-editor', state: { url: '/vote-editor', parent: 'dashboard', templateUrl: 'views/dashboard/vote-editor.html', data: {text: "Vote Editor", visible: true, admin: true } } },
{ name: 'new-vote', state: { url: '/new-vote', parent: 'dashboard', templateUrl: 'views/dashboard/new-vote.html', data: {text: "New Vote", visible: false, admin: true } } },
{ name: 'restricted-page', state: { url: '/restricted-page', parent: 'dashboard', templateUrl: 'views/dashboard/restricted-page.html', data: {text: "Restricted Page", visible: false, admin: false } } },
{ name: 'admin-options', state: { url: '/admin-options', parent: 'dashboard', templateUrl: 'views/dashboard/admin-options.html', data: {text: "Admin Options", visible: false, admin: true } } },
{ name: 'new-batch-vote', state: { url: '/new-batch-vote', parent: 'dashboard', templateUrl: 'views/dashboard/new-batch-vote.html', data: {text: "New Batch Vote", visible: false, admin: true } } },
{ name: 'vote-history', state: { url: '/vote-history', parent: 'dashboard', templateUrl: 'views/dashboard/vote-history.html', data: {text: "Vote History", visible: false, admin: false } } },
{ name: 'my-org', state: { url: '/my-org', parent: 'dashboard', templateUrl: 'views/dashboard/my-org.html', data: {text: "My Org", visible: true, admin: false } } }
//,{ name: 'logout', state: { url: '/login', data: {text: "Logout", visible: true }} }
];
angular.module('yapp', [
'ui.router',
'snap'
// 'ngAnimate'
])
.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.when('/dashboard', '/dashboard/overview');
$urlRouterProvider.otherwise('/login');
angular.forEach(states, function (state) {
$stateProvider.state(state.name, state.state);
});
});
|
angular.module('zingClient')
.factory('Support', ['$resource', function($resource) {
return $resource('/api/support/:id', {id : "@_id"},
{
'update': {method: 'PUT', isArray:true},
'get': {method:'GET'},
'save': {method:'POST', isArray:true},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE', isArray:true}
});
}]);
|
/**
* Copyright 2016 Google Inc.
*
* 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.
*/
goog.provide('audioCat.ui.widget.SliderWidget');
goog.require('audioCat.ui.dialog.DialogText');
goog.require('audioCat.ui.dialog.EventType');
goog.require('audioCat.ui.widget.Widget');
goog.require('audioCat.ui.widget.templates');
goog.require('goog.dom.classes');
goog.require('goog.events');
goog.require('goog.string');
goog.require('soy');
/**
* A generic, abstract slider.
* @param {!audioCat.utility.DomHelper} domHelper Facilitates DOM interactions.
* @param {string} className The class name to give to the container of the
* slider widget as a whole.
* @param {string} sliderMainLabel The main label to give the slider for the
* user to see.
* @param {string} leftLabel The label to the left of the slider.
* @param {string} rightLabel The label to the right of the slider.
* @param {number} decimalRound The number of decimal points to round values to
* for display.
* @param {number} divisions The number of stopping points on the slider. The
* more stopping points, the finer the slider resolution.
* @param {number} minStateValue The min value of the state the slider is
* representing. For gain, this would be 0.
* @param {number} maxStateValue The max value of the state the slider is
* representing. For gain, this would be 1.0.
* @param {number} initialStateValue The initial state value the slider will
* take on. The slider will round to the closest stop on it.
* @param {number} defaultStateValue The default state value. When the user
* hits reset, the slider will be set to this state value.
* @param {!audioCat.utility.dialog.DialogManager} dialogManager Manages
* dialogs.
* @constructor
* @extends {audioCat.ui.widget.Widget}
*/
audioCat.ui.widget.SliderWidget = function(
domHelper,
className,
sliderMainLabel,
leftLabel,
rightLabel,
decimalRound,
divisions,
minStateValue,
maxStateValue,
initialStateValue,
defaultStateValue,
dialogManager) {
/**
* Facilitates DOM interactions.
* @private {!audioCat.utility.DomHelper}
*/
this.domHelper_ = domHelper;
/**
* The main label for the slider.
* @private {string}
*/
this.mainLabel_ = sliderMainLabel;
/**
* The number of stops on the slider.
* @private {number}
*/
this.numberOfStops_ = divisions;
/**
* The min DOM value of the slider
* @private {number}
*/
this.minSliderValue_ = 1;
/**
* The max DOM value of the slider.
* @private {number}
*/
this.maxSliderValue_ = divisions + this.minSliderValue_ - 1;
// Above, we must subtract 1 to discount the min value as a single stop.
/**
* The minimum state value.
* @private {number}
*/
this.minStateValue_ = minStateValue;
/**
* The maximum state value.
* @private {number}
*/
this.maxStateValue_ = maxStateValue;
/**
* The difference in state value.
* @private {number}
*/
this.stateDifference_ = maxStateValue - minStateValue;
/**
* The initial state value.
* @private {number}
*/
this.initialStateValue_ = initialStateValue;
/**
* The default state value.
* @private {number}
*/
this.defaultStateValue_ = defaultStateValue;
/**
* Manages dialogs.
* @private {!audioCat.utility.dialog.DialogManager}
*/
this.dialogManager_ = dialogManager;
/**
* The number of places to round decimal points to for display.
* @private {number}
*/
this.decimalRound_ = decimalRound;
/**
* The lower bound of the range [-small value, 0] in which the display value
* will dangerously display a negative 0 value, ie something like -0.00.
* @private {number}
*/
this.negativeZeroBound_ = -1 * Math.pow(10, -1 * decimalRound);
var initialSliderValue = this.computeSliderValue_(this.initialStateValue_);
// The DOM element for container of the slider.
var element = /** @type {!Element} */ (
soy.renderAsFragment(audioCat.ui.widget.templates.SliderWidget, {
mainLabel: sliderMainLabel,
leftLabel: leftLabel,
rightLabel: rightLabel,
initialStateValue: initialStateValue,
initialSliderValue: initialSliderValue,
minSliderValue: this.minSliderValue_,
maxSliderValue: this.maxSliderValue_
}));
goog.dom.classes.add(element, className);
goog.base(this, element);
/**
* The slider element.
* @private {!Element}
*/
this.sliderElement_ = domHelper.getElementByClassForSure(
goog.getCssName('sliderInputElement'), element);
/**
* The container for the value label.
* @private {!Element}
*/
this.sliderLabelContainer_ = domHelper.getElementByClassForSure(
goog.getCssName('sliderValueContainer'), element);
this.setValueDisplayer_(initialStateValue);
/**
* The stable slider DOM value.
* @private {number}
*/
this.stableSliderDomValue_ = initialSliderValue;
/**
* The function to call when the slider changes, not necessarily stabily. The
* new state value will be given to the callback.
* @private {!Function}
*/
this.genericChangeCallback_ = goog.nullFunction;
/**
* The function to call when the slider changes stabily. The new stable state
* value will be given to the callback.
* @private {!Function}
*/
this.stableChangeCallback_ = goog.nullFunction;
var sliderElement = this.sliderElement_;
goog.events.listen(
sliderElement, 'change', this.handleSliderValueChange_, false, this);
goog.events.listen(
sliderElement, 'input', this.handleSliderValueChange_, false, this);
domHelper.listenForUpPress(sliderElement,
this.handleSliderStableValueChange_, false, this);
// TODO(chizeng): Clean up this listener if this widget ever goes away.
// Open a dialog letting the user alter the value upon clicking.
domHelper.listenForUpPress(this.sliderLabelContainer_,
this.handleSliderLabelContainerClicked_, false, this);
};
goog.inherits(audioCat.ui.widget.SliderWidget, audioCat.ui.widget.Widget);
/**
* Handles what happens when the user clicks on the value displayer.
* Specifically, lets the user manually input a value.
* @private
*/
audioCat.ui.widget.SliderWidget.prototype.handleSliderLabelContainerClicked_ =
function() {
var dialogManager = this.dialogManager_;
var domHelper = this.domHelper_;
var content = /** @type {!Element} */ (soy.renderAsFragment(
audioCat.ui.widget.templates.SliderWidgetValueDialog, {
mainLabel: this.mainLabel_,
minStateValue: this.minStateValue_,
maxStateValue: this.maxStateValue_,
currentStateValue:
this.obtainValueDisplayerString_(this.getCurrentStateValue())
}
));
var inputElement = domHelper.getElementByClassForSure(
goog.getCssName('sliderDialogInputElement'), content);
// Updates the stable value of the slider. Returns 0 if successful. Otherwise,
// returns display string.
var updateValue = function(opt_stateValue) {
var stateValue = goog.isDef(opt_stateValue) ?
opt_stateValue : goog.string.toNumber(inputElement.value.trim());
if (isNaN(stateValue)) {
return 'Invalid value.';
}
if (stateValue < this.minStateValue_ || stateValue > this.maxStateValue_) {
// Value is out of range.
return 'Value is out of range.';
}
var sliderValue = this.computeSliderValue_(stateValue);
stateValue = this.computeStateValue_(sliderValue);
// Update the slider.
this.sliderElement_.value = sliderValue;
// Make updates.
this.handleSliderValueChange_();
this.handleSliderStableValueChange_();
// Display the rounded value for consistency.
inputElement.value = this.obtainValueDisplayerString_(stateValue);
return 0;
};
var messageBoxContainer = domHelper.getElementByClassForSure(
goog.getCssName('messageBoxContainer'), content);
var warningBox = domHelper.getElementByClassForSure(
goog.getCssName('warningBox'), content);
var successBox = domHelper.getElementByClassForSure(
goog.getCssName('successBox'), content);
domHelper.removeNode(warningBox);
domHelper.removeNode(successBox);
// Apply a value. Return true on success.
var applyValue = function(e, opt_value) {
var error = goog.bind(updateValue, this)(opt_value);
if (error) {
domHelper.setRawInnerHtml(warningBox, error);
domHelper.appendChild(messageBoxContainer, warningBox);
domHelper.removeNode(successBox);
return false;
}
domHelper.removeNode(warningBox);
domHelper.setRawInnerHtml(successBox, 'Value applied successfully.');
domHelper.appendChild(messageBoxContainer, successBox);
return true;
};
// The applyValue function bound to the correct execution context.
var boundApply = goog.bind(applyValue, this);
// Obtain a cancelable dialog.
var dialog = dialogManager.obtainDialog(
content, audioCat.ui.dialog.DialogText.CLOSE);
// The OK button applies the value, then closes the dialog if all is well.
var formSubmitListenerKey;
var dialogCancelListenerKey;
var handleOk = function(e) {
// Prevent the form from actually submitting and refreshing the page.
e.preventDefault();
if (boundApply(e, undefined)) {
dialogManager.hideDialog(dialog);
// Stop listening to the form.
goog.events.unlistenByKey(formSubmitListenerKey);
// Stop listening to the cancel event.
goog.events.unlistenByKey(dialogCancelListenerKey);
}
// Return false to help suppress browsers from submitting the form and
// refreshing the page.
return false;
};
// Create the primary dialog buttons.
var buttonsArea = domHelper.createElement('div');
goog.dom.classes.add(buttonsArea, goog.getCssName('sliderButtonsArea'));
var applyButton = dialogManager.obtainButton('Apply');
applyButton.performOnUpPress(boundApply);
domHelper.appendChild(buttonsArea, applyButton.getDom());
var okButton = dialogManager.obtainButton('OK');
var boundOkCallback = goog.bind(handleOk, this);
okButton.performOnUpPress(boundOkCallback);
domHelper.appendChild(buttonsArea, okButton.getDom());
var resetButton = dialogManager.obtainButton('Reset to ' +
this.obtainValueDisplayerString_(this.defaultStateValue_));
resetButton.performOnUpPress(
goog.bind(applyValue, this, undefined, this.defaultStateValue_));
domHelper.appendChild(buttonsArea, resetButton.getDom());
// Put the buttons onto the main content panel.
domHelper.appendChild(content, buttonsArea);
// The user could've submitted the form by hitting enter instead of clicking
// OK.
var sliderDialogForm = domHelper.getElementByClassForSure(
goog.getCssName('sliderDialogForm'), content);
formSubmitListenerKey = goog.events.listen(sliderDialogForm, 'submit',
boundOkCallback, false, this);
dialogCancelListenerKey = goog.events.listenOnce(
dialog, audioCat.ui.dialog.EventType.HIDE_DIALOG_REQUESTED,
function() {
// Stop listening to the form.
goog.events.unlistenByKey(formSubmitListenerKey);
}, false, this);
// Show the dialog.
dialogManager.showDialog(dialog);
};
/**
* @return {number} The current state value.
*/
audioCat.ui.widget.SliderWidget.prototype.getCurrentStateValue = function() {
return this.computeStateValue_(this.sliderElement_.value);
};
/**
* Sets the string that the value displayer shows.
* @param {number} stateValue The state value.
* @private
*/
audioCat.ui.widget.SliderWidget.prototype.setValueDisplayer_ =
function(stateValue) {
this.domHelper_.setTextContent(
this.sliderLabelContainer_,
this.obtainValueDisplayerString_(stateValue));
};
/**
* Obtains the string that the value displayer should show.
* @param {number} stateValue The state value to show.
* @return {string} A string representation of the state value that is
* presentable to the user.
* @private
*/
audioCat.ui.widget.SliderWidget.prototype.obtainValueDisplayerString_ =
function(stateValue) {
if (stateValue > this.negativeZeroBound_ && stateValue < 0) {
// Prevent displays of negative 0 values, ie something like -0.00.
stateValue = 0;
}
return stateValue.toFixed(this.decimalRound_);
};
/**
* Handles changes in slider value.
* @private
*/
audioCat.ui.widget.SliderWidget.prototype.handleSliderValueChange_ =
function() {
var newStateValue = this.getCurrentStateValue();
this.setValueDisplayer_(newStateValue);
this.genericChangeCallback_(newStateValue);
};
/**
* Performs a certain function when the slider changes as the user actively
* drags it. The given function takes the state value as parameter.
* @param {!Function}
* callback A method to call with the slider as the context when the user
* drags the slider.
*/
audioCat.ui.widget.SliderWidget.prototype.performAsSliderShifts =
function(callback) {
this.genericChangeCallback_ = callback;
};
/**
* Performs a certain function when the slider enters a new stable position.
* @param {!Function}
* callback A method to call with the slider as the context when the user
* drags the slider. The given function takes the state value as parameter.
*/
audioCat.ui.widget.SliderWidget.prototype.performOnStableConfiguration =
function(callback) {
this.stableChangeCallback_ = callback;
};
/**
* Handles changes in the stable value of the slider.
* @private
*/
audioCat.ui.widget.SliderWidget.prototype.handleSliderStableValueChange_ =
function() {
var sliderValue = this.sliderElement_.value;
if (this.stableSliderDomValue_ != sliderValue) {
// Only change the slider value if there is an actual change.
this.stableSliderDomValue_ = sliderValue;
this.stableChangeCallback_(this.computeStateValue_(sliderValue));
}
};
/**
* Computes the state value from the slider DOM value.
* @param {number} sliderValue Slider DOM value.
* @return {number} The corresponding state value.
* @private
*/
audioCat.ui.widget.SliderWidget.prototype.computeStateValue_ =
function(sliderValue) {
var minSliderValue = this.minSliderValue_;
return this.minStateValue_ +
(sliderValue - minSliderValue) * this.stateDifference_ /
(this.maxSliderValue_ - minSliderValue);
};
/**
* Computes the slider value from the state value.
* @param {number} stateValue State value. Like gain or pan.
* @return {number} The corresponding slider value.
* @private
*/
audioCat.ui.widget.SliderWidget.prototype.computeSliderValue_ =
function(stateValue) {
var minStateValue = this.minStateValue_;
var minSliderValue = this.minSliderValue_;
return minSliderValue + Math.round((stateValue - minStateValue) *
(this.maxSliderValue_ - minSliderValue) /
this.stateDifference_);
};
/**
* Sets the new state value. Alters the slider if the state value differs.
* @param {number} stateValue The new state value.
*/
audioCat.ui.widget.SliderWidget.prototype.setStateValue =
function(stateValue) {
var sliderElement = this.sliderElement_;
var newSliderValue = this.computeSliderValue_(stateValue);
if (newSliderValue != sliderElement.value) {
// Take no action if the state value did not change enough to change the
// slider.
sliderElement.value = newSliderValue;
this.setValueDisplayer_(stateValue);
}
};
/** @override */
audioCat.ui.widget.SliderWidget.prototype.cleanUp = function() {
var unlistenFunction = goog.events.unlisten;
var sliderElement = this.sliderElement_;
unlistenFunction(sliderElement, 'change',
this.handleSliderValueChange_, false, this);
unlistenFunction(sliderElement, 'input',
this.handleSliderValueChange_, false, this);
var domHelper = this.domHelper_;
domHelper.unlistenForUpPress(sliderElement,
this.handleSliderStableValueChange_, false, this);
domHelper.unlistenForUpPress(this.sliderLabelContainer_,
this.handleSliderLabelContainerClicked_, false, this);
// Just to be sure, remove references to callbacks.
this.performAsSliderShifts(goog.nullFunction);
this.performOnStableConfiguration(goog.nullFunction);
audioCat.ui.widget.SliderWidget.base(this, 'cleanUp');
};
|
/**
* 单例
*
* 规则:
1. overscroll:scroll的元素始终可以在对应坐标方向滚动
2. overscroll:auto的元素如果在对应方向滚动到头则继续向上层寻找可滚动元素
3. 符合extra条件的元素不能作为选择元素的条件
*/
var startPosY, startPosX, curPosY, curPosX;
var stat = false;
var defaultConfig = {
//其他不爽的element
isExtraElement : function(element){
switch(true){
case element.tagName === 'INPUT' && element.type === 'range':;
return true;
default :
return false;
}
}
};
var config = {};
var notPreventScrollElement = function(element){
return config.isExtraElement(element) || isScrollElement(element);
}
//能滚的element
var isScrollElement = function(element, whileTouch) {
var checkFunc = whileTouch ? checkIsScrollElementWhileTouch : checkIsScrollElementWhileScroll;
while(element) {
if(checkFunc(element)){
return element;
}
element = element.parentElement;
}
return false;
}
var checkIsScrollElementWhileTouch = function(element){
var style = window.getComputedStyle(element);
var tmp, check;
//规则1
if(style.overflowY === 'scroll' && element.scrollHeight > element.clientHeight){
check = true;
if(element.scrollTop === 0){
element.scrollTop = 1;
}
tmp = element.scrollHeight - element.clientHeight;
if(tmp === element.scrollTop){
element.scrollTop = tmp - 1;
}
}
if(style.overflowX === 'scroll' && element.scrollWidth > element.clientWidth){
check = true;
if(element.scrollLeft === 0){
element.scrollLeft = 1;
}
tmp = element.scrollWidth - element.clientWidth;
if(tmp === element.scrollLeft){
element.scrollLeft = tmp - 1;
}
}
if(check){
return element;
}
}
var checkIsScrollElementWhileScroll = function(element){
var style = window.getComputedStyle(element);
//规则2
return (
(style.overflowY === 'scroll' || style.overflowY === 'auto')
&& (
element.scrollHeight > element.clientHeight
&& !(startPosY <= curPosY && element.scrollTop === 0)
&& !(startPosY >= curPosY && element.scrollHeight - element.scrollTop === element.clientHeight)
)
||
(style.overflowX === 'scroll' || style.overflowX === 'auto')
&&
element.scrollWidth > element.clientWidth
&& !(startPosX <= curPosX && element.scrollLeft === 0)
&& !(startPosX >= curPosX && element.scrollWidth - element.scrollLeft === element.clientWidth)
);
}
//bind
var bindFunc = {
move : function(e) {
curPosY = e.touches ? e.touches[0].screenY : e.screenY;
curPosX = e.touches ? e.touches[0].screenX : e.screenX;
notPreventScrollElement(e.target) || e.preventDefault();
},
start : function(e){
var target = isScrollElement(e.target, true);
startPosY = e.touches ? e.touches[0].screenY : e.screenY;
startPosX = e.touches ? e.touches[0].screenX : e.screenX;
}
}
var api = {
bind : function(){
if(!stat){
stat = true;
document.addEventListener('touchmove', bindFunc.move, false);
document.addEventListener('touchstart', bindFunc.start, false);
}
return this;
},
config : function(cfg){
cfg = cfg || {};
config.isExtraElement = cfg.isExtraElement || defaultConfig.isExtraElement;
return this;
},
move : function(nodes, target){
nodes = nodes ?
nodes :
'all' in document ?
[].filter.call(document.all, function(el){
return window.getComputedStyle(el).position === 'fixed';
}) :
[];
target = target || document.body;
[].forEach.call(nodes, function(el){
target.appendChild(el);
});
return this;
},
destory : function(){
stat = false;
document.removeEventListener('touchmove', bindFunc.move, false);
document.removeEventListener('touchstart', bindFunc.start, false);
}
};
if(typeof module !== 'undefined'){
module.exports = api;
}
api.config();
|
const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Body = Matter.Body;
const Constraint=Matter.Constraint;
var ground;
function setup() {
createCanvas(800, 700);
engine = Engine.create();
world = engine.world;
ground=new Roof(400,200,400,30);
bob1=new Bob(300,480,25);
bob2=new Bob(350,480,25);
bob3=new Bob(400,480,25);
bob4=new Bob(450,480,25);
bob5=new Bob(500,480,25);
rop1=new Chain(bob1.body,ground.body,-100,0);
rop2=new Chain(bob2.body,ground.body,-50,0);
rop3=new Chain(bob3.body,ground.body,0,0);
rop4=new Chain(bob4.body,ground.body,50,0);
rop5=new Chain(bob5.body,ground.body,100,0);
Engine.run(engine);
}
function draw() {
background(0);
Engine.update(engine);
rectMode(CENTER);
ground.display();
bob1.display();
bob2.display();
bob3.display();
bob4.display();
bob5.display();
rop1.display();
rop2.display();
rop3.display();
rop4.display();
rop5.display();
drawSprites();
}
function keyPressed(){
if(keyCode===UP_ARROW){
Matter.Body.applyForce(bob1.body,bob1.body.position,{x:-25,y:-25});
}
}
|
import React, { Component } from 'react';
import Pumpkin from "./Pumpkin";
import './App.css';
class Deal extends Component {
constructor(props) {
super(props);
this.state = {
pumpkinData: [
{
name: "Blaze",
description: "Flashy yellow, orange-striped fruits are flattened-round with shallow ribs. Sturdy, short vine plants have excellent powdery mildew resistance and produce very high yields of 3 lb. x 7'' diam. x 3.5'' tall fruits with exceptional uniformity in shape and size. Bright color and remarkable productivity make Blaze a fantastic addition to any ornamental lineup. Intermediate resistance to powdery mildew. ",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dw6045ba66/images/products/vegetables/3668_01_blaze.jpg?sw=560&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Jill-Be-Little",
description: "Uniform and high yielding Jill-Be-Little has a flattened shape and wide, deep ribs. Orange 1/2 lb. fruits measure 3-4'' diam. x 2 1/2'' tall. Great for tabletop and window displays, especially when paired with Spark. Improved disease resistance over Munchkin, which it replaces. Strong long vine plants",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dwb10a5b68/images/products/vegetables/3767_01_jillbelittle.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Galeux d'Esines",
description: "Unique heirloom with flattened-globe shape and salmon-pink skin. While the amount of skin blistering increases as a result of time spent on the vine, we recommend harvesting at maturity because fruits can crack when overmature. Galeux d'Eysines is an ornamental with a lot of character but also lends good flavor to soups and stews. Long vine plant habit.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dwe466fdad/images/products/vegetables/3777_01_galeuxdeysines.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Early Giant",
description: "Elongated and blocky, medium-dark orange fruits are uniform in shape. Excellent size potential, fruits range 14-40 lb. avg. 25 lb. Stocky handles, light ribs, and long vine habit. Easy to grow for such a large-fruited type, Early Giant is also well adapted and a reliable producer. Tall fruits with rich color attract attention at roadside stands and farmers' markets.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dw1471c081/images/products/vegetables/03782_01_earlygiant.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Darling",
description: "Early maturing small pumpkin with a different look. Very uniform, elongated fruit shape and stocky handles. Skin is smooth, lightly ribbed, and a vibrant medium-orange color. Fruits average 5 lb., weight range 3-9 lb. Short vine habit with concentrated fruit set. ",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dwaaab5a3c/images/products/vegetables/3781_01_darling.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Porcelain Doll",
description: "Add diversity to fall ornamental displays with the unique color of Porcelain Doll. The sweet flesh can be used for pies, soups, and other gourmet delights. Full vines bear blocky, deeply ribbed fruit averaging 16-24 lb. Avg. yield 2-3 fruits/plant. ",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dw045bcd57/images/products/vegetables/03997_01_porcelaindoll.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Moonshine",
description: "Very uniform, smooth-skinned pumpkins avg. 8-12 lb. Perfect for decorating or carving. Long, dark green handles. Avg. 3-4 fruits/plant. Combine it with Kakai, Sunlight PMR, and Orange Smoothie for a great display.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dw735bd315/images/products/vegetables/00690_01_moonshine.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Musque de Prevence",
description: "Ribbed, flat, tan fruits are bigger than Long Island Cheese, avg. 8-15 lb. Thick, deep orange, moderately sweet flesh. In France cut wedges are sold in supermarkets and farmers' markets for cooking. Decorative. Late maturity.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dw981526a1/images/products/vegetables/02621_01_musqueprovence.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Dill's Atlantic Giant",
description: "Huge pinkish or orange fruits for fall display. 50 to 100 pounders are commonly grown. Fertile soil, irrigation, wide spacing (70 or more sq.ft./plant), and limiting each long-vined plant to one fruit commonly result in 200-300 pounders. The current world record is an Atlantic Giant of over 2,000 lb. We offer seeds from the originator, Howard Dill of Nova Scotia. ",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dw65564c90/images/products/vegetables/00602_01_dillsatlantic.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Valenciano",
description: "Clearly the whitest pumpkin; unique for doorstep decorations and painting. Medium-size, flattened, avg. 11-15'' diam. x 6-8'' tall, slightly ribbed, with a smooth white skin. Thick orange flesh suitable for pies.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dwad558901/images/products/vegetables/02185_01_valenciano.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Rouge Vif D'Etampes",
description: "Known as Rouge vif d'Etampes in France. 'Rouge vif' means 'vivid red'. This is an attractive variety for fall display. Shaped flat, looking like a red cheese wheel, the fruits average 10-15 lb. The moderately sweet, orange flesh is suited for pie.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dwbfe43fa0/images/products/vegetables/00614_01_rougevifdetmps.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Knuckle Head",
description: "Freaky, orange, and warted. Spectacular warting makes them the star of the show. Moderate vines bear fruit averaging 12-16 lb. and 12'' h x 10'' w. ",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dw9caaaed3/images/products/vegetables/00091_01_knuckle_head.jpg?sw=774&cx=322&cy=38&cw=1146&ch=1146"
},
{
name: "New England Pie",
description: "Dark orange-skinned pumpkins in a range of small sizes, typically 4-6 lb. Although not as sweet as squash, the well-colored, orange flesh is relatively starchy, dry, and stringless. A well-known mini Jack O'Lantern type for pies. ",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dw985a42cb/images/products/vegetables/00592g_01_new_england_pie.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Casperita",
description: "Ideal for pick-your-own operations, fall markets, and home decoration. This mini, 1/2-1 lb., white pumpkin has strong green handles and holds its color well. Avg. yield: 7-8 fruits/plant. Intermediate resistance to powdery mildew and watermelon mosaic virus. ",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dwd87acab5/images/products/vegetables/03076_01_casperita.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Long Island Cheese",
description: "Medium-large, flattened, medium-ribbed, suggesting a wheel of cheese. Smooth, tan skin, slender woody stem. Deep orange, moderately sweet flesh for pie. Long storage. A beautiful oldie.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dwea6c2a98/images/products/vegetables/02051_01_longislandcheese.jpg?sw=774&cx=630&cy=124&cw=1000&ch=1000"
},
{
name: "Marina Di Chioggia",
description: "Avg. 6-12 lb. bumpy squashes make a wild yet subdued ornamental statement for fall. Amy Goldman in her new book, The Compleat Squash, describes this Italian seaside specialty as deliziosa, especially for gnocchi and ravioli, and a culinary revelation.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dw79cf54bd/images/products/vegetables/02625_01_marinadichioggia.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Bliss",
description: "This Asian hybrid is a mottled combination of green and orange with long, thin handles. A truly unusual coloration on the avg. 5-7 lb. fruit. The beautiful, dark yellow to orange flesh is best for savory dishes, such as curries. Vigorous plants with later maturity.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dw1ac03625/images/products/vegetables/00692_01_bliss.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Baby Bear",
description: "Baby Bear is a unique size and shape, and the deep orange, 1 1/2-2 1/2-lb. fruits are about half the size of a normal pie pumpkin. With slender, sturdy, easy-to-grip handles, they are very appealing to children. In addition to its decorative use, the flesh is good for pies and the semi-hulless seeds are good for roasted snacks.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dw30957bd3/images/products/vegetables/0600t_01_babybear.jpg?sw=774&cx=70&cy=0&cw=1196&ch=1196"
},
{
name: "Cargo PMR",
description: "Cargo PMR is a perfect medium- to large-size jack-o'-lantern pumpkin. Cargo has intermediate resistance to powdery mildew to help ensure that your crop will develop to full maturity with strong, green handles.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dwa6425655/images/products/vegetables/03978t_01_cargopmr.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Turk's Turban",
description: "Prominent blossom end button is striped silver, green, and white with a scarlet top that measures 7-9'' across. Avg. 3-5 lb.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dw6e9bdfd4/images/products/vegetables/00618_01_turksturban.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Polar Bear",
description: "Polar Bear retains its color after maturity in the field, at market, and in decorative displays. Long, vigorous vines produce fruit typically weighing 30-65 lb. ",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dw0c19e980/images/products/vegetables/02504_01_polarbear_sm_.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Champion",
description: "Typically 30 lb. or more, well ribbed, with thick, medium length handle with an upright shape. Vigorous medium vines.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dwc3a398c8/images/products/vegetables/2601_01_champion.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Speckled Hound",
description: "Yellow-orange, thick, dense flesh with dry matter. Oblate shape with shallow ribbing. Avg. 3-6 lb. ",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dweb586a6a/images/products/vegetables/02506_01_spec_hound.jpg?sw=774&cx=236&cy=94&cw=1000&ch=1000"
},
{
name: "Munchkin",
description: "Fruits avg. 1/2 lb., and are bright orange with deep ribs. Avg. yield: 14 fruits/plant. Very uniform, only 3-4'' wide.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dwc3bb7d14/images/products/vegetables/03075_01_munchkin.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Winter Luxury",
description: "This marvelous, small pumpkin has a unique, netted skin. Typical weight is 5-7 lb. Doing double duty, Winter Luxury is not only a gorgeous ornamental, but is also superb for eating. Long vines.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dw4d79ec0e/images/products/vegetables/2783_01_winterluxury.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Autumn Crown",
description: "Fantastic squash with excellent eating quality. Medium-long vine. Extremely uniform, buff-colored fruit. Combines the attractive skin and flesh characteristics of a butternut with a flat shape and great flavor. Internal color is bright orange with a small seed cavity. Fruits have the aroma of sweet melon when cut. 2-4 lb. fruits.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dwc1d7f725/images/products/vegetables/02508_01_autumncrown.jpg?sw=774&cx=432&cy=86&cw=1000&ch=1000"
},
{
name: "Sunlight PMR",
description: "Create eye-catching displays, and differentiate yourself from others with these 4-6 lb. yellow pumpkins. Great for markets and mixed bins.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dw9c197960/images/products/vegetables/03910_01_sunlight.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Autumn Colors Cushaw",
description: "Unusual, tri-colored fruits have green bottoms, light-orange tops, and white stripes from top to bottom. Avg. 4-10 lb. Great for decorating.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dw9a86908b/images/products/vegetables/03078_01_autumncolorscushawhorz.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Green Striped Cushaw",
description: "Striking green and white striped fruits avg. 7-25 lb. Great for cooking. Avg. 2-4 fruits per plant. Bulbous bottom with tapered neck. Full vine.",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dwaa114b92/images/products/vegetables/03899_01_greencushaw.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
},
{
name: "Kakai",
description: "Eye-catching, medium-small, avg. 5-8 lb., black-striped pumpkins. After displaying the pumpkins in the fall, you can scoop out the large, dark-green, hull-less seeds, which are delicious roasted. The seeds also yield savory oil. Semibush, short-vine plants. ",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dwe69b9145/images/products/vegetables/2860_01_kakai.jpg?sw=774&cx=368&cy=14&cw=1134&ch=1134"
},
{
name: "Red October",
description: "Red October bears uniform, bright red-orange fruit resembling hubbard squash. Avg. 6-10 lb. fruit. ",
url: "http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dw884d4015/images/products/vegetables/02595_01_redoctober.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196"
}
]
}
}
render() {
var num = 0;
let dealOfDay = null;
let headerPhoto = null;
if (num === 1 ) {
dealOfDay =
<div id="deal-container">
<div id="deal-div">
<img src="http://demandware.edgesuite.net/sits_pod32/dw/image/v2/BBBW_PRD/on/demandware.static/-/Sites-jss-master/default/dwe466fdad/images/products/vegetables/3777_01_galeuxdeysines.jpg?sw=774&cx=302&cy=0&cw=1196&ch=1196" />
</div>
<div id="deal-div-right">
<h1>Limited Edition Featured Pumpkin</h1>
<h2>Uniform and high yielding Jill-Be-Little has a flattened shape and wide, deep ribs. Orange 1/2 lb. fruits measure 3-4'' diam. x 2 1/2'' tall. Great for tabletop and window displays, especially when paired with Spark. Improved disease resistance over Munchkin, which it replaces. Strong long vine plants</h2>
</div>
</div>
} else {
headerPhoto =
<div id="headerPhoto">
<img src="https://static.pexels.com/photos/265258/pexels-photo-265258.jpeg" />
</div>
}
return (
<div>
{headerPhoto}
{dealOfDay}
<div id="main-body">
< Pumpkin url={this.state.pumpkinData[2].url} name={this.state.pumpkinData[0].name} />
< Pumpkin url={this.state.pumpkinData[1].url} name={this.state.pumpkinData[1].name} />
< Pumpkin url={this.state.pumpkinData[3].url} name={this.state.pumpkinData[3].name} />
< Pumpkin url={this.state.pumpkinData[22].url} name={this.state.pumpkinData[22].name} />
< Pumpkin url={this.state.pumpkinData[28].url} name={this.state.pumpkinData[28].name} />
< Pumpkin url={this.state.pumpkinData[13].url} name={this.state.pumpkinData[13].name} />
< Pumpkin url={this.state.pumpkinData[24].url} name={this.state.pumpkinData[24].name} />
< Pumpkin url={this.state.pumpkinData[25].url} name={this.state.pumpkinData[25].name} />
< Pumpkin url={this.state.pumpkinData[17].url} name={this.state.pumpkinData[17].name} />
</div>
</div>
);
}
}
export default Deal;
|
$(document).ready(function(){
var input; // 입력값
var calc_2 = 0; // 1항
var result = 0; // 2항
var cookie = null; // 대입
var cookie2 = null; // 대입
$('.btn .num').on('click', function(){
input = $(this).text();
calc_2 += input;
calc_2 = Number(calc_2)
cookie = calc_2;
$('.output').text(calc_2);
console.log(calc_2, result,cookie);
})
var operator;
function calculation(){
switch(operator){
case '+' : result += Number(cookie);
break;
case 'X' : result *= Number(cookie);
break;
case '÷' : result /= Number(cookie);
break;
case '-' : result -= Number(cookie);
break;
//default: cookie = Number(result);
}
}
$('.btn .op').on('click', function(){
var opop = $('.ops').text();
if(opop == 'result'){
var op2 = $(this).text();
operator = op2;
$('.ops2').text(op2)
calc_2 = 0;
}else{
$('.ops2').text('');
operator = $(this).text();
$('.ops').text(operator);
result = calc_2;
calc_2 = 0;
console.log(calc_2, result,cookie);
console.log('bye~')
}
});
$('.btn .result').on('click', function(){
calculation();
console.log(calc_2, result,cookie);
$('.output').text(result);
$('.ops').text('result');
})
//////////////////////////////////////////////////
var onOff = true;
$('.onoff').on('click',function(){
onOff = !onOff;
if(onOff == false){
$(this).find('p').animate({
'left' : '0px'
},100);
$('.output').text(0).css({
'color' : 'darkgoldenrod'
});
$('.cover').hide();
}else{
$(this).find('p').animate({
'left' : '-30px'
},100);
$('.output').text('Bye-').css({
'color' : 'transparent'
})
$('.ops').text('');
$('.ops2').text('');
$('.cover').show();
calc_2 = 0;
result = 0;
}
})
$('.clr').on('click', function(){
calc_2 = 0;
result = 0;
$('.output').text(0);
$('.ops').text('');
$('.ops2').text('');
})
})
|
import ucFirst from "./ucFirst";
const actions = {
getWeatherCity: cityName => dispatch => {
const URL = `/data/2.5/weather?q=${cityName}&APPID=01d43d3c7f7d4442d855a56e23659f74&units=metric&lang=ru`;
dispatch({
type: "CITY_START_FETCH"
})
return fetch(URL)
.then(response => {
return response.json();
})
.then(response => {
dispatch({
type: "DAY_FORECAST",
payload: {
cityName: response.name,
temp: Math.floor(response.main.temp),
humidity: response.main.humidity,
pressure: response.main.pressure,
description: ucFirst(response.weather[0].description),
windSpeed: response.wind.speed,
id: response.id
}
})
})
.catch(err => {
console.log(err);
})
},
useCurrentStore: currentCity => dispatch => {
dispatch({
type: "USE_CURRENT_FORECAST",
payload: {
cityName: currentCity.cityName,
temp: currentCity.temp,
humidity: currentCity.humidity,
pressure: currentCity.pressure,
description: currentCity.description,
windSpeed: currentCity.windSpeed,
id: currentCity.id
}
})
},
weekForecast: (cityId, ifGetFiveDayForecast) => dispatch => {
const URL5Days = `/data/2.5/forecast?id=${cityId}&APPID=01d43d3c7f7d4442d855a56e23659f74&units=metric&lang=ru`;
return fetch(URL5Days)
.then(response => {
return response.json();
})
.then(response => {
dispatch({
type: "WEEK_FORECAST",
payload: {
cityName: response.city.name,
cityId: response.city.id,
list: response.list
}
})
ifGetFiveDayForecast();
})
},
useCurrentWeekForecast: (fiveDayForecastFromStore, ifGetFiveDayForecast) => dispatch => {
dispatch({
type: "USE_CURRENT_WEEK_FORECAST_FROM_STORE",
payload: {
cityName: fiveDayForecastFromStore.cityName,
cityId: fiveDayForecastFromStore.cityId,
list: fiveDayForecastFromStore.list
}
})
ifGetFiveDayForecast();
}
}
export default actions;
|
import { stripTrailingSlash } from './utils';
const WEBSITE_BASE_URL = stripTrailingSlash(process.env.REACT_APP_WEBSITE_BASE_URL);
const BASE_AIRQLOUDS_URL = stripTrailingSlash(
process.env.REACT_APP_BASE_AIRQLOUDS_URL || process.env.REACT_NETMANAGER_BASE_URL
);
export const AIRQLOUD_SUMMARY = `${BASE_AIRQLOUDS_URL}/devices/airqlouds/summary?tenant=airqo`;
const BASE_NEWSLETTER_URL = stripTrailingSlash(
process.env.REACT_APP_BASE_NEWSLETTER_URL || process.env.REACT_NETMANAGER_BASE_URL
);
export const NEWSLETTER_SUBSCRIPTION = `${BASE_NEWSLETTER_URL}/users/newsletter/subscribe?tenant=airqo`;
// // This requires a docker config
// const BASE_INQUIRY_URL = stripTrailingSlash(
// process.env.REACT_APP_BASE_INQUIRY_URL || process.env.REACT_NETMANAGER_BASE_URL,
// );
const BASE_INQUIRY_URL = stripTrailingSlash(process.env.REACT_NETMANAGER_BASE_URL);
export const INQUIRY_URL = `${BASE_INQUIRY_URL}/users/inquiries/register?tenant=airqo`;
const BASE_AUTH_SERVICE_URL = stripTrailingSlash(process.env.REACT_NETMANAGER_BASE_URL);
export const EXPLORE_DATA_URL = `${BASE_AUTH_SERVICE_URL}/users/candidates/register?tenant=airqo`;
// careers urls
export const CAREERS_URL = `${WEBSITE_BASE_URL}/career/`;
export const DEPARTMENTS_URL = `${WEBSITE_BASE_URL}/departments/`;
// members urls
export const TEAMS_URL = `${WEBSITE_BASE_URL}/team/`;
// netmanager url
export const NETMANAGER_URL = stripTrailingSlash(
process.env.REACT_NETMANAGER_BASE_URL.replace('/api/v1/', '')
);
// highlights urls
export const HIGHLIGHTS_URL = `${WEBSITE_BASE_URL}/highlights/`;
export const TAGS_URL = `${WEBSITE_BASE_URL}/tags/`;
// Partners url
export const PARTNERS_URL = `${WEBSITE_BASE_URL}/partner/`;
// Board Member url
export const BOARD_MEMBERS_URL = `${WEBSITE_BASE_URL}/board/`;
// Publications url
export const PUBLICATIONS_URL = `${WEBSITE_BASE_URL}/publications/`;
// Press url
export const PRESS_URL = `${WEBSITE_BASE_URL}/press/`;
// Events url
export const EVENTS_URL = `${WEBSITE_BASE_URL}/event/`;
// African Cities url
export const CITIES_URL = `${WEBSITE_BASE_URL}/african_city/`;
// Impact Number url
export const IMPACT_URL = `${WEBSITE_BASE_URL}/impact/`
|
const isInteger = (NumberForCheck) => Math.floor(NumberForCheck) === NumberForCheck;
console.log(isInteger(4));
console.log(isInteger(4.5));
|
import styled from 'styled-components';
export const FieldContainer = styled.div`
background-color: #f1f4f6;
border: 1px solid #e3e6ea;
box-sizing: border-box;
border-radius: 8px;
width: 100%;
height: 56px;
display: flex;
flex-direction: column;
padding: 7px 16px;
// margin: 4px 0px;
${props => (props.extendFieldContainer ? props.extendFieldContainer : '')};
`;
export const FieldLabel = styled.p`
color: #9c9c9c;
font-size: 12px;
line-height: 18px;
`;
export const FieldValue = styled.p`
font-size: 16px;
line-height: 24px;
color: #484848;
direction: ${props => (props.language === 'ar' ? 'ltr' : 'unset')};
margin: ${props => (props.isTagged ? '0px 8px' : 'unset')};
${props => (props.extendFieldText ? props.extendFieldText : '')};
`;
export const FieldTag = styled(FieldValue)`
margin: 0px 0px;
`;
export const ValueTagContainer = styled.div`
display: flex;
flex-direction: row;
`;
|
import { FaShieldAlt } from "react-icons/fa";
export default {
name: "team",
type: "document",
title: "Teams",
icon: FaShieldAlt,
fields: [
{
name: "name",
title: "Name",
type: "string"
},
{
name: "logo",
type: "image",
title: "Logo"
},
{
name: "active",
type: "boolean",
title: "Active"
},
{
name: "fullName",
type: "string",
title: "Full Name"
},
{
name: "id",
type: "number",
title: "Id"
}
],
preview: {
select: {
name: "fullName",
logo: "logo"
},
prepare(selection) {
const { name, logo } = selection;
return {
title: name,
media: logo
};
}
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.