text
stringlengths
7
3.69M
import successfulPermApi from '@/api/successfulPerm' import clientApi from '@/api/client' import userApi from '@/api/user' import commonJS from '@/common/common' import configApi from '@/api/config' import clientlinkmanApi from '@/api/clientlinkman' export default { data () { return { // 显示搜索结果 showSearchResult: false, table: { loading: true, content: [], totalElements: 0, pageable: { pageNumber: commonJS.getPageNumber('successfulPermList.pageNumber'), pageSize: commonJS.getPageSize('successfulPermList.pageSize') } }, page: { pageSizes: [10, 30, 50, 100, 300] }, currentRow: null, searchDialog: false, clients: [], hrs: [], consultants: [], bds: [], cws: [], leaders: [], approveStatusList: [{ 'id': 'applied', 'name': '申请状态' }, { 'id': 'approved', 'name': '审批通过' }, { 'id': 'denied', 'name': '审批否决' }], search: commonJS.getStorageContentObject('successfulPermList.search'), billingSum: null, gpSum: null, billingAvg: null, gpAvg: null, typeList: [], roles: [], jobType: '' } }, methods: { // 通过id删除成功case deleteById () { if (this.checkSelectRow()) { this.$confirm('确认要删除 ' + this.currentRow.title + '-' + this.currentRow.candidateChineseName + ' 成功职位吗?', '确认信息', { distinguishCancelAndClose: true, confirmButtonText: '确定', cancelButtonText: '取消' }).then(() => { let params = { 'id': this.currentRow.id } successfulPermApi.deleteById(params).then(res => { if (res.status === 200) { if (res.data.length > 0) { this.$message.error(res.data) } else { this.$message({ message: '删除成功!', type: 'success', showClose: true }) // 删除后刷新列表 this.query() } } else { this.$message.error('删除失败!') } }) }) } }, formatApproveStatus (row, column, cellvalue, index) { if (typeof (cellvalue) !== 'undefined') { if (cellvalue === 'approved') { return '审批通过' } else if (cellvalue === 'denied') { return '审批否决' } } return '申请状态' }, formatDate (row, column, cellvalue, index) { if (typeof (cellvalue) !== 'undefined' && cellvalue !== null && cellvalue !== '') { return cellvalue.substr(0, 10) } return '' }, // 显示控制 showControl (key) { if (key === 'add' || key === 'edit' || key === 'delete') { return commonJS.isAdminInArray(this.roles) } // 没有特殊要求的不需要角色 return true }, // 检查是否选择了一条记录 checkSelectRow () { if (this.currentRow === null) { this.$message({ message: '请选择一条记录!', type: 'info', showClose: true }) return false } return true }, // 新增 add () { this.$router.push('/case/successfulPerm') }, // 修改 modify () { if (this.checkSelectRow()) { this.$router.push({ path: '/case/successfulPerm', query: { mode: 'modify', successfulPerm: this.currentRow } }) } }, // 查看 detail () { if (this.checkSelectRow()) { this.$router.push({ path: '/case/successfulPerm', query: { mode: 'detail', successfulPerm: this.currentRow } }) } }, // 查询后台数据 query () { window.localStorage['successfulPermList.search'] = JSON.stringify(this.search) window.localStorage['successfulPermList.pageNumber'] = this.table.pageable.pageNumber window.localStorage['successfulPermList.pageSize'] = this.table.pageable.pageSize this.searchDialog = false let query = { 'currentPage': this.table.pageable.pageNumber, 'pageSize': this.table.pageable.pageSize, 'search': this.search } // 显示加载中 this.table.loading = true // 调用接口获取数据 successfulPermApi.queryPage(query).then(res => { if (res.status !== 200) { this.$message.error({ message: '查询失败,请联系管理员!' }) return } // 显示加载中 this.table.loading = false this.table = res.data this.table.pageable.pageNumber = this.table.pageable.pageNumber + 1 }) successfulPermApi.queryStatistics(query).then(res => { if (res.status !== 200) { this.$message.error({ message: '查询失败,请联系管理员!' }) return } this.billingSum = res.data.billingSum this.gpSum = res.data.gpSum this.billingAvg = res.data.billingAvg this.gpAvg = res.data.gpAvg }) }, // 行变化 rowChange (val) { this.currentRow = val }, // 页尺寸变化 sizeChange (val) { this.table.pageable.pageSize = val this.query() }, // 当前页变化 currentChange (val) { this.table.pageable.pageNumber = val this.query() }, // 上一页 点击 prevClick (val) { this.table.pageable.pageNumber = val this.query() }, // 下一页 点击 nextClick (val) { this.table.pageable.pageNumber = val this.query() }, // 搜索对话框,确定按钮 sureSearchDialog () { this.table.pageable.pageNumber = 1 this.query() }, // 清空查询条件 clearQueryCondition () { this.search = { nonPaymentDue: false } window.localStorage['successfulPermList.search'] = this.search } }, created () { // 获取当前用户的角色列表 userApi.findSelf().then(res => { if (res.status === 200) { this.roles = res.data.roles this.jobType = res.data.jobType } }) // 获取所有“客户”信息 clientApi.findAllOrderByChineseName().then(res => { if (res.status === 200) { this.clients = res.data } }) userApi.findAllEnabled().then(res => { if (res.status === 200) { this.consultants = res.data this.cws = res.data this.bds = res.data this.leaders = res.data } }) clientlinkmanApi.queryAllForSimple().then(res => { if (res.status === 200) { this.hrs = res.data } }) // 查询成功case类型列表 configApi.findAllByCategory({ category: 'SuccessfulCaseType' }).then(res => { if (res.status === 200) { this.typeList = res.data } }) this.query() } }
import React, { useState } from 'react'; import { useDispatch } from 'react-redux'; import _ from 'lodash'; import jsPDF from 'jspdf'; import 'jspdf-autotable'; import { CSVDownload } from 'react-csv'; import { exportCsv } from '../../containers/dashboard/export-csv-action'; const Downloadcvv = ({ exportUrl, downloadcvv, setDownloadcvv, filterParams, tableHeaderData, tableData, }) => { const [isDownloaded, setIsDownloaded] = useState(false); const [exportCsvDetails, setExportCsvDetails] = useState(null); const dispatch = useDispatch(); const csvResponseCallBack = (csvData) => { setExportCsvDetails(csvData); setIsDownloaded(true); setDownloadcvv(!downloadcvv); }; const handleDownloadCsv = () => { const params = filterParams; let newObj = {}; params.forEach((el) => { newObj = Object.assign(newObj, el); }); const urlParams = _.omit(newObj, 'name'); exportCsv(exportUrl, urlParams, csvResponseCallBack, dispatch); }; const printDocument = () => { const unit = 'pt'; const size = 'A4'; // Use A1, A2, A3 or A4 const orientation = 'portrait'; // portrait or landscape const marginLeft = 40; // eslint-disable-next-line new-cap const doc = new jsPDF(orientation, unit, size); doc.setFontSize(15); const title = ''; const headerArray = tableHeaderData.map(({ name }) => name); const headers = [headerArray]; const data = tableData.map((elt) => { return tableHeaderData.map((el) => { if (el.dataField === 'iconUrl') { return ''; } return elt[el.dataField]; }); }); const content = { body: data, head: headers, startY: 50, }; doc.text(title, marginLeft, 40); doc.autoTable(content); doc.save('report.pdf'); setDownloadcvv(!downloadcvv); }; return ( <div className="downloadcvv-sec"> <ul> <li onClick={handleDownloadCsv}>Download CSV file</li> <li onClick={printDocument}> <a>Download PDF file</a> </li> {isDownloaded && ( <CSVDownload data={exportCsvDetails && exportCsvDetails} target="_self" /> )} </ul> </div> ); }; export default Downloadcvv;
/* eslint-disable react-hooks/exhaustive-deps */ import { useEffect, useState } from 'react'; import Layout from '../../components/Layout'; import { useRouter } from 'next/router'; import Link from 'next/link'; import Head from 'next/head'; import { useFormik } from 'formik'; import { useMutation, useQuery } from '@apollo/client'; import * as Yup from 'yup'; import Swal from 'sweetalert2'; import CreatableSelect from 'react-select/creatable'; import { NUEVO_PRODUCTO, OBTENER_HASHTAGSPRODUCTO, OBTENER_PRODUCTOS, } from '../../graphql/dslgql'; const initialValues = { name: '', description: '', amount: 0, active: true, }; const validationSchema = Yup.object({ name: Yup.string().required('El nombre del producto es requerido'), description: Yup.string().required('La descripcion del producto es requerida'), amount: Yup.number() .min(0, 'Monto minimo del producto es 0') .max(999999999, 'Monto maximo es 999.999.999') .required('El monto del productos es requerido'), }); const NuevoProducto = () => { const router = useRouter(); const [selHashTags, setSelHashTags] = useState([]); const [listHashTags, setListHashTags] = useState([]); const { data: dataHashTags, loading: obtenerHashTagsLoading, error: obtenerHashTagsError, } = useQuery(OBTENER_HASHTAGSPRODUCTO); useEffect(() => { if (!obtenerHashTagsLoading) { const _listHashTags = dataHashTags.getProductHashTag.map((tag) => ({ value: tag, label: tag, })); setListHashTags([..._listHashTags]); } }, [obtenerHashTagsLoading]); const [newProduct] = useMutation(NUEVO_PRODUCTO, { update: (cache, { data: { newProduct } }) => { const { getProducts } = cache.readQuery({ query: OBTENER_PRODUCTOS, }); cache.writeQuery({ query: OBTENER_PRODUCTOS, data: { getProducts: [...getProducts, newProduct] }, }); }, }); const handleChange = (newValue, actionMeta) => { setSelHashTags([...newValue]); // console.log(selHashTags, actionMeta.action); // console.group('Value Changed'); // console.log(newValue); // console.log(`action: ${actionMeta.action}`); // console.groupEnd(); }; const formik = useFormik({ initialValues, validationSchema, onSubmit: async (values) => { const { name, description, amount } = values; const hashtags = selHashTags.map((tag) => tag.value.toString().trim()); try { const { data } = await newProduct({ variables: { newProductInput: { name, description, amount, hashtags, }, }, }); Swal.fire('Producto Creado', `${name} se ingreso correctamente`, 'success'); router.push('/productos'); } catch (error) { console.log(error); const { message } = error; Swal.fire('Error', `${message}`, 'error'); } }, }); return ( <> <Head> <title>Productos Nuevo | TodoWork</title> </Head> <Layout> <div className="min-h-screen flex justify-center sm:py-12"> <div className="w-full md:w-2/3 "> <h1 className="font-bold text-center text-2xl mb-5 uppercase text-gray-600"> Nuevo Producto </h1> <div className="bg-white shadow w-full rounded-lg divide-y divide-gray-200"> <form className="px-5 py-7" onSubmit={formik.handleSubmit}> <div className="mb-6"> <label htmlFor="name" className="font-semibold text-sm text-gray-600 pb-1 block" > Nombre </label> <input id="name" type="text" className="shadow appearance-none border border-transparent rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:ring-2 focus:shadow-outline" value={formik.values.name} onChange={formik.handleChange} onBlur={formik.handleBlur} /> {formik.touched.name && formik.errors.name && ( <div className="mb-2 mt-1 bg-red-50 border-l-4 border-red-500 text-red-700 px-4 py-2"> <p className="text-sm">{formik.errors.name}</p> </div> )} </div> <div className="mb-6"> <label htmlFor="description" className="font-semibold text-sm text-gray-600 pb-1 block" > Descripcion </label> <textarea id="description" type="text" className="shadow appearance-none border border-transparent rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:ring-2 focus:shadow-outline" rows="3" value={formik.values.description} onChange={formik.handleChange} onBlur={formik.handleBlur} /> {formik.touched.description && formik.errors.description && ( <div className="mb-2 mt-1 bg-red-50 border-l-4 border-red-500 text-red-700 px-4 py-2"> <p className="text-sm">{formik.errors.description}</p> </div> )} </div> <div className="mb-6"> <label htmlFor="amount" className="font-semibold text-sm text-gray-600 pb-1 block" > Monto </label> <input id="amount" type="number" className="shadow appearance-none border border-transparent rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:ring-2 focus:shadow-outline" value={formik.values.amount} onChange={formik.handleChange} onBlur={formik.handleBlur} /> {formik.touched.amount && formik.errors.amount && ( <div className="mb-2 mt-1 bg-red-50 border-l-4 border-red-500 text-red-700 px-4 py-2"> <p className="text-sm">{formik.errors.amount}</p> </div> )} </div> <div className="mb-6"> <label htmlFor="hashtag" className="font-semibold text-sm text-gray-600 pb-1 block" > Caracteristicas </label> <CreatableSelect id="hashtag" isClearable isMulti options={listHashTags} onChange={handleChange} // value={formik.values.hashtags} // onChange={formik.handleChange} // onBlur={formik.handleBlur} placeholder="Caracteristicas" noOptionsMessage={() => 'No hay resultados'} /> </div> <button type="submit" className="transition duration-200 bg-blue-500 hover:bg-blue-600 hover:shadows-md focus:bg-blue-700 focus:shadow-sm focus:ring-4 focus:ring-blue-500 focus:ring-opacity-50 text-white w-full py-2.5 rounded-lg text-sm shadow-sm hover:shadow-md font-semibold text-center inline-block" > <span className="inline-block mr-2 uppercase">Guardar</span> <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 inline-block" fill="none" viewBox="0 0 24 24" stroke="currentColor" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" /> </svg> </button> <button className=" w-full mt-4 text-blue-500 border-blue-500 border hover:bg-blue-100 text-white py-2.5 rounded-lg text-sm font-semibold text-center inline-block" onClick={formik.resetForm} > <span className="inline-block mr-2 uppercase">Limpiar datos</span> </button> </form> <div className="py-5"> <div className="grid grid-cols-2 gap-1"> <div className="text-center sm:text-left whitespace-nowrap"> <Link href="/productos"> <a className="transition duration-200 mx-5 px-4 py-2 cursor-pointer font-normal text-sm rounded-lg text-gray-500 hover:bg-gray-100 hover:shadow-md focus:outline-none focus:bg-gray-200 focus:ring-2 focus:ring-gray-400 focus:ring-opacity-50 ring-inset"> <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 inline-block align-text-top" fill="none" viewBox="0 0 24 24" stroke="currentColor" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" /> </svg> <span className="inline-block ml-1">Volver</span> </a> </Link> </div> </div> </div> </div> </div> </div> </Layout> </> ); }; export default NuevoProducto;
/** * 参数错误, 为 res 对象添加 参数不合法 响应体封装 * code: 400 * ok: 0 * msg: '参数不合法' */ function resParamsErr(req, res, next) { function fun(args) { if (typeof args === 'string') { // 修改 msg参数 res.status(400).send({ ok:0, code:400, msg: args }) return } if (typeof args === 'object' && args!==null) { args.code || (args.code=400) args.ok || (args.ok=0) args.msg || (args.msg= '参数不符合要求') res.status(args.code).send(args) return } if (typeof args === 'undefined') { res.status(400).send({ ok:0, code:400, msg: '参数不符合要求' }) return } } res.resParamsErr = fun next() } /** * 数据库错误, 为 res 对象添加 数据库语法错误 响应体封装 * code: 500 * ok : -100 * msg : '数据库出错' */ function resDataErr(req, res, next) { // 挂载到 res中 let fun = args=> { if (typeof args === 'string') { // 修改 msg参数 res.status(500).send({ ok:-100, code:500, msg:args }) return } // 传递对象 if (typeof args === 'object' && args!==null) { args.code || (args.code=500) args.ok || (args.ok=-100) args.msg || (args.msg='数据库有误') res.status(args.code).send(args) return } // 默认情况 if (typeof args === 'undefined') { res.status(500).send({ ok:-100, code:500, msg:'数据库有误' }) return } } res.resDataErr = fun next() } /** * 参数通过, 数据库通过, 但不满足业务需求 * code: 202 * ok : -1 * msg : '请更换信息' */ function resBadErr(req, res, next) { // 挂载到 res中 let fun = args=> { if (typeof args === 'string') { // 修改 msg参数 res.status(202).send({ ok:-1, code:202, msg:args }) return } // 传递对象 if (typeof args === 'object' && args!==null) { args.code ||(args.code=202) if (args.ok === undefined || args.ok === null) { args.ok = -1 } args.msg || (args.msg='请更换信息') res.status(args.code).send(args) return } // 默认情况 if (typeof args === 'undefined') { res.status(202).send({ ok:-1, code:202, msg:'请更换信息' }) return } } res.resBadErr = fun next() } /** * OK, * code: 200 * ok : 1 * msg : 'ok' */ function resOk(req, res, next) { // 挂载到 res中 let fun = args=> { if (typeof args === 'string') { // 修改 msg参数 res.send({ ok:1, code:200, msg:args }) return } // 传递对象 if (typeof args === 'object' && args!==null) { args.code || (args.code=200) if (args.ok===undefined || args.ok===null) { args.ok = 1 } args.msg || (args.msg='ok') res.send(args) return } // 默认情况 if (typeof args === 'undefined') { res.send({ ok:1, code:200, msg:'ok' }) return } } res.resOk = fun next() } // function resNotFound(req, res, next) { // // 挂载到 res中 // let fun = args=> { // if (typeof args === 'string') { // // 修改 msg参数 // res.send({ ok:1, code:200, msg:args, result: }) // return // } // // 传递对象 // if (typeof args === 'object' && args!==null) { // args.code || (args.code=200) // if (args.ok===undefined || args.ok===null) { // args.ok = 1 // } // args.msg || (args.msg='ok') // res.send(args) // return // } // // 默认情况 // if (typeof args === 'undefined') { // res.send({ ok:1, code:200, msg:'未找到当前资源' }) // return // } // } // res.resOk = fun // next() // } module.exports = { resParamsErr, resDataErr, resBadErr, resOk }
import React, { useRef } from "react"; import SettingsIcon from "@material-ui/icons/Settings"; // css styles import "assets/css/d3/chart-container.scss"; const ChartContainer = ({ title, children, action, open, onClick }) => { const anchorEl = useRef(); return ( <div className="panel panel-default"> <div className="panel-heading"> <div className="panel-title"> {title || "Chart Area"} <ul className="rad-panel-action" ref={anchorEl}> <SettingsIcon onClick={onClick} style={{ fontSize: "15", cursor: "pointer" }} /> {action(open, anchorEl.current)} </ul> </div> </div> <div className="panel-body"> <div id="areaChart" className="rad-chart"> {children} </div> </div> </div> ); }; export default ChartContainer;
/** * 实现Index的数据模型 * @author 学彤 */ import {resolve} from "dns"; /** * IndexModel类,生成一段异步的数据 * @author 学彤 */ export default class IndexModel { contructor(){} /** * 获取具体的API接口数据,返回异步处理结果 * @author 学彤 */ getData(){ return new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve("Hello IndexAction"); },1000) }) } }
global.request = (global.request === undefined) ? require('request') : global.request; global.request = request.defaults({followRedirect: false, followAllRedirects: false}); global.open = (global.open === undefined) ? require('open') : global.open; global.Handlebars = (global.Handlebars === undefined) ? require('handlebars') : global.Handlebars; global.fs = (global.fs === undefined) ? require('fs') : global.fs; global.epic_api = (global.epic_api === undefined) ? require('../js/epic_api.js') : global.epic_api; require('events').EventEmitter.prototype._maxListeners = 100; // http://stackoverflow.com/questions/8853396/logical-operator-in-a-handlebars-js-if-conditional Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) { switch (operator) { case '==': return (v1 == v2) ? options.fn(this) : options.inverse(this); case '===': return (v1 === v2) ? options.fn(this) : options.inverse(this); case '<': return (v1 < v2) ? options.fn(this) : options.inverse(this); case '<=': return (v1 <= v2) ? options.fn(this) : options.inverse(this); case '>': return (v1 > v2) ? options.fn(this) : options.inverse(this); case '>=': return (v1 >= v2) ? options.fn(this) : options.inverse(this); case '&&': return (v1 && v2) ? options.fn(this) : options.inverse(this); case '||': return (v1 || v2) ? options.fn(this) : options.inverse(this); default: return options.inverse(this); } }); Handlebars.registerHelper('ISODateToUnix', function(ISODate) { return Date.parse(ISODate); }); Handlebars.registerHelper('ISODateToMonthDayYear', function(ISODate) { return (new Date(ISODate).toLocaleDateString(window.navigator.language, {month: 'long', day: 'numeric', year: 'numeric'})); }); global.window.nwDispatcher.requireNwGui().Window.get().title = "Allar's UE4 Marketplace Frontend"; var common = function () {}; common.prototype.getTemplateFromFile = function(template_path) { var data = fs.readFileSync(template_path); return Handlebars.compile(''+data); } module.exports = new common();
//Array subset using Map() - find if an array is a subset of another array const isArraySubset = (superset, subset) => { if (subset.length > superset.length) { return false; } const count = new Map(); for (let i = 0; i < superset.length; i++) { const currentItem = superset[i] if (!count.has(currentItem)) { count.set(currentItem, 1) } else { count.set(currentItem, count.get(currentItem) + 1) } } for (let i = 0; i < subset.length; i++) { const currentItem = subset[i] if (!count.has(currentItem)) { return false } count.set(currentItem, count.get(currentItem) - 1) if (count.get(currentItem) === 0) { count.delete(currentItem); } } return true } // How can you match substring of a sting? function subStringFinder(str, subStr){ var idx = 0, i = 0, j = 0, len = str.length, subLen = subStr.length; for(; i<len; i++){ if(str[i] == subStr[j]) j++; else j = 0; //check starting point or a match if(j == 0) idx = i; else if (j == subLen) return idx; } return -1; } console.log(subStringFinder('abbcdabbbbbck', 'ab')) console.log(subStringFinder('abbcdabbbbbck', 'bck'))
import React, { PureComponent } from 'react' import { FooterWrapper } from './styled' class Footer extends PureComponent { render() { return( <FooterWrapper>Footer</FooterWrapper> ) } } export default Footer
var prefs = new gadgets.Prefs(); // configure Automation REST call var NXRequestParams = { operationId: 'Document.PageProvider', operationParams: { providerName: 'user_socialworkspaces', pageSize: 5, documentLinkBuilder: prefs.getString("documentLinkBuilder") }, operationContext: {}, operationDocumentProperties: "common,dublincore", entityType: 'documents', usePagination: true, displayMethod: displayDocumentList, displayColumns: [ {type: 'builtin', field: 'icon'}, {type: 'builtin', field: 'titleWithLink', label: prefs.getMsg('label.dublincore.title'), view: 'dashboard', codec: 'collaboration'}, {type: 'date', field: 'dc:modified', label: prefs.getMsg('label.dublincore.modified')}, {type: 'text', field: 'dc:creator', label: prefs.getMsg('label.dublincore.creator')} ], noEntryLabel: prefs.getMsg('label.gadget.no.document') }; // execute automation request onload gadgets.util.registerOnLoadHandler(function() { doAutomationRequest(NXRequestParams); });
import React, { Component } from 'react'; import Routing from './Routing.js'; import axios from 'axios'; import './App.css'; class AddGame extends Component { constructor(props) { super(props); this.state = { gameName: '', gameID: null, games: [] } } pushRequest = () => { var nameGame = document.getElementById('nameGame').value; axios.post(`/addGame/${this.state.gameName}`); } editRequest = () => { axios.put(`/updateGame/${this.state.gameID}/${this.state.gameName}`); } deleteRequest = () => { axios.delete(`/removeGame/${this.state.gameID}`); } setStates = (event) => { this.setState({ [event.target.name]: event.target.value }); } handleSubmit = (event) => { console.log('A game name was submitted: ' + this.state.gameName); event.preventDefault(); } render() { return ( <div> {/* <form onSubmit={this.handleSubmit} className="form-inline"> */} <div className="container"> <br /> <br /> <div className="row"> <div className="col-12"> <label> <h1>GAME CREATOR</h1> </label> </div> </div> <br /> <div className="row"> <div className="col-8"> <label> <input type="text" name="gameName" target='one' className="form-control inputArea" onChange={this.setStates} gameName={this.state.gameName} id="nameGame" placeholder="Game *"></input> </label> </div> <div className="col-4"> <label> <input type="submit" value="Submit" onClick={this.pushRequest} /> </label> </div> </div> <br /> <div className="row"> <div className="col-4"> <label> <input type="text" name="gameID" target='one' className="form-control inputArea" onChange={this.setStates} gameName={this.state.gameID} id="gameID" placeholder="Game ID *"></input> </label> </div> <div className="col-4"> <label> <input type="text" name="gameName" target='one' className="form-control inputArea" onChange={this.setStates} gameName={this.state.gameName} id="nameGame" placeholder="New Game Name *"></input> </label> </div> <div className="col-4"> <label> <input type="submit" value="Submit" onClick={this.editRequest} /> </label> </div> </div> <br /> <div className="row"> <div className="col-8"> <label> <input type="text" name="gameID" target='one' className="form-control inputArea" onChange={this.setStates} gameID={this.state.gameID} id="gameID" placeholder="Game ID *"></input> </label> </div> <div className="col-4"> <label> <input type="submit" value="Submit" onClick={this.deleteRequest} /> </label> </div> </div> </div> {/* </form> */} </div > ); } } export default AddGame;
//存储了actionCreator的type, 保证调用正确 不因为字符错误出错 export const REQUEST_LIST = 'citymanage/requestList'; export const FILTER_SUBMIT = 'citymanage/filterSubmit'; export const SHOW_OPEN_CITY_MODAL = 'citymanage/showOpenCityModal';
const express = require('express') const app = express() const cors = require('cors') const port = process.env.PORT || 3001 require('dotenv').config() const helper = require('./helper') const analytics = require('./analytics') const moment = require('moment-timezone') const mailer = require('nodemailer') const templates = require('./email/templates') const fs = require('fs') const fetch = require('node-fetch') app.use(cors()) app.use(express.json()) const MongoClient = require('mongodb').MongoClient const password = encodeURI("B.pdQ5L@c7s!Ayp") const uri = `mongodb+srv://sword:${password}@jmsword-5rgwp.mongodb.net/test?retryWrites=true&w=majority` const client = new MongoClient(uri, { useNewUrlParser: true }) app.get('/', (req, res) => { client.connect(err => { if (err) { res.json({ err: err }) } res.json({ msg: 'Hello' }) }) }) // ADD app.post('/v1/add-record', (req, res) => { let record = { title: req.body.title, description: req.body.description, amount: req.body.amount, date: moment().format("LLLL") } client.connect(err => { if (err) { res.status(518).json({ err: err }) } const collection = client.db("money").collection("records") if (!collection) { res.status(510).json({ msg: "no collection found" }) } collection.insertOne(record, (err, result) => { if (err) { res.status(511).json({ err: err }) } res.status(201).json({ msg: "Successfully inserted", result: result }) }) }) }) // GET ALL WITH TOTAL app.get('/v1/records', (req, res) => { client.connect(err => { if (err) { res.status(518).json({ err: err }) } const collection = client.db("money").collection("records") if (!collection) { res.status(510).json({ msg: "no collection found" }) } collection.find().sort({ date: -1 }).toArray().then( async(resp) => { let total = await helper.get_total(collection) resp = resp.sort((a, b) => { let formatter = "LLLL" let formatterComparator = "YYYYMMDDHHmmss" let momentA = moment(a.date, formatter).format(formatterComparator) let momentB = moment(b.date, formatter).format(formatterComparator) return momentB - momentA }) res.json({ records: resp, total: total[0].total }).status(200) }, err => { res.status(512).json({ err: err }) } ) }) }) app.get('/v2/records', (req, res) => { client.connect(err => { if (err) { res.status(518).json({ err: err }) } const collection = client.db("money").collection("records_v2") if (!collection) { res.status(510).json({ msg: "no collection found" }) } collection.find().sort({ date: -1 }).toArray().then( async (resp) => { let total = await helper.get_total(collection) resp = resp.sort((a, b) => { let formatter = "LLLL" let formatterComparator = "YYYYMMDDHHmmss" let momentA = moment(a.date, formatter).format(formatterComparator) let momentB = moment(b.date, formatter).format(formatterComparator) return momentB - momentA }) res.json({ records: resp, total: total[0].total }).status(200) }, err => { res.status(512).json({ err: err }) } ) }) }) app.post('/v2/records', (req, res) => { let record = { title: req.body.title, description: req.body.description, amount: req.body.amount, date: moment().tz('Asia/Manila').format("LLLL") } client.connect(err => { if (err) { res.status(518).json({ err: err }) } const collection = client.db("money").collection("records_v2") if (!collection) { res.status(510).json({ msg: "no collection found" }) } collection.insertOne(record, (err, result) => { if (err) { res.status(511).json({ err: err }) } res.status(201).json({ msg: "Successfully inserted", result: result }) }) }) }) // DAILY EXPENSE REPORT app.get('/v1/email/daily', async(req, res) => { let data = await analytics.dailyExpenseReport() let totalCurrentMonth = await analytics.totalCurrentMonth() fs.readFile('./email/daily-report.html', "utf8", (err, info) => { if (err) { res.json({ err: err }).status(599) } info = info.split("$DAILY_TOTAL").join(data.dailyTotal) let tableData = helper.createHTMLtable(data.recordsToday) let currMonthHTML = helper.getTotalCurrentMonthHTML currMonthHTML = currMonthHTML.split("$CURRENT_MONTH_TOTAL").join(totalCurrentMonth) let content = info + tableData + currMonthHTML let mail = helper.setupMail(mailer, 'Daily Expense Report', content) mail.transporter.sendMail(mail.mailOptions, (err, info) => { if (err) { res.status(520).json({ error: err }) return } res.status(203).json({ success: 'Email succesfully sent' }) return }) }) }) app.get('/v1/telegram/daily', async(req, res) => { let data = await analytics.dailyExpenseReport() let totalCurrentMonth = await analytics.totalCurrentMonth() fs.readFile('./email/daily-report.html', "utf8", async(err, info) => { if (err) { res.json({ err: err }).status(599) } info = info.split("$DAILY_TOTAL").join(data.dailyTotal) let tableData = helper.createHTMLtable(data.recordsToday) let currMonthHTML = helper.getTotalCurrentMonthHTML currMonthHTML = currMonthHTML.split("$CURRENT_MONTH_TOTAL").join(totalCurrentMonth) let content = helper.getDailyExpenseReportTemplate({ total: data.dailyTotal, records: data.recordsToday, total_current_month: totalCurrentMonth }) let url = `https://api.telegram.org/bot824519524:AAElodIngYraobRAiEl96OXbR66bCopMFnE/sendMessage` let chat_id = `-1001207631326` let body = { text: content, chat_id: chat_id, parse_mode: "Markdown" } let response = await fetch(url, { method: 'POST', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' } }) let json = await response.json() res.json({ response: json, body: body }) }) }) app.get('/v2/telegram/daily', async (req, res) => { let data = await analytics.dailyExpenseReport() let totalCurrentMonth = await analytics.totalCurrentMonth() fs.readFile('./email/daily-report.html', "utf8", async (err, info) => { if (err) { res.json({ err: err }).status(599) } info = info.split("$DAILY_TOTAL").join(data.dailyTotal) // let tableData = helper.createHTMLtable(data.recordsToday) let currMonthHTML = helper.getTotalCurrentMonthHTML currMonthHTML = currMonthHTML.split("$CURRENT_MONTH_TOTAL").join(totalCurrentMonth) let content = helper.getDailyExpenseReportTemplate({ total: data.dailyTotal, records: data.recordsToday, total_current_month: totalCurrentMonth }) let url = `https://api.telegram.org/bot824519524:AAElodIngYraobRAiEl96OXbR66bCopMFnE/sendMessage` let chat_id = `-1001207631326` let body = { text: content, chat_id: chat_id, parse_mode: "Markdown" } let response = await fetch(url, { method: 'POST', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' } }) let json = await response.json() res.json({ response: json, body: body }) }) }) app.get('/v1/email/monthly-report', async(req, res) => { let monthlyData = await analytics.totalPerMonth() let cleanedData = Object.keys(monthlyData).map(key => { let temp = {} temp[key] = monthlyData[key] return temp }) let content = templates.PER_MONTH_TEMPLATE.concat(templates.createPerMonthTable(cleanedData)) let mail = helper.setupMail(mailer, 'Monthly Expense Report', content) mail.transporter.sendMail(mail.mailOptions, (err, info) => { if (err) { res.status(520).json({ error: err }) } res.status(203).json({ info }) }) }) app.get('/playground', async(req, res) => { let averages = await analytics.loadAverages() let dailyTotal = await analytics.loadTotalPerDay() let totalCurrentMonth = await analytics.totalCurrentMonth() let dailyReport = await analytics.dailyExpenseReport() let monthlyTotal = await analytics.totalPerMonth() res.json({ monthlyTotal }) }) app.listen(port, () => { console.log(`running on port ${port}`) })
import axios from "axios"; async function filterCourses({ isPaid, intermediate, beginner, advanced, maxRating, category }) { try { const res = await axios.put( "http://localhost:5000/courses/filter", { isPaid, intermediate, advanced, beginner, minRating: 0, maxRating, category }, { headers: { 'Content-Type': 'application/json', } } ); if (res.status >= 300) { return { statusCode: res.status, error: res.statusText } } return { statusCode: res.status, message: res.statusText, payload: res.data } } catch (error) { return { statusCode: 500, error: "Server Error" } } }; export default filterCourses;
$(document).ready(function(){ var navheight = $('nav').height(); $('main').css({ margin: '0 auto -navheight' }) $('.navbar-toggler').click(function(){ $('main').css({ margin: '0 auto -navheight' }) }) $('#menu_icon').click(function(){ $('.menu').addClass('nav-expanded'); }) $('.close').click(function(){ $('.menu').removeClass('nav-expanded'); }) /* $('html').click(function(e) { if($('.menu').hasClass('nav-expanded')){ if(!$(e.target).hasClass("menu")) { $('.menu').removeClass('nav-expanded'); } } }); */ });
import React from 'react'; import { Container } from 'react-bootstrap'; import Header from '../Header/Header'; import HomeBody from '../HomeBody/HomeBody'; import Particle from '../Particle'; const Home = () => { return ( <section> <Container fluid className="home-section" id="home"> <Particle /> <Header/> <HomeBody/> </Container> </section> ); }; export default Home;
import React, { useState } from "react"; export default function AudioControlsA() { var [volume, setVolume] = useState(85); var [treble, setTreble] = useState(33); var [mid, setMid] = useState(71); var [bass, setBass] = useState(92); return ( <span> <div> <button style={buttonStyle} onClick={() => setVolume((volume = volume + 1))} > <h3>+</h3> </button> {volume} Volume <button style={buttonStyle} onClick={() => setVolume((volume = volume - 1))} > <h3>-</h3> </button> </div> <div> <button style={buttonStyle} onClick={() => setTreble((treble = treble + 1))} > <h3>+</h3> </button> {treble} Treble <button style={buttonStyle} onClick={() => setTreble((treble = treble - 1))} > <h3>-</h3> </button> </div> <div> <button style={buttonStyle} onClick={() => setMid((mid = mid + 1))}> <h3>+</h3> </button> {mid} Mid <button style={buttonStyle} onClick={() => setMid((mid = mid - 1))}> <h3>-</h3> </button> </div> <div> <button style={buttonStyle} onClick={() => setBass((bass = bass + 1))}> <h3>+</h3> </button> {bass} Bass <button style={buttonStyle} onClick={() => setBass((bass = bass - 1))}> <h3>-</h3> </button> </div> </span> ); } var buttonStyle = { background: "white", border: "2px solid black", width: "50px", height: "50px", textAlign: "center", margin: "20px" };
var searchData= [ ['partiecentrale',['PartieCentrale',['../class_partie_centrale.html',1,'PartieCentrale'],['../class_partie_centrale.html#a7d751cb5c469134f70d8736b1307399a',1,'PartieCentrale::PartieCentrale()']]], ['partiecentrale_2ecpp',['partiecentrale.cpp',['../partiecentrale_8cpp.html',1,'']]], ['partiecentrale_2eh',['partiecentrale.h',['../partiecentrale_8h.html',1,'']]], ['partiedroite',['PartieDroite',['../class_partie_droite.html',1,'']]], ['partiedroite_2ecpp',['partiedroite.cpp',['../partiedroite_8cpp.html',1,'']]], ['partiedroite_2eh',['partiedroite.h',['../partiedroite_8h.html',1,'']]], ['partiegauche',['PartieGauche',['../class_partie_gauche.html',1,'']]], ['partiegauche_2ecpp',['partiegauche.cpp',['../partiegauche_8cpp.html',1,'']]], ['partiegauche_2eh',['partiegauche.h',['../partiegauche_8h.html',1,'']]], ['passagepremierplan',['passagePremierPlan',['../class_affichage_note.html#a0aa51540d6daf86d1ea941a5d02619f6',1,'AffichageNote']]], ['path',['path',['../class_affichage_multimedia.html#a8cc81b33f2a8a47dc934c3fdc4e606ea',1,'AffichageMultimedia']]], ['preferences',['Preferences',['../class_preferences.html',1,'Preferences'],['../class_preferences.html#a3fc460c1a11115945b78b2d35d7ade00',1,'Preferences::Preferences()']]], ['preferences_2ecpp',['preferences.cpp',['../preferences_8cpp.html',1,'']]], ['preferences_2eh',['preferences.h',['../preferences_8h.html',1,'']]], ['putinarchive',['putInArchive',['../class_note.html#a56fdb920f299aae703f632698e5121fe',1,'Note']]], ['putincorbeille',['putInCorbeille',['../class_note.html#a27fdfd99521a119ef5f1cbc0c945d59e',1,'Note']]] ];
/** * Functionality specific to Twenty Thirteen. * * Provides helper functions to enhance the theme experience. */ var free_shipping_total_required = 50; ( function( $ ) { var body = $( 'body' ), _window = $( window ), _foxycartURL = 'https://secure.poopourri.com/'; /** * Adds a top margin to the footer if the sidebar widget area is higher * than the rest of the page, to help the footer always visually clear * the sidebar. */ $( function() { if ( body.is( '.sidebar' ) ) { var sidebar = $( '#secondary .widget-area' ), secondary = ( 0 == sidebar.length ) ? -40 : sidebar.height(), margin = $( '#tertiary .widget-area' ).height() - $( '#content' ).height() - secondary; if ( margin > 0 && _window.innerWidth() > 999 ) $( '#colophon' ).css( 'margin-top', margin + 'px' ); } } ); /** * Enables menu toggle for small screens. */ ( function() { var nav = $( '#site-navigation' ), button, menu; if ( ! nav ) return; button = nav.find( '.menu-toggle' ); if ( ! button ) return; // Hide button if menu is missing or empty. menu = nav.find( '.nav-menu' ); if ( ! menu || ! menu.children().length ) { button.hide(); return; } $( '.menu-toggle' ).on( 'click.twentythirteen', function() { nav.toggleClass( 'toggled-on' ); } ); } )(); /** * Makes "skip to content" link work correctly in IE9 and Chrome for better * accessibility. * * @link http://www.nczonline.net/blog/2013/01/15/fixing-skip-to-content-links/ */ _window.on( 'hashchange.twentythirteen', function() { var element = document.getElementById( location.hash.substring( 1 ) ); if ( element ) { if ( ! /^(?:a|select|input|button|textarea)$/i.test( element.tagName ) ) element.tabIndex = -1; element.focus(); } } ); // Header content classes var contentClasses = 'follow-content-open shop-content-open', expandedClass = 'is-expanded', _header = $('.site_header'); // Detect scroll position and change header class _window.scroll(function() { if($('.site_header_checkout').length!=0){ return false; } var minimize = 300, top = _window.scrollTop(); if (top >= minimize) { if (!_header.hasClass('is-minimized')) { _header.removeClass(contentClasses + ' ' + expandedClass); setTimeout(function() { if (_header.hasClass('is-minimized')) { $('.header-content-link').hide(); } }, 300); } _header.addClass('is-minimized'); } else { if (_header.hasClass('is-minimized')) { $('.header-content-link').show(); } setTimeout(function() { _header.removeClass('is-minimized'); }, 0); } } ); // Toggles for header content $('.header-content-link').click(function() { var _link = $(this), _content = _link.attr('data-content'), openClass = _content + '-open'; if (_header.hasClass(openClass)) { _header.removeClass(expandedClass + ' ' + openClass); return false; } if (_header.hasClass(expandedClass)) { _header.removeClass(contentClasses); _header.addClass(openClass); return false; } _header.addClass(expandedClass + ' ' + openClass); }); function updateFreeShippingNotice(cart_price){ if($('.foxyshop_product').length!=0){ var package_price_on_page = parseInt($('#adding_package input#fs_price_'+$('.foxyshop_product').prop('id').split('_')[3]).val()); }else{ var package_price_on_page = 0; } var current_total_price = cart_price + package_price_on_page; $('#total_order_on_page').text(current_total_price); if(current_total_price < free_shipping_total_required){ var remaining = free_shipping_total_required - Math.round(current_total_price); $('.free_shipping_notice').html('FREE shipping to USA on any order $'+free_shipping_total_required+'+ (only $<span class="free_shipping_remaining">'+Math.round(remaining)+'</span> away from free shipping)'); }else{ $('.free_shipping_notice').html('You qualify for FREE shipping to the USA!'); } } // Toggle cart content $('.cart-link, .close_cart_btn').click(function() { var openClass = 'cart-is-open'; _header.toggleClass(openClass); // load the cart if it has something in it if(_header.hasClass(openClass)){ $('#cart-content').html('<iframe id="foxycart_iframe" src="'+_foxycartURL+'cart?'+fcc.session_get()+'" style="width:'+$('#cart-content').width()+'px;height:'+$('#cart-content').height()+'px;border:0px;margin:0px;padding:0px;"></iframe>'); } jQuery.getJSON(_foxycartURL+'cart?'+fcc.session_get()+'&output=json&callback=?', function(cart) { $('.cart-items .count').text(cart.product_count); updateFreeShippingNotice(cart.total_price); }); }); /** * Load the cart quantity */ if (typeof fcc !== 'undefined') { jQuery.getJSON(_foxycartURL+'cart?'+fcc.session_get()+'&output=json&callback=?', function(cart) { $('#cart-content').html('<iframe id="foxycart_iframe" src="'+_foxycartURL+'cart?'+fcc.session_get()+'" style="width:'+$('#cart-content').width()+'px;height:'+$('#cart-content').height()+'px;border:0px;margin:0px;padding:0px;"></iframe>'); $('.cart-items .count').text(cart.product_count); updateFreeShippingNotice(cart.total_price); fcc.events.cart.preprocess.add_pre(function(e, arr) { if (arr['cart'] != "view" && arr['cart'] != "checkout") { console.log("Preprocess - adding a product silently"); var jsonString = ""; jsonString = 'https://' + fcc.storedomain + '/cart?output=json&'+jQuery(e).serialize(); $.getJSON(jsonString+'&callback=?' + fcc.session_get(), function(data) { console.log("And added."); console.info(this); FC.json = data; // fcc.cart_update(); console.log('= = = = = = = = = = = = = = = = = = = = ='); console.info(this); fcc.events.cart.postprocess.execute(e); }); return "pause"; } else { return true; } }); fcc.events.cart.postprocess.add(function(){ jQuery.getJSON(_foxycartURL+'cart?'+fcc.session_get()+'&output=json&callback=?', function(cart) { var openClass = 'cart-is-open'; if(!_header.hasClass(openClass)){ _header.toggleClass(openClass); } // load the cart if it has something in it if(_header.hasClass(openClass)){ $('#cart-content').html('<iframe id="foxycart_iframe" src="'+_foxycartURL+'cart?'+fcc.session_get()+'" style="width:'+$('#cart-content').width()+'px;height:'+$('#cart-content').height()+'px;border:0px;margin:0px;padding:0px;"></iframe>'); } $('.cart-items .count').text(cart.product_count); }); }); }); } /** * Arranges footer widgets vertically. */ if ( $.isFunction( $.fn.masonry ) ) { var columnWidth = body.is( '.sidebar' ) ? 228 : 245; $( '#secondary .widget-area' ).masonry( { itemSelector: '.widget', columnWidth: columnWidth, gutterWidth: 20, isRTL: body.is( '.rtl' ) } ); } } )( jQuery );
(function(){ var site = { init : function() { this.loadPage(); this.cacheDom(); this.bindEvents(); }, cacheDom : function() { this.$basketTable = $('#cos-table'); this.$url = $('.fake-url, .home-link'); this.$item = $('.box'); this.$continua = $('.continua-la-checkout'); this.$cos = $('.cos-body').clone(); this.livrareCos = $('.livrare-cos'); this.cosTd = $('.livrare-cos tr td'); this.codTr = $('.livrare-cos tr'); this.afisor = $('.afisorComanda'); }, bindEvents : function() { var self = this; this.$url.on('click', {self: this}, this.pageLinks); this.$item.on('click', '.btnCart', {self: this}, this.addToCart); this.$basketTable.on('click','.remove', {self: this}, this.itemRemove); this.$basketTable.on('change','.quantity', {self: this}, this.calculateItemPrice); this.$basketTable.on('change','.quantity', {self: this}, this.calculateTotalPrice); this.$continua.on('click', {self: this}, this.checkout); $(document).on('click', '.trimite-comanda', {self: this}, this.sendOrder); }, loadPage : function() { var currentHash = window.location.hash.substr(1); currentHash = currentHash != '' && currentHash != null ? currentHash : 'acasa'; var $page = $(".pagina."+currentHash); $('.pagina.active').removeClass('active'); $("#navigation .selected").removeClass('selected'); $page.addClass('active'); }, pageLinks : function(e) { var self = e.data.self; var url = $(this).attr("href"); var hash = url.split('#')[1]; var $activePage = $('.pagina.active'); var $activeUrls = $("#navigation .selected"); var $parent = $(this).parent(); if (hash != null && hash != "" ) { var $page = $(".pagina."+hash); $activeUrls.removeClass('selected'); $activePage.removeClass('active'); $page.addClass('active'); $parent.addClass('selected'); } }, addToCart : function(e) { var self = e.data.self; var details = $(this).parent().find('p').html(); var title = $(this).parent().find('h3').html(); var processedTitle = title.toLowerCase().trim().replace(/ /g,'-'); var price = $(this).parent().find('span').html(); var identify = $(this).parent().hasClass('details'); var $itemInBasket = self.$basketTable.find('.item.'+processedTitle); if (identify) { var img = $(this).closest('li').find('.view a').clone().html(); } else { var img = $(this).closest('li').find('.img-class').clone().html(); } if($itemInBasket.length == 0) { var html = ""; html += '<tr class="item '+processedTitle+'">'; html += '<td>'; html += '<div class="frame">'+ img + '</div>'; html += '<span class="title">'+title+'</span>'; html += '<p>'+details+'</p>'; html += '</td>'; html += '<td class="pretProdus">'+price+'</td>'; html += '<td class="quant">'; html += '<input type="number" min="0" value="1" class="quantity" />'; html += '<a href="index.html#cos" class="remove">Remove</a>'; html += '</td>'; html += '<td class="totalProdus">'+price+'</td>'; html += '</tr>'; self.$basketTable.append(html); } else { var $quantityInput = $itemInBasket.find('.quantity'); var currentQuantity = parseInt( $quantityInput.val() ); $quantityInput.val(currentQuantity+1); var thisProd = $itemInBasket.find('.pretProdus').text().replace("lei",""); thisProd = parseFloat(thisProd.trim()); totalProdus = thisProd * (currentQuantity+1); $itemInBasket.find('.totalProdus').html(totalProdus + ' lei'); } self=>calculateTotalPrice(self); }, calculateItemPrice : function(e) { var self = e.data.self; var quant = $(this).val(); var thisProd = $(this).parents().find('.pretProdus').text().replace("lei",""); //$(this).parent().parent().find('.totalProdus').text(''); quant = parseInt(quant); thisProd = parseFloat(thisProd.trim()); totalProdus = thisProd * quant; $(this).parents().find('.totalProdus').html(totalProdus + ' lei'); }, calculateTotalPrice : function(e) { var self; if(e.data) { self = e.data; } else { self = e; } if(event) { event.preventDefault(); } var total = 0; var $checkoutBtn = $(".continua-la-checkout"); self.$basketTable.find('.totalProdus').each( function(){ var pret = $(this).text().replace("lei",""); var cantitate = $(this).prev().find('.quantity').val(); cantitate = parseInt(cantitate); pret = parseFloat(pret.trim()); total += pret; }); if(total == 0) { $checkoutBtn.hide(); } else { $checkoutBtn.show(); } self.$basketTable.find('.totalPrice').html(total + ' lei'); }, itemRemove : function(e) { var self = e.data.self; var $item = $(this).parents('.item'); if(confirm('Esti sigur ca vrei sa stergi acest produs din cos?')) { $item.remove(); $self.calculateTotalPrice(); } event.preventDefault(); }, checkout : function() { this.$cos.find('input.quantity').each(function() { var quantity = parseInt( $(this).val() ); $(this).parents('.quant').html(quantity); }); this.livrareCos.html(cos.html()); this.cosTd.find('.frame').each(function() { $(this).removeClass('frame').addClass('frame2'); }); this.codTr.find('.quant').each(function() { $(this).parent().find('.pretProdus').before($(this)); }); var total = 0; var transport = 20; this.livrareCos.find('.totalProdus').each( function(){ //total sum var pret = $(this).text().replace("lei",""); total += parseFloat(pret.trim()); }); this.afisor.find('.totalProd').html(total + ' lei'); //append total sum this.afisor.find('.transport').html('20' + ' lei'); var totalProd = this.afisor.find('.totalProd').html(); totalProd = parseFloat(totalProd); var pretFinal = transport + totalProd; this.afisor.find('.totalCom').html(pretFinal + ' lei'); }, sendOrder: function() { var data = {}; var $formular = $(".pagina.livrare"); data.nume = $formular.find('input.nume').val(); data.adresa = $formular.find('input.adresa').val(); data.adresa2 = $formular.find('input.adresa2').val(); data.oras = $formular.find('input.oras').val(); data.judet = $formular.find('input.judet').val(); data.email = $formular.find('input.email').val(); data.telefon = $formular.find('input.telefon').val(); data.card = $formular.find('input.card').val(); data.numarCard = $formular.find('input.numar-card').val(); data.numeCard = $formular.find('input.nume-card').val(); data.dataCard = $formular.find('input.data-card').val(); $compute = $formular.find('#compute').clone(); $compute.find('img').remove(); data.compute = $compute.html(); var request = $.ajax({ method: "POST", url: "/proceseaza-comanda.php", data: data }); request.done(function () { alert('Comanda dumneavoastra a fost salvata.'); }); request.fail(function( jqXHR, textStatus ) { alert('Comanda dumneavoastra nu a fost salvata.'); }); event.preventDefault(); } } site.init(); })();
export { Model as default } from '@miragejs/server';
/** * Created by tsadykhov on 12/7/16. */ import React from 'react'; import Player from './Player.jsx'; import { createContainer } from 'meteor/react-meteor-data'; import { Players } from '../../imports/players'; class PlayerList extends React.Component { constructor(props) { super(props); } renderPlayers() { return this.props.players.map((player) =>( <Player player={player} /> )); } render() { return ( <ul> {this.renderPlayers()} </ul> ) } } PlayerList.propTypes = { players: React.PropTypes.array.isRequired }; export default createContainer(() => { return { players: Players.find({}).fetch() }; }, PlayerList);
function getPasswordForm(item) { toggleThis('pw'); if((getToggleState('mail')=="down_change")) { toggleUP('mail'); } if(item.className=="down_change") { $("#changing").html(""); $.post("functions/pasw.php", function(data) { $("#change").html(data); }); } else { $("#info").html(""); $("#change").html(""); } } $(function() { $("ul.tabs").tabs("div.panes > div"); }); $(function() { $("ul.admintabs").tabs("div.adminpanes > div"); }); function getEmailForm(item) { toggleThis('mail'); if((getToggleState('pw')=="down_change")) { toggleUP('pw'); } if(item.className=="down_change") { $("#changing").html(""); $.post("functions/email.php", function(data) { $("#change").html(data); }); } else { $("#info").html(""); $("#change").html(""); } } function toggleUP(id) { var d=document.getElementById(id); d.className="up_change"; } function toggleDOWN(id) { var d=document.getElementById(id); d.className="down_change"; } function toggleThis(id) { var d=document.getElementById(id); if(d.className=="up_change") { //alert("Changed to DOWN"); d.className="down_change"; } else { //alert("Changed to UP"); d.className="up_change"; } } function getToggleState(id) { var d=document.getElementById(id); return d.className; } function deleteBookmark(strid) { $.post("mypages.php", {strID:strid}, function(data) { $("#code").html(data); }); } function deleteComment(comid) { $.post("mypages.php", {comID:comid}, function(data) { $("#code").html(data); }); } function changePassword(value1, value2, value3) { var old = (document.getElementById(value1)).value; var new1 = (document.getElementById(value2)).value; var new2 = (document.getElementById(value3)).value; $.post("functions/changepw.php", {oldpw:old, new1pw:new1, new2pw:new2}, function(data) { if(data=="success") { toggleThis('mail'); if((getToggleState('pw')=="down_change")) { toggleUP('pw'); } $("#info").html(""); $("#change").html(""); $("#changing").html("Password was successfully changed!"); } else if(data=="regreq") { $("#changing").html("You need to be logged in."); } $("#info").html(data); }); } function changeEmail(value1, value2, value3) { var old = (document.getElementById(value1)).value; var new1 = (document.getElementById(value2)).value; var new2 = (document.getElementById(value3)).value; $.post("functions/changeEmail.php", {oldpw:old, new1pw:new1, new2pw:new2}, //Skriv ut resultatet som jquerytest.php har kommit fram till i <div> med id results function(data) { if(data=="success") { $("#email").html("Email was successfully changed!"); } $("#info2").html(data); }); }
import { findUserBy } from '../../../db/repositories/user.repository' import HashCrypt from '../../../common/auth/hash' const tokenUtil = require('../../../common/auth/token') const login = async (_, { input }) => { const { email, password } = input let user = await findUserBy(email) if (user != null) { await HashCrypt.validateString(password, user.password) let userLogged = user.dataValues delete userLogged.password let token = tokenUtil.create(userLogged) return { token, isAdmin: userLogged.isAdmin } } else { throw new Error('UserNotExists') } } module.exports = login
// Levene's Test // Luke Mitchell, April 2016 // https://github.com/lukem512/levene-test var sm = require('statistical-methods'); var abs = function(mu, s) { return Math.abs(mu - s); }; var quad = function(mu, s) { var delta = (mu - s); return delta * delta; }; // Perform the Levene transformation. var transform = module.exports.transform = function(samples, quadratic) { var z = []; var modifier = (quadratic) ? quad : abs; samples.forEach(function(sample) { var mu = sm.mean(sample); var zj = []; sample.forEach(function(s) { zj.push(modifier(mu, s)); }); z.push(zj); }); return z; }; // Compute the W-value var test = module.exports.test = function(samples, quadratic) { var z = transform(samples, quadratic); // Compute N, the total number of observations // and p, the number of samples var N = 0, p = samples.length; samples.forEach(function(sample) { N += sample.length; }); // Compute z.., the mean of all zij var zs = []; z.forEach(function(zi) { zs = zs.concat(zi); }); var zdotdot = sm.mean(zs); // Compute the denominator and the numerator var numerator = 0, denominator = 0; for (var i = 0; i < p; i++) { // The number of observations in sample i var n = samples[i].length; // The mean of all zij for sample i var zidot = sm.mean(z[i]); var dz = (zidot - zdotdot); numerator += (n * (dz * dz)); denominator += sm.sum(z[i].map(function(zij) { var dz = (zij - zidot); return (dz * dz); })); } // Add divisors numerator = (N - p) * numerator; denominator = (p - 1) * denominator; // Return ratio return (numerator / denominator); };
import React from 'react'; import {Meteor} from 'meteor/meteor'; import {withTracker} from "meteor/react-meteor-data"; import {Route, Switch} from "react-router"; import NewGameComponent from "../NewGame"; import GamesComponent from '../Home'; import RegularPlay from "../RegularPlay/RegularPlay"; import FastMoney from "../FastMoney/FastMoney"; import './App.css'; import Navbar from "../../components/Navbar"; import Buzzer from "../Buzzer/Buzzer"; import Controller from "../Controller/Controller"; import Paper from "@material-ui/core/Paper"; import HowToPlay from "../HowToPlay"; const styles = { paper: { minHeight: '400px', padding: '100px', marginTop: '50px' }, mobile: { padding: '20px' } }; const EverythingButBuzzer = (props) => ( props.currentUser ? <Switch> <Route path="/" exact> <Navbar/> <div className={"content"}> <GamesComponent/> </div> </Route> <Route path="/games/new"> <Navbar/> <div className={"content"}> <NewGameComponent/> </div> </Route> <Route path="/games/:game_id/regular/:question_num" component={RegularPlay}/> <Route path="/games/:game_id/fast/:round_num" component={FastMoney}/> </Switch> : <React.Fragment> <Navbar/> <div className={"content"}> <Paper style={styles.paper}> <h1>Welcome to Financial Feud!</h1> <h2>Login or Register to Play!</h2> </Paper> </div> </React.Fragment> ); class App extends React.Component { render() { return ( <div className={'App'}> <Switch> <Route path="/how-to-play"> <Navbar/> <div className={"content"}> <HowToPlay/> </div> </Route> {/*Buzzer doesnt require user to be logged in*/} <Route path="/games/:game_id/controller" component={Controller}/> <Route path="/games/:game_id/buzzer/:team_name" component={Buzzer}/> <Route path="/" component={() => <EverythingButBuzzer {...this.props}/>}/> </Switch> </div> ) } } export default withTracker(() => { return { currentUser: Meteor.user() }; })(App);
import { combineReducers } from 'redux'; import articles from './addArticle'; import articleToUpdateId from './articleToUpdate'; const mainReducer = combineReducers({ articles, articleToUpdateId }); export default mainReducer;
///<reference types="Cypress" /> import { When, Then, Given } from 'cypress-cucumber-preprocessor/steps' import homePagePO from '../../../../pageObjects/WAM/functionalPO/homePagePO' import FooterPO from '../../../../pageObjects/WAM/navigationPO/footerPO/FooterPO' import CommonPage from '../../../../pageObjects/commonPO/CommonPO' const footerPage = new FooterPO(); const commonPage = new CommonPage(); const homePage = new homePagePO(); let commonprop = {} let homePageData = {} before(function () { cy.fixture("CommonProperties").then(function (commonProperties) { commonprop = commonProperties; }) cy.fixture("HomeProperties").then(function (homeProperties) { homePageData = homeProperties; }) }); Given('User visits the nblytest site and lands on home page', () => { //Launch application commonPage.LaunchApplication(Cypress.env('us_url_nbhlyTest')) }); Then('User lands on home Page', () => { cy.url().then(url => { cy.request({ url: url }).then((resp) => { //verify the response status code to check whether page opens up successfully or not expect(resp.status).to.eq(200) }) }) }); Then('User able to view header', () => { cy.xpath('//header').should("be.visible") cy.xpath('(//a[@class="nav-link"])[2]').should("be.visible") cy.xpath('(//a[@class="nav-link"])[3]').should("be.visible") cy.xpath('(//a[@class="nav-link"])[4]').should("be.visible") cy.xpath('(//a[@data-title="contact"])').should("be.visible") cy.xpath('(//a[@class="nav-link"])[1)').should("be.visible") }); Then('User able to view main', () => { cy.xpath('//img[@alt="HouseMaster"]').should("be.visible") cy.xpath('//img[@alt="Rainbow International"]').should("be.visible") cy.xpath('//img[@alt="Window Genie"]').should("be.visible") cy.xpath('//img[@alt="Mosquito Joe"]').should("be.visible") cy.xpath('//img[@alt="DryerVent Wizard"]').should("be.visible") cy.xpath('//img[@alt="Mr Rooter"]').should("be.visible") cy.xpath('//img[@alt="Aireserv"]').should("be.visible") cy.xpath('//img[@alt="GroundGuys"]').should("be.visible") cy.xpath('//img[@alt="MrElectric"]').should("be.visible") cy.xpath('//img[@alt="Mr Appliance]').should("be.visible") cy.xpath('//img[@alt="MrHandyman"]').should("be.visible") }); Then('User able to view footer', () => { cy.xpath('//footer').should("be.visible") cy.xpath('//a[@data-title="Contact Us"]').should("be.visible") cy.xpath('//a[@data-title="ADA Notice"]').should("be.visible") cy.xpath('//a[@data-title="Privacy Policy & Legal Statement"]').should("be.visible") cy.xpath('//a[@data-title="Terms of Use"]').should("be.visible") cy.xpath('//a[@data-title="About Ads"]').should("be.visible") cy.xpath('//a[@data-title="Site Map"]').should("be.visible") cy.xpath('//a[@data-title="ProTradeNet"]').should("be.visible") cy.xpath('//a[@data-title="California Privacy Policy"]').should("be.visible") cy.xpath('////a[@data-title="Do Not Sell My Info"]').should("be.visible") cy.xpath('////a[@data-title="California Collection Notice"]').should("be.visible") }); Then('User able to see Footer Links', () => { cy.scrollTo('bottom') cy.wait(500) footerPage.getFooterLinks().then((footerLinks)=>{ expect(footerLinks).to.have.length.greaterThan(0) }) });
import { Types } from './actions'; const localData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : null; const initialState = { user: null, loading: false, error: false, userData: localData, }; const reducer = (state = initialState, action) => { switch (action.type) { case Types.REGISTER_REQUEST: { return { ...state, loading: true, error: false } } case Types.REGISTER_SUCCESS: { return { ...state, user: action.payload, loading: false, error: false, } } case Types.REGISTER_FAILURE: { return { ...state, user: null, error: action.payload, loading: false, } } case Types.LOGIN_REQUEST: { return { ...state, loading: true, error: false } } case Types.LOGIN_SUCCESS: { return { ...state, user: null, userData: action.payload, loading: false, error: false, } } case Types.LOGIN_FAILURE: { return { ...state, user: null, error: action.payload, loading: false, } } case Types.LOGIN_OUT: { return { ...state, userData: null, } } default: return state }; }; export default reducer;
import clone from './deep-clone/index' console.log(clone(1)) console.log(clone(true)) console.log(clone(['hello', 'world']))
'use strict'; angular.module('AYARApp') .controller('ProfileController', function ($scope, ProfilePages) { $scope.getProfilePage = ProfilePages.getProfilePage; $scope.getProfilePage() .success(function (user) { $scope.user = user; }); }) .factory('ProfilePages', function ($http) { var getProfilePage = function () { return $http({ method: 'GET', url: 'api/user', }).success(function (user) { return user; }); }; return { getProfilePage: getProfilePage }; });
require('jquery'); require('angular'); require('angular-ui-bootstrap'); require('angular-ui-router'); require('ui-router-extras'); require('ng-context-menu'); require('underscore'); require('restangular'); var moment = require('moment'); require('./templates'); var modal = require('./modal/modal'); var notification = require('./notification/notification'); var session = require('./session/session'); var authentication = require('./authentication/authentication'); var home = require('./home/home'); var login = require('./login/login'); var socket = require('./socket/socket'); var torrents = require('./torrents/torrents'); var torrentsAdd = require('./torrents.add/torrents.add'); var feeds = require('./feeds/feeds'); var feed = require('./feed/feed'); var feedsAdd = require('./feeds.add/feeds.add'); var feedsEdit = require('./feeds.edit/feeds.edit'); var feedsDelete = require('./feeds.delete/feeds.delete'); angular.module('app', [ 'ui.bootstrap', 'ui.router', 'ct.ui.router.extras', 'restangular', 'ng-context-menu', 'templates', modal.name, notification.name, home.name, login.name, session.name, authentication.name, socket.name, torrents.name, torrentsAdd.name, feeds.name, feed.name, feedsAdd.name, feedsEdit.name, feedsDelete.name ]).config(function($urlRouterProvider, $stickyStateProvider) { $urlRouterProvider.otherwise('/'); }); require('./filters/bytes-filter'); require('./filters/datatransferrate-filter'); require('./filters/percentage-filter'); require('./filters/time-filter'); require('./directives/resize-directive');
import Utils from '../utils/utils'; import Mixins from '../utils/mixins'; import __vueComponentDispatchEvent from '../runtime-helpers/vue-component-dispatch-event.js'; import __vueComponentProps from '../runtime-helpers/vue-component-props.js'; export default { name: 'f7-block', props: Object.assign({ id: [String, Number], inset: Boolean, tabletInset: Boolean, strong: Boolean, tabs: Boolean, tab: Boolean, tabActive: Boolean, accordionList: Boolean, noHairlines: Boolean, noHairlinesMd: Boolean, noHairlinesIos: Boolean, noHairlinesAurora: Boolean }, Mixins.colorProps), created() { Utils.bindMethods(this, ['onTabShow', 'onTabHide']); }, mounted() { const el = this.$refs.el; if (!el) return; el.addEventListener('tab:show', this.onTabShow); el.addEventListener('tab:hide', this.onTabHide); }, beforeDestroy() { const el = this.$refs.el; if (!el) return; el.removeEventListener('tab:show', this.onTabShow); el.removeEventListener('tab:hide', this.onTabHide); }, render() { const _h = this.$createElement; const self = this; const props = self.props; const { className, inset, strong, accordionList, tabletInset, tabs, tab, tabActive, noHairlines, noHairlinesIos, noHairlinesMd, noHairlinesAurora, id, style } = props; const classes = Utils.classNames(className, 'block', { inset, 'block-strong': strong, 'accordion-list': accordionList, 'tablet-inset': tabletInset, tabs, tab, 'tab-active': tabActive, 'no-hairlines': noHairlines, 'no-hairlines-md': noHairlinesMd, 'no-hairlines-ios': noHairlinesIos, 'no-hairlines-aurora': noHairlinesAurora }, Mixins.colorClasses(props)); return _h('div', { style: style, class: classes, ref: 'el', attrs: { id: id } }, [this.$slots['default']]); }, methods: { onTabShow(event) { this.dispatchEvent('tabShow tab:show', event); }, onTabHide(event) { this.dispatchEvent('tabHide tab:hide', event); }, dispatchEvent(events, ...args) { __vueComponentDispatchEvent(this, events, ...args); } }, computed: { props() { return __vueComponentProps(this); } } };
import React from 'react'; import UserLine from './UserLine'; import { Tree, TreeNode } from 'react-organizational-chart'; function WingTree(props) { let wgCC = props.users.filter(user => user.roleHeiararchy === 3 && user.roleId === 1); let ViceCC = props.users.filter(user => user.roleHeiararchy === 3 && user.roleId === 2); let CCC = props.users.filter(user => user.roleHeiararchy === 3 && user.roleId === 4); let GpCCs = props.users.filter(user => user.roleHeiararchy === 4 && user.roleId === 1); let SqCCs = props.users.filter(user => user.roleHeiararchy === 5 && user.roleId === 1); let vacantWgCC = { firstName: 'VACANT', lastName: '', unit: '', afsc: '', roleId: 1, roleHeiararchy: 3, phone: '', email: '', grade: '', }; let vacantVice = { firstName: 'VACANT', lastName: '', unit: '', afsc: '', roleId: 2, roleHeiararchy: 3, phone: '', email: '', grade: '', }; let vacantCCC = { firstName: 'VACANT', lastName: '', unit: '', afsc: '', roleId: 4, roleHeiararchy: 3, phone: '', email: '', grade: '', }; let vacantSqCC = { firstName: 'VACANT', lastName: '', unit: '', afsc: '', roleId: 4, roleHeiararchy: 3, phone: '', email: '', grade: '', }; return ( <Tree lineWidth={'2px'} lineHeight={'30px'} lineColor={'blue'} lineBorderRadius={'10px'} label={wgCC.length !== 0 ? <UserLine key={wgCC[0].id} user={wgCC[0]} roles={props.roles} /> : <UserLine key="1" user={vacantWgCC} roles={props.roles} />} > <TreeNode label={ViceCC.length !== 0 ? <UserLine key={ViceCC[0].id} user={ViceCC[0]} roles={props.roles} /> : <UserLine key="1" user={vacantVice} roles={props.roles} />} /> {GpCCs.length !== 0 ? GpCCs.map((user, index) => <TreeNode label={<UserLine key={index} user={user} roles={props.roles} />} children={ SqCCs.length !== 0 ? SqCCs.map((user, index) => <TreeNode label={<UserLine key={index} user={user} roles={props.roles} />} /> ) : <TreeNode label={<UserLine key={index} user={vacantSqCC} roles={props.roles} /> } />} /> ) : ""} <TreeNode label={CCC.length !== 0 ? <UserLine key="1" user={CCC[0]} roles={props.roles} /> : <UserLine key="1" user={vacantCCC} roles={props.roles} /> } /> </Tree> ) } export default WingTree;
import AppHeader from '../components/app-header' import JuanScroll from '../components/juan-scroll' import AppScroll from '../components/app-scroll' import AppTab from '../components/app-tab' import TheEnd from '../components/the-end' import { Icon, Toast, Lazyload, Uploader, DropdownMenu, DropdownItem, SwitchCell, Loading, Popup, Field, Cell, CellGroup, Picker, DatetimePicker, Radio, RadioGroup, Button, Collapse, CollapseItem, Switch, List, Tab, Tabs, ImagePreview, Swipe, SwipeItem } from 'vant' export default { install(Vue) { // 使用vant的插件 Vue.use(Icon) .use(Lazyload) .use(Uploader) .use(Icon) .use(Lazyload) .use(Uploader) .use(Tab) .use(Tabs) .use(List) .use(Loading) .use(DropdownMenu) .use(DropdownItem) .use(SwitchCell) .use(Popup) .use(Field) .use(Cell) .use(CellGroup) .use(Picker) .use(DatetimePicker) .use(Radio) .use(RadioGroup) .use(Button) .use(Collapse) .use(CollapseItem) .use(Switch) .use(ImagePreview) .use(Swipe) .use(SwipeItem); Vue.prototype.$Toast = Toast; Vue.component(AppHeader.name, AppHeader); Vue.component(JuanScroll.name, JuanScroll); Vue.component(AppScroll.name, AppScroll); Vue.component(AppTab.name, AppTab); Vue.component(TheEnd.name, TheEnd); } }
// 卡牌分组 import cardTeam from '../../code/array/cardTeam'; test('cardTeam:[1,2,3,4,4,3,2,1]', () => { expect(cardTeam([1, 2, 3, 4, 4, 3, 2, 1])).toBe(true); }); test('cardTeam:[1,1,1,2,2,2,3,3]', () => { expect(cardTeam([1, 1, 1, 2, 2, 2, 3, 3])).toBe(false); }); test('cardTeam:[1,1,2,2,2,2]', () => { expect(cardTeam([1, 1, 2, 2, 2, 2])).toBe(true); });
'use strict'; // Book search app using Google Books API // $(document).ready(function(){ // // Setup ajax error handling $(function () { $.ajaxSetup({ error: function (x, status, error) { if (x.status == 400) { console.log('This search failed.') $('#secondary p').css("color", "#db2104"); $('#secondary h3').html('Uh oh...'); $('#secondary p').html('Please type in a book title or author name to search the Google Books database.'); } } }); }); // $('#book_form').submit(function(){ event.preventDefault(); bookSearch(); }); // Using the Google Books API function bookSearch() { // Storing the user input var search = $('#search').val(); // Clear any previous data $('#results').html(''); console.log(search); // $.ajax({ // URL for Google Books database url: "https://www.googleapis.com/books/v1/volumes?q=" + search, dataType: "json", type: 'GET', // On success, run this function success: function(data) { console.log(data); $('#book_form').trigger("reset"); $('#secondary p').css("color", "#49c593"); $('#secondary h3').html('Success!'); $('#secondary p').html('Thank you for using Google Books Lookup. Happy reading!'); // Loop through the data in data.items for(var i = 0; i < data.items.length; i++){ // Store current books' volume info var jdata = data.items[i].volumeInfo; // Create elements and assign them to a variable var newColSm4 = document.createElement('div'); var newImg = document.createElement('img'); var newH2 = document.createElement('h2'); var newH3 = document.createElement('h3'); var newH4 = document.createElement('h4'); var newAnchor = document.createElement('a'); // Add classes to elements newColSm4.className = 'col-sm-12 col-md-8 col-md-offset-2 item'; newAnchor.className = 'button button-primary'; // Add text to tags newH2.innerText = jdata.title; newAnchor.innerText = 'Read now'; // Add attributes newAnchor.href = jdata.infoLink; newAnchor.setAttribute('target', '_blank'); // Create image if one exists if(jdata.imageLinks) { newImg.src = jdata.imageLinks.thumbnail; } else { newImg.src = 'images/no-book-cover.png'; }; // Create publish date if one exists if(jdata.publishedDate) { newH4.innerText = jdata.publishedDate; } else { newH4.innerText = 'No publish date found'; }; // Create author if one exists if(jdata.authors) { newH3.innerText = jdata.authors[0]; } else { newH3.innerText = 'No author found'; }; // Add contents of the variables to html newColSm4.appendChild(newImg); newColSm4.appendChild(newH2); newColSm4.appendChild(newH3); newColSm4.appendChild(newH4); newColSm4.appendChild(newAnchor); // Add results to the screen $('#results').append(newColSm4); }; } }); }; // }); // End document ready function
module.exports = { sassLoaderOptions: { sourceMap: true }, postcssLoaderOptions: { sourceMap: true }, publicRuntimeConfig: { DMPENV: process.env.DMPENV, ISDEVMODE: process.env.ISDEVMODE, baseUrl: process.env.BASE_URL, title: process.env.TITLE_PROJECT, baseApiUrl: `${process.env.BASE_URL}${process.env.PROXY_PATH}`, baseAuth: { username: process.env.AUTH_USER, password: process.env.AUTH_PASSWORD } } };
const express = require('express'); const path = require('path'); const hbs = require('hbs'); const app = express(); const { env } = require('process'); const port = process.env.PORT || 8000; const publicPath = path.join(__dirname, '../public'); const templatePath = path.join(__dirname, '../templates/views'); const partialPath = path.join(__dirname,'../templates/partials'); app.set('view engine', 'hbs'); app.set('views',templatePath); hbs.registerPartials(partialPath); app.use(express.static(publicPath)); app.get('/', (req,res) => { res.render("index"); }); app.get('/about', (req,res) => { res.render("about"); }); app.get('/weather', (req,res) => { res.render("weather"); }); app.get('*', (req,res) => { res.render("404",{ errorMsg: 'Oops! Page Not Found', }); }); app.listen(port, ()=>{ console.log(`Port listning ${port}`); });
'use strict'; /** * @description This class encapsulates all DateTime related logic in * this application */ class DateTimeFunctions { /** * @description returns the current time in 24h format as a String * @returns {string} currentTime */ GetCurrentTime() { const dateObject = new Date(); const cHour = dateObject.getHours(); const cMinute = dateObject.getMinutes(); const hour = (cHour < 10 ? '0' : '') + cHour; const minute = (cMinute < 10 ? '0' : '') + cMinute; const currentTime = `${hour}:${minute}`; return currentTime; } /** * @description returns the current date in dayname, month day format * @returns {string} cDate */ GetCurrentDate() { const dateObject = new Date(); const month = this.GetMonthName(); const day = ('0' + dateObject.getDate()).slice(-2); const dayName = this.GetDayName(); const cDate = `${dayName}, ${month} ${day}`; return cDate; } /** * @description returns the name of the current day * @returns {string} cDayName */ GetDayName() { const date = new Date(Date.now()); const days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', ]; const cDayName = days[date.getDay()]; return cDayName; } /** * @description returns the name of the current day from argument * @param {Date | string} dt * @returns {string} cDayName */ GetDayNameFromParam(dt) { if (!dt) return null; var date = new Date(dt); const days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', ]; const cDayName = days[date.getDay()]; return cDayName; } /** * @description returns the name of the current month * @returns {string} cMonthName */ GetMonthName() { const date = new Date(Date.now()); const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ]; const cMonthName = months[date.getMonth()]; return cMonthName; } } const instance = new DateTimeFunctions(); export { instance as dateTimeFunctions };
import React from 'react'; class Followers extends React.Component { render() { return ( <div className='follower-list'> {this.props.followers.map(follower => { return ( <div key={follower.id}> <p>{follower.login}</p> </div> ) })} </div> ) } } export default Followers;
import React from 'react' import Layout from '../Layout' import {Title, Container} from 'bloomer' import BooksSearchBar from '../components/BooksSearchBar' export default function BooksFinderContainer() { return ( <Layout> <Title>Books Finder</Title> <Container> <BooksSearchBar /> </Container> </Layout> ) }
function compute() //function to calculte interest and total amount { p = document.getElementById("principal").value; var principal = document.getElementById("principal").value; //getting the amount value var rate = document.getElementById("rate").value; //getting the rate of interest var years = document.getElementById("years").value; //getting the number of years if(principal < 1) //if condition to check wheteher the input is validor not { alert("Enter a positive number"); //prompt message if input is not valid principal.focus(); return false; //return } var interest = principal * years * rate /100; //calculating the interest using the formula var year = new Date().getFullYear()+parseInt(years); //calculating the year in which the amount will be matured with interest var amount = parseInt(principal) + parseInt(interest); //calculating the total amount (principal+interest) document.getElementById("result").innerHTML="If you deposit "+principal+",\<br\>at an interest rate of "+rate+"%\<br\>You will receive an amount of "+interest+" as interest,\<br\>in the year "+year+"\<br\>Total amount="+amount+"<br\>" //display statement } function updateRate() //function to update rate value based on user input { var rateval = document.getElementById("rate").value; //getting the user input document.getElementById("rate_val").innerText=rateval; //displaying the user input }
(function(){ angular.module('main.controllers').controller('RunsEntryController', ['$scope', 'api', '$location', function($scope, api, $location){ api.runsEntry.list().success(function(data){ data.status_pagamento = data.status_pagamento *1; if(data.status_pagamento){ data.status_pagamento = "Sim"; }else{ data.status_pagamento = "Não"; } $scope.runsEntry = data; }); $scope.insert = function(runEntry){ $location.path('/runsEntry/insert'); }; $scope.update = function(runEntry){ $location.path('/runsEntry/update/' + runEntry.id); }; }]); angular.module('main.controllers').controller('RunsEntryFormController', ['$scope', 'api', '$location', '$routeParams', function($scope, api, $location, $routeParams){ api.runs.list().success(function(data){ $scope.runs = data; }); api.runners.list().success(function(data){ $scope.runners = data; }); $scope.id_run_entry = $routeParams.idRunEntry; if ( $scope.id_run_entry != null && $scope.id_run_entry > 0 ){ $scope.title = "Editar Inscrição"; api.runsEntry.get($scope.id_run_entry).success(function(data){ $scope.runEntry = data; }); $scope.save = function(){ api.runsEntry.update($scope.runEntry).success(function(){ $location.path('/runsEntry'); }).error(function(data, headers, status){ console.log(headers + status); }); }; }else{ $scope.title = "Efetuar Inscrição"; $scope.runEntry = new RunsEntry(); $scope.save = function(){ api.runsEntry.insert($scope.runEntry).success(function(){ $location.path('/runsEntry'); }).error(function(data, headers, status){ alert("Corredor já cadastrado para a corrida selecionada!"); }); }; } $scope.open = function($event) { $event.preventDefault(); $event.stopPropagation(); $scope.opened = true; }; $scope.cancel = function(){ $location.path('/runsEntry'); }; }]); }).call(this);
/* Eloquent JavaScript: Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a “#” character. The characters should form a chess board. */ function chessBoard(input) { //Enter your code here var width = input; var height = input; var chessGrid = ''; for(var i = 0; i < height; i++){ if(i%2!=0){ for (var k=0; k <width; k++){ if(k%2!=0){ chessGrid += ' '; } else{ chessGrid += '#'; } } } else{ for (var k=0; k <width; k++){ if(k%2!=0){ chessGrid += '#'; } else{ chessGrid += ' '; } } } chessGrid += '\n'; } console.log(chessGrid); } chessBoard(8); chessBoard(10);
var searchData= [ ['headerfield',['HeaderField',['../compose_8c.html#adaffad40d353965ad6b52804bc72afef',1,'compose.c']]], ['historyclass',['HistoryClass',['../history_2lib_8h.html#acb0a49d94e5b4fe512c30e2c12621234',1,'lib.h']]] ];
document.addEventListener('DOMContentLoaded',function (){ let wrapper =document.getElementById('wrapper'); let toplayer =wrapper.querySelector('.top'); let handle= wrapper.querySelector('.handle'); let skew =999; let delta=0; wrapper.addEventListener('mousemove',function(e){ delta=(e.clientX-window.innerWidth/2)*0.5; handle.style.left = e.clientX+ delta +'px'; toplayer.style.width = e.clientX+skew+ delta +'px'; }); });
const CustomError = require('../extensions/custom-error'); const MODERN_ACTIVITY = 15; const HALF_LIFE_PERIOD = 5730; module.exports = function dateSample(sampleActivity) { if (typeof sampleActivity !== 'string') return false; const numActivity = parseFloat(sampleActivity); if (isNaN(parseFloat(sampleActivity)) || numActivity <= 0 || numActivity > 15) { return false; } const k = 0.693 / HALF_LIFE_PERIOD; const t = Math.log(MODERN_ACTIVITY / numActivity) / k; return Math.ceil(t); };
import Projectile from './Projectile.js'; class FireProjectile extends Projectile { constructor(source) { super(stats, source); this.name = 'fire-projectile'; }; }; const stats = { img: 'images/fire-dot.png', xFrame: 0, yFrame: 0, pngWidth: 600, pngHeight: 560, spriteWidth: 30, spriteHeight: 28, speed: 1 }; let source = { x: 150, y: 150 }; let target = { x: 50, y: 350 }; let foo = new FireProjectile(source); foo.active = true; export { FireProjectile, foo, source, target };
import React from 'react'; import classes from './Card.scss'; const Card = (props) => { const currentClasses = props.active ? classes.Card + ' ' + classes.active : classes.Card; return ( <li className={currentClasses} onClick={props.toggleOption}> <div className={classes.Card__card}> <div className={[classes.Card__cardImage, classes[props.keyword]].join(' ')}></div> <div className={classes.Card__cardContent}> <div className={classes.Card__cardTitle}>{props.name}</div> <p className={classes.Card__cardText}>{props.description}</p> </div> </div> </li> ); } export default Card;
/* eslint-disable react/jsx-one-expression-per-line */ import React from 'react' import _range from 'lodash.range' import * as Story from '_story' import ToggleGroup from '.' const Demo = () => ( <> <h1>ToggleGroup</h1> <p> The <em>ToggleGroup</em> component renders a set of <em>Toggle</em>{' '} options. </p> {_range(2, 21).map(count => { const options = [] for (let i = 1; i <= count; i += 1) { options.push({ key: `Option ${i} very very very long`, value: i, }) } return ( <React.Fragment key={count}> <Story.Box> <h4>{count} Radio Toggles</h4> <ToggleGroup type="radio" id={`example-radio-${count}`} name={`example_radio_${count}`} errorMessage="error message very very very very very very very very very very very very long" hasError options={options} /> </Story.Box> <Story.Box> <h4>{count} Checkbox Toggles</h4> <ToggleGroup type="checkbox" id={`example-checkbox-${count}`} name={`example_checkbox_${count}`} errorMessage="error message very very very very very very very very very very very very long" hasError options={options} /> </Story.Box> </React.Fragment> ) })} </> ) Demo.story = { name: 'ToggleGroup', } export default Demo
class Validation{ email(email){ let emailPattern = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/; return emailPattern.test(email); } name(string){ let name=string.trim(); let regex=/[0-9]/ if(name==undefined || name=='' || regex.test(name)){ return false; } if(name.length==1 || name.length>60){ return false; } return true } password(string){ let password=string if(password==null || password.trim()==''){ return false; } if(string.trim().length<6){ return false; } return true; } role(value){ if(value==undefined){ return false; } if(value>1 || value<0){ return false; } return true; } id(value){ let a=isNaN(value); if(a){ return false; } if(value<0){ return false; } return true; } } module.exports=new Validation();
function fn_cp_catalog_changes_search_by_q(elm, val) { var input = $(elm).parents('.ty-search-block').find('input[type="text"].ty-search-block__input'); var submit = $(elm).parents('.ty-search-block').find('button[type="submit"].ty-search-magnifier'); input.val(val); submit.click(); } $(document).mouseup(function (e) { var container = $('#live_reload_box').children(); if (container.has(e.target).length === 0){ container.parents('.ty-search-block').find('input[type="text"].ty-search-block__input').removeClass('cp-live-search-input'); } }); function fn_cp_set_pname_params(value, elm) { $("input[name='is_pname_search']").val(value); tabs = $(elm).siblings(); tabs.each(function(e, child_elm) { $(child_elm).removeClass('cp-selected'); }); $(elm).addClass('cp-selected'); search_elm = $('#search_input'); id_class = $(search_elm).attr('id'); var id = id_class.replace("search_input", ""); search_title = $(search_elm).attr("title") if (search_title == search_elm.val()){ $(search_elm).val(''); $(search_elm).removeClass('cm-hint'); } if (value == 'N') { var reg = /[а-яА-ЯёЁ]/g; if ($(search_elm).val().search(reg) != -1) { $(search_elm).val($(search_elm).val().replace(reg, '')); } } $(search_elm).focus(); ls_go_search(search_elm, id); }
var map; var d = document; function initMap() { // Create a map object and specify the DOM element for display. map = new google.maps.Map(document.getElementById('divMap'), { center: { lat: 43, lng: -76 }, zoom: 7 }); infoWindow = new google.maps.InfoWindow; } < script src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyAIiDv7x_SziT_0Gj-v2SAv6sZaHQWWeEw&callback=initMap" async > < /script> function findMe() { // Try HTML5 geolocation. if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var pos = { lat: position.coords.latitude, lng: position.coords.longitude }; infoWindow.setPosition(pos); infoWindow.setContent('Location found.'); infoWindow.open(map); map.setCenter(pos); map.setZoom(15); }, function() { handleLocationError(true, infoWindow, map.getCenter()); }); } else { // Browser doesn't support Geolocation handleLocationError(false, infoWindow, map.getCenter()); } } function handleLocationError(browserHasGeolocation, infoWindow, pos) { infoWindow.setPosition(pos); infoWindow.setContent(browserHasGeolocation ? 'Error: The Geolocation service failed.' : 'Error: Your browser doesn\'t support geolocation.'); infoWindow.open(map); } d.getElementById("findMe").addEventListener('click', function() { findMe(); }); d.getElementById("clearMap").addEventListener('click', function() { initMap(); });
// Click Event let images = ['image1.jpg','image2.jpg','image3.jpeg','image4.jpeg','image5.jpeg','image6.jpeg','image7.jpeg']; $('#btn-1').click(function() { let random = getRandomNumber(); if(random > 6){ random = getRandomNumber(); } else{ $('#image').attr('src','../img/' + images[random]); } }); // get random Number let getRandomNumber = () => { let randomNumber = Math.floor(Math.random() * 10); return randomNumber; }; let reverseString = (str) => { let tempStr = ''; for(let i=str.length-1; i>=0; i--){ tempStr += str.charAt(i); } return tempStr; }; // Keyup event $('#text-box').keyup(function() { $('#display').text(reverseString($(this).val())); }); // Click Event $('#technologies').change(function() { let selectedOption = $(this).val(); $('#options').text(selectedOption.toUpperCase()); });
// http://finance.yahoo.com/webservice/v1/symbols/GOOG/quote?format=json H.kind({ name: 'H.Api.Yahoo.Stock', });
/* * @lc app=leetcode id=289 lang=javascript * * [289] Game of Life */ // @lc code=start /** * @param {number[][]} board * @return {void} Do not return anything, modify board in-place instead. */ var gameOfLife = function(board) { const yLen = board.length; if (!yLen) { return []; } const xLen = board[0].length; function handleNeighbor(y, x) { let count = 0; const xMin = Math.max(0, x - 1); const xMax = Math.min(xLen - 1, x + 1); const yMin = Math.max(0, y - 1); const yMax = Math.min(yLen - 1, y + 1); for (let j = yMin; j <= yMax; j++) { for (let i = xMin; i <= xMax; i++) { if (!(j === y && x === i)) { count += board[j][i]; } } } return count; } let neighbor = Array.from(board, () => []); for (let j = 0; j < yLen; j++) { for (let i = 0; i < xLen; i++) { neighbor[j][i] = handleNeighbor(j, i); } } for (let j = 0; j < yLen; j++) { for (let i = 0; i < xLen; i++) { if (neighbor[j][i] < 2) { board[j][i] = 0; } else if (neighbor[j][i] < 4) { if (neighbor[j][i] === 3 && !board[j][i]) { board[j][i] = 1; } } else { board[j][i] = 0; } } } }; gameOfLife([[0,1,0],[0,0,1],[1,1,1],[0,0,0]]); // @lc code=end
(function() { 'use strict'; function rename(obj, fn) { if (typeof fn !== 'function') { return obj; } var res = {}; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { res[fn(key) || key] = obj[key]; } } return res; } if (typeof module !== 'undefined' && module.exports) { module.exports = rename; } else { if (typeof define === 'function' && define.amd) { define([], function() { return rename; }); } else { window.rename = rename; } } })();
var $on = $('#on'); var $off = $('#off'); var $relayOn = $('#relay-on'); var $relayOff = $('#relay-off'); var $slider = $('#inputSlider'); var $sliderValue = $('#inputSliderValue'); var $lightTime = $('#lightTime'); var $tempField = $('#temperature-field'); var $pirField = $('#pir-field'); var socket = io.connect(); $on.click(function(){ socket.emit('led:on'); }); $off.click(function(){ socket.emit('led:off'); }); $relayOn.mousedown(function(){ socket.emit('relay-on'); }); $relayOff.mousedown(function(){ socket.emit('relay-off'); }); socket.on('temperature',function(data){ var date = new Date(); $tempField.text(data.temperature+"°C @ "+ date.getHours() + ":" + date.getMinutes() + " hours"); }); // socket.on('pir',function(data){ // $pirField.text(data.moving); // }); // function showValue(value){ // socket.emit('led:change',{value:value}); // } // $slider.on('change',function(){ // var newVal = $(this).val(); // socket.emit('led:change',{value:newVal}); // }); // socket.on('led:change',function(data){ // console.log("the data returned is "+ data.value); // $slider.val(data.value); // $sliderValue.text(data.value); // // socket.emit('led:change',{value:data.value}); // }); // //when there is a lightChange event fired from the light-handler // socket.on('led:lightChange',function(data){ // console.log("the data returned is "+ data.value); // $slider.val(data.value); // $sliderValue.text(data.value); // $lightTime.text(data.time); // socket.emit('led:lightChange',{value:data.value}); // }); // socket.on('temperature',function(data){ // $tempField.text(data.value+" °C"); // });
export default { test: () => {console.log("sukces")} };
const Canvas = require("./../canvas"); const Image = Canvas.Image; var img = new Image(); module.exports = function(urlData, coord) { return new Promise((resolve, reject) => { img.onerror = function(err) { reject(err) } img.onload = function() { let w = Number(coord.w); let h = Number(coord.h); let canvas = Canvas.createCanvas(w, h) let ctx = canvas.getContext('2d') ctx.imageSmoothingEnabled = true; if (!coord.x || !coord.y) ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, w, h) ; else ctx.drawImage(img, Number(coord.x), Number(coord.y), w, h, 0, 0, w, h) ; canvas.toDataURL('image/jpeg', (err, jpeg) => { if (err) return reject(err); resolve(jpeg); }) } try { img.src = urlData; } catch (e) { reject(e); }; }) }
self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "21ce319df321ac3ced0c6f10af092fb9", "url": "/build/index.html" }, { "revision": "06ade12e3835aef9b065", "url": "/build/static/css/main.cfda8877.chunk.css" }, { "revision": "adca6b1d1367ec3ea743", "url": "/build/static/js/2.434ab397.chunk.js" }, { "revision": "06ade12e3835aef9b065", "url": "/build/static/js/main.ed3dc1bf.chunk.js" }, { "revision": "b4d8ef2cb7791815737b", "url": "/build/static/js/runtime~main.9df7376b.js" }, { "revision": "e99543bb86794e15928d03e9b41bb3c8", "url": "/build/static/media/Google_logo.e99543bb.svg" } ]);
const commando = require('discord.js-commando'); var request = require('request'); var http = require('http'); const createEmbed = require("embed-creator"); class Ability extends commando.Command { constructor(client) { super(client, { name: 'ability', group: 'cards', memberName: 'ability', description: 'Returns information for entered hero ability', examples: ['--ability riktor,q', '--ability murdock,square'] }); } async run(message, args) { let hero = args.split(",")[0]; if(hero[0] === " ") hero = hero.slice(1); let skill = args.slice(hero.length + 1); if(skill[0] === " ") skill = skill.slice(1); switch(skill.toLowerCase()){ case "square": skill = "q"; break; case "circle": skill = "e"; break; case "triangle": skill = "r"; break; case "r1": skill = "rmb"; break; case "r2": skill = "lmb"; break; default: skill = skill.toLowerCase(); break; } var heroid; var options = { url: 'https://developer-paragon.epicgames.com/v1/heroes/complete', setEncoding: 'utf8', //This is the only line that is new. `headers` is an object with the headers to request headers: {'X-Epic-ApiKey': settings.apikey, 'Accept': "application/json" } }; function callback(error, response, body){ var info2 = JSON.parse(body); var heroname; var use_mana = 0; var passive = 1; var abilinf = []; var herofound = 0; var scaling = []; var cooldown = []; var manacost = []; var basedmg = []; var descrip = "", shortdescrip = ""; var scalestr = "", cdstr = "", manastr = "", basedmgstr = "", silencedurstr = "", movespdstr = "", dmgdurstr = "", durstr = "", splitdmgstr = "", radiusstr = "", stunstr = "", numatkstr = "", maxhealthpctstr = "", stackstr = "", maxhealthstr = "", rootdr = "", slowlongstr = "", healthregstr = "", cdrstr = "", atkspstr = "", manargstr = "", stundrstr = "", bonusdmgstr = "", ultdurstr = "", lifetimestr = "", cooldownstr = "", slowdurationstr = "", airwalkspd = "", airwalkdur = "", markchancestr = "", shieldstr = "", pingintstr = "", warddurstr = "", stackdurstr = "", stackmaxstr = "", stacknumstr = "", healthpsvstr = "", dmgpsvstr = "", rootshrstr = "", slowsecstr = "", countstr = "", raddurstr = "", physarstr = "", rangestr = ""; var atts = {}; for (var heronum = 0; heronum < info2.length; heronum++) { heroname = info2[heronum].name.toLowerCase() if(heroname.includes(hero.toLowerCase())) { herofound = 1; for(var abilnum = 0; abilnum < info2[heronum].abilities.length; abilnum++) { if(info2[heronum].abilities[abilnum].binding.toLowerCase() === skill) { descrip = info2[heronum].abilities[abilnum].description; shortdescrip = info2[heronum].abilities[abilnum].shortDescription; for(var i = 0; i < info2[heronum].abilities[abilnum].modifiersByLevel.length;i++) { abilinf[i] = JSON.stringify(info2[heronum].abilities[abilnum].modifiersByLevel[i],null,"\t"); if(info2[heronum].abilities[abilnum].modifiersByLevel[0].attackratingcoefficient == info2[heronum].abilities[abilnum].modifiersByLevel[1].attackratingcoefficient) scalestr = info2[heronum].abilities[abilnum].modifiersByLevel[i].attackratingcoefficient; else scalestr += info2[heronum].abilities[abilnum].modifiersByLevel[i].attackratingcoefficient; if(info2[heronum].abilities[abilnum].modifiersByLevel[i].cooldown !== undefined){ cdstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].cooldown.toFixed(1); passive = 0;} if(info2[heronum].abilities[abilnum].modifiersByLevel[i].energycost !== undefined){ manastr += -(info2[heronum].abilities[abilnum].modifiersByLevel[i].energycost); use_mana = 1;} basedmgstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].damage; silencedurstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].silencedur; movespdstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].movespeed; dmgdurstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].damageduration; splitdmgstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].splitdamage; durstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].duration; maxhealthstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].maxhealth; radiusstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].radius; stunstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].stun; numatkstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].numattacks; stackstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].stacks; maxhealthpctstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].maxhealthpercent; rootdr += info2[heronum].abilities[abilnum].modifiersByLevel[i].rootduration; slowlongstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].slowlong; healthregstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].healthregen; cdrstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].cdr; atkspstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].attackspeed; manargstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].manaregen; stundrstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].stunduration; bonusdmgstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].bonusdamage; ultdurstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].ultduration; lifetimestr += info2[heronum].abilities[abilnum].modifiersByLevel[i].lifetime; cooldownstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].cooldown; slowdurationstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].slowduration; airwalkspd += info2[heronum].abilities[abilnum].modifiersByLevel[i].airwalkspeedboost; airwalkdur += info2[heronum].abilities[abilnum].modifiersByLevel[i].airwalkduration; markchancestr += info2[heronum].abilities[abilnum].modifiersByLevel[i].markchance; shieldstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].shield; pingintstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].pinginterval; warddurstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].wardduration; stackmaxstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].stacksmax; stackdurstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].stackduration; stacknumstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].stacknumber; healthpsvstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].healthpassive; dmgpsvstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].damagepassive; rootshrstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].rootshort; slowsecstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].slowsecondary; countstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].count; raddurstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].radduration; physarstr += info2[heronum].abilities[abilnum].modifiersByLevel[i].physarmor; rangestr += info2[heronum].abilities[abilnum].modifiersByLevel[i].range; if(i<info2[heronum].abilities[abilnum].modifiersByLevel.length-1) { if(info2[heronum].abilities[abilnum].modifiersByLevel[0].attackratingcoefficient != info2[heronum].abilities[abilnum].modifiersByLevel[1].attackratingcoefficient) scalestr += "/"; pingintstr += "/"; warddurstr += "/"; stackmaxstr += "/"; stackdurstr += "/"; stacknumstr += "/"; cdstr += "/"; manastr += "/"; basedmgstr += "/"; silencedurstr += "/"; movespdstr += "/"; dmgdurstr += "/"; splitdmgstr += "/"; durstr += "/"; maxhealthstr += "/"; radiusstr += "/"; stunstr += "/"; numatkstr += "/"; maxhealthpctstr += "/"; stackstr += "/"; rootdr += "/"; slowlongstr += "/"; healthregstr += "/"; cdrstr += "/"; atkspstr += "/"; manargstr += "/"; stundrstr += "/"; bonusdmgstr += "/"; lifetimestr += "/"; ultdurstr += "/"; cooldownstr += "/"; slowdurationstr += "/"; airwalkspd += "/"; airwalkdur += "/"; markchancestr += "/"; shieldstr += "/"; healthpsvstr += "/"; dmgpsvstr += "/"; rootshrstr += "/"; slowsecstr += "/"; countstr += "/"; raddurstr += "/"; physarstr += "/"; rangestr += "/"; } } if(skill === "lmb") { manastr = 0; abilinf = []; } if(scalestr === undefined) scalestr = "0"; if(passive) cdstr = "Passive"; if(!use_mana) manastr = 0; descrip = descrip.replace(/{damage}/g, basedmgstr); descrip = descrip.replace(/{movespeed}/g, movespdstr); descrip = descrip.replace(/{silencedur}/g, silencedurstr); descrip = descrip.replace(/{splitdamage}/g, splitdmgstr); descrip = descrip.replace(/{damageduration}/g, dmgdurstr); descrip = descrip.replace(/{duration}/g, durstr); descrip = descrip.replace(/{maxhealth}/g, maxhealthstr); descrip = descrip.replace(/{radius}/g, radiusstr); descrip = descrip.replace(/{stun}/g, stunstr); descrip = descrip.replace(/{numattacks}/g, numatkstr); descrip = descrip.replace(/{maxhealthpercent}/g, maxhealthpctstr); descrip = descrip.replace(/{stacks}/g, stackstr); descrip = descrip.replace(/{rootduration}/g, rootdr); descrip = descrip.replace(/{slowlong}/g, slowlongstr); descrip = descrip.replace(/{healthregen}/g, healthregstr); descrip = descrip.replace(/{attackspeed}/g, atkspstr); descrip = descrip.replace(/{cdr}/g, cdrstr); descrip = descrip.replace(/{manaregen}/g, manargstr); descrip = descrip.replace(/{stunduration}/g, stundrstr); descrip = descrip.replace(/{bonusdamage}/g, bonusdmgstr); descrip = descrip.replace(/{ultduration}/g, ultdurstr); descrip = descrip.replace(/{lifetime}/g, lifetimestr); descrip = descrip.replace(/{cooldown}/g, cooldownstr); descrip = descrip.replace(/{slowduration}/g, slowdurationstr); descrip = descrip.replace(/{airwalkspeedboost}/g, airwalkspd); descrip = descrip.replace(/{airwalkduration}/g, airwalkdur); descrip = descrip.replace(/{markchance}/g, markchancestr); descrip = descrip.replace(/{shield}/g, shieldstr); descrip = descrip.replace(/{stackduration}/g, stackdurstr); descrip = descrip.replace(/{stacknumber}/g, stacknumstr); descrip = descrip.replace(/{stacksmax}/g, stackmaxstr); descrip = descrip.replace(/{wardduration}/g, warddurstr); descrip = descrip.replace(/{pinginterval}/g, pingintstr); descrip = descrip.replace(/{healthpassive}/g, healthpsvstr); descrip = descrip.replace(/{damagepassive}/g, dmgpsvstr); descrip = descrip.replace(/{rootshort}/g, rootshrstr); descrip = descrip.replace(/{slowsecondary}/g, slowsecstr); descrip = descrip.replace(/{count}/g, countstr); descrip = descrip.replace(/{radduration}/g, raddurstr); descrip = descrip.replace(/{physarmor}/g, physarstr); descrip = descrip.replace(/{range}/g, rangestr); descrip = descrip.replace(/{attr:endmg}/g, "Ability Damage"); descrip = descrip.replace(/{attr:atkspd}/g, "Attack Speed"); descrip = descrip.replace(/{attr:mp}/g, "Mana"); descrip = descrip.replace(/{attr:hp}/g, "Health"); descrip = descrip.replace(/{attr:enar}/g, "Ability Armor"); descrip = descrip.replace(/{attr:physdmg}/g, "Basic Damage"); descrip = descrip.replace(/{attr:physar}/g, "Basic Armor"); descrip = descrip.replace(/{attr:spd}/g, "Movement Speed"); descrip = descrip.replace(/{attr:hpreg}/g, "Health Regen"); descrip = descrip.replace(/{attr:mpreg}/g, "Mana Regen"); descrip = descrip.replace(/{status:slow}/g, "Slow"); descrip = descrip.replace(/{status:slnc}/g, "Silence"); descrip = descrip.replace(/{status:stun}/g, "Stun"); descrip = descrip.replace(/{status:root}/g, "Root"); descrip = descrip.replace(/{status:bleed}/g, "Bleed"); shortdescrip = shortdescrip.replace(/{damage}/g, basedmgstr); shortdescrip = shortdescrip.replace(/{movespeed}/g, movespdstr); shortdescrip = shortdescrip.replace(/{silencedur}/g, silencedurstr); shortdescrip = shortdescrip.replace(/{splitdamage}/g, splitdmgstr); shortdescrip = shortdescrip.replace(/{damageduration}/g, dmgdurstr); shortdescrip = shortdescrip.replace(/{duration}/g, durstr); shortdescrip = shortdescrip.replace(/{maxhealth}/g, maxhealthstr); shortdescrip = shortdescrip.replace(/{radius}/g, radiusstr); shortdescrip = shortdescrip.replace(/{stun}/g, stunstr); shortdescrip = shortdescrip.replace(/{numattacks}/g, numatkstr); shortdescrip = shortdescrip.replace(/{maxhealthpercent}/g, maxhealthpctstr); shortdescrip = shortdescrip.replace(/{stacks}/g, stackstr); shortdescrip = shortdescrip.replace(/{rootduration}/g, rootdr); shortdescrip = shortdescrip.replace(/{slowlong}/g, slowlongstr); shortdescrip = shortdescrip.replace(/{healthregen}/g, healthregstr); shortdescrip = shortdescrip.replace(/{attackspeed}/g, atkspstr); shortdescrip = shortdescrip.replace(/{cdr}/g, cdrstr); shortdescrip = shortdescrip.replace(/{manaregen}/g, manargstr); shortdescrip = shortdescrip.replace(/{stunduration}/g, stundrstr); shortdescrip = shortdescrip.replace(/{bonusdamage}/g, bonusdmgstr); shortdescrip = shortdescrip.replace(/{ultduration}/g, ultdurstr); shortdescrip = shortdescrip.replace(/{lifetime}/g, lifetimestr); shortdescrip = shortdescrip.replace(/{cooldown}/g, cooldownstr); shortdescrip = shortdescrip.replace(/{slowduration}/g, slowdurationstr); shortdescrip = shortdescrip.replace(/{airwalkspeedboost}/g, airwalkspd); shortdescrip = shortdescrip.replace(/{airwalkduration}/g, airwalkdur); shortdescrip = shortdescrip.replace(/{markchance}/g, markchancestr); shortdescrip = shortdescrip.replace(/{shield}/g, shieldstr); shortdescrip = shortdescrip.replace(/{stackduration}/g, stackdurstr); shortdescrip = shortdescrip.replace(/{stacknumber}/g, stacknumstr); shortdescrip = shortdescrip.replace(/{stacksmax}/g, stackmaxstr); shortdescrip = shortdescrip.replace(/{wardduration}/g, warddurstr); shortdescrip = shortdescrip.replace(/{pinginterval}/g, pingintstr); shortdescrip = shortdescrip.replace(/{healthpassive}/g, healthpsvstr); shortdescrip = shortdescrip.replace(/{damagepassive}/g, dmgpsvstr); shortdescrip = shortdescrip.replace(/{rootshort}/g, rootshrstr); shortdescrip = shortdescrip.replace(/{slowsecondary}/g, slowsecstr); shortdescrip = shortdescrip.replace(/{count}/g, countstr); shortdescrip = shortdescrip.replace(/{radduration}/g, raddurstr); shortdescrip = shortdescrip.replace(/{physarmor}/g, physarstr); shortdescrip = shortdescrip.replace(/{range}/g, rangestr); shortdescrip = shortdescrip.replace(/{attr:endmg}/g, "Ability Damage"); shortdescrip = shortdescrip.replace(/{attr:atkspd}/g, "Attack Speed"); shortdescrip = shortdescrip.replace(/{attr:mp}/g, "Mana"); shortdescrip = shortdescrip.replace(/{attr:hp}/g, "Health"); shortdescrip = shortdescrip.replace(/{attr:enar}/g, "Ability Armor"); shortdescrip = shortdescrip.replace(/{attr:physdmg}/g, "Basic Damage"); shortdescrip = shortdescrip.replace(/{attr:physar}/g, "Basic Armor"); shortdescrip = shortdescrip.replace(/{attr:spd}/g, "Movement Speed"); shortdescrip = shortdescrip.replace(/{attr:hpreg}/g, "Health Regen"); shortdescrip = shortdescrip.replace(/{attr:mpreg}/g, "Mana Regen"); shortdescrip = shortdescrip.replace(/{status:slow}/g, "Slow"); shortdescrip = shortdescrip.replace(/{status:slnc}/g, "Silence"); shortdescrip = shortdescrip.replace(/{status:stun}/g, "Stun"); shortdescrip = shortdescrip.replace(/{status:root}/g, "Root"); shortdescrip = shortdescrip.replace(/{status:bleed}/g, "Bleed"); var image_url = "https:" + info2[heronum].abilities[abilnum].images.icon; message.channel.sendEmbed(createEmbed( "#ffffff", {name: "mmonney31",icon_url:"http://www.pngall.com/wp-content/uploads/2016/05/PayPal-Donate-Button-Download-PNG-180x180.png",url:"https://www.paypal.me/MattMonnie"}, info2[heronum].abilities[abilnum].name, "Description: " + descrip + "\r\n" + "Short Description:" + "\r\n" + shortdescrip + "\r\n" + "Scaling: " + scalestr + "\r\n" + "Cooldown(seconds): " + cdstr + "\r\n" + "Mana Cost: " + manastr + "\r\n" ,null,{text: "Bot built by mmonney31 Want to help the bot? Donations help with server and development costs. Simply click on mmonney31 at top to donate."}, image_url )); } } } } if(!herofound) message.channel.sendMessage("Hero not found"); } request(options,callback); } } module.exports = Ability;
function updateIcon (iconType) { chrome.browserAction.setIcon({path: "icons/" + iconType + "/16.png"}); } function checkUrl () { chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) { var url = tabs[0].url; if (url.indexOf("easybib.com/") > -1) { updateIcon("colored"); } else { updateIcon("transparent"); } }); } //listen for new tab to be activated chrome.tabs.onActivated.addListener(function(activeInfo) { checkUrl(); }); //listen for current tab to be changed chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { checkUrl(); }); /* * http://stackoverflow.com/questions/6222353/chrome-extension-how-do-i-change-my-icon-on-tab-focus * http://stackoverflow.com/questions/6132018/how-can-i-get-the-current-tab-url-for-chrome-extension * https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/docs/examples/api/browserAction/ */
import React from 'react' import { StyleSheet } from 'quantum' const styles = StyleSheet.create({ self: { position: 'absolute', width: 0, height: 0, borderColor: 'transparent', borderStyle: 'solid', }, 'align=bottom': { left: '50%', top: '-5px', marginLeft: '-5px', borderWidth: '0 5px 5px', borderBottomColor: '#546e7a', }, 'align=top': { left: '50%', bottom: '-5px', marginLeft: '-5px', borderWidth: '5px 5px 0 5px', borderTopColor: '#546e7a', }, 'align=right': { top: '50%', left: '-5px', marginTop: '-5px', borderWidth: '5px 5px 5px 0', borderRightColor: '#546e7a', }, 'align=left': { top: '50%', right: '-5px', marginTop: '-5px', borderWidth: '5px 0 5px 5px', borderLeftColor: '#546e7a', }, }) const Pointer = ({ align = 'bottom' }) => ( <div className={styles({ align })} /> ) export default Pointer
/** Copyright (c) 2018 Uber Technologies, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import React from 'react'; import {createPlugin, dangerouslySetHTML} from 'fusion-core'; import {HelmetProvider} from 'react-helmet-async'; import type {FusionPlugin} from 'fusion-core'; const keys = ['meta', 'link', 'style', 'base', 'noscript', 'script']; const plugin = __NODE__ && createPlugin({ middleware: () => { return async (ctx, next) => { if (!ctx.element) { return next(); } const helmetContext = {}; ctx.element = ( <HelmetProvider context={helmetContext}>{ctx.element}</HelmetProvider> ); await next(); const {helmet} = helmetContext; if (helmet) { ctx.template.title = helmet.title .toString() .replace('</title>', '') .replace(/^<title.*>/, ''); keys.forEach(key => { ctx.template.head.push(dangerouslySetHTML(helmet[key].toString())); }); } }; }, }); export default ((plugin: any): FusionPlugin<void, void>);
const mongoose = require('mongoose'); const itemSchema = new mongoose.Schema({ userId: { type: String, required: true, index: true }, category: { type: mongoose.Types.ObjectId, ref: 'categories' }, name: { type: String, required: true }, amount: { type: Number, required: true, index: true }, isDeleted: { type: Boolean, default: false }, date: { type: Date, default: Date.now() } }, { timestamps: true } ); itemSchema.index({ category: 1, isDeleted: 1, }); module.exports = mongoose.model('items', itemSchema);
import Description from './Description'; import { useEffect, useState } from 'preact/hooks'; import classNames from 'classnames'; export function ToggleSwitch(props) { const { id, label, onInput, value, switcherLabel, inline, onFocus, onBlur, inputRef } = props; const [ localValue, setLocalValue ] = useState(value); const handleInputCallback = async () => { onInput(!value); }; const handleInput = e => { handleInputCallback(e); setLocalValue(e.target.value); }; useEffect(() => { if (value === localValue) { return; } setLocalValue(value); }, [ value ]); return ( <div class={ classNames( 'bio-properties-panel-toggle-switch', { inline } ) }> <label class="bio-properties-panel-label" for={ prefixId(id) }> { label } </label> <div class="bio-properties-panel-field-wrapper"> <label class="bio-properties-panel-toggle-switch__switcher"> <input ref={ inputRef } id={ prefixId(id) } class="bio-properties-panel-input" type="checkbox" onFocus={ onFocus } onBlur={ onBlur } name={ id } onInput={ handleInput } checked={ !!localValue } /> <span class="bio-properties-panel-toggle-switch__slider" /> </label> { switcherLabel && <p class="bio-properties-panel-toggle-switch__label">{ switcherLabel }</p> } </div> </div> ); } /** * @param {Object} props * @param {Object} props.element * @param {String} props.id * @param {String} props.description * @param {String} props.label * @param {String} props.switcherLabel * @param {Boolean} props.inline * @param {Function} props.getValue * @param {Function} props.setValue * @param {Function} props.onFocus * @param {Function} props.onBlur */ export default function ToggleSwitchEntry(props) { const { element, id, description, label, switcherLabel, inline, getValue, setValue, onFocus, onBlur } = props; const value = getValue(element); return ( <div class="bio-properties-panel-entry bio-properties-panel-toggle-switch-entry" data-entry-id={ id }> <ToggleSwitch id={ id } label={ label } value={ value } onInput={ setValue } onFocus={ onFocus } onBlur={ onBlur } switcherLabel={ switcherLabel } inline={ inline } /> <Description forId={ id } element={ element } value={ description } /> </div> ); } export function isEdited(node) { return node && !!node.checked; } // helpers ///////////////// function prefixId(id) { return `bio-properties-panel-${ id }`; }
$(document).ready(function () { $('.i-check').iCheck({ checkboxClass: 'icheckbox_quacol', radioClass: 'iradio_quacol', //increaseArea: '20%' // optional }); $('.lk-comments-views-rating .rating select').each(function () { $(this).barrating({ theme: 'small-white-stars', initialRating: $(this).data('current-rating'), readonly: true, allowEmpty: true, emptyValue: 0, }); }); $('#publication-rating-select').change(function () { $.post('/local/assets/json/post-rating.json', { rating : $(this).val(), id : $(this).data('publication-id'), }, function () { }); }).barrating({ theme: 'fa-stars', initialRating: $('#publication-rating-select').data('current-rating'), allowEmpty: true, emptyValue: 0, }); $('#publication-subscribe-topic').on('ifChanged', function (event) { $.post('/local/assets/json/get-one.json', { action : $(event.target).is(':checked') ? 'subscribe' : 'unsubscribe', topic_id : $(event.target).data('topic-id') }).done(function (data) { if (!data) {$(event.target).iCheck('uncheck');} }).fail(function(xhr, status, error) { $(event.target).iCheck('uncheck'); }); }); $('#publication-subscribe-author').on('ifChanged', function (event) { $.post('/local/assets/json/get-one.json', { action : $(event.target).is(':checked') ? 'subscribe' : 'unsubscribe', topic_id : $(event.target).data('author-id') }).done(function (data) { if (!data) {$(event.target).iCheck('uncheck');} }).fail(function(xhr, status, error) { $(event.target).iCheck('uncheck'); }); }); $('.endoexpert-poll').flip({ trigger: 'manual' }).each(function () { $(this).find('.poll-results').height($(this).find('.poll-question').height()) }); $('.flip-toggle').click(function (e) { $('.endoexpert-poll').flip('toggle'); e.preventDefault(); return false; }); $('#invite-friends-button').click(function () { $.magnificPopup.open({ items: { src: '#invite-friends-popup' }, modal: true, type: 'inline', tClose: 'Закрыть (Esc)', tLoading: 'Загрузка...', callbacks: { open: initInviteFiendsApp(function () { $.ajax({ url: '/local/assets/json/get-one.json', type: 'post', data: {topic_id: inviteFriendsApp.topic_id, friends : inviteFriendsApp.selected_items}, cache: false, success: function(){ $.magnificPopup.close(); $.magnificPopup.open({ items: { src: '#invite-friends-popup-success' }, type: 'inline', tClose: 'Закрыть (Esc)', tLoading: 'Загрузка...', }); }, error: function(){ alert('error!'); } }); }), close: destroyInviteFiendsApp } }); }); });
import { StyleSheet } from 'react-native' export default StyleSheet.create({ container: { flex: 1 }, headerView:{ height: 50, marginRight:15, backgroundColor: '#282727', alignSelf: 'flex-end', borderRadius: 5, alignItems: 'center', flexDirection: 'row' }, dateText:{ marginLeft:13, marginRight:5, alignItems:'center', flexDirection:'column' },text:{ color: '#fff', fontFamily:'Lato-Regular' } })
export const SET_ARTIST = 'SET_ARTIST' export const SET_FULLSCREEN = 'SET_FULLSCREEN' export const SET_PLAYING = 'SET_PLAYING' export const SET_PLAY_LIST = 'SET_PLAY_LIST' export const SET_SEQUENCE_LIST = 'SET_SEQUENCE_LIST' export const SET_CURRENT_INDEX = 'SET_CURRENT_INDEX' export const SET_PLAY_MODE = 'SET_PLAY_MODE' export const SET_CURRENT_MUSIC_URL = 'SET_CURRENT_MUSIC_URL' export const SET_FAVOURITE_LIST = 'SET_FAVOURITE_LIST' export const SET_RANK = 'SET_RANK' export const SET_TRACK_LIST = 'SET_TRACK_LIST'
import Sequelize from 'sequelize'; import db from '../../../config/db'; import bcrypt from 'bcrypt'; import moment from 'moment'; const User = db.define('users', { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, barcode: Sequelize.STRING, fname: Sequelize.STRING, mname: Sequelize.STRING, lname: Sequelize.STRING, username: Sequelize.STRING, password: Sequelize.STRING, apiToken: Sequelize.STRING, level: Sequelize.STRING, areaId: Sequelize.INTEGER, createdAt: Sequelize.DATE, updatedAt: Sequelize.DATE }, { timestamps: false }); //instance function for comparing password User.prototype.comparePassword = function(password, done) { const user = this; bcrypt.compare(password, this.password) .then(res => { return done(null, res) }) .catch(error => { db.Promise.reject(error); }) }; //convert password to hash before saving it User.beforeCreate((user, options) => { return bcrypt.hash(user.password, 10).then(hash => { user.password = hash; }).catch(error => { db.Promise.reject(new Error('Failed to hash user password!')); }); }); export default User;
$(function () { $('#brand').on('click', function () { gtag('event', 'brand-click'); console.log('brand'); }); $('#description').on('click', function () { gtag('event', 'description-click'); console.log('description'); }); $('#flyer').on('click', function () { gtag('event', 'flyer-click'); console.log('flyer'); }); $('.apple-badge-link').on('click', function () { gtag('event', 'apple-badge-click'); console.log('apple'); $('.subscribe-modal').modal(); }); $('.google-badge-link').on('click', function () { gtag('event', 'google-badge-click'); console.log('google'); $('.subscribe-modal').modal(); }); $('#mc-embedded-subscribe').on('click', function () { gtag('event', 'submit-click'); console.log('submit'); }); $('#twitter-link').on('click', function () { gtag('event', 'twitter-click'); console.log('twitter'); }); $('#instagram-link').on('click', function () { gtag('event', 'instagram-click'); console.log('instagram'); }); });
import React, { useEffect, useState } from "react"; import StoreLayout from "../../components/StoreLayout/StoreLayout"; import client from '../../components/ApolloClient'; import AddToCartButton from '../../components/cart/AddToCartButton'; import PRODUCT_BY_SLUG_QUERY from '../../queries/product-by-slug'; import clientConfig from '../../client-config'; import { isEmpty } from 'lodash'; import { Card, Grid, Header, Image, Label } from "semantic-ui-react"; import PostsContent from "../../components/PostsContent"; import Product from "../../components/Product"; import AddToCart from "../../components/cart/AddToCartButton"; import Link from "next/link"; import { stringToNumber } from "../../functions"; import Listattrsbook from "../../components/Book/ListAttrsBook"; const Book = (props) => { const { product } = props; const [desc, setDesc] = useState(null); // const router = useRouter() // const { slug } = router.query useEffect(() => { console.log(product); }, []); return ( <StoreLayout> {product ? ( <> <Grid.Row columns={2} centered> <Grid.Column> <Header as='h1'>{product.name}</Header> <Listattrsbook product={product} /> <div dangerouslySetInnerHTML={{ __html: product.description, }} className="card-text" /> <div dangerouslySetInnerHTML={{ __html: desc, }} className="card-text" /> <AddToCartButton product={product} /> </Grid.Column> <Grid.Column centered> {!isEmpty(product.image) ? ( <Image src={product.image.sourceUrl} alt="Product Image" size='large' srcSet={product.image.srcSet} /> ) : !isEmpty(clientConfig.singleImagePlaceholder) ? ( <Image src={clientConfig.singleImagePlaceholder} alt="Placeholder product image" /> ) : null} </Grid.Column> </Grid.Row> <Grid.Row centered> <Header as='h2' block color='grey'> {`از دیگر انتشارات`} </Header> </Grid.Row> <Grid.Row centered> {product.related.nodes.length ? ( product.related.nodes.map(pr => { if (pr.type !== 'SIMPLE') { // if (!desc) setDesc(pr.description); return false; }; return ( <Grid.Column mobile={16} tablet={8} computer={4} > <Link as={`/book/${pr.slug}`} href={`/book/[slug]`} > <Card as='a' fluid> <Card.Content> {!isEmpty(pr.image) ? ( <Image floated="right" src={pr.image.sourceUrl} size="tiny" /> ) : ''} <Card.Header as="h2" style={{ marginBottom: "10px" }}>{pr.name}</Card.Header> <AttributesRender label={`نشر`} attrs={pr.paPublishers.nodes} /> <AttributesRender label={`نویسنده`} attrs={pr.paWriters.nodes} /> <AttributesRender label={`مترجم`} attrs={pr.paTranslators.nodes} /> </Card.Content> <Card.Content extra textAlign="center"> <Label.Group tag> <AddToCart product={pr} /> <Label color="red">{stringToNumber(pr.price)}</Label> <Label style={{ textDecoration: "line-through" }}>{stringToNumber(pr.regularPrice)}</Label> </Label.Group> </Card.Content> </Card> </Link> </Grid.Column> ); }) ) : ('')} </Grid.Row> </> ) : ( '' )} </StoreLayout> ); }; export const getServerSideProps = async (context) => { let { query: { slug } } = context const id = slug ? slug : context.query.id; const result = await client.query({ query: PRODUCT_BY_SLUG_QUERY, variables: { id } }) return { props: { product: result.data.product, revalidate: 1, }, }; } function AttributesRender({ attrs, label }) { return ( <Card.Meta style={{ marginTop: "2px" }}> <Label key={label}> {`${label}:`} {attrs.map(attr => ( < Label.Detail key={attr.databaseId}> { attr.name} </Label.Detail> )) } </Label > </Card.Meta> ) } export default Book;
"use strict"; exports.__id = "shell/ui"; var mods = [ "shellfish/low", "shellfish/mid", "shellfish/high" ]; require(mods, function (low, mid, high) { function showInfo(title, msg, callback) { var dlg = high.element(mid.Dialog); dlg .onClosed(dlg.discard) .title(title) .add( high.element(mid.Label).text(msg) ) .button( high.element(mid.Button).text("Ok") .action(function () { dlg.close_(); if (callback) { callback(); } }) ); dlg.show_(); } exports.showInfo = showInfo; function showError(msg, callback) { var dlg = high.element(mid.Dialog); dlg .onClosed(dlg.discard) .title("Error") .add( high.element(mid.Label).text(msg) ) .button( high.element(mid.Button).text("Ok") .action(function () { dlg.close_(); if (callback) { callback(); } }) ); dlg.show_(); } exports.showError = showError; function showQuestion(title, msg, yesCb, noCb) { var dlg = high.element(mid.Dialog); dlg .onClosed(dlg.discard) .title(title) .add( high.element(mid.Label).text(msg) ) .button( high.element(mid.Button).text("Yes").action(function () { dlg.close_(); yesCb(); }).isDefault(true) ) .button( high.element(mid.Button).text("No").action(function () { dlg.close_(); noCb(); }) ); dlg.show_(); } exports.showQuestion = showQuestion; function StatusBox() { var that = this; var m_box = $( low.tag("footer").class("sh-dropshadow") /* .style("position", "fixed") .style("bottom", "0") .style("left", "0") .style("right", "0") */ .style("height", "auto") .style("text-align", "left") //.style("border", "solid 1px var(--color-border)") //.style("background-color", "var(--color-primary-background)") .html() ); this.get = function () { return m_box; }; this.push = function (item) { m_box.append(item.get()); }; } exports.StatusBox = StatusBox; function StatusItem() { Object.defineProperties(this, { left: { set: addLeft, get: left, enumerable: true }, right: { set: addRight, get: right, enumerable: true }, icon: { set: setIcon, get: icon, enumerable: true }, text: { set: setText, get: text, enumerable: true }, progress: { set: setProgress, get: progress, enumerable: true }, onClicked: { set: setOnClicked, get: onClicked, enumerable: true } }); var m_left = []; var m_right = []; var m_icon = ""; var m_text = ""; var m_progress = 0; var m_onClicked = null; var m_item = $( low.tag("div") .style("position", "relative") .style("border-top", "solid 1px var(--color-border)") .content( // box low.tag("div") .style("position", "relative") .style("display", "flex") .style("align-items", "center") .style("width", "100%") .content( // progress bar low.tag("div") .style("position", "absolute") .style("background-color", "var(--color-highlight-background)") .style("top", "0") .style("left", "0") .style("width", "0%") .style("height", "100%") ) .content( // left content area low.tag("div") .style("position", "relative") ) .content( // text low.tag("h1") .style("position", "relative") .style("flex-grow", "1") .style("line-height", "100%") .content( low.tag("span").class("sh-fw-icon") ) .content( low.tag("span") ) ) .content( // right content area low.tag("div") .style("position", "relative") ) ) .content( // custom content area low.tag("div") ) .html() ); m_item.on("click", function () { if (m_onClicked) { m_onClicked(); } }) function addLeft(child) { m_item.find("> div:nth-child(1) > div:nth-child(2)").append(child.get()); m_left.push(child); } function left() { return m_left; } function addRight(child) { m_item.find("> div:nth-child(1) > div:nth-child(4)").append(child.get()); m_right.push(child); } function right() { return m_right; } function setIcon(icon) { m_item.find("h1 > span").first().removeClass(m_icon).addClass(icon); m_icon = icon; } function icon() { return m_icon; } function setText(text) { m_item.find("h1 > span").last().html(low.escapeHtml(text)); m_text = text; } function text() { return m_text; } function setProgress(progress) { m_item.find("> div:nth-child(1) > div:nth-child(1)").css("width", progress + "%"); m_progress = progress; } function progress() { return m_progress; } function setOnClicked(callback) { m_onClicked = callback; } function onClicked() { return m_onClicked; } this.get = function () { return m_item; }; this.add = function (child) { m_item.find("> div:nth-child(2)").append(child.get()); }; } exports.StatusItem = StatusItem; });
angular.module('DemoApp.directives', []).directive('pageType', function($state,viewAllUsers,deleteUserService) { return { restrict: "E", scope: {}, templateUrl:'static/directiveViews/paginationcontent.html', controller: function($scope) { $scope.filteredTodos = [] ,$scope.currentPage = 1 ,$scope.numPerPage = 5 ,$scope.maxSize = 5; $scope.OnSave=function(todo){ //alert("I am update button"+todo.id); $state.go('home',{data:todo}); }; $scope.onDelete=function(todo){ var User=new Object(); User.id=todo.id; User.firstname=todo.firstname; User.lastname=todo.lastname; User.country=todo.country; User.email=todo.email; User.phone=todo.phone; User.gender=todo.gender; deleteUserService.removeUser(User).then(function(result){ $scope.todos=result.data; //alert("Directive data:"+JSON.stringify($scope.todos)+"Length: "+$scope.todos.length); $scope.$watch('currentPage + numPerPage', function() { var begin = (($scope.currentPage - 1) * $scope.numPerPage) , end = begin + $scope.numPerPage; $scope.filteredTodos = $scope.todos.slice(begin, end); // alert("Begin: "+begin+"End: "+end+"todos data: "+JSON.stringify($scope.filteredTodos)); }); }); }; $scope.todos=[]; viewAllUsers.getUsersList().then(function(result){ $scope.todos=result.data; //alert("Directive data:"+JSON.stringify($scope.todos)+"Length: "+$scope.todos.length); $scope.$watch('currentPage + numPerPage', function() { var begin = (($scope.currentPage - 1) * $scope.numPerPage) , end = begin + $scope.numPerPage; $scope.filteredTodos = $scope.todos.slice(begin, end); // alert("Begin: "+begin+"End: "+end+"todos data: "+JSON.stringify($scope.filteredTodos)); }); }); } }; });
export default function reducer(state = { startPointAddress:'', endPointAddress:'', choiceOptions:[{ 'text': "Time", 'value': "Time" }, { 'text': "Cost", 'value': "Cost" }, { 'text': "Comfort", 'value': "Comfort" }], selectedOption:[], mapCenter:{ lat: 28.689265, lng: 77.27813 }, startAndEndAddressPoint:[{ lat: 18.56564, lng: 73.76968 },{ lat: 18.56564, lng: 73.76968 }], showHideDetails:false, number:0, totalCost:0, }, action) { switch (action.type) { case "START_POINT_ADDRESS_CHANGED": { return { ...state, startPointAddress: action.payload, mapCenter:action.payload } } case "END_POINT_ADDRESS_CHANGED": { return { ...state, endPointAddress: action.payload, mapCenter:action.payload } } case "CHOICE_CHANGED": { return { ...state, selectedOption: action.payload } } case "SHOW_HIDE_ROUTE_DETAILS":{ return {...state, showHideDetails:!state.showHideDetails} } case "NUMBER_CHANGED":{ return {...state, number:action.payload} } case "TOTAL_COST_NUM":{ return{ ...state, totalCost:action.payload } } default: { return { ...state } } } }
import styled from "styled-components/macro"; export const Container = styled.div` width: 40%; height: 600px; display: flex; flex-direction: column; align-items: center; justify-content: center; border: 6px solid #fff; border-radius: 5px; @media (max-width: 1190px) { width: 100%; } `; export const Form = styled.form` width: 60%; display: flex; flex-direction: column; gap: 10px; `; export const ButtonContainer = styled.div` display: flex; flex-direction: row; justify-content: center; gap: 10px; `; export const Title = styled.h2` font-weight: bold; `; export const SubTitle = styled.h4` font-weight: 100; `; export const ErrorMessage = styled.p` color: #e72749; font-weight: bold; `;
function mergeEm(left, right) { // initialize new array to hold sorted order let combinedArray = []; let combinedIndex = 0; let leftIndex = 0; let rightIndex = 0; // loop through each, if left is greater than or equal to right add value to new, otherwise add right to new while (leftIndex < left.length && rightIndex < right.length) { if (left[leftIndex] <= right[rightIndex]) { combinedArray[combinedIndex] = left[leftIndex]; leftIndex++; combinedIndex++; } else if (right[rightIndex] < left[leftIndex]) { combinedArray[combinedIndex] = right[rightIndex]; rightIndex++; combinedIndex++; } } if (leftIndex < left.length) { for (let i = leftIndex; i < left.length; i++) { combinedArray.push(left[i]); } } if (rightIndex < right.length) { for (let i = rightIndex; i < right.length; i++) { combinedArray.push(right[i]); } } return combinedArray; } function msort(array) { //base case if (array.length <= 1) { return array; } // split array in 2 let middle = Math.floor(array.length / 2); // pass left side to msort let left = array.slice(0, middle); left = msort(left); // pass right side to msort let right = array.slice(middle, array.length); right = msort(right); // merge sides array = mergeEm(left, right); return array; } class _Node { constructor(value, next) { this.value = value; this.next = next; } } class LinkedList { constructor() { this.head = null; } insertFirst(item) { this.head = new _Node(item, this.head); } insertLast(item) { //if no items, insert as first item if (this.head === null) { this.insertFirst(item); } else { //move through the list until you hit a node that points to null, signifying last node let tempNode = this.head; while (tempNode.next !== null) { tempNode = tempNode.next; } //the last node will now point to the new node tempNode.next = new _Node(item, null); } } insertBefore(item, keyVal) { //start at list head let currNode = this.head; // if no head, then list is empty if (!currNode) { return null; } //if the node containing the key value is the head, just insert first if (currNode.value === keyVal) { this.insertFirst(item); return; } //find the node with the keyValue, once it is the next while ((currNode.next.value !== keyVal) & (currNode.next.next !== null)) { currNode = currNode.next; } if (currNode.next.value === keyVal) { let tempNode = new _Node(item, currNode.next); currNode.next = tempNode; } else { console.log('item to insert before not found'); return; } } insertAfter(item, keyVal) { //start at list head let currNode = this.head; // if no head, then list is empty if (!currNode) { return null; } //find the node with the keyValue, once it is the next while ((currNode.value !== keyVal) & (currNode.next !== null)) { currNode = currNode.next; } //if the node to insert after is the last node, just insert last if (currNode.value === keyVal && currNode.next === null) { this.insertLast(item); return; } if (currNode.value === keyVal) { let tempNode = new _Node(item, currNode.next); currNode.next = tempNode; } else { console.log('item to insert before not found'); return; } } insertAt(index, item) { //NOTE - this function assumes 0 indexing of the list. Therefore, if you pass in the number 1 with your item to add, it will be stored in the SECOND position. Passing in 0 will store a value in the FIRST position. if (!this.head) { console.log('list is empty, nothing to insert before'); return; } // if index is 0, just insert first if (index === 0) { this.insertFirst(item); return; } //else, move through list, iterating a count variable. When count === index, take current Node value and use for insertBefore let count = 0; //start at head let currNode = this.head; while (count !== index && currNode.next !== null) { currNode = currNode.next; count++; } if (count === index) { this.insertBefore(item, currNode.value); return; } else { console.log('this index does not exist'); return; } } find(item) { //start at list head let currNode = this.head; // if no head, then list is empty if (!this.head) { return null; } //check the value of current node for the item while (currNode.value !== item) { // return null if reach end without finding item if (currNode.next === null) { return null; } else { //move to next node currNode = currNode.next; } } //sweet, found it return currNode; } remove(item) { // if list is empty return null if (!this.head) { return null; } // if node to remove its head, make next node the new head if (this.head.value === item) { this.head = this.head.next; return; } // start at the head otherwise let currNode = this.head; //keep track of previous node to re-route next value once on correct node to delete let previousNode = this.head; // find right node while (currNode !== null && currNode.value !== item) { previousNode = currNode; currNode = currNode.next; } // if currNode is null you hit the end of the list if (currNode === null) { console.log('item not found'); } else { //otherwise, set the previous node to point to the next node, dropping out the node to delete previousNode.next = currNode.next; } } } function main() { let SLL = new LinkedList(); let insertion = [1, 7, 3, 5, 17]; insertion.map((item) => SLL.insertLast(item)); return SLL; } console.dir(main(), { depth: null });
/** * Return an array of constructor function names based on the prototype chain * * @param {object} source Source input * @param {string[]} acc Accumulator array * * @returns {string[]} * * @tag Core * @signature (source: Object, acc: string[]): string[] */ const protoChain = (source, acc = []) => { const proto = Object.getPrototypeOf(source) return proto ? protoChain(proto, [...acc, proto.constructor.name]) : acc } export { protoChain }
/** * Essa função verifica a situação * do protudo baseado pela suua quantidade * @param {*} row * @returns */ export default function situacao(row) { if (row >= 0 && row <= 20) { return 'Crítico'; } else if (row >= 21 && row <= 50) { return 'Alerta'; } else { return 'Ok'; } }
import serverApp from './app'; serverApp.listen(3333);
import {PageViewElement} from './page-view-element.js'; import {connect} from 'pwa-helpers/connect-mixin.js'; import {ItemDetailTemplate} from './templates/tpl_item-detail'; import './item-offline.js'; import './item-image.js'; // This element is connected to the redux store. import {store} from '../store.js'; import {fetchItem} from '../actions/item.js'; import {item, itemSelector} from '../reducers/item.js'; // We are lazy loading its reducer. store.addReducers({ item, }); class ItemDetail extends connect(store)(PageViewElement) { _render({_item, _lastVisitedListPage, _showOffline}) { // Don't render if there is no item. if (!_item) { return; } return ItemDetailTemplate(_item,_lastVisitedListPage, _showOffline); } static get properties() { return { _item: Object, _lastVisitedListPage: Boolean, _showOffline: Boolean } } // This is called every time something is updated in the store. _stateChanged(state) { this._item = itemSelector(state); this._lastVisitedListPage = state.app.lastVisitedListPage; this._showOffline = state.app.offline && state.item.failure; } } window.customElements.define('item-detail', ItemDetail); export {fetchItem};
const assert = require('chai').assert; const q = require('../index'); describe('queryfy', function() { const params = { param1: 'This is param1', param2: 'This is param2', }; const path = 'https://something.com/'; it('params', function() { assert.equal( q.queryfy(params), 'param1=This%20is%20param1&param2=This%20is%20param2' ); }); it('path with params', function() { assert.equal( q.queryfy(path, params), 'https://something.com/?param1=This%20is%20param1&param2=This%20is%20param2' ); }); }); describe('deQueryfy', function() { const path = 'https://something.com/?param1=This%20is%20param1&param2=This%20is%20param2'; const query = 'param1=This%20is%20param1&param2=This%20is%20param2'; it('params from path string', function() { assert.deepEqual(q.deQueryfy(path), { param1: 'This is param1', param2: 'This is param2', }); }); it('params from query string with ?', function() { assert.deepEqual(q.deQueryfy('?' + query), { param1: 'This is param1', param2: 'This is param2', }); }); it('params from query string only with ?', function() { assert.deepEqual(q.deQueryfy('?'), {}); }); it('params from query string without ?', function() { assert.deepEqual(q.deQueryfy(query), { param1: 'This is param1', param2: 'This is param2', }); }); });
/* LEARN YOU THE NODE.JS FOR MUCH WIN! ───────────────────────────────────── HTTP FILE SERVER Exercise 11 of 13 Write an HTTP server that serves the same text file for each request it receives. Your server should listen on the port provided by the first argument to your program. You will be provided with the location of the file to serve as the second command-line argument. You must use the fs.createReadStream() method to stream the file contents to the response. */ var http = require('http') var fs = require('fs') var file = process.argv[process.argv.length - 1]; var server = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); var src = fs.createReadStream(file); src.pipe(res); }) var port = process.argv[process.argv.length - 2]; server.listen(port)
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider, useSelector, useDispatch } from "react-redux"; import reactStore from 'react-store'; import reactTheme from 'react-theme'; import { ThemeProvider, makeStyles, StylesProvider, createGenerateClassName } from '@material-ui/core/styles'; import { Paper, TextField, Fab } from '@material-ui/core'; import InputLabel from '@material-ui/core/InputLabel'; import FormControl from '@material-ui/core/FormControl'; import Select from '@material-ui/core/Select'; import SaveIcon from '@material-ui/icons/Save'; const useState = React.useState; const useEffect = React.useEffect; const generateClassName = createGenerateClassName({ productionPrefix: 'md2', }); const useStyles = makeStyles({ editField: { marginBottom: '1rem', textAlign: 'right', }, editContainer: { padding: '1rem', }, editSelect: { marginRight: '1rem', minWidth: 120, } }); const SimpleEdit = () => { const items = useSelector(state => state.items); const currentItem = useSelector(state => state.currentItem); const dispatch = useDispatch(); const classes = useStyles(); const [hasItem, setHasItem] = useState(false); const [title, setTitle] = useState(''); const [description, setDescription] = useState(''); const [priority, setPriority] = useState(2); useEffect(() => { const itemForEdit = items.find(item => item.id == currentItem); if (itemForEdit) { setHasItem(true); setTitle(itemForEdit.title); setDescription(itemForEdit.description); setPriority(itemForEdit.priority); } }, [currentItem, items]) const handleSave = () => { const itemForEdit = items.find(item => item.id == currentItem); if (itemForEdit) { itemForEdit.title = title; itemForEdit.description = description; itemForEdit.priority = priority; dispatch({ type: 'SET_ITEMS', payload: items }) } } return ( <Paper className={classes.editContainer}> <div className={classes.editField}><TextField disabled={!hasItem ? 'disabled' : ''} value={title} onChange={(evt) => setTitle(evt.target.value)} fullWidth label="Title" variant="filled" /></div> <div className={classes.editField}><TextField disabled={!hasItem ? 'disabled' : ''} value={description} onChange={(evt) => setDescription(evt.target.value)} multiline fullWidth rows="6" label="Description" variant="filled" /></div> <div className={classes.editField}> <FormControl disabled={!hasItem ? 'disabled' : ''} variant="filled" className={classes.editSelect}> <InputLabel id="demo-simple-select-filled-label">Priority</InputLabel> <Select labelId="demo-simple-select-filled-label" id="demo-simple-select-filled" value={priority} onChange={(evt) => setPriority(evt.target.value)} native > <option value={1}>highest</option> <option value={2}>high</option> <option value={3}>normal</option> <option value={4}>low</option> </Select> </FormControl> <Fab disabled={!hasItem ? 'disabled' : ''} onClick={handleSave} size="small" color="secondary"><SaveIcon /></Fab> </div> </Paper> ) } const App = () => { return ( <Provider store={reactStore}><StylesProvider generateClassName={generateClassName}><ThemeProvider theme={reactTheme}><SimpleEdit></SimpleEdit></ThemeProvider></StylesProvider></Provider> ) } export default (el) => { const app = App(); ReactDOM.render(app, el); return app; };
/* eslint-disable max-lines-per-function */ import { REQUEST_CURRENCY, RECEIVE_CURRENCY, ADD_EXPENSE, DELETE_EXPENSE, EDIT_EXPENSE, EDITED_EXPENSE, RENDER_EXPENSE_FORM, } from '../actions'; const INITIAL_STATE = { currencies: [], expenses: [], methods: ['Dinheiro', 'Cartão de crédito', 'Cartão de débito'], tags: ['Alimentação', 'Lazer', 'Trabalho', 'Transporte', 'Saúde'], editMode: false, editID: '', shouldExpenseFormRender: false, }; const walletReducer = (state = INITIAL_STATE, action) => { switch (action.type) { case REQUEST_CURRENCY: return { ...state, loading: true }; case RECEIVE_CURRENCY: return { ...state, currencies: action.payload, loading: false, }; case ADD_EXPENSE: return { ...state, expenses: [...state.expenses, action.payload], shouldExpenseFormRender: false, }; case DELETE_EXPENSE: return { ...state, expenses: state.expenses.filter(({ id }) => id !== action.payload), }; case EDIT_EXPENSE: return { ...state, editMode: true, shouldExpenseFormRender: true, editID: action.payload, }; case EDITED_EXPENSE: { const oldExpenseIndex = state.expenses .indexOf(state.expenses.find(({ id }) => state.editID === id)); state.expenses[oldExpenseIndex] = action.payload; return { ...state, expenses: [ ...state.expenses, ], editID: '', editMode: false, shouldExpenseFormRender: false, }; } case RENDER_EXPENSE_FORM: return { ...state, shouldExpenseFormRender: action.payload, }; default: return state; } }; export default walletReducer;
// Created by zr8732@126.com on 2014/10/7. module.exports = function(grunt){ //项目配置 grunt.initConfig({ pkg:grunt.file.readJSON('package.json'), path:{ src:"dev", dist:"build" }, clean:{ build:{ src:[ '<%= path.dist%>/' ] } }, less:{ build:{ files:[ { src:['<%= path.src%>/less/base.less'], dest:'<%= path.dist%>/css/base.css' }, { src:['<%= path.src%>/less/layout.less'], dest:'<%= path.dist%>/css/layout.css' } ] } }, concat:{ js:{ files:[{ src:['<%= path.src%>/js/a.js', '<%= path.src%>/js/b.js' ], dest:'<%= path.dist%>/js/base.debug.js' }] }, css:{ files:[ { src:[ '<%= path.dist%>/css/base.css', '<%= path.dist%>/css/layout.css' ], dest:'<%= path.dist%>/css/all.debug.css' } ] } }, cssmin:{ build:{ expand:true, cwd:'<%= path.dist%>/css/', src:['*.debug.css','!.min.css'], dest:'<%= path.dist%>/css/', ext:'.min.css' } }, uglify:{ build:{ files:[ { expand: true, cwd:'<%= path.dist%>/js/', src:'*.debug.js', dest:'<%= path.dist%>/js/', ext:'.min.js' } ] } }, copy:{ main:{ files:[ { expand:true, cwd:'<%= path.src%>/img/', src:'**', dest:'<%= path.dist%>/img/' } ] } }, watch:{ css:{ files:['<%= path.src%>/less/*.less'], tasks:['less','concat:css','cssmin'] }, js:{ files:['<%= path.src%>/js/*.js'], tasks:['concat:js','uglify'] } } }); //加载任务插件 // grunt.loadNpmTasks('grunt-contrib-clean'); //grunt.loadNpmTasks('grunt-contrib-less'); require('load-grunt-tasks')(grunt); //执行的命令 grunt.registerTask('build:less',['less']); grunt.registerTask('build:css',['concat:css']); grunt.registerTask('build:cssmin',['cssmin']); grunt.registerTask('build:js',['concat:js','uglify']); grunt.registerTask('build:copy',['copy']); grunt.registerTask('default',['clean','build:less','build:css','build:cssmin','build:js','copy']); grunt.registerTask('dev','watch'); };
const jwt = require('jsonwebtoken'); const config = require('../config'); const response = require('../util/response'); const RoomModel = require('../models/RoomModel.js'); const PlayerModel = require('../models/PlayerModel.js'); const GameModel = require('../models/GameModel.js'); const createRoomValidator = require('./validators/CreateRoomValidator'); const { playerInRoom, playerExists } = require('./validators/player'); const playerNotFoundResponse = response({}, 'Player not found', { player: 'Not found' }); module.exports = { create(req, res) { const { name, password } = req.body; const validator = createRoomValidator.validate({ name, password }); const { id: _id } = req.player; if (!validator.valid) { res.send(response({}, 'Invalid', validator.errors)); } PlayerModel.findOne({ _id }, '-__v -token') .then(createdBy => { if (!createdBy) { res.status(400); res.send(playerNotFoundResponse); } const room = new RoomModel({ name, password, createdBy, players: [createdBy], }); room.save() .then(room => { res.status(200); res.send(response({ room }, 'Room created')); }) .catch(error => { res.status(500); res.send(response({}, 'Room created', error)); }); }); }, join(req, res) { const { id: roomId } = req.params; const { id: playerId } = req.player; const { password, game } = req.body; const promises = [ GameModel.findOne({ name: game }, '_id'), RoomModel.findOne({ _id: roomId }, '_id password name') .populate('players'), playerExists(playerId, '_id'), ]; Promise.all(promises).then(result => { const [game, room, player] = result; if (!room) { res.status(404); res.send(response({}, 'Room not found', { room: 'Not found' })); } else if (room.password && !password) { res.status(400); res.send(response({}, 'We need the password', { password: 'Password is requiered' })); } else if (room.password !== password) { res.status(403); res.send(response({}, 'Not valid password', { password: 'Not valid password' })); } else if (!player) { res.status(400); res.send(playerNotFoundResponse); } else if (!game) { res.status(404); res.send(response({}, 'Game not found', { game: 'Not found' })) } else { res.status(200); const { _id: id, name } = room; const payload = { room: { id, name }, player: { id: player._id } }; const token = jwt.sign(payload, config.session.secret); if (playerInRoom(room, player)) { res.send(response({ token }, 'You already joined in this room')); } else { room.players = [...room.players, player]; room.save(); res.send(response({ token }, `Joined to "${name}"`)); } } }); }, list(req, res) { RoomModel.find({}, '-__v') .populate('owner', 'requests createdAt players _id name passwordCHSM_hb4V') .populate('players', '-token -__v -anonymous') .then((rooms) => { rooms.map((room) => { // switch the password string into a boolean room._doc.password = !!room._doc.password; }); res.send(response({ rooms }, `${rooms.length} rooms found`)); }); }, show(req, res) { const { id: _id } = req.params; RoomModel.findOne({ _id }, '-__v') .populate('players', '-__v -token') .then((room) => { if (!room) { res.status(404); res.send(response({}, 'Room not found', { room: 'Room not found' })); } // switch the password string into a boolean room._doc.password = !!room._doc.password; res.status(200); res.send(response({ room, }, 'Room found')); }); }, };
const grid = document.querySelector('.gridPage'); const rubberBtn = document.querySelector('.rubber'); const paintBtn = document.querySelector('.paint'); const resetBtn = document.querySelector('.reset'); function createGrid(){ for(let i = 0; i < 256; i++){ const gridDiv = document.createElement("div"); gridDiv.classList.add("square"); grid.appendChild(gridDiv); } } function updateGrid(){ grid.innerHTML = ""; grid.style.setProperty("grid-template-columns", 'repeat(${16}, 2fr)') grid.style.setProperty("grid-template-rows", 'repeat(${16}, 2fr)') for (let i = 0; i < 16 * 16; i++) { const gridDiv = document.createElement("div"); gridDiv.classList.add("square"); grid.appendChild(gridDiv); } } function paintActivate(){ const square = document.querySelector("div"); square.addEventListener("mouseover", function(event) { event.target.classList.replace("square", "colour"); }); }; function rubberActivate(){ const rubberSquare = document.querySelector("div"); rubberSquare.addEventListener("mouseover", function(event) { event.target.classList.replace("colour", "square"); }); }; function resetBoard(){ grid.innerHTML = ""; createGrid(); } rubberBtn.onclick = rubberActivate; paintBtn.onclick = paintActivate; resetBtn.onclick = resetBoard; createGrid();
module.exports = (function () { var tedious = require("tedious"); var Request = tedious.Request; var TYPES = tedious.TYPES; var Todo = require("../models/models.js").Todo; var moment = require("moment"); function createTodo(connection, todo) { return new Promise(function (resolve, reject) { var createTodoCommand = `INSERT INTO Todo(Taskname, Completed, DateCreated, DateCompleted, CreatedByUserId) VALUES(@Taskname, @Completed, @DateCreated, @DateCompleted, @CreatedByUserId); SELECT CAST(SCOPE_IDENTITY() AS INT) as Id;`; var request = new Request(createTodoCommand, function(err, rowCount, rows){ if(err) return reject(err); todo.id = rows[0].id.value; return resolve(todo); }); request.addParameter('Taskname', TYPES.NVarChar, todo.taskname); request.addParameter('Completed', TYPES.Bit, todo.completed || false); request.addParameter('DateCreated', TYPES.DateTimeOffset, new Date(todo.dateCreated)); request.addParameter('DateCompleted', TYPES.DateTimeOffset, todo.dateCompleted || null); request.addParameter('CreatedByUserId', TYPES.NVarChar, todo.createdByUserId); connection.execSql(request); }); } function readTodosForUser(connection, id) { return new Promise(function (resolve, reject) { var readTodosForUserCommand = `SELECT todo.Id as Id, todo.Taskname as Taskname, todo.Completed as Completed, todo.DateCreated as DateCreated, todo.DateCompleted as DateCompleted, todo.CreatedByUserId as CreatedByUserId FROM todo WHERE todo.CreatedByUserId = @UserId`; var request = new Request(readTodosForUserCommand, function(err, rowCount, rows){ if(err) return reject(err); if(rowCount === 0) return resolve([]); return resolve(rows.map(function(row){ return new Todo(row); })); }); request.addParameter('UserId', TYPES.Int, id); connection.execSql(request); }); } function readTodoById(connection, id) { return new Promise(function (resolve, reject) { var readTodoByIdCommand = `SELECT todo.Id as Id, todo.Taskname as Taskname, todo.Completed as Completed, todo.DateCreated as DateCreated, todo.DateCompleted as DateCompleted, todo.CreatedByUserId as CreatedByUserId FROM todo WHERE todo.Id = @Id`; var request = new Request(readTodoByIdCommand, function(err, rowCount, rows){ if(err) return reject(err); if(rowCount !== 1) return reject("Unexpected number of rows returned."); return resolve(new Todo(rows[0])); }); request.addParameter('Id', TYPES.Int, id); connection.execSql(request); }); } function updateTodo(connection, todo) { return new Promise(function (resolve, reject) { var updateTodoCommand = `UPDATE Todo SET Taskname = @Taskname, Completed = @Completed, DateCompleted = @DateCompleted WHERE Id = @Id`; var request = new Request(updateTodoCommand, function(err, rowCount){ if(err) return reject(err); return resolve(connection); }); var dateCompleted = todo.completed ? moment.utc().toDate() : null; request.addParameter('Id', TYPES.Int, todo.id); request.addParameter('Taskname', TYPES.NVarChar, todo.taskname); request.addParameter('Completed', TYPES.Bit, todo.completed); request.addParameter('DateCompleted', TYPES.DateTimeOffset, dateCompleted); connection.execSql(request); }); } function deleteTodo(connection, id) { return new Promise(function (resolve, reject) { var deleteTodoCommand = "DELETE FROM Todo WHERE Id = @Id"; var request = new Request(deleteTodoCommand, function(err, rowCount){ if(err) return reject(err); return resolve(); }); request.addParameter('Id', TYPES.Int, id); connection.execSql(request); }); } return { createTodo: createTodo, readTodosForUser: readTodosForUser, readTodoById: readTodoById, updateTodo: updateTodo, deleteTodo: deleteTodo }; })();
const test = require('tape'); const isBrowser = require('./isBrowser.js'); test('Testing isBrowser', (t) => { //For more information on all the methods supported by tape //Please go to https://github.com/substack/tape t.true(typeof isBrowser === 'function', 'isBrowser is a Function'); //t.deepEqual(isBrowser(args..), 'Expected'); //t.equal(isBrowser(args..), 'Expected'); //t.false(isBrowser(args..), 'Expected'); //t.throws(isBrowser(args..), 'Expected'); t.end(); });
/** * Created by wen on 2016/8/17. */ import React from 'react'; import Message from './message'; import {serverFetch} from '../../../utils/clientFetch'; export default { path: '/', async action({cookie,query}) { let isReady = await serverFetch(cookie,'/user/hasMessage',{});//判断是否有未读信息 let system = await serverFetch(cookie,'/user/findnoticelist',{page: 1,pagesize: 10});//系统消息 return <Message query={query} isReady={{...isReady}} system={{...system}} />; } };
function View(view, parentRandom){ this.random = Math.random().toString(16).slice(2); this.view = view; this.view.action = view.action || 'find'; this.nav = this.getNav(parentRandom); this.query = this.getQuery(parentRandom); this.result = this.getResult(parentRandom); this.setPrompt(); this.bindEvents(); return this; } View.prototype.getNav = function(parentRandom){ var count = parseInt($('.navlist').data('count')); var html = Html('#tViewNav', { id : 'nav'+this.random, index : count++, name : this.view.name, parent : parentRandom }); $('.navlist').data('count', count); if(parentRandom){ $('#nav'+parentRandom).after(html); } else { $('.navlist').append(html); } return $('#nav'+this.random); } View.prototype.getQuery = function(){ $('.queries').append(Html('#tQuery', { id : 'query'+this.random, view : this.view, collections : Storage.get('collections', true) })); return $('#query'+this.random); } View.prototype.getResult = function(){ $('.results').append(Html('#tResult', { id : 'result'+this.random, view : this.view })); return $("#result"+this.random); } View.prototype.setPrompt = function(){ var _this = this, prompt, operators, defaultOperators = {}; this.promptList = {}; this.query.find('.qpromt').html(''); if(typeof this.view.prompt === 'object'){ for(var i in this.view.prompt){ prompt = this.view.prompt[i]; prompt.name = i; prompt.dataType = prompt.dataType || 'string'; defaultOperators[prompt.operator || 'eq'] = prompt.value; operators = prompt.operators ? prompt.operators : defaultOperators; for(var operator in operators){ prompt.operator = operator; prompt.value = operators[operator]; _this.appendPrompt(prompt); } } } } View.prototype.appendPrompt = function(prompt){ var feed = prompt.feed ? Feed.load(this.query.find('.qcollection').val(), prompt.name) : null; var id = this.random+'-prompt-'+Html.clean(prompt.name+'-'+prompt.operator); var html = Html('#tPrompt', { id : id, prompt : prompt }) if(this.query.find('#'+id).length){ this.query.find('#'+id).replaceWith(html); } else { this.query.find('.qpromt').append(html); } return id; } View.prototype.fillFilter = function(prompt){ var fpromptModal = this.query.find('.fpromptModal'); for(var i in prompt){ if(prompt[i]){ fpromptModal.find('[name="'+i+'"]').val(prompt[i]); } } fpromptModal.modal(); } View.prototype.addFilter = function(submit){ $('#query'+this.random+'fPrompt').modal('toggle'); var prompt = this.query.find('.qpromtAdd').serializeObject(); this.query.find('.qpromtAdd')[0].reset(); if(prompt.name && prompt.name.trim()){ var id = this.appendPrompt(prompt); $('#'+id).focus(); } if(submit){ this.submit(); } } View.prototype.activate = function(){ $(".viewnav.active").removeClass('active'); this.nav.addClass('active'); $(".query.active").removeClass('active'); this.query.addClass('active'); $(".result.active").removeClass('active'); this.result.addClass('active'); }; View.prototype.submit = function(data){ var _this = this; var dataObject = data || this.query.find('.viewForm').serialize(); if(!(this.query.find('.qcollection').val())){ $(".collections").addClass('active'); } else { this.actionStart('submit'); $.ajax({ url : APP_PATH+'collection', data : dataObject }).done(function(data){ $('.views').scrollTop(0); _this.actionStop('submit'); _this.appendSuccess(data); }).error(function(xhr){ _this.actionStop('submit'); _this.appendError(xhr); }); } }; View.prototype.reset = function(){ this.query.find('.viewform')[0].reset(); } View.prototype.remove = function(){ var toFocus = this.nav.prev().length ? this.nav.prev() : this.nav.next(); this.nav.remove(); this.query.remove(); this.result.remove(); toFocus.click(); }; View.prototype.actionStart = function(action){ this.nav.find('.vn-name .glyphicon').addClass('glyphicon-repeat gly-spin'); this.query.find('.queryActions .submit .glyphicon').addClass('gly-spin'); } View.prototype.actionStop = function(action){ this.query.find('.queryActions .submit .glyphicon').removeClass('gly-spin'); this.nav.find('.vn-name .glyphicon').removeClass('glyphicon-repeat gly-spin'); } View.prototype.appendSuccess = function(data){ this.result.html(Html('#tResultTop', {meta : data.meta})); var resultSet = this.result.find('.result-set'); if(data.result.length){ var result = Result(this, data.meta.context.collection); if(data.meta.context.action === 'find'){ data.result.forEach(function(item, index){ resultSet.append(result.item(item, index, data.result.length)); }); } else { data.result.forEach(function(item, index){ resultSet.append(result.string(item, index, data.result.length)); }); } result.end(); } else { // Do something, Karen } } View.prototype.appendError = function(error){ this.result.html(Html('#tResultError', error)); } View.prototype.bindEvents = function(){ var to = this; to.nav.click(function(event){ to.activate(event); }); to.nav.find('.remove').click(function(event){ event.preventDefault(); to.remove(); }); to.query.find('.qcollection').click(function(event){ $(".collections").addClass('active'); }); to.query.find('.viewform').submit(function(event){ event.preventDefault(); to.submit(); }); to.query.find('.reset').click(function(event){ to.reset(); }); to.query.find('.remove').click(function(event){ to.remove(); }); to.query.find('.qpromtAdd').submit(function(event){ event.preventDefault(); to.addFilter(true); }); to.query.find('.btnAddFilter').click(function(event){ event.preventDefault(); to.addFilter(); }); };
'use strict'; import LivingThing from './LivingThing'; class Eukaryota extends LivingThing { constructor(name, uniCellular, trueNucleus, anaerobic, asexual, mobile, heterotroph) { super (name, uniCellular, trueNucleus, anaerobic, asexual, mobile); this._heterotroph = heterotroph; } get heterotroph() { return this._heterotroph; } set heterotroph(theBoolean) { this._heterotroph = theBoolean; } get autotroph() { return !this._heterotroph; } set autotroph(theBoolean) { this._heterotroph = !theBoolean; } } export default Eukaryota;
var api_home="http://inventory.sparcedge.com/api/"; $(document).on('submit', '#userdel', function(e){ // validation code here e.preventDefault(); $.ajax({ type: 'POST', url: api_home+"users/delete", async: true, dataType: 'html', data: $(this).serialize(), success: function(data) { $('#response').html(data); }, error: function(data) { $('#response').html(data); } }); return false; }); $(document).on('submit', '#itemdel', function(e){ // validation code here e.preventDefault(); $.ajax({ type: 'POST', url: api_home+"items/delete", async: true, dataType: 'html', data: $(this).serialize(), success: function(data) { $('#response').html(data); }, error: function(data) { $('#response').html(data); } }); return false; }); $(document).on('submit', '#inventorydel', function(e){ // validation code here e.preventDefault(); $.ajax({ type: 'POST', url: api_home+"inventory/delete", async: true, dataType: 'html', data: $(this).serialize(), success: function(data) { $('#response').html(data); }, error: function(data) { $('#response').html(data); } }); return false; }); $(function(){ $("#useradd").submit(function (e) { // validation code here e.preventDefault(); $.ajax({ type: 'POST', url: api_home+"users/add", async: true, dataType: 'html', data: $("#useradd").serialize(), success: function(data) { $('#response').html(data); $("#useradd")[0].reset(); }, error: function(data) { $('#response').html(data); } }); return false; }); }); $(function(){ $("#itemadd").submit(function (e) { // validation code here e.preventDefault(); $.ajax({ type: 'POST', url: api_home+"items/add", async: true, dataType: 'html', data: $("#itemadd").serialize(), success: function(data) { $('#response').html(data); $("#itemadd")[0].reset(); }, error: function(data) { $('#response').html(data); } }); return false; }); }); $(function(){ $("#inventoryadd").submit(function (e) { // validation code here e.preventDefault(); $.ajax({ type: 'POST', url: api_home+"inventory/add", async: true, dataType: 'html', data: $("#inventoryadd").serialize(), success: function(data) { $('#response').html(data); $("#inventoryadd")[0].reset(); }, error: function(data) { $('#response').html(data); } }); return false; }); }); $(document).on('submit', '#inventoryedit', function(e){ // validation code here e.preventDefault(); $.ajax({ type: 'POST', url: api_home+"inventory/edit", async: true, dataType: 'html', data: $("#inventoryedit").serialize(), success: function(data) { $('#response').html(data); $("#inventoryedit")[0].reset(); }, error: function(data) { $('#response').html(data); } }); return false; }); $(document).on('submit', '#itemedit', function(e){ // validation code here e.preventDefault(); $.ajax({ type: 'POST', url: api_home+"items/edit", async: true, dataType: 'html', data: $("#itemedit").serialize(), success: function(data) { $('#response').html(data); $("#itemedit")[0].reset(); }, error: function(data) { $('#response').html(data); } }); return false; }); $(document).on('submit', '#useredit', function(e){ // validation code here e.preventDefault(); $.ajax({ type: 'POST', url: api_home+"users/edit", async: true, dataType: 'html', data: $("#useredit").serialize(), success: function(data) { $('#response').html(data); $("#useredit")[0].reset(); }, error: function(data) { $('#response').html(data); } }); return false; });
import axios from 'axios' const baseUrl = process.env.REACT_APP_PORTFOLIO_URL let token = null const setToken = newToken => { token = `bearer ${newToken}` } const addStock = async stock => { const config = { headers: { Authorization: token } } const response = await axios.post(baseUrl + '/asset', stock, config) return response.data } const sellStock = async stock => { const config = { headers: { Authorization: token } } const response = await axios.post(baseUrl + '/sell', stock, config) return response.data } const getAssets = async () => { const config = { headers: { Authorization: token } } console.log('Post') try { await axios.post(baseUrl + '/update', null, config) const response = await axios.get(baseUrl, config) return response.data } catch (error) { console.log('CAUGHT') let message = { message: 'API Key Exhausted' } throw message } } const getChart = async (symbol) => { const config = { headers: { Authorization: token } } const stock = { ticker: symbol } try { const response = await axios.post(baseUrl + '/chart', stock, config) console.log('The data', response.data) return response.data } catch (error) { //Error can be either // Payment Required // Not Found console.log('The Error', error.response.data.error) return null } } const updateCash = async (cash) => { const config = { headers: { Authorization: token } } const body = { cash } const response = await axios.post(baseUrl + '/cash', body, config) return response.data } const updateAllocations = async (stocks) => { const config = { headers: { Authorization: token } } const stocksToUpdate = { stocks } const response = await axios.post(baseUrl + '/allocation', stocksToUpdate, config) return response.data } const getSettings = async () => { const config = { headers: { Authorization: token } } const response = await axios.get('/api/users/settings', config) console.log(response.data) return response.data } const setAlerts = async (alertSettings) => { const config = { headers: { Authorization: token } } const response = await axios.post('/api/users/alerts', alertSettings, config) return response.data } const updateThreshold = async threshold => { const config = { headers: { Authorization: token } } const newThreshold = { balanceThreshold: threshold } const response = await axios.post('/api/users/threshold', newThreshold, config) return response.data } export default { setToken, addStock, sellStock, getAssets, getChart, updateAllocations, updateCash, updateThreshold, getSettings, setAlerts }
(function () { "use strict"; /*global $q, $scope, $window */ describe("NetworksService", function () { var service, ApiService, ResultsHandlerService, networkList, networkData, networkPost, successResponse, AppStore; beforeEach(inject(function (_$injector_) { service = _$injector_.get("NetworksService"); ApiService = _$injector_.get("ApiService"); ResultsHandlerService = _$injector_.get("ResultsHandlerService"); AppStore = _$injector_.get("AppStore"); networkList = { networks: [{ smsNetworkId: "dvb", networkType: "DVB", connection: { uri: "dvb://172.20.244.10:11010", authId: "000005", authPassword: "", timeout: 1800, retryCount: 2, retryInterval: 1000, keepAlive: true, } }, { smsNetworkId: "iptv", networkType: "IPTV", connection: { uri: "iptv://172.20.244.201:1313", authId: "", authPassword: "", timeout: 0, retryCount: 0, retryInterval: 0, keepAlive: false, } }, { smsNetworkId: "ott", networkType: "OTT" }] }; networkData = { smsNetworkId: "dvb", networkType: "DVB", uri: "dvb://172.20.244.10:11010", authId: "000005", authPassword: "", timeout: 1800, retryCount: 2, retryInterval: 1000, keepAlive: true, }; networkPost = { "network": { "omit:smsNetworkId": networkData.smsNetworkId, "omit:networkType": networkData.networkType, "omit:connection": { "omit:uri": networkData.uri, "omit:authId": networkData.authId, "omit:authPassword": networkData.authPassword, "omit:timeout": networkData.timeout, "omit:retryCount": networkData.retryCount, "omit:retryInterval": networkData.retryInterval, "omit:keepAlive": networkData.keepAlive } } }; successResponse = { "result": { "ns1:resultId": "dvb", "ns1:resultCode": 0, "ns1:resultText": "Success" } }; spyOn(ApiService, "callEndpoint").and.callFake(function (url) { return $q(function (resolve) { resolve(/(add|modify|remove)Network$/.test(url) ? successResponse : networkList); }); }); spyOn(AppStore, "remove").and.callThrough(); spyOn(AppStore, "get").and.callThrough(); spyOn(AppStore, "put").and.callThrough(); // reset the localStorage cache $window.localStorage.clear(); })); describe("getNetworks", function () { it("should call ApiService.callEndpoint with the correct arguments", function () { var url = "/services/ConfigurationMgmtService/omi_getNetworkList", params = null, error = "Unable to retrieve the list of networks."; service.getNetworks(); expect(ApiService.callEndpoint).toHaveBeenCalledWith(url, params, error); }); it("should return a promise", function () { expect(service.getNetworks).toReturnAPromise(); }); it("should cache the results", function () { service.getNetworks(); $scope.$digest(); service.getNetworks(); $scope.$digest(); expect(ApiService.callEndpoint.calls.count()).toEqual(1); // First request only, putting the data in to localStorage expect(AppStore.put.calls.count()).toEqual(1, "AppStore.put"); // Checking that AppStore.get is called 3 times in total -- 2 times for // the first request (the initial presence check, which returns // undefined, and then again when the request is complete as it's the // value that is returned by the Promise handler), and 1 for the second // (the initial check of whether or not the data exists) expect(AppStore.get.calls.count()).toEqual(3, "AppStore.get"); }); it("should store the results in localStorage", function() { var storage = $window.localStorage, appKeys, appData; expect(getKeys()).toBe(null); expect(getData()).toBe(null); service.getNetworks(); $scope.$digest(); appKeys = getKeys(); expect(appKeys).toEqual("[\"getNetworkList\"]"); appData = getData(); expect(appData).toBeDefined(); expect(angular.fromJson(appData).value).toEqual(networkList.networks); expect(AppStore.put).toHaveBeenCalledWith("getNetworkList", networkList.networks); expect(AppStore.get.calls.count()).toBe(2); ///// function getKeys() { return storage.getItem("cachefactory.caches.appStore.keys"); } function getData() { return storage.getItem("cachefactory.caches.appStore.data.getNetworkList"); } }); }); describe("getNetworkType", function () { beforeEach(function () { spyOn(service, "getNetworks").and.callFake(function() { return $q(function(resolve) { resolve([{ "smsNetworkId": "dvb", "networkType": "DVB", }, { "smsNetworkId": "iptv", "networkType": "IPTV", }, { "smsNetworkId": "testNetwork1", "networkType": "ott" }]); }); }); }); it("should return a promise", function () { expect(service.getNetworkType).toReturnAPromise(); }); it("should cache the results", function () { service.getNetworkType("dvb"); $scope.$digest(); service.getNetworkType("dvb"); $scope.$digest(); expect(service.getNetworks.calls.count()).toEqual(1); // First request only, putting the data in to localStorage expect(AppStore.put.calls.count()).toEqual(1, "AppStore.put"); // Checking that AppStore.get is called 3 times in total -- 2 times for // the first request (the initial presence check, which returns // undefined, and then again when the request is complete as it's the // value that is returned by the Promise handler), and 1 for the second // (the initial check of whether or not the data exists) expect(AppStore.get.calls.count()).toEqual(3, "AppStore.get"); }); it("should store the results in localStorage", function() { var storage = $window.localStorage, appKeys, appData, networkTypes; networkTypes = { "dvb": "dvb", "iptv": "iptv", "testNetwork1": "ott", }; expect(getKeys()).toBe(null); expect(getData()).toBe(null); service.getNetworkType("dvb"); $scope.$digest(); appKeys = getKeys(); expect(appKeys).toEqual("[\"getNetworkType\"]"); appData = getData(); expect(appData).toBeDefined(); expect(angular.fromJson(appData).value).toEqual(networkTypes); expect(AppStore.put).toHaveBeenCalledWith("getNetworkType", networkTypes); expect(AppStore.get.calls.count()).toBe(2); ///// function getKeys() { return storage.getItem("cachefactory.caches.appStore.keys"); } function getData() { return storage.getItem("cachefactory.caches.appStore.data.getNetworkType"); } }); }); describe("createNetwork", function () { it("should call ApiService.callEndpoint with the correct arguments", function () { var url = "/services/ConfigurationMgmtService/omi_addNetwork", error = "Unable to create Network."; service.createNetwork(networkData); expect(ApiService.callEndpoint).toHaveBeenCalledWith(url, networkPost, error); }); it("should return a promise", function () { expect(ApiService.callEndpoint).toReturnAPromise(); }); it("should reset the network cache", function () { service.getNetworks(); $scope.$digest(); service.createNetwork(networkData); $scope.$digest(); service.getNetworks(); $scope.$digest(); expect(AppStore.remove).toHaveBeenCalledWith("getNetworkList"); expect(ApiService.callEndpoint.calls.count()).toEqual(3); }); }); describe("updateNetwork", function () { it("should call ApiService.callEndpoint with the correct arguments", function () { var url = "/services/ConfigurationMgmtService/omi_modifyNetwork", error = "Unable to update Network."; service.updateNetwork(networkData); expect(ApiService.callEndpoint).toHaveBeenCalledWith(url, networkPost, error); }); it("should return a promise", function () { expect(service.updateNetwork).toReturnAPromiseWith(networkData); }); it("should reset the network cache", function () { service.getNetworks(); $scope.$digest(); service.updateNetwork(networkData); $scope.$digest(); service.getNetworks(); $scope.$digest(); expect(ApiService.callEndpoint.calls.count()).toEqual(3); }); }); describe("removeNetwork", function () { it("should call ApiService.callEndpoint with the correct arguments", function () { var url = "/services/ConfigurationMgmtService/omi_removeNetwork", error = "Unable to remove Network."; service.removeNetwork(networkData); expect(ApiService.callEndpoint).toHaveBeenCalledWith(url, networkPost, error); }); it("should return a promise", function () { expect(service.removeNetwork).toReturnAPromiseWith(networkData); }); it("should reset the network cache", function () { service.getNetworks(); $scope.$digest(); service.removeNetwork(networkData); $scope.$digest(); service.getNetworks(); $scope.$digest(); expect(AppStore.remove).toHaveBeenCalledWith("getNetworkList"); expect(ApiService.callEndpoint.calls.count()).toEqual(3); }); }); describe("getNetworkStreamCount", function () { var networks, response; beforeEach(function () { networks = [{ networkType: "DVB" }, { networkType: "IPTV" }, { networkType: "OTT" }]; response = { systemTree: { children: [{ attribute: { name: "NETWORK", value: "DVB" }, children: [{ attribute: { name: "STREAM COUNT", value: "5" } }] }, { attribute: { name: "NETWORK", value: "IPTV" }, children: [{ attribute: { name: "STREAM COUNT", value: "10" } }] }, { attribute: { name: "NETWORK", value: "OTT" }, children: [{ attribute: { name: "STREAM COUNT", value: "15" } }] }] } }; }); it("should add count properties to each network", function () { expect(service.getNetworkStreamCount("DVB", response)).toEqual("5"); }); it("should set a null count property if a network LICENSE item does not exist", function () { response.systemTree.children.pop(); expect(service.getNetworkStreamCount("OTT", response)).toEqual(null); }); }); }); }());
sap.ui.define([ "sap/f/sample/ShellBarWithSplitApp/controller/BaseController", "sap/m/MessageToast", ], function (BaseController, MessageToast) { "use strict"; return BaseController.extend("sap.f.sample.ShellBarWithSplitApp.controller.Login", { onInit() { var that = this; this.byId("InventFilesLoginPage").attachBrowserEvent("keypress", oEvent => { if(oEvent.keyCode != jQuery.sap.KeyCodes.ENTER) return; that.onLogin(); }); this.UserCredentials = { UserName: "", Password:"", grant_type : 'password' }; }, onLogin(oEvent) { this.UserCredentials.UserName = this.byId("userName").getValue() this.UserCredentials.Password = this.byId("userPass").getValue() if(!this.UserCredentials.UserName || !this.UserCredentials.Password) { MessageToast.show("Infome o usuário e senha"); return; }else{ this.setUserSession(this.UserCredentials) this.getRouter().navTo("services") } } }); });
import React from 'react'; import { PropTypes } from 'prop-types'; const Opportunity = ({ title, location, duration, programmes, coverPhotoUrl, onClick, }) => ( <li className="Opportunity" onClick={() => onClick()}> <div className="Opp-header"> <h2>{title}</h2> </div> <div className="App-intro"> <p>{location}</p> <p> {duration} {' weeks'} </p> <p>{programmes.short_name}</p> <p> <img src={coverPhotoUrl} alt="" /> </p> </div> </li> ); Opportunity.propTypes = { title: PropTypes.string.isRequired, location: PropTypes.string.isRequired, duration: PropTypes.number.isRequired, branch: PropTypes.shape({ organisation: PropTypes.shape({ name: PropTypes.string.isRequired, }).isRequired, }).isRequired, programmes: PropTypes.shape({ id: PropTypes.number.isRequired, short_name: PropTypes.string.isRequired, }).isRequired, coverPhotoUrl: PropTypes.string.isRequired, onClick: PropTypes.func.isRequired, }; export default Opportunity;