text
stringlengths
7
3.69M
import React, { useEffect, useState } from "react"; import roomService from "../../services/roomService"; import userService from "../../services/userService"; import { roles, departments } from '../../utils/enums' import Loader from "../../common/Loader/Loader"; import { DialogActions, DialogContent, DialogTitle, Typography, Button, makeStyles } from "@material-ui/core"; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; import EditOutlinedIcon from '@material-ui/icons/EditOutlined'; import DeleteOutlineOutlinedIcon from '@material-ui/icons/DeleteOutlineOutlined'; import TextField from '@material-ui/core/TextField'; import InputLabel from '@material-ui/core/InputLabel'; import MenuItem from '@material-ui/core/MenuItem'; import FormHelperText from '@material-ui/core/FormHelperText'; import FormControl from '@material-ui/core/FormControl'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import Checkbox from '@material-ui/core/Checkbox'; import Select from '@material-ui/core/Select'; import SaveOutlinedIcon from '@material-ui/icons/SaveOutlined'; import ReplayOutlinedIcon from '@material-ui/icons/ReplayOutlined'; const useStyles = makeStyles(theme => ({ formGroup: { display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20, paddingRight: 20, '& > div': { margin: theme.spacing(1), width: '25ch', }, }, inputItems: { width: "70%" }, span: { color: "#0088bc" }, table: { maxWidth: 1400, maxHeight: "70vh" }, roomsDiv:{ display: "flex", flexFlow: "row wrap", alignItems: "flex-start", justifyContent: "center" } })); const Users = ({ onClose }) => { const classes = useStyles(); const [rooms, setRooms] = useState([]); // const [roles, setRoles] = useState([ // { label: "Admin", value: "Admin" }, // { label: "Manager", value: "Manager" }, // { label: "General Manager", value: "General Manager" }, // { label: "Staff", value: "Staff" }, // ]); // const [departments, setDepartment] = useState([ // { label: "Front Office", value: "Front Office" }, // { label: "Restaurant", value: "Restaurant" }, // { label: "Finance", value: "Finance" }, // { label: "Operations", value: "Operations" }, // { label: "House Keeping", value: "House Keeping" }, // { label: "IT", value: "IT" }, // ]); const [loading, setLoading] = useState(false); const [newDoc, setNewDoc] = useState({}); const [editingRow, setEditingRow] = useState({}); const [checkbox,setCheckbox]=useState(false); useEffect(() => { setLoading(true); fetchData(); }, []); const fetchData = async () => { const rooms = await userService.getUsers(); setRooms(rooms); setLoading(false); }; const handleFormSubmit = async (e) => { e.preventDefault(); setLoading(true); const res = await userService.addUser(newDoc); setLoading(false); if(res.status===201){ // setNewDoc({}) setLoading(true); fetchData() }else { console.log(res) // setNewDoc({}) alert("Bad Request") } } const handleInput = (e) => { setNewDoc({ ...newDoc, [e.target.name]:e.target.value }) } const handleEdit = (row) => { setEditingRow(row) console.log("row",row); } const handleUndo = () => { setEditingRow({}) } const handleUpdate = async () => { setLoading(true); const res = await userService.updateUser(editingRow); setLoading(false); if(res){ setEditingRow({}) setLoading(true); fetchData() } } const handleDelete = async (row) => { // return setLoading(true); const res = await userService.deleteUser(row); setLoading(false); if(res){ setLoading(true); fetchData() } } const handleInputChange = (e) => { setEditingRow({ ...editingRow, [e.target.name]:e.target.value }) } //Styles to Table Headers const tablestyles={ color:'#0088bc', fontWeight:"bold" } return ( <React.Fragment> <DialogTitle>User Management</DialogTitle> <DialogContent className={classes.roomsDiv}> <form className={classes.formGroup} autoComplete="off" onSubmit={handleFormSubmit}> <TextField required id="standard-required" label="Username" name="username" onChange={handleInput}/> <TextField required id="standard-required" label="Password" name="password" onChange={handleInput}/> <FormControl className={classes.formControl}> <InputLabel id="demo-simple-select-label">Department*</InputLabel> <Select labelId="demo-simple-select-label" id="demo-simple-select" required name="department" value={newDoc.department} onChange={handleInput} > {departments.map(el=><MenuItem value={el.value}>{el.label}</MenuItem>)} </Select> </FormControl> <FormControl className={classes.formControl}> <InputLabel id="demo-simple-select-label">Role*</InputLabel> <Select labelId="demo-simple-select-label" id="demo-simple-select" required name="role" value={newDoc.role} onChange={handleInput} > {roles.map(el=><MenuItem value={el.value}>{el.label}</MenuItem>)} </Select> </FormControl> <Button type="submit" variant="contained" style={{backgroundColor:"#0088bc",color:'white'}} > ADD </Button> </form> {loading && <Loader color="#0088bc" />} <TableContainer className={classes.table} component={Paper}> <Table className={classes.table} size="small" stickyHeader aria-label="sticky table"> <TableHead> <TableRow> <TableCell style={tablestyles}>ID</TableCell> <TableCell align="center" style={tablestyles}>Username</TableCell> <TableCell align="center" style={tablestyles}>Password</TableCell> <TableCell align="center" style={tablestyles}>Department</TableCell> <TableCell align="center" style={tablestyles}>Role</TableCell> <TableCell align="center" style={tablestyles}>Edit</TableCell> <TableCell align="center" style={tablestyles}>Delete</TableCell> </TableRow> </TableHead> <TableBody> {rooms.map((row,i) => ( <TableRow key={row._id}> <TableCell component="th" scope="row"> {i+1} </TableCell> <TableCell align="center">{row.username}</TableCell> {editingRow._id !== row._id && <TableCell align="center">{row.password}</TableCell>} {editingRow._id === row._id && <TableCell align="center"> <TextField required id="standard-required" label="Password" name="password" value={editingRow.password} onChange={handleInputChange}/> </TableCell>} {editingRow._id !== row._id && <TableCell align="center">{row.department}</TableCell>} {editingRow._id === row._id && <TableCell align="center"> <FormControl style={{width:"100%"}}> <InputLabel id="demo-simple-select-label">Department*</InputLabel> <Select labelId="demo-simple-select-label" id="demo-simple-select" required name="department" value={editingRow.department} onChange={handleInputChange} > {departments.map(el=><MenuItem value={el.value}>{el.label}</MenuItem>)} </Select> </FormControl> </TableCell>} {editingRow._id !== row._id && <TableCell align="center">{row.role}</TableCell>} {editingRow._id === row._id && <TableCell align="center"> <FormControl style={{width:"100%"}}> <InputLabel id="demo-simple-select-label">Role*</InputLabel> <Select labelId="demo-simple-select-label" id="demo-simple-select" required name="role" value={editingRow.role} onChange={handleInputChange} > {roles.map(el=><MenuItem value={el.value}>{el.label}</MenuItem>)} </Select> </FormControl> </TableCell>} {editingRow._id !== row._id && <TableCell align="center"><EditOutlinedIcon style={{cursor:"pointer"}} onClick={()=>handleEdit(row)}/></TableCell>} {editingRow._id === row._id && <TableCell align="center"> <ReplayOutlinedIcon style={{cursor:"pointer"}} onClick={handleUndo}/> <SaveOutlinedIcon style={{cursor:"pointer"}} onClick={handleUpdate}/> </TableCell>} <TableCell align="center"><DeleteOutlineOutlinedIcon style={{cursor:"pointer"}} onClick={()=>handleDelete(row)}/></TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> </DialogContent> </React.Fragment> ); }; export default Users;
'use strict'; (function() { var fbUtils = this.FbUtils = {}; function graphUrl(fbName) { return 'https://graph.facebook.com/' + fbName; } function appendToken(url, token) { return url + '&access_token=' + token; } function isLinkToFbAccount(link, fbName) { return link.indexOf(fbUtils.makeAccountLink(fbName)) === 0; } function messageContainsLink(post) { var lastIndexOfLink = post.link.length - 1; return post.message.indexOf(post.link[lastIndexOfLink] === '/' ? post.link.substring(0, lastIndexOfLink) : post.link) >= 0; } function fbStringToDate(dateString) { return new Date(dateString.replace(/\+0000/g, 'Z')); // IE support } function findAllPostsWithMessage(data) { var posts = []; if (data) { var post; for (var i=0; i<data.length; ++i) { post = data[i]; if (post.message) { /*jshint camelcase:false*/ post.created = fbStringToDate(post.created_time); posts.push(post); } } } return posts; } function isPostYoungEnough(post, now, postsNoOlderThan) { return post.created.getTime() + postsNoOlderThan > now.getTime(); } function isToday(date1, date2) { return date1.toDateString() === date2.toDateString(); } function fixLinkToMessage(post, fbName) { if (post.link && (isLinkToFbAccount(post.link, fbName) || messageContainsLink(post))) { post.link = ''; } return post; } fbUtils.postsUrl = function(fbName, token) { return appendToken(graphUrl(fbName) + '/posts?fields=message,link', token); }; fbUtils.collectYoungPosts = function(fbName, data, now, postsNoOlderThan) { var youngPosts = []; var posts = findAllPostsWithMessage(fbName, data); if (posts.length > 0 && isPostYoungEnough(posts[0], now, postsNoOlderThan)) { youngPosts.push(fixLinkToMessage(posts[0], fbName)); for (var i = 1; i < posts.length; ++i) { if (isToday(now, posts[i].created)) { youngPosts.push(fixLinkToMessage(posts[i], fbName)); } else { break; } } } return youngPosts; }; fbUtils.getTransformedFeedsWithPosts = function(fbFeedsToCheck, fetchedFbFeeds) { var output = [], fbPosts, feed; for (var i=0; i<fbFeedsToCheck.length; ++i) { feed = fbFeedsToCheck[i]; fbPosts = fetchedFbFeeds[i]; if (fbPosts && fbPosts.length > 0) { feed.time = fbPosts[0].created; feed.posts = fbPosts; output.push(feed); } } return output; }; fbUtils.makeAccountLink = function(uid) { return 'https://www.facebook.com/' + uid; }; fbUtils.deserializeFeeds = function(feeds, postProcessing) { if (feeds) { var feed, post, posts; for (var j,i=0; i<feeds.length; ++i) { feed = feeds[i]; posts = feed.posts; /*jshint camelcase:false*/ feed.time = fbStringToDate(posts[0].created_time); for (j=0; j<posts.length; ++j) { post = posts[j]; /*jshint camelcase:false*/ post.created = fbStringToDate(post.created_time); } if (postProcessing) { postProcessing(feed); } } return feeds; } return []; }; /*jshint validthis:true*/ }.call(this));
const webpack = require('webpack'); const fs = require('fs'); const paths = require('../paths'); const defaultBrowsers = { browsers: [ '>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9', // React doesn't support IE8 anyway ] }; // Check if there is a browsers.json file and loads it if exists // this allows us to customize the browsers list without having to eject function loadBrowsersConfig() { return fs.existsSync(paths.browsersFile) ? require(paths.browsersFile) : defaultBrowsers } const postcssBasePlugins = [ require('postcss-modules-local-by-default'), require('postcss-import')({ addDependencyTo: webpack, }), require('postcss-cssnext')(loadBrowsersConfig()), ]; const postcssDevPlugins = []; const postcssProdPlugins = [ require('cssnano')({ safe: true, sourcemap: true, autoprefixer: false, }), ]; const postcssPlugins = postcssBasePlugins .concat(process.env.NODE_ENV === 'production' ? postcssProdPlugins : []) .concat(process.env.NODE_ENV === 'development' ? postcssDevPlugins : []); module.exports = () => { return postcssPlugins; };
import React from "react" import ReactDOM from "react-dom" import "./index.css" import App from "./05-3-App" import { createStore } from "redux" import { Provider } from "react-redux" const stateChanger = (state, action) => { if (state === undefined) { return { n: 0 } } else { if (action.type === "add") { let newState = { n: state.n + action.payload } return newState } else { return state } } } const store = createStore(stateChanger) ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById("root") )
//观察者模式 var observer = (function(){ var _messages = {}; return { //注册信息接口 regist: function(type,fn){ //消息不存在则创建一个 if(typeof _messages[type] === 'undefined'){ _messages[type] = [fn]; }else{ _messages[type].push(fn); } console.log("regist:"+type); return this; }, //发布信息接口 fire: function(type,args){ //如果该消息没有被注册,则返回 if(!_messages[type]){ return this; } //定义消息信息 var events = { type: type,//消息类型 args: args||{}//消息携带的数据 }, i = 0, len = _messages[type].length; for( ; i<len; i++){ _messages[type][i].call(this,events); } console.log("fire:"+type+" "+args); return this; }, //移除信息接口 remove: function(type,fn){ if(_messages[type] instanceof Array){ var i = _messages[type].length - 1; for(; i>=0; i--){ if(_messages[type][i] === fn){ _messages[type].splice(i,1); } } } console.log("remove:"+type); return this; } } })(); function $(id){ return document.getElementById(id); } //留言评论展示模块 (function(){ //追加一则消息 function addMsgItem(e){ var text = e.args.text, ul = $('msg'), li = document.createElement('li'), span = document.createElement('span');//删除按钮 span.innerHTML="删除"; li.innerHTML = text; span.addEventListener('click',function(){ ul.removeChild(li); observer.fire('removeCommentMessage',{ num: -1 }); }); li.appendChild(span); ul.appendChild(li); } //注册添加评论信息 observer.regist('addCommentMessage',addMsgItem); })(); //用户消息模块 (function(){ //更改用户消息数目 function changeMsgNum(e){ //获取需要增加的用户消息数目 var num = e.args.num; //增加用户消息数目并写入页面中 $('msg_num').innerHTML = parseInt($('msg_num').innerHTML) + num; } //注册添加评论信息 observer.regist('addCommentMessage',changeMsgNum) .regist('removeCommentMessage',changeMsgNum); })(); //提交模块 (function(){ //用户点击提交按钮 $('user_submit').addEventListener('click',function(){ var text = $('user_input'); if(text.value === ''){ return; } observer.fire('addCommentMessage',{ text: text.value, num: 1 }); text.value = ''; }); })();
const Aerospike = require('aerospike'); const uuid = require('uuid/v4'); let request = require('request'); let httpe = require('http-errors'); const config = as_settings; let policies = { // exists: Aerospike.policy.exists.IGNORE write: new Aerospike.WritePolicy({ exists: Aerospike.policy.exists.IGNORE }) }; config.policies = policies; var client = new Aerospike.client(config); client.captureStackTraces = true; client.connect().then(logger.info('Client Connected')).catch(reason => { logger.error(reason) }); module.exports.checkconn = function checkConnection() { if (!client.isConnected()) { client.connect() } }; module.exports.syn = function () { try { logger.debug("SYN Called, will now fetch data from upstream. [" + new Date().toISOString() + "]"); getUpstream(function () { doTransfers(); doAdds(); }) } catch (e) { logger.error(e) } }; function getUpstream(callback) { try { var scan = client.scan(settings.db_namespace, "accounts"); var stream = scan.foreach(); stream.on('error', error => { logger.error(error); }); stream.on('end', () => { callback() }); stream.on('data', record => { request.get({ uri: settings.P9_2_json.proto + '://' + env.B2N_SERVICE_AUTH + '@' + settings.P9_2_json.ip + ':' + settings.P9_2_json.port + env.B2N_SERVICE_PATH + '/read.cgi', useQuerystring: true, qs: { bankn: settings.team, accnt: record.bins.account_number } }, function (error, response, body) { if (error) { logger.error(error) } else { // Can we possibly change this to work on request status code? // I feel like this isn't a great way to distinguish errors if (!JSON.stringify(body).toLowerCase().includes("internal server error")) { logger.info(JSON.stringify(body, null, 4)); let key = new Aerospike.Key(settings.db_namespace, 'accounts', record.bins.account_number); client.put(key, { amount: parseFloat(body.balance), owner: body.name }, function (err, key) { if (err) logger.error(err); else logger.info({body: body, key: key}) }) } } }) }) } catch (e) { logger.error(e) } } function doTransfers() { let scan = client.scan(settings.db_namespace, "transfers"); var stream = scan.foreach(); stream.on('error', error => { logger.error(error); }); stream.on('end', () => { client.truncate(settings.db_namespace, 'transfers', function () { logger.info("doTransfers: stream finished."); }) }); stream.on('data', record => { let bins = record.bins; logger.debug(JSON.stringify(bins)) request.post({ uri: settings.P9_2_json.proto + '://' + env.B2N_SERVICE_AUTH + '@' + settings.P9_2_json.ip + ':' + settings.P9_2_json.port + env.B2N_SERVICE_PATH + '/transaction.cgi', useQuerystring: true, qs: { pin: bins.pin }, body: bins, json: true }, function (err, resp, body) { if (err) logger.error(err) else { logger.info(body) } }) }) } function doAdds() { let scan = client.scan(settings.db_namespace, "adds"); var stream = scan.foreach(); stream.on('error', error => { logger.error(error); }); stream.on('end', () => { client.truncate(settings.db_namespace, 'adds', function () { logger.info("doAdds: stream finished."); }) }); stream.on('data', record => { }) } module.exports.test = function () { const key = new Aerospike.Key(settings.db_namespace, 'demo', 'demo'); Aerospike.connect(config) .then(client => { const bins = { i: 123, s: 'hello', b: Buffer.from('world'), d: new Aerospike.Double(3.1415), g: Aerospike.GeoJSON.Point(103.913, 1.308), l: [1, 'a', {x: 'y'}], m: {foo: 4, bar: 7} } const meta = {ttl: 10000} const policy = new Aerospike.WritePolicy({ exists: Aerospike.policy.exists.CREATE_OR_REPLACE }) return client.put(key, bins, meta, policy) .then(() => { const ops = [ Aerospike.operations.incr('i', 1), Aerospike.operations.read('i'), Aerospike.lists.append('l', 'z'), Aerospike.maps.removeByKey('m', 'bar') ] return client.operate(key, ops) }) .then(result => { logger.info(result.bins) // => { i: 124, l: 4, m: null } return client.get(key) }) .then(record => { logger.info(record.bins) // => { i: 124, // s: 'hello', // b: <Buffer 77 6f 72 6c 64>, // d: 3.1415, // g: '{"type":"Point","coordinates":[103.913,1.308]}', // l: [ 1, 'a', { x: 'y' }, 'z' ], // m: { foo: 4 } } }) .then(() => client.close()) }) .catch(error => { logger.error('Error: %s [%i]', error.message, error.code) if (error.client) { error.client.close() } }); }; module.exports.delete_acct = function (account_number, callback) { let key = new Aerospike.Key(settings.db_namespace, 'accounts', account_number.toString()) client.remove(key, function (err, key) { if (err) logger.error(err) else logger.info(key) callback() }) }; // TODO Figure out how to work this in with passport // When we make a new user with passport, we also // have to create a new bank account with the bank module.exports.newAccount = function (acount_number = 0, owner, bal, pin = 0, callback) { this.checkconn(); request.post({ uri: settings.P9_2_json.proto + '://' + env.B2N_SERVICE_AUTH + '@' + settings.P9_2_json.ip + ':' + settings.P9_2_json.port + env.B2N_SERVICE_PATH + '/acct.cgi', json: true, body: { bank: settings.team.toString(), name: owner, pin: pin.toString(), balance: bal.toString(), acct: acount_number.toString() } }, function (err, response, body) { if (err) { logger.error(err); callback(0) } else if (!body.acct) { callback(0); this.emit('error', httpe(400, 'https://http.cat/400')); } else { logger.info(body); let key = new Aerospike.Key(settings.db_namespace, "accounts", body.acct); const policy = new Aerospike.WritePolicy({ exists: Aerospike.policy.exists.CREATE_OR_REPLACE }); client.put(key, { pin: pin, account_number: body.acct, owner: owner, amount: new Aerospike.Double(parseFloat(bal)) }, policy, (err, key) => { if (err) { logger.error(err) callback(0) } else { logger.info(key) addTransfer({ account_number: 0, amount: bal, pin: 1337, destination: { branch: settings.team, account_number: body.acct } }, (d) => { logger.info(d); callback(body.acct); }) } }) } }) }; module.exports.addTransaction = function (type, data, callback) { let res = false; switch (type.toLowerCase()) { case "transfer": addTransfer(data, function (res) { callback(null, res) }); break; case "add": newAdd(data, function (res) { callback(null, res) }); break; default: callback(new Error("METHOD_NOT_IMPLEMENTED"), null) } }; function addTransfer(data, callback1) { let id = uuid(); let key = new Aerospike.Key(settings.db_namespace, "transfers", id); client.put(key, { action: "transfer", facct: parseInt(data.account_number), fbank: parseInt(settings.team), amount: new Aerospike.Double(parseFloat(data.amount)), pin: parseInt(data.pin), tacct: parseInt(data.destination.account_number), tbank: parseInt(data.destination.branch) }); add({account_number: data.account_number, amount: 0 - data.amount}, function (res) { callback1(res) }) } module.exports.truncate = function (req, res, next) { client.truncate(settings.db_namespace, "accounts", function () { logger.info('truncate: finished truncating accounts') }); client.truncate(settings.db_namespace, 'adds', function () { logger.info('truncate: finished truncating adds') }); client.truncate(settings.db_namespace, 'transfers', function () { logger.info('truncate: finished truncating transfers') }); next() }; // TODO Uh.. That's not a great callback. What is this used for? function add(data, callback) { // let key = new Aerospike.Key(settings.db_namespace, "accounts", data.account_number); let key = new Aerospike.Key(settings.db_namespace, "accounts", data.account_number.toString()); logger.debug(JSON.stringify(key, null, 4)) logger.debug(JSON.stringify(data, null, 4)); client.get(key).then(record => { client.put(key, {amount: parseFloat(record.bins.amount) + parseFloat(data.amount)}, function (error, key) { callback(error, "It did _something_, idk if its the thing you asked for tho") }) }).catch(e => { logger.error(JSON.stringify(e, null, 4)) }) } module.exports.getUser = function (username, callback) { client.exists(new Aerospike.Key(settings.db_namespace, "users", username), function (error, result) { if (error) { logger.error("Error while checking for user: " + username); callback(error, null); } else if (result) { return client.get(new Aerospike.Key(settings.db_namespace, "users", username), (err, user) => { return callback(error, user) }); } else { logger.error("Nonexistent user attempted to log in: " + username); callback(error, null); } }); } function newAdd(data, callback1) { let id = uuid(); let key = new Aerospike.Key(settings.db_namespace, "adds", id); client.put(key, { action: "add", amnt: new Aerospike.Double(data.amount), pin: parseInt(data.pin), acct: parseInt(data.account_number) }); add({account_number: data.account_number, amount: data.amount}, function (res) { add({account_number: 0, amount: 0 - data.amount}, function () { callback1(res) }) }) } module.exports.getAccount = function (account_number = 0, callback) { let key = new Aerospike.Key(settings.db_namespace, "accounts", account_number); logger.debug(JSON.stringify(key, null, 4)) client.get(key, function (err, rec) { if (err) { logger.error(err); callback(err, null) } else { callback(null, rec.bins) } }) }; module.exports.getAllAccounts = function (callback) { let all = {}; var scan = client.scan(settings.db_namespace, "accounts"); var stream = scan.foreach(); stream.on('error', error => { logger.error(error); }); stream.on('end', () => { callback(null, all) }); stream.on('data', record => { all[record.bins.account_number] = record; }) }; module.exports.getComments = function (callback, set = "propaganda") { let all = []; var scan = client.scan(settings.db_namespace, set); var stream = scan.foreach(); stream.on('error', error => { logger.error(error); }); stream.on('end', () => { callback(null, all) }); stream.on('data', record => { all.push({"set":record.bins.set, "uname":record.bins.uname, "comment":record.bins.comment}); }) }; module.exports.addComment = function (callback, set = "propaganda", bins) { let key = new Aerospike.Key(settings.db_namespace, set, uuid()); client.put(key, bins, function (error, key) { callback(error, key) }) }; module.exports.addBlacklistedJWT = function (jwt, callback) { let key = new Aerospike.Key(settings.db_namespace, "jwt_blacklist", uuid()); const policy = new Aerospike.WritePolicy({ exists: Aerospike.policy.exists.CREATE_OR_REPLACE }); client.put(key, {token: jwt}, policy, function (error, key) { if(error) logger.error("Error while blacklisting a JWT"); callback(error); }) }; module.exports.checkJWTBlacklist = function(jwt, callback) { client.exists(new Aerospike.Key(settings.db_namespace, "jwt_blacklist", jwt), function (error, result) { if (error) { logger.error("Error while checking JWT blacklist"); callback(error, null); } else if (result) { logger.error("Blacklisted JWT encountered in checkJWTBlacklist"); return callback(error, true) } else { callback(error, false); } }); }; // We can call this prior to competition. module.exports.precomp = function () { client.truncate(settings.db_namespace, 'accounts', function () { client.truncate(settings.db_namespace, 'adds', function () { client.truncate(settings.db_namespace, 'transfers', function () { request.get({ uri: settings.P9_2_json.proto + '://' + env.B2N_SERVICE_AUTH + '@' + settings.P9_2_json.ip + ':' + settings.P9_2_json.port + env.B2N_SERVICE_PATH + '/read.cgi', useQuerystring: true, qs: { bank: settings.team.toString(), acct: 'ALL' } }, function (err, resp, body) { if (err) { logger.error(err); logger.error("Pre-competition sync: Connection to bank2node service failed!") } else { logger.info(body) body = JSON.parse(body); for (acct of body.accounts) { logger.info(JSON.stringify(acct)); let ac = {}; ac.account_number = acct.acct; ac.balance = parseFloat(acct.balance); ac.owner = acct.name; let key = new Aerospike.Key(settings.db_namespace, 'accounts', acct.acct); client.put(key, ac, function (err, key) { if (err) { logger.error(err); logger.error("Pre-competition sync: failed to update account information for " + key); } else { logger.info("Updated " + JSON.stringify(key, null, 4)); } }) } } }) }) }) }) };
jQuery(document).ready(function(){ // init Isotope var $container = jQuery('#recipes_container').isotope({ itemSelector: '.recipe', layoutMode: 'fitRows' }); var $output = jQuery('#output'); // filter with selects and checkboxes var $checkboxes = jQuery('#recipe_tax_filter input'); $checkboxes.change( function() { // map input values to an array var inclusives = []; // inclusive filters from checkboxes $checkboxes.each( function( i, elem ) { // if checkbox, use value if checked if ( elem.checked ) { inclusives.push( elem.value ); } }); // combine inclusive filters var filterValue = inclusives.length ? inclusives.join(', ') : '*'; $output.text( filterValue ); $container.isotope({ filter: filterValue }) }); // function createItems() { // var $items; // // loop over colors, sizes, prices // // create one item for each // for ( var i=0; i < colors.length; i++ ) { // for ( var j=0; j < sizes.length; j++ ) { // for ( var k=0; k < prices.length; k++ ) { // var color = colors[i]; // var size = sizes[j]; // var price = prices[k]; // var $item = $('<div />', { // 'class': 'item ' + color + ' ' + size + ' price' + price // }); // $item.append( '<p>' + size + '</p><p>$' + price + '</p>'); // // add to items // $items = $items ? $items.add( $item ) : $item; // } // } // } // $items.appendTo( jQuery('#recipes_container') ); // } // jQuery('.checkbox-custom-label').click(function(){ // console.log('clicked'); // jQuery(this).prev('input').prop('checked', function(i, v) { return !v; }); // }); });
Ext.define('Ext.ux.NU.FieldWindow', { extend : 'Ext.ux.NU.DisplayWindow', alias : ['widget.nu.field_window'], title: 'Localisation Display', autoShow: true, width: 800,//800, height: 400, layout: 'fit', mainScene: null, robots: [], items: [{ xtype: 'threejs', itemId: 'mainscene', id: 'mainscene' }], tbar: [{ text: 'HawkEye', handler: function () { var controls = this.findParentByType('window').getComponent('mainscene').controls; controls.yawObject.position.set(0, 3.5 * 100, 0); controls.yawObject.rotation.set(0, 0, 0); controls.pitchObject.rotation.set(-Math.PI / 2, 0, 0); } }, { text: 'Perspective', handler: function () { var controls = this.findParentByType('window').getComponent('mainscene').controls; controls.yawObject.position.set(-3 * 100, 1.6 * 100, 3 * 100); controls.yawObject.rotation.set(0, -6.9, 0); controls.pitchObject.rotation.set(-0.5, 0, 0); } }, { text: 'Side', handler: function () { var controls = this.findParentByType('window').getComponent('mainscene').controls; controls.yawObject.position.set(0, 1.9 * 100, -4.5 * 100); controls.yawObject.rotation.set(0, Math.PI, 0); controls.pitchObject.rotation.set(-0.6, 0, 0); } }], constructor: function () { NU.Network.on('robot_ips', Ext.bind(this.onRobotIPs, this)); NU.Network.on('sensor_data', Ext.bind(this.onSensorData, this)); NU.Network.on('localisation', Ext.bind(this.onLocalisation, this)); this.callParent(arguments); }, listeners: { afterRender: function () { this.init(); }, resize: function (obj, width, height) { } }, onRobotIPs: function (robotIPs) { var self = this; Ext.each(robotIPs, function (robotIP) { var robot; robot = this.getRobot(robotIP); if (robot !== null) { return; // already exists } robot = new NU.FieldWindow.Robot({ robotIP: robotIP }); //robot.darwinModel.traverse( function ( object ) { object.visible = false; } ); this.mainScene.scene.add(robot.darwinModel); //robot.darwinModel.position.x = Math.random() * 800 - 400; //robot.darwinModel.position.z = Math.random() * 400 - 200; //robot.darwinModel.visualiser.scale.x = Math.random() * 50; //robot.darwinModel.visualiser.scale.y = Math.random() * 50; //robot.darwinModel.visualiser.rotation.y = Math.random() * 2 * Math.PI; //robot.darwinModel.object.dataModel.localisation.angle.set(Math.random() * 2 * Math.PI); robot.darwinModel.behaviourVisualiser.rotation.y = robot.darwinModel.object.dataModel.localisation.angle.get(); //robot.ballModel.traverse( function ( object ) { object.visible = false; } ); this.mainScene.scene.add(robot.ballModel); //robot.ballModel.position.x = Math.random() * 800 - 400; //robot.ballModel.position.z = Math.random() * 400 - 200; //robot.ballModel.visualiser.scale.x = Math.random() * 10; //robot.ballModel.visualiser.scale.y = Math.random() * 10; //robot.ballModel.visualiser.rotation.y = Math.random() * 2 * Math.PI; this.robots.push(robot); }, this); }, onSensorData: function (robotIP, api_message) { var robot = this.getRobot(robotIP); if (robot == null) { console.log('error', robotIP); return; } var api_sensor_data = api_message.sensor_data; robot.onSensorData(api_sensor_data); }, onLocalisation: function (robotIP, api_message) { var robot = this.getRobot(robotIP); if (robot == null) { console.log('error', robotIP); return; } var api_localisation = api_message.localisation; robot.onLocalisation(api_localisation); }, getRobot: function (robotIP) { var foundRobot = null; Ext.each(this.robots, function (robot) { if (robot.robotIP == robotIP) { foundRobot = robot; return false; } return true; }); return foundRobot; }, init: function () { var self; self = this; self.mainScene = self.createMainScene(); Ext.getCmp('mainscene') .setComponents(self.mainScene.scene, self.mainScene.renderer, self.mainScene.camera) .enableControls({ movementSpeed: 200 }); var controls = Ext.getCmp('mainscene').controls; controls.yawObject.position.set(0, 3.5 * 100, 0); controls.yawObject.rotation.set(0, 0, 0); controls.pitchObject.rotation.set(-Math.PI / 2, 0, 0); }, createMainScene: function () { var darwin, field, ball, camera, scene, renderer; scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000); camera.lookAt(scene.position); /*darwin = new DarwinOP(); //var DarwinModel = window.dm = Modeler.model(DataModel); darwin.bindToData(Data.robot); darwin = LocalisationVisualiser.localise(darwin);//, new THREE.Vector3(0, -0.343, 0) window.darwin = darwin; ball = new Ball(); ball = LocalisationVisualiser.localise(ball, {color: 0x0000ff}); ball.position.x = 20; window.ball = ball; scene.add(darwin); scene.add(ball);*/ field = new Field(); scene.add(field); //var circle = new THREE.Circle(); //scene.add(circle); //window.circle = circle; /* debug */ // red = x // green = y // blue = z //Axis array[x,y,z] var axisLength = 4 * 100; var info = [[-axisLength, 0, 0, axisLength, 0, 0, 0xff0000], [0, -axisLength ,0 , 0, axisLength, 0, 0x00ff00], [0, 0, -axisLength, 0, 0, axisLength, 0x0000ff]]; //Draw some helpfull axis for (var i = 0; i < 3; i++) { var material = new THREE.MeshBasicMaterial({color: 0xffffff}); var geometry = new THREE.Geometry(); //Define the start point var particle = new THREE.Particle(material); particle.position.x = info[i][0]; particle.position.y = info[i][1]; particle.position.z = info[i][2]; //Add the new particle to the scene scene.add(particle); //Add the particle position into the geometry object geometry.vertices.push(new THREE.Vertex(particle.position)); //Create the second point particle = new THREE.Particle(material); particle.position.x = info[i][3]; particle.position.y = info[i][4]; particle.position.z = info[i][5]; //Add the new particle to the scene scene.add(particle); //Add the particle position into the geometry object geometry.vertices.push(new THREE.Vertex(particle.position)); //Create the line between points var line = new THREE.Line(geometry, new THREE.LineBasicMaterial({color: info[i][6], opacity: 0.8, linewidth: 1})); scene.add(line); } renderer = new THREE.WebGLRenderer({antialias: true}); renderer.setClearColorHex(0x0); //renderer.setClearColorHex(0xFFFFFF); renderer.setSize(window.innerWidth, window.innerHeight); return { scene: scene, camera: camera, renderer: renderer }; } });
import React from "react"; import PropTypes from "prop-types"; import styles from "./button.css"; // Helper const joinClassNames = (str, classNames) => classNames.concat(str).join(" "); function Button({ text, classNames, type, children, ...attr }) { return ( <button type={type} className={joinClassNames(styles.btn, classNames)} {...attr} > {children} </button> ); } Button.defaultProps = { type: "button", classNames: [] }; Button.propTypes = { type: PropTypes.string, classNames: PropTypes.arrayOf(PropTypes.string) }; export default Button;
export const SHOW_SPLASH = 'SHOW_SPLASH'; export const HIDE_SPLASH = 'HIDE_SPLASH'; export const showSplash = () => dispatch => { dispatch({ type: SHOW_SPLASH }); setTimeout(() => { dispatch({ type: HIDE_SPLASH }); }, 750); };
import React from 'react'; import WorkoutTab from './WorkoutTab'; import { shallow, mount } from 'enzyme'; const props = { categories: {}, detail: {}, exercises: { all: [], current: [], }, fetchCategories: jest.fn(), fetchAPIExercises: jest.fn(), fetchUserExercises: jest.fn(), fetchWorkouts: jest.fn(), randomizeExercises: jest.fn(), saveWorkout: jest.fn(), user: {}, workouts: [], } describe('WorkoutTab Component', () => { it('should render', () => { const wrapper = shallow(<WorkoutTab {...props} />); expect(wrapper.length).toEqual(1) }) })
import WrapContent from '../HOC/WrapContent/WrapContent'; import icon_one from '../img/icon_one.svg'; import icon_two from '../img/icon_two.svg'; import icon_three from '../img/icon_three.svg'; import icon_four from '../img/icon_four.svg'; import icon_five from '../img/icon_five.svg'; const WhatNeedKnow = () => { const data = [ {title: 'Профилактика', src: icon_one}, {title: 'Диагностика', src: icon_two}, {title: 'Лечение', src: icon_three}, {title: 'Реабилитация', src: icon_four}, {title: 'Поддержка', src: icon_five} ] return ( <WrapContent> <div className={'WhatNeedKnow'}> <h3 className="heading">Что нужно знать об онкологии</h3> { data.map((item, ind) => ( <div className="iconBlock" key={ind}> <div className="imgBlock"> <img src={item.src} alt=""/> </div> <span className="text">{item.title}</span> </div> )) } </div> </WrapContent> ) } export default WhatNeedKnow;
import React, { useState } from 'react'; import { withRouter } from 'react-router-dom'; import { connect } from 'react-redux'; import { isRequired, isEmail } from 'calidators'; import action from '../../actions'; import TextInput from '../../components/TextInput'; import Button from '../../components/Button'; import AppHeader from '../../components/AppHeader'; import '../Index/index.scss'; import './index.scss'; import mockup from '../../assets/smartmockups_jxfuqv8i.jpg'; const ForgetPassword = (props) => { const [email, setEmail] = useState(''); const emailValidator = isRequired({ message: '請輸入E-mail' })(email); const emailValidator2 = isEmail({ message: '請輸入正確的Email' })(email); const forgetPasswordHandler = () => { const forgetPasswordData = { email, }; props.forgetPassword(forgetPasswordData, props.history); }; return ( <div className="ForgetPassword"> <AppHeader isDropdownVisible={false} isTabVisible={false} isUserBtnVisible={false} /> <div className="AppContent"> <div className="photo-section" style={{ backgroundImage: `url(${mockup})` }} /> <div className="form-section"> <p className="title">忘記密碼</p> <p className="extrainfo"> 請輸入當時註冊的信箱來接收一個暫時的密碼 </p> <form> <TextInput title="E-mail" text={email} showHint={false} hintType="ok" onChange={e => setEmail(e.target.value)} required /> <Button className="submit_btn" text="送出" type="primary" size="small" onClick={forgetPasswordHandler} disabled={emailValidator !== null || emailValidator2 !== null} /> </form> </div> </div> </div> ); }; const mapStateToProps = store => ({ user: store.user, editor: store.editor, }); export default withRouter( connect( mapStateToProps, action, )(ForgetPassword), );
const request = require('request'); const { weather_key } = require('../config'); // weather API const forecast = (lat, long, service) => { const url = `http://api.weatherstack.com/current?access_key=${weather_key}&query=${long},${lat}&units=f`; request({url, json: true}, (err, { body }) => { if(err) { service('Unable to connect to weather API'); } else if(body.error) { service('Unable to find location'); } else { let temp = body.current; service(undefined, `It is currently ${temp.temperature} degrees farenheit. It feels like ${temp.feelslike} degrees farenheit.`) } }) } module.exports = forecast;
// // Declare all the graphs.. // var graphs = [${graphs}]; // // This method is responsible for pausing the automatic refresh. // var paused = false; function pauseRefresh() { var refreshText = "${pause.text}"; paused = !paused; if (paused) { refreshText = "${resume.text}"; } $('pause').value = refreshText; } // // This method is responsible for refreshing all the graphs below. // function doRefresh(fromButton) { // check that this was from a button click // not a time where we are paused but the timeout // was set to trigger.. if (fromButton || !paused) { $('lastRefreshDate').update(new Date()); // loop through all graphs calling zoom for (var x=0; x<graphs.size(); x++) { zoom(x, 0, 100); } // reset the timer.. if (!paused) { setTimeout("doRefresh(false)", ${refresh.time}); } } } // // This method is responsible for refreshing a particular graph // and including the proper zooming. // function zoom(index, low, high) { // refresh the image w/ a new chart based on the low/high percentage. Ajax.Updater( 'graph' + index + '_image', '${servlet_mapping}', { parameters: $H({ graph_id:graphs[index], low:low, high:high }) } ); } // // Initialize the page.. // doRefresh();
'use strict'; require.config({ paths:{ 'esri':'http://localhost/arcgis_js_api/jsapi/esri/', 'dojo':'http://localhost/arcgis_js_api/jsapi/dojo/', 'dijit':'http://localhost/arcgis_js_api/jsapi/dijit/', 'dojox':'http://localhost/arcgis_js_api/jsapi/dojox/', 'dgrid':'http://localhost/arcgis_js_api/jsapi/dgrid/', 'xstyle':'http://localhost/arcgis_js_api/jsapi/xstyle/', 'angular':'../bower_components/angular/angular', 'angular-animate':'../bower_components/angular-animate/angular-animate', 'angular-aria':'../bower_components/angular-aria/angular-aria', 'angular-cookies':'../bower_components/angular-cookies/angular-cookies', 'angular-leaflet-directive':'../bower_components/angular-leaflet-directive/dist/angular-leaflet-directive', 'angular-messages':'../bower_components/angular-messages/angular-messages', 'angular-mocks':'../bower_components/angular-mocks/angular-mocks', 'angular-resource':'../bower_components/angular-resource/angular-resource', 'angular-route':'../bower_components/angular-route/angular-route', 'angular-sanitize':'../bower_components/angular-sanitize/angular-sanitize', 'angular-simple-logger':'../bower_components/angular-simple-logger/dist/angular-simple-logger', 'angular-touch':'../bower_components/angular-touch/angular-touch', 'jquery':'../bower_components/jquery/dist/jquery', 'bootstrap':'../bower_components/bootstrap/dist/js/bootstrap', 'leaflet':'../bower_components/leaflet/dist/leaflet', 'angular-esri-map':'../bower_components/angular-esri-map/dist/angular-esri-map', 'domReady':'../bower_components/domReady/domReady' }, shim:{ 'angular':{ exports:'angular' }, 'angular-animate': { deps: ['angular'], exports: 'angular-animate' }, 'angular-aria': { deps: ['angular'], exports: 'angular-aria' }, 'angular-cookies': { deps: ['angular'], exports: 'angular-cookies' }, 'angular-leaflet-directive': { deps: ['angular'], exports: 'angular-leaflet-directive' }, 'angular-messages': { deps: ['angular'], exports: 'angular-messages' }, 'angular-mocks': { deps: ['angular'], exports: 'angular-mocks' }, 'angular-resource': { deps: ['angular'], exports: 'angular-resource' }, 'angular-route': { deps: ['angular'], exports: 'angular-route' }, 'angular-sanitize': { deps: ['angular'], exports: 'angular-sanitize' }, 'angular-simple-logger': { deps: ['angular'], exports: 'angular-simple-logger' }, 'angular-touch': { deps: ['angular'], exports: 'angular-touch' }, 'angular-esri-map': { deps: ['angular'], exports: 'angular-esri-map' }, 'bootstrap': { deps: ['jquery'], exports: 'bootstrap' }, 'leaflet':{ exports:'leaflet' }, 'jquery': { exports: 'jquery' } } }); require(['angular', 'leaflet', './controllers/header', './controllers/about', './controllers/main', 'domReady!'], function(ng, L){ window.L = L; ng.bootstrap(document, ['myapp']); });
printDate(); var arrFeedURLs = [ 'https://api.rss2json.com/v1/api.json?rss_url=http://www.abc.net.au/news/feed/46800/rss.xml', 'https://api.rss2json.com/v1/api.json?rss_url=http://www.abc.net.au/news/feed/51120/rss.xml']; //displayFeedContent('https://api.rss2json.com/v1/api.json?rss_url=http://www.abc.net.au/news/feed/46800/rss.xml'); for (var item in arrFeedURLs) { var contentDiv = 'rs-feed'+ item; console.log(contentDiv); displayFeedContent(arrFeedURLs[item], contentDiv); } function displayFeedContent(rsstoJSON, contentDiv) { var displayDiv = document.getElementById(contentDiv); var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if (xhr.readyState==4 && xhr.status==200) { var data = JSON.parse(xhr.responseText); var numToDisplay = 9; if(data.status == 'ok'){ var output = '<h1 class="feedTitle">'+data.feed.title+'</h1>'; for(var i=0;i<numToDisplay;++i){ output += '<a href="' + data.items[i].link + '" target="_blank">'; output+= '<div class="item-container col-lg-4 col-md-6 col-sm-6 col-xs-12"><div class="item-container-inner"><h2>' + data.items[i].title + '</h2>'; output+= '<img src="' + data.items[i].enclosure.link + '" />'; output += '</a><p>' + data.items[i].description + '<p></div></div>'; output += '</a>'; }//for displayDiv.innerHTML = output; }//if else { var output = '<p>'+ "Apologies - we could not retrieve any content" +'</p>'; } }//if }; xhr.open('GET',rsstoJSON,true); // xhr.open('GET','https://api.rss2json.com/v1/api.json?rss_url=http://www.abc.net.au/news/feed/46182/rss.xml',true); xhr.send(); } function printDate() { //print copyright date in footer $('#footer-date').text("Copyright " + new Date().getFullYear()); }
import { APPLY_FILTERS, HIDE_LOADING, LOAD_LOCATIONS, LOAD_STORE_TYPES, LOAD_STORES, OPEN_STORE_DETAILS, RESET_SEARCH_TERM, RESET_STORE_TYPES, SET_MAP_INITIAL_COORDS, SET_USER_LOCATION, SET_STORE_TYPES, SHOW_LOADING, TOGGLE_FILTER_PANEL, TOGGLE_SEARCH_LAYER, TOGGLE_STORE_TYPE, UPDATE_SEARCH_TERM, UPDATE_COORDS, } from './actionTypes.js'; export const loadStoresAction = (stores) => ({ type: LOAD_STORES, stores }); export const loadStoreTypesAction = (storeTypes) => ({ type: LOAD_STORE_TYPES, storeTypes }); export const loadLocationsAction = (locations) => ({ type: LOAD_LOCATIONS, locations }); export const updateSearchTermAction = (searchTerm) => ({ type: UPDATE_SEARCH_TERM, searchTerm }); export const actionWithLoading = (action) => (dispatch) => { dispatch(showLoadingAction()); setTimeout(() => dispatch(action), 50); }; export const resetSearchTermAction = () => ({type: RESET_SEARCH_TERM}); export const toggleFilterPanelAction = () => ({ type: TOGGLE_FILTER_PANEL }); export const setStoreTypesAction = (storeTypes) => ({ type: SET_STORE_TYPES, storeTypes }); export const toggleStoreTypeAction = (storeTypeId) => ({ type: TOGGLE_STORE_TYPE, storeTypeId}); export const resetStoreTypesAction = () => ({ type: RESET_STORE_TYPES }); export const openStoreDetailsAction = (store) => ({type: OPEN_STORE_DETAILS, store}); export const toggleSearchLayerAction = () => ({type: TOGGLE_SEARCH_LAYER}); export const setUserLocationAction = (userLocation) => ({type: SET_USER_LOCATION, userLocation}) export const showLoadingAction = () => ({type: SHOW_LOADING}); export const hideLoadingAction = () => ({type: HIDE_LOADING}); export const updateCoordsAction = (coords) => ({type: UPDATE_COORDS, coords}); export const applyFiltersAction = (filters) => ({type: APPLY_FILTERS, filters}); export const setMapInitialCoords = (coords) => ({type: SET_MAP_INITIAL_COORDS, coords});
function sayIt(n) { switch(n) { case 1: console.log("1"); break; case 2: console.log("2"); break; case "상수" + "아님": console.log("case에 표현식도 가능"); break; default: console.log("기본"); } } sayIt(1); // -> "1" sayIt(2); // -> "2" sayIt("상수아님"); // -> "2" sayIt("디폴트는"); // -> "기본"
let mongoose = require('mongoose'); const ObjectId = mongoose.Schema.ObjectId; let fields = { bannerType: { type: String, enum: 'GameCategory|GameList'.split('|') }, status: { type: String, enum: 'Inactive|Active'.split('|'), default: 'Active' }, gameCategory: { type: ObjectId, ref: 'gameCategory', }, gameName: { type: ObjectId, ref: 'game' }, banner: [{ type: String }] }; let Schema = require('utils/generate-schema')(fields); Schema.index({ gameCategory: 1, gameName: 1 }, { background: true }); module.exports = Schema;
var express = require('express'); var router = express.Router(); var pg = require('pg'); var host = process.env.OPENSHIFT_POSTGRESQL_DB_HOST; var port = process.env.OPENSHIFT_POSTGRESQL_DB_PORT; var connectionString = "pg://adminunl69sf:am7dXX6vY_jy@" + host + ":" + port + "/leaderboard"; /* GET home page. */ router.get('/api/scores', function(req, res) { var results = []; pg.connect(connectionString, function(err, client, done) { if (err) { done(); console.log(err); return res.status(500).json({ success: false, data: err }); } var query = client.query("SELECT * FROM scores WHERE name IS NOT NULL ORDER BY score DESC LIMIT 10"); query.on('row', function(row) { results.push(row); }); query.on('end', function() { done(); return res.json(results); }); }); }); router.post('/api/scores', function(req, res) { var results = []; // console.log(JSON.stringify(req.body)); var data = { name: req.body.name, score: req.body.score }; pg.connect(connectionString, function(err, client, done) { if (err) { done(); console.log(err); return res.status(500).json({ success: false, data: err }); } var query = client.query("INSERT INTO scores(name, score) values($1, $2)", [data.name, data.score]); query.on('end', function() { done(); res.send("added!"); }); }); }); module.exports = router;
import React from "react"; import "./Item.css"; function Item({ item, index, editable, clickHandle, dblClickHandle, keyPressHandle }) { return ( <div className="item-list"> {editable ? ( <input type="text" defaultValue={item.name} onKeyPress={e => keyPressHandle(e, index)} /> ) : ( <h3 onDoubleClick={dblClickHandle}>{item.name}</h3> )} <h3>{item.calories}</h3> <button className="remove-button" name={item.name} onClick={clickHandle}> Remove </button> </div> ); } export default Item;
module.exports = { LogCtx: require("./src/Context.js"), VError: require("./src/verror.js").VError, Hit: require("./src/Hit.js"), };
/* See license.txt for terms of usage */ define([ "firebug/firebug", "firebug/lib/trace", "firebug/lib/domplate", "firebug/lib/locale", "firebug/chrome/window", "firebug/lib/css", "firebug/lib/dom", ], function(Firebug, FBTrace, Domplate, Locale, Win, Css, Dom) { "use strict"; // ********************************************************************************************* // // Constants const Cc = Components.classes; const Ci = Components.interfaces; var {domplate, DIV, TABLE, TBODY, TR, TD, SPAN, BUTTON} = Domplate; // ********************************************************************************************* // // Implementation var PanelNotification = domplate( { tag: TABLE({"class": "panelNotification", cellpadding: 0, cellspacing: 0}, TBODY( TR({"class": "panelNotificationRow"}, TD({"class": "panelNotificationCol"}, SPAN({"class": "panelNotificationMessage"}, "$message" ) ), TD({"class": "panelSeparatorCol"}), TD({"class": "panelNotificationCol"}, BUTTON({"class": "panelNotificationButton", title: "$buttonTooltip", onclick: "$onPreferences"}, "$buttonLabel" ) ) ) ) ), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // onPreferences: function(event) { var table = Dom.getAncestorByClass(event.target, "panelNotification"); Win.openNewTab("about:config?filter=" + table.config.prefName); }, // xxxHonza: this API should be a little more generic updateCounter: function(row) { var container = Dom.getAncestorByClass(row, "panelNotificationBox"); if (container) Css.removeClass(container, "collapsed"); // Update info within the limit row. var message = row.getElementsByClassName("panelNotificationMessage").item(0); message.firstChild.nodeValue = Locale.$STRP("plural.Limit_Exceeded2", [row.config.totalCount]); }, render: function(parent, config) { // Set default values config.buttonTooltip = config.buttonTooltip || null; config.buttonLabel = config.buttonLabel || Locale.$STR("LimitPrefs"); config.message = config.message || Locale.$STRP("plural.Limit_Exceeded2", [0]); var element = this.tag.append(config, parent, this); element.config = config; return element; } }); // ********************************************************************************************* // // Registration return PanelNotification; // ********************************************************************************************* // });
const itemParse = (item) => { const title = item.querySelector('title').textContent; const description = item.querySelector('description').textContent; const link = item.querySelector('link').textContent; // prettier-ignore return { title, description, link, }; }; export default (rss, link) => { const parser = new DOMParser(); const doc = parser.parseFromString(rss, 'application/xml'); const parserError = doc.querySelector('parsererror'); if (parserError) { throw new Error(parserError.textContent); } const title = doc.querySelector('title').textContent; const description = doc.querySelector('description').textContent; const items = [...doc.querySelectorAll('item')].map(itemParse); // prettier-ignore return { title, description, link, items, }; };
import React, {useContext} from 'react'; import axios from "axios"; import jwt from 'jsonwebtoken'; import {ApiStoreContext} from "../stores/api_store"; import URI from 'urijs'; import Router from 'next/router'; import cookie from 'js-cookie'; export async function handleJWT(currentFullUrl) { const isServer = typeof window === 'undefined'; const context = useContext(ApiStoreContext); const currentFullUrlParts = URI(isServer ? currentFullUrl : window.location.href); if (currentFullUrlParts.hasQuery('jwt')) { const query = currentFullUrlParts.query(true); const decodedJWT = jwt.decode(query.jwt); if (isServer) { // decoded JWT consists of partial user context.setUser(decodedJWT.user); } else { // on the client, fetch the entirety of the user const response = await axios.get(`/api/users/${decodedJWT.user.id}`, { headers: {'x-access-token': query.jwt}, }); cookie.set('jwt', query.jwt); context.setUser(response.data.user); currentFullUrl = currentFullUrlParts.removeQuery('jwt').path(); await Router.replace(currentFullUrl); } } }
/** * Using the useTransition for getting a change * @module Experiences/Experience1 */ import React, { useTransition, useState } from 'react' /** * @function Experience * You can try to spam the button, you should see the Loading appeared from time to time * @return {Object} Return the dom */ const Experience = () => { const [val, setVal] = useState(0) const [isPending, startTransition] = useTransition({ timeoutMs: 3000 }) return ( <> <button onClick={() => startTransition(() => { setVal((v) => v + 1) }) } > Increment </button> {isPending ? ' Loading...' : null} <div>{val}</div> </> ) } export default Experience
var Qna = { getListUrl:function(form) { var form = $(form); $.ajax({ type:"POST", url:ENV.getProcessUrl("qna","listUrl"), data:form.serialize(), dataType:"json", success:function(result) { if (result.success == true) { location.href = result.url; } }, error:function() { iModule.alertMessage.show("Server Connect Error!"); } }); return false; }, post:{ init:function(form) { var $form = $("#"+form); $form.formInit(Qna.post.submit,Qna.post.check); $(document).triggerHandler("Qna.post.init",[$form]); }, check:function($input) { if ($input.attr("required") == "required") { if ($input.val().length == 0) { $input.inputStatus("error"); } else { $input.inputStatus("success"); } } }, submit:function($form) { var data = $form.serialize(); $form.formStatus("loading"); $.ajax({ type:"POST", url:ENV.getProcessUrl("qna","postWrite"), data:data, dataType:"json", success:function(result) { if (result.success == true) { location.href = result.redirect; } else { $form.formStatus("error",result.errors); if (result.message) { iModule.alertMessage.show("error",result.message,5); } } }, error:function() { iModule.alertMessage.show("Server Connect Error!"); } }); } }, answer:{ init:function(form) { var $form = $("#"+form); $form.formInit(Qna.answer.submit,Qna.answer.check); $(document).triggerHandler("Qna.answer.init",[$form]); }, check:function($input) { if ($input.attr("required") == "required") { if ($input.val().length == 0) { $input.inputStatus("error"); } else { $input.inputStatus("success"); } } }, submit:function($form) { var data = $form.serialize(); $form.formStatus("loading"); $.ajax({ type:"POST", url:ENV.getProcessUrl("qna","answerWrite"), data:data, dataType:"json", success:function(result) { if (result.success == true) { if (result.message) iModule.alertMessage.show("success",result.message,5); Qna.answer.load(result.parent,result.idx); Qna.answer.reset($form); } else { $form.formStatus("error",result.errors); if (result.message) { iModule.alertMessage.show("error",result.message,5); } } }, error:function() { iModule.alertMessage.show("Server Connect Error!"); } }); }, select:function(idx,confirm) { var confirm = confirm == true ? "TRUE" : "FALSE"; $.ajax({ type:"POST", url:ENV.getProcessUrl("qna","answerSelect"), data:{idx:idx,confirm:confirm}, dataType:"json", success:function(result) { if (result.success == true) { if (result.modalHtml) { iModule.modal.showHtml(result.modalHtml); } else { location.href = location.href.split("#").shift(); } } else { if (result.message) { iModule.alertMessage.show("error",result.message,5); } } } }); return false; }, load:function(parent,idx) { $.ajax({ type:"POST", url:ENV.getProcessUrl("qna","getAnswer"), data:{parent:parent}, dataType:"json", success:function(result) { if (result.success == true) { Qna.answer.print(result); if (iModule.isInScroll($("#ModuleQnaAnswerItem-"+idx)) == false) { $("html,body").animate({scrollTop:$("#ModuleQnaAnswerItem-"+idx).offset().top - 100},"fast"); } } } }); }, print:function(result) { $("#ModuleQnaAnswerList-"+result.parent+" .empty").remove(); for (var i=0, loop=result.answers.length;i<loop;i++) { var answer = $(result.answers[i].html); answer.find("img").on("load",function() { if ($(this).parents(".wrapContent").innerWidth() < $(this).width()) { $(this).width($(this).parents(".wrapContent").innerWidth()); } }); if ($("#ModuleQnaAnswerItem-"+result.answers[i].idx).length == 0) { $("#ModuleQnaAnswerList-"+result.parent).append(answer); } } $(".liveUpdateQnaAnswer"+result.parent).text(result.answerCount); $(document).triggerHandler("Qna.answer.print",[result]); }, reset:function($form) { var parent = $("input[name=parent]",$form).val(); $form.reset(); $("input[name=parent]",$form).val(parent); Qna.answer.init($form.attr("id")); } }, ment:{ init:function(form) { var $form = $("#"+form); $form.formInit(Qna.ment.submit,Qna.ment.check); $(document).triggerHandler("Qna.ment.init",[$form]); }, check:function($input) { if ($input.attr("required") == "required") { if ($input.val().length == 0) { $input.inputStatus("error"); } else { $input.inputStatus("success"); } } }, submit:function($form) { var data = $form.serialize(); $form.formStatus("loading"); $.ajax({ type:"POST", url:ENV.getProcessUrl("qna","mentWrite"), data:data, dataType:"json", success:function(result) { if (result.success == true) { if (result.message) iModule.alertMessage.show("success",result.message,5); Qna.ment.load(result.parent,result.idx); Qna.ment.reset($form); } else { if (result.message) { iModule.alertMessage.show("error",result.message,5); } } } }); return false; }, load:function(parent,idx) { $.ajax({ type:"POST", url:ENV.getProcessUrl("qna","getMent"), data:{parent:parent}, dataType:"json", success:function(result) { if (result.success == true) { Qna.ment.print(result); if (iModule.isInScroll($("#ModuleQnaMentItem-"+idx)) == false) { $("html,body").animate({scrollTop:$("#ModuleQnaMentItem-"+idx).offset().top - 100},"fast"); } } } }); }, print:function(result) { $("#ModuleQnaMentList-"+result.parent+" .empty").remove(); for (var i=0, loop=result.ments.length;i<loop;i++) { var ment = $(result.ments[i].html); ment.find("img").on("load",function() { if ($(this).parents(".wrapContent").innerWidth() < $(this).width()) { $(this).width($(this).parents(".wrapContent").innerWidth()); } }); if ($("#ModuleQnaMentItem-"+result.ments[i].idx).length == 0) { $("#ModuleQnaMentList-"+result.parent).append(ment); } } $(".liveUpdateQnaMent"+result.parent).text(result.answerCount); $(document).triggerHandler("Qna.ment.print",[result]); }, reset:function($form) { var parent = $("input[name=parent]",$form).val(); $form.reset(); $("input[name=parent]",$form).val(parent); Qna.ment.init($form.attr("id")); } }, vote:{ good:function(idx,button) { if (button) { $(button).addClass("selected").attr("disabled",true); $(button).find(".fa").data("class",$(button).find(".fa").attr("class")).removeClass().addClass("fa fa-spinner fa-spin"); } $.ajax({ type:"POST", url:ENV.getProcessUrl("qna","vote"), data:{idx:idx,vote:"good"}, dataType:"json", success:function(result) { if (result.success == true) { iModule.alertMessage.show("default",result.message,5); $("."+result.liveUpdate).text(result.liveValue); } else { iModule.alertMessage.show("error",result.message,5); if (result.result === undefined || result.result != "GOOD") { $(button).removeClass("selected"); } } if (button) { $(button).attr("disabled",false); $(button).find(".fa").removeClass("fa-spinner fa-spin").addClass($(button).find(".fa").data("class")); } } }); }, bad:function(idx,button) { if (button) { $(button).addClass("selected").attr("disabled",true); $(button).find(".fa").data("class",$(button).find(".fa").attr("class")).removeClass().addClass("fa fa-spinner fa-spin"); } $.ajax({ type:"POST", url:ENV.getProcessUrl("qna","vote"), data:{idx:idx,vote:"bad"}, dataType:"json", success:function(result) { if (result.success == true) { iModule.alertMessage.show("default",result.message,5); $("."+result.liveUpdate).text(result.liveValue); } else { iModule.alertMessage.show("error",result.message,5); if (result.result === undefined || result.result != "BAD") { $(button).removeClass("selected"); } } if (button) { $(button).attr("disabled",false); $(button).find(".fa").removeClass("fa-spinner fa-spin").addClass($(button).find(".fa").data("class")); } } }); } }, sort:function(sort) { $("form[name=ModuleQnaListForm]").find("input[name=sort]").val(sort); $("form[name=ModuleQnaListForm]").submit(); } }; $(document).ready(function() { var temp = location.href.split("#"); if (temp.length == 2 && temp[1].indexOf("answer") == 0) { var answer = temp[1].replace("answer",""); if ($("#ModuleQnaAnswerItem-"+answer).length == 1) { $("html, body").animate({scrollTop:$("#ModuleQnaAnswerItem-"+answer).offset().top - 100},"fast"); } } $("a").on("click",function() { var temp = $(this).attr("href").split("#"); if (temp.length == 2 && location.href.split("#").shift().search(new RegExp(temp[0]+"$")) != -1 && temp[1].indexOf("answer") == 0) { var answer = temp[1].replace("answer",""); if ($("#ModuleQnaAnswerItem-"+answer).length == 1) { $("html, body").animate({scrollTop:$("#ModuleQnaAnswerItem-"+answer).offset().top - 100},"fast"); } } }); });
import React from "react"; import { Grid } from "../utils/style"; import styled, { keyframes } from "styled-components"; import GroupIcon from "@material-ui/icons/Group"; import LaptopChromebookIcon from "@material-ui/icons/LaptopChromebook"; import ContactSupportIcon from "@material-ui/icons/ContactSupport"; // animatons const sliderAnimeBottom = keyframes` 0% { transform: translateY(100%); opacity: 0; } 100% { transform: translateY(0); opacity: 1; } `; // css const StatSection = styled.section` animation: ${sliderAnimeBottom} 1s linear; color: #333; margin-top: 100px; h2 { text-align: center; font-weight: 600; font-size: 1.35rem; color: #001838; max-width: 500px; margin: 0 auto; margin-bottom: 2.6rem; } .MuiSvgIcon-root { color: #024daf; transform: scale(1.4); } p { margin: 0.3rem 0; font-size: medium; font-weight: 600; } `; const IndividualStat = styled.div` display: flex; align-items: center; justify-content: center; flex-direction: column; transform: scale(1.2); @media (max-width: 500px) { margin: 0.7rem 0; } `; const GridWrapper = styled(Grid)` @media (max-width: 500px) { grid-template-columns: 1fr; } `; const Stats = () => { return ( <StatSection> <h2> Welcome To ProLearner, Largest Online Learnig Platform For Programmers! </h2> <GridWrapper span={3}> <IndividualStat> <GroupIcon /> <p>10,323</p> <p>Learner</p> </IndividualStat> <IndividualStat> <LaptopChromebookIcon /> <p>233</p> <p>Courses</p> </IndividualStat> <IndividualStat> <ContactSupportIcon /> <p>24 H</p> <p>Mentor Support</p> </IndividualStat> </GridWrapper> </StatSection> ); }; export default Stats;
export const VISIBILITY_FILTERS = { ALL: '所有', COMPLETED: '已完成', INCOMPLETE: '代办' }
import Api from '../api' const signIn = '/signin' const signOutURL = '/signout' const Articles = { signIn(params) { return Api.request(signIn, { data: params, method: 'POST' }) }, signOut() { return Api.request(signOutURL, { method: 'POST' }) }, } export default Articles
import React from 'react'; import { storiesOf } from '@storybook/react'; import { text, number, select } from '@storybook/addon-knobs'; import Tooltip from './index'; import Card from '../_storybookWrappers/Card'; const stories = storiesOf('Components|Tooltip', module).addParameters({ component: Tooltip, componentSubtitle: 'Displays a tooltip component', }); stories.add('default', () => ( <Card center> <Tooltip tip="Default tip">Hover me</Tooltip> </Card> )); const positions = (defaultValue = 'left') => select( 'position', { left: 'left', right: 'right', }, defaultValue, ); stories.add('with all props', () => { const tip = text('tip', 'Place for tip'); const top = number('top', 20); const width = number('width', 100); return ( <Card center> <Tooltip position={positions()} tip={tip} top={top} width={width}> Hover me </Tooltip> </Card> ); });
(global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/index/top_search/host_list" ], { "305a": function(e, t, n) { n.r(t); var a = n("b1c5"), i = n("e60c"); for (var c in i) [ "default" ].indexOf(c) < 0 && function(e) { n.d(t, e, function() { return i[e]; }); }(c); n("6cd7"); var o = n("f0c5"), l = Object(o.a)(i.default, a.b, a.c, !1, null, "0f5bf110", null, !1, a.a, void 0); t.default = l.exports; }, "6cd7": function(e, t, n) { var a = n("c559"); n.n(a).a; }, "7af1": function(e, t, n) { Object.defineProperty(t, "__esModule", { value: !0 }), t.default = void 0; var a = n("371c"), i = { computed: { result: function() { return this.items.slice(0, this.max_length); } }, methods: { goDetail: function(e, t) { var n = ""; (0, a.sendCtmEvtLog)("".concat(this.source, "-热搜榜top").concat(t + 1)), "Fc::Building" !== e.viewable_type && a.UserLog.click_article("weixin_articles", e.viewable_id), n = e.jump_path ? e.jump_path : n = "Fc::Building" === e.viewable_type ? "/pages/building/main?building_id=".concat(e.viewable_id) : "/pages/packageA/web_article/main?id=".concat(e.viewable_id, "&title=").concat(encodeURIComponent(e.title), "&type=weixin_articles"), wx.navigateTo({ url: n }); } }, props: { items: { type: Array, default: [] }, max_length: { type: Number, default: 0 }, source: { type: String, default: "榜单页" } } }; t.default = i; }, b1c5: function(e, t, n) { n.d(t, "b", function() { return a; }), n.d(t, "c", function() { return i; }), n.d(t, "a", function() {}); var a = function() { var e = this; e.$createElement; e._self._c; }, i = []; }, c559: function(e, t, n) {}, e60c: function(e, t, n) { n.r(t); var a = n("7af1"), i = n.n(a); for (var c in a) [ "default" ].indexOf(c) < 0 && function(e) { n.d(t, e, function() { return a[e]; }); }(c); t.default = i.a; } } ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/index/top_search/host_list-create-component", { "pages/index/top_search/host_list-create-component": function(e, t, n) { n("543d").createComponent(n("305a")); } }, [ [ "pages/index/top_search/host_list-create-component" ] ] ]);
// 'use strict'; // self.addEventListener('push', function (event) { // console.log('[Service Worker] Push Received.'); // console.log(`[Service Worker] Push had this data: "${event.data.text()}"`); // const title = '키미노하나와'; // const options = { // body: '경고 알림 테스트중..', // icon: './imgs/icon.png', // badge: './imgs/badge.png', // }; // const notificationPromise = self.registration.showNotification(title, options); // event.waitUntil(notificationPromise); // }); // // self.addEventListener('push', ......); // // selft는 서비스 워커 자체를 참조한다. 따라서 서비스워커에 이벤트 리스터를 추가한다는 의미. // self.addEventListener('notificationclick', function (event) { // console.log(' [Service Worker] Notification click Received.'); // event.notification.close(); // event.waitUntil( // clients.openWindow('http://bokvengers.s3-website.ap-northeast-2.amazonaws.com') // ); // });
//variable xPosition controls the horizontal position of the visualization $(document).ready(function() { "use strict"; var av_name = "linkNodes5CON"; var av = new JSAV(av_name); // Load the config object with interpreter and code created by odsaUtils.js var config = ODSA.UTILS.loadConfig({av_name: av_name}), interpret = config.interpreter, // get the interpreter code = config.code; // get the code object var pseudo = av.code(code[0]); pseudo.hide(); var linkedListStartPositionX = 450; var linkedListStartPositionY = 50; // Slide 1 av.umsg("Consider we have the following list."); var list = av.ds.list({nodegap: 30, center: false, left: linkedListStartPositionX, top: linkedListStartPositionY}); list.addLast(20).addLast(30).addLast(10).addLast(5); var head = av.pointer("head", list.get(0)); list.layout(); av.displayInit(); // Slide 2 av.umsg("To add a new <tt>Link</tt> to the chain, we need to create it first."); pseudo.show(); pseudo.setCurrentLine(1); var newNode = list.newNode("8"); newNode.css({ top: 0, left: -80 }); var newLink = av.pointer("newLink", newNode,{anchor:"center bottom", myAnchor:"right top",top:-5, left:-35, arrowAnchor: "center bottom"}); newNode.highlight(); av.step(); // Slide 3 av.umsg("To add this <tt>Link</tt> to the head of the chain, we need to make the its <tt>next</tt> field point to the head node."); pseudo.setCurrentLine(2); list.addFirst(newNode); list.layout(); av.step(); // Slide 4 av.umsg("Now, the new <tt>Link</tt> is the first node in the chain, so we set <tt>head</tt> to point to it."); pseudo.setCurrentLine(3); head.target(newNode); list.layout(); newNode.unhighlight(); av.recorded(); });
({ searchProducts: function (component, event) { let name = event.getParam('name'); let spaceType = event.getParam('spaceType'); let type = event.getParam('type'); let pageSize = component.get('v.pageSize'); let page = component.get('v.page'); let offset = (page - 1) * pageSize; let action = component.get('c.searchProduct'); component.set('v.showSpinner', true); action.setParams({ 'name': name, 'spaceType': spaceType, 'type': type, 'resultLimit': pageSize, 'offset': offset }); action.setCallback(this, function (response) { if (response.getState() === "SUCCESS") { this.getPagesCount(component, event); component.set('v.recordsStart', offset + 1); component.set('v.recordsEnd', offset + response.getReturnValue().length); component.set('v.products', response.getReturnValue()); } if (response.getState() === "ERROR") { this.sendErrorMessage(response); } component.set('v.showSpinner', false); }); $A.enqueueAction(action); }, changePage: function (component, event) { let name = event.getParam('name'); let spaceType = event.getParam('spaceType'); let type = event.getParam('type'); let page = component.get('v.page'); let pageSize = component.get('v.pageSize'); let offset = (page - 1) * pageSize; let action = component.get('c.searchProduct'); component.set('v.showSpinner', true); action.setParams({ 'name': name, 'spaceType': spaceType, 'type': type, 'resultLimit': pageSize, 'offset': offset }); action.setCallback(this, function (response) { if (response.getState() === "SUCCESS") { component.set('v.recordsStart', offset + 1); component.set('v.recordsEnd', offset + response.getReturnValue().length); component.set('v.products', response.getReturnValue()); } if (response.getState() === "ERROR") { this.sendErrorMessage(response); } component.set('v.showSpinner', false); }); $A.enqueueAction(action); }, getPromotedProducts: function (component, event) { let action = component.get('c.getPromotedProducts'); component.set('v.showSpinner', true); action.setCallback(this, function (response) { if (response.getState() === "SUCCESS") { component.set('v.products', response.getReturnValue()); } if (response.getState() === "ERROR") { this.sendErrorMessage(response); } component.set('v.showSpinner', false); }); $A.enqueueAction(action); }, getPagesCount: function (component, event) { let name = event.getParam('name'); let spaceType = event.getParam('spaceType'); let type = event.getParam('type'); let action = component.get('c.getSearchCount'); action.setParams({ 'name': name, 'spaceType': spaceType, 'type': type }); action.setCallback(this, function (response) { if (response.getState() === "SUCCESS") { let results = response.getReturnValue(); component.set('v.productsCount', results); let pageCount = results / component.get('v.pageSize'); pageCount = Math.ceil(pageCount); if (pageCount == 0) { pageCount = 1; } component.set('v.pageCount', pageCount); if (results > 0) { this.sendMessage($A.get('$Label.c.GS_Success'), $A.get('$Label.c.GS_Search_Success_1') + ' ' + results + ' ' + $A.get('$Label.c.GS_Search_Success_2'), 'success'); } else { this.sendMessage($A.get('$Label.c.GS_Success'), $A.get('$Label.c.GS_Search_Without_Results'), 'info'); } } if (response.getState() === "ERROR") { this.sendErrorMessage(response); } }); $A.enqueueAction(action); }, sendErrorMessage: function (response) { let message; try { message = response.getError()[0].message; } catch (e) { message = $A.get('$Label.c.GS_Unknown_Error'); } this.sendMessage('Error', message, 'error'); }, sendMessage: function (title, message, type) { let toastParams = { title: title, message: message, type: type }; let toastEvent = $A.get("e.force:showToast"); toastEvent.setParams(toastParams); toastEvent.fire(); } });
const config = { serverSchemasDir: 'src/api/schemas/', gqlTypesDest: 'src/api/_generated/gqlTypes.d.ts', gqlNamespace: 'GqlTypes', }; const fs = require('fs'); const schema = getGQLSchemaFromServer(); createGQLTypes(); function createGQLTypes(){ const fromSchema = require('@gql2ts/from-schema'); let gqlTypes = fromSchema.generateNamespace(config.gqlNamespace, schema); gqlTypes +='\n export default ' + config.gqlNamespace + ';'; fs.writeFile(config.gqlTypesDest, gqlTypes); } function getGQLSchemaFromServer(){ const tools = require('graphql-tools'); const typeDefinitionsArray = []; fs.readdirSync(config.serverSchemasDir, {}).forEach((file) => { const f = fs.readFileSync(config.serverSchemasDir + file, 'utf8'); typeDefinitionsArray.push(f); }); return tools.makeExecutableSchema({ typeDefs: [...typeDefinitionsArray] }); }
import markerStrategy from '../src/strategies/marker'; import markerGroupStrategy from '../src/strategies/markergroup'; import pathStrategy from '../src/strategies/path'; import pathGroupStrategy from '../src/strategies/pathgroup'; import directionStrategy from '../src/strategies/direction/index'; describe('Marker Strategy', () => { test('MarkerStrategy is defined', () => { expect(markerStrategy).toBeDefined(); expect(markerStrategy({ size: "normal", location: "test" })).toBe( 'markers=size:normal%7Ctest' ); }); test('location prop is required', () => { expect(() => markerStrategy({})).toThrow( 'Marker expects a valid location' ); }); test('it parses valid marker props', () => { const wrapper = markerStrategy({ color: "red", size: "tiny", label: "P", iconURL: "testIcon", anchor: "topleft", location: "testLocation" }); expect(wrapper).toContain('color:red'); expect(wrapper).toContain('size:tiny'); expect(wrapper).toContain('label:P'); expect(wrapper).toContain('anchor:topleft'); expect(wrapper).toContain('testLocation'); expect(wrapper).not.toContain('location:testLocation'); expect(wrapper).toMatchSnapshot(); }); test('Marker group passes on all props from children except location', () => { const wrapper = markerGroupStrategy( { size: "tiny", color: "blue", label: "G", iconURL: "testIcon", anchor: "topleft", markers: [ { color: "green", location: "marker1" }, { color: "red", location: "marker2" }, { size: "small", color: "brown", label: "T", iconURL: "testIcon2", anchor: "topright", location: "marker3" } ] } ); expect(wrapper).toContain('color:blue'); expect(wrapper).toContain('size:tiny'); expect(wrapper).toContain('label:G'); expect(wrapper).toContain('icon:testIcon'); expect(wrapper).toContain('anchor:topleft'); expect(wrapper).not.toContain('color:green'); expect(wrapper).not.toContain('color:red'); expect(wrapper).not.toContain('color:brown'); expect(wrapper).not.toContain('size:small'); expect(wrapper).not.toContain('label:T'); expect(wrapper).not.toContain('icon:testIcon2'); expect(wrapper).not.toContain('anchor:topright'); expect(wrapper).toContain('marker1'); expect(wrapper).toContain('marker2'); expect(wrapper).toContain('marker3'); expect(wrapper).toMatchSnapshot(); }); }); describe('Path Strategy', () => { test('it is defined', () => { expect(pathStrategy).toBeDefined(); expect(pathStrategy({ weight: 5, points: "test" })).toBe('path=weight:5%7Ctest'); }); test('points prop is required', () => { expect(() => pathStrategy({})).toThrow( 'Path expects a valid points prop' ); }); test('it parses valid point props', () => { const wrapper = pathStrategy({ weight: 3, color: "blue", fillcolor: "red", geodesic: true, points: "test1" }); expect(wrapper).toContain('weight:3'); expect(wrapper).toContain('color:blue'); expect(wrapper).toContain('fillcolor:red'); expect(wrapper).toContain('geodesic:true'); expect(wrapper).toContain('test1'); expect(wrapper).not.toContain('points:test1'); expect(wrapper).toMatchSnapshot(); }); test('Path group passes on all props except points', () => { const wrapper = pathGroupStrategy({ weight: 2, color: 'red', fillcolor: 'blue', paths: [ { points: 'test1' }, { points: 'test2', geodesic: true }, { points: 'test3' }, ] }); expect(wrapper).toContain('weight:2'); expect(wrapper).toContain('color:red'); expect(wrapper).toContain('fillcolor:blue'); expect(wrapper).not.toContain('geodesic'); expect(wrapper).toContain('test1'); expect(wrapper).toContain('test2'); expect(wrapper).toContain('test3'); }); }); describe('Directions Strategy', () => { test('it is defined', () => { expect(directionStrategy).toBeDefined(); }); test('origin prop is required', () => { expect(() => directionStrategy({})).toThrow( 'Origin prop is required' ); }); test('destination prop is required', () => { expect(() => directionStrategy({ origin: 'testOrigin' })).toThrow( 'Destination prop is required' ); }); });
const exec = require('child_process').exec; const http = require('http'); const fs = require('fs'); const server = http.createServer((request, response) => { switch (request.url) { case '/dotnet': exec('dotnet --version', (error, stdout, stderr) => { if (error) { response.end('Error: ' + error); } else { response.end('dotnet: ' + stdout); } }); break; case '/fs/Procfile': const procfile = fs.readFileSync('Procfile'); response.end(procfile); break; case '/fs/package.json': const packagejson = fs.readFileSync('package.json'); response.end(packagejson); break; case '/fs/server.js': const serverjs = fs.readFileSync('server.js'); response.end(serverjs); break; case '/process': response.end(JSON.stringify({ version: process.version, env: process.env, })); break; default: response.end('Hello world!'); } }); const port = process.env.PORT || 8080; server.listen(port, (err) => { if (err) { return console.log('something bad happened', err); } console.log(`server is listening on ${port}`); })
/** * Created by yangchunrun on 17/2/23. */ exports.install = function (Vue, options) { Vue.http.options.headers = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }; Vue.http.options.emulateJSON = true; Vue.prototype.callHttp = function (method, url, data, callback) { var params = {_token: Laravel.csrfToken}; if (typeof data !== "undefined") { params = Object.assign(data, params); } if (method == 'GET') { var get = params; } Vue.http({url: url, method: method, body: params, params: get}) .then(response => { var responseJson = response.data; this.func = callback; this.func(responseJson); }, response => { var responseJson = response.data; if (responseJson.error == 'Unauthenticated.') { location.href = '/admin/login'; } else { var errorStr = ''; for (var item in responseJson) { errorStr += responseJson[item][0] + ";"; } toastr.error(errorStr, '出错啦!'); } }); } Vue.prototype.can = function (as) { var permissions = window.Permissions; if ($.inArray(as, permissions)>-1 || window.User.id == 1) { return true; } return false; } };
import './nav.html'; import './nav.css'; Template.nav.events({ 'click .logout': function(e) { e.preventDefault(); Meteor.logout(); FlowRouter.redirect('/users/login'); } })
import React, { Component } from 'react'; import classnames from 'classnames'; import PropTypes from 'prop-types'; import isEqual from 'lodash/isEqual'; class ImgSlider extends Component { constructor(props) { super(props); this.state = { index: 0, transition: true, big: false, console: 0, zoom: 1, items: props.items, }; this.onTouchStart = this.onTouchStart.bind(this); this.onTouchMove = this.onTouchMove.bind(this); this.onTouchEnd = this.onTouchEnd.bind(this); } componentWillReceiveProps(nextProps) { if (!isEqual(nextProps.items, this.state.items)) { this.setState({ items: nextProps.items, index: 0, }); } } onTouchStart(e) { this.touchSize = e.touches.length; this.touchStartX = e.touches[0] ? e.touches[0].pageX : 0; // e.preventDefault(); // if (this.state.big && this.touchSize === 2) { // this.touchStartY = e.touches[0] ? e.touches[0].pageY : 0; // this.touchStartX2 = e.touches[1] ? e.touches[1].pageX : 0; // this.touchStartY2 = e.touches[1] ? e.touches[1].pageY : 0; // } // if (this.state.big && this.touchSize === 2) { // this.touchEndX = e.touches[0] ? e.touches[0].pageX : 0; // this.touchEndY = e.touches[0] ? e.touches[0].pageY : 0; // this.touchEndX2 = e.touches[1] ? e.touches[1].pageX : 0; // this.touchEndY2 = e.touches[1] ? e.touches[1].pageY : 0; // const distance = Math.sqrt((this.touchEndX2 - this.touchEndX) ** 2 + (this.touchEndY2 - this.touchEndY) ** 2 ) // this.firstDistance = distance; // } } onTouchMove(e) { // let domThis = ReactDOM.findDOMNode(this); // let domContent = domThis.querySelector('.content'); // domContent.style.transition = ''; // let gap = e.touches[0].screenX - this.touchLast.screenX; // this.translateX = this.translateX + gap; // // console.log(gap); // domContent.style.transform = `translateX(${this.translateX}px)`; // // console.log(domContent.style.transform); // this.touchLast = e.touches[0]; // e.preventDefault(); } onTouchEnd(e) { this.firstDistance = null; // let newIndex = this.state.index; // console.log(deltaX, "++++++++"); // if (this.touchEnd.screenX > this.touchStart.screenX && index<this.props.items.length - 1) { // nexIndex = this.state.index; // } // const reset = () => { // if (this.state.index === 0) { // this.setState({ // transition: false, // }, () => { // setTimeout(() => { // this.setState({ // index: this.props.items.length, // }); // }, 50); // }); // } // if (this.state.index === this.props.items.length + 1) { // this.setState({ // transition: false, // }, () => { // setTimeout(() => { // this.setState({ // index: 1, // }); // }, 50); // }); // } // }; if (this.touchSize === 1) { this.touchEndX = e.changedTouches[0] ? e.changedTouches[0].pageX : 0; const deltaX = this.touchEndX - this.touchStartX; if (deltaX > 30 && this.state.index > 0) { this.setState({ index: this.state.index - 1, }); } if (deltaX < -30 && this.state.index < this.props.items.length - 1) { this.setState({ index: this.state.index + 1, }); } } // 向左 // if (deltaX > 50) { // this.setState({ // transition: true, // }, () => { // this.setState({ // index: newIndex - 1, // }, () => { // setTimeout(reset, 600); // }); // }); // } // 向右 // if (deltaX < -50) { // this.setState({ // transition: true, // }, () => { // this.setState({ // index: newIndex + 1, // }, () => { // setTimeout(reset, 600); // }); // }); // } } // componentWillReceiveProps(nextProps) { // } render() { return ( <div className={classnames('bmui-img-slider', { hide: this.props.show, big: this.props.big, })} style={{ width: this.props.width, height: this.props.height, }} > <div onTouchStart={this.onTouchStart} onTouchMove={this.onTouchMove} onTouchEnd={this.onTouchEnd} className="content" style={{ transform: `translateX(-${100 * this.state.index}%)`, // transition: this.state.transition ? this.transition transition: this.state.transition ? 'all .5s ease' : null, }} > {/* <section> <img src={this.props.items[this.props.items.length - 1].src} alt="" /> </section> */} {this.state.items.map((item, i) => ( <section onClick={(e) => { this.props.onItemClick(item, e); }} key={i} > <img onClick={(e) => { // if (this.props.big) { // this.setState({ // big: !this.state.big, // }); // } if (this.props.disableImgClick) { e.preventDefault(); } }} src={item} style={{ maxHeight: this.props.big ? '100%' : this.props.height, maxWidth: this.props.big ? '100%' : this.props.width, }} alt="" /> </section> ))} {/* <section> <img src={this.props.items[0].src} alt="" /> </section> */} </div> {this.props.showBubble ? ( <ul className="bubble-list"> {this.state.items.map((item, i) => ( <li className={classnames('pull-left', { active: this.state.index === i, })} key={i} /> ))} </ul> ) : null} {/* <h2 style={{ position: 'absolute', bottom: 10, left: 0, color: 'white', width: 30, height: 10, fontSize: 20, }} >{this.state.console}</h2> */} </div> ); } } ImgSlider.propTypes = { show: PropTypes.bool, items: PropTypes.array, width: PropTypes.string, height: PropTypes.string, onItemClick: PropTypes.func, theme: PropTypes.string, showBubble: PropTypes.bool, disableImgClick: PropTypes.bool, big: PropTypes.bool, }; ImgSlider.defaultProps = { show: false, items: [], width: '100vw', height: '50vw', theme: 'orange', onItemClick: () => {}, showBubble: true, disableImgClick: false, big: false, }; export default ImgSlider;
db.collection('RegisteredUser').onSnapshot(function (snapshot) { var htmlAll = ""; var childCounts = snapshot.size; var t = 0; var i = childCounts + 1; console.log(childCounts); snapshot.forEach(function (doc) { var childUID = doc.id; var childData = doc.data(); if (t == 0) { htmlAll = ""; } t++; i--; var html = ""; let style = ""; if (childData.Role === "admin") { style = "color:red;"; } html += ` <tr> <td>${i}</td> <td><img src="${childData.photo}" alt="" srcset=""></td> <td>${childData.Username}</td> <td>${childData.Email}</td> <td>${childData.Role}</td> <td> <a href="#User" id="admin" class="icon" onclick="promoteUser(this, '${childUID}')"><i class="fas fa-user-tie" style ="${style}"></i></a> <a href="#deleteUser" class="icon" onclick="deleteUser('${childUID}')"><i class="fas fa-trash-alt"></i></a> </td> </tr> `; htmlAll = html + htmlAll; if (t == childCounts) { document.getElementById("users").innerHTML = htmlAll; } }); }); function deleteUser(childUID) { db.collection("RegisteredUser").doc(childUID).delete().catch(console.log); } function promoteUser(element, childUID) { element.style.color = 'red'; db.collection("RegisteredUser").doc(childUID).update({ Role: 'admin' }).catch(console.log); } /// count db.collection('RegisteredUser').get().then(function (snapshot) { var childCounts = snapshot.size; document.getElementById("countuser").innerHTML = childCounts; });
import React, { Component, PropTypes } from 'react' import { connect } from 'react-redux' import { Link } from "react-router"; // import OutfitsList from "../../components/OutfitsList" import OutfitsFilters from "../../components/OutfitsFilters" import { fetchOutfits } from '../../actions/OutfitsActions.js' import CreateLookbookListOutfits from "../../components/CreateLookbookListOutfits" export default class CreateLookbook extends Component { constructor() { super(); this.state = { selectBox:"" } } handleSelectBox(e){ let el = e.target.id; if (this.state.selectBox=="") { this.setState({selectBox: el}) } else { this.setState({selectBox:""}) } } render() { const { dispatch, dataOutfits } = this.props const category = [ {"name": "Vetements", "id":"3"}, {"name": "Chaussures", "id":"4"} ] return ( <div className="app-outfits"> <CreateLookbookListOutfits fetchOutfits={() => dispatch(fetchOutfits())} dataOutfits={dataOutfits} /> </div> ); } } function mapStateToProps(state) { const { fetchOutfits } = state const { dataOutfits } = fetchOutfits return { dataOutfits } } export default connect(mapStateToProps)(CreateLookbook)
'use strict' angular.module('main') .controller('ProjectsTasksListController', ['$scope', '$routeParams', 'ProjectTask', 'Config', function ($scope, $routeParams, ProjectTask, Config) { $scope.project_id = $routeParams.id; $scope.tasks = ProjectTask.query({id: $scope.project_id}); $scope.status = Config.project.status; }]);
/* * @lc app=leetcode.cn id=150 lang=javascript * * [150] 逆波兰表达式求值 */ // @lc code=start /** * @param {string[]} tokens * @return {number} */ var evalRPN = function(tokens) { let temp = []; for (let i = 0; i < tokens.length; i++) { if (chargeCode(tokens[i])) { temp.push(tokens[i]); } else { let len = temp.length; let result = typeCodeAndSum(tokens[i], temp[len - 2], temp[len - 1]); temp.pop(); temp.pop(); temp.push(result) } } return temp[0] }; var chargeCode = (val) => { if (val !== '+' && val !== '-' && val !== '*' && val !== '/') { return true; } return false; } var typeCodeAndSum = (code, val1, val2) => { val1 = Number(val1) val2 = Number(val2) let res = 0; switch(code) { case'+': res = val1 + val2;break; case'-': res = val1 - val2;break; case'*': res = val1 * val2;break; case'/': if (val1 / val2 > 0) { res = Math.floor(val1 / val2) } else { res = Math.ceil(val1 / val2) } break; } return res; } // @lc code=end
import React from 'react' import { View } from 'react-native' import COLORS from "./../constants/Colors" export default props => <View style={[{ height: 1, backgroundColor: COLORS.line }, props.style]} />
import { ContentState, convertFromRaw, convertToRaw, EditorState, } from 'draft-js'; import React, {Component} from 'react'; import ReactDOM from 'react-dom'; import Loader from './Loader'; import Workspace from './Workspace'; import getSessionId from './getSessionId'; import {getHello} from './hello'; import './App.css'; const GRID_PROBE_WIDTH = 10000; const {moveFocusToEnd} = EditorState; const MODES = Object.freeze({ CONTROL: 'control', INSERT: 'insert', LOAD: 'load', }); // [key, message, callback] const NOTICES = Object.freeze({ DELETE: 'delete', CONTROL: 'control', }); const notices = { delete: [ 'Delete? y/N', function({key}) { switch (key) { case 'y': case 'Y': localStorage.removeItem( this.state.documents[this.state.loadIndex] ); this.setState(({documents, loadIndex}) => { const newDocuments = [ ...documents.slice(0, loadIndex), ...documents.slice(loadIndex + 1), ]; const newLoadIndex = Math.max( 0, Math.min(loadIndex, documents.length - 2) ); return { documents: newDocuments, editors: this.getEditors( newDocuments[newLoadIndex] ), notice: null, loadIndex: newLoadIndex, }; }); break; case 'n': case 'N': case 'Enter': this.setState({notice: null}); break; default: break; } }, ], control: ['Control mode'], }; class App extends Component { state = { cX: 0, cY: 0, documents: [], editors: [], gridGap: null, hash: null, keyStates: {}, lastFocus: 0, loadIndex: 0, mode: MODES.INSERT, notice: null, showGrid: false, }; componentDidMount() { window.addEventListener('click', this.handleClick); window.addEventListener('hashchange', this.handleHashChange); window.addEventListener('resize', this.measure); window.addEventListener('keydown', this.handleKeydown); window.addEventListener('keyup', this.handleKeyup); this.handleHashChange(); } componentWillUnmount() { window.removeEventListener('click', this.handleClick); window.removeEventListener('hashchange', this.handleHashChange); window.removeEventListener('resize', this.measure); window.removeEventListener('keydown', this.handleKeydown); window.removeEventListener('keyup', this.handleKeyup); } componentDidUpdate(prevProps, prevState) { if (typeof this.state.gridGap !== 'number' && this.GridProbe) { const gridGap = (ReactDOM.findDOMNode(this.GridProbe).offsetWidth / GRID_PROBE_WIDTH) * 2; document.documentElement.style.setProperty( '--grid-gap', `${gridGap}px` ); this.setState({gridGap}); } else if (typeof prevState.gridGap !== 'number') { this.measure(); } } measure = () => { const container = ReactDOM.findDOMNode(this.Container); const cX = container.clientWidth / 2; const cY = container.clientHeight / 2; this.setState({cX, cY}); }; // TODO(riley): Store editors in Dexie or PouchDB. getEditors = hash => { const rawDraftEditors = window.localStorage.getItem(hash); return rawDraftEditors ? JSON.parse(rawDraftEditors).map(({x, y, editorRawContent}) => ({ x, y, editorProps: { // TODO(riley): Save and restore props. textAlignment: 'center', spellCheck: false }, editorState: moveFocusToEnd( EditorState.createWithContent( convertFromRaw(editorRawContent) ) ), })) : [ { x: 0, y: 0, editorProps: {textAlignment: 'center', spellCheck: false}, editorState: moveFocusToEnd( EditorState.createWithContent( ContentState.createFromText(`${getHello()}.`) ) ), }, ]; }; load = hash => { document.title = 'Write | ' + hash .split('-') .map(word => word[0].toUpperCase() + word.slice(1)) .join(' '); this.setState({ hash, editors: this.getEditors(hash), mode: MODES.INSERT, }); }; handleHashChange = () => { let {hash} = window.location; if (hash) { this.load(hash.slice(1)); } else this.createNewDocument(); }; createNewDocument = () => { const hash = getSessionId(); window.history.pushState(null, null, `#${hash}`); this.load(hash); }; handleClick = ({metaKey, pageX, pageY}) => { if (metaKey) { this.setState(({cX, cY, editors, gridGap, lastFocus}) => ({ editors: [ ...editors, { // TODO(riley): Latch to the grid on render, not on construction. x: Math.round((pageX - cX) / gridGap) * gridGap, y: Math.round((pageY - cY) / gridGap) * gridGap, editorProps: {...editors[lastFocus].editorProps}, editorState: moveFocusToEnd(EditorState.createEmpty()), }, ], lastFocus: editors.length, })); } else if ( !this.state.editors.some(({editorState}) => editorState.getSelection().getHasFocus() ) ) { const {Container: {Editors = []} = {}} = this; if (Editors.length) Editors[0].focus(); } }; handleChange = (newEditorState, i) => { const {hash, editors, lastFocus} = this.state; // Update the focused Editor and remove any empty, unfocused ones. const updatedEditors = [ ...editors.slice(0, i), {...editors[i], editorState: newEditorState}, ...editors.slice(i + 1), ].filter( ({editorState}) => editorState.getSelection().getHasFocus() || editorState.getCurrentContent().hasText() || lastFocus === i ); // Persist the current state to localStorage and state. const rawDraftEditors = JSON.stringify( updatedEditors.map(({x, y, editorState}, j) => ({ x, y, editorRawContent: convertToRaw( (i === j ? newEditorState : editorState ).getCurrentContent() ), })) ); window.localStorage.setItem(hash, rawDraftEditors); this.setState({editors: updatedEditors, lastFocus: i}); }; handleKeyup = e => { const {key} = e; this.setState({ keyStates: { ...this.state.keyStates, [key]: false, }, }); }; handleKeydown = e => { const {key, metaKey, repeat} = e; if (repeat) return; const {documents, keyStates, loadIndex, mode, notice} = this.state; this.setState({ keyStates: { ...keyStates, [key]: true, }, }); if (notice && notices[notice][1]) { notices[notice][1].call(this, e); if (!metaKey) { e.preventDefault(); e.stopPropagation(); } } else if (mode === MODES.LOAD) { switch (key) { case 'ArrowUp': this.setState(({documents, loadIndex}) => { const newIndex = (documents.length + loadIndex - 1) % documents.length; return { loadIndex: newIndex, editors: this.getEditors(documents[newIndex]), }; }); break; case 'ArrowDown': this.setState(({documents, loadIndex}) => { const newIndex = (loadIndex + 1) % documents.length; return { loadIndex: newIndex, editors: this.getEditors(documents[newIndex]), }; }); break; case 'Enter': const newDocument = documents[loadIndex]; window.history.pushState(null, null, `#${newDocument}`); this.load(newDocument); this.setState({mode: MODES.INSERT}); break; case 'ArrowRight': // Stub: Navigate document history. break; case 'c': case 'C': // Stub: Duplicate. break; case 'd': case 'D': this.setState({notice: NOTICES.DELETE}); break; case 'r': case 'R': // Stub: Rename. break; case 'q': case 'Q': this.setState({mode: MODES.INSERT}); break; default: break; } if (!metaKey) { console.log(`Prevented a ${key}`); e.preventDefault(); e.stopPropagation(); } } else if (mode === MODES.CONTROL && !metaKey) { switch (key) { case 'ArrowLeft': this.setState(({editors, lastFocus}) => { const editor = editors[lastFocus]; const updatedEditors = [ ...editors.slice(0, lastFocus), { ...editor, editorProps: { ...editor.editorProps, textAlignment: editor.editorProps.textAlignment === 'right' ? 'center' : 'left', }, }, ...editors.slice(lastFocus + 1), ]; return { editors: updatedEditors, mode: MODES.INSERT, }; }); break; case 'ArrowRight': this.setState(({editors, lastFocus}) => { const editor = editors[lastFocus]; const updatedEditors = [ ...editors.slice(0, lastFocus), { ...editor, editorProps: { ...editor.editorProps, textAlignment: editor.editorProps.textAlignment === 'left' ? 'center' : 'right', }, }, ...editors.slice(lastFocus + 1), ]; return { editors: updatedEditors, mode: MODES.INSERT, }; }); break; case 'g': case 'G': this.setState(({showGrid}) => ({ mode: MODES.INSERT, showGrid: !showGrid, })); break; case 'n': case 'N': this.createNewDocument(); break; case 'o': case 'O': this.setState(() => { const documents = Object.keys(localStorage); const hash = window.location.hash && window.location.hash.slice(1); return { documents, loadIndex: Math.max(0, documents.indexOf(hash)), mode: MODES.LOAD, }; }); break; case 's': case 'S': this.setState(({editors, lastFocus}) => { const editor = editors[lastFocus]; const updatedEditors = [ ...editors.slice(0, lastFocus), { ...editor, editorProps: { ...editor.editorProps, spellCheck: !editor.editorProps.spellCheck, }, }, ...editors.slice(lastFocus + 1), ]; return { editors: updatedEditors, mode: MODES.INSERT, }; }); break; default: this.setState({mode: MODES.INSERT}); return; } e.preventDefault(); e.stopPropagation(); } else if (metaKey && key.toLowerCase() === 'e') { // If it's in insert or control mode, toggle to the other one. Otherwise, don't change the mode. this.setState(({mode}) => ({ mode: {insert: MODES.CONTROL, control: MODES.INSERT}[mode] || mode, })); } }; render() { const { cX, cY, documents, editors, gridGap, hash, keyStates, lastFocus, loadIndex, mode, notice, showGrid, } = this.state; const sized = typeof gridGap === 'number'; return ( <div className={`App${ sized && (showGrid || mode === 'control' || keyStates.Meta) ? ' show-grid' : '' } control-mode-${mode === 'control' ? 'on' : 'off'}`} style={ sized ? { backgroundSize: `${gridGap}px ${gridGap}px`, lineHeight: `${gridGap}px`, } : {} } > {hash && (sized ? ( <> {mode === MODES.LOAD && ( <Loader documents={documents} index={loadIndex} /> )} {notice && ( <p> <strong className="App-notice"> {notices[notice][0]} </strong> </p> )} <Workspace cX={cX} cY={cY} editors={editors} lastFocus={lastFocus} onChange={this.handleChange} ref={el => (this.Container = el)} /> </> ) : ( <span className="Grid-probe" ref={el => (this.GridProbe = el)} > {new Array(GRID_PROBE_WIDTH).fill('0').join('')} </span> ))} </div> ); } } export default App;
import gameStart from "./gameMock"; let game; beforeEach(() => { game = gameStart(); }); describe("test game", () => { test("check for game start", () => { expect(typeof game).toBe("object"); }); test("check if all four scenes exist", () => { // eslint-disable-next-line expect(game.scene._pending.length).toBe(4); }); test("expect scenes not to be less than 1", () => { // eslint-disable-next-line expect(game.scene._pending.length).toBeGreaterThan(0); }); });
export default function select (state) { return { isLoggedIn: state.auth.user !== null, user: state.auth.user, failure: !!state.auth.failure, failureMsg: state.auth.failure } }
import { NextSeo } from 'next-seo' import React from 'react' import axios from 'axios' import { useTranslation } from 'react-i18next' import useSWR from 'swr' import Layout from '../components/layout/Layout' import { PAGES } from '../config/api' import Skeleton from 'react-loading-skeleton' const DonateUs = () => { const { t } = useTranslation() const { data: p } = useSWR( PAGES + '/136', () => axios.get(PAGES + '/136').then(res => res.data), { refreshInterval: 1000 } ) const topBanner = p ? ( <div key={p.id} className="position-relative"> <img src={p.acf.image.url} alt="" className="w-100" style={{ height: '50vh', minHeight: '400px', objectFit: 'cover' }} /> <div className="position-absolute" style={{ left: 0, right: 0, top: '50%', transform: 'translateY(-50%)' }} > <div className="container"> <h4 className="mb-0 text-white text-center text-uppercase" style={{ fontSize: '2rem' }} > { t('a.d', { d_mon: p.title.rendered, d_mm: p.acf.title_mm }) } </h4> </div> </div> </div> ) : ( <> <Skeleton height={400} style={{ display: 'block' }} /> </> ) const lists = p ? ( <div className="row" key={p.id}> <div className="col-12 col-md-8 mb-4 mb-md-0"> <div className="text-color" dangerouslySetInnerHTML={{ __html: t('a.d', { d_mon: p.acf.description_mon, d_mm: p.acf.description_mm }) }} style={{ lineHeight: '2em' }} /> </div> <div className="col-12 col-md-4"> </div> </div> ) : ( <div className="row"> <div className="col-12 col-md-8 mb-4 mb-md-0"> <div className="mb-3" style={{lineHeight:2}}> <Skeleton count={5} height={21} /> </div> </div> <div className="col-12 col-md-4"> </div> </div> ) const w = typeof window !== 'undefined' ? window.location.href : 'undefined' const title = p ? ( t('a.d', { d_mon: p.title.rendered, d_mm: p.acf.title_mm }) + ' - ' + t('site.main') ) : ( 'ကော့ဒွတ်ကျေးရွာ' ) return ( <> <NextSeo title={title} description={ p && t('a.d', { d_mon: p.acf.info_mon, d_mm: p.acf.info_mm })} canonical={w} openGraph={{ url: w, title: title, description: p && t('a.d', { d_mon: p.acf.info_mon, d_mm: p.acf.info_mm }), images: [ { url: p && p.acf.image.url, width: 900, height: 800, alt: 'About Village - KawtDut Village', } ], }} /> <Layout> {topBanner} <div className="bg-color" style={{ padding: '4rem 0' }} > <div className="container"> {lists} </div> </div> </Layout> </> ) } export default DonateUs
$(function() { $.get("../app/vip/customer/treasure",{token:getCookie("token")},function(result){ var data=result.hetongs; var s1=" <div class='swiper-slide' style='background-image:url(img/1@2x.png)'><img src='img/22x.png' /><p class='time'>起始时间</p><p class='date'>SHIJIAN</p><p class='rate'>年化<span class='num'>NIANHUA</span>收益</p><div class='information'><p><span class='one'>方案号</span><span class='two'>FANGANHAO</span></p> <p><span class='three'>方案期限</span><span class='four'>QIXIAN</span></p><p><span class='five'>投资总额</span><span class='six'>ZONGE元</span></p> <p><span class='seven'>预期收益</span><span class='eight'>YUQI元</span></p> </div><p class='msg'><a href='javascript:;' onclick='detail(\"P\")'>查看详情<img src='img/3@2x.png'></a></p></div>"; //var s2=" <div class='swiper-slide' style='background-image:url(img/4@2x.png)'><p class='fanganhao'>方案号FANGANHAO&nbsp;&nbsp;&nbsp;SHIJIAN</p><img src='img/8@2x.png' class='circle'><p class='nianhuashouyi'>年化收益率</p><p class='baifenbi'>NIANHUA<span class='fuhao'>%</span></p><p class='shuzi'><span class='liu'>QIXIAN</span><span class='baqian'>ZONGE</span><span class='ershi'>YUQI</span></p><p class='wenzi'><span class='fanganqixian'>方案期限</span><span class='touzizonge'>投资总额</span><span class='yijishouyi'>预期收益</span></p><p class='msg1'><a href='javascript:;' onclick='detail(ID)'>查看详情<img src='img/3@2x.png'></a></p></div>"; var str=""; for(var i in data){ str+=s1. replace(/FANGANHAO/,data[i].hetonghao). replace(/SHIJIAN/,data[i].kaishi). replace(/NIANHUA/,data[i].lilv). replace(/QIXIAN/,data[i].qixian+"天"). replace(/ZONGE/,data[i].jine). replace(/YUQI/,data[i].yuqi). replace(/P/,data[i].hetonghao); } if(str==""){ str+="<img src='img/wushuju.png' class='wsj'/>"; } $("div.swiper-wrapper").html(str); }); }) function getCookie(name) { var arr=document.cookie.split('; '); var i=0; for(i=0;i<arr.length;i++) { //arr2->['username', 'abc'] var arr2=arr[i].split('='); if(arr2[0]==name) { var getC = decodeURIComponent(arr2[1]); return getC; } } return ''; } function detail(hetonghao){ setCookie("hetonghao",hetonghao,99999); setCookie("type",2,99999); window.location.href="fanganhao.html" } function setCookie(name, value, iDay) { var oDate=new Date(); oDate.setDate(oDate.getDate()+iDay); document.cookie=name+'='+encodeURIComponent(value)+';expires='+oDate; }
/** @jsxImportSource @emotion/core */ import { css } from "@emotion/core"; import { useState } from 'react'; import { activeDays } from "./helpers/weeklyLogs" import { totalHourReducer, hourForWeek, updateTimeLog } from "./helpers/updateHourLog" import "./App.css"; import TableRowData from "./components/DailyValueLogs/TableRowData" import HoursForTheWeek from './components/DailyValueLogs/HoursWeek' import TableHeader from "./components/DailyValueLogs/TableHeader" const table = css` background-color: #434a52; min-width:550px; `; const Main = () => { const [dailyTimeLog, setDailyTimeLog] = useState(() => activeDays); const [hoursWorkedDaily, setHoursWorkedDaily] = useState(() => hourForWeek(activeDays) ); const [hoursWorkedWeek, setHoursWorkedWeek] = useState(0); function updateWeeklyHours(updateLogs) { const newData = (updateTimeLog(dailyTimeLog, updateLogs)); setDailyTimeLog([...newData]); updateDailyHoursWorked(dailyTimeLog); } function updateDailyHoursWorked(dailyTimeLog = []) { // update the hours for each day const hoursWorked = hourForWeek(dailyTimeLog); setHoursWorkedDaily([ ...hoursWorked]); updateWeeklyHoursWorked(hoursWorked); } function updateWeeklyHoursWorked(hourLogs = []) { // updates the total hours for the week const hoursWorked = hourLogs.map((x) => x.hours); setHoursWorkedWeek(hoursWorked.reduce(totalHourReducer)); } return ( <main> <HoursForTheWeek hoursWorkedWeek={hoursWorkedWeek} /> <table css={table}> <thead> <TableHeader /> </thead> <tbody> {dailyTimeLog.map((dailyValue) => { const dailyHours = hoursWorkedDaily.find(x=> x.id === dailyValue.id) return ( <> <TableRowData key={dailyValue.id} dayId={dailyValue.id} dayOfWeek={dailyValue.day} timeLog={dailyValue.timeLog} updateTimeLog={updateWeeklyHours} dailyHours={dailyHours.hours } /> </> );} ) } </tbody> </table> </main> ); }; function App() { return ( <div> <Main /> </div> ); } export default App;
//calling another function inside of function function fruitQuantity(x1) { return 5 * x1; } function fruitShake(x, y) { const t1 = fruitQuantity(x); const t2 = fruitQuantity(y); const juice = `Juice with ${t1} and ${t2} quantity fruits`; return juice; } console.log(fruitShake(4, 5));
import React, { useMemo, useCallback, useState } from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faCircle, faTrash } from '@fortawesome/free-solid-svg-icons'; import { useWorkspace } from '../../../contexts/providers/WorkspaceContextProvider'; import useModal from '../../../hooks/useModal'; import './WorkspaceNavList.scss'; export default function WorkspaceNavList({ currentWorkspace, active }) { const workspace = useWorkspace(); const { ModalRoot, promptDelete } = useModal(); const loading = workspace.workspaceLoading || workspace.projectLoading; const { workspaceId, projects, config } = currentWorkspace; const { activeProjectId, activeProjectTabs } = config; const [hovering, setHovering] = useState(null); const handleProjectClick = useCallback((evt) => { if (loading) { return; } const { pid } = evt.target.dataset; const updatedConfig = { ...config, activeProjectId: pid, activeProjectTabs: [ ...activeProjectTabs, ...(activeProjectTabs.map((item) => item.toLowerCase()).indexOf(pid.toLowerCase()) === -1 ? [pid] : []) ] }; workspace.actions.updateWorkspaceConfig(workspaceId, updatedConfig, true); }, [ workspaceId, config, activeProjectTabs, workspace.actions, loading ]); const handleMouseEnter = useCallback((evt) => { if (loading) { return; } const { pid } = evt.target.dataset; setHovering(pid); }, [setHovering, loading]); const handleMouseLeave = useCallback(() => { setHovering(null); }, [setHovering]); const renderProjects = useMemo(() => { if (!currentWorkspace || !projects.length) { return (<li className="ws-project-item" />); } return projects.map((project) => { const tabOpen = active && activeProjectTabs && activeProjectTabs.find((x) => x.toLowerCase() === project.projectId.toLowerCase()); const tabActive = active && activeProjectId && activeProjectId.toLowerCase() === project.projectId.toLowerCase(); const removeProject = (evt) => { evt.stopPropagation(); evt.preventDefault(); if (loading) { return; } const { projectId } = project; if (currentWorkspace.workspaceId && projectId) { promptDelete().then(() => workspace.actions.deleteProject(currentWorkspace.workspaceId, projectId)); } }; const renderHoverActions = () => { if (hovering !== project.projectId) { return null; } return ( <button className="remove-project" onClick={removeProject}> <FontAwesomeIcon icon={faTrash} /> </button> ); }; return ( <li className={`ws-project-item ${tabActive ? 'tab-active' : ''}`} key={project.projectId} data-pid={project.projectId} onClick={handleProjectClick} role="button" onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} > {tabOpen ? <FontAwesomeIcon icon={faCircle} data-pid={project.projectId} /> : null} <div data-pid={project.projectId} className="ws-project-item-text"> <span data-pid={project.projectId}>{project.projectName}</span> </div> {renderHoverActions()} </li> ); }); }, [ currentWorkspace, projects, activeProjectId, activeProjectTabs, handleProjectClick, handleMouseEnter, handleMouseLeave, hovering, promptDelete, loading, workspace.actions, active ]); return ( <React.Fragment> <ul className="workspace-nav-list"> {renderProjects} </ul> <ModalRoot /> </React.Fragment> ); }
import * as types from 'kitsu/store/types'; import { Kitsu } from 'kitsu/config/api'; export const fetchMedia = (id, type) => async (dispatch, getState) => { // console.log("##### Fetching media: ", id) dispatch({ type: types.FETCH_MEDIA }); try { const media = await Kitsu.one(type, id).get({ include: `categories,mediaRelationships.destination${type === 'anime' ? ',episodes' : ',chapters'}`, }); // console.log(media); dispatch({ type: types.FETCH_MEDIA_SUCCESS, payload: { mediaId: id, media } }); } catch (e) { // console.log(e); dispatch({ type: types.FETCH_MEDIA_FAIL, payload: `Failed to load media ${e[0] && e[0].detail}`, }); } }; export const fetchMediaCastings = (mediaId, limit = 20, pageIndex = 0) => async ( dispatch, getState, ) => { dispatch({ type: types.FETCH_MEDIA_CASTINGS }); let data = []; if (pageIndex > 0) { data = [...getState().media.castings[mediaId]]; } try { const castings = await Kitsu.findAll('castings', { filter: { mediaId, isCharacter: true, }, sort: '-featured', include: 'character', }); // console.log(castings); data = [...data, ...castings]; dispatch({ type: types.FETCH_MEDIA_CASTINGS_SUCCESS, payload: { castings: data, mediaId } }); } catch (e) { // console.log(e); dispatch({ type: types.FETCH_MEDIA_CASTINGS_FAIL, payload: `Failed to load media ${e[0] && e[0].detail}`, }); } }; export const fetchMediaReactions = (mediaId, mediaType, limit = 20, pageIndex = 0) => async ( dispatch, getState, ) => { dispatch({ type: types.FETCH_MEDIA_REACTIONS }); let data = []; if (pageIndex > 0) { data = [...getState().media.reactions[mediaId]]; } try { const reactions = await Kitsu.findAll('mediaReactions', { filter: { [`${mediaType}Id`]: mediaId, }, include: 'user', sort: '-upVotesCount', }); data = [...data, ...reactions]; dispatch({ type: types.FETCH_MEDIA_REACTIONS_SUCCESS, payload: { mediaId, reactions: data, }, }); } catch (e) { // console.log(e); dispatch({ type: types.FETCH_MEDIA_REACTIONS_FAIL, payload: { error: 'Failed to load reactions', }, }); } };
// INSTANTIATION var APP = require("/core"); var args = arguments[0] || {}; var _type = 0; var _latitude = 0; var _longitude = 0; var _title = ""; var _pkorgGroups = 0; var _ogfAdmin = "N"; var _controller = this; var _counter=0,_headerbar,_maximum=0,_interval,_cinterval=0,_timeout,_touch = false; // These are for pulldown to refresh // FUNCTIONS /** * Decrease the counter to refresh **/ function decrease() { _interval && clearInterval( _interval ); _interval = setInterval(function(){ _counter = parseInt(_counter) - 5; if( _counter <= 0 ){ _counter = 0; if( _cinterval++ > 25 ){ _interval && clearInterval( _interval ); _cinterval = 0; } } _headerbar.refresh_advice.setHeight( _counter + '%' ); _headerbar.refresh_counter.setWidth( _counter + '%' ); /**** / Ti.API.info( 'decrease >>> _counter:' + _counter ); /****/ return true; }, 20); return true; } function getMessages(_event){ decrease(); if( APP.walkthru.on ){ loadFake(); } else if(APP.getToken({openLogin:true})){ APP.showActivityindicator(); for(var i = $.commentsContainer.children.length-1; i >= 0; i--){ $.commentsContainer.remove($.commentsContainer.children[ i ]); } _latitude = _event.lat; _longitude = _event.lon; _title = _event.faname; _pkorgGroups= _event.pkorgGroups; _ogfAdmin = _event.ogfAdmin; if(_pkorgGroups != 0){ var groupID = _pkorgGroups; }else{ var groupID = 0; } var dataTemp = { url : L("ws_getcomments"), type : 'POST', format : 'JSON', data : { atoken : APP.getToken({openLogin:false}), groupID : groupID, flat : _event.lat, flon : _event.lon, corder : "recent", pknmessage : (_event.pknmessage)?_event.pknmessage:0 } }; Ti.API.info("-->"+JSON.stringify(dataTemp)); APP.http.request(dataTemp,function(_result){ //Ti.API.info("-->"+JSON.stringify(_result)); if(_result._result == 1){ if(_result._data.errorcode == 0){ $.neighborTitle.text = _event.faname; if(_event.pknmessage){ $.commentsContainer.add(Ti.UI.createView({height:APP.fixSizeIos7(40)})); }else{ $.commentsContainer.add(Ti.UI.createView({height:APP.fixSizeIos7(60)})); } if(_event.pknmessage){ $.commentsContainer.add(Alloy.createController("MyNeighborhoods/CommentView",{_data:_result._data.data[0],pknmessage:(_event.pknmessage)?_event.pknmessage:0,isFirst:true}).getView()); if(_result._data.data[0].total > 0){ for(var i=0;i<_result._data.data.length;i++){ //Ti.API.info("-->"+JSON.stringify(_result._data.data[i])); if(_result._data.data[i].nmessage1.length > 0){ $.commentsContainer.add(Alloy.createController("MyNeighborhoods/CommentView",{_data:_result._data.data[i],pknmessage:(_event.pknmessage)?_event.pknmessage:0}).getView()); } } } }else{ for(var i=0;i<_result._data.data.length;i++){ //Ti.API.info("-->"+JSON.stringify(_result._data.data[i])); $.commentsContainer.add(Alloy.createController("MyNeighborhoods/CommentView",{_data:_result._data.data[i],pknmessage:(_event.pknmessage)?_event.pknmessage:0}).getView()); } } $.commentsContainer.add(Ti.UI.createView({height:Alloy.Globals.CONTENT_BOTTOM})); APP.hideActivityindicator(); }else{ //alert(_result._data.message); APP.hideActivityindicator(); alert("No messages were found."); } }else{ APP.hideActivityindicator(); alert("Internet connection error, please try again."); } }); }else{ APP.hideActivityindicator(); } } function updateView(_params){ $.neighborTitle.text = ""; _type = _params.type; _latitude = 0; _longitude = 0; _title = ""; _pkorgGroups= 0; _ogfAdmin = "N"; APP.headerbar.removeAllCustomViews() APP.headerbar.setLeftButton(0,false); APP.headerbar.setRightButton(0,false); APP.headerbar.setLeftButton(APP.OPENMENU,true); APP.headerbar.setRightButton(APP.OPENOPTIONS,true,{},1); if(!APP.getToken({openLogin : false})){ for(var i = $.commentsContainer.children.length-1; i >= 0; i--){ $.commentsContainer.remove($.commentsContainer.children[i]); } } if(_params.type == 0){ APP.headerbar.setTitle("My Neighborhoods"); APP.optionbar.changeView(2, function(){ APP.openWindow({ controller : 'Settings/EditAddress', controllerParams : { callback : function(){ APP.optionbar.updateMyAddresses(); } } }); } ); currentPosition(); }else if(_params.type == 1){ for(var i = $.commentsContainer.children.length-1; i >= 0; i--){ $.commentsContainer.remove($.commentsContainer.children[i]); } APP.showActivityindicator(); APP.headerbar.setTitle("My Groups"); APP.optionbar.changeView(3, function(){ APP.openWindow({ controller : 'MyNeighborhoods/SearchGroups', controllerParams : { callback : function(){ //send update } } }); } ); }else if(_params.type == 2){ for(var i = $.commentsContainer.children.length-1; i >= 0; i--){ $.commentsContainer.remove($.commentsContainer.children[i]); } APP.showActivityindicator(); APP.headerbar.setTitle("My Friends and Family"); APP.optionbar.changeView(4, function(){ APP.openWindow({ controller : 'MyNeighborhoods/SearchGroups', controllerParams : { callback : function(){ //send update } } }); } ); } } function currentPosition(){ APP.getCurrentLocation(function(_event){ if(_event.success){ _event.faname = "Current Location"; _event.pkorgGroups = _pkorgGroups; _event.ogfAdmin = _ogfAdmin; getMessages(_event); } }); } function addComment(){ if( APP.getToken({ openLogin : true }) && APP.popUpController == null ){ APP.popUp({ title : 'New Post', container : { width : 300, height : 340 }, controller : 'MyNeighborhoods/NewPost', controllerParams : { isAdmin : _ogfAdmin, isGroup : (_pkorgGroups != 0)?1:0, groupID : (_pkorgGroups != 0)?_pkorgGroups:"", lat : _latitude, lon : _longitude, pknmessage : (args.params && args.params.pknmessage)?args.params.pknmessage:0, refButton : (args.params && args.params.refButton)?args.params.refButton:0, controller : _controller, callback : function(){ return true; } } }); } } function loadFake(){ for(var i = $.commentsContainer.children.length-1; i >= 0; i--){ $.commentsContainer.remove($.commentsContainer.children[i]); } $.commentsContainer.add(Ti.UI.createView({ height : APP.fixSizeIos7( 60 ) })); for (var i = 0; i < args.fake.length; i++) { $.commentsContainer.add(Alloy.createController("MyNeighborhoods/CommentView", { _data : args.fake[ i ], pknmessage : 0 }).getView()); } return true; } function refresh(){ reloadMessages(); return true; } function reloadMessages(){ if(args.params && args.params.pknmessage){ getMessages({lat:0,lon:0,faname:"",pkorgGroups:_pkorgGroups,pknmessage:args.params.pknmessage}); }else{ getMessages({lat:_latitude,lon:_longitude,faname:_title,pkorgGroups:_pkorgGroups}); } } function removeComment(_view){ $.commentsContainer.remove(_view); } function initializeView(){ if(_type==1 || _type==2){ APP.openCloseOptions(); } updateView({type:_type}); } function clearView(){ for(var i = $.commentsContainer.children.length-1; i >= 0; i--){ $.commentsContainer.remove($.commentsContainer.children[i]); } } // CODE $.neighborTitleContainer.top = 40+APP.fixSizeIos7(); if( args.params && args.params.pknmessage ){ //alert(args.params.pknmessage); _headerbar = args.toolBar; args.toolBar.setTitle("Thread Detail"); $.neighborTitleContainer.visible = false; getMessages({lat:0,lon:0,faname:"",pkorgGroups:_pkorgGroups,pknmessage:args.params.pknmessage}); } else{ _headerbar = APP.headerbar; } /** LISTENERS **/ /** * Pulldown to refresh **/ $.commentsContainer.addEventListener('scroll', function( event ){ if( _touch && parseInt( event.y ) <= _maximum ){ if( _counter < 105 ){ _counter = _counter + ( OS_ANDROID ? 10 : 5 ); _headerbar.refresh_advice.setHeight( _counter + '%' ); _headerbar.refresh_counter.setWidth( _counter + '%' ); } else{ decrease(); refresh(); } } _maximum = parseInt( event.y ); if( _maximum > 0 ){ _maximum = 0 }; return true; }); if( OS_ANDROID ){ $.commentsContainer.addEventListener('touchstart', function(event) { Ti.API.warn('touchstart'); _touch = true; return true; }); $.commentsContainer.addEventListener('touchend', function(event) { Ti.API.warn('touchend'); _touch = false; decrease(); return true; }); } if( OS_IOS ){ $.commentsContainer.addEventListener('dragstart', function(event) { Ti.API.warn('dragstart'); _touch = true; return true; }); $.commentsContainer.addEventListener('dragend', function(event) { Ti.API.warn('dragend'); _touch = false; decrease(); return true; }); } // EXPORTS exports.updateView = updateView; exports.getMessages = getMessages; exports.reloadMessages = reloadMessages; exports.currentPosition = currentPosition; exports.removeComment = removeComment; exports.initializeView = initializeView; exports.clearView = clearView; /* APP.headerbar.setLeftButton(APP.OPENMENU,true); APP.headerbar.setRightButton(APP.OPENWINDOW,true,{controller:"MyNeighborhoods/MyNeighborhoods"}); */
var MainBuildingViewer = MainBuildingViewer || {}; var index = 0; var indexReal = 0; var arr = []; var arrReal = []; var newObj = {}; var newObjReal = {}; var currArr = []; var currArrReal = []; var first = true; var firstReal = true; var ceshistate = false; var modelTile=null; var myviewer = null; var tuceng =[]; var imageEntity1 = {}; var imageEntity2 = {}; var imageEntity3 = {}; var downuppoints = []; window.obj = {}; MainBuildingViewer.EbsObj = function (nodeId, fatherId, type, name, startDatePlan, endDatePlan, startDate, endDate, modelId, leaf) { this.nodeId = nodeId; this.fatherId = fatherId; this.type = type; this.name = name; this.startDatePlan = startDatePlan; this.endDatePlan = endDatePlan; this.startDate = startDate; this.endDate = endDate; this.modelId = modelId; this.leaf = leaf; this.children = []; } MainBuildingViewer.ModelObj = function (id, parentId, name, type, url, lon, lat, height, course, alpha, roll, scaleX, scaleY, scaleZ) { this.id = id; this.parentId = parentId; this.name = name; this.url = url; this.type = type; this.lon = lon; this.lat = lat; this.height = height; this.course = course; this.alpha = alpha; this.roll = roll; this.scaleX = scaleX; this.scaleY = scaleY; this.scaleZ = scaleZ; var modelMatrix = FreeDoTool.getModelMatrix(lon, lat, height, course, alpha, roll, scaleX, scaleY, scaleZ); this.primitive = MainBuildingViewer.viewer.scene.primitives.add(FreeDo.Model.fromGltf( { id: id, url: url, show: true, // default modelMatrix: modelMatrix, allowPicking: false, // not pickable debugShowBoundingVolume: false, // default debugWireframe: false })); } MainBuildingViewer.GroupObj = function (id, parentId, name, type) { this.id = id; this.parentId = parentId; this.name = name; this.type = type; this.children = []; } MainBuildingViewer.init = function (earthId,baseImageryProvider) { if(!ceshistate){ this.modelContainer = this.modelContainer || {};//未来保存加载的模型的容器,便于快速访问 this.ebsContainer = this.ebsContainer || {}; this.timeArray = this.timeArray || [];//保存了按时间排序的Ebs叶子节点 this.timeIndex = 0; this.showEbsContainer = this.showEbsContainer || {};//保存了当前时间点中显示出来的Ebs节点对应的模型 this.viewer = this.viewer || {}; this.viewer = new Freedo.Viewer(earthId,{ animation : false, baseLayerPicker : false, fullscreenButton : false, geocoder : false, homeButton : false, infoBox :false, sceneModePicker : false, selectionIndicator : false, timeline : false, navigationHelpButton : false, navigationInstructionsInitiallyVisible : false, selectedImageryProviderViewModel : false, scene3DOnly : true, clock : null, showRenderLoopErrors : false, automaticallyTrackDataSourceClocks:false, imageryProvider : baseImageryProvider || this.getTiandituGloble() }); this.viewer._cesiumWidget._creditContainer.style.display = "none"; this.viewer.imageryLayers.addImageryProvider(new FreeDo.WebMapTileServiceImageryProvider({ url : "http://{s}.tianditu.com/cia_w/wmts?service=WMTS&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet={TileMatrixSet}&TileMatrix={TileMatrix}&TileRow={TileRow}&Tilecol={TileCol}&style={style}&format=tiles", style:"default", tileMatrixSetID:"w", maximumLevel:17, subdomains : ["t7","t6","t5","t4","t3","t2","t1","t0"] })); // cx 添加 this.flag = true; this.selectModels = []; this.lastModelId = -2; this.cam = [116.00013, 38.998999999999999999999999, 80.75962432438108]; new Compass(this.viewer); modelTile = this.viewer.scene.primitives.add(new FreeDo.FreedoPModelset({ url: "./static/model/tanggu_new" })); //3D视角 //-2302845.900566225,4394819.795728763,3994766.603806111,0.2482012574227772,-0.781820133327709,0.001139172205375516 this.viewer.camera.setView({ destination :new FreeDo.Cartesian3(-2302923.868697135,4394881.466502352,3995119.1300424132), orientation: { heading : 3.4103115877496184, pitch : FreeDo.Math.toRadians( -90 ),//-1.5214432671817395, roll : 3.1249876427485663 } }); ceshistate =true; MainBuildingViewer.right(window.merightclick); var imageMaterial1 = new FreeDo.ImageMaterialProperty ({ image : "./static/page/designcoordination/mainbuilding/img/tuzhi/jiegoupingmiantu1.png", repeat : new FreeDo.Cartesian2(1.0, 1.0), transparent : true, }); var imageMaterial2 = new FreeDo.ImageMaterialProperty ({ image : "./static/page/designcoordination/mainbuilding/img/tuzhi/shebeipingmiantu1.png", repeat : new FreeDo.Cartesian2(1.0, 1.0), transparent : true, }); var imageMaterial3 = new FreeDo.ImageMaterialProperty ({ image : "./static/page/designcoordination/mainbuilding/img/tuzhi/zhantingpingmiantu1.png", repeat : new FreeDo.Cartesian2(1.0, 1.0), transparent : true, }); var lon1 = 117.65387630669996; var lat1 = 39.02828312119988; imageEntity1 = this.viewer.entities.add({ show:true, rectangle : { coordinates : FreeDo.Rectangle.fromDegrees(lon1, lat1, lon1+0.0020, lat1+0.0009), outline : true, outlineColor : FreeDo.Color.WHITE, outlineWidth : 4, height : 20, rotation : FreeDo.Math.toRadians(168), stRotation : FreeDo.Math.toRadians(168+180), material : imageMaterial1, }, }); var lon2 = 117.65387630669996; var lat2 = 39.02828312119988; imageEntity2 = this.viewer.entities.add({ show:true, rectangle : { coordinates : FreeDo.Rectangle.fromDegrees(lon2, lat2, lon2+0.0020, lat2+0.0009), outline : true, outlineColor : FreeDo.Color.WHITE, outlineWidth : 4, height : 20, rotation : FreeDo.Math.toRadians(168), stRotation : FreeDo.Math.toRadians(168+180), material : imageMaterial2, }, }); var lon3 = 117.65357630669989; var lat3 = 39.028213121199855; imageEntity3 = this.viewer.entities.add({ show:true, rectangle : { coordinates : FreeDo.Rectangle.fromDegrees(lon3, lat3, lon3+0.0025, lat3+0.0012), outline : true, outlineColor : FreeDo.Color.WHITE, outlineWidth : 4, height : 20, rotation : FreeDo.Math.toRadians(168), stRotation : FreeDo.Math.toRadians(168+180), material : imageMaterial3, }, }); var hospital1 = this.viewer.entities.add( { name : '医院1', position : FreeDo.Cartesian3.fromDegrees( 117.65406261508599,39.0299073545233,15 ), point : { //点 pixelSize : 5, color : FreeDo.Color.RED, outlineColor : FreeDo.Color.WHITE, outlineWidth : 2 }, label : { //文字标签 text : '天津医科大学总医院', font : '14pt monospace', style : FreeDo.LabelStyle.FILL_AND_OUTLINE, outlineWidth : 2, verticalOrigin : FreeDo.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置 pixelOffset : new FreeDo.Cartesian2( 0, -18 ) //偏移量 }, billboard : { //图标 image : "static/page/designcoordination/mainbuilding/img/tuceng/hispital.svg", width : 50, height : 50 }, } ); var hospital2 = this.viewer.entities.add( { name : '医院2', position : FreeDo.Cartesian3.fromDegrees( 117.6524968652495,39.02839132165448,15 ), point : { //点 pixelSize : 5, color : FreeDo.Color.RED, outlineColor : FreeDo.Color.WHITE, outlineWidth : 2 }, label : { //文字标签 text : '天津海河医院', font : '14pt monospace', style : FreeDo.LabelStyle.FILL_AND_OUTLINE, outlineWidth : 2, verticalOrigin : FreeDo.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置 pixelOffset : new FreeDo.Cartesian2( 0, -18 ) //偏移量 }, billboard : { //图标 image : "static/page/designcoordination/mainbuilding/img/tuceng/hispital.svg", width : 50, height : 50 }, } ); var police1 = this.viewer.entities.add( { name : '警察局1', position : FreeDo.Cartesian3.fromDegrees( 117.65575555770128, 39.03009236445744,15 ), point : { //点 pixelSize : 5, color : FreeDo.Color.RED, outlineColor : FreeDo.Color.WHITE, outlineWidth : 2 }, label : { //文字标签 text : '天津西车站派出所', font : '14pt monospace', style : FreeDo.LabelStyle.FILL_AND_OUTLINE, outlineWidth : 2, verticalOrigin : FreeDo.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置 pixelOffset : new FreeDo.Cartesian2( 0, -18 ) //偏移量 }, billboard : { //图标 image : "static/page/designcoordination/mainbuilding/img/tuceng/police.svg", width : 50, height : 50 }, } ); var police2 = this.viewer.entities.add( { name : '警察局2', position : FreeDo.Cartesian3.fromDegrees( 117.65346121985428, 39.02767696856126,15 ), point : { //点 pixelSize : 5, color : FreeDo.Color.RED, outlineColor : FreeDo.Color.WHITE, outlineWidth : 2 }, label : { //文字标签 text : '天津下瓦房派出所', font : '14pt monospace', style : FreeDo.LabelStyle.FILL_AND_OUTLINE, outlineWidth : 2, verticalOrigin : FreeDo.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置 pixelOffset : new FreeDo.Cartesian2( 0, -18 ) //偏移量 }, billboard : { //图标 image : "static/page/designcoordination/mainbuilding/img/tuceng/police.svg", width : 50, height : 50 }, } ); var fire1 = this.viewer.entities.add( { name : '消防局1', position : FreeDo.Cartesian3.fromDegrees(117.65530601763803, 39.02779377137312,15 ), point : { //点 pixelSize : 5, color : FreeDo.Color.RED, outlineColor : FreeDo.Color.WHITE, outlineWidth : 2 }, label : { //文字标签 text : '天津市公安消防局', font : '14pt monospace', style : FreeDo.LabelStyle.FILL_AND_OUTLINE, outlineWidth : 2, verticalOrigin : FreeDo.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置 pixelOffset : new FreeDo.Cartesian2( 0, -18 ) //偏移量 }, billboard : { //图标 image : "static/page/designcoordination/mainbuilding/img/tuceng/firecontrol.svg", width : 50, height : 50 }, } ); var fire2 = this.viewer.entities.add( { name : '消防局2', position : FreeDo.Cartesian3.fromDegrees(117.65808325960933, 39.030095945865426,15 ), point : { //点 pixelSize : 5, color : FreeDo.Color.RED, outlineColor : FreeDo.Color.WHITE, outlineWidth : 2 }, label : { //文字标签 text : '天津市保税区公安消防支队', font : '14pt monospace', style : FreeDo.LabelStyle.FILL_AND_OUTLINE, outlineWidth : 2, verticalOrigin : FreeDo.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置 pixelOffset : new FreeDo.Cartesian2( 0, -18 ) //偏移量 }, billboard : { //图标 image : "static/page/designcoordination/mainbuilding/img/tuceng/firecontrol.svg", width : 50, height : 50 }, } ); var road1 = this.viewer.entities.add( { name : '道路1', position : FreeDo.Cartesian3.fromDegrees(117.6601106774757, 39.0278397440452,1 ), point : { //点 pixelSize : 5, color : FreeDo.Color.RED, outlineColor : FreeDo.Color.WHITE, outlineWidth : 2 }, label : { //文字标签 text : '解放北路东方华尔街', font : '14pt monospace', style : FreeDo.LabelStyle.FILL_AND_OUTLINE, outlineWidth : 2, verticalOrigin : FreeDo.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置 pixelOffset : new FreeDo.Cartesian2( 0, -18 ) //偏移量 }, polygon : { hierarchy : FreeDo.Cartesian3.fromDegreesArray([ 117.63658156506864, 39.03320978417418, 117.63663657280595, 39.03337380796097, 117.6720856828493, 39.02536903471689, 117.6720403445534, 39.02521646994533 ]), //material : FreeDo.Color.BLANCHEDALMOND.withAlpha(0.8) material : new FreeDo.GridMaterialProperty({ color : FreeDo.Color.BLANCHEDALMOND, lineCount : new FreeDo.Cartesian2(450, 0), lineThickness : new FreeDo.Cartesian2(1, 1), lineOffset : new FreeDo.Cartesian2(1100.9, 1100.9) }), height : 1, outline : true, outlineColor : FreeDo.Color.BLANCHEDALMOND } /*billboard : { //图标 image : "static/page/designcoordination/mainbuilding/img/tuceng/road.svg", width : 50, height : 50 },*/ } ); var road2 = this.viewer.entities.add( { name : '道路2', position : FreeDo.Cartesian3.fromDegrees(117.65717660285547, 39.029622371574646,1 ), point : { //点 pixelSize : 5, color : FreeDo.Color.RED, outlineColor : FreeDo.Color.WHITE, outlineWidth : 2 }, label : { //文字标签 text : '估衣街', font : '14pt monospace', style : FreeDo.LabelStyle.FILL_AND_OUTLINE, outlineWidth : 2, verticalOrigin : FreeDo.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置 pixelOffset : new FreeDo.Cartesian2( 0, -18 ) //偏移量 }, polygon : { hierarchy : FreeDo.Cartesian3.fromDegreesArray([117.65974723500142,39.0371200384198, 117.66011027202251,39.0370471463995, 117.65481825563658,39.022534013171935, 117.6543818169068,39.02263156515081]), //material : FreeDo.Color.BLANCHEDALMOND.withAlpha(0.8) material : new FreeDo.GridMaterialProperty({ color : FreeDo.Color.BLANCHEDALMOND, lineCount : new FreeDo.Cartesian2(75, 0), lineThickness : new FreeDo.Cartesian2(1, 1), lineOffset : new FreeDo.Cartesian2(1100.9, 1100.9) }), height : 1, outline : true, outlineColor : FreeDo.Color.BLANCHEDALMOND } /*billboard : { //图标 image : "static/page/designcoordination/mainbuilding/img/tuceng/road.svg", width : 50, height : 50 },*/ } ); var village1 = this.viewer.entities.add( { name : '村庄1', position : FreeDo.Cartesian3.fromDegrees(117.67026677659791, 39.032003373898725,1 ), point : { //点 pixelSize : 5, color : FreeDo.Color.RED, outlineColor : FreeDo.Color.WHITE, outlineWidth : 2 }, label : { //文字标签 text : '西井峪村', font : '14pt monospace', style : FreeDo.LabelStyle.FILL_AND_OUTLINE, outlineWidth : 2, verticalOrigin : FreeDo.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置 pixelOffset : new FreeDo.Cartesian2( 0, -18 ) //偏移量 }, polygon : { hierarchy : FreeDo.Cartesian3.fromDegreesArray([117.66034681966288, 39.03696093054726, 117.67636015797348, 39.037001994608055, 117.683610430754, 39.0348536651218, 117.67875832785094, 39.023853904183326, 117.6572953921832, 39.02884930425908]), // material : FreeDo.Color.AQUAMARINE.withAlpha(0.8) material : new FreeDo.GridMaterialProperty({ color : FreeDo.Color.AQUAMARINE, lineCount : new FreeDo.Cartesian2(75, 0), lineThickness : new FreeDo.Cartesian2(1, 1), lineOffset : new FreeDo.Cartesian2(1100.9, 1100.9) }), height : 1, outline : true, outlineColor : FreeDo.Color.AQUAMARINE } /*billboard : { //图标 image : "static/page/designcoordination/mainbuilding/img/tuceng/village.svg", width : 50, height : 50 }, */ } ); var village2 = this.viewer.entities.add( { name : '村庄2', position : FreeDo.Cartesian3.fromDegrees(117.64511517639922, 39.037866096987834,1), point : { //点 pixelSize : 5, color : FreeDo.Color.RED, outlineColor : FreeDo.Color.WHITE, outlineWidth : 2 }, label : { //文字标签 text : '崔庄村', font : '14pt monospace', style : FreeDo.LabelStyle.FILL_AND_OUTLINE, outlineWidth : 2, verticalOrigin : FreeDo.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置 pixelOffset : new FreeDo.Cartesian2( 0, -18 ) //偏移量 }, polygon : { hierarchy : FreeDo.Cartesian3.fromDegreesArray([117.65993478164839, 39.03817311220826, 117.65850840699085, 39.04107067581256, 117.64055101073738, 39.04503444119745, 117.63106129257102, 39.04540355836992, 117.62705854783655, 39.04096019521865, 117.62673707271034, 39.03587500050924, 117.65659980243063, 39.02900451182315]), //material : FreeDo.Color.AQUAMARINE.withAlpha(0.8) material : new FreeDo.GridMaterialProperty({ color : FreeDo.Color.AQUAMARINE, lineCount : new FreeDo.Cartesian2(75, 0), lineThickness : new FreeDo.Cartesian2(1, 1), lineOffset : new FreeDo.Cartesian2(1100.9, 1100.9) }), height : 1, outline : true, outlineColor : FreeDo.Color.AQUAMARINE } /*billboard : { //图标 image : "static/page/designcoordination/mainbuilding/img/tuceng/village.svg", width : 50, height : 50 }*/ } ); var river1 = this.viewer.entities.add( { name : '水系1', position : FreeDo.Cartesian3.fromDegrees(117.65443147101222, 39.02762212630358,1 ), point : { //点 pixelSize : 5, color : FreeDo.Color.RED, outlineColor : FreeDo.Color.WHITE, outlineWidth : 2 }, label : { //文字标签 text : '北运河', font : '14pt monospace', style : FreeDo.LabelStyle.FILL_AND_OUTLINE, outlineWidth : 2, verticalOrigin : FreeDo.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置 pixelOffset : new FreeDo.Cartesian2( 0, -18 ) //偏移量 }, polygon : { hierarchy : FreeDo.Cartesian3.fromDegreesArray([ 117.653982677402, 39.028091097756, 117.65503969067898, 39.02781802125717, 117.6548674943786, 39.027403095513776, 117.65381412585376, 39.02761683748278]), //material : FreeDo.Color.DEEPSKYBLUE.withAlpha(0.8) material : new FreeDo.GridMaterialProperty({ color : FreeDo.Color.DEEPSKYBLUE, lineCount : new FreeDo.Cartesian2(25, 0), lineThickness : new FreeDo.Cartesian2(1, 1), lineOffset : new FreeDo.Cartesian2(1100.9, 1100.9) }), height : 1, outline : true, outlineColor : FreeDo.Color.DEEPSKYBLUE } /*billboard : { //图标 image : "static/page/designcoordination/mainbuilding/img/tuceng/river.svg", width : 50, height : 50 }, */ } ); var river2 = this.viewer.entities.add( { name : '水系2', position : FreeDo.Cartesian3.fromDegrees(117.65066204707234, 39.02692651335879,1 ), point : { //点 pixelSize : 5, color : FreeDo.Color.RED, outlineColor : FreeDo.Color.WHITE, outlineWidth : 2 }, label : { //文字标签 text : '海河', font : '14pt monospace', style : FreeDo.LabelStyle.FILL_AND_OUTLINE, outlineWidth : 2, verticalOrigin : FreeDo.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置 pixelOffset : new FreeDo.Cartesian2( 0, -18 ) //偏移量 }, polygon : { hierarchy : FreeDo.Cartesian3.fromDegreesArray([117.65066927457492, 39.02795259702767, 117.65147178875964, 39.02776766347203, 117.6505447513961, 39.025518921564206, 117.64983000414954, 39.025622293822636, 117.6496401353364, 39.02545125718353, 117.64809849977627, 39.02572863893886, 117.64835503758722, 39.02636789492214, 117.64976244099792, 39.025852710459255]), // material : FreeDo.Color.DEEPSKYBLUE.withAlpha(0.8) material : new FreeDo.GridMaterialProperty({ color : FreeDo.Color.DEEPSKYBLUE, lineCount : new FreeDo.Cartesian2(50, 0), lineThickness : new FreeDo.Cartesian2(1, 1), lineOffset : new FreeDo.Cartesian2(1100.9, 1100.9) }), height : 1, outline : true, outlineColor : FreeDo.Color.DEEPSKYBLUE } /* billboard : { //图标 image : "static/page/designcoordination/mainbuilding/img/tuceng/river.svg", width : 50, height : 50 },*/ } ); tuceng.push(hospital1); tuceng.push(hospital2); tuceng.push(police1); tuceng.push(police2); tuceng.push(fire1); tuceng.push(fire2); tuceng.push(road1); tuceng.push(road2); tuceng.push(river1); tuceng.push(river2); tuceng.push(village1); tuceng.push(village2); myviewer = this.viewer; modelTile.readyPromise.then(function() { moveModel(modelTile,-80,20,-23,15,0,0,1,1,1); }); $("#zongduanmian").click(function() { lon+=0.001; imageEntity.rectangle.coordinates = FreeDo.Rectangle.fromDegrees(lon, lat, lon+0.0078, lat+0.00333); }); $("#zhixianceliang").click(function() { lat+=0.001; imageEntity.rectangle.coordinates = FreeDo.Rectangle.fromDegrees(lon, lat, lon+0.0078, lat+0.00333); }) } } var shuxingshuju = [ {id:"4",componentId:"f9d881e3-914b-11e7-350c-41f03c953867",position:{x: -2194085.358357283, y: 4378020.501802686, z: 4073309.593950244,h:5.35265519096344,p:-0.957659926884252,r:6.278567474111711}}, {id:"3",componentId:"ed72d504-914b-11e7-350c-41f03c953867",position:{x: -2195060.2573393, y: 4378576.951533875, z: 4073663.174259837,h:5.352722440967762,p:-0.9575901024379618,r:6.2785770863994745}}, {id:"7",componentId:"ed779002-914b-11e7-350c-41f03c953867",position:{x: -2193793.6199775375, y: 4377914.767535423, z: 4073137.8297135117,h:5.630378750477897,p:-0.5528137024056186,r:6.280823088992896}}, {id:"6",componentId:"edc8bd46-914b-11e7-350c-41f03c953867",position:{x: -2193708.6772762756, y: 4377904.534220799, z: 4073202.5056291255,h:1.994404289117547,p:-0.6097462455837199,r:0.0036707497876156125}}, {id:"8",componentId:"f4af8dd0-914b-11e7-350c-41f03c953867",position:{x: -2193811.879911349, y: 4377879.3756989, z: 4073278.261950106,h:2.484639075410328,p:-0.7742439563807868,r:0.0028153183111001567}}, {id:"9",componentId:"f71913d4-914b-11e7-350c-41f03c953867",position:{x: -2193752.736986991, y: 4377917.714569312, z: 4073448.8325745175,h:3.176375399572854,p:-0.8374943559959638,r:6.283014252876068}}, ]; MainBuildingViewer.changechoserow = function(row){ if(ceshistate&&modelTile){ for(i in shuxingshuju){ if(shuxingshuju[i].id==row.id){ var componentId = shuxingshuju[i].componentId; var redStyle = new FreeDo.FreedoPModelStyle({color: {conditions: [["${component} === \'" + componentId + "\'", "color('red')"],["true", "color('white')"]]}}); modelTile.style=redStyle; this.viewer.camera.flyTo({ destination : new FreeDo.Cartesian3(shuxingshuju[i].position.x, shuxingshuju[i].position.y, shuxingshuju[i].position.z), orientation: { heading : shuxingshuju[i].position.h, pitch : shuxingshuju[i].position.p, roll : shuxingshuju[i].position.r } }); } } } } var catchModelTile =null; MainBuildingViewer.right = function (callback) { var selectComponentEventType = FreeDo.ScreenSpaceEventType.RIGHT_CLICK; //var selectComponentEventType = FreeDo.ScreenSpaceEventType.LEFT_DOUBLE_CLICK; var that = this; this.screenSpaceEventHandler = new FreeDo.ScreenSpaceEventHandler(this.viewer.canvas); this.screenSpaceEventHandler.setInputAction(function (movement) { var picked = myviewer.scene.pick(movement.position); if (FreeDo.defined(picked) && picked instanceof FreeDo.FreedoPModelFeature) { var id = picked.getProperty('component'); if (FreeDo.defined(id)) { var menu = document.getElementById("menu"); //var event = event || window.event; menu.style.display = "block"; menu.style.left = movement.position.x+140+"px"; menu.style.top = movement.position.y+55+"px"; //catchModelTile.push(picked);1 catchModelTile=id; } } }, selectComponentEventType); } MainBuildingViewer.showHideModelsById =function(uid){ var showhide = new FreeDo.FreedoPModelStyle({ show: { conditions:uid } }); modelTile.style = showhide; } //左键点击事件 MainBuildingViewer.initLeftClick = function(viewer) { var screenSpaceEventHandler = new FreeDo.ScreenSpaceEventHandler(viewer.canvas); screenSpaceEventHandler.setInputAction(function(movement){ var picked = viewer.scene.pick(movement.position); var pick= new FreeDo.Cartesian2(movement.position.x,movement.position.y); var cartesian = viewer.camera.pickEllipsoid(pick, viewer.scene.globe.ellipsoid); var cartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian); var point=[ cartographic.longitude / Math.PI * 180, cartographic.latitude / Math.PI * 180]; console.log(point); var x = viewer.camera.position.x var y = viewer.camera.position.y var z = viewer.camera.position.z var heading = viewer.camera.heading; var pitch = viewer.camera.pitch; var roll = viewer.camera.roll; //console.log(x+","+y+","+z+","+heading+","+pitch+","+roll); }, FreeDo.ScreenSpaceEventType.LEFT_CLICK); } //右键点击事件 MainBuildingViewer.initRightClick = function(viewer) { var screenSpaceEventHandler = new FreeDo.ScreenSpaceEventHandler(viewer.canvas); screenSpaceEventHandler.setInputAction(function(movement){ $("#menu").hide(); var picked = viewer.scene.pick(movement.position); if(picked){ if(picked instanceof FreeDo.FreedoPModelFeature){ console.log(picked); $("#menu").css({ left:movement.position.x+130, top:movement.position.y+110 }).show(); }else{ $("#menu").hide(); } }else{ $("#menu").hide(); } }, FreeDo.ScreenSpaceEventType.RIGHT_CLICK); } /** * [initModels初始化场景中的模型] * @return {[type]} [description] */ MainBuildingViewer.initModels = function () { $.ajax({ url: "http://182.92.7.32:9510/ProjectManage/pm/selectAll", dataType: "JSON", success: function (content) { var node = null; var modelNode = null; var modelParentNode = null;//模型缓存中的父节点 var container = MainBuildingViewer.modelContainer; for (var i = 0; i < content.length; i++) { node = content[i]; modelParentNode = container[node.parentId]; if (modelParentNode == undefined) { modelParentNode = container[node.parentId] = { children: [] }; } //非叶子节点 if (node.leaf == 0) { modelNode = new MainBuildingViewer.GroupObj(node.id, node.parentId, node.text, node.type); if (container[node.id] != undefined) { modelNode.children = container[node.id].children; } } else { var parameter = JSON.parse(node.attributes.parameter); modelNode = new MainBuildingViewer.ModelObj(node.id, node.parentId, node.text, node.type, "http://182.92.7.32:9510/ProjectManage/models/" + parameter.filePath, parameter.lon, parameter.lat, parameter.height, parameter.course, parameter.alpha, parameter.roll, parameter.scaleX, parameter.scaleY, parameter.scaleZ); } container[node.id] = modelNode; modelParentNode.children.push(modelNode.id); } console.log(container); } }); } MainBuildingViewer.getTiandituGloble =function() { var tg = new Freedo.WebMapTileServiceImageryProvider({ url : "http://{s}.tianditu.com/img_c/wmts?service=WMTS&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet={TileMatrixSet}&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style={style}&format=tiles", style:"default", tileMatrixSetID:"c", tilingScheme:new Freedo.GeographicTilingScheme(), tileMatrixLabels:["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18"], maximumLevel:17, subdomains : ["t0","t1","t2","t3","t4","t5","t6","t7"] }); return tg; } MainBuildingViewer.manyou=function(arr){ // 三维基础环境。 m_Viewer = null; // 上一帧画面对应的系统时间(毫秒)。 m_LastTime = 0; // 总的运行时间。 m_Time = 0; // 场景管理器。 // m_Scene = new FDPScene; // 脚本。(匀速持续播放)。测试 m_Script = new FDPScript; // 鼠标事件响应函数队列。 m_MouseMoveEventList = new Array(); // 创建三维环境。 m_Viewer = this.viewer; // 屏蔽左下角图标。 m_Viewer._cesiumWidget._creditContainer.style.display="none"; if ( m_Viewer == null ) return false; // 初始化项目资源。 // 注册渲染循环响应函数。 // 帧循环事件。 OnPreRender = function() { var myDate = new Date(); var time = myDate.getTime(); var dt = time - m_LastTime; m_LastTime = time; m_Time = m_Time+dt; // 脚本运行。 m_Script.Run( dt ); } m_Viewer.scene.preRender.addEventListener( OnPreRender ); //? // 注册鼠标、键盘事件响应。 // 鼠标移动事件。测试。 OnMouseMove = function( movement ) { // 按队列顺序执行时间相应函数。 // 获取鼠标移动 距离 dx, dy // 循环调用鼠标移动响应函数。 for ( var i = 0; i < m_MouseMoveEventList.length; i++ ) { if ( m_MouseMoveEventList[i](dx, dy) == true ) break; // 返回 true 不在继续后续响应。 } } // 鼠标移动事件。测试。 OnMouseMove = function( movement ) { // 按队列顺序执行时间相应函数。 // 获取鼠标移动 距离 dx, dy // 循环调用鼠标移动响应函数。 for ( var i = 0; i < m_MouseMoveEventList.length; i++ ) { if ( m_MouseMoveEventList[i](dx, dy) == true ) break; // 返回 true 不在继续后续响应。 } } var handler = new FreeDo.ScreenSpaceEventHandler(m_Viewer.scene.canvas); handler.setInputAction( OnMouseMove, FreeDo.ScreenSpaceEventType.MOUSE_MOVE ); //注册鼠标移动事件。 // 注册其它鼠标事件。 // 测试脚本事件。 var CameraRoute = new FDPAction_Camera_2( m_Viewer.camera, arr); // 事件加入到脚本。 m_Script.AddAction( CameraRoute ); m_Script.Start(); var myDate = new Date(); m_LastTime = myDate.getTime(); m_Time = 0; AddMouseMoveEventFuc = function( eventFunc, Type ) { // 添加鼠标移动响应函数接口。接口形式为 function( dx, dy ), dx, dy 分别对应该次鼠标移动事件中鼠标移动的x轴和y轴方向上的距离。 if ( Type == 0 ) m_MouseMoveEventList.unshift( eventFunc ); else m_MouseMoveEventList( eventFunc ); } RemoveMouseMoveEventFuc = function( eventFunc ) { } return m_Script; } MainBuildingViewer.pause = function(script){ script.Pause(); } MainBuildingViewer.resume = function(script){ script.Resume(); }
import { connect } from 'react-redux'; import SignatureDialog from './SignatureDialog'; import {postOption, fetchJson, showError, validValue} from '../../../common/common'; import {Action} from '../../../action-reducer/action'; import {getPathValue} from '../../../action-reducer/helper'; import {updateTable} from './OrderPageContainer'; import {toFormValue} from '../../../common/check'; const URL_NEW = '/api/platform/mouldMake/new'; const URL_UPDATE = '/api/platform/mouldMake/edit'; const PARENT_STATE_PATH = ['platform', 'mouldMake']; const STATE_PATH = ['platform', 'mouldMake', 'signatureDialog']; const action = new Action(STATE_PATH); const actionParent = new Action(PARENT_STATE_PATH); const CLOSE_ACTION = action.assignParent({signatureDialog: undefined}); const buildSignatureState = (config, data, key, isEdit, editIndex) => { let newConfig = config; return { key, isEdit, editIndex, config: config.config, ...newConfig, controls: newConfig.signatureControls, title: isEdit ? config.edit : config.add, value: data, size: 'middle' }; }; const createContainer = (statePath, afterEditActionCreator) => { const action = new Action(statePath); const getSelfState = (rootState) => { return getPathValue(rootState, statePath); }; const changeActionCreator = (key, value) => async (dispatch,getState) => { dispatch(action.assign({[key]: value}, 'value')); }; const formSearchActionCreator = () => { }; const exitValidActionCreator = () => { return action.assign({valid: false}); }; const okActionCreator = () => async (dispatch, getState) => { const {isEdit, editIndex, value, controls, key} = getSelfState(getState()); if (!validValue(controls, value)) { dispatch(action.assign({valid: true})); return; } const postData = { id: value.id? value.id: '', modelType: value.modelType? value.modelType: key, excelReportGroup: value.excelReportGroup, modelName: value.modelName, content: value.content }; let option, data; if(isEdit){ data = await fetchJson(URL_UPDATE, postOption(toFormValue(postData), 'put')); }else{ data = await fetchJson(URL_NEW, postOption(toFormValue(postData))); } if (data.returnCode !== 0) { showError(data.returnMsg); return; } const result = data.result; afterEditActionCreator(result)(dispatch, getState); }; const cancelActionCreator = () => (dispatch, getState) => { afterEditActionCreator()(dispatch, getState); }; const actionCreators = { onChange: changeActionCreator, onSearch: formSearchActionCreator, onExitValid: exitValidActionCreator, onOk: okActionCreator, onCancel: cancelActionCreator }; const mapStateToProps = (state) => { return getSelfState(state); }; return connect(mapStateToProps, actionCreators)(SignatureDialog); }; const afterEditActionCreator = (result) => (dispatch, getState) => { dispatch(CLOSE_ACTION); result && updateTable(dispatch, getState); }; const Container = createContainer(STATE_PATH, afterEditActionCreator); export default Container; export {buildSignatureState, createContainer};
'use strict'; let categories = ["Geography", "Gastronomy", "Sports", "Science"]; let random /** * This class defines the game */ function Trivial () { this.questionList = []; this.allowedQuestionList = []; this.currentQuestion = 0; this.currentPlayer = 0; this.playerManager = null; this.answeredQuestions = []; /** * IF true, the random of the questions is random * if false, it is serial * @type {Boolean} */ this.random = true; /** * IF the questions can be repeated or not * To stop it, we will finish when the user has 1 score at least in every category * * @type {Boolean} */ this.repeatQuestions = false; this.selectedCategories = []; /** * Defines they playermanager that is going to be used * @param {[type]} playermanager [description] */ this.setPlayerManager = function (playermanager) { this.playerManager = playermanager; }; /** * Players that will play in this trivial game * We will save them in the playermanager object * @return {[type]} [description] */ this.setPlayers = function (){ let sign = prompt("Insert new player name"); let newPlayer = new Player (sign); this.playerManager.addPlayer (newPlayer); let confirmMorePlayers = confirm ("Add more players?"); if (confirmMorePlayers) { this.setPlayers(); } }; /** * Add questions into the question list of the trivial * @param {[question]} question [question] */ this.addQuestion = function (question) { this.questionList.push(question); }; //Ask que user for the question this.askQuestion = function (questionId){ let choosedQuestion = this.allowedQuestionList[questionId]; if (choosedQuestion.choices === true){ return confirm('Question for: ' + this.playerManager.playerList[this.currentPlayer].Player.name + " \n " + choosedQuestion.title + "? " + " \n "); }else{ let sign = prompt('Question for: ' + this.playerManager.playerList[this.currentPlayer].Player.name + " \n " + choosedQuestion.title + "? " + " \n " + choosedQuestion.choices[0] + " \n " + choosedQuestion.choices[1]); return sign.toLowerCase() === choosedQuestion.correctAns.toLowerCase(); } }; //Define if game is random or serial this.askRandom = function (random) { this.random = confirm("You want random questions for users?"); }; //Define if we want to repeat questions this.askRepeatedQuestions = function (repeat) { this.repeatQuestions = confirm("You want repeated questions for users?"); }; /** * Define the categories to be shown * @type {[array]} */ this.defineCategoriesGame = function (){ for (let i = 0; i < categories.length; i++) { var categoryAccepted = confirm("Do you want to play with category: " + categories[i] + "?"); if (categoryAccepted) { this.selectedCategories.push(categories[i]); } } }; /** * This is the main function where we define the game and its behaviour * @return {[type]} [description] */ this.play = function () { //the first time, we will choose randomly the player var maxPlayers = this.playerManager.playerId - 1; this.currentPlayer = Math.floor(Math.random() * maxPlayers) + 0; //Create new pool of questions with allowed categories for (let i = 0; i < this.questionList.length; i++) { if (this.selectedCategories.indexOf(this.questionList[i].category) >= 0){ this.allowedQuestionList.push(this.questionList[i]); } } //Check if we want to show the questions randomly or serial // if (this.random === true){ // // }else{ while (this.currentQuestion < this.allowedQuestionList.length){ let questionResult = this.askQuestion(this.currentQuestion); if (questionResult) { this.playerManager.playerList[this.currentPlayer][this.allowedQuestionList[this.currentQuestion].category]++; }else{ if (this.currentPlayer === maxPlayers) { this.currentPlayer = 0; }else{ this.currentPlayer++; } } this.currentQuestion++; } // } // Return results by player for (let key in this.playerManager.playerList) { let categoryString = ''; for (let i = 0; i < this.selectedCategories.length; i++) { categoryString += '\n' + this.selectedCategories[i] + ': ' + this.playerManager.playerList[key][this.selectedCategories[i]] + " points"; } confirm ('\nPlayer: ' + this.playerManager.playerList[key].Player.name + categoryString); } return; }; } //Create class question function Question (title, category, choices, correctAns) { if (categories.indexOf(category) >= 0){ this.title = title; this.category = category; this.choices = choices; this.correctAns = correctAns; } else { console.log("Category doesn't exist for " + title); } } /** * Class that defines the player name, could define more things * @param {[type]} name [description] */ function Player (name) { this.name = name; } /** * This class controls the players for a trivial game * and the scores of them for every category. * The category is taken from the array categories * and we save the score for every category and every player */ function PlayerManager () { this.playerList = {}; this.playerId = 0; //Add a player into playerList this.addPlayer = function (player) { this.playerList[this.playerId] = {}; this.playerList[this.playerId]['Player'] = player; //We need to create 1 score for every category //We are going to use an array and save it in the setPlayerManager //with same elements than in the initial array for (let i = 0; i < categories.length; i++){ this.playerList[this.playerId][categories[i]] = 0; } this.playerId++; } } //Body code let trivial = new Trivial(); trivial.setPlayerManager(new PlayerManager ()); trivial.setPlayers(); trivial.askRandom(true); trivial.askRepeatedQuestions(false); let question1 = new Question('Capital of France', 'Geography', ['A - Paris', 'B - Rome'], 'A'); let question2 = new Question('Capital of Spain', 'Geography', ['A - Madrid', 'B - Barcelona'], 'A'); let question3 = new Question('Capital of Italy', 'Geography', ['A - Milan', 'B - Rome'], 'B'); let question4 = new Question('What\'s a food name', 'Gastronomy', ['A - Hummus', 'B - Pen'], 'A'); let question5 = new Question('Where was created the pizza', 'Gastronomy', ['A - USA', 'B - Italy'], 'A'); let question6 = new Question('Is a tomato a fruit?', 'Gastronomy', true, true); let question7 = new Question('Who\'s the best player in the worlds', 'Sports', ['A - C.Ronaldo', 'B - Messi'], 'B'); let question8 = new Question('Where is playing Dybala', 'Sports', ['A - Juventus', 'B - Paris St. Germain'], 'A'); let question9 = new Question('Max. number of players of a basketball team?', 'Sports', ['A - 11', 'B - 12'], 'B'); let question10 = new Question('Can a man breath without nose?', 'Science', true, true); let question11 = new Question('Can an atom kill a human being?', 'Science', true, false); let question12 = new Question('How many subatomic particles exists?', 'Science', ['A - 3', 'B - 4'], 'A'); trivial.addQuestion(question1); trivial.addQuestion(question2); trivial.addQuestion(question3); trivial.addQuestion(question4); trivial.addQuestion(question5); trivial.addQuestion(question6); trivial.addQuestion(question7); trivial.addQuestion(question8); trivial.addQuestion(question9); trivial.defineCategoriesGame(); //console.log(trivial); //console.log(playerManager); trivial.play(); //console.log(trivial.questionList);
import React, {PureComponent} from 'react'; import {connect} from 'dva'; import Bind from 'lodash-decorators/bind'; import DataTable from '../../components/DataTable/DataTable'; import PageHeaderLayout from '../../layouts/PageHeaderLayout'; import { Card, Form, Badge, Modal, } from 'antd'; import Filter from './FilterDepartment'; import styles from './List.less'; const STATE_KEY = 'management_department'; const FETCH_TYPE = `${STATE_KEY}/fetch`; const confirm = Modal.confirm; const getValue = obj => Object.keys(obj).map(key => obj[key]).join(','); @connect(state => ({ franchiser: state[STATE_KEY], loading: state.loading, })) @Form.create() export default class ManagementDepartment extends PureComponent { state = { selectedRows: [], }; componentDidMount() { const {dispatch, location} = this.props; const payload = location.query; console.log(location) dispatch({ type: FETCH_TYPE, payload }); } handleStandardTableChange = (pagination, filtersArg, sorter) => { const {dispatch} = this.props; const {formValues} = this.state; const filters = Object.keys(filtersArg).reduce((obj, key) => { const newObj = {...obj}; newObj[key] = getValue(filtersArg[key]); return newObj; }, {}); const params = { currentPage: pagination.current, pageSize: pagination.pageSize, ...formValues, ...filters, }; if (sorter.field) { params.sorter = `${sorter.field}_${sorter.order}`; } dispatch({ type: FETCH_TYPE, payload: params, }); } handleSearch = (fieldsValue) => { console.log(fieldsValue); } @Bind() handleRemove(id) { const {dispatch} = this.props; const {selectedRows} = this.state; const doDel = () => { console.log('确认删除'+id); } confirm({ title: '你是否确定删除本条记录?', onOk () { doDel(); }, }) } @Bind() handleRecover(id) { const {dispatch} = this.props; const {selectedRows} = this.state; const doDel = () => { console.log('确认恢复'+id); } confirm({ title: '你是否确定恢复本条记录?', onOk () { doDel(); }, }) } render() { const {location, loading, franchiser} = this.props; const {list, pagination} = franchiser; const {selectedRows} = this.state; const status = ['否', '是']; const self = this; const statusMap = ['0', '1']; const columns = [ { title: 'ID', dataIndex: 'no', }, { title: '部门名称', dataIndex: 'cityId', }, { title: '部门ID', dataIndex: 'bank', }, { title: '父部门名称', dataIndex: 'num', }, { title: '父部门ID', dataIndex: 'tel', }, { title: '有效', dataIndex: 'status', filters: [ { text: status[0], value: 0, }, { text: status[1], value: 1, }, ], render(val) { return <Badge status={statusMap[val]} text={status[val]}/>; }, }, { title: '操作', render: function(item){ if(item.status == 1){ return( <div> <a onClick={() => self.handleRemove(item.no)}>删除</a> </div> ); }else{ return( <div> <a onClick={() => self.handleRecover(item.no)}>恢复</a> </div> ); } } }, ]; const tableProps = { rowKey: 'no', columns, list, selectedRows, loading: loading.effects[FETCH_TYPE], pagination, location, onSelectRow: (rows) => { this.setState({ selectedRows: rows, }); }, onChange: this.handleStandardTableChange, } return ( <PageHeaderLayout> <Card bordered={false}> <div className={styles.tableList}> <Filter {...this.props} handleSearch={this.handleSearch} /> <DataTable {...tableProps} /> </div> </Card> </PageHeaderLayout> ) } }
import React from 'react'; import IconMenu from 'material-ui/IconMenu'; import IconButton from 'material-ui/IconButton'; import FontIcon from 'material-ui/FontIcon'; import NavigationExpandMoreIcon from 'material-ui/svg-icons/navigation/expand-more'; import MenuItem from 'material-ui/MenuItem'; import DropDownMenu from 'material-ui/DropDownMenu'; import RaisedButton from 'material-ui/RaisedButton'; import {Toolbar, ToolbarGroup, ToolbarSeparator, ToolbarTitle} from 'material-ui/Toolbar'; import Paper from 'material-ui/Paper'; export default class ThingDes extends React.Component { constructor(props) { super(props); this.state = { value: 3, }; } handleChange = (event, index, value) => this.setState({value}); render() { const style = { height: '800', width: '50%', margin: 20, display: 'inline-block', }; return ( <Paper style={style} zDepth={2}> <Toolbar> <ToolbarGroup firstChild={true}> <DropDownMenu value={this.state.value} onChange={this.handleChange}> <MenuItem value={1} primaryText="参与讨论" /> <MenuItem value={2} primaryText="所有文件" /> <MenuItem value={3} primaryText="事件始末" /> </DropDownMenu> </ToolbarGroup> <ToolbarGroup> <ToolbarTitle text="事件详情" /> <FontIcon className="muidocs-icon-custom-sort" /> <ToolbarSeparator /> <RaisedButton label="创建从属事件" primary={true} /> <IconMenu iconButtonElement={ <IconButton touch={true}> <NavigationExpandMoreIcon /> </IconButton> } > <MenuItem primaryText="分享" /> </IconMenu> </ToolbarGroup> </Toolbar> </Paper> ); } }
import React, {useState, useRef, useCallback} from 'react'; import {Editor, EditorState, ContentState, RichUtils, convertToRaw, convertFromRaw} from 'draft-js'; import PropTypes from 'prop-types'; import {FontAwesomeIcon} from "@fortawesome/react-fontawesome"; import {faBold, faItalic, faListOl, faListUl, faQuoteLeft, faUnderline} from "@fortawesome/free-solid-svg-icons"; import styles from './styles/DraftEditor.module.scss'; import classNames from 'classnames'; import {draftToMarkdown, markdownToDraft} from "markdown-draft-js"; function StyleButton(props) { const styleButtonClassName = classNames({ [styles.styleButton]: true, [styles.styleButtonActive]: props.active, }); function handleToggle(e) { e.preventDefault(); props.handleToggle(props.type) } return <button className={styleButtonClassName} onMouseDown={handleToggle}><FontAwesomeIcon icon={props.icon}/> </button> } StyleButton.propTypes = { handleToggle: PropTypes.func.isRequired, type: PropTypes.string.isRequired, icon: PropTypes.func.isRequired, active: PropTypes.bool.isRequired, }; function BlockStyleButton(props) { const selection = props.editorState.getSelection(); const blockType = props.editorState .getCurrentContent() .getBlockForKey(selection.getStartKey()) .getType(); return <StyleButton {...props} active={props.type === blockType}/> } function InlineStyleButton(props) { const currentStyle = props.editorState.getCurrentInlineStyle(); return <StyleButton {...props} active={currentStyle.has(props.type)}/> } const inlineStyleTypes = [['BOLD', faBold], ['ITALIC', faItalic], ['UNDERLINE', faUnderline]]; const blockTypes = [['unordered-list-item', faListUl], ['ordered-list-item', faListOl], ['blockquote', faQuoteLeft]]; export default function DraftEditor(props) { const editorRef = useRef(null); const markdown = useRef(markdownToDraft(props.value)); markdown.current.blocks = markdown.current.blocks.map((b, i) => ({...b, key: `foo-${i}`})); const [editorState, setEditorState] = useState(EditorState.createWithContent(convertFromRaw(markdown.current))); function setFocus(e) { if (editorRef.current) { editorRef.current.focus(); } } function toggleBlockType(blockType) { handleChange(RichUtils.toggleBlockType(editorState, blockType)) } function toggleInlineStyle(style) { handleChange(RichUtils.toggleInlineStyle(editorState, style)); } function handleChange(state) { setEditorState(state); props.handleChange(draftToMarkdown(convertToRaw(state.getCurrentContent()))); } return <div> <div className={styles.controlBar}> {inlineStyleTypes.map(t => <InlineStyleButton editorState={editorState} handleToggle={toggleInlineStyle} type={t[0]} icon={t[1]}/>)} {blockTypes.map(t => <BlockStyleButton editorState={editorState} handleToggle={toggleBlockType} type={t[0]} icon={t[1]}/>)} </div> <div className={styles.editor} onClick={setFocus}> <Editor editorKey={"foobar"} editorState={editorState} onChange={handleChange} ref={editorRef}/> </div> </div> } DraftEditor.propTypes = { value: PropTypes.string.isRequired, };
/** * Created by ssanchez on 17/12/15. */ var redis = require('redis') .createClient(process.env.REDIS_URL); redis.on('error', function (err) { if (err) throw err; }); exports.init = function () { return redis; };
// VERSION 1.0.0 Services.scriptloader.loadSubScript("resource://thefoxonlybetter/modules/utils/content.js", this); this.theFoxOnlyBetter = this.__contentEnvironment; delete this.__contentEnvironment; this.theFoxOnlyBetter.objName = 'theFoxOnlyBetter'; this.theFoxOnlyBetter.objPathString = 'thefoxonlybetter'; this.theFoxOnlyBetter.init();
function numberBeer(){ userNumber = prompt ("Can you put a number? Please"); for(let i = userNumber; i <= 99; i++) { console.log(`${userNumber} bottles of beer`); console.log(`${userNumber++} bottles of beer on the wall`); for(let j = 1; j < 2; j++){ console.log(`Take ${j+1} down, pass them around`);} } } numberBeer();
document.getElementById("t1").innerHTML = greeting(); function greeting(name = "Anonymous") { return "Hello " + name; }
import React from 'react'; import { Container } from '@material-ui/core'; export default () => ( <Container maxWidth="lg"> <h1>Page not found</h1> </Container> )
// @flow import _ from "lodash/fp" import * as Types from "../types" import { mergeVersions } from "./merge" export function convertDataToVersion( browser: Types.SupportStatement ): Types.Versions { let normalize = browser if (Array.isArray(normalize)) { normalize = normalize.filter( (b) => !(b.partial_implementation || b.prefix) )[0] } if ( normalize == null || normalize.partial_implementation || normalize.prefix ) { return { support: normalize?.partial_implementation || normalize?.prefix ? "PARTIAL SUPPORT" : "UNKNOWN", start: null, end: null } } let support = "UNKNOWN" let start = null if (normalize.version_added == null || normalize.version_added === false) { support = normalize.version_added === false ? "NONE" : "UNKNOWN" start = null } else if ( normalize.version_added === true || normalize.version_added === "" ) { support = "UNKNOWN" start = "0" } else if (typeof normalize.version_added === "string") { support = "SUPPORTED" start = normalize.version_added } let end = null if ( normalize.version_removed == null || normalize.version_removed === false || normalize.version_removed === "" ) { end = null } else if (normalize.version_removed === true) { end = "0" } else if (typeof normalize.version_removed === "string") { end = normalize.version_removed } return { support, start, end } } export function determineVersion( supportStatements: Array<{ [browser: string]: Types.SupportStatement }>, browser: string ): Types.Versions { const sanitized = _.filter(Boolean, supportStatements) return _.reduce( (acc, ss) => { return mergeVersions(acc, convertDataToVersion(ss[browser])) }, { support: "UNKNOWN", start: null, end: null }, sanitized ) }
self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "bf8d5ae94b76611dba0518bb40b4b282", "url": "config.xml" }, { "revision": "584960604637f4c09d10", "url": "css/app.20908a14.css" }, { "revision": "46afa5860446d93e4167c7c48a4afb85", "url": "index.html" }, { "revision": "8bd9ec1d5d8f69911fd7", "url": "js/about.8ef7095e.js" }, { "revision": "584960604637f4c09d10", "url": "js/app.7d449ebc.js" }, { "revision": "e54845ab283cf892741c", "url": "js/chunk-vendors.98f3cc2e.js" }, { "revision": "f492c5f7389add5560a0240ed0b464f0", "url": "manifest.json" }, { "revision": "b6216d61c03e6ce0c9aea6ca7808f7ca", "url": "robots.txt" } ]);
var Main = { data () { return { spanLeft: 4, spanRight: 20, classA:'large-userName', menu:'收起菜单栏' } }, computed: { iconSize () { return this.spanLeft === 4 ? 20 :30; }, faceSize(){ return this.spanLeft === 4 ? 'large' :'small'; } }, methods: { toggleClick () { if (this.spanLeft === 4) { this.spanLeft = 2; this.spanRight = 22; this.classA = 'small-userName'; this.menu='展开菜单栏' } else { this.spanLeft = 4; this.spanRight = 20; this.classA = 'large-userName'; this.menu='收起菜单栏' } }, changeSrc(src){ document.getElementById('rightFrame').src=src } } }; var mainComponent = Vue.extend(Main); new mainComponent().$mount('#admin-index'); //个人信息 var PersonalInformation = { data () { return { formValidate: { name: '', mail: '', city: '', gender: '', interest: [], date: '', time: '', desc: '' }, ruleValidate: { name: [ { required: true, message: 'The name cannot be empty', trigger: 'blur' } ], mail: [ { required: true, message: 'Mailbox cannot be empty', trigger: 'blur' }, { type: 'email', message: 'Incorrect email format', trigger: 'blur' } ], city: [ { required: true, message: 'Please select the city', trigger: 'change' } ], gender: [ { required: true, message: 'Please select gender', trigger: 'change' } ], interest: [ { required: true, type: 'array', min: 1, message: 'Choose at least one hobby', trigger: 'change' }, { type: 'array', max: 2, message: 'Choose two hobbies at best', trigger: 'change' } ], date: [ { required: true, type: 'date', message: 'Please select the date', trigger: 'change' } ], time: [ { required: true, type: 'date', message: 'Please select time', trigger: 'change' } ], desc: [ { required: true, message: 'Please enter a personal introduction', trigger: 'blur' }, { type: 'string', min: 20, message: 'Introduce no less than 20 words', trigger: 'blur' } ] } } }, methods: { handleSubmit (name) { this.$refs[name].validate((valid) => { if (valid) { this.$Message.success('Success!'); } else { this.$Message.error('Fail!'); } }) }, handleReset (name) { this.$refs[name].resetFields(); } } }; var personalComponent = Vue.extend(PersonalInformation); new personalComponent().$mount('#personal-information'); // 教育经历 var EducationExperience = { }; var educationExperienceComponent = Vue.extend(EducationExperience); new educationExperienceComponent().$mount('#education-experience'); // 博客类别 var BlogCategory = { }; var blogCategoryComponent = Vue.extend(BlogCategory); new blogCategoryComponent().$mount('#blog-category'); // 创建博客 var BlogCreate = { }; var blogCreateComponent = Vue.extend(BlogCreate); new blogCreateComponent().$mount('#blog-create'); // 博客管理 var BlogManage = { }; var blogManageComponent = Vue.extend(BlogManage); new blogManageComponent().$mount('#blog-manage'); // 学习经历 var LearningExperience = { }; var learningExperienceComponent = Vue.extend(LearningExperience); new learningExperienceComponent().$mount('#learning-experience'); // 技能与能力 var SkillsAndAbilities = { }; var skillsAndAbilitiesComponent = Vue.extend(SkillsAndAbilities); new skillsAndAbilitiesComponent().$mount('#skills-and-abilities'); // 作品展示 var Works = { }; var worksComponent = Vue.extend(Works); new worksComponent().$mount('#works'); // 作品分类 var WorksCategory = { }; var WorksCategoryComponent = Vue.extend(WorksCategory); new WorksCategoryComponent().$mount('#works-category'); // 轮播图管理 var PictureManage = { }; var pictureManageComponent = Vue.extend(PictureManage); new pictureManageComponent().$mount('#picture-manage'); // 差链接管理 var UrlManage = { }; var urlManageComponent = Vue.extend(UrlManage); new urlManageComponent().$mount('#url-manage');
import Monkberry from 'monkberry'; import 'monkberry-events'; import App from './components/App.monk'; import * as TodoActions from './actions/todos' import { bindActionCreators } from 'redux' import configureStore from './store/configureStore' import 'todomvc-app-css/index.css' const store = configureStore(); const context = bindActionCreators(TodoActions, store.dispatch); let view = Monkberry.render(App, document.body, {context}); const listener = () => view.update(store.getState()); store.subscribe(listener); listener(); if (module.hot) { module.hot.accept('./components/App.monk', () => { view.remove(); const App = require('./components/App.monk'); view = Monkberry.render(App, document.body, {context}); view.update(store.getState()); }); }
import riot from 'riot' import {userService, projectService, categoryService} from 'services' import {notificationManager} from 'utils' import './new.styl' riot.tag('projects-new', require('./new.jade')(), function (opts) { this.mixin('login-required', 'form', 'load-entity') this.project = {} if (opts.projectID) { this.loadEntity(opts.projectID, projectService, {key: 'project'}) .then((project) => { if (project.author.id !== userService.currentUser.id) { riot.route('/') } }) } categoryService.list() .then(categories => this.categories = categories) .catch(_e => notificationManager.notify('Could not load categories, try again later', 'danger')) .finally(() => this.update()) this.saveProject = () => { this.startLoading({key: 'saving'}) const values = this.fetchValues('title', 'url', 'description', 'category_id') Object.assign(this.project, values) projectService.save(this.project).then((project) => { notificationManager.notify('The project has been saved') riot.route(`/projects/${project.id}`) }).catch(e => this.errors = this.formatErrors(e)) .finally(() => this.endLoading({key: 'saving', update: true})) } })
(function () { angular.module('upgradeDirective', []) .directive('upgradeDirective', upgradeDirective); upgradeDirective.$inject = ['gameService', '$timeout', '$interval']; function upgradeDirective (gameService, $timeout, $interval) { var upgradeController = function () { var uc = this; uc.clickedAutoClicker = clickedAutoClicker; uc.upgradePlayer = upgradePlayer; uc.clickGrandpa = clickGrandpa; function upgradePlayer() { gameService.updatePlayer(); } return { restrict: 'EA', controller: upgradeController, controllerAs: 'uc', bindToController: true, templateUrl: '../templates/upgrades.html' }; } })();
angular.module("ngApp.trackAndTraceDashboard") .controller("TrackAndTraceDashBoardController", function ($scope, $uibModal, AppSpinner, $translate, CustomerService, $filter, toaster, SessionService, $state, TrackAndTraceDashboardService) { //Set Multilingual for Modal Popup var setMultilingualOptions = function () { $translate(['FrayteError', 'FrayteInformation', 'FrayteValidation', 'FrayteSuccess', 'ErrorGettingRecordPleaseTryAgain', 'LoadingTrackTraceDashboard']).then(function (translations) { $scope.FrayteError = translations.FrayteError; $scope.FrayteInformation = translations.FrayteInformation; $scope.FrayteValidation = translations.FrayteValidation; $scope.FrayteSuccess = translations.FrayteSuccess; $scope.ErrorGettingRecordPleaseTryAgain = translations.ErrorGettingRecordPleaseTryAgain; $scope.LoadingTrackTraceDashboard = translations.LoadingTrackTraceDashboard; // Initial Deatil call here --> Spinner Message should be multilingual getInitialDetails(); }); }; var setUserDashBoard = function () { angular.forEach($scope.shipments, function (eachObj) { if (eachObj.StatusId === $scope.AftershipStatusTag.Pending) { $scope.dashBoardDetail.Pending.TotalShipment += 1; $scope.dashBoardDetail.Pending.Trackings.push(eachObj); } if (eachObj.StatusId === $scope.AftershipStatusTag.Expired) { $scope.dashBoardDetail.Expired.TotalShipment += 1; $scope.dashBoardDetail.Expired.Trackings.push(eachObj); } if (eachObj.StatusId === $scope.AftershipStatusTag.Exception) { $scope.dashBoardDetail.Exception.TotalShipment += 1; $scope.dashBoardDetail.Exception.Trackings.push(eachObj); } if (eachObj.StatusId === $scope.AftershipStatusTag.Delivered) { $scope.dashBoardDetail.Delivered.TotalShipment += 1; $scope.dashBoardDetail.Delivered.Trackings.push(eachObj); } if (eachObj.StatusId === $scope.AftershipStatusTag.AttemptFail) { $scope.dashBoardDetail.AttemptFail.TotalShipment += 1; $scope.dashBoardDetail.AttemptFail.Trackings.push(eachObj); } if (eachObj.StatusId === $scope.AftershipStatusTag.OutForDelivery) { $scope.dashBoardDetail.OutForDelivery.TotalShipment += 1; $scope.dashBoardDetail.OutForDelivery.Trackings.push(eachObj); } if (eachObj.StatusId === $scope.AftershipStatusTag.InTransit) { $scope.dashBoardDetail.InTransit.TotalShipment += 1; $scope.dashBoardDetail.InTransit.Trackings.push(eachObj); } if (eachObj.StatusId === $scope.AftershipStatusTag.InfoReceived) { $scope.dashBoardDetail.InfoReceived.TotalShipment += 1; $scope.dashBoardDetail.InfoReceived.Trackings.push(eachObj); } }); calculatePercentage(); }; var calculatePercentage = function () { var totalShipments = $scope.shipments.length; $scope.dashBoardDetail.InfoReceived.Percentage = ($scope.dashBoardDetail.InfoReceived.TotalShipment / totalShipments) * 100; $scope.dashBoardDetail.Expired.Percentage = ($scope.dashBoardDetail.Expired.TotalShipment / totalShipments) * 100; $scope.dashBoardDetail.Exception.Percentage = ($scope.dashBoardDetail.Exception.TotalShipment / totalShipments) * 100; $scope.dashBoardDetail.Delivered.Percentage = ($scope.dashBoardDetail.Delivered.TotalShipment / totalShipments) * 100; $scope.dashBoardDetail.AttemptFail.Percentage = ($scope.dashBoardDetail.AttemptFail.TotalShipment / totalShipments) * 100; $scope.dashBoardDetail.OutForDelivery.Percentage = ($scope.dashBoardDetail.OutForDelivery.TotalShipment / totalShipments) * 100; $scope.dashBoardDetail.InTransit.Percentage = ($scope.dashBoardDetail.InTransit.TotalShipment / totalShipments) * 100; $scope.dashBoardDetail.Pending.Percentage = ($scope.dashBoardDetail.Pending.TotalShipment / totalShipments) * 100; }; var getScreenInitials = function () { TrackAndTraceDashboardService.TrackAndTraceDashboard($scope.customerId).then(function (response) { if (response.status === 200 && response.data.Status) { $scope.shipments = response.data.Tracking; setUserDashBoard(); AppSpinner.hideSpinnerTemplate(); } }, function () { toaster.pop({ type: "error", status: $scope.FrayteError, body: $scope.ErrorGettingRecordPleaseTryAgain }); AppSpinner.hideSpinnerTemplate(); }); }; $scope.viewShipments = function (detail) { if (detail.TotalShipment) { var modalInstance = $uibModal.open({ animation: true, templateUrl: 'trackAndTraceDashBoard/trackAndTraceDashBoardShipments/trackAndTraceDashBoardShipments.tpl.html', controller: 'DashBoardShipmentController', windowClass: 'DirectBookingDetail', size: 'lg', backdrop: 'static', resolve: { StatusId: function () { return detail.StatusId; }, CustomerId: function () { return $scope.customerId; } } }); modalInstance.result.then(function () { }, function () { }); } }; var getInitialDetails = function () { $scope.customerId = $scope.userInfo.EmployeeId; AppSpinner.showSpinnerTemplate($scope.LoadingTrackTraceDashboard, $scope.Template); CustomerService.GetCustomerDetail($scope.customerId).then(function (response) { $scope.customerDetail = response.data; getScreenInitials(); }, function () { AppSpinner.hideSpinnerTemplate(); toaster.pop({ type: 'error', title: $scope.FrayteError, body: $scope.ErrorGettingRecordPleaseTryAgain, showCloseButton: true }); }); $scope.AftershipStatusTag = { Pending: 0, InfoReceived: 1, InTransit: 2, OutForDelivery: 3, AttemptFail: 4, Delivered: 5, Exception: 6, Expired: 7 }; $scope.AftershipStatus = { Pending: "Pending", PendingDisplay: "Pending", InfoReceived: "InfoReceived", InfoReceivedDisplay: "Info Received", InTransit: "InTransit", InTransitDisplay: "In Transit", OutForDelivery: "OutForDelivery", OutForDeliveryDisplay: "Out For Delivery", AttemptFail: "AttemptFail", AttemptFailDisplay: "Failed Attempt", Delivered: "Delivered", DeliveredDisplay: "Delivered", Exception: "Exception", ExceptionDislay: "Exception", Expired: "Expired", ExpiredDisplay: "Expired" }; $scope.dashBoardDetail = { Delivered: { StatusId: $scope.AftershipStatusTag.Delivered, Status: $scope.AftershipStatus.Delivered, StatusDisplay: $scope.AftershipStatus.DeliveredDisplay, TotalShipment: 0, Trackings: [], Percentage: 0, ImageName: 'Delivered.png' }, InTransit: { StatusId: $scope.AftershipStatusTag.InTransit, Status: $scope.AftershipStatus.InTransit, StatusDisplay: $scope.AftershipStatus.InTransitDisplay, TotalShipment: 0, Trackings: [], Percentage: 0, ImageName: 'InTransit.png' }, OutForDelivery: { StatusId: $scope.AftershipStatusTag.OutForDelivery, Status: $scope.AftershipStatus.OutForDelivery, StatusDisplay: $scope.AftershipStatus.OutForDeliveryDisplay, TotalShipment: 0, Trackings: [], Percentage: 0, ImageName: 'OutForDelivery.png' }, Pending: { StatusId: $scope.AftershipStatusTag.Pending, Status: $scope.AftershipStatus.Pending, StatusDisplay: $scope.AftershipStatus.PendingDisplay, TotalShipment: 0, Trackings: [], Percentage: 0, ImageName: 'Pending.png' }, AttemptFail: { StatusId: $scope.AftershipStatusTag.AttemptFail, Status: $scope.AftershipStatus.AttemptFail, StatusDisplay: $scope.AftershipStatus.AttemptFailDisplay, TotalShipment: 0, Trackings: [], Percentage: 0, ImageName: 'FailedAttemt.png' }, InfoReceived: { StatusId: $scope.AftershipStatusTag.InfoReceived, Status: $scope.AftershipStatus.InfoReceived, StatusDisplay: $scope.AftershipStatus.InfoReceivedDisplay, TotalShipment: 0, Trackings: [], Percentage: 0, ImageName: 'InfoReceived.png' }, Exception: { StatusId: $scope.AftershipStatusTag.Exception, Status: $scope.AftershipStatus.Exception, StatusDisplay: $scope.AftershipStatus.ExceptionDisplay, TotalShipment: 0, Trackings: [], Percentage: 0, ImageName: 'Exception.png' }, Expired: { StatusId: $scope.AftershipStatusTag.Expired, Status: $scope.AftershipStatus.Expired, StatusDisplay: $scope.AftershipStatus.ExpiredDisplay, TotalShipment: 0, Trackings: [], Percentage: 0, ImageName: 'Expired.png' } }; }; function init() { $scope.Template = 'directBooking/ajaxLoader.tpl.html'; $scope.spinnerMessage = $scope.LoadingTrackTraceDashboard; $scope.userInfo = SessionService.getUser(); if ($scope.userInfo) { setMultilingualOptions(); } else { $state.go("login"); } } init(); });
'use strict'; const expect = require('chai').expect; const encryptor = require('../../app/lib/encryptor'); describe('Encryptor', function(){ const text = 'Hello World!'; let encryptedText = encryptor.encrypt(text, 'secret'); describe('encrypt', function(){ it('encrypts the passing text', function(){ expect(encryptedText).not.to.equal(text) }); }); describe('decrypt', function(){ describe('when using the same secret key word', function(){ it('decrypts the passing text', function(){ const decryptedText = encryptor.decrypt(encryptedText, 'secret'); expect(decryptedText).to.equal(text); }); }); describe('when using different secret key word', function(){ it('does not decrypt the passing text correctly', function(){ const decryptedText = encryptor.decrypt(encryptedText, 'other secret'); expect(decryptedText).not.to.equal(text); }); }); }); });
const electron = require('electron'); const remote = electron.remote; const {Menu, MenuItem, BrowserWindow, Tray} = remote let tray; let contextMenu; function addTray() { if (tray != undefined) { return; } // 添加托盘图标 tray = new Tray('../images/open.png'); // 为托盘图标添加上下文菜单 contextMenu = Menu.buildFromTemplate([ {label: '复制', role: 'copy'}, {label: '粘贴', role: 'paste'}, {label: '剪切', role: 'cut'} ]) tray.setToolTip('这是一个托盘应用'); // tray.setContextMenu(contextMenu); /* altKey:Alt键 shiftKey:Shift键 ctrlKey:Ctrl键 metaKey:Meta键,在Mac OS X下是Command键,如果在Windows下,是窗口键 */ tray.on('right-click', (event) => { textarea.value += '\r\n' + 'right-click'; if (event.shiftKey) { window.open('https://geekori.com', 'right-click', 'width=300,height=200'); } else { tray.popUpContextMenu(contextMenu); } }) // 单击事件 tray.on('click', (event) => { textarea.value += '\r\n' + 'click'; if (event.shiftKey) { window.open('https://www.jd.com', 'click', 'width=600,height=300'); } else { tray.popUpContextMenu(contextMenu); } }); // Only Mac // 将任何东西拖动到拖动到托盘图标上是触发,例如,在word中将文字拖动到托盘图标上会触发。 tray.on('drop', () => { textarea.value += '\r\n' + 'drop'; }) // 拖动文件 tray.on('drop-files', (event, files) => { textarea.value += '\r\n' + 'drop-files'; for (var i = 0; i < files.length; i++) { textarea.value += files[i] + '\r\n'; } }) // 拖动文本 tray.on('drop-text', (event, text) => { textarea.value += '\r\n' + 'drop-text\r\n'; textarea.value += text; }) // 气泡消息显示事件 tray.on('balloon-show', () => { textarea.value += 'balloon-show\r\n'; }) // 气泡消息单击事件 tray.on('balloon-click', () => { textarea.value += 'balloon-click\r\n'; }); // 气泡消息关闭事件 tray.on('balloon-closed', () => { textarea.value += 'balloon-closed\r\n'; }); // 气泡的click和closed事件是互斥的,单击气泡只会触发click事件,只有当气泡自己关闭后,才会触发closed事件 } //修改托盘的图标 function changeTrayIcon() { if (tray != undefined) { tray.setImage('../images/note1.png') } } //mac 有效,在图标后面增加文字 function changeTrayTitle() { if (tray != undefined) { tray.setTitle('Hello Wordld') } } function changeTrayToolTip() { if (tray != undefined) { tray.setToolTip('tool tip') } } function removeTray() { if (tray != undefined) { tray.destroy() tray = undefined } }
const { successResponse, errorResponse } = require('../helper/index'); const jwt = require('jsonwebtoken'); const Cryptr = require('cryptr'); const cryptr = new Cryptr("SECRETKEY"); const { User } = require('../models/users'); const e = require('express'); // LOGIN API module.exports.login = async (req, res) => { const user = await User.findOne({ email: req.body.email }).lean() // CHECK IF USER EXISTS if (user == null || user == undefined) { errorResponse(req, res, "User does not exist", 204) return; } // DECRYPT USER PASSWORD console.log(user) const decryptedpassword = cryptr.decrypt(user.password); if (decryptedpassword == req.body.password) { delete user.password // SIGN A JWT TOKEN AND SEND IT BACK const token = await jwt.sign({_id:user._id},"TOKENSECRET"); user.token=token successResponse(req, res, user) } else { errorResponse(req, res, { err: "Invalid Credentials" }) } } // REGISTER API module.exports.register = async (req, res) => { const checkEmail = await User.findOne({ email: req.body.email }) // CHECK IF EMAIL ALREADY EXISTS if (checkEmail != null || checkEmail != undefined) { errorResponse(req, res, "Email already exist", 204) return; } // ENCRYPT THE PASSWORD BEFORE SAVING IN DATABASE const encryptedPassword = cryptr.encrypt(req.body.password); let savedUser = {} try { const user = new User({ firstName: req.body.firstName, lastName: req.body.lastName, mobile: req.body.mobile, email: req.body.email, password: encryptedPassword, city:req.body.city }) savedUser = await user.save() console.log(savedUser) delete savedUser._doc['password'] } catch (error) { errorResponse(req, res, error, 201) } successResponse(req, res, savedUser) }
$(document).ready(function () { "use strict"; var av_name = "RemoveUselessFS"; var av = new JSAV(av_name,); var Frames = PIFRAMES.init(av_name); var arrow = String.fromCharCode(8594); var grammar = "[[\"S\",\"→\",\"aB\"],\ [\"S\",\"→\",\"bA\"],\ [\"A\",\"→\",\"aA\"],\ [\"B\",\"→\",\"Sa\"],\ [\"B\",\"→\",\"b\"],\ [\"C\",\"→\",\"cBc\"],\ [\"C\",\"→\",\"a\"],\ [\"D\",\"→\",\"bCb\"],\ [\"E\",\"→\",\"Aa\"],\ [\"E\",\"→\",\"b\"]]"; var grammarArray = JSON.parse(grammar); var grammarMatrix = new GrammarMatrix( av,grammarArray, {style: "table", left: 10, top: 60}); grammarMatrix.hide(); var grammar2 = "[[\"S\",\"→\",\"aB\"],\ [\"B\",\"→\",\"Sa\"],\ [\"B\",\"→\",\"b\"],\ [\"C\",\"→\",\"cBc\"],\ [\"C\",\"→\",\"a\"],\ [\"D\",\"→\",\"bCb\"],\ [\"E\",\"→\",\"b\"]]"; var grammarArray2 = JSON.parse(grammar2); var grammarMatrix2 = new GrammarMatrix( av,grammarArray2, {style: "table", left: 10, top: 140}); grammarMatrix2.hide(); var grammar3 = "[[\"S\",\"→\",\"aB\"],\ [\"B\",\"→\",\"Sa\"],\ [\"B\",\"→\",\"b\"]]"; var grammarArray3 = JSON.parse(grammar3); var grammarMatrix3 = new GrammarMatrix(av,grammarArray3, {style: "table", left: 10, top: 60}); grammarMatrix3.hide(); // Frame 1 av.umsg("Previously we raised the question of what to do when some variables cannot ever lead to a useful derivation. This frameset discusses how to recognize and remove useless productions."); av.displayInit(); // Frame 2 av.umsg(Frames.addQuestion("reachC")); av.step(); // Frame 3 av.umsg(Frames.addQuestion("useless")); av.step(); // Frame 4 av.umsg(Frames.addQuestion("remove")); av.step(); // Frame 5 av.umsg(Frames.addQuestion("impossible")); av.step(); // Frame 6 av.umsg(Frames.addQuestion("alluseless")); av.step(); // Frame 7 av.umsg(Frames.addQuestion("nochange")); av.step(); // Frame 8 av.umsg(Frames.addQuestion("unreachable")); av.step(); // Frame 9 av.umsg(Frames.addQuestion("nonterm")); av.step(); // Frame 10 av.umsg("We will now show an algorithm for removing both types of useless productions. Since we have two types of useless productions, we will use two steps to remove them."); av.step(); // Frame 11 av.umsg(Frames.addQuestion("initv1")); grammarMatrix.show(); av.step(); // Frame 12 av.umsg(Frames.addQuestion("firstiter")); var V = new av.ds.array(["","","","","",""], {left: 40, top: 410, indexed: true}); var ALabel = av.label("$V_1$",{top: 415, left: 10}); av.step(); // Frame 13 av.umsg(Frames.addQuestion("seconditer")); V.value(0,"B"); V.value(1,"C"); V.value(2,"E"); av.step(); // Frame 14 av.umsg(Frames.addQuestion("lastiter")); V.value(3,"S"); V.value(4,"D"); av.step(); // Frame 15 av.umsg(Frames.addQuestion("doneiter")); av.step(); // Frame 16 av.umsg(Frames.addQuestion("whichprods")); av.step(); // Frame 17 av.umsg(Frames.addQuestion("doneyet")); grammarMatrix.hide(); grammarMatrix2.show(); av.step(); // Frame 18 av.umsg(Frames.addQuestion("howmanyvar")); V.hide(); ALabel.hide(); av.step(); // Frame 19 av.umsg(Frames.addQuestion("sb")); var VDG = new av.ds.FA({left: 120, top: 80, width: 300}); var S = VDG.addNode({value:"S", left: 0}); var B = VDG.addNode({value:"B", left: 50}); var C = VDG.addNode({value:"C", left:100}); var D = VDG.addNode({value:"D",left:150}); var E = VDG.addNode({value:"E", left:200}); grammarMatrix2.highlight(0); av.step(); // Frame 20 av.umsg(Frames.addQuestion("bs")); VDG.addEdge(S, B, {weight:" "}); VDG.layout(); grammarMatrix2.unhighlight(0); grammarMatrix2.highlight(1); av.step(); // Frame 21 av.umsg(Frames.addQuestion("cb")); VDG.addEdge(B, S, {weight:" "}); grammarMatrix2.unhighlight(1); grammarMatrix2.highlight(3); VDG.layout(); av.step(); // Frame 22 av.umsg(Frames.addQuestion("dc")); VDG.addEdge(C, B, {weight:" "}); grammarMatrix2.unhighlight(3); grammarMatrix2.highlight(5); VDG.layout(); av.step(); // Frame 23 av.umsg(Frames.addQuestion("whichremove")); VDG.addEdge(D, C, {weight:" "}); grammarMatrix2.unhighlight(5); VDG.layout(); av.step(); // Frame 24 av.umsg("The resulting Grammar $G'$ has $L(G)=L(G')$, and $G'$ has no useless productions."); grammarMatrix2.hide(); VDG.hide(); grammarMatrix3.show(); av.step(); // Frame 25 av.umsg("Finally, How would you implement Part 2 of the algorithm to remove useless productions? How do you know which nodes are accessible from S?"); grammarMatrix3.hide(); av.step(); // Frame 26 av.umsg("Finally, How would you implement Part 2 of the algorithm to remove useless productions? How do you know which nodes are accessible from S?<br/><br/>The answer is to use a Depth First Search or Breadth First Search graph algorithm."); av.step(); //Frame 27 av.umsg("Congratulations! Frameset completed."); av.recorded(); });
var express = require('express'); var router = express.Router(); var controllers = require('../controllers'); /* GET home page. */ router.get('/', controllers.index.indexAction); router.get('/home', controllers.home.indexAction); router.get('/home/procedure', controllers.home.procedureAction); module.exports = router;
import React from 'react'; import PropTypes from 'prop-types'; import {Input} from '../../atoms/input/Input'; import {FormattedNumberInput} from '../../atoms/formattedNumberInput/FormattedNumberInput'; import {Button} from '../../atoms/button/Button'; import "./RentRoll.scss"; /** * The component RentRollRow represent one row of a rent roll. The rent roll keeps track of the annual rent income for the row. */ class RentRollRow extends React.Component { constructor(props) { super(props); this.state = { rowNumber: props.rowNumber, monthlyRent:0, vacancyRate:0, annualRent:0, annualRentKey:Math.floor(Math.random() * Math.floor(100000000)) //random value for the key, used to force a repaint of the component }; this.handleOnBlur = this.handleOnBlur.bind(this); } /** * handleOnBlur() is called by all financially relevant fields (monthly rent, vacancy rate) when they lose the input focus * in order to recalculate the annual rent income. * @param fieldName * @param event */ handleOnBlur(fieldName, event) { // update the value that has changed and recalculate the annual rent const currentState = this.state; currentState[fieldName] = event.target.value; const maxAnnualRent = currentState.monthlyRent * 12; const vacancyLoss = maxAnnualRent * currentState.vacancyRate; const newAnnualRent = maxAnnualRent - vacancyLoss; currentState["annualRent"] = newAnnualRent; currentState["annualRentKey"] = Math.floor(Math.random() * Math.floor(100000000)); // update the key to force a redraw of the annual rent input field this.setState(currentState); // tell the parent that the annual rent income has changed this.props.onChange && this.props.onChange(this.state.rowNumber, {annualRent: newAnnualRent}); } render() { return [ <Input name="unitNumber" className="text-input" key={this.state.rowNumber} />, <FormattedNumberInput name="monthlyRent" key={this.state.rowNumber+1} format="$0,0.00" onBlur={(event)=>{this.handleOnBlur("monthlyRent", event)}}/>, <FormattedNumberInput name="vacancyRate" key={this.state.rowNumber+2} format="0.0%" required={true} onBlur={(event)=>{this.handleOnBlur("vacancyRate", event)}}/>, <FormattedNumberInput name="numberBedrooms" key={this.state.rowNumber+3} format="0,0"/>, <FormattedNumberInput name="numberBathrooms" key={this.state.rowNumber+4} className="number-of-bedrooms" format="0,0"/>, <FormattedNumberInput name="annualRent" key={this.state.annualRentKey} format="$0,0.00" value={this.state.annualRent} readonly={true}/> ]; } } RentRollRow.propTypes = { onChange:PropTypes.func, rowNumber:PropTypes.number, }; /** * The component RentRoll implements the Rent Roll functionality. It allows the user to enter one or more rent roll data rows. * The component keeps track of and display the total annual rent income for all rows that are displayed */ export class RentRoll extends React.Component { constructor() { super(); this.state = { rentRoll: [0], totalAnnualRent:0, totalAnnualRentKey:Math.floor(Math.random() * Math.floor(100000000)) }; this.handleOnChange = this.handleOnChange.bind(this); this.addRowHandler = this.addRowHandler.bind(this); } /** * handleOnChange() is called every time a rent roll row changes a financially relevant value and it receives * the updated annual rent fot the row. The annual rent row total for each row is tracked is this component and * the grand total is maintained here as well * @param rowNumber * @param rentRowValue */ handleOnChange(rowNumber, rentRowValue) { //get the current rent roll, update it with the rent from the changed row const currentRentRoll = this.state.rentRoll; currentRentRoll[rowNumber] = rentRowValue.annualRent; // calculate the total let totalAnnualRent = 0; currentRentRoll.forEach((rowAnnualRent) => { totalAnnualRent += rowAnnualRent; }); // update the state // changing the annual rent key with a random number causes the component to repaint this.setState({rentRoll:currentRentRoll, totalAnnualRent, totalAnnualRentKey:Math.floor(Math.random() * Math.floor(100000000))}); // and tell the parent the new annjual rent total this.props.onChange && this.props.onChange(totalAnnualRent); } /** * renderRentRollRows renders all the rent roll rows * @returns {*[]} */ renderRentRollRows() { return this.state.rentRoll.map((_, index) => { return ( <RentRollRow key={index} rowNumber={index} onChange={this.handleOnChange}/> )} ); }; /** * addRowHandler is called when the user clicks the Add Row button. It adds a new entry to the state for the new rent row */ addRowHandler() { const currentRentRoll = this.state.rentRoll; currentRentRoll.push(0); this.setState({rentRoll: currentRentRoll}); } render() { return ( <div className="organism-rent-roll"> <h2 key="1"> Rent Roll </h2> <Button key={"Add Button"} className="add-row-button" onClick={this.addRowHandler}>Add Row</Button> <div key="2" className="rent-roll-container"> <div className="rent-roll-column-header rent-roll-unit-number"> <strong>Unit</strong> </div> <div className="rent-roll-column-header rent-roll-monthly-rent"> Monthly Rent ($) </div> <div className="rent-roll-column-header rent-roll-vacancy-rate"> Vacancy Rate (%) </div> <div className="rent-roll-column-header rent-roll-number-bedrooms"> Number of Bedrooms </div> <div className="rent-roll-column-header rent-roll-number-bathrooms"> Number of Bathrooms </div> <div className="rent-roll-column-header rent-roll-annual-rent"> Annual Rent ($) </div> {this.renderRentRollRows()} <div className="rent-roll-column-footer rent-roll-unit-number" /> <div className="rent-roll-column-footer rent-roll-monthly-rent" /> <div className="rent-roll-column-footer rent-roll-vacancy-rate" /> <div className="rent-roll-column-footer rent-roll-number-bedrooms" /> <div className="rent-roll-column-footer rent-roll-number-bathrooms" /> <div className="rent-roll-column-footer rent-roll-annual-rent"> <FormattedNumberInput name="annualRent" key={this.state.totalAnnualRentKey} format="$0,0.00" value={this.state.totalAnnualRent} readonly={true}/> </div> </div> </div> ); } } RentRoll.propTypes = { onChange:PropTypes.func };
requirejs.config({ baseUrl: 'resources/js', });
import React, { Component } from 'react'; import Head from 'next/head'; import Link from 'next/link'; import WPAPI from 'wpapi'; import Router from 'next/router'; // import Header from '../components/Header'; // import Footer from '../components/Footer'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import Quote from '@material-ui/icons/FormatQuoteRounded'; import Config from '../config'; import PageWrapper from '../components/PageWrapper'; import Layout from '../components/Layout'; import Menu from '../components/Menu'; import Products from '../static/mockDB/products.json' import Reviews from '../static/mockDB/reviews.json' const wp = new WPAPI({ endpoint: Config.apiUrl }); const ButtonLink = props => ( <div className="button-wrapper" style={props.styles}> <Link href={ props.url }> <button>{ props.children }</button> </Link> <style jsx>{` button { background-color: #f06c0d; border: none; color: white; padding: 6px 20px; border-radius: 3px; font-size: 20px; } `}</style> </div> ) const Review = ({ review, idx }) => ( <div className='yapi-review'> <div className="review-box"> <div className={ (idx%2 !== 0) ? 'icon-wrap green-ico': 'icon-wrap orange-ico'}> <Quote style={{height: '40px', width: '40px'}} /> </div> <div className="img-wrap"> <img src={review.reviewerImg} /> </div> <div className="review-wrap"> <p className="review-text">{review.review}</p> <p className="review-name">{review.reviewerName}</p> <p className="review-practice">{ review.practice }</p> </div> </div> <style jsx>{` .yapi-review{ max-width: 1080px; margin: 0 auto; padding: 27px 0; } .yapi-review + .yapi-review { margin-top: 30px; } .review-box{ position: relative; background-color: white; border: 1px solid #e6e6e6; box-shadow: 0px 1px 18px rgba(23,23,23,0.17); -moz-box-shadow: 0px 1px 18px rgba(23,23,23,0.17); -webkit-box-shadow: 0px 1px 18px rgba(23,23,23,0.17); padding: 40px; display: grid; grid-template-columns: 160px 1fr; grid-column-gap: 15px; } .icon-wrap { border-radius: 50%; width: 40px; height: 40px; position: absolute; margin-left: auto; margin-right: auto; left: 0; right: 0; top: -20px; } .green-ico{ border: 3px solid #5fb324; color: #5fb324; } .orange-ico{ border: 3px solid #f06c0d; color: #f06c0d; } .img-wrap, .review-wrap { width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center; } .img-wrap img{ width: 100%; height: 155px; border-radius: 50%; } .review-text { margin-bottom: 0; padding-bottom: 15px; } .review-name, .review-practice{ align-self: flex-start; margin:5px 0; } .review-name { border-top: 1px solid #e6e6e6; font-weight: bold; width: 100%; padding-top:15px } .review-practice{ color: #f06c0d } `}</style> </div> ) const ProductSection = ({ product, idx }) => ( <section className={(idx % 2 === 0) ? '' : 'rev'} data-bla={idx}> <div className='two-col'> <div className="img-wrapper"> <img src={product.sectionImg}></img> </div> <div className="section-wrapper"> <h3>{ product.name }</h3> <p>{ product.desc }</p> <p>{ product.descP }</p> <ButtonLink url={`/p/${product.pageURL}`} styles={{alignSelf: 'center'}}>Learn More</ButtonLink> </div> </div> <style jsx>{` section { margin: 0 -8px; width: 100vw; max-width: 100vw; padding: 30px 0; } .two-col { max-width: 1100px; margin: 0 auto; display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 20px; } section .img-wrapper, section .section-wrapper{ width: 100%; display: flex; flex-direction: column; justify-content:center; align-items: flex-start; } .rev .img-wrapper{ align-items: flex-end; } .rev{ background-color: #fbfcfb; } .rev .section-wrapper { grid-column: 1 / 2; grid-row: 1 / 2 } .rev .img-wrapper { grid-column: 2 / 3; grid-row: 1 / 2 } .section-wrapper h3 { width: 100%; text-align: left; font-size: 22px; } .section-wrapper p { margin:0; font-size:20px; text-align: left; width: 100%; } .section-wrapper p+p { padding-top: 20px; padding-bottom: 20px; } .img-wrapper img { padding: 20px 0; width: 75%; height: auto; } `}</style> </section> ) const ProductIcon = ({ product }) => ( <li className='productIcon'> <Link as={`/p/${product.pageURL}`} href={`/post?title=${product.pageURL}`}> <a> <img src={product.iconURL} /> <p>{ product.name }</p> </a> </Link> <style jsx>{` li { list-style: none; margin: 5px 0; } a { text-decoration: none; color: #6d6d6d; display: flex; flex-direction: column; justify-content:center; align-items:center; font-family: 'Arimo',Helvetica,Arial,Lucida,sans-serif; font-size: 25px; } a:hover { opacity: 0.6; } .productIcon img{ width: 100px; height:100px; } `}</style> </li> ) class Index extends Component { state = { id: '', }; static async getInitialProps() { try { const [page, posts, pages] = await Promise.all([ wp .pages() .slug('index') .embed() .then(data => { return data[0]; }), wp.posts().embed(), wp.pages().embed(), ]); return { page, posts, pages }; } catch (err) { if (err.data.status === 403) { tokenExpired(); } } return null; } componentDidMount() { const token = localStorage.getItem(Config.AUTH_TOKEN); if (token) { wp.setHeaders('Authorization', `Bearer ${token}`); wp.users() .me() .then(data => { const { id } = data; // console.log(data) this.setState({ id }); }) .catch(err => { if (err.data.status === 403) { tokenExpired(); } }); } } render() { const { id } = this.state; const { posts, pages, headerMenu, page } = this.props; console.log(this.props) console.log(page) return ( <Layout> {/* <Menu menu={headerMenu} /> */} <h1>Index</h1> {/* <div // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: page.content.rendered, }} /> */} </Layout> ) } } // export default () => ( // <div> // <Head> // <title>Paperless Dental Software – YAPI</title> // <link href="https://fonts.googleapis.com/css?family=Arimo:400,400i,700|Roboto:100,400" rel="stylesheet"></link> // <style> // {` // body { // font-family: 'Arimo',Helvetica,Arial,Lucida,sans-serif; // color: #6d6d6d; // -webkit-font-smoothing: antialiased; // -moz-osx-font-smoothing: grayscale; // } // `} // </style> // </Head> // <Layout> // <section className="two-col"> // <div className='img-wrapper'> // <img src='https://yapiapp.com/wp-content/uploads/2018/07/Flat-Style00008-1-1.png'></img> // </div> // <div className='section-wrapper' style={{justifyContent: 'flex-start', padding: '0 0 0 50px'}}> // <h2>Paperless Dental Software</h2> // <ButtonLink url="/demo" styles={{alignSelf: 'flex-start'}}>Schedule a Demo!</ButtonLink> // </div> // </section> // <section style={{ padding: '30px 0', backgroundColor: '#fbfcfb', margin: '0 -8px', width: '100vw', maxWidth: '100vw' }}> // <h2 style={{ textAlign: 'center', fontWeight: 500, fontSize: '35px', width: '100%' }}>Focus on what matters the most - your patients. Automate the rest.</h2> // </section> // <section style={{ padding: '30px 0'}}> // <ul className="productIcons"> // {getProducts().map(product => ( // <ProductIcon key={product.name} product={product} /> // ))} // </ul> // </section> // <section style={{ padding: '30px 0', backgroundColor: '#fbfcfb', margin: '0 -8px', width: '100vw', maxWidth: '100vw', display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}> // <h2 style={{ textAlign: 'center', fontWeight: 500, fontSize: '35px', width: '100%' }}>Everything you need for an efficient dental practice, all in one place</h2> // <ButtonLink url='/videos'>Watch Product Videos!</ButtonLink> // </section> // { getProducts().map( (product, idx) => ( // <ProductSection key={product.name} product={product} idx={idx} /> // )) } // <section className="box-inset" tyle={{ backgroundColor: '#fbfcfb' }}> // <h2 style={{textAlign: 'center', fontSize: 50, fontWeight: 500}}>Why Dentists Love YAPI</h2> // { getReviews().map( (review, idx) => ( // <Review key={review.id} review={review} idx={idx} /> // ))} // </section> // </Layout> // <style jsx>{` // section { // max-width: 1200px; // margin: 0 auto; // } // .boxinset { // box-shadow: inset 0 0 7px rgba(0,0,0,.07); // } // section.two-col { // display: grid; // grid-template-columns: 1fr 1fr; // grid-column-gap: 20px; // } // section .img-wrapper, // section .section-wrapper{ // width: 100%; // display: flex; // flex-direction: column; // justify-content:center; // align-items: center; // } // .img-wrapper img { // padding: 20px 0; // width: 75%; // height: auto; // } // .section-wrapper h2 { // font-family: 'Roboto',Helvetica,Arial,Lucida,sans-serif; // font-weight: 100; // font-size: 55px; // } // .productIcons { // display: grid; // grid-template-columns: repeat(3, 1fr); // justify-items:center; // align-items: center; // padding: 0; // } // `}</style> // </div> // ) // export default PageWrapper(Index); export default Index;
var document = document || {}; function getRecipes() { var mySearch = document.getElementById('mySearch').value var container = document.getElementById('outPut'); fetch(`https://api.spoonacular.com/recipes/search?query=${mySearch}&number=10&apiKey=91b95939da654bce89b6eb7840578ec9&diet=vegetarian`) .then(response => response.json()) .then(data => { var recipes = data.results; // console.log(recipes); for (var i = 0; i < recipes.length; i++) { var content = document.createElement('div'); var contentImage=document.createElement('div'); var image = document.createElement('img'); var text = document.createElement('p'); var imageRecipe = data.baseUri + recipes[i].image; console.log(imageRecipe); var nameRecipe = recipes[i].title; console.log(nameRecipe); content.setAttribute('id', 'content'); contentImage.setAttribute('id', 'contentImage'); image.setAttribute('class', 'portrait'); image.src = imageRecipe; text.innerHTML = nameRecipe; container.appendChild(content); content.appendChild(contentImage); contentImage.appendChild(image); content.appendChild(text); } }) }
import React, { Fragment } from 'react'; import {Link} from "react-router-dom" class IconsGrid extends React.Component { constructor(props) { super(props) this.text = "The effort for a better eSolution • Developing better e-Vote web app" this.state = {text:"", index:0} //this.state = { color: "#282c34" }//this constructor line to make a different background color for this component } componentDidMount() { this.timerID = setInterval( () => {this.animateText()}, 400) } componentWillUnmount() { clearInterval(this.timerID) } animateText = () => { if (this.state.index === 67) { setTimeout(() => { this.setState({index:0}) },2000) } this.setState({ index:this.state.index + 1, text:this.text.slice(0,this.state.index) }) } render() { return ( <div className="banner"> <Fragment> <div className="name"> <h2>Upcoming features of eVote</h2> </div> <div className="anime-text"> <small>{this.state.text}</small> <i className="fa fa-i-cursor" aria-hidden="true"></i> </div> <div className="me"> <p data-aos='fade-up'>The web app is developed with React.js and ASP.Net Core for the purpose of a Online voting demonstration in the covid-19 season.</p> </div> <div className="learn-more" data-aos='fade-up'> <p>Learn<Link className="a-link" to="/aboutUs">More about us</Link> or <Link className="a-link" to="/contactUs">Contact Us</Link></p> </div> </Fragment> </div> ) } } export default IconsGrid
// VERSION 1.0.4 this.__defineGetter__('BrowserSearch', function() { return window.BrowserSearch; }); this.focusOmnibar = false; // will be set in omnibar.jsm if loaded this.focusSearchWhenFinished = false; this.focusSearchOnWidthFinished = function() { if(focusSearchWhenFinished) { focusSearchWhenFinished = false; BrowserSearch.webSearch(); } }; Modules.LOADMODULE = function() { // Omnibar nukes this method and replaces it with its own, which is flawed in Australis. // So, I have to replace it myself as well, to make sure it works, rather than call _webSearch(). Piggyback.add('focusSearch', BrowserSearch, 'webSearch', function() { // For Mac, opens a new window or focuses an existing window, if necessary. if(DARWIN) { if(window.location.href != window.getBrowserURL()) { var win = window.getTopWin(); if(win) { // If there's an open browser window, it should handle this command win.focus(); win.BrowserSearch.webSearch(); } else { // If there are no open browser windows, open a new one var observer = function observer(subject, topic, data) { if(subject == win) { BrowserSearch.webSearch(); Services.obs.removeObserver(observer, "browser-delayed-startup-finished"); } }; win = window.openDialog(window.getBrowserURL(), "_blank", "chrome,all,dialog=no", "about:blank"); Services.obs.addObserver(observer, "browser-delayed-startup-finished", false); } return; } } let openSearchPageIfFieldIsNotActive = function(aSearchBar) { if(!aSearchBar || document.activeElement != aSearchBar.textbox.inputField) { if(!focusOmnibar) { window.openUILinkIn("about:home", "current"); } else { window.openLocation(); } } }; let searchBar = this.searchBar; let placement = CustomizableUI.getPlacementOfWidget("search-container"); if(placement) { // show the chrome if the search bar is somewhere in there, before we do anything else if(typeof(slimChrome) != 'undefined' && !trueAttribute(slimChrome.container, 'hover') && (placement.area == CustomizableUI.AREA_PANEL || placement.area == CustomizableUI.AREA_NAVBAR || isAncestor(searchBar, slimChrome.container))) { focusSearchWhenFinished = true; slimChrome.initialShow(1500); return; } let focusSearchBar = () => { searchBar = this.searchBar; searchBar.select(); openSearchPageIfFieldIsNotActive(searchBar); }; if(placement.area == CustomizableUI.AREA_PANEL) { // The panel is not constructed until the first time it is shown. window.PanelUI.show().then(focusSearchBar); return; } if(placement.area == CustomizableUI.AREA_NAVBAR && searchBar && searchBar.parentNode.getAttribute("overflowedItem") == "true") { let navBar = document.getElementById(CustomizableUI.AREA_NAVBAR); navBar.overflowable.show().then(() => { focusSearchBar(); }); return; } } if(searchBar) { // we unload when fullScreen, so this isn't needed //if(window.fullScreen) // window.FullScreen.mouseoverToggle(true); searchBar.select(); } openSearchPageIfFieldIsNotActive(searchBar); }); Listeners.add(window, 'FinishedSlimChromeWidth', focusSearchOnWidthFinished); }; Modules.UNLOADMODULE = function() { Listeners.remove(window, 'FinishedSlimChromeWidth', focusSearchOnWidthFinished); Piggyback.revert('focusSearch', BrowserSearch, 'webSearch'); };
module.exports = function(grunt) { grunt.initConfig({ bowerDirectory: require('bower').config.directory, less: { compile: { options: { compress: false, paths: ['src/_less', 'tmp', '<%= bowerDirectory %>/bootstrap/less'] }, files: { 'tmp/assets/css/bootstrap.css': ['src/_less/theme.less'] } } }, watch: { less: { files: ['src/_less/*.less'], tasks: ['less:compile', 'cssmin:minify', 'clean'] } }, uglify: { js: { files: { 'dist/assets/js/site.js': [ '<%= bowerDirectory %>/jquery/dist/jquery.min.js', '<%= bowerDirectory %>/bootstrap/dist/js/bootstrap.min.js' ] } } }, cssmin: { minify: { expand: true, cwd: 'tmp/assets/css/', src: ['*'], dest: 'dist/assets/css/', ext: '.min.css' } }, copy: { 'dist-files': { files: [ { expand: true, cwd: '<%= bowerDirectory %>/bootstrap/dist/fonts/', src: ['**'], dest: 'dist/assets/fonts/' }, { expand: true, cwd: 'images', src: ['**'], dest: 'dist/assets/images/' } ], }, 'src-files': { files: [ { expand: true, cwd: '<%= bowerDirectory %>/bootstrap/less', src: ['bootstrap.less'], dest: 'tmp/' }, ] } }, exec: { build: { cmd: 'jekyll build' }, serve: { cmd: 'jekyll serve --watch' } }, 'gh-pages': { options: { base: 'dist' }, src: ['**'] }, clean: ['tmp'], concurrent: { dev: { tasks: ['exec:serve', 'watch:less'], options: { logConcurrentOutput: true } } } }); grunt.loadNpmTasks('grunt-concurrent'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-uglify'); //grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-gh-pages'); grunt.loadNpmTasks('grunt-exec'); //grunt.registerTask('default', [ 'less', 'uglify', 'copy', 'exec:build' ]); grunt.registerTask('default', [ 'copy:src-files', 'less', 'uglify', 'cssmin', 'copy:dist-files', 'concurrent:dev' ]); grunt.registerTask('deploy', [ 'uglify', 'cssmin', 'copy', 'exec:build', 'gh-pages' ]); };
import { lazy } from 'react'; export const lazyRoutes = [ { path: '/', label: 'home', exact: true, component: lazy(() => import( './pages/ProductGalleryPage/ProductGalleryPage' /* webpackChunkName: "home" */ ), ), }, { path: '/product/:productId', label: 'detailsPage', exact: false, component: lazy(() => import( './pages/ProductDetailsPage/ProductDetailsPage' /* webpackChunkName: "home" */ ), ), }, { path: '/card', label: 'cardPage', exact: true, component: lazy(() => import('./pages/CardPage/CardPage' /* webpackChunkName: "home" */), ), }, ]; export default { home: '/', detailsPage: '/product/:productId', cardPage: '/card', };
import styled from "styled-components"; export const Container = styled.div` width: 100%; padding: 15px 0; background-color: #5098a3; ul { display: flex; list-style: none; text-transform: uppercase; font-size: 14px; letter-spacing: 1px; flex-wrap: wrap; li { margin: 0 24px; width: 70px; a { color: white; text-decoration: none; &:hover { font-weight: bold; } } } .active { font-weight: bold; } } `;
import React, { Component } from 'react'; import { StyleSheet, Text, View } from 'react-native'; import firebase from 'firebase'; import FirebaseActions from './src/FirebaseActions'; export default class App extends Component { componentWillMount() { const config = { apiKey: 'AIzaSyD1d_dKYbzHQS5gavWothUmQUAoxqGI6yQ', // authDomain: 'test-18516.firebaseapp.com', databaseURL: 'https://test-18516.firebaseio.com/', projectId: 'test-18516', // storageBucket: 'test-18516.appspot.com', messagingSenderId: '857334559219' }; firebase.initializeApp(config); } render() { return <FirebaseActions />; } }
/** * Created by admin on 2017/5/7. * * 模块/路由/action * */ export default [ ["api/user/email", {post: "user/api/tools/email"}], ['api/user/password',{post:'user/api/tools/password'}], //['api/user/login',{post:'user/api/login'}], //['api/user/update',{post:'user/api/update'}] [/^api\/user\/([\s\S]*)$/,'user/api/:1'] ];
import React, { Fragment } from "react"; import Grid from "@material-ui/core/Grid"; import Typography from "@material-ui/core/Typography"; import TextInput from "./TextInput"; import { Divider } from "@material-ui/core"; import { makeStyles } from "@material-ui/core/styles"; import DeleteIcon from "@material-ui/icons/Delete"; import IconButton from "@material-ui/core/IconButton"; import Tooltip from "@material-ui/core/Tooltip"; const useStyles = makeStyles((theme) => ({ divider: { // margin: theme.spacing(1, 0), width: "100%", }, })); const TableRow = ({ className, name, formFields, createChangeHandler, index, removeRow, }) => { const classes = useStyles(); return ( <Fragment> <Grid container item sm={12} justify="space-between" alignItems="center" spacing={1} className={className} > <Grid item sm={1}> <Typography fontWeight="fontWeightBold">{index + 1}</Typography> </Grid> <Grid item sm={5}> <TextInput name={`${name}.description`} value={formFields.description} onChange={createChangeHandler(`${name}.description`)} multiline InputProps={{ disableUnderline: true }} /> </Grid> <Grid item sm={1}> <TextInput name={`${name}.unit`} value={formFields.unit} onChange={createChangeHandler(`${name}.unit`)} InputProps={{ disableUnderline: true }} /> </Grid> <Grid container item sm={1}> <Grid container item justify="flex-end"> <Grid item> <TextInput name={`${name}.quantity`} value={formFields.quantity} onChange={createChangeHandler(`${name}.quantity`)} type="number" InputProps={{ disableUnderline: true }} /> </Grid> </Grid> </Grid> <Grid container item sm={1}> <Grid container item justify="flex-end"> <Grid item> <TextInput name={`${name}.unitPrice`} value={formFields.unitPrice} onChange={createChangeHandler(`${name}.unitPrice`)} type="number" InputProps={{ disableUnderline: true }} /> </Grid> </Grid> </Grid> <Grid container item sm={2}> <Grid container item justify="flex-end"> <Grid item> <Typography fontWeight="fontWeightBold"> {formFields.quantity * formFields.unitPrice} </Typography> </Grid> </Grid> </Grid> <Grid item sm={1}> <Grid container item justify="flex-end"> <Grid item> <Tooltip title="Delete product"> <IconButton aria-label="delete product" onClick={() => removeRow(index)} > <DeleteIcon /> </IconButton> </Tooltip> </Grid> </Grid> </Grid> </Grid> <Divider className={classes.divider} /> </Fragment> ); }; export default TableRow;
/** * Created by wuyin on 2016/5/18. */ var myMo = require('./MyModules'); myMo.setName("wuyinlei"); //myMo.sayHello(); var myMo1 = require('./MyModules'); myMo1.setName('dasf'); myMo.sayHello(); //Hello ,my name is dasf 这个可以看到这两个myMo和myMo1是用的是一个实例 var myMo2 = require('./MyMoudles2'); var hello = new myMo2(); hello.setName('ok'); hello.sayHello();
Ext.define("Gvsu.Core.ProjectServer",{ extend: "Core.ProjectServer" ,dbConnect: function(callback) { this.sources.db = Ext.create("Database.drivers.Mysql.Database", this.config.mysql) callback() } })
var http = require("http"); var cookie = require("cookie"); var fs = require("fs"); var child_process = require("child_process"); var PORT = 8000; var DEFAULT_PROCESS_PORT = 7999; var BOOT = "./boot.sh"; var HTTP_HEADERS = ["Accept", "Accept-Charset", "Accept-Encoding", "Accept-Language", "Accept-Datetime", "Authorization", "Cache-Control", "Connection", "Cookie", "Content-Length", "Content-MD5", "Content-Type", "Date", "Expect", "From", "Host", "If-Match", "If-Modified-Since", "If-None-Match", "If-Range", "If-Unmodified-Since", "Max-Forwards", "Origin", "Pragma", "Proxy-Authorization", "Range", "Referer", "TE", "User-Agent", "Via", "Warning", "X-Requested-With", "DNT", "X-Forwarded-For", "X-Forwarded-Proto", "Front-End-Https", "X-ATT-DeviceId", "X-Wap-Profile", "Proxy-Connection", "Access-Control-Allow-Origin", "Accept-Ranges", "Age", "Allow", "Cache-Control", "Connection", "Content-Encoding", "Content-Language", "Content-Length", "Content-Location", "Content-MD5", "Content-Disposition", "Content-Range", "Content-Type", "Date", "ETag", "Expires", "Last-Modified", "Link", "Location", "P3P", "Pragma", "Proxy-Authenticate", "Refresh", "Retry-After", "Server", "Set-Cookie", "Status", "Strict-Transport-Security", "Trailer", "Transfer-Encoding", "Upgrade", "Vary", "Via", "Warning", "WWW-Authenticate", "X-Frame-Options", "Public-Key-Pins", "X-XSS-Protection", "Content-Security-Policy", "X-Content-Security-Policy", "X-WebKit-CSP", "X-Content-Type-Options", "X-Powered-By", "X-UA-Compatible" ]; var HTTP_HEADER_MAP; var cookieUserMap = {}; var processes = { "count": 1, "default": { port: DEFAULT_PROCESS_PORT, proc: null } }; var server; function readCookies() { var data = fs.readFileSync('arc/cooks'); var str = data.toString().replace(/[")]/g, ''); var lines = str.split("("); for (var i=0; i<lines.length; i++) { var tokens = lines[i].split(" "); if (tokens.length > 1) { cookieUserMap[tokens[0]] = tokens[1]; } } return; } function fixHeaders(old) { var result = {}; for (var key in old) { if (old.hasOwnProperty(key)) { result[HTTP_HEADER_MAP[key]] = old[key] } } return result; } function addMissingProcess(user) { if (!processes.hasOwnProperty(user)) { processes[user] = { port: (PORT + processes["count"]), proc: null }; processes["count"] += 1; } if (processes[user].proc == null) { console.log("Spawning web server on port: " + processes[user].port + " for user: " + user); processes[user].proc = child_process.spawn(BOOT, [ processes[user].port, user ]); processes[user].proc.stdout.on('data', function (data) { console.log(user+':' + data); }); } } function getForwardingPort(request) { if (!request.headers.hasOwnProperty("cookie")){ console.log("Route: default: Missing cookies"); return processes["default"].port; } var cookies = cookie.parse(request.headers.cookie); if (!cookies.hasOwnProperty("user")) { console.log("Route: default: Missing 'user' in cookies: " + request.headers.cookie); return processes["default"].port; } var cook = cookies["user"]; if (!cookieUserMap.hasOwnProperty(cook)) { readCookies(); } if (!cookieUserMap.hasOwnProperty(cook)) { console.log("Route: default: cookie doesn't exist in cookie map: " + cook); console.log(cookieUserMap); return processes["default"].port; } var user = cookieUserMap[cook]; addMissingProcess(user); console.log("Routing request for user " + user + " to port " + processes[user].port); return processes[user].port; //return processes["default"].port; } function requestHandler(request, response) { var options = { hostname: "localhost", port: getForwardingPort(request), path: request.url, method: request.method, headers: fixHeaders(request.headers) }; /** if (options.headers.hasOwnProperty("Host")) { options.headers["Host"] = options.hostname + ":" + options.port; } **/ //DEBUG //console.log("---REQUEST---"); //console.log(options); var forwardRequest = http.request(options, function(forwardResponse) { var headers = fixHeaders(forwardResponse.headers); //DEBUG //console.log("---RESPONSE---"); //console.log(headers); response.writeHead(forwardResponse.statusCode, headers); forwardResponse.on('data', function (chunk) { response.write(chunk); }); forwardResponse.on('end', function() { response.end(); }); }); forwardRequest.on('error', function(e) { console.log("Got error: " + e.message); response.writeHead(500, {"Content-Type": "text/plain"}); response.write("Error: " + e); response.end(); }); request.on("data", function(chunk) { forwardRequest.write(chunk); }); request.on("end", function() { forwardRequest.end(); }); } function initialize() { userProcesses = {}; processes["default"].proc = child_process.spawn(BOOT, [ processes["default"].port, "default" ]); processes["default"].proc.stdout.on('data', function (data) { console.log('default:' + data); }); readCookies(); server = http.createServer(requestHandler); HTTP_HEADER_MAP = {}; HTTP_HEADERS.forEach(function(x) { HTTP_HEADER_MAP[x.toLowerCase()] = x; }); } console.log("Starting userrouter on port " + PORT); initialize(); server.listen(PORT);
const Service = (req, res, next) => { res.render('privacy-policy'); }; export default Service;
import Axios from 'axios'; const listOfConditions = '/api/conditions'; // URL to POST to export const LOAD_CONDITIONS = 'LOAD_CONDITIONS'; export const ERROR = 'ERROR'; //GET all conditions export const loadConditions = () => { return (dispatch) => { return Axios.get(listOfConditions) .then(conditions => { dispatch({ type: LOAD_CONDITIONS, conditions: conditions.data }); }) .catch(err => { dispatch({ type: ERROR, error: err }); }); }; };
import React from 'react'; import {Link} from 'react-router-dom'; import HomeHeader from '../HomeComponents/HomeHeader'; class StepOne extends React.Component { render(){ return ( <div> <HomeHeader/> <div className='sign-up-page'> <div> <p className='step-one-header'>Step 2 of 2</p> <p className='step-one-sub-header'>Add a payment method.</p> <br></br> <p className='step-one-sub-header-2'>No commitments. Cancel anytime.</p> <p className='step-one-sub-header-3'>Your first 30 days are free. Cancel before <br></br>30 days and you won't be charged. After <br></br>30 days, you'll be charged $14.99/month.</p> <Link to="/LoggedInHome"><button className='sign-up-form-button-3'>SIGN UP</button></Link> </div> </div> </div> ) } } export default StepOne;
import React, { useContext } from 'react'; // Components import Product from './Product'; // Contexts import { ShoppingContext } from '../contexts/ShoppingContext'; import { ProductContext } from '../contexts/ProductContext'; const Products = () => { const { products, addItem } = useContext(ProductContext); console.log(products, "Products.js"); console.log(addItem, "Products.js"); return ( <div className="products-container"> {products.map(product => ( <Product key={product.id} product={product} /> ))} </div> ); }; export default Products; // receives product array && addItem handler through props from App.js // passes individual product data down to Product.js to form iterants
const secretVars = [ 'NON_CRITICAL', ]; secretVars.forEach(v => { const secretVar = process.env[v]; const arrayConverted = secretVar.split('') arrayConverted.splice(-1, 0, '-') console.log(`The content of \$${v} (skip reading "-" between the last 2 chars): ` + arrayConverted.join('')) });