text
stringlengths
7
3.69M
var mongoose = require('./MongoDB.js'), Schema = mongoose.Schema; var RoutedataSchema = new Schema({ SPortName: {type:String}, SPortLat: {type:Number}, SPortLont: {type:Number}, DesPortName: {type:String}, DesPortLat:{type: Number}, DesPortLont:{type: Number}, Count: {type: Number}, },{ collection: "Rawroutes"}); module.exports = mongoose.model('Rawroute',RoutedataSchema);
import React, { Component, PropTypes } from "react"; import { Link } from "react-router"; import sematable, { SortableHeader, SelectAllHeader, SelectRow, } from "sematable"; const columns = [ { key: "id", header: "ID", searchable: true, sortable: true, primaryKey: true, }, { key: "name", header: "Name", searchable: true, sortable: true }, ]; const propTypes = { headers: PropTypes.object.isRequired, data: PropTypes.array.isRequired, }; export default () => { const { headers: { select, id, name }, data, } = this.props; return ( <div className="table-responsive"> <table className="table table-sm table-striped table-hover"> <thead> <tr> <SelectAllHeader {...select} /> <SortableHeader {...id} /> <SortableHeader {...name} /> <th>Actions</th> </tr> </thead> <tbody> {data.map((app) => ( <tr key={app.id} className={`${select.isSelected(app) ? "table-info" : ""}`} > <td> <SelectRow row={app} {...select} /> </td> <td>{app.id}</td> <td>{app.name}</td> <td> <Link to={`/settings/${app.id}`}>Settings</Link> </td> </tr> ))} </tbody> </table> </div> ); }; AppsTable.propTypes = propTypes; export default sematable("allApps", AppsTable, columns);
var Attribute = require('attribute'); var assert = require('component-assert'); var User; var user; var me = { name: 'Federico', age: 28, isHungry: true, pets: ['Laica', 'Duccio'] }; var check_user = function(user, me) { for (var prop in me) { assert(user.get(prop) === me[prop]); } }; describe('Attribute', function() { describe('mixin', function() { describe('constructor', function() { beforeEach(function() { User = function(id) { this.id = id; }; user = new User('007'); Attribute(user); }); afterEach(function() { user = undefined; User = undefined; }); it('should not modify instance properties', function() { assert(user.hasOwnProperty('id')); assert(user.id === '007'); }); it('should been mixed-in `Attributes` properties correctly', function() { assert(user.hasOwnProperty('get')); assert(typeof user.get === 'function'); assert(user.hasOwnProperty('set')); assert(typeof user.set === 'function'); }); it('should been mixed-in `Emitter` properties correctly', function() { assert(user.hasOwnProperty('on')); assert(typeof user.on === 'function'); assert(user.hasOwnProperty('once')); assert(typeof user.once === 'function'); assert(user.hasOwnProperty('off')); assert(typeof user.off === 'function'); assert(user.hasOwnProperty('emit')); assert(typeof user.emit === 'function'); assert(user.hasOwnProperty('listeners')); assert(typeof user.listeners === 'function'); assert(user.hasOwnProperty('hasListeners')); assert(typeof user.hasListeners === 'function'); }); }); describe('.set(name_or_obj, value)', function() { beforeEach(function() { User = function(id) { this.id = id; }; user = new User('007'); Attribute(user); }); afterEach(function() { user = undefined; User = undefined; }); it('should set `name/value` pair when pass `name` and `value`', function() { user .set('name', me.name) .set('age', me.age) .set('isHungry', me.isHungry) .set('pets', me.pets); check_user(user, me); }); it('should set `undefine` value to property `name` when pass only a `name` string', function() { user.set('name'); assert(user.get('name') === undefined); }); it('should set all the `name/value` pairs when pass an object', function() { user.set(me); check_user(user, me); }); it('should emit `change:[name]` when pass `name` and `value`', function(done) { user.on('change:name', function(user, value, previous) { assert(user.id === '007'); assert(user.get('name') === me.name); done(); }); user.set('name', me.name); }); it('should emit `change:[name]` value to property `name` when pass only a `name` string', function(done) { user.on('change:name', function(user, value, previous) { assert(user.id === '007'); assert(user.get('name') === undefined); done(); }); user.set('name'); }); it('should emit `change:[name]` for each of the properties when pass an abject', function(done) { var map = ['name', 'age', 'isHungry', 'pets']; var fired = new Array(4); var check = function(prop) { var index = map.indexOf(prop); fired[index] = true; assert(user.get(prop) === me[prop]); if (fired.every(function(item) { return item; })) { done(); } }; user .on('change:name', function() { check('name'); }) .on('change:age', function() { check('age'); }) .on('change:isHungry', function() { check('isHungry'); }) .on('change:pets', function() { check('pets'); }) user.set(me); }); it('should emit `change` event when pass `name` and `value`', function(done) { user.on('change', function(user) { assert(user.id === '007'); assert(user.get('name') === me.name); done(); }); user.set('name', me.name); }); it('should emit `change` (only once) when pass an abject', function(done) { user.on('change', function(user) { assert(user.id === '007'); check_user(user, me); done(); }); user.set(me); }); }); describe('.get(attribute)', function() { beforeEach(function() { User = function(id) { this.id = id; }; user = new User('007'); Attribute(user); user .set('name', me.name) .set('age', me.age) .set('isHungry', me.isHungry) .set('pets', me.pets); }); afterEach(function() { user = undefined; User = undefined; }); it('should not assign properties directly to instance', function() { assert(!user.hasOwnProperty('name')); assert(!user.hasOwnProperty('age')); assert(!user.hasOwnProperty('isHungry')); assert(!user.hasOwnProperty('pets')); }); it('should return queried attribute valued', function() { assert(user.get('name') === me.name); assert(user.get('age') === me.age); assert(user.get('isHungry') === me.isHungry); assert(user.get('pets') === me.pets); }); }); }); describe('prototype mixin', function() { describe('constructor', function() { beforeEach(function() { User = function(id) { this.id = id; }; Attribute(User.prototype); user = new User('007'); user .set('name', me.name) .set('age', me.age) .set('isHungry', me.isHungry) .set('pets', me.pets); }); afterEach(function() { user = undefined; User = undefined; }); it('should not modify instance properties', function() { assert(user.hasOwnProperty('id')); assert(user.id === '007'); }); it('should been mixed-in `Attributes` properties correctly', function() { assert(!user.hasOwnProperty('get')); assert(typeof user.get === 'function'); assert(!user.hasOwnProperty('set')); assert(typeof user.set === 'function'); }); it('should been mixed-in `Emitter` properties correctly', function() { assert(typeof user.on === 'function'); assert(typeof user.once === 'function'); assert(typeof user.off === 'function'); assert(typeof user.emit === 'function'); assert(typeof user.listeners === 'function'); assert(typeof user.hasListeners === 'function'); }); }); describe('.set(name_or_obj, value)', function() { beforeEach(function() { User = function(id) { this.id = id; }; Attribute(User.prototype); user = new User('007'); }); afterEach(function() { user = undefined; User = undefined; }); it('should set `name/value` pair when pass `name` and `value`', function() { user .set('name', me.name) .set('age', me.age) .set('isHungry', me.isHungry) .set('pets', me.pets); check_user(user, me); }); it('should set `undefine` value to property `name` when pass only a `name` string', function() { user.set('name'); assert(user.get('name') === undefined); }); it('should set all the `name/value` pairs when pass an object', function() { user.set(me); check_user(user, me); }); it('should emit `change:[name]` when pass `name` and `value`', function(done) { user.on('change:name', function(changed_user) { assert(changed_user.id === '007'); assert(changed_user.get('name') === me.name); done(); }); user.set('name', me.name); }); it('should emit `change:[name]` value to property `name` when pass only a `name` string', function(done) { user.on('change:name', function(changed_user) { assert(changed_user.id === '007'); assert(changed_user.get('name') === undefined); done(); }); user.set('name'); }); it('should emit `change:[name]` for each of the properties when pass an abject', function(done) { var map = ['name', 'age', 'isHungry', 'pets']; var fired = new Array(4); var check = function(prop) { var index = map.indexOf(prop); fired[index] = true; assert(user.get(prop) === me[prop]); if (fired.every(function(item) { return item; })) { done(); } }; user .on('change:name', function() { check('name'); }) .on('change:age', function() { check('age'); }) .on('change:isHungry', function() { check('isHungry'); }) .on('change:pets', function() { check('pets'); }) user.set(me); }); it('should emit `change` event when pass `name` and `value`', function(done) { user.on('change', function(changed_user) { assert(changed_user.id === '007'); assert(changed_user.get('name') === me.name); done(); }); user.set('name', me.name); }); it('should emit `change` (only once) when pass an abject', function(done) { user.on('change', function(changed_user) { assert(changed_user.id === '007'); check_user(changed_user, me); done(); }); user.set(me); }); }); describe('.get(attribute)', function() { beforeEach(function() { User = function(id) { this.id = id; }; Attribute(User.prototype); user = new User('007'); user .set('name', me.name) .set('age', me.age) .set('isHungry', me.isHungry) .set('pets', me.pets); }); afterEach(function() { user = undefined; User = undefined; }); it('should not assign properties directly to instance', function() { assert(!user.hasOwnProperty('name')); assert(!user.hasOwnProperty('age')); assert(!user.hasOwnProperty('isHungry')); assert(!user.hasOwnProperty('pets')); }); it('should return queried attribute valued', function() { assert(user.get('name') === me.name); assert(user.get('age') === me.age); assert(user.get('isHungry') === me.isHungry); assert(user.get('pets') === me.pets); }); }); }); });
//@ts-check const Todo = require("../model/Todo"); module.exports = { createTodo: async (req, res) => { const { name, description } = req.body; // TODO: validate before save let newTodo = new Todo({ name, description }); let todo = await newTodo.save(); res.json({ todo }); }, showAllTodo: async (req, res) => { const todos = await Todo.find({}); res.json({ todos }); } };
export async function retryRequest(promise, args, options, errorCb) { const { count, timeout } = options || { count: 3, timeout: 50 } const sleep = (promise, args, wait) => { return new Promise((resolve, reject) => { setTimeout(() => { promise(args) .then(result => { resolve(result) }) .catch(err => { reject(err) }) }, wait) }) } for (let i = 1; i <= count; i++) { try { const result = await sleep(promise, args, i === 1 ? 0 : timeout) return result } catch (err) { //自定义处理异常 if (errorCb && errorCb instanceof Function) { //如果errorCb返回true,表示不再尝试 const isNoTry = errorCb(err) if (isNoTry) { throw err } } else if (!(err instanceof Error)) { //若不是Error对象,则表示是业务错误,直接抛异常 throw err } if (i === count) { throw err } } } }
import React, { Component } from 'react'; import PropTypes from 'prop-types' import { connect } from 'react-redux' import { Button, FormControl, FormGroup, Form } from 'react-bootstrap' import { addWatchedMovie, removeMovie, rateMovie } from '../actions' class MovieButtons extends Component { constructor(props) { super(props); this.state = { rate: 10 }; } alreadyOnList(movie) { const { userMovies } = this.props; return userMovies.some(el => el.id === movie.id) } alreadyRated(movie) { const { userMovies } = this.props; return userMovies.some(el => el.id === movie.id && typeof el.rate !== "undefined") } getRate(movie) { const { userMovies } = this.props; var result = userMovies.filter(obj => { return obj.id === movie.id }) return result[0].rate; } onChange(event) { this.setState({ rate: event.target.value}) } onSubmit(event) { event.preventDefault(); this.props.rateMovie(this.props.movie, this.state.rate); } render() { const { movie } = this.props; if (this.alreadyOnList(movie)) { if(typeof this.getRate(movie) !== "undefined"){ return ( <div> <Button className="button movie-button" onClick={() => this.props.removeMovie(movie)}>Delete movie</Button> Your rate: {this.getRate(movie)} </div> ) } return ( <div> <Button className="button movie-button" onClick={() => this.props.removeMovie(movie)}>Delete movie</Button> <Form onSubmit={this.onSubmit.bind(this)} inline> <FormGroup> <FormControl onChange={this.onChange.bind(this)} componentClass="select" placeholder="select"> <option value={1}>1</option> <option value={2}>2</option> <option value={3}>3</option> <option value={4}>4</option> <option value={5}>5</option> <option value={6}>6</option> <option value={7}>7</option> <option value={8}>8</option> <option value={9}>9</option> <option value={10}>10</option> </FormControl> </FormGroup> <Button type="submit" className="button rate-button">Add rate</Button> </Form> </div> ) } return <Button className="button movie-button" onClick={() => this.props.addWatchedMovie(movie)}>Add to watched history</Button> } } MovieButtons.propTypes = { movie: PropTypes.object.isRequired } const mapStateToProps = state => { return { userMovies: state.moviesLists.USER_MOVIES.items } } const mapDispatchToProps = dispatch => { return { addWatchedMovie: movie => dispatch(addWatchedMovie(movie)), removeMovie: movie => dispatch(removeMovie(movie)), rateMovie: (movie, rate) => dispatch(rateMovie(movie, rate)) }; }; export default connect(mapStateToProps, mapDispatchToProps)(MovieButtons)
const Koa = require('koa'); const app = new Koa(); const koaBody = require('koa-body'); const Router = require('koa-router'); const fs = require('fs'); const path = require('path'); const QRCode = require('qrcode'); var os = require('os'); function getUploadUrl() { const ocType = os.type(); if (ocType === "Windows_NT") { return path.join(__dirname, "/upload"); } else return "/var/www/html/upload"; } app.use(async (ctx, next) => { // 允许来自所有域名请求 // ctx.set("Access-Control-Allow-Origin", "http://localhost:7778"); // ctx.set("Access-Control-Allow-Origin", "http://localhost:7778"); ctx.set('Access-Control-Allow-Origin', ctx.req.headers.origin) // 设置所允许的HTTP请求方法 ctx.set("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS"); // 字段是必需的。它也是一个逗号分隔的字符串,表明服务器支持的所有头信息字段. ctx.set("Access-Control-Allow-Headers", "x-requested-with, accept, origin, Content-Type"); // 服务器收到请求以后,检查了Origin、Access-Control-Request-Method和Access-Control-Request-Headers字段以后,确认允许跨源请求,就可以做出回应。 // Content-Type表示具体请求中的媒体类型信息 // ctx.set("Content-Type", "application/json;charset=utf-8,multipart/form-data"); // 该字段可选。它的值是一个布尔值,表示是否允许发送Cookie。默认情况下,Cookie不包括在CORS请求之中。 // 当设置成允许请求携带cookie时,需要保证"Access-Control-Allow-Origin"是服务器有的域名,而不能是"*"; ctx.set("Access-Control-Allow-Credentials", true); // 该字段可选,用来指定本次预检请求的有效期,单位为秒。 // 当请求方法是PUT或DELETE等特殊方法或者Content-Type字段的类型是application/json时,服务器会提前发送一次请求进行验证 // 下面的的设置只本次验证的有效时间,即在该时间段内服务端可以不用进行验证 ctx.set("Access-Control-Max-Age", 3000); /* CORS请求时,XMLHttpRequest对象的getResponseHeader()方法只能拿到6个基本字段: Cache-Control、 Content-Language、 Content-Type、 Expires、 Last-Modified、 Pragma。 */ // 需要获取其他字段时,使用Access-Control-Expose-Headers, // getResponseHeader('myData')可以返回我们所需的值 //https://www.rails365.net/articles/cors-jin-jie-expose-headers-wu // ctx.set("Access-Control-Expose-Headers", "myData"); /* 解决OPTIONS请求 */ if (ctx.method == 'OPTIONS') { ctx.body = ''; ctx.status = 204; } else { await next(); } }) app.use(koaBody({ multipart: true, formidable: { maxFileSize: 200 * 1024 * 1024 // 设置上传文件大小最大限制,默认2M } })); const router = new Router(); async function GetCode(url) { return new Promise((res, rej) => { QRCode.toDataURL(url, (err, url) => { if (!err) { res(url) } else rej(err); }); }) } router.post("/upload", async (ctx, next) => { console.log(4546); try { const file = ctx.request.files.files; // 获取上传文件 const reader = fs.createReadStream(file.path); // 创建可读流 const ext = file.name.split('.').pop(); // 获取上传文件扩展名 let name = `${Math.random().toString()}.obj` let url = `${getUploadUrl()}/${name}` const upStream = fs.createWriteStream(path.join(__dirname, url)); // 创建可写流 reader.pipe(upStream); // 可读流通过管道写入可写流 let code = await GetCode('http://www.dodream.wang/upload/' + name); ctx.body = { msg: "上传成功", code: 200, data: { fileUrl: `/upload/${name}`, code } }; } catch (err) { console.log(err); ctx.body = { msg: "上传失败", code: 444, }; } }); router.post("/uploadImg", async (ctx, next) => { console.log(123); try { const file = ctx.request.files.files; // 获取上传文件 const reader = fs.createReadStream(file.path); // 创建可读流 const ext = file.name.split('.').pop(); // 获取上传文件扩展名 let name = `${Date.now().toString()}.${ext}` let url = `${getUploadUrl()}/${name}` const upStream = fs.createWriteStream( url); // 创建可写流 reader.pipe(upStream); // 可读流通过管道写入可写流 ctx.body = { msg: "上传成功", code: 200, data: { url: `/upload/${name}`, } }; } catch (err) { console.log(err); ctx.body = { msg: "上传失败", code: -1, }; } }); const AUTH_KEY = "joelee"; router.get("/cdnauth", async (ctx, next) => { try { if (ctx.query.key === AUTH_KEY) ctx.status = 200; else ctx.status = 401; } catch (err) { ctx.status = 401; } }); app.use(router.routes()); app.listen(3600, () => { console.log("listening on 3600") });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _winston = _interopRequireDefault(require("winston")); var _DefaultFormatter = _interopRequireDefault(require("../formatters/DefaultFormatter")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } require('dotenv').config(); function ConsoleTransport(level, formatter) { if (!formatter) { formatter = (0, _DefaultFormatter.default)(); } if (!level) { level = process.env.LOG_LEVEL ? process.env.LOG_LEVEL : 'debug'; } return new _winston.default.transports.Console({ format: formatter, level: level }); } var _default = ConsoleTransport; exports.default = _default;
// rfce import React , {useContext} from 'react' import {Link, useHistory} from 'react-router-dom' import {UserContext} from "../App" const Navbar= ()=> { const {state , dispatch} =useContext(UserContext) const history = useHistory(); const renderList =()=>{ if(state){ // console.log(state); return[<li className="nav-item"> <Link className="nav-link" to="/profile">My post</Link> </li>, <li className="nav-item"> <Link className="nav-link" to="/create">Create Post</Link> </li>, <button onClick={()=>{localStorage.clear() dispatch({type:"CLEAR"}) history.push("/signin") } }>logout</button> ] } else{ return[ <li className="nav-item"> <Link className="nav-link" to="/signin">Login</Link> </li>, <li className="nav-item"> <Link className="nav-link" to="/signup">Signup</Link> </li> ] } } return ( <> <nav className="navbar navbar-expand-lg navbar-dark bg-dark"> <Link className="navbar-brand" to="/">WebinarMeeting</Link> <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse" id="navbarSupportedContent"> <ul className="navbar-nav ml-auto"> <li className="nav-item active"> <Link className="nav-link" to={state?"/":"/signin"}>Home <span className="sr-only">(current)</span></Link> </li> {renderList()} </ul> </div> </nav> </> ) } export default Navbar
import React, { Component } from 'react'; import { Row, Col } from 'reactstrap'; import './Photo.css'; class Photo extends Component { constructor(props){ super(props); this.state={ id: this.props.location.pathname.slice(7,this.props.location.pathname.length), } } componentDidMount(){ if(this.props.photo.listPhotos.length === 0){ this.props.loadFunc(); this.props.history.push(`/photo/${this.state.id}`); } } setHistory(nextId){ this.props.loadFunc(); this.props.history.push(`/photo/${this.state.id}`); this.handleClick(this.props.photo.listPhotos[nextId].id); } handleClick(id){ if(id){ this.props.history.push(`/photo/${id}`); this.setState({ id: id }) } } render() { if(this.props.photo.listPhotos.length !== 0){ let info; let prevId = null, nextId = null; for(let i = 0; i < this.props.photo.listPhotos.length;i++){ if(this.props.photo.listPhotos[i].id === this.state.id){ info = this.props.photo.listPhotos[i]; if(i === this.props.photo.listPhotos.length-1){ this.props.loadFunc(); nextId = this.props.photo.listPhotos.length; } else{ nextId = this.props.photo.listPhotos[i+1].id; } if(i>0){ prevId = this.props.photo.listPhotos[i-1].id; } break; } } return ( <div> <Row className='PhotoView'> <Col xs="1" onClick={()=>this.handleClick(prevId)}> {this.props.photo.listPhotos[0].id === this.state.id ? "": "<"} </Col> <Col xs="10"> <img src={info.url_c}></img> </Col> <Col xs="1" onClick={()=>{ nextId===this.props.photo.listPhotos.length?this.setHistory(nextId):this.handleClick(nextId)}}> {">"} </Col> </Row> <Row> <Col xs='1'></Col> <Col xs="5" className="Owner"> {info.ownername} </Col> <Col xs="2"> Views: {info.views} </Col> <Col xs="4"> Taken on {info.datetaken} </Col> </Row> <Row> <Col xs='1'></Col> <Col xs="5"><div dangerouslySetInnerHTML={{__html: info.description._content}} /></Col> <Col xs="5">Tags: {info.tags} </Col> </Row> </div> ); } else{ return <div></div> } } } export default Photo;
//Binary Search Example 1 //Write a function called binarySearch which accepts a sorted array and a value and returns the index at which the value exists. Otherwise, return -1. // Solution 1 - Time: O(log(n)) function binarySearch(arr,val) { let start = 0 let end = arr.length-1 let mid = Math.floor((start+end)/2) while (arr[mid] !== val && start <= end) { if (arr[mid] < val) { start = mid + 1 } else { end = mid - 1 } mid = Math.floor((start+end)/2) } if (arr[mid] === val) { return mid } return -1 }
/** * Created by WangChong on 15/12/08. * * 所有50dh 替换为当前项目名称 * * 修改 平均值 averageScoreSelf * 修改 标准差 standardDeviationSelf * * Init 方法需在项目主函数初始化 * SubmitPlayerDetail 方法在游戏刚结束在可以生成详细数据时调用 需替换方法内detailJson内容 * * 为UidUrlManager、ShareSDK脚本的50dh改名为项目名称 * * */ var NetManager = (function () { function NetManager() { this.InfoJson = ""; this.sysTime = { "year": "2000", "month": "01", "day": "01", "hour": "11", "minute": "59", "second": "59" }; } var d = __define,c=NetManager,p=c.prototype; p.Init = function () { console.log("uid=" + Info.uid + " pass=" + Info.pass); if (NetAPI.api != null && Info.uid != "error") { //this.onLoadGameNorm (); this.GetFriendUid(); this.GetInfo(); } }; /** * 获取 上传用户朋友Uid */ p.GetFriendUid = function () { if (localStorage.getItem("zqdn_friend_uid") == null) { return; } Info.fid = localStorage.getItem("zqdn_friend_uid"); localStorage.removeItem("zqdn_friend_uid"); console.log("friendUid: " + Info.fid); //MyDebug.MyLog("friendUid: " + Info.fid); DCAgent.onEvent("normal_Sharelink_Enter"); var urlLoader = new egret.URLLoader; var urlreq = new egret.URLRequest(NetAPI.api["addfriend"]); urlreq.method = egret.URLRequestMethod.POST; urlreq.data = new egret.URLVariables("uid=" + Info.uid + "&pass=" + Info.pass + "&fuid=" + Info.fid); urlLoader.addEventListener(egret.Event.COMPLETE, onComplete, this); urlLoader.addEventListener(egret.IOErrorEvent.IO_ERROR, onError, this); urlLoader.load(urlreq); console.log("~~正在上传详细数据..."); //MyDebug.MyLog("~~正在上传详细数据..."); function onComplete() { console.log("~~上传用户朋友Uid成功~~"); //MyDebug.MyLog("~~上传用户朋友Uid成功~~"); } function onError() { console.log("!!上传用户朋友Uid失败!!"); //MyDebug.MyLog("!!上传用户朋友Uid失败!!"); } }; /** * 通过PlayerUID获取Player信息 */ p.GetInfo = function () { if (localStorage.getItem("zqdn_Info") != null) { this.InfoJson = localStorage.getItem("zqdn_Info"); console.log("~~本地获取Info~~"); //MyDebug.MyLog("~~本地获取Info~~"); this.PickPlayerDataFromJson(); } else { console.log("~~网络获取Info~~"); //MyDebug.MyLog("~~网络获取Info~~"); this.ConnectToGetInfo(); } }; /** * 连接到服务器获取该UID的玩家信息 */ p.ConnectToGetInfo = function () { var urlLoader = new egret.URLLoader; var urlreq = new egret.URLRequest; urlreq.url = NetAPI.api["getginfo"]; urlLoader.addEventListener(egret.Event.COMPLETE, this.onLoadInfoComplete, this); urlLoader.addEventListener(egret.IOErrorEvent.IO_ERROR, function (e) { console.error("网络连接失败……玩家信息获取失败。"); //MyDebug.MyLog("网络连接失败……玩家信息获取失败。"); }, this); urlLoader.load(urlreq); }; p.onLoadInfoComplete = function (e) { this.InfoJson = e.target.data.toString(); this.PickPlayerDataFromJson(); localStorage.setItem("zqdn_Info", this.InfoJson); }; /** * 从玩家信息Json文件提取数据 */ p.PickPlayerDataFromJson = function () { console.log(this.InfoJson); var info = JSON.parse(this.InfoJson); // 将获取到的玩家信息赋给变量 Info.nickname = info["nickname"]; Info.iconUrl = info["headimgurl"]; Info.sex = info["sex"]; Info.add = info["province"]; console.log("name: " + Info.nickname + " id: " + Info.uid); if (Info.nickname == null || Info.iconUrl == null) { console.log("网络连接失败……玩家信息获取失败。"); } else { console.log("玩家信息Json解析成功"); //MyDebug.MyLog("玩家信息Json解析成功"); this.GetPlayerPic(); } }; /** * 获取玩家头像 */ p.GetPlayerPic = function () { RES.getResByUrl(Info.iconUrl, this.onGetPicComplete, this, RES.ResourceItem.TYPE_IMAGE); }; p.onGetPicComplete = function (_pic) { if (_pic != null) { Info.icon = _pic; } console.log("~~玩家头像获取完成 " + _pic + " " + Info.iconUrl); //MyDebug.MyLog("~~玩家头像获取完成 " + _pic + " " + Info.iconUrl); }; /** * 连接服务器获取常模数据 */ p.onLoadGameNorm = function () { var urlLoader = new egret.URLLoader; var urlreq = new egret.URLRequest; urlreq.url = NetAPI.api["norm"]; urlLoader.addEventListener(egret.Event.COMPLETE, onComplete, this); urlLoader.addEventListener(egret.IOErrorEvent.IO_ERROR, onError, this); urlLoader.load(urlreq); function onComplete(e) { var normInfo = JSON.parse(e.target.data.toString()); // 当获取到的平均值或标准差正常 if (!isNaN(parseFloat(normInfo["averageScore"])) && !isNaN(parseFloat(normInfo["standardDeviation"]))) { Info.averageScore = parseFloat(normInfo["averageScore"]); Info.standardDeviation = parseFloat(normInfo["standardDeviation"]); console.log("网络获取常模成功 averageScore: " + Info.averageScore + " standardDeviation: " + Info.standardDeviation); } } function onError() { console.error("!!网络获取常模失败!!"); } }; p.SubmitPlayerScore = function (_score) { if (isNaN(_score)) { return; } this.submitScore = _score; Info.rank = ""; if (NetAPI.api == null || Info.uid == "error") { return; } var url = NetAPI.api["newrank"]; url = url.replace("%R", Info.app + "_rank"); var urlLoader = new egret.URLLoader; var urlreq = new egret.URLRequest(url); urlreq.method = egret.URLRequestMethod.POST; urlreq.data = new egret.URLVariables("uid=" + Info.uid + "&pass=" + Info.pass + "&score=" + _score); urlLoader.addEventListener(egret.Event.COMPLETE, this.onPostPlayerScoreComplete, this); urlLoader.addEventListener(egret.IOErrorEvent.IO_ERROR, this.onPostPlayerScoreError, this); urlLoader.load(urlreq); console.log("~~正在上传玩家分数... " + _score); MyDebug.MyLog("~~正在上传玩家分数... " + _score); }; p.onPostPlayerScoreComplete = function (e) { var playerRank = JSON.parse(e.target.data.toString()); var allPlayerCount = parseInt(playerRank["total"]); var nowPlayerCount = parseInt(playerRank["rank"]); console.log(e.target.data.toString() + "all : " + allPlayerCount + " now : " + nowPlayerCount); // 当allplayercount和nowplayercount为空时,则再次调用获取json if (isNaN(allPlayerCount) || isNaN(nowPlayerCount)) { console.log("网络获取Json异常……开始本地计算排名..."); MyDebug.MyLog("网络获取Json异常……开始本地计算排名..."); this.CalculateRank(); this.SubmitPlayerDetail(); } else { if (nowPlayerCount == 1) { Info.rank = "100"; } else { Info.rank = (((allPlayerCount - 1) - (nowPlayerCount - 1)) / (allPlayerCount - 1) * 100).toFixed(2); } if (isNaN(parseFloat(Info.rank))) { Info.rank = "-2"; } console.log("~~上传玩家分数、获取用户排名信息完成~~" + e.target.data.toString() + "all : " + allPlayerCount + " now : " + nowPlayerCount + " rank: " + Info.rank); //MyDebug.MyLog("~~上传玩家分数、获取用户排名信息完成~~" + e.target.data.toString() + "all : " + allPlayerCount + " now : " + nowPlayerCount + " rank: " + Info.rank); this.SubmitPlayerDetail(); NetDetailRank.instance.SubmitPlayerScore(this.submitScore); } }; p.onPostPlayerScoreError = function (e) { this.CalculateRank(); this.SubmitPlayerDetail(); }; /** * 本地计算排名 */ p.CalculateRank = function () { var norm = jStat.ztest(this.submitScore, Info.averageScore, Info.standardDeviation, 1); if (GameController.getInstance().data.originalScore > Info.averageScore) { norm = 1 - norm; } Info.rank = (norm * 100).toFixed(2); if (isNaN(parseFloat(Info.rank))) { Info.rank = "-1"; } console.log("原始得分:" + this.submitScore + " 平均值:" + Info.averageScore + " 标准差:" + Info.standardDeviation); console.log("超过百分之" + Info.rank); MyDebug.MyLog("本地计算排行,,超过百分之" + Info.rank); }; /** * 上传用户详细测试数据 */ p.SubmitPlayerDetail = function () { var data = Info.GetData(); var urlLoader = new egret.URLLoader; var urlreq = new egret.URLRequest; urlreq.method = egret.URLRequestMethod.POST; urlreq.url = NetAPI.api["oprecord"]; urlreq.data = new egret.URLVariables("pass=" + Info.pass + "&content=" + data); urlLoader.addEventListener(egret.Event.COMPLETE, function (e) { console.log("~~上传详细数据成功~~"); //MyDebug.MyLog("~~上传详细数据成功~~"); }, this); urlLoader.addEventListener(egret.IOErrorEvent.IO_ERROR, function (e) { console.error("!!网络连接失败……数据未成功上传。!!"); //MyDebug.MyLog("!!网络连接失败……数据未成功上传。!!"); }, this); urlLoader.load(urlreq); console.log("~~正在上传详细数据..."); //MyDebug.MyLog("~~正在上传详细数据..."); }; /** * 获取是否 关注公众号 */ p.GetIfFollowedServer = function () { console.log("~~正在获取是否 关注公众号~~"); //MyDebug.MyLog("~~正在获取是否 关注公众号~~"); var urlLoader = new egret.URLLoader; var urlreq = new egret.URLRequest; urlreq.url = NetAPI.api["getmpuinfo"]; urlLoader.addEventListener(egret.Event.COMPLETE, this.onFollowedServerComplete, this); urlLoader.addEventListener(egret.IOErrorEvent.IO_ERROR, function (e) { console.error("!!获取是否 关注公众号失败!!"); //MyDebug.MyLog("!!获取是否 关注公众号失败!!"); }, this); urlLoader.load(urlreq); }; p.onFollowedServerComplete = function (e) { console.log(e.target.data.toString()); var receiveStr = e.target.data.toString(); var followedJson; if (receiveStr.indexOf("head") != -1 && receiveStr.indexOf("body") != -1) { var aux = receiveStr.split("<body>")[1]; aux = aux.split("</body>")[0]; aux = aux.replace(new RegExp("&quot;", 'g'), "\""); console.log(aux); followedJson = JSON.parse(aux); } else { followedJson = JSON.parse(receiveStr); } if (followedJson["subscribe"] == 1) { Info.isLikeServer = true; console.warn("~~获取是否 关注公众号成功 已关注~~"); MyDebug.MyLog("~~获取是否 关注公众号成功 已关注~~"); } else { Info.isLikeServer = false; console.warn("~~获取是否 关注公众号成功 未关注~~"); MyDebug.MyLog("~~获取是否 关注公众号成功 未关注~~"); } }; /** * 获取时间 */ p.GetSysTime = function () { console.log("~~正在获取服务器时间..."); MyDebug.MyLog("~~正在获取服务器时间..."); var urlLoader = new egret.URLLoader; var urlreq = new egret.URLRequest; urlreq.url = NetAPI.api["time"]; urlLoader.addEventListener(egret.Event.COMPLETE, this.onSysTimeLoadComplete, this); urlLoader.addEventListener(egret.IOErrorEvent.IO_ERROR, this.onSysTimeLoadError, this); urlLoader.load(urlreq); }; p.onSysTimeLoadComplete = function (e) { console.log(e.target.data.toString()); var sysTime = JSON.parse(e.target.data.toString()); var t = sysTime["time"]; this.sysTime.year = t.split('/')[0]; this.sysTime.month = t.split('/')[1]; this.sysTime.day = t.split('/')[2].split(' ')[0]; this.sysTime.hour = t.split('/')[2].split(' ')[1].split(':')[0]; this.sysTime.minute = t.split('/')[2].split(' ')[1].split(':')[1]; this.sysTime.second = t.split('/')[2].split(' ')[1].split(':')[2]; console.warn("year:" + this.sysTime.year + " month:" + this.sysTime.month + " day:" + this.sysTime.day + " hour:" + this.sysTime.hour + " minute:" + this.sysTime.minute + " second:" + this.sysTime.second); MyDebug.MyLog("year:" + this.sysTime.year + " month:" + this.sysTime.month + " day:" + this.sysTime.day + " hour:" + this.sysTime.hour + " minute:" + this.sysTime.minute + " second:" + this.sysTime.second); NetDetailRank.instance.GetxxbgInfo(); }; p.onSysTimeLoadError = function () { console.error("!!获取服务器时间 失败!!"); MyDebug.MyLog("!!获取服务器时间 失败!!"); NetDetailRank.instance.GetxxbgInfo(); }; NetManager.instance = new NetManager(); return NetManager; }()); egret.registerClass(NetManager,'NetManager');
import {Button, Icon} from 'react-native-elements'; import i18n from 'i18n-js'; import * as PropTypes from 'prop-types'; import React from 'react'; import {useDerbyTheme} from '../utils/theme'; import {StyleSheet} from 'react-native'; export default function DateField({date, onPress}) { const {dark, colors, sizes} = useDerbyTheme(); return ( <Button title={ date ? i18n.l('date_formats_day', date) + ' at ' + i18n.l('date_formats_time', date) : i18n.t('match_add_select_date') } buttonStyle={styles.dateButton} containerStyle={{ marginTop: sizes.BASE * 1.5, marginBottom: sizes.BASE, width: '100%', }} onPress={onPress} titleStyle={[ styles.submitButtonText, { color: dark ? colors.text : colors.textMuted, fontSize: sizes.BASE, }, ]} type="outline" icon={ <Icon type="antdesign" name="calendar" style={{marginRight: sizes.BASE / 2}} size={20} color={colors.text} /> } /> ); } DateField.propTypes = { date: PropTypes.any, onPress: PropTypes.func, }; const styles = StyleSheet.create({ dateButton: { width: '100%', borderRadius: Math.round(45 / 2), height: 35, }, });
/** * isAuthorized * * @module :: Policy * @docs :: http://sailsjs.org/#!/documentation/concepts/Policies * */ module.exports = function(req, res, next) { if (req.currentUser) { next(); } else { res.forbidden('You are not permitted to perform this action.');; } };
viewController.setObserver("Signup", function () { $('select').material_select(); let data = {}; let elementProperty = new ElementProperty(); Mask.setMaskPhone('#contact-user'); Mask.setMaskCpf('#cpf-user'); elementProperty.addEventInElement('.show-password','onclick',function(){ if(this.innerHTML === 'visibility'){ this.innerHTML = 'visibility_off'; elementProperty.getElement('#password-user', input => { input.setAttribute('type' , 'text'); }); return; } this.innerHTML = 'visibility'; elementProperty.getElement('#password-user', input => { input.setAttribute('type' , 'password'); }); }); CustomerController.getUf().then(response => { elementProperty.getElement('#mount-estates', options => { let txt = ''; txt += response.response.map(that => { return ` <option value='${that.id}'>${that.slug}</option> `; }).join(''); options.innerHTML = txt; $('select').material_select(); }); }); elementProperty.addEventInElement('#mount-estates','onchange',function(){ let state = document.getElementById('mount-estates').value; CustomerController.getCities(state).then(response => { let data = response.response; elementProperty.getElement('#mount-cities', options => { let txt = ''; txt += data.map(that => { return ` <option value='${that.id}'>${that.slug}</option> `; }).join(''); options.innerHTML = txt; $('select').material_select(); }); }); }); elementProperty.addEventInElement('.go-second','onclick',function(){ elementProperty.getElement('.content-1' , first => { first.classList.add('hidden'); }); elementProperty.getElement('.content-2' , second => { second.classList.remove('hidden'); second.classList.add('show'); }); }); elementProperty.addEventInElement('.backFirstLawer','onclick',function(){ Route.redirectDynamic('Main','Login') }); elementProperty.addEventInElement('.backSecondPass','onclick',function(){ elementProperty.getElement('.content-1' , first => { first.classList.remove('hidden'); }); elementProperty.getElement('.content-2' , second => { second.classList.remove('show'); second.classList.add('hidden'); }); }); Route.pageDynamic(); });
// @flow strict import * as React from 'react'; import { graphql, createFragmentContainer } from '@kiwicom/mobile-relay'; import { TitledMenuGroup, MenuGroup, SeparatorTrimmed, } from '@kiwicom/mobile-navigation'; import { Translation } from '@kiwicom/mobile-localization'; import CabinBags from './CabinBags'; import CheckedBaggage from './CheckedBaggage'; import BaggageGroupButton from './BaggageGroupButton'; import type { Baggage as BaggageType } from './__generated__/Baggage.graphql'; type Props = {| +data: BaggageType, |}; const Baggage = ({ data }: Props) => ( <TitledMenuGroup title={<Translation passThrough="Baggage" />}> <BaggageGroupButton> <MenuGroup customSeparator={<SeparatorTrimmed gapSizeStart={15} gapSizeEnd={15} />} > <CabinBags data={data.allowedBaggage} /> <CheckedBaggage data={data.allowedBaggage} /> </MenuGroup> </BaggageGroupButton> </TitledMenuGroup> ); export default createFragmentContainer( Baggage, graphql` fragment Baggage on BookingInterface { allowedBaggage { ...CabinBags ...CheckedBaggage } } `, );
// Get the modal var form = document.getElementById('myform'); // Get the button that opens the modal var btn = document.getElementById("create_event_button"); // Get the <span> element that closes the modal var span = document.getElementsByClassName("form_close")[0]; // When the user clicks the button, open the modal btn.onclick = function() { form.style.display = "block"; } // When the user clicks on <span> (x), close the modal span.onclick = function() { form.style.display = "none"; } // Get the modal var form2 = document.getElementById('myform2'); // Get the button that opens the modal var btn2 = document.getElementById("edit_event_button"); // Get the <span> element that closes the modal var span2 = document.getElementsByClassName("form_close2")[0]; // When the user clicks the button, open the modal btn2.onclick = function() { form2.style.display = "block"; } // When the user clicks on <span> (x), close the modal span2.onclick = function() { form2.style.display = "none"; } var form3 = document.getElementById('myform3'); // Get the button that opens the modal var btn3 = document.getElementById("delete-button"); // Get the <span> element that closes the modal var span3 = document.getElementsByClassName("form_close3")[0]; // Get the button that closes the modal var btn4 = document.getElementById("cancel-button"); btn3.onclick = function() { form3.style.display = "block"; } btn4.onclick = function() { form3.style.display = "none"; } span3.onclick = function() { form3.style.display = "none"; } // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == form2) { form2.style.display = "none"; } if (event.target == form) { form.style.display = "none"; } if (event.target == form3) { form3.style.display = "none"; } } function smallAlert(){ alert("Japanese 111 begins in 10 mins. Expected time to reach is 4 mins. Leave within the next 6 mins to earn 3 Puncuality Points."); } function importantAlert(){ alert("EECS 330 discussion begins in 15 mins. Expected time to reach is 7 mins. Leave within the next 8 mins to earn 5 Puncuality Points."); }
import { jsonRequest } from "./httpService.js"; let baseUrl = "http://localhost:3030/users"; function setUser(user) { localStorage.setItem("user", JSON.stringify(user)); } function getUser() { let user = localStorage.getItem("user") == null ? undefined : JSON.parse(localStorage.getItem("user")); return user; } async function login(user) { let result = await jsonRequest(`${baseUrl}/login`, "Post", user); setUser(result); } async function register(user) { let result = await jsonRequest(`${baseUrl}/register`, "Post", user); setUser(result); } async function logout() { await jsonRequest(`${baseUrl}/logout`, "Get", undefined, true, true); localStorage.clear(); } export default { setUser, getUser, login, register, logout }
import React from "react"; class MinimalistPagination extends React.Component { constructor(props) { super(props); /** Pagination fields */ this.currentPage = props.data.currentPage this.minPage = props.data.min this.maxPage = props.data.max /** SelectController */ this.SelectController = props.onSelect /** PossibleInputController */ this.PreviewInputController = props.onInputPreview this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } /** Controls handlers */ onPrevClick = () => { if (this.currentPage > this.minPage) this.SelectController(this.currentPage - 1) } onNextClick = () => { if (this.currentPage < this.maxPage) this.SelectController(this.currentPage + 1) } /** Input change listeners */ handleChange = (e) => { this.PreviewInputController(e.target.value) } handleSubmit = (e) => { console.log ('handleSubmit') // const InputValidator = new Validator({ // value:e.target.value // },{ // value:['required', 'integer', { 'min': this.minPage }, {'max': this.maxPage}, {'not_in':[this.currentPage]}] // }) // // /** Input validator listeners */ // const onValidInput = () => { // //this.PreviewInputController(this.props.possiblePage) // this.SelectController (e.target.value) // } // const onFailsInput = () => { // this.PreviewInputController(this.props.currentPage) // } // // /** Input Validator */ // InputValidator.passes(onValidInput) // InputValidator.fails(onFailsInput) // // e.preventDefault(); } render () { return <div> <button onClick={this.onPrevClick}>Prev</button> <input onChange={this.handleChange} onBlur={this.handleSubmit} value={this.props.data.possiblePage}/> <span>/{this.props.data.totalPages}</span> <button onClick={this.onNextClick}>Next</button> </div> } } export default MinimalistPagination
import React from 'react'; import './Header.css'; import HelpIcon from '@material-ui/icons/Help'; import AppsIcon from '@material-ui/icons/Apps'; import SettingsIcon from '@material-ui/icons/Settings'; import { Avatar, Button, IconButton } from '@material-ui/core'; export default function Headers(props) { return ( <nav className = "headers" > <div className="header__left"> <IconButton className="header__leftIcon" variant="default"><AppsIcon /> </IconButton> <h3 className="header__Title"> Sticky Notes </h3> </div> <div> <div className="header__right"> <SettingsIcon className="header__rightIcon"/> <HelpIcon className="header__rightIcon"/> <Avatar className="rightAvatar">N</Avatar> </div> </div> </nav> ) }
// Renders the video information contained in the data in the video-section html element function InfoViewer(data) { this.data = data; } InfoViewer.prototype = { video_section: function () { return document.getElementById('videos-section'); }, html_href: function (url) { return url; }, _html_link: function (url, message) { //Html link with no on_click listener var link = document.createElement('a'); link.href = this.html_href(url) || "#"; link.textContent = message || url; return link; }, html_link_on_click: function (url) { return null; }, html_link: function (url, message) { //Html link with an on_click listener var link = this._html_link(url, message); link.addEventListener("click", this.html_link_on_click(url), false); return link; }, html_video_link_on_click: function (url) { //Return a function that will be called when the link is clicked. return null; }, html_video_link: function (url, message) { var link = this._html_link(url,message); link.addEventListener("click", this.html_video_link_on_click(url), false); return link; }, html_rtmp_command: function (video) { var url = video.url, play_path = video.play_path; var command_el = document.createElement('code'), command_message = document.createElement('p') command = 'rtmpdump -o video.' + video.ext + ' -r "' + url + '"'; if (play_path) command += ' -y "' + play_path + '"'; command_el.textContent = command command_el.className = 'command' command_message.textContent = 'Run this command in the commnad line:' command_message.appendChild(command_el) return command_message }, html_download_element_for_video: function (video) { var url = video.url; var protocol = url.substring(0,4) if (protocol === 'http') return this.html_video_link(url, 'Download video'); else if (protocol === 'rtmp') return this.html_rtmp_command(video); else console.error('Protocol not supported'); }, // Return an html element for the video, it's actually a table row. video_html: function (video) { var i, imageHTML, el = document.createElement('tr'), cell_image = document.createElement('td'), cell_title = document.createElement('td'), cell_ext = document.createElement('td'), cell_video_link = document.createElement('td'), cells = [cell_image, cell_title, cell_ext, cell_video_link]; if (video.thumbnail) { imageHTML = document.createElement('img'); imageHTML.src = video.thumbnail; imageHTML.className = "video-thumbnail"; } else { imageHTML = document.createElement('p'); imageHTML.textContent = 'NA'; } cell_image.appendChild(imageHTML); cell_title.textContent = video.title; cell_ext.textContent = video.ext; cell_video_link.appendChild(this.html_download_element_for_video(video)); for (i = 0; i < cells.length; i++) { el.appendChild(cells[i]); } return el; }, /* Display an error message error_msg can be a string or a html element */ display_error: function (error_msg) { var el = this.video_section(), div = document.createElement('div'), oops = document.createElement('strong'), close = document.createElement('button'), msg = document.createElement('p'), error; div.className = 'alert alert-danger'; close.type = 'button'; close.className = 'close'; close.setAttribute('data-dismiss', 'alert'); close.textContent = '×'; div.appendChild(close); oops.textContent = 'Oops!'; div.appendChild(oops); if (typeof error_msg === "string") { error = document.createElement('p'); error.textContent = error_msg; div.appendChild(error); } else { div.appendChild(error_msg); } msg.textContent = 'Make sure the website is supported by youtube-dl.'; div.appendChild(msg); el.appendChild(div); }, // Display a progress bar while the data is being load display_loading: function (url) { this.clear(); var vid_section = this.video_section(), message = document.createElement('p'), progress = document.createElement('div'); message.innerHTML = 'Requesting info for the url: '; message.appendChild(this.html_link(url)); vid_section.appendChild(message); progress.id = "progressbar"; progress.setAttribute('class', 'progress'); progress.innerHTML = '<div class="progress-bar progress-bar-striped active" style="width: 100%;"></div>'; vid_section.appendChild(progress); }, // Display the videos information display: function () { this.clear(); var data = this.data, el = this.video_section(), err_msg, table, table_body, i; if (data.error) { err_msg = document.createElement('code'); err_msg.textContent = data.error; this.display_error(err_msg); return; } el.innerHTML = 'Videos for: '; el.appendChild(this.html_link(data.url)); table = document.createElement('table'); table.setAttribute('class', 'table'); table.innerHTML = '<thead><tr><th>Thumbnail</th><th>Video title</th><th>Format</th><th>Download link</th></tr></thead>'; table_body = document.createElement('tbody'); info = data.info result_type = info._type || 'video' if (result_type === 'video') { var videos = [info] } else { var videos = info.entries } for (i = 0; i < videos.length; i++) { table_body.appendChild(this.video_html(videos[i])); } table.appendChild(table_body); el.appendChild(table); }, // Clear the video-section clear: function () { this.video_section().innerHTML = ''; } };
const Video = require('tapas-video'); function load() { const source = location.hash.slice(1); if (source) { video.setVideo(source); video.play(); } } const video = new Video('#app'); load(); window.addEventListener('hashchange', load);
//No arquivo page2.html, faça uma instrução jQuery que selecione o input text pelo atributo, depois navegue até seu elemento pai e adicione a classe "alert alert-info" nele. $(function() { $('input[type="text"]').parent().addClass('alert alert-info'); //No arquivo page2.html, faça uma instrução jQuery que selecione o item da lista e: //Adicione a classe "list-group-item-info" nenhum item. //Adicione a classe "list-group-item-dark" nos demais itens. $(".list-group-item").click(function() { $(this).removeClass("list-group-item-dark").addClass("list-group-item-info"); $(this).siblings().removeClass("list-group-item-info").addClass("list-group-item-dark"); }) });
/* global Promise */ export default fn => new Promise((resolve, reject) => { try { const result = fn(); if (result) { return resolve(result); } return reject(result); } catch (e) { reject(e); } });
// User Age Calcualtion export class Age { constructor(dob, gender, smoker, runner, lefty) { this.dob = dob; this.gender = gender; this.smoker = smoker; this.runner = runner; this.lefty = lefty; } ageInYears() { const dob = this.dob; const ageInYears = moment().diff(dob, 'years'); return ageInYears; } ageInSeconds(){ const ageInSeconds = this.ageInYears() * 31536000; return ageInSeconds; } mercury(){ const mercuryAge = Math.round(this.ageInYears() * 0.24); return mercuryAge; } venus(){ const venusAge = Math.round(this.ageInYears() * 0.62); return venusAge; } mars() { const marsAge = Math.round(this.ageInYears() * 1.88); return marsAge; } jupiter() { const jupiterAge = Math.round(this.ageInYears() * 11.86); return jupiterAge; } //Life Expectancy Notes// // US average age = 71 // male --> takes 5 years off life // smoker --> takes 13 years off life // runner --> adds 5 years to life // lefty --> takes 3 years off life lifeExpectancyEarth(gender, smoker, runner, lefty) { let averageLife = 71; if (gender === 'male') { averageLife -= 5; } if (smoker === 'yes') { averageLife -= 13; } if (runner === 'yes') { averageLife += 5; } if (lefty === 'yes') { averageLife -= 3; } return averageLife; } lifeExpectancyMercury() { const earthLife = this.lifeExpectancyEarth(); const mercuryLife = Math.round(earthLife / 0.24); return mercuryLife; } lifeExpectancyVenus() { const earthLife = this.lifeExpectancyEarth(); const venusLife = Math.round(earthLife / 0.62); return venusLife; } lifeExpectancyMars() { const earthLife = this.lifeExpectancyEarth(); const marsLife = Math.round(earthLife / 1.88); return marsLife; } lifeExpectancyJupiter() { const earthLife = this.lifeExpectancyEarth(); const jupiterLife = Math.round(earthLife / 11.86); return jupiterLife; } earthYearsLeft() { const earthLife = this.lifeExpectancyEarth(); const age = this.ageInYears(); const yearsLeft = earthLife - age; return yearsLeft; } mercuryYearsLeft() { const mercuryLife = this.lifeExpectancyMercury(); const age = this.ageInYears(); const yearsLeft = mercuryLife - age; return yearsLeft; } venusYearsLeft() { const venusLife = this.lifeExpectancyVenus(); const age = this.ageInYears(); const yearsLeft = venusLife - age; return yearsLeft; } marsYearsLeft() { const marsLife = this.lifeExpectancyMars(); const age = this.ageInYears(); const yearsLeft = marsLife - age; return yearsLeft; } jupiterYearsLeft() { const jupiterLife = this.lifeExpectancyJupiter(); const age = this.ageInYears(); const yearsLeft = jupiterLife - age; return yearsLeft; } }
let router = require('koa-router')(); let userInfoApi = require('./../api/userInfo'); const routers = router .post('/login', userInfoApi.signUp) .post('/signin', userInfoApi.signIn) .get('/logout',userInfoApi.logout) .post('/resetpassword',userInfoApi.resetPwd) .post('/setSignture',userInfoApi.updateSignature) // 修改个性签名 .post('/setUsername',userInfoApi.setUsername) // 修改用户名 .post('/setName',userInfoApi.setName) .post('/setSchool',userInfoApi.setSchool) .post('/setCollege',userInfoApi.setCollege) .post('/setProfession',userInfoApi.setProfession) .post('/setTeam',userInfoApi.setTeam) .post('/setAvatar',userInfoApi.setAvatar) .post('/getUsers',userInfoApi.getUsers) module.exports = routers;
import { Link } from "gatsby" import PropTypes from "prop-types" import React from "react" import Menu from "./nav/menu" import styled from "styled-components" // RGB (16, 210, 73 ) const Header = ({ siteTitle }) => ( <header className="header" style={{ backgroundColor:`RGB(112, 122, 139)`, marginBottom: `1.45rem`, }} > <div style={{ width: `974px`, height: `65px`, margin: `0 auto` }}> <Menu name="Home" dir="/" /> <Menu name="skill" dir="/skill" /> <Menu name="Portfolio" dir="/portfolio" /> <Menu name="History" dir="/history" /> <Menu name="Contact" dir="/contact" /> </div> </header> ) Header.propTypes = { siteTitle: PropTypes.string, } Header.defaultProps = { siteTitle: ``, } export default Header
module.exports = { "unscriptable": "Page doesn't work properly without JavaScript enabled. Please enable it to continue.", "html": { "name": "Test APP", "adminName": "Test BGAPP ", "title": "application", "description": "This is a test Application for art-template-webpack-plugin", "footer_power_explain": "Power By JHL", }, "notes": [ "Be careful you password", "Be careful data", "Be careful operation", ] }
import { forEach } from 'lodash' import { initialize, change, reset } from 'redux-form' export const standardActions = [ // common list actions 'FETCH_LIST', // saga 'SET_ENTITY_PAGE', 'SET_FETCHING_LIST', 'RESET_FETCH_CONTEXT', 'REMOVE_LOCAL_ENTITIES', 'TOGGLE_SELECTED_ITEM', 'CLEAR_SELECTED_ITEMS', // common crud actions 'FETCH_ENTITY', // saga 'SET_FETCHING_ENTITY', // saga 'SAVE_REMOTE_ENTITY', // saga 'DELETE_REMOTE_ENTITIES', // saga 'ARCHIVE_REMOTE_ENTITIES', // saga 'RESTORE_REMOTE_ENTITIES' // saga ] export const createActions = (prefix, actionNames) => { const actions = {} forEach(actionNames, (actionName) => { actions[actionName] = `${prefix}/${actionName}` }) return actions } export const createBaseActionCreators = (actions, entityName) => { return { fetchList: (serverFilters) => ({ type: actions.FETCH_LIST, serverFilters }), setEntitiesPage: (pageContext, entities, totalCount) => ({type: actions.SET_ENTITY_PAGE, pageContext, entities, totalCount}), setFetchingList: (isFetching) => ({ type: actions.SET_FETCHING_LIST, isFetching }), resetFetchContext: () => ({type: actions.RESET_FETCH_CONTEXT}), removeLocalEntities: (entityIds) => ({ type: actions.REMOVE_LOCAL_ENTITIES, entityIds }), toggleSelectedItem: (id) => ({type: actions.TOGGLE_SELECTED_ITEM, id}), clearSelectedItems: () => ({type: actions.CLEAR_SELECTED_ITEMS}), // common crud actions fetchEntity: (id) => ({ type: actions.FETCH_ENTITY, id }), setFetchingEntity: (isFetching) => ({ type: actions.SET_FETCHING_ENTITY, isFetching }), setEditedEntity: (entity) => initialize(entityName, entity), setEditedEntityFieldValue: (field, value) => change(entityName, field, value), resetEditedEntity: () => reset(entityName), clearEditedEntity: () => initialize(entityName, null), saveEntity: (entity, callback = null) => ({ type: actions.SAVE_REMOTE_ENTITY, entity, callback }), deleteEntities: (remoteIds, callback = null) => ({ type: actions.DELETE_REMOTE_ENTITIES, remoteIds, callback }), archiveEntities: (remoteIds, callback = null) => ({ type: actions.ARCHIVE_REMOTE_ENTITIES, remoteIds, callback }), restoreEntities: (remoteIds, callback = null) => ({ type: actions.RESTORE_REMOTE_ENTITIES, remoteIds, callback }) } }
const express = require('express'); const bodyParser = require('body-parser'); const compress = require('compression'); const cors = require('cors'); const helmet = require('helmet'); const logger = require('morgan'); const { ValidationError } = require('express-validation'); /* Require configuration */ const { ENV } = require('./config'); /* Get required libraries */ const { Factory: { ErrorFactory }, Mappings: { Errors: { RouteErrors } }, } = require('./libraries'); /* Require all routes */ const routes = require('./routes'); /* Create Express Application */ const app = express(); /** * Load all middlewares */ app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(compress()); // secure apps by setting various HTTP headers app.use(helmet()); // enable CORS - Cross Origin Resource Sharing app.use(cors()); // configure logger if in development if (ENV === 'development') { app.use(logger('dev')); } /** * Mount all routes on path /api */ app.use('/api', routes); /** * If requested route does not exist */ app.use((req, res, next) => { const error = ErrorFactory.getError(RouteErrors.ROUTE_NOT_FOUND); next(error); }); /** * GLOBAL ERROR HANDLER * this is a global error handler to catch all errors and pass it to next middleware * to pass a custom error to this handler from any route call next(error) */ app.use((err, req, res, next) => { let finalError = err; /* Validation Error */ if (finalError instanceof ValidationError) { /** * Handling on flattened validation error * make sure to use custom validation middleware in middleware dir * or to set keyByField to true if using validate middleware directly * or change this handling to handle detailed Validation error * See: https://www.npmjs.com/package/express-validation */ // deep clone whole error let ROUTE_VALIDATION_FAILED = { ...RouteErrors.ROUTE_VALIDATION_FAILED }; ROUTE_VALIDATION_FAILED.meta = finalError.details; finalError = ErrorFactory.getError(ROUTE_VALIDATION_FAILED); } /* Unexpected Error */ if (finalError.name !== 'APIError') { // log this error since this is an unexpected error that we didn't created ourself console.error('SYSTEM ERROR: ', finalError); finalError = ErrorFactory.getError(); } next(finalError); }); /** * This middleware sends error response back to user that is formatted by previous user * stack trace is sent only when the system is running in development mode */ app.use((err, req, res, next) => res .status(err.statusCode) .json({ message: err.message, errorKey: err.errorKey, meta: err.meta, stack: ENV === 'development' ? err.stack : {}, }) ); /** * Export express app */ module.exports = app;
var sor_8h = [ [ "sor5", "sor_8h.html#a9a3783c4b1894ab9952f87de6e8477a1", null ], [ "sor9", "sor_8h.html#abe60e0ab2bfa88f40a27de78306d3f5f", null ] ];
import bcrypt from 'bcrypt'; import dotenv from 'dotenv'; import open from 'open'; import model from '../db/models/index'; import mail from '../helpers/mail'; import validations from '../helpers/validations'; import processToken from '../helpers/processToken'; import UserHelper from '../helpers/userHelper'; import sendVerificationEmail from '../helpers/sendVerificationEmail'; dotenv.config(); const { Users, BlacklistTokens } = model; /** * user controller */ class UserManager { /** * * @param {Object} req * @param {Object} res * @returns {Object} user object */ static async registerUser(req, res) { try { const createUser = await UserHelper.createUser(req.body); const { id, username, email, bio, role } = createUser.dataValues; const token = await processToken.signToken({ id, username, email, role }); const sendVerification = await sendVerificationEmail.send(token, email); if (sendVerification) { return res.status(201).json({ message: 'Thank you for registration, You should check your email for verification', user: { token, email, username, bio, image: null } }); } } catch (error) { return res.status(409).json({ error: 'User with the same email already exist' }); } } /** * * @param {Object} req * @param {Object} res * @returns {Object} verification message */ static async verification(req, res) { try { const findUser = await Users.findOne({ where: { email: req.query.email } }); if (findUser) { if (findUser.isVerified) { return res.status(202).json({ message: 'Email already Verified.' }); } await Users.update({ isVerified: true }, { where: { id: findUser.id } }); return open('https://ah-lobos-frontend.herokuapp.com/login'); } } catch (error) { return res.status(500).json({ message: 'internal server error! please try again later' }); } } /** * @param {object} req * @param {object} res * @returns {Object} user object */ static async login(req, res) { try { const findUser = await Users.findOne({ where: { email: req.body.email } }); if (findUser) { const userData = { id: findUser.dataValues.id, username: findUser.dataValues.username, email: findUser.dataValues.email, hash: findUser.dataValues.hash, isVerified: findUser.dataValues.isVerified, role: findUser.dataValues.role }; if (!findUser.dataValues.isVerified) { return res.status(401).json({ message: 'Please check your email and click the button for email verification' }); } if (bcrypt.compareSync(req.body.password, userData.hash)) { const payload = { id: userData.id, username: userData.username, email: userData.email, role: userData.role }; const token = await processToken.signToken(payload); return res.status(200).json({ message: 'User has been successfully logged in', user: { token, email: payload.email, username: payload.username } }); } return res.status(401).json({ message: 'incorrect password' }); } return res.status(404).json({ message: `user with email: ${req.body.email} does not exist` }); } catch (error) { return res.status(500).json({ message: 'internal server error! please try again later' }); } } /** * @param {Object} req * @param {Object} res * @returns {String} acknowledgement message */ static async forgotPassword(req, res) { const checkUserInput = validations.checkForgotPasswordData(req.body); if (!checkUserInput.email) { return res.status(400).json({ error: checkUserInput, }); } const findUser = await Users.findOne({ where: { email: req.body.email } }); if (findUser !== null) { const { username, email } = findUser.dataValues; const user = { username, email }; const resetEmail = await mail.sendEmail(user); if (resetEmail[0].statusCode === 202) { return res.status(200).json({ message: 'please check your email for password reset', }); } return res.status(400).json({ error: resetEmail, }); } return res.status(404).json({ error: 'We couldn not find your account with that information,Please check and try again', }); } /** * * @param {Object} req * @param {Object} res * @returns {Object} success user password reset message */ static async resetPassword(req, res) { try { const checkUserData = validations.checkResetPasswordData(req.body); if (checkUserData.password) { const verifyToken = await processToken.verifyToken(req.params.userToken); const { password } = checkUserData; const hashedPassword = bcrypt.hashSync(password, 10); const findUser = await Users.findOne({ where: { email: verifyToken.email } }); const comparePassword = bcrypt.compareSync(password, findUser.dataValues.hash); if (comparePassword !== true) { const updatePassword = await Users.update( { hash: hashedPassword }, { where: { email: verifyToken.email } } ); if (updatePassword[0] === 1) { return res.status(200).json({ message: 'password changed successful', }); } } return res.status(406).json({ error: 'the provided password is the same as the one you had, please change it or continue using the one you have', }); } return res.status(400).json({ errors: checkUserData, }); } catch (error) { return res.status(404).json({ error: 'password reset failed, please try again' }); } } /** * * @param {obkect} req * @param {object} res * @returns {message} User logged out */ static async logout(req, res) { const { token } = req.headers; const tokenPayload = await processToken.verifyToken(token); const { exp } = tokenPayload; await BlacklistTokens.create({ token, expires: exp * 100000 }); return res.status(200).json({ message: 'User logged out' }); } } export default UserManager;
$(document).ready(function(){ $("#loginBtn").click(function(){ var data = $('#loginForm').serialize(); console.log(data); $.ajax({ url: "http://188.166.237.168/api/user/auth", method: "POST", data: data, dataType: 'json', success:function(data){ console.log('sucess : '); window.location.href= "/Users/madfo/Desktop/login-register-master/login-register/view/main.html"; } }); }); $("#regisSpan").click(function(){ $("#modal").modal("show"); //window.location.href= "/Users/madfo/Desktop/login-register-master/login-register/view/register.html"; }); $("#regisBtn").click(function(){ var data = $('#regisForm').serialize(); $.ajax({ url: "http://188.166.237.168/api/user", method: "POST", data: data, success:function(data){ console.log('sucess : ', data); $("#regisForm")[0].reset(); $("#modal").modal("hide"); // window.location.href= "/Users/User/Documents/login-register/view/index.html"; } }); }); });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const network_1 = require("./network"); const ui = {}; exports.default = ui; ui.selectedRevision = "current"; let defaultPosition; window.addEventListener("message", (event) => { if (event.data.type === "setRevision") onSelectRevision(event.data.revisionId); else if (event.data.type === "activate") ui.editor.codeMirrorInstance.focus(); else if (event.data.type === "setState") { const line = parseInt(event.data.state.line, 10); const ch = parseInt(event.data.state.ch, 10); if (ui.editor != null) ui.editor.codeMirrorInstance.getDoc().setCursor({ line, ch }); else defaultPosition = { line, ch }; } }); // Parameter hint popup ui.parameterElement = document.querySelector(".popup-parameter"); ui.parameterElement.parentElement.removeChild(ui.parameterElement); ui.parameterElement.style.display = ""; const parameterPopupKeyMap = { "Esc": () => { clearParameterPopup(); }, "Up": () => { updateParameterHint(ui.selectedSignatureIndex - 1); }, "Down": () => { updateParameterHint(ui.selectedSignatureIndex + 1); }, "Enter": () => { const selectedSignature = ui.signatureTexts[ui.selectedSignatureIndex]; if (selectedSignature.parameters.length === 0) return; const cursorPosition = ui.editor.codeMirrorInstance.getDoc().getCursor(); let text = ""; for (let parameterIndex = 0; parameterIndex < selectedSignature.parameters.length; parameterIndex++) { if (parameterIndex !== 0) text += ", "; text += selectedSignature.parameters[parameterIndex]; } ui.editor.codeMirrorInstance.getDoc().replaceRange(text, cursorPosition, null); const endSelection = { line: cursorPosition.line, ch: cursorPosition.ch + selectedSignature.parameters[0].length }; ui.editor.codeMirrorInstance.getDoc().setSelection(cursorPosition, endSelection); }, "Tab": () => { const selectedSignature = ui.signatureTexts[ui.selectedSignatureIndex]; if (selectedSignature.parameters.length === 0) return; if (ui.selectedArgumentIndex === selectedSignature.parameters.length - 1) return; const cursorPosition = ui.editor.codeMirrorInstance.getDoc().getCursor(); cursorPosition.ch += 2; const endSelection = { line: cursorPosition.line, ch: cursorPosition.ch + selectedSignature.parameters[ui.selectedArgumentIndex + 1].length }; ui.editor.codeMirrorInstance.getDoc().setSelection(cursorPosition, endSelection); } }; function clear() { document.querySelector(".loading").hidden = false; document.querySelector(".text-editor-container").hidden = true; ui.editor.setText(""); ui.errorPaneInfo.textContent = SupClient.i18n.t("common:states.loading"); ui.errorPaneStatus.classList.toggle("has-draft", false); ui.errorPaneStatus.classList.toggle("has-errors", false); clearErrors(); } exports.clear = clear; function start(asset) { document.querySelector(".loading").hidden = true; document.querySelector(".text-editor-container").hidden = false; ui.editor.setText(asset.pub.draft); ui.errorPaneStatus.classList.toggle("has-draft", asset.hasDraft && ui.selectedRevision === "current"); if (ui.selectedRevision !== "current") ui.editor.codeMirrorInstance.setOption("readOnly", true); else if (defaultPosition != null) ui.editor.codeMirrorInstance.getDoc().setCursor(defaultPosition); } exports.start = start; // Setup editor function setupEditor(clientId) { const textArea = document.querySelector(".text-editor"); ui.editor = new TextEditorWidget(network_1.data.projectClient, clientId, textArea, { mode: "text/typescript", extraKeys: { "Ctrl-S": () => { applyDraftChanges({ ignoreErrors: false }); }, "Cmd-S": () => { applyDraftChanges({ ignoreErrors: false }); }, "Ctrl-Alt-S": () => { applyDraftChanges({ ignoreErrors: true }); }, "Cmd-Alt-S": () => { applyDraftChanges({ ignoreErrors: true }); }, "Ctrl-Space": () => { scheduleParameterHint(); scheduleCompletion(); }, "Cmd-Space": () => { scheduleParameterHint(); scheduleCompletion(); }, "Shift-Ctrl-F": () => { onGlobalSearch(); }, "Shift-Cmd-F": () => { onGlobalSearch(); }, "F8": () => { const cursor = ui.editor.codeMirrorInstance.getDoc().getCursor(); const token = ui.editor.codeMirrorInstance.getTokenAt(cursor); if (token.string === ".") token.start = token.end; let start = 0; for (let i = 0; i < cursor.line; i++) start += ui.editor.codeMirrorInstance.getDoc().getLine(i).length + 1; start += cursor.ch; network_1.data.typescriptWorker.postMessage({ type: "getDefinitionAt", name: network_1.data.fileNamesByScriptId[SupClient.query.asset], start }); } }, editCallback: onEditText, sendOperationCallback: (operation) => { network_1.data.projectClient.editAsset(SupClient.query.asset, "editText", operation, network_1.data.asset.document.getRevisionId()); } }); ui.previousLine = -1; SupClient.setupCollapsablePane(ui.errorPane, () => { ui.editor.codeMirrorInstance.refresh(); }); ui.editor.codeMirrorInstance.on("keyup", (instance, event) => { clearInfoPopup(); // "("" character triggers the parameter hint if (event.keyCode === 53 || (ui.parameterElement.parentElement != null && event.keyCode !== 27 && event.keyCode !== 38 && event.keyCode !== 40)) scheduleParameterHint(); // Ignore Ctrl, Cmd, Escape, Return, Tab, arrow keys, F8 if (event.ctrlKey || event.metaKey || [27, 9, 13, 37, 38, 39, 40, 119, 16].indexOf(event.keyCode) !== -1) return; // If the completion popup is active, the hint() method will automatically // call for more autocomplete, so we don't need to do anything here. if (ui.editor.codeMirrorInstance.state.completionActive != null && ui.editor.codeMirrorInstance.state.completionActive.active()) return; scheduleCompletion(); }); ui.editor.codeMirrorInstance.on("cursorActivity", () => { const currentLine = ui.editor.codeMirrorInstance.getDoc().getCursor().line; if (Math.abs(currentLine - ui.previousLine) >= 1) clearParameterPopup(); else if (ui.parameterElement.parentElement != null) scheduleParameterHint(); ui.previousLine = currentLine; }); ui.editor.codeMirrorInstance.on("endCompletion", () => { ui.completionOpened = false; if (ui.parameterElement.parentElement != null) ui.editor.codeMirrorInstance.addKeyMap(parameterPopupKeyMap); }); } exports.setupEditor = setupEditor; let localVersionNumber = 0; function onEditText(text, origin) { const localFileName = network_1.data.fileNamesByScriptId[SupClient.query.asset]; const localFile = network_1.data.files[localFileName]; localFile.text = text; localVersionNumber++; localFile.version = `l${localVersionNumber}`; // We ignore the initial setValue if (origin !== "setValue") { network_1.data.typescriptWorker.postMessage({ type: "updateFile", fileName: localFileName, text: localFile.text, version: localFile.version }); network_1.scheduleErrorCheck(); } } function onSelectRevision(revisionId) { if (revisionId === "restored") { ui.selectedRevision = "current"; ui.editor.codeMirrorInstance.setOption("readOnly", false); return; } ui.selectedRevision = revisionId; clear(); if (ui.selectedRevision === "current") { network_1.data.asset = network_1.data.assetsById[SupClient.query.asset]; start(network_1.data.asset); network_1.updateWorkerFile(SupClient.query.asset, network_1.data.asset.pub.draft, network_1.data.asset.pub.revisionId.toString()); } else { network_1.data.projectClient.getAssetRevision(SupClient.query.asset, "script", ui.selectedRevision, (id, asset) => { start(asset); network_1.updateWorkerFile(SupClient.query.asset, asset.pub.draft, `l${localVersionNumber}`); }); } } // Error pane ui.errorPane = document.querySelector(".error-pane"); ui.errorPaneStatus = ui.errorPane.querySelector(".header"); ui.errorPaneInfo = ui.errorPaneStatus.querySelector(".info"); const errorsContent = ui.errorPane.querySelector(".content"); ui.errorsTBody = errorsContent.querySelector("tbody"); ui.errorsTBody.addEventListener("click", onErrorTBodyClick); function clearErrors() { ui.editor.codeMirrorInstance.operation(() => { // Remove all previous errors for (const textMarker of ui.editor.codeMirrorInstance.getDoc().getAllMarks()) { if (textMarker.className !== "line-error") continue; textMarker.clear(); } ui.editor.codeMirrorInstance.clearGutter("line-error-gutter"); ui.errorsTBody.innerHTML = ""; }); } function refreshErrors(errors) { clearErrors(); ui.saveButton.hidden = false; ui.saveWithErrorsButton.hidden = true; if (errors.length === 0) { ui.errorPaneInfo.textContent = SupClient.i18n.t("scriptEditor:errors.noErrors"); ui.errorPaneStatus.classList.remove("has-errors"); return; } ui.errorPaneStatus.classList.add("has-errors"); let selfErrorsCount = 0; let lastSelfErrorRow = null; // Display new ones ui.editor.codeMirrorInstance.operation(() => { for (const error of errors) { const errorRow = document.createElement("tr"); errorRow.dataset["line"] = error.position.line.toString(); errorRow.dataset["character"] = error.position.character.toString(); const positionCell = document.createElement("td"); positionCell.textContent = (error.position.line + 1).toString(); errorRow.appendChild(positionCell); const messageCell = document.createElement("td"); messageCell.textContent = error.message; errorRow.appendChild(messageCell); const scriptCell = document.createElement("td"); errorRow.appendChild(scriptCell); if (error.file !== "") { errorRow.dataset["assetId"] = network_1.data.files[error.file].id; scriptCell.textContent = error.file.substring(0, error.file.length - 3); } else scriptCell.textContent = "Internal"; if (error.file !== network_1.data.fileNamesByScriptId[SupClient.query.asset]) { ui.errorsTBody.appendChild(errorRow); continue; } ui.errorsTBody.insertBefore(errorRow, (lastSelfErrorRow != null) ? lastSelfErrorRow.nextElementSibling : ui.errorsTBody.firstChild); lastSelfErrorRow = errorRow; selfErrorsCount++; const line = error.position.line; ui.editor.codeMirrorInstance.getDoc().markText({ line, ch: error.position.character }, { line, ch: error.position.character + error.length }, { className: "line-error" }); const gutter = document.createElement("div"); gutter.className = "line-error-gutter"; gutter.innerHTML = "●"; ui.editor.codeMirrorInstance.setGutterMarker(line, "line-error-gutter", gutter); } const otherErrorsCount = errors.length - selfErrorsCount; const selfErrorsValue = SupClient.i18n.t(`scriptEditor:errors.${selfErrorsCount > 1 ? "severalErrors" : "oneError"}`, { errors: selfErrorsCount.toString() }); const selfErrors = SupClient.i18n.t("scriptEditor:errors.selfErrorsInfo", { errors: selfErrorsValue.toString() }); const otherErrorsValue = SupClient.i18n.t(`scriptEditor:errors.${otherErrorsCount > 1 ? "severalErrors" : "oneError"}`, { errors: otherErrorsCount.toString() }); const otherErrors = SupClient.i18n.t("scriptEditor:errors.otherErrorsInfo", { errors: otherErrorsValue.toString() }); if (selfErrorsCount > 0) { ui.saveButton.hidden = true; ui.saveWithErrorsButton.hidden = false; if (otherErrorsCount === 0) ui.errorPaneInfo.textContent = selfErrors; else ui.errorPaneInfo.textContent = SupClient.i18n.t("scriptEditor:errors.bothErrorsInfo", { selfErrors, otherErrors }); } else ui.errorPaneInfo.textContent = otherErrors; }); } exports.refreshErrors = refreshErrors; function onErrorTBodyClick(event) { let target = event.target; while (true) { if (target.tagName === "TBODY") return; if (target.tagName === "TR") break; target = target.parentElement; } const assetId = target.dataset["assetId"]; if (assetId == null) return; const line = target.dataset["line"]; const character = target.dataset["character"]; if (assetId === SupClient.query.asset) { ui.editor.codeMirrorInstance.getDoc().setCursor({ line: parseInt(line, 10), ch: parseInt(character, 10) }); ui.editor.codeMirrorInstance.focus(); } else { if (window.parent != null) SupClient.openEntry(assetId, { line, ch: character }); } } // Save buttons ui.saveButton = ui.errorPane.querySelector(".draft button.save"); ui.saveButton.addEventListener("click", (event) => { event.preventDefault(); event.stopPropagation(); applyDraftChanges({ ignoreErrors: false }); }); ui.saveWithErrorsButton = ui.errorPane.querySelector(".draft button.save-with-errors"); ui.saveWithErrorsButton.addEventListener("click", (event) => { event.preventDefault(); event.stopPropagation(); applyDraftChanges({ ignoreErrors: true }); }); function applyDraftChanges(options) { ui.saveButton.disabled = true; ui.saveWithErrorsButton.disabled = true; ui.saveButton.textContent = SupClient.i18n.t("common:states.saving"); if (options.ignoreErrors) ui.saveWithErrorsButton.textContent = SupClient.i18n.t("common:states.saving"); network_1.data.projectClient.editAssetNoErrorHandling(SupClient.query.asset, "applyDraftChanges", options, (err) => { if (err != null && err !== "foundSelfErrors") { new SupClient.Dialogs.InfoDialog(err); SupClient.onDisconnected(); return; } ui.saveButton.disabled = false; ui.saveWithErrorsButton.disabled = false; ui.saveButton.textContent = SupClient.i18n.t("common:actions.applyChanges"); ui.saveWithErrorsButton.textContent = SupClient.i18n.t("common:actions.applyChangesWithErrors"); }); } // Info popup ui.infoElement = document.createElement("div"); ui.infoElement.classList.add("popup-info"); document.addEventListener("mouseout", (event) => { clearInfoPopup(); }); let previousMousePosition = { x: -1, y: -1 }; document.addEventListener("mousemove", (event) => { if (ui.editor == null) return; // On some systems, Chrome (at least v43) generates // spurious "mousemove" events every second or so. if (event.clientX === previousMousePosition.x && event.clientY === previousMousePosition.y) return; previousMousePosition.x = event.clientX; previousMousePosition.y = event.clientY; clearInfoPopup(); ui.infoTimeout = window.setTimeout(() => { ui.infoPosition = ui.editor.codeMirrorInstance.coordsChar({ left: event.clientX, top: event.clientY }); if (ui.infoPosition.outside) return; let start = 0; for (let i = 0; i < ui.infoPosition.line; i++) start += ui.editor.codeMirrorInstance.getDoc().getLine(i).length + 1; start += ui.infoPosition.ch; ui.infoTimeout = null; network_1.data.typescriptWorker.postMessage({ type: "getQuickInfoAt", name: network_1.data.fileNamesByScriptId[SupClient.query.asset], start }); }, 200); }); function clearInfoPopup() { if (ui.infoElement.parentElement != null) ui.infoElement.parentElement.removeChild(ui.infoElement); if (ui.infoTimeout != null) clearTimeout(ui.infoTimeout); } function showParameterPopup(texts, selectedItemIndex, selectedArgumentIndex) { ui.signatureTexts = texts; ui.selectedArgumentIndex = selectedArgumentIndex; updateParameterHint(selectedItemIndex); const position = ui.editor.codeMirrorInstance.getDoc().getCursor(); const coordinates = ui.editor.codeMirrorInstance.cursorCoords(position, "page"); ui.parameterElement.style.top = `${Math.round(coordinates.top - 30)}px`; ui.parameterElement.style.left = `${coordinates.left}px`; document.body.appendChild(ui.parameterElement); if (!ui.completionOpened) ui.editor.codeMirrorInstance.addKeyMap(parameterPopupKeyMap); } exports.showParameterPopup = showParameterPopup; function updateParameterHint(index) { if (index < 0) index = ui.signatureTexts.length - 1; else if (index >= ui.signatureTexts.length) index = 0; ui.selectedSignatureIndex = index; ui.parameterElement.querySelector(".item").textContent = `(${index + 1}/${ui.signatureTexts.length})`; const text = ui.signatureTexts[index]; let prefix = text.prefix; let parameter = ""; let suffix = ""; for (let parameterIndex = 0; parameterIndex < text.parameters.length; parameterIndex++) { let parameterItem = text.parameters[parameterIndex]; if (parameterIndex < ui.selectedArgumentIndex) { if (parameterIndex !== 0) prefix += ", "; prefix += parameterItem; } else if (parameterIndex === ui.selectedArgumentIndex) { if (parameterIndex !== 0) prefix += ", "; parameter = parameterItem; } else { if (parameterIndex !== 0) suffix += ", "; suffix += parameterItem; } } ui.parameterElement.querySelector(".prefix").textContent = prefix; ui.parameterElement.querySelector(".parameter").textContent = parameter; suffix += text.suffix; ui.parameterElement.querySelector(".suffix").textContent = suffix; } function clearParameterPopup() { if (ui.parameterElement.parentElement != null) ui.parameterElement.parentElement.removeChild(ui.parameterElement); ui.editor.codeMirrorInstance.removeKeyMap(parameterPopupKeyMap); } exports.clearParameterPopup = clearParameterPopup; function scheduleParameterHint() { if (ui.parameterTimeout != null) clearTimeout(ui.parameterTimeout); ui.parameterTimeout = window.setTimeout(() => { const cursor = ui.editor.codeMirrorInstance.getDoc().getCursor(); const token = ui.editor.codeMirrorInstance.getTokenAt(cursor); if (token.string === ".") token.start = token.end; let start = 0; for (let i = 0; i < cursor.line; i++) start += ui.editor.codeMirrorInstance.getDoc().getLine(i).length + 1; start += cursor.ch; network_1.data.typescriptWorker.postMessage({ type: "getParameterHintAt", name: network_1.data.fileNamesByScriptId[SupClient.query.asset], start }); ui.parameterTimeout = null; }, 100); } function hint(instance, callback) { const cursor = ui.editor.codeMirrorInstance.getDoc().getCursor(); const token = ui.editor.codeMirrorInstance.getTokenAt(cursor); if (token.string === ".") token.start = token.end; let start = 0; for (let i = 0; i < cursor.line; i++) start += ui.editor.codeMirrorInstance.getDoc().getLine(i).length + 1; start += cursor.ch; network_1.setNextCompletion({ callback, cursor, token, start }); } hint.async = true; const hintCustomKeys = { "Up": (cm, commands) => { commands.moveFocus(-1); }, "Down": (cm, commands) => { commands.moveFocus(1); }, "Enter": (cm, commands) => { commands.pick(); }, "Tab": (cm, commands) => { commands.pick(); }, "Esc": (cm, commands) => { commands.close(); }, }; function scheduleCompletion() { if (ui.completionTimeout != null) clearTimeout(ui.completionTimeout); ui.completionTimeout = window.setTimeout(() => { ui.completionOpened = true; if (ui.parameterElement.parentElement != null) ui.editor.codeMirrorInstance.removeKeyMap(parameterPopupKeyMap); ui.editor.codeMirrorInstance.showHint({ completeSingle: false, customKeys: hintCustomKeys, hint }); ui.completionTimeout = null; }, 100); } // Global search function onGlobalSearch() { if (window.parent == null) { // TODO: Find a way to make it work? or display a message saying that you can't? return; } const options = { placeholder: SupClient.i18n.t("scriptEditor:globalSearch.placeholder"), initialValue: ui.editor.codeMirrorInstance.getDoc().getSelection(), validationLabel: SupClient.i18n.t("common:actions.search") }; new SupClient.Dialogs.PromptDialog(SupClient.i18n.t("scriptEditor:globalSearch.prompt"), options, (text) => { if (text == null) { ui.editor.codeMirrorInstance.focus(); return; } window.parent.postMessage({ type: "openTool", name: "search", state: { text } }, window.location.origin); }); }
const { Sequelize } = require('sequelize') require('dotenv').config() const database = new Sequelize( process.env.BD_NAME, process.env.BD_USER, process.env.BD_PASSWORD, { host: process.env.BD_HOST, dialect: 'mysql', port: process.env.BD_PORT }) module.exports = database
import { http, Http } from '../../../src/platform/net/http.js'; import { expect } from 'chai'; import { restore, spy } from 'sinon'; describe('Http', function () { let retryDelay; beforeEach(function () { retryDelay = Http.retryDelay; Http.retryDelay = 1; }); afterEach(function () { Http.retryDelay = retryDelay; restore(); }); describe('#get()', function () { it('returns resource', function (done) { http.get('http://localhost:3000/test/test-assets/test.json', function (err, data) { expect(err).to.equal(null); expect(data).to.deep.equal({ a: 1, b: true, c: 'hello world' }); done(); }); }); it('does not retry if retry is false', function (done) { spy(http, 'request'); http.get('http://localhost:3000/someurl.json', function (err, data) { expect(err).to.equal(404); expect(http.request.callCount).to.equal(1); done(); }); }); it('retries resource and returns 404 in the end if not found', function (done) { spy(http, 'request'); http.get('http://localhost:3000/someurl.json', { retry: true, maxRetries: 2 }, function (err) { expect(err).to.equal(404); expect(http.request.callCount).to.equal(3); done(); }); }); it('retries resource 5 times by default', function (done) { spy(http, 'request'); http.get('http://localhost:3000/someurl.json', { retry: true }, function (err) { expect(http.request.callCount).to.equal(6); done(); }); }); }); });
import React from 'react'; import './Error.scss'; const Error = ({ text }) => ( <div className="Error">Something went wrong:{text}</div> ); export default Error;
// element creators and selectors var btn = document.createElement("button"); var h3 = document.createElement("h3"); var timer = document.getElementById("timer") var par = document.createElement("p"); var listItem1 = document.createElement("li"); var listItem2 = document.createElement("li"); var listItem3 = document.createElement("li"); var listItem4 = document.createElement("li"); var list = document.createElement("ol"); var divC = document.createElement("div"); var body = document.body; var timeInterval; var question1; var question2; var question3; var question4; var question5; // when user clicks button labelled "begin" the quiz will begin and take them to the first question var beginQuiz = function() { btn.innerHTML = "Click here to begin! Good luck!"; document.getElementById("start-button").appendChild(btn); btn.setAttribute("style", "background-color:red; color:white; padding:50px; font-size:20px; margin:auto; margin-top:100px;"); }; // the landing page will clear and the questions will begin var clearLandingPage = function() { document.getElementById("wrapper").textContent = ""; }; // a timer will begin countding down from 120 seconds. Ten seconds will be deducted from time when users pick wrong selection var countdown = function() { var timeLeft = 120; var timeInterval = setInterval(function() { if (timeLeft <= 0) { clearInterval(timeInterval); window.alert("You've run out of time! Let's see how you did!"); document.getElementById("timer").textContent = ""; } else { timer.textContent = timeLeft + " seconds remaining." timeLeft--; } if (question1 === 1) { timeLeft = timeLeft - 10; question1 = question1 + 1; }; if (question2 === 1) { timeLeft = timeLeft - 10; question2 = question2 + 1; }; if (question3 === 1) { timeLeft = timeLeft - 10; question3 = question3 + 1; }; if (question4 === 1) { timeLeft = timeLeft - 10; question4 = question4 + 1; }; if (question5 === 1) { timeLeft = timeLeft - 10; question5 = question5 + 1; }; }, 1000); }; // question one will display // If the correct choice is selected, the time will remain the same and the next question will display // If the incorrect choice is selected, ten seconds will be deducted from the timer var questionOne = function() { className = "question-one"; divC.textContent = "Question One"; body.appendChild(divC); divC.setAttribute("style", "font-size:30px; text-align:center;"); h3.textContent = "Which of the following is NOT a conditional statement."; divC.appendChild(h3); divC.appendChild(list); listItem1.textContent = "for"; list.appendChild(listItem1); listItem1.addEventListener("click", function () { question1 = 0, questionTwo(); }); listItem2.textContent = "while"; list.appendChild(listItem2); listItem2.addEventListener("click", function() { question1 = 0, questionTwo(); }); listItem3.textContent = "but"; list.appendChild(listItem3); listItem3.addEventListener("click", function() { questionTwo(); }); listItem4.textContent = "else"; list.appendChild(listItem4); listItem4.addEventListener("click", function() { question1 = 0, questionTwo(); }); }; // question two var questionTwo = function() { divC.textContent = "Question Two"; className = "question-two"; body.appendChild(divC); divC.setAttribute("style", "font-size:30px; text-align:center;"); h3.textContent = "Which of the following letters is used to represent an iterator."; divC.appendChild(h3); divC.appendChild(list); listItem1.textContent = "i"; list.appendChild(listItem1); listItem1.addEventListener("click", function() { question2 = 0, questionThree(); }); listItem2.textContent = "p"; list.appendChild(listItem2); listItem2.addEventListener("click", function() { question2 = 1, questionThree(); }); listItem3.textContent = "r"; list.appendChild(listItem3); listItem3.addEventListener("click", function() { question2 = 1, questionThree(); }); listItem4.textContent = "y"; list.appendChild(listItem4); listItem4.addEventListener("click", function() { question2 = 1, questionThree(); }); }; // question three var questionThree = function() { divC.textContent = "Question Three"; divC.className = "question-three"; body.appendChild(divC); divC.setAttribute("style", "font-size:30px; text-align:center;"); h3.textContent = "What does DOM stand for?"; divC.appendChild(h3); divC.appendChild(list); listItem1.textContent = "Directory Object Model"; list.appendChild(listItem1); listItem1.addEventListener("click", function() { question3 = 1, questionFour(); }); listItem2.textContent = "Directional Omni Mode"; list.appendChild(listItem2); listItem2.addEventListener("click", function() { question3 = 1, questionFour(); }); listItem3.textContent = "Document Object Model"; list.appendChild(listItem3); listItem3.addEventListener("click", function() { question4 = 0, questionFour(); }); listItem4.textContent = "Documentational Object Mode"; list.appendChild(listItem4); listItem4.addEventListener("click", function() { question3 = 1, questionFour(); }); }; // question four var questionFour = function() { divC.textContent = "Question Four"; body.appendChild(divC); divC.setAttribute("style", "font-size:30px; text-align:center;"); h3.textContent = "What does the appendChild function do?"; divC.appendChild(h3); divC.appendChild(list); listItem1.textContent = "appends a child element to its parent element"; list.appendChild(listItem1); listItem1.addEventListener("click", function() { question4 = 0, questionFive(); }); listItem2.textContent = "creates a child element"; list.appendChild(listItem2); listItem2.addEventListener("click", function() { question4 = 1, questionFive(); }); listItem3.textContent = "deletes a child element"; list.appendChild(listItem3); listItem3.addEventListener("click", function() { question4 = 1, questionFive(); }); listItem4.textContent = "iterates through an array"; list.appendChild(listItem4); listItem4.addEventListener("click", function() { question4 = 1, questionFive(); }); }; // question five. When a selection is made, the user will be taken to the endgame page var questionFive = function() { className = "question-five"; divC.textContent = "Question Five"; body.appendChild(divC); divC.setAttribute("style", "font-size:30px; text-align:center;"); h3.textContent = "When using JavaScript, where should the source file be placed in the HTML?"; divC.appendChild(h3); divC.appendChild(list); listItem1.textContent = "in the head"; list.appendChild(listItem1); listItem1.addEventListener("click", function() { question5 = 1, endScreen(); }); listItem2.textContent = "at the top of the body"; list.appendChild(listItem2); listItem2.addEventListener("click", function() { question5 = 1, endScreen(); }); listItem3.textContent = "after the closing </html> element"; list.appendChild(listItem3); listItem3.addEventListener("click", function() { question5 = 1, endScreen(); }); listItem4.textContent = "at the end of the body"; list.appendChild(listItem4); listItem4.addEventListener("click", function() { question5 = 0, endScreen(); }); }; var endScreen = function() { }; // their score will be logged into the localstorage btn.addEventListener("click", function() { clearLandingPage(); countdown(); questionOne(); }); beginQuiz();
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import State from './State'; import { noop } from '../utils'; export default class Filter extends Component { static propTypes = { /** * The default query. Default: ''. */ defaultQuery: PropTypes.any, /** * A function to filter the items. (Should return all items for a null or * undefined query). * @param {arrray} items * @param {any} query */ filterFunc: PropTypes.func.isRequired, /** * The items to filter. */ items: PropTypes.array, /** * Control prop. [Optional] */ query: PropTypes.any, /** * This function is called when the query is changed. * @param {*} newQuery The new query. */ onQueryChange: PropTypes.func, /** * The render function * @param {object} props * @param {array} props.filteredItems The filtered items. * @param {*} props.query The current query. * @param {func} props.refine This function takes a new query and updates * the filteredItems. */ render: PropTypes.func.isRequired, } static defaultProps = { items: [], defaultQuery: '', onQueryChange: noop, } handleStateChange = changes => { if (changes.hasOwnProperty('query')) { this.props.onQueryChange(changes.query); } }; renderFunc = ({state, setState}) => { const { render, filterFunc, items } = this.props; const filteredItems = filterFunc(items, state.query); const refine = query => setState({ query }); return render({ filteredItems, refine, query: state.query }); } render() { const { defaultQuery, query } = this.props; return ( <State initial={{ query: defaultQuery }} onStateChange={this.handleStateChange} query={query} render={this.renderFunc} /> ); } }
const todoPageNumberReducer = (state = 1, action) => { if (action.type === "TODO-INCREMENT") { return state + 1; } return state; }; const donePageNumberReducer = (state = 1, action) => { if (action.type === "DONE-INCREMENT") { return state + 1; } return state; }; const pinPageNumberReducer = (state = 1, action) => { if (action.type === "PIN-INCREMENT") { return state + 1; } return state; }; export { todoPageNumberReducer, donePageNumberReducer, pinPageNumberReducer };
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; var _excluded = ["defaultPageIndex", "pageCount", "pageIndex", "pageIndexChange", "pagesCountText"]; import { createVNode, createComponentVNode } from "inferno"; import { InfernoEffect, InfernoComponent } from "@devextreme/vdom"; import { Page } from "./page"; import { PAGER_INFO_CLASS } from "../info"; import { NumberBox } from "../../number_box"; import messageLocalization from "../../../../localization/message"; import { calculateValuesFittedWidth } from "../utils/calculate_values_fitted_width"; import { getElementMinWidth } from "../utils/get_element_width"; import { PagerProps } from "../common/pager_props"; var PAGER_INFO_TEXT_CLASS = "".concat(PAGER_INFO_CLASS, " dx-info-text"); var PAGER_PAGE_INDEX_CLASS = "dx-page-index"; var LIGHT_PAGES_CLASS = "dx-light-pages"; var PAGER_PAGES_COUNT_CLASS = "dx-pages-count"; export var viewFunction = _ref => { var { pageIndexRef, pagesCountText, props: { pageCount }, selectLastPageIndex, value, valueChange, width } = _ref; return createVNode(1, "div", LIGHT_PAGES_CLASS, [createComponentVNode(2, NumberBox, { "rootElementRef": pageIndexRef, "className": PAGER_PAGE_INDEX_CLASS, "min": 1, "max": pageCount, "width": width, "value": value, "valueChange": valueChange }), createVNode(1, "span", PAGER_INFO_TEXT_CLASS, pagesCountText, 0), createComponentVNode(2, Page, { "className": PAGER_PAGES_COUNT_CLASS, "selected": false, "index": pageCount - 1, "onClick": selectLastPageIndex })], 4); }; var PagerSmallProps = { pageCount: PagerProps.pageCount, defaultPageIndex: PagerProps.pageIndex }; import { createRef as infernoCreateRef } from "inferno"; export class PagesSmall extends InfernoComponent { constructor(props) { super(props); this._currentState = null; this.pageIndexRef = infernoCreateRef(); this.state = { minWidth: 10, pageIndex: this.props.pageIndex !== undefined ? this.props.pageIndex : this.props.defaultPageIndex }; this.updateWidth = this.updateWidth.bind(this); this.selectLastPageIndex = this.selectLastPageIndex.bind(this); this.valueChange = this.valueChange.bind(this); } createEffects() { return [new InfernoEffect(this.updateWidth, [this.minWidth])]; } updateEffects() { var _this$_effects$; (_this$_effects$ = this._effects[0]) === null || _this$_effects$ === void 0 ? void 0 : _this$_effects$.update([this.minWidth]); } get minWidth() { var state = this._currentState || this.state; return state.minWidth; } set_minWidth(value) { this.setState(state => { this._currentState = state; var newValue = value(); this._currentState = null; return { minWidth: newValue }; }); } get __state_pageIndex() { var state = this._currentState || this.state; return this.props.pageIndex !== undefined ? this.props.pageIndex : state.pageIndex; } set_pageIndex(value) { this.setState(state => { var _this$props$pageIndex, _this$props; this._currentState = state; var newValue = value(); (_this$props$pageIndex = (_this$props = this.props).pageIndexChange) === null || _this$props$pageIndex === void 0 ? void 0 : _this$props$pageIndex.call(_this$props, newValue); this._currentState = null; return { pageIndex: newValue }; }); } updateWidth() { this.set_minWidth(() => this.pageIndexRef.current && getElementMinWidth(this.pageIndexRef.current) || this.minWidth); } get value() { return this.__state_pageIndex + 1; } get width() { var pageCount = this.props.pageCount; return calculateValuesFittedWidth(this.minWidth, [pageCount]); } get pagesCountText() { return this.props.pagesCountText || messageLocalization.getFormatter("dxPager-pagesCountText")(); } selectLastPageIndex() { var _this$props$pageIndex2, _this$props2; var { pageCount } = this.props; (_this$props$pageIndex2 = (_this$props2 = this.props).pageIndexChange) === null || _this$props$pageIndex2 === void 0 ? void 0 : _this$props$pageIndex2.call(_this$props2, pageCount - 1); } valueChange(value) { this.set_pageIndex(() => value - 1); } get restAttributes() { var _this$props$pageIndex3 = _extends({}, this.props, { pageIndex: this.__state_pageIndex }), restProps = _objectWithoutPropertiesLoose(_this$props$pageIndex3, _excluded); return restProps; } render() { var props = this.props; return viewFunction({ props: _extends({}, props, { pageIndex: this.__state_pageIndex }), pageIndexRef: this.pageIndexRef, value: this.value, width: this.width, pagesCountText: this.pagesCountText, selectLastPageIndex: this.selectLastPageIndex, valueChange: this.valueChange, restAttributes: this.restAttributes }); } } PagesSmall.defaultProps = _extends({}, PagerSmallProps);
let arr = [16,17,4,3,19,2]; var n = arr.length; var result=leader(arr,n) console.log(result); function leader(arr,n){ // var arr = [16,17,4,3,5,2]; // var n=arr.length; var i ,j; for(i=0;i<n;i++){ for(j=i+1;j<n;j++) { if(arr[i]<arr[j]) // break; console.log(arr[j]); break; } if(j==n){ console.log(arr[i]); } // return } } // return;
const path = require("path"); const CracoAlias = require("craco-alias"); module.exports = function({ env, paths }) { return { webpack: { alias: { environment: path.join( __dirname, "src", "environments", process.env.CLIENT_ENV ) } }, plugins: [ { plugin: CracoAlias, options: { aliases: { "@shared": "src/_shared", "@assets": "src/assets" } } } ] }; };
import React from 'react'; import { Flex, Box, Grid } from 'reflexbox'; import EasyTransition from 'react-easy-transition'; import PetroTheme from '../theme/PetroTheme'; import Sidebar from './sidebar/Sidebar'; import RightContent from './rightContent/RightContent'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import styles from './App.css.js'; class App extends React.Component{ constructor(props, context) { super(props, context); console.log('In App props are', props); console.log('In App context is', context); } render(){ return ( <MuiThemeProvider muiTheme={PetroTheme}> <div> <Grid col={2} px={0}> <Sidebar currentPath={this.props.location} /> </Grid> <Grid col={10} px={0} style={{height:"100vh"}}> <RightContent nav={this.props.history}> <div id="pre" style={{width:'100%', height:'100%'}}> {this.props.children} </div> </RightContent> </Grid> </div> </MuiThemeProvider> ) } } export default App;
let net; const webcamElement = document.getElementById('webcam'); const classifier = knnClassifier.create(); /* creating arrays for each class var Isha_set=localStorage.getItem("isha")? localStorage.getItem("isha").split("ISHA"):[]; var is_new = Isha_set.map(Ish =>{ return JSON.parse(Ish); }) const Prabhat_set=[]; const Shourya_set=[]; const Avi_set=[]; */ async function app() { console.log('Loading mobilenet..'); // Load the model. net = await mobilenet.load(); console.log('Successfully loaded model'); // Create an object from Tensorflow.js data API which could capture image // from the web camera as Tensor. const webcam = await tf.data.webcam(webcamElement); // Reads an image from the webcam and associates it with a specific class // index. const addExample = async classId => { // Capture an image from the web camera. const img = await webcam.capture(); // Get the intermediate activation of MobileNet 'conv_preds' and pass that // to the KNN classifier. const activation = net.infer(img, true); // Pass the intermediate activation to the classifier. classifier.addExample(activation, classId); /*if(classId==0){ Isha_set.push(img); var nm1=Isha_set.map(val=>{ return JSON.stringify(val) }) var tm1=nm1.join("ISHA") localStorage.setItem("isha",tm1) } else if(classId==1){ Prabhat_set.push(img); } else if(classId==2){ Shourya_set.push(img); } else if(classId==3){ Avi_set.push(img); } */ //console.log(Isha_set); //is.show(); //await img.save('localStorage://mymodel'); //classifier.getClassifierDataset(); // Dispose the tensor to release the memory. img.dispose(); }; // When clicking a button, add an example for that class. document.getElementById('Isha').addEventListener('click', () => addExample(0)); document.getElementById('Prabhat').addEventListener('click', () => addExample(1)); document.getElementById('Shourya').addEventListener('click', () => addExample(2)); document.getElementById('Avi').addEventListener('click', () => addExample(3)); while (true) { if (classifier.getNumClasses() > 0) { const img = await webcam.capture(); // Get the activation from mobilenet from the webcam. const activation = net.infer(img, 'conv_preds'); // Get the most likely class and confidence from the classifier module. const result = await classifier.predictClass(activation); const classes = ['Isha', 'Prabhat', 'Shourya','Avi']; document.getElementById('console').innerText = ` prediction: ${classes[result.label]}\n probability: ${result.confidences[result.label]}`; // Dispose the tensor to release the memory. img.dispose(); } await tf.nextFrame(); } } app();
import styled from "styled-components"; const LogoutStyled = styled.div` display: flex; flex-direction: row-reverse; margin-right: 15%; button { background: white; border: none; color: #EF271B; margin-bottom: 10px; } ` export default LogoutStyled
/*var num = prompt("How many series have you watched on our website? ? "); console.log(num); if (num >= 5) { alert("hello you are one from our family Please tell others about us") document.write("<p style='color:red;'> This became " + num + " series from our website </p>") } else if(num < 5) { alert("We hope you have a great time to come back and watch another series") document.write("<p style='color:red;'> This became " + num + " series from our website </p>") }*/ /*var kindwatch = prompt("How do you prefer to watch your series? Choose if online ,download ") while (kindwatch != "online" && kindwatch!= "download") { kindwatch = prompt("please enter on of : online, download"); } var numser = prompt("How many series have you watched on our website?") var output=""; for (var i=0 ; i<numser; i++) { var output = output + "<img src='https://money-h.com/picture//fin-will_1/how-to-encourage-someone-in-3-steps.jpg' width='50px'; />"; } document.write(output);*/ /*var kindwatch = prompt("How do you prefer to watch your series? Choose if online ,download ") function kindwatchfun() { while (kindwatch != "online" && kindwatch!= "download") { kindwatch = prompt("please enter on of : online, download"); } } kindwatchfun(); var numser = prompt("How many series have you watched on our website?") var numserfun = function () { var output=''; for (var i=0 ; i<numser; i++) { output = output + "<img src='https://money-h.com/picture//fin-will_1/how-to-encourage-someone-in-3-steps.jpg' width=50px; />" } return output; } var result = numserfun(); document.write(result);*/ let userName = prompt('what is your name?'); alert('hi'+userName+'for our web site' ); let location = prompt('where the most place in jordan think to vist?'); alert('It is a good option that you are considering a visit'+location+' It is a nice place for entertainment I think you can ask me to go with you '+userName ); let food = prompt('What is your favorite food?'); alert('You must try the' + location + 'in the Jordanian way, it is very tasty' ); let souv = prompt('What will you take from Jordan as a souvenir?'); alert('It is agood choose' + souv+'You must take a picture of the Jordanian shemagh, it will look beautiful on you and you will not forget this experience' ); var userName = prompt('what is your name');
import Store from "./Store"; import _ from "lodash"; import * as t from "@babel/types"; import { appendParams, getEntryIdentifier, getExpressionIdentifier, isValidExpression, isArrayValue } from "./util"; const getArrayItems = ({ elements }) => _.map(elements, ({ value }) => value); const propVisitor = { AssignmentExpression(path, state) { const identifier = getExpressionIdentifier(path); const right = _.get(path, "node.right"); if (!state.hasEntry(identifier)) return; /** defaultParams is declared */ if (isValidExpression(path, ["defaultParams"]) && isArrayValue(right)) { /** [TODO] Should double check if it's string, object or array before assuming it's an object */ state.addParams(identifier, right.elements); // console.log('getENTRIES --', state.entries) // console.log("identifier --->", state.entries.greet.params[0][0].value); path.remove(); return; } } }; const entryVisitor = { "Class|Function": (path, state) => { /** Set the function identifier as an entry */ // if (!isReactComponent(path)) return; state.createEntry(getEntryIdentifier(path), path); } }; export default () => { return { manipulateOptions: (opts, parserOptions) => { parserOptions.plugins.push("classProperties"); parserOptions.plugins.push("jsx"); parserOptions.plugins.push("objectRestSpread"); }, pre() { this.store = new Store(); }, visitor: { Program(programPath, { opts }) { // console.log("programPath -->", programPath); // programPath.traverse(importVisitor, this.store); // if (!this.store.hasImport) return; programPath.traverse(entryVisitor, this.store); programPath.traverse(propVisitor, this.store); // console.log('mqdlsfkjfqdmlj', this.store.getEntries()) appendParams(this.store.getEntries(), opts); } } }; };
$(".btn-success, .linka").on("click", function (event) { closeNav(); if($(this).attr('href').includes('#')) { event.preventDefault(); var id = $(this).attr('href'), top = $(id).offset().top; $('body,html').animate({scrollTop: top}, 800); } }); $('.services-block').click(function() { let collapsed = $(this).find('.plus-minus-toggle').hasClass('collapsed'); if(!$('div').hasClass('collapsing')) { $('.plus-minus-toggle').addClass('collapsed'); if(collapsed) { $(this).find('.plus-minus-toggle').removeClass('collapsed'); } else { $(this).find('.plus-minus-toggle').addClass('collapsed'); } } }) function openNav() { $("#Sidenav").css('width', '100%'); } function closeNav() { $("#Sidenav").css('width', '0px'); } function ajax() { let mail = { name: $('#name').val(), email: $('#email').val(), message: $('#message').val() }; fetch('mail.php', { method: 'post', body: JSON.stringify(mail) }).then(res=>res.json()) .then(res => console.log(res)); }
var passport = require('passport'); var LdapStrategy = require('passport-ldapauth').Strategy; var User = require('../models/user'); var Corpus = require('../models/corpus'); var fs = require('fs'); var path = require('path'); var os = require('os'); module.exports = function(app){ passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.findById(id, function (err, user) { done(err, user); }); }); passport.use(new LdapStrategy({ server: { url: 'ldaps://ldap.rit.edu', searchBase: 'ou=people,dc=rit,dc=edu', searchFilter: '(uid={{username}})' } }, function(user, done){ User.find({ dce: user.uid }).limit(1).exec(function(err, users){ if(users.length === 0) { User.create({ dce: user.uid, name: user.cn }, function(err, user){ var files = ['1928 News article', '2015 News article', 'My Bondage and My Freedom excerpt', 'Romeo and Juliet excerpt', 'The Raven', 'Tom Sawyer excerpt', '310 DementiaBank1', '310 DementiaBank2', '310 DementiaBank3', '310 DementiaBank4', '470 Raleigh', '470 Lennox', '470 Austen', '470 Doyle', '310 Very-Formal', '310 Semi-Formal', '310 Semi-Informal', '310 Very-Informal']; files.forEach(function(file) { var corpusPath = path.join('dirname', '../assets/corpora/', file); fs.readFile(corpusPath, function(err,data) { if(err) { console.log(err); } var corpus = { user_id: user._id, contents: data, title: file, fileSize: 0, fileName: file, fileType: 'plaintext' }; Corpus.create(corpus, function(err, c) { }); }); }); done(null, user); }); }else { done(null, users[0]); } }); })); app.post('/api/login', passport.authenticate('ldapauth'), function(req, res) { res.send({user: req.user}); }); app.get('/api/logged_in', function(req, res){ if(req.user) { res.send({loggedIn: true, user: req.user }); }else{ res.send({loggedIn: false}); } }); app.post('/api/logout', function(req, res){ req.logout(); res.send({}); }); }
class Bookmarks { constructor(){ this._data = { _: this._newBookmNode() }; this._size = 0; } _newBookmNode(){ return new Samples(ConfigMgr.get('SamplesDirectory')); } empty(){ return (this._size===0); } size(){ return this._size; } sort(){ let bkeys = Object.keys(this._data); let _self = this; bkeys.forEach((label)=>{ _self._data[label].sort(); }); } getByIndex(index){ let keys = Object.keys(this._data); let fIndex = -1; let fLabel = '_'; let fObj = null; let totalCount = 0; for(let i=0; i<keys.length; i++){ fObj = this._data[keys[i]]; totalCount += this._data[keys[i]].size(); if(index < totalCount){ fIndex = index - (totalCount-this._data[keys[i]].size()); fLabel = keys[i]; break; } } if(fIndex===-1) return null; let _return = { index: fIndex, label: fLabel, smpobj: fObj.get(fIndex) }; if(!_return.smpobj) return null; return _return; } printIndexedList(printFn){ let keys = Object.keys(this._data); let printLabels = keys.length>1; let index=0; printFn(''); for(let i=0; i<keys.length; i++){ if(this._data[keys[i]].empty()) continue; if(printLabels){ if(keys[i]==='_') printFn('Unlabeled:'); else printFn(keys[i]+':'); } this._data[keys[i]].forEach((v)=>{ printFn(' ' + (index+1) + ') ' + v.base );//+ ' [ '+v.rel_path+' ] '); index++; }); printFn(''); } } add(elmt,label){ if(!_.isString(label)) label='_'; if(!this._data[label]) this._data[label]=this._newBookmNode(); if(this._data[label].add(elmt,true /*no clone*/)===true){ this._size++; return true; } return false; } remove(elmt,label){ if(!_.isString(label)) label='_'; if(!this._data[label]) return false; return this._data[label].remove(elmt); //boolean } cloneStructure(){ let newBookm = new this.constructor(); this.forEach((value,index,label)=>{ newBookm.add(value,label); }); return newBookm; } cloneSubStructure(label){ let newBookm = new this.constructor(); if(!this._data[label]){ return newBookm; } this.forEach(label,(value)=>{ newBookm.add(value); }); return newBookm; } forEach(label,cb){ if(_.isString(label)){ this._forEachValues(label, cb, 0/*index*/); return; } cb=label; this._forEachAll(cb); } _forEachValues(label,cb,index){ let diffLb=true; this._data[label].forEach((value)=>{ cb(value,index,label,diffLb); diffLb=false; index++; }); return index; } _forEachAll(cb){ let bkeys = Object.keys(this._data); let index=0; bkeys.forEach((label)=>{ index=this._forEachValues(label,cb,index); }); } fromJson(jsondata){ let keys = Object.keys(jsondata.collection); for(let i=0; i<keys.length; i++){ if(jsondata.collection[keys[i]].length===0) continue; jsondata.collection[keys[i]].forEach((v)=>{ let phi = new PathInfo(); phi.fromJson(v); this.add(phi,keys[i]); }); } } toJson(){ let jsondata = { size:this._size, collection:{} }; this.forEach((value,index,label,diffLb)=>{ if(!_.isObject(value)) return; if(diffLb===true) jsondata.collection[label]=[]; jsondata.collection[label].push(value.toJson()); }); return jsondata; } } module.exports = Bookmarks;
/* @flow */ import { Meteor } from 'meteor/meteor' import { check } from 'meteor/check' import WorkCollection from './../lib/collection.js' Meteor.publish('writings', () => { return WorkCollection.find() }) Meteor.publish('writing', (url: string) => { check(url, String) return WorkCollection.find({url}) })
// @flow import { LOG_PLOG, UPDATE_PLOGS, SET_CURRENT_USER, SET_PREFERENCES} from './actionTypes'; type Location = { lat: number, lng: number, name: ?string } type PlogInfo = { location: Location, when: Date, trashType: string[], activityType: string, groupType: string, plogPhotos: object[], }; type Preferences = { shareActivity: boolean, }; /** * @typedef {Object} PlogInfo * @property {Location} location * @property {} */ export const logPlog = (plogInfo: PlogInfo) => ({ type: LOG_PLOG, payload: plogInfo }); export const updatePlogs = (plogs: PlogInfo[]) => ({ type: UPDATE_PLOGS, payload: { plogs, }, }); export const setCurrentUser = (user) => ({ type: SET_CURRENT_USER, payload: { user, }, }); export const setPreferences = (preferences: Preferences) => ({ type: SET_PREFERENCES, payload: { preferences, } }); export default { logPlog, updatePlogs, setCurrentUser, };
import React from "react"; import 'bootstrap/dist/css/bootstrap.css'; import './collage.css'; import work1 from './imgs/work1.jpg'; import work4 from './imgs/work4.gif'; import work5 from './imgs/work5.gif'; import work8 from './imgs/work8.gif'; class WorkCollage extends React.Component{ constructor(props){ super(props) this.state = { img:"", imgKey:{ "work11":work1, "work14":work4, "work15":work5, "work18":work8, } } } componentDidMount(){ this.setState({ img:this.props.img }) } render(){ return( <React.Fragment> <div className="container"> <div className="container float-left col-md-3 nopadding imgs"> <img src={this.state.imgKey[this.state.img]} className="size rounded"></img> </div> </div> </React.Fragment> ); } } export default WorkCollage;
// NPM files import React, { useEffect } from "react"; import OrderReducer from "./OrderReducer"; import { useContext, useReducer } from "react"; //script import STORAGE_KEY from "../scripts/storageKey"; // const STORAGE_KEY = process.env.REACT_APP_ORDER_API; const OrderContext = React.createContext(null); export function OrderProvider(props) { // Global state const [orders, dispatch] = useReducer(OrderReducer, loadOrder(STORAGE_KEY)); useEffect(() => saveOrder(STORAGE_KEY, orders), [orders]); return ( <OrderContext.Provider value={{ orders, dispatch }}> {props.children} </OrderContext.Provider> ); } export function useOrder() { const context = useContext(OrderContext); return context; } function loadOrder(key) { return JSON.parse(sessionStorage.getItem(key)); } function saveOrder(key, orders) { sessionStorage.setItem(key, JSON.stringify(orders)); }
function arrayEqualValues(arr) { let res = true; arr.forEach((element) => { if (element !== arr[0]) res = false; }); return res; } // arr = [2, 2, 2, 2]; // console.log(arrayEqualValues(arr)); module.exports = arrayEqualValues;
class Node { constructor(value, nextNode) { this.value = value; this.nextNode = nextNode; } } class Stack { constructor() { this.top = null; } push(value) { console.log("PUSH"); let node = new Node(value, this.top); this.top = node; this.print(); } pop() { console.log("POP"); let value = null; if (this.top) { value = this.top.value; this.top = this.top.nextNode; } this.print(); return value; } print() { let ptr = this.top; while (ptr) { console.log(ptr.value); ptr = ptr.nextNode; } console.log("---"); } } let stack = new Stack(); stack.push(1); stack.push(2); stack.push(3); stack.push(4); stack.pop(); stack.pop(); stack.pop(); stack.pop(); stack.pop();
/** * Created by 123 on 2017/8/16. */ $(function () { $(".tabNav li").delegate("a","click",function(){ var link = $(this).attr("data-link"); $(this).parent().addClass("active").siblings().removeClass("active"); $("article").hide(); if(link == "#fahuo"){ if($("#fahuo section").length != 1){ $("#fahuo section.nullOrder").hide(); $("#fahuo section.order").show(); } } $(link).show(); }); $(".look").on("click",function () { $("article").hide(); $("#order").show(); }); $(".cancle").click(function(){ $(this).parent().parent().parent().remove(); if($("#fukuan section").length == 1){ $("#fukuan").find(".noFukuan").show(); } }); // 请求物流信息 var res={"status":"3","message":"","errCode":"0","data":[{"time":"收件时间2017-08-10 17:10","context":"已收件 收件人:王光 "},{"time":"发出时间:2017-08-11 17:59","context":"已从聊城徐营镇发出"},{"time":"到达时间:2017-08-11 18:11","context":"已到达济南中转部"},{"time":"发出时间2017-08-12 07:33","context":"已从济南中转部发出"},{"time":"到达时间:2017-08-12 16:47","context":"已到达柘城胡襄镇"},{"time":"派件时间:2017-08-12 16:47","context":"正在派件,业务员联系电话:0370-73333338"}],"html":"","mailNo":"7151900624","expTextName":"圆通快递","expSpellName":"yuantong","update":"1362656241","cache":"186488","ord":"ASC"}; var html="<h3 class='pd15'>订单跟踪</h3>"; for(var i=0;i<res.data.length;i++){ html +="<p class='mt10 mb10'>您的快件【<span>"+res.mailNo+"</span>】<span class='name pl15'>"+res.data[i].context+"</span>,<span class='time'>"+res.data[i].time+"</span></p>" } $("#wuliu").append(html); });
const commonFunction = require("../functions/commonFunctions"); const privacyModel = require("../models/privacy") module.exports = { delete: function (id, req) { return new Promise(function (resolve, reject) { req.getConnection(function (err, connection) { connection.query("SELECT * FROM audio WHERE audio_id = ?", [id], function (err, results, fields) { const audio = JSON.parse(JSON.stringify(results))[0]; connection.query("DELETE FROM audio WHERE audio_id = ?", [id], function (err, results, fields) { if (err) resolve(false) if (results) { commonFunction.deleteImage(req,'',"","",audio); connection.query("DELETE FROM comments WHERE type = 'audio' && id = ?", [id], function (err, results, fields) { }) connection.query("DELETE FROM favourites WHERE type = 'audio' && id = ?", [id], function (err, results, fields) { }) connection.query("DELETE FROM likes WHERE type = 'audio' && id = ?", [id], function (err, results, fields) { }) connection.query("DELETE FROM recently_viewed WHERE type = 'audio' && id = ?", [id], function (err, results, fields) { }) connection.query("DELETE FROM ratings WHERE type = 'audio' && id = ?", [id], function (err, results, fields) { }) connection.query("DELETE FROM notifications WHERE (object_type = 'audio' && object_id = ?) OR (subject_type = 'audio' && object_id = ?)", [id,id], function (err, results, fields) { }) connection.query("DELETE FROM reports WHERE type = ? AND id = ?", ["audio", audio.custom_url], function (err, results, fields) { }) resolve(true) } else { resolve(""); } }) }) }) }); }, getAudios: function (req, data) { return new Promise(function (resolve, reject) { req.getConnection(async function (err, connection) { let condition = [] let owner_id = 0 if (req.user && req.user.user_id) { owner_id = parseInt(req.user.user_id) } let customSelect = "" if (data.orderby == "random") { customSelect = ' FLOOR(1 + RAND() * audio.audio_id) as randomSelect, ' } let customUrlAudio = "" // if(!data.myContent){ customUrlAudio = "audio.custom_url as vcustom_url," // } let isAllowedView = req.levelPermissions["audio.view"] && req.levelPermissions["audio.view"].toString() == "2"; let checkPlanColumn = ' CASE WHEN '+(isAllowedView ? 1 : 0)+' = 1 THEN 1 WHEN audio.owner_id = '+owner_id+' THEN 1 WHEN member_plans.price IS NULL THEN 1 WHEN mp.price IS NULL THEN 0 WHEN `member_plans`.price <= mp.price THEN 1' checkPlanColumn += ' WHEN `member_plans`.price > mp.price THEN 2' checkPlanColumn += ' ELSE 0 END as is_active_package, ' let sql = 'SELECT '+checkPlanColumn+customUrlAudio+'audio.*,'+customSelect+'likes.like_dislike,userdetails.displayname,userdetails.username,userdetails.verified,IF(audio.image IS NULL || audio.image = "","' + req.appSettings['audio_default_photo'] + '",audio.image) as image,IF(userdetails.avtar IS NULL || userdetails.avtar = "",(SELECT value FROM `level_permissions` WHERE name = \"default_mainphoto\" AND type = \"member\" AND level_id = users.level_id),userdetails.avtar) as avtar,favourites.favourite_id FROM audio ' condition.push(req.user ? req.user.user_id : 0) sql += ' LEFT JOIN `member_plans` ON `member_plans`.member_plan_id = REPLACE(`audio`.view_privacy,"package_","") LEFT JOIN ' sql += ' `subscriptions` ON subscriptions.id = audio.owner_id AND subscriptions.owner_id = ? AND subscriptions.type = "user_subscribe" AND subscriptions.status IN ("active","completed") LEFT JOIN `member_plans` as mp ON mp.member_plan_id = `subscriptions`.package_id ' if (data.channel_id) { sql += " LEFT JOIN channelaudio ON channelaudio.audio_id = audio.audio_id AND channel_id = " + data.channel_id } sql += ' LEFT JOIN users on users.user_id = audio.owner_id LEFT JOIN userdetails on users.user_id = userdetails.user_id LEFT JOIN likes ON likes.id = audio.audio_id AND likes.type = "audio" AND likes.owner_id = ' + owner_id + ' LEFT JOIN favourites ON (favourites.id = audio.audio_id AND favourites.type = "audio" AND favourites.owner_id = ' + owner_id + ') ' let orderbyField = false if (data.recentlyViewed) { condition.push(parseInt(data.owner_id)) orderbyField = " recently_viewed.creation_date DESC " sql += " INNER JOIN recently_viewed ON audio.audio_id = recently_viewed.id AND recently_viewed.owner_id = ? AND recently_viewed.type='audio' " } if (data.myrated) { orderbyField = " ratings.creation_date DESC " condition.push(parseInt(data.owner_id)) sql += " INNER JOIN ratings ON audio.audio_id = ratings.id AND ratings.owner_id = ? AND ratings.type='audio' " } if (data.myfav) { orderbyField = " f.creation_date DESC " condition.push(parseInt(data.owner_id)) sql += " INNER JOIN favourites as f ON audio.audio_id = f.id AND f.owner_id = ? AND f.type='audio' " } if (data.mylike) { orderbyField = " l.creation_date DESC " condition.push(parseInt(data.owner_id)) sql += " INNER JOIN likes as l ON audio.audio_id = l.id AND l.owner_id = ? AND l.type='audio' AND l.like_dislike = 'like' " } if (data.mydislike) { orderbyField = " l.creation_date DESC " condition.push(parseInt(data.owner_id)) sql += " INNER JOIN likes as l ON audio.audio_id = l.id AND l.owner_id = ? AND l.type='audio' AND l.like_dislike = 'dislike' " } if (data.mycommented) { orderbyField = " comments.creation_date DESC " condition.push(parseInt(data.owner_id)) sql += " INNER JOIN comments ON audio.audio_id = comments.id AND comments.owner_id = ? AND comments.type='audio' " } sql += " WHERE 1=1 " await privacyModel.checkSQL(req,'audio','audio','audio_id').then(result => { if(result){ sql += " AND ( "+result+" )" } }) sql += " AND users.active = 1 AND users.approve = 1 " if (!data.myContent) { if (data.audioview) { if(!req.user || req.levelPermissions['audio.view'] != 2) sql += " AND audio.approve = 1 " }else{ sql += ' AND audio.search = 1 AND audio.approve = 1 ' } } sql += " AND audio.title IS NOT NULL AND audio.title != '' " if (data.title) { condition.push(data.title.toLowerCase()) sql += " AND LOWER(audio.title) LIKE CONCAT('%', ?, '%')" } if (data.owner_id && !data.myCustom) { condition.push(parseInt(data.owner_id)) sql += " AND audio.owner_id = ?" } if (data.is_featured) { condition.push(parseInt(data.is_featured)) sql += " AND audio.is_featured = ?" } if (data.is_not_hot) { condition.push(1) sql += " AND audio.is_hot != ?" } if (data.is_not_featured) { condition.push(1) sql += " AND audio.is_featured != ?" } if (data.not_audio_id) { condition.push(parseInt(data.not_audio_id)) sql += " AND audio.audio_id != ?" } if (data.is_not_sponsored) { condition.push(1) sql += " AND audio.is_sponsored != ?" } if (data.is_hot) { condition.push(parseInt(data.is_hot)) sql += " AND audio.is_hot = ?" } if (data.is_sponsored) { condition.push(parseInt(data.is_sponsored)) sql += " AND audio.is_sponsored = ?" } if (data.offtheday) { condition.push(data.offtheday) sql += " AND audio.offtheday = ?" } if (data.custom_url) { condition.push(data.custom_url) sql += " AND audio.custom_url =?" } if(data.user_home_content){ sql += " AND view_privacy LIKE 'package_%'"; } //if (!data.myContent) { sql += " GROUP BY audio.audio_id " // } if (data.orderby == "random") { sql += " ORDER BY randomSelect DESC " } else if (orderbyField) { sql += " ORDER BY " + orderbyField } else if (data.orderby) { sql += " ORDER BY " + data.orderby } else { sql += " ORDER BY audio.audio_id desc " } if (data.limit) { condition.push(data.limit) sql += " LIMIT ?" } if (data.offset) { condition.push(data.offset) sql += " OFFSET ?" } connection.query(sql, condition, function (err, results, fields) { if (err) resolve(err) if (results) { const level = JSON.parse(JSON.stringify(results)); const audios = [] if(level && level.length){ level.forEach(audio => { delete audio.password if(audio.is_active_package != 1) delete audio.audio_file if(!req.allowPeaks){ delete audio.peaks; } audios.push(audio) }) resolve(audios) }else{ resolve(level); } } else { resolve(""); } }) }) }) }, userAudioUploadCount: function (req, res) { return new Promise(function (resolve, reject) { req.getConnection(function (err, connection) { connection.query('SELECT COUNT(audio_id) as totalAudios FROM audio WHERE owner_id = ?', [req.user.user_id], function (err, results, fields) { if (err) reject(err) if (results) { const audio = JSON.parse(JSON.stringify(results)); resolve(audio[0]); } else { resolve(""); } }) }) }); }, findByCustomUrl: function (id, req,allowData = false) { return new Promise(function (resolve, reject) { req.getConnection(function (err, connection) { connection.query('SELECT * FROM audio WHERE custom_url = ?', [id], function (err, results, fields) { if (err) reject(false) if (results) { const audio1 = JSON.parse(JSON.stringify(results)); let audio = audio1[0] if (!allowData && audio) { delete audio['password'] } resolve(audio); } else { resolve(false); } }) }) }); }, }
var config = { src: '../src/', dist: '../dist/' } var gulp = require('gulp'), minifycss = require('gulp-minify-css'), concat = require('gulp-concat'), rev = require('gulp-rev'), revCollector = require('gulp-rev-collector'), changed = require('gulp-changed'), htmlReplace = require('gulp-html-replace'), fs = require('fs') /** * 当前项目js内容比较少,我就打算简化gulp处理: * * 1、 做一个copy * 2、 公共html替换 * 3、 CSS压缩合并 */ gulp.task('copy', () => { var exclode = '!' + config.src+'/css/**/*.*'; return gulp.src([config.src + '**/*.*', exclode]) .pipe(gulp.dest(config.dist)) }) //将css文件夹下的css压缩且合并 gulp.task('css', function() { return gulp.src(config.src + 'css/**/*.css') .pipe(concat('style.css')) .pipe(minifycss()) .pipe(gulp.dest(config.dist+"css")); }); gulp.task('htmlReplace', ['copy','css'], () => { let folds = 'blog request service'.split(' ') let options = { header: 'tpl/common/header.tpl', nav: 'tpl/common/nav.tpl', footer: 'tpl/common/footer.tpl', contact:'tpl/common/contact.tpl', } for (var i in options) { options[i] = fs.readFileSync(config.src + options[i], 'utf-8') } folds.forEach(fold => { let files = fs.readdirSync(config.src + fold) files.every(file => { if (file.indexOf('.html') > -1) { var fileName = file.replace('.html', ''), key = fold + '-' + fileName, filePath = config.src + 'tpl/' + fold + '/' + fileName + '.tpl' fs.stat(filePath, err => { err.code !== 'ENOENT' && (options[key] = fs.readFileSync(filePath)) }) } }) }) options["css"] = 'css/style.css'; 'html tpl'.split(' ').every(item => { return gulp.src(config.src + '**/*.' + item) .pipe(htmlReplace(options)) .pipe(gulp.dest(config.dist)) }) //renderBlog() }) //监听文件是否修改 gulp.task('watch', () => { gulp.watch(config.src + '**/*.*', ['default']) }) // ------------- [ 临时给测试用的 ] ------------- const https = require("http"), url = require('url') //在构建完之后,生成blog详情页 function renderBlog(){ const href = 'http://dev.weintrade.com:8080/blogs/create/all', res = https.request(url.parse(href), result => {}) res.on('error', err => { console.log('has error', err) }) res.on('data', chunk => { console.log('request get data', chunk) }) res.on('end', () => { console.log('request end') }) res.end() } // ------------- [ 临时给测试用的 ] ------------- gulp.task('default', ['htmlReplace'])
const express = require('express'); const fs = require('fs'); const path = require('path'); const router = express.Router(); router.get('/', (req, res) => { res.json(`admin controller test - RESTful API Time:${new Date(Date.now()).toTimeString()}`); }); function _loadDir(dirpath) { return new Promise(((resolve) => { const route = path.resolve(process.cwd(), dirpath); fs.readdir(route, (_err, items) => resolve(items)); })); } function _loadFile(filePath) { return new Promise(((resolve) => { const route = path.resolve(process.cwd(), filePath); fs.readFile(route, 'utf8', (_err, data) => resolve(data)); })); } function _writeFile(filePath, content) { return new Promise(((resolve, reject) => { const route = path.resolve(process.cwd(), filePath); fs.writeFile(route, content, 'utf8', (err) => { if (!err) { return resolve(); } return reject(err); }); })); } router.get('/logs/all', async (req, res) => { const logFiles = await _loadDir('./logs/all'); const logFilesResp = []; for (let i = 0; i < logFiles.length; i++) { logFilesResp.push({ file: logFiles[i], url: `/admin/logs/all/${logFiles[i]}` }); } res.json(logFilesResp); }); router.get('/logs/all/:filename', async (req, res) => { const filename = req.params.filename; const file = await _loadFile(`./logs/all/${filename}`); res.send(file); }); router.get('/logs/error', async (req, res) => { const logFiles = await _loadDir('./logs/error'); const logFilesResp = []; for (let i = 0; i < logFiles.length; i++) { logFilesResp.push({ file: logFiles[i], url: `/admin/logs/error/${logFiles[i]}` }); } res.json(logFilesResp); }); router.get('/logs/error/:filename', async (req, res) => { const filename = req.params.filename; const file = await _loadFile(`./logs/error/${filename}`); res.send(file); }); // get config router.get('/config', async (req, res) => { const file = await _loadFile('./server/library/recipeSiteIndex.json'); res.send(file); }); // update config router.post('/config', async (req, res) => { const body = req.body; try { await _writeFile('./server/library/recipeSiteIndex.json', JSON.stringify(body)); // delete require.cache[require.resolve('recipeSiteIndex')]; res.status(204).send(); } catch (err) { res.send(err); } }); module.exports = router;
$(document).ready(function(){ $("#flip").click(function(){ $("#panel").slideToggle("slow") }); $("#flip2").click(function(){ $("#panel2").slideToggle("slow") }); $("#flip3").click(function(){ $("#panel3").slideToggle("slow") }); $("button").on("click", function(){ $(".overlay").addClass("active"); }); $(".tab-list").on("click", ".tab", function(e) { e.preventDefault(); $(".tab").removeClass("active"); $(".tab-content").removeClass("show"); $(this).addClass("active"); $($(this).attr("href")).addClass("show"); }); });
function oldOrderSave() { xmlrb = new XMLHttpRequest(); xmlrb.onreadystatechange = function() { if (xmlrb.readyState == 4 && xmlrb.status == 200) { location.reload(); } } oid = -1; try { oid = document.getElementById("OrderID").value; } catch (error) { oid = 0; } xmlrb.open("POST", "/araujo_tc/getdata/oldSaveOrder.php"); // This is required for PHP in order to populate $_POST xmlrb.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlrb.send("VendorID=" + document.getElementById("VendorID").value + "&RestaurantID=" + document.getElementById("RestaurantID").value + "&OrderDate=" + document.getElementById("OrderDate").value + "&DueDate=" + document.getElementById("DueDate").value + "&OrderID=" + oid); } function OrderSave() { xmlrb = new XMLHttpRequest(); xmlrb.onreadystatechange = function() { if (xmlrb.readyState == 4 && xmlrb.status == 200) { location.reload(); } } oid = -1; try { oid = document.getElementById("OrderID").value; } catch (error) { oid = 0; } xmlrb.open("POST", "/araujo_tc/getdata/SaveOrder.php"); // This is required for PHP in order to populate $_POST xmlrb.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlrb.send("VendorID=" + document.getElementById("VendorID").value + "&RestaurantID=" + document.getElementById("RestaurantID").value + "&OrderDate=" + document.getElementById("OrderDate").value + "&DueDate=" + document.getElementById("DueDate").value + "&OrderID=" + oid); } function orderUpdate() { xmlrb = new XMLHttpRequest(); xmlrb.onreadystatechange = function() { if (xmlrb.readyState == 4 && xmlrb.status == 200) { location.reload(); } } oid = -1; try { oid = document.getElementById("OrderID").value; } catch (error) { oid = 0; } xmlrb.open("POST", "/araujo_tc/getdata/UpdateOrder.php"); // This is required for PHP in order to populate $_POST xmlrb.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlrb.send("VendorID=" + document.getElementById("VendorID").value + "&RestaurantID=" + document.getElementById("RestaurantID").value + "&OrderDate=" + document.getElementById("OrderDate").value + "&DueDate=" + document.getElementById("DueDate").value + "&OrderID=" + oid); } function orderClear() { xmlrb = new XMLHttpRequest(); xmlrb.onreadystatechange = function() { if (xmlrb.readyState == 4 && xmlrb.status == 200) { location.reload(); } } xmlrb.open("POST", "/araujo_tc/getdata/ClearProductToOrder.php"); // This is required for PHP in order to populate $_POST xmlrb.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlrb.send(""); } function addProduct(id) { xmlrb = new XMLHttpRequest(); xmlrb.onreadystatechange = function() { if (xmlrb.readyState == 4 && xmlrb.status == 200) { location.reload(); } } xmlrb.open("POST", "/araujo_tc/getdata/AddProductToOrder.php"); // This is required for PHP in order to populate $_POST xmlrb.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlrb.send("ProductID=" + document.getElementById("ProductID").value + "&UnitID=" + document.getElementById("UnitID").value + "&Quantity=" + document.getElementById("Quantity").value + "&UnitPrice=" + document.getElementById("UnitPrice").value + "&ExtPrice=" + document.getElementById("ExtPrice").value + "&Comment=" + document.getElementById("Comment").value); } function removeProduct(id) { xmlrb = new XMLHttpRequest(); xmlrb.onreadystatechange = function() { if (xmlrb.readyState == 4 && xmlrb.status == 200) { location.reload(); } } xmlrb.open("POST", "/araujo_tc/getdata/RemoveProductFromOrder.php"); // This is required for PHP in order to populate $_POST xmlrb.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlrb.send("ProductIndex=" + id + "&OrderID=" + document.getElementById("OrderID").value); } function saveProduct(id) { xmlrb = new XMLHttpRequest(); xmlrb.onreadystatechange = function() { if (xmlrb.readyState == 4 && xmlrb.status == 200) { location.reload(); } } xmlrb.open("POST", "/araujo_tc/getdata/SaveProductToOrder.php"); // This is required for PHP in order to populate $_POST xmlrb.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlrb.send("ProductID=" + document.getElementById("ProductID").value + "&UnitID=" + document.getElementById("UnitID").value + "&Quantity=" + document.getElementById("Quantity").value + "&UnitPrice=" + document.getElementById("UnitPrice").value + "&ExtPrice=" + document.getElementById("ExtPrice").value + "&Comment=" + document.getElementById("Comment").value + "&OrderID=" + document.getElementById("OrderID").value); } function orderEdit() { orderEditing = document.getElementById("OrderID").value; xmlra = new XMLHttpRequest(); xmlra.onreadystatechange = function() { if (xmlra.readyState == 4 && xmlra.status == 200) { var responseStr = xmlra.response; var splitArry = xmlra.response.split("/-/"); document.getElementById("VendorID").value = splitArry[0]; document.getElementById("OrderDate").value = splitArry[1]; document.getElementById("OrderID").value = splitArry[2]; document.getElementById("DueDate").value = splitArry[3]; document.getElementById("RestaurantID").value = splitArry[4]; location.reload(true); } } xmlra.open("GET", "../../getdata/GetOrderData.php?id=" + orderEditing); xmlra.send(); } function calculateProductPrice() { document.getElementById("ExtPrice").value = document.getElementById("UnitPrice").value * document.getElementById("Quantity").value }
import * as APIUtils from '../utils/APIUtils' import {FETCH_CATEGORIES_FAILURE, FETCH_CATEGORIES_REQUEST, FETCH_CATEGORIES_SUCCESS} from './actionTypes'; const fetchCategories = () => dispatch => { dispatch({type: FETCH_CATEGORIES_REQUEST}); return APIUtils.fetchCategories().then( ({data}) => dispatch({ type: FETCH_CATEGORIES_SUCCESS, data: data.categories } ), error => dispatch({ type: FETCH_CATEGORIES_FAILURE, error: error.message }), ); }; const shouldFetchCategories = ({categories}) => !categories || ( !categories.isFetching && !categories.error && !categories.data.length); export const fetchCategoriesIfNeeded = () => (dispatch, getState) => shouldFetchCategories(getState()) ? dispatch(fetchCategories()) : Promise.resolve();
import React from "react"; import "./Accommodation.css"; import "bootstrap/dist/css/bootstrap.min.css"; import AccommodationHeader from "./AccommodationHeader/AccommodationHeader"; import AccommodationHost from "./AccommodationHost/AccommodationHost"; import Footer from "./CustomFooter/CustomFooter"; const Accommodation = () => { return ( <div className="acc"> <AccommodationHeader /> <AccommodationHost /> <Footer /> </div> ); }; export default Accommodation;
import React, { Component } from 'react'; class Header extends Component { render() { return ( <header> <div className="img-hold"> <img src={require("./img/page-heder.png")} alt="logo" /> </div> </header> ); } } export default Header;
let challangeService = require("../../models/challange/challangeService"); module.exports = async function (req, res, next) { var challangeExist = await challangeService.findOne({ expiryDate: { $lte: req.body.startDate }, }); if (challangeExist) return res .status(400) .send({ error: "Challange in this date range already exist" }); req.isValidated = true; next(); };
import React from "react"; import BaseComponent from "core/BaseComponent/BaseComponent"; import { withStyles, Button, Grid, IconButton, Typography, TextField, Checkbox, FormLabel, } from "@material-ui/core"; import { sensitiveStorage } from "core/services/SensitiveStorage"; import { DayOfWeek } from "core/Enum"; import RCSTable from "views/general/RCSTable"; import moment from "moment"; import { ClassStatus } from "core/Enum"; import { ClassStatusName } from "core/Enum"; import GridContainer from "components/Grid/GridContainer"; import { OpenInNew as OpenIcon } from "@material-ui/icons"; class StudentDetail extends BaseComponent { constructor(props) { super(props); this.teacherId = sensitiveStorage.getTeacherId(); } _onChangeDiemDanh = (classSchedule) => { const { classOfTeacher, studentId } = this.props; this.ajaxGet({ url: `/api/teacher/ChangeRollCall?classScheduleId=${classSchedule.id}&studentId=${studentId}`, success: (r) => { classOfTeacher.classSchedules.forEach((cs) => { if (cs.id == classSchedule.id) { let rc = cs.rollCalls.filter( (i) => i.studentId == studentId && i.classScheduleId == classSchedule.id ); if (rc.length > 0) { rc[0].isActive = r.data.isActive; } else { cs.rollCalls.push(r.data); } } }); this.setState({}); this.success(r.messages[0]); }, unsuccess: (r) => { this.error(r.messages[0]); }, }); }; renderBody() { const { classOfTeacher, studentId } = this.props; const { classes } = this.props; const sobuoidahoc = classOfTeacher.classSchedules.filter((cs) => { return cs.status != ClassStatus.schedule; }).length; const sobuoidihoc = classOfTeacher.classSchedules.filter( (cs) => cs.status != ClassStatus.schedule && cs.rollCalls.some((rc) => rc.studentId == studentId && rc.isActive) ).length; console.log("student detail"); return ( <div className={classes.root}> <div className={classes.content}> <Grid container> <Grid item xs={12}> <FormLabel> Tổng số buổi: {classOfTeacher.classSchedules.length} </FormLabel> </Grid> <Grid item xs={6}> <FormLabel>Đi học: {sobuoidihoc}</FormLabel> </Grid> <Grid item xs={6}> <FormLabel>Vắng mặt: {sobuoidahoc - sobuoidihoc}</FormLabel> </Grid> </Grid> <RCSTable data={classOfTeacher.classSchedules} head={(Cell) => ( <React.Fragment> <Cell>Ngày học</Cell> <Cell>Trạng thái</Cell> <Cell>Thời gian bắt đầu</Cell> <Cell>Thời gian kết thúc</Cell> <Cell>Điểm danh</Cell> </React.Fragment> )} body={(row, Cell) => ( <React.Fragment> <Cell>{moment(row.datetime).format("DD/MM/yyyy")}</Cell> <Cell>{ClassStatusName[row.status]}</Cell> <Cell> {row.startDatetime ? moment(row.startDatetime).format("HH:mm") : null} </Cell> <Cell> {row.endDatetime ? moment(row.endDatetime).format("HH:mm") : null} </Cell> <Cell className={classes.celCenter}> <Checkbox checked={row.rollCalls.some( (rc) => rc.studentId == studentId && rc.isActive )} onClick={() => { this._onChangeDiemDanh(row); }} /> </Cell> </React.Fragment> )} /> </div> </div> ); } } export default withStyles({ root: {}, title: { padding: "15px 30px 10px", borderBottom: "1px solid #ccc", textTransform: "uppercase", }, content: { padding: "10px 15px", }, })(StudentDetail);
// Evolutility-UI-React :: global_var.js // Using window as a global variables holder // TODO: find better way // https://github.com/evoluteur/evolutility-ui-react // (c) 2017 Olivier Giulieri if (!window.evol) { window.evol = {} } export default function() { return window.evol }
import React, {Component} from 'react'; import './CreateTask1.css'; class CreateTask1 extends Component{ render() { return( <div className="task1-container"> <p>Title</p> <input style={{width:'100%',fontSize:'20px',minHeight:"50%"}} onChange={(event)=>this.props.addTitle(event.target.value)}></input> <p>Date</p> <div className="data1-container"> <div style={{width:'15%'}}> <p style={{color:'gray'}}>Day</p> <input style={{width:'100%',fontSize:'20px',minHeight:"40%"}} onChange={(event)=>this.props.addDay(event.target.value)}></input> </div> <div style={{width:'15%',marginLeft:'10%'}}> <p style={{color:'gray'}}>Month</p> <input style={{width:'100%',fontSize:'20px',minHeight:"40%"}} onChange={(event)=>this.props.addMonth(event.target.value)}></input> </div> <div style={{width:'15%',marginLeft:'10%'}}> <p style={{color:'gray'}}>Year</p> <input style={{width:'100%',fontSize:'20px',minHeight:"40%"}} onChange={(event)=>this.props.addYear(event.target.value)}></input> </div> </div> </div>) } } export default CreateTask1;
!function() { var view = '.swiper-container' var controller = { view: view, swiper: null, options: { pagination: { el: '.swiper-pagination' } }, init: function() { this.swiper = new Swiper(this.view) this.initPagenation() }, initPagenation() { var mySwiper = this.swiper portfolio1.onclick = function() { portfolioBar.className = 'bar state-1' mySwiper.slideTo(0, 500, false) } portfolio2.onclick = function() { portfolioBar.className = 'bar state-2' mySwiper.slideTo(1, 500, false) } portfolio3.onclick = function() { portfolioBar.className = 'bar state-3' mySwiper.slideTo(2, 500, false) } } } controller.init() }.call()
document.addEventListener('DOMContentLoaded', function() { // simple JS feature detection var className, html; html = document.documentElement; className = html.className.replace('no-js', 'js'); html.className = className; // off-canvas-navigation var toggle = document.getElementById('toggle'); toggle.addEventListener('click', function(e) { e.preventDefault(); var innerWrap = document.querySelector('.inner-wrap'); innerWrap.classList.toggle('is-open'); }); }); // Insert your JS MAGIC HERE :)
import React from 'react'; import {getCourseByName} from '../../../services/ref-data/course'; export let CourseManagerTableHeaderRow =()=>{ return ( <tr> <th scope="col" >#Seq</th> <th scope="col">Name</th> <th scope="col"></th> <th scope="col"></th> </tr> ); }; export let CourseManagerTableBodyRow = (props)=>{ return ( <tr onDoubleClick={()=>props.onDoubleClick(props.course.id)}> <th scope="row">{props.course.seqOrder}</th> <td>{props.course.name}</td> <td> <button type="button" onClick={()=>props.onDoubleClick(props.course.id)} className="btn btn-primary mobile-heading"> Edit </button> </td> <td> <button type="button" onClick={()=>props.onDelete(props.course.id)} className="btn btn-danger"> Delete</button> </td> </tr> ); };
'use strict'; var mongoose = require('mongoose'); var Schema = mongoose.Schema; var showSchema = new Schema({ date: { type: Date, required: true }, venue: String, bands: String, regBands: [{type: Schema.Types.ObjectId, ref: 'Bands'}], cost: Number }); module.exports = mongoose.model('Show', showSchema);
var models = require('../models'); var bluebird = require('bluebird'); module.exports = { messages: { get: function (req, res) { console.log("About to respond to Get"); models.messages.get(function(results) { res.json({results: results}); }); }, // a function which handles a get request for all messages post: function (req, res) { console.log(req.body); var username = req.body.username; var text = req.body.text; var roomname = req.body.roomname; //check if user exists models.users.get([req.body.username], function(results) { if (!results.length) { console.log("new user created"); models.users.post([req.body.username]); } }); var params = [text, username, roomname]; models.messages.post(params, function(results) { console.log(results) res.json(results); }); } // a function which handles posting a message to the database }, users: { // Ditto as above get: function (req, res) {}, post: function (req, res) { } } };
import React, { Component } from "react"; import _ from "lodash"; import moment from "moment"; import ApiService from "../../libs/ApiService"; import BlockUi from "react-block-ui"; import Router from "next/router"; import { Collapse } from "../page"; import ModalAlert, { BTN_ACTION_BACK, BTN_ACTION_OK } from "../modalAlert"; import { i18n, withTranslation } from "~/i18n"; import { formatNumber, numberOnly, GrThead } from "../invoices/edit/models/item"; import { async } from "q"; import GA from "~/libs/ga"; const Api = new ApiService(); const QTY_COLUMN_PATTERN = [ { data: "cnItemNo" }, { data: "invoiceItemNo" }, { data: "materialDescription" }, { data: "poNo" }, { data: "invoiceQty" }, { data: "invoiceAmount" }, { data: "cnQty" }, { data: "unit" }, { data: "unitPrice" }, { data: "cnAmount" }, { data: "currency" } ]; const PRICE_COLUMN_PATTERN = [ { data: "cnItemNo" }, { data: "invoiceItemNo" }, { data: "materialDescription" }, { data: "poNo" }, { data: "invoiceQty" }, { data: "invoiceAmount" }, { data: "unit" }, { data: "unitPrice" }, { data: "cnAmount" }, { data: "currency" } ]; const CREATE_TYPE_ENUMS = { QTY: "QTY", PRICE: "PRICE" }; class createCreditNoteStepFour extends Component { constructor(props) { super(props); this.toggleBlocking = this.toggleBlocking.bind(this); this.state = { blocking: false, allItems: [], vatRate: "", invoiceDetail: {}, entryDate: moment(), cnAmount: {}, cnRmnAmount: 0, taxTotal: {}, createErrMessage: "", fileAttachments: [], taxRateList: [], taxRateListItem: [], isChangeSubTotalTaxTotal: false, stepFourProp: {}, totalAmount: 0, isAlertModalVisible: false, alertModalAlertTitle: "", alertModalMsg: "", isTextOnly: true, buttonAlert: [] }; } toggleBlocking() { this.setState({ blocking: !this.state.blocking }); } async componentDidMount() { this.toggleBlocking(); await this.extractAllInvoiceItems( this.props.mainState.stepTwoProp.invoiceItems, this.props.mainState.stepTwoProp.rowSelected ); await this.calAll(); this.extractPurchaseItemByTaxRate(); //this.renderInvoiceItemTable(this.state.allItems); this.toggleBlocking(); } isChangeSubTotalTaxTotal = () => { if (!this.state.isChangeSubTotalTaxTotal) { this.setState({ isChangeSubTotalTaxTotal: true }); } }; handleAmountChange = e => { let input = event.target.value; let value = input.replace(".", ""); if (value == "" || isNaN(parseFloat(e.target.value))) { e.target.value = formatNumber(0, 2); this.state.cnAmount = formatNumber(0, 2); } else { this.state.cnAmount = parseFloat(e.target.value.replace(/,/g, "")); e.target.value = formatNumber( parseFloat(e.target.value.replace(/,/g, "")).toFixed(2), 2 ); } this.isChangeSubTotalTaxTotal(); this.calTotalAmount(); }; handleTaxTotalChange = e => { let input = event.target.value; let value = input.replace(".", ""); if (value == "" || isNaN(parseFloat(e.target.value))) { e.target.value = formatNumber(0, 2); this.state.taxTotal = formatNumber(0, 2); } else { this.state.taxTotal = parseFloat(e.target.value.replace(/,/g, "")); e.target.value = formatNumber( parseFloat(e.target.value.replace(/,/g, "")).toFixed(2), 2 ); } this.isChangeSubTotalTaxTotal(); this.calTotalAmount(); }; calTotalAmount = () => { const { cnAmount, taxTotal } = this.state; this.setState({ totalAmount: cnAmount + taxTotal }); }; extractAllInvoiceItems(invoiceItems, rowSelected) { let allItems = []; rowSelected.forEach(rowIndex => { allItems.push(invoiceItems[rowIndex - 1]); }); this.setState( { allItems: allItems }, () => { // this.renderInvoiceItemTable(this.state.allItems) } ); } extractPurchaseItemByTaxRate() { let purchaseItem = this.state.allItems; let taxRateList = []; let taxRateListItem = {}; purchaseItem.forEach(item => { if (taxRateList.includes(item.vatRate) == false) { taxRateList.push(item.vatRate); taxRateListItem[`tax${item.vatRate}`] = []; } taxRateListItem[`tax${item.vatRate}`] = [ ...taxRateListItem[`tax${item.vatRate}`], item ]; }); this.setState({ taxRateList, taxRateListItem }); } generateRowTableForTax(taxItems) { if (this.props.mainState.stepTwoProp.createType === CREATE_TYPE_ENUMS.QTY) { if (taxItems.length > 0) { return _.map( taxItems, ( { materialDescription, purchaseOrderExternalId, quantity, creditNoteQuantity, itemSubTotal, unitPrice, creditNoteAdjustedSubtotal, currency }, index ) => ( <tr> <td>{index + 1}</td> <td>{this.props.mainState.stepTwoProp.rowSelected[index]}</td> <td>{materialDescription}</td> <td>{purchaseOrderExternalId}</td> <td>{this.formatQtyNumber(quantity.initial)}</td> <td>{this.formatPriceNumber(itemSubTotal)}</td> <td>{this.formatQtyNumber(creditNoteQuantity.initial)}</td> <td>{quantity.unit}</td> <td>{this.formatPriceNumber(unitPrice)}</td> <td>{this.formatPriceNumber(creditNoteAdjustedSubtotal)}</td> <td>{currency}</td> </tr> ) ); } else { return ( <div> <center>No Item Found</center> </div> ); } } else if ( this.props.mainState.stepTwoProp.createType === CREATE_TYPE_ENUMS.PRICE ) { if (taxItems.length > 0) { return _.map( taxItems, ( { materialDescription, purchaseOrderExternalId, quantity, itemSubTotal, unitPrice, creditNoteAdjustedSubtotal, currency }, index ) => ( <tr> <td>{index + 1}</td> <td>{this.props.mainState.stepTwoProp.rowSelected[index]}</td> <td>{materialDescription}</td> <td>{purchaseOrderExternalId}</td> <td>{this.formatQtyNumber(quantity.initial)}</td> <td>{this.formatPriceNumber(itemSubTotal)}</td> <td>{quantity.unit}</td> <td>{this.formatPriceNumber(unitPrice)}</td> <td>{this.formatPriceNumber(creditNoteAdjustedSubtotal)}</td> <td>{currency}</td> </tr> ) ); } else { return ( <div> <center>No Item Found</center> </div> ); } } } ///////This function is to be remove // async renderInvoiceItemTable(cnItem) { // console.log(cnItem); // let data = []; // cnItem.forEach((item, index) => { // data.push( // this.populateRowForInvoiceItemTable( // item, // index, // this.props.mainState.stepTwoProp.rowSelected[index] // ) // ); // }); // console.log(data); // let dts = window // .jQuery(this.el) // .DataTable({ // //dom: '<<"row justify-content-between align-items-center mb-3"<"col d-flex align-items-center"lp><"col d-flex justify-content-end"<"btn-wrap upload"><"btn-wrap create"><"btn-wrap col-display"><"btn-wrap export">>><t>>', // language: { // lengthMenu: "Display _MENU_ Per Page" // }, // data: data, // columns: // this.props.mainState.stepTwoProp.createType === CREATE_TYPE_ENUMS.QTY // ? QTY_COLUMN_PATTERN // : PRICE_COLUMN_PATTERN, // columnDefs: [ // { // targets: [0], // width: "60px" // }, // { // targets: [1], // width: "80px" // }, // { // targets: [2], // width: "300px" // }, // { // targets: [3], // width: "100px" // }, // { // targets: [4], // width: "80px" // }, // { // targets: [5], // width: "80px" // }, // { // targets: [6], // width: "80px" // }, // { // targets: // this.props.mainState.stepTwoProp.createType === // CREATE_TYPE_ENUMS.QTY // ? [7, 8, 9, 10] // : [7, 8, 9], // width: "80px" // }, // { // targets: "_all", // orderable: false, // sortable: false // } // ], // order: [[1, "asc"]], // fixedHeader: true, // stateSave: false, // paging: false, // bLengthChange: true, // searching: false, // info: false, // ordering: true // }) // .on("error", function (e, settings, techNote, message) { // console.log("An error has been reported by DataTables: ", message); // }); // await this.toggleBlocking(); // } ///////This function is to be remove // populateRowForInvoiceItemTable(item, index, row) { // if (this.props.mainState.stepTwoProp.createType === CREATE_TYPE_ENUMS.QTY) { // return { // cnItemNo: index + 1, // invoiceItemNo: row, // materialDescription: item.materialDescription, // poNo: item.purchaseOrderExternalId, // invoiceQty: this.formatQtyNumber(item.quantity.initial), // invoiceAmount: this.formatPriceNumber(item.itemSubTotal), // cnQty: this.formatQtyNumber(item.creditNoteQuantity.initial), // unit: item.quantity.unit, // unitPrice: this.formatPriceNumber(item.unitPrice), // cnAmount: this.formatPriceNumber(item.creditNoteAdjustedSubtotal), // currency: item.currency // }; // } else if ( // this.props.mainState.stepTwoProp.createType === CREATE_TYPE_ENUMS.PRICE // ) { // return { // cnItemNo: index + 1, // invoiceItemNo: row, // materialDescription: item.materialDescription, // poNo: item.purchaseOrderExternalId, // invoiceQty: this.formatQtyNumber(item.quantity.initial), // invoiceAmount: this.formatPriceNumber(item.itemSubTotal), // unit: item.quantity.unit, // unitPrice: this.formatPriceNumber(item.unitPrice), // cnAmount: this.formatPriceNumber(item.creditNoteAdjustedSubtotal), // currency: item.currency // }; // } // } calAll() { let total = 0; let taxTotal = 0; let allItems = this.state.allItems; allItems.forEach(item => { total = total + item.creditNoteAdjustedSubtotal; taxTotal = this.calItemsTaxTotal(allItems); }); if (this.props.mainState.stepFourProp) { if (this.props.mainState.stepFourProp.isChangeSubTotalTaxTotal) { this.setState({ cnAmount: this.props.mainState.stepFourProp.cnAmount, cnRmnAmount: this.props.mainState.stepFourProp.cnRmnAmount, taxTotal: this.props.mainState.stepFourProp.taxTotal, totalAmount: this.props.mainState.stepFourProp.cnAmount + this.props.mainState.stepFourProp.taxTotal, isChangeSubTotalTaxTotal: true }); } else { this.setState({ cnAmount: total, cnRmnAmount: total, taxTotal: taxTotal, totalAmount: total + taxTotal }); } } else { this.setState({ cnAmount: total, cnRmnAmount: total, taxTotal: taxTotal, totalAmount: total + taxTotal }); } } calItemsTaxTotal(items) { let taxTotal = 0; let taxSumMapping = {}; items.forEach(item => { if (_.has(taxSumMapping, `tax${item.vatRate}`)) { taxSumMapping[`tax${item.vatRate}`] += +item.creditNoteAdjustedSubtotal; } else { taxSumMapping[`tax${item.vatRate}`] = +item.creditNoteAdjustedSubtotal; } }); _.forOwn(taxSumMapping, (value, key) => { taxTotal = taxTotal + +this.calTax(value, key.replace("tax", "")); }); return taxTotal; } calTax(amount, percentage) { return parseFloat( ( parseFloat(amount.toFixed(2)) * parseFloat((percentage / 100).toFixed(2)) ).toFixed(2) ); } async submitCreateCreditNote() { this.toggleBlocking(); let uploadPromises = await this.populateFileAttachmentForCreate(); Promise.all(uploadPromises).then(data => { let fileAttachments = data; let cnObject = {}; if ( this.props.mainState.stepTwoProp.createType === CREATE_TYPE_ENUMS.QTY ) { cnObject = { vendorTaxNumber: this.props.mainState.stepOneProp.selectedInvoice .vendorTaxNumber, vendorAddress: this.props.mainState.stepOneProp.selectedInvoice .vendorAddress, vendorNumber: this.props.mainState.stepOneProp.selectedInvoice .vendorNumber, vendorBranchCode: this.props.mainState.stepOneProp.selectedInvoice .vendorBranchCode, vendorName: this.props.mainState.stepOneProp.selectedInvoice .vendorName, companyTaxNumber: this.props.mainState.stepOneProp.selectedInnerItem .businessPlaceTaxNumber, companyAddress: this.props.mainState.stepOneProp.selectedInvoice .companyAddress, companyBranchCode: this.props.mainState.stepOneProp.selectedInvoice .companyBranchCode, companyCode: this.props.mainState.stepOneProp.selectedInvoice .companyCode, companyBranchName: this.props.mainState.stepOneProp.selectedInvoice .companyBranchName, companyName: this.props.mainState.stepOneProp.selectedInvoice .companyName, companyTelephone: this.props.mainState.stepOneProp.selectedInnerItem .businessPlacePostalTelephone, invoiceExternalId: this.props.mainState.stepOneProp.selectedInvoice .externalId, invoiceLinearId: this.props.mainState.stepOneProp.selectedInvoice .linearId, externalId: this.props.mainState.stepThreeProp.creditNote.trim(), adjustmentType: "QUANTITY", reason: this.props.mainState.stepThreeProp.creditNoteReason, creditNoteDate: this.props.mainState.stepThreeProp.creditNoteDate, documentEntryDate: moment(this.state.entryDate).format("DD/MM/YYYY"), creditNoteAdjustedSubtotal: +this.state.cnAmount, subTotal: +this.state.cnAmount, vatTotal: +this.state.taxTotal, // "total": +this.state.cnAmount, total: Number(this.state.cnAmount) + Number(this.state.taxTotal), currency: this.props.mainState.stepOneProp.selectedInvoice.currency, creditNoteItems: this.populateCNItem(), fileAttachments: fileAttachments }; } else if ( this.props.mainState.stepTwoProp.createType === CREATE_TYPE_ENUMS.PRICE ) { cnObject = { vendorTaxNumber: this.props.mainState.stepOneProp.selectedInvoice .vendorTaxNumber, vendorAddress: this.props.mainState.stepOneProp.selectedInvoice .vendorAddress, vendorNumber: this.props.mainState.stepOneProp.selectedInvoice .vendorNumber, vendorBranchCode: this.props.mainState.stepOneProp.selectedInvoice .vendorBranchCode, vendorName: this.props.mainState.stepOneProp.selectedInvoice .vendorName, companyTaxNumber: this.props.mainState.stepOneProp.selectedInnerItem .businessPlaceTaxNumber, companyAddress: this.props.mainState.stepOneProp.selectedInvoice .companyAddress, companyBranchCode: this.props.mainState.stepOneProp.selectedInvoice .companyBranchCode, companyCode: this.props.mainState.stepOneProp.selectedInvoice .companyCode, companyBranchName: this.props.mainState.stepOneProp.selectedInvoice .companyBranchName, companyName: this.props.mainState.stepOneProp.selectedInvoice .companyName, invoiceExternalId: this.props.mainState.stepOneProp.selectedInvoice .externalId, invoiceLinearId: this.props.mainState.stepOneProp.selectedInvoice .linearId, externalId: this.props.mainState.stepThreeProp.creditNote.trim(), adjustmentType: "PRICE", reason: this.props.mainState.stepThreeProp.creditNoteReason, creditNoteDate: this.props.mainState.stepThreeProp.creditNoteDate, creditNoteAdjustedSubtotal: +this.state.cnAmount, subTotal: +this.state.cnAmount, vatTotal: +this.state.taxTotal, // "total": +this.state.cnAmount, total: Number(this.state.cnAmount) + Number(this.state.taxTotal), currency: this.props.mainState.stepOneProp.selectedInvoice.currency, creditNoteItems: this.populateCNItem(), fileAttachments: fileAttachments }; } else { console.log("UNSUPPORTED TYPE"); } if (!_.isEmpty(cnObject)) { GA.event({ category: "Credit Note", action: "CN Submit (Request)", label: `Credit Note | ${ cnObject.externalId } | ${moment().format()}` // value: cnObject.total }); Api.postCreateCreditNote(cnObject) .then(res => { this.toggleBlocking(); GA.event({ category: "Credit Note", action: "CN Submit (Success)", label: `Credit Note | ${ cnObject.externalId } | ${moment().format()}`, value: cnObject.total }); Router.push("/credit-note"); }) .catch(err => { this.toggleBlocking(); GA.event({ category: "Credit Note", action: "CN Submit (Failed)", label: `Credit Note | ${ cnObject.externalId } | ${moment().format()}` }); const response = handleError(err, this.handleDismissBtnModal); this.setState({ ...response }); }); } }); } async populateFileAttachmentForCreate() { let fileAttachments = []; /// populate & upload file let fileTypeMapping = []; this.props.mainState.stepThreeProp.creditNoteFiles.forEach(file => { fileTypeMapping.push("CreditNote"); }); this.props.mainState.stepThreeProp.otherFiles.forEach(file => { fileTypeMapping.push("Others"); }); let uploadPackage = this.props.mainState.stepThreeProp.creditNoteFiles.concat( this.props.mainState.stepThreeProp.otherFiles ); let delay = -1000; const delayIncrement = 1000; let uploadPromise = uploadPackage.map((file, index) => { delay += delayIncrement; return new Promise((resolve, reject) => { setTimeout(() => { resolve( this.uploadFiles(file.data).then(hash => { let attachment = { attachmentHash: hash, attachmentName: file.name, attachmentType: fileTypeMapping[index] }; return attachment; }) ); }, delay); }); }); return uploadPromise; } populateCNItem() { let cnItemArray = []; let items = this.state.allItems; items.forEach((item, index) => { let cnItemObject = { externalId: "" + (index + 1), invoiceItemLinearId: item.linearId, invoiceItemExternalId: item.externalId, quantity: item.creditNoteQuantity.initial, unit: item.quantity.unit, unitDescription: item.purchaseItem.unitDescription, unitPrice: item.unitPrice, currency: item.currency, subTotal: this.props.mainState.stepTwoProp.createType === CREATE_TYPE_ENUMS.PRICE ? item.creditNoteAdjustedSubtotal : item.creditNoteQuantity.initial * item.unitPrice, vatTotal: this.props.mainState.stepTwoProp.createType === CREATE_TYPE_ENUMS.PRICE ? +this.calTax(item.creditNoteAdjustedSubtotal, item.vatRate) : +this.calTax( item.creditNoteQuantity.initial * item.unitPrice, item.vatRate ) }; cnItemArray.push(cnItemObject); }); return cnItemArray; } ///// Util ///// sliceFileName(fileName) { let ext = fileName.lastIndexOf("."); let fileNameWithoutExt = fileName.substr(0, ext); if (fileNameWithoutExt.length > 15) { let charArray = [...fileNameWithoutExt]; let newFileName = charArray[0] + charArray[1] + charArray[2] + charArray[3] + "...." + charArray[charArray.length - 4] + charArray[charArray.length - 3] + charArray[charArray.length - 2] + charArray[charArray.length - 1]; return newFileName + fileName.substr(ext); } else return fileName; } numberOnly(event, digitAmount) { let input = event.target.value.replace(/[^0-9.]/gm, ""); let valueReplace = input.replace(/[^0-9.]/gm, ""); let valueSplit = valueReplace.split("."); let digit = valueReplace.replace(".", ""); let cursorPosition = event.currentTarget.selectionStart; let integer = valueSplit[0]; let decimal = valueSplit[1]; let typablePosition = digit.length - (decimal ? decimal.length : 0); console.log(event); console.log("selectionStart", event.currentTarget.selectionStart); console.log("selectionEnd", event.currentTarget.selectionEnd); console.log("target", event.target); console.log("event.which", event.which); console.log("digit.length - decimal.length", typablePosition); if ( window.getSelection().toString().length == 0 && ((event.which >= "48" && event.which <= "57") || event.which == "46") ) { if (event.target.value.indexOf(".") !== -1) { if ( (digit.length >= 16 || decimal.length >= 16 - digitAmount) && event.which != "46" ) { if ( (cursorPosition > typablePosition || integer.length >= digitAmount) && event.which != "46" ) { event.preventDefault(); } } else if (event.which == "46") { event.preventDefault(); } } else { if (integer.length >= digitAmount && event.which != "46") { event.preventDefault(); } } } else if ( (event.which < "48" || event.which > "57") && event.which != "46" ) { event.preventDefault(); } } formatQtyNumber(amount) { return Intl.NumberFormat("th-TH", { useGrouping: true, maximumFractionDigits: 3, minimumFractionDigits: 3 }).format(amount); } formatPriceNumber(amount) { return Intl.NumberFormat("th-TH", { useGrouping: true, maximumFractionDigits: 2, minimumFractionDigits: 2 }).format(amount); } formatNumberInput(input, decimal) { let valueReplace = input.replace(/[^0-9.]/gm, ""); let valueSplit = valueReplace.split("."); let interger = valueSplit[0]; let fraction = ""; if (input.endsWith(".")) { fraction = valueSplit[1] === "" ? "." : "." + valueSplit[1].substring(0, decimal); } else { fraction = valueSplit[1] === undefined ? "" : "." + valueSplit[1].substring(0, decimal); } return fraction === "" ? interger.replace("-", "") : (interger + fraction).replace("-", ""); } uploadFiles(data) { return Api.postUploadFile(data).then(res => { return res[0].attachmentHash; }); } ///// NEXT & BACK ////// async handleBack() { await this.props.updateState(this.state); //this.props.setMainState({ stepFourProp: this.state }); this.props.previousStep(); } routeCancel() { Router.push("/credit-note"); } // numberOnly = e => { // const keyCode = e.keyCode || e.which; // if ((keyCode >= 48 && keyCode <= 57) || keyCode == 46) { // if (keyCode == 46) { // if (e.target.value.indexOf(".") !== -1) { // e.preventDefault(); // } // } // e.target.value = e.target.value.replace(/,/g, ""); // } else { // e.preventDefault(); // } // }; handleCNAmountFocus = e => { e.target.value = e.target.value.replace(/,/g, ""); if (e.target.value == 0) { e.target.value = ""; } e.target.select(); }; handleCNAmountValidation = async e => { let val = parseFloat(e.target.value.replace(/,/g, "")); let colorDefault = "#626262"; let res = false; if (val >= 0) { res = true; } if (!res) { $(e.target).css("color", "red"); } else { $(e.target).css("color", colorDefault); } return res; }; handleTaxTotalFocus = e => { e.target.value = e.target.value.replace(/,/g, ""); if (e.target.value == 0) { e.target.value = ""; } e.target.select(); }; handleTaxTotalValidation = async e => { let val = parseFloat(e.target.value.replace(/,/g, "")); let colorDefault = "#626262"; let res = false; if (val >= 0) { res = true; } if (!res) { $(e.target).css("color", "red"); } else { $(e.target).css("color", colorDefault); } return res; }; render() { const { t } = this.props; const { cnAmount, cnRmnAmount, isChangeSubTotalTaxTotal, taxTotal, totalAmount } = this.state; return ( <BlockUi tag="div" blocking={this.state.blocking}> <div> <div id="cn_create" class="step-4"> <div id="step-indicator" class="col-12"> <ul class="d-flex justify-content-center"> <li class="flex-fill finished no-gradient"> <div class="indicator step-1 rounded-circle text-center finished"> <span class="number">1</span> <i class="fa fa-check" /> </div> <p class="text-center">{t("Select Invoice")}</p> </li> <li class="flex-fill finished no-gradient"> <div class="indicator step-2 rounded-circle text-center"> <span class="number">2</span> <i class="fa fa-check" /> </div> <p class="text-center">{t("Credit Note Items")}</p> </li> <li class="flex-fill finished"> <div class="indicator step-3 rounded-circle text-center"> <span class="number">3</span> <i class="fa fa-check" /> </div> <p class="text-center">{t("Insert Credit Note Details")}</p> </li> <li class="flex-fill active"> <div class="indicator step-4 rounded-circle text-center"> <span class="number">4</span> <i class="fa fa-check" /> </div> <p class="text-center">{t("Summary")}</p> </li> </ul> </div> <div class="page__header col-12"> <h2> {t("Credit Note No")} :{" "} {this.props.mainState.stepThreeProp.creditNote} </h2> </div> <form id="cnCreateForm" name="cnCreateForm" method="post" enctype="multipart/form-data" action="" class="form col-12 px-0" > <section id="invoice_detail_page" class="box box--width-header"> <div class="box__header"> <div class="justify-content-between align-items-center"> <div class="col-4"> {" "} {t("Entry Date")} :{" "} <strong> {moment(this.state.entryDate).format("DD/MM/YYYY")} </strong> </div> </div> </div> <div class="box__inner"> <div class="row box"> <a href="#vendorInfo" data-toggle="collapse" role="button" aria-expanded="true" area-controls="vendorInfo" class="d-flex w-100 btnToggle" > <div class="col-6"> <h3 class="border-bottom gray-1">{t("Vendor")}</h3> </div> <div class="col-6"> <h3 class="border-bottom gray-1">{t("Company")}</h3> <i class="fa fa-chevron-up gray-1" aria-hidden="true" /> <i class="fa fa-chevron-down gray-1" aria-hidden="true" /> </div> </a> <div id="vendorInfo" class="collapse multi-collapse w-100 show" > <div class="card card-body noborder"> <div class="row"> <div class="col-6"> <div class="row"> <p class="col-4 text-right">{t("Code")} :</p> <p class="col-6"> { this.props.mainState.stepOneProp .selectedInnerItem.vendorNumber } </p> </div> <div class="row"> <p class="col-4 text-right">{t("Name")} :</p> <p class="col-6"> { this.props.mainState.stepOneProp .selectedInnerItem.vendorName } </p> </div> <div class="row"> <p class="col-4 text-right">{t("Tax ID")} :</p> <p class="col-6"> { this.props.mainState.stepOneProp .selectedInnerItem.vendorTaxNumber } </p> </div> <div class="row"> <p class="col-4 text-right">{t("Branch")} :</p> <p class="col-6"> { this.props.mainState.stepOneProp .selectedInnerItem.vendorBranchCode } </p> </div> <div class="row"> <p class="col-4 text-right">{t("Address")} :</p> <p class="col-6"> { this.props.mainState.stepOneProp .selectedInvoice.vendorAddress } </p> </div> <div class="row"> <p class="col-4 text-right">{t("Tel")} :</p> <p class="col-6"> { this.props.mainState.stepOneProp .selectedInnerItem.vendorTelephone } </p> </div> </div> <div class="col-6"> <div class="row"> <p class="col-4 text-right">{t("Code")} :</p> <p class="col-6"> { this.props.mainState.stepOneProp .selectedInnerItem.companyCode } </p> </div> <div class="row"> <p class="col-4 text-right">{t("Name")} :</p> <p class="col-6"> { this.props.mainState.stepOneProp .selectedInnerItem.companyName } </p> </div> <div class="row"> <p class="col-4 text-right">{t("Tax ID")} :</p> <p class="col-6"> { this.props.mainState.stepOneProp .selectedInnerItem.businessPlaceTaxNumber } </p> </div> <div class="row"> <p class="col-4 text-right">{t("Branch")} :</p> <p class="col-6"> { this.props.mainState.stepOneProp .selectedInnerItem.companyBranchCode } </p> </div> <div class="row"> <p class="col-4 text-right">{t("Address")} :</p> <p class="col-6"> { this.props.mainState.stepOneProp .selectedInvoice.companyAddress } </p> </div> <div class="row"> <p class="col-4 text-right">{t("Tel")} :</p> <p class="col-6"> { this.props.mainState.stepOneProp .selectedInnerItem .businessPlacePostalTelephone } </p> </div> </div> </div> </div> </div> </div> {/* end box1 */} <div class="row box"> <a href="#paymentInfo" data-toggle="collapse" role="button" aria-expanded="true" area-controls="paymentInfo" class="d-flex w-100 btnToggle" > <div class="col-12"> <h3 class="border-bottom gray-1"> {t("Credit Note Information")} </h3> <i class="fa fa-chevron-up gray-1" aria-hidden="true" /> <i class="fa fa-chevron-down gray-1" aria-hidden="true" /> </div> </a> <div id="paymentInfo" class="collapse multi-collapse w-100 show" > <div class="card card-body noborder"> <div class="row"> <div class="col-6"> <div class="d-flex flex-wrap"> <p class="col-4 text-right"> {t("Credit Note Date")} :{" "} </p> <p class="col-6"> { this.props.mainState.stepThreeProp .creditNoteDate } </p> </div> <div class="d-flex flex-wrap"> <p class="col-4 text-right"> {t("Invoice Ref No")} : </p> <p class="col-6"> { this.props.mainState.stepOneProp .selectedInvoice.externalId } </p> </div> <div class="d-flex flex-wrap"> <p class="col-4 text-right"> {t("Type of CN")} :{" "} </p> <p class="col-6"> {this.props.mainState.stepTwoProp.createType === CREATE_TYPE_ENUMS.QTY ? "Quantity Adjustment" : "Price Adjustment"} </p> </div> </div> <div class="col-6"> <div class="d-flex flex-wrap"> <p class="col-6 text-right"> {t("CN Amount")} :{" "} </p> <p class="col-6 d-flex flex-wrap"> <div className="col-8 text-right"> {cnAmount >= 0 ? ( <input className="form-control" data-tip="custom show" data-event="focus" data-event-off="blur" data-for="priceSelect" key="cnAmount" id="cnAmount" ref="cnAmount" type="text" name="cnAmount" pattern="[0-9]*" defaultValue={formatNumber(cnAmount, 2)} placeholder={formatNumber(cnAmount, 2)} onKeyPress={e => this.numberOnly(e, 14)} onFocus={this.handleCNAmountFocus} onChange={e => { this.handleCNAmountValidation(e); }} onBlur={e => { this.handleAmountChange(e); }} /> ) : ( formatNumber(0, 2) )} </div> <div className="col-4 text-left">THB</div> </p> </div> <div class="d-flex flex-wrap"> <p class="col-6 text-right"> {t("TAX Total")} :{" "} </p> <p class="col-6 d-flex flex-wrap"> <div className="col-8 text-right"> {taxTotal >= 0 ? ( <input className="form-control" data-tip="custom show" data-event="focus" data-event-off="blur" data-for="priceSelect" key="taxTotal" id="taxTotal" ref="taxTotal" type="text" name="taxTotal" pattern="[0-9]*" defaultValue={formatNumber(taxTotal, 2)} placeholder={formatNumber(taxTotal, 2)} onKeyPress={e => this.numberOnly(e, 14)} onFocus={this.handleTaxTotalFocus} onChange={e => { this.handleTaxTotalValidation(e); }} onBlur={e => { this.handleTaxTotalChange(e); }} /> ) : ( formatNumber(0, 2) )} </div> <div className="col-4 text-left">THB</div> </p> </div> <div class="d-flex flex-wrap"> <p class="col-6 text-right"> {t("Credit Note Amount (inc TAX)")} :{" "} </p> <p class="col-6 d-flex flex-wrap"> <div className="col-8 text-right" id="cnAmountIncTax" > {this.formatPriceNumber(totalAmount)} </div>{" "} <div className="col-4 text-left">THB</div> </p> </div> <div class="d-flex flex-wrap"> <p class="col-6 text-right">{t("Reason")} : </p> <p class="col-6"> { this.props.mainState.stepThreeProp .creditNoteReason } </p> </div> </div> </div> </div> </div> </div> {/* end box2 */} <div class="row box"> <a href="#AttachInfo" data-toggle="collapse" role="button" aria-expanded="true" area-controls="AttachInfo" class="d-flex w-100 btnToggle" > <div class="col-12"> <h3 class="border-bottom gray-1">{t("Attachments")}</h3> <i class="fa fa-chevron-up gray-1" aria-hidden="true" /> <i class="fa fa-chevron-down gray-1" aria-hidden="true" /> </div> </a> <div id="AttachInfo" class="collapse multi-collapse w-100 show" > <div class="card card-body noborder"> <div class="row"> <div class="col-6"> <div class="d-flex flex-wrap"> <p class="col-4 text-right"> {t("Attached Credit")} :{" "} </p> <ul class="col-6 list-style-none"> {this.props.mainState.stepThreeProp .creditNoteFiles.length > 0 ? this.props.mainState.stepThreeProp.creditNoteFiles.map( file => ( <li>{this.sliceFileName(file.name)}</li> ) ) : "-"} </ul> </div> </div> <div class="col-6"> <div class="d-flex flex-wrap"> <p class="col-6 text-right"> {t("Other Documents")} :{" "} </p> <ul class="col-6 list-style-none"> {this.props.mainState.stepThreeProp.otherFiles .length > 0 ? this.props.mainState.stepThreeProp.otherFiles.map( file => ( <li>{this.sliceFileName(file.name)}</li> ) ) : "-"} </ul> </div> </div> </div> </div> </div> </div> {/* end box3 */} </div> </section> <section id="invoice_detail_page_2" class="box box--width-header"> <div class="box__header"> <div class="row justify-content-between align-items-center"> <div class="col"> <h4 class="mb-0">{t("Items Information")}</h4> </div> </div> </div> {this.state.taxRateList && this.state.taxRateList.map(vatRate => { return ( <div className="box__inner"> <Collapse id={`tax${vatRate}`} expanded="true" collapseHeader={[`${t("TAX")} ${vatRate}%`]} > <div className="table_wrapper"> <table className="table table-3 dataTable"> <thead> {this.props.mainState.stepTwoProp.createType === CREATE_TYPE_ENUMS.QTY ? ( <tr> <th> {t("CN Item No1")} <br /> {t("CN Item No2")} </th> <th> {t("Invoice Item No1")} <br /> {t("Invoice Item No2")} </th> <th>{t("Material Description")}</th> <th>{t("PO No")}</th> <th>{t("Invoice QTY")}</th> <th> {t("Invoice Amount1")} <br /> {t("Invoice Amount2")} </th> <th> {t("CN QTY1")} <br /> {t("CN QTY2")} </th> <th>{t("Unit")}</th> <th> {t("Unit Price1")} <br /> {t("Unit Price2")} </th> <th> {t("CN Amount1")} <br /> {t("CN Amount2")} </th> <th>{t("Currency")}</th> </tr> ) : ( <tr> <th> {t("CN Item No1")} <br /> {t("CN Item No2")} </th> <th> {t("Invoice Item No1")} <br /> {t("Invoice Item No2")} </th> <th>{t("Material Description")}</th> <th>{t("PO No")}</th> <th>{t("Invoice QTY")}</th> <th> {t("Invoice Amount1")} <br /> {t("Invoice Amount2")} </th> <th>{t("Unit")}</th> <th> {t("Unit Price1")} <br /> {t("Unit Price2")} </th> <th> {t("CN Amount1")} <br /> {t("CN Amount2")} </th> <th>{t("Currency")}</th> </tr> )} </thead> <tbody> {this.generateRowTableForTax( this.state.taxRateListItem[`tax${vatRate}`] )} </tbody> </table> </div> </Collapse> </div> ); })} </section> <div class="row"> <div class="col-12 text-center"> <button type="button" name="btnCancel" id="btnCancel" class="btn btn--transparent btn-wide" data-toggle="modal" data-target="#cancelWarning" > {t("Cancel")} </button> <button type="button" name="btnBack" id="btnBack" onClick={() => this.handleBack()} class="btn btn--transparent btn-wide" > <i class="fa fa-chevron-left" /> {t("Back")} </button> <button type="button" name="btnNext" id="btnNext" class="btn btn-wide" onClick={() => this.submitCreateCreditNote()} > {t("Submit")} </button> </div> </div> <div class="row">&nbsp;</div> </form> <div id="cancelWarning" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="cancel" aria-hidden="true" > <div class="modal-dialog modal-sm" role="document"> <div class="modal-content"> <div class="modal-header"> <h3 id="myModalLabel" style={{ margin: "auto" }}> Cancel </h3> </div> <div class="modal-body text-center"> <div className="text">Do you want to cancel this CN?</div> </div> <div class="modal-footer justify-content-center"> <button type="button" name="btnCloseModal" id="btnCloseModal" class="btn btn-wide" data-dismiss="modal" aria-hidden="true" > No </button> <button type="button" name="btnCloseModal" id="btnCloseModal" class="btn btn--transparent btn-wide" data-dismiss="modal" aria-hidden="true" onClick={() => this.routeCancel()} > Yes </button> </div> </div> </div> </div> <div id="smallScreenCover"> <p class="text-center"> <img src="img/icon_expanded.png" alt="" /> </p> </div> </div> {/* <p><a href="javascript:void(0);" data-toggle="modal" data-target="#alertBox">Click ME!</a></p> */} <div id="alertBox" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="alertBox" aria-hidden="true" > <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header justify-content-center"> <h3 id="myModalLabel">Error</h3> </div> <div class="modal-body d-flex justify-content-center"> <p> Unable to create credit note because{" "} {this.state.createErrMessage} </p> </div> <div class="modal-footer justify-content-center"> <button type="button" name="btnCloseModal" id="btnCloseModal" class="btn btn-wide" data-dismiss="modal" aria-hidden="true" > OK </button> </div> </div> </div> </div> </div> <ModalAlert title={this.state.alertModalAlertTitle} visible={this.state.isAlertModalVisible} button={this.state.buttonAlert} isTextOnly={this.state.isTextOnly} > {this.state.alertModalMsg} </ModalAlert> </BlockUi> ); } } export default withTranslation(["credit-create", "detail"])( createCreditNoteStepFour );
import { x } from '@xstyled/styled-components' const FixedRatioBox = ({ ratio = '1/1', ...props }) => ( <x.div position="relative" width="100%" pt={`calc(100% / (${ratio}))`} {...props} /> ) export default FixedRatioBox
// VANILLA JAVASCRIPT const skills = document.querySelectorAll('article.skill'); skills.forEach((skill) => { const percetage = skill.querySelector('.percentage').innerHTML, progressBar = skill.querySelector('.progressBar'); progressBar.style.width = percetage; }); const menuIcon = document.querySelector('#menu'); const ul = document.querySelector('header nav ul'); const listItems = document.querySelectorAll('header nav ul li'); menuIcon.addEventListener('click', function () { this.classList.toggle('active'); this.querySelectorAll('i').forEach((item) => { item.classList.toggle('show'); }); ul.classList.toggle('active'); }); listItems.forEach((listitem) => { listitem.addEventListener('click', function () { ul.classList.remove('active'); menuIcon.classList.remove('active'); menuIcon.querySelectorAll('i').forEach((item) => { item.classList.toggle('show'); }); }); }); // JQUERY $(window).on('load', function () { setTimeout(function () { $('#loader').fadeOut(800); setTimeout(() => { $('#loader .loaderBackground').css('animation', 'none'); }, 1000); }, 2000); }); $(document).ready(function () { // SMOOTH SCROLL $('nav a').click(function (e) { e.preventDefault(); $('html,body').animate( { scrollTop: $(this.hash).offset().top, }, { duration: 800, easing: 'swing', } ); }); // SCROLL BASED TRANSITIONS $(window).scroll(function () { if (window.scrollY > 80) { $('header').addClass('active'); $('nav').addClass('active'); } else { $('header').removeClass('active'); $('nav').removeClass('active'); } const scrollBarLocation = $(this).scrollTop(); $('nav a').each(function () { const sectionOffset = $(this.hash).offset().top - 50; if (sectionOffset <= scrollBarLocation) { $('nav a').removeClass('active'); $(this).addClass('active'); } }); }); // EMAIL ME $('#MailMePersonally').on('click', function () { window.open('mailto:takrishtak2002@gmail.com'); }); // MESSAGE $('#form').on('submit', function (e) { e.preventDefault(); const sendersName = $('input#name').val(); const sendersEmail = $('input#email').val(); const sendersMessage = $('textarea#message').val(); const subject = 'From Your Portfolio'; window.open( `mailto:takrishtak2002@gmail.com?subject=${subject}&body=Sender: ${sendersName} ,%0D%0AEmail: ${sendersEmail} ,%0D%0A${sendersMessage}` ); }); });
const asyncErrorWrapper = require("express-async-handler"); const { searchHelper, paginationHelper } = require("./queryMiddlewaresHelpers"); const userQueryMiddlewares = function(model,options) { return asyncErrorWrapper(async function(req, res, next) { let query = model.find(); query = searchHelper("name",query,req); const total = await model.countDocuments(); const paginationResult = await paginationHelper(total,query,req); query = paginationResult.query; pagination = paginationResult.pagination; const queryResult = await query.find(); res.queryResult = { success: true, count: queryResult.length, pagination: pagination, data: queryResult }; next(); }); } module.exports = userQueryMiddlewares
//建立陣列 let colors = new Array('white', 'black' , 'custom'); let el = document.getElementById('colors'); el.innerHTML = colors.item(0);
var myApp= angular .module("myModule",[]) .controller("myController",function($scope){ // var employee={ // firstName:"Shailesh", // lastName:"Rai", // gender:"Male" // }; // $scope.employee=employee; // var country={ // name:"India", // capital:'New Delhi', // flag:'/images/india.png' // } // $scope.country=country; // $scope.message="Shailesh"; // var employees=[ // {firstName:"Tom",lastName:"Potter",gender:"Male"}, // {firstName:"Dick",lastName:"Mathews",gender:"Male"}, // {firstName:"Harry",lastName:"Weasly",gender:"Male"}, // {firstName:"Linda",lastName:"Gates",gender:"Female"}, // {firstName:"Maya",lastName:"Raj",gender:"Female"}, // ]; //$scope.employees=employees; // var countries=[ // {name:"India",cities:["New Delhi","Chandigarh","Ranchi"]}, // {name:"USA",cities:["New York","Washignton DC","Las Vegas"]}, // {name:"Japan",cities:["Tokyo","Osaka","Hokaido"]} // ]; // $scope.countries=countries; //events // var programming=[ // {name:"java",likes:0,dislikes:0}, // {name:"c++",likes:0,dislikes:0}, // {name:"python",likes:0,dislikes:0}, // {name:"javascript",likes:0,dislikes:0}, // ] // $scope.programming=programming; // $scope.incrementLike= function(language){ // language.likes++; // } // $scope.incrementDislike=function(language) // { // language.dislikes++; // } //filters var employees=[ {name:"Ben",dob:new Date('23 March 1998'),gender:1,city:'Mumbai',salary:50000.918}, {name:"Lee",dob:new Date('22 February 1994'),gender:1,city:'Kolkata',salary:150000.90}, {name:"Tom",dob:new Date('12 March 1996'),gender:2,city:'Ranchi',salary:540000.618}, {name:"Dick",dob:new Date('31 August 1998'),gender:3,city:'Ranchi',salary:150000.198}, {name:"Harry",dob:new Date('29 February 1992'),gender:2,city:'Chandigarh',salary:250080.98} ]; $scope.employees=employees; $scope.displayType="table"; $scope.employeesView= function() { if($scope.displayType=="table") { return 'employeeTable.html' }else{ return 'employeeList.html'; } } $scope.salaryState=true; $scope.search=function (item) { if($scope.searchText==undefined) { return true; }else{ if(item.name.toLowerCase().indexOf($scope.searchText.toLowerCase()) != -1 || item.city.toLowerCase().indexOf($scope.searchText.toLowerCase()) != -1 ) { //console.log(item); return true; } return false; } } //$scope.rowLimit=3; $scope.sortColumn="name"; $scope.reverseSort=false; $scope.sortData=function(column) { if($scope.sortColumn==column) $scope.reverseSort=!$scope.reverseSort; else $scope.reverseSort=false; $scope.sortColumn=column; } $scope.getSortClass=function(column) { if($scope.sortColumn==column) if($scope.reverseSort) return 'fa-arrow-up'; else return 'fa-arrow-down'; return ''; } }); // var myControlller = function ($scope){ // $scope.message= "Angular JS tutorial"; // }; // myApp.controller("myController",myControlller); // myApp.controller("myController",function($scope){ // var employee={ // firstName:"Shailesh", // lastName:"Rai", // gender:"Male" // }; // $scope.employee=employee; // }); // var myImg=angular // .module("imgModule",[]) // .controller("imgController",($scope)=>{ // $scope.message="Yo Yo"; // });
import React from 'react'; export default class PastOrdersDiv extends React.Component { render(){ const {order, dishes, restaurants} = this.props const date = new Date(Date.parse(order[0].created_at)) return( <li> <div className="past-orders"> Restaurant: {restaurants.find(ele => ele.id === order[0].restaurant_id).name} <br/> When: {date.toLocaleString('en-US', {hour: 'numeric', minute: 'numeric', hour12: true})}, {date.toLocaleString('en-us', { month: "long" })} {date.getDate()}, {date.getFullYear()} <br/> Dishes: <ul>{order.map(ele => <li key={ele.dish_id}>{dishes.find(item=>item.id === ele.dish_id).name}</li> )}</ul> </div> <hr/> </li> ) } }
import test from "tape" import { lt } from "./lt" test("lt", t => { t.equals(lt(10)(14), false, "14 is not less than 10") t.equals(lt(10)(10), false, "10 is not less than 10") t.equals(lt(10)(4), true, "4 is less than 10") t.end() })
function editMe() { var user = { name: editName.value, // surname: editSurname.value, phone: editPhone.value, email: editEmail.value, password: editPassword.value } // alert(JSON.stringify(user)) $.ajax({ url: '/editUser', dataType: 'text', type: 'post', contentType: "application/json; charset=utf-8", data: JSON.stringify(user), success: function (data, textStatus, jQxhr) { location.href = '/logout'; // inputLogin3.value = ""; // inputEmail3.value = ""; textareaClass.value = ""; }, error: function (jqXhr, textStatus, errorThrown) { // alert(jqXhr + " " + textStatus + " " + errorThrown) } }); } // // // // // // var phn = true; // var na = false; // var eme = false; // var pas = false; // var namefield; // var surnamefield; // var phonefield; // var emailfield; // var passwordfield; // var confirmPasswordfield; // var canAdd = false; // // editPhone.onblur = function (i) { // alert(i.value) // if (!isNaN(editPhone.value)) { // // // } // else if (isNaN(editPhone.value)) { // editPhone.style.borderColor = "red"; // erPhone.innerHTML = 'not a number'; // phn = false; // } // else { // editPhone.style.borderColor = "red"; // erPhone.innerHTML = ''; // phn = false; // // } // } // // editName.onblur = function () { // if (!this.value) { // namefield = null; // this.className = "error"; // errorname.innerHTML = 'please enter your name.'; // na = false; // } // // else { // names.style.backgroundColor = "green"; // ername.innerHTML = ""; // namefield = this.value; // na = true; // if (isKyr(this.value)) { // alert("kyrillic"); // } // } // } // email.onblur = function () { // this.css = this.className; // var em = this.value; // if (!this.value) { // emailfield = null; // email.style.borderColor = "red"; // errormail.innerHTML = 'please enter your email.'; // eme = false; // } // // else if (this.value) { // // if (isKyr(this.value)) { // emailfield = null; // email.style.borderColor = "red"; // errormail.innerHTML = 'please email in latin letters'; // eme = false; // } // // else { // var r = /^\w+@\w+\.\w{2,4}$/i; // if (!r.test(document.getElementById("email").value)) { // emailfield = null; // email.style.borderColor = "red"; // errormail.innerHTML = 'please enter correct email '; // eme = false; // } // // else { // fetch("ckeckMail", { // method: 'post', // body: this.value // }) // .then(function (response) { // return response.text(); // }) // .then(function (data) { // if (data !== "empty") { // emailfield = null; // email.style.borderColor = "red"; // errormail.innerHTML = 'this email is already registered'; // eme = false; // } // else { // email.style.borderColor = "green"; // errormail.innerHTML = ''; // emailfield = em; // eme = true; // } // }) // .catch(error); // // } // // // } // } // } // var isKyr = function (str) { // return /[а-я]/i.test(str); // } // password.onblur = function () { // var passwordval = this.value; // if (!this.value) { // password.style.borderColor = "red"; // errorpassword.innerHTML = "please enter password"; // passwordfield = null; // pas = false; // } // else if (isKyr(this.value)) { // password.style.borderColor = "red"; // errorpassword.innerHTML = "please enter password in latin symbols"; // passwordfield = null; // pas = false; // } // else if (this.value.length < 4 && this.value && !isKyr(this.value)) { // password.style.borderColor = "red"; // errorpassword.innerHTML = "password is too short (min 4 symbols)"; // passwordfield = null; // pas = false; // } // else { // password.style.borderColor = "green"; // errorpassword.innerHTML = ""; // passwordfield = passwordval; // pas = true; // } // } // confirmPassword.onblur = function () { // var passwordConfirm = this.value; // if (!passwordConfirm // & passwordfield) { // password.style.borderColor = "red"; // errorpassword.innerHTML = "please enter password from confirm"; // confirmPasswordfield = null; // pas = false; // } // else if (this.value != passwordfield) { // confirmPassword.style.borderColor = "red"; // errorpasswordConfirm.innerHTML = "password does not match"; // confirmPasswordfield = null; // pas = false; // } // else { // confirmPassword.style.borderColor = "green"; // errorpasswordConfirm.innerHTML = "password match"; // confirmPasswordfield = passwordConfirm; // pas = true; // } // } // // function checkFields() { // if (document.getElementById("confirmPassword").value != document.getElementById("password").value) { // pas = false // } // if (!document.getElementById("phone").value) { // phn = true; // } // if (!document.getElementById("email").value) { // email.style.borderColor = "red"; // errormail.innerHTML = 'please enter your email.'; // } // if (isKyr(document.getElementById("email").value)) { // emailfield = null; // email.style.borderColor = "red"; // errormail.innerHTML = 'please email latin symbols'; // eme = false; // } // var r = /^\w+@\w+\.\w{2,4}$/i; // // if (!r.test(document.getElementById("email").value)) { // emailfield = null; // email.style.borderColor = "red"; // errormail.innerHTML = 'please enter correct email '; // eme = false; // } // if (!document.getElementById("names").value) { // names.style.borderColor = "red" // errorname.innerHTML = 'please enter your name.'; // } // // if (!document.getElementById("password").value) { // password.style.borderColor = "red"; // errorpassword.innerHTML = "please enter correct password"; // } // // // if (isKyr(document.getElementById("password").value)) { // password.style.borderColor = "red"; // errorpassword.innerHTML = "please enter password in latin symbols"; // } // if (document.getElementById("password").value & document.getElementById("password").value.length < 4) { // password.style.borderColor = "red"; // errorpassword.innerHTML = "password is too short (min 4 symbols)"; // } // if (document.getElementById("password").value.length >= 4 & !document.getElementById("confirmPassword").value) { // confirmPassword.style.borderColor = "red"; // errorpasswordConfirm.innerHTML = "please enter password from confirm"; // } // if (document.getElementById("password").value.length >= 4 & // document.getElementById("confirmPassword").value != undefined & document.getElementById("confirmPassword").value !== document.getElementById("password").value) { // confirmPassword.style.borderColor = "red"; // errorpasswordConfirm.innerHTML = "password does not match"; // } // if (document.getElementById("password").value.length >= 4 & // document.getElementById("confirmPassword").value == document.getElementById("password").value) { // confirmPassword.style.borderColor = "green"; // errorpasswordConfirm.innerHTML = ""; // password.style.borderColor = "green"; // errorpassword.innerHTML = ""; // pas = true; // } // // if (eme == true & na == true & pas == true & phn == true) { // // valid(); // function valid() { // // // } // } // }
import React from 'react'; import ReactDOM from 'react-dom'; import PrimeraApp from './PrimeraApp'; import CounterApp from './CounterApp'; import PrimerTestApp from './PrimerTestApp'; import './index.css'; //Importar CSS console.log('Hola mundo'); const saludo = <h1>Hola mundo</h1>; const divRoot = document.querySelector('#root'); console.log(saludo); console.log(divRoot); //Renderización de html directo // ReactDOM.render(saludo, divRoot); //Renderización desde componente, sobreescribe el render anterior porque apunta al mismo elemento 'root' // ReactDOM.render(<PrimeraApp />, divRoot); //Renderización desde componente enviando props // ReactDOM.render(<PrimeraApp nombreProps='Juan Manuel' apellidoProps='Correa Lomas' edadProps={12}/>, divRoot); //Renderización desde componente sin enviar props para usar valores por defecto (manera 1 y 2) // ReactDOM.render(<PrimeraApp />, divRoot); //Renderización desde componente enviando props pero con el valor de edadProps de tipo string y espara number por lo que da un warning, si no se envían ya no da error sino un warning por el propTypes // ReactDOM.render(<PrimeraApp nombreProps='Juan Manuel' apellidoProps='Correa Lomas' edadProps='12'/>, divRoot); //Tarea (Tarea.md) // ReactDOM.render(<CounterApp value={10} />, divRoot); //Test ReactDOM.render(<PrimerTestApp />, divRoot); //Tarea // Validar CounterApp por snapshot y valores por defecto // Validar CounterApp enviando 100 y verificando el elemento HTML correspondiente ReactDOM.render(<CounterApp value={10} />, divRoot);
class Navigate { to(route) { let element = document.querySelector(`#${route}`); if ('scrollRestoration' in window.history) { window.history.scrollRestoration = 'manual' } // setTimeout(() => { // console.log(' ::>> element >>>>> ', { element }, element.offsetTop); // window.scrollTo(0, element.offsetTop); element.scrollIntoView({ behavior: 'smooth', block: 'start' }); // }, 500); } } class BlockSelector { blockSelector; activeElement; activeContentElement; contentElements; parentElement; constructor(blockSelector, selector) { this.blockSelector = blockSelector; this.contentElements = Array.prototype.slice.call( document.querySelectorAll(selector) ); } select(el, parentElementId) { if (parentElementId) { this.hideElement(parentElementId); } else { this.removeActive(); this.addActive(el); } this.showServiceInfo(el.id); } hideElement(parentElementId) { if (!this.parentElement) { let el = document.querySelector('#' + parentElementId); this.parentElement = el; } if (this.parentElement) { this.hide(this.parentElement); } } removeActive() { if (this.activeElement) { this.activeElement.className = this.activeElement.className.replace(' showHover', ''); } else { let el = document.querySelector(this.blockSelector + ' .showHover'); if (el) { el.className = el.className.replace(' showHover', ''); } } } addActive(el) { if (el) { this.activeElement = el; this.activeElement.className += ' showHover'; this.show(this.activeElement); } } showServiceInfo(id) { this.contentElements.find(el => { if (el.id === id + '-block') { this.activeContentElement = el; this.show(this.activeContentElement); } else { this.hide(el); } }); } show(el) { let element = document.querySelector('#' + el.id) element.className = element.className.replace(' hidden', ''); } hide(el) { console.log(' ::>> hide ', el); let element = document.querySelector('#' + el.id) if (element.className.indexOf(' hidden') === -1) { element.className += ' hidden'; } } back() { console.log(' ::>> back ', this.activeContentElement); if (this.activeContentElement) { this.hide(this.activeContentElement); } console.log(' ::>> this.parentElement >>>> ', this.parentElement); if (this.parentElement) { this.show(this.parentElement); } } resetAndBack(elementToHideId, elementParentToHideId, elementToShowId1, elementToShowId2) { console.log(' ::>> resetAndBack >>>> ', { elementToHideId, elementParentToHideId, elementToShowId1, elementToShowId2 }); if (elementToHideId) this.hide({ id: elementToHideId }); if (elementParentToHideId) this.hide({ id: elementParentToHideId }); if (elementToShowId1) this.show({ id: elementToShowId1 }); if (elementToShowId2) this.show({ id: elementToShowId2 }); this.back(); } } const actions = { navigate: new Navigate(), service: new BlockSelector('#services', '#services .website-info'), explore: new BlockSelector('#explore', '#explore .website-info'), about: new BlockSelector('#about', '#about .website-info'), aboutProfile: new BlockSelector('#profile-block', '#profile-block .website-info-about'), };
var arabic2roman = function (a,s,r,c,i){ var S='MCXIDLV',R='',v=1e3; for(i=0;s=S[i],i<4;i++,v/=10,a=r){// for symbols M, C ,X, then I and value = 1000, 100, 10 then 1 r=a%v; // rest = arabic modulo value c=(a-r)/v; // c = a div v R+=c<4? // to the roman string, add Array(c+1).join(s) // c times the current symbol (I, II, III, X, XX,... , MMM) :c==4? s+S[i+3] // IV, XL, CD :c==9? s+S[i-1] // IX, XC, CM : S[i+3]+Array(c-4).join(s) // VI, VII, ..., DCCC ; } return R; };
'use strict'; $(document).ready(function () { var phones = [ '<button class="btn btn-success">John</button>', '<button class="btn btn-success">Rachel</button>' ]; $.each(phones, function (index, value) { $('.canvas').append(value).append('&nbsp;'); }); $('.canvas').children().first().on('click', function (e) { alert('John called ' + $(phones[1]).text()); }); $('.canvas').children().last().on('click', function (e) { alert('Rachel called ' + $(phones[0]).text()); }); });
import React from "react" const EndContent = (props) => { //item count props.itemCount return ( <React.Fragment> { props.itemCount == 0 && props.text ? <div className="no-content text-center"> {props.t(props.text)} </div> : <React.Fragment>{ props.itemCount == 0 ? <div className="container"> <div className="row"> <div className="col-md-12"> <div className="no-content text-center"> {props.t("We Didn't Find Any Data.")} </div> </div> </div> </div> : props.itemCount > 20 && !props.notShow ? <div className="container"> <div className="row"> <div className="col-md-12"> <div className="content-end text-center"> {props.t("Looks like you've reached the end.")} </div> </div> </div> </div> : null } </React.Fragment> } </React.Fragment> ) } export default EndContent;
$(document).ready(function () { var lon = -73.9529; var lat = 40.7723; var zoom = 10; var map = new L.Map('map'); var cloudmade = new L.TileLayer('http://{s}.tile.cloudmade.com/1a1b06b230af4efdbb989ea99e9841af/997/256/{z}/{x}/{y}.png', { maxZoom: 18 }); map.addLayer(cloudmade); var tile = new L.TileLayer.TileJSON({ debug: false, point: { color: 'rgba(252,146,114,0.6)', radius: 5 }, linestring: { color: 'rgba(161,217,155,0.8)', size: 3 }, polygon: { color: 'rgba(43,140,190,0.4)', outline: { color: 'rgb(0,0,0)', size: 1 } } }); tile.createUrl = function (bounds) { var url = ['/json.ashx?MAP_TYPE=PM&BBOX=', bounds[0], ',', bounds[1], ',', bounds[2], ',', bounds[3] ].join(''); return url; }; map.addLayer(tile); var center = new L.LatLng(lat, lon); map.setView(center, zoom); });
var requirejs = require('requirejs'); var TableViewFallback = requirejs('extensions/views/table_fallback'); var Model = requirejs('extensions/models/model'); var Collection = requirejs('extensions/collections/collection'); describe('TableFallback', function () { describe('initialize', function () { var table, options; beforeEach(function () { options = { model: new Model(), collection: new Collection([ { value: 01 }, { value: 02 }, { value: 03 }, { value: 04 }, { value: 05 }, { value: 06 }, { value: 07 } ]) }; }); it('replaces collection with partial collection', function () { table = new TableViewFallback(options); spyOn(TableViewFallback.prototype, 'initialize'); expect(table.collection.length).toEqual(6); }); }); });
if (typeof(mob) == "undefined") { mob = []; } mob["addcap"] = function( scene, nexus, mob, id, selfid ) { this.return = ( (nexus[id].maxCap == nexus[id].Cap)? true : false ); nexus[id].Cap = Math.min( nexus[id].maxCap, nexus[id].Cap+1 ); scene.sound.play( "upgrade.mp3", "fx", 0.5 ); } mob["addcap"].prototype.notmob = true; mob["addcap"].prototype.cost = 200; mob["addcap"].prototype.name = "+1 Mob Cap";
/* * Globals */ var app = app || {}; $(document).ready(function () { $('.fa-bars').click(function () { $("#container").toggleClass("sidebar-closed"); }); app.times = [ { 'zone': 'EST', 'time': '1pm', 'next': 'CST' }, { 'zone': 'CST', 'time': '12pm', 'next': 'MST' }, { 'zone': 'MST', 'time': '11am', 'next': 'PST' }, { 'zone': 'PST', 'time': '10am', 'next': 'EST' } ]; /* toggle between timezones */ $('#when').click(function () { var zone = $('#when .zone').text(); // lookup replacement info var current = _.find(app.times, { 'zone': zone }); var next = _.find(app.times, { 'zone': current.next }); // update page $('#when .zone').html(next.zone); $('#when .time').html(next.time); }); }); $(function() { function responsiveView() { var wSize = $(window).width(); if (wSize <= 768) { $('#container').addClass('sidebar-closed'); } if (wSize > 768) { $('#container').removeClass('sidebar-closed'); } } $(window).on('load', responsiveView); $(window).on('resize', responsiveView); });
window.onload = function () { let gap = 0; let carousel = document.getElementById("carousel"), content = document.getElementById("content"), next = document.getElementById("next"), prev = document.getElementById("prev"), width = carousel.offsetWidth; //condition for sliding right side and to display or not the next button// if (next) { next.addEventListener("click", e => { carousel.scrollBy(width, 0); if (carousel.scrollWidth !== 0) { prev.style.display = "flex"; } if (content.scrollWidth - width - gap <= carousel.scrollLeft + width) { next.style.display = "none"; } }); } //condition for sliding left side and to display or not the previous button// if (prev) { prev.addEventListener("click", e => { carousel.scrollBy(-(width), 0); if (carousel.scrollLeft - width - gap <= 0) { prev.style.display = "none"; } if (!content.scrollWidth - width - gap <= carousel.scrollLeft + width) { next.style.display = "flex"; } }); } //Whenever we resize the window it will change the width of carousel// window.onresize = function() { if (carousel) { window.addEventListener("resize", e => (width = carousel.offsetWidth)); console.log(width); } } }
const DissplayTodos=(props)=>{ const {todos,deleteHandle,handleComplete}=props; return( <>{ todos.map( (todo)=>{ return(<div className="todo-item" key={todo.id}> <p className={todo.isCompleted ? "text-comleted" : ""}>{todo.text}</p> <div className="btn-item"> <button className="btn" onClick={()=>{deleteHandle(todo.id)}}>delete</button> <button className="btn" onClick={()=>{handleComplete(todo.id)}}> {todo.isCompleted ? "Undo" : "Complete"}{" "}</button> </div> </div>) } ) }</> ) }; export default DissplayTodos
import React from 'react'; import './App.css'; import Countries from "./Countries"; const App = () => { return ( <div className="App"> <h1>Where in the World?</h1> <Countries /> </div> ); } export default App;
//导入第三方模块 const express = require("express"); const bcrypt = require("bcryptjs"); const formidable = require("formidable"); const { resolve } = require('path'); //导入自己的模块 const db = require("./db.js"); const readFile = require("./readfile.js"); const router = express.Router(); //设置开放文件夹的路径 const dir = __dirname; //给出加密种子 const salt = '$2a$10$avJpn7JMVNCBm7mHxHiMlu'; router.all('/public/*', function (req, res) { readFile.readfile(dir+req.url) .then(function (data) { res.send(data); }) .catch(function (err) { res.send('找不到数据!'); }); }); router.get('/', function (req, res) { let deviceAgent = req.headers["user-agent"].toLowerCase(); let agentID = deviceAgent.match(/(iphone|ipod|ipad|android)/); if(agentID){ readFile.readfile(dir+'/public/phone/index.html') .then(function (data) { res.send(data); }) .catch(function (err) { res.send('找不到页面!'); }); }else{ readFile.readfile(dir+'/public/build/index.html') .then(function (data) { res.send(data); }) .catch(function (err) { res.send('找不到页面!'); }); } }); //登录 router.post('/api/login', function (req, res) { let resm = {status:0, message:'error'}; let password = bcrypt.hashSync(req.body.password,salt); db.querydb('select count,name,tel,email,sex,birthday,touxiang from user where count = '+req.body.count+' and password = "'+password+'" limit 1') .then((data)=>{ if (data.length === 1){ req.session.user = data[0]; resm.user = data[0]; resm.status = 1; resm.message = 'success'; } res.send(resm); }) .catch((error)=>{ res.send(resm); }) }); //检查是否登录 router.get('/api/islogin', function (req, res) { let resm = {status:0, message:'未登录'}; if (req.session.user){ resm.status = 1; resm.message = '已登录'; resm.user = req.session.user; } res.send(resm); }); //退出登录 router.get('/api/logout', function (req, res) { let resm = {status:1, message:'退出成功!'}; req.session.user = null; res.send(resm); }); //检查某个账户是否已经注册 router.get('/api/isregist', function (req, res) { let resm = {status:0, message:'该账户已经被注册!'}; db.querydb('select count(count) as count from user where count = '+req.query.count) .then(data=>{ if (data[0].count === 0){ resm.status = 1; resm.message = '允许注册该账户!'; } res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //注册 router.post('/api/regist', function (req, res) { let resm = {status:0, message:'输入信息不符合规则!'}; let xinxi = req.body; //数据验证 if ( !xinxi.count || xinxi.count.length<5 || xinxi.count.length>11 || !xinxi.name || xinxi.name.length>7 || !xinxi.password || xinxi.password.length<6 || xinxi.password.length>20 || !['男','女'].includes(xinxi.sex) || !xinxi.tel || xinxi.tel.length>11 ){ res.send(resm); return; } xinxi.password = bcrypt.hashSync(xinxi.password,salt);//对密码加密 db.updatedb(db.creatInsertSql('user', xinxi)) .then(data=>{ if (data.affectedRows === 1){ resm.status = 1; resm.message = '注册成功!'; //添加一条欢迎信息 return db.updatedb('insert into message (sender,resever,content,time,isread) VALUES (111111,'+ xinxi.count+',"【欢迎使用】 欢迎 '+xinxi.name+' 来到嘻苑!该网站可以使您轻松的写出各种样式的文章!点击(新苑)发表一篇自己的文章吧!","'+ new Date().format('yyyy-MM-dd hh:mm:ss')+'","未读")') } else throw new Error('注册失败!'); }) .then(data=>{ res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //处理头像 router.post('/api/touxiang',function (req, res) { var form = new formidable.IncomingForm(); form.encoding = 'utf-8'; form.uploadDir = "./public/touxiang"; form.keepExtensions = true;//保留后缀 form.maxFieldsSize = 20 * 1024 * 1024; //处理图片 form.parse(req, function (err, fields, files) { var resm = {status:1,message:'上传图片成功!',path:''}; if (err){ resm.status = 0; resm.message = '上传图片失败!'; return res.send(JSON.stringify(resm)); } resm.path = files.touxiang.path; res.send(JSON.stringify(resm)); }); }); //用户修改信息 router.post('/api/updateuser', function (req, res) { let resm = {status:0, message:'输入信息不符合规则!'}; let xinxi = req.body; //数据验证 if (!xinxi.count || (xinxi.name && xinxi.name.length>7) || (xinxi.sex && !['男','女'].includes(xinxi.sex)) || (xinxi.tel && xinxi.tel.length>11)){ res.send(resm); return; } db.updatedb(db.creatUpdateSql('user',xinxi,['count'])+' limit 1') .then(data=>{ if (data.affectedRows === 1){ resm.status = 1; resm.message = '修改信息成功!'; //修改保存在session中的数据 for (let key in xinxi){ req.session.user[key] = xinxi[key]; } } res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //用户修改密码 router.post('/api/updatepassword', function (req, res) { let resm = {status:0, message:'输入信息不符合规则!'}; if (req.body.password !== req.body.confirmPassword || req.body.password === req.body.oldPassword){ res.send(resm); return; } db.updatedb('update user set password = "'+bcrypt.hashSync(req.body.password,salt)+ '" where count="'+req.body.count+'" and password="'+bcrypt.hashSync(req.body.oldPassword,salt)+'" limit 1') .then(data=>{ if (data.affectedRows === 1){ resm.status = 1; resm.message = '修改成功!'; } else { resm.message = '密码错误!'; } res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //用于检查某个访问地址是否已经存在 router.get('/api/availableurl', function (req, res) { let resm = {status:0, message:'输入信息不符合规则!'}; let xinxi = req.query; if (!xinxi.count || !xinxi.url || !/^[a-zA-Z0-9]{4,23}$/.test(xinxi.url)){ res.send(resm); return; } db.querydb('select count(id) as count from page where usercount='+xinxi.count+' and url="'+xinxi.url+'"') .then(data=>{ if (data[0].count === 0){ resm.status = 1; resm.message = '该地址可用!'; } else { resm.message = '该地址已经被使用过了!'; } res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //用于查询显示哪些组件 router.get('/api/showcomponent', function (req, res) { let resm = {status:0, message:'获取组件信息失败!'}; if (req.query.micorkey){ //表示获取某个组件的信息 db.querydb('select * from microapp where micorkey = "'+req.query.micorkey+'" limit 1') .then(data=>{ resm.data = data; resm.status = 1; resm.message = '获取成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); return; } // 获取到某个用户的所有组件及其组件的分组信息 if (!req.query.count){ res.send(resm); return; } Promise.all([db.querydb('select * from microapp where looker = "base"'), db.querydb('SELECT micorgroup.groupname, microapp.* from micorgroup LEFT JOIN' + ' microapp on micorgroup.micorid=microapp.id where usercount="'+req.query.count+'"')]) .then(data=>{ const resData = {'基础样式': data[0]}; data[1].forEach(value=>{ if (!resData[value.groupname]){ resData[value.groupname] = [value]; } else { resData[value.groupname].push(value); } }); resm.data = resData; resm.status = 1; resm.message = '获取成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }) }); //用于搜索组件 router.get('/api/serchmicor', function (req, res) { let resm = {status:0, message:'搜索失败!'}; if (!req.query.serchText || !req.query.count){ res.send(resm); return; } const st = req.query.serchText; db.querydb('select * from microapp WHERE looker != "base" and ' + '(micorkey like "%'+st+'%" or micorname like "%'+st+'%" or micordis like "%'+st+'%")') .then(data=>{ resm.status = 1; resm.message = '查询成功!'; resm.data = data.filter(value=>{ if (!value.looker || value.looker.split(',').includes(req.query.count)) return true; return false; }); res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //用于添加组件到自己的显示栏中 router.post('/api/addmicorgroup', function (req, res) { let resm = {status:0, message:'参数错误!'}; let xinxi = req.body; if (!xinxi.usercount || !xinxi.groupname || !xinxi.micorid || !(xinxi.micorid instanceof Array) || xinxi.micorid.length === 0){ res.send(resm); return; } xinxi.time = new Date().format('yyyy-MM-dd hh:mm:ss'); const values = xinxi.micorid.map(item=>[xinxi.usercount, xinxi.groupname, item, xinxi.time]); db.insertAll('INSERT INTO micorgroup(`usercount`,`groupname`,`micorid`, `time`) VALUES ?', values) .then(data=>{ if (data.affectedRows > 0){ resm.status = 1; resm.message = '添加成功!'; } res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //用于删除某个分组 router.post('/api/deletemicorgroup', function (req, res) { let resm = {status:0, message:'参数错误!'}; let xinxi = req.body; if (!xinxi.usercount || !xinxi.groupname || !xinxi.action){ res.send(resm); return; } if (xinxi.action === '直接删除'){ db.updatedb('delete from micorgroup where usercount="'+xinxi.usercount+ '" and groupname="'+xinxi.groupname+'"') .then(data=>{ if (data.affectedRows > 0){ resm.status = 1; resm.message = '删除成功'; } res.send(resm); }) .catch(error=>{ res.send(resm); }) } else { const moveto = xinxi.action.split(' ')[1]; db.updatedb('update micorgroup set groupname="'+moveto+'" where usercount="' +xinxi.usercount+'" and groupname="'+xinxi.groupname+'"') .then(data=>{ if (data.affectedRows > 0){ resm.status = 1; resm.message = '移动成功'; } res.send(resm); }) .catch(error=>{ res.send(resm); }) } }); //用于删除某个样式 router.post('/api/deletesiglemicor', function (req, res) { let resm = {status:0, message:'参数错误!'}; let xinxi = req.body; if (!xinxi.usercount || !xinxi.groupname || !xinxi.action || !xinxi.micorid){ res.send(resm); return; } if (xinxi.action === '直接删除'){ db.updatedb('delete from micorgroup where usercount="'+xinxi.usercount+ '" and groupname="'+xinxi.groupname+'" and micorid='+xinxi.micorid+' limit 1') .then(data=>{ if (data.affectedRows > 0){ resm.status = 1; resm.message = '删除成功'; } res.send(resm); }) .catch(error=>{ res.send(resm); }) } else { const moveto = xinxi.action.split(' ')[1]; db.updatedb('update micorgroup set groupname="'+moveto+'" where usercount="' +xinxi.usercount+'" and groupname="'+xinxi.groupname+'" and micorid='+xinxi.micorid+' limit 1') .then(data=>{ if (data.affectedRows > 0){ resm.status = 1; resm.message = '移动成功'; } res.send(resm); }) .catch(error=>{ res.send(resm); }) } }); //用户点击存稿 router.post('/api/savepage', function (req, res) { let xinxi = req.body; xinxi.status = '草稿'; saveNewPage(xinxi, res); }); //用户点击发表 router.post('/api/publish', function (req, res) { let xinxi = req.body; xinxi.status = '发表'; saveNewPage(xinxi, res); }); function saveNewPage(xinxi, res){ let resm = {status:0, message:'保存失败!'}; //当提供了页面的id时,表示已经保存过了,则使用更新语句来更新页面信息 if (xinxi.id){ db.updatedb(db.creatUpdateSql('page', xinxi, ['id'], ['componentData', 'pageid'])) .then(data=>{ return db.updatedb('delete from component where pageid = '+xinxi.id) }) .then(data=>{ let componentData = xinxi.componentData; let promiseArray = []; componentData.forEach((value,index)=>{ value.pageid = xinxi.id; value.cporder = index; promiseArray.push(db.updatedb(db.creatInsertSql('component', value))); }); return Promise.all(promiseArray) }) .then(value => { resm.status = 1; resm.data = {id:xinxi.id}; resm.message = '保存成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); return; } //当没有提供id时,表示是第一次保存,则需要先验证数据的正确性 if (!xinxi.usercount || !xinxi.url || !/^[a-zA-Z0-9]{4,23}$/.test(xinxi.url)){ res.send(resm); return; } //再去数据库中判断该地址是否已经被使用过了 db.querydb('select count(id) as count from page where usercount='+xinxi.usercount+' and url="'+xinxi.url+'"') .then(data=>{ if (data[0].count === 0){ return db.updatedb(db.creatInsertSql('page', xinxi, ['componentData'])) } throw new Error('该地址已经存在!'); }) .then(data=>{ if (data.affectedRows === 0){ throw new Error('保存失败!'); } let pageid = data.insertId; resm.data = {id:pageid}; let componentData = xinxi.componentData; let promiseArray = []; componentData.forEach((value,index)=>{ value.pageid = pageid; value.cporder = index; promiseArray.push(db.updatedb(db.creatInsertSql('component', value))); }); return Promise.all(promiseArray) }) .then(value => { resm.status = 1; resm.message = '保存成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); } //用于查询某个用户有哪些草稿 router.get('/api/querydraft', function (req, res) { let resm = {status:0, message:'查询失败!'}; const count = req.query.count; if (!count){ res.send(resm); return; } db.querydb('select * from page where usercount='+count+' and status="草稿" order by time desc') .then(data=>{ resm.status = 1; resm.message='查询成功!'; resm.data = data; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //用于查询某个发表了哪些文章包括(标题,描述,时间,点赞数,评论数) router.get('/api/queryuppage', function (req, res) { let resm = {status:0,message:'查询失败!'}; const count = req.query.count; const pagenum = 6; const page = req.query.page; if (!count){ res.send(resm); return; } db.querydb('select page.id,page.title,page.url,page.usercount,page.version,page.discription,page.time,' + 'count(DISTINCT agument.id) as agumentCount,count(DISTINCT pagelike.id) as likeCount ' + 'from page left join agument on agument.pageid=page.id LEFT JOIN pagelike on pagelike.pageid=page.id ' + 'where page.usercount='+count+' and page.status="发表" GROUP BY page.id order by page.time desc limit '+(page-1)*pagenum+','+pagenum) .then(data=>{ resm.data = data; resm.status = 1; resm.message = '查询成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //用于查询某个人发表了哪些评论包括(这些评论的文章信息) router.get('/api/queryuagument', function (req, res) { let resm = {status:0,message:'查询失败!'}; const count = req.query.count; const pagenum = 6; const page = req.query.page; if (!count){ res.send(resm); return; } db.querydb('select agument.*, user.name, user.touxiang from agument left JOIN user on agument.usercount=user.count' + ' where agument.usercount='+count+' ORDER BY agument.time desc limit '+(page-1)*pagenum+','+pagenum) .then(data=>{ resm.data = data; let pageids = Array.from(data,item=>item.pageid).join(','); if (data.length === 0){ return new Promise(resolve => { resolve(1); }); } else { return db.querydb('select page.id,page.url,page.usercount,page.version,page.title,page.discription,page.time,user.name,' + 'count(DISTINCT agument.id) as agumentCount,count(DISTINCT pagelike.id) as likeCount ' + 'from page left join agument on agument.pageid=page.id LEFT JOIN pagelike on pagelike.pageid=page.id ' + 'LEFT JOIN user on user.count=page.usercount ' + 'where page.id in ('+pageids+') GROUP BY page.id'); } }) .then(data=>{ if (data !== 1){ resm.data.forEach(item=>{ let index = data.findIndex(indexv=>indexv.id===item.pageid); if (index===-1) throw new Error('查找对应id失败!'); item.pageInfo = data[index]; }); } resm.status = 1; resm.message = '查找成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //用于查询被关注的排行 router.get('/api/followtop', function (req, res) { let resm = {status:0, message:'查询失败!'}; const page = req.query.page||1; const pagenum = 10; db.querydb('select byfollowuc, count(id) as followCount from follow GROUP BY byfollowuc ORDER BY followCount desc limit '+(page-1)*pagenum+','+pagenum) .then(data=>{ let follows = Array.from(data,value=>value.byfollowuc).join(','); resm.data = data; if (data.length === 0){ return new Promise(resolve => { resolve(1); }); } else { return Promise.all([db.querydb('select count,sex,name,touxiang from user where count in ('+follows+')'), db.querydb('select usercount,count(id) as pageCount from page where usercount in ('+follows+') and status="发表" GROUP BY usercount'), db.querydb('select usercount,count(id) as agumentCount from agument where usercount in ('+follows+') GROUP BY usercount'), db.querydb('select page.usercount,count(pagelike.id) as likeCount from page,pagelike where page.usercount in ('+follows+')' + ' and page.status="发表" and page.id=pagelike.pageid GROUP BY page.usercount')]); } }) .then(values=>{ if (values !== 1){ resm.data.forEach(item=>{ let index = values[0].findIndex(vi=>vi.count===item.byfollowuc); item.userInfo = values[0][index]; index = values[1].findIndex(vi=>vi.usercount===item.byfollowuc); if (index === -1) item.pageCount = 0; else item.pageCount = values[1][index].pageCount; index = values[2].findIndex(vi=>vi.usercount===item.byfollowuc); if (index === -1) item.agumentCount = 0; else item.agumentCount = values[2][index].agumentCount; index = values[3].findIndex(vi=>vi.usercount===item.byfollowuc); if (index === -1) item.likeCount = 0; else item.likeCount = values[3][index].likeCount; }); } resm.status = 1; resm.message = '查询成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //用于查询某人被哪些人关注了包括(这些人的发表文章数,被关注数,评论数,收获的喜欢数) router.get('/api/queryubyfollow', function (req, res) { let resm = {status:0,message:'查询失败!'}; const count = req.query.count; const pagenum = 10; const page = req.query.page; if (!count){ res.send(resm); return; } db.querydb('select * from follow where byfollowuc='+count+' ORDER BY time DESC limit '+(page-1)*pagenum+','+pagenum) .then(data=>{ let follows = Array.from(data,value=>value.followuc).join(','); resm.data = data; if (data.length === 0){ return new Promise(resolve => { resolve(1); }); } else { return Promise.all([db.querydb('select count,sex,name,touxiang from user where count in ('+follows+')'), db.querydb('select usercount,count(id) as pageCount from page where usercount in ('+follows+') and status="发表" GROUP BY usercount'), db.querydb('select byfollowuc,count(followuc) as followCount from follow where byfollowuc in ('+follows+') GROUP BY byfollowuc'), db.querydb('select usercount,count(id) as agumentCount from agument where usercount in ('+follows+') GROUP BY usercount'), db.querydb('select page.usercount,count(pagelike.id) as likeCount from page,pagelike where page.usercount in ('+follows+')' + ' and page.status="发表" and page.id=pagelike.pageid GROUP BY page.usercount')]); } }) .then(values=>{ if (values !== 1){ resm.data.forEach(item=>{ let index = values[0].findIndex(vi=>vi.count===item.followuc); item.userInfo = values[0][index]; index = values[1].findIndex(vi=>vi.usercount===item.followuc); if (index === -1) item.pageCount = 0; else item.pageCount = values[1][index].pageCount; index = values[2].findIndex(vi=>vi.byfollowuc===item.followuc); if (index === -1) item.followCount = 0; else item.followCount = values[2][index].followCount; index = values[3].findIndex(vi=>vi.usercount===item.followuc); if (index === -1) item.agumentCount = 0; else item.agumentCount = values[3][index].agumentCount; index = values[4].findIndex(vi=>vi.usercount===item.followuc); if (index === -1) item.likeCount = 0; else item.likeCount = values[4][index].likeCount; }); } resm.status = 1; resm.message = '查询成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //用于删除某一篇文章(包括草稿,发表等) router.get('/api/deletepage', function (req, res) { let resm = {status:0, message:'删除失败!'}; const id = req.query.id; if (!id){ res.send(resm); return; } db.updatedb('delete from page where id='+id+' limit 1') .then(data=>{ if (data.affectedRows === 1){ resm.status = 1; resm.message = '删除成功!'; } res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //用于查询整个页面(根据页面的id,包括页面的组件) router.get('/api/querypage', function (req, res) { let resm = {status:0,message:'查询失败!'}; const id = req.query.id; if (!id){ res.send(resm); return; } Promise.all([db.querydb('select * from page where id = '+id+' limit 1'), db.querydb('select * from component where pageid = '+id+' group by cporder')]) .then(value=>{ let data = value[0][0]; //去掉值为null的键值对,以防传送到前端时null变成字符串'null' for (let key in data){ if (data[key] === null) delete data[key]; } value[1].forEach(dv=>{ for (let key in dv){ if (dv[key] === null) delete dv[key]; } }); data.componentData = value[1]; resm.status = 1; resm.message = '查询成功!'; resm.data = data; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //用于查询整个页面(根据页面的id,包括页面的组件, 作者信息) router.get('/api/querypageandwriter', function (req, res) { let resm = {status:0,message:'查询失败!'}; const id = req.query.id; if (!id){ res.send(resm); return; } db.querydb('select * from page where id = '+id+' limit 1') .then(data=>{ if (data[0].status === '禁止'){ resm.data = '该文章已被禁止,无法查看!'; resm.status = 1; resm.message = '查询成功!'; throw new Error('该文章已被禁止'); } if (data[0].lookuser === 'online' && !req.query.count){ resm.data = '该文章需要登录才能看,请先登录!'; resm.status = 1; resm.message = '查询成功!'; throw new Error('登录才能看'); } if (data[0].lookuser === 'onlyme' && req.query.count !== data[0].usercount){ resm.data = '您没有权限看这篇文章!'; resm.status = 1; resm.message = '查询成功!'; throw new Error('无权限查看文章'); } //去掉值为null的键值对,以防传送到前端时null变成字符串'null' for (let key in data[0]){ if (data[0][key] === null) delete data[0][key]; } resm.data = data[0]; return Promise.all([ db.querydb('select * from component where pageid = '+id+' group by cporder'), db.querydb('select usercount from pagelike where pageid = '+id), db.querydb('select agument.*,user.name,user.touxiang from agument,user where pageid='+id+' and user.count=agument.usercount ORDER BY agument.time DESC limit 6')]) }) .then(value=>{ //去掉值为null的键值对,以防传送到前端时null变成字符串'null' value[0].forEach(dv=>{ for (let key in dv){ if (dv[key] === null) delete dv[key]; } }); resm.data.componentData = value[0]; resm.data.likes = []; value[1].forEach(value=>{ resm.data.likes.push(value.usercount); }); resm.aguments = value[2]; //为查询评论的评论准备数据 let parentids = '('; value[2].forEach(value=>{ parentids += (value.id+','); }); parentids = parentids.substring(0,parentids.length-1)+')'; let promiseArray = [db.querydb('select count,name,touxiang from user where count='+resm.data.usercount+' limit 1'), db.querydb('select version from page where usercount='+resm.data.usercount+' and url="'+resm.data.url+'" and status="发表"'), db.querydb('select followuc from follow where byfollowuc='+resm.data.usercount)]; if (value[2].length > 0)//若有评论则去查询评论的子评论 promiseArray.push(db.querydb('select childagu.*,user.name,user.touxiang from childagu,user where parentid in '+parentids+' and user.count=childagu.usercount ORDER BY time ASC')); return Promise.all(promiseArray) }) .then(data=>{ if (data[0].length === 0 || data[1].length === 0){ throw new Error('查询失败'); } resm.writer = data[0][0]; resm.versions = []; data[1].forEach(value=>{ resm.versions.push(value.version); }); resm.writer.follows = []; data[2].forEach(value=>{ resm.writer.follows.push(value.followuc); }); //若有查询子评论,则将子评论添加到对应的评论下 data[3] && data[3].forEach(value=>{ let index = resm.aguments.findIndex(aguvalue => { return aguvalue.id === value.parentid; }); if (!resm.aguments[index].childagus) resm.aguments[index].childagus = []; resm.aguments[index].childagus.push(value); }); resm.status = 1; resm.message = '查询成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //用于查询整个页面(根据页面的usercount,url,version,包括页面的组件, 作者信息) router.get('/api/querypagebyversion', function (req, res) { let resm = {status:0,message:'查询失败!'}; const usercount = req.query.usercount; const url = req.query.url; const version = req.query.version; if (!usercount || !url){ res.send(resm); return; } let sql = ''; if (!version){ sql = 'select * from page where usercount = '+usercount+ ' and url="'+url+'" order by version desc limit 1'; } else { sql = 'select * from page where usercount = '+usercount+ ' and url="'+url+'" and version='+version+' limit 1'; } db.querydb(sql) .then(data=>{ if (data[0].length === 0){ throw new Error('查询失败!'); } if (data[0].status === '禁止'){ resm.data = '该文章已被禁止,无法查看!'; resm.status = 1; resm.message = '查询成功!'; throw new Error('该文章已被禁止'); } if (data[0].lookuser === 'online' && !req.query.count){ resm.data = '该文章需要登录才能看,请先登录!'; resm.status = 1; resm.message = '查询成功!'; throw new Error('登录才能看'); } if (data[0].lookuser === 'onlyme' && req.query.count !== data[0].usercount){ resm.data = '您没有权限看这篇文章!'; resm.status = 1; resm.message = '查询成功!'; throw new Error('无权限查看文章'); } //去掉值为null的键值对,以防传送到前端时null变成字符串'null' for (let key in data[0]){ if (data[0][key] === null) delete data[0][key]; } resm.data = data[0]; return Promise.all([ db.querydb('select count,name,touxiang from user where count='+usercount+' limit 1'), db.querydb('select version from page where usercount='+usercount+' and url="'+url+'" and status="发表"'), db.querydb('select followuc from follow where byfollowuc='+usercount)]) }) .then(value => { if (value[0].length === 0 || value[1].length === 0){ throw new Error('查询失败!'); } resm.writer = value[0][0]; resm.writer.follows = []; value[2].forEach(value=>{ resm.writer.follows.push(value.followuc); }); resm.versions = []; value[1].forEach(value=>{ resm.versions.push(value.version); }); return Promise.all([db.querydb('select * from component where pageid = '+resm.data.id+' group by cporder'), db.querydb('select usercount from pagelike where pageid = '+resm.data.id), db.querydb('select agument.*,user.name,user.touxiang from agument,user where pageid='+resm.data.id+' and user.count=agument.usercount ORDER BY agument.time DESC limit 6')]) }) .then(value => { value[0].forEach(dv=>{ for (let key in dv){ if (dv[key] === null) delete dv[key]; } }); resm.data.componentData = value[0]; resm.data.likes = []; value[1].forEach(value=>{ resm.data.likes.push(value.usercount); }); resm.aguments = value[2]; //为查询评论的评论准备数据 let parentids = '('; value[2].forEach(value=>{ parentids += (value.id+','); }); parentids = parentids.substring(0,parentids.length-1)+')'; //若该页面有评论,则进行子评论的查询,否则不查询 if (value[2].length > 0) return db.querydb('select childagu.*,user.name,user.touxiang from childagu,user where parentid in '+parentids+' and user.count=childagu.usercount ORDER BY time ASC') else{ return new Promise(resolve => { resolve(1); }) } }) .then(data=>{ if (data !== 1){//若有进行子评论的查询,则将查询结果添加到对应的评论中 data.forEach(value=>{ let index = resm.aguments.findIndex(aguvalue => { return aguvalue.id === value.parentid; }); if (!resm.aguments[index].childagus) resm.aguments[index].childagus = []; resm.aguments[index].childagus.push(value); }); } resm.status = 1; resm.message = '查询成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //用于查询首页的数据(每个文章的分类前五篇) router.get('/api/categorytopfive', function (req, res) { let resm = {status:0, message:'查询失败!'}; db.querydb('select a.*,t.likeCount from page a LEFT JOIN (select page.id, count(pagelike.id) as likeCount ' + 'from page,pagelike where pageid=page.id GROUP BY page.id) t on a.id = t.id where a.status="发表" and ' + '5 > (select count(page.id) from page LEFT JOIN (select page.id, count(pagelike.id) as likeCount ' + 'from page,pagelike where pageid=page.id GROUP BY page.id) ts on page.id = ts.id where page.category = a.category' + ' and page.status="发表" and ts.likeCount > t.likeCount) order by a.category,t.likeCount desc') .then(data=>{ let ids = Array.from(data, v => v.id).join(','); let counts = Array.from(data, v => v.usercount).join(','); resm.data = data; if (data.length === 0){ return new Promise(resolve => { resolve(1); }); } return Promise.all([db.querydb('select pageid, count(id) as agumentCount from agument where pageid in ('+ids+') group by pageid'), db.querydb('select count, name from user where count in ('+counts+')')]); }) .then(values=>{ if (values !== 1){ let index = -1; resm.data.forEach(item=>{ index = values[0].findIndex(v=>v.pageid === item.id); if (index === -1) item.agumentCount = 0; else item.agumentCount = values[0][index].agumentCount; index = values[1].findIndex(v=>v.count === item.usercount); item.name = values[1][index].name; }); } resm.status = 1; resm.message = '查询成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //根据分类和关键字分页搜索页面(每一页最多10条数据) router.get('/api/serchpage', function (req, res) { let resm = {status:0,message:'搜索失败!'}; let category = req.query.category||'';//分类的取值 let text = req.query.text||'';//搜索文本,会去文章title或discription中比对 const page = parseInt(req.query.page);//查询的页数 let order = req.query.order;//按什么方式排序,有orderArray中的值可取,若不是则默认为time const orderArray = ['likeCount','agumentCount','page.time']; let desc = req.query.desc==='asc'?'asc':'desc';//表示升序还是降序,默认升序 const pagenum = 10;//表示一页最多可以获取到10条数据 const start = (page-1)*pagenum; if (category){ if (category === '所有分类') category = ''; else category = ' and page.category="'+category+'" '; } if (text){ text = ' and (page.title like "%'+text+'%" or page.discription like "%'+text+'%") ' } if (!orderArray.includes(order)){ order = 'page.time' } let sql = 'select page.id,user.name,page.title,page.url,page.usercount,page.version,page.discription,page.time,' + ' count(DISTINCT agument.id) as agumentCount,count(DISTINCT pagelike.id) as likeCount ' + ' from page left join agument on agument.pageid=page.id LEFT JOIN pagelike on pagelike.pageid=page.id ,user' + ' where page.status="发表"'+category+text+' and user.count=page.usercount GROUP BY page.id order by '+ order+' '+desc+' limit '+start+','+pagenum; db.querydb(sql) .then(data=>{ resm.data = data; resm.status = 1; resm.message = '搜索成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //根据页面的id查询对该页面的更多评论 router.get('/api/loadmoreagument', function (req, res) { let resm = {status:0, message:'查询失败!'}; const pagemun = 6;//一页查询6条数据 const id = req.query.id; const page = req.query.page; const offset = req.query.offset; const start = parseInt((page-1)*pagemun)+parseInt(offset); db.querydb('select agument.*,user.name,user.touxiang from agument,user where pageid='+id+ ' and user.count=agument.usercount ORDER BY agument.time DESC limit '+start+','+pagemun) .then(data=>{ resm.aguments = data; //为查询评论的评论准备数据 let parentids = '('; data.forEach(value=>{ parentids += (value.id+','); }); parentids = parentids.substring(0,parentids.length-1)+')'; //若该页面还有评论,则进行子评论的查询,否则不查询 if (data.length > 0) return db.querydb('select childagu.*,user.name,user.touxiang from childagu,user where parentid in '+parentids+' and user.count=childagu.usercount ORDER BY time ASC') else{ return new Promise(resolve => { resolve(1); }) } }) .then(data=>{ if (data !== 1){//若有进行子评论的查询,则将查询结果添加到对应的评论中 data.forEach(value=>{ let index = resm.aguments.findIndex(aguvalue => { return aguvalue.id === value.parentid; }); if (!resm.aguments[index].childagus) resm.aguments[index].childagus = []; resm.aguments[index].childagus.push(value); }); } resm.status = 1; resm.message = '查询成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //用于查询发表过的文章(根据发表人的账户,不包括页面的组件) router.get('/api/querypublish', function (req, res) { let resm = {status:0,message:'查询失败!'}; const count = req.query.count; if (!count){ res.send(resm); return; } db.querydb('select * from page where usercount='+count+' and status="发表" order by time desc') .then(data=>{ resm.status = 1; resm.message = '查询成功!'; resm.data = data; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //用于对发表的页面重新编辑(即生成一个该地址访问的最高版本,但是内容复制所点击编辑的那一条数据) router.get('/api/updatepublish', function (req, res) { let resm = {status:0, message:'更新失败!'}; const id = req.query.id; let newid = null; db.querydb('select page.version as maxv, t.* from page,(select * from page where id = '+id+') t ' + 'where page.usercount=t.usercount and page.url=t.url ORDER BY page.version desc LIMIT 1') .then(data=>{ if (data.length === 0){ throw new Error('查询失败!'); } let newData = data[0]; newData.version = newData.maxv+1; newData.time = new Date().format('yyyy-MM-dd hh:mm:ss'); newData.status = '草稿'; return Promise.all([db.updatedb(db.creatInsertSql('page',newData,['maxv','id'])), db.querydb('select * from component where pageid='+id)]); }) .then(data=>{ if (data[0].affectedRows === 0){ throw new Error('插入失败!'); } newid = data[0].insertId; let componentData = data[1]; let promiseArray = []; componentData.forEach((value)=>{ value.pageid = newid; promiseArray.push(db.updatedb(db.creatInsertSql('component', value, ['cpid']))); }); return Promise.all(promiseArray) }) .then(data=>{ resm.status = 1; resm.message = '新建成功!'; resm.id = newid; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //用于修改某个页面的可见性 router.get('/api/updatelookuser', function (req, res) { let resm = {status:0, message:'修改失败!'}; db.updatedb('update page set lookuser="'+req.query.lookuser+'" where id='+req.query.id) .then(data=>{ resm.status = 1; resm.message = '修改成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //对页面点赞 router.get('/api/addpagelike', function (req, res) { let resm = {status:0, message:'点赞失败!'}; const pageid = req.query.pageid; const usercount = req.query.usercount; if (!pageid || !usercount){ res.send(resm); return; } Promise.all([db.querydb('select usercount from page where id = '+pageid+' limit 1'), db.querydb('select count(id) as count from pagelike where pageid = '+pageid+' and usercount='+usercount)]) .then(data=>{ //自己不能给自己写的文章点赞,并且同一个人不能对同一篇文章重复点赞 if (data[0].length === 0 || data[0][0].usercount == usercount || data[1][0].count !== 0){ throw new Error('点赞失败!'); } return db.updatedb('insert into pagelike (pageid, usercount, time) values ('+pageid+','+ usercount+',"'+(new Date()).format('yyyy-MM-dd hh:mm:ss')+'")') }) .then(data=>{ if (data.affectedRows === 1){ resm.status = 1; resm.message = '点赞成功!'; } res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //关注某个人 router.get('/api/addfollow', function (req, res) { let resm = {status:0, message:'关注失败!'}; const byfollowuc = req.query.byfollowuc; const followuc = req.query.followuc; if (!byfollowuc || !followuc){ res.send(resm); return; } //自己不能关注自己 if (byfollowuc === followuc){ res.send(resm); return; } db.querydb('select count(id) as count from follow where byfollowuc='+byfollowuc+' and followuc='+followuc) .then(data=>{ //同一个人不能被另一个人重复关注 if (data[0].count !== 0){ throw new Error('关注失败!'); } return db.updatedb('insert into follow (byfollowuc, followuc, time) values ('+byfollowuc+','+ followuc+',"'+(new Date()).format('yyyy-MM-dd hh:mm:ss')+'")') }) .then(data=>{ if (data.affectedRows === 1){ resm.status = 1; resm.message = '关注成功!'; } res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //提交评论 router.post('/api/addagument', function (req, res) { let resm = {status:0, message:'提交评论失败!'}; let xinxi = req.body; if (!xinxi.pageid || !xinxi.usercount || !xinxi.content || xinxi.content.length>200){ res.send(resm); return; } xinxi.time = (new Date()).format('yyyy-MM-dd hh:mm:ss'); db.updatedb(db.creatInsertSql('agument',xinxi)) .then(data=>{ if (data.affectedRows === 1){ resm.status = 1; resm.message = '提交评论成功!'; resm.data = {id:data.insertId,time:xinxi.time}; } res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //提交评论的子评论 router.post('/api/addchildagu', function (req, res) { let resm = {status:0, message:'提交评论失败!'}; let xinxi = req.body; if (!xinxi.parentid || !xinxi.usercount || !xinxi.content || xinxi.content.length>200){ res.send(resm); return; } xinxi.time = (new Date()).format('yyyy-MM-dd hh:mm:ss'); db.updatedb(db.creatInsertSql('childagu',xinxi)) .then(data=>{ if (data.affectedRows === 1){ resm.status = 1; resm.message = '提交评论成功!'; resm.data = {id:data.insertId,time:xinxi.time}; } res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //查询某人的动态信息(包括名字,头像,文章数,关注数,评论数,总点赞数) router.get('/api/getaction', function (req, res) { let resm = {status:0,message:'获取失败!'}; const count = req.query.count; if (!count){ res.send(resm); return; } Promise.all([db.querydb('select name,touxiang,count from user where count='+count+' limit 1'), db.querydb('select count(id) as pageCount from page where usercount='+count+' and status="发表"'), db.querydb('select followuc from follow where byfollowuc='+count), db.querydb('select count(id) as agumentCount from agument where usercount='+count), db.querydb('select count(pagelike.id) as likeCount from page,pagelike where page.usercount='+count + ' and page.status="发表" and page.id=pagelike.pageid')]) .then(values=>{ let data = values[0][0]; data.pageCount = values[1][0].pageCount; data.follows = Array.from(values[2],v=>v.followuc); data.agumentCount = values[3][0].agumentCount; data.likeCount = values[4][0].likeCount; resm.status = 1; resm.message = '获取成功!'; resm.data = data; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //查询某用户与哪些用户互发过消息,并返回他们之间最后发的那一条消息 router.get('/api/getfirstmessage', function (req, res) { let resm = {status:0,message:'查询失败!'}; const count = req.query.count; if (!count){ res.send(resm); return; } Promise.all([db.querydb('select message.* from message, (select sender, max(time) as maxtime FROM message where resever='+count +' GROUP BY sender) as t where resever='+count+' and message.sender=t.sender and message.time = t.maxtime'), db.querydb('select message.* from message, (select resever, max(time) as maxtime FROM message where sender='+count +' GROUP BY resever) as t where sender='+count+' and message.resever=t.resever and message.time = t.maxtime'), db.querydb('select sender,count(id) as noread from message where resever='+count+' and isread="未读" GROUP BY sender')]) .then(values => { let index = -1; let usercount = '('; for (let i = 0; i < values[0].length; i++){ usercount = usercount+values[0][i].sender+','; //将未读的条数插入到对应的聊天信息里 index = values[2].findIndex(v=>v.sender === values[0][i].sender); if (index !== -1){ values[0][i].noread = values[2][index].noread; } //判断同一个人的接收和发送哪一个更靠后,只保留靠后的那一条信息 index = values[1].findIndex(v=>v && v.resever === values[0][i].sender); if (index !== -1){ if (new Date(values[1][index].time)>new Date(values[0][i].time)) values[0][i] = values[1][index]; delete values[1][index]; } } //给第一个去重 let data = []; values[0].forEach(v=>{ let index = data.findIndex(item=>item.sender===v.sender); if (index === -1) data.push(v); }); let data1 = []; values[1].forEach(v=>{ usercount = usercount+v.resever+','; let index = data1.findIndex(item=>item.resever===v.resever); if (index === -1) data1.push(v); }); data = [...data,...data1]; resm.data = data; usercount = usercount.substring(0,usercount.length-1)+')'; if (data.length === 0){ return new Promise(resolve => { resolve(1); }); } else { return db.querydb('select count,touxiang,name,sex from user where count in '+usercount); } }) .then(data=>{ if (data !== 1){ let index = -1; resm.data.forEach(item=>{ index = data.findIndex(v=>(v.count===item.sender || v.count===item.resever)); if (index === -1){ throw new Error('寻找失败!'); } item.muser = data[index]; }); } resm.status = 1; resm.message = '查询成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //根据两个账户,获取这两个账户的聊天信息 router.get('/api/getmessages', function (req, res) { let resm = {status:0,message:'查询失败!'}; const fcount = req.query.fcount; const lcount = req.query.lcount; const page = req.query.page; const offset = parseInt(req.query.offset); const pagenum = 20; const start = parseInt((page-1)*pagenum)+offset; if (!fcount || !lcount){ res.send(resm); return; } db.querydb('select * from message where (sender='+fcount+' and resever=' +lcount +') or (sender='+lcount+' and resever = '+fcount+ ') ORDER BY time desc limit '+start+','+pagenum) .then(data=>{ resm.data = data; resm.status = 1; resm.message = '查询成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //获取某个用户有多少条未读信息 router.get('/api/getnoreadmun', function (req, res) { let resm = {status:0,message:'查询失败!'}; const count = req.query.count; if (!count){ res.send(resm); return; } db.querydb('select count(id) as number from message where resever='+count+' and isread="未读"') .then(data=>{ resm.status = 1; resm.message = '获取成功!'; resm.number = data[0].number; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //让数据库将一个接收者对一个发送者的所有信息标记为已读 router.get('/api/markread', function (req, res) { let resm = {status:0,message:'修改失败!'}; const sender = req.query.sender; const resever = req.query.resever; if (!sender || !resever){ res.send(resm); return; } db.updatedb('update message set isread="已读" where sender='+sender+' and resever='+resever+' and isread="未读"') .then(data=>{ resm.status = 1; resm.message = '修改成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //让数据库将某一条信息标记为已读 router.get('/api/markreadbyid', function (req, res) { let resm = {status:0,message:'修改失败!'}; const id = req.query.id; if (!id){ res.send(resm); return; } db.updatedb('update message set isread="已读" where id='+id) .then(data=>{ resm.status = 1; resm.message = '修改成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //查询某人的基本信息(包括头像,名字,账号,性别) router.get('/api/userbaseinfo', function (req, res) { let resm = {status:0,message:'查询失败!'}; const count = req.query.count; if (!count){ res.send(resm); return; } db.querydb('select count,touxiang,name,sex from user where count = '+count) .then(data=>{ if (data.length === 0) throw new Error('查询失败'); resm.status = 1; resm.message = '查询成功!'; resm.data = data[0]; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //将没有保存的数据保存到数据库的临时保存表中 router.post('/api/savetemp', function (req, res) { let resm = {status:0, message:'保存失败'}; const usercount = req.body.usercount; const time = req.body.time; if (!usercount || !time){ res.send(resm); return; } db.querydb('select id from temp where usercount='+usercount+' limit 1') .then(data=>{ if (data.length === 0){ return db.updatedb(db.creatInsertSql('temp',req.body)); } else{ resm.id = data[0].id; return db.updatedb("update temp set componentData='"+req.body.componentData+"' , pageConfig='" +req.body.pageConfig+"' ,time='"+req.body.time+"' where id="+data[0].id); } }) .then(data=>{ if (data.affectedRows === 1){ resm.status = 1; resm.message = '保存成功!'; resm.id = resm.id || data.insertId; } res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //查询有没有未保存的数据 router.get('/api/queryhavetemp', function (req, res) { let resm = {status:0, message:'获取失败!'}; const usercount = req.query.usercount; if (!usercount){ res.send(resm); return; } db.querydb('select id from temp where usercount='+usercount+' limit 1') .then(data=>{ if (data.length !== 0){ resm.data = '有数据!'; } resm.status = 1; resm.message = '获取成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //根据用户的账户获取临时保存表中的临时数据(若有则获取数据,然后删除该记录,表示用户已经获取过了,没有没保存的数据) router.get('/api/querytemp', function (req, res) { let resm = {status:0, message:'获取失败!'}; const usercount = req.query.usercount; if (!usercount){ res.send(resm); return; } db.querydb('select * from temp where usercount='+usercount+' limit 1') .then(data=>{ if (data.length === 1){ //表示有没保存的数据 resm.data = data[0]; } resm.status = 1; resm.message = '获取成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //删除某人的临时保存数据 router.get('/api/deletetemp', function (req, res) { let resm = {status:0, message:'删除成功!'}; const usercount = req.query.usercount; if (!usercount){ res.send(resm); return; } db.updatedb('delete from temp where usercount='+usercount) .then(data=>{ resm.status = 1; resm.message = '删除成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //接收用户传来的网页图片 router.post('/api/images',function (req, res) { var form = new formidable.IncomingForm(); form.encoding = 'utf-8'; form.uploadDir = "./public/images"; form.keepExtensions = true;//保留后缀 form.maxFieldsSize = 20 * 1024 * 1024; //处理图片 form.parse(req, function (err, fields, files) { var resm = {status:1,message:'上传图片成功!',path:''}; if (err){ resm.status = 0; resm.message = '上传图片失败!'; return res.send(resm); } resm.path = files.file.path; res.send(resm); }); }); //用户反馈 router.post('/api/feedback', function (req, res) { let resm = {status:0, message:'反馈失败!'} const usercount = req.body.usercount; const type = req.body.type; const content = req.body.content; if (!usercount || !type || !content){ resm.message = '参数不足'; res.send(resm); return; } db.updatedb('insert into feedback (usercount,type,content,sendtime) values ('+ usercount+',"'+type+'","'+content+'","'+(new Date()).format('yyyy-MM-dd hh:mm:ss')+'")') .then(data=>{ if (data.affectedRows === 0) throw new Error('插入失败'); resm.status = 1; resm.message = '反馈成功!'; res.send(resm); }) .catch(error=>{ res.send(resm); }); }); //将router导出 module.exports = router;
import twc from '../../src/directives/twc'; import { twcOptions } from './mockOptions'; describe('Test tw directive', () => { let el; beforeEach(() => { el = document.createElement('div'); }); it('Should add default classes for custom card as v-twc="\'card\'"', () => { twc(twcOptions).bind(el, { value: 'card' }); twcOptions.card.classes.split(' ').forEach((c) => { expect(el.classList.contains(c)).toBeTruthy(); }); }); it("Should add multiple default classes as v-twc=\"['card', 'listItemCard' ]\"", () => { twc(twcOptions).bind(el, { value: ['card', 'listItemCard'] }); twcOptions.card.classes.split(' ').forEach((c) => { expect(el.classList.contains(c)).toBeTruthy(); }); twcOptions.listItemCard.classes.split(' ').forEach((c) => { expect(el.classList.contains(c)).toBeTruthy(); }); }); it("Should add modifiers as v-twc=\"{card: ['green', 'bordered']}\"", () => { twc(twcOptions).bind(el, { value: { card: ['green', 'bordered'] } }); twcOptions.card.classes.split(' ').forEach((c) => { expect(el.classList.contains(c)).toBeTruthy(); }); twcOptions.card.modifiers.green.split(' ').forEach((c) => { expect(el.classList.contains(c)).toBeTruthy(); }); twcOptions.card.modifiers.bordered.split(' ').forEach((c) => { expect(el.classList.contains(c)).toBeTruthy(); }); }); it("Should add default classes and modifiers as v-twc=\"['listItemCard', { card: ['green'] }]\"", () => { twc(twcOptions).bind(el, { value: ['listItemCard', { card: ['green', 'bordered'] }], }); twcOptions.listItemCard.classes.split(' ').forEach((c) => { expect(el.classList.contains(c)).toBeTruthy(); }); twcOptions.card.classes.split(' ').forEach((c) => { expect(el.classList.contains(c)).toBeTruthy(); }); twcOptions.card.modifiers.green.split(' ').forEach((c) => { expect(el.classList.contains(c)).toBeTruthy(); }); }); });
const { updateTopExperts } = require('utilities/operations/objectType'); const { ObjectType } = require('database').models; /** * Make any changes you need to make to the database here */ exports.up = async function up(done) { await updateTopExperts(); done(); }; /** * Make any changes that UNDO the up function side effects here (if possible) */ exports.down = async function down(done) { await ObjectType.updateMany({}, { $unset: { top_experts: '' } }); done(); };
lotus.controller("LoginController", ["$scope", "$http", "$window", function ($scope, $http, $window) { $scope.Login = {}; $scope.submit = function () { if ($scope.LoginForm.$valid) { $http.post("/LoginUser/", $scope.Login).then(function (data) { $.Notify({ caption: "Success!", content: "Successfully logged in!", type: 'success' }); $window.location = "/"; }, function (error) { $.Notify({ caption: "Failed to login!", content: error.data.Error, type: 'alert' }); }); } } }]);