text
stringlengths
7
3.69M
/** * Copyright 2021-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * * Messenger For Original Coast Clothing * https://developers.facebook.com/docs/messenger-platform/getting-started/sample-apps/original-coast-clothing */ "use strict"; // Import dependencies and set up http server const express = require("express"), { urlencoded, json } = require("body-parser"), crypto = require("crypto"), path = require("path"), Receive = require("./services/receive"), GraphApi = require("./services/graph-api"), User = require("./services/user"), config = require("./services/config"), i18n = require("./i18n.config"), app = express(); var users = {}; // Parse application/x-www-form-urlencoded app.use( urlencoded({ extended: true }) ); // Parse application/json. Verify that callback came from Facebook app.use(json({ verify: verifyRequestSignature })); // Serving static files in Express app.use(express.static(path.join(path.resolve(), "public"))); // Set template engine in Express app.set("view engine", "ejs"); // Respond with index file when a GET request is made to the homepage app.get("/", function (_req, res) { res.render("index"); }); // Add support for GET requests to our webhook app.get("/webhook", (req, res) => { // Parse the query params let mode = req.query["hub.mode"]; let token = req.query["hub.verify_token"]; let challenge = req.query["hub.challenge"]; // Check if a token and mode is in the query string of the request if (mode && token) { // Check the mode and token sent is correct if (mode === "subscribe" && token === config.verifyToken) { // Respond with the challenge token from the request console.log("WEBHOOK_VERIFIED"); res.status(200).send(challenge); } else { // Respond with '403 Forbidden' if verify tokens do not match res.sendStatus(403); } } }); // Create the endpoint for your webhook app.post("/webhook", (req, res) => { let body = req.body; console.log(`\u{1F7EA} Received webhook:`); console.dir(body, { depth: null }); // Check if this is an event from a page subscription if (body.object === "page") { // Returns a '200 OK' response to all requests res.status(200).send("EVENT_RECEIVED"); // Iterate over each entry - there may be multiple if batched body.entry.forEach(async function (entry) { if ("changes" in entry) { // Handle Page Changes event let receiveMessage = new Receive(); if (entry.changes[0].field === "feed") { let change = entry.changes[0].value; switch (change.item) { case "post": return receiveMessage.handlePrivateReply( "post_id", change.post_id ); case "comment": return receiveMessage.handlePrivateReply( "comment_id", change.comment_id ); default: console.warn("Unsupported feed change type."); return; } } } // Iterate over webhook events - there may be multiple entry.messaging.forEach(async function (webhookEvent) { // Discard uninteresting events if ("read" in webhookEvent) { console.log("Got a read event"); return; } else if ("delivery" in webhookEvent) { console.log("Got a delivery event"); return; } else if (webhookEvent.message && webhookEvent.message.is_echo) { console.log( "Got an echo of our send, mid = " + webhookEvent.message.mid ); return; } // Get the sender PSID let senderPsid = webhookEvent.sender.id; // Get the user_ref if from Chat plugin logged in user let user_ref = webhookEvent.sender.user_ref; // Check if user is guest from Chat plugin guest user let guestUser = isGuestUser(webhookEvent); if (senderPsid != null && senderPsid != undefined) { if (!(senderPsid in users)) { if (!guestUser) { // Make call to UserProfile API only if user is not guest let user = new User(senderPsid); GraphApi.getUserProfile(senderPsid) .then((userProfile) => { user.setProfile(userProfile); }) .catch((error) => { // The profile is unavailable console.log(JSON.stringify(body)); console.log("Profile is unavailable:", error); }) .finally(() => { console.log("locale: " + user.locale); users[senderPsid] = user; i18n.setLocale("en_US"); console.log( "New Profile PSID:", senderPsid, "with locale:", i18n.getLocale() ); return receiveAndReturn( users[senderPsid], webhookEvent, false ); }); } else { setDefaultUser(senderPsid); return receiveAndReturn(users[senderPsid], webhookEvent, false); } } else { i18n.setLocale(users[senderPsid].locale); console.log( "Profile already exists PSID:", senderPsid, "with locale:", i18n.getLocale() ); return receiveAndReturn(users[senderPsid], webhookEvent, false); } } else if (user_ref != null && user_ref != undefined) { // Handle user_ref setDefaultUser(user_ref); return receiveAndReturn(users[user_ref], webhookEvent, true); } }); }); } else { // Return a '404 Not Found' if event is not from a page subscription res.sendStatus(404); } }); function setDefaultUser(id) { let user = new User(id); users[id] = user; i18n.setLocale("en_US"); } function isGuestUser(webhookEvent) { let guestUser = false; if ("postback" in webhookEvent) { if ("referral" in webhookEvent.postback) { if ("is_guest_user" in webhookEvent.postback.referral) { guestUser = true; } } } return guestUser; } function receiveAndReturn(user, webhookEvent, isUserRef) { let receiveMessage = new Receive(user, webhookEvent, isUserRef); return receiveMessage.handleMessage(); } // Set up your App's Messenger Profile app.get("/profile", (req, res) => { let token = req.query["verify_token"]; let mode = req.query["mode"]; if (!config.webhookUrl.startsWith("https://")) { res.status(200).send("ERROR - Need a proper API_URL in the .env file"); } var Profile = require("./services/profile.js"); Profile = new Profile(); // Check if a token and mode is in the query string of the request if (mode && token) { if (token === config.verifyToken) { if (mode == "webhook" || mode == "all") { Profile.setWebhook(); res.write( `<p>&#9989; Set app ${config.appId} call to ${config.webhookUrl}</p>` ); } if (mode == "profile" || mode == "all") { Profile.setThread(); res.write( `<p>&#9989; Set Messenger Profile of Page ${config.pageId}</p>` ); } if (mode == "personas" || mode == "all") { Profile.setPersonas(); res.write(`<p>&#9989; Set Personas for ${config.appId}</p>`); res.write( "<p>Note: To persist the personas, add the following variables \ to your environment variables:</p>" ); res.write("<ul>"); res.write(`<li>PERSONA_BILLING = ${config.personaBilling.id}</li>`); res.write(`<li>PERSONA_CARE = ${config.personaCare.id}</li>`); res.write(`<li>PERSONA_ORDER = ${config.personaOrder.id}</li>`); res.write(`<li>PERSONA_SALES = ${config.personaSales.id}</li>`); res.write("</ul>"); } if (mode == "nlp" || mode == "all") { GraphApi.callNLPConfigsAPI(); res.write( `<p>&#9989; Enabled Built-in NLP for Page ${config.pageId}</p>` ); } if (mode == "domains" || mode == "all") { Profile.setWhitelistedDomains(); res.write( `<p>&#9989; Whitelisted domains: ${config.whitelistedDomains}</p>` ); } if (mode == "private-reply") { Profile.setPageFeedWebhook(); res.write(`<p>&#9989; Set Page Feed Webhook for Private Replies.</p>`); } res.status(200).end(); } else { // Responds with '403 Forbidden' if verify tokens do not match res.sendStatus(403); } } else { // Returns a '404 Not Found' if mode or token are missing res.sendStatus(404); } }); // Verify that the callback came from Facebook. function verifyRequestSignature(req, res, buf) { var signature = req.headers["x-hub-signature"]; if (!signature) { console.warn(`Couldn't find "x-hub-signature" in headers.`); } else { var elements = signature.split("="); var signatureHash = elements[1]; var expectedHash = crypto .createHmac("sha1", config.appSecret) .update(buf) .digest("hex"); if (signatureHash != expectedHash) { throw new Error("Couldn't validate the request signature."); } } } // Check if all environment variables are set config.checkEnvVariables(); // Listen for requests :) var listener = app.listen(config.port, function () { console.log(`The app is listening on port ${listener.address().port}`); if ( Object.keys(config.personas).length == 0 && config.appUrl && config.verifyToken ) { console.log( "Is this the first time running?\n" + "Make sure to set the both the Messenger profile, persona " + "and webhook by visiting:\n" + config.appUrl + "/profile?mode=all&verify_token=" + config.verifyToken ); } if (config.pageId) { console.log("Test your app by messaging:"); console.log(`https://m.me/${config.pageId}`); } });
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { increase,decrease } from './actions/action' class App extends Component { render(){ console.log(this.props) return ( <div className="App"> <button onClick={this.props.increase}> + </button> <div>{this.props.count}</div> <button onClick={this.props.decrease}> - </button> </div> ); } } function mapStateToProps(state) { return { count : state.count } } const action1 = { type: 'INCREASE' } const action2 = { type: 'DECREASE' } function mapDispatchToProps (dispatch) { return { increase : () => dispatch(increase()), decrease : () => dispatch(decrease()) } } export default connect(mapStateToProps, mapDispatchToProps)(App); // connect :: lié l component par le data dans reducer /// lié redux avec notre component App // mapStateToProps : donne moi le state du store et envoie le comme props pour le component App //mapDispatchToProps => envoi les parametre increase et decrease comme props
import React from 'react'; import {compose, lifecycle} from 'recompose'; import {applyToParticipate, detectParticipate} from "../store/action"; import {connect} from "react-redux"; import { Button, } from 'reactstrap'; import {Loader} from "../../Layout/Loader"; const mapStateToProps = ({ outingReducer: { outing_participate, outing_participate_fetch, } }) => ({ outing_participate, outing_participate_fetch, }); export const ButtonHandleParticipate = compose( connect( mapStateToProps, dispatch => ({ applyToParticipate: (...args) => dispatch(applyToParticipate(...args)), detectParticipate: (...args) => dispatch(detectParticipate(...args)), }) ), lifecycle({ componentDidMount() { this.props.detectParticipate(this.props.participate); } }) )(({applyToParticipate, id, outing_participate, outing_participate_fetch, ...rest}) => ( <div className={'pt-2 pb-2 text-center'}> <Button className={'primary'} disabled={outing_participate_fetch} onClick={() => applyToParticipate({outing: id, value: !outing_participate})}> <h3>{outing_participate_fetch ? <Loader/> : outing_participate ? `Je n'y vais plus` : `J'y participe`}</h3> </Button> </div> ));
angular.module("mainModule") .component("note", { templateUrl: "Scripts/Components/Note/Note.html", controller: function () { var ctrl = this; var component = {}; setTimeout(function () { component = $("#note-" + ctrl.id); component.draggable({ grid: [10, 10] }); }, 100); }, bindings: { id: "=", body: "=" } });
/*global beforeEach, describe, it, assert, expect */ 'use strict'; describe('ProfileInfo Model', function () { beforeEach(function () { this.ProfileInfoModel = new PipedriveTest.Models.ProfileInfo(); }); });
// Controller.Start.js Ext.regController('Start', { index: function(options) { console.log('[Controller.Start] index'); if (options.game && !this.game) this.initGame(options.game); // this user ready to play App.on( 'player-button-start', function() { console.log('Controller.Start pressed button start'); this.game.playerStart(); }, this ); this.showStart(); }, initGame: function(game) { console.log('[Controller.Start] initGame'); this.game = game; this.game.on( 'player-connected', function() { console.log('[Controller.Start] game.on.player-connected'); this.viewStart.showPlayerConnected(this.game); }, this ); this.game.on( 'player-started', function() { console.log('[Controller.Start] game.on.player-started'); this.viewStart.showPlayerStarted(); }, this ); this.game.on( 'opponent-connected', function() { console.log('[Controller.Start] game.on.opponent-connected'); this.viewStart.showOpponentConnected(this.game); }, this ); this.game.on( 'opponent-started', function(game) { console.log('[Controller.Start] game.on.opponent-started', game); this.viewStart.showOpponentStarted(); }, this ); this.game.on( 'game-on', function() { console.log('[Controller.Start] game.on.opponent-started', game); this.viewStart.showGameOn(); }, this ); this.game.connect(); }, showStart: function() { console.log('[Controller.Start] showStart'); if (!this.viewStart) { this.viewStart = this.render({ xtype: 'App.View.Start' }); /* example bind tap: this.viewChat.query('#settingsButton')[0].on( 'tap', this.showConfig, this ); */ } /* example set active item: this.application.viewport.setActiveItem( this.viewStart, { type: 'slide', direction: 'left' } ); */ }, showGame: function() { Ext.dispatch({ controller: 'Viewport', action : 'showGame' }); } });
const GOOD_PASSWORD = "qwerty123"; const MAX_TRIES = 5;
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import iView from 'iview' import store from './store' import 'iview/dist/styles/iview.css' // 使用 CSS //import VueAwesomeSwiper from 'vue-awesome-swiper' //import 'swiper/dist/css/swiper.css' import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; import ECharts from 'vue-echarts/components/ECharts.vue' import bmap from 'echarts-bmap' import 'echarts/lib/component/tooltip' import 'echarts/lib/component/toolbox' import 'echarts/lib/component/title' import 'echarts/lib/component/grid' import 'echarts/lib/component/legend' import 'echarts/lib/component/dataZoom' import 'echarts/lib/component/polar' import 'echarts/lib/component/radiusAxis' import 'echarts/lib/chart/pie' import 'echarts/lib/chart/bar' import 'echarts/lib/chart/lines' import 'echarts/lib/chart/effectScatter' import 'echarts/lib/chart/line' require('echarts-wordcloud') require('echarts/extension/bmap/bmap') import echarts from 'echarts' import liquidfill from 'echarts-liquidfill' Vue.prototype.$echarts = echarts Vue.config.productionTip = false Vue.use(iView) Vue.use(ElementUI); //Vue.use(VueAwesomeSwiper, /* { default global options } */ ) /* eslint-disable no-new */ Vue.component('chart',ECharts) Vue.prototype.$Echarts = ECharts Vue.prototype.$echarts = echarts new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })
const config = { botName: 'BigBraim', ownerName: 'Brayan', youtube: 'www.youtube.com/channel/UCI15ahRyhf_cssUSPXgF0Mw', instagram: 'INSTAGRAM_LINK', }
//ДЗ 1-2 var x = prompt ('ввести значение'); var n = prompt('ввести степень'); function pow (x,n){ var result=x; for (var i=1; i<n; i++){ result*=x; } return result; } alert (pow(x,n));
require('express-async-errors'); const {Genre, validateGenre} = require('../model/genre'); const auths = require('../middleware/auths'); const admin = require('../middleware/admin'); const express = require('express'); const router = express.Router(); router.get('/', async (req, res) => { const genre = await Genre.find(); res.send(genre); } ); router.get('/:id', async (req, res)=> { const genre = await Genre.findById(req.params.id); if(!genre) return res.status(404).send("genre was not found with given id"); res.send(genre); }); router.post('/', auths, async (req, res) => { const {error } = validateGenre(req.body); if(error) return res.status(400).send(error.details[0].message); const genre = new Genre({ name : req.body.name }); await genre.save(); res.send(genre); }); router.put('/:id', async (req, res)=> { const genre = await Genre.findByIdAndUpdate(req.params.id, {name : req.body.name}); if(!genre) return res.status(404).send("genre was not found with given id"); res.send(genre); }); router.delete('/:id',[auths, admin], async (req, res) => { const genre = await Genre.findByIdAndRemove(req.params.id); if(!genre) return res.status(404).send("genre was not found with given id"); res.send(genre); }); module.exports =router;
/*import express from 'express'; import http from 'http'; import bodyParser from 'body-parser'; //node 这里还不支持es6的import 的写法 import morgan from 'morgan'; */ const express = require('express'); const http = require('http'); const bodyParser = require('body-parser'); const morgan = require('morgan'); const router= require('./router.js'); const app = express();//app = express()的意思是新建了一个HTTPserver,这样你就可以发request給它;之前的项目,用webpack来跑一个服务器;webpack的服务器功能简单,基本就负责静态文件 const mongoose = require('mongoose'); //db setup mongoose.connect('mongodb://localhost:auth/auth'); //app setup app.use(morgan('combined'));//login incoming request//middleware app.use(bodyParser.json({type:'*/*'}));//parse incoming request into json,type是任何类型//middleware router(app); //servere setup const port = process.env.PORT||7777;//The process object is a global that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using require(). const server = http.createServer(app); server.listen(port); console.log('Server listening on:',port);
'use strict' angular.module('app').directive('appPositionInfo',[function(){ return{ restrict:'AE', replace:true, templateUrl:'view/template/positioninfo.html' } }])
/** * Title: Exercise 1.3 - Class Refresher * Author: Nathaniel Liebhart * Date: August 6th, 2019 * Description: Create a cell phone object with properties and methods */ /** * Params: firstName, lastName, assignment * Response: output * Description: Returns formatted header string */ const header = require("../liebhart-header"); console.log(header("Nathaniel", "Liebhart", "Exercise 1.3") + "\n"); /* Expected output: FirstName LastName <AssignmentName> <Today's Date> -- DISPLAYING CELL PHONE DETAILS -- Manufacturer: <manufacturer> Model: <model> Color: <color> Price: <price> */ // CellPhone constructor function function CellPhone(manufacturer, model, color, price) { this.manufacturer = manufacturer; this.model = model; this.color = color; this.price = price; } // Add methods to the prototype property for inheritance // getPrice method CellPhone.prototype.getPrice = function() { return this.price; }; // getModel method CellPhone.prototype.getModel = function() { return this.model; }; // getDetails method CellPhone.prototype.getDetails = function() { let output = "-- DISPLAYING CELL PHONE DETAILS --\n"; output += `Manufacturer: ${this.manufacturer}\n`; output += `Model: ${this.getModel()}\n`; output += `Color: ${this.color}\n`; output += `Price: $${this.getPrice()}\n`; return output; }; // Instantiate new CellPhone let galaxy = new CellPhone( "Samsung", "Galaxy Fold", "Astro Blue with Gold Hinge", 1980 ); // Print new CellPhone Object's details to the console console.log(galaxy.getDetails());
class CartPage { get cartemptyText() { return $("div[class='_3Y9ZP']")} get itemName() { return $("div[class='_33KRy']")} get addButton() {return $("div[class='_1ds9T']")} get removeButton() { return $("div[class='_29Y5Z']")} get individualItemCount() { return $("div[class='_2zAXs']")} getcartText() { return this.cartemptyText.getText(); } getitemNameText() { return this.itemName.getText(); } clickRemoveButton() { this.removeButton.waitForDisplayed(6000); return this.removeButton.click(); } clickAddButton() { this.addButton.waitForDisplayed(6000); return this.addButton.click(); } getIndividualItemCount() { return this.individualItemCount.getText(); } } module.exports = new CartPage();
/* open menu */ const menuButton = document.querySelector('button.menu-button'); menuButton.addEventListener('click', () => { menuButton.classList.toggle('active'); }); /* external link in new tab */ Array.from(document.querySelectorAll('a')).forEach(a => { if (a.href.search(/\w+:\/\//) === 0 && a.hostname !== location.hostname) a.setAttribute('target', '_blank') })
var structfsml_1_1FlatMachine = [ [ "FlatMachine", "structfsml_1_1FlatMachine.html#a506e347690aa39f7eb7637fd7a952e40", null ], [ "FlatMachine", "structfsml_1_1FlatMachine.html#a939aa63ea93b644c498cf2e31f67499f", null ], [ "~FlatMachine", "structfsml_1_1FlatMachine.html#af9260de8b6528b4d8839d3a21b7dd68c", null ], [ "operator AstMachine", "structfsml_1_1FlatMachine.html#a79e252b2ba388c1064d9570a6df275af", null ], [ "operator std::string", "structfsml_1_1FlatMachine.html#a3c50e3140f7629c8c34f2c760522203b", null ], [ "initials", "structfsml_1_1FlatMachine.html#a3069121ea01eab1cec46590ab186b622", null ], [ "states", "structfsml_1_1FlatMachine.html#a5f3c317f5a3a8f13f10160dcaeef63e3", null ], [ "steps", "structfsml_1_1FlatMachine.html#a2fc01c07d6bc3f62fba880e96e538390", null ] ];
import React from 'react' import { Row, Col, Image } from 'react-bootstrap' import Header from '../components/Header/customHeader' import * as actions from '../../redux/actions' import { connect } from 'react-redux' import { CircularProgress } from '@material-ui/core' import {withRouter} from 'react-router-dom' import BlogCard from './BlogCard' import './index.scss' function Blog(props) { React.useEffect(()=>{ props.getBlogList() }, []) return ( <div className='parent'> <Header title='Blogs' backButton backTo={() => props.history.push('/')}/> <Row className='mt-3 px-2'> <Col> {props.blogList ? props.blogList.length > 0 ? props.blogList.map(item => <BlogCard key={item.id} data={item} /> ) : <p className='text-center'>No Blogs!</p> :<Row className='mt-3'><Col className='text-center'><CircularProgress color='primary' /></Col></Row>} </Col> </Row> </div> ) } const mapStateToProps = state => ({ blogList: state.user.blogList }) const mapDispatchToProps = dispatch => ({ getBlogList: () => dispatch(actions.getBlogList()) }) export default connect(mapStateToProps, mapDispatchToProps)(Blog)
import React from "react"; import { Link } from "gatsby"; import Menu from "./menu"; import styles from "./layout.module.scss"; const Header = ({ location, title }) => { const rootPath = `${__PATH_PREFIX__}/`; const isRootPath = location.pathname === rootPath; let headerTitle = isRootPath ? ( <h1 className={styles.mainHeading}> <Link to="/">{title}</Link> </h1> ) : ( <Link className={styles.headerLinkHome} to="/"> {title} </Link> ); return ( <header className={styles.globalHeader}> {headerTitle} <Menu location={location} /> </header> ); }; export default Header;
$(function () { $('.close').click(function () { $('#info').fadeOut(500) }); }); // Handle full screen mode toggle // toggle full screen function toggleFullScreen() { if (!document.fullscreenElement && // alternative standard method !document.mozFullScreenElement && !document.webkitFullscreenElement) { // current working methods if (document.documentElement.requestFullscreen) { document.documentElement.requestFullscreen(); } else if (document.documentElement.mozRequestFullScreen) { document.documentElement.mozRequestFullScreen(); } else if (document.documentElement.webkitRequestFullscreen) { document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); } } else { if (document.cancelFullScreen) { document.cancelFullScreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } } } $('#fullscreen').click(function () { toggleFullScreen(); }); $(window).on('load', function () { $('#myModal').modal('toggle'); }); setTimeout(function () { $('#myModal').modal('hide'); }, 5000); $('#events-modal').on('hidden.bs.modal', function () { location.reload() }); function abrir_modal(url) { $('#delete').load(url, function () { $(this).modal('show'); }); return false; } function cerrar_modal() { $('#popup').modal('hide'); return false; } function open_re_useful_modal(url, id=null) { if(id) { $(`#dropdown_${id}`).load(url, function () {}); return false; } $("#re-useful").load(url, function () { $(this).modal('show'); }); return false; } function close_re_useful_modal() { $("#re-useful").modal('hide'); $("#re-useful div").remove(); return false; } function reload_table(url) { $(".table-responsive").load(url); return false; } $(document).ready(function () { // Collapse/Show sidebar menu $('#sidebarCollapse').on('click', function () { $('#sidebar').toggleClass('active'); $(this).toggleClass('active'); }); // Any anonymous datatable var count = $("#tabla").find("tr:first td").length - 1; $('#tabla').dataTable({ "language": { url: "/static/localizacion/es_ES.json" }, aaSorting: [], columnDefs: [ { orderable: false, searchable: false, targets: count } ] }); // Report datatable $("#tabla_report").dataTable({ language: { url: '/static/localizacion/es_ES.json' }, ordering: false, scrollCollapse: true, scrollY: 350, paging: false, dom: 'Bfrtip', buttons: ['excelHtml5'], drawCallback: function () { $('.dt-buttons')[0].style.visibility = 'hidden'; $('.dataTables_info')[0].style.visibility = 'hidden'; } }); // Excel export button for Report datatable $('#excel_btn').on('click', function () { $('.buttons-excel').click(); }); // Hide and show up button when scroll down more than 200 px from top $(window).scroll(function () { if ($(this).scrollTop() > 200) { $('#topcontrol').css({'opacity': 1}); } else { $('#topcontrol').css({'opacity': 0}); } }); // Click event to scroll to top $('#topcontrol').click(function () { $('html, body').animate({scrollTop: 0}, 600); }); });
import messageConstants from '../constants/message_constants'; export const receiveMessage = msg => ({ type: messageConstants.MESSAGE_RECEIVED, msg }); export const submitMessage = msg => { socket.emit('messageUp', msg); return { type: messageConstants.SUBMIT_MESSAGE }; };
import React from "react"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faUpload, faSearch, faCog, faComment, faBell, faBars, faWindowClose, } from "@fortawesome/free-solid-svg-icons"; import logo from "../images/logo.jpg"; const Navbar = () => { return ( <> <section id="navbar"> <nav className="navbar navbar-expand-lg navbar-light "> <div className="container-fluid"> <div className="type mx-lg-5"> <form className="d-flex"> <FontAwesomeIcon className="mt-2 fs-5" icon={faSearch} style={{ color: "grey" }} /> <input className="form-control if " type="search" placeholder="Type to search..." /> </form> </div> <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse" id="navbarSupportedContent" > <ul className="navbar-nav ml-auto"> <li className="nav-item px-lg-2"> <FontAwesomeIcon className="mx-md-2 my-md-3 fs-5" icon={faCog} style={{ color: "grey" }} /> </li> <li className="nav-item px-md-2"> <FontAwesomeIcon className="mx-md-2 my-md-3 fs-5" icon={faComment} style={{ color: "grey" }} /> </li> <li className="nav-item px-2"> <FontAwesomeIcon className="mx-md-2 my-md-3 fs-5" icon={faBell} style={{ color: "grey" }} /> </li> <li className="nav-item dropdown my-md-2"> <a className="nav-link dropdown-toggle name" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false" > Sajanbir Singh <img src={logo} className="logo" /> </a> <ul className="dropdown-menu" aria-labelledby="navbarDropdown" > <li> <a className="dropdown-item">Add account</a> </li> </ul> </li> </ul> </div> </div> </nav> <hr /> </section> </> ); }; export default Navbar;
import colorPalettes from "utils/colorPalettes"; // Structure to define the relation among the type of information, the palette to use and // the order to assign the colors in the palette to the values (if any) const match = { fc: { palette: "rainbowFc", sort: [10, 9.5, 9, 8.5, 8, 7.5, 7, 6.5, 6, 5.5, 5, 4.5, 4], }, biomas: { palette: "greenBiomes", }, bioticReg: { palette: "bioticReg", }, coverage: { palette: "coverage", sort: ["N", "S", "T"], }, pa: { palette: "pa", sort: ["No Protegida"], }, se: { palette: "seBlue", sort: ["NA"], }, biomeComp: { palette: "shortFC", sort: ["high", "medium", "low"], }, hfTimeline: { palette: "hfTimeline", // TODO: The id part could change once the API endpoint is implemented sort: [ "aTotal", "aTotalSel", "paramo", "paramoSel", "dryForest", "dryForestSel", "wetland", "wetlandSel", ], }, hfCurrent: { palette: "hfCurrent", // TODO: This could change once the API endpoint is implemented sort: ["natural", "baja", "media", "alta"], }, hfPersistence: { palette: "hfPersistence", // TODO: This could change once the API endpoint is implemented sort: ["estable_natural", "dinamica", "estable_alta"], }, paramo: { palette: "paramo", sort: ["paramo"], }, dryForest: { palette: "dryForest", sort: ["dryForest"], }, wetland: { palette: "wetland", sort: ["wetland"], }, paramoPAConn: { palette: "sePAConn", }, dryForestPAConn: { palette: "sePAConn", }, wetlandPAConn: { palette: "sePAConn", }, forestLP: { palette: "forestLP", sort: ["persistencia", "perdida", "ganancia", "no_bosque"], }, SciHf: { palette: "SciHf", sort: [ "alta-estable_natural", "alta-dinamica", "alta-estable_alta", "baja_moderada-estable_natural", "baja_moderada-dinamica", "baja_moderada-estable_alta", ], }, currentPAConn: { palette: "currentPAConn", sort: ["prot_conn", "prot_unconn", "unprot"], }, dpc: { palette: "dpc", sort: ["muy_bajo", "bajo", "medio", "alto", "muy_alto"], }, timelinePAConn: { palette: "timelinePAConn", sort: ["prot", "protSel", "prot_conn", "prot_connSel"], }, richnessNos: { palette: "richnessNos", // first values, then limits, then backgrounds, then legend limits sort: [ "inferred", "observed", "min_inferred", "min_observed", "max_inferred", "max_observed", "region_inferred", "region_observed", "area", "region", "legend-from", "legend-to", ], }, richnessGaps: { palette: "richnessGaps", // first values, then limits, then backgrounds sort: [ "value", "min", "max", "min_threshold", "max_threshold", "min_region", "max_region", "area", "legend-from", "legend-middle", "legend-to", ], }, caTargets: { palette: "caTargets", sort: ["Biod · SS.EE. · Riesgo", "ELSA", "Rest · WePlan", "Biod · Carbono · Agua", "ACC · Biod. Acuática"], }, functionalDryForestValues: { palette: "functionalDryForestValues", sort: ["value", "value_nal"], }, functionalDFFeatureLA: { palette: "functionalDFFeatureLA", // first values, then limits, then backgrounds sort: ["value", "min", "max", "area"], }, functionalDFFeatureLN: { palette: "functionalDFFeatureLN", // first values, then limits, then backgrounds sort: ["value", "min", "max", "area"], }, functionalDFFeaturePH: { palette: "functionalDFFeaturePH", // first values, then limits, then backgrounds sort: ["value", "min", "max", "area"], }, functionalDFFeatureSLA: { palette: "functionalDFFeatureSLA", // first values, then limits, then backgrounds sort: ["value", "min", "max", "area"], }, functionalDFFeatureSSD: { palette: "functionalDFFeatureSSD", // first values, then limits, then backgrounds sort: ["value", "min", "max", "area"], }, functionalDFFeatureSM: { palette: "functionalDFFeatureSM", // first values, then limits, then backgrounds sort: ["value", "min", "max", "area"], }, polygon: { palette: "polygon", }, border: { palette: "border", }, default: { palette: "default", }, }; const cache = { biomas: { counter: 0 }, bioticReg: { counter: 0 }, pa_counter: 1, }; /** * returns the color determined for a given value. * * @param {string} type type of information to apply colors. * @param {boolean} resetCache whether to clean the cache before assigning colors. Applies to 'pa' * * @param {any} value value to assign a color, type of data will depend on type arg. * * fc will receive numbers between 4 and 10 (multiple of 0.25). * The rest of the types will receive strings. */ const matchColor = (type, resetCache = false) => { const info = match[type] || match.default; const palette = colorPalettes[info.palette]; const sort = info.sort || []; switch (type) { case "fc": return (value) => { const numValue = parseFloat(value); let idx = sort.indexOf(numValue); if (idx === -1) idx = sort.indexOf(numValue + 0.25); if (idx === -1) return null; return palette[idx]; }; case "biomas": case "bioticReg": return (value) => { if (cache[type][value]) return cache[type][value]; const { counter } = cache[type]; cache[type][value] = palette[counter]; cache[type].counter = counter === palette.length - 1 ? 0 : counter + 1; return palette[counter]; }; case "pa": if (resetCache) { cache.pa_counter = 1; } return (value) => { const idx = sort.indexOf(value); if (idx !== -1) return palette[idx]; const { pa_counter: counter } = cache; cache.pa_counter = counter === palette.length - 1 ? 1 : counter + 1; return palette[counter]; }; case "hfPersistence": case "hfCurrent": case "coverage": case "biomeComp": case "hfTimeline": case "forestLP": case "SciHf": case "forestIntegrity": case "currentPAConn": case "dpc": case "timelinePAConn": case "caTargets": case "se": return (value) => { const idx = sort.indexOf(value); if (idx === -1) return palette[palette.length - 1]; return palette[idx]; }; case "paramo": case "dryForest": case "wetland": case "richnessNos": case "richnessGaps": case "functionalDryForestValues": case "functionalDFFeatureLA": case "functionalDFFeatureLN": case "functionalDFFeaturePH": case "functionalDFFeatureSLA": case "functionalDFFeatureSSD": case "functionalDFFeatureSM": return (value) => { const idx = sort.indexOf(value); if (idx === -1) return null; return palette[idx]; }; case "border": case "polygon": default: return () => palette[0]; } }; export default matchColor;
cc.Class({ extends: cc.Component, properties: { sp1: cc.Node, sp2: cc.Node }, start: function() { this.updateFrame = 1, cc.director.getCollisionManager().enabled = !0, this.sp1.active = !0, this.sp2.active = !1, this.sp2.scaleX = 1.1, this.sp2.scaleY = 1.1; }, onCollisionEnter: function(o) { var e = o.node.name; "puffer" == e && (this.node.removeFromParent(), this._isdestroy = !0), "BigBoss" == e && this.onBlast(); }, onBlast: function() { this._isdestroy || (this._isdestroy = !0, this.node.getChildByName("puffer").active = !1, this.node.getChildByName("blast").active = !0, this.scheduleOnce(function() { this.node.removeFromParent(); }, 2)); }, update: function(t) { this._isdestroy || (window.isGameOver && this.onBlast(), this.updateFrame -= t, 0 >= this.updateFrame && (this.sp1.active = !this.sp1.active, this.sp2.active = !this.sp1.active, this.updateFrame = 1)); } });
//var Chart = require('chart.js/Chart'); function randomLine() { var t = 30000; var i = -30000; return Math.floor(Math.random() * (t - i)) + i; }; function randomBar() { return Math.round(100 * Math.random()); }; function mountCharts() { var chartLine = document.getElementById('chartCashFlow').getContext('2d'); var lineChartData = { labels: ['01/15', '02/15', '03/15', '04/15', '05/15', '06/15'], datasets: [{ label: 'data set', fillColor: 'rgba(1198,35,112,.1)', strokeColor: 'rgba(1198,35,112,.8)', pointColor: 'rgba(1198,35,112,1)', pointStrokeColor: '#fff', pointHighlightFill: '#fff', pointHighlightStroke: 'rgba(151,187,205,1)', data: [randomLine(), randomLine(), randomLine(), randomLine(), randomLine(), randomLine(), randomLine()] }] }; window.chartLine = new Chart(chartLine).Line(lineChartData, { animationSteps: 30, responsive: !0, scaleBeginAtZero: !0, scaleOverride: !0, scaleSteps: 6, scaleStepWidth: 1e4, scaleStartValue: -3e4, scaleLabel: '<%= (value != 0)? value + " €": 0 %>', tooltipTemplate: '<%= value + " €" %>', tooltipCornerRadius: 0, tooltipCaretSize: 0, tooltipFillColor: 'rgba(0,21,51,.8)' }); var chartBar = document.getElementById('chartBar').getContext('2d'); var barChartData = { labels: ['', ''], datasets: [ { fillColor: 'rgba(69,112,180,1)', strokeColor: 'rgba(69,112,180,0)', highlightFill: 'rgba(151,187,205,1)', highlightStroke: 'rgba(151,187,205,1)', data: [randomBar(), randomBar()] } ] }; window.chartBar = new Chart(chartBar).Bar(barChartData, { animationSteps: 30, responsive: !0, scaleShowLabels: !1, barShowStroke: !1, scaleShowVerticalLines: !1, tooltipCornerRadius: 0, tooltipCaretSize: 0, tooltipFillColor: 'rgba(0,21,51,.8)', tooltipTemplate: '<%= value + ' % ' %>', scaleOverride: !0, scaleSteps: 10, scaleStepWidth: 10, scaleStartValue: 0 }); window.chartBar.datasets[0].bars[1].fillColor = 'rgba(194,14,26,1)'; window.chartBar.update(); }
const axios = require('axios'); let todos; axios.get('https://hlv7793ve8.execute-api.us-east-1.amazonaws.com/jsontest') .then((response) => { todos = response.data; console.log(todos[0].name); }) .catch((err) => console.log(err)); // async / await approach async function AWSTest() { try { const response = await axios.get('https://hlv7793ve8.execute-api.us-east-1.amazonaws.com/jsontest'); console.log(response.data); } catch (error) { console.log(error); } } AWSTest();
/*========================================================================================= File Name: router.js Description: Routes for vue-router. Lazy loading is enabled. ---------------------------------------------------------------------------------------- Item Name: Vuexy - Vuejs, HTML & Laravel Admin Dashboard Template Author: Pixinvent Author URL: http://www.themeforest.net/user/pixinvent ==========================================================================================*/ import Vue from "vue"; import Router from "vue-router"; import Profile from "./views/pages/User/Profile.vue"; import ProfileSetting from "./views/pages/User/ProfileSettings/ProfileSetting.vue"; import axios from "@/axios.js"; Vue.use(Router); const router = new Router({ mode: "history", base: "/", scrollBehavior() { return { x: 0, y: 0 }; }, routes: [ { // ============================================================================= // MAIN LAYOUT ROUTES // ============================================================================= path: "/", component: () => import("./layouts/main/Main.vue"), children: [ // ============================================================================= // Theme Routes // ============================================================================ { path: "/", name: "dashboard", component: () => import("@/views/pages/Dashboard.vue"), meta: { rule: "all", requiresAuth: true } }, { path: "/profile-setting", name: "profile-setting", component: ProfileSetting, meta: { rule: "all", requiresAuth: true } }, { path: "/profile", name: "profile", component: Profile, meta: { rule: "all", requiresAuth: true } }, { path: "/editors", name: "editors", component: () => import("@/views/pages/Editors/EditorIndex.vue"), meta: { rule: "Editor", requiresAuth: true, requiresAdmin: true } }, { path: "/editors/:slug", name: "editor", component: () => import("@/views/pages/Editors/Editor.vue"), meta: { rule: "Editor", requiresAuth: true, requiresEditor: true } }, { path: "/editors/:slug/edit", name: "editor-edit", component: () => import( "@/views/pages/Editors/editor-edit/EditorEdit.vue" ), meta: { rule: "Admin", requiresAuth: true, requiresAdmin: true } }, { path: "/create-editor", name: "editor-create", component: () => import("@/views/pages/Editors/EditorCreate.vue"), meta: { rule: "Admin", requiresAuth: true, requiresAdmin: true } }, //ARTISTS { path: "/clients", name: "clients", component: () => import( "@/views/pages/Settings/Artists/ArtistIndex.vue" ), meta: { rule: "Commercial", requiresAuth: true, requiresAdmin: true, requiresCommercial: true } }, { path: "/clients/:slug", name: "client", component: () => import("@/views/pages/Settings/Artists/Artist.vue"), meta: { rule: "Commercial", requiresAuth: true, requiresAdmin: true, requiresCommercial: true } }, { path: "/clients/:slug/edit", name: "client-edit", component: () => import("@/views/pages/Settings/Artists/ArtistEdit.vue"), meta: { rule: "Admin", requiresAuth: true, requiresAdmin: true } }, // CONTACTS { path: "/create-contact", name: "contact-create", component: () => import("@/views/pages/Contacts/ContactCreate.vue"), meta: { rule: "Editor" // requiresAuth: true, // requiresAdmin: true, // requiresEditor: true } }, { path: "/contacts/:slug/edit", name: "contact-edit", component: () => import("@/views/pages/Contacts/ContactEdit.vue"), meta: { rule: "Editor", requiresAuth: true, requiresAdmin: true, requiresEditor: true } }, { path: "/contacts", name: "contacts", component: () => import("@/views/pages/Contacts/ContactsIndex.vue"), meta: { rule: "Editor", requiresAuth: true, requiresAdmin: true, requiresEditor: true } }, { path: "/contacts/:slug", name: "contact", component: () => import("@/views/pages/Contacts/Contact.vue"), meta: { rule: "Editor", requiresAuth: true, requiresEditor: true, requiresAdmin: true } }, { path: "/create-type", name: "contact-type-create", component: () => import("@/views/pages/ContactTypes/TypeCreate.vue"), meta: { rule: "Editor", requiresAuth: true, requiresAdmin: true } }, { path: "/types/:slug/edit", name: "contact-contact-edit", component: () => import("@/views/pages/ContactTypes/TypeEdit.vue"), meta: { rule: "Editor", requiresAuth: true, requiresAdmin: true } }, { path: "/types", name: "types", component: () => import("@/views/pages/ContactTypes/TypesIndex.vue"), meta: { rule: "Editor", requiresAuth: true, requiresAdmin: true } }, { path: "/templates/:alias/edit", name: "modifier-template", component: () => import("@/views/pages/Templates/EditTemplate.vue"), meta: { rule: "Admin", requiresAuth: true, requiresAdmin: true } }, { path: "/templates/add", name: "add-template", component: () => import("@/views/pages/Templates/AddTemplate.vue"), meta: { rule: "Admin", requiresAuth: true, requiresAdmin: true } }, { path: "/templates", name: "liste-templates", component: () => import("@/views/pages/Templates/TemplateIndex.vue"), meta: { rule: "Admin", requiresAuth: true, requiresAdmin: true } }, { path: "/entreprises", name: "entreprises", component: () => import("@/views/pages/Entreprises/EntrepriseIndex.vue"), meta: { rule: "Admin", requiresAuth: true, requiresAdmin: true } }, { path: "/create-entreprise", name: "create-entreprise", component: () => import( "@/views/pages/Entreprises/EntrepriseCreate.vue" ), meta: { rule: "Admin", requiresAuth: true, requiresAdmin: true } }, { path: "/entreprises/:slug/edit", name: "edit-entreprise", component: () => import("@/views/pages/Entreprises/EntrepriseEdit.vue"), meta: { rule: "Admin", requiresAuth: true, requiresAdmin: true } }, { path: "/service/prix", name: "modifier-prix", component: () => import("@/views/components/price/Price.vue"), meta: { rule: "Admin", requiresAuth: true, requiresAdmin: true } }, { path: "/service/faq", name: "faqs", component: () => import("@/views/pages/Faq/IndexFaq.vue"), meta: { rule: "Editor", requiresAuth: true, requiresAdmin: true } } ] }, { path: "", component: () => import("@/layouts/full-page/FullPage.vue"), children: [ { path: "/", name: "page-login", component: () => import("@/views/pages/Auth/Login.vue"), meta: { guest: true, rule: "guest" } } ] }, { path: "/404", name: "page-error-404", component: () => import("@/views/pages/Error404.vue"), meta: { rule: "all" } } // Redirect to 404 page, if no match found // { // path: "*", // // rule: "all", // redirect: "/404" // } ] }); // router.beforeEach((to, from, next) => { // const auth = to.matched.some(record => record.meta.requiresAuth); // const admin = to.matched.some(record => record.meta.requiresAdmin); // const editor = to.matched.some(record => record.meta.requiresEditor); // const commercial = to.matched.some( // record => record.meta.requiresCommercial // ); // const activated = to.matched.some(record => record.meta.activated); // if (auth) { // if (localStorage.getItem("jwt") == null) { // next({ // name: "page-login", // params: { nextUrl: to.fullPath } // }); // } else { // let role = JSON.parse(localStorage.getItem("user")).role; // if (!admin && !editor && !commercial && role != "") { // next(); // } else if (admin || editor || commercial) { // if ( // (admin && role == "Admin") || // (editor && role == "Editor") || // (commercial && role == "Commercial") // ) { // next(); // } else { // next({ name: "dashboard" }); // } // } else { // if ( // activated && // localStorage.getItem("user").StatusName == "Suspendu" // ) { // next({ name: "dashboard" }); // } else { // next(); // } // } // } // } else if (to.matched.some(record => record.meta.guest)) { // if (localStorage.getItem("jwt") == null) { // next(); // } else { // next({ name: "dashboard" }); // } // } else { // next(); // } // }); router.afterEach(() => { // Remove initial loading const appLoading = document.getElementById("loading-bg"); if (appLoading) { appLoading.style.display = "none"; } }); export default router;
(function () { "use strict"; /*global $scope*/ describe("serviceId", function () { var $window, $compile, ContentsService, markup, form, queryResult; beforeEach(inject(function (_$injector_) { $window = _$injector_.get("$window"); $compile = _$injector_.get("$compile"); ContentsService = _$injector_.get("ContentsService"); $scope.vm = { contentId: "40", networkId: "dvb", service: { smsContentId: "40", }, }; spyOn($window, "$q").and.callFake(); queryResult = undefined; spyOn(ContentsService, "getContentOnNetwork").and.callFake(function () { return { then: function (cb) { cb(queryResult || { result: { resultCode: "0", resultText: "Success", }, networkContent: {}, }); } }; }); })); describe("initialize", function() { var form; beforeEach(function() { var element = angular.element("<form name='serviceForm'><p class='form-control-static' name='smsNetworkId' service-id ng-model='vm.networkId' content-id='vm.service.smsContentId'></p></form>"); spyOn($scope, "$watch").and.callThrough(); $compile(element)($scope); $scope.$digest(); form = $scope.serviceForm; }); it("should call scope.$watch", function () { expect($scope.$watch).toHaveBeenCalledWith("vm.service.smsContentId", jasmine.any(Function)); }); it("should run the ngModel.$validate() when $scope.vm.service.smsContentId changes", function() { expect(form.smsNetworkId.$valid).toBe(false); queryResult = { result: { resultCode: "0", resultText: "Success", }, }; $scope.vm.service.smsContentId = "41"; $scope.$digest(); expect(form.smsNetworkId.$valid).toBe(true); window.debugMeNow = false; }); }); describe("given no ngModel controller", function () { beforeEach(function () { markup = "<form name='testForm' norequire><div service-id content-id='vm.contentId'></div></form>"; form = $compile(markup)($scope); $scope.$digest(); }); it("should do nothing", function () { expect(ContentsService.getContentOnNetwork).not.toHaveBeenCalled(); }); }); describe("given no content-id attribute value", function () { beforeEach(function () { markup = "<form name='testForm' norequire><div service-id ng-model='vm.networkId'></div></form>"; form = $compile(markup)($scope); $scope.$digest(); }); it("should do nothing", function () { expect(ContentsService.getContentOnNetwork).not.toHaveBeenCalled(); }); }); describe("given a content-id and ngModel controller", function () { beforeEach(function () { markup = "<form name='testForm' norequire><div service-id ng-model='vm.networkId' content-id='vm.contentId'></div></form>"; form = $compile(markup)($scope); }); it("should call ContentsService.getContentOnNetwork with the provided content id and network id", function () { $scope.$digest(); expect(ContentsService.getContentOnNetwork).toHaveBeenCalledWith({ smsContentId: "40", smsNetworkId: "dvb", }); }); it("should notify the form if content already exists with the given content id and network id", function () { $scope.$digest(); expect(form).toHaveClass("ng-invalid-service-id"); expect(form).not.toHaveClass("ng-valid-service-id"); }); it("should notify the form if no content exists with the given content id and network id", function () { queryResult = { result: { resultCode: "0", resultText: "Success", }, }; $scope.$digest(); expect(form).not.toHaveClass("ng-invalid-service-id"); expect(form).toHaveClass("ng-valid-service-id"); }); }); }); }());
import { connect } from 'react-redux'; import * as ComicsActions from '../../../redux/comics/actions'; import View from './comics'; import { Actions } from 'react-native-router-flux'; // nos subscribimos a los cambios de valor de estas valores const mapStateToProps = (state) => { return { isFetching: state.comics.isFetching, list: state.comics.list, house: state.comics.item }; } const mapDispatchToProps = (dispatch, props) => { return { fetchComicsList: (query) => { if (!query || !query.trim()) { dispatch( ComicsActions.fetchComicsList() ); return; } dispatch( ComicsActions.searchComicsList(query) ); }, onComicTapped: (comic) => { dispatch( ComicsActions.setItem(comic) ); Actions.comicDetail({ title: comic.title }); } }; } export default connect(mapStateToProps, mapDispatchToProps)(View)
'use strict'; angular.module('SearchSetupService', []) .factory('SearchSetup', function(DataProcessing) { var searchFormFields = function () { var resultObj = {}; // step radio list resultObj.stepRLOptions = { label: 'services.crm.search.steptype.step', data: [ {"id": 1,"name": 'services.crm.searchsetup.inquiry'}, {"id": 2,"name": 'services.crm.searchsetup.decline'}, {"id": 3,"name": 'services.crm.searchsetup.buyer+'}] }; // transactionType radio list resultObj.transactionTypeRLOptions = { label: 'services.crm.search.transactiontype.transaction-type', data: [ {"id": 0,"name": 'services.crm.searchsetup.auth'}, {"id": 1,"name": 'services.crm.searchsetup.sale'}, {"id": 2,"name": 'services.crm.searchsetup.refund'}, {"id": 3, "name": 'services.crm.searchsetup.void'}, {"id": 4,"name": 'services.crm.searchsetup.capture'} ] }; // chargeType radio list resultObj.chargeTypeRLOptions = { label: 'services.crm.search.chargetype.charge-type', data: [ {"id": 16, "name": 'services.crm.searchsetup.signup-charge'}, {"id": 18, "name": 'services.crm.searchsetup.recurring-charge'}, {"id": 19, "name": 'services.crm.searchsetup.imported-charge'}, {"id": 20, "name": 'services.crm.searchsetup.upsell-charge'} ] }; // recurringStatus radio list resultObj.recurringStatusRLOptions = { label: 'services.crm.search.recurringstatus.recurring-status', data: [ {"id":"all","name": 'services.crm.searchsetup.all'}, {"id":"active","name": 'services.crm.searchsetup.active'}, {"id":"inactive","name": 'services.crm.searchsetup.inactive'} ] }; // orderType radio list resultObj.orderTypeRLOptions = { label: 'services.crm.search.ordertype.order-type', data: [ {"id":'RealOrders',"name": 'services.crm.searchsetup.real-orders-only'}, {"id":'TestOrdersOnly',"name": 'services.crm.searchsetup.test-orders-only'}, {"id":'All',"name": 'services.crm.searchsetup.all-orders'}] }; // Search form input boxes resultObj.customerIdTxtOptions = { label: 'services.crm.searchsetup.customer-id', id: 1, type: 'number', disAllowNegative: true, valNumber: true }; resultObj.transactionIdTxtOptions = { label: 'services.crm.searchsetup.transaction-id', id: 1, type: 'number', disAllowNegative: true, valNumber: true }; resultObj.firstNameTxtOptions = { label: 'services.crm.searchsetup.first-name', id: 1 }; resultObj.lastNameTxtOptions = { label: 'services.crm.searchsetup.last-name', id: 1 }; resultObj.emailTxtOptions = { label: 'services.crm.searchsetup.email', id: 1, type: 'email', valEmail: true }; resultObj.accountNumberTxtOptions = { label: 'services.crm.searchsetup.account-number', id: 1, inline: true, type: 'text', valNumber: true }; resultObj.bankAccountTxtOptions = { label: 'services.crm.searchsetup.bank-account-(ach)', id: 1, type: 'text', valNumber: true }; // chargeType radio list resultObj.accountNumberRLOptions = { label: 'services.crm.searchsetup.account-number', data: [ {"id":4,"name": 'services.crm.searchsetup.credit-card', checked: "checked"}, {"id":5,"name": 'services.crm.searchsetup.bank-account'} ], inline: true }; resultObj.ccLast4TxtOptions = { label: 'services.crm.searchsetup.cc-last-4-digits', id: 1, type: 'text', valNumber: true, valMax: 9999, maxlength: 4, placeholder: 'xxxx', disAllowNegative: true }; resultObj.phoneNumTxtOptions = { label: 'services.crm.searchsetup.phone-number', id: 1, disAllowNegative: true }; resultObj.chargeCodeTxtOptions = { label: 'services.crm.searchsetup.charge-code', id: 1, type: 'number', valNumber: true }; resultObj.refNumberTxtOptions = { label: 'services.crm.searchsetup.reference-number', id: 1, type: 'number', valNumber: true, disAllowNegative: true }; resultObj.zipCodeTxtOptions = { label: 'services.crm.searchsetup.zip', id: 1, valZip: true }; resultObj.fromDateOptions = { label: 'common.from', id: 304, inline: true, longLabel: true }; resultObj.toDateOptions = { label: 'common.to', id: 305, inline: true, longLabel: true }; return resultObj; }; var makeFields = function (sm, f) { return { Sites: sm.length ? sm.map(function (item) {return item.id;}) : [], CustomerID: f.customerIdTxtValue || 0, TransactionID: f.transactionIdTxtValue || 0, StepType: f.stepRLValue && f.stepRLValue.id ? f.stepRLValue.id : null, TransactionType: f.transactionTypeRLValue && f.transactionTypeRLValue.id ? f.transactionTypeRLValue.id : null, ChargeType: f.chargeTypeRLValue && f.chargeTypeRLValue.id ? f.chargeTypeRLValue.id : null , DateFrom: DataProcessing.dateToServer(f.fromDateValue), DateTo: DataProcessing.dateToServer(f.toDateValue), FirstName: f.firstNameTxtValue || "", LastName: f.lastNameTxtValue || "", Email: f.emailTxtValue || null, Zip: f.zipCodeTxtValue || null, Phone: f.phoneNumTxtValue || null, CCLast4Digits: f.ccLast4TxtValue || null, AccountNumber: f.accountNumberTxtValue || null, AccountType: f.accountNumberRLValue && f.accountNumberRLValue.id ? f.accountNumberRLValue.id : null, IsRecurringActive: f.recurringStatusRLValue && f.recurringStatusRLValue.id ? f.recurringStatusRLValue.id : null, ReferenceNumber: f.refNumberTxtValue || null, OrderType: f.orderTypeRLValue && f.orderTypeRLValue.id ? f.orderTypeRLValue.id : null }; }; var makeCustomers = function (c, startPos) { var resultArray = []; startPos = startPos || 0; for (var i = 0; i < c.length; i++) { var obj = c[i]; obj.id = i + startPos; resultArray.push(angular.copy(obj)); } return resultArray; }; return { searchFormFields: searchFormFields, makeFields: makeFields, makeCustomers: makeCustomers }; });
/** @Name:layuiAdmin 主页示例 @Author:star1029 @Site:http://www.layui.com/admin/ @License:GPL-2 */ layui.define(function (exports) { var admin = layui.admin; //回复留言 admin.events.replyNote = function(othis){ var nid = othis.data('id'); var nindex = othis.data('index'); var notifyData = notifyList[nindex]; var dialog=layer.open({ type: 2 //此处以iframe举例 ,title: '查 看' ,area:['1200px','550px'] ,shade: 0.5 ,maxmin: true ,content: ['/oa/notify/read/'+ nid] ,zIndex: layer.zIndex //重点1 ,btn: ['取 消'] //只是为了演示 ,yes: function (index, layero) { layer.closeAll(); } ,success: function(layero,index){ var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象,执行iframe页的方法:iframeWin.method(); iframeWin.setData(notifyData); layer.setTop(layero); //重点2 } }); layer.full(dialog); }; exports('sample', {}) });
// main body // ------------------------------ let newCardWindow = document.getElementById("newCardWindow"); let newCardInput = document.getElementById("addCardInput"); let doneButton = document.getElementById("doneButton"); let okWindow =document.getElementById("okWindow"); let okWindow2 =document.getElementById("okWindow2"); let okH62 = document.getElementById("okCardText2"); let okCardBody= document.getElementById("okCardBody"); let closeButton= document.getElementById("closeButton"); let addCard = document.getElementById("addCard") // adding new card addCard.addEventListener("click",function(){ newCardWindow.style.height="170px"; newCardWindow.style.visibility="visible"; newCardWindow.style.height="120px"; }) // closing new card window closeButton.addEventListener("click",function(){ newCardWindow.style.height="0px"; newCardWindow.style.visibility="hidden"; newCardWindow.style.height="0px"; }) // adding new card in new window doneButton.addEventListener("click",function(){ if(newCardInput.value!=null){ okWindow.lastChild; var cln = okWindow.cloneNode(true); okWindow2.appendChild(cln); newCardWindow.style.height="0px"; newCardWindow.style.visibility="hidden"; newCardWindow.style.height="0px"; okWindow2.style.height="170px"; okWindow2.style.visibility="visible"; okWindow2.style.height="120px"; okH62.innerHTML=newCardInput.value; } else{ console.log("asjdkashdkjk"); newCardWindow.style.display="block"; alert("Please Fill All Required Field"); return false; } }); let lastCardBody = document.getElementById("lastCardBody"); let lastCardInput = document.getElementById("lastCardInput"); // last card opening and closing let fourthHeadx = document.getElementById("fourthHeadx"); fourthHeadx.addEventListener("click",function(){ fourthHeadx.style.backgroundColor="white"; lastCardBody.style.visibility="visible"; lastCardInput.style.visibility="visible"; }) // ------------------------------ //end main body //opening overlay let profileImages = document.getElementsByClassName("profileImages"); let taskBoardOverlay = document.getElementById("taskBoardOverlay"); let taskBoardOverlayClass = document.getElementsByClassName("taskBoardOverlay"); let taskBoardCardDetailsButton = document.getElementById("taskBoardCardDetailsButton"); let taskBoardActivityButton = document.getElementById("taskBoardActivityButton"); let taskBoardCardDetailsBody = document.getElementById("taskBoardCardDetailsBody"); let taskBoardActivityBody = document.getElementById("taskBoardActivityBody"); let calendarTime = document.getElementsByClassName("calendarTime"); calendarTime.innerHTML="asdasdasdasdas"; let rightOpenButton = document.getElementsByClassName("rightOpenButton"); let rightOpenButton1 = document.getElementById("rightOpenButton1"); taskBoardOverlay.style.visibility="hidden"; taskBoardOverlay.style.display="none"; rightOpenButton1.addEventListener("click", function(){ alert("zart"); }) // right side profiles // // opening right side profiles when click small images // rightOpenButton.addEventListener("click",function(){ // taskBoardOverlay.style.visibility="visible"; // // }) taskBoardActivityBody.style.visibility="hidden"; taskBoardActivityBody.style.display="none"; //choose either card details or activity section taskBoardCardDetailsButton.addEventListener("click", function(){ taskBoardCardDetailsBody.style.visibility = "visible"; taskBoardCardDetailsBody.style.display = "block"; taskBoardActivityBody.style.visibility = "hidden"; taskBoardActivityBody.style.display="none"; }) taskBoardActivityButton.addEventListener("click", function(){ taskBoardActivityBody.style.visibility = "visible"; taskBoardActivityBody.style.display="block"; taskBoardCardDetailsBody.style.visibility = "hidden"; taskBoardCardDetailsBody.style.display = "none"; })
/*global define, alert, Howler */ // Array Remove - By John Resig (MIT Licensed) Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); }; define(['player', 'platform', 'controls', 'background'], function(Player, Platform, Controls, Background) { var transform = $.fx.cssPrefix + 'transform'; var INCREASE_DIFF_INTERVAL = 1000; var increaseDiff = 0; var INITIAL_NEW_PLATFORM_INTERVAL = 30; var newPlatformInterval = 0; /** * Main game class. * @param {Element} el DOM element containing the game. * @constructor */ var Game = function(el) { this.RESOLUTION_X = 320; this.RESOLUTION_Y = 480; this.el = el; this.platformsEl = el.find('.platforms'); this.backgroundsEl = el.find('.backgrounds'); this.scoreboardEl = el.find('.scoreboard'); this.player = new Player(this.el.find('.player'), this); this.setupGameScreens(el); this.setupBackgrounds(); this.freezeGame(); // Cache a bound onFrame since we need it each frame. this.onFrame = this.onFrame.bind(this); }; Game.prototype.setupBackgrounds = function(backgr) { this.backgrounds = []; this.addBackground(new Background({ x: 0, y: 0, width: this.RESOLUTION_X, height: this.RESOLUTION_Y }, 1)); this.addBackground(new Background({ x: this.RESOLUTION_X, y: -this.RESOLUTION_Y, width: this.RESOLUTION_X, height: this.RESOLUTION_Y }, 2)); } Game.prototype.addBackground = function(backgr) { this.backgrounds.push(backgr); this.backgroundsEl.append(backgr.el); } Game.prototype.onGameOverTransitionEnd = function(el) { if (el.hasClass('center') === false) { this.unfreezeGame(); }; }; Game.prototype.setupGameScreens = function(gameEl) { self = this; this.gameOverEl = gameEl.find('.gameOver'); this.gameOverEl.on('webkitTransitionEnd', this.onGameOverTransitionEnd.bind(this, this.gameOverEl)); this.gameOverEl.find('.button').click(function() { self.reset(); if (self.gameOverEl.hasClass('center') === true) { self.gameOverEl.removeClass('center'); }; }); this.mainScreenEl = gameEl.find('.mainScreen'); this.gameOverEl.on('webkitTransitionEnd', this.onGameOverTransitionEnd.bind(this, this.gameOverEl)); this.mainScreenEl.toggleClass('center'); this.mainScreenEl.find('.button').click(function() { self.mainScreenEl.toggleClass('center'); self.unfreezeGame(); }); } Game.prototype.addPlatform = function(platform) { this.platforms.push(platform); this.platformsEl.append(platform.el); }; Game.prototype.setupPlatforms = function() { this.platformsEl.empty(); // ground this.addPlatform(new Platform({ x: 100, y: 418, width: 80, height: 80 })); this.addPlatform(new Platform({ x: 150, y: 100, width: 80, height: 80 })); this.addPlatform(new Platform({ x: 250, y: 300, width: 80, height: 80 })); this.addPlatform(new Platform({ x: 10, y: 150, width: 80, height: 80 })); }; /** * Reset all game state for a new game. */ Game.prototype.reset = function() { newPlatformInterval = INITIAL_NEW_PLATFORM_INTERVAL; increaseDiff = INCREASE_DIFF_INTERVAL; this.total_y_vel = 0; this.cumulutive_y_vel = 0; this.scoreboardEl.text(0); // Reset platforms. this.platforms = []; this.setupPlatforms(); this.player.reset(); Controls.reset(); }; /** * Runs every frame. Calculates a delta and allows each game entity to update itself. */ Game.prototype.onFrame = function() { if (!this.isPlaying) { return; } var now = +new Date() / 1000, delta = now - this.lastFrame; this.lastFrame = now; Controls.onFrame(); var playerInfo = this.player.onFrame(delta); //Is the player moving upwards, then update platforms if (playerInfo.movingUpwards === true) { for (var i = 0, p; p = this.platforms[i]; i++) { p.onFrame(delta, playerInfo); if (p.rect.y > this.RESOLUTION_Y) { this.platforms.remove(i); p.el.remove(); } } for (var i = 0; i < this.backgrounds.length; i++) { this.backgrounds[i].onFrame(delta, playerInfo); } this.total_y_vel += Math.abs(playerInfo.velY); this.cumulutive_y_vel += Math.abs(playerInfo.velY); this.scoreboardEl.text(Math.round(this.total_y_vel)); if (this.total_y_vel > increaseDiff) { newPlatformInterval += 5; increaseDiff += INCREASE_DIFF_INTERVAL; } //If interval reach, create new random platform if (this.cumulutive_y_vel > newPlatformInterval) { var randomX = Math.floor((Math.random()*270)+1); this.addPlatform(new Platform({ x: randomX, y: -50, width: 80, height: 80 })); this.cumulutive_y_vel = 0; } }; this.checkGameover(); // Request next frame. requestAnimFrame(this.onFrame); }; Game.prototype.checkGameover = function() { if (this.player.pos.y > this.RESOLUTION_Y + 50) { this.gameover(); } }; /** * Stop the game and notify user that he has lost. */ Game.prototype.gameover = function() { this.gameOverEl.find('.headline').text('Game Over'); this.gameOverEl.find('.text').text('Score: '+ Math.round(this.total_y_vel)); //this.gameOverEl.css('visibility', 'visible'); if (this.gameOverEl.hasClass('center') === false) { this.gameOverEl.addClass('center'); } this.freezeGame(); //var game = this; //setTimeout(function() { // game.reset(); //}, 0); }; /** * Starts the game. */ Game.prototype.start = function() { this.reset(); }; /** * Freezes the game. Stops the onFrame loop and stops any CSS3 animations. * Can be used both for game over and pause. */ Game.prototype.freezeGame = function() { this.isPlaying = false; }; /** * Unfreezes the game. Starts the game loop again. */ Game.prototype.unfreezeGame = function() { if (!this.isPlaying) { this.isPlaying = true; // Restart the onFrame loop this.lastFrame = +new Date() / 1000; requestAnimFrame(this.onFrame); } }; /** * Cross browser RequestAnimationFrame */ var requestAnimFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(/* function */ callback) { window.setTimeout(callback, 1000 / 60); }; })(); return Game; });
import React from 'react' import data from '../../data' import Product from '../product' function HomeScreen() { return ( <div className="row center"> { data.products.map(product => { return <Product key={ product._id } product={product} /> } ) } </div> ) } export default HomeScreen
function sendCategory(category,sex) { var a=category var b=sex; window.location.href = "/ssm/index?category="+a+"&sex="+b; }
import { h } from 'preact'; import { useInView } from 'react-intersection-observer'; import Section from "./../../components/section" import style from './style.css'; const Wrapper = ({ initialInView, height, children }) => { const { ref, inView } = useInView({ // Add any options here (https://www.npmjs.com/package/react-intersection-observer#options) threshold: 0.3, triggerOnce: true, initialInView }) return ( <div ref={ref} style={{ height }}> {inView && children} </div> ) } const ReactIntersectionObserver = () => { return ( <div class={style.container}> <Wrapper initialInView={true}> <Section style={{ backgroundColor: "aquamarine" }} /> </Wrapper> <Wrapper height={"100vh"}> <Section style={{ backgroundColor: "coral" }} /> </Wrapper> <Wrapper height={"100vh"}> <Section style={{ backgroundColor: "blueviolet" }} /> </Wrapper> <Wrapper height={"100vh"}> <Section style={{ backgroundColor: "yellow" }} /> </Wrapper> <Wrapper height={"100vh"}> <Section style={{ backgroundColor: "goldenrod" }} /> </Wrapper> <Wrapper height={"100vh"}> <Section style={{ backgroundColor: "greenyellow" }} /> </Wrapper> </div> ); } export default ReactIntersectionObserver;
import React, {useEffect, useState} from 'react'; import { Row, Col } from 'antd'; import axios from 'axios'; import CategoryComponent from './CategoryComponent'; import ProductItem from './../../components/ProductItem'; import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; const CategoryPage = () => { const [categoryState, setCategoryState] = useState([]); useEffect(() => { axios({ method: "get", url: "http://localhost:3000/api/categorys" }) .then(res => { setCategoryState(res.data); console.log(res.data) }) },[]); return( <Row> <Col offset={2} span={20}> { categoryState.map(category => <CategoryComponent title={category.name} data={category.products} renderItem={(product) => <Link to={`/product/${product.id}`} style={{color: "black"}}> <ProductItem name={product.name} price={product.price} img={product.link_img} description={product.description} /> </Link> } /> ) } </Col> </Row> ) } export default CategoryPage;
const chai = require('chai') const chaiHttp = require('chai-http') const chaiSpies = require('chai-spies') const faker = require('faker') const { expect } = chai const UserController = require('../../../server/controllers/users') chai.use(chaiHttp) chai.use(chaiSpies) describe('Users controller', () => { let req = { user: { id: faker.random.number() }, value: { body: { email: faker.internet.email(), password: faker.internet.password(), } } } let res = { json: function() { return this }, status: function() { return this } } describe('signIn', () => { it('should return token when signIn called', () => { chai.spy.on(res, 'status', function(statusCode) { expect(statusCode).to.equal(200) return this }) chai.spy.on(res, 'json', function(resBody) { expect(resBody).to.be.an('object') expect(resBody).to.have.property('token') return this }) UserController.signIn(req, res) expect(res.status).is.spy expect(res.status).is.called.once expect(res.json).is.spy expect(res.json).is.called }) }) })
import * as store from "./store.js"; import * as ui from "./ui.js"; import * as webRTCHandler from "./webRTCHandler.js"; import * as constants from "./constants.js"; import * as strangerUtils from "./strangerUtils.js"; let socketIO = null; export const registerSocketEvents = (socket) => { socketIO = socket; socket.on("connect", () => { store.setSocketId(socket.id); ui.updatePersonalCode(socket.id); }); socket.on("connected-peers-status", (data) => { ui.updateStatus(data); }); socket.on("disconnect-status", (data) => { ui.updateStatus(data); }); socket.on("cluster-a-status", (data) => { ui.clusterAStatus(data); }); socket.on("cluster-b-status", (data) => { ui.clusterBStatus(data); }); socket.on("pre-offer", (data) => { webRTCHandler.handlePreOffer(data); }); socket.on("pre-offer-answer", (data) => { webRTCHandler.handlePreOfferAnswer(data); }); socket.on("user-hanged-up", () => { webRTCHandler.handleConnectedUserHangedUp(); }); socket.on("webRTC-signaling", (data) => { switch (data.type) { case constants.webRTCSignaling.OFFER: webRTCHandler.handleWebRTCOffer(data); break; case constants.webRTCSignaling.ANSWER: webRTCHandler.handleWebRTCAnswer(data); break; case constants.webRTCSignaling.ICE_CANDIDATE: webRTCHandler.handleWebRTCCandidate(data); break; default: return; } }); socket.on("stranger-socket-id", (data) => { strangerUtils.connectWithStranger(data); }); }; export const sendPreOffer = (data) => { socketIO.emit("pre-offer", data); }; export const sendPreOfferAnswer = (data) => { socketIO.emit("pre-offer-answer", data); }; export const sendDataUsingWebRTCSignaling = (data) => { socketIO.emit("webRTC-signaling", data); }; export const sendUserHangedUp = (data) => { socketIO.emit("user-hanged-up", data); }; // ClusterA 소켓 대기열에 추가 및 제거 export const changeClusterAConnectionStatus = (data) => { socketIO.emit("cluster-a-connection-status", data); }; // ClusterB 소켓 대기열 추가 및 제거 export const changeClusterBConnectionStatus = (data) => { socketIO.emit("cluster-b-connection-status", data); }; // ClusterA 소켓 대기열에서 소켓 얻기 export const getClusterASocketId = () => { socketIO.emit("get-cluster-a-socket-id"); }; // ClusterB 소켓 대기열에서 소켓 얻기 export const getClusterBSocketId = () => { socketIO.emit("get-cluster-b-socket-id"); }; // 요청 허용시 상태 False 상태 변경하기 export const changeCallStatusFalse = () => { socketIO.emit("change-call-status-false"); };
var express = require("express"); var app = express(); app.set("views", __dirname + "/views"); app.set("view engine", "ejs"); app.use(express.static(__dirname + "/static")); app.get("/cars", function (request, response){ response.render("cars"); }) app.get("/cats", function (request, response){ response.render("cats"); }) app.get("/dog1", function (request, response){ var dogArr = [ {name: "Rex", breed: "Pug", hobby: "sleep"} ] response.render("dogs", {dogs: dogArr}); }) app.get("/dog2", function (request, response){ var dogArr = [ {name: "Buddy", breed: "Golden Retriever", hobby: "smile"} ] response.render("dogs", {dogs: dogArr}); }) app.get("/cars/new", function (request, response){ response.render("form"); }) app.listen(8000, function(){ console.log("listening on port 8000"); })
/* eslint-disable strict, new-cap */ 'use strict'; const request = require('request'); const zlib = require('zlib'); const tar = require('tar'); const headers = { 'Accept-Encoding': 'gzip', }; request({ url: 'http://localhost:3000/download?fileId=123', headers }) .pipe(zlib.createGunzip()) // unzip .pipe(tar.Extract({ path: 'node_modules_test', strip: 1 })) .on('error', (err) => { console.log(err); });
import fetchMock from 'fetch-mock'; import * as Requests from 'services/requests'; describe('Services - Requests', () => { describe('requestGET', () => { const data = { name: 'Jim', gender: 'male' }; const url = 'test-url'; beforeEach(() => { fetchMock.get(url, data) }); afterEach(() => { fetchMock.restore(); }); test('Promise returns parsed data', done => { Requests.requestGET(url) .then(response => { expect(response).toEqual(data); done(); }) .catch(done.fail) }); }); });
const { gql } = require("apollo-server"); const bookQuery = gql` type QueryBook { books: [Book] } `;
const initialState = { keyword: "", category : "", surveys: [{'title':'d'},], error: null, } export default function surveys(state = initialState, action){ switch(action.type) { case "SELECT_CATEGORY" : return{...state, category : action.category}; case "SEARCH_SURVEY" : return{...state, keyword : action.keyword}; case "LOAD_SURVEY_SUCCESS" : return {...state, surveys :action.surveys}; case "LOAD_SURVEY_FAIL" : return {...state, error : action.error}; default : return state; } };
import React from "react"; import PropTypes from "prop-types"; import { Waypoint } from "react-waypoint"; import OompaCard from "./OompaCard"; import LoaderComponent from "./LoaderComponent"; const OompasGrid = ({ data, size, setSize, searchValue, isResultEmpty }) => { const handleNextPage = () => { const totalDataLength = data && data[0].total; if (totalDataLength === size || searchValue) return null; setSize(size + 1); }; if (isResultEmpty && searchValue) return ( <div className="flex justify-center pt-20 text-red-400 text-xl"> Please try again, no results were found. </div> ); if (!data.length) return ( <div className="flex justify-center"> <LoaderComponent /> </div> ); return ( <div className="grid grid-cols-3 gap-4 gap-y-8 pt-20 p-40"> {data.map((oompas) => oompas.results?.map((oompa) => ( <OompaCard key={oompa.id} oompa={oompa} /> )) )} <Waypoint onEnter={handleNextPage} /> <span data-cy="gridBottom" /> </div> ); }; OompasGrid.propTypes = { data: PropTypes.arrayOf(PropTypes.shape()), size: PropTypes.number, setSize: PropTypes.func, searchValue: PropTypes.string, isResultEmpty: PropTypes.bool, }; OompasGrid.defaultProps = { data: [], size: 0, setSize: () => {}, searchValue: "", isResultEmpty: false, }; export default OompasGrid;
const { injectBabelPlugin, getLoader } = require('react-app-rewired'); const path = require('path'); const theme = require('./theme') const fileLoaderMatcher = function(rule) { return rule.loader && rule.loader.indexOf(`file-loader`) != -1; } const resolve = function(dir) { return path.join(__dirname, '.', dir) } module.exports = function override(config, env) { config = injectBabelPlugin(['import', { libraryName: 'antd-mobile', style: true }], config); config.module.rules[1].oneOf.unshift({ test: /\.less$/, use: [ require.resolve('style-loader'), require.resolve('css-loader'), { loader: require.resolve('postcss-loader'), options: { // Necessary for external CSS imports to work // https://github.com/facebookincubator/create-react-app/issues/2677 ident: 'postcss', plugins: () => [ require('postcss-flexbugs-fixes'), autoprefixer({ browsers: [ '>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9', // React doesn't support IE8 anyway ], flexbox: 'no-2009', }), ], }, }, { loader: require.resolve('less-loader'), options: { // theme vars, also can use theme.js instead of this. modifyVars: theme, }, }, ] }); let l = getLoader(config.module.rules, fileLoaderMatcher); l.exclude.push(/\.less$/); config.resolve.alias = { '@': resolve('src'), 'components': resolve('src/components'), 'services': resolve('src/services'), 'styles': resolve('src/styles'), 'utils': resolve('src/utils'), 'views': resolve('src/views'), } return config; };
var http = require('http'); http.createServer((req, res) => { // 인자를 파싱한 url var _url; // method name을 소문자로 사용하는 client에 대해서 대문자로 통일 req.method = req.method.toUpperCase(); console.log(req.method + ' ' + req.url); res.end('The Current time is ' + Date.now()); }).listen(3000); console.log('Server running at http://localhost:3000/');
var searchData= [ ['q_5flevel',['q_level',['../structPagerRedrawData.html#aa4b6264cb3765622bc9592e1288481c4',1,'PagerRedrawData']]], ['qresync',['qresync',['../structImapAccountData.html#a65af7d98fa8ec32e0ce94505f11c1802',1,'ImapAccountData']]], ['quadvalues',['QuadValues',['../quad_8c.html#aa543c1d754d2ee8c48add8911f801f43',1,'QuadValues():&#160;quad.c'],['../quad_8h.html#aa543c1d754d2ee8c48add8911f801f43',1,'QuadValues():&#160;quad.c']]], ['quasi_5fdeleted',['quasi_deleted',['../structEmail.html#ae08999047328c1756061fa3453399b4b',1,'Email']]], ['query_5fstrings',['query_strings',['../structUrl.html#a30ca5136a9649e6df583a48cbdee35d2',1,'Url']]], ['query_5ftype',['query_type',['../structNmMboxData.html#a8851650d8d08c3490375ea41f4fe39d8',1,'NmMboxData']]], ['queryhelp',['QueryHelp',['../dlgquery_8c.html#a12d28b03eb265706a3c03ee5ff42c82d',1,'dlgquery.c']]], ['quote',['quote',['../structLine.html#ad9dda57834117eb0598816db9e9833c0',1,'Line']]], ['quote_5flist',['quote_list',['../structPagerRedrawData.html#af899ef2b9ee182ed1ddb9525e7d18034',1,'PagerRedrawData']]], ['quotes',['quotes',['../structColors.html#a4b6f5612828b483a1bbaf41542e1d950',1,'Colors']]], ['quotes_5fused',['quotes_used',['../structColors.html#ac845965ecb1c215ebc5120e7d8036093',1,'Colors']]] ];
import React from 'react'; import ReactHowler from 'react-howler'; import music from "assets/backgroundMusic.mp3"; class BackgroundMusic extends React.Component{ constructor(props){ super(props); } // This sound file may not work due to cross-origin setting render () { const { mute } = this.props; return ( <ReactHowler mute={mute} src={music} playing={true} loop={true} /> ) } } export default BackgroundMusic;
/* Sum the numbers Write a function sumNumbers which is given an array of numbers and returns the sum of the numbers. > sumNumbers([1, 4, 8]) 13 */ function sumNumbers(numbers) { let sum = 0; for (let i = 0; i < numbers.length; i++) { sum += numbers[i]; } return sum; } //console.log(sumNumbers([1,2,3,4,5]));
/* eslint-disable react/prefer-stateless-function */ // Won't be stateless for long. import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Redirect } from 'react-router-dom'; import SidebarNavigator from '../../core/components/SidebarNavigator'; import UserDetailsHeader from '../../user/components/UserDetailsHeader'; import EventModal from '../components/EventModal'; import AssignmentModal from '../components/AssignmentModal'; import EventList from '../components/EventsList'; import GanttDisplay from '../components/GanttDisplay'; import CompletedList from '../components/CompletedList'; import ModulesList from '../components/ModulesList'; import UsersList from '../components/UsersList'; import UserModal from '../components/UserModal'; import ModulesModal from '../components/ModulesModal'; import ClassModal from '../components/ClassModal'; class Dashboard extends Component { editEvent = (event = undefined) => { if (this.eventModal) { if (this.activityDropDown) { this.activityDropDown.close(); } this.eventModal.open(event); } } editModule = (module = undefined) => { if (this.modulesModal) { this.modulesModal.open(module); } } addUser = () => { if (this.userModal) { this.userModal.open(); } } viewUser = (user) => { if (this.userModal) { this.userModal.open(user); } } editAssignment = (assignment = undefined) => { if (this.assignmentModal) { if (this.assignmentSettingsDropDown) { this.assignmentSettingsDropDown.close(); } this.assignmentModal.open(assignment); } } editClass = (classEvent = undefined) => { if (this.classModal) { this.classModal.open(classEvent); } } render() { if (!this.props.board.currentBoard) { return <Redirect to="/boards" />; } return ( <> <SidebarNavigator> <div> <UserDetailsHeader /> <div className="container-fluid"> <div className="main-display"> <div className="row"> <div className="col-lg-4"> <div className="box"> <div className="box-content"> <div className="box-header"> <p className="header">Upcoming Assignments</p> <div className="ico-container" id="assign-drop-btn" onClick={() => this.editAssignment()}> <i className="fas fa-plus" /> </div> </div> <div className="list-container"> <EventList type="Assignment" placeholder="No upcoming assignments" onPressEvent={this.editAssignment} /> </div> </div> </div> </div> <div className="col-lg-4"> <div className="box"> <div className="box-content"> <div className="box-header"> <p className="header">Upcoming Events</p> <div className="ico-container" id="assign-drop-btn" onClick={() => this.editEvent()}> <i className="fas fa-plus" /> </div> </div> <div className="list-container"> <ul className="activities"> <EventList placeholder="No upcoming events" onPressEvent={this.editEvent} /> </ul> </div> </div> </div> </div> <div className="col-lg-4"> <div className="box"> <div className="box-content"> <div className="box-header"> <p className="header">Upcoming Classes</p> <div className="ico-container" onClick={() => this.editClass()}> <i className="fas fa-plus" /> </div> </div> <div className="list-container"> <EventList type="Class" placeholder="No upcoming classes" onPressEvent={this.editClass} /> </div> </div> </div> </div> </div> <div className="row"> <div className="col-lg-4"> <div className="box"> <div className="box-content"> <div className="box-header"> <p className="header">Modules</p> <div className="ico-container" id="assign-drop-btn" onClick={this.editModule}> <i className="fas fa-plus" /> </div> </div> <div className="list-container upcoming"> <ModulesList onPressEvent={this.editModule} /> </div> </div> </div> </div> <div className="col-lg-4"> <div className="box"> <div className="box-content"> <div className="box-header"> <p className="header">Users</p> <div className="ico-container" id="assign-drop-btn" onClick={this.addUser}> <i className="fas fa-plus" /> </div> </div> <div className="list-container upcoming"> <UsersList onPressUser={this.viewUser} /> </div> </div> </div> </div> </div> <div className="row"> <div className="col-lg-12"> <div className="box gantt-box non-mobile"> <div className="box-content"> <GanttDisplay /> </div> </div> </div> </div> <div className="row"> <div className="col-lg-12"> <div className="box non-mobile"> <div className="box-content"> <CompletedList /> </div> </div> </div> </div> </div> </div> </div> </SidebarNavigator> <EventModal ref={(eventModal) => { this.eventModal = eventModal; }} /> <AssignmentModal ref={(assignmentModal) => { this.assignmentModal = assignmentModal; }} /> <UserModal ref={(userModal) => { this.userModal = userModal; }} /> <ModulesModal ref={(modulesModal) => { this.modulesModal = modulesModal }} /> <ClassModal ref={(classModal) => { this.classModal = classModal }} /> </> ); } } const mapStateToProps = ({ board }) => ({ board }); export default connect(mapStateToProps)(Dashboard);
home_animation = (function() { var endFrame = 0; function init() { document.getElementById("container").style.display = "block"; TweenLite.to(bg, 0, {scaleX:1, scaleY:1}); frame1(); } function frame1() { TweenLite.to(first_text, 1.4, {opacity:0, top:-300, delay: 3}); TweenLite.to(product_text, .6, {top:-17, scaleX:.72, scaleY:.72, delay:3}); TweenLite.to(bg, .6, {top:-110, scaleX:.9, scaleY:.9, delay:3}); TweenLite.delayedCall(3, frame2); } function frame2() { // slide up white bg TweenLite.to(white_BG, .6, {top:420}); TweenLite.to(logo, 1, {opacity:1, delay:.9}); TweenLite.to(second_text, 3, {opacity:1, delay:1.4, ease: Expo.easeOut}); TweenLite.to(third_text, 4, {opacity:1, delay:2.6, ease: Expo.easeOut}); TweenLite.delayedCall(4.5, frame3); } function frame3() { endFrame = 1; TweenLite.to(buy_now, 0.5, {opacity:1, delay:0}); } container.onmouseover = function() { if(endFrame == 1) { TweenLite.to(buy_now_over, 0.2, {opacity:1}); TweenLite.to(buy_now, 0.2, {opacity:0}); } } container.onmouseout = function() { if(endFrame == 1) { TweenLite.to(buy_now_over, 0.2, {opacity:0}); TweenLite.to(buy_now, 0.2, {opacity:1}); } } init(); }); // If true, start function. If false, listen for INIT. window.onload = function() { home_animation(); }
app.service('ModalProvider', ['$uibModal', '$log', '$rootScope', function ($uibModal, $log, $rootScope) { /************************************************************** * * * Customer Model * * * *************************************************************/ this.openCustomerCreateModel = function () { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: '/ui/partials/customer/customerCreateUpdate.html', controller: 'customerCreateUpdateCtrl', backdrop: 'static', keyboard: false, resolve: { title: function () { return $rootScope.lang === 'AR' ? 'انشاء حساب عميل جديد' : 'New Customer'; }, action: function () { return 'create'; }, customer: function () { return {}; } } }); }; this.openCustomerUpdateModel = function (customer) { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: '/ui/partials/customer/customerCreateUpdate.html', controller: 'customerCreateUpdateCtrl', backdrop: 'static', keyboard: false, resolve: { title: function () { return $rootScope.lang === 'AR' ? 'تعديل حساب عميل' : 'Update Customer Information'; }, action: function () { return 'update'; }, customer: function () { return customer; } } }); }; this.openCustomerDetailsModel = function (customer) { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: '/ui/partials/customer/customerDetails.html', controller: 'customerDetailsCtrl', backdrop: 'static', keyboard: false, size: 'lg', resolve: { customer: function () { return customer; } } }); }; this.openCustomerPaymentsSummaryReportModel = function () { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: "/ui/partials/report/customer/paymentsSummary.html", controller: "paymentsSummaryCtrl", backdrop: 'static', keyboard: false }); }; this.openCustomerPaymentsDetailsReportModel = function () { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: "/ui/partials/report/customer/paymentsDetails.html", controller: "paymentsDetailsCtrl", backdrop: 'static', keyboard: false }); }; /************************************************************** * * * Supplier Model * * * *************************************************************/ this.openSupplierCreateModel = function () { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: '/ui/partials/supplier/supplierCreateUpdate.html', controller: 'supplierCreateUpdateCtrl', backdrop: 'static', keyboard: false, resolve: { title: function () { return $rootScope.lang === 'AR' ? 'انشاء حساب تاجر جديد' : 'New Supplier'; }, action: function () { return 'create'; }, supplier: function () { return {}; } } }); }; this.openSupplierUpdateModel = function (supplier) { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: '/ui/partials/supplier/supplierCreateUpdate.html', controller: 'supplierCreateUpdateCtrl', backdrop: 'static', keyboard: false, resolve: { title: function () { return $rootScope.lang === 'AR' ? 'تعديل حساب تاجر' : 'Update Supplier Information'; }, action: function () { return 'update'; }, supplier: function () { return supplier; } } }); }; this.openSupplierReceiptInCreateModel = function () { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: '/ui/partials/supplier/supplierReceiptCreate.html', controller: 'supplierReceiptCreateCtrl', backdrop: 'static', keyboard: false, resolve: { receiptType: function () { return 'In'; } } }); }; this.openSupplierReceiptOutCreateModel = function () { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: '/ui/partials/supplier/supplierReceiptCreate.html', controller: 'supplierReceiptCreateCtrl', backdrop: 'static', keyboard: false, resolve: { receiptType: function () { return 'Out'; } } }); }; this.openSupplierBalanceSummaryReportModel = function () { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: "/ui/partials/report/supplier/balanceSummary.html", controller: "balanceSummaryCtrl", backdrop: 'static', keyboard: false }); }; this.openSupplierCustomersListReportModel = function () { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: "/ui/partials/report/supplier/customersList.html", controller: "customersListCtrl", backdrop: 'static', keyboard: false }); }; /************************************************************** * * * Contract Model * * * *************************************************************/ this.openContractCreateModel = function () { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: '/ui/partials/contract/contractCreateUpdate.html', controller: 'contractCreateUpdateCtrl', backdrop: 'static', keyboard: false, size: 'lg', resolve: { title: function () { return $rootScope.lang === 'AR' ? 'انشاء عقد جديد' : 'New Contract'; }, action: function () { return 'create'; }, contract: function () { return {}; } } }); }; this.openContractUpdateModel = function (contract) { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: '/ui/partials/contract/contractCreateUpdate.html', controller: 'contractCreateUpdateCtrl', backdrop: 'static', keyboard: false, size: 'lg', resolve: { title: function () { return $rootScope.lang === 'AR' ? 'تعديل عقد' : 'Update Contract Information'; }, action: function () { return 'update'; }, contract: function () { return contract; } } }); }; this.openReceiptCreateByContractModel = function (contract) { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: '/ui/partials/contract/receiptCreateByContract.html', controller: 'receiptCreateByContractCtrl', backdrop: 'static', keyboard: false, resolve: { contract: function () { return contract; } } }); }; this.openContractReceiptInCreateModel = function () { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: '/ui/partials/contract/contractReceiptCreate.html', controller: 'contractReceiptCreateCtrl', backdrop: 'static', keyboard: false, resolve: { receiptType: function () { return 'In'; } } }); }; /************************************************************** * * * Employee Model * * * *************************************************************/ this.openEmployeeCreateModel = function () { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: '/ui/partials/employee/employeeCreateUpdate.html', controller: 'employeeCreateUpdateCtrl', backdrop: 'static', keyboard: false, size: 'lg', resolve: { title: function () { return $rootScope.lang === 'AR' ? 'انشاء حساب موظف جديد' : 'New Employee'; }, action: function () { return 'create'; }, employee: function () { return {}; } } }); }; this.openEmployeeUpdateModel = function (employee) { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: '/ui/partials/employee/employeeCreateUpdate.html', controller: 'employeeCreateUpdateCtrl', backdrop: 'static', keyboard: false, size: 'lg', resolve: { title: function () { return $rootScope.lang === 'AR' ? 'تعديل حساب موظف' : 'Update Employee Information'; }, action: function () { return 'update'; }, employee: function () { return employee; } } }); }; /************************************************************** * * * Team Model * * * *************************************************************/ this.openTeamCreateModel = function () { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: '/ui/partials/team/teamCreateUpdate.html', controller: 'teamCreateUpdateCtrl', backdrop: 'static', keyboard: false, size: 'lg', resolve: { title: function () { return $rootScope.lang === 'AR' ? 'انشاء مجموعة جديدة' : 'New Team'; }, action: function () { return 'create'; }, team: function () { return undefined; } } }); }; this.openTeamUpdateModel = function (team) { return $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: '/ui/partials/team/teamCreateUpdate.html', controller: 'teamCreateUpdateCtrl', backdrop: 'static', keyboard: false, size: 'lg', resolve: { title: function () { return $rootScope.lang === 'AR' ? 'تعديل بيانات مجموعة' : 'Update Team'; }, action: function () { return 'update'; }, team: function () { return team; } } }); }; }]); app.service('NotificationProvider', ['$http', function ($http) { this.notifyOne = function (code, title, message, type, receiver) { $http.post("/notifyOne?" + 'code=' + code + '&' + 'title=' + title + '&' + 'message=' + message + '&' + 'type=' + type + '&' + 'receiver=' + receiver); }; this.notifyAll = function (code, title, message, type) { $http.post("/notifyAll?" + 'code=' + code + '&' + 'title=' + title + '&' + 'message=' + message + '&' + 'type=' + type ); }; this.notifyAllExceptMe = function (code, title, message, type) { $http.post("/notifyAllExceptMe?" + 'code=' + code + '&' + 'title=' + title + '&' + 'message=' + message + '&' + 'type=' + type ); }; }]);
const chalk = require('chalk'); module.exports = function(){ console.log(chalk.yellow( `EXERCISE 9: Write a function called "sumTo100" that takes a parameter called "num" and returns the sum of that number and all other numbers up to, and including, 100. For example: sumTo100(100) should return 100 sumTo100(99) should return 199 sumTo100(98) should return 297 ` )); process.exit(); };
exports.printMsg= function() { console.log("Hello World - GCI 2017"); }
'use strict'; const path = require('path'); const nopt = require('nopt'); const utils = require('./utils'); const vars = require('./vars'); const run = require('./run'); const npmconf = require('../node_modules/npm/lib/config/core.js'); const npmCommands = {i: true, install: true}; module.exports = function (args) { if(!Array.isArray(args) || args.lengh < 4) { return; } var name = args[2].trim(), defs = npmconf.defs, conf = nopt(defs.types, defs.shorthands), rem = conf.argv.remain, argv; if(npmCommands[name] && rem.length > 0) { argv = utils.map(utils.slice(rem, 1), function (item, index) { return path.join(vars.path, item); }); run(rem[0], conf, argv); } };
import React from 'react'; import { connect } from 'react-redux'; import { fetchCoinChart } from '../actions'; import { selectDuration } from '../actions'; import * as d3 from 'd3'; class CoinChart extends React.Component { componentDidMount() { this.props.fetchCoinChart(this.props.cid, this.props.duration); } componentDidUpdate(prevProps) { if (prevProps.duration !== this.props.duration) { this.props.fetchCoinChart(this.props.cid, this.props.duration) } } render() { d3.select('#chart-container') .select('svg') .remove(); d3.select('#chart-container') .select('.svg-container') .remove(); d3.select('#chart-container') .select('.tooltip') .remove(); const renderChart = (data, width, height) => { const margin = { top: 50, right: 50, bottom: 50, left: 50 }; const yMinValue = d3.min(data, d => d.value); const yMaxValue = d3.max(data, d => d.value); const xMinValue = d3.min(data, d => d.label); const xMaxValue = d3.max(data, d => d.label); const svg = d3 .select('#chart-container') .append("div") .classed("svg-container", true) .append('svg') .attr("preserveAspectRatio", "xMinYMin meet") .attr("viewBox", `0 0 ${width + margin.left + margin.right} ${height + margin.top + margin.bottom}`) .classed("svg-content-responsive", true) .attr('width', width + margin.left + margin.right) .attr('height', height + margin.top + margin.bottom) .append('g') .attr('transform', `translate(${margin.left},${margin.top})`); const tooltip = d3 .select('#chart-container') .append('div') .attr('class', 'tooltip'); const xScale = d3 .scaleLinear() .domain([xMinValue, xMaxValue]) .range([0, width]); const yScale = d3 .scaleLinear() .range([height, 0]) .domain([yMinValue, yMaxValue]); const line = d3 .line() .x(d => xScale(d.label)) .y(d => yScale(d.value)) .curve(d3.curveMonotoneX); svg .append('g') .attr('class', 'grid') .attr('transform', `translate(0,${height})`) .call( d3.axisBottom(xScale) .tickSize(-height) .tickFormat(''), ); svg .append('g') .attr('class', 'grid') .call( d3.axisLeft(yScale) .tickSize(-width) .tickFormat(''), ); svg .append('g') .attr('class', 'x-axis') .attr('transform', `translate(0,${height})`) .call(d3.axisBottom().scale(xScale).tickSize(15)); svg .append('g') .attr('class', 'y-axis') .call(d3.axisLeft(yScale)); svg .append('path') .datum(data) .attr('fill', 'none') .attr('stroke', '#45b4f5') .attr('stroke-width', 4) .attr('class', 'line') .attr('d', line); const focus = svg .append('g') .attr('class', 'focus') .style('display', 'none'); focus.append('circle').attr('r', 5).attr('class', 'circle'); svg .append('rect') .attr('class', 'overlay') .attr('width', width) .attr('height', height) .style('opacity', 0) .on('mouseover', () => { focus.style('display', null); }) .on('mouseout', () => { tooltip .transition() .duration(300) .style('opacity', 0); }) .on('mousemove', mousemove); function mousemove(event) { const bisect = d3.bisector(d => d.label).left; const xPos = d3.pointer(event)[0]; const x0 = bisect(data, xScale.invert(xPos)); const d0 = data[x0]; focus.attr( 'transform', `translate(${xScale(d0.label)},${yScale(d0.value)})`, ); tooltip .transition() .duration(300) .style('opacity', 0.9); tooltip .html(d0.tooltipContent || d0.label) .style( 'transform', `translate(${xScale(d0.label) - 30}px,${yScale(d0.value) - 600}px)`, ) .style( 'height', 0, ); } tooltip .on('mouseover', function(d){ tooltip.transition().style("opacity", "1"); }) .on('mouseout', function(d) { tooltip.transition().duration(1000).style("opacity", "0"); }); } const normalizeData = (data) => { if (!data) return null; let dataArr = []; data.map((d) => { let date = new Date(d[0]/1000).toString(); dataArr.push({ label: d[0], value: d[1], tooltipContent: `$${d[1]}` }) }) return dataArr; } if (this.props.data.prices) { renderChart(normalizeData(this.props.data.prices), 1100, 500) } const durations = [ {name: '24H', value: 1}, {name: '14D', value: 14}, {name: '1M', value: 30}, {name: '3M', value: 90}, {name: '1Y', value: 365}, {name: 'ALL', value: 'max'}, ] return ( <div className="coin-chart"> <div className="chart-controls"> {durations.map((d, index) => { let selected = d.value === this.props.duration ? 'selected' : ''; return ( <button key={index} onClick={() => { this.props.selectDuration(d.value) }} className={`duration-button ${selected}`} > {d.name} </button> ) })} </div> <div id="chart-container" className="chart-container"></div> </div> ); } } const mapStateToProps = (state, ownProps) => { return { data: state.chartData, duration: state.chartDuration } } export default connect(mapStateToProps, { fetchCoinChart, selectDuration })(CoinChart);
import render from './render.js'; import ingredients from './ingredients.js'; import ingredientToOption from './ingredient_to_option.js'; import { addPizza } from './pizza_management.js'; const options = ()=> ingredients.map(ingredientToOption).join('\n'); const formHTML = ` <form> <h2>Create your own pizza</h2> <input name="pizza_name" placeholder="pizza name" /> <select multiple name="pizza_ingredients" > ${options()} </select> <button class="submit_pizza">Add pizza</button> </form> `; const readInputs = function(event){ event.preventDefault(); let name = event.target.querySelector('input[name="pizza_name"]').value; let ingredients_select = event.target.querySelector('select[name="pizza_ingredients"]') let ingredients = [...ingredients_select.options].filter(option => option.selected).map(option => option.value); addPizza({ name, ingredients }); }; export default function(){ render(formHTML,'form'); document.querySelector('form').addEventListener('submit', readInputs); }
const {StyledPageTagsDialog} = require("./PageTagsDialog.style"); import DialogContent from "~/components/atoms/dialog/DialogContent"; import {Grid, ListItem} from "@material-ui/core"; import Table from "@material-ui/core/Table"; import TableBody from "@material-ui/core/TableBody"; import TableHead from "@material-ui/core/TableHead"; import TableRow from "@material-ui/core/TableRow"; import TableCell from "@material-ui/core/TableCell"; import List from "~/components/atoms/list/List"; import {FontAwesomeIcon} from "@fortawesome/react-fontawesome"; import Api from "~/util/api"; import {useEffect, useState} from "react"; import {useRecoilState} from "recoil"; import {messageboxState} from "~/components/molecules/Messagebox/MessageboxAtom"; import MessageboxStoreManager from "~/components/molecules/Messagebox/MessageboxFactory"; import LoadingIndicator from "~/components/atoms/loadingIndicator/LoadingIndicator"; import VariableRow from "~/components/organisms/VariableSelector/VariableRow"; import Button from "~/components/atoms/button/Button"; import TagSelector from "~/components/organisms/TagSelector/TagSelector"; const PageTagsDialog = function (props) { const messageboxStateAtom = useRecoilState(messageboxState); const [loading, setLoading] = useState(false); const [variables, setVariables] = useState(null); const [selectedTag, setSelectedTag] = useState(null); const [showTagSelectorDialog, setShowTagSelectorDialog] = useState(false); const toggleTagSelectorDialog = () => setShowTagSelectorDialog(!showTagSelectorDialog); const api = new Api({ onLoad: () => setLoading(true), onFinished: () => setLoading(false), }); useEffect(() => { if (selectedTag) { (async () => { const response = await api.fetch({ endpoint: api.endpoints.getVariables, urlReplacements: [["tag", selectedTag]], }); if (!response.success) { MessageboxStoreManager.AddMessage(messageboxStateAtom, response.message); return; } setVariables(response.result); })(); } }, [selectedTag]); const handleTagSelect = (tag, input, customInput) => { console.log(tag, input, customInput); }; const insertRow = (variableName, variableValue, variableChainName, key) => { return <VariableRow readonly onSelect={props.onSelect} key={key} name={`${variableChainName}.${variableName}`} value={variableValue} />; }; let availableInputs = [...props.page.urlTags]; availableInputs.push("*"); return ( <> <StyledPageTagsDialog open={true} title="Beschikbare bronnen"> <DialogContent bottomMargin> <Grid container> <Grid item> <div className="item-selector"> <List noPaddingTop> {props.page.urlTags.map((tag, key) => { return ( <ListItem key={key} className="list-item" button onClick={() => setSelectedTag(tag)}> <FontAwesomeIcon icon={["fal", "tag"]} className="list-icon" /> {tag} </ListItem> ); })} </List> <div className="button-wrapper"> <Button variant="outlined" onClick={toggleTagSelectorDialog}> Bron toevoegen </Button> </div> </div> </Grid> <Grid item className="variable-selector"> {loading && <LoadingIndicator />} {variables && ( <div className="table-wrapper"> <Table stickyHeader aria-label="sticky table" size="small"> <TableHead> <TableRow> <TableCell className="property">Variabele</TableCell> <TableCell className="type">Type</TableCell> <TableCell>Voorbeeld</TableCell> </TableRow> </TableHead> <TableBody> {Object.keys(variables).map((variable, key) => { return insertRow(variable, variables[variable], selectedTag, key); })} </TableBody> </Table> </div> )} </Grid> </Grid> </DialogContent> </StyledPageTagsDialog> {showTagSelectorDialog && <TagSelector input={availableInputs} onTagSelect={handleTagSelect} onClose={toggleTagSelectorDialog} />} </> ); }; export default PageTagsDialog;
import Navbar from './nav' import Plot from './plots' import About from './about' import MyForm from './form' import Footer from './footer' function App() { return ( <div className="App"> <Navbar/> <Plot/> <About/> <MyForm/> <Footer/> </div> ); } export default App;
import React from 'react' import ReactPlayer from "react-player"; import Grid from "@material-ui/core/Grid"; import GreenButton from '../GreenBtn' import withRouter from "react-router/es/withRouter"; import './style.css' import WOW from 'wow.js' class GiftComponent extends React.Component { state = { videoHidden: true }; componentDidMount() { new WOW().init() } handleCloseError = () => { this.props.history.push("/") }; videoIsReady = () => { this.setState({videoHidden: false}) }; render() { return ( <Grid container justify="center" id="giftGrid"> <Grid item className="wow bounceIn" hidden={this.state.videoHidden}> <ReactPlayer url={this.props.gift.videoUrl} controls width="100%" height="auto" onReady={this.videoIsReady}/> </Grid> <Grid item xs={12} className="wow bounceInDown"> <GreenButton id="gotoBtn" color="primary" variant="contained" onClick={this.handleCloseError}>Go to Gift Of Charity</GreenButton> </Grid> </Grid> ); } } export default withRouter(GiftComponent)
/** * Created by StarkX on 08-Apr-18. */ const mongoose = require('mongoose'); const Token = require('../schema/tokenSchema'); const tokenGenerator = require('../../lib/tokenGenerator'); Token.statics.getAccessToken = (bearerToken) => { return tokenModel .findOne({ accessToken : bearerToken }) .populate('user') .populate('client') .catch((err) => { if (xConfig.debugMode) console.log("getAccessToken - Err: ", err); }); }; Token.statics.generate = (client, user, scope) => { return tokenGenerator(); }; Token.statics.revokeToken = (token) => { return tokenModel.findOne({ refreshToken : token.refreshToken }) .then((rT) => { if (rT) return rT.remove(); }) .then(() => { let expiredToken = token; expiredToken.refreshTokenExpiresAt = new Date('1996-05-9T06:59:53.000Z'); return expiredToken; }).catch((err) => { if (xConfig.debugMode) console.log("revokeToken - Err: ", err) }); }; Token.statics.getRefreshToken = (refreshToken) => { return tokenModel .findOne({ refreshToken : refreshToken }) .populate('user') .populate('client') .then((token) => { if (!token) return false; token.refresh_token = token.refreshToken; return token; }).catch((err) => { if (xConfig.debugMode) console.log("getRefreshToken - Err: ", err) }); }; Token.statics.saveToken = (token, client, user) => { return tokenModel.create({ accessToken : token.accessToken, accessTokenExpiresAt : token.accessTokenExpiresAt, refreshToken : token.refreshToken, refreshTokenExpiresAt : token.refreshTokenExpiresAt, client : client._id, user : user._id, scope : token.scope }).then(() => { return Object.assign({ client : client, user : user, accessToken : token.accessToken, refreshToken : token.refreshToken, }, token); }).catch((err) => { if (xConfig.debugMode) console.log("revokeToken - Err: ", err) }); }; module.exports = tokenModel = mongoose.model('Token', Token);
var Service = require('node-linux').Service; // Create a new service object var svc = new Service({ name:'Vandelay', description: 'Vandelay-Inspector', script:'../../server.js', }); // Listen for the install event, which indicates that the process is available as a service. svc.on('install',function(){ svc.start(); }); svc.install();
/* eslint-disable no-param-reassign */ import { fromJS } from 'immutable' import { createReducer } from 'bypass/utils/index' import { toObject, timeConverter, parseBins, unformatSearch, SearchState } from 'bypass/app/utils/utils' import * as actions from '../constants' const initialState = fromJS({ showSearch: false, presearch: { sort_column: [], }, search: { ...SearchState, }, result: { show: false, list: [], offset: 0, perpage: 50, total: 0, search_col: [], }, }) const getLoadText = load => [ timeConverter(load.add_time, false, true), `(${load.available} ${__i18n('COM.COUNT')})`, (load.valid ? `(${parseFloat(load.valid).toFixed(2)}%)` : ''), ].join(' ') const getValidText = item => [ item.name, (item.valid ? `(${parseFloat(item.valid).toFixed(2)}%)` : ''), ].join(' ') export default createReducer(initialState, { [actions.presearch]: (state, { presearch }) => { const data = Object.keys(presearch).reduce((result, key) => { if (key === 'search') { result[key] = presearch[key].map(item => { try { return { ...item, ...JSON.parse(item.search_string), } } catch (error) { return initialState.get('search').merge(fromJS(item)) } }) } if (key === 'sort_column') { result[key] = presearch[key].map(column => ({ column })) } if (!(presearch[key].map && presearch[key].data)) { return result } const values = toObject(presearch[key].map, presearch[key].data) if (key === 'load') { result[key] = values.map(item => ({ ...item, text: getLoadText(item) })) } else if (key === 'base') { result[key] = values.map(item => ({ ...item, text: getValidText(item) })) } else if (key === 'seller') { result[key] = values.map(item => ({ ...item, text: getValidText(item) })) } else { result[key] = values } return result }, presearch) const [search] = data.search.filter(searchItem => searchItem.def == 1) // eslint-disable-line eqeqeq if (search) { const currentSearch = { ...unformatSearch(search), search_id: search.search_id, search_name: search.search_name, def: search.def, } return state.set('presearch', fromJS(data)) .set('search', initialState.get('search').merge(currentSearch)) } return state.set('presearch', fromJS(data)) }, [actions.changeFilter]: (state, { filter, value }) => { if (filter === 'bin') { return state.setIn(['search', filter, 'value'], fromJS(parseBins(value))) } else if (filter === 'valid') { return state.mergeIn(['search', 'valid'], fromJS({ ...value, touched: !(value.from == 0 && value.to == 100), // eslint-disable-line eqeqeq })) } else if (filter === 'zipMask') { return state.setIn(['search', 'zip', 'mask'], value) } else if (filter === 'sortOrder') { return state.setIn(['search', 'sort', 'order'], value) .setIn(['search', 'sort', 'touched'], true) } else if (filter === 'sortDirection') { return state.setIn(['search', 'sort', 'direction'], value) .setIn(['search', 'sort', 'touched'], true) } else if (filter === 'dates') { return state.mergeIn(['search', 'dates'], fromJS({ ...value, touched: true, })) } return state.setIn(['search', filter, 'value'], fromJS(value)) }, [actions.inverseFilter]: (state, { filter, value }) => state.setIn(['search', filter, 'inversed'], value), [actions.showSearch]: state => state.set('showSearch', true), [actions.hideSearch]: state => state.set('showSearch', false), [actions.clearSearch]: state => state.set('search', initialState.get('search')), [actions.search]: (state, { search }) => { const count = parseInt(search.count, 10) const limit = parseInt(search.limit, 10) const total = count > limit ? limit : count return state.set('showSearch', false) .mergeIn(['result'], fromJS({ ...search, show: true, total, list: search.data, search_col: search.search_col.filter(column => column !== 'brand'), })) }, [actions.loadSearch]: (state, { search }) => { const list = state.getIn(['result', 'list']) const count = parseInt(search.count, 10) const limit = parseInt(search.limit, 10) const total = count > limit ? limit : count return state.mergeIn(['result'], fromJS({ ...search, checkTimeout: search.check_timeout, total, list: list.concat(fromJS(search.data)), search_col: search.search_col.filter(column => column !== 'brand'), allSelected: false, })) }, [actions.loadSearchPage]: (state, { search }) => { const count = parseInt(search.count, 10) const limit = parseInt(search.limit, 10) const total = count > limit ? limit : count const data = search.data.map((item, index) => ({ ...item, index: search.offset + index + 1, })) return state.mergeIn(['result'], fromJS({ ...search, checkTimeout: search.check_timeout, list: fromJS(data), search_col: search.search_col.filter(column => column !== 'brand'), total, allSelected: false, })) }, [actions.selectSearchRow]: (state, { row }) => { const index = state.getIn(['result', 'list']) .findIndex(item => item.get('card_id') === row.get('card_id')) if (index !== -1) { const updated = state.setIn(['result', 'list', index, 'selected'], !row.get('selected')) return updated.setIn( ['result', 'hasSelected'], updated.getIn(['result', 'list']) .some(item => item.get('selected')) ).setIn( ['result', 'allSelected'], false ) } return state }, [actions.selectSearchRows]: state => { const selected = !state.getIn(['result', 'allSelected']) return state.setIn(['result', 'list'], state.getIn(['result', 'list']).map(item => item.set('selected', selected))) .setIn(['result', 'allSelected'], selected) .setIn(['result', 'hasSelected'], selected) }, [actions.unselectCards]: state => state .setIn(['result', 'allSelected'], false) .setIn(['result', 'hasSelected'], false) .setIn( ['result', 'list'], state.getIn(['result', 'list']) .map(item => item.set('selected', false)) ), [actions.complete]: (state, { field, result }) => { let data = result if (field === 'address') { data = result.map(address => ({ ...address, label: address.address, value: address.address })) } else if (field === 'city') { data = result.map(city => ({ ...city, label: city.city, value: city.city })) } else if (field === 'zip') { data = result.map(zip => ({ ...zip, label: zip.zip, value: zip.zip })) } else if (field === 'bank') { data = result.map(bank => ({ ...bank, label: bank.bank, value: bank.bank })) } return state.setIn(['presearch', field, 'value'], fromJS(data)) }, [actions.clear]: state => state.merge(initialState), [actions.createSearch]: (state, { result }) => { const parsed = result.map(item => { try { return { ...item, ...JSON.parse(item.search_string), } } catch (error) { return initialState.get('search').merge(fromJS(item)) } }) return state.setIn(['presearch', 'search'], fromJS(parsed)) }, [actions.updateDefaultSearch]: (state, { value }) => state.setIn(['search', 'def'], value), [actions.applySearch]: (state, { searchId }) => { const search = state.getIn(['presearch', 'search']).find(item => item.get('search_id') === searchId) if (search) { const data = search.toJS() const current = { ...unformatSearch(data), search_id: data.search_id, search_name: data.search_name, def: data.def, } return state.set('search', initialState.get('search').merge(current)) } return state }, [actions.refreshSearch]: (state, { result }) => { const search = result.map(item => { try { return { ...item, ...JSON.parse(item.search_string), } } catch (error) { return initialState.get('search').merge(fromJS(item)) } }) return state.setIn(['presearch', 'search'], fromJS(search)) }, })
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const fs = require("fs"); const path = require("path"); exports.systems = {}; function shouldIgnoreFolder(pluginName) { return pluginName.indexOf(".") !== -1 || pluginName === "node_modules"; } class System { constructor(id, folderName) { this.id = id; this.folderName = folderName; this.plugins = {}; this.data = new SystemData(this); } requireForAllPlugins(filePath) { const pluginsPath = path.resolve(`${SupCore.systemsPath}/${this.folderName}/plugins`); for (const pluginAuthor of fs.readdirSync(pluginsPath)) { const pluginAuthorPath = `${pluginsPath}/${pluginAuthor}`; if (shouldIgnoreFolder(pluginAuthor)) continue; for (const pluginName of fs.readdirSync(pluginAuthorPath)) { if (shouldIgnoreFolder(pluginName)) continue; const completeFilePath = `${pluginAuthorPath}/${pluginName}/${filePath}`; if (fs.existsSync(completeFilePath)) { /* tslint:disable */ require(completeFilePath); /* tslint:enable */ } } } } registerPlugin(contextName, pluginName, plugin) { if (this.plugins[contextName] == null) this.plugins[contextName] = {}; if (this.plugins[contextName][pluginName] != null) { console.error("SupCore.system.registerPlugin: Tried to register two or more plugins " + `named "${pluginName}" in context "${contextName}", system "${this.id}"`); } this.plugins[contextName][pluginName] = plugin; } getPlugins(contextName) { return this.plugins[contextName]; } } exports.System = System; class SystemData { constructor(system) { this.system = system; this.assetClasses = {}; this.resourceClasses = {}; } registerAssetClass(name, assetClass) { if (this.assetClasses[name] != null) { console.log(`SystemData.registerAssetClass: Tried to register two or more asset classes named "${name}" in system "${this.system.id}"`); return; } this.assetClasses[name] = assetClass; return; } registerResource(id, resourceClass) { if (this.resourceClasses[id] != null) { console.log(`SystemData.registerResource: Tried to register two or more plugin resources named "${id}" in system "${this.system.id}"`); return; } this.resourceClasses[id] = resourceClass; } }
import React from "react"; import { List, ListItem, ListInput, Block, Row, Button, Link, Col } from 'framework7-react'; import { dict } from '../../Dict'; import crypto from 'crypto-js'; const TodoForm = (props) => { if (true) { function involvementChecked(workInvolvement) { var flag = false props.involvements.map((involvement) => { if (involvement.id === workInvolvement.profile.id) { flag = true } } ) return flag } return ( <List> <ListInput key='todos-form-title' label={dict.title} type="text" placeholder={dict.select_appropriate_title} defaultValue={props.title} required={true} onInput={(e) => { props.handleChange({ title: e.target.value }) }} /> <List className='fs-11 ' > {props.workInvolvements.map((workInvolvement) => <ListItem key={workInvolvement.id} checkbox checked={involvementChecked(workInvolvement)} onChange={(e) => props.involvementCheck(workInvolvement.profile.id, e)} title={workInvolvement.profile.fullname} after=''> </ListItem> )} </List> <Block strong> <Row tag="p"> <Col> <Link className="btn-notice"></Link> <Button className="col btn" fill disabled={!props.editing} onClick={props.submit}>{dict.submit}</Button> </Col> </Row> </Block> </List> ) } else { return (null) } } export default TodoForm;
import firebase from '../../firebase'; import { Redirect } from 'react-router'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; function Handleclickforqr(phone) { //console.log("hello"); console.log(phone); //var duration = 3000; //in milliseconds. therefore 3 seconds. //which may either late or early let recaptcha = new firebase.auth.RecaptchaVerifier('recaptcha-container'); document.getElementById('sent').textContent = "OTP has been sent to your registered phone"; //document.getElementById('button-one').textContent="Click to get otp"; let number = phone; //console.log(number); firebase.auth().signInWithPhoneNumber(number, recaptcha) .then((e) => { let code = prompt("Enter your OTP"); if(code === null) return; e.confirm(code) .then((result) => { console.log(result.user, 'user'); document.getElementById('verify').textContent = "Now proceed to scan Employee ID QRcode"; //document.getElementById('result').style.visibility="visible"; document.getElementById('otpqr').style.visibility="hidden"; document.getElementById('qrcode').style.visibility="visible"; //document.getElementById('emailpage').toggleAttribute() //return( <Redirect to="/email" />); //setText(true); }) .catch((error) => { console.log(error); document.getElementById('verify').textContent = "Incorrect OTP"; }) }) } // Handleclick.propTypes = { // auth: PropTypes.object.isRequired // }; // const mapStateToProps = (state) => ({ // auth: state.auth, // }); // export default connect(mapStateToProps)( // Handleclick // ); export default Handleclickforqr
/* * description:使用原生js封装基本 dom 操作功能 * author: fanyong@gmail.com * */ var domUtil = { /* version v0.1*/ hasClass: function(obj, className) { var classNames = obj.className; // 获取DOM中的 class 内容 var classNameArr = classNames.split(/\s+/); // 将字符串 split 为数组 for (var item in classNameArr) { if (classNameArr[item] === className) { return true; } } return false; }, addClass: function(obj, className) { if (!this.hasClass(obj, className)) // 没有则添加 obj.className += ' ' + className; }, removeClass: function(obj, className) { if (this.hasClass(obj, className)) { // 有则移除 var reg = new RegExp('(\\s|^)' + className + '(\\s|$)'); // /(\s|^)cname(\s|$)/ obj.className = obj.className.replace(reg, ' '); } }, toggleClass: function(obj, className) { if (this.hasClass(obj, className)) { // 有则移除 this.removeClass(obj, className); } else { // 没有则添加 this.addClass(obj, className); } }, /* version v0.2 */ createScript: function (url, isAsync) { var s = document.createElement('script'); s.type = 'text/javascript'; s.async = isAsync; s.src = url; var h = document.getElementsByTagName('head')[0]; h.appendChild(s); }, createStyleTag: function (css) { head = document.getElementsByTagName('head')[0], style = document.createElement('style'); style.type = 'text/css'; if (style.styleSheet) { style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } head.appendChild(style); } }; /* 测试 hasClass、addClass 、removeClass功能 * 测试方法: * 1)HTML添加 <a id="popfloating_send_msg" href="javascript:;" class="app_wrap_pop_btn01 a">免费获取</a> * 2)将该js引入到HTML,最好放在body底部,以免获取不到dom元素 */ // var obj = document.getElementById('popfloating_send_msg'); // console.log(domUtil.hasClass(obj, 'a')); // domUtil.addClass(obj, 'test'); // domUtil.removeClass(obj, 'a'); // domUtil.toggleClass(obj, 'b'); /* 动态创建css */ // var css = '.app_wrap_pop input,' // + '.app_wrap_pop p{margin:0;padding:0;}' // + '.app_wrap_pop a{color:#06c;text-decoration:none;}' // + '.app_wrap_pop a:hover{text-decoration:underline;}'; // domUtil.createStyleTag(css); /* 动态创建script */ // var smsUrl = utils.getDomain() + "/sms/JsonpSendSMS.ashx?tel=" + num + "&callback=Floating.MsgRespone&rd=" + Math.random(); // utils.createScript(smsUrl, true);
import React from "react"; const LabelInfo = ({ labelfor, labeltitle }) => { return <label htmlFor={labelfor}>{labeltitle}</label>; }; export default LabelInfo;
var Promise = require('bluebird'); var _ = require('lodash'); var app = require('../../server/server'); module.exports = function(Costcenter) { Costcenter.afterRemote('**', function(ctx, costcenter, next) { var findOrders = Promise.promisify(app.models.Purchaseorder.find, app.models.Purchaseorder); function countTotalPriceOfOrders(costcenter) { costcenter = costcenter.toObject(); var filter = { where: { costcenterId: costcenter.costcenterId }, include: { relation: 'order_rows', scope: { include: 'title', }, }, }; return findOrders(filter) .then(function(orders) { if (orders) { var totalPrice = _.reduce(orders, function(totalOfOrders, order) { order = order.toObject(); var total = _.reduce(order.order_rows, function(totalOfOrderrows, row) { if (row.finalPrice === 0 || row.finalPrice) { return totalOfOrderrows + row.finalPrice; } else { var title = row.title || { }; var titlePrice = row.priceOverride || title.priceWithTax || 0; return totalOfOrderrows + (row.amount * titlePrice); } }, 0); return totalOfOrders + total; }, 0); return totalPrice; } else { return 0; } }).then(function(price) { costcenter.totalPrice = price; return costcenter; }); } if (ctx.result) { if (_.isArray(ctx.result)) { // handling many costcenters return Promise.map(ctx.result, countTotalPriceOfOrders) .then(function(costcenters) { ctx.result = costcenters; }); } else { // only one costcenter return countTotalPriceOfOrders(ctx.result) .then(function(costcenter) { ctx.result = costcenter; }); } } }); };
// shows the game and you can play it yay let questionsIndex = 0 let answers = [] let score = 0 const renderGamePlay = () => { app.innerHTML = `score: ${score}` titleBox.innerHTML = `<h2><i class='icon star is-medium'></i> ${selectedGame.title}</h2>` // create element to display the question and append to #app q1 = document.createElement('p') q1.innerHTML = ` <section class='container with-title is-rounded'> <p class='title'>Question #${questionsIndex+1} of ${selectedGame.questions.length}</p> ${selectedGame.questions[questionsIndex].question} </section> ` app.append(q1) // answerBox is a section to hold all answers // answers is a new array with correct and incorrect answers, then shuffle (see utils.js) // forEach to display each answer, they are selectable answerBox = document.createElement('section') answerBox.className = 'container is-rounded' answers = selectedGame.questions[questionsIndex].incorrect_answers.slice() answers.push(selectedGame.questions[questionsIndex].correct_answer) shuffle(answers) answers.forEach( answer => { a = document.createElement('div') a.innerHTML = ` <label> <input type='radio' class='radio' name='answer'> <span>${answer}</span> </label> ` answerBox.append(a) app.append(answerBox) }) answerBox.firstElementChild.firstElementChild.firstElementChild.checked = true app.append( renderButton('try it', function() { checkAnswer() renderNextQuestion() })) return '' // return score later } const checkAnswer = () => { document.querySelectorAll('input').forEach( e => { if (e.checked) { if (e.nextElementSibling.innerText === selectedGame.questions[questionsIndex].correct_answer) { score = score + 10 } } }) } const renderNextQuestion = () => { if (questionsIndex < selectedGame.questions.length-1) { questionsIndex++ renderGamePlay() } else { selectedGame.average_score = updateAverageScore(selectedGame) selectedGame.attempts++ updateGame(selectedGame) renderGameEnd() } } const renderGameEnd = () => { app.innerHTML = ` Final Score: ${score}<br><br> Attempts: ${selectedGame.attempts}<br> ` if (score > selectedGame.high_score) { updateHighScore() } app.append( renderButton('<i class="nes-logo"></i> Play Again?', () => { questionsIndex = 0 score = 0 answers = [] renderGamePlay() }), renderButton('<i class="icon star"></i> Back to Games', () => { questionsIndex = 0 score = 0 answers = [] getGames() }) ) } function updateAverageScore(selectedGame){ currentAverage = selectedGame.average_score currentAttempts = selectedGame.attempts return (currentAverage*currentAttempts+score)/(currentAttempts+1) } function updateGame(selectedGame){ server.patch(`/games/${selectedGame.id}`, selectedGame) } const updateHighScore = () => { highScoreForm = document.createElement('form') highScoreForm.className = 'container with-title' highScoreTitle = document.createElement('h3') highScoreTitle.innerHTML = "New High Score! Please enter initials" highScoreTitle.className = "title" highScoreForm.append(highScoreTitle) nameField = document.createElement('input') nameField.className = 'input' nameField.setAttribute('maxlength', '3') nameField.placeholder = 'AAA' highScoreForm.append( nameField, renderButton('save', (e) => { e.preventDefault() selectedGame.high_score = score; selectedGame.high_score_holder = nameField.value updateGame(selectedGame) renderGameEnd() }) ) // nameField.addEventListener('keydown', e => { // if(e.target.value.length >= 3) { // e.preventDefault() // } // }) app.append(highScoreForm) }
// Aula 17 - 20/09/2021 // Métodos Avançados // ex07Splice.js // splice = emenda // Splice() é o método que serve para remover e adicionar elementos // de uma array // Sintaxe array.splic(inicio, quantidade, item1, item2...) // quantidade é opcional - números inteiro a eliminar no array let frutas = ['Banana','Laranja','Limão','Maçã','Manga']; console.log(frutas); // frutas.splice(2,0,"Mamão","Kiwi"); // console.log("Lista com adição.....: ",frutas); console.log(frutas.splice(1, 1, "Pedro", "João")); console.log(frutas); // Splice => Retira e troca elementos de um array. Recebendo como parâmetro um ínicio, a quantidade de retiradas // e opcionalmente o que deve ser substituído
var User = require('./user.server.model'), Quiz = require('../quiz/quiz.server.model'), Test = require('../test/test.server.model'); exports.getUsers = function (req, res, next) { User.find({}) .exec(function (err, users) { if (err) res.status(500).send(err); else res.json(users); }); }; exports.getOneUser = function (req, res, next) { User.findById(req.params.id) .populate('editing') .exec(function (err, user) { if (err) res.status(500).send(err); else res.json(user); }); }; exports.patchUser = function (req, res, next) { User.findById(req.params.id) .exec(function (err, user) { if (req.query.quiz) { Quiz.findById(req.query.quiz) .exec(function (err, quiz) { if (user.editing.indexOf(quiz._id) === -1) { user.editing.push(quiz); } else { user.editing.splice(user.editing.indexOf(quiz._id), 1); } user.save(function (err, user) { if (err) res.status(500).send(err); else res.json(user); }); }); } else if (req.query.test) { Test.findById(req.query.test) .exec(function (err, test) { user.editing = []; test.quizzes.forEach(function (quiz) { user.editing.push(quiz); }); user.save(function (err, user) { if (err) res.status(500).send(err); else res.json(user); }); }); } }); }; exports.resetEditing = function (req, res, next) { User.findById(req.params.id) .exec(function (err, user) { if (err) res.status(500).send(err); else { user.editing = []; user.save(function (err, user) { if (err) res.status(500).send(err); else res.json(user); }); } }); };
import { withRouter } from 'react-router-dom' import requireAuth from '../../decorators/requireAuth' import Home from './Home' export default withRouter(requireAuth(Home));
/* eslint-env node */ 'use strict'; var gulp = require('gulp'); var autoprefixer = require('gulp-autoprefixer'); var browserSync = require('browser-sync'); var concat = require('gulp-concat'); var connect = require('gulp-connect-php'); var del = require('del'); var eslint = require('gulp-eslint'); var filter = require('gulp-filter'); var minifyCSS = require('gulp-minify-css'); var plumber = require('gulp-plumber'); var rename = require('gulp-rename'); var sass = require('gulp-sass'); var scsslint = require('gulp-scss-lint'); var size = require('gulp-size'); var sourcemaps = require('gulp-sourcemaps'); var uglify = require('gulp-uglify'); var gutil = require('gulp-util'); var zip = require('gulp-zip'); var reload = browserSync.reload; var configs = { connect: { hostname: '127.0.0.1', port: '8000', base: '.', stdio: 'ignore' }, sass: { precision: 10, includePaths: ['bower_components/'] }, autoprefixer: { browsers: [ '> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1' ] } }; var paths = { css: 'assets/css/', fonts: 'assets/fonts/', images: 'assets/img/', js: 'assets/js/', scss: 'assets/scss/' }; var scripts = { main: { src: [ 'bower_components/jquery/dist/jquery.js', 'bower_components/bootstrap/js/dist/util.js', 'bower_components/bootstrap/js/dist/collapse.js', paths.js + 'main.js' ], template: false } }; // Bip on error and display them in 'stylish' style var errorHandler = { sass: function () { gutil.beep(); browserSync.notify('Error in compiling sass files'); this.emit('end'); }, js: function (err) { var color = gutil.colors; var message = color.gray(err.lineNumber) + ' ' + err.message; message = new gutil.PluginError(err.plugin, message).toString(); gutil.beep(); process.stderr.write(message + '\n'); browserSync.notify('Error in compiling js files'); this.emit('end'); } }; // Compile, minify, autoprefix & sourcemap scss files gulp.task('styles', function () { return gulp.src([paths.scss + '**/*.scss']) .pipe(plumber({errorHandler: errorHandler.sass})) .pipe(sourcemaps.init()) .pipe(sass.sync(configs.sass).on('error', sass.logError)) .pipe(autoprefixer(configs.autoprefixer)) .pipe(gulp.dest(paths.css)) .pipe(minifyCSS()) .pipe(rename({suffix: '.min'})) .pipe(sourcemaps.write('.')) .pipe(gulp.dest(paths.css)) .pipe(filter('**/*.css')) .pipe(reload({stream: true})); }); // Concat, minify & sourcemap js files gulp.task('scripts', function (cb) { for (var i in scripts) { if ({}.hasOwnProperty.call(scripts, i)) { var script = scripts[i]; var fileName = i + '.js'; var dest = paths.js; if (script.template) { dest += 'templates/'; } gulp.src(script.src) .pipe(sourcemaps.init()) .pipe(plumber({errorHandler: errorHandler.js})) .pipe(uglify()) .pipe(concat(fileName)) .pipe(rename({suffix: '.min'})) .pipe(sourcemaps.write('.')) .pipe(gulp.dest(dest)) .pipe(reload({stream: true, once: true})); } } cb(); }); // Copy some files out of bower_components folder gulp.task('copy', function () { // return gulp.src(['']) // .pipe(gulp.dest(paths.fonts)); }); // Cleanup generated files gulp.task('clean', function (cb) { del([ paths.css + '**/*.min.css', paths.css + '**/*.map', paths.js + '**/*.min.js', paths.js + '**/*.map' ], cb); }); // lint scss & js files gulp.task('lint', function (cb) { gulp.src([paths.scss + '**/*.scss']) .pipe(scsslint({customReport: require('gulp-scss-lint-stylish')})); gulp.src([paths.js + '**/*.js', '!**/*.min.js', 'gulpfile.js']) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); cb(); }); // Make a zip ready for releasing gulp.task('zip', ['build'], function () { var p = require('./package.json'); var fileName = p.name + '-' + p.version + '.zip'; var src = [ '**/*', '!bower_components/**/*', '!bower_components', '!node_modules/**/*', '!node_modules', '!site/account/*.php', '!thumbs/**/*', '!assets/avatars/**/*', '!site/cache/**/*', 'site/cache/index.html', '!site/config/**/*', 'site/config/config.php', '!*.zip' ]; return gulp.src(src) .pipe(size({title: 'unziped'})) .pipe(zip(fileName)) .pipe(size({title: 'ziped'})) .pipe(gulp.dest('.')); }); // Run a development server with browsersync gulp.task('serve', ['compile'], function () { connect.server(configs.connect, function () { browserSync({proxy: configs.server.hostname + ':' + configs.server.port}); }); // watch for changes gulp.watch([ 'site/**/*.php', paths.images + '**/*', paths.fonts + '**/*' ]).on('change', reload); gulp.watch(paths.scss + '**/*.scss', ['styles']); gulp.watch([paths.js + '**/*.js', '!**/*.min.js'], ['scripts']); }); // aliases gulp.task('compile', ['styles', 'scripts', 'copy']); gulp.task('build', ['lint', 'clean'], function () { gulp.start('compile'); }); gulp.task('default', ['build']);
(function(){ var canvas = document.getElementById('hexmap'); var tipCanvas = document.getElementById("tip"); var tipCtx = tipCanvas.getContext("2d"); var canvasOffset = $("canvas").offset(); var offsetX = canvasOffset.left; var offsetY = canvasOffset.top; var xPadding = 30; var yPadding = 30; var hexHeight, hexRadius, hexRectangleHeight, hexRectangleWidth, hexagonAngle = 0.523598776, // 30 degrees in radians sideLength = 56, boardWidth = 10, boardHeight = 10; hexHeight = Math.sin(hexagonAngle) * sideLength; hexRadius = Math.cos(hexagonAngle) * sideLength; hexRectangleHeight = sideLength + 2 * hexHeight; hexRectangleWidth = 2 * hexRadius; var lastX = -1, lastY = -1; localStorage.setItem("lastX", lastX); localStorage.setItem("lastY", lastY); var stack = "",stackId = ""; //var objMoves = [], arrHex = {x:0,y:0}; var arrLocation = [ { locId: 'adffd', name: 'Rivendell', locx: 0 , locy: 0, x: 2, y: 3, mp: 2, locType : 'hamlet', commodity: 'wood', terrain: 'woods', defenseAdd: 2, defenseMult: 1, value: 200 }, { locId: 'asdfd', name: 'Gilgould', locx : 0, locy : 0, x: 4, y: 5, mp: 2, locType : 'hamlet', commodity: 'livestock', terrain: 'plains', defenseAdd: 1, defenseMult: 1, value: 150 } ]; var arrBlockedHexes = [ { hexX: 0, hexY: 0, adjHexes : [{ adjhexX: 0, adjhexY: 1 }, { adjhexX: 1, adjhexY: 0 }], hexX: 0, hexY: 1, adjHexes : [{ adjhexX: 0, adjhexY: 0 }, { adjhexX: 1, adjhexY: 0 }, { adjhexX: 1, adjhexY: 1 }] } ]; // define tooltips for each data point function printAt(context, text, x, y, lineHeight, fitWidth) { fitWidth = fitWidth || 0; if (fitWidth <= 0) { context.fillText(text, x, y); return; } for (var idx = 1; idx <= text.length; idx++) { var str = text.substr(0, idx); console.log(str, context.measureText(str).width, fitWidth); if (context.measureText(str).width > fitWidth) { context.fillText(text.substr(0, idx - 1), x, y); printAt(context, text.substr(idx - 1), x, y + lineHeight, lineHeight, fitWidth); return; } } context.fillText(text, x, y); } var objMoves = { addElem: function (id, elem) { var obj = this[id] || { moves: [] }; obj.moves.push(elem); this[id] = obj; }, removeElem: function (id, last) { this[id].moves.splice(last, 1); } } // Returns the max Y value in our data list function getMaxY() { var max = 0; for (var i = 0; i < data.values.length; i++) { if (data.values[i].Y > max) { max = data.values[i].Y; } } max += 10 - max % 10; return max; } // Returns the max X value in our data list function getMaxX() { var max = 0; for (var i = 0; i < data.values.length; i++) { if (data.values[i].X > max) { max = data.values[i].X; } } // omited //max += 10 - max % 10; return max; } // Return the x pixel for a graph point function getXPixel(val) { // uses the getMaxX() function return ((canvas.width - xPadding) / (getMaxX() + 1)) * val + (xPadding * 1.5); // was //return ((graph.width - xPadding) / getMaxX()) * val + (xPadding * 1.5); } // Return the y pixel for a graph point function getYPixel(val) { return canvas.height - (((canvas.height - yPadding) / getMaxY()) * val) - yPadding; } Number.prototype.between = function (a, b) { var min = Math.min(a, b), max = Math.max(a, b); return this > min && this < max; }; if (canvas.getContext){ var ctx = canvas.getContext('2d'); ctx.fillStyle = "#000000"; ctx.strokeStyle = "#CCCCCC"; ctx.lineWidth = 1; drawBoard(ctx, boardWidth, boardHeight,false,false); canvas.addEventListener("click" , function(eventInfo) { var x, y, hexX, hexY, screenX, screenY; x = eventInfo.offsetX || eventInfo.layerX; y = eventInfo.offsetY || eventInfo.layerY; stack = document.getElementById('stack'); stackId = stack.value; hexY = Math.floor(y / (hexHeight + sideLength)); hexX = Math.floor((x - (hexY % 2) * hexRadius) / hexRectangleWidth); var fill = true; lastX = localStorage.getItem("lastX"); lastY = localStorage.getItem("lastY"); console.log("Lastx : " + lastX + ",LastY : " + lastY); //console.log(localStorage.lastX + "," + localStorage.lastY); screenX = hexX * hexRectangleWidth + ((hexY % 2) * hexRadius); screenY = hexY * (hexHeight + sideLength); //console.log ("screenx,y : " + screenX + "," + screenY) //ctx.clearRect(0, 0, canvas.width, canvas.height); //drawBoard(ctx, boardWidth, boardHeight); // Check if the mouse's coords are on the board if(hexX >= 0 && hexX < boardWidth) { if(hexY >= 0 && hexY < boardHeight) { if (lastX == hexX && lastY == hexY) { objMoves.removeElem(stackId, objMoves[stackId].moves.length - 1); if (objMoves[stackId].moves.length > 0) { localStorage.setItem("lastX", objMoves[stackId].moves[objMoves[stackId].moves.length - 1].x); localStorage.setItem("lastY", objMoves[stackId].moves[objMoves[stackId].moves.length - 1].y); } else { localStorage.setItem("lastX", -1); localStorage.setItem("lastY", -1); } ctx.clearRect(0, 0, canvas.width, canvas.height); drawBoard(ctx, boardWidth, boardHeight, false,false); } else { objMoves.addElem(stackId, { x: hexX, y: hexY }); localStorage.setItem("lastX", hexX); localStorage.setItem("lastY", hexY); } drawBoard(ctx, boardWidth, boardHeight, true, true); console.log(JSON.stringify(objMoves)); //drawHexagon(ctx, screenX, screenY, hexX, hexY, fill, "#EFEFEF"); } } //drawBoard(objMoves,ctx, boardWidth, boardHeight); }); canvas.addEventListener("mousemove", function(eventInfo) { var x, y, hexX, hexY, screenX, screenY; x = eventInfo.offsetX || eventInfo.layerX; y = eventInfo.offsetY || eventInfo.layerY; hexY = Math.floor(y / (hexHeight + sideLength)); hexX = Math.floor((x - (hexY % 2) * hexRadius) / hexRectangleWidth); document.getElementById("demo").innerHTML = "hexX:" + hexX + ",hexY:" + hexY + ",screenX:" + screenX + ",screenY:" + screenY; screenX = hexX * hexRectangleWidth + ((hexY % 2) * hexRadius); screenY = hexY * (hexHeight + sideLength); var hit = false; var result = arrLocation.find(loc => loc.x === hexX && loc.y === hexY); if (typeof result != "undefined") { document.getElementById("demo").innerHTML = "found it"; if (x.between(result.locx + 10, result.locx - 10) && y.between(result.locy + 10, result.locy - 10)) { //document.getElementById("demo").innerHTML = "hexX:" + hexX + ",hexY:" + hexY + ",screenX:" + screenX + ",screenY:" + screenY; tipCanvas.style.left = (x + 465) + "px"; tipCanvas.style.top = (y - 40) + "px"; tipCtx.clearRect(0, 0, tipCanvas.width, tipCanvas.height); tipCtx.fillText("Name : " + result.name, 5, 15); tipCtx.fillText("Value : " + result.value, 5, 25); tipCtx.fillText("Commodity : " + result.commodity, 5, 35); tipCtx.fillText("Defense : +" + result.defenseAdd, 5, 45); hit = true; } } if (!hit) { tipCanvas.style.left = "-200px"; } }); } function drawBoard(canvasContext, width, height,fill,drawMoves) { var i, j; for(i = 0; i < width; ++i) { for (j = 0; j < height; ++j) { x = i * hexRectangleWidth + ((j % 2) * hexRadius); y = j * (sideLength + hexHeight); hexY = Math.floor(y / (hexHeight + sideLength)); hexX = Math.floor((x - (hexY % 2) * hexRadius) / hexRectangleWidth); displayY = hexY - 1; displayX = hexX - 1; var result = arrLocation.find(loc => loc.x === displayX && loc.y === displayY); var hexName = hexX + "," + hexY; ctx.fillStyle = "#CCCCCC"; ctx.font = "bold 14px Arial"; if (typeof result != "undefined") { ctx.fillText(result.name, x+3, y -15); ctx.beginPath(); ctx.arc(x-10, y-20, 5, 0, 2 * Math.PI); ctx.stroke(); ctx.fill(); result.locx = x + 3; result.locy = y - 15; ctx.beginPath(); ctx.arc(x-10, y-20, 8, 0, 2 * Math.PI); ctx.stroke(); } if (drawMoves) { for (m = 0; m < objMoves[stackId].moves.length; ++m) { clickedX = objMoves[stackId].moves[m].x; clickedY = objMoves[stackId].moves[m].y; if (clickedX == hexX && clickedY == hexY) { console.log("found it"); ctx.fillText(hexName, x+38, y+25); // console.log(hexName); drawHexagon( ctx, i * hexRectangleWidth + ((j % 2) * hexRadius), j * (sideLength + hexHeight), hexX, hexY, true, "#EFEFEF" ); } } } else { // console.log(hexName); drawHexagon( ctx, i * hexRectangleWidth + ((j % 2) * hexRadius), j * (sideLength + hexHeight), hexX, hexY, false, "#FFFFFF" ); } } } } function drawHexagon(canvasContext, x, y, hexX, hexY, fill, fillstyle) { var fill = fill || false; var hexName = hexX + "," + hexY; canvasContext.fillStyle = "#EFEFEF"; document.getElementById("demo").innerHTML = fillstyle; canvasContext.beginPath(); canvasContext.moveTo(x + hexRadius, y); canvasContext.lineTo(x + hexRectangleWidth, y + hexHeight); canvasContext.lineTo(x + hexRectangleWidth, y + hexHeight + sideLength); canvasContext.lineTo(x + hexRadius, y + hexRectangleHeight); canvasContext.lineTo(x, y + sideLength + hexHeight); canvasContext.lineTo(x, y + hexHeight); canvasContext.closePath(); if (fill) { //canvasContext.fillStyle = "#000000"; //canvasContext.font = "bold 14px Arial"; //canvasContext.fillStyle = "#FFFFFF"; //canvasContext.fillText(hexName, x + 46, y + 82); // canvasContext.shadowColor = '#999'; //canvasContext.shadowBlur = 20; //canvasContext.shadowOffsetX = 15; //canvasContext.shadowOffsetY = 15; canvasContext.fillStyle = fillstyle; canvasContext.fill(); } else { canvasContext.stroke(); if ((hexX == 0 && hexY == 0) || (hexX == 0 && hexY == 1) || (hexX == 0 && hexY == 2) || (hexX == 1 && hexY == 0) || (hexX == 2 && hexY == 0)) { canvasContext.fillStyle = "blue"; } else { canvasContext.fillStyle = "#999966";} canvasContext.fill(); } canvasContext.fillStyle = "#EFEFEF"; canvasContext.fillText(hexName, x + 38, y + 25); } })();
import { CUBEPROJ_NONE, DETAILMODE_MUL, FRESNEL_SCHLICK, SPECOCC_AO, SPECULAR_BLINN } from '../../../src/scene/constants.js'; import { Color } from '../../../src/core/math/color.js'; import { Material } from '../../../src/scene/materials/material.js'; import { StandardMaterial } from '../../../src/scene/materials/standard-material.js'; import { Vec2 } from '../../../src/core/math/vec2.js'; import { expect } from 'chai'; describe('StandardMaterial', function () { function checkDefaultMaterial(material) { expect(material).to.be.an.instanceof(StandardMaterial); expect(material).to.be.an.instanceof(Material); expect(material.alphaFade).to.equal(1); expect(material.ambient).to.be.an.instanceof(Color); expect(material.ambient.r).to.equal(0.7); expect(material.ambient.g).to.equal(0.7); expect(material.ambient.b).to.equal(0.7); expect(material.ambientTint).to.equal(false); expect(material.anisotropy).to.equal(0); expect(material.aoDetailMap).to.be.null; expect(material.aoDetailMapChannel).to.equal('g'); expect(material.aoDetailMapOffset).to.be.an.instanceof(Vec2); expect(material.aoDetailMapOffset.x).to.equal(0); expect(material.aoDetailMapOffset.y).to.equal(0); expect(material.aoDetailMapRotation).to.equal(0); expect(material.aoDetailMapTiling).to.be.an.instanceof(Vec2); expect(material.aoDetailMapTiling.x).to.equal(1); expect(material.aoDetailMapTiling.y).to.equal(1); expect(material.aoDetailMapUv).to.equal(0); expect(material.aoDetailMode).to.equal(DETAILMODE_MUL); expect(material.aoMap).to.be.null; expect(material.aoMapChannel).to.equal('g'); expect(material.aoMapOffset).to.be.an.instanceof(Vec2); expect(material.aoMapOffset.x).to.equal(0); expect(material.aoMapOffset.y).to.equal(0); expect(material.aoMapRotation).to.equal(0); expect(material.aoMapTiling).to.be.an.instanceof(Vec2); expect(material.aoMapTiling.x).to.equal(1); expect(material.aoMapTiling.y).to.equal(1); expect(material.aoMapUv).to.equal(0); expect(material.aoVertexColor).to.equal(false); expect(material.aoVertexColorChannel).to.equal('g'); expect(material.bumpiness).to.equal(1); expect(material.chunks).to.be.empty; expect(material.clearCoat).to.equal(0); expect(material.clearCoatBumpiness).to.equal(1); expect(material.clearCoatGlossMap).to.be.null; expect(material.clearCoatGlossMapChannel).to.equal('g'); expect(material.clearCoatGlossMapOffset).to.be.an.instanceof(Vec2); expect(material.clearCoatGlossMapOffset.x).to.equal(0); expect(material.clearCoatGlossMapOffset.y).to.equal(0); expect(material.clearCoatGlossMapRotation).to.equal(0); expect(material.clearCoatGlossMapTiling).to.be.an.instanceof(Vec2); expect(material.clearCoatGlossMapTiling.x).to.equal(1); expect(material.clearCoatGlossMapTiling.y).to.equal(1); expect(material.clearCoatGlossMapUv).to.equal(0); expect(material.clearCoatGlossVertexColor).to.equal(false); expect(material.clearCoatGlossVertexColorChannel).to.equal('g'); expect(material.clearCoatGloss).to.equal(1); expect(material.clearCoatMap).to.be.null; expect(material.clearCoatMapChannel).to.equal('g'); expect(material.clearCoatMapOffset).to.be.an.instanceof(Vec2); expect(material.clearCoatMapOffset.x).to.equal(0); expect(material.clearCoatMapOffset.y).to.equal(0); expect(material.clearCoatMapRotation).to.equal(0); expect(material.clearCoatMapTiling).to.be.an.instanceof(Vec2); expect(material.clearCoatMapTiling.x).to.equal(1); expect(material.clearCoatMapTiling.y).to.equal(1); expect(material.clearCoatMapUv).to.equal(0); expect(material.clearCoatNormalMap).to.be.null; expect(material.clearCoatNormalMapOffset).to.be.an.instanceof(Vec2); expect(material.clearCoatNormalMapOffset.x).to.equal(0); expect(material.clearCoatNormalMapOffset.y).to.equal(0); expect(material.clearCoatNormalMapRotation).to.equal(0); expect(material.clearCoatNormalMapTiling).to.be.an.instanceof(Vec2); expect(material.clearCoatNormalMapTiling.x).to.equal(1); expect(material.clearCoatNormalMapTiling.y).to.equal(1); expect(material.clearCoatNormalMapUv).to.equal(0); expect(material.clearCoatVertexColor).to.equal(false); expect(material.clearCoatVertexColorChannel).to.equal('g'); expect(material.conserveEnergy).to.equal(true); expect(material.cubeMap).to.be.null; expect(material.cubeMapProjection).to.equal(CUBEPROJ_NONE); expect(material.cubeMapProjectionBox).to.be.null; expect(material.diffuse).to.be.an.instanceof(Color); expect(material.diffuse.r).to.equal(1); expect(material.diffuse.g).to.equal(1); expect(material.diffuse.b).to.equal(1); expect(material.diffuseDetailMap).to.be.null; expect(material.diffuseDetailMapChannel).to.equal('rgb'); expect(material.diffuseDetailMapOffset).to.be.an.instanceof(Vec2); expect(material.diffuseDetailMapOffset.x).to.equal(0); expect(material.diffuseDetailMapOffset.y).to.equal(0); expect(material.diffuseDetailMapRotation).to.equal(0); expect(material.diffuseDetailMapTiling).to.be.an.instanceof(Vec2); expect(material.diffuseDetailMapTiling.x).to.equal(1); expect(material.diffuseDetailMapTiling.y).to.equal(1); expect(material.diffuseDetailMapUv).to.equal(0); expect(material.diffuseDetailMode).to.equal(DETAILMODE_MUL); expect(material.diffuseMap).to.be.null; expect(material.diffuseMapChannel).to.equal('rgb'); expect(material.diffuseMapOffset).to.be.an.instanceof(Vec2); expect(material.diffuseMapOffset.x).to.equal(0); expect(material.diffuseMapOffset.y).to.equal(0); expect(material.diffuseMapRotation).to.equal(0); expect(material.diffuseMapTiling).to.be.an.instanceof(Vec2); expect(material.diffuseMapTiling.x).to.equal(1); expect(material.diffuseMapTiling.y).to.equal(1); expect(material.diffuseMapUv).to.equal(0); expect(material.diffuseTint).to.equal(false); expect(material.diffuseVertexColor).to.equal(false); expect(material.diffuseVertexColorChannel).to.equal('rgb'); expect(material.emissive).to.be.an.instanceof(Color); expect(material.emissive.r).to.equal(0); expect(material.emissive.g).to.equal(0); expect(material.emissive.b).to.equal(0); expect(material.emissiveIntensity).to.equal(1); expect(material.emissiveMap).to.be.null; expect(material.emissiveMapChannel).to.equal('rgb'); expect(material.emissiveMapOffset).to.be.an.instanceof(Vec2); expect(material.emissiveMapOffset.x).to.equal(0); expect(material.emissiveMapOffset.y).to.equal(0); expect(material.emissiveMapRotation).to.equal(0); expect(material.emissiveMapTiling).to.be.an.instanceof(Vec2); expect(material.emissiveMapTiling.x).to.equal(1); expect(material.emissiveMapTiling.y).to.equal(1); expect(material.emissiveMapUv).to.equal(0); expect(material.emissiveTint).to.equal(false); expect(material.emissiveVertexColor).to.equal(false); expect(material.emissiveVertexColorChannel).to.equal('rgb'); expect(material.enableGGXSpecular).to.equal(false); expect(material.fresnelModel).to.equal(FRESNEL_SCHLICK); expect(material.gloss).to.equal(0.25); expect(material.glossMap).to.be.null; expect(material.glossMapChannel).to.equal('g'); expect(material.glossMapOffset).to.be.an.instanceof(Vec2); expect(material.glossMapOffset.x).to.equal(0); expect(material.glossMapOffset.y).to.equal(0); expect(material.glossMapRotation).to.equal(0); expect(material.glossMapTiling).to.be.an.instanceof(Vec2); expect(material.glossMapTiling.x).to.equal(1); expect(material.glossMapTiling.y).to.equal(1); expect(material.glossMapUv).to.equal(0); expect(material.glossVertexColor).to.equal(false); expect(material.glossVertexColorChannel).to.equal('g'); expect(material.heightMap).to.be.null; expect(material.heightMapChannel).to.equal('g'); expect(material.heightMapFactor).to.equal(1); expect(material.heightMapOffset).to.be.an.instanceof(Vec2); expect(material.heightMapOffset.x).to.equal(0); expect(material.heightMapOffset.y).to.equal(0); expect(material.heightMapRotation).to.equal(0); expect(material.heightMapTiling).to.be.an.instanceof(Vec2); expect(material.heightMapTiling.x).to.equal(1); expect(material.heightMapTiling.y).to.equal(1); expect(material.heightMapUv).to.equal(0); expect(material.lightMap).to.be.null; expect(material.lightMapChannel).to.equal('rgb'); expect(material.lightMapOffset).to.be.an.instanceof(Vec2); expect(material.lightMapOffset.x).to.equal(0); expect(material.lightMapOffset.y).to.equal(0); expect(material.lightMapRotation).to.equal(0); expect(material.lightMapTiling).to.be.an.instanceof(Vec2); expect(material.lightMapTiling.x).to.equal(1); expect(material.lightMapTiling.y).to.equal(1); expect(material.lightMapUv).to.equal(1); expect(material.lightVertexColor).to.equal(false); expect(material.lightVertexColorChannel).to.equal('rgb'); expect(material.metalness).to.equal(1); expect(material.metalnessMap).to.be.null; expect(material.metalnessMapChannel).to.equal('g'); expect(material.metalnessMapOffset).to.be.an.instanceof(Vec2); expect(material.metalnessMapOffset.x).to.equal(0); expect(material.metalnessMapOffset.y).to.equal(0); expect(material.metalnessMapRotation).to.equal(0); expect(material.metalnessMapTiling).to.be.an.instanceof(Vec2); expect(material.metalnessMapTiling.x).to.equal(1); expect(material.metalnessMapTiling.y).to.equal(1); expect(material.metalnessMapUv).to.equal(0); expect(material.metalnessVertexColor).to.equal(false); expect(material.metalnessVertexColorChannel).to.equal('g'); expect(material.normalDetailMap).to.be.null; expect(material.normalDetailMapBumpiness).to.equal(1); expect(material.normalDetailMapOffset).to.be.an.instanceof(Vec2); expect(material.normalDetailMapOffset.x).to.equal(0); expect(material.normalDetailMapOffset.y).to.equal(0); expect(material.normalDetailMapRotation).to.equal(0); expect(material.normalDetailMapTiling).to.be.an.instanceof(Vec2); expect(material.normalDetailMapTiling.x).to.equal(1); expect(material.normalDetailMapTiling.y).to.equal(1); expect(material.normalDetailMapUv).to.equal(0); expect(material.normalMap).to.be.null; expect(material.normalMapOffset).to.be.an.instanceof(Vec2); expect(material.normalMapOffset.x).to.equal(0); expect(material.normalMapOffset.y).to.equal(0); expect(material.normalMapRotation).to.equal(0); expect(material.normalMapTiling).to.be.an.instanceof(Vec2); expect(material.normalMapTiling.x).to.equal(1); expect(material.normalMapTiling.y).to.equal(1); expect(material.normalMapUv).to.equal(0); expect(material.occludeDirect).to.equal(false); expect(material.occludeSpecular).to.equal(SPECOCC_AO); expect(material.occludeSpecularIntensity).to.equal(1); expect(material.onUpdateShader).to.be.undefined; expect(material.opacity).to.equal(1); expect(material.opacityFadesSpecular).to.equal(true); expect(material.opacityMap).to.be.null; expect(material.opacityMapChannel).to.equal('a'); expect(material.opacityMapOffset).to.be.an.instanceof(Vec2); expect(material.opacityMapOffset.x).to.equal(0); expect(material.opacityMapOffset.y).to.equal(0); expect(material.opacityMapRotation).to.equal(0); expect(material.opacityMapTiling).to.be.an.instanceof(Vec2); expect(material.opacityMapTiling.x).to.equal(1); expect(material.opacityMapTiling.y).to.equal(1); expect(material.opacityMapUv).to.equal(0); expect(material.opacityVertexColor).to.equal(false); expect(material.opacityVertexColorChannel).to.equal('a'); expect(material.pixelSnap).to.equal(false); expect(material.reflectivity).to.equal(1); expect(material.refraction).to.equal(0); expect(material.refractionIndex).to.equal(1.0 / 1.5); expect(material.shadingModel).to.equal(SPECULAR_BLINN); expect(material.specular).to.be.instanceof(Color); expect(material.specular.r).to.equal(0); expect(material.specular.g).to.equal(0); expect(material.specular.b).to.equal(0); expect(material.specularMap).to.be.null; expect(material.specularMapChannel).to.equal('rgb'); expect(material.specularMapOffset).to.be.an.instanceof(Vec2); expect(material.specularMapOffset.x).to.equal(0); expect(material.specularMapOffset.y).to.equal(0); expect(material.specularMapRotation).to.equal(0); expect(material.specularMapTiling).to.be.an.instanceof(Vec2); expect(material.specularMapTiling.x).to.equal(1); expect(material.specularMapTiling.y).to.equal(1); expect(material.specularMapUv).to.equal(0); expect(material.specularTint).to.equal(false); expect(material.specularVertexColor).to.equal(false); expect(material.specularVertexColorChannel).to.equal('rgb'); expect(material.specularityFactor).to.be.equal(1); expect(material.specularityFactorMap).to.be.null; expect(material.specularityFactorMapChannel).to.equal('g'); expect(material.specularityFactorMapOffset).to.be.an.instanceof(Vec2); expect(material.specularityFactorMapOffset.x).to.equal(0); expect(material.specularityFactorMapOffset.y).to.equal(0); expect(material.specularityFactorMapRotation).to.equal(0); expect(material.specularityFactorMapTiling).to.be.an.instanceof(Vec2); expect(material.specularityFactorMapTiling.x).to.equal(1); expect(material.specularityFactorMapTiling.y).to.equal(1); expect(material.specularityFactorMapUv).to.equal(0); expect(material.specularityFactorTint).to.equal(false); expect(material.specularityFactorVertexColor).to.equal(false); expect(material.specularityFactorVertexColorChannel).to.equal('g'); expect(material.sphereMap).to.be.null; expect(material.twoSidedLighting).to.equal(false); expect(material.useFog).to.equal(true); expect(material.useGammaTonemap).to.equal(true); expect(material.useLighting).to.equal(true); expect(material.useMetalness).to.equal(false); expect(material.useMetalnessSpecularColor).to.equal(false); expect(material.useSkybox).to.equal(true); } describe('#constructor()', function () { it('should create a new instance', function () { const material = new StandardMaterial(); checkDefaultMaterial(material); }); }); describe('#clone()', function () { it('should clone a material', function () { const material = new StandardMaterial(); const clone = material.clone(); checkDefaultMaterial(clone); }); }); describe('#copy()', function () { it('should copy a material', function () { const src = new StandardMaterial(); const dst = new StandardMaterial(); dst.copy(src); checkDefaultMaterial(dst); }); }); });
const h = require("./helper"); const knex = require("./../config/knex"); const Common = require("../model/common.model"); const patient = {}; patient._formatAllergies = allergies => { if (allergies.length > 0) { const formattedAllergies = h.map(allergies, function (obj) { return { mrno: obj.mrno, allergyCode: obj.code, allergyDescription: obj.generic, defaultSelectedSeverityLevel: (obj.allergy_level == 'SEVERE') ? 'S' : (obj.allergy_level == 'MILD' ? 'M' : 'D'), defaultSelectedAllergyType: obj.type, }; }); return formattedAllergies; } else { return [] } } patient._formatDiagnosis = diagnosis => { if (diagnosis.length > 0) { const formattedDiagnosis = h.map(diagnosis, function (obj) { return { code: obj.code, name: obj.name, ref_code: obj.ref_code }; }); return formattedDiagnosis; } else { return [] } } patient._formatDiagnostics = diagnostics => { if (diagnostics.length > 0) { const formattedDiagnostics = h.map(diagnostics, function (obj) { return { service_description: obj.service_description, service_id: obj.service_id, clinicalHistory: obj.clinical_det, specialInstruction: obj.special_instruction, type: obj.site, fasting: obj.fasting, full_bladder: obj.full_bladder, stat: obj.periority, is_asked_rightleft: obj.is_asked_rightleft, prev_code: obj.prev_code, }; }); return formattedDiagnostics; } else { return [] } } patient._formatMedicines = medicines => { if (medicines.length > 0) { const formattedMedicines = h.map(medicines, function (obj) { return { medication: obj.medication, generic: obj.generic, medicine_code: obj.medicine_code, route: obj.route, dosage: obj.dose_unit, dosage_name: obj.dosage_name, unit: obj.unit, form: obj.form, gen_code: obj.gen_code, enteredLength: obj.length, enteredremarks: obj.remarks, selectedLength: obj.len_unit, selectedfrequency: obj.freq, selectedfrequency_name: obj.freq_name, selectedmealinstruction: obj.meal_instructions, total_dosage: obj.qty, medication_frequency: obj.medication_frequency }; }); return formattedMedicines; } else { return [] } } patient._formatMedicinesHistory = medicines => { if (medicines.length > 0) { const formattedMedicines = h.map(medicines, function (obj) { return { medication: obj.medication, generic: obj.generic, medicine_code: obj.medicine_code, route: obj.route, dosage: obj.dose_unit, dosage_name: obj.dosage_name, unit: obj.unit, form: obj.form, gen_code: obj.gen_code, enteredLength: obj.length, enteredremarks: obj.remarks, selectedLength: obj.len_unit, selectedfrequency: obj.freq, selectedfrequency_name: obj.freq_name, selectedmealinstruction: obj.meal_instructions, total_dosage: obj.qty, medication_frequency: obj.medication_frequency, visit_date: obj.visit_date, doctor_id: obj.doctor_id, doctor_name: obj.doctor_name }; }); return formattedMedicines; } else { return [] } } patient._formatDoctors = medicines => { if (medicines.length > 0) { const formattedMedicines = h.map(medicines, function (obj) { return { doctor_id: obj.doctor_id, doctor_name: obj.doctor_name }; }); return formattedMedicines; } else { return [] } } patient._formatInvite = invite => { if (h.checkExistsNotEmptyGreaterZero(invite, 'meetingid')) { return { status: true, start_url: invite.start_url } } else { return { status: false, start_url: "" } } } patient._formatVitals = (vitalsAndDefinitions, previousVitals) => { if (vitalsAndDefinitions.length > 0) { const vitals_definitions = h.map(vitalsAndDefinitions, function (obj) { return { vital_id: obj.vital_id, description: obj.label, unit: obj.unit, speciality_id: obj.speciality_id, value_type: obj.value_type, min_val: obj.min_val, max_val: obj.max_val, range_lower: obj.range_lower, range_upper: obj.range_upper, value_range: obj.value_range, mrno: obj.mrno, visit_id: obj.visit_id, result: obj.result, }; }); const formattedVitals = []; for (const v of vitals_definitions) { var p_vital = previousVitals.find(obj => { return obj.vital_id === v.vital_id }) formattedVitals.push({ ...v, previousVitalResult: h.checkExistsNotEmpty(p_vital, 'result') ? p_vital.result : '' }) } return formattedVitals; } else { return [] } } patient._formatPresentingComplaints = visit => { if (h.checkExistsNotEmpty(visit, 'pc')) { return visit.pc; } else { return '' } } patient._formatClinicalDetails = visit => { if (h.checkExistsNotEmpty(visit, 'clinical_details')) { return visit.clinical_details; } else { return '' } } patient._formatImpression = visit => { if (h.checkExistsNotEmpty(visit, 'impression')) { return visit.impression; } else { return '' } } patient._formatFollowUp = visit => { if (h.checkExistsNotEmpty(visit, 'followup_d')) { return visit.followup_d; } else { return '' } } patient._formatFollowUpSelect = visit => { if (h.checkExistsNotEmpty(visit, 'followup_unit')) { return visit.followup_unit; } else { return '' } } patient._formatVisitDate = visit => { if (h.checkExistsNotEmpty(visit, 'visit_date')) { return visit.visit_date; } else { return h.dateFormat(new Date(), 'YYYY-MM-DD HH:mm:ss') } } patient._formatHomeServices = visit => { if (h.checkExistsNotEmptyGreaterZero(visit, 'home_services')) { return 1; } else { return 0; } } patient._formatManagementPlan = visit => { if (h.checkExistsNotEmpty(visit, 'management_plan')) { return visit.management_plan; } else { return '' } } patient._formatPhysicalExamination = visit => { if (h.checkExistsNotEmpty(visit, 'physical_examination')) { return visit.physical_examination; } else { return '' } } patient._formatOtherInstruction = visit => { if (h.checkExistsNotEmpty(visit, 'other_instruction')) { return visit.other_instruction; } else { return '' } } patient._constNotesDTO = (d) => { let obj = { "pc": d.presentingComplaints, "impression": d.impression, "plan": d.managementPlan, "objective": d.physicalExamination, "note": d.clinicalDetails, "other_instruction": d.other_instruction, // "followup": h.exists(d.followup) ? new Date(d.followup) : '', "followup_d": h.exists(d.followupEnter) ? d.followupEnter : '', "followup_unit": h.exists(d.followupSelect) ? d.followupSelect : '', "home_services": h.checkExistsNotEmptyGreaterZero(d, 'home_services') ? '1' : '0', "visit_date": h.exists(d.visit_date) ? new Date(d.visit_date) : new Date() } return obj; } patient._diagnosisDTO = (diagnosis, visit) => { let obj = { "mr#": visit.mrno, "icd_code": diagnosis.code, "visit_id": visit.visit_id, "doctor_id": visit.doctor_id, "type": diagnosis.defaultSelectedType, "ref_code1": diagnosis.ref_code, } return obj; } patient._diagnosticsDTO = (diagnostics, visit) => { let obj = { "visit_id": visit.visit_id, "service_id": diagnostics.service_id, "service": diagnostics.service_description, "clinical_det": h.checkExistsNotEmpty(diagnostics, 'clinicalHistory') ? diagnostics.clinicalHistory : '', "special_instruction": h.checkExistsNotEmpty(diagnostics, 'specialInstruction') ? diagnostics.specialInstruction : '', "site": h.checkExistsNotEmpty(diagnostics, 'type') ? diagnostics.type : '', "fasting": h.checkExistsNotEmpty(diagnostics, 'fasting') ? diagnostics.fasting : '', "full_bladder": h.checkExistsNotEmpty(diagnostics, 'full_bladder') ? diagnostics.full_bladder : '', "periority": h.checkExistsNotEmpty(diagnostics, 'stat') ? diagnostics.stat : '', } return obj; } patient._brandAllergiesDTO = (allergies, visit) => { let obj = { "mr_no": visit.mrno, "medicine_code": allergies.allergyCode, "allergy_level": allergies.defaultSelectedSeverityLevel, "is_valid": 'Y', // "entry_code": 'MOAR_BRAND_ALLERGY.nextval' } return obj; } patient._genericAllergiesDTO = (allergies, visit, subclass) => { let obj = { "mrno": visit.mrno, "active": 'Y', "allergy_level": allergies.defaultSelectedSeverityLevel, "tran_date": new Date(), "tran_by": "WEB_USER" // "entry_code": 'pharmacy_shifa.DRUG_ALLERGY_SEQ.nextval' } if (h.checkExistsNotEmpty(subclass, 'subclassid')) { obj = { ...obj, "class_code": subclass.classid, "sub_class_code": subclass.subclassid, "class_code": subclass.classid, } } else { obj = { ...obj, "gen_code": allergies.allergyCode, } } return obj; } patient._medicinesDTO = (medicine, visit) => { let obj = { "medicine": medicine.medication, "mr#": visit.mrno, "medicine_code": (medicine.medicine_code) ? medicine.medicine_code : null, "route": medicine.route, "freq": medicine.selectedfrequency, "length": medicine.enteredLength, "len_unit": medicine.selectedLength, "form": medicine.form, "start_at": knex.raw('sysdate'), "substitute": 1, "visit_id": visit.visit_id, "dose_unit": medicine.dosage, "qty": medicine.total_dosage, "remarks": medicine.enteredremarks, "doctor_id": visit.doctor_id, "meal_instructions": medicine.selectedmealinstruction, } let note = medicine.total_dosage + ' ' + medicine.dosage_name; if (medicine.enteredLength > 0) { note += ' ' + medicine.selectedfrequency_name + ' For ' + medicine.enteredLength + ' ' + medicine.selectedLength; } else { note += ' ' + medicine.selectedfrequency_name + ' ' + medicine.selectedLength; } note += ' ' + medicine.selectedmealinstruction + ' ' + medicine.enteredremarks; obj['note'] = note.replace(/ +(?= )/g, ''); //replace(/\s\s+/g, ' '); return obj; } patient._deleteConstNotesDTO = (d) => { let obj = { "isactive": 'N', "token#": '' } return obj; } patient._deleteDiagnosisDTO = (sess_user) => { let obj = { "isactive": 'F', "deactive_by": sess_user.doctor_id, "deactive_at": knex.raw('sysdate'), } return obj; } patient._deleteDiagnosticsDTO = () => { let obj = { "cancel": 'T', } return obj; } patient._deleteMedicinesDTO = (sess_user) => { let obj = { "isactive": 'N' } return obj; } patient._deleteBrandAllergyDTO = (sess_user) => { let obj = { "is_valid": 'N' } return obj; } patient._deleteGenericAllergyDTO = (sess_user) => { let obj = { "active": 'N' } return obj; } patient._invitationLogDTO = (log, invitation) => { let obj = { "visit_id": log.visit_id, "mrno": log.mrno, "phoneno": log.phoneno, "meetingid": log.id, "start_url": log.start_url, "join_url": log.join_url, "meeting_data": JSON.stringify(invitation), "status": 1 } return obj; } module.exports = patient;
import React, { Component } from 'react'; import AppHeader from '../app-header'; import SearchPanel from '../search-panel'; import ItemStatusFilter from '../item-status-filter'; import AppItemList from '../app-item-list'; import Popup from '../popup'; import ItemAddForm from '../item-add-form'; import './App.css'; export default class App extends Component { maxId = 100; state = { showPopup: false, itemsAllData: [ this.createApplianceItem('Appliance One'), this.createApplianceItem('Appliance Two'), this.createApplianceItem('Appliance Three') ] }; createApplianceItem(title, programme, timer, temperature) { return { title, programme, timer, temperature, id: this.maxId++ } } deleteItem = (id) => { this.setState(({ itemsAllData }) => { const idx = itemsAllData.findIndex((el) => el.id === id); const newArray = [ ...itemsAllData.slice(0, idx), ...itemsAllData.slice(idx + 1) ]; return { itemsAllData: newArray }; }); }; addItem = (text) => { // generate id ? const newItem = this.createApplianceItem(text); /*{ title: text, programme: '0', timer: '0', temperature: '0', id: this.maxId++ } */ // add element in array ? this.setState(({ itemsAllData }) => { const newArr = [ ...itemsAllData, newItem ]; return { itemsAllData: newArr }; }); }; updateItem = (text) => { } toggleProperty(arr, id, propName) { const idx = arr.findIndex((el) => el.id === id); // 1. update object const oldItem = arr[idx]; const newItem = {...oldItem, [propName]: !oldItem[propName]}; // 2. return new array return [ ...arr.slice(0, idx), newItem, ...arr.slice(idx + 1) ]; } onToggleProgramme = (id) => { this.setState(({ itemsAllData }) => { return { itemsAllData: this.toggleProperty(itemsAllData, id, 'programme') }; }); }; onToggleTimer = (id) => { this.setState(({ itemsAllData }) => { return { itemsAllData: this.toggleProperty(itemsAllData, id, 'timer') }; }); }; togglePopup = (id) => { this.setState({ showPopup: !this.state.showPopup }); }; render() { const { itemsAllData } = this.state; const doneCount = itemsAllData .filter((el) => el.done).length; const toselectCount = itemsAllData.length - doneCount; return ( <div className="appliance-app"> <AppHeader toSelect={toselectCount} done={doneCount} /> <div className="top-panel d-flex"> <SearchPanel /> <ItemStatusFilter /> </div> <AppItemList allItems={ this.state.itemsAllData } onDeleted={ this.deleteItem } onUpdated={ this.updateItem } onTogglePopup={this.togglePopup} /> <ItemAddForm onItemAdded={ this.addItem } /> {this.state.showPopup ? <Popup text='Select Settings' closePopup={this.togglePopup.bind(this)} /> : null } </div> ); } };
export * from "./provider"; export * from "./hook";
'use strict'; /** * @requires ../node_modules/fuse.js/dist/fuse.js * @requires ../node_modules/@babel/polyfill/dist/polyfill.min.js */ class GhostSearch { constructor(args) { this.check = false; const defaults = { host: '', key: '', version: 'v2', input: '#ghost-search-field', results: '#ghost-search-results', button: '', defaultValue: '', template: function(result) { let url = [location.protocol, '//', location.host].join(''); return '<a href="' + url + '/' + result.slug + '/">' + result.title + '</a>'; }, trigger: 'focus', options: { keys: ['title'], limit: 10, async: true, asyncChunks: 1, shouldSort: true, tokenize: true, matchAllTokens: true, includeMatches: true, includeScore: true, threshold: 0.3, location: 0, distance: 50000, maxPatternLength: 32, minMatchCharLength: 2 }, api: { resource: 'posts', parameters: { limit: 'all', fields: ['title', 'slug'], filter: '', include: '', order: '', formats: '', page: '' }, }, on: { beforeDisplay: function(){}, afterDisplay: function(results){}, beforeFetch: function(){}, afterFetch: function(results){}, beforeSearch: function(){} } } const merged = this.mergeDeep(defaults, args); Object.assign(this, merged); this.init(); } mergeDeep(target, source) { if ((target && typeof target === 'object' && !Array.isArray(target) && target !== null) && (source && typeof source === 'object' && !Array.isArray(source) && source !== null)) { Object.keys(source).forEach(key => { if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key]) && source[key] !== null) { if (!target[key]) Object.assign(target, { [key]: {} }); this.mergeDeep(target[key], source[key]); } else { Object.assign(target, { [key]: source[key] }); } }); } return target; } fetch(){ this.on.beforeFetch(); let ghostAPI = new GhostContentAPI({ host: this.host, key: this.key, version: this.version }); let browse = {} let parameters = this.api.parameters; for (var key in parameters) { if(parameters[key] != ''){ browse[key] = parameters[key] } } ghostAPI[this.api.resource] .browse(browse) .then((data) => { this.search(data); }) .catch((err) => { console.error(err); }); } createElementFromHTML(htmlString) { var div = document.createElement('div'); div.innerHTML = htmlString.trim(); return div.firstChild; } displayResults(data) { this.on.beforeSearch(); let inputValue = document.querySelectorAll(this.input)[0].value.trim(); if (this.defaultValue != '') { inputValue = this.defaultValue; } if (this.options.async) { this.searchAsyncImproved(data, inputValue) .catch(e => { console.error(e) }); } else { const fuse = new Fuse(data, this.options); const results = fuse.search(inputValue); this.displayResultsInBrowser(results); } } async searchAsync(fuse, inputValue) { let promise = new Promise(function(resolve, reject) { resolve(fuse.search(inputValue)); }); let results = await promise; return results; } async searchAsyncImproved(data, inputValue) { const chunksCount = this.options.asyncChunks; const promises = []; for (let i=0; i < data.length; i+=chunksCount) { const fuse = new Fuse(data.slice(i, i + chunksCount), this.options); const promiseInstance = new Promise(function(resolve, reject) { setTimeout(() => resolve(fuse.search(inputValue)), 0); }); promises.push(promiseInstance); } let results = await Promise.all(promises); results = results.flat().sort((a, b) => { return a.score - b.score }); this.displayResultsInBrowser(results); } displayResultsInBrowser(results) { results = results.slice(0, this.options.limit); let tempBlock = document.createElement('div'); for (let key in results) { if (key < results.length) { let item = results[key]; /* For case if includeMatches turned on */ if (item.matches) item = item.item; //document.querySelectorAll(this.results)[0].appendChild(this.createElementFromHTML(this.template(item))); tempBlock.appendChild(this.createElementFromHTML(this.template(item))); } } document.querySelectorAll(this.results)[0].innerHTML = tempBlock.innerHTML; this.on.afterDisplay(results); this.defaultValue = ''; } search(data){ this.on.afterFetch(data); this.check = true; if(this.defaultValue != ''){ this.on.beforeDisplay() this.displayResults(data) } if (this.button != '') { let button = document.querySelectorAll(this.button)[0]; if (button.tagName == 'INPUT' && button.type == 'submit') { button.closest('form').addEventListener("submit", e => { e.preventDefault() }); }; button.addEventListener('click', e => { e.preventDefault() this.on.beforeDisplay() this.displayResults(data) }) }else{ document.querySelectorAll(this.input)[0].addEventListener('keyup', e => { this.on.beforeDisplay() this.displayResults(data) }) }; } checkArgs(){ if(!document.querySelectorAll(this.input).length){ console.log('Input not found.'); return false; } if(!document.querySelectorAll(this.results).length){ console.log('Results not found.'); return false; }; if(this.button != ''){ if (!document.querySelectorAll(this.button).length) { console.log('Button not found.'); return false; }; } if(this.host == ''){ console.log('Content API Client Library host missing. Please set the host. Must not end in a trailing slash.'); return false; }; if(this.key == ''){ console.log('Content API Client Library key missing. Please set the key. Hex string copied from the "Integrations" screen in Ghost Admin.'); return false; }; return true; } validate(){ if (!this.checkArgs()) { return false; }; return true; } init(){ if (!this.validate()) { return; } if(this.defaultValue != ''){ document.querySelectorAll(this.input)[0].value = this.defaultValue; window.onload = () => { if (!this.check) { this.fetch() }; } } if (this.trigger == 'focus') { document.querySelectorAll(this.input)[0].addEventListener('focus', e => { if (!this.check) { this.fetch() }; }) }else if(this.trigger == 'load'){ window.onload = () => { if (!this.check) { this.fetch() }; } } } }
controllers .controller('logoutController', function($state, AccountManager) { console.log('logout controller'); var vm = this; AccountManager.logout(); });
let targets = []; let title; let titleOpacity = 255; function setup() { createCanvas(windowWidth, windowHeight); title = loadImage('./assets/title.png'); imageMode(CENTER); textAlign(CENTER); } function draw() { background(0); noStroke(); if (titleOpacity > 0.01) { tint(255, titleOpacity) image(title, width/2, height/2-50, title.width/title.height*125, 125); fill(255, titleOpacity); textSize(height/42) textStyle(BOLD); text('toque em qualquer lugar para começar', width/2, height/2+50); if (!("vibrate" in window.navigator)) { textStyle(ITALIC); text('*navegador não suporta a função de vibração', width/2, height-100); } if (targets.length > 0) { titleOpacity = lerp(titleOpacity, 0, 0.1) } } noFill() for (let i = 0; i < targets.length; i++) { for (let j = 0; j < targets.length; j++) { if (i != j && targets[i].checkIntersection(targets[j])) { if ("vibrate" in window.navigator) { window.navigator.vibrate((targets[i].opacity*targets[j].opacity)/sq(255)*50); } } } targets[i].display(); targets[i].grow(); if (targets[i].opacity <= 0) { targets.pop(i) } } } function touchStarted() { if (targets.length < 3) { targets.push(new Target(mouseX, mouseY)) if ("vibrate" in window.navigator) { window.navigator.vibrate(50); } } } class Target { constructor(x, y) { this.position = createVector(x, y) this.diameter = 0; this.speed = 2.5; this.thickness = 50; this.opacity = 255 } grow() { this.diameter+= this.speed this.speed+= 0.001 this.opacity-= this.speed/10 } checkIntersection(target) { if (this.position.dist(target.position) < this.diameter/2 + target.diameter/2) { let intersection = (this.diameter/2 + target.diameter/2 - this.position.dist(target.position))%(this.thickness/4) if (intersection > 0 && intersection < 5) { return true } } } display() { stroke(255, this.opacity) for (let i = this.diameter; i > 0; i-= this.thickness) { strokeWeight(this.thickness/4) if (i-this.thickness <= 0) { strokeWeight(this.thickness/4*(i/this.thickness)) } ellipse(this.position.x, this.position.y, i, i) } } }
/** * Created by m314029 on 8/7/2017. */ 'use strict'; /** * Constructs the API to call the backend for custom hierarchy. * * @author m314029 * @since 2.11.0 */ (function(){ angular.module('productMaintenanceUiApp').factory('CustomHierarchyApi', customHierarchyApi); customHierarchyApi.$inject = ['urlBase', '$resource']; /** * Constructs the API. * * @param urlBase The base URL to contact the backend. * @param $resource Angular $resource to extend. * @returns {*} The API. */ function customHierarchyApi(urlBase, $resource) { var unassignProductUrlBase = urlBase; urlBase = urlBase + '/pm/customHierarchy'; return $resource( urlBase ,null, { 'findAllHierarchyContexts': { method: 'GET', url: urlBase + '/hierarchyContext/findAll', isArray:true }, 'findRelationshipByHierarchyContext': { method: 'POST', url: urlBase + '/entityRelationship/findByHierarchyContext', isArray:true }, 'getCustomHierarchyBySearch': { method: 'GET', url: urlBase + '/hierarchyContext/getCustomHierarchyBySearch', isArray:true }, 'getCustomHierarchyByChild': { method: 'GET', url: urlBase + '/hierarchyContext/getCustomHierarchyByChild', isArray:false }, 'updateCustomHierarchy': { method: 'POST', url: urlBase + '/hierarchyContext/updateCustomHierarchy', isArray:true }, 'addCustomHierarchy': { method: 'POST', url: urlBase + '/hierarchyContext/addCustomHierarchy', isArray:false }, 'loadCustomerHierarchyContext': { method: 'GET', url: urlBase + '/hierarchyContext/customerHierarchyContext', isArray:false }, 'updateCurrentLevel': { method: 'POST', url: urlBase + '/entityRelationship/updateCurrentLevel', isArray:false }, 'getCurrentLevelImages': { method: 'GET', url: urlBase + '/imageInformation/getImageInfo', isArray:true }, 'getImage': { method: 'POST', url: urlBase + '/imageInformation/getImages', isArray:false }, 'getImageCategories': { method: 'GET', url: urlBase + '/imageInformation/getImageCategories', isArray:true }, 'getImageStatuses': { method: 'GET', url: urlBase + '/imageInformation/getImageStatuses', isArray:true }, 'getImagePriorities': { method: 'GET', url: urlBase + '/imageInformation/getImagePriorities', isArray:true }, 'getImageSources': { method: 'GET', url: urlBase + '/imageInformation/getImageSources', isArray:true }, 'updateImageMetadata': { method: 'POST', url: urlBase + '/imageInformation/updateImages', isArray:false }, 'uploadImageMetadata': { method: 'POST', url: urlBase + '/imageInformation/uploadImage', isArray:false }, 'findAllParentsByChild': { method: 'GET', url: urlBase + '/entityRelationship/findAllParentsByChild', isArray: true }, 'massUpdate': { method: 'POST', url: unassignProductUrlBase + "/pm/massUpdate", isArray: false }, 'findProductsByParent': { method: 'POST', url: urlBase + "/entityRelationship/findProductsByParent", isArray: false }, 'linkLevels': { method: 'POST', url: urlBase + '/entityRelationship/linkLevels', isArray: false }, 'moveLevels': { method: 'POST', url: urlBase + '/entityRelationship/moveLevels', isArray: false }, 'saveRemoveLevel': { method: 'POST', url: urlBase + '/hierarchyContext/saveRemoveLevel', isArray:false }, 'deleteAllRemoveLevel': { method: 'POST', url: urlBase + '/hierarchyContext/deleteAllRemoveLevel', isArray:false }, 'deleteSingleRemoveLevel': { method: 'POST', url: urlBase + '/hierarchyContext/deleteSingleRemoveLevel', isArray:false }, 'findAllCustomerProductGroupsByParent': { method: 'POST', url: urlBase + "/entityRelationship/findAllCustomerProductGroupsByParent", isArray: false }, 'findAllCustomerProductGroupsNotOnParentEntity': { method: 'GET', url: urlBase + "/entityRelationship/findAllCustomerProductGroupsNotOnParentEntity", isArray: true }, 'getImmediateNonProductChildren': { method: 'GET', url: urlBase + "/entityRelationship/getImmediateNonProductChildren", isArray: true }, 'getCurrentLevel': { method: 'POST', url: urlBase + "/entityRelationship/getResolvedCurrentLevelByKey", isArray: false }, 'findAttributesByHierarchyContextAndEntity': { method: 'GET', url: urlBase + "/attribute/findAttributesByHierarchyContextAndEntity", isArray: true } } ); } })();
import React from 'react' import { useHistory } from 'react-router' import './style.scss' const dialogType = { login: { title:'Join with us', desc:'You are not logged in. Please login & try again.' }, empty: { title:'Order us services', desc:'Your cart is empty. Please order & try again.' }, success: { title:'Order Successfully Places', desc:'Thank you for ordering. We received your order & will begin processing it soon.' } } const Dialog = (props) => { const {isShow, onShow, type} = props const history= useHistory() const handleLogin = () => { onShow(!isShow) if(type === 'login') { history.push('/login') } else { history.push('/product') } } return ( <> <div className = {`dialog ${isShow && 'active'}`}> <h3> <i className='bx bxs-info-circle'></i> {dialogType[type]?.title} </h3> <span>{dialogType[type]?.desc}</span> <div className="dialog__button"> <button className="btn btn__close btn--small btn--rounded-sm btn--secondary" onClick = {() => onShow(!isShow)}> Close </button> <button className="btn btn--primary btn--rounded-sm btn--small btn__login " onClick = {handleLogin}> {type === 'login' ? 'Login' : type === 'success' ? 'Continue Order' : 'Order now'} </button> </div> </div> <div className={`dialog__overlay ${isShow && 'active'}`}></div> </> ) } export default Dialog
import React, {Component} from 'react'; import moment from 'moment'; import Alert from "./partials/Alert"; import {Redirect} from 'react-router-dom'; import PropTypes from 'prop-types'; import User from "../data/User"; class Login extends Component { constructor(props) { super(props); this.state = { email: "", password: "", errorMessage: null, } } handleSubmit(e) { e.preventDefault(); this.setState({errorMessage: null}); const {email, password} = this.state; if (!(email && password)) { window.notificationSystem.addNotification({ level: 'warning', message: "Please enter your email and password", }); return; } axios.post('/api/login', { email, password }) .then(({data}) => { if(!('user' in data)) { throw new Error("Wrong server answer format"); } window.user = new User(data.user); this.context.router.history.push('/dashboard'); }) .catch(error => { this.setState({ errorMessage: error.response ? (error.response.data.email || error.response.data.password || error.message) : error.message, }); }) } handleChange(field) { return ({target}) => { this.setState({[field]: target.value}); }; } render() { if(window.user === undefined) { return <Redirect to="/"/>; } return <div className="signup-page"> <div className="wrapper"> <div className="header header-filter" style={{ backgroundImage: 'url(https://source.unsplash.com/random)', backgroundSize: 'cover', backgroundPosition: 'top center', }}> <div className="container"> <div className="row"> <div className="col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3"> <div className="card card-signup"> <div className="header header-info text-center"> <h4>Log In</h4> <h2>The Workfow</h2> </div> <form onSubmit={this.handleSubmit.bind(this)}> <Alert type="danger" isOpen={!!this.state.errorMessage}> {this.state.errorMessage} </Alert> <div className="form-group label-floating"> <label className="control-label">Email</label> <input type="text" className="form-control" value={this.state.email} onChange={this.handleChange('email')}/> <span className="material-input"/> </div> <div className="form-group label-floating"> <label className="control-label">Password</label> <input type="password" className="form-control" value={this.state.password} onChange={this.handleChange('password')}/> <span className="material-input"/> </div> <button type="submit" className="btn btn-primary pull-right"> Login </button> <div className="clearfix"/> </form> </div> </div> </div> </div> <footer className="footer"> <div className="container"> <div className="copyright pull-right"> &copy; {moment().format('YYYY')}, made with <i className="fa fa-heart heart"/> using <a href="http://github.com/horat1us/workflow" target="_blank">GitHub</a> </div> </div> </footer> </div> </div> </div>; } } Login.contextTypes = { router: PropTypes.shape({ history: PropTypes.object.isRequired, }), }; export default Login;
import React, { Component } from 'react'; import './App.css'; import { Switch, Redirect, Route } from 'react-router'; import { BrowserRouter, Link } from 'react-router-dom'; import Clients from './components/Clients/Clients'; import SingleClientComponent from './components/Clients/SingleClientComponent'; import ClientAdministrationContainer from './components/ClientAdministration/ClientAdministrationContainer'; import noMatch from './components/Navigation/noMatch'; import HomePage from './components/Navigation/HomePage'; import ClientCardContainer from './components/Clients/ClientCardContainer'; import UpdatingClientContainer from './components/ClientAdministration/UpdatingClientContainer'; import NewClientContainer from './components/ClientAdministration/NewClientContainer' class App extends Component { render() { return ( <BrowserRouter> <HomePage> <Switch> <Route exact path='/' component={Clients} /> <Route exact path='/clients/:name' component={ClientCardContainer}/> <Route exact path="/clients/:name" component={SingleClientComponent} /> <Route exact path='/admin' component={ClientAdministrationContainer} /> <Route exact path="/admin/clients/new" component={NewClientContainer} /> <Route exact path="/admin/clients/:name" component={UpdatingClientContainer} /> <Route path="*" component={noMatch} /> <Route component={HomePage} /> </Switch> </HomePage> </BrowserRouter> ); } } export default App;
import { Button, Card, Grid, Paper } from "@mui/material"; export const Home = () => { return ( <div> <Paper elevation={1} sx={{ width: "98.5vw", height: "98vh", backgroundColor: "slategray", margin: ".5vw", marginTop: "1vh", }} > <Paper elevation={3} sx={{ marginBottom: "2vw" }}> <Grid container spacing={2}> <Grid item xs={2} sx={{ display: "flex", justifyContent: "center", alignItems: "center", }} > <Button variant="contained" color="warning"> Left </Button> </Grid> <Grid item xs={8}> <Card sx={{ display: "flex", height: "60vw", width: "60vw", justifyContent: "center", alignItems: "center", }} > <div>Center</div> </Card> </Grid> <Grid item xs={2} sx={{ display: "flex", justifyContent: "center", alignItems: "center", }} > <Button variant="contained" color="warning" sx={{ margin: "auto" }} > Right </Button> </Grid> </Grid> </Paper> </Paper> </div> ); };
import React, {Component} from 'react' export default class CandyList extends Component { render() { return ( <section className="candies"> <h1>Candy List</h1> { this.props.candies.map(candie => <div key={candie.id}> <div><strong>Candy: </strong>{candie.name}</div> <div><strong>Type: </strong> { this.props.candyTypes .find(type => type.id === candie.candyTypeId).type } </div> </div> ) } </section> ) } }
import Joi from "joi"; const ValidateDTO = class ValidateDTO { static getProduct(params) { const schema = Joi.number().required(); return schema.validate(params); } }; export default ValidateDTO;
'use strict' module.exports = (app, db) => { app.get('/bookmarks', (req, res) => { var sess = req.session if (typeof sess.userid != 'undefined'){ db.account.findOne({ where: {userid:sess.userid}, include: [{model: db.bookmark, include: [db.scanProfile, db.trigger]}] }) .then( account=>{ res.json( account.bookmarks.map( bm=>{ return { id: bm.id, active: bm.active, scanProfile: bm.scanProfile.dataValues, trigger: bm.trigger.dataValues } } ) ) }, err=>{ res.status(401).send() } ) } else { res.status(401).send() } }) app.post('/bookmarks/', (req, res) => { var sess = req.session var triggerId = req.body.trigger var defaultProfile = { exchange: req.body.exchange, coin: req.body.coin, asset: req.body.asset, interval: req.body.interval } if (typeof sess.userid != 'undefined'){ db.account.findOne({ where: {userid:sess.userid} }) .then( account => { db.scanProfile.findOrCreate({ where: defaultProfile, defaults: defaultProfile }) .spread( (profile, created) => { db.bookmark.create({ scan_profile_id: profile.id, trigger_id: triggerId, account_id: account.id, active: true }) .then(bookmark => { res.json(bookmark.dataValues) }) if (created) { //TODO: Check this default. shoul be in model definition? profile.limit = 20 profile.save() } } ) } ) } }) }
module.exports = { View: {}, Model: {}, Layout: {}, Collection: {}, Controller: {} };
/* Project specific Javascript goes here. */ /* Formatting hack to get around crispy-forms unfortunate hardcoding in helpers.FormHelper: if template_pack == 'bootstrap4': grid_colum_matcher = re.compile('\w*col-(xs|sm|md|lg|xl)-\d+\w*') using_grid_layout = (grid_colum_matcher.match(self.label_class) or grid_colum_matcher.match(self.field_class)) if using_grid_layout: items['using_grid_layout'] = True Issues with the above approach: 1. Fragile: Assumes Bootstrap 4's API doesn't change (it does) 2. Unforgiving: Doesn't allow for any variation in template design 3. Really Unforgiving: No way to override this behavior 4. Undocumented: No mention in the documentation, or it's too hard for me to find */ $('.form-group').removeClass('row'); //$(function () { // // /* Functions */ // // var loadForm = function () { // var btn = $(this); // $.ajax({ // url: btn.attr("data-url"), // type: 'get', // dataType: 'json', // beforeSend: function () { // $("#modal-equipment .modal-content").html(""); // $("#modal-equipment").modal("show"); // }, // success: function (data) { // $("#modal-equipment .modal-content").html(data.html_form); // } // }); // }; // // var saveForm = function () { // var form = $(this); // $.ajax({ // url: form.attr("action"), // data: form.serialize(), // type: form.attr("method"), // dataType: 'json', // success: function (data) { // if (data.form_is_valid) { // $("dataTables-equipment tbody").html(data.html_list); // $("#modal-equipment").modal("hide"); // } // else { // $("#modal-equipment .modal-content").html(data.html_form); // } // } // }); // return false; // }; // // // /* Binding */ // // // Create // $(".js-create-equipment").click(loadForm); // $("#modal-equipment").on("submit", ".js-equipment-create-form", saveForm); // // // Update // $("#dataTables-equipment").on("click", ".js-update-equipment", loadForm); // $("#modal-equipment").on("submit", ".js-equipment-update-form", saveForm); // // // Delete // $("#dataTables-equipment").on("click", ".js-delete-equipment", loadForm); // $("#modal-equipment").on("submit", ".js-equipment-delete-form", saveForm); // //});
import React from "react"; import Image from "next/image"; const index = () => { return ( <div style={{ width: "100%" }}> <Image src='/images/br_post_page_footer.png' alt='End of Page Footer' layout='responsive' width={2352} height={724} /> </div> ); }; export default index;
highway_bus_8042_interval_name = ["臺南<br />航空站","奇美<br />博物館","高鐵<br />臺南站","阿蓮","崗山頭","月世界","古亭","鹿埔","馬頭山","旗山","中埔"]; highway_bus_8042_interval_stop = [ ["臺南航空站"], // 臺南航空站 ["奇美博物館"], // 奇美博物館 ["高鐵臺南站"], // 高鐵臺南站 ["崙仔頂","阿蓮分駐所","阿蓮","中正路","工業區","源勝社區","磚子窯"], // 阿蓮 ["大埤","南崗山","峰山里","崗山頭","崗山頭溫泉","崗安路","崗山頭市場"], // 崗山頭 ["竹山","糖廠(西德社區)","營盤頂","崇德國小","崇德市場","北勢宅","月世界","日月禪寺","古亭橋"], // 月世界 ["南勢崎頂","古亭水庫","古亭"], // 古亭 ["鹿埔","鹿埔分校","內門路口"], // 鹿埔 ["馬頭山頂","馬頭山","旗山分校","喬覺寺","鼓山崎嶺"], // 馬頭山 ["旗亭橋","中學路","德昌路","旗山轉運站","延平路","旗山市場","中華路口","旗山北站"], // 旗山 ["旗山監理所","朝天宮","嶺頂","實踐大學"] // 中埔 ]; highway_bus_8042_fare = [ [26], [26,26], [26,26,26], [51,46,26,26], [62,57,35,26,26], [77,72,50,26,26,26], [84,79,57,33,26,26,26], [92,87,66,41,30,26,26,26], [103,99,77,53,42,27,26,26,26], [122,118,96,72,61,46,39,30,26,26], [138,133,111,87,76,61,54,46,34,26,26] ]; // format = [time at the start stop] or // [time, other] or // [time, start_stop, end_stop, other] highway_bus_8042_main_stop_name = ["臺南航空站<br /><font color=\"red\">(假日延駛)</font>","奇美博物館<br /><font color=\"red\">(假日延駛)</font>","高鐵臺南站","阿蓮分駐所","崗山頭","月世界","旗山轉運站","旗山北站","實踐大學"]; highway_bus_8042_main_stop_time_consume = [0,2,17,32,37,45,62,67,77]; highway_bus_8042_important_stop = [0, 1, 2, 6, 8]; // 臺南航空站, 奇美博物館, 高鐵台南站, 旗山轉運站, 實踐大學 highway_bus_8042_time_go = [ ["08:58"],["10:18"],["12:13"],["13:58"],["16:03"],["18:43"] ]; highway_bus_8042_time_return = [ ["07:30"],["08:50"],["10:45"],["12:30"],["14:15"],["17:15"] ];
import * as d3 from 'd3'; export default function GridChart(ciudades, target) { const GridChart = {}; const getRubros = (ciudades) => { let rubrs = [] console.log("ciudades", ciudades) ciudades.forEach(ciudad => ciudad.irregularidadesEncontradas.forEach(rubro => rubrs.push(rubro.name))) return [... new Set(rubrs)] }; const rubros = ["ciudad"].concat(getRubros(ciudades)); const marginTopDown = 100; const marginLeftRight = 400; const p = 4; const r = 100; const cols = ciudades.length; const rows = rubros.length; const nElements = ciudades.length * rubros.length; const width = 20 * cols + 2 * marginLeftRight; const height = 20 * rows + 2 * marginTopDown;; const gridLayout = function (cols, rows, padding, width, height) { let __c = d3.scaleOrdinal().domain(d3.range(cols * rows)).range(d3.range(marginLeftRight, width - marginLeftRight, (width - 2 * marginLeftRight) / cols)); let __r = d3.scaleQuantile().domain([0, cols * rows]).range(d3.range(marginTopDown, height - marginTopDown, (height - 2 * marginTopDown) / rows)); let c = d3.scaleOrdinal().domain(d3.range(cols * rows)).range(d3.range(cols)); let r = d3.scaleQuantile().domain([0, cols * rows]).range(d3.range(rows)); // let __cellWidth = (width - 2 * marginLeftRight) / cols; // let __cellHeight = (height - 2 * marginTopDown) / rows; //let __cellHeight = (height - 2 * marginTopDown) / rows; let __cellWidth = 20; let __cellHeight = 20; let __boxWidth = __cellWidth - padding * 2; let __boxHeight = __cellHeight - padding * 2; function gridLayout(selection) { let grid = d3.select(selection.node().parentNode).append("g").attr("class", "grid"); return selection.each(function (d, i) { let el = this; let grr = grid.append("g") .attr("class", _ => "cell " + "col-" + c(i) + " row-" + r(i)) .attr("transform", function (_) { let span_element = document.createElement("span"); document.body.appendChild(span_element); d3.select(span_element).append("svg").attr("width", width).attr("hieght", height).append(x => el); //d3.select(span_element).append("svg").attr("width", __cellWidth*cols+2*marginTopDown).attr("hieght", height).append(x => el); let size = d3.select(el).node().getBBox() document.body.removeChild(span_element); let fw = size.width > __boxWidth ? __boxWidth / size.width : 1; let fh = size.height > __boxHeight ? __boxHeight / size.height : 1; let xp = 0; let yp = 0; if (fw > fh) xp = (__boxWidth - (fh * size.width)) / 2; if (fh > fw) yp = (__boxHeight - (fw * size.height)) / 2; if (fh == fw) { xp = (__boxWidth - (fh * size.width)) / 2; yp = (__boxHeight - (fw * size.height)) / 2; } return "translate(" + (__c(i) + padding + xp) + " " + (__r(i) + padding + yp) + ")" + " " + "scale(" + d3.min([fw, fh]) + ")" }); grr.append(x => el); grr.append("text").text(dd => { let coord = getGridCoordinates(d, ciudades.length) let ciudad = ciudades[coord[0]] let rubro = rubros[coord[1]] if (rubro == "ciudad") return ciudad.name else return "" }) .attr("font-family", "sans-serif") .attr("font-size", "200px") .attr("fill", "black") .attr("transform", "translate(175,0) rotate(270)"); }) }; gridLayout.rows = rows; gridLayout.cols = cols; gridLayout.width = width; gridLayout.height = height; gridLayout.padding = padding; return gridLayout; }; const getGridCoordinates = (n, grx) => { let lvy = Math.floor(n / grx); let lvx = n % grx; return [lvx, lvy]; }; const yAxis = svg => svg .attr("transform", `translate(${marginLeftRight},0)`) .call(d3.axisLeft(yy)); const yy = d3.scaleBand() .domain(rubros) .range([marginTopDown, height - marginTopDown]); GridChart.pintar = () => { d3.select(target).selectAll("svg").remove(); const svgg = d3.select(target).append("svg").attr("width", width).attr("height", height) svgg.append("g") .call(yAxis); var circulos = svgg.selectAll("circle").data(d3.range(nElements)).enter().append("circle") .attr("r", r).attr("cx", r).attr("cy", r) .attr("fill", d => { let coord = getGridCoordinates(d, ciudades.length) let ciudad = ciudades[coord[0]] let rubro = rubros[coord[1]] let incos = ciudad.irregularidadesEncontradas.find(d => d.name == rubro) if (rubro == "ciudad") return "white" return incos ? incos.ingreso ? "#F9CA3D" : "#B75952" : "#9E9FA3" }); circulos.call(gridLayout(cols, rows, p, width, height)); return svgg.node(); }; return GridChart; }
import React from "react" import Layout from "../components/layout" const services = () => { return ( <Layout> <h1>Our Services</h1> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Neque dolorem ullam, vero sapiente obcaecati provident unde? Quo ipsam itaque quod error deserunt sint, cupiditate ducimus veniam beatae, iusto aperiam nam? </p> <p> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Sed neque quis esse voluptatibus expedita doloremque temporibus asperiores optio voluptate qui! </p> </Layout> ) } export default services
var log = require('../log/log'); var authentication = require('../authentication/authentication'); module.exports = angular .module('login', [ log.name, authentication.name, 'ui.router', 'ct.ui.router.extras' ]) .config(function ($stateProvider) { $stateProvider.state('login', { url: '/login', views: { 'modal@': { templateUrl: 'login/login.tpl.html', controller: 'LoginCtrl as loginCtrl' } }, isModal: true }); }); require('./login-controller');
/* Like projection, filtering an array is also a very common operation. To filter an array we apply a test to each item in the array and collect the items that pass into a new array. */ var newReleasesMov = [ { "id": 1, "title": "Hard", "boxart": "Hard.jpg", "uri": "http://vikask/movies/1", "rating": [4.0], "bookmark": [] }, { "id": 2, "title": "Bad", "boxart": "Bad.jpg", "uri": "http://vikask/movies/2", "rating": [5.0], "bookmark": [{ id: 1, time: 2 }] }, { "id": 3, "title": "Cham", "boxart": "Cham.jpg", "uri": "http://vikask/movies/3", "rating": [4.0], "bookmark": [] }, { "id": 4, "title": "Fra", "boxart": "Fra.jpg", "uri": "http://vikask/movies/4", "rating": [5.0], "bookmark": [{ id: 4, time: 6 }] } ], videos = []; newReleases.filter(video => { if (video.rating == 5) { videos.push(video); } }) console.log(videos);
const UglyfyjsWebpackPlugin=require("uglifyjs-webpack-plugin"); const webpackMerge=require('webpack-merge'); const baseConfig = require("./base.config"); module.exports=webpackMerge(baseConfig,{ plugins:[ new UglyfyjsWebpackPlugin() //开发时不用这个,不好调试,最终打包再用 ] } )