text
stringlengths
7
3.69M
export const postRequest = async (body) => { const response = await fetch('/message', { method: 'POST', body: JSON.stringify(body), headers: { "Content-type": "application/json; charset=UTF-8" } }); const responseJson = await response.json(); console.log(responseJson); return responseJson; };
function solve(arr) { let count=0; for (let i = 0; i < arr.length-1; i++) { for (let j = 1; j < arr[i].length; j++) { let current=arr[i][j]; if (current==arr[i+1][j]) { count++; } else if (current==arr[i][j-1]) { count++; } } } for (let i = 0; i < arr.length-1 ; i++) { if (arr[i][0]==arr[i+1][0]) { count++; } } for (let i = 0; i < arr[arr.length-1].length; i++) { if (arr[arr.length-1][i]==arr[arr.length-1][i+1]) { count++; } } return count; } console.log(solve([['2','2','5','7','4'], ['4','0','5','3','4'], ['2','5','5','4','2']]))
import React from 'react'; import './header.css'; const Header = (props) => { return ( <header className="text-center py-4"> <div className="container"> <h1 className="mb-4 app-logo"><a href="/" className="text-light">Lista de Tareas</a></h1> {props.children} </div> </header> ); } export default Header;
import React, { Component } from 'react' import styled from 'styled-components' import { H2 } from '../../mia-ui/text' import { Loading } from '../../mia-ui/loading' import StoryList from '../StoryList' import CreateStoryButton from '../CreateStoryButton' import PropTypes from 'prop-types' import { LinkStyled } from '../../mia-ui/links' import { Icon } from '../../mia-ui/icons' import { Flex, Box } from 'grid-styled' import { Page, Card } from '../../mia-ui/layout' import Head from '../../shared/head' import Joyride from 'react-joyride' import Link from 'next/link' import { Button } from '../../mia-ui/buttons' import { StoryQuery } from '../../../apollo/queries/story' export default class CmsHome extends Component { // static propTypes = { // organization: PropTypes.shape({ // name: PropTypes.string.isRequired // }).isRequired, // user: PropTypes.shape({ // id: PropTypes.string.isRequired // }).isRequired, // router: PropTypes.shape({ // query: PropTypes.shape({ // subdomain: PropTypes.string.isRequired // }).isRequired // }).isRequired // } startGuidedTour = async () => { try { // let { // data: { story } // } = await this.props.client.query({ // query: StoryQuery, // variables: { // slugInput: { // organization: { // subdomain: this.props.router.query.subdomain // }, // slug: 'curators-office-demo' // } // } // }) // // if (story) { // this.props.router.push( // { // pathname: '/cms/edit', // query: { // subdomain: this.props.router.query.subdomain, // storySlug: 'curators-office-demo', // demo: true // } // }, // `/${this.props.router.query.subdomain}/curators-office-demo` // ) // } else { const { data: { createStory: story } } = await this.props.createStory({ title: "Curator's Office (Demo)" }) this.props.router.push( { pathname: '/cms/edit', query: { subdomain: this.props.router.query.subdomain, storySlug: story.slug, tour: true } }, `/${this.props.router.query.subdomain}/${story.slug}` ) // } } catch (ex) { console.error(ex) } } render() { if (!this.props.organization) return <Loading /> const { props: { user, organization, router: { query: { subdomain } } } } = this let showSettings = user.organizations.find( org => org.role === 'admin' && org.subdomain === subdomain ) return ( <Page> <Head title={organization ? organization.name : 'Organization Stories'} /> <Flex w={1} pb={2}> <Box width={9 / 10}> <H2>{organization ? organization.name : ''}</H2> </Box> <Flex width={1 / 10} justifyContent={'flex-end'} id={'org-settings'}> {showSettings ? ( <Link href={{ pathname: '/cms/orgSettings', query: { subdomain } }} as={`/${subdomain}/settings`} > <a> <Icon icon={'settings'} color={'black'} title={'Settings'} size={'30px'} /> </a> </Link> ) : null} </Flex> </Flex> <Card p={3}> <StoryFlex flexWrap={'wrap'}> <CreateFlex w={1} justifyContent={'flex-end'}> <CreateStoryButton user={user} id={'create-story'} /> </CreateFlex> <Box width={1}> <StoryList /> <TutorialDiv> Want help?{' '} <LinkStyled onClick={this.startGuidedTour}> Click here{' '} </LinkStyled>{' '} to get a tutorial on creating stories. </TutorialDiv> </Box> </StoryFlex> </Card> </Page> ) } } const TutorialDiv = styled.div` margin-top: 30px; display: flex; justify-content: center; ` const StoryFlex = styled(Flex)` position: relative; ` const CreateFlex = styled(Flex)` position: absolute; `
import './Card.css'; import Box from "./Box"; import formatNumber from "./util"; import numeral from "numeral"; function Card({countryInfo}) { return ( <div className="container"> <Box title="Coronavirus Cases" cases={formatNumber(countryInfo.todayCases)} total={numeral(countryInfo.cases).format("0.0a")} /> <Box title="Recovered Cases" cases={formatNumber(countryInfo.todayRecovered)} total={numeral(countryInfo.recovered).format("0.0a")} /> <Box title="Death Cases" cases={formatNumber(countryInfo.todayDeaths)} total={numeral(countryInfo.deaths).format("0.0a")} /> </div> ); } export default Card;
define(['frame', 'editor'], function (ngApp, editorProxy) { 'use strict' /** * */ ngApp.provider.controller('ctrlPage', [ '$scope', '$location', 'srvEnrollApp', 'srvEnrollPage', function ($scope, $location, srvEnrollApp, srvAppPage) { var _oApp window.onbeforeunload = function (e) { var message if ($scope.ep && $scope.ep.$$modified) { message = '已经修改的页面还没有保存,确定离开?' e = e || window.event if (e) { e.returnValue = message } return message } } $scope.ep = null $scope.togglePageSetting = function ($event) { var target = event.target if (target.dataset.isOpen === 'Y') { delete target.dataset.isOpen $(target).trigger('hide') } else { target.dataset.isOpen = 'Y' $(target).trigger('show') } } $scope.closePageSetting = function () { var $popover $popover = $('#popoverPageSetting') delete $popover[0].dataset.isOpen $popover.trigger('hide') } $scope.addPage = function () { $scope.closePageSetting() srvAppPage.create().then(function (page) { $scope.choosePage(page) }) } $scope.updPage = function (page, props) { if (props.indexOf('html') !== -1) { /* 如果是当前编辑页面 */ if (page === $scope.ep) { page.html = editorProxy.getEditor().getContent() } editorProxy.purifyPage(page, true) } return srvAppPage.update(page, props) } $scope.cleanPage = function () { if ( window.confirm('确定清除页面【' + $scope.ep.title + '】的所有内容?') ) { srvAppPage.clean($scope.ep).then(function () { editorProxy.getEditor().setContent('') }) } } //@todo 应该检查页面是否已经被使用 $scope.delPage = function () { var oPage, oActSchema, bUserd $scope.closePageSetting() for (var i = _oApp.pages.length - 1; i >= 0; i--) { oPage = _oApp.pages[i] if (oPage.actSchemas && oPage.actSchemas.length) { for (var j = oPage.actSchemas.length - 1; j >= 0; j--) { oActSchema = oPage.actSchemas[j] if (oActSchema.next === $scope.ep.name) { bUserd = true break } } } if (bUserd) break } if (bUserd) { alert( '页面已经被【' + oPage.title + '/' + oActSchema.label + '】使用,不能删除' ) } else if ( window.confirm('确定删除页面【' + $scope.ep.title + '】?') ) { srvAppPage.remove($scope.ep).then(function (pages) { $scope.choosePage(pages.length ? pages[0] : null) }) } } $scope.choosePage = function (page) { var pages if (angular.isString(page)) { pages = _oApp.pages for (var i = pages.length - 1; i >= 0; i--) { if (pages[i].name === page) { page = pages[i] break } } if (i === -1) return false } return ($scope.ep = page) } $scope.$on( 'xxt.matter.enroll.app.dataSchemas.modified', function (event, state) { var originator = state.originator, modifiedSchema = state.schema _oApp.pages.forEach(function (page) { if (originator === $scope.ep && page !== $scope.ep) { page.updateSchema(modifiedSchema) } }) } ) /** * 1,检查页面中是否存在错误 * 2,如果页面中有添加记录的操作,活动的限制填写数量应该为0或者大于1 */ $scope.save = function () { var pages, oPage, aCheckResult, updatedAppProps, bCanAddRecord pages = _oApp.pages updatedAppProps = ['dataSchemas'] bCanAddRecord = false /* 更新当前编辑页 */ $scope.ep.html = editorProxy.getEditor().getContent() editorProxy.purifyPage($scope.ep, true) for (var i = pages.length - 1; i >= 0; i--) { oPage = pages[i] aCheckResult = oPage.check() if (aCheckResult[0] !== true) { srvAppPage.repair(aCheckResult, oPage) return false } if (oPage.type === 'V') { if (oPage.actSchemas && oPage.actSchemas.length) { for (var j = oPage.actSchemas.length - 1; j >= 0; j--) { if (oPage.actSchemas[j].name === 'addRecord') { bCanAddRecord = true break } } } } } if (bCanAddRecord) { if (_oApp.count_limit == 1) { _oApp.count_limit = 0 updatedAppProps.push('count_limit') } } else { if (_oApp.count_limit != 1) { _oApp.count_limit = 1 updatedAppProps.push('count_limit') } } srvEnrollApp.update(updatedAppProps).then(function () { _oApp.pages.forEach(function (page) { $scope.updPage(page, ['dataSchemas', 'actSchemas', 'html']) }) }) } $scope.gotoCode = function () { window.open( '/rest/pl/fe/code?site=' + _oApp.siteid + '&name=' + $scope.ep.code_name, '_self' ) } srvEnrollApp.get().then(function (app) { _oApp = app if ( _oApp.entryRule && _oApp.entryRule.scope.group === 'Y' && _oApp.entryRule.group && _oApp.entryRule.group.id ) { $scope.bSupportGroup = true } $location.search().page && $scope.choosePage($location.search().page) if (!$scope.ep) $scope.ep = app.pages[0] }) }, ]) })
import * as THREE from 'three'; //export default canvas => { class SceneManager { constructor(canvas) { this.canvas = canvas; this.screenDimensions = { width: canvas.width, height: canvas.height } this.scene = this.buildScene(); this.renderer = this.buildRender(this.screenDimensions); this.camera = this.buildCamera (this.screenDimensions); this.ground = this.createGround(); this.scene.add(this.ground); // return { // update(), // onWindowResize() // } } buildScene(){ const scene = new THREE.Scene(); scene.background = new THREE.Color( 0x000000 ); return scene; } buildRender({width, height}){ let renderer = new THREE.WebGLRenderer({canvas: this.canvas, alpha:true}); // renderer with transparent backdrop renderer.shadowMap.enabled = true;//enable shadow renderer.shadowMap.type = THREE.PCFSoftShadowMap; renderer.setSize( width, height ); renderer.setClearColor(0xfffafa, 1); return renderer; } buildCamera({width, height}){ const aspectRatio = width / height; const fieldOfView = 60; const nearPlane = 0.1; const farPlane = 1000; const camera = new THREE.PerspectiveCamera( fieldOfView, aspectRatio, nearPlane, farPlane ); // perspective camera camera.position.z = 4; // camera.position.x = -0.2; camera.position.y = 2.5; return camera; } createGround(){ var sides=32; var tiers=32; var worldRadius = 2; var sphereGeometry = new THREE.SphereGeometry( worldRadius, sides,tiers); var sphereMaterial = new THREE.MeshStandardMaterial( { color: 0xffffff, shading:THREE.FlatShading} ) var vertexIndex; var vertexVector= new THREE.Vector3(); var nextVertexVector= new THREE.Vector3(); var firstVertexVector= new THREE.Vector3(); var offset= new THREE.Vector3(); var currentTier=1; var lerpValue=0.5; var heightValue; var maxHeight=0.07; for(var j=1;j<tiers-2;j++){ currentTier=j; for(var i=0;i<sides;i++){ vertexIndex=(currentTier*sides)+1; vertexVector=sphereGeometry.vertices[i+vertexIndex].clone(); if(j%2!==0){ if(i===0){ firstVertexVector=vertexVector.clone(); } nextVertexVector=sphereGeometry.vertices[i+vertexIndex+1].clone(); if(i==sides-1){ nextVertexVector=firstVertexVector; } lerpValue=(Math.random()*(0.75-0.25))+0.25; vertexVector.lerp(nextVertexVector,lerpValue); } heightValue=(Math.random()*maxHeight)-(maxHeight/2); offset=vertexVector.clone().normalize().multiplyScalar(heightValue); sphereGeometry.vertices[i+vertexIndex]=(vertexVector.add(offset)); } } var rollingGroundSphere = new THREE.Mesh( sphereGeometry, sphereMaterial ); rollingGroundSphere.scale.set(1,2.5,1); rollingGroundSphere.rotation.z += Math.PI / 2;; return rollingGroundSphere; } update(){ // animate scene this.ground.rotation.x += 0.005; this.renderer.render(this.scene, this.camera); } onWindowResize(){ // resize & align if window size changes let sceneHeight = window.innerHeight; let sceneWidth = window.innerWidth; this.renderer.setSize(sceneWidth, sceneHeight); this.camera.aspect = sceneWidth/sceneHeight; this.camera.updateProjectionMatrix(); } }
const express = require('express'); const RateLimit = require('express-rate-limit'); const authentication = require('../authentication'); const authRouter = new express.Router(); const db = require('../database'); authRouter.post('/register', authentication.register); authRouter.post('/login', authentication.login); authRouter.post('/logout', authentication.logout); authRouter.post('/user', authentication.getLoggedInUser); // limits the amount of requests by single IP so that user cannot // spam login/validate-credientials requests if(process.env.NODE_ENV === 'production') { authRouter.use(['/login', '/register'], new RateLimit({ windowMs: 5 * 60 * 1000, // 5 minutes max: 50, // 50 requests message: "Too many requests.. Try again later" })); } module.exports = authRouter;
import React from 'react' import PropTypes from 'prop-types' // Components import { reduxForm, Field } from 'redux-form' import {CheckboxList, SearchableSelect, Input, FieldWrapper} from '../../components/forms' import {createTranslate} from '../../../locales/translate' import {Form} from '../../components/controls/SemanticControls' // module stuff import config from '../../../modules/accounts/config' import validateAccount from '../../../modules/accounts/schema' class AccountForm extends React.PureComponent { constructor (props) { super(props) this.message = createTranslate('accounts', this) } render () { const {locale, isNew, roleOptionList, organismRoleOptionList} = this.props return ( <Form> <Field name="username" label={this.message('userName')} required component={FieldWrapper} InputControl={Input} locale={locale} /> <Field name="lastName" label={this.message('lastName')} required component={FieldWrapper} InputControl={Input} locale={locale} /> <Field name="firstName" label={this.message('firstName')} required component={FieldWrapper} InputControl={Input} locale={locale} /> <Field name="organismRole" label={this.message('organismRole')} required component={FieldWrapper} InputControl={SearchableSelect} locale={locale} options={organismRoleOptionList} /> <Field name="password" label={this.message('password')} required={isNew} component={FieldWrapper} InputControl={Input} locale={locale} type="password" /> <Field name="confirmPassword" label={this.message('confirmPassword')} required={isNew} component={FieldWrapper} InputControl={Input} locale={locale} type="password" /> <Field name="roles" label={this.message('roles')} component={FieldWrapper} InputControl={CheckboxList} locale={locale} options={roleOptionList} /> </Form> ) } } AccountForm.propTypes = { locale: PropTypes.string.isRequired, roleOptionList: PropTypes.array.isRequired, organismRoleOptionList: PropTypes.array.isRequired, isNew: PropTypes.bool.isRequired } const ConnectedAccountForm = reduxForm({ form: config.entityName, validate: validateAccount })(AccountForm) export default ConnectedAccountForm
function parseGenericResponseError(res) { if (parseInt(res.status) >= 400) { return 'Connection failed with code ' + res.status; } if (res.readyState === 0 || res.statusText.toLowerCase() == 'error') { return 'Connection failed with unspecified error'; } return String(res); } export default Object.freeze({ safeParseLocalStorageObject(key) { var res; try { res = JSON.parse(localStorage.getItem(key)); if (typeof res != 'object') { throw new TypeError(); } if (Array.isArray(res)) { throw new TypeError(); } } catch (e) { // ignore } return res || {}; }, safeParseLocalStorageInteger(key, defaultValue) { var res = parseInt(localStorage.getItem(key)); if (isNaN(res)) { return defaultValue; } return res; }, parseErrorText(res) { if (res.responseText) { return res.responseText; } return parseGenericResponseError(res); }, parseErrorJSON(res) { if (res.responseJSON) { if (Array.isArray(res.responseJSON.Errors)) { return res.responseJSON.Errors.map(function(err) { return Object.values(err).join('\n'); }).join('\n'); } else if (typeof res.responseJSON.Error == 'string') { return res.responseJSON.Error; } } else { return 'JSON fetch failed: ' + this.parseErrorText(res); } }, cleanYoutubeUrl(url) { var match = url.match(/(youtu.be\/|\/video\/|[?&]v=)([A-Za-z0-9_-]+)/); if (match) { url = match[2]; } return url; }, });
import React from 'react'; import PropTypes from 'prop-types'; import styles from './Memeviewer.module.css'; import {BASE_IMG_URL} from '../../config/config'; const Memeviewer = (props) => ( <svg className={styles.Memeviewer} data-testid="Memeviewer" viewBox={'0 0 '+ (props.meme.image?`${props.meme.image.w} ${props.meme.image.h}`:'0 0')}> {props.meme.image && <image href={`${BASE_IMG_URL}${props.meme.image.url}`} x={props.meme.image.x} y={props.meme.image.y} />} <text x={props.meme.x} y={props.meme.y} fill={props.meme.color} fontSize={props.meme.fontsize}>{props.meme.text}</text> </svg> ); Memeviewer.propTypes = {meme:PropTypes.object.isRequired}; Memeviewer.defaultProps = {}; export default Memeviewer;
import React from 'react'; {/* import {withRouter, Link} from 'react-router-dom';*/} class Navi extends React.Component{ constuctor() { this.onLogIn = this.onLogIn.bind(this); } onLogIn = () =>{ alert('Login Here'); let path = '/CreateAccount'; this.props.history.push(path); } render(){ return( <div> <nav id="mainNav" className="navbar navbar-expand-lg navbar-light"> <div className="container"> <div className="collapse navbar-collapse" id="navbarResponsive"> <ul className="navbar-nav ml-auto"> <li className="nav-item"> <button onClick={this.onLogIn} className="navbar-brand js-scroll-trigger" >Login New</button><br /> <Link to="/Login">Home</Link> </li> </ul> </div> </div> </nav> </div> ); } } export default Navi;
import passport from 'passport'; import { signin, signup, verifiEmail, resendVerification } from './controllers/authController'; import { resetPassword, verifyResetPassword, resetPasswordNew } from './controllers/resetPasswordController'; import { fetchUsers } from './controllers/usersController'; import { categoriesController, fetchCategories, addCategory, getCategory, deleteCategory } from './controllers/categoriesController'; import passportService from './services/passport'; const requireAuth = passport.authenticate('jwt', { session: false }); const requireSignin = passport.authenticate('local', { session: false }); const router = (app) => { // Users app.get('/', requireAuth, fetchUsers); app.post('/signup', signup); app.post('/signup/verify-email', verifiEmail); app.post('/resend-verify-code', resendVerification); app.post('/signin', requireSignin, signin); app.post('/reset-password', resetPassword); app.post('/reset-password/verify', verifyResetPassword); app.post('/reset-password/new', resetPasswordNew); // Categories app.get('/categories', requireAuth, fetchCategories); app.post('/categories', requireAuth, addCategory); app.get('/categories/:id', requireAuth, getCategory); app.delete('/categories/:id', requireAuth, deleteCategory); }; export default router;
//vimrioゲームのJavaScript var width=800; var height; var offsetleft=0; var offsetright=0; var cvsw,cvsh; var stagenum=0; var game=null; var errorcnt=0; var stageIndex=0; var initialize=false; var keymap=[]; var keymapindex=0; var initchars=["$","^"]; var prekey=""; $(function() { if(localStorage) { var mapst = localStorage.getItem('keymap'); if(typeof mapst !=="undefined" && mapst!=null){ var ary=JSON.parse(mapst); if(typeof ary !=="undefined" && ary!=null && ary.length===initchars.length){ var mapindex; var map=[]; for(mapindex=0;mapindex<ary.length;mapindex++){ //console.log(JSON.parse(ary[mapindex])); map[initchars[mapindex]]=JSON.parse(ary[mapindex]); } if(typeof map !=="undefined" && map!=null && mapindex===initchars.length){ keymap=map; keymapindex=mapindex; initialize=true; } } } } //console.log("jquery init"); $.getScript("itemclass.js", function(){ $.getScript("stageclass.js", function(){ $.getScript("gameclass.js", function(){ jqInit(); }); }); }); }); function showAns(success){ if(success){ var typeStr=game.getStage().getTypeStr(); $("p",".typeStr").text(typeStr); $(".ansStr").css("display","none"); } else{ $(".ansStr").css("display","none"); $(".ansStr").delay(0).fadeIn("fast",function(){ $(".ansStr").delay(1000).fadeOut("fast",function(){ var typeStr=game.getStage().getTypeStr(); $("p",".typeStr").text(typeStr); }); }); } } function jqInit(){ //console.log("jqInit"); width=$(window).width(); height=$(window).height(); if(height<width){ width=height; offsetleft=($(window).width()-width)/2; offsettop=0; } else{ height=width; offsettop=($(window).height()-height)/2; offsetleft=0; } cvsw=width*0.9; cvsh=height*0.9; game=new GameClass(); $("body").keydown(function(e){ //console.log(e.keyCode); var stage=game.getStage(); var c=String.fromCharCode(e.keyCode); //console.log("code=["+c.charCodeAt(0)+"] c="+c+" shift="+e.shiftKey+" ctrl="+e.ctrlKey+" len="+c.length+" keycode="+e.keyCode); var code=c.charCodeAt(0); if(code==16 || code==17){ return; } var shift=false; var ctrl=false; if(e.ctrlKey){ ctrl=true; } if(e.shiftKey){ shift=true; //console.log("shift"); } else{ c=c.toLowerCase(); } if(initialize==false){ initKeyDown(e.keyCode,c,shift,ctrl); } else{ //console.log("type="+c); var isfinish=stage.isFinish(); if(isfinish==false){ var success=stage.typeKeyboard(c,shift,ctrl); if(success==false){ errorcnt++; showFooter(); } showAns(success); } switch(e.keyCode){ case 32: // space //console.log("space"); break; case 13: // enter //console.log("enter"); if(isfinish){ nextStage(); return ; } break; } if(isfinish==false){ stageUpdate(stage); } prekey=c; } }); } function reInitialize(clear){ $(".hlp").css("display","none"); initialize=false; keymapindex=0; keymap=[]; if(clear && localStorage){ localStorage.clear(); } $("#keytxt").text(""); $("#ktxt").text(initchars[keymapindex]); $("#ktxt").css("display","block"); $("#keytxt").css("display","block"); $("#initdone").css("display","none"); $("#initpanel").css("display","block"); } function initClose(){ $("#initpanel").css("display","none"); initialize=true; } function initKeyDisp(){ keymapindex++; $("#ktxt").text(initchars[keymapindex]); $("#keytxt").text(""); if(keymapindex==initchars.length){ if(localStorage){ var i; var ary=[]; for(i=0;i<keymapindex;i++){ ary[i]=JSON.stringify(keymap[initchars[i]]); } localStorage.setItem('keymap',JSON.stringify(ary)); } $("#ktxt").css("display","none"); $("#keytxt").css("display","none"); $("#initdone").css("display","block"); setTimeout("initClose()",800); } } function initKeyDown(code,c,shift,ctrl){ $('#keytxt').html("code:"+code+"<br/>shift:"+shift+"<br/>ctrl:"+ctrl); var keytemp=[c,shift,ctrl]; keymap[initchars[keymapindex]]=keytemp; setTimeout("initKeyDisp()",300); } function getGameItemPixX(per){ var pixx=Math.floor(cvsw*per*0.01); if(pixx<0){ pixx=0; } return pixx; } function getGameItemPixY(per){ var pixy=Math.floor(cvsh*per*0.01); if(pixy<0){ pixy=0; } return pixy; } function loadScriptAjax(fname,i){ var nostr=('00'+(i+1)).slice(-3); var fullfname=(fname+nostr)+".js"; //console.log("load "+fullfname); $.ajax({ type: 'GET', dataType: 'script', url:fullfname, success: function(data){ i++; //console.log("stagei="+i); loadScriptAjax(fname,i); }, error: function(){ stagenum=i; //console.log("stagenum="+stagenum); stageIndex=0; initStages(); } }); } function initAll(){ if(initialize==false){ $('#ktxt').text(initchars[0]); } //name : [width,height,left,top] $("*").css("border-width",""+(height*0.003)+"px"); $("#area").css("width",""+width+"px"); $("#area").css("height",""+height+"px"); $("#area").css("left",""+offsetleft+"px"); $("#area").css("top",""+offsettop+"px"); //console.log("offsetleft:"+offsetleft+" offsettop:"+offsettop); var whlt= { ".header":[width*1.0,height*0.05,0,0] ,".ttl":[width*1.0*1.0*0.2,height*0.05*0.8,width*1.0*0.4,0] ,".cmbstage":[width*1.0*1.0*0.2,height*0.05*0.8,width*1.0*0.05,height*0.05*0.05] ,".notebtn":[width*1.0*1.0*0.1,height*0.05*0.8,width*1.0*0.85,height*0.05*0.05] ,".leftside":[width*0.05,height*0.9,0,height*0.05] ,".rightside":[width*0.05,height*0.9,width*0.95,height*0.05] ,".footer":[width*1.0,height*0.05,0,height*0.95] ,".cvs":[cvsw,cvsh,width*0.05,height*0.05] ,".game":[cvsw,cvsh,0,0] ,".endpanel":[cvsw*0.6,cvsh*0.6,cvsw*0.2,cvsh*0.2] ,".endmsg":[cvsw*0.6,cvsh*0.6*0.5,0,cvsh*0.6*0.1] ,".retrybtn":[cvsw*0.6*0.3,cvsh*0.6*0.2,cvsw*0.6*0.1,cvsh*0.6*0.7] ,".nextbtn":[cvsw*0.6*0.3,cvsh*0.6*0.2,cvsw*0.6*0.6,cvsh*0.6*0.7] ,".hlp":[width*0.8,height*0.6,width*0.05,height*0.1] ,".initbtn":[width*0.8*0.4,height*0.8*0.1,width*0.8*0.2*0.3,height*0.8*0.4] }; for (var obj in whlt) { // console.log(obj); if(whlt[""+obj][0]>=0){ $(""+obj).css("width",""+whlt[""+obj][0]+"px"); } if(whlt[""+obj][1]>=0){ $(""+obj).css("height",""+whlt[""+obj][1]+"px"); } if(whlt[""+obj][2]>=0){ $(""+obj).css("left",""+whlt[""+obj][2]+"px"); } if(whlt[""+obj][3]>=0){ $(""+obj).css("top",""+whlt[""+obj][3]+"px"); } } if(game.getStageNum()==0){ loadScriptAjax("stage",0); } if(initialize==false){ $('#keytxt').focus(); } } function setItem(item){ var name=item.name; var id="#"+item.id; var x,y,w,h; x=item.getX(); y=item.getY(); w=item.getW(); h=item.getH(); var backgroundColor=item.getBackgroundColor(); var borderColor=item.getBorderColor(); var backgroundImage=item.getBackgroundImage(); var display=item.getDisplay(); var zIndex=item.getZIndex(); var wd=item.getWd(); if(typeof(x)!=="undefined" && x!==""){ $(id).css("left",""+getGameItemPixX(x)+"px"); } if(typeof(y)!=="undefined" && y!==""){ $(id).css("top",""+getGameItemPixY(y)+"px"); } if(typeof(w)!=="undefined" && w!==""){ $(id).css("width",""+getGameItemPixX(w)+"px"); } if(typeof(h)!=="undefined" && h!==""){ $(id).css("height",""+getGameItemPixY(h)+"px"); } if(typeof(backgroundColor)!=="undefined" && backgroundColor!=""){ $(id).css("background-color",backgroundColor); } if(typeof(borderColor)!=="undefined" && borderColor!=""){ $(id).css("border-color",borderColor); } if(typeof(backgroundImage)!=="undefined" && backgroundImage!=""){ $(id).css("background-image",'url("'+backgroundImage+'")'); } if(typeof(display)!=="undefined" && display!=""){ if(display){ $(id).css("display","block"); } else{ $(id).css("display","none"); } } if(typeof(zIndex)!=="undefined" && zIndex!==""){ $(id).css("z-index",zIndex); } if(typeof(w)!=="undefined" && w!=="" && typeof(h)!=="undefined" && h!==""){ $(id).css("background-size",""+getGameItemPixX(w)+"px "+getGameItemPixY(h)+"px"); $(id).css("font-size",""+getGameItemPixX(w)*0.7+"px"); } if(typeof(wd)!=="undefined" && wd!==""){ $("p",id).text(wd); } } function reset(){ stageIndex=0; initStages(); } function changeStage(){ console.log("change stage"); stageIndex=Number($('select','.cmbstage').val()); $('select','.cmbstage').blur(); initStages(); } function createCmbBox(num){ var i; var str="<select onChange='changeStage()'>"; for(i=0;i<num;i++){ str+="<option value='"+i+"'>stage"+(i+1)+"</option>"; } str+="</select>"; $(".cmbstage").html(str); } function initStages(){ //console.log("initStages"); if(game.getStageNum()==0){ game.createStages(stagenum); createCmbBox(stagenum); } $('select','.cmbstage').val(stageIndex); game.setStageIndex(stageIndex); game.initStage(); var divstr=game.getDivString(); // console.log(divstr); $(".game").html(divstr); // console.log($(".game").html()); var stage=game.getStage(); errorcnt=0; stage.setFrameIndex(0); stageUpdate(stage); var fontsize=cvsw*0.04; $("p",".fnt").css("font-size",""+fontsize*2+"px"); $("p",".footer").css("font-size",""+fontsize+"px"); $("p",".keystring").css("font-size",""+fontsize+"px"); $("p",".retrybtn").css("font-size",""+fontsize*1.5+"px"); $("p",".nextbtn").css("font-size",""+fontsize*1.5+"px"); $("p",".ttl").css("font-size",""+fontsize+"px"); $("select",".cmbstage").css("font-size",""+fontsize*0.7+"px"); $("select",".notebtn").css("font-size",""+fontsize*0.7+"px"); $(".keystring").css("padding-top",""+fontsize/5+"px"); $(".keystring").css("padding-bottom",""+fontsize/5+"px"); $(".keystring").css("top",""+fontsize/2+"px"); $(".keystring").css("left",""+fontsize+"px"); $(".ansStr").css("display","block"); $(".endpanel").css("display","none"); $(".hlp").css("display","none"); } function stageUpdate(stage){ stage.setFrame(); var items=stage.getItems(); var i; for(i=0;i<items.length;i++){ var item=items[i]; setItem(item); } if(stage.isFinish()){ if(errorcnt==0){ $("p",".endmsg").text("Excellent!"); } else{ if(errorcnt<3){ $("p",".endmsg").text("Good!"); } else{ if(errorcnt<7){ $("p",".endmsg").text("Keep it up."); } else{ $("p",".endmsg").text("Hang in there."); } } } $(".endpanel").css("display","block"); } else{ $(".endpanel").css("display","none"); } showFooter(); } function showFooter(){ $("p",".footer").html("stage : "+(stageIndex+1)+"&nbsp;&nbsp;&nbsp;&nbsp; fail : "+errorcnt); } function retryStage(){ initStages(); } function nextStage(){ if(stageIndex+1<game.getStageNum()){ stageIndex++; } else{ stageIndex=0; } initStages(); } function showHelp(){ if($(".hlp").css("display")=="block"){ $(".hlp").css("display","none"); } else{ $(".hlp").css("display","block"); } } function initBody(){ if(game==null){ setTimeout(initBody,1000); return; } //console.log("initBody"); initAll(); if(initialize==false){ reInitialize(false); } }
import { createStore, applyMiddleware, compose } from 'redux'; import createSagaMiddleware from 'redux-saga'; import createReducer from './reducers'; import productSaga from '../src/containers/ProductDashboard/sagas'; export default function configureStore() { const initialState = {}; const sagaMiddleware = createSagaMiddleware(); const middlewares = [sagaMiddleware]; const store = createStore( createReducer(), //initialState, applyMiddleware(sagaMiddleware) // compose(...[applyMiddleware(...middlewares)]) ); store.runSaga = sagaMiddleware.run; store.injectedReducers = {}; // Reducer registry store.injectedSagas = {}; // Saga registry sagaMiddleware.run(productSaga); if (module.hot) { module.hot.accept('./reducers', () => { store.replaceReducer(createReducer(store.injectedReducers)); }); } return store; }
class App { constructor() { } createDOM() { this.listen() const main = this.createEl('main', 'body') this.createEl('div', main, { 'class': 'form' }) this.createEl('div', main, { 'class': 'contacts' }) this.createEl('div', main, { 'class': 'contact' }) this.router = new Router() } listen() { window.addEventListener('click', e => { if (e.target.className.includes('add-input-field')) this.addInputSection(e.target.id) if (e.target.className.includes('save-contact')) this.saveContact(e.target.id) if (e.target.className.includes('edit-contact')) this.editContact(e.target.id) if (e.target.className.includes('delete-contact')) this.deleteContact(e.target.id) if (e.target.className.includes('update-contact')) this.updateContact(e.target.id) if (e.target.closest('.change-version')) this.changeVersion(e.target.parentElement.id) if (e.target.className.includes('choose')) this.changeVersion(e.target.id) if (e.target.className.includes('exit-form')) this.exitForm() if (e.target.closest('.go-back')) this.goBack() }) window.addEventListener('popstate', () => { this.router.frontendRouter(location.pathname) }) } createEl(tagName, parent, attributes = '') { const el = document.createElement(tagName) if (attributes) Object.keys(attributes).forEach(attribute => el.setAttribute(attribute, attributes[attribute])) if (typeof parent === 'string') document.querySelector(parent).append(el) else parent.append(el) return el } readForm() { const name = document.querySelector('input#name-input').value const emailSectionEls = document.querySelector('div#input-section-email').children const email = [] .filter.call(emailSectionEls, input => input.tagName === 'INPUT') .map(input => input.value) const telephoneSectionEls = document.querySelector('div#input-section-telephone').children const telephone = [] .filter.call(telephoneSectionEls, input => input.tagName === 'INPUT') .map(input => input.value) return { name, email, telephone } } addInputSection(id) { const inputSection = document.querySelector(`div#input-section-${id}`) this.createEl('input', inputSection, { type: 'text', 'class': `${id}-input`, value: '' }) } saveContact(id = '') { const data = this.readForm() if (!data.name) { alert('Du måste ange ett namn!') return false } const time = new Date().getTime() data.email = data.email.filter(email => email) data.telephone = data.telephone.filter(telephone => telephone) data.added = time let contact if (id) { contact = contacts.find(contact => contact.id === +id) contact.versions.push(data) contact.chosenVersion = contact.versions.length - 1 } else { contact = { id: time, chosenVersion: 0, versions: [data] } contacts.push(contact) } contacts.save() if (!id) { this.router.addRoute(contact.id) this.router.frontendRouter('/') } else { this.router.frontendRouter(`/${id}`) } } editContact(id) { history.pushState(null, null, `/${id}`) this.router.frontendRouter(`/${id}`) } deleteContact(id) { const contact = contacts.find(contact => contact.id === +id) if (confirm(`Är du säker på att du vill ta bort ${contact.versions[contact.chosenVersion].name}?`)) contacts.splice(contacts.findIndex(contact => contact.id === +id), 1) contacts.save() this.router.frontendRouter('/') } updateContact(id) { this.form = new Form(id) } changeVersion(targetId) { const id = targetId.split('-')[0] const version = +targetId.split('-')[1] const contact = contacts.find(contact => contact.id === +id) if (confirm(`Vill du ändra version av ${contact.versions[contact.chosenVersion].name}?`)) { contact.chosenVersion = version contacts.save() document.querySelector('div.contact-section').outerHTML = '' this.contact = new Contact(id) if (document.querySelector('div.form-section')) { document.querySelector('div.form-section').outerHTML = '' this.form = '' } } } exitForm() { this.form = '' document.querySelector('div.form-section').outerHTML = '' } goBack() { history.pushState(null, null, '/') this.router.frontendRouter('/') } }
class MonthValidator { constructor() { } validate(value) { return { isValid: /^((?!MISSING)[\s\S])*$/.test(value), message: 'Must consist of literals (december|dec). Bibtex-normalizer default: MISSING' }; } } export default (new MonthValidator());
import $ from "jquery"; import 'bootstrap/dist/css/bootstrap.min.css'; import "./mystyle2.scss"; import "./carousel.js";
export const url = 'mongodb+srv://dbUser:newpassword321@cluster0.9buvk.mongodb.net/notesdb';
import gql from 'graphql-tag' import objFragment from './obj' import groupFragment from './group' import imageFragment from './image' import mediaFragment from './media' import contentFragment from './content' const fragment = gql` fragment StoryFragment on story { id title slug description template visibility previewImage { ...ImageFragment } groups { ...GroupFragment } contents { ...ContentFragment } relatedStories { id title slug } } ${groupFragment} ${imageFragment} ${mediaFragment} ${contentFragment} ` export default fragment
/* * val4 is an array of 3 numbers that range from [0,1000] * size is the number of pixels for width and height * use p5.js to draw a round grawscale glpyh within the bounding box */ function gray_glyph(values, size) { //determine the center of the circle var center = size/2; //draw a black background for the glyphs area fill(0); ellipse(center, center, size); //hue dimension var hueDegree = floor(values[0]); //a modulo variable used to provide slight variation in the transparency levels of the ellipses that represent the hue dimension var hueModulo = (hueDegree % 12) * 4; var hue = map(hueDegree, 0, 360, size, 0 + size/16); //saturation dimension //saturationMin and saturationMax are values that determine the positions for the alternating points (between the center of a circle and its edge) of the triangles representing the saturation dimension var saturationMin = map(values[1], 0, 100, center, 0); var saturationMax = map(values[1], 0, 100, center, size); //brightness dimension //brightnessMin and brightnessMax are values that determine the position for the alternating points (between the center of a circle and its edge) of the triangles representing the brightness dimension var brightnessMin = map(values[2], 0, 100, center, (0 + size/8 + size/32)); var brightnessMax = map(values[2], 0, 100, center, (size - size/8 - size/32)); //draw the circles that represent the hue dimension stroke(255); //outer circle fill(255, 255, 255, 47 + hueModulo); ellipse(center, center, hue); //middle circle fill(255, 255, 255, 159 + hueModulo); ellipse(center, center, hue / 2); //inner circle fill(0); ellipse(center, center, hue / 4); //JSON objects used to store all the x and y positions of the triangles that represent the saturation and brightness dimensions var positions = { 'x1': [ center - size/32, center - size/32, center, center + size/32, center - size/32, center - size/32, center, center + size/32, ], 'y1': [ center, center - size/32, center - size/32, center - size/32, center, center - size/32, center - size/32, center - size/32 ], 'x2': [ center, brightnessMax, saturationMax, brightnessMax, center, brightnessMin, saturationMin, brightnessMin ], 'y2': [ saturationMin, brightnessMin, center, brightnessMax, saturationMax, brightnessMax, center, brightnessMin ], 'x3': [ center + size/32, center + size/32, center, center - size/32, center + size/32, center + size/32, center, center - size/32 ], 'y3': [ center, center + size/32, center + size/32, center + size/32, center, center + size/32, center + size/32, center + size/32 ] } //draw the 8 triangles that represnt the saturation and brightness dimensions fill(255, 255, 255, 127); noStroke(); for($i = 0; $i < 8; $i++){ triangle(positions['x1'][$i], positions['y1'][$i], positions['x2'][$i], positions['y2'][$i], positions['x3'][$i], positions['y3'][$i]); } }
/* * ybm * https://github.com/qiu8310/ybm * * Copyright (c) 2015 Zhonglei Qiu * Licensed under the MIT license. */ var ybm = require('../'); ybm( { name: 'single-async', maxTime: 1, // 如果是异步,参数必须是 done; // 另外你可以用 benchmark.js 默认的 defer 属性,参考这里的第二个 Example:http://benchmarkjs.com/docs#Benchmark fn: function(done) { setTimeout(done, 100); } }, { historyOptions: {file: 'single-async'} // 如果指定了 `name`,这时的 `file` 就可以不写 } );
(function () { angular .module('driverCheck') .controller('loginCtrl', loginCtrl); loginCtrl.$inject = ['$location','authentication']; function loginCtrl($location, authentication) { var vm = this; vm.pageHeader = { title: 'Sign in' }; if(authentication.isLoggedIn()) $location.path('/auth'); vm.email=""; vm.password=""; vm.onSubmit = function () { vm.formError = ""; if (!vm.email || !vm.password) { vm.formError = "All fields required, please try again"; return false; } else { authentication.login(vm.email); $location.path('/auth'); } }; } })();
function setup() { createCanvas(400, 400); } function draw() { background(220); for (var x = 25; x <= 375 ; x= x+50){ for ( var y = 25; y <=375 ; y=y+50){ ellipse(x,y,50,50); } } }
/** * Created by Administrator on 2017/1/1 0001. */ // 对象写法 var module1 = new Object({ _count : 0, m1 : function () { console.log('module1.m1'); }, m2 : function () { console.log('module1.m2'); }, m3 : function () { console.log('module1.m3'); } });
import React from 'react'; import './index.scss'; import { Link, NavLink } from 'react-router-dom'; import { AiOutlineHome, AiOutlineCalendar, AiOutlineTag, AiOutlineBell, AiOutlineDown } from 'react-icons/ai'; import { FiSearch } from 'react-icons/fi'; import * as Routes from '../../assets/js/Routes'; import Logo from '../../Elements/Logo'; import ProfileImage from '../ProfileImage'; const Header = () => ( <header className="header"> <article className="header__content"> <Link to={Routes.HOME} className="header__content__logo"> <Logo /> </Link> <nav className="header__content__nav"> <NavLink to={Routes.HOME} activeClassName="header__content__nav-active"> <span><AiOutlineHome /></span> Inicio </NavLink> <NavLink to={Routes.AGENDAR} activeClassName="header__content__nav-active"> <span><AiOutlineCalendar /></span> Agendar </NavLink> <NavLink to={Routes.BUSCAR} activeClassName="header__content__nav-active"> <span><FiSearch /></span> Buscar </NavLink> <NavLink to={Routes.PUNTOS} activeClassName="header__content__nav-active"> <span><AiOutlineTag /></span> Mis puntos </NavLink> </nav> <div className="header__content__user"> <span className="header__content__user__notification"><AiOutlineBell /></span> <div className="header__content__user__profile"> <ProfileImage /> <span className="header__content__user__down"><AiOutlineDown /></span> </div> </div> </article> </header> ); export default Header;
'use babel' const fs = require('fs'); const stackedArea = require('stacked-area'); const moment = require('moment'); const NOW = '2018-09-11 12:00'; const NUMBER_OF_TEST_IMAGES = 12; let actuals = []; let expected = []; let settings; function makeTestSettings() { settings = {}; let now = moment(NOW); settings.data = makeTestData(); settings.svg = document.createElement('svg'); settings.title = 'Testing the Stacked Area Chart'; settings.fromDate = moment(now).subtract(8, 'days'); settings.toDate = moment(now).add(3, 'days'); return settings; } function makeTestData() { let testData = {}; testData.keys = ['Lowest', 'Low', 'Medium', 'High', 'Highest']; let now = moment(NOW); testData.entries = []; testData.entries.push({ date: moment(now).subtract(8, 'days'), Highest: 2, High: 1, Medium: 4, Low: 0, Lowest: 1 }, { date: moment(now).subtract(7, 'days'), Highest: 2, High: 1, Medium: 4, Low: 0, Lowest: 1 }, { date: moment(now).subtract(6, 'days'), Highest: 3, High: 2, Medium: 6, Low: 1, Lowest: 2 }, { date: moment(now).subtract(5, 'days'), Highest: 1, High: 2, Medium: 3, Low: 1, Lowest: 0 }, { date: moment(now).subtract(4, 'days'), Highest: 2, High: 5, Medium: 6, Low: 3, Lowest: 2 }, { date: moment(now).subtract(3, 'days'), Highest: 1, High: 4, Medium: 3, Low: 1, Lowest: 0 }, { date: moment(now).subtract(2, 'days'), Highest: 1, High: 3, Medium: 2, Low: 1, Lowest: 1 }, { date: moment(now).subtract(1, 'days'), Highest: 0, High: 1, Medium: 1, Low: 0, Lowest: 0 } ); return testData; } function makeArrayOfArraysTestData() { let testData = {}; testData.keys = ['Lowest', 'Low', 'Medium', 'High', 'Highest']; let now = moment(NOW); testData.entries = []; testData.entries.push( [moment(now).subtract(8, 'days'), 1, 0, 4, 1, 2], [moment(now).subtract(7, 'days'), 1, 0, 4, 1, 2], [moment(now).subtract(6, 'days'), 2, 1, 6, 2, 3], [moment(now).subtract(5, 'days'), 0, 1, 3, 2, 1], [moment(now).subtract(4, 'days'), 2, 3, 6, 5, 2], [moment(now).subtract(3, 'days'), 0, 1, 3, 4, 1], [moment(now).subtract(2, 'days'), 1, 1, 2, 3, 1], [moment(now).subtract(1, 'days'), 0, 0, 1, 1, 0] ); return testData; } function writeTestFile(path, content) { fs.writeFile(path, content); } function readTestFile(path) { return fs.readFileSync(path).toString(); } function readExpectedFiles(folder, count) { let expected = []; for (let i = 0; i < count; i++) { try { expected.push(readTestFile(folder + '/expect' + i + '.svg')); } catch (e) { console.log(e); } } return expected; } //test the functions beforeAll(() => { expected = readExpectedFiles('./test', NUMBER_OF_TEST_IMAGES); }); test('no settings at all', () => { //no settings at all let diagram = stackedArea(); expect(() => diagram.draw()) .toThrow(/No settings/); }); test('empty settings', () => { let settings = {}; diagram = stackedArea(settings); expect(() => { diagram.draw() }).toThrow(/No svg/); }); test('no svg tag', () => { let settings = {}; settings.svg = document.createElement('div'); expect(() => { diagram.draw() }).toThrow(/No svg/); }); test('no data', () => { let settings = makeTestSettings(); let diagram = stackedArea(settings); delete settings.data; expect(() => { diagram.draw() }).toThrow(/No data/); }); test('no data entries', () => { let settings = makeTestSettings(); delete settings.data.entries; let diagram = stackedArea(settings); expect(() => { diagram.draw() }).toThrow(/No data entries/); }); test('empty data entries', () => { let settings = makeTestSettings(); let diagram = stackedArea(settings); settings.data = { entries: [] } expect(() => { diagram.draw() }).toThrow(/Empty data entries/); }); test('data entries not an array', () => { let settings = makeTestSettings(); let diagram = stackedArea(settings); settings.data.entries = {} expect(() => { diagram.draw() }).toThrow(/Data entries not an array/); }); test('no keys defined', () => { let settings = makeTestSettings(); let diagram = stackedArea(settings); delete settings.data.keys; expect(() => { diagram.draw(); }).toThrow(/No keys defined/); }); test('default width and default height', () => { let settings = makeTestSettings(); delete settings.width; delete settings.height; let diagram = stackedArea(settings); diagram.draw(); expect(settings.width) .toBe(800); expect(settings.height) .toBe(400); }); test('default margins', () => { let settings = makeTestSettings(); settings.margin = {}; settings.width = 800; settings.height = 400; let diagram = stackedArea(settings); diagram.draw(); expect(settings.margin.top) .toBe(50); expect(settings.margin.right) .toBe(70); expect(settings.margin.bottom) .toBe(50); expect(settings.margin.left) .toBe(40); }); test('inner width and inner height', () => { let settings = makeTestSettings(); settings.margin = {}; let diagram = stackedArea(settings); diagram.draw(); expect(settings.innerWidth) .toBe(800 - settings.margin.left - settings.margin.right); expect(settings.innerHeight) .toBe(400 - settings.margin.top - settings.margin.bottom); }); test('set top margin', () => { let settings = makeTestSettings(); let diagram = stackedArea(settings); settings.margin = { top: 10 }; diagram.draw(); expect(settings.margin.top) .toBe(10); expect(settings.margin.right) .toBe(70); expect(settings.margin.bottom) .toBe(50); expect(settings.margin.left) .toBe(40); expect(settings.innerWidth) .toBe(800 - settings.margin.left - settings.margin.right); expect(settings.innerHeight) .toBe(400 - settings.margin.top - settings.margin.bottom); }); test('set right margin', () => { let settings = makeTestSettings(); let diagram = stackedArea(settings); settings.margin = { right: 10 }; diagram.draw(); expect(settings.margin.top) .toBe(50); expect(settings.margin.right) .toBe(10); expect(settings.margin.bottom) .toBe(50); expect(settings.margin.left) .toBe(40); expect(settings.innerWidth) .toBe(800 - settings.margin.left - settings.margin.right); expect(settings.innerHeight) .toBe(400 - settings.margin.top - settings.margin.bottom); }); test('set bottom margin', () => { let settings = makeTestSettings(); let diagram = stackedArea(settings); settings.margin = { bottom: 10 }; diagram.draw(); expect(settings.margin.top) .toBe(50); expect(settings.margin.right) .toBe(70); expect(settings.margin.bottom) .toBe(10); expect(settings.margin.left) .toBe(40); expect(settings.innerWidth) .toBe(800 - settings.margin.left - settings.margin.right); expect(settings.innerHeight) .toBe(400 - settings.margin.top - settings.margin.bottom); }); test('set left margin', () => { let settings = makeTestSettings(); let diagram = stackedArea(settings); settings.margin = { left: 10 }; diagram.draw(); expect(settings.margin.top) .toBe(50); expect(settings.margin.right) .toBe(70); expect(settings.margin.bottom) .toBe(50); expect(settings.margin.left) .toBe(10); expect(settings.innerWidth) .toBe(800 - settings.margin.left - settings.margin.right); expect(settings.innerHeight) .toBe(400 - settings.margin.top - settings.margin.bottom); }); test('set left and top margin to 0', () => { let settings = makeTestSettings(); let diagram = stackedArea(settings); settings.margin = { left: 0, top: 0 }; diagram.draw(); expect(settings.margin.top) .toBe(0); expect(settings.margin.right) .toBe(70); expect(settings.margin.bottom) .toBe(50); expect(settings.margin.left) .toBe(0); expect(settings.innerWidth) .toBe(800 - settings.margin.left - settings.margin.right); expect(settings.innerHeight) .toBe(400 - settings.margin.top - settings.margin.bottom); }); test('default style', () => { let settings = makeTestSettings(); let diagram = stackedArea(settings); let color = '#222'; let background = '#fff'; diagram.draw(); expect(settings.style.fontSize).toBe(12); expect(settings.style.fontFamily).toBe('sans-serif'); expect(settings.style.color).toBe(color); expect(settings.style.backgroundColor).toBe(background); expect(settings.style.axis.color).toBe(color); expect(settings.style.markers.backgroundColor).toBe(background); expect(settings.style.markers.color).toBe(color); }); test('stroke colors, empty axis color', () => { let settings = makeTestSettings(); let diagram = stackedArea(settings); let color = '#222'; let background = '#fff'; settings.style = {}; settings.style.markers = { backgroundColor: color }; settings.style.axis = {}; diagram.draw(); expect(settings.style.fontSize).toBe(12); expect(settings.style.fontFamily).toBe('sans-serif'); expect(settings.style.color).toBe(color); expect(settings.style.backgroundColor).toBe(background); expect(settings.style.axis.color).toBe(color); expect(settings.style.markers.backgroundColor).toBe(color); expect(settings.style.markers.color).toBe(color); }); test('no draw options', () => { let settings = makeTestSettings(); delete settings.drawOptions; let diagram = stackedArea(settings); diagram.draw(); expect(settings.drawOptions).toEqual(['title', 'axis', 'legend', 'markers', 'focus']); }); test('empty draw options', () => { let settings = makeTestSettings(); settings.drawOptions = []; let diagram = stackedArea(settings); diagram.draw(); expect(settings.drawOptions).toEqual([]); }); test('title draw options', () => { let settings = makeTestSettings(); settings.drawOptions = ['title']; let diagram = stackedArea(settings); diagram.draw(); expect(settings.drawOptions).toEqual(['title']); }); test('axis draw options', () => { let settings = makeTestSettings(); settings.drawOptions = ['axis']; let diagram = stackedArea(settings); diagram.draw(); expect(settings.drawOptions).toEqual(['axis']); }); test('legend draw options', () => { let settings = makeTestSettings(); settings.drawOptions = ['legend']; let diagram = stackedArea(settings); diagram.draw(); expect(settings.drawOptions).toEqual(['legend']); }); test('markers draw options', () => { let settings = makeTestSettings(); settings.drawOptions = ['markers']; let diagram = stackedArea(settings); diagram.draw(); expect(settings.drawOptions).toEqual(['markers']); }); test('image 0 with default test data', () => { let settings = makeTestSettings(); settings.title = 'Testing Stacked Area'; settings.markers = [ { date: settings.fromDate }, { date: settings.toDate } ]; let diagram = stackedArea(settings); let actual = diagram.svgSource(); actuals.push(actual); expect(actuals[0]).toBe(expected[0]); }); test('image 1 with custom colors, no markers, no axis', () => { let settings = makeTestSettings(); settings.title = 'Testing Stacked Area with custom colors, no markers, no axis'; settings.drawOptions = ['legend', 'title']; settings.markers = [ { date: moment(settings.fromDate).add(1, 'days') }, { date: moment(settings.toDate).subtract(1, 'days') } ]; settings.style = { Highest: { color: 'chartreuse', stroke: 'white' }, High: { color: 'cornflowerblue', stroke: 'white' }, Medium: { color: 'darkorange', stroke: 'white' }, Low: { color: 'firebrick', stroke: 'white' }, Lowest: { color: 'purple', stroke: 'white' } } let diagram = stackedArea(settings); let actual = diagram.svgSource(); actuals.push(actual); expect(actuals[1]).toBe(expected[1]); }); test('image 2 with markers out of range', () => { let settings = makeTestSettings(); settings.title = 'Testing Stacked Area with markers out of range'; settings.markers = [ { date: moment(settings.fromDate).subtract(2, 'days') }, { date: moment(settings.toDate).add(2, 'days') } ]; let diagram = stackedArea(settings); let actual = diagram.svgSource(); actuals.push(actual); expect(actuals[2]).toBe(expected[2]); }); test('image 3 without fromDate and toDate', () => { let settings = makeTestSettings(); settings.title = 'Testing Stacked Area without fromDate and toDate'; settings.markers = [ { date: moment(settings.fromDate).subtract(2, 'days') }, { date: moment(settings.toDate).add(2, 'days') } ]; delete settings.fromDate; delete settings.toDate; let diagram = stackedArea(settings); let actual = diagram.svgSource(); actuals.push(actual); expect(actuals[3]).toBe(expected[3]); }); test('image 4 with legend title and no further draw options', () => { let settings = makeTestSettings(); settings.drawOptions = ['legend']; settings.title = 'Testing Stacked Area with legend title and no further draw options'; settings.legendTitle = 'Issues:'; delete settings.fromDate; delete settings.toDate; let diagram = stackedArea(settings); let actual = diagram.svgSource(); actuals.push(actual); expect(actuals[4]).toBe(expected[4]); }); test('image 5 with curve step', () => { let settings = makeTestSettings(); settings.title = 'Testing Stacked Area with step curve'; let diagram = stackedArea(settings); diagram.draw(); expect(settings.curve.type).toEqual('linear'); settings.curve.type = 'step'; let actual = diagram.svgSource(); actuals.push(actual); expect(actuals[5]).toBe(expected[5]); }); test('image 6 with step curve and marker', () => { let settings = makeTestSettings(); settings.title = 'Testing Stacked Area with step curve and marker'; settings.markers = [ { date: moment(settings.fromDate).add(1, 'days') }, { date: moment(settings.toDate).subtract(1, 'days') } ]; let diagram = stackedArea(settings); diagram.draw(); expect(settings.curve.type).toEqual('linear'); settings.curve.type = 'step'; let actual = diagram.svgSource(); actuals.push(actual); expect(actuals[6]).toBe(expected[6]); }); test('image 7 with curve cardinal and tension 0.5', () => { let settings = makeTestSettings(); settings.title = 'Testing Stacked Area curve cardinal and tension 0.5'; settings.markers = [ { date: moment(settings.fromDate).add(1, 'days') }, { date: moment(settings.toDate).subtract(1, 'days') } ]; settings.curve = { type: 'cardinal', tension: 0.5 } let diagram = stackedArea(settings); diagram.draw(); let actual = diagram.svgSource(); actuals.push(actual); expect(actuals[7]).toBe(expected[7]); }); test('image 8 with curve catmullRom and alpha 0.5', () => { let settings = makeTestSettings(); settings.title = 'Testing Stacked Area curve catmullRom and alpha 0.5'; settings.markers = [ { date: moment(settings.fromDate).add(1, 'days') }, { date: moment(settings.toDate).subtract(1, 'days') } ]; settings.curve = { type: 'catmullRom', alpha: 0.5 } let diagram = stackedArea(settings); diagram.draw(); let actual = diagram.svgSource(); actuals.push(actual); expect(actuals[8]).toBe(expected[8]); }); test('image 9 with data given as array of arrays', () => { let settings = makeTestSettings(); settings.data = makeArrayOfArraysTestData(); settings.title = 'Testing Stacked Area with array of array data entries'; settings.markers = [ { date: settings.fromDate }, { date: settings.toDate } ]; let diagram = stackedArea(settings); diagram.draw(); let actual = diagram.svgSource(); actuals.push(actual); expect(actuals[9]).toBe(expected[9]); }); test('image 10 with reduced data and reduced legend', () => { let settings = makeTestSettings(); settings.title = 'Testing Stacked Area with removed "Medium" data entries'; settings.markers = [ { date: settings.fromDate }, { date: settings.toDate } ]; for(let entry of settings.data.entries) { entry['Medium'] = 0; } let diagram = stackedArea(settings); let actual = diagram.svgSource(); actuals.push(actual); expect(actuals[10]).toBe(expected[10]); }); test('image 11 with reduced data and reduced legend in array organized entries', () => { let settings = makeTestSettings(); settings.data = makeArrayOfArraysTestData(); settings.title = 'Testing Stacked Area with removed "Medium" data in array organized entries'; settings.markers = [ { date: settings.fromDate }, { date: settings.toDate } ]; for(let entry of settings.data.entries) { entry[3] = 0; } let diagram = stackedArea(settings); diagram.draw(); let actual = diagram.svgSource(); actuals.push(actual); expect(actuals[11]).toBe(expected[11]); }); test('write test results into file', () => { let testFileContent = '<!DOCTYPE html>\n<meta charset="utf-8">\n' + '<body><style>* {font-family:sans-serif;}\n' + '.image-set {border-bottom: 1px solid black; padding:2em 0;}\n' + '.label {text-transform:uppercase; color:white; background:gray; margin:0 1em;}\n' + '.label.mismatch {color:white; background:red;}\n' + '.label.expected {color:white; background:green;}\n' + '.box {display:inline-block;}</style>' + '<h1>Expected Test Results with Actual Values</h1>'; for (let i = 0; i < actuals.length; i++) { writeTestFile('./test/actual' + i + '.svg', actuals[i]); let match = expected[i] == actuals[i]; if (match) { testFileContent += '<div class="image-set"><div class="box"><div class="label">Expected ' + i + '</div>' + expected[i] + '</div>' + '<div class="box"><div class="label expected">Actual ' + i + ' is as expected</div>' + actuals[i] + '</div></div>'; } else { testFileContent += '<div class="image-set"><div class="box"><div class="label">Expected ' + i + '</div>' + expected[i] + '</div>' + '<div class="box"><div class="label mismatch">Actual ' + i + ' has a mismatch</div>' + actuals[i] + '</div></div>'; } } testFileContent += '</body'; writeTestFile('./test/stacked-area.html', testFileContent); //have a look at ./test/stacked-area.html to view the result });
'use strict'; const _ = require('lodash'); const dcp = require('dcp'); const Benchmark = require('benchmark'); function resolveFunc(obj) { return _.transform(obj, (result, funcStr, key) => { result[key] = new Function(`return ${funcStr}`)(); }); } class Executor { constructor(info, res) { this._async = info.async; this._setup = resolveFunc(info.setup); this._funcs = resolveFunc(info.funcs); this._suite = new Benchmark.Suite(); this._res = res; this._self = {}; this._data = {}; this._clone = {}; this._resolved = false; } setup() { _.forEach(this._setup, (func) => { const data = func.call(this._self, this._data); if (data) { this._data = data; } }); dcp.clean(); this._clone = { self: dcp.define('self', this._self), data: dcp.define('data', this._data) }; return this; } test() { if(_.isEmpty(this._funcs)) { return this.error(new Error('functions are empty.')); } let pre; let checkResult = _.every(this.funcs, func => { let _pre = pre; let current = func.call(this._clone.self(this._self), this._clone.data(this._data)); pre = current; if (!_pre) { return true; } return _.isEqual(_pre, current); }); if (!checkResult) { return this.error(new Error('Didn\'t get same results.')); } this._resolved = true; return this; } error(err) { this._res.status(500); this._res.send(err.message); return this; } execute() { if (!this._resolved) { return this; } const suite = new Benchmark.Suite(); _.forEach(this._funcs, (func, key) => { suite.add(key, () => { func.call(this._clone.self(this._self), this._clone.data(this._data)); }); }); const opts = { async: this._async }; const res = this._res; suite .on('complete', () => { const result = _.chain(suite) .map(data => { return { name: data.name, mean: data.stats.mean }; }) .sortBy('mean') .map((data, index, array) => { const name = data.name; const mean = data.mean * 1000; const diff = mean / (_.first(array).mean * 1000); console.log(`[${++index}]\t${name}\t${mean.toPrecision(3)}ms\t[${diff.toPrecision(5)}]`); return { name: name, mean: mean, diff: diff }; }) .value(opts); res.status(200); res.json(result); }) .run(); return this; } } module.exports = (req, res) => { const info = _.pick(req.body, 'async', 'setup', 'funcs'); console.log(info); const executor = new Executor(info, res); executor .setup() .test() .execute(); };
let search_outer = new Vue({ el: '#search-outer', data: { inputWord: '', //保存的是临时的搜索关键字,主要是为了上下键能回到原来关键字 tempWord: '', //设置搜索框的宽度 width: 300, left: (document.documentElement.clientWidth - 300) / 2, top: 120 }, watch: { width: function () { suggest_outer.width = this.width; }, left: function () { suggest_outer.left = this.left; }, top: function () { suggest_outer.top = this.top; } }, methods: { inputFn: function (event) { let searchKey = event.target.value; console.log(event.target.value); console.log(event.key + " " + event.code); if (event.key === 'ArrowUp') { //按下了上键 if (suggest_outer.isDisplay) { suggest_outer.liIndex--; } else { suggest_outer.isDisplay = true; suggest_outer.liIndex = -1; } } else if (event.key === 'ArrowDown') { //按下了下键 if (suggest_outer.isDisplay) { suggest_outer.liIndex++; } else { suggest_outer.isDisplay = true; suggest_outer.liIndex = -1; } } else if (event.key === 'Escape') { //按下了ESC键 console.log("按下了ESC键"); suggest_outer.isDisplay = false; suggest_outer.liIndex = -1; this.tempWord = this.inputWord; } else if (event.key === 'Enter') { //按下了回车键 if (suggest_outer.liIndex === -1) { if (this.inputWord.trim().length === 0) { return; } //搜索结果 window.open('./result.html?w=' + this.inputWord, '_self'); } else if (suggest_outer.liIndex < suggest_outer.songs.length) { //歌曲结果 alert("还没有写歌曲详情页"); } else if (suggest_outer.liIndex < suggest_outer.songs.length + suggest_outer.singers.length) { //歌手结果 window.open('./singer.html?p=1&mid=' + suggest_outer.singers[suggest_outer.liIndex - suggest_outer.songs.length].mid, '_self'); } } else { //按下了可显示的键 this.tempWord = this.inputWord; if (searchKey.length === 0) { suggest_outer.songs = []; suggest_outer.singers = []; return; } suggest_outer.liIndex = -1; suggest_outer.isDisplay = true; axios({ method: 'get', url: webUrl + '/suggest', params: { w: searchKey, } }).then(response => { console.log("ajax请求:" + searchKey); let songsTemp = []; for (let i = 0; i < response.data.data.song.itemlist.length; i++) { let song = response.data.data.song.itemlist[i]; songsTemp.push(song); } suggest_outer.songs = songsTemp; let singersTemp = []; for (let i = 0; i < response.data.data.singer.itemlist.length; i++) { let singer = response.data.data.singer.itemlist[i]; singersTemp.push(singer); } suggest_outer.singers = singersTemp; }).catch(error => console.log(error)); } }, btnClick: function () { window.open('./result.html?w=' + this.inputWord, '_self'); }, inputClick: function () { suggest_outer.isDisplay = true; // console.log("show"); } }, mounted: function () { this.$el.style.display = "block"; window.addEventListener("click", function (event) { // console.log(event.target); // console.log("click"); suggest_outer.isDisplay = false; suggest_outer.liIndex = -1; }) } }); let suggest_outer = new Vue({ el: '#suggest-outer', data: { isDisplay: true, width: search_outer.width, left: search_outer.left, top: search_outer.top, //上下键位置 liIndex: -1, //鼠标选中位置,-1表示未选中任何<li> mouseIndex: -1, songs: [ // { // name: '我还想她', // singer: '林俊杰' // } ], singers: [ // { // name: '林俊杰' // } ] }, methods: { songClick: function (id, mid) { console.log(id + " " + mid); alert("还没有写歌曲详情页"); }, singerClick: function (id, mid) { console.log(id + " " + mid); window.open('./singer.html?p=1&mid=' + mid, '_self'); } }, watch: { width: function () { search_outer.width = this.width; }, left: function () { search_outer.left = this.left; }, top: function () { search_outer.top = this.top; }, liIndex: function () { if (this.liIndex < -1) { this.liIndex = this.songs.length + this.singers.length - 1; } else if (this.liIndex > this.songs.length + this.singers.length - 1) { this.liIndex = -1; } if (this.liIndex === -1) { search_outer.inputWord = search_outer.tempWord; } else if (this.liIndex < this.songs.length) { search_outer.inputWord = this.songs[this.liIndex].name + " -" + this.songs[this.liIndex].singer; } else { search_outer.inputWord = this.singers[this.liIndex - this.songs.length].name; } } } });
$.extend({ websocket:function(type,callback) { var socket; if (!window.WebSocket) { window.WebSocket = window.MozWebSocket; } var domain = document.domain; if (window.WebSocket) { // ws://"+domain+":9090/ws?type=event// 智能检测 // ws://"+domain+":9090/ws?type=traffic_warning// 路况预警 // ws://"+domain+":9090/ws?type=msg_publish// 信息发布 // ws://"+domain+":9090/ws?type=traffic// 实时路况 socket = new WebSocket("ws://"+domain+":9090/ws?type="+type); socket.onmessage = function(event) { callback(event); }; socket.onopen = function(event) { console.log("打开websocket服务正常"); } socket.onclose = function(event) { console.log("websocket关闭"); } } else { alert("对不起,您的浏览器不支持WebSocket."); } return socket; } });
import R from '../R/R' import { render } from './render' const RD = { render } // class Demo extends R.Component { // constructor() { // this.state = { // name: "zzx" // } // } // setState() { // } // render() { // return ( // <div> // </div> // ) // } // } const el = R.createElement RD.render( el("div", { className: "kuangjiajia" }, [el("div", { className: "zzxa" }, "zxadsad"), el("div", { className: "zzxa" }, "zxadsad")]), document.querySelector("#root") )
(() => { const app = Stimulus.Application.start(); app.register("greeter", class extends Stimulus.Controller { static get targets() { return ['input', 'output']; } connect() { } greet(e) { e.preventDefault(); let value = this.inputTarget.value; this.outputTarget.innerHTML = `Greetings, ${value}`; } }); })();
const test = require('tape'); const flatten = require('./flatten.js'); test('Testing flatten', (t) => { //For more information on all the methods supported by tape //Please go to https://github.com/substack/tape t.true(typeof flatten === 'function', 'flatten is a Function'); t.deepEqual(flatten([1, [2], 3, 4]), [1, 2, 3, 4], "Flattens an array"); t.deepEqual(flatten([1, [2, [3, [4, 5], 6], 7], 8], 2), [1, 2, 3, [4, 5], 6, 7, 8], "Flattens an array"); //t.deepEqual(flatten(args..), 'Expected'); //t.equal(flatten(args..), 'Expected'); //t.false(flatten(args..), 'Expected'); //t.throws(flatten(args..), 'Expected'); t.end(); });
import React, { Component } from "react"; import AddCustomer from "./Component/AddCustomer" import AddProduct from "./Component/AddProduct"; import AddSale from "./Component/AddSale"; import { Route, BrowserRouter as Router } from "react-router-dom"; import Customer from "./Component/Customer"; import Product from "./Component/Product"; import Sale from "./Component/Sale"; import Sidebar from "./Component/NavBar" import Home from "./Component/Home" import Analytics from "./Component/Analytics" class App extends Component { render() { return ( <div id="App"> <Sidebar/> <Router> <Route exact path="/Home" component={Home} /> <Route exact path="/AddCustomer" component={AddCustomer} /> <Route exact path="/AddProduct" component={AddProduct} /> <Route exact path="/AddSale" component={AddSale} /> <Route exact path="/customer" component={Customer} /> <Route exact path="/product" component={Product} /> <Route exact path="/sale" component={Sale} /> <Route exact path="/Analytics" component={Analytics} /> <Route exact path="/" component={Home} /> </Router> </div> ); } } export default App;
import React from 'react'; import {Grid, Typography, Fade } from '@material-ui/core'; import '../index.css'; export default class App extends React.Component { render(){ return( <Grid className="Screen_Challenger" container spacing={0} direction="column" alignItems="center" justify="center" style={{ minHeight: '100vh', color:'#FFF' }} > <Grid item xs={6}> <Fade in={true}> <Typography variant="subtitle1" gutterBottom> <br/> Waiting for host to start the game </Typography> </Fade> </Grid> </Grid> ) } }
import axios from 'axios' const baseURL = process.env.CONVERSION_URL || 'http://localhost:3001' export async function getRoman(num) { const url = 'toRoman' const result = await axios.get(`${url}/${num}`, { baseURL }) return result.data } export async function getArabic(str) { const url = 'toArabic' const result = await axios.get(`${url}/${str}`, { baseURL }) return result.data }
/* * * scaleManagementApi.js * * Copyright (c) 2016 HEB * All rights reserved. * * This software is the confidential and proprietary information * of HEB. * */ 'use strict'; /** * Constructs the API to call the backend for scale management api. */ (function () { angular.module('productMaintenanceUiApp').factory('ScaleManagementApi', scaleManagementApi); scaleManagementApi.$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 scaleManagementApi(urlBase, $resource) { return $resource(null, null, { // Get the scale management list by plu(s). 'queryByPluList': { method: 'GET', url: urlBase + '/pm/scaleManagement/pluList', isArray:false }, // Get the scale management list by description. 'queryByDescription': { method: 'GET', url: urlBase + '/pm/scaleManagement/description', isArray:false }, // Retrieve a list of found and not found PLUs in the scale upc table. 'queryForMissingPLUs': { method: 'GET', url: urlBase + '/pm/scaleManagement/hits/pluList', isArray:false }, // Updates the scale management upc from the maintenance page. 'updateScaleUpc': { method: 'PUT', url: urlBase + '/pm/scaleManagement/updateScaleUpc', isArray:false }, // Bulk updates the scale management upc list from the maintenance page. 'bulkUpdateScaleUpc': { method: 'PUT', url: urlBase + '/pm/scaleManagement/bulkUpdateScaleUpc' }, // Get the scale management action codes information by action codes. 'queryByActionCodes': { method: 'GET', url: urlBase + '/pm/scaleManagement/actionCodes', isArray:false }, // Get the scale management action codes information by action codes. 'queryByActionCodeDescription': { method: 'GET', url: urlBase + '/pm/scaleManagement/actionCodeDescription', isArray:false }, // Retrieve a list of plus by action code in the scale upc table. 'queryForPLUsByActionCode': { method: 'GET', url: urlBase + '/pm/scaleManagement/pluListByActionCode', isArray:false }, // Retrieve a list of found and not found action codes in the scale upc table. 'queryForMissingActionCodes': { method: 'GET', url: urlBase + '/pm/scaleManagement/hits/actionCodes', isArray:false }, // Updates an action code with a new description. 'updateActionCode': { method: 'PUT', url: urlBase + '/pm/scaleManagement/updateScaleActionCode', isArray:false }, // Creates a new action code with a new description. 'addActionCode': { method: 'POST', url: urlBase + '/pm/scaleManagement/addScaleActionCode', isArray:false }, // Deletes an action code. 'deleteActionCode': { method: 'DELETE', url: urlBase + '/pm/scaleManagement/deleteScaleActionCode', isArray:false }, //Retrieve a list of All action codes in the scale upc table. 'queryAllActionCodes': { method: 'GET', url: urlBase + '/pm/scaleManagement/queryAllActionCodes', isArray:false }, // Get all label formats. 'queryForLabelFormats': { method: 'GET', url: urlBase + '/pm/scaleManagement/labelFormats', isArray:false }, // Retrieve a list of found and not found action codes in the scale upc table. 'queryForMissingLabelFormats': { method: 'GET', url: urlBase + '/pm/scaleManagement/labelFormats/hits', isArray:false }, // Get label formats by description. 'queryForLabelFormatsByDescription': { method: 'GET', url: urlBase + '/pm/scaleManagement/labelFormats/description' }, // Get label formats by code. 'queryForLabelFormatsByCode': { method: 'GET', url: urlBase + '/pm/scaleManagement/labelFormats/code' }, // Get a list of UPCs that have a given label format set for label format one. 'queryforUpcsByFormatCodeOne': { method: 'GET', url: urlBase + '/pm/scaleManagement/labelFormats/upcs/one' }, // Get a list of UPCs that have a given label format set for label format two. 'queryforUpcsByFormatCodeTwo': { method: 'GET', url: urlBase + '/pm/scaleManagement/labelFormats/upcs/two' }, // Get a list of UPCs that have a given ingredient statement number. 'queryforUpcsByIngredientStatementNumber': { method: 'GET', url: urlBase + '/pm/ingredientStatement/scaleUpc' }, // Updates a label format code with a new description. 'updateFormatCode': { method: 'PUT', url: urlBase + '/pm/scaleManagement/labelFormats/updateScaleLabelFormatCode', isArray:false }, // Creates a new label format code with a new description. 'addLabelFormat': { method: 'POST', url: urlBase + '/pm/scaleManagement/labelFormats/addScaleLabelFormatCode', isArray:false }, // Deletes an action code. 'deleteFormatCode': { method: 'DELETE', url: urlBase + '/pm/scaleManagement/labelFormats/deleteScaleLabelFormatCode', isArray:false }, //Get Ingredient report by ingredient Code. 'queryByIngredientCode': { method: 'GET', url: urlBase + '/pm/ingredient/ingredientCodes', isArray:false }, // Get Ingredients that a code is a sub-ingredient of. 'queryForSuperIngredients': { method: 'GET', url: urlBase + '/pm/ingredient/superIngredients', isArray:false }, //Get Ingredient report by ingredient description. 'queryByIngredientDescription':{ method: 'GET', url: urlBase + '/pm/ingredient/ingredientDescription', isArray:false }, //Get Ingredient report by Ingredient statement. 'queryByIngredientStatement':{ method: 'GET', url: urlBase + '/pm/ingredient/ingredientStatement', isArray:false }, //Query for Nutrient information by nutrient code. 'queryForNutrientsByNutrientCode':{ method: 'GET', url: urlBase + '/pm/nutrients/nutrientCodes', isArray:false //Query for Nutrient information by Description. },'queryByNutrientDescription':{ method: 'GET', url: urlBase + '/pm/nutrients/nutrientDescription', isArray:false //Query for all Nutrient information. },'queryForNutrientsByAll':{ method: 'GET', url: urlBase + '/pm/nutrients/queryAllNutrientCodes', isArray:false }, // Updates an action code with a new description. 'updateNutritionData': { method: 'PUT', url: urlBase + '/pm/nutrients/updateNutritionData', isArray:false }, // Creates a new nutrient code. 'addNutrientData': { method: 'POST', url: urlBase + '/pm/nutrients/addNutrientData', isArray:false }, // Deletes a nutrient code. 'deleteNutrientData': { method: 'DELETE', url: urlBase + '/pm/nutrients/deleteNutrientData', isArray:false }, // Finds nutrient unit of measure by regular exp ression. 'findNutrientUomByRegularExpression': { method: 'GET', url: urlBase + '/pm/scaleManagement/nutrientUomCode/nutrientUomIndex', isArray:false }, // Query for the nutrient statement rules by nutrient code 'queryForNutrientStatementByNutrientCode': { method: 'GET', url: urlBase + '/pm/nutrientsStatement/nutrientStatementByCode', isArray:false }, 'queryForNutrientStatementsByAll': { method: 'GET', url: urlBase + '/pm/nutrientsStatement/queryAllNutrientStatement', isArray:false }, 'queryForNutrientStatementByStatementId': { method: 'GET', url: urlBase + '/pm/nutrientsStatement/nutrientStatementByNutrientStatementId', isArray:false }, 'queryForMissingNutrientStatementsByNutrientStatements': { method: 'GET', url: urlBase + '/pm/nutrientsStatement/hits/nutrientStatements', isArray:false }, 'queryForMissingNutrientCodesByNutrientStatements': { method: 'GET', url: urlBase + '/pm/nutrientsStatement/hits/nutrientCodes', isArray:false }, //Add new nutrient statement 'addStatement':{ method: 'POST', url: urlBase + '/pm/nutrientsStatement/addStatement', isArray:false }, // Updates an nutrition statement with a new data. 'updateNutritionStatementData': { method: 'PUT', url: urlBase + '/pm/nutrientsStatement/updateNutrientStatementData', isArray:false }, // Gets the mandated nutrients by statement Id. 'getMandatedNutrientsByStatementId':{ method: 'GET', url: urlBase + '/pm/nutrientsStatement/mandatedNutrientsByStatementId', isArray:true }, // Removes a nutrient statement. 'deleteNutrientStatement':{ method: 'DELETE', url: urlBase + '/pm/nutrientsStatement/deleteNutrientStatement', isArray:false }, // Searches to see if nutrient statement is available. 'searchForAvailableNutrientStatement':{ method: 'GET', url: urlBase + '/pm/nutrientsStatement/searchForAvailableNutrientStatement', isArray:false }, // Query for the nutrient rounding rules by nutrient code 'queryForNutrientRoundingRules':{ method: 'GET', url: urlBase + '/pm/nutrients/nutrientRoundingRules', isArray:true }, // Checks to see if any searched nutrient codes aren't found. 'queryForMissingNutrientCodes': { method: 'GET', url: urlBase + '/pm/nutrients/hits/nutrientCodes', isArray:false }, // Searches to see if nutrient code is available. 'searchForAvailableNutrientCode':{ method: 'GET', url: urlBase + '/pm/nutrients/searchForAvailableNutrientCode', isArray:false }, // Updates a nutrient Rounding Rules. 'updateRoundingRule': { method: 'PUT', url: urlBase + '/pm/nutrients/updateRoundingRules', isArray:false }, // Retrieves all ingredient categories by category code. 'queryByIngredientCategoryCode':{ method: 'GET', url: urlBase + '/pm/ingredientCategory/ingredientCode', isArray:false }, // Retrieves all ingredient categories by description. 'queryByIngredientCategoryDescription':{ method: 'GET', url: urlBase + '/pm/ingredientCategory/ingredientDescription', isArray:false }, // Retrieves all ingredient categories. 'getAllCategories':{ method: 'GET', url: urlBase + '/pm/ingredientCategory/allCategories', isArray:false }, // Retrieve a list of found and not found action codes in the scale upc table. 'queryForMissingIngredientCategoryCodes': { method: 'GET', url: urlBase + '/pm/ingredientCategory/hits/ingredientCode', isArray:false }, // Updates an an ingredient category with a new description. 'updateIngredientCategory': { method: 'PUT', url: urlBase + '/pm/ingredientCategory/updateIngredientCategory', isArray:false }, // Creates a new ingredient category.. 'addIngredientCategory': { method: 'POST', url: urlBase + '/pm/ingredientCategory/addIngredientCategory', isArray:false }, // Deletes an ingredient category. 'deleteIngredientCategory': { method: 'DELETE', url: urlBase + '/pm/ingredientCategory/deleteIngredientCategory', isArray:false }, // Creates a new ingredient. 'addIngredient': { method: 'POST', url: urlBase + '/pm/ingredient/addIngredient', isArray:false }, // Creates a new ingredient. 'updateIngredient': { method: 'POST', url: urlBase + '/pm/ingredient/updateIngredient', isArray:false }, 'getIngredientsByRegularExpression': { method: 'GET', url: urlBase + '/pm/ingredient/ingredientRegex', isArray: false }, //Query for all Categories information 'getAllCategoriesList':{ method: 'GET', url: urlBase + '/pm/ingredientCategory/allCategoriesList', isArray:true }, // Deletes an ingredient. 'deleteIngredient': { method: 'POST', url: urlBase + '/pm/ingredient/deleteIngredient' }, // Gets all ingredients. 'queryAllIngredients': { method: 'GET', url: urlBase + '/pm/ingredient/allIngredients' }, // Retrieves all ingredient statements. 'queryAllIngredientStatements': { method: 'GET', url: urlBase + '/pm/ingredientStatement/allIngredientStatement', isArray:false }, // Retrieves ingredient statements by ingredient statements. 'queryIngredientStatementByStatementCode': { method: 'GET', url: urlBase + '/pm/ingredientStatement/ingredientStatement', isArray: false }, // Retrieves ingredient statements by ingredient code. 'queryIngredientStatementByIngredientCode': { method: 'GET', url: urlBase + '/pm/ingredientStatement/ingredientCode', isArray: false }, // Retrieves ingredient statements by ingredient code. 'queryIngredientStatementByIngredientCodeOrdered': { method: 'GET', url: urlBase + '/pm/ingredientStatement/ingredientCodeOrdered', isArray: false }, // Retrieves ingredient statements with ingredients contain the provided description. 'queryIngredientStatementByDescription' : { method: 'GET', url: urlBase + '/pm/ingredientStatement/description', isArray: false }, // Deletes an ingredient category. 'deleteIngredientStatement': { method: 'DELETE', url: urlBase + '/pm/ingredientStatement/deleteIngredientStatement', isArray:false }, // Creates a new ingredient statement. 'addIngredientStatement': { method: 'POST', url: urlBase + '/pm/ingredientStatement/addIngredientStatement', isArray:false }, // Creates a new ingredient statement based on a set of ingrdeients. 'newIngredientStatement': { method: 'GET', url: urlBase + '/pm/ingredientStatement/newIngredientStatement', isArray:false }, // Creates a new ingredient. 'updateIngredientStatement': { method: 'POST', url: urlBase + '/pm/ingredientStatement/updateIngredientStatement', isArray:false }, // Retrieve a list of found and not found PLUs in the scale upc table. 'queryIngredientStatementsForMissingIngredientStatements': { method: 'GET', url: urlBase + '/pm/ingredientStatement/hits/ingredientStatements', isArray:false }, // Finds the next statement number equal or less than the statement number provided. 'queryForNextIngredientStatementNumber':{ method: 'GET', url: urlBase + '/pm/ingredientStatement/nextIngredientStatement', isArray: true }, 'getNextIngredientCode':{ method: 'GET', url: urlBase + '/pm/ingredient/nextIngredientCode', isArray: true }, 'getNutrientsByRegularExpression':{ method:'GET', url: urlBase + '/pm/nutrients/getNutrientsByRegularExpression', isArray: false }, 'queryByGraphicsCodes': { method: 'GET', url: urlBase + '/pm/scaleManagement/graphicsCode/graphicsCodes', isArray:false }, 'queryByGraphicsCodeDescription': { method: 'GET', url: urlBase + '/pm/scaleManagement/graphicsCode/graphicsCodeDescription', isArray:false }, 'queryScaleUpcByScaleCode': { method: 'GET', url: urlBase + '/pm/scaleManagement/graphicsCode/scaleUpc', isArray:false }, 'findHitsByGraphicsCodes' : { method: 'GET', url: urlBase + '/pm/scaleManagement/graphicsCode/hits', isArray:false }, 'update' : { method: 'PUT', url: urlBase + '/pm/scaleManagement/graphicsCode', isArray:false }, 'deleteGraphicsCode' : { method: 'DELETE', url: urlBase + '/pm/scaleManagement/graphicsCode', isArray:false }, 'addGraphicsCode' : { method: 'POST', url: urlBase + '/pm/scaleManagement/graphicsCode/addGraphicsCode', isArray:false }, 'findAllGraphicsCodes' : { method: 'GET', url: urlBase + '/pm/scaleManagement/graphicsCode/findAllGraphicsCodes', isArray:false }, 'applyRoundingRuleToNutrient' : { method: 'PUT', url: urlBase + '/pm/nutrientsStatement/applyRoundingRuleToNutrient', isArray:false }, 'getNutrientStatementPanelHeaderBySourceSystemReferenceId': { method: 'GET', url: urlBase + '/pm/NLEA16NutrientStatement/:sourceSystemReferenceId', params: {sourceSystemReferenceId:'@sourceSystemReferenceId'}, isArray: false }, 'findAllNutrientStatementPanels': { method: 'GET', url: urlBase + '/pm/NLEA16NutrientStatement/all', isArray:false }, 'findAllNutrientStatementPanelsByIds': { method: 'GET', url: urlBase + '/pm/NLEA16NutrientStatement', isArray:false }, 'updateNLEA16Statement':{ method: 'POST', url: urlBase + '/pm/NLEA16NutrientStatement/update', isArray:false }, 'sendScaleMaintenance': { method: 'PUT', url: urlBase + '/pm/scaleManagement/sendMaintenance', isArray:false }, 'isNLEA16NutrientStatementExists': { method: 'GET', url: urlBase + '/pm/nutrientsStatement/isNLEA16NutrientStatementExists', isArray:false }, 'findAllUnitOfMeasures': { method: 'GET', url: urlBase + '/pm/NLEA16NutrientStatement/unitOfMeasures', isArray:true }, 'getMandatedNutrients':{ method: 'GET', url: urlBase + '/pm/NLEA16NutrientStatement/mandatedNutrients', isArray:true }, 'addNLEA16Statement':{ method: 'POST', url: urlBase + '/pm/NLEA16NutrientStatement/add', isArray:false }, 'isNutrientStatementExists':{ method: 'GET', url: urlBase + '/pm/NLEA16NutrientStatement/isNutrientStatementExists', isArray:false }, // Removes a nutrient statement. 'deleteNLEA16NutrientStatement':{ method: 'DELETE', url: urlBase + '/pm/NLEA16NutrientStatement/deleteNLEA16NutrientStatement', isArray:false } }); } })();
import axios from 'axios'; const nums = '0123456789'; export default { metodoPost: (valores, matricula, texto, data) => { axios({ method: 'post', url: "https://backend-icc.herokuapp.com/salvaValores", //"https://backend-icc.herokuapp.com/salvaValores" "http://localhost:9000/salvaValores" headers: { "Content-Type": "application/json" }, data: { values: valores, matricula: matricula, textArea: texto, data: data } }); }, metodoGet: (dataAgora) => { return axios.get("https://backend-icc.herokuapp.com/pegaValores", { params: dataAgora }); //"https://backend-icc.herokuapp.com/pegaValores" "http://localhost:9000/pegaValores" }, validarMatricula: (matricula) => { if (matricula.length < 10 && matricula.length > 0) { for (let i = 0; i < matricula.length; i++) { if (!nums.match(matricula[i])) { return false; } } } else { return false; } return true; } };
import ava from 'ava' import permutations from '../src/index.js' const components = { Button: ` import React from 'react' const Button = ({ big, color, outline, title, padding, config, children, ...props }) => { const style = { display: 'inline-block', padding: padding, border: 0, borderRadius: 2, color: 'white', backgroundColor: color, } return ( <button {...props} style={style}> {children} </button> ) } Root.propTypes = { big: React.PropTypes.bool, color: React.PropTypes.oneOf([ 'blue', 'green', 'red' ]), outline: React.PropTypes.bool, title: React.PropTypes.string, padding: React.PropTypes.number, items: React.PropTypes.array, nums: React.PropTypes.arrayOf(React.PropTypes.number), config: React.PropTypes.object } Root.defaultProps = { color: 'blue', icon: 'check', padding: 16 } export default Button `, Root: ` import React from 'react' class Root extends React.Component { render () { const { title } = this.props return <html>{title}</html> } } Root.propTypes = { title: React.PropTypes.string, responsive: React.PropTypes.bool, fontFamily: React.PropTypes.oneOf(['Georgia', 'Helvetica', 'Verdana']) } export default Root `, Input: ` import React from 'react' var sizes = [ 8, 16, 24 ] var Input = React.createClass({ propTypes: { size: React.PropTypes.oneOf(sizes) }, render: function () { var style = { padding: size } return ( <input {...this.props} style={style} /> ) } }) module.exports = Input ` } ava('is a function', t => { t.same(typeof permutations, 'function') }) ava('returns an array', t => { const p = permutations(components.Button) t.same(Array.isArray(p), true) }) ava('returns false if no component is found', t => { const p = permutations('Not a component') t.same(p, false) }) ava('returns 12 permutations for Button', t => { const p = permutations(components.Button) t.same(p.length, 12) }) ava('returns 6 permutations for Root', t => { const p = permutations(components.Root) t.same(p.length, 6) }) ava('allows configurable keys', t => { const p = permutations(components.Button, { color: ['green', 'blue'] }) t.same(p.length, 8) }) ava('returns correct values for configurable keys', t => { const p = permutations(components.Button, { color: ['green', 'blue'] }) t.same(p[0].color, 'green') }) ava('should handle computed enum', t => { const p = permutations(components.Input) t.same(p[0], undefined) }) ava('allows configurable strings', t => { const p = permutations(components.Button, { strings: [ 'Hello', 'Button' ] }) t.same(p.length, 24) }) ava('allows configurable numbers', t => { const p = permutations(components.Button, { numbers: [ 2, 4, 8 ] }) t.same(p.length, 36) }) ava('allows configurable arrays', t => { const p = permutations(components.Button, { arrays: [ [1, 2, 3], [4, 5, 6] ] }) t.same(p.length, 24) }) ava('allows configurable objects', t => { const p = permutations(components.Button, { objects: [ { name: 'Hello' }, { name: 'Test' } ] }) t.same(p.length, 24) })
'use strict' const btoa = require('btoa') const uuidv4 = require('uuid/v4') const authorizer = require('./helpers/authorizer') const createHelper = require('./helpers/create') const getHelper = require('./helpers/get') const updateHelper = require('./helpers/update') const deleteHelper = require('./helpers/delete') const allowedKeys = require('./helpers/keys') const errors = require('./helpers/errors') const headers = require('./helpers/headers') const USER_TABLE_NAME = process.env.USER_TABLE_NAME || 'marble-user-content-users' const USER_PRIMARY_KEY = process.env.USER_PRIMARY_KEY || 'uuid' const USER_SECONDARY_KEY = process.env.USER_SECONDARY_KEY || 'userName' const COLLECTION_TABLE_NAME = process.env.COLLECTION_TABLE_NAME || 'marble-user-content-collections' const COLLECTION_PRIMARY_KEY = process.env.COLLECTION_PRIMARY_KEY || 'uuid' const COLLECTION_SECONDARY_KEY = process.env.COLLECTION_SECONDARY_KEY || 'userId' const ITEM_TABLE_NAME = process.env.ITEM_TABLE_NAME || 'marble-user-content-items' const ITEM_PRIMARY_KEY = process.env.ITEM_PRIMARY_KEY || 'uuid' const ITEM_SECONDARY_KEY = process.env.ITEM_SECONDARY_KEY || 'collectionId' module.exports.handler = async (event) => { const props = await requestProps(event) if (['POST', 'PATCH', 'DELETE'].includes(event.httpMethod)) { const authorized = await canModify(event, props.claims) if (!authorized) { return { statusCode: 401, headers: headers, body: errors.UNAUTHORIZED, } } } switch (event.httpMethod) { case 'POST': if (event.resource.indexOf('user') !== 1) { props.parentId = props.id props.id = uuidv4() } return createHelper.create(props) case 'PATCH': return updateHelper.update(props) case 'DELETE': return deleteHelper.delete(props) case 'GET': if (event.resource.indexOf('user') === 1 && event.resource.indexOf('user-id') !== 1) { props.secondaryId = props.id props.secondaryKey = USER_SECONDARY_KEY } return getHelper.get(props) default: return { statusCode: 500, headers: headers, body: errors.UNKNOWN_REQUEST, } } } const requestProps = async (event) => { const props = { id: event.pathParameters.id, body: event.body, claims: await authorizer.verifyTokenAndReturnClaims(event.headers.Authorization) || {}, } if (event.resource.indexOf('user') === 1) { props.table = USER_TABLE_NAME props.primaryKey = USER_PRIMARY_KEY props.allowedKeys = allowedKeys.user props.childrenName = 'collections' props.childTable = COLLECTION_TABLE_NAME props.childPrimaryKey = COLLECTION_PRIMARY_KEY props.childSecondaryKey = COLLECTION_SECONDARY_KEY } else if (event.resource.indexOf('collection') === 1) { props.table = COLLECTION_TABLE_NAME props.primaryKey = COLLECTION_PRIMARY_KEY props.secondaryKey = COLLECTION_SECONDARY_KEY props.allowedKeys = allowedKeys.collection props.childrenName = 'items' props.childTable = ITEM_TABLE_NAME props.childPrimaryKey = ITEM_PRIMARY_KEY props.childSecondaryKey = ITEM_SECONDARY_KEY } else if (event.resource.indexOf('item') === 1) { props.table = ITEM_TABLE_NAME props.primaryKey = ITEM_PRIMARY_KEY props.secondaryKey = ITEM_SECONDARY_KEY props.allowedKeys = allowedKeys.item } return props } const canModify = async (event, claims) => { if (userIdFromClaims(claims)) { if (event.resource.indexOf('user') === 1) { // users cannot currently be deleted if (event.httpMethod === 'DELETE') { return false } return userIdFromClaims(claims) === event.pathParameters.id } else if (event.resource.indexOf('collection') === 1) { // valid users can create new collections, but ownership must be checked before modify or delete if (event.httpMethod === 'POST') { return true } const collection = await getHelper.get({ id: event.pathParameters.id, table: COLLECTION_TABLE_NAME, primaryKey: COLLECTION_PRIMARY_KEY, }) return collection.statusCode === 200 && JSON.parse(collection.body)[COLLECTION_SECONDARY_KEY] === userIdFromClaims(claims) } else if (event.resource.indexOf('item') === 1) { // items must have a parent collection and user must match if (event.httpMethod === 'POST') { const parentCollection = await getHelper.get({ id: event.pathParameters.id, table: COLLECTION_TABLE_NAME, primaryKey: COLLECTION_PRIMARY_KEY, }) return parentCollection.statusCode === 200 && JSON.parse(parentCollection.body)[COLLECTION_SECONDARY_KEY] === userIdFromClaims(claims) } // get item then get collection } const item = await getHelper.get({ id: event.pathParameters.id, table: ITEM_TABLE_NAME, primaryKey: ITEM_PRIMARY_KEY, }) if (item.statusCode === 200) { const collectionId = JSON.parse(item.body)[ITEM_SECONDARY_KEY] const collection = await getHelper.get({ id: collectionId, table: COLLECTION_TABLE_NAME, primaryKey: COLLECTION_PRIMARY_KEY, }) return collection.statusCode === 200 && JSON.parse(collection.body)[COLLECTION_SECONDARY_KEY] === userIdFromClaims(claims) } } } return false } const userIdFromClaims = (claims) => { const { iss, sub } = claims if (!iss || !sub) { return null } return `${sub}.${btoa(iss)}` }
import Head from 'next/head' import Image from 'next/image' import Layout from '../components/Layout' export default function Home() { return ( <div> <nav className="py-10" > <div className="absolute inset-y-0 right-0 h-[600px]" > <Image src="/cok.png" quality={100} width={500} height={650} layout="intrinsic" /> </div> <div className="max-w-screen-xl mx-auto relative"> <div className="flex"> <div className="w-2/12 flex items-center justify-start font-bold "> <img src="/logo.png" className="w-7 h-7 mr-4" alt="logo"/> NExON </div> <div className="w-8/12 flex justify-center"> <ul className="space-x-12 font-semibold cursore flex items-center"> <li><a className="hover:underline">About</a></li> <li><a className="hover:underline">Shop</a></li> <li><a className="hover:underline">Testimoni</a></li> <li><a className="hover:underline">Contact</a></li> </ul> </div> <div className="w-2/12 flex items-center justify-end"> <button className="bg-gray-700 py-2 px-7 rounded-lg text-white hover:bg-gray-700/70">Masuk</button> </div> </div> </div> </nav> <div className="max-w-screen-xl mx-auto flex relative py-10 w-full"> <div className="w-6/12"> <div className=""> <h1 className="text-5xl mt-5 font-sans font-bold items-center ">Beli makanan apapun secara online hanya disini</h1> <p className="mt-5 item-center text-lg">nexon adalah website untuk membeli makanan nusantara indonesia secara online melalui website serta gratis ongkir seluruh indonesia tanpa dikenankan biaya apapun</p> <div className="py-8"> <label className="flex relative rounded-full bg-gray-200 pl-8 pr-4 py-2"> <input className=" mt-1 px-8 py-2 border-transparent text-lg flex-1 block bg-transparent focus:ring-0 focus:border-transparent" placeholder="Makanan"/> <button className="bg-red-500 text-white text-2lg px-6 py-3 w-53 flex-shrink-0 rounded-l-full rounded-r-full flex items-center"> <svg className="w-6 h-6 mr-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg> Cari Menu </button> </label> </div> </div> </div> <div className="w-6/12"> <div className=" flex justify-center"> <Image src="/hero.png" quality={100} width={500} height={460} layout="intrinsic" /> </div> </div> </div> <div className="bg-green-500 h-44"> <div className="max-w-screen-xl mx-auto"> <div> </div> <div className="w-4/12"> </div> </div> </div> </div> ) }
// conecting fun.js file var fun = require('./fun.js'); // using inquirer var inquirer = require("inquirer"); // using inquirer(user input) inquirer.prompt({ type: 'rawlist', name: 'input', message: 'select your choice', choices: ["buy product","see the list of product"] }) //then function .then(function (answers) { //if statment if (answers.input == "buy product") { // buy function fun.buy(); } if (answers.input == "see the list of product") { // display function fun.display(); } });
// define window size var width = window.innerWidth, height = window.innerHeight; // creating an svg element var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); // create two svg group elements, one for the base map //and one for the earthquake points var group = svg.append("g"); //load both datasets Promise.all([d3.json("data/world.geojson"), ]).then(drawMap); //define the d3 projection var projection = d3.geoMercator() .translate([width / 2, height / 2]) .center([0, 0]) .scale(180); //create a tooltip div element var tooltip = d3.select("body") .append("div") .attr("id", "tooltip") //make the tooltip visible, populate with data and locate function showToolTip(properties, coords) { //event screen coordinates var x = coords[0]; var y = coords[1]; //parse the date var date = new Date(properties.time).toString(); date = date.split('GMT') date = date[0] + "UTC" //style the tooltip and add nested html content d3.select("#tooltip") .style("display", "block") .style("top", y + 'px') .style("left", x + 'px') .html(`<h3>${properties.name}</h3>` + `<b>GDP: </b>${properties.gdp_md_est}</br>` + `<b>Population: </b>${properties.pop_est}`) } function drawMap(data) { // the world geojson var world = data[0]; //create a continents array for the color scale domain var continents = [] world.features.forEach(function(item){ if(!continents.includes(item.properties.continent)){ continents.push(item.properties.continent) } }); //create color scales var catScale = d3.scaleOrdinal() .domain(continents) .range(["red", "blue", "cyan", "pink","yellow", "purple"]) var catScalePal = d3.scaleOrdinal() .domain(continents) .range(d3.schemeAccent ) // create a d3 geopath var path = d3.geoPath() .projection(projection); //bind the data (no exit and update in this case) group.selectAll("path") .data(world.features) .enter() .append("path") .attr("d", function (d) { return path(d) }) .attr("stroke", "black") .attr("fill", function(d){ return catScalePal(d.properties.continent) }) //show tooltip event .on("mousemove", function (d) { showToolTip(d.properties, [d3.event.clientX, d3.event.clientY + 30]) }) .on("mouseleave", function () { d3.select("#tooltip") .style("display", "none") }) }
import React, { PureComponent } from 'react'; import { DataProvider, Series, Collection, LineChart } from '@cognite/griff-react'; /* Since NOAA Api has no timestamps on their objects we generate some based on their idx */ const generateDataPoints = ({ timeDomain, }, telemetry) => { const data = []; let j = 0; const dt = (timeDomain[1] - timeDomain[0]) / telemetry.length + 1; for (let i = timeDomain[0]; i <= timeDomain[1]; i += dt) { data.push({ timestamp: i, value: telemetry[j].value, }); j++; } return data; }; /* Simple Loader that returns the api data with timestamp and a value */ export const demoLoader = (data, { timeDomain, }) => ({ data: generateDataPoints({ timeDomain }, data).map(point => [point.timestamp, point.value]), }); const Footer = () => ( <> <h4 style={{ width: '9%', margin: 'auto', position: 'absolute', right: '50%', bottom: '1%' }} onClick={() => window.open('https://cognite.com')} >Made by <strong style={{ color: 'navy', textDecoration: 'underline' }}>Cognite</strong>⚡️</h4> </> ); const JanToJulyRanges = [1514764800000, 1530662400000]; // 1st Jan - 4th July 2018 class ScatterPlot extends PureComponent { render() { const { data } = this.props; return ( <div style={{ marginLeft: 'auto', marginRight: 'auto', width: '80%', height: '100%', }} > <> <> <div style={{ height: '500px', width: '100%', marginTop: '10%' }}> {data.length > 0 ? <DataProvider defaultLoader={(args) => demoLoader(data, args)} timeDomain={JanToJulyRanges} timeAccessor={d => d[0]} yAccessor={d => d[1]} > <Collection id="collection"> <Series id="1" color="steelblue" drawPoints /> </Collection> <LineChart /> </DataProvider> : <h3 style={{ fontStyle: 'italic', textAlign: 'center' }}>Fetching data from NOAA... ☀️</h3>} </div> <Footer /> </> </> </div> ) } } export default ScatterPlot;
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; /* class Square extends React.Component { render() { return ( <button className="square" onClick={() => this.props.onClick()} > {this.props.value} </button> ); } } */ function Square(props) { return ( <button className={ props.isPartOfWinner ? "winnerSquare" : "square"} onClick = {props.onClick} > {props.value} </button> ) } class Board extends React.Component { /* moved to Game constructor(props) { super(props); this.state = { squares: Array(9).fill(null), xIsNext: true, } } handleClick(i) { const squares = this.props.squares.slice(); if (calculateWinner(squares) || squares[i]) { return; } squares[i] = this.props.xIsNext ? 'X':'O'; this.setState({ squares: squares, xIsNext: !this.props.xIsNext, }) } */ renderSquare(i) { return <Square value = {this.props.squares[i]} onClick = {() => this.props.onClick(i)} isPartOfWinner = {this.props.winner.includes(i)} />; } render() { let stageOne = []; let stageTwo = []; for (let j=0; j<3; j++ ) { for (let k=0; k<3; k++ ){ stageOne.push(this.renderSquare(3*j+k)); }; stageTwo.push(<div className="board-row">{stageOne}</div>); stageOne = []; }; return ( <div> {stageTwo} </div> ); } } class Game extends React.Component { constructor(props) { super(props); this.state = { history: [{ squares: Array(9).fill(null), row: null, column : null, }], stepNumber:0, xIsNext: true, clickedStep: null, winner: [], isReversed: false, }; } handleClick(i) { const history = this.state.history.slice(0, this.state.stepNumber + 1); const current = history[history.length - 1]; const squares = current.squares.slice(); if (this.state.winner.length>0 || squares[i]){ return; } squares[i] = this.state.xIsNext ? 'X' : 'O'; this.setState({ history: history.concat([{ squares: squares, row: whichRow(i), column: whichCol(i), }]), stepNumber: history.length, xIsNext: !this.state.xIsNext, clickedStep: null, }); const winner = calculateWinner(squares); this.setState({winner:winner}); } handleReverse (){ this.setState ({ isReversed: !this.state.isReversed, }); } jumpTo(step) { this.setState({ stepNumber: step, xIsNext: (step % 2) === 0, clickedStep: step, winner: calculateWinner(this.state.history[step]), }); } restart() { this.setState({ history: [{ squares: Array(9).fill(null), row: null, column : null, }], stepNumber:0, xIsNext: true, clickedStep: null, winner: [], isReversed: false, }); } render() { const history = this.state.history; const current = history[this.state.stepNumber]; let moves = history.map ((step, move) => { const desc = move ? 'Go to move #' + move + ' row ' + step.row + ' column ' + step.column: 'Go to Start'; return ( <li key={move}> <button onClick={() => this.jumpTo(move)} className={move === this.state.clickedStep ? "active" : ''}>{desc}</button> </li> ); }); let status; let gameFinished = false; if (this.state.winner.length>0) { status = this.state.winner[0] + ' wins!'; gameFinished = true; } else if (current.squares.every(val=> val)){ status = 'The game has ended, there is no winner :(' gameFinished = true; } else { status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O') } return ( <div className="game"> <div className="game-board"> <Board squares={current.squares} onClick={(i) => this.handleClick(i)} winner = {this.state.winner} /> </div> <div className="game-info"> <div>{status}</div> <button onClick={() => {this.restart();}} hidden={!gameFinished}> Restart </button> <button onClick={() => this.handleReverse()}>'Reverse the list'</button> <ul>{this.state.isReversed ? moves.reverse() : moves }</ul> </div> </div> ); } } // ======================================== ReactDOM.render( <Game />, document.getElementById('root') ); function calculateWinner(squares) { const lines = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6], ]; for (let i = 0; i < lines.length; i++){ const [a,b,c] = lines[i]; if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { return [squares[a], a, b, c]; } } return []; } function whichRow(i) { /* not nice const row1 = [0,1,2]; const row2 = [3,4,5]; let row = (rowA.includes(i) ? '1' : (rowB.includes(i) ? '2' : '3'));*/ let rowI = parseInt(i/3); let row = ( rowI === 0 ? '1' : (rowI === 1 ? '2' : '3')); return row; } function whichCol(i) { /* not nice const col1 = [0,3,6]; const col2 = [1,4,7]; let col = (col1.includes(i) ? '1' : (col2.includes(i) ? '2' : '3'));*/ let col = (i%3 === 0 ? '1' : (i%3 === 1 ? '2' : '3')); return col; }
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import { margin, compose } from 'styled-system'; import { createPropTypes } from '@styled-system/prop-types'; import { getRectFor, lerp } from '../../helpers/geometry'; import { noop, isNotTouchEvent } from '../../helpers/event'; import { onKey, onKeys } from '../../helpers/keyEvents'; import { roundToPlaces, clamp } from '../../helpers/math'; import { getWindow } from '../../helpers/window'; import { useResizeObserver } from '../../hooks'; import { slider, rail, railHover, track, tick, tickHover, tickLabel, handle, handleShadow, } from './styles'; import { pick } from '@styled-system/props'; const system = compose(margin); export const StyledSlider = styled('div')` ${slider} ${system} `; const StyledRail = styled('div')` ${rail} ${StyledSlider}:hover & { ${railHover} } `; const StyledTrack = styled('div')` ${track} `; const StyledTick = styled('div')` ${tick} ${StyledSlider}:hover & { ${tickHover} } `; const StyledTickLabel = styled('div')` ${tickLabel} `; const StyledHandle = styled('div')` ${handle} `; const StyledHandleShadow = styled('div')` ${handleShadow} `; function Slider(props) { const { defaultValue, disabled, id, max, min, onBlur, onFocus, onChange, precision, ticks, value, ...rest } = props; const systemProps = pick(rest); const environment = getWindow(); const [resizeRef, { contentRect }] = useResizeObserver(); const [sliderValue, setSliderValue] = React.useState( value || defaultValue != null ? defaultValue : min, ); const [sliderLocation, setSliderLocation] = React.useState(0); const [rect, setRect] = React.useState({}); const [moving, setMoving] = React.useState(); const sliderRef = React.useRef(); React.useEffect(() => { setRect(getRectFor(sliderRef.current)); }, [contentRect, sliderRef.current]); // Calculates step increments based on precision const interval = React.useMemo(() => { let interval = 1; if (precision > 0) { const zeros = '0'.repeat(precision - 1); interval = parseFloat(`0.${zeros}1`); } return interval; }, [precision]); // Sets internal value when value is controlled externally React.useEffect(() => { if (!isNaN(parseFloat(value)) && isFinite(value)) { setValue(value); } }, [value]); // Updates slider location when value changes React.useEffect(() => { if (rect.width) { const absoluteProportion = (sliderValue - min) / Math.abs(min - max); setSliderLocation(lerp(0, rect.width, absoluteProportion)); if (onChange) { onChange(sliderValue); } } }, [sliderValue, rect.width]); // Updates tick locations when ticks or component size change const tickLocations = React.useMemo(() => { if (!ticks || !rect.width) { return {}; } return Object.keys(ticks).reduce((acc, number) => { const absoluteProportion = (Number(number) - min) / Math.abs(min - max); return { ...acc, [number]: { position: lerp(0, rect.width, absoluteProportion), label: ticks[number], }, }; }, {}); }, [ticks, rect.width]); // Event handlers function handleMouseDown(e) { if (e.button !== 0) { return; } const mousePosition = e.pageX; setPositions(mousePosition); setMoving('mouse'); } function handleMouseMove(e) { const mousePosition = e.pageX; setPositions(mousePosition); } function handleTouchStart(e) { if (isNotTouchEvent(e)) { return; } const position = e.touches[0].pageX; setPositions(position); setMoving('touch'); } function handleTouchMove(e) { if (isNotTouchEvent(e)) { return; } const position = e.touches[0].pageX; setPositions(position); } function handleEnd() { setMoving(null); } function handleKeyDown(e) { e.stopPropagation(); e.preventDefault(); onKeys(['arrowLeft', 'arrowDown'], () => setValue(sliderValue - interval))(e); onKeys(['arrowRight', 'arrowUp'], () => setValue(sliderValue + interval))(e); onKey('home', () => setValue(min))(e); onKey('end', () => setValue(max))(e); } // Sets slider value based on an x position function setPositions(xPosition) { const clampedPixelOffset = clamp(xPosition - rect.left, 0, rect.width); const percentOffset = clampedPixelOffset / rect.width; setValue(lerp(min, max, percentOffset)); } // Sets value to a provided value function setValue(newValue) { const clampedValue = clamp(newValue, min, max); setSliderValue(roundToPlaces(clampedValue, precision)); } // Binding of mouse/touch drag events React.useEffect(() => { if (moving === 'mouse') { environment.addEventListener('mousemove', handleMouseMove); environment.addEventListener('mouseup', handleEnd); } if (moving === 'touch') { environment.addEventListener('touchmove', handleTouchMove); environment.addEventListener('touchend', handleEnd); } return () => { if (moving === 'mouse') { environment.removeEventListener('mousemove', handleMouseMove); environment.removeEventListener('mouseup', handleEnd); } if (moving === 'touch') { environment.removeEventListener('touchmove', handleTouchMove); environment.removeEventListener('touchend', handleEnd); } }; }, [moving]); const tickMarkup = Object.keys(tickLocations).map(tick => { const { label, position } = tickLocations[tick]; return ( <StyledTick key={tick} style={{ left: position }} disabled={disabled} included={tick < sliderValue} > <StyledTickLabel>{label}</StyledTickLabel> </StyledTick> ); }); const assignRefs = node => { if (sliderRef) { sliderRef.current = node; } if (resizeRef) { resizeRef(node); } }; return ( <StyledSlider hasTicks={ticks} disabled={disabled} data-id="slider-wrapper" onTouchStart={disabled ? noop : handleTouchStart} onMouseDown={disabled ? noop : handleMouseDown} ref={assignRefs} {...systemProps} > <StyledRail disabled={disabled} /> {tickMarkup} <StyledTrack disabled={disabled} style={{ width: sliderLocation }} /> <StyledHandle id={id} aria-controls={props['aria-controls']} aria-valuemin={min} aria-valuemax={max} aria-valuenow={sliderValue} aria-disabled={disabled} data-id={props['data-id']} onBlur={onBlur} onFocus={onFocus} onKeyDown={disabled ? noop : handleKeyDown} role="slider" disabled={disabled} style={{ left: sliderLocation }} tabIndex="0" > <StyledHandleShadow disabled={disabled} /> </StyledHandle> </StyledSlider> ); } Slider.defaultProps = { min: 0, max: 100, precision: 0, }; Slider.propTypes = { /** * The slider's initial value on first render */ defaultValue: PropTypes.number, /** * Disables focus, key down, mouse and touch events */ disabled: PropTypes.bool, /** * The slider's lower bounds */ min: PropTypes.number, /** * The slider's upper bounds */ max: PropTypes.number, onBlur: PropTypes.func, onChange: PropTypes.func, onFocus: PropTypes.func, /** * The number of decimal places to round values to */ precision: PropTypes.number, /** * Generates tick marks */ ticks: PropTypes.objectOf(PropTypes.node), /** * A value to programatically control the slider */ value: PropTypes.number, /** * Describes a side-effect relationship with another DOM element */ 'aria-controls': PropTypes.string, /** * Identifier passed to the handle for testing or tracking purposes */ 'data-id': PropTypes.string, /** * System props for margin */ ...createPropTypes(margin.propNames), }; export default Slider;
var game={ RN:4, CN:4, data:null, score:0, state:0, RUNNING:1, GAMEOVER:0, getGrids:function(){ for(var r=0,arr=[];r<this.RN;r++){ for(var c=0;c<this.CN;c++){ arr.push(""+r+c); } } return '<div id="g'+arr.join('" class="grid"></div><div id="g') +'" class="grid"></div>'; }, getCells:function(){ for(var r=0,arr=[];r<this.RN;r++){ for(var c=0;c<this.CN;c++){ arr.push(""+r+c); } } return '<div id="c'+arr.join('" class="cell"></div><div id="c') +'" class="cell"></div>'; }, init:function(){ this.RN=prompt("请输入行数(1~8):"); this.CN=prompt("请输入列数(1~8):"); var out=document.getElementById("outBox"); out.style.width=115*this.CN+15+"px"; out.style.height=115*this.RN+15+"px"; out.innerHTML=this.getGrids()+this.getCells(); }, start:function(){ this.init(); this.state=this.RUNNING; this.data=[]; this.score=0; for(var r=0;r<this.RN;r++){ this.data[r]=[]; for(var c=0;c<this.CN;c++){ this.data[r][c]=0; } } this.randomNum(); this.randomNum(); console.log(this.data.join("\n")); this.updateView(); }, randomNum:function(){ if(this.isFull()==false){ while(true){ var r=parseInt(Math.random()*this.RN); var c=parseInt(Math.random()*this.CN); if(this.data[r][c]==0){ var a=Math.random(); this.data[r][c]=a<0.5?4:2; break; } } } }, isFull:function(){ for(var r=0;r<this.RN;r++){ for(var c=0;c<this.CN;c++){ if(this.data[r][c]==0){ return false; } } } return true; }, updateView:function(){ for(var r=0;r<this.RN;r++){ for(var c=0;c<this.CN;c++){ var div=document.getElementById("c"+r+c); if(this.data[r][c]!=0){ div.innerHTML=this.data[r][c]; div.setAttribute("class","cell n"+this.data[r][c]); }else{ div.setAttribute("class","cell"); div.innerHTML=""; } } } var scoreI=document.getElementById("score"); scoreI.innerHTML=this.score; var div=document.getElementById("gameover"); if(this.state==this.GAMEOVER){ div.style.display="block"; var span=document.getElementById("finalScore"); span.innerHTML=this.score; }else{ div.style.display="none"; } }, isGameOver:function(){ for(var r=0;r<this.RN;r++){ for(var c=0;c<this.CN;c++){ if(this.data[r][c]==0){ return false }else{ if((c!=this.CN-1)&&this.data[r][c]==this.data[r][c+1]){ return false; }else if((r!=this.RN-1)&&this.data[r][c]==this.data[r+1][c]){ return false; } } } } this.state=this.GAMEOVER; return false; }, zuoAll:function(){ var old=this.data.toString(); for(var r=0;r<this.RN;r++){ this.zuoYiHang(r); } var newD=this.data.toString(); if(newD!=old){ this.randomNum(); this.isGameOver(); this.updateView(); } }, zuoYiHang:function(r){ for(var c=0;c<this.CN-1;c++){ var next=this.getYouNext(r,c); if(next==-1){ break; }else{ if(this.data[r][c]==0){ this.data[r][c]=this.data[r][next]; this.data[r][next]=0; c--; }else if(this.data[r][c]==this.data[r][next]){ this.data[r][c]*=2; this.data[r][next]=0; this.score+=this.data[r][c]; } } } }, getYouNext:function(r,c){ for(var next=c+1;next<this.CN;next++){ if(this.data[r][next]!=0){ return next; } } return -1; }, youAll:function(){ var old=this.data.toString(); for(var r=0;r<this.RN;r++){ this.youYiHang(r); } var newD=this.data.toString(); if(newD!=old){ this.randomNum(); this.isGameOver(); this.updateView(); } }, youYiHang:function(r){ for(var c=this.CN-1;c>0;c--){ var prev=this.getZuoPrev(r,c); if(prev==-1){ break; }else{ if(this.data[r][c]==0){ this.data[r][c]=this.data[r][prev]; this.data[r][prev]=0; c++; }else if(this.data[r][c]==this.data[r][prev]){ this.data[r][c]*=2; this.data[r][prev]=0; this.score+=this.data[r][c]; } } } }, getZuoPrev:function(r,c){ for(var prev=c-1;prev>=0;prev--){ if(this.data[r][prev]!=0){ return prev; } } return -1; }, shangAll:function(){ var old=this.data.toString(); for(var c=0;c<this.CN;c++){ this.shangYiHang(c); } var newD=this.data.toString(); if(old!=newD){ this.randomNum(); this.isGameOver(); this.updateView(); } }, shangYiHang:function(c){ for(var r=0;r<this.RN-1;r++){ var next=this.getXiaNext(r,c); if(next==-1){break;} else{ if(this.data[r][c]==0){ this.data[r][c]=this.data[next][c]; this.data[next][c]=0; r--; }else if(this.data[r][c]==this.data[next][c]){ this.data[r][c]*=2; this.data[next][c]=0; this.score+=this.data[r][c]; } } } }, getXiaNext:function(r,c){ for(var next=r+1;next<this.RN;next++){ if(this.data[next][c]!=0){ return next; } } return -1; }, xiaAll:function(){ var old=this.data.toString(); for(var c=0;c<this.CN;c++){ this.xiaYiHang(c); } var newD=this.data.toString(); if(newD!=old){ this.randomNum(); this.isGameOver(); this.updateView(); } }, xiaYiHang:function(c){ for(var r=this.RN-1;r>0;r--){ var prev=this.getShangPrev(r,c); if(prev==-1){break;} else{ if(this.data[r][c]==0){ this.data[r][c]=this.data[prev][c]; this.data[prev][c]=0; r++; }else if(this.data[r][c]==this.data[prev][c]){ this.data[r][c]*=2; this.data[prev][c]=0; this.score+=this.data[r][c]; } } } }, getShangPrev:function(r,c){ for(var prev=r-1;prev>=0;prev--){ if(this.data[prev][c]!=0){ return prev; } } return -1; } } window.onload=function(){ game.start(); /*document.onkeydown=function(){ if(game.state==game.RUNNING){ var e=window.event||arguments[0]; if(e.keyCode==37){ game.zuoAll(); }else if(e.keyCode==39){ game.youAll(); }else if(e.keyCode==38){ game.shangAll(); }else if(e.keyCode==40){ game.xiaAll(); } } }*/ document.getElementById("up").onclick=function(){game.shangAll()}; document.getElementById("down").onclick=function(){game.xiaAll()}; document.getElementById("left").onclick=function(){game.zuoAll()}; document.getElementById("right").onclick=function(){game.youAll()}; }
const express = require('express') const routes = express.Router() const { getAllDrinks, getDrink, getDrinksBySupplier } = require('../actions/drinks') routes.get('/drinks', (req, res) => { return getAllDrinks() .then((drinks) => { res.send(drinks) }) .catch(console.error) }) routes.get('/drinks/:id', (req, res) => { return getDrink(req.params.id) .then((drinkDetails) => { res.send(drinkDetails) }) .catch(console.error) }) routes.get('/drinks/supplier/:supplierName', (req, res) => { return getDrinksBySupplier(req.params.supplierName) .then((supplierDrinks) => { res.send(supplierDrinks) }) .catch(console.error) }) module.exports = routes
import React from "react"; import "./CenterLine.css"; const CenterLine = props => <div className="box col-8">{props.children}</div>; export default CenterLine;
app.config(function ($stateProvider) { $stateProvider.state('home', { url: '/', templateUrl: 'js/home/home.html', controller: 'HomeController' }); }); app.controller('HomeController', function ($rootScope, $scope, $state, AuthService, AUTH_EVENTS, ToneFactory, keyConfigFactory, SexyBackFactory) { $scope.user = null; $('.homeMenu').click( function (e) { e.stopPropagation(); e.preventDefault(); e.stopImmediatePropagation(); }); var setUser = function () { AuthService.getLoggedInUser().then(function (user) { $scope.user = user; }); }; var removeUser = function () { $scope.user = null; }; setUser(); $rootScope.$on(AUTH_EVENTS.loginSuccess, setUser); $rootScope.$on(AUTH_EVENTS.logoutSuccess, removeUser); (function landingPageAnimation() { SexyBackFactory.init(); })(); function play(fx) { ToneFactory.play(fx); }; var $document = $(document); $document.on('keydown', onArrowKey); window.addEventListener('gamepadbuttondown', onArrowKey); $document.on('keydown', moveArrows); window.addEventListener('gamepadbuttondown', moveArrows); $document.on('keyup', replaceArrows); window.addEventListener('gamepadbuttonup', replaceArrows); var arrows = { left: { el: $('.arrow-keys .left img')[0], dir: "left", start: "0", end: "-20px" }, right: { el: $('.arrow-keys .right img')[0], dir: "left", start: "0", end: "20px" }, down: { el: $('.arrow-keys .down img')[0], dir: "top", start: "0", end: "20px" }, up: { el: $('.arrow-keys .up img')[0], dir: "top", start: "0", end: "-20px" }, enter: { el: $('#home .enter img')[0], dir: "top", start: "0", end: "20px" }, }; function moveArrows (e) { var button = keyConfigFactory.getButton(e); if (!button) return; var a = arrows[button.name]; if (!a) return; a.el.style[a.dir] = a.end; a.el.style['-webkit-filter'] = "grayscale(1) brightness(200%)"; } function replaceArrows (e) { var button = keyConfigFactory.getButton(e); if (!button) return; var a = arrows[button.name]; if (!a) return; a.el.style[a.dir] = a.start; a.el.style['-webkit-filter'] = ""; } function onArrowKey(event) { var button = keyConfigFactory.getButton(event); if (!button) return; if (button.name === 'enter') { SexyBackFactory.pause(); play('start'); $document.off('keydown', onArrowKey); window.removeEventListener('gamepadbuttondown', onArrowKey); $document.off('keydown', moveArrows); window.removeEventListener('gamepadbuttondown', moveArrows); $document.off('keydown', replaceArrows); window.removeEventListener('gamepadbuttondown', replaceArrows); $state.go('mainMenu'); }; }; function logout() { AuthService.logout().then(function () { setUser(); }); }; });
import styled from 'styled-components' import logoChrome from '../../../images/logo-chrome.svg'; import logoFirefox from '../../../images/logo-firefox.svg'; import logoOpera from '../../../images/logo-opera.svg'; import Card from './Card/Card'; const cards = [ { id: 1, browser: 'Chrome', logo: logoChrome, version: 62 }, { id: 2, browser: 'Firefox', logo: logoFirefox, version: 55 }, { id: 3, browser: 'Opera', logo: logoOpera, version: 46 }, ]; const CardsContainer = styled.div` display: flex; flex-direction: column; margin: auto; margin-top: 40px; @media (min-width: 280px) { width: 90%; } @media (min-width: 992px) { width: 100%; margin-top: 100px; flex-direction: row; justify-content: center; } `; function Cards() { return ( <CardsContainer> {cards.map((card) => ( <Card key={card.id} logo={card.logo} browser={card.browser} version={card.version} /> ))} </CardsContainer> ) } export default Cards;
var searchData= [ ['call',['call',['../struct_s_k_e_l___fxns.html#ab2dcf212fdf13134020ff2fd607a5dc2',1,'SKEL_Fxns']]], ['cmd',['cmd',['../struct_v_i_s_a___msg_header.html#a6c989b8f8016b9a1d2a90fc8fc9529f9',1,'VISA_MsgHeader']]], ['codecclassconfig',['codecClassConfig',['../struct_engine___alg_desc.html#aab82593192bd4b3713326e09e5d2107a',1,'Engine_AlgDesc::codecClassConfig()'],['../struct_engine___dll_alg_desc.html#a33d33c5835fb156eeaab3a5fae9af638',1,'Engine_DllAlgDesc::codecClassConfig()']]] ];
"use strict"; const moment = require("moment"); const express = require('express'); const app = express(); const port = 3000; const person = require('./controllers/person.js'); app.set('view engine', 'ejs'); (async () => { await person.table(); })() app.use((req, res, next) => { moment.locale('pt-br') res.locals.moment = moment; next(); }); app.get('/', async (req, res) => { await person.insert(req.query.name); const usersList = await person.get(); res.render('index', { usersList }); }); app.listen(port, () => { console.log(`App listening at http://localhost:${port}`); });
'use strict'; const webpack = require("webpack"); const webpackConfig = require('./webpack.config.js'); const webpackStats = require('./webpack.stats.js'); async function pack() { console.log(`Packing ...`); // initialize the compiler: let compiler; try { compiler = webpack(webpackConfig); } catch (error) { console.error(`Webpack error: ${error.message} (${error.name})`); error.validationErrors.forEach((verr) => console.error(verr)); return -1; } // run the compiler: const stats = await new Promise((resolve, reject) => { compiler.run((error, stats) => { if (error) { console.error('# Pack failed:'); console.error(error.stack || error); if (error.details) { console.error(error.details); } if (error.missing) { console.error(`- missing:\n`, error.missing); } reject(error); } else { resolve(stats); } }); }); // Log errors/warnings/stats: console.log(stats.toString(webpackStats)); } pack();
var express = require("express"), app = express(), path = require('path'), ejs = require('ejs'), request = require('request'), config = require('./config/config'); var options = { url: 'https://www.blueapron.com/api/users/orders/upcoming?include_wine=false', headers: config.api }; app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.static(path.join(__dirname, 'app'))); app.get('/', function(req, res) { res.render('index'); }); app.get('/recipes', function(req, res) { res.render('index'); }); app.get('/palette', function(req, res) { res.render('index'); }); app.get('/api/recipes', function(req, res) { app.curl(function(json) { var response = app.parseRecipes(json); res.send(response); }); }); app.parseRecipes = function(json) { var recipes = []; json.orders.forEach(function(order, key) { order.recipes.forEach(function(recipe) { delete recipe.product_pairings; recipes.push(recipe); }); }); return recipes; }; app.curl = function(cb) { request(options, function(error, response, body) { if(!error && response.statusCode === 200) { var json = JSON.parse(body); cb(json); } else { cb({"error": error, "code": response.statusCode, "message": response.statusMessage}); } }); }; app.listen(process.env.PORT || 5000, function() { console.log("Listening on port "+ this.address().port); });
var users = require('../controllers/user.server.controller'); var authorization = require('../controllers/authorization.server.controller'); module.exports = function(app) { // Create a new user app.post('/api/users', users.create); // Authenticate a user app.post('/api/users/authenticate', users.authenticate); // Find one user app.get('/api/users/:userId', authorization.requiresLogin, users.findOne); // update an existing user app.put('/api/users/:userId', authorization.requiresLogin, users.update); // Find all users app.get('/api/users', authorization.requiresAdmin, users.findAll); // Delete a user app.delete('/api/users/:userId', authorization.requiresAdmin, users.delete); app.get('/api/check', users.check); };
function displayAccount() { document.getElementById("changeableText").innerHTML = "Account Settings"; } function displayPrivacy() { document.getElementById("changeableText").innerHTML = "Privacy Settings"; } function displayLanguage() { document.getElementById("changeableText").innerHTML = "Language Settings"; } function displayAccessibility() { document.getElementById("changeableText").innerHTML = "Accessibility Settings"; } function displayTerms() { document.getElementById("changeableText").innerHTML = "Terms and Conditions"; }
function myRemoveWithoutCopy(arr, item) { for (let i = 0, len = arr.length; i < len; i += 1) { if (arr[i] === item) { arr.splice(i, 1); i -= 1; len -= 1; } } return arr; } const list = [1, 2, 3, 4] const expected = myRemoveWithoutCopy(list, 3) test('Has undergone changes', () => { expect(list).toEqual([1, 2, 3, 4]); })
var apiEndpoint = 'https://jsonplaceholder.typicode.com/todos/1' var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { var responseObject = JSON.parse(this.responseText); console.log("Response from jsonplaceholder API"); console.log(responseObject); } }; xhttp.open("GET", apiEndpoint, true); xhttp.send(); var fruits = ["Banana", "Orange", "Apple", "Mango"]; console.log("Fruits Array:", fruits); console.log("Pushing..."); fruits.push("Apricot"); console.log("New Fruits Array:", fruits); console.log("Shifting..."); fruits.shift(); console.log("New Fruits Array:", fruits); console.log("Poping..."); fruits.pop(); console.log("New Fruits Array:", fruits); console.log("Unshifting...") fruits.unshift("Melon"); console.log("New Fruits Array:", fruits); console.log("Slicing..."); var fruits_first = fruits.slice(0, 2); var fruits_last = fruits.slice(2); console.log("First New Fruits Array:", fruits_first); console.log("Second New Fruits Array:", fruits_last); console.log("Concating..."); fruits = fruits_last.concat(fruits_first) console.log("Prettified New Fruits Array:", fruits.join(" * "));
const { Roles } = require('../../../data/models'); module.exports = (req, res, next) => { const { roleId } = req.body; console.log(roleId) Roles .findBy({ 'roles.id': roleId }) .then(role => { console.log(role) if (role.length) { next(); } else { res.status(404).json({ message: 'role id does not exist' }); } }) .catch(error => res.status(500).json({ error: error.message, step: 'checkRoleExists' })); }
import Ember from 'ember'; import RevealPresentation from 'ember-reveal-js/controllers/reveal-presentation'; const { set } = Ember; export default RevealPresentation.extend({ presentation() { let viewRegistry = this.container.lookup('-view-registry:main'); // for < 1.12.0 support if (!viewRegistry) { viewRegistry = Ember.View.views; } return viewRegistry.demoPresentation; }, actions: { setTheme(theme) { set(this.presentation(), 'theme', theme); } } });
import React from 'react'; import useWindowEvent from './useWindowEvent'; import { getRectFor } from '../helpers/geometry'; import { getWindow } from '../helpers/window'; /** * Reusable hook that returns true when element is scrolled into view * * @param {Boolean} once // defaults to true. If set to false the inView param will change when the element is scrolled into and out of view * * @example * const [ref, inView] = useInView({ once: false }); * return <div>{inView ? 'In View' : 'Not In View'}</div> * */ function useInView({ offset = 0, once = true } = {}) { const [node, setNode] = React.useState(null); const [inView, setInView] = React.useState(false); const [scroll, setScroll] = React.useState(0); const [rect, setRect] = React.useState({}); const environment = getWindow(); useWindowEvent('scroll', () => { setScroll(environment.scrollY); }); React.useEffect(() => { setRect(getRectFor(node)); }, [node]); React.useLayoutEffect(() => { const { top, height } = rect; const { innerHeight } = environment; if (top) { if (scroll >= top + offset - innerHeight) { setInView(true); } if (scroll > top + height || scroll < top - innerHeight) { if (!once) { setInView(false); } } } }, [scroll]); return [setNode, inView]; } export default useInView;
import React, { useContext } from 'react'; import LoginPage from './login'; import AuthContext from '../store/auth-context'; import HomePage from './home'; const Home = () => { const authCtx = useContext(AuthContext); return <>{authCtx.isLoggedIn ? <HomePage /> : <LoginPage />}</>; }; export default Home;
function genSiteURL(path) { return ROOT_URL + path; } function genMediaURL(path) { return ROOT_URL + path; } function genStaticURL(path) { return S3_URL + path; } const URLService = { genSiteURL, genMediaURL, genStaticURL }; export default URLService;
module.exports = input => { let grid = []; let gates = new Map(); let portals = new Map(); input.split('\r\n').forEach((row, y) => { grid[y] = row.split(''); }); const letter = (x, y) => grid[y] && grid[y][x] && grid[y][x].match('[A-Z]'); const get = (x, y) => grid[y] && grid[y][x] ? grid[y][x] : ' '; const parse = id => id.split('#').map(Number); const id = (x, y, level) => `${x}#${y}#${level}`; const port = (x, y, dx, dy, level) => { if (letter(x + dx, y + dy) && back.get(id(x, y)) != 'AA' && back.get(id(x, y)) != 'ZZ') { let [x2, y2] = parse(portals.get(id(x, y))); let offset = (y2 == 2 || x2 == 2 || y2 == grid.length - 3 || x2 == grid[0].length - 3) ? 1 : -1; if (offset == 1 || level != 0) { return [x2, y2, level + offset]; } } return [x + dx, y + dy, level]; } const identify = (x, y, dx, dy) => { if (letter(x, y)) { if (letter(x + dx, y + dy) && get(x + dx * 2, y + dy * 2) == '.') { let name = get(x, y) + get(x + dx, y + dy); gates.set(name, gates.get(name) || new Set()); gates.get(name).add(id(x + dx * 2, y + dy * 2)); } if (letter(x + dx, y + dy) && get(x - dx, y - dy) == '.') { let name = get(x, y) + get(x + dx, y + dy); gates.set(name, gates.get(name) || new Set()); gates.get(name).add(id(x - dx, y - dy)); } } } const next = (x, y, dx, dy, level, dist) => { let [x2, y2, level2] = port(x, y, dx, dy, level); return [[x2, y2], dist + 1, level2]; } for (let y = 0; y < grid.length; y++) { for (let x = 0; x < grid[y].length; x++) { identify(x, y, 0, 1); identify(x, y, 0, -1); identify(x, y, 1, 0); identify(x, y, -1, 0); } } let back = new Map(); [...gates.entries()].forEach(([k, v]) => { for (let a of v) { back.set(a, k); } }); for (let v of gates.values()) { if (v.size == 2) { let [a, b] = [...v]; portals.set(a, b); portals.set(b, a); } } let start = parse([...gates.get('AA')][0]); let goal = parse([...gates.get('ZZ')][0]); let queue = [[start, 0, 0]]; let visited = new Set(); while (queue.length) { let [p, dist, level] = queue.shift(); let [x, y] = p; if (visited.has(id(x, y, level))) { continue; } if (get(x, y) == '#' || letter(x, y)) { continue; } if (x == goal[0] && y == goal[1] && level == 0) { return dist; } queue.push(next(x, y, 0, 1, level, dist)); queue.push(next(x, y, 0, -1, level, dist)); queue.push(next(x, y, 1, 0, level, dist)); queue.push(next(x, y, -1, 0, level, dist)); visited.add(id(x, y, level)); } }
import React, { Component } from 'react'; import '../stylesheets/project.css'; import PropTypes from 'prop-types'; export default class Project extends Component{ static propTypes = { title: PropTypes.string.isRequired, img: PropTypes.string.isRequired, alt: PropTypes.string.isRequired, src: PropTypes.string.isRequired, id: PropTypes.string.isRequired, about: PropTypes.arrayOf(PropTypes.string).isRequired } render(){ const {title, img, alt, src, id} = this.props const about = this.props.about.map((item, index)=>( <li className="projectLI" key={index}>{item}</li> )) return ( <div className="demo"> <a target= "_blank" href = {src}><img srcSet= {img} alt={alt} id={id}/></a> <h2 className="name">{title}</h2> <ul className="projectUL"> {about} </ul> </div> ) } } //IMPORTANT- when using an array method, each item in the array must be assigned a unique key for React's rendering //in this case we'll just use the index but keep in mind this is not good practice if array may change //the props passed in using spread operator can be accessed by using just this.props.eachOne //we DO need to set the passed in props equal to a variable in order to use them, //otherwise we would have to use this.props.eachOne
import React,{useContext} from 'react' import {dataApi } from '../contexApi/dataContex' export const Alert = () => { const { alerts } = useContext( dataApi ) console.log(alerts) return ( alerts !== null && alerts.length > 0 && alerts.map(alert => <div key={alert.id} className={`alert alert-${alert.alertType}`}> {alert.msg} </div> ) ) } export default Alert;
$(function () { (function () { var ulobj = $(".show-list-con ul"); var picimg = $(".introShow .show-pic img"); var objimg = $(".introShow .show-shadow img"); ulobj.on("mouseenter", "li", function () { var imgsrc = $(this).children("img").attr("src"); $(this).addClass("active").siblings().removeClass("active"); picimg.attr("src", imgsrc); objimg.attr("src", imgsrc); }); $('.i_lift').click(function(){ var imgsrc = $('.imageul .active').prev().children("img").attr("src"); $('.imageul .active').prev().addClass("active").siblings().removeClass("active"); picimg.attr("src", imgsrc); objimg.attr("src", imgsrc); if($('.imageul .active').index()==0){ var llength=$('.imageul li').length; // console.log(llength); var imgsrc = $('.imageul li').eq(0).children("img").attr("src"); $('.imageul li').eq(llength-1).addClass("active").siblings().removeClass("active"); picimg.attr("src", imgsrc); objimg.attr("src", imgsrc); } // console.log($('.imageul .active').index()); }); $('.i_right').click(function(){ var imgsrc = $('.imageul .active').next().children("img").attr("src"); $('.imageul .active').next().addClass("active").siblings().removeClass("active"); picimg.attr("src", imgsrc); objimg.attr("src", imgsrc); if($('.imageul .active').index()==3){ var llength=$('.imageul li').length; // console.log(llength); var imgsrc = $('.imageul li').eq(0).children("img").attr("src"); $('.imageul li').eq(0).addClass("active").siblings().removeClass("active"); picimg.attr("src", imgsrc); objimg.attr("src", imgsrc); } // console.log($('.imageul .active').prev().index()); }); var pic = $(".introShow .show-pic"); var magnify = $(".introShow .show-pic .magnify"); var bigpic = $(".introShow .show-shadow"); var objimg = $(".introShow .show-shadow img"); pic.mousemove(function (e) { magnify.show(); bigpic.show(); var pagex = e.pageX; var pagey = e.pageY; var pictop = pic.offset().top; var picleft = pic.offset().left; var magnifyw = magnify.width(); var magnifyh = magnify.height(); var magnifytop = pagey - pictop - magnifyh / 2; var magnifyleft = pagex - picleft - magnifyw / 2; var picw = pic.width() - magnifyw; var pich = pic.height() - magnifyh; magnifytop = magnifytop < 0 ? 0 : magnifytop; magnifyleft = magnifyleft < 0 ? 0 : magnifyleft; magnifytop = magnifytop > pich ? pich : magnifytop; magnifyleft = magnifyleft > picw ? picw : magnifyleft; magnify.css({ top: magnifytop, left: magnifyleft }); var minl = bigpic.width() - objimg.width(); var mint = bigpic.height() - objimg.height(); var objimgl = -magnifyleft * 2; var objimgt = -magnifytop * 2; objimgl = objimgl < minl ? minl : objimgl; objimgt = objimgt < mint ? mint : objimgt; objimg.css({ top: objimgt, left: objimgl }) }); pic.mouseleave(function () { magnify.hide(); bigpic.hide() }) })() });
$(document).ready(function() { $('input[name=TYP]').focus(); //$('#myModal').on('shown.bs.modal', function () { //$('#iframePracownicy').focus(); //}); }); function valid($name,$validType) { $value=$('input[name='+$name+']').val(); $params='val='+$value+'&validType='+$validType; $('input[name='+$name+']').load("valid.php",$params,function(){ $wynik=$(this).html(); if ($(this).parent().prev().css('color')=='rgb(255, 0, 0)') { $(this).attr("title",""); $(this).tooltip("destroy"); $(this).parent().prev().css('font-weight', '').css('color', ''); $(this).css('font-weight', '').css('color', ''); $('#button_Enter').prop('disabled',false); $('#button_Enter').show(); } if ($wynik.substr(0,4)=='brak') { $(this).attr("title",'<font style="font-size:12pt">'+$wynik+'</font>'); $(this).tooltip({placement: "top", html: true}).tooltip("show"); $(this).parent().prev().css('font-weight', 'bold').css('color', 'red'); $(this).css('font-weight', 'bold').css('color', 'red'); $('#button_Enter').prop('disabled',true); $('#button_Enter').hide(); $wynik=$value; } $(this).val($wynik); }); return true; }
import { takeEvery, takeLatest, delay } from 'redux-saga' import { call, put, select } from 'redux-saga/effects' import { loginWithPasswordFail, logoutFail, loginWithPasswordSuccess, logoutSuccess, setToken } from '@actions/login' import { LOGIN_WITH_PASSWORD_REQUEST, LOGOUT_REQUEST, WRITE_TOKEN_TO_STORAGE, READ_TOKEN_FROM_STORAGE, CLEAR_TOKEN_FROM_STORAGE} from '@actionTypes/login' import { NavigationActions } from '@exponent/ex-navigation' import { AsyncStorage } from 'react-native' function* readTokenFromStorageHandler() { try { const token = yield AsyncStorage.getItem('token') if (token) { yield put(setToken(token)) } } catch (e) { console.log(e) } } function* clearTokenFromStorageHandler() { try { yield AsyncStorage.removeItem('token') yield put(setToken(null)) } catch (e) { console.log(e) } } function* writeTokenToStorageHandler(action) { try { yield AsyncStorage.setItem('token', action.payload.token) yield put(setToken(action.payload.token)) } catch (e) { console.log(e) } } function* loginWithPasswordHandler(action) { try { yield call(delay, 1000) // const navigatorUID = yield select(state => { // return state.navigation.currentNavigatorUID // }) // yield put(NavigationActions.push(navigatorUID, Router.getRoute('main'))) yield put(loginWithPasswordSuccess('abc')) } catch (e) { console.log(e) const error = new Error(e.error) yield put(loginWithPasswordFail(error)) } } function* logoutHandler(action) { try { yield call(delay, 1000) // const navigatorUID = yield select(state => state.navigation.currentNavigatorUID) // yield put(NavigationActions.popToTop(navigatorUID, Router.getRoute('login'))) yield put(logoutSuccess()) } catch (e) { console.log(e) const error = new Error(e.error) yield put(logoutFail(error)) } } export default function* saga() { yield takeLatest(LOGIN_WITH_PASSWORD_REQUEST, loginWithPasswordHandler) yield takeLatest(LOGOUT_REQUEST, logoutHandler) yield takeLatest(WRITE_TOKEN_TO_STORAGE, writeTokenToStorageHandler) yield takeLatest(READ_TOKEN_FROM_STORAGE, readTokenFromStorageHandler) yield takeLatest(CLEAR_TOKEN_FROM_STORAGE, clearTokenFromStorageHandler) }
import React, {Component} from 'react'; class FoodDetail extends Component { render(){ console.log(this.props.item.image); return( <div className="detailsContainer"> <div className="imageContainer"> <img src={this.props.item.image} alt="Food_image" className="foodImg"/> </div> <div className="descContainer"> <p className="foodName">{this.props.item.name}</p> <div dangerouslySetInnerHTML={{ __html: this.props.item.description }} /> <hr/> {this.props.items.nonVeg ? <span className="foodTypeNV">Non-Veg</span> : ""} {this.props.items.spicy ? <span className="foodTypeSpicy">Spicy</span> : ""} </div> </div> ); } } export default FoodDetail;
var compmbox_2compress_8c = [ [ "mutt_comp_init", "compmbox_2compress_8c.html#a8440ad71a5e3d43cd2c836c777bccded", null ], [ "lock_realpath", "compmbox_2compress_8c.html#a8c82fa05ac9a30a1cd0e5c5b472ae066", null ], [ "unlock_realpath", "compmbox_2compress_8c.html#aa35e239a0ed2772ae5824c317276f83a", null ], [ "setup_paths", "compmbox_2compress_8c.html#a60e1b3c821fbb441941a42b24149fbb3", null ], [ "store_size", "compmbox_2compress_8c.html#a877acb05482802a48bc56da5e24c8c54", null ], [ "set_compress_info", "compmbox_2compress_8c.html#a958dff103de14a95ce0a8a5dd977167b", null ], [ "compress_info_free", "compmbox_2compress_8c.html#a5ae987f4dda46e1423fedf6a0ac0b2de", null ], [ "compress_format_str", "compmbox_2compress_8c.html#a804a1a638527ebaddb0d693ec35d5198", null ], [ "expand_command_str", "compmbox_2compress_8c.html#abec93f40f46e453d46cb9d7181ae39f9", null ], [ "execute_command", "compmbox_2compress_8c.html#a77600af8755fc3921168f6c0727abf18", null ], [ "mutt_comp_can_append", "compmbox_2compress_8c.html#a9f3c7362d3b06ea8c32ce55d5c3db5f1", null ], [ "mutt_comp_can_read", "compmbox_2compress_8c.html#af5e4caf583046a535cf5fda9933d3c74", null ], [ "mutt_comp_valid_command", "compmbox_2compress_8c.html#ab77ea42f102d3aced8ea915e95a83bd4", null ], [ "comp_ac_find", "compmbox_2compress_8c.html#a5a72d9df3a0aeedccf7bd6ac0fb4e12b", null ], [ "comp_ac_add", "compmbox_2compress_8c.html#ab1af5dae348409b32251325a3c91d890", null ], [ "comp_mbox_open", "compmbox_2compress_8c.html#a7ad6d8fff1d3afeb0ff6b88263a99725", null ], [ "comp_mbox_open_append", "compmbox_2compress_8c.html#a5c3fd55d08b7899a9010df6088a3c1ce", null ], [ "comp_mbox_check", "compmbox_2compress_8c.html#aacc5514861dae8839d75317159500fcb", null ], [ "comp_mbox_sync", "compmbox_2compress_8c.html#a186f83caeb64abb53f83cdf0e7811972", null ], [ "comp_mbox_close", "compmbox_2compress_8c.html#a616221215cd9a4dd6d750ae4235553ff", null ], [ "comp_msg_open", "compmbox_2compress_8c.html#a1570c091fe68f805495bcdd1c457b47a", null ], [ "comp_msg_open_new", "compmbox_2compress_8c.html#a8ee2e7c8c528fd5338663badb7763d45", null ], [ "comp_msg_commit", "compmbox_2compress_8c.html#a449d225488040512f5696e4f76f36694", null ], [ "comp_msg_close", "compmbox_2compress_8c.html#a9cedad82abc13c823ff2d0e7bc1b66f9", null ], [ "comp_msg_padding_size", "compmbox_2compress_8c.html#a0e6812b4bba1845ea248f4df93c06fea", null ], [ "comp_msg_save_hcache", "compmbox_2compress_8c.html#ac329588156f6dfd55072cc812ff043cd", null ], [ "comp_tags_edit", "compmbox_2compress_8c.html#a6baf16b10893271190480d29fbc8b493", null ], [ "comp_tags_commit", "compmbox_2compress_8c.html#a1c0b7ffa4578c0b91fda494e873f13e7", null ], [ "comp_path_probe", "compmbox_2compress_8c.html#ad886126ad1805be0c69f9b2fe138db10", null ], [ "comp_path_canon", "compmbox_2compress_8c.html#afc352b335c9a8dd1d6e89bcc566dba80", null ], [ "comp_path_pretty", "compmbox_2compress_8c.html#a164a2844f1899843274d6c80a194ca86", null ], [ "comp_path_parent", "compmbox_2compress_8c.html#ab807f84b5a28020a4250500f9fa7463c", null ], [ "comp_commands", "compmbox_2compress_8c.html#a08818c1789d0341db65745d36f50f1b3", null ], [ "MxCompOps", "compmbox_2compress_8c.html#a69f737b0581952c0ef57f37af78ac6c7", null ] ];
const req = require('./req'); const ipad = require('./ipad'); const usd = require('./usd'); const year = require('./year'); module.exports = { req, ipad, usd, year };
exports.seed = function(knex, Promise) { // Deletes ALL existing entries return knex('users').del() .then(function () { // Inserts seed entries return knex('users').insert([ {firstname: 'user', lastname: 'one', email:'one.user@email.com', password: 'user1'}, {firstname: 'user', lastname: 'two', email:'two.user@email.com', password: 'user2'}, {firstname: 'user', lastname: 'three', email:'three.user@email.com', password: 'user3'}, ]); }); };
import React from 'react' import PropTypes from 'prop-types' import Todo from './Todo.js' const TodoLists = ({ todoList = [], onTodoClick }) => ( <ul> { todoList.map(d => ( <Todo key={d.id} text={d.text} completed={d.completed} onClick={ () => onTodoClick(d.id) }/> )) } </ul> ) TodoLists.propTypes = { todoList: PropTypes.array.isRequired, onTodoClick: PropTypes.func.isRequired } export default TodoLists
import _ from 'lodash'; import AccessibilityModule from '@curriculumassociates/createjs-accessibility'; import Article from './Article'; import Button from './Button'; import ComboBox from './ComboBox'; import Img from './Img'; import ListBox from './ListBox'; import Link from './Link'; import ListItem from './ListItem'; import MenuBar from './MenuBar'; import Menu from './Menu'; import MenuItem from './MenuItem'; import MenuItemCheckBox from './MenuItemCheckBox'; import MenuItemRadio from './MenuItemRadio'; import MultiListBox from './MultiListBox'; import Option from './Option'; import OrderedList from './OrderedList'; import SingleLineTextInput from './SingleLineTextInput'; import MultiLineTextInput from './MultiLineTextInput'; import CheckBox from './CheckBox'; import Search from './Search'; import RadioGroup from './RadioGroup'; import Draggable from './Draggable'; import Slider from './Slider'; import Table from './Table'; import Switch from './Switch'; import Tooltip from './Tooltip'; import ProgressBar from './ProgressBar'; import Figure from './Figure'; import SpinButton from './SpinButton'; import Grid from './Grid'; import Tree from './Tree'; import TreeItem from './TreeItem'; import Separator from './Separator'; import Dialog from './Dialog'; import ScrollBar from './ScrollBar'; import ToolBar from './ToolBar'; import TabList from './TabList'; import Tab from './Tab'; import TabPanel from './TabPanel'; import Feed from './Feed'; import TreeGrid from './TreeGrid'; import FormatText from './FormatText'; import AlertDialog from './AlertDialog'; import Marquee from './Marquee'; import PlainTextMath from './PlainTextMath'; import imgTestSrc from './media/Curriculum-Associates-Logo-964x670.png'; import formulaImg1 from './media/formula1.png'; import formulaImg2 from './media/formula2.png'; const MENU_HEIGHT = 20; const OPTION_WIDTH = 115; const OPTION_HEIGHT = 18; const HEADER_HEIGHT = 34; const FOOTER_HEIGHT = 30; export default class AppWindow extends createjs.Container { constructor(width, height) { super(); _.bindAll( this, '_showDefaultScreen', '_showFormTestCase', '_showLinkTestCase', '_showDragAndDropTestCase', '_showTableTestCase', '_showTabListWithPanelCase', '_showAboutDialog', '_showListTestCase', '_showArticleTestCase', '_showCheckBoxTestCase', '_showSearchTestCase', '_showSliderTestCase', '_showMenuItemCheckBoxTestCase', '_showMenuItemRadioTestCase', '_showRadioGroupAndProgressBarTestCase', '_showGridTestCase', '_showTreeTestCase', '_showFeedTestCase', '_showTreeGridTestCase', '_showTextFormatCase', '_mathTextCase' ); AccessibilityModule.register({ displayObject: this, role: AccessibilityModule.ROLES.NONE, }); this._headerArea = new createjs.Container(); this.addChild(this._headerArea); AccessibilityModule.register({ displayObject: this._headerArea, role: AccessibilityModule.ROLES.BANNER, }); this.accessible.addChild(this._headerArea); const headerText = new createjs.Text( 'Createjs Accessibility Test APP', 'bold 32px Arial', '#000' ); this._headerArea.addChild(headerText); AccessibilityModule.register({ displayObject: headerText, role: AccessibilityModule.ROLES.HEADING1, accessibleOptions: { text: headerText.text, }, }); this._headerArea.accessible.addChild(headerText); this._headerArea.accessible.title = 'Createjs Accessibility Test APP'; this._headerArea.accessible.lang = 'en'; this._headerArea.setBounds(0, 0, 800, HEADER_HEIGHT); headerText.lineWidth = 800; const bannerBounds = this._headerArea.getBounds(); headerText.x = bannerBounds.width * 0.5 - headerText.getBounds().width * 0.5; headerText.y = bannerBounds.height * 0.5 - headerText.getBounds().height * 0.5; const headerBG = new createjs.Shape(); headerBG.graphics .beginFill('#808080') .drawRect(0, 0, bannerBounds.width, bannerBounds.height); this._headerArea.addChildAt(headerBG, 0); this._createMenu(width, height); this._contentArea = new createjs.Container(); this._contentArea.y = HEADER_HEIGHT + MENU_HEIGHT; this._contentArea.setBounds( 0, 0, width, height - (MENU_HEIGHT + HEADER_HEIGHT + FOOTER_HEIGHT) ); this.addChild(this._contentArea); AccessibilityModule.register({ displayObject: this._contentArea, parent: this, role: AccessibilityModule.ROLES.MAIN, }); this._footerArea = new createjs.Container(); this.addChild(this._footerArea); AccessibilityModule.register({ displayObject: this._footerArea, role: AccessibilityModule.ROLES.CONTENTINFO, }); this.accessible.addChild(this._footerArea); this._footerArea.setBounds(0, 0, width, FOOTER_HEIGHT); const contentinfo = new createjs.Text( 'This webapp uses the ISC license', 'bold 18px Arial', '#000' ); this._footerArea.addChild(contentinfo); AccessibilityModule.register({ displayObject: contentinfo, role: AccessibilityModule.ROLES.HEADING3, accessibleOptions: { text: contentinfo.text, }, }); this._footerArea.accessible.addChild(contentinfo); contentinfo.lineWidth = width; const footerBounds = this._footerArea.getBounds(); contentinfo.x = footerBounds.width * 0.5 - contentinfo.getBounds().width * 0.5; contentinfo.y = footerBounds.height * 0.5 - contentinfo.getBounds().height * 0.5; const footerBG = new createjs.Shape(); footerBG.graphics .beginFill('#808080') .drawRect(0, 0, footerBounds.width, footerBounds.height); this._footerArea.addChildAt(footerBG, 0); this._footerArea.y = this._contentArea.y + this._contentArea.getBounds().height; const currentTime = new createjs.Container(); this._footerArea.addChild(currentTime); AccessibilityModule.register({ displayObject: currentTime, role: AccessibilityModule.ROLES.NONE, }); this._footerArea.accessible.addChildAt(currentTime, 0); const timeLabel = new createjs.Text('Elapsed time: ', 'bold 18px Arial'); AccessibilityModule.register({ displayObject: timeLabel, role: AccessibilityModule.ROLES.SPAN, accessibleOptions: { text: timeLabel.text, }, }); currentTime.addChild(timeLabel); currentTime.accessible.addChild(timeLabel); const startTime = Date.now(); const timer = new createjs.Text('0 seconds', 'bold 18px Arial'); timer.x = timeLabel.getBounds().width; currentTime.addChild(timer); AccessibilityModule.register({ displayObject: timer, role: AccessibilityModule.ROLES.TIMER, accessibleOptions: { text: timer.text, }, }); currentTime.accessible.addChild(timer); currentTime.accessible.dir = 'ltr'; currentTime.x = 10; currentTime.y = 5; const updateTime = () => { const ellapsedSeconds = Math.floor((Date.now() - startTime) / 1000); timer.text = `${ellapsedSeconds} seconds`; timer.accessible.text = timer.text; }; setInterval(updateTime, 1000); this._showDefaultScreen(); this.createGrid(); } _createMenu(width) { this.nav = new createjs.Container(); this.addChild(this.nav); AccessibilityModule.register({ displayObject: this.nav, parent: this, role: AccessibilityModule.ROLES.NAVIGATION, }); this.nav.y = this._headerArea.getBounds().height; this._menuBar = new MenuBar(width, MENU_HEIGHT, 'Test case selector'); this.nav.addChild(this._menuBar); this.nav.accessible.addChild(this._menuBar); const testCasesMenu = new Menu('Test Cases', MENU_HEIGHT, 0, 'T'); this._menuBar.addMenu(testCasesMenu); const testCasesGroup = { group1: { ClassRef: MenuItem, testCases: [ { name: 'Default', listener: this._showDefaultScreen }, { name: 'Form', listener: this._showFormTestCase }, { name: 'Drag and drop', listener: this._showDragAndDropTestCase }, { name: 'Table', listener: this._showTableTestCase }, { name: 'TabList With Panel', listener: this._showTabListWithPanelCase, }, { name: 'Link', listener: this._showLinkTestCase }, { name: 'List', listener: this._showListTestCase }, { name: 'Article', listener: this._showArticleTestCase }, { name: 'CheckBox', listener: this._showCheckBoxTestCase }, { name: 'Search', listener: this._showSearchTestCase }, { name: 'Color Editor and Transforms', listener: this._showSliderTestCase, }, { name: 'Order Pizza', listener: this._showRadioGroupAndProgressBarTestCase, }, { name: 'Grid', listener: this._showGridTestCase }, { name: 'Tree', listener: this._showTreeTestCase }, { name: 'Feed', listener: this._showFeedTestCase }, { name: 'TreeGrid', listener: this._showTreeGridTestCase }, { name: 'Text Format', listener: this._showTextFormatCase }, { name: 'Math', listener: this._mathTextCase }, ], }, group2: { ClassRef: MenuItemCheckBox, testCases: [ { name: 'ShowGrid', listener: this._showMenuItemCheckBoxTestCase }, ], }, }; _(testCasesGroup).forEach((group) => { const { ClassRef, testCases } = group; const listenerAsCallback = ClassRef === MenuItemCheckBox; _.forEach(testCases, (testCase) => { const item = new ClassRef( testCase.name, 0, listenerAsCallback ? testCase.listener : _.noop() ); !listenerAsCallback && item.addEventListener('click', testCase.listener); item.addEventListener('keyboardClick', testCase.listener); testCasesMenu.addMenuItem(item); }); if (group !== _.findLast(testCasesGroup)) { const bounds = testCasesMenu._itemContainer.getBounds(); const separator = new Separator(bounds.width, 1); testCasesMenu.addMenuItem(separator); } }); const testCasesMenuItemRadio = new Menu( 'Contrast Radio', MENU_HEIGHT, 0, 'c' ); this._menuBar.addMenu(testCasesMenuItemRadio); const testCasesMenuRadio = [ { name: ' Black-Yellow', bgColor: '#000000', textColor: '#ffff00' }, { name: ' Grey-White', bgColor: '#343A40', textColor: '#F8F9FA' }, { name: ' Blue-White', bgColor: '#0000C7', textColor: '#E0E0E0' }, ]; const menuItemRadioArray = []; testCasesMenuRadio.forEach((testCase) => { const item = new MenuItemRadio( testCase.name, 0, this._showMenuItemRadioTestCase ); item.radio.bgColor = testCase.bgColor; item.radio.textColor = testCase.textColor; testCasesMenuItemRadio.addMenuItem(item); menuItemRadioArray.push(item); }); this.menuItemRadioArray = menuItemRadioArray; const help = new Menu('Help', MENU_HEIGHT, 0, 'h'); const about = new MenuItem('About', 0); about.addEventListener('click', this._showAboutDialog); about.addEventListener('keyboardClick', this._showAboutDialog); help.addMenuItem(about); this._menuBar.addMenu(help); } _clearScreen() { this._menuBar._closeMenus(); this._contentArea.removeAllChildren(); this._contentArea.accessible.removeAllChildren(); // Move the nav to the top this.setChildIndex(this.nav, this.getNumChildren() - 1); } _showDefaultScreen() { this._clearScreen(); const options = { src: imgTestSrc, alt: 'Curriculum Associates Logo', width: 500, height: 300, cjsScaleX: 500 / 964, cjsScaleY: 300 / 673, }; const figure = new Figure( options, 'Making Classrooms Better Place for Teachers and Students' ); figure.x = 100; figure.y = 50; this._contentArea.addChild(figure); this._contentArea.accessible.addChild(figure); const testDisplayObject1 = new createjs.Text( 'Welcome to the Createjs Accessibility Module test program.', '16px Arial' ); testDisplayObject1.x = 144; testDisplayObject1.y = 400; AccessibilityModule.register({ displayObject: testDisplayObject1, parent: this._contentArea, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: testDisplayObject1.text, }, }); this._contentArea.addChild(testDisplayObject1); const testDisplayObject2 = new createjs.Text( 'Use the menu bar to move between the various test cases.', '14px Arial' ); testDisplayObject2.x = 169; testDisplayObject2.y = 440; AccessibilityModule.register({ displayObject: testDisplayObject2, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: testDisplayObject2.text, }, }); } createGrid() { const dummyCanvas = document.createElement('canvas'); dummyCanvas.width = 800; dummyCanvas.height = 800; dummyCanvas.id = 'dummyCanvas'; const ctx = dummyCanvas.getContext('2d'); ctx.strokeStyle = '#000'; ctx.lineWidth = 0.5; for (let i = 0; i <= 800; i += 10) { ctx.moveTo(i, 0); ctx.lineTo(i, 800); ctx.stroke(); ctx.moveTo(0, i); ctx.lineTo(800, i); ctx.stroke(); } const gridImageData = dummyCanvas.toDataURL(); const options = { src: gridImageData, alt: 'a grid covering the background', width: 800, height: 800, cjsScaleX: 1, cjsScaleY: 1, }; this.gridImage = new Img(options, options.width, options.height); } _showMenuItemCheckBoxTestCase(event) { let menuItemCheckBoxInst = event; if (!(menuItemCheckBoxInst instanceof MenuItemCheckBox)) { menuItemCheckBoxInst = event.currentTarget; } const showGrid = menuItemCheckBoxInst.checkBox.checked; if (showGrid) { this._contentArea.addChildAt(this.gridImage, 1); this._contentArea.accessible.addChildAt(this.gridImage, 1); } else { this._contentArea.removeChild(this.gridImage); this._contentArea.accessible.removeChild(this.gridImage); } } _showMenuItemRadioTestCase(evt) { this._clearScreen(); this.menuItemRadioArray.forEach((item) => { item.accessible.checked = false; item.radio.checked = false; }); evt.currentTarget.checked = true; this._menuBar._bg.graphics .clear() .beginFill(`${evt.currentTarget.bgColor}`) .drawRect(0, 0, 800, 20); this._menuBar._menus.forEach((menu) => { menu._label.color = `${evt.currentTarget.textColor}`; }); } _showRadioGroupAndProgressBarTestCase() { this._clearScreen(); let submit; const PizzaCrustData = [ { name: 'Pizza Crust', value: 'Regular Margherita', position: 1, size: 3, }, { name: 'Pizza Crust', value: 'Mexican Green Wave', position: 2, size: 3, }, { name: 'Pizza Crust', value: 'Veg Extravaganza', position: 3, size: 3, }, ]; const PizzaDeliveryData = [ { name: 'Pizza Delivery', value: 'Pickup', position: 1, size: 2, }, { name: 'Pizza Delivery', value: 'Home Delivery', position: 2, size: 2, }, ]; let count = 0; const onRadioSelect = () => { if (++count >= 2) { submit.enabled = true; } }; const appendProgressBar = () => { this._clearScreen(); const { width, height } = this._contentArea.getBounds(); const label = new createjs.Text( 'Placing Order', 'bold 20px Arial', '#000' ); const percent = new createjs.Text('0%', 'bold 20px Arial', '#000'); const percentLabelLeft = () => this._contentArea.x + (width - percent.getBounds().width) / 2; const onProgress = (now, state) => { percent.text = `${now}%`; percent.x = percentLabelLeft(); percent.accessible.text = `${now}%`; if (state === 'completed') { label.text = 'Order placed successfully'; label.accessible.text = label.text; } }; const progressBar = new ProgressBar({ onProgress }); label.x = this._contentArea.x + (width - progressBar.width) / 2; label.y = this._contentArea.y + (height - 24) / 2; this._contentArea.addChild(label); AccessibilityModule.register({ displayObject: label, role: AccessibilityModule.ROLES.STATUS, accessibleOptions: { text: label.text, }, }); this._contentArea.accessible.addChild(label); progressBar.x = label.x; progressBar.y = label.y + 30; this._contentArea.addChild(progressBar); this._contentArea.accessible.addChild(progressBar); percent.x = percentLabelLeft(); percent.y = progressBar.y + progressBar.height + 2; this._contentArea.addChild(percent); AccessibilityModule.register({ displayObject: percent, parent: this._contentArea, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: percent.text, }, }); progressBar.startProgress(); }; const title = new createjs.Text( 'Select the pizza and delivery type', 'bold 24px Arial', '#000' ); title.x = 50; title.y = 50; this._contentArea.addChild(title); AccessibilityModule.register({ displayObject: title, parent: this._contentArea, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: title.text, }, }); const labelGroup1 = new createjs.Text( 'Pizza Crust', 'bold 24px Arial', '#000' ); this._contentArea.addChild(labelGroup1); AccessibilityModule.register({ displayObject: labelGroup1, parent: this._contentArea, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: labelGroup1.text, }, }); const radioGroup1 = new RadioGroup({ radioData: PizzaCrustData, name: 'Pizza Crust', callBack: _.once(onRadioSelect), }); radioGroup1.x = 100; radioGroup1.y = 100; this._contentArea.addChild(radioGroup1); this._contentArea.accessible.addChild(radioGroup1); radioGroup1.accessible.labelledBy = labelGroup1; labelGroup1.y = radioGroup1.x; labelGroup1.x = radioGroup1.y; const labelGroup2 = new createjs.Text( 'Pizza Delivery', 'bold 24px Arial', '#000' ); this._contentArea.addChild(labelGroup2); AccessibilityModule.register({ displayObject: labelGroup2, parent: this._contentArea, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: labelGroup2.text, }, }); const radioGroup2 = new RadioGroup({ radioData: PizzaDeliveryData, name: 'Pizza Delivery', callBack: _.once(onRadioSelect), }); radioGroup2.x = radioGroup1.x; radioGroup2.y = 300; this._contentArea.addChild(radioGroup2); this._contentArea.accessible.addChild(radioGroup2); radioGroup2.accessible.labelledBy = labelGroup2; labelGroup2.x = radioGroup2.x; labelGroup2.y = radioGroup2.y; const submitBtnData = { type: 'button', value: 'Place Order', name: 'SUBMIT', enabled: false, height: 60, width: 250, }; // Submit form button submit = new Button(submitBtnData, 0, appendProgressBar); const { width } = labelGroup2.getBounds(); submit.x = labelGroup2.x + (width - submit.getBounds().width) / 2; submit.y = 420; this._contentArea.addChild(submit); this._contentArea.accessible.addChild(submit); } _showFormTestCase() { this._clearScreen(); // Creating form const form = new createjs.Container(); form.x = 10; form.y = 10; AccessibilityModule.register({ displayObject: form, parent: this._contentArea, role: AccessibilityModule.ROLES.FORM, }); this._contentArea.addChild(form); // Implementing SINGLE LINE INPUT TEXT FIELD let label = new createjs.Text('Name', '14px Arial'); label.x = 10; label.y = 100; AccessibilityModule.register({ displayObject: label, parent: form, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: label.text, }, }); form.addChild(label); form.accessible.autoComplete = true; const nameField = new SingleLineTextInput(OPTION_WIDTH, OPTION_HEIGHT, 0); nameField.x = 160; nameField.y = 100; form.addChild(nameField); form.accessible.addChild(nameField); nameField.accessible.autoComplete = 'name'; nameField.accessible.name = 'name'; // Tooltip for field const nameFieldToolTip = new Tooltip({ target: nameField, content: 'Enter username', position: 'top', }); form.addChild(nameFieldToolTip); form.accessible.addChild(nameFieldToolTip); // Button to clear field const clearField = () => { nameField._updateDisplayString(''); }; const clearNameFieldBtn = this._createClearButton( 'Clear name field', 0, clearField ); form.addChild(clearNameFieldBtn); form.accessible.addChild(clearNameFieldBtn); clearNameFieldBtn.set({ x: nameField.x + OPTION_WIDTH + 10, y: nameField.y, }); let clearBtnToolTip = new Tooltip({ target: clearNameFieldBtn, content: 'Clear name field', position: 'top', }); form.addChild(clearBtnToolTip); form.accessible.addChild(clearBtnToolTip); // Label for Address Field label = new createjs.Text('Address', '14px Arial'); label.x = 160 + OPTION_WIDTH + 150; label.y = 100; AccessibilityModule.register({ displayObject: label, parent: form, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: label.text, }, }); form.addChild(label); // Address Field const addressField = new SingleLineTextInput( OPTION_WIDTH, OPTION_HEIGHT, 0 ); addressField.x = 160 + OPTION_WIDTH + 150 + 90; addressField.y = 100; addressField.accessible.name = 'address'; addressField.accessible.autoComplete = 'off'; form.addChild(addressField); form.accessible.addChild(addressField); // Tooltip for Address field const addressFieldToolTip = new Tooltip({ target: addressField, content: 'Enter address', position: 'top', }); form.addChild(addressFieldToolTip); form.accessible.addChild(addressFieldToolTip); const clearAddressField = () => { addressField._updateDisplayString(''); }; const clearAddressFieldBtn = this._createClearButton( 'Clear address field', clearAddressField ); form.addChild(clearAddressFieldBtn); form.accessible.addChild(clearAddressFieldBtn); clearAddressFieldBtn.set({ x: addressField.x + OPTION_WIDTH + 10, y: addressField.y, }); clearBtnToolTip = new Tooltip({ target: clearAddressFieldBtn, content: 'Clear address field', position: 'top', }); form.addChild(clearBtnToolTip); form.accessible.addChild(clearBtnToolTip); // Implementing SINGLE SELECT LISTBOX field label = new createjs.Text('Membership Level', '14px Arial'); label.x = 10; label.y = 120; AccessibilityModule.register({ displayObject: label, parent: form, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: label.text, }, }); form.addChild(label); // Options let optionLabels = ['Free', 'Member', 'Premium']; let options = []; optionLabels.forEach((optionLabel) => { options.push(new Option(optionLabel, OPTION_WIDTH, OPTION_HEIGHT, true)); }); // List box const membershipList = new ListBox(options, OPTION_WIDTH, OPTION_HEIGHT, 0); const membershipOption = options; membershipList.x = 160; membershipList.y = 118; membershipList.accessible.labelledBy = label; form.addChild(membershipList); form.accessible.addChild(membershipList); // List box's tooltip const membershipListToolTip = new Tooltip({ target: membershipList, content: 'Select membership level', }); form.addChild(membershipListToolTip); form.accessible.addChild(membershipListToolTip); // Label for Email field label = new createjs.Text('Email ID', '14px Arial'); label.x = 160 + OPTION_WIDTH + 150; label.y = 118; AccessibilityModule.register({ displayObject: label, parent: form, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: label.text, }, }); form.addChild(label); // Email Field const emailField = new SingleLineTextInput(OPTION_WIDTH, OPTION_HEIGHT, 0); emailField.x = 160 + OPTION_WIDTH + 150 + 90; emailField.y = 118; emailField.accessible.name = 'email'; form.addChild(emailField); form.accessible.addChild(emailField); // Tooltip for Email field const emailFieldToolTip = new Tooltip({ target: emailField, content: 'Enter email', position: 'bottom', }); form.addChild(emailFieldToolTip); form.accessible.addChild(emailFieldToolTip); const clearEmailField = () => { emailField._updateDisplayString(''); }; const clearEmailFieldBtn = this._createClearButton( 'Clear address field', clearEmailField ); form.addChild(clearEmailFieldBtn); form.accessible.addChild(clearEmailFieldBtn); clearEmailFieldBtn.set({ x: emailField.x + OPTION_WIDTH + 10, y: emailField.y, }); clearBtnToolTip = new Tooltip({ target: clearEmailFieldBtn, content: 'Clear email field', position: 'bottom', }); form.addChild(clearBtnToolTip); form.accessible.addChild(clearBtnToolTip); label = new createjs.Text('Comments', '14px Arial'); label.x = 10; label.y = 140; AccessibilityModule.register({ displayObject: label, parent: form, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: label.text, }, }); form.addChild(label); // Implementing MULTI LINE TEXT BOX const commentArea = new MultiLineTextInput( OPTION_WIDTH, OPTION_HEIGHT * 5, 14, 0 ); commentArea.x = 160; commentArea.y = 140; form.addChild(commentArea); form.accessible.addChild(commentArea); commentArea.accessible.spellcheck = true; // Text box's tooltip const commentAreaToolTip = new Tooltip({ target: commentArea, content: 'Comment regarding membership', }); form.addChild(commentAreaToolTip); form.accessible.addChild(commentAreaToolTip); // Button to clear area const clearArea = () => { commentArea._updateDisplayString(''); }; const clearCommentAreaBtn = this._createClearButton( 'Clear comment area', 0, clearArea ); form.addChild(clearCommentAreaBtn); form.accessible.addChild(clearCommentAreaBtn); clearCommentAreaBtn.set({ x: commentArea.x + OPTION_WIDTH + 10, y: commentArea.y + 70, }); clearBtnToolTip = new Tooltip({ target: clearCommentAreaBtn, content: 'Clear comment area', }); form.addChild(clearBtnToolTip); form.accessible.addChild(clearBtnToolTip); // Implementing MULTI SELECT LIST BOX label = new createjs.Text('Mailing Lists', '14px Arial'); label.x = 10; label.y = 235; AccessibilityModule.register({ displayObject: label, parent: form, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: label.text, }, }); form.addChild(label); // Options optionLabels = [ 'OpenGL', 'Direct3D12', 'Vulkan', 'Mantle', 'Metal', 'WebGL', ]; options = []; optionLabels.forEach((optionLabel) => { options.push(new Option(optionLabel, OPTION_WIDTH, OPTION_HEIGHT, false)); }); // Multi select list box const mailingList = new MultiListBox( options, OPTION_WIDTH, OPTION_HEIGHT, 0 ); mailingList.x = 160; mailingList.y = 233; mailingList.accessible.labelledBy = label; form.addChild(mailingList); form.accessible.addChild(mailingList); // Box's tooltip const mailingListToolTip = new Tooltip({ target: mailingList, content: 'Choose between mailing types', }); form.addChild(mailingListToolTip); form.accessible.addChild(mailingListToolTip); // combobox example label = new createjs.Text('Primary interest', '14px Arial'); label.x = 10; label.y = 352; AccessibilityModule.register({ displayObject: label, parent: form, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: label.text, }, }); form.addChild(label); optionLabels = [ 'Graphics', 'Game Engines', 'AI', 'Pathfinding', 'Game Design', ]; options = _.map( optionLabels, (optionLabel) => new Option(optionLabel, OPTION_WIDTH, OPTION_HEIGHT, true) ); // eslint-disable-line max-len const combobox = new ComboBox(options, OPTION_WIDTH, OPTION_HEIGHT, 0); combobox.x = 160; combobox.y = 350; form.addChild(combobox); form.accessible.addChild(combobox); // Alert when form gets submitted const alert = new createjs.Container(); AccessibilityModule.register({ displayObject: alert, parent: form, role: AccessibilityModule.ROLES.ALERT, }); alert.set({ x: 640, y: 10 }); form.addChild(alert); form.accessible.addChild(alert); // background const alertBg = new createjs.Shape(); alertBg.graphics.beginFill('#000000').drawRoundRect(0, 0, 150, 30, 7); alert.addChild(alertBg); // Label const alertLabel = new createjs.Text( 'Form submitted', 'Bold 18px Arial', 'white' ); alertLabel.set({ x: 10, y: 6 }); AccessibilityModule.register({ displayObject: alertLabel, parent: alert, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: alertLabel.text, }, }); alert.accessible.addChild(alertLabel); alert.addChild(alertLabel); alert.visible = false; label = new createjs.Text('', '14px Arial'); AccessibilityModule.register({ displayObject: label, parent: form, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: label.text, }, }); form.addChild(label); form.accessible.addChild(label); // Implementing BUTTON const submitCallBack = () => { label.text = `NAME: ${nameField._text.text}, Comments: ${commentArea._text.text}, MEMBERSHIP: ${membershipList._selectedDisplay.text}, mailingList: ${mailingList.accessible.selectedValue}, primary interest: ${combobox.text}`; label.x = 10; label.y = 390; // Show alert alert.visible = true; const timeId = setTimeout(() => { alert.visible = false; clearTimeout(timeId); }, 1000); const frame = document.createElement('iframe'); frame.setAttribute('id', 'hiddenFrame'); frame.setAttribute('name', 'hiddenFrame'); frame.style.display = 'none'; const f = document.querySelector('form'); f.append(frame); f.target = 'hiddenFrame'; f.submit(); }; const resetAll = () => { label.text = ''; form.accessible.removeChild(label); nameField._updateDisplayString(''); nameField.onBlur(); commentArea._updateDisplayString(''); commentArea.onBlur(); membershipList._updateSelectedOption(membershipOption[0]); mailingList.onBlur(); mailingList._unhighlightAll(); mailingList.accessible.selected = []; combobox.text = ''; emailField._updateDisplayString(''); emailField.onBlur(); addressField._updateDisplayString(''); addressField.onBlur(); }; const submitBtnData = { type: 'submit', value: 'SUBMIT', name: 'SUBMIT', enabled: true, autoFocus: false, form: 'form_1', formAction: '', formMethod: 'GET', formTarget: '_blank', formnoValidate: '', height: 60, width: 250, }; form.accessible.action = ''; form.accessible.method = 'GET'; // Submit form button const submit = new Button(submitBtnData, 0, submitCallBack); submit.x = 50; submit.y = 410; form.addChild(submit); form.accessible.addChild(submit); submit.setBounds(0, 0, 250, 60); const submitBtnToolTip = new Tooltip({ target: submit, content: 'Submit given data to the server', position: 'bottom', }); form.addChild(submitBtnToolTip); form.accessible.addChild(submitBtnToolTip); const resetBtnData = { type: 'reset', value: 'RESET', name: 'RESET', enabled: true, autoFocus: false, form: 'form_1', formAction: '', formMethod: 'GET', formTarget: '_blank', formnoValidate: '', height: 60, width: 250, }; let reset; function makeFormTabbable() { form.accessible.hidden = false; nameField.accessible.tabIndex = 0; clearNameFieldBtn.accessible.tabIndex = 0; membershipList.setTabbable(true); commentArea.accessible.tabIndex = 0; clearCommentAreaBtn.accessible.tabIndex = 0; mailingList.accessible.tabIndex = 0; combobox.setTabbable(true); submit.accessible.tabIndex = 0; reset.accessible.tabIndex = 0; } const alertDialog = new AlertDialog({ buttonTabIndex: 0, cancelCallback: () => { alertDialog.visible = false; form.accessible.hidden = false; makeFormTabbable(); }, doneCallback: () => { resetAll(); alertDialog.visible = false; form.accessible.hidden = false; makeFormTabbable(); }, }); alertDialog.visible = false; this._contentArea.addChild(alertDialog); this._contentArea.accessible.addChild(alertDialog); const resetCallback = () => { alertDialog.visible = true; form.accessible.hidden = true; nameField.accessible.tabIndex = -1; clearNameFieldBtn.accessible.tabIndex = -1; membershipList.setTabbable(false); commentArea.accessible.tabIndex = -1; clearCommentAreaBtn.accessible.tabIndex = -1; mailingList.accessible.tabIndex = -1; combobox.setTabbable(false); submit.accessible.tabIndex = -1; reset.accessible.tabIndex = -1; }; // Reset form button reset = new Button(resetBtnData, 0, resetCallback); reset.x = 400; reset.y = 410; form.addChild(reset); form.accessible.addChild(reset); reset.setBounds(0, 0, 250, 60); const resetBtnToolTip = new Tooltip({ target: reset, content: 'Reset all fields', position: 'bottom', }); form.addChild(resetBtnToolTip); form.accessible.addChild(resetBtnToolTip); } _createClearButton(name, tabIndex, callBack) { const clearBtnData = { type: 'clear', value: '', name, enabled: true, autoFocus: false, form: 'form_1', formAction: '', formMethod: 'GET', formTarget: '_blank', formnoValidate: '', height: 20, width: 20, tabIndex, }; const button = new Button(clearBtnData, 0, callBack); button.accessible.text = name; const shape = new createjs.Shape(); shape.graphics .beginStroke('black') .setStrokeStyle(2) .arc(0, 0, 5, 0, 300 * (Math.PI / 180)); shape.set({ x: 10, y: 10 }); button.addChild(shape); button.setBounds(0, 0, 20, 20); return button; } _showLinkTestCase() { this._clearScreen(); const document = new createjs.Container(); AccessibilityModule.register({ displayObject: document, parent: this._contentArea, role: AccessibilityModule.ROLES.DOCUMENT, }); this._contentArea.addChild(document); const openingLine = new createjs.Text( 'There are multiple resources to learn about aria roles, WCAG, and Section 508 standards.', '16px Arial' ); openingLine.x = 50; openingLine.y = 50; AccessibilityModule.register({ displayObject: openingLine, parent: document, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: openingLine.text, }, }); document.addChild(openingLine); let options = { href: 'https://www.w3.org/WAI/WCAG20/quickref/?currentsidebar=#col_customize&levels=aaa', tabIndex: 0, text: "W3C's guide to meeting WCAG requirements", }; const wcag = new Link(options); wcag.x = 50; wcag.y = 70; document.addChild(wcag); document.accessible.addChild(wcag); options = { href: 'https://www.w3.org/TR/wai-aria-1.1/', tabIndex: 0, text: "W3C's general guide to Accessible Rich Internet Applications", }; const aria = new Link(options); aria.x = 50; aria.y = 90; document.addChild(aria); document.accessible.addChild(aria); options = { href: 'https://www.w3.org/TR/html-aria/#allowed-aria-roles-states-and-properties', tabIndex: 0, text: "W3C's guide to allowed ARIA roles, states, and properties", }; const allowedAria = new Link(options); allowedAria.x = 50; allowedAria.y = 110; document.addChild(allowedAria); document.accessible.addChild(allowedAria); } _showCheckBoxTestCase() { this._clearScreen(); let lasty = 0; let selectedCheckBoxes; let selected; const V_GAP = 60; const X = 50; const FONT = '20px Arial'; const checkBoxArray = []; const labelArray = ['Golf', 'Baseball', 'Tennis', 'Cricket', 'Soccer']; // Callback function to get current state of each checkbox in group const callBack = () => { selectedCheckBoxes = _.map( _.filter(checkBoxArray, (box) => box.checked === true), 'label' ); selected.text = selectedCheckBoxes.toString(); selected.accessible.text = selected.text; }; // Title const title = new createjs.Text( 'Select below sports to get an updates on respective one', FONT ); title.set({ x: X, y: 50 }); AccessibilityModule.register({ displayObject: title, parent: this._contentArea, role: AccessibilityModule.ROLES.NONE, }); this._contentArea.addChild(title); // Checkboxes with labels for (let i = 0; i < labelArray.length; i++) { // checkbox const checkBox = new CheckBox(25, 25, 0, callBack); checkBox.set({ x: X, y: title.y + V_GAP + i * V_GAP }); const boxBounds = checkBox.getBounds(); this._contentArea.addChild(checkBox); this._contentArea.accessible.addChild(checkBox); // label const label = new createjs.Text(`${labelArray[i]}`, FONT); this._contentArea.addChild(label); const labelBounds = label.getBounds(); label.set({ x: checkBox.x + boxBounds.width + 10, y: checkBox.y + (boxBounds.height - labelBounds.height) * 0.5, }); AccessibilityModule.register({ displayObject: label, parent: this._contentArea, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: label.text, }, }); checkBox.label = label.text; checkBoxArray.push(checkBox); lasty = checkBox.y; } // Selected checkboxes const total = new createjs.Text('Selected Sports:', FONT); total.set({ x: X, y: lasty + V_GAP }); this._contentArea.addChild(total); AccessibilityModule.register({ displayObject: total, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: total.text, }, }); this._contentArea.accessible.addChild(total); selected = new createjs.Text('', FONT); selected.set({ x: X + total.getBounds().width + 10, y: lasty + V_GAP }); this._contentArea.addChild(selected); AccessibilityModule.register({ displayObject: selected, role: AccessibilityModule.ROLES.LOG, accessibleOptions: { text: selected.text, }, }); this._contentArea.accessible.addChild(selected); } _showDragAndDropTestCase() { this._clearScreen(); const dragDataArr = ['red', 'green', 'blue']; const FONT = '20px Arial'; const WIDTH = 100; const HEIGHT = 50; const dropArr = []; const dragArr = []; // Label const dragText = new createjs.Text( 'Put the draggables into their correct drop zones', FONT ); dragText.set({ x: 50, y: 50 }); this._contentArea.addChild(dragText); AccessibilityModule.register({ displayObject: dragText, parent: this._contentArea, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: dragText.text, }, }); // Creating drop zones for (let i = 0; i < dragDataArr.length; i++) { const drop = new createjs.Shape(); drop.graphics.beginFill(dragDataArr[i]).drawRect(0, 0, WIDTH, HEIGHT); drop.set({ x: 50 + i * (WIDTH + 20), y: 400, alpha: 0.5, placed: false, label: dragDataArr[i], }); drop.setBounds(0, 0, WIDTH, 50); drop.backgroundColor = dragDataArr[i]; drop.opacity = 0.5; dropArr.push(drop); } // Creating draggables for (let i = 0; i < dragDataArr.length; i++) { const options = { type: 'button', value: dragDataArr[i], name: dragDataArr[i], enabled: true, autoFocus: false, width: WIDTH, height: HEIGHT, }; // Container where draggable starts, for returning draggables to their start positions const dragStart = new createjs.Shape(); dragStart.graphics.beginFill('grey').drawRect(0, 0, WIDTH, HEIGHT); dragStart.set({ x: 50 + i * (WIDTH + 20), y: 100, alpha: 0, }); dragStart.setBounds(0, 0, WIDTH, 50); AccessibilityModule.register({ displayObject: dragStart, role: AccessibilityModule.ROLES.NONE, }); this._contentArea.addChild(dragStart); this._contentArea.accessible.addChild(dragStart); // Interactive draggable const drag = new Draggable(options, dropArr, 0, _.noop, dragStart); drag.set({ x: 50 + i * (WIDTH + 20), y: 100, }); drag.origX = drag.x; drag.origY = drag.y; this._contentArea.addChild(drag); dragStart.accessible.addChild(drag); dragArr.push(drag); drag.button.addEventListener('focus', (evt) => { _.forEach(dragArr, (draggable) => draggable.toggleMenuVisibility(false) ); const { target } = evt; target._onFocus(); }); } // As per UI drop zones will get added after the draggables _.forEach(dropArr, (drop, i) => { AccessibilityModule.register({ displayObject: drop, role: AccessibilityModule.ROLES.NONE, }); drop.accessible.dropEffects = 'move'; drop.accessible.label = `${dragDataArr[i]} drop target`; this._contentArea.addChild(drop); this._contentArea.accessible.addChild(drop); }); } _showAboutDialog() { const clearBtnData = { type: 'button', value: 'x', name: 'close dialog', enabled: true, height: 25, width: 25, }; const parentContainer = new createjs.Container(); const rect = new createjs.Shape(); rect.graphics .beginStroke('#ccc') .setStrokeStyle(1) .beginFill('#000') .drawRect(0, 0, 800, 600); parentContainer.addChild(rect); this._contentArea.addChild(parentContainer); AccessibilityModule.register({ displayObject: parentContainer, parent: this._contentArea, role: AccessibilityModule.ROLES.NONE, }); const dialog = new Dialog(clearBtnData, 600, 400, -1); parentContainer.addChild(dialog); parentContainer.accessible.addChild(dialog); dialog.visible = true; dialog.x = 100; dialog.y = 100; this._menuBar._closeMenus(); } _showListTestCase() { this._clearScreen(); const directory = new createjs.Container(); const testDisplayObject = new createjs.Text( 'We have developed a basic workflow for creating these different role objects', '16px Arial' ); testDisplayObject.x = 50; testDisplayObject.y = 50; AccessibilityModule.register({ displayObject: testDisplayObject, parent: this._contentArea, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: testDisplayObject.text, }, }); this._contentArea.addChild(testDisplayObject); const listItems = []; const options = { text: 'src/Roles.js - look at the roles enum, may have to break apart the aria roles as needed', }; listItems.push(new ListItem(options)); options.text = 'src/Roles.js - go to RoleTagMapping so that the Roles enum value gets converted to an html tag'; listItems.push(new ListItem(options)); options.text = 'https://www.w3.org/TR/wai-aria/roles && https://www.w3.org/TR/wai-aria/rdf_model.png - go and check\n' + "if there are new aria attributes that are going to be added to your new object (that aren't covered in a\n" + 'parent object) from the aria attribute page (link 1) and the flowchart (link 2), and look at the html tag\n' + 'page and pick and choose the necessary properties that pertain to how the object will be used and add\nthem in'; listItems.push(new ListItem(options)); options.text = 'src/RolesObjects - create the new object, usually have to extend the accessibility object but that\n' + "may be sufficient in the rare case. if the accessibility object is sufficient, you're done."; listItems.push(new ListItem(options)); options.text = 'src/RoleObjectFactory.js - actually instantiate your new object in the switch statement'; listItems.push(new ListItem(options)); options.text = 'src/test/widgets - add a test case .js file for your new object'; listItems.push(new ListItem(options)); options.text = 'src/test/widgets/AppWindow.js - add your new object to the actual app window code'; listItems.push(new ListItem(options)); const orderedList = new OrderedList({ type: '1', start: '1', reversed: false, }); orderedList.x = 50; orderedList.y = 80; let y = 0; for (let i = 0; i < listItems.length; i++) { orderedList.addListItem(listItems[i], y, i); if (i === 2) { y += 60; } if (i === 3) { y += 15; } y += 20; } this._contentArea.addChild(directory); AccessibilityModule.register({ displayObject: directory, parent: this._contentArea, role: AccessibilityModule.ROLES.DIRECTORY, }); directory.addChild(orderedList); directory.accessible.addChild(orderedList); } _showArticleTestCase() { this._clearScreen(); const openingParagraph = new createjs.Text( 'Call me Ishmael. Some years ago—never mind how long precisely—having little or no money in my purse, and\n' + 'nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the\n' + 'world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing\n' + 'grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily\n' + 'pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever\n' + 'my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from\n' + "deliberately stepping into the street, and methodically knocking people's hats off—then, I account it high time\n" + 'to get to sea as soon as I can. This is my substitute for pistol and ball. With a philosophical flourish Cato\n' + 'throws himself upon his sword; I quietly take to the ship. There is nothing surprising in this. If they but knew it,\n' + 'almost all men in their degree, some time or other, cherish very nearly the same feelings towards the ocean\nwith me.', '16px Arial' ); const secondParagraph = new createjs.Text( 'There now is your insular city of the Manhattoes, belted round by wharves as Indian isles by coral\n' + 'reefs—commerce surrounds it with her surf. Right and left, the streets take you waterward. Its extreme\n' + 'downtown is the battery, where that noble mole is washed by waves, and cooled by breezes, which a few hours\n' + 'previous were out of sight of land. Look at the crowds of water-gazers there.', '16px Arial' ); const quoteInfo = new createjs.Text( 'The above quotes are from "Moby Dick (Chap. 1: Loomings) by Herman Melville".', 'bold 16px Arial' ); AccessibilityModule.register([ { displayObject: openingParagraph, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: openingParagraph.text, }, }, { displayObject: secondParagraph, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: secondParagraph.text, }, }, { displayObject: quoteInfo, role: AccessibilityModule.ROLES.NOTE, accessibleOptions: { text: quoteInfo.text, }, }, ]); const article = new Article(); article.x = 10; article.y = 50; article.addSection(openingParagraph); article.addSection(secondParagraph); article.addSection(quoteInfo); this._contentArea.addChild(article); this._contentArea.accessible.addChild(article); const complementary = new createjs.Container(); this._contentArea.addChild(complementary); AccessibilityModule.register({ displayObject: complementary, role: AccessibilityModule.ROLES.COMPEMENTARY, }); this._contentArea.accessible.addChild(complementary); const sumaryText = 'SUMMARY: \n' + 'Ishmael explains that, whenever he feels depressed and suicidal, he always goes to sea.\n' + 'Ishmael claims that most people and most cultures around the world have a special attraction \n' + 'to water in general and the sea in particular.'; const summary = new createjs.Text(sumaryText, '16px Arial'); AccessibilityModule.register({ displayObject: summary, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: summary.text, }, }); complementary.addChild(summary); complementary.accessible.addChild(summary); complementary.x = article.x; complementary.y = article.y + article.getBounds().height + 10; const loop = -1; // Sets the number of times the marquee will scroll. // If no value is specified, the default value is −1, which means // the marquee will scroll continuously. const direction = 'right'; // left, right, up and down const behaviour = 'scroll'; // scroll, slide and alternate const text = 'Moby Dick (1956 film) Release date June 27, 1956 in the United States'; const marquee = new Marquee({ text, behaviour, direction, loop, }); this._contentArea.addChild(marquee); this._contentArea.accessible.addChild(marquee); } _showTabListWithPanelCase() { this._clearScreen(); const region = new createjs.Container(); this._contentArea.addChild(region); AccessibilityModule.register({ displayObject: region, role: AccessibilityModule.ROLES.REGION, }); this._contentArea.accessible.addChild(region); const heading = new createjs.Text( 'Descriptions of planets using tab widgets', 'bold 18px Arial', '#000' ); region.addChild(heading); AccessibilityModule.register({ displayObject: heading, role: AccessibilityModule.ROLES.HEADING3, accessibleOptions: { text: heading.text, }, }); region.accessible.addChild(heading); region.accessible.labelledBy = heading; heading.x = 0; heading.y = 20; heading.lineWidth = 800; const directory = new createjs.Container(); region.addChild(directory); AccessibilityModule.register({ displayObject: directory, role: AccessibilityModule.ROLES.DIRECTORY, }); region.accessible.addChild(directory); directory.y = 100; directory.setBounds(0, 0, 200, 600); const earth = { tabListArr: [ { name: 'Earth Info', value: 'Earth Info', width: 200, height: 50, position: 1, size: 3, data: { link: { href: 'https://en.wikipedia.org/wiki/Earth', text: 'Earth wikipedia reference', }, description: 'Earth is the third planet from the Sun and the only astronomical object known to harbor life. According to radiometric dating and other\n' + "sources of evidence, Earth formed over 4.5 billion years ago.[24][25][26] Earth's gravity interacts with other objects in space, \n" + "especially the Sun and the Moon, Earth's only natural satellite. Earth revolves around the Sun in 365.26 days, a period known as \n" + 'an Earth year. During this time, Earth rotates about its axis about 366.26 times', }, }, { name: 'Orbit', value: 'Orbit ', width: 200, height: 50, position: 2, size: 3, data: { link: { href: 'https://en.wikipedia.org/wiki/Earth#Orbit_and_rotation', text: 'Earth Orbit', }, description: "Earth's rotation period relative to the Sun—its mean solar day—is 86,400 seconds of mean solar time (86,400.0025 SI seconds). \n" + "[182] Because Earth's solar day is now slightly longer than it was during the 19th century due to tidal deceleration, \n" + 'each day varies between 0 and 2 SI ms longe', }, }, { name: 'Rotation', value: 'Rotation', width: 200, height: 50, position: 3, size: 3, data: { link: { href: 'https://en.wikipedia.org/wiki/Earth#Orbit_and_rotation', text: 'Earth Rotation', }, description: 'Earth orbits the Sun at an average distance of about 150 million km (93 million mi) every 365.2564 mean solar days, or one sidereal \n' + 'year. This gives an apparent movement of the Sun eastward with respect to the stars at a rate of about 1°/day, which is one \n' + 'apparent Sun or Moon diameter every 12 hours. Due to this motion, on average it takes 24 hours—a solar day—for Earth to complete \n' + 'a full rotation about its axis so that the Sun returns to the meridian. The orbital speed of Earth averages about 29.78 km/s \n' + "(107,200 km/h; 66,600 mph), which is fast enough to travel a distance equal to Earth's diameter, about 12,742 km (7,918 mi),\n" + 'in seven minutes, and the distance to the Moon, 384,000 km (239,000 mi), in about 3.5 hours.[3]', }, }, ], buttonData: { type: 'button', value: 'Earth', name: 'Earth', enabled: true, height: 60, width: 150, }, }; const moon = { tabListArr: [ { name: 'Moon Info', value: 'Moon Info', width: 200, height: 50, position: 1, size: 3, data: { link: { href: 'https://en.wikipedia.org/wiki/Moon', text: 'Moon Wikipedia reference', }, description: "The Moon is an astronomical body that orbits planet Earth and is Earth's only permanent natural satellite. It is the fifth-largest natural \n" + 'satellite in the Solar System, and the largest among planetary satellites relative to the size of the planet that it orbits (its primary). \n' + "The Moon is after Jupiter's satellite Io the second-densest satellite in the Solar System among those whose densities are known.", }, }, { name: 'Orbit', value: 'Orbit', width: 200, height: 50, position: 2, size: 3, data: { link: { href: 'https://en.wikipedia.org/wiki/Moon#Orbit', text: 'Moon Orbit', }, description: 'The Moon makes a complete orbit around Earth with respect to the fixed stars about once every 27.3 days[g] (its sidereal period). \n' + 'However, because Earth is moving in its orbit around the Sun at the same time, it takes slightly longer for the Moon to show the \n' + 'same phase to Earth, which is about 29.5 days[h] (its synodic period).[66] Unlike most satellites of other planets, the Moon orbits \n' + "closer to the ecliptic plane than to the planet's equatorial plane. The Moon's orbit is subtly perturbed by the Sun and Earth in many \n" + "small, complex and interacting ways. For example, the plane of the Moon's orbit gradually rotates once every 18.61[131] years, which \n" + 'affects other aspects of lunar motion. ', }, }, { name: 'Rotation', value: 'Rotation', width: 200, height: 50, position: 3, size: 3, data: { link: { href: 'https://en.wikipedia.org/wiki/Moon', text: 'Moon Rotation', }, description: 'The Moon is in synchronous rotation with Earth, and thus always shows the same side to Earth, the near side. The near side is \n' + 'marked by dark volcanic maria that fill the spaces between the bright ancient crustal highlands and the prominent impact craters. After the\n' + "Sun, the Moon is the second-brightest regularly visible celestial object in Earth's sky. Its surface is actually dark, although compared\n" + 'to the night sky it appears very bright, with a reflectance just slightly higher than that of worn asphalt. Its gravitational influence \n' + 'produces the ocean tides, body tides, and the slight lengthening of the day.', }, }, ], buttonData: { type: 'button', value: 'Moon', name: 'Moon', enabled: true, height: 60, width: 150, }, }; const mars = { tabListArr: [ { name: 'Mars Info', value: 'Mars Info', width: 200, height: 50, position: 1, size: 3, data: { link: { href: 'https://en.wikipedia.org/wiki/Mars', text: 'Mars Wikipedia reference', }, description: 'Mars is the fourth planet from the Sun and the second-smallest planet in the Solar System after Mercury. In English, Mars carries\n' + "a name of the Roman god of war, and is often referred to as the 'Red Planet' because the reddish iron oxide prevalent on its surface \n" + 'gives it a reddish appearance that is distinctive among the astronomical bodies visible to the naked eye.[17] Mars is a terrestrial\n' + 'planet with a thin atmosphere, having surface features reminiscent both of the impact craters of the Moon and the valleys, deserts,\n' + 'and polar ice caps of Earth.', }, }, { name: 'Orbit', value: 'Orbit', width: 200, height: 50, position: 2, size: 3, data: { link: { href: 'https://en.wikipedia.org/wiki/Mars#Orbit_and_rotation', text: 'Mars Orbit', }, description: "Mars is about 230 million km (143 million mi) from the Sun; its orbital period is 687 (Earth) days, depicted in red. Earth's orbit is in blue.\n" + "Mars's average distance from the Sun is roughly 230 million km (143 million mi), and its orbital period is 687 (Earth) days. The solar day \n" + '(or sol) on Mars is only slightly longer than an Earth day: 24 hours, 39 minutes, and 35.244 seconds.[179] A Martian year is equal to\n' + '1.8809 Earth years, or 1 year, 320 days, and 18.2 hours The axial tilt of Mars is 25.19 degrees relative to its orbital plane, which \n' + 'is similar to the axial tilt of Earth.', }, }, { name: 'Rotation', value: 'Rotation', width: 200, height: 50, position: 3, size: 3, data: { link: { href: 'https://en.wikipedia.org/wiki/Mars#Orbit_and_rotation', text: 'Mars Rotation', }, description: 'Mars has a relatively pronounced orbital eccentricity of about 0.09; of the seven other planets in the Solar System, only Mercury has a \n' + 'larger orbital eccentricity. It is known that in the past, Mars has had a much more circular orbit. At one point, 1.35 million Earth years ago,\n' + "Mars had an eccentricity of roughly 0.002, much less than that of Earth today.[180] Mars's cycle of eccentricity is 96,000 Earth years\n" + "compared to Earth's cycle of 100,000 years.[181] Mars has a much longer cycle of eccentricity, with a period of 2.2 million Earth years, \n" + 'and this overshadows the 96,000-year cycle in the eccentricity graphs. For the last 35,000 years, the orbit of Mars has been getting\n' + 'slightly more eccentric because of the gravitational effects of the other planets. The closest distance between Earth and Mars will \n' + 'continue to mildly decrease for the next 25,000 years', }, }, ], buttonData: { type: 'button', value: 'Mars', name: 'Mars', enabled: true, height: 60, width: 150, }, }; const planetsData = [earth, moon, mars]; const tabArr = ['Information', 'Orbit', 'Rotation']; const ITEM_PADDING = 100; this.planetBtnArry = []; let tabPanel = null; _.forEach(planetsData, (planet, index) => { const planetClick = () => { _.forEach(this.planetBtnArry, (planetBtn) => { planetBtn.accessible.pressed = false; }); this.planetBtnArry[index].accessible.pressed = true; this.selectedPlanetIndex = index; const currentData = this.planetBtnArry[this.selectedPlanetIndex].tabListArr[0].data; tabPanel.description.text = currentData.description; tabPanel.description.accessible.text = currentData.description; tabPanel.dataLink._text.text = currentData.link.text; tabPanel.dataLink.accessible.text = currentData.link.text; tabPanel.dataLink.href = currentData.link.href; tabPanel.dataLink.accessible.href = currentData.link.href; }; const planetBtn = new Button(planet.buttonData, 0, planetClick); directory.addChild(planetBtn); directory.accessible.addChild(planetBtn); this.planetBtnArry.push(planetBtn); const bounds = planetBtn.getBounds(); planetBtn.tabListArr = planet.tabListArr; planetBtn.pressed = false; planetBtn.y = planetBtn.y + bounds.height + index * ITEM_PADDING; }); const tabList = new TabList(800, 60, 'horizontal'); region.addChild(tabList); region.accessible.addChild(tabList); tabList.x = 170; tabList.y = 70; _.forEach(tabArr, (tabData, index) => { const _showTabPanel = () => { const currentData = this.planetBtnArry[this.selectedPlanetIndex].tabListArr[index].data; tabPanel.description.text = currentData.description; tabPanel.description.accessible.text = currentData.description; tabPanel.dataLink._text.text = currentData.link.text; tabPanel.dataLink.accessible.text = currentData.link.text; tabPanel.dataLink.href = currentData.link.href; tabPanel.dataLink.accessible.href = currentData.link.href; }; const tab = new Tab({ name: tabData, value: tabData, width: 200, height: 50, position: index, size: tabArr.length, tabIndex: 0, callback: _showTabPanel, }); tabList.addTab(tab); }); tabPanel = new TabPanel(604, 400); region.addChild(tabPanel); region.accessible.addChild(tabPanel); tabPanel.x = tabList.x + 2; tabPanel.y = tabList.y; const firstData = this.planetBtnArry[0].tabListArr[0].data; const linkData = { href: `${firstData.link.href}`, text: `${firstData.link.text}`, }; const dataLink = new Link(linkData); tabPanel.addChild(dataLink); tabPanel.accessible.addChild(dataLink); tabPanel.dataLink = dataLink; dataLink.x = 10; dataLink.y = 100; const description = new createjs.Text( `${firstData.description}`, '18px Arial' ); tabPanel.addChild(description); AccessibilityModule.register({ displayObject: description, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: description.text, }, }); tabPanel.accessible.addChild(description); tabPanel.description = description; tabPanel.description.lineWidth = 550; description.x = 10; description.y = 150; this.selectedPlanetIndex = 0; } _showFeedTestCase() { this._clearScreen(); const feed = new Feed(780, 600); this._contentArea.addChild(feed); this._contentArea.accessible.addChild(feed); const openingParagraph = new createjs.Text( 'Call me Ishmael. Some years ago—never mind how long precisely—having little or no money in my purse, and\n' + 'nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the\n' + 'world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing\n' + 'grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily\n' + 'pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever\n' + 'my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from\n' + "deliberately stepping into the street, and methodically knocking people's hats off—then, I account it high time\n" + 'to get to sea as soon as I can. This is my substitute for pistol and ball. With a philosophical flourish Cato\n' + 'throws himself upon his sword; I quietly take to the ship.', '16px Arial' ); AccessibilityModule.register({ displayObject: openingParagraph, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: openingParagraph.text, }, }); const reference1 = new createjs.Text( 'The above quotes are from "Moby Dick (Chap. 1: Loomings) by Herman Melville".', 'bold 16px Arial' ); AccessibilityModule.register({ displayObject: reference1, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: reference1.text, }, }); const secondParagraph = new createjs.Text( 'All day long we seemed to dawdle through a country which was full of beauty of every kind. Sometimes we \n' + 'saw little towns or castles on the top of steep hills such as we see in old missals; sometimes we ran by rivers \n' + 'and streams which seemed from the wide stony margin on each side of them to be subject to great floods.\n' + 'It takes a lot of water, and running strong, to sweep the outside edge of a river clear. At every station \n' + 'there were groups of people, sometimes crowds, and in all sorts of attire.', '16px Arial' ); AccessibilityModule.register({ displayObject: secondParagraph, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: secondParagraph.text, }, }); const reference2 = new createjs.Text( 'The above quotes are from "DRACULA (Chap. I: JONATHAN HARKER’S JOURNAL) by Bram Stoker".', 'bold 16px Arial' ); AccessibilityModule.register({ displayObject: reference2, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: reference2.text, }, }); const thirdParagraph = new createjs.Text( 'On Greenhaven, everything had evidently been done the hard way. She had heard about that facet of the\n' + 'Greenie character before leaving the ship, and she now wished that she had listened more carefully. It \n' + 'was difficult to picture in her mind just how far away that spaceship was by this time.', '16px Arial' ); AccessibilityModule.register({ displayObject: thirdParagraph, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: thirdParagraph.text, }, }); const reference3 = new createjs.Text( ' The above quotes are from "D-99 a science-fiction novel (CHAPTER SIX) by H. B. FYFE".', 'bold 16px Arial' ); AccessibilityModule.register({ displayObject: reference3, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: reference3.text, }, }); let article = new Article({ position: 1, size: 3 }); article.x = 10; article.y = 0; article.addSection(openingParagraph); article.addSection(reference1); feed.addArticls(article); feed.accessible.addChild(article); article = new Article({ position: 2, size: 3 }); article.x = 10; article.addSection(secondParagraph); article.addSection(reference2); feed.addArticls(article); feed.accessible.addChild(article); article = new Article({ position: 3, size: 3 }); article.x = 10; article.y = 200; article.addSection(thirdParagraph); article.addSection(reference3); feed.addArticls(article); feed.accessible.addChild(article); openingParagraph.lineWidth = 790; secondParagraph.lineWidth = 790; thirdParagraph.lineWidth = 790; const { width, height } = feed.getBounds(); const holderWidth = width; const holderHeight = height * 0.5; const feedHolder = new createjs.Container(); feedHolder.setBounds(0, 0, holderWidth, holderHeight); AccessibilityModule.register({ displayObject: feedHolder, role: AccessibilityModule.ROLES.NONE, }); feedHolder.addChild(feed); feedHolder.accessible.addChild(feed); // Center align on stage const contentAreaBounds = this._contentArea.getBounds(); feedHolder.set({ x: (contentAreaBounds.width - holderWidth) * 0.5, y: (contentAreaBounds.height - holderHeight) * 0.3, }); const scrollBar = new ScrollBar(feedHolder, 0); scrollBar.x = feedHolder.x + holderWidth - scrollBar.getBounds().width; scrollBar.y = feedHolder.y; this._contentArea.addChild(feedHolder); this._contentArea.accessible.addChild(feedHolder); this._contentArea.addChild(scrollBar); this._contentArea.accessible.addChild(scrollBar); } _showSliderTestCase() { this._clearScreen(); const shapeObject = new createjs.Shape(); shapeObject.graphics.drawRect(0, 0, 200, 200); shapeObject.graphics.endFill(); shapeObject.setBounds(0, 0, 200, 200); shapeObject.set({ x: 350, y: 150 }); this._contentArea.addChild(shapeObject); const toolBar = new ToolBar(500, 20); this._contentArea.addChild(toolBar); this._contentArea.accessible.addChild(toolBar); toolBar.y = 20; const ColorEditorBtnData = { type: 'button', value: 'Color-Editor', name: 'Color-Editor', enabled: true, height: 50, width: 125, }; const _showColorEditor = () => { this.transformControlContainer.visible = false; this.alphaControlContainer.visible = false; this._showColorSliderTool = true; this.colorSliderContainer.visible = this._showColorSliderTool; }; // colorEditor button const colorEditor = new Button(ColorEditorBtnData, 0, _showColorEditor); colorEditor.text.font = 'bold 14px Arial'; toolBar.addTool(colorEditor); const transformControlBtnData = { type: 'button', value: 'Transformation', name: 'Transformation', enabled: true, height: 50, width: 125, }; this.transformControlContainer = new createjs.Container(); this._contentArea.addChild(this.transformControlContainer); AccessibilityModule.register({ displayObject: this.transformControlContainer, role: AccessibilityModule.ROLES.NONE, }); this._contentArea.accessible.addChild(this.transformControlContainer); this.transformControlContainer.visible = false; this.transformControlContainer.y = toolBar.y + 50; this._showTransformControl = false; this._addTrasformationTestCase(shapeObject); const _showTransformTool = () => { this.transformControlContainer.visible = !this._showTransformControl; this.alphaControlContainer.visible = false; this.colorSliderContainer.visible = false; }; const transformControl = new Button( transformControlBtnData, 0, _showTransformTool ); transformControl.text.font = 'bold 14px Arial'; toolBar.addTool(transformControl); const alphaControlBtnData = { type: 'button', value: 'Alpha', name: 'Alpha', enabled: true, height: 50, width: 125, }; this.alphaControlContainer = new createjs.Container(); this._contentArea.addChild(this.alphaControlContainer); AccessibilityModule.register({ displayObject: this.alphaControlContainer, role: AccessibilityModule.ROLES.NONE, }); this._contentArea.accessible.addChild(this.alphaControlContainer); this.alphaControlContainer.visible = false; this._showAlphaTool = false; const _showAlphaTool = () => { this.alphaControlContainer.visible = !this._showAlphaTool; this.transformControlContainer.visible = false; this.colorSliderContainer.visible = false; }; const alphaControl = new Button(alphaControlBtnData, 0, _showAlphaTool); alphaControl.text.font = 'bold 16px Arial'; toolBar.addTool(alphaControl); alphaControl.addEventListener('click', _showAlphaTool); const sliderData = [ { label: 'Red', min: 0, max: 255, step: 1, value: 60, rgb: 'rgb(255,0,0)', }, { label: 'Green', min: 0, max: 255, step: 1, value: 125, rgb: 'rgb(0,255,0)', }, { label: 'Blue', min: 0, max: 255, step: 1, value: 226, rgb: 'rgb(0,0,255)', }, ]; this.colorSliderContainer = new createjs.Container(); this._contentArea.addChild(this.colorSliderContainer); AccessibilityModule.register({ displayObject: this.colorSliderContainer, role: AccessibilityModule.ROLES.NONE, }); this._contentArea.accessible.addChild(this.colorSliderContainer); this.colorSliderContainer.visible = false; this._showColorSliderTool = false; const sliderArray = []; let color = ''; this.alphaVal = 0.5; const label = new createjs.Text('Toggle Alpha', 'bold 18px Arial'); label.x = 350; label.y = 100; this.alphaControlContainer.addChild(label); AccessibilityModule.register({ displayObject: label, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: label.text, }, }); this.alphaControlContainer.accessible.addChild(label); const callBack = () => { const redVal = sliderArray[0].valueNow; const greenVal = sliderArray[1].valueNow; const blueVal = sliderArray[2].valueNow; color = `rgba(${redVal}, ${greenVal}, ${blueVal}, ${this.alphaVal})`; shapeObject.graphics .clear() .beginFill(color) .drawRect(0, 0, 200, 200) .endFill(); }; const switchCallBack = (val) => { this.alphaVal = val ? 1 : 0.5; callBack(); }; const switchBtn = new Switch(90, 45, 0, switchCallBack); switchBtn.set({ x: 475, y: 90 }); this.alphaControlContainer.addChild(switchBtn); this.alphaControlContainer.accessible.addChild(switchBtn); switchBtn.accessible.labelledBy = label; for (let i = 0; i < sliderData.length; i++) { const name = sliderData[i].label; const { min, max, step, value } = sliderData[i]; const labelValue = new createjs.Text( `${name}`, '14px Arial', `${sliderData[i].rgb}` ); this.colorSliderContainer.addChild(labelValue); AccessibilityModule.register({ displayObject: labelValue, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: labelValue.text, }, }); this.colorSliderContainer.accessible.addChild(labelValue); const slider = new Slider( min, max, 200, 50, 'horizontal', step, value, 0, callBack ); slider.set({ x: 100, y: i === 0 ? 200 : 200 + i * 50 }); const sliderBounds = slider.getBounds(); this.colorSliderContainer.addChild(slider); this.colorSliderContainer.accessible.addChild(slider); const labelBounds = labelValue.getBounds(); labelValue.set({ x: slider.x - 50, y: slider.y + (sliderBounds.height - labelBounds.height) * 0.5, }); slider.label = labelValue.text; sliderArray.push(slider); } callBack(); } _showSearchTestCase() { this._clearScreen(); const bulletList = [ 'The Western States and Provinces of North America thrive on our “thousand-pounders” and “remittance-men.', 'Students have come here from Mexico, Argentine, and even from Japan, sent by their respective countries.', 'Guelph has two Volunteer Artillery companies, one filled with students from the college, and one with town boys, four guns to each battery.', 'Calgary is a beautiful place on the slope of the foothills, at an elevation of about 3400 feet, rather cold in winter, but delightful in the summer and fall.', 'In Montana, Indian Territory, and Texas, great roping contests are organised every year, and cow-punchers flock from all over the United States and Canada.', 'Manitoba is not all prairie, nor timberless, as so many 36people imagine.', 'Chicago, which lays claim to having the largest in everything, whether it be drainage canals, skyscrapers, slaughter-houses, or the amount of railroad traffic, is certainly a wonderful city.', 'The fall and winter of 1893 were exceptional', 'The Nueces River is so called from the immense quantities of pecan trees which line both banks from the head to the mouth', ]; const listObjectArr = []; // Making bullet list in canvas bulletList.forEach((sentence) => { // Text const textObj = new createjs.Text().set({ text: sentence, font: '18px Arial', lineWidth: 700, }); listObjectArr.push(textObj); this._contentArea.addChild(textObj); AccessibilityModule.register({ displayObject: textObj, parent: this._contentArea, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: textObj.text, }, }); // Bullets const bullet = new createjs.Shape(); bullet.graphics.beginFill('black').drawCircle(0, 0, 5); this._contentArea.addChild(bullet); textObj.bullet = bullet; }); listObjectArr[0].set({ x: 62, y: 50 }); listObjectArr[0].bullet.set({ x: listObjectArr[0].x - 12, y: listObjectArr[0].y + 12, }); for (let i = 1; i < listObjectArr.length; i++) { const preText = listObjectArr[i - 1]; const preTextHeight = preText.getBounds().height; listObjectArr[i].set({ x: listObjectArr[0].x, y: preText.y + preTextHeight + 20, }); listObjectArr[i].bullet.set({ x: listObjectArr[i].x - 12, y: listObjectArr[i].y + 12, }); } // Search const options = { width: OPTION_WIDTH + 300, height: OPTION_HEIGHT + 10, listArr: listObjectArr, buttonOptions: { type: 'button', value: 'Search', name: 'Search', enabled: 'true', width: 85, height: OPTION_HEIGHT + 10, }, }; const search = new Search(options, 0); search.set({ x: 50, y: 10 }); this._contentArea.addChild(search); this._contentArea.accessible.addChildAt(search, 1); } _showGridTestCase() { this._clearScreen(); const squareTileDimension = 30; const buttonData = { value: '', enabled: true, height: squareTileDimension, width: squareTileDimension, }; const buttonClickHandler = (evt) => { const prevValue = evt.currentTarget.text.text; let newValue; if (prevValue === '') { newValue = 'X'; } else if (prevValue === 'X') { newValue = 'O'; } else { newValue = ''; } evt.currentTarget.text.text = newValue; }; const gridData = []; for (let r = 0; r < 3; r++) { const row = []; for (let c = 0; c < 3; c++) { const button = new Button(buttonData, -1, buttonClickHandler); button.setBounds(0, 0, squareTileDimension, squareTileDimension); row.push({ value: button, type: 'cell', cellWidth: squareTileDimension, cellHeight: squareTileDimension, }); } gridData.push(row); } const grid = new Grid(gridData, 0); this._contentArea.addChild(grid); this._contentArea.accessible.addChild(grid); // just moving the grid so it's not right up against the menu bar or left side of the window grid.x = 50; grid.y = 50; } _showTableTestCase() { this._clearScreen(); const options = { headersData: [ { value: 'Role', width: 80 }, { value: 'TagName', width: 100 }, { value: 'Type', width: 80 }, { value: 'Description', width: 300 }, ], data: [ [ 'Button', 'button', 'input', 'An input that allows for user-triggered actions when clicked or pressed.', ], [ 'Menubar', 'ul', 'static', 'A presentation of menu that usually remains visible and is usually presented horizontally.', ], [ 'Form', 'form', 'input', 'A landmark region that contains a collection of items and objects that, as a whole, combine to create a form.', ], [ 'Table', 'table', 'static', 'A section containing data arranged in rows and columns.', ], ], showBorders: true, }; // Creating table content in <tbody> tag const tableBody = new Table(options); // actual <table> tag const table = new createjs.Container(); table.addChild(tableBody); AccessibilityModule.register({ displayObject: table, role: AccessibilityModule.ROLES.TABLE, }); table.accessible.addChild(tableBody); table.accessible.rowCount = tableBody.rowCount; table.accessible.colCount = tableBody.colCount; const { width, height } = table.getBounds(); const holderWidth = width; const holderHeight = height / 2; // Needed because scrollbar cannot be appended in table const tableHolder = new createjs.Container(); tableHolder.setBounds(0, 0, holderWidth, holderHeight); AccessibilityModule.register({ displayObject: tableHolder, role: AccessibilityModule.ROLES.NONE, }); tableHolder.addChild(table); tableHolder.accessible.addChild(table); // Center align on stage const contentAreaBounds = this._contentArea.getBounds(); tableHolder.set({ x: (contentAreaBounds.width - holderWidth) / 2, y: (contentAreaBounds.height - holderHeight) / 2, }); const scrollBar = new ScrollBar(tableHolder, 0); scrollBar.x = tableHolder.x + holderWidth - scrollBar.getBounds().width; scrollBar.y = tableHolder.y; this._contentArea.addChild(tableHolder); this._contentArea.accessible.addChild(tableHolder); this._contentArea.addChild(scrollBar); this._contentArea.accessible.addChild(scrollBar); } _addTrasformationTestCase(shapeObject) { let label; let x = 50; let y = 75; let horizontalScale; let verticalScale; let horizontalSkew; let verticalSkew; let transformX; let transformY; const padding = 10; const transformShape = () => { shapeObject.set({ scaleX: horizontalScale.text, scaleY: verticalScale.text, skewX: horizontalSkew.text, skewY: verticalSkew.text, regX: transformX.text, regY: transformY.text, }); }; const options = { width: 30, height: 60, }; options.minValue = 1; options.maxValue = 4; label = this.createText('scaleX', x, y); x += label.getBounds().width + padding; horizontalScale = this.createText('1', x, y, false); x += horizontalScale.getBounds().width + padding; const scaleXButton = this.createSpinButton( { options, textContainer: horizontalScale, callback: transformShape, }, x, y ); x += scaleXButton.getBounds().width + padding; label = this.createText('scaleY', x, y); x += label.getBounds().width + padding; verticalScale = this.createText('1', x, y, false); x += verticalScale.getBounds().width + padding; const scaleYButton = this.createSpinButton( { options, textContainer: verticalScale, callback: transformShape, }, x, y ); x += scaleYButton.getBounds().width + padding + 20; options.maxValue = 50; x = 50; y = 175; label = this.createText('skewX', x, y); x += label.getBounds().width + padding; horizontalSkew = this.createText('1', x, y, false); x += horizontalSkew.getBounds().width + padding; const skewXButton = this.createSpinButton( { options, textContainer: horizontalSkew, callback: transformShape, }, x, y ); x += skewXButton.getBounds().width + padding; label = this.createText('skewY', x, y); x += label.getBounds().width + padding; verticalSkew = this.createText('1', x, y, false); x += verticalSkew.getBounds().width + padding; const skewYButton = this.createSpinButton( { options, textContainer: verticalSkew, callback: transformShape, }, x, y ); x += skewYButton.getBounds().width + padding + 20; options.minValue = 0; options.maxValue = 200; x = 50; y = 275; label = this.createText('regX', x, y); x += label.getBounds().width + padding; transformX = this.createText('0', x, y, false); x += transformX.getBounds().width + padding + 15; const transformXButton = this.createSpinButton( { options, textContainer: transformX, callback: transformShape, }, x, y ); x += transformXButton.getBounds().width + padding; label = this.createText('regY', x, y); x += label.getBounds().width + padding; transformY = this.createText('0', x, y, false); x += transformY.getBounds().width + padding + 15; this.createSpinButton( { options, textContainer: transformY, callback: transformShape, }, x, y ); } createText(value, x, y, shouldAccesible = true) { const label = new createjs.Text(value, '18px Arial'); this.transformControlContainer.addChild(label); if (shouldAccesible) { AccessibilityModule.register({ displayObject: label, parent: this.transformControlContainer, role: AccessibilityModule.ROLES.NONE, accessibleOptions: { text: label.text, }, }); } label.set({ x, y }); return label; } createSpinButton(data, x, y) { const spinButton = new SpinButton(data); this.transformControlContainer.addChild(spinButton); this.transformControlContainer.accessible.addChild(spinButton); spinButton.set({ x, y }); return spinButton; } _showTreeGridTestCase() { this._clearScreen(); const row0 = { rowData: ['Class', 'Student Name', 'Roll No'], childrenData: 0, type: 'header', level: 1, }; const row1 = { rowData: ['III', 'Anish', '5'], childrenData: 1, type: 'cell', level: 1, }; const row2 = { rowData: ['X', 'Fida', '10'], childrenData: 1, type: 'cell', level: 2, }; const row3 = { rowData: ['XI', 'Sudhir', '20'], level: 3, type: 'cell', childrenData: 1, }; const row4 = { rowData: ['XI', 'Aniket', '25'], level: 4, type: 'cell', childrenData: 0, }; const row5 = { rowData: ['XI', 'Sudhir', '30'], level: 1, type: 'cell', childrenData: 0, }; const rows = [row0, row1, row2, row3, row4, row5]; const data = { rows, cellWidth: 265, cellHeight: 60, }; const treeGrid = new TreeGrid(data, 0); this._contentArea.addChild(treeGrid); this._contentArea.accessible.addChild(treeGrid); treeGrid.y = 20; } _showTreeTestCase() { this._clearScreen(); const twoWheelers = [ { label: 'Bicycle', childArr: [ { label: 'Mountain Bike', }, { label: 'Road Bike', }, { label: 'BMX/Trick Bike', }, ], }, { label: 'Motorcycle', childArr: [ { label: 'Cruiser', }, { label: 'Dirt Bike', }, { label: 'Sport Bike', }, { label: 'Touring Bike', }, ], }, ]; const threeWheelers = [{ label: 'Motor tricycle' }]; const fourWheelers = [ { label: 'Cars', childArr: [ { label: 'Hatchback', }, { label: 'Sedan', }, { label: 'MPV', }, { label: 'SUV', childArr: [ { label: 'Compact', }, { label: 'Mid-size', }, { label: 'Full-size', }, { label: 'Crossovers', childArr: [ { label: 'Subcompact', }, { label: 'Compact', }, { label: 'Mid-size', }, { label: 'Full-size', }, ], }, ], }, ], }, ]; const vehicleArr = [ { label: '2 Wheeler', childArr: twoWheelers, }, { label: '3 Wheeler', childArr: threeWheelers, }, { label: '4 Wheeler', childArr: fourWheelers, }, ]; const vehicles = { label: 'Vehicles', childArr: vehicleArr, }; const addAsTreeItem = (obj) => new TreeItem(obj.label, 0); const makeTree = (obj, parentContainer, parentItem) => { const element = addAsTreeItem(obj); parentContainer.addChild(element); parentContainer.accessible.addChild(element); if (!_.isEmpty(obj.childArr)) { const containerTree = new Tree(); element.addSubTree(containerTree); _.forEach(obj.childArr, (child) => { makeTree(child, containerTree, element); }); } parentItem.addTreeItem(element); }; const tree = new Tree(); const vehicleTreeItem = addAsTreeItem(vehicles); tree.addChild(vehicleTreeItem); tree.accessible.addChild(vehicleTreeItem); const vehicleTree = new Tree(); vehicleTreeItem.addSubTree(vehicleTree); _.forEach(vehicles.childArr, (child) => { makeTree(child, vehicleTree, vehicleTreeItem); }); this._contentArea.addChild(tree); this._contentArea.accessible.addChild(tree); } _mathTextCase() { this._clearScreen(); const options = { src: formulaImg1, label: '(a+b)^{2}=a^{2}+2ab+b^{2}', cjsScaleX: 1, cjsScaleY: 1, }; const mathText = new PlainTextMath(options); mathText.x = 200; mathText.y = 200; this._contentArea.addChild(mathText); this._contentArea.accessible.addChild(mathText); const option1 = { src: formulaImg2, label: 'a^{2}+b^{2}=c^{2}', cjsScaleX: 1, cjsScaleY: 1, }; const mathml = '<math xmlns ="http://www.w3.org/1998/Math/MathML"><mrow><msup><mi>a</mi><mn>2</mn></msup><mo>+</mo><msup><mi>b</mi><mn>2</mn></msup><mo> = </mo><msup><mi>c</mi><mn>2</mn></msup> </mrow></math>'; const text = new PlainTextMath(option1); text.x = 200; text.y = 250; this._contentArea.addChild(text); AccessibilityModule.register({ displayObject: text, role: AccessibilityModule.ROLES.MATH, }); this._contentArea.accessible.addChild(text); text.accessible.mathML = mathml; } _showTextFormatCase() { this._clearScreen(); this.textFormat = new createjs.Container(); this._contentArea.addChild(this.textFormat); AccessibilityModule.register({ displayObject: this.textFormat, role: AccessibilityModule.ROLES.NONE, }); this._contentArea.accessible.addChild(this.textFormat); let prefixText = 'Example of '; const PADDING = 7; const boldText = new FormatText( prefixText, 'Bold Text', AccessibilityModule.ROLES.FORMAT_TEXT_BOLD, 'bold', '22', 'Arial' ); this.textFormat.addChild(boldText); this.textFormat.accessible.addChild(boldText); boldText.y = PADDING; const codeText = new FormatText( prefixText, 'Computer Code', AccessibilityModule.ROLES.FORMAT_TEXT_CODE, '', '22', 'monospace' ); this.textFormat.addChild(codeText); this.textFormat.accessible.addChild(codeText); codeText.y = boldText.y + boldText.getBounds().height + PADDING; const deletedText = new FormatText( prefixText, 'Deleted Text', AccessibilityModule.ROLES.FORMAT_TEXT_DELETE, '', '22', 'Arial' ); this.textFormat.addChild(deletedText); this.textFormat.accessible.addChild(deletedText); deletedText.y = codeText.y + codeText.getBounds().height + PADDING; const emphasizeText = new FormatText( prefixText, 'Emphasize Text', AccessibilityModule.ROLES.FORMAT_TEXT_EMPHASIZE, 'italic', '22', 'Arial' ); this.textFormat.addChild(emphasizeText); this.textFormat.accessible.addChild(emphasizeText); emphasizeText.y = deletedText.y + deletedText.getBounds().height + PADDING; const italicText = new FormatText( prefixText, 'Italic Text', AccessibilityModule.ROLES.FORMAT_TEXT_ITALIC, 'italic', '22', 'Arial' ); this.textFormat.addChild(italicText); this.textFormat.accessible.addChild(italicText); italicText.y = emphasizeText.y + emphasizeText.getBounds().height + PADDING; const insertedText = new FormatText( prefixText, 'Inserted Text', AccessibilityModule.ROLES.FORMAT_TEXT_INSERT, '', '22', 'Arial' ); this.textFormat.addChild(insertedText); this.textFormat.accessible.addChild(insertedText); insertedText.y = italicText.y + italicText.getBounds().height + PADDING; const keybordtext = new FormatText( prefixText, 'Keybord Text', AccessibilityModule.ROLES.FORMAT_TEXT_KBD, '', '22', 'monospace' ); this.textFormat.addChild(keybordtext); this.textFormat.accessible.addChild(keybordtext); keybordtext.y = insertedText.y + insertedText.getBounds().height + PADDING; const preformatedTxt = 'Text in a pre element \n' + 'is displayed in a fixed-width\n' + 'font, and it preserves\n' + 'both spaces and\n' + 'line breaks'; const preformatedText = new FormatText( prefixText, preformatedTxt, AccessibilityModule.ROLES.FORMAT_TEXT_PREFORMAT, '', '22', 'monospace' ); this.textFormat.addChild(preformatedText); this.textFormat.accessible.addChild(preformatedText); preformatedText.y = keybordtext.y + keybordtext.getBounds().height + PADDING; const strikeText = new FormatText( prefixText, 'Strike Text', AccessibilityModule.ROLES.FORMAT_TEXT_STRIKETHROUGH, '', '22', 'Arial' ); this.textFormat.addChild(strikeText); this.textFormat.accessible.addChild(strikeText); strikeText.y = preformatedText.y + preformatedText.getBounds().height + PADDING; const sampleText = new FormatText( prefixText, 'Sample Text', AccessibilityModule.ROLES.FORMAT_TEXT_SAMPLE, '', '22', 'monospace' ); this.textFormat.addChild(sampleText); this.textFormat.accessible.addChild(sampleText); sampleText.y = strikeText.y + strikeText.getBounds().height + PADDING; const smallText = new FormatText( prefixText, 'SmallText', AccessibilityModule.ROLES.FORMAT_TEXT_SMALL, '', '12px', 'Arial' ); this.textFormat.addChild(smallText); this.textFormat.accessible.addChild(smallText); smallText.y = sampleText.y + sampleText.getBounds().height + PADDING; const strongText = new FormatText( prefixText, 'Strong Text', AccessibilityModule.ROLES.FORMAT_TEXT_STRONG, 'bold', '22', 'Arial' ); this.textFormat.addChild(strongText); this.textFormat.accessible.addChild(strongText); strongText.y = smallText.y + smallText.getBounds().height + PADDING; prefixText = 'Example of SubscriptText Log'; const subscriptText = new FormatText( prefixText, '2', AccessibilityModule.ROLES.FORMAT_TEXT_SUBSCRIPT, '', '22', 'Arial' ); this.textFormat.addChild(subscriptText); this.textFormat.accessible.addChild(subscriptText); subscriptText.y = strongText.y + strongText.getBounds().height + PADDING; prefixText = 'Example of SupscriptText 2'; const supscriptText = new FormatText( prefixText, '4', AccessibilityModule.ROLES.FORMAT_TEXT_SUPERSCRIPT, '', '22', 'Arial' ); this.textFormat.addChild(supscriptText); this.textFormat.accessible.addChild(supscriptText); supscriptText.y = subscriptText.y + subscriptText.getBounds().height + PADDING; const date = new Date(); prefixText = 'Example of Time '; const timeText = new FormatText( prefixText, `${date}`, AccessibilityModule.ROLES.FORMAT_TEXT_TIME, '', '16', 'Arial' ); this.textFormat.addChild(timeText); this.textFormat.accessible.addChild(timeText); timeText.y = supscriptText.y + supscriptText.getBounds().height + PADDING; prefixText = 'Example of '; const underLineText = new FormatText( prefixText, 'UnderLine Text', AccessibilityModule.ROLES.FORMAT_TEXT_UNDERLINE, '', '16', 'Arial' ); this.textFormat.addChild(underLineText); this.textFormat.accessible.addChild(underLineText); underLineText.y = timeText.y + timeText.getBounds().height + PADDING; prefixText = 'and'; const variableText = new FormatText( prefixText, 'Variable Text', AccessibilityModule.ROLES.FORMAT_TEXT_ITALIC, 'italic', '22', 'Arial' ); this.textFormat.addChild(variableText); this.textFormat.accessible.addChild(variableText); variableText.x = underLineText.x + underLineText.getBounds().width + PADDING; variableText.y = underLineText.y; const bounds = this._contentArea.getBounds(); this.textFormat.x = bounds.width * 0.5 - this.textFormat.getBounds().width * 0.5; this.textFormat.y = bounds.height * 0.5 - this.textFormat.getBounds().height * 0.5; const shape = new createjs.Shape(); shape.graphics .beginFill('#FFD64B') .drawRect(0, 0, bounds.width, bounds.height); this._contentArea.addChildAt(shape, 0); } }
const Home = () => { return <p className="homePage">Home page design starts here</p>; }; export default Home;
exports = module.exports = function(io) { io.sockets.on('connection', function (socket) { socket.on('chat message', function (msg, user) { console.log("Chatted"); io.emit('chat message', user + ": " + msg); var dt = new Date(); var txt = "\r\n" + user + ": " + msg + " - " + dt; var fs = require('fs'); fs.appendFile("chattext.txt", txt, function(err) { if(err) { return console.log(err); } }); }); }); }
export default { OPENPOP: 'OPENPOP', CLOSEPOP: 'CLOSEPOP', INPUTVALUE: 'INPUTVALUE', CLICKOK: 'CLICKOK', SELECTVALUE: 'SELECTVALUE', ADDMONTH: 'ADDMONTH', SUBMONTH: 'SUBMONTH', ADDYEAR: 'ADDYEAR', SUBYEAR: 'SUBYEAR', }
import React, { Component } from 'react'; import { StyleSheet } from 'react-native'; import { Button, Icon, Text } from 'native-base'; const BackButton = ({ goBackFn, text }) => ( <Button onPress={goBackFn} title="backButton" transparent> <Icon name="arrow-back" style={[styles.backIcon, !!text && styles.isTextIcon]} /> {text && <Text style={styles.text}>{text}</Text>} </Button> ); const styles = StyleSheet.create({ backIcon: { fontSize: 34, }, isTextIcon: { marginRight: 0, marginLeft: 8, }, text: { paddingLeft: 5, }, }); export default BackButton;
class Quiz { constructor(){ this.restartButton = createButton('Restart'); } diaplay(){ } getState(){ var gameStateRef = database.ref('gameState'); gameStateRef.on("value",function(data){ gameState = data.val(); }) } update(state){ database.ref('/').update({ gameState: state }); } async start(){ if(gameState === 0){ contestant = new Contestant(); var contestantCountRef = await database.ref('contestantCount').once("value"); if(contestantCountRef.exists()){ contestantCount = contestantCountRef.val(); contestant.getCount(); } question = new Question() question.display(); } } play(){ //this.restartButton.hide() question.hide(); var posy = 300; Contestant.getPlayerInfo(); for(var plr in allContestants){ var correctAns = "2"; if(correctAns === allContestants[plr].answer){ fill ("green") }else{ fill ("red") } textSize(15); text (allContestants[plr].name + ": " + allContestants[plr].answer,290,posy); posy+=20 } if(gameState === 1 ){ // Background("yellow") document.body.style.backgroundColor = "yellow"; this.restartButton.position(290,390); //location.reload(); this.restartButton.mousePressed(()=>{ clear(); n = ON; this.restartButton.hide(); //if(gameState !== 0){ database.ref('restartPressed').once("value",function (d){ contestant.updateReCount(d.val()+1); restartPressed = d.val()+1; }); // } }); if(restartPressed === contestantCount){ gameState = 0; clear(); this.restartButton.hide() //if( n===1){ location.reload(); n =2; //} quiz.update(0); contestantCount = 0; contestant.updateCount(0); console.log("all restart"); question = new Question; clear (); question.display(); this.restartButton.show(); location.reload(); database.ref("contestants").remove(); restartPressed = 0; contestant.updateReCount(restartPressed); } } // else { document.body.style.backgroundColor = "pink"; } } //write code to change the background color here //write code to show a heading for showing the result of Quiz //write condition to check if contestantInfor is not undefined //write code to add a note here //write code to highlight contest who answered correctly changeBGC(){ document.body.style.background = 'light green'; } }
const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; const GoogleStrategy = require('passport-google-oauth20').Strategy; const User = require('../models/User'); const bcrypt = require('bcrypt'); passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' }, (email, password, done) => { User.findOne({ email }) .then(foundUser => { if (!foundUser) { done(null, false, { message: 'Incorrect email' }); return; } if (!bcrypt.compareSync(password, foundUser.password)) { done(null, false, { message: 'Incorrect password' }); return; } done(null, foundUser); }) .catch(err => done(err)); } )); ///////// NUEVA ESTRATEGIA DE GOOGLE // Nueva estrategia: Google Strategy. passport.use( new GoogleStrategy( { clientID: process.env.GOOGLE_KEY, clientSecret: process.env.GOOGLE_SECRET, callbackURL: process.env.GOOGLE_CALLBACK }, async (_, __, profile, callback) => { console.log("PROFILE: ", profile) // Tenemos que verificar si hay un usuario con ese googleID, Si existe, lo dejamos entrar, si no... lo creamos e iniciamos su sesion const user = await User.findOne({ googleID: profile.id }) if (user) { return callback(null, user) } const newUser = await User.create({ googleID: profile.id, email: profile.emails[0].value, avatar: profile.photos[0].value }) return callback(null, newUser) } ) )
const express = require('express'); const router = express.Router(); const adminController = require('../controllers/adminController'); router.get('/formulario', adminController.admin); /*agregar ruta por post */ module.exports = router;
//guardara la autentication en el local storage //pero no sera visible localStorageService es de angular-local-storage.js (function () { 'use strict'; angular.module('app') .factory('authenticationService', authenticationService); authenticationService.$inject = ['$http', '$state', 'localStorageService']; function authenticationService($http, $state, localStorageService) { var apiUrl = 'http://localhost/WebDeveloper.API/'; var service = {} service.login = login; return service; function login(user) { var url = apiUrl + 'Token'; var data = 'grant_type=password&username=' + user.userName + '&password=' + user.password; $http.post(url, data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .then(function (result) { localStorageService.set('authorizationData', { token: result.access_token, userName: user.userName }); $state.go('person'); }); } } })();
function splitKakaoTextIntoMessage(data) { const re = /\[[^\n\[\]]*\]\s\[오[전|후]\s\d:\d{2}\]/g; const messages = [...data.matchAll(re)]; const idxes = []; messages.forEach((message) => { idxes.push(message.index); }); idxes.push(data.length); messages.splice(0, messages.length); for (var i = 0; i < idxes.length - 1; i++) { messages.push(data.substring(idxes[i], idxes[i + 1])); } return messages; } function splitKaKaoMassageIntoMessageElements(kakaoMessage) { const messageElements = {}; const first = kakaoMessage.indexOf("]"); const second = kakaoMessage.indexOf("]", first + 1); const end = kakaoMessage.length; messageElements["name"] = kakaoMessage.substring(1, first); messageElements["date"] = kakaoMessage.substring(first + 3, second); messageElements["content"] = kakaoMessage.substring(second + 1, end); messageElements["password"] = "1234"; messageElements["kakao"] = true; return messageElements; } function convertKakaoMessageIntoComentsJson(data) { data = splitKakaoTextIntoMessage(data); for (var i = 0; i < data.length; i++) { data[i] = splitKaKaoMassageIntoMessageElements(data[i]); } return data; } export { convertKakaoMessageIntoComentsJson };
var _viewer = this; var height = jQuery(window).height() - 50; var width = jQuery(window).width() - 200; //取消行点击事件 $(".rhGrid").find("tr").unbind("dblclick"); //每一行添加编辑和删除 $("#TS_BM_GROUP_DEPT .rhGrid").find("tr").each(function (index, item) { if (index != 0) { var dataId = item.id; $(item).find("td[icode='BUTTONS']").append( '<a class="rhGrid-td-rowBtnObj rh-icon" id="TS_BM_GROUP_DEPT_look" operCode="optLookBtn" rowpk="' + dataId + '"><span class="rh-icon-inner">查看</span><span class="rh-icon-img btn-edit"></span></a>' + '<a class="rhGrid-td-rowBtnObj rh-icon" id="TS_BM_GROUP_DEPT_delete" actcode="delete" rowpk="' + dataId + '"><span class="rh-icon-inner-notext">删除</span><span class="rh-icon-img btn-delete"></span></a>' ); // 为每个按钮绑定卡片 bindCard(); } }); //绑定的事件 function bindCard() { //当行删除事件 jQuery("td [id='TS_BM_GROUP_DEPT_delete']").unbind("click").bind("click", function() { var pkCode = jQuery(this).attr("rowpk"); rowDelete(pkCode,_viewer); $("#TS_COMM_CATALOG-refresh").trigger("click"); }); //查看 jQuery("td [id='TS_BM_GROUP_DEPT_look']").unbind("click").bind("click", function () { var pkCode = jQuery(this).attr("rowpk"); //$(".hoverDiv").css('display','none'); openMyCard(pkCode, true); }); } /* * 删除前方法执行 */ _viewer.beforeDelete = function(pkArray) { showVerify(pkArray,_viewer); } //列表操作按钮 弹dialog function openMyCard(dataId, readOnly, showTab) { var temp = { "act": UIConst.ACT_CARD_MODIFY, "sId": _viewer.servId, "parHandler": _viewer, "widHeiArray": [width, height], "xyArray": [50, 50] }; temp[UIConst.PK_KEY] = dataId; if (readOnly != "") { temp["readOnly"] = readOnly; } if (showTab != "") { temp["showTab"] = showTab; } var cardView = new rh.vi.cardView(temp); cardView.show(); } _viewer.getBtn("impDept").unbind("click").bind("click", function(event) { // var configStr = "TS_ORG_DEPT,{'TARGET':'DEPT_CODE~DEPT_NAME','SOURCE':'DEPT_CODE~DEPT_NAME'," + // "'HIDE':'DEPT_CODE','TYPE':'multi','HTMLITEM':''}"; var configStr = "TS_ORG_DEPT_ALL,{'TYPE':'multi','sId':'TS_ORG_DEPT','pvlg':'CODE_PATH'}"; var options = { "config" :configStr, // "params" : {"_TABLE_":"SY_ORG_USER"}, "params" : {"USE_SERV_ID":"TS_ORG_DEPT"}, "parHandler":_viewer, "formHandler":_viewer.form, "replaceCallBack":function(idArray,nameArray) {//回调,idArray为选中记录的相应字段的数组集合 var codes = idArray; var names = nameArray; var paramArray = []; var codestr = ""; for(var i=0;i<codes.length;i++){ if(i==0){ codestr=""+codes[i]+""; }else{ codestr+=","+codes[i]+""; } } var paramstr = {}; paramstr["codes"]=codestr; paramstr["G_ID"]=_viewer.getParHandler()._pkCode; var resultstr = FireFly.doAct("TS_BMLB_BM","getMaxDept",paramstr); /*for(var i=0;i<codes.length;i++){ var param = {}; //群组ID param.G_ID = _viewer.getParHandler()._pkCode; //用户编码 param.USER_DEPT_CODE = codes[i]; //用户名称 param.USER_DEPT_NAME = names[i]; //选取类型 1人员 param.G_TYPE = 2; paramArray.push(param); }*/ /* var batchData = {}; batchData.BATCHDATAS = paramArray; //批量保存 var rtn = FireFly.batchSave(_viewer.servId,batchData,null,2,false);*/ _viewer.refresh(); } }; //2.用系统的查询选择组件 rh.vi.rhSelectListView() // var queryView = new rh.vi.rhSelectListView(options); var queryView = new rh.vi.rhDictTreeView(options); queryView.show(event,[],[0,495]); }); //从excel中导入人员 const IMPORT_FILE_ID = _viewer.servId + "-impUserByExcel"; var $importUser = $('#' + IMPORT_FILE_ID); var $impFile = jQuery('#' + _viewer.servId + '-impFile'); //避免刷新数据重复添加 if ($importUser.length === 0) { var config = { "SERV_ID": _viewer.servId, "TEXT": "导入机构", "FILE_CAT": "", "FILENUMBER": 1, "BTN_IMAGE": "btn-imp", // "VALUE": 15, "TYPES": "*.xls;*.xlsx;", "DESC": "" }; var file = new rh.ui.File({ "id": IMPORT_FILE_ID, "config": config }); file._obj.insertBefore($impFile); $("#" + file.time + "-upload span:first").css('padding', '0 7px 2px 20px'); jQuery('<span class="rh-icon-img btn-imp"></span>').appendTo($("#" + file.time + "-upload")); file.initUpload(); file.afterQueueComplete = function (fileData) {// 这个上传队列完成之后 console.log("这个上传队列完成之后" + fileData); for (var propertyName in fileData) { var filesize = fileData[propertyName].FILE_SIZE; if(filesize>1024*1024*20){ alert("文件超过20M"); file.clear(); return false; } var fileId = fileData[propertyName].FILE_ID; /*alert(fileData.fileId);*/ if (fileId) { var data = {}; // data.XM_SZ_ID = xmSzId; data.G_ID = _viewer.getParHandler()._pkCode; data.FILE_ID = fileId; FireFly.doAct(_viewer.servId, "saveFromExcel", data, false, false, function (data) { rh.ui.File.prototype.downloadFile(data.FILE_ID, "test"); _viewer.refresh(); alert(data._MSG_); }); } } file.clear(); }; } $importUser.find('object').css('cursor', 'pointer'); $importUser.find('object').css('z-index', '999999999'); $importUser.find('object').css('width', '100%'); $importUser.attr('title', '导入文件为excel格式文件,内容为无标题的单列数据,一行数据为一个用户,数据为人力资源编码、统一认证号、身份证号'); //导入模板下载 $impFile.unbind('click').bind('click', function () { window.open(FireFly.getContextPath() + '/ts/imp_template/可见机构导入模板.xls'); });
import React from 'react'; import { connect } from 'react-redux'; import { Field, reduxForm, change } from 'redux-form'; import { MdSettings, MdDateRange } from 'react-icons/lib/md'; import { addSettingMember } from '../../../actions/member.actions'; import { getMemberSelected } from '../../../reducers/member.reducers'; import './scss/styles.scss'; import loader from '../../../assets/images/loader.svg'; class SettingMember extends React.Component { constructor(props) { super(props); this.state = { member: { firstName: '', lastName: ''}, settings: null }; } componentWillReceiveProps(nextProps) { if(nextProps.selected){ this.setState({ ...this.state, member: { ...nextProps.selected.member } }); if(nextProps.selected.settings){ this.setState({ member: { ...nextProps.selected.member }, settings: { [nextProps.labelSession]: (nextProps.selected.settings[nextProps.labelSession]) ? { ...nextProps.selected.settings[nextProps.labelSession] } : null }, }, ()=>{ this.changeField(this.state, nextProps.labelSession); }); } } }; changeField = (state, session) => { if(state.settings[session]){ if(state.settings[session].language) this.props.dispatch(change('settingForm', 'language', state.settings[session].language)); if(state.settings[session].admission) this.props.dispatch(change('settingForm', 'admission', state.settings[session].admission)); if(state.settings[session].payment) this.props.dispatch(change('settingForm', 'payment', state.settings[session].payment)); if(state.settings[session].payMonth) this.props.dispatch(change('settingForm', 'payMonth', state.settings[session].payMonth)); if(state.settings[session].notificationByEmail) this.props.dispatch(change('settingForm', 'notificationByEmail', state.settings[session].notificationByEmail)); if(state.settings[session].notificationBySms) this.props.dispatch(change('settingForm', 'notificationBySms', state.settings[session].notificationBySms)); } } submit = async (values, dispatch, props) => { dispatch(change('settingForm', 'submitting', true)); await new Promise(resolve => setTimeout(resolve, 500)); var session = props.labelSession; var settings = { [session]: values }; return dispatch(addSettingMember(settings)); }; render() { return ( <div className="setting-member"> <div className="menu"> <p>Paramètres</p> <ul> <li><a className="active"><MdSettings /> Géneral</a></li> <li><a><MdDateRange /> Calendrier</a></li> </ul> </div> <div className="corps"> <p> {this.state.member.firstName} {this.state.member.lastName} </p> <form onSubmit={this.props.handleSubmit(this.submit)}> <table> <tbody> <tr> <td className="formControl"> <label>Langue : </label> <Field name="language" component="select"> <option >Choisir....</option> <option value="fr">Français</option> <option value="en">Anglais</option> </Field> </td> </tr> <tr> <td className="formControl"> <label>Frais d'inscription : </label> <Field name="admission" component="input" type="text" placeholder="Entrer un montant" /> </td> </tr> <tr> <td className="formControl"> <label>Combien souhaite cotiser ? / mois : </label> <Field name="payment" component="input" type="text" placeholder="Entrer un montant" /> </td> </tr> <tr> <td className="formControl"> <label>Quand souhaite béneficier ? : </label> <Field name="payMonth" component="select"> <option >Choisir....</option> <option value="1">Janvier</option> <option value="2">Février</option> <option value="3">Mars</option> <option value="4">Avril</option> <option value="5">Mai</option> <option value="6">Juin</option> <option value="7">Juillet</option> <option value="8">Aout</option> <option value="9">Septembre</option> <option value="10">Octobre</option> <option value="11">Novembre</option> <option value="12">Decembre</option> </Field> </td> </tr> <tr> <td className="formControl checkbox"> <Field name="notificationByEmail" id="notificationByEmail" component="input" type="checkbox" /> <label>Souhaitez-vous recevoir les notifications par email des actions faites par vous ou de l'adminstrateur ?</label> </td> </tr> <tr> <td className="formControl checkbox"> <Field name="notificationBySms" id="notificationBySms" component="input" type="checkbox" /> <label>Souhaitez-vous recevoir les notifications par sms des actions faites par vous ou de l'adminstrateur ?</label> </td> </tr> <tr> <td className="btnForm text-right"> <div className="loader"> { (this.props.submitting) ? (<img src={loader}/>) : ('') } </div> <button type="submit" disabled={this.props.pristine || this.props.submitting}> Envoyer </button> </td> </tr> </tbody> </table> </form> </div> </div> ); }; }; SettingMember = reduxForm({ form: 'settingForm' })(SettingMember); const mapStateToProps = state => ({ selected: getMemberSelected(state.members), labelSession: state.session.labelSession }); export default connect(mapStateToProps)(SettingMember);
import { shallowMount } from "@vue/test-utils"; import Post from "./Post.vue"; describe("PostPage", () => { test("has the proper name", () => { const wrapper = shallowMount(Post, { stubs: ["router-link"], mocks: { $store: { state: { posts: [{ title: "foo", body: "bar" }] } }, $route: { params: { id: 0 } } } }); expect(wrapper.vm.$options.name).toBe("page-post"); }); });
var a1a1 = .15; var a2a2 = .35; var a1a2 = 1 - (a1a1 + a2a2); var p = a1a1 + (a1a2 / 2); var q = 1 - p; function create_next_generation() { a1a1 = p * p; a2a2 = q * q; a1a2 = 2 * p * q; } function rnd(number, decimals) { var shifter = Math.pow(10, decimals || 2); return Math.round(number * shifter) / shifter; } console.log("generation 0:", rnd(a1a1), rnd(a1a2), rnd(a2a2)); for (var i = 1; i < 10; i++) { create_next_generation(); console.log("generation " + i + ":", rnd(a1a1), rnd(a1a2), rnd(a2a2)); }
import './pattern-control.less'; import template from './pattern-control.html'; import controller from './pattern-control.controller'; export default { bindings: {}, template, controller }
define(function (require, exports, module) { var Class, mask, closeTpl, titleTpl; mask = require('modules/widget/dialog/mask'); closeTpl = '<a href="javascript:void(0);" class="ico_close J_close">关闭</a>'; titleTpl = '<h3 class="dialog_title J_title">{title}</h3>'; /** * Example : * require(['dialog'], function(Dialog) { * var dialog = new Dialog('<html/>', { * width : 300, * height : 300, * onShow : fn, * onHide : fn * }); * }); * * PS: 没有针对IE6下不支持position:fixed做处理 */ Class = Backbone.View.extend({ options: { width: '', //box宽度 height: '', //box高度 hasMark: true, //是否显示遮罩层 hasClose: true, //是否显示关闭按钮 isRemoveAfterHide: true, //隐藏后是否自动销毁相关dom isAutoShow: true, //是否自动显示dialog title: '', className: '', effect: 'fade', //显示效果 可选none, fade draggable: true, onShow: function () {}, onHide: function () {} }, events: { 'click .J_close': '_close' }, initialize: function (obj) { if(obj){ this.options = _.extend(this.options, obj); } this._status = false; this.$el = $('<div class="dialog"/>').append(this.$el.show()) .addClass(this.options.className) .appendTo(document.body); this._isShowTitle(); this._isShowClose(); this._adjustPosition(); this.on('show', function () { this._status = true; this._toggle('show'); }); this.on('hide', function () { this._status = false; this._toggle('hide'); }); this.on('show', this.options.onShow, this.$el); this.on('hide', this.options.onHide, this.$el); if (this.options.isAutoShow) { this.trigger('show'); } this._setDraggable(); }, _getStyle: function (style) { var width, height; width = this.options.width; height = this.options.height; if (height && this.options.title != '') { height = height + 30; } var style = { 'width': width, 'height': height, 'margin-left': -(width / 2), 'margin-top': -(height / 2) }; return style; }, _isShowTitle: function () { var title = this.options.title; if (title != '') { this.$title = $(titleTpl.replace('{title}', title)).prependTo(this.$el); } }, _isShowClose: function () { if (this.options.hasClose) { $(closeTpl).attr('hidefocus', 'true').appendTo(this.$el); } }, _close: function () { this.trigger('hide'); }, _toggle: function (action) { var effect, temp; effect = this.options.effect; temp = this; if (action == 'show') { if (effect === 'none') { this.$el.css('display', 'block'); } else if (effect === 'fade') { this.$el.fadeIn(); } } else if (action == 'hide') { if (effect === 'none') { this.$el.css('display', 'none'); } else if (effect === 'fade') { this.$el.fadeOut(); } if (this.options.isRemoveAfterHide) { setTimeout(function () {temp.$el.remove();}, 2000); } } this._toggleMask(action); }, _toggleMask: function (action) { if (this.options.hasMark) { if (action == 'show') { mask.show(); } else if (action == 'hide') { mask.hide(); } } }, _adjustPosition: function () { var size = { width: this.options.width || this.$el.innerWidth(), height: this.options.height ? (this.options.title != '' ? this.options.height+30 : this.options.height) : this.$el.innerHeight() }; this.$el.css(_.extend({ marginLeft: -(size.width / 2), marginTop: -(size.height / 2) }, size)); }, _setDraggable: function() { var self = this, draggable = this.options.draggable, title = this.options.title; if ( draggable ) { require(["modules/widget/jquery-draggable-min"], function() { var config = { containment: mask.element || "body", scroll: false }, ele; if ( title ) { ele = "h3.J_title"; config.handle = ele; $(ele).css("cursor", "move"); } self.$el.draggable(config); }); } }, status: function () { return this._status ? 'show' : 'hide'; }, show: function () { this.trigger('show'); return this; }, hide: function () { this.trigger('hide'); return this; }, destroy: function () { this.$el.remove(); mask.hide(); }, resize: function (width, height) { this.options.width = width; this.options.height = height; this._adjustPosition(); return this; }, title: function (title) { this.$title && this.$title.html(title); return this; } }); function Dialog(content, options) { options = options || {}; options.el = content || '<b></b>'; return new Class(options); } return Dialog; });
import React from 'react'; import './footer.css'; import { FaLinkedin } from 'react-icons/fa' import { CgMail } from 'react-icons/cg' import { GiPhone } from 'react-icons/gi' import { IoLogoWhatsapp } from 'react-icons/io' import { FaInstagram } from 'react-icons/fa'; const Footer = () =>{ return( <div className='footerformat'> <div className='subscribeformat'> <div className='subscribelabels'> <label className='subscribetext'>Subscribe</label> <p className='getupdatestext'>Get the latest updates and offers</p> </div> <div className='emaildetailsubmit'> <input type='text' placeholder='Your Email' className='emailtext'/> <button className='subscribebutton'>SUBSCRIBE</button> </div> </div> <div className='followmeformat'> <label className='followustext'>Contact Us</label> <div className='socialmedia'> <FaLinkedin className='linkedin' onClick={()=>window.location.href = 'https://www.linkedin.com/in/ankit-jaiswal-b51b57129'}/> <CgMail className='linkedin' onClick={()=>window.location.href = 'mailto:ankitjswl56@gmail.com'}/> <GiPhone className='linkedin' onClick={()=>window.location.href = 'tel:+917206230848'}/> <IoLogoWhatsapp className='linkedin'onClick={()=>window.location.href = 'https://api.whatsapp.com/send?phone=+917206230848'}/> <FaInstagram className='linkedin' onClick={()=>window.location.href = 'https://www.instagram.com/ohankitx'}/> </div> </div> </div> ) } export default Footer;
import React, { useEffect } from 'react'; import { observer, inject } from "mobx-react"; import Button from '@material-ui/core/Button'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogTitle from '@material-ui/core/DialogTitle'; const DeleteUserDialog = inject("store")( observer((props) => { useEffect(() => { const ENTER_KEY_CODE = 13 const enterSubmit = (e) => { if (e.keyCode == ENTER_KEY_CODE) { const submitBtn = document.getElementById("submit") submitBtn.click() } } window.addEventListener('keyup', enterSubmit) return function cleanup() { window.removeEventListener('keyup', enterSubmit) } }, []) const handleClose = () => { props.store.set( "isDeleteUserOpen", false ) } const handleUserDelete = async () => { try { const userId = props.store.targetUserForDetails.id await props.store.deleteUser(userId) props.store.set( "targetUserForDetails", {} ) handleClose() } catch (e) { } } return ( <div> {props.store.isDeleteUserOpen && <Dialog open={props.store.isDeleteUserOpen} onClose={handleClose} style={{ minWidth: 350 }} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title"> {`사용자 탈퇴`} </DialogTitle> <div style={{ flex: "1 1 auto", padding: "8px 24px", overflowY: "auto", }}> <div style={{ fontSize: "1rem", fontWeight: 400, lineHeight: 1.5, letterSpacing: "0.00938em", margin: 0, marginBottom: 12, color: "rgba(0,0,0,0.84)" }}> <div> {`사용자 명 : ${props.store.targetUserForDetails.name}`} </div> <div style={{ marginTop: 10 }}> {`사용자 이메일 : ${props.store.targetUserForDetails.email}`} </div> <div style={{ marginTop: 10 }}> 해당 사용자를 정말로 탈퇴시키겠습니까? </div> </div> </div> <DialogActions> <Button onClick={handleClose} color="primary"> 취소 </Button> <Button id="submit" onClick={handleUserDelete} color="primary" autoFocus> 탈퇴 </Button> </DialogActions> </Dialog>} </div> ); })) export default DeleteUserDialog;
import { observable, action } from 'mobx' class CartStore { @observable qtdCart = 0 @observable qtdTeste = 10 @action setQuantity(value){ this.qtdCart = value } } export default CartStore = new CartStore()
/** * MyBishop * @constructor * @param game - game instance where bishop will be used * @param {string} color - piece's color * @param representation - piece's internal representation for the server module * @param initialPosition - piece's initial position in the scene * @param file - file where piece object is stored (for realistic pieces) */ function MyBishop(game, color, representation, initialPosition, file) { MyPiece.call(this, game, color, representation, initialPosition, file); this.primitiveComponents = [ new MyCylinder(game.scene,[1, 1, 1, 5, 10, 1, 1]), new MyCylinder(game.scene,[1, 0.7, 0.3, 5, 10, 0, 0]), new MySphere(game.scene, [1, 5, 10]), new MyCylinder(game.scene,[1, 1, 1, 5, 10, 0, 0]), new MyCylinder(game.scene,[1, 0.65, 1, 5, 10, 0, 0]), new MyCylinder(game.scene,[1, 1, 0.65, 5, 10, 0, 0]), new MyCylinder(game.scene,[1, 1, 0, 5, 10, 0, 0]) ]; } MyBishop.prototype = Object.create(MyPiece.prototype); MyBishop.prototype.constructor = MyBishop; /** * Displays the bishop using previously defined primitives */ MyBishop.prototype.displayWithPrimitives = function() { this.scene.pushMatrix(); // base this.scene.pushMatrix(); this.scene.rotate(-Math.PI/2, 1, 0, 0); this.scene.scale(1, 1, 0.5); this.primitiveComponents[0].display(); this.scene.popMatrix(); this.scene.pushMatrix(); this.scene.rotate(-Math.PI/2, 1, 0, 0); this.scene.translate(0, 0, 0.25); this.scene.scale(1, 1, 1.5); this.primitiveComponents[1].display(); this.scene.popMatrix(); this.scene.pushMatrix(); this.scene.rotate(-Math.PI/2, 1, 0, 0); this.scene.translate(0, 0, 1.75); this.scene.scale(0.3, 0.3, 0.5); this.primitiveComponents[0].display(); this.scene.popMatrix(); // inverted cone this.scene.pushMatrix(); this.scene.rotate(-Math.PI/2, 1, 0, 0); this.scene.translate(0, 0, 1.90); this.scene.scale(0.51, 0.51, 0.45); this.primitiveComponents[4].display(); this.scene.popMatrix(); // normal cylinder this.scene.pushMatrix(); this.scene.rotate(-Math.PI/2, 1, 0, 0); this.scene.translate(0, 0, 2.35); this.scene.scale(0.51, 0.51, 0.45); this.primitiveComponents[3].display(); this.scene.popMatrix(); // 3/4 height top cone this.scene.pushMatrix(); this.scene.rotate(-Math.PI/2, 1, 0, 0); this.scene.translate(0, 0, 2.8); this.scene.scale(0.51, 0.51, 0.3); this.primitiveComponents[5].display(); this.scene.popMatrix(); // Top cone this.scene.pushMatrix(); this.scene.rotate(-Math.PI/2, 1, 0, 0); this.scene.translate(0, 0, 3.1); this.scene.scale(0.335, 0.335, 0.42); this.primitiveComponents[6].display(); this.scene.popMatrix(); // Sphere at the top this.scene.pushMatrix(); this.scene.translate(0, 3.535, 0); this.scene.scale(0.1, 0.1, 0.1); this.primitiveComponents[2].display(); this.scene.popMatrix(); this.scene.popMatrix(); }
var url = "https://fcc-weather-api.glitch.me/api/current?"; var res, temp, celsius; $(document).ready(function() { //if geolocation is available, do ajax call if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var lat = position.coords.latitude; var lon = position.coords.longitude; getWeather(lat, lon); }); } else { alert("Geolocation unavailable. Please refresh page and allow location sharing."); } }); $(document).ajaxStop(function(){ $("#cel").click(function(){ $("#temperature").text(celsius); $("#fah").css("border", "none"); $("#cel").css("border", "0.05em solid white"); $("#cel").css("background-color", "rgb(120, 210, 180)"); $("#fah").css("background-color", "rgb(100, 190, 160)"); }); $("#fah").click(function(){ $("#temperature").text(Math.round(celsius * 9 / 5 + 32)); $("#cel").css("border", "none"); $("#fah").css("border", "0.05em solid white"); $("#fah").css("background-color", "rgb(120, 210, 180)"); $("#cel").css("background-color", "rgb(100, 190, 160)"); }); }); function getWeather(lat, lon) { $.ajax({ url: url + "lat=" + lat + "&lon=" + lon, success: function(result) { res = result; temp = result.weather[0].main; $("#condition").text(temp); $("#location").text(result.name); $("#icon").html(getIcon(temp)); celsius = result.main.temp; $("#temperature").text(celsius); $("img").css("height", "5em"); $(".title").animate({ opacity: 0 }, 0); $(".inner-container").animate({ opacity: 1 }, 1000); } }); } function getIcon(weather) { switch(weather) { case "Sunny": icon = "<i class=\"wi wi-day-sunny\"></i>"; return icon; case "Clouds": icon = "<i class=\"wi wi-day-cloudy\"></i>"; return icon; case "Windy": icon = "<i class=\"wi wi-day-windy\"></i>"; return icon; case "Rain": icon = "<i class=\"wi wi-day-rain\"></i>"; return icon; case "Clear": icon = "<i class=\"wi wi-night-clear\"></i>"; return icon; } }
#!/usr/bin/env node require('dotenv').config() const Octokit = require('@octokit/rest') const octokit = new Octokit({ auth: process.env.GH_AUTH_TOKEN, previews: ['dorian-preview'] }) const [, , ...args] = process.argv const owner = args const options = octokit.repos.listForOrg.endpoint.merge({ org: owner, type: 'all' }) const RequestPromises = [] octokit .paginate(options) .then(repositories => { for (const repository of repositories) { if (!repository.archived) { const repo = repository.name RequestPromises.push(octokit.repos.checkVulnerabilityAlerts({ owner, repo }).then(response => { return true }).catch(error => { return `${owner}/${repo}` })) } } Promise.all(RequestPromises).then(responses => { if (responses.every(value => { return value === true })) { console.log('Success! All repos have security vulnerability alerts enabled') } else { const reposWithoutVulnerabilityAlerts = responses.filter(result => result !== true) console.log(`Failure! Repos without security vulnerability alerts enabled: ${reposWithoutVulnerabilityAlerts} `) } }) })
const express = require('express'), path = require('path'), morgan = require('morgan'), mysql = require('mysql'), myConnection = require('express-myconnection'); const app = express(); // importing routes const customerRoutes = require('./routes/customer'); // settings app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); // middlewares app.use(morgan('dev')); // Initialize DB var databaseName = process.env.DB_NAME || 'nodejs2'; var con = mysql.createConnection({ host: process.env.DB_HOST || 'localhost', port: process.env.DB_PORT || 3306, user: process.env.DB_USER || 'root', password: process.env.DB_PW || 'root' }); con.connect((err)=>{ if(err) throw err; con.query("CREATE DATABASE IF NOT EXISTS "+databaseName+";", (err, result)=>{ if(err) throw err; var con = mysql.createConnection({ host: process.env.DB_HOST || 'localhost', port: process.env.DB_PORT || 3306, user: process.env.DB_USER || 'root', password: process.env.DB_PW || 'root', database: databaseName }); con.query("CREATE TABLE IF NOT EXISTS customer (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL, address VARCHAR(100) NOT NULL, phone VARCHAR(15));", (err, result)=>{ if(err) throw err; app.use(myConnection(mysql, { host: process.env.DB_HOST || 'localhost', user: process.env.DB_USER || 'root', password: process.env.DB_PW || 'root', port: process.env.DB_PORT || 3306, database: databaseName }, 'single')); app.use(express.urlencoded({extended: false})); // routes app.use('/', customerRoutes); // static files app.use(express.static(path.join(__dirname, 'public'))); // starting the server app.listen(app.get('port'), () => { console.log(`server on port ${app.get('port')}`); }); }); }); });
const express = require("express"); const authMiddleware = require("../middleware/authmiddleware"); const blogRouter = express.Router(); const Blog = require("../models/blog"); blogRouter.get("/getblogs", async (req, res) => { try { const blogs = await Blog.find(); res.status(200).json(blogs); } catch (err) { res.status(404).json(err); } }); blogRouter.get("/getblog/:id", async (req, res) => { try { const blog = await Blog.findById(req.params.id); res.status(200).json(blog); } catch (err) { res.status(404).json(err); } }); blogRouter.get("/getcomments/:id", async (req, res) => { try { const comments = await Blog.findById(req.params.id); res.status(200).json(comments.comment); } catch (err) { res.status(404).json(err); } }); blogRouter.post("/createBlog", async (req, res) => { try { const blog = new Blog({ title: req.body.title, image: req.body.image, content: req.body.content, }); await blog.save(); res.status(200).json(blog); } catch (err) { res.status(404).json(err); } }); blogRouter.delete("/deleteBlog", async (req, res) => { const blog = await Blog.deleteOne({ title: req.body.title }).then(function(){ res.json("Data deleted"); // Success }).catch(function(error){ res.json(error); // Failure }); }); blogRouter.put("/blog/comment/:id", async (req, res) => [ Blog.findOneAndUpdate( { _id: req.params.id }, { $push: { comment: req.body.comment, }, } ).then((result, err) => { try { res.json({ updated_list: result, }); } catch (err) { res.json(err); } }), ]); blogRouter.put("/blog/likes/:id", async (req, res) => { const blog = await Blog.findById(req.params.id, (err, blog) => { if (err) { res.status(404).json(err); } else { blog.likesCount = blog.likesCount + 1; blog.save(); res.status(200).json(blog); } }); }); //update blog blogRouter.put("/blog", async (req, res) => { const blog = await Blog.findOne({title: req.body.title}); if(req.body.image) { blog.image = req.body.image; } if(req.body.content) { blog.content = req.body.content; } try { blog.save(); } catch (error) { res.json(error); } res.status(200).json({ message: "Blog updated successfully!" }); }); module.exports = blogRouter;
/* jshint strict:false */ module.exports = { options: { join: true }, "src": { files: { 'dist/js/main.js': [ 'src/coffee/init.coffee', 'src/coffee/config/*.*', 'src/coffee/service/*.*', 'src/coffee/**/*.*' ] } } }