text
stringlengths
7
3.69M
import { Card } from 'react-bootstrap' import Visualizer from './Visualizer' import Button from 'react-bootstrap/Button'; import { useState } from 'react' import muteIcon from './mic-fill.svg'; import unmute from './mic-mute-fill.svg'; export default function UserCard({username, mediaStream, play}) { const [mute, setMute] = useState(false); //are we muted? /** * TODO: * 1. Fix the visualizer on the bottom * 2. Make mute button less aggressive */ //handle clicking mute/unmute function toggleMute() { mediaStream.getTracks()[0].enabled = !mediaStream.getTracks()[0].enabled; setMute(!mute); } //url to profile picture function profilePicturePath() { return "https://github.com/" + username + ".png" } return ( <Card className="text-center" style={{ maxWidth: '200px', maxHeight: '300px'}} > <Card.Header className="d-flex justify-content-md-between "> {username} </Card.Header> <Card.Img src={profilePicturePath()} alt="Profile Picture" style={{ width: '200px', height: '200px'}} /> <Card.ImgOverlay> <Card.Body> <div className="d-flex flex-column"> <div className="p-2"> <Button variant="secondary" onClick={toggleMute}> <img src={mute ? unmute : muteIcon} alt="mute" /> </Button> </div> <div className="mt-auto p-3"> {play && <audio autoPlay={true} ref={audio => {if (audio) audio.srcObject = mediaStream}} style = {{width: 0}}/>} <Visualizer mediaStream={mediaStream} /> </div> </div> </Card.Body> </Card.ImgOverlay> </Card> ) }
import React from 'react' import { useDispatch, useSelector } from 'react-redux' import {BASE_URL} from '../constants.js' export default function CurrentCheck() { // const check = props.check const check = useSelector(state => state.currentCheck) const dispatch = useDispatch() //delete item from check const deleteProduct = product => { fetch(BASE_URL + '/delete_from_check', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ check_id: check.id, product_id: product.id }) }) .then(r => r.json()) .then(data => { console.log() dispatch({ type: 'DELETE_PRODUCT', payload: {selCheck: check, delProduct: product} }) dispatch({ type: 'DELETE_PRODUCT_FROM_CURRENT_CHECK', payload: product }) }) } //starting for check total let checkTotal = 0 return ( <div className="current-check-container"> <h2 className="current-check-id">{check.id === -1 ? "" : check.id}</h2> {console.log(check)} <ul className="check-items"> {check.products.map(product => { checkTotal += product.price return <li key={product.id} className="check-item"> <h5 key={product.name}>{product.name}</h5> <h6 key={product.price}>{product.price}</h6> <button onClick={() => deleteProduct(product)}>Delete Product</button> </li> })} </ul> <h3>Total: {checkTotal}</h3> </div> ) }
import React, { useEffect, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Typography } from '@material-ui/core'; import { makeStyles } from '@material-ui/core/styles'; import Grid from '@material-ui/core/Grid'; import { Controlled as CodeMirror } from 'react-codemirror2'; import Button from '@material-ui/core/Button'; import ButtonGroup from '@material-ui/core/ButtonGroup'; import Paper from '@material-ui/core/Paper'; import Tabs from '@material-ui/core/Tabs'; import Tab from '@material-ui/core/Tab'; import TextField from '@material-ui/core/TextField'; import Dialog from '@material-ui/core/Dialog'; import MenuBar from '../Component/menuBar'; import { submitAlgo } from '../store/actions/algo'; import CircularProgress from '@material-ui/core/CircularProgress'; import Backdrop from '@material-ui/core/Backdrop'; import { deleteDraftName } from '../store/actions/editor'; import { submitSnippet } from '../store/actions/snippet'; import IconButton from '@material-ui/core/IconButton'; import AddShoppingCartIcon from '@material-ui/icons/AddShoppingCart'; require('codemirror/lib/codemirror.css'); require('codemirror/theme/material.css'); require('codemirror/theme/neat.css'); require('codemirror/mode/python/python.js'); const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, }, appBar: { zIndex: theme.zIndex.drawer + 1, height: 60, margin: 'auto', paddingTop: 10, paddingLeft: 10, }, drawerContainer: { overflow: 'auto', }, content: { flexGrow: 1, padding: theme.spacing(3), }, })); const SnippetRow = props => { const handleImport = () => { window.alert(`${props.type} 코드를 불러왔습니다.`); props.handleImportState(props.type, props.name, props.des, props.code); }; return ( <Paper variant="outlined" square className='SnippetRow' style={{ padding: 5 }}> <Grid container> <Grid item xs={11}> <b>{`Name: ${props.name}`}</b> <Typography>{`(Type: ${props.type})`}</Typography> </Grid> <Grid item xs={1}> <IconButton align="right" onClick={handleImport} id='import_button'> <AddShoppingCartIcon/> </IconButton> </Grid> </Grid> </Paper> ); }; export const WritePage = (props) => { const classes = useStyles(); const [TabValue, setTabValue] = useState(1); const dispatch = useDispatch(); const snippetSubmitStore = useSelector((s) => s.user.snippetSubmit); const algorithmSubmitStore = useSelector((s) => s.user.algorithmSubmit); const loadingStore = useSelector((s) => s.user.loading); const likedSnippets = useSelector(s => s.snippet.likedSnippetList); const ownedSnippets = useSelector(s => s.snippet.ownedSnippetList); const [editorValue, setEditorValue] = useState({ 1: 'scope = QC.query(universe, \'code_name == "삼성전자"\')', 2: `for index, candidate in enumerate(scope): if index==0: chosen_stocks.append(candidate) break`, 3: `for candidate in sell_candidates: chosen_stocks.append(candidate)`, 4: `if opt == SnippetType.BUY: for stock in chosen_stocks: buy_amount_list.append((stock, 1)) else: for stock in chosen_stocks: sell_amount_list.append((stock, stock.get_amount()))`, }); /* istanbul ignore next */ const handleEditorValueChange = (i, d) => { setEditorValue({ ...editorValue, [i]: d }); // handleEditorValidationChange(i, false); }; // const [snippetValidated, setSnippetValidated] = useState({ // 1: false, // 2: false, // 3: false, // 4: false, // }); // const handleEditorValidationChange = (i, v) => { // setSnippetValidated({...snippetValidated, [i]: v}); // }; const [snippetName, setSnippetName] = useState({ 1: '', 2: '', 3: '', 4: '', }); const [snippetDescr, setSnippetDescr] = useState({ 1: '', 2: '', 3: '', 4: '', }); const [algorithmName, setAlgorithmName] = useState(''); const [algorithmDescr, setAlgorithmDescr] = useState(''); const [importModalOpen, setImportModalOpen] = useState(false); const handleTabChange = (event, newValue) => { setTabValue(newValue); }; // const [errorMsg, setErrorMsg] = useState({ // 1: '', // 2: '', // 3: '', // 4: '', // }); // // const handleErrorMsgChange = (i, v) => { // setErrorMsg({ ...errorMsg, [i]: v }); // }; const draftName = useSelector((store) => store.editor.loadedDraftName); useEffect(() => { // TODO: editor라는 store의 loadedDraftName 항목을 통해 draft의 이름을 불러온다 dispatch(deleteDraftName()); if (draftName) { handleDraft(draftName); } }, []); /* istanbul ignore next */ const handleDraft = (n) => { if (n !== undefined) { const draft = JSON.parse(localStorage.getItem(n)); setAlgorithmName(n); setEditorValue(draft.code); setSnippetName(draft.name); } }; /* istanbul ignore next */ const handleImport = () => { setImportModalOpen(true); }; const handleImportState = (type, name, des, code) => { const newSnippetDescr = snippetDescr; const newSnippetName = snippetName; const newEditorValue = editorValue; switch (type) { case 'scope': newSnippetDescr['1'] = des; newSnippetName['1'] = name; newEditorValue['1'] = code; break; case 'buy': newSnippetDescr['2'] = des; newSnippetName['2'] = name; newEditorValue['2'] = code; break; case 'sell': newSnippetDescr['3'] = des; newSnippetName['3'] = name; newEditorValue['3'] = code; break; case 'amount': newSnippetDescr['4'] = des; newSnippetName['4'] = name; newEditorValue['4'] = code; break; default: break; } setSnippetDescr(newSnippetDescr); setSnippetName(newSnippetName); setEditorValue(newEditorValue); }; // const handleValidate = (i) => { // if (Math.random() > 0.5) { // window.alert('validated'); // handleEditorValidationChange(i, true); // } else { // window.alert('validation fail: change name'); // } // }; const handleSubmitSnippet = (i) => { // TODO: check for name duplicate const snippetType = [undefined, 'scope', 'buy', 'sell', 'amount']; dispatch( submitSnippet( snippetName[i], snippetDescr[i], snippetType[i], editorValue[i], i, ), ); }; const saveAlgorithmAsDraft = () => { localStorage.setItem( algorithmName, JSON.stringify({ code: editorValue, name: snippetName, }), ); // TODO: message? window.alert('code saved to localstorage'); }; const handleSubmitAlgorithm = () => { // TODO: check for name duplicate => not now // TODO: feedback message? if ( snippetSubmitStore[0] !== false && snippetSubmitStore[1] !== false && snippetSubmitStore[2] !== false && snippetSubmitStore[3] !== false && algorithmName !== '' && algorithmDescr !== '' ) { dispatch(submitAlgo(algorithmName, algorithmDescr, snippetSubmitStore)); } else { window.alert('Please submit algorithms first'); } }; return ( <div className={classes.root}> <MenuBar/> <Grid container justify="center" spacing={2}> <Grid item xs={4} style={{ backgroundColor: '#eeeeee' }}> API DOC </Grid> <Grid item xs={8}> <Paper elevation={1}> <Paper elevation={3} style={{ marginBottom: 5, marginTop: 5 }}> <Tabs value={TabValue} onChange={handleTabChange} indicatorColor="primary" textColor="primary" centered > <Tab id="snippet_1" label="Snippet: Scope" value={1}/> <Tab id="snippet_2" label="Snippet: Buy" value={2}/> <Tab id="snippet_3" label="Snippet: Sell" value={3}/> <Tab id="snippet_4" label="Snippet: Amount" value={4}/> </Tabs> </Paper> <div style={{ margin: 10 }}> <TextField id="snippet_name" variant="outlined" size={'small'} label="snippet name" disabled={snippetSubmitStore[TabValue] !== false} fullWidth value={snippetName[TabValue]} onChange={(e) => { setSnippetName({ ...snippetName, [TabValue]: e.target.value, }); }} /> </div> <div style={{ margin: 10 }}> <TextField id="snippet_descr" variant="outlined" size={'small'} label="snippet Description" disabled={snippetSubmitStore[TabValue] !== false} fullWidth value={snippetDescr[TabValue]} onChange={(e) => { setSnippetDescr({ ...snippetDescr, [TabValue]: e.target.value, }); }} /> </div> <CodeMirror value={editorValue[TabValue]} options={{ mode: 'python', theme: 'material', lineNumbers: true, readOnly: snippetSubmitStore[TabValue] !== false, }} onBeforeChange={ /* istanbul ignore next */ (editor, data, value) => { handleEditorValueChange(TabValue, value); } } // onChange={(editor, data, value) => { // // setEditor1Value(value); // }} /> <ButtonGroup color="primary" style={{ margin: 10 }}> <Button id="import_algorithm" size={'small'} disabled={snippetSubmitStore[TabValue] !== false} onClick={() => { handleImport(); }} > Import </Button> {/*<Button*/} {/* id='snippet_validate'*/} {/* size={'small'}*/} {/* disabled={*/} {/* snippetName[TabValue] === '' || snippetValidated[TabValue]*/} {/* }*/} {/* onClick={() => {*/} {/* handleValidate(TabValue);*/} {/* }}*/} {/*>*/} {/* Validate*/} {/*</Button>*/} <Button id="submit_snippet" size={'small'} disabled={ snippetName[TabValue] === '' || snippetDescr[TabValue] === '' || editorValue[TabValue] === '' || // || !snippetValidated[TabValue] snippetSubmitStore[TabValue] !== false } onClick={() => { handleSubmitSnippet(TabValue); }} > Submit Snippet </Button> </ButtonGroup> <Typography id="status_message" component="span" style={{ color: '#ff0000' }} > {/*{`Status: ${snippetValidated[TabValue] === true*/} {/* ? snippetSubmitStore[TabValue] === true*/} {/* ? 'Submitted'*/} {/* : 'Not submitted'*/} {/* : 'Unvalidated'}`*/} {/*}*/} {`Status: ${ snippetSubmitStore[TabValue] !== false ? 'Submitted' : 'Not submitted' }`} </Typography> </Paper> <Grid container justify="space-between" style={{ padding: 10 }}> <Grid item xs={3}> <TextField id="algorithm_name" variant="outlined" label="Algorithm name" size={'small'} style={{ marginRight: 10 }} value={algorithmName} onChange={(e) => { setAlgorithmName(e.target.value); }} /> </Grid> <Grid item xs={9}> <TextField id="algorithm_descr" variant="outlined" label="Algorithm Description" size={'small'} fullWidth style={{ marginRight: 10 }} value={algorithmDescr} onChange={(e) => { setAlgorithmDescr(e.target.value); }} /> </Grid> <Grid item style={{ marginTop: 16 }}> <ButtonGroup color="primary" style={{ marginTop: 2 }}> <Button id="save_algorithm" onClick={() => { saveAlgorithmAsDraft(); }} > Save As Draft </Button> <Button id="submit_algorithm" disabled={ algorithmName === '' || snippetSubmitStore[1] === false || snippetSubmitStore[2] === false || snippetSubmitStore[3] === false || snippetSubmitStore[4] === false || algorithmSubmitStore !== false } onClick={() => { handleSubmitAlgorithm(); }} > Submit as Algorithm </Button> </ButtonGroup> </Grid> <Grid item style={{ marginTop: 16 }}> <Button id="go_back" size={'small'} color={'secondary'} variant={'contained'} onClick={() => { props.history.push('/'); }} > Back </Button> </Grid> </Grid> </Grid> </Grid> <Dialog fullWidth={true} maxWidth={'md'} open={importModalOpen} onClose={ /* istanbul ignore next */ () => { setImportModalOpen(false); } } > <Grid container style={{ padding: 20 }}> <Grid item xs={6} style={{ padding: 10, height: 500 }} component={Paper}> <Typography variant="h6" gutterBottom component="div" style={{ marginLeft: 20 }}> Liked Snippets </Typography> <div style={{ maxHeight: 450, overflowY: 'auto' }}> {likedSnippets.map(s => <SnippetRow key={s.id} name={s.name} type={s.type} code={s.code} des={s.description} handleImportState={(type, name, des, code) => { handleImportState(type, name, des, code); setImportModalOpen(false); }} />)} </div> </Grid> <Grid item xs={6} style={{ paddingTop: 10, height: 500 }} component={Paper}> <Typography variant="h6" gutterBottom component="div" style={{ marginLeft: 20 }}> Detailed log </Typography> <div style={{ maxHeight: 450, overflowY: 'auto' }}> {ownedSnippets.map(s => <SnippetRow key={s.id} name={s.name} type={s.type} code={s.code} des={s.description} handleImportState={(type, name, des, code) => { handleImportState(type, name, des, code); setImportModalOpen(false); }} />)} </div> </Grid> </Grid> </Dialog> <Backdrop open={loadingStore} onClick={ /* istanbul ignore next */ () => { /* istanbul ignore next */ dispatch({ type: 'CHANGE_LOADING', data: false }); } } style={{ zIndex: 999 }} > <CircularProgress color="inherit"/> </Backdrop> </div> ); };
import React from 'react'; import './CharacterDetail.css' const CharacterDetail = ({ character }) => { if (!character) { return null; } return ( <div className="flex-container"> <h3> House: {character.house} </h3> <h3> Species: {character.species} </h3> <h3> Gender: {character.gender} </h3> </div> ) } export default CharacterDetail;
import React, {useContext} from 'react'; import ThemeContext from '../context/ThemeContext' import '../assets/Theme/darkTheme.css' import '../assets/pages/Home.css' const Home = () => { var theme = useContext(ThemeContext) return ( <div className={theme ? "Home dark": "Home"}> <div> Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, quo. Omnis rem quam quo est error nesciunt in quibusdam animi neque pariatur at architecto maxime, saepe a nam illo eaque ut quis hic ullam sapiente. Adipisci quo, atque at possimus sequi earum nemo neque, ad laboriosam quaerat eos maiores exercitationem illum pariatur provident placeat, vitae eum consectetur. Deleniti at inventore accusamus voluptatum perferendis? Pariatur, sint cupiditate nulla magni vel eveniet id dolorem enim ad consequatur. Blanditiis quidem corrupti similique explicabo doloremque neque deleniti, exercitationem odit eveniet dicta nisi, alias ipsa earum adipisci rem provident dolor ipsam, recusandae pariatur harum vero. </div> </div> ); } export default Home;
import Router from 'next/router' class Setting extends React.Component { constructor () { super(); this.state= { placeholder: "", btn_name: "", access_token: "" } } componentDidMount(){ if(localStorage.getItem("accessToken")){ this.setState({ access_token: localStorage.getItem("accessToken") }) } else{ Router.push('/login') } } changeInputPlaceholder=(e)=>{ this.setState({ placeholder: e.target.value }) } changeButtonName=(e)=> { this.setState({ btn_name: e.target.value }) } addInput=()=>{ var maindiv = document.createElement('div'); var btn = document.createElement('button'); btn.setAttribute('onClick', 'this.parentNode.remove()' ); btn.innerHTML = "X" btn.style.backgroundColor = "yellow" btn.style.width = "35px" btn.style.height = "35px" btn.style.borderRadius = "50%" btn.style.border= "1px solid yellow" btn.style.fontWeight= "bold" btn.style.fontSize= "15px" btn.style.color = "darkgray" maindiv.innerHTML = ` <input style= "width: 200px; margin: 20px; height: 30px; padding-left: 15px; border-radius: 6px; border: 1px solid lightgray;" placeholder= ${this.state.placeholder} /> `; maindiv.appendChild(btn) document.getElementById('former').appendChild(maindiv); } addButton=()=>{ var maindiv = document.createElement('div'); var btn = document.createElement('button'); btn.setAttribute('onClick', 'this.parentNode.remove()' ); btn.innerHTML = "X" btn.style.backgroundColor = "yellow" btn.style.width = "35px" btn.style.height = "35px" btn.style.borderRadius = "50%" btn.style.border= "1px solid yellow" btn.style.fontWeight= "bold" btn.style.fontSize= "15px" btn.style.color = "darkgray" maindiv.innerHTML = ` <button style="width: 220px; margin: 20px; height: 30px; background-color: bisque; border: 1px solid bisque; border-radius: 6px; " > ${this.state.btn_name}</button> `; maindiv.appendChild(btn) document.getElementById('former').appendChild(maindiv); } render(){ return( <div className="main-div"> <div className="setting-div"> <h2>Add & Remove Fields</h2> <div className="div-1"> <div> <input className="input_placeholder" onChange={(e)=>{this.changeInputPlaceholder(e)}} placeholder="Enter Input Placeholder" /> <button onClick={()=>{this.addInput()}}>Add Input Field</button> </div> <div> <input className="button_name" onChange={(e)=>{this.changeButtonName(e)}} placeholder="Enter Button Name" /> <button onClick={()=>{this.addButton()}}>Add Button</button> </div> </div> </div> <div id = 'former' className="form-generator"> </div> <style jsx>{` .main-div { display: flex; width: 70%; margin: 0px auto; } .form-generator { margin-left: 50px; margin-top: 70px; border: 1px solid darkgrey; border-radius: 8px; width: 400px; height: 400px; overflow: auto; } .setting-div { margin-top: 70px; } .setting-div h2{ margin-left: 20px; } input { width: 200px; margin: 20px; height: 30px; padding-left: 15px; border-radius: 6px; border: 1px solid lightgray; } } button { width: 220px; margin: 20px; height: 30px; background-color: bisque; border: 1px solid bisque; border-radius: 6px; } `}</style> </div> ) } } export default Setting;
import { mount } from 'enzyme'; import VitalSourceBookViewer from '../VitalSourceBookViewer'; describe('VitalSourceBookViewer', () => { let container; let launchForm; let wrappers; const createComponent = ({ launchUrl, launchParams }) => { const beforeSubmit = form => { sinon.stub(form, 'submit'); launchForm = form; }; const wrapper = mount( <VitalSourceBookViewer launchUrl={launchUrl} launchParams={launchParams} willSubmitLaunchForm={beforeSubmit} />, // The `VitalSourceBookViewer` must be rendered into a connected element // for the iframe's document to be created. { attachTo: container } ); wrappers.push(wrapper); return wrapper; }; beforeEach(() => { wrappers = []; launchForm = null; container = document.createElement('div'); document.body.appendChild(container); }); afterEach(() => { wrappers.forEach(w => w.unmount()); container.remove(); }); it('creates and submits a form with the launch parameters', () => { const launchParams = { roles: 'Learner', context_id: 'testcourse', location: 'chapter-1', }; const launchUrl = 'https://hypothesis.vitalsource.com/launch'; const onSubmit = sinon.stub(); createComponent({ launchUrl, launchParams, onSubmit, }); assert.ok(launchForm); assert.calledOnce(launchForm.submit); assert.equal(launchForm.tagName, 'FORM'); assert.equal(launchForm.method, 'post'); assert.equal(launchForm.action, launchUrl); const fields = Array.from(launchForm.elements).reduce((obj, el) => { obj[el.name] = el.value; return obj; }, {}); assert.deepEqual(fields, launchParams); }); });
Ext.define('AM.view.Login', { extend : 'Ext.form.Panel', alias : 'widget.login', config : { fullscreen : true, items : [ { xtype : 'toolbar', title : 'Login', docked : 'top', items : [ {xtype : 'spacer'}] }, { xtype : 'fieldset', items : [ { xtype : 'textfield', name : 'email', label : 'Email*', allowBlank : false, vtype : 'email' }, { xtype : 'passwordfield', name : 'password', label : 'Password*', inputType: 'password', allowBlank : false } ] }, { xtype : 'toolbar', docked : 'bottom', items : [{ xtype : 'button', action:'loginAsDemo', text : 'Login As Demo' }, { xtype : 'button', text : 'Register' }, { xtype : 'spacer' }, { xtype : 'button', text : 'Login' } ] } ] }, initialize : function() { this.callParent(arguments); } });
var HelloWorld = artifacts.require("HelloWorld"); contract("HelloWorld", function(_accounts) { let instance; before(async () => { instance = await HelloWorld.deployed(); }); it("Default message should be Hello world", async () => { let message = await instance.getMessage.call({from: _accounts[0]}); assert.equal(message, "Hello world", "Incorrect message."); }); it('Should save name', async () => { let result = await instance.setName.sendTransaction('yungshun', {from: _accounts[0]}); let message = await instance.getMessage.call({from: _accounts[0]}); assert.equal(message, "Hello yungshun", "Incorrect message."); }); it('Should be default message for other accounts', async () => { let message1 = await instance.getMessage.call({from: _accounts[0]}); let message2 = await instance.getMessage.call({from: _accounts[1]}); assert.equal(message1, "Hello yungshun", "Incorrect user message."); assert.equal(message2, "Hello world", "Incorrect message."); }); it('Should throw error on empty name', async () => { try { let result = await instance.setName.sendTransaction('', {from: _accounts[0]}); assert.fail(true, false, "The function should throw error"); } catch(err) { assert.include(String(err), 'revert', 'throws different error'); } }); });
import React, { Component } from 'react'; export default class InputValues extends Component { constructor() { super() this.state = { name: '', species: '', gender: '', image: '', input:'' } } handleNameChange = val => { this.setState({ name: val, }) } handleSpeciesChange = val => { this.setState({ species: val, }) } handleGenderChange = val => { this.setState({ gender: val, }) } handleImageChange = val => { this.setState({ image: val, }) } addCharacter = () => { const { name, species, gender, image } = this.state; const {handleAddBtn} = this.props; handleAddBtn({name, species, gender, image}); } render() { return ( <div className="inputs-div"> <input className="inputs" type="text" placeholder="Name" onChange={e => this.handleNameChange(e.target.value)} /> <input className="inputs" type="text" placeholder="Species" onChange={ e => this.handleSpeciesChange(e.target.value) } value={this.state.value} /> <input className="inputs" type="text" placeholder="Gender" onChange={e => this.handleGenderChange(e.target.value)} value={this.state.value} /> <input className="inputs" type="text" placeholder="Image URL" onChange={e => this.handleImageChange(e.target.value)} value={this.state.value} /> <button className="inputs" onClick={this.addCharacter} >Add Character</button> </div> ) } }
var server = require('../lib/server'); var shared = require('../lib/shared'); var Buffer = require('buffer').Buffer; var serialized = shared.Serialize(new Buffer(01)); console.log("Serialized: ", serialized); console.log("Deserialized: ", shared.Deserialize(serialized)); // Callback test var request = function(/* arguments */) { console.log("Callback!"); }; serialized = shared.Serialize(request); console.log("Serialized: ", serialized); console.log("Deserialized: ", shared.Deserialize(serialized));
"use strict"; const Content = require('../models/Content'); /** * ApiController * @type {Xpresser.Controller.Handler} */ const ApiController = $.handler({ // Controller Name name: "ApiController", // Controller Middleware middlewares: {}, // Controller Default Service Error Handler. e: $$.defaultApiErrorHandler, boot: async (http) => { const api_key = http.locals.get('api_key'); const device = http.locals.get('api_device'); const user = http.locals.get('api_user'); const clip = http.locals.get('api_clip'); return {device, api_key, user, clip}; }, /** * Connect . * @returns {*} */ connect: async (http, {device}) => { let used_by = http.body('device_id', undefined); if (!device.used) { // noinspection JSCheckFunctionSignatures device = await device.$query().updateAndFetch({used: true, used_by}) } used_by = device.used_by; const data = { ...device.$pick([ 'name', 'api_key', 'hits', 'used_by' ]), used_by }; return $$.toApi(http, data); }, /** * Get all User Clips * @param http * @param user * @returns {Promise<void>} */ all: async (http, {user}) => { let page = http.query('page', 1); let search = http.query('search', undefined); if (Number(page) < 1) page = 1; let query = Content.query().where({user_id: user.id}); if (search && search.length > 1) { query.where('content', 'like', `%${search}%`) } const clips = await query.orderBy('id', 'desc') .paginate(page, 20); for (const content of clips.data) { content.$pick(Content.jsPick); } return $$.toApi(http, {search, clips}); }, /** * Add content using the content add service. */ add: {'content.add': 'api'}, /** * Delete Content * @param http * @param clip * @returns {Promise<*>} */ delete: async (http, {clip}) => { const code = clip.code; await clip.$query().delete(); return $$.toApi(http, {deleted: true, code}) }, /** * 404 error response. * @param http * @param boot * @param error * @returns {*} */ notFound: (http, boot, error) => error({ type: '404', message: `Route not found!` }, 404), }); module.exports = ApiController;
function sumadedos(numeros, resultadodelasuma) { var i = 0; var z = numeros.length - 1; var resultado = [] sumaresultado = false while (i < z) { var resultadoq = numeros[i] + numeros[z]; if (resultadoq < resultadodelasuma) { i++; } else if (resultadoq > resultadodelasuma) { z--; } else { sumaresultado = true break; } } if (sumaresultado == true) { resultado.push(numeros[i]); resultado.push(numeros[z]); console.log("El array se compone de " + numeros); console.log("El numero buscado es " + resultadodelasuma); console.log("Los numeros que suman " + resultadodelasuma + " son " + resultado); } else {console.log("No hay dos numeros que sumen ese numero en el array");} }
export const customStyle = [ { "featureType": "administrative.land_parcel", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "landscape.man_made", "stylers": [ { "color": "#b5e3f7" }, { "visibility": "on" } ] }, { "featureType": "landscape.natural", "stylers": [ { "color": "#89c6e6" } ] }, { "featureType": "poi", "stylers": [ { "color": "#d6eaf5" } ] }, { "featureType": "poi", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi", "elementType": "labels.text", "stylers": [ { "color": "#5f5353" }, { "visibility": "off" }, { "weight": 0.5 } ] }, { "featureType": "poi", "elementType": "labels.text.fill", "stylers": [ { "color": "#ffffff" } ] }, { "featureType": "poi", "elementType": "labels.text.stroke", "stylers": [ { "color": "#525151" }, { "weight": 1 } ] }, { "featureType": "road", "stylers": [ { "color": "#89c6e6" } ] }, { "featureType": "road", "elementType": "labels.text", "stylers": [ { "color": "#ffffff" }, { "visibility": "on" }, { "weight": 0.5 } ] }, { "featureType": "road", "elementType": "labels.text.stroke", "stylers": [ { "color": "#453030" }, { "weight": 0.5 } ] }, { "featureType": "road.local", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "transit.station", "stylers": [ { "visibility": "off" } ] } ] ;
import jwt from 'jwt-simple'; import dotenv from 'dotenv'; import User from '../models/user_model'; dotenv.config({ silent: true }); // encodes a new token for a user object function tokenForUser(user) { const timestamp = new Date().getTime(); return jwt.encode({ sub: user.id, iat: timestamp }, process.env.AUTH_SECRET); } export const signin = (user) => { return tokenForUser(user); }; // note the lovely destructuring here indicating that we are passing in an object with these 3 keys export const signup = async ({ email, password, owner }) => { if (!email || !password || !owner) { throw new Error('You must provide email, password and owner name'); } // See if a user with the given email exists const existingUser = await User.findOne({ email }); if (existingUser) { // If a user with email does exist, return an error throw new Error('Email is in use'); } const user = new User(); user.email = email; user.password = password; user.owner = owner; await user.save(); return tokenForUser(user); }; // Get all the pics of a particular user export const getUser = async (userId) => { try { const foundUser = await User.findOne({ _id: userId }); if (!foundUser) { throw new Error('Can\'t find user'); } else { return foundUser.populate('picsLiked').populate('picsOwn'); } } catch (error) { throw new Error(`get user Pics error: ${error}`); } }; export const updateUser = async (userId, newUserData) => { try { if (newUserData) { await User.findByIdAndUpdate(userId, { picsLiked: newUserData.picsLiked, picsOwn: newUserData.picsOwn, }); const returnUser = await User.findById({ _id: userId }); if (returnUser) return returnUser; else return new Error('Can not update user'); } else { return new Error('Can not update user'); } } catch (error) { throw new Error(`update user error: ${error}`); } };
/** * Created by zhoucaiguang on 16/8/15. */ var express = require('express'); var router = express.Router(); var request = require('request'); var fs = require('fs'); var url = require('url'); function handelReferer(url) { if(url.indexOf('girlatlas')>-1){ return 'http://girlatlas.b0.upaiyun.com/'; }else{ return null; } } router.get('/', function(req, res){ // console.log(res); var path = decodeURIComponent(req.query.path); // path ? path : res.end(); // path ? request(path).pipe(res) : res.end(); var option ={}; var queryUrl = url.parse(path); if(path=='undefined'){ res.end(); return; } // console.log(path); // if(!queryUrl){res.end();} option.url= path; option.encoding = null; option.headers = {Referer:queryUrl.protocol+'//'+queryUrl.host}; var resUrl = handelReferer(path); if(resUrl){ option.headers = {Referer:'http://girl-atlas.net/'}; } // console.log(option); request(option,function(error, response, body){ // console.log(1); console.log('image-proxy'); if(error){console.log(error);return;} // console.log(response.statusCode); if (!error && response.statusCode == 200) { var type = response.headers["content-type"]; res.set('Content-Type',type); res.send(body); }else{ res.end(); } }); }); module.exports = router;
import React from "react" import { Flex, Box } from "rebass" import { Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink, UncontrolledDropdown, DropdownToggle, DropdownMenu, DropdownItem, } from "reactstrap" export default class Example extends React.Component { constructor(props) { super(props) this.toggle = this.toggle.bind(this) this.state = { isOpen: false, } } toggle() { this.setState({ isOpen: !this.state.isOpen, }) } render() { return ( <Flex> <Box w={1}> <Navbar color="dark" dark expand="lg"> <NavbarBrand href="/" className="mr-auto" /> <NavbarToggler onClick={this.toggle} /> <Collapse isOpen={this.state.isOpen} navbar> <Nav navbar> <NavItem> <NavLink href="#">Cookware</NavLink> </NavItem> <NavItem> <NavLink href="#">Cook's Tools</NavLink> </NavItem> <NavItem> <NavLink href="#">Cutlery</NavLink> </NavItem> <NavItem> <NavLink href="#">Electrics</NavLink> </NavItem> <NavItem> <NavLink href="#">Bakeware</NavLink> </NavItem> <NavItem> <NavLink href="#">Food</NavLink> </NavItem> <NavItem> <NavLink href="#">TableTop & Bar</NavLink> </NavItem> <NavItem> <NavLink href="#">Homekeeping</NavLink> </NavItem> <NavItem> <NavLink href="#">Outdoor</NavLink> </NavItem> <NavItem> <NavLink href="#">Sale</NavLink> </NavItem> <NavItem> <NavLink className="text-truncate" href="#"> Williams-Sonoma Home </NavLink> </NavItem> </Nav> </Collapse> </Navbar> </Box> </Flex> ) } }
const iconsLogoutCopy = { "en": { "LOGOUT": {} }, "kr": { "LOGOUT": {} }, "ch": { "LOGOUT": {} }, "jp": { "LOGOUT": {} } } export default iconsLogoutCopy;
import React, { useEffect, useState } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Card from '@material-ui/core/Card'; import CardActionArea from '@material-ui/core/CardActionArea'; import CardActions from '@material-ui/core/CardActions'; import CardContent from '@material-ui/core/CardContent'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; import { Container } from '@material-ui/core'; import { useHistory, useParams } from 'react-router-dom'; import Comment from '../Comment/Comment'; const useStyles = makeStyles({ root: { maxWidth: "100%", marginTop: "80px" }, media: { height: 140, }, }); export default function MediaCard() { const { postId } = useParams() const [post, setPost] = useState({}) const [comments, setComments] = useState([]) const classes = useStyles(); useEffect(() => { fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`) .then(res => res.json()) .then(data => setPost(data)) }, []) useEffect(() => { fetch(`https://jsonplaceholder.typicode.com/comments?postId=${postId}`) .then(res => res.json()) .then(commentData => setComments(commentData)) }, []) return ( <> <Container maxWidth="md"> <Card className={classes.root}> <CardActionArea> <CardContent> <Typography style={{ textTransform: "uppercase" }} gutterBottom variant="h4" component="h2"> {post.title} </Typography> <Typography style={{ margin: "20px 0" }} variant="h6" color="textSecondary" component="p"> {post.body} </Typography> </CardContent> </CardActionArea> <CardActions style={{ display: 'flex', justifyContent: 'space-between' }}> <Button size="large" variant="contained" color="primary"> Like </Button> <Button size="large" variant="contained" color="primary"> {comments.length} Comments </Button> <Button size="large" variant="contained" color="primary"> Share </Button> </CardActions> </Card> </Container> <Container maxWidth='md'> <Card style={{marginTop:"30px"}}> <Typography style={{marginLeft:'30px'}} variant='h5' color="textSecondary" component="h2">Comments: ({comments.length})</Typography> <Container maxWidth='md'> { comments.map(comment => <Comment comment={comment} key={comment.id} />) } </Container> </Card> </Container> </> ); }
async function startYMusic(browser, page=undefined) { // open ymusic const ymusic = (page === undefined) ? await browser.newPage() : page; await ymusic.goto("https://music.youtube.com"); await blockAdsYTmusic(ymusic); // console.log("Youtube Music opened."); return ymusic; } async function blockAdsYTmusic(ymusic) { // adblocking node module - https://www.npmjs.com/package/@cliqz/adblocker-playwright const { PlaywrightBlocker } = require('@cliqz/adblocker-playwright'); const fetch = require('cross-fetch').fetch; PlaywrightBlocker.fromPrebuiltAdsAndTracking(fetch).then((blocker) => { blocker.enableBlockingInPage(ymusic); }); } /** * * @param {*} ymusic * @param {string} query - The string to be searched. * @param {'song'|'playlist'|'artist'|'album'} type - The type of result to * select, defaults to song. * @returns */ async function playMusic(ymusic, query, musicType = "song") { // console.log(`Attempting to play ${query}.`); // search query let results = await searchQuery(ymusic, query); if (results === "No results.") return null; await decideMusic(ymusic, musicType); // return current song const songData = await getCurrentSong(ymusic); // console.log(`Playing ${songData.name} by ${songData.artist}!`); return songData; } /** * Search a query in youtube music. * @param {*} ymusic * @param {string} query * @returns */ async function searchQuery(ymusic, query) { // wait for search bar to load, just in case await ymusic.waitForSelector('tp-yt-paper-icon-button[role="button"]'); // console.log("Search bar loaded."); // focus search bar if ( (await ymusic.getAttribute( 'tp-yt-paper-icon-button[role="button"]', "title" )) == "Initiate search" ) await ymusic.click('tp-yt-paper-icon-button[title="Initiate search"]'); // console.log("Search bar focused."); // seacrh song await ymusic.fill('input[placeholder="Search"]', query); await ymusic.keyboard.press("Enter"); // console.log(`Searching for ${query}.`); // wait for search results to load, if no results, return. await ymusic.waitForSelector( "#search-page > ytmusic-tabbed-search-results-renderer > div.content.style-scope.ytmusic-tabbed-search-results-renderer" ); if ((await ymusic.$("text=Top result")) === null) { // console.log("No results."); return "No results."; } // console.log("Results Loaded."); return "Results Loaded."; } /** * Decide which result to select. * @param {'song'|'playlist'|'artist'|'album'} musicType - The type of result to * select, defaults to song. */ async function decideMusic(ymusic, musicType = "") { await ymusic.evaluate(async (musicType) => { // currently artist plays song too if (musicType === "artist") musicType = "songs"; // check the musicType of Top result const topResult = {}; topResult.musicType = await document.querySelector( " ytmusic-shelf-renderer > #contents > ytmusic-responsive-list-item-renderer > .flex-columns > .secondary-flex-columns > yt-formatted-string > span " ).innerText; // this should instead point to whatever element plays the top result // this wont work for artist topResult.playButton = await document .querySelector( " ytmusic-shelf-renderer > #contents > ytmusic-responsive-list-item-renderer " ) .querySelector(" .ytmusic-play-button-renderer "); if (topResult.musicType.toLowerCase() === musicType) { await topResult.playButton.click(); } else { if (musicType === "playlist") musicType = "featured playlists"; else { musicType += "s"; } // get all titles, store in object const getTitlesList = async () => { const titles = await document .querySelector( " .content.style-scope.ytmusic-tabbed-search-results-renderer " ) .querySelectorAll(" h2 "); const titleSelectors = {}; for (idx in titles) { var titleName = titles[idx].innerText; if (typeof titleName == "string") { var firstItemPlayButton = await titles[ idx ].parentElement.querySelector( ".ytmusic-play-button-renderer" ); titleSelectors[titleName.toLowerCase()] = firstItemPlayButton; } } return titleSelectors; }; const titlesList = await getTitlesList(); if (titlesList[musicType] !== undefined) { await titlesList[musicType].click(); } else { await topResult.playButton.click(); } } }, musicType); } /** * Returns details of the currently playing song. * @param {*} ymusic * @returns */ async function getCurrentSong(ymusic) { await ymusic.waitForSelector( 'yt-formatted-string[class="byline style-scope ytmusic-player-bar complex-string"]' ); const songName = await ymusic.evaluate(async () => { return await document.querySelector( 'yt-formatted-string[class="title style-scope ytmusic-player-bar"]' ).title; }); const { songArtist, songAlbum } = await ymusic.evaluate(async () => { const otherData = await document.querySelector( 'yt-formatted-string[class="byline style-scope ytmusic-player-bar complex-string"]' ); const otherSongData = {}; otherSongData.songArtist = await otherData.children[0].innerText; otherSongData.songAlbum = await otherData.children[2].innerText; return otherSongData; }); const songData = { name: songName, artist: songArtist, album: songAlbum, }; return songData; } // refactor the three functions below into single function. /** * If player is playing then pause, else nobody cares. * @param {page} ymusic * @returns */ async function pauseMusic(ymusic) { if ((await ymusic.getAttribute("#play-pause-button", "title")) == "Pause") { await ymusic.click("#play-pause-button"); // console.log("Paused!"); return "Paused!"; } else { // console.log("Already paused!"); return "Already paused!"; } } /** * If player is paused then resume, else nobody cares. * @param {page} ymusic * @returns */ async function resumeMusic(ymusic) { if ((await ymusic.getAttribute("#play-pause-button", "title")) == "Play") { await ymusic.click("#play-pause-button"); // console.log("Resumed!"); return "Resumed!"; } else { // console.log("Already playing!"); return "Already playing!"; } } /** * If player is playing then pause, else resume. * @param {page} ymusic * @returns */ async function toggleMusic(ymusic) { await ymusic.click("#play-pause-button"); const playerState = await ymusic.getAttribute( "#play-pause-button", "title" ); if (playerState == "Play") { // console.log("Resumed!"); return "Resumed!"; } else { // console.log("Paused!"); return "Paused!"; } } // testing function, to be removed in production async function main() { const { startBrowser } = require("./browser"); const browser = await startBrowser(); const ymusic = await startYMusic(browser); await playMusic( ymusic, "iauydvbklaiudblaidufsblaiuwdfbaiydbf;uiawsgbdg;klasgdlfvakiusdhfwoey9r5h243f" ); await ymusic.waitForTimeout(10000); await playMusic(ymusic, "darkside"); await ymusic.waitForTimeout(10000); await playMusic(ymusic, "lmaoded playlist"); await ymusic.waitForTimeout(10000); await playMusic(ymusic, "lmaoded"); await ymusic.waitForTimeout(10000); await playMusic(ymusic, "eminem"); await ymusic.waitForTimeout(10000); await playMusic(ymusic, "songs about jane"); await ymusic.waitForTimeout(10000); await pauseMusic(ymusic); await ymusic.waitForTimeout(10000); await resumeMusic(ymusic); await ymusic.waitForTimeout(10000); await toggleMusic(ymusic); } // main() module.exports = { startYMusic, playMusic, pauseMusic, resumeMusic, toggleMusic, };
import * as APIUtil from '../util/session_api_util'; export const RECEIVE_USER = 'RECEIVE_USER'; // export const RESET_USER = 'RESET_USER'; export const getUser = (id) => (dispatch) => { return APIUtil.getUser(id).then( (user)=> dispatch(receiveUser(user))); }; // export const resetUser = (id) => (dispatch) => { // return APIUtil.getUser(id).then( // (user) => dispatch(receiveResetUser) // ); // }; export const createFollow = (follow) => (dispatch) => { return APIUtil.addFollow(follow).then( (user) => dispatch(receiveUser(user))); }; export const deleteFollow = (follow) => (dispatch) => { return APIUtil.deleteFollow(follow).then( (user) => dispatch(receiveUser(user))); }; export const receiveUser = (user) => { return { type: RECEIVE_USER, user }; }; // export const receiveResetUser = (user) => { // return { // type: RESET_USER, // user // }; // };
$(document).ready(function () { buildImageCropper(); buildFormSubmit(); $('.cancel').on('click', function(e){ e.preventDefault(); window.location.href = "home"; }); $('#profile-picture-change-form').each(function(){ $(this).data('serialized', $(this).serialize()); }).on('change input', function(){ $(this).find('button[name=submit]').prop('disabled', $(this).serialize() === $(this).data('serialized')); }).find('input[name=submit], button[name=submit]').prop('disabled', true); }); function buildFormSubmit(){ } function buildImageCropper(){ var $image = $(".image-crop > img"); $($image).cropper({ preview: ".img-preview", zoomable: false, done: function(data) { $('input[name=xCanvas]').val(data['x']); $('input[name=yCanvas]').val(data['y']); $('input[name=widthCanvas]').val(data['width']); $('input[name=heightCanvas]').val(data['height']); } }); var $inputImage = $("#inputImage"); if (window.FileReader) { $inputImage.change(function() { var fileReader = new FileReader(), files = this.files, file; if (!files.length) { return; } file = files[0]; if (/^image\/\w+$/.test(file.type)) { fileReader.onload = function () { $image.cropper("reset", true).cropper("replace", this.result); }; fileReader.readAsDataURL(file); } else { showMessage("Por favor, escolha um arquivo de imagem."); } }); } else { $inputImage.addClass("hide"); } }
// Some math and calculation helpers export class Vec2 { constructor(x, y) { this.set(x, y); } set(x, y) { this.x = x; this.y = y; } static dot(a, b) { return ((a.x*b.x)+(a.y*b.y)); } static addv(a, b) { return { x: a.x + b.x, y: a.y + b.y }; } static addi(v, num) { return { x: v.x + num, y: v.y + num }; } static subv(a, b) { return { x: a.x - b.x, y: a.y - b.y }; } static subi(v, num) { return { x: v.x - num, y: v.y - num }; } static mults(v, num) { return { x: v.x * num, y: v.y * num } } static len(v) { return Math.sqrt((v.x*v.x) + (v.y*v.y)); } static norm(v) { let l = Vec2.len(v); if(l === 0) { return v; } else { let scale = 1.0 / l; return { x: v.x * scale, y: v.y * scale }; } } static make(x, y) { return {x, y}; } } export function vec2(x, y) { return {x, y}; } export class Vec3 { constructor(x, y, z) { this.set(x, y, z); } set(x, y, z) { this.x = y; this.y = y; this.z = z; } } export class Box { constructor(x, y, w, h) { this.set_pos(x, y); this.set_size(w, h); } set_pos(x, y) { this.x = x; this.y = y; } set_size(w, h) { this.w = w; this.h = h; } floor() { return { x: Math.floor(this.x), y: Math.floor(this.y), w: Math.floor(this.w), h: Math.floor(this.h), } } } export function CollisionBox(box1, box2) { return !( box1.floor().x + box1.floor().w < box2.floor().x || box1.floor().x > box2.floor().x + box2.floor().w || box1.floor().y + box1.floor().h < box2.floor().y || box1.floor().y > box2.floor().y + box2.floor().h ); } export function CollisionPointBox(x, y, box) { return x >= box.x && x <= box.x + box.w && y >= box.y && y <= box.y + box.y; } export function MoveAgainstVert(box1, box2) { let result = new Box(box1.x, box1.y, box1.w, box1.h); if(CollisionBox(box1, box2)) { let cb1 = new Vec2(box1.x + box1.w/2, box1.y + box1.h/2); let cb2 = new Vec2(box2.x + box2.w/2, box2.y + box2.h/2); if(cb1.y < cb2.y) { result.y = box2.y - box1.h; } else { result.y = box2.y + box2.h; } } return result; } export function MoveAgainstHorz(box1, box2) { let result = new Box(box1.x, box1.y, box1.w, box1.h); if(CollisionBox(box1, box2)) { let cb1 = new Vec2(box1.x + box1.w/2, box1.y + box1.h/2); let cb2 = new Vec2(box2.x + box2.w/2, box2.y + box2.h/2); if(cb1.x < cb2.x) { result.x = box2.x - box1.w; } else { result.x = box2.x + box2.w; } } return result; } export function CollideAgainst(box1, box2, horizontal) { let result_box = new Box(box1.x, box1.y, box1.w, box1.h); if(CollisionBox(box1, box2)) { let cb1 = new Vec2(box1.x + box1.w/2, box1.y + box1.h/2); let cb2 = new Vec2(box2.x + box2.w/2, box2.y + box2.h/2); if(cb1.y >= box2.y && cb1.y <= box2.y + box2.h) { if(cb1.x < cb2.x) { result_box.x = box2.x - box1.w; } else { result_box.x = box2.x + box2.w; } } if(cb1.x >= box2.x && cb1.x <= box2.x + box2.w) { if(cb1.y < cb2.y) { result_box.y = box2.y - box1.h; } else { result_box.y = box2.y + box2.h; } } } return result_box; } export function DistanceCheck(point_a, point_b, distance) { let dstx = Math.abs(point_b.x - point_a.x); let dsty = Math.abs(point_b.y - point_a.y); return ((dstx*dstx)+(dsty*dsty) <= (distance*distance)); } export function clamp(val, lower, upper) { return Math.min(Math.max(val, lower), upper); } // These functions accept Vec2's or Vec2 likes. export let Interpolate = { lerpv(start, end, scale) { let v = Vec2.subv(end, start); v = Vec2.mults(v, scale); return Vec2.addv(start, v); }, lerpi(start, end, scale) { return (scale*(end-start))+start; }, SMOOTHSTEP(t) { return ((t*t)*(3-2*t)); }, SMOOTHERSTEP(t) { return ((t*t*t)*(t*(t*6-15)+10)); }, POWSTEP(t) { return t*t; }, POW2STEP(t) { return t*t*t }, POWSTEPINV(t) { return (1 - (1 - t) * (1 - t)); } }
import { useEffect } from "react" import { useRouter } from "next/router" import * as Fathom from "fathom-client" import { css } from "stitches.config" css.global({ body: { padding: 0, margin: 0, fontFamily: "@body", fontSize: "@1", lineHeight: 1.4, WebkitFontSmoothing: "antialiased", MozOsxFontSmoothing: "grayscale", }, }) export default function App({ Component, pageProps }) { const router = useRouter() useEffect(() => { // Initialize Fathom when the app loads Fathom.load("CUOXTDGQ", { excludedDomains: ["localhost"], url: "https://bee.nfte.app/script.js", }) function onRouteChangeComplete() { Fathom.trackPageview() } // Record a pageview when route changes router.events.on("routeChangeComplete", onRouteChangeComplete) // Unassign event listener return () => { router.events.off("routeChangeComplete", onRouteChangeComplete) } }, []) return <Component {...pageProps} /> }
const mongoose = require('mongoose'); const _ = require('lodash'); const Schema = mongoose.Schema; const EmployeeSchema = new Schema({ name: { type: String, required: true, minlength: 5, maxlength: 100 }, salary: { type: Number, required: true }, address: { type: String, required: true, minlength: 10, maxlength: 200 }, senior: { type: Boolean, required: true }, workExperience: { type: Number, required: true } }); EmployeeSchema.methods.toJSON = function () { const employee = this; return _.omit(employee.toObject(), ['__v']); }; const Employee = mongoose.model('Employee', EmployeeSchema); module.exports = Employee; module.exports.getListOfEmployees = () => { return Employee.find(); }; module.exports.getUserById = (root, {_id}) => { return Employee.findById({_id}); }; module.exports.addEmployee = (root, employeeInfo) => { const newUser = new Employee(employeeInfo); return newUser.save(); }; module.exports.updateEmployee = async (root, employeeInfo) => { const employee = await Employee.findById(employeeInfo._id); const employeeDoc = _.extend(employee, _.omit(employeeInfo, ['_id'])); return employeeDoc.save(); }; module.exports.deleteEmployee = async (root, {_id}) => { const employee = await Employee.findById(_id); return employee.remove(); };
$(document).ready(function() { var eventDate = $(".add-event-form").find(".input-group.date"); if (eventDate) { $('.input-group.date').datepicker({}); } $('#confirm-delete').on('show.bs.modal', function(e) { $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href')); $('.proj-name').html('<strong>' + $(e.relatedTarget).data('project') + '</strong>'); }); /* $(window).scroll(function() { if($(window).scrollTop() == $(document).height() - $(window).height()) { $.ajax({ url: "/timelineItems", type: 'GET', success: function (response) { $("#jobs-container").append(response); } }); } });*/ $(".projectUsers").click(function(e){ e.preventDefault();//this will prevent the link trying to navigate to another page var href = $(this).attr("href");//get the href so we can navigate later $("#hdnPage").val(parseInt($(this).data("page")) -1 ); $("#hdnSize").val($(this).data("size")); var username = $("#txtUserName").val(); if(username){ href = href.concat("&username="+username); } //when update has finished, navigate to the other page //window.location = href; $(".project-users-form").submit(); }); $(".remove-userd").click(function(e){ e.preventDefault(); // Set the remove user flag $("#hdnRemoveUser").val(true); $("#hdnUserId").val($(this).data("userid")); // Submit the form //$(".project-users-form").submit(); }); $(".add-user").click(function(e){ // Set the remove user flag $("#hdnAddUser").val(true); $("#hdnUserId").val($(this).data("userid")); // Submit the form $(".project-users-form").submit(); }); $(".btn-ok").click(function(e){ $(".project-users-form").submit(); }); });
angular.module('ForgotCtrl', []).controller('ForgotPasswordController', function($scope, $window, authentication) { //Credetials to be sent to server $scope.credentials = { email : "", }; $scope.errorMessageForgot = false; $scope.successMessageForgot = false; //make call to forgot password with AuthService $scope.onSubmit = function () { $scope.successMessageForgot = "Please wait..." console.log("reseting password"); authentication .forgotPassword($scope.credentials) .then(function(data){ console.log(data); $scope.errorMessageForgot = false; $scope.successMessageForgot = "An email has been sent to your account." }, function(err){ console.log(err); $scope.successMessageForgot = false; switch(err.data.message) { case 'noEmailError': $scope.errorMessageForgot = 'No account with that email address exists.'; break; default: $scope.errorMessageForgot = 'An error occurred during password reset.'; break; } // $scope.errorMessage = err.data.message; }); }; });
/** * Copyright © 2014 Julian Reyes Escrigas <julian.reyes.escrigas@gmail.com> * * This file is part of concepto-sises. * * concepto-sises * can not be copied and/or distributed without the express * permission of Julian Reyes Escrigas <julian.reyes.escrigas@gmail.com> */ ; (function () { "use strict"; G.modules.RRHH = 'RRHH'; G.BuildModule(G.modules.RRHH, { register: true, label: 'RRHH', category: 'empresas', resource: 'recurso_humano' }); })();
var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); var indexRouter = require('./routes/index'); var usersRouter = require('./routes/users'); var app = express(); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('*', indexRouter); // app.use('/users', usersRouter); // var { graphqlHTTP } = require('express-graphql'); // var { buildSchema } = require('graphql'); // // Construct a schema, using GraphQL schema language // // Sets routes and return types // var schema = buildSchema(` // type Query { // quoteOfTheDay: String // random: Float! // rollDice(numDice: Int!, numSides: Int): [Int] // } // `); // // The root provides a resolver function for each API endpoint // var root = { // quoteOfTheDay: () => { // return Math.random() < 0.5 ? 'Take it easy' : 'Salvation lies within'; // }, // random: () => { // return Math.random(); // }, // rollDice: ({numDice, numSides}) => { // var output = []; // for (var i = 0; i < numDice; i++) { // output.push(1 + Math.floor(Math.random() * (numSides || 6))); // } // return output; // } // }; // var app = express(); // app.use('/graphql', graphqlHTTP({ // schema: schema, // rootValue: root, // graphiql: true, // })); module.exports = app;
/** * @author v.lugovsky * created on 16.12.2015 */ (function () { 'use strict'; angular.module('BlurAdmin.pages.safeEdu') .controller('safeEduPageCtrl', safeEduPageCtrl); /** @ngInject */ function safeEduPageCtrl($scope, $filter, editableOptions, editableThemes) { $scope.smartTablePageSize = 10; $scope.innerTableData = [{ id: "1", month: "五月", num: "LYABB20190208", project: "地震知识培训", cate: "其它", persion: "各部门员工", addr: "场内" }]; // 资格证table数据 $scope.eduTableData = [ { id: "1", num: "PXLA12014854", cate: "安全生产", name: "安全生产督导师", persion: "徐健", sex: "男", dept: "安全保卫科", perDate: "2017-01-01", eduDept: "国家就业培训技术指导中心", deuDate: "--", isCancel: "否" }, { id: "2", num: "PXLA12012874", cate: "安全生产", name: "安全生产检测师", persion: "郭华龙", sex: "男", dept: "安全保卫科", perDate: "2018-04-01", eduDept: "国家就业培训技术指导中心", deuDate: "--", isCancel: "否" }, { id: "3", num: "PXLA12003454", cate: "安全生产", name: "生产实施师", persion: "孙希子", sex: "女", dept: "生产部", perDate: "2017-09-10", eduDept: "国家就业培训技术指导中心", deuDate: "--", isCancel: "否" }, { id: "4", num: "PXLA12014854", cate: "安全生产", name: "安全生产督导师", persion: "徐健康", sex: "男", dept: "安全保卫科", perDate: "2017-01-01", eduDept: "国家就业培训技术指导中心", deuDate: "--", isCancel: "否" }, { id: "5", num: "PXLA12012874", cate: "安全生产", name: "生产检测师", persion: "郭晓龙", sex: "男", dept: "生产部", perDate: "2010-04-01", eduDept: "国家就业培训技术指导中心", deuDate: "--", isCancel: "否" }, { id: "6", num: "PXLA12003454", cate: "安全生产", name: "安全生产实施师", persion: "冷冰", sex: "女", dept: "安全保卫科", perDate: "2017-09-10", eduDept: "国家就业培训技术指导中心", deuDate: "--", isCancel: "否" }, { id: "7", num: "PXLA12014854", cate: "安全生产", name: "安全生产督导师", persion: "徐晓健", sex: "男", dept: "安全保卫科", perDate: "2007-01-01", eduDept: "省级就业培训技术指导中心", deuDate: "--", isCancel: "否" }, { id: "8", num: "PXLA12012874", cate: "安全生产", name: "生产检测师", persion: "吴华", sex: "男", dept: "生产部", perDate: "2008-04-01", eduDept: "省级就业培训技术指导中心", deuDate: "--", isCancel: "否" }, { id: "9", num: "PXLA12003454", cate: "安全生产", name: "生产实施师", persion: "冷晓", sex: "女", dept: "生产部", perDate: "2017-09-10", eduDept: "省级就业培训技术指导中心", deuDate: "--", isCancel: "否" }, { id: "10", num: "PXLA12013424", cate: "安全生产", name: "安全生产督导师", persion: "邱东", sex: "男", dept: "安全保卫科", perDate: "2007-01-30", eduDept: "国家就业培训技术指导中心", deuDate: "--", isCancel: "否" }, { id: "11", num: "PXLA12012274", cate: "安全生产", name: "母猪产后护理", persion: "西子", sex: "女", dept: "动物委员会", perDate: "2011-01-01", eduDept: "国家就业培训技术指导中心", deuDate: "--", isCancel: "否" }, { id: "12", num: "PXLA12004454", cate: "安全生产", name: "安全生产实施师", persion: "万德", sex: "女", dept: "信息安全科", perDate: "2008-09-10", eduDept: "省级就业培训技术指导中心", deuDate: "--", isCancel: "否" }, ]; } })();
var searchData= [ ['grille_5fafficher',['grille_afficher',['../affichage_8c.html#a01ec43ffd117d89bf879cc74b3c7e052',1,'affichage.c']]], ['grille_5finitialiser',['grille_initialiser',['../joueur__contre__joueur_8c.html#a9191a0d9d7aadf2c9e4f4a9e85273dec',1,'joueur_contre_joueur.c']]] ];
var pushIt = document.getElementById("button"); var showBlock = document.getElementById("order"); console.log(pushIt); console.log(showBlock); pushIt.onclick = function(){ if(showBlock.style.display == "none"){ showBlock.style.display = "block"; }else if(showBlock.style.display != "none"){ showBlock.style.display = "none"; }; };
import React from "react"; import { Helmet } from "react-helmet"; import LinearProgress from '@material-ui/core/LinearProgress'; import Fade from '@material-ui/core/Fade'; import Chip from '@material-ui/core/Chip'; import undraw_resume from '../imgs/undraw_resume.svg'; const styles = { bar: { marginTop: "30px", }, add_skills: { marginTop: "40px", }, hr: { borderColor: 'rgb(31, 80, 255)', width: '15%', height: '1px', background: 'rgb(31, 80, 255)', marginTop: '30px', }, chip: { border: '2px solid rgb(31, 80, 255)', color: '#ffffff', padding: '10px', margin: '10px', backgroundColor: 'rgb(31, 80, 255)', fontWeight: '600', textTransform: 'uppercase', }, }; function Skills(props) { const [progress_HTML, setProgress] = React.useState(0); const [progress_wordpress, setProgress3] = React.useState(0); React.useEffect(() => { const timer = setInterval(() => { setProgress3(() => { const diff = 95; return diff; }); }, 100); return () => { clearInterval(timer); }; }, []); React.useEffect(() => { const timer = setInterval(() => { setProgress(() => { const diff = 90; return diff; }); }, 200); return () => { clearInterval(timer); }; }, []); const [progress_CSS, setProgress2] = React.useState(0); React.useEffect(() => { const timer = setInterval(() => { setProgress2(() => { const diff = 85; return diff; }); }, 300); return () => { clearInterval(timer); }; }, []); const [progress_js, setProgress4] = React.useState(0); React.useEffect(() => { const timer = setInterval(() => { setProgress4(() => { const diff = 75; return diff; }); }, 400); return () => { clearInterval(timer); }; }, []); const [progress_react, setProgress5] = React.useState(0); React.useEffect(() => { const timer = setInterval(() => { setProgress5(() => { const diff = 70; return diff; }); }, 500); return () => { clearInterval(timer); }; }, []); return ( <div> <Helmet> <title>Skills | Brendan Lenzner</title> <meta name="description" content="Front-End Web Developer, WordPress, React Developer" /> </Helmet> <div className="skils"> <Fade in={true}> <h2 className="page-title">Skills</h2> </Fade> <div className="row"> <div className="col-sm-2"> <strong><p>WordPress</p></strong> </div> <div className="col-sm-10"> <LinearProgress style={styles.bar} className="wordpress_bar" variant="determinate" value={progress_wordpress} /> </div> </div> <div className="row"> <div className="col-sm-2"> <strong><p>HTML5</p></strong> </div> <div className="col-sm-10"> <LinearProgress style={styles.bar} className="html_bar" variant="determinate" value={progress_HTML} /> </div> </div> <div className="row"> <div className="col-sm-2"> <strong><p>CSS3</p></strong> </div> <div className="col-sm-10"> <LinearProgress style={styles.bar} className="css_bar" variant="determinate" value={progress_CSS} /> </div> </div> <div className="row"> <div className="col-sm-2"> <strong><p>JavaScript</p></strong> </div> <div className="col-sm-10"> <LinearProgress style={styles.bar} className="js_bar" variant="determinate" value={progress_js} /> </div> </div> <div className="row"> <div className="col-sm-2"> <strong><p>React.js</p></strong> </div> <div className="col-sm-10"> <LinearProgress style={styles.bar} className="react_bar" variant="determinate" value={progress_react} /> </div> </div> <Fade in={true}> <div style={styles.add_skills}> <h3>Additonal Skills</h3> <Chip style={styles.chip} label="Drupal" variant="outlined" /> <Chip style={styles.chip} label="Omeka" variant="outlined" /> <Chip style={styles.chip} label="Adobe Photoshop" variant="outlined" /> <Chip style={styles.chip} label="Adobe XD" variant="outlined" /> <Chip style={styles.chip} label="PHP" variant="outlined" /> <Chip style={styles.chip} label="Python" variant="outlined" /> <Chip style={styles.chip} label="SQL" variant="outlined" /> <Chip style={styles.chip} label="Bootstrap" variant="outlined" /> <Chip style={styles.chip} label="Google Analytics" variant="outlined" /> <Chip style={styles.chip} label="Java" variant="outlined" /> <Chip style={styles.chip} label="Swift" variant="outlined" /> </div> </Fade> </div> <hr style={styles.hr} /> <Fade in={true}> <div className="skills-img"><img src={undraw_resume} alt="resume graphic" /></div> </Fade> </div> ) } export default Skills;
const matter = require('gray-matter'); const glob = require('glob'); const fs = require('fs'); const R = require('ramda'); export function get(directory) { return glob.sync(directory); } export function read(path) { return fs.readFileSync(path, 'utf8'); } export function write(path, content) { return fs.writeFileSync(path, content, 'utf8'); } export function existsAt(path) { return fs.existsSync(path); } export function readMatterToObj(path) { return get(path).map(x => matter.read(x)); } export const readJSON = R.compose(JSON.parse, read);
function linearSearch(value, array) { for (let i = 0; i < array.length; i++) { if (array[i] === value) { return value; } } return -1; } function recursiveBinarySearch(value, array) { let middleIdx = Math.floor(array.length / 2); if (value == array[middleIdx]) { return value } if (array.length) { if (value < array[middleIdx]) { return recursiveBinarySearch(value, array.slice(0, middleIdx)); } else { return recursiveBinarySearch(value, array.slice(middleIdx)) } } return -1 } function iterativeBinarySearch(value, array) { let minIdx = 0; let maxIdx = array.length - 1; let middleIdx; while (minIdx <= maxIdx) { middleIdx = Math.floor((maxIdx + minIdx) / 2); if (value === array[middleIdx]) { return value } else if (value < array[middleIdx]) { maxIdx = middleIdx - 1; } else { minIdx = middleIdx + 1; } } return -1 } const array = [1, 2, 3, 4, 5, 6]; console.log(linearSearch(3, array)); console.log(recursiveBinarySearch(3, array)); console.log(iterativeBinarySearch(0, array)); console.log(iterativeBinarySearch(1, array)); console.log(iterativeBinarySearch(2, array)); console.log(iterativeBinarySearch(3, array)); console.log(iterativeBinarySearch(4, array)); console.log(iterativeBinarySearch(5, array)); console.log(iterativeBinarySearch(6, array)); console.log(iterativeBinarySearch(7, array));
class Avatar extends Phaser.Sprite { //initialization code in the constructor constructor(game, x, y, frame, bullet, infinite, c, d) { super(game, x, y, 'horse', frame); console.log(game, x, y, frame, 'bullet sprite referenced from game state', bullet, 'inifinite run: no velocity test', infinite, 'custom param3', c , 'custom param 4', d); this.anchor.setTo(0.5, 0.5); this.animations.add('walk'); this.animations.play('walk', 30, true); //basic speed variables this.maxVelocity = 1000; this.acceleleration = 100; this.gravity = 1600; this.velocityX = 0; this.infinite = infinite; this.accelerate = true; this.onGround = false; //jumping mechanic variables this.doubleJump = false; this.tripleJump = false; this.jumpHeight = -750; //dashing mechanic variables this.dashing = false; this.dashingVelocity = 0; this.dashingFor = 0; //set: how long; accel: how fast this.dashSet = 300; this.dashSpeed = 1000; this.dashNext = 0; //1 = forward : 2 = backward this.direction = 1; this.directDelay = 100; //setup game physics in class constructor:: unicorn go!! this.game.physics.enable(this); this.body.maxVelocity.setTo(this.maxVelocity, this.maxVelocity); this.body.gravity.y = this.gravity; this.body.collideWorldBounds = true; this.body.tilePadding.set(50, 50); this.nextFire = 0; this.fireRate = 50; this.ammoAmount = 24; this.ammo = this.ammoAmount; this.reloadDelay = 0; this.reloadSpeed = 2000; this.gun = this.game.add.group(); this.gun.enableBody = true; this.gun.physicsBodyType = Phaser.Physics.ARCADE; this.gun.createMultiple(this.ammoAmount * 2, 'rocket'); this.gun.setAll('checkWorldBounds', true); this.gun.setAll('outOfBoundsKill', true); if (!infinite) this.game.camera.follow(this, Phaser.Camera.FOLLOW_PLATFORMER); // this.game.camera.deadzone = new Phaser.Rectangle(100, 100, this.game.width/16, this.game.height/16); } //Code ran on each frame of game update() { //dash attack w delay if (this.dashing) this.dashingAttack(); this.movementUpdate(); } //TODO seperate this code from main internal game loop. Can be heavy on performance for free roaming parts movementUpdate(){ //free roaming enviroment if ( !this.infinite ) { //endless acceleration if (this.accelerate) { this.direction ? this.body.acceleration.x = this.acceleleration : this.body.acceleration.x = -this.acceleleration; this.velocityX = this.body.velocity.x; } else { //this line creates problem with normal Phaser physics routine if (this.dashing) this.body.velocity.x = this.velocityX; } //endless enviroment } else { //acceleration illusion, holy shit three conditionals in one line... fucking TODO ( Math.abs(this.velocityX) < this.maxVelocity / 2 ) ? this.direction ? this.velocityX += 1 : this.velocityX -= 1 : this.direction ? this.velocityX -= 5 : this.velocityX += 5; if ( this.dashing ) { this.direction ? this.body.velocity.x = this.dashSpeed : this.body.velocity.x = -this.dashSpeed; } else { //TODO create function to check + improve. Goal is to position avatar from the opposite momentum, also could just consolidate into one conditional if ( this.body.position.x > this.game.world.width * 7/8 ) { this.body.velocity.x = -600; } else if ( this.body.position.x > this.game.world.width * 1/6 && this.direction ) { this.body.velocity.x = -200; } else if ( this.body.position.x < this.game.world.width * 1/8 ) { this.body.velocity.x = 600; } else if ( this.body.position.x < this.game.world.width * 3/4 && !this.direction ) { this.body.velocity.x = 200; } else { this.body.velocity.x = 0; if (!this.accelerate) this.velocityX = 0; } } } if (Math.abs(this.velocityX) > 475 && Math.abs(this.velocityX) < 510) this.direction ? this.velocityX = 500 : this.velocityX = -500; //match avatar velocity with animation speed (Math.abs(this.velocityX / 20) > 5) ? this.animations._anims.walk.speed = Math.abs(this.velocityX / 20) : this.animations._anims.walk.speed = 5; //debug spaghetti loop console.log(this.direction, 'accel ', this.accelerate, 'dash ', this.dashing, 'jump ', this.doubleJump, this.tripleJump, this.velocityX); } movePlayerPosition(move){ if ( this.body.position.x > this.game.world.width * 7/8 ); } //input methods inputLeft(){ if (this.direction && !this.dashing) { this.changeDirection(); } else if (this.direction && this.dashing) { this.jump(); this.changeDirection(); } else if (!this.direction && this.dashing) { } else { if (this.game.time.now > this.dashNext) this.dashReset(); } } inputRight(){ console.log('input right', this.direction, this.dashing); if (!this.direction && !this.dashing) { this.changeDirection(); } else if (!this.direction && this.dashing) { this.jump(); this.changeDirection(); } else if (this.direction && this.dashing) { } else { if (this.game.time.now > this.dashNext) this.dashReset(); } } inputDown(){ this.body.velocity.y = 10000; } inputUp(){ } //basic mouse + touch input acivteInput(pointer){ this.fire(pointer); } dashingAttack() { //normal dash if (this.game.time.now < this.dashingFor) { this.velocityX = this.dashingVelocity; } else { //reset dashing this.dashing = false; this.accelerate = true; } } dashReset() { this.dashing = true; this.dashingFor = (this.dashSet) + this.game.time.now; this.dashNext = (this.dashSet*2) + this.game.time.now; this.direction ? this.dashingVelocity = this.dashSpeed : this.dashingVelocity = -this.dashSpeed; this.infinite ? this.velocityX /= 5 : this.body.velocity.x /= 5; } changeDirection() { if (this.game.time.now > this.directDelay) { this.directDelay = this.game.time.now + 500; this.direction ? this.direction = 0 : this.direction = 1; this.animations._anims.walk.speed = 5; this.scale.x *= -1; //quick hack to make work with infinite + tilemap this.infinite ? this.velocityX = 0 : this.body.velocity.x = 0; this.accelerate = false; } } fire(point) { this.fireAt = point; if ( this.game.time.now > this.nextFire && this.gun.countDead() > 0 && this.ammo > 0 ) { this.nextFire = this.game.time.now + this.fireRate; this.bullet = this.gun.getFirstDead(); this.bullet.reset(this.x, this.y); this.bullet.anchor.setTo(0.5, 0.5); this.bullet.rotation = this.game.physics.arcade.moveToPointer(this.bullet, 1000, this.fireAt); this.ammo--; if (this.ammo === 0) this.reloadDelay = this.game.time.now + this.reloadSpeed; } else if (this.ammo === 0 && this.game.time.now > this.reloadDelay) { this.ammo = this.ammoAmount; } } jump() { if (this.doubleJump || this.tripleJump || this.onGround) { this.body.velocity.y = this.jumpHeight; this.jumpReset(); } } jumpReset() { console.log('jumpreset' , this.onGround, this.doubleJump , this.tripleJump); if (this.onGround && !this.doubleJump && !this.tripleJump) { this.doubleJump = true; } else if (!this.onGround && this.doubleJump && !this.tripleJump){ this.tripleJump = true; } else if (!this.onGround && this.doubleJump && this.tripleJump){ this.doubleJump = false; this.tripleJump = false; } else { console.log('error', this.doubleJump , this.tripleJump , this.onGround); } } } export default Avatar;
function setup() { createCanvas(windowWidth, windowHeight); background(51); } function draw() { stroke(255, 0, 200); strokeWeight(10); if (mouseIsPressed === true) { line(mouseX, mouseY, pmouseX, pmouseY); } }
import { Debug } from '../../../core/debug.js'; import { BLEND_NONE, FRESNEL_SCHLICK, SHADER_FORWARD, SHADER_FORWARDHDR, SPECULAR_PHONG, SPRITE_RENDERMODE_SLICED, SPRITE_RENDERMODE_TILED } from '../../constants.js'; import { ShaderPass } from '../../shader-pass.js'; import { LitShader } from './lit-shader.js'; import { ChunkBuilder } from '../chunk-builder.js'; import { ChunkUtils } from '../chunk-utils.js'; import { StandardMaterialOptions } from '../../materials/standard-material-options.js'; import { LitOptionsUtils } from './lit-options-utils.js'; import { ShaderGenerator } from './shader-generator.js'; const _matTex2D = []; const buildPropertiesList = (options) => { return Object.keys(options) .filter(key => key !== "litOptions") .sort(); }; class ShaderGeneratorStandard extends ShaderGenerator { // Shared Standard Material option structures optionsContext = new StandardMaterialOptions(); optionsContextMin = new StandardMaterialOptions(); generateKey(options) { let props; if (options === this.optionsContextMin) { if (!this.propsMin) this.propsMin = buildPropertiesList(options); props = this.propsMin; } else if (options === this.optionsContext) { if (!this.props) this.props = buildPropertiesList(options); props = this.props; } else { props = buildPropertiesList(options); } const key = "standard:\n" + props.map(prop => prop + options[prop]).join('\n') + LitOptionsUtils.generateKey(options.litOptions); return key; } // get the value to replace $UV with in Map Shader functions /** * Get the code with which to to replace '$UV' in the map shader functions. * * @param {string} transformPropName - Name of the transform id in the options block. Usually "basenameTransform". * @param {string} uVPropName - Name of the UV channel in the options block. Usually "basenameUv". * @param {object} options - The options passed into createShaderDefinition. * @returns {string} The code used to replace "$UV" in the shader code. * @private */ _getUvSourceExpression(transformPropName, uVPropName, options) { const transformId = options[transformPropName]; const uvChannel = options[uVPropName]; const isMainPass = options.litOptions.pass === SHADER_FORWARD || options.litOptions.pass === SHADER_FORWARDHDR; let expression; if (isMainPass && options.litOptions.nineSlicedMode === SPRITE_RENDERMODE_SLICED) { expression = "nineSlicedUv"; } else if (isMainPass && options.litOptions.nineSlicedMode === SPRITE_RENDERMODE_TILED) { expression = "nineSlicedUv"; } else { if (transformId === 0) { expression = "vUv" + uvChannel; } else { // note: different capitalization! expression = "vUV" + uvChannel + "_" + transformId; } // if heightmap is enabled all maps except the heightmap are offset if (options.heightMap && transformPropName !== "heightMapTransform") { expression += " + dUvOffset"; } } return expression; } _addMapDef(name, enabled) { return enabled ? `#define ${name}\n` : `#undef ${name}\n`; } _addMapDefs(float, color, vertex, map, invert) { return this._addMapDef("MAPFLOAT", float) + this._addMapDef("MAPCOLOR", color) + this._addMapDef("MAPVERTEX", vertex) + this._addMapDef("MAPTEXTURE", map) + this._addMapDef("MAPINVERT", invert); } /** * Add chunk for Map Types (used for all maps except Normal). * * @param {string} propName - The base name of the map: diffuse | emissive | opacity | light | height | metalness | specular | gloss | ao. * @param {string} chunkName - The name of the chunk to use. Usually "basenamePS". * @param {object} options - The options passed into to createShaderDefinition. * @param {object} chunks - The set of shader chunks to choose from. * @param {object} mapping - The mapping between chunk and sampler * @param {string} encoding - The texture's encoding * @returns {string} The shader code to support this map. * @private */ _addMap(propName, chunkName, options, chunks, mapping, encoding = null) { const mapPropName = propName + "Map"; const uVPropName = mapPropName + "Uv"; const identifierPropName = mapPropName + "Identifier"; const transformPropName = mapPropName + "Transform"; const channelPropName = mapPropName + "Channel"; const vertexColorChannelPropName = propName + "VertexColorChannel"; const tintPropName = propName + "Tint"; const vertexColorPropName = propName + "VertexColor"; const detailModePropName = propName + "Mode"; const invertName = propName + "Invert"; const tintOption = options[tintPropName]; const vertexColorOption = options[vertexColorPropName]; const textureOption = options[mapPropName]; const textureIdentifier = options[identifierPropName]; const detailModeOption = options[detailModePropName]; let subCode = chunks[chunkName]; if (textureOption) { const uv = this._getUvSourceExpression(transformPropName, uVPropName, options); subCode = subCode.replace(/\$UV/g, uv).replace(/\$CH/g, options[channelPropName]); if (mapping && subCode.search(/\$SAMPLER/g) !== -1) { let samplerName = "texture_" + mapPropName; const alias = mapping[textureIdentifier]; if (alias) { samplerName = alias; } else { mapping[textureIdentifier] = samplerName; } subCode = subCode.replace(/\$SAMPLER/g, samplerName); } if (encoding) { if (options[channelPropName] === 'aaa') { // completely skip decoding if the user has selected the alpha channel (since alpha // is never decoded). subCode = subCode.replace(/\$DECODE/g, 'passThrough'); } else { subCode = subCode.replace(/\$DECODE/g, ChunkUtils.decodeFunc((!options.litOptions.gamma && encoding === 'srgb') ? 'linear' : encoding)); } // continue to support $texture2DSAMPLE if (subCode.indexOf('$texture2DSAMPLE')) { const decodeTable = { linear: 'texture2D', srgb: 'texture2DSRGB', rgbm: 'texture2DRGBM', rgbe: 'texture2DRGBE' }; subCode = subCode.replace(/\$texture2DSAMPLE/g, decodeTable[encoding] || 'texture2D'); } } } if (vertexColorOption) { subCode = subCode.replace(/\$VC/g, options[vertexColorChannelPropName]); } if (detailModeOption) { subCode = subCode.replace(/\$DETAILMODE/g, detailModeOption); } const isFloatTint = !!(tintOption & 1); const isVecTint = !!(tintOption & 2); const invertOption = !!(options[invertName]); subCode = this._addMapDefs(isFloatTint, isVecTint, vertexColorOption, textureOption, invertOption) + subCode; return subCode.replace(/\$/g, ""); } _correctChannel(p, chan, _matTex2D) { if (_matTex2D[p] > 0) { if (_matTex2D[p] < chan.length) { return chan.substring(0, _matTex2D[p]); } else if (_matTex2D[p] > chan.length) { let str = chan; const chr = str.charAt(str.length - 1); const addLen = _matTex2D[p] - str.length; for (let i = 0; i < addLen; i++) str += chr; return str; } return chan; } } /** * @param {import('../../../platform/graphics/graphics-device.js').GraphicsDevice} device - The * graphics device. * @param {StandardMaterialOptions} options - The create options. * @returns {object} Returns the created shader definition. * @ignore */ createShaderDefinition(device, options) { const shaderPassInfo = ShaderPass.get(device).getByIndex(options.litOptions.pass); const isForwardPass = shaderPassInfo.isForward; const litShader = new LitShader(device, options.litOptions); // generate vertex shader const useUv = []; const useUnmodifiedUv = []; const mapTransforms = []; const maxUvSets = 2; const textureMapping = {}; for (const p in _matTex2D) { const mname = p + "Map"; if (options[p + "VertexColor"]) { const cname = p + "VertexColorChannel"; options[cname] = this._correctChannel(p, options[cname], _matTex2D); } if (options[mname]) { const cname = mname + "Channel"; const tname = mname + "Transform"; const uname = mname + "Uv"; options[uname] = Math.min(options[uname], maxUvSets - 1); options[cname] = this._correctChannel(p, options[cname], _matTex2D); const uvSet = options[uname]; useUv[uvSet] = true; useUnmodifiedUv[uvSet] = useUnmodifiedUv[uvSet] || (options[mname] && !options[tname]); // create map transforms if (options[tname]) { mapTransforms.push({ name: p, id: options[tname], uv: options[uname] }); } } } if (options.forceUv1) { useUv[1] = true; useUnmodifiedUv[1] = (useUnmodifiedUv[1] !== undefined) ? useUnmodifiedUv[1] : true; } litShader.generateVertexShader(useUv, useUnmodifiedUv, mapTransforms); // handle fragment shader if (options.litOptions.shadingModel === SPECULAR_PHONG) { options.litOptions.fresnelModel = 0; options.litOptions.ambientSH = false; } else { options.litOptions.fresnelModel = (options.litOptions.fresnelModel === 0) ? FRESNEL_SCHLICK : options.litOptions.fresnelModel; } const decl = new ChunkBuilder(); const code = new ChunkBuilder(); const func = new ChunkBuilder(); const args = new ChunkBuilder(); let lightingUv = ""; // global texture bias for standard textures if (options.litOptions.nineSlicedMode === SPRITE_RENDERMODE_TILED) { decl.append(`const float textureBias = -1000.0;`); } else { decl.append(`uniform float textureBias;`); } if (isForwardPass) { // parallax if (options.heightMap) { // if (!options.normalMap) { // const transformedHeightMapUv = this._getUvSourceExpression("heightMapTransform", "heightMapUv", options); // if (!options.hasTangents) tbn = tbn.replace(/\$UV/g, transformedHeightMapUv); // code += tbn; // } decl.append("vec2 dUvOffset;"); code.append(this._addMap("height", "parallaxPS", options, litShader.chunks, textureMapping)); func.append("getParallax();"); } // opacity if (options.litOptions.blendType !== BLEND_NONE || options.litOptions.alphaTest || options.litOptions.alphaToCoverage) { decl.append("float dAlpha;"); code.append(this._addMap("opacity", "opacityPS", options, litShader.chunks, textureMapping)); func.append("getOpacity();"); args.append("litArgs_opacity = dAlpha;"); if (options.litOptions.alphaTest) { code.append(litShader.chunks.alphaTestPS); func.append("alphaTest(dAlpha);"); } } else { decl.append("float dAlpha = 1.0;"); } // normal if (litShader.needsNormal) { if (options.normalMap || options.clearCoatNormalMap) { // TODO: let each normalmap input (normalMap, normalDetailMap, clearCoatNormalMap) independently decide which unpackNormal to use. code.append(options.packedNormal ? litShader.chunks.normalXYPS : litShader.chunks.normalXYZPS); if (!options.litOptions.hasTangents) { // TODO: generalize to support each normalmap input (normalMap, normalDetailMap, clearCoatNormalMap) independently const baseName = options.normalMap ? "normalMap" : "clearCoatNormalMap"; lightingUv = this._getUvSourceExpression(`${baseName}Transform`, `${baseName}Uv`, options); } } decl.append("vec3 dNormalW;"); code.append(this._addMap("normalDetail", "normalDetailMapPS", options, litShader.chunks, textureMapping)); code.append(this._addMap("normal", "normalMapPS", options, litShader.chunks, textureMapping)); func.append("getNormal();"); args.append("litArgs_worldNormal = dNormalW;"); } if (litShader.needsSceneColor) { decl.append("uniform sampler2D uSceneColorMap;"); } if (litShader.needsScreenSize) { decl.append("uniform vec4 uScreenSize;"); } if (litShader.needsTransforms) { decl.append("uniform mat4 matrix_viewProjection;"); decl.append("uniform mat4 matrix_model;"); } // support for diffuse & ao detail modes if (options.diffuseDetail || options.aoDetail) { code.append(litShader.chunks.detailModesPS); } // albedo decl.append("vec3 dAlbedo;"); if (options.diffuseDetail) { code.append(this._addMap("diffuseDetail", "diffuseDetailMapPS", options, litShader.chunks, textureMapping, options.diffuseDetailEncoding)); } code.append(this._addMap("diffuse", "diffusePS", options, litShader.chunks, textureMapping, options.diffuseEncoding)); func.append("getAlbedo();"); args.append("litArgs_albedo = dAlbedo;"); if (options.litOptions.useRefraction) { decl.append("float dTransmission;"); code.append(this._addMap("refraction", "transmissionPS", options, litShader.chunks, textureMapping)); func.append("getRefraction();"); args.append("litArgs_transmission = dTransmission;"); decl.append("float dThickness;"); code.append(this._addMap("thickness", "thicknessPS", options, litShader.chunks, textureMapping)); func.append("getThickness();"); args.append("litArgs_thickness = dThickness;"); } if (options.litOptions.useIridescence) { decl.append("float dIridescence;"); code.append(this._addMap("iridescence", "iridescencePS", options, litShader.chunks, textureMapping)); func.append("getIridescence();"); args.append("litArgs_iridescence_intensity = dIridescence;"); decl.append("float dIridescenceThickness;"); code.append(this._addMap("iridescenceThickness", "iridescenceThicknessPS", options, litShader.chunks, textureMapping)); func.append("getIridescenceThickness();"); args.append("litArgs_iridescence_thickness = dIridescenceThickness;"); } // specularity & glossiness if ((litShader.lighting && options.litOptions.useSpecular) || litShader.reflections) { decl.append("vec3 dSpecularity;"); decl.append("float dGlossiness;"); if (options.litOptions.useSheen) { decl.append("vec3 sSpecularity;"); code.append(this._addMap("sheen", "sheenPS", options, litShader.chunks, textureMapping, options.sheenEncoding)); func.append("getSheen();"); args.append("litArgs_sheen_specularity = sSpecularity;"); decl.append("float sGlossiness;"); code.append(this._addMap("sheenGloss", "sheenGlossPS", options, litShader.chunks, textureMapping)); func.append("getSheenGlossiness();"); args.append("litArgs_sheen_gloss = sGlossiness;"); } if (options.litOptions.useMetalness) { decl.append("float dMetalness;"); code.append(this._addMap("metalness", "metalnessPS", options, litShader.chunks, textureMapping)); func.append("getMetalness();"); args.append("litArgs_metalness = dMetalness;"); decl.append("float dIor;"); code.append(this._addMap("ior", "iorPS", options, litShader.chunks, textureMapping)); func.append("getIor();"); args.append("litArgs_ior = dIor;"); } if (options.litOptions.useSpecularityFactor) { decl.append("float dSpecularityFactor;"); code.append(this._addMap("specularityFactor", "specularityFactorPS", options, litShader.chunks, textureMapping)); func.append("getSpecularityFactor();"); args.append("litArgs_specularityFactor = dSpecularityFactor;"); } if (options.useSpecularColor) { code.append(this._addMap("specular", "specularPS", options, litShader.chunks, textureMapping, options.specularEncoding)); } else { code.append("void getSpecularity() { dSpecularity = vec3(1); }"); } code.append(this._addMap("gloss", "glossPS", options, litShader.chunks, textureMapping)); func.append("getGlossiness();"); func.append("getSpecularity();"); args.append("litArgs_specularity = dSpecularity;"); args.append("litArgs_gloss = dGlossiness;"); } else { decl.append("vec3 dSpecularity = vec3(0.0);"); decl.append("float dGlossiness = 0.0;"); } // ao if (options.aoDetail) { code.append(this._addMap("aoDetail", "aoDetailMapPS", options, litShader.chunks, textureMapping)); } if (options.aoMap || options.aoVertexColor) { decl.append("float dAo;"); code.append(this._addMap("ao", "aoPS", options, litShader.chunks, textureMapping)); func.append("getAO();"); args.append("litArgs_ao = dAo;"); } // emission decl.append("vec3 dEmission;"); code.append(this._addMap("emissive", "emissivePS", options, litShader.chunks, textureMapping, options.emissiveEncoding)); func.append("getEmission();"); args.append("litArgs_emission = dEmission;"); // clearcoat if (options.litOptions.useClearCoat) { decl.append("float ccSpecularity;"); decl.append("float ccGlossiness;"); decl.append("vec3 ccNormalW;"); code.append(this._addMap("clearCoat", "clearCoatPS", options, litShader.chunks, textureMapping)); code.append(this._addMap("clearCoatGloss", "clearCoatGlossPS", options, litShader.chunks, textureMapping)); code.append(this._addMap("clearCoatNormal", "clearCoatNormalPS", options, litShader.chunks, textureMapping)); func.append("getClearCoat();"); func.append("getClearCoatGlossiness();"); func.append("getClearCoatNormal();"); args.append("litArgs_clearcoat_specularity = ccSpecularity;"); args.append("litArgs_clearcoat_gloss = ccGlossiness;"); args.append("litArgs_clearcoat_worldNormal = ccNormalW;"); } // lightmap if (options.lightMap || options.lightVertexColor) { const lightmapDir = (options.dirLightMap && options.litOptions.useSpecular); const lightmapChunkPropName = lightmapDir ? 'lightmapDirPS' : 'lightmapSinglePS'; decl.append("vec3 dLightmap;"); if (lightmapDir) { decl.append("vec3 dLightmapDir;"); } code.append(this._addMap("light", lightmapChunkPropName, options, litShader.chunks, textureMapping, options.lightMapEncoding)); func.append("getLightMap();"); args.append("litArgs_lightmap = dLightmap;"); if (lightmapDir) { args.append("litArgs_lightmapDir = dLightmapDir;"); } } // only add the legacy chunk if it's referenced if (code.code.indexOf('texture2DSRGB') !== -1 || code.code.indexOf('texture2DRGBM') !== -1 || code.code.indexOf('texture2DRGBE') !== -1) { Debug.deprecated('Shader chunk macro $texture2DSAMPLE(XXX) is deprecated. Please use $DECODE(texture2D(XXX)) instead.'); code.prepend(litShader.chunks.textureSamplePS); } } else { // all other passes require only opacity if (options.litOptions.alphaTest) { decl.append("float dAlpha;"); code.append(this._addMap("opacity", "opacityPS", options, litShader.chunks, textureMapping)); code.append(litShader.chunks.alphaTestPS); func.append("getOpacity();"); func.append("alphaTest(dAlpha);"); args.append("litArgs_opacity = dAlpha;"); } } decl.append(litShader.chunks.litShaderArgsPS); code.append(`void evaluateFrontend() { \n${func.code}\n${args.code}\n }\n`); func.code = `evaluateFrontend();`; for (const texture in textureMapping) { decl.append(`uniform sampler2D ${textureMapping[texture]};`); } // decl.append('//-------- frontend decl begin', decl.code, '//-------- frontend decl end'); // code.append('//-------- frontend code begin', code.code, '//-------- frontend code end'); // func.append('//-------- frontend func begin\n${func}//-------- frontend func end\n`; // format func func.code = `\n${func.code.split('\n').map(l => ` ${l}`).join('\n')}\n\n`; litShader.generateFragmentShader(decl.code, code.code, func.code, lightingUv); return litShader.getDefinition(); } } const standard = new ShaderGeneratorStandard(); export { _matTex2D, standard };
import RecoveryValidationInProgress from "./RecoveryValidationInProgress"; export {RecoveryValidationInProgress} export default RecoveryValidationInProgress
import * as request from 'superagent' import { logout } from '../auth/users' import { isExpired } from '../../jwt' import {baseUrl} from '../../constants' export const SET_SHOP = 'SET_SHOP' const setShop = products => ({ type: SET_SHOP, payload: products }) export const getShopProducts = (id) => (dispatch, getState) => { const state = getState() const jwt = state.currentUser.jwt if (isExpired(jwt)) return dispatch(logout()) request .get(`${baseUrl}/shops/${id}`) .set('Authorization', `Bearer ${jwt}`) .then(response => { dispatch(setShop(response.body)) }) .catch(err => console.error(err)) }
import React, { useEffect, useState } from 'react'; import styled from 'styled-components'; import axios from 'axios'; import CandidateVotes from './Candidate'; import { Link } from 'react-router-dom'; import { Button } from './Candidate'; const url = 'http://ec2-13-209-5-166.ap-northeast-2.compute.amazonaws.com:8000/api/candidates'; function LoginoutButton({ isLogined, handleLogoutButton }) { if (isLogined) { return ( <UserButton onClick={handleLogoutButton} r={128} g={203} b={196}> 로그아웃 </UserButton> ); } else return ( <Link to="/signin"> <UserButton r={128} g={203} b={196}> 로그인 </UserButton> </Link> ); } function VoteView({ loginCookie, removeLoginCookie }) { const [candidates, setCandidates] = useState([]); const [voteFlag, setVoteFlag] = useState(false); const [isLogined, setIsLogined] = useState(Boolean(loginCookie.loginCookie)); function flipVoteFlag() { setVoteFlag(!voteFlag); } function handleLogoutButton() { if (isLogined) { removeLoginCookie('loginCookie'); setIsLogined(false); alert('로그아웃 되었습니다.'); } else alert('로그인이 되어있지 않습니다.'); } useEffect(() => { const fetchCandidates = async () => { try { const response = await axios.get(url); setCandidates(response.data); } catch (e) {} }; fetchCandidates(); }, [voteFlag]); const sortedCandidates = candidates.sort((a, b) => { return b.voteCount - a.voteCount; }); return ( <Container> <Title>CEOS 13기 FRONT 운영진 투표 &gt;.0</Title> <Link to="/signup"> <UserButton r={207} g={216} b={220}> 회원가입 </UserButton> </Link> <LoginoutButton isLogined={isLogined} handleLogoutButton={handleLogoutButton} ></LoginoutButton> <CandidateContainer> {sortedCandidates.map((candidate) => ( <CandidateVotes candidate={candidate} key={candidate.id} flipVoteFlag={flipVoteFlag} rank={sortedCandidates.indexOf(candidate) + 1} loginCookie={loginCookie} /> ))} </CandidateContainer> </Container> ); } export default VoteView; const Container = styled.div` text-align: center; `; const CandidateContainer = styled.div` margin-top: 50px; `; const Title = styled.h1``; const UserButton = styled(Button)` border: #00897b 1px solid; color: #004d40; `;
import styled from 'styled-components' export const SceneDetailsWrapper = styled.div` background-color: white; padding: 16px; `;
"use strict"; var cars = [{ id: 1, brand: 'Chevrolett', model: 'asd', color: 'blue', year: 2020, price: '$150,000' }, { id: 2, brand: 'Chevrolett', model: '', color: 'blue', year: 2020, price: '$150,000' }, { id: 3, brand: 'Chevrolett', model: 'asd', color: 'blue', year: 2020, price: '$150,000' }, { id: 4, brand: 'Chevrolett', color: 'blue', model: 'asd', year: 2020, price: '$150,000' }, { id: 5, brand: 'Chevrolett', model: 'asd', color: 'blue', year: 2020, price: '$150,000' }, { id: 6, brand: 'Chevrolett', mode: 'asd', color: 'blue', year: 2020, price: '$150,000' }]; function printCars() { //1 donde quiero poner los usuarios //2 genero el html //3 pongo el html var container = document.getElementById('container-cars'); var html = ''; cars.forEach(function (car) { html += "<tr>\n <td>".concat(car.brand, "</td>\n <td>").concat(car.model, "</td>\n <td>").concat(car.color, "</td>\n <td>").concat(car.year, "</td>\n <td>").concat(car.price, "</td>\n <td><button onclick=\"updateCar(").concat(car.id, ")\" class=\"btn btn-primary\">Update</button> \n <button onclick=\"deleteCar(").concat(car.id, ")\" class=\"btn btn-danger\">Delete</button></td>\n \n </tr>"); }); container.innerHTML = html; } function deleteCar(id) { //como elimino un valor de un arreglo con -> splice //necesito el indice -> como obtengo el indice del elemento a eliminar si yo recibo el id? -> findIndex var index = cars.findIndex(function (car) { return car.id == id; }); cars.splice(index, 1); //hay que eliminar del html igual alert("Are you sure deleting this produc id ".concat(id)); printCars(); } function addCar() { //obtener el valor del input //agregar el usuario al arreglo //imprimir nuevamente los usuarios var brand = document.getElementById('brand').value; var model = document.getElementById('model').value; var color = document.getElementById('color').value; var year = document.getElementById('year').value; var price = document.getElementById('price').value; var id = cars[cars.length - 1].id + 1; var newCar = { brand: brand, model: model, color: color, year: year, price: price, id: id }; cars.push(newCar); alert('Car Added'); printCars(); //limpiar el formulario document.getElementById('form-car').reset(); } printCars();
import { Module, VuexModule, Mutation } from "vuex-module-decorators"; @Module({ stateFactory: true, namespaced: true, name: "messages" }) class Messages extends VuexModule { messages = []; @Mutation info(message) { this.messages.push({ type: "info", message }); } @Mutation error(message) { this.messages.push({ type: "error", message }); } @Mutation dismiss(index) { this.messages.splice(index, 1); } @Mutation clearMessages() { this.messages.splice(0, this.messages.length); } @Mutation addMessage(alert) { this.messages.push(alert); } @Mutation removeMessage(index) { this.messages.splice(index, 1); } } export { Messages };
import React from 'react' import { Link, Redirect } from "react-router-dom"; import { connect } from "react-redux"; import "./index.scss" import logo from "../../assets/logo.svg" import anonymuser from '../../assets/anonymous.png' import { logout } from '../../actions/auth'; import { clearMessage } from '../../actions/message'; import { API_URL } from '../../constants'; function Header(props) { const {isLoggedIn,dispatch, history} = props ; const username = props.user?.username; const loggout = () =>{ dispatch(logout()) ; } return ( <header className="header"> <div className="main-wrapper header--wrapper"> <Link to="/"> <img className="header--logo" src={logo} alt="Logo de Groupomania" /> </Link> {isLoggedIn ? ( // Si l'utilisateur est loggé <nav className="header--nav"> {props.user.isAdmin && ( <Link to="/report-posts"> <div className="moderation"> <i class="fas fa-comment-slash"></i> Posts Signaler </div> </Link> )} <Link to="/profile"> <div className="header--nav--profile" title={"profil de "+username}> <img src={props.user?.profile_picture ? `${API_URL}${props.user?.profile_picture}` : anonymuser} alt={"Photo de profil"+username} /> </div> </Link> <button type="button" onClick={loggout} className="btn--logout" aria-label="Se déconnecter" title="Se déconnecter"> <i className="fas fa-sign-out-alt"></i> </button> </nav> ):( // Si l'utilisateur n'est pas encore loggé <nav className="header--nav"> <Link to="/login"> <a>S'identifier</a> </Link> <Link to="/register"> <a>S'inscrire</a> </Link> </nav> )} </div> </header> ) } const mapStateToProps = function(state) { const {isLoggedIn,user}=state.auth ; return { isLoggedIn, user }; } export default connect(mapStateToProps)(Header) ;
import { Table, Tag } from 'Components/UI-Library' import { CheckCircleOutlined, SyncOutlined } from 'Components/UI-Library/Icons' import { ROUTER } from 'Constants/CommonConstants' import { format } from 'date-fns' import { useStoreActions, useStoreState } from 'easy-peasy' import React from 'react' import { Link } from 'react-router-dom' const AllOrders = () => { // State const orders = useStoreState((state) => state.orderAdmin.orders) const loading = useStoreState((state) => state.orderAdmin.loading) // const page = useStoreState((state) => state.orderAdmin.page) const getOrderDetail = useStoreActions( (action) => action.orderAdmin.getOrderDetail ) // Function const onHanleId = (id) => { getOrderDetail(id) } const handlePagination = (pagination) => { console.log('pagination :>> ', pagination) } // data table const columns = [ { title: 'Orders', dataIndex: 'id', key: 'order', render: (id, record) => ( <Link to={`${ROUTER.OrderDetail}/${id}`} onClick={() => onHanleId(id)} style={{ fontWeight: '500', color: '#2271b1' }} > #{id} {record.reciver.firstName} {record.reciver.lastName} </Link> ), }, { title: 'Date', dataIndex: 'create_at', key: 'date', render: (create_at) => format(create_at, 'dd-MM-yyyy'), }, { title: 'Status', dataIndex: 'status', key: 'status', render: (status) => ( <Tag icon={ status === 'Processing' ? ( <SyncOutlined spin /> ) : ( <CheckCircleOutlined /> ) } color={`${status === 'Processing' ? 'processing' : 'success'}`} > {status} </Tag> ), }, { title: 'Total', dataIndex: 'total', key: 'total', }, { title: 'Payment', dataIndex: 'payment', key: 'payment', }, ] return ( <> <h1 style={{ fontSize: '32px' }}>ALL ORDERS</h1> <Table dataSource={orders} columns={columns} loading={loading} onChange={handlePagination} /> </> ) } export default AllOrders
var searchData= [ ['requesthttpmethod',['RequestHTTPMethod',['../interface_c1_connector_h_t_t_p_request_controller.html#acdec09871bc9eb6f34be1c006e337d7d',1,'C1ConnectorHTTPRequestController']]], ['requestmethod',['RequestMethod',['../interface_c1_connector_service.html#a5d08d9000cff9eda1bc9c1e87941a071',1,'C1ConnectorService']]] ];
var socket = io(); var named=false, nameValid=false; var nickname; //reading data from server socket.on('welcome message', function(data){ $('#messages').append($('<li>').text(data)); console.log("welcome is working"); while(named==false){ nickname = window.prompt('Hey, ( ͡° ͜ʖ ͡°) \nyou\'re attempting to join a secret millitary meeting!\n(No space key allowed!!!.)', 'Type your name here! ヾ(´ε`*)ゝ'); if(nickname.indexOf(' ')== -1){ named=true; socket.emit('nick name', nickname);} else {window.alert("(;・ε・)ゝ” Name invalid. \n Make a new one! (●´ω`●)ゞ ");} } }) socket.on('latest message', function(data){ $('#messages').append($('<li>').text(data.userName + ": " + data.message)); }) socket.on('message confirmation', function(data){ window.alert(data.text); }) //sending data to server $('form').submit(submitFired); function submitFired(){ var dataFromClient = { 'msgText' : $('#m').val() } socket.emit('chat message', dataFromClient); $('#m').val(); return false; }
/** @class Models.AprovacaoMedicao * Modelo que representa a informação de quem aprovou o processo. * @private * @alteracao 12/05/2015 185753 Projeto Carlos Eduardo Santos Alves Domingos * Criação. * @cfg {String} Usuario Login da pessoa que aprovou o contrato. * @cfg {String} Date Data em que foi aprovado por essa pessoa. */ exports.definition = { config: { columns: { "Usuario" : "String", "Date" : "Date" }, adapter: { type: "properties", collection_name: "AprovacaoMedicao" } }, extendModel: function(Model) { _.extend(Model.prototype, { // extended functions and properties go here }); return Model; }, extendCollection: function(Collection) { _.extend(Collection.prototype, { // extended functions and properties go here }); return Collection; } };
module.exports = { ruleArchive: "latest", policies: ["IBM_Accessibility"], failLevels: ["violation", "potentialviolation"], reportLevels: [ "violation", "potentialviolation", "recommendation", "potentialrecommendation", "manual", "pass", ], outputFormat: ["json"], label: [process.env.TRAVIS_BRANCH], outputFolder: "reports/tests/accessibility/aCheckerOutput", baselineFolder: "reports/tests/accessibility/baselines", };
import React, { useEffect } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { getMovies } from 'app/packages/store/actions/actions' import { Container, Wrapper, HeaderTitleContainer, HeaderTitleWrapper, Title, extendContactButtonStyle } from './TraktMoviesContainer.style'; import Movies from './Movies'; const TraktMoviesContainer = ({ movies, ...props }) => { useEffect(() => { props.getMovies({ query: 'a' }); }, []); return ( <Container> <Movies movies={movies} /> </Container> ) } const mapStateToProps = state => ({ movies: state.actions.movies, }); const mapDispatchToProps = dispatch => bindActionCreators( { getMovies, }, dispatch, ); export default connect( mapStateToProps, mapDispatchToProps, )(TraktMoviesContainer);
import React from 'react' import { Editor, EditorState } from 'draft-js' class AppDraftEditor extends React.Component { constructor(props) { super(props) this.state = { editorState: EditorState.createEmpty() } this.onChange = (editorState) => this.setState({ editorState }) this.setEditor = (editor) => { this.editor = editor } this.focusEditor = () => { if (this.editor) { this.editor.focus() } } } componentDidMount() { this.focusEditor() } render() { return ( <div onClick={ this.focusEditor }> <Editor ref={ this.setEditor } editorState={ this.state.editorState } onChange={ this.onChange } /> </div> ) } } export default AppDraftEditor
var Vue = require('vue') Vue.use(require('vue-resource')) Vue.use(require('vue-highcharts')) var moment = require('moment') import { fundsList } from './constants' import { addKeysInFunds } from './format-funds' import { setOptions, success} from './highcharts-utils' var afer = new Vue({ el: '.afer', data: { funds: addKeysInFunds(fundsList), globalBeginDate: '1990-01-01', globalEndDate: moment().format('YYYY-MM-DD'), }, mounted:function() { this.getData() }, methods: { changeFundDate: function(fund) { setOptions(fund) }, changeGlobalDate: function() { for (let fund of this.funds) { fund.beginDate = this.globalBeginDate fund.endDate = this.globalEndDate this.changeFundDate(fund) } }, getData: function() { const baseURL = 'https://www.afer.asso.fr/amcharts/' for (let fund of this.funds) { const reqURL = baseURL + fund.key + '_data.csv' // let us make a request to a server we control // const reqURL = 'http://localhost:8000/fund?code=' + fund.key this.$http.get(reqURL) .then( // success callback success.bind(null, fund) ) .catch((response) => { // error callback console.log('Unable to fetch csv') }) } } }, })
import { AppHeader } from './cmps/app-header.jsx' const Router = ReactRouterDOM.HashRouter; const { Route, Switch } = ReactRouterDOM; // Simple React Component export class App extends React.Component { render() { return ( <Router> <section className="app"> <AppHeader /> {/* <Switch> <Route path="/book/:bookId" component={BookDetails}/> <Route path="/book" component={MissBook}/> <Route path="/about" component={About}/> <Route path="/" component={Home}/> </Switch> */} </section> </Router> ) } }
import React from 'react'; export default class extends React.Component{ render() { var className="avatar"; var char = this.props.login ? this.props.login[0] : ""; var style = { 'backgroundColor': this.props.color }; if (this.props.size) { className += ` avatar_size_${this.props.size}`; } return ( <span className={className} style={style}> {char} <span className="avatar__mask"/> </span> ); } };
jest.mock('http'); describe('server/server', () => { it('can be required', () => { jest.dontMock('../server'); require('../server'); }); });
import fetch from 'node-fetch'; import { config } from '../../../../config' export const getChain = async ({ startBlock, endBlock, startDate, endDate, miner, cid, skip, limit, sortOrder }) => { const maxLimit = 500 let wheres = [] if (startBlock) { wheres.push(['where', 'height', '>=', Number(startBlock)]) } if (endBlock) { wheres.push(['where', 'height', '<=', Number(endBlock)]) } if (startDate) { let date = new Date(startDate) let seconds = date.getTime() / 1000 wheres.push(['where', 'timestamp', '>', seconds]) } if (endDate) { let date = new Date(endDate) let seconds = date.getTime() / 1000 wheres.push(['where', 'timestamp', '<', seconds]) } if (miner) { wheres.push(['where', 'miner', '=', miner]) } if (cid) { wheres.push(['where', 'cid', '=', cid]) } skip = Number(skip) if (!skip || isNaN(skip)) { skip = null } limit = Number(limit) if (isNaN(limit)) { limit = null } if (limit && limit > maxLimit) { limit = maxLimit } if (sortOrder && sortOrder.toUppercase() !== 'ASC' && sortOrder.toUppercase() !== 'DESC') { sortOrder = 'DESC' } const url = `${config.slateUrl}/chain-visualizer-chain-data-view?offset=${skip}&limit=${limit}&where=${JSON.stringify(wheres)}&sort=${JSON.stringify([['height', 'asc']])}`; const apiResponse = await fetch(url, { method: 'get', headers: { 'Content-Type': 'application/json' }, }) const body = await apiResponse.json(); return body.data; } export const getOrphans = async ({ startBlock, endBlock, startDate, endDate, miner, cid, skip, limit, sortOrder }) => { const maxLimit = 500 let wheres = [] if (startBlock) { wheres.push(['where', 'height', '>=', Number(startBlock)]) } if (endBlock) { wheres.push(['where', 'height', '<=', Number(endBlock)]) } if (startDate) { let date = new Date(startDate) let seconds = date.getTime() / 1000 wheres.push(['where', 'timestamp', '>', seconds]) } if (endDate) { let date = new Date(endDate) let seconds = date.getTime() / 1000 wheres.push(['where', 'timestamp', '<', seconds]) } if (miner) { wheres.push(['where', 'miner', '=', miner]) } if (cid) { wheres.push(['where', 'cid', '=', cid]) } skip = Number(skip) if (!skip || isNaN(skip)) { skip = null } limit = Number(limit) if (isNaN(limit)) { limit = null } if (limit && limit > maxLimit) { limit = maxLimit } if (sortOrder && sortOrder.toUppercase() !== 'ASC' && sortOrder.toUppercase() !== 'DESC') { sortOrder = 'DESC' } const url = `${config.slateUrl}/chain-visualizer-orphans-view?offset=${skip}&limit=${limit}&where=${JSON.stringify(wheres)}&sort=${JSON.stringify([['height', 'asc']])}`; const apiResponse = await fetch(url, { method: 'get', headers: { 'Content-Type': 'application/json' }, }) const body = await apiResponse.json(); return body.data; } export const getGraph = async ({ start, end }) => { let wheres = [] wheres.push(['where', 'height', '>', Number(start)]) wheres.push(['where', 'height', '<', Number(end)]) const url = `${config.slateUrl}/chain-visualizer-blocks-with-parents-view?where=${JSON.stringify(wheres)}&sort=${JSON.stringify([['height', 'asc']])}`; const apiResponse = await fetch(url, { method: 'get', headers: { 'Content-Type': 'application/json' }, }) const body = await apiResponse.json(); return body.data; }
const express = require('express'); const uuidv4 = require('uuid/v4'); const router = express.Router(); router.get('/', (req, res, next) => { const protocol = req.connection.encrypted ? 'Running Using Secure HTTPS Protocol' : 'Running Using Insecure HTTP Protocol'; res.type('html'); res.status(200); res.render('index', { title: 'API Server Home', protocol: protocol, request: req.sessionID, }); }); router.get('/health-check', (req, res, next) => { res.type('json'); res.status(200).json({ status: res.statusCode, message: 'Server health is OK!', request: req.sessionID, }); }); module.exports = router;
// build the object, including geometry (triangle vertices) // and possibly colors and normals for each vertex //Overwrote create gear function to take two parameters to //build user specified gear. function dSaeleeGear(numTeeth, numSpokes) { let drawTooth; let norm; const vertices = []; const colors = []; const normals = []; // Making gear triangles const n = numTeeth * 2; const rad = 1.0; const outRad = rad * 1.2; const angInc = 2 * 3.14159 / n; let ang = 0; let z = 0.1; const teethMover = .2; const spokeIncrement = n / numSpokes; const shaftSize = 3; // coin face, front let i; for (i = 0; i < n; i++) { if (!(i % spokeIncrement === 0)) { //Coin face outer rim. drawingRectangle(vertices, colors, normals, .8 * rad * Math.cos(ang + angInc), .8 * rad * Math.sin(ang + angInc), z, .8 * rad * Math.cos(ang), .8 * rad * Math.sin(ang), z, rad * Math.cos(ang), rad * Math.sin(ang), z, rad * Math.cos(ang + angInc), rad * Math.sin(ang + angInc), z); //Coin face outer rim walls. drawingRectangle(vertices, colors, normals, .8 * rad * Math.cos(ang), .8 * rad * Math.sin(ang), z, .8 * rad * Math.cos(ang + angInc), .8 * rad * Math.sin(ang + angInc), z, .8 * rad * Math.cos(ang + angInc), .8 * rad * Math.sin(ang + angInc), -z, .8 * rad * Math.cos(ang), .8 * rad * Math.sin(ang), -z); } else { //Creates Spokes vertices.push(0, 0, z, rad * Math.cos(ang), rad * Math.sin(ang), z, rad * Math.cos(ang + angInc), rad * Math.sin(ang + angInc), z) pushColor(colors); normals.push(0, 0, 1, 0, 0, 1, 0, 0, 1); //Spoke side wall 1 drawingRectangle(vertices, colors, normals, .2 * rad * Math.cos(ang), .2 * rad * Math.sin(ang), z, .2 * rad * Math.cos(ang), .2 * rad * Math.sin(ang), -z, .8 * rad * Math.cos(ang), .8 * rad * Math.sin(ang), -z, .8 * rad * Math.cos(ang), .8 * rad * Math.sin(ang), z); //Spoke side wall 2 drawingRectangle(vertices, colors, normals, .2 * rad * Math.cos(ang + angInc), .2 * rad * Math.sin(ang + angInc), z, .8 * rad * Math.cos(ang + angInc), .8 * rad * Math.sin(ang + angInc), z, .8 * rad * Math.cos(ang + angInc), .8 * rad * Math.sin(ang + angInc), -z, .2 * rad * Math.cos(ang + angInc), .2 * rad * Math.sin(ang + angInc), -z); } //Draw shaft walls drawingRectangle(vertices, colors, normals, .2 * rad * Math.cos(ang), .2 * rad * Math.sin(ang), -shaftSize, .2 * rad * Math.cos(ang + angInc), .2 * rad * Math.sin(ang + angInc), -shaftSize, .2 * rad * Math.cos(ang + angInc), .2 * rad * Math.sin(ang + angInc), shaftSize, .2 * rad * Math.cos(ang), .2 * rad * Math.sin(ang), shaftSize); vertices.push(0, 0, shaftSize, .2 * rad * Math.cos(ang), .2 * rad * Math.sin(ang), shaftSize, .2 * rad * Math.cos(ang + angInc), .2 * rad * Math.sin(ang + angInc), shaftSize); pushColor(colors); normals.push(0, 0, 1, 0, 0, 1, 0, 0, 1); vertices.push(0, 0, -shaftSize, .2 * rad * Math.cos(ang), .2 * rad * Math.sin(ang), -shaftSize, .2 * rad * Math.cos(ang + angInc), .2 * rad * Math.sin(ang + angInc), -shaftSize); pushColor(colors); normals.push(0, 0, 1, 0, 0, 1, 0, 0, 1); ang += angInc; } ang = 0; for (i = 0; i < n; i++) { if (!(i % spokeIncrement === 0)) { //Coin face outer rim (back) vertices.push( .8 * rad * Math.cos(ang), .8 * rad * Math.sin(ang), -z, .8 * rad * Math.cos(ang + angInc), .8 * rad * Math.sin(ang + angInc), -z, rad * Math.cos(ang), rad * Math.sin(ang), -z); pushColor(colors); normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1); //Coin face outer rim (back) vertices.push( .8 * rad * Math.cos(ang + angInc), .8 * rad * Math.sin(ang + angInc), -z, rad * Math.cos(ang), rad * Math.sin(ang), -z, rad * Math.cos(ang + angInc), rad * Math.sin(ang + angInc), -z); pushColor(colors); normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1); } else { vertices.push(0, 0, -z, rad * Math.cos(ang), rad * Math.sin(ang), -z, rad * Math.cos(ang + angInc), rad * Math.sin(ang + angInc), -z); pushColor(colors); normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1); } ang += angInc; } let r; for (r = 0; r < 2; r++) { ang = 0; drawTooth = false; // face of the teeth for (i = 0; i < n; i++) { drawTooth = !drawTooth; if (drawTooth) { //inner right vertices.push(rad * Math.cos(ang), rad * Math.sin(ang), z, //inner left (top of right) rad * Math.cos(ang + angInc), rad * Math.sin(ang + angInc), z, //outer left (top of outer right) outRad * Math.cos(ang + angInc), outRad * Math.sin(ang + angInc), z * teethMover); pushColor(colors); norm = calcNormal(rad * Math.cos(ang), rad * Math.sin(ang), z, rad * Math.cos(ang + angInc), rad * Math.sin(ang + angInc), z, outRad * Math.cos(ang + angInc), outRad * Math.sin(ang + angInc), z * teethMover ); if (z > 0) { normals.push(-norm[0], -norm[1], -norm[2], -norm[0], -norm[1], -norm[2], -norm[0], -norm[1], -norm[2]); } else { normals.push(norm[0], norm[1], norm[2], norm[0], norm[1], norm[2], norm[0], norm[1], norm[2]); } //inner right vertices.push(rad * Math.cos(ang), rad * Math.sin(ang), z, //outer left (top of outer right) outRad * Math.cos(ang + angInc), outRad * Math.sin(ang + angInc), z * teethMover, //outer right (bottom of outer left) outRad * Math.cos(ang), outRad * Math.sin(ang), z * teethMover); pushColor(colors); norm = calcNormal(rad * Math.cos(ang), rad * Math.sin(ang), z, outRad * Math.cos(ang + angInc), outRad * Math.sin(ang + angInc), z * teethMover, outRad * Math.cos(ang), outRad * Math.sin(ang), z * teethMover); if (z > 0) { normals.push(-norm[0], -norm[1], -norm[2], -norm[0], -norm[1], -norm[2], -norm[0], -norm[1], -norm[2]); } else { normals.push(norm[0], norm[1], norm[2], norm[0], norm[1], norm[2], norm[0], norm[1], norm[2]); } } ang += angInc; } z = -z; } // coin edge ang = 0; drawTooth = true; for (i = 0; i < n; i++) { drawTooth = !drawTooth; norm = [rad * Math.cos(ang + angInc / 2), rad * Math.sin(ang + angInc / 2), 0]; if (drawTooth) { vertices.push( rad * Math.cos(ang), rad * Math.sin(ang), -z, rad * Math.cos(ang + angInc), rad * Math.sin(ang + angInc), -z, rad * Math.cos(ang + angInc), rad * Math.sin(ang + angInc), z) pushColor(colors); normals.push(norm[0], norm[1], norm[2], norm[0], norm[1], norm[2], norm[0], norm[1], norm[2]) vertices.push( rad * Math.cos(ang), rad * Math.sin(ang), -z, rad * Math.cos(ang + angInc), rad * Math.sin(ang + angInc), z, rad * Math.cos(ang), rad * Math.sin(ang), z) pushColor(colors); normals.push(norm[0], norm[1], norm[2], norm[0], norm[1], norm[2], norm[0], norm[1], norm[2]) } ang += angInc; } // tooth roof ang = 0; drawTooth = false; for (i = 0; i < n; i++) { drawTooth = !drawTooth; if (drawTooth) { norm = [outRad * Math.cos(ang + angInc / 2), outRad * Math.sin(ang + angInc / 2), 0]; vertices.push( outRad * Math.cos(ang), outRad * Math.sin(ang), -z * teethMover, outRad * Math.cos(ang + angInc), outRad * Math.sin(ang + angInc), -z * teethMover, outRad * Math.cos(ang + angInc), outRad * Math.sin(ang + angInc), z * teethMover) pushColor(colors); normals.push(norm[0], norm[1], norm[2], norm[0], norm[1], norm[2], norm[0], norm[1], norm[2]) vertices.push( outRad * Math.cos(ang), outRad * Math.sin(ang), -z * teethMover, outRad * Math.cos(ang + angInc), outRad * Math.sin(ang + angInc), z * teethMover, outRad * Math.cos(ang), outRad * Math.sin(ang), z * teethMover) pushColor(colors); normals.push(norm[0], norm[1], norm[2], norm[0], norm[1], norm[2], norm[0], norm[1], norm[2]) } ang += angInc; } // tooth walls ang = 0; drawTooth = false; for (i = 0; i < n; i++) { drawTooth = !drawTooth; if (drawTooth) { norm = calcNormal(rad * Math.cos(ang), rad * Math.sin(ang), -z, outRad * Math.cos(ang), outRad * Math.sin(ang), -z * teethMover, outRad * Math.cos(ang), outRad * Math.sin(ang), z * teethMover); vertices.push( rad * Math.cos(ang), rad * Math.sin(ang), -z, outRad * Math.cos(ang), outRad * Math.sin(ang), -z * teethMover, outRad * Math.cos(ang), outRad * Math.sin(ang), z * teethMover); pushColor(colors); normals.push(norm[0], norm[1], norm[2], norm[0], norm[1], norm[2], norm[0], norm[1], norm[2]) vertices.push( rad * Math.cos(ang), rad * Math.sin(ang), -z, outRad * Math.cos(ang), outRad * Math.sin(ang), z * teethMover, rad * Math.cos(ang), rad * Math.sin(ang), z); pushColor(colors); normals.push(norm[0], norm[1], norm[2], norm[0], norm[1], norm[2], norm[0], norm[1], norm[2]); norm = calcNormal(rad * Math.cos(ang + angInc), rad * Math.sin(ang + angInc), -z, outRad * Math.cos(ang + angInc), outRad * Math.sin(ang + angInc), z * teethMover, outRad * Math.cos(ang + angInc), outRad * Math.sin(ang + angInc), -z * teethMover); vertices.push( rad * Math.cos(ang + angInc), rad * Math.sin(ang + angInc), -z, outRad * Math.cos(ang + angInc), outRad * Math.sin(ang + angInc), -z * teethMover, outRad * Math.cos(ang + angInc), outRad * Math.sin(ang + angInc), z * teethMover); pushColor(colors); normals.push(norm[0], norm[1], norm[2], norm[0], norm[1], norm[2], norm[0], norm[1], norm[2]); vertices.push( rad * Math.cos(ang + angInc), rad * Math.sin(ang + angInc), -z, outRad * Math.cos(ang + angInc), outRad * Math.sin(ang + angInc), z * teethMover, rad * Math.cos(ang + angInc), rad * Math.sin(ang + angInc), z); pushColor(colors); normals.push(norm[0], norm[1], norm[2], norm[0], norm[1], norm[2], norm[0], norm[1], norm[2]); } ang += angInc; } return [vertices, colors, normals] } //Helper method to calculate normals. function calcNormal(x1, y1, z1, x2, y2, z2, x3, y3, z3) { const ux = x2 - x1, uy = y2 - y1, uz = z2 - z1; const vx = x3 - x1, vy = y3 - y1, vz = z3 - z1; return [uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx]; } //Helper method to change the color of the gear. function pushColor(colors) { const r = 212 / 255; const g = 175 / 255; const b = 55 / 255; colors.push(r, g, b, r, g, b, r, g, b); } //Helper method to draw two triangles. function drawingRectangle(vertices, colors, normals, x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) { const norm = calcNormal(x1, y1, z1, x2, y2, z2, x3, y3, z3); vertices.push(x1, y1, z1, x2, y2, z2, x3, y3, z3); pushColor(colors); normals.push(norm[0], norm[1], norm[2], norm[0], norm[1], norm[2], norm[0], norm[1], norm[2]); vertices.push(x1, y1, z1, x3, y3, z3, x4, y4, z4); pushColor(colors); normals.push(norm[0], norm[1], norm[2], norm[0], norm[1], norm[2], norm[0], norm[1], norm[2]); } //Helper method to test code. // function createGear() { // // return dSaeleeGear(20, 8); // // }
import { Box, Grid, Typography } from '@material-ui/core'; import React from 'react'; import FilmCard from 'src/components/FilmCard'; const FilmList = ({ favourites, setFavourites, addToFavouritHandler }) => { return ( <Box> <Grid container spacing={1}> <Grid item xs> <Typography variant={'h4'}>Избрание фильми</Typography> {favourites.length} {favourites.length === 1 ? 'Фильм' : 'Фильмов'} </Grid> <Grid container spacing={2}> {favourites.map((film, id) => ( <Grid item xs={3} key={`${id}${film.id}`}> <FilmCard film={film} favourites={favourites} setFavourites={setFavourites} addToFavouritHandler={addToFavouritHandler} /> </Grid> ))} </Grid> </Grid> </Box> ); }; export default FilmList;
var interactive = true; // Create an new instance of a pixi stage. var stage = new PIXI.Stage(0x000000, interactive); stage.buttonMode = true; var WIDTH = 800; var HEIGHT = 500; var P_WIDTH = 16; var P_HEIGHT = 80; var B_WIDTH = 8; var B_HEIGHT = 8; // Create a renderer instance. var renderer = PIXI.autoDetectRenderer(WIDTH, HEIGHT, { view: document.getElementById('main') }); var loader = new PIXI.AssetLoader(['paddle.png', 'ball.png']) loader.onComplete = function() { window.console.log('complete'); requestAnimFrame(animate); } loader.load(); var score = 0; var scoreText = new PIXI.Text(score, {font:"bold 50px Arial", fill:"#fff"}); scoreText.position.x = WIDTH/2 - 25; scoreText.position.y = 12; stage.addChild(scoreText); var highScore = 0; var highScoreText = new PIXI.Text(highScore, { font:"bold 30px Arial", fill:"#ccc" }); highScoreText.visible = false highScoreText.position.x = WIDTH/2 + 25; highScoreText.position.y = 20; stage.addChild(highScoreText); // Create a texture. var paddle_texture = PIXI.Texture.fromImage('paddle.png'); // Create two sprites using the same texture. var paddle_left = new PIXI.Sprite(paddle_texture); var paddle_right = new PIXI.Sprite(paddle_texture); var ball_texture = PIXI.Texture.fromImage('ball.png'); var ball = new PIXI.Sprite(ball_texture); // Position and size the paddles. paddle_left.position.x = P_WIDTH; paddle_left.position.y = HEIGHT * 0.5; paddle_left.width = P_WIDTH; paddle_left.height = P_HEIGHT; paddle_right.position.x = WIDTH - P_WIDTH * 2; paddle_right.position.y = HEIGHT * 0.5; paddle_right.width = P_WIDTH; paddle_right.height = P_HEIGHT; // Add the paddles to the stage. stage.addChild(paddle_left); stage.addChild(paddle_right); // Position and size the ball function resetBall() { ball.position.x = WIDTH/2; ball.position.y = HEIGHT/2; // Velocity is not a built in property ball.velocity = { x: (Math.random() > 0.5 ? -1 : 1) * 4, y: (Math.random() > 0.5 ? -1 : 1) * 4 } } resetBall(); // Add the ball to the stage. stage.addChild(ball); // The width that the user can use to control the paddles. var MOVABLE_WIDTH = WIDTH - 12 * P_WIDTH; stage.defaultCursor = 'none'; // Move the paddles stage.mousemove = function(data) { if (data.global.x > WIDTH - 6 * P_WIDTH || data.global.x < 6 * P_WIDTH) { return; } var scale = (HEIGHT - P_HEIGHT)/MOVABLE_WIDTH; var scaledPos = scale * (data.global.x - WIDTH/2); paddle_left.position.y = HEIGHT/2 + scaledPos - P_HEIGHT/2; paddle_right.position.y = HEIGHT/2 - scaledPos - P_HEIGHT/2; }; function gameOver() { if (score > highScore) { highScore = score; } highScoreText.setText(highScore); highScoreText.visible = true; score = 0; scoreText.setText(score); resetBall(); } function scorePoint() { score += 1; scoreText.setText(score); if (score >= highScore) { highScore = score; highScoreText.setText(highScore); } } function updateBallPosition() { // Detect if the ball is about to bounce off the top or bottom wall; var y_pos_dist = (HEIGHT - B_HEIGHT - ball.position.y); var y_neg_dist = -1 * (ball.position.y); if (y_pos_dist == 0 || y_neg_dist == 0) { ball.velocity.y = -1 * ball.velocity.y; ball.position.y = ball.position.y + ball.velocity.y; } else if (y_pos_dist < ball.velocity.y) { ball.velocity.y = -1 * ball.velocity.y; ball.position.y = ball.position.y + ball.velocity.y; } else if (y_neg_dist > ball.velocity.y) { ball.velocity.y = -1 * ball.velocity.y; ball.position.y = ball.position.y + ball.velocity.y; } else { ball.position.y = ball.position.y + ball.velocity.y; } if (ball.position.x < 3 * P_WIDTH) { // Try to detect left paddle hit var xdist = ball.position.x - paddle_left.position.x; if(xdist < paddle_left.width && xdist > -1 * paddle_left.width) { var ydist = ball.position.y - paddle_left.position.y; if(ydist < paddle_left.height && ydist > 0) { scorePoint(); ball.velocity.x = -1 * ball.velocity.x; ball.position.x = paddle_left.position.x + paddle_left.width + 2; } } } if (ball.position.x > WIDTH - 3 * P_WIDTH) { // Try to detect left paddle hit var xdist = ball.position.x - paddle_right.position.x; if(xdist < paddle_right.width && xdist > -1 * paddle_right.width) { var ydist = ball.position.y - paddle_right.position.y; if(ydist < paddle_right.height && ydist > 0) { scorePoint(); ball.velocity.x = -1 * ball.velocity.x; ball.position.x = paddle_right.position.x - paddle_right.width - 2; } } } if (ball.position.x < 0 || ball.position.x > WIDTH) { gameOver(); } ball.position.x = ball.position.x + ball.velocity.x; } function animate() { requestAnimFrame(animate); updateBallPosition(); // render the stage renderer.render(stage); }
require('dotenv').config({ path: '../server/.env' }) // const path = require('path') const express = require('express') const cors = require('cors') const app = express() const graphqlHTTP = require('express-graphql') const { setupDB } = require('./config/databaseConnection') const printSchemaFromBuild = require('./config/printSchema') const schema = require('./graphql/schema') printSchemaFromBuild(schema) // Call in database connection setupDB(value => console.log(value)) app.use(express.static('public')) app.use(cors()) app.use( '/graphql', graphqlHTTP( { schema, graphiql: true, pretty: true } ) ) app.listen(4000) console.log('JULIA IS C00L')
import { useEffect, useRef } from 'preact/hooks'; /** * @pinussilvestrus: we need to introduce our own hook to persist the previous * state on updates. * * cf. https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state */ export function usePrevious(value) { const ref = useRef(); useEffect(() => { ref.current = value; }); return ref.current; }
const crypto = require('crypto'); /** for encryption */ var encrypto = function(variable1,callback) { var mystr; var promise =new Promise( function(resolve,reject) { const mystr = crypto.createHmac('sha256', "elpsycongroo") .update(variable1) .digest('hex'); resolve(mystr); }); promise.then(function(mystr) { console.log(mystr); callback(mystr); }); }; /** for decryption which won't work cause encryption is learnt from different site */ var Decrypt = function(variable1,callback) { var mystr; var promise =new Promise( function(resolve,reject) { var mykey = crypto.createDecipher('aes-128-cbc', 'mypassword'); mystr = mykey.update('34feb914c099df25794bf9ccb85bea72', 'hex', 'utf8') mystr += mykey.update.final('utf8'); resolve(variable1); }); promise.then(function(variable1) { console.log(mystr); callback(mystr); }); }; module.exports.encrypto = encrypto; module.exports.Decrypt = Decrypt;
我们在平时开发的时候,会有很多场景会频繁触发事件,比如说搜索框实时发请求,onmousemove,resize,onscroll等等, 有些时候,我们并不能或者不想频繁触发事件, 咋办呢?这时候就该用到函数防抖和函数节流了! 函数防抖(debounce) 什么是防抖?短时间内多次触发同一个事件,只执行最后一次,或者只在开始时执行,中间不执行。 function debounce(doSomething,wait){ var timeout;//需要一个外部变量,为增强封装,所以使用闭包 return function(){ var _this = this, _arguments = arguments;//arguments中存着e clearTimeout(timeout); timeout = setTimeout(function(){ doSomething.apply(_this,_arguments); },wait); } } // 触发onmouseover事件 xcd.onmousemove = debounce(doSomething,1000); 函数节流(throttle) 什么是节流?节流是连续触发事件的过程中以一定时间间隔执行函数。 节流会稀释你的执行频率,比如每间隔1秒钟,只会执行一次函数, 无论这1秒钟内触发了多少次事件。 //节流时间戳版 function throttle(doSomething,wait){ var _this, _arguments, initTime = 0; return function(){ var now = +new Date();//将new date()转化为时间戳 _this = this; _arguments = arguments; if(now - initTime>wait){ doSomething.apply(_this,_arguments); initTime = now; } } } //触发onmousemove事件 xcd.onmousemove = throttle(doSomething,1000); //节流定时器版 function throttle(doSomething,wait){ var timeout; return function(){ var _this = this; _arguments = arguments; if(!timeout){ timeout = setTimeout(function(){ timeout = null; doSomething.apply(_this,_arguments); },wait); }; } } //触发onmousemove事件 xcd.onmousemove = throttle(doSomething,1000);
(function() { // cached super methods var _route = Backbone.History.prototype.route; var _getFragment = Backbone.History.prototype.getFragment; var _start = Backbone.History.prototype.start; var _checkUrl = Backbone.History.prototype.checkUrl; var _navigate = Backbone.History.prototype.navigate; var _extractParameters = Backbone.Router.prototype._extractParameters; // If we are in hash mode figure out if we are on a browser that is hit by 63777 and 85881 // https://bugs.webkit.org/show_bug.cgi?id=63777 // https://bugs.webkit.org/show_bug.cgi?id=85881 var _useReplaceState = /WebKit\/([\d.]+)/.exec(navigator.userAgent) && window.history.replaceState; // pattern to recognize state index in hash var hashStrip = /^(?:#|%23)*\d*(?:#|%23)*/; // Cached regex for index extraction from the hash var indexMatch = /^(?:#|%23)*(\d+)(?:#|%23)/; _.extend(Backbone.Router.prototype, { // the direction index will be exposed on the parameters as 'direction' _extractParameters: function() { var params = _extractParameters.apply(this, arguments); params = params || []; var history = Backbone.history; if (history._trackDirection) { var oldIndex = history._directionIndex; history._directionIndex = history.loadIndex(); params.direction = history._directionIndex - oldIndex; } return params; } }); _.extend(Backbone.History.prototype, { // Get the location of the current route within the backbone history. // This should be considered a hint // Returns -1 if history is unknown or disabled getIndex : function() { return this._directionIndex; }, getFragment : function(/* fragment, forcePushState */) { var rtn = _getFragment.apply(this, arguments); return rtn && rtn.replace(hashStrip, ''); }, start: function(/* options */) { var rtn = _start.apply(this, arguments); // Direction tracking setup this._trackDirection = !!this.options.trackDirection; if (this._trackDirection) { var loadedIndex = this.loadIndex(); this._directionIndex = loadedIndex || window.history.length; this._state = {index: this._directionIndex}; // If we are tracking direction ensure that we have a direction field to play with if (!loadedIndex) { var loc = window.location; if (!this._hasPushState) { loc.replace(loc.pathname + (loc.search || '') + '#' + this._directionIndex + '#' + this.fragment); } else { window.history.replaceState({index: this._directionIndex}, document.title, loc); } } } return rtn; }, checkUrl : function(e) { var fromIframe = this.getFragment() == this.fragment && this.iframe; var loadedIndex = this.loadIndex(fromIframe && this.iframe.location.hash); var navigateOptions = { trigger: false, replace: !loadedIndex, forceIndex: loadedIndex || this._directionIndex + 1 }; _checkUrl.call(this, e, navigateOptions); }, // The options object can contain `trigger: true` if you wish to have the // route callback be fired (not usually desirable), or `replace: true`, if // you wish to modify the current URL without adding an entry to the history. navigate: function(fragment, options) { if (this._ignoreChange) { this._pendingNavigate = _.bind(this.navigate, this, fragment, options); return; } if (!options || options === true) { options = {trigger: options}; } var newIndex; if (this._trackDirection) { newIndex = options.forceIndex || (this._directionIndex + (options.replace ? 0 : 1)); } if (this._hasPushState) { options.state = {index: newIndex}; } else { if (this._trackDirection) { fragment = newIndex + '#' + fragment; } } _navigate.call(this, fragment, options); }, _updateHash: function(location, frag, replace) { var base = location.toString().replace(/(javascript:|#).*$/, '') + '#'; if (replace) { if (_useReplaceState) { window.history.replaceState({}, document.title, base + frag); } else { location.replace(base + frag); } } else { location.hash = frag; } }, // Pulls the direction index out of the state or hash loadIndex : function(fragmentOverride) { if (!this._trackDirection) { return; } if (!fragmentOverride && this._hasPushState) { return (this._state && this._state.index) || 0; } else { var match = indexMatch.exec(fragmentOverride || window.location.hash); return (match && parseInt(match[1], 10)) || 0; } }, route: function (route, callback) { return _route.call(this, route, _.bind(function() { if (this._ignoreChange) { this._ignoreChange = false; this._directionIndex = Backbone.history.loadIndex(); this._pendingNavigate && setTimeout(Backbone.history._pendingNavigate, 0); } else { callback && callback.apply(this, arguments); } }, this)); }, back : function(triggerRoute) { this.go(-1, triggerRoute); }, foward : function(triggerRoute) { this.go(1, triggerRoute); }, go : function(count, triggerRoute) { this._ignoreChange = !triggerRoute; window.history.go(count); } }); }());
import React from 'react'; import { Card, StyledBody, StyledAction } from 'baseui/card'; import { Button } from 'baseui/button'; import { styled } from 'baseui'; const Centered = styled('div', { display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh', }); const App = () => { const [celebrationItems, setCelebrationItems] = React.useState(''); const renderCelebration = () => { setCelebrationItems(`${celebrationItems} 🎉`); } return ( <Centered> <Card> <StyledBody> Hi, you've selected the starter kit :) <br /> {celebrationItems} </StyledBody> <StyledAction> <Button overrides={{ BaseButton: { style: { width: "100%" } } }} onClick={renderCelebration}>click to celebrate</Button> </StyledAction> </Card> </Centered> ) } export default App;
var Game = require('./game'); var GameManager = require('./games-manager'); var gamesManager = new GameManager(); var playersOnline = 0; module.exports = function (server) { var io = require('socket.io')(server); io.on('connection', function (socket) { console.log('we have a connection! id = ' + socket.id); playersOnline++; // текущий онлайн отправим сразу же socket.emit('current online', playersOnline); // и обновляем каждые 5 секунд var timerID = setInterval(function () { socket.emit('current online', playersOnline); }, 3000); socket.on('find game', function () { // проверить возможность создания новой игры let newGameIsPossible = gamesManager.checkForNewGame(); if (newGameIsPossible) { // если возможно то создать новую игру let playerTwoID = gamesManager.getPlayerForNewGame(); let game = gamesManager.startGame({ playerOne: socket.id, playerTwo: playerTwoID }); // отправляем события о начале игры только 2 игрокам io.to(socket.id).to(playerTwoID).emit('game started', game.getGameData()); } else { // если нет то поставить игрока в очередь gamesManager.addPlayerToQueue(socket.id); io.to(socket.id).emit('looking for game'); } }); // обработчик хода socket.on('move', function (moveData) { let game = gamesManager.getGame(moveData.gameID); if (game) { let result = game.makeMove(moveData.row, moveData.col, socket.id); if (result === 'ok') { let opponentID = game.getOpponentID(socket.id); io.to(opponentID).emit('move', game.getGameData()); } else if (result === 'bad move') { io.to(socket.id).emit('bad move'); } else if (result === 'game over') { game.setLastMovePlayerID(socket.id); io.to(game.getPlayerOne()).to(game.getPlayerTwo()).emit('game over', game.getGameData()); // завершаем игру gamesManager.deleteGame(game.getGameID()); } } else { // TODO добавить обработку ошибки } }); socket.on('cancel game', function () { console.log('user canceled game'); let playerID = socket.id; // удаляем игрока из очереди, если он там был gamesManager.deletePlayerFromQueue(playerID); // если была игра с этим игроком let game = gamesManager.getGameByPlayerID(playerID); // оповещаем 2-го игрока о дисконекте 1-го if (game) { let playerOneID = game.getPlayerOne(); let playerTwoID = game.getPlayerTwo(); if (playerID === playerOneID) { io.to(playerTwoID).emit('opponent canceled game'); } else { io.to(playerOneID).emit('opponent canceled game'); } // и завершаем игру gamesManager.deleteGame(game.getGameID()); } }); socket.on('cancel search', function () { let playerID = socket.id; // удаляем игрока из очереди, если он там был gamesManager.deletePlayerFromQueue(playerID); }); socket.on('disconnect', function () { console.log('user disconnected'); playersOnline--; clearInterval(timerID); let playerID = socket.id; // удаляем игрока из очереди, если он там был gamesManager.deletePlayerFromQueue(playerID); // если была игра с этим игроком let game = gamesManager.getGameByPlayerID(playerID); // оповещаем 2-го игрока о дисконекте 1-го if (game) { let playerOneID = game.getPlayerOne(); let playerTwoID = game.getPlayerTwo(); if (playerID === playerOneID) { io.to(playerTwoID).emit('opponent is disconnected'); console.log('opponent with ID = ' + playerID + ' was diconected!'); console.log('opponent with ID = ' + playerTwoID + ' was informed!'); } else { io.to(playerOneID).emit('opponent is disconnected'); console.log('opponent with ID = ' + playerID + ' was diconected!'); console.log('opponent with ID = ' + playerOneID + ' was informed!'); } // и завершаем игру gamesManager.deleteGame(game.getGameID()); } }); }); };
// Copyright (c) 2016-2018, BuckyCloud, Inc. and other BDT contributors. // The BDT project is supported by the GeekChain Foundation. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the BDT nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. "use strict"; const Base = require('../base/base.js'); const BaseUtil = require('../base/util.js'); const TimeHelper = BaseUtil.TimeHelper; const LOG_INFO = Base.BX_INFO; const LOG_WARN = Base.BX_WARN; const LOG_DEBUG = Base.BX_DEBUG; const LOG_CHECK = Base.BX_CHECK; const LOG_ASSERT = Base.BX_ASSERT; const LOG_ERROR = Base.BX_ERROR; const Result = { SUCCESS: 0, CACHE_FULL: 110, }; class PeerInfoCache { constructor({MAX_PEER_COUNT = 1024, PEER_TIMEOUT = 60809} = {}) { this.m_peers = new Map(); this.MAX_PEER_COUNT = MAX_PEER_COUNT; this.PEER_TIMEOUT = PEER_TIMEOUT; } get peerCount() { return this.m_peers.size; } update(peerid, pingBody, address) { let now = TimeHelper.uptimeMS(); let peerInfo = this.m_peers.get(peerid); if (!peerInfo) { if (this.m_peers.size >= this.MAX_PEER_COUNT) { let outtimePeerids = []; this.m_peers.forEach((pinfo, pid) => { if (now - pinfo.lastUpdateTime > this.PEER_TIMEOUT) { outtimePeerids.push(pid); } }); outtimePeerids.forEach(pid => this.m_peers.delete(pid)); } if (this.m_peers.size >= this.MAX_PEER_COUNT) { return Result.CACHE_FULL; } peerInfo = { eplist: new Map(), peerid: peerid, updateCount: 0, dynamics: new Map(), // 动态地址, <srcPeerid, map<sessionid,eplist>> }; this.m_peers.set(peerid, peerInfo); } peerInfo.updateCount++; peerInfo.address = address; peerInfo.info = pingBody.info; peerInfo.lastUpdateTime = now; if(peerInfo.updateCount % 7 === 0) { let timeoutEPList = []; peerInfo.eplist.forEach((updateTime, ep) => { if (now - updateTime >= this.PEER_TIMEOUT) { timeoutEPList.push(ep); } }); timeoutEPList.forEach(ep => peerInfo.eplist.delete(ep)); peerInfo.dynamics.clear(); } for (let ep of pingBody.eplist) { peerInfo.eplist.set(ep, now); } return Result.SUCCESS; } getPeerInfo(peerid) { return this.m_peers.get(peerid); } } PeerInfoCache.Result = Result; module.exports = PeerInfoCache;
/* begin copyright text * * Copyright © 2016 PTC Inc., Its Subsidiary Companies, and /or its Partners. All Rights Reserved. * * end copyright text */ /* jshint node: true */ /* jshint strict: global */ /* jshint camelcase: false */ 'use strict'; var deleteApp = require('../cds/deleteApp.js'); var rolesManager = require("./rolesManager"); var resourceAccess = require('./resourceAccess'); var debug = require('debug')('vxs:access.deleteAppListener'); if (rolesManager.hasAnyRoleConfig("reps")) { deleteApp.eventEmitter.on('post-map', function(data){ debug("Start of deleteAppListener"); if (data.store === "reps") { return resourceAccess.removeResourceAccess(data) .tap(function(){debug("End of deleteAppListener");}); } }); }
/** * @author Ignacio González Bullón - <nacho.gonzalez.bullon@gmail.com> * @since 22/11/15. */ (function () { 'use strict'; angular.module('corestudioApp') .controller('MainController', MainController); MainController.$inject = ['Alerts']; function MainController(Alerts) { var vm = this; vm.alerts = Alerts.list; vm.closeAlert = closeAlert; function closeAlert(index) { Alerts.closeAlert(index); } } })();
/**@param enchanter reducer function without default */ export const withEnchanter = (reducer, enchanter) => (state, action) =>{ const encanterState = enchanter(state, action); return encanterState ? encanterState : reducer(state, action) } export const makeActionCreators = (name, actionCreators) => { return Object.keys(actionCreators).reduce((result, key)=>{ result[key] = actionCreators[key](name); return result; }, {}) } export const makeTypeGenerators = (name, types) => { return Object.keys(types).reduce((result, key)=>{ result[key] = typeGenerator(key, name); return result; }, {}) } export const typeGenerator = (type, name) => `${type}_${name}`
import React, { Component } from 'react'; import './App.css'; import { BrowserRouter as Router, Route } from "react-router-dom"; import Student from './Student'; import Lecturer from './Lecturer'; import Visualization from './Visualization'; import TimePeriod from './TimePeriod'; import Join from './join'; class App extends Component { render() { return ( <Router> <div className="App"> <Route exact path='/' render={() => <Join/>} /> <Route exact path='/student/:room' render={({match}) => <Student room={match.params.room}/>} /> <Route exact path='/lecturer/:room' render={({match}) => <Lecturer room={match.params.room}/>} /> <Route exact path='/timeperiod/:course' render={({match}) => <TimePeriod course={match.params.course}/>} /> <Route exact path='/visualization/:course/:begin/:end' render={({match}) => <Visualization course={match.params.course} begin={match.params.begin} end={match.params.end}/>} /> </div> </Router> ); } } export default App;
"use strict"; let nowYear = () => { let date = new Date(); let span = document.querySelector('footer .year'); span.innerHTML = date.getFullYear(); }; let nowDateInput = () => { let inputDate = document.querySelectorAll('input[type="date"]'); let now = new Date(); let day = now.getDate(); let month = now.getMonth() + 1; let year = now.getFullYear(); if (month < 10) month = "0" + month; if (day < 10) day = "0" + day; now = year + "-" + month + "-" + day; inputDate.forEach((el) => { el.value = now; }); }; nowYear(); nowDateInput();
Scrolling = Class.extend({ $element: null, $textElement: null, text: null, init: function(element) { this.$element = $(element); this.$textElement = $("<div></div>").css('position', 'absolute').addClass('text'); this.$element.append(this.$textElement); }, setText: function(text) { this.text = text; this.$textElement.text(this.text); }, start: function() { console.log("scrolling start"); this.$textElement.css('right', '-' + this.$element.width() + 'px'); var me = this; window.setInterval(function() { var curRight = parseInt(me.$textElement.css('right').replace('px', '')); me.$textElement.css('right', curRight+1); }, 5); } });
var softSlider = document.getElementById('soft'); noUiSlider.create(softSlider, { start: 50, step:0.1, range: { min: 0.01, max: 1.15, }, pips: { mode: 'values', values: [0,], density: 9 } }); var softSlider = document.getElementById('slider-non-linear-value'); soft.noUiSlider.on('update', function (values, handle) { softSlider.innerHTML = values[handle]; });
'use strict' /* */ var D = require('./d.js') function decilNove (arr) { return (9 * D) } module.exports = decilNove
const express = require('express'); const app = express(); const morgan = require('morgan'); const bodyParser = require('body-parser'); const mongoose = require('./mongoose'); const notificationsRoutes = require('./api/routes/notifications'); const smsRoutes = require('./api/routes/sms'); const subscribeRoutes = require('./api/routes/subscribe'); const refreshTokenRoutes = require('./api/routes/refreshToken'); const rabbitmq = require('./api/controllers/rabbitmq'); const SMSController = require('./api/controllers/sms'); const NotificationsController = require('./api/controllers/notifications'); let count=0; rabbitmq.create_connection().then(()=>{ rabbitmq.channel.consume('notification', async (msg) => { console.log('processing messages'); msg.content = JSON.parse(msg.content.toString()) if (msg.content.type && msg.content.type == 'sms' ){ SMSController.send_sms(msg.content) }else{ NotificationsController.send_notification(msg.content.token, msg.content.payload) } setTimeout(function(){ rabbitmq.channel.ack(msg); },5000); }, { noAck: false, consumerTag: 'notification' }); }) app.use(morgan('dev')); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization'); if (req.method === 'OPTIONS') { res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET'); return res.status(200).json({}); } next(); }); //Routes which handle the requests app.use('/notifications', notificationsRoutes); app.use('/sms', smsRoutes); app.use('/subscribe', subscribeRoutes); app.use('/refreshToken', refreshTokenRoutes); app.use((req, res, next) => { const error = new Error("not found"); error.status = 404; next(error); }); app.use((error, req, res, next) => { res.status(error.status || 500); res.json({ error: { message: error.message } }) }); module.exports = app;
/** @jsx jsx */ import theme from '../../../gatsby-plugin-theme-ui'; import { keyframes, ThemeProvider } from '@emotion/react'; import styled from '@emotion/styled'; import { jsx } from 'theme-ui'; const flicker = keyframes` 0% { opacity: 0.27861; } 5% { opacity: 0.34769; } 10% { opacity: 0.23604; } 15% { opacity: 0.90626; } 20% { opacity: 0.18128; } 25% { opacity: 0.83891; } 30% { opacity: 0.65583; } 35% { opacity: 0.67807; } 40% { opacity: 0.26559; } 45% { opacity: 0.84693; } 50% { opacity: 0.96019; } 55% { opacity: 0.08594; } 60% { opacity: 0.20313; } 65% { opacity: 0.71988; } 70% { opacity: 0.53455; } 75% { opacity: 0.37288; } 80% { opacity: 0.71428; } 85% { opacity: 0.70419; } 90% { opacity: 0.7003; } 95% { opacity: 0.36108; } 100% { opacity: 0.24387; } `; const textShadow = keyframes` 0% { text-shadow: 0.4389924193300864px 0 1px rgba(0,30,255,0.5), -0.4389924193300864px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 5% { text-shadow: 2.7928974010788217px 0 1px rgba(0,30,255,0.5), -2.7928974010788217px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 10% { text-shadow: 0.02956275843481219px 0 1px rgba(0,30,255,0.5), -0.02956275843481219px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 15% { text-shadow: 0.40218538552878136px 0 1px rgba(0,30,255,0.5), -0.40218538552878136px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 20% { text-shadow: 3.4794037899852017px 0 1px rgba(0,30,255,0.5), -3.4794037899852017px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 25% { text-shadow: 1.6125630401149584px 0 1px rgba(0,30,255,0.5), -1.6125630401149584px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 30% { text-shadow: 0.7015590085143956px 0 1px rgba(0,30,255,0.5), -0.7015590085143956px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 35% { text-shadow: 3.896914047650351px 0 1px rgba(0,30,255,0.5), -3.896914047650351px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 40% { text-shadow: 3.870905614848819px 0 1px rgba(0,30,255,0.5), -3.870905614848819px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 45% { text-shadow: 2.231056963361899px 0 1px rgba(0,30,255,0.5), -2.231056963361899px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 50% { text-shadow: 0.08084290417898504px 0 1px rgba(0,30,255,0.5), -0.08084290417898504px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 55% { text-shadow: 2.3758461067427543px 0 1px rgba(0,30,255,0.5), -2.3758461067427543px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 60% { text-shadow: 2.202193051050636px 0 1px rgba(0,30,255,0.5), -2.202193051050636px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 65% { text-shadow: 2.8638780614874975px 0 1px rgba(0,30,255,0.5), -2.8638780614874975px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 70% { text-shadow: 0.48874025155497314px 0 1px rgba(0,30,255,0.5), -0.48874025155497314px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 75% { text-shadow: 1.8948491305757957px 0 1px rgba(0,30,255,0.5), -1.8948491305757957px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 80% { text-shadow: 0.0833037308038857px 0 1px rgba(0,30,255,0.5), -0.0833037308038857px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 85% { text-shadow: 0.09769827255241735px 0 1px rgba(0,30,255,0.5), -0.09769827255241735px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 90% { text-shadow: 3.443339761481782px 0 1px rgba(0,30,255,0.5), -3.443339761481782px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 95% { text-shadow: 2.1841838852799786px 0 1px rgba(0,30,255,0.5), -2.1841838852799786px 0 1px rgba(255,0,80,0.3), 0 0 3px; } 100% { text-shadow: 2.6208764473832513px 0 1px rgba(0,30,255,0.5), -2.6208764473832513px 0 1px rgba(255,0,80,0.3), 0 0 3px; } `; const StyledScreen = styled.div` width: 100%; height: 100%; border-radius: 20px; padding: 16px; background: ${(props) => props.theme.colors.secondary}; background-image: ${(props) => `radial-gradient(ellipse, ${props.theme.colors.secondary} 0%, ${props.theme.colors.muted} 90%)`}; animation: ${textShadow} 1.6s infinite; &::after { content: ' '; display: block; position: absolute; border-radius: 20px; top: 0; left: 0; bottom: 0; right: 0; background: rgba(18, 16, 16, 0.1); opacity: 0; z-index: 2; pointer-events: none; animation: ${flicker} 0.15s infinite; } &::before { content: ' '; display: block; position: absolute; border-radius: 20px; top: 0; left: 0; bottom: 0; right: 0; background: linear-gradient( rgba(18, 16, 16, 0) 50%, rgba(0, 0, 0, 0.25) 50% ), linear-gradient( 90deg, rgba(255, 0, 0, 0.06), rgba(0, 255, 0, 0.02), rgba(0, 0, 255, 0.06) ); z-index: 2; background-size: 100% 6px, 4px 100%; pointer-events: none; } `; const Screen = (props) => ( <ThemeProvider theme={theme}> <StyledScreen {...props} /> </ThemeProvider> ); export default Screen;
import PencilBox from './PencilBox'; export default function createPencilBox(canvas) { return new PencilBox(canvas); }
/** * @class widgets.GUI.ComboBox * ComboBox personalizada. * @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ var args = arguments[0] || {}; /** * @property {String} keyColumn Nome da coluna chave da coleção. * @private */ var keyColumn = null; /** * @property {widgets.GUI.PopUpList} lista Controller da lista apresentada ao listar a ComboBox * @private */ var lista = Widget.createWidget("GUI", "PopUpList"); /** * @property {Function} funcAdd Rotina executada ao se clicar em Adicionar. * @private */ var funcAdd = null; /** * @method init * Construtor da classe. * @param {Object} parans Configurações da ComboBox * @param {String} parans.nome título da combobox * @param {Function} addFunc Referência utilizada por widgets.GUI.ComboBox.funcAdd * @param {String} chave Referência utilizada por widgets.GUI.ComboBox.keyColumn * @param {BackBone.Collection} colecao Coleção vinculada a listagem da combobox * @param {String} coluna Coluna da coleção que será exibida na listagem. * @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ $.init = function(parans){ try{ $.lblDesc.text = parans.nome; funcAdd = parans.addFunc; keyColumn = parans.chave; lista.init($.lblDesc.text, parans.colecao, parans.chave, parans.coluna, $.setSelected); lista.getView().addEventListener("atualizou", checkInput); return null; } catch(e){ Alloy.Globals.onError(e.message, "init", "app/widgets/GUI/controllers/ComboBox.js"); } }; /** * @event checkInput * Rotina executada quando a coleção vinculada a lista é atualizada. * @param {Object} param Resposta do evento. * @param {BackBone.Collection} colecao Nova coleção. * @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ function checkInput(param){ var flag = false; if($.selectedDesc.chave !== null){ for(var i = 0; i < param.colecao.length; i++){ if(param.colecao[i][keyColumn] === $.selectedDesc.chave){ flag = true; break; } } if(!flag){ $.selectedDesc.chave = null; $.selectedDesc.text = ""; } } } /** * @method refreshList * Atualiza manualmente a lista vinculada. * @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ $.refreshList = function(){ try{ lista.refresh(); } catch(e){ Alloy.Globals.onError(e.message, "refreshList", "app/widgets/GUI/controllers/ComboBox.js"); } }; /** * @method selecionar * Abre a lista da combobox. * @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ $.selecionar = function(){ $.btList.fireEvent("click", {source: $.btList}); }; /** * @method getSelected * Pega as informações do item selecionado na lista da combobox * @return {Object} Item selecionado * @return {String} return.texto Descrição do item selecionado. * @return {String} return.chave Chave do item selecionado. * @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ $.getSelected = function(){ var retorno = {texto: $.selectedDesc.text, chave: $.selectedDesc.chave}; return retorno; }; /** * @method setSelected * Altera o item selecionado manualmente. * @param {String} texto Descrição. * @param {String} chave Chave que identifica o item. * @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ $.setSelected = function(texto, chave){ $.selectedDesc.text = texto; $.selectedDesc.chave = chave; }; /** * @event listar * Execuatada quando o botão listar é clicado. * @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ function listar(){ try{ lista.show(); } catch(e){ Alloy.Globals.onError(e.message, "listar", "app/widgets/GUI/controllers/ComboBox.js"); } } /** * @event btAddFunc * Executada quando o botão adicionar é clicado. * @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ function btAddFunc(){ try{ funcAdd(); } catch(e){ Alloy.Globals.onError(e.message, "btAddFunc", "app/widgets/GUI/controllers/ComboBox.js"); } }
import React from 'react'; import axios from 'axios'; import './styles.css'; export default class ListConferenceInfo extends React.Component { constructor(props) { super(props); this.state = { conference_detail: [], approved_details: [] } } componentDidMount() { axios.get('/conference') .then(response => { this.setState({ approved_details: response.data.data }); }) } navigateUpdatePage(e, id) { window.location = `/editor/${id}` } removeInfo(e, id) { axios.delete(`/conference/${id}`) .then(response => { // alert('Deletion successful!') window.location.reload(); }) .catch(error => { console.log(error.message); alert(error.message) }) } getApprove(e, id) { axios.post('/conference/send-email') .then(response => { alert('Email sent'); }) .catch(error => { console.log(error.message); alert(error.message) }) } render() { return ( <div> {/* <div className="container"> */} {this.state.approved_details.length > 0 && this.state.approved_details.map((item, index) => ( <div className="approveView"> <div key={index} className="textStyle"> <div onClick={e => this.navigateUpdatePage(e, item._id)}> <p>Venue : {item.venue}</p> <p>Dates : {item.venue_dates}</p> <p>Time : {item.venue_time}</p> <p>Regstration open : {item.registrationopen_date}</p> <p>Regstration close : {item.lastregistration_date}</p> <p>Status : {item.is_approved.toString()}</p> </div> <button type="submit" className="button1" onClick={e => this.removeInfo(e, item._id)}>Remove</button> <button type="submit" className="button2" onClick={e => this.getApprove(e, item._id)}>Get Approve</button> </div> </div> ))} </div> ) } }
module.exports = { commands: [], url: 'http://localhost:3000', elements: { docButton: { selector: '.button--green' }, githubButton: { selector: '.button--grey' } } }
const router = require("express").Router(); let Favorite = require("../models/favorite_model"); router.route("/").get((req, res) => { Favorite.find() .then((favorites) => res.json(favorites)) .catch((err) => res.status(400).json("Error: " + err)); }); router.route("/").post((req, res) => { const id = req.body.id; const previewURL = req.body.previewURL; const user = req.body.user; const username = req.body.username; const newFavorite = new Favorite({ id, previewURL, user, username }); newFavorite .save() .then(() => res.json("Favorite added!")) .catch((err) => res.status(400).json("Error: " + err)); }); router.route("/:id").delete((req, res) => { Favorite.findByIdAndDelete(req.params.id) .then(() => res.json("Favorite deleted.")) .catch((err) => res.status(400).json("Error: " + err)); }); module.exports = router;
var http = require('http') var url = require('url'); http.createServer(function (req, res) { if (req.method != 'GET') return res.end('send me a GET\n') //console.log(url.parse(req.url).query) var route = url.parse(req.url).pathname var query = url.parse(req.url,true).query if (!query.iso){ console.log('Bad request'); res.statusCode = 500; res.end('Internal Server Error'); } if (route == '/api/unixtime'){ res.writeHead(200, { 'Content-Type': 'application/json' }) res.end(JSON.stringify({ unixtime: Date.parse(query.iso) })) } //console.log(query.iso) if (route == '/api/parsetime'){ res.writeHead(200, { 'Content-Type': 'application/json' }) var date = new Date(query.iso) //console.log(date) var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); console.log(hours + ':' + minutes + ':' + seconds); res.end(JSON.stringify({ "hour": hours, "minute": minutes, "second": seconds })) } }).listen(Number(process.argv[2]))
var gulp = require('gulp'); var electron = require('gulp-electron'); var pkg = require('./package.json'); var del = require('del'); var uglify = require('gulp-uglify'); var debug = require('gulp-debug'); var replace = require('gulp-replace'); var obfuscate = require('gulp-obfuscate'); var rename = require('gulp-rename'); var zip = require('gulp-zip'); var path = require('path'); var fs = require('fs'); var exec = require('child_process').exec; var env = 'TEST'; if (gulp.env.env && (gulp.env.env == 'prod' || gulp.env.env == 'prod'.toUpperCase())) { env = 'PROD'; } else if (gulp.env.env && (gulp.env.env == 'test' || gulp.env.env == 'test'.toUpperCase())) { env = 'TEST'; } else if (gulp.env.env && (gulp.env.env == 'dev' || gulp.env.env == 'dev'.toUpperCase())) { env = 'DEV'; } else{ console.log('unknown arg env, should be use gulp --env prod (test, dev), set to prod default.'); } // build target dir const BUILD_TARGET = './build/'+ pkg.name + '/'; console.log('build with env = ', env); // error.. gulp.task('clean-main',['copy-js'], function() { del.sync([BUILD_TARGET+'src/main/main.js']); }); gulp.task('copy-main', ['clean-main'], function(){ gulp.src('gulp_config/'+ env + '/main.js', {"base": "."}) .pipe(rename({ dirname: "src/main" })) //.pipe(uglify()) .pipe(gulp.dest(BUILD_TARGET)); }); gulp.task('copy-js', function () { return gulp.src(['src/renderer/js/**/*.js', 'src/main/**/*.js'], { "base" : "." }) //.pipe(uglify()) // 压缩 // .pipe(obfuscate()) // 混淆 .pipe(gulp.dest(BUILD_TARGET)); }); gulp.task('copy-all', function () { return gulp.src(['resources/*','src/main/**/*','src/renderer/css/**/*', 'src/renderer/icon/**/*', 'src/renderer/libs/**/*', 'src/renderer/tpl/**/*', 'package.json'], { "base" : "." }) .pipe(gulp.dest(BUILD_TARGET)); }); gulp.task('clean', function() { del.sync(['build/'+ pkg.name +'/**']); del.sync(['build/release/v' + pkg.version + '/**']); }); gulp.task('copy', ['clean', 'copy-js', 'copy-all','copy-main'], function () { }); gulp.task('npm-dep', ['copy'], function () { exec(`cd build/${pkg.name} && npm install --production && cd ../../`, function (err, stdout, stderr) { }); }); gulp.task('build', function() { gulp.src("") .pipe(electron({ src: './build/' + pkg.name, packageJson: pkg, release: './build/release/v' + pkg.version, cache: './build/cache', version: 'v'+pkg.electronVersion, packaging: false, //asar: true, // token: undefined, platforms: ['win32-ia32','win32-x64'], platformResources: { darwin: { CFBundleDisplayName: pkg.displayName, CFBundleIdentifier: pkg.name + pkg.version, CFBundleName: pkg.name, CFBundleVersion: pkg.version, // icon: 'gulp-electron.ico' }, win: { "version-string": pkg.version, "file-version": pkg.version, "product-version": pkg.version, // "icon": 'gulp-electron.ico' } } })) .pipe(gulp.dest("")); }); gulp.task('default', ['npm-dep'], function(){ console.log("copy success"); }); gulp.task('package-upload', ['npm-dep'], function(){});
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Select from '@material-ui/core/Select'; import MenuItem from '@material-ui/core/MenuItem'; import Button from '@material-ui/core/Button'; class AddGenre extends Component { state = { name: '', genre_id: '', } // on click add movie / genre relation addGenre = () => { if(this.state.genre_id === ''){ alert('please select a genre to add.') } else { this.props.dispatch({ type: 'ADD_GENRE', payload: { movie_id: this.props.movieId, genre_id: this.state.genre_id, } }); } } // handle change on select handleChange = (event, props) => { this.setState({ name: event.target.value, genre_id: props.key, }) } // fetch genre list on load componentDidMount() { this.props.dispatch({ type: 'FETCH_GENRES' }); } render() { return ( <div> <Select value={this.state.name} onChange={this.handleChange}> {this.props.reduxState.genres.map( genre => { return ( <MenuItem key={genre.id} value={genre.name}>{genre.name}</MenuItem> ); })} </Select> <Button onClick={this.addGenre}>Add Genre</Button> </div> ); } } const mapReduxStateToProps = (reduxState) => ({reduxState}); export default connect(mapReduxStateToProps)(AddGenre);
import _ from 'lodash'; import React from 'react'; import { View } from 'react-native'; import { GiftedChat } from 'react-native-gifted-chat'; import { ifIphoneX } from 'react-native-iphone-x-helper'; import data_manager from './data_manager'; export default class HomeScreen extends React.Component { constructor(props) { super(props); this.state = { arrayHolder: [], message: '', }; } static navigationOptions = { title: 'Welcome to the app!', }; componentDidMount(): void { this.setState(previousState => ({ messages: GiftedChat.append(previousState.messages, { _id: 19, text: 'successfully connected', createdAt: new Date(), system: true, }), })); data_manager.clearQueue(); data_manager.setMessageCB(async message => { try { await this.handleMessage(message);} catch (e) { } }); } async handleMessage(messagesPayload) { const messages = [await data_manager.decryptMessage(messagesPayload.message)]; console.log('pullMessage', messages); const parsedMessages = []; _.forEach(messages, payload => { if (payload.message_type === 'text') { parsedMessages.push({ _id: payload.msg.msgid, text: payload.msg.text, createdAt: new Date(payload.msg.created), user: { _id: 2, avatar: 'https://placeimg.com/140/140/any', }, }); } }); this.setState(previousState => ({ messages: GiftedChat.append(previousState.messages, parsedMessages), })); } async sendMessage(messages) { await Promise.all(_.map(messages, async message => data_manager.sendTextMessage({ msgid: _.uniqueId(await data_manager.getID()), text: message.text, created: message.createdAt, }))); this.setState(previousState => ({ messages: GiftedChat.append(previousState.messages, messages), })); } render() { return ( <GiftedChat isAnimated={true} messages={this.state.messages} onSend={messages => this.sendMessage(messages)} renderAccessory={() => <View style={{ height: ifIphoneX() ? 30 : 0 }}/>} user={{ _id: 1, avatar: 'https://placeimg.com/140/140/any', }} /> ); } }
const { RichEmbed } = require("discord.js"); const { guild, createNewGuildEntry} = require("database.js"); module.exports = async (client, message, args) => { message.delete(); if(!message.member.hasPermission("BAN_MEMBERS", false, true, true)) { return 0; } if (!message.guild.me.hasPermission(["BAN_MEMBERS", "MANAGE_ROLES"], false, true)) { message.reply("Preciso da permissão `BAN_MEMBERS` e `MANAGE_ROLES` para isso"); return 0; } if (args.length < 1) { message.reply("Mencione alguém ou use o ID"); return 0; } var member; if (message.mentions.members.size > 0) { if (/<@!?[\d]{18}>/.test(args[0]) && args[0].length <= 22) { member = message.mentions.members.first(); } } else if (/[\d]{18}/.test(args[0]) && args[0].length === 18) { member = message.guild.members.get(args[0]); } if (!member) { message.reply("Mencione alguém do servidor ou use o ID"); return 0; } let reason = args.slice(1).join(' ').slice(0, 201); if (!reason.length) { message.reply("**Você esqueceu de colocar o motivo**"); return 0; } if (checagem(message, member)) return; let toxico = message.guild.roles.find(r => r.name === "☢ Tóxico ☢"); let adv2 = message.guild.roles.find(r => r.name === "advertência 2"); let adv1 = message.guild.roles.find(r => r.name === "advertência 1"); if (!toxico) toxico = await message.guild.createRole({ name: "☢ Tóxico ☢"}).catch(()=>{}); if (!adv2) adv2 = await message.guild.createRole({ name: "advertência 2"}).catch(()=>{}); if (!adv1) adv1 = await message.guild.createRole({ name: "advertência 1"}).catch(()=>{}); guild.findById(message.guild.id, "edit usuariosReportados", (err, guildTable) => { if (err) { console.log(err); return 1; } if (!guildTable) { createNewGuildEntry(message.guild.id); setTimeout(() => client.commands.reporte(client, message, args), 500); return 1; } let index = -1; let users = guildTable.usuariosReportados; for (let i = 0; i < users.length; ++i) { if (users[i]._id === member.id) { index = i; break; } } let advNumber = 1; let userEntry; if (index < 0) { userEntry = { _id: member.id, primeira: { _id: message.author.id, text: reason }, segunda: {} }; index = users.length; let roles = []; roles.push(toxico); roles.push(adv1); addRoles(member, roles); } else { userEntry = users[index]; if (userEntry.segunda._id) { advNumber = 3; } else if (userEntry.primeira._id) { userEntry.segunda = { _id: message.author.id, text: reason }; advNumber = 2; roles.push(toxico); roles.push(adv1); roles.push(adv2); addRoles(member, roles); } } let embed; let embedDM; if (advNumber === 3) { let report = guildTable.usuariosReportados[index]; embed = new RichEmbed() .setTitle(`${client.getEmoji("negado")} Membro banido`) .addField("**Usuário banido**", member, true) .addField("**Quem baniu:**", message.author,true) .addField("**Advertência 1**", `<@${report.primeira._id}> : ${report.primeira.text}`) .addField("**Advertência 2**", `<@${report.segunda._id}> : ${report.segunda.text}`) .addField("**Advertência 3**", `${message.author} : ${reason}`) .setColor("8e04cf") .setThumbnail(member.user.displayAvatarURL) .setFooter(message.guild.name, message.guild.iconURL); embedDM = new RichEmbed() .setAuthor(message.author.tag, message.author.displayAvatarURL) .setTitle(`:do_not_litter: Você foi banido por receber três advertências no servidor ${message.guild.name} ${client.getEmoji("negado")}`) .addField(`${client.getEmoji("suicidu")} Advertência dada por:`, message.author.tag) .addField(`:pencil: Motivo 1:`, `<@${report.primeira._id}> : ${report.primeira.text}`) .addField(`:pencil: Motivo 2:`, `<@${report.segunda._id}> : ${report.segunda.text}`) .addField(`:pencil: Motivo 3:`, `${message.author} : reason`) .setColor("8e04cf") .setThumbnail(message.guild.iconURL) .setFooter(`Comando executado por: ${message.author.username}`) .setTimestamp(); guildTable.usuariosReportados.splice(index, 1); member.ban().catch(()=>{}); } else { let x = advNumber === 1 ? "uma advertência" : "duas advertências" embed = new RichEmbed() .setAuthor(`Punido por: ${message.author.tag}`) .setDescription(`${member.user.username} Recebeu ${x}. ${client.getEmoji("negado")}`) .addField("Staff Tag", message.author.tag, true) .addField("Staff ID", message.author.id, true) .addField("Discord tag", member.user.tag, true) .addField("Discord ID", member.user.id, true) .addField(":pencil: Motivo:", reason) .setColor("FC0909") .setThumbnail(message.author.displayAvatarURL) .setTimestamp(); embedDM = new RichEmbed() .setAuthor(message.author.tag, message.author.displayAvatarURL) .setTitle(`:do_not_litter: Você recebeu ${x} no servidor ${message.guild.name} ${client.getEmoji("negado")}`) .addField(`${client.getEmoji("suicidu")} Advertência dada por:`, message.author.tag) .addField(`:pencil: Motivo:`, reason) .setColor("BLACK") .setThumbnail(message.guild.iconURL) .setFooter(`Comando executado por: ${message.author.username}`) .setTimestamp(); guildTable.usuariosReportados[index] = userEntry; } guildTable.save().then(() => { let channel = message.channel; if (guildTable.edit.reporte.length) { channel = message.guild.channels.get(guildTable.edit.reporte); if (!channel) channel = message.channel; } channel.send(embed).catch(()=>{}); member.send(embedDM).catch(()=>{}); }).catch(err => { console.log(err); message.reply("Erro"); }); }); }; var addRoles = (member, roles) => { for (let i = 0; i < roles.length; ++i) { if (roles[i]) { roles[i] = roles[i].id; } else { roles.splice(i, 1); } } if (roles.length) member.addRoles(roles).catch(()=>{}); } var checagem = (message, member) => { if (member.user.bot) { message.reply("**Você não pode reportar um bot!**"); return 1; } if (member.id === message.guild.ownerID) { message.reply("Você não tem permissão para punir este usuário"); return 1; } let executorRole = message.member.highestRole; let targetRole = member.highestRole; if (executorRole.comparePositionTo(targetRole) <= 0 && message.author.id !== message.guild.ownerID) { message.reply("Você não pode punir este usuário, seu cargo é menor ou igual a o do usuário a ser punido!"); return 1; } let clientRole = message.guild.me.highestRole; if (clientRole.comparePositionTo(targetRole) <= 0) { message.reply("Não tenho permissão para punir este usúario"); return 1; } return 0; };
var stage var square console.log(stage+"") window.addEventListener("load", () => { init() }) /* adjust_canvas depending on screensize */ function canvasFunction(){ console.log("here") let canvasElement = document.getElementById("splashCanvas") if(window.screen.width <= 787 ){ canvasElement.width = "500" canvasElement.height = "600" canvasElement.style.margin = "auto" } /*else if( window.screen.width > 787){ canvasElement.width = "850" canvasElement.height = "700" canvasElement.style.margin = "auto" }*/ stage = new createjs.Stage("splashCanvas") createjs.Ticker.timingMode = createjs.Ticker.RAF createjs.Ticker.addEventListener("tick", handleTick) shapeTest() } function shapeTest(){ console.log("reached function") for(let i = 0; i < 30; i++){ if(i > 1 && i < 30) setTimeout( () => {}, 1000) square = new createjs.Shape().graphics.beginFill("white").drawRect(0,0,100,100) if(square.x < 500){ square.x += 100 } if(square.x > 500) { square.x = 0 square.y += 100 } console.log("square:"+square.x+","+square.y) stage.addChild(square) } } /*function shapeTest(){ console.log("reached function") square = new createjs.Shape() square.graphics.beginFill("white").drawRect(0,0,100,100) square.x = 0 square.y = 0 console.log("square:"+square.x+","+square.y) stage.addChild(square) }*/ /*function moveCircle(){ console.log("reached circle movement function") square.x+=1 square.y+=2 if(square.x === stage_canvas.width){ square.x-=1 square.y+=2 } if(square.y === stage_canvas.height){ square.x-=1 square.y+=2 } }*/ function handleTick(tick){ stage.update(tick) } function init(){ canvasFunction() }
import React from "react"; import { useState, useEffect } from "react"; import Teams from "./teams"; import { Link } from "react-router-dom"; import axios from "axios"; // Players Component const Players = ({ match }) => { const [players, setPlayers] = useState([]); const [color, setColor] = useState(""); useEffect(() => { getPlayersData(match.params.id); // eslint-disable-next-line }, [match.params.id]); // Function to get the relevant players data based on the teamId const getPlayersData = async (id) => { try { let res = await axios.get( `https://ipflserver.herokuapp.com/players/${id}` ); const playersDataArray = JSON.parse(JSON.stringify(res.data)); setPlayers(playersDataArray, players); getTeamColor(match.params.id); } catch (error) { console.log(error.daata); } }; // Get the relevant team color based on the teamId const getTeamColor = async (id) => { try { let res = await axios.get(`https://ipflserver.herokuapp.com/teams/${id}`); const data = JSON.parse(JSON.stringify(res.data)); setColor( data.map((Team) => Team.color), color ); } catch (error) { console.log(error.daata); } }; return ( <React.Fragment> <div className="row"> <Teams teamChosen={match.params.id}></Teams> </div> <div className="container"> <div className="row"> {players.map((player) => ( <div key={player.id} className="col-sm" id="card"> <div className="test"> <img src={`${player.img}`} alt="Person" className="card__image" id={`numberBoxShadow${color}`} ></img> <p className="card__name" style={{ fontFamily: "arial", paddingTop: "5px", color: "white", }} > {player.name.length < 20 ? player.name : player.name.split(" ")[0] + " ".concat( player.name.split(" ")[ player.name.split(" ").length - 1 ] )} <span> #{player.shirtNumber}</span> </p> <Link to={`../playerStats/${player.id}`}> <button className="btn draw-border">Stats</button> </Link> </div> </div> ))} </div> </div> </React.Fragment> ); }; export default Players;
var EBE_TopActionManager = function(){ var timer = -1; var isPopOver = false; var isOpen = false; var popBtnEl = $(".header .mainNavBar .checked"); var actionBlock = $(".header .actionBlock"); popBtnEl.mouseenter(function(){ if(isOpen){return;} actionBlock.addClass("show"); isOpen = true; }).mouseleave(function(){ clearTimeout(timer); timer = setTimeout(function() { if(isPopOver){return;} isOpen = false; actionBlock.removeClass("show"); }, 50); }); actionBlock.mouseleave(function(){ isPopOver = false; isOpen = false; actionBlock.removeClass("show"); }).mouseenter(function(){ isPopOver = true; }); }; var EBE_ActionElemenGroupManager = function(el){ this.el = el; this.timer = -1; this.itemCount = 0; this.pageTotal = 0; this.page = 0; this.pageWidth = 0; this.init(); }; (function(){ this.init = function(){ this.build(); this.itemCount = this.itemEls.length; this.pageTotal = Math.ceil( this.itemCount/6 ); this.blockCount = Math.floor(this.itemCount/6 ); this.maxRedundant = this.itemCount % 6; if( this.maxRedundant < 3){ this.maxRedundant = this.maxRedundant%3; }else{ this.maxRedundant = 3; } var fCount = this.blockCount * 3 + this.maxRedundant; this.topItems = this.itemBorderEls.slice(0 , fCount ); this.bottomItems = this.itemBorderEls.slice( fCount, this.itemCount); this.bottomItems.css("marginTop",2); if( this.itemCount > 6 ){ this.arrowEls.eq(1).show(); } var that = this; this.arrowEls.click(function(){ if( that.itemUlEl.is(":animated") ){ return; } var tIndex = that.arrowEls.index(this); var toPage = that.page + (tIndex==0?-1:1); that.itemUlEl.animate({"left":-toPage * that.pageWidth },"normal",function(){ that.setIndex(toPage); }); }); }; this.setIndex = function(val){ this.itemUlEl.stop(); this.page = val; if( this.page == 0 ){ this.arrowEls.eq(0).hide(); }else{ this.arrowEls.eq(0).show(); } if( this.page < this.pageTotal-1 ){ this.arrowEls.eq(1).show(); }else{ this.arrowEls.eq(1).hide(); } this.itemUlEl.css("left", -this.page * this.pageWidth); }; this.updateSize = function(val){ this.el.height(val); this.pageWidth = this.itemsBlockEl.width(); var itemWidth = this.pageWidth/3; this.itemUlEl.width( (itemWidth*3)*this.blockCount + this.maxRedundant*itemWidth ); this.itemEls.width( itemWidth ); this.topItems.height( val/2 - 1); this.bottomItems.height( val/2 - 2); this.setIndex( this.page ); }; this.build = function(){ this.itemsBlockEl = this.el.find(".itemsBlock"); this.itemUlEl = this.el.find("ul"); this.itemEls = this.itemUlEl.find("li"); this.itemBorderEls = this.itemEls.find(".item"); this.arrowEls = this.el.find(".arrow"); }; }).call(EBE_ActionElemenGroupManager.prototype); var EBE_ActionElementNav = function(count,setPage){ var el = $(".actionElementNavBar"); var index = 0; var i; for(i=0;i<count;i++){ $("<a href='javascript:;'></a>").appendTo(el); } var btnEls = el.find("a"); if(count==1){ btnEls.hide(); } btnEls.click(function(){ var tIndex = btnEls.index(this); var btnEl = btnEls.eq( tIndex ); if( btnEl.hasClass("current") ){ return; } setPage(tIndex); }); function setIndex(val){ index = val; btnEls.removeClass("current"); btnEls.eq(index).addClass("current"); } return {"setIndex":setIndex}; }; var EBE_ActionElement = function(){ var i,group,index=0; var timer = -1,isMouseOver = false; var groups = []; var winEl = $(window); var el = $(".common_mainPanel .actionElementBlock"); var borderEl = el.find(".borderBlock"); var holderEl = el.find(".holder"); var groupUlEls = el.find(".groupPanel"); var groupEls = groupUlEls.find(".groupBlock"); var groupCount = groupEls.length; var groupHeight = 0; var isBgLoaded = false; var nav = new EBE_ActionElementNav(groupCount,function(val){ if( groupUlEls.is(":animated") ){ return false;} animaPosByIndex( index,val); return true; }); el.mouseenter(function(){ isMouseOver = true; }).mouseleave(function(){ isMouseOver = false; }); function animaPosByIndex(startIndex,endIndex){ clearTimeout(timer); groupUlEls.stop(); index = endIndex; nav.setIndex( endIndex ); var curY = parseInt( groupUlEls.css("top") ); groupUlEls.animate({"top": curY - (endIndex-startIndex)* groupHeight },500* Math.abs(endIndex-startIndex),function(){ setIndex(index); }); } function animaPosByAuto(){ if(groupCount<=1){return;} clearTimeout(timer); groupUlEls.stop(); timer = setTimeout(function(){ if( el.is(":hidden") || isMouseOver){ animaPosByAuto(); return; } index = (index+1) % groupCount; nav.setIndex( index ); var curY = parseInt( groupUlEls.css("top") ); groupUlEls.animate({"top": curY - groupHeight },500,function(){ setIndex(index); }); },5000); } if( groupEls.length > 1 ){ var fEl = groupEls.eq(0); var lEl = groupEls.eq(groupCount-1); fEl.before( lEl.clone()); lEl.after( fEl.clone()); var groupEls = groupUlEls.find(".groupBlock"); } for( i=0; i < groupEls.length;i++){ group = new EBE_ActionElemenGroupManager( groupEls.eq(i) ); groups.push( group ); } function setIndex(val){ groupUlEls.stop(); index = val; if(groupCount<=1){ groupUlEls.css("top", 0 ); }else{ groupUlEls.css("top", -(index+1)*groupHeight ); } nav.setIndex(val); animaPosByAuto(); } function winResizeHandler(){ if(!isBgLoaded){return;} groupHeight = holderEl.height(); for(i=0; i <groups.length ;i++){ groups[i].updateSize( groupHeight ); } groupUlEls.height( groupHeight * (groupCount + 2) ); setIndex(index); borderEl.height( groupHeight ); }; winEl.resize(winResizeHandler); if( holderEl.prop("complete") ){ isBgLoaded = true; borderEl.show(); winResizeHandler(); }else{ isBgLoaded = true; borderEl.show(); holderEl[0].onload = winResizeHandler; } }; var EBE_MobileActionElementBlock = function(tragetLi,container){ var el = $("<li></li>"); var tImgEl = tragetLi.find(".mainBlock img"); var mainImgContainerEl = $("<div class='mainBlock'></div>").appendTo(el).append( tImgEl.clone() ); $("<div class='navSpacer'></div>").appendTo(el); var itemBlockEl = $("<div class='itemsBlock'></div>").appendTo(el); var tItemEls = tragetLi.find(".itemsBlock .itemPanel li"); var i,tItemEl; for( i = 0; i < tItemEls.length;i++ ){ tItemEl = tItemEls.eq(i).children("a"); tItemEl.clone().appendTo(itemBlockEl); } $("<div class='clearFloat'></div>").appendTo(el); container.append(el); var itemEl = itemBlockEl.children("a"); function resizeHandler( blockWidth ){ el.width( blockWidth ); var itemWidth = itemEl.eq(0).width(); var rowCount = Math.floor(blockWidth/itemWidth); var space = ( blockWidth - rowCount*itemWidth ) /(rowCount+1); if( space < 10 ){ rowCount--; space = ( blockWidth - rowCount*itemWidth ) /(rowCount+1); } itemEl.css("marginLeft",space); return el.height(); } return {"el":el, "resizeHandler":resizeHandler, "getMainImgHeight":function(){ return mainImgContainerEl.height(); }}; }; var EBE_MobileActionElement=function(){ var winEl = $(window); var el = $(".common_mainPanel .mobileActionElementBlock"); var ulEl = el.children("ul"); var targetEl = $(".common_mainPanel .actionElementBlock .borderBlock .groupPanel>li"); var liWidth = 0; var index = 0; var timer = -1; var liCount = targetEl.length; var blocks = [ new EBE_MobileActionElementBlock( targetEl.eq(targetEl.length-1),ulEl) ]; for(var i=0;i<targetEl.length;i++){ blocks.push( new EBE_MobileActionElementBlock( targetEl.eq(i),ulEl) ); } blocks.push( new EBE_MobileActionElementBlock( targetEl.eq(0),ulEl) ); var nav = new EBE_MobileActionElementNav( liCount ,el, function(val){ animaPosByIndex(index,val); }); function animaPosByIndex(startIndex,endIndex){ clearTimeout(timer); ulEl.stop(); index = endIndex; nav.setIndex( endIndex ); var curX = parseInt( ulEl.css("left") ); ulEl.animate({"left": curX - (endIndex-startIndex)* liWidth },500* Math.abs(endIndex-startIndex),function(){ setIndex(index); animaPosByAuto(); }); } function animaPosByAuto(){ if(liCount<=1){return;} clearTimeout(timer); ulEl.stop(); timer = setTimeout(function(){ if( el.is(":hidden") ){ animaPosByAuto(); return; } index = (index+1) % liCount; nav.setIndex( index ); var curX = parseInt( ulEl.css("left") ); ulEl.animate({"left": curX - liWidth },500,function(){ setIndex(index); }); },5000); } function setIndex(val){ ulEl.stop(); index = val; if(liCount<=1){ ulEl.css("left", 0 ); }else{ ulEl.css("left", -(index+1)*liWidth ); } nav.setIndex(val); animaPosByAuto(); } function resizeHandler(){ if( el.is(":hidden") ){return;} liWidth = el.width(); var i,th,maxHeight = 0; for(var i=0; i < blocks.length;i++){ th = blocks[i].resizeHandler( liWidth ); if(maxHeight < th){ maxHeight = th; } } el.height(maxHeight); nav.el.css("top",blocks[0].getMainImgHeight() ); ulEl.width( (liCount+ 2) * liWidth ); setIndex(index); } winEl.resize(resizeHandler); resizeHandler(); }; var EBE_MobileActionElementNav = function(count,container,setPage){ var el = $("<div class='navBar'></div>").appendTo(container); var index = 0; var i; for(i=0;i<count;i++){ $("<a href='javascript:;'></a>").appendTo(el); } var btnEls = el.find("a"); if(count==1){ btnEls.hide(); } btnEls.click(function(){ var tIndex = btnEls.index(this); var btnEl = btnEls.eq( tIndex ); if( btnEl.hasClass("current") ){ return; } setPage(tIndex); }); function setIndex(val){ index = val; btnEls.removeClass("current"); btnEls.eq(index).addClass("current"); } return {"el":el,"setIndex":setIndex}; }; var EBE_HistoryManager = function(){ var winEl = $(window); var el = $(".common_mainPanel .historyPanel"); var liEls = el.find("li"); var liCount = liEls.length; var aEls = el.find("li a"); var imgEls = el.find("li a img"); var popEls = el.find(".popBlock"); var popAEls = popEls.find("a"); var popImgEls = popEls.find("img"); var liWidth=0,liHeight=0; var rowItemCount = 0; var colItemCount = 0; aEls.mouseenter(function(){ var tIndex = aEls.index(this); popAEls.attr( "href", aEls.eq(tIndex).attr("href") ); popImgEls.attr("src",imgEls.eq(tIndex).attr("src") ); var isRowLast = tIndex % rowItemCount == rowItemCount-1?true:false; var isColLsat = Math.floor(tIndex/rowItemCount) % colItemCount == colItemCount-1?true:false; var sTop = Math.floor(tIndex/rowItemCount) * liHeight; var sLeft = tIndex % rowItemCount * liWidth; popAEls.css({"marginRight":3,"marginLeft":0} ); if( isRowLast ){ sLeft = (tIndex % rowItemCount-1) * liWidth; } if(isColLsat){ sTop = (Math.floor(tIndex/rowItemCount)-1) * liHeight;; } popEls.addClass("show").css({"top":sTop,"left":sLeft}); }); el.mouseleave(function(){ popEls.removeClass("show"); }); function resizeHandler(){ liWidth = liEls.eq(0).width(); liHeight = liEls.eq(0).height()+3; rowItemCount = Math.round(el.width()/ liWidth); colItemCount = Math.round(el.height()/liHeight ); } var imgCount = 0; var imgEls = el.find("ul img"); imgEls.each(function(index){ if( imgEls.eq(index).prop("complete") ){ init(); }else{ imgEls[index].onload =init; } }); function init(){ imgCount++; if( imgCount >= imgEls.length ){ winEl.resize(resizeHandler); resizeHandler(); } } }; var EBE_MobileHistoryManager = function(){ var winEl = $(window); var el = $(".common_mainPanel .mobileHistoryPanel"); var bgEl = el.find(".holder"); var ulEl = el.find("ul"); var liEls = $(".common_mainPanel .historyPanel ul li").clone(); var arrowEls = el.find(".arrow"); ulEl.append(liEls); var liWidth = 0; var liCount = liEls.length; var isBgLoaded = false; var timer = -1; var index = 0; if( liCount > 1){ arrowEls.click(function(){ if( ulEl.is(":animated") ){return;} var tIndex = arrowEls.index(this); var toIndex = index + (tIndex==0?-1:1); ulEl.animate({"left":-toIndex * liWidth },"normal",function(){ setIndex(toIndex); }); }); } function setIndex(val){ ulEl.stop(); index = val; if(liCount<=1){ ulEl.css("top", 0 ); }else{ ulEl.css("left", -index*liWidth ); } if( index == 0 ){ arrowEls.eq(0).hide(); }else{ arrowEls.eq(0).show(); } if( index < liCount-1 ){ arrowEls.eq(1).show(); }else{ arrowEls.eq(1).hide(); } } function resizeHandler(){ liWidth = bgEl.width(); liEls.width(liWidth); ulEl.width( (liCount+ 2) * liWidth ); setIndex(index); } winEl.resize(resizeHandler); if( bgEl.prop("complete") ){ isBgLoaded = true; resizeHandler(); }else{ bgEl[0].onload = resizeHandler; } }; $(function(){ new EBE_TopActionManager(); new EBE_MobileActionElement(); new EBE_ActionElement(); new EBE_HistoryManager(); new EBE_MobileHistoryManager(); });
function listScenarios(src, skipFirst) { const menu = { items: [], settings: { title: '=== Select Scenario ===', }, onSelect: function(item, i) { log('selected: #' + i + ': ' + item.name) trap('showScenario', { map: item.map, land: item.land, }) }, } menu.items.itemStep = 1 for (let i = skipFirst? 1 : 0; i < src.length; i++) { const land = src[i] menu.items.push({ name: land.name, map: i, land: src[i], }) } menu.items.push({ name: env.msg.back, action: function(menu) { menu.selectMore(lib.menu.main) }, }) return menu }
function recuperarDatos(url, callback) { $.ajax({ url: url, type: 'GET', dataType:"jsonp", success: function(data) { callback(data); }, error: function(jqXHR, textStatus, error) { alert( "error: " + jqXHR.responseText); } }); } function recuperarDatos2(url, tipo) { $.ajax({ url: url, type: 'GET', dataType:"jsonp", success: function(data) { switch(tipo) { case "pilotos": localStorage.setItem("pilotos", JSON.stringify(data)); break; case "constructores": localStorage.setItem("constructores", JSON.stringify(data)); break; case "carrera": localStorage.setItem("carrera", JSON.stringify(data)); break; case "calendario": localStorage.setItem("calendario", JSON.stringify(data)); break; case "circuitos": localStorage.setItem("circuitos", JSON.stringify(data)); break; } }, error: function(jqXHR, textStatus, error) { alert( "error: " + jqXHR.responseText); } }); } function anadirMarcador(mapa, posicion,contenido) { var opcionesMarcador = { position: posicion, map: mapa, icon: "./icons/marker.png", clickable: true }; var marcador = new google.maps.Marker(opcionesMarcador); var opcionesVentanaInformacion = { content: "<span class='info'>"+ contenido +"</span>", position: posicion }; var ventanaInformacion = new google.maps.InfoWindow(opcionesVentanaInformacion); google.maps.event.addListener(marcador, "click", function() { ventanaInformacion.open(map); }); } function mostrarMapa() { var centro = new google.maps.LatLng(19.416775400000000000,19.703790199999957600); var opcionesMapa = { zoom: 1, center: centro, mapTypeId: google.maps.MapTypeId.ROADMAP }; var divMap = document.getElementById("mapa"); map = new google.maps.Map(divMap, opcionesMapa); return map; } function pilotos(data) { var pilotos = data.MRData.StandingsTable.StandingsLists[0].DriverStandings; $('#contenidoPilotos').empty(); $('#contenidoPilotos').append('<table class="fullTable">'); $('#contenidoPilotos table').append('<thead>'); $('#contenidoPilotos table').append('<tbody>'); $('#contenidoPilotos table thead').append('<tr><th class="mobileHide">Posición</th><th>Nombre</th><th>Escudería</th><th>Puntos</th></tr>'); for (var i=0; i < pilotos.length; i++) { var piloto = pilotos[i]; $('#contenidoPilotos table tbody').append('<tr><td class="mobileHide">' + (i+1) + '</td><td>' + piloto.Driver.givenName + " " + piloto.Driver.familyName + " </td><td> " + piloto.Constructors[0].name + " </td><td>" + piloto.points + '</td></tr>'); } } function constructores(data) { var constructores = data.MRData.StandingsTable.StandingsLists[0].ConstructorStandings; //$('nav').hide(); $('#contenidoConstructores').empty(); $('#contenidoConstructores').append('<table class="fullTable">'); $('#contenidoConstructores table').append('<thead>'); $('#contenidoConstructores table').append('<tbody>'); $('#contenidoConstructores table thead').append('<tr><th>Posición</th><th>Nombre</th><th class="mobileHide">Nacionalidad</th><th>Puntos</th></tr>'); for (var i=0; i < constructores.length; i++) { var constructor = constructores[i]; $('#contenidoConstructores table tbody').append('<tr><td>' + (i+1) + '</td><td>'+ constructor.Constructor.name + "</td><td class='mobileHide'>" + constructor.Constructor.nationality + "</td><td>" + constructor.points + '</td></tr>'); } } function ultimaCarrera(data) { var resultados = data.MRData.RaceTable.Races[0].Results; $('#contenidoUltimaCarrera').empty(); $('#contenidoUltimaCarrera').append('<table class="fullTable">'); $('#contenidoUltimaCarrera table').append('<thead>'); $('#contenidoUltimaCarrera table').append('<tbody>'); $('#contenidoUltimaCarrera table thead').append('<tr><th>Posición</th><th>Piloto</th><th class="mobileHide">Escudería</th><th class="mobileHide">Vueltas</th><th class="mobileHide">Posición en parrilla</th><th class="mobileHide">Tiempo</th><th class="mobileHide">Estado</th><th>Puntos</th></tr>'); for (var i=0; i < resultados.length; i++) { var resultado = resultados[i]; if(resultado.hasOwnProperty("Time")) { $('#contenidoUltimaCarrera table tbody').append('<tr><td>' + resultado.position + '</td><td>' + resultado.Driver.givenName + " " + resultado.Driver.familyName + '</td><td class="mobileHide">' + resultado.Constructor.name + '</td><td class="mobileHide">' + resultado.laps + '</td><td class="mobileHide">' + resultado.grid + '</td><td class="mobileHide">' + resultado.Time.time + '</td><td class="mobileHide">' + resultado.status + '</td><td>' + resultado.points + '</td></tr>'); } else { $('#contenidoUltimaCarrera table tbody').append('<tr><td>' + resultado.position + '</td><td>' + resultado.Driver.givenName + " " + resultado.Driver.familyName + '</td><td class="mobileHide">' + resultado.Constructor.name + '</td><td class="mobileHide">' + resultado.laps + '</td><td class="mobileHide">' + resultado.grid + '</td><td class="mobileHide">No time</td><td class="mobileHide">' + resultado.status + '</td><td>' + resultado.points + '</td></tr>'); } } } function calendario(data) { var carreras = data.MRData.RaceTable.Races; var map; $('#contenidoCalendario').empty(); $('#contenidoCalendario').append('<table class="halfTable">'); if(flagConnection === 0) { $('#contenidoCalendario').append('<div id="mapa" class="mapa mobileHide">'); } $('#contenidoCalendario table').append('<thead>'); $('#contenidoCalendario table').append('<tbody>'); $('#contenidoCalendario table thead').append('<tr><th class="mobileHide tabletHide">Número</th><th>Carrera</th><th class="mobileHide tabletHide">Circuito</th><th>Fecha</th></tr>'); if(flagConnection === 0) { map = mostrarMapa(); } for (var i=0; i < carreras.length; i++) { var carrera = carreras[i]; if(flagConnection === 0) { var latitude = carrera.Circuit.Location.lat; var longitude = carrera.Circuit.Location.long; var centro = new google.maps.LatLng(latitude, longitude); anadirMarcador(map, centro, carrera.Circuit.circuitName); } $('#contenidoCalendario table tbody').append('<tr><td class="mobileHide tabletHide">' + carrera.round + '</td><td>' + carrera.raceName + '</td><td class="mobileHide tabletHide">' + carrera.Circuit.circuitName + '</td><td>' + carrera.date + '</td></tr>'); } } function circuitos(data) { var circuitos = data.MRData.CircuitTable.Circuits; $('#contenidoCircuitos').empty(); $('#contenidoCircuitos').append('<table class="fullTable">'); $('#contenidoCircuitos table').append('<thead>'); $('#contenidoCircuitos table').append('<tbody>'); $('#contenidoCircuitos table thead').append('<tr><th class="mobileHide">Número</th><th>Nombre</th><th class="mobileHide">Localidad</th><th>País</th></tr>'); for (var i=0; i < circuitos.length; i++) { var circuito = circuitos[i]; $('#contenidoCircuitos table tbody').append('<tr><td class="mobileHide">' + (i+1) + '</td><td>' +circuito.circuitName + '</td><td class="mobileHide">' + circuito.Location.locality +'</td><td>' + circuito.Location.country + '</td></tr>'); } } var flagConnection; window.addEventListener("load", function() { if (navigator.onLine) { flagConnection = 0; recuperarDatos2('http://ergast.com/api/f1/current/driverStandings.json', 'pilotos'); recuperarDatos2('http://ergast.com/api/f1/current/constructorStandings.json', 'constructores'); recuperarDatos2('http://ergast.com/api/f1/current/last/results.json', 'carrera'); recuperarDatos2('http://ergast.com/api/f1/current.json', 'calendario'); recuperarDatos2('http://ergast.com/api/f1/current/circuits.json', 'circuitos'); console.log("Carga de datos en el LocalStorage completada"); } else { flagConnection = 1; } }); if ("onLine" in navigator) { window.addEventListener("online", function online() { flagConnection = 0; alert("Ya tienes conexión"); console.log("estamos on"); }); window.addEventListener("offline", function offline(e) { flagConnection = 1; alert("Estas sin conexión. Los datos utilizados serán recogidos del localstorage"); console.log("estamos off"); }); } else { console.log("not supported"); } $(document).on( "pageshow", '#main, #divPilotos, #divCircuitos, #divCalendario', function() { ScaleContentToDevice() ; }); $('#main').on('pageinit', function() { $('#divPilotos').on({ pageshow: function() { if(flagConnection === 0) { recuperarDatos('http://ergast.com/api/f1/current/driverStandings.json', pilotos); } else { pilotos(JSON.parse(localStorage.getItem("pilotos"))); console.log("Datos de Pilotos recogidos del LocalStorage"); } } }); $('#divConstructores').on({ pageshow: function() { if(flagConnection === 0) { recuperarDatos('http://ergast.com/api/f1/current/constructorStandings.json', constructores); } else { constructores(JSON.parse(localStorage.getItem("constructores"))); console.log("Datos de Constructores recogidos del LocalStorage"); } } }); $('#divUltimaCarrera').on({ pageshow: function() { if(flagConnection === 0) { recuperarDatos('http://ergast.com/api/f1/current/last/results.json', ultimaCarrera); } else { ultimaCarrera(JSON.parse(localStorage.getItem("carrera"))); console.log("Datos de la ultima carrera recogidos del LocalStorage"); } } }); $('#divCalendario').on({ pageshow: function() { if(flagConnection === 0) { recuperarDatos('http://ergast.com/api/f1/current.json', calendario); } else { calendario(JSON.parse(localStorage.getItem("calendario"))); $('#contenidoCalendario table').css({'width':'95%', 'margin-left':'15px'}); console.log("Datos de Calendario recogidos del LocalStorage"); } } }); $('#divCircuitos').on({ pageshow: function() { if(flagConnection === 0) { recuperarDatos('http://ergast.com/api/f1/current/circuits.json', circuitos); } else { circuitos(JSON.parse(localStorage.getItem("circuitos"))); console.log("Datos de Circuitos recogidos del LocalStorage"); } } }); }); $(window).on("resize orientationchange", function() { ScaleContentToDevice(); }); function ScaleContentToDevice() { scroll(0, 0); var content = $.mobile.getScreenHeight() - $(".ui-header").outerHeight() - $(".ui-footer").outerHeight() - $(".ui-content").outerHeight() + $(".ui-content").height(); $(".ui-content").height(content); } $( window ).on( "orientationchange", function() { switch(window.orientation) { case 0: alert("Estas en Portrait"); break; case -90: alert("Landscape girado sentido agujas reloj"); break; case 90: alert("Landscape girado sentido contrario agujas reloj"); break; case 180: alert("Estas en Portrait boca abajo"); break; } });
import React from 'react'; import './index.scss'; const Input = ({ title = 'Titulo', type = 'text', placeholder = 'Aquí va un mensaje', value, exportValue, defaultValue }) => { const onChangeValue = (event) => { if (type === 'number') { exportValue(parseFloat(event)); } exportValue(event); }; return ( // eslint-disable-next-line jsx-a11y/label-has-associated-control <label className="Input"> <p>{title}</p> <input type={type} placeholder={placeholder} value={value} defaultChecked={defaultValue} onChange={(event) => onChangeValue(event.target.value)} /> </label> ); }; export default Input;
import React from 'react' import Thumbnail from './Thumbnail' import Button from '../estilos' const Item = (props) => { return( <div className="row pt-4 pb-4"> <div className="col-md-10 offser-md-1"> <div> <div className="card px-5"> <div className="row"> <div className="col-md-4"> <Thumbnail url={props.url}/> </div> <div className="col-md-8"> <div className="pt-4 pb-4"> <h4>{props.title}</h4> <p>{props.description}</p> <div className="cta-wrapper"> <Button onClick={props.cambioVideo} className="btn cta-btn">Ver</Button> </div> </div> </div> </div> </div> </div> </div> </div> ) } export default Item
describe('<database module spes>', function() { var db = null; beforeEach(function() { db = new Rho.Database(Rho.Application.databaseFilePath('local'), 'local'); }); afterEach(function() { db.close(); db = null; }); // Database.prototype.startTransaction = function() // Database.progtotype.commitTransaction = function() it('starts and commits transaction', function() { db.executeBatchSql('DROP TABLE IF EXISTS t; CREATE TABLE t(x INTEGER, y TEXT, z VARCHAR(10));'); db.startTransaction(); db.executeSql('INSERT INTO t (x, y, z) VALUES (?, ?, ?);', [10, 'ten', 'TEN']); expect(db.executeSql('SELECT * FROM t;')).toEqual([{x: 10, y: 'ten', z: 'TEN'}]); db.commitTransaction(); expect(db.executeSql('SELECT * FROM t;')).toEqual([{x: 10, y: 'ten', z: 'TEN'}]); }); // Database.prototype.startTransaction = function() // Database.prototype.rollbackTransaction = function() it('starts and rollbacks transaction', function() { db.executeBatchSql('DROP TABLE IF EXISTS t; CREATE TABLE t(x INTEGER, y TEXT, z VARCHAR(10));'); db.startTransaction(); db.executeSql('INSERT INTO t (x, y, z) VALUES (?, ?, ?);', [10, 'ten', 'TEN']); expect(db.executeSql('SELECT * FROM t;')).toEqual([{x: 10, y: 'ten', z: 'TEN'}]); db.rollbackTransaction(); expect(db.executeSql('SELECT * FROM t;')).toEqual([]); }); // Database.prototype.lockDb = function() // Database.prototype.unlockDb = function() it('locks and unlocks database', function() { db.lockDb(); db.executeBatchSql('DROP TABLE IF EXISTS t; CREATE TABLE t(x INTEGER, y TEXT, z VARCHAR(10));'); db.executeSql('INSERT INTO t (x, y, z) VALUES (?, ?, ?);', [10, 'ten', 'TEN']); db.unlockDb(); expect(db.executeSql('SELECT * FROM t;')).toEqual([{x: 10, y: 'ten', z: 'TEN'}]); }); // Database.prototype.isUiWaitForDb = function() it('calls isUiWaitForDb', function() { expect(db.isUiWaitForDb()).toBe(false); }); // Database.prototype.executeSql = function(/* const rho::String& */ sqlStmt, /* const rho::Vector<rho::String>& */ args) it('executes SQL statements', function() { db.executeSql('DROP TABLE IF EXISTS t;'); db.executeSql('CREATE TABLE t(x INTEGER, y TEXT, z VARCHAR(10));'); db.executeSql('INSERT INTO t (x, y, z) VALUES (?, ?, ?);', [10, 'ten', 'TEN']); db.executeSql('INSERT INTO t (x, y, z) VALUES (?, ?, ?);', [11, 'eleven', 'ELEVEN']); expect(db.executeSql('SELECT * FROM t ORDER BY x DESC;')).toEqual([{x: 11, y: 'eleven', z: 'ELEVEN'}, {x: 10, y: 'ten', z: 'TEN'}]); }); // Database.prototype.executeBatchSql = function(/* const rho::String& */ sqlStmt, /* const rho::Vector<rho::String>& */ args) it('executes SQL statements as batch', function() { db.executeBatchSql('DROP TABLE IF EXISTS t; CREATE TABLE t(x INTEGER, y TEXT, z VARCHAR(10));'); db.executeSql('INSERT INTO t (x, y, z) VALUES (?, ?, ?);', [10, 'ten', 'TEN']); db.executeSql('INSERT INTO t (x, y, z) VALUES (?, ?, ?);', [11, 'eleven', 'ELEVEN']); expect(db.executeSql('SELECT * FROM t ORDER BY x DESC;')).toEqual([{x: 11, y: 'eleven', z: 'ELEVEN'}, {x: 10, y: 'ten', z: 'TEN'}]); }); // Database.prototype.destroyTable = function(/* const rho::String& */ tableName) it('destroys table', function() { db.executeBatchSql('CREATE TABLE IF NOT EXISTS t1(x INTEGER); CREATE TABLE IF NOT EXISTS t2(x INTEGER);'); db.destroyTable('t1'); db.destroyTable('t3'); expect(db.isTableExist('t1')).toBe(false); expect(db.isTableExist('t2')).toBe(true); expect(db.isTableExist('t3')).toBe(false); }); // Database.prototype.destroyTables = function(/* const rho::Hashtable<rho::String, rho::String>& */ propertyMap) describe('destroys multiple tables', function() { var makeTest = function(name, include, exclude, remaining) { var contains = function(array, item) { for (var i = 0; i < array.length; ++i) { if (array[i] === item) { return true; } } return false; }; it(name, function() { for (var i = 1; i < 5; ++i) { db.executeSql('CREATE TABLE IF NOT EXISTS t' + i + '(x INTEGER);'); } db.destroyTables({'include': include, 'exclude': exclude}); var actual = []; for (var i = 1; i < 5; ++i) { if (db.isTableExist('t' + i)) { actual.push('t' + i); } } expect(actual).toEqual(remaining); }); }; // names of tables to delete included excluded remaining makeTest('all' , [ ], [ ], [ ]); makeTest('all but excluded' , [ ], ['t2', 't1'], ['t1', 't2' ]); makeTest('included only' , ['t2', 't1'], [ ], ['t3', 't4' ]); makeTest('included only but excluded', ['t2', 't1'], ['t2', 't3'], ['t2', 't3', 't4']); }); // Database.prototype.isTableExist = function(/* const rho::String& */ tableName) it('checks for table existence', function() { db.executeSql('DROP TABLE IF EXISTS t;'); expect(db.isTableExist('t')).toBe(false); db.executeSql('CREATE TABLE t(x INTEGER, y TEXT, z VARCHAR(10));'); expect(db.isTableExist('t')).toBe(true); db.executeSql('DROP TABLE IF EXISTS t;'); expect(db.isTableExist('t')).toBe(false); }); // Database.prototype.setDoNotBackupAttribute = function(/* bool */ setFlag) xit('sets "don\'t backup attribute"', function() { db.setDoNotBackupAttribute(true); }); });
'use strict'; module.exports=[ require(__dirname+'/helloWorld.js'), require(__dirname+'/log.js'), require(__dirname+'/product.js') ];
var num = 10; var obj = {num: 20}; obj.fn = (function (num) { this.num = num * 3; num ++; return function (n) { this.num += n; num ++; console.log(num); } })(obj.num); var fn = obj.fn; fn(5); obj.fn(10); // 22 23 /** * 关键是this的指向. fn前面没点 ,所以两个都是window * 自执行函数中的this是window; * **/
var app = app || {} app.signIn = Backbone.View.extend({ el: '.container-signin-signup', className: "sigin-form", template: _.template($('#signin').html()), events: { 'click button': 'signInUser' }, render: function(){ this.$el.empty(); var htmlForSignIn = this.$el.html(this.template()); return this }, signInUser: function(evt){ evt.preventDefault(); var email = $('input#email').val(); var password = $('input#password').val(); var signInAjax = $.ajax({ url: '/account/signin', type: 'POST', data: { email: email, password: password } }) signInAjax.done(this.createSession) }, createSession: function(reply){ if (isNaN(reply.user_id) === false) { sessionStorage.setItem('user_id', reply.user_id) sessionStorage.setItem('username', reply.username) // setting the items for sessionStorage $('div.container-signin-signup').remove(); $('#maingrid').show(); app.View = new app.AppView(); app.View.addAll(); var userId = app.Todos.at(0).get('user_id'); if (userId != sessionStorage.getItem('user_id') && userId !== undefined){ $('.todo-item').remove() } inputResizer(); } else if (reply.message !== undefined){ $('.errors-signin').remove() var errors = reply.message var compileErrors = _.template('<p class="errors-signin text-center helveticaneue red-text"><%=text%></p>'); $('#form-holder').prepend(compileErrors({text: errors})); }else { $('.errors-signin').remove() var errors = reply.errors var compileErrors = _.template('<p class="errors-signin text-center helveticaneue red-text"><%=text%></p>'); $('#form-holder').prepend(compileErrors({text: errors})); } } })