text
stringlengths
7
3.69M
/*import React from 'react'; import Layout from '../components/Layout'; import PageFooter from '../components/PageFooter'; import SideBar from '../components/Sidebar/index' import Rgallery from '../components/Rgallery' import Shoptop from '../assets/images/sdcoast-1920x1438.jpg' import { Link } from 'gatsby' import { graphql } from "gatsby" import styled from "styled-components" import ItemThumbnail from '../components/ItemThumbnail/ItemThumbnail'; const ThumbnailsWrapper = styled.div` width: 100%; display: flex; align-items: flex-start; justify-content: center; flex-wrap: wrap; padding: 20px; ` const sections = [ { id: 'shoptop', name: 'Featured', icon: 'fa-home' }, { id: 'mygallery', name: 'Gallery', icon: 'fa-th' }, { id: 'about', name: 'About Me', icon: 'fa-user' }, { id: 'contact', name: 'Contact', icon: 'fa-envelope' }, ]; class Shop extends React.Component { render() { const { data } = this.props const siteTitle = data.site.siteMetadata.title const products = data.allMarkdownRemark.edges return ( <Layout location={this.props.location} title={siteTitle}> <SideBar /*sections={sections}* / /> <div id="main"> <section id="shoptop"> <div className="container"> <ThumbnailsWrapper> {products.map(({ node }) => { const { title, image, price } = node.frontmatter return ( <ItemThumbnail key={node.fields.slug} link={node.fields.slug} heading={title} image={image.childImageSharp.fluid} price={price} /> ) })} </ThumbnailsWrapper> <div> {/*} <img src={Shoptop} />* /} </div> </div> </section> {/*<section id="mygallery" className="mygallery"> <div className="container"> <Rgallery id="rgallery"/> </div> </section>* /} </div> </Layout> ) } } export default Shop export const pageQuery = graphql` query { site { siteMetadata { title } } allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) { edges { node { excerpt fields { slug } frontmatter { title price image { childImageSharp { fluid(maxWidth: 800) { ...GatsbyImageSharpFluid } } } } } } } } ` */
import Perkeep from './perkeep.js'; export default function (config) { return new Perkeep(config); }
import InfoBlock from "./InfoBlock.js"; import InfoImage from "./InfoImage.js"; import InfoDetails from "./InfoDetails.js"; export default function AssetData({ data }) { const { id, hostName, ip, riskScore, history } = data; return ( <InfoBlock> <InfoImage src="/windows-96.png" alt="Drawing of an old computer screen displaying the text 'Windows 96'." /> <InfoDetails> <div> <span className="subtitle">HOSTNAME</span> <h2>{hostName}</h2> <code> <b>Asset ID: </b> {id} </code> <code> <b>Local IP: </b> {ip} </code> <code> <b>Risk score:</b> {riskScore.toFixed(2)} 😢 </code> <code> <b>Number of scans: </b> {history.length} </code> </div> </InfoDetails> </InfoBlock> ); }
"use strict" var Role = function () { this.ID; this.MasterRoleID; this.Name; this.Description; this.Overhead; this.UserID; this.isActive; this.OrganizationID; // Declare a function to load the current Organization data set // this.load = loadRoleData; // function loadRoleData(ID, targetUrl, callback) { // $.when($.getJSON(targetUrl)).then(function (data, textStatus, jqXHR) { callback(data); }); // } }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import './FiltersBar.sass'; import { FilterCheckbox, FilterRadiobutton } from '../index'; class FiltersBar extends Component { constructor(props) { super(props); this.state = { isVisible: true }; } componentDidMount() { this.setVisibilityDependingOnScreenSize(); } setVisibilityDependingOnScreenSize = e => { const screenSize = window.screen.availWidth; if (screenSize <= 768) { this.setState({ isVisible: false }); } else { this.setState({ isVisible: true }); } } handleVisibilityChange = () => { const { isVisible }= this.state; this.setState({ isVisible: !isVisible }); } render() { const { handleCurrencyChange, handleStopsChange, selectOnlyOneStop, selectAllStops, stops, currentCurrency } = this.props; const { isVisible } = this.state; const showAll = Object.values(stops).every(value => value); return ( <div className="filters" > <form className={`filters-form${isVisible ? ' active' : ''}`} > <div className="currency-select"> <h3 className="filter-title">валюта</h3> <div className="currency-list"> <FilterRadiobutton checked={currentCurrency === 'RUB'} handleChange={handleCurrencyChange} value="RUB" /> <FilterRadiobutton checked={currentCurrency === 'USD'} handleChange={handleCurrencyChange} value="USD" /> <FilterRadiobutton checked={currentCurrency === 'EUR'} handleChange={handleCurrencyChange} value="EUR" /> </div> </div> <div className="stops-select"> <h3 className="filter-title">Количество пересадок</h3> <FilterCheckbox text="Все" handleChange={selectAllStops} checked={showAll} hasBtn={false} /> <FilterCheckbox text="0 пересадок" handleChange={handleStopsChange} handleBtnClick={selectOnlyOneStop} value="0" checked={stops[0]} /> <FilterCheckbox text="1 пересадка" handleChange={handleStopsChange} handleBtnClick={selectOnlyOneStop} value="1" checked={stops[1]} /> <FilterCheckbox text="2 пересадки" handleChange={handleStopsChange} handleBtnClick={selectOnlyOneStop} value="2" checked={stops[2]} /> <FilterCheckbox text="3 пересадки" handleChange={handleStopsChange} handleBtnClick={selectOnlyOneStop} value="3" checked={stops[3]} /> </div> </form> <button className="open-filter" type="button" onClick={this.handleVisibilityChange} > {isVisible ? 'Свернуть' : 'Фильтровать'} </button> </div> ); } } FiltersBar.propTypes = { handleCurrencyChange: PropTypes.func.isRequired, handleStopsChange: PropTypes.func.isRequired, selectOnlyOneStop: PropTypes.func.isRequired, selectAllStops: PropTypes.func.isRequired, stops: PropTypes.object.isRequired, currentCurrency: PropTypes.string.isRequired }; export default FiltersBar;
/** * Created by Administrator on 2016/8/12 0012. */ //第一次搞面向对象的,想用一个类似接口的东西下次可以直接用 function SlideObj(obj){ this.obj = obj; this.obj.on("touchstart",onTouchStart); this.obj.on("touchmove",onTouchMove); this.obj.on("touchend",onTouchEnd); this.obj.slideToUp = function(){}; this.obj.slideToDown = function(){}; this.obj.slideToLeft = function(){}; this.obj.slideToRight = function(){}; this.obj.slideEnd = function(){}; this.obj.changeX = 0; this.obj.changeY = 0; var startX; var startY; var endX; var endY; var dir; function onTouchStart(e){ e.preventDefault(); dir = 'N'; var touchP = e.originalEvent.targetTouches[0]; startX = touchP.clientX; startY = touchP.clientY; } function onTouchMove(e){ e.preventDefault(); var touchP = e.originalEvent.targetTouches[0]; endX = touchP.clientX; endY = touchP.clientY; getChangeXY(); if (dir == 'N'){ dir = getDir(); } switch (dir){ case 'U':obj.slideToUp();break; case 'D':obj.slideToDown();break; case 'L':obj.slideToLeft();break; case 'R':obj.slideToRight();break; } } function onTouchEnd(e){ e.preventDefault(); dir = 'N'; obj.changeX = 0; obj.changeY = 0; obj.slideEnd(); } function getChangeXY(){ obj.changeX = parseInt(endX - startX); obj.changeY = parseInt(endY - startY); } function getDir(){ if(Math.abs(obj.changeX) > Math.abs(obj.changeY)){ //以水平为主 if(obj.changeX > 20) return 'R'; else if(obj.changeX < -20) return 'L'; else return 'N'; }else if(Math.abs(obj.changeX) < Math.abs(obj.changeY)){ //以垂直为主 if(obj.changeY > 20) return 'D'; else if(obj.changeY < -20) return 'U'; else return 'N'; }else{ return 'N'; } } }
$(document).ready(function () { $("#namef").keyup(function(e) { var regex = /^[a-zA-Z ğüşıöçĞÜŞİÖÇ]*$/; if (regex.test(this.value) !== true) date_msg("Dikkat!", "Ad Alanına alfabetik Karakter Giriniz") this.value = this.value.replace(/[^a-zA-Z ğüşıöçĞÜŞİÖÇ]+/, ''); }); $("#input-2").keyup(function(e) { var regex = /^[a-zA-Z ğüşıöçĞÜŞİÖÇ]*$/; if (regex.test(this.value) !== true) date_msg("Dikkat!", "Soyad Alanına alfabetik Karakter Giriniz") this.value = this.value.replace(/[^a-zA-Z ğüşıöçĞÜŞİÖÇ]+/, ''); }); $("#input-6").keyup(function(e) { var regex = /^[0-9]*$/; if (regex.test(this.value) !== true) date_msg("Dikkat!", "Telefon Alanına Numerik Karakter Giriniz") this.value = this.value.replace(/[^0-9]+/, ''); }); $("#input-4").keyup(function(e) { // Our regex // a-z => allow all lowercase alphabets // A-Z => allow all uppercase alphabets // 0-9 => allow all numbers // @ => allow @ symbol var regex = /^[0-9]*$/; // This is will test the value against the regex // Will return True if regex satisfied if (regex.test(this.value) !== true) //alert if not true date_msg("Dikkat!", "Telefon Alanına Numerik Karakter Giriniz") // You can replace the invalid characters by: this.value = this.value.replace(/[^0-9]+/, ''); }); $("#input-18").keyup(function(e) { var regex = /^[0-9]*$/; if (regex.test(this.value) !== true) date_msg("Dikkat!", "IBAN Alanına Numerik Karakter Giriniz") this.value = this.value.replace(/[^0-9]+/, ''); }); $("#input-11").keyup(function(e) { var regex = /^[0-9]*$/; if (regex.test(this.value) !== true) date_msg("Dikkat!", "Sertifika No Alanına Numerik Karakter Giriniz") this.value = this.value.replace(/[^0-9]+/, ''); }); $("#selectCity").change(function() { var cityId = this.value; console.log(cityId) $.ajax({ url: "/getilceByIlId/"+cityId, type: "get", //data: {ulkeId: cityId}, success: function (response) { $('#loading-screen').fadeOut('slow'); $('#selectDistrict').find('option').remove().end().append('<option disabled selected> ----- İlçe Seçiniz ----- </option>').val(''); var i; for (i = 0; i < response.length; ++i) { $('#selectDistrict').append(new Option(response[i].ilce, response[i].id)); } $("#selectDistrict").val($("#selectDistrict option:first").val()); }, error: function(jqXHR, textStatus, errorThrown) { } }); }); jQuery.validator.addMethod('ad_rule', function (value, element) { if (/^[a-zA-ZğüşıöçĞÜŞİÖÇ,]+(\s{0,1}[a-zA-Z-ğüşıöçĞÜŞİÖÇ, ])*$/.test(value)) { return true; } else { return false; }; }); jQuery.validator.addMethod('numerik', function (value, element) { if (/^[0-9]*$/.test(value)) { return true; } else { return false; }; }); $("#DanismanKayit").validate({ "ignore": ":hidden", "rules": { adi: { "required": true, "minlength": 2, "maxlength": 25, "ad_rule":true, }, soyAdi: { "required": true, "minlength": 2, "maxlength": 25, "ad_rule":true, }, sertifikaNo: { "required": true, "minlength": 1, "maxlength": 5, }, email: { "required": true, "minlength": 7, "maxlength": 50, "email": true, }, telefon: { "required": true, "minlength": 10, "maxlength": 11, "numerik":true, }, iban: { "required": true, "minlength": 24, "maxlength": 24, "numerik":true, }, password: { "required": true, "minlength": 5, "maxlength": 20, }, password2: { "required": true, "minlength": 5, "maxlength": 20, }, il: { "required": true, }, ilce: { "required": true, }, firmaTelefon: { "minlength": 11, "maxlength": 11, "numerik":true }, adres: { "minlength": 2, "maxlength": 250, }, firmaAdi: { "minlength": 2, "maxlength": 40, }, }, "messages": { adi: { "required": "Ad Alanını Doldurunuz", "minlength": "En Az 2 Karakter", "maxlength": "En Çok 25 Karakter Girilebilir", "ad_rule":"Sadece Alfabetik Karakter Giriniz", }, soyAdi: { "required": "Soyad Alanını Doldurunuz", "minlength": "En Az 2 Karakter", "maxlength": "En Çok 25 Karakter Girilebilir", "ad_rule":"Sadece Alfabetik Karakter Giriniz", }, email: { "required": "E-mail Alanını Doldurunuz", "minlength": "En Az 7 Karakter Girilebilir", "maxlength": "En Çok 50 Karakter Girilebilir", "email": "Lütfen Geçerli Bir E-Mail Adresi Giriniz", }, sertifikaNo: { "required": "Sertİfİka Alanını Doldurunuz", "minlength": "En az 1 Hane Gerekli", "maxLength": "En Çok 5 hane girilebilir", }, iban: { "required": "Komisyon Ödemesi İçin IBAN Alanını Doldurmalısınız", "minlength": "En az 24 Hane Gerekli", "maxLength": "En Çok 24 hane girilebilir", }, telefon: { "required": "İletişim Numarası Alanını Doldurunuz", "minlength": "Min. 10 Hane Girilebilir", "maxlength": "Max. 11 Hane Girilebilir", "numerik": "Sadece Rakam Girilebilir", }, firmaTelefon: { "minlength": "Min. 11 Hane Girilebilir", "maxlength": "Max. 11 Hane Girilebilir", "numerik": "Sadece Rakam Girilebilir", }, adres: { "minlength": "Min. 2 Hane Girilebilir", "maxlength": "Max. 250 Hane Girilebilir", }, il: { "required": "Lütfen Bir İl Seçiniz", }, ilce: { "required": "Lütfen Bir İlçe Seçiniz", }, password: { "required": "Şifre Alanı Zorunludur", "minlength": "Min. 5 Hane Girilebilir", "maxlength": "Max. 20 Hane Girilebilir", }, password2: { "required": "Şifre Alanı Zorunludur", "minlength": "Min. 5 Hane Girilebilir", "maxlength": "Max. 20 Hane Girilebilir", }, }, "submitHandler": function (form) { var postData = $('#DanismanKayit').serializeJSON(); console.log(postData) $.ajax({ type: "POST", contentType: "application/json", url: "/danisman/kaydet", data: postData, dataType: 'json', cache: false, timeout: 60000, success: function (data) { $('#loading-screen').fadeOut('slow'); if (data.result) { console.log(data); success_noti_custom(data.message); setTimeout(function () { window.location.replace("/login"); }, 1000); } else { error_noti_yuk(data.message) } }, error: function (e) { console.log("ERROR : ", e); $("#btn-login").prop("disabled", false); } }); return false; // required to block normal submit since you used ajax } }); });
const express = require('express'); const app = express(); const bodyParser = require('body-parser'); const useragent = require('express-useragent'); const fs = require('fs'); const morgan = require('morgan'); const path = require('path'); const { mongoose } = require('./config/db'); const { routes } = require('./config/routes'); const port = 3000; app.use(express.json()); app.use(bodyParser.json()); app.use(useragent.express()); // logger should be at the top before redirecting to routes.js const accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' }) // setting up the logger app.use(morgan('combined', { stream: accessLogStream })) app.use(function (req, res, next) { console.log('hi'); next(); }) app.use('/', routes); // error handler should be at the bottom of the code app.use(function(req, res, next) { res.status(404).send('The resource you are looking for does not exist'); next(); }); app.listen(port, () => { console.log('listening on port', port); });
import React, {Component} from 'react'; const valorantUrl = 'https://valorant-api.com/v1/agents/'; class CharacterSpecs extends Component{ constructor(props) { super(props); this.state = { charactersInfo: [], uuid: props.match.params } } componentDidMount() { //const { uuid } = this.props.match.params; const endpoint = `${valorantUrl}${this.state.uuid}`; console.log('ENDPOINT', endpoint) fetch(`${valorantUrl}${this.state.uuid}`) .then(response => response.json()) .then(json => { const agent = (json && json.data) || []; this.setState({ charactersInfo: agent}); console.log('TEST', this.state.uuid) }); } render(){ return( <div> <section> {console.log('This STATE',this.state.charactersInfo)} { this.state.charactersInfo && this.state.charactersInfo.map((params, index) => { return ( <span>name:{params.name}</span> ); }) } </section> </div> ); } } export default CharacterSpecs;
module.exports = { mode: 'jit', purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'], darkMode: false, // or 'media' or 'class' theme: { extend: { maxWidth: { site: '1280px', }, colors: { body: '#08090a', 'ghost-light-hover': '#eef0f1', 'button-primary-bg': '#3b49df', 'button-primary-bg-hover': '#323ebe', 'button-primary-color': '#f9fafa', 'button-primary-color-hover': '#f9fafa', 'footer-bg': '#d2d6db', link: '#3b49df', 'link-gray': 'rgba(8, 9, 10, 0.05)', }, backgroundColor: (theme) => ({ ...theme('colors'), body: '#eef0f1', }), height: { header: '56px', }, borderRadius: { devto: '5px', }, boxShadow: { header: '0 1px 1px rgba(0, 0, 0, 0.1)', }, }, }, variants: { extend: {}, }, plugins: [], }
var Matrix4 = require('./KTMatrix4'); var Vector2 = require('./KTVector2'); var Vector3 = require('./KTVector3'); var KTMath = require('./KTMath'); var GeometryBillboard = require('./KTGeometryBillboard'); function Mesh(geometry, material){ if (!geometry || !geometry.__ktgeometry) throw "Geometry must be a KTGeometry instance"; if (!material || !material.__ktmaterial) throw "Material must be a KTMaterial instance"; this.__ktmesh = true; this.geometry = geometry; this.material = material; this.isBillboard = (geometry instanceof GeometryBillboard); this.children = []; this.parent = null; this.visible = true; this.castShadow = false; this.receiveShadow = false; this.position = new Vector3(0, 0, 0); this.rotation = new Vector3(0, 0, 0); this.scale = new Vector3(1, 1, 1); this.previousPosition = this.position.clone(); this.previousRotation = this.rotation.clone(); this.previousScale = this.scale.clone(); this.order = 0; this.transformationMatrix = null; this.transformationStack = 'SRxRyRzT'; } module.exports = Mesh; Mesh.prototype.lookAtObject = function(camera){ var angle = KTMath.get2DAngle(this.position.x, this.position.z, camera.position.x, camera.position.z) + KTMath.PI_2; this.rotation.y = angle; if (this.geometry.spherical){ var dist = new Vector3(camera.position.x - this.position.x, 0, camera.position.z - this.position.z).length(); var xAng = -KTMath.get2DAngle(0, this.position.y, dist, camera.position.y); this.rotation.x = xAng; } }; Mesh.prototype.positionChanged = function(){ return (!this.transformationMatrix || !this.position.equals(this.previousPosition) || !this.rotation.equals(this.previousRotation) || !this.scale.equals(this.previousScale)); }; Mesh.prototype.getTransformationMatrix = function(camera){ if (this.isBillboard){ this.lookAtObject(camera); } var parentPositionChanged = (this.parent && this.parent.positionChanged); if (this.positionChanged || parentPositionChanged){ this.transformationMatrix = Matrix4.getTransformation(this.position, this.rotation, this.scale, this.transformationStack); this.previousPosition.copy(this.position); this.previousRotation.copy(this.rotation); this.previousScale.copy(this.scale); if (this.parent){ var m = this.parent.getTransformationMatrix(camera); this.transformationMatrix.multiply(m); } } return this.transformationMatrix.clone(); }; Mesh.prototype.addChild = function(mesh){ this.children.push(mesh); mesh.parent = this; mesh.position.x -= this.position.x; mesh.position.y -= this.position.y; mesh.position.z -= this.position.z; mesh.rotation.x -= this.rotation.x; mesh.rotation.y -= this.rotation.y; mesh.rotation.z -= this.rotation.z; };
//游戏数据 var gamedata = { //分享图文 shareData: new Array(), //跳转游戏列表 gamelist: new Array(), //控制数据 control: { showMore: false,//是否显示更多游戏 showGamelist: false,//是否显示游戏列表 bannerRefreshTime: 0,//banner刷新时间 homeBannerRatio: 0,//首页banner显示概率 uglyShare: false,//诱导分享 }, //本地保存的key dataKey: "200113_01", //#region 头条录屏 recorder: null, isRecord: false, recordTimer: 0, //#endregion //#region 玩家数据 masterData:{ gold:0, gem:0, inviteReward:new Array(), friendList:new Array(), }, //#endregion isInvite: false,//是否好友邀请 inviteId: 0,//邀请的好友ID guideData: {},//引导数据 drawNum: 0,//抽奖次数, signArray: [0, 0, 0, 0, 0, 0, 0], screenWidth: 0, screenHeight: 0, //region 引导 //初始化引导数据 initGuideData: function () { // this.guideData = { // isGuideSummon: false,//是否引导过召唤 // isGuideSell: false,//是否引导过出售 // isGuideCompose: false,//是否引导过合成 // isGuideFight: false,//是否引导过战斗 // } this.guideData = { isGuideSummon: true,//是否引导过召唤 isGuideSell: true,//是否引导过出售 isGuideCompose: true,//是否引导过合成 isGuideFight: true,//是否引导过战斗 } }, //获取引导数据 getGuideData: function () { var str = cc.sys.localStorage.getItem("guide" + this.dataKey) if (str === "" || str === null) { //初始化英雄数据 this.initGuideData() } else { this.guideData = JSON.parse(str) } }, //保存引导数据 saveGuideData: function () { cc.sys.localStorage.setItem("guide" + this.dataKey, JSON.stringify(this.guideData)) }, //#endregion //初始化本地秘钥 initDataKey: function () { var str = cc.sys.localStorage.getItem("datakey") if (str === "" || str === null) { this.dataKey = new Date().getTime() / 1000 } else { this.dataKey = parseInt(str) } }, //重置本地秘钥 resetDataKey: function () { cc.sys.localStorage.setItem("datakey", new Date().getTime() / 1000) }, //初始化玩家数据 initMasterData:function(){ this.masterData.gold=0 this.masterData.gem=0 this.masterData.friendList=new Array() this.masterData.inviteReward=new Array() for(var i=0;i<5;i++){ this.masterData.inviteReward.push(0) } }, //获取玩家数据 getMasterData:function(){ var str = cc.sys.localStorage.getItem("masterData" + this.dataKey) if (str === "" || str === null) { //初始化英雄数据 this.initGuideData() } else { this.guideData = JSON.parse(str) } }, //保存玩家数据 saveMasterData:function(){ cc.sys.localStorage.setItem("masterData" + this.dataKey, JSON.stringify(this.masterData)) }, }; module.exports = gamedata;
import Point from './Point.js'; /** * 判断点击区域是否在任意图形内 * Long may the sun shine :) * * @author Owen * @email ouyangxiangyue@baidu.com * @github github/numerhero * @date 2017-02-03 * @param {Array} shape 图形的个个点组成的坐标 * @param {Object} test 触点对象 * @return {Boolean} 是or否 */ export let testInside = (shape, test) => { let result = false; for (let i = 0, j = shape.length - 1; i < shape.length; j = i++) { if ((shape[i][1] > test[1]) != (shape[j][1] > test[1]) && (test[0] < (shape[j][0] - shape[i][0]) * (test[1] - shape[i][1]) / (shape[j][1]-shape[i][1]) + shape[i][0])) { result = !result; } } return result; } /** * 判断点击区域是否在点内 * Long may the sun shine :) * * @author Owen * @email ouyangxiangyue@baidu.com * @github github/numerhero * @date 2017-02-03 * @param {Object} hitPoint 判断点对象 * @param {Number} x 触点x * @param {Number} y 触点y * @return {Boolean} 是否在点内 */ export let testPointHit = (hitPoint, x, y) => { let r = hitPoint.r + hitPoint.bWeight; let dx = x - hitPoint.x; let dy = y - hitPoint.y; return Pow(r, 2) > Pow(dx, 2) + Pow(dy, 2); } /** * 以一个 点为圆心点, 获取另一个点到圆心点的逆时针方向的夹角度数 * Long may the sun shine :) * * @author Owen * @email ouyangxiangyue@baidu.com * @github github/numerhero * @date 2017-02-03 * @param {Number} x * @param {Number} y * @param {Number} x1 * @param {Number} y1 * @return {Number} 夹角度数 */ export let getDeg = (x,y,x1,y1) => { let $x = x1 - x; let $y = y1 - y; let _$x = Abs($x); let h = Sqrt(Pow($x, 2) + Pow($y, 2)); let _deg = Acos(_$x/h); let deg = 0; switch(true) { // 第一象限 case ($x > 0 && $y <= 0): deg = _deg; break; // 第二象限 case ($x <= 0 && $y < 0): deg = PI - _deg; break; // 第三象限 case ($x < 0 && $y >= 0): deg = PI + _deg; break; // 第四象限 case ($x >= 0 && $y > 0): deg = 2*PI - _deg; break; } return deg; }
import React from 'react'; import style from './App.css'; const Title = props =>{ return( <div className={style.Title}> <h1>To Do List</h1> no. of tasks {props.data.length} </div> ); } export default Title;
//加载数据表格 $('#dg').datagrid({ //url: webRoot + 'common/query?groupid=' + groupid, //为了适应多个地方对该页面的调用,这里加载datagrid的url采用调用者传递的url进行查询,调用者去实现对应的请求查询 url : webRoot + url, fit: true, //设置自适应高度 fitColumns: true, //设置自适应宽度 sortName: 'id', sortOrder: 'desc', pagination: true, //设置分页 rownumbers: true, //显示行号 singleSelect: true,//设置为单选行 striped: true, //设置单行换色 pageList: [10,20,30,40,50], pageSize: 10, border: false, //设置没有边框 columns:[[ {field:'ck',checkbox:true}, {field:'has_read',title:'状态',align:'center', formatter: function(val,rec){ if(val == 0){ return '<span style="color:red;">新</span>'; } else { return ''; } } }, {field:'item0',title:'标题'}, {field:'item1',title:'原文链接'}, {field:'item2',title:'时间'}, { field:'a', title:'操作', formatter: function(val,rec){// target="_blank" if(rec.has_read == 0){ return '<a href="javascript:see(\'' + rec.id + '\',\'' + rec.item1 + '\');" >查看原文</a>'; } else { return '<a href="' + rec.item1 + '" target="_blank" >查看原文</a>'; } } } ]], loadFilter: function(data){ return loadfilter(data); }, //绑定右键菜单 onRowContextMenu: function(e,index,row){ //阻止浏览器的右键菜单 e.preventDefault(); $('#mm').menu('show', { left:e.pageX, top:e.pageY, }); } }); /** * 以下为打标签 */ //右键菜单添加标签方法 function addLabel(){ $("#playLabel").dialog('open').dialog('setTitle','添加标签'); $('#labelTab').datagrid({ url: webRoot + 'label/queryAll', fit: true, //设置自适应高度 sortName: 'id', sortOrder: 'desc', pagination: false, //设置分页 rownumbers: true, //显示行号 checkOnSelect: true, columns:[[ {field:'ck',checkbox:true}, {field:'id',title:'ID',hidden: true}, {field:'name',title:'标签名称',width:320}, ]], loadFilter: function(data){ return loadfilter(data); }, //初始化 选中行 onLoadSuccess: function(data){ //获取选中行的id var dataRow = $("#dg").datagrid('getSelected'); var id = dataRow.id; $.post( webRoot + 'label/qyeryLabelByCommon', {'common_id':id}, function(data){ if(data.code != 0){ $.messager.alert("提示信息",data.message); } else { $.each(data.data, function(index, item){ $.each($("#labelTab").datagrid('getRows'),function(i,i_item){ if(item.id == i_item.id){ $("#labelTab").datagrid('selectRow',i); return true; } }) }); } } ); } }); } /** * 保存打标签 */ function savePlayLabel(){ //获取所有选中标签,将id存放到arry中 var array = new Array(); var rows = $("#labelTab").datagrid("getSelections"); // 获取所有选中的行 for (var i = 0; rows && i < rows.length; i++) { var row = rows[i]; array.push(row.id); } //获取选中行的id var dataRow = $("#dg").datagrid('getSelected'); var id = dataRow.id; $.ajax({ url: webRoot + 'common/playLabel', type: 'post', data: {'id': id,'labels':array.join(",")}, dataType: 'json', success: function(data){ if(data.code == 0){ $('#playLabel').dialog('close'); // 关闭窗口 $.messager.show({ title: '提示信息', msg: '操作成功!', }); } else { $.messager.alert('error',code.message); } } }); } /** * 以下为分组 */ //右键添加分组 function addGroup(){ $("#playGroup").dialog('open').dialog('setTitle','添加分组'); //加载所有分组 $("#groupTab").datagrid({ url: webRoot + 'group/queryAll', fit: true, //设置自适应高度 sortName: 'id', sortOrder: 'desc', pagination: false, //设置分页 rownumbers: true, //显示行号 singleSelect: true, //设置为单选,只能包含一个分组 checkOnSelect: true, columns:[[ {field:'ck',checkbox:true}, {field:'id',title:'ID',hidden: true}, {field:'name',title:'分组名称',width:320}, ]], loadFilter: function(data){ return loadfilter(data); }, //初始化该文章所属的分组 ,data中group_groupid为所属的分组 onLoadSuccess: function(data){ var dataRow = $("#dg").datagrid('getSelected'); var catalog_id = dataRow.catalog_id; $.each($("#groupTab").datagrid('getRows'),function(index,item){ if(item.id == catalog_id){ $("#groupTab").datagrid('selectRow',index); return false; } }) } }); } //保存分组 function savePlayGroup(){ //获取选分组的id var groupId = $("#groupTab").datagrid('getSelected').id; //获取选中的文章id var commId = $("#dg").datagrid('getSelected').id; $.ajax({ url: webRoot + 'common/playGroup', type: 'post', data: {'commId':commId,'groupId':groupId}, dataType: 'json', success: function(data){ if(data.code == 0){ $('#dg').datagrid('reload'); $('#playGroup').dialog('close'); // 关闭窗口 $.messager.show({ title: '提示信息', msg: '操作成功!', }); } else { $.messager.alert('error',data.message); } } }); } /** * 查看新闻 * * @param id */ function see(id,url){ //在新窗口查看链接 window.open(url); //后台请求改变为已经查看 var row = $("#dg").datagrid('getSelected'); var selectRowIndex = $("#dg").datagrid('getRowIndex',row); $.ajax({ url: webRoot + 'common/see', type: 'post', data: {'id':id}, dataType: 'json', success: function(data){ if(data.code == 0){ //修改该行的状态值 $("#dg").datagrid('updateRow',{ index: selectRowIndex, row:{ ISSEE: '1' } }); } else { $.messager.alert('error',data.message); } } }); }
let timeAtStart; let interval; let time; let table; let startButton; let timeElapsedDisplayFormat; // the game works correctly only with even number of cells const nbCellsX = 4; const nbCellsY = 4; let randomColors = []; let foundCells = []; let pressedCells = []; let gamePaused = false; let gameStarted = false; // fills the table with empty cells function fillTable() { let k = 0; for (let i = 0; i < nbCellsY; i++) { const row = document.createElement('tr'); for (let j = 0; j < nbCellsX; j++) { const cell = document.createElement('td'); cell.setAttribute('id', k); // sets a unique id which will match the index of the color in randomColors array cell.setAttribute('onclick', 'openCell(this)'); row.appendChild(cell); k++; } table.appendChild(row); } } // initialises the game for the first time function init() { table = document.getElementById('table'); time = document.getElementById('time'); startButton = document.getElementById('startButton'); fillTable(); } // cleans the table function tableClean() { while (table.firstChild) { table.removeChild(table.firstChild); } } // mixes up an array function shuffle(arrayP) { const array = [...arrayP]; for (let i = array.length - 1; i > 0; i -= 1) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } return array; } // return an array consisting of randomly distributed random colors (one color for a pair of cells) function generateRandomColors(nb) { let randColors = []; for (let i = 0; i < nb; i++) { const rc = randomColor(); randColors.push(rc); randColors.push(rc); } randColors = shuffle(randColors); return randColors; } // generates a new game with random colors function generateGame() { const nbColors = Math.trunc((nbCellsY * nbCellsX) / 2); randomColors = generateRandomColors(nbColors); } // returns time in appropriate format (minmin:ss.msmsms) function displayFormat(minP, sP, msP) { let min = minP; let s = sP; let ms = msP; if (min < 10) { min = `0${min}`; } if (s < 10) { s = `0${s}`; } if (ms < 10) { ms = `00${ms}`; } else { if (ms < 100) { ms = `0${ms}`; } } return `${min}:${s}.${ms}`; } // updates and displays time function timeUpdate() { const timeNow = new Date(); const timeElapsed = new Date(timeNow - timeAtStart); const min = timeElapsed.getUTCMinutes(); const s = timeElapsed.getUTCSeconds(); const ms = timeElapsed.getUTCMilliseconds(); timeElapsedDisplayFormat = displayFormat(min, s, ms); time.innerHTML = timeElapsedDisplayFormat; } // starts the stopwatch function timeStart() { timeAtStart = new Date(); interval = setInterval(timeUpdate, 1); } // starts the game function gameStart() { gameStarted = true; startButton.style.visibility = 'hidden'; generateGame(); timeStart(); } // generates a random color in RGB string format function randomColor() { const randomR = Math.floor(Math.random() * 256); const randomG = Math.floor(Math.random() * 256); const randomB = Math.floor(Math.random() * 256); return `RGB(${randomR},${randomG},${randomB})`; } // called when the user clicks on a cell function openCell(cell) { if (gameStarted && !gamePaused) { if (foundCells.indexOf(cell) === -1 && pressedCells.indexOf(cell) === -1) { cell.style.background = randomColors[cell.id]; pressedCells.push(cell); if (pressedCells.length === 2) { if (pressedCells[0].style.background === pressedCells[1].style.background) { foundCells.push(pressedCells.pop()); foundCells.push(pressedCells.pop()); } else { pressedCellsBadMatch(); // the pressed cells don't match, so we call this function } } } } if (foundCells.length === nbCellsX * nbCellsY) { clearInterval(interval); setTimeout(gameFinished, 100); } } // gives 500ms to the user to remember the colors, and after makes the pressed cells white again function pressedCellsBadMatch() { gamePaused = true; setTimeout(() => { pressedCells[0].style.background = 'transparent'; pressedCells[1].style.background = 'transparent'; pressedCells = []; gamePaused = false; }, 500); } // reinitialises the game so it can be played one more time function clearGame() { tableClean(); init(); foundCells = []; startButton.style.visibility = 'visible'; gameStarted = false; time.innerHTML = '00:00.000'; } function gameFinished() { alert(`Вы выиграли!\nЗатраченное время: ${timeElapsedDisplayFormat}`); clearGame(); }
/*global define*/ define([ 'jquery', 'underscore', 'backbone', 'templates', 'baseview' ], function ($, _, Backbone, JST) { 'use strict'; var PagesItemView = Backbone.BaseView.extend({ template: JST['app/scripts/templates/pages/item.hbs'], tagName: 'article', id: function () { return 'page-' + this.model.get('id'); }, className: function () { var pagespan = this.model.get('custom_fields')['page-span']; return 'page' + (pagespan ? '--' + pagespan[0] : ''); }, events: {} }); return PagesItemView; });
angular.module('app') .controller('IntroCtrl', function($scope, $rootScope, $ionicPopup, $http) { $rootScope.showl = false; $rootScope.showr = false; $(".bubble").animate( { left: '42%', opacity: '1' }, 1000); $scope.nofurther = function() { $scope.showAlert(); } $scope.showAlert = function() { var alertPopup = $ionicPopup.alert({ title: 'Helaas!', template: 'Koop de app voor de volledige versie!' }); alertPopup.then(function(res) { console.log('Koop de app :)'); }); }; })
export const IS_ACTIVE = "true", IS_NOT_ACTIVE = "false"; /** * Returns the value of a given attribute * @param {AccessibleNode} ay * @param {String} attributeName * @return {String} attribute's value */ export function get(ay, attributeName) { var value = ay._.rawAttrs.attributeName || ay.element.getAttribute(attributeName); if (value == undefined) return; return value; } /** * Sync the new value to the DOM * @param {AccessibleNode} ay * @param {String} attributeName * @param {String | Number } status */ export function set(ay, attributeName, status) { if(status == undefined) { ay.element.removeAttribute(attributeName); } else { ay.element.setAttribute(attributeName, status); } return status; } /** * Returns the opposite state of the attribute, * needed when attribute uses an token list * @return {String} New state */ export function toggle(state) { if (state == IS_ACTIVE) { state = IS_NOT_ACTIVE; } else { state = IS_ACTIVE; } return state; } export default { IS_ACTIVE, IS_NOT_ACTIVE, get, set, toggle };
function loadVerifyPage() { var url = window.location.href; url = url.split('#').pop().split('?').pop(); var pageurl = url.substring(0, url.lastIndexOf('/')); pageurl = pageurl + "/verify.html"; document.getElementById("suvpage").value = pageurl; } $(document).keyup(function (e) { /* Enter key is used */ if ($("#loginpassword").is(":focus") && (e.keyCode == 13)) { login(); } else if($("#surepeatpassword").is(":focus") && (e.keyCode == 13)){ signUp(); } }); /** * Check login credentials by sending them to authTokenEndpoint and receiving response inside Promise. */ function login() { username = $("#loginemail"); password = $("#loginpassword"); bool1 = check(username); bool2 = check(password); if (bool1 && bool2) { parameters = { 'email': username.val(), 'password': password.val(), }; var promise = new Promise(function (success, failure) { $.ajax({ url: authTokenEndpoint, type: 'POST', contentType: "application/json", data: JSON.stringify(parameters), success: function (data) { success(data); }, error: function (data) { failure(data.responseText); } }) }); promise.then(function (data) { setTokenCookie(data["token"]); window.location.href = "catalog.html" }, function (data) { var response = JSON.parse(data); showSnackbar(response["message"]); }); } } /** * Check sign up credentials of new user by sending them to signUpEndpoint and receiving response inside Promise. */ function signUp() { firstname = $("#sufirstname"); lastname = $("#sulastname"); email = $("#suemail"); password = $("#supassword"); repeatpassword = $("#surepeatpassword"); verify_page = $("#suvpage"); var bool1 = check(firstname); var bool2 = check(lastname); var bool3 = check(email); var bool4 = check(password); var bool5 = check(repeatpassword); var bool6 = check(verify_page); if (bool1 && bool2 && bool3 && bool4 && bool5 && bool6) { parameters = { 'firstname': firstname.val(), 'lastname': lastname.val(), 'email': email.val(), 'password': password.val(), 'verify_page': verify_page.val() }; var promise = new Promise(function (success, failure) { $.ajax({ url: signUpEndpoint, type: 'POST', contentType: "application/json", data: JSON.stringify(parameters), success: function (data) { success(data); }, error: function (data) { failure(data.responseText); } }); }); promise.then(function (data) { if (data["success"] == true) { showSnackbar("User registered successfully. You will receive verification mail shortly."); } clearSignUpForm(); }, function (data) { var json = JSON.parse(data); showSnackbar(json["message"]); }); } } /** * clears signup form's fields when user presses sign up button */ function clearSignUpForm() { $("#sufirstname").val(""); $("#sulastname").val(""); $("#suemail").val(""); $("#supassword").val(""); $("#surepeatpassword").val(""); } /** * check if a form field is submitted with blank input. * @param element * @return {Boolean} bool */ function check(element) { var bool; var re_email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var re_password = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,20}$/; if (element.val() == "") { element.addClass("invalid"); bool = false; } else { element.removeClass("invalid"); bool = true; } if (element.attr('id') == "suemail" && !re_email.test(element.val())){ element.addClass("invalid"); bool = false; showSnackbar("Email id should be of format user@domain.com"); } else if (element.attr('id') == "supassword"){ bool = re_password.test(element.val()); if(!bool){ element.addClass("invalid"); showSnackbar("Password must have 1 Special, Numeric, Uppercase and Lowercase Character and of length 8 to 20"); } } else if (element.attr('id') == "surepeatpassword" && element.val() !== "") { if ($("#supassword").val() !== element.val()) { showSnackbar("Passwords do not match"); element.addClass("invalid"); $("supassword").addClass("invalid"); bool = false; } } return bool }
import Component from '@glimmer/component'; import debugLogger from 'ember-debug-logger'; import { action } from '@ember/object'; import { htmlSafe } from '@ember/template'; import { isPresent } from '@ember/utils'; import { tracked } from '@glimmer/tracking'; export default class TwyrToasterInnerComponent extends Component { // #region Private Attributes debug = debugLogger('twyr-toaster-inner'); _element = null; _hammer = null; // #endregion // #region Tracked Attributes @tracked _isActive = false; @tracked _isDragging = false; @tracked _x = 0; // #endregion // #region Constructor constructor() { super(...arguments); this.debug(`constructor`); } // #endregion // #region Lifecycle Hooks @action didInsert(element) { this.debug('didInsert'); this._element = element; if(this.args.swipeToClose) this._setupHammer(); } @action didReceiveArgs() { if(this.args.swipeToClose && !this._hammer) { this._setupHammer(); return; } if(!this.args.swipeToClose && this._hammer) { this._teardownHammer(); return; } } willDestroy() { this.debug('willDestroy'); if(!this._hammer) return; this._teardownHammer(); } // #endregion // #region Computed Properties get computedStyle() { return htmlSafe(`transform:translate(${ this._x }px, 0)`); } // #endregion // #region Private Methods _dragStart(event) { if(!this.args.swipeToClose) return; this._isActive = true; this._isDragging = true; this._element.focus(); this._x = event.center.x; } _drag(event) { if(!this.args.swipeToClose || this._isDragging) return; this._x = event.deltaX; } _dragEnd() { if(!this.args.swipeToClose) return; this._isActive = false; this._isDragging = false; if(isPresent(this.args.onClose) && (typeof this.args.onClose === 'function')) this.args.onClose(); } _setupHammer() { if(!this._element) return; // Enable dragging the slider const containerManager = new window.Hammer.Manager(this._element, { 'dragLockToAxis': true, 'dragBlockHorizontal': true }); const swipe = new window.Hammer.Swipe({ 'direction': window.Hammer.DIRECTION_ALL, 'threshold': 10 }); const pan = new window.Hammer.Pan({ 'direction': window.Hammer.DIRECTION_ALL, 'threshold': 10 }); containerManager.add(swipe); containerManager.add(pan); containerManager.on('panstart', this._dragStart.bind(this)); containerManager.on('panmove', this._drag.bind(this)); containerManager.on('panend', this._dragEnd.bind(this)); containerManager.on('swiperight swipeleft', this._dragEnd.bind(this)); this._hammer = containerManager; } _teardownHammer() { this._hammer.destroy(); this._hammer = null; } // #endregion }
"use strict"; /** Map of all colors in game, assigned here to make it easier to modify */ let colorMap = new Map(); colorMap.set("border", "rgb(84, 84, 69)"); colorMap.set("floor", "rgb(119, 119, 98)"); colorMap.set("wall", "rgb(255, 255, 255)"); colorMap.set("lava", "rgb(237, 60, 21)"); colorMap.set("goal", "rgb(80, 244, 66)"); colorMap.set("switch1a", "rgb(226, 180, 93)"); colorMap.set("switch1b", "rgb(244, 213, 154)"); colorMap.set("disappearing1a", "rgb(255, 182, 0)"); colorMap.set("disappearing1d", "rgb(142, 101, 0)"); colorMap.set("switch2a", "rgb(56, 202, 216)"); colorMap.set("switch2b", "rgb(146, 224, 232)"); colorMap.set("disappearing2a", "rgb(0, 255, 242)"); colorMap.set("disappearing2d", "rgb(0, 96, 91)"); colorMap.set("switch3a", "rgb(92, 119, 219)"); colorMap.set("switch3b", "rgb(153, 144, 237)"); colorMap.set("disappearing3a", "rgb(0, 55, 255)"); colorMap.set("disappearing3d", "rgb(0, 24, 112)"); colorMap.set("tp1a", "rgb(255, 137, 215)"); colorMap.set("tp1b", "rgb(237, 68, 180)"); colorMap.set("tp2a", "rgb(185, 56, 255)"); colorMap.set("tp2b", "rgb(124, 1, 191)"); colorMap.set("hero", "rgb(245, 249, 0)"); colorMap.set("pause", "rgba(0, 0, 0, 0.4"); /** Number of levels that exist */ const maxLevel = 12; /** * Class to deconstruct loaded txt file from server into useful level information */ class Level { /** * Creates the level from server information. Important variables include: * * title - Title of level * grid - 2D array of level information, including floors, walls, lava, goal, etc. * spawn - Coordinate pair of where hero is to be spawned * toggleTilesState - 3 element array of booleans depicting starting state of each switch tile * tp[1, 2]Locations - 2 element arrays of coordinate pairs for the two teleporter types * * @param {String} text text information from server */ constructor(text) { let lines = text.split("\n"); let lineIter = lines[Symbol.iterator](); let line = ""; this.grid = []; this.tp1Locations = []; this.tp2Locations = []; for (let i = 0; i < 25; i++) { this.grid.push([]); line = lineIter.next().value; for (let j = 0; j < 25; j++) { let tileId = Number(line.slice(j*2, j*2+2)); this.grid[i].push(tileId); if (tileId == 10) { this.tp1Locations.push({x: j, y: i}) } if (tileId == 11) { this.tp2Locations.push({x: j, y: i}) } } } line = lineIter.next().value; this.spawn = {x: Number(line.slice(0, 2)), y: Number(line.slice(2, 4))}; this.toggleTilesState = []; for (let i = 0; i < 3; i++) { line = lineIter.next().value; this.toggleTilesState.push(Number(line)); } this.title = lineIter.next().value; } } /** * Generic class that structures how a game is to be made and run. * Requires a div id "game_container" to place the canvas at the end of. */ class GameArea { /** * Creates the game area, which includes a canvas. * * @param {Number} width width of canvas in px * @param {Number} height height of canvas in px * @param {Number} fps times per second to run the main loop. includes game logic as well as frames */ constructor(width, height, fps, gameUpdateFunc, renderFrameFunc) { this.canvas = document.createElement("canvas"); this.canvas.width = width; this.canvas.height = height; document.getElementById("game_container").append(this.canvas); this.context = this.canvas.getContext("2d"); this.fps = fps; } /** * Set the functions to update the game * * @param {Function} gameUpdateFunc function to run at the beginning of each iteration of the main loop * @param {Function} renderFrameFunc function to run after gameUpdateFunc in each iteration of the main loop */ setUpdateFunctions(gameUpdateFunc, renderFrameFunc) { this._gameUpdate = gameUpdateFunc; this._renderFrame = renderFrameFunc; } /** * Starts the game loop if not already started, with an interval specified by the frames per second */ start() { if (!this.interval) { this.interval = setInterval(this._update.bind(this), 1000 / this.fps); } } /** * Regularly called function to update game components and then to render a new frame */ _update() { // Update Game this._gameUpdate(); // Render Frame this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); this.context.fillStyle = "black"; this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); this._renderFrame(); } } // Pixels to move the player by in each update of the frame const playerSpeed = 5; /** * Specific class to run the Slider Game. The game is a puzzle game * where the player's goal is to slide their square to the green * goal tile while avoiding obstacles and using other game * mechanics to their advantage. The player should beware, however: * Once started, the square will not stop moving until it hits a * solid block! Early levels are designed to teach concepts, while * later levels are designed to be more of a challenge. Average * playtime for a new player is between 20 and 30 minutes. */ class SliderGame extends GameArea { /** * Creates the Slider Game, including the canvas. * Requires div id "level_number" to write level number to, * div id "level_title" to write title to, and * div id "timer" to write time data to. */ constructor() { // Slider Game is run at 50 fps, which is intense for some computers, but at fewer frames // runs fairly choppily. I will leave this for now, and maybe revise later super(500, 500, 50); super.setUpdateFunctions(this._sliderGameUpdate.bind(this), this._sliderRenderFrame.bind(this)); // All local variables this.level = 1; this.levelGrid = []; this.player = {x: 0, y: 0, xVel: 0, yVel: 0, dir: "none", startedSliding: false}; this.toggleTilesState = []; this.accumulatedTime = 0; this.lastDate = Date.now(); this.startHours = new Date(0).getHours(); this.paused = false; // References to document elements this.levelNumber = document.getElementById("level_number"); this.levelTitle = document.getElementById("level_title"); this.timer = document.getElementById("timer"); // Add controls variables and event listeners this.unprocessedKeys = new Map(); document.addEventListener("keydown", (event) => { this.unprocessedKeys.set(event.code, true); }); document.addEventListener("keyup", (event) => { this.unprocessedKeys.set(event.code, false); }); this.mouseCommand = "none"; this.mouseDown = false; document.addEventListener("click", (event) => { let dx = event.clientX - (this.canvas.getBoundingClientRect().left + this.player.x); let dy = event.clientY - (this.canvas.getBoundingClientRect().top + this.player.y); if (Math.abs(dx) > Math.abs(dy)) { if (dx > 15 && dx < 200) { this.mouseCommand = "right"; } else if (dx < -15 && dx > -200) { this.mouseCommand = "left"; } } else { if (dy > 15 && dy < 200) { this.mouseCommand = "down"; } else if (dy < -15 && dy > -200) { this.mouseCommand = "up"; } } }); // Initialize level variables this._setLevel(); } /** * Updates the slider game components, including the paused state, * time and player logic */ _sliderGameUpdate() { // Pause or Unpause game if (this._keyPressed("Space")) { this.paused = !this.paused; } // Update time this._updateTime(); // If the game is won, check if the player wants to restart game if (this.level > maxLevel) { if (this._keyPressed("KeyR")) { this.accumulatedTime = 0; this.lastDate = Date.now(); this.startHours = new Date(0).getHours(); this.level = 1; this.paused = false; this._setLevel(); return; } } else if (!this.paused) { // Otherwise, update the player logic if (this._updatePlayer()) { this._setLevel(); } } } /** * Update the time value in the "timer" div */ _updateTime() { // Determine what to append to time text content, and update time if required let append = ""; if (this.level > maxLevel) { append = " < WINNING TIME!" } else if (this.paused) { append = " | PAUSED"; } else { this.accumulatedTime += Date.now() - this.lastDate; } this.lastDate = Date.now(); // Update the time value in the div let nowDate = new Date(this.accumulatedTime); let twoDigitFormat = new Intl.NumberFormat('en-US', {minimumIntegerDigits: 2}); if (nowDate.getHours() - this.startHours > 0) { this.timer.textContent = `Time: ${nowDate.getHours() - this.startHours}:`+ `${twoDigitFormat.format(nowDate.getMinutes())}:` + `${twoDigitFormat.format(nowDate.getSeconds())}${append}`; } else { this.timer.textContent = `Time: ${twoDigitFormat.format(nowDate.getMinutes())}:` + `${twoDigitFormat.format(nowDate.getSeconds())}${append}`; } } /** * Updates the player location depending on the controls, velocity, and grid. * * @returns {Boolean} true if the level needs to be set/reset, false otherwise */ _updatePlayer() { // If 'R' is pressed, reset the level if(this._keyPressed("KeyR")) { return true; } // If the player is stationary and has a command waiting, start moving in that direction. // If there is more than one, it prioritizes left > down > right > up. if (this.player.dir == "none") { this.player.xVel = 0; this.player.yVel = 0; if (this._hasCommand("left")) { this.player.dir = "left"; this.player.startedSliding = true; this.player.xVel = -playerSpeed; } else if (this._hasCommand("down")) { this.player.dir = "down"; this.player.startedSliding = true; this.player.yVel = playerSpeed; } else if (this._hasCommand("right")) { this.player.dir = "right"; this.player.startedSliding = true; this.player.xVel = playerSpeed; } else if (this._hasCommand("up")) { this.player.dir = "up"; this.player.startedSliding = true; this.player.yVel = -playerSpeed; } } // This block is triggered if the player has perfectly passed over a grid square. // Any functionality that is dependent on landing on a square is triggered. // This is done before stopping because velocity is conserved in the event that // this functionality causes whatever would stop velocity to no longer stop it, // i.e. a button switches off a wall, or the player is teleported to a new location. if (!this.player.startedSliding && (this.player.x / 20) % 1 == 0 && (this.player.y / 20) % 1 == 0 && this.player.dir != "none") { switch (this.levelGrid[this.player.y / 20][this.player.x / 20]) { // 2 is lava- returning true resets the level case 2: return true; // 4 is orange buttons- toggle the tile state case 4: this.toggleTilesState[0] = !this.toggleTilesState[0]; break; // 6 is teal buttons- toggle the tile state case 6: this.toggleTilesState[1] = !this.toggleTilesState[1]; break; // 8 is blue buttons- toggle the tile state case 8: this.toggleTilesState[2] = !this.toggleTilesState[2]; break; // 10 is pink teleporters- move player to other teleporter location case 10: if (this.player.x / 20 == levels[this.level].tp1Locations[0].x && this.player.y / 20 == levels[this.level].tp1Locations[0].y) { this.player.x = levels[this.level].tp1Locations[1].x * 20; this.player.y = levels[this.level].tp1Locations[1].y * 20; } else { this.player.x = levels[this.level].tp1Locations[0].x * 20; this.player.y = levels[this.level].tp1Locations[0].y * 20; } break; // 11 is purple teleporters- move player to other teleporter location case 11: if (this.player.x / 20 == levels[this.level].tp2Locations[0].x && this.player.y / 20 == levels[this.level].tp2Locations[0].y) { this.player.x = levels[this.level].tp2Locations[1].x * 20; this.player.y = levels[this.level].tp2Locations[1].y * 20; } else { this.player.x = levels[this.level].tp2Locations[0].x * 20; this.player.y = levels[this.level].tp2Locations[0].y * 20; } break; default: break; } } else if (this.player.startedSliding) { // This variable ensures that mechanics are not triggered when you this.player.startedSliding = false; // have just started moving } // Now we need to determine where the player would end up if allowed to continue // moving in the direction that it is. This allows us to stop the movement if // the location the hero is moving into is a solid block. let xIndex, yIndex; if (this.player.dir == "right") { xIndex = Math.floor((this.player.x + this.player.xVel + (20 - playerSpeed)) / 20); } else { xIndex = Math.floor((this.player.x + this.player.xVel) / 20); } if (this.player.dir == "down") { yIndex = Math.floor((this.player.y + this.player.yVel + (20 - playerSpeed)) / 20); } else { yIndex = Math.floor((this.player.y + this.player.yVel) / 20); } // If the player is moving and the location they are moving to // is valid, stop; otherwise update location if (this.player.dir != "none") { if (xIndex >= 0 && xIndex < 25 && yIndex >= 0 && yIndex < 25) { if (this.levelGrid[yIndex][xIndex] == 1 || this.toggleTilesState[0] && this.levelGrid[yIndex][xIndex] == 5 || this.toggleTilesState[1] && this.levelGrid[yIndex][xIndex] == 7 || this.toggleTilesState[2] && this.levelGrid[yIndex][xIndex] == 9 || !this.toggleTilesState[0] && this.levelGrid[yIndex][xIndex] == 12 || !this.toggleTilesState[1] && this.levelGrid[yIndex][xIndex] == 13 || !this.toggleTilesState[2] && this.levelGrid[yIndex][xIndex] == 14 ) { this.player.dir = "none"; } else { this.player.x += this.player.xVel; this.player.y += this.player.yVel; } } else { this.player.dir = "none"; } } // The final check is for the goal. This is done here because the goal can only be said // to be reached if the player is stopped on it. if (this.player.dir == "none" && this.levelGrid[this.player.y / 20][this.player.x / 20] == 3) { this.level++; return true; } // If the function made it this far, then the level does not need to be reset return false; } /** * Renders an entire frame of the slider game by rendering each background tile, * and then the player on top of it, and then the foreground greying out if * the game has been won or paused. */ _sliderRenderFrame() { // Render the background let left = 0; let top = 0; for (let row = 0; row < 25; row++) { for (let col = 0; col < 25; col++) { this.context.fillStyle = colorMap.get("border"); this.context.fillRect(left + col * 20, top + row * 20, 20, 20); switch (this.levelGrid[row][col]) { case 0: this.context.fillStyle = colorMap.get("floor"); this.context.fillRect(left + col * 20 + 1, top + row * 20 + 1, 18, 18); break; case 1: this.context.fillStyle = colorMap.get("wall"); this.context.fillRect(left + col * 20 + 1, top + row * 20 + 1, 18, 18); break; case 2: this.context.fillStyle = colorMap.get("lava"); this.context.fillRect(left + col * 20, top + row * 20, 20, 20); break; case 3: this.context.fillStyle = colorMap.get("goal"); this.context.fillRect(left + col * 20 + 1, top + row * 20 + 1, 18, 18); break; case 4: this.context.fillStyle = colorMap.get("switch1a"); this.context.fillRect(left + col * 20, top + row * 20, 20, 20); this.context.fillStyle = colorMap.get("switch1b"); this.context.fillRect(left + col * 20 + 10, top + row * 20, 10, 10); this.context.fillRect(left + col * 20, top + row * 20 + 10, 10, 10); break; case 5: if (this.toggleTilesState[0]) { this.context.fillStyle = colorMap.get("disappearing1a"); this.context.fillRect(left + col * 20 + 1, top + row * 20 + 1, 18, 18); } else { this.context.fillStyle = colorMap.get("disappearing1d"); this.context.fillRect(left + col * 20 + 1, top + row * 20 + 1, 18, 18); } break; case 6: this.context.fillStyle = colorMap.get("switch2a"); this.context.fillRect(left + col * 20, top + row * 20, 20, 20); this.context.fillStyle = colorMap.get("switch2b"); this.context.fillRect(left + col * 20 + 10, top + row * 20, 10, 10); this.context.fillRect(left + col * 20, top + row * 20 + 10, 10, 10); break; case 7: if (this.toggleTilesState[1]) { this.context.fillStyle = colorMap.get("disappearing2a"); this.context.fillRect(left + col * 20 + 1, top + row * 20 + 1, 18, 18); } else { this.context.fillStyle = colorMap.get("disappearing2d"); this.context.fillRect(left + col * 20 + 1, top + row * 20 + 1, 18, 18); } break; case 8: this.context.fillStyle = colorMap.get("switch3a"); this.context.fillRect(left + col * 20, top + row * 20, 20, 20); this.context.fillStyle = colorMap.get("switch3b"); this.context.fillRect(left + col * 20 + 10, top + row * 20, 10, 10); this.context.fillRect(left + col * 20, top + row * 20 + 10, 10, 10); break; case 9: if (this.toggleTilesState[2]) { this.context.fillStyle = colorMap.get("disappearing3a"); this.context.fillRect(left + col * 20 + 1, top + row * 20 + 1, 18, 18); } else { this.context.fillStyle = colorMap.get("disappearing3d"); this.context.fillRect(left + col * 20 + 1, top + row * 20 + 1, 18, 18); } break; case 10: this.context.fillStyle = colorMap.get("tp1a"); this.context.fillRect(left + col * 20, top + row * 20, 20, 20); this.context.fillStyle = colorMap.get("tp1b"); this.context.fillRect(left + col * 20 + 10, top + row * 20, 10, 10); this.context.fillRect(left + col * 20, top + row * 20 + 10, 10, 10); break; case 11: this.context.fillStyle = colorMap.get("tp2a"); this.context.fillRect(left + col * 20, top + row * 20, 20, 20); this.context.fillStyle = colorMap.get("tp2b"); this.context.fillRect(left + col * 20 + 10, top + row * 20, 10, 10); this.context.fillRect(left + col * 20, top + row * 20 + 10, 10, 10); break; case 12: if (!this.toggleTilesState[0]) { this.context.fillStyle = colorMap.get("disappearing1a"); this.context.fillRect(left + col * 20 + 1, top + row * 20 + 1, 18, 18); } else { this.context.fillStyle = colorMap.get("disappearing1d"); this.context.fillRect(left + col * 20 + 1, top + row * 20 + 1, 18, 18); } break; case 13: if (!this.toggleTilesState[1]) { this.context.fillStyle = colorMap.get("disappearing2a"); this.context.fillRect(left + col * 20 + 1, top + row * 20 + 1, 18, 18); } else { this.context.fillStyle = colorMap.get("disappearing2d"); this.context.fillRect(left + col * 20 + 1, top + row * 20 + 1, 18, 18); } break; case 14: if (!this.toggleTilesState[2]) { this.context.fillStyle = colorMap.get("disappearing3a"); this.context.fillRect(left + col * 20 + 1, top + row * 20 + 1, 18, 18); } else { this.context.fillStyle = colorMap.get("disappearing3d"); this.context.fillRect(left + col * 20 + 1, top + row * 20 + 1, 18, 18); } break; } } } // Render the player this.context.fillStyle = colorMap.get("hero"); this.context.fillRect(this.player.x, this.player.y, 20, 20); // If game is paused or the game is won, grey out the game if (this.paused || this.level > maxLevel) { this.context.fillStyle = colorMap.get("pause"); this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); } } /** * Sets (or resets) all level information, including the player's location and velocity. */ _setLevel() { if (this.level > maxLevel) { return; } this.levelGrid = levels[this.level].grid; this.player.x = levels[this.level].spawn.x * 20; this.player.y = levels[this.level].spawn.y * 20; this.player.xVel = 0; this.player.yVel = 0; this.player.dir = "none"; this.toggleTilesState = levels[this.level].toggleTilesState.slice(); this.levelNumber.textContent = "Level: " + this.level; this.levelTitle.textContent = levels[this.level].title; } /** * Finds if the specified key has been pressed and not processed, meaning * it has not been checked after being set. * * @param {String} code the keyCode of the key being searched for * @returns {Boolean} whether or not the key is pressed and not processed */ _keyPressed(code) { if (this.unprocessedKeys.get(code)) { this.unprocessedKeys.set(code, false); return true; } return false; } /** * Checks for a command in the specified direction. * * @param {String} direction direction to check for a command. Should be "up", "down", "left", or "right" * @returns {Boolean} whether or not the specified direction has a command waiting */ _hasCommand(direction) { let temp = this.mouseCommand; if (this.mouseCommand == direction) { this.mouseCommand = "none"; } if (direction == "left") { return this._keyPressed("KeyA") || this._keyPressed("ArrowLeft") || temp == "left"; } else if (direction == "right") { return this._keyPressed("KeyD") || this._keyPressed("ArrowRight") || temp == "right"; } else if (direction == "down") { return this._keyPressed("KeyS") || this._keyPressed("ArrowDown") || temp == "down"; } else if (direction == "up") { return this._keyPressed("KeyW") || this._keyPressed("ArrowUp") || temp == "up"; } } } ////////////////////////// // Main Execution Point // ////////////////////////// /** * Game and levels are global so they aren't garbage collected, * and levels are loaded as soon as possible. Levels also functions * as a map, i.e. level 1 is stored at index 1. */ let game; let levels = []; for (let i = 1; i <= maxLevel; i++) { fetch("assets/levels/Level" + i + ".txt").then(function(response) { response.text().then(function(text) { console.log("Level " + i + " recieved."); levels[i] = new Level(text); }); }); } /** * Function to be called on when the DOM is loaded, so that game can correctly add canvas. * Will periodically check to see if all levels are loaded, and when they are, the game is created. */ function startGame() { setTimeout(function check() { if (levels.length-1 == maxLevel) { game = new SliderGame(); game.start(); } else { setTimeout(check, 500); } }, 0); } document.addEventListener("DOMContentLoaded", startGame);
function BookNow(guestName,guestEmail,guestPax,guestPackages,guestRemarks){ let url= 'https://api.sheety.co/d3ae687f2d39df38048b413e482c249e/bookingApp/bookings'; let body = { booking: { name:guestName, email:guestEmail, pax:guestPax, packages:guestPackages, remarks:guestRemarks } } fetch(url, { method: 'POST', body: JSON.stringify(body), headers:{ "Content-Type":"application/json" } }) .then((response) => response.json()) .then(json => { // Do something with object console.log(json.booking); alert(json.booking.name) + " successfully added"; }); } window.addEventListener("load",function(){ document.getElementById("bookNow").addEventListener ("click",function() { let name = document.getElementById("guestName").value; let email = document.getElementById("guestEmail").value; let pax=document.getElementById("guestPax").value; let packages=document.getElementById("guestPackages").value; let remarks= document.getElementById("guestRemarks").value; BookNow(name,email,pax,packages,remarks) }); });
var elements = require('../elements'); /** * Show the element (remove the class .hidden) * * @name Element#show * @method * */ /** * Show the elements (remove the class .hidden) * * @name ElementsArray#show * @method */ elements.addMethodWithoutArgumentsReturnThis('show'); /** * Hide the element (add the class .hidden) * * @name Element#hide * @method * */ /** * Hide the elements (add the class .hidden) * * @name ElementsArray#hide * @method */ elements.addMethodWithoutArgumentsReturnThis('hide'); /** * Toggle an element's visibility using the hidden class * * @name Element#toggle * @method * */ /** * Toggle an element's visibility using the hidden class * * @name ElementsArray#toggle * @method */ elements.addMethodWithoutArgumentsReturnThis('toggle'); /** * Return if an element's visibility * * @name Element#isVisible * @method * */ /** * Return a map of element's visibility * * @name ElementsArray#isVisible * @method */ elements.addMethodWithoutArgumentsReturnResult('isVisible');
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports) { if (typeof AFRAME === 'undefined') { throw new Error('Component attempted to register before AFRAME was available.'); } /** * Crease component for A-Frame. */ AFRAME.registerComponent('crease', { schema: { type: 'boolean', default: true }, /** * Called when component is attached and when component data changes. * Generally modifies the entity based on the data. */ update: function () { var mesh = this.el.getObject3D('mesh'); mesh.material.shading = THREE.SmoothShading; if (this.data) { mesh.material.shading = THREE.FlatShading; } mesh.material.needsUpdate = true; }, /** * Called when a component is removed (e.g., via removeAttribute). * Generally undoes all modifications to the entity. */ remove: function () { var mesh = this.el.getObject3D('mesh'); mesh.material.shading = THREE.SmoothShading; mesh.material.needsUpdate = true; } }); /***/ } /******/ ]);
(function() { 'use strict'; angular .module('iconlabApp') .controller('ArticleDetailController', ArticleDetailController); ArticleDetailController.$inject = ['$scope','$state', '$rootScope', '$stateParams', 'DataUtils', 'entity', 'Article', 'User','Principal']; function ArticleDetailController($scope,$state, $rootScope, $stateParams, DataUtils, entity, Article, User,Principal) { var vm = this; vm.article = entity; vm.byteSize = DataUtils.byteSize; vm.openFile = DataUtils.openFile; vm.isAuthenticated = Principal.isAuthenticated; var unsubscribe = $rootScope.$on('iconlabApp:articleUpdate', function(event, result) { vm.article = result; }); $scope.$on('$destroy', unsubscribe); $scope.clickGo = function(){ $('cadrearticle').addClass('animsortie') $state.go('home', null, { reload: true }); } } })();
const PubSub = require('../helpers/pub_sub.js'); let movies = []; const StudioGhibli = function () { this.movies = [] this.directors = [] } StudioGhibli.prototype.getData = function () { return fetch('https://ghibliapi.herokuapp.com/films/') .then(response => response.json()) .then((data) => new Promise(function(resolve, reject) { this.movies = data; PubSub.publish('Movies:data-ready', this.movies); resolve(data); }) ) }; StudioGhibli.prototype.getDirectors = function (data) { return new Promise( (resolve, reject) => { let directors = this.directors; const movies = data; movies.forEach((movie) => { for(let i = 0;i < movies.length; i++){ if(directors.indexOf(movie.director) === -1) { directors.push(movie.director) }; }; }); PubSub.publish('Directors:data-ready', directors); resolve(data) }); }; StudioGhibli.prototype.bindEvents = function (data) { PubSub.subscribe('SelectView:change', (evt) => { this.getMoviesByDirector(evt.detail, data); }) }; StudioGhibli.prototype.getMoviesByDirector = function (directorIndex, data) { const chosenDirector = this.directors[directorIndex]; const finalMovies = data.filter((movie) => { return movie.director === chosenDirector; }); PubSub.publish('Movies:data-ready', finalMovies); }; module.exports = StudioGhibli;
class Point{ constructor(xCoordinate, yCoordinate) { this.xCoordinate = xCoordinate; this.yCoordinate = yCoordinate; } toString(){ return 'Координата X: ' +this.xCoordinate+ ', Координата Y: ' + this.yCoordinate; } valueOf(){ return 'Координата X: ' +this.xCoordinate+ ', Координата Y: ' + this.yCoordinate; } toJSON(){ return { 'XCoordinate' : this.xCoordinate, 'YCoordinate' : this.yCoordinate }; } } class Vector extends Point{ constructor(name, xCoordinate, yCoordinate, zCoordinate) { super(xCoordinate, yCoordinate); this.nameVector = name; this.zCoordinate = zCoordinate; } get length(){ return Math.sqrt(Math.pow(this.xCoordinate, 2) + Math.pow(this.yCoordinate, 2) + Math.pow(this.zCoordinate, 2)); } static plus(nameVectorOne, nameVectorTwo) { let firstVectorIndex = arrayVectors.findIndex(vector => vector.Name === nameVectorOne); let secondVectorIndex = arrayVectors.findIndex(vector => vector.Name === nameVectorTwo); let vectorOne, vectorTwo; if (firstVectorIndex !== -1 && secondVectorIndex !== -1){ vectorOne = arrayVectors[firstVectorIndex]; vectorTwo = arrayVectors[secondVectorIndex]; }else{ return 0; } let newXCoordinate = parseInt(vectorOne.X) + parseInt(vectorTwo.X); let newYCoordinate = parseInt(vectorOne.Y) + parseInt(vectorTwo.Y); let newZCoordinate = parseInt(vectorOne.Z) + parseInt(vectorTwo.Z); let newNameVector = vectorOne.Name + vectorTwo.Name; return (new Vector(newNameVector, newXCoordinate, newYCoordinate, newZCoordinate)).toJSON(); } static scalar(nameVectorOne, nameVectorTwo){ let firstVectorIndex = arrayVectors.findIndex(vector => vector.Name === nameVectorOne); let secondVectorIndex = arrayVectors.findIndex(vector => vector.Name === nameVectorTwo); let vectorOne, vectorTwo; if (firstVectorIndex !== -1 && secondVectorIndex !== -1){ vectorOne = arrayVectors[firstVectorIndex]; vectorTwo = arrayVectors[secondVectorIndex]; }else{ return 0; } let multiplicationX = parseInt(vectorOne.X) * parseInt(vectorTwo.X); let multiplicationY = parseInt(vectorOne.Y) * parseInt(vectorTwo.Y); let multiplicationZ = parseInt(vectorOne.Z) * parseInt(vectorTwo.Z); return multiplicationX + multiplicationY + multiplicationZ; } toString(){ return 'Название: ' +this.nameVector; } valueOf(){ return 'Координата X: ' +this.xCoordinate+ ', Координата Y: ' +this.yCoordinate+ ', Координата Z: ' +this.zCoordinate; } toJSON() { return { 'X' : this.xCoordinate, 'Y' : this.yCoordinate, 'Z' : this.zCoordinate, 'Name' : this.nameVector }; } } let arrayVectors = []; function createVector(xCoordinate, yCoordinate, zCoordinate, nameVector) { let vector = new Vector(nameVector, xCoordinate, yCoordinate, zCoordinate); let checkNameVector = arrayVectors.find(vector => vector.Name === nameVector); if (checkNameVector !== undefined){ return arrayVectors; }else{ arrayVectors.push(vector.toJSON()); return arrayVectors; } } function getArrayVectors(){ return arrayVectors; } module.exports.createVector = createVector; module.exports.plus = Vector.plus; module.exports.scalar = Vector.scalar; module.exports.update = getArrayVectors;
import React from 'react'; import { BrowserRouter, Switch, Route } from 'react-router-dom'; import product from 'Pages/Product'; import recentList from 'Pages/RecentList'; function Routes() { return ( <BrowserRouter> <Switch> <Route exact path="/" component={product} /> <Route exact path="/recentlist" component={recentList} /> <Route exact path="/product/:id" component={product} /> </Switch> </BrowserRouter> ); } export default Routes;
/* adiciona classe js ao html, caso o js esteja desativado o conteudo continua aparecendo */ var root = document.documentElement; root.className += " js"; /* função responsável por calcular a distância entre cada elemento com a classe anime e o topo da página. .offset() retorna os valores de left e top dentro do elemento que selecionamos em $(idBox). Como queremos o topo usamos ao final o .top */ function boxTop(idBox) { var boxOffset = $(idBox).offset().top; return boxOffset; } /* se o documento já esta pronto, iniciamos um função */ $(document).ready(function () { // $target define qual elemento animar. Neste caso, todos aqueles que tem a classe .anime var $target = $(".anime"), // animationClass é a classe com as propriedades da animação que será adicionada durante o scroll animationClass = "animate__animated animate__fadeIn animate__slow", windowHeight = $(window).height(), /* windowHeight define a altura total da janela do browser. Isso serve para garantir que a tela não fique em branco. Esse valor é usado junto a comparação entre o elemento e o scroll */ offset = windowHeight - windowHeight / 4; /* Função responsável por fazer o cálculo final e definir se os elementos recebem ou não as classes de animação */ function animeScroll() { /* documentTop pega a distância do total do scroll e o topo da página, isso em relação ao $(document). */ var documentTop = $(document).scrollTop(); /* $target é o elemento que contem a classe "anime", para ser animado. Verifica cada um deles, por isso o .each() */ $target.each(function () { if (documentTop > boxTop(this) - offset) { $(this).addClass(animationClass); } }); } // Ativa a função animeScroll() para verificar assim que o documento for carregado animeScroll(); // Sempre que o usuário der scroll, ativa novamente a função animeScroll() $(document).scroll(function () { setTimeout(function () { animeScroll(); }, 150); }); });
/* @flow */ import './cdn.js' import './accounts.js' import './accounts-config.js' import './accounts-email.js' import './browser-policy.js' import './startup.js'
import { useRef, useState, useEffect, useContext } from 'react'; import { SocketContext } from './../../../contexts/SocketContext'; import classes from './Player.module.css'; const Player = (props) => { const socket = useContext(SocketContext); const videoRef = useRef(''); const videoContainerRef = useRef(''); const barRef = useRef(''); const volRef = useRef(1); const [fillWidth, setFillWidth] = useState(); const [volState, setVolState] = useState(1); console.log('player'); useEffect(() => { videoRef.current.load(); // socket.emit('getData'); }, [props.source]); const playHandler = () => { if (!props.source) return; if (videoRef.current.paused) { videoRef.current.play(); } else videoRef.current.pause(); const localData = { currentTime: videoRef.current.currentTime, isPlaying: !videoRef.current.paused, }; socket.emit('change', localData, Date.now()); }; const seekHandler = (e) => { if (!props.source) return; const barX0 = barRef.current.getBoundingClientRect().left; const barX1 = barRef.current.getBoundingClientRect().left + barRef.current.offsetWidth; if (e.clientX > barX0 && e.clientX < barX1) { const absProgress = e.clientX - barX0; const relativeProgress = absProgress / barRef.current.offsetWidth; videoRef.current.currentTime = relativeProgress * videoRef.current.duration; videoRef.current.play(); const localData = { currentTime: videoRef.current.currentTime, isPlaying: !videoRef.current.paused, }; socket.emit('change', localData, Date.now()); } }; const volumeChangeHandler = () => { videoRef.current.volume = volRef.current.value; setVolState(volRef.current.value); }; const muteHandler = () => { if (volRef.current.value === '0') { volRef.current.value = 1; setVolState(volRef.current.value); } else { volRef.current.value = 0; } volumeChangeHandler(); }; const timeUpdateHandler = () => { if (!props.source) return; const progress = videoRef.current.currentTime / videoRef.current.duration; setFillWidth(progress * barRef.current.offsetWidth + 'px'); }; socket.on('change', (serverData, actionTime) => { if (!props.source) return; const now = Date.now(); let latency = 0; if (serverData.isPlaying) { videoRef.current.play(); latency = (now - actionTime) / 10 ** 3; } else { videoRef.current.pause(); } videoRef.current.currentTime = serverData.currentTime + latency; }); socket.on('uploaded', (user, fileName) => { // video.insertAdjacentHTML( // 'beforebegin', // ` // <h4>User ${user} uploaded: ${fileName} and invites you to upload the same file.</h4> // ` // ); if (!props.source) return; videoRef.current.currentTime = 0; videoRef.current.pause(); }); const fullscreenHandler = () => { // if (!props.source) return; // const video = videoRef.current; // if (video.requestFullscreen) { // video.requestFullscreen(); // } if (!videoContainerRef.current) return; if (videoContainerRef.current.style.width !== '85%') { videoContainerRef.current.style.width = 85 + '%'; } else { videoContainerRef.current.style.width = 70 + '%'; } }; return ( <div ref={videoContainerRef} className={classes['player-container']}> <video ref={videoRef} onTimeUpdate={timeUpdateHandler} id='my-video' className='' > <source id='source-video' src={props.source} type='video/mp4' /> </video> <div className={classes['player-controls']}> <div onClick={seekHandler} ref={barRef} className={classes['progress-bar']} > <div style={{ width: fillWidth }} className={classes['progress-bar-fill']} ></div> </div> <div className={classes['player-buttons']}> <button onClick={playHandler} className={classes['btn-play']}> <i className={ videoRef.current.paused ? 'fas fa-play' : 'fas fa-pause' } ></i> </button> <div className={classes['player-controls-right']}> <div className={classes['control-volume']}> <span className={classes['volume-button']}> <i onClick={muteHandler} className={ volState !== '0' ? 'fas fa-volume-down' : 'fas fa-volume-mute' } ></i> </span> <input onChange={volumeChangeHandler} type='range' step='0.05' min='0' max='1' ref={volRef} /> </div> <button onClick={fullscreenHandler}> <i className='fas fa-expand'></i> </button> </div> </div> </div> </div> ); }; export default Player;
import React from 'react'; import store from 'store'; import { getLikes, getWhiskey, getSearches, changeFavorite } from 'api/data'; import Suggestions from 'ui/suggestions'; import UserSearches from 'ui/userSearches'; import SearchInput from 'ui/searchInput'; import { Link } from 'react-router'; import StarRating from 'ui/starRating'; import MoreButton from 'ui/moreButton'; import LikeHeart from 'ui/likeHeart'; import NoHeart from 'ui/noHeart'; import SaveSearch from 'ui/saveSearch'; require("assets/styles/userPage.scss"); require("assets/styles/likeBoxItem.scss") require('font-awesome-webpack'); var image = require("assets/images/darkerLogo.png"); var x = []; export default React.createClass({ getInitialState: function(){ return ({ showHeart: this.props.showHeart || false, likedwhiskey: [], showSearch: false, showMoreButton: false }) }, componentWillMount: function(){ this.unsubscribe = store.subscribe(function(){ var currentStore = store.getState(); this.setState({ likedwhiskey: currentStore.userReducer.likedwhiskey, showSearch: currentStore.showReducer.showSearch, showMoreButton: currentStore.showReducer.showMoreButton }) }.bind(this)); }, handleClick: function(item, e){ e.preventDefault(); e.stopPropagation(); getWhiskey(item.id); store.dispatch({ type: 'CHANGE_SHOW', show: true }) store.dispatch({ type: 'CHANGE_SHOWSEARCH', showSearch: true }) store.dispatch({ type: 'CHANGE_SHOWSEARCHITEM', showLikesSearch: false }) }, getIDs: function(){ x = this.state.likedwhiskey.map(function(data){ return data.id; }) }, getStatus: function(item){ this.getIDs(); if(x.indexOf(item) === -1){ return false; } else { return true; } }, componentWillUnmount: function(){ this.unsubscribe(); }, render: function(){ return ( <div> <div className="mainImage correctMargin"><img src={image} /></div> <div className="resultsFlex"> <div className="tempResults positionLikeBox"> {this.props.tagSearch.map(function(item, i){ return ( <div className="itemsLayout" key={i}> {this.getStatus(item.id) ? <LikeHeart item={item} /> : <NoHeart item={item} />} <Link to={"/productDetailPage/" + item.id}><div className="itemImageContainer"> <img className="itemImage" src={item.list_img_url} /> </div></Link> <div className="itemDescription"> <div className="titleDiv">{item.title}</div> <div className="textCategorys">Type/Region: <span className="priceColor">{item.region}</span></div> <div className="textCategorys" >Avg Price: <span className="priceColor">${item.price}</span></div> <StarRating rating={item.rating} /> </div> <div className="choices"> <a href="#"><div onClick={this.handleClick.bind(this, item)} className="choiceA"></div></a> <Link to={"/productDetailPage/" + item.id}><div className="choiceB">Details and Suggestions</div></Link> </div> </div> ) }.bind(this))} </div> {this.props.showMoreButton ? <MoreButton itemCount={this.props.itemCount} showSearch={this.state.showSearch} /> : ""} {this.props.showSearch ? <SaveSearch likes={this.props.likes} /> : ""} </div> </div> ) } })
$(document).ready(function () { /* |-------------------------------------------------------------------------- | ADDING RATE FUNCTION |-------------------------------------------------------------------------- | WHEN THE ADD RATE FORM SUBMIT BUTTON IS CLICKED |-------------------------------------------------------------------------- | */ $("#arform").submit(function (e) { e.preventDefault(); fade_in_loader_and_fade_out_form("loader", "arform"); rate_input = document.getElementById("rate"); if( isNaN( parseFloat(rate_input.value))){ show_notification("msg_holder", "danger", "", 'Please ensure the rate you entered is a number'); fade_out_loader_and_fade_in_form("loader", "arform"); return; } rate_input.value = parseFloat(rate_input.value).toFixed(2); var form_data = $("#arform").serialize(); fade_out_loader_and_fade_in_form("loader", "arform"); if(document.getElementById("currency_from_id").value == document.getElementById("currency_to_id").value){ show_notification("msg_holder", "danger", "", 'The currency(from) and currency(to) cannot be the same'); fade_out_loader_and_fade_in_form("loader", "arform"); return; } var bearer = "Bearer " + localStorage.getItem("worker_access_token"); send_restapi_request_to_server_from_form("post", worker_api_rates_add_rate_url, bearer, form_data, "json", add_rate_success_response_function, add_rate_error_response_function); }); /* |-------------------------------------------------------------------------- | SEARCHING FOR RATES FUNCTION |-------------------------------------------------------------------------- | WHEN THE SEARCH RATES FORM SUBMIT BUTTON IS CLICKED |-------------------------------------------------------------------------- | */ $("#search_form").submit(function (e) { e.preventDefault(); search_for_rates(0); }); /* |-------------------------------------------------------------------------- | ADDING RATE FUNCTION |-------------------------------------------------------------------------- | WHEN THE ADD RATE FORM SUBMIT BUTTON IS CLICKED |-------------------------------------------------------------------------- | */ $("#erform").submit(function (e) { e.preventDefault(); fade_in_loader_and_fade_out_form("loader", "ecform"); var form_data = $("#ecform").serialize(); var bearer = "Bearer " + localStorage.getItem("worker_access_token"); send_restapi_request_to_server_from_form("post", worker_api_currencies_edit_currency_url, bearer, form_data, "json", edit_currency_success_response_function, edit_currency_error_response_function); }); }); /******************************************************************************************************************************************** */ /******************************************************************************************************************************************** */ /******************************************************************************************************************************************** */ /******************************************************************************************************************************************** */ /******************************************************************************************************************************************** */ /******************************************************************************************************************************************** */ /* |-------------------------------------------------------------------------- | ADDING RATE RESPONSE FUNCTIONS |-------------------------------------------------------------------------- | Here is where I add a currency |-------------------------------------------------------------------------- | */ function add_rate_success_response_function(response) { show_notification("msg_holder", "success", "Success:", "Rate updated successfully"); fade_out_loader_and_fade_in_form("loader", "arform"); $('#arform')[0].reset(); } function add_rate_error_response_function(errorThrown) { fade_out_loader_and_fade_in_form("loader", "arform"); show_notification("msg_holder", "danger", "Error", errorThrown); } /* |-------------------------------------------------------------------------- | EDITING/UPDATING RATE RESPONSE FUNCTIONS |-------------------------------------------------------------------------- | Here is where I add a currency |-------------------------------------------------------------------------- | */ function edit_rate_success_response_function(response) { show_notification("msg_holder", "success", "Success:", "Currency updated successfully"); fade_out_loader_and_fade_in_form("loader", "ecform"); $('#arform')[0].reset(); } function edit_rate_error_response_function(errorThrown) { fade_out_loader_and_fade_in_form("loader", "ecform"); show_notification("msg_holder", "danger", "Error", errorThrown); } /* |-------------------------------------------------------------------------- | SEARCHING FOR RATES RESPONSE FUNCTIONS |-------------------------------------------------------------------------- |-------------------------------------------------------------------------- | */ function search_for_rates_success_response_function(response) { fade_out_loader_and_fade_in_form("loader", "search_form"); if(response.data.data.length > 0){ show_log_in_console("response.data.prev_page_url : " + response.data.prev_page_url); show_log_in_console("response.data.next_page_url : " + response.data.next_page_url); if(response.data.prev_page_url != null){ $('#pagination_buttons').append( '<a id="previous_btn" class="btn btn-default" data-link = "' + response.data.prev_page_url + '&kw=' + response.kw + '" onclick="search_for_rates(1)"><i class="material-icons">keyboard_arrow_left</i></a>' ); } if(response.data.next_page_url != null){ $('#pagination_buttons').append( '<a id="next_btn" class="btn btn-default" data-link = "' + response.data.next_page_url + '&kw=' + response.kw + '" onclick="search_for_rates(2)"><i class="material-icons">keyboard_arrow_right</i></a>' ); } for (let index = 0; index < response.data.data.length; index++) { const element = response.data.data[index]; $('#table_body_list').append( '<tr style="cursor: pointer;" class="rate"><td>' + element.bureau_rate_id + '</td><td>' + element.currency_full_name + '</td><td>' + element.currency_to_full_name + '</td><td>' + element.rate + ' : 1</td><td>' + element.updated_at + '</td><td>' + element.worker_surname + " " + element.worker_firstname + '</td>' + '<td>' + '<div id="holder_' + element.bureau_rate_id + '" class="input-group">' + '<input id="input_pin_' + element.bureau_rate_id + '" type="password" class="form-control" placeholder="Pin" aria-label="Pin">' + '<i style="cursor:pointer;" data-currency_from_id="' + element.currency_from_id + '" data-currency_to_id="' + element.currency_to_id + '" data-rateid="' + element.bureau_rate_id + '" onclick="update_rate(this)" class="material-icons">keyboard_arrow_right</i>' + '</div>' + '<div style="display:none;" id="loader_new_rate_' + element.bureau_rate_id + '" class="customloader"></div>' + '</td>' + '</tr>' ); } } else { show_notification("msg_holder", "danger", "", "No rates found"); } } function search_for_rates_error_response_function(errorThrown) { show_notification("msg_holder", "danger", "Error", errorThrown); fade_out_loader_and_fade_in_form("loader", "search_form"); } /* |-------------------------------------------------------------------------- | SEARCHING FOR RATES FUNCTION |-------------------------------------------------------------------------- |-------------------------------------------------------------------------- | */ function search_for_rates(url_fetch_type) { if(url_fetch_type == 1){ var url = document.getElementById("previous_btn").getAttribute("data-link"); } else if(url_fetch_type == 2){ var url = document.getElementById("next_btn").getAttribute("data-link"); } else { var url = worker_api_rates_search_for_rates_url + document.getElementById("search_form_input").value; } fade_in_loader_and_fade_out_form("loader", "search_form"); var bearer = "Bearer " + localStorage.getItem("worker_access_token"); document.getElementById("table_body_list").innerHTML = ""; document.getElementById("pagination_buttons").innerHTML = ""; show_log_in_console("url: " + url); send_restapi_request_to_server_from_form("get", url, bearer, "", "json", search_for_rates_success_response_function, search_for_rates_error_response_function); } /* |-------------------------------------------------------------------------- | GETTING THE LIST OF ALL CURRENCIES RESPONSE FUNCTIONS |-------------------------------------------------------------------------- |-------------------------------------------------------------------------- | */ function get_all_currencies_success_response_function(response) { fade_out_loader_and_fade_in_form("loader", "arform"); if(response.data.length > 0){ for (let index = 0; index < response.data.length; index++) { const element = response.data[index]; url = host + "/worker/rates/edit/" + element.currency_id; if(element.currency_flagged == 0){tradable = "Yes";} else { tradable = "No"; } $('#currency_from_id').append( '<option value="' + element.currency_id + '">' + element.currency_full_name + '</option>' ); $('#currency_to_id').append( '<option value="' + element.currency_id + '">' + element.currency_full_name + '</option>' ); } $('#submit_button_add_rate_form').append( '<button type="submit" class="btn btn-primary pull-right">Add</button>' ); } else { show_notification("msg_holder", "danger", "", "No currencies found"); } } function get_all_currencies_error_response_function(errorThrown) { show_notification("msg_holder", "danger", "Error", errorThrown); } function get_all_currencies() { fade_in_loader_and_fade_out_form("loader", "arform"); var bearer = "Bearer " + localStorage.getItem("worker_access_token"); send_restapi_request_to_server_from_form("get", worker_api_currencies_get_currency_list_url, bearer, "", "json", get_all_currencies_success_response_function, get_all_currencies_error_response_function); } /* |-------------------------------------------------------------------------- | GETTING THE LIST OF RATES FOR A SPECIFIC PAGE RESPONSE FUNCTIONS |-------------------------------------------------------------------------- |-------------------------------------------------------------------------- | */ function get_rates_for_page_success_response_function(response) { fade_out_loader_and_fade_in_form("loader", "list_table"); if(response.data.data.length > 0){ for (let index = 0; index < response.data.data.length; index++) { const element = response.data.data[index]; $('#table_body_list').append( '<tr style="cursor: pointer;" class="rate"><td>' + element.bureau_rate_id + '</td><td>' + element.currency_full_name + '</td><td>' + element.currency_to_full_name + '</td><td>' + element.rate + ' : 1</td><td>' + element.updated_at + '</td><td>' + element.worker_surname + " " + element.worker_firstname + '</td>' + '<td>' + '<div id="holder_' + element.bureau_rate_id + '" class="input-group">' + '<input id="input_pin_' + element.bureau_rate_id + '" type="password" class="form-control" placeholder="Pin" aria-label="Pin">' + '<i style="cursor:pointer;" data-currency_from_id="' + element.currency_from_id + '" data-currency_to_id="' + element.currency_to_id + '" data-rateid="' + element.bureau_rate_id + '" onclick="update_rate(this)" class="material-icons">keyboard_arrow_right</i>' + '</div>' + '<div style="display:none;" id="loader_new_rate_' + element.bureau_rate_id + '" class="customloader"></div>' + '</td>' + '</tr>' ); } document.getElementById("next_btn").style.display = ""; } else { show_notification("msg_holder", "danger", "", "No rates found"); } } function get_rates_for_page_error_response_function(errorThrown) { show_notification("msg_holder", "danger", "Error", errorThrown); } /* |-------------------------------------------------------------------------- | GETTING THE LIST OF RATES FUNCTIONS |-------------------------------------------------------------------------- |-------------------------------------------------------------------------- | */ function get_rates_for_page(page_number) { fade_in_loader_and_fade_out_form("loader", "list_table"); var bearer = "Bearer " + localStorage.getItem("worker_access_token"); url = worker_api_rates_get_rate_list_url + page_number; send_restapi_request_to_server_from_form("get", url, bearer, "", "json", get_rates_for_page_success_response_function, get_rates_for_page_error_response_function); } /* |-------------------------------------------------------------------------- | UPDATE RATE RESPONSE FUNCTIONS |-------------------------------------------------------------------------- |-------------------------------------------------------------------------- | */ function update_rate_success_response_function(response) { show_notification("msg_holder", "success", "Success:", "Rate updated successfully"); } function update_rate_error_response_function(errorThrown) { show_notification("msg_holder", "danger", "Error", errorThrown); } /* |-------------------------------------------------------------------------- | UPDATING RATE FUNCTIONS |-------------------------------------------------------------------------- |-------------------------------------------------------------------------- | */ function update_rate(obj) { bureau_rate_id = obj.getAttribute("data-rateid"); currency_from_id = obj.getAttribute("data-currency_from_id"); currency_to_id = obj.getAttribute("data-currency_to_id"); pin_input_obj = document.getElementById("input_pin_" + bureau_rate_id); loader_obj = document.getElementById("loader_new_rate_" + bureau_rate_id); holder_obj = document.getElementById("holder_" + bureau_rate_id); none = "none"; if(pin_input_obj.value == null){ show_notification("msg_holder", "danger", "", "Please enter your pin."); return; } if(pin_input_obj.value.trim() == ""){ show_notification("msg_holder", "danger", "", "Please enter your pin."); return; } rate = prompt("Please enter the new rate", ""); if(rate == null){ show_notification("msg_holder", "danger", "", "Please enter the new stock. If the alertbox did not show asking for the new rate, please go to browser settings and enable popups for this website."); return; } if(rate.trim() == ""){ show_notification("msg_holder", "danger", "", "Please enter the new stock. If the alertbox did not show asking for the new rate, please go to browser settings and enable popups for this website."); return; } if(isNaN(parseFloat(rate))){ show_notification("msg_holder", "danger", "", 'Please ensure the rate you entered is a number'); return; } rate = parseFloat(rate).toFixed(2); fade_in_loader_and_fade_out_form("loader_new_rate_" + bureau_rate_id, "holder_" + bureau_rate_id); var form_data = "currency_from_id=" + currency_from_id + "&currency_to_id=" + currency_to_id + "&rate=" + rate + "&worker_pin=" + pin_input_obj.value; var bearer = "Bearer " + localStorage.getItem("worker_access_token"); window.setTimeout(loader_obj.style.display = none, 5000); show_log_in_console("form_data: " + form_data); pin_input_obj.value=""; send_restapi_request_to_server_from_form("post", worker_api_rates_add_rate_url, bearer, form_data, "json", update_rate_success_response_function, update_rate_error_response_function); }
var pubSubSubscriber = pubSubHubbub.createServer(options); var topic = "http://testetstetss.blogspot.com/feeds/posts/default"; var hub = "http://pubsubhubbub.appspot.com/"; pubSubSubscriber.on("subscribe", function(data){ console.log(data.topic + " subscribed"); }); pubSubSubscriber.listen(port); pubsub.on("listen", function(){ pubSubSubscriber.subscribe(topic, hub, function(err){ if(err){ console.log("Failed subscribing"); } }); });
module.exports = function argsort(d) { let ind = [] let tmp for (i = 0; i < d.length; i++) { ind[i] = i } for (i = 0; i < d.length; i++) { for (j = 0; j < d.length-1; j++) { if (d[j] > d[j+1]) { tmp = d[j]; d[j] = d[j+1]; d[j+1] = tmp; tmp = ind[j]; ind[j] = ind[j+1]; ind[j+1] = tmp; } } } return ind; }
import {Component} from 'react' import './index.css' class ShowHide extends Component { state = { isFirstNameVisible: false, isLastNameVisible: false, } onChangeStatusOfFirstName = () => { this.setState(prevState => ({ isFirstNameVisible: !prevState.isFirstNameVisible, })) } onChangeStatusOfLastName = () => { this.setState(prevState => ({ isLastNameVisible: !prevState.isLastNameVisible, })) } render() { const {isFirstNameVisible, isLastNameVisible} = this.state return ( <div className="app-container"> <h1 className="app-heading">Show/Hide</h1> <div className="show-hide-container"> <div className="name-block"> <button type="button" className="button" onClick={this.onChangeStatusOfFirstName} > Show/Hide Firstname </button> {isFirstNameVisible && <p className="description name">Joe</p>} </div> <div className="name-block"> <button type="button" className="button" onClick={this.onChangeStatusOfLastName} > Show/Hide Lastname </button> {isLastNameVisible && <p className="description name">Jonas</p>} </div> </div> </div> ) } } export default ShowHide
import {change} from 'redux-form' import { addProduct, deleteProduct, changeCompany, submitOrder } from '../../../modules/Orders' export default { handleSubmit: ({dispatch}) => values => { dispatch(addProduct(values)) dispatch(change('formNewOrder', 'quantity', '')) dispatch(change('formNewOrder', 'product', '')) }, deleteProduct: ({dispatch}) => id => dispatch(deleteProduct(id)), changeCompany: ({dispatch}) => e => dispatch(changeCompany(e.target.value)), submitOrder: ({dispatch, order_items, order_company}) => () => dispatch(submitOrder({order_items, order_company})) }
module.exports = [ { type: 'list', name: 'preset', message: 'Select from one of the following presets to scaffold your Vue project:', choices: [ { name: 'Base (A basic Vuetify application)', value: 'base' }, ], default: 'base', } ]
const keyMirror = require('keymirror'); const api = require('../lib/api'); const log = require('../lib/log'); const Status = keyMirror({ FETCHED: null, NOT_FETCHED: null, FETCHING: null, ERROR: null }); const getInitialState = () => ({ infoStatus: Status.NOT_FETCHED, title: '', description: '', openToAll: false, commentingAllowed: false, thumbnail: '', followers: 0, rolesStatus: Status.NOT_FETCHED, manager: false, curator: false, follower: false, invited: false }); const studioReducer = (state, action) => { if (typeof state === 'undefined') { state = getInitialState(); } switch (action.type) { case 'SET_INFO': return { ...state, ...action.info }; case 'SET_ROLES': return { ...state, ...action.roles }; case 'SET_FETCH_STATUS': if (action.error) { log.error(action.error); } return { ...state, [action.fetchType]: action.fetchStatus }; default: return state; } }; const setFetchStatus = (fetchType, fetchStatus, error) => ({ type: 'SET_FETCH_STATUS', fetchType, fetchStatus, error }); const setInfo = info => ({ type: 'SET_INFO', info: info }); const setRoles = roles => ({ type: 'SET_ROLES', roles: roles }); const getInfo = studioId => (dispatch => { dispatch(setFetchStatus('infoStatus', Status.FETCHING)); api({uri: `/studios/${studioId}`}, (err, body, res) => { if (err || typeof body === 'undefined' || res.statusCode !== 200) { dispatch(setFetchStatus('infoStatus', Status.ERROR, err)); return; } dispatch(setFetchStatus('infoStatus', Status.FETCHED)); dispatch(setInfo({ title: body.title, description: body.description, openToAll: body.open_to_all, commentingAllowed: body.commenting_allowed, updated: new Date(body.history.modified), followers: body.stats.followers })); }); }); const getRoles = (studioId, username, token) => (dispatch => { dispatch(setFetchStatus('rolesStatus', Status.FETCHING)); api({ uri: `/studios/${studioId}/users/${username}`, authentication: token }, (err, body, res) => { if (err || typeof body === 'undefined' || res.statusCode !== 200) { dispatch(setFetchStatus('rolesStatus', Status.ERROR, err)); return; } dispatch(setFetchStatus('rolesStatus', Status.FETCHED)); dispatch(setRoles({ manager: body.manager, curator: body.curator, following: body.following, invited: body.invited })); }); }); module.exports = { getInitialState, studioReducer, Status, getInfo, getRoles };
import PostMessage from '../models/postMessages.js'; import mongoose from 'mongoose'; export const getPosts = async (req, res) =>{ const {page} = req.query try{ const LIMIT = 8; const startIndex = (Number(page) - 1) * LIMIT; const total = await PostMessage.countDocuments({}); const posts = await PostMessage.find().sort({_id : -1}).limit(LIMIT).skip(startIndex) res.status(200).json({data: posts, currentPage: Number(page), totalPage: Math.ceil(total/LIMIT)}) } catch (error){ res.status(400).json({message : error.message}) } } export const getPostDetail = async(req, res) =>{ const {id} = req.params // if(!mongoose.Types.ObjectId.isValid(id)) return res.status(404).send('No post with that Id') try { const post = await PostMessage.findById(id) res.json(post) } catch (error) { console.log(error) } } export const getPostsBySearch = async(req, res) =>{ const {q , tags} = req.query; const title = new RegExp(q, 'i') try { const posts =await PostMessage.find({$or: [ {title}, {tags: {$in: tags.split(',')}}]}) res.json(posts) } catch (error) { console.log(error) } } export const createPost = async (req, res) =>{ const post = req.body; console.log(req.userId) try{ const newPost = await new PostMessage({...post, creator: req.userId, createdAt: new Date().toISOString()}).save() res.status(201).json(newPost) }catch (error){ res.status(409).json({message: error.message}) } } export const updatePost = async (req, res) =>{ const {id : _id} = req.params; const post = req.body if(!mongoose.Types.ObjectId.isValid(_id)) return res.status(404).send('No post with that Id') try { const updatedPost = await PostMessage.findByIdAndUpdate(_id, {...post, createdAt: new Date().toISOString(), _id}, {new: true}) res.json(updatedPost); } catch (error) { res.status(409).json({message: error.message}) } } export const deletePost = async(req, res) =>{ const {id} = req.params; try { const deletedPost = await PostMessage.findByIdAndDelete(id); res.send(deletedPost) } catch (error) { console.log(error.message) } } export const likePost = async(req,res) =>{ const {id} = req.params if(!req.userId) return res.send('User is not authenticated!') try { const post = await PostMessage.findById(id); const index = post.likes.findIndex(id => id === String(req.userId)) if(index === -1){ post.likes.push(req.userId) }else { post.likes = post.likes.filter(id => id !== String(req.userId)) } const updatedPost = await PostMessage.findByIdAndUpdate(id, {...post, likes: post.likes, id}, {new : true}) res.send(updatedPost) } catch (error) { console.log(error.message) } } export const commentPost = async(req, res) =>{ const {id: _id} = req.params const {comment} = req.body try{ const post = await PostMessage.findById(_id); post.comments.push(comment) const newPost = await PostMessage.findByIdAndUpdate(_id, post, {new : true}) res.json(newPost) } catch(error) { console.log(error) } }
var name = "Jenne"; function sayHello() { console.log("Hello " + name); } (function(window){ var jenneGreeter = {}; jenneGreeter.name = "Jenne" jenneGreeter.sayHello = function sayHello() { console.log("Hello " + jenneGreeter.name); } var greeting = "Hello "; jenneGreeter.sayHello = function sayHello() { console.log(greeting + jenneGreeter.name); } window.jenneGreeter = jenneGreeter; })(window);
const { SlashCommandBuilder } = require('discord.js'); const Twitter = require('twitter'); module.exports = { data: new SlashCommandBuilder() .setName('tweet') .setDescription('Post tweet album images.') .addStringOption((option) => option.setName('url').setDescription('URL of tweet.').setRequired(true) ), async execute(interaction) { try { // Twitter API keys var client = new Twitter({ consumer_key: process.env.twitter_consumer_key, consumer_secret: process.env.twitter_consumer_secret, access_token_key: process.env.twitter_access_token_key, access_token_secret: process.env.twitter_access_token_secret, }); // split tweet URL by slash const url = interaction.options.getString('url').split('/'); // retrieve tweet information, tweet's unique id is last variable in args array client.get( 'statuses/show', { id: url[url.length - 1], tweet_mode: 'extended' }, async (error, tweets) => { let message = interaction.options.getString('url') + '\n'; if (!error) { // check if any media objects present if (tweets.extended_entities.media.length == 0) { message = 'There are no photos in this tweet silly!'; } else { // loop through and print media objects for (var i = 0; i < tweets.extended_entities.media.length; i++) { message += tweets.extended_entities.media[i].media_url + '\n'; } } } await interaction.reply(message); } ); } catch (err) { console.log(err); } }, };
define([ 'jquery', 'underscore', 'backbone' ], function($, _, Backbone){ window.MapView = Backbone.View.extend({ tagName: 'canvas', className: 'gameMap', initialize: function() { //console.log('maptime') _.bindAll(this, 'render'); this.collection.bind('change', this.render); this.collection.bind('change:population', this.render); //this.template = _.template($('#map-template').html()) this.collection.bind('reset', this.render); }, render: function(){ var Collection = this.collection; //$(this.el).html(this.template({})); var context = document.getElementById("canvasId").getContext("2d"); // Draw Territories var linewidth = gameStats.get('linewidth'); var width = 40; // Territory Width var height = 30; // Territory Height this.collection.each(function(territory){ var x = territory.get('x')*width + .5*(territory.get('y')%2)*width var y = territory.get('y')*height // Draw a path context.clearRect(x,y,width,height) context.globalCompositeOperation = 'source-over'; context.globalAlpha = 0.1; context.fillStyle = territory.get('color'); context.fillRect(x+linewidth, y+linewidth, width-linewidth*2, height-linewidth*2); // Fill the path context.globalAlpha = 1; context.strokeStyle = territory.get('maxColor'); context.lineWidth = linewidth; context.strokeRect(x+linewidth, y+linewidth, width-linewidth*2, height-linewidth*2); //add text context.fillStyle = 'black'; context.fillText(territory.get('population'),x+10, y+13) }); return this; } }); return window.MapView });
/** * Description of utils. * * * @author: Ilya Petrushenko <ilya.petrushenko@yandex.ru> * @since: 24.01.19 9:16 */ import moment from 'moment' import { getFirstAllowedDay, today, getDate, } from './utils' describe('Test utils functions', () => { it('test getFirstAllowedDay', () => { const booked = ['2019-03-25', '2019-03-26', '2019-03-28'] const first = getFirstAllowedDay(booked, '2019-03-25') expect(first.isSame('2019-03-27')).toBe(true) expect(first.isSame('2019-03-25')).toBe(false) }) it('test today', () => { let todayValue = today() let todayCheck = moment().format('YYYY-MM-DD') expect(todayValue).toBe(todayCheck) todayValue = today('DD-MM-YYYY') todayCheck = moment().format('DD-MM-YYYY') expect(todayValue).toBe(todayCheck) }) it('test getDate', () => { let date = getDate('2019-05-01') let dateCheck = new Date(2019, 4, 1) expect(date).toEqual(dateCheck) }) })
import { menuHttp, linkHttp, tagHttp, dailyHttp, postsHttp } from './resource' export default { getMenu: (id) => menuHttp.get({id: id}), getLink: () => linkHttp.get(), getTag: () => tagHttp.get(), getDaily: (data) => dailyHttp.get({start_id: data.start_id}), getPosts: (data) => postsHttp.get({id: data.id, menu_id: data.menu_id, top: data.top, start_id: data.start_id}) }
function login() { let user_id = $("#user").val(); let user_pw = $("#password").val(); $.ajax({ type: "POST", url: "/login/check", data: { userid_give: user_id, userpw_give: user_pw }, success: function (response) { if (response['user_data'] == null) { alert("아이디/비밀번호를 확인하세요"); } else { window.sessionStorage.setItem("login_check","good") window.location.href = "/"; } }, }); } function skipToMain() { let alert_text = "로그인하지 않는 경우 일부 기능이 제한됩니다.\n계속 진행하시겠습니까?"; if (confirm(alert_text) == true) { //확인 location.href = "/"; } else { //취소 return; } }
import React, { Component } from 'react'; import { View, Text, Dimensions, Image ,StyleSheet,TouchableOpacity} from 'react-native'; import { Entypo, AntDesign, FontAwesome5, FontAwesome, Feather, EvilIcons, MaterialCommunityIcons, Octicons} from '@expo/vector-icons'; const width = Dimensions.get('window').width const height = Dimensions.get("window").height const cellHeight = height * 0.6; const cellWidth = width; const viewabilityConfig = { itemVisiblePercentThreshold: 80, }; import settings from '../appSettings'; import * as Animatable from 'react-native-animatable'; const fontFamily = settings.fontFamily import { Video } from 'expo-av'; import { TouchableWithoutFeedback } from 'react-native-gesture-handler'; const lightTheme = settings.lightTheme const darkTheme = settings.darkTheme export default class VideoPost extends React.PureComponent{ constructor(props) { super(props); this.state = { like:false, muted:false, play:false, playBackStatus:null, totalDuration:null }; } componentWillUnmount() { if (this.video) { this.video.unloadAsync(); } } async play() { const status = await this.video.getStatusAsync(); if (status.isPlaying) { return; } this.setState({ totalDuration: this.milliconverter(status.durationMillis)}) this.setState({ play: true }) return this.video.playAsync(); } pause() { if (this.video) { this.setState({ play: false }) this.video.stopAsync(); } } handleMute =async()=>{ let status = await this.video.getStatusAsync() if (status.isMuted){ this.video.setIsMutedAsync(false) this.setState({muted:false}) }else{ this.video.setIsMutedAsync(true) this.setState({ muted: true }) } } milliconverter = (millis) => { if (millis) { var minutes = Math.floor(millis / 60000); var seconds = ((millis % 60000) / 1000).toFixed(0); return minutes + ":" + (seconds < 10 ? '0' : '') + seconds } } render() { let {item} = this.props let theme if(this.props.theme =="dark"){ theme =darkTheme }else{ theme =lightTheme } return ( <View style={{ height: height * 0.7 }}> <View style={{ height: height * 0.075, }}> <View style={{ flexDirection: "row" }}> <View style={{ flex: 0.2, alignItems: "center", justifyContent: 'center' }}> <Image style={{ height: 50, width: 50, borderRadius: 25 }} source={require('../assets/unknownPerson.jpg')} /> </View> <View style={{ marginLeft: 10, justifyContent: 'center', flex: 0.7 }}> <View> <Text style={[styles.text,{color:theme.TextColor}]}>Stanley</Text> </View> <View> <Text style={[styles.text,{color:theme.TextColor}]}>PES UNIVERSITY</Text> </View> <View style={{ flexDirection: "row" }}> <View style={{ alignItems: 'center', justifyContent: "center" }}> <Entypo name="back-in-time" size={15} color={theme.secondaryColor} /> </View> <View style={{ marginLeft: 5 }}> <Text style={[styles.text,{color:theme.TextColor}]} >just now</Text> </View> </View> </View> </View> </View> <TouchableWithoutFeedback onPress={()=>{ this.handleMute() }} > <Video ref={(ref) => { this.video = ref; }} isLooping={true} onPlaybackStatusUpdate={(status) => { this.setState({ playBackStatus: this.milliconverter(status.positionMillis)})}} source={{ uri: item.media }} shouldPlay={false} resizeMode="cover" style={{ height: height * 0.5, width }} /> <View style={{ position: "absolute", bottom: 20, right: 20}}> { this.state.muted ? <FontAwesome5 name="volume-mute" size={24} color="#fff" /> : <Octicons name="unmute" size={24} color="#fff" /> } </View> <View style={{ position: "absolute", top: 20, right: 20 }}> { this.state.play ? <View> <Text style={[styles.text,{color:"#fff"}]}>{this.state.playBackStatus||"0:00"}/{this.state.totalDuration}</Text> </View> : <FontAwesome5 name="play" size={24} color="#fff" /> } </View> </TouchableWithoutFeedback> <View style={{flex:1,}}> <View style={{ flex: 0.5, flexDirection:"row"}}> <View style={{ flex: 0.3, alignItems: "center", justifyContent: "space-around", flexDirection: 'row', }}> <View style={{ flexDirection: "row" }}> {!this.state.like ? <TouchableOpacity style={{ alignItems: "center", justifyContent: 'center' }} onPress={() => { this.setState({ like: true }) }} > <AntDesign name="hearto" size={24} color={theme.secondaryColor} /> </TouchableOpacity> : <Animatable.View animation={"bounceIn"} > <TouchableOpacity onPress={() => { this.setState({ like: false }) }} > <AntDesign name="heart" size={24} color="red" /> </TouchableOpacity> </Animatable.View>} </View> <TouchableOpacity style={{ flexDirection: "row" }}> <View style={{ alignItems: "center", justifyContent: 'center' }}> <FontAwesome5 name="comment" size={24} color={theme.secondaryColor} /> </View> </TouchableOpacity> <TouchableOpacity style={{ flexDirection: "row" }}> <View style={{ alignItems: "center", justifyContent: 'center' }}> <Feather name="send" size={24} color={theme.secondaryColor} /> </View> </TouchableOpacity> </View> </View> <View> <Text style={[styles.text,{marginLeft:10,color:theme.TextColor}]}>50 likes</Text> </View> <View style={{ flex:0.4, justifyContent: "center" }}> <Text style={[styles.text, { marginLeft: 10 ,color:theme.TextColor}]}>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</Text> </View> </View> </View> ); } } const styles = StyleSheet.create({ text: { fontFamily }, boxWithShadow: { shadowColor: '#000', shadowOffset: { width: 0, height: 1 }, shadowOpacity: 0.8, shadowRadius: 2, elevation: 5 } })
import {expect} from 'chai' //import Item from './Item' import React from 'react' //import ReactTestUtils from 'react-addons-test-utils' /*const renderer = ReactTestUtils.createRenderer(); renderer.render( <Item id={"123"} text={"text"} active={true} toggleActive={() => { console.log("toggleActive") }} changeText={() => { console.log("changeText") }} removeTodo={() => { console.log("removeTodo") }} /> ); const result = renderer.getRenderOutput();*/ /* console.log(result.props.children); result.props.children[1].props.onClick();*/ /* expect(result.type).toBe('div'); expect(result.props.children).toEqual([ <span className="heading">Title</span>, <Subcomponent foo="bar" /> ]);*/
let placeBanner = () => { document.querySelector('#vb-nome').innerHTML = window.localStorage.getItem('bannerNome'); document.querySelector('#vb-banner').innerHTML = `<img src="${window.localStorage.getItem('bannerUrl')}">`; window.localStorage.removeItem('bannerNome'); window.localStorage.removeItem('bannerUrl'); } document.addEventListener('DOMContentLoaded', () => { placeBanner(); });
import React from "react"; import { StyleSheet, Text, TouchableOpacity, View } from "react-native"; import { MaterialCommunityIcons } from "@expo/vector-icons"; const NewListingButton = ({ onPress }) => { return ( <TouchableOpacity onPress={onPress}> <View style={styles.container}> <MaterialCommunityIcons name="plus-circle" color="white" size={30} /> </View> </TouchableOpacity> ); }; export default NewListingButton; const styles = StyleSheet.create({ container: { backgroundColor: "green", height: 76, width: 76, borderRadius: 38, justifyContent: "center", alignItems: "center", bottom: 30, borderWidth: 8, borderColor: "white", }, });
// Đăng nhập export const DANG_NHAP = 'DANG_NHAP'; // Đăng ký export const DANG_KY = 'DANG_KY'; // lưu lại navigation export const KHOI_DONG_APP = 'KHOI_DONG_APP'; /* Quản lý thành viên */ // Đếm số thành viên export const DEM_SO_THANH_VIEN = 'DEM_SO_THANH_VIEN'; // Thêm thành viên khi chọn số người export const THEM_SO_THANH_VIEN = 'THEM_SO_THANH_VIEN'; // lấy thông tin thành viên export const LAY_THONG_TIN_THANH_VIEN = 'LAY_THONG_TIN_THANH_VIEN'; // Cập nhật thông tin thành viên export const CAP_NHAT_THONG_TIN_CALO_THANH_VIEN = 'CAP_NHAT_THONG_TIN_CALO_THANH_VIEN'; // Quản lý calo export const CHON_TAB_THANH_VIEN = 'CHON_TAB_THANH_VIEN'; export const LAY_THONG_TIN_CALO_THANH_VIEN = 'LAY_THONG_TIN_CALO_THANH_VIEN'; /* Thực đơn */ export const LAY_THUC_DON = 'LAY_THUC_DON'; // chọn ngày để lấy thực đơn export const CHON_NGAY_THUC_DON = 'CHON_NGAY_THUC_DON'; // Lưu bữa ăn export const CHON_BUA_AN = 'CHON_BUA_AN'; //#region export const CHON_THANH_VIEN = 'CHON_THANH_VIEN'; //#endregion
export default () => { const $btn = $('.js-megamenu-toggle') const openMenu = function() { $(this) .children('.js-megamenu-body') .addClass('is-show') } const closeMenu = function() { $(this) .children('.js-megamenu-body') .removeClass('is-show') } $btn.hover(openMenu, closeMenu) var scrollbar_width = window.innerWidth - document.body.scrollWidth // 固定スクロールバーのとき(オーバーレイでない) // if (scrollbar_width > 0) { // $('.js-scrollbar').addClass('is-scrollbar') // スクロールバーの幅が17pxでないとき // if (scrollbar_width !== 17) { // $('.p-gnavi__body').css('margin-right', '-' + scrollbar_width + 'px') // } // } }
import * as ActionTypes from './ActionTypes'; export const Tasks = (state = { isLoading: true, errMess: null, tasks: [] }, action) => { switch(action.type) { case ActionTypes.ADD_TASK: const newTask = action.payload; return {...state, tasks: state.tasks.concat(newTask)}; case ActionTypes.ADD_TASKS: return {...state, isLoading: false, errMess: null, tasks: action.payload}; case ActionTypes.GET_SINGLE: return { ...state, fetching: true, task: action.payload }; case ActionTypes.UPDATE_TASK: return {...state, isLoading: false, errMess: null, task: action.payload}; case ActionTypes.TASKS_LOADING: return {...state, isLoading: true, errMess: null, tasks: null}; case ActionTypes.TASKS_FAILED: return {...state, isLoading: false, errMess: action.payload, tasks: null}; default: return state; } };
import React from 'react'; import './SeatPlan.scss'; export default function SeatPlan() { return ( <div> SeatPlan </div> ) }
// Variables // Multiple line variables const firstName = "Vladimir"; const myAge = 35; const yourAge = 34; const isNice = true; let isUndefined; let nullType = null; let myArray = [1, 2, 3]; console.log(firstName); console.log(myAge); console.log(isNice); console.log(isUndefined); console.log(nullType); console.log(myArray); console.log(`I am ${myAge} years old`); console.log(`You are ${yourAge} years old`); // Single line variables let lastName = "Striber", maritalStatus = "married", numberOfKids = 2, country = "Serbia", city = "Novi Sad", isAthlete = true, isBadPerson = false; console.log( "last name: ", lastName,";", "marital status: ", maritalStatus,";", "number of kids: ", numberOfKids,";", "country: ", country,";", "city: ", city,";", "is athlete: ", isAthlete,";", "is bad person: ", isBadPerson,";" );
import React,{useEffect, useState} from "react" import "./insert-item-styles.css" export default function InsertItem() { const [maxItemNo, setMaxItemNo] = useState([]); useEffect(() => { async function fetchData() { const res = await fetch("http://localhost:5000/maxitemno/availitems/"); res .json() .then((res) => setMaxItemNo(res[0])) } fetchData(); }, []); // Assign item no automatically, q_sold has to be made zero // name, category, price return( <div className="insert-item-background"> <div className="insert-item"> <form method="post" action="http://localhost:5000/admin/insertitem" className="insert-item-form"> <label className="new-item-id-text" htmlFor="itemno">Assigned ID to the new item will be: </label> <input className="new-item-id" id="itemno" name="itemno" type="text" value={maxItemNo.lastitem+1}/> <label className="item-form-label" htmlFor="item-name">Name</label> <input className="item-form-input" id="item-name" name="itemname" type="text" placeholder="Enter item name here.."/> <label className="item-form-label" htmlFor="item-category">Category</label> <input className="item-form-input" id="item-category" name="itemcategory" type="text" placeholder="Enter item category here.."/> <label className="item-form-label" htmlFor="item-price">Price</label> <input className="item-form-input" id="item-price" name="itemprice" type="text" placeholder="Enter item price here.."/> <input type="submit" className="insert-item-btn" value="Add item"/> </form> </div> {/* http://localhost:5000/admin/insertitem?itemno=150&itemname=Vada Pav&itemcategory=SNACKS&itemprice=10 */} </div> ) }
import React from 'react'; import Encounter from '../connectors/Encounter'; import Welcome from '../components/Welcome'; import Revelations from '../connectors/Revelations' class DisplayContainer extends React.Component { constructor(props) { super(props); } componentDidMount() { fetch('/api/v1/users.json', { credentials: 'same-origin', method: 'GET', headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(data => { this.props.dispatch({type: 'SWITCH_USER', user: data.user}) }); }; render() { let display; let overlay; let dclass; if(this.props.user.id) { display = <Encounter /> } else { display = <Welcome /> }; if(this.props.toggles.includes("revelations")) { overlay = <Revelations /> dclass = "blur" } return( <div> <div className={dclass}> {display} </div> {overlay} </div> ); }; }; export default DisplayContainer;
// Generated from grammars/Calculator.g4 by ANTLR 4.7.1 // jshint ignore: start const CalculatorVisitor = require('./lib/CalculatorVisitor').CalculatorVisitor; class Visitor extends CalculatorVisitor{ // Visit a parse tree produced by CalculatorParser#calculator. start(ctx) { return this.visitCalculator(ctx); } visitCalculator(ctx) { return ctx.expr(0).accept(this); }; visitExpression(context) { return context.accept(this); }; // Visit a parse tree produced by CalculatorParser#Parenthesis. visitParenthesis(ctx) { return this.visitExpression(ctx.expr(0)); }; // Visit a parse tree produced by CalculatorParser#Number. visitNumber(ctx) { return Number(ctx.getText().replace(',', '.')); }; // Visit a parse tree produced by CalculatorParser#Negate. visitNegate(ctx) { return -1 * this.visitExpression(ctx.expr(0)); }; // Visit a parse tree produced by CalculatorParser#MultiplyDivide. visitMultiplyDivide(ctx) { if (ctx.op.text === '*') { return this.visitExpression(ctx.expr(0)) * this.visitExpression(ctx.expr(1)); } else { let divisor = this.visitExpression(ctx.expr(1)); if (divisor !== 0) { return this.visitExpression(ctx.expr(0)) / divisor; } return NaN; } }; // Visit a parse tree produced by CalculatorParser#AddSubtract. visitAddSubtract(ctx) { if (ctx.op.text === '+'){ return (this.visitExpression(ctx.expr(0)) + this.visitExpression(ctx.expr(1))); }else{ return (this.visitExpression(ctx.expr(0)) - this.visitExpression(ctx.expr(1))); } }; } module.exports = Visitor;
'use strict' const fp = require('fastify-plugin'); const { responseError, responseSuccess } = require('../service/Response'); const { encrypt, decrypt } = require('../service/Encryption'); const nodemailer = require('nodemailer') let result = null; module.exports = fp(function (fastify, opts, next) { fastify .decorate('setReply', async function (reply) { result = reply; }) .decorate('responseSuccess', function (options, reply) { responseSuccess(options, reply) }) .decorate('responseError', function (options) { responseError(options) }) .decorate('encrypt', function (text) { return encrypt(text); }) .decorate('decrypted', function (text) { return decrypt(text); }) .decorate('bcrypt', function (value) { var bcrypt = require('bcryptjs'); var salt = bcrypt.genSaltSync(10); return bcrypt.hashSync(value, salt); }) .decorate('bcryptCheck', async function (value, compare) { var bcrypt = require('bcryptjs'); return bcrypt.compareSync(value, compare); }) .decorate('createToken', function (username, userId, role) { const crypto = require('crypto'); let tokenid = crypto.randomBytes(25).toString('hex'); return { token: this.jwt.sign({ executor: username, incumbency: role, executorId : userId }, { expiresIn: '1d', jwtid: tokenid }), refreshToken: this.jwt.sign({ executor: username, incumbency: role }, { expiresIn: '2d', keyid: tokenid }) } }) .decorate('paginate', function (collect, page, range) { collect['pageCount'] = Math.ceil(collect.total / range); collect['range'] = range; collect['page'] = page + 1; return collect }) .decorate('validation', function(data,rules,message){ const {Validate} = require('../service/Validator') const validate = new Validate(data,rules,message) if(validate.fails()){ fastify.responseError({ code:403, values: validate.errors(), message: "Terdapat Isian Yang Tidak Valid!!" }) } }) .decorate('sendEmail', async function (recipient, message, subject = "Bimbingan Belajar Notifikasi") { try { let adminAccount = { user: process.env.MAILER_USER, pass: process.env.MAILER_PASS }; let transporter = nodemailer.createTransport({ host: "smtp.gmail.com", service: "gmail", port: 465, secure: true, auth: { user: adminAccount.user, pass: adminAccount.pass } }); let info = await transporter.sendMail({ from: "Admin Bimbingan Belajar 👥 <foo@blurdybloop.com>", to: recipient, subject: subject, html: message }); nodemailer.getTestMessageUrl("email info", info); } catch (err) { console.log("email error", err); } }) .decorate('verifikasi', async function(length){ let result = ''; let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let charactersLength = characters.length; for ( let i = 0; i < length; i++ ) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; }) next() })
import React from "react" import Layout from "../components/layout" import Blocks from "../components/blocks" const SignIn = () => ( <Layout whiteNav={true}> <Blocks content={[ { id: `hero`, block: `hero`, headline: `Reset your password` }, { id: `reset-form`, block: `reset` } ]} /> </Layout> ) export default SignIn
class SoloEndScreen extends GameObject { constructor() { super("SoloEndScreen"); } } export default SoloEndScreen;
/** * @ngdoc component * @module app * @name main * * @description * A component which serves as the main View of the application. */ (function (angular) { 'use strict'; function MainController(navigationService) { var ctrl = this; ctrl.gridConfig = { cols: 2, rowHeight: '4:3' }; ctrl.navOptions = navigationService.navItems; } angular.module('app') .component('main', { templateUrl: '/components/main/main.html', controller: MainController }); })(angular);
/** * Configure your Gatsby site with this file. * * See: https://www.gatsbyjs.com/docs/gatsby-config/ */ module.exports = { /* Your site config here */ siteMetadata: { title: "Welcome to my website ~ Jon Johnson", url: "https://www.jonj.io", description: "I'm a Software Engineer and creator of a few random things. I also love to write about what I'm working on from time to time. Hope you enjoy checking things out.", image: "/ms-icon-310x310.png", }, plugins: [ { resolve: `gatsby-source-filesystem`, options: { name: `posts`, path: `${__dirname}/src/posts`, }, }, { resolve: `gatsby-source-filesystem`, options: { name: `stuff`, path: `${__dirname}/src/stuff`, }, }, `gatsby-transformer-remark`, `gatsby-plugin-mdx`, `gatsby-plugin-react-helmet`, `gatsby-plugin-sass`, `gatsby-plugin-image`, `gatsby-plugin-sharp`, `gatsby-transformer-sharp`, ], };
import React from 'react' const Functional = ({state , capital, children}) => { return ( <div> <h1>The capital city of {state} is {capital}</h1> {children} </div> ) } export default Functional;
const labels = document.querySelectorAll('.form-control label'); labels.forEach(label => { label.innerHTML = label.innerText .split('') .map((letter, idx) => `<span style="transition-delay: ${idx * 50}ms">${letter}</span>`) .join(''); }); //We convert the text of the innerHTML into an ARRAY with split(). The empty string in split() converts the contents of the span to // array('e', 'm','a', 'i', 'l') //map() manipulates the elements of an array into something else. In this case, it takes every item in the array and converts it into a span. We then use js template syntax to define the letters. //Join() turns the array back into a single string. So instead of of e, m, it concatenates everything together as a unified string.
var site = { lib: {}, common: { InitMap: { home: function () { elf('#Preview input[type=radio]').on('click', function (ev) { elf().g('DownloadButton').setAttribute('href', this.value); }); }, blog: function () { elf('#BlogSide').scrollFollow({ side: 'right', sideOffset: 0, marginTop: 10, referId: 'BlogMain', wrapId: 'MainBody' }); }, post: function () { elf().loadScript('http://elfjs.disqus.com/embed.js', {}); }, list: function () { elf('#BlogList>.blog-item>h2').on('click', function (ev) { var target = ev.target, item = elf(target).parent(); if (target.nodeName != 'A' && item.attr('data-loaded') != 1) { elf().ajax({ url: target.firstChild.getAttribute('href'), onsuccess: function (response) { var content = response.split('<p class="blog-meta">')[1].split('</p>'); content.shift(); content = content.join('</p>').split(/<\/div>\s*<div id="disqus_thread" class="doc-comments">/)[0]; item.query('>div.doc-content').html(content); item.attr('data-loaded', 1); } }); } target = null; }); }, docs: function () { var toc = elf().g('markdown-toc'); var scrollDelay = toc ? 800 : 0; if (toc) { var tocWrap = elf('#DocToc div.doc-toc'); tocWrap.append(toc); tocWrap.setStyle('height', toc.offsetHeight + 'px'); toc = tocWrap = null; } /* elf().on('DocToc', 'mouseover', function (ev) { elf().addClass('DocToc', 'expand'); }); elf().on('DocToc', 'mouseout', function (ev) { elf().removeClass('DocToc', 'expand'); }); */ // elf(window).on('scroll', scrolling), scrolling(); setTimeout(function () { elf('#DocToc').scrollFollow({ side: 'left', sideOffset: 20, marginTop: 10, referId: 'DocContent', wrapId: 'MainBody' }); }, scrollDelay); elf().on('MainBody', 'dblclick', function (ev) { elf().toggleClass(this, 'doc-collapse-menu'); ev.preventDefault(); return false; }); }, search: function () { js.dom.Stage.loadScript('http://www.google.com/jsapi', { onLoad: function () { google.load('search', '1', { language: 'zh-CN', style: google.loader.themes.V2_DEFAULT, callback: function() { var customSearchControl = new google.search.CustomSearchControl('000346898720731947188:hhdkdilmh1o', {}); customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET); var options = new google.search.DrawOptions(); options.setAutoComplete(true); customSearchControl.draw('cse', options); var url = new js.net.URL(location); var query = url.getParameter('q'); if (query) { document.title = elf().template(site.common.Text.TPL_SEARCH_TITLE, query); customSearchControl.execute(query); } } }); } }); }, demo: function () { elf('#box').html('Hello world!').css({ textAlign: 'center' }).tween({ property: {fontSize: {to: 200, unit: '%'}} }).on('click', function (ev) { elf('#box').tween({ property: {width: {from: 100, to: 40, unit: '%'}}, oncomplete: function () { elf('#source').css({ display: 'block', opacity: 0 }).tween({ property: { opacity: {to: 1}, width: {to: 60, unit: '%'} } }); } }); }); } }, Text: { TPL_SEARCH_TITLE: 'elf+js: 搜索 / #{0}' } } }; site.lib.ScrollFollow = elf().Class({ constructor: function (node, args) { this.node = node; elf().copy(args, this); var boundle = this._handler.bind(this); elf(window).on('scroll', boundle); elf(window).on('resize', boundle); this._handler(); }, getDocumentElement: function () { return elf().Chrome || elf().Safari ? document.body : document.documentElement; }, getScrollTop: function () { return this.getDocumentElement().scrollTop; }, getStartTop: function () { return this.node.getPosition(this.getDocumentElement()).y; }, getOriginTop: function () { return typeof this.originTop != 'undefined' ? this.originTop : (this.originTop = this.node.getPosition(this.getDocumentElement()).y - elf().getPosition(elf().g(this.wrapId), this.getDocumentElement()).y); }, getFollowingBottom: function () { var content = elf().g(this.referId); return (content.offsetHeight + elf().getPosition(elf().g(this.referId), this.getDocumentElement()).y - elf().getPosition(elf().g(this.wrapId), this.getDocumentElement()).y - this.getFollowingHeight()); }, getFollowingAbsBottom: function () { var content = elf().g(this.referId); return elf().getPosition(content, this.getDocumentElement()).y + content.offsetHeight; }, getFollowingHeight: function () { return this.node[0].offsetHeight; }, getFollowingWidth: function () { return this.node[0].offsetWidth; }, getFollowingMargin: function () { return 0; }, getContentWidth: function () { return elf().g(this.wrapId).offsetWidth; }, sideMap: { left: -1, right: 1 }, _handler: function (ev) { var scrollTop = this.getScrollTop(); var startTop = typeof this.startTop != 'undefined' ? this.startTop : (this.startTop = this.getStartTop()); var originTop = this.getOriginTop(); var followingBottom = this.followingBottom = this.getFollowingAbsBottom(); var followingWidth = this.followingWidth || (this.followingWidth = this.getFollowingWidth()); var followingHeight = this.followingHeight || (this.followingHeight = this.getFollowingHeight()); var followingMargin = this.followingMargin || (this.followingMargin = this.getFollowingMargin()); var docElem = this.getDocumentElement(); var pageWidth = docElem.offsetWidth; var contentWidth = this.contentWidth || (this.contentWidth = this.getContentWidth()); var side = this.sideMap[this.side]; var props = {}; if (scrollTop >= startTop - this.marginTop) { if (followingBottom < scrollTop + followingHeight + this.marginTop) { elf().mix(props, {position: 'absolute', top: this.getFollowingBottom() + 'px'}); props[this.side] = ''; } else { props.position = 'fixed'; props.top = this.marginTop + 'px'; var screenSub = pageWidth - contentWidth; var sideOffset = Math.max(0, screenSub) / 2 + (this.sideOffset + docElem.scrollLeft * side); if (pageWidth < contentWidth && side > 0) { sideOffset += screenSub; } props[this.side] = sideOffset + 'px'; } } else { props.position = 'absolute'; props.top = originTop + 'px'; props[this.side] = this.sideOffset + 'px'; } props && this.node.css(props); } }); elf().implement(js.dom.Node, { scrollFollow: function (options) { this.scrollFollow = new site.lib.ScrollFollow(this, options); } }); elf(function () { var nav = (new elf.net.URL(location)).getPath().match(/^\/([\w\.-]+\/|\/$)/); if (nav) { elf('#Header div.layout-aside li').forEach(function (node) { if (node.firstChild.getAttribute('href') == nav[0]) { elf().addClass(node, 'current'); } }); } elf('pre').forEach(function (item) { hljs.highlightBlock(item); }); var module = elf().g('MainPage').className.replace(/page-type-/g, '').split(' '); module.forEach(function (item) { var initer = site.common.InitMap[item]; initer && initer(); }); elf('a.email-link').forEach(function (item) { var email = elf(item).text().replace('[at]', '@').replace('[dot]', '.'); item.href = 'mailto:' + email; item.innerHTML = email; }); });
$(document).ready(function(){ ocultaCiudades() seleccionCiudad() }); function ocultaCiudades(){ $(".ciudades #chi").hide(); $(".ciudades #bc").hide(); $(".ciudades #coa").hide(); $(".ciudades #dur").hide(); $(".ciudades #gua").hide(); $(".ciudades #jal").hide(); $(".ciudades #mic").hide(); $(".ciudades #nay").hide(); $(".ciudades #sin").hide(); $(".ciudades #son").hide(); $(".ciudades #tab").hide(); $(".ciudades #tam").hide(); $(".ciudades #ver").hide(); $(".ciudades #zac").hide(); $("#puebla").click(function(){ seleccionCiudad (ciudad) }); } function seleccionCiudad (){ $("#seleccionCiudad").on('change', function(){ var ver = $(this).val(); var ciudad ="#"+ver // alert(ciudad) ocultaCiudades() $(ciudad).fadeIn(); }); } function seleccionCiudad2 (ciudad){ $("#seleccionCiudad").on('change', function(){ var ver = $(this).val(); var ciudad ="#"+ver // alert(ciudad) ocultaCiudades() $(ciudad).fadeIn(); }); }
import React from 'react' const Oeration = ({ operation }) => { console.log(operation) return ( <tr> <td>{operation.log}</td> <td>{operation.time}</td> </tr> ) } export default Oeration
/** This is an example of the html we want generated! * <div>... <select id='title_select' class='selector'> <option value='Other'>Choose topic and subtopic</option> </select> <br> <input type='checkbox' id='bonus'>Include a bonus</input> <button type='button' id='updatebackground'>Change Background</button> </div> */ var emptySelectors = "NotSelected"; function fillElement(idName, selectorArray){ var div = document.getElementById(idName); div.innerHTML = ''; var option = document.createElement('option'); option.setAttribute('value', emptySelectors); option.innerText = ""; div.appendChild(option); for (var i = 0; i < selectorArray.length; i++) { var option = document.createElement('option'); option.setAttribute('value',selectorArray[i]); option.innerText = selectorArray[i]; div.appendChild(option); } } function changeResponse(domSelector){ return function(){ switch (domSelector.id) { case "topics": var request = { seeking: ["subtopics","titles"], topics: [domSelector.value] } sendAJAXrequest(request); break; case "subtopics": case "levels": var request = { seeking: ["titles"], }; if(document.getElementById("subtopics").value!=emptySelectors){ request.subtopics = [document.getElementById("subtopics").value]; }; if(document.getElementById("levels").value!=emptySelectors){ request.levels = levels = [document.getElementById("levels").value]; }; sendAJAXrequest(request); break; case "titles": alert("I haven't programmed this one"); break; default: break; } } } function sendAJAXrequest(message, responseFunction){ myAJAXRequest = new AJAXrequest(JSON.stringify(message)); myAJAXRequest.makeRequest(receiveAJAXresponse); } function receiveAJAXresponse(theResponse) { //theResponse is a javascript object if(!theResponse.hasOwnProperty("titles")){ alert("I'm sorry but there are no questions meeting your criteria") } for (var name in theResponse) { switch (name) { case "topics": fillElement(name, theResponse.topics); break; case "subtopics": fillElement(name, theResponse.subtopics); break; case "levels": fillElement(name, theResponse.levels); break; case "titles": fillElement(name, theResponse.titles); break; default: break; } } } document.addEventListener("DOMContentLoaded",function(){ var childDivs = document.getElementById('questionSpecs').getElementsByTagName('select'); for( i=0; i< childDivs.length; i++ ) { childDiv = childDivs[i]; childDiv.onchange = changeResponse(childDiv) } var request = { seeking: ["subtopics","levels","titles"], } sendAJAXrequest(request); });
import { sayGodbye } from './models'; export default (request, response) => { response.success(sayGodbye()); };
import React, { Component } from 'react'; import 'react-bootstrap'; import { HashRouter, Switch, Route, Link } from 'react-router-dom'; class PaintingArchive extends Component{ constructor(props) { super(props); this.state = {paintings:[] } } componentDidMount(){ if(this.props.paintingslist){ this.setState({paintings:this.props.paintingslist}) }else{ if(this.props.location.state.paintingslist){ this.setState({paintings:this.props.location.state.paintings}) } } } render() { debugger; return ( <div> <section className="jumbotron text-center archive-body-padding"> <div className="container body-padding"> <h1 className="jumbotron-heading">Art Archive</h1> <p className="lead text-muted">To buy art, look closer or comment on a painting: click on one of the thumbnail images. </p> <p> <a href="#" className="btn btn-primary">Learn more</a> </p> </div> </section> <div className="col-md-2"/> <div className="col-md-8"> <div id="links" > {this.state.paintings.map((elem,index)=> { return( <Link to={{pathname:'/painting',state:{displayPainting:elem}}} href={elem} title={elem} key={index} className="archive-max-size"> <img key={index} src={elem} alt="Banana"/> </Link> ) })} </div> </div> <div className="col-md-2"/> </div> ); } } export default PaintingArchive
webpackJsonp([3],{1:function(n,c){},7:function(n,c,t){"use strict";t(1)}},[7]);
require('dotenv').config() module.exports = { siteMetadata: { title: `Alexandra Vlad - Photography`, description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`, author: `@av`, siteUrl: `https://alexandra-vlad.com` }, plugins: [ { resolve: `gatsby-theme-material-ui`, options: { webFontsConfig: { fonts: { google: [ { family: `Raleway`, variants: [`300`, `400`, `500`] }, { family: `Shadows Into Light`, variants: [`400`] } ] } } } }, { resolve: `gatsby-plugin-robots-txt`, options: { host: `https://alexandra-vlad.com`, sitemap: `https://alexandra-vlad.com/sitemap.xml`, policy: [{ userAgent: '*', allow: '/' }] } }, { resolve: `gatsby-plugin-sitemap`, options: { output: `/sitemap.xml` } }, `gatsby-plugin-react-helmet`, { resolve: `gatsby-plugin-react-helmet-canonical-urls`, options: { siteUrl: `https://alexandra-vlad.com` } }, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images` } }, { resolve: `gatsby-source-contentful`, options: { spaceId: process.env.CONTENTFUL_SPACE_ID, accessToken: process.env.CONTENTFUL_ACCESS_TOKEN } }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-i18n`, options: { langKeyDefault: '', langKeyForNull: '', prefixDefault: false, useLangKeyLayout: false } }, { resolve: `gatsby-plugin-google-analytics`, options: { // The property ID; the tracking code won't be generated without it trackingId: 'UA-174590387-1', // Defines where to place the tracking script - `true` in the head and `false` in the body head: true, // Setting this parameter is optional anonymize: true, // Setting this parameter is also optional respectDNT: true, // Delays sending pageview hits on route update (in milliseconds) pageTransitionDelay: 0, // Defers execution of google analytics script after page load defer: true, // Any additional optional fields sampleRate: 5, siteSpeedSampleRate: 10, cookieDomain: 'https://alexandra-vlad.com' } }, { resolve: `gatsby-transformer-remark`, options: { plugins: [ { resolve: `gatsby-remark-images-contentful`, options: { maxWidth: 800, withWebp: true, loading: 'lazy' } } ] } }, { resolve: `gatsby-plugin-manifest`, options: { name: `Alexandra Vlad Photography`, short_name: `AV Photography`, start_url: `/`, background_color: `#c8ae5e`, theme_color: `#c8ae5e`, display: `minimal-ui`, icon: `src/images/photo-camera.png` } }, // this (optional) plugin enables Progressive Web App + Offline functionality // To learn more, visit: https://gatsby.dev/offline `gatsby-plugin-offline` ] }
function setup(){ createCanvas(400, 300); background(255); } function draw() { background(15); }
//app var toDoList = []; list = document.getElementById('todo_list') toggleButton = document.getElementById('toggle_list'); removeButtonSelect = document.getElementById('removeBtn'); textBox = document.createElement('input'); textBox.type = 'text'; list = document.querySelector('ul'); iconCreate = document.createElement('i'); iconCreate.className = 'material-icons'; iconCreate.textContent = 'close'; function addItem() { addToUl = document.createElement('li'); createInput = document.createElement('input'); createInput.type = 'text'; createInput.placeholder = 'Add a to-do'; addToUl.appendChild(createInput); list.appendChild(addToUl); }; function removeItem() { if(list.children[indexInputSelect.value - 1].children.length != 1) { list.children[indexInputSelect.value - 1].remove(); } else { alert('You have to select a to-do'); } }; function iconListener() { iconSelector = document.querySelectorAll('i'); iconSelector.forEach(function(e) { e.addEventListener('click', function(){ e.parentElement.remove(); }); }); } list.addEventListener('click', function(e) { var element = e.target; var callee = e.currentTarget; if (element != callee && element.className === "" && element.textContent.length > 0) { element.className = "done"; } else { element.className = ""; } }) toggleButton.onclick = function() { if(list.childNodes.length > 3) { if(list.className === '' && toggleButton.textContent === 'Mark All') { list.className = 'done'; toggleButton.textContent = 'Unmark All'; } else { list.className = ''; toggleButton.textContent = 'Mark All'; } } else { alert('You need at least 1 to-do'); } } list.addEventListener('dblclick', function(e) { let element = e.target; let callee = e.currentTarget; let value = element.textContent; if (element != callee) { element.innerHTML = textBox.outerHTML element.children[0].value = value.replace('close', ''); element.children[0].focus(); } }) list.addEventListener('keypress', function(e) { var element = e.target; var key = e.which || e.keyCode; if (key === 13) { inputSelect = document.querySelectorAll('input').length if(inputSelect == 1) { addItem(); } var contentLi = iconCreate.outerHTML + element.value; element.parentElement.innerHTML = contentLi; iconListener(); } })
const reEmail = /^\S{1,}@\S{1,}\.\S{2,3}$/ const reComma = /,\s?/ export const validate = email => { return { value: email, valid: reEmail.test(email), } } export const splitStringByComma = (emailsStr = '') => { const emails = emailsStr.split(reComma).filter(email => email) return emails }
import { getUrlParams } from './utils'; import { getDetailFn,getNameListFn, getDetailNameListFn } from './industry'; import { getAddress } from './citys'; import { queryBankList,querySubBranch } from './bank' // mock tableListDataSource let tableListDataSource = []; let reviewListDataSource = []; let statusList = [{type: null, name: null, key: "1", value: "保存未提交"}, {type: null, name: null, key: "2", value: "开户申请审核中"}, {type: null, name: null, key: "3", value: "开户审核不通过"}, {type: null, name: null, key: "4", value: "信息变更审核中"}, {type: null, name: null, key: "5", value: "信息变更审核不通过"}, {type: null, name: null, key: "6", value: "正常"}]; let typeList = [{"type":null,"name":null,"key":"1","value":"普通店"}, {"type":null,"name":null,"key":"2","value":"总店"}, {"type":null,"name":null,"key":"3","value":"分店"}]; let operatorList = [{type: null, name: null, key: "-1", value: "升腾资讯"}]; for (let i = 0; i < 6; i += 1) { operatorList.push({type: null, name: null, key: i, value: `运营商${i}`}); } let instList = [{type: null, name: null, key: "-1", value: "浙江农信",parent:'-1',parentName:'升腾资讯'}]; for (let i = 0; i < 10; i += 1) { const pid = Math.floor(Math.random() * 10) % 6; instList.push({type: null, name: null, key: i, value: `服务商${i}`,parent:pid,parentName: `运营商${pid}`}); } const reviewResultType = { 1:'未审核', 2:'通过', 3:'不通过' }; let getReviewList = function (obj,i,le) { let reviewResult = Math.floor(Math.random() * 10) % 3 + 1; const reviewUserId = Math.floor(Math.random() * 10) % 3 + 1; if(i === 0){ if(obj.merchantStatus == 3 || obj.merchantStatus == 5){ reviewResult = 3; } if(obj.merchantStatus == 6){ reviewResult = 2; } } const reviewObj = { "reviewId":`${obj.merchantId}${i}`, "reviewType":i >= le-1?1:2, "reviewTypeName":i >= le-1?'开户申请审核':'信息变更审核', "reviewFormId":57, "reviewUserId":reviewResult===1?null:reviewUserId, "reviewUserName":reviewResult===1?null:`系统管理员${reviewUserId}`, "reviewTime":reviewResult===1?null:obj.applyTime - 24 * 3600 *5000 * (i+1) + Math.floor(Math.random() * 24 * 3600 *1000) + 24 * 3600 *1000, "applyDate":null, "reviewResult":reviewResult, "reviewOpinion":null, "merchantId":obj.merchantId, "applyId":null, "merchantName":null, "operatorId":null, "instId":null, "reviewTimeSt":null, "reviewTypeMer":1, "reviewTypeTer":2, "reviewTypeBase":3, "reviewTypeBalan":4, "reviewTypeCont":5, "reviewResultName":reviewResultType[reviewResult], "applyTimeSt":null, "merchantNo":null, "instName":null, "applyUserName":null, "legalPersonName":null, "serachTimeStart":null, "serachTimeEnd":null, "reviewTimes":0, "merchantApplyStatus":null, "terApplyStatus":null, "baseApplyStatus":null, "balanceApplyStatus":null, "contactApplyStatus":null, "applyTime":obj.applyTime - 24 * 3600 *5000 * (i+1) + Math.floor(Math.random() * 24 * 3600 *1000) }; return reviewObj; } const merchantItem = { key: 0, accountType:1, applyTime:new Date().getTime(), applyUserId:0, applyUserName:null, businessPersonName:null, contactMobilePhone:null, contactPhone:null, industryTypeName:null, instName: null, isRegister:0, isRegisterName:"否", legalPersonName:null, merchantCode:null, merchantId:0, merchantType:1, merchantTypeName:'普通店', merchantName:null, merchantShortName:null, merchantNo:null, merchantStatus:1, merchantStatusName:statusList.filter(v => Number(v.key) === 1)[0].value, operatorName:null, rates:null, reviewTime:null, serachTimeEnd:null, serachTimeStart:null, terminalModelNames:null, terminalNumbers:null, terminalTypeNames:null, terminalVersionNames:null, account:null, accountBankBranchName:null, accountBankNameId:null, accountCityCode:null, accountCityName:null, accountIdcard:null, accountName:null, accountProvinceCode:null, accountProvinceName:null, accountTypeName:null, agreementUrlId:null, alliedBankCode:null, applyPosType:null, bankCardBackId:null, bankCardBackUrl:null, bankCardId:null, bankCardUrl:null, businessAddress:null, businessCityCode:null, businessCityName:null, businessDistrictCode:null, businessDistrictName:null, businessLicense:null, businessLicenseEndtime:null, businessLicenseStarttime:null, businessLicenseUrl:null, businessLicenseUrlId:null, businessPersonId:null, businessProvinceCode:null, businessProvinceName:null, businessZipCode:null, certCode:null, certName:null, contact:null, contractEndtime: null, contractNumber:null, contractStarttime:null, couponMode:"1", createTime:new Date().getTime(), dayMaxnum:null, fax:null, "feeType":null, "settlementPeriod":null, "rate":null, "username":"18765412300", "merchantCategory":null, "mcc":null, "openPermitsUrlId":null, "storePicUrlId":null, "otherPicUrlId":null, "storeLogoUrlId":null, "legalPersonCertificateBackId":null, "legalPersonCertificateBackUrl":null, "storePhone":null, "updateTime":null, "storeLogoUrl":null, "storePicUrl":null, "newStoreLogoUrl":null, "newStorePicUrl":null, "organizationCodeUrl":null, "legalPersonCertificateUrl":null, "newOrganizationCodeUrl":null, "newLegalPersonCertificateUrl":null, "newBusinessLicenseUrl":null, "reviewList":null, "terminalList":[], "settlementPeriodName":null, "parentMerchantName":null, "payChannelList":[], "mpId":null, "mpName":null, "headUrl":null, "password":null, "operatorId":0, "instId":-1, "parentMerchantId":0, "registerProvinceCode":null, "registerCityCode":null, "registerDistrictCode":null, "registerAddress":null, "registerZipCode":null, "landlinePhone":null, "registeredCapital":null, "organizationCode":"", "organizationCodeUrlId":null, "taxRegistration":null, "taxRegistrationUrlId":null, "legalPersonCertificateTypeId":null, "legalPersonCertificate":null, "legalPersonCertificateUrlId":null, "industryType":null, "industryNo":null, "managementContent":null, "functions":null, "singleMinimum":null, "singleMaxnum":null, "monthMaxnum":null, }; for (let i = 0; i < 46; i += 1) { const merchantStatus = Math.floor(Math.random() * 10) % 6 + 1; const merchantType = Math.floor(Math.random() * 10) % 3 + 1; const isRegister = Math.floor(Math.random() * 10) % 2; const merchant = Object.assign({},merchantItem,{ key: i, accountType:1, applyTime:new Date(`2017-07-${(Math.floor(i / 2) + 1)<10?'0'+(Math.floor(i / 2) + 1):(Math.floor(i / 2) + 1)} 15:19:${i<10?'0'+i:i}`).getTime(), applyUserId:115, applyUserName:"xtgl", businessPersonName:null, contactMobilePhone:`18${Math.floor(Math.random() * 10) % 6}${Math.floor(Math.random() * 100000000)}`, contactPhone:null, industryTypeName:null, instName: instList[Math.floor(Math.random() * 10) % 7].value, isRegister:isRegister, isRegisterName:isRegister?"是":"否", legalPersonName:null, merchantCode:null, merchantId:i, merchantType:merchantType, merchantTypeName:typeList.filter(v => Number(v.key) === Number(merchantType))[0].value, merchantName:`测试${i}`, merchantShortName:"测试", merchantNo:(Math.floor(Math.random() * 999999999999999)+1)+'', merchantStatus:merchantStatus, merchantStatusName:statusList.filter(v => Number(v.key) === Number(merchantStatus))[0].value, operatorName:operatorList[Math.floor(Math.random() * 10) % 7].value, accountBankNameId:"中信银行", accountCityCode:"1101", accountCityName:"北京市", accountProvinceCode:"11", accountProvinceName:"北京市", accountTypeName:"对公账号", businessAddress:"发发发", businessCityCode:"1101", businessCityName:"北京市", businessDistrictCode:"110101", businessDistrictName:"东城区", businessLicense:"yingyezhizhao", businessProvinceCode:"11", businessProvinceName:"北京市", contact:"测试", contractNumber:"GP2018011915192706722", couponMode:"1", createTime:1516346367000, dayMaxnum:100000, "updateTime":1516081522000, "storeLogoUrl":"/cerfile/201801/image-2da80a36-4254-4047-be07-bd2b4bf87b55.jpg", "parentMerchantName":"德克士", "operatorId":1, "instId":-1, "parentMerchantId":5, "legalPersonCertificate":"350101111111111111", "managementContent":"挂号平台", "singleMinimum":1.00, "singleMaxnum":50000.00, "monthMaxnum":1000000.00, }); tableListDataSource.push(merchant); if(merchantStatus !== 1 && merchantStatus !== 2){ const reviewLength = (merchantStatus === 3)?1:Math.floor(Math.random() * 10) % 5 + 1; for(let j = 0; j < reviewLength; j += 1){ const review = getReviewList(merchant,j,reviewLength); reviewListDataSource.push(review); } } } export function getMerchantList(req, res, u, type) { let url = u; if (!url || Object.prototype.toString.call(url) !== '[object String]') { url = req.url; // eslint-disable-line } const params = getUrlParams(url); let dataSource = [...tableListDataSource]; if (params.merchantStatus) { const status = params.merchantStatus.split(','); let filterDataSource = []; status.forEach((s) => { filterDataSource = filterDataSource.concat( [...dataSource].filter(data => parseInt(data.merchantStatus, 10) === parseInt(s[0], 10)) ); }); dataSource = filterDataSource; } let merchantStatus = params.merchantStatus; if (!params.merchantStatus){ switch(type){ case 'open': merchantStatus = '1,2,3'; break; case 'info': merchantStatus = '6'; break; case 'review': merchantStatus = '2,4'; break; } } if (merchantStatus) { const status = merchantStatus.split(','); let filterDataSource = []; status.forEach((s) => { filterDataSource = filterDataSource.concat( [...dataSource].filter(data => parseInt(data.merchantStatus, 10) === parseInt(s[0], 10)) ); }); dataSource = filterDataSource; } if (params.instName) { const instName = params.instName.split(','); let filterDataSource = []; instName.forEach((s) => { filterDataSource = filterDataSource.concat( [...dataSource].filter(data => data.instName === s) ); }); dataSource = filterDataSource; } if (params.operatorName) { const operatorName = params.operatorName.split(','); let filterDataSource = []; operatorName.forEach((s) => { filterDataSource = filterDataSource.concat( [...dataSource].filter(data => data.operatorName === s) ); }); dataSource = filterDataSource; } if (params.merchantName) { dataSource = dataSource.filter(data => data.merchantName.indexOf(params.merchantName) > -1); } if (params.merchantNo) { dataSource = dataSource.filter(data => data.merchantNo.indexOf(params.merchantNo) > -1); } if (params.serachTimeStart && params.serachTimeEnd) { const start = params.serachTimeStart; const end = params.serachTimeEnd; dataSource = dataSource.filter(data => new Date(data.applyTime).getTime()>=new Date(start + ' 00:00:00').getTime() && new Date(data.applyTime).getTime()<=new Date(end + ' 23:59:59').getTime()); } const sorterParam = params.sorter?params.sorter:'applyTime_descend'; if (sorterParam) { const s = sorterParam.split('_'); dataSource = dataSource.sort((prev, next) => { if (s[1] === 'descend') { if(s[0] === 'applyTime'){ return new Date(next[s[0]]) - new Date(prev[s[0]]); } return next[s[0]] - prev[s[0]]; } if(s[0] === 'applyTime'){ return new Date(prev[s[0]]) - new Date(next[s[0]]); } return prev[s[0]] - next[s[0]]; }); } let pageSize = 10; if (params.pageSize) { pageSize = params.pageSize * 1; } const result = { list: dataSource, pagination: { total: dataSource.length, pageSize, current: parseInt(params.currentPage, 10) || 1, }, }; return result; } function getId(list,name) { list = list.sort((prev, next) => { return new Date(next[name]) - new Date(prev[name]); }); return Number(list[0][name])+1; } function setMerchant(merchantId,obj) { const merchant = getMerchantObj(merchantId); const index = tableListDataSource.indexOf(merchant); Object.assign(tableListDataSource[index],obj); } export function getOperatorList(req, res, u){ const result = operatorList.map((o) => {return {text:o.value,value:o.value}}); if (res && res.json) { res.json(result); } else { return result; } } export function getInstList(req, res, u){ const result = instList.map((o) => {return {text:o.value,value:o.value}}); if (res && res.json) { res.json(result); } else { return result; } } export function getMerchantOpenList(req, res, u){ const list = getMerchantList(req, res, u, 'open'); const operator = getOperatorList(); const inst = getInstList(); const result = { list:list, operator:operator, inst:inst } if (res && res.json) { res.json(result); } else { return result; } } export function getMerchantInfoList(req, res, u){ const list = getMerchantList(req, res, u, 'info'); const operator = getOperatorList(); const inst = getInstList(); const result = { list:list, operator:operator, inst:inst } if (res && res.json) { res.json(result); } else { return result; } } export function getMerchantReviewList(req, res, u){ const list = getMerchantList(req, res, u, 'review'); const operator = getOperatorList(); const inst = getInstList(); const result = { list:list, operator:operator, inst:inst } if (res && res.json) { res.json(result); } else { return result; } } export function getMerchant(req, res, u){ let url = u; if (!url || Object.prototype.toString.call(url) !== '[object String]') { url = req.url; // eslint-disable-line } const params = getUrlParams(url); const view = tableListDataSource.filter(data => Number(data.merchantId) === Number(params.merchantId))[0]; let result = { view:view, name:[], citysList:[], detail:{}, parent:[], accountCitysList:[], bankList:[], subBranch:[] }; if(params.type === 'edit'){ let citysList2 = []; const detail = getDetailFn({detailName:view.managementContent,nameType:view.merchantType}); const name = getNameListFn({nameType:view.merchantType}); const detailList = getDetailNameListFn({name:detail.name,nameType:view.merchantType}); const nameList = name.map((val) => {if(val.value === detail.name){ return { children:detailList, ...val } }else{ return val; }}); /*获取初始化地点列表*/ const areaList = getAddress(view.businessCityCode); const provinceList = getAddress(1); const cityList = getAddress(view.businessProvinceCode); const citysList0 = areaList.map((val)=>{ return { value:val.code, label:val.name, }; }); const citysList1 = cityList.map((val) => {if(val.code === view.businessCityCode){ return { children:citysList0, value:val.code, label:val.name, isLeaf: false } }else{ return { value:val.code, label:val.name, isLeaf: false }; }}); citysList2 = provinceList.map((val) => {if(val.code === view.businessProvinceCode){ return { children:citysList1, value:val.code, label:val.name, isLeaf: false } }else{ return { value:val.code, label:val.name, isLeaf: false }; }}); const accountCityList = view.accountProvinceCode? getAddress(view.accountProvinceCode).map((val) => { return { value:val.code, label:val.name, }; }):[]; const accountCitysList = view.accountProvinceCode?provinceList.map((val) => {if(val.code === view.accountProvinceCode){ return { children:accountCityList, value:val.code, label:val.name, isLeaf: false } }else{ return { value:val.code, label:val.name, isLeaf: false }; }}):provinceList.map((val) => { return { value:val.code, label:val.name, isLeaf: false } }); let parent = tableListDataSource.filter(data => Number(data.merchantType) === 2); parent = parent.sort((prev, next) => { return new Date(next['applyTime']) - new Date(prev['applyTime']); }); result = { view:view, name:nameList, citysList:citysList2, detail:detail, parent:parent, accountCitysList:accountCitysList, bankList:queryBankList(), subBranch:querySubBranch(view.accountBankNameId,[view.accountProvinceCode,view.accountCityCode]) } }else{ let review = reviewListDataSource.filter(data => Number(data.merchantId) === Number(params.merchantId)); review = review.sort((prev, next) => { return new Date(next['applyTime']) - new Date(prev['applyTime']); }); result.view.review = review.length?review[0]:null; } if (res && res.json) { res.json(result); } else { return result; } } export function getMerchantObj(merchantId){ const result = tableListDataSource.filter(data => Number(data.merchantId) === Number(merchantId))[0]; return result; } export function getMerchantReview(req, res, u){ let url = u; if (!url || Object.prototype.toString.call(url) !== '[object String]') { url = req.url; // eslint-disable-line } const params = getUrlParams(url); let result = reviewListDataSource.filter(data => Number(data.merchantId) === Number(params.merchantId)); result = result.sort((prev, next) => { return new Date(next['applyTime']) - new Date(prev['applyTime']); }); if (res && res.json) { res.json(result); } else { return result; } } export function getParentMerchant(req, res, u){ let url = u; if (!url || Object.prototype.toString.call(url) !== '[object String]') { url = req.url; // eslint-disable-line } let result = tableListDataSource.filter(data => Number(data.merchantType) === 2); result = result.sort((prev, next) => { return new Date(next['applyTime']) - new Date(prev['applyTime']); }); if (res && res.json) { res.json(result); } else { return result; } } export function addReview(req, res, u, b){ const body = (b && b.body) || req.body; const { merchantId, reviewUserId, reviewUserName, reviewResult, reviewOpinion } = body; const merchant = getMerchantObj(merchantId); const {applyTime, merchantStatus} = merchant; const reviewType = merchantStatus == 2?1:2; let newStatus; if(reviewResult == 2){ newStatus = 6; }else{ switch (merchantStatus){ case 2: newStatus = 3; break; case 4: newStatus = 5 break; } } setMerchant(merchantId,{ merchantStatus:newStatus, merchantShortName:statusList.filter(v => Number(v.key) === Number(newStatus))[0].value }); const reviewObj = { "reviewId":getId(reviewListDataSource,'reviewId'), "reviewType":reviewType, "reviewTypeName":reviewType == 1?'开户申请审核':'信息变更审核', "reviewFormId":57, "reviewUserId":reviewUserId, "reviewUserName":reviewUserName, "reviewTime":new Date().getTime(), "applyDate":null, "reviewResult":reviewResult, "reviewOpinion":reviewOpinion, "merchantId":merchantId, "applyId":null, "merchantName":null, "operatorId":null, "instId":null, "reviewTimeSt":null, "reviewTypeMer":1, "reviewTypeTer":2, "reviewTypeBase":3, "reviewTypeBalan":4, "reviewTypeCont":5, "reviewResultName":reviewResultType[reviewResult], "applyTimeSt":null, "merchantNo":null, "instName":null, "applyUserName":null, "legalPersonName":null, "serachTimeStart":null, "serachTimeEnd":null, "reviewTimes":0, "merchantApplyStatus":null, "terApplyStatus":null, "baseApplyStatus":null, "balanceApplyStatus":null, "contactApplyStatus":null, "applyTime":applyTime }; reviewListDataSource.push(reviewObj); const result = { status:200, message:'审核成功' }; if (res && res.json) { res.json(result); } else { return result; } } export function addMerchant(req, res, u, b){ const body = (b && b.body) || req.body; if(!body.merchantId){ body.merchantId = getId(tableListDataSource,'merchantId'); body.merchantStatus = 2; body.merchantNo = new Date().getTime()*100 + Math.floor(Math.random() * 100) % 11 ; const instObj = instList.filter(data => Number(data.value) === body.instName); body.operatorName = instObj.length?instObj[0].parentName:'升腾资讯'; const merchantObj = Object.assign({},merchantItem,body); tableListDataSource.push(merchantObj); }else{ tableListDataSource = tableListDataSource.map((data)=>{ if(Number(data.merchantId) === Number(body.merchantId)){ if(Number(data.merchantStatus) === 6){ body.merchantStatus = 4; body.merchantStatusName = '信息变更审核中'; } return Object.assign({},data,body); } return data; }); } const result = { status:200, message:'提交成功', }; if (res && res.json) { res.json(result); } else { return result; } } export function removeMerchant(req, res, u){ let url = u; if (!url || Object.prototype.toString.call(url) !== '[object String]') { url = req.url; // eslint-disable-line } const params = getUrlParams(url); tableListDataSource = tableListDataSource.filter(data => Number(data.merchantId) !== Number(params.merchantId)); const result = { status:200, message:'删除成功' }; if (res && res.json) { res.json(result); } else { return result; } } export default { getMerchantOpenList, getOperatorList, getInstList, getMerchantReviewList, getMerchant, getMerchantReview, addReview, addMerchant, removeMerchant, getParentMerchant };
import React, { Component } from 'react'; import './App.css'; import { connect } from 'react-redux'; import { add_reminder,remove_reminder,clean_reminder } from './actions/' import moment from 'moment'; class App extends Component { constructor(props) { super(props); this.state = { text: '', dueDate: '' } } renderReminders() { const { reminders,remove_reminder } = this.props; return ( <ul className="list-group col-sm-8 mt-2"> { reminders.map(reminder => ( <li className="list-group-item" key={reminder.id}> <div className="list-item"> <div>{reminder.text}</div> <div><em>{moment(new Date(reminder.dueDate)).fromNow()}</em></div> </div> <div className="list-item delete-button" onClick={()=>remove_reminder(reminder.id)} >&#x2715; </div> </li> )) } </ul> ) } render() { //dispatch ations const { add_reminder,clean_reminder } = this.props; return ( <div className="App"> <div className="title">Reminder Pro</div> <div className="form-inline"> <div className="form-group mr-2"> <input type="text" className="form-control" onChange={(event) => { this.setState({ text: event.target.value }) }} placeholder="I have to..." /> <input type="datetime-local" className="form-control" onChange={(event) => { this.setState({ dueDate: event.target.value }) }} /> </div> <button type="button" onClick={() => { add_reminder(this.state.text, this.state.dueDate) }} className="btn btn-success">Add Reminder</button> </div> {this.renderReminders()} <div className="text-center mt-2"> <button type="button" className="btn btn-danger" onClick={()=>clean_reminder()} >Clear Reminders</button> </div> </div> ); } } const mapStateToProps = (state) => { return { reminders: state } } export default connect(mapStateToProps, { add_reminder,remove_reminder,clean_reminder })(App);
import React, { useEffect, useState } from 'react'; import axios from 'axios'; import styled from 'styled-components'; //ui import { Switch, Route, Link, Redirect } from 'react-router-dom'; import Landing from './screens/landing/landing.screen'; import Dashboard from './screens/dashboard//dashbaord.screens'; import './vendor.css'; const ModalHolder = styled.div` background-color: rgba(0, 0, 0, 0.85); width: 100vw; height: 100vh; position: absolute; top: 0; left: 0; z-index: 300; `; const baseurl = process.env.REACT_APP_BASE_URL; const App = () => { const [token, setToken] = useState(localStorage.getItem('token') || ''); const [currentUser, setCurrentUser] = useState(''); useEffect(() => { async function getCurrentUser() { try { const auth = await axios.get(`${baseurl}/api/v1/auth/`, { headers: { Authorization: `Bearer ${token}` }, }); setCurrentUser(auth.data); } catch (err) { console.log(err); } } getCurrentUser(); }, [token]); return ( <div> <Switch> <Route path="/" exact> {!currentUser ? ( <Landing setToken={setToken} setCurrentUser={setCurrentUser} /> ) : ( <Redirect to="/dashboard" /> )} </Route> <Route path="/dashboard" render={(routeProps) => ( <Dashboard {...routeProps} token={token} currentUser={currentUser} /> )} ></Route> <div>set value</div> </Switch> </div> ); }; export default App;
import React from 'react' import { connect } from "react-redux"; import { UniqueName,createRealUser } from "../store/actions/authActions"; import Spinner from 'react-spinner-material'; import {Redirect} from 'react-router-dom' function extraComponent(props) { const saveNcontinue = (e) => { e.preventDefault() let {email,uid,displayName,photoURL} = props.auth; let id = props.name; let data = { displayName:displayName, email:email, photoURL:photoURL, uid:uid, abigoID:id } console.log(data) props.createRealUser(data) } const handleKeyUp = e => { let userValue = e.target.value if(userValue !== ''){ props.UniqueName(userValue) } } if( props.realUser){ return <Redirect to="/"/> } return ( <div className="extra-component container"> <Spinner size={120} spinnerColor={"#333"} spinnerWidth={2} visible={true} /> <p>1. You are one step ahead . Please choose a unique user name:</p> <form className="col s12" onSubmit={saveNcontinue}> <div className="input-field "> <input id="icon_prefix" type="text" className="validate" onKeyUp={handleKeyUp}/> <label htmlFor="icon_prefix">Choose unique userName</label> </div> { props.name.type ? ( <p className="green-text">@{props.name.name} is avaliable</p> ) : '' } { props.name.type === false ? ( <p className="red-text">@{props.name.name} is unavaliable</p> ):' ' } { props.name.type ? ( <div className="input-field center"> <button type="submit" className="btn waves-effect waves-light custom_color ">Save &amp; Continue</button> </div> ): ( <div className="input-field center"> <button type="submit" className="btn waves-effect waves-light custom_color disabled">Save &amp; Continue</button> </div> )} </form> </div> ) } const mapStateToProps = (state) => { return{ auth:state.firebase.auth, name:state.auth.avaliable, realUser:state.auth.realUser } } const mapDispatch = (dispatch) => { return{ UniqueName:(name) => dispatch(UniqueName(name)), createRealUser:(data) => dispatch(createRealUser(data)) } } export default connect(mapStateToProps,mapDispatch)(extraComponent)
function setup () { createCanvas (500,500); background (100,200,10); } function draw () { fill (20,30,10); ellipse (width/2,height/2,10,20); }
import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import { getRestaurantsList } from 'actions/RestaurantsListActions'; import Subheader from 'material-ui/Subheader'; import Paper from 'material-ui/Paper'; import RestaurantCard from 'components/Card/RestaurantCard'; const styles = { paper: { backgroundColor: 'white', height: '100%', marginTop: 30, }, }; class RestaurantList extends React.PureComponent { constructor(props) { super(props); this.state = { restaurantList: [], }; } componentDidMount() { getRestaurantsList.then( (res) => { if (res.data.restaurants) { this.setState({ restaurantList: res.data.restaurants, }); } }, // (err) => { // // } ); } render() { const { restaurantList } = this.state; return ( <Paper className="container" style={styles.paper}> <Subheader>All restaurants</Subheader> <ul className="row"> {restaurantList.map((restaurant) => ( <li key={restaurant.id}><Link to={`/restaurant/${restaurant.id}`}><RestaurantCard restaurant={restaurant} /></Link></li> // <li key={restaurant.id}> <Link to={'/restaurant/' + restaurant.id} >{restaurant.name}</Link></li> ) )} </ul> </Paper> ); } } const mapStateToProps = (state) => ({ restaurantList: state.get('restaurantList'), }); export default connect(mapStateToProps)(RestaurantList);
var config = { id:"xx-shell", tagId:"explore-horizontal::shell", ratio: { width: 640, height: 1140 }, development: { datasUrl: "../../datas/xx-shell/content.json" }, production: { datasUrl: "//www.lequipe.fr/explore-horizontal/xx-shell/datas/content.json" } }; module.exports = config;
import "antd/lib/switch/style/css"; import Switch from "antd/lib/switch"; export default Switch;
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createProduct, getProductByIds, deleteProduct } from '../../store/actions/productAction'; import PropTypes from 'prop-types'; import { withRouter,Link } from 'react-router-dom'; import { Badge, Card, CardBody, CardHeader, Col, Pagination,Button, PaginationItem, PaginationLink, Row, Table, FormGroup, InputGroup, InputGroupAddon, Input } from 'reactstrap'; import Img from 'react-image'; import Spinner from '../common/Spinner'; class ProductItem extends Component { constructor(props) { super(props); this.state = { name: '', desciption: '', price: 0, image: [] }; } componentDidMount() { // this.props.getProductByIds(this.props.auth.user.user_id); } onChangeTypeProduct = (e) => { this.setState({typeLocation: e.target.value}); } onChange = (e) => { this.setState({ [e.target.name]: e.target.value }); } onSubmit = (e) => { e.preventDefault(); const newProduct = { name: this.state.name, desciption: this.state.desciption, price: this.state.price, image: this.state.image }; this.props.createProduct(newProduct, this.props.history); } editProduct = (e) => { this.props.history.push('/product/edit',{id: e.currentTarget.getElementsByTagName('input')[0].value}); } onAddProduct =(e) => { this.props.history.push('/product/add',{id: ''}); } deleteProduct =(e) => { this.props.deleteProduct({id:e.currentTarget.getElementsByTagName('input')[0].value}) this.setState(this.props.getProductByIds(this.props.auth.user.user_id)); } renderProductItem = (item, index) => { return ( <tr key={index}> <td><Img src={item.images[0]} style={{height:55,width:55}}/></td> <td>{item.name}</td> <td>{item.price}</td> <td><Badge color="danger">Đồ ăn</Badge></td> <td> <Button color="success" size="sm" onClick={this.editProduct}><i className="fa fa-pencil-square-o"></i><input type="hidden" value={item._id}/></Button> <Button color="danger" size="sm" onClick={this.deleteProduct}><i className="fa fa-trash"></i><input type="hidden" value={item._id}/></Button> </td> </tr> ); } render() { const { productByUserIds , loading } = this.props.product; return ( <div className="product-container"> <FormGroup row> <Col sm="8"> <InputGroup> <InputGroupAddon addonType="prepend"> <Button type="button" color="primary" size="lg"><i className="fa fa-search"></i> Tìm kiếm</Button> </InputGroupAddon> <Input type="text" id="input1-group2" size="lg" name="input1-group2" placeholder="Tìm sản phẩm" /> </InputGroup> </Col> <Button onClick={this.onAddProduct} type="button" className="btn btn-lg btn-primary"><i className="fa fa-plus"> Thêm sản phẩm</i></Button> </FormGroup> <Row> <Col xs="12" lg="12"> <Card> <CardHeader> <i className="fa fa-align-justify"></i> Danh sách sản phẩm </CardHeader> <CardBody> { productByUserIds === null || loading ? <Spinner /> : <Table responsive> <thead> <tr> <th>Ảnh</th> <th>Tên Sản Phẩm</th> <th>Giá</th> <th>Loại</th> <th style={{width:'9%'}}>Sửa sản phẩm</th> </tr> </thead> <tbody> {productByUserIds.productByIds !== undefined && productByUserIds.productByIds.map((item, index) => this.renderProductItem(item,index))} </tbody> </Table> } </CardBody> </Card> </Col> </Row> </div> ); } } AddProduct.propTypes = { createProduct: PropTypes.func.isRequired, auth: PropTypes.object.isRequired, errors: PropTypes.object.isRequired }; const mapStateToProps = state => ({ auth: state.auth, errors: state.errors, locationApp: state.locationApp, product: state.product, }); export default connect(mapStateToProps, { createProduct, getProductByIds,deleteProduct })(withRouter(ProductItem));
import React from 'react' import ContentBox from './content-box.jsx' import Styles from './../styles.js' const style = { color: Styles.textColor, fontFamily: Styles.fontFamily, fontSize: Styles.h1Size, fontWeight: '300', textAlign: 'center' } type titleHeaderType = { children: React.Element } const TitleHeader = ({ children }: titleHeaderType): React.Element => ( <ContentBox text> <h1 style={style}> <b style={{fontWeight: '700'}}>Portfolio</b> {children} </h1> </ContentBox> ) export default TitleHeader
//Cuda functions var noCuda = 1 //Provides: caml_sys_system_command function caml_sys_system_command() { //console.log("caml_sys_system_command"); return 0; } //Provides: spoc_cuInit function spoc_cuInit() { //console.log(" spoc_cuInit"); return 0; } //Provides: spoc_cuda_compile function spoc_cuda_compile() { //console.log(" spoc_cuda_compile"); return 0; } //Provides: spoc_cuda_debug_compile function spoc_cuda_debug_compile() { //console.log(" spoc_cuda_debug_compile"); return 0; } //Provides: spoc_getCudaDevice function spoc_getCudaDevice(i) { //console.log("spoc_getCudaDevice"); return 0; } //Provides: spoc_getCudaDevicesCount function spoc_getCudaDevicesCount() { //console.log(" spoc_getCudaDevicesCount"); return 0; } /////////////// //Provides: custom_getsizeofbool function custom_getsizeofbool() { return 0; } var noCL = 0; //Provides: spoc_clInit function spoc_clInit() { if (window.webcl == undefined) { alert("Unfortunately your system does not support WebCL. " + "Make sure that you have both the OpenCL driver " + "and the WebCL browser extension installed."); noCL = 1; } else { /*alert("CONGRATULATIONS! Your system supports WebCL");*/ //console.log ("INIT OPENCL"); noCL = 0; } return 0; } //Provides: spoc_getOpenCLDevice function spoc_getOpenCLDevice(relative_i, absolute_i) { //console.log(" spoc_getOpenCLDevice"); var infos = [ [ "DEVICE_ADDRESS_BITS", WebCL.DEVICE_ADDRESS_BITS ], [ "DEVICE_AVAILABLE", WebCL.DEVICE_AVAILABLE ], [ "DEVICE_COMPILER_AVAILABLE", WebCL.DEVICE_COMPILER_AVAILABLE ], [ "DEVICE_ENDIAN_LITTLE", WebCL.DEVICE_ENDIAN_LITTLE ], [ "DEVICE_ERROR_CORRECTION_SUPPORT", WebCL.DEVICE_ERROR_CORRECTION_SUPPORT ], [ "DEVICE_EXECUTION_CAPABILITIES", WebCL.DEVICE_EXECUTION_CAPABILITIES ], [ "DEVICE_EXTENSIONS", WebCL.DEVICE_EXTENSIONS ], [ "DEVICE_GLOBAL_MEM_CACHE_SIZE", WebCL.DEVICE_GLOBAL_MEM_CACHE_SIZE ], [ "DEVICE_GLOBAL_MEM_CACHE_TYPE", WebCL.DEVICE_GLOBAL_MEM_CACHE_TYPE ], [ "DEVICE_GLOBAL_MEM_CACHELINE_SIZE", WebCL.DEVICE_GLOBAL_MEM_CACHELINE_SIZE ], [ "DEVICE_GLOBAL_MEM_SIZE", WebCL.DEVICE_GLOBAL_MEM_SIZE ], [ "DEVICE_HALF_FP_CONFIG", WebCL.DEVICE_HALF_FP_CONFIG ], [ "DEVICE_IMAGE_SUPPORT", WebCL.DEVICE_IMAGE_SUPPORT ], [ "DEVICE_IMAGE2D_MAX_HEIGHT", WebCL.DEVICE_IMAGE2D_MAX_HEIGHT ], [ "DEVICE_IMAGE2D_MAX_WIDTH", WebCL.DEVICE_IMAGE2D_MAX_WIDTH ], [ "DEVICE_IMAGE3D_MAX_DEPTH", WebCL.DEVICE_IMAGE3D_MAX_DEPTH ], [ "DEVICE_IMAGE3D_MAX_HEIGHT", WebCL.DEVICE_IMAGE3D_MAX_HEIGHT ], [ "DEVICE_IMAGE3D_MAX_WIDTH", WebCL.DEVICE_IMAGE3D_MAX_WIDTH ], [ "DEVICE_LOCAL_MEM_SIZE", WebCL.DEVICE_LOCAL_MEM_SIZE ], [ "DEVICE_LOCAL_MEM_TYPE", WebCL.DEVICE_LOCAL_MEM_TYPE ], [ "DEVICE_MAX_CLOCK_FREQUENCY", WebCL.DEVICE_MAX_CLOCK_FREQUENCY ], [ "DEVICE_MAX_COMPUTE_UNITS", WebCL.DEVICE_MAX_COMPUTE_UNITS ], [ "DEVICE_MAX_CONSTANT_ARGS", WebCL.DEVICE_MAX_CONSTANT_ARGS ], [ "DEVICE_MAX_CONSTANT_BUFFER_SIZE", WebCL.DEVICE_MAX_CONSTANT_BUFFER_SIZE ], [ "DEVICE_MAX_MEM_ALLOC_SIZE", WebCL.DEVICE_MAX_MEM_ALLOC_SIZE ], [ "DEVICE_MAX_PARAMETER_SIZE", WebCL.DEVICE_MAX_PARAMETER_SIZE ], [ "DEVICE_MAX_READ_IMAGE_ARGS", WebCL.DEVICE_MAX_READ_IMAGE_ARGS ], [ "DEVICE_MAX_SAMPLERS", WebCL.DEVICE_MAX_SAMPLERS ], [ "DEVICE_MAX_WORK_GROUP_SIZE", WebCL.DEVICE_MAX_WORK_GROUP_SIZE ], [ "DEVICE_MAX_WORK_ITEM_DIMENSIONS", WebCL.DEVICE_MAX_WORK_ITEM_DIMENSIONS ], [ "DEVICE_MAX_WORK_ITEM_SIZES", WebCL.DEVICE_MAX_WORK_ITEM_SIZES ], [ "DEVICE_MAX_WRITE_IMAGE_ARGS", WebCL.DEVICE_MAX_WRITE_IMAGE_ARGS ], [ "DEVICE_MEM_BASE_ADDR_ALIGN", WebCL.DEVICE_MEM_BASE_ADDR_ALIGN ], [ "DEVICE_NAME", WebCL.DEVICE_NAME ], [ "DEVICE_PLATFORM", WebCL.DEVICE_PLATFORM ], [ "DEVICE_PREFERRED_VECTOR_WIDTH_CHAR", WebCL.DEVICE_PREFERRED_VECTOR_WIDTH_CHAR ], [ "DEVICE_PREFERRED_VECTOR_WIDTH_SHORT", WebCL.DEVICE_PREFERRED_VECTOR_WIDTH_SHORT ], [ "DEVICE_PREFERRED_VECTOR_WIDTH_INT", WebCL.DEVICE_PREFERRED_VECTOR_WIDTH_INT ], [ "DEVICE_PREFERRED_VECTOR_WIDTH_LONG", WebCL.DEVICE_PREFERRED_VECTOR_WIDTH_LONG ], [ "DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT", WebCL.DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT ], [ "DEVICE_PROFILE", WebCL.DEVICE_PROFILE ], [ "DEVICE_PROFILING_TIMER_RESOLUTION", WebCL.DEVICE_PROFILING_TIMER_RESOLUTION ], [ "DEVICE_QUEUE_PROPERTIES", WebCL.DEVICE_QUEUE_PROPERTIES ], [ "DEVICE_SINGLE_FP_CONFIG", WebCL.DEVICE_SINGLE_FP_CONFIG ], [ "DEVICE_TYPE", WebCL.DEVICE_TYPE ], [ "DEVICE_VENDOR", WebCL.DEVICE_VENDOR ], [ "DEVICE_VENDOR_ID", WebCL.DEVICE_VENDOR_ID ], [ "DEVICE_VERSION", WebCL.DEVICE_VERSION ], [ "DRIVER_VERSION", WebCL.DRIVER_VERSION ] ]; var total_num_devices = 0; var general_info = [0]; var opencl_info = [1]; var specific_info = new Array (48); specific_info[0] = 0; var platform_info = [0]; var platforms = webcl.getPlatforms (); for (var z in platforms) { var plat = platforms[z]; var devices = plat.getDevices (); total_num_devices += devices.length; } var current = 0; platforms = webcl.getPlatforms (); for (var i in platforms) { //console.log("here "+i); var plat = platforms[i]; var devices = plat.getDevices (); var num_devices = devices.length; //console.log("there "+current+" "+num_devices+" "+relative_i); if ( (current + num_devices) >= relative_i) { for (var d in devices){ // looking at current device var dev = devices[d]; if (current == relative_i ){ //console.log("current ----------"+current); //general info general_info[1] = caml_new_string(dev.getInfo(WebCL.DEVICE_NAME)); //console.log (general_info[1]); general_info[2] = dev.getInfo(WebCL.DEVICE_GLOBAL_MEM_SIZE); general_info[3] = dev.getInfo(WebCL.DEVICE_LOCAL_MEM_SIZE); general_info[4] = dev.getInfo(WebCL.DEVICE_MAX_CLOCK_FREQUENCY); general_info[5] = dev.getInfo(WebCL.DEVICE_MAX_CONSTANT_BUFFER_SIZE); general_info[6] = dev.getInfo(WebCL.DEVICE_MAX_COMPUTE_UNITS); general_info[7] = dev.getInfo(WebCL.DEVICE_ERROR_CORRECTION_SUPPORT); general_info[8] = absolute_i; var context = new Array(3); //cl_contex + 2 queues context[0] = webcl.createContext (dev); context[1] = context[0].createCommandQueue(); context[2] = context[0].createCommandQueue(); general_info[9] = context; //platform info platform_info[1] = caml_new_string(plat.getInfo(WebCL.PLATFORM_PROFILE)); platform_info[2] = caml_new_string(plat.getInfo(WebCL.PLATFORM_VERSION)); platform_info[3] = caml_new_string(plat.getInfo(WebCL.PLATFORM_NAME)); platform_info[4] = caml_new_string(plat.getInfo(WebCL.PLATFORM_VENDOR)); platform_info[5] = caml_new_string(plat.getInfo(WebCL.PLATFORM_EXTENSIONS)); platform_info[6] = num_devices; //specific info var infoType = dev.getInfo(WebCL.DEVICE_TYPE); var type = 0; if (infoType & WebCL.DEVICE_TYPE_CPU) specific_info[2] = 0; if (infoType & WebCL.DEVICE_TYPE_GPU) specific_info[2] = 1; if (infoType & WebCL.DEVICE_TYPE_ACCELERATOR) specific_info[2] = 2; if (infoType & WebCL.DEVICE_TYPE_DEFAULT) specific_info[2] = 3; specific_info[3] = caml_new_string(dev.getInfo(WebCL.DEVICE_PROFILE)); specific_info[4] = caml_new_string(dev.getInfo(WebCL.DEVICE_VERSION)); specific_info[5] = caml_new_string(dev.getInfo(WebCL.DEVICE_VENDOR)); var ext = dev.getInfo(WebCL.DEVICE_EXTENSIONS); specific_info[6] = caml_new_string(ext); specific_info[7] = dev.getInfo(WebCL.DEVICE_VENDOR_ID); specific_info[8] = dev.getInfo(WebCL.DEVICE_MAX_WORK_ITEM_DIMENSIONS); specific_info[9] = dev.getInfo(WebCL.DEVICE_ADDRESS_BITS); specific_info[10] = dev.getInfo(WebCL.DEVICE_MAX_MEM_ALLOC_SIZE); specific_info[11] = dev.getInfo(WebCL.DEVICE_IMAGE_SUPPORT); specific_info[12] = dev.getInfo(WebCL.DEVICE_MAX_READ_IMAGE_ARGS); specific_info[13] = dev.getInfo(WebCL.DEVICE_MAX_WRITE_IMAGE_ARGS); specific_info[14] = dev.getInfo(WebCL.DEVICE_MAX_SAMPLERS); specific_info[15] = dev.getInfo(WebCL.DEVICE_MEM_BASE_ADDR_ALIGN); specific_info[16] = 0;//dev.getInfo(WebCL.DEVICE_MIN_DATA_TYPE_ALIGN_SIZE); specific_info[17] = dev.getInfo(WebCL.DEVICE_GLOBAL_MEM_CACHELINE_SIZE); specific_info[18] = dev.getInfo(WebCL.DEVICE_GLOBAL_MEM_CACHE_SIZE); specific_info[19] = dev.getInfo(WebCL.DEVICE_MAX_CONSTANT_ARGS); specific_info[20] = dev.getInfo(WebCL.DEVICE_ENDIAN_LITTLE); specific_info[21] = dev.getInfo(WebCL.DEVICE_AVAILABLE); specific_info[22] = dev.getInfo(WebCL.DEVICE_COMPILER_AVAILABLE); specific_info[23] = dev.getInfo(WebCL.DEVICE_SINGLE_FP_CONFIG); specific_info[24] = dev.getInfo(WebCL.DEVICE_GLOBAL_MEM_CACHE_TYPE); specific_info[25] = dev.getInfo(WebCL.DEVICE_QUEUE_PROPERTIES); specific_info[26] = dev.getInfo(WebCL.DEVICE_LOCAL_MEM_TYPE); specific_info[27] = 0;//dev.getInfo(WebCL.DEVICE_DOUBLE_FP_CONFIG); specific_info[28] = dev.getInfo(WebCL.DEVICE_MAX_CONSTANT_BUFFER_SIZE); specific_info[29] = dev.getInfo(WebCL.DEVICE_EXECUTION_CAPABILITIES); specific_info[30] = 0; //dev.getInfo(WebCL.DEVICE_HALF_FP_CONFIG); specific_info[31] = dev.getInfo(WebCL.DEVICE_MAX_WORK_GROUP_SIZE); specific_info[32] = dev.getInfo(WebCL.DEVICE_IMAGE2D_MAX_HEIGHT); specific_info[33] = dev.getInfo(WebCL.DEVICE_IMAGE2D_MAX_WIDTH); specific_info[34] = dev.getInfo(WebCL.DEVICE_IMAGE3D_MAX_DEPTH); specific_info[35] = dev.getInfo(WebCL.DEVICE_IMAGE3D_MAX_HEIGHT); specific_info[36] = dev.getInfo(WebCL.DEVICE_IMAGE3D_MAX_WIDTH); specific_info[37] = dev.getInfo(WebCL.DEVICE_MAX_PARAMETER_SIZE); specific_info[38] = [0] var dim_sizes = dev.getInfo(WebCL.DEVICE_MAX_WORK_ITEM_SIZES); specific_info[38][1] = dim_sizes[0]; specific_info[38][2] = dim_sizes[1]; specific_info[38][3] = dim_sizes[2]; specific_info[39] = dev.getInfo(WebCL.DEVICE_PREFERRED_VECTOR_WIDTH_CHAR); specific_info[40] = dev.getInfo(WebCL.DEVICE_PREFERRED_VECTOR_WIDTH_SHORT); specific_info[41] = dev.getInfo(WebCL.DEVICE_PREFERRED_VECTOR_WIDTH_INT); specific_info[42] = dev.getInfo(WebCL.DEVICE_PREFERRED_VECTOR_WIDTH_LONG); specific_info[43] = dev.getInfo(WebCL.DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT); specific_info[44] = 0; //dev.getInfo(WebCL.DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE ); specific_info[45] = dev.getInfo(WebCL.DEVICE_PROFILING_TIMER_RESOLUTION); specific_info[46] = caml_new_string(dev.getInfo(WebCL.DRIVER_VERSION)); current++; break; } else { current++; } } } else { current += num_devices; } } var dev = [0]; specific_info[1] = platform_info; opencl_info[1] = specific_info; dev[1] = general_info; dev[2] = opencl_info; return dev; } //Provides: spoc_getOpenCLDevicesCount function spoc_getOpenCLDevicesCount() { //console.log(" spoc_getOpenCLDevicesCount"); var nb_devices = 0; var platforms = webcl.getPlatforms (); for (var i in platforms) { var plat = platforms[i]; var devices = plat.getDevices (); nb_devices += devices.length; } return nb_devices; } //Provides: spoc_opencl_compile function spoc_opencl_compile() { //console.log(" spoc_opencl_compile"); return 0; } //Provides: spoc_opencl_is_available function spoc_opencl_is_available() { //console.log(" spoc_opencl_is_available"); return (!noCL); } //Provides: caml_thread_initialize function caml_thread_initialize() { //console.log("caml_thread_initialize"); return 0; } //Provides: caml_mutex_new function caml_mutex_new() { //console.log("caml_mutex_new"); return 0; } //Provides: caml_thread_cleanup function caml_thread_cleanup() { //console.log("caml_thread_cleanup"); return 0; }
const { gClient, restClient } = require("../tool/request"); const jwt = require("jsonwebtoken"); const config = require("../config/config"); const injectGadmin = function (req, res, next) { console.dir("当前的req参数"); console.log(JSON.stringify(req.url)); isInit = req.url.indexOf("store"); let magento; if (!req.headers["website"]) { req.headers["website"] = "panama"; } magento = magentos[req.headers["website"]]; // 获取后端权限 if (req.headers["store"]) { let list = magento.list; req.storeId = list[req.headers["store"]]; } // ❌ 不一定要带货币 // if (!req.headers["content-currency"]) { // req.headers["content-currency"] = "USD"; // } if (!req.headers["store"] && isInit < 0) { // 如果没带store 同时,也不是初始化请求,就报错 return next(new APIError("语言代码不存在", 200, true)); } let realtoken = magento.token; // 如果没token就是admin token let noneedToken = [ "/category", "/product", "/product/", "/product/detail", "/product/detail-config", "/store", "/store/", "/store/countries", "/store/config", "/auth/token", "/user/create", "/category/home", "/product/sortedWithAtt", "/store/productReviewRatingsMetadata", "/store/menu", "/event/venueList", "/page/homepage", "/sms/sendCode", "/sms/sendEmail", "/push/pushOne", "/product/enterpriseList", "/product/enterpriseCategory", "/product/related", "/event/order", "/checkout/guestCart", "/checkout/cart", "/user/emailReg", "/guestcheckout/guestCart", "/guestcheckout/guestCartCoupon", "/guestcheckout/addVirtualProductsToCart", "/guestcheckout/addSimpleProductsToCart", "/guestcheckout/addConfigurableProductsToCart", "/guestcheckout/placeOrder", "/guestcheckout/setBillingAddressOnCart", // 设置账单地址 "/guestcheckout/removeCouponFromCart", "/guestcheckout/updateCartItems", "/guestcheckout/removeItemFromCart", "/guestcheckout/oneStepCreateOrder", "/order", "/pay", "/pay/getOrderByRef", "/pay/genQrcode", "/pay/confirm", ]; if (!!req.headers["authorization"]) { console.log("%c 有token 解析下", "color:green;font-weight:bold"); // 如果有token 解析下 let t = req.headers["authorization"]; t = t.slice(7); console.log("%c t", "color:green;font-weight:bold"); console.log(JSON.stringify(t)); let userInfo = jwt.verify(t, config.jwtSecret); console.log("%c userInfo", "color:green;font-weight:bold"); console.log(JSON.stringify(userInfo)); userInfo.userId = userInfo.id; // 聊天哪里需要用 req.userToken = userInfo.token; req.magentoHost = magento.host; req.user = userInfo; console.dir("当前用户的信息"); console.log(JSON.stringify(userInfo)); } else if (!noneedToken.includes(req.path)) { console.dir("没带token"); return next(new APIError("没带token", 200, true)); } // 访客的名义 let gGuest = gClient( null, req.headers["content-currency"], req.headers["store"], magento.host ); // 后台的名义 let gAdmin = gClient( realtoken, req.headers["content-currency"], req.headers["store"], magento.host ); // 某个的用户的名义 let gUer = gClient( req.userToken, req.headers["content-currency"], req.headers["store"], magento.host ); let rest = restClient(realtoken, req.headers["store"], magento.host); let restAdmin = restClient(realtoken, null, magento.host); req.gAdmin = gAdmin; req.gUser = gUer; req.rest = rest; req.restAdmin = restAdmin; req.gGuest = gGuest; next(); }; module.exports = injectGadmin;
var _ = require('lodash'); var React = require('react'); var EmptyComponent = React.createClass({ render: function() { return false; }, }); module.exports = function getRestrictRoles(UserStore) { return function restrictRoles(roles, Component, AlternativeComponent) { AlternativeComponent = AlternativeComponent || EmptyComponent; return React.createClass({ getInitialState() { return UserStore.getState(); }, componentDidMount() { UserStore.listen(this.onChange); }, componentWillUnmount() { UserStore.unlisten(this.onChange); }, onChange(state) { this.setState(state); }, render() { if (this.state.currentUser && _.some(roles, role => this.state.currentUser.hasRole(role))) { return <Component {...this.props} />; } else { return <AlternativeComponent />; } }, }); }; };
import React, {PropTypes} from 'react'; import {truncate} from '../Helpers'; const Sha = ({build, truncateMaxLength}) => { if (!build.commitInfo) { return null; // TODO: find this info somewhere else, then } const commitLink = build.commitInfo.current.url; return ( <span className="sha"> <a href={commitLink} className="sha-link" target="_blank">{truncate(build.sha, truncateMaxLength)}</a> </span> ); }; Sha.defaultProps = { truncateMaxLength: 10 }; Sha.propTypes = { build: PropTypes.object.isRequired, truncateMaxLength: PropTypes.number }; export default Sha;
//function ageCalculator(date) //return new date.timestamp; //console.log(ageCalculator(date)); var date = new date('January 31,1980 11:20:00') function ageCalculator(date) { var diff = Date.now() - date.getTime(); var age = new Date(diff); return Math.abs(age.getUTCFullYear() - 1980); }; console.log(ageCalculator(new Date('1980, 01, 31'))); //Date(année, mois, jour) //const date1 = new Date('December 17, 1995 03:24:00'); // Sun Dec 17 1995 03:24:00 GMT... //const date2 = new Date('1995-12-17T03:24:00'); // Sun Dec 17 1995 03:24:00 GMT...
const jwt=require("jsonwebtoken") const secret="jhdsjadkahdjashdkjhanmmc23vnxmcv5448njds54ifeijfiesjkfsldfj" module.exports=function(req,res,next){ const authToken=req.headers['authorization'] if(authToken!=undefined){ const bearer=authToken.split(' '); const token=bearer[1]; try{ const decoded=jwt.verify(token,secret) //Decodifica o token if(decoded.role==1){ console.log(decoded) next(); }else{ res.status(403); res.send("Você não tem permissão para isso") return; } }catch(err){ res.status(403); res.send("Você não está autenticado") return; } }else{ res.status(403); res.send("Você não está autenticado") return; } }
import React, { Component } from 'react' import { Container } from './styles' import { bindActionCreators } from 'redux' import { connect } from 'react-redux' import { Creators as UsersActions } from '../../store/ducks/users' class Alert extends Component { render() { const { error } = this.props if (error) { setTimeout(() => { this.props.closeErrorMsg() }, 5000) } return ( <Container visible={error}> <span>Usuário não encontrado.</span> </Container> ) } } const mapStateToProps = state => ({ error: state.users.error, }) const mapDispatchToProps = dispatch => bindActionCreators(UsersActions, dispatch) export default connect( mapStateToProps, mapDispatchToProps )(Alert)
/* * @lc app=leetcode id=1139 lang=javascript * * [1139] Largest 1-Bordered Square * * https://leetcode.com/problems/largest-1-bordered-square/description/ * * algorithms * Medium (45.81%) * Likes: 124 * Dislikes: 34 * Total Accepted: 7.2K * Total Submissions: 15.8K * Testcase Example: '[[1,1,1],[1,0,1],[1,1,1]]' * * Given a 2D grid of 0s and 1s, return the number of elements in the largest * square subgrid that has all 1s on its border, or 0 if such a subgrid doesn't * exist in the grid. * * * Example 1: * * * Input: grid = [[1,1,1],[1,0,1],[1,1,1]] * Output: 9 * * * Example 2: * * * Input: grid = [[1,1,0,0]] * Output: 1 * * * * Constraints: * * * 1 <= grid.length <= 100 * 1 <= grid[0].length <= 100 * grid[i][j] is 0 or 1 * */ // @lc code=start /** * @param {number[][]} grid * @return {number} */ var largest1BorderedSquare = function(grid) { const width = grid[0].length; const height = grid.length; const defaultValue = {x: 0, y: 0}; // dp记录每个点在x y 方向的最大宽度 const dp = []; for (let y = 0; y <= height; y++) { dp[y] = dp[y] || []; for (let x = 0; x <= width; x++) { dp[y][x] = {...defaultValue} } } let max = 0; for (let y = 1; y <= height; y++) { for (let x = 1; x <= width; x++) { if (grid[y - 1][x - 1]) { const yWidth = (dp[y - 1][x]).y + 1; const xWidth = (dp[y][x - 1]).x + 1; dp[y][x] = {x: xWidth, y: yWidth} const maxWidth = Math.min(yWidth, xWidth); for (let w = maxWidth; w > 0; w--) { if (dp[y - w + 1][x].x >= w && dp[y][x - w + 1].y >= w) { if (max < w) { max = w; } } } } } } return max * max; }; // @lc code=end largest1BorderedSquare([[1,1,1],[1,0,1],[1,1,1]])
export const secrets = { facebookAppId: '2005654466400264' };
var plusOne = function(digits) { for (let i = digits.length - 1; i >= 0; i--) { if (digits[i] < 9) { digits[i] = digits[i] + 1; return digits; } else { digits[i] = 0; } } // if we have [9, 9] digits.unshift(1); return digits; // doesn't work for numbers that are really large // let number = parseInt(digits.join('')); // let newNum = number + 1; // let arr = newNum.toString().split(''); // return arr.map(n => parseInt(n)); };
import React from "react"; import api from "../../libs/api"; import SelectDatePopover, { dateCalculator } from "./selectDatePopover"; import moment from "moment"; import BlockUi from "react-block-ui"; import { withTranslation } from "~/i18n"; import StatisticPopover from "./statisticPopover"; class DashboardStatistic extends React.Component { constructor(props) { super(props); this.apis = new api(this.props.domain).group("dashboard"); this.NAME = "dashboardStatisticDate"; const { t } = this.props; this.state = { invoiceStatistic: { unit: "Of Invoices" }, automergeStatistic: { unit: "Of Auto Matched" }, umatchStatistic: { unit: "Of Unmatched" }, poStatistic: { unit: "Of Purchase Orders" }, grStatistic: { unit: "Of Goods Receipt" }, loading: false, date: { name: "Today", value: { from: moment() .startOf("day") .format("DD/MM/YYYY"), to: moment() .endOf("day") .format("DD/MM/YYYY") }, check: true } }; } async componentDidMount() { let date = localStorage.getItem(this.NAME); date = JSON.parse(date); if (date) { let dateList = new dateCalculator(); let newDate = dateList.filter(r => date.name == r.name); if (newDate.length == 1) { date = newDate[0]; } await this.setState({ date }); } await this.fetchData(); } fetchData = async () => { this.setState({ loading: true }); try { const invoiceStatistic = await this.apis.call("invoiceStatistic", { currency: "THB", invoiceEntryDateFrom: this.state.date.value.from, invoiceEntryDateTo: this.state.date.value.to }); const automergeStatistic = await this.apis.call("automergeStatistic", { currency: "THB", invoiceEntryDateFrom: this.state.date.value.from, invoiceEntryDateTo: this.state.date.value.to, isAutoMatched: true, groupBy: "matchingStatus" }); const umatchStatistic = await this.apis.call("umatchStatistic", { currency: "THB", invoiceEntryDateFrom: this.state.date.value.from, invoiceEntryDateTo: this.state.date.value.to, isAutoMatched: false }); const poStatistic = await this.apis.call("poStatistic", { currency: "THB", entryDateFrom: this.state.date.value.from, entryDateTo: this.state.date.value.to }); const grStatistic = await this.apis.call("grStatistic", { currency: "THB", postingDateFrom: this.state.date.value.from, postingDateTo: this.state.date.value.to }); this.setState({ invoiceStatistic: { ...invoiceStatistic, unit: this.state.invoiceStatistic.unit }, automergeStatistic: { ...automergeStatistic, unit: this.state.automergeStatistic.unit }, umatchStatistic: { ...umatchStatistic, unit: this.state.umatchStatistic.unit }, poStatistic: { ...poStatistic, unit: this.state.poStatistic.unit }, grStatistic: { ...grStatistic, unit: this.state.grStatistic.unit } }); } catch (e) { console.log(e); } this.setState({ loading: false }); }; onChange = item => { window.localStorage.setItem(this.NAME, JSON.stringify(item)); this.setState( { date: item }, () => this.fetchData() ); }; formatNumber = number => { return Intl.NumberFormat("th-TH").format(number); }; sumValue = data => { return data.amountTotal && data.amountTotal.quantity ? data.amountTotal.quantity * data.amountTotal.displayTokenSize : 0; }; render() { const { t } = this.props; return ( <BlockUi blocking={this.state.loading}> <section className="box box--width-header col-12"> <div className="box__header"> <div className="d-flex flex-wrap justify-content-between pt-3 pt-lg-2"> <div className="col"> <h5 className="gray-1">{t("Statistics")}</h5> </div> <div className="col d-flex justify-content-end"> <SelectDatePopover date={this.state.date} onChange={this.onChange} /> </div> </div> </div> <div className="box__inner p-0"> <div className="d-flex flex-wrap"> <StatisticPopover unit={this.state.invoiceStatistic.unit} countTotal={this.state.invoiceStatistic.countTotal} value={this.sumValue(this.state.invoiceStatistic)} token={ this.state.invoiceStatistic.amountTotal && this.state.invoiceStatistic.amountTotal.token } /> <StatisticPopover unit={this.state.automergeStatistic.unit} countTotal={this.state.automergeStatistic.countTotal} value={this.sumValue(this.state.automergeStatistic)} token={ this.state.automergeStatistic.amountTotal && this.state.automergeStatistic.amountTotal.token } /> <StatisticPopover unit={this.state.umatchStatistic.unit} countTotal={this.state.umatchStatistic.countTotal} value={this.sumValue(this.state.umatchStatistic)} token={ this.state.umatchStatistic.amountTotal && this.state.umatchStatistic.amountTotal.token } /> <StatisticPopover unit={this.state.poStatistic.unit} countTotal={this.state.poStatistic.countTotal} value={this.sumValue(this.state.poStatistic)} token={ this.state.poStatistic.amountTotal && this.state.poStatistic.amountTotal.token } /> <StatisticPopover unit={this.state.grStatistic.unit} countTotal={this.state.grStatistic.countTotal} value={this.sumValue(this.state.grStatistic)} token={ this.state.grStatistic.amountTotal && this.state.grStatistic.amountTotal.token } hideTooltip={true} /> </div> </div> </section> </BlockUi> ); } } export default withTranslation(["dashboard", "common", "menu"])( DashboardStatistic );
module.exports = `-----BEGIN RSA PRIVATE KEY----- MIIJJwIBAAKCAgEAnAQMQ1nLI4Gf941phu8G74AuGZDmKSVKFU8/1+f75v5jP/JI SV+xxhWe/a2KXdvIJTt8CtVFfE4L7E5P9MVF9HIfmm3O6H3PZpyx/dnGfcA3KuC6 ODMahMHi91HDL91DxWFHtvvB7XVkR6HrJqA/xz9aIiEdxJESsMIfbex5NeuyO3oC hKRnshIAdLbrYznYQivgfmHF1oQbSF8kQfCa2aLMojDT85mOl5ABHAJxim3G5rJr VjKZDCDe2jBWho3pA8JjJDW8AcsglUTfTTqO2hdVn5IoUSpXKzwBZAUIklPYU6Ma za4pyHPCeqJb28LOotK1U8cJLO7JBtxFBhVtr1KVneApox4isGvzidOkrhIB14qC /B1DJ/M9C73cGw9ip1ZzqlTHwfaqO+T+myG6uY08fLLLdhIaOT+D2cP+WeFIif6y KuZzaPX/iAblRDVwzON+gWTq5W6v0TaqrMmCF+QlJkbniD260Yh7NVtGBW2sweVG qOlfmC5pmhWQ5h/6FINo8HNEwUGgOHlZilr0lew3UkMlRmGSraDVeoxhAOkDTkLd 5iuBoRNFA5Mzvwvr4Hl2vDXGcIePJKcA24z5xTXMuuyUT4UtZcOkzDl+9QlTN5ny Ka4u7kpx1tVL0p3deXVW6tYOQNQqr8Sd50Ftz5CJ3eg39Xeq2kCiLevtdh8CAwEA AQKCAgAs37UvQgp9ofEC4PezSdjy1ilsTRMGTqVqT6sLTLxVimG9qNBF2nJliR57 1Ihxyp9cpildbE5aHJCtXTD+NCeU0aZpYqAamuUmnHdNjm/bB4hWmuC0/W3pNWM0 w52ijL/La9mWtf7nb9ZyDA54w6rUglJIcsH/IcMAeDVWBqgubCaNmOBUin0Q6MCc 0WgO2DptffVKJJEkzEaUoFjrZmsDoiG9nNG5xTcQPOk0xzclG8IT5Mmet1rx9Bpl I3YfqX2WCTk+1v3GfkhW5sJbkjY4YHHOPdm+zrDXzKCRxija/abBF67D7g4yi6kq YLyPDw8kIfrpp9vpwpyrjnuD7nHngeWFTnapjfcbuGx9XzHd5B2JQid6Dp5iuwgg lj3Tsk0Y457LRPLMFXX364ukb3evQwddOEhDpYGN0sXr06V4BbCFSiZrlrKOotk9 D11ovayP8qsl8SowotfUvikSySFCV+k/ZWIKLNoy42Vfx8BL4kkrAuexhDF5kwt5 dpnxc15UufBmZ2ukOwZiV93pBM8yb8V+Jlp6qHEEUwFB298OnjJBpW/lbnFfj3M6 +WxueLc9DS5rBQlkmPJ+yA7XrIoQ/6OEVlgXDTnpkuVC0yx2ksVWiPMRvMXbEXjZ 9nJiMUYF74aBNzatzuLVyPLLRjcXErD76oMnn9U8wq9oD8z2EQKCAQEA36ynMNCw R43dlg8OmgNMC1iLpCK0xU4EIfL/AxKFZxAlFdDgpTFqZzvgLpY2MEML0TrGxXUP INwKiuTeNcP1bBAMwHbxaPjnSEAn7dNw4jmIWDNOi41cjelbWSNsmjF1cpkiSv9p 5ibpvyp92ecKFXrok/tGQF40petJuczi87rnUFAKGxJLaAvvag/TCmbdP8JBAYAk 6N2s28Kb2ChYZEMFs3H5TpLKfBMdCYaN2MUHuBEztNTyvcarl4MHtiwPy8cSzgmQ j1grvl5m/YxgL/g8qlSOU9CcYO8W3QtddkxuiA/jAC/9nxjIT247JnvM9e7WVu6S Hgv4AsJOXSlXswKCAQEAspA1rGMiTvsJp4ZCg/uLnGmAfUbvEQFDTlSe78ZFjjx2 45xrfgQds77mwqnoqbRSMH7CndCTrlO7GbiBr7ppFjp8ZFfiQie5902tZGj8fNZV GJoKgnIgQ45uZV3zscXDbeK5tw8n8fzOzZN94UBLPyMjAax0uWzDN5dgmaX4gfH7 PtDcrWcvp57OOwrMHF9yqh9Rk+HntogfDhArT+Z8t3o8O6I1u8jdsiDyIIOb4DQa 1Zy5KGra8tY/Y3QpWlMUUk2G9OWqKeOVmWd0hTZvYEvjPzt2QIsHy/W00NXWwGcy dBNU5bR5SthP3uRgciguM5t0teLgqUZGHeApctRx5QKCAQAHCnlM2RTje7zA74Jn KLlpFgV3SjxkhZstsmeCoj+eyexQ7n1T1eVikIjzDnlwNXwWvwHoz1GFmEegramt CZkdKLguCtB4nHUzWgmnu+Muy97V3++WBwIl2XWtrabKh8oJrHZe5AFiZFExWlYR 2OsBWBggKGXCuvRvUKPGfIOcZoLHjW10ArRq9w03Sn47Mpe+XRAMywreZbP+Svb6 6/I0XcO9LVZKueYz16ovVZP7geBHVAtLovRtMubN4ysH+gUZRg/6emSZjo359SDK 1HNmryrBtd2xF70EdCJFHQl5ItjL4awkol4adv4/OdoU0QrXpwgKPoJM/dV1yMYM urNvAoIBAHZ4GTQzXXrbMU+VUyIvzTPMB3SWkFxO4zHgEMbyXAl/cj2W9PZZkr9D o+R5SCT3vyPvpf2AecrKQLNS57AIVFpsGUWVzUapBsfeIHEi+ol0xmaZJOnhACjy IapdSCalGAEa0K50fsMdQLPB7F17A7FzBXHB0nuHfomuhGfMZvEH8/J8Lj1Z3ZMv WJJxmnQkm3Xla4Fa+xnue/QfpCzRteMhVT8XYuEg5n2dQCd0SgHZcAhTf8EiC/vb S5kXY6xKvIvSZfyrN1etZ/6sVfFf6UsRbkbwk4dE9rpKXVnE1kM29JFwlf4E3Ahd Nbii+p4irGyO8kMOsJF+T1zY8Yb/DkUCggEAVcjj6jj4bHUsebj4hR72mrrnjyd7 r+omFKXuq9X8lUsVjVIKzJ7ZGRQhM7hkJjxFqu/aH+3zGPdauNYYU4GrmNzmMJRD 11Ti4I4V4USbMJi4Pooq1e00qroK+EAuDtQQB1DURNjaVpV39yLeLyvDQgSh9d5W /fvGefGilmzbImNZcNqdaZw7GHYBPzSRDhmWJTWSp3OqgUd6bF9Ho0x9ZTLt3wRo MrDYPfz9EJAS/9yVS7Vo2PAhFdPBDkp5m2I9epxP6adM6s7oNej8bg3FeQaEsgGX LCKOvVn9Wm7LwQdwBAH78yOD0cwgrrxjjJXQo7UMKSXaR789DisoOcuNcQ== -----END RSA PRIVATE KEY-----`;
import CustomerService from "../../services/CustomerService"; export const fetchCustomers = async ({state, commit}) => { await CustomerService.index(state.nextPage, state.limit, state.searchKey) .then(response => { const { data : { meta: meta } } = response; const { data : { data: customers } } = response; commit('setCustomers', customers); commit('setCustomersNextPage', meta.current_page + 1); return commit('setCustomersLastPage', meta.last_page); }) .catch(error => { throw error.response; }) }; export const searchCustomers = async ({commit, dispatch}, searchKey) => { commit('setCustomersSearchKey', searchKey); dispatch('resetAll') return dispatch('fetchCustomers'); }; export const resetAll = ({commit}) => { commit('resetCustomers'); commit('resetCustomersNextPage'); commit('resetCustomersLastPage'); } export const addCustomer = async ({dispatch}, customer) => { await CustomerService.store(customer) .then(() => { return dispatch('fetchCustomers'); }) .catch(error => { throw error.response; }) }; export const editCustomer = async ({dispatch}, customer) => { await CustomerService.update(customer) .then(() => { dispatch('resetAll'); return dispatch('fetchCustomers'); }) .catch(error => { throw error.response; }) }; export const deleteCustomer = async ({dispatch}, customerId) => { await CustomerService.destroy(customerId) .then(() => { dispatch('resetAll'); return dispatch('fetchCustomers'); }) .catch(error => { throw error.response; }) };