text
stringlengths
7
3.69M
const chai = require('chai'); const assert = chai.assert; const Ball = require('../lib/scripts/ball'); const stub = require('./support/stub'); describe('Ball', function() { context('with default attributes', function() { it('should be instantiated', function() { let context = stub(); let canvas = stub(); let ball = new Ball({context: context, canvas: canvas}); assert.isObject(ball); assert.equal(ball.x, 275); assert.equal(ball.y, 300); assert.equal(ball.radius, 20); assert.equal(ball.x_speed, 0); assert.equal(ball.y_speed, 5); assert.equal(ball.color, "white"); assert.equal(ball.context, context); }); }); context('with default functions', function() { it('should be instantiated', function() { let context = stub(); let canvas = stub(); let ball = new Ball({context: context, canvas: canvas}); assert.isFunction(ball.render); assert.isFunction(ball.isTouchingSlime); assert.isFunction(ball.bounce); assert.isFunction(ball.isTouchingWall); assert.isFunction(ball.isTouchingGround); assert.isFunction(ball.isTouchingNet); assert.isFunction(ball.isTouchingCeiling); assert.isFunction(ball.resetAfterPoint); assert.isFunction(ball.setSpeed); }); }); }); describe('Render', function() { context('Ball should be rendered', function() { it('it appears on screen', function() { let context = stub().of('beginPath').of('arc').of('fill'); let ball = new Ball({context: context}); assert.equal(ball.context.arc.calls.length, 0); ball.render(); assert.equal(ball.context.arc.calls.length, 1); assert.equal(ball.context.arc.calls[0][0], ball.x); assert.equal(ball.context.arc.calls[0][1], ball.y); assert.equal(ball.context.arc.calls[0][2], ball.radius); assert.equal(ball.context.arc.calls[0][3], (Math.PI * 2)); assert.equal(ball.context.arc.calls[0][4], false); }); it('it moves on screen', function() { let context = stub().of('beginPath').of('arc').of('fill'); let ball = new Ball({context: context}); assert.equal(ball.y, 300); ball.movement(); assert.equal(ball.y, 305.8); assert.equal(ball.x, 275); }); it('it sets speed', function() { let context = stub().of('beginPath').of('arc').of('fill'); let ball = new Ball({context: context}); assert.equal(ball.y_speed, 5); ball.difficulty = "insane"; ball.setSpeed("insane"); assert.equal(ball.y_speed, 25); ball.difficulty = "normal"; ball.setSpeed("normal"); assert.equal(ball.y_speed, 5); }); it('it resets after point', function() { let context = stub().of('beginPath').of('arc').of('fill'); let ball = new Ball({context: context}); ball.y = 400; ball.x_speed = 19; ball.resetAfterPoint("normal"); assert.equal(ball.y_speed, 5); assert.equal(ball.y, 300); assert.equal(ball.x_speed, 0); }); it("it knows it's touching the ceiling", function() { let context = stub().of('beginPath').of('arc').of('fill'); let ball = new Ball({context: context}); ball.y = -100; assert.notStrictEqual(ball.isTouchingCeiling, true); }); it("it knows it's touching the net", function() { let context = stub().of('beginPath').of('arc').of('fill'); let ball = new Ball({context: context}); ball.y = 800; ball.x = 550; assert.notStrictEqual(ball.isTouchingNet, true); }); it("it knows it's touching the ground", function() { let context = stub().of('beginPath').of('arc').of('fill'); let ball = new Ball({context: context}); ball.y = 800; assert.notStrictEqual(ball.isTouchingNet, true); }); it("it knows it's touching the wall", function() { let context = stub().of('beginPath').of('arc').of('fill'); let ball = new Ball({context: context}); ball.x = 1100; assert.notStrictEqual(ball.isTouchingNet, true); }); it("it knows it's touching slime", function() { let context = stub().of('beginPath').of('arc').of('fill'); let ball = new Ball({context: context}); ball.x = 225; ball.y = 800; assert.notStrictEqual(ball.isTouchingNet, true); }); }); });
import request from '@/utils/request' // 仓库列表 export function warehousesList(data) { return request({ url: 'warehouses', method: 'get', params: data }) } // 仓库详情 export function warehousesInfo(id) { return request({ url: 'warehouses/' + id, method: 'get' }) } // 仓库添加 export function warehousesAdd(data) { return request({ url: 'warehouses', method: 'post', data: data }) } // 仓库修改 export function warehousesModify(id, data) { return request({ url: 'warehouses/' + id, method: 'put', data: data }) } // 仓库删除 export function warehousesDel(id) { return request({ url: 'warehouses/' + id, method: 'delete' }) } // 供应商列表 export function suppliersList(data) { return request({ url: 'suppliers', method: 'get', params: data }) } // 供应商添加 export function suppliersAdd(data) { return request({ url: 'suppliers', method: 'post', data: data }) } // 供应商修改 export function suppliersModify(id, data) { return request({ url: 'suppliers/' + id, method: 'put', data: data }) } // 供应商详情 export function suppliersInfo(id) { return request({ url: 'suppliers/' + id, method: 'get' }) } // 供应商删除 export function suppliersDel(id) { return request({ url: 'suppliers/' + id, method: 'delete' }) } // 采购单列表 export function purchaseList(data) { return request({ url: 'warehouse-purchases', method: 'get', params: data }) } // 采购单详情 export function purchaseInfo(id) { return request({ url: 'warehouse-purchases/' + id, method: 'get' }) } // 采购单添加 export function purchaseAdd(data) { return request({ url: 'warehouse-purchases', method: 'post', data: data }) } // 采购单修改 export function purchaseModify(id, data) { return request({ url: 'warehouse-purchases/' + id, method: 'put', data: data }) } // 付款单列表 export function paysList(data) { return request({ url: 'warehouse-purchase-pays', method: 'get', params: data }) } // 获取单个付款单 export function singlepaysList(id, data) { return request({ url: 'warehouse-purchase-pays/' + id, method: 'get', params: data }) } // 付款单添加 export function AddpaysList(data) { return request({ url: 'warehouse-purchase-pays', method: 'post', data: data }) } // 付款单修改 export function modifypaysList(id, data) { return request({ url: 'warehouse-purchase-pays/' + id, method: 'put', data: data }) } // 采购单.支付完毕 export function Paymentcomplete(id, data) { return request({ url: 'warehouse-purchases/' + id + '/pay-complete', method: 'put', data: data }) } // 仓库.位置.批量添加 export function CwarehouseAdd(id, data) { return request({ url: 'warehouses/' + id + '/batch-positions', method: 'post', data: data }) } // 仓库.位置列表 export function Locationlist(id, data) { return request({ url: 'warehouses/' + id + '/positions', method: 'get', params: data }) } // 仓库.库存信息 export function warehouseInventories(data) { return request({ url: 'warehouse-inventories', method: 'get', params: data }) } // 仓库.出库信息 export function warehouseOutbounds(data) { return request({ url: 'warehouse-outbounds', method: 'get', params: data }) } // 仓库.出库信息*添加 export function warehouseOutboundsAdd(data) { return request({ url: 'warehouse-outbounds', method: 'post', data: data }) } // 仓库.入库单.列表 export function warehouseReceipts(data) { return request({ url: 'warehouse-receipts', method: 'get', params: data }) } // 仓库.位置.批量删除 export function LocationDel(id, data) { return request({ url: 'warehouses/' + id + '/batch-positions', method: 'delete', params: data }) } // 仓库.入库单.添加 export function warehouseReceiptsAdd(data) { return request({ url: 'warehouse-receipts', method: 'post', data: data }) } // 仓库.位置.批量添加 export function warelocalAll(id, data) { return request({ url: 'warehouses/' + id + '/batch-positions', method: 'post', data: data }) } // 仓库.位置列表 export function waregetlocallist(id, data) { return request({ url: 'warehouses/' + id + '/positions', method: 'get', params: data }) } // 采购单.审核 export function warehousePurchasesReview(id, data) { return request({ url: 'warehouse-purchases/' + id + '/review', method: 'put', params: data }) } // 仓库.库存信息导出 export function warehousereport(data) { return request({ url: 'warehouse-inventories-report', method: 'get', params: data, responseType: 'blob' }) } // 仓库.库存信息.根据商品归类 export function warehousegroup(data) { return request({ url: 'warehouse-inventories-group', method: 'get', params: data }) } // 仓库.库存信息.根据仓库区分组 export function warehousegroupclass(data) { return request({ url: 'warehouse-inventories-group-warehouse', method: 'get', params: data }) } // 采购单.收货完毕 export function purchaseover(id, data) { return request({ url: `warehouse-purchases/${id}/receive-complete`, method: 'put', data: data }) } // 采购单.获取数量 export function warehousePurchasesCount() { return request({ url: 'warehouse-purchases-count', method: 'get' }) } // 仓库.入库单.入库 export function receiptsinventory(id, data) { return request({ url: 'warehouse-receipts/' + id + '/inventory', method: 'post', data: data }) } // 仓库.出库信息.审核 export function warehouseOutboundReview(id, data) { return request({ url: 'warehouse-outbounds/' + id + '/review', method: 'put', data: data }) } // 入库单.导出 export function warehouseReceiptsExport(data) { return request({ url: 'warehouse-receipts-export', method: 'get', params: data, responseType: 'blob' }) } // 出库单.导出Issue Note export function warehouseOutboundsExport(data) { return request({ url: 'warehouse-outbounds-export', method: 'get', params: data, responseType: 'blob' }) } // 出库单.导出Delivery Note export function warehouseDeliveryNoteExport(data) { return request({ url: 'warehouse-outbounds-export-deliverynote', method: 'get', params: data, responseType: 'blob' }) } // 出库单.导出Express Note export function warehouseExpressNote(data) { return request({ url: 'warehouse-outbounds-export-expressnote', method: 'get', params: data, responseType: 'blob' }) } // 采购单.导出 export function warehousePurchasesExport(data) { return request({ url: 'warehouse-purchases-export', method: 'get', params: data, responseType: 'blob' }) } // 库存.合并 export function warehouseInventMerge(data) { return request({ url: 'warehouse-inventories/merge', method: 'post', data: data }) }
const express = require("express"); const router = express.Router(); const getNextLevelOneScan = require("../library/getNextLevelOneScan"); /** * Express.js router for /findNextLevelOneScan * Return scan number of next level one scan with given scan number. */ let findNextLevelOneScan = router.get('/findNextLevelOneScan', function (req, res) { console.log("Hello, findNextLevelOneScan!"); const projectDir = req.query.projectDir; const scan = req.query.scanID; getNextLevelOneScan(projectDir, scan, function (err, row) { if (row !== undefined) { res.write(row.scan.toString()); res.end(); }else { res.write("0"); res.end(); } }); }); module.exports = findNextLevelOneScan;
'use strict'; var http = require('http'), fs = require('fs'), World = require('./src/world'), WebSocket = require('ws'), RockMUD = function(port, cfg, callback) { this.port = port; this.server = null; this.running = false; this.setup(cfg, callback); }; RockMUD.prototype.setup = function(cfg, callback) { var mud = this; mud.server = http.createServer(function (req, res) { if (req.url === '/' || req.url === '/index.html' || req.url === '/design.html') { if (req.url === '/') { req.url = '/index.html'; } fs.readFile('./public' + req.url, function (err, data) { if (err) { throw err; } res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); res.end(); }); } else if (req.url === '/styles.css') { fs.readFile('./public/css/styles.css', function (err, data) { if (err) { throw err; } res.writeHead(200, {'Content-Type': 'text/css'}); res.write(data); res.end(); }); } else if (req.url === '/bootstrap.css') { fs.readFile('./public/css/bootstrap.min.css', function (err, data) { if (err) { throw err; } res.writeHead(200, {'Content-Type': 'text/css'}); res.write(data); res.end(); }); } else if (req.url === '/rockmud-client.js') { fs.readFile('./public/js/rockmud-client.js', function (err, data) { if (err) { throw err; } res.writeHead(200, {'Content-Type': 'text/javascript'}); res.write(data); res.end(); }); } else if (req.url === '/bg.jpg') { fs.readFile('./public/images/terminal_bg.jpg', function (err, data) { if (err) { throw err; } res.writeHead(200, { 'Cache-Control': 'public, max-age=85400', 'Expires': new Date(Date.now() + 2592000000).toUTCString(), 'Content-Type': 'image/jpeg' }); res.write(data); res.end(); }); } else if (req.url === '/favicon.ico') { res.writeHead(200); res.write(''); res.end(); } }); var nextWorld = new World(new WebSocket.Server({ server: mud.server }), cfg, function(newWorld) { mud.world = newWorld; // newWorld.setup(newWorld, new WebSocket.Server({ server: mud.server }), cfg, function(updatedWorld) { if (!callback) { mud.server.listen(process.env.PORT || mud.port); } mud.running = true; mud.world.io.on('connection', function connection (s) { var parseCmd = function(r, s) { var skillObj, cmdObj, valid = false; if (r.msg) { var roomObj = mud.world.getRoomObject(s.player.area, s.player.roomid); cmdObj = mud.world.commands.createCommandObject(r, s.player, roomObj, true); if (!s.player.creationStep) { valid = mud.world.isSafeCommand(cmdObj); if (valid) { if (cmdObj.cmd) { if (cmdObj.cmd in mud.world.commands) { mud.world.addCommand(cmdObj, s.player); } else if (cmdObj.cmd in mud.world.skills) { skillObj = mud.world.character.getSkill(s.player, cmdObj.cmd); if (skillObj && s.player.wait === 0) { cmdObj.skill = skillObj; mud.world.addCommand(cmdObj, s.player); } else { if (!skillObj) { mud.world.msgPlayer(s, { msg: 'You do not know how to ' + cmdObj.cmd + '.', styleClass: 'error' }); } else { mud.world.msgPlayer(s, { msg: '<strong>You can\'t do that yet!</strong>', styleClass: 'warning' }); } } } else { mud.world.msgPlayer(s, { msg: cmdObj.cmd + ' is not a valid command.', styleClass: 'error' }); } } else { return mud.world.msgPlayer(s, { onlyPrompt: true }); } } else { return mud.world.msgPlayer(s, { onlyPrompt: true }); } } else { mud.world.character.newCharacter(s, cmdObj); } } else if (!s.player.creationStep) { return mud.world.msgPlayer(s, { onlyPrompt: true }); } }, charNameStr = 'Character Name: '; mud.world.msgPlayer(s, { msg : charNameStr, evt: 'reqInitialLogin', styleClass: 'enter-name', noPrompt: true }); s.on('pong', function() { s.player.connected = true; }); s.on('message', function (r) { r = JSON.parse(r); if (r.msg !== '' && !s.player || s.player && !s.player.logged) { if (!s.player || !s.player.verifiedName) { mud.world.character.login(r, s, function (s) { if (s.player) { s.player.verifiedName = true; mud.world.msgPlayer(s, { msg: 'Password for ' + s.player.displayName + ': ', evt: 'reqPassword', noPrompt: true }); } else { s.player = JSON.parse(JSON.stringify(mud.world.entityTemplate)); s.player.name = r.msg; s.player.displayName = s.player.name[0].toUpperCase() + s.player.name.slice(1); s.player.connected = true; s.player.socket = s; s.player.creationStep = 1; s.player.isPlayer = true; s.player.logged = true; parseCmd(r, s); } }) } else if (r.msg && s.player && !s.player.verifiedPassword) { mud.world.character.getPassword(s, mud.world.commands.createCommandObject(r), function(s) { s.player.verifiedPassword = true; s.player.logged = true; mud.world.commands.look(s.player); // we auto fire the look command on login }); } else { mud.world.msgPlayer(s, { msg : charNameStr, noPrompt: true, styleClass: 'enter-name' }); } } else if (s.player && s.player.logged === true) { parseCmd(r, s); } else { mud.world.msgPlayer(s, { msg : 'Please enter a character name:', noPrompt: true, styleClass: 'enter-name' }); } }); s.on('close', function () { var i = 0, j = 0, roomObj; if (s.player !== undefined) { s.player.connected = false; mud.world.character.removePlayer(s.player); } }); }); if (callback && typeof callback === 'function') { callback(); } // }); }); } module.exports = RockMUD;
var path = require("path"); var db = require("../models") var isAuthenticated = require("../config/middleware/isAuthenticated"); function getPageTitle(page) { return 'RulEr | ' + page; } function redirectOnError(res, previousPage, message) { res.render("error", { previous_page: previousPage, error_message: message }) } module.exports = function(app) { app.get("/", function(req, res) { // If the user already has an account send them to the dashboard page if (req.user) { res.redirect("/dashboard"); } else { res.redirect('/login'); } }); app.get("/signup", function(req, res) { // Check the query string // In order for parent to be recognized, they must already be in the system // When teacher adds student, the parent will be entered in the db because they are associated with the student // Therefore, teacher must have added their student before parent can sign up if (req.query.occupation === "TEACHER") { res.render('signup', { layout: 'login', title: getPageTitle('Sign Up'), isTeacher: true, }); } else { db.Parent.findAll().then(parents => { // console.log(parents); res.render('signup', { layout: 'login', title: getPageTitle('Sign Up'), isTeacher: false, parents: parents }); }); } }); app.get("/login", function(req, res) { // If the user already has an account send them to the members page if (req.user) { res.redirect("/dashboard"); } res.render('login', { layout: 'login', title: getPageTitle('Login') }); }); app.get("/calendar", isAuthenticated, function(req, res) { res.render('calendar', { title: getPageTitle('Calendar') }) }); app.get("/addStudent", isAuthenticated, function(req, res) { // get all parents const teacherId = req.query.teacher_id; db.Parent.findAll().then(parents => { res.render('addStudent', { title: getPageTitle('Add New Student'), teacher_id: teacherId, parents: parents }); }).catch(err => { redirectOnError(res, "/dashboard", err.message); }); }) app.post("/addStudent", isAuthenticated, function(req, res) { console.log(req.body) const teacherId = parseInt(req.body.teacher_id); const studentName = req.body.student_name; // find Parent by parent_name db.Parent.findOrCreate({ where: { parent_name: req.body.parent } }).then(([parent, created]) => { return db.Student.create({ student_name: studentName, ParentId: parent.id, TeacherId: teacherId }); }).then(() => { res.redirect('/dashboard') }).catch(err => { redirectOnError(res, "/dashboard", err.message); }) }) app.get("/dashboard", isAuthenticated, function(req, res) { console.log(req.user); if (req.user.occupation === "TEACHER") { // get all students from teacher_id db.Teacher.findOne({ where: { UserId: req.user.id } }).then(function(teacher) { db.Student.findAll({ where: { TeacherId: teacher.id } }).then(function(students) { return Promise.all(students.map(student => student.getPosts())) // posts is an array of arrays of Posts .then(posts => { const studentsWithComments = students.map((student, i) => { return { student_name: student.student_name, id: student.id, comments: posts[i].map(post => { return { date: post.createdAt.toDateString(), comment: post.comment } }) }; }) res.render('dashboard', { title: getPageTitle('Dashboard'), isTeacher: true, name: teacher.teacher_name, teacher_id: teacher.id, students: studentsWithComments }); }).catch(err => { console.log(err.message) redirectOnError(res, "/dashboard", err.message) }) }); }).catch(function(err) { redirectOnError(res, "/dashboard", err.message); }); } else if (req.user.occupation === "PARENT") { // get all students from parent_id db.Parent.findOne({ where: { UserId: req.user.id } }).then(function(parent) { db.Student.findAll({ where: { ParentId: parent.id } }).then(function(students) { return Promise.all(students.map(student => student.getPosts())) // posts is an array of arrays of Posts .then(posts => { const studentsWithComments = students.map((student, i) => { return { student_name: student.student_name, id: student.id, comments: posts[i].map(post => { return { date: post.createdAt.toDateString(), comment: post.comment } }) }; }); res.render('dashboard', { title: getPageTitle('Dashboard'), isTeacher: false, name: parent.parent_name, parent_id: parent.id, students: studentsWithComments }); }) }); }).catch(function(err) { redirectOnError(res, "/dashboard", err.message); }) } else { redirectOnError(res, "/dashboard", `Occupation ${req.body.occupation} is not a valid occupation!`) } }) //page to add a student comment app.get("/addComment", isAuthenticated, function(req, res) { const teacherId = req.query.teacher_id; db.Student.findAll().then(students => { res.render('addComment', { title: getPageTitle('Add Comment'), students: students, teacher_id: teacherId }); }).catch(err => { redirectOnError(res, "/dashboard", err.message); }); }) }
const assert = require('assert'); const fs = require('fs'); const BitmapHeader = require('../lib/bitmap-header.js'); const BitmapTransformer = require('../lib/bitmap-transformer.js'); describe('inverts colors in a bitmap', () => { let buffer = null; before(done => { fs.readFile('./non-palette-bitmap-test.bmp', (err, _buffer) => { if(err) done(err); else { buffer = _buffer; done(); } }); }); it('gives correct header data', () => { const bmHeader = new BitmapHeader(buffer); assert.equal(bmHeader.pixelOffset, 54); assert.equal(bmHeader.bitsPerPixel, 24); assert.equal(bmHeader.fileSize, 30054); assert.equal(bmHeader.isPaletted, false); }) it('checks the invert function', () => { const bitMap = new BitmapTransformer(buffer); const color = { r: 155, g: 155, b: 155, } const newColor = bitMap.invert(color); assert.deepEqual(newColor, {r: 100, g: 100, b: 100}); }); it('transforms the file', done => { var bitMap = new BitmapTransformer(buffer); bitMap.transform(); // fs.writeFile('./inverted.bmp', bitMap.buffer, (err) => { // done(err); // }) fs.readFile('./inverted.bmp', (err, buffer) =>{ assert.deepEqual(bitMap.buffer, buffer); done(err); }); }); });
// Copyright (C) 2020 to the present, Crestron Electronics, Inc. // All rights reserved. // No part of this software may be reproduced in any form, machine // or natural, without the express written consent of Crestron Electronics. // Use of this source code is subject to the terms of the Crestron Software License Agreement // under which you licensed this source code. /* global WebXPanel, translateModule*/ var webXPanelModule = (function () { "use strict"; const config = { "host": "", "port": 49200, "roomId": "", "ipId": "", "tokenSource": "", "tokenUrl": "" }; const RENDER_STATUS = { success: 'success', error: 'error', warning: 'warning', hide: 'hide', loading: 'loading' }; var WARN_DAYS_BEFORE = 0; var status; var header, appVer, params; var pcConfig = config; var urlConfig = config; var isDisplayHeader = false; var isDisplayInfo = false; /** * Function to set status bar current state - hidden being default * @param {*} classNameToAdd */ function setStatus(classNameToAdd = RENDER_STATUS.hide) { if (!isDisplayHeader) { return; } let preloader = document.getElementById('pageStatusIdentifier'); if (preloader) { preloader.className = classNameToAdd; } } /** * Get WebXPanel configuration present in project-config.json */ function getWebXPanelConfiguration(projectConfig) { if (projectConfig.config && projectConfig.config.controlSystem) { pcConfig.host = projectConfig.config.controlSystem.host || ""; pcConfig.port = projectConfig.config.controlSystem.port || ""; pcConfig.roomId = projectConfig.config.controlSystem.roomId || ""; pcConfig.ipId = projectConfig.config.controlSystem.ipId || ""; pcConfig.tokenSource = projectConfig.config.controlSystem.tokenSource || ""; pcConfig.tokenUrl = projectConfig.config.controlSystem.tokenUrl || ""; // if undefined, assign 60 days as default WARN_DAYS_BEFORE = projectConfig.config.controlSystem.licenseExpirationWarning || 60; } } /** * Get the url params if defined. */ function getWebXPanelUrlParams() { let urlString = window.location.href; let urlParams = new URL(urlString); // default host should be the IP address of the PC urlConfig.host = urlParams.searchParams.get("host") || pcConfig.host; urlConfig.port = urlParams.searchParams.get("port") || pcConfig.port; urlConfig.roomId = urlParams.searchParams.get("roomId") || pcConfig.roomId; urlConfig.ipId = urlParams.searchParams.get("ipId") || pcConfig.ipId; urlConfig.tokenSource = urlParams.searchParams.get("tokenSource") || pcConfig.tokenSource; urlConfig.tokenUrl = urlParams.searchParams.get("tokenUrl") || pcConfig.tokenUrl; } /** * Set the listeners for WebXPanel */ function setWebXPanelListeners() { // A successful WebSocket connection has been established WebXPanel.default.addEventListener(WebXPanel.WebXPanelEvents.CONNECT_WS, (event) => { updateInfoStatus("app.webxpanel.status.CONNECT_WS"); }); WebXPanel.default.addEventListener(WebXPanel.WebXPanelEvents.DISCONNECT_CIP, (msg) => { updateInfoStatus("app.webxpanel.status.DISCONNECT_CIP"); displayConnectionWarning(); }); WebXPanel.default.addEventListener(WebXPanel.WebXPanelEvents.ERROR_WS, (msg) => { updateInfoStatus("app.webxpanel.status.ERROR_WS"); displayConnectionWarning(); }); WebXPanel.default.addEventListener(WebXPanel.WebXPanelEvents.AUTHENTICATION_FAILED, (msg) => { updateInfoStatus("app.webxpanel.status.AUTHENTICATION_FAILED"); displayConnectionWarning(); }); WebXPanel.default.addEventListener(WebXPanel.WebXPanelEvents.AUTHENTICATION_REQUIRED, (msg) => { updateInfoStatus("app.webxpanel.status.AUTHENTICATION_REQUIRED"); displayConnectionWarning(); }); WebXPanel.default.addEventListener(WebXPanel.WebXPanelEvents.CONNECT_CIP, (msg) => { setStatus(RENDER_STATUS.success); removeConnectionWarning(); // Hide the bar after 10 seconds setTimeout(() => { setStatus(RENDER_STATUS.hide); }, 10000); updateInfoStatus("app.webxpanel.status.CONNECT_CIP"); let connectInfo = `<span>CS: ${msg.detail.url}</span>` + `<span>IPID: ${Number(msg.detail.ipId).toString(16)}</span>`; // Show roomId in info when it is not empty if (msg.detail.roomId !== "") { connectInfo += `<span>Room Id: ${msg.detail.roomId}</span>`; } if (isDisplayInfo) { document.getElementById("webXPnlParams").innerHTML = connectInfo; } }); // Display License errors WebXPanel.default.addEventListener(WebXPanel.WebXPanelEvents.LICENSE_WS, ({ detail }) => { updateDialogLicenseInfo(detail); }); function updateDialogLicenseInfo(detail) { const controlSystemSupportsLicense = detail.controlSystemSupportsLicense; // boolean const licenseApplied = detail.licenseApplied; // optional boolean const licenseDaysRemaining = detail.licenseDaysRemaining; // optional number const licenseHasExpiry = detail.licenseHasExpiry; // optional boolean const trialPeriod = detail.trialPeriod; // optional boolean const trialPeriodDaysRemaining = detail.trialPeriodDaysRemaining; // optional number const resourceAvailable = detail.resourceAvailable; // boolean let licenseMessage = ""; if (!controlSystemSupportsLicense) { licenseMessage = translateModule.translateInstant("app.webxpanel.license.csmobilitysupport"); } else if (!resourceAvailable) { licenseMessage = translateModule.translateInstant("app.webxpanel.license.mobilitylicenserequired"); } else if (licenseApplied) { if (!licenseHasExpiry) { licenseMessage = translateModule.translateInstant("app.webxpanel.license.mobilitylicensevalid"); } else { // Display warning displayLicenseWarning(WARN_DAYS_BEFORE, licenseDaysRemaining); licenseMessage = translateModule.translateInstant("app.webxpanel.license.mobilitylicensewarning", { licenseDaysRemaining }); const updatedDetail = detail; updatedDetail.licenseDaysRemaining = licenseDaysRemaining - 1; setTimeout(updateDialogLicenseInfo, 24 * 60 * 60 * 1000, updatedDetail); } } else if (trialPeriod) { licenseMessage = translateModule.translateInstant("app.webxpanel.license.mobilitylicensetrial", { trialPeriodDaysRemaining }); // Display warning displayLicenseWarning(WARN_DAYS_BEFORE, trialPeriodDaysRemaining); const updatedDetail = detail; updatedDetail.trialPeriodDaysRemaining = trialPeriodDaysRemaining - 1; setTimeout(updateDialogLicenseInfo, 24 * 60 * 60 * 1000, updatedDetail); } if(isDisplayInfo) { const licenseText = document.getElementById("webXPnlLicense"); licenseText.textContent = licenseMessage; } } // Authorization WebXPanel.default.addEventListener(WebXPanel.WebXPanelEvents.NOT_AUTHORIZED, ({ detail }) => { const redirectURL = detail.redirectTo; updateInfoStatus("app.webxpanel.status.NOT_AUTHORIZED"); setTimeout(() => { console.log("redirecting to " + redirectURL); window.location.replace(redirectURL); }, 3000); }); } /** * Update info status if Info icon is enabled */ function updateInfoStatus(statusMessageKey) { let statusMsgPrefix = translateModule.translateInstant("app.webxpanel.statusmessageprefix"); let statusMessage = translateModule.translateInstant(statusMessageKey); if (statusMessage) { let sMsg = statusMsgPrefix + statusMessage; if (isDisplayInfo) { status.innerHTML = sMsg; } else { console.log(sMsg); } } } /** * Show the badge on the info icon for connection status. */ function displayConnectionWarning() { if (!isDisplayInfo) { return; } let classArr = document.getElementById("infobtn").classList; if (classArr) { classArr.add("warn"); } } /** * Remove the badge on the info icon. */ function removeConnectionWarning() { if (!isDisplayInfo) { return; } let classArr = document.getElementById("infobtn").classList; if (classArr) { classArr.remove("warn"); } } /** * Show the badge on the info icon for license expiry warning. */ function displayLicenseWarning(warnDays, remainingDays) { if (!isDisplayInfo) { return; } // 0 means no license warning messages if (WARN_DAYS_BEFORE !== 0) { if (warnDays >= remainingDays) { let classArr = document.getElementById("infobtn").classList; if (classArr) { classArr.add("warn"); } } else { return false; } } } /** * Show WebXPanel connection status */ function webXPanelConnectionStatus() { //Display the connection animation on the header bar setStatus(RENDER_STATUS.loading); // Hide the animation after 30 seconds setTimeout(() => { setStatus(RENDER_STATUS.hide); }, 30000); } /** * Connect to the control system through websocket connection. * Show the status in the header bar using CSS animation. * @param {object} projectConfig */ function connectWebXPanel(projectConfig) { let connectParams = config; let ver = WebXPanel.getVersion(); let bdate = WebXPanel.getBuildDate(); isDisplayHeader = projectConfig.header.display; isDisplayInfo = projectConfig.header.displayInfo; if (isDisplayInfo) { document.getElementById("versionDetails").style.display = 'block'; // Show the style header = document.getElementById("webXPnlHdr").innerHTML = `WebXPanel Version: ${ver}<span>Build date: ${bdate}</span>`; appVer = document.getElementById("webXPnlVer"); status = document.getElementById("webXPnlStatus"); params = document.getElementById("webXPnlParams"); } webXPanelConnectionStatus(); // Merge the configuration params, params of the URL takes precedence getWebXPanelConfiguration(projectConfig); getWebXPanelUrlParams(); // Assign the combined configuration connectParams = urlConfig; connectParams.host + connectParams.ipId WebXPanel.default.initialize(connectParams); updateInfoStatus("app.webxpanel.status.CONNECT_WS"); let connectInfo = `<span>CS: wss://${connectParams.host}:${connectParams.port}/</span>` + `<span>IPID: ${Number(connectParams.ipId).toString(16)}</span>`; // Show roomId in info when it is not empty if (connectParams.roomId !== "") { connectInfo += `<span>Room Id: ${connectParams.roomId}</span>`; } if (isDisplayInfo) { document.getElementById("webXPnlParams").innerHTML = connectInfo; } // WebXPanel listeners are called in the below method setWebXPanelListeners(); } /** * Initialize WebXPanel */ function connect(projectConfig) { // Connect only in browser environment if (!WebXPanel.isActive) { return; } else { connectWebXPanel(projectConfig); } } /** * All public method and properties exporting here */ return { connect }; })();
septageLogger.controller('LoginCtrl',['$scope', '$location', 'loginService', 'userService', function($scope, $location, loginService, userService){ $scope.showMessage = false; $scope.sendLogin = function(){ loginService.login($scope.login.username.toLowerCase(), $scope.login.password) .then(function(data){ //console.log("login good"); $scope.loginResult = ""; $scope.login.password = ""; //a test $scope.loginStatus = true; $scope.showMessage = true; $scope.loginResult = 'Success, redirecting . . .'; userService.getUser($scope.login.username.toLowerCase()) .then(function(data){ $scope.username = data.data.username; $scope.accountType = data.data.type; if ($scope.accountType !== 'driver'){ $location.url("/user/"+$scope.login.username.toLowerCase()+'#scrollhere'); } else { $location.url("/driver/"+$scope.login.username.toLowerCase()); } }, function(error){ console.log("problem"); }); }, function(error){ console.log("login bad"); console.log(error); $scope.login.username = ""; $scope.login.password = ""; $scope.loginStatus = false; $scope.showMessage = true; $scope.loginResult = error.data.message; }); }; }]);
import React, {Component} from 'react'; import ReactDOM from 'react-dom'; import {Router} from 'react-router-dom'; import {Dimmer, Loader} from 'semantic-ui-react'; import Store from './Store'; import Routes from './Routes'; import Header from './Components/Header'; import Footer from './Components/Footer'; export default class App extends Component { render() { return ( <Store.Provider> <Store.Consumer> { (state) => { return state.loaded ? <Router history={state.history}> <div> <Header/> <Routes/> <Footer/> </div> </Router> : <Dimmer active> <Loader>Loading</Loader> </Dimmer> } } </Store.Consumer> </Store.Provider> ); } } if (document.getElementById('app')) { ReactDOM.render(<App/>, document.getElementById('app')); }
/* * Module code goes here. Use 'module.exports' to export things: * module.exports.thing = 'a thing'; * * You can import it from another modules like this: * var mod = require('role.war.wallBreaker'); * mod.thing == 'a thing'; // true */ murderer = { pickup: function(creep) { if(creep.memory.fighting && creep.hits < 2000) { creep.memory.fighting = false; } if(!creep.memory.fighting && creep.hitsMax == creep.hits) { creep.memory.fighting = true; } if(creep.memory.fighting && creep.pos.roomName == Game.flags.trenches.pos.roomName) { // //Break the first wall var hurtThis = creep.room.find(FIND_HOSTILE_CREEPS); console.log(hurtThis); // //Break the second wall // if(hurtThis.length == 0) { // hurtThis = creep.room.lookForAt(LOOK_STRUCTURES, Game.flags.entrypoint2); // } //Break their spawn // if(hurtThis.length == 0) { // hurtThis = creep.room.find(FIND_HOSTILE_CREEPS); // } if(hurtThis.length != 0) { hurtThis = hurtThis[0]; if(creep.rangedAttack(hurtThis) == ERR_NOT_IN_RANGE){ creep.moveTo(hurtThis); } else { console.log("attacking " + hurtThis); } } } else { creep.moveTo(Game.flags.trenches); } } } module.exports = murderer;
// for the map var markers;//历史线路上的标注 var marker; var marker1;//汽车位置临时标注 var lat0=100;//纬度最大不超过90 var lng0=200;//经度最大不超过180 var timeOut = 500; // length to wait till next point is plotted var i = 0; var currentCheckPoint = 0;//当前标注点 var checkPoints = new Array();//所有标注点 // for display var loadingMessage; var distanceMessage; var speedMessage; var timeMessage; var checkPointCount = 1; // for distance calculations var distance = 0; var checkPoint; var checkPointDistance = 0; var latMax = 0; var latMin = 0; var longMax = 0; var longMin = 0; var latSum = 0; var longSum = 0; var coordinateCount = 0; var lastMileMinutes1;//上一英里耗时 // for time calculations var totalTime = 0; var startTime = 0; var timeSpan=0;//已耗时间 var enabled = 0;//设定是否自动刷新当前汽车位置 var searchOverlayTree; var dynamicOverlayTreeNode,tempTreeNode,kmlFileOverlayTreeNode; //var dynamicOverlay=new K_DynamicOverlay("K_Reverter.kml"); var imageOverlay; //一组google提供的ICON var baseIcon = new GIcon(); baseIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png"; baseIcon.iconSize = new GSize(12, 20); baseIcon.shadowSize = new GSize(22, 20); baseIcon.iconAnchor = new GPoint(6, 10); baseIcon.infoWindowAnchor = new GPoint(5, 1); icon_Green= new GIcon(baseIcon); icon_Green.image = "http://labs.google.com/ridefinder/images/mm_20_green.png"; icon_Blue= new GIcon(baseIcon); icon_Blue.image = "http://labs.google.com/ridefinder/images/mm_20_blue.png"; icon_Red= new GIcon(baseIcon); icon_Red.image = "http://labs.google.com/ridefinder/images/mm_20_red.png"; //自定义的汽车图标 icon_car=new GIcon(); icon_car.image='car.gif'; icon_car.iconSize=new GSize(20,20); icon_car.iconAnchor = new GPoint(10,10); icon_car.infoWindowAnchor=new GPoint(10,10); function onLoad() { loadingMessage = document.getElementById('progress'); distanceMessage = document.getElementById('distanceMessage'); speedMessage = document.getElementById("speedMessage"); timeMessage = document.getElementById('timeMessage'); var file = getFileName(); if (file) { loadInfo(); } } function K_GetQueryString(key) { var returnValue =""; var sURL = window.document.URL; if (sURL.indexOf("?") > 0) { var arrayParams = sURL.split("?"); var arrayURLParams = arrayParams[1].split("&"); for (var j = 0; j < arrayURLParams.length; j++) { var sParam = arrayURLParams[j].split("="); if ((sParam[0] ==key) && (sParam[1] != "")) returnValue=sParam[1]; } } return returnValue; } function CreateMarker1(point,icon,html) { marker = new GMarker(point,icon); if(html && html!="") { GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html); } ); } map.addOverlay(marker); return marker; } function showInfo() { var zoom=map.getZoom(); var num=parseInt(Math.log(1/map.spec.pixelsPerLonDegree[zoom])/Math.log(10)); alert(num); var point=map.getCenter(); var px=point.x.toString(); // px=px.substring(0,px.indexOf(".")-num+2); var py=point.y.toString(); // py=py.substring(0,py.indexOf(".")-num+2); document.getElementById("I_Center").value =px+","+py; document.getElementById("I_ZoomLevel").value = zoom; // document.getElementById("I_MapType").value = map.getCurrentMapType().getShortLinkText(); // setMinimapRect(); } function readGPS() { var request = false; var xmlDoc; var point1; var polyline; var lat1; var lng1; var datetime,date,time; request = GXmlHttp.create(); request.open("GET","getXML.php?type=point", true); request.send(null); request.onreadystatechange = function() { if (request.readyState == 4) { if (request.status == 200) { xmlDoc = request.responseXML; lng1=xmlDoc.documentElement.getElementsByTagName("Longitude"); lng1=lng1[0].firstChild.nodeValue; lng1=parseFloat(lng1); lat1=xmlDoc.documentElement.getElementsByTagName("Latitude"); lat1=lat1[0].firstChild.nodeValue; lat1=parseFloat(lat1); if(lng1<-180 || lng1>180) { alert('经度值超过界限'); return; } if(lat1<-90 || lat1>90) { alert('纬度值超过界限'); return; } datetime=xmlDoc.documentElement.getElementsByTagName("Time"); datetime=datetime[0].firstChild.nodeValue; date=datetime.substring(0,10); time=datetime.substring(11,19); if(marker1!=null) { map.removeOverlay(marker1); // map.clearOverlays() } point1=new GPoint(lng1,lat1); map.recenterOrPanToLatLng(point1); if(lng0==200 && lat0==100)//初始位置 { map.centerAndZoom(point1,2);//将起点位置居中,并放大地图到合适等级,设置合适地图类型 CreateMarker1(point1,icon_Red,'起点<br>'+date+'<br>'+time); } else if(lat0!=lat1 || lng0!=lng1)//周期时间内有移动,先创建折线,再添加汽车标识 { polyline = new GPolyline([new GPoint(lng0,lat0),new GPoint(lng1,lat1)], "#0000ff", 3,1); map.addOverlay(polyline); marker1=CreateMarker1(point1,icon_car,'当前时间:<br>'+date+'<br>'+time); } else//周期时间内未移动,只添加汽车标识 { marker1=CreateMarker1(point1,icon_car,'停留<br>'+date+'<br>'+time); } lng0=lng1; lat0=lat1; } } } // window.setTimeout(function(){readGPS();},5000); } function TOfunc() { var space=parseInt(document.clock.space.value); TO = window.setTimeout( "TOfunc()", space ); readGPS(); } function initCheckpoint() { checkPoint = 1 } // LOAD THE XML FILE AND PLOT THE FIRST POINT // function loadInfo() { markers = null; marker = null; var request = GXmlHttp.create(); var fileName = getFileName(); request.open("GET", fileName, true); request.onreadystatechange = function() { if (request.readyState == 4) { var xmlDoc = request.responseXML; markers = xmlDoc.documentElement.getElementsByTagName("Trackpoint"); plotPoint(); } } request.send(null); } function plotPoint() { if (i < markers.length ) { var Lat = markers[i].getElementsByTagName("Latitude"); var Lng = markers[i].getElementsByTagName("Longitude"); Lat = Lat[0].firstChild.nodeValue; Lng = Lng[0].firstChild.nodeValue; if (Lat > latMax) { latMax = Lat; } else if (Lat < latMin) { latMin = Lat; } if (Lng > longMax) { longMax = Lng; } else if (Lng < longMin) { longMin = Lng; } latSum = latSum + Lat; longSum = longSum + Lat; coordinateCount = coordinateCount + 1; var point = new GPoint(Lng,Lat); if (i < markers.length - 1){ window.setTimeout(plotPoint,timeOut); calculateTime(i); averageSpeed = Math.round((distance / (totalTime/3600))*100)/100; var minutesSoFar = totalTime / 60; var currentPace = minutesSoFar / distance; // speedMessage.innerHTML = '每英里耗时:'+displayMinutes(currentPace); speedMessage.innerHTML = '平均速度:'+averageSpeed+'公里/小时 '; } marker = createMarker(point,i,markers.length); if (i < markers.length && i != 0) { var Lat1 = markers[i-1].getElementsByTagName("Latitude"); var Lng1 = markers[i-1].getElementsByTagName("Longitude"); Lat1 = Lat1[0].firstChild.nodeValue; Lng1 = Lng1[0].firstChild.nodeValue; var point1 = new GPoint(Lng1,Lat1); var points=[point, point1]; //RECENTER MAP EVERY TEN POINTS if (i%3==0) { map.recenterOrPanToLatLng(point); } /* if (i < markers.length/2) { map.addOverlay(new GPolyline(points, "#0000ff",3,1)); } else { map.addOverlay(new GPolyline(points, "#ff0000",3,1)); } */ if (lastMileMinutes1 > 10) { map.addOverlay(new GPolyline(points, "#ff0000",3,1)); } else { map.addOverlay(new GPolyline(points, "#0000ff",3,1)); } calculateDistance(Lng, Lat, Lng1, Lat1); } loadingPercentage(i); distanceMessage.innerHTML=Math.round(distance*100)/100 + "公里 "; i++; } } // GET THE APPROPRIATE MARKER FOR START, FINISH, CHECKPOINT, AND LINE function createMarker(point, i, markerLength) { var icon = new GIcon(); icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png"; icon.iconSize = new GSize(24, 38); icon.shadowSize = new GSize(40, 38); icon.iconAnchor = new GPoint(10, 34); icon.infoWindowAnchor = new GPoint(9, 5); if (i == 0 ){ checkPoints[currentCheckPoint] = { timestamp: markers[i].getElementsByTagName('Time')[0].firstChild.nodeValue }; map.centerAndZoom(point, 2); icon.image = "http://labs.google.com/ridefinder/images/mm_20_green.png"; marker = new GMarker(point,icon); map.addOverlay(marker); GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml("开始");}); return marker; } else if(i == markers.length -1){ icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png"; marker = new GMarker(point,icon); map.addOverlay(marker); GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml("结束");}); map.recenterOrPanToLatLng(point, 2000); return marker; } if (checkPointDistance - checkPoint >= 0 && checkPoint != 0){ currentCheckPoint = currentCheckPoint + 1; checkPoints[currentCheckPoint] = { timestamp: markers[i].getElementsByTagName('Time')[0].firstChild.nodeValue }; var thisCheckPointDuration = getTimeBetweenCheckPoints(checkPoints[currentCheckPoint-1].timestamp,checkPoints[currentCheckPoint].timestamp); var thisCheckPoint = currentCheckPoint; var lastMileMinutes = thisCheckPointDuration / 60; var mileTime = displayMinutes(lastMileMinutes); var timeSpan1=timeSpan; lastMileMinutes1=lastMileMinutes; var img_id=thisCheckPoint>39?0:thisCheckPoint; // if (lastMileMinutes < 10) { icon.image = "images/red" + img_id + ".png"; // } else { // icon.image = "images/green" + img_id + ".png"; // } var distance1 = checkPointDistance; marker = new GMarker(point,icon); map.addOverlay(marker); GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml("行程: " + thisCheckPoint + "公里<br>前1公里耗时:" + mileTime+'<br>行驶时间:'+timeSpan1);}); checkPointDistance = 0; checkPointCount += 1; } else { marker = new GMarker(point, icon); } return marker; } function displayMinutes(num_seconds,do_alert) { if (do_alert) { alert("seconds " + num_seconds); } currentPace = num_seconds.toString(); var a = currentPace.split('.'); var myregex = new RegExp("^\\d{1,3}"); var minuteParts = myregex.exec(a[1]); while (minuteParts < 100 && minuteParts != 0) { minuteParts = minuteParts * 10; } if (do_alert) { alert("mintes " + a[0] + " parts " + minuteParts); } var secondsPlace = Math.round(minuteParts/10) * 60 / 100; if (do_alert) { alert("secondsPlace " + secondsPlace); } var displayString = a[0] + "分" + leadingZero(secondsPlace)+'秒'; return displayString; } function leadingZero(x){ return (x>9)?x:'0'+x; } function getTimeBetweenCheckPoints(lastCheckPoint,thisCheckPoint) { var secondsBetween = secondsBetweenDates(lastCheckPoint,thisCheckPoint); return secondsBetween; } // LOADING BAR // function loadingPercentage(currentPoint){ var percentage = Math.round((currentPoint/(markers.length - 1)) * 100); loadingMessage.style.width = percentage +"%"; } // Function based on Vincenty formula // Website referenced: http://www.movable-type.co.uk/scripts/LatLongVincenty.html // Thanks Chris Veness for this! //Also a big thank you to Steve Conniff for taking the time to intruoduce to this more accurate method of calculating distance function calculateDistance(point1y, point1x, point2y, point2x) { // Vincenty formula traveled = LatLong.distVincenty(new LatLong(point2x, point2y), new LatLong(point1x, point1y)); // traveled = traveled * 0.000621371192; // Convert to miles from meters traveled = traveled * 0.001; //转换米到公里 distance = distance + traveled; checkPointDistance = checkPointDistance + traveled; // alert(checkPointDistance); } /* * LatLong constructor: * * arguments are in degrees, either numeric or formatted as per LatLong.degToRad * returned lat -pi/2 ... +pi/2, E = +ve * returned lon -pi ... +pi, N = +ve */ function LatLong(degLat, degLong) { if (typeof degLat == 'number' && typeof degLong == 'number') { // numerics this.lat = degLat * Math.PI / 180; this.lon = degLong * Math.PI / 180; } else if (!isNaN(Number(degLat)) && !isNaN(Number(degLong))) { // numerics-as-strings this.lat = degLat * Math.PI / 180; this.lon = degLong * Math.PI / 180; } else { // deg-min-sec with dir'n this.lat = LatLong.degToRad(degLat); this.lon = LatLong.degToRad(degLong); } } /* * Calculate geodesic distance (in m) between two points specified by latitude/longitude. * * from: Vincenty inverse formula - T Vincenty, "Direct and Inverse Solutions of Geodesics on the * Ellipsoid with application of nested equations", Survey Review, vol XXII no 176, 1975 * http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf */ LatLong.distVincenty = function(p1, p2) { var a = 6378137, b = 6356752.3142, f = 1/298.257223563; var L = p2.lon - p1.lon; var U1 = Math.atan((1-f) * Math.tan(p1.lat)); var U2 = Math.atan((1-f) * Math.tan(p2.lat)); var sinU1 = Math.sin(U1), cosU1 = Math.cos(U1); var sinU2 = Math.sin(U2), cosU2 = Math.cos(U2); var lambda = L, lambdaP = 2*Math.PI; var iterLimit = 20; while (Math.abs(lambda-lambdaP) > 1e-12 && --iterLimit>0) { var sinLambda = Math.sin(lambda), cosLambda = Math.cos(lambda); var sinSigma = Math.sqrt((cosU2*sinLambda) * (cosU2*sinLambda) + (cosU1*sinU2-sinU1*cosU2*cosLambda) * (cosU1*sinU2-sinU1*cosU2*cosLambda)); if (sinSigma==0) return 0; // co-incident points var cosSigma = sinU1*sinU2 + cosU1*cosU2*cosLambda; var sigma = Math.atan2(sinSigma, cosSigma); var alpha = Math.asin(cosU1 * cosU2 * sinLambda / sinSigma); var cosSqAlpha = Math.cos(alpha) * Math.cos(alpha); var cos2SigmaM = cosSigma - 2*sinU1*sinU2/cosSqAlpha; var C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha)); lambdaP = lambda; lambda = L + (1-C) * f * Math.sin(alpha) * (sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM))); } if (iterLimit==0) return NaN // formula failed to converge var uSq = cosSqAlpha * (a*a - b*b) / (b*b); var A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq))); var B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq))); deltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)- B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM))); s = b*A*(sigma-deltaSigma); s = s.toFixed(3); // round to 1mm precision return s; } function secondsBetweenDates(first_date,second_date) { //begin year/month/day var largeDate = second_date.toString().split("T"); var date = largeDate[0]; date = date.split("-"); var beforeYear = date[0]; var beforeDay = date[2]; //beforeDay = beforeDay.replace("0",""); var beforeMonth = date[1]; //beforeMonth = beforeMonth.replace("0",""); //end year/month/day var largeDate1 = first_date.toString().split("T"); var date1 = largeDate1[0]; date1 = date1.split("-"); var afterYear = date1[0]; var afterDay = date1[2]; //afterDay = afterDay.replace("0",""); var afterMonth = date1[1]; //afterMonth = afterMonth.replace("0",""); //begin hour/min/seconds var after = largeDate[1].replace("T",""); after = largeDate[1].replace("Z",""); afterArray = after.split(":"); var hour = afterArray[0]; var minute = afterArray[1]; var second = afterArray[2]; //end hour/min/seconds var after1 = largeDate1[1].replace("T",""); after1 = largeDate1[1].replace("Z",""); afterArray1 = after1.split(":"); var hour1 = afterArray1[0]; var minute1 = afterArray1[1]; var second1 = afterArray1[2]; var before =new Date(beforeYear, beforeMonth, beforeDay, hour, minute, second); var after =new Date(afterYear, afterMonth, afterDay, hour1, minute1, second1); var seconds = 1000; var secondsBetween = Math.ceil((before.getTime()-after.getTime())/(seconds)); return secondsBetween; } function calculateTime(i) { if (startTime == 0) { startTime = markers[0].getElementsByTagName("Time"); startTime = startTime[0].firstChild.nodeValue; } var current_timestamp = markers[i].getElementsByTagName("Time"); current_timestamp = current_timestamp[0].firstChild.nodeValue; var secondsBetween = secondsBetweenDates(startTime,current_timestamp); totalTime = secondsBetween; timeSpan=convertSeconds(secondsBetween); timeMessage.innerHTML='已行驶时间:'+timeSpan; } function convertSeconds(seconds) { //find hours if(seconds > 3600) { hours = Math.round(((seconds / 3600)*10)/10) - Math.round((((seconds % 3600)*10)/3600)/10); seconds = seconds - (hours * 3600); hours += "小时"; } else { hours = ""; } //find minutes if(seconds > 60) { minutes = Math.round(((seconds / 60)*10)/10) - Math.round((((seconds % 60)*10)/60)/10); seconds = seconds - (minutes * 60); minutes += "分"; } else { minutes = ""; } return hours + minutes + seconds + "秒"; } function getFileName () { var args = getArgs(); return args.file; } function getMapType () { var args = getArgs(); return args.map; } function getArgs() { var args = new Object(); var query = location.search.substring(1); // Get query string var pairs = query.split("&"); // Break at comma for(var i = 0; i < pairs.length; i++) { var pos = pairs[i].indexOf('='); // Look for "name=value" if (pos == -1) continue; // If not found, skip var argname = pairs[i].substring(0,pos); // Extract the name var value = pairs[i].substring(pos+1); // Extract the value args[argname] = unescape(value); // Store as a property // In JavaScript 1.5, use decodeURIComponent( ) instead of unescape( ) } return args; // Return the object } function getAveragePace (mph) { mph = mph.toString(); var a = mph.split('.'); var seconds = Math.round(a[1] * 60 / 100); return a[0] + ":" + seconds; } window.onload = function() { initCheckpoint(); onLoad(); } //用来在地图上显示一张图片的控件 function K_ImageOverlay(imageUrl,bounds,rotation,opacity) { this.imageUrl=imageUrl; this.bounds=bounds; this.rotation=-rotation; this.opacity=opacity||0.45; } K_ImageOverlay.prototype.initialize=function(a) { this.map=a; if(this.rotation>5 || this.rotation<-5) { this.drawElement=a.ownerDocument.createElement("v:Image"); this.drawElement.style.rotation=this.rotation; } else this.drawElement=a.ownerDocument.createElement("img"); this.drawElement.title=this.imageUrl; this.drawElement.style.position="absolute"; this.drawElement.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity="+(this.opacity*100)+");"; this.drawElement.style.display="none"; this.drawElement.src=this.imageUrl; if(browser.type==1) { this.drawElement.unselectable="on"; this.drawElement.onselectstart=function(){return false}; this.drawElement.galleryImg="no" } else { this.drawElement.style.MozUserSelect="none" } this.drawElement.style.border="0"; this.drawElement.style.padding="0"; this.drawElement.style.margin="0"; this.drawElement.oncontextmenu=function(){return false}; a.markerPane.appendChild(this.drawElement); }; K_ImageOverlay.prototype.redraw=function(a) { if(!a)return; var b=this.map.spec.getBitmapCoordinate(this.bounds.minY,this.bounds.minX,this.map.zoomLevel); var min=this.map.getDivCoordinate(b.x,b.y); b=this.map.spec.getBitmapCoordinate(this.bounds.maxY,this.bounds.maxX,this.map.zoomLevel); var max=this.map.getDivCoordinate(b.x,b.y); this.drawElement.style.left=(min.x)+"px"; this.drawElement.style.top=(max.y)+"px"; this.drawElement.style.width=(max.x-min.x)+"px"; this.drawElement.style.height=(min.y-max.y)+"px"; }; K_ImageOverlay.prototype.setOpacity=function(opacity) { this.opacity=opacity||0.45; this.drawElement.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity="+(this.opacity*100)+");"; } K_ImageOverlay.prototype.copy=function(){return new K_ImageOverlay(this.imageUrl,this.bounds,this.rotation,this.opacity)}; K_ImageOverlay.prototype.remove=window.GPolyline.prototype.remove; K_ImageOverlay.prototype.display=window.GPolyline.prototype.display; K_ImageOverlay.prototype.setZIndex=window.GPolyline.prototype.setZIndex; K_ImageOverlay.prototype.getLatitude=function(){return 180}; window.K_ImageOverlay=K_ImageOverlay;
import React from "react"; import { create } from "react-test-renderer"; import { mount } from "enzyme"; import News from "../News"; describe("News", () => { // mount the component let mountedComponent; const getMountedComponent = () => { if (!mountedComponent) { mountedComponent = mount(<News />); } return mountedComponent; }; beforeEach(() => { mountedComponent = undefined; }); it("it should render", () => { let tree = create(<News />); expect(tree.toJSON()).toMatchSnapshot(); }); it("it should say News!", () => { const h1 = getMountedComponent() .find("h1") .first(); expect(h1.text()).toContain("News!"); }); });
import React from 'react'; require('./resouce-usage.scss'); export default class ResourceUsage extends React.Component { getPoint(r, degree) { const size = 100; const trackWidth = 15; const d = degree / 180 * Math.PI; return { x: r * Math.sin(d) + size / 2, y: trackWidth / 2 + r * (1 - Math.cos(d)), }; } render() { const size = 100; const r = 40; const progress = 35; const startDegree = 0; const endDegree = startDegree + progress * 360 / 100; const s = this.getPoint(r, startDegree); const e = this.getPoint(r, endDegree); let progressPath = null; if (progress < 50) { progressPath = `M ${s.x} ${s.y} A ${r} ${r}, 0, 0, 1, ${e.x},${e.y}`; } else { const m = this.getPoint(r, startDegree + 180); progressPath = `M ${s.x} ${s.y} A ${r} ${r}, 0, 0, 1, ${m.x},${m.y} M ${m.x} ${m.y} A ${r} ${r}, 0, 0, 1, ${e.x},${e.y}`; } return ( <svg {...this.props} width={size} height={size} viewBox={`0 0 ${size} ${size}`}> <circle className="resource-usage" cx={size / 2} cy={size / 2} r={r}/> {progress > 0 ? <path d={progressPath} className="resource-usage__progress" /> : null} {progress > 0 ? <circle cx={s.x} cy={s.y} r={15 / 2} className="resource-usage__progress" /> : null} {progress > 0 ? <circle cx={e.x} cy={e.y} r={15 / 2} className="resource-usage__progress" /> : null} </svg> ); } } ResourceUsage.propTypes = { };
import React from 'react' import { BrowserRouter, Route, Switch } from 'react-router-dom' import SecureRoute from './components/common/SecureRoute' import NavigationBar from './components/common/NavigationBar' import Home from './components/common/Home' import Register from './components/auth/Register' import Login from './components/auth/Login' import Dashboard from './components/common/Dashboard' import PlayerAdd from './components/common/PlayerAdd' import GameAdd from './components/common/GameAdd' import GameEdit from './components/common/GameEdit' function App() { return ( <BrowserRouter> <NavigationBar/> <Switch> <Route exact path="/" component={Home} /> <SecureRoute path="/addplayer"> <PlayerAdd /> </SecureRoute> <SecureRoute path="/addgame"> <GameAdd /> </SecureRoute> <SecureRoute path="/editgame"> <GameEdit/> </SecureRoute> <Route path="/register" component={Register} /> <Route path="/login" component={Login} /> <SecureRoute path="/dashboard"> <Dashboard/> </SecureRoute> </Switch> </BrowserRouter> ) } export default App
const axios = require('axios'); export const getDemo = params => { const URL = 'https://reactjsteachingproj.herokuapp.com/users'; return axios.get(URL).then(response => { return response.data; }); }; export const apiCall = (url, data, headers, method) => axios({ method, url, data, headers })
var config = { "key":"", //Enter Personal Key "token":"" //Enter Private Token } var departments = { "depCrestline":"", "depFarmersAlmanac": "", "depGeiger":"CorporateProgramsProgramManagersGroup1,CorporateProgramsProgramManagersGroup2,CorporateProgramsProgramManagersGroup3,CorporateProgramsProgramManagersPSG,CorporateProgramsWeb&GraphicsGroup1,CorporateProgramsWeb&GraphicsGroup2,CorporateProgramsCustomerAdvocates,AssistantProgramManagers&AdminAssistant,CorporateProgramsInventory&Pricing", "depSupport":"", } var teams = { // TEST Team // "CPWEB":"bobdagget,jeffpatterson,pedmands,lesliemercier,preston409,johnpaine5,lesliemercier,johnathanplummer,dawnlaprell,mikefrench,mikeplourde,scottstowe,jallen19,alangroudle,tylerturcotte,jessicalevy10,kevinmcgrory,sthompsongeiger1", "Graphics": "", "Marketing/Brand/Data": "", "Sales": "", "SalesSupport": "", "Farmers'Almanac": "", "CorporateProgramsProgramManagersGroup1": "charlenedion,christamatuszewski,kimberlyblais,marcylavallee,kevinboilard,ryanmockler,sarahcouturier", "CorporateProgramsProgramManagersGroup2": "jonisatterthwaite,kaitlynnegibson1,rachellepower,kmillercraft,scottlaberge,stelladuclos", "CorporateProgramsProgramManagersGroup3": "jamesayotte3,justinfortier5,kellysutton3,nikkihamlin,rkilgore,theajones1", "CorporateProgramsProgramManagersPSG": "crystalparadis,erinhutchinson,bshuster1,julianarua,juliestinson1,jvickers1,kevinboilard,priscillakistner,jenruler1,ambryant,stephaniehobbs,wendythorne,traceydespres,reneeperdicaro1", "CorporateProgramsWeb&GraphicsGroup1": "dawnlaprell,mikefrench,sthompsongeiger1,mikeplourde,johnpaine5,preston409,scottstowe", "CorporateProgramsWeb&GraphicsGroup2": "alangroudle,jallen19,jessicalevy10,johnathanplummer,lesliemercier,tylerturcotte,kevinmcgrory", "CorporateProgramsCustomerAdvocates": "amandapaul,andreasands2,hcote2,heidi96961679,madisonsawyer,pamelamorris4", "AssistantProgramManagers&AdminAssistant": "amyrioux4,brandivachon,jrbourgoin,joshnickerson3,rubyphillips,scottsmith209", "CorporateProgramsInventory&Pricing": "bevhemond,kaseyplourde,katherineparlove,katiedoucette1", "RiskManagement": "", "DC": "", "Finance": "", "Marketing": "", "TotalCareA/P&FreightPayables": "", "TotalCareA/R": "", "TotalCareBillingGroup": "", "TotalCareClaims": "", "TotalCareCRSThinkTankElite": "", "TotalCareCRSTurnItUp": "", "TotalCareCRSMightyGreenDots": "", "TotalCareCRSConceptCrew": "", "TotalCareCRSEastFlorida": "", "TotalCareCRSDefendersofTrello": "", "TotalCareCRSMellowTrello": "", "TotalCareCRSWest": "", "TotalCareCRSLewiston": "", "TotalCareCRSServiceNow": "", "TotalCareOrderExpediting": "", "TotalCareOrderVerifier": "", "CorporateFinance": "", "ExMgmt&AdminServices": "", "VendorRelations": "", "HR/OD/OS": "", "ITEcommerce": "", "ITHelpdesk/WebApps/NOC": "", "ProductData": "" };
import React, { createContext, useState, useEffect } from 'react'; import AsyncStorage from '@react-native-community/async-storage'; const TodoListContext = createContext({ todoList: [], addTodoList: todo => {}, removeTodoList: index => {}, }); const TodoListContextProvider = ({ children }) => { const [ todoList, setTodoList ] = useState([]); const addTodoList = todo => { const list = [ ...todoList, todo ]; setTodoList(list); AsyncStorage.setItem('todoList', JSON.stringify(list)); }; const removeTodoList = index => { let list = [ ...todoList ]; list.splice(index, 1); setTodoList(list); AsyncStorage.setItem('todoList', JSON.stringify(list)); }; const initData = async () => { try { const list = await AsyncStorage.getItem('todoList'); if(list != null) { setTodoList(JSON.parse(list)); } } catch(e) { console.log(e); } }; useEffect(() => { initData(); }, []); return ( <TodoListContext.Provider value={{ todoList, addTodoList, removeTodoList, }}> {children} </TodoListContext.Provider> ) }; export { TodoListContextProvider, TodoListContext };
import Vue from 'vue' import API from '../config/api.js' // import axios from 'axios' // import qs from 'qs' // axios // function apiFactory(api) { // return (key = null) => { // let sendData = { // url: '/api' + api.url, // methods: 'POST', // data: api.params(key) // } // console.log(sendData) // return Vue.prototype.$axios(sendData) // } // } function apiFactory(api) { return (key = null) => Vue.http.jsonp(api.url,{ params: api.params(key), jsonp: api.jsonp }) } export default { actions: { getHotKey() { return apiFactory(API.hotkey)() }, getSearch(context,key) { return apiFactory(API.search)(key) }, getRecommend() { return apiFactory(API.first_page_data)() }, getAlbum(context,id) { return apiFactory(API.album)(id) } } }
module.exports = function(content, file, settings) { return require('./lib/parser')(content, file, settings).renderTpl(); };
// HEADER COMPONENT 'use strict'; var menu = { menus: [ { title: 'dashboard', link: 'index.html', isActive: true }, { title: 'workflow', link: 'workflow.html', isActive: false }, { title: 'todo list', link: 'todo.html', isActive: false }, { title: 'messages', link: 'messages.html', isActive: false } ] } Vue.component('main-menu', { methods: { changeTheme(){ $("#theme-changer").on('click', function(){ $("main").toggleClass('dark'); }); } }, template: ` <div class="topnav"> <a class="pic" <img src="img/profilepic.png" alt="profile picture"/></a> <h1>Micheal Mathews</h1> <a class="active" href="#home"><i class="fa fa-angle-right"></i></a> <a href="#"><i class="fa fa-bell"></i></a> <a href="#contact"><i class="fa fa-envelope"></i></a> <div class="search-container"> <form action="/action_page.php"> <input type="text" placeholder="Search.." name="search"> <button type="submit"><i class="fa fa-search"></i></button> </form> <button v-on:click="changeTheme" class="btn btn-outline-success my-2 my-sm-0" type="submit" id="theme-changer">Theme</button> </div> </div> `, data: function() { return menu; } }); var menus = new Vue({ el: '#mainmenu' })
const mongoose = require("mongoose"); const { Schema } = mongoose; const schema = new Schema( { summonerId: { type: String, required: true }, matchId: { type: Number, required: true }, spell1Id: { type: Number }, spell2Id: { type: Number }, win: { type: Boolean, }, item0: { type: Number, }, item1: { type: Number, }, item2: { type: Number, }, item3: { type: Number, }, item4: { type: Number, }, item5: { type: Number, }, item6: { type: Number, }, kills: { type: Number, }, deaths: { type: Number, }, assists: { type: Number, }, largestKillingSpree: { type: Number, }, largestMultiKill: { type: Number, }, killingSprees: { type: Number, }, longestTimeSpentLiving: { type: Number, }, doubleKills: { type: Number, }, tripleKills: { type: Number, }, quadraKills: { type: Number, }, pentaKills: { type: Number, }, unrealKills: { type: Number, }, totalDamageDealt: { type: Number, }, magicDamageDealt: { type: Number, }, physicalDamageDealt: { type: Number, }, trueDamageDealt: { type: Number, }, largestCriticalStrike: { type: Number, }, totalDamageDealtToChampions: { type: Number, }, magicDamageDealtToChampions: { type: Number, }, physicalDamageDealtToChampions: { type: Number, }, trueDamageDealtToChampions: { type: Number, }, totalHeal: { type: Number, }, totalUnitsHealed: { type: Number, }, damageSelfMitigated: { type: Number, }, damageDealtToObjectives: { type: Number, }, damageDealtToTurrets: { type: Number, }, visionScore: { type: Number, }, timeCCingOthers: { type: Number, }, totalDamageTaken: { type: Number, }, magicalDamageTaken: { type: Number, }, physicalDamageTaken: { type: Number, }, trueDamageTaken: { type: Number, }, goldEarned: { type: Number, }, goldSpent: { type: Number, }, turretKills: { type: Number, }, inhibitorKills: { type: Number, }, totalMinionsKilled: { type: Number, }, neutralMinionsKilled: { type: Number, }, neutralMinionsKilledTeamJungle: { type: Number, }, neutralMinionsKilledEnemyJungle: { type: Number, }, totalTimeCrowdControlDealt: { type: Number, }, champLevel: { type: Number, }, visionWardsBoughtInGame: { type: Number, }, sightWardsBoughtInGame: { type: Number, }, wardsPlaced: { type: Number, }, wardsKilled: { type: Number, }, firstBloodKill: { type: Boolean, }, firstBloodAssist: { type: Boolean, }, firstTowerKill: { type: Boolean, }, firstTowerAssist: { type: Boolean, }, firstInhibitorKill: { type: Boolean, }, firstInhibitorAssist: { type: Boolean, }, perk0: { type: Number, }, perk1: { type: Number, }, perk2: { type: Number, }, perk3: { type: Number, }, perk4: { type: Number, }, perk5: { type: Number, }, perkPrimaryStyle: { type: Number, }, perkSubStyle: { type: Number, }, statPerk0: { type: Number, }, statPerk1: { type: Number, }, statPerk2: { type: Number, }, creepsPerMinDeltas: { type: Map, of: Number }, xpPerMinDeltas: { type: Map, of: Number }, goldPerMinDeltas: { type: Map, of: Number }, csDiffPerMinDeltas: { type: Map, of: Number }, xpDiffPerMinDeltas: { type: Map, of: Number }, damageTakenPerMinDeltas: { type: Map, of: Number }, damageTakenDiffPerMinDeltas: { type: Map, of: Number }, }, { timestamps: true }, ); // https://mongoosejs.com/docs/schematypes.html#maps schema.set("toJSON", { virtuals: true }); module.exports = mongoose.model("Stats", schema);
/////////////////// ///// MOBILOT ///// /////////////////// angular .module('Mobilot') .config([ '$logProvider', '$stateProvider', '$urlRouterProvider', '$translateProvider', function ( $logProvider, $stateProvider, $urlRouterProvider, $translateProvider ) { /// Debugging var isDeveloperEnv = ( document.location.hostname != 'mobilot.at' && document.location.hostname != 'mobilot.fhstp.ac.at' // && document.location.hostname != 'localhost' ); console.info('Debugging: ' + isDeveloperEnv); $logProvider.debugEnabled(isDeveloperEnv); if ( ! isDeveloperEnv ) { if ( ! window.console ) { window.console = {}; } var methods = ['log', 'debug', 'warn', 'info']; for (var i = 0; i < methods.length; i++) { console[methods[i]] = function(){}; } } /// Language Settings $translateProvider.useStaticFilesLoader({ prefix: 'assets/lang/lang-', suffix: '.json' }); $translateProvider.determinePreferredLanguage(); $translateProvider.fallbackLanguage('en_US'); $translateProvider.useSanitizeValueStrategy('escapeParameters'); $translateProvider.useLocalStorage(); $urlRouterProvider .when('/map', '/') .when('/map/', '/') .when('//map', '/') .when('//map/', '/') // TODO: this is somehow ignored .when('/:mobidulCode/list', '/:mobidulCode/list/all') .when('/:mobidulCode/list/', '/:mobidulCode/list/all') // .when('/:mobidulCode/:stationCode/', '/:mobidulCode/:stationCode') // .when('/:mobidulCode//edit', '/:mobidulCode') // .when('/:mobidulCode//edit/basis', '/:mobidulCode') // .when('/:mobidulCode/:stationCode/edit', '/:mobidulCode/:stationCode/edit/basis') // .when('/:mobidulCode/:stationCode/edit/', '/:mobidulCode/:stationCode/edit/basis') // .when('/:mobidulCode/:stationCode/edit/basis/', '/:mobidulCode/:stationCode/edit/basis') // .when('/:mobidulCode/:stationCode//edit/basis/', '/:mobidulCode/:stationCode/edit/basis') .otherwise('/'); /// States $stateProvider //////////////// ///// home ///// //////////////// .state('home', { url: '/', views: { // 'loader': { // templateUrl: 'app/modules/common/LoaderPartial.html', // controller: 'CoreController as core' // }, 'header': { templateUrl: 'app/modules/core/Header.html', controller: 'HeaderController as header' }, 'content': { templateUrl: 'app/modules/home/HomeView.html', controller: 'HomeController as home' } } }) //////////////////////////////// ///// meine mobidule login ///// //////////////////////////////// .state('home.login', { url: 'home/login', views: { 'login': { templateUrl: 'app/modules/login/LoginView.html', controller: 'LoginController as login' } } }) ///////////////// ///// login ///// ///////////////// .state('login', { url: '/login', views: { 'header': { templateUrl: 'app/modules/core/Header.html', controller: 'HeaderController as header' }, 'content': { templateUrl: 'app/modules/login/LoginView.html', controller: 'LoginController as login' } } }) //////////////////// ///// register ///// //////////////////// .state('register', { url: '/register', views: { 'header': { templateUrl: 'app/modules/core/Header.html', controller: 'HeaderController as header' }, 'content': { templateUrl: 'app/modules/login/RegisterView.html', controller: 'LoginController as login' } } }) //////////////////// ///// activate ///// //////////////////// .state('activate', { url: '/activate', views: { 'header': { templateUrl: 'app/modules/core/Header.html', controller: 'HeaderController as header' }, 'content': { templateUrl: 'app/modules/login/ActivateView.html', controller: 'LoginController as login' } } }) /////////////////// ///// profile ///// /////////////////// .state('profile', { url: '/profile', views: { 'header': { templateUrl: 'app/modules/core/Header.html', controller: 'HeaderController as header' }, 'content': { templateUrl: 'app/modules/profile/ProfileView.html', controller: 'ProfileController as profile' } } }) //////////////// ///// play ///// //////////////// .state('play', { url: '/play/:triggerScan', views: { 'header': { templateUrl: 'app/modules/core/Header.html', controller: 'HeaderController as header' }, 'content': { templateUrl: 'app/modules/play/PlayView.html', controller: 'PlayController as play' } } }) /////////////////// ///// restore ///// /////////////////// .state('restore', { url: '/restore', views: { 'header': { templateUrl: 'app/modules/core/Header.html', controller: 'HeaderController as header' }, 'content': { templateUrl: 'app/modules/login/RestoreView.html', controller: 'LoginController as login' } } }) ///////////////////////// ///// restore reset ///// ///////////////////////// .state('reset', { url: '/restore/:token', views: { 'header': { templateUrl: 'app/modules/core/Header.html', controller: 'HeaderController as header' }, 'content': { templateUrl: 'app/modules/login/ResetView.html', controller: 'LoginController as login' } } }) /////////////////// //// impressum //// /////////////////// .state('impressum', { url: '/impressum', views: { 'header': { templateUrl: 'app/modules/core/Header.html', controller: 'HeaderController as header' }, 'content': { templateUrl: 'app/modules/mobidul/about/AboutPartial.html', controller: 'AboutController as about' } } }) /////////////////// ///// mobidul ///// /////////////////// // /:mobidulCode .state('mobidul', { url: '/:mobidulCode', views: { // 'loader': { // templateUrl: 'app/modules/common/LoaderPartial.html', // controller: 'CoreController as core' // }, 'header': { templateUrl: 'app/modules/core/Header.html', controller: 'HeaderController as header' }, 'content': { templateUrl: 'app/modules/mobidul/MobidulView.html', controller: 'MobidulController as mobidul' } } }) /////////////////// ///// creator ///// /////////////////// .state('mobidul.creator', { abstract: true, url: '/creator', views: { 'header': { templateUrl: 'app/modules/core/Header.html', controller: 'HeaderController as header' }, 'mobidulContent': { templateUrl: 'app/modules/creator/CreatorView.html', controller: 'CreatorController as creator' }, } }) ///////////////////////// ///// creator steps ///// ///////////////////////// .state('mobidul.creator.basis', { url: '/basis', views: { 'creatorContent': { templateUrl: 'app/modules/creator/CreatorBasisPartial.html' } } }) .state('mobidul.creator.categories', { url: '/categories', views: { 'creatorContent': { templateUrl: 'app/modules/creator/CreatorCategoriesPartial.html' //, controller: 'CreatorCategoriesController as categories' } } }) .state('mobidul.creator.menu', { url: '/menu', views: { 'creatorContent': { templateUrl: 'app/modules/creator/CreatorMenuPartial.html' } } }) .state('mobidul.creator.settings', { url: '/settings', views: { 'creatorContent': { templateUrl: 'app/modules/creator/CreatorSettingsPartial.html' //, controller: 'CreatorSettingsController as settings' } } }) /////////////// ///// map ///// /////////////// // /:mobidulCode/map .state('mobidul.map', { url: '/map', views: { 'mobidulContent': { templateUrl: 'app/modules/mobidul/map/MapPartial.html', controller: 'MapController as map' } } }) // /:mobidulCode/about .state('mobidul.about', { url: '/about', views: { 'mobidulContent': { templateUrl: 'app/modules/mobidul/about/AboutPartial.html', controller: 'AboutController as about' } } }) /////////////////// ///// station ///// ////////////////// // /:mobidulCode/list/:category .state('mobidul.list', { url: '/list/:category', views: { 'mobidulContent': { templateUrl: 'app/modules/mobidul/list/ListStationsPartial.html', controller: 'ListStationsController as list' } } }) // /:mobidulCode/:stationCode .state('mobidul.station', { url: '/{stationCode:(?!\/)[a-z0-9\-]{1,20}}', views: { 'mobidulContent': { templateUrl: 'app/modules/mobidul/station/StationView.html', controller: 'StationController as station' } } }) .state('mobidul.station.verify', { url: '/{verifier}', views: { 'mobidulContent': { templateUrl: 'app/modules/mobidul/station/StationView.html', controller: 'StationController as station' } } }) /////////////////////////// ///// station creator ///// /////////////////////////// // /:mobidulCode/:stationCode/edit .state('mobidul.station.edit', { abstract: true, // url: '/edit', views: { 'stationContent': { templateUrl: 'app/modules/mobidul/station/creator/StationCreatorView.html', controller: 'StationCreatorController as stationCreator' } } }) // /:mobidulCode/:stationCode/edit/basis .state('mobidul.station.edit.basis', { url: '/edit/basis', views: { 'stationCreatorContent': { templateUrl: 'app/modules/mobidul/station/creator/StationCreatorBasisPartial.html', } } }) // /:mobidulCode/:stationCode/edit/place .state('mobidul.station.edit.place', { url: '/edit/place', views: { 'stationCreatorContent': { templateUrl: 'app/modules/mobidul/station/creator/StationCreatorPlacePartial.html', controller: 'MapController as map' } } }) // /:mobidulCode/:stationCode/edit/categories .state('mobidul.station.edit.categories', { url: '/edit/categories', views: { 'stationCreatorContent': { templateUrl: 'app/modules/mobidul/station/creator/StationCreatorCategoriesPartial.html', } } }) // /:mobidulCode/:stationCode/edit/settings .state('mobidul.station.edit.settings', { url : '/edit/settings', views : { 'stationCreatorContent' : { templateUrl : 'app/modules/mobidul/station/creator/StationCreatorSettingsPartial.html', } } }) // /:mobidulCode/:stationCode/:media .state('mobidul.media', { url: '/media/:media', views: { 'mobidulContent': { templateUrl: 'app/modules/mobidul/station/media/MediaPartial.html', controller: 'MediaController as media' } } }) //////////////// ///// social ///// //////////////// //http://mobilot.app/#/social/station1/socialConfirm/ACTIVATED/eez4gu .state('mobidul.station.verify.socialStatus', { url : '/{socialStatus}', views : { 'mobidulContent' : { templateUrl : 'app/modules/mobidul/station/StationView.html', controller : 'StationController as station' } } }) .state('mobidul.station.verify.socialStatus.socialCode', { url : '/{socialCode}', views : { 'mobidulContent' : { templateUrl : 'app/modules/mobidul/station/StationView.html', controller : 'StationController as station' } } }); /// Exceptional Redirects $urlRouterProvider .when('/:mobidulCode/', '/:mobidulCode/map') // NOTE: this redirect doesn't seem to work properly .when('/:mobidulCode', '/:mobidulCode/map') .when('/:mobidulCode/map/', '/:mobidulCode/map'); } ]) //////////////////////// ///// CUSTOM THEME ///// //////////////////////// .config([ '$mdThemingProvider', function ( $mdThemingProvider ) { var mobilotBlueMap = $mdThemingProvider .extendPalette('blue', { '500': '3797c4' }); var mobilotGreyMap = $mdThemingProvider .extendPalette('grey', { '50': 'ffffff' }); $mdThemingProvider .definePalette('mobilotBlue', mobilotBlueMap); $mdThemingProvider .definePalette('mobilotGrey', mobilotGreyMap); $mdThemingProvider .theme('default') .primaryPalette('mobilotBlue') .accentPalette('amber') .backgroundPalette('mobilotGrey'); } ]) ////////////////////// ///// FOREST GUMP //// ////////////////////// .run([ '$log', '$rootScope', 'StateManager', 'UserService', 'HeaderService', function ( $log, $rootScope, StateManager, UserService, HeaderService ) { $log.debug('< mobilot >'); $log.debug('Run Forest ! Run !'); UserService.restoreUser(); $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) { $log.debug('=============================='); $log.debug('>>>> STATE CHANGE START <<<<'); $log.debug('= ', toState, toParams); $log.debug('= ', fromState, fromParams); $log.debug('------------------------------'); if (fromState) { console.debug('= Setting new state !') StateManager.set(toState, toParams); } else { // TODO: StateManager.reset() and figure out default previous route when necessary // StateManager.reset(); $log.error('= Missing fromState Object !'); } if ( toParams.mobidulCode && toParams.mobidulCode !== StateManager.NEW_MOBIDUL_CODE ) { console.debug('= restoreUserRole for mobidulCode: ', toParams.mobidulCode) UserService.restoreUserRole(toParams.mobidulCode); } $log.debug('############################'); }); $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) { $log.debug('>>>> STATE CHANGE SUCCESS <<<<'); HeaderService.refresh(); }); } ]); /////////////// ///// END ///// ///////////////
import React from 'react' import { connect } from 'react-redux' import { bindActionCreators, compose } from 'redux'; import { Redirect } from "react-router-dom"; import { history, routes } from '../history.js' import './auth.scss' /* When composed with this HOC, the component can only be viewed by user of role >= minimumUserRole (0 = user, 1 = mod, 2 = admin); */ const withAuthorization = (minimumUserRole) => WrappedComponent => { return ( class WithAuthorization extends React.Component { render () { return( (this.props.user.role >= minimumUserRole) ? <WrappedComponent {...this.props} /> : <div className='authErrorPage'> <h3>User Role: {this.props.user.role}</h3> <h1>Error 401</h1> <h3>You are Unauthorized to be here 🤖</h3> <button onClick={() => history.push(routes._HOME)}>Take Me To Safety</button> <button onClick={() => history.goBack()}>Go Back</button> </div> ) } } ) function mapStateToProps(state) { return { user: state.user.currUser }; } function mapDispatchToProps(dispatch) { return { }; } const composedHoc = compose( connect(mapStateToProps,mapDispatchToProps), withAuthorization(minimumUserRole) ); composedHoc(); } export default withAuthorization;
"use strict"; require("@babel/register"); const db = require("./src/db"); const server = require("./src/server"); db.connect(); server.listen(3000, "0.0.0.0", (err, address) => { if (err) throw err; server.log.info(`Server listening on ${address}`); });
'use strict'; function asynchronously(generator) { var g = generator(); (function go(err, result) { var step; if (err) { step = g.throw(err); } else { step = g.next(result); } if (!step.done) { var promise = step.value; promise .then(function(resolvedValue) { go(null, resolvedValue); }) .catch(function(e) { go(e); }); } })(); } module.exports = asynchronously;
import autoprefixer from 'autoprefixer'; import cssnano from 'cssnano'; import filter from 'gulp-filter'; import gulp from 'gulp'; import header from 'gulp-header'; import pkg from './package.json'; import postcss from 'gulp-postcss'; import rename from 'gulp-rename'; import transpile from 'gulp-sass'; import sassCompiler from 'sass'; transpile.compiler = sassCompiler; const { NODE_ENV = 'development' } = process.env; // Compile the SASS to CSS export function css() { // Initialize the processors,... let processors = [ autoprefixer ]; // ... the banner,... let banner = '/*! <%= pkg.name %> <%= pkg.version %> | <%= pkg.license %> License | <%= pkg.homepage %> */'; // ... and rename options let options = {}; // Depending on what type of assets are being built, change the initial variables switch (NODE_ENV) { case 'development': banner += '\n\n'; // Provide additional spacing below the banner on development CSS break; case 'production': processors.push(cssnano); // Use CSS Nano on production CSS options.suffix = '.min'; // Add the ".min" suffix to the production CSS file name } return gulp.src('src/*.sass') .pipe(transpile()) // Transpile the SASS to CSS .pipe(postcss(processors)) // Process the CSS with PostCSS .pipe(header(banner, { pkg })) // Add a header to the CSS .pipe(rename(options)) // Rename the CSS file .pipe(gulp.dest('dist/css')); // Move the CSS to the correct location }; // Package the SASS to be reusable export function sass() { // Store the name of the main file const mainFile = filter([ 'src/chassis.sass' ], { restore: true }); // For each file in the source directory... return gulp.src('src/**/*') .pipe(mainFile) // If currently processing the main file,... .pipe(rename({ prefix: '_' })) // ... prefix its file name with "_" .pipe(mainFile.restore) .pipe(gulp.dest('dist/sass')); // Copy the files to the correct location }; // Build all assets (CSS and SASS) export const build = gulp.series(gulp.parallel(css, sass)); // Watch for changes and build CSS export const develop = () => gulp.watch('src/**/*', css);
import React, { useState, Fragment } from 'react' import PropTypes from 'prop-types' import { useStripe, useElements, CardElement } from '@stripe/react-stripe-js' import { Elements } from '@stripe/react-stripe-js' import { loadStripe } from '@stripe/stripe-js' import { Dialog, Transition } from '@headlessui/react' const stripePromise = loadStripe(`${process.env.STRIPE_PUBLIC_KEY}`) const TipForm = () => { const stripe = useStripe() const elements = useElements() const [loading, setLoading] = useState(false) const [errorMessage, setErrorMessage] = useState(``) const [successMessage, setSuccessMessage] = useState(``) const [tipAmountValue, setTipAmountValue] = useState(``) // tip amount const [name, setName] = useState(``) const [email, setEmail] = useState(``) const changeTip = (event) => { const amount = event.target.value setTipAmountValue(amount) } const changeName = (event) => { const newName = event.target.value setName(newName) } const changeEmail = (event) => { const newEmail = event.target.value setEmail(newEmail) } const handleSubmit = async (event) => { event.preventDefault() //console.log(`submitting...`) setLoading(true) if (!stripe || !elements || !tipAmountValue || !name || !email) { return } try { const { error, paymentMethod } = await stripe.createPaymentMethod({ type: `card`, card: elements.getElement(CardElement), }) if (error) { console.log(`Payment error:`, error) setErrorMessage(error.message) } else { const tipAmount = tipAmountValue * 100 //convert to cents // eslint-disable-next-line ghost/ember/require-fetch-import const res = await fetch(`/api/processpayment`, { method: `POST`, headers: { 'Content-Type': `application/json`, }, body: JSON.stringify({ paymentMethodId: paymentMethod.id, tipAmount: tipAmount, email: email, name: name, }), }) const { e, message } = await res.json() if (e) { setErrorMessage(e) setLoading(false) //console.log(error) } else { setSuccessMessage(message) setErrorMessage(``) setLoading(false) //console.log(res) } } setLoading(false) } catch (error) { console.error(`Payment error:`, error) setLoading(false) setErrorMessage(error.message) } } return ( <> {successMessage ? ( <p className="bg-blue mt-2 px-4 py-2 font-bold text-wide uppercase">{successMessage}</p> ) : ( <form onSubmit={handleSubmit}> <input aria-label="Name" placeholder="Name" type="text" required value={name} onChange={changeName} className="w-full px-2 py-1.5 text-sm border border-black dark:border-purple focus:outline-none dark:bg-purple-dark dark:text-white mb-2" /> <input aria-label="Email" placeholder="Email" type="email" required value={email} onChange={changeEmail} className="w-full px-2 py-1.5 text-sm border border-black dark:border-purple focus:outline-none dark:bg-purple-dark dark:text-white mb-2" /> <input aria-label="Tip amount" placeholder="$5.00" type="number" required className="w-full px-2 py-1.5 text-sm border border-black dark:border-purple focus:outline-none dark:bg-purple-dark dark:text-white mb-2" value={tipAmountValue} onChange={changeTip} /> <div className="mb-3 border dark:border-purple px-2 py-1.5"> <CardElement options={{ style: { base: { fontSize: `16px`, color: `#424770`, '::placeholder': { color: `#aab7c4`, }, }, invalid: { color: `#9e2146`, }, }, }} /> </div> <button type="submit" disabled={!stripe} className="btn btn-primary flex"> Leave a tip </button> </form> )} {loading && <p className="text-gray-500 mt-2">Processing payment...</p>} {errorMessage && <p className="mt-2 text-red">{errorMessage}</p>} </> ) } const TipButton = ({ text = `Add a tip` }) => { const [isOpen, setIsOpen] = useState(false) function closeModal() { setIsOpen(false) } function openModal() { setIsOpen(true) } return ( <> <button type="button" onClick={openModal} className="btn btn-primary text-base text-wide uppercase flex"> {text} </button> <Transition appear show={isOpen} as={Fragment}> <Dialog as="div" className="relative z-10" onClose={closeModal}> <Transition.Child as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0" enterTo="opacity-100" leave="ease-in duration-200" leaveFrom="opacity-100" leaveTo="opacity-0"> <div className="fixed inset-0 bg-black bg-opacity-50" /> </Transition.Child> <div className="fixed inset-0 overflow-y-auto"> <div className="flex min-h-full items-center justify-center p-4 text-center"> <Transition.Child as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0 scale-95" enterTo="opacity-100 scale-100" leave="ease-in duration-200" leaveFrom="opacity-100 scale-100" leaveTo="opacity-0 scale-95"> <Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-white dark:bg-purple-dark dark:text-purple-light p-6 text-left align-middle shadow-xl transition-all relative"> <div className="absolute right-8 top-6"> <button type="button" className="text-xs" onClick={closeModal}> Close </button> </div> <Dialog.Title as="h3" className="text-sm font-bold leading-6 text-gray-900"> Show Your Support! </Dialog.Title> <div className="mt-2"> <p className="mb-5"> Blog posts published on this site will always remain free. If you come across something that has helped or inspired you though, consider showing your support! </p> <Elements stripe={stripePromise}> <TipForm /> </Elements> </div> </Dialog.Panel> </Transition.Child> </div> </div> </Dialog> </Transition> </> ) } export default TipButton TipButton.propTypes = { text: PropTypes.string, }
function checkPassword(password) { const ADMIN_PASSWORD = "jqueryismyjam"; let message; switch (password) { case null: message = "Отменено пользователем!"; break; case ADMIN_PASSWORD: message = "Добро пожаловать!"; break; default: message = "Доступ запрещён, неверный пароль!"; } console.log(message); return message; } checkPassword("mangohackzor"); checkPassword(null); checkPassword("polyhax"); checkPassword("jqueryismyjam"); // Функция checkPassword(password) получает пароль в параметр password, проверяет его на совпадение с паролем администратора в переменной ADMIN_PASSWORD и возвращает сообщение о результате сравнения, хранящееся в переменной message. // Если значение параметра password: // равно null, значит пользователь отменил операцию и в message записывается строка 'Отменено пользователем!'. // совпадает со значением ADMIN_PASSWORD, в переменную message присваивается строка 'Добро пожаловать!'. // не удобвлетворяет ни одному из предыдущих условий, в переменную message записывается строка 'Доступ запрещен, неверный пароль!'.
import _ from 'underscore'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { loadConfig } from 'shared/actions/Config'; import { fetchTasks } from 'mgmt/Dashboard/actions'; import Loading from 'shared/components/Loading'; import TaskChart from 'mgmt/Dashboard/components/TaskChart'; import { STATUS } from 'mgmt/Dashboard/constants'; class Root extends Component { constructor(props) { super(props); props.dispatch(loadConfig()); } componentWillMount() { this.props.dispatch(fetchTasks()); } getChartData() { const height = 200, width = 500, padding = {top: 20, right: 0, bottom: 50, left: 75}, yTransform = [padding.left, 0], xTransform = [0, height - padding.bottom], colors = {}; Object.keys(STATUS).map((key) => colors[key] = STATUS[key].color ); return {height, width, padding, yTransform, xTransform, colors}; } renderNoTasks(){ return <p>To tasks have yet assigned.</p>; } renderTasksByType(chartData, list){ let types = _.chain(list) .pluck('type') .uniq() .value(); return types.map(function(type){ let subset = list.filter((d) => d.type === type), data = _.extend({}, chartData, { label: subset[0].type_display, }); return <div key={`type-${type}`}> <TaskChart chartData={data} tasks={subset} /> </div>; }); } renderTasksByUser(chartData, list){ let users = _.chain(list) .map((d)=> (d.owner)? d.owner.full_name: null) .compact() .uniq() .value(); return users.map(function(user){ let subset = list.filter((d) => d.owner && d.owner.full_name === user), data = _.extend({}, chartData, { label: subset[0].owner.full_name, }); return <div key={`user-${user}`}> <TaskChart chartData={data} tasks={subset} /> </div>; }); } render() { if (!this.props.tasks.isLoaded){ return <Loading />; } if (this.props.tasks.list.length === 0){ return this.renderNoTasks(); } let list = this.props.tasks.list, chartData = this.getChartData(); return ( <div> <h3>All task summary</h3> <TaskChart chartData={chartData} tasks={list} /> <h3>Tasks by type</h3> {this.renderTasksByType(chartData, list)} <h3>Tasks by user</h3> {this.renderTasksByUser(chartData, list)} </div> ); } } function mapStateToProps(state){ return state; } export default connect(mapStateToProps)(Root);
$(document).ready(function() { $(document).on('submit', '#login_form', function(e){ var path = window.location.pathname; var page = path.split("/").pop(); e.preventDefault(); var email = $('#email').val(); var password = $('#password').val(); var isValid = true; $(".error").remove(); if (email.length < 5 || email.length > 25) { $('#email').after('<span class="error">Enter a valid email</span>'); isValid = false; } else { var regEx = /[a-zA-Z]+@{1}[a-zA-Z]+\.{1}[a-zA-Z]{2,4}/; var validEmail = regEx.test(email); if (!validEmail) { $('#email').after('<span class="error">Enter a valid email</span>'); isValid = false; } } if (password.length < 5 || password.length > 30) { $('#password').after('<span class="error">Password must be 5-30 symbols long</span>'); isValid = false; } else { var regExPass = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{5,}$/; var validPass = regExPass.test(password); if (!validPass) { $('#password').after('<span class="error">Example : Password1</span>'); isValid = false; } } if(isValid){ $('#login_form')[0].submit(); } }); });
import React,{Component} from 'react'; import ReactDOM from 'react-dom'; import {Login} from './login'; import Navbar from './navbar'; import HomeBody from './homeBody'; require('./bootstrap.css'); require('./home.css'); require('./home_responsive.css'); export class Home extends Component { render() { return(<div> <div id='navbar'> <Navbar /> </div> <div id="main"> <HomeBody /> </div> </div> ); } }
import Vue from 'vue' import Vuex from 'vuex' //import web3 from '../plugins/web3'; //import ABI from "../../../../build/contracts/RegalERC20.json"; //import Web3 from "web3"; Vue.use(Vuex) /*const vm = new Vue({ web3: function() { return { contract: RegalERC20 } } })*/ //const provider = new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/654adc0bbc0f4667a3a725b55d5e84ac"); //Vue.use(VueWeb3, { web3: new Web3(Web3.givenProvider)}); //vm.use(VueWeb3, { web3: new Web3(Web3.givenProvider)}); export default new Vuex.Store({ state: { myEthAddress: "", metamaskConnected: false, web3: null, profile_info: {}, contracts: { regal:null, tokens:null, users:null } }, mutations: { setWeb3(state, payload) { state.web3 = payload; }, setEthAddress(state, payload) { state.myEthAddress = payload; }, setMetamaskConnected(state, payload) { state.metamaskConnected = payload; }, setContracts(state, payload) { state.contracts = payload; }, setProfileInfo(state, payload) { state.profile_info = payload; } }, actions: { initialize: ({commit}, payload) => { commit('setWeb3', payload); if(typeof payload !== 'undefined') { commit('setMetamaskConnected', true); } }, registerData: ({commit}, payload) => { commit('setEthAddress', payload.metaMaskAddress); }, registerContracts: ({commit}, payload) => { commit('setContracts', payload); } }, getters: { getWeb3(state) { return state.web3; }, getMyAddress(state) { return state.myEthAddress; }, getUserContract(state) { return state.contracts.users; }, getTokenContract(state) { return state.contracts.tokens; }, getRegalERC20Contract(state) { return state.contracts.regal; } }, modules: { } })
var mongoose = require('mongoose'); var Schema = mongoose.Schema; //评论collection结构 var CommentsSchema = new Schema({ //动态的用户名 username: String, //发布者 publisher: String, //评论来源类型 source_type: String, //影讯id aid: String, //动态中的电影id filmid: String, //评论内容 content: String, //创建时间 create_time: String }); module.exports = CommentsSchema;
import View from "."; const updateView = (node) => { View.innerText = ""; View.append(node); }; export default updateView;
import Button from '@material-ui/core/Button'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogTitle from '@material-ui/core/DialogTitle'; import Paper from '@material-ui/core/Paper'; import { Alert } from '@material-ui/lab'; import React, { useEffect, useState } from 'react'; import bankingInfoApi from '../../api/bankingInfoApi'; function PaperComponent(props) { return <Paper {...props} />; } export default function ModalBookCoachingConfirm(props) { const { isOpen, onClose, onClickConfirm, id, contentDialog, onSuccess, onError, } = props; const [bankingInfo, setBankingInfo] = useState([]); useEffect(() => { const fetchBankingInfo = async () => { const res = await bankingInfoApi.getBankingInfo(); console.log(res); setBankingInfo(res.data); }; fetchBankingInfo(); }, []); console.log(bankingInfo); const handleClick = (id) => { onClickConfirm(id); }; return ( <Dialog open={isOpen} onClose={onClose} PaperComponent={PaperComponent} aria-labelledby='draggable-dialog-title' > <DialogTitle style={{ cursor: 'move' }} id='draggable-dialog-title'> <div style={{ textAlign: 'center' }}>{contentDialog}</div> </DialogTitle> <DialogContent> <DialogContentText> <b> Để hoàn tất quá trình đặt lịch, bạn cần thanh toán trước dịch vụ theo hình thức chuyển khoản </b> <p>Ngân hàng: {bankingInfo[0] && <b>{bankingInfo[0].bank}</b>}</p> <p> Số tài khoản: {bankingInfo[0] && <b>{bankingInfo[0].number}</b>} </p> <p>Chủ tài khoản: {bankingInfo[0] && <b>{bankingInfo[0].name}</b>}</p> <p> Nội dung chuyển khoản: <span style={{ color: '#f50057', fontWeight: 'bold', }} > DAT LICH TU VAN - Ten - SĐT </span> ( Trong đó: Ten là tên người đặt lịch, SĐT là số điện thoại liên hệ) </p> <p style={{ fontWeight: 'bold', }} > Sau khi nhận được thông tin chuyển khoản, chúng tôi sẽ và liên hệ với bạn trong vòng tối đa 2 tiếng (từ 8h30 sáng đến 18h chiều) </p> </DialogContentText> {onSuccess && ( <Alert variant='filled' severity='success' style={{ marginTop: '1rem', justifyContent: 'center' }} > <strong>Đặt dịch vụ thành công!</strong> </Alert> )} {onError && ( <Alert variant='filled' severity='error' style={{ marginTop: '1rem', justifyContent: 'center' }} > <strong>Đặt dịch vụ không thành công!</strong> </Alert> )} </DialogContent> <DialogActions style={{ justifyContent: 'space-around' }}> <Button onClick={onClose} color='secondary' variant='contained'> Hủy </Button> <Button onClick={(e) => { handleClick(id); }} color='primary' variant='contained' type='button' autoFocus > Xác nhận đặt lịch </Button> </DialogActions> </Dialog> ); }
function preload(){ } function setup() { canvas=createCanvas(700, 700); video=createCapture(VIDEO); video.hide(); } function draw() { background(220); fill(100) text("("+mouseX+","+mouseY+")",mouseX, mouseY); image(video, 200, 200, 400, 400); fill("#ffe6ee"); stroke("#7fffd4"); rect(200, 180, 400, 20); rect(200, 600, 400, 20); rect(200, 180, 20, 420); rect(600, 180, 20, 440); circle(209, 187, 50); circle(609, 185, 50); circle(609, 615, 50); circle(209, 615, 50); } function take_snap() { save('framedimg.png'); }
import React from 'react'; const CatalogIcon = ({className}) => { return ( <div> <svg _ngcontent-fao-c30="" height="14px" version="1.1" viewBox="0 0 20 14" width="20px" className={className}> <desc _ngcontent-fao-c30="">Created with Sketch.</desc> <g _ngcontent-fao-c30="" fill="none" fill-rule="evenodd" id="Admin-Panel" stroke="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="1"> <g _ngcontent-fao-c30="" className="stroke-color" id="Step-1-Copy-3" stroke="#4785EF" stroke-width="2" transform="translate(-17.000000, -198.000000)"> <g _ngcontent-fao-c30="" id="Group-2"> <g _ngcontent-fao-c30="" id="Side-Menu"> <g _ngcontent-fao-c30="" id="Catalog" transform="translate(0.000000, 184.000000)"> <g _ngcontent-fao-c30="" id="Group-6" transform="translate(17.505000, 14.500000)"> <path style="fill: rgb(73,84,125)" _ngcontent-fao-c30="" d="M5.495,0.5 L18.495,0.5" id="Line_70"></path> <path _ngcontent-fao-c30="" d="M5.495,6.5 L18.495,6.5" id="Line_71"></path> <path _ngcontent-fao-c30="" d="M5.495,12.5 L18.495,12.5" id="Line_72"></path> <path _ngcontent-fao-c30="" d="M0.495,0.5 L0.505,0.5" id="Line_73"></path> <path _ngcontent-fao-c30="" d="M0.495,6.5 L0.505,6.5" id="Line_74"></path> <path _ngcontent-fao-c30="" d="M0.495,12.5 L0.505,12.5" id="Line_75"></path> </g> </g> </g> </g> </g> </g> </svg> </div> ); }; export default CatalogIcon;
function fun(s){ if(s==1) document.get
import styled from 'styled-components' export const Container = styled.div` position: sticky; top: 100vh; color: #fff; background-color: #444b54; padding: 10px; display: flex; align-items: center; justify-content: space-between; ` export const Logo = styled.div` display: flex; align-items: center; font-family: 'Pathway Gothic One', sans-serif; img { width: 35px; margin-right: 10px; } ` export const Social = styled.div` a { color: #fff; text-decoration: none; margin-right: 10px; cursor: pointer } `
const Engine = Matter.Engine; const World = Matter.World; const Bodies = Matter.Bodies; const Body = Matter.Body; const Constraint = Matter.Constraint function preload() { } function setup() { createCanvas(800, 700); engine = Engine.create(); world = engine.world; //Create the Bodies Here. aa = new normal(); ground = new normal(400,670,800,20) stone1 = new Stone(70,560,80,80) slingSS = new SlingShot(stone1.body,{x:70,y:560}) mango1 = new Mango(550,420,50,50) mango2 = new Mango(450,440,50,50) mango3 = new Mango(650,380,50,50) mango4 = new Mango(500,340,50,50) mango5 = new Mango(600,340,50,50) mango6 = new Mango(700,430,50,50) Engine.run(engine); } function draw() { rectMode(CENTER); background("lightBlue"); aa.display(); ground.display(); stone1.display(); slingSS.display(); mango1.display(); mango2.display(); mango3.display(); mango4.display(); mango5.display(); mango6.display(); detectCollision(stone1,mango1) detectCollision(stone1,mango2) detectCollision(stone1,mango3) detectCollision(stone1,mango4) detectCollision(stone1,mango5) detectCollision(stone1,mango6) } function mouseDragged(){ Matter.Body.setPosition(stone1.body,{x:mouseX,y:mouseY}); } function mouseReleased(){ slingSS.fly(); } function detectCollision(lstone,lmango){ mangoBodyPosition = lmango.body.position stoneBodyPosition = lstone.body.position var distance = dist(stoneBodyPosition.x,stoneBodyPosition.y,mangoBodyPosition.x,mangoBodyPosition.y) if(distance<=lmango.radius/10+lstone.radius){ Matter.Body.setStatic(lmango.body,false) } } function keyPressed(){ if(keyCode == 32){ Matter.Body.setPosition(stone1.body,{x:70,y:560}); slingSS.attach(stone1.body); } }
//E.7 Imprima uma mensagem de saudação com o nome completo para cada um dos objetos. O nome deve ter a primeira letra maiúscula. const Obj = [ { id: 1, nome: "juca", sobrenome: "da silva", idade: 42 }, { id: 2, nome: "daniel", sobrenome: "gonçalves", idade: 21 }, { id: 3, nome: "matheus", sobrenome: "garcia", idade: 28 }, { id: 4, nome: "gabriel", sobrenome: "pinheiro", idade: 21 } ]; for (let i = 0; i < Obj.length; i++) { const b = Obj[i].nome.slice(1); const a = Obj[i].nome.charAt(0).toUpperCase(); console.log("Olá, " + a + b + " " + Obj[i].sobrenome + "!"); }
'use strict'; define(['../app'], function(app){ app.controller('AboutCtrl', function(){ this.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ]; } ); });
function solve() { const [lecture, date] = document.querySelectorAll('input'); const module = document.querySelector('select'); const addButton = document.querySelector('button'); const modules = document.querySelector('.modules'); addButton.addEventListener('click', addModules) function addModules(ev) { ev.preventDefault(); if (lecture.value !== undefined && lecture.value !== '' && date.value !== undefined && date.value !== '' && module.value !== 'Select module') { let trainingName = module.value.toUpperCase() + '-MODULE'; let lectureValue = lecture.value; module.value = module.children[0].value; lecture.value = ''; let dateString = date.value; let ul; if (!(Array.from(modules.children).some(e => e.textContent == trainingName) == true)) { const h3 = e('h3', trainingName); modules.appendChild(h3); ul = document.createElement('ul'); } else { ul = modules.querySelector('ul'); } const li = document.createElement('li'); li.className = 'flex'; const h4 = e('h4', lectureValue + ' - ' + dateString.replaceAll('-', '/').replace('T', ' - ')); const delButton = e('button', 'Del', 'red'); li.appendChild(h4); li.appendChild(delButton); ul.appendChild(li); modules.appendChild(ul); delButton.addEventListener('click', deleteElement) } } function deleteElement(ev) { let ul = ev.target.parentElement.parentElement; ev.target.parentElement.remove(); if (ul.children.length === 0) { ul.parentElement.remove(); } } function e(type, content, className) { const result = document.createElement(type); result.textContent = content; if (className) { result.className = className; } return result; } }
// Dependencies // ============================================================= const express = require("express"); const path = require("path"); // Sets up the Express App // ============================================================= const app = express(); const PORT = process.env.PORT || 8000; // Sets up the Express app to handle data parsing app.use(express.urlencoded({ extended: true })); app.use(express.json()); // store reservation & waitlist data let reservations = [ { customerName: "Kevin", customerEmail: "kevkevwu@example.com", customerID: "kevkevwu", phoneNumber: "000-000-0000", }, ]; let waitlist = []; // routes app.get("/api/tables", (req, res) => { return res.json(reservations); }); app.get("/api/waitlist", (req, res) => { return res.json(waitlist); }); app.listen(PORT, function () { console.log("App listening on PORT " + PORT); });
const mongoose = require("mongoose"); const orangeSellerSchema = new mongoose.Schema({ userName: String, email: String, password: String, description: String, // image: File, }); const Seller = new mongoose.model("Sellers", orangeSellerSchema); module.exports = Seller;
// Electron Desktop window const { app, BrowserWindow } = require('electron'); // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let mainWindow; function createWindow () { // Create the browser window mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }); // and load the index.html of the app. mainWindow.loadFile('index.html'); // mainWindow.loadURL('http://localhost:3000/'); // mainWindow.focus(); // Open the DevTool mainWindow.webContents.openDevTools() }; // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.whenReady().then(createWindow); // Quit when all windows are closed, except on macOS. There, it's common // for applications and their menu bar to stay active until the user quits // explicitly with Cmd + Q. app.on('window-all-closed', () => { if (process.platform != 'darwin') { app.quit(); } }); app.on('activate', () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if(BrowserWindow.getAllWindows().length === 0) { createWindow(); } }); /* without fs */ // // create a server object: // http.createServer((req, res) => { // // add an HTTP Header // res.writeHead(200, {'Content-Type': 'text/html'}); // // write a response to the client // res.write(req.url); // res.write('<br/>The current time: ' + dt.myDataTime()) // // enter this url for testing: http://localhost:8080/?year=2017&month=July // let q = url.parse(req.url, true).query; // let txt = '<br/>' + q.year + ' ' + q.month; // res.write(txt); // // end the response // res.end('<br/>Hello world!'); // }).listen(8080); // the server object listens on port 8080 /* with fs: create a Node.js file that reads the HTML file, and return the content */ // http.createServer((req, res) => { // let q = url.parse(req.url, true); // let filename = '.' + q.pathname + '.html'; // fs.readFile(filename, (err, data) => { // if (err) { // res.writeHead(404, {'Content-Type': 'text/html'}); // return res.write('404 Not Found'); // } // res.writeHead(200, {'Content-Type': 'text/html'}); // res.write(data); // return res.end(); // }); // // create a new file or appends the specified content // // at the end of the specified file // fs.appendFile('myAppendFile.txt', 'Hello content!', (err) => { // if (err) throw err; // console.log('Append Saved!'); // }); // // create/open a file writing, "w" flag is for "writing" // fs.open('myOpenFile.txt', 'w', (err, file) => { // if (err) throw err; // console.log('Open Saved!'); // }); // // replaces the specified file and content // fs.writeFile('myWriteFile.txt', 'This is my text', (err) => { // if (err) throw err; // console.log('Write Saved!'); // }); // }).listen(8080);
import AppContext from './context.services' import useDataFunnel from './hook.services' export { useDataFunnel, AppContext }
export const SOLICITUD_USUARIO_LOGIN = 'SOLICITUD_USUARIO_LOGIN'; export const EXITO_USUARIO_LOGIN = 'EXITO_USUARIO_LOGIN'; export const FALLA_USUARIO_LOGIN = 'FALLA_USUARIO_LOGIN'; export const LOGOUT_USUARIO = 'LOGOUT_USUARIO'; export const SOLICITUD_USUARIO_REGISTRO = 'SOLICITUD_USUARIO_REGISTRO'; export const EXITO_USUARIO_REGISTRO = 'EXITO_USUARIO_REGISTRO'; export const FALLA_USUARIO_REGISTRO = 'FALLA_USUARIO_REGISTRO'; export const REINICIO_USUARIO_REGISTRO = 'REINICIO_USUARIO_REGISTRO';
import React from 'react'; import { Characters } from '../../api/characters'; import { Meteor } from 'meteor/meteor'; import { withTracker } from 'meteor/react-meteor-data'; import { Session } from 'meteor/session'; export class Editor extends React.Component { constructor(props) { super(props); this.state = { name: '', description: '' } } handleNameChange(e) { const name = e.target.value; this.setState({ name }) Meteor.call('characters.update', this.props.character._id, { name }) } handleDescriptionChange(e) { const description = e.target.value; this.setState({ description }) Meteor.call('characters.update', this.props.character._id, { description }) } handleDeleteCharacter() { Meteor.call('characters.remove', this.props.character._id); Session.set('selectedCharacterId', undefined) this.props.appProps.history.push('/dashboard'); } componentDidMount(prevProps, prevState) { this.setState({ name: this.props.character.name, description: this.props.character.description }) } componentDidUpdate(prevProps, prevState) { const currentCharacterId = this.props.character ? this.props.character._id : undefined; const prevCharacterId = prevProps.character ? prevProps.character._id : undefined; if (currentCharacterId && currentCharacterId !== prevCharacterId) { this.setState({ name: this.props.character.name, description: this.props.character.description }) } } render() { return ( <div className="editor__panel"> <input className="editor__title" value={this.state.name} placeholder="Character Name Here" onChange={this.handleNameChange.bind(this)}/> <textarea className="editor__body" value={this.state.description} placeholder="Character Description Here" onChange={this.handleDescriptionChange.bind(this)}></textarea> <div> <button className="button button--secondary" onClick={this.handleDeleteCharacter.bind(this)}>Delete Character</button> </div> </div> ) } }; export default withTracker(() => { const selectedCharacterId = Session.get('selectedCharacterId') return { selectedCharacterId } })(Editor);
const express = require('express'); const { validate } = require('express-jsonschema'); const router = module.exports = express.Router(); const handleRequestModule = require('../../modules/handleRequestModule'); const projectController = require('../../controllers/projectController'); const createProjectScheme = { type: 'object', properties: { projectName: { type: 'string', required: true, } } }; const updateContributorsScheme = { type: 'object', properties: { projectUuid: { type: 'string', required: true, }, contributors: { type: 'array', required: true, items: { type: 'string' } } } }; const addTaskScheme = { type: 'object', properties: { projectUuid: { type: 'string', required: true, }, title: { type: 'string', required: true, }, explanation: { type: 'string', required: true, }, users: { type: 'array', required: true, items: { type: 'string' } }, notes: { type: 'array', required: true, items: { type: 'string' } } } } const updateTaskScheme = { type: 'object', properties: { projectUuid: { type: 'string', required: true, }, taskUUID: { type: 'string', required: true, }, title: { type: 'string', required: true, }, explanation: { type: 'string', required: true, }, users: { type: 'array', required: true, items: { type: 'string' } }, notes: { type: 'array', required: true, items: { type: 'string' } }, completed: { type: 'boolean', required: true, } } } const removeTaskScheme = { type: 'object', properties: { projectUuid: { type: 'string', required: true, }, taskUUID: { type: 'string', required: true, } } } const addReferencekScheme = { type: 'object', properties: { projectUuid: { type: 'string', required: true, }, noteUUID: { type: 'string', required: true, }, referenceText: { type: 'string', required: true, } } } const updateReferencekScheme = { type: 'object', properties: { projectUuid: { type: 'string', required: true, }, noteUUID: { type: 'string', required: true, }, referenceUUID: { type: 'string', required: true, }, referenceText: { type: 'string', required: true, } } } const deleteReferencekScheme = { type: 'object', properties: { projectUuid: { type: 'string', required: true, }, noteUUID: { type: 'string', required: true, }, referenceUUID: { type: 'string', required: true, } } } const addFindingScheme = { type: 'object', properties: { projectUUID: { type: 'string', required: true, }, noteUUID: { type: 'string', required: true, }, findingText: { type: 'string', required: true, } } } const updateFindingScheme = { type: 'object', properties: { projectUUID: { type: 'string', required: true, }, noteUUID: { type: 'string', required: true, }, findingUUID: { type: 'string', required: true, }, findingText: { type: 'string', required: true, }, level: { type: 'string', required: false, } } } const deleteFindingScheme = { type: 'object', properties: { projectUUID: { type: 'string', required: true, }, noteUUID: { type: 'string', required: true, }, findingUUID: { type: 'string', required: true, } } } //projectUUID, taskUUID, title, explanation, users, notes, completed //projectUUID, title, explanation, users, notes /** * Create a new project * @param projectName {string} the project name * @return {object} example: { password: "tempPassword", projectUuid: "projectUuid"} */ router.post('/create/', validate({ body: createProjectScheme }), function (req, res) { handleRequestModule.handleCall(projectController.createProject, req, res); }) /** * Get project info by project UUID * @param uuid {string} project UUID * @return {object} project info */ router.get('/info/:uuid', function (req, res) { handleRequestModule.handleCall(projectController.getProjectInfo, req, res); }) /** * Get project meta by project UUID * @param uuid {string} project UUID * @return {object} project meta */ router.get('/meta/:uuid', function (req, res) { handleRequestModule.handleCall(projectController.getProjectMetaData, req, res); }) /** * Get all projects * @return {array} array of project objects */ router.get('/all/', function (req, res) { handleRequestModule.handleCall(projectController.getAllProjects, req, res); }) /** * Update project contributors * @param projectUuid {string} project uuid * @param contributors {array} of string with userUUID's * @return {string} "Contributors updated." */ router.post('/update/contributors/', validate({ body: updateContributorsScheme }), function (req, res) { handleRequestModule.handleCall(projectController.updateContributors, req, res); }) /** * Get all encrypted projects * @return {array} of encrypted projects */ router.get('/all/encrypted', function (req, res) { handleRequestModule.handleCall(projectController.getAllEncryptedProjects, req, res); }) /** * add task to project * @param projectUuid {string} * @param title {string} * @param explanation {string} * @param users {array} list of user UUID's * @param notes {array} list of notes * @return {string} taskUUID */ router.post('/task/add', validate({ body: addTaskScheme }), function (req, res) { handleRequestModule.handleCall(projectController.addTask, req, res); }) /** * update task * @param projectUuid {string} * @param taskUUID {string} * @param title {string} * @param explanation {string} * @param users {array} list of user UUID's * @param notes {array} list of notes * @param completed {bool} is this task completed? * @return {string} taskUUID */ router.post('/task/update', validate({ body: updateTaskScheme }), function (req, res) { handleRequestModule.handleCall(projectController.updateTask, req, res); }) /** * delete task from this project * @param projectUuid {string} * @param taskUUID {string} */ router.post('/task/delete', validate({ body: removeTaskScheme }), function (req, res) { handleRequestModule.handleCall(projectController.removeTask, req, res); }) /** * Add a reference for this project to an other node * @param projectUuid {string} * @param noteUUID {string} * @param referenceText {string} * @return {object} reference object */ router.post('/reference/add', validate({ body: addReferencekScheme }), function (req, res) { handleRequestModule.handleCall(projectController.addReference, req, res); }) /** * Update a reference for this project * @param projectUuid {string} * @param noteUUID {string} * @param referenceUUID {string} * @param referenceText {string} * @return {object} reference object */ router.post('/reference/update', validate({ body: updateReferencekScheme }), function (req, res) { handleRequestModule.handleCall(projectController.updateReference, req, res); }) /** * Delete a reference * @param projectUuid {string} * @param noteUUID {string} * @param referenceUUID {string} * @return {bool} true if successful */ router.post('/reference/delete', validate({ body: deleteReferencekScheme }), function (req, res) { handleRequestModule.handleCall(projectController.deleteReference, req, res); }) /** * Get all references for this project * @param {string} projectUUID */ router.get('/reference/getAll/:projectUUID', function (req, res) { handleRequestModule.handleCall(projectController.getAllReferences,req, res); }) /** * add a new finding to a project * @param projectUuid {string} * @param noteUUID {string} * @param findingText {string} * @return {object} finding object */ router.post('/finding/add', validate({ body: addFindingScheme }), function (req, res) { handleRequestModule.handleCall(projectController.addFinding, req, res); }) /** * Update a finding * @param projectUuid {string} * @param noteUUID {string} * @param findingUUID {string} * @param findingText {string} * @return {object} finding object */ router.post('/finding/update', validate({ body: updateFindingScheme}), function (req, res) { handleRequestModule.handleCall(projectController.updateFinding, req, res); }) /** * Delete a finding * @param projectUuid {string} * @param noteUUID {string} * @param findingUUID {string} * @return {bool} true if successful */ router.post('/finding/delete', validate({ body: deleteFindingScheme }), function (req, res) { handleRequestModule.handleCall(projectController.deleteFinding, req, res); }) /** * Get all findings for this project * @param {string} projectUUID */ router.get('/finding/getAll/:projectUUID', function (req, res) { handleRequestModule.handleCall(projectController.getAllFindings,req, res); })
var festCollection,eventCollection,collegeCollection,sponsorCollection; $(document).ready(function(){ $("#tabs").tabs().addClass( "ui-tabs-vertical ui-helper-clearfix" ); $( "#tabs li" ).removeClass( "ui-corner-top" ).addClass( "ui-corner-left" ); $.fn.bootstrapBtn = $.fn.button.noConflict(); getFestList(); getSponsors(); }); $(document).on("click","#tab2",function(){ getParticipants(); }); $(document).on("click","#tab3",function(){ getSponsors(); }); $(document).on("click","#tab1",function(){ getFestList(); }); //********************************************************Ajax method setup*******************************// function getRequest(reqMethod,reqURL,reqData){ var responedData = []; $.ajax({ type:reqMethod, url:reqURL, dataType:'json', async:false, contentType:'application/json', data:JSON.stringify(reqData), success:function(data){ responedData.push(data); }, error:function(error,status,xhr){ responedData.push(error); responedData.push(status); responedData.push(xhr); } }); return responedData; } function getFestList(){ $("tbody").html(""); var reqResponse = getRequest('GET','xyz/fest/getAllFest',''); console.log("From get Festlist"+reqResponse); var data = reqResponse[0]; festCollection = data; for(var i=0;i<data.length;i++){ var newFormattedDate = setDateFormat(data[i].startDate); var $row = $("<tr class='bg-info'>" + "<td class='td_cls'>"+data[i].festName+"</td><td class='td_cls'>"+newFormattedDate+"</td><td class='td_cls'>"+data[i].duration+"</td>" + "<td class='td_cls'><button class='btn btn-success btn-xs view_details_button' id='view_details"+data[i].festId+"'>View Detail</button></td>" + "<td class='td_cls'><button class='btn btn-primary btn-xs update_fest_button' id='update_fest"+data[i].festId+"'>Update</button></td>" + "<td class='td_cls'><button class='btn btn-danger btn-xs' id='fest_delete_button'>Delete</button></td></tr>").appendTo("#fest_tbody"); $("#view_details"+data[i].festId).prop("fest",data[i]); $row.prop("fest",data[i]); } } $(document).on("click",".view_details_button",function(){ var $fest = $("#"+this.id).prop("fest"); getFestEvents($fest); }); function getFestEvents(fest){ var festEventsDialog = $("<div id='fest_event_dialog' title='Event List For "+fest.festName+"'><table class='table' style='width:800px;'><thead><tr class='bg-info'><th class='td_cls'>Event</th>" + "<th class='td_cls'>Type</th><th class='td_cls'>1st Price</td><th class='td_cls'>2nd Price</th><th class='td_cls'>3rd Price</th>" + "<th class='td_cls'>&nbsp;</th></thead><tfoot><tr class='bg-infor'><td class='td_cls'>&nbsp;</td></tr><tr class='bg-info'><td class='td_cls' colspan='6' style='color:red'>*Mouse over on SLOTS to view slot details.</td></tr></tfoot><tbody></tbody></tr></table></div>"); var response = getRequest("GET","xyz/events/getfestevents/"+fest.festId,""); console.log("From getFestEvents "+response); var data = response[0]; if(data.length>0){ console.log(data); for(var i=0;i<data.length;i++){ var $slrow = $("<tr class='bg-info'><td class='td_cls'>"+data[i].eventName+"</td><td class='td_cls'>"+data[i].eventType+"</td>" + "<td class='td_cls'>"+data[i].firstPrice+"</td><td class='td_cls'>"+data[i].secondPrice+"</td>" + "<td class='td_cls'>"+data[i].thirdPrice+"</td><td class='td_cls view_slots' id='view_slots"+data[i].eventId+"'>Slots</td></tr>"); $slrow.prop("slotsList",data[i]); festEventsDialog.find("tbody").append($slrow); } festEventsDialog.dialog({ width:800, height:'auto', modal:'true', buttons:{ OK:function(){ $(this).dialog('close'); $(this).remove(); } } }); }else{ festEventsDialog.html("<h5>No Event Assigned</h5>") } festEventsDialog.dialog({ width:'auto', height:'auto', modal:'true', close:function(){ $(this).dialog("close"); $(this).remove(); }, buttons:{ OK:function(){ $(this).dialog('close'); $(this).remove(); } } }); } $(document).on("click",".update_fest_button",function(){ var $updatingFest = $(this).parents("tr:first").prop("fest"); updateFest($updatingFest); }); //////////////////////////////////// Dialog Using Bootstrap ////////////////////////////////////////////////// function updateFest(updatingFest){ var start = updatingFest.festStart; var end = updatingFest.festEnd; var finalStart = start.split(":")[0]; var finalEnd = end.split(":")[0]; var $updateDialog = $("<div id='update_dailog' class='modal fade' role='dialog' tabindex='-1'>" + "<div class='modal-admin'><div class='modal-content'><div class='modal-header'><button type='button' class='close' data-dismiss='modal'>&times;</button>" + "<h4 class='modal-title'>Update Fest</h4></div><div class='modal-body'>" + "<div class='row'><div class='col-md-4'>S.No.</div><div class='col-md-8'><input type='text' id='update_fest_id' value='"+updatingFest.festId+"' disabled='disabled'/></div></div>"+ "<div class='row'><div class='col-md-4'>Name:</div><div class='col-md-8'><input type='text' id='update_fest_name' value='"+updatingFest.festName+"'/></div></div>"+ "<div class='row'><div class='col-md-4'>Start Date:</div><div class='col-md-8'><input type='text' id='update_fest_date' value='"+updatingFest.startDate+"'/></div></div>" + "<div class='row'><div class='col-md-4'>Duration:</div><div class='col-md-8'><input type='text' id='update_fest_duration' value='"+updatingFest.duration+"'/></div></div>"+ "<div class='row'><div class='col-md-4'>Start Hour:</div><div class='col-md-8'><select id='update_fest_start' class='watch'></select>&nbsp;<select id='update_start_minute' class='watch'></select>&nbsp;<select class='watch' id='startClock'><option value='1'>AM</option><option value='2'>PM</option></select></div></div>" + "<div class='row'><div class='col-md-4'>End Hour:</div><div class='col-md-8'><select id='update_fest_end' class='watch'></select>&nbsp;<select id='update_end_minute' class='watch' ></select>&nbsp;<select class='watch' id='endClock'><option value='1'>AM</option><option value='2'>PM</option></select></div></div>" + "</div><div class='modal-footer'><button type='button' id='update_button' class='btn btn-default'>Update</button><button type='button' class='btn btn-default update_close' data-dismiss='modal'>Close</button></div></div></div></div>"); $(this).prop("data-toggle","modal"); $(this).prop("data-target",$updateDialog); $updateDialog.find("#update_button").prop("updatingFest",updatingFest); for(var i=1;i<=12;i++){ var $hours = $("<option value="+i+">"+i+"</option>"); $updateDialog.find("#update_fest_start,#update_fest_end").append($hours); } for(var j=0;j<=59;j++){ var $minutes = $("<option value="+j+">"+j+"</option>"); $updateDialog.find("#update_start_minute,#update_end_minute").append($minutes); } $updateDialog.modal({keyboard: true,backdrop: true});// {keyboard: true} or tab index='-1' To enable escape close functionality $updateDialog.find("#update_fest_date").datepicker({ minDate:0, altFormat: "dd-MM-YYYY" }); if(parseInt(finalStart)>12){ $updateDialog.find("#startClock option[value='2']").attr("selected",true); finalStart = Math.abs(12-parseInt(finalStart)); $updateDialog.find("#update_fest_start option[value='"+parseInt(finalStart)+"']").attr("selected",true); }else{ $updateDialog.find("#startClock option[value='1']").attr("selected",true); $updateDialog.find("#update_fest_start option[value='"+parseInt(finalStart)+"']").attr("selected",true); } if(parseInt(finalEnd)>12){ $updateDialog.find("#endClock option[value='2']").attr("selected",true); finalEnd = Math.abs(12-parseInt(finalEnd)); $updateDialog.find("#update_fest_end option[value='"+parseInt(finalEnd)+"']").attr("selected",true); }else{ $updateDialog.find("#endClock option[value='1']").attr("selected",true); finalEnd = parseInt(finalEnd); $updateDialog.find("#update_fest_end option[value='"+parseInt(finalEnd)+"']").attr("selected",true); } var tempField = '' $updateDialog.find("input[type='text']").on("focus",function(){ tempField = this.value; $(this).val(""); $updateDialog.find("h6").remove(); }); $updateDialog.find("input[type='text']:not('#update_fest_date')").on("focusout",function(){ if(this.value==""){ this.value = tempField; } }); } $(document).on("hidden","#update_dailog",function (){ $(this).data('modal', null); }); $(document).on("hidden","#update_dailog,.modal fade",function(){ $(this).remove();// to remove added modal from body }); $(document).on("click","#update_button",function(){ $("#update_dailog").find("h6").remove(); var validationMsg = ""; var param = {}; if($("#update_fest_id").val()!="") param.festId = $("#update_fest_id").val(); if($("#update_fest_name").val().trim()!="" && $("#update_fest_name").val().trim().length>2 && isNaN($("#update_fest_name").val().trim())){ param.festName = $("#update_fest_name").val().trim(); }else{ validationMsg = validationMsg + "Name, "; } if($("#update_fest_date").datepicker("getDate")!="" && $("#update_fest_date").datepicker("getDate")>new Date("January 1, 1970")){ param.startDate = reverseDateFormat(new Date($("#update_fest_date").datepicker("getDate"))); }else{ validationMsg = validationMsg + "Date,"; } if($("#update_fest_duration").val()!=""){ param.duration = $("#update_fest_duration").val(); }else{ validationMsg ='Duration, '; } var updateStartTime = getStartTime($("#update_fest_start").val(), $("#update_start_minute").val(), $("#startClock").val()); var updateEndTime = getEndTime($("#update_fest_end").val(),$("#update_end_minute").val(), $("#endClock").val()); param.sponsor = $(this).prop("updatingFest").sponsor; param.festStart = updateStartTime; param.festEnd = updateEndTime; param.festInvestment = 0; param.totalInvestment = 0; if(validationMsg==""){ var responseData = getRequest("POST",'xyz/fest/updateFest',param) console.log(responseData); var data = responseData[0]; if(data.message!=null){ $(this).parents(".modal-footer").siblings(".modal-body").html("<h6>"+data.message+"</h6>"); $(this).parents(".modal-footer").html("<button type='button' id='ok_button' class='btn btn-default' data-dismiss='modal'>OK</button>"); }else if(data.responseJSON.errorMessage!=null){ $("<h6 style='color:red;' > "+data.responseJSON.errorMessage+"</h6>").insertBefore($("#update_dailog").find(".modal-footer")); } }else{ $("<h6 style='color:red;'> Invalid "+validationMsg+"</h6>").insertBefore($(this).parents(".modal-footer")); } }); $(document).on("click","#fest_delete_button",function(){ deleteFest($(this).parents("tr").prop("fest")); }); function deleteFest(deletingFest){ console.log(festCollection.length); var delFest = null; deletingFest!=null?delFest=deletingFest:null; var responseData = getRequest("DELETE", "xyz/fest/deleteFest", delFest) console.log("From Delete Fest"+responseData); var data = responseData[0]; if(data.message!=null){ var index = festCollection.indexOf(deletingFest); festCollection.splice(index,1); var $respDialog = $("<div id='resp_dialog'><h6>"+data.message+"</h6></div>"); $respDialog.dialog({ width:'auto', height:'auto', modal:'true', resizable:false, buttons:{ OK:function(){ $(this).dialog("close"); $(this).remove(); } } }); getFestList(); } } function getSponsors(){ $("#sponsor_tbody").html(""); var responseData = getRequest("GET", "xyz/sponsor/getSponsors", "") console.log("From getSponsors"+responseData); var data = responseData[0]; console.log(data); if(data.length!=0){ $("#sponsor_table").css("display","block"); sponsorCollection = data; /*console.log(sponsorCollection);*/ for(var q=0;q<data.length;q++){ var $sprow = $("<tr class='bg-info'><td class='td_cls'>"+data[q].sponsorId+"</td><td class='td_cls'>"+data[q].sponsorName+"</td><td class='td_cls'><button class='btn btn-info btn-xs fest' id='fest_"+data[q].sponsorId+"'>Fest List</button></td><td class='td_cls'><button class='btn btn-info btn-xs event' id='event_"+data[q].sponsorId+"'>Event List</button></td></tr>"); $sprow.prop("spObject",data[q]); $("#sponsor_tbody").append($sprow); } } } function getParticipants(){ $("#participant_tbody").html(""); var responseData = getRequest("GET", "xyz/participants/getparticipants", ""); console.log("From Get participants"+responseData); var data = responseData[0]; if(data.length!=0){ $("#participant_table").css("display","block"); for(var w=0;w<data.length;w++){ var row = $("<tr class='bg-info'><td class='td_cls'>"+w+1+"</td><td class='td_cls'>"+data[w].participantName+"</td><td class='td_cls'>"+data[w].stream+"</td>" + "<td class='td_cls'>"+data[w].college.collegeName+"</td><td class='td_cls'>"+data[w].enrolmentNo+"</td><td class='td_cls'>"+data[w].mobile+"</td>" + "<td class='td_cls'>"+data[w].event.eventName+"</td><td class='td_cls'>"+data[w].email+"</td></tr>"); row.appendTo($("#participant_tbody")); } } } $(document).on("click",".event",function(){ getSponsorEventList(((($(this)).parent()).parent()).prop("spObject")); }); $(document).on("click",".fest",function(){ getSponsorFestList(((($(this)).parent()).parent()).prop("spObject")); }); function getSponsorFestList(fsponsor){ var id = fsponsor.sponsorId; var responseData = getRequest("GET", "xyz/sponsor/getSponsorFest/"+id, ""); var data = responseData[0]; console.log(data); console.log("From Get Sponsor Fest List "+data+"---"+responseData[0]+"--"+responseData[1]+"--"+responseData[2]); if(!data.message){ var $fDialog = $("<div id='sponsorFestDialog'><table class='table'><thead><th>Fest Id</th><th>Name</th><th>Amount</th><th>Sponsor</th></thead><tfoot></tfoot><tbody id='fest_body'></tbody></table></div>"); for(var z=0;z<data.length;z++){ var $fdr = $("<tr class='bg-info'><td class='td_cls'>"+data[z].festId+"</td><td class='td_cls'>"+data[z].festName+"</td><td class='td_cls'>"+data[z].investmentAmount+"</td><td class='td_cls'>"+fsponsor.sponsorName+"</td></tr>"); $fDialog.find("#fest_body").append($fdr); } $("body").append($fDialog); $fDialog.dialog({ height:'auto', width:'auto', modal:true, resizable:false, buttons:{ OK:function(){ $(this).dialog("close"); $(this).remove(); } } }); }else{ var $noFestDialog = $("<div><h6 style='color:red;'>No Fest Sponsored.</h6></div>"); $noFestDialog.dialog({ width:'auto', height:'auto', resizable:'false', buttons:{ OK:function(){ $(this).dialog("close"); $(this).remove(); } } }); } } function getSponsorEventList(sponsor){ var id = sponsor.sponsorId; var responseData = getRequest("GET", "xyz/sponsor/getSponsorEvent/"+id,""); var data = responseData[0]; console.log("From getSponsorEventList "+responseData); if(!data.message){ var $eDialog = $("<div id='sponsorEventDialog'><table class='table'><thead><th>Event Id</th><th>Name</th><th>Amount</th><th>Sponsor</th></thead><tfoot></tfoot><tbody id='event_body'></tbody></table></div>"); for(var z=0;z<data.length;z++){ var $edr = $("<tr class='bg-info'><td class='td_cls'>"+data[z].eventId+"</td><td class='td_cls'>"+data[z].eventName+"</td><td class='td_cls'>"+data[z].investmentAmount+"</td><td class='td_cls'>"+sponsor.sponsorName+"</td></tr>"); $eDialog.find("#event_body").append($edr); } $eDialog.dialog({ height:'auto', width:'auto', modal:true, resizable:false, buttons:{ OK:function(){ $(this).dialog("close"); $(this).remove(); } } }); }else{ var $noFestDialog = $("<div><h6 style='color:red;'>No Event Sponsored.</h6></div>"); $noFestDialog.dialog({ width:'auto', height:'auto', resizable:'false', buttons:{ OK:function(){ $(this).dialog("close"); $(this).remove(); } } }); } } $(document).on("click","#create_fest",function(){ if($("#form_dialog")){ $("#form_dialog").remove(); } var $sponsor =""; var $crDialog = $("<div id='form_dialog' title='Add Fest..'><table class='table'>" + "<tr><td class='td_cls'>Fest Name:</td><td class='td_cls'><input type='text' id='fest_name' placeholder='Fest Name'/></td></tr>"+ "<tr id='sponsor_row'><td class='td_cls'>Sponsor:</td><td class='td_cls'><select id='sponsor_select' ><option value='-1'>Select Sponsor</option></select>" + "&nbsp;<button id='addSponsor' class='btn btn-info btn-xs'>Add</button></td></tr>"+ "<tr><td class='td_cls'>Amount:</td><td class='td_cls'><input type='text' id='investment' placeholder='Rs.'></td></tr>"+ "<tr><td class='td_cls'>Duration:</td><td class='td_cls'><input type='text' id='duration' placeholder='No. of Days' /></td></tr>" + "<tr><td class='td_cls'>Start Date:</td><td class='td_cls'><input type='text' id='datepicker' placeholder='Select Date' /></td></tr>" + "<tr><td class='td_cls'>Start Time:</td><td class='td_cls'><select id='fest_start_hours' class='watch' placeholder='HH'></select>" + "<span> : </span><select id='fest_start_minutes' placeholder='MM' class='watch'></select><span> : </span><select id='start_format' class='watch'>" + "<option value=1>AM</option><option value=2>PM</option></select></td></tr>" + "<tr id='insert_hear'><td class='td_cls'>End Time:</td><td class='td_cls'><select id='fest_end_hours' placeholder='HH' class='watch'></select>" + "<span> : </span><select id='fest_end_minutes' placeholder='MM' class='watch' ></select><span> : </span><select id='end_format'class='watch'>" + "<option value=1>AM</option><option value=2>PM</option></select><h6>*Time Format 12 Hour</h6></td></tr></table></div>"); for(var i=0;i<=12;i++){ var $hours = $("<option val="+i+">"+i+"</option>"); $crDialog.find("#fest_start_hours,#fest_end_hours").append($hours); } for(var j=0;j<=59;j++){ var $minutes = $("<option val="+j+">"+j+"</option>"); $crDialog.find("#fest_start_minutes,#fest_end_minutes").append($minutes); } $crDialog.dialog({ width:'auto', height:'auto', resizable: false, modal:true, close:function(){ $(this).dialog("close"); $(this).remove(); }, buttons:{ Save:function(){ var validationMap = new Map(); validationMap.set("name",($("#fest_name").val()).trim()); validationMap.set("duration",($("#duration").val()).trim()); validationMap.set("date",new Date($("#datepicker").datepicker("getDate"))); validationMap.set("startHours",$("#fest_start_hours").val()); validationMap.set("endHours",$("#fest_end_hours").val()); validationMap.set("sponsor",$("#sponsor_select").val()); validationMap.set("amount",$("#investment").val().trim()); var flag1 = getFestValidate(validationMap); if(flag1==""){ var startTime = getStartTime($("#fest_start_hours").val(),$("#fest_start_minutes").val(),$("#start_format").val()); var endTime = getEndTime($("#fest_end_hours").val(),$("#fest_end_minutes").val(),$("#end_format").val()); var reverseFomattedDate = reverseDateFormat(new Date($("#datepicker").datepicker("getDate"))); var $param = { festId:'', festName:($("#fest_name").val()).trim(), sponsor:[$sponsor], duration:$("#duration").val(), startDate:reverseFomattedDate, festStart:startTime, festEnd:endTime, festInvestment:'', totalInvestment:'' }; var responseData = getRequest("POST", "xyz/fest/addFest/"+$("#investment").val(), $param); console.log("From Create Fest"+responseData) var data = responseData[0]; if(data.message){ getFestList(); getParticipants(); getSponsors(); $crDialog.remove(); var $promptDialog = $("<div id='propmt_dialog' title='Success..'><p>"+data.message+"</p><p>Would you like to create events for this Fest?</p></div>"); $promptDialog.prop("festDetail",data.obj); $promptDialog.dialog({ width:'auto', height:'auto', resizable:false, modal:true, buttons:{ Create:function(){ createEvent($(this).prop("festDetail")); $(this).dialog("close"); $(this).remove(); }, Cancel:function(){ $(this).dialog("close"); $(this).remove(); } } }); } }else{ if($("#validation_row").length==0){ $("<tr id='validation_row'><td style='color:red;' colspan='2'><h6>Invalid "+flag1+"</h6></td></tr>").insertAfter("#insert_hear"); }else{ $("#validation_row").remove(); $("<tr id='validation_row'><td style='color:red;' colspan='2'><h6>Invalid "+flag1+"</h6></td></tr>").insertAfter("#insert_hear"); } } }, Cancel:function(){ $(this).dialog("close"); $(this).remove(); } } }); $("#sponsor_select").on("change",function(){ $sponsor = $(this).find("option:selected").prop("sponsor"); }); $("#datepicker").datepicker({ minDate: 0 }).datepicker("setDate", new Date()); if(sponsorCollection.length!=0){ for(var w=0;w<sponsorCollection.length;w++){ var $sponsorOption = $("<option id='"+sponsorCollection[w].sponsorId+"'value='"+sponsorCollection[w].sponsorId+"'>"+sponsorCollection[w].sponsorName+"</option>"); $sponsorOption.prop("sponsor",sponsorCollection[w]); $("#sponsor_select").append($sponsorOption); } } }); //------------------------------------------------------------Utility Methods-----------------------------------------------------------// //////////////////////////////Date Format Changer Method////////////////////////////////////////////////// function setDateFormat(getDate){ var formattedDate = ""; var dt = new Date(getDate); formattedDate = dt.getDate()+"-"+(dt.getMonth()+1)+"-"+dt.getFullYear(); return formattedDate; } function reverseDateFormat(getDate){ var reverseDate = ""; reverseDate = getDate.getFullYear()+"-"+(getDate.getMonth()+1)+"-"+getDate.getDate(); return reverseDate; } /////////////////////////////////////Method to set AM or PM in 12 hour time////////////////////////////// function getStartTime(startHour,startMinute,startFormat){ var $startHour; var $festStartMinutes; //Event Start Timings if((startHour!=12) && startFormat==2){ //if Event starts in evening $startHour = parseInt(startHour)+12; $festStartMinutes = parseInt(startMinute); }else if((startHour==12) && startFormat==2){ //if Event starts at 12:00pm afternoon $startHour = parseInt(startHour); $festStartMinutes = parseInt(startMinute); }else{ // if Event Starts in morning $startHour = parseInt(startHour); $festStartMinutes = parseInt(startMinute); } return $startHour+":"+$festStartMinutes+":"+"00"; } function getEndTime(endHour,endMinute,endFormat){ var $endHour; var $festEndMinutes; //Event End Timings if((endHour<12) && endFormat==2){ //if fest end in evening but before 12Am and after 12PM $endHour = parseInt(endHour)+12; $festEndMinutes = parseInt(endMinute); }else if(endHour==12 && endMinute==0 && endFormat==2){ $endHour = parseInt(endHour)+11; $festEndMinutes = parseInt(endMinute)+59; }else if(endHour==12 && endMinute!=0 && endFormat==2){ $endHour = parseInt(endHour); $festEndMinutes = parseInt(endMinute); }else{ // if fest is going to end bfore 12pm means in morning or equal to 12Pm $endHour = parseInt(endHour); $festEndMinutes = parseInt(endMinute); } return $endHour+":"+$festEndMinutes+":"+"00"; } //************************************************************************************************************************************************// $(document).on("click","#addSponsor",function(){ if($("#add_sponsor_row").length==0){ var $Sponsorrow = $("<tr id='add_sponsor_row'><td class='td_cls'>Sponsor Name</td><td class='td_cls'><input type='text' id='sponsor_name' placeholder='Sponsor Name'>" + "<button id='save_spnosor' class='btn btn-success btn-xs'>Save</button>&nbsp;<button id='cancel_spnosor' class='btn btn-danger btn-xs' >Cancel</button></td></tr>"); $Sponsorrow.insertAfter($("#sponsor_row")); $(this).prop("disabled",true); } }); $(document).on("change","#sponsor_select",function(){ /*console.log("change called");*/ /*console.log($(this).find(":selected").prop("sponsor"));*/ }); $(document).on("click","#save_spnosor",function(){ if($("#sponsor_name").val().trim()!="" || $("#sponsor_name").val().trim().length>2){ var param = { sponsorId:'', sponsorName:$("#sponsor_name").val(), } var responseData = getRequest("POST", "xyz/sponsor/addSponsor?flag="+"", param); console.log("From Save Sponsor"+responseData); var data = responseData[0]; var $tempSpOpt = $("<option id='"+data.obj.sponsorId+"'>"+data.obj.sponsorName+"</option>"); $tempSpOpt.prop("sponsor",data.obj); $("#sponsor_select").append($tempSpOpt); $("<span id='sadded' style='color:red'>Added</span>").insertAfter($("#addSponsor")); $("#sadded").delay("slow").fadeOut(); $("#cancel_spnosor").trigger("click"); } }); $(document).on("click","#cancel_spnosor",function(){ $(this).parent().parent().remove(); }); $(document).on("click","#create_Event",function(){ getSponsors(); getParticipants(); createEvent(festCollection); }); function createEvent(fest){ var $selectedFest =''; if(fest){ var $eventDialog = getEventDailog(fest); var $availableEvents = ["CONFERENCE", "WORKSHOP", "TECHFEST", "CODE_EVENT", "DANCE", "CULTURAL"]; /*if(fest.length>=1){*/ $eventDialog.dialog({ width:'auto', height:'auto', resizable:false , modal:true, close:function(){ $(this).dialog("close"); $(this).remove(); }, buttons:{ Save:function(){ if($.isArray(fest)){ $selectedFest = $("#fest_list").find(":selected").prop("selectedFest"); }else{ $selectedFest = fest; } ///////////////////////////***********Event Fields Validation*********************************//////////// var msge =""; if($("#event_name").val().trim()=="" || !isNaN($("#event_name").val().trim()) || $("#event_name").val().trim().length<=1 || $("#event_name").val().trim().length>=100){ msge = msge + " Name,"; mark($("#event_name")); } if($("#event_exp").val().trim()=="" || isNaN($("#event_exp").val().trim()) || parseInt($("#event_exp").val().trim())<=0){ msge = msge + " Expenditure,"; mark($("#event_exp")); } if($("#event_investment").val().trim()=="" || isNaN($("#event_investment").val().trim()) || parseInt($("#event_investment").val().trim())<=0){ msge = msge + " Investment Amount,"; mark($("#event_investment")); } if($("#first_price").val().trim()=="" || isNaN($("#first_price").val().trim()) || parseInt($("#first_price").val().trim())<=0 || parseInt($("#first_price").val().trim())>=parseInt($("#event_exp").val().trim())){ msge = msge + " 1st Price," mark($("#first_price")); } if($("#second_price").val().trim()=="" || isNaN($("#second_price").val().trim()) || parseInt($("#second_price").val().trim())<=0 || parseInt($("#second_price").val().trim())>=parseInt($("#event_exp").val().trim())){ msge = msge + " 2nd Price,"; mark($("#second_price")); } if($("#third_price").val().trim()=="" || isNaN($("#third_price").val().trim()) || parseInt($("#third_price").val().trim())<=0 || parseInt($("#third_price").val().trim())>=parseInt($("#event_exp").val().trim())){ msge = msge + " 3rd Price,"; mark($("#third_price")); } if($("#event_ypes").val()==""){ msge = msge + " Event Types,"; mark($("#event_ypes")); } if($("#fest_list").val()=="-1"){ msge = msge + " Fest,"; mark($("#fest_list")); } if($("#duration_hour").val()=="" || isNaN($("#duration_hour").val()) || parseInt($("#duration_hour").val())<=0){ msge = msge + " Duration Hours"; mark($("#duration_hour")); }else if($("#fest_list").val()!="-1"){ var dr = parseInt(fest.festEnd)-parseInt(fest.festStart); if(parseInt($("#duration_hour").val())>parseInt(fest.festEnd)-parseInt(fest.festStart)){ msge = msge + " Hours should not more than "+dr; } } if($("#event_sponsor").val()=="-1"){ msge = msge + " Sponsor,"; mark($("#event_sponsor")); } if(msge==""){ var param = { eventId:'', eventName:$("#event_name").val(), expenditure:$("#event_exp").val(), firstPrice:$("#first_price").val(), secondPrice:$("#second_price").val(), thirdPrice:$("#third_price").val(), eventType:$("#event_ypes").val(), eventHours:$("#duration_hour").val(), fest:$selectedFest, slots:null, sponsors:[$("#event_sponsor").find(":selected").prop("object")] }; var responseData = getRequest("POST", "xyz/events/addEvent/"+$("#event_investment").val(), param); console.log("from create Event "+responseData); var data = responseData[0]; $eventDialog.remove(); var $promptDialog = $("<div id='propmt_dialog' title='Message..'></div>"); if(data.message!=null){ var responseMsg = $("<p>"+data.message+"</p>").appendTo($promptDialog); $("body").append($promptDialog); }else if(data.errorMessage!=null){ var responseMsg = $("<p>"+data.errorMessage+"</p>").appendTo($promptDialog); $("body").append($promptDialog); } $promptDialog.dialog({ width:'auto', height:'auto', modal:'true', resizable:false, buttons:{ OK:function(){ $(this).dialog('close'); $(this).remove(); } }, }); }else{ if($eventDialog.find("textarea").length!=0){ $eventDialog.find("textarea").remove(); } $("<textarea rows='3' cols='50' disabled='disabled'> Invalid :"+msge+"</textarea>").insertAfter($eventDialog.find("table")); } }, Cancel:function(){ $(this).dialog('close'); $(this).remove(); } } }); if(sponsorCollection.length!=0){ for(var n=0;n<sponsorCollection.length;n++){ var $sopt = $("<option id='"+sponsorCollection[n].sponsorId+"' value='"+sponsorCollection[n].sponsorId+"'>"+sponsorCollection[n].sponsorName+"</option>"); $sopt.prop("object",sponsorCollection[n]); $eventDialog.find("#event_sponsor").append($sopt); } } $eventDialog.find("#addSponsor").on("click",function(){ if($("#added").length!=0){ $("#added").remove(); } if($("#new_row").length==0){ $(this).prop("disabled",true); var $asr = $("<tr id='new_row'><td class='td_cls'>Sponsor Name:</td><td class='td_cls'><input type='text' id='new_sponsor' placeholder='Sponsor Name' />&nbsp;<button id='save_sponsor' class='btn btn-success btn-xs'>Save</button>&nbsp;<button id='cancel_sponsor' class='btn btn-danger btn-xs'>Cancel</button></td></tr>"); $asr.insertAfter($eventDialog.find("#select_row")); $("#new_sponsor").on("focus",function(){ $("#new_sponsor").addClass("unvalidate_css"); $("#new_sponsor").val(""); }); $("#save_sponsor").on("click",function(){ if($("#new_sponsor").val()!='' && $("#new_sponsor").val().trim().length>=3){ var param = { sponsorId:'', sponsorName:$("#new_sponsor").val(), } var responseData = getRequest("POST","xyz/sponsor/addSponsor?flag="+"" , param); console.log("From Add Sponsor from event"+responseData); var data = responseData[0]; sponsorCollection.push(data.obj); var $tempOpt = $("<option value='"+data.obj.sponsorId+"'>"+data.obj.sponsorName+"</option>"); $tempOpt.prop("object",data.obj); $eventDialog.find("#event_sponsor").append($tempOpt); $("#cancel_sponsor").trigger("click"); $("<span stype='color:red;'id='added'> Added</span>").insertAfter($eventDialog.find("#addSponsor")); $("#added").delay("slow").fadeOut(); }else{ $("#new_sponsor").removeClass("unvalidate_css"); $("#new_sponsor").addClass("validation_css"); $("#new_sponsor").val("Required"); } }); $("#cancel_sponsor").on("click",function(){ $("#new_row").remove(); $("#addSponsor").prop("disabled",false); }); } }); $eventDialog.find("#event_ypes").autocomplete({ source:$availableEvents }); }else{ var $festWarn = $("<div>There is no Fest to assign Event. Please Create Fest First.</div>"); $festWarn.dialog({ height:'auto', width:'auto', modal:true, resizable:false, close:function(){ $(this).dialog("close"); $(this).remove(); }, buttons:{ OK:function(){ $(this).dialog("close"); $(this).remove(); } } }); } } function mark(ot){ if(!ot.siblings('span').length!=0){ $("<span style='color:red;' id='valid_span'>*</span>").insertAfter(ot); } } $(document).on("focus",".for_valid",function(){ $(this).removeClass("validation_css"); $(this).siblings('span').remove(); }); function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function getEventDailog(fest){ var $d = $("<div id='event_dialog' title='Create Event..' style='word-wrap:break-word'><table class='table'><tr><td class='td_cls'>Fest:</td><td class='td_cls' id='fest_name'></td></tr>" + "<tr><td class='td_cls'>Starts From</td><td class='td_cls' id='start_from'></td></tr>" + "<tr><td class='td_cls'>Duration</td><td class='td_cls' id='fest_duration'></td></tr>" + "<tr><td class='td_cls'>Slots</td><td class='td_cls' id='fest_slots'></td></tr>" + "<tr><td class='td_cls'>Event Name:</td><td class='td_cls'><input type='text' id='event_name' class='for_valid'/></td></tr>" + "<tr><td class='td_cls'>Type of Event:</td><td class='td_cls'><input id='event_ypes' class='for_valid' placeholder='Ex: CONFERENCE, WORKSHOP, TECHFEST' /></td></tr>" + "<tr id='select_row'><td class='td_cls'>Sponsor:</td><td class='td_cls'><select id='event_sponsor' class='for_valid'><option value='-1'>Select Sponsor</option></select>&nbsp;<button id='addSponsor' class='btn btn-primary btn-xs'>Add</button></td></tr>"+ "<tr><td class='td_cls'>Amount:</td><td class='td_cls'><input type='text' id='event_investment' class='for_valid' placeholder='Rs.'></td></tr>"+ "<tr><td class='td_cls'>Approx Expenditure:</td><td class='td_cls'><input type='text' id='event_exp' class='for_valid' /></td></tr>" + "<tr><td class='td_cls'>First Price:</td><td class='td_cls'><input type='text' id='first_price' class='for_valid' /></td></tr>" + "<tr><td class='td_cls'>Second Price:</td><td class='td_cls'><input type='text' id='second_price' class='for_valid' /></td></tr>" + "<tr><td class='td_cls'>Third Price:</td><td class='td_cls'><input type='text' id='third_price' class='for_valid' /></td></tr>" + "<tr><td class='td_cls'>Event Hours</td><td class='td_cls'><input type='text' id='duration_hour' class='watch for_valid' placeholder='1 or 2' />" + "</td></tr></table><textarea rows='4' cols='40' disabled='disabled'>*Event duration would be up to One hours. \n Event Hours should not be more than \n available slots. " + "Each Slot can have one type event only.</textarea></div>"); if(fest!=null){ if(fest.length>=1){ var $select = $("<select id='fest_list' class='for_valid'><option value='-1' class='td_cls'>Select Fest</option></select>"); for(var i=0;i<fest.length;i++){ var opt = $("<option val='"+fest[i].festId+"' class='td_cls'>"+fest[i].festName+"</option>"); opt.prop("selectedFest",fest[i]); $select.append(opt); } $d.find("#fest_name").html($select); }else{ $d.find("#fest_name").html(fest.festName); $d.find("#start_from").html(setDateFormat(fest.startDate)); $d.find("#fest_duration").html(fest.duration+" Days"); $d.find("#fest_slots").html((parseInt(fest.festEnd)-parseInt(fest.festStart))*fest.duration); } } return $d; } $(document).on("change","#fest_list",function(){ if($(this).find(":selected").val()!="-1"){ $("#event_dialog").find("#start_from").html(setDateFormat($(this).find(":selected").prop("selectedFest").startDate)); $("#event_dialog").find("#fest_duration").html($(this).find(":selected").prop("selectedFest").duration+" Days"); console.log(parseInt(($(this).find(":selected").prop("selectedFest").festEnd))-parseInt(($(this).find(":selected").prop("selectedFest").festStart))); $("#event_dialog").find("#fest_slots").html($(this).find(":selected").prop("selectedFest").duration*(parseInt(($(this).find(":selected").prop("selectedFest").festEnd))-parseInt(($(this).find(":selected").prop("selectedFest").festStart)))); }else{ $("#event_dialog").find("#start_from").html(""); $("#event_dialog").find("#fest_duration").html(""); $("#event_dialog").find("#fest_slots").html(""); } }); $(document).on('mouseover','.view_slots',function(){ var $slots = (($(this)).parent()).prop("slotsList").slots; showSlots($slots,this.id); }); $(document).on('mouseout','.view_slots',function(){ $('body').find("#slot_list_dialog").remove(); }); function showSlots(rdx,id){ var $slotsDialog = $("<div id='slot_list_dialog'><table class='table slot_table'><tr class='bg-info'><td class='td_cls'>S No.</td><td class='td_cls'>Date</td>" + "<td class='td_cls'>From</td><td class='td_cls'>To</td></tr></table></div>"); for(var k = 0;k<rdx.length;k++){ var newSlotDate = setDateFormat(rdx[k].slotDate); var $slRow1 = $('<tr><td class="td_cls">'+(k+1)+'</td><td class="td_cls">'+newSlotDate+'</td><td class="td_cls">'+rdx[k].startTime+'</td><td class="td_cls">'+rdx[k].endTime+'</td></tr>'); $slotsDialog.find(".slot_table").append($slRow1); } $slotsDialog.dialog({ width:'auto', height:'auto', resizable:false, modal:false, close:function(){ $(this).dialog("close"); $(this).remove(); }, position:{ my:"right+185 top", at:"right+50 top", of:$("#"+id) } }); $("#slot_list_dialog").parent().find(".ui-dialog-titlebar").remove(); } $(document).on("click","#be_a_participant_button",function(){ getColleges(); createParticipant(); }) function getColleges(){ var responseData = getRequest("GET", "xyz/college/getColleges", ""); console.log("From Get Colleges "+responseData); var data = responseData[0]; collegeCollection = data; } function createParticipant(){ var $streams = ["BE", "BTECH", "MCA", "BCA", "MBA"]; var partiDialog = $("<div id='participant_dialog' title='Add Participant'><table class='table' id='create_participant_table'>" + "<tr><td class='td_cls'>Select Fest</td><td class='td_cls'><select id='fest_select'><option value='-1'>Select Fest</option></select></td><td class='td_cls'>&nbsp;</td></tr>" + "<tr><td class='td_cls'>Select Event</td><td class='td_cls'><select id='event_list'><option value='-1'>Select Event</option></select></td><td class='td_cls'>&nbsp;</td></tr>" + "<tr><td class='td_cls'>Name</td><td class='td_cls'><input type='text' id='participant_name' /></td><td class='td_cls'>&nbsp;</td></tr>" + "<tr id='after_this'><td class='td_cls'>College</td><td class='td_cls'><select id='college_list'><option value='-1'>Select College</select></td>" + "<td class='td_cls'><button id='addClg' class='btn btn-info btn-xs'>Add College</button></td></tr>" + "<tr><td class='td_cls'>Enrollment No.</td><td class='td_cls'><input type='text' id='enrollment' /></td><td class='td_cls'>&nbsp;</td></tr>" + "<tr><td class='td_cls'>Stream</td><td class='td_cls'><input type='text' id='stream' /></td><td class='td_cls'>&nbsp;</td></tr>" + "<tr><td class='td_cls'>Email</td><td class='td_cls'><input type='text' id='email' /></td><td class='td_cls'>&nbsp;</td></tr>" + "<tr><td class='td_cls'>Mobile</td><td class='td_cls'><input type='text' id='mobile' /></td><td class='td_cls'>&nbsp;</td></tr>" + "</table></div>"); if(festCollection){ for(var t=0;t<festCollection.length;t++){ var opts = $("<option value='"+festCollection[t].festId+"' id='"+festCollection[t].festId+"'>"+festCollection[t].festName+"</option>"); partiDialog.find("#fest_select").append(opts); /*$('#'+festCollection[t].festId).prop("festselect",festCollection[t]);*/ } for(var k=0;k<collegeCollection.length;k++){ var op = $("<option value='"+collegeCollection[k].collegeId+"' id='"+collegeCollection[k].collegeId+"'>"+collegeCollection[k].collegeName+"</option>"); op.prop("collegeObject",collegeCollection[k]); partiDialog.find("#college_list").append(op); } partiDialog.dialog({ width:'auto', height:'auto', modal:true, resizable:false, close:function(){ $(this).dialog("close"); $(this).remove(); }, buttons:{ Save: function(){ var validationMap = new Map(); validationMap.set("name",$("#participant_name").val().trim()); validationMap.set("email",($("#email").val()).trim()); validationMap.set("mobile",$("#mobile").val()); validationMap.set("enrolmentNo",$("#enrollment").val()); validationMap.set("fest",$("#fest_select").val()); validationMap.set("event",$('#event_list').val()); validationMap.set("College",$('#college_list').val()); validationMap.set("stream",$("#stream").val()); var flag = getValidate(validationMap); if(flag==""){ var $param = { participantId:'', participantName:$("#participant_name").val(), email:$("#email").val(), mobile:$("#mobile").val(), enrolmentNo:$("#enrollment").val(), event:$('#event_list').find(":selected").prop("eventObject"), college:$('#college_list').find(":selected").prop("collegeObject"), stream:$("#stream").val() } var responseData = getRequest("POST", "xyz/participants/addParticipant", $param); console.log("From create Participants"+responseData); var data = responseData[0]; getParticipants(); if(data.message!=null){ partiDialog.dialog('close'); partiDialog.remove(); var cnfDialog = $("<div id='cnf_dialog'>"+data.message+"</div>").appendTo('body'); cnfDialog.dialog({ width:'auto', height:'auto', modal:true, resizable:false, buttons:{ OK:function(){ $(this).dialog('close'); $(this).remove(); } } }); } }else{ if($("#validation_row").length==0){ $("<tr id='validation_row'><td style='color:red;' colspan='2'><h6>Invalid"+flag+"</h6></td></tr>").insertAfter("#create_participant_table"); } } }, Cancel:function(){ $(this).dialog('close'); $(this).remove(); } } }); partiDialog.find("#stream").autocomplete({ source:$streams }); }else{ var $festWarn = $("<div>There is no Fest. Please Create Fest First.</div>"); $festWarn.dialog({ height:'auto', width:'auto', modal:true, resizable:false, close:function(){ $(this).dialog("close"); $(this).remove(); }, buttons:{ OK:function(){ $(this).dialog("close"); $(this).remove(); } } }); } } $(document).on('click','#addClg',function(){ /*console.log($("#main_row").length);//to check element is exist of not */ if($("#main_row").length==0){ var mr = $("<tr id='main_row'><td class='td_cls'><span id='clg_lbl'>College Name</span></td><td class='td_cls'><input type='text' id='clg_input' /></td>" + "<td class='td_cls'><button id='clg_save' class='btn btn-success btn-xs'>Save</button>&nbsp;<button id='clg_cancel' class='btn btn-danger btn-xs'>Cancel</button></td><td class='td_cls'>&nbsp;</td></tr>").insertAfter("#after_this"); } }); $(document).on('click','#clg_cancel',function(){ $('#main_row').remove(); }); $(document).on('click','#clg_save',function(){ if($("#clg_input").val()!=''){ var param = { collegeId:'', collegeName:$("#clg_input").val(), } var responseData = getRequest("POST", "xyz/college/addCollege", param); console.log(responseData); console.log("From Clg_Save"+responseData); var data = responseData[0]; if(data.obj!=null){ collegeCollection.push(data.obj); var op1 = $("<option value='"+data.obj.collegeId+"' id='"+data.obj.collegeId+"'>"+data.obj.collegeName+"</option>"); op1.prop("collegeObject",data.obj); $("#participant_dialog").find("#college_list").append(op1); } $("#clg_cancel").trigger('click'); } }); $(document).on('change','#fest_select',function(){ var tttd; var ot = $(this).find("option:selected").val() var responseData = getRequest("GET", "xyz/events/getfestevents/"+ot, ""); console.log("Fest Select"+responseData); var data = responseData[0]; $("#participant_dialog").find("#event_list").html(""); var firstOption = $("<option value='-1'>Select Fest</option>").appendTo($("#participant_dialog").find("#event_list")); for(var p=0;p<data.length;p++){ var $eOpts = $("<option value='"+data[p].eventId+"'>"+data[p].eventName+"</option>"); $eOpts.prop("eventObject",data[p]); $("#participant_dialog").find("#event_list").append($eOpts); } }); $(document).on("click","#be_a_sponsor",function(){ if(festCollection){ var responseData = getRequest("GET", "xyz/events/getAllEvents", ""); var data = responseData[0]; eventCollection = data; var $sponsorDialog = $("<div id='sponsor_dialog' title='Be a Sponsor' class='widget'>" + "<table class='table'><tr><td class='td_cls'>Name</td><td class='td_cls'><input type='text' id='sponsor_name' /></td></tr>" + "<tr id='sponsor_after'><td class='td_cls'>Sponsor to:</td><td class='td_cls'><input type='radio' name='sponsor_radio' id='fest_radio' value='fest' /><label f or='fest_radio'> Fest</label>" + "<input type='radio' name='sponsor_radio' id='event_radio' value='event' /><label for='event_radio'> Event</label></td></tr>" + "<tr><td class='td_cls'>Amount</td><td class='td_cls'><input type='text' id='amt_invest' /></td></tr></table></div>"); $sponsorDialog.dialog({ width:'auto', height:'auto', modal:true, resizable:false, close:function(){ $(this).dialog("close"); $(this).remove(); }, buttons:{ Save:function(){ var flag = ''; var $spmsg = ""; if($("input:radio[name='sponsor_radio']:checked").val()=='fest'){ flag = 'fest'; id=$("#spoonsor_fest").find(":selected").val(); festObject = $("#spoonsor_fest").find(":selected").prop("festselect"); eventObject = null; }else if($("input:radio[name='sponsor_radio']:checked").val()=='event'){ flag = 'event'; id=$("#spoonsor_event").find(":selected").val(); festObject = $("#spoonsor_fest").find(":selected").prop("festselect"); eventObject = $("#spoonsor_event").find(":selected").prop("eventselect"); }else{ $spmsg = $spmsg +"Select Sponsor To, "; } if($("#sponsor_name").val().trim()=="" || $("#sponsor_name").val().trim().length<=3 || !isNaN($("#sponsor_name").val().trim())){ $spmsg= $spmsg + " Name, "; } if($("#amt_invest").val().trim()=="" || isNaN($("#amt_invest").val().trim()) || parseInt($("#amt_invest").val().trim())<=0){ $spmsg = $spmsg + "Amount." } if($("#spoonsor_fest").val()=="-1"){ $spmsg = $spmsg + "Sponsor, "; } if($("#spoonsor_event").val()=="-1"){ $spmsg = $spmsg + "Event, "; } if($spmsg==""){ $sponsorDialog.find("textarea").remove(); var param = { sponsorId:'', sponsorName:$("#sponsor_name").val(), fests:[festObject], events:[eventObject] } var responseData = getRequest("POST", "xyz/sponsor/addSponsor?amt="+$("#amt_invest").val()+'&flag='+flag, param); console.log("From be a sponsor"+responseData); var data = responseData[0]; if(data.message!=null){ getSponsors(); $sponsorDialog.html(""); $sponsorDialog.html("<h5>"+data.message+"</h5>"); $sponsorDialog.dialog({ close:function(){ $(this).dialog("close"); $(this).remove(); }, buttons:{ Ok:function(){ $(this).dialog("close"); $(this).remove(); } } }); } }else{ if($sponsorDialog.find("textarea").length==0){ $("<textarea rows='3' cols='40' disabled='disabled'>"+$spmsg+"</textarea>").insertAfter($sponsorDialog.find("table")); }else{ $sponsorDialog.find("textarea").html($spmsg); } } }, Cancel:function(){ $(this).dialog('close'); $(this).remove(); } } }); }else{ var $festWarn = $("<div>There is no Fest. Please Create Fest First.</div>"); $festWarn.dialog({ height:'auto', width:'auto', modal:true, resizable:false, close:function(){ $(this).dialog("close"); $(this).remove(); }, buttons:{ OK:function(){ $(this).dialog("close"); $(this).remove(); } } }); } }); $(document).on("change","input:radio[name='sponsor_radio']",function(){ if( $(this).val()=="fest"){ $("#sponsor_dialog").find("#sponsor_event_row").remove(); $("#sponsor_dialog").find("#sponsor_fest_row").remove(); var $sponsorfestRow = $("<tr id='sponsor_fest_row'><td class='td_cls'>Please Fest</td><td class='td_cls'><select id='spoonsor_fest'><option value='-1'>Select Fest</option></select></td></tr>"); for(var u=0;u<festCollection.length;u++){ var opts1 = $("<option value='"+festCollection[u].festId+"' id='"+festCollection[u].festId+"'>"+festCollection[u].festName+"</option>"); $sponsorfestRow.find("#spoonsor_fest").append(opts1); opts1.prop("festselect",festCollection[u]); } $sponsorfestRow.insertAfter("#sponsor_after"); }else{ $("#sponsor_dialog").find("#sponsor_fest_row").remove(); var $sponsorfestRow = $("<tr id='sponsor_fest_row'><td class='td_cls'>Please Fest</td><td class='td_cls'><select id='spoonsor_fest'><option value='-1'>Select Fest</option></select></td></tr>"); for(var u=0;u<festCollection.length;u++){ var opts1 = $("<option value='"+festCollection[u].festId+"' id='"+festCollection[u].festId+"'>"+festCollection[u].festName+"</option>"); $sponsorfestRow.find("#spoonsor_fest").append(opts1); opts1.prop("festselect",festCollection[u]); } $sponsorfestRow.insertAfter("#sponsor_after"); var $sponsorEventRow = $("<tr id='sponsor_event_row'><td class='td_cls'>Please Event</td><td class='td_cls'><select id='spoonsor_event'><option value='-1'>Select Event</option></select></td></tr>"); $sponsorEventRow.insertAfter($sponsorfestRow); $("#spoonsor_fest").on("change",function(){ for(var v=0;v<eventCollection.length;v++){ if(eventCollection[v].fest.festId==$(this).val()){ var opts = $("<option value='"+eventCollection[v].eventId+"' id='"+eventCollection[v].eventId+"'>"+eventCollection[v].eventName+"</option>"); $sponsorEventRow.find("#spoonsor_event").append(opts); opts.prop("eventselect",eventCollection[v]); } } }); } }); //*****************************************************/Validation/*************************************************// function getFestValidate(festMapObject){ var Iterator = festMapObject.keys(); var msg1 = ""; while(true){ cr = Iterator.next(); var mv = festMapObject.get(cr.value); if(cr.done){ break; } if(cr.value=="name"){ if(mv=="" || mv.length<=2 || !isNaN(mv)){ msg1 = msg1 + " Name"; } } if(cr.value=="duration"){ if(mv=="" || isNaN(mv) || mv<=0 || mv>7){ msg1 = msg1 +" Duration"; } } if(cr.value=="date"){ var currentDate = new Date().toString("DD-MM-YYYY"); if(mv<currentDate){ msg1 = msg1 + " Date"; } } if(cr.value=="startHours"){ } if(cr.value=="endHours"){ } if(cr.value=="sponsor"){ if(mv=="-1" || mv==""){ msg1 = msg1 +" Sponsor"; } } if(cr.value=="amount"){ if(mv=="" || isNaN(mv) || mv<=0 || mv>10000000){ msg1 = msg1 + " Investment Amount"; } } } return msg1; } function getValidate(mapObject){ var iterator = mapObject.keys(); var msg = ""; while(true){ current = iterator.next(); var mapvalue = mapObject.get(current.value); if(current.done){ break; } if(current.value=="name"){ if(mapvalue=="" || mapvalue.length<=2 || !isNaN(mapvalue)){ msg = msg +" Name "; } } if(current.value=="email"){ if(mapvalue=="" || mapvalue.length<=2 || !isNaN(mapvalue) || !mapvalue.includes("@") && !mapvalue.includes(".") && (mapvalue.length - (mapvalue.indexOf(".")+1))!=3){ msg = msg +" Email "; } } if(current.value=="mobile"){ if(mapvalue=="" || mapvalue.length!=10 || isNaN(mapvalue)){ msg = msg + " Mobile "; } } if(current.value=="event"){ if(mapvalue=="-1"){ msg = msg +" Event "; } } if(current.value=="fest"){ if(mapvalue=="-1"){ msg = msg +" Fest "; } } if(current.value=="College"){ if(mapvalue=="-1"){ msg = msg + " College "; } } if(current.value=="enrolmentNo"){ if(mapvalue=="" || mapvalue.trim().length<=2){ msg = msg +" Enrolment"; } } if(current.value=="stream"){ if(mapvalue==""){ msg = msg + "Stream "; } } } return msg; }
// Shroud mask var mask = { factor: 4, surf: undefined, make: function (xs, ys, rs) { var can = document.createElement("canvas") var con = can.getContext("2d") var px = can.width = settings.sx / this.factor var py = can.height = settings.sy / this.factor con.fillStyle = "white" con.fillRect(0, 0, px, py) for (var j = 0 ; j < xs.length ; ++j) { var x = xs[j]/this.factor, y = ys[j]/this.factor, r = rs[j]/this.factor var grad = con.createRadialGradient(x, y, 0, x, y, r) grad.addColorStop(0, "black") grad.addColorStop(0.8, "black") grad.addColorStop(1, "rgba(0,0,0,0)") con.fillStyle = grad con.fillRect(0, 0, px, py) } var idata = con.getImageData(0, 0, px, py) var data = idata.data for (var j = 0 ; j < 4*px*py ; j += 4) { var d = data[j] // data[j+3] = d == 0 ? 0 : d == 255 ? 255 : data[j] + UFX.random.rand(-30, 30) data[j+3] = d data[j] = data[j+1] = data[j+2] = UFX.random.rand(18, 22) } con.putImageData(idata, 0, 0) this.surf = document.createElement("canvas") this.surf.width = settings.sx this.surf.height = settings.sy var c = this.surf.getContext("2d") c.scale(this.factor, this.factor) c.drawImage(can, 0, 0) }, draw: function () { context.drawImage(this.surf, 0, 0) }, }
import React from 'react'; import PropTypes from 'prop-types'; class Question extends React.PureComponent { static propTypes = { questions: PropTypes.shape({ code: PropTypes.number.isRequired, question: PropTypes.string.isRequired, }), cbHandleSubmit: PropTypes.func.isRequired, }; questionClicked = (EO) => { console.log("user made the choice " + EO.target.value); this.props.cbHandleSubmit(this.props.questions); } render() { return( <p> <input onClick={this.questionClicked} name="vote" type="radio" value={this.props.questions.code}/> {this.props.questions.question} </p> ); } } export default Question;
//函数声明和函数表达式 /** * 解析器会率先读取函数声明通过一个叫函数声明提升的过程 */ //以下代码可用 alert(sum(10,10)); function sum(num1,num2){ return num1 + num2; } //以下代码不可用 alert(sum(10,10)); var sum = function(num1,num2){ return num1 + num2; } // 除了什么时候可以通过变量访问函数这一点,函数声明和函数表达式是一样的
'use strict'; const decorator = require('./lib/decorator'); exports.isMasked = decorator.isMasked; exports.mask = decorator.mask; exports.unMask = decorator.unMask;
/** * @author v.lugovsky * created on 16.12.2015 */ (function() { 'use strict'; angular.module('ROA.pages.performance', []) .config(function($stateProvider) { $stateProvider .state('pacientes', { url: '/pacientes', templateUrl: 'app/pages/performance/performance.html', title: 'Pacientes', sidebarMeta: { icon: 'ion-android-home', order: 0 }, controller: 'PerformanceCtrl', data: { requireLogin: true } }); }) .controller('PerformanceCtrl', ['$rootScope', '$scope', 'AnalyticsService', 'layoutColors', 'layoutPaths', '$filter', function($rootScope, $scope, AnalyticsService, layoutColors, layoutPaths, $filter) { // First filter $scope.first_filter = 'network'; $scope.setFirstFilter = function(newFilter){ $scope.first_filter = newFilter; if($scope.first_filter === $scope.second_filter.filter){ $scope.second_filter = {title: 'Combine With', filter: false}; } AnalyticsService.calculatePerformance($scope); }; // Second filter $scope.second_filter = {title: 'Combine With', filter: false}; $scope.setSecondFilter = function(newFilter){ $scope.second_filter = {title: 'Combine With', filter: false}; if($scope.first_filter !== $scope.second_filter.filter){ $scope.second_filter = newFilter; } AnalyticsService.calculatePerformance($scope); }; // Third filter $scope.third_filter = 'users'; $scope.bubble_message = 'Returning Users'; $scope.bubble_submessage = 'Returning User'; $scope.setThirdFilter = function(newFilter){ $scope.third_filter = newFilter; switch($scope.third_filter){ case 'users': $scope.bubble_message = 'Returning Users'; $scope.bubble_submessage = 'Returning User'; break; case 'new_users': $scope.bubble_message = 'New Users'; $scope.bubble_submessage = 'New User'; break; case 'conversions': $scope.bubble_message = 'Conversions'; $scope.bubble_submessage = 'Conversion'; break; } AnalyticsService.calculatePerformance($scope); }; $scope.cost_per_user = 0; $scope.cost_per_new_user = 0; $scope.cost_per_conversion = 0; if($rootScope.performanceCalculated || AnalyticsService.informationLoaded){ AnalyticsService.calculatePerformance($scope); }else{ //Intercept the Loaded information action $rootScope.$on('informationLoaded', function(){ AnalyticsService.calculatePerformance($scope); $rootScope.performanceCalculated = true; }); } // Define the list of available columns and the default ones $scope.tableColumns = { name: { title: 'Name', enabled: true, searchable: true, count: 'Total' }, ads: { title: 'Ads', enabled: true, searchable: true, count: 0 }, budget: { title: 'Budget', enabled: true, searchable: true, count: 0 }, roi: { title: 'ROI', enabled: false, searchable: true, count: 0 }, revenue: { title: 'Revenue', enabled: true, searchable: true, count: 0 }, users: { title: 'Returning Visitors', enabled: false, searchable: true, count: 0 }, new_users: { title: 'New Visitors', enabled: true, searchable: true, count: 0 }, conversions: { title: 'Conversions', enabled: true, searchable: true, count: 0 } }; $scope.displayColumn = function(column_id){ $scope.tableColumns[column_id].enabled = !$scope.tableColumns[column_id].enabled; }; $scope.needFormat = [ 'budget', 'roi', 'revenue' ]; // Handle the update of the totals $scope.setPerformanceTotals = function(totals) { for (var data in totals) { if ($scope.tableColumns[data]) { $scope.tableColumns[data].count = parseFloat(Math.round(totals[data] * 100) / 100).toFixed(2); if ($scope.needFormat.indexOf(data) > -1) { $scope.tableColumns[data].count = $filter('currency')($scope.tableColumns[data].count, $rootScope.userSettings.currency, 2); } } } $scope.cost_per_user = totals.cpu; $scope.cost_per_new_user = totals.cpnu; $scope.cost_per_conversion = totals.cpc; }; $scope.enableChart = function(data){ var minVal = parseFloat(data[0].x), maxVal = 0; data.map(function(currentValue){ var temporal = parseFloat(currentValue.x); if(temporal > maxVal){ maxVal = temporal; }else if(temporal < minVal){ minVal = temporal; } }); console.log(maxVal); console.log(minVal); var chart = AmCharts.makeChart("bubble-chart", { "type": "xy", "balloon": { "fixedPosition": false }, "pathToImages": "assets/img/", "dataProvider": data, "valueAxes": [{ "position": "bottom", "axisAlpha": 0, "autoGridCount": true, minimum: minVal, maximum: maxVal }, { //"minMaxMultiplier": 1.2, "axisAlpha": 0, "position": "left", "unit": $rootScope.userSettings.currency, "title": "Avg Cost per "+$scope.bubble_submessage, "titleColor" : "#666666" }], //"startDuration": 1.5, "graphs": [{ "balloonFunction": function(graphDataItem, graph) { return "<b>"+graphDataItem.dataContext.title+"</b><br>"+$scope.bubble_message+":<b>"+$filter('currency')(graphDataItem.dataContext.x, '', 2)+"</b><br> Cost Per "+$scope.bubble_submessage+":<b>"+$filter('currency')(graphDataItem.dataContext.y, '', 2)+"</b>" }, "bullet": "circle", "bulletBorderAlpha": 0.2, "bulletAlpha": 0.8, "lineAlpha": 0, "fillAlphas": 0, "valueField": "value", "xField": "x", "yField": "y", "maxBulletSize": 100 }], "marginLeft": 0, "marginBottom": 0, "export": { "enabled": true }, maxZoomFactor: 15, "chartScrollbar": {}, "chartCursor": { selectionAlpha: 0.5 } }); chart.pathToImages = "assets/img/"; $scope.name_search_box = ''; chart.addListener("clickGraphItem", function(event) { var input = document.getElementById("name_search_box"); angular.element(input).val(event.item.dataContext.title).trigger('input'); }); // init object to hold chart zoom chart.zoomValues = { x: { startValue: 0, endValue: 0 }, y: { startValue: 0, endValue: 0 } }; }; //chart.addLabel(3,320,'','left', 12, '#666666', -90 ); $scope.smartTablePageSize = 10; $scope.resultCollection = []; } ]); })();
alert ('Hey!') //This is a basic alert console.log ("This is an example of you typing things directly into the Console"); var name: "Nikhil"; //You can add properties to properties to variables var x = 5; console.log ('Hello Nikhil'); var isCodingFun = true; //You can add multiple values to variables called Arrays var Peanuts = ["charlie brown", "snoopy"] console.log (Peanuts) var user = { firstName: "Nikhil", lastName: "Solanki", birthday: "August 20, 2001" }; console.log (user.firstName + " " + user.lastName); //You can add Logic, which are true or false statements if (5>10) { console.log ("You'll never see this because 5 isn't greater than 10") }else { alert ("This is true!") } //You can alert the user anything you want, by using functions function alertUser (name) { return alert (name); } alertUser("John Appleseed II"); alertUser("Dr. Suess"); } alertUser("Pizza") alertUser("Pasta")
import { RealDAOHelper } from './realdao-helper.js' import config from './config.js' import { Overview } from './components/overview.js' import { Mining } from './components/mining.js' const { mode } = window.__pdm__ function main() { const env = 'test' const network = config.networks[env] const realDAO = new RealDAOHelper({ Web3, env, config: network, }) async function init() { await realDAO.loadOrchestrator() const overview = new Overview({ el: '#overview', realDAO, config: network , mode: mode}) const mining = new Mining({ el: '#mining', realDAO, mode: mode }) // const unsubscribe = mode.subscribe((v) => console.log(v, '===========')) overview.run() mining.run() } init() } window.onload = main
// pages/banjiRecord/banjiRecord.js let app = getApp(); let baseUrl = app.globalData.baseUrl; const utils = require('../../utils/util.js') const regeneratorRuntime = require('../../lib/runtime') Page({ /** * 页面的初始数据 */ data: { P_playing: false, P_endPlay: false, initIcon: '../../images/recordPlay.png', playIcon: '../../images/playings.gif', imgHoverIndex: 1000, value: 0, percent: 0, max: 17, pass_time: '00:00', total_time: '00:00' }, async commentdetail(pratice_id, kpl_id) { var token = wx.getStorageSync('token'); const data = await utils.get('practice/comment_class_record', { pratice_id: pratice_id, kpl_class_id: kpl_id }, token); if (data.code == 1) { this.setData({ recordList: data.data.record }) wx.hideLoading(); } }, selectAudio(e) { var audio = e.currentTarget.dataset.audio; var index = e.currentTarget.dataset.index; var time = e.currentTarget.dataset.time; var seconds = e.currentTarget.dataset.seconds; this.setData({ audio: audio, imgHoverIndex: index, max: seconds, total_time: time //initIcon:'../../images/playings.png' }) console.log(audio) this.playAudio.autoplay = true; this.playAudio.src = audio; this.playAudio.play(); this.playAudio.onPlay(() => { console.log('开始播放') }) this.setData({ P_playing: true, P_endPlay: false, }) }, P_endPlay: function() { var that = this; this.playAudio.pause(); //clearInterval(that.data.secs); this.setData({ P_playStart: false, P_endPlay: true, P_playing: false }) }, P_contiunePlay: function() { this.playAudio.play(); this.setData({ P_playStart: false, P_endPlay: false, P_playing: true }) }, tip: function(msg) { wx.showModal({ title: '提示', content: msg, showCancel: false }) }, P_playRec:function(){ var audio=this.data.audio; if(audio==''){ wx.showToast({ title: '当前未选择播放录音', }) } }, /** * 生命周期函数--监听页面加载 */ onLoad: function(options) { this.wxzxSlider = this.selectComponent("#wxzxSlider"); wx.showLoading({ title: '正在加载中', }) var that = this; var kpl_id = options.kpl_class_id; var pratice_id = options.pratice_id; this.setData({ kpl_id: kpl_id, pratice_id: pratice_id }) this.commentdetail(pratice_id, kpl_id); this.playAudio = wx.createInnerAudioContext(); this.playAudio.onError((res) => { that.tip("播放录音失败!"); that.setData({ imgHoverIndex: 1000, P_endPlay: false, P_playing: false }) }) this.playAudio.onTimeUpdate(function() { if (!that.wxzxSlider.properties.isMonitoring) { return } var currentTime = that.playAudio.currentTime.toFixed(0); if (currentTime > that.data.max) { currentTime = that.data.max; } var pass_time = that.secondTransferTime(currentTime); that.setData({ value: currentTime, pass_time: pass_time, percent: that.playAudio.buffered / that.playAudio.duration * 100, disabled: false }) }) this.playAudio.onEnded((res) => { console.log('jieshu'); that.setData({ P_endPlay: false, P_playing: false, value: 0, pass_time: '00:00', percent: 0, }) }) }, // 点击slider时调用 sliderTap: function(e) { console.log("sliderTap") this.seek() }, // 开始滑动时 sliderStart: function(e) { console.log("sliderStart") }, // 正在滑动 sliderChange: function(e) { console.log("sliderChange") }, // 滑动结束 sliderEnd: function(e) { console.log("sliderEnd") this.seek() }, // 滑动取消 (左滑时滑到上一页面或电话等情况) sliderCancel: function(e) { console.log("sliderCancel") this.seek() }, seek: function() { var value = this.wxzxSlider.properties.value console.log(value) var seek_time = value.toFixed(0); var pass_time = this.secondTransferTime(seek_time); this.setData({ pass_time: pass_time, }) this.playAudio.seek(Number(seek_time)); }, secondTransferTime: function(time) { if (time > 3600) { return [ parseInt(time / 60 / 60), parseInt(time / 60 % 60), parseInt(time % 60) ] .join(":") .replace(/\b(\d)\b/g, "0$1"); } else { return [ parseInt(time / 60 % 60), parseInt(time % 60) ] .join(":") .replace(/\b(\d)\b/g, "0$1"); } }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function() { }, /** * 生命周期函数--监听页面显示 */ onShow: function() { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function() { this.playAudio.stop(); }, /** * 生命周期函数--监听页面卸载 */ onUnload: function() { this.playAudio.stop(); }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function() { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function() { }, /** * 用户点击右上角分享 */ onShareAppMessage: function() { } })
document.write(origin分支未完成); console.log(紧急的新需求); console.log(完成);
$(document).ready(function(){ $(".menu-button").click(function(){ if($(this).next().is(':visible')) { $(this).next().slideUp(); $(this).css("transform", "rotate(0deg)") } else { $(this).next().slideDown(); $(this).css("transform", "rotate(180deg)") } }); });
// Write a function called RepeatN that accpets and string and a number the return that string n times function RepeatN(string, n) { var str = ''; for (var i = 0; i < n; i++) { str += string + ' '; } return str; } RepeatN('RBK', 3); // => RBK RBK RBK RepeatN('Javascript', 5); // => Javascript Javascript Javascript Javascript Javascript
'use strict'; const {Router} = require(`express`); const sequelize = require(`~/service/lib/sequelize`); const defineModels = require(`~/service/models`); const { ArticleService, CategoryService, SearchService, CommentService, UserService, } = require(`~/service/data-service`); const articles = require(`./articles/articles`); const comments = require(`./comments/comments`); const categories = require(`./categories/categories`); const search = require(`./search/search`); const users = require(`./users/users`); const app = new Router(); defineModels(sequelize); (async () => { articles(app, new ArticleService(sequelize), new CommentService(sequelize)); comments(app, new CommentService(sequelize)); categories(app, new CategoryService(sequelize)); search(app, new SearchService(sequelize)); users(app, new UserService(sequelize)); })(); module.exports = app;
import express from 'express' import { User, Pet, Code, Record, Store, Room, Book, Good, Word } from '../models' import md5 from 'md5' import https from 'https' import querystring from 'querystring' import { MESSAGE, KEY, YUNPIAN_APIKEY, validate, md5Pwd, } from '../config' const router = express.Router() /* users/code */ router.post('/code', (req, res) => { const { account } = req.body const region = req.query.region || 'china' validate(res, false, account) const now = Date.now() const code = Math.floor(Math.random() * 8999 + 1000) const postData = { mobile: account, text: region === 'china' ? ('【双生日记】您的验证码是' + code) : ('【2Life】Your SMS Verification Code:' + code), apikey: YUNPIAN_APIKEY } const content = querystring.stringify(postData) const options = { host: 'sms.yunpian.com', path: '/v2/sms/single_send.json', method: 'POST', agent: false, rejectUnauthorized: false, headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': content.length } } const model = { account, code, timestamp: now, used: false } const sendMsg = async () => { const req = https.request(options, (res) => { res.setEncoding('utf8') }) req.write(content) req.end() return true } const response = async () => { const results = await Code.findAll({ where: { account, used: false } }) if (results[0] !== undefined) { if (now - results[0].timestamp < 600000) { return res.json(MESSAGE.REQUEST_ERROR) } } await Code.create(model) await sendMsg() return res.json({ ...MESSAGE.OK, data: { timestamp: now } }) } response() }) /* users/register */ router.post('/register', (req, res) => { const { account, password, code, timestamp } = req.body validate(res, false, account, password, code, timestamp) const findCode = async () => { return await Code.findOne({ where: { code, timestamp } }) } const response = async () => { const code = await findCode() if (code) { const user = await User.findOne({ where: { account } }) // TODO: 未知 bug // await Code.update({ used: true }, { where: { account, code, timestamp } }) if (user) { return res.json(MESSAGE.USER_EXIST) } else { // TODO: 注册时送宠物还是以后再送? const userinfo = { account, password: md5(password), sex: 0, name: account, face: 'https://airing.ursb.me/image/twolife/male.png' } await User.create(userinfo) return res.json({ ...MESSAGE.OK, data: userinfo }) } } return res.json(MESSAGE.CODE_ERROR) } response() }) /* users/login */ router.post('/login', (req, res) => { const { account, password } = req.body validate(res, false, account, password) const response = async () => { const user = await User.findOne({ where: { account }, include: [Pet] }) if (!user) return res.json(MESSAGE.USER_NOT_EXIST) if (user.password !== md5(password)) return res.json(MESSAGE.PASSWORD_ERROR) const timestamp = Date.now() const token = md5Pwd((user.id).toString() + timestamp.toString() + KEY) return res.json({ ...MESSAGE.OK, data: { user: { ...user.dataValues, password: 0 }, key: { uid: user.id, token, timestamp }, } }) } response() }) /* users/learn */ router.post('/learn', (req, res) => { const { uid, timestamp, token, word_id, score } = req.body validate(res, true, uid, timestamp, token, word_id, score) const response = async () => { const record = await Record.findOne({ where: { user_id: uid, word_id } }) if (!record) { await Record.create({ user_id: uid, word_id, remember: +score + 50, mark_time: Date.now() }) } else { record.mark_time = Date.now() await record.save() await record.increment({ remember: +score }) } return res.json(MESSAGE.OK) } response() }) /* users/buy_good */ router.post('/buy_good', (req, res) => { const { uid, timestamp, token, good_id } = req.body validate(res, true, uid, timestamp, token, good_id) const response = async () => { const good = await Good.findById(good_id) const user = await User.findById(uid) if (+user.coins < +good.price) { return res.json(MESSAGE.NOT_ENOUGH_MONEY) } await user.decrement({ 'coins': +good.price }) const store = await Store.findOne({ where: { user_id: uid, good_id } }) if (!store) { await Store.create({ user_id: uid, good_id, num: 1 }) } else { await store.increment('num') } return res.json(MESSAGE.OK) } response() }) /* users/buy_book */ router.post('/buy_book', (req, res) => { const { uid, timestamp, token, book_id } = req.body validate(res, true, uid, timestamp, token, book_id) const response = async () => { const book = await Book.findById(book_id) const user = await User.findById(uid) if (+user.coins < +book.price) { return res.json(MESSAGE.NOT_ENOUGH_MONEY) } await user.decrement({ 'coins': +book.price }) const room = await Room.findOne({ where: { user_id: uid, book_id } }) if (!room) { await Room.create({ user_id: uid, book_id, }) } else { return res.json(MESSAGE.ALREADY_HAVE_BOOK) } return res.json(MESSAGE.OK) } response() }) /* users/books */ router.get('/books', (req, res) => { const { uid, timestamp, token } = req.query validate(res, true, uid, timestamp, token) const response = async () => { // const books = await Book.findAll({ attributes: ['id', 'name', 'category', 'price', 'pic', 'word_count', 'description'] }) const books = await Book.findAll() return res.json({ ...MESSAGE.OK, data: books }) } response() }) /* users/goods */ router.get('/goods', (req, res) => { const { uid, timestamp, token } = req.query validate(res, true, uid, timestamp, token) const response = async () => { const data = await Good.findAll() return res.json({ ...MESSAGE.OK, data }) } response() }) /* users/records */ router.get('/records', (req, res) => { const { uid, timestamp, token } = req.query validate(res, true, uid, timestamp, token) const response = async () => { const data = await Record.findAll({ where: { user_id: uid }, include: [Word] }) return res.json({ ...MESSAGE.OK, data }) } response() }) /* users/words */ router.get('/words', (req, res) => { const { uid, timestamp, token, book_id } = req.query validate(res, true, uid, timestamp, token, book_id) const response = async () => { const data = await Word.findAll({ where: { book_id } }) return res.json({ ...MESSAGE.OK, data }) } response() }) router.post('/reset_password', (req, res) => { const { account, password, code, timestamp } = req.body validate(res, false, account, password, code, timestamp) const findCode = async () => { return await Code.findOne({ where: { code, timestamp } }) } const response = async () => { const code = await findCode() if (code) { const user = await User.findOne({ where: { account } }) if (!user) { return res.json(MESSAGE.USER_NOT_EXIST) } else { await User.update({ password: md5(password) }, { where: { account } }) return res.json(MESSAGE.OK) } } return res.json(MESSAGE.CODE_ERROR) } response() }) module.exports = router
const express = require('express') const winston = require('winston') const compression = require('compression') const Path = require('path') const staticFiles = require('./lib/static') const frontMatter = require('./lib/front-matter') const markdown = require('./lib/markdown') const altFormats = require('./lib/alt-formats') const layouts = require('./lib/layouts') const vhosts = require('./lib/vhosts') const basicAuth = require('./lib/basic-auth') const cookieParser = require('cookie-parser') const cookieAuth = require('./lib/cookie-auth') const tokenAuth = require('./lib/token-auth') const accessRules = require('./lib/access-rules') const accessEnforcement = require('./lib/access-enforcement') const loginForm = require('./lib/login-form') const sendRenderedFile = require('./lib/send-rendered-file') const editFiles = require('./lib/edit-files') const collections = require('./lib/collections') const signup = require('./lib/signup') const cron = require('./lib/cron') const headers = require('./lib/headers') const helmet = require('helmet') const rewrite = require('./lib/rewrite') const { reader } = require('time-streams') const altcloud = function (options) { const app = express() const opts = Object.assign({ root: '.', logger: winston }, options) opts.root = Path.resolve(opts.root) opts.logger.level = opts.logLevel cron(opts) const cookies = cookieAuth(opts) app.use(function (req, res, next) { opts.logger.info(req.method, req.url) next() }) app.use('/', loginForm(opts)) app.use('/', signup(opts)) app.use(helmet()) app.use(basicAuth(opts)) app.use(cookieParser()) app.use(cookies.checkCookie) app.use(tokenAuth(opts)) app.use(compression()) app.use(vhosts(opts)) app.use(accessRules(opts)) app.use(rewrite(opts)) app.use(altFormats(opts)) app.use(accessEnforcement(opts)) app.use(headers(opts)) app.use(frontMatter(opts)) app.use(markdown(opts)) app.use(layouts(opts)) app.use(sendRenderedFile(opts)) app.use(editFiles(opts)) app.use(reader(opts.root)) app.use(staticFiles(opts)) app.use(collections(opts)) // error handler app.use(function (err, req, res, next) { // see if we have a custom error page const rules = req.altcloud.fullRules if (rules[err.status]) { const fileBase = req.altcloud.siteBase ? Path.join(opts.root, req.altcloud.siteBase) : opts.root return res.sendFile(Path.join(fileBase, rules[err.status])) } if (err && req.headers['content-type'] === 'application/json' && err.status) { res.status(err.status) res.json({ message: err.message }) } else { next() } }) return app } module.exports = altcloud
/* Copyright 2015 Intel Corporation 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 */ // This try/catch is temporary to maintain backwards compatibility. Will be removed and changed to just // require('cordova/exec/proxy') at unknown date/time. var commandProxy; try { commandProxy = require('cordova/windows8/commandProxy'); } catch (e) { commandProxy = require('cordova/exec/proxy'); } module.exports = { busy: false, cameraCaptureTask: null, photoChooserTask: null, localStorageHelper: null, photoCaptureDevice: null, pictureName: "_pictures", pictureExtension: "ms-appdata:///local/", deviceList: new Array(), getInfo: function (successCallback, errorCallback, params) { var me = module.exports; // replace picture location to pull picture from local folder. if (!intel.xdk.camera.pictureLocation || intel.xdk.camera.pictureLocation.indexOf("ms-appdata") == -1) { intel.xdk.camera.pictureLocation = me.pictureExtension + me.pictureName; } me.enumerateCameras(); var applicationData = Windows.Storage.ApplicationData.current; var localFolder = applicationData.localFolder; localFolder.createFolderAsync(intel.xdk.camera.pictureLocation.replace(me.pictureExtension, ""), Windows.Storage.CreationCollisionOption.openIfExists).then( function (dataFolder) { dataFolder.getFilesAsync().then( function (files) { var tempPictureList = []; files.forEach(function (file) { tempPictureList.push(file.name); }) var info = {}; info.pictureLocation = me.pictureExtension + me.pictureName; info.pictureList = tempPictureList; successCallback(info); }, function (error) { } ) } ); }, takePicture: function(successCallback, errorCallback, params) { var me = module.exports; var quality = params[0]; var saveToLib = params[1]; var picType = params[2]; if (me.busy) { me.cameraBusy(); return; } me.busy = true; if (Windows.Media.Capture.CameraCaptureUI) { var cameraCaptureUI = new Windows.Media.Capture.CameraCaptureUI(); cameraCaptureUI.photoSettings.allowCropping = true; if (picType == "png") { cameraCaptureUI.photoSettings.format = Windows.Media.Capture.CameraCaptureUIPhotoFormat.png; } else { cameraCaptureUI.photoSettings.format = Windows.Media.Capture.CameraCaptureUIPhotoFormat.jpeg; } cameraCaptureUI.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo).then(function (picture) { if (picture) { var applicationData = Windows.Storage.ApplicationData.current; var localFolder = applicationData.localFolder; localFolder.createFolderAsync(intel.xdk.camera.pictureLocation.replace(me.pictureExtension, ""), Windows.Storage.CreationCollisionOption.openIfExists).then( function (dataFolder) { picture.copyAsync(dataFolder, picture.name, Windows.Storage.NameCollisionOption.replaceExisting).then( function (storageFile) { if (storageFile != null) { /*var ev = document.createEvent('Events'); ev.initEvent('intel.xdk.camera.internal.picture.add', true, true); ev.success = true; ev.filename = storageFile.name; document.dispatchEvent(ev);*/ me.createAndDispatchEvent("intel.xdk.camera.internal.picture.add", { success: true, filename: storageFile.name }); /*ev = document.createEvent('Events'); ev.initEvent('intel.xdk.camera.picture.add', true, true); ev.success = true; ev.filename = storageFile.name; document.dispatchEvent(ev);*/ me.createAndDispatchEvent("intel.xdk.camera.picture.add", { success: true, filename: storageFile.name }); cameraCaptureUI = null; me.busy = false; } }, function () { /*var ev = document.createEvent('Events'); ev.initEvent('intel.xdk.camera.picture.add', true, true); ev.success = false; ev.message = 'Photo capture failed'; ev.filename = storageFile.name; document.dispatchEvent(ev);*/ me.createAndDispatchEvent("intel.xdk.camera.picture.add", { success: false, message: "Photo capture failed", filename: storageFile.name }); cameraCaptureUI = null; me.busy = false; }, function () { }); }); } else { /*var ev = document.createEvent('Events'); ev.initEvent('intel.xdk.camera.picture.add', true, true); ev.success = false; ev.message = 'The user canceled.'; ev.filename = ""; document.dispatchEvent(ev);*/ me.createAndDispatchEvent("intel.xdk.camera.picture.add", { success: false, message: "The user canceled", filename: "" }); cameraCaptureUI = null; me.busy = false; } }, function () { errorCallback("Fail to capture a photo."); }); } else { /* ******************************************************************************************** THIS WAS TAKEN FROM APACHE CORDOVA'S CAMERA PROXY PLUGIN. ******************************************************************************************** */ // We are running on WP8.1 which lacks CameraCaptureUI class // so we need to use MediaCapture class instead and implement custom UI for camera var saveToPhotoAlbum = params[1]; var encodingType = params[2]; var mediaType = params[3]; var targetWidth = params[3]; var targetHeight = params[3]; var sourceType = params[3]; var destinationType = params[3]; var allowCrop = !!params[3]; var cameraDirection = params[3]; var CaptureNS = Windows.Media.Capture; var capturePreview = null, captureCancelButton = null, capture = null, captureSettings = null; var createCameraUI = function () { // Create fullscreen preview capturePreview = document.createElement("video"); // z-order style element for capturePreview and captureCancelButton elts // is necessary to avoid overriding by another page elements, -1 sometimes is not enough capturePreview.style.cssText = "position: fixed; left: 0; top: 0; width: 100%; height: 100%; z-index:222999;"; // Create cancel button captureCancelButton = document.createElement("button"); captureCancelButton.innerText = "Cancel"; captureCancelButton.style.cssText = "position: fixed; right: 0; bottom: 0; display: block; margin: 20px; z-index:2221000;"; capture = new CaptureNS.MediaCapture(); captureSettings = new CaptureNS.MediaCaptureInitializationSettings(); captureSettings.streamingCaptureMode = CaptureNS.StreamingCaptureMode.video; }; var startCameraPreview = function () { // Search for available camera devices // This is necessary to detect which camera (front or back) we should use var expectedPanel = cameraDirection === 1 ? Windows.Devices.Enumeration.Panel.front : Windows.Devices.Enumeration.Panel.back; Windows.Devices.Enumeration.DeviceInformation.findAllAsync(Windows.Devices.Enumeration.DeviceClass.videoCapture) .done(function (devices) { if (devices.length > 0) { devices.forEach(function (currDev) { if (currDev.enclosureLocation.panel && currDev.enclosureLocation.panel == expectedPanel) { captureSettings.videoDeviceId = currDev.id; } }); capture.initializeAsync(captureSettings).done(function () { // This is necessary since WP8.1 MediaCapture outputs video stream rotated 90 degrees CCW // TODO: This can be not consistent across devices, need additional testing on various devices capture.setPreviewRotation(Windows.Media.Capture.VideoRotation.clockwise90Degrees); // msdn.microsoft.com/en-us/library/windows/apps/hh452807.aspx capturePreview.msZoom = true; capturePreview.src = URL.createObjectURL(capture); capturePreview.play(); // Insert preview frame and controls into page document.body.appendChild(capturePreview); document.body.appendChild(captureCancelButton); // Bind events to controls capturePreview.addEventListener('click', captureAction); captureCancelButton.addEventListener('click', function () { destroyCameraPreview(); errorCallback('Cancelled'); }, false); }, function (err) { destroyCameraPreview(); errorCallback('Camera intitialization error ' + err); }); } else { destroyCameraPreview(); errorCallback('Camera not found'); } }); }; var destroyCameraPreview = function () { capturePreview.pause(); capturePreview.src = null; [capturePreview, captureCancelButton].forEach(function (elem) { if (elem /* && elem in document.body.childNodes */) { document.body.removeChild(elem); } }); if (capture) { capture.stopRecordAsync(); capture = null; } }; var captureAction = function () { var encodingProperties, fileName, generateUniqueCollisionOption = Windows.Storage.CreationCollisionOption.generateUniqueName, tempFolder = Windows.Storage.ApplicationData.current.temporaryFolder; var applicationData = Windows.Storage.ApplicationData.current; var localFolder = applicationData.localFolder; localFolder.createFolderAsync(intel.xdk.camera.pictureLocation.replace(me.pictureExtension, ""), Windows.Storage.CreationCollisionOption.openIfExists).then( function (dataFolder) { if (encodingType == "png") { fileName = 'photo.png'; encodingProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createPng(); } else { fileName = 'photo.jpg'; encodingProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createJpeg(); } dataFolder.createFileAsync(fileName, generateUniqueCollisionOption).done(function (capturedFile) { capture.capturePhotoToStorageFileAsync(encodingProperties, capturedFile).done(function () { destroyCameraPreview(); // success callback for capture operation var success = function (capturedfile) { capturedfile.copyAsync(Windows.Storage.ApplicationData.current.localFolder, capturedfile.name, generateUniqueCollisionOption).done(function (copiedfile) { successCallback("ms-appdata:///local/" + copiedfile.name); me.busy = false; me.createAndDispatchEvent("intel.xdk.camera.internal.picture.add", { success: true, filename: copiedfile.name }); me.createAndDispatchEvent("intel.xdk.camera.picture.add", { success: true, message: "Photo capture failed", filename: copiedfile.name }); }, function () { errorCallback(); me.busy = false; me.createAndDispatchEvent("intel.xdk.camera.picture.add", { success: false, message: "Photo capture failed", filename: "" }); }); }; if (saveToPhotoAlbum) { capturedFile.copyAsync(Windows.Storage.KnownFolders.picturesLibrary, capturedFile.name, generateUniqueCollisionOption) .done(function () { success(capturedFile); }, function () { errorCallback(); me.busy = false; me.createAndDispatchEvent("intel.xdk.camera.picture.add", { success: false, message: "Photo capture failed", filename: "" }); }); } else { success(capturedFile); } }, function (err) { destroyCameraPreview(); errorCallback(err); me.busy = false; me.createAndDispatchEvent("intel.xdk.camera.picture.add", { success: false, message: "Photo capture failed", filename: "" }); }); }, function (err) { destroyCameraPreview(); errorCallback(err); me.busy = false; me.createAndDispatchEvent("intel.xdk.camera.picture.add", { success: false, message: "Photo capture failed", filename: "" }); }); }); }; try { createCameraUI(); startCameraPreview(); } catch (ex) { errorCallback(ex); } /* ******************************************************************************************** THIS WAS TAKEN FROM APACHE CORDOVA'S CAMERA PROXY PLUGIN. ******************************************************************************************** */ } }, takeFrontPicture: function (successCallback, errorCallback, params) { var me = module.exports; me.takePicture(successCallback, errorCallback, params); }, importPicture: function() { var me = module.exports; // replace picture location to pull picture from local folder. if (intel.xdk.camera.pictureLocation.indexOf("ms-appdata") == -1) { intel.xdk.camera.pictureLocation = pictureExtension + intel.xdk.camera.pictureLocation; } if (me.busy) { me.cameraBusy(); return; } // Verify that we are currently not snapped, or that we can unsnap to open the picker var currentState = Windows.UI.ViewManagement.ApplicationView.value; if (currentState === Windows.UI.ViewManagement.ApplicationViewState.snapped && !Windows.UI.ViewManagement.ApplicationView.tryUnsnap()) { // Fail silently if we can't unsnap return; } var openPicker = new Windows.Storage.Pickers.FileOpenPicker(); openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary; openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail; openPicker.fileTypeFilter.clear(); openPicker.fileTypeFilter.append(".bmp"); openPicker.fileTypeFilter.append(".png"); openPicker.fileTypeFilter.append(".jpeg"); openPicker.fileTypeFilter.append(".jpg"); openPicker.pickSingleFileAsync().done( function (picture) { if (picture) { var applicationData = Windows.Storage.ApplicationData.current; var localFolder = applicationData.localFolder; localFolder.createFolderAsync(intel.xdk.camera.pictureLocation.replace(me.pictureExtension, ""), Windows.Storage.CreationCollisionOption.openIfExists).then( function (dataFolder) { picture.copyAsync(dataFolder, picture.name, Windows.Storage.NameCollisionOption.replaceExisting).then( function (storageFile) { if (storageFile != null) { /*var ev = document.createEvent('Events'); ev.initEvent('intel.xdk.camera.internal.picture.add', true, true); ev.success = true; ev.filename = storageFile.name; document.dispatchEvent(ev);*/ me.createAndDispatchEvent("intel.xdk.camera.internal.picture.add", { success: true, filename: storageFile.name }); /*ev = document.createEvent('Events'); ev.initEvent('intel.xdk.camera.picture.add', true, true); ev.success = true; ev.filename = storageFile.name; document.dispatchEvent(ev);*/ me.createAndDispatchEvent("intel.xdk.camera.picture.add", { success: true, filename: storageFile.name }); } }, function () { /*var ev = document.createEvent('Events'); ev.initEvent('intel.xdk.camera.picture.add', true, true); ev.success = false; ev.message = 'Photo capture failed'; ev.filename = storageFile.name; document.dispatchEvent(ev);*/ me.createAndDispatchEvent("intel.xdk.camera.picture.add", { success: false, message: "Photo capture failed", filename: storageFile.name }); }, function () { }); }); } else { /*var ev = document.createEvent('Events'); ev.initEvent('intel.xdk.camera.picture.add', true, true); ev.success = false; ev.message = 'The user canceled.'; ev.filename = ""; document.dispatchEvent(ev);*/ me.createAndDispatchEvent("intel.xdk.camera.picture.add", { success: false, message: "The user canceled", filename: "" }); openPicker = null; me.busy = false; } }, function (error) { }); }, deletePicture: function (successCallback, errorCallback, params) { var me = module.exports; var picURL = params[0]; var applicationData = Windows.Storage.ApplicationData.current; var localFolder = applicationData.localFolder; localFolder.createFolderAsync(intel.xdk.camera.pictureLocation.replace(me.pictureExtension, ""), Windows.Storage.CreationCollisionOption.openIfExists).then( function (dataFolder) { dataFolder.getFileAsync(picURL).then( function (file) { if (file) { file.deleteAsync(); /*var ev = document.createEvent('Events'); ev.initEvent('intel.xdk.camera.internal.picture.remove', true, true); ev.success = true; ev.filename=picURL; document.dispatchEvent(ev);*/ me.createAndDispatchEvent("intel.xdk.camera.internal.picture.remove", { success: true, filename: picURL }); /*ev = document.createEvent('Events'); ev.initEvent('intel.xdk.camera.picture.remove', true, true); ev.success = true; ev.filename = picURL; document.dispatchEvent(ev);*/ me.createAndDispatchEvent("intel.xdk.camera.picture.remove", { success: true, filename: picURL }); } else { /*var ev = document.createEvent('Events'); ev.initEvent('intel.xdk.camera.picture.remove', true, true); ev.success = false; ev.filename = picURL; document.dispatchEvent(ev);*/ me.createAndDispatchEvent("intel.xdk.camera.picture.remove", { success: false, filename: picURL }); } }, function (error) { } ) } ); }, clearPictures: function () { var me = module.exports; var applicationData = Windows.Storage.ApplicationData.current; var localFolder = applicationData.localFolder; try { localFolder.createFolderAsync(intel.xdk.camera.pictureLocation.replace(me.pictureExtension, ""), Windows.Storage.CreationCollisionOption.openIfExists).then( function (dataFolder) { var list = new WinJS.Binding.List(me.pictureList); list.forEach(function (value, index, array) { dataFolder.getFileAsync(value).then( function (file) { if (file) { file.deleteAsync(); } else { } }, function (error) { } ) }); /*var ev = document.createEvent('Events'); ev.initEvent('intel.xdk.camera.internal.picture.clear', true, true); ev.success = true; document.dispatchEvent(ev);*/ me.createAndDispatchEvent("intel.xdk.camera.internal.picture.clear", { success: true }); /*ev = document.createEvent('Events'); ev.initEvent('intel.xdk.camera.picture.clear', true, true); ev.success = true; document.dispatchEvent(ev);*/ me.createAndDispatchEvent("intel.xdk.camera.picture.clear", { success: true }); } ); } catch (e) { /*var ev = document.createEvent('Events'); ev.initEvent('intel.xdk.camera.picture.clear', true, true); ev.success = false; ev.message = 'Clearing images failed.'; document.dispatchEvent(ev);*/ me.createAndDispatchEvent("intel.xdk.camera.picture.clear", { success: false, message: "Clearing images failed" }); } }, cameraBusy: function() { var me = module.exports; /*var e = document.createEvent('Events'); e.initEvent('intel.xdk.camera.picture.busy', true, true); e.success=false;e.message='busy';document.dispatchEvent(e);*/ me.createAndDispatchEvent("intel.xdk.camera.picture.busy", { success: false, message: "busy" }); }, enumerateCameras: function() { var me = module.exports; Windows.Devices.Enumeration.DeviceInformation.findAllAsync(Windows.Devices.Enumeration.DeviceClass.videoCapture).done(function (devices) { for (var i = 0; i < devices.length; i++) { me.deviceList.push(devices[i]); } }); }, createAndDispatchEvent: function (name, properties) { var e = document.createEvent('Events'); e.initEvent(name, true, true); if (typeof properties === 'object') { for (key in properties) { e[key] = properties[key]; } } document.dispatchEvent(e); }, }; commandProxy.add('IntelXDKCamera', module.exports);
var alertBox = function(opt){ var ele = document.body; var opt = opt || {}; var alertMain = ele.querySelector('.alert-bg'); var _this = this; this._opt = { title: opt.title || '标题', //标题文案 titleShow: opt.titleShow || false, //是否显示标题,默认否 content: opt.content || '内容', //内容文案 buttonShow: opt.buttonShow || false, //是否显示按钮,默认否 buttonText: opt.buttonText || '确定', //按钮文案 buttonCbk: opt.buttonCbk || this.cbk, //按钮事件 spaceHide: opt.spaceHide || false //点击空白是否关闭弹框,默认否 } this.init = function(){ var _bg = document.createElement('div'); var _body = document.createElement('div'); var _content = document.createElement('p'); _content.innerHTML = this._opt.content; _body.className = 'alert-body'; _bg.className = 'alert-bg'; _content.className = 'alert-content'; if(this._opt.titleShow){ var _title = document.createElement('h3'); var _span = document.createElement('span'); var _close = document.createElement('a'); _span.innerHTML = this._opt.title; _close.className = 'alert-close'; _close.setAttribute('href','javascript:;'); _close.onclick = this.cbk; _title.className = 'alert-title'; _title.appendChild(_span); _title.appendChild(_close); _body.appendChild(_title); } _body.appendChild(_content); if(this._opt.buttonShow){ var _button = document.createElement('button'); _button.className = 'alert-button'; _button.innerHTML = this._opt.buttonText; _button.onclick = this._opt.buttonCbk; _body.appendChild(_button); } _bg.appendChild(_body); _bg.onclick = this.cbk; ele.appendChild(_bg); } this.cbk = function(e){ if(_this._opt.spaceHide == false && e.target.className == 'alert-bg'){ return ; } if(e.target.className == 'alert-bg' || e.target.className == 'alert-close' || e.target.className == 'alert-button'){ ele.querySelector('.alert-bg').className += ' hide'; } e.preventDefault(); e.stopPropagation(); } if(alertMain){ alertMain.remove(); } init(); }
describe('Route: Home', () => { describe('Unauthenticated', () => { beforeEach(() => { cy.visit('http://localhost:3000'); }); it('Redirects to Sign-In route when unauthenticated', () => { cy.url().should('include', '/sign-in'); cy.contains('Sign In with Google'); }); it('Redirects to Workflow route on sign-in', () => { cy.login(); cy.url().should('include', '/workflow'); }); afterEach(() => { cy.logout(); }); }); describe('Authenticated', () => { beforeEach(() => { cy.visit('http://localhost:3000'); cy.login(); }); afterEach(() => { cy.logout(); }); it('Redirects to Workflow route on sign-in', () => { cy.visit('http://localhost:3000'); cy.login(); cy.url().should('include', '/workflow'); }); it('can navigate to Projects route', () => { cy.get('[data-testid="SVGSideBar"]').click(); cy.get('[data-testid="projects"]').click(); cy.url().should('include', '/projects'); }); it('can navigate to Users route', () => { cy.get('[data-testid="SVGSideBar"]').click(); cy.get('[data-testid="users"]').click(); cy.url().should('include', '/users'); }); it('can navigate to Account route', () => { cy.get('[data-testid="account"]').click(); cy.url().should('include', '/account'); }); }); }); // Firestore Tests // it('adds document to firestore collection', () => { // cy.callFirestore('add', 'this is a test', { some: 'value' }); // });
var { Post, PostImage, PostType, PostPropertyType, PostFurnishing } = require('./models/post') const mongoose = require('mongoose'); const uri = process.env.MONGODB_URI || 'mongodb://localhost/rose' || 'mongodb+srv://user1:mongodb@cluster0.o1zql.mongodb.net/rose?retryWrites=true&w=majority'; const options = { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false, autoIndex: false, // Don't build indexes poolSize: 10, // Maintain up to 10 socket connections serverSelectionTimeoutMS: 2000, // Keep trying to send operations for 5 seconds socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity family: 4 // Use IPv4, skip trying IPv6 }; mongoose.connect(uri, options).then(connection => { console.log("CONEECTION SUCESS","======="); PostType.create({name:"1 BHK"}) PostType.create({name:"2 BHK"}) PostType.create({name:"3 BHK"}) PostType.create({name:"4 BHK"}) PostType.create({name:"5+ BHK"}) PostPropertyType.create({name:"CONDO"}) PostPropertyType.create({name:"APARTMENT"}) PostPropertyType.create({name:"TOWN HOUSE"}) PostFurnishing.create({name:"Furnished"}) PostFurnishing.create({name:"Semi-Furnished"}) PostFurnishing.create({name:"UnFurnished"}) }).catch((err) => { console.log(err); })
// parkscrape.js - Sally Calpo <spcalpo@gmail.com> // Requires node.js and jsdom // To install jsdom: npm install jsdom const CITY_NAME = "San Jose CA"; const CSS_SELECTOR = "#rhs_block"; const DATA_DIR = "data"; const SEARCH_URL = "https://www.google.com/search?q="; const USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"; var jsdom = require('jsdom'); var fs = require('fs'); // get csv file name from cmd line var csvFileName = process.argv[2]; // create data dir if necessary fs.stat(DATA_DIR, (err, stats) => { if(err) { // directory doesn't exist, so create it fs.mkdir(DATA_DIR, (err) => { if(err) { console.log("Couldn't create directory " + DATA_DIR + ". Aborting."); return false; } }); } if(!stats.isDirectory()) { // DATA_DIR exists, but is not a directory console.log(DATA_DIR + " is not a directory. Aborting."); return false; } }); // open csv file & process data if(csvFileName !== undefined && csvFileName !== null) { fs.readFile(csvFileName, 'utf8', (err, csvData) => { if(err) { console.log(csvFileName + " could not be read.") return false; } // read row from csv file csvData.split('\n').forEach((csvRow, index) => { // skip header row and empty rows if(index > 0 && csvRow != '') { // get park name from row var parkName = csvRow.split(',')[0]; // append city name & replace spaces with '+' to construct search query var searchQuery = (parkName + ' ' + CITY_NAME).replace(/ /gi, '+'); // jsdom pulls html data from url as if accessed by userAgent jsdom.env({ url: SEARCH_URL + searchQuery, userAgent: USER_AGENT, onload: (window) => { // after search results load, if not null, save to file var parkData = window.document.querySelector(CSS_SELECTOR); if(parkData !== null) { // replace spaces in park name with '_' to construct filename var parkDataFileName = DATA_DIR + "/" + parkName.replace(/ /gi, '_') + ".html"; // write park data file console.log("Found park data for " + parkName + ". Writing file to " + parkDataFileName + "."); fs.writeFile(parkDataFileName, parkData.outerHTML, (err) => { if(err) { console.log(parkDataFileName + " could not be written."); } }); } }, }); } }); }); } else { // print usage help if filename is missing console.log("Usage: node parkscrape.js <name of CSV file w/park names>"); return false; }
import sum from "../../src/js/services/sum"; describe('Sum function', () => { it("should calculate a sum", () => { expect(sum(1, 5)).toBe(6); }) });
// Place your application-specific JavaScript functions and classes here // This file is automatically included by javascript_include_tag :defaults var facebook_api = null; $(document).ready( function() { // Just because the document is loaded doesn't mean the FB // library has finished loading. Including all the usual onready() // stuff inside this callback. FB.init( api_key, xd_receiver ); FB.ensureInit(function() { facebook_api = FB.Facebook.apiClient; try { if( top.location.host == undefined ) { throw( "error" ); } //## Outside Facebook if( top.location.pathname == "/chat" ) { //## Outside Facebook but inside our chat frame } else { //## Outside Facebook not in any frames } } catch( err ) { //## Inside a Facebook iframe FB.CanvasClient.startTimerToSizeToContent(); } check_cookie(); }); // ensureInit }); // ready function check_cookie() { if( typeof session_cookie != "undefined" && typeof session_id != "undefined" ) { if( $.cookie( session_cookie ) != session_id ) { /* if( $.browser.mozilla ) { $('body').html( $('#third_party_cookies_disabled').html() ); } else { */ fix_cookie_with_ajax( function() { if( $.cookie( session_cookie ) != session_id ) { fix_cookie_with_form(); } } ); /* } */ } } }
import React, {Component} from 'react'; import PropTypes from "prop-types"; import TabItem from "./TabItem"; export default class Accordion extends Component { constructor(props) { super(props); this.state = { tabs: this.props.tabs, isActive: Array.from({ length: this.props.tabs.length }, (x) => false) }; this.handleClick = this.handleClick.bind(this); } handleClick(index) { const tmp = this.state.isActive; tmp[index] = !tmp[index]; this.setState(prevState => ({tabs: prevState.tabs, isActive: tmp})); } render() { return (<div> { this.state.tabs.map((item, index) => { return (<TabItem index={index} header={item.header} content={item.content} onActive={this.handleClick} headerClass={this.state.isActive[index] ? "card-header active text-white bg-info" : "card-header text-white bg-info"} contentClass={this.state.isActive[index] ? "card-body" : "card-body d-none"}/>); }) } </div>); } } Accordion.propTypes = { tabs: PropTypes.arrayOf(PropTypes.shape({header: PropTypes.string, content: PropTypes.string})) };
const Profile = require('../models/profile'); const User = require('../models/Users'); const exphbs = require("express-handlebars"); // Functions for the MVC user db module.exports = { find: function(req, res) { // console.log(req); console.log("req.params: ", req.body.id); User.findById(req.params.userId).populate("Profile").then(function(data) { // res.json(data); console.log(data); res.json(data) // res.send("profile", { profiles: data }); }).catch(function(err) { res.json(err); }); }, insert: function(req, res) { console.log(req.body) Profile.create(req.body) .then(function(data) { console.log("Profilecontroller data: ", data); res.render("profile", { profiles: data } ); }).catch(function(err) { res.json(err); }); }, delete: function(req, res) { Profile.remove({_id: req.params.id }).then(function() { res.redirect("main"); }).catch(function(err) { res.json(err); }); }, update: function(req, res) { Profile.update({ _id: req.params.id }).then(function(data) { res.json(data); }).catch(function(err) { res.json(err); }); } };
define(['./module'], function (constants) { 'use strict'; constants.constant('MENU', { HOME: '/#/', CUSTOMERS: '/#/customers' }); });
/** * Copyright 2014 Pacific Controls Software Services LLC (PCSS). All Rights Reserved. * * This software is the property of Pacific Controls Software Services LLC and its * suppliers. The intellectual and technical concepts contained herein are proprietary * to PCSS. Dissemination of this information or reproduction of this material is * strictly forbidden unless prior written permission is obtained from Pacific * Controls Software Services. * * PCSS MAKES NO REPRESENTATION OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTANILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGMENT. PCSS SHALL * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ /** * Version : 1.0 * User : pcseg306 * Function : This file is controller file for all user login flow related functions binded with html page. */ gxMainApp.controller("loginFlowController", function ($scope,$rootScope) { /****** SECTION FOR LOGIN FORM****/ /** * @ function to submit the LOGIN FORM */ $scope.submitLoginCredentials = function(isValid) { // check to make sure the form is completely valid if (isValid) { //$rootScope.moduleState ='home'; window.location.href = '#Home'; } }; });
import React from 'react'; import Button from '@material-ui/core/Button'; import TextField from '@material-ui/core/TextField'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; // import DialogContentText from '@material-ui/core/DialogContentText'; // import DialogTitle from '@material-ui/core/DialogTitle'; import './index.css'; const ActionGroups = () => { const [open, setOpen] = React.useState(false); const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; return ( <div className="" style={{ display: 'flex', width: '48%', paddingTop: '90px', marginLeft: 'auto', marginRight: 'auto' }}> <div className="container"> <div className="content"> <div className="content-overlay"></div> <Button style={{ width: '400px', height: '300px' }} onClick={handleClickOpen}> <img src="images/action-4.jpg" alt=""></img> </Button> <Dialog open={open} style={{ margin: '0, auto' }} onClose={handleClose} aria-labelledby="form-dialog-title"> <div style={{ display: 'flex' }}> <div style={{ backgroundColor: '#2d2d35', width: '190%' }}> <h2 style={{ marginTop: '55px', paddingLeft: '10px', paddingRight: '10px', textAlign: 'center' }}> Match Me </h2> </div> <DialogContent style={{ width: '1800px', height: '500px' }}> <div style={{ display: 'block' }}> <Button style={{ marginLeft: '294px' }} onClick={handleClose} color="primary"> X </Button> <h4 style={{ marginTop: '18px' }}> ENTER YOUR EMAIL BELOW TO UNLOCK </h4> <TextField autoFocus margin="dense" id="name" label="First Name" type="email" fullWidth /> <TextField autoFocus margin="dense" id="name" label="Last Name" type="email" fullWidth /> <TextField autoFocus margin="dense" id="name" label="Email Address" type="email" fullWidth /> <TextField autoFocus margin="dense" id="name" label="Phone Number" type="email" fullWidth /> <DialogActions> <Button onClick={handleClose} color="primary"> Cancel </Button> <Button onClick={handleClose} color="primary"> Subscribe </Button> </DialogActions> </div> </DialogContent> </div> </Dialog> <div className="content-details fadeIn-top"> <h3>Match me with apartment</h3> </div> </div> </div> <div className="container"> <div className="content"> <a href="#" target="_blank"> <div className="content-overlay"></div> <img src="images/action-2.png" style={{ width: '500px', height: '300px' }} alt=""></img> <div className="content-details fadeIn-top"> <h3>SEE THE LOCATION</h3> </div> </a> </div> </div> </div> ); }; export default ActionGroups;
/*jshint expr: true*/ var bsp = require('../js/lib/bsp.js'), vector = require('../js/lib/vector.js'), Plane = require('../js/lib/plane.js'), expect = require('chai').expect, THREE = require('three'); describe('Vector', function() { describe('#negate', function() { it('should return the negative of each vector element', function() { var a = { x:1, y:1, z:1 }; expect(vector.negate(a)).to.eql({ x: -1, y: -1, z: -1 }); }); }); describe('#add', function() { it('should return the component to component sum vector', function() { var a = { x:1, y:0, z:0 }; var b = { x:0, y:1, z:0 }; expect(vector.add(a, b)).to.eql({ x: 1, y: 1, z: 0 }); }); }); describe('#sub', function() { it('should return the component to component difference vector', function() { var a = { x:2, y:5, z:0 }; var b = { x:0, y:1, z:0 }; expect(vector.sub(a, b)).to.eql({ x: 2, y: 4, z: 0 }); }); }); describe('#dotProduct', function() { it('should return the dot product of two vectors', function() { var a = { x:1, y:0, z:1 }; var b = { x:1, y:2, z:3 }; expect(vector.dotProduct(a, b)).to.be.equal(4); }); it('should return 0 if vectors are perpendicular', function() { var a = { x:1, y:0, z:0 }; var b = { x:0, y:1, z:0 }; expect(vector.dotProduct(a, b)).to.be.equal(0); }); it('should return less than 0 if vectors are obtuse', function() { var a = { x:1, y:0, z:0 }; var b = { x:-1, y:1, z:0 }; expect(vector.dotProduct(a, b)).to.be.lessThan(0); }); it('should return greater than 0 if vectors are acute', function() { var a = { x:1, y:0, z:0 }; var b = { x:1, y:1, z:0 }; expect(vector.dotProduct(a, b)).to.be.greaterThan(0); }); }); describe('#crossProduct', function() { it('should return the correct direction and magnitude', function() { var a = { x:1, y:0, z:0 }; var b = { x:1, y:1, z:0 }; var sinTheta = Math.sin(Math.PI/4); var v = vector.crossProduct(a, b); // For whatever reason chai thinks that -0 doesn't equal 0 only in // an array. If I use expect(0).to.equal(-0) that test passes... expect(v).to.eql({ x:0, y:-0, z:1 }); expect(vector.magnitude(v)).to.equal(vector.magnitude(a) * vector.magnitude(b) * sinTheta); }); }); describe('#normalize', function() { it('should return a vector of length of 1', function() { var a = { x:3, y:4, z:5 }; expect(Math.abs(vector.magnitude(vector.normalize(a)))).to.closeTo(1, 0.0001); }); }); }); describe('Plane', function() { var plane = null, a, b, c; before(function() { a = { x:0, y:0, z:3 }; b = { x:1, y:0, z:3 }; c = { x:0, y:1, z:3 }; plane = Plane.createPlaneFromThreePoints(a, b, c); }); describe('#createPlane', function(){ it('should return a plane computed from three noncolinear points', function() { expect(plane).to.be.instanceof(Plane); expect(plane.normal).to.eql({ x:0, y:-0, z:1 }); expect(plane.d).to.equal(3); }); }); describe('#distance', function() { it('should return 0 for all points on plane', function() { expect(plane.distance(a)).to.equal(0); expect(plane.distance(b)).to.equal(0); expect(plane.distance(c)).to.equal(0); }); it('should return a positive value when points are in front of the plane', function() { expect(plane.distance({ x:1, y:2, z:5 })).to.be.greaterThan(0); }); it('should return a negative value when points are behind the plane', function() { expect(plane.distance({ x:1, y:2, z:-3 })).to.be.lessThan(0); }); }); describe('#splitPolygon', function() { it('should return two polygons, one in front and one behind, when a polygon straddles the plane', function() { var frontPolygon = {}, backPolygon = {}, a = { x: 0, y: 2, z: 0 }, b = { x: 3, y: -1, z: 0 }, c = { x: 6, y: 2, z: 0 }, intersection = { x: 3, y: 2, z: 0 }, plane = new Plane({ x: 1, y: 0, z: 0 }, 3), polygon = new bsp.Triangle(a, b, c, { x: 0, y: 0, z: 1 }); plane.splitPolygon(polygon, frontPolygon, backPolygon); expect(backPolygon).to.eql({ a: intersection, b: a, c: b, normal: { x: 0, y: 0, z: 1 } }); expect(frontPolygon).to.eql({ a: intersection, b: b, c: c, normal: { x: 0, y: 0, z: 1 } }); }); }); }); describe('SolidBSP', function() { var box = null, polygons = []; before(function() { box = new THREE.BoxGeometry(1, 1, 1); polygons = bsp.polygonsFromThreeJsGeometry(box); }); describe('#polygonsFromThreeJsGeometry', function() { it('should return a polygon for each face', function() { expect(polygons).to.have.length(box.faces.length); polygons.forEach(function(polygon, index) { expect(polygon).to.be.instanceof(bsp.Triangle); var face = box.faces[index]; expect(polygon.a).to.be.equal(box.vertices[face.a]); expect(polygon.b).to.be.equal(box.vertices[face.b]); expect(polygon.c).to.be.equal(box.vertices[face.c]); expect(polygon.normal).to.be.equal(face.normal); }); }); }); describe('#classifyPolygon()', function() { it('should return "front" if in front of the plane', function(){ var polygon = new bsp.Triangle({ x:-1, y:1, z:0 }, { x:1, y:0, z:0 }, { x:3, y:1, z:0 }, { x:0, y:0, z:1 }); var plane = new Plane({ x:0, y:1, z:0 }, 0); expect(bsp.classifyPolygon(polygon, plane)).to.equal("front"); }); it('should return "behind" if behind the plane', function(){ var polygon = new bsp.Triangle({ x:-1, y:-1, z:0 }, { x:1, y:-3, z:0 }, { x:3, y:-1, z:0 }, { x:0, y:0, z:1 }); var plane = new Plane({ x:0, y:1, z:0 }, 0); expect(bsp.classifyPolygon(polygon, plane)).to.equal("behind"); }); it('should return "straddle" if straddling the plane', function(){ var polygon = new bsp.Triangle({ x:-1, y:1, z:0 }, { x:1, y:-1, z:0 }, { x:3, y:1, z:0 }, { x:0, y:0, z:1 }); var plane = new Plane({ x:0, y:1, z:0 }, 0); expect(bsp.classifyPolygon(polygon, plane)).to.equal("straddle"); }); it('should return "coplanar" if coplanar to the plane', function() { var polygon = new bsp.Triangle({ x:-1, y:0, z:0 }, { x:1, y:0, z:1 }, { x:3, y:0, z:0 }, { x:0, y:0, z:-1 }); var plane = new Plane({ x:0, y:1, z:0 }, 0); expect(bsp.classifyPolygon(polygon, plane)).to.equal("coplanar"); }); }); describe('#isPointInside()', function() { it('should return true if a point is inside solid space', function() { var rootNode = bsp.createFromPolygons(polygons.slice()); var point = { x:0, y:0, z:0 }; expect(bsp.isPointInside(point, rootNode)).to.be.true; }); it('should return false when a point is outside of solid space', function() { var rootNode = bsp.createFromPolygons(polygons.slice()); var point = { x:2, y:2, z:2 }; expect(bsp.isPointInside(point, rootNode)).to.be.false; }); }); describe('#classifyBrush()', function() { it('should return the expected inside, outside, touching aligned, and touching inversed', function() { var otherBox = new THREE.BoxGeometry(1, 1, 1), translationMat4 = new THREE.Matrix4(); translationMat4.makeTranslation(0.5, 0, 0); otherBox.applyMatrix(translationMat4); var otherPolygons = bsp.polygonsFromThreeJsGeometry(otherBox); var brush = bsp.createFromPolygons(polygons.slice()); var otherBrush = bsp.createFromPolygons(otherPolygons); var results = brush.classifyBrush(otherBrush); expect(results.inside).to.have.length(2); expect(results.outside).to.have.length(10); expect(results.touchingAligned).to.have.length(8); }); }); });
'use strict'; import { StyleSheet } from 'react-native'; import COLOR from './Color'; export default StyleSheet.create({ safearea: { flex: 1, backgroundColor: COLOR.WHITE, }, //Shadow shadowSettings: { shadowColor: COLOR.BLACK, shadowOffset: { width: 0, height: 1, }, shadowOpacity: 0.18, shadowRadius: 1.00, elevation: 1, }, //TitleText textTitle: { fontSize: 20, fontWeight: 'bold', fontFamily: 'Helvetica Neue', color: COLOR.WHITE, opacity: 1.0 }, subTextTitle: { fontSize: 16, fontWeight: 'normal', fontFamily: 'Helvetica Neue', color: COLOR.WHITE, opacity: 0.5 }, // HomeScreens launchbutton: { marginRight: 40, marginLeft: 40, marginTop: 20, paddingTop: 20, paddingBottom: 20, backgroundColor: COLOR.WHITE, borderRadius: 10, borderWidth: 1, borderColor: COLOR.PRIMARY_LiGHT, }, launchbuttonText: { color: COLOR.PRIMARY_LiGHT, textAlign: 'center', }, homeContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', }, launchform: { justifyContent: 'center', width: '100%', height: '100%', }, // Main screens // Todo mainScreenContainer: { flex: 1, backgroundColor: COLOR.MAINSCREEN_BACKGROUND_COLOR, paddingTop: 10, paddingLeft: 0, }, todoImage: { alignSelf: 'flex-start', padding: 5, width: 20, height: 20, tintColor: COLOR.WHITE, opacity: 0.5 }, todoTitleText: { paddingLeft: 10, fontSize: 20, fontWeight: "bold", fontFamily: "Cochin", color: COLOR.WHITE, opacity: 0.5 }, // Profile profileContainer: { flex: 2, paddingTop: 30, marginLeft: 0, paddingLeft: 5, flexDirection: "row", }, profileBox: { width: 50, height: 50, }, rightArrowImage: { paddingLeft: 30, width: 15, height: 15, tintColor: COLOR.WHITE, opacity: 0.5 }, profileImage: { borderWidth: 2, borderColor: COLOR.WHITE, height: 40, width: 40, borderRadius: 20, overflow: 'hidden', }, //Allowance allowanceContainer: { flex: 2, paddingTop: 0, marginLeft: 0, flexDirection: "row", justifyContent: 'center', }, allowanceBox: { width: 100, height: 100, paddingLeft: 10, }, //Allowance Text allowanceTextContainer: { flex: 1, justifyContent: 'center', paddingTop: 10, padding: 8, }, allowanceContainerRow: { flexDirection: 'row', backgroundColor: 'transparent', }, amountText: { fontSize: 24, fontWeight: 'bold', fontFamily: 'Helvetica Neue', color: COLOR.WHITE, opacity: 1.0, paddingLeft: '40%' }, accountCardImage: { width: '120%', height: '120%', aspectRatio: 2, }, //Account accountContainer: { flex: 5, paddingTop: 0, marginLeft: 0, flexDirection: "row", justifyContent: 'center', }, accountBox: { width: 100, height: 100, paddingLeft: 10, backgroundColor: 'transparent', }, topUpbutton: { marginLeft: '67%', marginTop: 20, width: 100, height: 40, backgroundColor: COLOR.PRIMARY_DARK, borderRadius: 10, borderWidth: 2, borderColor: COLOR.PRIMARY_DARK, justifyContent: 'center', }, topUpButtonText: { color: COLOR.WHITE, fontWeight: 'bold', textAlign: 'center', }, //Track trackContainer: { flex: 5, paddingTop: 0, marginLeft: 0, flexDirection: "row", justifyContent: 'center', }, // Goals goalsContainerColumn: { flexDirection: 'column', backgroundColor: 'transparent', }, goalsbutton: { marginLeft: '20%', marginTop: '10%', width: 100, height: 40, backgroundColor: COLOR.PRIMARY_DARK, borderRadius: 10, borderWidth: 2, borderColor: COLOR.PRIMARY_DARK, justifyContent: 'center', }, goalsImage: { borderWidth: 3, borderColor: COLOR.MAINSCREEN_GREEN, height: 40, width: 40, borderRadius: 20, overflow: 'hidden', justifyContent: 'center', marginLeft: '40%', marginTop: '10%', }, goalsButtonText: { color: COLOR.WHITE, fontWeight: 'bold', textAlign: 'center', }, //Chores choresContainerColumn: { flexDirection: 'column', backgroundColor: 'transparent', }, choresbutton: { marginLeft: '20%', marginTop: '10%', width: 100, height: 40, backgroundColor: COLOR.PRIMARY_DARK, borderRadius: 10, borderWidth: 2, borderColor: COLOR.PRIMARY_DARK, justifyContent: 'center', }, choresImage: { borderWidth: 3, borderColor: COLOR.MAINSCREEN_GREEN, height: 40, width: 40, borderRadius: 20, overflow: 'hidden', justifyContent: 'center', marginLeft: '40%', marginTop: '10%', }, choresButtonText: { color: COLOR.WHITE, fontWeight: 'bold', textAlign: 'center', }, });
$(function() { $("#create_new_album").click(function() { $("#create_album_modal").modal(); }); $("#create_album_modal .btn").click(function() { var title = $("#create_album_modal input").val(); if(title == '') { alert("Please enter an album title"); return; } $.post('/api/create_new_album', { title: title }, function(data) { window.location = data.album_url; }); }); }); $(function() { /* $('#albumupload').fileupload({ add: function (e, data) { console.log('add'); console.log(e) console.log(data) //data.submit(); }, progress: function (e, data) { console.log('progress'); }, start: function (e) { console.log('start'); } }).bind('fileuploadadd', function (e, data) { console.log('fileuploadadd'); }).bind('fileuploadprogress', function (e, data) { console.log('fileuploadprogress'); }).bind('fileuploadstart', function (e) { console.log('fileuploadstart'); }); */ });
require('dotenv').config(); const express = require('express'); const logger = require('morgan'); const cookieParser = require('cookie-parser'); const connectDB = require('./config/db'); const app = express(); // connect database connectDB(); // middlewares app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); // routes require('./routes')(app); // global error handler require('./routes/globalErrorHandler')(app); // start the server const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Listening at http://localhost:${port}`); });
require('dotenv').config(); const tmi = require('tmi.js'); const client = new tmi.Client({ options: { debug: true }, connection: { reconnect: true, secure: true }, identity: { username: "captain_bboy", password: process.env.BOT_AUTH }, channels: [ 'captain_bboy' ] }); client.connect().catch(console.error); client.on('message', (channel, tags, message, self) => { if(self) return; if(message.toLowerCase() === '!hello') { client.say(channel, `Hey @${tags.username}!`); } });
import { computed } from '@ember/object'; import Component from '@ember/component'; import moment from 'moment'; export default Component.extend({ classNames: ['ember-appointment-slots-pickers'], init() { this._super(...arguments); this.baseProps = this.baseProps || {}; }, days: computed('baseProps.days', function () { return this.get('baseProps.days'); }).readOnly(), rows: computed('baseProps.rows', function () { return this.get('baseProps.rows'); }).readOnly(), cols: computed('baseProps.cols', function () { return this.get('baseProps.cols'); }).readOnly(), cellsPerCol: computed('baseProps.cellsPerCol', function () { return this.get('baseProps.cellsPerCol'); }).readOnly(), multiSelected: computed('baseProps.multiSelected', function () { return this.get('baseProps.multiSelected'); }).readOnly(), noSlotLabel: computed('baseProps.noSlotLabel', function () { return this.get('baseProps.noSlotLabel'); }).readOnly(), slotsAreLoading: computed('baseProps.slotsAreLoading', function () { return this.get('baseProps.slotsAreLoading'); }).readOnly(), selectedFilter: computed('baseProps.selectedFilter', function () { return this.get('baseProps.selectedFilter'); }).readOnly(), canSelectMultipleSlots: computed('baseProps.canSelectMultipleSlots', function () { return this.get('baseProps.canSelectMultipleSlots'); }).readOnly(), actions: { onDateChange(date) { if (this.baseProps.selectedFilter) { const col = this.cellsPerCol.find((item) => { const dayId = item.col.dayId; return dayId && moment(dayId).isSame(date, 'date'); }); if (col && col.cellsForCol.length && this.onSelectSlot) { this.onSelectSlot(col.cellsForCol[0]); } } } } });
import jwt from 'jsonwebtoken'; import authConfig from '../../config/auth'; const authMiddleware = (request, response, next) => { const xApiKey = request.headers['x-api-key']; if (!xApiKey) { return response.status(401).json({ error: 'Token not provided' }); } try { jwt.verify(xApiKey, authConfig.SECRET); } catch (error) { return response.status(401).json({ error: 'Invalid token' }); } return next(); }; export { authMiddleware };
function zeroArray(len) { var rv = new Array(len); while (--len >= 0) { rv[len] = 0; } return rv; } function arrays_equal(a,b) { return !(a < b || b < a); } function array_belong(array,elem) { for (var i = 0; i < array.length; i++) { if (arrays_equal(elem,array[i])) { return true; } } return false; } function alg2coor(alg) { var col = 'abcdefgh'.split('').indexOf(alg.charAt(0)); var row = 8 - parseInt(alg.charAt(1)); return 16*row + col; } function coor2alg(coor) { var col = coor%16; var row = 8 - (coor-col)/16; return 'abcdefgh'.charAt(col) + row; } // check if a fen string is valid // TODO: add check control! function validate_FEN(fen) { fenArray = fen.split(/\s+/); if (fenArray.length != 6) return false; if (isNaN(fenArray[5]) || (parseInt(fenArray[5], 10) <= 0)) return false; if (isNaN(fenArray[4]) || (parseInt(fenArray[4], 10) < 0)) return false; if (!/^(w|b)$/.test(fenArray[1])) return false; if (!/^(-|[abcdefgh][36])$/.test(fenArray[3])) return false; if( !/^(KQ?k?q?|Qk?q?|kq?|q|-)$/.test(fenArray[2])) return false; var rows = fenArray[0].split("/"); if (rows.length != 8) return false; var sum_pawns = [0,0]; var sum_kings = [0,0]; var sum_pieces = [0,0]; for (var i = 0; i < 8; i++) { var sum_fields = 0; var previous_was_number = false; for (var k = 0; k < rows[i].length; k++) { if (!isNaN(rows[i][k])) { if (previous_was_number) { return false; } sum_fields += parseInt(rows[i][k]); previous_was_number = true; } else { if (i == 0 || i == 7) { if (!/^[rnbqkRNBQK]$/.test(rows[i][k])) return false; } else { if (!/^[prnbqkPRNBQK]$/.test(rows[i][k])) return false; } sum_fields += 1; previous_was_number = false; if (rows[i][k] == rows[i][k].toUpperCase()) { sum_pieces[0]++; if (rows[i][k] == 'P') sum_pawns[0]++; if (rows[i][k] == 'K') sum_kings[0]++; } else { sum_pieces[1]++; if (rows[i][k] == 'p') sum_pawns[1]++; if (rows[i][k] == 'k') sum_kings[1]++; } } } if (sum_fields != 8) return false; } if ( sum_pawns[0] > 8 || sum_pawns[1] > 8 || sum_kings[0] != 1 || sum_kings[1] != 1 || sum_pieces[0] > 16 || sum_pieces[1] > 16 ) return false; return true; } function move (coordinates,isPromotion,promotion,fen) { this.coor = coordinates; this.isPromotion = isPromotion; this.promotion = promotion; this.fen = fen; this.comment = ''; } function chess () { // public variables this.movesList = [new move([-1,-1],false,0,defaultFEN)]; // the moves list this.kingsPosition = [116, 4]; // the positions of the kings, usefull to verify if a king is checked this.position = zeroArray(128); // initialize positions array with 0 array of dimension 128 this.castles = [[true,true],[true,true]]; // avaiblity of calstles [[white 0-0-0, white 0-0],[black 0-0-0, black 0-0]] this.legalMoves = []; // the legal moves in a specific moment. updated after every move this.turn = 0; // the turn, initialized whit 0 -> white // private variables var defaultFEN = 'rnbqkbnr\/pppppppp\/8\/8\/8\/8\/PPPPPPPP\/RNBQKBNR w KQkq - 0 1', // fen loaded if no other valid fen is passed actualCoordinates = [], // the coordinates of actual move actualIsPromotion = false, // boolean, is true if this move is a promotion move actualPromotion = 0, // id of promotion piece enPassant = -1, // coordiantes of enpassant square zIndex = 50, // z-index property only for graphical effects pawnMoves = 0; // variable for the pawn move variables (for fen string) // methods this.restart = function () { var self = this; self.parseFEN(defaultFEN); self.movesList = [new move([-1,-1],false,0,defaultFEN)]; self.findLegalMoves(); } // parse the fen string passed as argument this.parseFEN = function (fen) { this.position = zeroArray(128); // clean position vector //check if argument is a valid fen string if (!validate_FEN(fen)) fen = defaultFEN; var fenObj = _.object(['position', 'turn', 'castle','enpassant','pawnMoves','movesLength'],fen.split(' ')); var actualIndex = 0; for (var i = 0; i < fenObj.position.length; i++) { var ch = fenObj.position.charAt(i); if (!isNaN(ch)) actualIndex += parseInt(ch); // ch is a number else { if (ch == '\/') actualIndex += 8; else { var color = (ch == ch.toLowerCase()) ? 1 : 0; var pieceType = _.find(['PAWN','ROOK','NIGHT','BISHOP','QUEEN','KING'],function (str) {return (str.charAt(0) == ch.toUpperCase())}); this.position[actualIndex] = new piece(color,pieceType); // create new piece and put it in position if (ch == 'k') this.kingsPosition[1] = actualIndex; // update black king position if (ch == 'K') this.kingsPosition[0] = actualIndex; // update white king position actualIndex ++; } } } this.turn = (fenObj.turn == 'w') ? 0 : 1; // update turn this.castles = [[false,false],[false,false]]; // clean castle avaiblity for (var i = 0; i < fenObj.castle.length; i++) { var ch = fenObj.castle.charAt(i); if (ch == '-') break; var row = (ch == ch.toLowerCase()) ? 1 : 0; var col = (ch.toLowerCase() == 'k') ? 1 : 0; this.castles[row][col] = true; } if (fenObj.enpassant != '-') enPassant = alg2coor(fenObj.enpassant); pawnMoves = parseInt(fenObj.pawnMoves); }; // get the fen string this.getFEN = function () { var fen = ''; for (var row = 0; row < 8; row++) { var zeroCount = 0; for (var col = 0; col < 8; col++) { var pos = 16*row + col; var piece = this.position[pos]; if (piece == 0) zeroCount++; else { if (zeroCount > 0) { fen += zeroCount + piece.getFEN(); zeroCount = 0; } else fen += piece.getFEN(); } } if (zeroCount != 0) fen += zeroCount; if (row != 7) fen += "\/"; } fen = fen + ' ' + ['w','b'][this.turn] + ' '; var castleAvaible = false; for (var i = 0; i < 2; i++) { for (var j = 0; j < 2; j++) { if (this.castles[i][1-j]) { castleAvaible = true; fen += [['Q','K'],['q','k']][i][1-j]; } } } if (!castleAvaible) fen += '-'; fen += ' '; (enPassant != -1) ? fen += coor2alg(enPassant) : fen += '-'; fen += ' ' + pawnMoves; fen += ' ' + Math.floor(this.movesList.length/2 + 1); return fen; }; // execute the move passed as argument. return the captured piece. this.executeMove = function(move) { var from = move.coor[0]; var to = move.coor[1]; var piece = this.position[from]; var capturedPiece = this.position[to]; //update the position at index from and to this.position[to] = piece; this.position[from] = 0; //check if is an enPassant or castle move switch (piece.type) { case 'PAWN': var diff = Math.abs(from - to); if (diff == 32) enPassant = (from > to) ? to + 16 : to - 16; else if ((diff == 15 || diff == 17) && !capturedPiece) { //execute enpassant var capturedPosition = from > to ? to + 16 : to - 16; capturedPiece = this.position[capturedPosition]; this.position[capturedPosition] = 0; } break; case 'KING': this.kingsPosition[this.turn] = to; //update king position this.castles[this.turn] = [false,false]; //set castle to false if (Math.abs(from - to) == 2) { //make castle var rookTo = from + (from > to ? -1 : 1); var rookFrom = from + (from > to ? -4 : 3); this.position[rookTo] = this.position[rookFrom]; this.position[rookFrom] = 0; } break; case 'ROOK': //set castle to false if (this.turn == 1) { if (from == 0) this.castles[1][0] = false; else if (from == 7) this.castles[1][1] = false; } else if (this.turn == 0) { if (from == 112) this.castles[0][0] = false; else if (from == 119) this.castles[0][1] = false; } break; } //take carefull of promotion if (move.isPromotion) this.position[to].type = ['QUEEN','ROOK','NIGHT','BISHOP'][move.promotion]; this.turn = 1 - this.turn; return capturedPiece; }; // is player's king checked? this.isChecked = function (player) { var self = this; var bdir = [-15,15,-17,17]; // bishop direction var rdir = [-1,1,-16,16]; // rook direction var ndir = [-14,14,-18,18,-31,31,-33,33]; // night direction var kdir = [-1,1,-16,16,-15,15,-17,17]; // king direction var i = self.kingsPosition[player]; for (var k = 0; k < 4; k++) { var onBoard = _.filter(_.map(_.range(1,8),function (num) {return i + num*bdir[k];}), function (num) {return !(num & 0x88);}); var occupied = _.find(onBoard, function (num) {return self.position[num] != 0;}); if (!(_.isUndefined(occupied)) && self.position[occupied].color == 1 - player && ['QUEEN','BISHOP'].indexOf(self.position[occupied].type) != -1) return true; } for (var k = 0; k < 4; k++) { var onBoard = _.filter(_.map(_.range(1,8),function (num) {return i + num*rdir[k];}), function (num) {return !(num & 0x88);}); var occupied = _.find(onBoard, function (num) {return self.position[num] != 0;}); if (!(_.isUndefined(occupied)) && self.position[occupied].color == 1 - player && ['QUEEN','ROOK'].indexOf(self.position[occupied].type) != -1) return true; } for (var k = 0; k < 8; k++) { if (!((i + ndir[k]) & 0x88) && self.position[i + ndir[k]].color == 1 - player && self.position[i + ndir[k]].type == 'NIGHT') return true; } if (player == 0) { if (!((i - 15) & 0x88) && self.position[i - 15].type == 'PAWN' && self.position[i - 15].color == 1) return true; if (!((i - 17) & 0x88) && self.position[i - 17].type == 'PAWN' && self.position[i - 17].color == 1) return true; } if (player == 1) { if (!((i + 15) & 0x88) && self.position[i + 15].type == 'PAWN' && self.position[i + 15].color == 0) return true; if (!((i + 17) & 0x88) && self.position[i + 17].type == 'PAWN' && self.position[i + 17].color == 0) return true; } for (var k = 0; k < 4; k++) { if (!((i + kdir[k]) & 0x88) && self.position[i + kdir[k]].type == 'KING') { return true; } } return false; }; // is checkmate ? this.isCheckMate = function () { return ( this.isChecked(this.turn) && this.legalMoves.length == 0 );}; // is stalemate ? this.isStaleMate = function () { return ( !this.isChecked(this.turn) && this.legalMoves.length == 0 );}; // find the legal moves this.findLegalMoves = function () { var bdir = [-15,15,-17,17]; // bishop direction var rdir = [-1,1,-16,16]; // rook direction var ndir = [-14,14,-18,18,-31,31,-33,33]; // night direction var kdir = [-1,1,-16,16,-15,15,-17,17]; // king direction var s = 1; var piece = -1; var movesTemp = []; this.legalMoves = []; // clear the list // find the move without considering the checks for( var i = 0 ; i < 128 ; i++ ){ var piece = this.position[i]; if (piece.color != this.turn) continue; else { switch (piece.type) { case 'PAWN': if (this.turn == 0) { if (!this.position[i - 16]) { movesTemp.push([i,i - 16]); if (((i & 0x70) == 0x60) && !this.position[i - 32]) movesTemp.push([i,i - 32]); } if (!((i - 15) & 0x88) && this.position[i - 15] && (this.position[i - 15].color != this.turn)) movesTemp.push([i,i - 15]); if (!((i - 17) & 0x88) && this.position[i - 17] && (this.position[i - 17].color != this.turn)) movesTemp.push([i,i - 17]); } else { if (!this.position[i + 16]) { movesTemp.push([i,i + 16]); if (((i & 0x70) == 0x10) && !this.position[i + 32]) movesTemp.push([i,i + 32]); } if (!((i + 15) & 0x88) && this.position[i + 15] && (this.position[i + 15].color != this.turn)) movesTemp.push([i,i + 15]); if (!((i + 17) & 0x88) && this.position[i + 17] && (this.position[i + 17].color != this.turn)) movesTemp.push([i,i + 17]); } break; case 'NIGHT': for (var k = 0; k <= 7; k++) { if (!((i + ndir[k]) & 0x88) && (this.position[i + ndir[k]] == 0 || this.position[i + ndir[k]].color != this.turn )) movesTemp.push([i,i+ndir[k]]); } break; case 'BISHOP': for (var k = 0; k < 4; k++) { var step = 1; while (!(((i + step*bdir[k]) & 0x88)) && !this.position[i + step*bdir[k]]) { movesTemp.push([i,i+step*bdir[k]]); step++; } if (!(((i + step*bdir[k]) & 0x88)) && this.position[i + step*bdir[k]].color != this.turn) movesTemp.push([i,i+step*bdir[k]]); } break; case 'ROOK': for (var k = 0; k < 4; k++) { var step = 1; while (!(((i + step*rdir[k]) & 0x88)) && !this.position[i + step*rdir[k]]) { movesTemp.push([i,i+step*rdir[k]]); step++; } if (!(((i + step*rdir[k]) & 0x88)) && this.position[i + step*rdir[k]].color != this.turn) movesTemp.push([i,i+step*rdir[k]]); } break; case 'QUEEN': for (var k = 0; k < 8; k++) { var step = 1; while (!(((i + step*kdir[k]) & 0x88)) && !this.position[i + step*kdir[k]]) { movesTemp.push([i,i+step*kdir[k]]); step++; } if (!(((i + step*kdir[k]) & 0x88)) && this.position[i + step*kdir[k]].color != this.turn) movesTemp.push([i,i+step*kdir[k]]); } break; case 'KING': for (var k = 0; k < 8; k++) { if (!(((i + kdir[k]) & 0x88)) && (!this.position[i + kdir[k]] || this.position[i + kdir[k]].color != this.turn)) movesTemp.push([i,i+kdir[k]]); } break; } } } if (enPassant != -1) { for (var i = 0; i < 2; i++) { var posToCheck = enPassant + (this.turn == 0 ? 16 : -16) + Math.pow(-1,i); if (!(posToCheck & 0x88) && this.position[posToCheck] != 0 && this.position[posToCheck].color == this.turn && this.position[posToCheck].type == 'PAWN') { movesTemp.push([posToCheck,enPassant]); } } } // filter the move considering the checks var castlesTemp = [[0,0],[0,0]]; var turnTemp = this.turn; var positionTemp = []; var kingsTemp = []; for (var i = 0; i < 128; i++) { positionTemp.push(this.position[i]); } for (var i = 0; i < 2; i++) { kingsTemp.push(this.kingsPosition[i]); for (var j = 0; j < 2; j++) { castlesTemp[i][j] = this.castles[i][j]; } } for (var t = 0; t < movesTemp.length; t++) { var move = movesTemp[t]; this.executeMove({'coor': move, 'type': 0, 'promotion': 0}); if (!this.isChecked(1-this.turn)) { this.legalMoves.push(move); } for (var i = 0; i < 128; i++) { this.position[i] = positionTemp[i]; } for (var i = 0; i < 2; i++) { this.kingsPosition[i] = kingsTemp[i]; for (var j = 0; j < 2; j++) { this.castles[i][j] = castlesTemp[i][j]; } } this.turn = turnTemp; } movesTemp = []; if (this.turn == 0 && this.castles[0][1] && !(this.position[7*16+5]) && !(this.position[7*16+6]) && array_belong(this.legalMoves,[7*16 + 4,7*16 + 5])) movesTemp.push([7*16 + 4,7*16 + 6]); if (this.turn == 0 && this.castles[0][0] && !(this.position[7*16+1]) && !(this.position[7*16+2]) && !(this.position[7*16+3]) && array_belong(this.legalMoves,[7*16 + 4,7*16 + 3])) movesTemp.push([7*16 + 4,7*16 + 2]); if (this.turn == 1 && this.castles[1][1] && !(this.position[5]) && !(this.position[6]) && array_belong(this.legalMoves,[4,5])) movesTemp.push([4,6]); if (this.turn == 1 && this.castles[1][0] && !(this.position[1]) && !(this.position[2]) && !(this.position[3]) && array_belong(this.legalMoves,[4,3])) movesTemp.push([4,2]); for (var t = 0; t < movesTemp.length; t++) { var move = movesTemp[t]; this.executeMove({'coor': move, 'type': 0, 'promotion': 0}); if (!this.isChecked(1-this.turn)) { this.legalMoves.push(move); } for (var i = 0; i < 128; i++) { this.position[i] = positionTemp[i]; } for (var i = 0; i < 2; i++) { this.kingsPosition[i] = kingsTemp[i]; for (var j = 0; j < 2; j++) { this.castles[i][j] = castlesTemp[i][j]; } } this.turn = turnTemp; } enPassant = -1; }; this.move2PGN = function(start,end,capturing,otherMoves) { var self = this; var piece = self.position[end]; var moveString = ''; var endString = coor2alg(end); if (piece.type != 'PAWN' && !actualIsPromotion) moveString += piece.type.charAt(0); else { if (Math.abs(start - end) == 15 || Math.abs(start - end) == 17) { moveString += coor2alg(start).charAt(0); } } var others = _.map(_.filter(otherMoves, function (move) {return (move[1] == end && move[0] != start && self.position[move[0]].type == piece.type);}), function (move) { return move[0];}); uniqueCol = true; for (var i = 0; i < others.length; i++) { if ((others[i] - start)%16 == 0) { uniqueCol = false; break; } } uniqueRow = true; if (!uniqueCol) { for (var i = 0; i < others.length; i++) { if ((start-(start%16))/16 == (others[i]-(others[i]%16))/16) { uniqueRow = false; break; } } } if (piece.type == 'PAWN') { uniqueRow = true; uniqueCol = true; } if (others.length > 0) { if (uniqueCol) moveString += coor2alg(start).charAt(0); else if (uniqueRow) moveString += coor2alg(start).charAt(1); else moveString += coor2alg(start); } if (capturing) moveString += 'x'; moveString += endString; if (piece.type == 'KING') { if (end - start == 2) moveString = 'O-O'; if (end - start == -2) moveString = 'O-O-O'; } if (actualIsPromotion) moveString += '=' + 'QRNB'.charAt(actualPromotion); if (self.isChecked(self.turn)) { if (self.isCheckMate()) moveString += '#'; else moveString += '+'; } return moveString; }; this.pgn2move = function (pgn) { var self = this; var _coor, _promo = 0, _isPromo = false, _fen = ''; pgn = pgn.replace('+','').replace('#','').replace('x',''); if (pgn == 'O-O') { if (self.turn == 0) _coor = [7*16 + 4,7*16 + 6]; if (self.turn == 1) _coor = [4,6]; } else if (pgn == 'O-O-O') { if (self.turn == 0) _coor = [7*16 + 4,7*16 + 2]; if (self.turn == 1) _coor = [4,2]; } else { splittedPgn = pgn.split('='); if (splittedPgn.length == 2) { _isPromo = true; _promo = ['Q','R','N','B'].indexOf(splittedPgn[1]); } pgn = splittedPgn[0]; endSquare = alg2coor(pgn.slice(pgn.length-2,pgn.length)); startString = pgn.slice(0,pgn.length-2); if (startString.length > 0 && startString.charAt(0) == startString.charAt(0).toUpperCase()) { var t = startString.charAt(0); } else { startString = 'P' + startString; var t = 'P'; } filteredMoves = _.filter(self.legalMoves, function(coor) { return (coor[1] == endSquare && self.position[coor[0]].type.charAt(0) == t); }); if (filteredMoves.length == 1) _coor = filteredMoves[0]; else if (filteredMoves.length == 2) { var col = ['a','b','c','d','e','f','g','h'].indexOf(startString.charAt(1)); if (col != -1) { filteredMoves = _.filter(filteredMoves, function(coor) { return (coor[0] - col) % 16 == 0; }); } else filteredMoves = _.filter(filteredMoves, function(coor) { return Math.abs(coor[0] - parseInt(startString.charAt(1))) <= 7; }); } else if (filteredMoves.length == 3) { var col = ['a','b','c','d','e','f','g','h'].indexOf(startString.charAt(1)); var row = parseInt(startString.charAt(1)); filteredMoves = _.filter(filteredMoves, function(coor) { return (Math.abs(coor[0] - row) <= 7 && (coor[0] - col) % 16 == 0); }); } _coor = filteredMoves[0] } return new move(_coor,_isPromo,_promo,_fen); }; } function piece (color,type) { this.color = color; this.type = type; this.setType = function (newType) { this.type = newType; } this.getFEN = function() { var fenCharacter = this.type.charAt(0); if (color) fenCharacter = fenCharacter.toLowerCase(); return fenCharacter; } }
require([ "esri/request" ], function ( esriRequest ) { esriRequest("https://services3.arcgis.com/JuknJLoAEm9DTWXh/arcgis/rest/services/Updated/FeatureServer/0/query?where=1%3D1&objectIds=&time=&resultType=none&outFields=Updated&returnIdsOnly=false&returnUniqueIdsOnly=false&returnCountOnly=false&returnDistinctValues=false&cacheHint=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&having=&resultOffset=&resultRecordCount=&sqlFormat=none&f=pjson&token=",{ responseType:"json" }).then(function(response){ document.getElementById("updated").innerHTML = response.data.features[0].attributes['Updated']; }) });
import React from 'react'; import './style.scss'; const Logistique = () => { return ( <div classname="logistique"> <h1>logistique</h1> </div> ) } export default Logistique;
import { connect } from 'react-redux'; import MessagesList from './MessagesList'; let mapStateToProps = (state) => { return { messages: state.dialogsPage.dialogs[0].messages }; }; let mapDispatchToProps = (dispatch) => { return { }; }; const MessagesListContainer = connect(mapStateToProps, mapDispatchToProps)(MessagesList); export default MessagesListContainer;
/* jshint indent: 2 */ module.exports = function(sequelize, DataTypes) { return sequelize.define('rep_personalizations_conversion', { rep_conversion_id: { type: DataTypes.INTEGER(10).UNSIGNED, allowNull: false, primaryKey: true, autoIncrement: true }, date: { type: DataTypes.DATEONLY, allowNull: false }, pfl_personalization_id: { type: DataTypes.INTEGER(11), allowNull: false }, first_visit: { type: DataTypes.INTEGER(11), allowNull: false }, second_visit: { type: DataTypes.INTEGER(11), allowNull: false }, third_visit: { type: DataTypes.INTEGER(11), allowNull: false }, more_visit: { type: DataTypes.INTEGER(11), allowNull: false }, cg: { type: DataTypes.INTEGER(1), allowNull: false } }, { tableName: 'rep_personalizations_conversion' }); };
import React from "react"; import styled from "styled-components"; import useEditForm from "../hooks/useEditForm"; export default function EditForm({ title, inputs, handleSubmitForm, isNestedInput = false, }) { const { data, handleSubmit, handleChange } = useEditForm( inputs, handleSubmitForm ); function onChangeNestedValue(e, name, unit) { handleChange({ target: { name: name, value: { value: e.target.value, unit }, }, }); } function onChangeNestedUnit(e, name, value) { handleChange({ target: { name: name, value: { value: value, unit: e.target.value }, }, }); } return ( <FormContainer onSubmit={handleSubmit}> <Name>{title}</Name> {isNestedInput && Object.entries(data).map(([name, value]) => ( <S_Row> <Label key={name + "value"}> <Name>{name} value</Name> <TextInput type="text" name={name + "value"} placeholder={name} value={value.value} onChange={(e) => onChangeNestedValue(e, name, value.unit)} /> </Label> <Label key={name + "unit"}> <Name>{name} unit</Name> <TextInput type="text" name={name + "unit"} placeholder={name} value={value.unit} onChange={(e) => onChangeNestedUnit(e, name, value.value)} /> </Label> </S_Row> ))} {!isNestedInput && Object.entries(data).map(([name, value]) => ( <Label key={name}> <Name>{name}</Name> <TextInput type="text" name={name} placeholder={name} value={value} onChange={handleChange} /> </Label> ))} <ButtonContainerAlignRight> <GreyButton type="submit">Ok</GreyButton> </ButtonContainerAlignRight> </FormContainer> ); } const S_Row = styled.div` display: flex; flex-direction: row; `; const Name = styled.div` padding-left: 0.3rem; padding-top: 0.5rem; font-weight: 500; `; const Label = styled.label` display: flex; flex-direction: column; align-items: flex-start; justify-content: center; width: 100%; & input { width: 100%; } `; const FormContainer = styled.form` position: relative; display: flex; flex-direction: column; justify-content: center; align-items: center; width: 100%; background: rgba(255, 255, 255, 1); border: 1px solid rgb(243, 243, 243); box-shadow: 4px 17px 20px 0px rgb(0 0 0 / 8%); padding: 12px 12px; box-sizing: border-box; `; const TextInput = styled.input` width: 100%; height: 50px; box-sizing: border-box; margin: 0; font-family: sans-serif; font-size: 15px; letter-spacing: 1px; padding: 0; padding-left: 8px; color: #111111; display: inline-block; border: none; border-bottom: 1px solid rgba(0, 0, 0, 0.08); border-radius: 0; background-color: #fbfbfb; &:focus { outline: none; } `; const ButtonContainerAlignRight = styled.div` text-align: right; `; const GreyButton = styled.button` width: 51px; height: 45px; background-color: rgba(255, 255, 255, 0.95); color: #111111; font-family: sans-serif; font-size: 12px; letter-spacing: 1px; font-weight: 300; border: transparent 1px solid; box-shadow: 0px 3px 6px -6px rgb(0 0 0 / 32%); opacity: 1; line-height: 1; box-sizing: border-box; margin: 0; padding: 0; cursor: pointer; text-transform: none; position: relative; border-radius: 0; display: inline-block; width: auto; height: 50px; padding-left: 30px; padding-right: 30px; min-width: 135px; background: #f7f7f7; &:hover { background: #e0dfdf; } `;
import mongoose from 'mongoose'; mongoose.connect('mongodb://localhost/psy-links'); export default mongoose;
import { combineReducers } from 'redux'; import { createReducer } from '@reduxjs/toolkit'; import * as actions from './actions'; const contacts = createReducer( [ { id: 'id-1', name: 'Rosie Simpson', number: '459-12-56' }, { id: 'id-2', name: 'Hermione Kline', number: '443-89-12' }, { id: 'id-3', name: 'Eden Clements', number: '645-17-79' }, { id: 'id-4', name: 'Annie Copeland', number: '227-91-26' }, ], { [actions.addContact]: (state, { payload }) => { const contactName = state.find( contact => contact.name.toLowerCase() === payload.name.toLowerCase(), ); const contactNumber = state.find(contact => contact.number === payload.number); if (contactName) { alert(`${payload.name} is already in contacts`); return state; } if (contactNumber) { alert(`${payload.number} is already in contacts`); return state; } return [payload, ...state]; }, [actions.deleteContact]: (state, { payload }) => state.filter(contact => contact.id !== payload), }, ); const filter = createReducer('', { [actions.filterContacts]: (_, { payload }) => payload, }); export default combineReducers({ contacts, filter, });
// @ts-check const FileLoader = require("./FileLoader"); const Op = require("./Operators"); class Parser { /** * @param {string} strFileName */ constructor(strFileName) { this._strFileName = strFileName; this._arrRawFormulas = []; this._arrParsedFormulas = []; } async processFile() { const strFileContents = await FileLoader.readFile(this._strFileName); this._arrFormulas = this._separateFormulas(strFileContents); // Concatanate all formulas using operator AND this._arrFormulas = [this._arrFormulas.reduce((acc, red) => { if(acc.length === 0) { return `(${red})`; } return acc += `&(${red})`; }, "")]; for(let strFormula of this._arrFormulas) { this._arrRawFormulas.push(strFormula); this._arrParsedFormulas.push(this._parseFormula(strFormula)); } } printAllFormulas() { for(let objFormula of this._arrParsedFormulas) { console.log("----------------------------------"); console.log(JSON.stringify(objFormula, null, 4)); console.log("----------------------------------\n"); } } _parseFormula(strFormula) { // First make sure to eliminate all white spaces and line endings strFormula = strFormula.replace(/ |\r?\n|\r/g,''); return this._addExpressionBlock(strFormula, true); } _addExpressionBlock(strFormula, bFirstCall = false) { console.log("Parsing: " + strFormula); const objCurrentBlock = {}; if(strFormula.length === 0) { throw new Error("Empty string representation of formula given."); } // Make sure the raw formula is not bounded by redundant parentheses if( strFormula.charAt(0) === "(" && strFormula.charAt(strFormula.length - 1) === ")" && bFirstCall === false ) { strFormula = strFormula.substring(1, strFormula.length - 1); } // // Check if there are parentheses // if(strFormula.indexOf("(") !== -1) let nOpenParenthesesCount = 0; let nPrincipalOpOffset = null; let principalOp = null; for(let i = 0; i < strFormula.length; i++) { let strCurrentChar = strFormula.charAt(i); // Only use the operators that are exterior to any parentheses if(strCurrentChar === "(") { nOpenParenthesesCount++; } if(strCurrentChar === ")") { nOpenParenthesesCount--; } if(nOpenParenthesesCount != 0) { continue; } if(strCurrentChar === Op.OR.symbol) { nPrincipalOpOffset = i; principalOp = Op.OR; break; } if(strCurrentChar === Op.AND.symbol && principalOp !== Op.AND) { nPrincipalOpOffset = i; principalOp = Op.AND; } if(strCurrentChar === Op.NOT.symbol && principalOp === null) { nPrincipalOpOffset = i; principalOp = Op.NOT; } if(strCurrentChar === Op.IMP.symbol.charAt(0) && principalOp === null) { nPrincipalOpOffset = i; principalOp = Op.IMP; } if(strCurrentChar === Op.EQI.symbol.charAt(0) && principalOp === null) { nPrincipalOpOffset = i; principalOp = Op.EQI; } } if(principalOp === null || nPrincipalOpOffset === null) { throw new Error("No valid operator found in expression. Check syntax."); } if(principalOp.type === "unary") { if(nPrincipalOpOffset === (strFormula.length - 1)) { throw new Error("No characters left."); } objCurrentBlock.op = principalOp.name; if(strFormula.charAt(nPrincipalOpOffset + 1) === "(") { // If is not primitive then it must be a parantheses block objCurrentBlock.expR = this._addExpressionBlock(strFormula.substring(nPrincipalOpOffset + 1, strFormula.length)); } else { objCurrentBlock.expR = strFormula.charAt(nPrincipalOpOffset + 1); } } if(principalOp.type === "binary") { objCurrentBlock.op = principalOp.name; // Checks for the left expression if(nPrincipalOpOffset > 1) { objCurrentBlock.expL = this._addExpressionBlock(strFormula.substring(0, nPrincipalOpOffset)); } else { objCurrentBlock.expL = strFormula.charAt(0); } // Checks for the right expression if(strFormula.length - nPrincipalOpOffset > 2) { objCurrentBlock.expR = this._addExpressionBlock(strFormula.substring(nPrincipalOpOffset + 1, strFormula.length)); } else { objCurrentBlock.expR = strFormula.charAt(nPrincipalOpOffset + 1); } } return objCurrentBlock; } _separateFormulas(strFileContents) { const arrFormulas = strFileContents.split("\n"); return arrFormulas; } get parsedFormulas() { return this._arrParsedFormulas; } } module.exports = Parser;
const Sequelize = require('sequelize'); module.exports = function(sequelize, DataTypes) { return sequelize.define('CheckoutAgreement', { agreement_id: { autoIncrement: true, type: DataTypes.INTEGER.UNSIGNED, allowNull: false, primaryKey: true, comment: "Agreement ID" }, name: { type: DataTypes.STRING(255), allowNull: true, comment: "Name" }, content: { type: DataTypes.TEXT, allowNull: true, comment: "Content" }, content_height: { type: DataTypes.STRING(25), allowNull: true, comment: "Content Height" }, checkbox_text: { type: DataTypes.TEXT, allowNull: true, comment: "Checkbox Text" }, is_active: { type: DataTypes.SMALLINT, allowNull: false, defaultValue: 0, comment: "Is Active" }, is_html: { type: DataTypes.SMALLINT, allowNull: false, defaultValue: 0, comment: "Is Html" }, mode: { type: DataTypes.SMALLINT, allowNull: false, defaultValue: 0, comment: "Applied mode" } }, { sequelize, tableName: 'checkout_agreement', timestamps: false, indexes: [ { name: "PRIMARY", unique: true, using: "BTREE", fields: [ { name: "agreement_id" }, ] }, ] }); };
'use strict'; const endPoint = 'http://thebulletin.org/timeline'; const request = require('request'); const cheerio = require('cheerio'); const midnight = new Date(2000, 0, 0, 0, 0, 0, 0); const toTime = mins => new Date(midnight.getTime() + mins * -60000); const pad = (min, input) => { const out = input + '' while (out.length < min) out = '0' + out return out } /** * Minutes to midnight. */ const conf = { source: endPoint, selector: '.view-content .node-title', title: /(?:(\d+)|(one|two|three|four|five|six|seven|eight|nine)(.*?half)) minutes to midnight/i }; /** * Request the current minutes to midnight feed. * * Also contains a bunch of unrelated other posts. */ const _request = () => new Promise((resolve, reject) => request(conf.source, function(error, response, body) { if (error) return reject(err); if (response.statusCode !== 200) return reject("Unexpected status code") return resolve(body) })); const dateToString = (d) => pad(2, d.getHours() - 12) + ':' + pad(2, d.getMinutes()) + (d.getSeconds() ? ':' + pad(2, d.getSeconds()) : '') + ' PM'; const numberStringToInt = value => { switch (value.toLowerCase()) { case 'one': return 1; case 'two': return 2; case 'three': return 3; case 'four': return 4; case 'five': return 5; case 'six': return 6; case 'seven': return 7; case 'eight': return 8; case 'nine': return 9; } return NaN; }; const _extract = data => new Promise((resolve, reject) => { const $ = cheerio.load(data); const nodes = $(conf.selector) .map(function() { return $(this).text() }) .get(); for (const node of nodes) { const result = node.match(conf.title); if (result) { if (!isNaN(result[1])) return resolve(parseInt(result[1])); if (result[2]) { const whole = numberStringToInt(result[2]); if (!isNaN(whole)) return resolve(whole + 0.5); } } } reject("No result found"); }); const M2M = () => _request() .then(_extract) .then(x => dateToString(toTime(x))); module.exports = M2M;
var ExperimentReport = Backbone.Model.extend({ defaults : function(){}, initialize : function(){}, parse : function(response){ if(response.status && response.status.code == 1000){ return response.data; } return response; }, error : function(model, error){ if(error.status == 500){ var data = $.parseJSON(error.responseText); this.set('status', {isError : true, message : data.message}, {silent : true}); }else if(error.statusText != undefined){ this.set('status', {isError : true, message : error.statusText}, {silent : true}); }else{ this.set('status', {isError : true, message : error}, {silent : true}); } }, synced : function(model, error){ this.set('status', {isError : false}); } }); var ExperimentReportList = Backbone.Collection.extend({ model : ExperimentReport, url : function(){ return '/api/reports_data'; }, parse : function(response){ if(response.status && response.status.code == 1000){ return response.data; } return null; } }); var reportsList = new ExperimentReportList(); var ExperimentReportView = Views.BaseView.extend({ tagName : "div", initialize : function(){ this._super('initialize'); this.loadTemplate('experiment-report'); this.model.bind('sync', this.render, this); }, render : function(){ this.$el.html(this.template(this.model.toJSON())); return this; } }); Views.ListReportsView = Views.BaseView.extend({ initialize : function(){ this.$el = $("#dashboard-content"); this._super('initialize'); this.loadTemplate('experiment-report-list'); reportsList.bind('reset', this.addAll, this); eventBus.on( 'close_view', this.close, this ); }, init : function(){ this._super('init'); this.render(); reportsList.fetch(); }, render : function(){ this.$el.html(this.template()); }, add : function(reportData){ var view = new ExperimentReportView({model : reportData}); this.$('#experiment-report-list').append(view.render().el); }, addAll : function(){ if(reportsList.length == 0) this.$el.html("<h3>You do not have any active Experiments or Goals. " + "Create a new <a id='create-experiment-btn' href='#'>Experiment</a> " + "or <a id='create-goal-btn' href='#'>Goal</a></h3>"); else reportsList.each(this.add); }, close : function(){ this._super('close'); reportsList.off(); delete reportsList; } });
/** * Created by hasee on 2017/12/27. */ Ext.define('Admin.view.hero.Hero', { extend: 'Ext.Panel', xtype: 'hero', title: '英雄管理', requires: [ 'Admin.view.hero.HeroController', 'Ext.button.Button', 'Ext.form.field.Date' ], controller: "hero", layout: { type: 'vbox', align: 'stretch' }, items: [{ xtype: 'form', reference: 'form', defaultButton: 'btn_search', layout: 'column', defaults: { labelAlign: 'right' }, items: [{ xtype: 'datefield', name: 'startTime', reference:'startTime', hidden:true, fieldLabel: '起始时间', margin: '15px 0px 0px 0px', labelWidth: 60, format: 'Y-m-d', editable: false }, { xtype: 'datefield', name: 'endTime', reference:'endTime', hidden:true, fieldLabel: '结束时间', margin: '15px 0px 0px 0px', labelWidth: 60, format: 'Y-m-d', editable: false },{ xtype: 'textfield', reference: 'localizedName', fieldLabel: '英雄名称', margin: '15px 0px 0px 0px', name: 'localizedName' }] }, { xtype: 'grid', sortableColumns: true, reference: 'grid', flex: 1, store: 'hero.Hero', columns: [{ xtype: 'rownumberer' },{ text: 'id', dataIndex: 'id', width: 30 },{ text: '标准名称', dataIndex: 'name', width: 150 },{ text: '本地化名称', dataIndex: 'localizedName', width: 150 },{ text: '英雄头像', dataIndex: 'headportraitPath', width: 200, renderer:function (v) { if (v == null || v == '') { return '<a href="' + v + '" target="_blank" >' + '<img style="width: 75%;height: 75%;" title="未上传文件" alt="未上传文件" src="' + v + '">' + '</a>' } else { return '<a href="' + v + '" target="_blank" >' + '<img style="width: 75%;height: 75%;" title="下载" alt="下载" src="' + v + '">' + '</a>' } } },{ text: '英雄图片', dataIndex: 'heroPath', width: 108, renderer:function (v) { if (v == null || v == '') { return '<a href="' + v + '" target="_blank" >' + '<img style="width: 75%;height: 75%;" title="未上传文件" alt="未上传文件" src="' + v + '">' + '</a>' } else { return '<a href="' + v + '" target="_blank" >' + '<img style="width: 75%;height: 75%;" title="下载" alt="下载" src="' + v + '">' + '</a>' } } },{ text: '操作', xtype: 'actioncolumn', width: 100, items: [{ tooltip: '编辑', icon: 'resources/images/icons/ic_edit.png', handler: 'modifyHero', columnWidth :25, isDisabled: function () { if (!Common.permission.Permission.hasPermission("英雄修改")) { return true; } return false; } }] }], selModel: { selType: 'checkboxmodel' }, dockedItems: [{ xtype: 'toolbar', items: [{ text: '查询', iconCls: 'fa fa-search', reference: 'btn_search', handler: 'search' }, { text: '清空条件', iconCls: 'fa fa-search', listeners: { click: 'reset' } }] }, { xtype: 'pagingtoolbar', store: 'hero.Hero', dock: 'bottom', displayInfo: true }], listeners: { beforerender: 'gridBeforeRender', render: 'search' } }] });
(function() { angular .module('BackyardApp', ['ui.router']) .config(MainRouter); MainRouter.$inject = ['$stateProvider', '$urlRouterProvider', '$locationProvider']; function MainRouter($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('blank', { url: '/', templateUrl: 'blank.html' //this shows up at the beginning -- change it if applicable }) .state('login', { url: '/login', templateUrl: 'login.html' }) .state('signup', { url: '/signup', templateUrl: 'signup.html' }) .state('home', { url: '/home', templateUrl: 'home.html' }); $urlRouterProvider.otherwise('/'); $locationProvider.html5Mode({ enabled: true, requireBase: false }) } //MainRouter })() // end IIFE
/* Author: Anshu Krishna Contact: anshu.krishna5@gmail.com Date: 13-Sep-2019 */ class StarRating extends HTMLElement { constructor() { super(); let root = this.attachShadow({ mode: 'closed' }); root.appendChild(StarRating.__template.content.cloneNode(true)); Object.defineProperties(this, { __cntr: { enumerable: false, writable: false, value: root.querySelector('#cntr') }, __painter: { enumerable: false, writable: false, value: () => { let value = this.value, max = this.max; let style = getComputedStyle(this); let color = style.getPropertyValue('--star-fill-color'); let back = style.getPropertyValue('--star-back-color'); this.__cntr.innerHTML = StarRating.StarMaker.gen(value, max, color, back); this.__cntr.setAttribute('title', `${value} of ${max}`); } }, __onclick: { enumerable: false, writable: false, value: e => { e.stopPropagation(); let svg = null; switch(e.target.nodeName) { case 'path': svg = e.target.parentNode; break; case 'svg': svg = e.target; } if(svg === null) { return; } let index = 1; while( (svg = svg.previousSibling) !== null) { index++; } let value = this.value; if(value === index) { this.value = 0; this.dispatchEvent(new CustomEvent('change', { detail: { old: value, new: 0 } })); } else { this.value = index; this.dispatchEvent(new CustomEvent('change', { detail: { old: value, new: index } })); } } } }); } get value() { let v = this.getAttribute('value'); return (v === null) ? 0 : parseFloat(v); } get max() { let v = this.getAttribute('max'); return (v === null) ? 5 : parseInt(v); } set value(val) { if(val === null) { this.removeAttribute('value'); } else { this.setAttribute('value', parseFloat(val)); } } set max(val) { if(val === null) { this.removeAttribute('max'); } else { this.setAttribute('max', parseInt(val)); } } connectedCallback() { this.__painter(); } // disconnectedCallback() {} // adoptedCallback() {} static get observedAttributes() { return ['value', 'max', 'changeable']; } attributeChangedCallback(name, oldval, newval) { // console.log("Changed", name, ":", oldval, "->", newval); switch(name) { case 'value': case 'max': this.__painter(); break; case 'changeable': if(newval === null) { this.__cntr.removeEventListener('click', this.__onclick); this.__cntr.classList.remove('clickable'); } else { this.__cntr.addEventListener('click', this.__onclick); this.__cntr.classList.add('clickable'); } break; } } } Object.defineProperties(StarRating, { __template: { enumerable: false, writable: false, value: document.createElement('template') }, StarMaker: { enumerable: false, writable: false, value: class { static fullStar(color) { let span = document.createElement('span'); span.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 300 300"><path fill="${color}" d="M150 14.3l35.3 101.4 107.4 2.2-85.6 64.9 31.1 102.8L150 224.3l-88.2 61.3 31.1-102.8L7.4 118l107.4-2.2L150 14.3l35.3 101.4z"/></svg>`; return span.firstChild; } static partialStar(part, color, background) { let span = document.createElement('span'); span.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 300 300"><defs><linearGradient id="partial"><stop offset="0%" stop-color="${color}"/><stop offset="${part}%" stop-color="${color}"/><stop offset="${part}%" stop-color="${background}"/><stop offset="100%" stop-color="${background}"/></linearGradient></defs><path fill="url(#partial)" d="M150 14.3l35.3 101.4 107.4 2.2-85.6 64.9 31.1 102.8L150 224.3l-88.2 61.3 31.1-102.8L7.4 118l107.4-2.2L150 14.3l35.3 101.4z"/></svg>`; return span.firstChild; } static gen(value, max = 5, color = 'red', background = 'grey') { color = String(color).trim(); background = String(background).trim(); max = parseInt(max); let div = document.createElement('div'); if(value >= max) { for(let i = 0; i < max; i++) { div.appendChild(StarRating.StarMaker.fullStar(color)); } } else { let full = parseInt(value); let part = parseInt(Number(value - full).toFixed(2) * 100); for(let i = 0; i < full; i++) { div.appendChild(StarRating.StarMaker.fullStar(color)); } if(part !== 0) { div.appendChild(StarRating.StarMaker.partialStar(part, color, background)); full++; } for(let i = full; i < max; i++) { div.appendChild(StarRating.StarMaker.fullStar(background)); } } return div.innerHTML; } } } }); StarRating.__template.innerHTML = `<style> :host { --star-fill-color: #ffd700; --star-back-color: #b2b2b2; --star-stroke: none; --star-stroke-opacity: inherit; --star-stroke-width: 0.2em; display: inline-block; } svg { height: 1em; width: auto; } path { stroke: var(--star-stroke); stroke-opacity: var(--star-stroke-opacity); stroke-width: var(--star-stroke-width); } #cntr { display: flex; grid-gap: 0.1em; } #cntr.clickable svg { cursor: pointer; } </style><div id="cntr"></div>`; customElements.define("star-rating", StarRating);
import React from 'react'; import Qr from '../Qr'; import widget from '../../assets/images/temp/widget.svg'; class HowTo extends React.Component { render() { return ( <section className="how-to-section"> <div className="container"> <div className="how-to-wrap"> <div className="how-to-header"> <span>How to</span> </div> <div className="how-to-title"> {'Generate "request QR code"'} <br />{'with Bridge'} </div> <div className="how-to-row"> <div className="column"> <div className="code-example"> <div className="title">Code</div> <div className="code"> {'https://echo-bridge.io/receive/{receiver-account-name}/'} {'{“asset” || “token”}-{id-asset-or-id-token-contract-without-prefix}'} {'/{amount-without-delimeter}/qr-code.png'} </div> <div className="fields"> <div className="field"> <div className="argument"> {'{receiver-account-name}'} </div> <div className="type">required field</div> </div> <div className="field"> <div className="argument"> {'{“asset” || “token”}-{id-asset-or-id-token-contract-without-prefix}'} </div> <div className="type">optional field</div> </div> <div className="field"> <div className="argument"> {'{amount-without-delimeter}'} </div> <div className="type">optional field</div> </div> </div> <div className="fields-hints"> <div className="hint"> You can replace optional fields with {'"-"'} </div> </div> </div> </div> <div className="column"> <div className="code-example"> <div className="title">Example</div> <div className="code"> {'https://echo-bridge.io/receive/testaccount/asset-14/-/qr-code.png'} </div> <Qr /> </div> </div> </div> <div className="how-to-title"> {'GET Widget'} <br />{'"request QR code"'} </div> <div className="how-to-row"> <div className="column"> <div className="code-example"> <div className="title">Code</div> <div className="code"> {'https://echo-bridge.io/receive/{receiver-account-name}/'} {'{“asset” || “token”}-{id-asset-or-id-token-contract-without-prefix}'} {'/{amount-without-delimeter}/widget'} </div> <div className="fields"> <div className="field"> <div className="argument"> {'{receiver-account-name}'} </div> <div className="type">required field</div> </div> <div className="field"> <div className="argument"> {'{“asset” || “token”}-{id-asset-or-id-token-contract-without-prefix}'} </div> <div className="type">optional field</div> </div> <div className="field"> <div className="argument"> {'{amount-without-delimeter}'} </div> <div className="type">optional field</div> </div> </div> <div className="fields-hints"> <div className="hint"> You can replace optional fields with {'"-"'} </div> </div> </div> </div> <div className="column"> <div className="code-example"> <div className="title">Example</div> <div className="code"> {'https://echo-bridge.io/receive/testaccount/asset-14/-/widget'} </div> <div className="widget"> <img src={widget} alt="widget" /> </div> </div> </div> </div> </div> </div> </section> ); } } export default HowTo;