text
stringlengths
7
3.69M
require("../common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/building/img_preview/_audio_player" ], { "1e53": function(n, e, t) { var i = t("ed86"); t.n(i).a; }, 4653: function(n, e, t) { t.d(e, "b", function() { return i; }), t.d(e, "c", function() { return o; }), t.d(e, "a", function() {}); var i = function() { var n = this; n.$createElement; n._self._c; }, o = []; }, "6b10": function(n, e, t) { t.r(e); var i = t("bce6"), o = t.n(i); for (var r in i) [ "default" ].indexOf(r) < 0 && function(n) { t.d(e, n, function() { return i[n]; }); }(r); e.default = o.a; }, bce6: function(n, e, t) { Object.defineProperty(e, "__esModule", { value: !0 }), e.default = void 0; var i = t("ed08"), o = { data: function() { return { show: !1, progress: 0 }; }, props: { playing: Boolean, time: Number, running_time: Number }, watch: { playing: function(n, e) { n && n != e && (this.show = !0); }, running_time: function(n) { this.time && (this.progress = parseInt(n / this.time * 100)); } }, computed: { duration: function() { return (0, i.handleSeconds)(this.time); }, running_duration: function() { return (0, i.handleSeconds)(this.running_time); } }, methods: { onPress: function() { this.playing ? this.stop() : this.play(); }, play: function() { this.$emit("play"); }, stop: function() { this.$emit("stop"); }, onClose: function() { this.show = !1, this.stop(); }, changeProgress: function(n) { console.log("change progress", n), this.progress = n.target.value, this.$emit("seek", this.progress / 100); } } }; e.default = o; }, d48a: function(n, e, t) { t.r(e); var i = t("4653"), o = t("6b10"); for (var r in o) [ "default" ].indexOf(r) < 0 && function(n) { t.d(e, n, function() { return o[n]; }); }(r); t("1e53"); var a = t("f0c5"), u = Object(a.a)(o.default, i.b, i.c, !1, null, "ded0c7f0", null, !1, i.a, void 0); e.default = u.exports; }, ed86: function(n, e, t) {} } ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/building/img_preview/_audio_player-create-component", { "pages/building/img_preview/_audio_player-create-component": function(n, e, t) { t("543d").createComponent(t("d48a")); } }, [ [ "pages/building/img_preview/_audio_player-create-component" ] ] ]);
module.exports = { cmd: function() { this.shell.print('playing console...') lab.vm.pause = false }, help: 'resume the playback' }
import { createSlice } from "@reduxjs/toolkit"; const signIn = createSlice({ name: "signIn", initialState: { email: "" }, reducers: { signInVerifyEmail: (state, action) => { state.email = action.payload; }, }, }); const { reducer, actions } = signIn; export const { signInVerifyEmail } = actions; export default reducer;
import React, { Component } from 'react'; /* Custom React components */ import RequestService from '../../Services/RequestService'; let HOST = "https://" + window.location.hostname; const PORT = window.location.port; if (PORT !== '3000') { HOST += ':' + PORT; } class Settings extends Component { constructor(props) { super(props); this.state = { projectUuid: this.props.projectUuid, projectUsers: this.props.projectUsers, users: [] } this.saveUsers = this.saveSettings.bind(this); this.getAllUsers = this.getAllUsers.bind(this); this.drawSelectUsersListItem = this.drawSelectUsersListItem.bind(this); this.drawUserInfo = this.drawUserInfo.bind(this); this.userItemClicked = this.userItemClicked.bind(this); this.exportProject = this.exportProject.bind(this); } componentDidMount() { this.getAllUsers(); } getAllUsers() { RequestService.Get('/user/all') .then(content => { let tempUsers = {}; let userArray = Object.values(content.response); for (var i = 0; i < userArray.length; i++) { let user = userArray[i]; if (this.projectContainsUser(user)) { tempUsers[user.uuid] = user; tempUsers[user.uuid].isSelected = true; } else { tempUsers[user.uuid] = user; tempUsers[user.uuid].isSelected = false; } } this.setState( { users: tempUsers }); this.props.handleChangeProjectUsers(); }); } drawUserInfo(user, index) { let imgStyle = { height: '47px', width: '42px', padding: '1px 1px 8px 1px' }; let imgDivStyle = { display: 'inline-block', margin: '0px 2px', backgroundColor: user.color }; let divStyle = { display: 'inline-block', marginRight: '10px', textAlign: 'center' }; if (user.isSelected) { return ( <div key={index} style={divStyle} onClick={() => {this.userItemClicked(user)}}> <div style={imgDivStyle}> <svg fill="#000000" height="18" viewBox="0 0 24 24" width="18" xmlns="http://www.w3.org/2000/svg" className="checkmark"> <path d="M0 0h24v24H0z" fill="none"/> <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/> </svg> <img src={user.picture} style={imgStyle} alt={user.username} /> </div> <p><small>{user.username}</small></p> </div> ); } else { return ( <div key={index} style={divStyle} onClick={() => {this.userItemClicked(user)}}> <div style={imgDivStyle}> <img src={user.picture} style={imgStyle} alt={user.username} /> </div> <p><small>{user.username}</small></p> </div> ); } } projectContainsUser(user) { let found = false; for(let i = 0; i < Object.keys(this.state.projectUsers).length; i++) { if (Object.keys(this.state.projectUsers)[i] === user.uuid) { found = true; break; } } return found; } drawSelectUsersListItem(user, index) { let imgDivStyle = { display: 'inline-block', marginRight: '10px', backgroundColor: user.color, borderRadius: '3px' }; let imgStyle = { height: '42px', width: '42px', padding: '2px 2px 2px 2px', borderRadius: '3px' }; let listItemStyle = {} let spanStyle = { marginTop: '0.60rem' } let cssClass = ""; let itemText = ""; if (user.isSelected) { cssClass = "list-group-item list-group-item-action active"; itemText = "Selected"; listItemStyle = { padding: '0.2rem 1.25rem', borderColor: '#0071ea' } } else { cssClass = "list-group-item list-group-item-action"; itemText = ""; listItemStyle = { padding: '0.2rem 1.25rem' } } return( <div style={listItemStyle} className={cssClass} key={index} onClick={() => {this.userItemClicked(user)}}> <div style={imgDivStyle}> <img src={user.picture} style={imgStyle} alt={user.username} /> </div> {user.username} <span style={spanStyle} className="badge float-right">{itemText}</span> </div> ) } userItemClicked(user) { let tempUsers = this.state.users; tempUsers[user.uuid].isSelected = !user.isSelected; this.setState({ users: tempUsers }) } saveSettings() { let contributorsRequestArray = []; let newProjectUsersArray = {}; let userArray = Object.values(this.state.users); for (var i = 0; i < userArray.length; i++) { let user = userArray[i]; if (user.isSelected) { contributorsRequestArray.push(user.uuid); newProjectUsersArray[user.uuid] = user; } } let requestBody = { projectUuid: this.state.projectUuid, contributors: contributorsRequestArray } RequestService.Post('project/update/contributors/', requestBody) .then(() => { this.setState( { users: {}, projectUsers: newProjectUsersArray }); this.getAllUsers(); }) } exportProject() { window.open(`${HOST}/api/download/project/${this.state.projectUuid}`); } render() { if(!this.state.users || Object.keys(this.state.users).length <= 0 || !this.state.projectUsers || Object.keys(this.state.projectUsers).length <= 0) { return ( <div className="loading-icon-wrapper" > </div> ) } return ( <div className="col-xl-10 col-md-9 col-sm-8"> <div className="row editor-container-wrapper"> <div className="col-lg-9"> <h2>Settings</h2> </div> <div className="col-lg-3 text-right"> <button className="btn btn-primary saveButton" onClick={this.saveSettings.bind(this)}>Save</button> <button className="btn btn-primary exportButton" onClick={this.exportProject}>Export</button> </div> </div> <hr/> <h3>ProjectName</h3> <hr/> <h3>Project members</h3> { Object.values(this.state.users).map((user, index) => ( this.drawUserInfo(user, index) )) } </div> ); } } export default Settings;
import React, {useState, createContext,useEffect} from 'react'; export const AuthContext =createContext(); const AuthContextProvider = (props) => { const[austate, setAuth]=useState( { isAutentificated: false, message:"", id:'', role:'', 'salary':'', 'assets_pack':'' } ); const logOut =()=>{ setAuth({isAutentificated: !austate.isAutentificated }); } const getCredentionals=(email,password)=>{ // console.log('austate'+austate.isAutentificated); ( async function fetchData (){ const settings = { method: 'POST', body: JSON.stringify({email: email, password:password}), headers: { Accept: 'application/json', 'Content-Type': 'application/json', } }; const data= await fetch("/api/auth",settings); let jdata =await data.json(); if(jdata.status==="err"){ console.log("res message"+jdata.message) setAuth({isAutentificated: false,message:jdata.message}); // console.log("res sdfg"+austate.message) // console.log("res austate"+austate.message) }else{ // for(let i in jdata.data){ // // console.log("jdata.data.id"+jdata.data[i]); // } setAuth({isAutentificated: !austate.isAutentificated, id:jdata.data.id,role: jdata.data.role }); //console.log("austate.id"+austate.id ); } })() } return ( <AuthContext.Provider value={{austate, getCredentionals,logOut}}> {props.children} </AuthContext.Provider> ) } export default AuthContextProvider
import { useState, useEffect } from 'react' import Link from 'next/link' import Router from 'next/router' import $api from '../api' import { Affix, Row, Col, Menu } from 'antd' import { HomeOutlined, YoutubeOutlined, SmileOutlined } from '@ant-design/icons' import '../styles/components/header.css' const Header = () => { const [typeList, setTypeList] = useState([]) useEffect(() => { $api.common.getTypeInfo({ setName: setTypeList }) }, []) const handClick = async (e) => { let path = '' if (e.key === '0') { path = '/' } else { path = '/list?id=' + e.key } Router.push(path) } return ( <Affix offsetTop={0}> <div className="header"> <div className="header-center"> <Row type="flex" justify="center"> <Col xs={24} sm={24} md={13}> <Link href="/"> <a><span className="header-logo">个人博客</span></a> </Link> <span className="header-txt">前端开发</span> </Col> <Col className="memu-div" xs={0} sm={0} md={11}> <Menu mode="horizontal"> <Menu.Item key="0" icon={<HomeOutlined />} onClick={handClick}> 博客首页 </Menu.Item> { typeList.map(item => { const iconArr = [null, <YoutubeOutlined />, <SmileOutlined />] return ( <Menu.Item key={item.id} icon={iconArr[item.id]} onClick={handClick}> {item.typeName} </Menu.Item> ) }) } </Menu> </Col> </Row> </div> </div> </Affix> ) } export default Header
const ONE_TO_MANY = () => { const sql = `SELECT employee.employeeID, employee.name AS employee_name, employee.role AS employee_role, employee.address AS employee_address, customers.customersID, customers.name AS customers_name, customers.email AS customers_email, order_product.count AS count, products.name AS product_name, products.price AS product_price, category.name AS category FROM order_product INNER JOIN orders ON order_product.orderID = orders.orderID INNER JOIN customers ON orders.customerID = customers.customersID INNER JOIN employee ON orders.employeeID = employee.employeeID INNER JOIN products ON order_product.productID = products.productID INNER JOIN category ON products.categoryID = category.categoryID ` } // const data = { // dt: [{ // order_product: ['count'] // }, // { // product: ['name', 'price'] // }, // { // category: ['name'] // }, // { // employee: ['name', 'address'] // }, // { // customer: ['name', 'email'] // } // ], // from: 'order_product', // cond: [{ // join: ['order_product', 'dorder'], // on: 'orderID', // val: 77091 // }, { // join: ['dorder', 'customer'], // on: 'customerID' // }, { // join: ['dorder', 'employee'], // on: 'employeeID' // }, { // join: ['order_product', 'product'], // on: 'productID' // }, { // join: ['product', 'category'], // on: 'categoryID' // }] // } const exCond = [{join: Array, on: String}] const fieldName = Array const exDt = [{tableName: fieldName}] const exData = { dt: exDt, from: String, cond: exCond } /** * * @param {exData} data * */ const innerJoin = (data) => { const checkData = (data) => { if (typeof data === 'string') { return 'string' } else if (typeof Object.getPrototypeOf(data) === 'object') { return 'object' } } let sqlTop = 'SELECT ' let sqlBody = '' let sqlFoot = ' ' let idx = 0 let listKey = [] for (let i of data.dt) { if (checkData(i) === 'object') { let tempQuery = `` let keys = '' for (let [key, value] of Object.entries(i)) { let tmp = '' let index = 0 for (let val of value) { let temp = '' if (index > 0) { if (index === (value.length - 1)) { // temp = key + '.' + val + ' AS' temp = `${key}.${val} AS ${key}_${val}` } else { temp = `${key}.${val} AS ${key}_${val},` } } else { if (index === (value.length - 1)) { temp = `${key}.${val} AS ${key}_${val}` } else { temp = `${key}.${val} AS ${key}_${val},` } } tmp += temp index = index + 1 } tempQuery += tmp keys = key } sqlBody += tempQuery listKey.push(keys) } else if (checkData(i) === 'string') { if (idx === (data.dt.length - 1)) { sqlBody += ',' + i + '.* ' } else { sqlBody += i + '.*' } listKey.push(i) } if (idx < (data.dt.length - 1)) { sqlBody += ',' } idx += 1 } let dd = ` FROM ${data.from} ` // sql foot for (let val of data.cond) { // if(data.cond.val) let q = `INNER JOIN ${val.join[1]} ON ${val.join[0]}.${val.on} = ${val.join[1]}.${val.on} ` if (val.val) { q = `INNER JOIN ${val.join[1]} ON ${val.join[0]}.${val.on} = ${val.val} ` } dd += q } sqlFoot += dd return sqlTop+sqlBody+sqlFoot } module.exports = { innerJoin }
'use strict'; const CryptoJS = require("crypto-js"); let express = require('express'); let router = express.Router(); //path: /bai-giai let subjects = { 'toan': { id: 2, name: 'Toán', max_round: 19, test_count: 3, free: true }, 'tieng-anh': { id: 3, name: 'Tiếng Anh', max_round: 19, test_count: 3, free: true }, 'tieng-viet': { id: 1, name: 'Tiếng Việt', max_round: 19, test_count: 3, free: true }, 'khoa-hoc-tu-nhien': { id: 4, name: 'Khoa học - tự nhiên', max_round: 19, test_count: 3, free: true }, 'su-dia-xa-hoi': { id: 5, name: 'Sử - địa -xã hội', max_round: 19, test_count: 3, free: true }, 'iq-toan-tieng-anh': { id: 6, name: 'IQ - Toán tiếng anh', max_round: 19, test_count: 3, free: true }, }; router.get('/', function(req, res) { try{ res.render('answer-home',{layout:'layout', title: 'Bài giải Trạng Nguyên'}); } catch(e){ logger.error(e); } }); router.post('/', function(req, res) { try{ // } catch(e){ logger.error(e); } }); router.use('/:subject',(req,res,next)=>{ let subject = req.params.subject; let subject_info = subjects[subject]; if(subject_info){ req.subject_url = subject; req.subject_id = subject_info.id; req.subject_name = subject_info.name; next(); } else{ res.status(404).render('404'); } }); router.get('/:subject', auth.checkAuthor, function(req, res) { try{ let user_id = req.tndata.user._id; let class_id = req.tndata.user.class_id; let subject_id = req.subject_id; const page_size = 20; let class_name = class_id==0?'mẫu giáo':class_id; let param_render = { layout:'answer-layout', title: 'Bài giải ' + req.subject_name + ' - Trạng Nguyên', class_id: class_id, className: class_name, page_size: page_size, base_url: req.baseUrl, subject_url: req.subject_url, subject_name: req.subject_name }; /*async.parallel([ callback => { ExamAnswersService.GetList(class_id, page_size, 0, (err, list)=>{ if(err) logger.error(err); else{ param_render.list = list; callback(null, true); } }); }, callback => { ExamAnswersService.CountList(class_id, (err, iCount)=>{ if(err) logger.error(err); else{ param_render.total_row = iCount; callback(null, true); } }); } ],()=>{ res.render('select-questions', param_render); });*/ async.parallel([ callback=>{ ExamAnswersService.getListType(class_id, subject_id, (err, list)=>{ if(err) logger.error(err); else{ param_render.list = list; callback(err, list); } }); }, callback =>{ UserService.checkVip(user_id, (err, info)=>{ if(err){ logger.error(err); } else{ if(info){ if(info.vip_expire){ if(info.vip_expire >= new Date()){ //nothing => pass } else{ param_render.pass = false; param_render.redirect = 'https://trangnguyen.edu.vn/huong-dan/huong-dan-nop-hoc-phi-qua-ngan-hang-va-the-trang-nguyen.1260'; param_render.message = 'Tài khoản luyện tập của bạn đã hết hạn.<br/>Bạn hãy nộp học phí'; } } else{ param_render.pass = false; param_render.redirect = 'https://trangnguyen.edu.vn/huong-dan/huong-dan-nop-hoc-phi-qua-ngan-hang-va-the-trang-nguyen.1260'; param_render.message = 'Bạn chưa nộp học phí.<br/>Bạn hãy nộp học phí'; } } else{ param_render.pass = false; param_render.message = 'Không tìm thấy thông tin người dùng'; } callback(err, info); } }); } ],()=>{ res.render('answer-list', param_render); }); } catch(e){ logger.error(e.stack); } }); router.get('/:subject/:rewrite?.:id.html', auth.checkAuthor, function(req, res) { try { let class_id = req.tndata.user.class_id; let id = req.params.id; let param_render = { layout: 'answer-layout', title: 'Luyện tập lớp ' + class_id + ' Trạng Nguyên', class_id: class_id, className: class_id == 0 ? 'mẫu giáo' : class_id, base_url: req.baseUrl, subject_url: req.subject_url, subject_name: req.subject_name }; ExamAnswersService.info(id, (err, info)=>{ if(err) logger.error(err); else{ if(info){ if(info.class_id == class_id){ req.tndata.id = id; param_render.title = info.name + ' - lớp ' + class_id + ' - Trạng Nguyên'; param_render.pageName = info.name; param_render.ads = false; // let num = util.randomInt(10,30); // let s = util.randomString(num); // param_render.info = s + CryptoJS.AES.encrypt(JSON.stringify(info), 'MVT2017' + s).toString() + num; res.render('answer-play', param_render); } else{ res.status(401).render('error',{ error: 401, message: 'Bài thi này không giành cho lớp của bạn' }); } } else{ res.status(404).render('error',{ error: 404, message: 'Địa chỉ này không tồn tại' }); } } }); } catch(e){ logger.error(e.stack); } }); router.get('/:subject/play.min.js', auth.checkAuthor, function(req, res) { res.header('content-type','application/x-javascript; charset=utf-8'); let id = util.parseInt(req.tndata.id); let user = req.tndata.user; let user_id = user._id; // let referer = req.header('Referer'); delete req.tndata.id; if(id>0){ async.waterfall([ callback=>{ UserService.checkVip(user_id, (err, info)=>{ if(err){ logger.error(err); } else{ if(info){ if(info.vip_expire){ if(info.vip_expire >= new Date()){ callback(null, {}); } else{ res.send('Alert("Tài khoản luyện tập của bạn đã hết hạn.<br/>Bạn hãy nộp học phí");'); } } else{ res.send('Alert("Bạn chưa nộp học phí.<br/>Bạn hãy nộp học phí");'); } } else{ res.send('Alert("Không tìm thấy thông tin người dùng");'); } } }); }, //check mark // (data, callback) => { // if(user.mark){ // callback(null, data) // } // else{ // res.send('Alert("Bạn đăng nhập ở quá nhiều thiết bị.\nVui lòng liên hệ với BTC để được trợ giúp");'); // } // }, (data,callback)=>{ ExamAnswersService.info(id, (err, info)=>{ if(err) logger.error(err); else{ if(info) { let num = util.randomInt(10, 30); let s = util.randomString(num); let response = { layout: null, name: info.name, description: (info.description && info.description!='')? info.description: 'Nếu là câu trắc nghiệm hãy chọn đáp án đúng nhất.<br/>Nếu là câu điền, hãy nhập vào ô đáp án của bạn.<br/>Click vào nút <strong>Bắt đầu</strong> để bắt đầu luyện.', play: info.play, time: info.time, spq: 10 }; delete info._id; delete info.name; delete info.play; delete info.time; response.info = s + CryptoJS.AES.encrypt(JSON.stringify(info), 'MVT2017' + s).toString() + num; res.render('game/examAnswers', response); } else{ res.send('Alert("Không có thông tin bài thi");'); } } }); } ]); } else{ res.render('game/examAnswers',{ layout: null, info:'btm290doxnh9xU2FsdGVkX1+jGL+AONfxUmTxLWNRznJ22GH0OmC9dt8NignsTmKij2ybNEOEfAcJJl21Z7cObXq6U5VRsV9lGnAxyW5v1A2S1QxrRxVqVschn9N+QSPbKR4JiitzRn4HLjk9s8KA+H7Y0/yW6D5DI2l1lCFPsxKHQW97WQDS/F39Q7jl5ByRgIXGpM6B2SqmJBktWwmihaPejGZRf5byL2B0AuBNedBQAt/ZPaP5RmzFrVdAxPyNmaP0C70iljrPCTqK/50DKfEercNP2vCTz0Ad3EQ3elJRjb9i4RLbSujHvrrul+JVny8iIZvvJnJyePvznTrUHyN4K+BNYN39KiwkOhCMVMLyALF2p7ZFI5UXc2FX3J4A0S+eI0HE755pb8l5oHj6qZKfWUfzq+wfj00VWtjOOe03KxJMXq3euGz8NNcIISCwAmjfFSgv499NCAUs1XmYr3nQ8pEuwqeGM1dZ/D9Te/zhHb7QjU5lLVffKOT+LCmbLhgswhgBp1D0aiSh5oA3QV2Xmt/xjElCcTQKK/HdKPKOvJc1AiM6nBbk9hOz8dRiiEP2EOJjygaGZ9jo1xlbjmVrWsJRsXa15Z7L6PhxI3JH7hZ9BfUJJASJGqusvzSSJaN4Hk6SzmXvbUmHjzFg3wyfY5QWMB3SK7UkDPdUk+8ZQUu3kQxeNfBSUcmUVB/d0V5NBh5dnIjx4ZifRjjcQPwuYFRbRJwYwzhvoyAv8L4Y/UAdymWxKV5QbUE21YwrHhn+qG+mATJvuVc2MM+a5scZDJDJsNUhUX4PYFsaMJFSCuoGnmc1lZu5Aff83WwbN26tgBFU5kIxSfbdP2c8uv4PQTDFXFiNUP7dfxHsao+9M0gu1bhtcL2kJ1RD1alJWKfOpVtEZPonhJ92fiuDSD9x5OTrY0i7uM5jh9qpCQk1YT4l+yh10EjfpcLs4AUNQU6iTrKsAkoLFLwpiLRQfoW2xfkB+LOOso8prT5xEiUM0abLGazebKWAD++Xw7tW0UJP4wX+ONm9FZVknqkw0cF5vJBb1l1bW1YEhZG3BnfOYf9T/AVFtC/VH2Jy0gjn+Yn+C2ZdRS+qJ7O01G7Jvl+AAM6yYGFSHSWuD6UdqeblHJbagi+u0ue5ykIDXDPTYtL9Cm54UluR0MdxHgzxu+wUNjFd2pvsiigq1DZLmHZfwtzOoih3MVRDpDwzFRKp6d6XmKUilUR2cLyeOcFmgupqmhDpLm6R1HotLxWLllF3h4WmZvChdjb2dqOTWjCZbYXMDSSf2APS1eWNABMJp6pYiJeyF01nrjV2Y88u9cjI+2dYhOQzfDOFBP88xXTthFwcPKYNz14fKGaj5wAJp20HHjL5Hzv0Pc+waIAe7y8Y+Emna1XirUXHFusUwbhYxfBHfhqk5ST3fDcUlIQOKV7nZWaftrKwe9TCwdryjjT99uDQTWyZ70cbMtIwnl5TEh6wBpSldTYm+M6Jtco/7t7ggBdpiaAkviFoznxE4+nCx3Yd9C94FiORK8MFsDz/3jYqDSmpQedyMrThR7hXQYzRtAu+EhD6zURsulQxnKXuIAhUalFY3Pe1TjIRokFn++yf8wXcoBTtLwBh0GAsm0MGSGkcriLUbdaJox+3bzafzwucaGjnj82xF0yoG+Ow4ZCxLmApvLddy/ICqNdhU0UDKN07HIzKDKE6sJECys2NS8/2DV3+EBhuS3g+9ZYr2/8kMigbMyf3pGmjCv7nmBLPNLooCnqdLD68yK1JdGXmIwd6rvGa7G9JL+o04wtcOEQNMpwDJMwT13', name: 'Trạng Nguyên Tiếng Việt', description: 'play thôi', play: 0, time: 10000, spq: 1 }); } }); module.exports = router;
define([ 'app' ], function (app) { app.registerFilter('isSuperAdmin', function () { return function (value) { return value ? '超级管理员' : '管理员'; } }); });
var express = require('express'); var roomTypesRouter = express.Router(); //------------------------------------------------------------------------ // Models var RoomType = Utils.getModel('RoomType'); //------------------------------------------------------------------------ // Validator var validator = Utils.getValidator('roomTypes'); //------------------------------------------------------------------------ // API paths roomTypesRouter.get('/', validator.validateGetRequest, (req, res, next) => { RoomType .find({propertyId: req.query.propertyId}) .exec((err, roomTypes) => { if (err) return next(err); res.status(200).json({roomTypes: roomTypes}); }); }); roomTypesRouter.get('/:roomTypeId', validator.validateGetSingleRequest, (req, res, next) => { RoomType .findById(req.params.roomTypeId) .exec((err, roomType) => { if (err) return next(err); if (!roomType) return res.status(404).json({message: 'can\'t find any roomType by provided id'}); res.status(200).json({roomType: roomType}); }); }); roomTypesRouter.post('/', validator.validatePostRequest, (req, res, next) => { var roomType = new RoomType(req.body); roomType.save((err) => { if (err) return next(err); res.status(200).json({roomTypeId: "/api/roomTypes/" + roomType._id}); }); }); roomTypesRouter.put('/:roomTypeId', validator.validatePutRequest, (req, res, next) => { RoomType .findById(req.params.roomTypeId) .exec((err, roomType) => { if (err) return next(err); if (!roomType) return res.status(404).json({message: 'can\'t find any roomType by provided id'}); Object.assign(roomType, req.body); roomType.save((err) => { if (err) return next(err); res.status(200).json({roomTypeId: '/api/roomTypes/' + roomType._id}); }); }); }); roomTypesRouter.delete('/:roomTypeId', validator.validateDeleteRequest, (req, res, next) => { RoomType .findById(req.params.roomTypeId) .exec((err, roomType) => { if (err) return next(err); if (!roomType) return res.status(404).json({message: 'can\'t find any roomType by provided id'}); roomType.remove((err) => { if (err) return next(err); res.status(200).json({message: 'removed'}); }); }); }); //------------------------------------------------------------------------ // Exports module.exports = roomTypesRouter;
const crypto = require('crypto') module.exports = { getData(userCookie) { const shasum = crypto.createHash('sha1') shasum.update(userCookie) // similate aysnc service call here return new Promise((res) => { setTimeout(() => { const sha = shasum.digest('hex') res(sha) }, 1000) }) } }
import {instance} from './AuthenticationService'; export const API_ADMIN = '/admin' export const API_ORGANIZATION_ALL = API_ADMIN + '/organization/all' export const API_ADD_ORGANIZATION = API_ADMIN + '/organization/add/organization' export const API_FILE = '/file' export const API_FILE_UPLOAD = API_FILE + '/upload' class ApiService { getAllOrganization(){ return instance.get(API_ORGANIZATION_ALL); } addOrganization(organization){ return instance.post(API_ADD_ORGANIZATION, organization); } uploadFile(file){ const formData = new FormData(); formData.append('file',file) const config = { headers: { 'content-type': 'multipart/form-data' } } return instance.post(API_FILE_UPLOAD, formData, config) } getFile(fileId){ return instance.get(API_FILE + "/" + fileId); } } export default new ApiService()
import PropTypes from 'prop-types' import React from 'react' import pic01 from '../images/pic01.jpg' import pic02 from '../images/pic02.jpg' import pic03 from '../images/pic03.jpg' import evcharger from '../images/EVcharger.jpeg' import home from '../images/home.jpeg' import industrial from '../images/industrial.jpeg' import commercial from '../images/commercial.jpeg' import emailjs from 'emailjs-com'; class Main extends React.Component { render() { let close = ( <div className="close" onClick={() => { this.props.onCloseArticle() }} ></div> ) function sendEmail(e) { e.preventDefault(); emailjs.sendForm('service_aowwt6i', 'template_aet7kl2', e.target, 'user_a0rjfw8OMeVzDOA0zEqBY') .then((result) => { console.log(result.text); }, (error) => { console.log(error.text); }); } return ( <div ref={this.props.setWrapperRef} id="main" style={this.props.timeout ? { display: 'flex' } : { display: 'none' }} > <article id="intro" className={`${this.props.article === 'intro' ? 'active' : ''} ${ this.props.articleTimeout ? 'timeout' : '' }`} style={{ display: 'none' }} > <h2 className="major">Our Services</h2> <span className="image main"> <img src={evcharger} alt="" /> </span> <h2>Electrical Vehicle Charging</h2> <p> All Netz Electric employees are Tesla and Chargepoint certified installers. We can provide installation for condominium buildings, residential homes, and commercial parking lots. </p> <button> learn more</button> <span className="image main"> <img src={home} alt="" /> </span> <h2>Residential</h2> <p>Whether you're looking to add lighting, build your dream home, or start that next construction project Netz Electric is here to help!</p> <button> learn more</button> <span className="image main"> <img src={industrial} alt="" /> </span> <h2>Industrial</h2> <p>Adding a new piece of machinery? Need to change all of your current lighting to LED to save money on hydro cost? Do you have an old piece of machinery that just keeps giving you issues? Give us a call and we will be there for you!</p> <button> learn more</button> <span className="image main"> <img src={commercial} alt="" /> </span> <h2>Commercial</h2> <p>We provide a wide range of services ranging from restaurants to office spaces. We're here to help!</p> <button> learn more</button> {close} </article> <article id="work" className={`${this.props.article === 'work' ? 'active' : ''} ${ this.props.articleTimeout ? 'timeout' : '' }`} style={{ display: 'none' }} > <h2 className="major">Work</h2> <span className="image main"> <img src={pic02} alt="" /> </span> <p> Adipiscing magna sed dolor elit. Praesent eleifend dignissim arcu, at eleifend sapien imperdiet ac. Aliquam erat volutpat. Praesent urna nisi, fringila lorem et vehicula lacinia quam. Integer sollicitudin mauris nec lorem luctus ultrices. </p> <p> Nullam et orci eu lorem consequat tincidunt vivamus et sagittis libero. Mauris aliquet magna magna sed nunc rhoncus pharetra. Pellentesque condimentum sem. In efficitur ligula tate urna. Maecenas laoreet massa vel lacinia pellentesque lorem ipsum dolor. Nullam et orci eu lorem consequat tincidunt. Vivamus et sagittis libero. Mauris aliquet magna magna sed nunc rhoncus amet feugiat tempus. </p> {close} </article> <article id="about" className={`${this.props.article === 'about' ? 'active' : ''} ${ this.props.articleTimeout ? 'timeout' : '' }`} style={{ display: 'none' }} > <h2 className="major">About</h2> <span className="image main"> <img src={pic03} alt="" /> </span> <h3 style={{textAlign:'center'}}>Reliable Electricians</h3> <p> Netz Electric specializes in residential, commercial and industrial services. Whether you need a small wiring fix or the installation of a state-of-the-art smart home, we can help. </p> <h3 style={{textAlign:'center'}}>Flexible Services</h3> <p> We provide a thorough consultation to explain your available options. With that information, you can choose the scope of work that’s right for your home or business and for your budget. </p> <h3 style={{textAlign:'center'}}>Satisfaction Guaranteed</h3> <p> We strive to save you both time and money by combining experience, high quality parts and equipment, and exceptional service. We will stick with the job until you are satisfied. </p> {close} </article> <article id="contact" className={`${this.props.article === 'contact' ? 'active' : ''} ${ this.props.articleTimeout ? 'timeout' : '' }`} style={{ display: 'none' }} > <h2 className="major">Contact</h2> <p>We stay in constant communication with our customers until the job is done. To get a free quote, or if you have questions or special requests, just drop us a line. </p> <form onSubmit={sendEmail}> <div className="field half first"> <label htmlFor="name">Name</label> <input type="text" name="user_name" id="name" /> </div> <div className="field half"> <label htmlFor="email">Email</label> <input type="email" name="user_email" id="email" /> </div> <div className="field half first"> <label htmlFor="phone">Phone</label> <input type="text" name="phone" id="phone" /> </div> <div className="field half"> <label htmlFor="address">Address</label> <input type="text" name="address" id="address" /> </div> <div className="field"> <label htmlFor="message">Message</label> <textarea name="message" id="message" rows="4"></textarea> </div> <ul className="actions"> <li> <input type="submit" value="Get A Free Quote" className="special" onClick={() => { this.props.onCloseArticle() }} /> </li> <li> <input type="reset" value="Reset" /> </li> </ul> </form> <p><b>NETZ ELECTRIC</b><br></br><small>17 Mcmahon Drive, Toronto, Ontario M2K 0E4, Canada</small><br></br><small></small></p> <ul className="icons"> <li> <a href="https://api.whatsapp.com/send/?phone=16479689674&text&app_absent=0" className="icon fa-whatsapp" > <span className="label">Whatsapp</span> </a> </li> <li> <a href="#" className="icon fa-facebook"> <span className="label">Facebook</span> </a> </li> <li> <a href="#" className="icon fa-instagram"> <span className="label">Instagram</span> </a> </li> </ul> {close} </article> </div> ) } } Main.propTypes = { route: PropTypes.object, article: PropTypes.string, articleTimeout: PropTypes.bool, onCloseArticle: PropTypes.func, timeout: PropTypes.bool, setWrapperRef: PropTypes.func.isRequired, } export default Main
import React from 'react' import { Box } from 'theme-ui' const Divider = ({ space, line }) => ( <Box sx={{ minWidth: `auto`, borderTopStyle: `solid`, borderTopColor: line ? `grayLighter` : `transparent`, borderTopWidth: 2, height: 0, my: [space - 1, space] }} /> ) export default Divider Divider.defaultProps = { space: 4, line: false }
'use strict'; module.exports = Bitset; function Bitset () { this.intArray = [0,0]; } Bitset.prototype.put = function (i) { this.intArray[i >>> 5] |= 1 << (31 & i); return this; } Bitset.prototype.flip = function (i) { this.intArray[i >>> 5] ^= 1 << (31 & i); return this; } Bitset.prototype.remove = function (i) { var idx = i >>> 5; if (idx < this.intArray.length) this.intArray[idx] &= ~(1 << (31 & i)); return this; } Bitset.prototype.has = function (i) { var idx = i >>> 5; if (idx >= this.intArray.length) return false; return this.intArray[idx] & (1 << (31 & i)); } Bitset.prototype.reset = function () { Bitset.call(this); return this; } Bitset.prototype.union = function (that) { var m = this.intArray.length; var n = that.intArray.length; var i; if (m < n) { this.intArray.length = n; for (i = m; i < n; ++i) this.intArray[i] = that.intArray[i]; } for (i = 0; i < m; ++i) this.intArray[i] |= that.intArray[i]; return this; } Bitset.prototype.intersect = function (that) { var m = this.intArray.length; var n = that.intArray.length; if (m > n) this.intArray.length = n; for (var i = 0; i < Math.min(m, n); ++i) this.intArray[i] &= that.intArray[i]; return this; } Bitset.prototype.difference = function (that) { var m = this.intArray.length; var n = that.intArray.length; for (var i = 0; i < Math.min(m,n); ++i) this.intArray[i] &= ~that.intArray[i]; return this; } Bitset.prototype.hasSubset = function (that) { var m = this.intArray.length; var n = that.intArray.length; var l = Math.min(m,n); var i = 0; var s = true; var a, b; while (i < l && s) { a = (this.intArray[i]|0); b = (that.intArray[i]|0); s = ((a & b) === b); ++i; } while (s && i < n) { s = !that.intArray[i]; ++i; } return s; } Bitset.prototype.isSubsetOf = function (that) { return that.hasSubset(this); } Bitset.prototype.isEmpty = function () { var n = this.intArray.length; for (var i = 0; i < n; ++i) if (this.intArray[i]) return false; return true; } Bitset.prototype.max = function () { for (var i = this.intArray.length - 1; i >= 0; --i) { var b = this.intArray[i]; if (b !== 0 && b !== undefined) return (i << 5) | Bitset.msb(b); } return undefined; } Bitset.prototype.min = function () { for (var i = 0; i < this.intArray.length; ++i) { var b = this.intArray[i]; if (b != 0) return (i << 5) + Bitset.lsb(b); } return undefined; } Bitset.prototype.count = function () { var c = 0; for (var i in this.intArray) c += Bitset.count(this.intArray[i]); return c; } Bitset.prototype.isSingleton = function () { var c = 0; var i = 0; var n = this.intArray.length; while (i < n && c < 2) { c += Bitset.count(this.intArray[i]); ++i; } return c === 1; } Bitset.prototype.each = function (f) { var b = 0; for (var i in this.intArray) { b = this.intArray[i]; for (var j = 0, k = 1; j < 32; ++j, k <<= 1) if (b & k) f((i << 5) | j); } } Bitset.prototype.map = function (f) { var result = new Array(this.count()); var i = 0; this.each(function (x) { result[i] = f(x, i); ++i; }); return result; } Bitset.prototype.toArray = function () { return this.map(function (x) { return x; }); } Bitset.prototype.toString = function () { return this.toArray().toString(); } // Alternative Bitset constructors Bitset.empty = function () { return new Bitset(); } Bitset.singleton = function (i) { return Bitset.empty().put(i); } Bitset.with = function (x) { var a = (x instanceof Array) ? x : arguments; var b = new Bitset(); for (var i = 0; i < a.length; ++i) b.put(a[i]) return b; } Bitset.from = function (i) { var b = new Bitset(); b.intArray = [i,0]; return b; } Bitset.copy = function (a) { var b = new Bitset(); b.intArray = a.intArray.slice(0); return b; } Bitset.union = function (a, b) { return Bitset.copy(a).union(b); } Bitset.intersection = function (a, b) { return Bitset.copy(a).intersect(b); } Bitset.difference = function (a, b) { return Bitset.copy(a).difference(b); } // Collection of 32bit operations, freely adapted from // https://graphics.stanford.edu/~seander/bithacks.html // maintained in the public domain by Sean Eron Anderson. // Most significant bit set in integer, // without 0 check, returns 0 when input 0. Bitset.msb = function (b) { var r = 0; var s = 0; r = ((b >>> 16) !== 0) << 4; b >>>= r; s = ((b >>> 8) !== 0) << 3; b >>>= s; r |= s; s = ((b >>> 4) !== 0) << 2; b >>>= s; r |= s; s = ((b >>> 2) !== 0) << 1; b >>>= s; r |= s; r |= (b >>> 1); return r; } // Least significant bit set in integer, // without 0 check, returns 0 when input 0. Bitset.lsb = function (b) { return Bitset.msbP2((b & (b-1)) ^ b); } // Most significant bit in a power of 2. Bitset.msbP2 = function (b) { var r = 0; r = (b & 0xAAAAAAAA) != 0; r |= ((b & 0xFFFF0000) != 0) << 4; r |= ((b & 0xFF00FF00) != 0) << 3; r |= ((b & 0xF0F0F0F0) != 0) << 2; r |= ((b & 0xCCCCCCCC) != 0) << 1; return r; } // Reverse the bits in an integer. Bitset.reverse = function (b) { b = b << 16 | b >>> 16; b = (b & 0x00FF00FF) << 8 | (b & 0xFF00FF00) >>> 8; b = (b & 0x0F0F0F0F) << 4 | (b & 0xF0F0F0F0) >>> 4; b = (b & 0x33333333) << 2 | (b & 0xCCCCCCCC) >>> 2; b = (b & 0x55555555) << 1 | (b & 0xAAAAAAAA) >>> 1; return b; } // Interleave lower significance 16 bits. Bitset.interleave = function (x, y) { var z = 0; x = (x | x << 8) & 0x00FF00FF; x = (x | x << 4) & 0x0F0F0F0F; x = (x | x << 2) & 0x33333333; x = (x | x << 1) & 0x55555555; y = (y | y << 8) & 0x00FF00FF; y = (y | y << 4) & 0x0F0F0F0F; y = (y | y << 2) & 0x33333333; y = (y | y << 1) & 0x55555555; z = x | y << 1; return z; } // count bits in integer Bitset.count = function (b) { for (var c = 0; b; ++c) b &= b - 1; return c; } // determine if integer is power of 2 Bitset.isPowerOf2 = function (b) { return b && !(b & (b - 1)); } // display as binary string `0b00101 ...` // Optional second parameter indicates a desired // minimum of bits displayed (maximum 32) Bitset.toBinary = function (n, d) { d = d || 0; var b = '0b'; var i = 31; while (i > 0 && i >= d && !(n & (1 << i))) --i; while (i >= 0) b += (n & (1 << i--) ? '1' : '0'); return b; }
 const hubConnection = new signalR.HubConnectionBuilder() .withUrl("/chat") .configureLogging(signalR.LogLevel.Information) .withAutomaticReconnect() .build(); hubConnection.serverTimeoutInMilliseconds = 1000 * 60 * 10; // 1 second * 60 * 10 = 10 minutes. let userName = "123"; let message = { name: userName }; // get new message from server hubConnection.on("Receive", function (message) { message.dialogid = message.dialogid; let newMessage = document.createElement("div"); if (message.senderType == "in") { newMessage.className = "chat first"; } else { newMessage.className = "chat second"; } newMessage.appendChild(document.createTextNode('Name:' + message.name)); // creates <p> element for user`s message let messageText = document.createElement("p"); if (message.textTupe == "json") { jsontext = JSON.parse(message.text); messageText.appendChild(document.createTextNode(jsontext.text)); newMessage.appendChild(messageText); if (jsontext.buttoncount > 0) { for (let i = 0; i < jsontext.textbutton.length; i++) { var button = document.createElement("button"); button.innerHTML = jsontext.textbutton[i]; button.classList.add("btn-interract"); button.classList.add("btn"); button.classList.add("btn-primary"); newMessage.appendChild(button); messageText.appendChild(button); button.onclick = UserButtonInterracts; newMessage.appendChild(document.createElement("br")); } } var str = " <span class=\"time\"><\/span>"; messageText.insertAdjacentHTML('beforeend', str); } else { messageText.appendChild(document.createTextNode(message.text)); var str = " <span class=\"time\"><\/span>"; messageText.insertAdjacentHTML('beforeend', str); newMessage.appendChild(messageText); } var firstElem = document.getElementById("chat-messages").firstChild; document.getElementById("chat-messages").insertBefore(newMessage, firstElem); }); hubConnection.start();
const amqp = require('amqplib/callback_api') const CONN_URL = 'amqp://ykehzqib:w2bn-j43V8EKl8-KO4tZ1ri8uHL9x8Bv@vulture.rmq.cloudamqp.com/ykehzqib'; module.exports = function(cb) { amqp.connect(CONN_URL, function(err, conn) { if (err) { throw new Error(err) } cb(conn) }) }
/** * 验收中心不通过 */ import React, { Component, PureComponent } from "react"; import { StyleSheet, Dimensions, View, Text, TextInput, TouchableOpacity, } from "react-native"; import { connect } from "rn-dva" import moment from 'moment' import CommonStyles from '../../common/Styles' import Header from '../../components/Header' import Content from "../../components/ContentItem"; import * as taskRequest from '../../config/taskCenterRequest' const { width, height } = Dimensions.get("window") function getwidth(val) { return width * val / 375 } export default class CancelTaskAudit extends Component { saveData = () => { let val = this.cancelReson._lastNativeText if (!val) { Toast.show('请输入原因') return } const { navigation } = this.props const { taskId, taskcore, callback, isToCneter, listcallBack } = navigation.state.params if (taskcore !== 'acceptancecore') { let param = { jobId: taskId, // action: 'no', reason: val, // merchantTaskNode:merchantTaskNode, } //审核 taskRequest.fetchMerchantauditFail(param).then(() => { Toast.show('操作成功') if (callback) { callback(1) } if (listcallBack) { listcallBack(1) } if (isToCneter) { navigation.navigate('TaskList') } else { navigation.navigate('TaskDetail') } }).catch((err)=>{ console.log(err) }); } else { let param = { jobId: taskId, // action: 'no', // merchantTaskNode:merchantTaskNode, reason: val, } //验收 taskRequest.fetchMerchantJoincheckJobFail(param).then((res) => { Toast.show('操作成功') if (callback) { callback(1) } if (listcallBack) { listcallBack(1) } navigation.navigate('TaskList') }).catch((err)=>{ console.log(err) }); } } render() { const { navigation } = this.props return ( <View style={styles.container}> <Header navigation={navigation} goBack={true} title='审核不通过原因' /> <Content style={styles.content}> <TouchableOpacity style={{ width: '100%', height: '100%' }} onPress={ () => { this.cancelReson.focus() } } > <TextInput multiline={true} autoFocus={true} placeholder='取消原因' returnKeyLabel="确定" returnKeyType="done" ref={(ref) => { this.cancelReson = ref }} /> </TouchableOpacity> </Content> <TouchableOpacity onPress={this.saveData} style={styles.savebtn}> <Text style={styles.cff17}>确认提交</Text> </TouchableOpacity> </View> ) } } const styles = StyleSheet.create({ container: { ...CommonStyles.containerWithoutPadding, alignItems: 'center', backgroundColor: CommonStyles.globalBgColor, }, content: { width: getwidth(355), height: 196, paddingHorizontal: 15 }, savebtn: { width: getwidth(355), height: 44, backgroundColor: '#4A90FA', borderRadius: 8, justifyContent: 'center', alignItems: 'center', marginTop: 20 }, cff17: { color: '#FFFFFF', fontSize: 17 } })
'use strict'; const supportedTypes = ['staffClassification', 'styles']; const COLLECTION = 'config'; class ConfigRepository { constructor(firestore) { this.firestore = firestore; } /** * Query for all the contents within the config * collection associated with the provided document * * @param {String} type * @returns {*} * @memberof ConfigRepository */ async query(docId) { const snapshot = await this.firestore .collection(COLLECTION) .doc(docId) .get(); if (snapshot && snapshot.exists) { return snapshot.data(); } return {}; } } module.exports = ConfigRepository; module.exports.supportedTypes = supportedTypes; module.exports.configRepositoryInstance = new ConfigRepository( require('./firestore') );
export const displayModal= () => { const backdrop = document.getElementById('backdrop') backdrop.classList.remove('display-none') document.getElementById('close-modal').addEventListener('click', () => { backdrop.classList.add('display-none') }) }
var fxApp = angular.module('pricing'); fxApp.controller('LoginCtrl', function($scope, $rootScope, $state, AUTH_EVENTS, AuthService) { $scope.credentials = { useremail: '', password: '' }; $scope.loginResult = null; $scope.login = function(credentials) { AuthService.login(credentials) .then(function(user) { if (user == "Failed") { $scope.loginResult = "Login Failed!"; $rootScope.$broadcast(AUTH_EVENTS.loginFailed); } else { $scope.loginResult = null; $rootScope.$broadcast(AUTH_EVENTS.loginSuccess); $scope.setCurrentUser(user); $state.go('watchlist', {}); } }); } })
/* jshint indent: 2 */ module.exports = function(sequelize, DataTypes) { return sequelize.define('acc_integrations', { acc_integrations_id: { type: DataTypes.INTEGER(10).UNSIGNED, allowNull: false, primaryKey: true, autoIncrement: true }, acc_environment_id: { type: DataTypes.INTEGER(10).UNSIGNED, allowNull: false }, integration_name: { type: DataTypes.STRING(255), allowNull: false }, api_key: { type: DataTypes.STRING(255), allowNull: false }, api_signature: { type: DataTypes.STRING(255), allowNull: false }, extravar1: { type: DataTypes.STRING(255), allowNull: false }, extravar2: { type: DataTypes.STRING(255), allowNull: false }, status: { type: DataTypes.INTEGER(4), allowNull: true, defaultValue: '0' } }, { tableName: 'acc_integrations' }); };
const countLetters = data => { const noSpaces = data.replace(/ /g, ""); //g removes all spaces (g for global) let result = {}; for (let i = 0; i < noSpaces.length; i++) { if (!result[noSpaces[i]]) { result[noSpaces[i]] = [i]; } else { result[noSpaces[i]].push(i); } } return res; }; console.log(countLetters("vrbo in the house")); console.log(countLetters("mississippi"));
var mongoose = require("mongoose"); var Schema = mongoose.Schema; var TheatreSchema = Schema({ name: String, address: String, other: String, pin:String }); module.exports = mongoose.model('Theatre', TheatreSchema);
const PREFIX = '$$route'; const exportMethod = {}; // define absolute url exportMethod.full = {}; const throwError = (msg) => { throw new Error(msg); }; const getFullTag = isFull => (isFull ? 'F' : ''); function destruct(args) { const hasPath = typeof args[0] === 'string'; const path = hasPath ? args[0] : ''; const middleware = hasPath ? args.slice(1) : args; if (middleware.some(m => typeof m !== 'function')) { throwError('Middleware must be function'); } return [path, middleware]; } // @route(method, path: optional, ...middleware: optional) function route(method, isFull, ...args) { if (typeof method !== 'string') { throwError('The first argument must be an HTTP method'); } const [path, middleware] = destruct(args); return (target, name) => { const key = `${PREFIX}_${getFullTag(isFull)}_${name}`; if (!target[key]) { target[key] = []; } target[key].push({ key, method, path, middleware }); }; } // @[method](...args) === @route(method, ...args) const methods = ['get', 'post', 'put', 'patch', 'delete']; methods.forEach((method) => { exportMethod[method] = route.bind(null, method, false); exportMethod.full[method] = route.bind(null, method, true); }); function baseAuto(target, name, descriptor, isFull) { // parse key const keyChips = name.split(/(?=[A-Z])/).map(x => x.toLowerCase()); if (methods.indexOf(keyChips[0]) > -1) { const method = keyChips[0]; const tail = keyChips[keyChips.length - 1]; if (tail !== 'html' && tail !== 'json') { throwError(`method ${name} should end with Html or Json`); } if (keyChips.length < 3) { throwError('method body is not right'); } if (keyChips.length === 3 && keyChips[1] === 'index') keyChips[1] = ''; const path = `/${keyChips.slice(1, keyChips.length - 1).join(isFull ? '/' : '-')}`; const key = `${PREFIX}_${getFullTag(isFull)}_${name}`; if (!target[key]) { target[key] = []; } target[key].push({ key, method, path, middleware: [] }); } else { throwError(`method ${name} cannot match any legal word, please use follwing words: ${methods}`); } } const auto = (...args) => baseAuto(...args, false); const fullAuto = (...args) => baseAuto(...args, true); // @controller(path: optional, ...middleware: optional) function controller(...args) { const [ctrlPath, ctrlMiddleware] = destruct(args); return (target) => { const proto = target.prototype; proto.$routes = Object.getOwnPropertyNames(proto) .filter(prop => prop.indexOf(PREFIX) === 0) .map(prop => proto[prop]) .reduce((prev, next) => prev.concat(next), []) .map((prop) => { const { key, method, path, middleware: actionMiddleware } = prop; const middleware = ctrlMiddleware.concat(actionMiddleware); const [, isFull, fnName] = key.split('_'); const url = `${isFull ? '' : ctrlPath}${path}`.replace(/\/\//g, '/'); return { method, url, middleware, fnName }; }); }; } exportMethod.auto = auto; exportMethod.controller = controller; exportMethod.full.auto = fullAuto; export default exportMethod;
/* Author: Byron Lutz */ /***** ENABLE DONATE BUTTON *****/ $(document).ready(function() { $('.menu-donate a').click(function(e) { e.preventDefault(); $.pressplus.f.pop('plans'); }); }); /***** CONTROL SIDEBAR POPULAR STORIES TABS *****/ $(document).ready(function() { $('#popular-select').click(sidebarChange); $('#commented-select').click(sidebarChange); $('#side-info-commented').hide(); function sidebarChange(eventObject) { eventObject.preventDefault(); var switchTo = $(this).attr('id'); $('#popular-select').removeClass('activetab'); $('#commented-select').removeClass('activetab'); $(this).addClass('activetab'); $('#side-info-popular').hide(); $('#side-info-commented').hide(); $('#'+$(this).attr('data-target')).show(); } }); /***** ADJUST SIDEBAR HEIGHT *****/ $(document).ready(function() { if($(window).width() >= 980) { var heightOfArticle = Math.max($('#sidebar').height(), $('article.post').height()); if($('#post-listing').height()) heightOfArticle = Math.max($('#post-listing').height()-10, heightOfArticle); $('#sidebar').attr('style','height:'+heightOfArticle+'px'); } }); /***** TOGGLE DROPDOWNS *****/ $(document).ready(function() { $('.dropdown-toggle').dropdown(); }); /***** GET RID OF HARD IMAGE SIZES *****/ $(document).ready(function() { $('.wp-post-image').removeAttr('height').removeAttr('width'); }); /****** POPULAR POSTS WIDGET *******/ /* Inefficient; replace this later */ $(document).ready(function() { // Tabs control $('.togglemenu').click(popularPosts); function popularPosts(event) { event.preventDefault(); var changeTo = event.currentTarget.id.substr(11); $('.togglemenu-current').removeClass('togglemenu-current'); $('#togglemenu-'+changeTo).addClass('togglemenu-current'); $('.popularlist').hide(); $('#popularlist-'+changeTo).show(); }; // Take out the "comment(s)" in the display. WE NEED A BETTER PLUGIN o.o var commentNum=/^\d+/g; $('.wpp-comments').each(function() { $(this).text( $(this).text().match(commentNum) ); $(this).addClass('popularlist-comments'); }); }); /****** ROTATOR *******/ $(document).ready(function() { var rotator = $('#topcontent-rotator'); if(rotator.length > 0) { var rotator_index = 0; var rotator_stories = 4; function changeRotator(eventData) { eventData.preventDefault(); var forward = eventData.data.forward; // direction of the rotator var changeToStory = eventData.data.changeToStory; if (!changeToStory && ((forward && (rotator_index+1 >= rotator_stories)) || (!forward && rotator_index == 0))) { return; } (forward) ? rotator_index++ : rotator_index--; if(changeToStory) rotator_index = changeToStory-1; // Change slug $('.rotate-current').removeClass('rotate-current'); $('#rotate-label-'+(rotator_index+1)).addClass('rotate-current'); // Set button enabled/disabled state $('.topcontent-rotator-control-back.disabled').removeClass('disabled'); // Set all enabled $('.topcontent-rotator-control-forward.disabled').removeClass('disabled'); // Set all enabled if(rotator_index == 0) $('.topcontent-rotator-control-back').addClass('disabled'); else if(rotator_index == (rotator_stories -1)) $('.topcontent-rotator-control-forward').addClass('disabled'); // Change story $('.topcontent-rotator-content').hide(); $('#topcontent-rotator-content-'+(rotator_index+1)).show(); } // Bind buttons $('.topcontent-rotator-control-back').on("click", { forward: false }, changeRotator); $('.topcontent-rotator-control-forward').on("click", { forward: true }, changeRotator); // Bind top links $('#rotate-label-1 a').on("click", { changeToStory: 1 }, changeRotator); $('#rotate-label-2 a').on("click", { changeToStory: 2 }, changeRotator); $('#rotate-label-3 a').on("click", { changeToStory: 3 }, changeRotator); $('#rotate-label-4 a').on("click", { changeToStory: 4 }, changeRotator); } }); /****** RESPONSIVE STYLES *******/ $(document).ready(function() { // Large screen /* if($(window).width() >= 1200) { } */ // Small screen if($(window).width() <= 979 && $(window).width() >= 768) { $('#nameplate-date').removeClass('offset1').removeClass('span2').addClass('span3'); $('#toplinks-info').removeClass('span6').addClass('span8'); $('#toplinks-socialmedia').removeClass('offset3').addClass('offset1'); } // Phone (Horizontal & Vertical) if($(window).width() <= 767) { $('#nameplate-image img').attr('src','/img/nameplate-mobile.png'); $('.nameplate-date-weather').insertBefore('#nameplate-date'); $('#multimedia-rotator').insertAfter('#paidadvertising'); } });
var express = require('express'); var router = express.Router(); var passport = require('passport'); const app = express(); var dashboardController = require('../controllers/dashboardController'); router.get('/', dashboardController) /* GET leaderboard stats. */ router.get('/dashboard', function(req, res, next) { res.render('./dashboard', { title: 'Dashboard' }); }); module.exports = router;
import React, { useState } from 'react'; import { connect } from 'react-redux'; import { login } from '../actions'; import styled from 'styled-components'; import FriendForm from './FriendForm'; const Wrapper = styled.div` form { margin-top: 20px; display: flex; justify-content: center; } input { margin-right: 10px; font-size: 1.1rem; } button { font-size: 1.1rem; } `; const Login = props => { const [credentials, setCredentials] = useState({ username: '', password: '' }); const changeHandler = e => { setCredentials({ ...credentials, [e.target.name]: e.target.value }); }; const login = e => { e.preventDefault(); props.login(credentials).then(() => { props.history.push('/api/friends'); }); }; if (props.token !== '') { return <FriendForm />; } else { return ( <Wrapper> <form onSubmit={login}> <input type='text' name='username' placeholder='Username' value={credentials.username} onChange={changeHandler} /> <input type='password' placeholder='Password' name='password' value={credentials.password} onChange={changeHandler} /> <button>Log In</button> </form> </Wrapper> ); } }; export default connect( null, { login } )(Login);
/* Create a function that moves all capital letters to the front of a word. Examples capToFront("hApPy") ➞ "APhpy" capToFront("moveMENT") ➞ "MENTmove" capToFront("shOrtCAKE") ➞ "OCAKEshrt" */ function capToFront(s) { let res=''; for(let i=0;i<s.length;i++) { if(s.charAt(i).codePointAt(0)>=65 && s.charAt(i).codePointAt(0)<=90) { res+=s.charAt(i); } } for(let i=0;i<s.length;i++) { if(s.charAt(i).codePointAt(0)>=97 && s.charAt(i).codePointAt(0)<=122) { res+=s.charAt(i); } } return res; }
//[string]replace([old],[new]) var email = "thosekidsme@udacity.com"; var newEmail = email.replace("udacity","gmail"); console.log(email); console.log(newEmail); var bio = { "name" : "Vincent Huang", "role" : "Product Manager", "contacts" : { "mobile" : "+1 415.547.0369", "github" : "huangv22", "twitter": "@huangv", "location":"San Francisco", "blog" :"http://www.vincentkardiogram.com/", }, "welcomeMsg" : "Zig a Zig ahhh", "skills" : ["Saying, good question", "Product Management"], "bioPic":"images/me.png" } //*/ var formattedName = HTMLheaderName.replace("%data%",bio.name); var formattedRole = HTMLheaderRole.replace("%data%",bio.role); $("#header").prepend(formattedRole).prepend(formattedName); var formattedMobile = HTMLmobile.replace("%data%", bio.contacts.mobile); var formattedTwitter = HTMLtwitter.replace("%data%",bio.contacts.twitter); var formattedgithub = HTMLgithub.replace("%data%",bio.contacts.github); var formattedlocation = HTMLlocation.replace("%data%",bio.contacts.location); var formattedblog = HTMLblog.replace("%data%",bio.contacts.blog); $("#topContacts").append(formattedlocation).append(formattedMobile).append(formattedTwitter) .append(formattedgithub).append(formattedblog); var formattedWelcomeMsg = HTMLWelcomeMsg.replace("%data%", bio.welcomeMsg); var formattedbioPic = HTMLbioPic.replace("%data%",bio.bioPic); var formattedskills = HTMLskills.replace("%data%",bio.skills) $("#header").append(formattedbioPic).append(formattedWelcomeMsg); $("#header").append(HTMLskillsStart).append(formattedskills); // $("#header").append(formmatedName); /*/ Replacing Awesome with Fun var awesomeThoughts = "I am Vincent and I am AWESOME"; console.log(awesomeThoughts); var funThoughts = awesomeThoughts.replace("AWESOME","FUN"); console.log(funThoughts); $("#main").append(funThoughts); */
import Levenshtein from 'fast-levenshtein' class PlayerMatching { static getBestPlayerMatch(playerName, players) { console.log(playerName) console.log(players) const matches = [] const filteredPlayers = players.filter(player => player.toLowerCase().includes(playerName.toLowerCase())); const playersBeginning = players.filter(player => player.toLowerCase().startsWith(playerName.toLowerCase())); if (playersBeginning.length > 0) { for (const player of playersBeginning) { matches.push({ distance: Levenshtein.get(playerName, player), playerName: player }) } } else { for (const player of filteredPlayers) { matches.push({ distance: Levenshtein.get(playerName, player), playerName: player }) } } matches.sort((n1, n2) => n2 - n1); if (matches.length <= 0) return (null); // No matches if (playersBeginning.length > 0) { // If the beginning matched if (matches.length == 1) { // And there's only one match return { type: "good", playerName: matches[0].playerName }; } const playerNames = matches .slice(0, 10) .map((match) => match.playerName); return { type: "multi", playerNames: playerNames }; // Multiple matches } if (matches.length == 1) { return { type: "good", playerName: matches[0].playerName }; } if (matches[0].distance <= 3) { if (matches[1].distance - matches[0].distance <= 2) { // Multiple matches const playerNames = matches .slice(0, 10) .map((match) => match.playerName); return { type: "multi", playerNames: playerNames }; // Multiple matches } return (matches[0].playerName); } if (matches[1].distance - matches[0].distance <= 2) { const playerNames = matches .slice(0, 10) .map((match) => match.playerName); return { type: "multi", playerNames: playerNames }; // Multiple matches // Multiple matches } return { type: "far", playerName: matches[0].playerName }; // Far match } } export default PlayerMatching
function ready(){ console.log("Sono pronto a caricare tutti gli smartlife services"); var idcategoria=1; $.ajax({ method: "POST", crossDomain: true, //localhost purposes url: "includes/php/query.php", //percorso file.php data: {query : "SELECT * FROM categoriasmartlifeservice ORDER BY idsmartlife ASC"}, success: function(response) { var smartlifeservices=JSON.parse(response); var i=0; var container = document.getElementById("smartlifeServices"); for(i=0;i<smartlifeservices.length;i++){ console.log("sono nel for"); var urlCategoria = "smartlife_services_by_category.html?c=2?category=" +smartlifeservices[i].idsmartlife; var imgTemp = document.createElement("img"); var urlImmagine = "images/smartlife/" + smartlifeservices[i].immaginesmartlife; imgTemp.setAttribute('src', urlImmagine); imgTemp.setAttribute("class", "img-responsive"); var nomeTemp = document.createElement("a"); nomeTemp.setAttribute('class', 'btn btn-smsll btn-block btn-default'); nomeTemp.setAttribute("href", urlCategoria); var nome = document.createTextNode("Esplora i servizi della categoria"); nomeTemp.appendChild(nome); var descrTemp = document.createElement("p"); var descr = document.createTextNode(smartlifeservices[i].descrizionesmartlife); descrTemp.appendChild(descr); var categoria = document.createElement("div"); categoria.setAttribute("class", "col-sm-6 feature"); var categoriaPanel = document.createElement("div"); categoriaPanel.setAttribute("class", "panel"); var panelHeading = document.createElement("div"); panelHeading.setAttribute("class", "panel-heading"); var panelTitle = document.createElement("h4"); panelTitle.appendChild(document.createTextNode(smartlifeservices[i].nomesmartlife)); panelHeading.appendChild(panelTitle); categoriaPanel.appendChild(panelHeading); categoriaPanel.appendChild(imgTemp); categoriaPanel.appendChild(descrTemp); categoriaPanel.appendChild(nomeTemp); categoria.appendChild(categoriaPanel); container.appendChild(categoria); } }, error: function(request,error) { console.log("Error"); } }); } $(document).ready(ready);
import React, { useState } from 'react'; import Agenda from "./Agenda"; var w = window.innerWidth; var h = window.innerHeight; export default function PageY() { return( <div style={{ background: '#fff', padding: 24, minHeight:h/1.1,backgroundColor:'#ebebeb' }}> <h1 style={{alignSelf:'center',textAlign:'center',fontSize:20}}>Mon emploi du temps</h1> <Agenda/> </div> ) ; }
const Card = (prop) => { return ( <div> <img width='100' src={prop.avatar_url} /> <div style={{fontWeight: 'bold'}}> {prop.name} </div> <div> {prop.company} </div> <div> {prop.bio} </div> </div> ) } const CardList = (props) => { return ( <div> {props.cards.map(card => <Card {...card} />)} </div> ) } class Form extends React.Component { state = { userName: "" } inputChange = (event) => { this.setState({ userName: event.target.value }) } handleSubmit = (event) => { event.preventDefault(); axios(`https://api.github.com/users/${this.state.userName}`) .then(response => { this.props.onSubmit(response.data); this.setState({ userName: "" }); }) } render() { return ( <form onSubmit={this.handleSubmit} > <input type="text" placeholder="github login" required onChange={this.inputChange} value={this.state.userName} /> <button type="submit"> Add </button> </form> ) } } class App extends React.Component { state = { cards: [] } addNewCard = (cardInfo) => { this.setState(prevState => ({ cards: prevState.cards.concat(cardInfo) })) } render() { return ( <div> <Form onSubmit={this.addNewCard} /> <CardList cards={this.state.cards} /> </div> ) } } ReactDOM.render(<App />, mountNode);
/* 1)Write a function, which receives an array as an argument which elements arrays of numbers. Find biggest negative number of each array. Return product of that numbers.If there is not any negative number in an array, ignore that one. Check that items of the given array are arrays. Input | Output [[2,-9,-3,0],[1,2],[-4,-11,0]] | 12 [[3,4],[11,0],[5,6,7,8]] | 'No negatives' [1, 2, 3] | 'Invalid Argument' */ let myArr = [[2,-9,-3,0],[1,2],[-4,-11,0]]; function myFunc(arr) { let bigNegativNumsProd = []; let onlyArr = arr.every(elem => Array.isArray(elem)); if(!onlyArr) { console.log("Invalid Argument"); }else { arr.forEach(function(el) { let negativNums = el.filter(function(item) { return item < 0; }); negativNums.sort(function(a,b) { return b-a; }); if(typeof negativNums[0] === "number") { bigNegativNumsProd.push(negativNums[0]); } }); if(bigNegativNumsProd.length === 0) { console.log("No negatives"); }else { let result = bigNegativNumsProd.reduce(function(sum,i) { return sum *= i; }); return result; } } } console.log(myFunc(myArr)); /* 2)Given an array of strings and numbers. Print the number of integers and the number of strings in the array. Input |Output [1,'10','hi',2,3] |"Numbers: 3, Strings: 2" [1,4,'i am a string','456'] |"Numbers: 2, Strings: 2" */ let myArr = [1,4,'i am a string','456']; function filterNumbersEndStrings(arr) { let nums = arr.filter(elem => typeof elem === "number"); let strings = arr.filter(elem => typeof elem === "string"); console.log(`Numbers: ${nums.length}, Strings: ${strings.length}`); } filterNumbersEndStrings(myArr); /* 3)Given an array consisting from the arrays of numbers (like a two-dimensional array). Find sum of each row and print them as an array. Input | Output [[3,4,5],[1,0,0],[4,5,4],[8,8,-1]] | [12,1,13,15] [[8,35,2],[8],[5,6,-5,-6],[1,3,-9,0,-1]] | [45,8,0,-6] [[1],[2],[3],[4]] | [1,2,3,4] */ let myArr = [[3, 4, 5], [1, 0, 0], [4, 5, 4], [8, 8, -1]]; function sumOfArrNums(arr) { let newArr = []; arr.forEach(function(el) { let sumsOfArrDigths = el.reduce(function(sum,elem) { return sum += elem; },0); newArr.push(sumsOfArrDigths); }); console.log(newArr); } sumOfArrNums(myArr); /* 4)Given an array of integers. Write a function that return new array from first array, where removed even numbers, and odd numbers was multiplied with new array length Input | Output [5,4,78,0,-3,7] | [15,-9,21] [2,4,6,88] | [] [] | [] */ let myArr = [5,4,78,0, -3,7]; function myFunc(arr) { let mulArr = []; let newArr = arr.filter(function(elem) { return elem % 2 !== 0; }); newArr.forEach(function(el) { mulArr.push(el * newArr.length); },0); console.log(mulArr); } myFunc(myArr); /* 5)Given an array of numbers. Create an array containing only elements once. Input | Output [1,2,3,3,2,5] | [1,2,3,5] [4, 4] | [4] */ let myArr = [1,2,3,3,2,5]; function onlyElementsOnce(arr) { let sortedArr = arr.sort(); let newArr = sortedArr.filter((item,index,arr) => arr.indexOf(item) === index); console.log(newArr); } onlyElementsOnce(myArr); /* 6)Given an array. Create the array which elements are products between two neighbours. Input | Output [3,7,12,5,20,0] | [21,84,60,100,0] [1,1,4,32,6] | [1,4,128,192] */ let myArr = [3,7,12,5,20,0]; const productsBetweenTwoNeighbours = arr => { let result = []; let newArr = arr.map((elem,i,arr) => elem * arr[i+1]); result = newArr.slice(0,-1); console.log(result); } productsBetweenTwoNeighbours(myArr);
import React from 'react'; import PropTypes from 'prop-types'; function Product({ imgUrl, name, price, quantity }) { return ( <div> <img src={imgUrl} alt={name} width="640" /> <h2>{name}</h2> <p>Price: {price}$</p> <p>Quantity: {quantity < 50 ? 'Few left' : 'In stock'}</p> <button type="button">Add to cart</button> </div> ); } Product.defaultProps = { imgUrl: 'https://dummyimage.com/640x480/2a2a2a/ffffff&text=Product+image+placeholder', }; Product.propTypes = { imgUrl: PropTypes.string, name: PropTypes.string.isRequired, price: PropTypes.number.isRequired, }; export default Product;
"use strict"; var _ = require("lodash"); var React = require("react"); var Category = require("./Category.jsx"); var Tags = require("./Tags.jsx"); var GITHUB_REGEX = new RegExp('github.com/(.*?)/([^/?#]+)'); var VIMORG_REGEX = new RegExp('vim.org/scripts/script.php\\?script_id=\\d+'); // TODO(david): Form validation on submit! Not done right now because we // currently just save this raw data to be manually reviewed. var SubmitPage = React.createClass({ getInitialState: function() { return { name: '', author: '', github: '', vimorg: '', tags: [], category: "uncategorized", submitting: false }; }, onTagsChange: function(tags) { this.setState({tags: _.uniq(tags)}); }, onCategoryChange: function(category) { this.setState({category: category}); }, nameIsValid: function() { return this.state.name !== ''; }, authorIsValid: function() { return this.state.author !== ''; }, githubIsValid: function() { return this.state.github === '' || GITHUB_REGEX.test(this.state.github); }, vimorgIsValid: function() { return this.state.vimorg === '' || VIMORG_REGEX.test(this.state.vimorg); }, onNameChange: function(e) { return this.setState({name: e.target.value}); }, onAuthorChange: function(e) { return this.setState({author: e.target.value}); }, onGithubChange: function(e) { return this.setState({github: e.target.value}); }, onVimorgChange: function(e) { return this.setState({vimorg: e.target.value}); }, formIsValid: function() { return _.every([ this.nameIsValid(), this.authorIsValid(), this.githubIsValid(), this.vimorgIsValid() ]); }, // TODO(captbaritone): Submit the form via API onSubmit: function(e) { // Enable validation errors this.setState({submitting: true}); // Should the form actually submit? if (!this.formIsValid()) { e.preventDefault(); } }, render: function() { var submitting = this.state.submitting; return <div className="submit-page"> <h1>Submit plugin</h1> <form className="form-horizontal" action="/api/submit" method="POST" onSubmit={this.onSubmit} > <div className="control-group"> <label className="control-label" htmlFor="name-input">Name</label> <div className="controls"> <input type="text" name="name" id="name-input" className={submitting && !this.nameIsValid() ? 'error' : ''} placeholder="e.g. Fugitive" value={this.state.name} onChange={this.onNameChange} /> </div> </div> <div className="control-group"> <label className="control-label" htmlFor="author-input"> Author </label> <div className="controls"> <input type="text" name="author" id="author-input" className={submitting && !this.authorIsValid() ? 'error' : ''} placeholder="e.g. Tim Pope" value={this.state.author} onChange={this.onAuthorChange} /> </div> </div> <div className="control-group"> <label className="control-label" htmlFor="github-input"> GitHub link (optional) </label> <div className="controls"> <input type="text" name="github-link" id="github-input" className={submitting && !this.githubIsValid() ? 'error' : ''} placeholder="e.g. https://github.com/tpope/vim-fugitive" value={this.state.github} onChange={this.onGithubChange} /> </div> </div> <div className="control-group"> <label className="control-label" htmlFor="vimorg-input"> Vim.org link (optional) </label> <div className="controls"> <input type="text" name="vimorg-link" id="vimorg-input" placeholder={"e.g. " + "http://www.vim.org/scripts/script.php?script_id=2975"} className={submitting && !this.vimorgIsValid() ? 'error' : ''} value={this.state.vimorg} onChange={this.onVimorgChange} /> </div> </div> <div className="control-group"> <label className="control-label" htmlFor="category-input"> Category </label> <div className="controls"> <Category category={this.state.category} editOnly={true} onCategoryChange={this.onCategoryChange} /> </div> </div> <div className="control-group"> <label className="control-label" htmlFor="tags-input"> Tags (up to four keywords for search) </label> <div className="controls"> <Tags tags={this.state.tags} editOnly={true} onTagsChange={this.onTagsChange} /> </div> </div> <div className="control-group"> <div className="controls"> <p className="other-info-blurb"> All other information, including descriptions, will be automatically extracted from the GitHub or Vim.org link. </p> </div> </div> <div className="control-group"> <div className="controls"> <button type="submit"> Submit <span className="right-arrow">{"\u2192"}</span> </button> </div> </div> <input type="hidden" name="category" value={this.state.category} /> <input type="hidden" name="tags" value={JSON.stringify(this.state.tags)} /> </form> </div>; } }); module.exports = SubmitPage;
import React from "react"; import Pokegame from './Pokegame'; function App() { function refreshPage() { window.location.reload(false); } return ( <div className="App"> <Pokegame /> <div className="container col-10"> <button className="btn btn-success p-3 my-5 d-block text-center" onClick={refreshPage}>Click to reload!</button> </div> </div> ); } export default App;
const util = require("util"); const gc = require("../config/index"); const bucket = gc.bucket("shrtcast_test"); exports.uploadImage = (file) => new Promise((resolve, reject) => { let filename = Date.now() + ".mp3"; const blob = bucket.file(filename); const blobStream = blob.createWriteStream({ resumable: false, }); blobStream .on("finish", () => { const publicUrl = `https://storage.cloud.google.com/${bucket.name}/${blob.name}`; resolve(publicUrl); }) .on("error", () => { reject(`Unable to upload image, something went wrong`); }) .end(file); });
import React from "react"; import {Card} from "antd"; const {Meta} = Card; const Customize = () => { return ( <Card hoverable cover={<img alt="example" src="https://os.alipayobjects.com/rmsportal/QBnOOoLaAfKPirc.png"/>} > <Meta title="Europe Street beat" description="www.instagram.com" /> </Card> ); }; export default Customize;
import React from "react"; import { Input, Button } from "antd"; import "antd/dist/antd.css"; import "./styles.css"; const DataEntry = (props) => { const { inputValue, onChangeInput, onPressEnterInput, onClickButton, buttonText, } = props; return ( <div className="inputStyle"> <Input style={{ height: "40px", fontSize: "20px" }} placeholder="Write..." value={inputValue} onChange={(event) => onChangeInput(event.target.value)} onPressEnter={(event) => onPressEnterInput(event.target.value)} /> <Button style={{ height: "40px", marginLeft: "15px", backgroundColor: "#ffff", color: "black", border: "2px solid #f2a899", }} onClick={() => onClickButton()} > <p style={{ fontSize: "20px", color: "#f2a899" }}>{buttonText}</p> </Button> </div> ); }; export default DataEntry;
const view = (namespace, view) => { const namespaced = () => view namespaced.namespace = String(namespace) return namespaced } const reducers = (config) => (state, {type, payload}) => { const [namespace, ...rest] = type.split('.') if (config[namespace]) { return { ...state, [namespace]: config[namespace](state[namespace], {type: rest.join('.'), payload}) } } return state } export default { view, reducers }
var Action = require("../model/Action"); exports.receive = function(msge){ var message = msge.split(";"); var type = message[2]; switch(type){ case "RPCRequest": var data = message[3]; var rpc = data.split("|"); var funcName = rpc[0]; var paras = rpc[1].split(","); //call function by funcName.and 调用rpcResponse返回结果(<funcName|result>)。 break; case "ActionSubmit": var a_id = message[0]; var action_descript = message[3]; //把action_descript 加入到a_id的agent的agentList中。 var action_content = JSON.parse(action_descript); var action_id = action_content.actionName; var action_paras = action_content.paras; var newAction = new Action(action_id,action_paras); var actor_list = ENV.getActorList(); var actor = actor_list.getAgent(a_id); actor.exec(newAction); break; default: console.log("in platform.receiver, a unknown type!!"); break; } }
window.FlickrGallery = (function(undefined) { "use strict"; var GalleryStage = 'flickr-gallery'; var GALLERY_TILE = 'c-gallery-tile', SELECTED_CLASS = 'is-selected'; function init(data){ if(!document.getElementById(GalleryStage)){ return; } setupGallery(data); addListeners(); } function setupGallery(data){ // process data window.GalleryReader.init(data); } function addListeners(){ var galleryEl = document.getElementsByClassName(GALLERY_TILE); for (var i = 0; i < galleryEl.length; i++) { galleryEl[i].addEventListener("click", handleItemClick); } } function handleItemClick(event){ event.preventDefault(); var clickedItemClass = event.target.className; var clickedItemDataID = event.target.dataset.id; if (event.target.className === SELECTED_CLASS){ window.localstorageItem.removeItem(clickedItemDataID); event.target.className = ''; } else { window.localstorageItem.saveItem(clickedItemDataID); event.target.className += SELECTED_CLASS; } } return { init: init }; })();
export default class Spa_util { /** * [setConfigMap common code to set configs in feature modules] * @param {[type]} arg_map * [ * * input_map - map of key-values to set in config * * settable_map - map of allowable keys to set * * config_map - map to apply settings to * ] * Throws: Exception if input key not allowed */ static setConfigMap(arg_map) { let input_map = arg_map.input_map, settable_map = arg_map.settable_map, config_map = arg_map.config_map, key_name, error; for(key_name in input_map) { if(input_map.hasOwnProperty(key_name)) { if(settable_map.hasOwnProperty(key_name)) { config_map[key_name] = input_map[key_name]; } else { error = this.makeError('Bad Input', `Setting config key | ${key_name} | is not supported`); throw error; } } } } static setStateMap(arg_map) { let input_map = arg_map.input_map, settable_map = arg_map.settable_map, state_map = arg_map.state_map, key_name, error; for(key_name in input_map) { if(input_map.hasOwnProperty(key_name)) { if(settable_map.hasOwnProperty(key_name)) { state_map[key_name] = input_map[key_name]; } else { error = this.makeError('Bad Input', `Setting state key | ${key_name} | is not supported`); throw error; } } } } /** * [makeError a convenience wrapper to create an error object] * @param {[type]} name_text [the error name] * @param {[type]} msg_text [long error message] * @param {[type]} data [optional data attached to error object] * @return {[type]} [newly constructed error object] */ static makeError(name_text, msg_text, data) { let error = new Error(); error.name = name_text; error.message = msg_text; if(data) { error.data = data; } return error; } }
import React from 'react'; // JSX 문법 규칙 (3) // JSX 내부의 자바스크립트 표현식에서 if문을 사용할 수 는 없습니다. // 하지만 조건에 따라 다른 내용을 렌더링해야 할 때는 // JSX 밖에서 if문을 사용하여 사전에 값을 설정하거나, // {} 안에 조건부 면산자를 사용하면 됩니다. function App(){ const name = '장나라'; return ( <div> {name === '장나라' ? (<h1>장나라 입니다.</h1>) : (<h2>장나라가 아닙니다.</h2>) } </div> )} export default App;
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state:{ msg:'', lists:[] }, mutations:{ change(state,value){ state.msg=value }, savelist(state,value){ state.lists=value } } })
const request = require('supertest'); const crypto = require('crypto'); const server = request('http://localhost:1337'); let token = ""; const deviceName1ToUse = crypto.randomBytes(10).toString('hex'); let lastInsertedId = 1; console.log("using as first cfg: "+deviceName1ToUse); it('authenticate correct', done => { server.post('/api/auth/login') .send({username: 'muster', password: 'plain'}) .expect(200) .expect((res) => { if (!('jwt' in res.body)) throw new Error("missing jwt token"); if (res.body.jwt === "") throw new Error("jwt token cannot be null"); token = res.body.jwt; }) .end(done); }); it('get all configurations, ok', done => { server.get('/api/configuration') .set("bearer", token) .expect(res => { console.log(JSON.stringify(res.body, null, 4)); }) .expect(200, done); }); for (let i = 0; i < 1_000; i++) { let devicename = crypto.randomBytes(10).toString('hex'); it('post 1 configuration correct, ok', done => { server.post('/api/configuration/') .set("bearer", token) .send({ name: devicename, description: deviceName1ToUse + "POSTdesc", reloadtime: 2312313, cycletime: 2222222, urls: ["asdasd", "12314", "12314", "12314", "12314", "12314", "12314", "12314", "12314", "12314", "12314"], }).expect((res) => { console.log(JSON.stringify(res.body, null, 4)); }) .expect(200) .end(done); }); } //GET ALL DEVICES and check that there is an updated string it('get all configurations, ok, deleted 1 configuration count now 1', done => { server.get('/api/configuration') .set("bearer", token) .expect(res => { console.log(JSON.stringify(res.body, null, 4)); //if (!(res.body.configuration.length === 1)) throw new Error("configuration with id 3 seems not to be deleted"); }) .expect(200, done); });
export default { name: "Level 3", content: ` <div class="container"> <div class="intro-1" style="display: block"> <h5>Conditionals and if statements:</h5> <ul> <li>A conditional is a line of code that resolves to <code>true</code> or <code>false</code>.</li> <li>A conditional can be created with <span style="color: #7d34eb">==</span>, which check if one thing is <span style="color: #7d34eb">equal</span> to another thing</li> <li>Conditionals are used to give your program the ability to make decisions in response to incoming information.</li> <li>An <span style="color: #7d34eb">if</span> statement will run a given block of code <span style="color: #7d34eb">if</span> a corresponding conditional resolves to <code>true</code>.</li> </ul> <button onclick="myFunction()" class="btn btn-primary" data-id="1" data-type="next" style="float: right">Next</button> </div> <div class="intro-2" style="display: none"> <p><strong>The syntax for this looks like:</strong></p><br/> <code><pre> // Walk to the track walkRight(7) if(trainIsComing() == true) { stop() } // Afterwards, keep walking...</pre> </code> <button onclick="myFunction()" class="btn btn-info" data-id="2" data-type="back">Back</button> <button onclick="myFunction()" class="btn btn-success" data-id="2" data-type="start" style="float: right">Start</button> </div> </div> `, deliverables: ` To see if a train is coming, use the function <span style="color: #7d34eb">trainIsComing()</span>. It will be <span style="color: #7d34eb">==</span> to true if a train is coming. Tell your character to <code>stop()</code> using the <code>stop()</code> function if a train is passing. If you call <code>stop()</code>, the character will wait for the train to pass before continuing. `, hint: ` You need to walk to the track. <br/> Then, use if to check <code>if(trainIsComing() == true)</code>. <br/> Use stop() to wait for the train to pass, then continue walking after your <code>if</code> block. ` };
import Promise from 'bluebird' import fs from 'fs' import minimist from 'minimist' import fetch from 'node-fetch' import { errorExit, catchErrors, checkJSONHeader, checkGraphQLError } from './errors' const readFile = Promise.promisify(fs.readFile) const argv = minimist(process.argv.slice(2)) const graphEndpoint = argv.u || argv.url const queryFileName = argv.f || argv.fileName || argv.file if (!graphEndpoint) { errorExit( 'A GraphQL Endpoint URL not provided.', 'Please provide an endpoint url with -u or --url.' ) } if (!queryFileName) { errorExit( 'A graph query file was not provided.', 'Please provide a query file with -f or --file.' ) } readFile(queryFileName, "UTF-8") .then(q => fetch(`${graphEndpoint}?query=${q}`)) .then(checkJSONHeader) .then(res => res.json()) .then(checkGraphQLError) .then(console.log) .catch(catchErrors)
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { View, TouchableOpacity } from 'react-native'; import moment from 'moment'; import Icon from 'react-native-vector-icons/Ionicons'; import { defaultAvatar } from 'kitsu/constants/app'; import { Avatar } from 'kitsu/screens/Feed/components/Avatar'; import * as Layout from 'kitsu/screens/Feed/components/Layout'; import { StyledText } from 'kitsu/components/StyledText'; import { styles } from './styles'; export class Comment extends PureComponent { constructor(props) { super(props); this.state = { isLiked: false, likesCount: props.comment.likesCount, }; } toggleLike = () => { this.setState({ isLiked: !this.state.isLiked, likesCount: this.state.isLiked ? this.state.likesCount - 1 : this.state.likesCount + 1, }); } render() { const { comment, isTruncated, onAvatarPress, onReplyPress, children, } = this.props; const { isLiked, likesCount } = this.state; const { content, createdAt, user } = comment; const { avatar, name } = user; const AvatarContainer = props => ( onAvatarPress ? <TouchableOpacity onPress={onAvatarPress} {...props} /> : <View {...props} /> ); return ( <Layout.RowWrap> <AvatarContainer> <Avatar avatar={(avatar && avatar.medium) || defaultAvatar} size="medium" /> </AvatarContainer> <Layout.RowMain> <View style={styles.bubble}> <StyledText size="xxsmall" color="dark" bold>{name}</StyledText> <StyledText size="xsmall" color="dark" numberOfLines={(isTruncated && 2) || undefined}> {content} </StyledText> </View> {!isTruncated && ( <View style={styles.commentActions}> <StyledText color="grey" size="xxsmall">{moment(createdAt).fromNow()}</StyledText> <TouchableOpacity onPress={this.toggleLike} style={styles.commentActionItem}> <StyledText color="grey" size="xxsmall">{`Like${isLiked ? 'd' : ''}`}</StyledText> </TouchableOpacity> <TouchableOpacity onPress={onReplyPress} style={styles.commentActionItem}> <StyledText color="grey" size="xxsmall">Reply</StyledText> </TouchableOpacity> <View style={styles.commentActionItem}> <Icon name={isLiked ? 'md-heart' : 'md-heart-outline'} style={[styles.likeIcon, isLiked && styles.likeIcon__active]} /> <StyledText color={isLiked ? 'red' : 'grey'} size="xxsmall">{likesCount}</StyledText> </View> </View> )} {children && ( <View style={styles.nestedCommentSection}>{children}</View> )} </Layout.RowMain> </Layout.RowWrap> ); } } Comment.propTypes = { comment: PropTypes.shape({ avatar: PropTypes.string, name: PropTypes.string, content: PropTypes.string, time: PropTypes.string, likesCount: PropTypes.number, createdAt: PropTypes.string, children: PropTypes.array, }).isRequired, children: PropTypes.node, isTruncated: PropTypes.bool, onAvatarPress: PropTypes.func, onReplyPress: PropTypes.func, }; Comment.defaultProps = { children: [], isTruncated: false, onAvatarPress: null, onReplyPress: null, };
import React from 'react'; import PropTypes from 'prop-types'; import { StyledResponsiveDiv, StyledNavList, StyledCollapsableNav } from './Navbar.styles'; import MenuButton from '../MenuButton/MenuButton'; import {Link} from 'react-router-dom'; const pages = [ { title:"Home", path:"/" } ] const Navbar = (props) => ( <div className="nav"> <StyledCollapsableNav className="StyledCollapsableNav"> {/* <Logo text="ROB CONNOLLY DESIGN" /> */} <StyledResponsiveDiv className="StyledResponsiveDiv"> <StyledNavList className="StyledNavList text-uppercase" id="navbarResponsive"> {/* { pages.map(page => { return <li key={page.title} className="nav-item"><Link className="nav-link js-scroll-trigger" to={page.path}>{page.title}</Link></li> }) } */} </StyledNavList> </StyledResponsiveDiv> <MenuButton toggleMenu={props.toggleMenu} /> </StyledCollapsableNav> </div> ); Navbar.propTypes = { // bla: PropTypes.string, }; Navbar.defaultProps = { // bla: 'test', }; export default Navbar;
import React, { Component } from "react"; import { createStackNavigator } from 'react-navigation-stack'; import { createSwitchNavigator, createAppContainer, } from "react-navigation"; import { Root } from "native-base"; // import Login from './Login/Login'; import MainScreen from './screens/Main'; import { AsyncStorage, InteractionManager, ActivityIndicator } from "react-native"; class AuthHandler extends Component { handleAuth = async () => { let routeName; let token = await AsyncStorage.getItem('token') if (token) { routeName = "Default"; } else { routeName = "Login"; } this.props.navigation.navigate(routeName); }; componentDidMount() { InteractionManager.runAfterInteractions(this.handleAuth); } render() { return <ActivityIndicator />; } } const Default = createStackNavigator( { General: { screen: MainScreen }, }, { index: 0, initialRouteName: "General", headerMode: "none", }, ); const Switch = createSwitchNavigator( { // AuthHandler: { screen: AuthHandler }, // Login: { screen: Login }, Default: { screen: Default }, }, { index: 0, initialRouteName: "Default", headerMode: "none", }, ); const App = createAppContainer(Switch); export default () => ( <Root> <App renderLoadingExperimental={() => <ActivityIndicator />} /> </Root> );
import React, { useContext, useEffect } from 'react'; import TodoContext from '../../context/todoContext/TodoContext'; import Todo from '../todoList/todo/Todo'; import { Paper, Typography, } from '@material-ui/core'; import './todoList.css'; function TodoList() { const todoContext = useContext(TodoContext); const { todos, getData, } = todoContext; useEffect(() => { // console.log('Todo App') // getData(); }) const todosArray = Object.keys(todos); return ( <div className='listBody'> { todosArray.length >= 1 ? todosArray.map(todo => { // console.log( todos[todo]) return ( <Todo key={todo} todo={todos[todo]} /> ) }) : <Paper className='paper'> <Typography variant="h6" component="p" > Add some todo first </Typography> </Paper> } </div> ); } export default TodoList;
const now = new Date();//текущая const now1 = new Date(0);// миллисекунд от 1970 года(учитывая пояса) const now2 = new Date(-41412342142342342342); // отрицательное колличество миллисекунд - чтоубы уйти за 1970 const now3 = new Date(20 , 6 , 1, 2); //задаём в ручную console.log(now); console.log(now.getFullYear()); console.log(now.getMonth()); console.log(now.getDate()); console.log(now.getDay());//день недели с воскресения console.log(now.getHours()); console.log(now.getUTCHours()); // учитвывая UTC console.log(now.getTimezoneOffset());// насколько отличие от главного пояса console.log(now.getTime()); // колличество миллисекунд с 1970 //Всё тоже самое с set let start = new Date(); for (let i = 0; i < 100000; i++){ let some = i ** 3; // возведение в степень } let end =new Date(); alert(`Цикл отработал за ${end - start}миллисекунд`);
const { Router } = require("express"); const statusMonitor = require("express-status-monitor"); const cors = require("cors"); const bodyParser = require("body-parser"); const compression = require("compression"); const methodOverride = require("method-override"); const controller = require("./utils/createControllerRoutes"); module.exports = ({ config, containerMiddleware, loggerMiddleware, errorHandler, swaggerMiddleware, auth }) => { const router = Router(); /* istanbul ignore if */ if (config.env === "development") { router.use(statusMonitor()); } /* istanbul ignore if */ if (config.env !== "test") { router.use(loggerMiddleware); } const apiRouter = Router(); apiRouter .use(methodOverride("X-HTTP-Method-Override")) .use(cors()) .use(bodyParser.json()) .use(bodyParser.urlencoded({ extended: true })) .use(compression()) .use(containerMiddleware) .use("/docs", swaggerMiddleware); /* * Add your API routes here * * You can use the `controllers` helper like this: * apiRouter.use('/users', controller(controllerPath)) * * The `controllerPath` is relative to the `interfaces/http` folder */ apiRouter.use("/auth", controller("token/TokenController")); apiRouter.use( "/users", auth.hasPermissions([config.permissions.MANAGE_USER]), controller("user/UsersController") ); apiRouter.use( "/categories", auth.hasPermissions([config.permissions.MANAGE_CATEGORY]), controller("category/CategoriesController") ); apiRouter.use( "/directories", auth.hasPermissions([config.permissions.MANAGE_DIRECTORY]), controller("directory/DirectoriesController") ); apiRouter.use( "/media", auth.hasPermissions([config.permissions.MANAGE_DIRECTORY]), controller("media/MediaController") ); apiRouter.use( "/tasks", auth.authenticate(), controller("task/TasksController") ); router.use("/api", apiRouter); router.use(errorHandler); return router; };
app.post('/api/users/signin', userController.signin);
import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store/index' //引入vant组件 import Vant from 'vant' import 'vant/lib/index.css' //引入提示组件 import {Toast} from 'vant' //懒加载组件 import lazyLoad from 'vue-lazyload' import http from 'network/request.js' Vue.prototype.$http = http;//导入原型 Vue.prototype.$msg = Toast; Vue.use(Vant); Vue.use(lazyLoad, { loading: require('./assets/img/default.jpg'), error: require('./assets/img/error.jpg') })//安装懒加载插件 Vue.config.productionTip = false new Vue({ router, store, render: h => h(App) }).$mount('#app')
'use strict'; // Embed the following file to a HTML document: // - From the previous flickr example extract the .jpg link directly // - Create an image tag in the with document.createElement // - Add a 'load' event to the image and only show the image to the user when the image is loaded var newImg = document.createElement('img'); function createImage () { document.body.appendChild(newImg); newImg.setAttribute('src', "https://c7.staticflickr.com/8/7562/15584243094_b268a32192_h.jpg"); newImg.style.visibility = 'hidden'; } createImage(); function showImage () { newImg.style.visibility = 'visible'; } newImg.addEventListener('load', showImage);
require('dotenv').config(); module.exports = { netgear: { username: process.env.NETGEAR_USERNAME, password: process.env.NETGEAR_PASSWORD, references: JSON.parse(process.env.NETGEAR_REFERENCES) }, openWeatherMap: { apiUrl: process.env.OPEN_WEATHER_MAP_API_URL, apiKey: process.env.OPEN_WEATHER_MAP_API_KEY, city: process.env.OPEN_WEATHER_MAP_CITY, }, googleMaps: { key: process.env.GOOGLE_MAPS_API_KEY, directions: JSON.parse(process.env.GOOGLE_MAPS_DIRECTIONS) }, vigicrue: { levelUrl: process.env.VIGICRUE_LEVEL_URL, attentionUrl: process.env.VIGICRUE_ATTENTION_URL }, netatmo: { apiUrl: process.env.NETATMO_API_URL, clientId: process.env.NETATMO_CLIENT_ID, clientSecret: process.env.NETATMO_CLIENT_SECRET, username: process.env.NETATMO_USERNAME, password: process.env.NETATMO_PASSWORD, }, transilien: { apiUrl: process.env.TRANSILIEN_API_URL, nextDepartureParams: JSON.parse(process.env.TRANSILIEN_NEXT_DEPARTURES_PARAMS) }, tuya: { username: process.env.TUYA_USERNAME, password: process.env.TUYA_PASSWORD, countryCode: process.env.TUYA_COUNTRY_CODE, }, control: { modes: JSON.parse(process.env.CONTROL_MODES), } };
function MyPromise(fn) { this.value; this.resolveFun = function () {console.log('resolve null')} this.rejectFun = function () {console.log('reject null')} fn(this.resolve.bind(this),this.reject.bind(this)) } MyPromise.prototype.resolve = function(val) { var self = this; self.value=val; setTimeout(function() { //延迟的关键,用setTimeout将事件加到下一个队列 self.resolveFun(self.value); }, 0); } MyPromise.prototype.reject = function (val) { this.value = val; var self = this; setTimeout(function () { self.rejectFun(self.value) },0); } MyPromise.prototype.then = function (resolveFun,rejectFun) { this.resolveFun = resolveFun; this.rejectFun = rejectFun; } var fn = function (resolve, reject) { let random = Math.random(); if(random < 0.5){ resolve('some resolve data'); }else{ reject('some reject data'); } } let p = new MyPromise(fn); p.then(function (data) { console.log(data) }, function (data) { console.log(data) })
import { or } from '@ember/object/computed'; import { computed } from '@ember/object'; import Component from '@ember/component'; import layout from './template'; export default Component.extend({ layout, tagName: 'button', classNames: ['bg-button', 'btn', 'ember-appointment-slots-pickers'], classNameBindings: ['bgTheme'], attributeBindings: ['isDisabled:disabled', 'type', 'tabindex'], isTagged: false, // attributes // whether the button is disabled or not disabled: false, // whether the button is loading state or not loading: false, // can be "primary" "secondary" "tertiary" theme: 'primary', // can be "button" "submit" "reset" type: 'button', // text to display when the button is in loading state 'loading-text': 'Loading...', // wheter to hide the left arrow icon 'hide-icon': false, customIcon: null, // persist loading even after the promise has returned forceLoadingToPersist: false, bgTheme: computed('theme', function () { return `btn-${this.theme}`; }), // computed properties of disable and loading isDisabled: or('disabled', 'loading'), click(...params) { const action = this.action; if (action) { const promise = action(...params); // if the action is a closure action // and a promise set loading state // until resolved if ( promise && promise.then && !this.isDestroyed && !this.isDestroying ) { this.set('loading', true); promise.finally(() => { if (!this.isDestroyed && !this.isDestroying && !this.forceLoadingToPersist) { this.set('loading', false); } }); } } return false; } });
import {Meteor} from 'meteor/meteor'; import {Template} from 'meteor/templating'; import {ReactiveDict} from 'meteor/reactive-dict'; import {Tasks} from '../api/tasks.js'; import './header.html'; import './list.html'; Template.list.onCreated(function bodyOnCreated() { this.state = new ReactiveDict(); Meteor.subscribe('tasks'); }); Template.list.helpers({ tasks() { const instance = Template.instance(); if (instance.state.get('hideOldPosts')) { // If hide completed is checked, filter tasks var today = new Date(); today.setHours(0); today.setMinutes(0); today.setSeconds(0); return Tasks.find({'createdAt': {$gte: today}}, {sort: {createdAt: -1}}); } // Otherwise, return all of the tasks return Tasks.find({}, {sort: {createdAt: -1}}); }, groups() { var tasks = Tasks.find({}, {sort: {createdAt: -1}}).fetch(); console.log(tasks); var groups = _.groupBy(tasks, function (task) { // console.log(task); return task && task.createdAt && task.createdAt.toDateString(); }); return _.map(groups, function (group) { return { date: group[0].createdAt, tasks: group } }); } }); Template.list.helpers({ is_today(date) { return date && date.toDateString() === new Date().toDateString(); } });
function addFunction(row, store, vendorid) { var cde_dt_shp; var pwy_dte_ctl; var cde_dt_var; var cde_dt_incr; var vendor_id; var editFrm = Ext.create('Ext.form.Panel', { id: 'editFrm', frame: true, plain: true, defaultType: 'textfield', layout: 'anchor', labelWidth: 120, url: '/WareHouse/InsertIinvd', defaults: { anchor: "95%", msgTarget: "side" }, items: [ { xtype: 'displayfield', fieldLabel: "商品品號/條碼", name: 'plas_prod_id', id: 'plas_prod_id', allowBlank:false, allowBlank: false, value: Ext.getCmp('item_id').getValue(), listeners: { afterrender: function () { var id = Ext.getCmp('plas_prod_id').getValue(); Ext.Ajax.request({ url: "/WareHouse/Getprodbyid", method: 'post', type: 'text', params: { id: Ext.getCmp('plas_prod_id').getValue() }, success: function (form, action) { var result = Ext.decode(form.responseText); if (result.success) { msg = result.msg; locid = result.locid; Ext.getCmp("product_name").setValue(msg); if (result.day == "") { Ext.getCmp("cde_dt_var").setValue("999"); } else { Ext.getCmp("cde_dt_var").setValue(result.day); } if (locid.length > 0) { Ext.getCmp("loc_id").setValue(locid); } else { Ext.getCmp("loc_id").setValue("無"); } cde_dt_shp = result.cde_dt_shp; pwy_dte_ctl = result.pwy_dte_ctl; cde_dt = result.cde_dt; cde_dt_var = result.cde_dt_var; cde_dt_incr = result.cde_dt_incr; //設置為可用 //Ext.getCmp('startTime').setDisabled(false); if (pwy_dte_ctl != "Y") { //如果不是有效期控管的商品就不顯示填寫時間 Ext.getCmp("createtime").hide(); Ext.getCmp("cdttime").hide(); Ext.getCmp('cde_dt').setDisabled(false); Ext.getCmp('startTime').allowBlank = true; Ext.getCmp('cde_dt').allowBlank = true; } else { Ext.getCmp('createtime').show(); Ext.getCmp('cdttime').show(); Ext.getCmp('us1').setDisabled(false); Ext.getCmp('us2').setDisabled(false); Ext.getCmp('cde_dt').setDisabled(true); Ext.getCmp('startTime').allowBlank = false; Ext.getCmp('cde_dt').allowBlank = false; } } else { Ext.getCmp("product_name").setValue("沒有該商品信息!"); Ext.getCmp('startTime').setDisabled(true); Ext.getCmp('us1').setDisabled(true); Ext.getCmp('us2').setDisabled(true); } } }); } } }, { xtype: 'displayfield', fieldLabel: "品名", name: 'product_name', id: 'product_name', allowBlank: false }, { xtype: 'displayfield', fieldLabel: "上架料位", name: 'plas_loc_id', id: 'plas_loc_id', allowBlank: false, value: Ext.getCmp('ktloc_id').getValue() }, { xtype: 'numberfield', fieldLabel: "數量", name: 'prod_qty', id: 'prod_qty', minValue: 1, allowBlank: false }, { xtype: 'textfield', fieldLabel: "庫調單號", name: 'doc_num', id: 'doc_num', value: Ext.getCmp('doc_no').getValue(), hidden:true }, { xtype: 'textfield', fieldLabel: "前置單號", name: 'Po_num', id: 'Po_num', value: Ext.getCmp('po_id').getValue(), hidden: true }, { xtype: 'textfield', fieldLabel: "備註", name: 'remark', id: 'remark', value: Ext.getCmp('remarks').getValue(), hidden: true }, { xtype: 'fieldcontainer', fieldLabel: "製造日期", combineErrors: true, height: 24, margins: '0 200 0 0', layout: 'hbox', id: 'createtime', hidden: true, defaults: { flex: 1, hideLabel: true }, items: [ { xtype: 'radiofield', name: 'us', inputValue: "1", id: "us1", checked: true, disabled: true, listeners: { change: function (radio, newValue, oldValue) { var i = Ext.getCmp('startTime');//製造日期 var j = Ext.getCmp('cde_dt'); if (newValue) { j.allowBlank = true; i.setDisabled(false); j.setDisabled(true); j.setValue(null); i.allowBlank = false; } } } }, { xtype: "datefield", fieldLabel: "製造日期", id: 'startTime', name: 'startTime', allowBlank: false, submitValue: true, listeners: { change: function (radio, newValue, oldValue) { if (Ext.getCmp('startTime').getValue() != "" && Ext.getCmp('startTime').getValue() != null) { Ext.Ajax.request({ url: "/WareHouse/JudgeDate", method: 'post', type: 'text', params: { dtstring: 1, item_id: Ext.getCmp('plas_prod_id').getValue(), startTime: Ext.Date.format(Ext.getCmp('startTime').getValue(), 'Y-m-d') }, success: function (form, action) { var result = Ext.decode(form.responseText); if (result.success) { if (result.msg == "1") { Ext.Msg.alert(INFORMATION, "該商品製造日期大於今天"); Ext.getCmp('startTime').setValue(null); } else if (result.msg == "2") { editFunction("超過允收天數"); return; } else if (result.msg == "3") { editFunction("超過允出天數!"); return; } else if (result.msg == "4") { editFunction("該商品已超過有效日期!"); return; } } } }); } } } } ] }, { xtype: 'fieldcontainer', fieldLabel: "有效日期", combineErrors: true, hidden: true, layout: 'hbox', height: 24, //margins: '0 200 0 0', id: 'cdttime', defaults: { flex: 1, hideLabel: true }, items: [ { xtype: 'radiofield', name: 'us', inputValue: "2", id: "us2", disabled: true, listeners: { change: function (radio, newValue, oldValue) { var i = Ext.getCmp('startTime');//製造日期 var j = Ext.getCmp('cde_dt'); if (newValue) { i.setDisabled(true); j.setDisabled(false); i.allowBlank = true; i.setValue(null); j.allowBlank = false; } } } }, { xtype: "datefield", fieldLabel: "有效日期", id: 'cde_dt', name: 'cde_dt', allowBlank: true, submitValue: true, listeners: { change: function (radio, newValue, oldValue) { if (Ext.getCmp('cde_dt').getValue() != "" && Ext.getCmp('cde_dt').getValue() != null) { Ext.Ajax.request({ url: "/WareHouse/JudgeDate", method: 'post', type: 'text', params: { dtstring: 2, item_id: Ext.getCmp('plas_prod_id').getValue(), startTime: Ext.Date.format(Ext.getCmp('cde_dt').getValue(), 'Y-m-d') }, success: function (form, action) { var result = Ext.decode(form.responseText); if (result.success) { if (result.msg == "1") { Ext.Msg.alert(INFORMATION, "該商品製造日期大於今天"); Ext.getCmp('startTime').setValue(null); } else if (result.msg == "2") { editFunction("超過允收天數"); return; } else if (result.msg == "3") { editFunction("超過允出天數!"); return; } else if (result.msg == "4") { editFunction("該商品已超過有效日期!"); return; } } }, failure: function (form, action) { Ext.Msg.alert(INFORMATION, "保存失敗"); } }); } } } } ] }, { xtype: 'displayfield', fieldLabel: "主料位", id: 'loc_id', name: 'loc_id' }, { xtype: 'displayfield', fieldLabel: "允收天數", id: 'cde_dt_var', name: 'cde_dt_var', allowBlank: false } ], buttons: [{ text: SAVE, formBind: true, handler: function () { var form = this.up('form').getForm(); var isloc = 0; Ext.Ajax.request({ url: "/WareHouse/Islocid", method: 'post', type: 'text', async: false,//是否異步 params: { plas_loc_id: Ext.getCmp('plas_loc_id').getValue(),//料位 prod_id: Ext.getCmp('plas_prod_id').getValue(),//商品品號 loc_id: Ext.getCmp('loc_id').getValue()//主料位 }, success: function (form, action) { var result = Ext.decode(form.responseText); isloc = result.msg; } }); if (isloc == 6) {//表示驗證成功 //vendor_id = store.data.items[0].raw.vendor_id; vendor_id = vendorid; if (form.isValid()) { var myMask = new Ext.LoadMask(Ext.getBody(), { msg: 'Loading...' }); myMask.show(); Ext.Ajax.request({ url: "/WareHouse/GetSearchStock", params: { loc_id: Ext.getCmp("plas_loc_id").getValue(), item_id: Ext.getCmp("plas_prod_id").getValue(), cde_date: Ext.getCmp('cde_dt').getValue(), made_date: Ext.getCmp('startTime').getValue() }, success: function (response) { var result = Ext.decode(response.responseText); if (result.msg != "0") { myMask.hide(); Ext.Msg.alert("提示", "該料位有上鎖的庫存,不能庫調!"); } else { form.submit({ params: { //id: Ext.htmlEncode(Ext.getCmp('plas_prdd_id').getValue()),//條碼 iialg: 'Y',//寄倉流程 新增庫存用到 item_id: Ext.htmlEncode(Ext.getCmp('plas_prod_id').getValue()),//商品品號 product_name: Ext.htmlEncode(Ext.getCmp('product_name').getValue()),//品名 prod_qty: Ext.htmlEncode(Ext.getCmp('prod_qty').getValue()),//數量 startTime: Ext.htmlEncode(Ext.getCmp('startTime').getValue()),//創建時間 cde_dt: Ext.htmlEncode(Ext.getCmp('cde_dt').getValue()),//有效時間 plas_loc_id: Ext.htmlEncode(Ext.getCmp('plas_loc_id').getValue()),//上架料位 loc_id: Ext.getCmp('loc_id').getValue(),//主料位 cde_dt_var: Ext.htmlEncode(Ext.getCmp('cde_dt_var').getValue()), cde_dt_incr: cde_dt_incr, doc_num: Ext.getCmp('doc_num').getValue(),//庫調單號 Po_num: Ext.getCmp('Po_num').getValue(),//前置單號 remark: Ext.getCmp('remark').getValue(),//備註 iarc_id: Ext.getCmp('iarc_id').getValue(), vendor_id: vendor_id }, success: function (form, action) { var result = Ext.decode(action.response.responseText); Ext.Msg.alert(INFORMATION, SUCCESS); if (result.success) { myMask.hide(); KucunTiaozhengStore.load(); editWin.close(); } else { myMask.hide(); Ext.MessageBox.alert(ERRORSHOW + result.success); } }, failure: function () { myMask.hide(); Ext.Msg.alert(INFORMATION, FAILURE); } }); } }, failure: function (form, action) { Ext.Msg.alert(INFORMATION, "等待超時!"); } }); //$.get('/WareHouse/GetSearchStock', // { // 'loc_id': Ext.getCmp("plas_loc_id").getValue(), // 'item_id': Ext.getCmp("plas_prod_id").getValue(), // cde_date: Ext.getCmp('cde_dt').getValue(), // made_date:Ext.getCmp('startTime').getValue() // }, function (data) { // //var datadata = data.parseJSON(); // var datadata = eval('(' + data + ')'); // if (datadata.islock != "0") { // Ext.Msg.alert("提示", "該料位有上鎖的庫存,不能庫調!"); // } // else { // } //}) } } else if (isloc == 1) { Ext.MessageBox.alert(INFORMATION, "上架料位不存在或已占用!"); } else if (isloc == 2) { Ext.MessageBox.alert(INFORMATION, "上架料位被其他商品占用!"); } else if (isloc == 3) { Ext.MessageBox.alert(INFORMATION, "上架料位已鎖定!"); } } }] }); var editWin = Ext.create('Ext.window.Window', { title: "庫存調整", id: 'editWin', iconCls: 'icon-user-edit', width: 550, height: 380, autoScroll: true, // height: document.documentElement.clientHeight * 260 / 783, layout: 'fit', items: [editFrm], closeAction: 'destroy', modal: true, constrain: true, //窗體束縛在父窗口中 resizable: false, labelWidth: 60, bodyStyle: 'padding:5px 5px 5px 5px', closable: false, tools: [ { type: 'close', qtip: CLOSEFORM, handler: function (event, toolEl, panel) { Ext.MessageBox.confirm(CONFIRM, IS_CLOSEFORM, function (btn) { if (btn == "yes") { Ext.getCmp('editWin').destroy(); } else { return false; } }); } }] , listeners: { 'show': function () { if (row == null) { // editFrm.getForm().loadRecord(row); //如果是添加的話 editFrm.getForm().reset(); } else { editFrm.getForm().loadRecord(row); //如果是編輯的 } } } }); editWin.show(); }
(function () { angular .module('myApp') .controller('GroupTextViewController', GroupTextViewController) GroupTextViewController.$inject = ['$state', '$scope', '$rootScope', '$sce']; function GroupTextViewController($state, $scope, $rootScope, $sce) { $rootScope.setData('showMenubar', true); $rootScope.setData('backUrl', "groupTextAnswer"); $scope.question = $rootScope.settings.questionObj; if ($scope.question.result_videoID) { $scope.question.result_videoURL = $sce.trustAsResourceUrl('https://www.youtube.com/embed/' + $scope.question.result_videoID + "?rel=0&enablejsapi=1"); $rootScope.removeRecommnedVideo() } $rootScope.safeApply(); $scope.$on("$destroy", function () { if ($rootScope.instFeedRef) $rootScope.instFeedRef.off('value'); if ($rootScope.questionResultImageRef) $rootScope.questionResultImageRef.off('value') if ($scope.groupSettingRef) $scope.groupSettingRef.off('value') if ($scope.answerRef) $scope.answerRef.off('value') }); $scope.trustHTML = function (origin) { return $sce.trustAsHtml(origin); } $scope.init = function () { $rootScope.setData("loadingfinished", false) $scope.groupSetting() $scope.getclassAllAnswer() } $scope.groupSetting = function () { if ($rootScope.settings.groupType == 'sub') { $scope.groupSettingRef = firebase.database().ref('Groups/' + $rootScope.settings.groupKey + '/groupTextSettings/groupsets/' + $rootScope.settings.groupSetKey + '/' + $rootScope.settings.questionSetKey + '/' + $rootScope.settings.questionKey + '/thumbup') } else { $scope.groupSettingRef = firebase.database().ref('Groups/' + $rootScope.settings.groupKey + '/groupTextSettings/subgroupsets/' + $rootScope.settings.groupSetKey + '/' + $rootScope.settings.subSetKey + '/' + $rootScope.settings.questionSetKey + '/' + $rootScope.settings.questionKey + '/thumbup') } $scope.groupSettingRef.on('value', snapshot => { $scope.groupSetting.thumbup = snapshot.val() ? true : false $scope.ref_1 = true $scope.finalCalc() }) } $scope.getclassAllAnswer = function () { $scope.answerRef = firebase.database().ref('GroupAnswers').orderByChild('questionKey').equalTo($rootScope.settings.questionKey); $scope.answerRef.on('value', function (snapshot) { $scope.allAnswers = snapshot.val() || {} $scope.ref_2 = true $scope.finalCalc() }); } $scope.finalCalc = function () { if (!$scope.ref_1 || !$scope.ref_2) return $scope.sumval = ''; $scope.otherAnswers = []; for (var key in $scope.allAnswers) { var ans = $scope.allAnswers[key]; var checkSubGroup = true; if ($rootScope.settings.groupType == 'second') { if (ans.subSetKey != $rootScope.settings.subSetKey || ans.secondIndex != $rootScope.settings.secondIndex) { checkSubGroup = false; } } if (ans.groupType == $rootScope.settings.groupType && ans.studentgroupkey == $rootScope.settings.groupKey && ans.groupSetKey == $rootScope.settings.groupSetKey && ans.subIndex == $rootScope.settings.subIndex && checkSubGroup) { if ($rootScope.settings.userId != ans.uid) { ans.key = key; if ($scope.groupSetting.thumbup) { ans.checked = false; //selected thumb up or down if (!ans.likeUsers) { ans.likeUsers = []; } else { if (ans.likeUsers.indexOf($rootScope.settings.userId) > -1) { ans.checked = true; ans.like = true; } } if (!ans.dislikeUsers) { ans.dislikeUsers = []; } else { if (ans.dislikeUsers.indexOf($rootScope.settings.userId) > -1) { ans.checked = true; ans.dislike = true; } } ans.likeCount = ans.likeUsers.length; ans.dislikeCount = ans.dislikeUsers.length; ans.order = ans.likeCount - ans.dislikeCount; } $scope.otherAnswers.push(ans); } } } $rootScope.setData("loadingfinished", true) $rootScope.safeApply(); } $scope.getLikeClass = function (ans) { if (!ans.checked) return ""; var classStr = 'checked'; if (ans.like) { classStr += ' like'; } return classStr; } $scope.getDisLikeClass = function (ans) { if (!ans.checked) return ""; var classStr = 'checked'; if (ans.dislike) { classStr += ' dislike'; } return classStr } $scope.thumbUp = function (ans) { if (ans.checked && ans.dislike) return; if (ans.checked) { ans.likeUsers.splice(ans.likeUsers.indexOf($rootScope.settings.userId), 1); } else { ans.likeUsers.push($rootScope.settings.userId); } var updates = {}; updates['GroupAnswers/' + ans.key + '/likeUsers'] = ans.likeUsers; firebase.database().ref().update(updates); } $scope.thumbDown = function (ans) { if (ans.checked && ans.like) return; if (ans.checked) { ans.dislikeUsers.splice(ans.dislikeUsers.indexOf($rootScope.settings.userId), 1); } else { ans.dislikeUsers.push($rootScope.settings.userId); } ans.dislikeUsers.push($rootScope.settings.userId); var updates = {}; updates['NewAnswers/' + ans.key + '/dislikeUsers'] = ans.dislikeUsers; firebase.database().ref().update(updates); } } })();
const config = { apiKey: "AIzaSyBZypGBE4lhAMF5B_yS9_JjohVFVC78mhs", authDomain: "safelocation-518d0.firebaseapp.com", databaseURL: "https://safelocation-518d0.firebaseio.com" } export default config;
import React, {useState, useEffect} from 'react'; import { Text, StyleSheet, ScrollView, View, Pressable } from 'react-native'; import Axios from 'axios' import Movie from '../componets/Movie' import { Service } from 'axios-middleware'; // Middleware logging message in console const service = new Service(Axios); service.register({ onRequest(config) { console.log('Request to API: SUCESS'); return config; }, onSync(promise) { console.log('Sync Done'); return promise; }, onResponse(response) { console.log('Response back from API: SUCCESS'); return response; } }); console.log('Ready to fetch.'); const key = 'faf981d79c94b75d3c34a1b45c9330b9' const URL = `https://api.themoviedb.org/3/movie/popular?api_key=${key}&language=en-US&page=1`; const popularMovies= ({navigation})=> { const [popularMovies, setPopularMovies] = useState(null) const fetchDetails = async()=>{ try { const {data} = await Axios.get(URL); const popularMovies = data; setPopularMovies(popularMovies); } catch (error) { console.warn(error); } } // console.log(recentMovies.results) useEffect(() => { fetchDetails(); }, []) if(!popularMovies){ return( <View> <Text>LOADING...</Text> </View> ); }else{ return ( <ScrollView> <View style={styles.container}> <View style={styles.movieContainer}> {popularMovies.results.map((movieDetail)=>( <Pressable onPress={() => navigation.navigate('Details',{movieid: movieDetail.id})} key={movieDetail.id}> <Movie details={movieDetail} key={movieDetail.id}/> </Pressable> ))} </View> </View> </ScrollView> ); }} const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#121212', }, movieContainer: { width: '107%', flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center', paddingTop: 30 }, }) export default popularMovies;
import React , { PropTypes } from 'react'; var ReactDOM = require('react-dom'); import { combineReducers, createStore } from 'redux'; import { Provider, connect } from 'react-redux'; // import loggingMiddleware from './loggingMiddleware'; import CalorieInput from './input'; import TimeToBurn from './time'; import PickableProfile from './profile'; import Food from './food'; import {PICK_PROFILE_SPORTY,PICK_PROFILE_OL,PICK_PROFILE_MIDDLEMAN,PICK_PROFILE_C9,UPDATE_CALORIES} from './actions'; //require('normalize.css') require('lib/semantic/semantic.css'); require('lib/smoothscroll.js'); // require('lib/justfont.js'); require('src/spritesmith-generated/sprite.css'); require('src/spritesmith-generated/sprite.png'); require('src/app/index.css'); //Using redux is overkill here, just to try out and learn //TODO encap reducers function calories(state = 0, action) { switch (action.type) { case PICK_PROFILE_SPORTY: return 3510; case PICK_PROFILE_OL: return 442; case PICK_PROFILE_MIDDLEMAN: return 1260; case PICK_PROFILE_C9: return 520; case UPDATE_CALORIES: return action.calories; default: //manual entry return state } } function currentFoodIndex(state=0,action){ switch (action.type){ case 'CREATE_FOOD_ACTION': return action.id default: return state } } let reducers = combineReducers({ calories, currentFoodIndex }) let store = createStore(reducers); // TODO hardcoded length, shd load from food let index = 0; setInterval(()=>{ index++; if(index >= 2){ index = 0; } store.dispatch({ type: 'CREATE_FOOD_ACTION',id: index }) },1500) function calculateTimeToBurn(){ } //Rendering ReactDOM.render( <Provider store={store}> <div className="ui four column stackable relaxed grid"> <div className="column"> <PickableProfile profileId={1} info={{ title:"運動型壯男", avatarUrl:"img/avatar/sporty.png", activity: "行山6小時/星期", desc:"男 22歲 75kg", gender:"man" }}/> </div> <div className="ui vertical divider">或</div> <div className="column"> <PickableProfile profileId={2} info={{ title:"妙齡OL", avatarUrl:"img/avatar/ol.png", activity: "踏單車1小時/星期", desc:"女 25歲 65kg", gender:"woman" }}/> </div> <div className="ui vertical divider">或</div> <div className="column"> <PickableProfile profileId={3} info={{ title:"健康中佬", avatarUrl:"img/avatar/middleman.png", activity: "3次30分鐘慢跑 /星期", desc:"男 50歲 70kg", gender:"man" }}/> </div> <div className="ui vertical divider">或</div> <div className="column"> <PickableProfile profileId={4} info={{ title:"青春常駐少婦", avatarUrl:"img/avatar/c9.png", activity: "游泳1小時/星期", desc:"女 40歲 65kg", gender:"woman" }}/> </div> </div> </Provider>, document.getElementById('profiles') ); ReactDOM.render( <Provider store={store}> <CalorieInput /> </Provider>, document.getElementById('burnt') ); ReactDOM.render( <Provider store={store}> <TimeToBurn /> </Provider>, document.getElementById('time-to-burn') ); ReactDOM.render( <Provider store={store}> <Food /> </Provider>, document.getElementById('food-container') );
import { SONGS } from './actionTypes'; export const initialState = { songs: [], songsFeching: false, songsFetchingError: null, paginationEnded: false, likeSuccess: null, likeFetching: false, likeError: null, commentSuccess: null, commentFetching: false, commentError: null, currentIndex: 0, }; export function reducer(state, action) { switch (action.type) { case SONGS.feching: return { ...state, songsFeching: true, songsFetchingError: null }; case SONGS.error: return { ...state, songsFeching: false, songsFetchingError: action.payload }; case SONGS.success: return { ...state, songs: [ ...state.songs, ...action.payload], songsFeching: false, songsFetchingError: null }; case SONGS.paginationEnded: return { ...state, paginationEnded: true, songsFeching: false, songsFetchingError: null }; case SONGS.likeFetching: return { ...state, likeFetching: true, likeSuccess: null, likeError: null }; case SONGS.likeSuccess: return { ...state, likeFetching: false, likeSuccess: action.payload, likeError: null }; case SONGS.likeError: return { ...state, likeFetching: false, likeSuccess: null, likeError: action.payload }; case SONGS.commentFetching: return { ...state, commentSuccess: null, commentFetching: false, commentError: null }; case SONGS.commentSuccess: return { ...state, commentSuccess: action.payload, commentFetching: true, commentError: null }; case SONGS.commentError: return { ...state, commentSuccess: null, commentFetching: false, commentError: action.payload }; case SONGS.setCurrent: return { ...state, currentIndex: action.payload }; default: return state; } }
$(function() { console.log( "ready!" ); $("#query").on("click", function(e){ $panel=$("#querypanel"); $panel.slideDown(); if( $panel.is(":visible") ) { $(this).text("query <"); } else $(this).text("query >"); } ); });
let mock = [{ id:1, CountryName: "Angola", CountryCode: "AO", Latitude: -9.2993916, Longitude: 14.9096846, TimeZone: "Africa/Luanda", image:'https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Emblem_of_Angola.svg/800px-Emblem_of_Angola.svg.png' }, { id:2, CountryName: "Bolivia", CountryCode: "BO", Latitude: -16.8740315, Longitude: -67.4985857, TimeZone: "America/La_Paz", image:'https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Escudo_de_Bolivia.svg/1920px-Escudo_de_Bolivia.svg.png' }, { id:3, CountryName: "Dominica", CountryCode: "DM", Latitude: 15.5891445, Longitude: -61.3531023, TimeZone: "America/Dominica", image:'https://upload.wikimedia.org/wikipedia/commons/thumb/2/26/Coat-of-arms-of-Dominica.svg/1920px-Coat-of-arms-of-Dominica.svg.png' }, { id:4, CountryName: "Indonesia", CountryCode: "ID", Latitude: 0.2213005, Longitude: 99.634135, TimeZone: "Asia/Jakarta", image:'https://upload.wikimedia.org/wikipedia/commons/thumb/9/90/National_emblem_of_Indonesia_Garuda_Pancasila.svg/1280px-National_emblem_of_Indonesia_Garuda_Pancasila.svg.png' }, { id:5, CountryName: "Brazil", CountryCode: "BR", Latitude: -12.6245549, Longitude: -39.1023228, TimeZone: "America/Bahia", image:'https://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/Coat_of_arms_of_Brazil.svg/1920px-Coat_of_arms_of_Brazil.svg.png' }, { id:6, CountryName: "France", CountryCode: "FR", Latitude: 49.3559892, Longitude: 2.7877074, TimeZone: "Europe/Paris", image:'https://upload.wikimedia.org/wikipedia/commons/b/b7/Armoiries_r%C3%A9publique_fran%C3%A7aise.svg' }, { id:7, CountryName: "Belarus", CountryCode: "BY", Latitude: 54.4168102, Longitude: 27.2930165, TimeZone: "Europe/Minsk", image:'https://upload.wikimedia.org/wikipedia/commons/thumb/5/5c/Coat_of_arms_of_Belarus_%282020%29.svg/1920px-Coat_of_arms_of_Belarus_%282020%29.svg.png' }, { id:8, CountryName: "Sweden", CountryCode: "SE", Latitude: 63.9043836, Longitude: 19.7606455, TimeZone: "Europe/Stockholm", image:'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e5/Great_coat_of_arms_of_Sweden.svg/800px-Great_coat_of_arms_of_Sweden.svg.png' }, { id:9, CountryName: "Germany", CountryCode: "DE", Latitude: 48.1440135, Longitude: 11.6074275, TimeZone: "Europe/Berlin", image:'https://upload.wikimedia.org/wikipedia/commons/thumb/d/da/Coat_of_arms_of_Germany.svg/1024px-Coat_of_arms_of_Germany.svg.png' }] export default mock;
// user-based collaborative filtering const Match = require('../core/match.js') const Sets = require('../algorithm/sets.js') const recommendations = (prefs, person, formula) => { const matches = Match(prefs, person, prefs.length, formula) const items1 = Object.keys(prefs[person]) let totals = {} let sumSimilarity = {} matches.map((data) => { const { user, score } = data // Ignore scores zero or lower if (score <= 0) return const items2 = Object.keys(prefs[user]) // Only scored movies not watched by the person const results = Sets.difference(items2, items1) totals = results.reduce((prev, item) => { if (!prev[item]) prev[item] = 0 prev[item] += prefs[user][item] * score return totals }, totals) sumSimilarity = results.reduce((prev, item) => { if (!prev[item]) prev[item] = 0 prev[item] += score return prev }, sumSimilarity) }) return Object.keys(totals).map((item) => { return { user: item, score: totals[item] / sumSimilarity[item] } }).sort((a, b) => b.score[0] - a.score[0]) } module.exports = recommendations
//function //Bài 1. Viết 1 function tính bình phương của 1 số. Tham số truyền vào là 1 số. Kết quả là bình phương của số đó. function func1(a) { return (a * a) } //Bài 2. Cho 3 số a, b và c. Viết function tính bình phương của (3a + 2b - c). Tham số truyền vào là 3 số a, b, c. Kết quả là bình phương của (3a + 2b - c). Sử dụng hàm viết sẵn của Bài 1. function func2(a, b, c) { let d = 3 * a; let e = 2 * b; let f = d + e - c; return (f * f); } //Bài 3. Cho 1 chuỗi dài hơn 30 ký tự. Viết 1 function cắt chuỗi, lấy ra 10 ký tự đầu tiên và thêm vào dấu "..." ở cuối chuỗi. Tham số truyền vào là 1 chuỗi dài hơn 30 ký tự. Kết quả là chuỗi đó sau khi cắt đi còn 10 ký tự, cuối chuỗi có dấu "..." biểu thị là chuỗi bị cắt. function func3(str) { return (str.slice(0, 10) + '...'); } //- Bài 4. Viết 1 function có tác dụng biến 1 chuỗi thành viết hoa từ đầu tiên.Tham số truyền vào là 1 chuỗi.Kết quả là 1 chuỗi mới chỉ viết hoa từ đầu tiên. Ví dụ "welcome to Techmaster" sẽ được convert thành "Welcome to techmaster". function func4(str) { return (str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()); } //Bài 5. Viết 1 function lấy ra 1 số nhỏ nhất trong 1 mảng các số.Tham số truyền vào là 1 mảng các số.Kết quả là số nhỏ nhất trong mảng.Gợi ý: có thể dùng phương thức sort() hoặc object Math, chú ý khi sort số khác với chữ. function func5(arr) { return (arr.sort(function (a, b) { return a - b })); } //Bài 6. Cho 1 mảng gồm tên của 5 học viên. Hãy viết function sắp xếp lại thứ tự các học viên theo bảng chữ cái và in ra màn hình danh sách học viên.Tham số truyền vào là 1 mảng gồm tên của 5 người.Kết quả: In ra màn hình danh sách các học viên theo thứ tự bảng chữ cái (tiếng Anh), không phân biệt hoa thường. function func6(arr) { return (arr.sort(function (a, b) { return a.localeCompare(b) })); } // // ???? Bài 7. Tạo 3 đối tượng là teacher, student và parent. Mỗi đối tượng đều có các thuộc tính: firstName, lastName, age. Cả 3 đối tượng đều có chung 1 phương thức là say(). Hãy viết function aboutMe() in ra màn hình 1 câu giới thiệu bản thân và gán vào phương thức say() của các đối tượng trên.Function aboutMe() không có tham số truyền vào.Khi truy xuất đến phương thức say() của một đối tượng bất kỳ trong 3 đối tượng tạo sẵn teacher, student và parent thì phải in ra được giá trị các thuộc tính của đối tượng đó. var teacher = { firstName: 'Dương', lastName: 'Quá', age: 28, say: function () { return ('xin chào, tôi là ' + this.firstName + ' ' + this.lastName + ' năm nay tôi ' + this.age + ' tuổi'); } } var student = { firstName: 'Quách', lastName: 'Phù', age: 16, say: function () { return ('xin chào, tôi là ' + this.firstName + ' ' + this.lastName + ' năm nay tôi ' + this.age + ' tuổi'); } } var student = { firstName: 'Hoàng', lastName: 'Dung', age: 46, say: function () { return ('xin chào, tôi là ' + this.firstName + ' ' + this.lastName + ' năm nay tôi ' + this.age + ' tuổi'); } } //vòng lặp //Bài 1. Cho 1 số nguyên n. Viết hàm tính n giai thừa (n!). Ví dụ: n = 5, kết quả trả về là 5! = 1 * 2 * 3 * 4 * 5 = 120. function vl1(a) { let kq = 1; for (let i = 1; i <= a; i++) { kq = kq * i; } return kq; } //Bài 2. Cho 1 chuỗi, hãy viết hàm đảo ngược chuỗi đó. Ví dụ cho chuỗi "hello" thì kết quả trả về sẽ là "olleh". Gợi ý: 1 chuỗi chính là 1 mảng với mỗi phần tử là 1 ký tự trong chuỗi. function vl2(str) { let kq = ''; for (let i = str.length - 1; i >= 0; i--) { kq = kq + str[i]; } return kq; } //Bài 3. Cho 1 chuỗi số, hãy viết hàm duplicate() có tác dụng sao chép chuỗi số lên 10 lần, ngăn cách nhau bởi ký tự "-". Ví dụ cho chuỗi "123" thì kết quả sẽ là "123-123-123-123-123-123-123-123-123-123" function vl3(str) { let kq = str; for (let i = 1; i < 10; i++) { kq = kq + '-' + str; } return kq; } //Bài 4. Cho 1 mảng tên của n học viên. Viết function sắp xếp lại thứ tự các học viên theo bảng chữ cái và in ra màn hình danh sách học viên kèm theo số thứ tự (sử dụng document.write()) function vl4(arr) { //sắp xếp arr.sort(function (a, b) { return a.localeCompare(b); }); console.log('arr: ', arr); //in từng phần tử ra màn hình for (let i = 0; i < arr.length; i++) { document.write((i + 1) + ". " + arr[i] + "<BR>"); } } //Bài 5. Cho 1 mảng các số. Viết function tăng gấp đôi giá trị của các số trong mảng. Ví dụ cho mảng [1,3,4] thì kết quả trả về sẽ là [2,6,8]. function vl5(arr) { for (let i = 0; i < arr.length; i++) { let kq = arr[i] * 2; console.log(kq); } } //Bài 6. Cho 1 mảng các số. Viết function tạo ra 1 mảng mới với các số là số dư tương ứng khi chia các số trong mảng cũ cho 2. Gợi ý: Để lấy số dư của 1 số cho 2 ta dùng toán tử %. Ví dụ: 5 % 2 = 1 (5 chia 2 dư 1) function vl6(arr) { for (let i = 0; i < arr.length; i++) { let kq = arr[i] % 2; console.log(kq); } } //if, else (1) // Bài 1. Sử dụng câu lệnh if để viết 1 hàm với 2 tham số bất kỳ, kiểm tra xem 2 tham số có phải là number không và tìm ra số lớn nhất trong 2 số đó. function bai1(a, b) { if (typeof a != 'number' || typeof b != 'number') { return ('a hoặc b ko phải là số') } else if (a > b) { return (a); } else if (b > a) { return (b); } else if (a == b) { return ('2 số đố = nhau') } } // Bài 2. Viết 1 hàm dùng để tính giai thừa của 1 số. Kiểm tra tham số đầu vào phải là 1 số nguyên dương (số Integer > 0), sau đó tính giai thừa và in ra kết quả. function giaiThua(a) { let kq = 1; for (let i = 1; i <= a; i++) { kq = kq * i; } return kq; } function bai2(a) { if (typeof a != 'number') { return ('ko phải là số') } else if (a % 1 != 0 || a < 0) { return ('ko phải là số nguyên dương') } else if (a % 1 == 0 && a > 0) { return giaiThua(a); } } //Bài 3. Cho 1 mảng các số bất kỳ. Tạo ra 1 mảng mới chỉ chứa các số chẵn lấy ra từ mảng trên và sắp xếp theo thứ tự giảm dần. function bai3(arr) { arr.sort(function (a, b) { return b - a }); var newArr = [] for (var i = 0; i < arr.length; i++) { if (arr[i] % 2 == 0) { newArr.push(arr[i]); } } return newArr; } //bài 4 ??????????????????????????? //Bài 4. Một trang web cho phép người dùng tạo tài khoản. Hãy viết hàm kiểm tra tính hợp lệ của thông tin người dùng nhập vào. var user = { name: 'str1'; pass: 'str2'; confirm: 'str2'; intro: function () { if (user.name == 'false' || user.name.length > 20) { return ('ko hợp lệ'); } else if (user.name.length > 0 && user.name.length < 0) { return ('hợp lệ'); } } } //dk, rẽ nhánh phần 2 //bài 1?????????????????? var now = new Date(); // Lấy thời gian hiện tại var date = now.getDate(2); // Lấy ngày từ thời gian hiện tại var month = now.getMonth(6) + 1; // Lấy tháng từ thời gian hiện tại. Do tháng trong javascript tính từ 0 - 11 nên phải +1 var year = now.getFullYear(2018); // Lấy năm (đầy đủ 4 số) từ thời gian hiện tại //Bài 2. Viết hàm cắt chuỗi với tham số là 1 chuỗi bất kỳ. Kiểm tra xem tham số nhập vào có phải là chuỗi không, nếu là số thì convert sang chuỗi. Sau đó lại kiểm tra nếu chuỗi có độ dài nhỏ hơn 10 ký tự thì hiển thị toàn bộ chuỗi, nếu chuỗi có độ dài lớn hơn 10 ký tự thì hiển thị 10 ký tự đầu tiên kèm theo dấu "...". function condition2(str) { console.log(typeof str); if (typeof str == 'string' && str.length < 10) { return (str); } else if (typeof str == 'string' && str.length >= 10) { return (str.slice(0, 10) + '...'); } else if (typeof str == 'number') { str = str.toString(); if (str.length >= 10) { return (str.slice(0, 10) + '...'); } else { return str; } } else { return "khong phai string or number"; } } // bài 3 Một sinh viên có điểm kiểm tra môn lập trình web là x dưới dạng số (0 <= x <= 10). Hãy chuyển điểm số sang dạng chữ với điều kiện sau: //Từ 0 đến 3.9: Điểm F //Từ 4 đến 5.4: Điểm D //Từ 5.5 đến 6.9: Điểm C //Từ 7 đến 8.4: Điểm B //Từ 8.5 đến 10: Điểm A function diem(a) { if (typeof a == 'number' && a >= 0 && a <= 10) { if (a >= 0 && a <= 3.9) { return 'Điểm F'; } else if (a >= 4 && a <= 5.4) { return 'Điểm D'; } else if (a >= 5.5 && a <= 6.9) { return 'Điểm C'; } else if (a >= 7 && a <= 8.4) { return 'Điểm B'; } else { return 'Điểm A'; } } else { return 'Điểm nhập vào ko đúng' } } //Bài 4. Viết hàm translate() có tác dụng dịch từ "Hello" sang 5 thứ tiếng khác nhau (tự chọn) với tham số truyền vào là mã quốc gia, sử dụng switch và mặc định dịch sang tiếng Việt. function translate(a) { switch (a) { case 'VN': return ('Xin Chào'); case 'China': return ('你 好'); case 'Japan': return ('こんにちは'); case 'Korea': return ('안녕하세요'); case 'Eng': return ('Hello'); case 'Italy': return ('Ciao'); } } //Bài 5. Cho 1 mảng gồm các giá trị true và false, ví dụ: [false, false, false, true, false, true, false, true]. Hãy kiểm tra xem giá trị true xuất hiện lần đầu trong mảng ở vị trí nào. function bai5(arr) { for (var i = 0; i < arr.length; i++) { if (arr[i] == 'true') { var a = i + 1; console.log('Giá trị true xuất hiện lần đầu trong mảng ở vị trí là: ' + a); break; } } } //Bài 6. Chỉ sử dụng while hoặc for, hãy viết function in ra màn hình các số từ 1 đến 100. Với điều kiện những giá trị là chẵn sẽ có màu xanh, giá trị lẻ có màu đỏ. function bai6() { for (let i = 1; i <= 100; i++) { console.log('%c' + i, color: ${ i % 2 === 0 ? 'red' : 'blue' }); } } // Vẽ Hình //vd vẽ hình vuông function vuong(n) { var str = ''; for (var i = 0; i < n; i++) { for (var j = 0; j < n; j++) { // In ra n dấu * str += ' * '; } // In ra dấu xuống dòng str += '<br/>'; } return str; } //bài 1 vẽ hình tam giác vuông cân function tamGiac(n) { var str = ''; for (var i = 0; i < n; i++) { for (var j = 0; j < n; j++) { // In ra n dấu * str += ' * '; } // In ra dấu xuống dòng str += '<br/>'; } return str; } // bài tập về nhà //bai1 var d = new Date(); var day = d.getDay(); var date = d.getDate(); var month = d.getMonth(); var s = d.getSeconds(); var m = d.getMinutes(); var h = d.getHours(); function ngayHT(day) { switch (day) { case 0: return ('Sunday'); case 1: return ('Monday'); case 2: return ('Tuesday'); case 3: return ('Wednesday'); case 4: return ('Thursday'); case 5: return ('Friday'); case 6: return ('Saturday'); } } function gioHT (h) { if (h<12) { return h + 'AM'; } else if (h==12) { return h +'PM'; } else { return h-12 + 'PM' } } function btvn1 () { return ('Today is: ' + ngayHT(day) + ' | Current time is ' + gioHT(h) + ':' + m + ':' + s); } //2 - Viết một function tính số ngày còn lại để đến ngày 2/9/2018. VD hôm nay là 31/8 thì còn 2 ngày, 1/9 thì còn 1 ngày //bai 2 function btvn2 (day, month) { const ngayHienTai = new Date(); let ngayHT = ngayHienTai.getDate(); let thangHT = ngayHienTai.getMonth() +1; let namHT = ngayHienTai.getFullYear(); if (thangHT >= month && ngayHT > day) { namHT +=1; console.log('namHT :', namHT); } const ngayTiepTheo = new Date (namHT, month-1; day); console.log ('ngayTiepTheo :', ngayTiepTheo); const soMiliGiayTrongNgay = 24*60*60*1000; const tongThoiGianHT = ngayHienTai.getTime(); const tongThoiGianNgayTiepTheo = ngayTiepTheo.getTime(); return Math.cell((tongThoiGianNgayTiepTheo - tongThoiGianHT)/soMiliGiayTrongNgay); } //bài 3 - Viết function khi truyền vào 2 số ra được kết quả nhân và chia 2 số đó. Ví dụ truyền 2 số (3,4) trả về phép nhân là 12 phép chia là 0.75 function btvn3(a, b) { if (typeof a == 'number' && typeof b == 'number') { let c = a * b; let d = a / b; return 'Kết quả phép nhân là ' + c + ' và kết quả phép chia là ' + d; } else { return 'a,b ko phải là số' } } //BTVN 4 Viết function chuyển đổi nhiệt độ từ độC sang nhiệt độ Celsius, độ F (công thức search trên mạng) function btvn4(c) { if (typeof c == 'number') { let a = c * 1.8; let f = a + 32; return ('Giá trị chuyển sang độ F là ' + f); } else { return 'tham số truyền vào ko phải là 1 số' } } //BTVN 5 Viết một function truyền vào 2 số trả về tổng 2 số đó, nếu 2 số bằng nhau thì trả về 3 lần tổng 2 số đó. ví dụ (2,2) kết quả 12 function btvn5(a, b) { if (typeof a == 'number' && typeof b == 'number') { let c = a + b; if (a == b) { return (3 * c); } else { return c; } } else { return 'a,b ko phải là số' } } //BTVN 6 //Viết một function đảo ngược số ví dụ 123 thành 321. Đầu vào đầu ra phải là số function btvn6(a) { if (typeof a != 'number') { return 'ko phải là số'; } else { let b = a.toString(); let kq = ''; for (let i = b.length - 1; i >= 0; i--) { kq = kq + b[i]; } console.log(kq); return parseInt(kq); } }
const ClientList = zoid.create({ tag: 'zoid-client-list', url: 'http://localhost/modularrazorweb/clientlist/show', dimensions: { width: '100%', height: '100%' } }); ClientList().render('#container-client-list');
var EVENTS = (function () { var my = {}; my.caughtPoint = function () { LOGIC.generateNewPointPosition(); LOGIC.scorePlusOne(); LOGIC.snakeIncrease(); }; my.clashBorders = function () { DRAW.gameOver(); }; my.clashTail = function () { DRAW.gameOver(); }; return my; }());
import React, { useEffect, useRef } from 'react' import { node, number, string } from 'prop-types' import classes from './parallax.module.scss' const Parallax = ({ src, children, threshold = .2 }) => { const ref = useRef() function parallax() { if (ref && ref.current) { const yOffset = window.pageYOffset const range = yOffset * threshold; if (range > 0 && yOffset > 0) { const bgPos = 'center ' + range + 'px'; ref.current.style.backgroundPosition = bgPos } else { ref.current.style.backgroundPosition = 'center top' } } } useEffect(() => { window.addEventListener("scroll", parallax) return () => { window.removeEventListener('scroll', parallax) } // eslint-disable-next-line react-app/react-hooks/exhaustive-deps }, []) return ( <div ref={ref} style={{backgroundImage: `url(${src})`}} className={classes.parallax} data-testid="parallax"> {children} </div> ) } Parallax.propTypes = { src: string.isRequired, children: node, threshold: number } export default Parallax
editFunction = function (row, store) { Ext.define('GIGADE.EmsGoalComActual', { extend: 'Ext.data.Model', fields: [ { name: 'department_code', type: 'string' }, { name: 'department_name', type: 'string' } ] }); var EmsGoalComStoreActual = Ext.create("Ext.data.Store", { autoDestroy: true, model: 'GIGADE.EmsGoalComActual', proxy: { type: 'ajax', url: '/Ems/GetDepartmentStore', reader: { type: 'json', root: 'data' } } }); var editFrm = Ext.create('Ext.form.Panel', { id: 'editFrm', frame: true, plain: true, layout: 'anchor', autoScroll: true, labelWidth: 45, url: '/Ems/SaveEmsActual', defaults: { anchor: "95%", msgTarget: "side", labelWidth: 80 }, items: [ { xtype: 'combobox', //網頁 allowBlank: false, editable: false, fieldLabel: "部門", id: 'department_code', name: 'department_code', store: EmsGoalComStoreActual, displayField: 'department_name', valueField: 'department_code', value: '通路發展部' }, { xtype: 'numberfield', fieldLabel: '年', id: 'year', name: 'year', allowBlank: false, allowDecimals: false, minValue: 2000, maxValue: 9999, editable:false, value: parseInt((new Date).getFullYear()) }, { xtype: 'numberfield', fieldLabel: '月', id: 'month', name: 'month', allowBlank: false, allowDecimals: false, minValue: 1, maxValue: 12, editable: false, value: parseInt(((new Date).getMonth() + 1)) }, { xtype: 'numberfield', fieldLabel: '日', id: 'day', name: 'day', allowBlank: false, allowDecimals: false, editable: false, minValue: 1, maxValue: 31, value: parseInt(((new Date).getDate())-1) }, { xtype: 'numberfield', fieldLabel: '成本', allowBlank: false, id: 'cost_sum', name: 'cost_sum', allowDecimals:false, minValue: 0 }, { xtype: 'numberfield', fieldLabel: '訂單總數', allowBlank: false, id: 'order_count', name: 'order_count', allowDecimals: false, minValue: 0 }, { xtype: 'numberfield', fieldLabel: '累計實績', allowBlank: false, id: 'amount_sum', name: 'amount_sum', allowDecimals: false, minValue: 0 } ], buttons: [{ text: "保存", formBind: true, disabled: true, handler: function () { var form = this.up('form').getForm(); if (form.isValid()) { form.submit({ params: { department_code: Ext.htmlEncode(Ext.getCmp("department_code").getValue()), year: Ext.htmlEncode(Ext.getCmp("year").getValue()), month: Ext.htmlEncode(Ext.getCmp("month").getValue()), day: Ext.htmlEncode(Ext.getCmp("day").getValue()), cost_sum: Ext.htmlEncode(Ext.getCmp("cost_sum").getValue()), order_count: Ext.htmlEncode(Ext.getCmp("order_count").getValue()), amount_sum: Ext.htmlEncode(Ext.getCmp("amount_sum").getValue()) }, success: function (form, action) { var result = Ext.decode(action.response.responseText); if (result.success) { if (result.msg == 0) { Ext.Msg.alert("提示信息", "此日期下數據已存在不可重複添加!"); } else if (result.msg == 1) { Ext.Msg.alert("提示信息", "保存成功!"); store.load(); editWin.close(); } else if (result.msg == 2) { Ext.Msg.alert("提示信息", "保存失敗!"); store.load(); editWin.close(); } else if (result.msg == 3) { Ext.Msg.alert("提示信息", "您選的日期有誤,請重新選擇!"); } else if (result.msg == 4) { Ext.Msg.alert("提示信息", "您選的日期大於當前日期,請重新選擇!"); } } else{ Ext.Msg.alert("提示信息", "保存失敗!"); store.load(); editWin.close(); } } }); } } } ] }); var editWin = Ext.create('Ext.window.Window', { title: "新增實際業績", id: 'editWin', iconCls: "icon-user-add", width: 350, height: 300, layout: 'fit', items: [editFrm], constrain: true, //束縛窗口在框架內 closeAction: 'destroy', modal: true, resizable: false, labelWidth: 60, bodyStyle: 'padding:5px 5px 5px 5px', closable: false, tools: [ { type: 'close', qtip: "關閉窗口", handler: function (event, toolEl, panel) { Ext.MessageBox.confirm("提示信息", "是否關閉窗口", function (btn) { if (btn == "yes") { Ext.getCmp('editWin').destroy(); } else { return false; } }); } }] }); editWin.show(); }
import React from 'react' import { Switch, Route } from 'react-router-dom' import ProtectedRoute from '@/components/ProtectedRoute' import Login from '@/views/Login' import Home from '@/views/Home' function Router() { return ( <Switch> <Route path='/login' component={Login} /> <ProtectedRoute path='/' component={Home} /> </Switch> ) } export default Router
const path = require('path') global.currentRootDir = path.join(__dirname, '..') global.rootRequire = function (name) { return require(path.join(__dirname, '..', name)) }
import React from "react"; import { connect } from "react-redux"; import { Link } from "react-router-dom"; import { getComments, postComment } from "./actions"; const mapStateToProps = (state, props) => { return { ...props, comments: state.wallpost[props.id], users: state.users }; }; class Wallpost extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.addNewWallPost = this.addNewWallPost.bind(this); this.state = {}; } componentDidMount() { this.props.dispatch(getComments(this.props.dispatch, this.props.id)); } addNewWallPost() { this.props.dispatch(postComment(this.state.newPost, this.props.id)); this.setState({ newPost: "" }); } handleChange(e) { this.setState({ newPost: e.target.value }); } createWallpost(comments, emptyMessage) { if (comments && comments.length > 0) { return comments.map(comment => { const author = this.props.users[comment.author_id]; const firstName = author ? author.first_name : ""; const lastName = author ? author.last_name : ""; const profilePic = author ? ( <img className="friendsonline-img" src={author.profile_pic || "/default.png"} /> ) : null; return ( <div key={comment.id} className="single-friend"> <div className="friendsof-wrapper"> <div className="img-comment"> <div className="img-name-wallpost"> <div className="wrapper-online-img"> <Link to={`/user/${comment.author_id}`}> {profilePic} </Link> </div> <Link className="a-name" to={`/user/${comment.author_id}`} > <div className="friendof-name"> {firstName} {lastName} </div> </Link> </div> </div> <div className="comment">{comment.comment}</div> </div> </div> ); }); } if (!comments) { return null; } return <div className="no-wallpost-requests">{emptyMessage}</div>; } createWallpostView() { return this.createWallpost(this.props.comments, "No posts"); } render() { return ( <div id="friendsof-page"> <div className="big-wrapper-friendsof"> <div className="extra-extra-wrapper"> <h1 className="online-title"> <i className="fas fa-utensils friendsof" />Share Your Hungry </h1> <div className="extra-wrapper-friendsof"> {this.createWallpostView()} </div> <div className="wrapper-inlet-online"> <textarea onChange={this.handleChange} name="comment" className="textarea-comment" value={this.state.newPost} /> <button className="button-comment" onClick={this.addNewWallPost} type="submit" > Send </button> </div> </div> </div> </div> ); } } export default connect(mapStateToProps)(Wallpost);
import test from 'ava'; import parseRoutes from '../../src/server/router/parseRoutes'; test('parseRoutes', (t) => { t.deepEqual(parseRoutes({}), []); t.is(parseRoutes({ quan: './data/aaa.json', '/quan': './data/aaa.json', }).length, 1); t.is( parseRoutes({ '/quan': './data/aaa.json', '/foo': 111, '/rice': { get: './data/qqq.json', post: './data/bbb.json', }, }).length, 3, ); });
// @flow import { runCreate } from '../../../helpers/database'; import type { TokenRecord } from '../types'; export const NO_TOKEN_ERROR = 'addToken requires a token parameter'; export const BAD_TOKEN_TYPE_ERROR = 'addToken requires a string token'; const addToken = async ( token: string ): Promise<TokenRecord | Error> => { if (!token) throw new Error(NO_TOKEN_ERROR); if (typeof token !== 'string') throw new Error(BAD_TOKEN_TYPE_ERROR); return runCreate('Token', { token }); }; export default addToken;
/** * Set global variables */ // structure of Array [element type, number of used arguments] // "-1" stand for infinity var _GatherList = [ [ "AND", -1 ], [ "OR", -1 ], [ "NOT", 1 ] ]; // a global counter for generating unique system id's - need for event // communication between designer field and rules model objects var cSYS_ID = new Counter() // console.log(Counter1()) /** * Klasse RulesDesigner TODO: Singleton */ function __RuleDesigner() { /* BEGIN INITS */ var _self = this Log('Ruledesigner.js - Create', '(main conroller)', 3) var stepsCounter = new Counter() // The view for user interaction var _view // Model 1: A wrapper is need to interact with the external home automation // server (import device data) var _wrapper // Model 2: Store rule data var _rules = new Rules() var cbInitWrapper = function() { Log('# RuleDesigner.js # cbInitWrapper', 4) _wrapper.init(cbBindWrapperData) } var cbBindWrapperData = function() { Log('# RuleDesigner.js # cbBindWrapperData', 4) Log('SuccessCallback', 5) var tmp = _wrapper.getAvailableSegmations.getVirtualDevices(); if ($(tmp).length > 0) { $.map(_wrapper.getAvailableSegmations.getVirtualDevices(), function(val) { val.TYPE = 'SYS_'+val.ID+'_'+val.NAME VIRTUAL_DEVICES.push(val); }) } _view.actualizeObjectList(_wrapper.getAvailableSegmations, VIRTUAL_DEVICES) _self.addNewRule() } // Step 1 - Load GUI-Ressource Helpers.loadGUIContainer(function() { stepsCounter() // Step 2 - Initialize/Build WildCard - GUI _view = new MainView(_self); stepsCounter() // Step 3 - LoadWrapper Helpers.loadWrapper(Configuration.WRAPPER, function() { _wrapper = new Wrapper(); cbInitWrapper() }) // Step 4 - Initialize other windows // Step 5 - Resize window $(window).resize(); stepsCounter() }) this.init = function(data) { Log('# RuleDesigner.js # Init-function', 4) _view.actualize(); $(window).resize(); }; /* END INITS */ /* BEGIN SERVICES */ /** * Function to create a new rule */ this.addNewRule = function() { Log('# RuleDesigner.js # addNewRule', 4) var newRule = _rules.createRule() _view.addRuleTab(newRule); // _view.actualize(); } /** * This function return the rules, representing as root node * * @return rules object {Rules.js} */ this.getRules = function() { return _rules; }; /** * Function to removes a rule object */ this.deleteRule = function(SYS_ID) { Log('# RuleDesigner.js # deleteRule (SYS_ID: ' + SYS_ID + ')', 4) // TODO - Verknuepfungen in anderen Objekten loeschen for (n = 0; n < rules; n++) { // search rule with ... if (rules[n].ID == SYS_ID) { // ... SYS_ID delete rules[n] // if found delete rule object, ... view.actualize(); // actualize view ... return // and break function up } } }; /** * @deprecated Function to commit the information about the available * gathers to the view */ this.getGatherList = function() { Log('# RuleDesigner.js # getGatherList', 4) return _GatherList; } /* END SERVICES */ /** * LoadRule * */ this.loadRule = function() { alert("loadRule"); return true; // TODO: false if fail }; /** * Save rule * */ this.saveRule = function() { alert("saveRule"); alert(JSON.stringify(RuleObject)); return true; // TODO: false if fail }; /** * SaveAs rule * */ this.saveAsRule = function() { alert("saveAsRule"); console.log(JSON.stringify(RuleObject)); return true; // TODO: false if fail }; this.generateJSONString = function() { return JSON.stringify(_rules.serialize(), null, 3); }; };
import React from 'react'; import PropTypes from "prop-types"; import { withStyles } from 'material-ui/styles'; import List, { ListItem, ListItemIcon, ListItemText } from 'material-ui/List'; import IconButton from 'material-ui/IconButton'; import Divider from 'material-ui/Divider'; import AddIcon from 'material-ui-icons/Add'; import DeleteIcon from 'material-ui-icons/Delete'; import OpenIcon from 'material-ui-icons/FolderOpen'; const styles = { text: { paddingRight: 0 }, row: { padding: '5 5 5 10px' } }; class NavMenu extends React.Component { render() { const {classes, onAdd} = this.props; let questions = this.props.questions.map(item => { return ( <ListItem key={item.id} className={classes.row}> <ListItemText className={classes.text} primary={item.sentence} /> <IconButton data-id={item.id} onClick={(e) => { this.props.onEdit(e.currentTarget.dataset.id)} }> <OpenIcon/> </IconButton> <IconButton data-id={item.id} onClick={(e) => { this.props.onDelete(e.currentTarget.dataset.id)} }> <DeleteIcon/> </IconButton> </ListItem> ); }); return( <List> <ListItem button onClick={onAdd}> <ListItemIcon><AddIcon/></ListItemIcon> <ListItemText primary="添加新句子" /> </ListItem> <Divider/> {questions} </List> ); }; } NavMenu.propTypes = { classes: PropTypes.object.isRequired, onAdd: PropTypes.func, questions: PropTypes.array.isRequired, onDelete: PropTypes.func, onEdit: PropTypes.func, }; export default withStyles(styles)(NavMenu);
describe('pixi/display/DisplayObjectContainer', function () { 'use strict'; var expect = chai.expect; var DisplayObjectContainer = PIXI.DisplayObjectContainer; it('Module exists', function () { expect(DisplayObjectContainer).to.be.a('function'); }); it('Confirm new instance', function () { var obj = new DisplayObjectContainer(); pixi_display_DisplayObjectContainer_confirmNew(obj); expect(obj).to.have.property('hitArea', null); expect(obj).to.have.property('interactive', false); expect(obj).to.have.property('renderable', false); expect(obj).to.have.property('stage', null); }); it('Gets child index', function() { var container = new PIXI.DisplayObjectContainer(); var children = []; for (var i = 0; i < 10; i++) { var child = new PIXI.DisplayObject(); children.push(child); container.addChild(child); } for (i = 0; i < children.length; i++) { expect(i).to.eql(container.getChildIndex(children[i])); } }); it('throws error when trying to get index of not a child', function() { var container = new PIXI.DisplayObjectContainer(); var child = new PIXI.DisplayObject(); expect(function() { container.getChildIndex(child); }).to.throw(); }); it('Sets child index', function() { var container = new PIXI.DisplayObjectContainer(); var children = []; for (var i = 0; i < 10; i++) { var child = new PIXI.DisplayObject(); children.push(child); container.addChild(child); } children.reverse(); for (i = 0; i < children.length; i++) { container.setChildIndex(children[i], i); expect(i).to.eql(container.getChildIndex(children[i])); } }); it('throws error when trying to set incorect index', function() { var container = new PIXI.DisplayObjectContainer(); var child = new PIXI.DisplayObject(); container.addChild(child); expect(function() { container.setChildIndex(child, -1); }).to.throw(); expect(function() { container.setChildIndex(child, 1); }).to.throw(); }); });
// Mostrar una serie de números del 0 al 15 // Cada vez que nuestra variable tome el valor de 3 o un multiplo, mostrar fizz // Cada vez que nuestra variable tome el valor de 5 o un multiplo, mostrar buzz // y si es multiplo de 3 y 5 mostrara la frese FizzBuzz for (var dato = 0; dato<16; dato++){ // var modulo3 = (dato%3); // var modulo5 = (dato%5) // console.log(modulo3) // console.log(modulo5) if (dato !== 0) { if ((dato%3) === 0 && (dato%5) === 0 ) { console.log(dato); console.log('Fizzbuzz'); }else if ((dato%3) === 0 ){ console.log(dato); console.log( "Fizz") }else if ((dato%5) === 0 ){ console.log(dato); console.log('Buzz') } } }
const express = require("express"); const app = express(); const mongoose = require("mongoose") const cors = require("cors"); require('dotenv').config(); //Importing My Routes const todoRoutes = require("./routes/todos") app.use(cors()) app.use(express.json()) //DB Connection mongoose.connect(process.env.ATLAS_URI, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true }).then(() => { console.log("DB CONNECTED"); }) //Static Files app.use(express.static('client/build')); //My Routes app.use("/api", todoRoutes) //Port const port = process.env.PORT //Starting the server app.listen(port, (req, res) => { console.log(`Server is running at ${port}`); })
/** * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Defines the GenericMap. */ 'use strict'; import {PriorityQueueMap} from './priority_queue_map'; /** * The priority for binding an explicit type to a generic type based on an input * of the block with the generic type. * @type {number} */ export const INPUT_PRIORITY = 100; /** * The priority for binding an explicit type to a generic type based on the * output of the block with the generic type. * @type {number} */ export const OUTPUT_PRIORITY = 200; /** * The minimum priority that can/should be passed to the GenericMap. * @type {number} */ export const MIN_PRIORITY = 0; /** * The maximum priority that can/should be passed to the GenericMap. * @type {number} */ export const MAX_PRIORITY = Number.MAX_SAFE_INTEGER; /** * Defines a map where generic types can be bound to explicit types in * a given environment. */ export class GenericMap { /** * Constructs the GenericMap. * @param {!Blockly.Workspace} workspace The workspace this GenericMap belongs * to. */ constructor(workspace) { /** * The workspace this GenericMap belongs to. * @type {!Blockly.Workspace} * @private */ this.workspace_ = workspace; /** * Map of block ids to PriorityQueMaps that define what the generic types * of the block are bound to. * @type {!Map<string, !PriorityQueueMap>} * @private */ this.dependenciesMap_ = new Map(); /** * Map of block ids to objects that map generic type names to arrays of * DependerInfo specifying what other blocks and generic types on those * blocks depend on the generic type of the lookup block. * @type {!Map<string, !Map<string, !Array<DependerInfo>>>} * @private */ this.dependersMap_ = new Map(); } /** * Returns the name of the explicit type bound to the generic type in the * context of the given block, or undefined if the type is not bound. * @param {string} blockId The block id that the generic type is * possibly bound in. * @param {string} genericType The generic type to find the explicit binding * of. * @return {undefined|string} The name of the explicit type bound to the * generic type in the context of the given block, or undefined if the * type is not bound. */ getExplicitType(blockId, genericType) { genericType = genericType.toLowerCase(); const priorityMap = this.dependenciesMap_.get(blockId); if (!priorityMap) { return undefined; } const types = priorityMap.getValues(genericType); if (!types) { return undefined; } // In the future we might add logic to figure out what the super type of all // of the types is. But for now there should only be one type bound anyway. return types[0]; } /** * Binds the given dependerType name to the dependencyType's explicit type in * the context of the dependerId. Should only be called if the dependencyType * is currently bound to an explicit type in the context of its block. * Also associates info about the depender with the dependency so that * dependers can be easily removed if the dependency block ever looses its * explicit type. * @param {string} dependerId The id of the block that is depending on the * dependency block. * @param {string} dependerType The name of the generic type in the depender * block that we want to bind to the other type in the dependency block. * @param {string} dependencyId The id of the block that the depender block * is depending on. * @param {string} dependencyType The name of the generic type in the * dependency block that we want to bind the dependerType to. * @param {number} priority The priority of the binding. Higher priority * bindings override lower priority bindings. */ bindTypeToGeneric( dependerId, dependerType, dependencyId, dependencyType, priority) { if (!this.workspace_.getBlockById(dependerId)) { throw Error( 'The depender id (' + dependerId + ') is not a valid block id'); } if (!this.workspace_.getBlockById(dependencyId)) { throw Error( 'The dependency id (' + dependencyId + ') is not a valid block id'); } const explicitType = this.getExplicitType(dependencyId, dependencyType); if (!explicitType) { throw Error('The type ' + dependencyType + ' on block ' + dependencyId + ' is not bound to an explicit type. The generic type must be bound' + ' before another generic type can bind to it.'); } this.bindTypeToExplicit(dependerId, dependerType, explicitType, priority); let types = this.dependersMap_.get(dependencyId); if (!types) { types = new Map(); this.dependersMap_.set(dependencyId, types); } let dependers = types.get(dependencyType); if (!dependers) { dependers = []; types.set(dependencyType, dependers); } dependers.push(new DependerInfo(dependerId, dependerType, dependencyType)); } /** * Binds the given genericType name to the explicitType name in the context * of the blockId. * @param {string} blockId The id of the block to bind the genericType within. * @param {string} genericType The name of the generic type that we want to * bind to the explicit type. * @param {string} explicitType The name of the explicit type we want to bind * the generic type to. * @param {number} priority The priority of the binding. Higher priority * bindings ovveride lower priority bindings. */ bindTypeToExplicit(blockId, genericType, explicitType, priority) { genericType = genericType.toLowerCase(); explicitType = explicitType.toLowerCase(); let queueMap = this.dependenciesMap_.get(blockId); if (!queueMap) { queueMap = new PriorityQueueMap(); this.dependenciesMap_.set(blockId, queueMap); } queueMap.bind(genericType, explicitType, priority); // TODO: Flow through all other connections if necessary. // Make sure to update them if we get a higher priority binding. } /** * Unbinds the given dependerType name from the dependencyType's explicit type * in the context of the dependerId. * Also de-associates info about the depender from the dependency. * @param {string} dependerId The id of the block that is depending on the * dependency block. * @param {string} dependerType The name of the generic type in the depender * block that we want to unbind from the other type on in the dependency * block. * @param {string} dependencyId The id of the block that the depender block * was depending on. * @param {string} dependencyType The name of the generic type in the * dependency block that we want to unbind the dependerType from. * @param {number} priority The priority of the binding to remove. */ unbindTypeFromGeneric( dependerId, dependerType, dependencyId, dependencyType, priority) { const types = this.dependersMap_.get(dependencyId); if (!types) { return; } const dependers = types.get(dependencyType); if (!dependers) { return; } const index = dependers.findIndex((elem) => { return elem.blockId == dependerId && elem.dependerType == dependerType && elem.dependencyType == dependencyType; }); if (index != -1) { const explicitType = this.getExplicitType(dependencyId, dependencyType); this.unbindTypeFromExplicit( dependerId, dependerType, explicitType, priority); dependers.splice(index, 1); } } /** * Unbinds the given generic type name from the explicit type name in the * context of the blockId. * @param {string} blockId The the block to unbind the types in. * @param {string} genericType The name of the generic type to unbind from the * explicit type. * @param {string} explicitType The name of the explicit type to unbind from * the generic type. * @param {number} priority The priority of the binding to remove. */ unbindTypeFromExplicit(blockId, genericType, explicitType, priority) { genericType = genericType.toLowerCase(); explicitType = explicitType.toLowerCase(); if (this.dependenciesMap_.has(blockId)) { this.dependenciesMap_.get(blockId).unbind( genericType, explicitType, priority); } // TODO: Flow through all other connections. } } /** * A class containing info about a depender. Used to tell the depender to stop * depending on the block it is depending on. */ class DependerInfo { /** * Constructs a DependerInfo. * @param {string} blockId The id of the depender block. * @param {string} dependerType The type on the depender block that is * depending on a generic type on another block. * @param {string} dependencyType The generic type on the other block that the * dependerType is depending on. */ constructor(blockId, dependerType, dependencyType) { this.blockId = blockId; this.dependerType = dependerType; this.dependencyType = dependencyType; } }
const encodeFormData=(data)=>{ return Object.keys(data) .map(key=>encodeURIComponent(key)+"="+encodeURIComponent(data[key])) .join("&"); } function submitForm(ev){ ev.preventDefault() let clientName = document.querySelector("#clientName").value let clientURI = document.querySelector("#clientURI").value let grantType = document.querySelector("#grantType").value let redirectURI = document.querySelector("#redirectURI").value let responseType = document.querySelector("#responseType").value let scope = document.querySelector("#scope").value let authMethod = document.querySelector("#authMethod").value const formData={ "clientName":clientName, "clientURI":clientURI, "grantType":grantType, "redirectURI":redirectURI, "responseType":responseType, "scope":scope, "authMethod":authMethod } fetch("http://localhost:3001/api/auth/create_client/", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: encodeFormData(formData) }).then( resp =>resp.json() ).then(data=>{ if(data){ window.sessionStorage.setItem("client_id",data.client_id) window.sessionStorage.setItem("client_secret",data.client_secret) } }) .catch(err=>{ }) return 0; }
// ... rest, ... spread /* const numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90]; const [firstNumber, , thirdNumber, , fifthNumber, , ...rest] = numbers; console.log(firstNumber, thirdNumber, fifthNumber); */ // 0 1 2 // 0 1 2 0 1 2 0 1 2 const numbers = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; const [listOne, listTwo, listThree] = numbers; console.log(listThree[2]);
$(function(){ let kigo = ['!','#','$','%','&','=','@','+','!','#','$','%','&','=','@','+']; let sels = []; //配列のシャッフル for(let i=0; i<20; i++){ let r1 = Math.floor(Math.random() * 16); let r2 = Math.floor(Math.random() * 16); let tmp = kigo[r1]; kigo[r1] = kigo[r2]; kigo[r2] = tmp; } //カードの配布 for(let i=0; i<16; i++){ let ko = $("<div>").text(kigo[i]); $("#container").append(ko); } //クリック時イベントの登録 $("#container div").on("click",function(){ $(this).css("color","#fff"); let moji = $(this).text(); sels.push(moji); if(sels.length == 2){ //比較判定 if(sels[0] == sels[1]){ $("#msg").text("OK!"); }else{ $("#msg").text("NG!"); } sels = [];//初期化 } }); });
import { QuickSend, QuickQuote } from './models'; import { QuickSendView } from './views'; if (HAS_QUICK_SEND === true) { let contact = new QuickSend(), quote = new QuickQuote(), formView = new QuickSendView({ model: contact, quoteModel: quote }); formView.render(); }
/* //////////////////////////////////////////////////////////////////////// */ /* */ /* //////////////////////////////////////////////////////////////////////// */ import Utils from 'web3-utils' import PluginBN from './plugin-bignumber' /* //////////////////////////////////////////////////////////////////////// */ /* */ /* //////////////////////////////////////////////////////////////////////// */ const convertWeiToEth = (val) => { val = PluginBN(val).toString(10) return Utils.fromWei(val, 'ether'); } const convertWeiToGwei = (val) => { val = PluginBN(val).toString(10) return Utils.fromWei(val, 'gwei') } const convertGweiToWei = (val) => { val = PluginBN(val).toString(10) return Utils.toWei(val, 'gwei') } /* //////////////////////////////////////////////////////////////////////// */ /* */ /* //////////////////////////////////////////////////////////////////////// */ export default { convertWeiToEth, convertWeiToGwei, convertGweiToWei } /* //////////////////////////////////////////////////////////////////////// */ /* */ /* //////////////////////////////////////////////////////////////////////// */
const getDb = require('../database/db').getDb; function isUsernameUsed(username) { const db = getDb(); return new Promise((resolve, reject) => { const queryText = 'SELECT username FROM users WHERE username = $1'; const queryValues = [username]; // parameterized query to avoid sql injections db.get(queryText, queryValues, (err, row) => { if (err) { console.log('DB ERROR: ', err); reject('database error'); return; } console.log('row:', row); if (row) { reject('username already in use'); } else { resolve(); } }); }); } module.exports = { isUsernameUsed }
import { Navigation } from '../../../src/Navigation'; jest.unmock('@railsmob/events'); describe('Navigation', () => { describe('.lock', () => { it('should set locked to true', () => { const navigation = new Navigation(); expect(navigation.locked).toBeFalsy(); navigation.lock(); expect(navigation.locked).toBeTruthy(); }); it('should set increment lock counter', () => { const navigation = new Navigation(); expect(navigation.lockCounter).toBe(0); navigation.lock(); navigation.lock(); navigation.lock(); expect(navigation.lockCounter).toBe(3); }); it('should emit lock event', () => { const navigation = new Navigation(); const handler = jest.fn(); navigation.on('lock', handler); navigation.lock(); navigation.lock(); navigation.lock(); expect(handler).toHaveBeenCalledTimes(3); }); }); });
// pages/search/search.js import { me, xmini, xPage, } from '../../config/xmini'; import api from '../../api/index'; import mixins from '../../utils/mixins'; import { debounce } from '../../utils/index'; const app = getApp(); let localHistory = []; xPage({ ...mixins, /** * 页面的初始数据 */ data: { historyList: [], // 历史搜索记录 inputValue: '', couponId: '', focus: true, isPinSku: false, // 从单品sku列表跳转过来为true,其它情况为false hotSearchList: [], hotSearch:{}, // 推荐热词 placeholder: '', searchList: [], //原始搜索建议列表 }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { this.onPageInit(options); const { hotSearch = {} } = app.getData(); console.log(app.getData()) let placeholder = ''; if (options.isPinSku) { const { skuHistoryList } = app.getData(); localHistory = skuHistoryList || []; placeholder = '搜索可使用券的商品'; }else { const { historyList } = app.getData(); localHistory = historyList || []; this.onFecthData(); placeholder = (hotSearch && hotSearch.value) || '搜索您想找的商品'; } console.log(placeholder, 'placeholder'); this.setData({ historyList: localHistory, couponId: options.id || '', isPinSku: options.isPinSku || false, hotSearch: hotSearch || {}, placeholder, }); }, onShow() { this.setData({ focus: true, }); }, onUnload() { }, // dealwith data onFecthData() { wx.showLoading(); api.getHotSearch({ }, (res) => { wx.hideLoading(); this.setData({ hotSearchList: res.data.list, }); }, (err) => { wx.hideLoading(); }); }, clearInput() { this.setData({ inputValue: '', focus: true, searchList: [] }); }, // 获取input value onInputValue(e) { this.setData({ inputValue: e.detail.value, }); if (e.detail.value) { debounce(this.getSearchSuggest.bind(this), 300)(); } else { this.setData({ searchList: [] }) } }, getSearchSuggest() { api.getSearchSuggest({ isLoading: false, keywords: this.data.inputValue }, res => { let { data: { list } } = res; this.setData({ searchList: list }); }, err => { console.log(err); }) }, goBack() { wx.navigateBack(); }, // 热门搜索 onHotSearch(e) { const { value,index } = e.currentTarget.dataset; this.forward('couple-search-list', { q: value, }); console.log(value, 'value111'); xmini.piwikEvent('c_hotsch',{ link:'', name:value, index, }); this.onSaveLocal(false, value); }, // onUrlPage(e){ // const { url,value,index } = e.currentTarget.dataset; // console.log('e1111', e); // xmini.piwikEvent('c_hotsch',{ // link: url, // value, // index, // }); // }, // 搜索 onInputSearch(e) { let value = this.data.inputValue; const { isPinSku } = this.data; const hotSearch = e.currentTarget.dataset.hotsearch; if (!hotSearch.url && hotSearch.value && !value) { value = hotSearch.value; } if (!value.length) { wx.showToast("关键字不能为空"); return; } console.log('value', value); xmini.piwikEvent('c_schbox_textsch',{name:value}); this.onSaveLocal(isPinSku, value); this.onForward(e.currentTarget.dataset.id, value, isPinSku); }, // 保存在本地 onSaveLocal(isPinSku, value) { if (localHistory.length) { let index = localHistory.indexOf(value); if (index > -1) { localHistory.splice(index, 1); } /* index: 数组开始下标 len: 替换 / 删除的长度 item: 替换的值,删除操作的话 item为空 */ localHistory.splice(0, 0, value); }else { localHistory.push(value); } // 取前10个 if (localHistory.length > 10) { const array = localHistory.slice(0, 10); localHistory = array; } if (isPinSku) { app.updateData({ skuHistoryList: localHistory }); }else { app.updateData({ historyList: localHistory }); } this.setData({ historyList: localHistory, }); }, // 点击历史记录跳转 onClickHistory(e) { const { id, value } = e.currentTarget.dataset; const isPinSku = e.currentTarget.dataset.ispinsku; let index = localHistory.indexOf(value); if (index > -1) { localHistory.splice(index, 1); } /* index: 数组开始下标 len: 替换 / 删除的长度 item: 替换的值,删除操作的话 item为空 */ localHistory.splice(0, 0, value); app.updateData({ historyList: localHistory }); this.setData({ historyList: localHistory, }); xmini.piwikEvent('c_hissch',{name:value}); this.onForward(id, value, isPinSku); }, onForward(couponId, q, isPinSku) { if (isPinSku) { this.forward('coupon-sku-list', { couponId, q, }); }else { this.forward('couple-search-list', { q, }); } }, // 清空历史记录 onGarbage(e) { const isPinSku = e.currentTarget.dataset.ispinsku; wx.showModal({ title: '提示', content: '确定清空搜索历史吗?', success:(res) => { if (res.confirm) { if (isPinSku) { app.updateData({ skuHistoryList: null }); }else { app.updateData({ historyList: null }); } localHistory = []; this.setData({ historyList: [], }); xmini.piwikEvent('c_hissch_delebtn'); } } }) }, });
const solution = { 0 : { type: "number", solution : 4, unit: "N", }, 1 : { type: "number", solution : -1, unit: "N", }, 2 : { type: "number", solution : -2, unit: "N", }, }; // Find a way to specify sets of equations being solved at any stage, // and the values that are assigned to variables in them at that time. const TRAINING=true;
//定义在不改变对象的前提下添加新的操作方法。 //主要是call和apply的使用 利用回调函数 //从而造成类数组对象 var Vistor = (function () { return { splice: function () { var args = Array.prototype.splice.call(arguments, 1) return Array.prototype.splice.apply(arguments[0], args) }, push: function () { var len = arguments[0].length var args = this.splice(arguments, 1) arguments[0].length = len + args.length return Array.prototype.push.apply(arguments[0], args) }, pop: function () { //这里不需要改变length.因为在push已经创建了length属性。这样不容易改变 return Array.prototype.pop.call(arguments[0]) } } })() // var a = new Object() // console.log(a.length) // Vistor.push(a, 1, 2, 3, 4) // console.log(a.length) // Vistor.pop(a) // console.log(a.length) //低版本IE的attachEvent中的this是window function bindIEEvent (dom, type, fn, data) { var data = data || {} dom.attachEvent('on' + type, function (e) { fn.call(dom, e, data) }) }
import React, { Component } from "react"; import "./Setup.css"; class Setup extends Component { reportState = this.props.reportState; state = this.props.state || { id: 0, newPlayerName: "", players: [], play: false, }; enterGame = () => { this.reportState(this.state); this.props.enterGame(); }; removePlayer = (id) => { const { players } = this.state; const newState = { ...this.state, players: players.filter((player) => player.id !== id), }; this.setState(newState, this.reportState(newState)); }; getPlayersList = () => { return ( <ul className="players-list"> {this.state.players.map((player) => { return ( <li> <span>{player.name}</span> <button onClick={() => { this.removePlayer(player.id); }} > x </button> </li> ); })} </ul> ); }; submitPlayer = () => { const { id, newPlayerName, players } = this.state; const newState = { ...this.state, players: [...players, { id, name: newPlayerName }], newPlayerName: "", id: id + 1, }; this.setState(newState, this.reportState(newState)); }; render() { const play = this.state.players.length ? ( <div className="play" onClick={() => this.enterGame()}> Play </div> ) : ( <div className="play disabled">Play</div> ); return ( <div className="Setup offset-md-3 col-md-6 col-xs-12"> <div className="new-player"> <input className="player-name" placeholder="player name" onChange={(e) => { const newState = { ...this.state, newPlayerName: e.target.value, }; this.setState(newState, this.reportState(newState)); }} onKeyPress={(e) => { if (e.key === "Enter") this.submitPlayer(); }} value={this.state.newPlayerName} /> <button className="new-player-submit" onClick={() => this.submitPlayer()} > Save Player </button> </div> {this.getPlayersList()} {play} </div> ); } } export default Setup;
define('component/imgUpload', ['jquery', 'KM', 'weui'], function ($, KM, Weui) { var exports = {}; //初始化 exports.init = function (selector, options) { var self = this; self.options = options; self.$imgWraps = $(selector); this.$imgWraps.find(".upload-img").append('<form action="' + this.options.uploadUrl + '" enctype="multipart/form-data" method="post"><input name="file" type="file" data-role="uploadFile"></form>'); self._imgPreviewInit(); self._watch(); } exports._imgPreviewInit = function (relationType) { var self = this; var $imgs = self.$imgWraps.find('img'); if (self.imgPreview) { self.imgPreview.destory(); self.imgPreview = null; } if ($imgs.length > 0) { self.imgPreview = KM.imgPreview($imgs); } } exports._watch = function () { var self = this; self.$imgWraps.on('change', '.upload-img [data-role="uploadFile"]', function () { self._upload($(this)); }).on('click', '.show-img .fa-remove,.show-img .icon-close', function () { self._remove($(this)); }); }; exports._upload = function ($el) { var self = this; if (self.isLoading) { return; } self.isLoading = true; KM.Loading.show(); var $form = $el.parent(); $form.ajaxSubmit({ url: $form.attr('action'), cache: false, success: function (ret) { var s = $form.attr('action'); console.log(s); if (typeof ret === 'string') { ret = JSON.parse(ret); } self._createImg(ret, $el); }, error: function (a, b, c) { KM.popTips.error('上传失败'); }, complete: function () { self.isLoading = false; KM.Loading.hide(); $el.remove(); $form.append('<input name="file" type="file" data-role="uploadFile">'); } }); }; //创建图片 exports._createImg = function (ret, $el) { var self = this; if (ret.Status) { var fileId = ret.Data.Fileld, imgUrl = self.options.imgUrlPrex + "?fileId=" + fileId, $uploadBox = $el.closest('.upload-img'), id = $uploadBox.attr('data-id'), isPdf = ret.Data.IsPDf; var html = '<a href="' + (ret.Data.IsPDf ? imgUrl : 'javascript:void(0);') + '" ' + (ret.Data.IsPDf ? 'target="_blank"' : '') + '>' + (ret.Data.IsPDf ? '附件PDF下载' : '<img src="' + imgUrl + '" />') + '</a>' + '<span class="iconfont icon-close" data-fileid="' + fileId + '"></span>'; $uploadBox.hide().removeClass('k-error') .prev().show().html(html).addClass(ret.Data.IsPDf ? 'no-img' : ''); $(id).val(fileId); self.options.validate.hideError($(id)); self._imgPreviewInit(); } else { KM.popTips.error(ret.ErrorMessage, 800); } }; //删除 exports._remove = function ($el) { var self = this; Weui.confirm('', { title: '您确认要删除该图片吗?', buttons: [{ label: '取消', type: 'default', onClick: function () { } }, { label: '确认', type: 'success', onClick: function () { KM.ajax.post(self.options.removeUrl, { id: $el.attr('data-fileid') }).done(function (ret) { if (ret.Status) { var $uploadBox = $el.closest('.show-img').next(); $uploadBox.show() .prev().hide().html(''); $($uploadBox.attr('data-id')).val(''); self._imgPreviewInit(); } }); } }] }); }; return exports; });