text
stringlengths
7
3.69M
import React from 'react'; import { FaRegHandPaper , FaCut} from 'react-icons/fa'; import { GiBoxingGlove } from 'react-icons/gi'; const stringtoicon = { boxing: <GiBoxingGlove size={30}></GiBoxingGlove>, hand: <FaRegHandPaper size={30}></FaRegHandPaper>, cut: <FaCut size={30}></FaCut>, } export default function Gamebutton(props) { return( ) }
//LICZY OD ZERA var imiona = ['Paweł', 'Krzysztof', 'Kasia', 'Nicole', 'Kamil']; //console.log(imiona[2]); //tu wyświetliło kasie /*console.log(imiona); imiona[5] = 'Monika'; imiona[6] = 'Marcin'; console.log(imiona); */ //push dodaje elemnt na końcu tablicy i z automatu przypisze kolejny indeks /*imiona.push('Mikołaj'); console.log(imiona);*/ //pop usuwa ostatni element z tablicy imiona.pop(); console.log(imiona); var usunietyElement = imiona.pop(); console.log(usunietyElement); //wstawienie elementu na początku tablicy imiona.unshift('Kajetan'); console.log(imiona); //usuwanie pierwszego elementu z tablicy imiona.shift(); console.log(imiona); // sprawdzenie długości tablicy console.log(imiona.length); // metoda join - rozbijanie tablicy na ciąg tekstowy var tablicaJakoTekst = imiona.join("--"); console.log(tablicaJakoTekst); //revers - odwraca kolejnosc elemntów tablicy var imionaReverse = imiona.reverse(); console.log(imionaReverse); // sort- sortuje tablice var posortowana = imiona.sort(); console.log(posortowana)
/** * This file contains the common middleware used by your routes. * * Extend or replace these functions as your application requires. * * This structure is not enforced, and just a starting point. If * you have more middleware you may want to group it as separate * modules in your project's /lib directory. */ var _ = require('underscore'); /** Initialises the standard view locals The included layout depends on the navLinks array to generate the navigation in the header, you may wish to change this array or replace it with your own templates / logic. */ exports.initLocals = function(req, res, next) { var locals = res.locals; if (req.user) { locals.navLinks = [ { label: 'Home', key: 'home', href: '/' }, //{ label: 'Innovation Item', key: 'project', href: '/project' }, //{ label: 'Review Status', key: 'contact', href: '/contact' }, { label: 'Item Review', key: 'itemreview', href: '/itemreview' }, { label: 'Notice', key: 'notice', href: 'notice'}, // {label: 'Calendar', key: 'calendar', href: '/notice'}, // {label: 'Selection', key: 'selection', href: '/visit'}, // ]}, { label: 'Contact', key: 'contact', href: '/contact' }, { label: 'Password', key: 'password', href: '/password' }, //TODO delete on 2017/07/03 for requirement_01 // { label: 'Visit', key: 'visit', href: '/visit' }, // { label: 'Template', key: 'template', href: '/template' }, // TODO add by wtshuai 20170620 { label: 'Themes', key: 'themes' }, { label: 'Spacelab', key: 'thText'} ]; locals.notice =[ { label: 'IISC Calendar', key: 'calendar', href: '/calendar' }, { label: 'Selection Result', key: 'result', href: '/result' }, ]; locals.themes =[{label:'Cerulean',key:'Cerulean'},{label:'Journal',key:'Journal'}, {label:'Paper',key:'Paper'},{label:'Readable',key:'Readable'},{label:'Slate',key:'Slate'}, {label:'Cosmo',key:'Cosmo'},{label:'Custom',key:'Custom'}, {label:'Cyborg',key:'Cyborg'},{label:'Darkly',key:'Darkly'}, {label:'Flatly',key:'Flatly'},{label:'Lumen',key:'Lumen'}, {label:'Sandstone',key:'Sandstone'},{label:'Simplex',key:'Simplex'}, {label:'Spacelab',key:'Spacelab'},{label:'Superhero',key:'Superhero'}, {label:'United',key:'United'},{label:'Yeti',key:'Yeti'}, ]; } else { locals.navLinks = [ { label: 'Home', key: 'home', href: '/' }, { label: 'Register', key: 'register', href: '/register' }, //{ label: 'Notice', key: 'notice', pages:[ // {label: 'Calendar', key: 'calendar', href: '/notice'}, // {label: 'Selection', key: 'selection', href: '/visit'}, // ]}, { label: 'Notice', key: 'notice', href: '/notice' }, { label: 'Contact', key: 'contact', href: '/contact' }, //TODO delete on 2017/07/03 for requirement_01 //{ label: 'Visit', key: 'visit', href: '/visit' }, //{ label: 'Template', key: 'template', href: '/template' }, // TODO add by wtshuai 20170620 { label: 'Themes', key: 'themes'}, { label: 'Spacelab', key: 'thText'} ]; locals.notice =[ { label: 'IISC Calendar', key: 'calendar', href: '/calendar' }, { label: 'Selection Result', key: 'result', href: '/result' }, ]; locals.themes =[{label:'Cerulean',key:'Cerulean'},{label:'Journal',key:'Journal'}, {label:'Paper',key:'Paper'},{label:'Readable',key:'Readable'},{label:'Slate',key:'Slate'}, {label:'Cosmo',key:'Cosmo'},{label:'Custom',key:'Custom'}, {label:'Cyborg',key:'Cyborg'},{label:'Darkly',key:'Darkly'}, {label:'Flatly',key:'Flatly'},{label:'Lumen',key:'Lumen'}, {label:'Sandstone',key:'Sandstone'},{label:'Simplex',key:'Simplex'}, {label:'Spacelab',key:'Spacelab'},{label:'Superhero',key:'Superhero'}, {label:'United',key:'United'},{label:'Yeti',key:'Yeti'}, ]; } locals.user = req.user; next(); }; /** Fetches and clears the flashMessages before a view is rendered */ exports.flashMessages = function(req, res, next) { var flashMessages = { info: req.flash('info'), success: req.flash('success'), warning: req.flash('warning'), error: req.flash('error') }; res.locals.messages = _.any(flashMessages, function(msgs) { return msgs.length; }) ? flashMessages : false; next(); }; /** Prevents people from accessing protected pages when they're not signed in */ exports.requireUser = function(req, res, next) { if (!req.user) { req.flash('error', 'Please sign in to access this page.'); res.redirect('/keystone/signin'); } else { next(); } };
import Vue from 'vue' import VueRouter from 'vue-router' const originalPush = VueRouter.prototype.push VueRouter.prototype.push = function push(location, onResolve, onReject) { if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject) return originalPush.call(this, location).catch(err => err) } // 模块自动化导入 const modulesFiles = require.context('./modules', false, /\.js$/) const modulesRouters = modulesFiles.keys().reduce((total, curr) => { // console.log(total, curr) const value = modulesFiles(curr) // console.log('-value-', value) return total.concat(value.default) }, []) Vue.use(VueRouter) const routes = [ { path: '/', redirect: '/index' }, { path: '/log', name: 'Log', component: () => import(/* webpackChunkName: 'login' */ '@/views/login'), meta: { title: '登录' } }, ...modulesRouters ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
import React, { Component } from 'react'; class Generes extends Component { state = { } render() { return ( <ul className="list-group"> <li key={'all'} onClick={()=>{this.props.onAllGeneres()}} className={this.props.activeGenre === "all"? "list-group-item active": "list-group-item"}>{"All Genres"}</li> {this.props.items.map(item => <li key={item._id} onClick={()=>{this.props.onSelect(item)}} className={this.props.activeGenre === item.name ? "list-group-item active": "list-group-item"}>{item.name}</li>)} </ul> ); } } export default Generes;
import models from '../models'; export default { add: async (req, res, next) => { try { const reg = await models.Loan.create(req.body); res.status(200).json(reg); } catch (e) { res.status(500).send({ message: 'Internal server error' }); next(e); } }, queryint: async (req, res, next) => { try { const reg = await models.Loan.findOne({ _id: req.query._id }) .populate('affiliate', { name: 1, registration: 1 }); // populate de mongoose let loan_id = reg._id; let loan_amount_requested = reg.amount_requested; const last_payment = await models.Payment.findOne({ loan: loan_id }).sort({ '_id': -1 }) if (last_payment) { // Tiene pagos anteriores? await models.Payment.create( { loan: loan_id, date: "2020-10-15", transaction_date: "2020-10-15", t_c: 5.25, interest: parseFloat((((12 / 100) / 360) * 90 * parseFloat(last_payment.balance))).toFixed(2), receipt: "OPRO", balance: parseFloat(parseFloat((((12 / 100) / 360) * 90 * parseFloat(last_payment.balance))) + parseFloat(last_payment.balance)).toFixed(2) }); } else { // Es su primera amortización? await models.Payment.create( { loan: loan_id, date: "2020-10-15", // Por qué hardcode? transaction_date: "2020-10-15", t_c: 5.25, interest: parseFloat((((12 / 100) / 360) * 90 * parseFloat(loan_amount_requested))).toFixed(2), receipt: "OPRO", balance: parseFloat(parseFloat((((12 / 100) / 360) * 90 * parseFloat(loan_amount_requested))) + parseFloat(loan_amount_requested)).toFixed(2) }); } if (!reg) { res.status(404).send({ message: 'The record does not exist' }) } else { res.status(200).json(reg); } } catch (e) { res.status(500).send({ message: 'Internal server error' }); next(e); } }, queryaccint: async (req, res, next) => { try { const reg = await models.Loan.findOne({ _id: req.query._id }) .populate('affiliate', { name: 1, registration: 1 }); let loan_id = reg._id; let loan_amount_requested = reg.amount_requested; const last_payment = await models.Payment.findOne({ loan: loan_id }).sort({ '_id': -1 }) if (last_payment) { await models.Payment.create( { loan: loan_id, date: "2020-10-15", transaction_date: "2020-10-15", t_c: 5.25, estimated_quota: 0, quota: 0, other_charge: 0, d_c: 0, interest: parseFloat((((12 / 100) / 360) * 270 * parseFloat(last_payment.balance))).toFixed(2), accumulated_interest: parseFloat((((12 / 100) / 360) * 270 * parseFloat(last_payment.balance))).toFixed(2), total: 0, receipt: "OPRO", registry: 0, balance: parseFloat(parseFloat((((12 / 100) / 360) * 270 * parseFloat(last_payment.balance))) * 2 + parseFloat(last_payment.balance)).toFixed(2) }); } else { await models.Payment.create( { loan: loan_id, date: "2020-10-15", transaction_date: "2020-10-15", t_c: 5.25, estimated_quota: 0, quota: 0, other_charge: 0, d_c: 0, interest: parseFloat((((12 / 100) / 360) * 270 * parseFloat(loan_amount_requested))).toFixed(2), accumulated_interest: parseFloat((((12 / 100) / 360) * 270 * parseFloat(loan_amount_requested))).toFixed(2), total: 0, receipt: "OCAS", registry: 0, balance: parseFloat(parseFloat((((12 / 100) / 360) * 270 * parseFloat(loan_amount_requested))) * 2 + parseFloat(loan_amount_requested)).toFixed(2) }); } if (!reg) { res.status(404).send({ message: 'The record does not exist' }) } else { res.status(200).json(reg); } } catch (e) { res.status(500).send({ message: 'Internal server error' }); next(e); } }, list: async (req, res, next) => { try { let valor = req.query.valor; //const reg = await models.Loan.find({$or:[{'code': new RegExp(valor, 'i')},{'voucher': new RegExp(valor, 'i')}]},{createdAt:0}) const reg = await models.Loan.find({}) .populate('affiliate', {}) .sort({ 'code': 1 }); res.status(200).json(reg); } catch (e) { res.status(500).send({ message: 'Internal server error' }); next(e); } }, update: async (req, res, next) => { try { const reg = await models.Loan.findByIdAndUpdate({ _id: req.body._id }, { code: req.body.code, voucher: req.body.voucher, exchange_rate: req.body.exchange_rate, request_date: req.body.request_date, debt_date: req.body.debt_date, amount_requested: req.body.amount_requested, loan_term: req.body.loan_term, amortization: req.body.amortization }); res.status(200).json(reg); } catch (e) { res.status(500).send({ message: 'Internal server error' }); next(e); } }, remove: async (req, res, next) => { try { const reg = await models.Loan.findByIdAndDelete({ _id: req.body._id }); res.status(200).json(reg); } catch (e) { res.status(500).send({ message: 'Internal server error' }); next(e); } }, activate: async (req, res, next) => { try { const reg = await models.Loan.findByIdAndUpdate({ _id: req.body._id }, { status: 1 }); res.status(200).json(reg); } catch (e) { res.status(500).send({ message: 'Internal server error' }); next(e); } }, deactivate: async (req, res, next) => { try { const reg = await models.Loan.findByIdAndUpdate({ _id: req.body._id }, { status: 0 }); res.status(200).json(reg); } catch (e) { res.status(500).send({ message: 'Internal server error' }); next(e); } } }
import styles from './css/TradeRow.css'; import {Icon,Modal} from 'antd'; let showMore = (detail) => { let myObject = JSON.parse(detail); // 格式化 let formattedStr = JSON.stringify(myObject, null, 2); Modal.info({ maskClosable: true, okText: '确定', title: '参数:', width: 700, content: <pre>{formattedStr}</pre>, }); }; let ActionItem = (data,index,isLast=false)=>{ let creater = ''; if(data.authorization.length > 0){ creater = `${data.authorization[0].actor}@${data.authorization[0].permission}`; } let _style = {}; if(index == 0){ _style = {paddingTop:20}; } let flag = false; let s = data.data; if(s.length > 108){ flag = true; s = s.substring(0,100) + '...'; } if(data){ return (<div key={index} className={styles.line} style={_style}> <div style={{overflow:'hidden'}}> <div style={{float:'left', width: 220}}>发起人:{creater}</div> <div style={{float:'left', width: 160}}>合约: {data.account}</div> <div style={{float:'left', width: 150}}>接口: {data.name}</div> <div className={styles.params} style={{float:'left', width: 760}}> <span>参数: {s}</span> {flag ? <Icon onClick={()=>showMore(data.data)} style={{marginLeft:10,cursor:'pointer',color:'#2d8fff',fontWeight:'bold'}} type="search"/> :null} </div> </div> { isLast ? null : <div className={styles.division}></div> } </div>); }else{ return <div></div>; } }; let TradeRow = (record, clickFunc)=>{ let data = record; console.log('>>>>>>>', data); if(data){ let action_info = record.action_info; // 多个action测试 // action_info = action_info.concat(action_info); let len = action_info.length; return ( <div className={styles.rowContent}> <div className={styles.header}> <div>交易ID: <a href="javascript:void(0)" onClick={() => {clickFunc(data.id);}}>{data.id}</a></div> <div>{data.timestamp}</div> </div> <div> { action_info.map((item, index) => { return ActionItem(item, index, index===len-1); }) } </div> </div>); }else{ return <div></div>; } }; export default TradeRow;
import React from 'react'; import ReactDOM from 'react-dom'; export default class Header extends React.Component<{}, {}> { constructor(props) { super(props); } componentDidMount() { console.log(this.props.username); } onClick() { this.props.logOut(); } render() { return ( <nav class="pt-navbar .modifier"> <div class="pt-navbar-group pt-align-left"> <div class="pt-navbar-heading">Hello, {this.props.username}</div> <button class="pt-button pt-minimal pt-icon-user"></button> </div> <div class="pt-navbar-group pt-align-right"> <span class="pt-navbar-divider"></span> <button class="pt-button pt-minimal pt-icon-cog" onClick={this.onClick.bind(this)}>Log out</button> </div> </nav> ); } }
const router = require('koa-router')(); const fs = require('fs'); router.prefix('/upload') // 文件上传 router.post('/', async (ctx, next) => { const file = ctx.request.files const originUrl = ctx.request.origin const fileName = file[Object.keys(file)[0]].path.split('public/').pop() return ctx.body = { msg: '上传成功', status:200, url: `${originUrl}/${fileName}` }; }) module.exports = router
/** * init.js - example of file that imports a library * */ var lib = require('./lib.js'); // fire on window 'load' event lib.attachEvent(window, 'load', function() { // fire on 'click' event lib.attachEvent(document.body, 'click', function(ev) { if (ev.target.tagName === 'BUTTON') alert('js-seeeeed!'); }); });
const elementoIntro = document.querySelector('#texto') const elementoImagem = document.querySelector('#arquivoImagem') let elementoBotao = document.querySelector('#alterar') let Lista = ['primeiro', 'segundo', 'terceiro','quarto', 'quinto', 'sexto'] elementoBotao.addEventListener('click', () => { if (elementoBotao.value == 'primeiro') { elementoImagem.src = './assets/img/gótica.jpg' elementoIntro.innerText = 'O seu humor é: Gretchen Gótica! \nVocê é intensa e profunda. Uma amiga leal, mas que Poucas pessoas compreendem.\nTente evitar ficar mais desanimada do que já é. \nAproveite o clima para um boa taça de vinho.' elementoBotao.value = 'segundo' } else if (elementoBotao.value == 'segundo') { elementoImagem.src = './assets/img/dança.gif' elementoIntro.innerText = 'O seu humor é: Gretchen Dançarina\nVocê é animada e divertida, a verdadeira alma da festa \n Continue sempre com seu CongaLaConga, mas cuidado para não abusar do álcool!' elementoBotao.value = 'terceiro' } else if (elementoBotao.value == 'terceiro') { elementoImagem.src = './assets/img/indignada.png' elementoIntro.innerText = 'O seu humor é: Gretchen indignada!\n Você não aceita desaforo e está sempre pronta para defender o que acredita\n Está ouvindo esse som? É o tabu sendo quebrado!' elementoBotao.value = 'quarto' } else if (elementoBotao.value == 'quarto'){ elementoImagem.src = './assets/img/grata.jpg' elementoIntro.innerText = 'O seu humor é: Gretchen Gratiluz!\nVocê é muito grata pela natureza, os animaizinho e as flores\n Cotinue com a essa vibe boa, mas atenção! Nem tudo quen é natural faz bem\nCuidado com as ervas, garota!' elementoBotao.value = 'quinto' } else if (elementoBotao.value == 'quinto'){ elementoImagem.src = './assets/img/samba.gif' elementoIntro.innerText = 'O seu humor é: Gretchen Brasileira!\nVocê adora um samba, um futebol e uma caipirinha\nAproveite o Carnaval e beije muito!\nO ministério da saúde adverte: #UseCamisinha' elementoBotao.value = 'sexto' } })
// Getting (on the next page) var rate = sessionStorage.rating.split(/[,]+/); console.log(rate); document.getElementById('rating').innerHTML = rate[0]; document.getElementById('time').innerHTML = rate[1];
function setStyleCss3(object, key, value) { object.style['-webkit-'+ key] = value; object.style['-moz-'+key] = value; object.style['-ms-'+key] = value; object.style[key] = value; } document.addEventListener("scroll",function(e){ var scrollTop = (window.pageYOffset || document.documentElement.scrollTop) - (document.documentElement.clientTop || 0); var scrollBottom = scrollTop + window.innerHeight; // com.onScroll(e); $(".auto-scroll").each(function(index,element){ var transition = +(element.style.cssText.match(/\d+/g) || [0])[0]; var height = +element.offsetHeight; if (scrollBottom > transition+height) transition = scrollBottom - height; if (scrollTop < transition) transition = scrollTop; setStyleCss3(element,"transform","translateY("+transition+"px)"); }); });
'use strict' const { Int64BE } = require('int64-buffer') // TODO remove dependency function writeUInt8 (buffer, value, offset) { buffer[offset] = value return 1 } function writeUInt16 (buffer, value, offset) { buffer[offset + 1] = value & 255 value = value >> 8 buffer[offset + 0] = value & 255 return 2 } function writeUInt32 (buffer, value, offset) { buffer[offset + 3] = value & 255 value = value >> 8 buffer[offset + 2] = value & 255 value = value >> 8 buffer[offset + 1] = value & 255 value = value >> 8 buffer[offset + 0] = value & 255 return 4 } function writeId (buffer, id, offset) { id = id.toBuffer() if (id.length > 8) { id = id.subarray(id.length - 8, id.length) } buffer.set(id, offset) return 8 } function writeInt64 (buffer, value, offset) { new Int64BE(buffer, offset, value) // eslint-disable-line no-new return 8 } function write (buffer, string, offset) { let index = offset || (offset |= 0) const length = string.length let chr = 0 let i = 0 while (i < length) { chr = string.charCodeAt(i++) if (chr < 128) { buffer[index++] = chr } else if (chr < 0x800) { // 2 bytes buffer[index++] = 0xC0 | (chr >>> 6) buffer[index++] = 0x80 | (chr & 0x3F) } else if (chr < 0xD800 || chr > 0xDFFF) { // 3 bytes buffer[index++] = 0xE0 | (chr >>> 12) buffer[index++] = 0x80 | ((chr >>> 6) & 0x3F) buffer[index++] = 0x80 | (chr & 0x3F) } else { // 4 bytes - surrogate pair chr = (((chr - 0xD800) << 10) | (string.charCodeAt(i++) - 0xDC00)) + 0x10000 buffer[index++] = 0xF0 | (chr >>> 18) buffer[index++] = 0x80 | ((chr >>> 12) & 0x3F) buffer[index++] = 0x80 | ((chr >>> 6) & 0x3F) buffer[index++] = 0x80 | (chr & 0x3F) } } return index - offset } module.exports = { writeUInt8, writeUInt16, writeUInt32, writeInt64, writeId, write }
/** * Steps: * 1. npm init -y && npm i express node-fetch * 2. require / import dependancies * 3. app.listen(3000) * 4. app.use(...) */ var express = require('express'); var app = express(); var fetch = require('node-fetch'); // built in node module var path = require('path'); /** * Documentation: * 1. app.param() * https://expressjs.com/en/api.html#app.param */ app.use('/:pokemonName', async (_req, _response) => { // :pokemonName ref to ${request.params.pokemonName} // see express documentation on req.params // req stands for the request, params is the parameters of the request // translation, what is your request to try { _response = await fetch(`https://pokeapi.co/api/v2/pokemon/${_req.params.pokemonName}`); // .then( function (response) { response.json()} ) // .then(DATA => console.log(DATA) ) // .catch(error => res.send(error)); const _json = await _response.json(); console.log(_json.forms); const [...forms] = _json.forms; console.log("forms",_json.forms); // const [...data] = _json.data; } catch (error) { console.log(error); } }); app.listen(3000)
var Ingredient = require('../models/ingredientModel.js'); var routes = {}; routes.showIngredients = function (req, res) { Ingredient.find({}) .exec(function (err, ingredients) { if (err) { res.status(500).send("Error! Can't find ingredients :("); } else { if (ingredients.length > 0) { var inStock = []; var outOfStock = []; var inStockMessage = ''; var outOfStockMessage = ''; for (var i=0; i < ingredients.length; i++) { ingredients[i].inStock ? inStock.push(ingredients[i]) : outOfStock.push(ingredients[i]); } if (inStock.length > 0) { inStockMessage = "In stock ingredients:"; } else { inStockMessage = "No in stock ingredients" } if (outOfStock.length > 0) { outOfStockMessage = "Out of stock ingredients:"; } else { outOfStockMessage = "No out of stock ingredients" } res.render("ingredients", {"inStockMessage": inStockMessage, "inStockIngredients": inStock, "outOfStockMessage": outOfStockMessage, "outOfStockIngredients": outOfStock}); } else { res.render("ingredients", {"inStockMessage": "No ingredients", "inStockIngredients": ingredients}); } } }); } routes.edit = function (req, res) { var edits = req.body; console.log(edits); Ingredient.count({name: edits.name}, function (err, count) { if (err) res.status(500).send("Problen editing your ingredient :(" + err); if (count > 0) { res.end(); } else { Ingredient.findByIdAndUpdate(edits.id, {name: edits.name, price: edits.price}, function (err, ingredient) { if (err) { res.status(500).send("Error finding ingredient"); } else { res.send(edits); } }); } }); } routes.addIngredient = function (req, res) { var ingredient = req.body; ingredient.inStock = true; var newIngredient = new Ingredient(ingredient); Ingredient.count({name: newIngredient.name}, function (err, count) { if (err) res.status(500).send("Problen editing your ingredient :(" + err); if (count > 0) { res.end(); } else { newIngredient.save(function (err) { if (err) res.status(500).send("Problem adding new ingredient" + err); }); res.send(newIngredient); } }); } routes.makeOutOfStock = function (req, res) { Ingredient.findByIdAndUpdate(req.body.id, {inStock: false}, function (err, ingredient) { if (err) { res.status(500).send("Error finding ingredient" + err); } else { res.send(ingredient); } }); } routes.restock = function (req, res) { Ingredient.findByIdAndUpdate(req.body.id, {inStock: true}, function (err, ingredient) { if (err) { res.status(500).send("Error finding ingredient" + err); } else { res.send(ingredient); } }); } module.exports = routes;
import axios from '@/utils/request' //添加站点 export function toAddSite(data) { return axios({ method: 'post', url: '/api/site/create', data: data, headers: {} }).then(res => { return Promise.resolve(res) }).catch(err => { console.log(err); }) }
import React, { useState } from "react"; import { useDispatch } from "react-redux"; import { dangNhapAction } from "../redux/actions/QuanLyNguoiDungAction"; import { NavLink } from "react-router-dom"; export default function DangNhap(props) { const dispatch = useDispatch(); const [userLogin, setUserLogin] = useState({ taiKhoan: "", matKhau: "", }); // console.log(userLogin); const handleChange = (e) => { console.log("e :", e.target); let { value, name } = e.target; // bốc tách phần tử console.log("e :", e.target, value, name); let newUserLogin = { ...userLogin, [name]: value }; setUserLogin(newUserLogin); }; const handleSubmit = (e) => { e.preventDefault(); // chặn sự kiện reload brower dispatch(dangNhapAction(userLogin)); }; return ( <div className="DangNhapCPN"> <form className="container formDangNhap " onSubmit={handleSubmit}> <div className="display-4 text-center TieuDeDN">ĐĂNG NHẬP </div> <div className="form-group"> <p>Tài Khoản</p> <input className="form-control" name="taiKhoan" onChange={handleChange} /> </div> <div className="form-group"> <p>Mật Khẩu</p> <input className="form-control" name="matKhau" type="password" onChange={handleChange} /> </div> <div className="text-left"> <a href="#">Quên mật khẩu?</a> </div> <div className="form-group text-left"> <br /> <button type="submit" className="btn btn-group btn-success"> Đăng Nhập </button>{" "} / <NavLink className="nutDangKy" to="/dangky"> <button className="btn btn-group btn-success">Đăng Ký</button> </NavLink> </div> <div className="form-group text-left"></div> <div className="text-left"> <p>Đăng nhập bằng </p> <> <div href="#" className="mr-2"> <img className="itemDangNhap" src="/img/tonghop/fb_logo.png" />{" "} <img className="itemDangNhap" src="/img/tonghop/zalo-logo.png" />{" "} </div> </> </div> <NavLink to="/"> <button className="btn btn-danger">Hủy</button> </NavLink> </form> </div> ); }
const q = require('../../database/SeedWithPostGres'); test('Random Function exists', () => { expect(q.randomFunction).toBeTruthy(); }); test('Random Function Creates an Id with an input', () => { const testNumber = 10; const pie = q.randomFunction(testNumber); expect(pie.id).toEqual(testNumber); }); test('Random Function A random s', () => { const testNumber = 10; const pie = q.randomFunction(testNumber); expect(pie.id).toEqual(testNumber); }); test('Random Function Creates A Random Name', () => { const testNumber1 = 10; const testNumber2 = 11; const FirstRandom = q.randomFunction(testNumber1); const SecondRandom = q.randomFunction(testNumber2); expect(typeof FirstRandom.name).toBe('string'); expect(FirstRandom.name).not.toBe(SecondRandom.name); }); test('Random Function Creates Random Closing and Opening Times', () => { const testNumber1 = 10; const testNumber2 = 11; const FirstRandom = q.randomFunction(testNumber1); const SecondRandom = q.randomFunction(testNumber2); expect(typeof FirstRandom.monday).toBe('string'); expect(FirstRandom.monday).not.toBe(SecondRandom.monday); }); test('Random Function Creates Random Address', () => { const testNumber1 = 10; const testNumber2 = 11; const FirstRandom = q.randomFunction(testNumber1); const SecondRandom = q.randomFunction(testNumber2); expect(typeof FirstRandom.address).toBe('string'); expect(FirstRandom.address).not.toBe(SecondRandom.address); }); test('Random Function Creates A Random url', () => { const testNumber1 = 10; const testNumber2 = 11; const FirstRandom = q.randomFunction(testNumber1); const SecondRandom = q.randomFunction(testNumber2); expect(typeof FirstRandom.url).toBe('string'); expect(FirstRandom.url).not.toBe(SecondRandom.url); }); test('Random Function Creates A Random Phone', () => { const testNumber1 = 10; const testNumber2 = 11; const FirstRandom = q.randomFunction(testNumber1); const SecondRandom = q.randomFunction(testNumber2); expect(typeof FirstRandom.phone).toBe('string'); expect(FirstRandom.phone).not.toBe(SecondRandom.phone); }); test('Random Function Creates A Random Latitutde', () => { const testNumber1 = 10; const testNumber2 = 11; const FirstRandom = q.randomFunction(testNumber1); const SecondRandom = q.randomFunction(testNumber2); expect(typeof FirstRandom.lat).toBe('string'); expect(FirstRandom.lat).not.toBe(SecondRandom.lat); }); test('Random Function Creates A Random Longitude', () => { const testNumber1 = 10; const testNumber2 = 11; const FirstRandom = q.randomFunction(testNumber1); const SecondRandom = q.randomFunction(testNumber2); expect(typeof FirstRandom.lng).toBe('string'); expect(FirstRandom.lng).not.toBe(SecondRandom.lng); });
X.define('modules.productManage.publishProduct', ['model.productsManageModel', 'common.layer', 'adapter.webuploader', 'adapter.ueditor'], function(model, layer) { var view = X.view.newOne({ el: $('.xbn-content'), url: X.config.productManage.tpl.publishProduct }) var ctrl = X.controller.newOne({ view: view }) var validate = { rules: { title: { required: true, rangelength: [1, 250] }, tagKeyword1: { required: true, rangelength: [1, 20] }, tagKeyword2: { rangelength: [1, 20] }, tagKeyword3: { rangelength: [1, 20] }, specificationsAndModels: { required: false, rangelength: [1, 20] }, commodityDescription: { required: true, rangelength: [1, 1500] }, price: { required: false, rangelength: [1, 50], isIntFloat2: 10 }, port: { required: false, rangelength: [1, 50] }, issuanceStationId: { required: true }, commodityAttachmentList: { required: true, rangelength: [1, 20] }, currency: { required: false }, priceClause: { rangelength: [1, 50] }, texture: { rangelength: [1, 20] }, weight: { rangelength: [1, 20] }, size: { rangelength: [1, 20] }, colour: { rangelength: [1, 20] }, peculiarity: { rangelength: [1, 20] }, hscode: { rangelength: [1, 10], isIntGteZeroExtend: true } }, messages: { title: { required: "请输入标题", rangelength: "字数在250字以内" }, tagKeyword1: { required: "请输入标签/关键词", rangelength: "字数在20字以内" }, tagKeyword2: { rangelength: "字数在20字以内" }, tagKeyword3: { rangelength: "字数在20字以内" }, specificationsAndModels: { required: "请输入规格型号", rangelength: "字数在20字以内" }, commodityDescription: { required: "请输入产品描述", rangelength: "字数在1500字以内" }, price: { required: "请输入价格", rangelength: "字数在50字以内", isIntFloat2: "必须数字且小数点前最多十位,后两位" }, port: { required: "请输入港口", rangelength: "字数在50字以内" }, issuanceStationId: { required: "请选择发布网站" }, commodityAttachmentList: { required: "请上传图片", rangelength: "图片数量在1-20张" }, currency: { required: "请选择货币类型" }, priceClause: { rangelength: "字数在50字以内" }, texture: { rangelength: "字数在20字以内" }, weight: { rangelength: "字数在20字以内" }, size: { rangelength: "字数在20字以内" }, colour: { rangelength: "字数在20字以内" }, peculiarity: { rangelength: "字数在20字以内" }, hscode: { rangelength: "字数在10字以内", isIntGteZeroExtend: "必须为正整数" } }, onkeyup: false, onfocusout: function (element) { var elem = $(element); elem.valid(); }, errorPlacement: function (error, element) { element.after(error) } } var submitClicked = false var events = { init: function() { var me = this ele = $('.purchaseInfoDetail', view.el) id && me.isEdit() UE.delEditor('publishProEditor') editor = UE.getEditor('publishProEditor',{maximumWords:1500, toolbars:[["bold", "forecolor", "fontsize", "paragraph", "link"]], errorClass: 'pro-man-edi-err', afterBlur: function() { var val = editor.getContent(), len = val.substr(0, editor.getContentLength(true)) $('input[data-property-name=commodityDescription]', view.el).val(val).next().val(len).valid() }}); //UE.delEditor() $('.js-submit', ele).on('click', me.save) ele.validate(validate) }, isEdit: function() { this.fillData() submitType = 'PUT' $('.now', view.el).html('自营商品 > 编辑商品') }, save: function() { //ele.find('[name=commodityDescription]').val(editor.getContent()) if (ele.valid()) { var data = events.dataConvert.call(this, ctrl.vm.collectData()) if (!submitClicked) { submitClicked = true model.save(data, submitType, function(res) { if (res.statusCode === X.constant.statusCode.SUCCESS) { layer.successMsg('提交成功', function() { history.go(-1) }) } else { layer.alert('提交失败, 请联系服务人员') } submitClicked = false }) } } }, dataConvert: function(data) { data.commodityDescription = editor.getContent() data.commodityStatus = this.getAttribute('stype') data.commodityAttachmentList.forEach(function(item) { if (item.url) { item.filePath = item.url delete item.url } }) data.tagKeyword = data.tagKeyword1 + (data.tagKeyword2? ',' + data.tagKeyword2.trim(): '') + (data.tagKeyword3? ',' + data.tagKeyword3.trim(): '') delete data.tagKeyword1 delete data.tagKeyword2 delete data.tagKeyword3 data.issuanceStationList = [] //{issuanceStationId: data.issuanceStationId} data.issuanceStationId.split(',').forEach(function(item) { data.issuanceStationList.push({issuanceStationId: item}) }) delete data.issuanceStationId submitType === 'PUT' && (data.commodityId = id) return data }, fillData: function() { model.query(id, function(res) { data = res.data[0] data.tagKeyword.split(',').forEach(function(item, i) { data['tagKeyword' + (i + 1)] = item }) for (var i in data) { var dom = ele.find('[name='+ i +']') dom.val(data[i]) } events.extraDataTransform() }) }, extraDataTransform: function() { //upload.setValue(data.commodityAttachmentList) editor.ready(function() { editor.setContent('<p>'+ data.commodityDescription +'</p>') }) ctrl.vm.getControl('currency').setValue(data.currency) var issuanceStationId = ctrl.vm.getControl('issuanceStationId') data.issuanceStationList.forEach(function(item) { issuanceStationId.setValue(item.issuanceStationId) }) ctrl.vm.getControl('commodityAttachmentList').renderAll(data.commodityAttachmentList) data.commodityStatus == '1' && $('.js-submit[stype=0]', ele).remove() } } var id, ele, data, upload, editor, submitType ctrl.load = function(para) { submitType = 'POST' id = para.id view.render(data,function() { events.init() var meta = { 'currency': {dataSource : model.currency}, 'issuanceStationId': {dataSource : model.issuanceStationId}, 'commodityAttachmentList': { size: 2, type: 14, //min: 3, max: 20, duplicate: false, accept: {extensions: 'jpg,jpeg,png'} } } ctrl.vm = ctrl.getViewModel(ele,{ meta: meta}); ctrl.vm.initControl() }) } return ctrl })
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ var swiper = new Swiper('.swiper-container', { // spaceBetween: 30, centeredSlides: true, autoplay: { delay: 5000, disableOnInteraction: false, }, pagination: { el: '.swiper-pagination', clickable: true, }, navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, });
import { combineReducers } from 'redux' import menuReducer from './menuReducer' export default combineReducers({ menus: menuReducer })
import { combineReducers } from 'redux'; const ids = (state = [], action) => { switch(action.type) { case 'FETCH_EXERCISES_SUCCESS': console.log(action.response.result); return action.response.result; case 'ADD_EXERCISE_SUCCESS': return [...state, action.response.result] default: return state; } }; const isLoading = (state = false, action) => { switch(action.type) { case 'FETCH_EXERCISES_REQUEST': case 'ADD_EXERCISE_REQUEST': return true; case 'FETCH_EXERCISES_SUCCESS': case 'FETCH_EXERCISES_FAILURE': case 'ADD_EXERCISE_SUCCESS': case 'ADD_EXERCISE_FAILURE': return false; default: return state; } } const errorMessage = (state = null, action) => { switch(action.type) { case 'FETCH_EXERCISES_FAILURE': case 'ADD_EXERCISE_FAILURE': return action.message; case 'FETCH_EXERCISES_SUCCESS': case 'ADD_EXERCISE_SUCCESS': return null; default: return state; } } export default combineReducers({ ids, isLoading, errorMessage, }); export const getIds = state => state.ids; export const getIsLoading = state => state.isLoading; export const getErrorMessage = state => state.errorMess
// This device will remap midi notes to random ones // Useful for arpeggiating a drumrack and switching up what notes will be ouput inlets = 1; outlets = 1; var mappedNotes = new Array(128); // For undo function var prevMappedNotes = new Array(128); var minMIDINote = 0; var maxMIDINote = 127; // Note in function list(a) { var noteIn = arguments[0]; var velIn = arguments[1]; var outList = [mappedNotes[noteIn], velIn]; outlet(0,outList); } function remapAll() { for (var i = minMIDINote; i <= maxMIDINote; i++) { prevMappedNotes[i] = mappedNotes[i]; mappedNotes[i] = Math.round((Math.random() * maxMIDINote)); } } function remapNote(note) { prevMappedNotes[note] = mappedNotes[note]; mappedNotes[note] = Math.round((Math.random() * maxMIDINote)); } function undo() { for (var i = minMIDINote; i <= maxMIDINote; i++) { mappedNotes[i] = prevMappedNotes[i]; } } function init() { for (var i = minMIDINote; i <= maxMIDINote; i++) { prevMappedNotes[note] = mappedNotes[note]; mappedNotes[i] = i; } }
const fs = require("fs"); const filePath = String(__dirname + "/input.txt"); const input = fs .readFileSync(filePath) .toString() .split(",") .map(value => parseInt(value)); const programAlarmLogic = (function(inputArray) { function findOutput(noun, verb) { const clone = [...inputArray]; clone[1] = noun; clone[2] = verb; i = 0; while (true) { if (clone[i] === 99) { break; } else if (clone[i] === 1) { clone[clone[i + 3]] = clone[clone[i + 1]] + clone[clone[i + 2]]; } else if (clone[i] === 2) { clone[input[i + 3]] = clone[input[i + 1]] * clone[clone[i + 2]]; } i = i + 4; } return clone[0]; } function findInputs(finalAnswer) { for (let noun of [...Array(100).keys()]) { for (let verb of [...Array(100).keys()]) { if (findOutput(noun, verb) === finalAnswer) { return 100 * noun + verb; } } } return "No results found"; } return { partOneAnswer: findOutput(12, 2), partTwoAnswer: findInputs(19690720) }; })(input); //Part One Answer console.log("The output is %d", programAlarmLogic.partOneAnswer); //Part Two Answer console.log("The input is", programAlarmLogic.partTwoAnswer);
import React from 'react' import { BrowserRouter as Router, Route, Link, Redirect, } from 'react-router-dom' import Loadable from 'react-loadable' import Home from '../components/Home' import Loading from '../components/Loading' const LoadableComponent = Loadable({ loader: () => import('../components/Test.jsx'), loading: Loading, }) const RouteConfig = () => ( <Router> <div className="container"> <nav> <ul> <li><Link to="/">home</Link> </li> <li><Link to="/test">test</Link></li> </ul> </nav> <Route exact path="/" component={Home} /> <Route path="/test" component={LoadableComponent} /> <Redirect from="*" to="/" /> </div> </Router> ) export default RouteConfig
let colors = ["Green", "Blue", "Yellow", "Brown"]; let num = 3; let text = "This is a string!"; document.write("Colors is an Array: " + Array.isArray(colors) + "<br>"); document.write("Num is an Array: " + Array.isArray(num) + "<br>"); document.write("Text is an Array: " + Array.isArray(text) + "<br>");
var NAVTREEINDEX30 = { "recvattach_8c.html#a999be3ce814a6a72a2a5c409b7583521":[2,0,119,13], "recvattach_8c.html#a9bb432bd5d6e9dd5a0a2ded079bc3238":[2,0,119,0], "recvattach_8c.html#a9f5ef40654633b4cdf0d6e15ca3d040c":[2,0,119,37], "recvattach_8c.html#aa18a07fb44233ba66b108e547049b0b4":[2,0,119,16], "recvattach_8c.html#aa21744623c750c6f114a93f06ac5e257":[2,0,119,27], "recvattach_8c.html#aa65ac63b4bb9d0b83b6f4128736ad190":[2,0,119,19], "recvattach_8c.html#aa9845701586d190b83e575e9e1f89303":[2,0,119,5], "recvattach_8c.html#aad56960e0d22f0b6e36dbf18d120d84a":[2,0,119,12], "recvattach_8c.html#abbeaadd477fc375248f1cd02818b4318":[2,0,119,31], "recvattach_8c.html#ad2db180cf6dcb64135698feb56c46e31":[2,0,119,33], "recvattach_8c.html#ad9fd4e0f66cfaae456b12604583b51de":[2,0,119,22], "recvattach_8c.html#ada90cfca09573e1031de106fd88cad72":[2,0,119,4], "recvattach_8c.html#adf1dd9e8d7f5246ed4030d38a360b29b":[2,0,119,21], "recvattach_8c.html#aee9ef3743bfbc7184db6e3a364c45f9d":[2,0,119,32], "recvattach_8c.html#af3d9eba146519070da9cdc16cd6d92b7":[2,0,119,15], "recvattach_8c_source.html":[2,0,119], "recvattach_8h.html":[2,0,120], "recvattach_8h.html#a04bcc22093de3415ac71326159b811a0":[2,0,120,5], "recvattach_8h.html#a15aa67845d7281e3b5263c24dcf75d0c":[2,0,120,2], "recvattach_8h.html#a2e4fa073f32fdd98a0bd153be8fd6bc8":[2,0,120,10], "recvattach_8h.html#a7688e395101baa5931494c883909d1da":[2,0,120,4], "recvattach_8h.html#a78aa13dd16615623c622c6a328eb1438":[2,0,120,9], "recvattach_8h.html#a7bea02ad8971e507de4d94b0f7e87a62":[2,0,120,3], "recvattach_8h.html#aa21744623c750c6f114a93f06ac5e257":[2,0,120,0], "recvattach_8h.html#aa9845701586d190b83e575e9e1f89303":[2,0,120,1], "recvattach_8h.html#abbeaadd477fc375248f1cd02818b4318":[2,0,120,6], "recvattach_8h.html#ad2db180cf6dcb64135698feb56c46e31":[2,0,120,8], "recvattach_8h.html#aee9ef3743bfbc7184db6e3a364c45f9d":[2,0,120,7], "recvattach_8h_source.html":[2,0,120], "recvcmd_8c.html":[2,0,121], "recvcmd_8c.html#a110f32c4e75cb004e0695ee4ec1f2a83":[2,0,121,20], "recvcmd_8c.html#a11892868ab4b577c562b2636f559a168":[2,0,121,17], "recvcmd_8c.html#a19645ec9979f53ad6f2671e6013d4ea4":[2,0,121,15], "recvcmd_8c.html#a39a129d4e768fdf693d33aae82cca2d6":[2,0,121,7], "recvcmd_8c.html#a3ece8162f54f872f718dc0b8a7efcd83":[2,0,121,12], "recvcmd_8c.html#a57bf017e070d58703cd1b742d61fe9cb":[2,0,121,4], "recvcmd_8c.html#a66adb00462737e047af99c9cd10b65c6":[2,0,121,5], "recvcmd_8c.html#a6e40010e67b096350dbb4344e2d7449e":[2,0,121,18], "recvcmd_8c.html#a6e898062c3b6c2c8f6701cb4595f37b4":[2,0,121,11], "recvcmd_8c.html#a7c55bf567b5f09c72e507d90b4d97ed4":[2,0,121,13], "recvcmd_8c.html#a803384ce9ee1cf1bef751ff4808584ef":[2,0,121,3], "recvcmd_8c.html#a8be856d602dd059fbed3a01b1abcf65f":[2,0,121,6], "recvcmd_8c.html#a901d3c7f945de489c16050a731dee83c":[2,0,121,8], "recvcmd_8c.html#a974b16877e9bb00f6680674b641591f9":[2,0,121,19], "recvcmd_8c.html#ab39fb82ff6781463a0a5953e6f470312":[2,0,121,14], "recvcmd_8c.html#acb021cf1aaf2ec1daa6eb09f7b9e8942":[2,0,121,9], "recvcmd_8c.html#add111d22e3be56af4dbf845fd0e52aca":[2,0,121,16], "recvcmd_8c.html#ae32812dd02476b8d30d33de490856e53":[2,0,121,0], "recvcmd_8c.html#ae6bdd547880206792de3620befcb18d0":[2,0,121,1], "recvcmd_8c.html#af2a32e11ee4abdd9f23eadfb3cfbe9f7":[2,0,121,2], "recvcmd_8c.html#af75f34573790a122a80c96ff84c36c79":[2,0,121,10], "recvcmd_8c_source.html":[2,0,121], "recvcmd_8h.html":[2,0,122], "recvcmd_8h.html#a110f32c4e75cb004e0695ee4ec1f2a83":[2,0,122,5], "recvcmd_8h.html#a19645ec9979f53ad6f2671e6013d4ea4":[2,0,122,2], "recvcmd_8h.html#a39a129d4e768fdf693d33aae82cca2d6":[2,0,122,1], "recvcmd_8h.html#a6e40010e67b096350dbb4344e2d7449e":[2,0,122,3], "recvcmd_8h.html#a8be856d602dd059fbed3a01b1abcf65f":[2,0,122,0], "recvcmd_8h.html#a974b16877e9bb00f6680674b641591f9":[2,0,122,4], "recvcmd_8h_source.html":[2,0,122], "reflow_8c.html":[2,0,12,11], "reflow_8c.html#a0c807a5c20cc6d04f426325ca3c46f96":[2,0,12,11,1], "reflow_8c.html#a272019359561fd9f5c369dcba4f235ae":[2,0,12,11,0], "reflow_8c.html#a50e81ea47b75f474efabdfce6231fe7f":[2,0,12,11,2], "reflow_8c_source.html":[2,0,12,11], "reflow_8h.html":[2,0,12,12], "reflow_8h.html#a50e81ea47b75f474efabdfce6231fe7f":[2,0,12,12,0], "reflow_8h_source.html":[2,0,12,12], "regex2_8h.html":[2,0,7,22], "regex2_8h.html#adc80368774feb74430c17707477aae78":[2,0,7,22,1], "regex2_8h.html#aff2fb0be83daa0d421af71fe4a7af233":[2,0,7,22,0], "regex2_8h_source.html":[2,0,7,22], "regex3_8h.html":[2,0,19,47], "regex3_8h.html#a10e50965e40cc0fe521c15c77d1e4841":[2,0,19,47,26], "regex3_8h.html#a198ba9499ba526f237d66ca2556294a8":[2,0,19,47,4], "regex3_8h.html#a2c9214257c0c29629a4481d8937a8be3":[2,0,19,47,17], "regex3_8h.html#a2f322455dea2489dd7f43ba968abdc7f":[2,0,19,47,3], "regex3_8h.html#a349838a3143be1dd9b0500bfbe54d48f":[2,0,19,47,7], "regex3_8h.html#a4cd5feab8463aea0a18d195f6c3a704d":[2,0,19,47,23], "regex3_8h.html#a4fd9f92b6c20e595b9487f874cb75f02":[2,0,19,47,20], "regex3_8h.html#a5c1dc418529747116226ffa8f97e9e88":[2,0,19,47,24], "regex3_8h.html#a67ed3f37a5cbaab7f957bf5d842a9ff9":[2,0,19,47,10], "regex3_8h.html#a73c8d3ccb577177ae092d69d16b97daa":[2,0,19,47,13], "regex3_8h.html#a7b0b955eaca9b1208ff025f30a98aef0":[2,0,19,47,21], "regex3_8h.html#a832d8611d480868199eab1ab47600ab9":[2,0,19,47,11], "regex3_8h.html#a85d894a61e6b1e7e31c01e6c9172e0f5":[2,0,19,47,5], "regex3_8h.html#a8c0336091c762c8206a756a3aa8753a3":[2,0,19,47,9], "regex3_8h.html#a9b4024e6d204d5df72a30b531a6e0b18":[2,0,19,47,14], "regex3_8h.html#aaff3892e138113fb1eaa76d65a58a308":[2,0,19,47,15], "regex3_8h.html#ab0efb83f9190881306c558339efb250a":[2,0,19,47,18], "regex3_8h.html#ab1005f6776a35ae11d421c0006cbb19e":[2,0,19,47,16], "regex3_8h.html#ab35a665810bd04fdc311a2691a00632c":[2,0,19,47,25], "regex3_8h.html#ab555bdefb9368b1d8291152bd69dfb05":[2,0,19,47,28], "regex3_8h.html#ac1d05fece1652b744d7c33c91629a71b":[2,0,19,47,19], "regex3_8h.html#acbf0cd6774750d7f48bd8a5dd466d1fa":[2,0,19,47,6], "regex3_8h.html#ace9a8836dfa6c039cb619573c60e253f":[2,0,19,47,8], "regex3_8h.html#ad25947e610db74945537b99edf428982":[2,0,19,47,27], "regex3_8h.html#ade73ed859442be7909ae50763f772d88":[2,0,19,47,22], "regex3_8h.html#af1d2870e8a90d604287ca13a457dee47":[2,0,19,47,12], "regex3_8h_source.html":[2,0,19,47], "remailer_8c.html":[2,0,123], "remailer_8c.html#a02b655c7006c40e3a5a3af7b3b720349":[2,0,123,8], "remailer_8c.html#a03e8541ce7387bb1e0901cd71c8d23c9":[2,0,123,4], "remailer_8c.html#a0b48fa9d9df7079340bb349c86635738":[2,0,123,20], "remailer_8c.html#a0df3fbea97e2b0fc17a753640d20d92d":[2,0,123,19], "remailer_8c.html#a4783bd16f7a686bbb78afbf24be9eab0":[2,0,123,17], "remailer_8c.html#a57ce2295be2a0adc039d590dd4383cc8":[2,0,123,21], "remailer_8c.html#a6aedd68d18973cb892555b9e0dff9353":[2,0,123,13], "remailer_8c.html#a718fa86ab6d391f0fe4fbe2c4a1831fb":[2,0,123,15], "remailer_8c.html#a774d684af1a1257c59c004a45ce70b93":[2,0,123,5], "remailer_8c.html#a8bf7833097cc538f7b1c315b590afc34":[2,0,123,9], "remailer_8c.html#a8c174dbaef54fb52a409dc4e69d67606":[2,0,123,3], "remailer_8c.html#a91ede3b43b8773ed01defd231dc17cd5":[2,0,123,16], "remailer_8c.html#a9e1af7b606bb190e11242ce57f3de147":[2,0,123,22], "remailer_8c.html#aa6446e37f57197ea42e073bffcfb8360":[2,0,123,7], "remailer_8c.html#ab3c1ebaeffae6f83d883842a9f6b3749":[2,0,123,1], "remailer_8c.html#ab3f70f41a449de7dab5d4d9d0264ba45":[2,0,123,12], "remailer_8c.html#ac1185869ada19a5d3f9b6bf8e0b64db4":[2,0,123,14], "remailer_8c.html#ac72a3f2de52cabdb78766c0de37b5e68":[2,0,123,6], "remailer_8c.html#ad50a9dfadc4f60139fba845ca4e8698a":[2,0,123,11], "remailer_8c.html#adc3bfc78dd5fcda39be0a3dabeeb8a5c":[2,0,123,18], "remailer_8c.html#add993060873690b1eea4383e8356a48a":[2,0,123,23], "remailer_8c.html#ae3fe25304d54610f53b73a27bbadbcce":[2,0,123,2], "remailer_8c.html#af5e45429360f721bb0f9665d479cf6a2":[2,0,123,10], "remailer_8c_source.html":[2,0,123], "remailer_8h.html":[2,0,124], "remailer_8h.html#a069205cbd3e1b4f69a1c94bdb578d054":[2,0,124,5], "remailer_8h.html#a0b48fa9d9df7079340bb349c86635738":[2,0,124,9], "remailer_8h.html#a0df3fbea97e2b0fc17a753640d20d92d":[2,0,124,10], "remailer_8h.html#a4f3b9f866ca70baa2f00c4e5a39c8441":[2,0,124,7], "remailer_8h.html#a57ce2295be2a0adc039d590dd4383cc8":[2,0,124,12], "remailer_8h.html#a9ade1beedd9b601cc63ebaecda58095b":[2,0,124,3], "remailer_8h.html#a9e1af7b606bb190e11242ce57f3de147":[2,0,124,13], "remailer_8h.html#aaffa59943f755b425c5d0af281ec664a":[2,0,124,2], "remailer_8h.html#adc3bfc78dd5fcda39be0a3dabeeb8a5c":[2,0,124,11], "remailer_8h.html#ae91ddbfa45876d4d8358fc79849a17e8":[2,0,124,4], "remailer_8h.html#af4908697bfee91b6ddacc8696aa1d7d7":[2,0,124,8], "remailer_8h.html#afba5f3f1e5f1eb0a96dcc5fdfe41aa42":[2,0,124,6], "remailer_8h_source.html":[2,0,124], "resize_8c.html":[2,0,125], "resize_8c.html#a1f18053a2fadd1f5c2f45382e3165dcb":[2,0,125,1], "resize_8c.html#a8d99fe6b2da016d237243f31e9403bf6":[2,0,125,0], "resize_8c_source.html":[2,0,125], "reverse_8c.html":[2,0,1,10], "reverse_8c.html#a8f5eca479605975d43e59cc8214cd2c9":[2,0,1,10,4], "reverse_8c.html#a91f1d4988876567a46a6b1291da267d9":[2,0,1,10,5], "reverse_8c.html#acbab505cc98b97d6524ed9ceed41f7be":[2,0,1,10,2], "reverse_8c.html#ad3fe271128056b406c800a2bcac1bb9e":[2,0,1,10,1], "reverse_8c.html#adcac6af93dc6927de0a242fb1a75577b":[2,0,1,10,3], "reverse_8c.html#af945cd681dba89fe5c8ce5842e96b31c":[2,0,1,10,0], "reverse_8c_source.html":[2,0,1,10], "reverse_8h.html":[2,0,1,11], "reverse_8h.html#acbab505cc98b97d6524ed9ceed41f7be":[2,0,1,11,1], "reverse_8h.html#ad3fe271128056b406c800a2bcac1bb9e":[2,0,1,11,3], "reverse_8h.html#adcac6af93dc6927de0a242fb1a75577b":[2,0,1,11,2], "reverse_8h.html#af945cd681dba89fe5c8ce5842e96b31c":[2,0,1,11,0], "reverse_8h_source.html":[2,0,1,11], "rfc2047_8c.html":[2,0,11,20], "rfc2047_8c.html#a1a52e96601eca65a96d0e9401b1ec1f9":[2,0,11,20,4], "rfc2047_8c.html#a386450bad3229da26d1cd1a63d0fc257":[2,0,11,20,5], "rfc2047_8c.html#a3cc43939d840544876d40c8da1f99b7d":[2,0,11,20,14], "rfc2047_8c.html#a470b076f25dc95af370a94d73dbd7cc0":[2,0,11,20,3], "rfc2047_8c.html#a4f979b4ba087d3291049da868935e005":[2,0,11,20,16], "rfc2047_8c.html#a68424d046b66d891da1b80929074f616":[2,0,11,20,10], "rfc2047_8c.html#a72b4275b0634c8faba7296d1c1c9d97e":[2,0,11,20,1], "rfc2047_8c.html#a78942300d9cc890e47b32b24c5a4d2e1":[2,0,11,20,7], "rfc2047_8c.html#a79026f5cfec0b561058f7021e19b9601":[2,0,11,20,18], "rfc2047_8c.html#a7bc348d3286019d04ba25d666fb86901":[2,0,11,20,12], "rfc2047_8c.html#a89c57c82465740567f73641c9397d760":[2,0,11,20,15], "rfc2047_8c.html#a8c4ea35c95b50455b895a18b7e4cbc10":[2,0,11,20,9], "rfc2047_8c.html#ac7aa3c6d84c8eaa435d161cc2c227b88":[2,0,11,20,17], "rfc2047_8c.html#ac84a78b1788e7c21ab20df68a24c9cd0":[2,0,11,20,6], "rfc2047_8c.html#aceeb3a044de1c06a649af033af856486":[2,0,11,20,19], "rfc2047_8c.html#ad304a6e40f646f43a411b649f960b306":[2,0,11,20,13], "rfc2047_8c.html#ae5a216c48811ce4274751b1ffed405da":[2,0,11,20,2], "rfc2047_8c.html#aed2999c145a004bc9c37fbd6248b822e":[2,0,11,20,0], "rfc2047_8c.html#af517130be123255c119dae5b47f3cb1c":[2,0,11,20,8], "rfc2047_8c.html#afef686b50d1bc6030d76a2c1c5dbb6c4":[2,0,11,20,11], "rfc2047_8c_source.html":[2,0,11,20], "rfc2047_8h.html":[2,0,11,21], "rfc2047_8h.html#a3cc43939d840544876d40c8da1f99b7d":[2,0,11,21,1], "rfc2047_8h.html#a4f979b4ba087d3291049da868935e005":[2,0,11,21,3], "rfc2047_8h.html#a79026f5cfec0b561058f7021e19b9601":[2,0,11,21,4], "rfc2047_8h.html#a89c57c82465740567f73641c9397d760":[2,0,11,21,0], "rfc2047_8h.html#ac7aa3c6d84c8eaa435d161cc2c227b88":[2,0,11,21,2], "rfc2047_8h.html#aceeb3a044de1c06a649af033af856486":[2,0,11,21,5], "rfc2047_8h_source.html":[2,0,11,21], "rfc2231_8c.html":[2,0,11,22], "rfc2231_8c.html#a18e1908042cf69dc9d9f4d18e729a1ea":[2,0,11,22,1], "rfc2231_8c.html#a2ceb659ae91979bc3555e06d8fd385dd":[2,0,11,22,4], "rfc2231_8c.html#a37a7cf8339df423fe726423ee9080a22":[2,0,11,22,7], "rfc2231_8c.html#a6ab88476a6050396968d81de51aba465":[2,0,11,22,5], "rfc2231_8c.html#a95eb6a825f563e45d47c100ea43954c6":[2,0,11,22,8], "rfc2231_8c.html#ab1146bbd3f5094bffce1e850bf2c0db0":[2,0,11,22,10], "rfc2231_8c.html#aca9032d6ef162cc900d4b96455c341ee":[2,0,11,22,9], "rfc2231_8c.html#ad5b8314b3c077f2f4ff930fff6741a86":[2,0,11,22,3], "rfc2231_8c.html#adff03833afc464d04a290f5faed3bc5c":[2,0,11,22,2], "rfc2231_8c.html#af5280631f410590ef909ebe62087e293":[2,0,11,22,6], "rfc2231_8c_source.html":[2,0,11,22], "rfc2231_8h.html":[2,0,11,23], "rfc2231_8h.html#a95eb6a825f563e45d47c100ea43954c6":[2,0,11,23,0], "rfc2231_8h.html#ab1146bbd3f5094bffce1e850bf2c0db0":[2,0,11,23,2], "rfc2231_8h.html#aca9032d6ef162cc900d4b96455c341ee":[2,0,11,23,1], "rfc2231_8h_source.html":[2,0,11,23], "rfc3676_8c.html":[2,0,126], "rfc3676_8c.html#a1a3abb7fcf3409cd1fe345fd20eee6a9":[2,0,126,10], "rfc3676_8c.html#a2fb3e8d4c89f28fca07fe90b66adff6a":[2,0,126,12], "rfc3676_8c.html#a420fe3b4413c3e4427b25a4f3ed96dd7":[2,0,126,1], "rfc3676_8c.html#a47bfc67ef302e9b51cee14c713a70f35":[2,0,126,14], "rfc3676_8c.html#a5be5171c37ea30b3ff53c2339daba4d2":[2,0,126,18], "rfc3676_8c.html#a65b6441acda161a859dcf941c4d0ee9f":[2,0,126,4], "rfc3676_8c.html#a75f88b287dd092e1c3129dee78409930":[2,0,126,9], "rfc3676_8c.html#a9cd1b3af0b88c1d0179e890b444c5be0":[2,0,126,16], "rfc3676_8c.html#aac259238494c57983f6b213392cbe91a":[2,0,126,8], "rfc3676_8c.html#aae9c55042003c431c7a004bab1f93860":[2,0,126,2], "rfc3676_8c.html#aafc5472c7687d8941a25999aa30d2be4":[2,0,126,15], "rfc3676_8c.html#accd9e2230903403065c98b39900c746d":[2,0,126,5], "rfc3676_8c.html#ad1b1f1283fe92b91d865d8b00183f3e8":[2,0,126,3], "rfc3676_8c.html#adc6a5cc71d87432efb771f495c6efb9c":[2,0,126,11], "rfc3676_8c.html#ae72a662cae766d5a2de536c96685f046":[2,0,126,17], "rfc3676_8c.html#ae80c6b55541960f57f67f4ea3e4467e8":[2,0,126,13], "rfc3676_8c.html#af18144e8c3e804270f048d2cb40e1f7b":[2,0,126,7], "rfc3676_8c.html#af68b25d42671ff7d158cd8c039add61d":[2,0,126,6], "rfc3676_8c_source.html":[2,0,126], "rfc3676_8h.html":[2,0,127], "rfc3676_8h.html#a1a3abb7fcf3409cd1fe345fd20eee6a9":[2,0,127,0], "rfc3676_8h.html#a47bfc67ef302e9b51cee14c713a70f35":[2,0,127,3], "rfc3676_8h.html#a5be5171c37ea30b3ff53c2339daba4d2":[2,0,127,7], "rfc3676_8h.html#a9cd1b3af0b88c1d0179e890b444c5be0":[2,0,127,5], "rfc3676_8h.html#aafc5472c7687d8941a25999aa30d2be4":[2,0,127,4], "rfc3676_8h.html#adc6a5cc71d87432efb771f495c6efb9c":[2,0,127,1], "rfc3676_8h.html#ae72a662cae766d5a2de536c96685f046":[2,0,127,6], "rfc3676_8h.html#ae80c6b55541960f57f67f4ea3e4467e8":[2,0,127,2], "rfc3676_8h_source.html":[2,0,127], "rocksdb_8c.html":[2,0,27,6], "rocksdb_8c.html#a25a9b116ea49135eee7780a0f78df1a2":[2,0,27,6,2], "rocksdb_8c.html#a3c5dc76edd4687480da0add4652582c5":[2,0,27,6,3], "rocksdb_8c.html#a56bcb2bb3afc459331ce6d4425d352db":[2,0,27,6,7], "rocksdb_8c.html#a67e2c415f2cd32951268d623ec9d055b":[2,0,27,6,6], "rocksdb_8c.html#a7a5d3f954de08403a1f7597cdc030a9f":[2,0,27,6,8], "rocksdb_8c.html#a92d9878041c9c09243f41d6233df6a03":[2,0,27,6,1], "rocksdb_8c.html#aa79687f4045daa903404222475340177":[2,0,27,6,5], "rocksdb_8c.html#adb155cb0de6af36ca6f7ae194663a0f2":[2,0,27,6,4], "rocksdb_8c_source.html":[2,0,27,6], "sasl_8c.html":[2,0,8,11], "sasl_8c.html#a187170c6d889153e49321cc01ee59dab":[2,0,8,11,9], "sasl_8c.html#a19c3688c37fc56800b64f982a0e41e28":[2,0,8,11,20], "sasl_8c.html#a1ca034422dab598e155db6ac83ebefc2":[2,0,8,11,1], "sasl_8c.html#a27f79aa92f9ee0eff38ba8ba9b783c15":[2,0,8,11,8], "sasl_8c.html#a31945ebcc56eca548dc53917f31c0d4b":[2,0,8,11,22] };
import React, { Component } from 'react'; import { Tooltip, Popover } from 'antd'; import Linkify from 'react-linkify'; import PopoverContent from './PopoverContent'; // This is the order in which the statuses are displayed in the cell: const status_order = ['BAD', 'GOOD', 'STANDBY', 'EXCLUDED', 'NOTSET', 'EMPTY']; const status_colors_and_text = { BAD: { backgroundColor: 'red', text: 'white', fontSize: '1em', }, GOOD: { backgroundColor: 'green', text: 'white', fontSize: '1em', }, STANDBY: { backgroundColor: 'yellow', text: 'black', fontSize: '1em', }, EXCLUDED: { backgroundColor: 'grey', text: 'white', fontSize: '0.85em', }, NOTSET: { backgroundColor: 'white', text: 'black', fontSize: '1em', }, EMPTY: { backgroundColor: 'black', text: 'black', fontSize: '1em', }, INSIG: { backgroundColor: 'white', text: 'black', fontSize: '1em', }, }; const linkifyTarget = (href, text, key) => ( <a href={href} key={key} target="_blank"> {text} </a> ); class Status extends Component { render() { const { run, triplet_summary, significant, run_number, dataset_name, component, } = this.props; let run_stop_reason = ''; if (triplet_summary) { const { comments, causes } = triplet_summary; const statuses = { ...triplet_summary }; // Stop reason is displayed on hover in CMS component if (run && component === 'cms-cms' && run.rr_attributes.stop_reason) { run_stop_reason = `Stop reason: ${run.rr_attributes.stop_reason} -- `; } const statuses_present = []; delete statuses.comments; delete statuses.causes; // Order the array according to status_order for (const [status, number_of_lumisections] of Object.entries(statuses)) { if (number_of_lumisections > 0) { statuses_present.push(status); } } statuses_present.sort((a, b) => { if (status_order.indexOf(b) === -1) { return -1; } return status_order.indexOf(a) - status_order.indexOf(b); }); return ( <Popover placement="top" content={ <PopoverContent run_number={run_number} dataset_name={dataset_name} component={component} triplet_summary={triplet_summary} /> } trigger="click" > <Popover placement="top" content={ <Linkify componentDecorator={linkifyTarget}> {run_stop_reason} {comments.join(' , ')} </Linkify> } // We use the length as conditional, because if there are no comments, we want no automatica popover on hover trigger={comments.length || run_stop_reason ? 'hover' : ''} > <div style={{ textAlign: 'center', position: 'relative', cursor: 'pointer', }} title={comments.join(',')} > {comments.length > 0 && ( <span> <span style={{ position: 'absolute', borderLeft: '16px solid blue', borderBottom: '16px solid transparent', zIndex: '100', left: '0', top: '0', }} /> <span style={{ position: 'absolute', borderLeft: '17px solid transparent', borderBottom: '16px solid blue', zIndex: '100', right: '0', bottom: '0', }} /> </span> )} {significant ? ( <div style={{ position: 'relative' }}> {statuses_present.map((status, index) => { const length = statuses_present.length; if (status_colors_and_text[status]) { const { backgroundColor, text, fontSize, } = status_colors_and_text[status]; return ( <div className={`${index > 0 && 'status_container'}`} key={status} style={{ display: 'inline-block', backgroundColor, width: `${100 / length}%`, }} > <span className="status" style={{ color: text, fontSize, }} > {length === 1 ? status : status[0]} </span> <style jsx>{` .status_container:before { content: ''; position: absolute; left: ${index * (100 / length) - 5}%; border-right: 3px solid ${backgroundColor}; border-top: 17px solid transparent; } `}</style> </div> ); } return ( <span key={status} style={{ backgroundColor: 'white', }} > <span style={{ color: 'black' }}>{status}</span> </span> ); })} </div> ) : ( <div style={{ backgroundColor: status_colors_and_text['INSIG'].backgroundColor, }} > <span style={{ color: status_colors_and_text['INSIG'].text, }} > INSIG. </span> </div> )} </div> </Popover> </Popover> ); } return <div>No Lumisection data in this run</div>; } } export default Status;
import React from 'react' import PropTypes from 'prop-types' import { browserHistory } from 'react-router' // redux import { bindActionCreators } from 'redux' import { connect } from 'react-redux' // sections components import ChangePasswordForm from './components/ChangePasswordForm' import {Button} from '../components/controls/SemanticControls' import { FormError } from '../components/forms/FormError' import {createTranslate} from '../../locales/translate' // actions and selectors import { ActionCreators as AppActions } from '../../modules/app/actions' import { ActionCreators as MyAccountActions } from '../../modules/my-account/actions' import MyAccountSelectors from '../../modules/my-account/selectors' import {getLocale} from '../../modules/app/selectors' const labelNamespace = 'accounts' const mapDispatchToProps = (dispatch) => { return { actions: bindActionCreators(MyAccountActions, dispatch), appActions: bindActionCreators(AppActions, dispatch) } } class ChangePasswordPage extends React.PureComponent { constructor (props) { super(props) this.handleSubmit = this.handleSubmit.bind(this) this.message = createTranslate(labelNamespace, this) } handleSubmit () { const notify = this.props.appActions.notify this.props.actions.submitChangePassword(this.props.changePasswordForm, (entity) => { browserHistory.goBack() notify('common.save', 'common.saved') }) } handleCancel () { browserHistory.goBack() } render () { const {canSave, error, locale} = this.props return ( <div> <h1>{this.message('changePassword')}</h1> <FormError error={error} locale={locale} /> <ChangePasswordForm locale={locale} /> <Button disabled={!canSave} onClick={this.handleSubmit} primary className="mr-2"> {this.message('save', 'common')} </Button> <Button onClick={this.handleCancel}> {this.message('cancel', 'common')} </Button> </div> ) } } const mapStateToProps = (state) => { const props = { changePasswordForm: MyAccountSelectors.getChangePasswordForm(state), canSave: MyAccountSelectors.canSaveNewPassword(state), error: MyAccountSelectors.getChangePasswordError(state), locale: getLocale(state) } return props } ChangePasswordPage.propTypes = { changePasswordForm: PropTypes.object, canSave: PropTypes.bool.isRequired, error: PropTypes.object, locale: PropTypes.string.isRequired } const ConnectedChangePasswordPage = connect(mapStateToProps, mapDispatchToProps)(ChangePasswordPage) export default ConnectedChangePasswordPage
import { GET_CLASSES, GET_MARKAS, GET_MODELS } from "../types"; const initialState = { classes:[], markas:[], models:[] }; export const filterDataReducer = (state=initialState,action) =>{ switch (action.type){ case GET_CLASSES: return { ...state, classes: [...action.payload] }; case GET_MARKAS:{ return { ...state, markas:[ ...action.payload ] } } case GET_MODELS:{ return { ...state, models:[ ...action.payload ] } } } return state }
/** * Title: Notifications library * Description: Important functions to notify user * Author: Samin Yasar * Date: 31/October/2021 */ // Dependencies const https = require("https"); const config = require("./config"); // Module scaffolding const notifications = {}; // Function to send sms by using twilio api notifications.sendTwilioSms = (phone, msg, callback) => { // input validation const expressionOfPhone = /(^\+88)01(\d{9})/gi; const phoneNumber = typeof phone === "string" && expressionOfPhone.test(phone.trim()) ? phone.trim() : null; const message = typeof msg === "string" && msg.trim().length > 0 && msg.trim().length <= 1600 ? msg.trim() : null; if (phoneNumber && message) { // Configure the twilio request const payload = { From: config.twilio.fromPhoneNumber, To: phoneNumber, Body: message, }; // stringify the payload const payloadString = JSON.stringify(payload); // configure the https const requestDetails = { hostname: "api.twilio.com", method: "POST", path: `/2010-04-01/Accounts/${config.twilio.accountSid}/Messages.json`, auth: `${config.twilio.accountSid}:${config.twilio.authToken}`, headers: { "Content-Type": "application/x-www-form-urlencoded", }, }; // Instantiate the request object const req = https.request(requestDetails, (res) => { const { statusCode } = res; if (statusCode === 200 || statusCode === 201) { callback(false); } else { callback(`Status code returned was ${statusCode}`); } }); // Handle error req.on("error", (error) => { callback(error); }); // Write payload in request object req.write(payloadString); req.end(); } else { callback("Please provide a phone number & a message."); } }; // notifications.sendTwilioSms("+8801830027750", "Hello Nizam", (err) => { // console.log(`Error: ${err}`); // }); // Export module module.exports = notifications;
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { addItem } from '../actions' class AddItems extends Component { constructor(){ super(); this.state = { inputText: "" } } handleInput = (e) => { this.setState({ inputText: e.target.value }) } render(){ return ( <div className = "input__field"> <input type = "text" onChange = {(e) => this.handleInput(e)} value = {this.state.inputText} placeholder="Add an item"></input> <button className="button-primary" onClick = {()=>this.props.dispatch(addItem(this.state.inputText))}>Add Bag</button> </div> ) } } export default connect()(AddItems);
// To contain the Google API map JS var issLocation = {}; // initiate empty lat-long object var issLat = 45.5163719; // code fellows latitude var issLng = -122.6765228; // code fellows longitude var map; // google map object var issLocRequests = 0; // counts every time new location is recieved var parkedDataIss; // Holds lat-long obj var reticleMarker; var reticleImage; //iss png var needMarker = false; var mapOptions = { center: {lat: issLat, lng: issLng}, zoom: 5, mapTypeId: 'satellite', draggable: false, scrollwheel: false, } function initMap() { geocoder = new google.maps.Geocoder(); map = new google.maps.Map(document.getElementById('mapCanvas'), mapOptions); } // Recieves the ISS location from JSONP function findISS() { var script = document.createElement('script'); script.src = 'http://api.open-notify.org/iss-now.json?callback=issLoc' document.head.appendChild(script); // console.log("Iss Location updated"); script.parentNode.removeChild(script); // console.log("Iss location script cleared"); issLocRequests++; } // ISS location data is stored in this function issLoc(data) { issLat = data.iss_position.latitude; issLng = data.iss_position.longitude; issLocation = data; parkedDataIss = new google.maps.LatLng(issLat, issLng); map.panTo(new google.maps.LatLng(issLat, issLng)); // console.log("issLocation"); document.getElementById("theISSIsLocatedLng").textContent = "Latitude: " + issLat; document.getElementById("theISSIsLocatedLat").textContent = "Longitude: " + issLng; if (!needMarker) { setMarker(); needMarker = true; } } //Gets new ISS data and sets map center every 5 seconds var locationTimer = setInterval(findISS, 5000); function setMarker() { reticleImage = new google.maps.MarkerImage( 'img/ship.png', // marker image new google.maps.Size(93, 93), // marker size new google.maps.Point(0, 0), // marker origin new google.maps.Point(32, 32)); // marker anchor point var reticleShape = { coords: [32, 32, 32, 32], // 1px type: 'rect' // rectangle }; console.log("blocked"); reticleMarker = new google.maps.Marker({ position: parkedDataIss, map: map, icon: reticleImage, shape: reticleShape, optimized: false, zIndex: 5 }); google.maps.event.addListener(map, 'bounds_changed', function () { reticleMarker.setPosition(map.getCenter()); }); } console.log("unseen");
Ext.require('Ext.panel.Panel'); Ext.define ( 'FPT.view.helper.Strategy' , { extend : 'Ext.panel.Panel' , alias : 'widget.strategy' , layout: { type: 'vbox', align: 'stretch' } , initComponent: function () { this.addListener("expand", this.after ); this.callParent(arguments); this.add(Ext.create('FPT.view.helper.Hints', { data: this.data.data.hints, flex: 1 })); } , after: function () { refreshLinks(); } } );
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { setTokenAccess } from '../actions/actionCreators'; class Home extends Component { componentDidMount() { var { location } = this.props; var token = location.hash.split('#access_token=')[1]; //let code = new URLSearchParams(location.search).get('code'); //for code, no token; if(token && !this.props.token) this.props.setToken(token); } render () { return ( <main> <p> Estamos en el main y aquí no pasa mucho</p> </main> ); } } const mapStateToProps = (state) => { return { token: state.token }; }; const mapDispatchToProps = (dispatch) => { return { setToken: (token) => { dispatch(setTokenAccess(token)); } }; }; export default connect(mapStateToProps, mapDispatchToProps)(Home);
// import { niceFlash } from '../../anim/animSpeedWordUI'; // import Render from '../../render'; import GameObject from '../../core/gameObject'; import speedProfilerScript from './speedProfilerScript'; const speedProfiler = () => { let obj = new GameObject('speedProfiler'); obj.addScript(new speedProfilerScript()); return obj; } export default speedProfiler;
/** * * @memberof module:apeman/lib * @function doc */ "use strict"; var doc = require('apeman-doc'), done = require('./done'), signature = require('apeman-doc/signature.json'), pkg = require('apeman-doc/package.json'); var command = doc.bind(this); command.pkg = pkg; command.signature = signature; command.done = doc.done || done; module.exports = command;
var canvas = document.getElementById("canvas"); var date = document.getElementById("updatedDate"); var mouseBox = document.getElementById("mousePos"); var performance = document.getElementById("performance"); var processingUpdate = false; var ratio; var scaleRatio; var updateTwice = 2; var center = { x: 0, y: 0, dx: 0, //offsets for camera dy: 0 //offsets for camera }; var Game = function () { this.foods = []; this.hills = []; this.ants = []; this.player = {}; this.world; this.mousePos; this.updateMouse = false; this.click; this.updateClick = false; canvas.addEventListener('mousemove', function(evt) { var mousePos = game.getMousePos(canvas, evt); var x = Math.round(mousePos.x/scaleRatio + center.dx); var y = Math.round(mousePos.y/scaleRatio + center.dy); mouseBox.value = "x: " + x + ", y: " + y; game.mousePos = {x: x, y: y}; game.updateMouse = true; }, false); canvas.addEventListener('click', function(evt) { var mousePos = game.getMousePos(canvas, evt); var x = Math.round(mousePos.x/scaleRatio + center.dx); var y = Math.round(mousePos.y/scaleRatio + center.dy); mouseBox.value = "x: " + x + ", y: " + y; game.click = {x: x, y: y}; game.updateClick = true; }, false); document.addEventListener('keydown', function(e) { //using keyinput }, false); } Game.prototype.update = function(world, player, hills, ants, food) { processingUpdate = true; //single objects this.world = world; this.player = player; this.updateFood(food); this.hills = hills; this.ants = ants; processingUpdate = false; if(this.updateMouse) { sendMsg(encodeMsg(3, this.mousePos)); this.updateMouse = false; } if(this.updateClick) { sendMsg(encodeMsg(4, this.click)); this.updateClick = false; } } Game.prototype.updateFood = function(newFoods) { if(this.foods.length == 0){ //first update this.foods = newFoods; } //multiple changing objects/arrays var tempArray = []; for(var i = 0; i < this.foods.length; ++i) { var curr = this.foods[i]; curr.updated = false; for(var j = 0; j < newFoods.length; ++j) { var newF = newFoods[j]; if(curr.id == newF.id){ newF.found = true; curr.updated = true; var dist = getDist(curr.position.x, curr.position.y, newF.position.x, newF.position.y); if(dist > 1 || dist < -1){ curr.dist = dist; curr.destination = newF.position; } curr.isOrbiting = newF.isOrbiting; curr.size = newF.size; curr.value = newF.value; tempArray.push(curr); } //if we've searched all the current food didn't find a new food, add the new food to the list; if(i == this.foods.length - 1 && !newF.found) { tempArray.push(newF); } } } this.foods = tempArray; } Game.prototype.getMousePos = function (canvas, evt) { var rect = canvas.getBoundingClientRect(); return { x: evt.clientX - rect.left, y: evt.clientY - rect.top }; } Game.prototype.render = function(ctx) { this.renderHills(ctx); this.renderFoods(ctx); } Game.prototype.renderHills = function(ctx) { for(var i = 0; i < this.hills.length; ++i){ ctx.fillStyle="#FF0000"; ctx.beginPath(); ctx.arc(getXPos(this.hills[i].position.x), getYPos(this.hills[i].position.y), this.hills[i].radius, 0, Math.PI * 2); ctx.fill(); ctx.fillStyle="#11FF00"; ctx.fillRect(getXPos(this.hills[i].position.x), getYPos(this.hills[i].position.y),2,2); //HILL TEXT - NAME AND POSITION ON MAP RELATIVE TO PLAYER ctx.font = "7px Arial"; ctx.fillText(this.hills[i].playerNick, getXPos(this.hills[i].position.x) - 10, getYPos(this.hills[i].position.y) + 15); var xdif = this.hills[i].position.x - this.player.hill.position.x; var ydif = this.hills[i].position.y - this.player.hill.position.y; ctx.font = "6px Arial"; ctx.fillText("(x: " + xdif + ", y: " + ydif + ")", getXPos(this.hills[i].position.x) - 20, getYPos(this.hills[i].position.y) + 30); } } Game.prototype.renderFoods = function(ctx) { var food; for(var i = 0; i < this.foods.length; ++i){ if(this.foods[i] == undefined) { continue; } if(this.foods[i].dist != undefined && this.foods[i].dist > 1){ if(this.foods[i].isOrbiting) { this.foods[i].color = "white"; } moveLinear(this.foods[i].position, this.foods[i].destination, 1); } this.renderFood(ctx, this.foods[i]); } } Game.prototype.renderFood = function(ctx, food) { ctx.save();//SAVE BEFORE MOVING THE CONTEXT ctx.translate(getXPos(food.position.x - food.size/2), getYPos(food.position.y - food.size/2)); ctx.beginPath(); ctx.strokeStyle = "rgba(10, 10, 10, .2)"; ctx.rect(food.size/4, food.size/4, food.size/2, food.size/2); ctx.stroke(); ctx.closePath(); //SET THE MAIN COLOR: ctx.fillStyle= convertHex(food.color, 60); ctx.beginPath(); ctx.arc(food.size/2, food.size/2, food.size/4, 0, Math.PI * 2, true); ctx.shadowBlur = 10; ctx.shadowColor = "black"; ctx.fill(); ctx.closePath(); ctx.fillStyle = "black"; ctx.fillRect(food.size/2 - .5, food.size/2-.5, 1, 1); renderText(ctx, food.size, food.size/2, food.size/2, 4, "#11FF00"); ctx.restore();//RESTORE THE CONTEXT } function update(data) { if(!lastMsg) { return; } if(!game) { return; }; game.update(lastMsg.world, lastMsg.player, lastMsg.hill, null, lastMsg.food); } function render(lagOffset) { if(!game && game.player == undefined) { return; }; var ctx = (document.getElementById("canvas")).getContext("2d"); ctx.canvas.width = window.innerWidth; ctx.canvas.height = window.innerHeight; //ratio for screen. ratio = ctx.canvas.width/ctx.canvas.height; scaleRatio = ctx.canvas.width/game.player.viewBox.width; widthVsSightRatio = canvas.width/game.player.viewBox.width; heightVsSightRatio = canvas.height/game.player.viewBox.height; ctx.center = center; center.x = ctx.canvas.width / (2 * scaleRatio); center.y = ctx.canvas.height / (2 * scaleRatio); center.dx = game.player.position.x - center.x; center.dy = game.player.position.y - center.y; //ctx.scale(2,2); //ctx.translate(game.player.position.x, game.player.position.y); //clear screen //console.log(game.player.position.x + " " + game.player.position.y); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.scale(scaleRatio, scaleRatio); //center dot ctx.fillStyle="#33FF32"; ctx.fillRect(center.x, center.y, 2, 2); var negXSight = game.player.position.x - game.player.viewBox.width; var posXSight = game.player.position.x + game.player.viewBox.width; var negYSight = game.player.position.y - game.player.viewBox.height; var posYSight = game.player.position.y + game.player.viewBox.height; ctx.fillStyle="rgba(255, 0, 0, .5)"; if(negXSight < game.world.mapBorderLeft - 1) { ctx.fillStyle="rgba(255, 0, 0, .5)"; ctx.fillRect(0, 0, getXPos(0), ctx.canvas.height/scaleRatio); ctx.stroke(); } if(posXSight > game.world.mapBorderRight) { ctx.fillStyle="rgba(255, 0, 0, .5)"; ctx.fillRect(getXPos(game.world.mapBorderRight), 0, (ctx.canvas.width/scaleRatio) - getXPos(game.world.mapBorderRight), ctx.canvas.height/scaleRatio); ctx.stroke(); } if(negYSight < game.world.mapBorderTop - 1) { ctx.fillStyle="rgba(255, 0, 0, .5)"; ctx.fillRect(0, 0, (ctx.canvas.width/scaleRatio), getYPos(0)); ctx.stroke(); } if(posYSight > game.world.mapBorderBottom) { ctx.fillStyle="rgba(255, 0, 0, .5)"; ctx.fillRect(0, getYPos(game.world.mapBorderBottom), (ctx.canvas.width/scaleRatio), ctx.canvas.height/scaleRatio - getYPos(game.world.mapBorderBottom)); ctx.stroke(); } ctx.fillStyle="rgba(255, 255, 255, 1)"; //render game ctx.beginPath(); ctx.strokeStyle = "rgba(10, 10, 10, .8)"; ctx.rect(getXPos(game.player.viewBox.leftX), getYPos(game.player.viewBox.topY), game.player.viewBox.width, game.player.viewBox.height); ctx.stroke(); game.render(ctx); } function startGame() { if(isPause) { isPause = false; gameLoop(); } } function stopGame() { isPause = true; } //*** GAME LOOP ****/ //Set the frame rate var fps = 10, //Get the start time start = Date.now(), //Set the frame duration in milliseconds frameDuration = 1000 / fps, //Initialize the lag offset lag = 0, lastUpdated = 0, isPause = true; //Start the game loop function gameLoop() { if(isPause) { return; } requestAnimationFrame(gameLoop, canvas); //Calcuate the time that has elapsed since the last frame var current = Date.now(), elapsed = current - start; start = current; //Add the elapsed time to the lag counter lag += elapsed; //Update the frame if the lag counter is greater than or //equal to the frame duration while (lag >= frameDuration){ //Update the logic update(); //Reduce the lag counter by the frame duration lag -= frameDuration; } //Calculate the lag offset and use it to render the sprites var lagOffset = lag / frameDuration; render(lagOffset); //Frame data output: actualFps = Math.floor(1000 / elapsed); performance.value = "ms: " + elapsed + " fps: " + actualFps; performance.value += " lag: " + Math.floor(lag); performance.value += " offset: " + lagOffset; } function getXPos(x) { return (x - center.dx); } function getYPos(y) { return (y - center.dy); } function convertHex(hex,opacity){ hex = hex.replace('#',''); r = parseInt(hex.substring(0,2), 16); g = parseInt(hex.substring(2,4), 16); b = parseInt(hex.substring(4,6), 16); result = 'rgba('+r+','+g+','+b+','+opacity/100+')'; return result; } function renderText(ctx, text, x, y, size, color) { ctx.fillStyle = color; ctx.font = size+"px Arial"; var width = ctx.measureText(text).width; ctx.fillText(text, x - width/2, y + size/3); } //***** MATH STUFF function abs(x) { // Because Math.abs is slow return x < 0 ? -x : x; }; function moveLinear(position, destination, speed) { var dist = getDist(destination.x, destination.y, position.x, position.y); var angle = getAngle(destination.x, destination.y, position.x, position.y); var speed = Math.min(dist / 30, speed); position.x = position.x + speed * Math.sin(angle) position.y = position.y + speed * Math.cos(angle); } function getAngle(x1, y1, x2, y2) { var deltaY = y1 - y2; var deltaX = x1 - x2; return Math.atan2(deltaX, deltaY); }; function getDist(x1, y1, x2, y2) { // Use Pythagoras theorem var deltaX = this.abs(x1 - x2); var deltaY = this.abs(y1 - y2); return Math.sqrt(deltaX * deltaX + deltaY * deltaY); }; function rotatePoint(point, center, angle){ angle = (angle ) * (Math.PI/180); // Convert to radians var rotatedX = Math.cos(angle) * (point.x - center.x) - Math.sin(angle) * (point.y-center.y) + center.x; var rotatedY = Math.sin(angle) * (point.x - center.x) + Math.cos(angle) * (point.y - center.y) + center.y; return {x: rotatedX, y: rotatedY}; }
/** * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ app.controller('HomeCtrl', function($scope, $ionicModal, $timeout) { // With the new view caching in Ionic, Controllers are only called // when they are recreated or on app start, instead of every page change. // To listen for when this page is active (for example, to refresh data), // listen for the $ionicView.enter event: //$scope.$on('$ionicView.enter', function(e) { //}); // Form data for the login modal $scope.loginData = {}; // Create the login modal that we will use later $ionicModal.fromTemplateUrl('app/views/login.html', { scope: $scope }).then(function(modal) { $scope.modal = modal; }); // Triggered in the login modal to close it $scope.closeLogin = function() { $scope.modal.hide(); }; // Open the login modal $scope.login = function() { $scope.modal.show(); }; // Perform the login action when the user submits the login form $scope.doLogin = function() { console.log('Doing login', $scope.loginData); // Simulate a login delay. Remove this and replace with your login // code if using a login system $timeout(function() { $scope.closeLogin(); }, 1000); }; });
import './Comment.css' import React, { PureComponent} from 'react'; import { Link } from 'react-router-dom'; export default class Comment extends PureComponent{ render(){ const { comment } = this.props; return( <div className="comment"> <div className="comment__img-block"> <img className="comment__img" src="http://www.bce.lu/wp-content/uploads/2018/07/Picto_Traffic_User-100x100.png" alt=""/> </div> <div className="comment__text-block"> <div className="comment__info"> <span className="comment__name"> <Link to={`/users/${comment.user._id}`}>{comment.user.firstName} {comment.user.lastName}</Link> </span> <span className="comment__date">APRIL 18, 2017</span> <span className="comment__post"> <Link to={`/posts/${comment.post._id}`}>{comment.post.title}</Link> </span> </div> <p className="comment__text">{comment.text}</p> </div> </div> ) } }
import * as data from "./Background.json"; const Images = data.cards; export default Images;
Ext.define('Rally.ui.menu.bulk.Restore', { alias: 'widget.rallyrecordmenuitemrestore', extend: 'Rally.ui.menu.item.RecordMenuItem', mixins: { messageable: 'Rally.Messageable' }, config: { onBeforeAction: function(){ // console.log('onbeforeaction'); }, /** * @cfg {Function} onActionComplete a function called when the specified menu item action has completed * @param Rally.data.wsapi.Model[] onActionComplete.successfulRecords any successfully modified records * @param Rally.data.wsapi.Model[] onActionComplete.unsuccessfulRecords any records which failed to be updated */ onActionComplete: function(){ // console.log('onActionComplete'); }, text: 'Restore', handler: function () { this.restore(this.record); }, predicate: function (records) { var record = this.record; if (record.get('_type').toLowerCase() === 'hierarchicalrequirement'){ var re = new RegExp(this.cancelledPrefix); if (re.test(record.get('Name'))){ return true; } } if (/portfolioitem/.test(record.get('_type').toLowerCase())){ var state = record.get('State') && record.get('State').Name; if (state === this.canceledPortfolioStateName){ return true; } } return false; } }, restore: function(record){ var deferred = Ext.create('Deft.Deferred'); find = {ObjectID: record.get('ObjectID')}; if (record.get('_type') === 'hierarchicalrequirement'){ find.Name = record.get('Name'); find["_PreviousValues.Name"] = {$exists: true} } else { find.State= this.canceledPortfolioStateName, find["_PreviousValues.State"] = {$exists: true} } this.publish('maskUpdate','Searching History...'); this._fetchLookbackRecords({ find: find, fetch: ['ObjectID','Name', 'State','Release','PlanEstimate','ScheduleState','ToDo','Blocked','BlockedReason','_ValidFrom','_PreviousValues'], hydrate: ['State','Release'], sort: { "_ValidFrom": -1 } }).then({ success: this._fetchItemsInHierarchy, failure: this._reportError, scope: this }); // this.fireEvent('loadtree'); // me.publish('maskUpdate', 'Retrieving Data...'); // // var artifactTree = Ext.create('Rally.technicalservices.ArtifactTree',{ // portfolioItemTypes: this.portfolioItemTypes, // portfolioItemCanceledStates: this.portfolioItemCanceledStates, // canceledReleaseHash: this.canceledReleaseHash, // canceledScheduleState: this.canceledScheduleState, // canceledPrefix: this.canceledPrefix, // completedStates: this.completedStates, // listeners: { // treeloaded: function(tree){ // me.publish('maskUpdate', 'Restoring Items...'); // tree.restoreItems(); // }, // completed: function(batch){ // // me.fireEvent('copycomplete'); // me.publish('maskUpdate'); // deferred.resolve({ // record: record, // batch: batch // }); // }, // error: function(errorMsg){ // // me.fireEvent('copyerror',{record: record, errorMessage: errorMsg}); // me.publish('maskUpdate'); // deferred.resolve({record: record, errorMessage: errorMsg}); // }, // scope: this // } // }); // // artifactTree.load(record); return deferred; }, _fetchItemsInHierarchy: function(records){ if (records && records.length > 0){ var validFrom = records[0].get('_ValidFrom'); this._fetchLookbackRecords({ find: { _TypeHierarchy: {$in: ['HierarchicalRequirement','Task','PortfolioItem']}, _ItemHierarchy: records[0].get('ObjectID'), _ValidFrom: {$gte: validFrom} }, fetch: ['_TypeHierarchy', 'ObjectID', 'Name', 'State', 'Release', 'PlanEstimate', 'ScheduleState', 'ToDo', 'Blocked', 'BlockedReason', '_ValidFrom', '_PreviousValues.ScheduleState', '_PreviousValues.Name', '_PreviousValues.Release', '_PreviousValues.State', '_PreviousValues.Blocked', '_PreviousValues.BlockedReason', '_PreviousValues.PlanEstimate', '_PreviousValues.Release', '_PreviousValues.ToDo'], hydrate: ['State','_TypeHierarchy','_PreviousValues.ScheduleState'], sort: { "_ValidFrom": -1 } }).then({ success: function(snapshots){ var taskUpdates = {}, storyUpdates = {}, portfolioItemUpdates = {}; if (snapshots.length === 0){ this.publish('bulkActionComplete'); this.publish('maskUpdate',false); this.publish('statusUpdate','No history found. Try again in a few minutes.'); return; } Ext.Array.each(snapshots, function(s){ var prevValues = s.get('_PreviousValues') || {}, oid = s.get('ObjectID'); var type = s.get('_TypeHierarchy').slice(-1)[0].toLowerCase(); console.log('s',s.getData(), type,prevValues,s.get('_ValidFrom')); if (/portfolioitem/.test(type)){ if (s.get("_PreviousValues.State") || s.get('_PreviousValues.State') === null){ portfolioItemUpdates[oid] = { State: s.get('_PreviousValues.State') } } } if (type === 'hierarchicalrequirement'){ if (s.get('_PreviousValues.Name')){ storyUpdates[oid] = storyUpdates[oid] || {}; storyUpdates[oid].Name = s.get('_PreviousValues.Name'); } if (s.get('_PreviousValues.Release') || s.get('_PreviousValues.Release') === null){ storyUpdates[oid] = storyUpdates[oid] || {}; storyUpdates[oid].Release = s.get('_PreviousValues.Release') && 'release/' + s.get('_PreviousValues.Release') || null; console.log('rel',storyUpdates[oid].Release) } if (s.get('_PreviousValues.PlanEstimate') || s.get('_PreviousValues.PlanEstimate') === null){ storyUpdates[oid] = storyUpdates[oid] || {}; storyUpdates[oid].PlanEstimate = s.get('_PreviousValues.PlanEstimate'); } if (s.get('_PreviousValues.ScheduleState')){ storyUpdates[oid] = storyUpdates[oid] || {}; storyUpdates[oid].ScheduleState = s.get('_PreviousValues.ScheduleState'); } if (s.get('_PreviousValues.Blocked')){ storyUpdates[oid] = storyUpdates[oid] || {}; storyUpdates[oid].Blocked = s.get('_PreviousValues.Blocked'); } if (s.get('_PreviousValues.BlockedReason')){ storyUpdates[oid] = storyUpdates[oid] || {}; storyUpdates[oid].BlockedReason = s.get('_PreviousValues.BlockedReason'); } } if (type === 'task'){ if (s.get('_PreviousValues.ToDo')){ taskUpdates[oid] = { ToDo: s.get('_PreviousValues.ToDo') || 0 }; } } }); this.updateObjects(portfolioItemUpdates,storyUpdates,taskUpdates); }, failure: this._reportError, scope: this }); } }, updateObjects: function(portfolioUpdates, storyUpdates, taskUpdates){ var portfolioConfig = this._getConfig(portfolioUpdates,'PortfolioItem'), storyConfig = this._getConfig(storyUpdates, 'HierarchicalRequirement'), taskConfig = this._getConfig(taskUpdates, 'Task'), promises = []; promises.push(this._fetchWsapiRecords(portfolioConfig)); promises.push(this._fetchWsapiRecords(storyConfig)); promises.push(this._fetchWsapiRecords(taskConfig)); this.publish('maskUpdate','Restoring Objects...'); Deft.Promise.all(promises).then({ success: function(results){ var batchStore = Ext.create('Rally.data.wsapi.batch.Store',{ data: _.flatten(results) }); var recordsUpdated = []; Ext.Array.each(results[2],function(r){ var fields = taskUpdates[r.get('ObjectID')]; if (fields){ recordsUpdated.push(r); Ext.Object.each(fields, function(key,val){ r.set(key,val); }); r.set('__changedFields', fields); } }); Ext.Array.each(results[1],function(r){ var fields = storyUpdates[r.get('ObjectID')]; if (fields){ recordsUpdated.push(r); Ext.Object.each(fields, function(key,val){ r.set(key,val); }); r.set('__changedFields', fields); } }); Ext.Array.each(results[0],function(r){ var fields = portfolioUpdates[r.get('ObjectID')]; if (fields){ recordsUpdated.push(r); Ext.Object.each(fields, function(key,val){ r.set(key,val); }); r.set('__changedFields', fields); } }); batchStore.sync({ success: function(){ var msg = Ext.String.format('{0} Records Restored.',recordsUpdated.length); this.publish('bulkActionComplete',msg, true, recordsUpdated, _.flatten(results)); }, scope: this, failure: this._reportError }).always(function(){ this.publish('maskUpdate', false); },this); }, failure: this._reportError, scope: this }); }, _getConfig: function(updates, type){ var filters =Ext.Array.map(Ext.Object.getKeys(updates), function(oid,fields){ return { property: 'ObjectID', value: oid } }); if (filters.length === 0){ filters = [{ property: 'ObjectID', value: 0 }]; } if (filters.length > 1){ filters = Rally.data.wsapi.Filter.or(filters) } return { model: type, fetch: ['ObjectID'], filters: filters }; }, _reportError: function(msg){ this.publish('bulkActionError', msg); }, _fetchWsapiRecords: function(config){ var deferred = Ext.create('Deft.Deferred'); if (!config.limit){ config.limit = "Infinity"; } if (!config.enablePostGet) {config.enablePostGet = true; } Ext.create('Rally.data.wsapi.Store',config).load({ callback: function(records,operation){ if (operation.wasSuccessful()){ deferred.resolve(records); } else { deferred.reject(operation.error.errors.join(",")); } } }); return deferred.promise; }, _fetchLookbackRecords: function(config){ var deferred = Ext.create('Deft.Deferred'); if (!config.limit){ config.limit = "Infinity"; } config.removeUnauthorizedSnapshots = true; Ext.create('Rally.data.lookback.SnapshotStore',config).load({ callback: function(records,operation){ if (operation.wasSuccessful()){ deferred.resolve(records); } else { deferred.reject(operation.error.errors.join(",")); } } }); return deferred.promise; } });
var dgram = require('dgram') var fs = require('fs') var ansi = require('ansi') var spawn = require('child_process').spawn var readline = require('readline') var url = require('url') var socket = dgram.createSocket('udp4') var port = 12346 module.exports = function(opts) { if (!opts.them) opts.them = 'them' if (!opts.target) opts.target = 'udp://0.0.0.0:9999' if (!opts.me) opts.me = 'you' if (!opts.local) opts.local = 'udp://0.0.0.0:9999' var target = url.parse(opts.target) var me = url.parse(opts.local) var rl = readline.createInterface(process.stdin, process.stdout) rl.clearLine = function() { rl.write(null, {ctrl: true, name: 'u'}) } var cursor = ansi(rl.output) rl.setPrompt('', 0) rl.prompt() // sending message rl.on('line', function(line) { rl.clearLine() rl.prompt() var message = line.trim() if (message === '') return var buf = new Buffer(message) socket.send(buf, 0, buf.length, target.port, target.hostname, function(err, bytes) { if (err && err.code === 'ENOTFOUND') return console.log('could not deliver message :(') else if (err) console.log('error!', err, err.message) cursor.white().bg.black().write(' ' + opts.me + ' ') cursor.reset().bg.reset().write(' ' + buf.toString() + '\n') }) }) // receiving message socket.on("message", function (msg, rinfo) { cursor.black().bg.cyan().write(' ' + opts.them + ' ') cursor.blue().bg.reset().write(' ' + msg.toString()) cursor.write('\u0007\n') cursor.reset() spawn("/usr/bin/afplay", ["/System/Library/Sounds/Submarine.aiff"]) }) socket.on('error', function(e) { // no op }) // open socket socket.bind(me.port) socket.on('listening', function () { var address = socket.address() console.log('listening on udp://' + address.address + ':' + address.port) console.log('sending to udp://' + target.hostname + ':' + target.port) console.log('type message + hit enter to send') socket.setMulticastTTL(16) }) }
var structMixChain = [ [ "cl", "structMixChain.html#a4e71bdf3ad655951947d856c3c09ff15", null ], [ "ch", "structMixChain.html#a50d11c4c52a1c1bde0da1135cf1ca90c", null ] ];
import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom' class ShowListOfBlog extends React.Component{ componentDidMount(){ this.props.getAllBlogs() } render(){ const listItems = this.props.state.blog.map((item)=>{ return( <li key={item._id} id={item._id}><input type="checkbox"/> <Link to={`/blogs/${item._id}`}>{item.blogHeader}</Link> <button onClick={(event) => this.props.deleteList(event)} >X</button></li> ) }); return( <div> {listItems} </div> ) } } const mapStateToProps =(state) => { return{ state: state } } const mapDispatchToProps = (dispatch) =>{ return{ deleteList: (event) =>{ dispatch({ type: "deleteBlogs", eventId: event.target.parentNode.id }) }, getAllBlogs: () =>{ fetch('/api/blogs/').then(res => res.json()) .then(data =>{ dispatch({ type: "getAllBlogs", payload: data })} ); } } } export default connect(mapStateToProps, mapDispatchToProps)(ShowListOfBlog);
'use strict'; var React = require('react'); var Card = require('../../card'); var Table = require('./table'); var skill = require('../../../sw2/skill'); var Skill = React.createClass({ render: function () { var data = this.props.data; var readOnly = this.props.readOnly; var onChange = this.props.onChange; var onAppend = this.props.onAppend; var onRemove = this.props.onRemove; var skills = skill.list.map(function (skill) { return { text: ( <span className='skill'> <span className='desc' style={{ display: 'inline-block', color: 'lightgray', width: '64px' }}>{skill.type + skill.table}</span> <span className='name'>{skill.name}</span> </span> ), payload: skill.name }; }); return ( <Card className="skill"> <Table data={data} path="skills" cols={[ {path: 'name', label: '技能', type: 'select', options: skills}, {path: 'level', label: 'レベル', type: 'number'}, {path: 'magic_power', label: '魔力', type: 'number', readOnly: true}, {path: 'next', label: '次', type: 'number', readOnly: true}, {path: 'total', label: '累計', type: 'number', readOnly: true} ]} onChange={onChange} onAppend={onAppend} onRemove={onRemove} /> </Card> ); } }); module.exports = Skill;
/* eslint-disable no-console,prefer-reflect */ const path = require('path'); const assert = require('assert'); const tc = require('text-censor') module.exports = class extends think.Controller { constructor(ctx) { super(ctx); // 从缓存中获取机构列表 this.resource = this.getResource(); this.id = this.getId(); assert(think.isFunction(this.model), 'this.model must be a function'); this.modelInstance = this.model(this.resource); this.tc = tc } async __before() { const appId = this.get('appId') if (think.isEmpty(appId)) { return this.fail('App params is Empty.') } const isDeal = await this.dealApp(appId) if (!isDeal) { return this.fail('App is Not found') } } /** * 处理并检测 app * @param appId * @returns {Promise.<boolean>} */ async dealApp (appId) { const appsModel = this.model('apps') const app = await appsModel.get(appId) if (!think.isEmpty(app)) { this.app = app this.appId = app.id this.cachePrefix = 'picker_' + this.appId + '_' this.modelInstance = this.model(this.resource, {appId: this.appId}) this.options = await this.model('options', {appId: this.appId}).get() return true } return false } async getRoles (user) {} /** * get resource * @return {String} [resource name] */ getResource() { const filename = this.__filename || __filename; const last = filename.lastIndexOf(path.sep); return filename.substr(last + 1, filename.length - last - 4); } getId() { const id = this.get('id'); if (id && (think.isString(id) || think.isNumber(id))) { return id; } const last = this.ctx.path.split('/').slice(-1)[0]; if (last !== this.resource) { return last; } return ''; } __call() { return this.fail() } }
alert("I'm external");
import Letter from '../../../models/letter'; export default (letter, args, { user, anonymousId }) => { if ( letter.toEmail === user.email || letter.fromAnonymousId === anonymousId || letter.fromEmail === user.email ) { return letter.thankYouMessage; } };
import { exportAllDeclaration } from "@babel/types"; describe("Home/root test", () => { beforeEach(() => { cy.visit("http://localhost:3000/topics/football"); }); it("renders the page without crashing", () => { expect(true).to.be.true; }); it("renders the title", () => { cy.get(".header__div").contains("Welcome to NC News"); }); it("renders the username input", () => { cy.get(":nth-child(1) > [data-cy=Login_Username]").type("text"); }); it("renders the password input", () => { cy.get(":nth-child(1) > [data-cy=Login_Username]").type("password"); }); it("renders the submit button with click function", () => { cy.get("[data-cy=Login_submit]").click(); }); it("renders a functional Home link", () => { cy.get("[data-cy=Home]").click(); cy.url().should("equal", "http://localhost:3000/"); }); it("renders a functional Coding topics link", () => { cy.get("[data-cy=coding]").click(); cy.url().should("equal", "http://localhost:3000/topics/coding"); }); it("renders a functional Football topics link", () => { cy.get("[data-cy=football]").click(); cy.url().should("equal", "http://localhost:3000/topics/football"); }); it("renders a functional Cooking topics link", () => { cy.get("[data-cy=cooking]").click(); cy.url().should("equal", "http://localhost:3000/topics/cooking"); }); it("renders h2 header with desired content", () => { cy.get("h2").contains("Articles on football"); }); it("display article has a function click button", () => { cy.get(".DisplayArticles__button").click(); }); it("displayed articles list have clickable links", () => { cy.get( ":nth-child(1) > .ArticleCard__div > :nth-child(2) > .ArticleCard__Link > h3" ).click(); }); it("displayed articles have 'votes' count entry", () => { cy.get( ":nth-child(1) > .ArticleCard__div > .ArticleCard__div--votes > :nth-child(1) > :nth-child(2) > p" ).contains("Votes"); }); it("displayed articles have created 'by' author entry", () => { cy.get( ":nth-child(1) > .ArticleCard__div > :nth-child(2) > :nth-child(2)" ).contains("by"); }); it("displayed articles have 'Posted On' entry", () => { cy.get( ":nth-child(1) > .ArticleCard__div > :nth-child(2) > :nth-child(3)" ).contains("Posted on"); }); it("displayed articles have 'Comments count' entry", () => { cy.get( ":nth-child(1) > .ArticleCard__div > :nth-child(2) > :nth-child(4)" ).contains("Comments count"); }); it("up-vote button has click function", () => { cy.get( ":nth-child(1) > .ArticleCard__div > .ArticleCard__div--votes > :nth-child(1) > :nth-child(1) > .Votes__button > .fas" ).click(); }); it("down-vote button has click function", () => { cy.get( ":nth-child(1) > .ArticleCard__div > .ArticleCard__div--votes > :nth-child(1) > :nth-child(3) > .Votes__button > .fas" ).click(); }); });
const G = 9.8; const START_SPEED = 90; const START_ANGLE = 45; let centerX = 250; let centerY = 250; let radius = 20; let Y_DIR = 1; class Vector { constructor(v, angle) { this.v = v; this.a = angle * (Math.PI / 180); } } class Ball { constructor(x, y, r, velocity) { this.x = x; this.y = y; this.r = r; this.velocity = velocity; this.t0 = Date.now(); this.x0 = x; this.y0 = y; firstDrawBall(this.x, this.y, this.r); this.ball = ball; } draw() { drawBall(this.x, this.y); } currentVelocity() { let v0 = this.velocity.v; let t = (Date.now() - this.t0) / 100; //todo let alpha = this.velocity.a; return Math.sqrt(Math.pow(v0, 2) - 2 * v0 * G * t * Math.sin(alpha) + Math.pow(G * t, 2)); } currentAngle() { let v0 = this.velocity.v; let t = (Date.now() - this.t0) / 100; let alpha = this.velocity.a; //console.log("currentAngle", v0, t, alpha*180/Math.PI, Math.cos(alpha)); let angle = Math.atan((v0 * Math.sin(alpha) - G * t) / (v0 * Math.cos(alpha))); if (Math.cos(alpha) < 0.0001 || Math.cos(alpha) > -0.0001) { return alpha; } if (Math.cos(alpha) < 0) { angle += Math.PI; } return angle; } bounce(angle) { this.velocity.v = this.currentVelocity(); this.velocity.a = 2 * Math.PI - this.currentAngle() + 2 * Math.atan(angle); this.t0 = Date.now(); this.x0 = this.x; this.y0 = this.y; } collides(o) { let distance = Math.sqrt(Math.pow(this.x - o.position.z, 2) + Math.pow(this.y - o.position.y, 2)); return distance <= this.r + o.radius; } move(borderY, borderX) { let v0 = this.velocity.v; let alpha = this.velocity.a; let t = (Date.now() - this.t0) / 100; this.x = this.x0 + v0 * t * Math.cos(alpha); this.y = this.y0 + Y_DIR * (v0 * t * Math.sin(alpha) - 0.5 * G * Math.pow(t, 2)); let angle = Math.atan((v0 * Math.sin(alpha) - G * t) / (v0 * Math.cos(alpha))); if (Math.cos(alpha) < 0) { angle += Math.PI; } if ((this.x + this.r >= borderX && Math.cos(alpha) > 0) || (this.x - this.r <= 0 && Math.cos(alpha) < 0)) { this.bounce(); this.velocity.a = Math.PI - angle; } else if ((this.y - this.r <= 0 && Y_DIR * Math.sin(angle) < 0) || ( this.y + this.r >= borderY && Y_DIR * Math.sin(angle) > 0)) { this.bounce(0); } } }
import api from '../../../Api/Django' export const GET_ACREEDORES_SUCCESS = 'GET_ACREEDORES_SUCCESS' export const getAcreedoresSuccess=(items)=>{ return { type:GET_ACREEDORES_SUCCESS, items } } export const getAcreedores = () => (dispatch, getState)=>{ return api.getAcreedores() .then(r=>{ dispatch(getAcreedoresSuccess(r)) }).catch(e=>{ throw e }) } export const NEW_ACREEDOR_SUCCESS = 'NEW_ACREEDOR_SUCCESS' export const newAcreedorSuccess = (item) =>{ return { type:NEW_ACREEDOR_SUCCESS, item } } export const newAcreedor=(item)=>(dispatch, getState)=>{ return api.newAcreedor(item) .then(r=>{ dispatch(newAcreedorSuccess(r)) }).catch(e=>{ throw e }) } export const EDIT_ACREEDOR_SUCCESS = 'EDIT_ACREEDOR_SUCCESS' export const editAcreedorSucess=(item)=>{ return { type:EDIT_ACREEDOR_SUCCESS, item } } export const editAcreedor=(item)=>(dispatch, getState)=>{ return api.editAcreedor(item) .then(r=>{ dispatch(editAcreedorSucess(r)) }).catch(e=>{ throw e }) } export const DELETE_ACREEDOR_SUCCESS = 'DELETE_ACREEDOR_SUCCESS' export const deleteAcreedorSuccess = (item)=>{ return { type:DELETE_ACREEDOR_SUCCESS, item } } export const deleteAcreedor=(item)=>(dispatch, getState)=>{ return api.deleteAcreedor(item) .then(r=>{ dispatch(deleteAcreedorSuccess(r)) }) }
class Node { constructor(val) { this.val = val; this.next = null } } class Stack { constructor() { this.top = null; this.bottom = null; this.size = 0; } push(val) { let newNode = new Node(val) if (!this.size) { this.top = newNode; this.bottom = newNode; } else { let temp = this.top this.top = newNode; this.top.next = temp; } return ++this.size; } pop() { if (!this.size) return null; let removedNode = this.top; this.top = removedNode.next; this.size--; if (!this.size) this.bottom = null; return removedNode.val; } } let stack = new Stack(); console.log(stack.push(0)); console.log(stack.push(1)); console.log(stack.push(2)); console.log(stack); console.log(stack.pop()); // 2 console.log(stack.pop()); // 1 console.log(stack.pop()); // 0 console.log(stack.pop()); // null console.log(stack);
$(document).ready(function() { //setInterval(check_login,5000); $("a.grouped_elements").fancybox({ 'padding' : 0, 'titleShow' : false , 'autoScale' : false, 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'hideOnOverlayClick' : false, 'hideOnContentClick' : false, 'overlayShow' : false, 'opacity' : false, 'type' : 'ajax' }); /* $('.v_link').click(function() { load_show(); var a_href = $(this).attr('href'); exploded = a_href.split('#'); var url_page = base_url+exploded[1]; $.ajax({ type: "POST", url: url_page, async:false, cache: false, dataType: "html", success: function(data){ load_hide(); $('#content').html(data); } }); }); */ $('.f_link').click(function() { load_show(); var a_href = $(this).attr('href'); exploded = a_href.split('#'); var url_page = base_url+exploded[1]; $.fancybox({ 'padding' : 0, 'titleShow' : false , 'autoScale' : false, 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'hideOnOverlayClick' : false, 'hideOnContentClick' : false, 'overlayShow' : false, 'opacity' : false, 'type' : 'ajax', 'href' : url_page }); load_hide(); }); }); function reload(page,div_id){ load_show(); $.ajax({ type: "POST", url: page, async:false, cache: false, dataType: "html", success: function(data){ $('#'+div_id+'_content').html(data); load_hide(); } }); } function check_login(){ $.getJSON(base_url+"api/check_login",function(data){ if(data.error == 1){ jAlert("Phiên làm việc của bạn đã hết. Vui lòng đăng nhập lại",'Thông báo'); setInterval(redirect_login,1000); } }); } function redirect_login(){ window.location = base_url; } function page(link){ load_show(); $.ajax({ type: "POST", url: base_url+link, //data: dataString, async:false, cache: false, dataType: "html", success: function(data){ $('#content').html(data); load_hide(); } }); } function getUrlVars(){ var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; } function show_msg(msg){ html ='<div class="_error">'; html +='<div>'+msg+'</div>'; html +='<div class="_close"><a onclick="close_msg()">Đóng</a></div>'; html +='</div>'; //$("#msg").html(html); $('#msg').html(html).slideToggleWidth("slow"); auto_close_msg(); } function auto_close_msg(){ setTimeout(remove_msg, 5000); } function remove_msg(){ if($("#msg").length > 0){ $("#msg").slideToggleWidth("slow"); $("#msg").html(''); } } function close_msg(){ $("#msg").slideToggleWidth("slow"); } function ToNumber(nStr) { if (nStr != null && nStr != NaN) { var rgx = /[₫\s.]/; while (rgx.test(nStr)) { nStr = nStr.replace(rgx, ''); } return eval(nStr) + 0; } return 0; } //formatCurrency function formatCurrency(num) { num = num.toString().replace(/\$|\,/g, ''); if (isNaN(num)) num = "0"; sign = (num == (num = Math.abs(num))); num = Math.floor(num * 100 + 0.50000000001); cents = num % 100; num = Math.floor(num / 100).toString(); if (cents < 10) cents = "0" + cents; for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) num = num.substring(0, num.length - (4 * i + 3)) + '.' + num.substring(num.length - (4 * i + 3)); var currency = (((sign) ? '' : '-') + num); return currency; } $.fn.extend({ slideRight: function() { return this.each(function() { $(this).animate({width: 'show'}); }); }, slideLeft: function() { return this.each(function() { $(this).animate({width: 'hide'}); }); }, slideToggleWidth: function() { return this.each(function() { var el = $(this); if (el.css('display') == 'none') { el.slideRight(); } else { el.slideLeft(); } }); } }); // Set language function set_lang(lang){ $.post(base_url+"api/setlang/",{'lang':lang},function(data){ location.reload(); }); } // Openr Images function openKCFinder(div) { window.KCFinder = { callBack: function(url) { window.KCFinder = null; div.innerHTML = '<div style="margin:5px">Đang tải ảnh...</div>'; var img = new Image(); img.src = url; img.onload = function() { div.innerHTML = '<img id="img" src="' + url + '" />'; base_url_str = base_url.replace('http://'+document.domain,''); base_url_str = base_url_str.replace('admin/',''); $("#news_img").val(url.replace(base_url_str,'')); var img = document.getElementById('img'); var o_w = img.offsetWidth; var o_h = img.offsetHeight; var f_w = div.offsetWidth; var f_h = div.offsetHeight; if ((o_w > f_w) || (o_h > f_h)) { if ((f_w / f_h) > (o_w / o_h)) f_w = parseInt((o_w * f_h) / o_h); else if ((f_w / f_h) < (o_w / o_h)) f_h = parseInt((o_h * f_w) / o_w); //img.style.width = f_w + "px"; //img.style.height = f_h + "px"; } else { // f_w = o_w; // f_h = o_h; } //img.style.marginLeft = parseInt((div.offsetWidth - f_w) / 2) + 'px'; //img.style.marginTop = parseInt((div.offsetHeight - f_h) / 2) + 'px'; img.style.visibility = "visible"; } } }; window.open(base_url+'templates/ckeditor/kcfinder/browse.php?type=images&dir=images/news', 'kcfinder_image', 'status=0, toolbar=0, location=0, menubar=0, ' + 'directories=0, resizable=1, scrollbars=0, width=800, height=600' ); } function insertReadmore(editor) { contents = cke.getData(); if (contents.match(/<hr\s+id=(\"|')system-readmore(\"|')\s*\/*>/i)) { alert('Đọc thêm đã được thêm vào'); return false; } else { jInsertEditorText('<hr id=\"system-readmore\" />', editor); } } function jInsertEditorText( text,editor ) { CKEDITOR.instances[editor].insertHtml( text); } function popup(mylink, windowname){ if (! window.focus)return true; var href; if (typeof(mylink) == 'string') href=mylink; else href=mylink.href; window.open(href, windowname, 'width=750,height=500,scrollbars=yes'); return false; }
const fs = require('fs'); const path = require('path'); const httpMocks = require('node-mocks-http'); const createShoppingList = require('../controllers/createShoppingList'); // (done) parameter means jest will wait for async operations. it('creates a new shopping list', (done) => { // tells this test that one assertion will happen. expect.assertions(1); // creates an object that wiil represent our POST data. const body = { items: ['broccoli', 'bread', 'bananas'], }; // Mocks a request object passing a body key as controller // expects to find POST data on req.body. const request = httpMocks.createRequest({ method: 'POST', url: '/shopping-lists', body: body, }); // event emitter is passed in so that when res.send is // called node-mocks-http uses the event emitter to trigger // an end event. const response = httpMocks.createResponse({ eventEmitter: require('events').EventEmitter, }); createShoppingList(request, response); // listens out for the end event that signals that res.send // hasa been called. response.on('end', () => { // res.send has been called, response._getData should // return an object with created filename therefore // assign this filename to a filename variable. const filename = response._getData().filename; // then use path,join to get the exact location of the // file and assign to a filePath. // __dirname gives current directory name. const filePath = path.join(__dirname, '../controllers/shoppingLists', filename); // now read the newly created file. fs.readFile(filePath, 'utf8', (error, data) => { // expect contents of file to equal our body object. expect(data).toBe(JSON.stringify(request.body)); // done() tells jest that the test can end. done(); fs.unlink(filePath, (errors) => { if (errors) throw errors; }); }); }); // you could then delete the created file so there // is no evidence of the test being run. });
import Vue from 'vue' import InputSearch from './InputSearch' import DatePicker from './DatePicker' import Pagination from './Pagination' // 富文本 import VueUeditorWrap from 'vue-ueditor-wrap' export default () => { Vue.component('l-input-search', InputSearch) Vue.component('l-date-picker', DatePicker) Vue.component('l-pagination', Pagination) Vue.component('vue-ueditor-wrap', VueUeditorWrap) }
import logo from './logo.svg'; import './App.css'; import Student from './Student.js'; import University from './University.js'; import Menu from "./components/Menu"; import React from "react"; import Hello from "./components/hello"; function App() { return ( <React.Fragment> <Menu></Menu> <University/> <Student name="Rick Rude" number="1111" enrolled="2"/> <Hello name="Priya"/> </React.Fragment> ); } export default App;
import React from 'react'; import './App.css'; import TodoListTasks from "./TodoListTasks"; import TodoListFooter from "./TodoListFooter"; import TodoListTitle from "./TodoListTitle"; import AddNewItemForm from "./AddNewItemForm"; import {connect} from "react-redux"; import {addTaskAC, changeTodoListTitle, deleteTaskAC, deleteTodolistAC, setTasksAC, updateTaskAC} from "./reducer"; import axios from "axios"; import {api} from "./api"; class TodoList extends React.Component { constructor(props) { super(props); this.newTasksTitileRef = React.createRef(); } componentDidMount() { this.restoreState(); } saveState = () => { let stateAsString = JSON.stringify(this.state); localStorage.setItem("our-state-" + this.props.id, stateAsString); } restoreState = () => { api.getTasks(this.props.id) .then(res => { this.props.setTasks(res.data.items, this.props.id) }); } nextTaskId = 0; state = { tasks: [], filterValue: "All" }; addTask = (newText) => { api.createTask(newText,this.props.id,) .then(res => { this.props.addTask(res.data.data.item, this.props.id) }) } changeFilter = (newFilterValue) => { this.setState({ filterValue: newFilterValue }, () => { this.saveState(); }); } changeTask = (taskId, obj) => { let task = this.props.tasks.find(item => { return taskId === item.id }); let newTask = {...task, ...obj}; api.updateTask(newTask) .then(res => { this.props.updateTask(taskId, obj, this.props.id); }) .catch(res => { }) // } changeStatus = (taskId, status) => { this.changeTask(taskId, {status}); } changeTitle = (taskId, title) => { this.changeTask(taskId, {title: title}); } deleteTodolist = () => { api.deleteTodolist(this.props.id) .then(res => { this.props.deleteTodolist(this.props.id) }) } deleteTask = (taskId) => { api.deleteTask(taskId) .then(res => { this.props.deleteTask(taskId, this.props.id) }) } updateTodolistTitle =(title)=>{ api.updateTitleTodolist(this.props.id,title) .then(res => { this.props.changeTodoListTitle(this.props.id,title) }) } render = () => { let {tasks = []} = this.props return ( <div className="todoList"> <div className="todoList-header"> <TodoListTitle title={this.props.title} onDelete={this.deleteTodolist} updateTodolistTitle={this.updateTodolistTitle}/> <AddNewItemForm addItem={this.addTask}/> </div> <TodoListTasks changeStatus={this.changeStatus} changeTitle={this.changeTitle} deleteTask={this.deleteTask} tasks={tasks.filter(t => { if (this.state.filterValue === "All") { return true; } if (this.state.filterValue === "Active") { return t.status === 0; } if (this.state.filterValue === "Completed") { return t.status === 2; } })}/> <TodoListFooter changeFilter={this.changeFilter} filterValue={this.state.filterValue}/> </div> ); } } const mapDispatchToProps = (dispatch) => { return { addTask(newTask, todolistId) { //const action = addTaskAC(newTask, todolistId); dispatch(addTaskAC(newTask, todolistId)); }, updateTask(taskId, obj, todolistId) { const action = updateTaskAC(taskId, obj, todolistId); dispatch(action); }, deleteTodolist: (todolistId) => { const action = deleteTodolistAC(todolistId); dispatch(action) }, deleteTask: (taskId, todolistId) => { const action = deleteTaskAC(todolistId, taskId); dispatch(action) }, setTasks(tasks, todolistId) { dispatch(setTasksAC(tasks, todolistId)) }, changeTodoListTitle(todoListId,title){ dispatch(changeTodoListTitle(todoListId,title)) } } } const ConnectedTodolist = connect(null, mapDispatchToProps)(TodoList); export default ConnectedTodolist;
/* eslint-disable no-undef */ import React from 'react'; import { shallow, mount } from 'enzyme'; import { RegisterEmployeeView } from '../RegisterEmployeeView'; describe('<RegisterEmployeeView />', () => { it('should render without crashing', () => { const props = { RegistrationAction: jest.fn(), onChange: jest.fn(), onSubmit: jest.fn(), }; const wrapper = shallow(<RegisterEmployeeView {...props} />); expect(wrapper).toMatchSnapshot(); }); it('calls handle submit', () => { const props = { RegistrationAction: jest.fn(), }; const event = { preventDefault: jest.fn(), }; const spy = jest.spyOn(RegisterEmployeeView.prototype, 'handleSubmit'); const wrapper = mount(<RegisterEmployeeView {...props} />); wrapper.instance().handleSubmit(event); expect(spy).toHaveBeenCalled(); }); it('calls handle Change method', () => { const props = { onSubmit: jest.fn(), onChange: jest.fn(), }; const event = { target: { name: 'username', value: 'maria', }, }; const spy = jest.spyOn(RegisterEmployeeView.prototype, 'handleChange'); const wrapper = mount(<RegisterEmployeeView {...props} />); wrapper.instance().handleChange(event); expect(spy).toHaveBeenCalled(); }); it('calls handle success method', () => { const props = { onSubmit: jest.fn(), onChange: jest.fn(), }; const registrationState = { payload: { message: 'User registered successfully', }, }; const spy = jest.spyOn(RegisterEmployeeView.prototype, 'handleSuccess'); const wrapper = mount(<RegisterEmployeeView {...props} />); wrapper.instance().handleSuccess(registrationState); expect(spy).toHaveBeenCalled(); }); it('calls handle errors method', () => { const props = { onSubmit: jest.fn(), onChange: jest.fn(), registrationState: { error: 'errors', }, }; const spy = jest.spyOn(RegisterEmployeeView.prototype, 'handleErrors'); const wrapper = mount(<RegisterEmployeeView {...props} />); wrapper.instance().handleErrors(props); expect(spy).toHaveBeenCalled(); }); it('calls componentWillMount if nextProps', () => { const props = { onSubmit: jest.fn(), onChange: jest.fn(), }; const nextProps = { registrationState: { payload: 'payload', }, }; const spy = jest.spyOn(RegisterEmployeeView.prototype, 'componentWillReceiveProps'); const wrapper = mount(<RegisterEmployeeView {...props} />); wrapper.instance().componentWillReceiveProps(nextProps); expect(spy).toHaveBeenCalled(); }); it('calls componentWillMount if no nextProps', () => { const props = { onSubmit: jest.fn(), onChange: jest.fn(), }; const nextProps = { registrationState: { payload: undefined, }, }; const spy = jest.spyOn(RegisterEmployeeView.prototype, 'componentWillReceiveProps'); const wrapper = mount(<RegisterEmployeeView {...props} />); wrapper.instance().componentWillReceiveProps(nextProps); expect(spy).toHaveBeenCalled(); }); });
/** * @author tanna * @format * @flow * @param {number} time */ export const delay = time => new Promise(resolve => setTimeout(resolve, time));
const puppeteer = require('puppeteer'); const request = require('request-promise-native'); const scraper = async ({adapter, readOptions = {}, updateOptions = {}}) => { const scrape = async () => { const {data, meta} = await adapter.read({batchSize: readOptions.batchSize}); if(!data) { return; } for(let row of data) { row.MOTDueDate = row.MOTExpired = row.TaxDueDate = row.SORN = null; try { await page.goto('https://vehicleenquiry.service.gov.uk/'); await page.type('#Vrm', row.RegNo); await page.click('[name="Continue"]'); await page.waitFor('#Correct_True', {timeout: 5000}); await page.click('#Correct_True'); await page.click('[name="Continue"]'); await page.waitFor('.reg-mark', {timeout: 5000}); const additionalData = await page.evaluate((dateFns) => { eval(dateFns); // workaround until puppeteer #1229 is fixed. See: https://github.com/GoogleChrome/puppeteer/issues/1229 const data = {}; const containers = $('div.status-bar > div.column-half'); const taxContainer = containers.eq(0); const motContainer = containers.eq(1); if(taxContainer) { const dateMatch = taxContainer.find('p').text().match(/Tax due:(\d{2} \w+ \d{4})/); if(dateMatch) { const date = window.dateFns.parse(dateMatch[1], 'DD MMMM YYYY'); if(window.dateFns.isValid(date)) { data.TaxDueDate = window.dateFns.format(date, 'DD/MM/YYYY'); } } else if(taxContainer.find('h2').text().match(/SORN/)) { data.SORN = 'Yes'; } } if(motContainer) { const expiresMatch = motContainer.find('p').text().match(/Expires:(\d{2} \w+ \d{4})/); const expiredMatch = motContainer.find('p').text().match(/Expired:(\d{2} \w+ \d{4})/); if(expiresMatch) { const date = window.dateFns.parse(expiresMatch[1], 'DD MMMM YYYY'); data.MOTDueDate = window.dateFns.format(date, 'DD/MM/YYYY'); } else if(expiredMatch) { const date = window.dateFns.parse(expiredMatch[1], 'DD MMMM YYYY'); data.MOTExpired = window.dateFns.format(date, 'DD/MM/YYYY'); } } const regDate = window.dateFns.parse($('li#UKRegistrationDateDummyDateV5CMatch').find('strong').text(), 'MMMM YYYY'); if(window.dateFns.isValid(regDate)) { data.RegDate = window.dateFns.format(regDate, 'DD/MM/YYYY'); } return data; }, dateFns); row = Object.assign(row, additionalData); } catch(error) { console.log(error.message); } }; await adapter.update( { data, meta, options: updateOptions }); return scrape(); } const browser = await puppeteer.launch( { args: [ '--no-sandbox' ] }); const page = await browser.newPage(); const dateFns = await request('http://cdn.date-fns.org/v2.0.0-alpha0/date_fns.min.js', {gzip: true}); // need to use >= v2.0.0-alpha6 for dates to be parsed correctly with a custom format await scrape(); await browser.close(); } module.exports = scraper;
import React from 'react'; import { Header, Icon } from 'semantic-ui-react'; import { Link } from 'react-router-dom'; const TestList = ({ tests }) => { return ( <div> { tests.map(test => { return ( <Header as='h3' key={test.id}> <Icon name='book'/> <Header.Content> <Link to="/prueba/examen_de_historia">{test.title}</Link> </Header.Content> </Header> ) }) } </div> ); } export default TestList;
import React from 'react'; import { Text } from 'react-native'; import { storiesOf, action, linkTo } from '@kadira/react-native-storybook'; import CenterView from './CenterView'; import FullButton from '../Components/FullButton'; storiesOf('FullButton', module) .addDecorator(getStory => ( <CenterView>{getStory()}</CenterView> )) .add('Default view', () => ( <FullButton text="Hello!" onPress={action('pressed!')} /> ));
var _app = new Vue({ el : "#root", data : function() { return { isList: false, // set items to show to 12 given that we mount the component with the Tile view active itemsToShow: 12, filters: [], groupFilter: "All", refineSearch: "", parts: [], paginate: ["partsMultipleFilters"] } }, mounted() { Promise.all([ axios.get("data/parts.json"), axios.get("data/filters.json") ]).then(([parts,filters]) => { let partsExtendedWithMinimumQty = parts.data.reduce((r,v,k) => { v.hasOwnProperty("customField_MinimumQuantity") ? v._quantity = v.customField_MinimumQuantity : v._quantity = 1; r = [...r,v]; return r; },[]); this.parts = partsExtendedWithMinimumQty; let filtersWithCounters = filters.data.reduce((r,v,k) => { let temp = partsExtendedWithMinimumQty.filter(o => { // console.log(o.parentGroupNames , v); return o.parentGroupNames.includes(v.category); }).length ? v.count = partsExtendedWithMinimumQty.filter(o => o.parentGroupNames.includes(v.category)).length : v.count = 0; r = [...r,v]; return r; },[]); this.filters = filtersWithCounters; }); }, methods : { makeList: function(param) { param == true ? this.isList = true : this.isList = false; param == true ? this.itemsToShow = 10 : this.itemsToShow = 12; }, addToFav: function(part) { // add to favorite console.log(part, " add to favorite"); // change is favorite to true part.isFavorite = true; }, removeFromFav: function(part) { // remove from favorite console.log(part, " remove from favorite"); // change is favorite to false part.isFavorite = false; }, quantityHandler: function(part , event) { console.log(part); let range = []; let min = parseInt(part._quantity); let max = parseInt(part.stock); let req = event.currentTarget.value; for(let i = min; i <= max; i = i + min) { range = [...range,i]; } console.log(range); console.log(req); // figure out how to use functions that can be declared outside of Vue's scope // let out = rounded(range,req); }, rounded: function(arr,val) { for(let i = 0; i < arr.length; i++) { array[i] >= val ? array[i] : false; } } }, computed : { filteredParts: function() { let vm = this; let groupFilter = vm.groupFilter; if(groupFilter === "All") { return vm.parts; } else { return vm.parts.filter((part) => part.parentGroupNames.includes(groupFilter)) } }, partsMultipleFilters: function() { let filtered = this.parts; // reference to main dataset let vm = this; // filter group radios if(this.groupFilter !== "All") { filtered = this.parts.filter((part) => part.parentGroupNames.includes(this.groupFilter)) } else { filtered = this.parts } // refine search -- extend with Array of multiple search terms || split search terms by space and push them to an Array if(this.refineSearch) { let words = this.refineSearch.split(" "); // multiple words refine search filtered = filtered.reduce((r,v,k) => { words.filter(word => v.name.toLowerCase().includes(word.toLowerCase())).length ? r = [...r, v] : r = [...r]; return r; },[]); // exact match // filtered = filtered.filter((part) => part.name.toLowerCase().includes(this.refineSearch.toLowerCase()) || part.number.toLowerCase().includes(this.refineSearch.toLowerCase())) } // update filters counter // let filtersWithCounters = this.filters.reduce((r,v,k) => { // filtered.filter(o => { // return o.parentGroupNames.includes(v.category); // }).length ? v.count = filtered.filter(o => o.parentGroupNames.includes(v.category)).length : v.count = 0; // r = [...r,v]; // return r; // },[]); // console.log(filtersWithCounters); return filtered; } }, watch: { // if user types anything into the refine search input , set pagination to page 1 // and also update the filters count refineSearch: function(val) { this.$refs.paginator.goToPage(1); }, // if user clicks any radio filter , set pagination to page 1 groupFilter: function(val) { console.log(val); this.$refs.paginator.goToPage(1); } } }); Vue.filter('currency', function (value) { return '$' + parseFloat(value).toFixed(2); });
import React from 'react'; import ReactEcharts from '../charts/index'; class StockChartPreviewList extends React.Component { constructor(props) { // 构造函数 super(props); } static defaultProps = { isOnLoading: false, stockList: [] } componentWillMount() { } componentDidMount() { this.props.getStockChartPreview(); } componentDidUpdate() {} componentWillUpdate() {} getStockChartPreviewList() { var previewList = []; for (let i = 0; i < this.props.stockList.length; i++) { let chartsId = `J_chartPreview_${this.props.stockList[i].symbol}`; let stockInfo = this.props.stockList[i]; var riseUpStateClass = stockInfo.rate.slice(0,1) === '+' ? 'J_riseup' : ''; previewList.push( <li key={chartsId}> <a href={`/stockDetailList/${stockInfo.symbol}`}> <ReactEcharts ref={chartsId} chartId={chartsId} stockInfo={stockInfo} className={'J_chartPreview'} ></ReactEcharts> <div className={`stock-detail ${riseUpStateClass}`}> <strong className="stock-detail-name">{stockInfo.symbol}</strong> <strong className="stock-detail-price">{stockInfo.price}</strong> <span className="stock-detail-rate">{stockInfo.rate}</span> </div> </a> </li> ); } return previewList; } render() { return ( <section className="stock-chart-preview-list-container"> <ul className="clearfix"> {this.getStockChartPreviewList()} <li className="J_addMyFav iconfont"></li> </ul> </section> ); } } export default StockChartPreviewList;
import React from 'react'; import { Form,FormGroup,Col,Checkbox,Button,ControlLabel,FormControl,Row } from 'react-bootstrap'; import DatePicker from 'react-bootstrap-date-picker'; import { AutoComplete } from 'material-ui'; import Formulario from './FormularioSite.jsx'; class Alta extends React.Component{ constructor(){ super(); this.state = { Autocomplete:{ sourceGeo:["1"], sourceGeoNcr:["2"] }, FormPublic:0 } } Cambiar(e){ this.setState({FormPublic: parseInt(e.target.value)}); } agregarPublic(e){ this.setState({FormPublic:parseInt(e.target.value)}); } render(){ return( <div className="row wrapperWhite" style={{marginRight:"0",marginLeft:"0",paddingBottom: "10px",borderBottom: "2px solid #e7eaec"}}> <div className="col-xs-12 litleHeader"> <h5> Alta de Site </h5> </div> <div className="col-xs-12 litleBody"> <div className="col-xs-6"> <Form horizontal> <FormGroup controlId="formHorizontalEmail"> <Col componentClass={ControlLabel} xs={12} sm={2}> Site </Col> <Col xs={12} sm={8}> <FormControl type="text" placeholder="Site" /> </Col> </FormGroup> <FormGroup controlId="AutoCompleteModelo"> <Col componentClass={ControlLabel} xs={12} sm={2}> Tipo </Col> <Col xs={12} sm={8}> <FormControl componentClass="select" placeholder="select"> <option value="other">Tipo 1</option> <option value="select">Tipo 2</option> <option value="other">Tipo 3</option> </FormControl> </Col> </FormGroup> <FormGroup controlId="AutoCompleteCarga"> <Col componentClass={ControlLabel} xs={12} sm={2}> Geo Cliente </Col> <Col xs={12} sm={8}> <FormControl componentClass="select" placeholder="select"> <option value="other">Geo 1</option> <option value="select">Geo 2</option> <option value="other">Geo 3</option> </FormControl> </Col> </FormGroup> <FormGroup controlId="Fecha"> <Col componentClass={ControlLabel} xs={12} sm={2}> Fecha </Col> <Col xs={12} sm={8}> <Row> <Col xs={6}> <DatePicker /> </Col> <Col xs={6}> <DatePicker /> </Col> </Row> </Col> </FormGroup> </Form> </div> <div className="col-xs-6"> <Form horizontal> <FormGroup controlId="tel1"> <Col componentClass={ControlLabel} xs={12} sm={2}> Telefo 1 </Col> <Col xs={12} sm={8}> <FormControl type="text" placeholder="Numero" /> </Col> </FormGroup> <FormGroup controlId="tel2"> <Col componentClass={ControlLabel} xs={12} sm={2}> Telefo 2 </Col> <Col xs={12} sm={8}> <FormControl type="text" placeholder="Numero" /> </Col> </FormGroup> <FormGroup controlId="tel3"> <Col componentClass={ControlLabel} xs={12} sm={2}> Telefo 3 </Col> <Col xs={12} sm={8}> <FormControl type="text" placeholder="Numero" /> </Col> </FormGroup> <FormGroup controlId="tel3"> <Col componentClass={ControlLabel} xs={12} sm={2}> Telefo 3 </Col> <Col xs={12} sm={8}> <FormControl type="text" placeholder="Numero" /> </Col> </FormGroup> <FormGroup controlId="AutoCompleteModelo"> <Col componentClass={ControlLabel} xs={12} sm={2}> Tipo Direccion </Col> <Col xs={12} sm={8}> <FormControl componentClass="select" placeholder="select" onChange={this.Cambiar.bind(this)}> <option value="-1">Select</option> <option value="1">Publico</option> <option value="2">Privado</option> </FormControl> </Col> </FormGroup> </Form> </div> <Col xs={12}> {(()=>{ switch (this.state.FormPublic){ case 1: return <Col xs={12} sm={6}> <Form> <FormGroup controlId="AutoCompleteCarga"> <Col componentClass={ControlLabel} xs={12} sm={2}> Site Publico </Col> <Col xs={12} sm={8}> <AutoComplete hintText="Site Public" filter={AutoComplete.caseInsensitiveFilter} dataSource={["Abasto","Unicenter","Plaza Oeste"]} /> </Col> </FormGroup> <Button type="button" className="btn btn-default btn-sm" value="2" onClick={this.agregarPublic.bind(this)}> <span className="glyphicon glyphicon-plus"/> </Button> </Form> </Col>; break; case 2: return <Formulario/>; break; case 0: return ""; break; } })()} </Col> </div> <Row> <center> <Button>Crear</Button> </center> </Row> </div> ); } } module.exports = Alta;
const mongoose = require('mongoose') const pizzaSchema = new mongoose.Schema({ title :{type:String , required:true}, over_view :{type:String , required:true}, smallPrice :{type:String , required:true}, mediumPrice :{type:String , required:true}, largePrice :{type:String , required:true}, img_src :{type:mongoose.Schema.Types.Mixed,default:false}, }) module.exports = pizzaSchema
const express = require('express'); const router = express.Router(); const newController = require('../app/controllers/newcontroller'); const { requiresAuth } = require('express-openid-connect'); router.get('/:id',requiresAuth(), newController.show); router.get('/', newController.index ); module.exports = router;
import React, {Component} from 'react'; import { Dialog } from 'material-ui'; import renderPending from '../decorators/renderPending'; import Videos from './Videos'; export default class ReleaseDialog extends Component { render() { const { release, pending } = this.props; const standardActions = [ { text: 'Close' } ]; if (!release) { return null; } return ( <Dialog title={ `Watch ${release.title}: ${release.subtitle}` } actions={ standardActions } modal={ true } defaultOpen={ true } onRequestClose = { ::this.props.onRequestClose } actionFocus="submit"> <Videos urls={ release.videoUrls } pending={ pending } /> </Dialog> ); } }
import React, { Component } from 'react'; import _ from 'lodash'; export class ViewButton extends Component { state = { deals: this.props.deals } render() { const merchantFilter = _(this.state.deals).groupBy(merchant => merchant.merchant_name).map((value, key) => { return { merchant_name: key, deals: value }; }).value(); const viewDeal = merchantFilter.map(deal => { const mapDansMap = deal.deals.map(dansmap => { return ( <tbody> <td> <div className="image-container"> <img className="responsive" alt="" src={dansmap.image} /> </div> </td> <td>{dansmap.product_name}</td> <td>${dansmap.deal_price} </td> <td>{dansmap.quantity}</td> </tbody> ); }); return ( <td style={{ borderRight: '1px solid #d6d6d6' }}> <h5>{deal.merchant_name}</h5> <table> <thead> <tr> <th></th> <th>Name</th> <th>Price</th> <th>Quantity</th> </tr> </thead> {mapDansMap} </table> </td> ); }); return viewDeal; } } export default ViewButton;
import React, {useState, useEffect} from 'react'; import { useInterval, usePrevious } from '../usages/tool'; import InfoPage from './InfoPage'; import Fade from './Fade'; import {FullDiv} from '../usages/cssUsage'; import {excludeName} from '../usages/voiceUsage'; function Speak(props) { let genVoice = () => { let v = synth.getVoices(); let prevName = ''; console.log(v.length); for (var i=0; i<v.length; i++) { while (i<v.length && (excludeName.has(v[i].name) || v[i].name === prevName)) v.splice(i, 1); if (i < v.length) { prevName = v[i].name; if (v[i].default) changeVoiceIdx(i); } } return v; } const synth = window.speechSynthesis; const [voiceIndex, changeVoiceIdx] = useState(0); const [voices, setVoices] = useState(()=>{return genVoice();}); const [pitch, setPitch] = useState(1); const [rate, setRate] = useState(1); const [speaking, setSpeaking] = useState(false); //const [sentence, setSentence] = useState(''); const {toSpeak, data, changeVoice} = props; const prevSpeak = usePrevious(toSpeak); const prevChangeVoice = usePrevious(changeVoice); const [revealSentence, setRevealSentence] = useState(''); useEffect(()=>{ if (!toSpeak || speaking) return; if (prevSpeak !== toSpeak && data.text) { if (data.rate) setRate(data.rate); if (data.pitch) setPitch(data.pitch); //speakTxt(data.text); speakTxtWithPR(data.text, data.pitch?data.pitch:pitch, data.rate?data.rate:rate); } }, [toSpeak, data]); useEffect(()=>{ if (prevChangeVoice !== changeVoice) { changeVoiceIdx(Math.floor(Math.random()*voices.length)); } }, [changeVoice]); useEffect(()=>{ props.changeVoiceCallback({name:voices[voiceIndex].name, lang:voices[voiceIndex].lang}); }, [voiceIndex]); let populateVoice = () => { setVoices(genVoice()); } synth.onvoiceschanged = populateVoice; useInterval(() => { if (!synth.speaking) { //console.log('finish speak!'); props.speakOver(); setSpeaking(false); setRevealSentence(""); } }, speaking ? 100 : null); let submitSpeak = (event) => { event.preventDefault(); speakTxt('hello'); } let speakTxt = (txt) => { setSpeaking(true); setRevealSentence(txt); let utterThis = new SpeechSynthesisUtterance(txt); utterThis.voice = voices[voiceIndex]; utterThis.pitch = pitch; utterThis.rate = rate; synth.speak(utterThis); } let speakTxtWithPR = (txt, p, r) => { setSpeaking(true); setRevealSentence(txt); let utterThis = new SpeechSynthesisUtterance(txt); utterThis.voice = voices[voiceIndex]; utterThis.pitch = p; utterThis.rate = r; synth.speak(utterThis); } const formProps = { onSubmitF: submitSpeak, voiceIndex: voiceIndex, voiceOnChanged: changeVoiceIdx, voices: voices, pitch: pitch, rate: rate, pitchOnChanged: setPitch, rateOnChanged: setRate } let personName = voices[voiceIndex] !== undefined ? `${voices[voiceIndex].name} (${voices[voiceIndex].lang})` : ''; return ( <> {props.form && <SpeakForm {...formProps}/>} <InfoPage personName={personName} sentence={revealSentence} speakingVoice={props.nowSpeak} nameColor={speaking ? 'black': 'white'} /> <Fade show={speaking} speed={'0.3s'}> <FullDiv/> </Fade> </> ); } function SpeakForm(props) { const {onSubmitF, voiceIndex, voiceOnChanged, voices, pitch, rate, pitchOnChanged, rateOnChanged} = props; return ( <form onSubmit={onSubmitF}> <select value={voiceIndex} onChange={(e) => {voiceOnChanged(e.target.value)}}> {voices.map((value, index) => { return <option key={index} value={index}>{`${value.name} (${value.lang})`}</option> })} </select> <br/> <label htmlFor='pitch'>pitch</label> <input type='number' step={0.01} value={pitch} onChange={(e)=>{pitchOnChanged(e.target.value)}} id='pitch' /> <br/> <label htmlFor='rate'>rate</label> <input type='number' step={0.01} value={rate} onChange={(e)=>{rateOnChanged(e.target.value)}} id='rate'/> <input type='submit'></input> </form> ) } export default Speak;
export const UPDATE_RECIPE = 'UPDATE RECIPE' export default (recipe) => ({ type: UPDATE_RECIPE, payload: recipe })
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ class ProjectTile { constructor(projectName, projectInfoObj) { this.projectTileClassList = ["projectCard","w3-card","w3-center","w3-padding-32"]; this.projectCaptionContainerClassList = ["project-caption-container", "w3-black", "w3-opacity", "w3-text-white", "overlay"]; this.projectInfoObj = projectInfoObj; this.projectName = projectName; } getHTMLTileElement() { // Create top level div let projectTileElement = document.createElement("div"); let projectTileElementId = `${this.projectName}-project-card` projectTileElement.id = projectTileElementId this.projectTileClassList.forEach(className => projectTileElement.classList.add(className)); projectTileElement.style.backgroundImage = `url('${this.projectInfoObj.imageSrc}')`; // Create Caption Container let projectCaptionContainerElement = document.createElement("div") this.projectCaptionContainerClassList.forEach(className => { projectCaptionContainerElement.classList.add(className); }) // Create Text Class Label let innerDivElement = document.createElement("div"); innerDivElement.classList.add("overlay-text"); let projectNameElement = document.createElement("div"); projectNameElement.textContent = this.projectInfoObj.title; // Append the elements innerDivElement.append(projectNameElement) projectCaptionContainerElement.append(innerDivElement); projectTileElement.append(projectCaptionContainerElement); projectTileElement.setAttribute("data-aos", "fade-up-left") projectTileElement.setAttribute("data-focused-card", false) this.htmlElement = projectTileElement; return projectTileElement; } getExpandedTileHTMLElement() { let elemString = ``;//<div></div> //Add Title elemString += `<h2>${this.projectInfoObj.title}</h2>`; //Add Date and Status elemString += `<h6>Date: ${this.projectInfoObj.date} | Status: <span class='status ${this.projectInfoObj.status}-status'>${this.projectInfoObj.status} </span></h6>`; //Add Description elemString += `<p>${this.projectInfoObj.description}</p>`; //Add Tech Stack if (this.projectInfoObj.stack.length > 0) { elemString += `<h6>Technologies:`; this.projectInfoObj.stack.forEach((item) => { elemString += `<div class='tech-skill-tag'>${item}</div>`; }); elemString += `</h6>`; } //Add other Skill list if (this.projectInfoObj.skills.length > 0) { elemString += `<h6>Skills: <spanclass='other-skill-space'>`; for (let skillIdx=0; skillIdx < this.projectInfoObj.skills.length; skillIdx++) { if (skillIdx === this.projectInfoObj.skills.length - 1) {//no trailing comma elemString += `${this.projectInfoObj.skills[skillIdx]}` } else { elemString += `${this.projectInfoObj.skills[skillIdx]}, `; } } elemString += `</span></h6>` } elemString += `<br/>`; //Add link To button if (this.projectInfoObj.link.length > 0) { elemString += `<h4><a href=${this.projectInfoObj.link}><button class='w3-button w3-text-white w3-black w3-hover-text-black w3-hover-white'>Check it out</button></a></h4>` } //close and return element elemString += `<br/>`// </div> let expandedElementTileElement = document.createElement("div"); expandedElementTileElement.innerHTML = elemString //expandedElementTileElement.innerHTML = elemString return expandedElementTileElement; } } module.exports = ProjectTile; },{}],2:[function(require,module,exports){ class SkillCard { constructor(skillObj) { this.skillCardClassList = ["w3-card", "w3-center", "w3-padding-32", "w3-hover-opacity", "w3-hover-black", "skillCard"]; this.parentSkill = skillObj.parentSkill || "none"; this.skillClass = skillObj.skillClass || "other"; this.skillName = skillObj.skillName || "???"; } getHTMLElement() { // Create Element let skillCardElement = document.createElement("div"); // Add the class information this.skillCardClassList.forEach( skillCardClass => { skillCardElement.classList.add(skillCardClass); }); // Add aos flip animation skillCardElement.setAttribute("data-aos", "flip-left" ); // Add attribute for parent skill skillCardElement.setAttribute("data-parentskill", this.parentSkill); // Add attribute that identifies the skill classification skillCardElement.setAttribute("data-skillclass", this.skillClass); skillCardElement.id = `${this.skillName}-skill-card` // append the actual data let skillName = document.createElement("h3"); skillName.textContent = this.skillName; skillCardElement.append(skillName); return skillCardElement; } } module.exports = SkillCard; },{}],3:[function(require,module,exports){ const SkillCard = require('./src/components/SkillCard.js'); const ProjectTile = require('./src/components/ProjectTile.js'); fetch("./skills.json") .then(response => response.json()) .then(json => { loadSkillsCards(json) }); fetch("./projects.json") .then(response => response.json()) .then(json => { loadProjectTiles(json) }); let loadSkillsCards = (skillsArr) => { let skillCardContainer = document.getElementById("skillsPool"); skillsArr.forEach(skillObj => { let newSkillCard = new SkillCard(skillObj); skillCardContainer.append(newSkillCard.getHTMLElement()); }) } let metaTypeWriter = (txt, speed, element) => { var i = 0; function typeWriter(txt, speed) { if (i < txt.length) { if (txt.charAt(i) == "#") {// BackSpace on # element.textContent.slice(0, - 1); } else { element.textContent += txt.charAt(i); } i++; setTimeout(typeWriter, speed, txt.substring(1), speed); } } typeWriter(txt,speed) } let splashHeaderNameElement = document.getElementById("splashHeader"); // splashHeaderNameElement.addEventListener('click', function(event) { // console.log("hi") // metaTypeWriter("Hi There :)!############My Name Is##########Joseph Varilla", 40, splashHeaderNameElement) // }) AOS.init({ duration: 1200, once: true, }); //---Code for CV Tab Functionality------------------------------------------------ let selectedItemTab= document.getElementById("background_cv_tab"); let selectedItemSection = document.getElementById("cv_background"); selectedItemTab.classList.add("w3-dark-grey"); selectedItemTab.classList.add("w3-text-white"); const tabMap = { background: cv_background, education: cv_education, experience: cv_experience, // skills: cv_skills, honors: cv_honors }; function loadTab(event, tabVal) { //Remove Selected Classes From Tab (Removes Highlighting) selectedItemTab.classList.remove("w3-dark-grey"); selectedItemTab.classList.remove("w3-text-white"); //Hide The Selected Section selectedItemSection.hidden = true; //Point Selected Section and Tab To The New Ones selectedItemTab = event.target; selectedItemSection = tabMap[tabVal]; //HighLight The Selected Tab selectedItemTab.classList.add("w3-dark-grey"); selectedItemTab.classList.add("w3-text-white"); //Show the selected section selectedItemSection.hidden = false; } let backgroundTab = document.getElementById("background_cv_tab"); let educationTab = document.getElementById("education_cv_tab"); let experienceTab = document.getElementById("experience_cv_tab"); // let skillsTab = document.getElementById("skills_cv_tab"); let awardsTab = document.getElementById("awards_cv_tab"); backgroundTab.addEventListener('click', function(event) { loadTab(event, 'background'); }); educationTab.addEventListener('click', function(event) { loadTab(event, 'education'); }); experienceTab.addEventListener('click', function(event) { loadTab(event, 'experience'); }); // skillsTab.addEventListener('click', function(event) { // loadTab(event, 'skills'); // }); awardsTab.addEventListener('click', function(event) { loadTab(event, 'honors'); }); let cvTabIdx = 0; let cvTabs = [backgroundTab, educationTab, experienceTab, awardsTab]; let advanceTabToRight = () => { cvTabIdx++; cvTabs[cvTabIdx % cvTabs.length].click(); } let advanceTabToLeft = () => { cvTabIdx--; if (cvTabIdx < 0) { cvTabIdx = cvTabs.length -1; } cvTabs[cvTabIdx % cvTabs.length].click(); } let cvTabContainer = document.getElementById("cv"); document.addEventListener("keydown", function(event) { //Remove Selected Classes From Tab (Removes Highlighting) selectedItemTab.classList.remove("w3-dark-grey"); selectedItemTab.classList.remove("w3-text-white"); switch(event.keyCode) { // Right key press move tab one to right case 39: { advanceTabToRight(); break; } // Left key press move tab to left case 37: { advanceTabToLeft(); break; } } }) //---Code For Project Slides------------------------------------------------------------ function noScroll(event) { let pageY = event.pageY; if (pageY !== undefined) { window.scrollTo(0, event.pageY); } } // let slideContainer = document.getElementById("slideContainer") // slideContainer.addEventListener("mouseover", function(event) { // // add listener to disable scroll // console.log("focus in") // console.log(event) // window.addEventListener('scroll', noScroll, event); // }) // slideContainer.addEventListener("mouseout", function(event) { // console.log("focus out") // // Remove listener to re-enable scroll // window.removeEventListener('scroll', noScroll); // }) function revealCaption(event) { let captionBlock = event.target.childNodes.filter((child) => { child.classList.contains("project-caption-container"); }); } let focusedCard = null; function focusOnProjectSlide(event, elemId) { const targetCard = document.getElementById(elemId); document.querySelector('div#projects').scrollIntoView(); if (targetCard !== focusedCard) { if (focusedCard) { focusedCard.classList.remove('projectCardFocused'); } focusedCard = targetCard; loadProjectData(elemId); } else { hideProjectData(); focusedCard = null; } targetCard.classList.toggle('projectCardFocused'); } const projectDataCard = document.getElementById("dynamic-project-data-card"); let projectTiles = {} function loadProjectData(elemId) { projectDataCard.classList.remove("projectDataCardInactive"); projectDataCard.innerHTML = '' projectDataCard.append(projectTiles[elemId].getExpandedTileHTMLElement()); projectDataCard.classList.add("projectDataCardActive"); } function hideProjectData() { projectDataCard.innerHTML = '' projectDataCard.classList.remove("projectDataCardActive"); projectDataCard.classList.add("projectDataCardInactive"); } let loadProjectTiles = (projectsObj) => { let projectTileContainer = document.getElementById("projectTileContainer"); for (let projectKey in projectsObj) { let newProjectTile = new ProjectTile(projectKey, projectsObj[projectKey]); projectTiles[`${projectKey}-project-card`] = newProjectTile let newProjectTileElement = newProjectTile.getHTMLTileElement(); newProjectTileElement.addEventListener('click', function(event) { focusOnProjectSlide(event, `${projectKey}-project-card`) }) projectTileContainer.append(newProjectTileElement) } } },{"./src/components/ProjectTile.js":1,"./src/components/SkillCard.js":2}]},{},[3]);
let mysql = require('mysql'); module.exports = function () { if (!process.env.NODE_ENV) { return mysql.createConnection({ host: 'localhost', user: 'root', password: 'root', database: 'casa_codigo' }) } if (process.env.NODE_ENV == 'test') { return mysql.createConnection({ host: 'localhost', user: 'root', password: 'root', database: 'casa_codigo_test' }) } }
import React, { useEffect } from "react"; import { useLocation } from "react-router-dom"; import ReactPlayer from "react-player"; import { useResultContext } from "../contexts/ResultContextProvider"; import { Loading } from "./Loading"; export const Results = () => { const { results, isLoading, getResults, searchTerm } = useResultContext(); const location = useLocation(); useEffect(() => { if (searchTerm) { if (location.pathname === "/videos") { getResults(`/search/q=${searchTerm} videos`); } else { getResults(`${location.pathname}/q=${searchTerm}&num=40`); } } }, [searchTerm, location.pathname]); if (isLoading) return <Loading />; console.log(location.pathname); switch (location.pathname) { case "/search": return ( <div className="flex flex-wrap justify-between space-y-6 sm:px-56"> {results?.map(({ link, title }, index) => ( <div key={index} className="md:w-2/5 w-full"> <a href={link} target="_blank" rel="noreferrer"> <p className="text-sm"> {link.length > 30 ? link.substring(0, 30) : link} </p> <p className="text-lg hover:underline dark:text-blue-300 text-blue-700"> {title} </p> </a> </div> ))} </div> ); case "/images": return ( <div className="flex flex-wrap justify-center items-center"> {results?.map(({ image, link: { href, title } }, index) => ( <a className="sm:p-3 p-5" href={href} key={index} target="_blank" rel="noreferrer" > <img src={image?.src} alt={title} loading="lazy" /> <p className="w-36 break-words text-sm mt-2">{title}</p> </a> ))} </div> ); case "/news": return ( <div className="flex flex-wrap justify-between space-y-6 sm:px-56 items-center"> {results?.map(({ links, id, source, title }) => ( <div key={id} className="md:w-2/5 w-full"> <a href={links?.[0].href} target="_blank" rel="noreferrer" className="hover:underline" > <p className="text-lg dark:text-blue-300 text-blue-700"> {title} </p> </a> <div className="flex gap-4"> <a href={source?.href} target="_blank" rel="noreferrer"> {source?.href} </a> </div> </div> ))} </div> ); case "/videos": return ( <div className="flex flex-wrap"> {results.map((video, index) => ( <div key={index} className="p-2"> {video?.additional_links?.[0]?.href && <ReactPlayer url={video.additional_links?.[0].href} controls height="200px" width="355px" />} </div> ))} </div> ); default: return "ERROR"; } return <div>Results</div>; };
import React, { Component } from 'react'; import './App.css'; export default class _AtomsTextLabelDefault extends Component { // This component doesn't use any properties constructor(props) { super(props); this.state = { }; } componentDidMount() { } componentWillUnmount() { } componentDidUpdate() { } render() { const style_elLabel = { fontSize: 13.5, color: 'black', textAlign: 'left', }; return ( <div className="_AtomsTextLabelDefault"> <div className="foreground"> <div className="font-robotoRegular elLabel" style={style_elLabel}> <div>{this.props.locStrings._atomstextlabeldefault_label_732915}</div> </div> </div> </div> ) } }
import React from 'react'; import Link from 'next/link'; import classnames from 'classnames'; import PropTypes from 'prop-types'; import styles from './SearchResults.module.scss'; // TODO: look into framer motion const SearchResults = ({ isOpen, results }) => ( <ul className={classnames([ styles.searchResults, isOpen && styles.searchResults_active, ])} > {isOpen && ( <> {results && results.map(({ slug, frontmatter }) => ( <li key={slug} className={styles.searchResults__item}> <Link href="/posts/[slug]" as={`/posts/${slug}`}> <a className={styles.searchResults__link}> {frontmatter.title} </a> </Link> {frontmatter.description} </li> ))} </> )} </ul> ); SearchResults.propTypes = { isOpen: PropTypes.bool, results: PropTypes.arrayOf(PropTypes.object), }; SearchResults.defaultProps = { isOpen: false, results: null, }; export default SearchResults;
//dictionary let object = {"charlie": "coffee"}; function printKeyandValue(object) { for(keys in object){ console.log(keys, object[keys]) } } printKeyandValue(object) // reverse arrays function reverseArray(array) { let temp = 0; for(let i = 0; i < array.length/2; i++) { temp = array[i]; array[i] = array[array.length -1 - i]; array[array.length -1 -i] = temp } console.log(array) } let array = [1, 2, 3, 4, 5] reverseArray(array) // Singly Link List function slNode(val) { //node function this.val = null; this.next = null; } function slList() { this.head = null; this.AddToFront = function(val) { let neo = new slNode(val); neo.next = this.head; this.head = neo; } this.AddToBack = function(val) { runner = this.head while(runner){ if(runner.next == null){ runner.next = new slNode(val) return this.head; } else{ runner = runner.next; } } } }
export default function redicabTransportCompany(httpService) { const schedulePickupUrl = 'http://redicab.com/schedulepickup'; return { schedulePickup(transportDetails) { const details = { passeger: transportDetails.passengerName, pickup: '콘퍼런트 센터', pickupTime: transportDetails.departureTime, dropoff: '공항', rateCode: 'JavascriptConference', }; return httpService.post(schedulePickupUrl, details).then(function onSuccess(confirmation) { return confirmation.confirmationCode; }); }, }; }
const test = require('tape'); const stableSort = require('./stableSort.js'); test('Testing stableSort', (t) => { //For more information on all the methods supported by tape //Please go to https://github.com/substack/tape t.true(typeof stableSort === 'function', 'stableSort is a Function'); //t.deepEqual(stableSort(args..), 'Expected'); //t.equal(stableSort(args..), 'Expected'); //t.false(stableSort(args..), 'Expected'); //t.throws(stableSort(args..), 'Expected'); const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const compare = () => 0; t.deepEqual(stableSort(arr, compare), arr, 'Array is properly sorted'); t.end(); });
import Party from './party'; import v8n from 'v8n'; export default class Driver extends Party { constructor(gridChatroom) { super(gridChatroom); this.wantRiders = false; } startRepl() { super.startRepl(); this.inquirer.ui.process.subscribe(this.onEachAnswer.bind(this)); this.addMinPricePrompt(); } addMinPricePrompt() { this.prompts.next({ type: 'input', name: 'acceptanceBoundary', message: "What is the minimum price you'll accept?", validate: (input) => v8n() .number() .greaterThan(0) .test(parseInt(input, 10)), }); } addStartLookingConfirmationPrompt() { this.prompts.next({ type: 'confirm', name: 'confirmStart', message: `Start looking for riders who will pay >= $${this.acceptanceBoundary}?`, default: false, }); } onEachAnswer({ name, answer }) { switch (name) { case 'acceptanceBoundary': this.acceptanceBoundary = answer; this.addStartLookingConfirmationPrompt(); break; case 'confirmStart': if (answer) { // Start looking for riders this.prompts.complete(); this.bottomBar.log.write(`Looking for riders ${this.acceptanceBoundary}`); this.multipleNegotiator .startNegotiating(this.acceptanceBoundary, true, true) .then((a) => { console.log('Ha multi negotiation successful', a); }) .catch((e) => { console.log('Multi negotiation failed', e); }) .finally(async () => { // Start asking again await this.multipleNegotiator.reset(); this.startRepl(); }); } else { // Start asking again this.addMinPricePrompt(); } break; } } }
export function prettyDate(time) { let x = new Date(time); return x.getDay() + "." + x.getMonth() + "." + x.getFullYear(); } export function prettyTime(time) { let x = new Date(time) return x.getHours() + ":" + x.getMinutes() } export function prettyHslTimeDelay(timeIn) { if (!timeIn) { return null } let time = timeIn < 0 ? -timeIn : timeIn let hours = Math.floor(time / 3600) let minutes = Math.floor((time - hours * 3600) / 60) let seconds = time - hours * 3600 - minutes * 60 return (hours !== 0) ? `${hours} h ${minutes} min ${seconds} s` : `${minutes} min ${seconds} s` }
import React from 'react'; import { connect } from 'react-redux'; import CreatePoll from '../components/createPoll'; import update from 'immutability-helper'; class CreatePollContainer extends React.Component { constructor(props) { super(props); this.errors = []; } addOption = () => { this.props.setOptions([...this.props.options, ""]); } removeOption = (index) => { this.props.setOptions(this.props.options.filter((e, i) => i !== index)); } editOption = (index, value) => { const updated = update(this.props.options, {}); updated[index] = value; this.props.setOptions(updated); this.forceUpdate(); } handleCreate = () => { if (this.validatePoll()) { const body = JSON.stringify( { title: this.props.poll.title, options: this.getValidOptions(), allowAnon: this.props.poll.allowAnon, allowNewEntries: this.props.poll.allowNewEntries, } ); fetch('/api/newPoll', { credentials: 'include', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: 'POST', body: body }) .then((res) => res.json()) .then((res) => { if (res.error) { // Go to error page. this.props.setError(res.error); this.props.switchView("error"); return; } this.props.clearCreate(); this.props.changeToPoll(res); }); } }; getValidOptions = () => this.props.poll.options.filter((e) => e.length > 0); validatePoll = () => { const errors = []; const poll = this.props.poll; if (poll.title.length <= 0) { errors.push("Poll must have a title."); } if (this.getValidOptions().length < 2) { errors.push("Poll must have at least two options."); } this.errors = errors; this.forceUpdate(); return errors.length <= 0; } render() { return ( <CreatePoll poll={this.props.poll} options={this.props.options} errors={this.errors} setTitle={this.props.setTitle} addOption={this.addOption} removeOption={this.removeOption} editOption={this.editOption} toggleAnon={this.props.toggleAnon} toggleNew={this.props.toggleNew} handleCreate={this.handleCreate} /> ) } } const mapStateToProps = (state) => { return { poll: state.createPoll, options: state.createPoll.options }; }; const mapDispatchToProps = (dispatch) => { return { setTitle: (title) => dispatch({type: 'SET_TITLE', text: title}), setOptions: (options) => dispatch({type: 'SET_OPTIONS', options}), toggleAnon: () => dispatch({type: 'TOGGLE_ANON'}), toggleNew: () => dispatch({type: 'TOGGLE_NEW'}), changeToPoll: (poll) => { dispatch({type: 'SET_POLL', poll: poll}); dispatch({type: 'CHANGE_VIEW', view: 'viewPoll'}); }, clearCreate: () => dispatch({type: 'CLEAR_CREATE'}), switchView: (view) => dispatch({type: 'CHANGE_VIEW', view}), setError: (error) => dispatch({type: 'SET_ERROR', error}) } }; export default connect(mapStateToProps, mapDispatchToProps)(CreatePollContainer);
import React, {Component} from 'react'; import Comments from './Comments'; import CommentForm from './CommentForm'; class Comment extends Component { render() { return ( <div className="Commentbox"> <Comments comments={this.props.comments} /> <hr/> <CommentForm addComment={this.props.addComment} statusIndex={this.props.statusIndex}/> </div> ); } } Comment.propTypes = { comments: React.PropTypes.array.isRequired } export default Comment;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* global UserService, GroupService */ function SystemAction(appContext) { var own = this; own.systemLoad = function (message) { if (appContext.isReload) { var task = new Task(); task.push(function () { var userChatSender=appContext.getSender(UserChatSender); userChatSender.getLastList(); var roomSender = appContext.getSender(RoomSender); roomSender.getRoomList(); var userSender = appContext.getSender(UserSender); userSender.sendUpdateStatus("1"); }); task.start(); } }; } function PersonalAction(appContext) { var own = this; own.setUserData = function (message) { var head = message.head; var body = message.body; var userData = body.userData; var personalService = appContext.getService(PersonalService); personalService.setUserData(userData); }; } function UserAction(appContext) { var own = this; own.setUserCategoryWithUserList = function (message) { var head = message.head; var body = message.body; var userCategoryList = body.userCategoryList; var userDataList = body.userDataList; var userCategoryMemberList = body.userCategoryMemberList; var userService = appContext.getService(UserService); userService.setUserCategoryWithUserList(userCategoryList, userDataList, userCategoryMemberList); }; own.setUserData = function (message) { var head = message.head; var body = message.body; var userData = body.userData; }; own.updateUserData = function (message) { var head = message.head; var body = message.body; var userId = body.userId; var userService = appContext.getService(UserService); userService.updateUserDataById(userId); } } function GroupAction(appContext) { var own = this; own.setGroupCategoryWithGroupList = function (message) { var head = message.head; var body = message.body; var groupCategoryList = body.groupCategoryList; var groupList = body.groupList; var groupCategoryMemberList = body.groupCategoryMemberList; var groupService = appContext.getService(GroupService); groupService.setGroupCategoryWithGroupList(groupCategoryList, groupList, groupCategoryMemberList); }; own.updateGroup = function (message) { var head = message.head; var body = message.body; var group = body.group; // var userService=appContext.getService(UserService); // userService.setUserCategoryWithUserList(userCategoryList, userDataList, userCategoryMemberList); }; } function RoomAction(appContext) { var own = this; own.setRoomList = function (message) { var head = message.head; var body = message.body; var roomList = body.roomList; var roomService = appContext.getService(RoomService); roomService.setRoomList(roomList); }; } function UserChatAction(appContext) { var own = this; own.receiveUserChatMessage = function (message) { var head = message.head; var body = message.body; var messageKey = body.messageKey; var sendUserId = body.sendUserId; var receiveUserId = body.receiveUserId; var content = body.content; var userChatService = appContext.getService(UserChatService); userChatService.receiveUserChatMessage(messageKey, sendUserId, receiveUserId, content); } own.setLastList= function (message) { var head = message.head; var body = message.body; var userId = body.userId; var userLastList = body.userLastList; var groupLastList = body.groupLastList; var userChatService = appContext.getService(UserChatService); userChatService.setLastList(userId, userLastList, groupLastList); } } function GroupChatAction(appContext) { var own = this; own.receiveGroupChatMessage = function (message) { var head = message.head; var body = message.body; var messageKey = body.messageKey; var userId = body.userId; var groupId = body.groupId; var content = body.content; var groupChatService = appContext.getService(GroupChatService); groupChatService.receiveGroupChatMessage(messageKey, userId, groupId, content) } } function RoomChatAction(appContext) { var own = this; own.receiveRoomChatMessage = function (message) { var head = message.head; var body = message.body; var messageKey = body.messageKey; var userId = body.userId; var roomId = body.roomId; var content = body.content; var roomChatService = appContext.getService(RoomChatService); roomChatService.receiveRoomChatMessage(messageKey, userId, roomId, content) } } /*****************************/
import R from 'ramda'; import I from 'immutable'; export const getViewValue = (microcastleState, view) => { const parts = view.get('part') || []; if (view.get('state') == 'change') { const path = view.get('attribute') ? [view.get('type'), view.get('entry'), view.get('attribute'), ...parts] : [view.get('type'), view.get('entry'), ...parts]; const x = Symbol(); const saved = microcastleState.getIn(['data', ...path]); const changeState = microcastleState.getIn(['editor', 'tempState', ...path], x); return changeState == x ? saved : changeState; } if (view.get('state') == 'new') { const newState = microcastleState.getIn(['editor', 'newState']); const entry = newState.find(v => v.get('id') == view.get('entry')); if (!entry) return undefined; return entry.getIn(['data', view.get('attribute'), ...parts]); } }; export const getAllEntries = (microcastle, type) => { return microcastle.getIn(['data', type]).filter((v, k) => { const deleteList = microcastle.getIn(['editor', 'deleteState'], new I.List()); return !deleteList.map((deleted) => { return deleted.get('type') == type && deleted.get('entry') == k; }).includes(true); }); }; export const getNewViewEntry = (microcastleState, view) => { const newState = microcastleState.getIn(['editor', 'newState']); const entry = newState.find(v => v.get('id') == view.get('entry')); return entry; }; export const changeViewValue = (microcastleState, view, value) => { const parts = view.get('part') || []; if (view.get('state') == 'change') { const pathBase = [view.get('type'), view.get('entry'), view.get('attribute')]; const path = [...pathBase, ...parts]; let ret = microcastleState; if (!microcastleState.getIn(['editor', 'tempState', ...pathBase])) { const before = microcastleState.getIn(['data', ...pathBase]); if (before) { ret = ret.setIn(['editor', 'tempState', ...pathBase], before); } } return ret.setIn(['editor', 'tempState', ...path], value); } if (view.get('state') == 'new') { const newState = microcastleState.getIn(['editor', 'newState']); const index = newState.findIndex(v => v.get('id') == view.get('entry')); return microcastleState.setIn(['editor', 'newState', index, 'data', view.get('attribute'), ...parts], value); } }; export const getSchemaFromView = (schema, microcastle, view) => { const type = schema[view.get('type')]; const attributes = type['attributes']; if (!attributes) return type; const attribute = attributes[view.get('attribute')]; if (!attribute) return type; if (!view.has('part')) return attribute; return R.reduce((a, l) => { if (a.attr['type'] == 'array') { return { attr: a.attr['subtype'], view: a.view.update('part', p => p.push(l)) }; } if (a.attr['type'] == 'flex') { const flexType = getViewValue(microcastle, a.view).get('_flex_type'); return { attr: a.attr['flexes'][flexType][l], view: a.view.update('part', p => p.push(l)) }; } if (a.attr['type'] == 'group') { return { attr: a.attr.members[l], view: a.view.update('part', p => p.push(l)) }; } return {attr: a.attr.get(l), view: a.view.push(l)}; }, {attr: attribute, view: view.set('part', new I.List())}, view.get('part')).attr; }; export const getAllAttributesForEntry = (schema, microcastle, view) => { const scheme = getSchemaFromView(schema, microcastle, view); return R.pipe( R.keys, R.map(key => view.set('attribute', key)) )(scheme.attributes); };
function track(){ localStorage.setItem("reason", "track"); window.location.href = "sudTrack.html"; } function report(){ alert("Feature Not yet available"); }
module.exports = require('./learner_state.router.js');
const four ={ "results": { "id":4, "user_id":"", "date":"2019-03-21", "heading":"Past one month garbage and sewage are flowing", "detail":"Despite many complaints to chennai corporation about garbage and sewage overflowing past one month, there is no use at all. It causing problems to pedestrians and children’s ; You can see the street how bad it is.", "address":"Diwan sahib garden, royapettah, chennai", "posterpath":"https://i.ibb.co/WFwkwbn/4.jpg", "category":"Garbage Dumping", "location":"Chennai", "status":"Open", "comment":"" } } export default four;
import React from 'react'; import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import Dashboard from './Dashboard'; require('jest-canvas-mock'); const USER_NAME = 'joe'; const mockSummary = { totalOwed: 2, overallLender: USER_NAME, }; const mockUsers = { partner: 'john', }; const mockCurrency = '$'; test('Show login page when not authenticated', () => { render( <Dashboard summary={mockSummary} users={mockUsers} currency={mockCurrency} isAuthenticated={false} />, ); expect( screen.getByText('Sign up or login to get started'), ).toBeInTheDocument(); expect(screen.queryByText('Split A Bill')).not.toBeInTheDocument(); }); test('Show main dashboard when logged in', () => { render( <Dashboard summary={mockSummary} users={mockUsers} current={mockCurrency} isAuthenticated={true} />, ); expect( screen.queryByText('Sign up or login to get started'), ).not.toBeInTheDocument(); expect(screen.getByText('Split A Bill')).toBeInTheDocument(); }); test('Show Call It Even button when user owes money', () => { render( <Dashboard summary={mockSummary} users={mockUsers} currency={mockCurrency} isAuthenticated={true} />, ); expect(screen.getByText(/joe\s*gets\s*\$\s*2/)).toBeInTheDocument(); // if total owed > 0, and user.partner != summary.overallLender then call-it-even expect(screen.getByText('Call It Even')).toBeInTheDocument(); }); test('Show Settle Up button when user is owed money', () => { render( <Dashboard summary={mockSummary} users={{ partner: USER_NAME, }} currency={mockCurrency} isAuthenticated={true} />, ); // if total owed > 0, and user.partner == summary.overallLender then show settle up expect(screen.getByText('Settle Up')).toBeInTheDocument(); }); test('Correct elements show when no money is owed', () => { render( <Dashboard summary={{ totalOwed: 0, overallLender: USER_NAME, }} users={{ partner: USER_NAME, }} currency={mockCurrency} isAuthenticated={true} />, ); expect( screen.getByText(/You and \s*joe\s* are all square/), ).toBeInTheDocument(); expect(screen.queryByText('Settle Up')).not.toBeInTheDocument(); expect(screen.queryByText('Call It Even')).not.toBeInTheDocument(); });
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('vyan')) : typeof define === 'function' && define.amd ? define(['vyan'], factory) : (global = global || self, factory(global.vyan)); }(this, function (vyan) { 'use strict'; function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var MyButton = /*#__PURE__*/ function (_Component) { _inheritsLoose(MyButton, _Component); /** *Creates an instance of MyButton. * @param {*} [_id=null] - "vjs-component" wrapper id * @param {*} [_parentViewId=null] - Parent View ID * @param {*} [_parentContainerId=null] - Parent Container ID * @param {boolean} [_createDOMElement=true] - Set "True" if HTML Template of Component generate internally. Set - False when Template designed externally. * @memberof MyButton */ function MyButton(_id, _parentViewId, _parentContainerId, _createDOMElement) { if (_id === void 0) { _id = null; } if (_parentViewId === void 0) { _parentViewId = null; } if (_parentContainerId === void 0) { _parentContainerId = null; } if (_createDOMElement === void 0) { _createDOMElement = true; } return _Component.call(this, _id, _parentViewId, _parentContainerId, _createDOMElement) || this; } /** * * Lifecycle Method * @param {string} [_label="Button"] * @param {string} [_formId="defaultform"] * @memberof MyButton */ var _proto = MyButton.prototype; _proto.init = function init(_label, _formId) { if (_label === void 0) { _label = "Button"; } if (_formId === void 0) { _formId = "defaultform"; } this.label = _label; this.formId = _formId; // call super class init method _Component.prototype.init.call(this); } /** * * Lifecycle Method * @memberof MyButton */ ; _proto.initComponent = function initComponent() { _Component.prototype.initComponent.call(this); } /** * Create HTML Elements for Button * LifeCycle Method * @memberof MyButton */ ; _proto.createDOMContent = function createDOMContent() { _Component.prototype.createDOMContent.call(this); var tmpCompContentEl = this.createComponentHTML(); // Use following method to add Template to Component Wrapper this.addToComponentElement(tmpCompContentEl); } /** * * Call by Attached Method * Implement all Event Handlers here * LifeCycle Method * @memberof MyButton */ ; _proto.addEventHandler = function addEventHandler() { var _this = this; _Component.prototype.addEventHandler.call(this); if (this.componentElement != null) { var buttonEl = this.componentElement.querySelector("input[type='button']"); buttonEl.addEventListener("click", function (e) { _this.clickHandler(e); }); } }; _proto.clickHandler = function clickHandler(event) { event.preventDefault(); var srcObjfrmEvt = event.target; console.log(srcObjfrmEvt.value + " :: HTML Button Click Event Received ::"); console.log("MyButton Custom Click Event Dispatched"); this.dispatchEvent(vyan.EventUtils.CLICK, this); } /** * * Implement Component Enabled here * this method call by "enabled" setter * @memberof MyButton */ ; _proto.setComponentEnabled = function setComponentEnabled() { _Component.prototype.setComponentEnabled.call(this); var buttonEl = this.componentElement.querySelector("input[type='button']"); if (this.enabled == false) { buttonEl.setAttribute("disabled", "disabled"); } else { if (buttonEl.hasAttribute("disabled")) { buttonEl.removeAttribute("disabled"); } } } /** * * Implement Component ReadOnly here * this method call by "readonly" setter * @memberof MyButton */ ; _proto.setComponentReadOnly = function setComponentReadOnly() { _Component.prototype.setComponentReadOnly.call(this); } /** * * call by createDOMContent * @memberof MyButton */ ; _proto.createComponentHTML = function createComponentHTML() { var btnHtml = "<input type=\"button\" value=\"" + this.label + "\">"; return btnHtml; }; return MyButton; }(vyan.Component); var HelloWorldView = /*#__PURE__*/ function (_View) { _inheritsLoose(HelloWorldView, _View); function HelloWorldView(_id, _route, _navevent, _navparams, _parentViewStackId) { return _View.call(this, _id, _route, _navevent, _navparams, _parentViewStackId) || this; } var _proto = HelloWorldView.prototype; _proto.initView = function initView() { _View.prototype.initView.call(this); } //Overrides by SubClass // call by attachView ; _proto.bindView = function bindView() { _View.prototype.bindView.call(this); } /* Add HTML Element Event Handlers call by attachView */ ; _proto.addViewHandler = function addViewHandler() { _View.prototype.addViewHandler.call(this); } // call by attachView ; _proto.createViewContent = function createViewContent() { var tmpViewContentEl = this.createViewHTML(); this.addToViewElement(tmpViewContentEl); var cmpButton = new MyButton("cmpBtn", this.id, "helloContainer", true); cmpButton.init("My Component Button Enabled"); cmpButton.attach(); cmpButton.enabled = true; // Add Break Element var buttonContEl = vyan.ElementUtils.container("helloContainer", this.id); this.addBreakElement(buttonContEl); var cmpButton2 = new MyButton("cmpBtn2", this.id, "helloContainer", true); cmpButton2.init("My Component Disabled"); cmpButton2.attach(); cmpButton2.enabled = false; }; _proto.createViewHTML = function createViewHTML() { var thisRef = this; var helloTmplHtml = "\n <div>\n <p><h2>" + this.id + " View Contents</h2></p>\n <p><h4>Hello World !!!</h4></p>\n </div>\n <div> <p> " + this.id + " ::: Parameter Received ::: " + thisRef.navParams + " </p></div>\n </br>\n </div>\n <p> <h4> Custom Component Demo </h4></p>\n <p> Check Console for My Component Click Event </p>\n </div>\n </br>\n <div class=\"vjs-container helloContainer\">\n </div> \n "; return helloTmplHtml; }; _proto.addBreakElement = function addBreakElement(_parentEl) { var brakEl = "</br></br>"; _parentEl.insertAdjacentHTML('beforeend', brakEl); }; _proto.removeViewHandler = function removeViewHandler() { _View.prototype.removeViewHandler.call(this); }; return HelloWorldView; }(vyan.View); var SimpleNavigator = /*#__PURE__*/ function (_ViewNavigator) { _inheritsLoose(SimpleNavigator, _ViewNavigator); function SimpleNavigator(_id, _parentId, _parentContainerId) { return _ViewNavigator.call(this, _id, _parentId, _parentContainerId) || this; } var _proto = SimpleNavigator.prototype; _proto.initNavigator = function initNavigator() { this.history = false; this.initEventRoutes(); }; _proto.renderNavigatorContent = function renderNavigatorContent() { _ViewNavigator.prototype.renderNavigatorContent.call(this); }; _proto.createView = function createView(_viewId, _route, _navevent, _navparams, _viewStackId) { var tmpView = null; switch (_viewId) { case "helloview": tmpView = new HelloWorldView(_viewId, _route, _navevent, _navparams, _viewStackId); break; default: tmpView = new View(_viewId, _route, _navevent, _navparams, _viewStackId); break; } return tmpView; }; _proto.initEventRoutes = function initEventRoutes() { var helloEvntRoutes = [{ navEvent: "Hello_NavEvent", viewstackId: "HelloWorldStack", viewId: "helloview", path: "/hello" }]; this.eventRouter = new vyan.EventRouter(helloEvntRoutes); }; return SimpleNavigator; }(vyan.ViewNavigator); var AppViewManager = /*#__PURE__*/ function (_ViewManager) { _inheritsLoose(AppViewManager, _ViewManager); function AppViewManager() { return _ViewManager.apply(this, arguments) || this; } var _proto = AppViewManager.prototype; _proto.initialize = function initialize() { _ViewManager.prototype.initialize.call(this); this.initRoutes(); }; _proto.createNavigator = function createNavigator(_navigatorId, _parentId, _parentContainerId) { var tmpNavigator = null; switch (_navigatorId) { case "simpleNavigator": tmpNavigator = new SimpleNavigator(_navigatorId, _parentId, _parentContainerId); break; default: tmpNavigator = new vyan.ViewNavigator(_navigatorId, _parentId, _parentContainerId); } return tmpNavigator; }; _proto.initRoutes = function initRoutes() { var tmpRoutes = [{ path: "/hello", navigatorId: "simpleNavigator", parentId: "root" }]; this.routes = new vyan.Router(tmpRoutes); }; return AppViewManager; }(vyan.ViewManager); var Application = /*#__PURE__*/ function () { function Application() { this.initialize(); } var _proto = Application.prototype; _proto.initialize = function initialize() { this.viewmanager = new AppViewManager(); }; _proto.start = function start() { var helloNavEvent = new vyan.NavigationEvent(vyan.EventUtils.NAV_CHANGE_EVENT, "Hello_NavEvent", "My First Hello World Message as Navigation Param", "/hello"); //Dispatch Hello Navigation Event vyan.EventBroadCaster.navEventChannel.dispatchEvent(helloNavEvent); }; return Application; }(); var startApp = function startApp() { var myApp = new Application(); myApp.start(); }; startApp(); }));
const knex = require("./connection"); module.exports = { getOne: function(id) { return knex("users") .where("id", id) .first(); }, getOneByEmail: function(email) { return knex("users") .where("email", email) .first(); }, create: function(user) { return knex("users") .insert(user, "id") .then(ids => { return ids[0]; }); }, setToken: function(id, token) { console.log("ID IN USER JS", id); console.log("TOKEN IN USER JS", token); return knex("users") .where("id", id) .update("token", token); }, updateBot: bot => { if (bot.image_id) { return knex .raw( ` UPDATE bots SET name = '${bot.name}', description = '${bot.description}', updated_date = '${bot.updated_date}', tokens = setweight(to_tsvector('english','${ bot.name }'), 'A') || setweight(to_tsvector('english','${bot.description}'), 'B'), image_id = '${bot.image_id}' WHERE id = '${bot.id}' ` ) .then(ids => { return ids; }) .catch(err => { console.log("MY ERR", err); }); } else { return knex .raw( ` UPDATE bots SET name = '${bot.name}', description = '${bot.description}', updated_date = '${bot.updated_date}', tokens = setweight(to_tsvector('english','${ bot.name }'), 'A') || setweight(to_tsvector('english','${bot.description}'), 'B') WHERE id = '${bot.id}' ` ) .then(ids => { return ids; }) .catch(err => { console.log("MY ERR", err); }); } }, createBot: bot => { console.log("bot", bot); return knex .raw( ` INSERT INTO bots (id, name, description, user_id, created_date, tokens, image_id) VALUES ( '${bot.id}', '${bot.name}', '${bot.description}', '${bot.user_id}'::uuid, '${bot.created_date}', setweight(to_tsvector('english','${ bot.name }'), 'A') || setweight(to_tsvector('english','${ bot.description }'), 'B'), '${bot.image_id}' ) RETURNING id; ` ) .then(ids => { return ids; }) .catch(err => { console.log("MY ERR", err); }); }, deleteBotPlatforms: bot => { return knex("bots_platforms") .where("bot_id", bot.id) .del(); }, deleteBot: id => { return knex("bots") .where("id", id) .del(); }, getUserBot: function(bot_id) { return knex .raw( ` SELECT b.id, b.name, b.description, b.user_id, ROUND(AVG(r.rating_score), 1) AS rating_score, COUNT(r.user_id) AS count_voted, array_agg(json_build_object('platform', pl.platform, 'link', b_p.link)) AS platforms, b.created_date, img.uri FROM public.bots b LEFT OUTER JOIN public.rating r ON r.bot_id = b.id INNER JOIN public.bots_platforms b_p ON b_p.bot_id = b.id INNER JOIN public.platforms pl ON b_p.platform_id = pl.id INNER JOIN public.images img ON img.id = b.image_id WHERE b.id = '${bot_id}' GROUP BY (b.id, img.uri); ` ) .then(result => { return result.rows[0]; }); }, getUserBots: function(id) { return knex .raw( ` SELECT b.id, b.name, b.description, b.user_id, ROUND(AVG(r.rating_score), 1) AS rating_score, COUNT(r.user_id) AS count_voted, array_agg(json_build_object('platform', pl.platform, 'link', b_p.link)) AS platforms, b.created_date, img.uri FROM public.bots b LEFT OUTER JOIN public.rating r ON r.bot_id = b.id INNER JOIN public.bots_platforms b_p ON b_p.bot_id = b.id INNER JOIN public.platforms pl ON b_p.platform_id = pl.id INNER JOIN public.images img ON img.id = b.image_id WHERE b.user_id = '${id}' GROUP BY (b.id, img.uri); ` ) .then(result => { return result.rows; }); }, getTopFivePlatforms: () => { return knex .raw( ` SELECT pl.platform, COUNT(b_p.platform_id) AS count FROM public.platforms pl INNER JOIN public.bots_platforms b_p ON b_p.platform_id = pl.id GROUP BY(pl.platform) ORDER BY count DESC LIMIT 5; ` ) .then(result => { return result.rows; }); }, addAvatar: data => { console.log("add Avatar data:", data); return knex("images") .insert({ id: data.id, uri: data.uri }, "id") .then(result => { console.log(result); return result; }); }, getPlatformTopBots: async data => { try { const itemsPerPage = 7; const offset = (data.page - 1) * itemsPerPage; let queryCondition = ""; let responseTotalCount = 0; if (data.platform !== "All") { queryCondition = "WHERE pl.platform = '" + data.platform + "'"; responseTotalCount = await knex.raw( ` SELECT COUNT(b.id) FROM public.bots b INNER JOIN public.bots_platforms b_p ON b_p.bot_id = b.id INNER JOIN public.platforms pl ON b_p.platform_id = pl.id WHERE pl.platform = '${data.platform}'; ` ); } else { responseTotalCount = await knex.raw(`SELECT COUNT(b.id) FROM bots b;`); } totalCount = responseTotalCount.rows[0].count; console.log("queryCondition", queryCondition); const responseResult = await knex.raw( ` SELECT b.id, b.name, b.description, b.user_id, u.username as author_name, ROUND(AVG(r.rating_score), 1) AS rating_score, COUNT(r.user_id) AS count_voted, json_object(array_agg(pl.platform), array_agg(b_p.link)) AS platforms, b.created_date, img.uri FROM public.bots b LEFT OUTER JOIN public.rating r ON r.bot_id = b.id INNER JOIN public.users u ON b.user_id = u.id INNER JOIN public.bots_platforms b_p ON b_p.bot_id = b.id INNER JOIN public.platforms pl ON b_p.platform_id = pl.id INNER JOIN public.images img ON img.id = b.image_id ${queryCondition} GROUP BY (b.id, u.username, img.uri) ORDER BY count_voted DESC LIMIT ${itemsPerPage} OFFSET ${offset} ` ); result = responseResult.rows; return { totalCount: totalCount, bots: result }; } catch (err) { console.log("my err", err); return []; } }, getPlatformBots: function(data) { const itemsPerPage = 3; const offset = (data.page - 1) * itemsPerPage; let queryCondition = "WHERE pl.platform = " + "'" + data.platform + "'"; return knex .raw( ` SELECT b.id, b.name, b.description, b.user_id, u.username as author_name, ROUND(AVG(r.rating_score), 1) AS rating_score, COUNT(r.user_id) AS count_voted, json_object(array_agg(pl.platform), array_agg(b_p.link)) AS platforms, b.created_date, img.uri FROM public.bots b LEFT OUTER JOIN public.rating r ON r.bot_id = b.id INNER JOIN public.users u ON b.user_id = u.id INNER JOIN public.bots_platforms b_p ON b_p.bot_id = b.id INNER JOIN public.platforms pl ON b_p.platform_id = pl.id INNER JOIN public.images img ON img.id = b.image_id ${queryCondition} GROUP BY (b.id, u.username, img.uri) LIMIT ${itemsPerPage} OFFSET ${offset} ` ) .then(result => { console.log(queryCondition, result.rows); return result.rows; }) .catch(err => { console.log("my err", err); return []; }); }, getBots: function(page) { const itemsPerPage = 3; const offset = (page - 1) * itemsPerPage; return knex .raw( ` SELECT b.id, b.name, b.description, b.user_id, u.username as author_name, ROUND(AVG(r.rating_score), 1) AS rating_score, COUNT(r.user_id) AS count_voted, json_object(array_agg(pl.platform), array_agg(b_p.link)) AS platforms, b.created_date, img.uri FROM public.bots b LEFT OUTER JOIN public.rating r ON r.bot_id = b.id INNER JOIN public.users u ON b.user_id = u.id INNER JOIN public.bots_platforms b_p ON b_p.bot_id = b.id INNER JOIN public.platforms pl ON b_p.platform_id = pl.id INNER JOIN public.images img ON img.id = b.image_id GROUP BY (b.id, u.username, img.uri) LIMIT ${itemsPerPage} OFFSET ${offset} ` ) .then(result => { return result.rows; }); }, getTextPlatforms: keys => { return knex .select("id") .from("platforms") .whereIn("platform", keys) .then(platforms => { return platforms; }); }, getDigitPlatforms: keys => { return knex .select("platform") .from("platforms") .whereIn("id", keys) .then(platforms => { return platforms; }); }, setBotPlatform: arr => { return knex("bots_platforms").insert(arr); }, getBotPlatforms: botIds => { return knex("bots_platforms") .whereIn("bot_id", botIds) .then(platforms => { return platforms; }); }, getSearchBot: async data => { let punctuationLess = data.text.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, ""); let spacesLess = punctuationLess.replace(/\s{2,}/g, " "); const readyText = spacesLess.replace(/ /g, " | "); console.log("SEARCH SENTENCE: ", readyText); const itemsPerPage = 7; const offset = (data.page - 1) * itemsPerPage; let platformsStr = ""; let responseTotalCount = 0; console.log("data.platforms", data.platforms); if (!data.platforms.includes("All")) { data.platforms.forEach((item, index) => { if (index === 0) { if (data.platforms.length === 1) { platformsStr += "AND (pl.platform = " + "'" + item + "')"; } else { platformsStr += "AND (pl.platform = " + "'" + item; } } else if (index === data.platforms.length - 1) { platformsStr += "' OR" + " pl.platform = " + "'" + item + "')"; } else if (index !== data.platforms.length - 1) { platformsStr += "' OR" + " pl.platform = " + "'" + item; } }); } console.log(platformsStr); if (platformsStr) { responseTotalCount = await knex.raw( ` SELECT COUNT(b.id) FROM public.bots b INNER JOIN public.bots_platforms b_p ON b_p.bot_id = b.id INNER JOIN public.platforms pl ON b_p.platform_id = pl.id WHERE tokens @@ to_tsquery('${readyText}') ${platformsStr} ` ); } else { responseTotalCount = await knex.raw( `SELECT COUNT(b.id) FROM bots b WHERE tokens @@ to_tsquery('${readyText}');` ); } totalCount = responseTotalCount.rows[0].count; responseBots = await knex.raw( ` SELECT b.id, b.name, b.description, u.username as author_name, json_object(array_agg(pl.platform), array_agg(b_p.link)) AS platforms, ROUND(AVG(r.rating_score), 1) AS rating_score, COUNT(r.user_id) AS count_voted, b.created_date, img.uri FROM bots b LEFT OUTER JOIN public.rating r ON r.bot_id = b.id INNER JOIN public.bots_platforms b_p ON b_p.bot_id = b.id INNER JOIN public.platforms pl ON b_p.platform_id = pl.id INNER JOIN public.users u ON b.user_id = u.id INNER JOIN public.images img ON img.id = b.image_id WHERE tokens @@ to_tsquery('${readyText}') ${platformsStr} GROUP BY b.id, u.username, img.uri LIMIT ${itemsPerPage} OFFSET ${offset}; ` ); bots = responseBots.rows; console.log("totalCount", totalCount); console.log("bots", bots); return { totalCount: totalCount, bots: bots }; }, setBotRatingFromUser: data => { return knex("rating") .insert( { id: data.id, user_id: data.user_id, bot_id: data.bot_id, rating_score: data.rating_score, date_rated: data.date_rated }, "id" ) .then(result => { console.log(result); return result; }); }, updateBotRatingFromUser: data => { return knex("rating") .where({ user_id: data.user_id, bot_id: data.bot_id }) .update({ rating_score: data.rating_score, updated_date: data.updated_date }) .then(result => { return result; }); }, getBotRatingFromUser: data => { return knex("rating") .where({ user_id: data.user_id, bot_id: data.bot_id }) .select("rating_score") .then(result => { return result; }) .catch(error => { console.log(error); return 0; }); }, deleteBotRatingFromUser: data => { return knex("rating") .where({ user_id: data.user_id, bot_id: data.bot_id }) .del() .then(result => { return result; }); } };
const mysql = require('mysql2'); const connection = mysql.createConnection({ host: 'localhost', port: '3306', user: 'rafa', password: 'Cr6)sTYp:UfJ}4)', database: 'escudo' }); module.exports = connection;
import React, { PureComponent, Fragment} from 'react'; import moment from 'moment'; import { connect } from 'dva'; import { Row, Col, Card, Form, Input, Button, Table, Popconfirm, Divider, DatePicker, Modal } from 'antd'; import PageHeaderLayout from '../../../layouts/PageHeaderLayout'; const { RangePicker } = DatePicker; import styles1 from '../../common/List.less'; import styles2 from '../../common/Edit.less'; const styles = Object.assign({},styles1,styles2); const FormItem = Form.Item; const getValue = obj => Object.keys(obj).map(key => obj[key]).join(','); const formItemLayout = { labelCol: { span: 5, }, wrapperCol: { span: 19, }, }; const CashierAddForm = Form.create()( class CashierAddForm extends PureComponent{ handleAdd = (e) => { e.preventDefault(); const { dispatch, form,hideAddModal, handleFormReset,params } = this.props; form.validateFields((err, fieldsValue) => { if (err) return; delete fieldsValue.repassword; dispatch({ type: 'store/addCashier', payload: { ...fieldsValue, merchantId:params.id }, callback:handleFormReset }) hideAddModal(); }); } render(){ const { form,hideAddModal,addModalVisible } = this.props; const { getFieldDecorator } = form; return ( <Modal title="添加收银员" visible={addModalVisible} onOk={this.handleAdd} onCancel={hideAddModal} okText="保存" cancelText="取消" > <Form onSubmit={this.handleAdd} layout="horizontal"> <Form.Item {...formItemLayout} label="收银员编号" > {getFieldDecorator('code', { rules: [{ required: true, message: '请输入收银员编号' }], })( <Input placeholder="请输入收银员编号" /> )} </Form.Item> <Form.Item {...formItemLayout} label="收银员姓名" > {getFieldDecorator('name', { rules: [{ required: true, message: '请输入收银员姓名' }], })( <Input placeholder="请输入收银员编号" /> )} </Form.Item> {/*用于禁止浏览器自动写入密码*/} <Input name="password" type="password" style={{display:'none'}} /> <Form.Item {...formItemLayout} label="密码" > {getFieldDecorator('password', { rules: [{ required: true, message: '请输入密码' }], })( <Input type="password" name="password" placeholder="请输入密码" /> )} </Form.Item> <Form.Item {...formItemLayout} label="确认密码" > {getFieldDecorator('repassword', { rules: [{ required: true, message: '请重新输入密码' }, (rule, value, callback, source, options) =>{ const errors = []; if (value !== form.getFieldValue('password')) { errors.push(new Error('密码不一致')) } callback(errors) }], })( <Input type="password" placeholder="请重新输入密码" /> )} </Form.Item> </Form> </Modal> ); } } ) const CashierEditForm = Form.create()( class CashierEditForm extends PureComponent{ handleEdit = (e) => { e.preventDefault(); const { dispatch, form,hideEditModal,editModalId,handleStandardTableChange } = this.props; form.validateFields((err, fieldsValue) => { if (err) return; fieldsValue.id = editModalId; dispatch({ type: 'store/editCashier', payload: fieldsValue, callback:handleStandardTableChange }) hideEditModal(); }); } render(){ const { form,hideEditModal,editModalVisible,store:{ cashierObj } } = this.props; const { getFieldDecorator } = form; return ( <Modal title="添加收银员" visible={editModalVisible} onOk={this.handleEdit} onCancel={hideEditModal} okText="保存" cancelText="取消" > <Form onSubmit={this.handleEdit} layout="horizontal"> <Form.Item {...formItemLayout} label="收银员编号" > {getFieldDecorator('code', { initialValue:cashierObj.code, rules: [{ required: true, message: '请输入收银员编号' }], })( <Input placeholder="请输入收银员编号" /> )} </Form.Item> <Form.Item {...formItemLayout} label="收银员姓名" > {getFieldDecorator('name', { initialValue:cashierObj.name, rules: [{ required: true, message: '请输入收银员姓名' }], })( <Input placeholder="请输入收银员编号" /> )} </Form.Item> </Form> </Modal> ); } } ) const ChangePwdForm = Form.create()( class ChangePwdForm extends PureComponent{ handleChange = (e) => { e.preventDefault(); const { dispatch, form,hidePwdModal,pwdModalId } = this.props; form.validateFields((err, fieldsValue) => { if (err) return; fieldsValue.id = pwdModalId; delete fieldsValue.reNewPassword; dispatch({ type: 'store/changePwd', payload: fieldsValue, callback:function (result) { if(result.status !== 'error'){ hidePwdModal(); }else{ form.setFields({ adminPwd:{ errors:[new Error('管理员密码错误')] } }); } } }) }); } render(){ const { form,hidePwdModal,pwdModalVisible} = this.props; const { getFieldDecorator } = form; return ( <Modal title="修改密码" visible={pwdModalVisible} onOk={this.handleChange} onCancel={hidePwdModal} okText="保存" cancelText="取消" > <Form onSubmit={this.handleAdd} layout="horizontal"> <Form.Item {...formItemLayout} label="管理员密码" > {getFieldDecorator('adminPwd', { rules: [{ required: true, message: '请输入管理员密码' }], })( <Input placeholder="请输入管理员密码" /> )} </Form.Item> {/*用于禁止浏览器自动写入密码*/} <Input name="password" type="password" style={{display:'none'}} /> <Form.Item {...formItemLayout} label="新密码" > {getFieldDecorator('newPassword', { rules: [{ required: true, message: '请输入密码' }], })( <Input type="password" name="password" placeholder="请输入密码" /> )} </Form.Item> <Form.Item {...formItemLayout} label="确认密码" > {getFieldDecorator('reNewPassword', { rules: [{ required: true, message: '请重新输入密码' }, (rule, value, callback, source, options) =>{ const errors = []; if (value !== form.getFieldValue('newPassword')) { errors.push(new Error('密码不一致')) } callback(errors) }], })( <Input type="password" placeholder="请重新输入密码" /> )} </Form.Item> </Form> </Modal> ); } } ) @connect(({ store, loading }) => ({ store, loading: loading.models.store, })) @Form.create() export default class Cashier extends PureComponent { state = { addModalVisible: false, editModalVisible: false, pwdModalVisible: false, pwdModalId:0, editModalId:0, selectedRows: [], formValues: {}, }; componentDidMount() { const { dispatch, match:{params} } = this.props; dispatch({ type: 'store/fetchCashier', payload: {merchantId:params.id} }); } handleStandardTableChange = (pagination, filtersArg, sorter) => { const { dispatch, match} = this.props; const { formValues } = this.state; const filters = Object.keys(filtersArg).reduce((obj, key) => { const newObj = { ...obj }; newObj[key] = getValue(filtersArg[key]); return newObj; }, {}); const params = { currentPage: pagination.current, pageSize: pagination.pageSize, ...formValues, ...filters, }; if (sorter.field) { params.sorter = `${sorter.field}_${sorter.order}`; } dispatch({ type: 'store/fetchCashier', payload: { ...params, merchantId:match.params.id }, }); } renderForm() { return this.renderSimpleForm(); } showAddModal = () => { this.setState({ addModalVisible: true, }); } showEditModal = (id) => { this.setState({ editModalVisible: true, editModalId:id }); this.getCashier(id); } showPwdModal = (id) => { this.setState({ pwdModalVisible: true, pwdModalId:id }); } hideAddModal = () => { this.setState({ addModalVisible: false, }); } hideEditModal = () => { this.setState({ editModalVisible: false, }); } hidePwdModal = () => { this.setState({ pwdModalVisible: false, }); } getCashier = (id) => { this.props.dispatch({ type: 'store/getCashier', payload: {id:id} }); } handleFormReset = (o) => { const self = o.form?o:this; const { form, dispatch,match:{ params } } = self.props; form.resetFields(); self.setState({ formValues: {}, }); dispatch({ type: 'store/fetchCashier', payload: { merchantId:params.id, }, }); } handleSearch = (e) => { e.preventDefault(); const { dispatch, form, match:{ params } } = this.props; form.validateFields((err, fieldsValue) => { if (err) return; const values = { ...fieldsValue, updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(), }; if(values.serachTimeStart && values.serachTimeEnd){ values.serachTimeStart = moment(values.timeRange[0]).format('YYYY-MM-DD'); values.serachTimeEnd = moment(values.timeRange[1]).format('YYYY-MM-DD'); } delete values.timeRange; this.setState({ formValues: values, }); dispatch({ type: 'store/fetchCashier', payload: { merchantId:params.id, ...values }, }); }); } render() { const { store: { cashier }, loading, dispatch, match:{ params } } = this.props; const { getFieldDecorator } = this.props.form; const { list, pagination } = cashier; const { showPwdModal,showEditModal,handleStandardTableChange,handleFormReset } = this; const paginationProps = { showSizeChanger: true, showQuickJumper: true, ...pagination, }; const deleteCashier = (id)=>{ dispatch({ type: 'store/deleteCashier', payload: {id:id}, callback: (res) => { this.handleStandardTableChange({},{},{}) } }); } const columns = [ { title: '收银员编号', dataIndex: 'code', }, { title: '收银员姓名', dataIndex: 'name', }, { title: '交易金额(元)', dataIndex: 'trcansationMoney', render: (val) => val && Number(val)?Number(val).toFixed(2):0.00 }, { title: '交易笔数', dataIndex: 'trcansationNum' }, { title: '操作', dataIndex: 'id', render: (val) => ( <Fragment> <a onClick={function () { showPwdModal(val); }}>修改密码</a> <Divider type="vertical" /> <a onClick={function () { showEditModal(val); }}>编辑</a> <Divider type="vertical" /> <Popconfirm placement="topLeft" title="是否确定删除" onConfirm={function () { deleteCashier(val); }} okText="是" cancelText="否"> <a href="javascript:;">删除</a> </Popconfirm> </Fragment> ), }, ]; return ( <PageHeaderLayout> <Card bordered={false}> <div className={styles.tableList}> <div className={styles.tableListForm}> <Form onSubmit={this.handleSearch} layout="inline"> <Row gutter={{ md: 8, lg: 24, xl: 48 }}> <Col md={7} sm={24}> <FormItem label="收银员姓名"> {getFieldDecorator('searchName')( <Input placeholder="请输入" /> )} </FormItem> </Col> <Col md={7} sm={24}> <FormItem label="收银员编号"> {getFieldDecorator('searchCode')( <Input placeholder="请输入" /> )} </FormItem> </Col> <Col md={10} sm={24}> <FormItem label="交易时间区间"> {getFieldDecorator('timeRange')( <RangePicker/> )} </FormItem> </Col> </Row> <div style={{ overflow: 'hidden' }}> <span style={{ float: 'right', marginBottom: 24 }}> <Button type="primary" htmlType="submit">查询</Button> <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button> </span> </div> </Form> </div> <div className={styles.tableListOperator}> <Button icon="plus" type="primary" onClick={this.showAddModal}> 添加收银员 </Button> </div> <Table loading={loading} rowKey={record => record.key} dataSource={list} columns={columns} pagination={paginationProps} onChange={this.handleStandardTableChange} /> </div> </Card> <CashierAddForm dispatch={dispatch} addModalVisible={this.state.addModalVisible} params={params} handleFormReset={function () { handleFormReset(this); }} hideAddModal={this.hideAddModal} /> <CashierEditForm dispatch={dispatch} editModalVisible={this.state.editModalVisible} hideEditModal={this.hideEditModal} editModalId={this.state.editModalId} store={this.props.store} handleStandardTableChange={function () { handleStandardTableChange({ current:pagination.current, pageSize:pagination.pageSize },{},{}) }} /> <ChangePwdForm dispatch={dispatch} pwdModalVisible={this.state.pwdModalVisible} hidePwdModal={this.hidePwdModal} pwdModalId={this.state.pwdModalId} /> </PageHeaderLayout> ); } }
import React from 'react' import { Column, BodyCell, HeaderCell } from 'bypass/ui/table' import { Checkbox } from 'bypass/ui/checkbox' import { Table } from './table' import getColumn from '../../../Search/list/column' const columns = [ '_row', 'number', 'exp', 'cvv2', 'holder', 'level', 'type', 'bank', 'country_code', 'state_code', 'city', 'zip', 'address', 'email', 'phone', 'provider', 'returned', ] const List = ({ cards, minWidth, rowHeight, total, allSelected, onLoad, onSelect, onSelectAll }) => ( <Table list={cards} total={total} minWidth={minWidth} rowHeight={rowHeight} onLoad={onLoad} onRowClick={onSelect} > {columns.map(getColumn)} <Column label={'_'} width='50px' dataKey='selected' headerRenderer={() => ( <HeaderCell justify='center'> <Checkbox checked={allSelected} onChange={onSelectAll} /> </HeaderCell> )} cellRenderer={(cellData, dataKey, rowData, rowIndex) => ( <BodyCell justify='center' oddRow={(rowIndex % 2) !== 0} selected={rowData.get('selected')}> <Checkbox checked={cellData} /> </BodyCell> )} /> </Table> ) export default List
const {BaseModel} = require('./../base.model') class Keahlian extends BaseModel{ static get tableName(){ return 'support.keahlian' } static get idColumn(){ return 'id_keahlian' } } module.exports = Keahlian
var ExamwidgetStats = React.createClass({ getInitialState() { return { blank: null, doubt: null, answered: null } }, componentDidMount() { $.getJSON('/api/v1/exams.json', (response) => { this.blankAnswer(response); this.doubtAnswer(response); this.answered(response); }); }, blankAnswer(exams){ var blank = exams.filter((e) => { return ((e.value == null || e.value == "") && e.answer_id == null) ; }); this.setState({blank: blank.length}); }, doubtAnswer(exams){ var doubt = exams.filter((e) => { return e.doubt == true; }); this.setState({doubt: doubt.length}); }, answered(exams){ var doubt = exams.filter((e) => { return ((e.value != null || e.value != "") && e.answer_id != null) ; }); this.setState({answered: doubt.length}); }, render(){ return( <div className="widget"> <h3 className="page-header">{this.props.title}</h3> <ul className="nomargin"> <li> <button className="btn btn-xs btn-info"> - </button> : current question </li> <li> <button className="btn btn-xs btn-default"> - </button> : blank answer <strong>( {this.state.blank} )</strong> </li> <li> <button className="btn btn-xs btn-warning"> - </button> : doubt answer <strong>( {this.state.doubt} )</strong> </li> <li> <button className="btn btn-xs btn-success"> - </button> : answered question <strong>( {this.state.answered} )</strong> </li> </ul> <p>Click the last number to submit Quiz!</p> </div> ) } })
"use strict" var assert = require("chai").assert; var Calculator = require("../src/calculator"); suite("string calculator should", function() { function createCalculator() { return new Calculator(); } test("return default value if input is empty", function(){ var calculator = createCalculator(); var sum = calculator.add(null); assert.equal(sum, 0) }); test("return single number if input is single number", function () { var calculator = createCalculator(); var sum = calculator.add("2"); assert.equal(sum, 2); }); test("return sum of two comma separated one-digit numbers", function () { var calculator = createCalculator(); var sum = calculator.add("1,2"); assert.equal(sum, 1 + 2); }); test("return sum of any two comma separate numbers", function () { var calculator = createCalculator(); var sum = calculator.add("11,22"); assert.equal(sum, 11 + 22); }); test("return sum of any amount comma separate values", function () { var calculator = createCalculator(); var sum = calculator.add("1,2,3,4,5"); assert.equal(sum, 1+2+3+4+5); }); test("return sum of two newline separated numbers", function () { var calculator = createCalculator(); var sum = calculator.add("1\n2"); assert.equal(sum, 1 + 2); }); });
module.exports={ local_link:'http://localhost:3003', user_server_link:'http://localhost:3002' }