text
stringlengths
7
3.69M
import { Form, Input, Button, Checkbox } from "antd"; import { connect } from "react-redux"; import { Addcontact } from "../redux-store/actions/actions"; function AddContact(props) { const onFinish = (values) => { console.log("Success:", values); props.addcontact({ ...values, id: Date.now() }); //{name:"Payal", phone : 76347867869428, id: 546655667768} }; const onFinishFailed = (errorInfo) => { console.log("Failed:", errorInfo); }; return ( <Form name="basic" labelCol={{ span: 8, }} wrapperCol={{ span: 16, }} initialValues={{ remember: true, }} onFinish={onFinish} onFinishFailed={onFinishFailed} > <Form.Item label="Name" name="username" rules={[ { required: true, message: "Please Enter Name!", }, ]} > <Input /> </Form.Item> <Form.Item label="Contact Number" name="contact" rules={[ { required: true, message: "Please Enter Contact Number !", }, ]} > <Input /> </Form.Item> <Form.Item wrapperCol={{ offset: 10, span: 30, }} > <Button type="primary" htmlType="submit"> Submit </Button> </Form.Item> </Form> ); } const mapDispachToProps = (dispatch) => { return { addcontact: (data) => dispatch(Addcontact(data)), //left to right }; }; export default connect(null, mapDispachToProps)(AddContact);
/** ** engine.js ** sets up event handlers and runs the main game loop **/ //globals const Direction = {"up": 1, "down": 2, "right": 3, "left": 4}; //Direction enum var dir; //current direction snake is travelling var startButton = document.getElementById("start-button"); (function() { var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); startButton.addEventListener("click", function() { var service = SnakeGameService(ctx, 500, 500, 10, 25); service.initGame(); var gameSpeed = 120; //interval time in millis gameLoop = setInterval(service.runGameLoop, gameSpeed); startButton.disabled = true; }); document.addEventListener("keydown", function(event) { switch (event.keyCode) { case 37: if (dir != Direction.right) { dir = Direction.left; } break; case 38: if (dir!= Direction.down) { dir = Direction.up; } break; case 39: if (dir != Direction.left) { dir = Direction.right; } break; case 40: if (dir != Direction.up) { dir = Direction.down; } break; } }); }());
JCL_firebase.setup({ DB_DOMAIN:"grdigital-com" }); function googleLogin(){ var nextURL = document.referrer || "/"; $(document).ready(function(){ JCL_firebase.googleLogin(function(user){ console.log(user); window.top.location = nextURL; },function(error){ console.log(error); }); }); } function facebookLogin(){ var nextURL = document.referrer || "/"; $(document).ready(function(){ JCL_firebase.facebookLogin(function(user){ console.log(user); window.top.location = nextURL; },function(error){ console.log(error); }); }); } function signout(){ var nextURL = window.top.location || "/"; $(document).ready(function(){ JCL_firebase.signOut(function(){ window.top.location = nextURL; }); }); } function registerAuthCallback(callback) { window._JCL_firebase_onAuthStateChanged = window. _JCL_firebase_onAuthStateChanged || []; window._JCL_firebase_onAuthStateChanged.push(callback); var obj = callback; var key = Object.keys(obj)[0]; $(document).ready(function(){ if(typeof(callback[key])=="function") callback[key](); }); } function fireAuthCallbacks() { window._JCL_firebase_onAuthStateChanged = window. _JCL_firebase_onAuthStateChanged || []; var authFiredKeys = []; for (x in window._JCL_firebase_onAuthStateChanged) { var obj = window._JCL_firebase_onAuthStateChanged[x]; var key = Object.keys(obj)[0]; if(typeof(authFiredKeys[key])=="undefined"){ authFiredKeys[key] = key; console.log(key); if(typeof(obj[key])=="function") obj[key](); } else{ consolr.log("already fired"); } } } $(document).ready(function(){ JCL_firebase.onAuthStateChanged(function(user){ fireAuthCallbacks(); }); }); registerAuthCallback({client_setupHeader:function(){ if(JCL_firebase.is_auth()) { } }});
import React, {Component} from 'react'; import {findDOMNode} from 'react-dom'; import {connect} from 'react-redux'; import {setAddDialogOpen, setActiveDetail, setDetailDialogOpen, setFilterSettingsOpen} from '../redux/actions'; import {getAllAlbums} from '../redux/selectors'; import styles from './albums-list.scss'; import {Album, Btn} from '../presentation'; class AlbumsList extends Component { render() { const {albums, onOpenDialog, activeDetailId, activeFilter, onSetFilterSettingsOpen} = this.props; if(albums.length === 0 && activeFilter === 0) { return ( <div className={styles.empty}> <span>You have no albums in your list.</span> <Btn label="Go, add some albums" onClick={() => onOpenDialog()} /> </div> ) } if(albums.length === 0 && activeFilter !== 0) { return ( <div className={styles.empty}> <span>You have no albums in this list.</span> <Btn label="Switch lists" onClick={() => onSetFilterSettingsOpen(true)} /> </div> ) } return ( <div className={styles['albums-list']} ref="container"> {albums.map(album => { return <Album ref={album.id} key={album.id} isActive={activeDetailId === album.id} showCategoryIcon={activeFilter === 0} {...album} onClick={this.handleAlbumClick.bind(this, album.id)} /> })} </div> ) } handleAlbumClick(id) { const {onSetActiveDetail, onSetDetailDialogOpen} = this.props; onSetActiveDetail(id); onSetDetailDialogOpen(true); // this.moveAlbum(id) } moveAlbum(id) { const albumNode = findDOMNode(this.refs[id]); const containerBCR = this.refs.container.getBoundingClientRect() const albumBCR = albumNode.getBoundingClientRect() const left = containerBCR.left - albumBCR.left const top = containerBCR.top - albumBCR.top albumNode.style.willChange = `transform` albumNode.style.transform = `translate(${left}px, ${top}px)` // albumNode.style.position = 'relative' albumNode.style.zIndex = 100 } } const mapState = state => { return { albums: getAllAlbums(state), activeDetailId: state.app.activeDetail, activeFilter: state.filters.activeFilter } } const mapDispatch = dispatch => ({ onOpenDialog() { dispatch(setAddDialogOpen(true)) }, onSetActiveDetail(id) { dispatch(setActiveDetail(id)) }, onSetDetailDialogOpen(open) { dispatch(setDetailDialogOpen(open)) }, onSetFilterSettingsOpen(open) { dispatch(setFilterSettingsOpen(open)) } }) export default connect(mapState, mapDispatch)(AlbumsList);
$(function () { //메인메뉴 $('.mainmenu>li').mouseover(function () { $('.mainnav').css('backgroundColor', 'white'); $('.mainnav').css('border-bottom', '1px solid #eee'); $('.mainmenu>li>a').css('color', 'black'); $('.subnav').show(); $('#logo img').attr('src', 'logo.png'); }); $('.subnav').mouseleave(function () { $('.mainnav').css('backgroundColor', 'transparent'); $('.mainnav').css( 'border-bottom', '1px solid rgba(255, 255, 255, 0.1)' ); $('.mainmenu>li>a').css('color', 'white'); $('.subnav').hide(); $('#logo img').attr('src', 'logo-white.png'); }); //탑 스크롤 $('footer .right>p').click(function () { $('html').animate({ scrollTop: 0 }, 500); }); //패밀리사이트 $('.family-site>li>p').click(function () { var family = $('.family-site>li>p>img').attr('src'); console.log(family); if (family == 'footer-more.png') { $('.family-submenu').slideDown(200); $('.family-site>li>p>img').attr('src', 'footer-less.png'); } else { $('.family-submenu').slideUp(200); $('.family-site>li>p>img').attr('src', 'footer-more.png'); } }); /*sticky*/ $('.mainnav').each(function () { var $window = $(window), $header = $(this), headerOffsetTop = $header.offset().top; $window.on('scroll', function () { if ($window.scrollTop() > headerOffsetTop) { $header.addClass('sticky'); } else { $header.removeClass('sticky'); } }); }); /*팝업창*/ //닫기버튼 $('.close2').click(function () { $('.popup').hide(); }); });
Polymer({ is: "iron-autogrow-textarea", behaviors: [Polymer.IronFormElementBehavior, Polymer.IronValidatableBehavior, Polymer.IronControlState], properties: { bindValue: { observer: "_bindValueChanged", type: String }, rows: { type: Number, value: 1, observer: "_updateCached" }, maxRows: { type: Number, value: 0, observer: "_updateCached" }, autocomplete: { type: String, value: "off" }, autofocus: { type: Boolean, value: !1 }, inputmode: { type: String }, placeholder: { type: String }, readonly: { type: String }, required: { type: Boolean }, minlength: { type: Number }, maxlength: { type: Number } }, listeners: { input: "_onInput" }, observers: ["_onValueChanged(value)"], get textarea() { return this.$.textarea }, get selectionStart() { return this.$.textarea.selectionStart }, get selectionEnd() { return this.$.textarea.selectionEnd }, set selectionStart(e) { this.$.textarea.selectionStart = e }, set selectionEnd(e) { this.$.textarea.selectionEnd = e }, attached: function() { var e = navigator.userAgent.match(/iP(?:[oa]d|hone)/); e && (this.$.textarea.style.marginLeft = "-3px") }, validate: function() { if (!this.required && "" == this.value) return this.invalid = !1, !0; var e; return this.hasValidator() ? e = Polymer.IronValidatableBehavior.validate.call(this, this.value) : (e = this.$.textarea.validity.valid, this.invalid = !e), this.fire("iron-input-validate"), e }, _bindValueChanged: function() { var e = this.textarea; e && (e.value !== this.bindValue && (e.value = this.bindValue || 0 === this.bindValue ? this.bindValue : ""), this.value = this.bindValue, this.$.mirror.innerHTML = this._valueForMirror(), this.fire("bind-value-changed", { value: this.bindValue })) }, _onInput: function(e) { this.bindValue = e.path ? e.path[0].value : e.target.value }, _constrain: function(e) { var t; for (e = e || [""], t = this.maxRows > 0 && e.length > this.maxRows ? e.slice(0, this.maxRows) : e.slice(0); this.rows > 0 && t.length < this.rows;) t.push(""); return t.join("<br/>") + "&#160;" }, _valueForMirror: function() { var e = this.textarea; if (e) return this.tokens = e && e.value ? e.value.replace(/&/gm, "&amp;").replace(/"/gm, "&quot;").replace(/'/gm, "&#39;").replace(/</gm, "&lt;").replace(/>/gm, "&gt;").split("\n") : [""], this._constrain(this.tokens) }, _updateCached: function() { this.$.mirror.innerHTML = this._constrain(this.tokens) }, _onValueChanged: function() { this.bindValue = this.value } });
[{"locale": "es"}, { "key": "2190", "mappings": {"default": {"default": "flecha izquierda"}}, "category": "Sm" }, {"key": "2191", "mappings": {"default": {"default": "flecha arriba"}}, "category": "Sm"}, { "key": "2192", "mappings": {"default": {"default": "flecha derecha", "defaultMP": "flecha"}}, "category": "Sm" }, {"key": "2193", "mappings": {"default": {"default": "flecha abajo"}}, "category": "Sm"}, { "key": "2194", "mappings": {"default": {"default": "flecha izquierda y derecha"}}, "category": "Sm" }, {"key": "2195", "mappings": {"default": {"default": "flecha arriba y abajo"}}, "category": "So"}, { "key": "2196", "mappings": {"default": {"default": "flecha a noroeste"}}, "category": "So" }, {"key": "2197", "mappings": {"default": {"default": "flecha a nordeste"}}, "category": "So"}, { "key": "2198", "mappings": {"default": {"default": "flecha a sureste"}}, "category": "So" }, {"key": "2199", "mappings": {"default": {"default": "flecha a suroeste"}}, "category": "So"}, { "key": "219A", "mappings": {"default": {"default": "flecha izquierda tachada"}}, "category": "Sm" }, {"key": "219B", "mappings": {"default": {"default": "flecha tachada"}}, "category": "Sm"}, { "key": "219C", "mappings": {"default": {"default": "flecha ondulada izquierda"}}, "category": "So" }, {"key": "219D", "mappings": {"default": {"default": "flecha ondulada"}}, "category": "So"}, { "key": "219E", "mappings": {"default": {"default": "flecha izquierda con doble punta"}}, "category": "So" }, { "key": "219F", "mappings": {"default": {"default": "flecha con doble punta hacia arriba"}}, "category": "So" }, { "key": "21A0", "mappings": {"default": {"default": "flecha derechaa con doble punta"}}, "category": "Sm" }, { "key": "21A1", "mappings": {"default": {"default": "flecha con doble punta hacia abajo"}}, "category": "So" }, {"key": "21A2", "mappings": {"default": {"default": "flecha izquierda con cola"}}, "category": "So"}, { "key": "21A3", "mappings": {"default": {"default": "flecha derecha con cola"}}, "category": "Sm" }, {"key": "21A4", "mappings": {"default": {"default": "flecha izquierda de barra"}}, "category": "So"}, { "key": "21A5", "mappings": {"default": {"default": "barra con flecha"}}, "category": "So" }, {"key": "21A6", "mappings": {"default": {"default": "flecha derecha de barra"}}, "category": "Sm"}, { "key": "21A7", "mappings": {"default": {"default": "flecha con barra"}}, "category": "So" }, { "key": "21A8", "mappings": {"default": {"default": "flecha arriba y abajo con base"}}, "category": "So" }, { "key": "21A9", "mappings": {"default": {"default": "flecha izquierda con gancho"}}, "category": "So" }, {"key": "21AA", "mappings": {"default": {"default": "flecha con gancho"}}, "category": "So"}, { "key": "21AB", "mappings": {"default": {"default": "flecha izquierda con lazo"}}, "category": "So" }, {"key": "21AC", "mappings": {"default": {"default": "flecha con lazo"}}, "category": "So"}, { "key": "21AD", "mappings": {"default": {"default": "flecha ondulada izquierda y derecha"}}, "category": "So" }, { "key": "21AE", "mappings": {"default": {"default": "flecha izquierda y derecha tachada"}}, "category": "Sm" }, {"key": "21AF", "mappings": {"default": {"default": "flecha zigzag abajo"}}, "category": "So"}, { "key": "21B0", "mappings": {"default": {"default": "flecha arriba con punta izquierda"}}, "category": "So" }, { "key": "21B1", "mappings": {"default": {"default": "flecha arriba con punta derecha"}}, "category": "So" }, { "key": "21B2", "mappings": {"default": {"default": "flecha abajo con punta izquierda"}}, "category": "So" }, { "key": "21B3", "mappings": {"default": {"default": "flecha abajo con punta derecha"}}, "category": "So" }, { "key": "21B4", "mappings": {"default": {"default": "flecha derecha desde esquina inferior"}}, "category": "So" }, { "key": "21B5", "mappings": {"default": {"default": "flecha hacia abajo desde esquina izquierda"}}, "category": "So" }, { "key": "21B6", "mappings": {"default": {"default": "flecha semicircular superior en sentido antihorario"}}, "category": "So" }, { "key": "21B7", "mappings": {"default": {"default": "flecha semicircular superior en sentido horario"}}, "category": "So" }, { "key": "21B8", "mappings": {"default": {"default": "flecha noroeste a barra larga"}}, "category": "So" }, { "key": "21B9", "mappings": {"default": {"default": "flecha izquierda a barra arriba de flecha derecha a barra"}}, "category": "So" }, { "key": "21BA", "mappings": {"default": {"default": "flecha circular abierta en sentido antihorario"}}, "category": "So" }, { "key": "21BB", "mappings": {"default": {"default": "flecha circular abierta en sentido horario"}}, "category": "So" }, { "key": "21C4", "mappings": {"default": {"default": "flecha derecha arriba de flecha izquierda"}}, "category": "So" }, { "key": "21C5", "mappings": {"default": {"default": "flecha arriba a la izquierda de flecha abajo"}}, "category": "So" }, { "key": "21C6", "mappings": {"default": {"default": "flecha izquierda arriba de flecha derecha"}}, "category": "So" }, { "key": "21C7", "mappings": {"default": {"default": "dos flechas hacia la izquierda"}}, "category": "So" }, {"key": "21C8", "mappings": {"default": {"default": "dos flechas hacia arriba"}}, "category": "So"}, { "key": "21C9", "mappings": {"default": {"default": "dos flechas"}}, "category": "So" }, {"key": "21CA", "mappings": {"default": {"default": "dos flechas hacia abajo"}}, "category": "So"}, { "key": "21CD", "mappings": {"default": {"default": "flecha doble izquierda tachada"}}, "category": "So" }, { "key": "21CE", "mappings": {"default": {"default": "flecha doble izquierda y derecha tachada"}}, "category": "Sm" }, {"key": "21CF", "mappings": {"default": {"default": "flecha doble tachada"}}, "category": "Sm"}, { "key": "21D0", "mappings": {"default": {"default": "flecha doble hacia la izquierda"}}, "category": "So" }, {"key": "21D1", "mappings": {"default": {"default": "flecha doble hacia arriba"}}, "category": "So"}, { "key": "21D2", "mappings": {"default": {"default": "flecha doble"}}, "category": "Sm" }, {"key": "21D3", "mappings": {"default": {"default": "flecha doble hacia abajo"}}, "category": "So"}, { "key": "21D4", "mappings": {"default": {"default": "flecha doble izquierda-derecha"}}, "category": "Sm" }, {"key": "21D5", "mappings": {"default": {"default": "flecha doble vertical"}}, "category": "So"}, { "key": "21D6", "mappings": {"default": {"default": "flecha doble hacia noroeste"}}, "category": "So" }, { "key": "21D7", "mappings": {"default": {"default": "flecha doble hacia nordeste"}}, "category": "So" }, { "key": "21D8", "mappings": {"default": {"default": "flecha doble hacia sudeste"}}, "category": "So" }, { "key": "21D9", "mappings": {"default": {"default": "flecha doble hacia sudoeste"}}, "category": "So" }, {"key": "21DA", "mappings": {"default": {"default": "flecha triple izquierda"}}, "category": "So"}, { "key": "21DB", "mappings": {"default": {"default": "flecha triple"}}, "category": "So" }, {"key": "21DC", "mappings": {"default": {"default": "flecha ondulada izquierda"}}, "category": "So"}, { "key": "21DD", "mappings": {"default": {"default": "flecha ondulada"}}, "category": "So" }, { "key": "21DE", "mappings": {"default": {"default": "flecha hacia arriba con doble tachado"}}, "category": "So" }, { "key": "21DF", "mappings": {"default": {"default": "flecha hacia abajo con doble tachado"}}, "category": "So" }, { "key": "21E0", "mappings": {"default": {"default": "flecha de puntos hacia la izquierda"}}, "category": "So" }, { "key": "21E1", "mappings": {"default": {"default": "flecha de puntos hacia arriba"}}, "category": "So" }, {"key": "21E2", "mappings": {"default": {"default": "flecha de puntos"}}, "category": "So"}, { "key": "21E3", "mappings": {"default": {"default": "flecha de puntos hacia abajo"}}, "category": "So" }, {"key": "21E4", "mappings": {"default": {"default": "flecha izquierda a barra"}}, "category": "So"}, { "key": "21E5", "mappings": {"default": {"default": "flecha derecha a barra"}}, "category": "So" }, { "key": "21E6", "mappings": {"default": {"default": "flecha vacía hacia la izquierda"}}, "category": "So" }, {"key": "21E7", "mappings": {"default": {"default": "flecha vacía hacia arriba"}}, "category": "So"}, { "key": "21E8", "mappings": {"default": {"default": "flecha vacía"}}, "category": "So" }, {"key": "21E9", "mappings": {"default": {"default": "flecha vacía hacia abajo"}}, "category": "So"}, { "key": "21EA", "mappings": {"default": {"default": "flecha vacía hacia arriba desde barra"}}, "category": "So" }, { "key": "21F5", "mappings": {"default": {"default": "upwards arrow to the right of downwards arrow"}}, "category": "Sm" }, { "key": "21FD", "mappings": {"default": {"default": "flecha izquierda con punta vacía"}}, "category": "Sm" }, { "key": "21FE", "mappings": {"default": {"default": "flecha izquierda con punta vacía"}}, "category": "Sm" }, { "key": "21FF", "mappings": {"default": {"default": "flecha izquierda derecha con punta vacía"}}, "category": "Sm" }, { "key": "27F0", "mappings": {"default": {"default": "flecha cuádruple hacia arriba"}}, "category": "Sm" }, { "key": "27F1", "mappings": {"default": {"default": "flecha cuádruple hacia abajo"}}, "category": "Sm" }, { "key": "27F2", "mappings": {"default": {"default": "flecha hacia la izquierda desde círculo"}}, "category": "Sm" }, { "key": "27F3", "mappings": {"default": {"default": "flecha hacia la derecha desde círculo"}}, "category": "Sm" }, {"key": "27F4", "mappings": {"default": {"default": "flecha con más en círculo"}}, "category": "Sm"}, { "key": "27F5", "mappings": {"default": {"default": "flecha larga hacia la izquierda"}}, "category": "Sm" }, {"key": "27F6", "mappings": {"default": {"default": "flecha larga"}}, "category": "Sm"}, { "key": "27F7", "mappings": {"default": {"default": "flecha larga hacia izquierda y derecha"}}, "category": "Sm" }, { "key": "27F8", "mappings": {"default": {"default": "doble flecha larga hacia la izquierda"}}, "category": "Sm" }, {"key": "27F9", "mappings": {"default": {"default": "doble flecha larga"}}, "category": "Sm"}, { "key": "27FA", "mappings": {"default": {"default": "doble flecha larga hacia izquierda y derecha"}}, "category": "Sm" }, { "key": "27FB", "mappings": {"default": {"default": "flecha larga hacia la izquierda, desde barra"}}, "category": "Sm" }, {"key": "27FC", "mappings": {"default": {"default": "flecha larga desde barra"}}, "category": "Sm"}, { "key": "27FD", "mappings": {"default": {"default": "doble flecha larga hacia la izquierda desde barra"}}, "category": "Sm" }, { "key": "27FE", "mappings": {"default": {"default": "doble flecha larga desde barra"}}, "category": "Sm" }, {"key": "27FF", "mappings": {"default": {"default": "flecha larga en zigzag"}}, "category": "Sm"}, { "key": "2905", "mappings": {"default": {"default": "rightwards two headed arrow from bar"}}, "category": "Sm" }, { "key": "290C", "mappings": {"default": {"default": "leftwards double dash arrow"}}, "category": "Sm" }, { "key": "290D", "mappings": {"default": {"default": "rightwards double dash arrow"}}, "category": "Sm" }, { "key": "290E", "mappings": {"default": {"default": "leftwards triple dash arrow"}}, "category": "Sm" }, { "key": "290F", "mappings": {"default": {"default": "rightwards triple dash arrow"}}, "category": "Sm" }, { "key": "2910", "mappings": {"default": {"default": "rightwards two headed triple dash arrow"}}, "category": "Sm" }, { "key": "2911", "mappings": {"default": {"default": "rightwards arrow with dotted stem"}}, "category": "Sm" }, {"key": "2912", "mappings": {"default": {"default": "upwards arrow to bar"}}, "category": "Sm"}, { "key": "2913", "mappings": {"default": {"default": "downwards arrow to bar"}}, "category": "Sm" }, { "key": "2916", "mappings": {"default": {"default": "rightwards two headed arrow with tail"}}, "category": "Sm" }, { "key": "2919", "mappings": {"default": {"default": "cola de flecha hacia la izquierda"}}, "category": "Sm" }, { "key": "291B", "mappings": {"default": {"default": "cola de doble flecha hacia la izquierda"}}, "category": "Sm" }, { "key": "291C", "mappings": {"default": {"default": "cola de doble flecha hacia la derecha"}}, "category": "Sm" }, { "key": "291D", "mappings": {"default": {"default": "flecha hacia diamante relleno a la izquierda"}}, "category": "Sm" }, { "key": "291E", "mappings": {"default": {"default": "flecha hacia diamante a la derecha"}}, "category": "Sm" }, { "key": "291F", "mappings": {"default": {"default": "flecha desde barra hacia diamante a la izquierda"}}, "category": "Sm" }, { "key": "2920", "mappings": {"default": {"default": "flecha desde barra hacia diamante a la derecha"}}, "category": "Sm" }, { "key": "2923", "mappings": {"default": {"default": "flecha a noroeste con garfio"}}, "category": "Sm" }, { "key": "2924", "mappings": {"default": {"default": "flecha a nordeste con garfio"}}, "category": "Sm" }, { "key": "2925", "mappings": {"default": {"default": "flecha a sureste con garfio"}}, "category": "Sm" }, { "key": "2926", "mappings": {"default": {"default": "flecha a suroeste con garfio"}}, "category": "Sm" }, { "key": "2927", "mappings": {"default": {"default": "flechas a noroeste y nordeste"}}, "category": "Sm" }, { "key": "2928", "mappings": {"default": {"default": "flechas a nordeste y sudeste"}}, "category": "Sm" }, { "key": "2929", "mappings": {"default": {"default": "flechas a suddeste y sudoeste"}}, "category": "Sm" }, { "key": "292A", "mappings": {"default": {"default": "flechas a sudoeste y noroeste"}}, "category": "Sm" }, {"key": "2933", "mappings": {"default": {"default": "flecha ondulada"}}, "category": "Sm"}, { "key": "2935", "mappings": {"default": {"default": "flecha hacia la derecha que gira hacia abajo"}}, "category": "Sm" }, { "key": "2936", "mappings": {"default": {"default": "flecha hacia abajo que gira hacia la izquierda"}}, "category": "Sm" }, { "key": "2937", "mappings": {"default": {"default": "flecha hacia abajo que gira hacia la derecha"}}, "category": "Sm" }, { "key": "2938", "mappings": {"default": {"default": "flecha semicircular a la derecha en sentido horario"}}, "category": "Sm" }, { "key": "2939", "mappings": {"default": {"default": "flecha semicircular a la izquierda en sentido antihorario"}}, "category": "Sm" }, {"key": "293C", "mappings": {"default": {"default": "giro negativo"}}, "category": "Sm"}, { "key": "293D", "mappings": {"default": {"default": "giro positivo"}}, "category": "Sm" }, {"key": "2945", "mappings": {"default": {"default": "flecha con más suscrito"}}, "category": "Sm"}, { "key": "2948", "mappings": {"default": {"default": "flecha hacia la izquierda a través de círculo"}}, "category": "Sm" }, { "key": "2949", "mappings": {"default": {"default": "dos cabezas de flecha hacia arriba desde círculo"}}, "category": "Sm" }, {"key": "2970", "mappings": {"default": {"default": "round implies"}}, "category": "Sm"}, { "key": "2971", "mappings": {"default": {"default": "flecha con igual"}}, "category": "Sm" }, {"key": "2972", "mappings": {"default": {"default": "flecha con tilde"}}, "category": "Sm"}, { "key": "2973", "mappings": {"default": {"default": "tilde con flecha hacia la izquierda"}}, "category": "Sm" }, {"key": "2974", "mappings": {"default": {"default": "tilde con flecha"}}, "category": "Sm"}, { "key": "2975", "mappings": {"default": {"default": "flecha con casi igual a"}}, "category": "Sm" }, { "key": "2976", "mappings": {"default": {"default": "flecha hacia la izquierda con menor que"}}, "category": "Sm" }, {"key": "2978", "mappings": {"default": {"default": "flecha con mayor que"}}, "category": "Sm"}, { "key": "2979", "mappings": {"default": {"default": "flecha hacia la izquierda con incluido"}}, "category": "Sm" }, { "key": "297B", "mappings": {"default": {"default": "flecha hacia la izquierda con contiene"}}, "category": "Sm" }, {"key": "29B3", "mappings": {"default": {"default": "conjunto vacío con flecha"}}, "category": "Sm"}, { "key": "29B4", "mappings": {"default": {"default": "conjunto vacío con flecha inversa"}}, "category": "Sm" }, { "key": "2A17", "mappings": {"default": {"default": "integral con flecha hacia la izquierda con garfio"}}, "category": "Sm" }]
try { require('../../config/env'); } catch (err) { require('dotenv').config(); } const jsonServer = require('json-server'); const path = require('path'); const fs = require('fs'); const { MOCK_SERVER_PORT } = process.env; const server = jsonServer.create(); const router = jsonServer.router(path.join(__dirname, 'db.json')); const middlewares = jsonServer.defaults(); server.use((req, res, next) => { res.setHeader('Access-Control-Allow-Origin', `${process.env.ORIGIN_URL}`); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); res.setHeader('Access-Control-Allow-Credentials', true); next(); }); server.use(middlewares); server.use(jsonServer.bodyParser); server.use((req, res, next) => { if (req.method === 'POST') { req.body.createdAt = Date.now(); } next(); }); // custom routes needed to do a replace on UxTos index of db, JSON server does not support the replace functionality out of the box. server.post('/unspentTxOuts', (req, res) => { fs.readFile(path.join(__dirname, 'db.json'), (err, data) => { if (err) { throw err; } const db = JSON.parse(data); const addIds = req.body.map((uTxO, index) => { return { ...uTxO, id: index + 1, }; }); db.unspentTxOuts = addIds; // validate uTxOs arraay fs.writeFile(path.join(__dirname, 'db.json'), JSON.stringify(db, null, 2), (err) => { if (err) { throw err; } res.send('uTxOs updated'); }); }); }); server.use(router); server.listen(MOCK_SERVER_PORT, () => { console.log(`JSON Server is running on port ${MOCK_SERVER_PORT}`); });
(function () { "use strict"; const TEXT_COLOR = "rgb(50, 50, 50)"; const CRITICAL_TEXT_COLOR = "rgb(200, 50, 50)"; const CRITICAL_COUNTDOWN_THRESHOLD = 5000; class CountdownDrawer extends Drawer { _draw(countdown) { this.context.font = "20px impact"; this.context.fillStyle = countdown.value < CRITICAL_COUNTDOWN_THRESHOLD ? CRITICAL_TEXT_COLOR : TEXT_COLOR; this.context.fillText("COUNTDOWN: " + formatTimer(countdown.value), 25, 45); } } function formatTimer(milliseconds) { const minutes = Math.floor(milliseconds / 60000); milliseconds %= 60000; const seconds = zfill(2, Math.floor(milliseconds / 1000)); milliseconds %= 1000; const hundredth = zfill(2, Math.floor(milliseconds / 10)); return `${minutes}'${seconds}"${hundredth}`; } function zfill(minLength, num) { const numString = num.toString(10); if (numString.length >= minLength) { return numString; } return '0'.repeat(minLength - numString.length) + numString; } window.CountdownDrawer = CountdownDrawer; }());
const albumID = 'jgv3Zpc'; const albumUrl = "https://api.imgur.com/3/album/" + albumID + "/images"; window.onload = function (e) { getData(albumUrl).then( data => { renderImageAPI("category__list", data.data) } ) } async function getData(url = "") { const rep = await fetch(url, { method: "GET", headers: { 'Authorization': 'Client-ID 6e3e1748bacf91d' } }) return rep.json(); } function renderImageAPI(id, data) { if (data != undefined && data.length != 0) { let result = data.map((val, i, arr) => { return ` <div class="category__item"> <img src="${val.link}" alt="" class="category__image"> <h3 class="category__name">DieuXinhDep</h3> <a href="#" class="category__link"> CC Certified <i class="fa fa-long-arrow-right" aria-hidden="true"></i> </a> </div> ` }) document.getElementById(id).innerHTML = result.join(''); return false; } }
import tw from 'tailwind-styled-components' /** */ export const StyledIntroCoTwoLiner = tw.div` col-span-2 `
import React from 'react'; import Layout from '../../components/Layout'; import ProjectRoll from '../../components/ProjectRoll'; import classes from './projects.module.scss'; import Helmet from 'react-helmet'; import PageTransition from 'gatsby-plugin-page-transitions'; const ProjectPage = () => { return ( <Layout> <PageTransition> <Helmet titleTemplate='%s | Henry Fellerhoff'> <title>Portfolio</title> </Helmet> <div className={classes.container}> <h1 className={classes.pageTitle}>Portfolio</h1> <ProjectRoll /> </div> </PageTransition> </Layout> ); }; export default ProjectPage;
cssPubSub.subscribe("heart_container","color");
'use strict'; app.controller('AnalyticsCtrl', function ($scope, factAnalytics, $timeout) { console.log ('AnalyticsCtrl'); $scope.selectedwebsite; $scope.loadpages = function (pagedata) { console.log('loadpages: started "loadpages"'); console.log('loadpages: pagedata: ' + JSON.stringify(pagedata)); factAnalytics.getPages(pagedata).then(function(data) { var websites = data.websites; var screenShotDirClient = data.screenShotDirClient; var s; console.log('"loadpages" - found a screenshot'); for (var i = 0; i < websites.length; i++) { console.log('loadpages: (websites[i]): ' + JSON.stringify(websites[i])); if (((websites[i].imgdirectory !== null) && (websites[i].imgfilename !== null)) && ((websites[i].imgdirectory !== '') && (websites[i].imgfilename !== ''))) { console.log('"loadpages" - found a screenshot'); websites[i].screenshoturl = screenShotDirClient + '/' + websites[i].imgdirectory +'/' + websites[i].imgfilename; console.log('"loadpages" - websites[i].screenshoturl: ' + websites[i].screenshoturl); } else { console.log('"loadpages" - found no screenshot'); websites[i].screenshoturl = 'nope'; } } $scope.allPages = websites; $scope.countPages = websites.length; // console.log('AnalyticsCtrl: $scope.allPages: ' + JSON.stringify(data)); $scope.selectedwebsite = pagedata.selectedWebsite.name; $scope.showSuccess = true; $scope.alertSuccessMessage = "pages loaded!"; $timeout(function() { $scope.showSuccess = false; $scope.alertSuccessMessage = ''; }, 3000); }, function (error) { console.log('JobCtrl: loadpages. ERROR: error: ' + JSON.stringify(error)); }); console.log('JobCtrl: ended "loadpages"'); }; function loadWebsites() { // load existing domains and show them factAnalytics.getWebsites().then(function(data) { var s; // add a useful text for the user to select for (var i = 0; i < data.length; i++) { s = 'uid: ' + data[i].uid + ' | ' + data[i].name + ' | ' + data[i].description + ' | ' + data[i].status; data[i].text = s; } $scope.allWebsites = data; $scope.showSuccess = true; $scope.alertSuccessMessage = "webpages loaded!"; $timeout(function() { $scope.showSuccess = false; $scope.alertSuccessMessage = ''; }, 3000); }, function(error) { $scope.allDomains = []; $scope.showError = true; $scope.alertErrorMessage = "an error occured while loading the webpages!"; $timeout(function() { $scope.showError = false; $scope.alertErrorMessage = ''; }, 3000); }); } $scope.numberPages = []; var entry= { text: '50', maxCount : 50 } $scope.numberPages.push(entry); var entry= { text: '100', maxCount : 1000 } $scope.numberPages.push(entry); var entry= { text: '250', maxCount : 250 } $scope.numberPages.push(entry); var entry= { text: '500', maxCount : 500 } $scope.numberPages.push(entry); var entry= { text: '1000', maxCount : 1000 } $scope.numberPages.push(entry); var entry= { text: '5000', maxCount : 5000 } $scope.numberPages.push(entry); var entry= { text: 'all', maxCount : 100000000 } $scope.numberPages.push(entry); loadWebsites(); })
import { combineReducers } from 'redux'; export const context_act = { SONG_EDIT_C: "SONG_EDIT_C", SONG_BURGER_C: "SONG_BURGER_C", PLAYLIST_BURGER_C: "PLAYLIST_BURGER_C", CLOSE_CONTEXT: "CLOSE_CONTEXT", SELECT_PLAYLIST_C: "SELECT_PLAYLIST_C", PLAYLIST_EDIT_C: "PLAYLIST_EDIT_C", NEW_PLAYLIST: 'NEW_PLAYLIST', ACCOUNT: "ACCOUNT", } export const error_act = { RECEIVE_SEARCH_ERRORS: "RECEIVE_SEARCH_ERRORS", RECEIVE_SESSION_ERRORS: "RECEIVE_SESSION_ERRORS", } export const session_act = { RECEIVE_CURRENT_USER: "RECEIVE_CURRENT_USER", LOGOUT_CURRENT_USER: "LOGOUT_CURRENT_USER", RECEIVE_SESSION_ERRORS: "RECEIVE_SESSION_ERRORS", } export const ent_act = { INIT_STORE: "INIT_STORE", RECEIVE_SONG_D: "RECEIVE_SONG_D", RECEIVE_SONG_D_EDIT: "RECEIVE_SONG_D_EDIT", DELETE_SONG: 'DELETE_SONG', RECEIVE_SONG_URL: "RECEIVE_SONG_URL", RECEIVE_PLAYLIST: "RECEIVE_PLAYLIST", UPDATE_PLAYLIST: "UPDATE_PLAYLIST", RECEIVE_PLAYLIST_TITLE_D: "RECEIVE_PLAYLIST_TITLE", APPEND_PLAYLIST: "APPEND_PLAYLIST", DELETE_PLAYLIST: "DELETE_PLAYLIST", RESET_PLAYLISTS: 'RESET_PLAYLISTS', REMOVE_FROM_PLAYLIST: "REMOVE_FROM_PLAYLIST", LOAD_TRACK: "LOAD_TRACK", SET_PLAY: "SET_PLAY", SET_PAUSE: "SET_PAUSE", RECEIVE_SEARCH_RESULTS: 'RECEIVE_SEARCH_RESULTS', CLEAR_SEARCH_RESULTS: 'CLEAR_SEARCH_RESULTS', SET_LOAD_START: 'SET_LOAD_START', SET_LOAD_STOP: 'SET_LOAD_STOP', } ////////////// UI Reducer ////////////////// const contextMenu = (state = null, action) => { Object.freeze(state); switch (action.type) { case context_act.SONG_BURGER_C: return action case context_act.PLAYLIST_BURGER_C: return action case context_act.NEW_PLAYLIST: return action case context_act.ACCOUNT: return action case context_act.SONG_EDIT_C: return { ...state, type: action.type } case context_act.PLAYLIST_EDIT_C: return { ...state, type: action.type } case context_act.SELECT_PLAYLIST_C: return { ...state, type: action.type } case context_act.CLOSE_CONTEXT: return null default: return state; } }; const ui = combineReducers({ contextMenu }); ////////////// UI Reducer ////////////////// ////////////// Errors Reducer ////////////////// const sessionErrors = (state = [], action) => { Object.freeze(state); switch (action.type) { case error_act.RECEIVE_SESSION_ERRORS: return action.errors; case session_act.RECEIVE_CURRENT_USER: return []; default: return state; } }; const searchErrors = (state = [], action) => { Object.freeze(state); switch (action.type) { case error_act.RECEIVE_SEARCH_ERRORS: return action.errors; case ent_act.RECEIVE_SEARCH_RESULTS: return [] default: return state; } }; const errors = combineReducers({ sessionErrors, searchErrors }); ///////////// Errors Reducer ////////////////// ///////////// Session Reducer ////////////////// const _nullUser = Object.freeze({ currentUser: null }); const session = (state = _nullUser, action) => { Object.freeze(state); switch (action.type) { case session_act.RECEIVE_CURRENT_USER: return { currentUser: action.currentUser }; case session_act.LOGOUT_CURRENT_USER: return _nullUser; default: return state; } }; ///////////// Session Reducer ////////////////// ///////////// Entities Reducer ////////////////// const songD = (state = [], action) => { Object.freeze(state); switch (action.type) { case ent_act.RECEIVE_SONG_D: return { ...state, ...action.songD, yt_id_set: new Set( [ ...state.yt_id_set, ...Object.values(action.songD).map(e => e.yt_id) ] ) }; case ent_act.RECEIVE_SONG_D_EDIT: return { ...state, ...action.songD }; case ent_act.INIT_STORE: return { ...state, ...action.songD, yt_id_set: new Set(Object.values(action.songD).map(e => e.yt_id)) }; case ent_act.DELETE_SONG: const newSongD = { ...state }; delete newSongD[action.song_id]; const ns = new Set(state.yt_id_set) ns.delete(state[action.song_id].yt_id) newSongD.yt_id_set = ns; return newSongD; default: return state; } }; const playlistD = (state = {}, action) => { Object.freeze(state); switch (action.type) { case ent_act.INIT_STORE: const songs_playlist = Object.values(action.songD) // .sort((a,b)=>parseInt(b.order)-parseInt(a.order)) .sort((b, a) => parseInt(b.order) - parseInt(a.order)) .map(e => [e.id, null]) return { ...state, songs_playlist, playlistTitleD: action.playlistTitleD }; case ent_act.RECEIVE_SONG_D: const new_songs = Object.values(action.songD) // .sort((a,b)=>parseInt(b.order)-parseInt(a.order)) .sort((b, a) => parseInt(b.order) - parseInt(a.order)) .map(e => [e.id, null]) // return { ...state, songs_playlist: [...new_songs, ...state.songs_playlist]}; return { ...state, songs_playlist: [...state.songs_playlist, ...new_songs] }; case ent_act.DELETE_SONG: return { ...state, songs_playlist: state.songs_playlist.filter(el => el[0] != action.song_id) }; case ent_act.RECEIVE_PLAYLIST: return { ...state, [action.playlist_id]: action.playlist }; case ent_act.RECEIVE_PLAYLIST_TITLE_D: return { ...state, playlistTitleD: { ...state.playlistTitleD, ...action.playlistTitleD } }; case ent_act.APPEND_PLAYLIST: return { ...state, [action.playlist_id]: [...state[action.playlist_id], ...action.tracks] } case ent_act.DELETE_PLAYLIST: const newSt = { ...state, playlistTitleD: { ...state.playlistTitleD } } delete newSt.playlistTitleD[action.playlist_id] delete newSt[action.playlist_id] return newSt case ent_act.REMOVE_FROM_PLAYLIST: const newpl = [...state[action.pl_id]] newpl.splice(action.idx, 1) return { ...state, [action.pl_id]: newpl } case ent_act.RESET_PLAYLISTS: const st = { ...state } action.pls_to_reset.forEach(id => delete st[id]) return st; case ent_act.RECEIVE_SEARCH_RESULTS: return { ...state, search_results: action.search_results, search_term: action.search_term, } case ent_act.SET_LOAD_START: return { ...state, search_results: [], loading: true, } case ent_act.SET_LOAD_STOP: return { ...state, loading: false } case ent_act.CLEAR_SEARCH_RESULTS: return { ...state, search_results: [], search_term: "", } default: return state; } }; const player = (state = {}, action) => { Object.freeze(state); switch (action.type) { case ent_act.RECEIVE_SONG_URL: return { ...state, songUrl: action.url }; case ent_act.LOAD_TRACK: return { ...state, track: action.track }; case ent_act.RECEIVE_PLAYLIST: return { ...state, track: action.track }; case ent_act.REMOVE_FROM_PLAYLIST: return { ...state, track: action.track }; case ent_act.DELETE_SONG: return { ...state, track: action.track }; case ent_act.SET_PLAY: return { ...state, playing: true }; case ent_act.SET_PAUSE: return { ...state, playing: false }; case ent_act.SET_LOAD_START: return { ...state, track: state.track && state.track[0] != 'search_results' ? state.track : null}; case ent_act.CLEAR_SEARCH_RESULTS: return { ...state, track: state.track && state.track[0] != 'search_results' ? state.track : null }; default: return state; } }; const entities = combineReducers({ playlistD, songD, }); ///////////// Entities Reducer ////////////////// const rootReducer = combineReducers({ entities, session, errors, ui, player }); export default rootReducer;
steal('jquery/class') .then(function($){ $.Class('TechStudio.JmvcExtensions.Lang.Looper', /* @static */ { }, /* @prototype */ { init: function(loopTime, callbackToLoop) { this.loopTime = loopTime; this.callbackToLoop = callbackToLoop; }, start : function(){ this.looper(); }, stop : function(){ clearTimeout(this.timer); }, looper : function(){ this.callbackToLoop(); this.timer = setTimeout(this.callback('looper'), this.loopTime); } }); })
function ClimateChange(year, carbonDioxide, globalTemp, iceSheets, seaLevel) { this.year = year; this.carbonDioxide = carbonDioxide; this.globalTemp = globalTemp; this.iceSheets = iceSheets; this.seaLevel = seaLevel; } const Y2017 = new ClimateChange(2017, 406.17, 0.95, -1915.45, 43.8); const Y2016 = new ClimateChange(2016, 402.56, 0.89, -1594.66, 44.75); const Y2015 = new ClimateChange(2015, 399.98, 0.83, -1421.03, 35.01); const Y2014 = new ClimateChange(2014, 397.85, 0.77, -1215.15, 28.43); const Y2013 = new ClimateChange(2013, 395.55, 0.71, -941.42, 29.66); const Y2012 = new ClimateChange(2012, 393.12, 0.67, -1026.55, 20.34); const Y2011 = new ClimateChange(2011, 391.33, 0.63, -841.22, 11.57); const Y2010 = new ClimateChange(2010, 388.71, 0.62, -676.08, 15.56); const Y2009 = new ClimateChange(2009, 386.94, 0.62, -709.52, 10.12); const Y2008 = new ClimateChange(2008, 385.52, 0.62, -449.31, 5.78); const Y2007 = new ClimateChange(2007, 382.89, 0.61, -310.88, 5.72); const Y2006 = new ClimateChange(2006, 381.38, 0.61, -316.99, 4.37); const Y2005 = new ClimateChange(2005, 378.46, 0.61, -213.58, 1.23); const Y2004 = new ClimateChange(2004, 377, 0.6, -243, -0.82); function createObjects() { var allObjects = [Y2004, Y2005, Y2006, Y2007, Y2008, Y2009, Y2010, Y2011, Y2012, Y2013, Y2013, Y2015, Y2016, Y2017]; var halfObjects = [Y2005, Y2007, Y2009, Y2011, Y2013, Y2015, Y2017]; return halfObjects; }
if (App == null || typeof App != "object") { var App = new Object(); } //set globals const d = document; let personName, bkImg, canvas, ctx, ctxTitle = "Happy Halloween!", titleHeight = 0, titleAnimation, nameWidth = 0, nameHeight = 0; App.Submit = function () { personName = d.getElementById("name").value; if (personName === "") { d.getElementById("name-validation").classList.remove("hidden"); } else { d.getElementById("greeting").classList.add("hidden"); d.getElementById("canvas-wrapper").classList.remove("hidden"); App.Canvas.Init(); } }; App.Canvas = {}; App.Canvas.Init = function () { canvas = d.getElementById("CanvasDisplay"); this.SetBkg(); this.SetTitle(); }; App.Canvas.SetBkg = function () { if (canvas && canvas.getContext) { ctx = canvas.getContext("2d"); ctx2 = canvas.getContext("2d"); if (ctx) { bkImg = d.getElementById("image-bkg"); ctx.drawImage(bkImg, 0, 0); } } }; App.Canvas.Reset = function () { App.Canvas.SetBkg(); }; App.Canvas.SetTitle = function () { ctx.font = "32pt Verdana"; ctx.fillStyle = "yellow"; ctx.strokeStyle = "rgba(0,255,0,0.8)"; titleAnimation = setInterval(this.TitleAnimate, 10); }; App.Canvas.TitleAnimate = function () { if (titleHeight < 70) { App.Canvas.Reset(); //ctx.restore(); titleHeight++; ctx.fillText(ctxTitle, 20, titleHeight); ctx.strokeText(ctxTitle, 20, titleHeight); } else { clearInterval(titleAnimation); ctx.fillText(ctxTitle, 20, titleHeight); ctx.strokeText(ctxTitle, 20, titleHeight); App.Canvas.DispName(); } }; App.Canvas.DispName = function () { var alpha = 0.0, interval = setInterval(function () { ctx.font = "italic 40px Arial"; ctx.textAlign = "center"; ctx.shadowColor = "rgba(0, 0, 0, .1)"; ctx.shadowBlur = 15; ctx.fillText(personName, 220, 120); ctx.fillStyle = "rgba(249, 108, 18, " + alpha + " )"; ctx.fillText(personName, 220, 120); ctx.fillStyle = "rgba(255, 255, 255, " + alpha + ")"; ctx.fillText(personName, 222, 123); alpha = alpha + 0.05; if (alpha < 0) { canvas.width = canvas.width; clearInterval(interval); } }, 50); App.Canvas.Glow.Start(); }; App.Canvas.Glow = {}; App.Canvas.Glow.Start = function () { let glowCount = 0; setInterval(function () { glowCount++; if (glowCount % 2 == 0) { App.Canvas.Glow.StarOne(true); App.Canvas.Glow.StarTwo(false); App.Canvas.Glow.StarThree(true); } else { App.Canvas.Glow.StarOne(false); App.Canvas.Glow.StarTwo(true); App.Canvas.Glow.StarThree(false); } }, 1200); }; App.Canvas.Glow.StarOne = function (glowOn) { ctx.beginPath(); let x = 29, y = 316; if (glowOn) { ctx.arc(x, y, 3, 0, 2 * Math.PI, false); ctx.shadowColor = "rgba(255, 255, 255, 1)"; ctx.shadowBlur = 10; ctx.fillStyle = "rgba(255, 255, 255, 1)"; ctx.fill(); ctx.lineWidth = 2; ctx.strokeStyle = "rgba(255, 255, 255, 1)"; ctx.stroke(); } else { ctx.arc(x, y, 10, 0, 2 * Math.PI, false); ctx.shadowColor = "rgba(43, 00, 130, 1)"; ctx.shadowBlur = 0; ctx.fillStyle = "rgba(43, 00, 130, 1)"; ctx.fill(); ctx.lineWidth = 2; ctx.strokeStyle = "rgba(43, 00, 130, 1)"; ctx.stroke(); } }; App.Canvas.Glow.StarTwo = function (glowOn) { ctx.beginPath(); let x = 375, y = 333; if (glowOn) { ctx.arc(x, y, 3, 0, 2 * Math.PI, false); ctx.shadowColor = "rgba(255, 255, 255, 1)"; ctx.shadowBlur = 10; ctx.fillStyle = "rgba(255, 255, 255, 1)"; ctx.fill(); ctx.lineWidth = 2; ctx.strokeStyle = "rgba(255, 255, 255, 1)"; ctx.stroke(); } else { ctx.arc(x, y, 10, 0, 2 * Math.PI, false); ctx.shadowColor = "rgba(64, 00, 147, 1)"; ctx.shadowBlur = 0; ctx.fillStyle = "rgba(64, 00, 147, 1)"; ctx.fill(); ctx.lineWidth = 2; ctx.strokeStyle = "rgba(64, 00, 147, 1)"; ctx.stroke(); } }; App.Canvas.Glow.StarThree = function (glowOn) { ctx.beginPath(); let x = 399, y = 124; if (glowOn) { ctx.arc(x, y, 1, 0, 2 * Math.PI, false); ctx.shadowColor = "rgba(255, 255, 255, 1)"; ctx.shadowBlur = 3; ctx.fillStyle = "rgba(255, 255, 255, 1)"; ctx.fill(); ctx.lineWidth = 2; ctx.strokeStyle = "rgba(255, 255, 255, 1)"; ctx.stroke(); } else { ctx.arc(x, y, 3, 0, 2 * Math.PI, false); ctx.shadowColor = "rgba(18, 00, 107, 1)"; ctx.shadowBlur = 0; ctx.fillStyle = "rgba(18, 00, 107, 1)"; ctx.fill(); ctx.lineWidth = 2; ctx.strokeStyle = "rgba(18, 00, 107, 1)"; ctx.stroke(); } };
import React, { useState } from 'react'; import { useSelector } from 'react-redux'; import { Form, Input, Button, DatePicker, InputNumber, Switch, Modal } from 'antd'; import moment from 'moment'; import { useFormik } from 'formik'; import movieApi from 'apis/movieApi'; import './AddMovie.scss'; const AddMovie = (props) => { const [imgSrc, setImgSrc] = useState(null); const maNhom = useSelector(state => state.authReducer.currentUser.maNhom); const { TextArea } = Input; const form = useFormik({ initialValues: { tenPhim: '', moTa: '', ngayKhoiChieu: '', trailer: '', dangChieu: false, sapChieu: false, hot: false, danhGia: 0, hinhAnh: {name: null}, maNhom, }, onSubmit: (value) => { console.log('Received', value); // Create formData let formData = new FormData(); for (let key in value) { if (key !== 'hinhAnh') { formData.append(key, value[key]); } else { formData.append('File', value.hinhAnh, value.hinhAnh.name); } } console.log(formData.get('File')) movieApi.addMovieUploadPictureApi(formData) .then(response => { console.log(response); Modal.success({ title: 'Added successfully!', content: ( <div> <p>New Movie {form.values.tenPhim} has been added</p> </div> ), onOk: () => props.history.push('/admin/movie') }); }) .catch(error => { console.log(error); Modal.error({ title: 'Found an error!', content: ( <div> <p>Error code {error}</p> </div> ), }) }); form.resetForm(); } }) const handleChange = event => { const { name, value } = event.target; form.setFieldValue(name, value); }; const handleChangeDatePicker = value => { let ngayKhoiChieu = moment(value).format('DD/MM/YYYY'); form.setFieldValue("ngayKhoiChieu", ngayKhoiChieu); } const handleChangeSwitch = (name) => { return (value) => { form.setFieldValue(name, value); } }; const handleChangeFile = (event) => { // extract file from event, since input can take several items, we only need the first one console.log(event.target.files) if (event.target.files.length === 0) { form.setFieldValue('hinhAnh', {}); setImgSrc(null); return; } let file = event.target.files[0]; form.setFieldValue('hinhAnh', file); // Display picture for user to test switch (file.type) { case 'image/jpeg': case 'image/jpg': case 'image/png': // create a file reader let reader = new FileReader(); reader.readAsDataURL(file); reader.onload = (event) => { setImgSrc(event.target.result) }; break; default: setImgSrc(null) break; } }; return ( <> <h3>Add New</h3> <Form labelCol={{ span: 6, }} wrapperCol={{ span: 14, }} layout="horizontal" onSubmitCapture={form.handleSubmit} initialValues={form.initialValues} validateTrigger="onBlur" style={{ textAlign: 'left' }} > <Form.Item label="Movie" rules={[ { required: true, message: 'Input Movie Name' } ]} > <Input onChange={handleChange} name="tenPhim" /> </Form.Item> <Form.Item label="Trailer URL" rules={[ { required: true, message: 'Input Trailer URL' } ]} > <Input onChange={handleChange} name="trailer" /> </Form.Item> <Form.Item label="Description" rules={[ { required: true, message: 'Input Trailer URL' } ]} > <TextArea rows={3} allowClear onChange={handleChange} name="moTa" /> </Form.Item> <Form.Item label="Premier Date" rules={[ { required: true, message: 'Please choose a Premier Date' } ]} > <DatePicker format={"DD/MM/YYYY"} onChange={handleChangeDatePicker} /> </Form.Item> <Form.Item label="Now Showing"> <Switch onChange={handleChangeSwitch('dangChieu')} /> </Form.Item> <Form.Item label="Hot"> <Switch onChange={handleChangeSwitch('hot')} /> </Form.Item> <Form.Item label="Coming Soon"> <Switch onChange={handleChangeSwitch('sapChieu')} /> </Form.Item> <Form.Item label="Rating" rules={[ { required: true, message: 'Please give it a rating', validationTrigger: 'onBlur', } ]} > <InputNumber min={1} max={10} onChange={value => form.setFieldValue('danhGia', value)} /> </Form.Item> <Form.Item label="Movie Poster"> <label className="custome__input__file"> <input id="input__file" type="file" onChange={handleChangeFile} accept="image/png, image/jpg, image/jpeg, image/gif" /> Upload Poster File </label> <img src={imgSrc} alt="poster" height={120} /> </Form.Item> <Form.Item wrapperCol={{ offset: 11, span: 13 }}> <Button htmlType="submit">Add Movie</Button> </Form.Item> </Form> </> ); }; export default AddMovie;
import Immutable from 'seamless-immutable' export default function combineColorOptions(options, placeholder) { /* eslint-disable prefer-const */ let colorOptions = Immutable.asMutable(options) /* eslint-enable prefer-const */ colorOptions.unshift(placeholder) return colorOptions }
import { mutations } from './mutations'; describe('@/store/supportChat/mutations', () => { const state = { chat: '', }; const chat = '<script>sample data</script>'; it('SET_SUPPORT_CHAT', () => { mutations.SET_SUPPORT_CHAT(state, chat); expect(state.chat).toEqual(chat); }); });
const storeTolocal=()=>{ let name=document.getElementById("name").value; let email=document.getElementById("email").value; let org=document.getElementById("org").value; let flag =0; if(localStorage.length>0){ Object.keys(localStorage).forEach((key)=>{ if(email == key){ alert("sorry user already found"); flag=1; } }); } if (flag ==0 ){ localStorage.setItem(email,JSON.stringify([{"name":name,"org":org}])); } let rows=''; Object.keys(localStorage).forEach((keys)=>{ // console.log(keys+localStorage.getItem(keys)); item = JSON.parse(localStorage.getItem(keys)); console.log(Object.values(item)[0].name); if(Object.values(item)[0].name!=''){ rows +=`<tr> <td> ${Object.values(item)[0].name} </td> <td> ${keys}</td> <td> ${Object.values(item)[0].org} </td> </tr> `} }); let table=` <table> <tr> <th> Name </th> <th> email </th> <th> Organizarion </th> </tr> ${rows} </table> ` document.getElementById('table-div').innerHTML=table; } let emap = new Map(); const deleteLocal=()=>{ let delemail = document.getElementById("emsearch").value; Object.keys(localStorage).forEach((key)=>{ emap.set(key,localStorage.getItem(key)); // console.log(key,localStorage.getItem(key)); }); if(emap.has(delemail)){ emap.delete(delemail); } else{ alert("id not found"); } let rows=' '; for(let [key,value] of emap.entries()){ if(key!=' ' || key !=''){ valuez = JSON.parse(value); rows +=`<tr> <td> ${Object.values(valuez)[0].name} </td> <td> ${key}</td> <td> ${Object.values(valuez)[0].name} </td> </tr> `}} let table=` <table> <tr> <th> Name </th> <th> email </th> <th> Organizarion </th> </tr> ${rows} </table> ` document.getElementById('table-div').innerHTML=table; localStorage.clear(); for(let [key,value] of emap.entries()){ if(key!=' '||key!=''){ localStorage.setItem(key,value); } } // Object.keys(localStorage).forEach((key)=>{ // item=JSON.parse(localStorage.getItem(key)); // if(Object.values(item)) // }) }
/* @flow */ import Clogy from './main/Clogy'; import type { ClogyType } from './globalFlowTypes'; const clogy: ClogyType = new Clogy(); export default clogy; // Because of Babel@6 // Can use plugin: https://www.npmjs.com/package/babel-plugin-add-module-exports // Used this soln. instead: // http://stackoverflow.com/questions/34736771/webpack-umd-library-return-object-default/34778391#34778391 // // This is intended behaviour from babel@ to babel@6 to support ES6 import export module system // // $FlowFixMe: suppressing this error until babel changes this style module.exports = clogy;
module.exports = { users: require("./users"), bills: require('./bills'), categories: require('./categories'), customers: require('./customers'), products: require('./products') };
import React from 'react'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemText from '@material-ui/core/ListItemText'; import ListSubheader from '@material-ui/core/ListSubheader'; import Avatar from '@material-ui/core/Avatar'; import strings from "../strings"; import git from '../img/tech/git.png'; import django from '../img/tech/django.png'; import flask from '../img/tech/flask.jpg'; import tornado from '../img/tech/tornado.jpg'; import celery from '../img/tech/celery.jpeg'; import node from '../img/tech/node.png'; import exprerss from '../img/tech/express.png'; import sails from '../img/tech/sails.png'; import electron from '../img/tech/electron.png'; import jquery from '../img/tech/jquery.png'; import react from '../img/tech/react.png'; import redux from '../img/tech/redux.png'; import backbone from '../img/tech/backbone.png'; import marionette from '../img/tech/marionette.png'; import bem from '../img/tech/bem.png'; import yii from '../img/tech/yii.png'; import zend from '../img/tech/zend.png'; import laravel from '../img/tech/laravel.png'; import wp from '../img/tech/wp.png'; import alamofire from '../img/tech/alamofire.png'; import coredata from '../img/tech/cd.png'; import rxswift from '../img/tech/rxswift.jpeg'; import xcode from '../img/tech/xcode.png'; import vuforia from '../img/tech/vuforia.png'; import docker from '../img/tech/docker.jpg'; import rabbit from '../img/tech/rabbit.png'; import webpack from '../img/tech/webpack.png'; import gulp from '../img/tech/gulp.png'; import mysql from '../img/tech/mysql.svg'; import postgres from '../img/tech/postgres.png'; import mongo from '../img/tech/mongo.jpeg'; import redis from '../img/tech/redis.jpg'; import sqlite from '../img/tech/sqlite.jpeg'; class Stack extends React.Component { componentDidMount() { } render() { return ( <div> <h2>{strings[this.props.lang].titles.technologyStack}</h2> <div style={{display: 'flex', flexWrap: 'wrap'}}> <List subheader={<ListSubheader component="div">Python</ListSubheader>} className="grayscaled" style={{flex: 1}}> <ListItem> <Avatar src={django}/> <ListItemText primary="Django"/> </ListItem> <ListItem> <Avatar src={flask}/> <ListItemText primary="Flask"/> </ListItem> <ListItem> <Avatar src={tornado}/> <ListItemText primary="Tornado"/> </ListItem> <ListItem> <Avatar src={celery}/> <ListItemText primary="Celery"/> </ListItem> </List> <List subheader={<ListSubheader component="div">Javascript (backend)</ListSubheader>} className="grayscaled" style={{flex: 1}}> <ListItem> <Avatar src={node}/> <ListItemText primary="Node.js"/> </ListItem> <ListItem> <Avatar src={exprerss}/> <ListItemText primary="Express"/> </ListItem> <ListItem> <Avatar src={sails}/> <ListItemText primary="Sails.js"/> </ListItem> <ListItem> <Avatar src={electron}/> <ListItemText primary="Electron"/> </ListItem> </List> <List subheader={<ListSubheader component="div">Swift</ListSubheader>} className="grayscaled" style={{flex: 1}}> <ListItem> <Avatar src={alamofire}/> <ListItemText primary="Alamofire"/> </ListItem> <ListItem> <Avatar src={coredata}/> <ListItemText primary="CoreData"/> </ListItem> <ListItem> <Avatar src={rxswift}/> <ListItemText primary="RxSwift"/> </ListItem> <ListItem> <Avatar src={xcode}/> <ListItemText primary="Xcode"/> </ListItem> <ListItem> <Avatar src={vuforia}/> <ListItemText primary="Vuforia"/> </ListItem> </List> <List subheader={<ListSubheader component="div">Php</ListSubheader>} className="grayscaled" style={{flex: 1}}> <ListItem> <Avatar src={yii}/> <ListItemText primary="Yii 2.0"/> </ListItem> <ListItem> <Avatar src={zend}/> <ListItemText primary="Zend framework"/> </ListItem> <ListItem> <Avatar src={laravel}/> <ListItemText primary="Laravel"/> </ListItem> <ListItem> <Avatar src={wp}/> <ListItemText primary="Wordpress"/> </ListItem> </List> </div> <div style={{display: 'flex', flexWrap: 'wrap', marginTop: 24}}> <List subheader={<ListSubheader component="div">Javascript (frontend)</ListSubheader>} className="grayscaled" style={{flex: 1}}> <ListItem> <Avatar src={jquery}/> <ListItemText primary="Jquery"/> </ListItem> <ListItem> <Avatar src={react}/> <ListItemText primary="React.js"/> </ListItem> <ListItem> <Avatar src={backbone}/> <ListItemText primary="Backbone.js"/> </ListItem> <ListItem> <Avatar src={marionette}/> <ListItemText primary="Marionette"/> </ListItem> <ListItem> <Avatar src={bem}/> <ListItemText primary="BEM"/> </ListItem> </List> <List subheader={<ListSubheader component="div">Utils</ListSubheader>} className="grayscaled" style={{flex: 1}}> <ListItem> <Avatar src={git}/> <ListItemText primary="Git"/> </ListItem> <ListItem> <Avatar src={docker}/> <ListItemText primary="Docker"/> </ListItem> <ListItem> <Avatar src={rabbit}/> <ListItemText primary="RabbitMQ"/> </ListItem> <ListItem> <Avatar src={webpack}/> <ListItemText primary="Webpack"/> </ListItem> <ListItem> <Avatar src={gulp}/> <ListItemText primary="Gulp"/> </ListItem> </List> <List subheader={<ListSubheader component="div">Database</ListSubheader>} className="grayscaled" style={{flex: 1}}> <ListItem> <Avatar src={mysql}/> <ListItemText primary="Mysql"/> </ListItem> <ListItem> <Avatar src={postgres}/> <ListItemText primary="Postgresql"/> </ListItem> <ListItem> <Avatar src={mongo}/> <ListItemText primary="Mongodb"/> </ListItem> <ListItem> <Avatar src={redis}/> <ListItemText primary="Redis"/> </ListItem> <ListItem> <Avatar src={sqlite}/> <ListItemText primary="Sqlite"/> </ListItem> </List> </div> </div> ) } } export default Stack;
export default class AnaliticsCounter { constructor(category) { this.category = category; this.categoryStored = this.getCategory(); } getCategory() { return localStorage.getItem(this.category) ? JSON.parse(localStorage.getItem(this.category)) : {}; } saveCategory() { localStorage.setItem(this.category, JSON.stringify(this.categoryStored)); } incrementTrainClick(word) { const wordData = this.getWordData(word); wordData.trainClicks += 1; this.saveCategory(); } incrementGameClick(word) { const wordData = this.getWordData(word); wordData.gameSuccessClicks += 1; this.saveCategory(); } incrementErrorCount(word) { const wordData = this.getWordData(word); wordData.gameErrorClicks += 1; this.saveCategory(); } getWordData(word) { if (!(word in this.categoryStored)) { this.categoryStored[word] = { trainClicks: 0, gameSuccessClicks: 0, gameErrorClicks: 0, }; } return this.categoryStored[word]; } }
const mongoose = require('mongoose'); const passport = require('passport'); const Score = mongoose.model('Score'); exports.homePage = (req, res) => { res.render('index'); }; exports.aboutPage = (req, res) => { res.render('about'); }; exports.quizPage = async (req, res) => { let quiz = null; if (req.user) { const quiz = await Score.findOne({id: req.user._json.id}); if (quiz.score) { res.redirect(`/results`); return; } } res.render('quiz', {title: 'Quiz'}); }; exports.loginPage = (req, res) => { res.render('login', {title: 'Login'}); }; exports.resultsPage = async (req, res) => { const quiz = await Score.findOne({id: req.user._json.id}); res.render('results', { title: 'Results', results: quiz.score }); }; exports.setResults = async (req, res) => { console.log(req.params.id); }; exports.accountPage = async (req, res) => { if (!req.user || !req.user._json) { return; } let userData = await Score.findOne({id: req.user._json.id}).lean().exec(); if (!userData) { userData = new Score({id: req.user._json.id}); userData.save(); } const linkedInData = req.user._json; let data = []; if (linkedInData.formattedName) { data.push({name: 'Display Name', key: 'formattedName', value: linkedInData.formattedName, checked: false}); } if (linkedInData.industry) { data.push({name: 'Industry', key: 'industry', value: linkedInData.industry, checked: false}); } if (linkedInData.location && linkedInData.location.name) { data.push({name: 'Location', key: 'location', value: linkedInData.location.name, checked: false}); } if (linkedInData.numConnections) { data.push({name: 'Connections', key: 'connections', value: linkedInData.numConnections, checked: false}); } if (linkedInData.positions && linkedInData.positions.values[0]) { if (linkedInData.positions.values[0].company && linkedInData.positions.values[0].company.name) { data.push({name: 'Current Employer', key: 'currentEmployer', value: linkedInData.positions.values[0].company.name, checked: false}); } if (linkedInData.positions.values[0].title) { data.push({name: 'Current Position', key: 'currentPosition', value: linkedInData.positions.values[0].title, checked: false}); } if (linkedInData.positions.values[0].company && linkedInData.positions.values[0].company.industry) { data.push({name: 'Current Industry', key: 'currentIndustry', value: linkedInData.positions.values[0].company.industry, checked: false}); } } data.forEach((item) => { if (!userData) { item.checked = false; } else { item.checked = userData[item.key]; } }); let accountData = { title: 'Account', user: data }; res.render('account', accountData); }; exports.setAccount = async (req, res) => { let score = await Score.findOne({id: req.user._json.id}); console.log(score); score.formattedName = req.body.formattedName; score.industry = req.body.industry; score.location = req.body.location; score.connections = req.body.connections; score.currentEmployer = req.body.currentEmployer; score.currentPosition = req.body.currentPosition; score.currentIndustry = req.body.currentIndustry; score.save(); res.send(); }; exports.submitQuiz = async (req, res) => { let score = await Score.findOne({id: req.user._json.id}); if (!score) { score = new Score({id: req.user._json.id, score: req.body}); } else { score.score = req.body; } await score.save(); res.send(); };
var counter=0;var num = 0; var TIV3335=function(){ var Array_of_Images = []; return { loadImages:function(){ var files = document.getElementById("images").files; for (var i = 0; i < files.length; i++) { var file = files[i]; if (file.name.match(/\.(jpg|jpeg|png|gif)$/)){ num++; Array_of_Images.push(file); } }}, getLoadedImages:function(){ return Array_of_Images; }, showLoadedImages:function(elem){ if (num>=1){ for (i = 0; i < Array_of_Images.length; i++) { var reader = new FileReader(); counter=i; // Closure to capture the file information. reader.onload = (function(file,counter){ return function(e) { // Render thumbnail var div = document.createElement('div'); div.setAttribute('class', 'box'); var id=counter; div.innerHTML = ['<img id="',id,'"src="', e.target.result, '" title="', escape(file.name), '" height="144" width="103" onClick="TIV3335.showImageDetailedExifWithMap(id,container); getID("',id,'");"> '].join(''); //parseInt(this.getattribute("id")) document.getElementById(elem).insertBefore(div, null); }; })(Array_of_Images[i],counter); // Read in the image file as a data URL. reader.readAsDataURL(Array_of_Images[i],i); } }else{ var div = document.createElement('div'); div.style.fontSize = "25px"; div.innerHTML = "No Images"; document.getElementById(elem).appendChild(div); } }, showImage:function(index,elem){ var modal = document.getElementById('myModal'); var container = document.getElementById("big"); modal.style.display = "block"; var tmpArr=TIV3335.getLoadedImages()[index]; container.innerHTML = ['<img class="bimg" src="' + document.getElementById(index).src + '" title="ela">'].join(''); }, showImageDetailedExifInfo:function(index, elem){ var img2 = document.getElementById(index); EXIF.getData(img2, function() { var allMetaData = EXIF.getAllTags(this); var allMetaDataSpan = document.getElementById("allMetaDataSpan"); allMetaDataSpan.innerHTML = JSON.stringify(allMetaData, null, "\t"); });}, showImageDetailedExifWithMap:function(index, elem){ function ConvertDMSToDD(degrees, minutes, seconds, direction) { var dd = degrees + minutes/60 + seconds/(60*60); if (direction == "S" || direction == "W") { dd = dd * -1; } // Don't do anything for N or E return dd; } TIV3335.showImage(index,elem); var img2 = document.getElementById(index); EXIF.getData(img2, function() { var lat=EXIF.getTag(this, "GPSLatitude")+''; var latdir=EXIF.getTag(this, "GPSLatitudeRef"); var parts1=lat.split(/[^\d\w]+/); var lng= EXIF.getTag(this, "GPSLongitude")+''; var lngdir=EXIF.getTag(this, "GPSLongitudeRef"); var parts2 = lng.split(/[^\d\w]+/); var lat = ConvertDMSToDD(parseInt(parts1[0]), parseInt(parts1[1]), parseInt(parts1[2]), latdir); var lng = ConvertDMSToDD(parseInt(parts2[0]), parseInt(parts2[1]), parseInt(parts2[2]), lngdir); console.log(lat); console.log(lng); var lat1=parseFloat(lat); var lng1=parseFloat(lng); var mapOptions = { zoom: 8, center: {lat: lat1, lng: lng1}, scrollwheel: true, zoomControl: true, scaleControl: true }; var map = new google.maps.Map(document.getElementById("map"), mapOptions); var marker = new google.maps.Marker({ position: {lat: lat1, lng: lng1}, map: map }); }); TIV3335.showImageDetailedExifInfo(index,elem); }, start:function(){ TIV3335.loadImages(); TIV3335.getLoadedImages(); TIV3335.showLoadedImages('container'); } }; }();
function setSelection(range) { var selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range); } /** * @mixin */ let Selection = (superclass) => class Selection extends superclass { /** * Selects everything in the text control. * @name Selection#select */ select() { this.setSelectionRange(0, this.value.length); } /** * Returns / Sets the beginning index of the selected text. When nothing is selected, * this returns the position of the text input cursor(caret) inside of the < input > element. * * @name Selection#selectionStart * @type {Number} */ get selectionStart() { let sel = window.getSelection(); if (sel.anchorNode && sel.anchorNode.parentNode == this.element) { return sel.anchorOffset > sel.focusOffset ? sel.focusOffset : sel.anchorOffset; } } set selectionStart(start) { let range = new Range(); range.setStart(this.element.firstChild, start); setSelection(range); } /** * Returns / Sets the end index of the selected text. When there's no selection,this returns the * offset of the character immediately following the current text input cursor position. * * @name Selection#selectionEnd * @type {Number} */ get selectionEnd() { let sel = window.getSelection(); if (sel.focusNode && sel.focusNode.parentNode == this.element) { return sel.focusOffset > sel.anchorOffset ? sel.focusOffset : sel.anchorOffset; } } set selectionEnd(end) { let range = new Range(); range.setEnd(this.element.firstChild, end); setSelection(range); } /** * Returns / Sets the direction in which selection occurred. * * * "forward" if selection was performed in the start - to - end direction of the current locale. * * "backward" for the opposite direction, * * "none" if the direction is unknown." * * @name Selection#selectionDirection * @todo improve method to set and get direction * @type { "forward" | "backward" | "none" } */ get selectionDirection() { let sel = window.getSelection(); if (sel.focusNode && sel.focusNode.parentNode == this.element) { if (sel.focusOffset == sel.anchorOffset) { return "none"; } else if (sel.anchorOffset > sel.focusOffset) { return "backward"; } else { return "forward"; } } } set selectionDirection(direction) { let sel = window.getSelection(); if (sel.focusNode && sel.focusNode.parentNode == this.element) { if (sel.focusOffset == sel.anchorOffset) { } else if (sel.anchorOffset > sel.focusOffset && direction != "backward") { let range = new Range(); range.setStart(this.element.firstChild, this.selectionEnd); range.setEnd(this.element.firstChild, this.selectionStart); setSelection(range); } else if (direction != "forward") { let range = new Range(); range.setStart(this.element.firstChild, this.selectionStart); range.setEnd(this.element.firstChild, this.selectionEnd); setSelection(range); } } } /** * Selects a range of text in the element (but does not focus it). * @name Selection#setSelectionRange * @param {Integer} selectionStart * @param {Integer} selectionEnd * @param { "forward" | "backward" | "none" } [selectionDirection = "none"] * Establish the direction in which selection was set */ setSelectionRange(selectionStart, selectionEnd, selectionDirection = "none") { let start = selectionDirection == "backward" ? selectionEnd : selectionStart; let end = selectionDirection == "backward" ? selectionStart : selectionEnd; let range = new Range(); range.setStart(this.element.firstChild, start); range.setEnd(this.element.firstChild, end); setSelection(range); } /** * Replaces the range of text with the new text. * @name Selection#setRangeText * @todo Keep previous selection on place * @param {String} replacement * @param {Integer} [start = {@link Textbox#selectionStart}] * @param {Integer} [end] * @param { "select" | "start" | "end" | "preserve" } [selectMode = "preserve"] */ setRangeText( replacement, start = this.selectionStart, end = this.selectionEnd, selectMode = "preserve" ) { let selectionStart = this.selectionStart; let selectionEnd = this.selectionEnd; if (start > end) { throw new RangeError(); } if (start > this.value.length) { start = this.value.length; } if (end > this.value.length) { end = this.value.length; } if (start < end) { // delete characters between start and end } this.value = this.value.slice(0, start) + replacement + this.value.slice(end); if (selectMode == "start") this.selectionStart = 0; if (selectMode == "end") this.selectionStart = this.value.length; if (selectMode == "select") this.select(); if (selectMode == "preserve") this.setSelectionRange(selectionStart, selectionEnd); } }; export default Selection;
/* @flow */ import React from 'react'; import type { Element } from 'react'; import Times from '../times/Times'; type Props = { first: () => ?Element<*>, second: () => ?Element<*>, container?: React$ElementType, className?: ?string, id?: ?string, }; // eslint-disable-next-line object-curly-spacing export default function Two({ render, container, className, id }: Props) { return ( <Times n={2} container={container} className={className} id={id} render={n => { switch (n) { case 0: return this.props.first(); case 1: return this.props.second(); } }} /> ); }
//Stampa le potenze di 2 fino a 1000 var base = 2; var esponente = 10; var risultato = 1; for (var i = 0; i < esponente; i++) { //console.log(i); risultato = risultato * base; console.log(risultato); }
// YOUR TASK: Add more pictures! var pictures = ['./imgs/dog.jpg',"./imgs/1.jpg","./imgs/2.jpg","./imgs/3,jpg","./imgs/4.jpg","./imgs/5.jpg" ]; var currentIndex = 0; function showNextPicture() { var img = getElementsByTagName("img")[0]; currentIndex++; // increment current picture // if currentIndex is too large, start from the beginning again img.src = prictures[currentIndex]; if (currentIndex >= pictures.length) { currentIndex = 0; } // YOUR TASK: Finish this function! var img = getElementsByTagName("img")[0]; img.addEventListener("click", showNextPicture); }
// NewItemForm.jsx import React from 'react'; import AppDispatcher from '../dispatcher/AppDispatcher'; class NewItemForm extends React.Component { createItem(e){ // so we don't reload the page e.preventDefault(); // create ID let id = guid(); // this gets the value from the input let item_title = React.findDOMNode(this.refs.item_title).value.trim(); // this removes the value from the input React.findDOMNode(this.refs.item_title).value = ''; // This is where the magic happens, // no need to shoot this action all the way to the root of your application to edit state. // AppDispatcher does this for you. AppDispatcher.dispatch({ action: 'add-item', new_item: { id: id, name: item_title } }); } render(){ return <form onSubmit={ this.createItem.bind(this) }> <input type="text" ref="item_title"/> <button>Add new item</button> </form> } } function guid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } export default NewItemForm;
import { connect } from 'react-redux' import * as evidencesActions from '../reducers/entities/evidences' import * as updatesFeedActions from '../reducers/ui/updates-feed' import * as evidencesSelector from '../selectors/entities/evidences' import * as updatesFeedSelector from '../selectors/ui/updates-feed' import { FeedMap as FeedMapComponent } from '../components/feed-map' export const FeedMap = connect( (state, props) => ({ invalidList: evidencesSelector.getEvidenceItemsInvalid(state, props), isAutomaticMapFitting: updatesFeedSelector.isAutomaticMapFitting(state, props), itemsBounce: updatesFeedSelector.getItemsBounce(state, props), listError: evidencesSelector.getEvidenceError(state, props), listInProgress: evidencesSelector.getEvidenceItemsInProgress(state, props), listItems: updatesFeedSelector.getSortedItems(state, props), hasMoreItems: updatesFeedSelector.hasMore(state, props), selectedItem: updatesFeedSelector.getSelectedItem(state, props), selectionSource: updatesFeedSelector.getSelectionSource(state, props), startDateISO: updatesFeedSelector.getStartDateISO(state, props) }), (dispatch, props) => ({ loadItemsAfter: ({ lat, long, startDateISO }) => dispatch(evidencesActions.fetchEvidences({ lat, long, startDateISO })), onSelect: itemId => dispatch(updatesFeedActions.selectItem(itemId, 'map')), onUnSelect: () => dispatch(updatesFeedActions.selectItem(null)), onUserMove: () => dispatch(updatesFeedActions.autoMapFitting(false)) }) )(FeedMapComponent)
/// <reference path="jquery-3.1.1.js" /> /// <reference path="config.js" /> /// <reference path="state.js" /> /// <reference path="scene.js" /> var App = function(scene) { this.scene = scene; this.state = new State(); this.timeoutId = 0; this.randomize = function() { this.state = StateFactory.createRandom(); this.scene.update(this.state); } this.showDone = function() { this.state = StateFactory.createDone(); this.scene.update(this.state); } this.step = function() { this.state = this.state.getNextState(); return this.scene.update(this.state); } this.keepPlaying = function(app) { if (app.timeoutId == 0) { return; } if (app.step()) { app.timeoutId = setTimeout(app.keepPlaying, Settings.speed, app); } else { app.stop(); app.showDone(); } } this.play = function() { if (this.timeoutId != 0) { return; } this.step(); this.timeoutId = setTimeout(this.keepPlaying, Settings.speed, this); } this.stop = function() { if (this.timeoutId == 0) { return; } clearTimeout(this.timeoutId); this.timeoutId = 0; } this.togglePlay = function() { if (this.timeoutId == 0) { this.play(); } else { this.stop(); } } this.showLogo = function() { this.stop(); this.state = StateFactory.createLogo(); this.scene.update(this.state); } } $(document).ready(function() { var canvas = $("#canvas"); canvas.attr("width", Settings.width); canvas.attr("height", Settings.height); var context = canvas[0].getContext("2d"); var ratioSpan = $("#ratio"); var scene = new Scene(context, ratioSpan); var app = new App(scene); app.showLogo(); $("#randomizeButton").click(function() { app.randomize(); }); $("#stepButton").click(function() { app.step(); }); $("#playButton").click(function() { app.play(); }); $("#stopButton").click(function() { app.stop(); }); $(document).keypress(function(e) { if (e.which === 114) { app.randomize(); } else if (e.which === 115) { app.step(); } else if (e.which === 112) { app.togglePlay(); } else if (e.which === 108) { app.showLogo(); } }); var controls = $("#controls"); controls.show(); });
export default { secret: "herman-secret-key", };
const uuidv4 = require('uuid/v4') exports.seed = function(knex, Promise) { // Deletes ALL existing entries return knex('user').del() .then(function () { // Inserts seed entries return knex('user').insert([ {id: uuidv4(), name: 'root', email: 'root@gmail.com'}, {id: uuidv4(), name: 'admin1', email: 'admin1@gmail.com'}, {id: uuidv4(), name: 'admin2', email: 'admin2@gmail.com'} ]); }); };
function get_content() { $.post(base_url+'/partials/dashboard_button', function(template, textStatus, xhr) { $('#main').html(template); abre_pulsador(); }); } var pulsador=false; function abre_pulsador () { pulsador = window.open(base_url+'/button', "PedirTaxi", "location=0,status=0,scrollbars=0,width=440,height=680"); setTimeout(function() { if (pulsador && pulsador.outerHeight != 0 && !pulsador.closed){ pulsador.moveTo(0,0); window.focus(); $('#loading').add('#error').hide(); $('#success').show(); } else{ $('#loading').add('#success').hide(); $('#error').show(); } }, 2000); } function cierra () { if (pulsador && pulsador.outerHeight != 0){ if (navigator.userAgent.indexOf('MSIE 6.0') > 0) window.opener='x'; if (parent.window.location == window.location) { window.open("","_self"); window.close(); } else parent.window.close(); } } function ver_tutorial () { if($('#tutorial').css('display')=='none') $('#tutorial').slideDown(); else $('#tutorial').slideUp(); }
import React from "react"; import FileBase64 from "react-file-base64"; import axios from "axios"; // import ImageUploader from 'react-images-upload'; import Toggle from 'react-toggle'; import "react-toggle/style.css" class Pixupload extends React.Component { constructor(props) { super(props); this.clientEmail = localStorage.getItem("userEmail"); console.log(this.clientEmail); this.state={ img: [], notes: "", title: "", location: "", userEmail: this.clientEmail, imagePreviewUrl: null }; this.handleSubmit = this.handleSubmit.bind(this); this.handleInputChangeNotes = this.handleInputChangeNotes.bind(this); this.handleInputChangeTitle = this.handleInputChangeTitle.bind(this); this.handleInputChangeLocation = this.handleInputChangeLocation.bind(this); this.handleFileUpload = this.handleFileUpload.bind(this); //this.handleToggleChange=this.handleToggleChange.bind(this); } //FUNCTION FOR WHAT HAPPENS WHEN SUBMIT BUTTON IS CLICKED AKA COLLECTING AND SENDING FILE handleSubmit(event) { event.preventDefault(); var data = { base64: this.state.img[0].base64, title: this.state.title, notes: this.state.notes, location: this.state.location, //toggle: this.state.toggle, userEmail: this.clientEmail } axios.post("/test/upload", data) .then(function(response) { console.log(response); }) .catch(function (error) { console.log(error); }); } handleInputChangeNotes(e) { console.log("handle input chance notes@@"); this.setState({notes: e.target.value}) } handleInputChangeTitle(e) { console.log("handle input chance title"); this.setState({title: e.target.value}) } handleInputChangeLocation(e) { console.log('handle inpout change location'); this.setState({location: e.target.value}) } handleFileUpload(picture) { console.log("fileupload" + JSON.stringify(this.state.img.concat(picture)[0].base64)); this.setState({ img: this.state.img.concat(picture), imagePreviewUrl: this.state.img.concat(picture)[0].base64 }); } //CREATION OF THE FORM UI render() { let {imagePreviewUrl} = this.state; let $imagePreview = null; if (imagePreviewUrl) { $imagePreview = (<img src={this.state.imagePreviewUrl} />); } console.log(this.state); return ( <div> <FileBase64 multiple={ true } onDone={ this.handleFileUpload.bind(this)} /> <br /> <img src={imagePreviewUrl} /> <label> Title: <input name="title" type="text" ref={input => { this.textInput = input; console.log(input); ; }} onChange={this.handleInputChangeTitle} /> </label> <br /> <label> Notes: <input name="notes" type="text" ref={input => { this.textInput = input; ; }} onChange={this.handleInputChangeNotes} /> <label> Location: <input name="location" type="text" ref={input => { this.textInput = input; ; }} onChange={this.handleInputChangeLocation} /> </label> <br /> <label> Share Photo?: <Toggle checked={this.state.Toggle} name='toggle' value='yes' onChange={this.handleToggleChange}/> </label> <br /> <br /> </label> <button onClick={this.handleSubmit}> SUBMIT UR PIC :) </button> </div> ); } } export default Pixupload
$('document').ready(function() { var width = 1000, height = 600, linkDistance = 50, //approximate distance between nodes charge = -150; //the repulsion between nodes //for the sprite images, which can't be handled well in svg var container = d3.select('.container') .style('width', width + 'px') //for the lines var svg = container.append('svg') .attr('width', width) .attr('height', height); //chart title var title = container.append('h1') .attr('class', 'title') .text('Neighbors') .style('left', width/2 + 'px') .style('top', height/2 + 'px'); //source link at bottom container.append('div') .attr('class', 'source') .append('a') .text('Source') .attr('href', 'https://raw.githubusercontent.com/DealPete/forceDirected/master/countries.json') .attr('target', '_blank'); //reading in the data $.getJSON('https://raw.githubusercontent.com/DealPete/forceDirected/master/countries.json').success(function(result) { var nodes = result.nodes, links = result.links; //creates force-directed graph var force = d3.layout.force() .size([width, height]) .nodes(nodes) .links(links) .charge(charge) .linkDistance(linkDistance); //creates links! var link = svg.selectAll('.link') .data(links) .enter().append('line') .attr('class', 'link'); //creates flag nodes! var node = container.selectAll('img') .data(nodes) .enter().append('img') .attr('class', function(d) { return 'flag flag-' + d.code }) .on('mouseover', function(d) { d3.select(this).classed('shadow', true); title.html(d.country); }) .on('mouseout', function(d) { d3.select(this).classed('shadow', false); }) .call(force.drag); //dynamically positions each node and link force.on('tick', function() { node.style('left', function(d) { return (d.x - 8) + 'px' }) .style('top', function(d) { return (d.y * .5625 + height/5 - 5) + 'px' }) link.attr('x1', function(d) { return d.source.x }) .attr('y1', function(d) { return (d.source.y * .5625 + height/5) }) .attr('x2', function(d) { return d.target.x }) .attr('y2', function(d) { return (d.target.y * .5625 + height/5) }) }); //starts the whole thing up force.start(); }); })
import dotenv from 'dotenv'; import model from '../db/models'; import processToken from '../helpers/processToken'; const { Users } = model; dotenv.config(); /** * User Information are saved here */ class UserInfo { /** * * @param {Object} req * @param {Object} res * @returns {Object} response after user signin */ static async googleLogin(req, res) { const { displayName } = req.user; const newUser = await Users.create({ username: displayName, email: req.user.emails[0].value, image: req.user.photos[0].value, isVerified: req.user.emails[0].verified, socialId: req.user.id, provider: 'google', hash: process.env.DEFAULT_PASSWORD }); if (newUser) { const { dataValues } = newUser; const generatedToken = await processToken.signToken(dataValues); return res.redirect(`${process.env.FRONT_END_URL}/social-login?token=${generatedToken}`); } } /** * * @param {Object} req * @param {Object} res * @returns {Object} user successfully logged in */ static async facebookLogin(req, res) { const { displayName } = req.user; const newUser = await Users.create({ username: displayName, email: req.user.emails[0].value, image: req.user.photos[0].value, isVerified: true, socialId: req.user.id, provider: 'facebook', hash: process.env.DEFAULT_PASSWORD }); if (newUser) { const token = await processToken.signToken(newUser.dataValues); return res.redirect(`${process.env.FRONT_END_URL}/social-login?token=${token}`); } } /** * * @param {Object} req * @param {Object} res * @return {Object} user logged in */ static async twitterLogin(req, res) { const newUser = await Users.create({ username: req.user.username, email: `${req.user.username}@gmail.com`, image: req.user.photos[0].value, isVerified: true, socialId: req.user.id, provider: 'twitter', hash: process.env.DEFAULT_PASSWORD }); if (newUser) { const { dataValues: payload } = newUser; /** * Twitter redirect */ const token = await processToken.signToken(payload); return res.redirect(`${process.env.FRONT_END_URL}/social-login?token=${token}`); } } } export default UserInfo;
generateMarkdown = answers => { const {username, email, name, description, url, role, goal, reason, license, installation, usage} = answers; const badge = license.replace(/\s/g, '%20'); return ` # ${name} [![GitHub license](https://img.shields.io/badge/license-${badge}-blue)](${url}) ## Description ${description} ## User Story \`\`\` AS A ${role} I WANT ${goal} SO THAT ${reason} \`\`\` ## Table of Content * [Installation](#installation) * [Usage](#usage) * [License](#license) * [Questions](#questions) ## Installation \`\`\` ${installation} \`\`\` ## Usage ${usage} ## License ${license} ## Questions If you have any questions about the repo, please contact ${username} at ${email}. ` } module.exports = generateMarkdown;
function createModal(header, content) { if (header == "" || header == null) { var modal = $("<div class = 'modal'><span id = 'close'>&#10006;</span>"+content+"</div>"); var filter = $("<div class = 'filter'></div>"); filter.appendTo($("body")).css({ position:"fixed", top:0, left:0, right:0, bottom:0, backgroundColor:"rgba(0,0,0,0.5)", display:"none" }).fadeIn().click(function() { $(".modal").remove(); $(".filter").remove(); }); modal.appendTo($("body")).css({ position:"fixed", top:"50%", left:"50%", transform: "translateY(-50%) translatex(-50%)", maxWidth:"1500px", mexHeight:"90%", overflow:"scroll", backgroundColor:"#fff", padding:"50px", fontSize:"24px", display:"none" }).fadeIn(); $("#close").css({ position:"absolute", top:"0", right:"0", display:"block", padding:"10px", cursor:"pointer" }) .click(function() { $(".modal").remove(); $(".filter").remove(); }); } else { var modal = $("<div class = 'modal'><span id = 'close'>&#10006;</span><h2>"+header+"</h2><div class = 'modal-content'>"+content+"</div></div>"); var filter = $("<div class = 'filter'></div>"); filter.appendTo($("body")).css({ position:"fixed", top:0, left:0, right:0, bottom:0, backgroundColor:"rgba(0,0,0,0.5)", display:"none" }).fadeIn().click(function() { $(".modal").remove(); $(".filter").remove(); }); modal.appendTo($("body")).css({ position:"fixed", top:"50%", left:"50%", transform: "translateY(-50%) translatex(-50%)", maxWidth:"2000px", maxHeight:"90%", overflow:"scroll", backgroundColor:"#fff", padding:"30px", paddingTop:"70px", fontSize:"24px", display:"none" }).fadeIn(); $(".modal>h2").css({ position:"absolute", top:"0", left:"0", display:"block", padding:"15px", fontSize:"30px", margin:"0" }) $("#close").css({ position:"absolute", top:"0", right:"0", display:"block", padding:"10px", cursor:"pointer" }) .click(function() { $(".modal").remove(); $(".filter").remove(); }); } }
import { useEffect, useState } from 'react' import ReactApexChart from 'react-apexcharts'; import { chartOptions } from './chart-config'; import { clone } from 'lodash'; const CityAqiChart = ({ cityName, dataPoints }) => { const [series, setSeries] = useState([]); const [options, setOptions] = useState({}); useEffect(() => { generateChartData(); }, [dataPoints[dataPoints.length - 1]]); function generateChartData() { let seriesData = []; const timestamps = dataPoints.map(dp => dp.timestamp); const minTimeStamp = Math.min(...timestamps); const op = clone(chartOptions(cityName, minTimeStamp)); seriesData = dataPoints.map(x => [x.timestamp, x.aqi]); op.series = [{ data: seriesData }]; setSeries([{ data: seriesData }]); setOptions(op); } return ( <div id="chart"> <ReactApexChart series={series} options={options} type="area" height={350} /> </div> ); } export default CityAqiChart;
'use strict'; var mongoose = require('mongoose'); var Shout = mongoose.model('Shout'); module.exports = function(app) { // List shouts app.get('/api/shouts', function(req, res) { Shout .find() .exec(function (err, shouts) { if(err) { console.log(err); } res.json(shouts); }); }); // Add shout app.post('/api/shouts', function(req, res) { console.log('post in api shouts: ' + req.body); var shout = new Shout(req.body); shout.save(function(err) { if (err) { console.error(err); } // res.json(shout, 201); res.status(201).json(shout); }); }); };
export default { white: '#fff', black: '#212121', primary: '#37474F', offWhite: '#ECEFF1', secondary: '#607D8B', gray: '#777', overlay: 'rgba(0,0,0, .5)' }
var postsData = require('../../data/data.js') Page({ /** * 页面的初始数据 */ data: { }, onPostTap: function (event) { var postId = event.currentTarget.dataset.postid; wx: wx.navigateTo({ url: 'post-detail/post-detail?id=' + postId }) }, swiperTap(event) { var postId = event.currentTarget.dataset.postid; wx: wx.navigateTo({ url: 'post-detail/post-detail?id=' + postId }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { this.dataLoad() }, onShow(){ this.dataLoad() }, dataLoad(){ var postsHasLooked = wx.getStorageSync('posts_hasLooked') if (postsHasLooked) { for (let i in postsHasLooked) { postsData.postList[i].hasLooked = postsHasLooked[i] } } else { postsHasLooked = {} postsData.postList.map((el, index) => { el.hasLooked = 0 postsHasLooked[index] = 0 }) wx.setStorageSync('posts_hasLooked', postsHasLooked); } this.setData({ arr: postsData.postList }) } })
import React, { useEffect } from 'react'; import useStorage from '../../StorageHook/useStorage'; import { motion } from 'framer-motion'; import db from "../../Firebase"; import "./Profile.css" const ProgressBar = ({ file, setFile,setPhoto,friends,id}) => { const { progress, url } = useStorage(file); useEffect(() => { if (url) { db.collection("users").doc(id).update({ photoUrl:url, }) friends.map((friend) => { db.collection("users").doc(friend.data.friend).collection("chats").doc(friend.data.friendRoomId).update({ photo: url, }) }) setPhoto(url); setFile(null); } }, [url, setFile]); return ( <motion.div className="progress-bar" initial={{ width: 0 }} animate={{ width: progress + '%' }} ></motion.div> ); } export default ProgressBar;
// aqiScaleTools.js import { parseScale } from './charts'; const POLLUTANTS = ['aqi', 'pm2.5', 'pm10', 'no2', 'o3', 'so2', 'co']; const WEATHER_VARIABLES = ['rh', 'temp', 'wspeed', 'wdir'] export default { POLLUTANTS, WEATHER_VARIABLES, normalizePollutantId: normalizePollutantId, extraChecks: extraChecks, getUserAqiScale: getUserAqiScale, parseAqiScale: parseAqiScale, parseAqiScaleAllPollutantsStyles:parseAqiScaleAllPollutantsStyles, parseScaleAllPollutants: parseScaleAllPollutants, sortMeasurementsArray: sortMeasurementsArray, prepareThresholdsForGauge, sortPollutantsArray, sensitivityChecks }; function normalizePollutantId(id) { switch (id.toLowerCase()) { case 'sp_aqi': case 'aqi': return 'aqi'; case 'pm2.5': case 'bpm2.5': case 'ipm2.5': case 'pm25': return 'pm2.5'; default: return id.toLowerCase(); } }; function extraChecks(aqiScaleId) { switch (aqiScaleId) { case 'EUEEA': case 'USEPA': case 'AUEPA': return (thresh, pollutant) => { return normalizePollutantId(thresh.pollutant) === normalizePollutantId(pollutant); }; default: return null; } } function sensitivityChecks(aqiIndex, sensitivityLevel, aqiScaleId) { switch (aqiScaleId) { case 'EUEEA': case 'USEPA': case 'AUEPA': if(aqiIndex<=33) { return 0; } else if(aqiIndex>33 && aqiIndex <=66) { if(sensitivityLevel === 0) { return 0; } else { return 1; } } else if(aqiIndex>66 && aqiIndex<=99){ if(sensitivityLevel === 0 || sensitivityLevel === 1) { return 1; } else if(sensitivityLevel === 2 || sensitivityLevel === 3){ return 2; } else { return 3; } } else if(aqiIndex>99 && aqiIndex<=149){ if(sensitivityLevel === 3) { return 3; } else if(sensitivityLevel === 4) { return 4; } else { return 2; } } else if(aqiIndex>149) { if(sensitivityLevel === 3 || sensitivityLevel==4){ return 4; } else { return 3; } } default: return 0; } } function getUserAqiScale(aqiScales, user) { if (aqiScales.length > 0 && user.profile && user.profile.aqi_scale) { return aqiScales[aqiScales.findIndex(x => { return x.abbreviation === user.profile.aqi_scale; })]; } return null; } function parseAqiScale (pollutant='aqi', aqiScale=null) { if (!aqiScale) return null; const extraCheck = extraChecks(aqiScale.abbreviation), extended = true, aqiThresholds = parseScale(aqiScale, pollutant, extraCheck, extended); return (val) => { let thresh; for (thresh in aqiThresholds.upperLimits) { if (val < aqiThresholds.upperLimits[thresh]) { break; } } return { bgColour: aqiThresholds.backgroundColors[thresh], description: aqiThresholds.descriptions[thresh], fgColour: aqiThresholds.foregroundColors[thresh], abbreviation: aqiThresholds.abbreviations[thresh] }; } } function parseAqiScaleAllPollutantsStyles (aqiScale=null) { if (!aqiScale) return null; var pollutantsStyles = {}; for (let p in POLLUTANTS) { pollutantsStyles[POLLUTANTS[p]] = parseAqiScale(POLLUTANTS[p], aqiScale); } return pollutantsStyles; } function getPollutantsForScale (aqiScale) { let pollutants = [] aqiScale.aqi_category_thresholds.forEach(thresh => { if (!pollutants.includes(thresh.pollutant)) { pollutants.push(thresh.pollutant); } }); return pollutants; } function parseScaleAllPollutants (aqiScale=null) { if (!aqiScale) return null; const pollutants = getPollutantsForScale(aqiScale), extraCheck = extraChecks(aqiScale.abbreviation), extended = true; var parsedPollutants = {}; for (let p in pollutants) { parsedPollutants[pollutants[p]] = parseScale(aqiScale, pollutants[p], extraCheck, extended); } return parsedPollutants; } function sortPollutantsArray (array, withWeatherVars=false) { var wholeKeys = (withWeatherVars) ? POLLUTANTS.concat(WEATHER_VARIABLES) : POLLUTANTS; const arr = array.sort((el1, el2) => { let el1idx = wholeKeys.indexOf(el1.toLowerCase()), el2idx = wholeKeys.indexOf(el2.toLowerCase()); el1idx = el1idx > -1 ? el1idx : 999999; el2idx = el2idx > -1 ? el2idx : 999999; if (el1idx > el2idx) return 1; if (el2idx > el1idx) return -1; return 0; }); return arr; } function sortMeasurementsArray (array) { const wholeKeys = POLLUTANTS.concat(WEATHER_VARIABLES); const arr = array.sort((el1, el2) => { const el1idx = wholeKeys.indexOf(Object.keys(el1)[0].toLowerCase()), el2idx = wholeKeys.indexOf(Object.keys(el2)[0].toLowerCase()) if (el1idx > el2idx) return 1; if (el2idx > el1idx) return -1; return 0; }); return arr; } function prepareThresholdsForGauge (aqiThresholds) { let thresholds = { colors: [], limits: []}; if (aqiThresholds && aqiThresholds.upperLimits && aqiThresholds.backgroundColors) { thresholds.colors = aqiThresholds.backgroundColors.slice(0); thresholds.limits = aqiThresholds.upperLimits.slice(0); thresholds.limits.pop(); if (thresholds.limits.length === 4) { thresholds.limits.push(thresholds.limits[thresholds.limits.length-1] * 2); } thresholds.limits.push(1000); thresholds.limits.unshift(0); if (thresholds.colors.length === 5) { thresholds.colors.push(thresholds.colors[thresholds.colors.length-1]); } } return thresholds; }
/** * Created by gautam on 19/12/16. */ import React from 'react'; import ActivityHeader from './ActivityHeader'; import ActivityFooter from './ActivityFooter'; import TopNotification from './TopNotification'; import { browserHistory } from 'react-router'; import $ from 'jquery'; import Base from './base/Base'; import {connect} from 'react-redux'; import {userRegistered, reFetchUserDetails, registerUser} from '../actions'; import {E, I, OTP, ADD_ADDRESS, LANDMARK, CITY, NAME} from '../constants'; import ajaxObj from '../../data/ajax.json'; class AddAddress extends React.Component { constructor(props) { super(props) ajaxObj.type = 'POST'; const address = this.props.location.query.address ? JSON.parse(this.props.location.query.address) : '', op = this.props.location.query.op; this.state = { city: address ? address.city : 'Delhi', name: '', otp: '', address: address ? address.address : '', landmark: address ? address.landmark : '', lkey: address ? address.lkey : '', op: op, notify: { show: false, type: I, timeout: 4000, msg:'', top: 30 } } } render() { const dropStyle = { height: 50 }, {notify, name, otp, address, landmark, city} = this.state, {isNewUser} = this.props.userDetails; return ( <div> <ActivityHeader heading = { 'Provide Address' } /> <TopNotification data={notify}/> <div className = 'col-md-offset-4 col-md-4 col-xs-12 address'> { isNewUser ? <input type = 'text' placeholder = 'Enter your name' className = 'col-xs-12' style={{marginTop: -10}} onChange = { this.saveName} value={name}></input> : ''} { isNewUser ? <input type = 'text' placeholder = 'Enter OTP' className = 'col-xs-12' onChange = { this.saveOTP} value={otp}></input> : ''} <input type = 'text' placeholder = 'Enter complete address' className = 'col-xs-12' onChange = { this.saveAddress } value = { address }/> <input type = 'text' placeholder = 'Landmark' className = 'col-xs-12' onChange = { this.saveLandMark } value = { landmark }/> <select className = 'col-xs-12' style = { dropStyle } onChange = { this.saveCity} value = { city }> <option value = 'New Delhi'> New Delhi </option> <option value = 'Noida'> Noida </option> <option value = 'Gurgaon'> Gurgaon </option> <option value = 'Faridabad'> Faridabad </option> <option value = 'Ghaziabad'> Ghaziabad </option> <option value = 'Greater Noida'> Greater Noida </option> <option value = 'Hyderabad'> Hyderabad </option> <option value = 'Dehradun'> Dehradun </option> </select> <div className = 'col-xs-12 message'> *All fields are mandatory </div> </div> <ActivityFooter key = { 45 } back = { this.navigateBack } next = { this.navigateNext }/> </div> ) } navigateBack = () => { if (this.state.op) { browserHistory.push('/address'); }else { browserHistory.push('/order/details'); } } navigateNext = () => { this.updatePreferences(); } showNotification = (type, msg) => { this.setState({notify: {show: true, type, msg, timeout: 4000, top: 50}}); } saveName = (e) => { let name = e.currentTarget.value; this.setState({ name, notify: {show: false}}); } saveOTP = (e) => { let otp = e.currentTarget.value; this.setState({ otp, notify: {show: false}}); } saveAddress = (e) => { let address = e.currentTarget.value; this.setState({ address, notify: {show: false}}); } saveCity = (e) => { let city = e.currentTarget.value; this.setState({ city, notify: {show: false} }); } saveLandMark = (e) => { let landmark = e.currentTarget.value; this.setState({ landmark, notify: {show: false} }); } updatePreferences = () => { if(this.props.userDetails.isNewUser) { this.registerUser(); } else { this.updateAddress(); } } registerUser = () => { const {name, otp, address, landmark, city} = this.state; if(name) { if(otp) { if(address) { if(landmark) { if(city) { this.registerUserForReal(); } else { this.showNotification(I, CITY); } } else { this.showNotification(I, LANDMARK); } } else { this.showNotification(I, ADD_ADDRESS); } } else { this.showNotification(I, OTP); } } else { this.showNotification(I, NAME); } } registerUserForReal = () => { const {userDetails: {number, token}, registerUser} = this.props, {otp, name} = this.state; Base.showOverlay(); //ajaxObj.url = ajaxObj.baseUrl + '/saveguestcustomer'; const data = { phonenumber: number, otp, token, name }; registerUser(data, this.showNotification, null, this.callBack); //ajaxObj.success = (data) => { // Base.hideOverlay(); // this.props.userRegistered(); // this.addAddress(); //} //ajaxObj.error = (e) => { // Base.hideOverlay(); // this.showNotification(E, e.responseText); //} //$.ajax(ajaxObj); } callBack = () => { this.props.userRegistered(); this.addAddress(); } updateAddress = () => { const {address, landmark, city, op} = this.state; if(city) { if(address) { if(landmark) { op === 'edit' ? this.editAddress() : (op === 'delete' ? this.deleteAddress() : this.addAddress()) } else { this.showNotification(I, LANDMARK); } } else { this.showNotification(I, ADD_ADDRESS); } } else { this.showNotification(I, CITY); } } addAddress = () => { this.changeAddress('/addaddress'); } editAddress = () => { this.changeAddress('/editaddress'); } deleteAddress = () => { this.changeAddress('/deleteaddress'); } changeAddress = (url) => { const {address, city, landmark, lkey} = this.state; //Base.showOverlay(); ajaxObj.url = ajaxObj.baseUrl + url; ajaxObj.dataType = "json"; ajaxObj.data = {address, city, landmark, lkey}; ajaxObj.success = () => { Base.hideOverlay(); this.props.reFetchUserDetails(true); browserHistory.push('/address') } ajaxObj.error = (e) => { Base.hideOverlay(); this.showNotification(E, e.responseJSON.message); } $.ajax(ajaxObj); } } function mapStateToProps(state) { return { userDetails: state.userDetails }; } function mapDispatchToProps(dispatch) { return { userRegistered: () => { dispatch(userRegistered()); }, reFetchUserDetails: (flag) => { dispatch(reFetchUserDetails(flag)); }, registerUser: (data, notificn, navigateTo, callBack) => { dispatch(registerUser(data, notificn, navigateTo, callBack)); } }; } export default connect(mapStateToProps, mapDispatchToProps)(AddAddress);
this.x = 9; var module = { x: 81, getX: function() { //return this.x; console.log(this.x); } }; module.getX(); // 81 var getX = module.getX; getX(); // 9, because in this case, "this" refers to the global object // Create a new function with 'this' bound to module var boundGetX = getX.bind(module); boundGetX(); // 81, because in this case, "this" is bound to module /* ---- */ function list() { return Array.prototype.slice.call(arguments); } var list1 = list(1, 2, 3); // [1, 2, 3] // Create a function with a preset leading argument var leadingThirtysevenList = list.bind(undefined, 37); var list2 = leadingThirtysevenList(); // [37] var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3] /* ---- */
import favouritesReducer from './favouritesReducer'; import { addFavourites, delFavourites } from '../action'; const addNotNewVacancies = { id: '421871bb-05d3-4fbe-b00c-3f372fa35584', title: 'Javascript Engineer', url: 'https://jobs.github.com/positions/421871bb-05d3-4fbe-b00c-3f372fa35584', }; const addNewVacancies = { id: 'abcd-345-bca', title: 'Javascript Engineer', url: 'https://jobs.github.com/positions/421871bb-05d3-4fbe-b00c-3f372fa35584', }; const initialState = { favouritesList: { '421871bb-05d3-4fbe-b00c-3f372fa35584': { id: '421871bb-05d3-4fbe-b00c-3f372fa35584', title: 'Javascript Engineer', url: 'https://jobs.github.com/positions/421871bb-05d3-4fbe-b00c-3f372fa35584', }, 'e67565ea-dd62-4444-8ebe-416b42adac3b': { id: 'e67565ea-dd62-4444-8ebe-416b42adac3b', title: 'Fullstack API Engineer/Integrations Specialist (Remote OK)', url: 'https://jobs.github.com/positions/e67565ea-dd62-4444-8ebe-416b42adac3b', }, '76fcca6f-7cb7-45fb-94c6-04ad68305479': { id: '76fcca6f-7cb7-45fb-94c6-04ad68305479', title: 'Product Engineer ', url: 'https://jobs.github.com/positions/76fcca6f-7cb7-45fb-94c6-04ad68305479', }, }, }; const stateTest = { favouritesList: { '421871bb-05d3-4fbe-b00c-3f372fa35584': { id: '421871bb-05d3-4fbe-b00c-3f372fa35584', title: 'Javascript Engineer', url: 'https://jobs.github.com/positions/421871bb-05d3-4fbe-b00c-3f372fa35584', }, 'e67565ea-dd62-4444-8ebe-416b42adac3b': { id: 'e67565ea-dd62-4444-8ebe-416b42adac3b', title: 'Fullstack API Engineer/Integrations Specialist (Remote OK)', url: 'https://jobs.github.com/positions/e67565ea-dd62-4444-8ebe-416b42adac3b', }, '76fcca6f-7cb7-45fb-94c6-04ad68305479': { id: '76fcca6f-7cb7-45fb-94c6-04ad68305479', title: 'Product Engineer ', url: 'https://jobs.github.com/positions/76fcca6f-7cb7-45fb-94c6-04ad68305479', }, 'abcd-345-bca': { id: 'abcd-345-bca', title: 'Javascript Engineer', url: 'https://jobs.github.com/positions/421871bb-05d3-4fbe-b00c-3f372fa35584', }, }, }; it('Тест добавление новой вакансии', () => { expect(favouritesReducer(initialState, addFavourites(addNewVacancies))) .toEqual(stateTest); }); it('Тест добавление уже имеющейся вакансии', () => { expect(favouritesReducer(initialState, addFavourites(addNotNewVacancies))) .toEqual({ ...initialState }); }); it('Удаление из избранных', () => { expect(favouritesReducer(initialState, delFavourites('abcd-345-bca'))) .toEqual(initialState); });
import { SPACE_FETCHED } from "../actions/spaceActions"; const initialState = null; export default function spaceReducer(state = initialState, action) { switch (action.type) { case SPACE_FETCHED: { return action.payload; } default: { return state; } } }
import css from 'styled-jsx/css' export default css` .text-effect { transform: translateX(-50%); display: inline-block; position: relative; transition: transform 0.4s ease-out; animation-delay: .5s; animation-duration: 1s; animation-name: textEffect; animation-fill-mode: forwards; animation-timing-function: cubic-bezier(.7, .3, 0, 1); } @keyframes textEffect { 0% { transform: translateX(-50%); } 100% { transform: translateX(0%); } } .text-effect::after { content: ""; width: 100%; background: linear-gradient(to right, #333, #333) no-repeat 0 0; height: 100%; background-size: 100% 100%; position: absolute; display: inline; transform: translateX(-50%); transition: background-size 0.4s ease-out, transform 0.4s ease-out; animation: 1s cubic-bezier(.7, .3, 0, 1) .5s forwards blockEffect, .8s ease-out 2s infinite alternate blinkEffect; } @keyframes blockEffect { 0% { transform: translateX(-50%); } 100% { transform: translateX(-199.9%); } } @keyframes blinkEffect { 0% { opacity: 1; } 100% { opacity: 0; } }`
// :style="{width: width + 'px'}" Vue.component('yt-menu', { template: ` <div id='frameMenu' style="height: 100%; display: flex; flex-direction: column; " :style="{width: width + 'px'}"> <div v-if="smallScreen" id="headerMenu" :style="{background: '#2d8cf0', 'display': 'flex', 'flex-direction': 'row', 'justify-content': 'flex-start', 'align-items': 'center', height: '50px', 'padding-right': '5px' }"> <Icon type="md-arrow-back" size="28" color="white" @click.native="onClickIcon" style="cursor: pointer; margin-left: 10px;"></Icon> <span v-if="project.length > 0" style="color: white; margin-left: 10px; font-size: 20px;"> {{project[topic].title}} </span> </div> <div :style="{padding: !smallScreen && project.length > 0 ? '10px' : '0px', zIndex: '10'}" v-if="$isDebug() && !smallScreen && project.length > 0"> <Dropdown @on-click="onClickProject"> <a href="javascript:void(0)"> {{project[topic].title}} <Icon type="ios-arrow-down"></Icon> </a> <DropdownMenu v-for="(item, index) in project" :key="index" slot="list"> <DropdownItem :name="index" :selected="index == topic">{{item.title}}</DropdownItem> </DropdownMenu> </Dropdown> </div> <i-menu theme="light" :width="width" ref="menu" @on-select="onSelect" style="flex: 1; overflow-y: auto; overflow-x: hidden; z-index: 0;" :active-name="active"> <menu-group title=""> <menu-item v-for="(item, index) in menu" :id="'menu' + index" :name="index + ''" :key="index"> <span>{{item.title}}</span> <span v-if="$isDebug() && $isLogin() && (typeof item.position == 'undefined' || item.position.length == 0) && (typeof item.topic == 'undefined' || item.topic.length == 0)" style="color: red; font-size: 8px;">{{"無"}}</span> <span v-else-if="$isDebug() && $isLogin() && (typeof item.position == 'undefined' || item.position.length == 0) && (Array.isArray(item.topic) && item.topic.length > 0)" style="color: blue; font-size: 8px;">{{"合"}}</span> <span v-else-if="$isDebug() && $isLogin() && Array.isArray(item.position) && Array.isArray(item.topic) && item.position.length != item.topic.length" style="color: green; font-size: 8px;">{{"未"}}</span> </menu-item> </menu-group> </i-menu> <div style="display: flex; flex-direction: row; align-items: center;" id="version"> <i-button v-if="$isLogin()" type="success" @click.native="onClickDocument()" icon="md-document" shape="circle" style="margin: 0px 5px; "></i-button> <div style="flex: 1;">2022-04-13 09:30</div> <i-button v-if="$isDebug() && $isLogin()" type="success" @click.native="onClickAdd()" icon="md-add" shape="circle" style="margin: 0px 5px; "></i-button> </div> <Icon v-if="$isFlutter()" type="logo-youtube" size="28" color="red" @click.native="changeTo()" style="cursor: pointer; position: absolute; right: 20px; bottom: 50px; padding: 10px;"> </Icon> <yt-document :menu="document" @on-close="document = [];" ></yt-document> </div> `, props: { }, data() { return { smallScreen: true, width: "250", active: "0", topic: "0", project: [ ], menu: [], document: [] }; // }, created(){ }, mounted () { this.intit(); this.broadcast.$on('onResize', this.onResize); }, destroyed() { this.broadcast.$off('onResize', this.onResize); }, methods: { onClickDocument(){ this.document = this.menu; }, changeTo() { location.replace('../VOA/index.html'); }, async intit(){ if(this.$isLogin()) { this.project = await this.downloadProject(); if(this.project.length > 0) { let m = window.localStorage["yt-project"]; if(typeof m != "undefined") { this.topic = m; } this.menu = await this.downloadMenu(); } } document.body.style.visibility = "visible"; // this.projectUpload() }, async onSelect(index){ if(index < this.menu.length) { this.$emit('on-select', this.menu[index]); let project = this.project[this.topic].id; window.localStorage["yt-menu-" + project] = this.menu[index].id; if(this.smallScreen == true) { this.onClickIcon(); } this.active = index + ''; // if(this.menu[index].title.indexOf("Form ") == 0) { // 修改 ALCPT index // console.log(this.menu[index].title + ", index: " + this.menu[index].index); // if(typeof this.menu[index].position == "undefined" && Array.isArray(this.menu[index].children)) { // this.menu[index].position = this.menu[index].children; // delete this.menu[index].children; // this.upload(Object.assign({}, this.menu[index])) // } // console.log(this.menu[index]) // // this.menu[index].index = parseInt(this.menu[index].title.replace("Form ", ""), 10); // // console.log(this.menu[index].title + ", index: " + this.menu[index].index); // // // } } }, onClickIcon(){ let el = document.getElementById("frameMenu"); el.style.visibility = "hidden"; }, onResize(small){ this.smallScreen = small; let el = document.getElementById("frameMenu"); if(small == true) { el.classList.add("smallScreen"); this.width = document.body.clientWidth + ""; el.style.visibility = "hidden"; } else { el.classList.remove("smallScreen"); this.width = "240"; el.style.visibility = "visible"; } }, onClickAdd(){ this.$emit('on-click-add'); }, set(data){ let i = this.menu.findIndex(el =>{ return el.id == data.id; }) let obj = Object.assign({}, data) if(i > -1) { this.menu[i] = data; this.$set(this.menu, i, data) } else { this.menu.push(data) obj.index = this.menu.length - 1; } if(obj.id == "" && typeof obj.topic == "undefined") { // obj.topic = [] } this.upload(obj) return i; }, async upload(json){ let id = json.id; delete json.id; let date = (new Date()).getTime(); try { let ref = FireStore.db.collection("YouTube").doc("目錄"). collection(this.project[this.topic].id).doc(id); let x = await ref.set(json); this.$Notice.success({title: '已上傳 Firebase'}); } catch(e) { console.log(e) } }, async downloadProject() { return new Promise( async (success, error) => { try { let project = []; let snapshot = await FireStore.db.collection("YouTube").doc("目錄") .collection("project").get(); snapshot.forEach(async doc => { let json = Object.assign({id: doc.id}, doc.data()); project.push(json); }); project.sort((a, b) => { if(a.index > b.index) return 1; else if(a.index < b.index) return -1; else return 0; }); success(project); } catch(e) { console.log(e) } }); }, async downloadMenu(){ return new Promise( async (success, error) => { try { let project = this.project[this.topic].id; let menu = []; let snapshot = await FireStore.db.collection("YouTube").doc("目錄") .collection(project).get(); snapshot.forEach(async doc => { let json = Object.assign({id: doc.id}, doc.data()); if(! this.$isDebug() && json.index <= 40){ } else if(this.$isDebug() || (Array.isArray(json.position) && Array.isArray(json.topic) && json.topic.length == json.position.length) || (Array.isArray(json.topic) && json.topic.length > 0 && (!Array.isArray(json.position) || json.position.length ==0) ) ) menu.push(json); }); menu.sort((a, b) => { if(a.index > b.index) return 1; else if(a.index < b.index) return -1; else return 0; }); let m = window.localStorage["yt-menu-" + project]; if(typeof m == "string" || typeof x == "number") { // this.active = m; for(let i = 0; i < menu.length; i++ ) { if(menu[i].id == m) { this.active = i.toString(); break; } } } else this.active = '0'; // console.log(m + "-" + this.active) setTimeout(() => { this.$nextTick(()=>{ this.$refs.menu.updateOpened(); this.$refs.menu.updateActiveName(); }); if(this.menu.length > 0) { let el = document.getElementById("menu" + this.active); if(el != null) el.scrollIntoView({block: "center"}); } this.onSelect(this.active); }, 600); success(menu); } catch(e) { console.log(e) } }); }, async projectUpload(){ console.log("fiebase.............") let date = (new Date()).getTime(); // /" + report let project = [ ]; let xProject = 0; async function uploadProject(){ // upload Project try { for(let i = 0; i < project.length; i++) { let obj = Object.assign({}, project[i]); obj.modifyDate = date; obj.index = i; let key = obj.key; delete obj.key; let ref = FireStore.db.collection("YouTube").doc("目錄"). collection("project").doc(key); let x = await ref.set(obj); console.log(x) } } catch(e) { console.log(e) } } async function uploadMenu(){ try { let menu = []; for(let i = 0; i < menu.length; i++) { let obj = { title: menu[i].title, modifyDate: date, index: i } let ref = FireStore.db.collection("YouTube").doc("目錄"). collection(project[xProject].key).doc(menu[i].key); let x = await ref.set(obj); console.log(x) } } catch(e) { console.log(e) } } // uploadMenu(); }, async onClickProject(name){ console.log(name) this.topic = name; window.localStorage["yt-project"] = name; this.menu = await this.downloadMenu(); } }, computed: { }, watch: { } });
// @flow strict import * as React from 'react'; import { Translation, DateFormatter } from '@kiwicom/mobile-localization'; type Props = {| +boardingPassAvailableDate: Date | null, +boardingPassUrl: ?string, |}; export default function PastBookingInformation({ boardingPassAvailableDate, boardingPassUrl, }: Props) { if (boardingPassAvailableDate === null || boardingPassUrl == null) { return null; } return ( <Translation id="mmb.boarding_passes.past_booking_information.missed_checkin" values={{ date: DateFormatter(boardingPassAvailableDate).formatToBirthday(), }} /> ); }
import React, { Component } from 'react' import enzyme, { shallow } from 'enzyme' import Adapter from 'enzyme-adapter-react-16' import renderer from 'react-test-renderer' import Member from './Member' import { Text, View, Image } from 'react-native' enzyme.configure({ adapter: new Adapter()}) let wrapper let data beforeEach(() => { data = { username: 'herby', deviceId: '123', email: 'foo@bar.com' } wrapper = shallow(<Member data={data}/>) }) describe('<Member/>', () => { it('should render <Member/>', () => { expect(wrapper).toBeDefined() }) }) describe('<Member/> child is rendered', () => { it('should render <Text/>' , () => { expect(wrapper.find(<Text/>)).toBeDefined() expect(wrapper.find('Text').length).toBe(3) }) it('Should render <View/>', () => { expect(wrapper.find(<View/>)).toBeDefined() expect(wrapper.find('View').length).toBe(4) }) it('Should render <Image/>', () => { expect(wrapper.find(<Image/>)).toBeDefined() expect(wrapper.find('Image').length).toBe(1) }) }) describe('<Image/> renders the correct image', () => { it('should render the proper image', () => { expect(wrapper.find(<Image source={require('./assets/hombre.png')}/>)).toBeDefined() }) })
const formats = [{ regex: /\*([^\*]+)\*/, replacer: function (m, p1) { return "%c" + p1 + "%c"; }, styles: function () { return ['background: rgb(255, 255, 219); padding: 1px 5px; border: 1px solid rgba(0, 0, 0, 0.1)', '']; } }, { regex: /\_([^\_]+)\_/, replacer: function (m, p1) { return "%c" + p1 + "%c"; }, styles: function () { return ['font-weight: bold', '']; } }, { regex: /\[c\=(?:\"|\')?((?:(?!(?:\"|\')\]).)*)(?:\"|\')?\]((?:(?!\[c\]).)*)\[c\]/, replacer: function (m, p1, p2) { return "%c" + p2 + "%c"; }, styles: function (match) { return [match[1], '']; } }]; let logger = {}; const levels = ['debug', 'info', 'warn', 'error']; levels.forEach((level) => { logger[level] = function () { let args; args = []; makeArray(arguments).forEach(function (arg) { if (typeof arg === 'string') { return args = args.concat(stringToArgs(arg)); } else { return args.push(arg); } }); let stack = new Error().stack; let line = stack.split('\n')[2]; let infoIndex = line.indexOf("eval at "); let clean = line.slice(infoIndex + 8, line.length).split(' ')[0]; return console[level].apply(console, makeArray(args)); }; }); let makeArray = function (arrayLikeThing) { return Array.prototype.slice.call(arrayLikeThing); }; let hasMatches = function (str) { let _hasMatches; _hasMatches = false; formats.forEach(function (format) { if (format.regex.test(str)) { return _hasMatches = true; } }); return _hasMatches; }; let getOrderedMatches = function (str) { let matches; matches = []; formats.forEach(function (format) { let match; match = str.match(format.regex); if (match) { return matches.push({ format: format, match: match }); } }); return matches.sort(function (a, b) { return a.match.index - b.match.index; }); }; let stringToArgs = function (str) { let firstMatch, matches, styles; styles = []; while (hasMatches(str)) { matches = getOrderedMatches(str); firstMatch = matches[0]; str = str.replace(firstMatch.format.regex, firstMatch.format.replacer); styles = styles.concat(firstMatch.format.styles(firstMatch.match)); } return [str].concat(styles); }; export default logger; export let log = logger.debug;
/* ******** * Requires * ********/ // Chrome var ChromeConstants = require("./xul-manager/chrome-constants.js").ChromeConstants; // SDK let Preferences = require('sdk/preferences/service'); var data = require("sdk/self").data; // Bugzilla libraries var User = require('./user').User; var BugManager = require("./bug-manager").BugManager; function BugzillaWidget () { // DOM objects let document = null; let view = null; // Bugzilla objects let user = new User(); let bugManager = new BugManager(); bugManager.setUser(user); user.setManager(bugManager); // Read preferences if (Preferences.isSet('australis-bugzilla-widget.user.name') && Preferences.isSet('australis-bugzilla-widget.user.email')) { user.setUserName(Preferences.get('australis-bugzilla-widget.user.name')); user.setUserEmail(Preferences.get('australis-bugzilla-widget.user.email')); } /** * Constructs all UI elements and appends them to the view. */ function injectUI () { // Load the main XUL file var xul = data.load('bug-list.xul'); // Write to view view.innerHTML = xul; // Set document user.setDocument(document); bugManager.setDocument(document); // Draw user.draw(); bugManager.draw(); } return { CONFIG: { id: "australis-bugzilla-widget", type: "view", viewId: "australis-bugzilla-widget-view", removable: true, defaultArea: ChromeConstants.AREA_PANEL() }, /** * Widget creation event handler. * * Inserts the widget's button in a given node. * * @param {XMLElement} node XML node to which the button will be attached. */ widgetCreated: function(node) { // Get the document let doc = node.ownerDocument; // Create the button's image let img = doc.createElement("image"); img.setAttribute("class", "toolbarbutton-icon"); img.id = "australis-bugzilla-widget-icon"; img.setAttribute("src", data.url('favicon.ico.png')); img.setAttribute("width", "16px"); img.setAttribute("height", "16px"); // Create the button's label let lbl = doc.createElement("label"); lbl.setAttribute("class", "toolbarbutton-text toolbarbutton-label"); lbl.setAttribute("flex", "1"); lbl.setAttribute("value", "Bugzilla"); lbl.id = "australis-bugzilla-widget-label"; // Attach the button elements to the node node.appendChild(img); node.appendChild(lbl); }, /** * Widget showing event handler. * * Inserts the widget's panel elements into the active window. * * @param {XMLDocument} doc The document into which the widget is to be inserted. * @param {XULElement} theView The widget panelview to be inserted into the active window. */ viewShowing: function (doc, theView) { // Get the document document = doc; // Load our stylesheet var css = data.url('styles.css'); // Resource URL to our stylesheet let xmlPI = document.createProcessingInstruction('xml-stylesheet', 'href="'+css+'" type="text/css"'); // Create an XML processing instruction for a stylesheet document.insertBefore(xmlPI, document.firstElementChild); // Set the view view = theView; // Write our UI to the panelview injectUI(); } }; } exports.BugzillaWidget = BugzillaWidget;
/* Admin view of edit/delete buttons for single item */ import React, { Component } from "react"; import PropTypes from "prop-types"; import Link from "next/link"; import Title from "../styles/Title"; import ProductStyles from "../styles/ItemStyles"; import PriceTag from "../styles/PriceTag"; import formatMoney from "../../lib/formatMoney"; import DeleteProduct from "../Admin/DeleteProduct"; import AddToCartButton from "../Cart/AddToCart"; export default class AdminProduct extends Component { static propTypes = { item: PropTypes.object.isRequired, }; render() { const { item } = this.props; return ( <ProductStyles> {item.image && <img src={item.image} alt={item.title} />} <Title> <Link prefetch href={{ pathname: "/product", query: { id: item.id }, }} > <a>{item.title}</a> </Link> </Title> <PriceTag>{formatMoney(item.price)}</PriceTag> <p>{item.description}</p> <div className="buttonList"> <Link prefetch href={{ pathname: "update", query: { id: item.id }, }} > <a>Edit Item ✏️</a> </Link> <DeleteProduct id={item.id}>Delete This Item</DeleteProduct> </div> </ProductStyles> ); } } /* Product Component for single item */
import React, { Component } from 'react'; import axios from 'axios'; import moment from 'moment'; class Edit extends Component{ constructor(){ super(); this.state = { task: {} } } componentDidMount(){ console.log(this.props) const tid = this.props.match.params.id; axios({ method: 'GET', url: `http://localhost:3000/getTask/${tid}` }).then((taskFromBackEnd)=>{ this.setState({ task: taskFromBackEnd.data.task }) }) } changeTask = (e)=>{ const value = e.target.value; let taskStateCopy = {...this.state.task} // stateCopy "unpacks" ...this.stat.task to convert property to object // let stateCopy = Object.assign({},this.state.task) taskStateCopy.taskName = value; this.setState({ task: taskStateCopy }) } changeDate = (e)=>{ let value = e.target.value; let taskStateCopy = {...this.state.task} taskStateCopy.task.taskDate = moment(value).format('YYYY-MM-DD'); this.setState({ task: taskStateCopy }) } editTask = (e)=>{ e.preventDefault() axios({ method: "POST", data: { task: this.state.task, id: this.props.match.params.id }, url: `http://localhost:3000/edit/` }).then ((jsonData)=>{ console.log(jsonData.data); if(jsonData.data.msg === 'updated'){ // the backend, whoever and whatever is, succeded // moving on... this.props.history.push('/'); } }) } render(){ console.log(this.state.task); return( <div className="container"> <form onSubmit={this.editTask} className="add-box"> <input onChange={this.changeTask} type="text" id="new-task" value={this.state.task.taskName} /> <input onChange={this.changeDate} type="date" id="new-task-date" value={moment(this.state.task.taskDate).format('YYYY-MM-DD')}/> <button type="submit" className="btn btn-primary">Update</button> </form> </div> ) } } export default Edit;
var express = require('express'); var router = express.Router(); var shareDao = require('../dao/shareDao'); var recommendDao = require('../dao/recommendDao'); var utils = require('../util/utils'); var util = require('util'); var setting = require('../config/setting'); /* 播放接口 */ router.get('/getShare', function (req, res, next) { var uid = req.query.uid; var gameId = req.query.gameId; // 必要参数验证 if (!uid || !gameId) { return utils.responseError(res, '100001'); } // 获取分享 shareDao.fetchCacheRowById(gameId,uid, function (err, row) { var data = {}; if (!row || err) { return utils.responseError(res, '101003'); } // 将缓存中的值进行拷贝,防止直接修改 for (var field in row.gameData) { data[field] = row.gameData[field]; } var flag = false; // 判断玩家是否参与牌局,玩家只能分享自己参与的牌局 for(key in data.gamers){ if(data.gamers[key].uid==uid && !flag){ flag = true; break; } continue; } console.log(flag); if(!flag){ console.log('api错误界面'); return res.render('error', {message: '您不能查看您没有参与的牌局'}); } var statisticsCache = shareDao.fetchStatisticsCacheItem(gameId,uid); if (statisticsCache) { // var likeStatisticsCache = statisticsCache['likeTimes'] ? statisticsCache['likeTimes'] : 0; // var playStatisticsCache = statisticsCache['playTimes'] ? statisticsCache['playTimes'] : 0; // data['AllPlay'] += playStatisticsCache; // data['AllLike'] += likeStatisticsCache; } data.ShareUid = uid; recommendDao.add(gameId,uid, data.ShareUid); utils.responseSuccess(res, data); // 增加播放次数 // shareDao.incrPlayStatistics(gameId,uid,function (code) { // // 播放,点赞数量 = 数据库数量+缓存数量 // // // }); }); }); /* 点赞 */ router.get('/doLike', function (req, res, next) { var uid = req.query.uid; var gameId = req.query.gameId; // 必要参数验证 if (!uid || !gameId) { return utils.responseError(res, '100001'); } // 分享存在增加点赞次数,否则放回错误 shareDao.fetchCacheRowById(gameId,uid, function (err, row) { if (!row || err) { return utils.responseError(res, '101003'); } shareDao.incrLikeStatistics(gameId,function (code) { if (code === '200') { return utils.responseSuccess(res); } }); // recommendDao.add(gameId,uid, uid); }); }); /*取消赞*/ router.get('/unDoLike', function (req, res, next) { var AllLike = req.query.AllLike; var gameId = req.query.gameId; // 必要参数验证 if (!AllLike || !gameId) { return utils.responseError(res, '100001'); } // 分享存在增加点赞次数,否则放回错误 shareDao.fetchCacheRowById(gameId,AllLike, function (err, row) { if (!row || err) { return utils.responseError(res, '101003'); } shareDao.decrLikeStatistics(gameId,AllLike,function (code) { if (code === '200') { return utils.responseSuccess(res); } }); // recommendDao.add(gameId,uid, uid); }); }); /* * 获取推荐 */ router.get('/getRecommend', function (req, res, next) { var recommendShowNum = 8; shareDao.fetchAll(recommendShowNum, function (err, rows) { // rows.splice(0, 5); // for(key in rows[0]){ // console.log('rows[0]='+key+':'+rows[0][key]); // } var recommends = []; for (var i in rows) { if (rows[i]) { // 解析牌局数据 var createAt = shareDao.parseShareDT(rows[i].createAt); // console.log(createAt); // 参与玩家 var sysCardUrlFormat = setting['sysCardUrlFormat']; // var uploadAvatarUrlFormat = setting['uploadAvatarUrlFormat']; // 获胜玩家 var winNick, winUserID, winScore = 0,winSlefCard; var gamers = rows[i].gamers; for (var j in gamers) { let score = gamers[j].endChip-gamers[j].startChip; if (gamers[j].endChip>gamers[j].startChip&& score > winScore) { winScore = score; winUserID = gamers[j].uid; winNick = decodeURIComponent(gamers[j].nick); winSlefCard = gamers[j].selfCard; // console.log('winSelfCard======================'+winSlefCard); winSlefCardUrl = []; for(let i=0;i<winSlefCard.length;i++){ if (winSlefCard[i] > 0) winSlefCardUrl.push(util.format(sysCardUrlFormat, winSlefCard[i])); // console.log('=-=-=-=-==-=-=-=-=-=-=-=-=-=-='+winSlefCardUrl); } // winSlefCardUrl = playerMap[winUserID]['avatar'] > 0 // ? util.format(sysCardUrlFormat, playerMap[winUserID]['avatar']) // : util.format(uploadAvatarUrlFormat, playerMap[winUserID]['avatar']); } } // 推荐数据 var recommendRow = { // MyShareID: rows[i]['ShareUid'], WinNick: winNick, WinScore: winScore, gameId:rows[i].gameId, winUserID:winUserID, winSlefCardUrl:winSlefCardUrl, AllLike: rows[i]['AllLike'], AllPlay: rows[i]['AllPlay'], }; recommends.push(recommendRow); } } return utils.responseSuccess(res, recommends); }); }); /* * 运行状态 */ router.get('/state', function (req, res, next) { var shareDateCacheSize = shareDao.shareDateCache.size(); var shareStatisticsCacheSize = shareDao.shareStatisticsCache.size(); recommendDao.size(function (err, recommendSize) { var stateData = { recommendSize: recommendSize, shareDateCacheSize: shareDateCacheSize, shareStatisticsCacheSize: shareStatisticsCacheSize }; return utils.responseSuccess(res, stateData); }); }); module.exports = router;
var touch = require('touch') var path = require('path') var fs = require('fs') module.exports = editTestFile function editTestFile (directory, opts, done) { if (!opts.hasTest) return done() var file = path.resolve(directory, 'test.js') var base = path.resolve(__dirname, 'test.base.js') var circleFile = path.resolve(directory, 'circle.yml') var circleBase = path.resolve(__dirname, 'circle.yml') var appveyorFile = path.resolve(directory, 'appveyor.yml') var appveyorBase = path.resolve(__dirname, 'appveyor.yml') touch.sync(file) touch.sync(circleFile) fs.readFile(file, 'utf8', function (err, content) { if (err) return doCircle(err) if (content.trim()) return doCircle() fs.writeFile(file, fs.readFileSync(base, 'utf8'), doCircle) }) function doCircle (err) { if (err) return done(err) fs.readFile(circleFile, 'utf8', function (err, content) { if (err) return done(err) if (content.trim()) return doAppveyor() fs.writeFile(circleFile, fs.readFileSync(circleBase, 'utf8'), doAppveyor) }) } function doAppveyor (err) { if (err) return done(err) fs.readFile(circleFile, 'utf8', function (err, content) { if (err) return done(err) if (content.trim()) return done() fs.writeFile(appveyorFile, fs.readFileSync(appveyorBase, 'utf8'), done) }) } }
import React,{useState} from 'react' import {FaCamera} from "react-icons/fa" import {ContextProvider} from "../Global/Context" const Create = () => { const {create, loader, user}= React.useContext(ContextProvider) const[title, setTitle]=useState(''); const[image, setImage]=useState(''); const handleImage =(e)=>{ setImage(e.target.files[0]); } const createPost =e=>{ e.preventDefault(); create({title,image}) setTitle(''); setImage('') } return ( <> {! loader && user ?<div className="create"> <form onSubmit={createPost}> <div className="create__input"> <input type="text" className="create__inputt" onChange={e=> setTitle(e.target.value)} value={title} placeholder="What are in your mind" required/> </div> <div className="create__second"> <label htmlFor="file"> <FaCamera className="camera"/> </label> <input type="file" onChange={handleImage} className="file" id="file" required/> </div> <div className="create__second-b"> <input type= "submit" value="Create" className="btn-sweet"/> </div> </form> </div> :""} </> ) } export default Create
let arraySrc = new Array(1, 2, 3, 3, 33, 4 , 5, 5, 5, 5, 6, 6); let result1 = arraySrc.find(num => num > 3); let result2 = arraySrc.filter(num => num > 3); //可以看出来find仅仅是返回一个元素 console.log(result1); console.log(result2); let objList = [ { name: "顾世豪", sex: "男" }, { name: "习近平", sex: "男" }, { name: "彭丽媛", sex: "女" }, { name: "哈哈哈", sex: "女" } ]; let result3 = objList.filter((item) => { return item.sex == "女"; }); console.log(result3); let result4 = objList.find((item) => { return item.sex == "女"; }); console.log(result4);
import React, { Component } from 'react'; import { View, Text, StyleSheet, Image, TouchableOpacity } from 'react-native'; import { Icon, Button } from 'react-native-elements'; import { Actions } from 'react-native-router-flux'; import { joinPublicGroup, joinPrivateGroup } from '../../services/apiActions'; export class GroupDetail extends Component { constructor(props) { super(props); this.state = { }; this.joinGroup = this.joinGroup.bind(this); } joinGroup(group) { console.log("THIS IS GROUP", group) if(group.publicGroup || !group.private) { //join public joinPublicGroup(group) .then((success) => { console.log("SUCCESS")}) .catch((err) => { console.log("FAILURE")}) } else { // join private } } render() { const { group } = this.props; return ( <View style={styles.groupItem}> { group.myGroup && <Icon name='group' color='#8E8E8E' /> } { group.publicGroup && <Icon name='lock-open' color='#8E8E8E' />} { group.privateGroup && <Icon name='lock' color='#8E8E8E' />} <View style={styles.textContainer}> <TouchableOpacity onPress={() => Actions.groupProfile({group: group})}> <Text style={styles.text}> {`${group.name}`} </Text> <Text style={styles.memberCount}> {`${group.memberCount} Members` } </Text> </TouchableOpacity> <TouchableOpacity style={styles.moveButtonsRight}> { group.publicGroup && <Button buttonStyle={styles.acceptJoinGroupRequestButton} title="JOIN" icon={{name: 'add', color: '#4296CC'}} backgroundColor='#FFF' color='#4296CC' borderRadius={1} onPress={() => this.joinGroup(group)} /> } { group.privateGroup && <Button buttonStyle={styles.acceptJoinGroupRequestButton} title="REQUEST" icon={{name: 'add', color: '#4296CC'}} backgroundColor='#FFF' color='#4296CC' borderRadius={1} /> } </TouchableOpacity> </View> </View> ); } } const styles = StyleSheet.create({ groupItem: { height: 45, flexDirection: 'row', marginLeft: 10, marginTop: 7, marginBottom: 5, alignItems: 'stretch', justifyContent: 'space-between' }, textContainer: { flex: 1, marginLeft: 5, marginTop: 10, flexDirection: 'row', alignSelf: 'flex-start' }, text: { marginLeft: 8, fontSize: 16, color: '#4296CC', fontWeight: '500' }, memberCount: { color: '#8D8F90', fontSize: 12, paddingLeft: 10 }, acceptJoinGroupRequestButton: { borderWidth: 1, borderColor: '#4296CC', alignSelf: 'flex-end' }, acceptJoinPlus: { color: '#4296CC', backgroundColor: '#4296CC' }, moveButtonsRight: { flex: 1 } });
const http = require('http'); const fs = require('fs'); let server = http.createServer((req, res) => { console.log('Yo! The request was made: ' + req.url); //If user visits localhost:3000 or localhost:3000/home //then respond (serve up) with the index.html file. if(req.url === '/home' || req.url === '/') { res.writeHead(200, {'Content-Type': 'text/html'}); fs.createReadStream(__dirname + '/index.html').pipe(res); } else if(req.url === '/contact') { res.writeHead(200, {'Content-Type': 'text/html'}); fs.createReadStream(__dirname + '/contact.html').pipe(res); } else if(req.url === '/api/people') { //Normally would get data from a database, but here for example. let myObj = { name: 'Tim', job: 'IT', age: 23 }; res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify(myObj)); } else { res.writeHead(404, {'Content-Type': 'text/html'}); fs.createReadStream(__dirname + '/404.html').pipe(res); } }); //or can be localhost server.listen(3000, '10.96.184.193');
export { PieChartIcon } from "./PieChartIcon"; export { BarChartIcon } from "./BarChartIcon"; export { LineChartIcon } from "./LineChartIcon";
//Punto 1 function secret(mensaje, tipo, num){ let retorno = [] mensaje.forEach(x => { if (tipo === "encrypt"){ let elem = Number(x)+ Number(num) console.log(elem) retorno.push(elem) }else{ let elem = Number(x) - Number(num) retorno.push(elem ) } }); return retorno } //Punto 2 const maxComunDiv = (a,b) => a===b ? a : a>b ? maxComunDiv(b, a-b): maxComunDiv(a, b-a)
// @flow import React, { Component, Fragment } from "react"; import { connect } from "react-redux"; import { type AsyncStatusType, type NotificationType, } from "shared/types/General"; import Layout from "components/inventoryLayout"; import Button from "components/button"; import Loader from "components/loader"; import Alert from "components/Alert"; import { confirmAlert } from "react-confirm-alert"; import "react-confirm-alert/src/react-confirm-alert.css"; import ReactHTMLTableToExcel from "react-html-table-to-excel"; import { Link } from "react-router-dom"; import { ASYNC_STATUS } from "constants/async"; import { getOrders, deleteOrders } from "action/orders"; import { filters } from "constants/user"; import "./styles.scss"; type AdminViewOrdersPageProps = { getOrders: Function, deleteOrders: Function, status: AsyncStatusType, notification: NotificationType, orders: Array<any>, }; class AdminViewOrdersPage extends Component<AdminViewOrdersPageProps> { constructor(props) { super(props); // $FlowFixMe this.confirmationMessage = this.confirmationMessage.bind(this); // $FlowFixMe this.deleteOrder = this.deleteOrder.bind(this); } componentDidMount() { this.props.getOrders({ ...filters }); } confirmationMessage(orderNumber) { confirmAlert({ title: "Confirm", message: "Are you sure to delete this?", buttons: [ { label: "Yes", onClick: () => { this.deleteOrder(orderNumber); }, }, { label: "No", onClick: () => {}, }, ], }); } deleteOrder(orderNumber) { this.props.deleteOrders(orderNumber); } render() { const { status, notification, orders } = this.props; return ( <Layout breadcrumbs={["View Orders"]} actions={ <Fragment> <ReactHTMLTableToExcel id="test-table-xls-button" className="download-table-xls-button" table="dataTable" filename="Orders Report" sheet="orders_report" buttonText="Generate Report" /> </Fragment> } > {notification && ( <Alert type={notification.type}>{notification.message}</Alert> )} {status === ASYNC_STATUS.LOADING ? ( <Loader isLoading /> ) : ( <div className="view-orders"> <div className="table-container"> <div className="table-section"> <table id="dataTable"> <tbody> <tr className="table-heading"> <th>Order Id</th> <th>Supplier Code</th> <th>Product Code</th> <th>Product Name</th> <th>Size</th> <th>Price</th> <th>Color</th> <th>Quantity</th> <th>Action</th> </tr> {orders.length > 0 && orders.map((order) => { return ( <tr key={order.orderId}> <td> <Link to={`/orders/update/${order.orderId}`}> {order.orderId} </Link> </td> <td>{order.supplierCode}</td> <td>{order.productCode}</td> <td>{order.productName}</td> <td>{order.size}</td> <td>{order.price}</td> <td>{order.color}</td> <td>{order.quantity}</td> <td> <Button type={Button.TYPE.DANGER} onClick={() => this.confirmationMessage(order.orderId) } > Delete </Button> </td> </tr> ); })} </tbody> </table> </div> </div> </div> )} </Layout> ); } } function mapStateToProps(state) { return { status: state.order.status, notification: state.order.notification, orders: state.order.orders, }; } const Actions = { getOrders, deleteOrders, }; export default connect(mapStateToProps, Actions)(AdminViewOrdersPage);
TextInput = React.createClass({ onKeyDown: function(e){ if(e.keyCode == 13){ this.save(); //this.setState({editing: false}) } }, //componentDidMount: function(){ // React.findDOMNode(this.refs.fieldName).select(); //}, save: function(e){ Celestial.updateItem(this.props, this.props.field ? this.props.field : 'value', e.target.value); }, edit(e) { console.log('TextInput: ' ); this.setState({value: e.target.value}) }, render() { const defaultValue = this.props.value ? this.props.value : this.props.field ? this.props.item[this.props.field] : this.props.item.value; console.log(`TextInput: ${this.props.field},${this.props.value},${this.props.item.value}`); return !this.props.allowLink ? <input type='text' onChange={this.edit} onBlur={this.save} defaultValue={defaultValue} /> : <div> <input type='text' onChange={this.edit} onBlur={this.save} defaultValue={defaultValue} /> <input type="checkbox" onChange={this.unlink} /> custom </div> } })
exports.command = function (selector, value) { return this.clearValue(selector) .setValue(selector, value) .trigger(selector, 'keyup', 13) }
Scoped.define("module:VideoPlayer.Dynamics.Loader", [ "dynamics:Dynamic", "module:Templates", "module:Assets" ], function (Class, Templates, Assets, scoped) { return Class.extend({scoped: scoped}, function (inherited) { return { template: Templates.video_player_loader, attrs: { "css": "ba-videoplayer" } }; }) .register("ba-videoplayer-loader") .attachStringTable(Assets.strings) .addStrings({ "tooltip": "Loading video..." }); });
let routes = function (router) { let controller = { "/home": "./user/home.js", }; // 此时步骤,加入了处理函数。 for (x in controller) { router.use(x, require(controller[x])); } }; module.exports = routes;
const addContext = require('mochawesome/addContext'); const reportLogger = require('../../e2e/support/reportLogger'); class SoftAssert { constructor(testContext) { this.testContext = testContext; this.assertCount = 0; this.isPassed = true; this.assertions = []; this.scenarios = []; this.scenario; this.scrAssertionsCounter = 0; this.scenarioCounter = 0; } setScenario(scr) { this.scenarioCounter++; this.scrAssertionsCounter = 0; this.scenario = scr; } async assert(expectCallBack, verificationMsg) { this.scrAssertionsCounter++; this.assertCount++; try { await expectCallBack(); this.scenarios.push(`${this.scenarioCounter}.${this.scrAssertionsCounter} PASSED: ${this.scenario} : ${verificationMsg ? verificationMsg : ''}`); reportLogger.AddMessage(`************* ${this.scenarioCounter}.${this.scrAssertionsCounter} PASSED: ${this.scenario}: ${verificationMsg ? verificationMsg : ''}`); } catch (assertError) { this.isPassed = false; this.scenarios.push(`${this.scenarioCounter}.${this.scrAssertionsCounter} FAILED **: ${this.scenario}: ${verificationMsg ? verificationMsg : ''}`); // addContext(this.testContext, { title: "Screenshot path" , value: "../../"}); this.assertions.push(`${this.scenarioCounter}.${this.scrAssertionsCounter} : ${assertError.message}`); reportLogger.AddMessage(`************* ${this.scenarioCounter}.${this.scrAssertionsCounter} FAILED **: ${this.scenario}: ${verificationMsg ? verificationMsg : ''} => ${assertError.message}`); await reportLogger.AddScreenshot(); } } finally() { let errors = '\n'; let errCounter = 0; for (const error of this.assertions) { errCounter++; errors = `${errors} \n ${error}`; } let scrs = errors + ' \n \n All Scenarios: \n'; for (const scr of this.scenarios) { scrs = `${scrs} \n ${scr}`; } scrs = scrs + '\n\n'; expect(this.isPassed).to.be.true; expect(this.assertions.length, `${this.assertions.length} of ${this.assertCount} assertions failed => Error(s) :` + scrs).to.equal(0); reportLogger.AddMessage(`************* All Scenarios \n\n ${scrs}`); } } module.exports = SoftAssert;
// import React from 'react'; // import ReactDOM from 'react-dom'; // import './index.css'; // import App from './App'; // import registerServiceWorker from './registerServiceWorker'; // ReactDOM.render(<App />, document.getElementById('root')); // registerServiceWorker(); import { createStore } from 'redux' import { combineReducers } from 'redux' const initialState = { cart: [ { product: 'bread 700g', quantity: 2, unitCost: 90, }, { product: 'milk 500ml', quantity: 1, unitCost: 47, }, ], } const productsReducer = function( state = [], action, ) { return state } const cartReducer = function(state = [], action) { return state } const allReducers = { products: productsReducer, shoppingCart: cartReducer, } const rootReducer = combineReducers(allReducers) let store = createStore(rootReducer) console.log('init state: ', store.getState()) function findArray(arr, cb) { const result = [] const indexArray = [] for (let i = 0; i < arr.length; i++) { if (cb(arr[i])) { result.push(arr[i]) indexArray.push(i) } } return { result, indexArray } } let arrlist = [21, 4, 5, 6, 7], cb = function(ele) { return ele % 2 == 0 } const { result, indexArray } = findArray( arrlist, cb, ) console.log(result) console.log(indexArray) const someArr = [1, 2, 3, 4] const [first, second, third] = someArr console.log(first) console.log(second) var url = 'https://developer.mozilla.org/en-US/Web/JavaScript' var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec( url, ) console.log(parsedURL) // ["https://developer.mozilla.org/en-US/Web/JavaScript", "https", "developer.mozilla.org", "en-US/Web/JavaScript"] var [, protocol, fullhost, fullpath] = parsedURL console.log(protocol) // "https" let { length: len } = 'abc' // len = 3 let { toString: s } = 123 // s = Number.prototype.toString console.log(len) console.log(s) let obj = { first: 'Jane', last: 'Doe' } let { ...xxx } = obj console.log(xxx)
const gameCardCopy = { en: { DESCRIPTION: "Displaying quantity of total games.", BUTTON: "Load more" }, kr: { DESCRIPTION: "total 개의 게임 중 quantity 개를 표시합니다.", BUTTON: "더로드" }, ch: { DESCRIPTION: "顯示total個遊戲中的quantity個。", BUTTON: "裝載更多" }, jp: { DESCRIPTION: "totalゲーム中quantityゲームを表示しています。", BUTTON: "もっと読み込む" }, ru: { DESCRIPTION: "Показано quantity из total игр.", BUTTON: "Больше Игр" } }; export default gameCardCopy;
"use strict"; // Gulp dev. var gulp = require('gulp'); var watch = require('gulp-watch'); var config = require('./gulp_tasks/config'); var plugins = require('gulp-load-plugins')(); var runSequence = require('run-sequence'); var exec = require('child_process').exec; function tasks(task, options) { return require('./gulp_tasks/' + task)(gulp, plugins, options); } //gulp.task('default', runSequence('sprite', 'sass')); gulp.task('watch', function(done){ watch(config.sprite.iconsPathSvg + '/**/*.svg', function(){runSequence('sprite', 'sass');}); watch(config.sprite.iconsPathPng + '/**/*.png', function(){runSequence('sprite', 'sass');}); }); // Default Task gulp.task('default', function(done){ runSequence('build', done); }) // Extract language file gulp.task('xi18n', function(done){ console.log('Extracting language file'); exec('node_modules/.bin/ng xi18n --i18n-format xlf --output-path src/locale --locale en-GB --out-file en-GB.xlf', {maxBuffer: 1024 * 500}, function (err, stdout, stderr) { if(stdout) console.log(stdout); if(stderr) console.log(stderr); done(err); }); }); // Build for Development gulp.task('build', function(done){ console.log('Build web application in Dev-Mode. Run "gulp build.prod" to build for production.') runSequence( 'sprite', 'ng-cli.build', 'copy.assets', done ); }); // Build for Development gulp.task('build.prod', function(done){ console.log('Build web application for Production. Run "gulp build" to build in Dev-Mode.') runSequence( 'sprite', 'ng-cli.build.prod', 'copy.assets.prod', done ); }); gulp.task('ng-cli.build', function(cb){ exec('node_modules/.bin/ng build', {maxBuffer: 1024 * 500}, function (err, stdout, stderr) { if(stdout) console.log(stdout); if(stderr) console.log(stderr); cb(err); }); }); gulp.task('ng-cli.build.prod', function(cb){ exec('node_modules/.bin/ng build -prod -aot', {maxBuffer: 1024 * 500}, function (err, stdout, stderr) { if(stdout) console.log(stdout); if(stderr) console.log(stderr); cb(err); }); }); gulp.task('copy.assets', tasks('copy.assets')); gulp.task('copy.assets.prod', tasks('copy.assets.prod')); gulp.task('sprite', tasks('spritinator'));
const fs = require('fs'); const mode = process.argv[2]; const dir = process.argv[3]; // create html for Sophie's web galleries // how to use: // $ node index.js work ~/Pictures/etc // $ node index.js news ~/Pictures/etc fs.readdir(dir, function(err, data) { if (err) { return err; } let dirString = (mode === 'work') ? 'work' : 'news'; data.forEach((file) => { console.log(`<div class="image-wrapper"><img src="/images/news/${dirString}${file}" alt="${file}" /></div>`); }); });
var Event = function(sender) { this._sender = sender; this._listeners = []; } Event.prototype.attach = function(listener) { this._listeners.push(listener) }; Event.prototype.notify = function(args) { for (var i = 0; i < this._listeners.length; i++) { this._listeners[i](args); } };
import React from 'react'; import Grid from '@material-ui/core/Grid'; import PropTypes from 'prop-types'; const ErrorNotification = ({ error }) => ( <Grid container justify="center"> <h1>Ой, что-то пошло не так: {error}</h1> </Grid> ); ErrorNotification.propTypes = { error: PropTypes.string.isRequired, }; export default ErrorNotification;
import { describe, it } from 'vitest'; import { shallowMount } from '@vue/test-utils'; import config from '../../../helpers/config.js' import reportCategoriesFromRouteMixin from '../reportCategoriesFromRouteMixin.js'; const mountComponentWithQuery = (component, query) => shallowMount(component, { global: { mocks: { $route: {query} } } }); const TestComponent = { mixins: [reportCategoriesFromRouteMixin], data() { return { geography: { id: 'blockgroup' } }; }, template: '<div></div>' }; describe('getVisibleMetrics', () => { it('properly parses null query', async ({expect}) => { const mockComponent = mountComponentWithQuery(TestComponent, {}); expect(mockComponent.vm.visibleMetrics).toEqual([]); }); it('properly parses array query', async ({expect}) => { const mockComponent = mountComponentWithQuery(TestComponent, {visibleMetrics: ['CCC', 'PCTIMP']}); expect(mockComponent.vm.visibleMetrics).toEqual(['CCC', 'PCTIMP']); }); it('properly parses string query', async ({expect}) => { const mockComponent = mountComponentWithQuery(TestComponent, {visibleMetrics: 'CCC'}); expect(mockComponent.vm.visibleMetrics).toEqual(['CCC']); }); }); describe('fullyVisibleCategories', () => { it('properly returns all categories with no query', async ({expect}) => { const mockComponent = mountComponentWithQuery(TestComponent, {}); expect(mockComponent.vm.fullyVisibleCategories).toEqual(config.categories.sort()); }); it('properly returns no categories with one visible metric', async ({expect}) => { const mockComponent = mountComponentWithQuery(TestComponent, { visibleMetrics: 'CCC'}); expect(mockComponent.vm.fullyVisibleCategories).toEqual([]); }); it('properly returns what is in the query parameter otherwise', async ({expect}) => { const mockComponent = mountComponentWithQuery(TestComponent, { visibleMetrics: 'CCC', visibleCategories: ['Education']}); expect(mockComponent.vm.fullyVisibleCategories).toEqual(['Education']); }); }); describe('partiallyVisibleCategories', () => { it('returns nothing with a null query', async ({expect}) => { const mockComponent = mountComponentWithQuery(TestComponent, {}); expect(mockComponent.vm.partiallyVisibleCategories).toEqual([]); }); it('returns partially visible categories if a few visible metrics are set', async ({expect}) => { const mockComponent = mountComponentWithQuery(TestComponent, { visibleMetrics: ['POPDENS', 'PTASNL', 'P_SQM'], visibleCategories: ['Environment'] }); expect(mockComponent.vm.partiallyVisibleCategories).toEqual(['Crime', 'Demographics']); }); }); describe('visibleCategories', () => { it('returns everything with a null query', async ({expect}) => { const mockComponent = mountComponentWithQuery(TestComponent, {}); expect(mockComponent.vm.visibleCategories).toEqual(config.categories.sort()); }); it('returns fully + partially visible categories if a few visible metrics are set', async ({expect}) => { const mockComponent = mountComponentWithQuery(TestComponent, { visibleMetrics: ['POPDENS', 'PTASNL', 'P_SQM'], visibleCategories: ['Environment'] }); expect(mockComponent.vm.visibleCategories).toEqual(['Crime', 'Demographics', 'Environment']); }); }); describe('getToggleCategoryRoute', () => { it('removes a single fully visible category', async ({ expect }) => { const mockComponent = mountComponentWithQuery(TestComponent, { visibleMetrics: ['POPDENS', 'PTASNL', 'P_SQM'], visibleCategories: ['Environment'] }); expect(mockComponent.vm.getToggleCategoryRoute('Environment').query).toEqual( { visibleCategories: [], visibleMetrics: ['POPDENS', 'PTASNL', 'P_SQM'],} ); }); it('removes all metrics from a partially visible category', async ({ expect }) => { const mockComponent = mountComponentWithQuery(TestComponent, { visibleMetrics: ['POPDENS', 'PTASNL', 'P_SQM'], visibleCategories: ['Environment'] }); expect(mockComponent.vm.getToggleCategoryRoute('Demographics').query).toEqual( { visibleCategories: ['Environment'], visibleMetrics: ['P_SQM'],} ); }); it('adds a fully invisible category', async ({ expect }) => { const mockComponent = mountComponentWithQuery(TestComponent, { visibleMetrics: ['POPDENS', 'PTASNL', 'P_SQM'], visibleCategories: ['Environment'] }); expect(mockComponent.vm.getToggleCategoryRoute('Housing').query).toEqual( { visibleCategories: ['Environment', 'Housing'], visibleMetrics: ['POPDENS', 'PTASNL', 'P_SQM'],} ); }); it('clears the querystring if now everything is visible', async ({ expect }) => { const allCategoriesButOne = config.categories.filter(c => c === 'Crime'); const mockComponent = mountComponentWithQuery(TestComponent, { visibleCategories: [...allCategoriesButOne], }); expect(mockComponent.vm.getToggleCategoryRoute('Crime').query).toEqual({ visibleCategories: [] } ); }); }); describe('getToggleMetricRoute', () => { it('adds/removes a single visible metric', async ({ expect }) => { const mockComponent = mountComponentWithQuery(TestComponent, { visibleMetrics: ['POPDENS', 'PTASNL', 'P_SQM'], visibleCategories: ['Environment'] }); expect(mockComponent.vm.getToggleMetricRoute('POPDENS').query).toEqual( { visibleCategories: ['Environment'], visibleMetrics: ['PTASNL', 'P_SQM'],} ); expect(mockComponent.vm.getToggleMetricRoute('PROXPH').query).toEqual( { visibleCategories: ['Environment'], visibleMetrics: ['POPDENS', 'PTASNL', 'P_SQM', 'PROXPH'],} ); }); it('fully enables a category if this is the last metric in the category', async ({ expect }) => { // TODO: This test will need to be updated if more metrics get added to crime cat. const mockComponent = mountComponentWithQuery(TestComponent, { visibleMetrics: ['D_SQM', 'P_SQM', 'PTASNL'], visibleCategories: ['Environment'] }); expect(mockComponent.vm.getToggleMetricRoute('V_SQM').query).toEqual( { visibleCategories: ['Environment', 'Crime'], visibleMetrics: ['PTASNL'],} ); }) it('removes a category from visibility if this is toggling off a single metric in that category', async ({ expect }) => { const mockComponent = mountComponentWithQuery(TestComponent, { visibleMetrics: ['PTASNL'], visibleCategories: ['Environment', 'Crime'] }); expect(mockComponent.vm.getToggleMetricRoute('V_SQM').query).toEqual( { visibleCategories: ['Environment'], visibleMetrics: ['PTASNL', 'D_SQM', 'P_SQM'],} ); }) it('clears the query parameter if this is the last invisible metric', async ({ expect }) => { const mockComponent = mountComponentWithQuery(TestComponent, { visibleMetrics: ['PTASNL'], }); expect(mockComponent.vm.getToggleMetricRoute('PTASNL').query).toEqual( { visibleMetrics: [],} ); }) });
$.ajaxPrefilter(function(ops){ ops.url = 'http://api-breakingnews-web.itheima.net'+ops.url; if(ops.url.indexOf('/my') !== -1){ ops.headers = { Authorization: localStorage.getItem('token') || '' } } ops.complete = function(res) { if(res.responseJSON.status === 1 && res.responseJSON.message === "身份认证失败!" ){ localStorage.removeItem('token') location.href = '/login.html' } } })
import React, {Component} from "react"; class Child extends Component{ constructor(props) { super(props); console.log("Demo3.Child: execute constructor"); this.state = { msg: 'this is child component.' }; } static getDerivedStateFromProps(props, state){ console.log("Demo3.Child: execute getDerivedStateFromProps"); return state; } componentWillUnmount() { console.log("Demo3.Child: execute componentWillUnmount"); } componentDidMount() { console.log("Demo3.Child: execute componentDidMount"); } render() { console.log("Demo3.Child: execute render"); return ( <div> <h3>{this.state.msg}</h3> </div> ); } } export default Child;
/** * @license * Copyright 2014 David Wolverton * Available under MIT license <https://raw.githubusercontent.com/dwolverton/my/master/LICENSE.txt> */ define([ "exports" ], function (exports) { /** * Returns the whole number beginning of the hour. For example, 11.5 would return 11. * @param {number} time * @returns {number} */ exports.beginningOfHour = function(time) { return Math.floor(time); }; /** * Returns a whole number percentage of the time within the hour. For example, 11.5 would * return 50. * @param {number} time * @returns {number} */ exports.percentageOfHour = function(time) { var percentage = time - Math.floor(time); return Math.round(percentage * 100); }; exports.roundToFifteenMinutes = function(time) { return Math.round(time * 4) / 4; }; exports.roundToFiveMinutes = function(time) { return Math.round(time * 12) / 12; }; /** * Convert the given JavaScript Date object to a date string as used to store dates in this * application (that is "yyyy-mm-dd"). * @param {Date} date * @returns {string} */ exports.convertDateObjectToDateString = function(date) { var year = date.getFullYear(), month = (date.getMonth() + 1), day = date.getDate(); if (month < 10) { month = "0" + month; } if (day < 10) { day = "0" + day; } return year + "-" + month + "-" + day; }; exports.convertDateStringToDateObject = function(dateString) { if (!dateString) { return null; } var parts = dateString.split('-'); var MIDDLE_OF_DAY = 12; return new Date(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2]), MIDDLE_OF_DAY); }; /** * Get the current date in the standard format for this application. * @returns {string} */ exports.getCurrentDate = function() { return exports.convertDateObjectToDateString(new Date()); }; exports.numberToStringWithNth = function(number) { var lastDigit = number % 10; if (number > 10 && number < 20) { return number + 'th'; } else if (lastDigit === 1) { return number + 'st'; } else if (lastDigit === 2) { return number + 'nd'; } else if (lastDigit === 3) { return number + 'rd'; } else { return number + 'th'; } }; /** * @param month {number} January = 0 * @returns {string} */ exports.monthToThreeDigitString = function(month) { switch (month) { case 0: return 'Jan' } }; });
import { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Auth } from "aws-amplify"; import { loggedInSet } from '../redux/actions'; class Logout extends Component { async componentDidMount() { await Auth.signOut(); const { loggedInSet } = this.props; loggedInSet(false); this.props.history.push('/'); } render() { return null; } } Logout.propTypes = { loggedInSet: PropTypes.func.isRequired, }; export default connect(null, { loggedInSet })(Logout);
import StateManager from "./States/StateManager"; import ControlManager from 'Controlers/ControlManager'; /** * Root game class */ export default class Game { constructor(app) { this.app = app; this.stateManager = new StateManager(this); this.controlManager = new ControlManager(); } /** * Initializing game states in game manager * Changing current game state to menu */ start() { this.stateManager.init(); this.stateManager.changeCurrentStateTo('menu'); } }
import ConChartPie from './src/ConChartPie' /* istanbul ignore next */ ConChartPie.install = function(Vue) { Vue.component(ConChartPie.name, ConChartPie); }; export default ConChartPie;
(function () { 'use strict'; angular .module('user') .factory('userFactory', ['$http', 'persistenceFactory', '$window', '$httpParamSerializer', userFactory]); function userFactory($http, persistence, $window, $httpParamSerializer) { function getUser() { var promise = $http.get('/user/me'); promise.success(function (data) { persistence.set('user', data); }); return promise; } function login() { var host = 'https://login.eveonline.com/oauth/authorize?'; var cb = 'http://localhost:8082/#/crest/callback'; var params = { 'response_type': 'code', 'redirect_uri': cb, 'client_id': '11d77446d3054979aaf51054b467ea67', 'scope': 'characterLocationRead characterNavigationWrite publicData characterContactsRead' }; $window.location.href = host + $httpParamSerializer(params); } function logout() { var promise = $http.post('/user/logout') promise.success(function () { persistence.set('user', {}); }); return promise; } function getLocation() { var promise = $http.get('/user/location'); promise.success(function (data) { persistence.set('user', data); }); return promise; } return { getUser: getUser, getLocation: getLocation, login: login, logout: logout }; } })();
/** * @file Score Class * @author yunxiange@gmail.com * @date 2017-09-05 */ (function () { function Score(options) { // } var ScoreProto = Score.prototype; ScoreProto.create = function () { // }; ScoreProto.init = function () { // }; ScoreProto.update = function () { // }; window.Score = Score; })();
var Util = require('../util'), Base = require('../base'); var transform = Util.prefixStyle("transform"); var transition = Util.prefixStyle("transition"); /** * An infinity dom-recycled list plugin for xscroll. * @constructor * @param {object} cfg * @param {string} cfg.zoomType choose scroll vertically or horizontally * @param {string} cfg.transition recomposition cell with a transition * @param {string} cfg.infiniteElements dom-selector for reused elements * @param {function} cfg.renderHook render function for cell by per col or per row duration scrolling * @extends {Base} */ var Infinite = function(cfg) { Infinite.superclass.constructor.call(this, cfg); this.userConfig = Util.mix({ zoomType: "y", transition: 'all 0.5s ease' }, cfg); } Util.extend(Infinite, Base, { /** * a pluginId * @memberOf Infinite * @type {string} */ pluginId: "infinite", /** * store the visible elements inside of view. * @memberOf Infinite * @type {object} */ visibleElements: {}, /** * store all elements data. * @memberOf Infinite * @type {object} */ sections:{}, /** * plugin initializer * @memberOf Infinite * @override Base * @return {Infinite} */ pluginInitializer: function(xscroll) { var self = this; self.xscroll = xscroll; self.isY = !!(self.userConfig.zoomType == "y"); self._nameTop = self.isY ? "_top" : "_left"; self._nameHeight = self.isY ? "_height" : "_width"; self.nameTop = self.isY ? "top" : "left"; self.nameHeight = self.isY ? "height" : "width"; self.nameWidth = self.isY ? "width" : "height"; self.nameY = self.isY ? "y" : "x"; self.nameTranslate = self.isY ? "translateY" : "translateX"; self.nameContainerHeight = self.isY ? "containerHeight" : "containerWidth"; self.nameScrollTop = self.isY ? "scrollTop" : "scrollLeft"; self._initInfinite(); xscroll.on("afterrender", function() { self.render(); self._bindEvt(); }); return self; }, /** * detroy the plugin * @memberOf Infinite * @override Base * @return {Infinite} */ pluginDestructor: function() { var self = this; for (var i = 0; i < self.infiniteLength; i++) { self.infiniteElements[i].style[self.nameTop] = "auto"; self.infiniteElements[i].style[transform] = "none"; } self.xscroll && self.xscroll.off("scroll", self._updateByScroll, self); self.xscroll && self.xscroll.off("tap panstart pan panend", self._cellEventsHandler, self); self._destroySticky(); return self; }, _initInfinite: function() { var self = this; var xscroll = self.xscroll; self.sections = {}; self.infiniteElements = xscroll.renderTo.querySelectorAll(self.userConfig.infiniteElements); self.infiniteLength = self.infiniteElements.length; self.infiniteElementsCache = (function() { var tmp = [] for (var i = 0; i < self.infiniteLength; i++) { tmp.push({}); self.infiniteElements[i].style.position = "absolute"; self.infiniteElements[i].style[self.nameTop] = 0; self.infiniteElements[i].style.visibility = "hidden"; self.infiniteElements[i].style.display = "block"; Util.addClass(self.infiniteElements[i], "_xs_infinite_elements_"); } return tmp; })(); self.elementsPos = {}; xscroll.on("scroll", self._updateByScroll, self); return self; }, _initSticky: function() { var self = this; self.stickyDomInfo = []; if (!self.hasSticky) { return; } //create sticky element if (!self._isStickyRendered) { var sticky = document.createElement("div"); sticky.style.position = "fixed"; sticky.style.left = 0; sticky.style.top = 0; sticky.style.display = "none"; Util.addClass(sticky, "_xs_infinite_elements_"); self.xscroll.renderTo.appendChild(sticky); self.stickyElement = sticky; self._isStickyRendered = true; } for (var i in self.__serializedData) { var sticky = self.__serializedData[i]; if (sticky && sticky.style && "sticky" == sticky.style.position) { self.stickyDomInfo.push(sticky); } } return self; }, _destroySticky: function() { var self = this; self.hasSticky = false; self.stickyElement && self.stickyElement.remove(); self._isStickyRendered = false; return self; }, _renderUnRecycledEl: function() { var self = this; var translateZ = self.userConfig.gpuAcceleration ? " translateZ(0) " : ""; for (var i in self.__serializedData) { var unrecycledEl = self.__serializedData[i]; if (self.__serializedData[i]['recycled'] === false) { var el = unrecycledEl.id && document.getElementById(unrecycledEl.id.replace("#", "")) || document.createElement("div"); var randomId = Util.guid("xs-row-"); el.id = unrecycledEl.id || randomId; unrecycledEl.id = el.id; self.xscroll.content.appendChild(el); for (var attrName in unrecycledEl.style) { if (attrName != self.nameHeight && attrName != "display" && attrName != "position") { el.style[attrName] = unrecycledEl.style[attrName]; } } el.style[self.nameTop] = 0; el.style.position = "absolute"; el.style.display = "block"; el.style[self.nameHeight] = unrecycledEl[self._nameHeight] + "px"; el.style[transform] = self.nameTranslate + "(" + unrecycledEl[self._nameTop] + "px) " + translateZ; Util.addClass(el, unrecycledEl.className); self.userConfig.renderHook.call(self, el, unrecycledEl); } } }, /** * render or update the scroll contents * @memberOf Infinite * @return {Infinite} */ render: function() { var self = this; var xscroll = self.xscroll; var offset = self.isY ? xscroll.getScrollTop() : xscroll.getScrollLeft(); self.visibleElements = self.getVisibleElements(offset); self.__serializedData = self._computeDomPositions(); self._initSticky(); var size = xscroll[self.nameHeight]; var containerSize = self._containerSize; if (containerSize < size) { containerSize = size; } xscroll[self.nameContainerHeight] = containerSize; xscroll.container.style[self.nameHeight] = containerSize + "px"; xscroll.content.style[self.nameHeight] = containerSize + "px"; self.curStickyIndex = undefined; self._renderUnRecycledEl(); self._updateByScroll(); self._updateByRender(offset); self.xscroll.boundryCheck(); return self; }, _getChangedRows: function(newElementsPos) { var self = this; var changedRows = {}; for (var i in self.elementsPos) { if (!newElementsPos.hasOwnProperty(i)) { changedRows[i] = "delete"; } } for (var i in newElementsPos) { if (newElementsPos[i].recycled && !self.elementsPos.hasOwnProperty(i)) { changedRows[i] = "add"; } } self.elementsPos = newElementsPos; return changedRows; }, _updateByScroll: function(e) { var self = this; var xscroll = self.xscroll; var _pos = e && e[self.nameScrollTop]; var pos = _pos === undefined ? (self.isY ? xscroll.getScrollTop() : xscroll.getScrollLeft()) : _pos; var elementsPos = self.getVisibleElements(pos); var changedRows = self._getChangedRows(elementsPos); for (var i in changedRows) { if (changedRows[i] == "delete") { self._pushEl(i); } if (changedRows[i] == "add") { var elObj = self._popEl(elementsPos[i][self.guid]); var index = elObj.index; var el = elObj.el; if (el) { self.infiniteElementsCache[index].guid = elementsPos[i].guid; self.__serializedData[elementsPos[i].guid].__infiniteIndex = index; self._renderData(el, elementsPos[i]); self._renderStyle(el, elementsPos[i]); } } } self._stickyHandler(pos); return self; }, _updateByRender: function(pos) { var self = this; var xscroll = self.xscroll; var pos = pos === undefined ? (self.isY ? xscroll.getScrollTop() : xscroll.getScrollLeft()) : pos; var prevElementsPos = self.visibleElements; var newElementsPos = self.getVisibleElements(pos); var prevEl, newEl; //repaint for (var i in newElementsPos) { newEl = newElementsPos[i]; for (var j in prevElementsPos) { prevEl = prevElementsPos[j]; if (prevEl.guid === newEl.guid) { if (newEl.style != prevEl.style || newEl[self._nameTop] != prevEl[self._nameTop] || newEl[self._nameHeight] != prevEl[self._nameHeight]) { // console.log( "data:", JSON.stringify(newEl.data),prevEl[self._nameTop], '->', newEl[self._nameTop]) self._renderStyle(self.infiniteElements[newEl.__infiniteIndex], newEl, true); } if (JSON.stringify(newEl.data) != JSON.stringify(prevEl.data)) { self._renderData(self.infiniteElements[newEl.__infiniteIndex], newEl); } } else { // paint if (self.__serializedData[newEl.guid].recycled && self.__serializedData[newEl.guid].__infiniteIndex === undefined) { var elObj = self._popEl(); self.__serializedData[newEl.guid].__infiniteIndex = elObj.index; self._renderData(elObj.el, newEl); self._renderStyle(elObj.el, newEl); } } } } self.visibleElements = newElementsPos; }, _stickyHandler: function(_pos) { var self = this; _pos = undefined === _pos ? (self.isY ? self.xscroll.getScrollTop() : self.xscroll.getScrollLeft()) : _pos; var pos = Math.abs(_pos); var index = []; var allTops = []; for (var i = 0; i < self.stickyDomInfo.length; i++) { allTops.push(self.stickyDomInfo[i][self._nameTop]); if (pos >= self.stickyDomInfo[i][self._nameTop]) { index.push(i); } } if (!index.length) { if (self.stickyElement) { self.stickyElement.style.display = "none"; } self.curStickyIndex = undefined; return; } var curStickyIndex = Math.max.apply(null, index); if (self.curStickyIndex !== curStickyIndex) { self.curStickyIndex = curStickyIndex; self.userConfig.renderHook.call(self, self.stickyElement, self.stickyDomInfo[self.curStickyIndex]); self.stickyElement.style.display = "block"; self.stickyElement.style[self.nameWidth] = "100%"; self.stickyElement.style[self.nameHeight] = self.stickyDomInfo[self.curStickyIndex].style[self.nameHeight] + "px"; self.stickyElement.setAttribute("xs-guid", self.stickyDomInfo[self.curStickyIndex].guid); Util.addClass(self.stickyElement, self.stickyDomInfo[self.curStickyIndex].className); for (var attrName in self.stickyDomInfo[self.curStickyIndex].style) { if (attrName != self.nameHeight && attrName != "display" && attrName != "position") { self.stickyElement.style[attrName] = self.stickyDomInfo[self.curStickyIndex].style[attrName]; } } } var trans = 0; if (self.stickyDomInfo[self.curStickyIndex + 1]) { var cur = self.stickyDomInfo[self.curStickyIndex]; var next = self.stickyDomInfo[self.curStickyIndex + 1]; if (_pos + cur[self._nameHeight] > next[self._nameTop] && _pos + cur[self._nameHeight] < next[self._nameTop] + cur[self._nameHeight]) { trans = cur[self._nameHeight] + pos - next[self._nameTop]; } else { trans = 0; } } self.stickyElement.style[transform] = self.isY ? "translateY(-" + (trans) + "px) translateZ(0)" : "translateX(-" + (trans) + "px) translateZ(0)"; //top if (_pos < Math.min.apply(null, allTops)) { self.stickyElement.style.display = "none"; self.curStickyIndex = undefined; return; } }, /** * get all element posInfo such as top,height,template,html * @return {Array} **/ _computeDomPositions: function() { var self = this; var pos = 0, size = 0, sections = self.sections, section; self.hasSticky = false; var data = []; var serializedData = {}; for (var i in sections) { for (var j = 0, len = sections[i].length; j < len; j++) { section = sections[i][j]; section.sectionId = i; section.index = j; data.push(section); } } //f = v/itemSize*1000 < 60 => v = 0.06 * itemSize self.userConfig.maxSpeed = 0.06 * 50; for (var i = 0, l = data.length; i < l; i++) { var item = data[i]; size = item.style && item.style[self.nameHeight] >= 0 ? item.style[self.nameHeight] : 100; item.guid = item.guid || Util.guid(); item[self._nameTop] = pos; item[self._nameHeight] = size; item.recycled = item.recycled === false ? false : true; pos += size; if (!self.hasSticky && item.style && item.style.position == "sticky") { self.hasSticky = true; } serializedData[item.guid] = item; } self._containerSize = pos; return serializedData; }, /** * get all elements inside of the view. * @memberOf Infinite * @param {number} pos scrollLeft or scrollTop * @return {object} visibleElements */ getVisibleElements: function(pos) { var self = this; var xscroll = self.xscroll; var pos = pos === undefined ? (self.isY ? xscroll.getScrollTop() : xscroll.getScrollLeft()) : pos; var threshold = self.userConfig.threshold >= 0 ? self.userConfig.threshold : xscroll[self.nameHeight] / 3; var tmp = {}, item; var data = self.__serializedData; for (var i in data) { item = data[i]; if (item[self._nameTop] >= pos - threshold && item[self._nameTop] <= pos + xscroll[self.nameHeight] + threshold) { tmp[item.guid] = item; } } return JSON.parse(JSON.stringify(tmp)); }, _popEl: function() { var self = this; for (var i = 0; i < self.infiniteLength; i++) { if (!self.infiniteElementsCache[i]._visible) { self.infiniteElementsCache[i]._visible = true; return { index: i, el: self.infiniteElements[i] } } } }, _pushEl: function(guid) { var self = this; for (var i = 0; i < self.infiniteLength; i++) { if (self.infiniteElementsCache[i].guid == guid) { self.infiniteElementsCache[i]._visible = false; self.infiniteElements[i].style.visibility = "hidden"; delete self.infiniteElementsCache[i].guid; } } }, _renderData: function(el, elementObj) { var self = this; if (!el) return; self.userConfig.renderHook.call(self, el, elementObj); }, _renderStyle: function(el, elementObj, useTransition) { var self = this; if (!el) return; var translateZ = self.xscroll.userConfig.gpuAcceleration ? " translateZ(0) " : ""; //update style for (var attrName in elementObj.style) { if (attrName != self.nameHeight && attrName != "display" && attrName != "position") { el.style[attrName] = elementObj.style[attrName]; } } el.setAttribute("xs-index", elementObj.index); el.setAttribute("xs-sectionid", elementObj.sectionId); el.setAttribute("xs-guid", elementObj.guid); el.style.visibility = "visible"; el.style[self.nameHeight] = elementObj[self._nameHeight] + "px"; el.style[transform] = self.nameTranslate + "(" + elementObj[self._nameTop] + "px) " + translateZ; el.style[transition] = useTransition ? self.userConfig.transition : "none"; }, getCell: function(e) { var self = this, cell; var el = Util.findParentEl(e.target, "._xs_infinite_elements_", self.xscroll.renderTo); var guid = el.getAttribute("xs-guid"); if (undefined === guid) return; return self.__serializedData[guid]; }, _bindEvt: function() { var self = this; if (self._isEvtBinded) return; self._isEvtBinded = true; self.xscroll.renderTo.addEventListener("webkitTransitionEnd", function(e) { if (e.target.className.match(/xs-row/)) { e.target.style.webkitTransition = ""; } }); self.xscroll.on("tap panstart pan panend", self._cellEventsHandler, self); return self; }, _cellEventsHandler: function(e) { var self = this; e.cell = self.getCell(e); e.cell && self[e.type].call(self, e); }, /** * tap event * @memberOf Infinite * @param {object} e events data include cell object * @event */ tap: function(e) { this.trigger("tap", e); return this; }, /** * panstart event * @memberOf Infinite * @param {object} e events data include cell object * @event */ panstart: function(e) { this.trigger("panstart", e); return this; }, /** * pan event * @memberOf Infinite * @param {object} e events data include cell object * @event */ pan: function(e) { this.trigger("pan", e); return this; }, /** * panend event * @memberOf Infinite * @param {object} e events data include cell object * @event */ panend: function(e) { this.trigger("panend", e); return this; }, /** * insert data before a position * @memberOf Infinite * @param {string} sectionId sectionId of the target cell * @param {number} index index of the target cell * @param {object} data data to insert * @return {Infinite} */ insertBefore: function(sectionId, index, data) { var self = this; if (sectionId === undefined || index === undefined || data === undefined) return self; if (!self.sections[sectionId]) { self.sections[sectionId] = []; } self.sections[sectionId].splice(index, 0, data); return self; }, /** * insert data after a position * @memberOf Infinite * @param {string} sectionId sectionId of the target cell * @param {number} index index of the target cell * @param {object} data data to insert * @return {Infinite} */ insertAfter: function(sectionId, index, data) { var self = this; if (sectionId === undefined || index === undefined || data === undefined) return self; if (!self.sections[sectionId]) { self.sections[sectionId] = []; } self.sections[sectionId].splice(Number(index) + 1, 0, data); return self; }, /** * append data after a section * @memberOf Infinite * @param {string} sectionId sectionId for the append cell * @param {object} data data to append * @return {Infinite} */ append: function(sectionId, data) { var self = this; if (!self.sections[sectionId]) { self.sections[sectionId] = []; } self.sections[sectionId] = self.sections[sectionId].concat(data); return self; }, /** * remove some data by sectionId,from,number * @memberOf Infinite * @param {string} sectionId sectionId for the append cell * @param {number} from removed index from * @param {number} number removed data number * @return {Infinite} */ remove: function(sectionId, from, number) { var self = this; var number = number || 1; if (undefined === sectionId || !self.sections[sectionId]) return self; //remove a section if (undefined === from) { delete self.sections[sectionId]; return self; } //remove some data in section if (self.sections[sectionId] && self.sections[sectionId][from]) { self.sections[sectionId].splice(from, number); return self; } return self; }, /** * replace some data by sectionId and index * @memberOf Infinite * @param {string} sectionId sectionId to replace * @param {number} index removed index from * @param {object} data new data to replace * @return {Infinite} */ replace: function(sectionId, index, data) { var self = this; if (undefined === sectionId || !self.sections[sectionId]) return self; self.sections[sectionId][index] = data; return self; }, /** * get data by sectionId and index * @memberOf Infinite * @param {string} sectionId sectionId * @param {number} index index in the section * @return {object} data data */ get: function(sectionId, index) { if (undefined === sectionId) return; if (undefined === index) return this.sections[sectionId]; return this.sections[sectionId][index]; } }); if (typeof module == 'object' && module.exports) { module.exports = Infinite; } else if (window.XScroll && window.XScroll.Plugins) { return XScroll.Plugins.Infinite = Infinite; }
import React from "react"; import "../../src/index.css"; const Month = (props) => { const { month, usersData } = props; const monthId = month.title; let listItems = 0; if (usersData !== "Wait..") { listItems = usersData.map((oneUserDate) => { return <li>{`${oneUserDate.firstName} ${oneUserDate.lastName}`}</li>; }); } return ( <div className="card month" id={monthId}> <img className="card-img-top" src={month.src} alt={month.title} /> <div class="birthdayList">{listItems !== 0 && <ul>{listItems}</ul>}</div> </div> ); }; export default Month;
const {Router} = require('express') const router = Router() const { createAuthor, loginauthor, getAuthorByBook, getAuthorById, UpdateAuthor, deleteAuthor } = require('../controllers/authorController') //route for creating and account router.post('/api/author',createAuthor) //route for login router.post('/api/loginUser',loginauthor) //route for updating an account details router.put('/api/update',UpdateAuthor) router.get('/api/author/:authorId',getAuthorById) router.get('/api/author/:authorId/books',getAuthorByBook) router.get('/api/author/delete',deleteAuthor) module.exports = router
(function(window, _, angular, undefined) { 'use strict'; /** * @name OnhanhDashboard * @description DashboardModule */ var dashboardModule = angular.module('app.dashboard', []); 'use strict'; /** * @name OnhanhDashboard * @description ... */ dashboardModule .config(['$stateProvider', function($stateProvider) { // Use $stateProvider to configure your states. $stateProvider ////////// // Home // ////////// .state("home", { title: "Dashboard", // Use a url of "/" to set a states as the "index". url: "/", // Example of an inline template string. By default, templates // will populate the ui-view within the parent state's template. // For top level states, like this one, the parent template is // the index.html file. So this template will be inserted into the // ui-view within index.html. controller: 'dashboardController', templateUrl: '/web/dashboard/dashboard.html' }); } ]); 'use strict'; /** * @name OnhanhDashboard * @description ... */ dashboardModule .controller('dashboardController', ['$location', '$scope', '$rootScope', function($location, $scope, $rootScope) { // Views (function() { var Views = {} Views.labels = []; for(var i = 0; i < 12; i++) { Views.labels.push(i+':00'); } Views.series = ['Views']; Views.data = [[]]; for(var i = 0; i < 12; i++) { Views.data[0].push(i); } Views.onClick = function (points, evt) { console.log(points, evt); }; $scope.views = Views; })($scope); } ]); 'use strict'; /** * @name OnhanhDashboard * @description ... */ dashboardModule .service('dashboardService',["$http", "Environment", function($http, Environment) { return { getRole: function() { var url = Environment.settings.api + '/role'; return $http.get(url); } } } ]); })(window, _, window.angular);
/* $(function () { var row = document.getElementsByClassName("afTableRow"); if (row.length === 0){ document.getElementById("afWidgetContainer").hidden = true; adsElement = document.getElementById("infoJobs") adsElement.innerText = ""; if (document.documentElement.lang == "en") { adsElement.innerText = "Unfortunately, there are no vacancies at the moment"; }else{ adsElement.innerText = "Tyvärr finns det inga lediga tjänster för tillfället"; } } }) */
/* jshint node: true */ module.exports = function (grunt) { "use strict"; grunt.loadNpmTasks('grunt-contrib-jasmine') grunt.initConfig({ pkg: grunt.file.readJSON('package.json') , jasmine: { src: "src/jquery.ga-event-track.*.js" , options: { specs: "spec/*.js" , vendor: "spec/javascripts/vendor/*.js" } } }) grunt.registerTask('test', ['jasmine']) grunt.registerTask('default', ['test']) };
var mongo_client = require('mongodb').MongoClient; var _ = require('underscore'); var config = require('./db_configuration'); var db; function db_operate(which_callback) { connecting_string = 'mongodb://' + config.host +':'+ config.port +'/'+ config.db_name; mongo_client.connect( connecting_string, function(err, db) { if (!err) { db.collection( 'cities', function( err, collection ) { collection.find().toArray( function( err, items ) { which_callback( items ); }); }); } }); }; exports.operate = function(input) { db_operate( input ); }; exports.sanity = function() { return true; }; exports.index = function(input_hash) { return []; }; exports.show = function(input_hash) { return []; };
function sayHello() { console.log("Hello"); } sayHello(); var sayBye = function() { console.log("Bye"); } sayBye(); function multiply(a, b) { return a * b; } alert(multiply(10, 3));
import LikeBtn from "./LikeBtn"; import CommentBtn from "./CommentBtn"; import RepostBtn from "./RepostBtn"; import {DivFlxItmCnt} from "../../../../layout/layout"; const FooterLeftSideBar = props => { const {likes, comments, reposts} = props return <DivFlxItmCnt> <LikeBtn value={likes} /> <CommentBtn value={comments} /> <RepostBtn value={reposts}/> </DivFlxItmCnt> } export default FooterLeftSideBar
angular.module('urlService', []) .factory('Url', function ($http,$location) { var urlFactory = {}; urlFactory.all = function () { return $http.get('/api/url'); }; urlFactory.create = function (url) { return $http.post('/api/url', url); }; urlFactory.update = function (id) { return $http.put('/api/url' + id); }; urlFactory.delete = function (id) { return $http.delete('/api/url' + id); } return urlFactory; }) .factory('isShortUrl',function($http){ var shortFactory = {}; shortFactory.urlCheck = function(i){ return $http.get('/api/url' + i); }; return shortFactory; })