text
stringlengths
7
3.69M
const timeline = anime.timeline({ loop: true, autoplay: true, // autoplay: true, duration: 200, easing: 'easeInOutSine', }); timeline.add({ targets: '#sun', duration: 100, opacity: [100, 0] }, '+=0') .add({ duration: 2000, })
import React from 'react'; export function Camper(props){ const {camper} = props; return ( <tr className="camper-row" > <th>{props.num}</th> <th> <img src={camper.img} alt=""/> &nbsp; <a href={`http://www.freecodecamp.com/${camper.username}`}>{camper.username}</a> </th> <th>{camper.recent}</th> <th>{camper.alltime}</th> </tr> )}; export default Camper;
import React from 'react'; const Form = () => ( <div className="container"> <h4 className="center">Form</h4> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Asperiores amet quos quas enim cumque commodi quo vero molestiae eaque, odio ipsum nam animi error voluptatibus voluptas, incidunt voluptatem soluta dicta. </p> </div> ); export default Form;
import React from 'react'; import Header from './components/Header' import Transaction from './components/Transaction' import Balance from './components/Balance' import Home from './components/Home' import CreateAccount from './components/CreateAccount' import { Route, Switch } from 'react-router-dom' function App() { return ( <div className="container"> <Header /> <Switch> <Route exact path='/' component={Home} /> <Route exact path='/create' component={CreateAccount} /> <Route exact path='/transaction' component={Transaction} /> <Route exact path='/balance' component={Balance} /> </Switch> </div> ); } export default App;
let screenPtr, screenbufferPtr; let framebuffer = new ImageData(640, 480); const screen = document.getElementById("screen") screen.width = 640; screen.height = 480; const screenCtx = screen.getContext("2d"); function start() { screenPtr = Module._malloc(640 * 480 * 4); screenbufferPtr = Module.ccall("makeScreenbuffer", "number", ["number", "number", "number"], [screenPtr, 640, 480]); requestAnimationFrame(jsupdate); } function jsupdate() { Module.ccall("update", null, ["number"], [screenbufferPtr]); for (let i = 0, len = framebuffer.data.length; i < len; i += 1) { framebuffer.data[i] = Module.HEAPU8[screenPtr + i]; } screenCtx.putImageData(framebuffer, 0, 0); requestAnimationFrame(jsupdate); }
import React from 'react' import _ from 'lodash' import interact from 'interactjs' // onmount items, we interact-ify them. // interact handler updates state in par class DraggableItem extends React.Component { constructor (props) { super(props) this.rootRef = React.createRef() this.dragHandleRef = React.createRef() this.dragContainerRef = React.createRef() } render () { const child = React.Children.only(this.props.children) const { pos } = this.props return React.cloneElement(child, { ref: this.rootRef, dragHandleRef: this.dragHandleRef, dragContainerRef: this.dragContainerRef, style: { position: 'absolute', ...(child.props.style || {}), left: pos.x + 'px', top: pos.y + 'px', }, }) } getDragHandleEl () { return this.dragHandleRef.current || this.rootRef.current } getDragContainerEl () { return this.dragContainerRef.current || this.rootRef.current } componentDidMount () { if (!this.props.afterMount) { return } this.props.afterMount(this) } componentWillUnmount () { if (!this.props.beforeUnmount) { return } try { this.props.beforeUnmount(this) } catch (e) {} } } class DragContainer extends React.Component { constructor (props) { super(props) this.state = { modified: 0, childItemPositions: {} } this.counter = 0 this.containerRef = React.createRef() this.avatarRef = React.createRef() this.childItems = {} this.childPositions = {} } componentDidMount () { this.setupDragMgr() } setupDragMgr() { this._dragMgr = { avatar: { el: this.avatarRef.current, updateStyle: (style) => { _.each(style, (val, key) => { this._dragMgr.avatar.el.style[key] = val }) }, incrementPos: ({x, y}) => { const currentPos = this._dragMgr.avatar.pos const nextPos = {x: currentPos.x + x, y: currentPos.y + y} this._dragMgr.avatar.setPos(nextPos) }, setPos: (pos) => { this._dragMgr.avatar.pos = pos this._dragMgr.avatar.updateStyle({ left: pos.x + 'px', top: pos.y + 'px', }) } }, reset: () => { this._dragMgr = { ...this._dragMgr, avatar: { ...this._dragMgr.avatar, startPos: null, key: null, pos: null, }, before: null, after: null, } this._dragMgr.avatar.updateStyle({visibility: 'hidden'}) } } this._dragMgr.reset() //extra scroll handling per: https://github.com/taye/interact.js/issues/568 interact(this.containerRef.current).on('scroll', () => { if (!(this._dragMgr.avatar.key)) { return } const currentScroll = { x: this.containerRef.current.scrollLeft, y: this.containerRef.current.scrollTop } this._dragMgr.before = this._dragMgr.after || currentScroll this._dragMgr.after = currentScroll this._dragMgr.avatar.incrementPos({ x: (this._dragMgr.after.x - this._dragMgr.before.x), y: (this._dragMgr.after.y - this._dragMgr.before.y), }) }) } render () { return ( <div className='drag-container' ref={this.containerRef} style={Object.assign({}, this.props.style)} > { React.Children.toArray(this.props.children).map((child) => { return this.renderDraggableChild(child) }) } <div key="avatar" ref={this.avatarRef} style={{ position: 'absolute', border: 'thin solid orange' }} /> </div> ) } renderDraggableChild (child) { const key = child.key const pos = this.getChildPos(key) || child.props.pos || {x: 0, y: 0} return ( <DraggableItem key={key} pos={pos} afterMount={(draggableItem) => { this.childItems[key] = draggableItem this.setChildPos({key, pos}) this.dragifyDraggableItem({draggableItem, key}) }} beforeUnmount={() => { interact(this.childItems[key].current).unset() this.deleteChildPos(key) delete this.childItems[key] }} onDragEnd={child && child.props.onDragEnd} > {child} </DraggableItem> ) } dragifyDraggableItem ({draggableItem, key}) { const dragHandleEl = draggableItem.getDragHandleEl() const dragContainerEl = draggableItem.getDragContainerEl() interact(dragHandleEl).draggable({ restrict: false, autoScroll: { container: this.containerRef.current }, onstart: () => { this._dragMgr.avatar.key = key const boundingRect = dragContainerEl.getBoundingClientRect() this._dragMgr.avatar.updateStyle({ visibility: 'visible', width: boundingRect.width + 'px', height: boundingRect.height + 'px', }) const startPos = { x: parseFloat(dragContainerEl.style.left) || 0, y: parseFloat(dragContainerEl.style.top) || 0, } this._dragMgr.avatar.setPos(startPos) this._dragMgr.avatar.startPos = startPos }, onend: () => { const currentPos = this.getChildPos(key) const avatar = this._dragMgr.avatar const nextPos = _.mapValues(currentPos, (curValue, xy) => { const delta = avatar.pos[xy] - avatar.startPos[xy] return curValue + delta }) this.setChildPos({key, pos: nextPos}) this._dragMgr.reset() this.onDragEnd({draggableItem, key, pos: nextPos}) }, onmove: (event) => { this._dragMgr.avatar.incrementPos({x: event.dx, y: event.dy}) } }) } getChildPos (key) { return this.childPositions[key] } setChildPos ({key, pos}) { const changed = (this.childPositions[key] !== pos) if (changed) { this.childPositions[key] = pos this.setState({modified: Date.now()}) } } deleteChildPos (key) { delete this.childPositions[key] } onDragEnd ({draggableItem, key, pos}) { if (draggableItem.props.onDragEnd) { draggableItem.props.onDragEnd({pos}) } if (this.props.onDragEnd) { this.props.onDragEnd({pos}) } } } export default DragContainer
const gulp = require('gulp'); const webpack = require('webpack-stream'); const sourcemaps = require('gulp-sourcemaps'); const sass = require('gulp-sass'); const postcss = require('gulp-postcss'); const autoprefixer = require('autoprefixer'); const cssnano = require('cssnano'); const plumber = require('gulp-plumber'); const browserSync = require('browser-sync'); const webpackConfig = require('./webpack.config'); const src = { js: 'src/js', css: 'src/scss', }; const dist = 'public'; function js() { webpackConfig.mode = 'production'; return gulp.src(`${src.js}/index.js`) .pipe(plumber()) .pipe(webpack(webpackConfig)) .pipe(gulp.dest(`${dist}/js`)) .pipe(browserSync.stream()); } function css() { return gulp.src(`${src.css}/**/main.scss`) .pipe(sourcemaps.init()) .pipe(sass().on('error', sass.logError)) .pipe(postcss([ autoprefixer(), cssnano(), ])) .pipe(sourcemaps.write('./')) .pipe(gulp.dest(`${dist}/css`)) .pipe(browserSync.stream()); } function serve() { browserSync.init({ server: { baseDir: './public', }, }); gulp.watch(`${src.js}/**/*.js`, js); gulp.watch(`${src.css}/**/*.scss`, css); gulp.watch(`${dist}/*.html`).on('change', browserSync.reload); } exports.js = js; exports.css = css; exports.serve = serve; exports.deploy = gulp.parallel(js, css); exports.watch = () => { gulp.watch(`${src.js}/**/*.js`, js); gulp.watch(`${src.css}/**/*.scss`, css); };
import React, { Component } from 'react'; import StartsItem from './StartsItem'; import NavBar from '../NavBar'; import { Link } from 'react-router-dom' class Start extends Component { state = { stateHtml: 0, stateCss: 0, stateJs: 0, stateSum: 0, result: "", } handleChange = (el) => { let html = 0; let css = 0; let js = 0; if (el.target.name == "html") { this.setState({ stateHtml: Number(el.target.value) }); } else if (el.target.name == "css") { this.setState({ stateCss: Number(el.target.value) }); } else { this.setState({ stateJs: Number(el.target.value) }); } this.setState({ stateSum: this.state.stateJs + this.state.stateCss + this.state.stateHtml }); } result = () => { if (this.state.stateSum < 11) { this.setState({ result: "Du bist Anfänger" }); } else if (this.state.stateSum < 20) { this.setState({ result: "Du bist gut aber noch nicht Super" }); } else { this.setState({ result: "Du bist Super" }); } } render() { return ( <main className="startMain" > <section> <StartsItem frage="wie ist deine Kentnisse in Html?" funcRange={this.handleChange} name="html" /> <StartsItem frage="wie ist deine Kentnisse in css?" funcRange={this.handleChange} name="css" /> <StartsItem frage="wie ist deine Kentnisse in JS?" funcRange={this.handleChange} name="js" /> <button onClick={this.result} >Submit</button> <h1>{this.state.result}</h1> </section> </main> ); } } export default Start;
import React from "react"; class Header extends React.Component { render() { return ( <> <div className="header pb-8 pt-5 pt-md-8" style={{background: "linear-gradient(87deg, #70A1D7 0, #C1E7E3 100%)"}}> </div> </> ); } } export default Header;
import React from 'react'; import _ from 'lodash'; import styles from './styles.css'; const USER_IMAGES = ['👨🏻', '👨🏼', '👨🏽', '👨🏽', '👨🏾', '👨🏿', '👩🏻', '👩🏼', '👩🏽', '👩🏾', '👩🏿']; class UserInfo extends React.Component { constructor(props) { super(props); } /* Generate a random but consistent emoji for each user */ getUserImage() { const userName = this.props.user.username; return USER_IMAGES[(userName.charCodeAt(0) - userName.length) % USER_IMAGES.length]; } render() { if (this.props.showError) { return ( <div>We were unable to locate the user you searched for.</div> ); } else if (this.props.user) { const trackList = _.map(this.props.user.tracklist, (track, index) => { return ( <li key={index} className={styles.track}>{track}</li> ); }); const formattedUserName = _.map(this.props.user.username.split('_'), name => _.capitalize(name)).join(' '); return ( [ <h3 className={styles.heading} key='userheader'> Username: {formattedUserName} ({this.props.user.username}) </h3>, <div className={styles.content} key='usercontent'> <div className={styles.details}> <div className={styles.image}> {this.getUserImage()} </div> <div className={styles.metrics}> <div> {this.props.user.plays} plays </div> <div> {this.props.user.tracks} tracks </div> </div> </div> <div className={styles.tracks}> <h3 className={styles.heading}>Tracks</h3> <ul> {trackList} </ul> </div> </div> ] ); } else { return null; } } } export default UserInfo;
import { status } from '../enum'; import { MOVIES } from '../actions/actions'; const initialState = { movies: undefined, moviesLoadStatus: status.SHOULD_CALL_API, }; export default (state = initialState, { type, ...payload }) => { switch (type) { case MOVIES.GET_MOVIES: return { ...state, moviesLoadStatus: status.FETCHING, }; case MOVIES.GET_MOVIES_SUCCESS: return { ...state, movies: payload.payload.response, moviesLoadStatus: status.SUCCESS, }; case MOVIES.GET_MOVIES_FAILED: return { ...state, moviesLoadStatus: status.FAIL, }; default: return state; } };
myApp.directive('header', function() { return { restrict: 'E', templateUrl: 'js/directives/header.html', controller: function($scope, $routeParams) { $scope.currenttopic = $routeParams.topic; } } }); myApp.directive('sideNav', function() { return { restrict: 'E', templateUrl: 'js/directives/sidenav.html', controller: function($http, $scope, $routeParams, $window) { $http.get('json/navigation.json', {cache:true}).success(function(data) { $scope.navitems = data; }); } } }); myApp.directive('banner', function() { return { restrict: 'E', templateUrl: 'js/directives/banner.html' } }); myApp.directive('carousel', function() { return { restrict: 'E', templateUrl: 'js/directives/carousel.html' } }); myApp.directive('resources', function() { return { restrict: 'E', templateUrl: 'js/directives/resources.html' } });
var sql=require('./db'); const Hospital=function(hospital) { this.HospitalName = hospital.HospitalName; this.HospitalPhoneNumber=hospital.HospitalPhoneNumber; }; Hospital.getAllHospital = function(result) { sql.query('Select * from Hospitals', function(err, res) { if (err) { console.log('error: ', err); result(null, err); } else { console.log('hospitals : ', res); result(null, res.recordset); } }); }; Hospital.getHospitalById = function(HospitalId, result) { // eslint-disable-next-line quotes sql.query("Select * from Hospitals where HospitalId ='"+HospitalId+"'", function(err, res) { if (err) { console.log('error: ', err); result(err, null); } else { result(null, res.recordset); } }); }; Hospital.createHospital = function(newHospital, result) { // eslint-disable-next-line quotes sql.query("Insert into Hospitals(HospitalName,HospitalPhoneNumber) values('"+newHospital.HospitalName+"','"+newHospital.HospitalPhoneNumber+"')", function(err, res) { if (err) { console.log('error: ', err); result(err, null); } else { console.log(res.HospitalId); result(null, res.HospitalId); } }); }; Hospital.updateById = function(id, hospital, result) { // eslint-disable-next-line quotes sql.query("Update Hospitals SET HospitalName= '"+hospital.HospitalName+"', HospitalPhoneNumber= '"+hospital.HospitalPhoneNumber+"' where HospitalId='"+id+"'", function(err, res) { if (err) { console.log('error: ', err); result(null, err); } else { result(null, res.recordset); } }); }; Hospital.remove = function(id, result) { // eslint-disable-next-line quotes sql.query("DELETE FROM Hospitals WHERE HospitalId ='"+id+"'", function(err, res) { if (err) { console.log('error: ', err); result(null, err); } else { result(null, res); } }); }; module.exports= Hospital;
import React, { Fragment } from 'react' import { MdTitle, MdFormatListBulleted, MdTextFormat, MdFormatQuote, MdFormatListNumbered, MdCode, } from 'react-icons/md' import basicNode from './basic' const HeadingIcon = ({ level }) => ( <Fragment> <MdTitle /> <span style={{ fontSize: 11, fontWeight: 'bold', lineHeight: 1, marginLeft: -4, verticalAlign: 'text-bottom', }} > {level} </span> </Fragment> ) const p = basicNode({ name: 'paragraph', element: 'p', icon: <MdTextFormat />, }) const h1 = basicNode({ name: 'heading-one', element: 'h1', icon: <HeadingIcon level={1} />, }) const h2 = basicNode({ name: 'heading-two', element: 'h2', icon: <HeadingIcon level={2} />, showIcon: true, }) const h3 = basicNode({ name: 'heading-three', element: 'h3', icon: <HeadingIcon level={3} />, showIcon: true, }) const h4 = basicNode({ name: 'heading-four', element: 'h4', icon: <HeadingIcon level={4} />, }) const h5 = basicNode({ name: 'heading-five', element: 'h5', icon: <HeadingIcon level={5} />, }) const h6 = basicNode({ name: 'heading-six', element: 'h6', icon: <HeadingIcon level={6} />, }) const blockquote = basicNode({ name: 'blockquote', element: 'blockquote', icon: <MdFormatQuote />, }) const ul = basicNode({ name: 'unordered-list', element: 'ul', icon: <MdFormatListBulleted />, showIcon: true, }) const ol = basicNode({ name: 'ordered-list', element: 'ol', icon: <MdFormatListNumbered />, }) const li = basicNode({ name: 'list-item', element: 'li', icon: <MdFormatListBulleted />, }) const pre = basicNode({ name: 'code-block', element: ({ children, ...props }) => ( <pre {...props}> <code>{children}</code> </pre> ), domRecognizer: el => el.tagName.toLowerCase() === 'pre', icon: <MdCode />, }) export default [p, h1, h2, h3, h4, h5, h6, blockquote, ul, ol, li, pre]
export const SET_TAB = 'SET_TAB'; export const SET_SEARCH = 'SET_SEARCH';
const db = require('../dbConfig.js'); const bcrypt = require('bcryptjs'); module.exports = { getUser, getUserByUsername, getUsers, registerUser, availableUsername }; // return all users in database function getUsers() { return db('users') .select('id', 'username'); }; // return user by id function getUser(id) { return db('users') .where({ id: id }) .select('id', 'username');; }; function getUserByUsername(username) { return db('users') .where({ username: username }) .first(); } // registers new user if valid, returns number of rows inserted (id for sql) function registerUser(user) { const newUser = user; const hash = bcrypt.hashSync(newUser.password, 14); newUser.username = newUser.username.toLowerCase(); // username NOT case sensitive newUser.password = hash; return db('users') .insert(newUser) .then(id => { return id }); }; // true if username is not in database function availableUsername(name) { name = name.toLowerCase(); return db('users') .where({ username: name }) .then(result => { if(result.length){ return false; } else { return true; } }); };
export { default } from 'paper-data-table/components/paper-data-table-head';
import React, { useState } from 'react' import { useDispatch } from 'react-redux' import { setAssets } from '../../../reducers/assets' import assetsService from '../../../services/asset' import PropTypes from 'prop-types' import Button from 'react-bootstrap/Button' import withModal from '../../Modal/withModal' import '../forms.css' const CashForm = ({ currentCash, onFormSubmit }) => { const dispatch = useDispatch() const [orderType, setOrderType] = useState('deposit') const [cash, setCash] = useState(0) const [showError, setShowError] = useState(false) const onSubmit = async (event) => { event.preventDefault() let signedCash = cash; if (orderType === "withdraw") { signedCash *= -1 } try { const updatedUserAssets = await assetsService.updateCash(signedCash) dispatch(setAssets(updatedUserAssets)) onFormSubmit() } catch (error) { setShowError(true) setTimeout(() => { setShowError(false) }, 3000) console.log(error) } } const onOrderTypeChange = () => { if (orderType === 'deposit') { setOrderType('withdraw') } else { setOrderType('deposit') } } const onCashChange = (event) => { setCash(event.target.value) } let errorMessage = <div className="error-message-invisible mb-2">Placeholder</div> if (showError) { errorMessage = <div className="error-message mb-2">Insufficient funds</div> } return ( <form onSubmit={onSubmit} className="form-container text-center"> <i className="fas fa-times-circle close-btn" onClick={onFormSubmit}></i> <div className="py-2 text-center"> <i className="fas fa-seedling fa-3x icon"></i> </div> <h2 className="mb-3">Portfolio Cash</h2> <div className="mb-3">Current Balance: ${Number(currentCash).toFixed(2)}</div> <input type="number" step="0.01" min="0" className="cash-input" id="cash" required value={cash} onChange={onCashChange} /> <div className='mt-3 mb-3 radio-container'> <div className="custom-control custom-radio centered-radio"> <input id="buyOrder" name="orderType" type="radio" className="custom-control-input" checked={orderType === 'deposit'} onChange={onOrderTypeChange} required /> <label className="custom-control-label" htmlFor="buyOrder">Deposit</label> </div> <div className="custom-control custom-radio centered-radio"> <input id="sellOrder" name="orderType" type="radio" className="custom-control-input" required checked={orderType === 'withdraw'} onChange={onOrderTypeChange} /> <label className="custom-control-label" htmlFor="sellOrder">Withdraw</label> </div> </div> {errorMessage} <Button type="allocation-button submit">Transact</Button> </form> ) } CashForm.propTypes = { currentCash: PropTypes.number.isRequired, onFormSubmit: PropTypes.func.isRequired } export default withModal(CashForm)
;(function(win, doc) { if (win.console) { console.log = function (str) { doc.getElementById('log').innerHTML += str + '<br>'; } } const each = function* (arr) { console.log('each start!!'); for (const v of arr.slice(0)) { console.log('each: ' + v); yield v; } } const filter = function* (e, f) { console.log('filter start!!'); for (const v of e) { if (f(v)) { console.log('filter: ' + v); yield v; } } } const map = function* (e, f) { console.log('map start!!'); for (const v of e) { console.log('map: ' + v); yield f(v); } } function runTask(taskId) { taskId = taskId.slice(-1) * 1; doc.getElementById('log').innerHTML = ''; if (taskId === 1) { for (const v of each([1,2,3,4])) { console.log(v); } } else if (taskId === 2) { for(const v of filter(each([1,2,3,4]), (v) => v%2 === 0)) { console.log(v); } } else if (taskId === 3) { for (const v of map(filter(each([1,2,3,4]), v => v%2 === 0), v => v * 2)) { console.log(v); } } } const btns = document.getElementsByTagName('button'); [].map.call( btns, (ele) => ele.onclick = (event) => runTask(event.target.id) ); // doc.getElementById('task1').onclick = function() { runTask(1); }; // doc.getElementById('task2').onclick = function() { runTask(2); }; // doc.getElementById('task3').onclick = function() { runTask(3); }; })(window, document);
const ReactDOM = require('react-dom') const ReactTestUtils = require('react-dom/test-utils') const React = require('react') const {PlayForm} = require('../src/PlayForm') describe('PlayForm', () => { let domFixture beforeEach(function () { domFixture = document.createElement('div') document.body.appendChild(domFixture) }) afterEach(function () { domFixture.remove() }) function renderPlayForm(game) { ReactDOM.render( <PlayForm game={game}></PlayForm>, domFixture ) } function play() { domFixture.querySelector('button').click() } function getResultText() { return domFixture.querySelector('.result').innerText } function inputUserThrow(selector, value) { const input = domFixture.querySelector('[name="' + selector + '"]') input.value = value ReactTestUtils.Simulate.change(input) } it('should display invalid when RPS returns invalid', () => { const alwaysInvalidGameStub = { playRound: (t1, t2, roundObserver) => roundObserver.invalid() } renderPlayForm(alwaysInvalidGameStub) expect(getResultText()).not.toBe('Invalid!') play() expect(getResultText()).toBe('Invalid!') }) it('should display tie when RPS returns tie', () => { const alwaysTieGameStub = { playRound: (t1, t2, roundObserver) => roundObserver.tie() } renderPlayForm(alwaysTieGameStub) expect(getResultText()).not.toBe('Tie!') play() expect(getResultText()).toBe('Tie!') }) it('should display p1_wins when RPS returns p1_wins', () => { const alwaysP1WinsGameStub = { playRound: (t1, t2, roundObserver) => roundObserver.p1_wins() } renderPlayForm(alwaysP1WinsGameStub) expect(getResultText()).not.toBe('Player 1 Wins!') play() expect(getResultText()).toBe('Player 1 Wins!') }) it('should display p2_wins when RPS returns p2_wins', () => { const alwaysP2WinsGameStub = { playRound: (t1, t2, roundObserver) => roundObserver.p2_wins() } renderPlayForm(alwaysP2WinsGameStub) expect(getResultText()).not.toBe('Player 2 Wins!') play() expect(getResultText()).toBe('Player 2 Wins!') }) it('should pass user inputs to RPS', function () { const p1_throw = Math.random().toString(); const p2_throw = Math.random().toString(); const gameSpy = jasmine.createSpyObj('game', ['playRound']) renderPlayForm(gameSpy) inputUserThrow('p1_throw', p1_throw) inputUserThrow('p2_throw', p2_throw) play() expect(gameSpy.playRound).toHaveBeenCalledWith(p1_throw, p2_throw, jasmine.any(Object)) }) })
// Dependencies import React, { Component } from 'react' import PropTypes from 'prop-types' import ReactGA from 'react-ga' // App components import ToggleButton from '../ToggleButton/ToggleButton' // Styles import './ListFilters.css' /** * This component parses props in order to update the state object. The filter * options depend on the languages and types presented by the available list * items. * @param {[type]} props [description] * @return {[type]} [description] */ const getState = (props) => { const { results } = props // Get all languages from the results set. const languages = Array.from(new Set(results.map((result) => { if (result.language) { return result.language.toLowerCase() } return null }))).filter(result => result !== null && result !== 'unknown') // Get all types from the results set const types = Array.from(new Set(results.map((result) => { if (result.type) { return result.type.toLowerCase() } return null }))).filter(result => result !== null) // Return the state object return ({ filters: languages.concat(types), languages, types, }) } export default class ListFilters extends Component { constructor(props) { super(props) this.state = getState(props) } componentWillReceiveProps(nextProps) { this.setState(getState(nextProps)) } /** * This function is called when the user toggles any filters. * @param {String} value The filter being toggled. * @param {Boolean} checked The status of the filter, whether ON or OFF * @return {Boolean} Dummy return value */ changeFilter = (value, checked) => { const { filters } = this.state if (!checked && filters.indexOf(value) !== -1) { filters.splice(filters.indexOf(value), 1) } if (checked && filters.indexOf(value) === -1) { filters.push(value) } // Log the event. ReactGA.event({ category: 'Filter', action: 'Change filters', label: `From ${this.state.filters.join(', ')} to ${filters.join(', ')}`, }) this.setState({ filters }, this.props.updateList({ filters, })) return true } renderLanguageFilters() { // If there are not at least 2 languages, don't render anything. if (this.state.languages.length < 2) { return '' } return this.state.languages.map(language => ( <ToggleButton className="u-margin-right--small" handleChange={this.changeFilter} key={language} value={language} /> )) } renderTypeFilters() { // If there are not at least 2 types, don't render anything. if (this.state.types.length < 2) { return '' } return this.state.types.map((type) => { if (type === 'movie' || type === 'tv') { return ( <ToggleButton handleChange={this.changeFilter} key={type} value={type} /> ) } return ( <ToggleButton handleChange={this.changeFilter} key={type} value="TV" /> ) }) } render() { return ( <div className="c-list-filters"> <div className="c-toggle-button-group u-display--flex u-margin-right--small"> {this.renderTypeFilters()} </div> <div className="c-toggle-button-group u-display--flex u-margin-right--small"> {this.renderLanguageFilters()} </div> </div> ) } } /** * Define the types for each property. * @type {Object} */ ListFilters.propTypes = { updateList: PropTypes.func, } /** * Define the default values for each property. * @type {Object} */ ListFilters.defaultProps = { updateList: () => {}, }
const http = require('http') const fs = require('fs') const filePath = './src/db/data.json' const getData = () => { try { return JSON.parse(fs.readFileSync(filePath)) } catch (error) { return [] } } const addData = (todo) => { const data = [] if(getData().length===0) { const newTodo = { id: 1, description: todo.description } data.push(newTodo) } else { oldData = getData() for(let i = 0;i<oldData.length;i++){ data.push(oldData[i]) } const newTodo = { id: oldData[oldData.length-1].id+1, description: todo.description } data.push(newTodo) } fs.writeFileSync(filePath, JSON.stringify(data)); } const deleteTodo = (id) => { const allData = getData() const newData = allData.filter( todo => {return id != todo.id }) fs.writeFileSync(filePath, JSON.stringify(newData)); } const app = ((req, res) => { if(req.url === '/getTodo'){ res.writeHead(200, { 'Content-Type' : 'application/json' }) res.write(JSON.stringify(getData())) res.end() } else if(req.url === '/addTodo') { let allData = '' req.on('data', packet => { allData += packet }) req.on('end', () => { // console.log(JSON.parse(allData)) addData(JSON.parse(allData)) }) } else if(req.url === '/deleteTodo') { let allData = '' req.on('data', packet => { allData += packet }) req.on('end', () => { // console.log(JSON.parse(allData)) deleteTodo(JSON.parse(allData)) }) } else { try { const file = fs.readFileSync('./client/index.html') res.writeHead(200, { 'Content-Type' : 'text/html' }) res.write(file) res.end() } catch (error) { res.writeHead(404) res.write('page not found!') res.end() } } }) const server = http.createServer(app) const PORT = process.env.PORT || 1212 server.listen(PORT, () => { console.log('server on') })
import React, { Component } from 'react'; import { View, Text, TouchableOpacity, Clipboard, StyleSheet, } from 'react-native'; export default class Donate extends Component { constructor(props) { super(props); this.state = { BTC: '1APTUw7u8AjDMfFvqqUypDqSmC4pS5E43R', ETH: '0xc0f7E9129158f2A73d63ee13F171Dd8Afad9cA19', } } click(coin) { if(coin === 'BTC') { Clipboard.setString(this.state.BTC) return alert('Copied!', 'Thank you for your donation') } else if(coin === 'ETH') { Clipboard.setString(this.state.ETH) return alert('Copied!', 'Thank you for your donation') } } render() { return ( <View style={styles.container}> <View> <Text> 더 좋은 인베스코인이 되기 위해 노력하겠습니다. 아래 비트코인과 이더리움 주소를 누르시면 클립보드에 복사됩니다. :)) </Text> </View> <View style={{margin: 20}}> <TouchableOpacity onPress={() => this.click('BTC')}> <Text> BTC : {this.state.BTC} </Text> </TouchableOpacity> <TouchableOpacity onPress={() => this.click('ETH')}> <Text> ETH : {this.state.ETH} </Text> </TouchableOpacity> </View> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'white', }, })
import React from "react"; import { Text, View, Dimensions, BackHandler } from "react-native"; import Store from "../store"; import Cat from "../Cat/Cat"; import styles from "./styles"; const { height } = Dimensions.get("window"); export default class EditProfile extends React.Component { constructor(props) { super(props); this.images = { 1: require("../../assets/img/cat1.png"), 2: require("../../assets/img/cat2.png"), 3: require("../../assets/img/cat3.png"), 4: require("../../assets/img/cat4.png"), 5: require("../../assets/img/cat5.png"), 6: require("../../assets/img/cat6.png"), 7: require("../../assets/img/cat7.png") }; this.state = { socket: this.props.navigation.state.params.socket }; } static navigationOptions = { headerTitle: ( <View style={{ alignItems: "center", flex: 1 }}> <Text style={{ fontFamily: "Goyang", fontSize: 17, color: "white" }}> 프로필 편집 </Text> </View> ), headerRight: <View />, headerStyle: { backgroundColor: "#f4da6c", height: height * 0.07 }, headerTintColor: "#fff", headerTitleStyle: { fontWeight: "bold", fontSize: 17 } }; _handleBackPress = () => { this.props.navigation.navigate("ProfileScreen"); return true; }; componentDidMount() { this.props.navigation.setParams({ navigation: this.props.navigation }); BackHandler.addEventListener("hardwareBackPress", this._handleBackPress); } componentWillUnmount() { BackHandler.removeEventListener("hardwareBackPress", this._handleBackPress); } render() { const upperCats = [1, 2, 3]; const lowerCats = [4, 5, 6]; return ( <View style={styles.body}> <View style={styles.container}> <View style={styles.title}> <Text style={styles.text}>고양이를 바꿀고양?</Text> </View> <View style={styles.catContainer}> <View style={styles.cats}> {upperCats.map(cat => ( <Cat key={cat} id={cat} sendCatInfom={this._sendCatInfom} /> ))} </View> <View style={styles.cats}> {lowerCats.map(cat => ( <Cat key={cat} id={cat} sendCatInfom={this._sendCatInfom} /> ))} </View> <Store.Consumer> {store => { return store.myInfo._enterCount > 40 ? ( <View style={styles.cats}> <Cat key={7} id={7} sendCatInfom={this._sendCatInfom} /> </View> ) : null; }} </Store.Consumer> </View> </View> </View> ); } _sendCatInfom = async (catId, store) => { try { await store.socket.emit("info", catId); await this.props.navigation.navigate("OpenBoxScreen"); } catch (err) { console.log(err); } }; }
import React, { Component } from 'react'; import { NavLink } from 'react-router-dom'; class EDashboard extends Component { handleButtonClick() { console.log(this.props, 'props') this.props.handleLoggedInStatus(false) // console.log( 'child working', handleLoggedInStatus ) // this.props.handleLoggedInStatus(false) } render() { return ( <div> <div className="nav"> <ul className="navLinks"> <NavLink exact to="/Employee/home" className="navLink"><li>Home</li></NavLink> <NavLink to="/Employee/edit" className="navLink"><li>Edit Profile</li></NavLink> <NavLink to="/Employee/about-us" className="navLink"><li>About us</li></NavLink> <li><button className="primary" onClick={this.handleButtonClick.bind(this)}>Logout</button></li> </ul> </div> <div className="employeeData"> <div className="employeeData1"> <p> <b className="boldd">Employee_id:</b><span>{this.props.profileData.employee_id}</span></p> <p> <b className="boldd">Name:</b><span>{this.props.profileData.name}</span></p> <p> <b className="boldd">UserName:</b><span>{this.props.profileData.username}</span></p> <p> <b className="boldd">Gender:</b><span>{this.props.profileData.gender}</span></p> <p> <b className="boldd">Email:</b><span>{this.props.profileData.email}</span></p> </div> <div className="employeeData2"> <p> <b className="boldd">Date of Birth:</b><span>{this.props.profileData.dob}</span></p> <p><b className="boldd">Salary:</b> <span>{this.props.profileData.salary} Dollars</span></p> <p> <b className="boldd">Company:</b><span>{this.props.profileData.company}</span></p> <p><b className="boldd">Password:</b> <span>{this.props.profileData.password}</span></p> </div> </div> </div> ); } } // EDashboard.propTypes = { // profileData: PropTypes.array.isRequired // } // function mapStateToProps(state) { // return { // profileData: state.profileData // } // } export default EDashboard
var largeurFrame, largerEcran, millieuFrame, millieuEcran, xZero; // Déclaration du tableau function TOF_Calk(iLeftX, iRightX, iHeight, sNom, sImgName, sImgRestore){ this.iLeftX = iLeftX; this.iRightX = iRightX; this.iHeight = iHeight; this.sNom = sNom; this.sImgName = sImgName; this.sImgRestore = sImgRestore; } Tb_Calk = new Array(); //Tb_Calk[Indice du tableau] = new TOF_Calk(iLeftX, iRightX, sNom, bEtat); // iLeftX : Position gauche du calque par rapport au bord gauche de la page // iRightX : iLeft + la largeur du calque // iHeight : Hauteur du calque // sNom : nom du calque Tb_Calk[0] = new TOF_Calk(870,950,380, 'divContainerPubli', 'publi', '/img/fo/gabarits/hp/publications.gif'); if (document.all) {n=0;ie=1;n6=0;} if (document.layers) {n=1;ie=0;n6=0;} if(!document.all && document.getElementById) {n=0;ie=0;n6=1}; function updateIt(e){ if (ie){ var x = window.event.clientX; var y = window.event.clientY; TOF_HideAll(x,y); } if (n){ var x = e.pageX; var y = e.pageY; TOF_HideAll(x,y) } if (n6){ var x = e.pageX; var y = e.pageY; TOF_HideAll(x,y) } //alert("x : " + x + " y : " + y + " x-xZero : " + (x-xZero)) } function TOF_HideAll(x,y){ for(ii=0;ii<=(Tb_Calk.length-1);ii++){ objSel = document.getElementById(Tb_Calk[ii].sNom); objImg = document.getElementById(Tb_Calk[ii].sImgName); if ((x-xZero) > Tb_Calk[ii].iRightX || (x-xZero) < Tb_Calk[ii].iLeftX || y > (Tb_Calk[ii].iHeight) || y < 246){ objSel.style.setAttribute("visibility","hidden"); objImg.src = Tb_Calk[ii].sImgRestore; } } } function TOF_Hide(){ for(ii=0;ii<=(Tb_Calk.length-1);ii++){ objSel = document.getElementById(Tb_Calk[ii].sNom); objSel.style.setAttribute("visibility","hidden"); } } function TOF_Show(sCalk){ objSel = document.getElementById(sCalk); objSel.style.setAttribute("visibility","visible"); } function ChangeData(){ largeurEcran = document.body.clientWidth; millieuFrame = largeurFrame/2; millieuEcran = largeurEcran/2; xZero = millieuEcran - millieuFrame; } function f_InitBody(){ largeurFrame = 949; largeurEcran = document.body.clientWidth; millieuFrame = largeurFrame/2; millieuEcran = largeurEcran/2; xZero = millieuEcran - millieuFrame; if (document.all){ document.body.onClick=TOF_Hide(); document.body.onScroll=TOF_Hide(); document.body.onmousemove=updateIt; document.body.onresize=ChangeData; } if (document.layers){ document.onmousedown=TOF_Hide(); window.captureEvents(Event.MOUSEMOVE); window.onmousemove=updateIt; window.onresize=ChangeData; } if(!document.all && document.getElementById){ document.onmousedown=TOF_Hide(); window.captureEvents(Event.MOUSEMOVE); window.onmousemove=updateIt; window.onresize=ChangeData; } }
"use strict"; const seats = Array.from(document.querySelectorAll(".movie-container .seat")); const container = document.querySelector(".movie-container"); const seatCountField = document.getElementById("count"); const totalPriceField = document.getElementById("total"); const movieSelect = document.getElementById("movie-select"); //Load all data loadData(); //Save selected seats to LocalStorage function saveSeatsIndexIntoLS() { const selectedSeats = Array.from(document.querySelectorAll(".movie-container .seat.selected")); const selectedSeatsIndex = selectedSeats.map((seat) => { return seats.indexOf(seat); }); localStorage.setItem("selectedSeats", JSON.stringify(selectedSeatsIndex)); } //Load selected seats from LocalStorage function loadSeatsFromLS() { const selectedSeatsFromLC = localStorage.getItem("selectedSeats"); let selectedSeats; if (selectedSeatsFromLC === null) return; try { selectedSeats = JSON.parse(selectedSeatsFromLC); } catch (_a) { selectedSeats = []; } if (Array.isArray(selectedSeats)) { seats.forEach((seat, index) => { if (selectedSeats.indexOf(index) > -1) { seat.classList.add("selected"); } }); } } //Show total count and price function totalCountAndPrice() { const selectedSeats = Array.from(document.querySelectorAll(".movie-container .seat.selected")); const price = Number(movieSelect.value); const seatsCount = selectedSeats.length; const totalPrice = seatsCount * price; seatCountField.innerText = seatsCount.toString(); totalPriceField.innerText = totalPrice.toString(); } //Load all data from LocalStorage function loadData() { loadSeatsFromLS(); const selectedMovie = Number(localStorage.getItem("selectedMovie")); if (selectedMovie !== NaN) { movieSelect.selectedIndex = selectedMovie; totalCountAndPrice(); } } container.addEventListener("click", (e) => { if (e.target instanceof HTMLDivElement) { if (e.target.classList.contains("seat") && !e.target.classList.contains("occupied")) { e.target.classList.toggle("selected"); saveSeatsIndexIntoLS(); totalCountAndPrice(); } } }); movieSelect.addEventListener("change", () => { totalCountAndPrice(); localStorage.setItem("selectedMovie", movieSelect.selectedIndex.toString()); });
!function (e, t) { var n = function (e) { var t = {}; function n(o) { if (t[o]) return t[o].exports; var r = t[o] = {i: o, l: !1, exports: {}}; return e[o].call(r.exports, r, r.exports, n), r.l = !0, r.exports } return n.m = e, n.c = t, n.d = function (e, t, o) { n.o(e, t) || Object.defineProperty(e, t, {configurable: !1, enumerable: !0, get: o}) }, n.r = function (e) { Object.defineProperty(e, "__esModule", {value: !0}) }, n.n = function (e) { var t = e && e.__esModule ? function () { return e.default } : function () { return e }; return n.d(t, "a", t), t }, n.o = function (e, t) { return Object.prototype.hasOwnProperty.call(e, t) }, n.p = "", n(n.s = 220) }({ 2: function (e, t) { var n; n = function () { return this }(); try { n = n || Function("return this")() || (0, eval)("this") } catch (e) { "object" == typeof window && (n = window) } e.exports = n }, 219: function (e, t, n) { "use strict"; (function (e) { Object.defineProperty(t, "__esModule", {value: !0}); var n = function () { function e(e, t) { for (var n = 0; n < t.length; n++) { var o = t[n]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, o.key, o) } } return function (t, n, o) { return n && e(t.prototype, n), o && e(t, o), t } }(); function o(e, t, n) { return t in e ? Object.defineProperty(e, t, { value: n, enumerable: !0, configurable: !0, writable: !0 }) : e[t] = n, e } /**! * @fileOverview Kickass library to create and place poppers near their reference elements. * @version 1.14.0 * @license * Copyright (c) 2016 Federico Zivolo and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ for (var r = "undefined" != typeof window && "undefined" != typeof document, i = ["Edge", "Trident", "Firefox"], a = 0, s = 0; s < i.length; s += 1) if (r && navigator.userAgent.indexOf(i[s]) >= 0) { a = 1; break } var f = r && window.Promise, p = f ? function (e) { var t = !1; return function () { t || (t = !0, window.Promise.resolve().then(function () { t = !1, e() })) } } : function (e) { var t = !1; return function () { t || (t = !0, setTimeout(function () { t = !1, e() }, a)) } }; function l(e) { return e && "[object Function]" === {}.toString.call(e) } function u(e, t) { if (1 !== e.nodeType) return []; var n = getComputedStyle(e, null); return t ? n[t] : n } function c(e) { return "HTML" === e.nodeName ? e : e.parentNode || e.host } function d(e) { if (!e) return document.body; switch (e.nodeName) { case"HTML": case"BODY": return e.ownerDocument.body; case"#document": return e.body } var t = u(e), n = t.overflow, o = t.overflowX, r = t.overflowY; return /(auto|scroll|overlay)/.test(n + r + o) ? e : d(c(e)) } var h = {}, m = function () { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : "all"; if (e = e.toString(), h.hasOwnProperty(e)) return h[e]; switch (e) { case"11": h[e] = -1 !== navigator.userAgent.indexOf("Trident"); break; case"10": h[e] = -1 !== navigator.appVersion.indexOf("MSIE 10"); break; case"all": h[e] = -1 !== navigator.userAgent.indexOf("Trident") || -1 !== navigator.userAgent.indexOf("MSIE") } return h.all = h.all || Object.keys(h).some(function (e) { return h[e] }), h[e] }; function v(e) { if (!e) return document.documentElement; for (var t = m(10) ? document.body : null, n = e.offsetParent; n === t && e.nextElementSibling;) n = (e = e.nextElementSibling).offsetParent; var o = n && n.nodeName; return o && "BODY" !== o && "HTML" !== o ? -1 !== ["TD", "TABLE"].indexOf(n.nodeName) && "static" === u(n, "position") ? v(n) : n : e ? e.ownerDocument.documentElement : document.documentElement } function g(e) { return null !== e.parentNode ? g(e.parentNode) : e } function b(e, t) { if (!(e && e.nodeType && t && t.nodeType)) return document.documentElement; var n = e.compareDocumentPosition(t) & Node.DOCUMENT_POSITION_FOLLOWING, o = n ? e : t, r = n ? t : e, i = document.createRange(); i.setStart(o, 0), i.setEnd(r, 0); var a, s, f = i.commonAncestorContainer; if (e !== f && t !== f || o.contains(r)) return "BODY" === (s = (a = f).nodeName) || "HTML" !== s && v(a.firstElementChild) !== a ? v(f) : f; var p = g(e); return p.host ? b(p.host, t) : b(e, g(t).host) } function w(e) { var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : "top", n = "top" === t ? "scrollTop" : "scrollLeft", o = e.nodeName; if ("BODY" === o || "HTML" === o) { var r = e.ownerDocument.documentElement, i = e.ownerDocument.scrollingElement || r; return i[n] } return e[n] } function y(e, t) { var n = "x" === t ? "Left" : "Top", o = "Left" === n ? "Right" : "Bottom"; return parseFloat(e["border" + n + "Width"], 10) + parseFloat(e["border" + o + "Width"], 10) } function x(e, t, n, o) { return Math.max(t["offset" + e], t["scroll" + e], n["client" + e], n["offset" + e], n["scroll" + e], m(10) ? n["offset" + e] + o["margin" + ("Height" === e ? "Top" : "Left")] + o["margin" + ("Height" === e ? "Bottom" : "Right")] : 0) } function E() { var e = document.body, t = document.documentElement, n = m(10) && getComputedStyle(t); return {height: x("Height", e, t, n), width: x("Width", e, t, n)} } var O = Object.assign || function (e) { for (var t = 1; t < arguments.length; t++) { var n = arguments[t]; for (var o in n) Object.prototype.hasOwnProperty.call(n, o) && (e[o] = n[o]) } return e }; function L(e) { return O({}, e, {right: e.left + e.width, bottom: e.top + e.height}) } function M(e) { var t = {}; try { if (m(10)) { t = e.getBoundingClientRect(); var n = w(e, "top"), o = w(e, "left"); t.top += n, t.left += o, t.bottom += n, t.right += o } else t = e.getBoundingClientRect() } catch (e) { } var r = {left: t.left, top: t.top, width: t.right - t.left, height: t.bottom - t.top}, i = "HTML" === e.nodeName ? E() : {}, a = i.width || e.clientWidth || r.right - r.left, s = i.height || e.clientHeight || r.bottom - r.top, f = e.offsetWidth - a, p = e.offsetHeight - s; if (f || p) { var l = u(e); f -= y(l, "x"), p -= y(l, "y"), r.width -= f, r.height -= p } return L(r) } function T(e, t) { var n = arguments.length > 2 && void 0 !== arguments[2] && arguments[2], o = m(10), r = "HTML" === t.nodeName, i = M(e), a = M(t), s = d(e), f = u(t), p = parseFloat(f.borderTopWidth, 10), l = parseFloat(f.borderLeftWidth, 10); n && "HTML" === t.nodeName && (a.top = Math.max(a.top, 0), a.left = Math.max(a.left, 0)); var c = L({top: i.top - a.top - p, left: i.left - a.left - l, width: i.width, height: i.height}); if (c.marginTop = 0, c.marginLeft = 0, !o && r) { var h = parseFloat(f.marginTop, 10), v = parseFloat(f.marginLeft, 10); c.top -= p - h, c.bottom -= p - h, c.left -= l - v, c.right -= l - v, c.marginTop = h, c.marginLeft = v } return (o && !n ? t.contains(s) : t === s && "BODY" !== s.nodeName) && (c = function (e, t) { var n = arguments.length > 2 && void 0 !== arguments[2] && arguments[2], o = w(t, "top"), r = w(t, "left"), i = n ? -1 : 1; return e.top += o * i, e.bottom += o * i, e.left += r * i, e.right += r * i, e }(c, t)), c } function F(e) { if (!e || !e.parentElement || m()) return document.documentElement; for (var t = e.parentElement; t && "none" === u(t, "transform");) t = t.parentElement; return t || document.documentElement } function N(e, t, n, o) { var r = arguments.length > 4 && void 0 !== arguments[4] && arguments[4], i = {top: 0, left: 0}, a = r ? F(e) : b(e, t); if ("viewport" === o) i = function (e) { var t = arguments.length > 1 && void 0 !== arguments[1] && arguments[1], n = e.ownerDocument.documentElement, o = T(e, n), r = Math.max(n.clientWidth, window.innerWidth || 0), i = Math.max(n.clientHeight, window.innerHeight || 0), a = t ? 0 : w(n), s = t ? 0 : w(n, "left"); return L({top: a - o.top + o.marginTop, left: s - o.left + o.marginLeft, width: r, height: i}) }(a, r); else { var s = void 0; "scrollParent" === o ? "BODY" === (s = d(c(t))).nodeName && (s = e.ownerDocument.documentElement) : s = "window" === o ? e.ownerDocument.documentElement : o; var f = T(s, a, r); if ("HTML" !== s.nodeName || function e(t) { var n = t.nodeName; return "BODY" !== n && "HTML" !== n && ("fixed" === u(t, "position") || e(c(t))) }(a)) i = f; else { var p = E(), l = p.height, h = p.width; i.top += f.top - f.marginTop, i.bottom = l + f.top, i.left += f.left - f.marginLeft, i.right = h + f.left } } return i.left += n, i.top += n, i.right -= n, i.bottom -= n, i } function C(e, t, n, o, r) { var i = arguments.length > 5 && void 0 !== arguments[5] ? arguments[5] : 0; if (-1 === e.indexOf("auto")) return e; var a = N(n, o, i, r), s = { top: {width: a.width, height: t.top - a.top}, right: {width: a.right - t.right, height: a.height}, bottom: {width: a.width, height: a.bottom - t.bottom}, left: {width: t.left - a.left, height: a.height} }, f = Object.keys(s).map(function (e) { return O({key: e}, s[e], {area: (t = s[e], n = t.width, o = t.height, n * o)}); var t, n, o }).sort(function (e, t) { return t.area - e.area }), p = f.filter(function (e) { var t = e.width, o = e.height; return t >= n.clientWidth && o >= n.clientHeight }), l = p.length > 0 ? p[0].key : f[0].key, u = e.split("-")[1]; return l + (u ? "-" + u : "") } function D(e, t, n) { var o = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : null, r = o ? F(t) : b(t, n); return T(n, r, o) } function P(e) { var t = getComputedStyle(e), n = parseFloat(t.marginTop) + parseFloat(t.marginBottom), o = parseFloat(t.marginLeft) + parseFloat(t.marginRight), r = {width: e.offsetWidth + o, height: e.offsetHeight + n}; return r } function k(e) { var t = {left: "right", right: "left", bottom: "top", top: "bottom"}; return e.replace(/left|right|bottom|top/g, function (e) { return t[e] }) } function S(e, t, n) { n = n.split("-")[0]; var o = P(e), r = {width: o.width, height: o.height}, i = -1 !== ["right", "left"].indexOf(n), a = i ? "top" : "left", s = i ? "left" : "top", f = i ? "height" : "width", p = i ? "width" : "height"; return r[a] = t[a] + t[f] / 2 - o[f] / 2, r[s] = n === s ? t[s] - o[p] : t[k(s)], r } function j(e, t) { return Array.prototype.find ? e.find(t) : e.filter(t)[0] } function W(e, t, n) { var o = void 0 === n ? e : e.slice(0, function (e, t, n) { if (Array.prototype.findIndex) return e.findIndex(function (e) { return e[t] === n }); var o = j(e, function (e) { return e[t] === n }); return e.indexOf(o) }(e, "name", n)); return o.forEach(function (e) { e.function && console.warn("`modifier.function` is deprecated, use `modifier.fn`!"); var n = e.function || e.fn; e.enabled && l(n) && (t.offsets.popper = L(t.offsets.popper), t.offsets.reference = L(t.offsets.reference), t = n(t, e)) }), t } function A(e, t) { return e.some(function (e) { var n = e.name, o = e.enabled; return o && n === t }) } function H(e) { for (var t = [!1, "ms", "Webkit", "Moz", "O"], n = e.charAt(0).toUpperCase() + e.slice(1), o = 0; o < t.length; o++) { var r = t[o], i = r ? "" + r + n : e; if (void 0 !== document.body.style[i]) return i } return null } function B(e) { var t = e.ownerDocument; return t ? t.defaultView : window } function I(e, t, n, o) { n.updateBound = o, B(e).addEventListener("resize", n.updateBound, {passive: !0}); var r = d(e); return function e(t, n, o, r) { var i = "BODY" === t.nodeName, a = i ? t.ownerDocument.defaultView : t; a.addEventListener(n, o, {passive: !0}), i || e(d(a.parentNode), n, o, r), r.push(a) }(r, "scroll", n.updateBound, n.scrollParents), n.scrollElement = r, n.eventsEnabled = !0, n } function _() { var e, t; this.state.eventsEnabled && (cancelAnimationFrame(this.scheduleUpdate), this.state = (e = this.reference, t = this.state, B(e).removeEventListener("resize", t.updateBound), t.scrollParents.forEach(function (e) { e.removeEventListener("scroll", t.updateBound) }), t.updateBound = null, t.scrollParents = [], t.scrollElement = null, t.eventsEnabled = !1, t)) } function R(e) { return "" !== e && !isNaN(parseFloat(e)) && isFinite(e) } function U(e, t) { Object.keys(t).forEach(function (n) { var o = ""; -1 !== ["width", "height", "top", "right", "bottom", "left"].indexOf(n) && R(t[n]) && (o = "px"), e.style[n] = t[n] + o }) } function Y(e, t, n) { var o = j(e, function (e) { var n = e.name; return n === t }), r = !!o && e.some(function (e) { return e.name === n && e.enabled && e.order < o.order }); if (!r) { var i = "`" + t + "`", a = "`" + n + "`"; console.warn(a + " modifier is required by " + i + " modifier in order to work, be sure to include it before " + i + "!") } return r } var q = ["auto-start", "auto", "auto-end", "top-start", "top", "top-end", "right-start", "right", "right-end", "bottom-end", "bottom", "bottom-start", "left-end", "left", "left-start"], K = q.slice(3); function V(e) { var t = arguments.length > 1 && void 0 !== arguments[1] && arguments[1], n = K.indexOf(e), o = K.slice(n + 1).concat(K.slice(0, n)); return t ? o.reverse() : o } var z = {FLIP: "flip", CLOCKWISE: "clockwise", COUNTERCLOCKWISE: "counterclockwise"}; function G(e, t, n, o) { var r = [0, 0], i = -1 !== ["right", "left"].indexOf(o), a = e.split(/(\+|\-)/).map(function (e) { return e.trim() }), s = a.indexOf(j(a, function (e) { return -1 !== e.search(/,|\s/) })); a[s] && -1 === a[s].indexOf(",") && console.warn("Offsets separated by white space(s) are deprecated, use a comma (,) instead."); var f = /\s*,\s*|\s+/, p = -1 !== s ? [a.slice(0, s).concat([a[s].split(f)[0]]), [a[s].split(f)[1]].concat(a.slice(s + 1))] : [a]; return (p = p.map(function (e, o) { var r = (1 === o ? !i : i) ? "height" : "width", a = !1; return e.reduce(function (e, t) { return "" === e[e.length - 1] && -1 !== ["+", "-"].indexOf(t) ? (e[e.length - 1] = t, a = !0, e) : a ? (e[e.length - 1] += t, a = !1, e) : e.concat(t) }, []).map(function (e) { return function (e, t, n, o) { var r = e.match(/((?:\-|\+)?\d*\.?\d*)(.*)/), i = +r[1], a = r[2]; if (!i) return e; if (0 === a.indexOf("%")) { var s = void 0; switch (a) { case"%p": s = n; break; case"%": case"%r": default: s = o } var f = L(s); return f[t] / 100 * i } return "vh" === a || "vw" === a ? ("vh" === a ? Math.max(document.documentElement.clientHeight, window.innerHeight || 0) : Math.max(document.documentElement.clientWidth, window.innerWidth || 0)) / 100 * i : i }(e, r, t, n) }) })).forEach(function (e, t) { e.forEach(function (n, o) { R(n) && (r[t] += n * ("-" === e[o - 1] ? -1 : 1)) }) }), r } var X = { shift: { order: 100, enabled: !0, fn: function (e) { var t = e.placement, n = t.split("-")[0], r = t.split("-")[1]; if (r) { var i = e.offsets, a = i.reference, s = i.popper, f = -1 !== ["bottom", "top"].indexOf(n), p = f ? "left" : "top", l = f ? "width" : "height", u = {start: o({}, p, a[p]), end: o({}, p, a[p] + a[l] - s[l])}; e.offsets.popper = O({}, s, u[r]) } return e } }, offset: { order: 200, enabled: !0, fn: function (e, t) { var n = t.offset, o = e.placement, r = e.offsets, i = r.popper, a = r.reference, s = o.split("-")[0], f = void 0; return f = R(+n) ? [+n, 0] : G(n, i, a, s), "left" === s ? (i.top += f[0], i.left -= f[1]) : "right" === s ? (i.top += f[0], i.left += f[1]) : "top" === s ? (i.left += f[0], i.top -= f[1]) : "bottom" === s && (i.left += f[0], i.top += f[1]), e.popper = i, e }, offset: 0 }, preventOverflow: { order: 300, enabled: !0, fn: function (e, t) { var n = t.boundariesElement || v(e.instance.popper); e.instance.reference === n && (n = v(n)); var r = N(e.instance.popper, e.instance.reference, t.padding, n, e.positionFixed); t.boundaries = r; var i = t.priority, a = e.offsets.popper, s = { primary: function (e) { var n = a[e]; return a[e] < r[e] && !t.escapeWithReference && (n = Math.max(a[e], r[e])), o({}, e, n) }, secondary: function (e) { var n = "right" === e ? "left" : "top", i = a[n]; return a[e] > r[e] && !t.escapeWithReference && (i = Math.min(a[n], r[e] - ("right" === e ? a.width : a.height))), o({}, n, i) } }; return i.forEach(function (e) { var t = -1 !== ["left", "top"].indexOf(e) ? "primary" : "secondary"; a = O({}, a, s[t](e)) }), e.offsets.popper = a, e }, priority: ["left", "right", "top", "bottom"], padding: 5, boundariesElement: "scrollParent" }, keepTogether: { order: 400, enabled: !0, fn: function (e) { var t = e.offsets, n = t.popper, o = t.reference, r = e.placement.split("-")[0], i = Math.floor, a = -1 !== ["top", "bottom"].indexOf(r), s = a ? "right" : "bottom", f = a ? "left" : "top", p = a ? "width" : "height"; return n[s] < i(o[f]) && (e.offsets.popper[f] = i(o[f]) - n[p]), n[f] > i(o[s]) && (e.offsets.popper[f] = i(o[s])), e } }, arrow: { order: 500, enabled: !0, fn: function (e, t) { var n; if (!Y(e.instance.modifiers, "arrow", "keepTogether")) return e; var r = t.element; if ("string" == typeof r) { if (!(r = e.instance.popper.querySelector(r))) return e } else if (!e.instance.popper.contains(r)) return console.warn("WARNING: `arrow.element` must be child of its popper element!"), e; var i = e.placement.split("-")[0], a = e.offsets, s = a.popper, f = a.reference, p = -1 !== ["left", "right"].indexOf(i), l = p ? "height" : "width", c = p ? "Top" : "Left", d = c.toLowerCase(), h = p ? "left" : "top", m = p ? "bottom" : "right", v = P(r)[l]; f[m] - v < s[d] && (e.offsets.popper[d] -= s[d] - (f[m] - v)), f[d] + v > s[m] && (e.offsets.popper[d] += f[d] + v - s[m]), e.offsets.popper = L(e.offsets.popper); var g = f[d] + f[l] / 2 - v / 2, b = u(e.instance.popper), w = parseFloat(b["margin" + c], 10), y = parseFloat(b["border" + c + "Width"], 10), x = g - e.offsets.popper[d] - w - y; return x = Math.max(Math.min(s[l] - v, x), 0), e.arrowElement = r, e.offsets.arrow = (o(n = {}, d, Math.round(x)), o(n, h, ""), n), e }, element: "[x-arrow]" }, flip: { order: 600, enabled: !0, fn: function (e, t) { if (A(e.instance.modifiers, "inner")) return e; if (e.flipped && e.placement === e.originalPlacement) return e; var n = N(e.instance.popper, e.instance.reference, t.padding, t.boundariesElement, e.positionFixed), o = e.placement.split("-")[0], r = k(o), i = e.placement.split("-")[1] || "", a = []; switch (t.behavior) { case z.FLIP: a = [o, r]; break; case z.CLOCKWISE: a = V(o); break; case z.COUNTERCLOCKWISE: a = V(o, !0); break; default: a = t.behavior } return a.forEach(function (s, f) { if (o !== s || a.length === f + 1) return e; o = e.placement.split("-")[0], r = k(o); var p = e.offsets.popper, l = e.offsets.reference, u = Math.floor, c = "left" === o && u(p.right) > u(l.left) || "right" === o && u(p.left) < u(l.right) || "top" === o && u(p.bottom) > u(l.top) || "bottom" === o && u(p.top) < u(l.bottom), d = u(p.left) < u(n.left), h = u(p.right) > u(n.right), m = u(p.top) < u(n.top), v = u(p.bottom) > u(n.bottom), g = "left" === o && d || "right" === o && h || "top" === o && m || "bottom" === o && v, b = -1 !== ["top", "bottom"].indexOf(o), w = !!t.flipVariations && (b && "start" === i && d || b && "end" === i && h || !b && "start" === i && m || !b && "end" === i && v); (c || g || w) && (e.flipped = !0, (c || g) && (o = a[f + 1]), w && (i = function (e) { return "end" === e ? "start" : "start" === e ? "end" : e }(i)), e.placement = o + (i ? "-" + i : ""), e.offsets.popper = O({}, e.offsets.popper, S(e.instance.popper, e.offsets.reference, e.placement)), e = W(e.instance.modifiers, e, "flip")) }), e }, behavior: "flip", padding: 5, boundariesElement: "viewport" }, inner: { order: 700, enabled: !1, fn: function (e) { var t = e.placement, n = t.split("-")[0], o = e.offsets, r = o.popper, i = o.reference, a = -1 !== ["left", "right"].indexOf(n), s = -1 === ["top", "left"].indexOf(n); return r[a ? "left" : "top"] = i[n] - (s ? r[a ? "width" : "height"] : 0), e.placement = k(t), e.offsets.popper = L(r), e } }, hide: { order: 800, enabled: !0, fn: function (e) { if (!Y(e.instance.modifiers, "hide", "preventOverflow")) return e; var t = e.offsets.reference, n = j(e.instance.modifiers, function (e) { return "preventOverflow" === e.name }).boundaries; if (t.bottom < n.top || t.left > n.right || t.top > n.bottom || t.right < n.left) { if (!0 === e.hide) return e; e.hide = !0, e.attributes["x-out-of-boundaries"] = "" } else { if (!1 === e.hide) return e; e.hide = !1, e.attributes["x-out-of-boundaries"] = !1 } return e } }, computeStyle: { order: 850, enabled: !0, fn: function (e, t) { var n = t.x, o = t.y, r = e.offsets.popper, i = j(e.instance.modifiers, function (e) { return "applyStyle" === e.name }).gpuAcceleration; void 0 !== i && console.warn("WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!"); var a = void 0 !== i ? i : t.gpuAcceleration, s = M(v(e.instance.popper)), f = {position: r.position}, p = { left: Math.floor(r.left), top: Math.floor(r.top), bottom: Math.floor(r.bottom), right: Math.floor(r.right) }, l = "bottom" === n ? "top" : "bottom", u = "right" === o ? "left" : "right", c = H("transform"), d = void 0, h = void 0; if (h = "bottom" === l ? -s.height + p.bottom : p.top, d = "right" === u ? -s.width + p.right : p.left, a && c) f[c] = "translate3d(" + d + "px, " + h + "px, 0)", f[l] = 0, f[u] = 0, f.willChange = "transform"; else { var m = "bottom" === l ? -1 : 1, g = "right" === u ? -1 : 1; f[l] = h * m, f[u] = d * g, f.willChange = l + ", " + u } var b = {"x-placement": e.placement}; return e.attributes = O({}, b, e.attributes), e.styles = O({}, f, e.styles), e.arrowStyles = O({}, e.offsets.arrow, e.arrowStyles), e }, gpuAcceleration: !0, x: "bottom", y: "right" }, applyStyle: { order: 900, enabled: !0, fn: function (e) { var t, n; return U(e.instance.popper, e.styles), t = e.instance.popper, n = e.attributes, Object.keys(n).forEach(function (e) { var o = n[e]; !1 !== o ? t.setAttribute(e, n[e]) : t.removeAttribute(e) }), e.arrowElement && Object.keys(e.arrowStyles).length && U(e.arrowElement, e.arrowStyles), e }, onLoad: function (e, t, n, o, r) { var i = D(r, t, e, n.positionFixed), a = C(n.placement, i, t, e, n.modifiers.flip.boundariesElement, n.modifiers.flip.padding); return t.setAttribute("x-placement", a), U(t, {position: n.positionFixed ? "fixed" : "absolute"}), n }, gpuAcceleration: void 0 } }, J = { placement: "bottom", positionFixed: !1, eventsEnabled: !0, removeOnDestroy: !1, onCreate: function () { }, onUpdate: function () { }, modifiers: X }, Q = function () { function e(t, n) { var o = this, r = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}; !function (e, t) { if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function") }(this, e), this.scheduleUpdate = function () { return requestAnimationFrame(o.update) }, this.update = p(this.update.bind(this)), this.options = O({}, e.Defaults, r), this.state = { isDestroyed: !1, isCreated: !1, scrollParents: [] }, this.reference = t && t.jquery ? t[0] : t, this.popper = n && n.jquery ? n[0] : n, this.options.modifiers = {}, Object.keys(O({}, e.Defaults.modifiers, r.modifiers)).forEach(function (t) { o.options.modifiers[t] = O({}, e.Defaults.modifiers[t] || {}, r.modifiers ? r.modifiers[t] : {}) }), this.modifiers = Object.keys(this.options.modifiers).map(function (e) { return O({name: e}, o.options.modifiers[e]) }).sort(function (e, t) { return e.order - t.order }), this.modifiers.forEach(function (e) { e.enabled && l(e.onLoad) && e.onLoad(o.reference, o.popper, o.options, e, o.state) }), this.update(); var i = this.options.eventsEnabled; i && this.enableEventListeners(), this.state.eventsEnabled = i } return n(e, [{ key: "update", value: function () { return function () { if (!this.state.isDestroyed) { var e = { instance: this, styles: {}, arrowStyles: {}, attributes: {}, flipped: !1, offsets: {} }; e.offsets.reference = D(this.state, this.popper, this.reference, this.options.positionFixed), e.placement = C(this.options.placement, e.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding), e.originalPlacement = e.placement, e.positionFixed = this.options.positionFixed, e.offsets.popper = S(this.popper, e.offsets.reference, e.placement), e.offsets.popper.position = this.options.positionFixed ? "fixed" : "absolute", e = W(this.modifiers, e), this.state.isCreated ? this.options.onUpdate(e) : (this.state.isCreated = !0, this.options.onCreate(e)) } }.call(this) } }, { key: "destroy", value: function () { return function () { return this.state.isDestroyed = !0, A(this.modifiers, "applyStyle") && (this.popper.removeAttribute("x-placement"), this.popper.style.position = "", this.popper.style.top = "", this.popper.style.left = "", this.popper.style.right = "", this.popper.style.bottom = "", this.popper.style.willChange = "", this.popper.style[H("transform")] = ""), this.disableEventListeners(), this.options.removeOnDestroy && this.popper.parentNode.removeChild(this.popper), this }.call(this) } }, { key: "enableEventListeners", value: function () { return function () { this.state.eventsEnabled || (this.state = I(this.reference, this.options, this.state, this.scheduleUpdate)) }.call(this) } }, { key: "disableEventListeners", value: function () { return _.call(this) } }]), e }(); Q.Utils = ("undefined" != typeof window ? window : e).PopperUtils, Q.placements = q, Q.Defaults = J, t.default = Q }).call(this, n(2)) }, 220: function (e, t, n) { "use strict"; Object.defineProperty(t, "__esModule", {value: !0}), t.Popper = void 0; var o, r = n(219), i = (o = r) && o.__esModule ? o : {default: o}; i.default.Defaults.modifiers.computeStyle.gpuAcceleration = !1, t.Popper = i.default } }); if ("object" == typeof n) { var o = ["object" == typeof module && "object" == typeof module.exports ? module.exports : null, "undefined" != typeof window ? window : null, e && e !== window ? e : null]; for (var r in n) o[0] && (o[0][r] = n[r]), o[1] && "__esModule" !== r && (o[1][r] = n[r]), o[2] && (o[2][r] = n[r]) } }(this);
const Command = require("./Command.js") , Table = require("cli-table3") , defaultStr = require("./strings/en.js") , parseSentence = require("minimist-string"); /* eslint-disable valid-jsdoc - syntax error for some reason? */ /** * @class App * * A command line app. An App can parse an input with {@link parseInput}, and if it's correct (i.e: * refers to an existing command and provides the required options), the command will be executed. * An App needs an onReply function to be able to communicate with the user. * * @param {object} options * @param {string} options.name * * The app's name. This isn't necessarily the same as the prefix. Its only purpose is to be shown to * the user in case of syntax error, or when they request the app help. * * @param {string} options.desc * * A description of what the app does. This will be used to document the app's help. * * @param {string} options.prefix * * The app's prefix. It will be used by {@link parseInput} to determine the user's intention to run * a command corresponding to this App instance. * * @param {onReply} options.onReply * * A function that allows the App to communicate with the end user. When the App needs to show an * output, the onReply function will be executed. * * @param {boolean} [options.caseSensitive=true] * * Whether or not the app's prefix is case sensitive. * * @param {string} [options.version] * * The app's version. It will be used to document the app's help. * * @param {string} [options.separator=" "] * * A string that separates the app's prefix from the rest of the CLI sentence. For instance, in the * sentence `-testapp foo` the separator would be `' '` (space character). Normally you wouldn't * want to touch this, but in some scenarios it's useful to have the separator be `''` * (empty string), so that you could do `/command`, where `/` is the app's prefix. * * @param {Command[]} [options.commands] * * An array of commands that will immediately be bound to the app. Additional commands can be later * bound using {@link App#addCommand}. * * @param {StringsObject} [options.strings] * * An object containing at least one valid string from the {@link StringsObject}, that will override * the default strings. Use it to customize the messages that are sent to the user. * * @example * const Clapp = require('clapp'); * * let myApp = new Clapp.App({ * name: "Test App", * desc: "An app created with Clapp!", * prefix: "-testapp", // Commands will have this structure: -testapp foo --bar * version: "1.2.0", * onReply: (msg, context) => { * // Called when the App shows output * console.log(msg); * }, * commands: [myCommand1, myCommand2], * strings: { * help_usage: "Here's how you use this: " * } * }); * * myApp.addCommand(myCommand3); */ /* eslint-enable */ class App { constructor(options) { if ( typeof options === "undefined" || // options is required typeof options.name !== "string" || // name is required typeof options.desc !== "string" || // desc is required typeof options.prefix !== "string" || // prefix is required typeof options.onReply !== "function" || // onReply is required ( options.commands && !Array.isArray(options.commands) ) || // commands are not required ( options.version && typeof options.version !== "string" ) || // version is not required ( options.caseSensitive && typeof options.caseSensitive !== "boolean" ) || // caseSensitive is not required ( options.separator && typeof options.separator !== "string" ) || // separator is not required ( options.strings && typeof options.strings !== "object" ) // strings is not required ) { throw new Error("Wrong options passed into the Clapp constructor. " + "Please refer to the documentation."); } this.name = options.name; this.desc = options.desc; this.prefix = options.prefix; this.caseSensitive = typeof options.caseSensitive === "boolean" ? options.caseSensitive : true; this.version = typeof options.version === "string" ? options.version : undefined; // doing options.separator || ' ' would invalidate the separator being '' this.separator = (typeof options.separator !== "undefined") ? options.separator : " "; this.str = Object.assign({}, defaultStr, options.strings); /** * @typedef {function} onReply * * The onReply function gets called every time Clapp needs to show output to the user. It * receives two parameters: `msg` and `context`. The `msg` parameter is the message that you * need to show to the user. It can be the generated command help, if the user requests * it, an error message if the user doesn't pass a valid cli sentence, or your own message, * returned by the command function. * * The `context` is anything that you defined when calling {@link App#parseInput}, for more * information see {@tutorial Working-with-contexts} * * @example * function(msg, context) { * createMessage(msg, context.user); * } */ this.reply = options.onReply; this.commands = {}; options.commands = options.commands || []; for (let i = 0; i < options.commands.length; i++) { this.addCommand(options.commands[i]); } } /** * Binds a command to the app so that the command can be executed from * [parseInput]{@link App#parseInput}. * * @param {Command} cmd The command to bind. * @return {undefined} * * @example * app.addCommand(new Clapp.Command({ * name: "foo", * desc: "An example command", * fn : (argv, context) => { * console.log("foo was executed"); * } * })): */ addCommand(cmd) { if (!(cmd instanceof Command)) { throw new Error("Error adding a command to " + this.name + ". Provided parameter is not a command. Please refer to the documentation."); } this.commands[cmd.name] = cmd; } /** * Parses an input CLI sentence (See [isCliSentence]{@link App#isCliSentence}) and performs * actions accordingly: * if the sentence is a valid command, that command is executed. If it is an invalid CLI * sentence, the user is warned about the problem. If the user passes the "--help" flag, they * are prompted with the app general help, or the command specific help. * * Please note the following: * * - The input is not sanitized. It is your responsibility to do so. * - It would be a good idea to sanitize your input by using [validations]{@link validation}. * - It is also imperative that you make sure that the input is a CLI sentence (valid or * not) by using [isCliSentence]{@link App#isCliSentence}. Otherwise, Clapp will throw an error. * * @param {string} input A CLI sentence. See [isCliSentence]{@link App#isCliSentence}. * @param {*} [context] The context to retrieve later. See {@tutorial Working-with-contexts}. * @return {undefined} * * @example * app.parseInput("/testapp foo"); // Executes `foo` * app.parseInput("/testapp foo --bar"); // Executes `foo` passing the --bar flag * app.parseInput("/testapp foo --help"); // Shows the command help for `foo` * app.parseInput("/testapp --help"); // Shows the app help * app.parseInput("Not a CLI sentence"); // Throws an error. Make sure to validate * // user input with App.isCliSentence(); */ parseInput(input, context) { if (typeof input !== "string") { throw new Error("Input must be a string! Don't forget to sanitize it."); } if (!this.isCliSentence(input)) { throw new Error("Clapp: attempted to parse the input \"" + input + "\", " + "but it is not a CLI sentence (doesn't begin with the app prefix)."); } let argv = parseSentence(input.replace(this.prefix + this.separator, "")); // Find whether or not the requested command exists let cmd = null; let userInputCommand = argv._[0]; for (let name in this.commands) { let command = this.commands[name]; let validCommandName = command.caseSensitive ? name : name.toLowerCase(); let validUserInput = command.caseSensitive ? userInputCommand : userInputCommand.toLowerCase(); if (validCommandName === validUserInput) { cmd = command; break; } } if (!cmd) { // The command doesn't exist. Four scenarios possible: let { validPrefix, userPrefix } = this._getValidPrefixes(input); let validInput = this._getValidUserInput(input, userPrefix); if (argv.help || validInput === validPrefix) { // The help flag was passed OR the user typed just the command prefix. // Show app help. this.reply(this._getHelp(), context); } else if (argv.version) { // The user asked for the app version this.reply("v" + this.version, context); } else { // The user made a mistake. Let them know. this.reply(this.str.err + this.str.err_unknown_command.replace("%CMD%", argv._[0]) + " " + this.str.err_type_help.replace("%PREFIX%", this.prefix), context); } } else { // The command exists. Three scenarios possible: if (argv.help) { // The user requested the command specific help. this.reply(cmd._getHelp(this), context); } else { // Find whether or not it supplies every required argument. let unfulfilled_args = []; let j = 1; // 1 because argv._[0] is the command name for (let i in cmd.args) { if (cmd.args[i].required && typeof argv._[j] === "undefined") { unfulfilled_args.push(cmd.args[i]); } j++; } if (unfulfilled_args.length) { let r = this.str.err + this.str.err_unfulfilled_args + "\n"; for (let i in unfulfilled_args) { r += unfulfilled_args[i.name] + "\n"; } r += "\n" + this.str.err_type_help.replace( "%PREFIX%", this.prefix + " " + argv._[0] ); this.reply(r, context); } else { let final_argv = { args: {}, flags: {} }; let errors = []; // Give values to every argument j = 1; for (let i in cmd.args) { let arg = cmd.args[i]; final_argv.args[arg.name] = argv._[j]; // If the arg wasn't supplied and it has a default value, use it if (typeof final_argv.args[arg.name] === "undefined" && typeof arg.default !== "undefined") { final_argv.args[arg.name] = arg.default; } // Convert it to the correct type, and register errors. final_argv.args[arg.name] = App._convertType( final_argv.args[arg.name], arg.type ); if (typeof final_argv.args[arg.name] === "object") { errors.push("Error on argument " + i + ": expected " + final_argv.args[arg.name].expectedType + ", got " + final_argv.args[arg.name].providedType + " instead."); } else { // If the user input matches the required data type, perform every // validation, if there's any: for (let validation of arg.validations) { if (!validation.validate(final_argv.args[arg.name])) { errors.push("Error on argument " + i + ": " + validation.errorMessage); } } } j++; } // Give values to every flag for (let name in cmd.flags) { let flag = cmd.flags[name]; let userValue = null; // Check if the user has passed the alias. // Otherwise check if the user has passed the flag. if (typeof argv[flag.alias] !== "undefined") { // The user has passed the alias. userValue = argv[flag.alias]; } else { // If the flag is case sensitive, just check if the user has passed it if (flag.caseSensitive && typeof argv[name] !== "undefined") { userValue = argv[name]; } else { // If not, compare every flag the user passed against this one. for (let userInputFlag in argv) { // _ represents the command and arguments; // we don't care about those. if (userInputFlag !== "_" && name.toLowerCase() === userInputFlag.toLowerCase()) { userValue = argv[userInputFlag]; } } } } final_argv.flags[name] = userValue !== null ? userValue : flag.default; // Convert it to the correct type, and register errors. final_argv.flags[name] = App._convertType( final_argv.flags[name], flag.type ); if (typeof final_argv.flags[name] === "object") { errors.push("Error on flag " + name + ": expected " + final_argv.flags[name].expectedType + ", got " + final_argv.flags[name].providedType + " instead."); } else { // If the user input matches the required data type, perform every // validation, if there's any: for (let k = 0; k < flag.validations.length; k++) { if (!flag.validations[k].validate(final_argv.flags[name])) { errors.push("Error on flag " + name + ": " + flag.validations[k].errorMessage); } } } } // If we don't have any errors, we can execute the command let response; if (errors.length === 0) { /** * @typedef {Object} argv * * For more information, see {@tutorial Defining-the-command-function}. * * @property {Object} args An object containing every argument. * @property {Object} flags An object containing every flag. * * @example * * { * args: { * myRequiredArg: 'foo', * myOptionalArgWithDefaultValue: 'bar', * }, * flags: { * limit: 20, * debug: true * } * } */ // The property async is deprecated, but we still give support to it if (!cmd.async) { response = cmd.fn(final_argv, context); if (response instanceof Promise) { // Even though the async attribute is set to false, the command // is actually async because it returned a promise. Promise.resolve(response).then(actualResponse => { // Note the difference between response and actual_response // response is a Promise that will eventually return a value // actualResponse is the value that was returned by the promise if (typeof actualResponse === "string") { this.reply(actualResponse, context); } else if ( typeof actualResponse === "object" && ( typeof actualResponse.message === "string" || typeof actualResponse.context !== "undefined" ) ) { this.reply(actualResponse.message, actualResponse.context); } }).catch(err => { this.reply( this.str.err_internal_error.replace( "%CMD%", cmd.name ), context ); console.error(err); }); } else if (typeof response === "string") { this.reply(response, context); } else if (typeof response === "object" && ( typeof response.message !== "string" || typeof response.context !== "undefined" )) { this.reply(response.message, response.context); } } else { let self = this; cmd.fn( final_argv, context, function cb(response, newContext) { if (typeof response === "string") { if (typeof newContext !== "undefined") { self.reply(response, newContext); } else { self.reply(response, context); } } } ); if (!cmd.suppressDeprecationWarnings) { /* istanbul ignore next */ console.warn("The Command.async property is deprecated. Please" + " return a Promise instead; refer to the documentation.\n" + "Set the suppressDeprecationWarnings property to true in" + " order to ignore this warning."); } } } else { response = this.str.err + this.str.err_type_mismatch + "\n\n"; for (let i = 0; i < errors.length; i++) { response += errors[i] + "\n"; } this.reply(response, context); } } } } } /** * Validates an input to find out whether or not it is a CLI sentence. * * A CLI sentence (valid or not) is a string that begins with the app prefix. A valid CLI * sentence is a CLI sentence that does not result in an error upon parsing. * * @param {string} sentence The string to test. * @return {boolean} Whether or not the sentence is a CLI sentence. * * @example * app.isCliSentence('/testapp foo --bar'); // True * app.isCliSentence('Hello, world!') // False */ isCliSentence(sentence) { let { validPrefix, userPrefix } = this._getValidPrefixes(sentence); // Replace the user-introduced prefix with the userPrefix variable let userSentence = this._getValidUserInput(sentence, userPrefix); return userSentence === validPrefix || userPrefix === (validPrefix + this.separator); } /** * Converts an argument to the requested data type. Returns null if impossible. * @param {string|number|boolean} arg The provided argument * @param {string} toType The type we want the argument to be. * @return {string|number|boolean|null|inputMismatchInfo} * Returns the desired value, or the error information on fail. * @private * * @typedef {object} inputMismatchInfo * @property {string} providedType * @property {string} expectedType */ static _convertType(arg, toType) { switch (typeof arg) { case "string": switch (toType) { case "string": // String asked, string provided. We're good to go. return arg; case "number": // Number asked, string provided. // We don't even try to convert the string to a number, because if the user // had provided a number, minimist would have given us a number, meaning // that we wouldn't be here. So we have an error. return { providedType: "string", expectedType: "number" }; case "boolean": // Boolean asked, string provided. // The common scenario for getting a boolean would be an user inputting // something like this: --boolOption. // But we also want this to work: --boolOption=true and --boolOption="true" // So we try to convert the string to boolean: switch (arg.toLowerCase()) { case "true": // We have a boolean with the value true. We're good to go. return true; case "false": // We have a boolean with the value false. We're good to go. return false; default: // The string can't be converted to boolean. // We have an error. return { providedType: "string", expectedType: "boolean" }; } /* istanbul ignore next */ default: // This shouldn't happen. throw new Error("Clapp: internal error." + "Please report this to the bug tracker."); } case "number": switch (toType) { case "string": // String asked, number provided. // This is fine, the expected value could be a number string, // so we just convert it. return arg.toString(); case "number": // Number asked, number provided. We're good to go. return arg; case "boolean": // We want to accept the values of 0 and 1 as booleans, and reject the rest. if (arg === 0) { return false; } else if (arg === 1) { return true; } else { return { providedType: "number", expectedType: "boolean" }; } /* istanbul ignore next */ default: // This shouldn't happen. throw new Error("Clapp: internal error." + "Please report this to the bug tracker."); } case "boolean": // If a boolean is provided, it only makes sense to accept it if a boolean is asked // because although true could be converted to 1 or string "true", it would only // be confusing and cause unexpected behaviour. switch (toType) { case "string": return { providedType: "boolean", expectedType: "string" }; case "number": return { providedType: "boolean", expectedType: "number" }; case "boolean": // We gucci return arg; /* istanbul ignore next */ default: // This shouldn't happen. throw new Error("Clapp: internal error." + "Please report this to the bug tracker."); } /* istanbul ignore next */ default: // This shouldn't happen. throw new Error("Clapp: internal error. Please report this to the bug tracker."); } } /** * Parses the app prefix and user inputted prefix to take into account case insensitivity. * * @param {string} input The user input. * @return {{validPrefix: string, userPrefix: string}} An object containing the result. * @private */ _getValidPrefixes(input) { let validPrefix = this.caseSensitive ? this.prefix : this.prefix.toLowerCase(); let userPrefix = input.substring(0, this.prefix.length + this.separator.length); userPrefix = this.caseSensitive ? userPrefix : userPrefix.toLowerCase(); return { validPrefix: validPrefix, userPrefix: userPrefix }; } /** * Converts the user input to a "valid" input which takes into account case insensitivity. * * @param {string} input The user input * @param {string} userPrefix The result of _getValidPrefixes() * @return {string} The parsed input * @private */ _getValidUserInput(input, userPrefix) { return userPrefix + input.substring(this.prefix.length + this.separator.length); } /** * Returns the global app help * * @return {string} The App Help * @private */ _getHelp() { const LINE_WIDTH = 100; let r = this.name + (typeof this.version !== "undefined" ? " v" + this.version : "") + "\n" + this.desc + "\n\n" + this.str.help_usage + this.prefix + this.separator + this.str.help_command + "\n\n" + this.str.help_cmd_list + "\n\n" ; // Command list let table = new Table({ chars: { "top": "", "top-mid": "", "top-left": "", "top-right": "", "bottom": "", "bottom-mid": "", "bottom-left": "", "bottom-right": "", "left": "", "left-mid": "", "mid": "", "mid-mid": "", "right": "", "right-mid": "", "middle": "" }, colWidths: [0.1 * LINE_WIDTH, 0.9 * LINE_WIDTH], wordWrap: true }); for (let i in this.commands) { table.push([i, this.commands[i].desc]); } r += table.toString() + "\n\n" + this.str.help_further_help + this.prefix + " " + this.str.help_command + " --help" ; return r; } } module.exports = App;
// Maian Weblog v4.0 // Javascript Functions // Theme: Green House // Pop Up Window function popWindow(URL,LEFT,TOP,WIDTH,HEIGHT,SCROLLBARS,RESIZE) { day = new Date(); id = day.getTime(); eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=" + SCROLLBARS + ",location=0,statusbar=0,menubar=0,left=" + LEFT + ",top=" + TOP + ",screenX=0,screenY=0,resizable=" + RESIZE + ",width=" + WIDTH + ",height=" + HEIGHT + "');"); } // This function allows links to open in a new window // XHTML removed the target attribute and this is the fix // Use rel="external" if you want links to open in new window function externalLinks() { if (!document.getElementsByTagName) return; var anchors = document.getElementsByTagName("a"); for (var i=0; i<anchors.length; i++) { var anchor = anchors[i]; if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") anchor.target = "_blank"; } } window.onload = externalLinks;
var NAVTREEINDEX0 = { "account_8c.html":[2,0,9,0], "account_8c.html#a14989e440fba9c705d4d64f4d121890a":[2,0,9,0,2], "account_8c.html#a28e797f55aea95117bd98686eda141d7":[2,0,9,0,0], "account_8c.html#ab8e8ca2bf1780642056e5522ba9650c7":[2,0,9,0,1], "account_8c.html#afa1f48d391eddc3e994c5e0e64decb82":[2,0,9,0,3], "account_8c_source.html":[2,0,9,0], "account_8h.html":[2,0,9,1], "account_8h.html#a14989e440fba9c705d4d64f4d121890a":[2,0,9,1,6], "account_8h.html#a19a9ad056d93491b610201fa644eef6e":[2,0,9,1,2], "account_8h.html#a19a9ad056d93491b610201fa644eef6ea0570a2408670a7e4865ab2f22b6f261c":[2,0,9,1,2,1], "account_8h.html#a19a9ad056d93491b610201fa644eef6ea1990aab4f0681c10c4a2e5036c647b0d":[2,0,9,1,2,2], "account_8h.html#a19a9ad056d93491b610201fa644eef6ea2f33ec4035fcd1ed206ae564c3c54631":[2,0,9,1,2,0], "account_8h.html#a28e797f55aea95117bd98686eda141d7":[2,0,9,1,7], "account_8h.html#a9c9dcde7ae3ff184449a229340ccdd3a":[2,0,9,1,3], "account_8h.html#ab8e8ca2bf1780642056e5522ba9650c7":[2,0,9,1,5], "account_8h.html#afa1f48d391eddc3e994c5e0e64decb82":[2,0,9,1,4], "account_8h_source.html":[2,0,9,1], "addr_address.html":[3,0,0], "addr_group.html":[3,0,1], "addr_idna.html":[3,0,2], "address_2address_8c.html":[2,0,0,0], "address_2address_8c.html#a063ba7f9bacb413f113386620fc75ca7":[2,0,0,0,24], "address_2address_8c.html#a0edcb239a41a0bd08370e3bdc0218b63":[2,0,0,0,8], "address_2address_8c.html#a16764dc80c9b3f6ad2897c8b7e59bd10":[2,0,0,0,18], "address_2address_8c.html#a16a97a499073187e58d4022ad6de29d1":[2,0,0,0,17], "address_2address_8c.html#a1de5e467c74e205ff465fd601c275b88":[2,0,0,0,15], "address_2address_8c.html#a1e5796ca41b0c0693168aa4d496951db":[2,0,0,0,26], "address_2address_8c.html#a1f6fcdd22fe42071c49ff7ca0d7beb91":[2,0,0,0,25], "address_2address_8c.html#a2528d2baa23c9e4444aceec65e09e6f6":[2,0,0,0,3], "address_2address_8c.html#a345cbe54f86e6e17da0789226c975056":[2,0,0,0,20], "address_2address_8c.html#a391539d42acc2637dd9d19a900915dbf":[2,0,0,0,4], "address_2address_8c.html#a396bcf6adfff6663096fa6ae99c31c9a":[2,0,0,0,40], "address_2address_8c.html#a3f26185f6b123539b752d5be774606ea":[2,0,0,0,32], "address_2address_8c.html#a40eda06e6e64ff9d9f1e7d3b69e7c846":[2,0,0,0,12], "address_2address_8c.html#a434492a707aadd897d74bdf7b493bbc2":[2,0,0,0,19], "address_2address_8c.html#a4924ea51b16e5d7d3156954477c647c4":[2,0,0,0,27], "address_2address_8c.html#a4ade26f339f13e9564b1d112a8a62cec":[2,0,0,0,6], "address_2address_8c.html#a4b1281c02f8b158f174c0b7c57af3d83":[2,0,0,0,10], "address_2address_8c.html#a4d146f05fa380f9ad7c38cd80ef1a23e":[2,0,0,0,5], "address_2address_8c.html#a51cd0cf4038bc17ec6402a5478cb6490":[2,0,0,0,47], "address_2address_8c.html#a55fa120cad4700e7401e0eccc2bebeb5":[2,0,0,0,28], "address_2address_8c.html#a5b9dcfae60924e14f0b55a33dcbdec33":[2,0,0,0,44], "address_2address_8c.html#a5fc8a0b1e781c6e88f43f86d0ede02d2":[2,0,0,0,16], "address_2address_8c.html#a60b3ced56e9f5be39c391250d951bf72":[2,0,0,0,22], "address_2address_8c.html#a64951ec4d595356746ef4d26dd7533c6":[2,0,0,0,29], "address_2address_8c.html#a68385b174baad74a9aecf3dec61432a0":[2,0,0,0,41], "address_2address_8c.html#a69d612ac8c7f2fc7e471561216bd1c41":[2,0,0,0,31], "address_2address_8c.html#a7b1224fc8c5dde7114228cfc8ffbbc23":[2,0,0,0,37], "address_2address_8c.html#a87d3aafedba94d99128c14ca87d7d6ef":[2,0,0,0,43], "address_2address_8c.html#a8ac391285f1af69a114544e6575b597a":[2,0,0,0,14], "address_2address_8c.html#a8bed9a1224d4a496eef671a07a416dc4":[2,0,0,0,2], "address_2address_8c.html#a930029e50328c7a0b48e302ef87fe023":[2,0,0,0,45], "address_2address_8c.html#a95bcf9ec8be0b69b33fadde85800b559":[2,0,0,0,36], "address_2address_8c.html#a968e9f56e7408d5e0fa1d1135bdee017":[2,0,0,0,39], "address_2address_8c.html#a9a6c4ff878258def25f155501ddb3e7a":[2,0,0,0,21], "address_2address_8c.html#a9b432973fafcabce986bae19e5b7c96c":[2,0,0,0,1], "address_2address_8c.html#a9bb4abe92405bac67f03e36936a29b6e":[2,0,0,0,13], "address_2address_8c.html#a9fec0414b05f202de503911070040bd9":[2,0,0,0,33], "address_2address_8c.html#aa68a29c1feb5938596aa589cf2d6a1af":[2,0,0,0,42], "address_2address_8c.html#ab846e8ee5f464af767e7bcf948210a26":[2,0,0,0,0], "address_2address_8c.html#abe8afdaeb5bdca19a1867823d73a1ec4":[2,0,0,0,35], "address_2address_8c.html#abfd85ca14a8e67427bbc809212ae7fd4":[2,0,0,0,34], "address_2address_8c.html#ac1ccf9a098991f797af50f11e6575695":[2,0,0,0,30], "address_2address_8c.html#ac1d39161f1f62fbe4a624d6e49221bf6":[2,0,0,0,11], "address_2address_8c.html#ac9b323dadeb2a55ce6e9cd4763b9d832":[2,0,0,0,9], "address_2address_8c.html#ad602a3cf6ff5c7fb79d21627553a586d":[2,0,0,0,23], "address_2address_8c.html#ad858e9af7a80f0d17ff763bed3821500":[2,0,0,0,46], "address_2address_8c.html#ae9b17c2b7e2c0239c39d347e8eb8dce7":[2,0,0,0,7], "address_2address_8c.html#aee5d40d84136d3a7adba727e2908ad66":[2,0,0,0,38], "address_2address_8c_source.html":[2,0,0,0], "address_2address_8h.html":[2,0,0,1], "address_2address_8h.html#a16764dc80c9b3f6ad2897c8b7e59bd10":[2,0,0,1,19], "address_2address_8h.html#a16a97a499073187e58d4022ad6de29d1":[2,0,0,1,8], "address_2address_8h.html#a1de5e467c74e205ff465fd601c275b88":[2,0,0,1,26], "address_2address_8h.html#a345cbe54f86e6e17da0789226c975056":[2,0,0,1,22], "address_2address_8h.html#a396bcf6adfff6663096fa6ae99c31c9a":[2,0,0,1,18], "address_2address_8h.html#a3f26185f6b123539b752d5be774606ea":[2,0,0,1,35], "address_2address_8h.html#a40eda06e6e64ff9d9f1e7d3b69e7c846":[2,0,0,1,11], "address_2address_8h.html#a434492a707aadd897d74bdf7b493bbc2":[2,0,0,1,6], "address_2address_8h.html#a4b1281c02f8b158f174c0b7c57af3d83":[2,0,0,1,9], "address_2address_8h.html#a51cd0cf4038bc17ec6402a5478cb6490":[2,0,0,1,37], "address_2address_8h.html#a5b9dcfae60924e14f0b55a33dcbdec33":[2,0,0,1,32], "address_2address_8h.html#a5fc8a0b1e781c6e88f43f86d0ede02d2":[2,0,0,1,5], "address_2address_8h.html#a60b3ced56e9f5be39c391250d951bf72":[2,0,0,1,7], "address_2address_8h.html#a64951ec4d595356746ef4d26dd7533c6":[2,0,0,1,10], "address_2address_8h.html#a68385b174baad74a9aecf3dec61432a0":[2,0,0,1,17], "address_2address_8h.html#a69d612ac8c7f2fc7e471561216bd1c41":[2,0,0,1,33], "address_2address_8h.html#a6ffe753b248beb6791054e2c4179332a":[2,0,0,1,4], "address_2address_8h.html#a7b1224fc8c5dde7114228cfc8ffbbc23":[2,0,0,1,31], "address_2address_8h.html#a87d3aafedba94d99128c14ca87d7d6ef":[2,0,0,1,15], "address_2address_8h.html#a8ac391285f1af69a114544e6575b597a":[2,0,0,1,24], "address_2address_8h.html#a90484d55cb9c6d3d227fb28011084fc9":[2,0,0,1,1], "address_2address_8h.html#a930029e50328c7a0b48e302ef87fe023":[2,0,0,1,38], "address_2address_8h.html#a93edb573e86b1896244e3805dab1885c":[2,0,0,1,34], "address_2address_8h.html#a95bcf9ec8be0b69b33fadde85800b559":[2,0,0,1,14], "address_2address_8h.html#a968e9f56e7408d5e0fa1d1135bdee017":[2,0,0,1,28], "address_2address_8h.html#a9a6c4ff878258def25f155501ddb3e7a":[2,0,0,1,20], "address_2address_8h.html#a9bb4abe92405bac67f03e36936a29b6e":[2,0,0,1,23], "address_2address_8h.html#aa3cf99a8b937291394a16ae959e175ae":[2,0,0,1,3], "address_2address_8h.html#aa3cf99a8b937291394a16ae959e175aea4d70e5a2d40cfa2720795098ec32c1ab":[2,0,0,1,3,3], "address_2address_8h.html#aa3cf99a8b937291394a16ae959e175aea6ac23b071971bad7e1b40a2c7b013110":[2,0,0,1,3,4], "address_2address_8h.html#aa3cf99a8b937291394a16ae959e175aea73949ddb55f1c35d9291866c47fe48ed":[2,0,0,1,3,5], "address_2address_8h.html#aa3cf99a8b937291394a16ae959e175aea9621128c93e043a6a52fc56e409f2ad9":[2,0,0,1,3,0], "address_2address_8h.html#aa3cf99a8b937291394a16ae959e175aeac9383ad3d3d38dd6086f261c96b8d434":[2,0,0,1,3,1], "address_2address_8h.html#aa3cf99a8b937291394a16ae959e175aead713806128d06cfdf125963755f89cfa":[2,0,0,1,3,2], "address_2address_8h.html#aa68a29c1feb5938596aa589cf2d6a1af":[2,0,0,1,25], "address_2address_8h.html#abe8afdaeb5bdca19a1867823d73a1ec4":[2,0,0,1,30], "address_2address_8h.html#abfd85ca14a8e67427bbc809212ae7fd4":[2,0,0,1,13], "address_2address_8h.html#ac1ccf9a098991f797af50f11e6575695":[2,0,0,1,16], "address_2address_8h.html#ac1d39161f1f62fbe4a624d6e49221bf6":[2,0,0,1,27], "address_2address_8h.html#ac9b323dadeb2a55ce6e9cd4763b9d832":[2,0,0,1,12], "address_2address_8h.html#ad602a3cf6ff5c7fb79d21627553a586d":[2,0,0,1,29], "address_2address_8h.html#ad858e9af7a80f0d17ff763bed3821500":[2,0,0,1,36], "address_2address_8h.html#ae1f1886d7f33660482f32c040278031b":[2,0,0,1,2], "address_2address_8h.html#aee5d40d84136d3a7adba727e2908ad66":[2,0,0,1,21], "address_2address_8h_source.html":[2,0,0,1], "address_2lib_8h.html":[2,0,0,6], "address_2lib_8h_source.html":[2,0,0,6], "alias_2commands_8c.html":[2,0,1,3], "alias_2commands_8c.html#a8487d20a2159f19cdf61e8a9030f0e72":[2,0,1,3,0], "alias_2commands_8c.html#a867b2daae6e906b5cb92d66f898acaad":[2,0,1,3,1], "alias_2commands_8c_source.html":[2,0,1,3], "alias_2config_8c.html":[2,0,1,4], "alias_2config_8c.html#a6accc5f32e32ca3daa7c85ceeb133106":[2,0,1,4,1], "alias_2config_8c.html#abeecb3c988acb9aa91ec8a680d328e6e":[2,0,1,4,0], "alias_2config_8c.html#afdb0e9d9303634ffd195c833daa8ab66":[2,0,1,4,2], "alias_2config_8c_source.html":[2,0,1,4], "alias_2lib_8h.html":[2,0,1,9], "alias_2lib_8h.html#a1205cb3b6c32c17817078da6a4666be5":[2,0,1,9,12], "alias_2lib_8h.html#a7c57d5376e9a1cf5e1f504a452996b86":[2,0,1,9,6], "alias_2lib_8h.html#a8487d20a2159f19cdf61e8a9030f0e72":[2,0,1,9,8], "alias_2lib_8h.html#a867b2daae6e906b5cb92d66f898acaad":[2,0,1,9,9], "alias_2lib_8h.html#a8bc2a37fada3aaa7c58cad015f43af16":[2,0,1,9,15], "alias_2lib_8h.html#a8f5eca479605975d43e59cc8214cd2c9":[2,0,1,9,13], "alias_2lib_8h.html#a9a5bce1105cd6bfb1f7a614f680dfef2":[2,0,1,9,2], "alias_2lib_8h.html#a9d6f6b4ea9d79c9c33ddd7c6b6ef764b":[2,0,1,9,4], "alias_2lib_8h.html#a9f4083666781c1d9d1775c15409a521f":[2,0,1,9,0], "alias_2lib_8h.html#aa85f5781f8449116951d77b6e5f42ebf":[2,0,1,9,7], "alias_2lib_8h.html#aa90fd4b086aebbf4fed5245ecaca1ac1":[2,0,1,9,5], "alias_2lib_8h.html#abeecb3c988acb9aa91ec8a680d328e6e":[2,0,1,9,14], "alias_2lib_8h.html#ac497f221c91e788faa8c110f70d26aee":[2,0,1,9,10], "alias_2lib_8h.html#ae0458160a347d92d2e375dcb974579c6":[2,0,1,9,3], "alias_2lib_8h.html#aeb04c5d6d412833406f364c7da4d672c":[2,0,1,9,1], "alias_2lib_8h.html#aed95bba2770f684ed0caadf42d924860":[2,0,1,9,11], "alias_2lib_8h_source.html":[2,0,1,9], "alias_2sort_8c.html":[2,0,1,12], "alias_2sort_8c.html#a1e81522b6d3873c3cc3ab2b3377d9a4f":[2,0,1,12,6], "alias_2sort_8c.html#a686731802c7f57440be4969da15efe7f":[2,0,1,12,3], "alias_2sort_8c.html#a89ffac83aa53c9558af1f25adf995450":[2,0,1,12,0], "alias_2sort_8c.html#a8bc2a37fada3aaa7c58cad015f43af16":[2,0,1,12,5], "alias_2sort_8c.html#aa3c8a17a637b4026b9294db2f3bf35f5":[2,0,1,12,4], "alias_2sort_8c.html#acd6d0d0b1a07834cdfc26b405b318d8a":[2,0,1,12,1], "alias_2sort_8c.html#aebd29f6692fe32844020c3904003f76d":[2,0,1,12,2], "alias_2sort_8c_source.html":[2,0,1,12], "alias_8c.html":[2,0,1,0], "alias_8c.html#a027ff288eb965c15ce16ca26b6467d44":[2,0,1,0,12], "alias_8c.html#a0831e7ca6080141051db5bde20cb45f7":[2,0,1,0,16], "alias_8c.html#a207a8105a441657885093d91f6dadcb2":[2,0,1,0,4], "alias_8c.html#a298053b358ffc2bb79c2d48ba893dc75":[2,0,1,0,3], "alias_8c.html#a5837890e435ba7ec3419412ec7446414":[2,0,1,0,11], "alias_8c.html#a72f25c630f91fffd47d013745fae3b74":[2,0,1,0,0], "alias_8c.html#a7c57d5376e9a1cf5e1f504a452996b86":[2,0,1,0,6], "alias_8c.html#a9a5bce1105cd6bfb1f7a614f680dfef2":[2,0,1,0,9], "alias_8c.html#a9d6f6b4ea9d79c9c33ddd7c6b6ef764b":[2,0,1,0,10], "alias_8c.html#a9f4083666781c1d9d1775c15409a521f":[2,0,1,0,14], "alias_8c.html#aa85f5781f8449116951d77b6e5f42ebf":[2,0,1,0,8], "alias_8c.html#aa90fd4b086aebbf4fed5245ecaca1ac1":[2,0,1,0,7], "alias_8c.html#ac3582f1f1874b36d1938d5a274346b02":[2,0,1,0,2], "alias_8c.html#ac62d3290984030d8a07d1388d2ec00dd":[2,0,1,0,13], "alias_8c.html#ae0458160a347d92d2e375dcb974579c6":[2,0,1,0,5], "alias_8c.html#aeb04c5d6d412833406f364c7da4d672c":[2,0,1,0,15], "alias_8c.html#afa6db199eab0d4f151c52b3712facae8":[2,0,1,0,1], "alias_8c_source.html":[2,0,1,0], "alias_8h.html":[2,0,1,1], "alias_8h.html#a027ff288eb965c15ce16ca26b6467d44":[2,0,1,1,4], "alias_8h.html#a0831e7ca6080141051db5bde20cb45f7":[2,0,1,1,7], "alias_8h.html#a5837890e435ba7ec3419412ec7446414":[2,0,1,1,6], "alias_8h.html#a62b52be6266dd0fae07e4133e7b97d7b":[2,0,1,1,2], "alias_8h.html#a62b52be6266dd0fae07e4133e7b97d7ba158a633155fe2f31d2c8b1123db406e1":[2,0,1,1,2,1], "alias_8h.html#a62b52be6266dd0fae07e4133e7b97d7ba2354c23554a676de7a0025e59218245a":[2,0,1,1,2,2], "alias_8h.html#a62b52be6266dd0fae07e4133e7b97d7ba854757840b396d5001e89290f995e94e":[2,0,1,1,2,0], "alias_8h.html#ac62d3290984030d8a07d1388d2ec00dd":[2,0,1,1,5], "alias_8h.html#ac8b2a934090d6906291ff2772ee26dc9":[2,0,1,1,3], "alias_8h_source.html":[2,0,1,1], "alias_alias.html":[3,1,0], "alias_array.html":[3,1,1], "alias_commands.html":[3,1,2], "alias_config.html":[3,1,3], "alias_dlgalias.html":[3,1,4], "alias_dlgquery.html":[3,1,5], "alias_gui.html":[3,1,6], "alias_reverse.html":[3,1,7], "alias_sort.html":[3,1,8], "annotated.html":[1,0], "array_8c.html":[2,0,1,2], "array_8c.html#a2140b343618666de7ad67e846a653601":[2,0,1,2,2], "array_8c.html#ae3b5a9a5dce9f8b995a226e50fdba12b":[2,0,1,2,1], "array_8c.html#ae61ddd1b0e8b8a6e2395801f5dcf4eaa":[2,0,1,2,0], "array_8c_source.html":[2,0,1,2], "array_8h.html":[2,0,19,0], "array_8h.html#a0202de48c654b38540292933b094716a":[2,0,19,0,12], "array_8h.html#a0d1d706abb177b6574c71aa7e89ae0b9":[2,0,19,0,13], "array_8h.html#a10248ed1fa20ea5a7c9f4025c1abd5c8":[2,0,19,0,20], "array_8h.html#a1a18863d08888c740a0a9f640c8ee591":[2,0,19,0,8], "array_8h.html#a24f8f1f7f0818a7ccf6de7b0949f20f5":[2,0,19,0,14], "array_8h.html#a2eecd0955cb62adb033c1146607fed1b":[2,0,19,0,22], "array_8h.html#a412164813009d6e48e4b2ae62889347d":[2,0,19,0,9], "array_8h.html#a4f570f2382025383e4b2cc46ede6ebd0":[2,0,19,0,11], "array_8h.html#a55149aa5bd71f172cda01a26583e55d2":[2,0,19,0,6], "array_8h.html#a5a50ba3db41d864890c1a6f176c5b1a1":[2,0,19,0,21], "array_8h.html#a6b8ea5fb2f366d7716f5042b347093a6":[2,0,19,0,16], "array_8h.html#a73f1ec257016f9107cd041f550ede034":[2,0,19,0,10], "array_8h.html#a748cb2df8cbe952b6fff91d62811a20a":[2,0,19,0,4], "array_8h.html#a7a13a7d57669de60f4e2ca0b2df103dd":[2,0,19,0,18], "array_8h.html#a7d53783c015122a6eee10abe2c26aa5d":[2,0,19,0,24], "array_8h.html#a7e8bd3238e25d762f17dd0950001a13f":[2,0,19,0,23], "array_8h.html#a7f1bf469a48c0a2618c94b7b8281c5bf":[2,0,19,0,5], "array_8h.html#aa8eb994df83be5712032f83e504a4b24":[2,0,19,0,1], "array_8h.html#aaa8805bd90a2015d8f5eb0fe3bb13b3f":[2,0,19,0,15], "array_8h.html#abf51c9136006cebde26a6b96f2c018fe":[2,0,19,0,17], "array_8h.html#ae857f8be0df0145d300fe44ad40d92f7":[2,0,19,0,3], "array_8h.html#aebd057bb37aec75b6bdbed9e76715803":[2,0,19,0,7], "array_8h.html#af50a4967d27a0531a1b10a23fc22fe05":[2,0,19,0,2], "array_8h.html#afc5f24e2abcf60ff018fc50afe26d1a9":[2,0,19,0,19], "array_8h.html#affd6264dc887ffea11c33d9936b3a1e8":[2,0,19,0,0], "array_8h_source.html":[2,0,19,0], "attach_8c.html":[2,0,11,0], "attach_8c.html#a0de4bc51c9c5a28627f56ee542661e58":[2,0,11,0,2], "attach_8c.html#a1ac389e189d5c0cbb84711076812f103":[2,0,11,0,0], "attach_8c.html#a2fa325c70db6c22515d0a5edc0024e53":[2,0,11,0,1], "attach_8c.html#a773158419b51bd96d4a7249422d21f73":[2,0,11,0,3], "attach_8c.html#ac215772ab5cc4d60e0a64fd5c84513e1":[2,0,11,0,5], "attach_8c.html#aea6cac12855c55e47a1d056caf989a14":[2,0,11,0,4], "attach_8c_source.html":[2,0,11,0], "attach_8h.html":[2,0,11,1], "attach_8h.html#a0de4bc51c9c5a28627f56ee542661e58":[2,0,11,1,3], "attach_8h.html#a1ac389e189d5c0cbb84711076812f103":[2,0,11,1,2], "attach_8h.html#a2fa325c70db6c22515d0a5edc0024e53":[2,0,11,1,4], "attach_8h.html#a773158419b51bd96d4a7249422d21f73":[2,0,11,1,6], "attach_8h.html#ac215772ab5cc4d60e0a64fd5c84513e1":[2,0,11,1,5], "attach_8h.html#aea6cac12855c55e47a1d056caf989a14":[2,0,11,1,7], "attach_8h_source.html":[2,0,11,1], "auth_8h.html":[2,0,16,1], "auth_8h.html#a203bd1c72cb86256613c10cb0c8e1c82":[2,0,16,1,4], "auth_8h.html#a2fe43890cdcb3e8cf4c4dbbc8b3e2fda":[2,0,16,1,3], "auth_8h.html#ab8347cf766db9a036c3ff83e98f967de":[2,0,16,1,2], "auth_8h.html#aba20e35487bf461507e63b783243dbad":[2,0,16,1,0], "auth_8h.html#aba20e35487bf461507e63b783243dbada4e84acd157fdc566eafb0f8963a179f2":[2,0,16,1,0,1], "auth_8h.html#aba20e35487bf461507e63b783243dbada544df33a559dae35b9b71951782eb897":[2,0,16,1,0,0], "auth_8h.html#aba20e35487bf461507e63b783243dbadaddf2ec71f2502b2e4684bfe42fc2fd40":[2,0,16,1,0,2] };
angular.module('app') .filter('brDate', function () { return function (data) { return moment(data).format('DD/MM/YYYY HH:mm:ss'); }; }) .filter('cpfcnpj', function () { return function (data) { if (data) { if (data.length == 11) { return data.replace(/\D/g, '').replace(/^(\d{3})(\d{3})?(\d{3})?(\d{2})?/, '$1.$2.$3-$4'); } else if (data.length == 14) { return data.replace(/\D/g, '').replace(/^(\d{2})(\d{3})?(\d{3})?(\d{4})?(\d{2})?/, '$1.$2.$3/$4-$5'); }else { return data; } } }; }) .filter('fillOrderNumber', function () { return function (data) { if (data) { var str = data.toString(); var pad = "0000000000"; var ans = pad.substring(0, pad.length - str.length) + str; return ans; } }; }) .filter('phone', function () { return function (tel, typeFormat) { if (!tel) { return ''; } var value = tel.toString().trim().replace(/^\+/, ''); if (value.match(/[^0-9]/)) {//se for numerico return tel; } var cod; var pt1; var pt2; switch (value.length) { case 10: // +1PPP####### -> C (PPP) ###-#### cod = value.slice(0, 2); pt1 = value.slice(2, 6); pt2 = value.slice(6, 10); break; case 11: // +CPPP####### -> CCC (PP) ###-#### cod = value.slice(0, 2); pt1 = value.slice(2, 7); pt2 = value.slice(7, 11); break; default: if (value.length == 9) { pt1 = value.slice(0, 5); pt2 = value.slice(5, 9); } else { pt1 = value.slice(0, 4); pt2 = value.slice(4, 8); } break; } if (typeFormat == 'onlyNumber') { return (pt1 + ' - ' + pt2).trim(); }else if (typeFormat == 'onlyDDD') { if (value.length > 9) { return cod; } else { return 'Sem DDD'; } } else { return ('(' + cod + ')' + pt1 + ' - ' + pt2).trim(); } }; });
import React, { useState, useContext } from 'react'; import IntersectionObserver from 'react-rawb-intersection-observer'; // import ProgressiveLoadableExtractorContext from './progressive-loadable-extractor'; const ProgressiveLoadable = (LoadableComponent, options = { threshold: .3 }) => { const Progressive = (props) => { // const context = useContext(ProgressiveLoadableExtractorContext); const [load, setLoad] = useState(!process.browser); const visible = () => { console.log('show', LoadableComponent); setLoad(true); }; let content = null; if (load) { content = (<LoadableComponent { ...props } />); } else { content = (<div dangerouslySetInnerHTML={{__html: '' }} />); } return ( <IntersectionObserver root=".main-content" onVisible={visible} threshold={options.threshold}>{ content }</IntersectionObserver> ); }; return Progressive; }; export default ProgressiveLoadable;
Ext.define('AM.view.master.cashmutation.List' ,{ extend: 'Ext.grid.Panel', alias : 'widget.cashmutationlist', store: 'CashMutations', initComponent: function() { this.columns = [ { header: 'ID', dataIndex: 'id'}, { header: 'Source', dataIndex: 'source_class', flex: 1}, { header: 'Source Code', dataIndex: 'source_code', flex: 1}, { header: 'CashBank', dataIndex: 'cash_bank_name', flex: 1}, { header: 'Amount', dataIndex: 'amount', flex: 1}, { header: 'status', dataIndex: 'status_text', flex: 1}, { header: 'Tanggal mutasi', dataIndex: 'mutation_date', flex: 1 } , ]; this.searchField = new Ext.form.field.Text({ name: 'searchField', hideLabel: true, width: 200, emptyText : "Search", checkChangeBuffer: 300 }); this.tbar = [this.searchField ]; this.bbar = Ext.create("Ext.PagingToolbar", { store : this.store, displayInfo: true, displayMsg: 'Displaying topics {0} - {1} of {2}', emptyMsg: "No topics to display" }); this.callParent(arguments); }, loadMask : true, getSelectedObject: function() { return this.getSelectionModel().getSelection()[0]; }, enableRecordButtons: function(record) { }, disableRecordButtons: function(record) { } });
//// How to create a SHA-256 hash in Node.js? //// // To create a SHA-256 hash, you need to import or require the crypto module and use the createHmac() method in Node.js. // get crypto module const crypto = require("crypto"); // string to be hashed const str = "d18483a7937babdc6e65c7848404dcc263c70ad3649d805fd12032abc288e145"; // const str = crypto.randomBytes(4); // secret or salt to be hashed with const secret = "_6iL"; // create a sha-256 hasher const sha256Hasher = crypto.createHmac("sha256", secret); // hash the string const hash = sha256Hasher.update(str).digest("hex"); // A unique sha256 hash 😃 console.log(hash); // d22101d5d402ab181a66b71bb950ff2892f6d2a1e436d61c4fb1011e9c49a77a let bb = Buffer.from(secret); console.log("This is salt in bytes: ", bb); // for(var ll in bb){ // console.log(ll); // } // const buf = crypto.randomBytes(4); // console.log(buf); // console.log(Buffer.from(hash)); ///////////////// Encryption //////////////////////// // const algorithm = 'aes-256-cbc'; //Using AES encryption // // const key = crypto.randomBytes(32); // const key = 'vOV_ksdmpNWj6+IqCc7rdx,01lwHzf-3'; // // const key = '61f4X0FjLs4pywEt1CiW4w==:BzrFyaL/aXrZD129ujRxaLcQdTtav+gMDpo84Lz2k6U='; // const iv = crypto.randomBytes(16); // //Encrypting text // function encrypt(text) { // let cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv); // let encrypted = cipher.update(text); // encrypted = Buffer.concat([encrypted, cipher.final()]); // return { // iv: iv.toString('hex'), // encryptedData: encrypted.toString('hex') // // bytes: Buffer.byteLength(encryptedData, 'utf8') // }; // } // var hw = encrypt(hash) // let gg = hw.encryptedData // console.log(hw) // bb = Buffer.byteLength(gg, 'utf8') // console.log("Total string length in bytes: ", bb)
import dayjs from 'dayjs'; export const toPrecision = (value, precision) => { if (typeof value !== 'number') { return value; } return Number(value.toFixed(precision)); }; export const toLocaleDate = (date, format = 'DD.MM.YYYY') => date instanceof dayjs ? date.format(format) : dayjs(date).format(format); export const toLocaleDateGraphQl = (date, format = 'DD.MM.YYYY') => date instanceof dayjs ? date.format(format) : dayjs(date).format(format); export const now = () => dayjs().format('YYYY-MM-DDTHH:mm:ss');
import React from 'react' import { sha256} from 'js-sha256' export default class Hash extends React.Component { constructor(props) { super(props); this.state = { userInput: "", outputHash:"" } } getHash = (e) => { let userInput = e.target.value var hash = sha256.create(); hash.update(userInput); this.setState({ outputHash: hash.hex() }); console.log(hash.hex()); } render() { return <div> <div> 请输入需要加密的字符串: <input onChange={this.getHash} /> </div> <div> sha256结果: <div>{this.state.outputHash}</div> </div> </div>; } }
const reset = '\x1b[0m'; const bright = '\x1b[1m'; const red = '\x1b[31m'; const yellow = '\x1b[33m'; const blue = '\x1b[34m'; // const green = '\x1b[32m'; const colorTable = { error: `${bright}${red}`, warning: `${bright}${yellow}`, note: `${bright}${blue}`, } function errorAtToken(msg, token, level) { level = level || 'error'; const { path, source, ln, col, raw } = token; const err = { level, msg, path, source, ln, col, span: raw.length }; errorManager.pushError(err); } function errorAtTokens(msg, firstToken, lastToken, level) { level = level || 'error'; const { path, source, ln, col } = firstToken; const err = { level, msg, path, source, ln, col, span: lastToken.end - firstToken.start }; errorManager.pushError(err); } function errorAfterToken(msg, token, level) { level = level || 'error'; const { path, source, ln, col, raw } = token; const err = { level, msg, path, source, ln, col: col + raw.length, span: 1 }; errorManager.pushError(err); } class ErrorManager { constructor() { this.errorStack = []; this.fileCache = {}; } pushError(err) { this.errorStack.push(err); } dumpAllAndExit() { this.dumpErrors(); process.exit(1); } dumpInternal(err) { const { level, msg, path, source, ln, col, span } = err; const color = colorTable[level]; if (!this.fileCache[path]) { this.fileCache[path] = source.split('\n'); } const line = this.fileCache[path][ln - 1]; const padding = 6; let lineNumber = `${' '.repeat(padding)}${ln}`; lineNumber = lineNumber.substring(lineNumber.length - padding); console.error(`${path}:${ln}:${col}: ${bright}${color}${level}:${reset} ${msg}${reset}`); console.error(`${lineNumber} | ${line}`); console.error(`${' '.repeat(padding + 1)}|${' '.repeat(col)}${color}^${'~'.repeat(span - 1)}${reset}`); } dumpErrors() { if (this.errorStack.length === 0) { return false; } let hasError = false; this.errorStack.forEach(err => { hasError = err.level === 'error' || hasError; this.dumpInternal(err); }); return hasError; } }; const errorManager = new ErrorManager(); exports.errorManager = errorManager; exports.errorAtToken = errorAtToken; exports.errorAtTokens = errorAtTokens; exports.errorAfterToken = errorAfterToken;
// Import styles import '../styles/styles.scss';
export const createReplyRequestSuccess = { data: { CreateOrUpdateReplyRequest: { replyRequestCount: 1, }, }, };
const { request, response } = require('express') const neDB = require('../configurations/database') const api = {} api.findAll = (request, response) => { neDB.find({}).sort({ name: 1}).exec((exception, cards) => { if(exception) { const setence = 'Could not list the cards!' console.log(setence, exception) response.status(exception) response.json({ 'mensagem': setence }) } response.json(cards) }) } api.save = (request, response) => { const canonical= request.body neDB.insert(canonical, (exception, card) => { if(exception) { const setence = "Could not list the cards!" console.log(setence, exception) response.status(exception.status | 400) response.json({ 'mensagem': setence }) } response.status(201) response.json(card) }) } api.delete = (request, response) => { card.findByIdAndDelete(request.params.id) .then((card) => { if(!card) { return response.status(404).send({ message: `Card Not Found ${request.params.id}`}) } response.status(200).send({ message: `Card deleted successfully `, card}) }).catch((err) => { if (err.kind === 'ObjectId') { return response.status(404).send({ message: `Card not found ${request.params.id}`}) } return response.status(500).send({ message: `Error ${request.params.id}`}) }) } module.exports = api
import React, { Component } from "react"; import {BrowserRouter, Switch, Route} from "react-router-dom"; import Header from "./components/Header"; import Landing from "./components/Landing"; import Carousel from "./components/Carousel"; import InfiniteScroll from "./components/InfiniteScroll"; import LoadingAnimations from "./components/LoadingAnimations"; class App extends Component { render() { return ( <BrowserRouter> <div className="main-flex-column-container"> <Header /> <Switch> <Route exact path="/" component={Landing} /> <Route exact path="/carousel" component={Carousel} /> <Route exact path="/infinite-scroll" component={InfiniteScroll} /> <Route exact path="/loading-animations" component={LoadingAnimations} /> </Switch> </div> </BrowserRouter> ); } } export default App;
angular.module('adobesdr').controller('mainCtrl', function ($scope, mainService) { $scope.userRequestObject = {}; $scope.userRequest = function (isValid) { if (isValid) { console.log('FORM VALID'); console.log($scope.userRequestObject); mainService.getAdobeReports($scope.userRequestObject).then(function (response) { console.log(response); }) } else { console.log('FORM NOT VALID - ERROR'); } }; });
var menuButton = document.querySelector(".page-header__navigation-toggle"); var menu = document.querySelector(".page-header__main-navigation"); var header = document.querySelector(".page-header"); document.addEventListener("DOMContentLoaded", function () { menuButton.classList.remove("page-header__navigation-toggle--open"); menuButton.classList.add("page-header__navigation-toggle--closed"); menu.classList.remove("page-header__main-navigation--open"); menu.classList.add("page-header__main-navigation--closed"); header.classList.remove("page-header--open"); header.classList.add("page-header--closed"); }); menuButton.addEventListener("click", function (evt) { evt.preventDefault(); menuButton.classList.toggle("page-header__navigation-toggle--open"); menuButton.classList.toggle("page-header__navigation-toggle--closed"); menu.classList.toggle("page-header__main-navigation--open"); menu.classList.toggle("page-header__main-navigation--closed"); header.classList.toggle("page-header--open"); header.classList.toggle("page-header--closed"); });
import Component from './DeleteContentButton.component' import mutation from '../../../apollo/mutations/deleteContent' import { compose } from 'react-apollo' export default compose(mutation)(Component)
import firebase from './Config.js' import Brewery from './Brewery.js' //api pull from open brewery database export default { getBreweries(query = "louisville"){ return fetch (`https://api.openbrewerydb.org/breweries/search?query=${query}`) .then(res =>res.json()); } }
module.exports = function (router, api) { router.get('/enemies/', function (req, res) { api.getEnemies(function (enemies) { setHeaders(res); res.end(JSON.stringify(enemies)); }); }); router.get("/enemies/:name([a-z-]+)", function (req, res) { api.getEnemy(req.params.name.replace(/-/g, ' '), function (enemy) { setHeaders(res); if (enemy == null) { sendResourceNotFound(res); } else { res.end(JSON.stringify(enemy)); } }); }); router.get('/heroes/', function (req, res) { api.getHeroes(function (heroes) { setHeaders(res); res.end(JSON.stringify(heroes)); }) }); router.get('/trinkets/', function (req, res) { api.getTrinkets(function (trinkets) { setHeaders(res); res.end(JSON.stringify(trinkets)); }); }); router.get("/trinkets/:name([a-z-]+)", function (req, res) { api.getTrinket(req.params.name, function (trinket) { setHeaders(res); if (trinket == null) { sendResourceNotFound(res); } else { res.end(JSON.stringify(trinket)); } }); }); router.get('/weapons/', function (req, res) { api.getWeapons(function (weapons) { setHeaders(res); res.end(JSON.stringify(weapons)); }); }); router.get("/weapons/:name([a-z-]+)", function (req, res) { api.getWeaponsByClass(req.params.name, function (trinket) { setHeaders(res); if (trinket == null) { sendResourceNotFound(res); } else { res.end(JSON.stringify(trinket)); } }); }); router.get("/weapons/:name([a-z-]+)/traits", function (req, res) { api.getWeaponTraitSets(req.params.name, function (traits) { setHeaders(res); if (traits == null) { sendResourceNotFound(res); } else { res.end(JSON.stringify(traits)); } }); }); }; function setHeaders(res) { res.set("Content-type", "application/json"); res.set("Access-Control-Allow-Origin", "*"); } function sendResourceNotFound(res) { res.status(404).end(JSON.stringify({"error": {"message": "Sorry, that resource does not exist"}})); }
import React from 'react'; import styled from 'styled-components/native'; const ListaItemSwipe = styled.TouchableHighlight` width: 100%; height: 50px; background-color: #FFF; justify-content: center; `; const ListaItemIcon = styled.View` width: 18px; height: 13px; background-color: #FF9933; margin-left: 15px; `; export default (props) => { return ( <ListaItemSwift onPress={props.onDelete} underlayColor="#335CFF"> <ListaItemIcon> </ListaItemIcon> </ListaItemSwift> ); }
$(function () { var count =60, myCountDown; var sendID="#register_send", //获取验证码 registerID="#register_bind",//注册 mobileID="#register_mobile",//手机号输入框 codeID="#register_code",//验证码输入框 pswID="#register_psw", formID="#register_form",//注册表单 url_send="http://127.0.0.102/newlgj_web/index.php/message/index?type=verify&code=0&num=";//验证码后台接口 $(sendID).click(function () { var register_send= $(this).html(); if(register_send=="获取验证码" || register_send=="重新获取"){ goverify(); } }); $(registerID).click(function(){ var mobile = $(mobileID).val(); var authcode = $(codeID).val(); var psw=$(pswID).val(); var message_info = ""; if (mobile==null || $.trim(mobile)=="") { message_info = "手机号不可为空"; }else if (authcode==null || $.trim(authcode)=="") { message_info = "验证码不可为空"; }else if (psw==null || $.trim(psw)=="") { message_info = "密码不可为空"; }else if (!checkverify(codeID)) { message_info = "验证码有误"; }else if (!checkpsw(pswID)) { message_info = "密码有误"; } if (message_info != "") { layer.msg(message_info,{time:1500}); } else { //后台数据? $(formID).submit(); } }); function checkmobile(n){ var reg = /^1[34578]\d{9}$/; return reg.test($(n).val()); } function checkverify(n){ var reg = /^\d{6}$/; return reg.test($(n).val()); } function checkpsw(n) { var reg=/^[a-zA-Z\d]{8,16}$/; return reg.test($(n).val()); } function countDown() { var sendbtn = $(sendID); sendbtn.html("" + count + "s"); count--; if (count == 0) { sendbtn.html("重新获取"); clearInterval(myCountDown); count = 60; } } $.show_error = function(message_info){ layer.msg(message_info,{time:1500}); }; // 发送手机短信验证码 function goverify(){ if(!checkmobile(mobileID)){ $.show_error('手机号码格式有误'); $(mobileID).focus(); return false; } $.ajax({ url : url_send+$(mobileID).val(), type : "POST", dataType : "json", success : function(data){ if(data.msg==true){ $(sendID).html("发送成功"); myCountDown = setInterval(countDown,1000); $(codeID).focus(); }else{ $.show_error('验证码返回错误,请重试!'); } }, beforeSend : function(){ $(sendID).html("正在发送..."); }, error : function(){ $.show_error('验证码返回错误,请重试!'); } }); } });
const fs = require("fs"); const os = require("os"); const path = require("path"); const sync = require("yare-sync"); const esbuild = require("esbuild"); const watch = require("node-watch"); require("colors"); function input() { return new Promise((r) => { process.stdin.once("data", (d) => { r(d); }); }); } const flags = process.argv.splice(2); const shouldwatch = flags.includes("-w") || flags.includes("--watch"); const shouldsync = flags.includes("-s") || flags.includes("--sync"); const switchacc = flags.includes("-a") || flags.includes("--switch-acc"); const usingts = fs.existsSync(path.join(__dirname, "src/main.ts")); const usingjs = fs.existsSync(path.join(__dirname, "src/main.js")); if (!usingjs && !usingts) { console.log("You don't have a main file smh"); process.exit(0); } let mainfile = usingjs ? "src/main.js" : "src/main.ts"; const esbuildConfig = { entryPoints: [mainfile], bundle: true, minify: true, outfile: "dist/bundle.js", treeShaking: true, target: "es2015", }; let acc = null; async function build() { let result = esbuild.buildSync(esbuildConfig); let code = fs.readFileSync(esbuildConfig.outfile, "utf-8"); if (result.errors.length > 0) return console.error("Build failed ):".red.bold); else console.log("Built successfully".green.bold); if (!shouldsync) return; let games = await sync.getGames(acc.user_id); let successful = await sync.sendCode(code, games, acc); if (successful) { console.log("Uploaded your code to these games:".green.bold, games); } else { console.error("Upload to yare failed.".red.bold); } } function login() { return new Promise(async (resolve) => { console.log("Log in to yare to enable yare-sync".bold); console.log("Username:"); let username = ((await input()) + "").split("\n")[0].split("\r")[0]; console.log("Password (SHOWN):"); let password = ((await input()) + "").split("\n")[0].split("\r")[0]; console.log("Trying to log in as".yellow, password); let acc = sync.login(username, password).catch(async (e) => { console.log("Invalid username or password, try again".red.bold); resolve(await login()); }); if (acc) resolve(acc); }); } async function main() { if (shouldsync) { let savedSessionFilePath = path.join( os.tmpdir(), "yare-sync-last-session.json" ); if (fs.existsSync(savedSessionFilePath) && !switchacc) { let savedSessionFile = JSON.parse( fs.readFileSync(savedSessionFilePath, "utf-8") ); console.log("Found previous session".blue); if (sync.verifySession(savedSessionFile)) { console.log("Session was valid! Using that".green); acc = savedSessionFile; } else { console.log("Invalid session".red); } } if (acc === null) { acc = await login(); } console.log("Logged in as".green.bold, acc.user_id, "\n"); fs.writeFileSync(savedSessionFilePath, JSON.stringify(acc), "utf-8"); } if (shouldwatch) { await build(); watch( path.dirname(mainfile), { recursive: true, }, (_, file) => { console.log("File change".yellow, file); build(); } ); } else { await build(); } } main();
export * from './uploadClient' export * from './customFetch'
/** * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ goog.provide('audioCat.action.mode.ChangeEditModeAction'); goog.require('audioCat.action.Action'); goog.require('audioCat.state.editMode.EditModeName'); goog.require('goog.asserts'); /** * An action for changing edit modes. * @param {!audioCat.state.editMode.EditModeManager} editModeManager Maintains * and updates the current edit mode. * @param {!audioCat.ui.message.MessageManager} messageManager Issues requests * to display messages to the user. * @constructor * @extends {audioCat.action.Action} */ audioCat.action.mode.ChangeEditModeAction = function( editModeManager, messageManager) { goog.base(this); /** * @private {!audioCat.state.editMode.EditModeManager} */ this.editModeManager_ = editModeManager; /** * The name of the edit mode we are about to switch into. Or are currently in. * @private {!audioCat.state.editMode.EditModeName} */ this.nextEditModeName_ = editModeManager.getCurrentEditMode().getName(); /** * @private {!audioCat.ui.message.MessageManager} */ this.messageManager_ = messageManager; }; goog.inherits( audioCat.action.mode.ChangeEditModeAction, audioCat.action.Action); /** * Sets the edit mode to switch into next via this action. * @param {!audioCat.state.editMode.EditModeName} editModeName The name of the * edit mode to switch into. */ audioCat.action.mode.ChangeEditModeAction.prototype.setNextEditModeName = function(editModeName) { this.nextEditModeName_ = editModeName; }; /** @override */ audioCat.action.mode.ChangeEditModeAction.prototype.doAction = function() { var editModeManager = this.editModeManager_; // Check if we should even switch modes. var nextEditMode = this.nextEditModeName_; if (editModeManager.getCurrentEditMode().getName() != nextEditMode) { // Actually update the edit mode. editModeManager.setCurrentEditMode(nextEditMode); // Issue a message based on the new edit mode. var message = 'Now, '; var secondPartOfMessage; var editModeNameEnum = audioCat.state.editMode.EditModeName; switch (nextEditMode) { case editModeNameEnum.DUPLICATE_SECTION: secondPartOfMessage = 'click a section to duplicate.'; break; case editModeNameEnum.REMOVE_SECTION: secondPartOfMessage = 'click a section to delete.'; break; case editModeNameEnum.SELECT: secondPartOfMessage = 'drag a section to move.'; break; case editModeNameEnum.SPLIT_SECTION: secondPartOfMessage = 'press and release to split a section.'; break; } goog.asserts.assertString(secondPartOfMessage); message += secondPartOfMessage; this.messageManager_.issueMessage(message); } };
var express = require('express'); var router = express.Router(); var monk = require('monk'); var db = monk('localhost:27017/Sample_Sales', function(err,data){ if(data){ console.log('connected') } else{ console.log('err') } }) var collection = db.get('Sales'); var moment = require('moment'); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); function gettimestamp(currentdate,temp) { var timestamp=currentdate+" "+temp; dateTimeParts=timestamp.split(' '), timeParts=dateTimeParts[1].split(':'), dateParts=dateTimeParts[0].split('-'); var date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]); return date.getTime(); } router.post('/:id/:name/:amount/:date', function(req,res){ var date = req.params.date; var testtime = moment().format('hh:mm'); var timestamp = gettimestamp(date,testtime); var data = { id:req.params.id, name:req.params.name, amount:parseInt(req.params.amount), date:req.params.date, weekofyear:moment(timestamp).format('w'), year:moment(timestamp).format('YYYY'), month:moment(timestamp).format('MMM'), time:moment().format('hh:mm:ss'), hourtime:moment().format('hh') } collection.insert(data,function(err,docs){ if(err){ res.send(err) } else{ res.send(docs) } }) }) router.get('/:id/:name/:amount/:date', function(req,res){ // console.log(req.params) var date = req.params.date; var testtime = moment().format('hh:mm'); var timestamp = gettimestamp(date,testtime); var data = { id:req.params.id, name:req.params.name, amount:parseInt(req.params.amount), date:req.params.date, weekofyear:moment(timestamp).format('w'), year:moment(timestamp).format('YYYY'), month:moment(timestamp).format('MMM'), time:moment().format('hh:mm:ss'), hourtime:moment().format('hh') } collection.insert(data,function(err,docs){ if(err){ res.send(err) } else{ res.send(docs) } }) }) router.get('/:daily', function(req,res){ if(req.params.daily == 'daily'){ var date = moment().format('DD-MM-YYYY') collection.aggregate([{$match:{"date":date}},{$group:{_id:{hourtime:"$hourtime"},Total_Amount:{$sum:"$amount"}}}],function(err,docs){ if(err){ res.send(err) } else{ res.send(docs) } }) } else if(req.params.daily == 'weekly'){ var week = moment().format('w') collection.aggregate([{$match:{"weekofyear":week}},{$group:{_id:{Date:"$date"},Total_Amount:{$sum:"$amount"}}}],function(err,docs){ if(err){ res.send(err) } else{ res.send(docs) } }) } else if(req.params.daily == 'monthly'){ var year = moment().format('YYYY') var month = moment().format('MMM') collection.aggregate([{$match:{"month":month,"year":year}},{$group:{_id:{Date:"$date"},Total_Amount:{$sum:"$amount"}}}],function(err,docs){ if(err){ res.send(err) } else{ res.send(docs) } }) } else{ res.send("Worng Parameter") } }) module.exports = router;
import React from "react"; import style from "./Header.css" const Footer = () =>{ return( <div className={style.footer}> <span>@Copyright 1223602915@qq.com</span> </div> ) } export default Footer;
'use strict' let kDirReadPromisified let kDirClosePromisified let kHandle const ddFhSym = Symbol('ddFileHandle') const tagMakers = { open: createOpenTags, close: createCloseTags, readFile: createReadFileTags, writeFile: createWriteFileTags, appendFile: createAppendFileTags, access: createPathTags, copyFile: createCopyFileTags, stat: createPathTags, lstat: createPathTags, fstat: createFDTags, readdir: createPathTags, opendir: createPathTags, read: createFDTags, write: createFDTags, writev: createFDTags, chmod: createChmodTags, lchmod: createChmodTags, fchmod: createFchmodTags, chown: createChownTags, lchown: createChownTags, fchown: createFchownTags, realpath: createPathTags, readlink: createPathTags, unlink: createPathTags, symlink: createCopyFileTags, link: createCopyFileTags, rmdir: createPathTags, rename: createCopyFileTags, fsync: createFDTags, fdatasync: createFDTags, mkdir: createPathTags, truncate: createPathTags, ftruncate: createFDTags, utimes: createPathTags, futimes: createFDTags, mkdtemp: createPathTags } const promisifiable = ['read', 'readv', 'write', 'writev'] const orphanable = false function createWrapCreateReadStream (config, tracer) { return function wrapCreateReadStream (createReadStream) { return function createReadStreamWithTrace (path, options) { if (!hasParent(tracer)) { return createReadStream.apply(this, arguments) } const tags = makeFSFlagTags('ReadStream', path, options, 'r', config, tracer) return tracer.trace('fs.operation', { tags, orphanable }, (span, done) => { const stream = createReadStream.apply(this, arguments) stream.once('end', done) stream.once('error', done) return stream }) } } } function createWrapCreateWriteStream (config, tracer) { return function wrapCreateWriteStream (createWriteStream) { return function createWriteStreamWithTrace (path, options) { const tags = makeFSFlagTags('WriteStream', path, options, 'w', config, tracer) return tracer.trace('fs.operation', { tags, orphanable }, (span, done) => { const stream = createWriteStream.apply(this, arguments) stream.once('finish', done) stream.once('error', done) return stream }) } } } function createWrapExists (config, tracer) { return function wrapExists (exists) { const existsWithTrace = function existsWithTrace (path, cb) { if (typeof cb !== 'function') { return exists.apply(this, arguments) } const tags = makeFSTags('exists', path, null, config, tracer) return tracer.trace('fs.operation', { tags, orphanable }, (span, done) => { arguments[1] = function (result) { done() cb.apply(this, arguments) } return exists.apply(this, arguments) }) } copySymbols(exists, existsWithTrace) return existsWithTrace } } function createWrapDirRead (config, tracer, sync) { const name = sync ? 'dir.readSync' : 'dir.read' return function wrapDirRead (read) { function options () { const tags = makeFSTags(name, this.path, null, config, tracer) return { tags, orphanable } } return tracer.wrap('fs.operation', options, read, true) } } function createWrapDirClose (config, tracer, sync) { const name = sync ? 'dir.closeSync' : 'dir.close' return function wrapDirClose (close) { function options () { const tags = makeFSTags(name, this.path, null, config, tracer) return { tags, orphanable } } return tracer.wrap('fs.operation', options, close, true) } } function createWrapDirAsyncIterator (config, tracer, instrumenter) { return function wrapDirAsyncIterator (asyncIterator) { return function asyncIteratorWithTrace () { if (!kDirReadPromisified) { const keys = Reflect.ownKeys(this) for (const key of keys) { if (kDirReadPromisified && kDirClosePromisified) break if (typeof key !== 'symbol') continue if (!kDirReadPromisified && getSymbolName(key).includes('kDirReadPromisified')) { kDirReadPromisified = key } if (!kDirClosePromisified && getSymbolName(key).includes('kDirClosePromisified')) { kDirClosePromisified = key } } } instrumenter.wrap(this, kDirReadPromisified, createWrapDirRead(config, tracer)) instrumenter.wrap(this, kDirClosePromisified, createWrapKDirClose(config, tracer, instrumenter)) return asyncIterator.call(this) } } } function createWrapKDirClose (config, tracer, instrumenter) { return function wrapKDirClose (kDirClose) { return function kDirCloseWithTrace () { const tags = makeFSTags('dir.close', this.path, null, config, tracer) return tracer.trace('fs.operation', { tags, orphanable }, (span) => { const p = kDirClose.call(this) const unwrapBoth = () => { instrumenter.unwrap(this, kDirReadPromisified) instrumenter.unwrap(this, kDirClosePromisified) } p.then(unwrapBoth, unwrapBoth) return p }) } } } function createOpenTags (resourceName, config, tracer) { return function openTags (path, flag, mode) { if (!flag || typeof flag === 'function') { flag = null } return makeFSFlagTags(resourceName, path, { flag }, 'r', config, tracer) } } function createCloseTags (resourceName, config, tracer) { return function closeTags (fd) { if (typeof fd === 'undefined' && this && this[ddFhSym]) { fd = this[ddFhSym].fd } if (typeof fd !== 'number' || !Number.isInteger(fd)) { return } return makeFSTags(resourceName, fd, null, config, tracer) } } function createReadFileTags (resourceName, config, tracer) { return function readFileTags (path, options) { return makeFSFlagTags(resourceName, path, options, 'r', config, tracer) } } function createWriteFileTags (resourceName, config, tracer) { return function writeFileTags (path, data, options) { return makeFSFlagTags(resourceName, path, options, 'w', config, tracer) } } function createAppendFileTags (resourceName, config, tracer) { return function appendFileTags (path, data, options) { return makeFSFlagTags(resourceName, path, options, 'a', config, tracer) } } function createCopyFileTags (resourceName, config, tracer) { return function copyFileTags (src, dest, flag) { return makeFSTags(resourceName, { src, dest }, null, config, tracer) } } function createChmodTags (resourceName, config, tracer) { return function chmodTags (fd, mode) { const tags = makeFSTags(resourceName, fd, null, config, tracer) tags['file.mode'] = mode.toString(8) return tags } } function createFchmodTags (resourceName, config, tracer) { return function fchmodTags (fd, mode) { if (typeof this === 'object' && this !== null && this.fd) { mode = fd fd = this.fd } const tags = makeFSTags(resourceName, fd, null, config, tracer) if (mode) { tags['file.mode'] = mode.toString(8) } return tags } } function createPathTags (resourceName, config, tracer) { return function pathTags (path) { return makeFSTags(resourceName, path, null, config, tracer) } } function createFDTags (resourceName, config, tracer) { return function fdTags (fd) { if (typeof this === 'object' && this !== null && this.fd) { fd = this.fd } return makeFSTags(resourceName, fd, null, config, tracer) } } function createChownTags (resourceName, config, tracer) { return function chownTags (fd, uid, gid) { const tags = makeFSTags(resourceName, fd, null, config, tracer) if (typeof uid === 'number') { tags['file.uid'] = uid.toString() } if (typeof gid === 'number') { tags['file.gid'] = gid.toString() } return tags } } function createFchownTags (resourceName, config, tracer) { return function fchownTags (fd, uid, gid) { if (typeof this === 'object' && this !== null && this.fd) { gid = uid uid = fd fd = this.fd } const tags = makeFSTags(resourceName, fd, null, config, tracer) if (typeof uid === 'number') { tags['file.uid'] = uid.toString() } if (typeof gid === 'number') { tags['file.gid'] = gid.toString() } return tags } } function getSymbolName (sym) { return sym.description || sym.toString() } function hasParent (tracer) { return !!tracer.scope().active() } function createWrapCb (tracer, config, name, tagMaker) { const makeTags = tagMaker(name, config, tracer) return function wrapFunction (fn) { return tracer.wrap('fs.operation', function () { if (typeof arguments[arguments.length - 1] !== 'function') { return } const tags = makeTags.apply(this, arguments) return tags ? { tags, orphanable } : { orphanable } }, fn, true) } } function createWrap (tracer, config, name, tagMaker) { const makeTags = tagMaker(name, config, tracer) return function wrapSyncFunction (fn) { return tracer.wrap('fs.operation', function () { const tags = makeTags.apply(this, arguments) return tags ? { tags, orphanable } : { orphanable } }, fn, true) } } function makeFSFlagTags (resourceName, path, options, defaultFlag, config, tracer) { const tags = makeFSTags(resourceName, path, options, config, tracer) if (tags) { let flag = defaultFlag if (typeof options === 'object' && options !== null) { if (options.flag) { flag = options.flag } else if (options.flags) { flag = options.flags } } tags['file.flag'] = flag return tags } } function makeFSTags (resourceName, path, options, config, tracer) { path = options && typeof options === 'object' && 'fd' in options ? options.fd : path const tags = { 'component': 'fs', 'span.kind': 'internal', 'resource.name': resourceName, 'service.name': config.service || `${tracer._service}-fs` } switch (typeof path) { case 'object': { if (path === null) return const src = 'src' in path ? path.src : null const dest = 'dest' in path ? path.dest : null if (src || dest) { tags['file.src'] = src tags['file.dest'] = dest } else { tags['file.path'] = path } break } case 'string': { tags['file.path'] = path break } case 'number': { tags['file.descriptor'] = path.toString() break } } return tags } function copySymbols (from, to) { const props = Object.getOwnPropertyDescriptors(from) const keys = Reflect.ownKeys(props) for (const key of keys) { if (typeof key !== 'symbol' || to.hasOwnProperty(key)) continue Object.defineProperty(to, key, props[key]) } } function getFileHandlePrototype (fs) { return fs.promises.open(__filename, 'r') .then(fh => { if (!kHandle) { kHandle = Reflect.ownKeys(fh).find(key => typeof key === 'symbol' && key.toString().includes('kHandle')) } fh.close() return Object.getPrototypeOf(fh) }) } function patchClassicFunctions (fs, tracer, config) { for (const name in fs) { if (!fs[name]) continue const tagMakerName = name.endsWith('Sync') ? name.substr(0, name.length - 4) : name const original = fs[name] if (tagMakerName in tagMakers) { const tagMaker = tagMakers[tagMakerName] if (name.endsWith('Sync')) { this.wrap(fs, name, createWrap(tracer, config, name, tagMaker)) } else { this.wrap(fs, name, createWrapCb(tracer, config, name, tagMaker)) } if (name in promisifiable) { copySymbols(original, fs[name]) } } } } function patchFileHandle (fs, tracer, config) { getFileHandlePrototype(fs).then((fileHandlePrototype) => { for (const name of Reflect.ownKeys(fileHandlePrototype)) { if (typeof name !== 'string' || name === 'constructor' || name === 'fd' || name === 'getAsyncId') { continue } let tagMaker const fName = 'f' + name if (fName in tagMakers) { tagMaker = tagMakers[fName] } else { tagMaker = createFDTags } const instrumenter = this const desc = Reflect.getOwnPropertyDescriptor(fileHandlePrototype, kHandle) if (!desc || !desc.get) { Reflect.defineProperty(fileHandlePrototype, kHandle, { get () { return this[ddFhSym] }, set (h) { this[ddFhSym] = h instrumenter.wrap(this, 'close', createWrap(tracer, config, 'filehandle.close', tagMakers.close)) }, configurable: true }) } this.wrap(fileHandlePrototype, name, createWrap(tracer, config, 'filehandle.' + name, tagMaker)) } }) } function patchPromiseFunctions (fs, tracer, config) { for (const name in fs.promises) { if (name in tagMakers) { const tagMaker = tagMakers[name] this.wrap(fs.promises, name, createWrap(tracer, config, 'promises.' + name, tagMaker)) } } } function patchDirFunctions (fs, tracer, config) { this.wrap(fs.Dir.prototype, 'close', createWrapDirClose(config, tracer)) this.wrap(fs.Dir.prototype, 'closeSync', createWrapDirClose(config, tracer, true)) this.wrap(fs.Dir.prototype, 'read', createWrapDirRead(config, tracer)) this.wrap(fs.Dir.prototype, 'readSync', createWrapDirRead(config, tracer, true)) this.wrap(fs.Dir.prototype, Symbol.asyncIterator, createWrapDirAsyncIterator(config, tracer, this)) } function unpatchClassicFunctions (fs) { for (const name in fs) { if (!fs[name]) continue const tagMakerName = name.endsWith('Sync') ? name.substr(0, name.length - 4) : name if (tagMakerName in tagMakers) { this.unwrap(fs, name) } } } function unpatchFileHandle (fs) { getFileHandlePrototype(fs).then(fileHandlePrototype => { for (const name of Reflect.ownKeys(fileHandlePrototype)) { if (typeof name !== 'string' || name === 'constructor' || name === 'fd' || name === 'getAsyncId') { continue } this.unwrap(fileHandlePrototype, name) } delete fileHandlePrototype[kHandle] }) } function unpatchPromiseFunctions (fs) { for (const name in fs.promises) { if (name in tagMakers) { this.unwrap(fs.promises, name) } } } function unpatchDirFunctions (fs) { this.unwrap(fs.Dir.prototype, 'close') this.unwrap(fs.Dir.prototype, 'closeSync') this.unwrap(fs.Dir.prototype, 'read') this.unwrap(fs.Dir.prototype, 'readSync') this.unwrap(fs.Dir.prototype, Symbol.asyncIterator) } module.exports = { name: 'fs', patch (fs, tracer, config) { patchClassicFunctions.call(this, fs, tracer, config) if (fs.promises) { patchFileHandle.call(this, fs, tracer, config) patchPromiseFunctions.call(this, fs, tracer, config) } if (fs.Dir) { patchDirFunctions.call(this, fs, tracer, config) } this.wrap(fs, 'createReadStream', createWrapCreateReadStream(config, tracer)) this.wrap(fs, 'createWriteStream', createWrapCreateWriteStream(config, tracer)) this.wrap(fs, 'existsSync', createWrap(tracer, config, 'existsSync', createPathTags)) this.wrap(fs, 'exists', createWrapExists(config, tracer)) }, unpatch (fs) { unpatchClassicFunctions.call(this, fs) if (fs.promises) { unpatchFileHandle.call(this, fs) unpatchPromiseFunctions.call(this, fs) } if (fs.Dir) { unpatchDirFunctions.call(this, fs) } this.unwrap(fs, 'createReadStream') this.unwrap(fs, 'createWriteStream') this.unwrap(fs, 'existsSync') this.unwrap(fs, 'exists') } } /** TODO fs functions: unwatchFile watch watchFile */
var Solution = function(nums) { this.set = nums this.original = Array.from(nums) }; Solution.prototype.reset = function() { return this.original }; Solution.prototype.shuffle = function() { let newSet = new Set(this.set) let retArray = []; };
function SaveReceipt() { if (X.getCmp("TypeId").value == "1" || X.getCmp("TypeId").value == "2" || X.getCmp("TypeId").value == "4" || X.getCmp("TypeId").value == "5") { data = this.GetGridItemsValue(); X.getCmp("Items").setValue(data); } if (ValidateReceipt()) { document.forms["saveReceiptForm"].submit(); } } function ValidateReceipt() { message = ""; message = ValidateField("OfficeList", message); message = ValidateField("Contract", message); message = ValidateClient(message); message = ValidateField("TaxSystemList", message); message = ValidateField("TaxList", message); message = ValidateField("Address", message); message = ValidateItems("GridItems", message); message = ValidateField("Total", message); if (message != "") { Ext.Msg.alert("Предупреждение", message); return false; } return true; } function ValidateClient(message) { field1 = X.getCmp("Email"); field2 = X.getCmp("Phone"); if (field1 != null && field2 != null) { if (field1.value.trim() == "" && field2.value.trim() == "") { if (message != "") { message = message + "<br/>"; } message = message + 'Заполните одно из полей "' + field1.fieldLabel + '" или "' + field2.fieldLabel + '"'; } } return message; } function ValidateItems(field, message) { isValid = true; gridPanel = X.getCmp("GridItems"); if (gridPanel != null) { if (gridPanel.store.data.items.length == 0) { isValid = false; } else { Ext.each(gridPanel.store.data.items, function (item) { if (item.data["name"].trim() == "") isValid = false; if (item.data["tax"].trim() == "") isValid = false; }); } } if (isValid == false) { if (message != "") { message = message + "<br/>"; } message = message + 'Заполните поле "Позиции фискального документа"'; } return message; } function GetGridItemsValue() { var data = []; gridPanel = X.getCmp("GridItems"); Ext.each(gridPanel.store.data.items, function (item) { data.push(item.data) }) return JSON.stringify(data, ["name", "price", "quantity", "sum", "tax", "taxsum"]); } function AddGridRow() { index = 0; gridPanel = X.getCmp("GridItems"); Ext.each(gridPanel.store.data.items, function (item) { if (item.data["id"] > index); { index = item.data["id"]; } }) Ext.define("ReceiptItem", { extend: "Ext.data.Model", fields: [ { name: "id", type: "string" }, { name: "name", type: "string" }, { name: "price", type: "float" }, { name: "quantity", type: "float" }, { name: "sum", type: "float" }, { name: "tax", type: "string" }, { name: "taxsum", type: "float" } ] }); var receiptItem = Ext.create("ReceiptItem", { id: index + 1 }); gridPanel.store.add(receiptItem); gridPanel.getSelectionModel().select(receiptItem); } function DeleteGridRow() { gridPanel = X.getCmp("GridItems"); if (gridPanel.getSelectionModel().selected.length > 0) { row = gridPanel.getSelectionModel().selected.items[0]; gridPanel.store.remove(row); } this.SetTotal(); } function UpdateGrid() { gridPanel = X.getCmp("GridItems"); row = gridPanel.getSelectionModel().selected.items[0]; row.data["sum"] = row.data["price"] * row.data["quantity"]; if (row.data["tax"] == "none") row.data["taxsum"] = row.data["sum"] * 0; if (row.data["tax"] == "vat0") row.data["taxsum"] = row.data["sum"] * 0; if (row.data["tax"] == "vat10") row.data["taxsum"] = row.data["sum"] * 10 / 110; if (row.data["tax"] == "vat18") row.data["taxsum"] = row.data["sum"] * 18 / 118; gridPanel.view.refresh(); this.SetTotal(); } function TaxColumnRenderer(value) { store = X.getCmp("ItemTaxList").getStore(); index = store.find("Code", value); if (index != -1) { record = store.getAt(index); return record.data["Name"]; } return ""; }; function SetTotal() { total = 0 gridPanel = X.getCmp("GridItems"); Ext.each(gridPanel.store.data.items, function (item) { sum = item.data["sum"]; total = total + sum; }) X.getCmp("Total").setValue(total); }
const chai = require("chai"); const chaiHttp = require("chai-http"); const mongoose = require('mongoose'); const {Album} = require('../models'); const {app, runServer, closeServer} = require('../server'); const {TEST_DATABASE_URL} = require('../config'); const expect = chai.should(); chai.use(chaiHttp); function seedEntryData() { console.info('seeding album data'); const seedData = [ { bandName: "Kiss", albumName: "Hotter Than Hell", releaseYear: "1974", format: "8 track", notes: "second album from the same year"}, { bandName: "Van Halen", albumName: "1984", releaseYear: "1984", format: "vinyl", notes: "biggest but last tour with original lineup"}, { bandName: "Judas Priest", albumName: "Turbo", releaseYear: "1986", format: "cassette", notes: "No explanation needed"}, { bandName: "Metallica", albumName: "Ride The Lightning", releaseYear: "1984", format: "cassette", notes: "Picking up steam overseas too at this point"}, { bandName: "Iron Maiden", albumName: "Number Of The Beast", releaseYear: "1982", format: "cassette", notes: "Major US breakthrough"}, { bandName: "Black Sabbath", albumName: "Paranoid", releaseYear: "1971", format: "vinyl", notes: "two albums in the same year"}, ]; return Album.insertMany(seedData); } function tearDownDb() { console.warn('Deleting database'); return mongoose.connection.dropDatabase(); } describe("Do I Have That Album app", function() { before(function() { return runServer(TEST_DATABASE_URL); }); beforeEach(function () { return seedEntryData(); }); afterEach(function () { return tearDownDb(); }); after(function() { return closeServer(); }); it("should return index html", function() { return chai .request(app) .get("/") .then(res => { res.should.have.status(200); res.should.be.html; }); }); describe('GET endpoint', function() { it('should return all albums', function() { let res; return chai.request(app) .get('/albums') .then(_res => { res = _res; res.should.have.status(200); res.body.should.have.lengthOf.at.least(1); return Album.count(); }) .then(count => { res.body.should.have.lengthOf(count); }); }); it('should return albums with right fields', function() { let resAlbum; return chai.request(app) .get('/albums') .then(function (res) { res.should.have.status(200); res.should.be.json; res.body.should.be.a('array'); res.body.should.have.lengthOf.at.least(1); res.body.forEach(function (post) { post.should.be.a('object'); post.should.include.keys('id', 'bandName', 'albumName', 'releaseYear', 'format', 'notes', 'dateAdded'); }); // just check one of the posts that its values match with those in db // and we'll assume it's true for rest resAlbum = res.body[0]; return Album.findById(resAlbum.id); }) .then(album => { resAlbum.bandName.should.equal(album.bandName); resAlbum.albumName.should.equal(album.albumName); resAlbum.releaseYear.should.equal(album.releaseYear); resAlbum.format.should.equal(album.format); }); }); it('should return 5 most recent albums', function() { let res; return chai.request(app) .get('/recent') .then(_res => { res = _res; res.should.have.status(200); res.body.should.have.lengthOf.at.least(5); }) }); it('should return albums from a specific band', function() { let band = "Motorhead"; let res; return chai.request(app) .get('/bands/' + band) .then(_res => { res = _res; res.should.have.status(200); }) }); it('should return an array of band names', function() { return chai.request(app) .get('/bands') .then(_res => { res = _res; res.should.have.status(200); }) }); }); describe('POST endpoint', function() { it('should add a new album', function() { const newAlbum = { bandName: "Kiss", albumName: "Love Gun", releaseYear: "1977", format: "8 track", notes: "I have the painting too" }; return chai.request(app) .post('/albums') .send(newAlbum) .then(function (res) { res.should.have.status(201); res.should.be.json; res.body.should.be.a('object'); res.body.should.include.keys('id', 'bandName', 'albumName', 'releaseYear', 'format', 'notes'); // cause Mongo should have created id on insertion res.body.id.should.not.be.null; res.body.bandName.should.equal(newAlbum.bandName); res.body.albumName.should.equal(newAlbum.albumName); res.body.releaseYear.should.equal(newAlbum.releaseYear); res.body.format.should.equal(newAlbum.format); res.body.notes.should.equal(newAlbum.notes); return Album.findById(res.body.id); }) .then(function (post) { post.bandName.should.equal(newAlbum.bandName); post.albumName.should.equal(newAlbum.albumName); post.releaseYear.should.equal(newAlbum.releaseYear); post.format.should.equal(newAlbum.format); post.notes.should.equal(newAlbum.notes); }); }); }); describe('PUT endpoint', function() { it('update an album', function() { const updateAlbum = { bandName: "Motorhead", albumName: "Ace Of Spades", releaseYear: "1981", format: "LP", notes: "major US break through" }; return Album .findOne() .then(album => { updateAlbum.id = album.id; return chai.request(app) .put(`/albums/${album.id}`) .send(updateAlbum); }) .then(res => { res.should.have.status(204); return Album.findById(updateAlbum.id); }) .then(album => { album.bandName.should.equal(updateAlbum.bandName); album.albumName.should.equal(updateAlbum.albumName); album.releaseYear.should.equal(updateAlbum.releaseYear); album.format.should.equal(updateAlbum.format); album.notes.should.equal(updateAlbum.notes); }); }); }); describe('DELETE endpoint', function() { it('delete an album by id', function() { let album; return Album .findOne() .then(_album => { album = _album; return chai.request(app).delete(`/albums/${album.id}`); }) .then(res => { res.should.have.status(204); return Album.findById(album.id); }) }); }); });
#!/usr/bin/env node // require('yargs') // eslint-disable-line // .command('serve [port]', 'start the server', (yargs) => { // yargs // .positional('port', { // describe: 'port to bind on', // default: 5000 // }) // }, (argv) => { // if (argv.verbose) console.info(`start server on :${argv.port}`) // serve(argv.port) // }) // .option('verbose', { // alias: 'v', // type: 'boolean', // description: 'Run with verbose logging' // }) // .argv // const spawn = require('cross-spawn'); // // Spawn NPM asynchronously // const child = spawn('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); // // Spawn NPM synchronously // const result = spawn.sync('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); var esprima = require('esprima'); var program = 'const answer = 42'; console.log(esprima.tokenize(program));
let cl = console.log /*var time = new Date() var now = time.toString();*/ // console.log(time.toString()) cl(new Date().toString()) function showTime() { let now = new Date().toString() let left = /2017\s/, right = /GMT/; left.exec(now) now = RegExp.rightContext; right.exec(now) cl(RegExp.leftContext) } showTime() //17:20:07 // cl(RegExp.rightContext) //+0800 (中国标准时间)
const { longestdynasty } = require('./LongestDynaFunctions'); const dynastyResign = [ { "San Dynasty" : "MXLI", }, { "Viloria Dynasty" : "MCCCIIII", }, { "Tan Dynasty" : "MCCCXCVIII", }, { "Bon Dynasty" : "MCDXLV", }, { "Maiko Dynasty" : "MDCLXIV", }, { "Paul Dynasty" : "MCMXLIX", }, { "Andre Dynasty" : "MMMXICX", } ] console.log(longestdynasty(dynastyResign))// tan dynasty
import { CLEAR_DATA, MATCH_GET_ALL_FAILURE, MATCH_GET_ALL_REQUEST, MATCH_GET_ALL_SUCCESS, MATCH_UPDATE_FAILURE, MATCH_UPDATE_REQUEST, MATCH_UPDATE_SUCCESS, } from '../actions'; const defaultState = { isFetching: false, isUpdating: false, list: [], }; const matches = (state = defaultState, action) => { switch (action.type) { case MATCH_GET_ALL_REQUEST: return { ...state, isFetching: true }; case MATCH_GET_ALL_SUCCESS: return { ...state, isFetching: false, list: action.response.data }; case MATCH_GET_ALL_FAILURE: return { ...state, isFetching: false, error: action.error }; case MATCH_UPDATE_REQUEST: return { ...state, isUpdating: true }; case MATCH_UPDATE_SUCCESS: if (action.status === 2) { return { ...state, isUpdating: false, list: state.list.filter((m) => m.id !== action.id) }; } const updatedList = state.list.map((m) => (m.id === action.response.data.id ? action.response.data : m)); return { ...state, isUpdating: false, list: updatedList }; case MATCH_UPDATE_FAILURE: return { ...state, isUpdating: false, error: action.error }; case CLEAR_DATA: return { ...state, list: [] }; default: return state; } }; export default matches;
const User = require('./user.model'); const Like = require('./like.model'); const Image = require('./image.model'); const Comment = require('./comment.model'); module.exports = { User, Like, Image, Comment }
// Get dependencies: npm install puppeteer puppeteer-extra puppeteer-extra-plugin-stealth // puppeteer-extra is a drop-in replacement for puppeteer, // it augments the installed puppeteer with plugin functionality const puppeteer = require('puppeteer-extra') // add stealth plugin and use defaults (all evasion techniques) const pluginStealth = require('puppeteer-extra-plugin-stealth') puppeteer.use(pluginStealth()) setInterval( ()=>{ // puppeteer usage as normal puppeteer.launch({ headless: true }).then(async browser => { const page = await browser.newPage() await page.setViewport({ width: 800, height: 600 }) await page.goto('https://www.udemy.com/the-web-developer-bootcamp/') await page.waitFor(5000); await page.screenshot({ path: 'testresult.png', fullPage: true }) await page.waitForSelector('.course-price-text > span + span > span'); const price = await page.$eval('.course-price-text > span + span > span', e => e.innerText); console.log(price); await browser.close() }); },1000);
import Accordion from '@mui/material/Accordion'; import AccordionDetails from '@mui/material/AccordionDetails'; import AccordionSummary from '@mui/material/AccordionSummary'; import AddIcon from '@mui/icons-material/Add'; import Autocomplete from '@mui/material/Autocomplete'; import CloudUploadIcon from '@mui/icons-material/CloudUpload'; import EditIcon from '@mui/icons-material/Edit'; import ExpandMoreIcon from '@mui/icons-material/ExpandMore'; import PropTypes from 'prop-types'; import React from 'react'; import TextField from '@mui/material/TextField'; class Selector extends React.Component { static getDerivedStateFromProps(nextProps, prevState) { if (prevState.new && nextProps.data.length > 0) { const { data } = nextProps; const expandedId = nextProps.expandedId || 0; const expandedByDefault = data[expandedId] || { id: null, label: null }; return { expanded: expandedByDefault.id, selected: expandedByDefault.id, new: false }; } return null; } constructor(props) { super(props); this.state = { expanded: null, subExpanded: null, new: true, }; } firstLevelChange = (panel) => (event, expanded) => { const { handlers } = this.props; const expandedPanel = expanded ? panel : false; handlers[0](expandedPanel); if (panel === 'addProject') { this.setState({ expanded: null, }); } else { this.setState((prevState) => ({ expanded: expandedPanel, selected: expanded ? panel : prevState.expanded, subExpanded: null, })); } return null; }; secondLevelChange = (subPanel) => (event, expanded) => { const { handlers } = this.props; this.setState({ subExpanded: expanded ? subPanel : false, }); handlers[1](subPanel, expanded); }; renderInnerElement = (parent, listSize, data) => (obj, index) => { const { type, label, name, id_project: projectId, } = obj; const { handlers } = this.props; switch (listSize) { case 'large': return ( <Autocomplete id="autocomplete-selector" options={data} getOptionLabel={(option) => option.name} onChange={(event, values) => { handlers[2](parent, values); }} style={{ width: '100%' }} renderInput={(params) => ( <TextField InputProps={params.InputProps} inputProps={params.inputProps} fullWidth={params.fullWidth} label="Escriba el nombre a buscar" placeholder="Seleccionar..." variant="standard" InputLabelProps={{ shrink: true }} /> )} key={`${type}-${label || name}-${index}`} autoHighlight ListboxProps={ { style: { maxHeight: '100px', border: '0px', }, } } /> ); default: return ( <button type="button" key={`${type}-${label || name}-${index}`} name={name} onClick={() => handlers[2](parent, projectId || name)} > {label || name} </button> ); } } render() { const { description, iconClass } = this.props; let { data } = this.props; data = data || []; const { expanded, selected, subExpanded, } = this.state; return ( <div className="selector"> <div className={iconClass} /> <div className="description"> {description} </div> { (data.length > 0) && (data.map((firstLevel) => { const { id, label, disabled, iconOption, detailId, idLabel, } = firstLevel; const options = firstLevel.options || firstLevel.projectsStates || []; return ( <Accordion className={`m0 ${selected === id ? 'selector-expanded' : ''}`} id={idLabel} expanded={expanded === id} disabled={disabled} onChange={this.firstLevelChange(id)} key={id} > <AccordionSummary expandIcon={ (((iconOption === 'add') && <AddIcon />) || ((iconOption === 'upload') && <CloudUploadIcon />) || ((iconOption === 'edit') && <EditIcon />) || (<ExpandMoreIcon />)) } > {label} </AccordionSummary> <AccordionDetails id={detailId} > {options.map((secondLevel) => { const { id: subId, label: subLabel, disabled: subDisabled, } = secondLevel; const subOptions = secondLevel.options || secondLevel.projects || []; return ( <Accordion className="m0" id={subId} expanded={subExpanded === subId} disabled={subDisabled} onChange={this.secondLevelChange(subId)} key={subId} > <AccordionSummary expandIcon={ (((iconOption === 'add') && <AddIcon />) || ((iconOption === 'upload') && <CloudUploadIcon />) || ((iconOption === 'edit') && <EditIcon />) || (<ExpandMoreIcon />)) } > {subLabel} </AccordionSummary> <AccordionDetails className={subOptions.length < 7 ? 'inlineb' : ''}> {subOptions.length < 7 ? subOptions.map(this.renderInnerElement(subId, subOptions.length)) : [{ subOptions }].map(this.renderInnerElement(subId, 'large', subOptions))} </AccordionDetails> </Accordion> ); })} </AccordionDetails> </Accordion> ); }))} </div> ); } } Selector.propTypes = { data: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string, label: PropTypes.string, disabled: PropTypes.bool, expandIcon: PropTypes.node, detailId: PropTypes.string, options: PropTypes.array, })), handlers: PropTypes.arrayOf(PropTypes.func), description: PropTypes.object, iconClass: PropTypes.string, expandedId: PropTypes.number, }; Selector.defaultProps = { data: [], handlers: [], description: {}, iconClass: '', expandedId: 0, }; export default Selector;
$(function () { var expr = /^[a-zA-Z0-9_\.\-]+@[A-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/; $(document).ready(function () { $("#btn-enviar").click(function () { var nombre = $("#nombre_us").val(); var apellido = $("#apellido_us").val(); var email = $("#correo_us").val(); var usuario = $("#nomUsuario_us").val(); var password = $("#password_us").val(); var repitaPassword = $("#repitaPassword_us").val(); var genero = $("input[type = 'radio']:checked"); var fechaNacimineto = $("#fechaNacimiento_us").val(); var pais = $("#nombre_pais option:selected"); var ciudad = $("#nombre_cty option:selected"); var numeroCelular = $("#numeroCelular_us").val(); if (nombre == "") { $("#msg-nombre").fadeIn(); return false; } else { $("#msg-nombre").fadeOut(); if (apellido == "") { $("#msg-apellido").fadeIn(); return false; } else { $("#msg-apellido").fadeOut(); if (email == "" || !expr.test(email)) { $("#msg-correo").fadeIn(); return false; } else { $("#msg-correo").fadeOut(); if (usuario == "") { $("#msg-usuario").fadeIn(); return false; } else { $("#msg-usuario").fadeOut(); if (password == "") { $("#msg-password").fadeIn(); return false; } else { $("#msg-password").fadeOut(); if (repitaPassword == "") { $("#msg-repitaPassword").fadeIn(); return false; } else { $("#msg-repitaPassword").fadeOut(); if (genero.length == 0) { $("#msg-genero").fadeIn(); return false; } else { $("#msg-genero").fadeOut(); if (fechaNacimineto == "") { $("#msg-fechaNacimiento").fadeIn(); return false; } else { $("#msg-fechaNacimiento").fadeOut(); if (pais.val() == "") { $("#msg-pais").fadeIn(); return false; } else { $("#msg-pais").fadeOut(); if (ciudad.val() == "") { $("#msg-ciudad").fadeIn(); return false; } else { $("#msg-ciudad").fadeOut(); if (numeroCelular == "") { $("#msg-numeroCelular").fadeIn(); return false; } else { $("#msg-numeroCelular").fadeOut(); } } } } } } } } } } } }); }); $("#boton-login").on(function (){ window.location.href="perfil.jsp"; }); });
/* * 详情页主Reducer */ import utils from '../../../../lib/util'; function stockDetailReducer(state = { newsOnLoading: false, // symbol: document.getElementById('J_data').attributes['data-symbol'].value, newsDetail: { body_chn: '', body_eng: '', body_html: '', date: '', ranking: '', sentiment: '', source: '', symbol: '', time: '', title: '', uri: '', url: '' } }, action) { switch (action.type) { case 'GET_STOCK_NEWS_DETAIL': return Object.assign({}, state, { newsDetail: action.newsDetail }); case 'BEGIN_NEWS_LOADING': return Object.assign({}, state, { newsOnLoading: true }); case 'FINISH_NEWS_LOADING': return Object.assign({}, state, { newsOnLoading: false }); default: return state; } } export default stockDetailReducer;
export { default as AddProducerForm } from "./add-producer-form";
// 引入依赖 import webpack from 'webpack' import path from 'path' import autoprefixer from 'autoprefixer' import cssImport from 'postcss-import' import cssMixins from 'postcss-mixins' import cssExtend from 'postcss-extend' import conditionals from 'postcss-conditionals' import cssEach from 'postcss-each' import cssFor from 'postcss-for' import nested from 'postcss-nested' import cssSimpleVars from 'postcss-simple-vars' import customMedia from 'postcss-custom-media' import cssAtroot from 'postcss-atroot' import sprites from 'postcss-sprites' import HtmlWebpackPlugin from 'html-webpack-plugin' import ExtractTextPlugin from 'extract-text-webpack-plugin' import OpenBrowserPlugin from 'open-browser-webpack-plugin' import CopyWebpackPlugin from 'copy-webpack-plugin' import CleanWebpackPlugin from 'clean-webpack-plugin' import CompressionWebpackPlugin from 'compression-webpack-plugin' import HappyPack from 'happypack' import os from 'os' import lodash from 'lodash' import pkg from './package.json' import manifest from './manifest.json' // 配置环境 const ENV = process.env.NODE_ENV const isDev = ENV === 'development' || ENV === 'dev' const isProd = ENV === 'production' || ENV === 'prod' // 公共模块 const deps = lodash.uniq(Object.keys(pkg.dependencies)) const vendor = lodash.pullAll(deps, []) const jsSourcePath = path.join(__dirname, 'src') const buildPath = path.join(__dirname, 'build/demo') const sourcePath = path.join(__dirname, 'src') // 开启 happypack 多进程的模式加速编译 const happyPackHandle = { threadPool: HappyPack.ThreadPool({ size: os.cpus().length, }), cacheLoaders: {}, cachePlugins: [], createPlugin(id, loaders) { this.cacheLoaders[id] = { loaders, happypack: `happypack/loader?id=${id}`, } this.cachePlugins.push(new HappyPack({ id, loaders, threadPool: this.threadPool, cache: true, verbose: true, })) return this }, getLoaders(id) { const { loaders, happypack } = this.cacheLoaders[id] return isProd ? loaders[0] : happypack }, } // 创建 happypack 实例对象 happyPackHandle .createPlugin('js', ['babel']) .createPlugin('css', ['css!postcss']) // 配置参数 const config = { context: jsSourcePath, entry: { app: [ './app.js', ], vendor, }, output: { path: buildPath, publicPath: '', filename: 'assets/js/app.js', chunkFilename: 'chunk/[name].chunk.js', }, module: { loaders: [ { test: /\.js$/, loader: happyPackHandle.getLoaders('js'), exclude: [path.resolve(__dirname, 'node_modules')], }, { test: /\.css/, loader: ExtractTextPlugin.extract('style', happyPackHandle.getLoaders('css'), { publicPath: '../../', }), }, { test: /\.(gif|jpg|png)\??.*$/, loader: 'url-loader?limit=8192&name=assets/images/[hash].[ext]', }, { test: /\.(woff|svg|eot|ttf)\??.*$/, loader: 'url-loader?limit=8192&name=assets/fonts/[hash].[ext]', }, ], noParse: [/html2canvas/, /jspdf/], }, postcss: webpack => { const dependent = { addDependencyTo: webpack, } const processors = [ cssImport(dependent), cssMixins, cssExtend, conditionals, cssEach, cssFor, nested, cssSimpleVars, customMedia, cssAtroot, autoprefixer, ] return processors }, plugins: [ // 分析和优先考虑使用最多的模块,并为它们分配最小的 ID new webpack.optimize.OccurenceOrderPlugin(), // 删除重复的依赖 new webpack.optimize.DedupePlugin(), // 跳过编译时出错的代码并记录,使编译后运行时的包不会发生错误 new webpack.NoErrorsPlugin(), // 复制静态文件 new CopyWebpackPlugin([{ from: './assets/', to: './assets/', }, ]), // 合并所有的 CSS 文件 new ExtractTextPlugin('assets/css/app.css', { allChunks: true, }), // 自动生成页面 new HtmlWebpackPlugin({ template: path.join(sourcePath, isDev ? 'index.dev.html' : 'index.html'), path: buildPath, filename: 'index.html', }), ], resolve: { extensions: [ '', '.js', '.json', '.css', ], root: [ path.resolve(__dirname), jsSourcePath, ], }, devServer: { contentBase: isProd ? buildPath : sourcePath, // historyApiFallback: true, port: 3000, // compress: isProd, hot: !isProd, inline: !isProd, // disableHostCheck: true, host: '0.0.0.0', }, } // 开发环境 if (isDev) { Object.assign(config, { plugins: [ ...config.plugins, // 抽离并打包变动不频繁的模块 new webpack.DllReferencePlugin({ context: __dirname, manifest, }), // 配置全局变量 new webpack.DefinePlugin({ __DEBUG__: true, }), // happypack 插件 ...happyPackHandle.cachePlugins, // 开启全局的模块热替换(HMR) new webpack.HotModuleReplacementPlugin(), // 当模块热替换(HMR)时在浏览器控制台输出对用户更友好的模块名字信息 new webpack.NamedModulesPlugin() // 打开浏览器 // new OpenBrowserPlugin({ // url: 'http://localhost:3000', // }), ], entry: Object.assign({}, config.entry, { app: [ // 开发环境全局变量配置 // path.resolve(__dirname, 'dev.config.js'), ...config.entry.app, ], }), // 产生.map文件,方便调试 devtool: 'source-map', }) } // 生产环境 if (isProd) { Object.assign(config, { plugins: [ ...config.plugins, // 清除文件 new CleanWebpackPlugin(['build'], { root: '', verbose: true, dry: false, }), // 提取公共模块单独打包,进而减小 rebuild 时的性能消耗 new webpack.optimize.CommonsChunkPlugin('vendor', 'assets/js/vendor.js'), // 打包压缩 JS 文件 new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, drop_console: true, } }), // 压缩成 gzip 格式 new CompressionWebpackPlugin({ asset: "[path].gz[query]", algorithm: "gzip", test: /\.js$|\.css$|\.html$/, threshold: 10240, minRatio: 0, }), ], entry: Object.assign({}, config.entry, { app: [ // 生成环境全局变量配置 // path.resolve(__dirname, 'prod.config.js'), ...config.entry.app, ], }), }) } export default config
module.exports = server => { require('./health')(server) require('./ROOT')(server) require('./word')(server) }
import axios from 'axios'; class MovieAPI { constructor() { this.API_KEY = '16793a08fc468099c942dee45d510578'; this.BASE_URL = 'https://api.themoviedb.org/3/'; } async getPopular() { const response = await axios.get( `${this.BASE_URL}trending/movie/day?api_key=${this.API_KEY}`, ); const movies = response.data.results; return movies; } async searchMovies(query) { const response = await axios.get( `${this.BASE_URL}search/movie?query=${query}&api_key=${this.API_KEY}&language=en-US&page=1&include_adult=false`, ); const movies = response.data.results; return movies; } async movieDetails(id) { const response = await axios.get( `${this.BASE_URL}movie/${id}?api_key=${this.API_KEY}&language=en-US`, ); const data = response.data; return data; } async movieReviews(id) { const response = await axios.get( `${this.BASE_URL}movie/${id}/reviews?api_key=${this.API_KEY}&language=en-US`, ); const results = response.data.results; return results; } async movieCast(id) { const response = await axios.get( `${this.BASE_URL}movie/${id}/credits?api_key=${this.API_KEY}&language=en-US`, ); const data = response.data; return data; } } const MoviesApi = new MovieAPI(); export default MoviesApi;
var pets = ["dog", "cat", "pika"]; // for (var i = 0; i < pets.length; i++){ // console.log(pets[i]) // } // for(var pet of pets){ // console.log(pet); // } // var object = {student1:3, student2:12, student4:30}; // for(var key in object){ // console.log("object." + key + " = " + object[key]) // }; var x = 0; while(x < 10){ console.log("loop " + x); // x = x + 1 - this is the same as below. x++; }
import axios from 'axios' class API { constructor () { this.userId = ''; } get api () { return axios.create({ baseURL: window.location.port === '3000' ? 'http://localhost:443' : '/', headers: {'user-id': this.userId} }); } get get () { return async (...props) => this.api.get(...props) } get post () { return async (...props) => this.api.post(...props) } get put () { return async (...props) => this.api.put(...props) } get delete () { return async (...props) => this.api.delete(...props) } } export default new API();
const alunos = [ {nome:'joão', nota: 7.3, bolsista: false}, {nome:'Maria', nota: 9.2, bolsista: true}, {nome:'Pedro', nota: 9.8, bolsista: false}, {nome:'Ana', nota: 8.7, bolsista: true}, ] //Desafio 1 : Todos os alunos são bolsistas? const todosBolsistas = (resultado, bolsista) => resultado && bolsista console.log(alunos.map(a => a.bolsista).reduce(todosBolsistas)) /*const bolsa = alunos.map(a => a.bolsista).reduce(function(status, sArray){ console.log(status, sArray) if(sArray == false){ sArray = 1 }else{ sArray = 0 } }, 1) console.log(bolsa) const bolsa = alunos => alunos.bolsista const simOuNao = alunos => alunos.bolsista const comBolsa = alunos.map(bolsa) const sim = comBolsa.filter(simOuNao) console.log(comBolsa) console.log(sim)*/ //Desafio 2 : Alguem aluno é bolsista? const algumBolsista = (resultado, bolsista) => resultado || bolsista console.log(alunos.map(a=>a.bolsista).reduce(algumBolsista))
// GLOBAL VARIABLES var score = 0; var startBtn = document.getElementById("startQuiz"); var questionBox = document.getElementById("questionsBox"); var correctAnswerAlert = document.querySelector(".alert-success"); var wrongAnswerAlert = document.querySelector(".alert-danger"); var quizRunTime = 90; var numberOfQuestions = questions.length; var timerInterval; var clicked = document.getElementById("answers"); var isClicked = ""; var timerDisplay = document.getElementById("timer"); var finalScore = document.getElementById("finalScore"); // START BUTTON EVENT LISTENER startBtn.addEventListener("click", function() { var jumbotron = document.getElementById("jumbotron"); jumbotron.classList.add("d-none"); // hides the jumbotron var header = document.getElementById("quiz-header"); header.classList.remove("d-none"); // shows the timer and high scores questionBox.classList.remove("d-none"); // shows the div containing the question var questionsCounter = 0; // Initializes the counter to get the first question in the array generateQuestion(questionsCounter); // displays the first question quizTimer(quizRunTime); // initializes the countdown }); // ANSWER CLICKED EVENT LISTENER clicked.addEventListener("click", function(event) { var CurrentIndex = document.getElementById("questionsBox").getAttribute("index"); var selectedAnswer = event.target.innerText; var correctAnswer = questions[CurrentIndex].answer; isClicked = "true"; if (selectedAnswer == correctAnswer) { score += 100; console.log(score); CurrentIndex++; correctAnswerAlert.classList.remove("d-none"); if (CurrentIndex < numberOfQuestions) { setTimeout(function() { correctAnswerAlert.classList.add("d-none"); generateQuestion(CurrentIndex); }, 500); } else { setTimeout(function() { correctAnswerAlert.classList.add("d-none"); endQuiz(timerInterval); }, 500); } } else { console.log(score); wrongAnswerAlert.classList.remove("d-none"); score -= 10; // this deducts points from total score if the answer is wrong CurrentIndex++; if (CurrentIndex < numberOfQuestions) { setTimeout(function() { wrongAnswerAlert.classList.add("d-none"); generateQuestion(CurrentIndex); }, 500); } else { setTimeout(function() { wrongAnswerAlert.classList.add("d-none"); endQuiz(timerInterval); }, 500); } } }); // POPULATE QUESTIONS function generateQuestion(q) { isClicked = "false"; questionBox.setAttribute("index", q); var questionHeader = document.getElementById("questionTitle"); questionHeader.innerText = questions[q].title; var currentQuestion = questions[q]; var qNumber = document.getElementById("qNumber"); qNumber.innerText = "Question " + (q + 1); // removes previusly appended li items var answers = document.getElementById("answers"); while (answers.hasChildNodes()) { answers.removeChild(answers.firstChild); } // the following loop displays the current question and answer list for (var i = 0; i < questions[q].choices.length; i++) { var listItem = document.createElement("li"); var answer = currentQuestion.choices[i]; listItem.innerText = answer; listItem.setAttribute("id", i); document.getElementById("answers").appendChild(listItem); } }; // TIMER FUNCTION function quizTimer(r) { var timerInterval = setInterval(function() { r--; timerDisplay.textContent = r; var CurrentIndex = document .getElementById("questionsBox") .getAttribute("index"); if (CurrentIndex == numberOfQuestions-1 && isClicked == "true") { clearInterval(timerInterval); }; if (r === 0) { endQuiz(timerInterval); } }, 1000); }; // DISPLAY FINAL SCREEN function endQuiz(t) { var endingDiv = document.getElementById("endOfQuiz"); var questionBox = document.getElementById("questionsBox"); questionBox.classList.add("d-none"); endingDiv.classList.remove("d-none"); clearInterval(t); setFinalScore(); leaderBoard(); }; // CALCULATE FINAL SCORE function setFinalScore() { var secondsRemaining = timerDisplay.textContent; if (score < 0) { // user gets bonus points based on how fast the quiz was answered, and if at least one choice was right score = 0; } else { if (secondsRemaining > 60) { score += 50; } else if (secondsRemaining > 40) { score += 30; } else if (secondsRemaining > 20) { score += 10; } else { score += 5; } }; finalScore.innerText = score; return score; }; function leaderBoard() { var storeBtn = document.getElementById("submitInitials"); storeBtn.addEventListener("click", function() { var saved = document.getElementById("saved"); saved.classList.remove("d-none"); var playerInitials = document.getElementById("playerInitials").value.toUpperCase(); var totalPoints = finalScore.innerText; var storedInitials = document.getElementById("storedInitials"); var storedScore = document.getElementById("storedScore"); var highScores = [ { playerInitials: playerInitials, finalScore: totalPoints } ]; storedInitials.innerText = highScores[0].playerInitials; storedScore.innerText = highScores[0].finalScore; localStorage.setItem("score", JSON.stringify(highScores)); }); var dataStored = JSON.parse(localStorage.getItem("score")); console.log(dataStored[0].playerInitials); console.log(dataStored[0].finalScore); };
/// <reference path="D:\Shop\Git\Shop.Web\Assets/admin/libs/angular/angular.js" /> (function (app) { app.controller('productAddController', productAddController); productAddController.$inject = ['$scope', 'apiService', 'notificationService', '$state', 'commonService'] function productAddController($scope, apiService, notificationService, $state, commonService) { $scope.categories = []; $scope.moreImages = []; $scope.product = { Status: true }; $scope.ckeditorOptions = { language: 'vi', height: '200px' } $scope.addProduct = addProduct; $scope.getSeoTitle = getSeoTitle; $scope.chooseImage = chooseImage; $scope.chooseMoreImage = chooseMoreImage; function chooseImage() { var finder = new CKFinder(); finder.selectActionFunction = function (fileUrl, data) { $scope.$apply(function () { $scope.product.Image = fileUrl; }); }; finder.popup(); } function addProduct() { $scope.product.MoreImages = JSON.stringify($scope.moreImages); apiService.post('/api/product/create', $scope.product, function (result) { notificationService.displaySuccess($scope.product.Name + ' đã được thêm thành công.'); $state.go('products'); }, function (err) { notificationService.displayError('Thêm mới không thành công.') }); } function getSeoTitle() { $scope.product.Alias = commonService.getSeoTitle($scope.product.Name); } function loadProductCategories() { apiService.get('/api/productcategory/getallparents', null, function (result) { $scope.categories = result.data; }, function (err) { console.log('Can not load product category list'); }) } function chooseMoreImage() { var finder = new CKFinder(); finder.selectActionFunction = function (fileUrl, data) { $scope.$apply(function () { $scope.moreImages.push(fileUrl); }) }; finder.popup(); } loadProductCategories(); } })(angular.module('shop.products'));
import loaderReducer from './loaderReducer'; import config from '../../services/config'; import types from '../../actions/actionTypes'; import initialState from '../initialState'; describe('loading reducer', () => { it('should return the initial state', () => { expect(loaderReducer(undefined, {})).toEqual( { loading: false, } ) }); it('should handle LOADING', () => { expect( loaderReducer({}, { type: types.LOADING, }) ).toEqual({ loading: true, }); }); it('should handle LOADING_SUCCESS', () => { expect( loaderReducer({}, { type: types.LOADING_SUCCESS, }) ).toEqual({ loading: false, }); }); });
import React, {Component} from 'react'; import styles from "./Dish.module.css"; class Dish extends Component { render() { return ( <div className={styles['dish']}> <span>{this.props.name}</span> <span className={styles['price']}>{this.props.price}</span> </div> ); } } export default Dish;
const andresses = require('../models/andresses'); const schemas = require('../schemas/andressesSchema'); const addStatisticsCity = async (city) => { const updateCity = await andresses.statisticsUpdateCity(city) if (updateCity.modifiedCount < 1) { await andresses.statisticsAddCity(city) return } } const addStatisticsUF = async (UF) => { const updateUF = await andresses.statisticsUpdateUF(UF) if (updateUF.modifiedCount < 1) { await andresses.statisticsAddUF(UF) return } } const getAndress = async (cepInput) => { const validations = schemas.validateCep(schemas.formatedCep(cepInput)) if (validations.message) return validations const result = await andresses.getAndressData(schemas.formatedCep(cepInput)); const { cep, uf, cidade, bairro, logradouro } = await andresses.getAndressApi(schemas.formatedCep(cepInput)); if (!uf) return { code: 404, message: 'CEP não encontrado' } if (!result) { const resultApi = await andresses.add(cep, uf, cidade, bairro, logradouro) await addStatisticsCity(cidade) await addStatisticsUF(uf) return resultApi } await addStatisticsCity(result.cidade) await addStatisticsUF(result.UF) return result } module.exports = { getAndress, }
CSSLint.addFormatter({ //format information id: "compact", name: "Compact, 'porcelain' format", startFormat: function(){ return ""; }, endFormat: function(){ return ""; }, formatResults: function(results, filename) { var messages = results.messages, output = "", pos = filename.lastIndexOf("/"), shortFilename = filename; if (messages.length === 0) { return shortFilename + ": Lint Free!"; } if (pos == -1){ pos = filename.lastIndexOf("\\"); } if (pos > -1){ shortFilename = filename.substring(pos+1); } messages.forEach(function (message, i) { if (message.rollup) { output += shortFilename + ": " + message.message + "\n"; } else { output += shortFilename + ": " + "line " + message.line + ", col " + message.col + ", " + message.message + "\n"; } }); return output; } });
const router = require('express').Router() const {ObjectId} = require('mongodb'); const { renderFormat, searchCriteria, version, distance } = require('../utils') const { allowDepartmentsFilter } = require('../query') const Actor = require('../models/actor') const Action = require('../models/action') router .get('/', async (req, res) => { const criteria = allowDepartmentsFilter(req) const actors = await Actor.find(criteria).limit(Number(req.query.limit) || 30) renderFormat(req, res, actors) }) .post('/', async (req, res) => { await createOrUpdateActor(req, res, x => Actor.create(x)) }) .put('/:id', async (req, res) => { await createOrUpdateActor(req, res, async actor => { await version('Actor', await Actor.findByIdAndUpdate(req.params.id, actor)) return Actor.findById(req.params.id) }) }) .delete('/:id', async (req, res) => { const actor = await Actor.findOneAndRemove({ _id: req.params.id }) await version('Actor', actor) const actions = await Action.find({ actorId: req.params.id }) await Action.remove({ id: { $in: actions.map(a => a.id) } }) await version('Action', actions) res.send(actor) }) .get('/count', async (req, res) => { const criteria = allowDepartmentsFilter(req) res.send(String(await Actor.countDocuments(criteria))) }) .get('/search/:q?', async (req, res) => { const from = req.query.from const location = from && from.split(',').map(v => Number(v)) const limit = Number(req.query.limit) || 30 const domains = req.query.domains && req.query.domains.split(',') const schoolLevels = req.query.schoolLevels && req.query.schoolLevels.split(',') let criteria = searchCriteria(req) if (domains) { criteria.domains = { $in: domains } } if (schoolLevels) { const actions = await Action.find({schoolLevels: { $in: schoolLevels }}) criteria._id = {$in: actions.map(e => ObjectId(e.actorId[0])) } } let actors = [] if (from) { actors = await Actor.find(criteria) actors.forEach(actor => { actor.distance = distance(actor.loc.coordinates, location) }) actors.sort((a, b) => a.distance - b.distance) if (limit !== -1) { actors = actors.splice(0, limit) } } else { actors = limit === -1 ? await Actor.find(criteria) : await Actor.find(criteria).limit(limit) } renderFormat(req, res, actors) }) .get('/:id', async (req, res) => { const actor = await Actor.findOne({ _id: req.params.id }) actor.actions = await Action.find({actorId: actor._id}) actor.distance = distance(actor.loc.coordinates, req.query.from) res.send(actor) }) async function createOrUpdateActor (req, res, callback) { const params = req.body try { const {actions, ...properties} = {...params, ...{updatedAt: new Date(), source: 'eac_website'}} // Create actor. const actor = await callback(properties) // Remove deleted actions. const existingActionsIds = (await Action.find({actorId: actor._id})).map(a => a.id) const updatedActionsIds = params.actions ? params.actions.filter(a => a.id).map(a => a.id) : [] const toBeRemovedActionsIds = existingActionsIds.filter(x => !updatedActionsIds.includes(x)) const toBeRemovedActions = await Action.find({ id: { $in: toBeRemovedActionsIds } }) await Action.remove({ id: { $in: toBeRemovedActionsIds } }) await version('Action', toBeRemovedActions) // Update existing actions and create new ones. params.actions && await Promise.all(params.actions.map(async action => { const actionProperties = {...action, ...{actorId: actor._id, loc: actor.loc}} if (!action.id) { return Action.create(actionProperties) } else { const actionBeforeUpdate = await Action.findByIdAndUpdate(action.id, actionProperties) return version('Action', actionBeforeUpdate) } })) res.send(actor) } catch (e) { res.status(400).send({ message: e.message }) } } module.exports = router
const express = require('express'); const plants = require('./plants'); const userModels = require('./models/plants'); const connection = require('./connection'); const app = express(); app.use(express.json()); const userModel = userModels.factory(connection) app.get('/plants' , userModel.findAll); app.get('/plant/:id' , plants.getPlantById); app.delete('/plant/:id',plants.removePlantById) app.put('/plant/:id' , plants.editPlant) app.post('/plant' , plants.createdPlant) app.get('/sunny/:id' , plants.getPlantByIdNeedSun) app.listen(3001,console.log('Rodando porta 3000'))
import React from "react"; import styled from "styled-components"; import { Heart } from "react-feather"; import { useHistory } from "react-router-dom"; import { useDarkMode } from "../../state"; const Wrapper = styled.div` background-color: ${(props) => props.theme.colors.backgroundColor}; border-radius: 8px; margin-bottom: 1rem; border: 1px solid ${(props) => props.theme.colors.headerBorder}; `; const UserInfo = styled.div` width: 100%; padding: 20px; font-size: 14px; cursor: pointer; font-weight: bold; color: ${(props) => props.theme.colors.titleColor}; `; const PostInformations = styled.div``; const StyledLike = styled.div` width: 100%; padding: 10px; `; const StyledContainer = styled.div` width: 100%; padding: 10px; font-size: 14px; `; const StyledLikes = styled.div` width: 100%; padding-left: 14px; font-size: 12px; color: ${(props) => props.theme.colors.titleColor}; `; const Image = styled.img` width: 100%; height: auto; `; const UserInfoDescription = styled.div` width: 100%; font-size: 14px; padding-left: 4px; `; const Description = styled.span` font-weight: normal; color: ${(props) => props.theme.colors.titleColor}; `; const Username = styled.span` cursor: pointer; font-weight: bold; color: ${(props) => props.theme.colors.titleColor}; `; function Post(props) { const history = useHistory(); const isDarkMode = useDarkMode((state) => state.isDarkMode); const { url, description, username, likeCount } = props; function showUserProfile() { history.push(`/user/${username}`); } return ( <Wrapper> <UserInfo onClick={() => showUserProfile()}>{username}</UserInfo> <Image src={`${url}`} /> <PostInformations> <StyledLike> <Heart style={{ height: "20px", width: "20px", cursor: "pointer", color: isDarkMode ? "#fff" : "#000", }} onClick={props.likePost} /> </StyledLike> {likeCount > 0 && <StyledLikes>Liked by {likeCount} users</StyledLikes>} <StyledContainer> <UserInfoDescription> <Username onClick={() => showUserProfile()}>{username}</Username>{" "} <Description> {description}</Description> </UserInfoDescription> </StyledContainer> </PostInformations> </Wrapper> ); } export default Post;
Ext.define('Assessmentapp.assessmentapp.shared.com.model.assessmentcontext.survey.AssessmentInferenceExtDTOModel.AssessmentInferenceExtDTOModel', { "extend": "Ext.data.Model", "fields": [{ "name": "questionNumber", "type": "string", "defaultValue": "" }, { "name": "inferenceKeyword", "type": "string", "defaultValue": "" }, { "name": "inferenceHeading", "type": "string", "defaultValue": "" }, { "name": "inferenceYesValue", "type": "string", "defaultValue": "" }, { "name": "inferenceNoValue", "type": "string", "defaultValue": "" }] });
export default { getItem:(key)=>{ return localStorage.getItem(key) }, setItem:(key,value)=>{ localStorage.setItem(key,value) } }
;(function($){ "use strict"; $(document).ready(function(){ /*---------------------- Search Popup -----------------------*/ var bodyOvrelay = $('#body-overlay'); var searchPopup = $('#search-popup'); $(document).on('click','#body-overlay',function(e){ e.preventDefault(); bodyOvrelay.removeClass('active'); searchPopup.removeClass('active'); }); $(document).on('click','#search',function(e){ e.preventDefault(); searchPopup.addClass('active'); bodyOvrelay.addClass('active'); }); }); })(jQuery);
sap.ui.define([ "sap/ui/core/UIComponent", "sap/ui/core/mvc/XMLView", "sap/m/Shell", "sap/m/App" ], function (UIComponent, XMLView, Shell, App) { "use strict"; return UIComponent.extend("kafka-webapp.Component", { metadata: { manifest: "json" }, createContent: function () { this.getRouter().initialize(); return new Shell({ app: new App("app") }); } }); });
/* This work is licensed under Creative Commons GNU LGPL License. License: http://creativecommons.org/licenses/LGPL/2.1/ Version: 0.9 Author: Stefan Goessner/2006 Web: http://goessner.net/ */ function json2xml(nodesData, edgeData, initialNode, finalNodes) { let edges = edgeData._data; let numOfTapes = edges[1].label.split("|").length; let xml = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n' + "<structure>\n" + "<type>turing</type>\n" + (numOfTapes > 1 ? `<tapes>${numOfTapes}</tapes>\n` : "") + "<automaton>\n"; let nodes = nodesData._data; nodes.length = nodesData.length; console.warn(nodes); edges.length = edgesData.length; console.warn(edges); let count = nodes.length; //adicionando estados for (var i in nodes) { if (nodes.hasOwnProperty(i)) { xml += `<state id="${nodes[i].id}" name="${nodes[i].label}">\n`; xml += `<x>${nodes[i].x}</x>\n`; xml += `<y>${nodes[i].y}</y>\n`; if (initialNode.id === nodes[i].id) { xml += `<initial/>\n`; } let finals = []; for (var node in finalNodes) { if (finalNodes.hasOwnProperty(node)) { finals.push(finalNodes[node].id); } } for (let j = 0; j < finals.length; j++) { if (String(nodes[i].id) == finals[j]) { xml += `<final/>\n`; break; } } xml += `</state>\n`; } count--; if (count === 0) break; } //adicionando transições for (let index = 1; index <= edges.length; index++) { if (edges.hasOwnProperty(index)) { let fitas = edges[index].label.split("|"); console.log(fitas); xml += `<transition>\n`; xml += `<from>${edges[index].from}</from>\n`; xml += `<to>${edges[index].to}</to>\n`; if (fitas.length > 1) for (let i = 0; i < fitas.length; i++) { regra = fitas[i].split(";"); console.log(regra); xml += regra[0] !== "&" ? `<read tape = "${i + 1}">${regra[0]}</read>\n` : `<read tape = "${i + 1}"/>\n`; xml += regra[1] !== "&" ? `<write tape = "${i + 1}">${regra[1]}</write>\n` : `<write tape = "${i + 1}"/>\n`; xml += `<move tape = "${i + 1}">${regra[2]}</move>\n`; } else { regra = fitas[0].split(";"); xml += regra[0] !== "&" ? `<read>${regra[0]}</read>\n` : `<read/>\n`; xml += regra[1] !== "&" ? `<write>${regra[1]}</write>\n` : `<write/>\n`; xml += `<move>${regra[2]}</move>\n`; } xml += `</transition>\n`; } } xml += "</automaton>\n"; xml += "</structure>"; return xml; }
import { ON_DELETE_ITEM_FROM_CART, ON_QUANTITY_CHANGE, ON_ADD_ITEM_TO_CART } from "../actions/types"; import update from 'react-addons-update'; const INIT_STATE = { cart: [ { objectID: '1', image: require('../assets/img/product-1.png'), name: 'Speaker', description: 'Rechargeable Battery', brand: 'JBL', price: 50, productQuantity: 1, totalPrice: 50 }, { objectID: '2', image: require('../assets/img/product-2.png'), name: 'Headphone', description: 'Clear Sound', brand: 'JBL', price: 45, productQuantity: 1, totalPrice: 45 }, { objectID: '3', image: require('../assets/img/product-3.png'), name: 'Bluetooth Speaker', description: 'Rechargeable Battery', brand: 'JBL', price: 96, productQuantity: 1, totalPrice: 96 }, { objectID: '4', image: require('../assets/img/product-4.png'), name: 'D.J. Speaker', description: '3d Surround Sound', brand: 'JBL', price: 87, productQuantity: 1, totalPrice: 87 } ], newCartItem: { objectID:"", name: "", image: "", description: "", brand: "", price: null, productQuantity: null, totalPrice: null }, } export default (state = INIT_STATE, action) => { switch (action.type) { case ON_DELETE_ITEM_FROM_CART: let index = state.cart.indexOf(action.payload) return update(state, { cart: { $splice: [[index, 1]] } }); case ON_QUANTITY_CHANGE: let cartItemIndex = state.cart.indexOf(action.payload.cartItem); return update(state, { cart: { [cartItemIndex]: { productQuantity: { $set: action.payload.quantity }, totalPrice: { $set: action.payload.cartItem.price * action.payload.quantity } } } }); case ON_ADD_ITEM_TO_CART: let newCartItem = { objectID:action.payload.objectID, name: action.payload.name, image: action.payload.image, description: action.payload.description, brand: action.payload.brand, price: action.payload.price, productQuantity: 1, totalPrice: action.payload.price }; return update(state, { cart: { $push: [newCartItem] } }) default: return { ...state }; } }
const express = require('express'); const Controller = require('./controller'); const app = express(); const port = 5001; // we are importing an object, the key "getproducts" has a value of a function // any function that's used on an express method ('app'will receive req and res as arguments by default app.get('/api/products', Controller.getProducts) app.get('/api/product/:id', Controller.getSingleProduct) app.listen(port, () => { console.log(`Our server is listening on port: ${port}`) })
const webpack = require('webpack'); const LiveReloadPlugin = require('webpack-livereload-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { entry: { bundle: './app.js', 'front.style': './styles/main.less', }, output: { path: __dirname, filename: '[name].js', chunkFilename: '[name].js', }, resolve: { // We can now require('file') instead of require('file.jsx') extensions: ['', '.js', '.jsx', '.scss'], }, module: { loaders: [ { test: /.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['es2015', 'react'], retainLines: true, cacheDirectory: true, }, }, { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader'), }, // Optionally extract less files // or any other compile-to-css language { test: /\.less$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader"), // eslint-disable-line }, //{ // test: /\.css/, // loader: 'style-loader!css-loader', // }, { // test: /\.less$/, // loader: 'css-loader!less-loader', // }, ], }, devtool: 'source-map', plugins: [ new LiveReloadPlugin(), new ExtractTextPlugin('./[name].css'), // new webpack.SourceMapDevToolPlugin({ // // Match assets just like for loaders. // test: /\.js$/, // // // `exclude` matches file names, not package names! // exclude: '/node_modules/', // // // If filename is set, output to this file. // // See `sourceMapFileName`. // filename: '[file].map', // // // This line is appended to the original asset processed. For // // instance '[url]' would get replaced with an url to the // // sourcemap. // append: false, // // module: true, // If false, separate sourcemaps aren't generated. // // // Use simpler line to line mappings for the matched modules. // // lineToLine: bool | {test, include, exclude} // }), ], };
/** * @license * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ describe('Storage', function() { var originalSupportsStorageEngine; var originalCreateStorageEngine; var SegmentReference; var fakeStorageEngine; var storage; var player; var netEngine; beforeAll(function() { SegmentReference = shaka.media.SegmentReference; originalSupportsStorageEngine = shaka.offline.OfflineUtils.supportsStorageEngine; originalCreateStorageEngine = shaka.offline.OfflineUtils.createStorageEngine; }); afterAll(function() { shaka.offline.OfflineUtils.supportsStorageEngine = originalSupportsStorageEngine; shaka.offline.OfflineUtils.createStorageEngine = originalCreateStorageEngine; }); beforeEach(function(done) { shaka.offline.OfflineUtils.supportsStorageEngine = function() { return true; }; fakeStorageEngine = new shaka.test.MemoryDBEngine(); shaka.offline.OfflineUtils.createStorageEngine = function() { return fakeStorageEngine; }; netEngine = new shaka.test.FakeNetworkingEngine(); // Use a real Player since Storage only uses the configuration and // networking engine. This allows us to use Player.configure in these // tests. player = new shaka.Player(new shaka.test.FakeVideo(), function(player) { player.createNetworkingEngine = function() { return netEngine; }; }); storage = new shaka.offline.Storage(player); fakeStorageEngine.init(shaka.offline.OfflineUtils.DB_SCHEME) .catch(fail) .then(done); }); afterEach(function(done) { storage.destroy().catch(fail).then(done); }); it('lists stored manifests', function(done) { var ContentType = shaka.util.ManifestParserUtils.ContentType; var manifestDb1 = { key: 0, originalManifestUri: 'fake:foobar', duration: 1337, size: 65536, periods: [{ streams: [ { id: 0, contentType: ContentType.VIDEO, kind: undefined, language: '', width: 1920, height: 1080, frameRate: 24, mimeType: 'video/mp4', codecs: 'avc1.4d401f', primary: false, segments: [], roles: [] }, { id: 1, contentType: ContentType.AUDIO, kind: undefined, language: 'en', width: null, height: null, frameRate: undefined, mimeType: 'audio/mp4', codecs: 'vorbis', primary: true, segments: [], roles: [] } ] }], appMetadata: { foo: 'bar', drm: 'yes', theAnswerToEverything: 42 } }; var manifestDb2 = { key: 1, originalManifestUri: 'fake:another', duration: 4181, size: 6765, periods: [{streams: []}], appMetadata: { something: 'else' } }; var manifestDbs = [manifestDb1, manifestDb2]; var expectedTracks = [ { id: 0, active: false, type: 'variant', bandwidth: 0, language: 'en', label: null, kind: null, width: 1920, height: 1080, frameRate: 24, mimeType: 'video/mp4', primary: true, codecs: 'avc1.4d401f, vorbis', audioCodec: 'vorbis', videoCodec: 'avc1.4d401f', roles: [], videoId: 0, audioId: 1, channelsCount: null, audioBandwidth: null, videoBandwidth: null } ]; Promise .all([ fakeStorageEngine.insert('manifest', manifestDb1), fakeStorageEngine.insert('manifest', manifestDb2) ]) .then(function() { return storage.list(); }) .then(function(data) { expect(data).toBeTruthy(); expect(data.length).toBe(2); for (var i = 0; i < 2; i++) { expect(data[i].offlineUri).toBe('offline:' + manifestDbs[i].key); expect(data[i].originalManifestUri) .toBe(manifestDbs[i].originalManifestUri); expect(data[i].duration).toBe(manifestDbs[i].duration); expect(data[i].size).toBe(manifestDbs[i].size); expect(data[i].appMetadata).toEqual(manifestDbs[i].appMetadata); } expect(data[0].tracks).toEqual(expectedTracks); expect(data[1].tracks).toEqual([]); }) .catch(fail) .then(done); }); describe('store', function() { var originalWarning; var manifest; var tracks; var drmEngine; var stream1Index; var stream2Index; beforeAll(function() { originalWarning = shaka.log.warning; }); beforeEach(function() { drmEngine = new shaka.test.FakeDrmEngine(); manifest = new shaka.test.ManifestGenerator() .setPresentationDuration(20) .addPeriod(0) .addVariant(0).language('en').bandwidth(160) .addVideo(1).size(100, 200).bandwidth(80) .addAudio(2).language('en').bandwidth(80) .build(); // Get the original tracks from the manifest. var getVariantTracks = shaka.util.StreamUtils.getVariantTracks; tracks = getVariantTracks(manifest.periods[0], null, null); // The expected tracks we get back from the stored version of the content // will have 0 for bandwidth, so adjust the tracks list to match. tracks.forEach(function(t) { t.bandwidth = 0; t.audioBandwidth = null; t.videoBandwidth = null; }); storage.loadInternal = function() { return Promise.resolve({ manifest: manifest, drmEngine: drmEngine }); }; player.configure({preferredAudioLanguage: 'en'}); stream1Index = new shaka.media.SegmentIndex([]); stream2Index = new shaka.media.SegmentIndex([]); var stream1 = manifest.periods[0].variants[0].audio; stream1.findSegmentPosition = stream1Index.find.bind(stream1Index); stream1.getSegmentReference = stream1Index.get.bind(stream1Index); var stream2 = manifest.periods[0].variants[0].video; stream2.findSegmentPosition = stream2Index.find.bind(stream2Index); stream2.getSegmentReference = stream2Index.get.bind(stream2Index); }); afterEach(function() { shaka.log.warning = originalWarning; }); it('stores basic manifests', function(done) { var originalUri = 'fake://foobar'; var appData = {tools: ['Google', 'StackOverflow'], volume: 11}; storage.store(originalUri, appData) .then(function(data) { expect(data).toBeTruthy(); // Since we are using a memory DB, it will always be the first one. expect(data.offlineUri).toBe('offline:0'); expect(data.originalManifestUri).toBe(originalUri); expect(data.duration).toBe(0); // There are no segments. expect(data.size).toEqual(0); expect(data.tracks).toEqual(tracks); expect(data.appMetadata).toEqual(appData); }) .catch(fail) .then(done); }); it('gives warning if storing tracks with the same type', function(done) { manifest = new shaka.test.ManifestGenerator() .setPresentationDuration(20) .addPeriod(0) .addVariant(0) .addVariant(1) .build(); // Store every stream. storage.configure({ trackSelectionCallback: function(tracks) { return tracks; } }); var warning = jasmine.createSpy('shaka.log.warning'); shaka.log.warning = warning; storage.store('') .then(function(data) { expect(data).toBeTruthy(); expect(warning).toHaveBeenCalled(); }) .catch(fail) .then(done); }); it('only stores the tracks chosen', function(done) { manifest = new shaka.test.ManifestGenerator() .setPresentationDuration(20) .addPeriod(0) .addVariant(0) .addVideo(1) .addVariant(2) .addVideo(3) .build(); // Store the first variant. storage.configure({ trackSelectionCallback: function(tracks) { return tracks.slice(0, 1); } }); storage.store('') .then(function(data) { expect(data.offlineUri).toBe('offline:0'); return fakeStorageEngine.get('manifest', 0); }) .then(function(manifestDb) { expect(manifestDb).toBeTruthy(); expect(manifestDb.periods.length).toBe(1); expect(manifestDb.periods[0].streams.length).toBe(1); }) .catch(fail) .then(done); }); it('stores offline sessions', function(done) { var sessions = ['lorem', 'ipsum']; drmEngine.setSessionIds(sessions); storage.store('') .then(function(data) { expect(data.offlineUri).toBe('offline:0'); return fakeStorageEngine.get('manifest', 0); }) .then(function(manifestDb) { expect(manifestDb).toBeTruthy(); expect(manifestDb.sessionIds).toEqual(sessions); }) .catch(fail) .then(done); }); it('stores DRM info', function(done) { var drmInfo = { keySystem: 'com.example.abc', licenseServerUri: 'http://example.com', persistentStateRequire: true, audioRobustness: 'HARDY' }; drmEngine.setDrmInfo(drmInfo); drmEngine.setSessionIds(['abcd']); storage.store('') .then(function(data) { expect(data.offlineUri).toBe('offline:0'); return fakeStorageEngine.get('manifest', 0); }) .then(function(manifestDb) { expect(manifestDb).toBeTruthy(); expect(manifestDb.drmInfo).toEqual(drmInfo); }) .catch(fail) .then(done); }); it('stores expiration', function(done) { drmEngine.setSessionIds(['abcd']); drmEngine.getExpiration.and.returnValue(1234); storage.store('') .then(function(data) { expect(data.offlineUri).toBe('offline:0'); return fakeStorageEngine.get('manifest', 0); }) .then(function(manifestDb) { expect(manifestDb).toBeTruthy(); expect(manifestDb.expiration).toBe(1234); }) .catch(fail) .then(done); }); it('throws an error if another store is in progress', function(done) { var p1 = storage.store('', {}).catch(fail); var p2 = storage.store('', {}).then(fail).catch(function(error) { var expectedError = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.STORAGE, shaka.util.Error.Code.STORE_ALREADY_IN_PROGRESS); shaka.test.Util.expectToEqualError(error, expectedError); }); Promise.all([p1, p2]).catch(fail).then(done); }); it('throws an error if the content is a live stream', function(done) { manifest.presentationTimeline.setDuration(Infinity); manifest.presentationTimeline.setStatic(false); storage.store('', {}).then(fail).catch(function(error) { var expectedError = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.STORAGE, shaka.util.Error.Code.CANNOT_STORE_LIVE_OFFLINE, ''); shaka.test.Util.expectToEqualError(error, expectedError); }).then(done); }); it('throws an error if DRM sessions are not ready', function(done) { var drmInfo = { keySystem: 'com.example.abc', licenseServerUri: 'http://example.com', persistentStateRequire: true, audioRobustness: 'HARDY' }; drmEngine.setDrmInfo(drmInfo); drmEngine.setSessionIds([]); storage.store('', {}).then(fail).catch(function(error) { var expectedError = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.STORAGE, shaka.util.Error.Code.NO_INIT_DATA_FOR_OFFLINE, ''); shaka.test.Util.expectToEqualError(error, expectedError); }).then(done); }); it('throws an error if storage is not supported', function(done) { fakeStorageEngine = null; // Recreate Storage object so null fakeStorageEngine takes effect. storage = new shaka.offline.Storage(player); storage.store('', {}).then(fail).catch(function(error) { var expectedError = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.STORAGE, shaka.util.Error.Code.STORAGE_NOT_SUPPORTED); shaka.test.Util.expectToEqualError(error, expectedError); }).then(done); }); it('throws an error if destroyed mid-store', function(done) { var p1 = storage.store('', {}).then(fail).catch(function(error) { var expectedError = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.STORAGE, shaka.util.Error.Code.OPERATION_ABORTED); shaka.test.Util.expectToEqualError(error, expectedError); }); var p2 = storage.destroy(); Promise.all([p1, p2]).catch(fail).then(done); }); describe('reports progress', function() { it('when byte ranges given', function(done) { netEngine.setResponseMap({ 'fake:0': new ArrayBuffer(54), 'fake:1': new ArrayBuffer(13), 'fake:2': new ArrayBuffer(66), 'fake:3': new ArrayBuffer(17) }); stream1Index.merge([ new SegmentReference(0, 0, 1, makeUris('fake:0'), 0, 53), new SegmentReference(1, 1, 2, makeUris('fake:1'), 31, 43), new SegmentReference(2, 2, 3, makeUris('fake:2'), 291, 356), new SegmentReference(3, 3, 4, makeUris('fake:3'), 11, 27) ]); var originalUri = 'fake:123'; var progress = jasmine.createSpy('onProgress'); progress.and.callFake(function(storedContent, percent) { expect(storedContent).toEqual({ offlineUri: 'offline:0', originalManifestUri: originalUri, duration: 4, size: 150, expiration: Infinity, tracks: tracks, appMetadata: undefined }); switch (progress.calls.count()) { case 1: expect(percent).toBeCloseTo(54 / 150); break; case 2: expect(percent).toBeCloseTo(67 / 150); break; case 3: expect(percent).toBeCloseTo(133 / 150); break; default: expect(percent).toBeCloseTo(1); break; } }); storage.configure({progressCallback: progress}); storage.store(originalUri) .then(function() { expect(progress.calls.count()).toBe(4); }) .catch(fail) .then(done); }); it('approximates when byte range not given', function(done) { netEngine.setResponseMap({ 'fake:0': new ArrayBuffer(54), 'fake:1': new ArrayBuffer(13), 'fake:2': new ArrayBuffer(66), 'fake:3': new ArrayBuffer(17) }); stream1Index.merge([ new SegmentReference(0, 0, 1, makeUris('fake:0'), 0, 53), // Estimate: 10 new SegmentReference(1, 1, 2, makeUris('fake:1'), 0, null), // Estimate: 20 new SegmentReference(2, 2, 4, makeUris('fake:2'), 0, null), new SegmentReference(3, 4, 5, makeUris('fake:3'), 11, 27) ]); var originalUri = 'fake:123'; var progress = jasmine.createSpy('onProgress'); progress.and.callFake(function(storedContent, percent) { expect(storedContent).toEqual({ offlineUri: 'offline:0', originalManifestUri: originalUri, duration: 5, size: jasmine.any(Number), expiration: Infinity, tracks: tracks, appMetadata: undefined }); switch (progress.calls.count()) { case 1: expect(percent).toBeCloseTo(54 / 101); expect(storedContent.size).toBe(71); break; case 2: expect(percent).toBeCloseTo(64 / 101); expect(storedContent.size).toBe(84); break; case 3: expect(percent).toBeCloseTo(84 / 101); expect(storedContent.size).toBe(150); break; default: expect(percent).toBeCloseTo(1); expect(storedContent.size).toBe(150); break; } }); storage.configure({progressCallback: progress}); storage.store(originalUri) .then(function() { expect(progress.calls.count()).toBe(4); }) .catch(fail) .then(done); }); }); // describe('reports progress') describe('segments', function() { it('stores media segments', function(done) { netEngine.setResponseMap({ 'fake:0': new ArrayBuffer(5), 'fake:1': new ArrayBuffer(7) }); stream1Index.merge([ new SegmentReference(0, 0, 1, makeUris('fake:0'), 0, null), new SegmentReference(1, 1, 2, makeUris('fake:0'), 0, null), new SegmentReference(2, 2, 3, makeUris('fake:1'), 0, null), new SegmentReference(3, 3, 4, makeUris('fake:0'), 0, null), new SegmentReference(4, 4, 5, makeUris('fake:1'), 0, null) ]); stream2Index.merge([ new SegmentReference(0, 0, 1, makeUris('fake:0'), 0, null) ]); storage.store('') .then(function(manifest) { expect(manifest).toBeTruthy(); expect(manifest.size).toBe(34); expect(manifest.duration).toBe(5); expect(netEngine.request.calls.count()).toBe(6); return fakeStorageEngine.get('manifest', 0); }) .then(function(manifest) { var stream1 = manifest.periods[0].streams[0]; expect(stream1.initSegmentUri).toBe(null); expect(stream1.segments.length).toBe(5); expect(stream1.segments[0]) .toEqual({startTime: 0, endTime: 1, uri: 'offline:0/2/0'}); expect(stream1.segments[3]) .toEqual({startTime: 3, endTime: 4, uri: 'offline:0/2/3'}); var stream2 = manifest.periods[0].streams[1]; expect(stream2.initSegmentUri).toBe(null); expect(stream2.segments.length).toBe(1); expect(stream2.segments[0]) .toEqual({startTime: 0, endTime: 1, uri: 'offline:0/1/5'}); return fakeStorageEngine.get('segment', 3); }) .then(function(segment) { expect(segment).toBeTruthy(); expect(segment.data).toBeTruthy(); expect(segment.data.byteLength).toBe(5); }) .catch(fail) .then(done); }); it('downloads different content types in parallel', function(done) { netEngine.setResponseMap({ 'fake:0': new ArrayBuffer(5), 'fake:1': new ArrayBuffer(7) }); stream1Index.merge([ new SegmentReference(0, 0, 1, makeUris('fake:0'), 0, null), new SegmentReference(1, 1, 2, makeUris('fake:1'), 0, null), new SegmentReference(2, 2, 3, makeUris('fake:1'), 0, null) ]); stream2Index.merge([ new SegmentReference(0, 0, 1, makeUris('fake:1'), 0, null), new SegmentReference(1, 1, 2, makeUris('fake:0'), 0, null), new SegmentReference(2, 2, 3, makeUris('fake:1'), 0, null) ]); // Delay the next segment download. This will stall either audio or // video, but the other should continue. var req1 = netEngine.delayNextRequest(); storage.store('') .then(function(manifest) { expect(manifest).toBeTruthy(); }) .catch(fail) .then(done); shaka.test.Util.delay(1).then(function() { // Should have downloaded all of the segments from either audio/video // and a single (pending) request for the other. expect(netEngine.request.calls.count()).toBe(4); req1.resolve(); }); }); it('stores init segment', function(done) { netEngine.setResponseMap({'fake:0': new ArrayBuffer(5)}); var stream = manifest.periods[0].variants[0].audio; stream.initSegmentReference = new shaka.media.InitSegmentReference(makeUris('fake:0'), 0, null); storage.store('') .then(function(manifest) { expect(manifest).toBeTruthy(); expect(manifest.size).toBe(5); expect(manifest.duration).toBe(0); expect(netEngine.request.calls.count()).toBe(1); return fakeStorageEngine.get('manifest', 0); }) .then(function(manifest) { var stream = manifest.periods[0].streams[0]; expect(stream.segments.length).toBe(0); expect(stream.initSegmentUri).toBe('offline:0/2/0'); return fakeStorageEngine.get('segment', 0); }) .then(function(segment) { expect(segment).toBeTruthy(); expect(segment.data).toBeTruthy(); expect(segment.data.byteLength).toBe(5); }) .catch(fail) .then(done); }); it('with non-0 start time', function(done) { netEngine.setResponseMap({'fake:0': new ArrayBuffer(5)}); var refs = [ new SegmentReference(0, 10, 11, makeUris('fake:0'), 0, null), new SegmentReference(1, 11, 12, makeUris('fake:0'), 0, null), new SegmentReference(2, 12, 13, makeUris('fake:0'), 0, null) ]; stream1Index.merge(refs); manifest.presentationTimeline.notifySegments(0, refs); storage.store('') .then(function(manifest) { expect(manifest).toBeTruthy(); expect(manifest.size).toBe(15); expect(manifest.duration).toBe(13); expect(netEngine.request.calls.count()).toBe(3); return fakeStorageEngine.get('manifest', 0); }) .then(function(manifest) { var stream = manifest.periods[0].streams[0]; expect(stream.segments.length).toBe(3); }) .catch(fail) .then(done); }); it('stops for networking errors', function(done) { netEngine.setResponseMap({'fake:0': new ArrayBuffer(5)}); stream1Index.merge([ new SegmentReference(0, 0, 1, makeUris('fake:0'), 0, null), new SegmentReference(1, 1, 2, makeUris('fake:0'), 0, null), new SegmentReference(2, 2, 3, makeUris('fake:0'), 0, null) ]); var delay = netEngine.delayNextRequest(); var expectedError = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.NETWORK, shaka.util.Error.Code.HTTP_ERROR); delay.reject(expectedError); storage.store('') .then(fail, function(error) { shaka.test.Util.expectToEqualError(error, expectedError); }) .catch(fail) .then(done); }); }); // describe('segments') describe('default track selection callback', function() { var allTextTracks; beforeEach(function() { manifest = new shaka.test.ManifestGenerator() .setPresentationDuration(20) .addPeriod(0) // Spanish, primary // To test language selection fallback to primary .addVariant(10).language('es').bandwidth(160).primary() .addVideo(100).size(100, 200) .addAudio(101).language('es').primary() // English variations // To test language selection for exact matches .addVariant(20).language('en').bandwidth(160) .addVideo(200).size(100, 200) .addAudio(201).language('en') .addVariant(21).language('en-US').bandwidth(160) .addVideo(200).size(100, 200) .addAudio(202).language('en-US') .addVariant(22).language('en-GB').bandwidth(160) .addVideo(200).size(100, 200) .addAudio(203).language('en-GB') // French // To test language selection without exact match .addVariant(30).language('fr-CA').bandwidth(160) .addVideo(300).size(100, 200) .addAudio(301).language('fr-CA') // Swahili, multiple video resolutions // To test video resolution selection .addVariant(40).language('sw').bandwidth(160) .addAudio(400).language('sw') .addVideo(401).size(100, 200) // small SD video .addVariant(41).language('sw').bandwidth(160) .addAudio(400).language('sw') .addVideo(402).size(1080, 720) // HD video .addVariant(42).language('sw').bandwidth(100) // low .addAudio(403).language('sw').kind('low') .addVideo(404).size(720, 480) // largest SD video .addVariant(43).language('sw').bandwidth(200) // mid .addAudio(405).language('sw').kind('mid') .addVideo(404).size(720, 480) // largest SD video .addVariant(44).language('sw').bandwidth(300) // high .addAudio(406).language('sw').kind('high') .addVideo(404).size(720, 480) // largest SD video // Text streams in various languages // To test text selection .addTextStream(90).language('es') .addTextStream(91).language('en') .addTextStream(92).language('ar') .addTextStream(93).language('el') .addTextStream(94).language('he') .addTextStream(95).language('zh') .build(); // Get the original text tracks from the manifest. allTextTracks = shaka.util.StreamUtils.getTextTracks( manifest.periods[0], null); storage.loadInternal = function() { return Promise.resolve({ manifest: manifest, drmEngine: drmEngine }); }; // Use the default track selection callback. storage.configure({ trackSelectionCallback: undefined }); }); function getVariants(data) { return data.tracks.filter(function(t) { return t.type == 'variant'; }); } function getText(data) { return data.tracks.filter(function(t) { return t.type == 'text'; }); } it('stores the best audio language match', function(done) { /** * @param {string} preferredLanguage * @param {string} expectedLanguage * @return {!Promise} */ function testAudioMatch(preferredLanguage, expectedLanguage) { player.configure({preferredAudioLanguage: preferredLanguage}); return storage.store('').then(function(data) { var variantTracks = getVariants(data); expect(variantTracks.length).toBe(1); expect(variantTracks[0].language).toEqual(expectedLanguage); }); } var warning = jasmine.createSpy('shaka.log.warning'); shaka.log.warning = warning; // An exact match is available for en-US, en-GB, and en. // Test all three to show that we are not just choosing the first loose // match, but rather always choosing the best available match. testAudioMatch('en-US', 'en-US').then(function() { return testAudioMatch('en-GB', 'en-GB'); }).then(function() { return testAudioMatch('en', 'en'); }).then(function() { // The best match for en-AU is a matching base language, en. return testAudioMatch('en-AU', 'en'); }).then(function() { // The best match for fr-FR is another related sub-language, fr-CA. return testAudioMatch('fr-FR', 'fr-CA'); }).then(function() { // When there is no related match at all, we choose the primary, es. return testAudioMatch('zh', 'es'); }).then(function() { // Set the primary flags to false. manifest.periods[0].variants.forEach(function(variant) { variant.primary = false; if (variant.audio) variant.audio.primary = false; }); // When there is no related match at all, and no primary, we issue a // warning, and we only store one track. warning.calls.reset(); return storage.store(''); }).then(function(data) { var variantTracks = getVariants(data); expect(variantTracks.length).toBe(1); expect(warning).toHaveBeenCalled(); }).catch(fail).then(done); }); it('stores the largest SD video track, middle audio', function(done) { // This language will select variants with multiple video resolutions. player.configure({preferredAudioLanguage: 'sw'}); storage.store('').then(function(data) { var variantTracks = getVariants(data); expect(variantTracks.length).toBe(1); expect(variantTracks[0].width).toBe(720); expect(variantTracks[0].height).toBe(480); expect(variantTracks[0].language).toEqual('sw'); // Note that kind == 'mid' is not realistic, but we use it here as a // convenient way to detect which audio was selected after offline // storage removes bandwidth information from the original tracks. expect(variantTracks[0].kind).toEqual('mid'); }).catch(fail).then(done); }); it('stores all text tracks', function(done) { storage.store('').then(function(data) { var textTracks = getText(data); expect(textTracks.length).toBe(allTextTracks.length); expect(textTracks).toEqual(jasmine.arrayContaining(allTextTracks)); }).catch(fail).then(done); }); }); // describe('default track selection callback') }); // describe('store') describe('remove', function() { var segmentId; beforeEach(function() { segmentId = 0; }); it('will delete everything', function(done) { var manifestId = 0; createAndInsertSegments(manifestId, 5) .then(function(refs) { var manifest = createManifest(manifestId); manifest.periods[0].streams.push({segments: refs}); return fakeStorageEngine.insert('manifest', manifest); }) .then(function() { expectDatabaseCount(1, 5); return removeManifest(manifestId); }) .then(function() { expectDatabaseCount(0, 0); }) .catch(fail) .then(done); }); it('will delete init segments', function(done) { var manifestId = 1; Promise .all([ createAndInsertSegments(manifestId, 5), createAndInsertSegments(manifestId, 1) ]) .then(function(data) { var manifest = createManifest(manifestId); manifest.periods[0].streams.push( {initSegmentUri: data[1][0].uri, segments: data[0]}); return fakeStorageEngine.insert('manifest', manifest); }) .then(function() { expectDatabaseCount(1, 6); return removeManifest(manifestId); }) .then(function() { expectDatabaseCount(0, 0); }) .catch(fail) .then(done); }); it('will delete multiple streams', function(done) { var manifestId = 1; Promise .all([ createAndInsertSegments(manifestId, 5), createAndInsertSegments(manifestId, 3) ]) .then(function(data) { var manifest = createManifest(manifestId); manifest.periods[0].streams.push({segments: data[0]}); manifest.periods[0].streams.push({segments: data[1]}); return fakeStorageEngine.insert('manifest', manifest); }) .then(function() { expectDatabaseCount(1, 8); return removeManifest(manifestId); }) .then(function() { expectDatabaseCount(0, 0); }) .catch(fail) .then(done); }); it('will delete multiple periods', function(done) { var manifestId = 1; Promise .all([ createAndInsertSegments(manifestId, 5), createAndInsertSegments(manifestId, 3) ]) .then(function(data) { var manifest = createManifest(manifestId); manifest.periods = [ {streams: [{segments: data[0]}]}, {streams: [{segments: data[1]}]} ]; return fakeStorageEngine.insert('manifest', manifest); }) .then(function() { expectDatabaseCount(1, 8); return removeManifest(manifestId); }) .then(function() { expectDatabaseCount(0, 0); }) .catch(fail) .then(done); }); it('will not delete other manifest\'s segments', function(done) { var manifestId1 = 1; var manifestId2 = 2; Promise .all([ createAndInsertSegments(manifestId1, 5), createAndInsertSegments(manifestId2, 3) ]) .then(function(data) { var manifest1 = createManifest(manifestId1); manifest1.periods[0].streams.push({segments: data[0]}); var manifest2 = createManifest(manifestId2); manifest2.periods[0].streams.push({segments: data[1]}); return Promise.all([ fakeStorageEngine.insert('manifest', manifest1), fakeStorageEngine.insert('manifest', manifest2) ]); }) .then(function() { expectDatabaseCount(2, 8); return removeManifest(manifestId1); }) .then(function() { expectDatabaseCount(1, 3); return fakeStorageEngine.get('segment', segmentId - 1); }) .then(function(segment) { expect(segment).toBeTruthy(); }) .catch(fail) .then(done); }); it('will not raise error on missing segments', function(done) { var manifestId = 1; createAndInsertSegments(manifestId, 5) .then(function(data) { var manifest = createManifest(manifestId); data[0].uri = 'offline:0/0/1253'; manifest.periods[0].streams.push({segments: data}); return fakeStorageEngine.insert('manifest', manifest); }) .then(function() { expectDatabaseCount(1, 5); return removeManifest(manifestId); }) .then(function() { // The segment that was changed above was not deleted. expectDatabaseCount(0, 1); }) .catch(fail) .then(done); }); it('throws an error if the content is not found', function(done) { removeManifest(0).then(fail).catch(function(error) { var expectedError = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.STORAGE, shaka.util.Error.Code.REQUESTED_ITEM_NOT_FOUND, 'offline:0'); shaka.test.Util.expectToEqualError(error, expectedError); }).then(done); }); it('throws an error if the URI is malformed', function(done) { var bogusContent = {offlineUri: 'foo:bar'}; storage.remove(bogusContent).then(fail).catch(function(error) { var expectedError = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.STORAGE, shaka.util.Error.Code.MALFORMED_OFFLINE_URI, 'foo:bar'); shaka.test.Util.expectToEqualError(error, expectedError); }).then(done); }); it('raises not found error', function(done) { removeManifest(0) .then(fail) .catch(function(e) { shaka.test.Util.expectToEqualError( e, new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.STORAGE, shaka.util.Error.Code.REQUESTED_ITEM_NOT_FOUND, 'offline:0')); }) .then(done); }); /** * @param {number} manifestCount * @param {number} segmentCount */ function expectDatabaseCount(manifestCount, segmentCount) { var manifests = fakeStorageEngine.getAllData('manifest'); expect(Object.keys(manifests).length).toBe(manifestCount); var segments = fakeStorageEngine.getAllData('segment'); expect(Object.keys(segments).length).toBe(segmentCount); } /** * @param {number} manifestId * @return {!Promise} */ function removeManifest(manifestId) { return storage.remove({offlineUri: 'offline:' + manifestId}); } function createManifest(manifestId) { return { key: manifestId, periods: [{streams: []}], sessionIds: [], duration: 10 }; } /** * @param {number} manifestId * @param {number} count * @return {!Promise.<!Array.<shakaExtern.SegmentDB>>} */ function createAndInsertSegments(manifestId, count) { var ret = new Array(count); for (var i = 0; i < count; i++) { ret[i] = {key: segmentId++}; } return Promise.all(ret.map(function(segment) { return fakeStorageEngine.insert('segment', segment); })).then(function() { return ret.map(function(segment, i) { return { uri: 'offline:' + manifestId + '/0/' + segment.key, startTime: i, endTime: (i + 1) }; }); }); } }); // describe('remove') function makeUris(uri) { return function() { return [uri]; }; } });
define(['SocialNetView', 'text!templates/post/posts.html','views/post/postheaderview','models/PostHeaderModel'], function(SocialNetView, postsTemplate, PostHeaderView, PostHeaderModel) { var postsView = SocialNetView.extend({ postId: 0 , tagName: 'div', myTarget:'', initialize: function(options){ }, render: function() { if(this.model.get('postId')!=undefined){ this.$el.html(_.template(postsTemplate,{ model: this.model.toJSON()})); var account = this.model.get('accountId'); var postId = this.model.get('postId'); var model = new PostHeaderModel(); model.url = 'accounts/'+account+'/getinfoheader'; var shtml = (new PostHeaderView({model:model, postId:postId})).render().el; $(shtml).appendTo('.header-post'); model.fetch(); } return this; } }); return postsView; });
import { initialState } from './selectors' import { IMPRESSION_DETAIL_READ_SUCCESS } from './actions' export default (state = initialState, { type, payload }) => { switch (type) { case IMPRESSION_DETAIL_READ_SUCCESS: return { ...state, detail: payload, } default: return state } }
import React, {PureComponent} from "react"; import Highcharts from 'highcharts'; import HighchartsReact from 'highcharts-react-official'; class ValueChart extends PureComponent { constructor(props) { super(props); this.state ={ dataChart: null } } render(){ return( <div className=""> <div className="titlechart"> Number of occurrences of values </div> <HighchartsReact highcharts={Highcharts} options={{ chart: { type: 'scatter', zoomType: 'xy', height: 375 }, title: { text: '' }, plotOptions: { scatter: { marker: { radius: 5, states: { hover: { enabled: true, lineColor: 'rgb(100,100,100)' } } }, states: { hover: { marker: { enabled: false } } }, tooltip: { headerFormat: '<b>{series.name}</b><br>', pointFormat: '{point.x}, {point.y}' } } }, series: this.props.dataChart, credits: { enabled: false }, yAxis: { title: { text: '' } } }} /> </div> ) } } export default ValueChart;
import React from "react"; import Dynamic from "./App"; import Reservation from "./Form"; class ContainerRow extends React.Component { render(){ return ( <div className='rowC'> <Dynamic /> <Reservation /> </div> ); } } export default ContainerRow;
// Objeto é uma coleção dinâmica de pares chave/valor // Primeiro exemplo const produto = new Object produto.nome = 'Cadeira' produto['marca do produto'] = 'Generica' produto.preco = 220 console.log(produto) // Vai printar geral delete produto.preco console.log(produto) // Segundo exemplo const carro = { modelo: 'A4', valor: 89000, proprietario: { nome: 'Nicolas', idade: 20, endereco: { logradouro: 'Rua ABC', numero: 1223 } }, // Array de objetos condutores: [{ nome: 'Junior', idade: 19 }, { nome: 'Ana', idade: 42 }] } console.log(carro.condutores[1]) delete carro.condutores // console.log(carro.condutores[1]) // Vai dar erro console.log(carro.condutores) // Não vai dar erro, so vai dar que o valor "undefined" não existe console.log(carro)
define([ 'app', 'directives/PostDetailsDirective', 'factories/PostFactory' ], function(app) { 'use strict'; app.create.controller('PostCtrl', [ '$scope', '$routeParams', 'PostFactory', function($scope, $routeParams, PostFactory) { $scope.post = PostFactory.getPost($routeParams.slug).toJSON(); }]); });
/** * @namespace * @constructor * @param {vonline.Base} object * @param {degree} deg 0..360° */ vonline.RotateCommand = function(object, deg) { this.object = object; this.deg = deg; this.oldDeg = this.object.data.rotation; } vonline.RotateCommand.prototype.execute = function() { this.object.setRotation(this.deg); } vonline.RotateCommand.prototype.undo = function() { this.object.setRotation(this.oldDeg); }
"use strict"; var _express = require("express"); var _express2 = _interopRequireDefault(_express); var _utils = require("hull/lib/utils"); var _updateUser = require("./update-user"); var _updateUser2 = _interopRequireDefault(_updateUser); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = function Server(app) { app.post('/notify', (0, _utils.notifHandler)({ groupTraits: true, handlers: { "user:update": function userUpdate(ctx, messages) { messages.map(function (m) { return (0, _updateUser2.default)(ctx, m); }); } } })); app.use("/batch", (0, _utils.batchHandler)(function (_ref, messages) { var metric = _ref.metric, client = _ref.client, ship = _ref.ship; client.logger.debug("batch.process", { messages: messages.length }); messages.map(function (message) { return (0, _updateUser2.default)({ metric: metric, client: client, ship: ship, isBatch: true }, message); }); }, { groupTraits: true, batchSize: 100 })); return app; };