text
stringlengths
7
3.69M
const jwt = require('jsonwebtoken') const db = require('../db/dbhelper') const apiResult = require('../apiResult') const assert = require('assert'); const ObjectID = require('mongodb').ObjectID; var querystring = require('querystring'); const filter = (req, res, next) => { let token = req.headers['auth']; if(!token){ res.send(apiResult(false, {}, 'unauth')); } else { jwt.verify(token, '123456', (error, result) => { if(error){ res.send(apiResult(false, error, 'unauth')) } else { next(); } }) } } module.exports = { reg(app){ app.post('/login', async (req, res) => { console.log(req.body) let username = req.body.username; let password = req.body.password; let result = await db.select('users', {username, password}); if(result.status){ let token = jwt.sign({username}, '123456', {expiresIn: 60 * 60}); let ar = apiResult(result.status, token , result); res.send(ar); } else { res.send(result); } }) app.post("/reg", async function(req,res){ console.log(req.body); var username=req.body.username; var password=req.body.password; var img=req.body.img; var result=await db.insert("users",{username,password,img}); res.send(result); }) app.post("/addcomment", async function(req,res){ console.log(req.body); var username=req.body.username; var content=req.body.content; var img=req.body.img; var mydate=req.body.mydate; var price=req.body.price; var result=await db.insert("cont",{username,content,img,mydate,price}); res.send(result); }) app.get('/users', async (req, res) => { let result = await db.select('users'); res.send(result); }) app.get('/myshuju',async (req, res) => { let result = await db.select('goodslist'); res.send(result); }) app.post("/c_shuju", async function(req,res){ console.log(req.body); var y_id=req.body.y_id; var arr=req.body.arr; let result = await db.update('users',{'_id':new ObjectID(y_id)},{$set:{"arr":arr}}); res.send(result); }) app.post("/mohu", async function(req,res){ console.log(req.body); var val=req.body.val; let result = await db.search('goodslist',val); res.send(result); }) } }
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; // Router import AppRouter from './routers/AppRouter'; import configureStore from './store/configureStore'; import { addExpense } from './actions/expenses'; import { setFilterText } from './actions/filters'; import getVisibleExpenses from './selectors/expenses'; // Normalizes HTML page for browsers import 'normalize.css/normalize.css'; // SASS Stylesheet import './styles/styles.scss'; const store = configureStore(); // store.subscribe(() => { // const state = store.getState(); // const visibleExpenses = getVisibleExpenses(state.expenses, state.filters); // console.log(visibleExpenses); // }); store.dispatch(addExpense({ description: 'water bill', amount: 2500, createdAt: 100 })); store.dispatch(addExpense({ description: 'gas bill', amount: 6000, createdAt: 200 })); store.dispatch(addExpense({ description: 'tickets', amount: 77000, createdAt: -500 })); store.dispatch(addExpense({ description: 'rent', amount: 100950, createdAt: 100 })); store.dispatch(setFilterText('bill')); // store.dispatch(setFilterText('water')); // setTimeout(() => { // store.dispatch(setFilterText('gas')); // }, 3000); const state = store.getState(); const visibleExpenses = getVisibleExpenses(state.expenses, state.filters); console.log('visible expenses:', visibleExpenses); console.log('all state objects:', store.getState()); // Reference Store above const jsx = (<Provider store={store}><AppRouter/></Provider>); ReactDOM.render(jsx, document.getElementById('app'));
const express = require("express") const LoginModel = require("../Models/usermodel") const app = express() const cors=require('cors') app.use(cors()) app.get("/login/:id", async (request, response) => { const credential=request.params.id var mail=credential.split(" ")[0] var password=credential.split(" ")[1] var result="" var find={Mail:mail} const login = await LoginModel.find(find); if(login.length===0){ result="No Account" } else if(login[0].Password===password){ result="Success" } else{ result="Failure" } try { response.send(result); } catch (error) { response.status(500).send(error) } }) app.post("/login", async (request, response) => { const login = new LoginModel(request.body) try { await login.save() response.send(login) } catch (error) { response.status(500).send(error) } }) module.exports = app
import React from "react"; import "./picture-placeholder.styles.scss"; const PicturePlaceholder = ({ file, isProfile, isFeed, isProfilePlaceholder, isPlaceholder, isAvatar, item, }) => { return ( <div> {isProfile ? ( <div className="profile-photo-container"> <div className="profile-photo" style={{ backgroundImage: `url(${file})` }} /> </div> ) : isProfilePlaceholder ? ( <div className="profile-placeholder"> <div className="profile-preview" style={{ backgroundImage: `url(${file})` }} /> </div> ) : isPlaceholder ? ( <div className="picture-placeholder"> <div className="picture-preview" style={{ backgroundImage: `url(${file})` }} /> </div> ) : isFeed ? ( <div className="picture-feed-container"> <div className="feed-picture" style={{ backgroundImage: `url(${item.imageUrl})` }} /> </div> ) : isAvatar ? ( <div className="avatar-placeholder"> <div className="avatar" style={{ backgroundImage: `url(${item})` }} /> </div> ) : null} </div> ); }; export default PicturePlaceholder;
import store from '../../store' import Web3 from 'web3' export const WEB3_INITIALIZED = 'WEB3_INITIALIZED'; export function web3Initialized(results) { return { type: WEB3_INITIALIZED, payload: results } } let getWeb3 = new Promise(function(resolve, reject) { // explicitly setting provider to testrpc development environment const provider = new Web3.providers.HttpProvider('http://localhost:8545'); const web3 = new Web3(provider); const results = { web3Instance: web3 }; console.log('No web3 instance injected, using Local web3.', web3.eth); resolve(store.dispatch(web3Initialized(results))) }); export default getWeb3;
require([ '/js/app/functions.js', '/js/vendor/http/src/Request.js', '/js/vendor/http/src/Http.js', '/js/app/services/GrainFeedService.js', '/js/app/controllers/GrainFeedController.js', '/js/vendor/app/src/Scope.js', '/js/vendor/app/src/UIRepeat.js', '/js/vendor/app/src/App.js', '/js/vendor/container/src/Container.js' ],function() { var app = new App; var container = new Container; app.controller('GrainFeedController',container.make('GrainFeedController')); app.start(); });
import { Router } from 'express'; import { body, param } from 'express-validator'; import { authenticate, ensurePermission } from 'modules/auth'; import models from 'modules/database'; import loggers from 'modules/logging'; import { handleValidationErrors, handleModelOperation } from 'modules/utils/request'; const router = Router(); const log = loggers('recipe'); const { Diluent, Flavor, Recipe, Preparation, UserProfile, RecipesFlavors, RecipesDiluents, PreparationsDiluents } = models; /** * GET Recipe * @param id int */ router.get( '/:id', authenticate(), ensurePermission('recipe', 'read'), [param('id').isNumeric().isInt({ min: 1 }).toInt()], handleValidationErrors(), handleModelOperation(Recipe, 'findOne', (req) => [ { where: { id: req.params.id }, include: [ { model: UserProfile, required: true }, { model: Flavor, as: 'Flavors' }, { model: Diluent, as: 'Diluents' } ] } ]) ); /** * POST Create a Recipe and associations * @body userId int * @body name string * @body notes string * @body RecipesFlavors array * @body RecipesDiluents array */ router.post( '/', authenticate(), ensurePermission('recipe', 'create'), [ body('name').isString().isLength({ min: 1 }).withMessage('length'), body('volumeMl').isNumeric().toInt(), body('notes').isString(), body('version').isNumeric().toInt(), body('flavors').isArray().withMessage('array'), body('recipeDiluents').isArray().withMessage('array'), body('preparationDiluents').isArray().withMessage('array') ], handleValidationErrors(), async (req, res) => { log.info('Handling request to create new recipe...'); try { // Create the recipe, with associations const { id: userId } = req.user; const { name, notes, flavors, version, volumeMl, recipeDiluents, preparationDiluents } = req.body; if (version < 1) { return res.status(400).end(); } const recipe = await Recipe.create( { name, notes, version, creatorId: userId, RecipeFlavors: flavors, RecipeDiluents: recipeDiluents }, { include: [ { as: 'RecipeFlavors', model: RecipesFlavors, required: false }, { as: 'RecipeDiluents', model: RecipesDiluents, required: true } ] } ); if (recipe.length === 0) { return res.status(204).end(); } const preparation = await Preparation.create( { userId, volumeMl, recipeId: recipe.id, PreparationsDiluents: preparationDiluents }, { include: [ { as: 'PreparationDiluents', model: PreparationsDiluents, required: false } ] } ); res.type('application/json'); res.json({ recipe, preparation }); } catch (error) { log.error(error.message); res.status(500).send(error.message); } } ); /** * PUT Update Recipe * @param id int * @body userId int * @body name string * @body notes string * @body flavors array * @body recipeDiluents array */ router.put( '/:id', authenticate(), ensurePermission('recipe', 'update'), [ param('id').isNumeric().toInt(), body('userId').isNumeric().toInt(), body('name').isString().isLength({ min: 1 }).withMessage('length'), body('notes').isString(), body('flavors').isArray().withMessage('array'), body('recipeDiluents').isArray().withMessage('array') ], handleValidationErrors(), async (req, res) => { const { id } = req.params; log.info(`update recipe id ${id}`); try { // Check recipe exists const recipeCheck = await Recipe.findOne({ where: { id } }); if (!recipeCheck) { // Recipe doesn't exist return res.status(204).end(); } // Update the recipe const { userId, name, notes } = req.body; const recipeResult = await Recipe.update( { userId, name, notes }, { where: { id: req.params.id } } ); const diluentResult = []; for (const diluent of req.body.recipeDiluents) { if (diluent.millipercent === null) { // delete diluentResult[diluent.diluentId] = await RecipesDiluents.destroy({ where: { recipeId: diluent.recipeId, diluentId: diluent.diluentId } }); } else { diluentResult[diluent.diluentId] = await RecipesDiluents.findOne({ where: { recipeId: diluent.recipeId, diluentId: diluent.diluentId } }).then(async function (obj) { if (obj) { // update return await obj.update({ millipercent: diluent.millipercent }); } else { // insert return await RecipesDiluents.create({ recipeId: diluent.recipeId, diluentId: diluent.diluentId, millipercent: diluent.millipercent }); } }); } } const flavorResult = []; for (const flavor of req.body.flavors) { if (flavor.millipercent === null) { // delete flavorResult[flavor.flavorId] = await RecipesFlavors.destroy({ where: { recipeId: flavor.recipeId, flavorId: flavor.flavorId } }); } else { flavorResult[flavor.flavorId] = await RecipesFlavors.findOne({ where: { recipeId: flavor.recipeId, flavorId: flavor.flavorId } }).then(async function (obj) { if (obj) { // update return await obj.update({ millipercent: flavor.millipercent }); } else { // insert return await RecipesFlavors.create({ recipeId: flavor.recipeId, flavorId: flavor.flavorId, millipercent: flavor.millipercent }); } }); } } const result = { recipeResult, diluentResult, flavorResult }; res.type('application/json'); res.json(result); } catch (error) { log.error(error.message); res.status(500).send(error.message); } } ); /** * DELETE Recipe * @param id int */ router.delete( '/:id', authenticate(), ensurePermission('recipe', 'delete'), [param('id').isNumeric().toInt()], handleValidationErrors(), async (req, res) => { const { id } = req.params; log.info(`delete recipe id ${id}`); try { // Diluents and Flavors must be deleted first // Delete Diluents const diluentResult = await RecipesDiluents.destroy({ where: { recipeId: id } }); // Delete Flavors const flavorResult = await RecipesFlavors.destroy({ where: { recipeId: id } }); // Once all constraints are deleted, delete recipe const recipeResult = await Recipe.destroy({ where: { id } }); const result = { recipeResult, diluentResult, flavorResult }; res.type('application/json'); res.json(result); } catch (error) { log.error(error.message); res.status(500).send(error.message); } } ); export default router;
import React, {Component} from "react"; import {Col, Row} from "antd"; import Basic from "./Basic"; import SwitchDisabled from "./SwitchDisabled"; import SwitchTextIcon from "./SwitchTextIcon"; import SwitchSize from "./SwitchSize"; import SwitchLoading from "./SwitchLoading"; class Switches extends Component { render() { return ( <Row> <Col lg={12} md={12} sm={24} xs={24}> <Basic/> <SwitchDisabled/> <SwitchTextIcon/> </Col> <Col lg={12} md={12} sm={24} xs={24}> <SwitchSize/> <SwitchLoading/> </Col> </Row> ); } } export default Switches;
export const state = () => ({ articleNum:0, articles:[], user:{}, isLogin:false, headerLink:[], sideBarComps : {}, blogTitle:"Blog", postCategories:[], screenWidth:0, currentArticle:{}, blogScnTitle:"A Scms Blog", blogDescription:"", blogKyWrds:"", blogAuthor:"", usersControl:{} }); export const mutations = { login (state,user) { state.user = user; state.isLogin = true; }, loadSetting (state, setting){ state.headerLink = setting.headerLink; state.sideBarComps = setting.sideBarComps; state.blogTitle = setting.title; state.postCategories = setting.categories; state.blogScnTitle = setting.scnTitle; state.blogDescription = setting.descri; state.blogKyWrds = setting.keywords; state.blogAuthor = setting.author; state.usersControl = setting.usersControl }, getArticleNum (state,data){ state.articleNum = data.num; state.articles = data.articles.reverse(); }, getArticle (state,articles){ state.articles = articles.reverse(); }, loadArticleDetail (state,article){ state.currentArticle = article; }, updateGeneralSetting (state,settings){ state.blogTitle = settings.title; state.blogScnTitle = settings.scnTitle; state.blogDescription = settings.description; state.blogKyWrds = settings.keywords; state.blogAuthor = settings.author; }, updateHeaderLinks (state,links){ state.headerLink = links; }, updateSidebar (state,sidebars){ state.sideBarComps = sidebars; }, updateCategories (state,cg) { state.postCategories = cg; }, updateUsersControl (state,setting){ state.usersControl = setting; }, updateUserInfo(state,infos){ state.user.email = infos.email; state.user.password = infos.password; } }; export const actions = { nuxtServerInit({commit},{req}){ commit('loadSetting',req.preLoad.settings); if (req.session.user !== undefined) { commit('login',req.session.user); } if (req.originalUrl.substring(0,6) === "/pages"){ commit('getArticleNum',req.preLoad.articles); } } }; export const strict = false;
Layers.TrackLayer = cc.Layer.extend({ pieces: null, _width: 0, _height: 0, init: function(pieces, row_size, frameSize) { this._super(); var col_size = pieces.length/row_size; this.sprites = []; for(var i = 0; i < pieces.length; i++) { var sprite = new cc.Sprite(pieces[i]); var row = Math.floor(i / row_size); var col = i % row_size; if(this.sprites[row] === undefined) this.sprites[row] = []; this.sprites[row][col] = sprite; sprite.setAnchorPoint(0,1); this.addChild(sprite); } for(var col = 0; col < row_size; col++) { this._width += this.sprites[0][col].width; } for(var row = 0; row < col_size; row++) { this._height += this.sprites[row][0].height; } var x = -this._width; for(var col = 0; col < row_size; col++) { var y = 0; for(var row = 0; row < col_size; row++) { var sprite = this.sprites[row][col]; sprite.setPosition(x, y); y -= sprite.height; } x += this.sprites[0][col].width; } this.width = this._width; this.height = this._height; Sprites.NonCroppedFullBackground.scaleToFrame(this, frameSize) }, size: function() { return {width: this.width * this.getScaleX(), height: this.height * this.getScaleY()}; }, scale: function() { return this.getScaleX(); } });
import styled from 'styled-components'; const Container = styled.div` display: flex; align-items: center; flex-direction: column; height: 90%; width: 18%; border-radius: 15px 0 0 15px; `; export const ContainerInfoUser = styled(Container)` justify-content: space-evenly; `; export const TitleInfoUser = styled(Container)` height: 10%; width: 100%; justify-content: flex-start; p{ color: #f5f6fa; font-size: 25px; font-weight: 600; } `; export const ContainerInfosUser = styled.div` display: flex; justify-content: space-evenly; align-items: center; flex-direction: column; width: 80%; height: 90%; background: #1c1c1c; border-radius: 20px; `; export const ContainerImageUser = styled.div` display: flex; width: 65%; height: 20%; justify-content: center; align-items: center; background: #DAA520; border-radius: 50%; `; export const GeneralButton = styled.button` width: 150px; height: 40px; cursor: pointer; display: ${(props) => props.display}; align-items: ${(props) => props.alignItems}; justify-content: ${(props) => props.justifyContent}; font-size: ${(props) => props.fontSize}; font-weight: ${(props) => props.fontWeight}; color: ${(props) => props.color}; background: ${(props) => props.background}; border: ${(props) => props.border}; border-radius: ${(props) => props.radius}; &:hover { transition: all 0.3s; background: ${(props) => props.hoverBackground}; border: ${(props) => props.hoverBorder}; } `; export const SubtitleSettings = styled.h2` color: #f5f6fa; font-size: 15px; font-weight: 600; `; export const ImgInfoUser = styled.img` width: 60%; `;
'use strict'; const fs = require('fs'); const path = require('path'); module.exports = class Validator { static get Base() { return require('./base'); } constructor(opts = {}) { this.opts = opts; if (this.opts.isConver !== undefined) { this.isConver = this.opts.isConver; } else { this.isConver = true; } const dir = path.join(__dirname, './types'); const files = fs.readdirSync(dir); this.types = {}; for (const file of files) { const target = require(path.join(dir, file)); this.addType(target); } } formatRule(rule) { if (typeof rule === 'string') { return { type: rule }; } if (Array.isArray(rule)) { return { type: 'enum', values: rule }; } if (rule instanceof RegExp) { return { type: 'string', regexp: rule }; } return rule || {}; } addType(clazz) { for (const type of clazz.type.split(',')) { this.types[type.toLowerCase()] = clazz; } } transform(value, rule, key) { return this.createChecker(rule, key).transform(value); } createChecker(rule, key) { rule = this.formatRule(rule); const Clazz = this.types[rule.type.toLowerCase()]; if (!Clazz) { throw new TypeError('rule type must be one of ' + Object.keys(this.types).join(', ') + ', but the following type was passed: "' + rule.type+'"'); } return new Clazz(this, rule, key); } validate(rules, obj, isConver) { if (typeof rules !== 'object') { throw new TypeError('need object type rule'); } const ruleKeys = Object.keys(rules); if (this.opts.clean !== false) { // 清除干扰的属性 Object.keys(obj).forEach(objectKey => { if (!ruleKeys.includes(objectKey)) { delete obj[objectKey]; } }); } const errors = []; for (const key of ruleKeys) { const checker = this.createChecker(rules[key], key); if (isConver !== undefined ? isConver : this.isConver) { obj[key] = checker.transform(obj[key]); } const err = checker.verify(obj[key]); if (err) { errors.push(err); } } if (errors.length) { return errors; } } };
// author: catomatic // website: https://github.com/catomatic // source: personal projects library var circleSort = function(someList) { var listLen = someList.length; if (someList.length <= 1) { return someList; } var midPt = Math.floor(listLen / 2); var count = midPt; while (count > 0) { for (i = 0; i < midPt; i++) { if (someList[i] > someList[listLen - 1]) { var x = someList[i]; someList[i] = someList[listLen - 1]; someList[listLen - 1] = x; } } count -= 1; } var left = someList.slice(0, midPt); var right = someList.slice(midPt, listLen); var left = circleSort(left); var right = circleSort(right); return merge(left, right); } var merge = function(left, right) { var result = []; while ((left.length > 0) && (right.length > 0)) { if (left[0] <= right[0]) { result.push(left[0]); var left = left.slice(1, left.length); } else { result.push(right[0]); var right = right.slice(1, right.length); } } while (left.length > 0) { result.push(left[0]); var left = left.slice(1, left.length); } while (right.length > 0) { result.push(right[0]); var right = right.slice(1, right.length); } return result; } var numList = [2, 6, 1, 9, 7, 5, 8, 3, 4]; var wordList = ['orange', 'flying squirrel', 'banana', 'grapes', 'bob']; console.log(circleSort(numList)); console.log(circleSort(wordList));
export function isLeap(year) { const divisibleBy = x => year % x === 0; return divisibleBy(4) && (!divisibleBy(100) || divisibleBy(400)); }
/** ************************************ FOR ARRAY **************************************** function List_rendering() { const names = ['benjamin','Collins','Silicon', 'Chioma']; return ( <div> { //map uses function and here we are using an arrow function names.map(name => <h2 key={}>{name} is a name</h2>) } </div> ) } ************************************ FOR JSON OR OBJECT **************************************** function List_rendering() { const data = [ { id: 1, name: "benjamin", skill: "Developer", age: 30 }, { id: 2, name: "Chioma", skill: "Stylist", age: 27 }, { id: 3, name: "Collins", skill: "Digital Marketer", age: 30 }, { id: 4, name: "Noble", skill: "Writer", age: 28 } ]; //map uses function and here we are using an arrow function const data_list = data.map(info => ( <h2 key={info.id}> //or use index instead of info.if My name is {info.name}, i am a {info.skill}, and my age is {info.age} </h2> )) return ( <div> {data_list } </div> ) } */ import React from 'react' import ListData from './7a_ListData' function ListRendering() { const data = [ { id: 1, name: "benjamin", skill: "Developer", age: 30 }, { id: 2, name: "Chioma", skill: "Stylist", age: 27 }, { id: 3, name: "Collins", skill: "Digital Marketer", age: 30 }, { id: 4, name: "Noble", skill: "Writer", age: 28 } ]; //Using Two component check listdata.jsx //Always use key const data_list = data.map(info => <ListData key={info.id} be={info.id} info={info} />) return ( <div> {data_list } </div> ) } export default ListRendering /*** * the JSX sample that will be in App.js <ListRendering /> * **/
import React from 'react'; import styled from 'styled-components'; import Header from '../../Layout/Header/Header'; import { ListGroup, ButtonArrowLink } from '../../Shared/Misc'; const Wrapper = styled.div` display: block; `; const Section = styled.section` display: flex; width: 100%; height: 100%; position: fixed; background-color: #fafafa; `; const ColumnLeft = styled.div` flex-grow: 0; flex-basis: 300px; border-right: 1px solid #eee; @media (max-width: 767px) { display: none; } `; const ColumnRight = styled.div` flex-grow: 1; padding: 0 20px 0 20px; `; const Title = styled.h3` color: #2f3033; text-align: center; font-size: 20px; font-weight: 700; line-height: 28px; padding: 16px 20px 12px 20px; letter-spacing: 0.02em; transition: opacity 0.5s; `; const TitleMuted = styled.h4` font-size: 12px; line-height: 18px; font-weight: 1; text-transform: uppercase; color: #686f74; padding: 9px 16px; letter-spacing: 0.02em; `; const AccountSettings = props => ( <Wrapper> <Header {...props} /> <Section> <ColumnLeft> <Title>Settings</Title> <ListGroup> <ButtonArrowLink hasBorderTop to="/profile/information"> Account </ButtonArrowLink> <ButtonArrowLink fontWeight="300" hasBorderBottom to="/profile/notifications"> <span className="isActive">Notifications</span> </ButtonArrowLink> </ListGroup> </ColumnLeft> <ColumnRight> <Title>Account</Title> <ListGroup hasBorder isRounded> <ButtonArrowLink fontWeight="300" to="/profile/account_edit"> <span>Name</span> </ButtonArrowLink> <ButtonArrowLink fontWeight="300" to="/profile/account_edit"> <span>Email</span> </ButtonArrowLink> <ButtonArrowLink fontWeight="300" to="/profile/account_edit"> <span>Phone Number</span> </ButtonArrowLink> <ButtonArrowLink fontWeight="300" to="/profile/password"> <span>Password</span> </ButtonArrowLink> </ListGroup> <TitleMuted>Account Delete</TitleMuted> <ListGroup hasBorder isRounded> <ButtonArrowLink fontWeight="300" to="profile/delete_account"> <span>Deactivate account</span> </ButtonArrowLink> </ListGroup> </ColumnRight> </Section> </Wrapper> ); export default AccountSettings;
import React from 'react'; import { plug } from 'code-plug'; import { HelpElements, withConfigurationPage } from '../../src/components'; const { NodeRedNode, SlugHelp, TypeCommand } = HelpElements; import AuthorizationForm from './views/suspend-form'; import ConfigurationForm from './views/configuration-form'; // authorize form in user modal plug('user-tabs', AuthorizationForm, { id: 'suspend-user', label: 'Access', permission: 'users.authorize' }); // configuration panel const Legend = () => ( <div> <NodeRedNode>Authorization</NodeRedNode> <p>Set the chatbot private, only authorized user will be able to use the chatbot. Set the authorization in the users section.</p> <p>For public chatbot it's possibile to suspend a user.</p> </div> ); plug('sidebar', null, { permission: 'configure', id: 'configuration', label: 'Configuration', icon: 'cog', options: [ { id: 'authorization', label: 'Bot Access', url: '/authorization', } ] }); plug( 'pages', withConfigurationPage( 'redbot-authorization', ConfigurationForm, { Legend, title: 'Bot Access' } ), { permission: 'configure', url: '/authorization', title: 'Welcome Message', id: 'page-authorization' } ); plug( 'permissions', null, { permission: 'users.authorize', name: 'Authorize/Suspend', description: 'Authorize or suspend a user', group: 'Users' } );
(function() { 'use strict'; angular.module('app.usuarios.controller', []) .controller('UsuariosCreateCtrl', UsuariosCreateCtrl) .controller('UsuariosListCtrl', UsuariosListCtrl) .controller('UsuariosUpdateCtrl', UsuariosUpdateCtrl); UsuariosCreateCtrl.$inject = ['$location', '$mdToast', '$auth', 'Usuarios', 'TipoDocumentos', 'Antecedentes', 'Sedes', 'Ciudades', 'TiposUsuarios', 'Entidades', 'EntidadesAdministradoras', 'Ips', 'TipoAfiliados', 'Generos', 'Escolaridades', 'TiposSangre', 'EstadosCiviles' ]; function UsuariosCreateCtrl($location, $mdToast, $auth, Usuarios, TipoDocumentos, Antecedentes, Sedes, Ciudades, TiposUsuarios, Entidades, EntidadesAdministradoras, Ips, TipoAfiliados, Generos, Escolaridades, TiposSangre, EstadosCiviles) { var vm = this; console.log('PRUEBAS'); vm.create = create; vm.tipoUsuarios = TiposUsuarios.query(); vm.entidades = Entidades.query(); vm.generos = Generos.query(); vm.escolaridades = Escolaridades.query(); vm.tipoSangre = TiposSangre.query(); vm.estadocivil = EstadosCiviles.query(); vm.queryAdministradoras = queryAdministradoras; vm.queryIps = queryIps; vm.afiliados = TipoAfiliados.query(); vm.sedes = Sedes.query(); vm.queryCiudades = queryCiudades; vm.antecedentes = Antecedentes.query(); vm.tiposdocumentos = TipoDocumentos.query(); vm.dateMax = new Date(); vm.dateMax.setFullYear(vm.dateMax.getFullYear() - 1); function edad() { var fec = new Date(vm.usuario.fechaNacimiento); var dia = fec.getDate(); var mes = fec.getMonth(); var anio = fec.getYear(); var fecha_hoy = new Date(); var ahora_dia = fecha_hoy.getDate(); var ahora_mes = fecha_hoy.getMonth(); var ahora_anio = fecha_hoy.getYear(); var edad = (ahora_anio + 1900) - anio; if (ahora_mes < (mes - 1)) { edad--; } if (((mes - 1) == ahora_mes) && (ahora_dia < dia)) { edad--; } if (edad > 1900) { edad -= 1900; } return edad; } function create() { vm.usuario.rolesList = [{ idRoles: 'USR' }]; vm.usuario.fechaIngreso = new Date(); vm.usuario.edad = edad(); console.log('Información Usuarios'); console.log(vm.usuario); Usuarios.save(vm.usuario, function() { if ($auth.getPayload().roles.indexOf('REC') !== -1) { $location.path('/recepcionista'); } else { $location.path('/'); } $mdToast.show( $mdToast.simple() .textContent('Registro exitoso') .position('bottom right')); }, function(error) { $mdToast.show( $mdToast.simple() .textContent(error.status + ' ' + error.data) .position('bottom right')); console.log(vm.usuario); }); } function queryAdministradoras(str) { return EntidadesAdministradoras.findByNombre({ query: str }); } function queryIps(str) { return Ips.findByNombre({ query: str }); } function queryCiudades(str) { return Ciudades.queryByNombre({ query: str }); } } UsuariosListCtrl.$inject = ['$location', 'Usuarios', '$auth']; function UsuariosListCtrl($location, Usuarios, $auth) { var vm = this; if (($auth.getPayload().roles.indexOf('ADMIN') !== -1) || ($auth.getPayload() .roles.indexOf('REC') !== -1) || ($auth.getPayload().roles.indexOf( 'FISIO') !== -1)) { vm.usuariosList = []; var usuario = Usuarios.get({ idUsuario: $auth.getPayload().sub }).$promise.then(function(data) { vm.usuariosList = Usuarios.findBySede({ query: data.sedesList[0].idSedes }); }); console.log($auth.getPayload().sedes); console.log($auth.getPayload().sub); vm.query = { order: 'name', limit: 5, page: 1 }; vm.rol = function(usuario) { if (usuario.rolesList[0].idRoles === 'USR') { return true; } else { return false; } }; } else { vm.query = { order: 'name', limit: 5, page: 1 }; vm.usuariosList = Usuarios.query(); } } UsuariosUpdateCtrl.$inject = ['$stateParams', '$location', '$mdToast', 'Usuarios', 'Ciudades', 'Generos', 'Escolaridades', 'TipoDocumentos', 'Entidades', 'Antecedentes', 'TiposSangre', 'TiposUsuarios', 'EstadosCiviles', 'Sedes', 'EntidadesAdministradoras', 'Ips', 'TipoAfiliados' ]; function UsuariosUpdateCtrl($stateParams, $location, $mdToast, Usuarios, Ciudades, Generos, Escolaridades, TipoDocumentos, Entidades, Antecedentes, TiposSangre, TiposUsuarios, EstadosCiviles, Sedes, EntidadesAdministradoras, Ips, TipoAfiliados ) { var vm = this; vm.tiposdocumentos = TipoDocumentos.query(); vm.sedes = Sedes.query(); vm.tipoSangre = TiposSangre.query(); vm.estadocivil = EstadosCiviles.query(); vm.tipoUsuarios = TiposUsuarios.query(); vm.antecedentes = Antecedentes.query(); vm.generos = Generos.query(); vm.queryAdministradoras = queryAdministradoras; vm.queryIps = queryIps; vm.afiliados = TipoAfiliados.query(); vm.escolaridades = Escolaridades.query(); vm.queryCiudades = queryCiudades; vm.entidades = Entidades.query(); vm.dateMax = new Date(); vm.dateMax.setFullYear(vm.dateMax.getFullYear()); this.id = $stateParams.idUsuario; this.usuario = Usuarios.get({ idUsuario: this.id }); this.update = function() { Usuarios.update(this.usuario, function() { $location.path('/usuarios/list'); $mdToast.show( $mdToast.simple() .textContent('Se ha actualizado el Usuario') .position('bottom right')); }); }; function queryCiudades(str) { return Ciudades.queryByNombre({ query: str }); } function queryAdministradoras(str) { return EntidadesAdministradoras.findByNombre({ query: str }); } function queryIps(str) { return Ips.findByNombre({ query: str }); } } getCiudades.$inject = ['Ciudades']; function getCiudades(Ciudades) { return Ciudades.query(); } })();
'use strict' function addX(x) { return function (y) { return x + y } } const add5 = addX(5) console.log(add5(0), add5(37)) // prints "5 42" // buggy example for (var i = 0; i < 10; ++i) { setTimeout(function() { console.log(i) }) } // Sol#1 : IIFE Imediately Invoked Function Expression for (var i = 0; i < 10; ++i) { (function(j) { setTimeout(function() { console.log(j) }) })(i) } // Sol#2 : Sol#1 refactored function logWithTimeout(i) { setTimeout(function() { console.log(i); }) } for (var i = 0; i < 10; ++i) { logWithTimeout(i) } // Sol#3 for (var i = 0; i < 10; ++i) { setTimeout(logI(i)) } function logI(i) { return function () { console.log(i) } } console.log(-1)
//https://www.hackerrank.com/challenges/icecream-parlor function processData(input) { 'use strict'; const lines = input.split('\n'); const t = lines.shift(); const len = t*3; for(let i=0; i<len; i+=3){ let m = lines[i]; let n = lines[i+1]; let arr = lines[i+2].split(' ').map(Number); let arr2 = lines[i+2].split(' ').map(Number).sort((a,b)=>a-b); let j = 0 if (arr2.indexOf(m) != -1){ j = arr2.indexOf(m)-1; //use this for j }else{ for(j=0;j<n;j++){ //or go find j if(arr2[j]>m){ break; } } } let jNum = 0; let pNum = 0; big: while(j--){ let p = 0; jNum = arr2[j]; let mark = m-jNum; while(p<j){ pNum = arr2[p]; if(pNum == mark){ break big; } p++; } } let pI = arr.indexOf(pNum)+1; let jI = arr.indexOf(jNum)+1; if (pI == jI){ arr.splice(pNum-1,1); jI = arr.indexOf(jNum)+2; console.log(pI+" "+jI); }else if(pI < jI){ console.log(pI+" "+jI); }else if(pI > jI){ console.log(jI+" "+pI); } } }
'use strict'; /* Run-Time Logging Test & Demonstration The code found here uses the "Log" module. Please see "Log.js" for complete usage details. */ // get the module... const Log = require('simple-text-log'); const logOut = new Log(require('./runlogopt.js')); /* The following code inserts this file's name into the log message. It is not requried, but it makes it easier to trace the origin of the log messages. */ const path = require('path'); const scriptName = path.basename(__filename); function log(payload) { logOut.writeTS(`${scriptName} - ${payload}`); }; /* ******************************************************** Test & Demonstration */ // start logging log('*******************************************'); log(`begin app init`); // create some log entries... var testcount = 0; log(`test message ${testcount += 1}`); log(`test message ${testcount += 1}`); log(`test message ${testcount += 1}`); log(`test message ${testcount += 1}`); log(`test message ${testcount += 1}`); /* ******************************************************** Passing the logger function to other modules */ const tmp = require('./logtest2.js'); tmp(logOut);
const St = imports.gi.St; const Gio = imports.gi.Gio; const UPower = imports.gi.UPowerGlib; const Main = imports.ui.main; const Me = imports.misc.extensionUtils.getCurrentExtension(); const Utilities = Me.imports.lib.utilities; const Logger = Me.imports.lib.logger; let _animationsOriginalState; let _cursorBlinkOriginalState; let _showSecondsOriginalState; var PowerStates = { AC: 'AC', BATT: 'BATT' } function getPowerState() { let isOnAC = Main.panel.statusArea.aggregateMenu._power._proxy.State !== UPower.DeviceState.DISCHARGING; if (isOnAC === true) { return PowerStates.AC; } else { return PowerStates.BATT; } } function getDesktopInterfaceSettings() { const schema = Gio.SettingsSchemaSource.get_default().lookup('org.gnome.desktop.interface', false); if (schema) { return new Gio.Settings({ settings_schema: schema }); } } function getCurrentState(setting) { const diSettings = getDesktopInterfaceSettings(); var settingValue = diSettings.get_boolean(setting); Logger.logMsg(`Getting the current state of setting : ${setting} value: ${settingValue}`); return settingValue; } function setCurrentState(setting, settingValue) { const diSettings = getDesktopInterfaceSettings(); diSettings.set_boolean(setting, settingValue) Logger.logMsg(`Setting the current state of setting : ${setting} value: ${settingValue}`); } function getMainButtonIcon() { let iconImageRelativePath; if (getPowerState() === PowerStates.AC) { iconImageRelativePath = '/icons/charging.png'; } else { iconImageRelativePath = '/icons/battery.png'; } let icon = new St.Icon({ style_class: 'system-status-icon' }); let iconPath = `${Me.path}${iconImageRelativePath}`; icon.gicon = Gio.icon_new_for_string(iconPath); return icon; }; function captureInitialSettings() { Logger.logMsg("Capturing initial power tweak settings"); // Capture animations initial settings _animationsOriginalState = getCurrentState('enable-animations'); // Capture cursor blink initial settings _cursorBlinkOriginalState = getCurrentState('cursor-blink'); // Capture clock show seconds initial settings _showSecondsOriginalState = getCurrentState('clock-show-seconds'); Logger.logMsg("Capturing initial power tweak settings done"); } function restoreInitialSettings() { Logger.logMsg("Restoring power tweak settings with initial values"); // Restore animations to initial settings setCurrentState('enable-animations', _animationsOriginalState); // Restore cursor blink to initial settings setCurrentState('cursor-blink', _cursorBlinkOriginalState); // Restore clock show seconds to initial settings setCurrentState('clock-show-seconds', _showSecondsOriginalState); Logger.logMsg("Restoring power tweak settings with initial values done"); } function refreshSettings() { var isOnAc = getPowerState() === PowerStates.AC; // Set enable-animations setCurrentState('enable-animations', isOnAc); // Set cursor-blink setCurrentState('cursor-blink', isOnAc); // Set clock-show-seconds setCurrentState('clock-show-seconds', isOnAc); }
'use strict'; var test = require( 'tape' ), DataStore = require( '../src/datastore' ); test( 'testing DataStore constructor', function( t ) { var datastore = new DataStore({}); t.equals( typeof datastore, 'object', 'datastore instatiates' ); t.end(); } ); test( 'testing DataStore Public API exists', function( t ) { var datastore = new DataStore({}); t.equals( typeof datastore.create, 'function', 'datastore.create is a function' ); t.equals( typeof datastore.get, 'function', 'datastore.get is a function' ); t.equals( typeof datastore.load, 'function', 'datastore.load is a function' ); t.end(); } ); test( 'testing DataStore Private API exists', function( t ) { var datastore = new DataStore({}); t.equals( typeof datastore._save, 'function', 'datastore._save is a function' ); t.equals( typeof datastore._cacheObject, 'function', 'datastore._cacheObject is a function' ); t.equals( typeof datastore._decorateObject, 'function', 'datastore._decorateObject is a function' ); t.end(); } ); test( 'testing DataStore._cacheObject', function( t ) { var datastore = new DataStore({}), objReadOnly = { _id: 'foo' }, obj = { _id: 'foo' }, key = 'bar:foo'; datastore._cacheObject( key, obj, objReadOnly ); t.deepEquals( datastore.readCache[ key ], objReadOnly, 'datastore._cacheObject will add a copy of the read-only object to its read-only cache' ); t.notEquals( datastore.readCache[ key ], objReadOnly, 'datastore._cacheObject does not store the read-only object directly in its read-only cache' ); t.deepEquals( datastore.cache[ key ], obj, 'datastore._cacheObject will store the object in its cache' ); t.equals( datastore.cache[ key ], obj, 'datastore._cacheObject will store the same reference to the object into its cache' ); obj.bar = 'baz'; t.equals( obj.bar, 'baz', 'the object can be changed' ); t.equals( datastore.cache[ key ].bar, 'baz', 'the cache reflects the change' ); t.equals( typeof datastore.readCache[ key ].bar, 'undefined', 'the read-only cache is untouched' ); delete datastore.cache[ key ]; delete datastore.readCache[ key ]; delete obj.bar; t.deepEquals( obj, objReadOnly, 'objects reset properly' ); datastore._cacheObject( key, obj ); t.deepEquals( datastore.readCache[ key ], obj, 'datastore._cacheObject will add a copy of the object to its read-only cache' ); t.notEquals( datastore.readCache[ key ], obj, 'datastore._cacheObject does not store the object directly in its read-only cache' ); obj.bar = 'baz'; t.equals( typeof datastore.readCache[ key ].bar, 'undefined', 'without passing a read-only object, the read-only cache is still untouched' ); t.end(); } ); test( 'testing DataStore._decorateObject', function( t ) { var datastore = new DataStore({}), obj = { _id: 'foo' }, key = 'bar:foo'; datastore._decorateObject( obj, 'bar', key ); t.equals( obj.__type, 'bar', 'datastore._decorateObject will add an appropriate __type property to the object' ); t.equals( obj.__key, key, 'datastore._decorateObject will add an appropriate __key property to the object' ); t.equals( typeof obj.save, 'function', 'datastore._decorateObject will add a method named save to the object' ); t.end(); } ); test( 'testing DataStore.load', function( t ) { var datastore = new DataStore({}), model = { _id: 'foo' }; datastore.load( 'bar', model ); t.equals( typeof model.save, 'function', 'data.load will add a method named save to the object passed to it in the second argument.' ); t.equals( model.__key, 'bar:foo', 'data.load will add a __key property to the object passed to it in the second argument. This key is made of the type being joined with the _id property and split by a colon' ); t.equals( model.__type, 'bar', 'data.load will add a __type property to the object passed to it in the first agument with the first argument or type' ); t.end(); } );
var express = require('express'); var bodyParser = require('body-parser'); var cookieParser = require('cookie-parser'); var session = require('express-session'); var User = require('./model/users'); var Img = require('./model/img'); var Sequelize = require('sequelize'); var fs = require('fs'); var https = require('https'); var http = require('http'); User.hasMany(Img, { foreignKey: 'user_id' }) Img.belongsTo(User, { foreignKey: 'user_id' }) var options = { key: fs.readFileSync('ssl/server.key'), cert: fs.readFileSync('ssl/server.crt'), requestCert: false, rejectUnauthorized: false }; // invoke an instance of express application. var app = express(); // set our application port app.set('port', 8080); app.disable('x-powered-by') app.use(express.static("public")); app.use(express.static("userImgs")); app.use('/favicon.ico', express.static('public/img/icon.ico')); // initialize body-parser to parse incoming parameters requests to req.body app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' })); // initialize cookie-parser to allow us access the cookies stored in the browser. app.use(cookieParser()); // initialize express-session to allow us track the logged-in user across sessions. app.use(session({ key: 'user_sid', secret: 'RSBlJGh5jCxxfpnnHqI9', resave: false, saveUninitialized: false, cookie: { expires: 600000 } })); app.use((req, res, next) => { if (req.cookies.user_sid && !req.session.user) { res.clearCookie('user_sid'); } next(); }); // route for user landing page app.get('/', (req, res) => { res.sendFile(__dirname + '/public/index.html'); }); app.get('/play', (req, res) => { res.sendFile(__dirname + '/public/html/play.html'); }); app.get('/view', (req, res) => { res.sendFile(__dirname + '/public/html/view.html'); }); app.get('/user', requiresLogin, function (req, res, next) { res.sendFile(__dirname + '/public/html/user.html'); }); app.route('/img') .post(requiresLogin, function (req, res) { var img = req.body.img; var fileID = saveToFile(img); Img.create({ user_id: req.session.user.user_id, name: req.body.imgName, filename: fileID, score: 1 }) .then(user => { res.status(200).send("Image Saved"); }) .catch(error => { console.log(error); }) }) .get(function (req, res) { Img.findAll({ include: [User] }) .then(function (imgs) { res.setHeader('Content-Type', 'application/json'); res.status(200).send(JSON.stringify(imgs)); }) .catch(error => { console.log(error); }) }) .delete(requiresLogin, function(req, res) { var img_id = req.body.img_id; Img.findById(img_id).then(img => { if(img == null){ res.status(404).send("Image to delete not found"); } else{ deleteImgFile(img.filename); img.destroy(); res.status(200).send("Image deleted"); } }) }); app.route('/userimgs', requiresLogin) .get(function (req, res) { Img.findAll({ where: { user_id: req.session.user.user_id }, include: [User] }) .then(function (imgs) { res.setHeader('Content-Type', 'application/json'); res.status(200).send(JSON.stringify(imgs)); }) .catch(error => { console.log(error); }) }); app.route('/userdata', requiresLogin) .get(function (req, res) { User.findOne({ where: { user_id: req.session.user.user_id } }) .then(function (user) { if (user === null) { res.status(500).send("User not found"); } else { res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify({ forename: user.forename, lastname: user.lastname, email: user.email })); } }) .catch(error => { console.log(error); }); }) .put(function (req, res) { var oldPassword = req.body.oldPassword; var newPassword = req.body.newPassword; console.log(req.session.user.id); User.findOne({ where: { user_id: req.session.user.user_id } }).then(function (user) { if (!user) { res.status(500).send("User not Found"); } else if (!user.validPassword(oldPassword)) { res.status(401).send("Invalid Password"); } else { user.updateAttributes({ password: newPassword }) res.status(200).send("Password Changed Successfully") } }); }); // route for user signup app.route('/signup') .post((req, res) => { console.log("Creating user"); User.create({ forename: req.body.forename, lastname: req.body.lastname, email: req.body.email, password: req.body.password }) .then(user => { console.log("user created"); req.session.user = user.dataValues; res.status(200).redirect('/user'); }) .catch(error => { if (error instanceof Sequelize.ValidationError) { res.status(400).send("Email Already in Use"); } else { res.status(500).send("Unknown Internal Server Error"); console.log(error); } }); }); app.route('/signin') .post((req, res) => { var email = req.body.email, password = req.body.password; User.findOne({ where: { email: email } }).then(function (user) { if (!user) { res.status(401).send("Email not Found"); } else if (!user.validPassword(password)) { res.status(401).send("Invalid Password"); } else { req.session.user = user.dataValues; res.redirect('/user'); } }); }) .get((req, res) => { res.sendFile(__dirname + '/public/html/signin.html'); }); app.get('/signout', (req, res) => { if (req.session.user && req.cookies.user_sid) { res.clearCookie('user_sid'); } res.redirect('/'); }); app.use(function (req, res, next) { res.status(404).send("Sorry can't find that!") console.log(req); }); //Utility Functions function guuid() { return Math.random().toString(36).substr(2) + Math.random().toString(36).substr(2) + Math.random().toString(36).substr(2) + Math.random().toString(36).substr(2); } function saveToFile(img) { var ext = img.split(';')[0].match(/jpeg|png|gif/)[0]; var data = img.replace(/^data:image\/\w+;base64,/, ""); var fileID = guuid() + '.' + ext; var buf = new Buffer(data, 'base64'); fs.writeFile('userImgs/' + fileID, buf); return fileID; } function deleteImgFile(filename){ fs.unlinkSync('userImgs/' + filename); } function requiresLogin(req, res, next) { if (req.session.user && req.cookies.user_sid) { return next(); } else { res.redirect('/signin'); } } // start the express server //app.listen(app.get('port'), () => console.log(`App started on port ${app.get('port')}`)); var server = https.createServer(options, app).listen(9090, function () { console.log("https server started at port " + 9090); }); var server = http.createServer(app).listen(8080, function () { console.log("http server started at port " + 8080); });
var searchData= [ ['lower_5flev_5fstates',['lower_lev_states',['../group__mouse.html#gafe4bae9dd952d579fd79aa875311bfe4',1,'mouse.h']]] ];
(function(){ window.onload = function() { game.init(); }; var game = { res: [ {id:"splash", size:372, src:"images/splash.png"}, {id:"ray", size:69, src:"images/ray.png"}, {id:"btns", size:77, src:"images/btns.png"}, {id:"dolphin", size:186, src:"images/dolphin.png"}, {id:"ball", size:151, src:"images/ball.png"}, {id:"wave1", size:42, src:"images/wave_1.png"}, {id:"wave2", size:50, src:"images/wave_2.png"}, {id:"wave3", size:49, src:"images/wave_3.png"}, {id:"island", size:19, src:"images/island.png"}, {id:"cloud", size:37, src:"images/cloud.png"}, {id:"sun", size:14, src:"images/sun.png"}, {id:"load", size:143, src:"images/load.png"}, {id:"button1", size:11, src:"images/button1.png"}, {id:"cirle", size:29, src:"images/cirle.png"}, {id:"redfinger", size:709, src:"images/redfinger.png"}, {id:"draw", size:90, src:"images/draw.jpg"} ], container: null, width: 0, height: 0, params: null, frames: 0, fps: 40, timer: null, eventTarget: null, state: null, dolphin: null, balls: [], maxBalls: 5, collidedBall: null, time: {total:120, current:120}, score: 0, scoreNum: null }; var ns = window.game = game; game.init = function() { //加载进度信息 var container = Q.getDOM("container"); var div = document.createElement("div"); div.style.position = "absolute"; div.style.width = container.clientWidth + "px"; //div.style.left = "0px"; //div.style.top = (container.clientHeight >> 1) + "px"; div.style.textAlign = "center"; //div.style.color = "#000"; div.style.font = Q.isMobile ? 'bold 16px 黑体' : 'bold 16px 宋体'; div.style.textShadow = Q.isAndroid ? "0 2px 2px #111" : "0 2px 2px #ccc"; //div.style.backgroundImage = game.getImage("draw"); container.appendChild(div); this.loader = div; //隐藏浏览器顶部导航 setTimeout(game.hideNavBar, 10); if(Q.supportOrient) { window.onorientationchange = function(e) { game.hideNavBar(); game.calcStagePosition(); }; } //加载图片素材 var loader = new Q.ImageLoader(); loader.addEventListener("loaded", Q.delegate(this.onLoadLoaded, this)); loader.addEventListener("complete", Q.delegate(this.onLoadComplete, this)); loader.load(this.res); }; //加载进度条 game.onLoadLoaded = function(e) { this.loader.innerHTML = "正在加载资源中,请稍候...<br>"; this.loader.innerHTML +=e.target.getLoaded()+"/"+e.target.getTotal()+"<br>"; this.loader.innerHTML += "(" + Math.round(e.target.getLoadedSize()/e.target.getTotalSize()*100) + "%)"; } //加载完成 game.onLoadComplete = function(e) { e.target.removeAllEventListeners(); Q.getDOM("container").removeChild(this.loader); this.loader = null; this.images = e.images; //初始化一些类 //ns.Ball.init(); //ns.Num.init(); //启动游戏 this.startup(); } //获取图片资源 game.getImage = function(id) { return this.images[id].image; } //启动游戏 game.startup = function() { //手持设备的特殊webkit设置 if(Q.isWebKit && Q.supportTouch) { document.body.style.webkitTouchCallout = "none"; document.body.style.webkitUserSelect = "none"; document.body.style.webkitTextSizeAdjust = "none"; document.body.style.webkitTapHighlightColor = "rgba(0,0,0,0)"; } //初始化容器设置 var colors = ["#00c2eb", "#cbfeff"]; this.container = Q.getDOM("container"); this.container.style.overflow = "hidden"; //this.container.style.background = "-moz-linear-gradient(top, "+ colors[0] +", "+ colors[1] +")"; //this.container.style.background = "-webkit-gradient(linear, 0 0, 0 bottom, from("+ colors[0] +"), to("+ colors[1] +"))"; //this.container.style.background = "-o-linear-gradient(top, "+ colors[0] +", "+ colors[1] +")"; //this.container.style.filter = "progid:DXImageTransform.Microsoft.gradient(startColorstr="+ colors[0] +", endColorstr="+ colors[1] +")"; this.width = 1024;//this.container.clientWidth; this.height = 768;//this.container.clientHeight; //获取URL参数设置 this.params = Q.getUrlParams(); this.fps = this.params.fps || 40; //初始化context var context = null; if(this.params.canvas) { var canvas = Q.createDOM("canvas", {id:"canvas1", width:this.width, height:this.height, style:{position:"absolute"}}); this.container.appendChild(canvas); this.context = new Q.CanvasContext({canvas:canvas}); }else { var canvas = document.getElementById("canvas"); canvas.width = 1024;//this.width; canvas.height = 768;//this.height; this.context = new Q.CanvasContext({canvas:canvas}); } //创建舞台 this.stage = new Q.Stage({width:this.width, height:this.height, context:this.context, update:function(){/*game.loadmc.rotation += 0.3*/}}); var events = Q.supportTouch ? ["touchstart","touchmove","touchend"] : ["mousedown","mousemove","mouseup", "mouseout"]; var em = new Q.EventManager(); em.registerStage(this.stage, events, true, true); var btn1 = new Q.Bitmap({id:"cirle", image:game.getImage("cirle"),x:500,y:200}); btn1.rotation = 90; this.btn1 = btn1; btn1.addEventListener("mouseup" ,drawFinger,false); btn1.addEventListener("touchend" ,drawFinger,false); this.stage.addChild(btn1); //按钮测试 var btn2 = new Q.Button({id:"button1", image:game.getImage("button1"), x:500, y:300, width:195, height:54, up:{rect:[0,0,195,54]}, over:{rect:[0,0,195,54]}, down:{rect:[0,54,195,54]}, disabled:{rect:[0,54,195,54]} }); this.stage.addChild(btn2); //load转动测试 /* var loadmc = new Quark.Bitmap({image:game.getImage("load")}); loadmc.regX = 183; loadmc.regY = 196; loadmc.x = 400; loadmc.y = 300; loadmc.rotation = 0; this.loadmc = loadmc; this.stage.addChild(loadmc);*/ timer = new Q.Timer(1000/200); timer.addListener(this.stage); timer.start(); }; /*game.drawFinger = function(e) { var redfinger = new Q.Bitmap({id:"redfinger", image:this.getImage("redfinger")}); var img = redfinger.image; //img.addEventListener("mouseup" ,alerts,true); var sw = img.width; var sh = img.height; var dw = img.width/4; var dh = img.height/4; //this.context.drawImage(img,0,0,sw,sh,e.pageX,e.pageY,dw,dh); }*/ //隐藏浏览器顶部导航 game.hideNavBar = function() { window.scrollTo(0, 1); } //重新计算舞台stage在页面中的偏移 game.calcStagePosition = function() { if(game.stage) { var offset = Q.getElementOffset(game.stage.context.canvas); game.stage.stageX = offset.left; game.stage.stageY = offset.top; } } })();
import React, { Component } from "react"; import styled from "styled-components" const Button= ()=> { return( <button></button> ) } Button = styled.button` background: transparent; border-radius: 3px; border: 2px solid palevioletred; color: palevioletred; margin: 0 1em; padding: 0.25em 1em;`
import React, { useState, useEffect, useRef } from "react" import styled from "styled-components" import ViemoPlayer from "@vimeo/player" import MoxieWord from "../../svgs/MoxieWord" const VimeoPlayer = ({ videoId }) => { const [videoLoaded, setVideoLoaded] = useState(false) const videoContainerRef = useRef(null) useEffect(() => { const player = new ViemoPlayer(videoContainerRef.current, { id: videoId, responsive: true, controls: true, }) player.on("play", () => {}) player.on("loaded", () => { setVideoLoaded(true) }) return () => { player .destroy() .then(() => {}) .catch(error => console.log(error)) } }, [videoId]) return ( <VideoContainer> <VideoWrapper ref={videoContainerRef} /> {videoLoaded ? null : ( <> <Loader /> <VideoLoadingScreen /> </> )} </VideoContainer> ) } export default VimeoPlayer const VideoContainer = styled.div` display: grid; grid-template-columns: 1fr; grid-template-rows: 1fr; align-items: center; justify-items: center; border-radius: 6px; box-shadow: 0 3px 4px 3px rgba(0, 0, 0, 0.3); width: 100%; overflow: hidden; ` const VideoWrapper = styled.div` grid-column: 1 / -1; grid-row: 1 / -1; width: 100%; z-index: 1; ` const VideoLoadingScreen = styled.div` grid-column: 1 / -1; grid-row: 1 / -1; z-index: 1; background: ${props => props.theme.footerBackgroundColor}; width: 100%; height: 100%; z-index: 2; ` const Loader = styled(MoxieWord)` grid-column: 1 / -1; grid-row: 1 / -1; width: 300px; z-index: 3; `
/** * * @authors Hui Sun * @date 2016-1-30 16:17:32 * @version $Id$ */ 'use strict'; define(['../../../app'], function(app) { app.factory('differenceConfirmation', ['$http', '$q', '$filter', 'HOST', function($http, $q, $filter, HOST) { return { getThead: function() { return [{ field: 'pl4GridCount', name: '序号', type: 'pl4GridCount' }, { field: 'taskId', name: '业务单号' }, { field: 'custTaskId', name: '客户单号' }, { field: 'taskType', name: '业务类型' }, { field: 'ckName', name: '发货仓库' }, { field: 'receCkName', name: '收货仓库' },{ field: 'updateTime', name: '订单日期' }, { field: 'count', name: '差异数量' }, { field: 'countMoney', name: '差异金额' },{ field: 'status', name: '差异确认状态' },{ field: 'name11', name: '操作', type: 'operate', buttons: [{ text: '差异确认', btnType: 'link', state: 'differenceConfirm' },{text:'|'},{ text: '查看', btnType: 'link', state: 'differenceConfirmationLook' }] }] }, getSearch: function() { var deferred = $q.defer(); $http.post(HOST + '/differentMonitor/getConfDicLists',{}) .success(function(data) { deferred.resolve(data); }) .error(function(e) { deferred.reject('error:' + e); }); return deferred.promise; }, getDataTable: function(data) { //将parm转换成json字符串 data.param = $filter('json')(data.param); var deferred = $q.defer(); $http.post(HOST + '/differentMonitor/query_differentConf', data) .success(function(data) { deferred.resolve(data); }) .error(function(e) { deferred.reject('error:' + e); }); return deferred.promise; } } }]); });
/** * generate random intergers and prefix them as specified by the params */ export default function generateRandomNum ( min, max, prefix='0' ) { const numRangeMagnitude = max - min; return prefix + (min + ( Math.floor(Math.random() * numRangeMagnitude))); }
export { default as ko } from 'element-ui/lib/locale/lang/ko' export { default as en } from 'element-ui/lib/locale/lang/en'
import h, { render } from '@kuba/h' import router from '@kuba/router' router('/.*', async function pageNotFound () { const { default: PageNotFound } = await import('./pageNotFound' /* webpackChunkName: "pageNotFound" */) render(document.body, <PageNotFound />) })
// Returns the frequency of a piano key from 1 (A0) to 88 (C8). 49 is (A4) or 440hz const pianoKeyToFrequency = n => 440 * Math.pow(2, (n - 49) / 12) // Returns the wavelength of a piano key from 1 (A0) to 88 (C8). 49 is (A4) or 78.41cm const pianoKeyToWavelength = n => +(345 / pianoKeyToFrequency(n) * 100).toFixed(2) // Returns the wavelength of a frequency. 440 is (A4) or 78.41cm const freqToWavelength = f => +(345 / f * 100).toFixed(2) // Returns the frequency at 'n' steps from the current frequency. Can be positive or negative. const freqAtPositionFrom = (f, n) => +(f * Math.pow(Math.pow(2, 1 / 12), n)).toFixed(2) // Returns the frequency one octave down from the input frequency. const octaveDown = f => f / 2 // Returns the frequency one octave up from the input frequency. const octaveUp = f => f * 2 module.exports = { pianoKeyToFrequency, pianoKeyToWavelength, freqToWavelength, freqAtPositionFrom, octaveDown, octaveUp }
import React from 'react'; const ContextData = React.createContext(null); export default ContextData;
const validateIp = str => { str = str.split(".").map(e => Number(e)) return str.length > 4 || str.length < 4 ? false : str.every(e => e <= 255 && e >= 0) } console.log ("should be false: " + validateIp("228.1.1"))
/* Slideshow - pokaz slajdów */ window.onload = function() { var box = document.getElementById("box"); box.onclick = function() { var self = this; var i = 0; var animationId = setInterval(function() { self.style.left = (i++) + "px"; if (i > 100) clearInterval(animationId); }, 10); }; };
"use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } $(document).ready(function () { /* $(function() { }); */ }); var test = function () { function test(msg) { _classCallCheck(this, test); this.msg = msg; } _createClass(test, [{ key: "say", value: function say() { console.log(this.msg); [1, 2, 3].map(function (n) { return n + 1; }); } }]); return test; }(); ; var t1 = new test("hi, Chanalaaa"); t1.say();
var noteServices = { addNotes: '/notes/addNotes', getNotes: '/notes/getNotesList', changeColorNotes: '/notes/changesColorNotes', updateNotes: '/notes/updateNotes', deleteNotes: '/notes/trashNotes', archiveNotes: '/notes/archiveNotes', // noteLabels: '/noteLabels', // NoteLabelList: ' /noteLabels/getNoteLabelList', addLabelToNotes: `/notes/{noteId}/addLabelToNotes/{lableId}/add`, //removeLabelToNotes: `/notes/${noteId}/addLabelToNotes/${lableId}/remove`, getArchiveNotesList: '/notes/getArchiveNotesList', getTrashNotesList: '/notes/getTrashNotesList', // addUpdateReminderNotes: '/notes/addUpdateReminderNotes', // removeReminderNotes: '/notes/removeReminderNotes', // getReminderNotesList: '/notes/getReminderNotesList', // deleteForeverNotes: '/notes/deleteForeverNotes', //getNoteLabelList: '/noteLabels/getNoteLabelList', } export default noteServices
import React from 'react'; import style from '../style.css'; import { FaPlayCircle } from 'react-icons/lib/fa'; const Start = ({ handleClick }) => <button onClick={handleClick} className={`${style.control_button} ${style.button_play}`} > <FaPlayCircle /> </button>; Start.propTypes = { handleClick: React.PropTypes.func, }; export default Start;
$(function() { var home = "Home" var calendar = "Calendar" var agenda = "Agenda" var resources = "Resources" var attendance = "Attendance" var path = window.location.pathname; var page = path.split("/").pop(); if (page == "attendance.html") { attendance = "<b>Attendance</b>" } if (page == "index.html") { home = "<b>Home</b>" } if (page == "agenda.html") { agenda= "<b>Agenda</b>" } if (page == "resources.html") { resources = "<b>Resources</b>" } if (page == "calendar.html") { calendar = "<b>Calendar</b>" } var html = [ '<div class="links">', '<a class="icons" target="_blank" href="https://www.sandiegounified.org/schools/la-jolla"><img src="css/ljhs_logo.png" alt="Vikings"></a>', '<a class="icons" target="_blank" href="https://discordapp.com/invite/5cZQAv3"><img src="css/discord_logo.png" alt="Discord"></a>', '<a class="icons" id="github" target="_blank" href="https://github.com/vikinggames"><img src="css/github_logo.png" alt="Github"></a>', '</div>', '<div class="title">', '<h1>Viking Games</h1>', '</div>', '<div class="menu">', '<ul>', '<li><a href="index.html">' + home + '</a></li>', '<li><a href="calendar.html">' + calendar + '</a></li>', '<li><a href="agenda.html">' + agenda + '</a></li>', '<li><a href="resources.html">' + resources + '</a></li>', '<li><a href="attendance.html">' + attendance + '</a></li>', '</ul>', '</div>' ].join("\n"); $("#nav-placeholder").append(html) });
(function() { 'use strict'; angular .module('acmeApp') .factory('AnsweredQuestionnaire', AnsweredQuestionnaire); AnsweredQuestionnaire.$inject = ['$resource', 'DateUtils']; function AnsweredQuestionnaire ($resource, DateUtils) { var resourceUrl = 'api/answered-questionnaires/:id'; return $resource(resourceUrl, {}, { 'query': { method: 'GET', isArray: true}, 'get': { method: 'GET', transformResponse: function (data) { if (data) { data = angular.fromJson(data); data.answeredDate = DateUtils.convertDateTimeFromServer(data.answeredDate); } return data; } }, 'update': { method:'PUT' } }); } })();
'use strict'; module.exports = function createUpdatedCollection(collectionA, objectB) { var result = []; var keyA, countA; result.push({key:collectionA[0],count:0}); for(var i = 0; i<collectionA.length; i++){ if(collectionA[i]===result[result.length-1].key){ result[result.length-1].count++; }else{ result.push({key:collectionA[i],count:1}); } } for(var j = 0; j < result.length; j++){ if(result[j].key.length > 1 && result[j].key[1]==='-'){ //console.log(result[j]); keyA = result[j].key[0]; countA = result[j].key[2]; result.splice(j,1); result.push({key:keyA,count:parseInt(countA)}); } } var num = 0; for(var k = 0; k < objectB.value.length; k++){ for(var h = 0; h < result.length; h++){ if(objectB.value[k] === result[h].key){ num = parseInt(result[h].count/3 ); result[h].count -= num; } } } return result; }
const xss = require('xss'); const NotesService = { getNotesByPubId(db, userId, pubId) { return db .distinct('n.id', 'n.pub_id', 'n.text', 'n.section', 's.title') .from('benrinote_notes AS n') .leftJoin('benrinote_sections As s', 'n.section', 's.section') .where({ 'n.user_id': userId, 's.pub_id': pubId, 'n.pub_id': pubId}) .orderBy('n.section') }, userPubByUserId(db, user_id) { return db .from('user_pub') .select('pub_id') .where('user_id', user_id) }, NotesExisty(db, user_id, pub_id) { console.log(user_id, pub_id) return db .from('benrinote_notes') .select('*') .where({ user_id, pub_id }) }, createNewNote(db, user_id, pub_id, section) { return db .insert({ user_id, pub_id, section }) .into('benrinote_notes') .then(res => console.log(`inserted note for User Id ${user_id}, Pub Id ${pub_id}, Section ${section}`)) }, deleteNotes(db, user_id, pub_id) { return db .from('benrinote_notes') .where({ user_id, pub_id }) .delete() .then(res => console.log(`(from NotesService)deleted notes for User Id ${user_id}, Pub Id ${pub_id}`)) }, updateNote(db, id, text) { return db('benrinote_notes').where({ id }).update({ text }) }, getPub(db, pub_id) { return db .from('benrinote_publications') .select('*') .where('id', pub_id) .first() }, serializeNotes(notes) { return notes.map(this.serializeNote) }, serializeNote(note) { return { id: note.id, pub_id: note.pub_id, section: note.section, title: note.title, text: xss(note.text) } } } module.exports = NotesService;
/* * @Author: zyc * @Date: 2016-01-15 14:37:05 * @Last Modified by: zyc * @Last Modified time: 2016-01-20 01:22:46 */ 'use strict'; const pg = require('pg'); class DBConnection { constructor(conString) { this.conString = conString; } get client() { return new pg.Client(this.conString); } end(client) { if (client) client.end(); pg.end(); } query(queryString, values, client) { console.log(queryString, values); return new Promise((resolve, reject) => { if (client) { client.query(queryString, values, (err, result) => { if (err) return reject({queryString, values, err}); resolve(result.rows.length ? result.rows : result.rowCount); }); } else { pg.connect(this.conString, (err, client, done) => { if (err) return reject(err); client.query(queryString, values, (err, result) => { done(); if (err) return reject({queryString, values, err}); resolve(result.rows.length ? result.rows : result.rowCount); }); }); } }); } }; module.exports = DBConnection;
'use strict' import { dbRol, dbPerson, dbUser } from '../db-api' const adminRole = { '_id': '5b9f37344ba1930a0a105eb4', 'permissions': [ 'admin', 'user', 'user:create', 'user:read', 'user:all', 'user:update', 'user:delete', 'user-persona:read', 'person', 'person:create', 'person:read', 'person:all', 'person:update', 'person:delete', 'pokemon', 'pokemon:create', 'pokemon:read', 'pokemon:all' ], 'rol': 'admin', 'status': 1, '__v': 0 } const userRole = { '_id': '5d8d932f7ce3c41c4971476e', 'permissions': [ 'user', 'user:create', 'user:read', 'user:all', 'user:update', 'user:delete', 'user-persona:read', 'person', 'person:create', 'person:read', 'person:all', 'pokemon', 'pokemon:create', 'pokemon:read', 'pokemon:all' ], 'rol': 'user', 'status': 1, '__v': 0 } const defaultPersonAdmin = { '_id': '5d8d93672bb32d4593187777', 'firstName': 'Admin', 'lastName': 'Admin', 'status': 1, '__v': 0 } const defaultUserAdmin = { '_id': '5d8d93672bb32d4593187778', 'rol': '5b9f37344ba1930a0a105eb4', 'email': 'admin@example.com', 'password': 'password', 'person': '5d8d93672bb32d4593187777', 'status': 1, '__v': 0 } const createDefaultAdminUser = async () => { try { await dbPerson.create(defaultPersonAdmin) await dbUser.create(defaultUserAdmin) } catch (error) { console.log(error) } } const createDefaultRoles = async () => { try { await dbRol.create(adminRole) await dbRol.create(userRole) } catch (error) { console.log(error) } } const createData = async () => { const roles = await dbRol.findAll() if (roles.length > 0) return false createDefaultRoles() createDefaultAdminUser() } export default createData
// (기존) 데이터 배열을 컴포넌트 배열로 변환하기 // 즉, 기존 배열로 컴포넌트로 구성된 배열을 생성해 봅시다. import React from 'react'; const IterationSample = () => { // 문자열로 구성된 배열을 선언합니다. const names = ['눈사람', '얼음', '눈', '바람']; // 앞서 문자열로 구성된 배열값을 사용하여 // <li>...</li> JSX 코드로 된 배열을 새로 생성한 후 // nameList에 담습니다. // 참고로, map 함수에서 JSX를 작성할 때는 DOM 요소를 작성해도 되고, // 컴포넌트를 사용해도 됩니다. const nameList = names.map(name => <li>{name}</li>); return <ul>{nameList}</ul>; }; export default IterationSample;
import React, { Component } from 'react'; import Form from 'react-bootstrap/Form'; import Button from 'react-bootstrap/Button'; import Card from 'react-bootstrap/Card'; import Accordion from 'react-bootstrap/Accordion'; export default class Accounts extends Component { state = { accountName: "", accountBalance: "", errors: [], } render() { const { errors, } = this.state; return ( <React.Fragment> { this.props.context.showAccountsState && <Accordion defaultActiveKey="0"> <Card> <Card.Body> <Form> <Form.Group> <Form.Label>Account Name</Form.Label> <Form.Control type="text" placeholder="Enter account name" name="accountName" onChange={this.change} /> </Form.Group> <Form.Group> <Form.Label>Account Balance</Form.Label> <Form.Text className="text-muted"> For credit cards, enter a negative balance </Form.Text> <Form.Control type="number" placeholder="Enter account balance" name="accountBalance" onChange={this.change} /> </Form.Group> <Button variant="primary" type="submit" onClick={this.submit}> Add Account </Button> </Form> </Card.Body> </Card> </Accordion> } </React.Fragment> ) } change = (event) => { let name = event.target.name; let value = event.target.value; if (name == "accountName") { value = value.charAt(0).toUpperCase() + value.slice(1); console.log(value); } this.setState(() => { return { [name]: value }; }); } submit = (e) => { e.preventDefault(); const { context } = this.props; const userId = context.authenticatedUser.user[0].id; const { accountName, accountBalance, errors } = this.state; context.data.createAccount(accountName, accountBalance, userId) .then( errors => { if (errors.length) { console.log(errors); } else { console.log('Account added') window.location.href = "/accounts"; } }) } }
//= components/slick.js $(document).ready(function () { $(".fancybox").fancybox({ 'transitionIn': 'elastic', 'transitionOut': 'elastic', 'speedIn': 600, 'speedOut': 200, 'overlayShow': false }); $('.js-show-menu').on('click', function (e) { e.preventDefault(); $('.mask').addClass('active'); $('.menu').addClass('opened'); $('body').addClass('fixed') }); $('.js-hide-menu').on('click', function (e) { e.preventDefault(); $('.mask').removeClass('active'); $('.menu').removeClass('opened'); $('body').removeClass('fixed'); }); $('.mask').on('click', function () { $(this).removeClass('active'); $('.menu').removeClass('opened'); $('body').removeClass('fixed'); }); $('.js-open-popup').on('click', function (e) { e.preventDefault(); var target = $(this).data('target'); $(target).addClass('opened'); setTimeout(function () { $('.js-name').focus(); }, 200); console.log(target); }); //$('.js-phone').mask('+7 (999) 999-99-99'), { placeholder: '+7 (___) ___-__-__' }; // Маска //$(".js-phone").attr("pattern","[+]7[ (][0-9]{3}[) ][0-9]{3}-[0-9]{2}-[0-9]{2}").inputmask({"mask": "+7(999)999-99-99"}); $('.js-popup').on('click', function () { $(this).removeClass('opened'); }); $('.js-popup-content').on('click', function (e) { e.stopPropagation(); }); $('.js-close-popup').on('click', function () { $('.js-popup').removeClass('opened'); }); $('.js-page-nav a ').on('click', function (e) { e.preventDefault(); var id = $(this).data('target'), currentBlockOffset = $(id).offset().top; $('.mask').removeClass('active'); $('.menu').removeClass('opened'); $('body').removeClass('fixed'); $("html, body").animate({ scrollTop: currentBlockOffset }, 500); }); $('.js-show-video').fancybox({ width: 640, height: 400, type: 'iframe' }); $('.js-parallax').on('mousemove', function (e) { var amountMovedX = (e.pageX * -1 / 64); var amountMovedY = (e.pageY * -1 / 64); $('.js-mouse-parallax').css("transform", "translate(" + amountMovedX + "px," + amountMovedY + "px)"); }); $('.slider-for').slick({ slidesToShow: 1, slidesToScroll: 1, arrows: true, fade: true, asNavFor: '.slider-nav', appendArrows: '.arrow-wrapper', // adaptiveHeight: true }); $('.slider-nav').slick({ slidesToShow: 3, slidesToScroll: 1, arrows: false, asNavFor: '.slider-for', // dots: true, // centerMode: true, focusOnSelect: true }); });
const express = require('express'); const fs = require('fs'); const https = require('https'); var bodyParser = require('body-parser'); var ffmpeg = require('fluent-ffmpeg'); const app = express(); app.set('port', 8080); app.use(bodyParser.urlencoded({extended: true})); app.listen(app.get('port'), function () { console.log("server up") }); app.get("/", function (req, res) { res.sendFile(__dirname + "/index.html"); }); app.post("/myaction", function (req, res) { console.log("Got a post req:" + req.body.videoname); var input = req.body.videoname; console.log("inside the function to covert the video:" + input); var temp = input.split('.'); var filename = temp[0] + '.mp4'; var file = fs.createWriteStream('./videos/' + input); var request = https.get("https://s3.ap-south-1.amazonaws.com/lightmetrics/" + input, function (response) { response.pipe(file); console.log("file stored locally"); ffmpeg().input('./videos/' + input).complexFilter([{ filter: 'setpts', options: '2.5*PTS', outputs: 'intermediate' }, { filter: 'rotate', options: '1*PI', inputs: 'intermediate', outputs: 'output' }], 'output').save('./videos/' + filename).on('end', function (stdout, stderr) { console.log("completed\ndeleting the h264 file"); fs.unlink('./videos/' + input, some => { console.log("deleted the file:" + input); var filePath = "./videos/" + filename; var stat = fs.statSync(filePath); res.writeHeader(200, { 'Content-Type': 'video/mp4', 'Content-Length': stat.size }); console.log(stat.size); var readStream = fs.createReadStream(filePath); // We replaced all the event handlers with a simple call to readStream.pipe() readStream.pipe(res); }); }); }); }); app.post("/myaction2", function (req, res) { console.log("Got a post req:" + req.body.videoname); var input = req.body.videoname; console.log("inside the function to covert the video:" + input); var temp = input.split('.'); var filename = temp[0] + '.mp4'; var file = fs.createWriteStream('./videos/' + input); var request = https.get("https://s3.ap-south-1.amazonaws.com/lightmetrics/" + input, function (response) { response.pipe(file); console.log("file stored locally"); ffmpeg().input('./videos/' + input).complexFilter([{ filter: 'setpts', options: '2.5*PTS', outputs: 'intermediate' }, { filter: 'rotate', options: '1*PI', inputs: 'intermediate', outputs: 'output' }], 'output').save('./videos/' + filename).on('end', function (stdout, stderr) { console.log("completed\ndeleting the h264 file"); fs.unlink('./videos/' + input, some => { console.log("deleted the file:" + input); res.download('./videos/' + filename); // var filePath = "./videos/" + filename; // var stat = fs.statSync(filePath); // res.writeHeader(200, { // 'Content-Type': 'video/mp4', // 'Content-Length': stat.size, // 'Content-Disposition': 'attachment; filename=' + filename // }); // // var readStream = fs.createReadStream(filePath); // readStream.pipe(res); }); }); }); }); //////////////////////////////////////////////////////////////// // ffmpeg().input('./videos/sample.h264').complexFilter([{ // filter: 'setpts', // options: '2*PTS', // outputs: 'intermediate' // }, { // filter: 'rotate', // options: '1*PI', // inputs: 'intermediate', // outputs: 'output' // }], 'output').save('cool.mp4').on('end', function () { // console.log("DONE :)"); // }); //// ------------Take screenshots------------- // ffmpeg().input('./cool.mp 4').screenshots({ // folder:'./videos', // count:6 // }); // ------------Generate a yuv file------------- // ffmpeg().input('./cool.mp4').save('out.yuv').on('end', function () { // console.log("Done2 :)") // });
import React, { Component } from "react"; import Form from "react-bootstrap/Form"; import Button from "react-bootstrap/Button"; import Card from "react-bootstrap/Card"; import Container from "react-bootstrap/Container"; import { api } from "../services/api"; class SignUp extends Component { state = { error: false, fields: { firstname: "", lastname: "", email: "", username: "", password: "", }, }; //HANDLES UPDATING STATE handleChange = (e) => { const newFields = { ...this.state.fields, [e.target.name]: e.target.value, }; this.setState({ fields: newFields }); }; //EVENT HANDLER FOR SUBMIT handleSubmit = (e) => { e.preventDefault(); // fetch request to login api.auth.signUp(this.state.fields).then((resp) => { console.log(resp) if (!resp.error) { // calls login function from App.js if no error from fetch this.props.onSignIn(resp); // redirects to home page this.props.history.push("/"); } else { this.setState({ error: true }); } }); }; render() { return ( <div> <Container className="mt-5"> <Card className="col-sm-6"> <Card.Body className="col-sm-6"> <Form className="text-center" onSubmit={this.handleSubmit}> <Form.Row> <Form.Group controlId="formGridEmail"> <Form.Label>First Name:</Form.Label> <Form.Control type="firstname" name="firstname" placeholder="Enter first name" onChange={this.handleChange} /> </Form.Group> </Form.Row> <Form.Row> <Form.Group controlId="formGridEmail"> <Form.Label>Last Name:</Form.Label> <Form.Control type="lastname" name="lastname" placeholder="Enter last name" onChange={this.handleChange} /> </Form.Group> </Form.Row> <Form.Row> <Form.Group controlId="formGridEmail"> <Form.Label>Email:</Form.Label> <Form.Control type="email" name="email" placeholder="Enter your email" onChange={this.handleChange} /> </Form.Group> </Form.Row> <Form.Row> <Form.Group controlId="formGridEmail"> <Form.Label>Username:</Form.Label> <Form.Control type="username" name="username" placeholder="Enter your username" onChange={this.handleChange} /> </Form.Group> </Form.Row> <Form.Row> <Form.Group controlId="formGridEmail"> <Form.Label>Password:</Form.Label> <Form.Control type="password" name="password" onChange={this.handleChange} /> </Form.Group> </Form.Row> <Form.Row> <Form.Group controlId="formGridEmail"> <Form.Label>Confirm Password:</Form.Label> <Form.Control type="password" name="password" /> </Form.Group> </Form.Row> <Button variant="primary" type="submit"> Submit </Button> </Form> </Card.Body> </Card> </Container> </div> ); } } export default SignUp
//导出获取 state export default { sidebar: (state) => { return state.sidebar.sidebar; }, visitedViews: (state) => { return state.visitedViews; }, count(state){ return state.count; }, getOdd: (state) => { return state.count % 2 == 0 ? '偶数' : '奇数' } }
const path = require('path') const webpack = require('webpack') const BundleAnalyzerPlugin = require('webpack-bundle-analyzer') .BundleAnalyzerPlugin const CopyWebpackPlugin = require('copy-webpack-plugin') const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin') const getMode = env => { if (env.production) { return 'production' } return 'development' } const getPlugins = env => { const plugins = [ new BundleAnalyzerPlugin({ analyzerMode: 'static', openAnalyzer: false }) // new ForkTsCheckerWebpackPlugin() ] if (!env.production) { plugins.push( new CopyWebpackPlugin([ { context: './src/game/', from: '*.html', to: './' }, { from: './src/maps/', to: './' } ]) ) } return plugins } module.exports = env => { if (env === undefined) { env = { development: true } } const config = { entry: { main: './src/game/index.tsx', 'terrain.worker': './src/terrainGeneration/worker.ts' }, output: { filename: '[name].js', path: path.join(__dirname, 'dist') }, devServer: { contentBase: path.join(__dirname, 'dist') }, devtool: 'cheap-module-source-map', mode: getMode(env), module: { rules: [ { test: /\.tsx?$/, include: path.join(__dirname, 'src'), use: { loader: 'ts-loader', options: { transpileOnly: true, projectReferences: true } } }, { test: /\.html$/, use: [ { loader: 'html-loader', options: { attrs: ['link:href'] // minimize: true, // removeComments: true, // collapseWhitespace: true } } ] }, { test: /\.scss$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' }, { loader: 'sass-loader' } ] }, { test: /\.osm$/, use: { loader: 'raw-loader' } } ] }, plugins: getPlugins(env), resolve: { extensions: ['.ts', '.tsx', '.js'] } } return config }
function loadTask() { var task = []; // CONSENT task[0] = {}; task[0].type = 'consent'; // consent is a default type with no callbacks task[0].variables = {}; task[0].variables.consent = NaN; // consent has no data // RT TRIALS task[1] = {}; task[1].type = 'trial'; // this will give us use of the canvas task[1].callbacks = {}; task[1].callbacks.startBlock = startBlock; task[1].callbacks.startSegment = startSegment; task[1].callbacks.updateScreen = updateScreen; task[1].callbacks.getResponse = getResponse; // RT task doesn't have any parameters, but this gets auto-populated with data task[1].parameters = {}; // RT task won't log any variables either (these get set by the user somewhere in the callbacks) // caution: these need a value (e.g. NaN) or they won't run correctly task[1].variables = {}; task[1].variables.key = undefined; // Segment timing task[1].segnames = ['delay','stim','iti']; // Seglen uses specific times task[1].segmin = [500,1000,1000]; task[1].segmax = [2000,1000,3000]; // Responses task[1].response = [0,1,0]; // Trials task[1].numTrials = 5; // can't be infinite, best to have smaller blocks with breaks in between (e.g. an instruction page that is blank) // Keys task[1].keys = 32; // (check w/ http://keycode.info/) return task; } let fix, rect, showResp, rt_text; function startBlock() { // pre-draw all the graphcis and make them invisible fix = jglFixationCross(); fix.visible = false; rect = jglFillRect(0,0,[1,1],'#ffffff'); rect.visible = false; } function startSegment() { if (jgl.trial.segname=='delay') { jglDestroy(rt_text); rect.visible = false; fix.visible = true; } if (jgl.trial.segname=='stim') { rect.visible = true; fix.visible = false; showResp = false; } } function updateScreen() { if (jgl.trial.segname=='stim' && jgl.trial.responded[jgl.trial.thisseg] && !showResp) { rect.visible = false; showResp = true; if (jgl.trial.RT[jgl.trial.thisseg]<300) { jglTextSet('Arial',1,'#00ff00'); } else { jglTextSet('Arial',1,'#ff0000'); } rt_text = jglTextDraw(Math.round(jgl.trial.RT[jgl.trial.thisseg]),0,0); } } function getResponse() { jgl.trial.key = jgl.event.which; }
import ProductDescr from "./product-descr"; export default ProductDescr;
/** * @param {number[][]} points * @return {number} */ var maxPoints = function(points) { let result = resolve(points); return result; }; function resolve(points) { let max = 0; return max; } function test1() { let input = [[1, 1], [3, 2], [5, 3], [4, 1], [2, 3], [1, 4]]; let result = maxPoints(input); console.log(result); } test1();
export const LOCALHOST = "http://localhost:35353"
import React, { Component } from 'react'; import './QbLayout.scss'; import QbHeader from '../QbHeader'; import QbFooter from '../QbFooter'; import gql from 'graphql-tag'; import ApolloClient, { createNetworkInterface } from 'apollo-client'; import { QB_COMPONENT_GQL_URL, TOKEN_KEY, TOKEN_KEY_QB, HOME_PAGE, DEFAULT_FOLDER, TUTOR_ADMIN, ALLOWED_TYPES } from '../common/const'; import Cookies from 'js-cookie'; import iconLoading from '../assets/image/icon/loading.gif'; class QbLayout extends Component { constructor(props) { super(props); const { gqlUrl, route } = this.props; const GQL_URL = gqlUrl || (route ? route.gqlUrl : route) || QB_COMPONENT_GQL_URL; const networkInterface = createNetworkInterface({ uri: GQL_URL }); networkInterface.use([ { applyMiddleware(req, next) { if (!req.options.headers) { req.options.headers = {}; // Create the header object if needed. } // get the authentication token from cookies if it exists, waiting for fix const token = Cookies.get(TOKEN_KEY); req.options.headers.authorization = token ? `bearer ${token}` : ''; next(); } } ]); this.client = new ApolloClient({ networkInterface }); this.state = { currentUser: null, navItemList: {}, isShowLoading: false }; } componentWillMount() { this.client.query({ query: gql` query { currentUser: current_user { id name avatar email first_name last_name exam_type_names avg_tutor_rating type one_of_section_part1_finished current_test } } `, fetchPolicy: 'network-only' }).then((res) => { let navItemList = this.props.navItemList || this.props.route.navItemList; let currentUser = res.data.currentUser; let pathname = window.location.pathname; if (!currentUser && pathname !== HOME_PAGE && window.location.href.indexOf("eclass") !== -1) { this.navHomePage(); } else if (pathname.indexOf(TUTOR_ADMIN) !== -1 && !ALLOWED_TYPES.includes(currentUser.type)) { this.navHomePage(); } else { const self = this; this.setState({ currentUser, navItemList }, () => { console.log("<--- Qblayout this props ---->", self.props); if (self.props.route) { const { doSthWhenFetchUserSuccess } = self.props.route; if (typeof doSthWhenFetchUserSuccess === 'function') { doSthWhenFetchUserSuccess(currentUser); } } }); } }).catch((e) => { this.navHomePage(); console.info('currentUser none', e); }); } componentWillReceiveProps(newProps) { let navItemList = newProps.navItemList || newProps.route.navItemList; this.setState({ navItemList: navItemList }); } navHomePage = () => { if (!this.state.isShowLoading) { this.setState({ isShowLoading: true }); if (window.location.hostname !== 'localhost') { window.location.href = HOME_PAGE; } } } onClick_Setting(userType) { window.location.href = window.location.origin + `${DEFAULT_FOLDER}/#/setting`; // switch (userType) { // case 'Student': // window.location.href = window.location.origin + `${DEFAULT_FOLDER}/#/setting`; // break; // case 'Tutor': // window.location.href = window.location.origin + `${DEFAULT_FOLDER}/#/settingTutor`; // break; // default: // window.location.href = window.location.origin + `${DEFAULT_FOLDER}/#/setting`; // } } onClick_MyClass() { window.location.href = window.location.origin + '/start/#/myClasses'; } onClick_SignOut() { let token = Cookies.get(TOKEN_KEY); function handleErrors(response) { if (!response.ok) { throw Error(response.statusText); } return response; } const { gqlUrl, route } = this.props; const GQL_URL = gqlUrl || (route ? route.gqlUrl : route) || QB_COMPONENT_GQL_URL; fetch(GQL_URL.replace('/graphql', '') + '/users/sign_out', { method: 'DELETE', credentials: 'include' }).then(handleErrors).then(res => { console.log('success'); Cookies.remove(TOKEN_KEY); Cookies.remove(TOKEN_KEY_QB); this.setState({ currentUser: null }); this.navHomePage(); return res.data; }).catch(error => { alert('sign out error!'); console.log(error); }); } sendTimeOnPlatform(time){ let token = Cookies.get(TOKEN_KEY); function handleErrors(response) { if (!response.ok) { throw Error(response.statusText); } return response; } const { gqlUrl, route } = this.props; const GQL_URL = gqlUrl || (route ? route.gqlUrl : route) || QB_COMPONENT_GQL_URL; fetch(GQL_URL.replace('/graphql', '') + '/api/v1/time_on_platform', { method: 'POST', credentials: 'include', headers: { Accept: 'application/vnd.api+json', 'Content-Type': 'application/vnd.api+json', Authorization: 'bearer ' + token }, body: JSON.stringify({"total_time": {"time_on_platform": time}}) }).then(handleErrors).then(res => { console.log('success'); return res.data; }).catch(error => { console.log(error); }); } renderLoading() { if (this.state.isShowLoading) { return ( <div className='box-flex-center' style={{ position: 'absolute', width: '100vw', height: '100vh', opacity: '0.8', backgroundColor: '#fff', zIndex: '999' }}> <img style={{ margin: 'auto' }} src={iconLoading} alt="" /> </div> ); } } render() { const { messageId } = this.props; let currentUser = this.state.currentUser; let styleNoLogin; if (!currentUser) { styleNoLogin = { marginTop: '50px' }; } return ( <div className="layout-ct"> {this.renderLoading()} <QbHeader messageId={messageId} client={this.client} currentUser={currentUser} navItemList={this.state.navItemList} onClick_SignOut={this.onClick_SignOut.bind(this)} onClick_MyClass={this.onClick_MyClass.bind(this)} onClick_Setting={this.onClick_Setting.bind(this)} sendTimeOnPlatform={this.sendTimeOnPlatform.bind(this)} updateUser={this.props.route.updateUser} dismissBanner={this.props.route.dismissBanner} banner = {this.props.route.banner} /> <div className="body-content" style={styleNoLogin}> {this.props.children} </div> <QbFooter /> </div> ); } } export default QbLayout;
var AppRouter = Backbone.Router.extend({ initialize: function(options) { this.collection = options.collection; }, routes: { "search/:title": "search", // }, search: function(query) { var models = this.collection.where({title:query}); if(models.length === 0) { alert("no articles found!"); } else { new ArticleView({ el: $('.row'), model: models[0] }); } } });
import React from 'react' import './classChatIndex.css' import { io } from 'socket.io-client'; import { connect } from 'react-redux' import { setClassRecvmsgRead } from 'myredux/myRedux' import { withRouter } from 'react-router-dom' import NavBar from 'components/navBar/navBar' import { InputItem, Toast, Grid } from 'antd-mobile'; import RightContent from './rightContent/rightContent' import BetterScroll from 'better-scroll' import { getUrl } from 'utils/nodeBaseUrl' class ClassChatIndex extends React.Component { state = { recvmsg: [], sendmsg: "", showEmoji: false } componentDidMount() { this.init() this.fixCarousel() } fixCarousel(){ setTimeout(function(){ window.dispatchEvent(new Event('resize')) },0) } componentDidUpdate() { this.bs.refresh() } init() { this.socket = io(getUrl()); this.readMsgCB() this.n3ScInit() this.byToBottom() if (!this.props.userInfo.clId) { return Toast.fail('会话信息丢失,请重新进入', 3, () => { this.props.history.push('/mine') }) } this.socket.on('recvmsg' + this.props.userInfo.clId, (data) => { Toast.info('您有新的聊天消息', 1, null, false); }) } componentWillUnmount() { this.readMsgCB() // this.clearMsgCB() // 清除消息 // 断开连接 if (this.socket) { this.socket.close() } } n3ScInit() { this.bs = new BetterScroll('#ClassChatIndex-content-id', { zoom: true, scrollbar: true, }) } clearMsgCB() { this.props.setClassRecvmsgRead([]) } // 修改未读消息状态 readMsgCB() { // 把所有消息变为已读 let newMsgObj = this.props.classRecvmsg.map(v => { return { ...v, read: 1 } }) this.props.setClassRecvmsgRead(newMsgObj) } // 回滚到底部 byToBottom() { let el = document.getElementsByClassName("ClassChatIndex-content-list-bottom")[0] this.bs.scrollToElement(el) } sendMsg() { // 滚动到底部 if (this.state.sendmsg === "") { return Toast.fail('发送的内容不能为空', 1, null, false); } const { userInfo } = this.props let msgObj = { stId: userInfo.stId, clId: userInfo.clId, clMsg: this.state.sendmsg, name: userInfo.stName, formAvImg: userInfo.stAvatar, } this.socket.emit("sendmsg", msgObj, (data) => { if (data.status === "ok") { this.byToBottom() }else{ // 发送不成功 Toast.fail('发送失败!', 1); } }) this.setState({ sendmsg: "", showEmoji: false }) // 聚焦 this.refs.myInput.focus() } // 输入框改变函数 inputChange(v, type) { this.setState({ [type]: v }) } createCard() { return this.props.classRecvmsg.map(v => { if (v.stId === this.props.userInfo.stId) { // 自己发的消息 return ( <div className="ClassChatIndex-content-right clearfix" key={v.id}> <div className="ClassChatIndex-content-right-content clearfix"> <div className="ClassChatIndex-content-right-content-av"> <img width="40px" src={v.formAvImg} alt="" /> </div> <div className="ClassChatIndex-content-right-content-name"> 我 </div> <div className="ClassChatIndex-content-right-content-desc"> {v.clMsg} </div> </div> </div> ) } else { // 别人发的 return ( <div className="ClassChatIndex-content-left clearfix" key={v.id}> <div className="ClassChatIndex-content-left-content clearfix"> <div className="ClassChatIndex-content-left-content-av"> <img width="40px" src={v.formAvImg} alt="" /> </div> <div className="ClassChatIndex-content-left-content-name"> {v.name} </div> <div className="ClassChatIndex-content-left-content-desc"> {v.clMsg} </div> </div> </div> ) } }) } render() { const { userInfo } = this.props const emoji = '😀 😃 😄 😁 😆 😅 😂 😊 😇 🙂 🙃 😉 😌 😍 😘 😗 😙 😚 😋 😜 ' .split(' ') .filter(v => v) .map(v => ({ text: v })) return ( <div className='ClassChatIndex'> <NavBar title={userInfo.clName + " - 聊天室"} back={true} url="/mine" rightContent={RightContent}/> <div className="ClassChatIndex-content" ref="content"> <div id="ClassChatIndex-content-id"> <div className="ClassChatIndex-content-list"> {this.createCard()} <div className="ClassChatIndex-content-list-bottom" style={{ height: "50px" }}></div> </div> </div> </div> { this.state.showEmoji ? <div className="emoji-wrap noSelect"> <Grid data={emoji} columnNum={8} carouselMaxRow={3} isCarousel={true} onClick={el => { this.setState({ sendmsg: this.state.sendmsg + el.text }) this.refs.myInput.focus() }} /> </div>:null } <div className="ClassChatIndex-input-wrap"> <div className="ClassChatIndex-input-wrap-input"> <div> <InputItem maxLength="250" onFocus={() => { this.byToBottom() }} ref="myInput" value={this.state.sendmsg} onChange={(v) => { this.inputChange(v, "sendmsg") }} /> </div> </div> <div className="ClassChatIndex-input-wrap-right"> <span className="ClassChatIndex-input-wrap-right-face" role="img" aria-label="" onClick={()=>{ this.setState({showEmoji: !this.state.showEmoji}) this.refs.myInput.focus() this.fixCarousel() }}>😀</span> <span className="ClassChatIndex-input-wrap-right-btn"> <span className="ClassChatIndex-input-wrap-right-btn-send" onClick={() => { this.sendMsg() }}>发送</span> </span> </div> </div> </div> ) } } const mapStateToProps = state => { return { userInfo: state.userInfo, classRecvmsg: state.classRecvmsg } } const mapDispatchToProps = dispatch => { return { setClassRecvmsgRead: msgInfo => { dispatch(setClassRecvmsgRead(msgInfo)) } } } export default withRouter(connect(mapStateToProps, mapDispatchToProps)(ClassChatIndex))
import React from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; import { findBubbleProduct } from '../../services/BubbleService' function getProducts(arr) { var products = []; //This function retrieves the items from the bundlelist for(var i = 0; i < arr.length; i++){ findBubbleProduct(arr[i]).then( item => (products.push({id: item.id, name: item.name, price: item})) ); } return products; }; const BundleItem = props => { const { name, items} = props; return ( <div className="card text-white bg-secondary mb-3"> <div className="card-header">{ name } <i className="fa fa-2x fa-times" style={{ float: 'right' }}></i></div> <div className="card-body"> <div className="card-text"> {/* trying to use 'ProductList' array to store the items of a bundle var ProductList = getProducts(items); We could not resolve a issue when we tried to map the items, so instead here's a dumb looking link */} {items.map(pl => <Link to={ "/products/" + pl }>Item{<br />}</Link>)} </div> </div> </div> ); }; BundleItem.propTypes = { id: PropTypes.oneOfType([ PropTypes.string, PropTypes.number ]).isRequired, name: PropTypes.string.isRequired }; export default BundleItem
import React, { Component, useState } from 'react' export default function HSL() { const [hue, setHue] = useState(Math.floor(Math.random() * 360)) const [saturation, setSaturation] = useState(Math.floor(Math.random() * 100)) const [lightness, setLightness] = useState(Math.floor(Math.random() * 100)) const [alpha, setAlpha] = useState(Math.floor(Math.random() * 100) / 100) const pickRandomColor = () => { setHue(Math.floor(Math.random() * 360)) setSaturation(Math.floor(Math.random() * 100)) setLightness(Math.floor(Math.random() * 100)) setAlpha(Math.floor(Math.random() * 100) / 100) } // hooks are sweet return ( <> <section className="pattern"> <main className="sliders" style={{ backgroundColor: `hsl(${hue}, ${saturation}%, ${lightness}%, ${alpha})` }} > <header className="title"> Pick a color, any color but Goldenrod </header> <div> <input type="range" min="1" max="360" class="slider" step="1" value={hue} onChange={e => setHue(e.target.value)} /> </div> <div> <input type="range" min="1" max="100" class="slider" step="1" value={saturation} onChange={e => setSaturation(e.target.value)} /> </div> <div> <input type="range" min="1" max="100" class="slider" step="1" value={lightness} onChange={e => setLightness(e.target.value)} /> </div> <div> <input type="range" min="0" max="1" class="slider" step="0.01" value={alpha} onChange={e => setAlpha(e.target.value)} /> </div> <div className="display-info"> <p>Hue {hue}</p> <p>Saturation {saturation}</p> <p>Lightness {lightness}</p> <p>Alpha {alpha}</p> </div> <button className="button" onClick={() => pickRandomColor()}> Can Do </button> </main> </section> </> ) }
/** MODULOS EXPRESS **/ let logger = require(process.cwd() + '/utils/logger.js'); //gerador de logs let express = require('express'); let Router = express.Router(); let security = require('../utils/security'); let utilsFunctions = require('../utils/functions'); /** CONEXAO DB **/ let db = require('../config/connect'); let mysql = require('mysql'); let Connection = mysql.createPool(db.config); /** METODOS DO CONTROLLER **/ Router.route('/') //LIST .get(function (req, res, next) { //EXECULTA CONSULTA logger.info('Iniciando pesquisa de empresas'); Connection.getConnection(function (err, sql) { if(err){ let msg = `Erro na conexão com o banco de dados, se o problema persistir consulte o suporte ténico!`; logger.warn(msg); res.status(400).json(msg); }else{ sql.query(`SELECT * FROM empresas ORDER BY name ASC`, function (error, rows, fields) { sql.release(); if (error) { let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(400).json(msg); }else { if (rows && rows.length > 0) { logger.info('Empresas carregadas'); res.status(200).send(rows); }else { logger.info('Lista de empresas vazia'); res.status(200).send([]); } } }); } }); }) //POST .post(function (req, res, next) { logger.info('Iniciando inclusão de empresa'); if(JSON.stringify(req.body) === '{}'){ let msg = `Nenhum dado foi enviado para inclusão`; logger.warn(msg); res.status(400).json(msg); }else{ //VERIFICANDO SE ITEM JA FOI CADASTRADO Connection.getConnection(function (err, sql) { if(err){ let msg = `Erro na conexão com o banco de dados, se o problema persistir consulte o suporte ténico!`; logger.warn(msg); res.status(400).json(msg); }else{ sql.query(`SELECT name FROM empresas WHERE name = '${req.body.nome}' OR email = '${req.body.email}' LIMIT 1`, function (error, rows, fields) { if (error) { sql.release(); let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(400).json(msg); }else { //SE NAO EXISTIR REGISTRO, INSERE if (rows.length === 0) { logger.info('Gerando senha de acesso'); let pass_user; if(req.body.senha){ pass_user = security.passGenerate(req.body.senha + security.passSegredo()) } logger.info('Gerando nome de usuário'); let nomeUser = req.body.nome; nomeUser = nomeUser.match(/\b(\w)/g); nomeUser = nomeUser.join(''); nomeUser = `${nomeUser}${Math.floor((Math.random() * 999) + 100)}`; let CAMPOS = { name: req.body.nome.toUpperCase(), email: req.body.email, user: nomeUser.toUpperCase(), pass: pass_user, logo: req.body.logomarca, created: utilsFunctions.getMoment('ymdh', Date.now()), updated: utilsFunctions.getMoment('ymdh', Date.now()) }; sql.query(`INSERT INTO empresas SET ?`, [CAMPOS], function (error, rows, fields) { sql.release(); if (error) { let msg = `Erro ao inserir item, se o problema persistir consulte o suporte técnico!`; logger.error(msg); res.status(400).json(msg); }else { let msg = `O cliente ${req.body.nome} foi cadastrado com sucesso!`; logger.info(msg); res.status(200).json(msg); } }); }else { sql.release(); let msg = `O item ${req.body.nome} já foi cadastrado!`; logger.warn(msg); res.status(200).json(msg); } } }); } }); } }); //ID Router.route('/:id') .get(function (req, res, next) { //EXECULTA CONSULTA logger.info(`Iniciando pesquisa de empresa: (${req.params.id})`); Connection.getConnection(function (err, sql) { if(err){ let msg = `Erro na conexão com o banco de dados, se o problema persistir consulte o suporte ténico!`; logger.warn(msg); res.status(400).json(msg); }else{ sql.query(`SELECT empresas.*, impressoras.name AS print_default FROM empresas, impressoras WHERE empresas.id = '${req.params.id}' AND impressoras.id = empresas.print_id LIMIT 1`, function (error, rows, fields) { sql.release(); if (error) { let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(400).json(msg); }else { if(rows){ logger.info(`Empresa carregada`); res.status(200).send(rows[0]); }else{ let msg = `Empresa não encontrada!`; logger.warn(msg); res.status(200).json(msg); } } }); } }); }) .put(function (req, res, next) { if(JSON.stringify(req.body) === '{}'){ let msg = `Nenhum dado foi enviado para inclusão`; logger.warn(msg); res.status(400).json(msg); }else{ logger.info(`Iniciando atualização de empresa: (${req.params.id})`); let CAMPOS = { name: req.body.nome.toUpperCase(), email: req.body.email, logo: req.body.logomarca, updated: utilsFunctions.getMoment('ymdh', Date.now()) }; //EXECULTA CONSULTA Connection.getConnection(function (err, sql) { if(err){ let msg = `Erro na conexão com o banco de dados, se o problema persistir consulte o suporte ténico!`; logger.warn(msg); res.status(400).json(msg); }else{ sql.query(`UPDATE empresas SET ? WHERE id = '${req.params.id}' LIMIT 1`, [CAMPOS], function (error, rows, fields) { sql.release(); if (error) { let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(400).json(msg); }else { let msg = `O cliente ${req.body.nome} foi atualizado com sucesso!`; logger.info(msg); res.status(200).json(msg); } }); } }); } }) //DESATIVAR ITEM Router.route('/:id/deactivate') .get(function (req, res, next) { //EXECULTA CONSULTA logger.info(`Iniciando bloqueio de empresa: (${req.params.id})`); Connection.getConnection(function (err, sql) { if(err){ let msg = `Erro na conexão com o banco de dados, se o problema persistir consulte o suporte ténico!`; logger.warn(msg); res.status(400).json(msg); }else{ sql.query(`UPDATE empresas SET sts = 'INATIVO' WHERE id = '${req.params.id}' LIMIT 1`, function (error, rows, fields) { sql.release(); if (error) { let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(400).json(msg); }else { let msg = `O item foi bloqueado com sucesso!`; logger.info(msg); res.status(200).json(msg); } }); } }); }); //REATIVANDO ITEM Router.route('/:id/activate') .get(function (req, res, next) { //EXECULTA CONSULTA logger.info(`Iniciando reativação de empresa: (${req.params.id})`); Connection.getConnection(function (err, sql) { if(err){ let msg = `Erro na conexão com o banco de dados, se o problema persistir consulte o suporte ténico!`; logger.warn(msg); res.status(400).json(msg); }else{ sql.query(`UPDATE empresas SET sts = 'ATIVO', deleted = false WHERE id = '${req.params.id}' LIMIT 1`, function (error, rows, fields) { sql.release(); if (error) { let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(400).json(msg); }else { let msg = `O item foi reativado com sucesso!`; logger.info(msg); res.status(200).json(msg); } }); } }); }); //LOGAR Router.route('/auth/user') .post(function (req, res, next) { //EXECULTA CONSULTA logger.info(`Iniciando autenticação de empresa`); Connection.getConnection(function (err, sql) { if(err){ let msg = `Erro na conexão com o banco de dados, se o problema persistir consulte o suporte ténico!`; logger.warn(msg); res.status(503).json(msg); }else{ sql.query(`SELECT empresas.*, impressoras.name AS print_default FROM empresas LEFT JOIN impressoras ON empresas.print_id = impressoras.id WHERE empresas.user = '${req.body.usuario}' AND empresas.sts = 'ATIVO' AND empresas.deleted = false AND empresas.count_connect <= 10 LIMIT 1`, function (error, rows, fields) { sql.release(); if (error) { let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(503).json(msg); } else { if (rows && rows.length > 0) { logger.info(`Validando senha de empresa`); isValid = security.passValid(req.body.senha + security.passSegredo(), rows[0].pass); if (isValid) { logger.info(`Empresa logada`); res.status(200).send(rows[0]); } else { let msg = `Senha inválida!`; logger.warn(msg); res.status(503).json(msg); } } else { let msg = `Usuário inválido ou bloqueado pelo sistema!`; logger.warn(msg); res.status(503).json(msg); } } }); } }); }); //LOGAR Router.route('/auth/token/:token') .get(function (req, res, next) { //EXECULTA CONSULTA logger.info(`Iniciando autenticação de empresa por token`); Connection.getConnection(function (err, sql) { if(err){ let msg = `Erro na conexão com o banco de dados, se o problema persistir consulte o suporte ténico!`; logger.warn(msg); res.status(400).json(msg); }else{ sql.query(`SELECT id FROM empresas WHERE id = '${req.params.token}' AND sts = 'ATIVO' AND deleted = false AND count_connect <= 10 LIMIT 1`, function (error, rows, fields) { sql.release(); if (error) { let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(400).json(msg); }else { if (rows && rows.length > 0) { logger.info(`Token de empresa válido`); res.status(200).send(true); }else{ logger.warn(`Token de empresa inválido`); res.status(200).send(false); } } }); } }); }); //ALTERAR SENHA Router.route('/:id/password') .put(function (req, res, next) { //EXECULTA CONSULTA logger.info(`Iniciando alteração de senha de empresa`); Connection.getConnection(function (err, sql) { if(err){ let msg = `Erro na conexão com o banco de dados, se o problema persistir consulte o suporte ténico!`; logger.warn(msg); res.status(400).json(msg); }else{ sql.query(`SELECT pass FROM empresas WHERE id = '${req.params.id}' LIMIT 1`, function (error, rows, fields) { if (error) { sql.release(); let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(400).json(msg); }else { if(rows){ logger.info(`Verificando senha atual`); isValid = security.passValid(req.body.senha_atual + security.passSegredo(), rows[0].pass); if(isValid){ logger.info(`Gerando nova senha de acesso`); let pass_user; if(req.body.senha){ pass_user = security.passGenerate(req.body.senha + security.passSegredo()) } sql.query(`UPDATE empresas SET pass = '${pass_user}' WHERE id = '${req.params.id}' LIMIT 1`, function (error, rows, fields) { sql.release(); if (error) { let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(400).json(msg); }else { let msg = `Senha alterada com sucesso!`; logger.info(msg); res.status(200).json(msg); } }); }else{ sql.release(); let msg = `Senha atual não confere!`; logger.warn(msg); res.status(503).json(msg); } }else{ sql.release(); let msg = `Empresa não encontrada!`; logger.warn(msg); res.status(200).json(msg); } } }); } }); }); module.exports = Router;
const express = require('express'); const asyncWrapper = require('../utils/asyncWrapper'); const router = express.Router(); function create({ projectService }) { router.get('/', asyncWrapper(async(req, res) => { const projects = await projectService.getAllProjects(); res.json(projects); })); // TODO: Install middleware to validate the input router.post('/', asyncWrapper(async(req, res) => { const project = req.body; await projectService.createProject(project); // TODO: Fix the response res.json({}); })); return router; } module.exports.create = create;
var RandomTotal = ""; var totalScore = 0; var wins = 0; var lossess = 0; var crystal1 = ""; var crystal2 = ""; var crystal3 = ""; var crystal4 = ""; function getRandom(min, max) { return Math.floor(Math.random() * (max - min) + min); }; $("CurrentScore").innerHTML = totalScore; function game() { if (totalScore === RandomTotal) { wins++; alert('You win'); $('#winner').html(wins); newGame(); } else if (totalScore > RandomTotal) { lossess++; alert("you Lose"); $('#loser').html(lossess); newGame(); } }; function newGame() { RandomTotal = getRandom(19, 120); crystal1 = getRandom(1, 12); crystal2 = getRandom(1, 12); crystal3 = getRandom(1, 12); crystal4 = getRandom(1, 12); totalScore = 0; $('#TotalRandom').html(RandomTotal); $('#CurrentScore').html(totalScore); }; newGame(); $('#crystal111').on('click', function () { crystal1 = getRandom(1, 12); totalScore = crystal1 + totalScore; $("#CurrentScore").html(totalScore); game(); console.log(crystal1); console.log(totalScore); }); $('#crystal222').on('click', function () { crystal2 = getRandom(1, 12); totalScore = crystal2 + totalScore; $('#CurrentScore').html(totalScore); game(); console.log(crystal2); console.log(totalScore); }); $('#crystal333').on('click', function () { crystal3 = getRandom(1, 12); totalScore = crystal3 + totalScore; $('#CurrentScore').html(totalScore); game(); console.log(crystal3); console.log(totalScore); }); $('#crystal444').on('click', function () { crystal4 = getRandom(1, 12); totalScore = crystal4 + totalScore; $('#CurrentScore').html(totalScore); game(); console.log(crystal4); console.log(totalScore); });
export const addItemToCart=(cartItems=[], cartItemToAdd)=>{ const exists = cartItems.find( cartItem => cartItem.id === cartItemToAdd.id ); if(exists){ return cartItems.map( cartItem=> cartItem.id===cartItemToAdd.id ?{...cartItem,quantity:cartItem.quantity+1} :cartItem ); }; return[...cartItems,{...cartItemToAdd,quantity:1}]; } export const clearFromCart=(cartItems,cartItemToRemove)=>{ let filteredCartItems = cartItems.filter( cartItem => cartItem.id!==cartItemToRemove.id ) return filteredCartItems; }; export const removeItemFromCart=(cartItems=[], cartItemToRemove)=>{ const existingItem = cartItems.find( cartItem => cartItem.id === cartItemToRemove.id ); if(existingItem){ if(existingItem.quantity===1){ let filteredCartItems = cartItems.filter( cartItem => cartItem.id!==cartItemToRemove.id ) return filteredCartItems; } return cartItems.map( cartItem=> cartItem.id===cartItemToRemove.id ?{...cartItem,quantity:cartItem.quantity-1} :cartItem ); }; }
/** * Created by matheus on 16/01/17. */ function CompletedUserDao(connection) { this._connection = connection; } CompletedUserDao.prototype.BuscarAlunosMdl_Modules_completion = function (callback) { this._connection.query('Select * from mdl_course_modules_completion where coursemoduleid = 123', callback); // ,\"completed\" as status,\"Enviando dados ao VO\" as resposta } var existeAluno; // Select from completed left join mdl_user on userid = mdl_user.id where coursemoduleid = 123 CompletedUserDao.prototype.BuscarAlunosCompleted = function (id, callback) { this._connection.query('Select * from completed where userid = ?', id, callback); } CompletedUserDao.prototype.InserirAlunoCompleted = function (dados, callback) { this._connection.query('INSERT INTO completed SET ?', dados, callback); } CompletedUserDao.prototype.BuscarAlunoPorId = function (id, callback) { this._connection.query('select username, email,\"A\" as status from mdl_user where id = ?', id, callback); } module.exports = function () { return CompletedUserDao; }
const createBox = require("./box"); const createBoard = (boardSize, moves) => { const boardData = []; const boxCount = Math.pow(boardSize, 2); for (let index = 0; index < boxCount; index++) { boardData.push(createBox(index, moves, boardSize)); } return boardData; }; module.exports = createBoard;
import React, {useContext, useEffect} from 'react'; import {View, LogBox} from 'react-native'; import {NavigationEvents} from 'react-navigation'; import AuthFormIN from '../components/AuthFormSignIN'; import {Context} from '../context/AuthContext'; const SigninScreen = () => { const {state, signin, clearErrorMessage} = useContext(Context); useEffect(() => { LogBox.ignoreLogs(['Animated: `useNativeDriver`']); }, []); return ( <View> <NavigationEvents onWillFocus={clearErrorMessage} /> <AuthFormIN errorMessage={state.errorMessage} onSubmit={signin} submitButtonText="Login" /> </View> ); }; SigninScreen.navigationOptions = { header: () => false, }; export default SigninScreen;
console.log(a); var a = 1; // undefined // hoisting moves the declaration before the console.log(); // but it does not move the assignment // so variable a is set to undefined // the value gets logged before it gets assigned to 1
/** * @param {number[]} A * @return {boolean} */ var isMonotonic = function(A) { var mon = 0, isMon = true; if (!A || A.length <= 1) return true; for (var i = 1; i < A.length; i++) { var diff = A[i] - A[i-1]; if (!mon) { if (diff !== 0) { mon = diff > 0 ? 1 : -1; } } else { if (diff === 0) { continue; } var cur = diff > 0 ? 1 : -1; if (mon !== cur && cur !==0) { return false; } } } return true; }; console.log(isMonotonic([1,2,2,3])); console.log(isMonotonic([6,5,4,4])); console.log(isMonotonic([1,3,2])); console.log(isMonotonic([1,2,4,5])); console.log(isMonotonic([1,1,1]));
import React from 'react'; import s from './Message.module.css'; function Message(props) { let author = props.message.from; let date = props.message.data; let text = props.message.text; return ( <div className={s.message}> {author + " " + date + " " + text} </div> ); } export default Message;
labPickup = { pickup: function(creep) { /* Determine priority based on: 0. Terminal needs more energy? Grab energy 1. Any exit labs full? Deplete lab 2. Any source labs empty? Find and pick up from terminal/storage */ // var terminal = Game.getObjectById(creep.memory.terminal); // var storage = Game.getObjectById(creep.memory.storage); // var resourceType = creep.getResourceType(); // if(terminal.store[RESOURCE_ENERGY] < 100000) { // var result = creep.withdraw(structure, resourceType); // if( == ERR_NOT_IN_RANGE){ // creep.moveTo(structure, {ignoreCreeps: false}); // } else if (result != OK) { // return false; // } // } } } module.exports = labPickup;
define(['marionette', 'jquery', 'compiledTemplates'], function ( Marionette, $, Templates) { 'use strict'; /** * This is a View for AddressPopupView * * @class AddressPopupView * @return AddressPopupView Object */ var HomeItemView = Marionette.ItemView.extend({ template: Templates.HomeItemTemplate }); return HomeItemView; });
Ext.define('gigade.Paper', { extend: 'Ext.data.Model', fields: [ { name: "paperID", type: "int" }, { name: "paperName", type: "string" }] }); var PaperStore = Ext.create('Ext.data.Store', { model: 'gigade.Paper', autoLoad: true, proxy: { type: 'ajax', url: '/Paper/GetPaperList?isPage=false', actionMethods: 'post', reader: { type: 'json', root: 'data' } } }); var frontCateStore = Ext.create('Ext.data.TreeStore', { autoLoad: true, proxy: { type: 'ajax', url: '/ProductList/GetFrontCatagory', actionMethods: 'post' }, root: { expanded: true, checked: false, children: [ ] } }); frontCateStore.load(); function editFunction(RowID, PromoAmountTrialStore) { //前台分類store SiteStore.load(); VipGroupStore.load(); var conditionID = ""; //保存條件id var condiCount = 0; var linkPath = "http://www.gigade100.com/promotion/combo_promotion.php?event_id="; //保存图片链接的地址 var currentPanel = 0; var Trial_id = ""; var websiteID = 1; var event_type = "T1"; var Event_id = ""; var promoID = ""; var prodCateID = ""; if (RowID != null) { Trial_id = RowID.data.id; event_type = RowID.data.event_type; Event_id = RowID.data.event_id; websiteID = RowID.data.site == "" ? 1 : RowID.data.site; conditionID = RowID.data.condition_id; } var navigate = function (panel, direction) { var layout = panel.getLayout(); if ('next' == direction) { if (currentPanel == 0) {//首頁時進行第一步保存 var ffrom = firstForm.getForm(); if (!RowID && Event_id == "") { if (ffrom.isValid()) { if (Ext.htmlEncode(Ext.getCmp("event_type").getValue().eventtype) == 1) { event_type = "T1"; } else if (Ext.htmlEncode(Ext.getCmp("event_type").getValue().eventtype) == 2) { event_type = "T2"; } Ext.Ajax.request({ url: '/PromotionsAmountTrial/SaveTrial', method: 'post', params: { name: Ext.getCmp("name").getValue(), event_type: Ext.htmlEncode(Ext.getCmp("event_type").getValue().eventtype), paper_id: Ext.htmlEncode(Ext.getCmp('paper_id').getValue()), start_date: Ext.htmlEncode(Ext.getCmp('start_date').getRawValue()), end_date: Ext.htmlEncode(Ext.getCmp('end_date').getRawValue()), event_desc: Ext.htmlEncode(Ext.getCmp('event_desc').getValue()) }, success: function (form, action) { var result = Ext.decode(form.responseText); if (result.success) { Trial_id = result.id; Event_id = result.event_id; Ext.getCmp("url").setValue(linkPath + Event_id); layout[direction](); currentPanel++; if (!layout.getNext()) { Ext.getCmp('move-next').hide(); } else { Ext.getCmp('move-prev').show(); Ext.getCmp('move-next').setText(NEXT_MOVE); } } else { Ext.Msg.alert(INFORMATION, FAILURE); } }, failure: function () { Ext.Msg.alert(INFORMATION, FAILURE); } }); } else { Ext.getCmp('move-prev').hide(); return; } } else {//編輯 if (Event_id.substr(0, 2) == "T1") { Ext.getCmp("eatdisplay").show(); Ext.getCmp("usedisplay").hide(); } else { Ext.getCmp("eatdisplay").hide(); Ext.getCmp("usedisplay").show(); } if (ffrom.isValid()) { Ext.getCmp('move-prev').show(); layout[direction](); currentPanel++; } } } else { var forms = secondForm.getForm(); if (Event_id.substr(0, 2) == "T1") { Ext.getCmp("eatdisplay").show(); Ext.getCmp("usedisplay").hide(); } else { Ext.getCmp("eatdisplay").hide(); Ext.getCmp("usedisplay").show(); } if (forms.isValid()) { layout[direction](); currentPanel++; Ext.getCmp('move-prev').show(); Ext.getCmp('move-next').hide(); } } } else { layout[direction](); currentPanel--; Ext.getCmp('move-prev').show(); Ext.getCmp('move-next').show(); if (currentPanel == 0) { Ext.getCmp('move-prev').hide(); } } }; var firstForm = Ext.widget('form', { id: 'editFrm1', plain: true, frame: true, defaultType: 'textfield', layout: 'anchor', defaults: { anchor: "95%", msgTarget: "side" }, items: [ { fieldLabel: '<span style="font-size:12px; color:#F00;">※</span>' + ACTIVENAME, xtype: 'textfield', id: 'name', name: 'name', allowBlank: false }, { xtype: 'radiogroup', hidden: false, id: 'event_type', name: 'event_type', fieldLabel: '<span style="font-size:12px; color:#F00;">※</span>' + ACTIVETYPE, colName: 'eventtype', width: 400, defaults: { name: 'eventtype', margin: '0 8 0 0' }, columns: 2, vertical: true, items: [ { boxLabel: TRYEAT, id: 'tryeat', inputValue: '1', checked: true }, { boxLabel: TRYUSE, id: 'tryuse', inputValue: '2' } ] }, { xtype: 'textfield', fieldLabel: '<span style="font-size:12px; color:#F00;">※</span>' + WEBURL, name: 'url', id: 'url', submitValue: true, vtype: 'url', hidden: true, editable: false, readOnly: true }, { xtype: 'combobox', //Wibset fieldLabel: '<span style="font-size:12px; color:#F00;">※</span>' + PAPER, id: 'paper_id', name: 'paper_id', hiddenName: 'paper_id', colName: 'paper_id', allowBlank: false, editable: false, store: PaperStore, displayField: 'paperName', valueField: 'paperID', typeAhead: true, lastQuery: '', forceSelection: false, emptyText: SELECT, queryMode: 'local' }, { xtype: "datetimefield", fieldLabel: '<span style="font-size:12px; color:#F00;">※</span>' + BEGINTIME, editable: false, id: 'start_date', name: 'start_date', anchor: '95%', format: 'Y-m-d H:i:s', time: { hour: 00, min: 00, sec: 00 },//add by jiaohe0625j width: 150, allowBlank: false, submitValue: true, //value: Tomorrow(), value: new Date(Tomorrow().setMonth(Tomorrow().getMonth() - 1)),//modify by jiaohe0625j listeners: { select: function (a, b, c) { var start = Ext.getCmp("start_date"); var end = Ext.getCmp("end_date"); if (end.getValue() < start.getValue()) { //Ext.Msg.alert(INFORMATION, TIMETIP); end.setValue(setNextMonth(start.getValue(), 1));//add by jiaohe0625j } } } }, { xtype: "datetimefield", fieldLabel: '<span style="font-size:12px; color:#F00;">※</span>' + ENDTIME, editable: false, id: 'end_date', anchor: '95%', name: 'end_date', format: 'Y-m-d H:i:s', time: { hour: 23, min: 59, sec: 59 },//add by jiaohe0625j allowBlank: false, submitValue: true, //value: new Date(Tomorrow().setMonth(Tomorrow().getMonth() + 1)), value: setNextMonth(Tomorrow(), 0),//modify by jiaohe0625j listeners: { select: function (a, b, c) { var start = Ext.getCmp("start_date"); var end = Ext.getCmp("end_date"); var s_date = new Date(start.getValue()); var now_date = new Date(end.getValue()); //if (end.getValue() < start.getValue()) { // Ext.Msg.alert(INFORMATION, TIMETIP); //} //var ttime = now_date; //ttime = new Date(ttime.setMonth(now_date.getMonth())); //ttime = new Date(ttime.setMinutes(59)); //ttime = new Date(ttime.setSeconds(59)); //ttime = new Date(ttime.setHours(23)); //end.setValue(ttime); //modify by jiaohe0625j if (end.getValue() < start.getValue()) { start.setValue(setNextMonth(end.getValue(), -1)); } } } }, { fieldLabel: ACTIVEDESC, xtype: 'textareafield', anchor: '95%', id: 'event_desc', name: 'event_desc' } ] }); //第二個form var secondForm = Ext.widget('form', { id: 'editFrm2', frame: true, plain: true, defaultType: 'textfield', layout: 'anchor', autoScroll: true, defaults: { anchor: "95%", msgTarget: "side" }, items: [ { xtype: 'fieldset', defaults: { labelWidth: 89, anchor: '95%', layout: { type: 'hbox' } }, items: [ { //會員群組和會員條件二擇一 xtype: 'fieldcontainer', fieldLabel: VIPGROUP, combineErrors: true, layout: 'hbox', defaults: { width: 120, hideLabel: true }, items: [ { xtype: 'radiofield', name: 'us', inputValue: "u_group", id: "us1", width: 90, checked: true, listeners: { change: function (radio, newValue, oldValue) { var rdo_group = Ext.getCmp("us1"); var rdo_groppset = Ext.getCmp("us2"); var com_group = Ext.getCmp("group_id"); var btn_group = Ext.getCmp("condi_set"); if (newValue) { btn_group.setDisabled(true); com_group.setValue("0"); com_group.setDisabled(false); com_group.allowBlank = false; Ext.getCmp("userShow").hide(); } } } }, { xtype: 'combobox', //會員群組 editable: false, hidden: false, id: 'group_id', //allowBlank: false, lastQuery: '', name: 'group_name', hiddenName: 'group_id', store: VipGroupStore, displayField: 'group_name', valueField: 'group_id', typeAhead: true, forceSelection: false, value: "0" } ] }, { xtype: 'fieldcontainer', fieldLabel: VIPCONDITION, combineErrors: true, layout: 'hbox', defaults: { width: 120, hideLabel: true }, items: [ { xtype: 'radiofield', name: 'us', width: 90, inputValue: "u_groupset", id: "us2", listeners: { change: function (radio, newValue, oldValue) { var rdo_group = Ext.getCmp("us1"); var rdo_groppset = Ext.getCmp("us2"); var com_group = Ext.getCmp("group_id"); var btn_group = Ext.getCmp("condi_set"); if (newValue) { com_group.setValue("0"); com_group.allowBlank = true; com_group.setValue(""); com_group.isValid(); btn_group.setDisabled(false); com_group.setDisabled(true); if (condition_id != "") { Ext.getCmp("userShow").show(); } } } } }, { xtype: 'button', text: CONDINTION, disabled: true, allowBlank: false, id: 'condi_set', colName: 'condi_set', handler: function () { if (conditionID != "") { showUserSetForm(event_type, conditionID, "userInfo"); } else { showUserSetForm(event_type, condition_id, "userInfo"); } } } ] }, { xtype: 'fieldset', title: USERDETAIL, defaultType: 'textfield', id: 'userShow', layout: 'anchor', width: '100%', hidden: true, items: [ { xtype: 'textareafield', name: 'textarea1', id: 'userInfo', readOnly: true, anchor: '100%', value: ShowConditionData(conditionID, "userInfo"), listeners: { change: function (textarea, newValue, oldValue) { var textArea = Ext.getCmp("userInfo"); var userShow = Ext.getCmp("userShow"); if (newValue != "" && oldValue != "") { userShow.show(); } } } }] } ] }, { xtype: 'fieldset', defaults: { anchor: '95%', layout: { type: 'hbox', defaultMargins: { top: 50, bottom: 0 } } }, items: [ { xtype: 'radiogroup', hidden: false, id: 'count_by', name: 'count_by', fieldLabel: NUMBERLIMIT, colName: 'count_by', width: 400, defaults: { name: 'count_by', margin: '0 8 0 0' }, columns: 3, vertical: true, items: [ { boxLabel: NOTHING, name: 'count_by', id: 'rdoNoTimesLimit', inputValue: "1", listeners: { change: function (radio, newValue, oldValue) { var numLimit = Ext.getCmp("num_limit"); var giftMundane = Ext.getCmp("gift_mundane"); if (newValue) { numLimit.setValue(0); numLimit.setDisabled(true); giftMundane.setValue(0); giftMundane.setDisabled(true); } } } }, { boxLabel: BYORDER, name: 'count_by', id: 'rdoByOrder', inputValue: "2", listeners: { change: function (radio, newValue, oldValue) { var numLimit = Ext.getCmp("num_limit"); var giftMundane = Ext.getCmp("gift_mundane"); if (newValue) { numLimit.setValue(1); numLimit.setDisabled(false); giftMundane.setValue(1); giftMundane.setDisabled(false); } } } }, { boxLabel: BYMEMBER, name: 'count_by', id: 'rdoByMember', inputValue: "3", checked: true, listeners: { change: function (radio, newValue, oldValue) { var numLimit = Ext.getCmp("num_limit"); var giftMundane = Ext.getCmp("gift_mundane"); if (newValue) { numLimit.setValue(1); numLimit.setDisabled(false); giftMundane.setValue(1); giftMundane.setDisabled(false); } } } } ] }, { xtype: 'fieldcontainer', combineErrors: true, layout: 'hbox', items: [ { xtype: 'displayfield', value: '試吃次數:', id: 'eatdisplay', width: 105 }, { xtype: 'displayfield', value: '試用次數:', id: 'usedisplay', hidden: true, width: 105 }, { xtype: 'numberfield', name: 'num_limit', id: 'num_limit', minValue: 0, value: 1 } ] }, { xtype: 'numberfield', fieldLabel: '限量件數', name: 'gift_mundane', id: 'gift_mundane', minValue: 0, value: 1 }, { xtype: 'radiogroup', hidden: false, id: 'repeat', name: 'repeat', fieldLabel: '是否重複送', colName: 'repeat', defaults: { name: 'IsRepeat', margin: '0 8 0 0' }, columns: 2, vertical: true, items: [ { boxLabel: ONLYONE, id: 'OnlyOne', inputValue: '0', checked: true }, { boxLabel: EVERY, id: 'Every', inputValue: '1' } ] } ] }, { xtype: 'combobox', fieldLabel: YSCLASS, store: YunsongStore, queryMode: 'local', allowBlank: false, editable: false, id: 'freight_type', name: 'freight_type', lastQuery: '', hiddenName: 'typeName', colName: 'typeName', displayField: 'type_name', valueField: 'type_id', typeAhead: true, forceSelection: false, emptyText: SELECT, value: 0 }, { xtype: 'radiogroup', hidden: false, id: 'device_name', name: 'device_name', fieldLabel: DEVICE, colName: 'deviceName', width: 400, defaults: { name: 'deviceName', margin: '0 8 0 0' }, columns: 3, vertical: true, items: [ { boxLabel: DEVICE_1, id: 'bufen', inputValue: '0', checked: true }, { boxLabel: DEVICE_2, id: 'pc', inputValue: '1' }, { boxLabel: DEVICE_3, id: 'mobilepad', inputValue: '4' } ] }, { xtype: 'combobox', //Wibset allowBlank: false, editable: false, fieldLabel: WEBSITESET, hidden: false, id: 'site', name: 'website', hiddenName: 'website', colName: 'site', store: SiteStore, displayField: 'Site_Name', valueField: 'Site_Id', typeAhead: true, forceSelection: false, queryMode: 'local', value: 1, multiSelect: true, //多選 emptyText: SELECT, listeners: { select: function (a, b, c) { websiteID = Ext.htmlEncode(Ext.getCmp('site').getValue()); } } } ] }); var thirdForm = Ext.widget('form', { id: 'editFrm3', frame: true, plain: true, url: ' /PromotionsAmountTrial/UpdateTrial', defaultType: 'textfield', layout: 'anchor', defaults: { anchor: "95%", msgTarget: "side" }, items: [ { xtype: 'fieldcontainer', defaults: { labelWidth: 80 }, combineErrors: true, layout: 'hbox', items: [ { xtype: 'numberfield', fieldLabel: '<span style="font-size:12px; color:#F00;">※</span>' + "活動商品", allowBlank: true, readOnly: true, id: 'product_id', name: 'product_id', width: 140, minValue: 0 }, { xtype: 'numberfield', fieldLabel: '<span style="font-size:12px; color:#F00;">※</span>' + "販售商品", allowBlank: false, readOnly: true, id: 'sale_product_id', name: 'sale_product_id', width: 140, margin: '0 5 0 5', minValue: 0 }, {//商品設定 xtype: 'button', text: PRODSELECT, id: 'btnProdId', name: 'btnProdId', width: 60, minValue: 0, handler: function () { var cate_id = Ext.getCmp('category_id'); var product_id = Ext.getCmp('product_id'); var sale_product_id = Ext.getCmp('sale_product_id'); var sale_product_name = Ext.getCmp('sale_product_name'); CategoryProductShow(websiteID, cate_id, product_id, sale_product_id, sale_product_name); } } ] }, {//商品名稱 xtype: 'textfield', fieldLabel: '<span style="font-size:12px; color:#F00;">※</span>' + PRODNAME, allowBlank: false, id: 'product_name', name: 'product_name', labelWidth: 80 }, { xtype: 'displayfield', fieldLabel: "販售商品名稱", allowBlank: true, readOnly: true, hidden: true, allowBlank: false, id: 'sale_product_name', name: 'sale_product_name', width: 180, labelWidth: 80 }, {//類別id xtype: 'textfield', fieldLabel: CATEGORYID, editable: false, hidden: true, id: 'category_id', name: 'category_id', minValue: 0, value: 0, labelWidth: 80, readOnly: true }, {//類別名稱 xtype: 'displayfield', fieldLabel: CATEGORYNAME, editable: false, width: 180, labelWidth: 80, hidden: true, id: 'category_name', name: 'category_name' }, {//品牌id xtype: 'textfield', fieldLabel: BRANDID, editable: false, hidden: true, labelWidth: 80, id: 'brand_id', name: 'brand_id', minValue: 0, value: 0, readOnly: true }, {//品牌名稱 xtype: 'displayfield', fieldLabel: BRANDNAME, hidden: true, editable: false, width: 200, labelWidth: 80, id: 'brand_name', name: 'brand_name' }, {//商品圖片路徑 xtype: 'displayfield', fieldLabel: PRODIMGFILE, hidden: true, editable: false, width: 200, id: 'prod_file', name: 'prod_file' }, {//商品图片 xtype: 'filefield', name: 'product_img', id: 'product_img', fieldLabel: PRODIMG, labelWidth: 80, msgTarget: 'side', anchor: '95%', buttonText: SELECT_IMG, submitValue: true, allowBlank: true, fileUpload: true, listeners: { change: function (field, value) { if (RowID != null) { if (value.indexOf("\:\\") > 0 || value != RowID.data.product_img) { Ext.getCmp("prod_file").setValue(""); } } else { Ext.getCmp("prod_file").setValue(""); } } } }, {//活动小图片 xtype: 'filefield', name: 'event_img_small', id: 'event_img_small', fieldLabel: EVENTIMGSMALL, labelWidth: 80, msgTarget: 'side', anchor: '95%', buttonText: SELECT_IMG, submitValue: true, allowBlank: true, fileUpload: true }, {//活动图片 xtype: 'filefield', name: 'event_img', id: 'event_img', fieldLabel: EVENTEDM, labelWidth: 80, msgTarget: 'side', anchor: '95%', buttonText: SELECT_IMG, submitValue: true, allowBlank: true, fileUpload: true }, { xtype: "numberfield", fieldLabel: '<span style="font-size:12px; color:#F00;">※</span>' + MARKETPRICE, id: 'market_price', name: 'market_price', allowBlank: false, minValue: 0, maxValue: 65535, value: 0, submitValue: true }, { xtype: "numberfield", fieldLabel: '<span style="font-size:12px; color:#F00;">※</span>' + SHOWNUMBER, id: 'show_number', name: 'show_number', allowBlank: false, minValue: 0, maxValue: 65535, value: 0, submitValue: true }, { xtype: "numberfield", fieldLabel: '<span style="font-size:12px; color:#F00;">※</span>' + APPLYLIMIT, id: 'apply_limit', name: 'apply_limit', allowBlank: false, minValue: 0, maxValue: 65535, value: 0, submitValue: true }, { xtype: "numberfield", fieldLabel: '<span style="font-size:12px; color:#F00;">※</span>' + APPLYSUM, id: 'apply_sum', name: 'apply_sum', allowBlank: false, minValue: 0, value: 0, submitValue: true } ], buttons: [ { text: SAVE, formBind: true, disabled: true, id: 'pSave', handler: function () { var form = this.up('form').getForm(); if (condition_id == "" && Ext.getCmp("group_id").getValue() == null) { Ext.Msg.alert(INFORMATION, USERCONDITIONERROR); return; } if (Ext.getCmp("product_id").getValue() == "" || Ext.getCmp("product_id").getValue() == null || Ext.getCmp("product_id").getValue() == 0) { Ext.Msg.alert(INFORMATION, "請選擇商品"); return; } if (Ext.getCmp("apply_limit").getValue() < Ext.getCmp("apply_sum").getValue()) { Ext.Msg.alert(INFORMATION, APPLYTIP); return; } if (form.isValid()) { this.disable(); form.submit({ params: { isEdit: RowID, trial_id: Trial_id, name: Ext.getCmp("name").getValue(), event_type: Ext.htmlEncode(Ext.getCmp("event_type").getValue().eventtype), event_url: Ext.htmlEncode(Ext.getCmp('url').getValue()), paper_id: Ext.htmlEncode(Ext.getCmp('paper_id').getValue()), start_date: Ext.htmlEncode(Ext.getCmp('start_date').getRawValue()), end_date: Ext.htmlEncode(Ext.getCmp('end_date').getRawValue()), event_desc: Ext.htmlEncode(Ext.getCmp('event_desc').getValue()), group_id: Ext.htmlEncode(Ext.getCmp('group_id').getValue()), condition_id: condition_id, count_by: Ext.htmlEncode(Ext.getCmp('count_by').getValue().count_by), numLimit: Ext.htmlEncode(Ext.getCmp('num_limit').getValue()), gift_mundane: Ext.htmlEncode(Ext.getCmp('gift_mundane').getValue()), IsRepeat: Ext.htmlEncode(Ext.getCmp('repeat').getValue().IsRepeat), freight_type: Ext.htmlEncode(Ext.getCmp('freight_type').getValue()), device_name: Ext.htmlEncode(Ext.getCmp("device_name").getValue().deviceName), site: Ext.htmlEncode(Ext.getCmp('site').getValue()), sale_product_id: Ext.htmlEncode(Ext.getCmp('sale_product_id').getValue()), product_id: Ext.htmlEncode(Ext.getCmp('product_id').getValue()), product_name: Ext.htmlEncode(Ext.getCmp('product_name').getValue()), category_id: Ext.htmlEncode(Ext.getCmp('category_id').getValue()), brand_id: Ext.htmlEncode(Ext.getCmp('brand_id').getValue()), market_price: Ext.htmlEncode(Ext.getCmp('market_price').getValue()), show_number: Ext.htmlEncode(Ext.getCmp('show_number').getValue()), apply_limit: Ext.htmlEncode(Ext.getCmp('apply_limit').getValue()), apply_sum: Ext.htmlEncode(Ext.getCmp('apply_sum').getValue()), prod_file: Ext.htmlEncode(Ext.getCmp('prod_file').getValue()) }, success: function (form, action) { var result = Ext.decode(action.response.responseText); if (result.success) { Ext.Msg.alert(INFORMATION, SUCCESS); PromoAmountTrialStore.load(); editWin.close(); } else { Ext.Msg.alert(INFORMATION, FAILURE); } }, failure: function (form, action) { var result = Ext.decode(action.response.responseText); if (result.msg.toString() == "1") { Ext.Msg.alert(INFORMATION, PHOTOSIZE); } else if (result.msg.toString() == "2") { Ext.Msg.alert(INFORMATION, PHOTOTYPE); } else if (result.msg.toString() == "3") { Ext.Msg.alert(INFORMATION, USERCONDIERROR); } else { Ext.Msg.alert(INFORMATION, FAILURE); } } }); } } } ] }); var allpan = new Ext.panel.Panel({ width: 400, layout: 'card', border: 0, bodyStyle: 'padding:0px', defaults: { border: false }, bbar: [ { id: 'move-prev', text: PREV_MOVE, hidden: true, handler: function (btn) { navigate(btn.up("panel"), "prev"); } }, '->', // 一个长间隔, 使两个按钮分布在两边 { id: 'move-next', text: NEXT_MOVE, margins: '0 5 0 0', handler: function (btn) { navigate(btn.up("panel"), "next"); } } ], items: [firstForm, secondForm, thirdForm] }); var editWin = Ext.create('Ext.window.Window', { title: ACTIVITY, iconCls: RowID ? "icon-user-edit" : "icon-user-add", width: 410, y: 100, layout: 'fit', items: [allpan], constrain: true, //束縛 closeAction: 'destroy', modal: true, closable: false, tools: [ { type: 'close', qtip: CLOSEFORM, handler: function (event, toolEl, panel) { Ext.MessageBox.confirm(CONFIRM, IS_CLOSEFORM, function (btn) { if (btn == "yes") { editWin.destroy(); } else { return false; } }); } }], listeners: { 'show': function () { if (RowID) { firstForm.getForm().loadRecord(RowID); secondForm.getForm().loadRecord(RowID); thirdForm.getForm().loadRecord(RowID); initForm(RowID); } else { firstForm.getForm().reset(); secondForm.getForm().reset(); thirdForm.getForm().reset(); } } } }); editWin.show(); function initForm(row) { //site賦值 if (row.data.site != "") { var siteIDs = row.data.site.toString().split(','); var combobox = Ext.getCmp('site'); //var store = combobox.store; var arrTemp = new Array(); for (var i = 0; i < siteIDs.length; i++) { //arrTemp.push(store.getAt(store.find("Site_Id", siteIDs[i]))); arrTemp.push(siteIDs[i]); } combobox.setValue(arrTemp); } //活動類型 switch (row.data.event_type) { case "T1": Ext.getCmp("tryeat").setValue(true); Ext.getCmp("tryuse").setDisabled(true); break; case "T2": Ext.getCmp("tryuse").setValue(true); Ext.getCmp("tryeat").setDisabled(true); break; } var numLimit = Ext.getCmp("num_limit"); var giftMundane = Ext.getCmp("gift_mundane"); if (row.data.count_by == "1") { Ext.getCmp("rdoNoTimesLimit").setValue(true); numLimit.setValue(0); numLimit.setDisabled(true); giftMundane.setValue(0); giftMundane.setDisabled(true); } if (row.data.count_by == "2") { Ext.getCmp("rdoByOrder").setValue(true); numLimit.setDisabled(false); giftMundane.setDisabled(false); numLimit.setValue(row.data.num_limit) giftMundane.setValue(row.data.gift_mundane); } if (row.data.count_by == "3") { Ext.getCmp("rdoByMember").setValue(true); //numLimit.setValue(0); numLimit.setDisabled(false); // giftMundane.setValue(0); giftMundane.setDisabled(false); numLimit.setValue(row.data.num_limit); giftMundane.setValue(row.data.gift_mundane); } //裝置 switch (row.data.device_name) { case DEVICE_2: Ext.getCmp("pc").setValue(true); break; case DEVICE_3: Ext.getCmp("mobilepad").setValue(true); break; default: Ext.getCmp("bufen").setValue(true); break; } //會員條件 if (row.data.condition_id != 0) { Ext.getCmp('us1').setValue(false); Ext.getCmp('us2').setValue(true); } else { Ext.getCmp('us1').setValue(true); Ext.getCmp('us2').setValue(false); if (row.data.group_id == "" || row.data.group_id == "0" || row.data.group_id == 0) { Ext.getCmp('group_id').setValue("0"); } } if (row.data.sale_productid != 0) { Ext.getCmp("sale_product_id").setValue(row.data.sale_productid); Ext.getCmp("sale_product_name").show(); Ext.getCmp("sale_product_name").setValue(row.data.sale_product_name); } //圖片 var img, imgUrl; if (row.data.event_img_small.toString() != "") { img = row.data.event_img_small.toString(); imgUrl = img.substring(img.lastIndexOf("\/") + 1); Ext.getCmp('event_img_small').setRawValue(imgUrl); } if (row.data.event_img.toString() != "") { img = row.data.event_img.toString(); imgUrl = img.substring(img.lastIndexOf("\/") + 1); Ext.getCmp('event_img').setRawValue(imgUrl); } if (row.data.product_img.toString() != "") { img = row.data.product_img.toString(); var regex = /^[T1|T2].*$/; if (!regex.test(img)) { Ext.getCmp("prod_file").setValue(img); } imgUrl = img. substring(img.lastIndexOf("\/") + 1); Ext.getCmp('product_img').setRawValue(imgUrl); } if (row.data.category_id != "0" && row.data.category_id != "") { Ext.getCmp('category_id').setValue(row.data.category_id); Ext.getCmp('category_name').setValue(row.data.category_name); Ext.getCmp('category_name').show(); } if (row.data.brand_id != 0 && row.data.brand_id != "") { Ext.getCmp('brand_id').setValue(row.data.brand_id); Ext.getCmp('brand_name').setValue(row.data.brand_name); Ext.getCmp('brand_name').show(); } //是否重複送 switch (row.data.repeat) { case "false": Ext.getCmp("OnlyOne").setValue(true); break; case "true": Ext.getCmp("Every").setValue(true); break; default: Ext.getCmp("OnlyOne").setValue(true); break; } } function Tomorrow() { var d; var dt; var s = ""; d = new Date(); // 创建 Date 对象。 s += d.getFullYear() + "/"; // 获取年份。 s += (d.getMonth() + 1) + "/"; // 获取月份。 s += d.getDate(); dt = new Date(s); dt.setDate(dt.getDate() + 1); return dt; // 返回日期。 } } setNextMonth = function (source, n) { var s = new Date(source); s.setMonth(s.getMonth() + n); if (n < 0) { s.setHours(0, 0, 0); } else { s.setHours(23, 59, 59); } return s; }
// components/media/media.js Component({ /** * 组件的属性列表 */ properties: { res: Array, jumpTo: String }, /** * 组件的初始数据 */ data: { }, /** * 组件的方法列表 */ methods: { checkThis (e) { let data = e.currentTarget.dataset if (this.data.jumpTo !== '/') { wx.navigateTo({ url: '/pages/' + this.data.jumpTo + '/' + this.data.jumpTo + '?id=' + data.id }) } } } })
import { Grid } from "@material-ui/core"; import React, { useEffect, useState } from "react"; import { useParams } from "react-router"; import api from "../../api"; import Time from "../../components/time"; export default function TimeView() { const { idTime } = useParams(); const [time, setTime] = useState(null); async function buscaTime() { const time = await api.buscaTime(idTime); setTime(time); console.log(time); } useEffect(() => { buscaTime(); }, []); return ( <> <Grid container>{time ? <Time {...time} /> : null}</Grid> </> ); }
var createPersonEntry = function (nameField,address,phoneNumber,picture,CCnumber){ var personEntry = document.createElement("div"); var personNameHeading = document.createElement("h1"); var personAddress = document.createElement("p"); var personPhoneNumber = document.createElement("p"); var personCCnumber = document.createElement("p"); var personPicture = document.createElement("img"); personNameHeading.className = "personTitle"; personNameHeading.innerHTML = nameField ; personAddress.className = "Address"; personAddress.innerHTML = address; personPhoneNumber.className = "phoneNumber"; personPhoneNumber.innerHTML = phoneNumber; personCCnumber.className = "CCnumber"; personCCnumber.innerHTML = CCnumber; personPicture.className = "picture"; personPicture.src = picture; // personNameHeading.innerHTML = address.value; // personNameHeading.innerHTML = phoneNumber.value; personEntry.appendChild(personNameHeading); personEntry.appendChild(personAddress); personEntry.appendChild(personPhoneNumber); personEntry.appendChild(personCCnumber); personEntry.appendChild(personPicture); return personEntry } /* var buttonClicked = function(){ var nameListDiv = document.getElementById("nameList"); for (var i =0; i<people.length; i++){ //nameListDiv.innerHTML += "<p>"+people[i].sayHello()+"</p>"; var personEntry = createPersonEntry(people[i]); nameListDiv.appendChild(personEntry); //var pElement = document.createElement("p"); //pElement.innerHTML = people[i].sayHello(); //nameListDiv.appendChild(pElement); } } */ var sumbitPressed = function (){ var nameField = document.getElementById("nameField").value; var address = document.getElementById("address").value; var phoneNumber = document.getElementById("phoneNumber").value; var picture = document.getElementById("picture").value; var CCnumber = document.getElementById("CCnumber").value; var nameListDiv = document.getElementById("nameList"); var personEntry = createPersonEntry(nameField,address,phoneNumber,picture,CCnumber); nameListDiv.appendChild(personEntry); }
import { numStoriesToDisplay } from 'common/constants'; const placeHolderItem = { _loaded: false, _loading: false, }; export const createPlaceholderItems = (n, data = {}) => n === 1 ? { ...placeHolderItem, ...data } : new Array(n).fill(placeHolderItem); export const padWithLoadingItems = ( arrayToPad, targetLength = numStoriesToDisplay ) => !arrayToPad || arrayToPad.length === 0 ? [ ...arrayToPad, ...createPlaceholderItems(targetLength - arrayToPad.length), ] : arrayToPad; export const getNumItems = itemsToCount => (itemsToCount && itemsToCount.length) || 0;
$(function() { initEvent(); // MoveTab(moveTabList); startBallTagRoll() }) function initEvent() { $('#recommendYes').click(function() { parent.UI.util.returnCommonWindow({ recommend: true }); parent.UI.util.closeCommonWindow(); }) $('#recommendNo').click(function() { parent.UI.util.closeCommonWindow(); }) }
const Job = require('./job'); class Queue { constructor(model, name, options) { if (typeof name === 'object' && options === undefined) { options = name; name = undefined; } options = options || {}; this.Model = model; this.name = name || 'default'; this.options = options; } job(task) { return new Job(task); } newJob(data) { return new Job(new this.Model(data)); } async get(id) { const task = await this.Model.findOne({_id: id, queue: this.name}); return this.job(task); } async enqueue(name, params, options = {}) { const job = this.newJob({ name, params, queue: this.name, attempts: parseAttempts(options.attempts), timeout: parseTimeout(options.timeout), delay: options.delay, priority: options.priority, status: options.paused ? Job.PAUSED : Job.QUEUED }); return job.enqueue(); } async unpause(query = {}) { query.status = Job.PAUSED; const update = {$set: {status: Job.QUEUED}}; return this.Model.update(query, update, {multi: true}); } async dequeue(worker, options = {}) { let query = { status: Job.QUEUED, queue: this.name, delay: { $lte: new Date() } }; if (options.query) { query = Object.assign(query, options.query); } if (options.minPriority !== undefined) { query.priority = {$gte: options.minPriority}; } if (options.callbacks !== undefined) { const callbackNames = Object.keys(options.callbacks); query.name = {$in: callbackNames}; } const opts = {new: true, sort: {priority: -1, enqueued: 1}}; const update = { $set: { worker, status: Job.DEQUEUED, dequeued: new Date() } }; const doc = await this.Model.findOneAndUpdate(query, update, opts); if (!doc) { return false; } return this.job(doc); } } module.exports = Queue; // Helpers function parseTimeout(timeout) { if (timeout === undefined) { return undefined; } return parseInt(timeout, 10); } function parseAttempts(attempts) { if (attempts === undefined) { return undefined; } if (typeof attempts !== 'object') { throw new Error('attempts must be an object'); } const result = {count: parseInt(attempts.count, 10)}; if (attempts.delay !== undefined) { result.delay = parseInt(attempts.delay, 10); result.strategy = attempts.strategy; } return result; }
const moment = require('moment'); class Rule_Set { constructor(params){ this.transaction = params.transaction; this.identification_rules = params.identification_rules; this.application_rules = params.application_rules; this.exclusions = params.exclusions; this.validate(); this.class_properties(); } matches(day){ for(const rule of this.identification_rules){ const is_match = this.rule_funcs[rule.type]; if(!is_match(rule, day)) return false; } return true; } validate(){ } class_properties(){ this.rule_funcs = { //{type: 'simple', property: 'date', flags: [17]} simple: function(rule, day){ return rule.flags.includes(day.get(rule.prop)); }, //{type: 'interval', interval: 2, unit: 'weeks', start_date: '2018-11-03'} interval: function(rule, day){ return ( 0 === moment(rule.start_date).diff(moment(day.epoch), rule.unit) % rule.interval ); } } } } module.exports = Rule_Set;
import '../scss/custom.scss'; import 'bootstrap';
const multer = require('multer'); const User = require('../models/userModel'); const AppError = require('../utils/appError'); const catchAsync = require('../utils/catchAsync'); const factory = require('./factoryHandler'); const multerStorage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, 'public/img/users'); }, filename: (req, file, cb) => { const ext = file.mimetype.split('/')[1]; cb(null, `user-${req.user.id}-${Date.now()}.${ext}`); }, }); const multerFilter = (req, file, cb) => { if (file.mimetype.startsWith('image')) { cb(null, true); } else { cb( new AppError('This is not an image! Please upload an image', 400), false ); } }; const upload = multer({ storage: multerStorage, fileFilter: multerFilter, }); exports.uploadUserImage = upload.single('photo'); const filter = (obj, ...allowedFields) => { const newObj = {}; Object.keys(obj).forEach((element) => { if (allowedFields.includes(element)) newObj[element] = obj[element]; }); return newObj; }; exports.createUser = (req, res) => { res.status(500).json({ status: 'error', message: 'This is not yet defined! Use /signup route', }); }; exports.profileUpdate = catchAsync(async (req, res, next) => { const filteredBody = filter(req.body, 'name', 'email'); if (req.file) { filteredBody.photo = req.file.filename; } const updatedUser = await User.findByIdAndUpdate(req.user.id, filteredBody, { new: true, runValidators: true, }); res.status(200).json({ status: 'success', user: updatedUser, }); }); exports.deactivateAccount = catchAsync(async (req, res, next) => { await User.findByIdAndUpdate(req.user.id, { active: false }); res.status(204).json({ status: 'success', data: null, }); }); exports.getMe = (req, res, next) => { req.params.id = req.user.id; next(); }; exports.getAllUsers = factory.getAll(User); exports.getUser = factory.getOne(User); exports.updateUser = factory.updateOne(User); exports.deleteUser = factory.deleteOne(User);
import Vue from 'vue' import Router from 'vue-router' import HelloWorld from '@/components/HelloWorld' import PokeCollection from '@/components/PokeCollection' import PokeCollectionFiltered from '@/components/PokeCollectionFiltered' import PokeCollectionEditor from '@/components/PokeCollection-Editor' import PokeStatCard from '@/components/PokeStatCard' import PokeMoves from '@/components/PokeMoves' import PokeMovesEditor from '@/components/PokeMoves-Editor' import BraceletPowers from '@/components/BraceletPowers' import BraceletPowersEditor from '@/components/BraceletPowers-Editor' import BraceletCanHold from '@/components/BraceletCanHold' import BraceletCanHoldEditor from '@/components/BraceletCanHold-Editor' import WishList from '@/components/WishList' import WishListEditor from '@/components/WishList-Editor' import Login from '@/components/auth/login' import Register from '@/components/auth/register' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'HelloWorld', component: HelloWorld }, { path: '/poke/:page', name: 'PokeCollection', component: PokeCollection }, { path: '/pokefiltered/:query', name: 'PokeCollectionFiltered', component: PokeCollectionFiltered }, { path: '/poke-editor/:key', name: 'PokeCollectionEditor', component: PokeCollectionEditor }, { path: '/pokecard/:key', name: 'PokeStatCard', component: PokeStatCard }, { path: '/poke-editor', name: 'PokeCollectionAdd', component: PokeCollectionEditor }, { path: '/moves', name: 'PokeMoves', component: PokeMoves }, { path: '/pokemoves-editor/:key', name: 'PokeMovesEditor', component: PokeMovesEditor }, { path: '/braceletpowers', name: 'BraceletPowers', component: BraceletPowers }, { path: '/braceletpowers-editor/:key', name: 'BraceletPowersEditor', component: BraceletPowersEditor }, { path: '/braceletcanhold', name: 'BraceletCanHold', component: BraceletCanHold }, { path: '/braceletcanhold-editor/:key', name: 'BraceletCanHoldEditor', component: BraceletCanHoldEditor }, { path: '/wishlist', name: 'WishList', component: WishList }, { path: '/wishlist-editor/:key', name: 'WishListEditor', component: WishListEditor }, { path: '/login', name: 'login', component: Login }, { path: '/register', name: 'register', component: Register } ], scrollBehavior (to, from, savedPosition) { return { x: 0, y: 0 } } })
if (window.matchMedia('(max-width: 420px)').matches) { $('.multiple-items').slick({ infinite: true, slidesToShow: 1, slidesToScroll: 1, prevArrow: '<button type="button" class="slider-arrow slider-arrow--left"></button>', nextArrow: '<button type="button" class="slider-arrow slider-arrow--right"></button>' }); } else if (window.matchMedia('(max-width: 600px)').matches) { $('.multiple-items').slick({ infinite: true, slidesToShow: 2, slidesToScroll: 2, prevArrow: '<button type="button" class="slider-arrow slider-arrow--left"></button>', nextArrow: '<button type="button" class="slider-arrow slider-arrow--right"></button>' }); } else if (window.matchMedia('(max-width: 900px)').matches) { $('.multiple-items').slick({ infinite: true, slidesToShow: 3, slidesToScroll: 3, prevArrow: '<button type="button" class="slider-arrow slider-arrow--left"></button>', nextArrow: '<button type="button" class="slider-arrow slider-arrow--right"></button>' }); } else { $('.multiple-items').slick({ infinite: true, slidesToShow: 4, slidesToScroll: 4, prevArrow: '<button type="button" class="slider-arrow slider-arrow--left"></button>', nextArrow: '<button type="button" class="slider-arrow slider-arrow--right"></button>' }); }
import React from "react" import Slider from "react-slick"; import CardJob from "./components/CardJob/CardJob" import { dummy } from "../../../assets/common/Utils/DummyProfie" const Jobs = () => { const settings = { dots: true, infinite: true, autoplay: false, speed: 500 } return ( <div className="jobs"> <div className="container"> <h2 className="primary-title">Trabaja con profesionales</h2> <div className="jobs__content"> {dummy.jobs.map(item=>( <CardJob data={item}/> ) )} </div> <div className="jobs__content-slider"> <Slider {...settings}> {dummy.jobs.map(item=>( <CardJob data={item}/> ) )} </Slider> </div> </div> </div> ) } export default Jobs
/* global Materialize */ import Ember from 'ember'; export default Ember.Controller.extend({ platforms: function() { return Ember.A([ { id: 'android', value: 'Android' }, { id: 'iphone', value: 'iPhone' }, { id: 'xbox', value: 'Xbox' }, { id: 'playstation', value: 'Playstation' }, { id: 'windows', value: 'Windows' }, { id: 'mac', value: 'mac' }, { id: 'linux', value: 'Linux' } ]); }.property(), games: Ember.computed.oneWay('model'), modalIsOpen: false, searchGameValue: '', title: '', selectedPlatform: null, description: '', searchGame: function() { var self = this; var title = this.get('searchGameValue'); if (Ember.isEmpty(title)) { self.set('games', this.store.findAll('game')); } else { this.store.query('game', {"filter": {"where": {"title": {"like": title }}}}).then(function (results) { self.set('games', results); }, function(error) { Materialize.toast('Error:' + error, 4000); }); } }, searchGameValueObserver: function() { Ember.run.debounce(this, this.searchGame, 369); }.observes('searchGameValue'), actions: { add: function() { this.set('modalIsOpen', true); }, resetSearch: function() { this.set('searchGameValue', ''); }, submitGame: function() { var title = this.get('title'); var platform = this.get('selectedPlatform.id'); var description = this.get('description'); var self = this; if (Ember.isPresent(title) && Ember.isPresent(platform) && Ember.isPresent(description)) { // form is valid var game = self.store.createRecord('game', { title: title, platform: platform, description: description }); game.save().then(function () { self.searchGame(); self.send('closeModal'); }).catch(function (failure) { Materialize.toast('Error:' + failure, 4000); }); } else { Materialize.toast('All fields are required', 4000); } }, closeModal: function() { this.set('title', ''); this.set('selectedPlatform', null); this.set('description', ''); this.set('modalIsOpen', false); } } });
"use strict"; const isNonEmptyArray = require("../../../utils/is-non-empty-array.js"); const visitNode = require("./visit-node.js"); const throwSyntaxError = require("./throw-syntax-error.js"); // Taken from `typescript` package const SyntaxKind = { AbstractKeyword: 126, SourceFile: 308, PropertyDeclaration: 169, }; // Copied from https://unpkg.com/typescript@4.8.2/lib/typescript.js function getSourceFileOfNode(node) { while (node && node.kind !== SyntaxKind.SourceFile) { node = node.parent; } return node; } function throwErrorOnTsNode(node, message) { const sourceFile = getSourceFileOfNode(node); const [start, end] = [node.getStart(), node.end].map((position) => { const { line, character: column } = sourceFile.getLineAndCharacterOfPosition(position); return { line: line + 1, column }; }); throwSyntaxError({ loc: { start, end } }, message); } function nodeCanBeDecorated(node) { const ts = require("typescript"); return [true, false].some((useLegacyDecorators) => // @ts-expect-error -- internal? ts.nodeCanBeDecorated( useLegacyDecorators, node, node.parent, node.parent.parent ) ); } // Invalid decorators are removed since `@typescript-eslint/typescript-estree` v4 // https://github.com/typescript-eslint/typescript-eslint/pull/2375 // There is a `checkGrammarDecorators` in `typescript` package, consider use it directly in future function throwErrorForInvalidDecorator(node) { const { modifiers } = node; if (!isNonEmptyArray(modifiers)) { return; } const ts = require("typescript"); const { SyntaxKind } = ts; for (const modifier of modifiers) { if (ts.isDecorator(modifier) && !nodeCanBeDecorated(node)) { if ( node.kind === SyntaxKind.MethodDeclaration && // @ts-expect-error -- internal? !ts.nodeIsPresent(node.body) ) { throwErrorOnTsNode( modifier, "A decorator can only decorate a method implementation, not an overload." ); } throwErrorOnTsNode(modifier, "Decorators are not valid here."); } } } // Values of abstract property is removed since `@typescript-eslint/typescript-estree` v5 // https://github.com/typescript-eslint/typescript-eslint/releases/tag/v5.0.0 function throwErrorForInvalidAbstractProperty(tsNode, esTreeNode) { if ( tsNode.kind !== SyntaxKind.PropertyDeclaration || (tsNode.modifiers && !tsNode.modifiers.some( (modifier) => modifier.kind === SyntaxKind.AbstractKeyword )) ) { return; } if (tsNode.initializer && esTreeNode.value === null) { throwSyntaxError( esTreeNode, "Abstract property cannot have an initializer" ); } } function throwErrorForInvalidNodes(result, options) { if ( // decorators or abstract properties !/@|abstract/.test(options.originalText) ) { return; } const { esTreeNodeToTSNodeMap, tsNodeToESTreeNodeMap } = result; visitNode(result.ast, (node) => { const tsNode = esTreeNodeToTSNodeMap.get(node); if (!tsNode) { return; } const esTreeNode = tsNodeToESTreeNodeMap.get(tsNode); if (esTreeNode !== node) { return; } throwErrorForInvalidDecorator(tsNode); throwErrorForInvalidAbstractProperty(tsNode, esTreeNode); }); } module.exports = { throwErrorForInvalidNodes };
import {onPost,onGet} from "../main"; //合同列表 export const queryContractInfoList = params =>{ return onPost('deal/queryContractInfoList',params) } //合同详细 export const queryContractDetailed = params =>{ return onPost('deal/queryContractDetailed',params) } //合同审批 export const updateContractStatus = params =>{ return onPost('deal/updateContractStatus',params) }
"use strict"; // let x = 16; // have to declare using let, const, or var because we are in strict mode // console.log(x) // *** FUNCTIONS REVIEW *** // // const ageCheck = (age) => { // if (age < 21) { // console.log("No drinks for you!") // } else { // console.log("PARTAYYY!") // } // } // ageCheck(12) // ageCheck(21) // *** .LENGTH METHOD *** // --> tells the length of the string or array, NOT the last index // const lengthOutput = (strang) => { // return strang.length // } // console.log(lengthOutput([1,2,3,4,5,6,7])) // *** .INDEXOF METHOD *** // --> tells the index of the value passed in // const quoteFinder = (testString) => { // return "winter is coming".indexOf(testString) // } // console.log(quoteFinder("is")) // *** OBJECTS *** // const employee = { firstName: 'Faitlyn', // all "key: value" pairs lastName: 'VanHook', role: 'student', accountNumber: '123456', isManager: false, titles: ['teacher', 'bad bitch',], // array inside of an object accolade: { // object inside of an object title: 'Employee of the Year', dateEarned: '1/2/2020', expires: '12/21/2020', isCool: true } } // console.log(employee.firstName) // dot notation // const keyToCheck = 'accolade'; // console.log(employee[keyToCheck]) // console.log(employee.accolade.isCool) // console.log(employee[keyToCheck]['isCool']) // console.log(employee[keyToCheck].isCool) // console.log(employee.keyToCheck.isCool) // "cannot read property isCool" keyToCheck isn't in this object, so if we use a variable, we need to use bracket notation // *** create a function that takes in an employee // *** if the employee's firstName starts with a K, add a key=status and value='vip' // *** if the employee's firstName does not start with a K, then add a key=staus and value='peasant' // const statusUpdate = (object) => { // if (object.firstName.startsWith('K')) { // object.status = 'vip' // } else { // object.status = 'peasant' // } // } // statusUpdate(employee) // console.log(employee.status) // const employeeStatus = (object) => { // if (object.firstName[0] === 'K') { // object.status = 'vip' // } else { // object.status = 'peasant' // } // } // employeeStatus(employee) // console.log(employee.status)
export const BASE_TAGS = '#tags=red,green,blue';
import React from "react"; import avatar from "./avatar.png"; import githublogo from "./githublogo.png"; import linkedinlogo from "./linkedinlogo.png"; import "./Main.css"; const Main = () => { return ( <div className="hero-home"> <div className="container"> <div className="home-content"> <div className="avatar-container"> <img className="avatar" src={avatar} alt="avatar" /> </div> <div className="line-separation" /> <h1 className="main-text">KvhHng</h1> <p className="sub-text"> Front-end developer, UX/UI, Keyboard enthusiast </p> <ul> <a className="link" href="https://github.com/kevinhhoang"> <img src={githublogo} alt="github logo" /> </a> <a className="link" href="https://www.linkedin.com/in/hoangkevinh/"> <img src={linkedinlogo} alt="linkedin logo" /> </a> </ul> </div> </div> <div className="gradient-bg"> <div className="bg-color"> <span className="gradient-highlight" /> </div> </div> </div> ); }; export default Main;
var searchData= [ ['environnement',['Environnement',['../classEnvironnement.html',1,'']]] ];
const fonts = require('./fonts.json') const apiURL = 'https://fonts.googleapis.com/css' const getName = stack => stack.split(',')[0].replace(/["']/g, '') const plusify = name => name.replace(/\s/g, '+') const isWebfont = name => fonts.includes(getName(name)) const getURL = (stack, weights = []) => { const name = getName(stack) if (!isWebfont(name)) return false const family = weights.length ? [plusify(name), weights.join(',') ].join(':') : plusify(name) return [apiURL, '?family=', family].join('') } const getLinkTag = (stack, weights) => { const fontURL = getURL(stack, weights) if (!fontURL) return false return `<link rel='stylesheet' href='${fontURL}'>` } module.exports = { fonts, apiURL, plusify, isWebfont, getURL, getLinkTag }
// alert("Welcome to my page"); // // Variable declaration // let a = 10, b = 5; // console.log(a+10+b); // // Function declaration ==> arrow method // const sum = (a,b) => a+10+b; // let s = sum(10,4); // console.log(s); // Regular function to arrow conversion practice ========== // const greet = function(){ // return 'hello, world'; // } const greet = () => 'hello, world'; let string = greet(); //console.log(string); const bill = (products, tax) =>{ let total = 0; for(let i=0;i<products.length;i++){ total+= products[i] + products[i] *tax; } return total; }; //console.log(bill([10,15,30], 0.2)); // For each method =========================== let people = ['chayan','vansu','mario','tvf']; people.forEach((person)=>{ // console.log(person); }); // Callback function concept ===================== const main = (callback)=>{ let value = 5; callback(value); }; // main((value)=>{ // console.log(value+5); // }); // Objects =============================== let user = { name: 'Vansu', age: 18, marks:[20,23,21,22,20], hobbies:[ {number:1,title:'chayan'}, {number:2,title:'chayan'} ], allMarks(){ this.marks.forEach(mark=>{ console.log(mark); }) }, allHobbies(){ this.hobbies.forEach(hobby=>{ console.log(hobby.number+" "+hobby.title); }) } }; //user.allHobbies(); // Math object(similar to java)============================ // console.log(Math); // console.log(Math.PI);
require.context('govuk-frontend/govuk/assets'); import '../styles/application.scss'; import Rails from 'rails-ujs'; import Turbolinks from 'turbolinks'; import { initAll } from 'govuk-frontend'; import * as cookieOptions from './cookie-consent'; Rails.start(); Turbolinks.start(); initAll(); if(!cookieOptions.checkForCookies("ghre_allow_cookies")) { cookieOptions.unhideBanner(); // Hide cookies if consent already given }; document.getElementById("accept-cookies").onclick = cookieOptions.acceptAllCookies; document.getElementById("hide-button").onclick = cookieOptions.hideBanner;
/* TMT Signon Controller - manage view for user signon and authentication. */ tmtModule .controller('signonController', function ($scope, $location, TmtUsers, TmtUtilities) { $scope.setStatusMessage(''); $scope.setShowingCollection(false); $scope.setMenu('tmt_signon_menu.html'); $scope.errorMessage = ''; $scope.setStatusMessage(''); // For testing only: preset email and password $scope.email = 'j.smith@nowhere.com'; $scope.password = 'abcd'; $scope.signon = function(){ $scope.errorMessage = ''; if (!$scope.signonForm.$valid){ $scope.errorMessage = 'Please enter an email address and password.'; return; } $scope.setStatusMessage('contacting server...'); TmtUsers.signonUser($scope.email, $scope.password, function(err){ $scope.setStatusMessage(''); if (err){ console.dir(err); $scope.errorMessage = TmtUtilities.parseErrorMessage(err); return; } var userId = TmtUsers.user._id; var viewId = TmtUsers.getDefaultViewId(); $location.path('/app/users/'+ userId +'/views/'+ viewId +'/pages'); }); }; $scope.resetForm = function(){ $scope.email = ''; $scope.password = ''; $scope.errorMessage = ''; }; });
import React, { PropTypes } from 'react'; import {Button, Input} from 'antd'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Dialog.less'; import {SuperForm, ModalWithDrag} from '../../../../src/components'; class Dialog extends React.Component { static propTypes = { formControls: PropTypes.array, textAreaControls: PropTypes.array, changeDialogState: PropTypes.func, editData: PropTypes.object, dialogState: PropTypes.bool, dialogType: PropTypes.string, onAdd: PropTypes.func, onClearEditData: PropTypes.func, }; state = { fromData: this.props.editData, }; onCancel = () => { this.props.onClearEditData(); this.props.changeDialogState(false) } onOk = () => { let postData = this.state.fromData; if (this.props.dialogType === 'edit') { postData.id = this.props.editData.id } else if (this.props.dialogType === 'copyAdd') { delete postData.id; } this.props.onAdd(postData, this.props.dialogType); this.onCancel(); } onChange = (key, value) => { const obj = this.state.fromData; this.setState({ fromData: { ...obj, [key]: value } }); } textareaChange = (e, key) => { const value = e.target.value; this.setState({ fromData: {...this.state.fromData, [key]: value} }); } renderTextArea() { return ( this.props.textAreaControls.map((textarea, index) => <div className={s.textareaWrap} key={index}> <span className={s.textareaTip}>{textarea.title}</span> <Input key={index} type="textarea" readOnly={textarea.type === 'readonly'? 'readOnly' : null} rows={textarea.rows} className={s.textarea} value={this.state.fromData[textarea.key]} onChange={(e) => this.textareaChange(e, textarea.key)} /> </div> ) ); } renderBody() { const props = { controls: this.props.formControls, value: this.state.fromData, colNum: 2, onChange: this.onChange, } return ( <div> <SuperForm {...props}/> {this.renderTextArea()} </div> ); } render() { return ( <ModalWithDrag wrapClassName="addDialog" visible={this.props.dialogState} closable={false} title={this.props.dialogType === 'add' ? '新增' : '编辑'} footer={ <div style={{textAlign: 'right'}}> <Button size='default' onClick={() => this.onCancel()}>取消</Button> <Button size='default' type='primary' onClick={() => this.onOk()}>保存</Button> </div> } > {this.renderBody()} </ModalWithDrag> ); } } export default withStyles(s)(Dialog);
/* The following function returns true if the parameter age is greater than 18. Otherwise it asks for a confirmation and returns its result. function checkAge(age) { if (age > 18) { return true; } else { return confirm('Did parents allow you?'); } } Rewrite it, to perform the same, but without if, in a single line. Make two variants of checkAge: Using a question mark operator ? Using OR || */ let age = 2; function checkAge(age){ return ((age >= 18)? true:false); } console.log(checkAge(age)); function checkAge(age){ return ((age > 18) || false); } console.log(checkAge(age));
var distance = require('google-distance-matrix'); //https://www.npmjs.com/package/google-distance-matrix distance.key('xxxxxxxxx'); distance.mode('driving'); var origins = ['Carmelaram', '12.904428,77.706918']; var destinations = ['12.9478598,77.6893068']; var dist = function() { return new Promise((resolve, reject) => { distance.matrix(origins, destinations, function (err, distances) { if (err) reject(err); resolve({ statusCode: 200, body: distances }); } ); }); } exports.handler = async (event) => { return await dist(); };