text
stringlengths
7
3.69M
var area_Produtos = document.querySelector("#areaProdutos"); var requestURL = 'https://gist.githubusercontent.com/mapreuss/cccf0781ba848648d9d8a6510201a027/raw/74b72ac19728a92306b296863b5a81c8a0b3d8d7/test.json'; var request = new XMLHttpRequest(); request.open('GET', requestURL); request.responseType = 'text'; request.send(); request.onload = function() { var infoProdutosText = request.response; var infoProdutos = JSON.parse(infoProdutosText); divProduto(infoProdutos); } function divProduto(jsonObj) { for(var i = 0; i < jsonObj.length; i++) { if(jsonObj[i].isActive == true){ //if(true){ var divProduto = document.createElement('div'); var imgProduto = document.createElement('img'); var ulProduto = document.createElement('ul'); var liProduto1 = document.createElement('li'); var liProduto2 = document.createElement('li'); var liProduto3 = document.createElement('li'); var liProduto4 = document.createElement('li'); var liProduto5 = document.createElement('li'); var aProduto = document.createElement('a'); divProduto.setAttribute("id", "div2"); imgProduto.setAttribute("src", jsonObj[i].picture); imgProduto.setAttribute("alt", "minha imagem"); imgProduto.setAttribute("id", "img_produtos"); divProduto.appendChild(imgProduto); ulProduto.setAttribute("id", "ul_info_produtos"); liProduto1.setAttribute("class", "nome_prod"); liProduto1.textContent = jsonObj[i].name; liProduto2.setAttribute("class", "prec_velho_prod"); liProduto2.textContent = jsonObj[i].oldPrice; liProduto3.setAttribute("class", "prec_novo_prod"); liProduto3.textContent = jsonObj[i].price; var precoEmTexto = jsonObj[i].price.substring(1) var preco = Number(precoEmTexto); var metadePreco = preco/2; liProduto4.setAttribute("class", "prec_vezes_prod"); liProduto4.textContent = "ou 2x de $" + metadePreco.toFixed(2); aProduto.setAttribute("class", "botao_comprar_produto"); aProduto.setAttribute("href", "#"); aProduto.textContent = "Comprar"; liProduto5.appendChild(aProduto); ulProduto.appendChild(liProduto1); ulProduto.appendChild(liProduto2); ulProduto.appendChild(liProduto3); ulProduto.appendChild(liProduto4); ulProduto.appendChild(liProduto5); divProduto.appendChild(ulProduto); //sessaoProdutos.appendChild(divProduto); area_Produtos.insertBefore(divProduto, area_Produtos.childNodes[4]) } } }
import React, { Component } from "react"; import ColorContext from "../../../contexts/ColorContext"; class Parent extends Component { constructor(props) { super(props); this.state = { color: "blue", }; } changeColor = (color) => { this.setState({ color: color }); }; render() { return ( <div> <ColorContext.Provider value={this.state.color}> {this.props.children} <button onClick={() => this.changeColor("yellow")}>Yellow</button> </ColorContext.Provider> </div> ); } } export default Parent;
// example.test.js is configurable but by default testing looks for .test.js // no need to use testing library // import { render, screen } from '@testing-library/react'; import App from './App'; // to Configure import Enzyme, {shallow} from 'enzyme' // adaptor to expect code import EnzymeAdapter from 'enzyme-adapter-react-16.1' //configure new instance of adaptor Enzyme.configure({adapter: new EnzymeAdapter()}) // example of Jest Test // Tests // test('renders learn react link', () => { // render(<App />); // const linkElement = screen.getByText(/learn react/i); // // expect assertions // expect(linkElement).toBeInTheDocument(); // }); //Enzyme creates a virtual dom // shallow rendering only renders parent level component but not react children components / places placeholders // mount will render Parent and all children components test('renders without crashing', () => { // render app fails if it can't load const wrapper = shallow(< App/>) //console.log(wrapper.debug()) const header = wrapper.find('[data-test="app-header-text"]') // expect api throws error if test faild expect (header).toBeTruthy(); // expect(header.length).toBe(1) })
import React from 'react'; import PropTypes from 'prop-types'; import { Switch, Route, withRouter } from 'react-router-dom'; import { Redirect } from 'react-router'; import { connect } from 'react-redux'; import Home from '../../views/home'; import NotFound from '../../views/not-found'; function PrivateRoute({ component: Component, authenticated, ...rest }) { return ( <Route {...rest} render={(props) => authenticated === true ? <Component {...props} /> : <Redirect to={{ pathname: '/login', state: { from: props.location } }} />} /> ); } const Rooting = (props) => { return ( <Switch> <Route exact path="/" component={Home} /> <Route component={NotFound} /> </Switch> ); }; Rooting.propTypes = { loggedIn: PropTypes.bool }; PrivateRoute.propTypes = { authenticated: PropTypes.bool, component: PropTypes.func, location: PropTypes.object }; function mapStateToProps() { return { loggedIn: sessionStorage.getItem('loggedInUser') != null }; } export default withRouter(connect( mapStateToProps, null )(Rooting));
import React from 'react'; import { useState } from 'react'; import './style.css'; import mapImage from './img/map.svg'; import CityOptions from './CityOptions/index'; import DatesOptions from './DatesOptions/index'; import { useEffect } from 'react'; const JourneyPicker = ({ onJourneyChange }) => { const [fromCity, setFromCity] = useState(''); const [toCity, setToCity] = useState(''); const [date, setDate] = useState(''); const [cities, setCities] = useState([]); const [dates, setDates] = useState([]); const [journey, setJourney] = useState([]); useEffect(() => { fetch('https://leviexpress-backend.herokuapp.com/api/cities') .then((resp) => resp.json()) .then((json) => setCities(json.data)); }, []); useEffect(() => { fetch('https://leviexpress-backend.herokuapp.com/api/dates') .then((resp) => resp.json()) .then((json) => setDates(json.data)); }, []); useEffect(() => { fetch( `https://leviexpress-backend.herokuapp.com/api/journey?fromCity=${fromCity}&toCity=${toCity}&date=${date}`, ) .then((resp) => resp.json()) .then((json) => setJourney(json.data.journeyId)); }, [fromCity, toCity, date]); const handleSubmit = (event) => { event.preventDefault(); console.log(fromCity, toCity, date); console.log(`Nalezeno spojení s id: ${journey}`); onJourneyChange(journey); }; const handleSelect = (e) => { setFromCity(e.target.value); }; const handleSelect2 = (e) => { setToCity(e.target.value); }; const handleSelect3 = (e) => { setDate(e.target.value); console.log(e.target.value); }; return ( <> <div className="journey-picker container"> <h2 className="journey-picker__head">Kam chcete jet?</h2> <div className="journey-picker__body"> <form className="journey-picker__form"> <label> <div className="journey-picker__label">Odkud:</div> <select value={fromCity} onChange={handleSelect}> <option></option> <CityOptions cities={cities} /> </select> </label> <label> <div className="journey-picker__label">Kam:</div> <select value={toCity} onChange={handleSelect2}> <option></option> <CityOptions cities={cities} /> </select> </label> <label> <div className="journey-picker__label">Datum:</div> <select value={dates.dateBasic} onChange={handleSelect3}> <option></option> <DatesOptions dates={dates} /> </select> </label> <div className="journey-picker__controls"> <button className="btn" type="submit" onClick={handleSubmit} disabled={ true ? fromCity === '' || toCity === '' || date === '' : false } > Vyhledat spoj </button> </div> </form> <img className="journey-picker__map" src={mapImage} /> </div> </div> <div className="journey-detail container"> <h2>Podrobnosti cesty</h2> <div className="stops"> <div className="bus-stop"> <div className="bus-stop__bullet"></div> <div className="bus-stop__place"> <div className="bus-stop__city">Město 1</div> <div className="bus-stop__station">Zastávka</div> </div> <div className="bus-stop__departure">10:45</div> </div> <div className="bus-stop"> <div className="bus-stop__bullet"></div> <div className="bus-stop__place"> <div className="bus-stop__city">Město 2</div> <div className="bus-stop__station">Zastávka</div> </div> <div className="bus-stop__departure">10:45</div> </div> <div className="bus-stop"> <div className="bus-stop__bullet"></div> <div className="bus-stop__place"> <div className="bus-stop__city">Město 3</div> <div className="bus-stop__station">Zastávka</div> </div> <div className="bus-stop__departure">10:45</div> </div> <div className="bus-stop"> <div className="bus-stop__bullet"></div> <div className="bus-stop__place"> <div className="bus-stop__city">Město 4</div> <div className="bus-stop__station">Zastávka</div> </div> <div className="bus-stop__departure">10:45</div> </div> </div> </div> </> ); }; export default JourneyPicker; // const CityOptions = { // mestoZ: ['Město1', 'Mesto2', 'Mesto3', 'Mesto4'], // mestoDo: ['Město1', 'Mesto2', 'Mesto3', 'Mesto4'], // datum: ['20.05.2021', '21.05.2021', '22.05.2021', '23.05.2021'], // }; // <option value={CityOptions.mestoZ[0]}>Město 1</option> // <option value={CityOptions.mestoZ[1]}>Město 2</option> // <option value={CityOptions.mestoZ[2]}>Město 3</option> // <option value={CityOptions.mestoZ[3]}>Město 4</option>
import fs from "fs"; import path from "path"; import matter from "gray-matter"; import { getAllFilesRecursively } from "../lib/files"; import { markdownToHtml } from "./markdownToHtml"; const root = process.cwd(); const postDirectoryName = `posts`; /** 日付の降順でソート */ function dateSortDesc(date1, date2) { if (date1 > date2) return -1; if (date1 < date2) return 1; return 0; } /** ファイルパスをWindows環境でも読み込める形式へ整形 */ function filePathConvertForWindows(prefixPaths, file) { return file.slice(prefixPaths.length + 1).replace(/\\/g, "/"); } /** フロントマターから必要なデータのみ抽出 */ function convertFrontMatter(frontMatter) { const result = { slug: frontMatter.slug, date: frontMatter.date ? new Date(frontMatter.date).toISOString() : null, title: frontMatter.title ?? "", description: frontMatter.description ?? "", author: frontMatter.author ?? "", coverImage: frontMatter.image ?? "", category: frontMatter.category ?? "", tags: frontMatter.tags ?? [], }; return result; } /** 全てのフロントマター(YAMLで記載した文書情報)を取得 */ export function getAllPostsFrontMatter() { const prefixPaths = path.join(root, postDirectoryName); const files = getAllFilesRecursively(prefixPaths); const allFrontMatter = []; files.forEach((file) => { // ファイル名を整形 const fileName = filePathConvertForWindows(prefixPaths, file); // mdファイル以外を除外 if (path.extname(fileName) !== ".md") return; // フロントマターを取得 const source = fs.readFileSync(file, "utf8"); const { data } = matter(source); const frontMatter = data; // 下書きを除外 if (frontMatter.draft) return; allFrontMatter.push(convertFrontMatter(frontMatter)); }); const sortedData = allFrontMatter.sort((post1, post2) => dateSortDesc(post1.date, post2.date) ); return sortedData; } /** slugから投稿を取得 */ export async function getPostBySlug(slug) { const prefixPaths = path.join(root, postDirectoryName); const files = getAllFilesRecursively(prefixPaths); // slugの一致するデータを取得 const postData = files .map((file) => { const source = fs.readFileSync(file, "utf8"); const frontMatter = matter(source); return frontMatter; }) .filter((fm) => fm.data.slug === slug)[0]; // 本文をHTML変換 const contentHtml = await markdownToHtml(postData.content); // 指定したデータ群をpropsとして返却 const { data } = postData; return { ...convertFrontMatter(data), contentHtml: contentHtml, }; } /** categoryから記事を取得(本文なし) */ export function getCategoryPosts(category, posts) { const allPosts = posts ? posts : getAllPostsFrontMatter(); const filteredPosts = allPosts .filter((p) => p.category) .filter((p) => p.category.toLowerCase() == category.toLowerCase()); return filteredPosts; } /** tagから記事を取得(本文なし) */ export function getTagPosts(tag, posts) { const allPosts = posts ? posts : getAllPostsFrontMatter(); const filteredPosts = allPosts .filter((p) => p.tags && p.tags.length > 0) .filter((p) => p.tags.map((t) => t.toLowerCase()).includes(tag.toLowerCase()) ); return filteredPosts; }
import {useState} from 'react'; import axios from 'axios'; import Button from './button-default'; import theme from './theme'; export default function Contact() { const [values, setValues] = useState({ email: "", firstName: "", lastName: "", message: "" }); const [loadStatus, setLoadStatus] = useState("uninit"); const handleChange = (e) => { e.preventDefault(); setValues({ ...values, [e.target.name]: e.target.value }) } const handleSubmit = () => { setLoadStatus("init"); axios.post('https://ueg-price-tool.herokuapp.com/contact', values) .then(res => { if (res.status == 200) { setLoadStatus("done") } else { setLoadStatus("error") } }) .catch(err => { setLoadStatus("error") }) } const {email, firstName, lastName, message} = values; return ( <div className="contact"> <div className="container"> <h1 className="default-heading">How can we help?</h1> <p className="default-text">Our dedicated team is ready to respond. Please reach out with any questions or service inquiries .</p> <div> <form target="" className="validate" name="contact-form" onSubmit={handleSubmit} id="contact-form"> <div className="inputs-container default-text"> <div className="input-wrpr"> <label htmlFor="email">Email Address <span className="asterisk">*</span></label> <input value={email} onChange={handleChange} type="email" name="email" className="contact-input input-normal required email" id="email" required/> </div> <div className="input-wrpr"> <label htmlFor="first_name">First Name </label> <input value={firstName} onChange={handleChange} type="text" name="firstName" className="contact-input input-normal" id="first_name" required/> </div> <div className="input-wrpr"> <label htmlFor="last_name">Last Name </label> <input value={lastName} onChange={handleChange} type="text" name="lastName" className="contact-input input-normal" id="last_name" required/> </div> <div className="input-wrpr"> <label htmlFor="message">Message </label> <textarea value={message} onChange={handleChange} form="contact-form" rows="5" cols="33" name="message" className="contact-input input-normal" id="message"/> </div> <div className="submit-container"> { loadStatus === 'uninit' ? <Button onClick={handleSubmit} text="Submit" className="submit-btn"></Button> : loadStatus === 'init' ? <span className="lds-dual-ring"></span> : loadStatus === 'done' ? <span>Thank you! We will reach out within 24 hours.</span> : <span>There was an error with the contact submission. Please try again later.</span> } </div> </div> </form> </div> <div className="contact-info"> <span> contact@uniesportsgroup.com </span> </div> </div> <style jsx>{` .default-heading { margin-bottom; } .container > .default-text { margin-bottom: 40px; display: inline-block; } .inputs-container { display: flex; flex-direction: column; } .input-wrpr { display: flex; align-self: center; justify-content: space-between; margin-bottom: 30px; } .contact-input { width: 35vw; height: 35px; padding: 5px 8px; color: grey; font-family: inherit; font-size: inherit; border: none; box-shadow: inset 1px 0px 2px 1px #00000047; } textarea.contact-input { height: 200px; } .input-wrpr > label { width: 160px; margin-right: 100px; text-align: left; align-self: center } .submit-container { align-self: center; } :global(.submit-container > .button-default) { color: ${theme.colors["med-blue"]}; } .contact-info { width: fit-content; margin: 100px auto 20px auto; } /* loading spinner */ .lds-dual-ring { display: inline-block; width: 64px; height: 64px; } .lds-dual-ring:after { content: " "; display: block; width: 46px; height: 46px; margin: 1px; border-radius: 50%; border: 5px solid #066b98; border-color: #066b98 transparent #066b98 transparent; animation: lds-dual-ring 1.2s linear infinite; } @keyframes lds-dual-ring { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } @media (max-width: 600px) { .input-wrpr { flex-direction: column; width: 100%; } .input-wrpr > label { align-self: start; margin-bottom: 10px; } .contact-input { width: 100%; align-self: start; } } `}</style> </div> ) }
const EventEmitter = require('events'); exports.Db = class Db extends EventEmitter { constructor() { super(); this.logs = new Map(); this.init(); } init() { this.on('data', function (data) { this.logs.set(new Date().toISOString(), data); console.log('this.logs', this.logs); }); } }
use test; db.players.insertMany([{ _id: 123, userName: "petesampras", country: "US", titles: 64 }, { _id: 124, userName: "bjornborg", country: "SE", titles: 63 } ]); db.players.aggregate([ { $match: { country: "SE" } }, { $group: { _id: "$country", count: { $sum: "$titles" } } } ]); sh.updateZoneKeyRange("myDb.players", { country: "SE", userName: MinKey }, { country: "SE", userName: MaxKey }, "EUR") sh.addShardToZone("shardA", "EUR") // See http://blog.rueckstiess.com/mtools/mlaunch.html // mlaunch --replicaset --sharded shardA shardB shardC use crm; sh.splitAt("crm.contacts", {country: "US", acct: "a"}); sh.splitAt("crm.contacts", {country: "US", acct: "l"}); sh.splitAt("crm.contacts", {country: "US", acct: "r"}); sh.splitAt("crm.contacts", {country: "US", acct: "zzzzzzzzz"}); sh.moveChunk("crm.contacts", {country: "US", acct: "abc"}, "shardA") sh.moveChunk("crm.contacts", {country: "US", acct: "man"}, "shardB") sh.moveChunk("crm.contacts", {country: "US", acct: "sta"}, "shardC")
/* From: https://github.com/Cortexelus/Polyphonic-Binaural-Beats */ function BiBeat() { let oscillators = []; function start(){ oscillators.forEach(o=>o.start()); } function stop(){ oscillators.forEach(o=>o.stop()); } function init(){ let ctx = new (window.AudioContext || window.webkitAudioContext)(); let b = 4 // beat in Hz let intervals = [1, 2, 3]; // integer multiples of the fundamental let f = 500 // fundamental frequency // Pan let panNodes = [ctx.createStereoPanner(), ctx.createStereoPanner()] panNodes[0].pan.value = -1; panNodes[1].pan.value = 1; panNodes[0].connect(ctx.destination); panNodes[1].connect(ctx.destination); // Oscillators for( let i=0; i<intervals.length*2; i++ ) { let pan = i%2; let o = ctx.createOscillator(); o.type = 'sine'; let interval = intervals[Math.floor(i/2)]; if( pan ){ o.frequency.value = (f + b) * interval; }else { o.frequency.value = (f + 0) * interval; } //o.start(); o.connect(panNodes[pan]); oscillators.push(o); } } // Set the beat in Hz, the new fundamental frequency, // and the new intervals (integer multiples) function set( newb, newf, newintervals, vol ) { b = newb intervals = newintervals //bottom_freq = new_bottom_freq //smallest_interval = Math.min.apply(null, newintervals); //f = bottom_freq / smallest_interval f = newf console.log("Fundamental", f, "hz") console.log("Beat", b, "hz") //oscilators= // [osc0left, osc0right, osc1l, osc1r, osc2l, osc2r ...] // intervals = // [ 1, 2, 3 ... ] for( let i=0; i< oscillators.length; i++ ) { let pan = i%2; let interval = intervals[ Math.floor( i/2 ) ]; let harmonic = vol; o = oscillators[i]; if(pan){ o.frequency.value = (f + b) * interval * harmonic }else{ o.frequency.value = (f + 0) * interval } console.log(i, o.frequency.value) } } return { init:init, set:set, start:start, stop:stop } }; // A beat of 4Hz // with 200Hz fundamental // with intervals of 2, 3, 4 // This plays in one ear: 400hz, 600hz, 800hz // And the other ear: 408hz, 612hz, 816hz //set(4, 200, [2, 3, 4])
window.onload = function () { // Vueとinspectorの相性が悪いみたい // Vueと何らかの要素がリンクしているとinspectorでの視点移動ができなくなる // さらに恐らくVueとリンクすると謎の要素が追加されているみたい const app = new Vue({ // el: '#scene', data: { cameraPosition: '', grip: false, selectedEl: null, }, created() { const vue = this; // これ用途によって作って色々できそう // ここからvueに値投げたりできるし AFRAME.registerComponent('input-listener', { dependencies: ['raycaster'], init() { const listener = this; this.el.addEventListener('triggerdown', function (e) { // vue.cannonBall(listener.el); //コントローラの位置を取得(thisはコントローラ) var point = this.object3D.getWorldPosition(); //ボールを生成 var ball = document.createElement('a-sphere'); ball.setAttribute('class', 'ball'); ball.setAttribute('scale', '0.2 0.2 0.2'); ball.setAttribute('position', point); //dynamic-bodyを設定することで物理演算をさせる ball.setAttribute('dynamic-body', 'shape: sphere; sphereRadius:0.2; '); //コントローラのレイキャスターの向きを取得 var dir = this.getAttribute("raycaster").direction; //球を発射するときの向きと大きさを設定(好みに応じて変更) var force = new THREE.Vector3(dir.x, dir.y, dir.z); force.multiplyScalar(2000); //レイキャスターの向きはコントローラを原点としたローカル座標系なのでワールド座標に変換 ball.force = this.object3D.localToWorld(force); //上記の設定を済ませた球をシーンに登場させる var scene = document.querySelector('a-scene'); scene.appendChild(ball); //物理関係の設定が済んだタイミングで球を飛ばす ball.addEventListener('body-loaded', function (e) { //ボールの位置を取得(ここでのthisはballを示す) var p = this.object3D.position; //加える力は先ほど計算したものを使用 var f = this.force; //球に力を加えて飛ばす this.body.applyForce( new CANNON.Vec3(f.x, f.y, f.z), new CANNON.Vec3(p.x, p.y, p.z) ); }); }); document.addEventListener('mousedown',() => { // 玉を投げる // vue.cannonBall(listener.el); // テレポートする // listener.el.emit('teleportstart'); // 物をつかむ // vue.grip = true; }); document.addEventListener('mouseup',() => { // テレポートする // listener.el.emit('teleportend'); // 物をつかむ // vue.grip = false; }); // this.el.addEventListener('raycaster-intersection',evt => { // }); // this.el.addEventListener('raycaster-intersection-cleared',evt => { // }); }, tick(time,timeDelta) { // const camera = document.querySelector("#camera"); // let p = camera.object3D.getWorldPosition(new THREE.Vector3); // const rate = 100; // p.x = Math.round(p.x * rate) / rate; // p.y = Math.round(p.y * rate) / rate; // p.z = Math.round(p.z * rate) / rate; // vue.cameraPosition = `x:${p.x} y:${p.y} z:${p.z}`; // 単位はms // console.log(time / 1000,timeDelta); } }); AFRAME.registerComponent('get-listener', { init() { this.el.addEventListener('raycaster-intersected', evt => { this.raycaster = evt.detail.el; }); this.el.addEventListener('raycaster-intersected-cleared', evt => { this.raycaster = null; }); }, tick() { if (!vue.grip) return; if (!this.raycaster) return; // 掴むというよりは押すような動作になってしまったやつ // let ray = new THREE.Vector3(); // this.raycaster.object3D.getWorldDirection(ray).negate(); // let p = new THREE.Vector3(ray.x, ray.y, ray.z); // p.normalize(); // p.multiplyScalar(0.5); // this.el.object3D.localToWorld(p); // this.el.object3D.position.set(p.x, p.y, p.z); // 掴む処理 掴む元の座標に掴む元の方向を足す let ray = new THREE.Vector3(); this.raycaster.object3D.getWorldDirection(ray); ray.normalize(); ray.multiplyScalar(1.3); ray.negate(); let p = this.raycaster.object3D.getWorldPosition(new THREE.Vector3); let pos = new THREE.Vector3(); pos.addVectors(p,ray); this.el.object3D.position.set(pos.x, pos.y, pos.z); } }); }, mounted() { }, methods: { cannonBall(raycaster) { const scene = document.querySelector('a-scene'); const position = raycaster.object3D.getWorldPosition(new THREE.Vector3); // // カメラ方向の取得 // let rocation = new THREE.Vector3; // getWorldDirectionの引数に入れると代入してくれる // raycaster.object3D.getWorldDirection(rocation).negate(); // 射出するボールの設定 let ball = document.createElement('a-sphere'); ball.setAttribute('class', 'ball'); ball.setAttribute('scale', '0.2 0.2 0.2'); ball.setAttribute('position', position); ball.setAttribute('color', '#000'); // dynamic-bodyを設定することで物理演算をさせる ball.setAttribute('dynamic-body', 'shape: sphere; sphereRadius:0.2; '); // 球を発射するときの向きと大きさを設定(好みに応じて変更) let dir = this.getAttribute("raycaster").direction; let force = new THREE.Vector3(dir.x,dir.y,dir.z); force.multiplyScalar(3000); // 代入 ball.force = this.object3D.localToWorld(force); // 上記の設定を済ませた球をシーンに登場させる scene.appendChild(ball); // 物理関係の設定が済んだタイミングで球を飛ばす ball.addEventListener('body-loaded', function (e) { // ボールの位置を取得(ここでのthisはballを示す) let p = this.object3D.position; // 加える力は先ほど計算したものを使用 let f = this.force; // 球に力を加えて飛ばす this.body.applyForce( new CANNON.Vec3(f.x, f.y, f.z), new CANNON.Vec3(p.x, p.y, p.z) ); }); } } }); };
/// <reference path="ContentsWindowHead.ts" /> var Contents; (function (Contents) { var ContentsWindow = /** @class */ (function () { function ContentsWindow(Obj, Parent, FinishFunction) { if (FinishFunction === void 0) { FinishFunction = function () { }; } this.Obj = Obj; this.Parent = Parent; this.FinishFunction = FinishFunction; this.ButtonClass = ['menu-toc']; this.ShowState = false; this.SetObjectList(); this.Parent.WindowsCarry.RegisterWindow(this); } ContentsWindow.prototype.ButtonHandler = function () { if (!this.ShowState) { this.ShowWindow(); } else { this.HideWindow(); } }; ContentsWindow.prototype.SetObjectList = function () { this.ObjList = this.Obj.querySelector('#toc-wrap ul'); }; ContentsWindow.prototype.MakeContent = function () { this.PrepareData(); this.ObjList.innerHTML = this.ParseWindowData(); this.SetHandlers(); }; ContentsWindow.prototype.MakeTOCTree = function (TOC, deep) { if (deep === void 0) { deep = 1; } var out = ''; for (var j = 0; j < TOC.length; j++) { var row = TOC[j], current = '', el = 'a', href = '', icons = '', bookmarkCount = 0; if (row.bookmarks) { if (row.bookmarks.g0) { current = ' current'; el = 'a class="current"'; } icons += '<span class="toc-icons">'; if (row.bookmarks.g3) { bookmarkCount += row.bookmarks.g3 * 1; } if (row.bookmarks.g5) { bookmarkCount += row.bookmarks.g5 * 1; } if (bookmarkCount) { icons += '<span class="icon-type icon-type-3"></span>' + '<span class="icon-text">' + bookmarkCount + '</span>'; } if (row.bookmarks.g1) { icons += '<span class="icon-type icon-type-1"></span>' + '<span class="icon-text">' + row.bookmarks.g1 + '</span>'; } icons += '</span>'; } var title, innerLi, hasTcl; if (row.t) { hasTcl = row.tcl || this.hasAllTcl(row); title = this.Parent.PrepareTitle(row.t); innerLi = hasTcl ? title : "<" + el + href + ">" + title + icons + "</" + el + ">"; out += "<li class=\"deep" + deep + current + "\" data-e=\"" + row.s + "\" " + (hasTcl ? 'data-tcl="true"' : '') + ">" + innerLi + "</li>\r\n"; } if (row.c) { for (var i = 0; i < row.c.length; i++) { out += this.MakeTOCTree([row.c[i]], deep + 1); } } } return out; }; ContentsWindow.prototype.hasAllTcl = function (row) { var childs = row.c; if (!childs) { return false; } var i = 0, len = childs.length; while (i < len) { if (!childs[i].tcl) { return false; } i++; } return true; }; ContentsWindow.prototype.ParseWindowData = function () { var html = this.MakeTOCTree(this.WindowData); return html; }; ContentsWindow.prototype.ShowWindow = function () { this.ShowState = true; this.MakeContent(); this.Parent.Mask.Show(); this.ToggleWindow('block'); if (!this.Parent.PDA.state) { this.Scroll = new scrollbar(this.Obj.querySelector('.scrollbar'), {}); } else { addClass(this.Obj, 'scroll_enabled'); } }; ContentsWindow.prototype.HideWindow = function () { this.Parent.Mask.Hide(); this.ToggleWindow('none'); this.ShowState = false; }; ContentsWindow.prototype.ToggleWindow = function (state) { this.Obj.style.display = state; }; ContentsWindow.prototype.PrepareData = function () { this.WindowData = this.Parent.Reader.TOC(); }; ContentsWindow.prototype.SetHandlers = function () { var _this = this; var buttons = this.Obj.querySelectorAll('li'), button; for (var j = 0; j < buttons.length; j++) { button = buttons[j]; if (!button.hasAttribute('data-tcl')) { button.addEventListener('click', function (e) { return _this.GoToTOCEntry(e); }, false); continue; } button.addEventListener('click', function (e) { return _this.FinishFunction(e); }, false); } }; ContentsWindow.prototype.GoToTOCEntry = function (e) { var e = this.Parent.GetEvent(e); var target = (e.target || e.srcElement); target = this.Parent.GetElement(target, 'li'); var Reader = this.Parent.Reader, AuthorizeIFrame = Reader.Site.AuthorizeIFrame, TOC = Reader.FB3DOM.TOC, Percent = Number(target.getAttribute('data-e')) / TOC[TOC.length - 1].e * 100; this.Parent.WindowsCarry.HideAllWindows(); if (this.Parent.Reader.Site.IsAuthorizeMode()) { if (AuthorizeIFrame.Hidden) { AuthorizeIFrame.SetPercent(Percent); AuthorizeIFrame.Show(); } } else { LitresHistory.push(this.Parent.Bookmarks.Bookmarks[0].Range.From.slice(0)); this.Parent.Reader.GoTO([parseInt(target.getAttribute('data-e'))]); } }; return ContentsWindow; }()); Contents.ContentsWindow = ContentsWindow; })(Contents || (Contents = {}));
import React from 'react'; import './searchFormAdditional.scss'; const SearchForm = () => <div className="ge-search-form__additional">sfsdfdsf </div>; export default SearchForm;
/** * Created by Indexyz on 2016/7/14. */ 'use strict'; const event = require("./Event"); module.exports = function (task, timeOut) { let streams = 0; let total = 0; let getData = 0; return function (res, url, cb) { let tTask = task; let timeout_wrapper = function (res) { return function () { res.end(); event.emit('taskTimeout', tTask) }; }; let fn = timeout_wrapper(res); let timeoutId = setTimeout(fn, timeOut); if (!res.headers['content-length']) { cb(); return; } streams++; total += parseInt(res.headers['content-length'], 10); res.on('data', function (data) { //noinspection JSUnresolvedFunction getData += data.length; event.emit("progressChange", tTask, getData / total); // Reload time out clearTimeout(timeoutId); timeoutId = setTimeout(fn, timeOut) }); res.on('end', function () { if (getData / total == 1) { console.log(task); clearTimeout(timeoutId); event.emit("taskFinish", task) } }) }; };
/* A organização de um código em Java Script é dividido em: * Sentença de código (Uma linha de comando) => console.log("Olá Mundo") * Blocos (Um grupo de sentenças) => { } */ { console.log("Olá") console.log("Mundo!") }
//等待页面加载完成(所有资源) window.addEventListener('DOMContentLoaded',function () { //获取dom元素 var liNodes = document.querySelectorAll('.nav li'); var arrowNode = document.querySelector('.arrow'); var upNodes = document.querySelectorAll('.up'); var contentUlNode = document.querySelector('.content-main'); var contentLiNodes = document.querySelectorAll('.content-main li'); var navBarLiNode = document.querySelectorAll('.nav-bar li'); var musicIcon = document.querySelector('.header-main .musicIcon'); var homeNode = document.querySelector('.home'); var plane1 = document.querySelector('.plane1'); var plane2 = document.querySelector('.plane2'); var plane3 = document.querySelector('.plane3'); var pencel1 = document.querySelector('.works .pencel1'); var pencel2 = document.querySelector('.works .pencel2'); var pencel3 = document.querySelector('.works .pencel3'); var aboutPhoto =document.querySelectorAll('.about-photo'); var teamTitle = document.querySelector('.team-title'); var teamContent = document.querySelector('.team-content'); var bootAnimationLine = document.querySelector('.boot-animation .line'); var bootAnimationTop = document.querySelector('.boot-animation .top'); var bootAnimationBottom = document.querySelector('.boot-animation .bottom'); var bootAnimation = document.querySelector('.boot-animation'); var count = 0; var timer = null; //第一屏js代码 headerHandle(); function headerHandle() { //初始化时小箭头来到第一个Li的位置 arrowNode.style.left = liNodes[0].getBoundingClientRect().left + liNodes[0].offsetWidth/2 - arrowNode.offsetWidth/2 +'px'; //第一个li显示 upNodes[0].style.width = '100%'; for (var i = 0; i < liNodes.length; i++) { liNodes[i].index = i; liNodes[i].onclick = function () { //默认清空所有width为0 for (var j = 0; j < upNodes.length; j++) { upNodes[j].style.width = ''; } //其他li切换 为100% --找到准确下标 upNodes[this.index].style.width = '100%'; //小箭头去当前指定的li下面 arrowNode.style.left = this.getBoundingClientRect().left + this.offsetWidth/2 - arrowNode.offsetWidth/2 +'px'; contentUlNode.style.top = -this.index* contentLiNodes[0].offsetHeight +'px'; } } } //轮播图 carousel(); function carousel() { var carouselLiNode = document.querySelectorAll('.carousel li'); var pointLiNode = document.querySelectorAll('.point li'); var lastIndex = 0; var nowIndex = 0; for (var i = 0; i < pointLiNode.length; i++) { pointLiNode[i].index = i; //函数节流:规定时间内,只让第一次操作生效,后面不生效 var lastTime = 0; pointLiNode[i].onclick = function () { var nowTime = Date.now(); //得到当前的格林时间 单位:毫秒 //如果点击的时间间隔小于2秒,不生效 if(nowTime - lastTime <= 2000) return; //同步上一次的点击时间 lastTime = nowTime; //nowIndex=lastIndex时 nowIndex = this.index; if(nowIndex ==lastIndex)return; if(nowIndex > lastIndex){ //如果nowIndex>lastIndex时,右边显示左边隐藏 carouselLiNode[nowIndex].className = 'common right-show'; carouselLiNode[lastIndex].className = 'common left-hide'; } else { //如果nowIndex<lastIndex时,左边显示右边隐藏 carouselLiNode[nowIndex].className = 'common left-show'; carouselLiNode[lastIndex].className = 'common right-hide'; } //小圆点切换 pointLiNode[nowIndex].className = 'active'; pointLiNode[lastIndex].className = ''; lastIndex = nowIndex; } } //自动轮播 var timers = null; timers = setInterval(function () { nowIndex++; //同步上一次点击时间,为了在轮播时用户不能点击小圆点 ,用户过2后再点轮播图 lastTime = Date.now(); if(nowIndex >= 4) nowIndex = 0; //如果nowIndex>lastIndex时,右边显示左边隐藏 carouselLiNode[nowIndex].className = 'common right-show'; carouselLiNode[lastIndex].className = 'common left-hide'; //小圆点切换 pointLiNode[nowIndex].className = 'active'; pointLiNode[lastIndex].className = ''; lastIndex = nowIndex; },3000) } //滚轮事件 document.onmousewheel = wheel; document.addEventListener('DOMMouseScroll',wheel); function wheel(event) { //关闭定时器 clearTimeout(timer); timer=setTimeout(function () { var flag = ''; if (event.wheelDelta) { //ie/chrome if (event.wheelDelta > 0) { flag = 'up'; } else { flag = 'down' } } else if (event.detail) { //firefox if (event.detail < 0) { flag = 'up'; } else { flag = 'down' } } switch (flag) { case 'up' : console.log(111) if(count >0){ count--; contentUlNode.style.top = -count* contentLiNodes[0].offsetHeight +'px'; arrowNode.style.left = liNodes[count].getBoundingClientRect().left + liNodes[count].offsetWidth/2 - arrowNode.offsetWidth/2 +'px'; for (var j = 0; j < upNodes.length; j++) { upNodes[j].style.width = ''; } //其他li切换 为100% --找到准确下标 upNodes[count].style.width = '100%'; } break; case 'down' : // console.log(111) if(count <4){ count++; contentUlNode.style.top = -count* contentLiNodes[0].offsetHeight +'px'; arrowNode.style.left = liNodes[count].getBoundingClientRect().left + liNodes[count].offsetWidth/2 - arrowNode.offsetWidth/2 +'px'; for (var j = 0; j < upNodes.length; j++) { upNodes[j].style.width = ''; } //其他li切换 为100% --找到准确下标 upNodes[count].style.width = '100%'; } break; } },200) event = event || window.event; //禁止默认行为 event.preventDefault && event.preventDefault(); return false; } //同步窗口 window.onresize = function () { arrowNode.style.left = liNodes[count].getBoundingClientRect().left + liNodes[count].offsetWidth/2 - arrowNode.offsetWidth/2 +'px'; } //第五屏js代码 lastHandle(); function lastHandle() { //获取dom元素 var teamUlNode = document.querySelector('.team-person'); var teamLiNode = document.querySelectorAll('.team-person li'); var width = teamLiNode[0].offsetWidth; var height = teamLiNode[0].offsetHeight; var canvas = null; var creatCircleTimer = null; var paintingTimer = null; for (var i = 0; i < teamLiNode.length; i++) { teamLiNode[i].index = i; teamLiNode[i].onmouseenter = function () { //改变透明度 for (var j = 0; j < teamLiNode.length; j++) { teamLiNode[j].style.opacity = 0.5; } this.style.opacity = 1; if(!canvas){ //创建画布 canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; canvas.className = 'canvas'; //产生气泡 buble(canvas); teamUlNode.appendChild(canvas); } //不管添加不添加canvas,left值都得改变 canvas.style.left = this.index * width +'px'; } } teamUlNode.onmouseleave = function () { for (var i = 0; i < teamLiNode.length; i++) { teamLiNode[i].style.opacity = 1; } //清除画布 canvas.remove(); canvas = null; //清除定时器,防止多次点击网页卡 clearInterval(creatCircleTimer); clearInterval(paintingTimer); } //封装气泡运动函数 function buble(myCanvas) { var circleArr = []; if(myCanvas.getContext){ var ctx = myCanvas.getContext('2d'); //画圆 creatCircleTimer= setInterval(function () { //清除画布;把之前画的清除掉 ctx.clearRect(0,0,myCanvas.width,myCanvas.height); for (var i = 0; i < circleArr.length; i++) { circleArr[i].deg += 8; //弧度的值 var rad = circleArr[i].deg *Math.PI/180; //计算得出小圆点运动坐标 var nowLeft = Math.floor(Math.sin(rad)*circleArr[i].s + circleArr[i].x); var nowTop = Math.floor(circleArr[i].y -rad*circleArr[i].s); ctx.fillStyle = 'rgba('+ circleArr[i].r+','+ circleArr[i].g+','+ circleArr[i].b+')'; ctx.beginPath(); ctx.arc(nowLeft,nowTop,circleArr[i].c_r,0,Math.PI*2); ctx.fill(); } },1000/60) //生成圆 paintingTimer= setInterval(function () { //颜色随机 var r = Math.floor(Math.random()*255); var g = Math.floor(Math.random()*255); var b = Math.floor(Math.random()*255); //半径随机 var c_r = Math.floor(Math.random()*8 +2); //位置随机 var x = Math.floor(Math.random()*myCanvas.width); var y = myCanvas.height + c_r; var s =Math.floor(Math.random()*30 +20); circleArr.push({ r: r, g: g, b: b, x: x, y: y, c_r: c_r, deg: 0, s: s }); },20); } } } //侧边导航 for (var i = 0; i < navBarLiNode.length; i++) { this.index = i; navBarLiNode.onclick = function () { nowIndex = this.index; //默认清空所有width为0 for (var j = 0; j < upNodes.length; j++) { upNodes[j].style.width = ''; navBarLiNode[j].className = ''; } //其他li切换 为100% --找到准确下标 upNodes[ nowIndex].style.width = '100%'; //小箭头去当前指定的li下面 arrowNode.style.left = this.getBoundingClientRect().left + this.offsetWidth/2 - arrowNode.offsetWidth/2 +'px'; contentUlNode.style.top = - nowIndex* contentLiNodes[0].offsetHeight +'px'; //侧边导航 navBarLiNode[this.index].className = 'active'; } } //音乐播放 // musicIcon.onclick = function () { // if(musicIcon.pushed){ // //当前音乐暂停,点击播放 // musicIcon.play(); // } // } //出入场动画 var animationArr = [ { anOut:function () { homeNode.style.transform = 'translateY(-200px)'; homeNode.style.opacity = 0; }, anIn:function () { homeNode.style.transform = 'translateY(0px)'; homeNode.style.opacity = 1; } }, { anOut:function () { plane1.style.transform = 'translate(-200px,-200px)'; plane2.style.transform = 'translate(-200px,200px)'; plane3.style.transform = 'translate(200px,-200px)'; }, anIn:function () { plane1.style.transform = 'translate(0)'; plane2.style.transform = 'translate(0)'; plane3.style.transform = 'translate(0)'; } }, { anOut:function () { pencel1.style.transform = 'translateY(-200px)'; pencel2.style.transform = 'translateY(200px)'; pencel3.style.transform = 'translateY(200px)'; }, anIn:function () { pencel1.style.transform = 'translate(0)'; pencel2.style.transform = 'translate(0)'; pencel3.style.transform = 'translate(0)'; } }, { anOut:function () { aboutPhoto[0].style.transform = 'rotate(30deg)'; aboutPhoto[1].style.transform = 'rotate(-30deg)'; }, anIn:function () { aboutPhoto[0].style.transform = 'rotate(0deg)'; aboutPhoto[1].style.transform = 'rotate(0deg)'; } }, { anOut:function () { teamTitle.style.transform = 'translateX(-200px)'; teamContent.style.transform = 'translateX(200px)'; }, anIn:function () { teamTitle.style.transform = 'translateX(0px)'; teamContent.style.transform = 'translateX(0px)'; } }, ] //开机动画 var imgArr = ['bg1.jpg','bg2.jpg','bg3.jpg','bg4.jpg','bg5.jpg','about1.jpg','about2.jpg','about3.jpg','about4.jpg','worksimg1.jpg','worksimg2.jpg','worksimg3.jpg','worksimg4.jpg','team.png','greenLine.png']; var num = 0; for (var i = 0; i < imgArr.length; i++) { var items = imgArr[i]; //创建img var image = new Image(); image.src = './img/'+ items; image.onload = function () { num++; bootAnimationLine.style.width = num/imgArr.length *100 + '%'; if(num === imgArr.length){ //说明图片加载完成 bootAnimationTop.style.height = 0; bootAnimationBottom.style.height = 0; bootAnimationLine.style.display = 'none'; bootAnimationTop.addEventListener('transitionend',function () { bootAnimation.remove(); }) } } } })
// requires node.js, twit, jquery and json // do this periodically setInterval(function () { 'use strict'; // set up the twitter auth var Twit = require('twit'); var T = new Twit({ consumer_key: 'VC5JsVXtVRYuW2iKSCdBdQ' , consumer_secret: 'KaopBi8BNp0V5mKzJzbW2iISR6TxSa5tIpijAnbEHc' , access_token: '2328747456-thj7As6jjoYE3XL38M012oRyvTTufHthr308Bx5' , access_token_secret: '2MSMUHZNZ5guxOZeiOoONWRK2XScO2hx7BbwCxQ51AHiI' }) // can't remember why this seemed like a good idea var env = require('jsdom').env ; //read in file env("next_tweet.txt", function (errors, window) { // if you can't read it in, throw up an error if (errors) {console.log("Error: ", errors);} // otherwise take the text out of the file (this makes more sense if you're making a markov chain, honestly) var $ = require('jquery')(window); var data = $("body").text(); // print out the text to the terminal console.log("Posting: ",data); // post it to twitter T.post('statuses/update', { status: data }, function(err, reply) { // if it goes wrong, post the error to the console! if(err) {console.log("Error:", err.message);} }) }); },10000);
var searchData= [ ['masterdata',['masterData',['../interface_c1_connector_session_response_public.html#ac607472e82ae4b44c4c1e2d321e8b555',1,'C1ConnectorSessionResponsePublic']]], ['maxcount',['maxCount',['../interface_c1_connector_track_event_response.html#aac22f087cf5463ac84ef8e60978dd879',1,'C1ConnectorTrackEventResponse::maxCount()'],['../interface_c1_connector_track_event_response_public.html#a344783988d1db6845ba60df38c5c23c6',1,'C1ConnectorTrackEventResponsePublic::maxCount()']]] ];
import Vue from 'vue' import Router from 'vue-router' import Login from '@/components/login/Login.vue' import Home from '@/components/home/Home.vue' import TestValue from '@/components/TestValue.vue' import Detail from '@/components/detail/Detail.vue' import AuthAuthentic from '@/components/auth/Authentic.vue' import AuthAuthenticOne from '@/components/auth/AuthenticOne.vue' import AuthAuthenticTwo from '@/components/auth/AuthenticTwo.vue' import AuthAuthenticThree from '@/components/auth/AuthenticThree.vue' Vue.use(Router) export default new Router({ routes: [ { path: '/', // 登录页 name: 'login', component: Login }, { path: '/home', name: 'home', component: Home }, { path: '/test', name: 'test', component: TestValue }, { path: '/detail', // 详情页 name: 'detail', component: Detail }, { path: '/authentic', name: 'authentic', redirect: '/authentic-one', component: AuthAuthentic, children: [ { path: '/authentic-one', name: 'authentic-one', component: AuthAuthenticOne }, { path: '/authentic-two', name: 'authentic-two', component: AuthAuthenticTwo }, { path: '/authentic-three', name: 'authentic-three', component: AuthAuthenticThree } ] } ] })
var React = require('react'); var connectToStores = require('alt/utils/connectToStores'); var ConfirmDeleteDialog = require('./utils/ConfirmDeleteDialog'); var Router = require('react-router'); var getDeletePurchaseOrderRow = function(PurchaseOrderActions, PurchaseOrderStore, TitleStore) { var deletePurchaseOrderRow = React.createClass({ propTypes: { titles: React.PropTypes.object, purchaseOrders: React.PropTypes.object, params: React.PropTypes.object, }, mixins: [ Router.Navigation ], statics: { getStores() { return [ PurchaseOrderStore, TitleStore ]; }, getPropsFromStores() { return { purchaseOrders: PurchaseOrderStore.getState(), titles: TitleStore.getState(), }; }, }, onHide: function() { this.goBack(); }, onConfirm: function() { var rowId = this.props.params.purchaseOrderRow; var row = this.props.purchaseOrders.purchaseOrderRows[rowId]; PurchaseOrderActions.deletePurchaseOrderRow(row); this.goBack(); }, render: function() { var rowId = this.props.params.purchaseOrderRow; var row = this.props.purchaseOrders.purchaseOrderRows[rowId] || { }; var title = this.props.titles.titles[row && row.titleId] || { }; if (row.prohibitChanges) { return null; } return ( <ConfirmDeleteDialog title="Poista tuote" onHide={ this.onHide } onConfirm={ this.onConfirm }> Haluatko varmasti poistaa tuotteen "{ row.nameOverride && 'Muu: ' + row.nameOverride || title.name } ({ row.amount } { row.unitOverride || title.unit })" tilauksestasi? </ConfirmDeleteDialog> ); }, }); return connectToStores(deletePurchaseOrderRow); }; module.exports = getDeletePurchaseOrderRow;
import React from 'react'; const StudentDetail = props => ( <div className="col s12"> <div className="card horizontal"> <div className="card-image"> <img src={props.imageUrl} /> </div> <div className="card-stacked"> <div className="card-content"> <ul> <li> <strong>Email:</strong> {props.email} </li> <li> <strong>GPA:</strong> {props.gpa} </li> </ul> </div> </div> </div> </div> ); export default StudentDetail;
var _ = require('lodash'); var React = require('react'); var ReactBootstrap = require('react-bootstrap'); var Alert = ReactBootstrap.Alert; var ErrorMessages = React.createClass({ propTypes: { messages: React.PropTypes.arrayOf(React.PropTypes.string), }, getDefaultProps: function() { return { messages: [ ], }; }, render: function() { if (this.props.messages.length === 0) { return null; } return ( <Alert bsStyle="danger"> <ul> { _.map(this.props.messages, message => <li>{ message }</li>) } </ul> </Alert> ); }, }); module.exports = ErrorMessages;
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), path: { closure: 'node_modules/obvious-closure-library/', src: 'src', tmp: 'tmp' }, gjslint: { options: { flags: [ //'--disable 220' //ignore error code 220 from gjslint '--strict', '--max_line_length=120', '--custom_jsdoc_tags=name,namespace,abstract,public,access,property' ], reporter: { name: 'console' } }, all: { src: '<%= path.src %>/**/*' } }, jshint: { options: { "smarttabs": true, "curly": true, "eqnull": true, "eqeqeq": true, "undef": true, "strict": true, "sub": true, "browser": true, "trailing": true, "unused": true, "globals": { "goog": true, "animatejs": true, "describe": true, "it": true, "expect": true, "spyOn": true, "jasmine": true, "beforeEach": true, "afterEach": true } }, all: 'src/**/*' }, clean: { tmp: ['<%= path.tmp %>/*'] }, jasmine: { options: { specs: '<%= path.src %>/**/*_spec.js' }, test: { options: { vendor: ['<%= path.closure %>/closure/goog/base.js', '<%= path.tmp %>/dependencies.js'], outfile: '<%= path.tmp %>/unittests/SpecRunner.html', junit: { path: '<%= path.tmp %>/unittests/', consolidate: true }, keepRunner: true } }, coverage: { options: { vendor: ['<%= path.closure %>/closure/goog/base.js', '<%= path.tmp %>/depscoverage.js'], template: require('grunt-template-jasmine-istanbul'), templateOptions: { coverage: '<%= path.tmp %>/coverage/coverage.json', report: [{ type: 'cobertura', options: { dir: '<%= path.tmp %>/coverage/' } }, { type: 'html', options: { dir: '<%= path.tmp %>/coverage/' } }] } } } }, instrument: { files: [ '<%= path.src %>/**/*.js', '!<%= path.src %>/**/*_spec.js', '!<%= path.src %>/**/IRequestAnimationFrame.js'], options: { basePath: '.grunt/grunt-contrib-jasmine/' } }, watch: { scripts: { files: ['<%= path.src %>/**/*.js'], tasks: ['lint', 'test'], options: { spawn: false } } }, connect: { serve: { options: { port: 8000, hostname: "*", keepalive: true } } }, closureDepsWriter: { options: { closureLibraryPath: '<%= path.closure %>', root_with_prefix: '"src ../../../../src/"' }, deps: { dest: '<%= path.tmp %>/dependencies.js' }, depsCoverage: { options: { root_with_prefix: '"src ../../../../.grunt/grunt-contrib-jasmine/src/"' }, dest: '<%= path.tmp %>/depscoverage.js' } }, closureBuilder: { options: { closureLibraryPath: '<%= path.closure %>', namespaces: 'animatejs', compilerFile: 'node_modules/closure-compiler/lib/vendor/compiler.jar', compile: true, compilerOpts: { compilation_level: 'ADVANCED_OPTIMIZATIONS', language_in: 'ECMASCRIPT5', generate_exports: true, define: ["'goog.DEBUG=false'"], warning_level: 'verbose', summary_detail_level: 3, output_wrapper: '\'(function(){%output%}).call(this);\'', extra_annotation_name: 'access', formatting: 'PRETTY_PRINT' } }, build: { src: ['src/', 'node_modules/closure-library/'], dest: 'tmp/animate.js' } }, jsdoc : { dist : { src: ['<%= path.src %>/**/*.js', '!<%= path.src %>/**/*_spec.js'], options: { destination: 'tmp/doc', template : "node_modules/grunt-jsdoc/node_modules/ink-docstrap/template", configure : "jsdoc.conf.json", private: true } } }, jsdoc2md: { oneOutputFile: { options: { index:true }, src: "src/*.js", dest: "tmp/documentation.md" } } }); grunt.registerTask('default', ['closureDepsWriter']); grunt.registerTask('lint', ['jshint', 'gjslint']); grunt.registerTask('deps', ['closureDepsWriter']); grunt.registerTask('http', ['connect:serve']); grunt.registerTask('test', ['deps', 'jasmine:test']); grunt.registerTask('coverage', ['instrument', 'closureDepsWriter:depsCoverage', 'jasmine:coverage']); grunt.registerTask('build', ['lint', 'deps', 'jasmine:test', 'closureBuilder:build']); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-gjslint'); grunt.loadNpmTasks('grunt-closure-tools'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-jasmine'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-istanbul'); grunt.loadNpmTasks('grunt-jsdoc'); grunt.loadNpmTasks('grunt-combine'); grunt.loadNpmTasks("grunt-jsdoc-to-markdown"); };
'use strict'; const expect = require('chai').expect; const protobuf = require("protobufjs"); const root = protobuf.Root.fromJSON(require("../lib/bundle.json")); const common = require('./common'); const BroadcastMessageRequest = root.lookupType("bboxapi.BroadcastMessageRequest"); const PingRequest = root.lookupType("bboxapi.PingRequest"); const StartAppRequest = root.lookupType("bboxapi.StartAppRequest"); const DeviceStateRequest = root.lookupType("bboxapi.DeviceStateRequest"); const RebootRequest = root.lookupType("bboxapi.RebootRequest"); const ShutdownRequest = root.lookupType("bboxapi.ShutdownRequest"); const ToastRequest = root.lookupType("bboxapi.ToastRequest"); const VolumeRequest = root.lookupType("bboxapi.VolumeRequest"); const VolumeUpRequest = root.lookupType("bboxapi.VolumeUpRequest"); const VolumeDownRequest = root.lookupType("bboxapi.VolumeDownRequest"); const MuteRequest = root.lookupType("bboxapi.MuteRequest"); const WakeUpRequest = root.lookupType("bboxapi.WakeUpRequest"); const HttpRequest = root.lookupType("HttpRequest"); const ListAppRequest = root.lookupType("bboxapi.ListAppRequest"); const GetVolumeRequest = root.lookupType("bboxapi.GetVolumeRequest"); const AudioType = root.lookupEnum("bboxapi.AudioType"); const HttpMethod = root.lookupEnum("bboxapi.HttpMethod"); const ToastDuration = root.lookupEnum("bboxapi.ToastDuration"); const Timing = root.lookupType("bboxapi.Timing"); const BboxApiRequest = root.lookupType("bboxapi.BboxApiRequest"); describe('Request test suite', function() { it('startAppRequest', function() { var obj = { packageName: "com.google.youtube", action: "android.intent.action.MAIN", componentName: "com.google.youtube.MainActivity", data: "content://android.media.tv/youtube/192#192", category: [ "android.intent.category.HOME" ] }; common.checkMessage(StartAppRequest, obj); }); it('pingRequest', function() { var obj = {}; common.checkMessage(PingRequest, obj); }); it('deviceStateRequest', function() { var obj = { state: 1 }; common.checkMessage(DeviceStateRequest, obj); }); it('rebootRequest', function() { var obj = {}; common.checkMessage(RebootRequest, obj); }); it('shutdownRequest', function() { var obj = {}; common.checkMessage(ShutdownRequest, obj); }); it('toastRequest', function() { var obj = { message: "this is a nice toast", color: "#FF0000", duration: ToastDuration.values.LONG_DELAY, posX: 100, posY: 500 }; common.checkMessage(ToastRequest, obj); }); it('VolumeRequest', function() { var obj = { type: AudioType.values.STREAM_SYSTEM, value: 100 }; common.checkMessage(VolumeRequest, obj); }); it('VolumeRequestBboxApi', function() { var obj = { setVolume: { type: AudioType.values.STREAM_SYSTEM, value: 100 }, timing: { serverSentAt: 1523412655 } }; common.checkMessage(BboxApiRequest, obj); }); it('VolumeUpRequest', function() { var obj = { type: AudioType.values.STREAM_SYSTEM }; common.checkMessage(VolumeUpRequest, obj); }); it('VolumeUpRequestBboxApi', function() { var obj = { volumeUp: { type: AudioType.values.STREAM_SYSTEM }, timing: { serverSentAt: 1523412655 } }; common.checkMessage(BboxApiRequest, obj); }); it('VolumeDownRequest', function() { var obj = { type: AudioType.values.STREAM_SYSTEM }; common.checkMessage(VolumeDownRequest, obj); }); it('VolumeDownRequestBboxApi', function() { var obj = { volumeDown: { type: AudioType.values.STREAM_SYSTEM }, timing: { serverSentAt: 1523412655 } }; common.checkMessage(BboxApiRequest, obj); }); it('MuteRequest', function() { var obj = { type: AudioType.values.STREAM_SYSTEM, state: true }; common.checkMessage(MuteRequest, obj); }); it('MuteRequestBboxAPi', function() { var obj = { mute: { type: AudioType.values.STREAM_SYSTEM, state: true }, timing: { serverSentAt: 1523412655 } }; common.checkMessage(BboxApiRequest, obj); }); it('WakeUpRequest', function() { var obj = {}; common.checkMessage(WakeUpRequest, obj); }); it('WakeUpRequestBboxApi', function() { var obj = { wakeUp: {}, timing: { serverSentAt: 1523412655 } }; common.checkMessage(BboxApiRequest, obj); }); it('SpideoIdRequestBboxApi', function() { var obj = { getSpideoId: {}, timing: { serverSentAt: 1523412655 } }; common.checkMessage(BboxApiRequest, obj); }); it('BroadcastMessageRequest', function() { var obj = { broadcastMessage: { action: "com.pkg.perform.Ruby", extras: { "some": "thing", "another": "thing" }, componentName: "com.pkg.AppB/com.pkg.AppB.MainActivity", flag: [ 16 ] }, timing: { serverSentAt: 1523412655 } }; common.checkMessage(BboxApiRequest, obj); }); it('HttpRequest', function() { var obj = { method: HttpMethod.values.POST, url: "/api/v1/test", headers: { "content-type": "application/json" }, body: '{"data":"test"}', auth: true }; common.checkMessage(HttpRequest, obj); }); it('HttpRequestBboxApiRouter', function() { var obj = { routerApi: { method: HttpMethod.values.POST, url: "/api/v1/test", headers: { "content-type": "application/json" }, body: '{"data":"test"}', auth: true }, timing: { serverSentAt: 1523412655 } }; common.checkMessage(BboxApiRequest, obj); }); it('HttpRequestBboxApiStb', function() { var obj = { stbApi: { method: HttpMethod.values.POST, url: "/api/v1/test", headers: { "content-type": "application/json" }, body: '{"data":"test"}', auth: true }, timing: { serverSentAt: 1523412655 } }; common.checkMessage(BboxApiRequest, obj); }); it('ListAppRequest', function() { var obj = {}; common.checkMessage(ListAppRequest, obj); }); it('ListAppRequestBboxApi', function() { var obj = { listApp: {}, timing: { serverSentAt: 1523412655 } }; common.checkMessage(BboxApiRequest, obj); }); it('GetVolumeRequest', function() { var obj = {}; common.checkMessage(GetVolumeRequest, obj); }); it('GetVolumeRequestBboxApi', function() { var obj = { getVolume: {}, timing: { serverSentAt: 1523412655 } }; common.checkMessage(BboxApiRequest, obj); }); it('BboxApiRequest', function() { common.checkMessage(BboxApiRequest, { startApp: { packageName: "com.google.youtube", action: "android.intent.action.MAIN", componentName: "com.google.youtube.MainActivity", data: "content://android.media.tv/youtube/192#192" }, timing: { serverSentAt: 1523412655 } }); common.checkMessage(BboxApiRequest, { listApp: {}, timing: { serverSentAt: 1523412655 } }); }); });
/** * @purpose :contains all methods which are require frequently in different module * @author :sangita awaghad * @since :21-08-2019 **********************************************************************************/ const readInput = require('readline-sync'); let permute = []; let count = 0; module.exports = { /** * return string containing only letters */ getString() { var format = /^[a-zA-Z]{1,}$/; var inputString = readInput.question(); if (format.test(inputString)) { return inputString; } else { throw new Error('input must contain letters only'); } }, /** * return number from keyboard */ getInputNumber() { return readInput.questionInt(); }, /** * return float number from keyboard */ getFloatInput() { return readInput.questionFloat().toFixed(2); }, /** * return boolean number from keyboard */ getBooleanInput() { return readInput.question(); }, /** * return true if year is leap year */ isLeapYear(year) { var isLeap = false; if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) { isLeap = true; } else { isLeap = false; } } else { isLeap = true; } } else { isLeap = false; } return isLeap; }, /** * return prime factors in string format */ calculatePrimeFactor(number) { var temp = number; var primefactor = ""; for (let i = 2; i * i < number; i++) { if (temp % i == 0.0) { primefactor = primefactor + i + " "; temp /= i; } } if (temp > 2) { primefactor = primefactor + temp; } return primefactor; }, /** * return associative array of win count ,loosecount,is achieve goal,is win variables */ gamblerGame(stake, goal, bets) { let betsCount = 0; let winCount = 0; let looseCount = 0; let isWin = false; let cash = stake; let isAchiveGoal = false; while (betsCount < bets) { betsCount++; if (Math.random() > 0.5) { winCount++; cash++; } else { looseCount++; cash--; } if (cash == goal) { isAchiveGoal = true; break; } } if (cash > stake) isWin = true; var result = { "looseCount": looseCount, "winCount": winCount, "isWin": isWin, "bets": betsCount, "isAchiveGoal": isAchiveGoal }; return result; }, /** * return array of distance coupon numbers */ generateCoupanNumbers(noOfCoupans) { let coupans = new Array(noOfCoupans); let count = 0; for (let j = 0; j <= noOfCoupans; j++) { let k = 0; let coupannumber = Math.ceil(Math.random() * noOfCoupans); for (let i = 0; i < j; i++) { if (coupans[i] == coupannumber) break; k++; } if (j == k) { coupans[count] = coupannumber; count++; } j = count; } return coupans; }, /** * return distance from origin(0,0) to point(x,y) */ calculateDistance(x, y) { let distance = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); return distance; }, /** *return all permutation of given string */ findPermutation(word, l, r, totalPermute) { if (l == r) { permute[count] = word; count = count + 1; if (count == totalPermute) { let i, j, k = 0; for (i = 0; i < totalPermute; i++) { for (j = 0; j < i; j++) { if (permute[j].localeCompare(permute[i]) === 0) break; } if (i == j) { permute[k] = permute[i]; k++; } } console.log(permute); return permute; } } else { for (let i = l; i <= r; i++) { word = this.swapString(word, l, i); this.findPermutation(word, l + 1, r, totalPermute); word = this.swapString(word, l, i); } } }, /** * swap alphabets at position l and i of string */ swapString(string, l, i) { let array = string.split(''); let temp = array[l]; array[l] = array[i]; array[i] = temp; string = array.join(''); return string; }, /** * return roots of quadratic equation */ findRoots(a, b, c) { let delta = b * b - 4 * a * c; let roots = []; if (delta > 0)// if delta is greater than zero then roots are real and different { root1 = Math.floor((-b + Math.sqrt(delta)) / (2 * a)); root2 = Math.floor((-b - Math.sqrt(delta)) / (2 * a)); roots = { "quote": "roots are real and different", "firstroot": root1, "secondroot": root2 }; } else if (delta < 0) // if delta is less than zero then roots are complex { let sqrt_avl = Math.sqrt(delta); roots = { "quote": "roots are complex", "firstroot": `( ${-b} + ${sqrt_avl}i)/${2 * a})`, "secondroot": `( ${-b} - ${sqrt_avl}i)/${2 * a})` }; } return roots; }, /** * display board for Tic Tac toe Game */ displayBoard(board) { console.log(`\t\t| ${board[0][0]} | ${board[0][1]} | ${board[0][2]} |`); console.log(`\t\t|---|---|---|`); console.log(`\t\t| ${board[1][0]} | ${board[1][1]} | ${board[1][2]} |`); console.log(`\t\t|---|---|---|`); console.log(`\t\t| ${board[2][0]} | ${board[2][1]} | ${board[2][2]} |`); }, /** * user enter position.program check the availability of position */ userTurn(checkPossibility) { let position; // do { console.log("Enter the Value"); position= this.getInputNumber(); switch (position) { case 1: if (checkPossibility["board"][0][0] == 'X' || checkPossibility["board"][0][0] == 'O') { this.userTurn(checkPossibility); } else { console.log("1111"); checkPossibility["board"][0][0] = 'X'; checkPossibility["countX"]["count1"]++; checkPossibility["countX"]["count4"]++; checkPossibility["countX"]["count7"]++; } break; case 2: if (checkPossibility["board"][0][1] == 'X' || checkPossibility["board"][0][1] == 'O') { this.userTurn(checkPossibility); } else { checkPossibility["board"][0][1] = 'X'; checkPossibility["countX"]["count5"]++; checkPossibility["countX"]["count1"]++; } break; case 3: if (checkPossibility["board"][0][2] == 'X' || checkPossibility["board"][0][2] == 'O') { this.userTurn(checkPossibility); } else { checkPossibility["board"][0][2] = 'X'; checkPossibility["countX"]["count1"]++; checkPossibility["countX"]["count6"]++; checkPossibility["countX"]["count8"]++; } break; case 4: if (checkPossibility["board"][1][0] == 'X' || checkPossibility["board"][1][0] == 'O') { this.userTurn(checkPossibility); } else { checkPossibility["board"][1][0] = 'X'; checkPossibility["countX"]["count2"]++; checkPossibility["countX"]["count4"]++; } break; case 5: if (checkPossibility["board"][1][1] == 'X' || checkPossibility["board"][1][1] == 'O') { this.userTurn(checkPossibility); } else { checkPossibility["board"][1][1] = 'X'; checkPossibility["countX"]["count5"]++; checkPossibility["countX"]["count2"]++; checkPossibility["countX"]["count7"]++; checkPossibility["countX"]["count8"]++; } break; case 6: if (checkPossibility["board"][1][2] == 'X' || checkPossibility["board"][1][2] == 'O') { this.userTurn(checkPossibility); } else { checkPossibility["board"][1][2] = 'X'; checkPossibility["countX"]["count6"]++; checkPossibility["countX"]["count2"]++; } break; case 7: if (checkPossibility["board"][2][0] == 'X' || checkPossibility["board"][2][0] == 'O') { this.userTurn(checkPossibility); } else { checkPossibility["board"][2][0] = 'X'; checkPossibility["countX"]["count3"]++; checkPossibility["countX"]["count4"]++; checkPossibility["countX"]["count8"]++; } break; case 8: if (checkPossibility["board"][2][1] == 'X' || checkPossibility["board"][2][1] == 'O') { this.userTurn(checkPossibility); } else { checkPossibility["board"][2][1] = 'X'; checkPossibility["countX"]["count3"]++; checkPossibility["countX"]["count5"]++; } break; case 9: if (checkPossibility["board"][2][2] == 'X' || checkPossibility["board"][2][2] == 'O') { this.userTurn(checkPossibility); } else { checkPossibility["board"][2][2] = 'X'; checkPossibility["countX"]["count6"]++; checkPossibility["countX"]["count3"]++; checkPossibility["countX"]["count7"]++; } break; } // } while (position < 1 || position > 9); return checkPossibility; }, /** * computer enter position.program check the availability of position */ computerTurn(checkPossibility) { let position; // do { console.log("Enter the Value"); position= this.checkWinPosition(checkPossibility) console.log(position); switch (position) { case 1: if (checkPossibility["board"][0][0] == 'X' || checkPossibility["board"][0][0] == 'O') { this.computerTurn(checkPossibility); } else { console.log("1111"); checkPossibility["board"][0][0] = 'O'; checkPossibility["countO"]["count1"]++; checkPossibility["countO"]["count4"]++; checkPossibility["countO"]["count7"]++; } break; case 2: if (checkPossibility["board"][0][1] == 'X' || checkPossibility["board"][0][1] == 'O') { this.computerTurn(checkPossibility); } else { checkPossibility["board"][0][1] = 'O'; checkPossibility["countO"]["count5"]++; checkPossibility["countO"]["count1"]++; } break; case 3: if (checkPossibility["board"][0][2] == 'X' || checkPossibility["board"][0][2] == 'O') { this.computerTurn(checkPossibility); } else { checkPossibility["board"][0][2] = 'O'; checkPossibility["countO"]["count1"]++; checkPossibility["countO"]["count6"]++; checkPossibility["countO"]["count8"]++; } break; case 4: if (checkPossibility["board"][1][0] == 'X' || checkPossibility["board"][1][0] == 'O') { this.computerTurn(checkPossibility); } else { checkPossibility["board"][1][0] = 'O'; checkPossibility["countO"]["count2"]++; checkPossibility["countO"]["count4"]++; } break; case 5: if (checkPossibility["board"][1][1] == 'X' || checkPossibility["board"][1][1] == 'O') { this.computerTurn(checkPossibility); } else { checkPossibility["board"][1][1] = 'O'; checkPossibility["countO"]["count5"]++; checkPossibility["countO"]["count2"]++; checkPossibility["countO"]["count7"]++; checkPossibility["countO"]["count8"]++; } break; case 6: if (checkPossibility["board"][1][2] == 'X' || checkPossibility["board"][1][2] == 'O') { this.computerTurn(checkPossibility); } else { checkPossibility["board"][1][2] = 'O'; checkPossibility["countO"]["count6"]++; checkPossibility["countO"]["count2"]++; } break; case 7: if (checkPossibility["board"][2][0] == 'X' || checkPossibility["board"][2][0] == 'O') { this.computerTurn(checkPossibility); } else { checkPossibility["board"][2][0] = 'O'; checkPossibility["countO"]["count3"]++; checkPossibility["countO"]["count4"]++; checkPossibility["countO"]["count8"]++; } break; case 8: if (checkPossibility["board"][2][1] == 'X' || checkPossibility["board"][2][1] == 'O') { this.computerTurn(checkPossibility); } else { checkPossibility["board"][2][1] = 'O'; checkPossibility["countO"]["count3"]++; checkPossibility["countO"]["count5"]++; } break; case 9: if (checkPossibility["board"][2][2] == 'X' || checkPossibility["board"][2][2] == 'O') { this.computerTurn(checkPossibility); } else { checkPossibility["board"][2][2] = 'O'; checkPossibility["countO"]["count6"]++; checkPossibility["countO"]["count3"]++; checkPossibility["countO"]["count7"]++; } break; } // } while (position < 1 || position > 9); return checkPossibility; }, /** * computer return win position if available otherwise give random number between 1 to 9 */ checkWinPosition(checkPossibility){ if(checkPossibility["countX"]["count1"]==2) { if(checkPossibility["board"][0][0]!='X') return 1; else if(checkPossibility["board"][0][1]!='X') return 2; else if(checkPossibility["board"][0][3]!='X') return 3; }else if(checkPossibility["countX"]["count2"]==2) { if(checkPossibility["board"][1][0]!='X') return 4; else if(checkPossibility["board"][1][1]!='X') return 5; else if(checkPossibility["board"][1][3]!='X') return 6; }else if(checkPossibility["countX"]["count3"]==2) { if(checkPossibility["board"][2][0]!='X') return 7; else if(checkPossibility["board"][2][1]!='X') return 8; else if(checkPossibility["board"][2][3]!='X') return 9; } else if(checkPossibility["countX"]["count4"]==2) { if(checkPossibility["board"][0][0]!='X') return 1; else if(checkPossibility["board"][1][0]!='X') return 4; else if(checkPossibility["board"][2][0]!='X') return 7; } else if(checkPossibility["countX"]["count5"]==2) { if(checkPossibility["board"][0][1]!='X') return 2; else if(checkPossibility["board"][1][1]!='X') return 5; else if(checkPossibility["board"][2][1]!='X') return 8; }else if(checkPossibility["countX"]["count6"]==2) { if(checkPossibility["board"][0][2]!='X') return 3; else if(checkPossibility["board"][1][2]!='X') return 6; else if(checkPossibility["board"][2][2]!='X') return 9; }else if(checkPossibility["countX"]["count7"]==2) { if(checkPossibility["board"][0][0]!='X') return 1; else if(checkPossibility["board"][1][1]!='X') return 5; else if(checkPossibility["board"][2][2]!='X') return 9; }else if(checkPossibility["countX"]["count8"]==2) { if(checkPossibility["board"][2][0]!='X') return 7; else if(checkPossibility["board"][1][1]!='X') return 5; else if(checkPossibility["board"][0][2]!='X') return 3; } else { return ((Math.floor(Math.random() * 9))+1); } }, /** * check tic-tac-toe winner */ checkWinner(checkPossibility){ let win=[false,false]; if(checkPossibility["countX"][0]==3||checkPossibility["countX"][1]==3||checkPossibility["countX"][2]==3||checkPossibility["countX"][3]==3||checkPossibility["countX"][4]==3||checkPossibility["countX"][5]==3||checkPossibility["countX"][6]==3||checkPossibility["countX"][7]==3) win[0]=true; else if(checkPossibility["countO"][0]==3||checkPossibility["countO"][1]==3||checkPossibility["countO"][2]==3||checkPossibility["countO"][3]==3||checkPossibility["countO"][4]==3||checkPossibility["countO"][5]==3||checkPossibility["countO"][6]==3||checkPossibility["countO"][7]==3) win[1]=true; return win; } }
import Subscription from './Subscription'; export{Subscription};
import React, { Component } from "react"; import PropTypes from "prop-types"; import { connect } from "react-redux"; //Material imports import { withStyles } from "@material-ui/core/styles"; import { Paper, Button } from "@material-ui/core"; import MobileStepper from "@material-ui/core/MobileStepper"; import QuestionItem from "../components/QuestionItem"; import LoadingScreen from "./LoadingScreen"; import { fetchQuizData } from "../actions/QuizDataActions"; import SwipeableViews from "react-swipeable-views"; import { autoPlay } from "react-swipeable-views-utils"; const AutoPlaySwipeableViews = autoPlay(SwipeableViews); class QuizScreens extends Component { state = { loading: true, activeStep: 0, disableNextButton: true }; showAnswer = false; componentDidMount = () => { this.props.fetchQuizData( () => { // Show Quiz this.setState({ loading: false }); }, () => { // Show Error Message } ); }; handleNext = () => { const { quizData: { results } } = this.props; if (this.state.activeStep === results.length - 1) { this.props.history.push({ pathname: "/result" }); } else { this.setState(prevState => ({ activeStep: prevState.activeStep + 1, disableNextButton: true })); } }; handleBack = () => { this.setState(prevState => ({ activeStep: prevState.activeStep - 1 })); }; handleAnswerSelect = value => { const { quizData: { results } } = this.props; results[this.state.activeStep].userAnswer = value; this.setState({ disableNextButton: false }); }; handleStepChange = activeStep => { this.setState({ activeStep }); }; render() { const { classes, quizData: { results } } = this.props; const { activeStep, loading } = this.state; if (results !== undefined) { } // Sent Value - So on every next question not either True Or False will be selected return ( <div className={classes.rootContainer}> {!loading && results !== undefined && ( <Paper className={classes.root}> <AutoPlaySwipeableViews axis={"x"} index={activeStep} onChangeIndex={this.handleStepChange} autoplay={false} > {results.map((step, index) => ( <QuestionItem key={index} quizDataItem={step} handleAnswerSelect={this.handleAnswerSelect} value={ step.userAnswer !== undefined ? step.userAnswer : "Blank" } showAnswer={this.showAnswer} /> ))} </AutoPlaySwipeableViews> <MobileStepper steps={results.length} position="static" activeStep={activeStep} className={classes.mobileStepper} nextButton={ <Button size="small" onClick={this.handleNext} disabled={this.state.disableNextButton} color="primary" variant="contained" > Next </Button> } backButton={ <Button size="small" onClick={this.handleBack} disabled={true} color="primary" variant="contained" > Back </Button> } /> </Paper> )} {loading && <LoadingScreen />} </div> ); } } const styles = theme => ({ rootContainer: { backgroundImage: `url(${theme.background.image})`, backgroundRepeat: "no-repeat", backgroundSize: "cover", height: "100%", width: "100%", display: "flex", alignItems: "center", justifyContent: "center", position: "fixed" }, messageArea: { position: "relative", height: "50%", width: "50%", boxShadow: "0px 0px 7px 0px rgba(0,0,0,0.2)" }, root: { maxWidth: 400, flexGrow: 1, margin: 20 } }); const mapStateToProps = ({ quizData }) => { return { quizData }; }; export default connect( mapStateToProps, { fetchQuizData } )(withStyles(styles)(QuizScreens)); QuizScreens.propTypes = { classes: PropTypes.object.isRequired, history: PropTypes.object.isRequired, fetchQuizData: PropTypes.func.isRequired, quizData: PropTypes.object.isRequired };
import { createSlice } from "@reduxjs/toolkit"; const initialState = { flowName: "Untitled flow_1", }; const cardSlice = createSlice({ initialState, name: "flowState", reducers: { SetFlowName: (state, action) => { if (action.payload === "") { state.flowName = "Untitled flow_1"; } else state.flowName = action.payload; }, }, }); export const { SetFlowName } = cardSlice.actions; export default cardSlice.reducer;
// @ts-check /* eslint-disable react/prefer-stateless-function */ import React from 'react'; // BEGIN (write your solution here) class Card extends React.Component { static defaultProps = { title: null, text: null, }; render() { const { title, text } = this.props; return ( <div className="card"> <div className="card-body"> <h4 className="card-title">{title}</h4> <p className="card-text">{text}</p> </div> </div> ); } } export default Card; // END
//Loading effect $(window).on('load',function() { $("body").removeClass("preload"); }); //Table sort button $(document).ready(function(){ $('table').addClass('tablesorter'); $('table').tablesorter({ // theme: 'blue', headers: { // set initial sort order by column, this headers option setting overrides the sortInitialOrder option 1: { sortInitialOrder: 'asc' } }, headerTemplate: '{content}{icon}', widgets: ['zebra','columns'] }); }); //Switch between cumulative and daily cases document.querySelector("#option1").addEventListener("click",()=>{ $(".disptotal").removeClass("hide"); $(".disptotal").removeClass("hide"); $(".disp").addClass("hide"); $(".disp").addClass("hide"); }) document.querySelector("#option2").addEventListener("click",()=>{ $(".disp").removeClass("hide"); $(".disp").removeClass("hide"); $(".disptotal").addClass("hide"); $(".disptotal").addClass("hide"); }) //daily data for charts var daily = JSON.parse(document.querySelector("#json").textContent); //line chart function function drawChart(chrtTitle,chrtName,colValues) { // Define the chart to be drawn. var data = new google.visualization.DataTable(); // var daily = [] ; data.addColumn('string', ''); data.addColumn('number', 'Cnfrmd'); data.addColumn('number', 'Rcvrd'); data.addColumn('number', 'Death'); rows=[]; // daily.forEach((day)=>{ // // if(day["date"].substring(0,2)=="15") // // rows.push([day["date"].substring(0,2),Number(day["dailyconfirmed"])]); // // else // rows.push(["",day[colValues[0]],day[colValues[1]],day[colValues[2]]]); // }) for(i=daily.length-30;i<daily.length;i++) { rows.push(["",daily[i][colValues[0]],daily[i][colValues[1]],daily[i][colValues[2]]]); } data.addRows(rows); // Set chart options var options = { legend: { position: 'bottom'}, chart: { title: chrtTitle, subtitle: 'Last 30 days' }, hAxis: { title: '', }, vAxis: { title: 'Cases', }, colors: [ 'rgb(0, 51, 102)','green','red' ] // 'width':auto, // 'height':60% }; // Instantiate and draw the chart. var chart = new google.charts.Line(document.getElementById(chrtName)); chart.draw(data, options); } google.charts.setOnLoadCallback(()=>{ drawChart('GROWTH - INDIA','chart1',['confirmed','recovered','deaths'])}); google.charts.setOnLoadCallback(barChart); //barchart function function barChart() { rows=[['', 'Death', 'Rcvrd', 'Cnfrmd']]; for(i=daily.length-30;i<daily.length;i++) { rows.push([" ",daily[i]['dailydeaths'],daily[i]['dailyrecovered'],daily[i]['dailyconfirmed']]); } var data = google.visualization.arrayToDataTable(rows); var options = { chart: { title: 'DAILY TRENDS - INDIA', subtitle: 'Last 30 days', }, legend: { position: 'top', alignment: 'start' }, // legend: { position: 'top', maxLines: 3 }, isStacked: true, colors: [ 'red' ], }; var chart = new google.charts.Bar(document.getElementById('chart2')); chart.draw(data, google.charts.Bar.convertOptions(options)); }
({ 'bold': 'Negrito', 'copy': 'Copiar', 'cut': 'Cortar', 'delete': 'Eliminar', 'indent': 'Indentar', 'insertHorizontalRule': 'Régua horizontal', 'insertOrderedList': 'Lista numerada', 'insertUnorderedList': 'Lista marcada', 'italic': 'Itálico', 'justifyCenter': 'Alinhar ao centro', 'justifyFull': 'Justificar', 'justifyLeft': 'Alinhar à esquerda', 'justifyRight': 'Alinhar à direita', 'outdent': 'Recuar', 'paste': 'Colar', 'redo': 'Repetir', 'removeFormat': 'Remover formato', 'selectAll': 'Seleccionar tudo', 'strikethrough': 'Rasurado', 'subscript': 'Inferior à linha', 'superscript': 'Superior à linha', 'underline': 'Sublinhado', 'undo': 'Anular', 'unlink': 'Remover ligação', 'createLink': 'Criar ligação', 'toggleDir': 'Alternar direcção', 'insertImage': 'Inserir imagem', 'insertTable': 'Inserir/Editar tabela', 'toggleTableBorder': 'Alternar limite da tabela', 'deleteTable': 'Eliminar tabela', 'tableProp': 'Propriedades da tabela', 'htmlToggle': 'Origem HTML', 'foreColor': 'Cor de primeiro plano', 'hiliteColor': 'Cor de segundo plano', 'plainFormatBlock': 'Estilo de parágrafo', 'formatBlock': 'Estilo de parágrafo', 'fontSize': 'Tamanho do tipo de letra', 'fontName': 'Nome do tipo de letra', /* Error messages */ 'systemShortcutFF': 'A acção "${0}" apenas está disponível no Mozilla Firefox utilizando um atalho de teclado. Utilize ${1}.' })
const request = require('request'); const zlib = require('zlib'); const readLogs = require('./readLogs'); const date = process.argv[2]; main(); function main() { const url = `https://storage.googleapis.com/anvyl-interview-challenge/${date}-orders-access.log.gz`; request(url, {encoding: null}, function(err, response, body){ if(response.headers['content-type'] == 'application/x-gzip'){ zlib.gunzip(body, function(err, dezipped) { readLogs.readLogs(dezipped); }); } else { console.log("There was an error downloading these logs.") } }); }
const { v4: uuidv4 } = require("uuid"); const { Activity } = require("../models/activity"); const getAllActivities = async (req, res, next) => { let activities = []; try { activities = res.user.activities; res.activities = activities; } catch (err) { res.activities = activities; return res.status(500).json({ message: err.message }); } next(); }; const getActivity = async (req, res, next) => { let activity = {}; try { const activityId = req.params.activityId; activity = res.user.activities.find( (activity) => activity.id === activityId ); res.activity = activity; } catch (err) { res.activity = activity; return res.status(500).json({ message: err.message }); } next(); }; const createActivity = async (req, res, next) => { try { let activities = res.activities; const date = new Date(); activities.push( new Activity({ id: uuidv4(), name: req.body.name, duration: req.body.duration, date: date.toISOString(), calories: req.body.calories, }) ); let user = res.user; user.activities = activities; await user.save(); } catch (err) { return res.status(500).json({ message: err.message }); } next(); }; const updateActivity = async (req, res, next) => { try { let activities = res.activities; const activityId = req.params.activityId; const targetActivity = activities.find( (activity) => activity.id === activityId ); for (const field of Object.entries(req.body)) { targetActivity[field[0]] = field[1]; } let user = res.user; user.activities = activities; await user.save(); } catch (err) { return res.status(500).json({ message: err.message }); } next(); }; const deleteActivity = async (req, res, next) => { try { let activities = res.activities; const activityId = req.params.activityId; const targetActivityIndex = activities.findIndex( (activity) => activity.id === activityId ); activities.splice(targetActivityIndex, 1); let user = res.user; user.activities = activities; await user.save(); } catch (err) { return res.status(500).json({ message: err.message }); } next(); }; module.exports = { getAllActivities: getAllActivities, getActivity: getActivity, createActivity: createActivity, updateActivity: updateActivity, deleteActivity: deleteActivity, };
const sortItem = [ { display:"Name: A - Z", value: {_sort:'name', _order:'asc'} }, { display:"Name: Z - A", value: {_sort:'name', _order:'desc'} }, { display:"Price: Low to High", value: {_sort:'price', _order:'asc'} }, { display:"Price: High to Low", value: {_sort:'price', _order:'desc'} }, { display:"Rating: Low to High", value: {_sort:'rate', _order:'asc'} }, { display:"Rating: High to Low", value: {_sort:'rate', _order:'desc'} } ] export default sortItem
import Joi from "joi"; const ValidateDTO = class ValidateDTO { static postOrder(params) { const schema = Joi.object({ user: Joi.string().required(), product: Joi.string().required(), }); return schema.validate(params); } }; export default ValidateDTO;
const Customer = require('../models/Customer') const mongoose = require('mongoose') const Account = require('../models/Account') String.prototype.insert = function(index, string) { if (index > 0) { return this.substring(0, index) + string + this.substr(index); } return string + this; } module.exports = { get_account: async (req, res) => { const account = await Account.findById(req.params.id).populate('customer').populate('transactions') let balance = 0 account.transactions.forEach(transaction => { if (transaction.from_account == account._id.toString()) { balance -= transaction.amount } else { balance += transaction.amount } }) let balanceString = balance.toString() if (balance < 0) { balanceString = balanceString.insert(1, "$"); } else { balanceString = balanceString.insert(0, "$"); } res.render('account-details', { title: 'Account Details', account: account, balance: balanceString }) }, create_account: async (req, res) => { const account = new Account(req.body) await account.save() account.customer = await Customer.findById(req.body.customer_id) await account.save() const customer = await Customer.findById(req.body.customer_id) customer.accounts.push(account) await customer.save() res.send(200, account) } }
function Mouse(color, weight) { this.color = color; this.weight = weight; this.isDead = false; } Mouse.prototype.sleep = function() { console.log('Zzzz ...'); }; Mouse.prototype.die = function() { this.isDead = true; } Mouse.prototype.run = function() { console.log('Run ...'); } module.exports = Mouse;
import axios from 'axios'; import network from '../../core/network'; import { showError } from '../../core/utils/UserFeedback'; import events from '../../core/events'; import { refreshCurrentBoard } from '../../board/actions/boardActions'; export const ACTION_RETRIEVE_USER = 'ACTION_RETRIEVE_USER'; export const ACTION_CLEAR_USER = 'ACTION_CLEAR_USER'; function deleteUserRequest(uuid) { return network.delete(`/user/${uuid}`); } function updateRequest(uuid, params) { return network.patch(`/user/${uuid}`, params); } function userRequest(uuid) { return network.get(`/user/${uuid}`); } function deleteImageRequest(uuid) { return network.delete(`/user/${uuid}/profilepicture`); } function getImageUploadKeyRequest(uuid) { return network.get(`/user/${uuid}/upload`); } function uploadImageRequest(url, file) { return axios.put(url, file); } export const retrievedUser = (user, partial) => dispatch => dispatch({ type: ACTION_RETRIEVE_USER, payload: { user, partial, }, }); export const logout = () => dispatch => dispatch({ type: ACTION_CLEAR_USER, }); export const retrieveUser = () => async (dispatch, getState) => { const userRes = await userRequest(getState().auth.userId); const user = userRes.data; return dispatch(retrievedUser(user, false)); }; export const updateUser = params => async (dispatch, getState) => { try { await updateRequest(getState().user.currentUser._id, params); await dispatch(retrievedUser(params, true)); // Because the user is part of the board, that needs refreshing too. return dispatch(refreshCurrentBoard()); } catch (e) { showError(e); } }; export const deleteUser = () => async (dispatch, getState) => { try { await deleteUserRequest(getState().user.currentUser._id); events.fire('logout'); } catch (e) { showError('Failed to delete user.'); } }; export const deleteUserProfilePicture = () => async (dispatch, getState) => { try { await deleteImageRequest(getState().user.currentUser._id); return dispatch(retrieveUser()); } catch (e) { showError('Failed to delete profile picture.'); } }; export const changeUserProfilePicture = file => async (dispatch, getState) => { try { const { url } = (await getImageUploadKeyRequest(getState().user.currentUser._id)).data; await uploadImageRequest(url, file); return dispatch(retrieveUser()); } catch (e) { showError('Failed to delete profile picture.'); } };
import shortid from 'shortid'; import { FormElement, FormGroup, Input, Label } from '../../Styles'; export const Filter = ({ value, onFilterInput }) => { const inputFilterId = shortid.generate(); return ( <FormElement> <FormGroup> <Label htmlFor={inputFilterId}>Filter</Label> <Input id={inputFilterId} name="filter" value={value} onChange={onFilterInput} /> </FormGroup> </FormElement> ); };
/** * 给easyui tabs绑定双击事件 */ $.extend($.fn.tabs.methods, { /** * 绑定双击事件 * @param {Object} jq * @param {Object} caller 绑定的事件处理程序 */ bindDblclick: function(jq, caller){ return jq.each(function(){ var that = this; $(this).children("div.tabs-header").find("ul.tabs").undelegate('li', 'dblclick.tabs').delegate('li', 'dblclick.tabs', function(e){ if (caller && typeof(caller) == 'function') { var title = $(this).text(); var index = $(that).tabs('getTabIndex', $(that).tabs('getTab', title)); caller(index, title); } }); }); }, /** * 解除绑定双击事件 * @param {Object} jq */ unbindDblclick: function(jq){ return jq.each(function(){ $(this).children("div.tabs-header").find("ul.tabs").undelegate('li', 'dblclick.tabs'); }); } }); var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"}; function isCardID(sId){ var iSum=0 ; var info="" ; if(!(/^\d{17}(\d|x)$/i.test(sId) || /^\d{15}$/i.test(sId))){ return "你输入的身份证长度或格式错误"; } sId=sId.replace(/x$/i,"a"); if(aCity[parseInt(sId.substr(0,2))]==null) return "你的身份证地区非法"; if(sId.length==18){ sBirthday=sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2)); }else if(sId.length==15){ sBirthday="19"+sId.substr(6,2)+"-"+Number(sId.substr(8,2))+"-"+Number(sId.substr(10,2)); } var d=new Date(sBirthday.replace(/-/g,"/")) ; if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate()))return "身份证上的出生日期非法"; if(sId.length==18){ for(var i = 17;i>=0;i --) { iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11) ; } if(iSum%11!=1) return "你输入的身份证号非法"; } return true;//aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女") } $.extend($.fn.validatebox.defaults.rules, { idCode: { validator: function(value,param){ var flag= isCardID(value); return flag==true?true:false; }, message: '请输入正确的身份证号' }, mobile: { validator: function(value,element){ var length = value.length; var mobileReg = /^1[3|4|5|7|8][0-9]\d{8}$/; return (length == 11 && mobileReg.test(value)); }, message: '请输入正确的手机号码' }, charOrNum: { validator: function(value,element){ var test = /^[a-zA-Z0-9]*$/g; return isCharOrNum(value); }, message: '请输入正确的密码' }, fixPhoneNum:{//固定电话号码校验 validator: function (value) { return /^((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/.test(value); }, message: '请输入正确的固定电话号码' }, equals: { validator: function(value,param){ return value == $(param[0]).val(); }, message: '密码和确认密码不同' } }); /** * 新增标签页 * @param title * @param url * @param icon */ function addTab(title,url,icon) { if($('#tabs').tabs('exists',title)) { //已经存在,先删除 $('#tabs').tabs('close',title); } $('#tabs').tabs('add', { title:title, content:createFrame(url), icon:icon, closable:true, cache:false } ); } function createFrame(url) { var frameHtml = ''; if(url.indexOf('http') <= -1) { //url = baseUrl + url; if (url.indexOf('?') == -1) { url = ctx + url + '?timestamp=' + (new Date()).getTime(); } else { url = ctx + url + '&timestamp=' + (new Date()).getTime(); } } frameHtml = '<iframe scrolling="auto" frameborder="0" src="'+url+'" style="width:100%;height:100%;"></iframe>'; return frameHtml; } Date.prototype.format = function (format) { var o = { "M+": this.getMonth() + 1, // month "d+": this.getDate(), // day "h+": this.getHours(), // hour "m+": this.getMinutes(), // minute "s+": this.getSeconds(), // second "q+": Math.floor((this.getMonth() + 3) / 3), // quarter "S": this.getMilliseconds() // millisecond } if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (this.getFullYear() + "") .substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); return format; } function formatDatebox(value) { if (value == null || value == '') { return ''; } var dt; if (value instanceof Date) { dt = value; } else { dt = new Date(value); } return dt.format("yyyy-MM-dd"); //扩展的Date的format方法(上述插件实现) } function formatDateTimebox(value) { if (value == null || value == '') { return ''; } var dt; if (value instanceof Date) { dt = value; } else { dt = new Date(value); } return dt.format("yyyy-MM-dd hh:mm:ss"); //扩展的Date的format方法(上述插件实现) } /** * 判断字符串是否为数字和字母组合 * @param nubmer * @returns {Boolean} */ function isCharOrNum(str){ var re =/^[0-9a-zA-Z]*$/g; if (re.test(str)){ return true; } return false; } /** * 加载数据字典 * @param name * @returns */ function loadDataDictionary(dicName) { var dataDictionaryList = []; var dicParams = {}; dicParams[csrfParameter]=csrfToken; dicParams['dicName']=dicName; $.ajax({ 'url' : ctx + '/sysDataDictionary/getSysDataDictionaryByName', 'type' : 'post', 'async' : false, 'data':dicParams, 'dataType':'json', 'error' : function() { }, 'success' : function(res) { if(res && res.code==200){ dataDictionaryList = res.data; } } }); return dataDictionaryList; } /** * 加载系统参数 * @param name * @returns */ function loadSysParam(paramKey) { // 数据字典url var sysParamValue = ''; var searchParams = {}; searchParams[csrfParameter]=csrfToken; searchParams['paramKey']=paramKey; $.ajax({ 'url' : ctx + '/sysParam/getSysParamByKey', 'type' : 'post', 'async' : false, 'data':searchParams, 'dataType':'json', 'error' : function() { }, 'success' : function(res) { if(res && res.code==200){ sysParamValue = res.data; } } }); return sysParamValue; }
isc.ClassFactory.defineClass('IRAppFrame', isc.VLayout);
myApp.config(function($routeProvider) { $routeProvider .when('/:role/:topic', { templateUrl: 'pages/page.html', controller: function($http, $scope, $routeParams, $timeout) { //get the correct JSON topic file based on the URL $http.get('json/' + $routeParams.topic + '.json', {cache:true}).success(function(data) { //locate the topic name $scope.topic = data.name; //locate banner image (if present) $scope.banner = data.banner; //locate the carousel images (if present) $scope.carousel = data.carousel; //locate the subtopics $scope.subtopics = data.subtopics; //locate the resources //$scope.resources = data.resources; }); $scope.role = $routeParams.role; } }) });
import '../../../../scripts/common/app' import AppRoutes from '../../../../configs/AppRoutes' import formItems from './table/form-item' import ImageText from '../../../../models/matter/imageText' import View from '../../../../views/domain/page.vue' new Vue({ el: '#app', render: h => { const v = h(View, { props: { display: 'grid', formItems, defaultCriterias: [ { filterType: 'EQ', property: 'type', value: 'imageText' } ], domain: ImageText, actions: [ { upload: { title: '新建图文素材', type: 'primary', unauthorize: true, onAction: ($list, rows) => { App.push(AppRoutes.Matter.createImageText()) } } } ], renderGrid: (h, ctx, $grid) => { return <div class='image-text-item'> <div class='ctime'>{dateformat(new Date(ctx.row.ctime), 'yyyy-mm-dd HH:MM:ss')}</div> <div class='title'>{ctx.row.name}</div> <div class='img'><img src={ctx.row.url}></img></div> <div class='abstract'>{ctx.row.metaData.description}</div> </div> } } }) return <card>{v}</card> } })
const Syntax = require('jsdoc/src/syntax').Syntax; // 添加对 TypeScipt interface 的支持 Syntax.TSInterfaceDeclaration = 'TSInterfaceDeclaration'; Syntax.TSInterfaceBody = 'TSInterfaceBody'; Syntax.TSMethodSignature = 'TSMethodSignature'; Syntax.TSModuleDeclaration = 'TSModuleDeclaration'; Syntax.TSPropertySignature = 'TSPropertySignature'; Syntax.TSDeclareFunction = 'TSDeclareFunction'; Syntax.TSIndexSignature = 'TSIndexSignature'; Syntax.TSTypeAliasDeclaration = 'TSTypeAliasDeclaration'; Syntax.TSEnumDeclaration = 'TSEnumDeclaration'; Syntax.TSCallSignatureDeclaration = 'TSCallSignatureDeclaration'; Syntax.TSEnumMember = 'TSEnumMember'; Syntax.TSQualifiedName = 'TSQualifiedName'; exports.Syntax = Syntax;
var searchData= [ ['lu_5fdecomp_21',['lu_Decomp',['../ludecomp_8h.html#a5f9664591deea4acaa4f0193f29305d9',1,'ludecomp.h']]], ['ludecomp_2eh_22',['ludecomp.h',['../ludecomp_8h.html',1,'']]] ];
/* idea is to not have one large gulp file, rather each file will handle a specific gulp task. to create a new task, add a new "taskName.js" to the task directory */ var requireDirectory = require('require-dir'); // require tasks from the task directory and subdirectorys requireDirectory('./tasks', {recurse: true} );
var width = 1000, height = 500; var colors = d3.scaleOrdinal(d3.schemeDark2); var svg = d3.select("body").append("svg") .attr("width", width).attr("height", height) .style("background", "pink") var newData = d3.json("newData.json"); var details = [{Party:"NUR-OTAN", number:73},{Party:"AK-ZHOL", number:8},{Party:"Communist People's Party", number:7} ]; var data = d3.pie().sort(null).value(function(d){return d.number;})(details); var segments = d3.arc() .innerRadius(0) .outerRadius(200) .padAngle(.05) .padRadius(50) var sections = svg.append("g").attr("transform", "translate(250,250)") .selectAll("path").data(data); sections.enter().append("path").attr("d", segments).attr("fill", function(d) {return colors(d.data.number);}); var content = d3.select("g").selectAll("text").data(data); content.enter().append("text").classed("inside", true).each(function(d){ var center = segments.centroid(d); d3.select(this).attr("x", center[0]).attr("y", center[1]).text(d.data.number); }); var legends = svg.append("g").attr("transform", "translate(500, 100)").selectAll(".legends").data(data); var legend = legends.enter().append("g").classed("legends", true).attr("transform", function(d,i){return "translate(0,"+(i+1)*30+")";}); legend.append("rect").attr("width", 20).attr("height", 20).attr("fill", function(d){return colors(d.data.number);}); legend.append("text").classed("label", true).text(function(d){return d.data.Party;}) .attr("fill", function(d){return colors(d.data.number);}) .attr("x", 30) .attr("y", 15);
Ext.define('Layouts.model.Content', { extend: 'Ext.data.Model', config: { fields: [ 'nid', 'title', 'icon1', 'icon2', ] }, /*sectionData: function(){ var d = this.data, taxonomy = [ d.tid, d.term ]; return taxonomy.join(" "); }*/ });
$("#slideshow > div:gt(0)").hide(); setInterval(function() { $('#slideshow > div:first') .fadeOut(1000) .next() .fadeIn(1000) .end() .appendTo('#slideshow'); }, 3000); //gor google maps on about page function initMap() { // accessed map and set the location var mapDiv = document.getElementById('map'); var map = new google.maps.Map(mapDiv, { center: {lat:49.407063, lng:8.629881}, zoom: 16 }); // additional features to map var marker=new google.maps.Marker({ position:{lat:49.407063, lng:8.629881}, animation: google.maps.Animation.BOUNCE }) marker.setMap(map); var infowindow = new google.maps.InfoWindow({ content:"My Current Position" }); infowindow.open(map,marker); } //Devlopers button on about page $(document).ready(function(){ //Accessed logedIn users profile and show in upper right corner................................... //for consistancy after refresh check if user is logged in and if yes then keep his name "displayed" and loginButton "undisplayed" var userprofile=localStorage.getItem('username'); if(userprofile!=null){ $(".loggedin_username").append(userprofile + '<b class="caret"></b>'); $(".loggedin_username").after(`<ul class="dropdown-menu"> <li><a href="" id="logoutbtn">logout</a></li> </ul>`); } if(localStorage.getItem('alreadyloggedin')=='true') { $('#loginsignupbtn').css({'display':'none'}); } $("#developer").click(function(){ $("#github").toggle(500); }); //login form made visible onclick of login button on navigation bar $('#loginsignupbtn').click(function() { $('#backdrop-login').css('display','block'); $('#backdrop-login').addClass('backdropvisible'); }) //on click of "Register" link on login form->1.signup form added, and 2.login form removed $('#signup').click(function() { $('#backdrop-login').css('display','none'); $('#backdrop-signup').css('display','block'); $('#backdrop-signup').addClass('backdropvisible'); $('#backdrop-login').removeClass('backdropvisible'); }) //on close(X) button of signupform 1.signupform removed, and 2.loginformadded $('#signupclose').click(function() { $('#backdrop-signup').css('display','none'); $('#backdrop-signup').removeClass('backdropvisible'); $('#backdrop-login').addClass('backdropvisible'); }) //on close(X) button of loginform 1.loginform removed $('#loginclose').click(function() { $('#backdrop-login').css('display','none'); $('#backdrop-login').removeClass('backdropvisible'); }); /**********************************************LOGIN/LOGOUT/SIGNUP************************************************************************************* */ $("#logoutbtn").click(function() { //on logout login option made available back localStorage.clear(); $("#loginsignupbtn").css({'display':'block'}); }) $('#loginform').submit(function(e) { e.preventDefault(); if($('#emailfield').val()!='' && $('#passwordfield').val()!='') { alert("login Button clicked"); $.ajax({ url:"/home/login", type:'POST', dataType:'JSON', data: JSON.stringify({ email: $('#emailfield').val(), password: $('#passwordfield').val() }), contentType:'application/json', complete:function(){ console.log("Completed.....") }, success:function(data){ //localStorage.clear(); localStorage.setItem('token',data.obj); localStorage.setItem('username',data.username); localStorage.setItem('alreadyloggedin',true); //Updated the login/logout feature //removed login/logout button $("#loginsignupbtn").css({'display':'none'}); //attached loggedin user name and logout feature $(".loggedin_username").append(data.username + '<b class="caret"></b>'); $(".loggedin_username").after(`<ul class="dropdown-menu"> <li><a href="" id="logoutbtn">logout</a></li> </ul>`); //removed loginform after submit is clicked $('#backdrop-login').css('display','none'); $('#backdrop-login').removeClass('backdropvisible'); }, error:function(jQxhr){ console.log("the the error has occured= ",jQxhr); } }); } });//login end............................. $('.signupbtn').click(function(e) { var username=$('#namefield').val(); var surname= $('#surnamefield').val(); var email= $('#signupemailfield').val(); var password=$('#signuppasswordfield').val(); e.preventDefault(); if(username!='' && surname!='' && email!='' && password!='') { alert("Signup Button clicked"); console.log("signup data on client side ", $('#namefield').val(),$('#surnamefield').val(),$('#signupemailfield').val(),$('#signuppasswordfield').val()); $.ajax({ url:'/home/signup', type:"POST", dataType:'JSON', data: JSON.stringify({ username: username, surname: surname, email: email, password: password }), contentType:'application/json', complete:function(){ console.log("Completed....."); }, success:function(data){ console.log(data.obj); $('#backdrop-signup').css('display','none'); $('#backdrop-signup').removeClass('backdropvisible'); }, error:function(jQxhr){ console.log("the error has occured= ",jQxhr); } }); } }); /********************************************RESTRICTED FEATURES******************************************************************** */ //for new "releases" $("#newreleases").click(function(e) { e.preventDefault(); alert("clicked newreleases"); var token1=localStorage.getItem('token') ? '?token=' + localStorage.getItem('token') : ''; console.log("token is ",token1); $.ajax({ type:"GET", url:"/newreleases"+token1, success:function() { window.location.href = '/newreleases'+token1; }, error:function() { } }); }); //for "show list" $("#tvserieslist").click(function(e) { e.preventDefault(); alert("clicked tvserieslist"); var token2=localStorage.getItem('token') ? '?token=' + localStorage.getItem('token') : ''; console.log("token is ",token2); $.ajax({ type:"get", url:`/showlist${token2}`, success:function() { window.location.href = '/showlist'+token2; }, error:function() { } }); }); //for "All episodes" $("#episodelist").click(function(e) { e.preventDefault(); alert("clicked episodelist"); var token3=localStorage.getItem('token') ? '?token=' + localStorage.getItem('token') : ''; console.log("token is ",token3); $.ajax({ type:"get", url:`/episodelist${token3}`, success:function() { window.location.href = '/episodelist'+token3; }, error:function() { } }); }); });
var Junjianxiada = new Vue({ el : '#Junjianxiada', data :{ adminId : $("#adminid").val(), deptId : $("#deptid").val(), xiangmutext:'', xiangmu : {}, xiangmulist : [], leibielist:[], danweilist:[], excelxiangmulist:[],//批量导入 xiangmuId:'', editFlag : 0, // 0:新增,1:修改 show : false, // 显示列表是否有数据 pageIndex : 1, pageSize : 10, pageCount : 0, recordCount : 0, inputPageIndexValue : "", }, created : function() { var _this = this; _this.bindXiadaList(); _this.bindLeibielist(); _this.bindDanweilist(); }, methods : { bindXiadaList:function (){ var _this = this; layer.open({type:3}); $.post("/junjianxiangmu/findXiangmuBydeptId",{ xiangmuname :_this.xiangmutext, deptid : _this.deptId, pageindex : _this.pageIndex, pagesize : _this.pageSize, rdm : Math.random() },function(ppData){ layer.closeAll("loading"); if (ppData != null){ if(ppData.result == "1"){ var data=ppData.resultContent; if(data.XiangMuList.length > 0){ _this.show = true; _this.xiangmulist=data.XiangMuList; var PageInfo = data.PageInfo; _this.pageIndex = PageInfo.pageIndex; _this.recordCount = PageInfo.recordCount; _this.pageCount = PageInfo.pageCount; }else { _this.show = false; } }else{ layer.alert(ppData.message); } } },"json"); }, toAdd : function (){ $('#editXiadaxiamgmuModal').modal(); $("#myModalLabel_xiadaxiangmu").html("新增军建计划下达情况"); this.editFlag = 0; this.xiangmu = {}; this.xiangmuId=""; }, bindLeibielist:function (){ var _this = this; layer.open({type:3}); $.post('/leibiebiaoqian/find_all',{ biaoqian:"", rdm:Math.random() },function(ppData){ layer.closeAll("loading"); if(ppData!=null){ if(ppData.result == '1'){ _this.leibielist =ppData.resultContent; }else{ layer.alert(ppData.message); } } },"json"); }, bindDanweilist:function (){ var _this = this; layer.open({type:3}); $.post("/dept/findVaild",{ pageindex : 1, pagesize : 1000, rdm : Math.random() },function(ppData){ layer.closeAll("loading"); if (ppData != null){ if(ppData.result == "1"){ var data=ppData.resultContent; if(data.DanweiList.length > 0){ _this.danweilist=data.DanweiList; }else { _this.show = false; } }else{ layer.alert(ppData.message); } } },"json"); }, addXiangmu:function(){ var _this = this; if(_this.checkInputData()){ layer.open({type:3}); $.post('/junjianxiangmu/add',{ adminId : _this.adminId, xiangmuname:$.trim(_this.xiangmu.xiangmuname), xiangmupifu:$.trim(_this.xiangmu.xiangmupifu), lianbaopifujine:$.trim(_this.xiangmu.lianbaopifujine), zhongxinpifujine:$.trim(_this.xiangmu.zhongxinpifujine), lianbaoyuliujine:$.trim(_this.xiangmu.lianbaoyuliujine), xiangmuleibie:$.trim(_this.xiangmu.xiangmuleibie), jieshoudanweiid:$.trim(_this.xiangmu.jieshoudanweiid), beizhu:$.trim(_this.xiangmu.beizhu), random : Math.random() },function(ppData){ if(ppData != null){ layer.closeAll("loading"); if(ppData.result == "1"){ layer.open({ time:1000, btn:[], content:"新增成功!", }); $("#editXiadaxiamgmuModal").modal("hide"); _this.bindXiadaList(); }else{ layer.alert(ppData.message); } } },"json"); } }, perpareToModifyXiangmu : function (ppxiangmuid){ $('#editXiadaxiamgmuModal').modal(); $("#myModalLabel_xiadaxiangmu").html("修改军建计划下达情况"); this.editFlag = 1; this.xiangmu = {}; this.xiangmuId=ppxiangmuid; this.bindXiangmu(); }, bindXiangmu:function (){ var _this = this; layer.open({type:3}); $.post('/junjianxiangmu/find_one', { xiangmuid : _this.xiangmuId, rdm : Math.random() },function(ppData) { layer.closeAll("loading"); if(ppData != null){ if(ppData.result == "1"){ var data = ppData.resultContent; _this.xiangmu = data; }else{ layer.alert(ppData.message); } } },"json"); }, modifyXiangmu:function (){ var _this = this; if(_this.checkInputData()){ layer.open({type:3}); $.post('/junjianxiangmu/modify',{ xiangmuId: _this.xiangmuId, adminId : _this.adminId, xiangmuname:$.trim(_this.xiangmu.xiangmuname), xiangmupifu:$.trim(_this.xiangmu.xiangmupifu), lianbaopifujine:$.trim(_this.xiangmu.lianbaopifujine), zhongxinpifujine:$.trim(_this.xiangmu.zhongxinpifujine), lianbaoyuliujine:$.trim(_this.xiangmu.lianbaoyuliujine), xiangmuleibie:$.trim(_this.xiangmu.xiangmuleibie), jieshoudanweiid:$.trim(_this.xiangmu.jieshoudanweiid), beizhu:$.trim(_this.xiangmu.beizhu), random : Math.random() },function(ppData){ if(ppData != null){ layer.closeAll("loading"); if(ppData.result == "1"){ layer.open({ time:1000, btn:[], content:"修改成功!", }); $("#editXiadaxiamgmuModal").modal("hide"); _this.bindXiadaList(); }else{ layer.alert(ppData.message); } } },"json"); } }, toDelete:function (ppxiangmuid){ var _this = this; layer.confirm("确定删除该条军建计划吗?",{ btn : ['是','否'] },function(){ layer.open({type:3}); $.post("/junjianxiangmu/delete", { xiangmuid : ppxiangmuid, random : Math.random() }, function(ppData) { if (ppData != null) { layer.closeAll("loading"); if(ppData.result != "1"){ layer.alert(ppData.message); }else{ layer.open({ time:1000, btn:[], content:"删除成功!", }); _this.bindXiadaList(); } } },"json"); }) }, showUploadXls : function(){ $("#uploadModal").modal("show"); this.getFileUrl("jjjf",'20','xls,xlsx',""); }, getFileUrl : function(ppFolderName,ppFileSize,ppShangChuanWenJianLeiXing,ppPiciId){ var _this = this; $("#uploadModal-body").load("upload_batch.html?fujianpath=/jjjf/"+ppFolderName+"&filesize="+ppFileSize, function(){ UploadVue.Init(ppShangChuanWenJianLeiXing,ppFileSize+"kb",function(jsonList){ if(jsonList.length==0){ return; } var filename=jsonList[0].filename; var fileurl=jsonList[0].fileurl; var filesize=jsonList[0].filesize; _this.getValue(fileurl); },function(){ $("#uploadModal").modal("hide"); }); }); }, getValue : function(ppFileurl){ var _this=this; layer.open({type:3}); $.post("/import_xiangmu/get_value",{ fileurl:ppFileurl, random : Math.random() },function(ppData){ layer.closeAll("loading"); if(ppData != null){ var mmData = ppData; var result = mmData.result; var message = mmData.message; var data = mmData.resultContent; if(result == "1") { _this.excelxiangmulist = ppData.resultContent; _this.importXiangmu(); }else{ layer.alert(message); } } },"json"); }, importXiangmu : function(){ var _this = this; layer.confirm("确定要导入所有经费项目吗?",{ btn : ["是","否"] },function(){ layer.closeAll("dialog"); _this.startDaoru(); }); }, startDaoru : function(){ var _this = this; layer.open({type:3}); //$("#daoru").attr("disabled","disabled"); _this.daoru(0); }, daoru : function(ppMuluCurrentIndex){ layer.open({type:3}); var _this=this; var CurrentIndex = ppMuluCurrentIndex+1; layer.open({ type: 3, content: "<div style='font-size:18px;font-weight:bold;padding-top:40px;width:200px;text-align:left;'>正在导入基建经费<br/>当前进度 "+CurrentIndex+" / "+_this.excelxiangmulist.length+"</div>" }); $.post("/import_xiangmu/import",{ xiangmuname:_this.excelxiangmulist[ppMuluCurrentIndex].项目名称, xiangmupifu:_this.excelxiangmulist[ppMuluCurrentIndex].两级批复情况, lianbaopifujine:_this.excelxiangmulist[ppMuluCurrentIndex].联保批复金额, zhongxinpifujine:_this.excelxiangmulist[ppMuluCurrentIndex].中心批复金额, lianbaoyuliujine:_this.excelxiangmulist[ppMuluCurrentIndex].联保预留预备费, jingfeixiadaqingkuang:_this.excelxiangmulist[ppMuluCurrentIndex].两级经费下达情况, yusuanniandu:_this.excelxiangmulist[ppMuluCurrentIndex].预算年度, lianbaojingfeizhibiao:_this.excelxiangmulist[ppMuluCurrentIndex].联保下达经费指标, zhongxinjingfeizhibiao:_this.excelxiangmulist[ppMuluCurrentIndex].中心下达经费指标, zhongxinyuliujine:_this.excelxiangmulist[ppMuluCurrentIndex].中心预留预备费, zhongxinkuaijihao:_this.excelxiangmulist[ppMuluCurrentIndex].中心会计账凭证号, chengshoujingfeidanwei:_this.excelxiangmulist[ppMuluCurrentIndex].承受经费单位名称, jingfeikemu:_this.excelxiangmulist[ppMuluCurrentIndex].经费科目, xiangmuzhuangtai:_this.excelxiangmulist[ppMuluCurrentIndex].项目状态, kaigongshijian:_this.excelxiangmulist[ppMuluCurrentIndex].开工时间, hetongzongjia:_this.excelxiangmulist[ppMuluCurrentIndex].各类合同总价, wangchengtouzi:_this.excelxiangmulist[ppMuluCurrentIndex].完成投资, jindukuaizhifu:_this.excelxiangmulist[ppMuluCurrentIndex].进度款支付, jindukuanbili:_this.excelxiangmulist[ppMuluCurrentIndex].进度款占总合同比例, wangongshijian:_this.excelxiangmulist[ppMuluCurrentIndex].完工时间, xiangzhongxinshenqingzijin:_this.excelxiangmulist[ppMuluCurrentIndex].向中心申请资金, shenqingshijian:_this.excelxiangmulist[ppMuluCurrentIndex].申请时间, xianglianbaoshenqingzijin:_this.excelxiangmulist[ppMuluCurrentIndex].向联保申请拨付金额, xianglianbaoshenqingbofushijian:_this.excelxiangmulist[ppMuluCurrentIndex].向联保申请拨付时间, lianbaobofujine:_this.excelxiangmulist[ppMuluCurrentIndex].联保拨付金额, lianbaobofushijian:_this.excelxiangmulist[ppMuluCurrentIndex].联保拨付时间, zhongxinbofujine:_this.excelxiangmulist[ppMuluCurrentIndex].中心资金拨付金额, zhongxinbofushijian:_this.excelxiangmulist[ppMuluCurrentIndex].中心拨付时间, jiesuanzhuangtai:_this.excelxiangmulist[ppMuluCurrentIndex].竣工结算状态, jiesuanwanchengtime:_this.excelxiangmulist[ppMuluCurrentIndex].竣工结算完成时间, jiesuanqingkuang:_this.excelxiangmulist[ppMuluCurrentIndex].竣工决算情况, shifoujizhang:_this.excelxiangmulist[ppMuluCurrentIndex].是否记账和登记, jiesuanpifuwenhao:_this.excelxiangmulist[ppMuluCurrentIndex].两级决算批复文号, jiesuanpifujine:_this.excelxiangmulist[ppMuluCurrentIndex].决算批复金额, jieyushangjiaojine:_this.excelxiangmulist[ppMuluCurrentIndex].结余上缴金额, xiangmuleibie:_this.excelxiangmulist[ppMuluCurrentIndex].类别, beizhu:_this.excelxiangmulist[ppMuluCurrentIndex].备注, random : Math.random() }, function(ppData) { layer.closeAll("loading"); if (ppData.result == "0") { layer.alert(message); }else{ if(ppMuluCurrentIndex >=_this.excelxiangmulist.length - 1){ layer.alert("导入完成!"); _this.bindXiadaList(); }else{ ppMuluCurrentIndex++; _this.daoru(ppMuluCurrentIndex); } } },"json") }, backup : function(){ var _this = this; //layer.open({type:3}); $.post("/import_xiangmu/backup",{ random : Math.random() },function(ppData){ layer.closeAll("loading"); if(ppData != null){ var mmData = ppData; var result = mmData.result; var message = mmData.message; var data = mmData.resultContent; window.location.href=data; } },"json"); }, //检查数字 checknum : function(ppNum) { var regPos = /^\d+(\.\d+)?$/; //非负浮点数 var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数 if (regPos.test(ppNum) || regNeg.test(ppNum)) { return true; } else { return false; } }, //检查输入信息 checkInputData : function(){ var _this=this; var xiangmuname = !_this.xiangmu.xiangmuname ? "" : $.trim(_this.xiangmu.xiangmuname); if("" == xiangmuname){ layer.alert("请填写项目名称!"); return false; } var xiangmupifu = !_this.xiangmu.xiangmupifu ? "" : $.trim(_this.xiangmu.xiangmupifu); if("" == xiangmupifu){ layer.alert("请填写两级建设计划或设计任务书批复!"); return false; } var lianbaopifujine = !_this.xiangmu.lianbaopifujine ? "" : $.trim(_this.xiangmu.lianbaopifujine); if("" == lianbaopifujine){ layer.alert("请填写联保建设计划批复金额!"); return false; } if (!_this.checknum(lianbaopifujine)) { layer.alert("联保建设计划批复金额请填写数字格式!"); return false; } var zhongxinpifujine = !_this.xiangmu.zhongxinpifujine ? "" : $.trim(_this.xiangmu.zhongxinpifujine); if("" == zhongxinpifujine){ layer.alert("请填写中心建设计划批复金额!"); return false; } if (!_this.checknum(zhongxinpifujine)) { layer.alert("中心建设计划批复金额请填写数字格式!"); return false; } var lianbaoyuliujine = !_this.xiangmu.lianbaoyuliujine ? "" : $.trim(_this.xiangmu.lianbaoyuliujine); if("" == lianbaoyuliujine){ layer.alert("请填写联保预留预备费!"); return false; } if (!_this.checknum(lianbaoyuliujine)) { layer.alert("联保预留预备费请填写数字格式!"); return false; } /*var xiangmuleibie = !_this.xiangmu.xiangmuleibie ? "" : $.trim(_this.xiangmu.xiangmuleibie); if("" == xiangmuleibie){ layer.alert("请选择类别!"); return false; }*/ var jieshoudanweiid = !_this.xiangmu.jieshoudanweiid ? "" : $.trim(_this.xiangmu.jieshoudanweiid); if("" == jieshoudanweiid){ layer.alert("请选择接受单位!"); return false; } return true; }, //跳到首页 SetPageIndex : function(){ this.pageIndex = 1; }, SetPageEnd : function(){ this.pageIndex = this.pageCount; }, //上一页 SetPageIndexPrePage : function(){ var PrePage = ((this.pageIndex -1) <= 0) ? 1 : (this.pageIndex -1); this.pageIndex = PrePage; }, //下一页 SetPageIndexNextPage : function(){ var NextPage = ((this.pageIndex +1) >= this.pageCount) ? this.pageCount : (this.pageIndex +1); this.pageIndex = NextPage; }, //跳转界面 JumpPage : function(){ if(this.inputPageIndexValue <= 1){ this.inputPageIndexValue = 1; }else if(this.inputPageIndexValue >= this.pageCount){ this.inputPageIndexValue = this.pageCount; } this.pageIndex = this.inputPageIndexValue; this.inputPageIndexValue = ''; }, }, watch :{ //监控分页情况,刷新列表 pageIndex : function(){ this.bindXiadaList(); } } })
class Background { constructor(){ this.x=0; this.y=0; this.width=$canvas.width; this.height=$canvas.height; this.img=new Image(); this.img.src="/images/classic_city.png" this.img.onload = () => { this.draw() } } draw(){ this.x = this.x-1*generalSpeed if(this.x <-$canvas.width){ this.x=0; } $context.drawImage(this.img,this.x, this.y, this.width, this.height) $context.drawImage(this.img, this.x+$canvas.width, this.y, this.width, this.height) } } class Level2 extends Background { constructor(x,y,width,height){ super(x,y,width,height) this.img=new Image() this.img.src= "/images/horror2.png" this.img.onload = () => { this.draw() } } } class Level3 extends Background { constructor(x,y,width,height){ super(x,y,width,height) this.img=new Image() this.img.src= "/images/volcanoes.png" this.img.onload = () => { this.draw() } } } class Music{ constructor(){ this.sound = new Audio() this.sound.src = "/music/YellowMagicOrchestra_Rydeen.mp3" this.sound.volume = 0.1 // this.sound.onload = () =>{ // this.playAudio() // } } play(){ this.sound.play() } pause(){ this.sound.pause() } stop(){ this.pause() this.sound.currentTime = 0 } } class Character{ constructor(x, y) { this.x=x this.y=y this.width=100 this.height=150 this.velY=0; this.velX=0; this.jumping=false this.jumpStrength = 297 this.friction = 0.8 this.img=new Image() this.img.src="../images/skatercat.png" this.img.onload = () => { this.draw() } } draw(){ if(this.y>$canvas.height - this.height){ this.y=$canvas.height - this.height -13 this.jumping=false } $context.drawImage(this.img, this.x, this.y, this.width, this.height) } jump(){ if(!this.jumping){ this.y -= this.jumpStrength this.jumping=true }else if(this.jumping){ this.y +=this.jumpStrength this.jumping=false } } newPos(){ if(this.jumping){ this.y +=gravity } } touch(obstacle){ return( this.x < obstacle.x + obstacle.width&& this.x+this.width > obstacle.x && this.y < obstacle.y + obstacle.height && this.y + this.height > obstacle.y ) } } class Policia { constructor(x,y) { this.x = x this.y = y this.width = 135 this.height = 160 this.hp = 4; this.img= new Image() this.img.src = "../images/policecat.png" } draw() { this.x = this.x-1*generalSpeed $context.drawImage(this.img, this.x, this.y, this.width, this.height) } damage(){ this.hp-- } } class Covid{ constructor(x,y) { this.x = x this.y = y this.width = 85 this.height = 85 this.hp = 2; this.img= new Image() this.img.src = "../images/covid.png" } draw() { this.x = this.x-1*generalSpeed $context.drawImage(this.img, this.x, this.y, this.width, this.height) } damage(){ this.hp-- } } class Monster{ constructor(x,y) { this.x = x this.y = y this.width = 120 this.height = 220 this.hp = 8 ; this.img= new Image() this.img.src = "../images/gatomalo.png" } draw() { this.x = this.x-1*generalSpeed $context.drawImage(this.img, this.x, this.y, this.width, this.height) } damage(){ this.hp-- } } class Ramen { constructor(x,y) { this.x = x this.y = y this.width = 70 this.height = 70 this.img = new Image() this.img.src = "../images/ramen.png" } draw() { this.x = this.x-1*generalSpeed $context.drawImage(this.img, this.x, this.y, this.width, this.height) } } class Arma{ constructor(x,y){ this.x=x this.y=y this.width=20 this.height=20 this.img=new Image(); this.img.src="../images/naruto.png" } draw(){ this.x += 4; $context.drawImage(this.img, this.x, this.y, this.width, this.height) } touch(obstacle){ return (this.x < obstacle.x + obstacle.width) && (this.x + this.width > obstacle.x) && (this.y < obstacle.y + obstacle.height) && (this.y + this.height > obstacle.y) } } class Barras{ constructor(x,y){ this.x=x this.y=y this.width=30 this.height=15 this.img=new Image(); this.img.src="../images/barraa.png" } draw(){ this.x -=5 $context.drawImage(this.img, this.x, this.y, this.width, this.height) } } class Cuchillo extends Barras{ constructor(x,y){ super(x,y) this.width = 90 this.height = 20 this.img=new Image() this.img.src= "../images/cuchillo.png" this.img.onload = () => { this.draw } } }
import { properties } from "../attrs"; import personel from "../personel"; import SimCreate from "./components/SimCreate"; import jenis_pengajuan_sim from "../jenis_pengajuan_sim"; import gol_sim from "../gol_sim"; import SimList from "./components/SimList"; import SimEdit from "./components/SimEdit"; const fields = { id: { source: "id", label: "Id" }, jenis_pengajuan_sim: { source: jenis_pengajuan_sim.identities.name + "_id", label: jenis_pengajuan_sim.identities.options.label, reference: jenis_pengajuan_sim.identities.name, sort: { field: jenis_pengajuan_sim.fields.id.source, order: "ASC" } }, gol_sim: { source: gol_sim.identities.name + "_id", label: gol_sim.identities.options.label, reference: gol_sim.identities.name, sort: { field: gol_sim.fields.id.source, order: "ASC" } }, personel: { ...personel.fields("personel") }, created: { source: "created", label: "Dibuat pada" }, berlaku_hingga: { source: "berlaku_hingga", label: "Berlaku Hingga" }, personel_id: { source: "personel_id", reference: "personel", label: "Personel" }, penyelenggara: { source: "penyelenggara_id", reference: "penyelenggara", label: "Penyelenggara" } }; const identities = { name: "sim", options: { label: "SIM" }, create: SimCreate, list: SimList, edit: SimEdit }; const components = { create: { title: properties.create + identities.options.label }, edit: { title: properties.edit + identities.options.label }, list: { title: properties.list + identities.options.label, sort: { field: fields.id.source, order: "ASC" } } }; export default { identities, fields, components };
/Users/jezrel_mx/Documents/Titanium_Studio_Workspace/ejemplo 1/Resources/app.js
export * as PhoneBookAction from './PhoneBook-action'; export * as PhoneBookOperations from './PhoneBook-operations'; export * as PhoneBookSelectors from './PhoneBook-selectors';
var server = require('net').createServer(); var port = 8081; // The next line sets the on to listen and it therefore will listen on port 8081 server.on('listening', function() { console.log('Server is listening on port', port); }); // The next line sets the on to connect and to receive the socket object server.on('connection', function(socket) { console.log('Server has a new connection'); socket.end(); server.close(); }); // The next line sets the on to close the connection server.on('close', function() { console.log('Server is now closed'); }); // The next handles any error that occur at server level e.g trying to use a port // that is already in use. server.on('error', function(errorreceived) { console.log('Error occurred:', errorreceived.message); }); server.listen(port)
import {UserRbacFactory} from "../../src/services/RbacService"; const mongoHandler = require('../utils/mongo-handler'); import { initAdminRole, initOperatorRole, initSupervisorRole, initPermissions, initRootUser, initSupervisorUser, initOperatorUser } from "../../src/services/InitService"; import UserResolvers from "../../src/graphql/resolvers/UserResolvers"; import {findUserByUsername} from "../../src/services/UserService"; import {findRoleByName} from "../../src/services/RoleService"; describe("UserDeleteResolver", () => { beforeAll(async () => { await mongoHandler.connect() await initPermissions() await initAdminRole() await initOperatorRole() await initSupervisorRole() await initRootUser() await initSupervisorUser() await initOperatorUser() }); afterAll(async () => { await mongoHandler.clearDatabase(); await mongoHandler.closeDatabase(); }) test('DeleteUserBySupervisorWithoutChildRoleNotAuthorized', async () => { const authUser = await findUserByUsername("supervisor") const userToDelete = await findUserByUsername("root") const rbac = await UserRbacFactory(authUser) await expect(() => UserResolvers.Mutation.deleteUser(null, { id: userToDelete.id}, {user: authUser, rbac}) ) .rejects.toThrow('Not Authorized') }); test('DeleteUserByOperatorWhitoutPermissionNotAuthorized', async () => { const authUser = await findUserByUsername("operator") const userToDelete = await findUserByUsername("operator") const rbac = await UserRbacFactory(authUser) await expect(() => UserResolvers.Mutation.deleteUser(null, { id: userToDelete.id}, {user: authUser, rbac})) .rejects.toThrow('Not Authorized') }); test('DeleteUserBySupervisorWithChildRole', async () => { const authUser = await findUserByUsername("supervisor") const userToDelete = await findUserByUsername("operator") const rbac = await UserRbacFactory(authUser) const userDeleted = await UserResolvers.Mutation.deleteUser(null, { id: userToDelete.id}, {user: authUser, rbac}) expect(userDeleted).toHaveProperty('success', true) }); test('DeleteUserByAdmin', async () => { const authUser = await findUserByUsername("root") const userToDelete = await findUserByUsername("supervisor") const rbac = await UserRbacFactory(authUser) const userDeleted = await UserResolvers.Mutation.deleteUser(null, { id: userToDelete.id}, {user: authUser, rbac}) expect(userDeleted).toHaveProperty('success', true) }); })
import withSplitting from 'lib/withSplitting'; export const EditorView = withSplitting(() => import('./EditorView'));
var express = require('express'); var router = express.Router(); var items = require('../controllers/cart'); router.get('/', items.list); router.get("/new", items.newPage); router.get("/:id/edit", items.getEdit); router.post("/", items.new); router.put("/:id", items.editPost); router.delete("/:id", items.deletePost); module.exports = router;
import React, {useState, useEffect} from 'react' import {ApiService} from '../../../services/apiService' import { connect } from "react-redux"; import { withRouter } from "react-router-dom"; import { setProduct } from "../../../redux/actions"; const symbolMainAssets = { 'BTCTRY' : 'BTC', 'BTCUSDT' : 'BTC', 'ETHTRY' : 'ETH', 'ETHBTC' : 'ETH', 'XRPTRY' : 'XRP', 'XRPBTC' : 'XRP', 'LTCTRY' : 'LTC', 'LTCBTC' : 'LTC', 'USDTTRY' : 'USDT', 'XRPUSDT' : 'XRP', 'LTCUSDT' : 'LTC', 'ETHUSDT' : 'ETH' } const symbolSecondAssets = { 'BTCTRY' : 'TRY', 'BTCUSDT' : 'USDT', 'ETHTRY' : 'TRY', 'ETHBTC' : 'BTC', 'XRPTRY' : 'TRY', 'XRPBTC' : 'BTC', 'LTCTRY' : 'TRY', 'LTCBTC' : 'BTC', 'USDTTRY' : 'TRY', 'XRPUSDT' : 'USDT', 'LTCUSDT' : 'USDT', 'ETHUSDT' : 'USDT' } const AssetsDesktop = (props) => { let walletData; let user; let api; let GetMainAsset = symbolMainAssets[props.product]; let GetSecondAsset = symbolSecondAssets[props.product]; const [assetsData,setAssetsData] = useState([]); async function getWallet() { api = new ApiService(); if(await api.isLoggedin()) { user = await api.authService.getUser(); walletData = await api.callApi('wallet/GetMyWallets'); let dataAppendString = '' for (let index = 0; index < walletData.data.length; index++) { if(GetMainAsset === walletData.data[index].asset || GetSecondAsset === walletData.data[index].asset){ dataAppendString += '<div className="ml-4"> <p> Kullanılabilir '+walletData.data[index].asset+': '+walletData.data[index].amount+'</p>'; } } setAssetsData(<div className="ml-4" dangerouslySetInnerHTML={{ __html:dataAppendString}}></div>); } else { setAssetsData(<div className="ml-4"> <p>Lütfen Giriş Yapın</p> </div>); } } async function getWalletUpdate() { api = new ApiService(); if(await api.isLoggedin()) { user = await api.authService.getUser(); walletData = await api.callApi('wallet/GetMyWallets'); let dataAppendString = '' for (let index = 0; index < walletData.data.length; index++) { if(GetMainAsset === walletData.data[index].asset || GetSecondAsset === walletData.data[index].asset){ dataAppendString += '<div className="ml-4"> <p> Kullanılabilir '+walletData.data[index].asset+': '+walletData.data[index].amount+'</p>'; } } setAssetsData(<div className="ml-4" dangerouslySetInnerHTML={{ __html:dataAppendString}}></div>); } else { setAssetsData(<div className="ml-4"> <p>Lütfen Giriş Yapın</p> </div>); } } useEffect( () => { getWallet(); return () => { }; }, [props.product]); useEffect( () => { const timer = setTimeout(() => { getWalletUpdate() }, 5000); return () => clearTimeout(timer); }, [assetsData]); return ( <div className="tab-content"> <ul className="nav nav-tabs"> <li role="presentation"> <a href="#history" className="active" data-toggle="tab" > Varlıklarım </a> </li> </ul> <div role="tabpanel" className="tab-pane active" id="history" style={{ maxHeight: "300px"}} > <div> <div className="crypt-boxed-area"> <div className="no-gutters" style={{minHeight:"200px"}}> <div className="row"> <div className="col ml-4 mt-3" style={{paddingRight:"15px"}}> <a href='https://myaccount.tomya.com/cuzdanim/yatirma' target="_blank" rel="noopener noreferrer"> <button style={{width:"100%", background:"#f7614e"}} className="percent-btn">Yatırım</button> </a> </div> <div className="col mr-4 mt-3" style={{paddingRight:"15px"}}> <a href='https://myaccount.tomya.com/cuzdanim/cekme' target="_blank" rel="noopener noreferrer"> <button style={{width:"100%", background:"#49c279"}} className="percent-btn">Çekim</button> </a> </div> </div> {assetsData} </div> </div> </div> </div> </div> ) } const mapStateToProps = (state) => { return { product: state.testRedux.product, }; }; const mapDispatchToProps = (dispatch) => ({ setProduct: (payload) => dispatch(setProduct(payload)), }); export default withRouter( connect(mapStateToProps, mapDispatchToProps)(AssetsDesktop) );
import React, { Component } from 'react'; import { StyleSheet, Text, View, Modal, Button, Linking, AlertIOS, ScrollView, Dimensions, TouchableHighlight } from 'react-native'; import fonts from '../fonts'; import Font from './Font'; export default class App extends Component { constructor() { super() this.state = { modalVisible: false, font: '' } } openLink = (link) => { console.log(link); Linking.canOpenURL(link).then(supported => { if(supported) { Linking.openURL(link); } else { AlertIOS.alert(`Error opening: ${link}`); } }) } setModalVisible(visible) { this.setState({modalVisible: visible}); } showModal(font) { this.setState({font: font}); this.setModalVisible(true); } render() { let modalStyle; if(this.state.font === 'Zapfino') { modalStyle = { textAlign: 'center', fontFamily: this.state.font, fontSize: 15 } } else { modalStyle = { textAlign: 'center', fontFamily: this.state.font, fontSize: 30 } } return ( <View style={styles.page}> <View style={styles.main}> <Text style={styles.welcome}> React Native fonts on iOS </Text> <Text style={styles.instructions}>Hold down on a font to see more</Text> <View style={styles.fontHolder}> <ScrollView> {fonts.map((font, i) => { return <Font key={i} font={font} onLongPress={this.showModal.bind(this, font)} /> }) } </ScrollView> </View> </View> <View style={styles.footer}> <Text style={styles.footerText}>Coded by <Text style={styles.link} onPress={this.openLink.bind(null, 'https://github.com/dixonscottr')}>Scott</Text> | Inspired by <Text style={styles.link} onPress={this.openLink.bind(null, 'https://github.com/dabit3/react-native-fonts')}> this project</Text> </Text> </View> <Modal animationType={"fade"} transparent={true} visible={this.state.modalVisible}> <View style={styles.modal}> <View style={styles.modalView}> <Text style={styles.modalTitle}> ({this.state.font}) </Text> <Text style={modalStyle}> the quick brown fox jumped over the lazy brown dog </Text> <Text></Text> <Text style={modalStyle}> THE QUICK BROWN FOX JUMPED OVER THE LAZY BROWN DOG </Text> <Button onPress={() => { this.setModalVisible(false) }} title="✕" color="black" > </Button> </View> </View> </Modal> </View> ); } } const styles = StyleSheet.create({ page: { flex: 1, alignItems: 'stretch', backgroundColor: '#880D1E' }, welcome: { fontSize: 22, textAlign: 'center', margin: 10, marginTop: 30, color: 'white', fontFamily: 'System' }, instructions: { textAlign: 'center', fontFamily: 'System', color: 'white' }, main: { flex: 0.95 }, footer: { flex: 0.05, alignItems: 'center', margin: 5 }, footerText: { color: 'white', fontFamily: 'System' }, fontHolder: { margin: 10, backgroundColor: 'white', padding: 10, borderColor: 'black', borderWidth: 1, borderRadius: 9, overflow: 'hidden', flex: 1 }, modal: { flex:1, flexDirection:'row', alignItems:'center', justifyContent:'center', backgroundColor: 'rgba(38, 12, 12, 0.5)' }, modalView: { backgroundColor: 'white', width: 250, padding: 10, borderColor: 'black', borderWidth: 1 }, modalTitle: { textAlign: 'center' } });
({ doInIt : function(component,event) { var action = component.get("c.getUserDetails"); action.setCallback(this, function(response) { var state = response.getState(); if (state === "SUCCESS") { var user = response.getReturnValue(); var salesAlerts = component.get("v.selectedSalesLead"); var atRiskAlerts = component.get("v.selectedAtRiskAlerts"); var retentionAlerts = component.get("v.selectedRetentionAlerts"); var salesAlerts = ["Get to Bronze", "Get to Silver", "Get to Gold","Large Deal"]; var i; var currentSalesAlerts = []; for (i = 0; i < salesAlerts.length; i++) { if(user.Active_NBA_Alerts__c.includes(salesAlerts[i])){ currentSalesAlerts.push(salesAlerts[i]); } console.log('currentSalesAlerts:>>'+currentSalesAlerts); } var atRiskAlerts = ["Practice admin changed", "Spike in CX case volume", "Business plan at risk"]; var i; var currentAtRiskAlerts = []; for (i = 0; i < salesAlerts.length; i++) { if(user.Active_NBA_Alerts__c.includes(atRiskAlerts[i])){ currentAtRiskAlerts.push(atRiskAlerts[i]); } } var retentionAlerts = ["Paying orgs deleted", "Partner dropped a Tier", "Partner is not moving forward on the Partner Journey"]; var i; var currentRetentionAlerts = []; for (i = 0; i < salesAlerts.length; i++) { if(user.Active_NBA_Alerts__c.includes(retentionAlerts[i])){ currentRetentionAlerts.push(retentionAlerts[i]); } } component.set("v.selectedSalesLead", currentSalesAlerts); component.set("v.selectedAtRiskAlerts", currentAtRiskAlerts); component.set("v.selectedRetentionAlerts", currentRetentionAlerts); component.set("v.currentUser", response.getReturnValue()); //component.set("v.isOpen", "true"); }else if (state === "ERROR") { var errors = response.getError(); if (errors) { if (errors[0] && errors[0].message) { console.log("Error message: " + errors[0].message); } } else { console.log("Unknown error"); } } }); $A.enqueueAction(action); }, save : function(component, event, helper) { var salesAlerts = component.get("v.selectedSalesLead"); var atRiskAlerts = component.get("v.selectedAtRiskAlerts"); var retentionAlerts = component.get("v.selectedRetentionAlerts"); var updateUser = false; var allSelectedAlerts = salesAlerts.concat(atRiskAlerts,retentionAlerts); if(allSelectedAlerts.length < 3){ component.set("v.alertMessage","Error: You need to select a minimum of 3 Alerts"); component.set("v.showAlertMessage","TRUE"); updateUser = false; }else{ component.set("v.showAlertMessage","FALSE"); component.set("v.alertMessage",""); updateUser = true; } if(updateUser){ component.set("v.alertMessage",""); var action = component.get("c.updateAlertPreferences"); action.setParams({ "selectedAlerts" : JSON.stringify(allSelectedAlerts) }); action.setCallback(this, function(response) { var state = response.getState(); if (state === "SUCCESS") { //$A.get("e.force:closeQuickAction").fire(); component.set("v.isOpen", "false"); }else if (state === "ERROR") { var errors = response.getError(); if (errors) { if (errors[0] && errors[0].message) { console.log("Error message: " + errors[0].message); } } else { console.log("Unknown error"); } } }); $A.enqueueAction(action); } }, cancel : function(component, event, helper) { // for Hide/Close Model,set the "isOpen" attribute to "Fasle" component.set("v.alertMessage",""); component.set("v.isOpen", false); }, openModal : function(component, event, helper) { // for Open Model,set the "isOpen" attribute to "Fasle" component.set("v.alertMessage",""); component.set("v.isOpen", true); } })
import React from 'react'; export default class Chart extends React.PureComponent { shouldComponentUpdate() { return false; } render() { return ( <svg width={this.props.width} height={this.props.height} > {this.props.children} </svg> ); } } Chart.propTypes = { children: React.PropTypes.element.isRequired, width: React.PropTypes.number, height: React.PropTypes.number, };
import React, {Component} from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import FormGasto from "../animals/FormGasto"; import {Link} from 'react-router-dom' import {Select, Form, message, Divider, Card, List} from 'antd'; import MainLoader from "../../common/Main Loader"; import * as animalGastoActions from '../../../redux/actions/ganado/gastoAnimalActions'; import * as animalActions from '../../../redux/actions/ganado/animalsActions'; import * as lotesActions from '../../../redux/actions/ganado/lotesActions'; import * as pesadasActions from '../../../redux/actions/ganado/pesadasActions'; import * as saleNotesActions from '../../../redux/actions/ganado/salenotesActions'; import FormAnimalLote from '../animals/FormLote'; import { AreteCard } from './AreteCard'; import FormPesada from '../animals/FormPesada'; import FormSalidas from '../animals/FormSalida' const FormItem = Form.Item; const {Option, OptGroup } = Select; class EventosPage extends Component { state = { aretes:[], aretesId:[], areteRancho:'', areteId:'', lote:'', loteId:{ animals:[] }, modo:'', loading:false, multiple:[], mIds:[] }; handleSearch=(a)=>{ //let basePath = 'http://localhost:8000/api/ganado/animals/?q='; let basePath = 'https://rancho.davidzavala.me/api/ganado/animals/?q='; let url = basePath+a; this.props.animalActions.getAnimals(url); }; handleChange=(a)=>{ //let basePath = 'https://rancho.davidzavala.me/api/ganado/animals/?q='; this.setState({areteRancho:a}); }; deleteFromMultiple=(a)=>{ let {mIds} = this.state; mIds = mIds.filter(i=>{return i.arete_siniga!== a}) this.setState({mIds}) } onSelectLote=(value, b)=>{ this.setState({lote:value}) }; saveId=(id)=>{ this.setState({areteId:id}); }; saveIds=(id)=>{ let {mIds}=this.state; mIds.push(id) this.setState({mIds}); }; saveLoteId=(id)=>{ this.setState({loteId:id}); }; handleSearchLote=(a)=>{ let basePath = 'https://rancho.davidzavala.me/api/ganado/lotes/?q='; let url = basePath+a; this.props.lotesActions.getLotes(url); }; handleChangeLote=(a)=>{ //let basePath = 'https://rancho.davidzavala.me/api/ganado/animals/?q='; this.setState({lote:a}); }; handleMultiple=(a)=>{ this.setState({multiple:a}); } //sale Notes functions saveSalida=(sn)=>{ let {modo, mIds, loteId, areteId} = this.state sn['animals_id'] = []; if(modo==='individual'){ sn.animals_id.push(areteId.id) //this.props.animalActions.editAnimal({id:areteId.id,status:false, lote_id:null,lote:null}) }else if(modo==='multiple'){ for(let j in mIds){ sn.animals_id.push(mIds[j].id) //this.props.animalActions.editAnimal({id:mIds[j].id,status:false, lote_id:null, lote:null}) } }else if(modo==='lote'){ for(let i in loteId.animals){ sn.animals_id.push(loteId.animals[i].id) //this.props.animalActions.editAnimal({id:loteId.animals[i].id,status:false, lote_id:null, lote:null}) } } console.log(sn) this.props.saleNotesActions.newSaleNote(sn) .then(r=>{ for(let j in sn.animals_id){ console.log(sn.animals_id[j]) this.props.animalActions.editAnimal({id:sn.animals_id[j],status:false}) .then(r=>{console.log(r)}) .catch(e=>{console.log(e.response)}) } message.success('Nota creada con éxito'); this.setState({areteRancho:'', areteId:'', modo:''}); }).catch(e=>{ console.log(e.response) for (let i in e.response.data){ message.error(e.response.data[i]) } }) }; saveGasto=(gasto)=>{ gasto['animal'] = this.state.areteId.id; this.props.animalGastoActions.saveAnimalGasto(gasto) .then(r=>{ message.success('Gasto agregado con éxito'); this.setState({areteRancho:'', areteId:'', modo:''}); this.handleSearch('') }).catch(e=>{ for (let i in e.response.data){ message.error(e.response.data[i]) } }) }; saveMultiplesGastos=(gasto)=>{ this.setState({loading:true}); let {mIds} = this.state; console.log(mIds) let parcialAmount = gasto.costo/mIds.length; parcialAmount = parcialAmount.toFixed(2); let parcialQuantity = gasto.cantidad/mIds.length; parcialQuantity = parcialQuantity.toFixed(2); for(let i in mIds){ let animalId = mIds[i].id; gasto['animal']=animalId; gasto['costo']=parcialAmount; if(gasto.cantidad)gasto['cantidad']=parcialQuantity; let toSend = Object.assign({}, gasto); this.props.animalGastoActions.saveAnimalGasto(toSend) .then(r=>{ }).catch(e=>{ for (let i in e.response.data){ message.error(e.response.data[i]) } }) } this.setState({loading:false}); message.success('Gasto agregado con éxito') }; saveLoteGastos=(gasto)=>{ this.setState({loading:true}); let {loteId} = this.state; //let keys = this.state.selectedRowKeys; let parcialAmount = gasto.costo/loteId.animals.length; parcialAmount = parcialAmount.toFixed(2); let parcialQuantity = gasto.cantidad/loteId.animals.length; parcialQuantity = parcialQuantity.toFixed(2); for(let i in loteId.animals){ let animalId = loteId.animals[i].id; gasto['animal']=animalId; gasto['costo']=parcialAmount; if(gasto.cantidad)gasto['cantidad']=parcialQuantity; let toSend = Object.assign({}, gasto); this.props.animalGastoActions.saveAnimalGasto(toSend) .then(r=>{ }).catch(e=>{ for (let i in e.response.data){ message.error(e.response.data[i]) } }) } this.setState({loading:false}); message.success('Gasto agregado con éxito') }; changeSingleLote=(animal)=>{ animal['id']= this.state.areteId.id let toSend = Object.assign({}, animal); this.props.animalActions.editAnimal(toSend) .then(r => { message.success('Modificado con éxito'); }).catch(e => { console.log(e) }) }; changeLoteLote=(animal)=>{ let {loteId} = this.state for(let j in loteId.animals){ animal['id']=loteId.animals[j].id; let toSend = Object.assign({}, animal); console.log(toSend) this.props.animalActions.editAnimal(toSend) .then(r => { message.success('Modificado con éxito'); }).catch(e => { for (let i in e.response.data){ message.error(e.response.data[i]) } }) } }; changeMultiplesLote=(animal)=>{ let {mIds} = this.state; for(let j in mIds){ animal['id']=mIds[j].id; let toSend = Object.assign({}, animal); this.props.animalActions.editAnimal(toSend) .then(r => { message.success('Modificado con éxito'); }).catch(e => { console.log(e) //message.error(e.response.data[i]) }) } }; /*pesadas*/ changeSinglePesada=(animal)=>{ animal['animal']= this.state.areteId.id let toSend = Object.assign({}, animal); this.props.pesadasActions.savePesada(toSend) .then(r => { message.success('Modificado con éxito'); }).catch(e => { console.log(e) }) }; changeLotePesada=(animal)=>{ let {loteId} = this.state for(let j in loteId.animals){ animal['animal']=loteId.animals[j].id; let toSend = Object.assign({}, animal); console.log(toSend) this.props.pesadasActions.savePesada(toSend) .then(r => { message.success('Modificado con éxito'); }).catch(e => { for (let i in e.response.data){ message.error(e.response.data[i]) } }) } }; changeMultiplePesada=(animal)=>{ let {mIds} = this.state; for(let j in mIds){ animal['animal']=mIds[j].id; let toSend = Object.assign({}, animal); this.props.pesadasActions.savePesada(toSend) .then(r => { message.success('Modificado con éxito'); }).catch(e => { for (let i in e.response.data){ message.error(e.response.data[i]) } }) } }; handleChangeMode=(a)=>{ //let basePath = 'https://rancho.davidzavala.me/api/ganado/animals/?q='; this.setState({modo:a, mIds:[], areteId:{}, aretes:[], areteRancho:'', areteId:'', lote:'', loteId:{}, multiple:[]}); }; handleChangeEvent=(a)=>{ //let basePath = 'https://rancho.davidzavala.me/api/ganado/animals/?q='; this.setState({event:a}); }; render() { let {fetched, animals, lotes, clients} = this.props; animals = animals.filter(a=>{return a.status === true}) let {modo, loading, event, multiple, areteId, mIds, loteId} = this.state; let displayList = []; let newList = []; modo==='individual'?displayList=[areteId]: modo==='multiple'?displayList=mIds: modo==='lote'?displayList=loteId.animals:displayList=[] console.log(displayList, 'antes del filtro') displayList=displayList?displayList.filter(a=>a.status===true):[] for(let i in displayList){ let animal = animals.find(a=>{return a.id==displayList[i].id}) console.log(animal) } console.log(newList) if(!fetched)return(<MainLoader/>); return ( <div> <div style={{marginBottom:10, color:'rgba(0, 0, 0, 0.65)' }}> Ganado <Divider type="vertical" /> Eventos </div> <div style={{display:'flex', justifyContent:'space-around'}}> <div style={{width:'50%'}}> <h2>Registro de Eventos</h2> <FormItem label={'Modo'}> <Select value={modo} onChange={this.handleChangeMode} style={{width:'100%'}} > <Option value={'individual'}>Individual</Option> <Option value={'lote'}>Por Lote</Option> <Option value={'multiple'}>Multiple</Option> </Select> </FormItem> <FormItem label={'Tipo de Evento'}> <Select value={event} onChange={this.handleChangeEvent} style={{width:'100%'}}> <Option value={'gasto'}>Gasto</Option> <Option value={'reubicacion'}>Reubicación</Option> <Option value={'pesada'}>Pesada</Option> <Option value={'salida'}>Salida</Option> </Select> </FormItem> {modo==='lote'? <FormItem label={'Lote'}> <Select value={this.state.lote} mode="combobox" style={{width:'100%'}} onSelect={this.onSelectLote} onChange={this.handleChangeLote} placeholder="ingresa el nombre del lote" filterOption={true} > {lotes.map((a, key)=><Option value={a.name} key={key}> <div onClick={()=>this.saveLoteId(a)}> <span style={{color:'gray', fontSize:'.8em'}}>Corral: {a.corral.no_corral}</span><br/> <span >Lote: {a.name}</span> </div> </Option>)} </Select> </FormItem>:modo==='individual'? <FormItem label={"Arete"}> <Select value={this.state.areteRancho} mode="combobox" style={{width:'100%'}} onSelect={this.onSelect} onSearch={this.handleSearch} onChange={this.handleChange} placeholder="ingresa el arete de rancho, o siniga para buscarlo" filterOption={false} > {animals.map((a, key)=><Option value={a.arete_siniga} key={key}> <div onClick={()=>this.saveId(a)}> <span style={{color:'gray', fontSize:'.8em'}}>R: {a.arete_rancho}</span><br/> <span >S: {a.arete_siniga}</span> </div> </Option>)} </Select> </FormItem>:modo==='multiple'? <FormItem label="Multiples Aretes"> <Select mode="tags" value={multiple} placeholder="Please select" defaultValue={[]} onSearch={this.handleSearch} onDeselect={this.deleteFromMultiple} onChange={this.handleMultiple} style={{ width: '100%' }} > {animals.map((a, key)=><Option value={a.arete_siniga} key={key}> <div onClick={()=>this.saveIds(a)}> <span>S: {a.arete_siniga}</span><br/> <span style={{color:'gray', fontSize:'.8em'}}>R: {a.arete_rancho}</span> </div> </Option>)} </Select> </FormItem>:'Elige un Modo* '} {event==='gasto'? <FormGasto saveGasto={modo==='individual'?this.saveGasto:modo==='lote'?this.saveLoteGastos:modo==='multiple'?this.saveMultiplesGastos:''}/>: event==='reubicacion'?<FormAnimalLote lotes={lotes} changeLote={modo==='individual'?this.changeSingleLote:modo==='lote'?this.changeLoteLote:modo==='multiple'?this.changeMultiplesLote:''}/>: event==='salida'?<FormSalidas saveSalida={this.saveSalida} clients={clients}/>: event==="pesada"?<FormPesada savePesada={modo==='individual'?this.changeSinglePesada:modo==='lote'?this.changeLotePesada:modo==='multiple'?this.changeMultiplePesada:''}/>:'Elige un Evento*'} </div> <div style={{width:'30%', }}> <Card style={{width:'100%', height:'80vh', overflowY:'scroll'}} title={'Aretes Seleccionados'}> <List itemLayout="horizontal" dataSource={modo==='individual'?[areteId]: modo==='multiple'?mIds: modo==='lote'?loteId.animals?loteId.animals.filter(a=>a.status===true):[]:[]} renderItem={item => ( <List.Item> <List.Item.Meta title={<Link to={`/admin/animals/${item.id}`}>{item.arete_siniga}</Link>} description={<AreteCard {...item}/>} /> </List.Item> )} /> </Card> </div> </div> </div> ); } } function mapStateToProps(state, ownProps) { return { animals:state.animals.list, lotes: state.lotes.list, clients:state.clientes.list, fetched:state.animals.list!==undefined && state.lotes.list!==undefined && state.clientes.list!==undefined } } function mapDispatchToProps(dispatch) { return { animalGastoActions: bindActionCreators(animalGastoActions, dispatch), animalActions:bindActionCreators(animalActions, dispatch), lotesAction:bindActionCreators(lotesActions, dispatch), pesadasActions:bindActionCreators(pesadasActions, dispatch), saleNotesActions:bindActionCreators(saleNotesActions, dispatch), } } EventosPage = connect(mapStateToProps, mapDispatchToProps)(EventosPage); export default EventosPage;
import React from 'react' import PropTypes from 'prop-types' import { Input } from 'antd' import DateRange from '../components/DateRange' import { StyledHeader } from '../styled' import { placeholders } from '../constants' export default function Header ({ onChange, selectedRange }) { const handleSearchChange = (e) => { onChange({ field: 'search', value: e.target.value }) } return ( <StyledHeader> <DateRange selectedRange={selectedRange} handleRangeChange={onChange} /> <Input.Search id="searchInput" placeholder={placeholders.searchText} onChange={handleSearchChange} style={{width: '200px'}} /> </StyledHeader> ) } Header.propTypes = { onChange: PropTypes.func.isRequired, selectedRange: PropTypes.shape({ startValue: PropTypes.object, endValue: PropTypes.object }) }
export const getProfesores = () => ({ type: 'GETPROFESORES' }); export const getProfesor = (profesor) => ({ type: 'GETPROFESOR', payload: { profesor } }); export const saveComment = (comentario, profesor) => ({ type: 'SAVECOMMENT', payload: { comentario, profesor } });
import { cloudwatchevents } from '../lib/aws_clients'; function getJobRuleTargetInputTransformer({ async, exclusive, guid, invocationTarget, invocationType, jobName, payload, schedule, serviceName, ttlSeconds, }) { const inputPathsMap = { // can define a max of 10 of these... id: '$.id', time: '$.time', account: '$.account', region: '$.region', ruleArn: '$.resources[0]', }; const eventParts = Object.keys(inputPathsMap).reduce((parts, key) => { parts.push(`"${key}":<${key}>`); return parts; }, []); let inputTemplate = `"jobExecution":{"event":{${eventParts.join(',')}}},`; inputTemplate += '"jobStatic":{'; inputTemplate += `"async": ${async ? 'true' : 'false'},`; inputTemplate += `"exclusive": ${exclusive ? 'true' : 'false'},`; inputTemplate += `"guid":"${guid}",`; inputTemplate += `"invocationTarget":"${invocationTarget}",`; inputTemplate += `"invocationType":"${invocationType}",`; inputTemplate += `"jobName":"${jobName}",`; inputTemplate += `"key":{"jobName":"${jobName}","serviceName":"${serviceName}"},`; inputTemplate += `"payload":${JSON.stringify(payload)},`; inputTemplate += `"ruleSchedule":"${schedule}",`; inputTemplate += `"serviceName":"${serviceName}",`; inputTemplate += `"ttlSeconds": ${ttlSeconds}`; inputTemplate += '}'; // job inputTemplate = `{${inputTemplate}}`; return { InputPathsMap: inputPathsMap, InputTemplate: inputTemplate, }; } export const makeUpdateJobScheduleTargets = ({ getLogger, iamRoleArnCloudwatchEvents, stateMachineArnExecuteJob, }) => async function updateJobScheduleTargets(ruleName, jobStatic) { const { guid } = jobStatic; const logger = getLogger(); logger.addContext('guid', guid); const inputTemplate = getJobRuleTargetInputTransformer(jobStatic); logger.debug(`InputTransformer: ${JSON.stringify(inputTemplate)}`); const putTargetsResp = await cloudwatchevents.putTargets({ Rule: ruleName, Targets: [ { Id: 'StateMachineQueueJobExecution', Arn: stateMachineArnExecuteJob, RoleArn: iamRoleArnCloudwatchEvents, InputTransformer: inputTemplate, }, ], }).promise(); logger.debug(`putTargets response: ${JSON.stringify(putTargetsResp)}`); if (putTargetsResp.FailedEntryCount > 0) { throw new Error('Failed to putTargets'); } return true; };
import React from "react" import { Box, Container, Grid, Typography } from "@material-ui/core" import { makeStyles } from "@material-ui/core/styles" import GridColorBar from "./../components/GridColorBar" import Layout from "./../components/layout" import Section from "./../components/Section" import BackgroundVideo from "./../images/background-video.mp4" const useStyles = makeStyles(theme => ({ video: { position: "fixed", left: 0, bottom: 0, minWidth: "100%", minHeight: "100%", zIndex: -4, }, title: { display: "inline-block", }, textContent: {}, })) const AboutPage = () => { const classes = useStyles() return ( <Layout> <video className={classes.video} autoplay="true" muted={true} loop={true}> <source type="video/mp4" src={BackgroundVideo} /> </video> <Section> <Container> <Typography color="textPrimary" component="div"> <Typography className={classes.title} variant="h2"> About <GridColorBar /> </Typography> <Box clone py={7}> <Typography variant="h1"> Building Top Level Technology <br /> <Box component="span" fontWeight={300}> For Lenders and Brokers </Box> </Typography> </Box> <Typography> Celesto Technology, Inc. was founded in March of 2002 by a group of highly sought-after and experienced internet marketing professionals. Today we continue their legacy by merging superb business sense with world class design & development from our highly skilled team. Each one of us brings years of experience to the table for your business or organization to use. Our designers are always ahead of the curve when it comes to trends, sometimes even setting trends of their own. The development team consists of people who are obsessed with what they do; they spend a majority of their free time building their skills even more and making sure that they are always inline with the most recent tools and techniques. Everyone at Celesto has dedicated their lives to developing a better brand identity for you, in print and on the web. </Typography> </Typography> </Container> </Section> </Layout> ) } export default AboutPage
$(function() { /* * @author huangyi * @memberOf {TypeName} * */ var h = $('#link').attr('href'); var hs = h.split('_'); var name = hs[1].split('.')[0]; $('#issueNo').change(function() { var issueNo = $(this).val(); location = "/award/award_" + name + ".htm?issueNo=" + issueNo; }) $('#fromDate').focus(function(){ WdatePicker({onpicking: function(dp){ var date = dp.cal.getDateStr(); var newDate = dp.cal.getNewDateStr(); if(date != newDate){ location.href = "/award/award_" + name + ".htm?issueNo=" + dp.cal.getNewDateStr(); } } }); }); })
import React from "react"; import { MdDone, MdClose } from "react-icons/md"; import { Button, Form } from "react-bootstrap"; export default function EditForm({ parent, text, editToDo, hideEdit, editSubToDo }) { const [value, setValue] = React.useState(text); let updateToDo = (parent, text, newValue, editToDo, editSubToDo) => { editSubToDo ? editSubToDo(parent, text, newValue) : editToDo(text, newValue); hideEdit(false); }; return ( <Form> <Form.Group controlId="addToDo"> <Form.Label>Edit ToDo</Form.Label> <Form.Control className={"editToDo"} type="text" placeholder="Enter new ToDo" value={value} onChange={(event) => setValue(event.target.value)} /> <Form.Text className="text-muted">Modify your ToDo</Form.Text> <Button className={"update"} onClick={() => updateToDo(parent, text, value, editToDo, editSubToDo)} > <MdDone /> </Button> <Button className={"cancel"} variant="danger" onClick={() => hideEdit()} > <MdClose /> </Button> </Form.Group> </Form> ); }
var mongoose = require('./MongoDB.js'), Schema = mongoose.Schema; var AisSchema = new Schema({ AISVersion: {type:Number}, AgeMinutes: {type:Number}, BandFlag: {type:Number}, Callsign: {type:String}, DTE: {type:Number}, Destination: {type:String}, Draught: {type:Number}, ETA: //{type:String},// {type:Date}, ExtraInfo: {type:String}, Heading: {type:Number}, IMO: {type:Number}, Lat: {type:Number}, Length: {type:Number}, LengthBow: {type:Number}, LengthStern: {type:Number}, Lon: {type:Number}, MMSI: {type:Number}, MessageTimestamp: //{type:String},// {type:Date}, Name: {type:String}, PositionAccuracy: {type:Number}, PositionFixType:{type:Number}, RAIMFlag: {type:Number}, RadioStatus: {type:Number}, ReceivedDate: {type:Date},//{type:String}, Regional: {type:Number}, Regional2: {type:Number}, RepeatIndicator: {type:Number}, RoT: {type:Number}, SoG: {type:Number}, Spare: {type:Number}, Spare2: {type:Number}, Status: {type:String}, TimestampUTC: {type:Number}, VesselType: {type:String}, Width: {type:Number}, WidthPort: {type:Number}, WidthStarboard: {type:Number} },{ collection: "ships"}); module.exports = mongoose.model('Ship',AisSchema);
class UserApiData{ constructor() { this.sessionUsers = [] } sendResponse(req,res, apiMethod, defaultResponseCallback){ const response = this.getUserData(req.headers.authorization, apiMethod) if (response) { res.send(response) } else { res.send(defaultResponseCallback()) } } setUserData(token, apiMethod, response) { apiMethod = apiMethod.toUpperCase(); let userSession = this.sessionUsers.find(sess => sess.token === token) if (!userSession) { userSession = { token: token, apiData: [] }; this.sessionUsers.push(userSession) } const apiResponse = userSession.apiData.find(methodData => methodData.method === apiMethod) if (!apiResponse){ userSession.apiData.push({ method: apiMethod, response: response }) }else{ apiResponse.response = response } } getUserData(token, apiMethod){ let userSession = this.sessionUsers.find(sess => sess.token === token.replace('Bearer ','')) if (!userSession) { return null; } const apiResponse = userSession.apiData.find(methodData => methodData.method === apiMethod) return apiResponse ? apiResponse.response : null } clearUserData(token){ this.sessionUsers = this.sessionUsers.filter(sess => sess.token !== token) } } module.exports = new UserApiData();
$(document).ready(function(){ $('#group-stage').removeClass('active'); $('#knockout-stage').addClass('active'); // Get knockout stage matches and bets for the user var round16matches = new Vue({ el: "#round16", data: { matches: [ ] }, methods: { add: function(match){ this.matches.push(match); }, selectBet: function(bet, match, active){ placeBet(bet, match, active); } } }) var quartermatches = new Vue({ el: "#quarter", data: { matches: [ ] }, methods: { add: function(match){ this.matches.push(match); }, selectBet: function(bet, match, active){ placeBet(bet, match, active); } } }) var semimatches = new Vue({ el: "#semi", data: { matches: [ ] }, methods: { add: function(match){ this.matches.push(match); }, selectBet: function(bet, match, active){ placeBet(bet, match, active); } } }) var finalmatch = new Vue({ el: "#final", data: { matches: [ ] }, methods: { add: function(match){ this.matches.push(match); }, selectBet: function(bet, match, active){ placeBet(bet, match, active); } } }) $.getJSON('/api/matches/2', function(data){ $.when(data.forEach(function(obj) { round16matches.add(obj); })).then(() => {location.href='#'+$('#anchor-match').html()}); }); $.getJSON('/api/matches/3', function(data){ $.when(data.forEach(function(obj) { quartermatches.add(obj); })).then(() => {location.href='#'+$('#anchor-match').html()}); }); $.getJSON('/api/matches/4', function(data){ $.when(data.forEach(function(obj) { semimatches.add(obj); })).then(() => {location.href='#'+$('#anchor-match').html()}); }); $.getJSON('/api/matches/5', function(data){ $.when(data.forEach(function(obj) { finalmatch.add(obj); })).then(() => {location.href='#'+$('#anchor-match').html()}); }); }); // Place or replace bet function placeBet(bet, match, active){ // Only if match is accessible if(active){ $.post("/api/placebet", {match: match, bet: bet}, function(response) { if(response){ window.location.href = "/quiniela/knockout?match="+match; } }); } }
import util from './util'; // deepCopy function deepCopy(data) { var t = util.typeOf(data); var o; if (t === 'array') { o = []; } else if (t === 'object') { o = {}; } else { return data; } if (t === 'array') { for (var i = 0; i < data.length; i++) { o.push(deepCopy(data[i])); } } else if (t === 'object') { for (var i in data) { o[i] = deepCopy(data[i]); } } return o; } const operateBtn = function (vm, h, currentRow, operationName, operation, type, permission) { return h('Button', { props: { type: type, size: "small", ghost: true, }, directives: [{ name: "permission", value: permission }], style: { margin: '0 2px' }, on: { 'click': () => { operation(vm, currentRow); } } }, operationName); }; const operateHref = function (vm, h, currentRow, operationName, operation) { return h('a', { on: { 'click': () => { operation(vm, currentRow); } } }, operationName); }; export {deepCopy, operateBtn, operateHref};
import types from 'Actions/types'; import { initialGenreState } from './initialState' const { SET_GENRES, ADD_GENRE } = types; const genres = (state = initialGenreState, action) => { switch (action.type) { case SET_GENRES: return { ...state, genres: action.genres }; break; case ADD_GENRE: return { ...state, genres: [ ...state.genres, action.genre ] }; break; default: return state; } }; export default genres;
export { default } from './simple-dialog'
var locals = { 'env':{ 'database': { dbname:'users', username: 'user1', password: '1234', host: 'localhost' }, 'twilio':{ accountSid: 'AC1166a0e35f94351b7613aa1da30e3c17', authToken: 'bf05e3c2da151f645b089bc952c0db22' } } } module.exports = locals;
// Dependencies import React from 'react' import { graphql } from 'react-apollo' import PropTypes from 'prop-types' import ReactGA from 'react-ga' // Queries import query from '../queries/getWatchlistItemByTitle' // App Components import EmptyList from './EmptyList/EmptyList' import Loader from './Loader/Loader' import WatchlistItemHeader from './WatchlistItem/WatchlistItemHeader' /** * The Watchlist Item component is a higher-order component that simply passes * data into Watchlist Item Header and ListContainer component. */ export default (PassedComponent) => { const WatchListItem = (props) => { if (props.data.loading) { return ( <Loader /> ) } ReactGA.pageview('Watchlist Item') if (!props.data.watchListItemByTitle.episodes) { return ( <React.Fragment> <WatchlistItemHeader {...props.data.watchListItemByTitle} /> <EmptyList message="No episodes to list." /> </React.Fragment> ) } return ( <div className="c-watchlistitem"> <WatchlistItemHeader {...props.data.watchListItemByTitle} /> <PassedComponent episodes={props.data.watchListItemByTitle.episodes} /> </div> ) } /** * Define the property types. * @type {Object} */ WatchListItem.propTypes = { data: PropTypes.object, } /** * Define default values for each property. * @type {Object} */ WatchListItem.defaultProps = { data: { loading: true, episodes: [], watchlistitem: {}, }, } // Append results of the graphQL query to the component properties. return graphql(query, { options: (props) => { const { title } = props.match.params return { fetchPolicy: 'network-only', variables: { title }, } }, })(WatchListItem) }
import { expect, sinon } from '../../test-helper' import positionRepository from '../../../src/domain/repositories/position-repository' import { Newposition } from '../../../src/domain/models/index' describe('Unit | Repository | position-repository', () => { const position = { lastNewposition: 'Mexico', id: 1, } describe('#create', () => { beforeEach(() => { sinon.stub(Newposition, 'create') }) afterEach(() => { Newposition.create.restore() }) it('should call Sequelize Model#create', () => { // given Newposition.create.resolves(position) const positionToCreate = { place: 'Mexico', time: '4 October 1999' } // when const promise = positionRepository.create(positionToCreate) // then return promise.then(res => { expect(Newposition.create).to.have.been.calledWith(positionToCreate) expect(res).to.deep.equal(position) }) }) }) describe('#getAll', () => { const positions = [position] beforeEach(() => { sinon.stub(Newposition, 'findAll').resolves(positions) }) afterEach(() => { Newposition.findAll.restore() }) it('should call Sequelize Model#findAll', () => { // when const promise = positionRepository.getAll() // then return promise.then(res => { expect(Newposition.findAll).to.have.been.calledWith() expect(res).to.deep.equal(positions) }) }) }) })
import React from "react" import { View, Image, ImageBackground, TouchableOpacity, Text, Button, Switch, TextInput, StyleSheet, ScrollView } from "react-native" import Icon from "react-native-vector-icons/FontAwesome" import { CheckBox } from "react-native-elements" import { connect } from "react-redux" import { widthPercentageToDP as wp, heightPercentageToDP as hp } from "react-native-responsive-screen" import { getNavigationScreen } from "@screens" export class Blank extends React.Component { constructor(props) { super(props) this.state = {} } render = () => ( <ScrollView contentContainerStyle={{ flexGrow: 1 }} style={styles.ScrollView_1} > <View style={styles.View_2} /> <TouchableOpacity style={styles.TouchableOpacity_831_1354} onPress={() => this.props.navigation.navigate(getNavigationScreen("791_66")) } > <View style={styles.View_I831_1354_791_37}> <View style={styles.View_I831_1354_791_38}> <Text style={styles.Text_I831_1354_791_38}>PIN</Text> </View> </View> <View style={styles.View_I831_1354_791_39}> <ImageBackground source={{ uri: "https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/f050/9616/fb213d1cd6b31745d25e8f75ffe964fd" }} style={styles.ImageBackground_I831_1354_791_39_280_4541} /> </View> </TouchableOpacity> <TouchableOpacity style={styles.TouchableOpacity_831_1355} onPress={() => this.props.navigation.navigate(getNavigationScreen("791_67")) } > <View style={styles.View_I831_1355_791_41}> <View style={styles.View_I831_1355_791_42}> <Text style={styles.Text_I831_1355_791_42}>Face ID</Text> </View> </View> </TouchableOpacity> <TouchableOpacity style={styles.TouchableOpacity_831_1356} onPress={() => this.props.navigation.navigate(getNavigationScreen("791_67")) } > <View style={styles.View_I831_1356_791_41}> <View style={styles.View_I831_1356_791_42}> <Text style={styles.Text_I831_1356_791_42}>Fingerprint</Text> </View> </View> </TouchableOpacity> <View style={styles.View_831_1405}> <View style={styles.View_I831_1405_654_33}> <View style={styles.View_I831_1405_654_34}> <ImageBackground source={{ uri: "https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/3d59/441b/1eed4ad1a718cb5e2479f01e85da3ad5" }} style={styles.ImageBackground_I831_1405_654_34_280_5123} /> </View> <View style={styles.View_I831_1405_654_35}> <Text style={styles.Text_I831_1405_654_35}>Security</Text> </View> <View style={styles.View_I831_1405_654_36}> <ImageBackground source={{ uri: "https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/f4af/a790/3402b06379130266366e0cc6bde93de6" }} style={styles.ImageBackground_I831_1405_654_36_280_12186} /> </View> </View> </View> <View style={styles.View_831_1583}> <View style={styles.View_I831_1583_217_6977} /> </View> <View style={styles.View_831_1506}> <View style={styles.View_I831_1506_816_137}> <View style={styles.View_I831_1506_816_138}> <Text style={styles.Text_I831_1506_816_138}>9:41</Text> </View> </View> <View style={styles.View_I831_1506_816_139}> <View style={styles.View_I831_1506_816_140}> <View style={styles.View_I831_1506_816_141}> <ImageBackground source={{ uri: "https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/42fe/75df/eee86effef9007e53d20453d65f0d730" }} style={styles.ImageBackground_I831_1506_816_142} /> <ImageBackground source={{ uri: "https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/323b/7a56/3bd8d761d4d553ed17394f5c34643bfe" }} style={styles.ImageBackground_I831_1506_816_145} /> </View> <View style={styles.View_I831_1506_816_146} /> </View> <View style={styles.View_I831_1506_816_147}> <View style={styles.View_I831_1506_816_148} /> <View style={styles.View_I831_1506_816_149} /> <View style={styles.View_I831_1506_816_150} /> <View style={styles.View_I831_1506_816_151} /> </View> <ImageBackground source={{ uri: "https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/6a2b/c9ca/21b52f3f9fca9a68ca91e9ed4afad110" }} style={styles.ImageBackground_I831_1506_816_152} /> </View> </View> </ScrollView> ) } const styles = StyleSheet.create({ ScrollView_1: { backgroundColor: "rgba(255, 255, 255, 1)" }, View_2: { height: hp("111%") }, TouchableOpacity_831_1354: { width: wp("100%"), minWidth: wp("100%"), height: hp("7%"), minHeight: hp("7%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("15%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_I831_1354_791_37: { flexGrow: 1, width: wp("6%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("4%"), top: hp("2%"), backgroundColor: "rgba(0, 0, 0, 0)" }, View_I831_1354_791_38: { width: wp("6%"), minWidth: wp("6%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_I831_1354_791_38: { color: "rgba(13, 14, 15, 1)", fontSize: 11, fontWeight: "500", textAlign: "center", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_I831_1354_791_39: { flexGrow: 1, width: wp("9%"), height: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("87%"), top: hp("1%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, ImageBackground_I831_1354_791_39_280_4541: { flexGrow: 1, width: wp("6%"), height: hp("3%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("1%"), top: hp("1%") }, TouchableOpacity_831_1355: { width: wp("100%"), minWidth: wp("100%"), height: hp("7%"), minHeight: hp("7%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("29%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_I831_1355_791_41: { flexGrow: 1, width: wp("13%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("4%"), top: hp("2%"), backgroundColor: "rgba(0, 0, 0, 0)" }, View_I831_1355_791_42: { width: wp("13%"), minWidth: wp("13%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_I831_1355_791_42: { color: "rgba(13, 14, 15, 1)", fontSize: 11, fontWeight: "500", textAlign: "center", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, TouchableOpacity_831_1356: { width: wp("100%"), minWidth: wp("100%"), height: hp("7%"), minHeight: hp("7%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("22%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_I831_1356_791_41: { flexGrow: 1, width: wp("20%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("4%"), top: hp("2%"), backgroundColor: "rgba(0, 0, 0, 0)" }, View_I831_1356_791_42: { width: wp("20%"), minWidth: wp("20%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_I831_1356_791_42: { color: "rgba(13, 14, 15, 1)", fontSize: 11, fontWeight: "500", textAlign: "center", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_831_1405: { width: wp("100%"), minWidth: wp("100%"), height: hp("9%"), minHeight: hp("9%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("6%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_I831_1405_654_33: { flexGrow: 1, width: wp("91%"), height: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("4%"), top: hp("2%"), backgroundColor: "rgba(0, 0, 0, 0)" }, View_I831_1405_654_34: { width: wp("9%"), minWidth: wp("9%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, ImageBackground_I831_1405_654_34_280_5123: { flexGrow: 1, width: wp("6%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("1%"), top: hp("1%") }, View_I831_1405_654_35: { width: wp("66%"), minWidth: wp("66%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("13%"), top: hp("0%"), justifyContent: "center" }, Text_I831_1405_654_35: { color: "rgba(33, 35, 37, 1)", fontSize: 14, fontWeight: "400", textAlign: "center", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_I831_1405_654_36: { width: wp("9%"), minWidth: wp("9%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("83%"), top: hp("0%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, ImageBackground_I831_1405_654_36_280_12186: { flexGrow: 1, width: wp("6%"), height: hp("3%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("1%"), top: hp("1%") }, View_831_1583: { width: wp("100%"), minWidth: wp("100%"), height: hp("5%"), minHeight: hp("5%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("106%"), backgroundColor: "rgba(0, 0, 0, 0)" }, View_I831_1583_217_6977: { flexGrow: 1, width: wp("36%"), height: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("32%"), top: hp("3%"), backgroundColor: "rgba(0, 0, 0, 1)" }, View_831_1506: { width: wp("100%"), minWidth: wp("100%"), height: hp("6%"), minHeight: hp("6%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_I831_1506_816_137: { flexGrow: 1, width: wp("14%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("5%"), top: hp("2%") }, View_I831_1506_816_138: { width: wp("14%"), minWidth: wp("14%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_I831_1506_816_138: { color: "rgba(22, 23, 25, 1)", fontSize: 12, fontWeight: "400", textAlign: "center", fontStyle: "normal", letterSpacing: -0.16500000655651093, textTransform: "none" }, View_I831_1506_816_139: { flexGrow: 1, width: wp("18%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("78%"), top: hp("2%") }, View_I831_1506_816_140: { width: wp("7%"), minWidth: wp("7%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("11%"), top: hp("0%") }, View_I831_1506_816_141: { width: wp("7%"), height: hp("2%"), top: hp("0%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%") }, ImageBackground_I831_1506_816_142: { width: wp("6%"), minWidth: wp("6%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, ImageBackground_I831_1506_816_145: { width: wp("0%"), minWidth: wp("0%"), height: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("6%"), top: hp("1%") }, View_I831_1506_816_146: { width: wp("5%"), minWidth: wp("5%"), height: hp("1%"), minHeight: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("1%"), top: hp("0%"), backgroundColor: "rgba(22, 23, 25, 1)", borderColor: "rgba(76, 217, 100, 1)", borderWidth: 1 }, View_I831_1506_816_147: { width: wp("5%"), height: hp("1%"), top: hp("0%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%") }, View_I831_1506_816_148: { width: wp("1%"), minWidth: wp("1%"), height: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("1%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_I831_1506_816_149: { width: wp("1%"), minWidth: wp("1%"), height: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("1%"), top: hp("1%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_I831_1506_816_150: { width: wp("1%"), minWidth: wp("1%"), height: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("3%"), top: hp("0%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_I831_1506_816_151: { width: wp("1%"), minWidth: wp("1%"), height: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("4%"), top: hp("0%"), backgroundColor: "rgba(255, 255, 255, 1)" }, ImageBackground_I831_1506_816_152: { width: wp("4%"), minWidth: wp("4%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("6%"), top: hp("0%") } }) const mapStateToProps = state => { return {} } const mapDispatchToProps = () => { return {} } export default connect(mapStateToProps, mapDispatchToProps)(Blank)
var express = require("express"); var router = express.Router(); var burger = require("../models/burger.js"); // creating the base route which will render index router.get("/", function(req, res){ burger.selectAll(function(burger_data){ var handlebarsObject = { burgers: burger_data }; console.log(handlebarsObject); res.render("index",handlebarsObject); }); router.post("/api/burgers", function(req, res){ burger.insertOne( ["burger_name", "devoured"], [req.body.burger_name, req.body.devoured], function(result){ // then send back the ID of new burger res.json({ id: result.insertId }); } ); }); router.put("/api/burgers/:id",function(req, res){ var condition = "id " + req.params.id; console.log("condition", condition); burger.updateOne({ devoured: req.body.devoured },condition, function( result ) { if((result. changedRows === 0)) { return res.status(404).end(); } else { res.status(200).end(); } }); }); router.deleteOne(condition, function(req, res){ var condition = "id = " + req.params.id; console.log("condition", condition); burger.deleteOne(condition, function(result){ if((result. changedRows === 0)) { return res.status(404).end(); } else { res.status(200).end(); } }); }); }); // we are having a file call another file and so on module.exports = router;
(function () { "use strict"; describe("SoapInterceptor", function () { var $httpBackend, $rootScope, wsdl, envConfig, soapInterceptor; beforeEach(function () { inject(function (_$injector_) { $httpBackend = _$injector_.get("$httpBackend"); $rootScope = _$injector_.get("$rootScope").$new(); soapInterceptor = _$injector_.get("SoapInterceptor"); wsdl = _$injector_.get("AdminMgmtWSDLMock"); envConfig = _$injector_.get("envConfig"); }); }); describe("setWSDL", function () { beforeEach(function () { spyOn($, "parseXML").and.callFake(function (xml) { return xml; }); }); it("should parse an XML string if not stored", function () { soapInterceptor.setWSDL("http://test.url", "<wsdl:test></wsdl:test>"); expect($.parseXML).toHaveBeenCalledWith("<wsdl:test></wsdl:test>"); }); it("should not store more WSDL files more than once", function () { soapInterceptor._wsdlCache["http://test.url"] = "Not an XML Document"; soapInterceptor.setWSDL("http://test.url", "<wsdl:test></wsdl:test>"); expect(soapInterceptor._wsdlCache["http://test.url"]).toBe("Not an XML Document"); }); }); describe("getSoapRequestParams", function () { var actual; beforeEach(function () { soapInterceptor.setWSDL("/test/url", wsdl); actual = soapInterceptor.getSoapRequestParams("/test/url/soap:method"); }); it("should return an Object", function () { expect(typeof actual).toBe("object"); }); it("should store the wsdl in the returned Object", function () { expect(actual.wsdl).toEqual($.parseXML(wsdl)); }); it("should identify the correct SOAP method", function () { expect(actual.method).toEqual("soap:method"); actual = soapInterceptor.getSoapRequestParams("/test/url?anotherMethod"); expect(actual.method).toEqual("anotherMethod"); }); it("should throw an Error if there's no value stored in the cache", function () { actual = function () { return soapInterceptor.getSoapRequestParams("/missing/url/soap:method"); }; expect(actual).toThrow(new Error("Base URL for provided URL was not found. Please make sure to call the soap interceptor's setWSDL() function before executing SOAP requests. Error in request for: /missing/url/soap:method", "error")); }); }); describe("handleSoapRequest", function () { var actual, fakeWSDL; beforeEach(function () { fakeWSDL = { "documentElement": { "attributes": { targetNamespace: undefined, getNamedItem: function () { return { nodeValue: "http://test/namespace/url" }; }, }, }, }; }); it("should construct use getNamedItem if targetNamespace is not available", function () { spyOn(soapInterceptor, "getSoapRequestParams").and.returnValue({ wsdl: fakeWSDL, }); actual = soapInterceptor.handleSoapRequest({ url: "/test/url/soap:method" }); expect(actual).toEqual({ url: "/test/url/soap:method", soapRequestParams: { wsdl: { documentElement: { attributes: { targetNamespace: undefined, getNamedItem: jasmine.any(Function), }, }, }, }, data: "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:omi=\"http://www.verimatrix.com/omi\" xmlns:omit=\"http://www.verimatrix.com/schemas/OMItypes.xsd\" ><soap:Body><undefined></undefined></soap:Body></soap:Envelope>", headers: { "SOAPAction": "http://test/namespace/url/undefined", "Content-Type": "text/xml; charset=utf-8", }, }); }); it("should look at the attributes.targetNamespace if available", function () { fakeWSDL.documentElement.attributes.targetNamespace = { value: "http://www.verimatrix.com/omi/" }; spyOn(soapInterceptor, "getSoapRequestParams").and.returnValue({ wsdl: fakeWSDL, }); actual = soapInterceptor.handleSoapRequest({ url: "/test/url/soap:method", }); expect(actual).toEqual({ url: "/test/url/soap:method", soapRequestParams: { wsdl: { documentElement: { attributes: { targetNamespace: { value: "http://www.verimatrix.com/omi/", }, getNamedItem: jasmine.any(Function), }, }, }, }, data: "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:omi=\"http://www.verimatrix.com/omi\" xmlns:omit=\"http://www.verimatrix.com/schemas/OMItypes.xsd\" ><soap:Body><undefined></undefined></soap:Body></soap:Envelope>", headers: { "SOAPAction": "http://www.verimatrix.com/omi/undefined", "Content-Type": "text/xml; charset=utf-8", }, }); }); it("should not inject envConfig.schemaHeader values if they're absent", function () { spyOn(soapInterceptor, "getSoapRequestParams").and.returnValue({ wsdl: fakeWSDL, }); envConfig.api.schemaHeaders = {}; actual = soapInterceptor.handleSoapRequest({ url: "/test/url/soap:method", }); expect(actual).toEqual({ url: "/test/url/soap:method", soapRequestParams: { wsdl: { documentElement: { attributes: { targetNamespace: undefined, getNamedItem: jasmine.any(Function), }, }, }, }, data: "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" ><soap:Body><undefined></undefined></soap:Body></soap:Envelope>", headers: { "SOAPAction": "http://test/namespace/url/undefined", "Content-Type": "text/xml; charset=utf-8", }, }); }); }); describe("handleSoapResponse", function () { var actual, response; beforeEach(function () { response = { config: { soapRequestParams: { method: "testMethod", }, }, data: "xml response goes here", }; spyOn(soapInterceptor, "handleSoapResponseError").and.returnValue({"soapResponseError": "value"}); spyOn(soapInterceptor, "soapResultToObject").and.returnValue({"soapResult": "value"}); spyOn($, "parseXML").and.callFake(function (xml) { return xml; }); }); it("should return an Object", function () { spyOn(soapInterceptor, "getElementsByTagName").and.returnValue({ node: "value", }); actual = soapInterceptor.handleSoapResponse(response); expect(typeof actual).toBe("object"); }); it("should check all possible response types when `nd` is an empty string before erroring", function () { spyOn(soapInterceptor, "getElementsByTagName").and.returnValue(""); actual = soapInterceptor.handleSoapResponse(response); expect(actual.data).toEqual({"soapResponseError": "value"}); expect(soapInterceptor.getElementsByTagName.calls.count()).toBe(4); // there are four branches expect(soapInterceptor.getElementsByTagName).toHaveBeenCalledWith("xml response goes here", "testMethodResult"); expect(soapInterceptor.getElementsByTagName).toHaveBeenCalledWith("xml response goes here", "return"); expect(soapInterceptor.getElementsByTagName).toHaveBeenCalledWith("xml response goes here", "testMethodReturn"); expect(soapInterceptor.getElementsByTagName).toHaveBeenCalledWith("xml response goes here", "testMethodResponse"); }); it("should set the response data to the handleSoapResponseError return value if not {method}Result, return, {method}Return, or {method}Response", function () { spyOn(soapInterceptor, "getElementsByTagName").and.returnValue(""); actual = soapInterceptor.handleSoapResponse(response); expect(actual.data).toEqual({"soapResponseError": "value"}); }); }); describe("handleSoapResponseError", function () { var actual; beforeEach(function () { spyOn($, "parseXML").and.callThrough(); }); it("should call parseXML if the response is a string", function () { soapInterceptor.handleSoapResponseError("<test></test>"); expect($.parseXML).toHaveBeenCalledWith("<test></test>"); }); it("should return 'Unknown Response' when it doesn't know what the error is", function () { actual = soapInterceptor.handleSoapResponseError("<test></test>"); expect(actual).toBe("Unknown Error"); }); it("should extract the faultstring when a faultcode is present", function () { actual = soapInterceptor.handleSoapResponseError($.parseXML("<response><faultcode></faultcode>4<faultstring>Error string</faultstring></response>")); expect(actual).toBe("Error string"); }); }); describe("soapSerializeParameter", function () { var actual, proto; describe("when string", function () { it("should return a string", function () { actual = soapInterceptor.soapSerializeParameter("test string"); expect(actual).toBe("test string"); }); it("should escape ampersands", function () { actual = soapInterceptor.soapSerializeParameter("Astair & Rogers"); expect(actual).toBe("Astair &amp; Rogers"); }); it("should escape less than", function () { actual = soapInterceptor.soapSerializeParameter("3 < 4"); expect(actual).toBe("3 &lt; 4"); }); it("should escape greater than", function () { actual = soapInterceptor.soapSerializeParameter("4 > 3"); expect(actual).toBe("4 &gt; 3"); }); it("should escape all", function () { actual = soapInterceptor.soapSerializeParameter("3 < 4 & 4 > 3"); expect(actual).toBe("3 &lt; 4 &amp; 4 &gt; 3"); }); }); describe("when number", function () { beforeEach(function () { proto = Number.prototype; spyOn(proto, "toString").and.callThrough(); }); it("should call toString for INTs", function () { actual = soapInterceptor.soapSerializeParameter(3); expect(proto.toString).toHaveBeenCalled(); expect(actual).toBe("3"); }); it("should call toString for FLOATs", function () { actual = soapInterceptor.soapSerializeParameter(3.14); expect(proto.toString).toHaveBeenCalled(); expect(actual).toBe("3.14"); }); it("should call toString for NaNs", function () { actual = soapInterceptor.soapSerializeParameter(NaN); expect(proto.toString).toHaveBeenCalled(); expect(actual).toBe("NaN"); }); }); describe("when boolean", function () { beforeEach(function () { proto = Boolean.prototype; spyOn(proto, "toString").and.callThrough(); }); it("should call toString for INTs", function () { actual = soapInterceptor.soapSerializeParameter(true); expect(proto.toString).toHaveBeenCalled(); expect(actual).toBe("true"); }); it("should call toString for FLOATs", function () { actual = soapInterceptor.soapSerializeParameter(false); expect(proto.toString).toHaveBeenCalled(); expect(actual).toBe("false"); }); }); describe("when date", function () { var date; beforeEach(function () { date = new Date(); proto = Date.prototype; }); it("should return date as a string", function () { date.setTime(Date.parse("2015/02/23 15:04:42")); actual = soapInterceptor.soapSerializeParameter(date); expect(typeof actual).toBe("string"); }); it("should properly parse the response (first variant)", function () { spyOnDate({ year: 2015, month: 1, date: 23, hours: 15, minutes: 59, seconds: 27, milliseconds: 36, timezone: 480, }); actual = soapInterceptor.soapSerializeParameter(new Date()); expect(actual).toBe("2015-02-23T15:59:27.36-08:00"); }); it("should properly parse the response (second variant)", function () { spyOnDate({ year: 1999, month: 11, date: 3, hours: 6, minutes: 9, seconds: 2, milliseconds: 999, timezone: -623, }); actual = soapInterceptor.soapSerializeParameter(new Date()); expect(actual).toBe("1999-12-03T06:09:02.999+10:23"); }); }); describe("when array", function () { describe("linear", function () { beforeEach(function () { spyOnDate({ year: 2015, month: 1, date: 23, hours: 15, minutes: 59, seconds: 27, milliseconds: 36, timezone: 480, }); }); it("should handle strings", function () { actual = soapInterceptor.soapSerializeParameter(["testing"]); expect(actual).toBe("<string>testing</string>"); }); it("should handle constructors that are anonymous functions", function () { var testParam = (function () { var self; // Because PhantomJS tests this scenario a *little* differently // than the browser does, and because we don't want to assume // that `this` is actually defined anywhere, we capture undefined // `this` and create an object stored as `self`. If it *is* // defined, it gets stored in a `self` variable. if (angular.isUndefined(this)) { self = {}; } else { self = this; } self.constructor = function () {}; return self; }()); actual = soapInterceptor.soapSerializeParameter([testParam]); expect(actual).toBe("<string><constructor></constructor></string>"); }); it("should handle numbers", function () { actual = soapInterceptor.soapSerializeParameter([10, 20]); expect(actual).toBe("<int>10</int><int>20</int>"); }); it("should handle booleans", function () { actual = soapInterceptor.soapSerializeParameter([true, false]); expect(actual).toBe("<bool>true</bool><bool>false</bool>"); }); it("should handle dates", function () { actual = soapInterceptor.soapSerializeParameter([new Date()]); // Date is stubbed, so it doesn't matter, so long as it's a Date instance expect(actual).toBe("<DateTime>2015-02-23T15:59:27.36-08:00</DateTime>"); }); it("should handle mixed arrays", function () { actual = soapInterceptor.soapSerializeParameter(["testing", 42, false, new Date()]); // Date is stubbed, so it doesn't matter, so long as it's a Date instance expect(actual).toBe("<string>testing</string><int>42</int><bool>false</bool><DateTime>2015-02-23T15:59:27.36-08:00</DateTime>"); }); }); describe("associative", function () { it("should set the propert and value", function () { var testArray = []; testArray.string = "This is a test string"; actual = soapInterceptor.soapSerializeParameter(testArray); expect(actual).toBe("<string>This is a test string</string>"); }); }); }); describe("when non-date and non-array object", function () { it("should return the object with nested properties", function () { actual = soapInterceptor.soapSerializeParameter({ testProp: "Test Value", childProps: { nestedProp: "Nested Value", }, }); expect(actual).toBe("<testProp>Test Value</testProp><childProps><nestedProp>Nested Value</nestedProp></childProps>"); }); it("should return the object with nested properties", function () { actual = soapInterceptor.soapSerializeParameter({ testProp: "Test Value", childProps: { nestedProp: "Nested Value", }, }); expect(actual).toBe("<testProp>Test Value</testProp><childProps><nestedProp>Nested Value</nestedProp></childProps>"); }); }); it("should convert Array of objects to a series of parameters with the same name", function () { // make sure that arrays of items are left alone actual = soapInterceptor.soapSerializeParameter({ arrayProp: ["test", "test", "test"] }); expect(actual).toBe("<arrayProp><string>test</string><string>test</string><string>test</string></arrayProp>"); // Test the behavior we're actually looking for: actual = soapInterceptor.soapSerializeParameter({ arrayProp: [{ id: "childProp1", }, { id: "childProp2", }, { id: "childProp3", }], }); expect(actual).toBe("<arrayProp><id>childProp1</id></arrayProp><arrayProp><id>childProp2</id></arrayProp><arrayProp><id>childProp3</id></arrayProp>"); }); it("should handled nested Arrays of objects", function () { // Test the behavior we're actually looking for: actual = soapInterceptor.soapSerializeParameter({ parentProp: { arrayProp: [{ id: "childProp1", }, { id: "childProp2", }, { id: "childProp3", }], } }); expect(actual).toBe("<parentProp><arrayProp><id>childProp1</id></arrayProp><arrayProp><id>childProp2</id></arrayProp><arrayProp><id>childProp3</id></arrayProp></parentProp>"); actual = soapInterceptor.soapSerializeParameter({ parentArrayProp: [{ arrayProp1: [{ id: "childProp1", }, { id: "childProp2", }, { id: "childProp3", }], },{ arrayProp2: [{ id: "childProp4", }, { id: "childProp5", }, { id: "childProp6", }], }], }); expect(actual).toBe("<parentArrayProp><arrayProp1><id>childProp1</id></arrayProp1><arrayProp1><id>childProp2</id></arrayProp1><arrayProp1><id>childProp3</id></arrayProp1></parentArrayProp><parentArrayProp><arrayProp2><id>childProp4</id></arrayProp2><arrayProp2><id>childProp5</id></arrayProp2><arrayProp2><id>childProp6</id></arrayProp2></parentArrayProp>"); }); function spyOnDate(params) { // spy on the methods, fake the responses spyOn(proto, "getFullYear").and.returnValue(params.year); spyOn(proto, "getMonth").and.returnValue(params.month); // remember, this is zero-indexed spyOn(proto, "getDate").and.returnValue(params.date); spyOn(proto, "getHours").and.returnValue(params.hours); spyOn(proto, "getMinutes").and.returnValue(params.minutes); spyOn(proto, "getSeconds").and.returnValue(params.seconds); spyOn(proto, "getMilliseconds").and.returnValue(params.milliseconds); spyOn(proto, "getTimezoneOffset").and.returnValue(params.timezone); } }); describe("soapSerializeNamespaces", function () { var actual, namespaces; beforeEach(function () { namespaces = { "test": "http://test/namespace/definition/url", "local": "/a/local/path", }; }); it("should return an empty string when no namespaces", function () { expect(soapInterceptor.soapSerializeNamespaces()).toBe(""); expect(soapInterceptor.soapSerializeNamespaces({})).toBe(""); }); it("should serialize the namespace and the URL for the namespace definition", function () { actual = soapInterceptor.soapSerializeNamespaces(namespaces); expect(actual).toBe("xmlns:test=\"" + namespaces.test + "\" xmlns:local=\"" + namespaces.local + "\" "); }); it("should ignore namespaces with missing values", function () { namespaces.emptyValue = ""; namespaces.undefValue = undefined; namespaces.nullValue = null; namespaces.falseValue = false; actual = soapInterceptor.soapSerializeNamespaces(namespaces); expect(actual).toBe("xmlns:test=\"" + namespaces.test + "\" xmlns:local=\"" + namespaces.local + "\" "); }); }); describe("getElementsByTagName", function () { var doc; describe("via selectNodes", function () { beforeEach(function () { doc = { selectNodes: jasmine.createSpy("document.selectNodes") }; }); it("should call the selectNodes method", function () { soapInterceptor.getElementsByTagName(doc, "result"); expect(doc.selectNodes).toHaveBeenCalledWith(".//*[local-name()=\"result\"]"); }); }); describe("via getElementsByTagName", function () { beforeEach(function () { doc = { selectNodes: jasmine.createSpy("document.selectNodes").and.callFake(function () { throw new Error(); }), getElementsByTagNameNS: jasmine.createSpy("document.getElementsByTagNameNS") }; }); it("should call the getElementsByTagName method when an exception is thrown", function () { envConfig.api.schemaHeaders.omi = "omi namespace uri"; soapInterceptor.getElementsByTagName(doc, "result"); expect(doc.selectNodes).toHaveBeenCalledWith(".//*[local-name()=\"result\"]"); expect(doc.getElementsByTagNameNS).toHaveBeenCalledWith(envConfig.api.schemaHeaders.omi, "result"); }); }); }); describe("soapResultToObject", function () { beforeEach(function () { spyOn(soapInterceptor, "getTypesFromWSDL").and.returnValue({ "type1": "testWSDLType" }); spyOn(soapInterceptor, "nodeToObject").and.returnValue({ "nodeObject": "testObject" }); soapInterceptor.soapResultToObject("node", "wsdl"); }); it("should call getTypesFromWSDL with the WSDL value", function () { expect(soapInterceptor.getTypesFromWSDL).toHaveBeenCalledWith("wsdl"); }); it("should call nodeToObject with the response of getTypesFromWSDL and the node", function () { expect(soapInterceptor.nodeToObject).toHaveBeenCalledWith("node", { "type1": "testWSDLType" }); }); }); describe("nodeToObject", function () { var wsdlTypes; beforeEach(function () { wsdlTypes = { "string": "s:string", "boolean": "s:boolean", "int": "s:int", "long": "s:long", "double": "s:double", "datetime": "s:datetime", }; spyOn(soapInterceptor, "extractValue").and.callThrough(); }); it("should return null if node is null", function () { var actual = soapInterceptor.nodeToObject(null, wsdlTypes); expect(actual).toBe(null); }); it("should extractValue from text nodes (types 3 and 4)", function () { var node = { nodeType: 3, nodeValue: "nodeValue", parentNode: { nodeName: "string", }, childNodes: [], hasChildNodes: jasmine.createSpy("hasChildNodes").and.returnValue(false), }; // Type 3: text soapInterceptor.nodeToObject(node, wsdlTypes); expect(soapInterceptor.extractValue).toHaveBeenCalledWith(node, wsdlTypes); // Type 4: also text soapInterceptor.extractValue.calls.reset(); node.nodeType = 4; soapInterceptor.nodeToObject(node, wsdlTypes); expect(soapInterceptor.extractValue).toHaveBeenCalledWith(node, wsdlTypes); // Type 5: not text soapInterceptor.extractValue.calls.reset(); node.nodeType = 5; soapInterceptor.nodeToObject(node, wsdlTypes); expect(soapInterceptor.extractValue).not.toHaveBeenCalled(); }); it("should extractValue from child text nodes (types 3 and 4)", function () { var node, childNode, siblingNode; node = { nodeType: 0, childNodes: [], hasChildNodes: jasmine.createSpy("hasChildNodes").and.returnValue(true), parentNode: { nodeName: "string", }, }; childNode = { nodeName: "testElement", nodeType: 3, childNodes: [], hasChildNodes: jasmine.createSpy("hasChildNodes").and.returnValue(false), parentNode: { nodeName: "string", }, }; siblingNode = { nodeName: "ns:anotherTestElement", nodeType: 4, childNodes: [], hasChildNodes: jasmine.createSpy("hasChildNodes").and.returnValue(false), parentNode: { nodeName: "string", }, }; node.childNodes.push(childNode); node.childNodes.push(siblingNode); // Type 3: text soapInterceptor.nodeToObject(node, wsdlTypes); expect(soapInterceptor.extractValue).toHaveBeenCalledWith(childNode, wsdlTypes); // Type 4: also text soapInterceptor.extractValue.calls.reset(); node.childNodes = []; childNode.nodeType = 4; node.childNodes.push(childNode); soapInterceptor.nodeToObject(node, wsdlTypes); expect(soapInterceptor.extractValue).toHaveBeenCalledWith(childNode, wsdlTypes); // Type 5: not text soapInterceptor.extractValue.calls.reset(); node.childNodes = []; childNode.nodeType = 5; node.childNodes.push(childNode); soapInterceptor.nodeToObject(node, wsdlTypes); expect(soapInterceptor.extractValue).not.toHaveBeenCalled(); }); it("should properly parse nodeName properties for object nodes", function () { var node, actual; node = { nodeType: 3, nodeName: "string", nodeValue: "nodeValue", childNodes: [], hasChildNodes: jasmine.createSpy("hasChildNodes").and.returnValue(true), parentNode: { nodeName: "string", }, }; node.childNodes.push({ nodeType: 3, nodeName: "string", nodeValue: "nodeValue", childNodes: [], hasChildNodes: jasmine.createSpy("hasChildNodes").and.returnValue(false), parentNode: { nodeName: node.nodeName, }, }); // Type 3: text actual = soapInterceptor.nodeToObject(node, wsdlTypes); expect(actual).toBe("nodeValue"); // Type 4: also text node.nodeValue = "test:prefixedValue"; node.nodeType = 4; node.childNodes[0].nodeName = "test:childNode"; actual = soapInterceptor.nodeToObject(node, wsdlTypes); expect(actual).toBe("test:prefixedValue"); }); it("should handle multiple nodes with the same nodeName", function () { var actual, xml; xml = "<parentNode>"; xml += "<childNode><value>Child Node 1</value></childNode>"; xml += "<childNode><value>Child Node 2</value></childNode>"; xml += "<childNode><value>Child Node 3</value></childNode>"; xml += "</parentNode>"; xml = $.parseXML(xml); actual = soapInterceptor.nodeToObject(xml, wsdlTypes); expect(actual).toEqual({ parentNode: { childNode: [{ value: "Child Node 1", }, { value: "Child Node 2", }, { value: "Child Node 3", }], }, }); }); describe("when array", function () { beforeEach(function () { spyOn(soapInterceptor, "getTypeFromWSDL").and.returnValue("ArrayOf"); }); it("should iterate through the child nodes", function () { expect(soapInterceptor.nodeToObject({ hasChildNodes: jasmine.createSpy("hasChildNodes").and.returnValue(true), childNodes: [{ childNodes: [], hasChildNodes: jasmine.createSpy("hasChildNodes").and.returnValue(false), }], }, wsdlTypes)).toEqual([[]]); }); }); }); describe("extractValue", function () { var wsdlTypes; beforeEach(function () { wsdlTypes = { "string": "s:string", "boolean": "s:boolean", "int": "s:int", "long": "s:long", "double": "s:double", "datetime": "s:datetime", }; }); describe("type: boolean", function () { it("should return a boolean when the type is boolean", function () { var actual = soapInterceptor.extractValue(mockNode("boolean", "false"), wsdlTypes); expect(typeof actual).toBe("boolean"); actual = soapInterceptor.extractValue(mockNode("boolean", "true"), wsdlTypes); expect(actual).toBe(true); actual = soapInterceptor.extractValue(mockNode("boolean", "false"), wsdlTypes); expect(actual).toBe(false); }); }); describe("type: string", function () { it("should return a string", function () { var actual = soapInterceptor.extractValue(mockNode("string"), wsdlTypes); expect(typeof actual).toBe("string"); }); it("should coerce a string", function () { var actual = soapInterceptor.extractValue(mockNode("string", 1000), wsdlTypes); expect(actual).toBe("1000"); }); it("should return '' if value is null", function () { var actual = soapInterceptor.extractValue(mockNode("string", null), wsdlTypes); expect(actual).toBe(""); }); }); describe("type: int", function () { it("should return an integer", function () { var actual = soapInterceptor.extractValue(mockNode("int", "1000"), wsdlTypes); expect(typeof actual).toBe("number"); }); it("should parse integers", function () { var actual = soapInterceptor.extractValue(mockNode("int", "1000"), wsdlTypes); expect(actual).toBe(1000); }); it("should return 0 if value is null", function () { var actual = soapInterceptor.extractValue(mockNode("int", null), wsdlTypes); expect(actual).toBe(0); }); }); describe("type: double", function () { it("should return an integer", function () { var actual = soapInterceptor.extractValue(mockNode("double", "1000"), wsdlTypes); expect(typeof actual).toBe("number"); }); it("should parse integers", function () { var actual = soapInterceptor.extractValue(mockNode("double", "1000"), wsdlTypes); expect(actual).toBe(1000); }); it("should return 0 if value is null", function () { var actual = soapInterceptor.extractValue(mockNode("double", null), wsdlTypes); expect(actual).toBe(0); }); }); describe("type: datetime", function () { it("should return an Date instance", function () { var actual = soapInterceptor.extractValue(mockNode("datetime", "July 1, 2015"), wsdlTypes); expect(actual instanceof Date).toBe(true); }); it("should parse ISO strings", function () { var date, actual, expected; date = "2015-02-22T19:10:11.511Z"; expected = new Date(); expected.setTime(Date.parse("2015/02/22 19:10:11")); actual = soapInterceptor.extractValue(mockNode("datetime", date), wsdlTypes); expect(actual).toEqual(expected); }); it("should return null if value is null", function () { var actual = soapInterceptor.extractValue(mockNode("datetime", null), wsdlTypes); expect(actual).toBe(null); }); }); describe("default", function () { it("should fall through the the string case", function () { var actual; actual = soapInterceptor.extractValue(mockNode("testName", "testValue"), wsdlTypes); expect(actual).toBe("testValue"); actual = soapInterceptor.extractValue(mockNode("testName", 10), wsdlTypes); expect(actual).toBe("10"); actual = soapInterceptor.extractValue(mockNode("testName", null), wsdlTypes); expect(actual).toBe(""); }); }); function mockNode (name, value) { return { nodeValue: value, parentNode: { nodeName: name } }; } }); describe("getTypesFromWSDL", function () { var actual, wsdlXML; beforeEach(function () { wsdlXML = $.parseXML("<testWSDL><childNode>A child node</childNode></testWSDL>"); spyOn(wsdlXML, "getElementsByTagName").and.callThrough(); }); it("should return an Array", function () { actual = soapInterceptor.getTypesFromWSDL(wsdlXML); expect(angular.isArray(actual)).toBe(true); }); it("should look up elements", function () { actual = soapInterceptor.getTypesFromWSDL(wsdlXML); expect(wsdlXML.getElementsByTagName).toHaveBeenCalledWith("s:element"); expect(wsdlXML.getElementsByTagName).toHaveBeenCalledWith("element"); }); describe("IE", function () { var nodeList, _wsdl; beforeEach(function () { nodeList = [{ attributes: { getNamedItem: jasmine.createSpy("getNamedItem").and.callFake(getNamedItem), } }]; _wsdl = _.cloneDeep(wsdlXML); _wsdl.getElementsByTagName = jasmine.createSpy("getElementsByTagName").and.returnValue(nodeList); ////////// function getNamedItem (attr) { if (attr == "name") { return { nodeValue: "itemName", }; } else if (attr == "type") { return { nodeValue: "itemType", }; } else { return false; } } }); it("should use the s:element lookup and not the element lookup", function () { actual = soapInterceptor.getTypesFromWSDL(_wsdl); expect(_wsdl.getElementsByTagName).toHaveBeenCalledWith("s:element"); expect(_wsdl.getElementsByTagName).not.toHaveBeenCalledWith("element"); }); it("should store the retrieved types in an associative Array", function () { actual = soapInterceptor.getTypesFromWSDL(_wsdl); expect(angular.isArray(actual)).toBe(true); expect(actual.hasOwnProperty("itemName")).toBe(true); expect(actual.itemName).toEqual("itemType"); }); it("should not have itemName if there is a missing type", function () { nodeList = [{ attributes: { getNamedItem: jasmine.createSpy("getNamedItem").and.callFake(getNamedItem), } }]; _wsdl.getElementsByTagName = jasmine.createSpy("getElementsByTagName:IE").and.returnValue(nodeList); actual = soapInterceptor.getTypesFromWSDL(_wsdl); expect(angular.isArray(actual)).toBe(true); expect(actual.hasOwnProperty("itemName")).toBe(false); ////////// function getNamedItem (attr) { if (attr == "name") { return { nodeValue: "itemName", }; } else { return false; } } }); }); describe("Everything else", function () { var nodeList, _wsdl; beforeEach(function () { nodeList = [{ attributes: { name: { value: "itemName" }, type: { value: "itemType" }, } }]; _wsdl = _.cloneDeep(wsdlXML); _wsdl.getElementsByTagName = jasmine.createSpy("getElementsByTagName:NonIE").and.callFake(getNodeList); ////////// function getNodeList (name) { if (name == "element") { return nodeList; } else { return []; } } }); it("should use the both s:element lookup AND the element lookup", function () { actual = soapInterceptor.getTypesFromWSDL(_wsdl); expect(_wsdl.getElementsByTagName).toHaveBeenCalledWith("s:element"); expect(_wsdl.getElementsByTagName).toHaveBeenCalledWith("element"); }); it("should store the retrieved types in an associative Array", function () { actual = soapInterceptor.getTypesFromWSDL(_wsdl); expect(angular.isArray(actual)).toBe(true); expect(actual.hasOwnProperty("itemName")).toBe(true); expect(actual.itemName).toEqual("itemType"); }); it("should not have itemName if there is a missing type", function () { nodeList = [{ attributes: { name: { value: "itemName" }, type: "" } }]; actual = soapInterceptor.getTypesFromWSDL(_wsdl); expect(angular.isArray(actual)).toBe(true); expect(actual.hasOwnProperty("itemName")).toBe(false); }); }); }); describe("getTypeFromWSDL", function () { var wsdlTypes; beforeEach(function () { wsdlTypes = []; wsdlTypes.testElement = "testType"; wsdlTypes.numberElement = 1; }); it("should return the type when requested", function () { var actual = soapInterceptor.getTypeFromWSDL("testElement", wsdlTypes); expect(actual).toBe("testType"); }); it("should coerce the type to a string", function () { var actual = soapInterceptor.getTypeFromWSDL("numberElement", wsdlTypes); expect(actual).toBe("1"); }); it("should return an empty string if element is not found in wsdlTypes", function () { var actual = soapInterceptor.getTypeFromWSDL("nonExistentElement", wsdlTypes); expect(actual).toBe(""); }); }); }); }());
canvas = document.getElementById('mycanvas'); ctx = canvas.getContext("2d"); img_image = "car2.png"; background_image = "parkingLot.jpg"; canvas_width = 900; canvas_height = 700; car_width = 115; car_height = 175; car_x = 10; car_y = 375; function add(){ //alert("I am called"); img_back = new Image(); img_back.onload = uploadback; img_back.src = background_image; img_imgTag = new Image(); img_imgTag.onload = uploadimg; img_imgTag.src = img_image; } function uploadimg(){ ctx.drawImage(img_imgTag, car_x, car_y, car_width, car_height); } function uploadback(){ ctx.drawImage(img_back, 0, 0, canvas_width, canvas_height); } window.addEventListener("keydown", keydown_function); function up(){ car_y = car_y - 10; console.log("When up arrow is pressed x = " + car_x + " | y = " + car_y); uploadback(); uploadimg(); //img_imgTag.car_y = img_imgTag.car_y - 10; } function down(){ car_y = car_y + 10; console.log("When down arrow is pressed x = " + car_x + " | y = " + car_y); uploadback(); uploadimg(); } function left(){ car_x = car_x - 10; console.log("When left arrow is pressed x = " + car_x + " | y = " + car_y); uploadback(); uploadimg(); } function right(){ car_x = car_x + 10; console.log("When right arrow is pressed x = " + car_x + " | y = " + car_y); uploadback(); uploadimg(); } function keydown_function(e){ keydown = e.keyCode; console.log(keydown); if (keydown == 38){ up(); } if (keydown == 40){ down(); } if (keydown == 37){ left(); } if (keydown == 39){ right(); } }
import React from "react"; import "./index.css"; import Active from "../Active"; import Done from "../Done"; import { Tabs } from 'antd'; const TabPane = Tabs.TabPane; export default class Home extends React.Component { render() { return ( <div> <Tabs defaultActiveKey="1"> <TabPane tab="Active" key="1"> <Active /> </TabPane> <TabPane tab="Done" key="2"> <Done /> </TabPane> </Tabs> </div> ) } }
// components/Boop.jsx import React from "react" import { animated } from "react-spring" import useBoop from "../hooks/useBoop" const Boop = ({ children, ...boopConfig }) => { const [style, trigger] = useBoop(boopConfig) return ( <animated.span onMouseEnter={trigger} style={style}> {children} </animated.span> ) } export default Boop
// format = [time at the start stop] or // [time, other] or // [time, start_stop, end_stop, other] STSP_red_main_stop_name = ["Park 17<br />商場","璞園<br />宿舍","馨園<br />宿舍","南科<br />實中","民生<br />水塔","臺鐵<br />南科站","南科<br />實中","社區<br />中心","晶圓<br />S1廠","東捷<br />科技","應材製<br />造中心","廣停3","南科健康<br />生活館","台灣<br />康寧","住華<br />科技","晶電<br />S3廠","Park 17<br />商場"]; STSP_red_main_stop_time_consume = [0, 0, 2, 7, 3, 7, 10, 13, 15, 17, 18, 20, 22, 23, 24, 26, 29]; STSP_red_important_stop = [0, 5, 7, 14]; // Park 17商場, 臺鐵南科站, 社區中心, 住華科技 var skip_list = [1, 2, 3]; // 璞園宿舍, 馨園宿舍, 南科實中 var stop_1 = 1; // 璞園宿舍 var stop_2 = 3; // 南科實中 var stop_3 = 4; // 民生水塔 var TRA_NK = 5; var life_hub = 7; // 社區中心 var stop_4 = 12; // 南科健康生活館 var stop_5 = 15; // 晶電S3廠 STSP_red_time_go = [["06:25",[...skip_list,[stop_5,1]]],["06:11",stop_1,TRA_NK+1,['*',stop_2,stop_3,[TRA_NK,18,TRA_NK+1,1]]], ["06:52",[...skip_list]],["06:46",stop_1,TRA_NK+1,[stop_3,[TRA_NK,8]]],["07:14",[...skip_list,[life_hub,1,life_hub+1,2]]], ["07:06",stop_1,TRA_NK+1,[stop_3,[stop_2,1,TRA_NK,7]]],["07:21",[...skip_list,[life_hub,1,life_hub+1,2]]], ["07:43",[...skip_list,[TRA_NK+2,1,TRA_NK+3,1]]],["07:49",[...skip_list,[TRA_NK+2,1,TRA_NK+3,1]]], ["07:58",[...skip_list,[life_hub+1,2]]],["08:18",[...skip_list]],["08:23",[...skip_list]],["09:08",[...skip_list]], ["09:43",[...skip_list]],["10:23",[...skip_list]],["11:25",[...skip_list]],["12:24",[...skip_list]],["13:34",[...skip_list]], ["14:19",[...skip_list]],["15:45",[...skip_list]],["16:16",[...skip_list]] ]; // The name of return stops are different STSP_red_main_stop_name_return = ["Park 17<br />商場","群創<br />C廠","台達電","台灣<br />康寧","南科健康<br />生活館","廣停3","漢民<br />科技","東捷<br />科技","茂迪","華園<br />宿舍","民生<br />水塔","臺鐵<br />南科站","南科<br />實中","社區<br />中心","璞園<br />宿舍","Park 17<br />商場"]; STSP_red_main_stop_time_consume_return = [0, 3, 6, 7, 8, 9, 10, 11, 13, 16, 18, 22, 25, 27, 27, 31]; STSP_red_important_stop_return = [0, 2, 9, 11]; // Park 17商場, 台達電, 華園宿舍, 臺鐵南科站 STSP_red_time_return = [["17:03"],["17:32"],["17:39"],["17:49"],["18:05"],["18:40"],["19:08"],["19:40"],["20:23"],["20:58"]];
"use strict"; var dinnerApp = angular.module( 'starter', [ 'ionic', 'ngResource', 'environment', 'ui.calendar', 'rzModule', 'angularPayments', 'auth0', 'angular-storage', 'angular-jwt', 'ngCordova' ]); dinnerApp.run(function($ionicPlatform) { $ionicPlatform.ready(function() { if (window.StatusBar) { // org.apache.cordova.statusbar required StatusBar.styleLightContent(); } Ionic.io(); var push = new Ionic.Push({ debug: true, canShowAlert: true, canSetBadge: true, canPlaySound: true, canRunActionsOnWake: true, onNotification: function(notification) { console.log(notification); return true; }, onRegister: function(data) { console.log(data); return true; } }); push.register(function(token) { console.log("Device token:",token.token); }); }); });
import React, { useEffect, useState } from "react"; import * as mapActions from "../store/actions/map"; import { useDispatch, useSelector } from "react-redux"; import { Layout, Button, Input, Card } from "antd"; import GoogleMapReact from "google-map-react"; import ReactDOM from "react-dom"; import mapboxgl from "mapbox-gl"; import ReactMapboxGl, { Layer, Feature } from "react-mapbox-gl"; const Map = ReactMapboxGl({ accessToken: "pk.eyJ1IjoieGlhbmdqdW4iLCJhIjoiY2s4cWpkYWdnMDM3azNtczFkZHhxd2hmZiJ9.dLC65wCHxIk2eKp9nQEE5g", }); // https://github.com/alex3165/react-mapbox-gl/blob/master/docs/API.md const SimpleMap = () => { return ( // Important! Always set the container height explicitly <div style={{ padding: 24, background: "#fff", textAlign: "center" }}> <Map style="mapbox://styles/mapbox/streets-v9" center={[-76.6215, 39.3286]} containerStyle={styles.mapContainer} zoom={[14]} > <Layer type="symbol" id="marker" layout={{ "icon-image": "harbor-15" }}> <Feature coordinates={[-76.6215, 39.3286]} /> <Feature coordinates={[-76.6235, 39.3286]} /> </Layer> </Map> ; </div> ); }; export default SimpleMap; let styles = { mapContainer:{ height: "100vh", width: "100vw", } }; // ReactDOM.render(<SimpleMap />, document.getElementById('app'));
const handleChangePassword = async function(event) { event.preventDefault(); event.stopImmediatePropagation(); $("#password-message").html(''); let password = document.getElementById('password').value; let confirmPassword = document.getElementById('confirm-password').value; if (password == "") { $("#password-message").html('<span class="has-text-danger">Password cannot be empty.</span>'); return; } if (password != confirmPassword) { $("#password-message").html('<span class="has-text-danger">Passwords do not match.</span>'); return; } let jwt = window.localStorage.getItem("jwt"); let response = await axios({ method: 'POST', url: "http://localhost:3000/account/update", headers: { "Authorization": "Bearer " + jwt }, data: { pass: password } }).catch(function(error) { console.log('Error fetching user data:', error); return; }); $("#password-message").html('<span>Successfully changed password!</span>'); } const handleChangeSignature = async function(event) { event.preventDefault(); event.stopImmediatePropagation(); let signature = document.getElementById('signature').value; let jwt = window.localStorage.getItem("jwt"); let response = await axios({ method: 'POST', url: "http://localhost:3000/account/update", headers: { "Authorization": "Bearer " + jwt }, data: { data: { signature: signature } } }).catch(function(error) { console.log('Error fetching user data:', error); return; }); $("#signature-message").html('<span>Successfully changed signature!</span>'); } const readySubmitHandlers = function() { $('#change-password').on('click', handleChangePassword); $('#change-signature').on('click', handleChangeSignature); } $(function() { readySubmitHandlers(); });
// Object.keys, values, entries // + 1. Сумма свойств объекта // describe("sumSalaries", function () { // it("returns sum of salaries", function () { // let salaries = { // "John": 100, // "Pete": 300, // "Mary": 250 // }; // assert.equal(sumSalaries(salaries), 650); // }); // it("returns 0 for the empty object", function () { // assert.strictEqual(sumSalaries({}), 0); // }); // }); // 2. Подсчёт количества свойств объекта // describe("count", function () { // it("counts the number of properties", function () { // assert.equal(count({ a: 1, b: 2 }), 2); // }); // it("returns 0 for an empty object", function () { // assert.equal(count({}), 0); // }); // it("ignores symbolic properties", function () { // assert.equal(count({ [Symbol('id')]: 1 }), 0); // }); // }); // 1. Фильтрация уникальных элементов массива // describe("unique", function () { // it("removes non-unique elements", function () { // let strings = ["Hare", "Krishna", "Hare", "Krishna", // "Krishna", "Krishna", "Hare", "Hare", ":-O" // ]; // assert.deepEqual(unique(strings), ["Hare", "Krishna", ":-O"]); // }); // it("does not change the source array", function () { // let strings = ["Krishna", "Krishna", "Hare", "Hare"]; // unique(strings); // assert.deepEqual(strings, ["Krishna", "Krishna", "Hare", "Hare"]); // }); // }); // 2. Отфильтруйте анаграммы // function intersection(arr1, arr2) { // return arr1.filter(item => arr2.includes(item)); // } // describe("aclean", function () { // it("returns exactly 1 word from each anagram set", function () { // let arr = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"]; // let result = aclean(arr); // assert.equal(result.length, 3); // assert.equal(intersection(result, ["nap", "PAN"]).length, 1); // assert.equal(intersection(result, ["teachers", "cheaters", "hectares"]).length, 1); // assert.equal(intersection(result, ["ear", "era"]).length, 1); // }); // it("is case-insensitive", function () { // let arr = ["era", "EAR"]; // assert.equal(aclean(arr).length, 1); // }); // }); // Object.keys, values, entries // 1. Сумма свойств объекта // describe("sumSalaries", function () { // it("returns sum of salaries", function () { // let salaries = { // "John": 100, // "Pete": 300, // "Mary": 250 // }; // assert.equal(sumSalaries(salaries), 650); // }); // it("returns 0 for the empty object", function () { // assert.strictEqual(sumSalaries({}), 0); // }); // }); // 2. Подсчёт количества свойств объекта // describe("count", function () { // it("counts the number of properties", function () { // assert.equal(count({ a: 1, b: 2 }), 2); // }); // it("returns 0 for an empty object", function () { // assert.equal(count({}), 0); // }); // it("ignores symbolic properties", function () { // assert.equal(count({ [Symbol('id')]: 1 }), 0); // }); // }); // Деструктурирующее присваивание // 2. Максимальная зарплата // describe("topSalary", function () { // it("returns top-paid person", function () { // let salaries = { // "John": 100, // "Pete": 300, // "Mary": 250 // }; // assert.equal(topSalary(salaries), "Pete"); // }); // it("returns null for the empty object", function () { // assert.isNull(topSalary({})); // }); // }); // Дата и время // 2. Покажите день недели // describe("getWeekDay", function () { // it("3 января 2014 года - пятница", function () { // assert.equal(getWeekDay(new Date(2014, 0, 3)), 'ПТ'); // }); // it("4 января 2014 года - суббота", function () { // assert.equal(getWeekDay(new Date(2014, 0, 4)), 'СБ'); // }); // it("5 января 2014 года - воскресенье", function () { // assert.equal(getWeekDay(new Date(2014, 0, 5)), 'ВС'); // }); // it("6 января 2014 года - понедельник", function () { // assert.equal(getWeekDay(new Date(2014, 0, 6)), 'ПН'); // }); // it("7 января 2014 года - вторник", function () { // assert.equal(getWeekDay(new Date(2014, 0, 7)), 'ВТ'); // }); // it("8 января 2014 года - среда", function () { // assert.equal(getWeekDay(new Date(2014, 0, 8)), 'СР'); // }); // it("9 января 2014 - четверг", function () { // assert.equal(getWeekDay(new Date(2014, 0, 9)), 'ЧТ'); // }); // }); // 3. День недели в европейской нумерации // describe("getLocalDay возвращает \"европейский\" день недели", function () { // it("3 января 2014 года - пятница", function () { // assert.equal(getLocalDay(new Date(2014, 0, 3)), 5); // }); // it("4 января 2014 года - суббота", function () { // assert.equal(getLocalDay(new Date(2014, 0, 4)), 6); // }); // it("5 января 2014 года - воскресенье", function () { // assert.equal(getLocalDay(new Date(2014, 0, 5)), 7); // }); // it("6 января 2014 года - понедельник", function () { // assert.equal(getLocalDay(new Date(2014, 0, 6)), 1); // }); // it("7 января 2014 года - вторник", function () { // assert.equal(getLocalDay(new Date(2014, 0, 7)), 2); // }); // it("8 января 2014 года - среда", function () { // assert.equal(getLocalDay(new Date(2014, 0, 8)), 3); // }); // it("9 января 2014 года - четверг", function () { // assert.equal(getLocalDay(new Date(2014, 0, 9)), 4); // }); // }); // 4. Какой день месяца был много дней назад? // describe("getDateAgo", function () { // it("1 день до 02.01.2015 -> день 1", function () { // assert.equal(getDateAgo(new Date(2015, 0, 2), 1), 1); // }); // it("2 дня до 02.01.2015 -> день 31", function () { // assert.equal(getDateAgo(new Date(2015, 0, 2), 2), 31); // }); // it("100 дней до 02.01.2015 -> день 24", function () { // assert.equal(getDateAgo(new Date(2015, 0, 2), 100), 24); // }); // it("365 дней до 02.01.2015 -> день 2", function () { // assert.equal(getDateAgo(new Date(2015, 0, 2), 365), 2); // }); // it("переданный объект date не модифицируется", function () { // let date = new Date(2015, 0, 2); // let dateCopy = new Date(date); // getDateAgo(dateCopy, 100); // assert.equal(date.getTime(), dateCopy.getTime()); // }); // }); // 5. Последнее число месяца? describe("getLastDayOfMonth", function () { it("последнее число 01.01.2012 - 31", function () { assert.equal(getLastDayOfMonth(2012, 0), 31); }); it("последнее число 01.02.2012 - 29 (високосный год)", function () { assert.equal(getLastDayOfMonth(2012, 1), 29); }); it("последнее число 01.02.2013 - 28", function () { assert.equal(getLastDayOfMonth(2013, 1), 28); }); });
new Vue({ el : "#root", data:{ artikli:[ { naziv: "Meri Popins", cena: 4850 }, { naziv: "Džoker", cena: 5130 }, { naziv: "Bel", cena: 4250 }, { naziv: "Luj XVI", cena: 4860 }, { naziv: "Grdana", cena: 5320 }, { naziv: "Penivajz", cena: 5125 }, { naziv: "Julije Cezar", cena: 3605 }, { naziv: "Isterivač duhova", cena: 3750 }, { naziv: "Kal Drogo", cena: 3605 }, { naziv: "Ursula", cena: 4150 }, { naziv: "Grinč", cena: 4150 }, { naziv: "Drvo", cena: 3800 }, { naziv: "Džejn Ostin", cena: 3230 }, { naziv: "Bliznakinja", cena: 3205 }, { naziv: "Čudesna žena", cena: 2850 }, { naziv: "Betmen", cena: 3950 }, ], jePodvuceno: true, posetilac : { ime: "", email : "" }, recenica: "Unesite ime i email:", rec:"Kostimi", prikazano: false, websajt : "https://www.halloweencostumes.com", websiteTag: '<a href="https://www.facebook.com/HalloweenCostumesDotCom">Posetite fejsbuk stranicu</a>', websiteTag2: '<a href="https://www.instagram.com/FunCostumes/">Posetite instagram stranicu</a>', websiteTag3: '<a href="https://www.pinterest.com/alwayshalloween/">Posetite pinterest stranicu</a>', }, computed: { greskaIme : function() { if (this.posetilac.ime.length < 4) { return "Ime mora sadržati najmanje 4 karaktera"; } else if (this.posetilac.ime.length > 10) { return "Ime ne sme sadržati više do 10 karaktera"; } }, greskaEmail : function() { if (this.posetilac.email.indexOf("@") < 0) { return "Email adresa nije pravilno uneta" } } }, });
import React from 'react' // Manual updating process class ForceUpdate extends React.Component { constructor() { super(); this.forceUpdateHandler1 = this.forceUpdateHandler.bind(this); }; forceUpdateHandler() { this.forceUpdate(); }; render() { return ( <div> <button onClick={this.forceUpdateHandler1}>FORCE UPDATE</button> <h4>Random number: {Math.random()}</h4> </div> ); } } export { ForceUpdate }
import React from 'react'; import PropTypes from 'prop-types'; import { makeStyles } from '@material-ui/core/styles'; import Pagination from '@material-ui/lab/Pagination'; const useStyles = makeStyles(theme => ({ root: { display: 'flex', justifyContent: 'center', marginTop: theme.spacing(2), marginBottom: theme.spacing(2), width: '100%', }, })); const ListPagination = ({ filters, fetchFunction, onPageUpdate = () => {}, }) => { const classes = useStyles(); const count = Math.ceil(filters.total / filters.limit); const handleChange = (event, value) => { fetchFunction({ limit: filters.limit, page: value }); onPageUpdate(value); }; const isEmpty = !filters.total; if (isEmpty) { return null; } return ( <div className={classes.root}> <Pagination count={count} page={filters.page} color="primary" onChange={handleChange} showFirstButton showLastButton /> </div> ); }; ListPagination.propTypes = { fetchFunction: PropTypes.func, filters: PropTypes.shape({ limit: PropTypes.number, page: PropTypes.number, total: PropTypes.number, }), onPageUpdate: PropTypes.func, }; ListPagination.defaultProps = { fetchFunction: () => {}, filters: { limit: 10, page: 1, total: 0, }, }; export default ListPagination;
import React, { useEffect, useState } from 'react'; import { Container, Content, InternalContent } from './styles'; import HeaderRestaurant from "../../../../components/HeaderRestaurant"; import MenuRestaurant from "../../../../components/MenuRestaurant"; import FooterComponent from "../../../../components/Footer"; import { NotificationContainer, NotificationManager } from "react-notifications"; import axios from "axios"; import { MAX_SIZE_FILE, PATH, USER_RESTAURANT } from "../../../../utils/Consts"; import { Redirect, useHistory } from "react-router-dom"; import { useSelector } from "react-redux"; import { Button, Form, Input, Select, TitleForm } from "../../Extra/new/styles"; import InputCurrency from "../../../../components/InputCurrency"; export default function ItemNew() { const history = useHistory(); const [description, setDescription] = useState(); const [price, setPrice] = useState(); const [isActive, setIsActive] = useState(); const [picture, setPicture] = useState(); const [category, setCategory] = useState(); const [extras, setExtras] = useState([]); const user = useSelector(state => state.user); const [categories, setCategories] = useState([]); const [extrasList, setExtrasList] = useState([]); useEffect(() => { getAllCategories(); getAllExtras(); }, []); async function getAllCategories() { await axios.get(PATH + "/item-category") .then((result) => { setCategories(result.data); }); } async function getAllExtras() { await axios.get(PATH + "/extra") .then((result) => { setExtrasList(result.data); }); } function checkInput() { if(description === "" || description == null){ NotificationManager.error("Erro o campo 'descrição' é obrigatório", "Erro", 1000); return false; } if(isActive === "" || isActive === null){ NotificationManager.error("Erro o campo 'Ativo' é obrigatório", "Erro", 1000); return false; } if(price === "" || price == null){ NotificationManager.error("Erro o campo 'Preço' é obrigatório", "Erro", 1000); return false; } if(category === "" || category == null){ NotificationManager.error("Erro o campo 'Categoria' é obrigatório", "Erro", 1000); return false; } return true; } async function save() { if(!checkInput()){ return; } console.log(extras); let ex = extras.map(extra => ({id: extra, description: undefined, image: undefined, isActive: true, price: 1.5})); await axios.post(`${PATH}/item`, { description:description, isActive:isActive, extras: ex, itemCategory: {id: category, name: undefined}, price:price, image:picture, restaurantId: user.restaurantId }).then(res => { NotificationManager.success("Item cadastrada com sucesso", "Sucesso", 1000); history.push('/restaurant/item') }).catch(err => { NotificationManager.error("Erro ao cadastrar item", "Erro", 1000); }); } function sendFile(e) { const file = e.target.files; const reader = new FileReader(); reader.readAsArrayBuffer(file[0]); reader.onloadend = () => { const fileByteArray = []; const array = new Uint8Array(reader.result); if(array.length > MAX_SIZE_FILE){ e.target.value = null; return NotificationManager.error("Erro a imagem deve ter no máximo 16MB!", "Erro", 1000); } for (let i = 0; i < array.length; i++) { fileByteArray.push(array[i]); } setPicture(fileByteArray); } } const handleChange = (event, value, maskedValue) => { event.preventDefault(); setPrice(value); }; const handleSelect = (e) => { setExtras(Array.from(e.target.selectedOptions, option => Number(option.value))); } return ( <Container> {user.userLogged === false || user.userType !== USER_RESTAURANT ? <Redirect to="/restaurant/login"></Redirect> : null} <HeaderRestaurant/> <Content> <MenuRestaurant/> <Container> <TitleForm>Item</TitleForm> <Form> <Input type={"text"} onChange={e => setDescription(e.target.value)} placeholder={"Digite a descrição do Item"}/> <Select defaultValue={"category"} onChange={e => {setCategory(e.target.value)}}> <option value="category" selected disabled hidden>Selecione uma Categoria</option> {categories.map((categoryItem) => ( <option key={categoryItem.id} value={categoryItem.id}>{categoryItem.name}</option> ))} </Select> </Form> <Form> <Select defaultValue={"extras"} onChange={handleSelect} multiple> <option value={"extras"} selected disabled hidden>Selecione os extras</option> {extrasList.map((extraItem) => ( <option key={extraItem.id} value={extraItem.id}>{extraItem.description}</option> ))} </Select> <Select defaultValue={"isActive"} onChange={e => {setIsActive(e.target.value)}}> <option value="isActive" selected disabled hidden>Selecione uma opção</option> <option value={true} >Ativo</option> <option value={false} >Inativo</option> </Select> </Form> <Form> <InputCurrency handleChange={handleChange} placeholder="Digite o valor do item"/> <Input type="file" id="inputPicture" className="form-control-file" onChange={e => sendFile(e)} accept="image/png, image/jpeg" /> </Form> <Button onClick={() => {save()}} type="button">Cadastrar</Button> <FooterComponent/> </Container> </Content> <NotificationContainer/> </Container> ); }
import { createLogger } from 'redux-logger' import { applyMiddleware, combineReducers, createStore } from 'redux' import thunk from 'redux-thunk' import { composeWithDevTools } from 'redux-devtools-extension' export const buildStore = reducers => { const loggerMiddleware = createLogger({ collapsed: true }) const combinedReducers = combineReducers(reducers) const appliedMiddlewares = composeWithDevTools(applyMiddleware(thunk, loggerMiddleware)) return createStore(combinedReducers, window.initialState, appliedMiddlewares) }
// Maria plays college basketball and wants to go pro. Each season she maintains a record of her play. She tabulates the number of times she breaks her season record for most points and least points in a game. Points scored in the first game establish her record for the season, and she begins counting from there. // Given Maria's scores for a season, find and print the number of times she breaks her records for most and least points scored during the season. // Complete the breakingRecords function below. function breakingRecords(scores) { let [bests, worsts] = [[scores[0]], [scores[0]]]; scores.forEach(score => { if (score > bests.slice(-1)) bests.push(score); if (score < worsts.slice(-1)) worsts.push(score); }); return [bests.length - 1, worsts.length - 1]; } function main() { let scores = "3 4 21 36 10 28 35 5 24 42".split(" ").map(Number); console.log(breakingRecords(scores)); // -> 4 0 scores = "10 5 20 20 4 5 2 25 1".split(" ").map(Number); console.log(breakingRecords(scores)); // -> 2 4 } main();
'use strict'; import React from 'react'; import { Link } from 'react-router'; export default (props) => { return ( <div id="cart-line-item" className="container"> <div className="panel panel-success"> <div className="panel-heading"> <div className="row"> <div className="col-sm-10 col-xs-9"> <h3 className="panel-title text-left">{ props.name }</h3> </div> <div className="col-sm-2 col-xs-3 text-right"> <button id="remove-from-cart" className="btn btn-sm btn-danger">Remove</button> </div> </div> </div> <div className="panel-body"> <div className="media"> <div className="media-left"> <div className="thumbContainer"> <Link to="/reviews"> <img className="thumbImg" src={ props.photo } alt={ props.name }/> </Link> </div> </div> <div className="media-body"> <p>{ props.description }</p> <p>Qty: { props.quantity }</p> <p>Price: ${ (props.price * props.quantity).toFixed(2) }</p> </div> </div> </div> </div> </div> ); };
import React, { Component } from 'react' import { Link } from 'react-router' import 'normalize.css' import './style.scss' export default class App extends Component { render() { return ( <div className="app"> <div className="menu"> <div> <a className="logo" href=""></a> </div> <nav> <ul className="navigation"> <li className="navigation__item"> <Link to="/" activeClassName='active' onlyActiveOnIndex={true}>HOME</Link> </li> <li className="navigation__item"> <Link to="/work" activeClassName='active'>WORK</Link> </li> <li className="navigation__item"> <Link to="/about" activeClassName='active'>ABOUT</Link> </li> <li className="navigation__item"> <Link to="/blog" activeClassName='active'>BLOG</Link> </li> <li className="navigation__item"> <Link to="/services" activeClassName='active'>SERVICES</Link> </li> <li className="navigation__item"> <Link to="/contact" activeClassName='active'>CONTACT</Link> </li> </ul> </nav> </div> <div className="context"> {this.props.children} </div> </div> ) } }
//const {SHA256} = require('crypto-js'); const jwt = require('jsonwebtoken'); // var message = "hey its me akash"; // var hash = SHA256(message).toString(); // console.log(message , hash) var data = { id: 10 }; var token = jwt.sign(data, '123'); var decode = jwt.verify(token, '123'); console.log(decode);
/* * Module code goes here. Use 'module.exports' to export things: * module.exports.thing = 'a thing'; * * You can import it from another modules like this: * var mod = require('class.spawn'); * mod.thing == 'a thing'; // true */ var classSpawn = { run: function(spawn){ var fleas = _.filter(Game.creeps, (creep) => creep.memory.class == 'flea'); if(fleas.length < 3){ spawn.spawnCreep([MOVE,CARRY,WORK],'Flea'+String(Game.time),{memory: {class: 'flea'}}) } } } module.exports = classSpawn
import store from "../../../store"; export default { notify(path, events, params, options) { if (params) { // 测试时暂时这么写。 store.dispatch({ type: "NOTICE_ADD", notice: { path, events, params, options } }) } } }