text stringlengths 7 3.69M |
|---|
(function (angular) {
angular
.module('angularConsent.controllers')
.controller('angularConsent.ConsentController', ConsentController);
function ConsentController($cookies, $attrs){
this.getCookieKey = function(){
return 'angular-consent.' + ($attrs.consent || 'global');
};
this.getCookieValue = function(){
return $cookies.get(this.getCookieKey());
};
this.setCookieValue = function(value){
return $cookies.put(this.getCookieKey(), value);
};
this.hasAlreadyAgreed = function(){
if(this.getCookieValue()){
return true;
}
return false;
};
this.hasNotAgreedYet = function(){
return !this.hasAlreadyAgreed();
};
this.reset = function(){
$cookies.remove(this.getCookieKey());
};
this.agree = function(){
this.setCookieValue(Date.now());
};
}
ConsentController.$inject = ['$cookies', '$attrs'];
})(angular);
|
import Prism from 'prismjs';
export default (el, {arg, value}) => {
console.log(arg);
let language = Prism.languages.javascript;
switch(arg){
case 'html':
language = Prism.languages.html;
break;
case 'css':
language = Prism.languages.css;
break;
case 'php':
language = Prism.languages.php;
break;
case 'python':
language = Prism.languages.python;
break;
case 'java':
language = Prism.languages.java;
break;
case 'scss':
language = Prism.languages.scss;
break;
case 'markup':
language = Prism.languages.markup;
break;
case 'typescript':
language = Prism.languages.typescript;
break;
}
console.log(value);
el.innerHTML = Prism.highlight(require('../examples/'+value), language)
} |
import React from 'react';
import {Route,Switch,Link, Router, NavLink}from "react-router-dom";
import image2 from './images/property-asknew_22.gif';
import image1 from './images/banner_image.gif';
import image3 from './images/logo.gif';
import {
Collapse,
Navbar,
NavbarToggler,
NavbarBrand,
Nav,
NavItem,
NavDropdown,
UncontrolledDropdown,
DropdownToggle,
DropdownMenu,
DropdownItem,
NavbarText,
Row,
Col
}from 'react-bootstrap';
import './App.css';
import Listing from './Listing';
import Jumbotron from 'react-bootstrap/Jumbotron'
import AboutUS from './AboutUS';
import ContactUS from './ContactUS';
import WHATNEW from './Whatnew';
import Cards from './cards'
import Latestproperties from './Latestproperties';
import whitelogo from './images/whitelogo.png';
import Advancesearch from './Advancesearch';
import pattern from './images/seriousaboutbuyingpattern.png';
import Houseimage from './images/House.jpg';
import flat from './images/02 (1).png'
import Contact from './contact';
import Footer from './Footer';
function App(){
return (
//<div className="container-fluid">
<div>
<div className="row">
<div className="col-sm-12">
<Navbar collapseOnSelect expand="lg" bg="#000000" variant="dark" className="nav1">
<Navbar.Brand href="#home" id="mumbai"><b><i class="fa fa-phone-square" aria-hidden="true"></i> MUMBAI: +91-8448455532</b></Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="mr-auto">
<Nav.Link href="#pricing" className="info"><b>BHOPAL: +91-8448455596 </b></Nav.Link>
<Nav.Link href="#pricing" className="info"><b><i class="fa fa-envelope-o" aria-hidden="true"></i> info@propertyask.com</b></Nav.Link>
</Nav>
</Navbar.Collapse>
</Navbar>
</div>
</div>
<div className="row">
<div className="col-sm-12">
<div className="jumbotron-fluid">
<div className="rd-navbar-inner">
<div className="rd-navbar-panel">
<div class="rd-navbar-nav-wrap ">
<Navbar collapseOnSelect expand="lg" bg="dark" variant="dark" id="navhome" className="nav2">
<Navbar.Brand href="#home"> {<img src={whitelogo} className="navlogo"></img>}</Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="mr-auto navbar-right">
<Link to="/"><b className="rightLink">Home /</b></Link>
<Link to="/Listing"><b className="rightLink">Listings /</b></Link>
<Link to="/AboutUS"><b className="rightLink">About Us /</b></Link>
<Link to="/Whatnew"><b className="rightLink"> What's New /</b></Link>
<Link to="/ContactUs"><b className="rightLink">Contact Us </b></Link>
</Nav>
</Navbar.Collapse>
</Navbar>
</div>
</div>
</div>
<Row>
<Col xs={6} lg={12}>
<h3 id="capsheading">LET'S FIND A<br/>
PROPERTY THAT'S <br/>
PERFECT FOR YOU
</h3>
</Col>
</Row>
<Row>
<Col xs={12}>
<h3 id="smallheading">BASED IN MUMBAI & BHOPAL</h3>
</Col>
</Row>
{/* <hr size="5"/> */}
{/* <img src={image2}className="img-fluid"/> */}
</div>
</div>
</div>
<Advancesearch />
<div className="container-fluid forbuying">
<Row>
<Col lg={2}></Col>
<Col lg={4} sm={12}>
<div className="heading">
<h3>SERIOUS ABOUT <br/>
BUYING ? </h3>
<br></br>
<br></br>
</div>
<div className="seriousaboutpara">
<h5>containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum</h5>
<br></br>
<h5>containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum</h5>
<br></br>
<h3>OUR SERVISES</h3>
<ul id="services" type="none">
<b><li>Buy Sell</li></b>
<b><li>Property Management</li></b>
<b><li>Commercial Property</li></b>
</ul>
</div>
<div className="learnmore">
<Link to="AboutUS"><b><h4 id="LearnMore">—— LEARN MORE</h4></b></Link>
</div>
</Col>
<Col lg={4} xs={12}>
<img src={Houseimage} className="Houseimage"></img>
</Col>
<Col lg={2}></Col>
</Row>
</div>
<br/><br/>
<Cards />
<Latestproperties />
<br></br>
<br></br>
<Contact />
<Footer/>
</div>
);
}
export default App;
|
require("pomeloClient")
var confige = require("confige");
cc.Class({
extends: cc.Component,
properties: {
},
// use this for initialization
onLoad: function () {
var loadNode = cc.find('loadNode').getComponent('loadNode'); //this.node.getChildByName("loadNode").getComponent("loadNode");
loadNode.onInit();
loadNode.hideNode();
// cc.loader.onProgress = function(completedCount, totalCount, item) {
// cc.log('step 1----------');
// var progress = (completedCount / totalCount).toFixed(2);
// cc.log(progress + '%' + completedCount + "///" + totalCount);
// var numString = "" + completedCount + "/" + totalCount;
// confige.loadNode.showNode();
// confige.loadNode.setProgress(progress,numString);
// };
// cc.loader.onComplete = function(errors, items){
// cc.log('loader.onComplete');
// confige.loadNode.hideNode();
// };
pomelo.clientScene = this;
confige.curSceneIndex = 0;
this.editBox = this.node.getChildByName("editBox");
this.editBox.active = false;
this.checkIco = this.node.getChildByName("check_mark");
this.checkShow = true;
this.btn_loginNode1 = this.node.getChildByName("btn_traveler");
this.btn_loginNode2 = this.node.getChildByName("btn_weixin");
this.btn_login1 = this.btn_loginNode1.getComponent("cc.Button");
this.btn_login2 = this.btn_loginNode2.getComponent("cc.Button");
this.loadingLayer = this.node.getChildByName("loadingLayer").getComponent("loadingLayer");
this.loadingLayer.onInit();
console.log("curUsePlatform === " + cc.sys.platform);
if(cc.sys.platform == cc.sys.DESKTOP_BROWSER)
{
confige.curUsePlatform = 0;
this.btn_loginNode2.active = false;
this.btn_loginNode1.x = 0;
console.log("cc.sys.platform == cc.sys.DESKTOP_BROWSER");
}else if(cc.sys.platform == cc.sys.ANDROID){
confige.shareTitle = "我爱牛牛,快来下载加入吧~";
confige.shareDes = "我爱牛牛,一起来玩!";
confige.curUsePlatform = 1;
this.btn_loginNode1.active = false;
this.btn_loginNode2.x = 0;
console.log("cc.sys.platform == cc.sys.ANDROID");
}else if(cc.sys.platform == cc.sys.IPHONE || cc.sys.platform == cc.sys.IPAD){
confige.shareTitle = "我爱牛牛,快来下载加入吧~";
confige.shareDes = "我爱牛牛,一起来玩!";
confige.curUsePlatform = 2;
console.log("cc.sys.platform == cc.sys.IPHONE");
this.btn_loginNode1.active = false;
this.btn_loginNode2.x = 0;
if(cc.sys.platform == cc.sys.IPAD)
cc.view.setDesignResolutionSize(1280,720,cc.ResolutionPolicy.EXACT_FIT);
}else if(cc.sys.platform == cc.sys.MOBILE_BROWSER){
confige.shareTitle = "我爱牛牛,点击可玩,无需下载";
confige.shareDes = "我爱牛牛H5,安全无挂,放心畅玩!";
cc.game.setFrameRate(24);
// confige.curUsePlatform = 0;
// this.btn_loginNode2.active = false;
// this.btn_loginNode1.x = 0;
confige.curUsePlatform = 3;
this.h5LoginError = this.node.getChildByName("h5LoginError");
console.log("cc.sys.platform == cc.sys.MOBILE_BROWSER");
// if(cc.sys.platform == cc.sys.MOBILE_BROWSER){
this.bgNode = this.node.getChildByName("loginBg");
this.bgNode.height = 790;
cc.view.setDesignResolutionSize(1280,790,cc.ResolutionPolicy.EXACT_FIT);
// }
this.btn_loginNode1.active = false;
this.btn_loginNode2.active = false;
// this.btn_loginNode1.x = 0;
confige.loginType = 2;
var RequestData = {};
RequestData = this.GetRequest();
console.log("打印url参数!!!!!");
console.log(RequestData);
if(RequestData.code)
{
// wx.config({
// debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
// appId: RequestData.appid, // 必填,企业号的唯一标识,此处填写企业号corpid
// timestamp: RequestData.timestamp, // 必填,生成签名的时间戳
// nonceStr: RequestData.noncestr, // 必填,生成签名的随机串
// signature: RequestData.signature,// 必填,签名,见附录1
// jsApiList: [ "onMenuShareTimeline",
// "onMenuShareAppMessage"] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
// });
if(RequestData.room_num)
confige.h5RoomID = RequestData.room_num;
confige.curUseCode = RequestData.code;
pomelo.clientLogin(-1,-1);
this.showLoading();
}
}
// if(cc.sys.platform != cc.sys.MOBILE_BROWSER)
// {
console.log("loadRes Native!!!!!!!!!!!!!!!!!!!")
// this.initAudio();
// this.initGameRes();
// }else{
// console.log("loadRes H5!!!!!!!!!!!!!!!!!!!")
// this.H5ResNode = this.node.getChildByName("H5ResNode");
// this.initAudioH5();
// this.initGameResH5();
// }
this.initLocalData();
cc.loader.loadRes("sound/game_bgm", function (err, audio) {
confige.audioList["bgm"] = audio;
if(confige.musicEnable == true)
if(confige.audioBgId == null)
confige.audioBgId = cc.audioEngine.play(audio,true,confige.audioVolume);
});
this.versionError = this.node.getChildByName("versionError");
this.versionNum = this.node.getChildByName("versionNum").getComponent("cc.Label");
this.versionNum.string = confige.versionCheck.split("&")[0];
cc.log("onLoad!!!!!!!!!!!!");
cc.sys.localStorage.setItem('currentVersion',confige.curVersion);
console.log("currentVersion === " + cc.sys.localStorage.getItem('currentVersion'));
// //大版本更新的包里面要带上下列处理,把热更新目录清除
// // 之前版本保存在 local Storage 中的版本号,如果没有认为是旧版本
// var previousVersion = cc.sys.localStorage.getItem('currentVersion');
// if(previousVersion == null)
// previousVersion = "1.1.0";
// console.log("previousVersion111 === " + previousVersion);
// // game.currentVersion 为该版本的常量
// if(confige.curUsePlatform == 1 && confige.curUsePlatform == 2)
// {
// if (previousVersion < confige.curVersion) {
// // 热更新的储存路径,如果旧版本中有多个,可能需要记录在列表中,全部清理
// var storagePath = ((jsb.fileUtils ? jsb.fileUtils.getWritablePath() : '/') + 'blackjack-remote-asset');
// jsb.fileUtils.removeDirectory(storagePath);
// cc.sys.localStorage.setItem('currentVersion',confige.curVersion);
// cc.sys.localStorage.setItem('HotUpdateSearchPaths', null);
// cc.audioEngine.stopAll();
// cc.game.restart();
// }
// }
// console.log("previousVersion222 === " + previousVersion);
this.updateLayer = this.node.getChildByName("updateLayer").getComponent("HotUpdate");
this.updateLayer.onInit();
if (cc.sys.isNative) {
this.updateLayer.checkUpdate();
}
},
start: function () {
// this.initAudio();
// this.initGameRes();
},
GetRequest:function(){
confige.h5SignURL = location.href;
console.log("完整路径11111====="+confige.h5SignURL);
var url = location.search; //获取url中"?"符后的字串
console.log(url);
var theRequest = new Object();
var strs = [];
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
}
}
return theRequest;
},
initLocalData:function(){
if(cc.sys.localStorage.getItem('check_invite') == null)
{
cc.sys.localStorage.setItem('check_invite',false);
}
if(cc.sys.localStorage.getItem('firstOpen') == null) //首次进入游戏
{
cc.sys.localStorage.setItem('firstOpen', false);
var userSetting = {
musicEnable : true,
soundEnable : true
};
cc.sys.localStorage.setItem('userSetting', JSON.stringify(userSetting));
confige.firstShowNotice = true;
// var curDate = new Date();
// var wxLoginData = {
// login : 0,
// openid : "",
// refresh_token : "",
// year : 0,
// dayCount : 0
// };
// cc.sys.localStorage.setItem('wxLoginData', JSON.stringify(wxLoginData));
}else{
// if(cc.sys.localStorage.getItem('wxLoginData') == null)
// {
// var curDate = new Date();
// var wxLoginData = {
// login : 0,
// openid : "",
// refresh_token : "",
// year : 0,
// dayCount : 0
// };
// cc.sys.localStorage.setItem('wxLoginData', JSON.stringify(wxLoginData));
// }
var userSetting = JSON.parse(cc.sys.localStorage.getItem('userSetting'));
console.log(userSetting);
if(userSetting.musicEnable == true)
confige.musicEnable = true;
else if(userSetting.musicEnable == false)
confige.musicEnable = false;
if(userSetting.soundEnable == true)
confige.soundEnable = true;
else if(userSetting.soundEnable == false)
confige.soundEnable = false;
if(cc.sys.localStorage.getItem('lastLoginDate') != null)
{
var lastLoginDate = JSON.parse(cc.sys.localStorage.getItem('lastLoginDate'));
var curDate = new Date();
console.log(lastLoginDate);
if( curDate.getFullYear() == lastLoginDate.year &&
curDate.getMonth()+1 == lastLoginDate.month &&
curDate.getDate() == lastLoginDate.day )
{
//console.log("在同一天登陆");
confige.firstShowNotice = false;
}else{
//console.log("不在同一天登陆");
confige.firstShowNotice = true;
}
}
}
},
initAudio:function(){
for(var i=0;i<8;i++)
{
cc.loader.loadRes("sound/0/chat" + (i+1),function(index){
return function (err, audio) {
var curIndex = "female_" + "chat_" + index;
confige.audioList[curIndex] = audio;
}
}(i));
cc.loader.loadRes("sound/1/chat" + (i+1),function(index){
return function (err, audio) {
var curIndex = "male_" + "chat_" + index;
confige.audioList[curIndex] = audio;
}
}(i));
}
for(var i=0;i<6;i++)
{
cc.loader.loadRes("sound/F_" + (i+1),function(index){
return function (err, audio) {
var curIndex = "female_" + "face_" + index;
confige.audioList[curIndex] = audio;
}
}(i+1));
cc.loader.loadRes("sound/M_" + (i+1),function(index){
return function (err, audio) {
var curIndex = "male_" + "face_" + index;
confige.audioList[curIndex] = audio;
}
}(i+1));
}
for(var i=0;i<7;i++)
{
cc.loader.loadRes("sound/" + (i+1),function(index){
return function (err, audio) {
var curIndex = "face_" + index;
confige.audioList[curIndex] = audio;
}
}(i+1));
}
for(var i=0;i<=18;i++)
{
cc.loader.loadRes("sound/0/type" + i,function(index){
return function (err, audio) {
var curIndex = "female_" + "type_" + index;
confige.audioList[curIndex] = audio;
}
}(i));
cc.loader.loadRes("sound/1/type" + i,function(index){
return function (err, audio) {
var curIndex = "male_" + "type_" + index;
confige.audioList[curIndex] = audio;
}
}(i));
}
cc.loader.loadRes("sound/fapai", function (err, audio) {
confige.audioList["fapai"] = audio;
});
},
initGameRes:function(){
cc.loader.loadRes("frame/card/card_00", cc.SpriteFrame, function (err, spriteFrame) {
confige.cardFrameMap[0] = spriteFrame;
});
for(var j=0;j<4;j++)
{
for(var i=1;i<=13;i++)
{
var t = i;
if(i == 10)
t = 'a';
else if(i == 11)
t = 'b';
else if(i == 12)
t = 'c';
else if(i == 13)
t = 'd';
var index = i + j*13;
cc.loader.loadRes("frame/card/card_" + j + t, cc.SpriteFrame,function(index){
return function (err, spriteFrame) {
confige.cardFrameMap[index] = spriteFrame;
}
}(index));
}
}
for(var i=0;i<=18;i++)
{
cc.loader.loadRes("frame/niutype/niu_" + i, cc.SpriteFrame,function(index){
return function (err, spriteFrame) {
confige.niuTypeFrameMap[index] = spriteFrame;
if(index <= 10){
confige.niuTypeFrameMapFK[index] = spriteFrame;
}else{
switch(index){
case 12:
confige.niuTypeFrameMapFK[15] = spriteFrame;
break;
case 13:
confige.niuTypeFrameMapFK[16] = spriteFrame;
break;
case 14:
confige.niuTypeFrameMapFK[14] = spriteFrame;
break;
case 15:
confige.niuTypeFrameMapFK[11] = spriteFrame;
break;
case 16:
confige.niuTypeFrameMapFK[12] = spriteFrame;
break;
case 17:
confige.niuTypeFrameMapFK[13] = spriteFrame;
break;
case 18:
confige.niuTypeFrameMapFK[17] = spriteFrame;
break;
}
}
}
}(i));
}
for(var i=1;i<=12;i++)
{
cc.loader.loadRes("frame/face/" + i, cc.SpriteFrame, function(index){
return function (err, spriteFrame) {
confige.faceFrameMap[index-1] = spriteFrame;
}
}(i));
}
},
initGameResH5:function(){
this.frameNode = this.H5ResNode.getChildByName("frame");
this.cardNode = this.frameNode.getChildByName("card");
this.faceNode = this.frameNode.getChildByName("face");
this.niutypeNode = this.frameNode.getChildByName("niutype");
confige.cardFrameMap[0] = this.cardNode.getChildByName("card_00").getComponent("cc.Sprite").spriteFrame;
for(var j=0;j<4;j++)
{
for(var i=1;i<=13;i++)
{
var t = i;
if(i == 10)
t = 'a';
else if(i == 11)
t = 'b';
else if(i == 12)
t = 'c';
else if(i == 13)
t = 'd';
var index = i + j*13;
confige.cardFrameMap[index] = this.cardNode.getChildByName("card_"+j+t).getComponent("cc.Sprite").spriteFrame;
}
}
for(var i=0;i<=18;i++)
{
var spriteFrame = this.niutypeNode.getChildByName("niu_"+i).getComponent("cc.Sprite").spriteFrame;
confige.niuTypeFrameMap[index] = spriteFrame;
if(index <= 10){
confige.niuTypeFrameMapFK[index] = spriteFrame;
}else{
switch(index){
case 12:
confige.niuTypeFrameMapFK[15] = spriteFrame;
break;
case 13:
confige.niuTypeFrameMapFK[16] = spriteFrame;
break;
case 14:
confige.niuTypeFrameMapFK[14] = spriteFrame;
break;
case 15:
confige.niuTypeFrameMapFK[11] = spriteFrame;
break;
case 16:
confige.niuTypeFrameMapFK[12] = spriteFrame;
break;
case 17:
confige.niuTypeFrameMapFK[13] = spriteFrame;
break;
case 18:
confige.niuTypeFrameMapFK[17] = spriteFrame;
break;
}
}
}
for(var i=1;i<=12;i++)
{
var spriteFrame = this.faceNode.getChildByName(""+i).getComponent("cc.Sprite").spriteFrame;
confige.faceFrameMap[index-1] = spriteFrame;
}
},
onBtnTravelerClicked:function(){
console.log("fuck click travler");
this.editBox.active = true;
// html2canvas(document.body, {
// allowTaint: true,
// taintTest: false,
// onrendered: function(canvas) {
// canvas.id = "GameCanvas";
// //document.body.appendChild(canvas);
// //生成base64图片数据
// var dataUrl = canvas.toDataURL();
// var newImg = document.createElement("img");
// newImg.src = dataUrl;
// // console.log("dataUrl === "+ dataUrl);
// // curDiv.appendChild(newImg);
// document.body.appendChild(newImg);
// // var newDiv= document.createElement('div');
// // // if(window.innerWidth)
// // // {
// // // console.log("window.innerWidth==="+gameViewDiv.style.width);
// // // newDiv.style.width= gameViewDiv.style.width*0.8 + "px";
// // // }
// // // if(window.innerWidth)
// // // {
// // // console.log("window.innerWidth==="+window.innerWidth);
// // // newDiv.style.width= window.innerWidth*0.8 + "px";
// // // }
// // newDiv.style.height="550px";
// // // ar L1 = oBox.offsetWidth;
// // // var H1 = oBox.offsetHeight;
// // // var Left = (document.documentElement.clientWidth-L1)/2;
// // // var top = (document.documentElement.clientHeight-H1)/2;
// // newDiv.style.left = "200px";
// // newDiv.style.top = "150px";
// // newDiv.style.position = "absolute";
// // document.body.appendChild(newDiv);
// // newDiv.id = "newDiv";
// // newImg.width = "1000";
// // newImg.height = "550";
// // newDiv.appendChild(newImg); //为dom添加子元素img
// }
// });
// if (!cc.sys.isNative) return;
// let dirpath = jsb.fileUtils.getWritablePath() + 'ScreenShoot/';
// if (!jsb.fileUtils.isDirectoryExist(dirpath)) {
// jsb.fileUtils.createDirectory(dirpath);
// }
// let name = 'ScreenShoot-' + (new Date()).valueOf() + '.png';
// let size = cc.winSize;
// let rt = cc.RenderTexture.create(size.width, size.height);
// cc.director.getScene()._sgNode.addChild(rt);
// rt.setVisible(false);
// console.log("fuck click travler1111111");
// rt.begin();
// cc.director.getScene()._sgNode.visit();
// rt.end();
// console.log("fuck click travler2222222");
// rt.saveToFile('ScreenShoot/' + name, cc.ImageFormat.PNG, true, function() {
// console.log("fuck click travler333333333333333");
// rt.removeFromParent();
// });
// console.log("fuck click travler44444444444");
},
onBtnUserKnowClicked:function(){
if(this.checkShow == true)
{
this.checkIco.active = false;
this.btn_login1.interactable = false;
this.btn_login2.interactable = false;
this.editBox.active = false;
this.checkShow = false;
}else{
this.checkIco.active = true;
this.btn_login1.interactable = true;
this.btn_login2.interactable = true;
this.checkShow = true;
}
},
onBtnTestClicked:function(){
console.log("test click test");
},
showLoading:function(){
if(confige.curUsePlatform == 0)
this.btn_loginNode1.active = false;
else
this.btn_loginNode2.active = false;
this.loadingLayer.showLoading();
},
loadingFalse:function(){
this.btn_loginNode2.active = true;
this.loadingLayer.hideLoading();
},
btn_login_click:function(){
confige.loginType = 0;
var editString = this.editBox.getChildByName("IDEdit").getComponent("cc.EditBox").string;
var id = parseInt(editString);
// pomelo.clientConnect(function(){
pomelo.clientLogin(id);
// });
this.showLoading();
},
connectCallBack:function(){
pomelo.request("connector.entryHandler.getNotify",null, function(data) {
confige.noticeData = data;
var newNoticeData = JSON.stringify(data);
var lastNoticeData = cc.sys.localStorage.getItem('lastNoticeData');
console.log(newNoticeData);
console.log(lastNoticeData);
if(newNoticeData == lastNoticeData)
{
console.log("没有新的公告");
}else{
console.log("有新的公告");
confige.firstShowNotice = true;
}
cc.sys.localStorage.setItem('lastNoticeData', JSON.stringify(data));
});
},
onBtnWeixinClicked:function(){
if(confige.curUsePlatform == 1 || confige.curUsePlatform == 2)
{
this.showLoading();
confige.loginType = 1;
var lastLoginCount = 99;
if(cc.sys.localStorage.getItem("wxLastLoginDay") != null)
{
lastLoginCount = confige.getDayCount() - cc.sys.localStorage.getItem("wxLastLoginDay");
}
if(cc.sys.localStorage.getItem('wxRefreshToken') == null || lastLoginCount >= 20 || lastLoginCount < 0)
{
if(confige.curUsePlatform == 1)
{
jsb.reflection.callStaticMethod("org/cocos2dx/javascript/JSCallJAVA", "WXLogin", "()V");
}else if(confige.curUsePlatform == 2){
jsb.reflection.callStaticMethod("JSCallOC", "WXLogin");
}
}else{
confige.WX_REFRESH_TOKEN = cc.sys.localStorage.getItem('wxRefreshToken');
var curRefreshToken = confige.WX_REFRESH_TOKEN;
this.wxRefreshLogin();
}
}
},
wxLoginJavaCall:function(code){
var self = this;
var xmlHttp = this.createXMLHttpRequest();
var httpCallback = function(){
var loginJson = JSON.parse(xmlHttp.responseText);
confige.WX_LOGIN_RETURN = loginJson;
confige.WX_ACCESS_TOKEN = loginJson.access_token;
confige.WX_OPEN_ID = loginJson.openid;
confige.WX_UNIONID = loginJson.unionid;
confige.WX_REFRESH_TOKEN = loginJson.refresh_token;
pomelo.clientLogin(confige.WX_OPEN_ID, confige.WX_ACCESS_TOKEN);
cc.sys.localStorage.setItem("wxRefreshToken",loginJson.refresh_token);
cc.sys.localStorage.setItem("wxLastLoginDay",confige.getDayCount());
};
this.scheduleOnce(function() {
confige.WX_CODE = code;
var url = confige.access_token_url;
url = url.replace("APPID", confige.APP_ID);
url = url.replace("SECRET", confige.SECRET);
url = url.replace("CODE", confige.WX_CODE);
xmlHttp.onreadystatechange = httpCallback;
xmlHttp.open("GET", url, true);// 异步处理返回
xmlHttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded;");
xmlHttp.send();
}, 0.25);
},
wxRefreshLogin:function(){
// jsb.reflection.callStaticMethod("org/cocos2dx/javascript/JSCallJAVA", "JAVALog", "(Ljava/lang/String;)V", "微信刷新登陆111");
var self = this;
var xmlHttp = this.createXMLHttpRequest();
var httpCallback = function(){
var loginJson = JSON.parse(xmlHttp.responseText);
confige.WX_LOGIN_RETURN = loginJson;
confige.WX_ACCESS_TOKEN = loginJson.access_token;
confige.WX_OPEN_ID = loginJson.openid;
confige.WX_REFRESH_TOKEN = loginJson.refresh_token;
// jsb.reflection.callStaticMethod("org/cocos2dx/javascript/JSCallJAVA", "JAVALog", "(Ljava/lang/String;)V", "WX_REFRESH_TOKEN");
// jsb.reflection.callStaticMethod("org/cocos2dx/javascript/JSCallJAVA", "JAVALog", "(Ljava/lang/String;)V", loginJson.refresh_token);
// jsb.reflection.callStaticMethod("org/cocos2dx/javascript/JSCallJAVA", "JAVALog", "(Ljava/lang/String;)V", "WX_OPEN_ID");
// jsb.reflection.callStaticMethod("org/cocos2dx/javascript/JSCallJAVA", "JAVALog", "(Ljava/lang/String;)V", loginJson.openid);
// jsb.reflection.callStaticMethod("org/cocos2dx/javascript/JSCallJAVA", "JAVALog", "(Ljava/lang/String;)V", "WX_ACCESS_TOKEN");
// jsb.reflection.callStaticMethod("org/cocos2dx/javascript/JSCallJAVA", "JAVALog", "(Ljava/lang/String;)V", loginJson.access_token);
pomelo.clientLogin(confige.WX_OPEN_ID, confige.WX_ACCESS_TOKEN);
cc.sys.localStorage.setItem("wxRefreshToken",loginJson.refresh_token);
};
this.scheduleOnce(function() {
var url = confige.refresh_token_url;
url = url.replace("APPID", confige.APP_ID);
url = url.replace("REFRESH_TOKEN", confige.WX_REFRESH_TOKEN);
// jsb.reflection.callStaticMethod("org/cocos2dx/javascript/JSCallJAVA", "JAVALog", "(Ljava/lang/String;)V", "refresh_token_url");
// jsb.reflection.callStaticMethod("org/cocos2dx/javascript/JSCallJAVA", "JAVALog", "(Ljava/lang/String;)V", url);
xmlHttp.onreadystatechange = httpCallback;
xmlHttp.open("GET", url, true);// 异步处理返回
xmlHttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded;");
xmlHttp.send();
}, 0.25);
},
createXMLHttpRequest:function() {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
if (xmlHttp.overrideMimeType)
xmlHttp.overrideMimeType('text/xml');
} else if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
return xmlHttp;
},
WXCancle:function(){
// this.btn_loginNode1.active = true;
this.btn_loginNode2.active = true;
this.loadingLayer.hideLoading();
},
btnClickExit:function(){
// cc.director.end();
if(confige.curUsePlatform == 3){
window.open(confige.h5LoginUrl);
window.close();
}
else
cc.sys.openURL(confige.shareURL);
},
showH5LoginError:function(){
this.loadingLayer.active = false;
this.h5LoginError.active = true;
},
showVersionError:function(){
this.versionError.active = true;
this.updateLayer.checkUpdate();
},
iosCallTest:function(string){
cc.log("iosCallTest");
if(typeof(string) == "string")
{
this.showVersionError();
}
this.btn_loginNode1.active = false;
this.btn_loginNode1.active = false;
},
btnShootClick:function(){
html2canvas(document.body, {
allowTaint: true,
taintTest: false,
onrendered: function(canvas) {
canvas.id = "Cocos2dGameContainer";//"GameCanvas";
//document.body.appendChild(canvas);
//生成base64图片数据
var dataUrl = canvas.toDataURL();
var newImg = document.createElement("img");
newImg.src = dataUrl;
console.log(dataUrl);
// var curGameDiv = document.getElementById("GameDiv");
// curGameDiv.appendChild(newImg);
// document.body.appendChild(newImg);
var newDiv = document.createElement('div');
// if(window.innerWidth)
// {
// console.log("window.innerWidth==="+gameViewDiv.style.width);
// newDiv.style.width= gameViewDiv.style.width*0.8 + "px";
// }
// if(window.innerWidth)
// {
// console.log("window.innerWidth==="+window.innerWidth);
// newDiv.style.width= window.innerWidth*0.8 + "px";
// }
// ar L1 = oBox.offsetWidth;
// var H1 = oBox.offsetHeight;
console.log(document.documentElement.clientWidth);
console.log(document.documentElement.clientHeight);
var Left = (document.documentElement.clientWidth-300)/2;
var top = (document.documentElement.clientHeight-600)/2;
newDiv.style.left = Left+"px";
newDiv.style.top = top+"px";
console.log(Left+"px");
console.log(top+"px");
newDiv.style.position = "absolute";
document.body.appendChild(newDiv);
newDiv.id = "newDiv";
newImg.width = "300";
newImg.height = "600";
newDiv.appendChild(newImg); //为dom添加子元素img
}
});
},
});
|
const routes = require('express').Router();
const password = require('password-hash-and-salt');
const log = require('../lib/log')('REST');
let db = null;
// REST Endpoints
routes.post('/login', (req, res) => {
const email = req.body.username.toLowerCase();
const remember = req.body.rememberMe;
log.info(`Incoming: User: ${email}\t`);
db.getUser(email).then((result) => {
console.log(`retrieve user ${result}`)
password(req.body.password).verifyAgainst(result.password, (err, verified) => {
if(err) {
log.info('Login failed due to an error');
res.status(401);
res.send({ error: err});
} else {
if(!verified) {
log.info('Login failed due to wrong credentials');
res.status(401);
res.send({ error: 'Wrong credentials' });
} else {
log.info('User authenticated');
req.session.rememberMe = remember;
req.session.email = email;
req.session.name = result.name;
res.status(200);
res.send({ message: 'authenticated',
user: { email: result.email, name: result.name } });
}
}
});
}, (err) => {
log.error(`Error: ${err}`);
res.status(401);
res.send({ error: 'An error occured while checking credentials.' });
});
});
routes.get('/session', (req, res) => {
// Check if user has a session, which is the case if remember is set to True
if (req.session.rememberMe === true) {
db.getUser(req.session.email).then((result) => {
// Send obtained user to client
log.info(`User ${result.email} identified by Session`);
res.status(200);
res.send({
message: 'authenticated',
hasSession: true,
user: { email: result.email, name: result.name }
});
}, (err) => {
log.error('User identification failed');
log.error(err);
res.status(200);
res.send({ message: `User ${req.session.email} not found`, hasSession: false, user: null });
});
} else {
log.info('No session found');
res.status(200);
res.send({ message: 'No session found', hasSession: false, user: null });
}
});
routes.post('/logout', (req, res) => {
// Check if user has a session
if (req.session) {
req.session.destroy((err) => {
if (err) {
log.error(`Error while deleting session: \n${err}`);
res.status(200).send({ message: 'An Error occured while deleting the session' });
} else {
log.info('Deleted Session');
res.clearCookie('connect.sid').status(200).send({ message: 'Deleted Session' });
}
});
} else {
log.info('No Session was found');
res.status(200).send({ message: 'No Session found' });
}
});
module.exports = function routing(database) {
db = database;
return routes;
};
|
import {
useEffect,
useRef,
useState
} from 'preact/hooks';
import classnames from 'classnames';
/**
*
* @param {object} props
* @param {string} [props.class]
* @param {import('preact').Component[]} [props.menuItems]
* @returns
*/
export function DropdownButton(props) {
const {
class: className,
children,
menuItems = []
} = props;
const dropdownRef = useRef(null);
const menuRef = useRef(null);
const [ open, setOpen ] = useState(false);
const close = () => setOpen(false);
function onDropdownToggle(event) {
if (menuRef.current && menuRef.current.contains(event.target)) {
return;
}
event.stopPropagation();
setOpen(open => !open);
}
function onActionClick(event, action) {
event.stopPropagation();
close();
action();
}
useGlobalClick([ dropdownRef.current ], () => close());
return (
<div
class={ classnames('bio-properties-panel-dropdown-button', { open }, className) }
onClick={ onDropdownToggle }
ref={ dropdownRef }
>
{ children }
<div class="bio-properties-panel-dropdown-button__menu" ref={ menuRef }>
{ menuItems.map((item, index) => (
<MenuItem onClick={ onActionClick } item={ item } key={ index } />
)) }
</div>
</div>
);
}
function MenuItem({ item, onClick }) {
if (item.separator) {
return <div class="bio-properties-panel-dropdown-button__menu-item bio-properties-panel-dropdown-button__menu-item--separator" />;
}
if (item.action) {
return (<button
class="bio-properties-panel-dropdown-button__menu-item bio-properties-panel-dropdown-button__menu-item--actionable"
onClick={ event => onClick(event, item.action) }
>
{item.entry}
</button>);
}
return <div
class="bio-properties-panel-dropdown-button__menu-item"
>
{item.entry}
</div>;
}
/**
*
* @param {Array<null | Element>} ignoredElements
* @param {Function} callback
*/
function useGlobalClick(ignoredElements, callback) {
useEffect(() => {
/**
* @param {MouseEvent} event
*/
function listener(event) {
if (ignoredElements.some(element => element && element.contains(event.target))) {
return;
}
callback();
}
document.addEventListener('click', listener, { capture: true });
return () => document.removeEventListener('click', listener, { capture: true });
}, [ ...ignoredElements, callback ]);
}
|
app.controller('about',['$scope',function($scope){
console.log("hello");
}]); |
'use strict';
/**
* Class for calculation of the line numbers.
*/
class Location {
/**
* Create class instance.
*
* @param {string} buf - Raw text.
* @example
* ```js
* let data = fs.readFileSync(file, 'utf8');
* let loc = new Location(data);
* ```
*/
constructor(buf) {
this._indexes = [];
let index = -1;
while ((index = buf.indexOf('\n', index + 1)) !== -1) {
this._indexes.push(index);
}
}
/**
* Get line number.
*
* @param {number} index - the 0-based index.
* @return {number} Returns 0-based line number for given index.
*/
getLine(index) {
if (!Number.isInteger(index)) {
throw new TypeError('First argument must be a number.');
}
for (let i = 0; i < this._indexes.length; i++) {
if (index <= this._indexes[i]) return i;
}
return this._indexes.length;
}
}
module.exports = Location;
|
//Yoav Ben-Yehoshua, Amit Goldberg
// The timeout for the server - no response:
exports.LAST_REQUEST_TIMEOUT_SEC=2; //
// Max requested allowed per ip:
exports.MAX_REQ_ALLOWED_PER_IP = 200;
// Max requested allowed overall (So the server won't collapse):
exports.MAX_REQ_ALLOWED_OVERALL = 15000;
// in minutes!
exports.SESSION_TIMEOUT_MIN = 30; |
(function($) {
"use strict";
var fullHeight = function() {
$('.js-fullheight').css('height', $(window).height());
$(window).resize(function(){
$('.js-fullheight').css('height', $(window).height());
});
};
fullHeight();
$('#sidebarCollapse').on('click', function () {
$('#sidebar').toggleClass('active');
});
})(jQuery);
/*
$(function (){
$("#notice").click(function (){
$("#message_content").hide();
$("#chatroom_content").hide();
$("#notice_content").show(); });
});
$(function (){
$("#message").click(function (){
$("#notice_content").hide();
$("#chatroom_content").hide();
$("#message_content").show(); });
});
$(function (){
$("#chatroom").click(function (){
$("#notice_content").hide();
$("#message_content").hide();
$("#chatroom_content").show(); });
});
*/
|
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
context.subscriptions.push(vscode.commands.registerCommand('imageOptimizer.losslessOptimization', losslessOptimization));
context.subscriptions.push(vscode.commands.registerCommand('imageOptimizer.lossyOptimization', lossyOptimization));
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() {
}
exports.deactivate = deactivate;
function losslessOptimization() {
console.log('Entered losslessOptimization function.');
}
function lossyOptimization() {
console.log('Entered lossyOptimization function');
} |
var lib_email =
[
[ "Handling of email attachments", "email_attach.html", null ],
[ "Representation of the body of an email", "email_body.html", null ],
[ "Representation of an email", "email_email.html", null ],
[ "Representation of an email header (envelope)", "email_envelope.html", null ],
[ "Determine who the email is from", "email_from.html", null ],
[ "Email Global Variables", "email_globals.html", null ],
[ "Constants and macros for managing MIME encoding", "email_mime.html", null ],
[ "Store attributes associated with a MIME part", "email_parameter.html", null ],
[ "Miscellaneous email parsing routines", "email_parse.html", null ],
[ "RFC2047 encoding / decoding functions", "email_rfc2047.html", null ],
[ "RFC2231 MIME Charset routines", "email_rfc2231.html", null ],
[ "Driver based email tags", "email_tags.html", null ],
[ "Create/manipulate threading in emails", "email_thread.html", null ],
[ "Parse and identify different URL schemes", "email_url.html", null ]
]; |
import Styles from './Stylepop';
import { Card, CardActions, CardContent, CardMedia, Button, Typography } from '@material-ui/core';
import MoreHorizIcon from '@material-ui/icons/MoreHoriz';
import ThumbUpAltIcon from '@material-ui/icons/ThumbUpAlt';
import DeleteIcon from '@material-ui/icons/Delete';
import moment from 'moment';
import axios from 'axios';
const Post = ({post, setCurrentId}) => {
const deletePost = async (post) => {
await axios.delete(`http://localhost:5000/posts/${post._id}`,{_id: post._id})
}
const likePost = async (post) => {
await axios.patch(`http://localhost:5000/posts/${post._id}/likePost`)
}
// useEffect(() => {
// if(post)
// setCurrentId(post);
// }, [post])
const editPost = (id) =>{
setCurrentId(id);
console.log(id)
};
const styles = Styles();
return (
<Card className={styles.card} >
<CardMedia className={styles.media} image={post.selectedFile} title={post.title} />
<div className={styles.overlay} >
<Typography variant="h6" > {post.creater} </Typography >
<Typography variant="body2">{moment(post.createdAt).fromNow()}</Typography>
</div>
<div className={styles.overlay2} >
<Button style={{color: 'white'}} size="small" onClick={() => {editPost(post._id)}} ><MoreHorizIcon fontsize="deafult" /></Button>
</div>
<div className={styles.details} >
<Typography variant="body2" color="textSecondary" >{post.tags.map((tag) => `#${tag} `)} </Typography>
</div>
<Typography className={styles.title} variant="h5" gutterBottom >{post.title}</Typography>
<CardContent>
<Typography variant="h5" gutterBottom >{post.message}</Typography>
</CardContent>
<CardActions className={styles.cardActions} >
<Button size="small" color="primary" onClick={() => {likePost(post)}} > <ThumbUpAltIcon fontSize="small" /> Like {post.likeCount}</Button>
<Button size="small" color="primary" onClick={() => {deletePost(post)}} > <DeleteIcon fontSize="small" /> Delete</Button>
</CardActions>
</Card>
);
};
export default Post
|
let table = 3; //資料表的單位
let operator = 'addition'; //計算方式(預設為加法)
let i = 1; //設定計數器為1
let msg = ''; //文字訊息
if(operator === 'addition'){//如果變數operator為加法
while(i<11){ //當計數器小於11時
msg += i + ' + ' + table + ' = ' +(i + table) + '<br />';//進行計算
i++; //計數器增加1
}
}else{ //反之
while(i<11){ //當計數器小於11時
msg += i + ' x ' + table + ' = ' +(i * table) + '<br />';//進行計算
i++; //計數器增加1
}
}
//撰寫訊息於頁面中
let el = document.getElementById('blackboard')
el.innerHTML = msg; |
(function(){
var fs, stitch, coffeescript, hamlc;
fs = require("fs");
stitch = require("stitch");
coffeescript = require("coffee-script");
hamlc = require("haml-coffee/src/haml-coffee");
stitch.compilers.hamlc = function(module, filename){
var compiler, content, template;
compiler = new hamlc({});
content = fs.readFileSync(filename, "utf8");
compiler.parse(content)
template = compiler.precompile();
template = coffeescript.compile(template);
module._compile("module.exports = (function(data){ return (function(){ return "+template+"; }).call(data); })", filename);
};
})();
|
// Evolutility-UI-React :: format.js
// Helpers for string manipulation and date formats
// https://github.com/evoluteur/evolutility-ui-react
// (c) 2017 Olivier Giulieri
import React from 'react'
import {filesUrl, filesType} from '../../config.js'
import Image from '../widgets/Image';
function notUndefined(v) {
return (typeof(v) != "undefined")
}
module.exports = {
fieldValue(f, d, abbr) {
if (f.type === 'boolean') {
return d ? <i className="glyphicon glyphicon-ok"></i> : '';
}
else if (f.type === 'lov') {
return d;
}
else if (f.type === 'date') {
return this.dateString(d);
}
else if (f.type === 'datetime') {
return this.dateTimeString(d);
}
else if (f.type === 'color') {
return (
<div>
<div className="evo-color-box" id={f.id} style={{backgroundColor: d}} title={d}>
{!abbr && d ? <span>{d}</span>:null}
</div>
</div>
)
}
else if (f.type === 'image' && d) {
return this.image(filesUrl + d);
}
else if (f.type === 'url' && d) {
return <a href={d} target="_blank">{d}</a>;
}
else if (f.type === 'email' && d) {
return <a href={'mailto:'+d}>{d}</a>;
}
return d;
},
image(d) {
if (d === null) {
return null
}
return <Image type={filesType} url={d} className="img-thumbnail" />;
},
// --- date formats ---
dateString: function(d){
if (d) {
d = d.substring(0, 10);
}
if (notUndefined(d) && d !== null) {
var dateParts = d.split('-');
if (dateParts.length > 1) {
return dateParts[2] + '/' + dateParts[1] + '/' + dateParts[0];
}
}
return '';
},
timeString: function(d){
if (notUndefined(d) && d !== null && d !== ''){
var timeParts = d.split(':'), hour = parseInt(timeParts[0],10);
if (hour > 12) {
return (hour-12) + ':' + timeParts[1] + ' PM';
}
else {
return hour + ':' + timeParts[1] + ' AM';
}
}
return '';
},
dateTimeString: function(d) {
if (notUndefined(d) && d !== null && d !== '') {
var dateParts = d.split('T');
if (dateParts.length > 1) {
return this.dateString(dateParts[0]) + ', ' + this.timeString(dateParts[1]);
}
else {
return this.dateString(dateParts[0]);
}
}
return '';
}
};
|
module.exports = function(grunt) {
'use strict';
var express = require('express');
var errorhandler = require('errorhandler');
var compression = require('compression');
grunt.registerTask('server', 'static file development server', function() {
var app, webPort, webRoot;
webPort = grunt.config.get('server.web.port') || 8000;
webRoot = grunt.config.get('server.base') || 'generated';
app = express();
app.use(compression());
app.use(express.static('' + (process.cwd()) + '/' + webRoot));
app.use(errorhandler());
app.listen(webPort);
grunt.log.writeln('Starting express web server in \'' + webRoot + '\' on port ' + webPort);
return app;
});
};
|
`line
break`+`he llo`;foo`hel( '');lo`;`he\nl\`lo`;(`he${one + two}`)`hello`
doSomething() |
var express = require('express');
var router = express.Router();
var path = require('path')
var knex = require('../db/knex.js')
var stormpath = require('express-stormpath');
/* GET home page. */
router.get('/', function(req, res, next) {
res.redirect('https://getmesafe.herokuapp.com/index.html')
});
router.get('/addecontact.html', stormpath.loginRequired, function(req, res, next) {
res.sendFile('../public/addecontact.html')
});
router.get('/econtact.html', stormpath.loginRequired, function(req, res, next) {
res.sendFile('../public/econtact.html')
});
router.get('/isloggedin', stormpath.getUser, (req, res) =>{
if(req.user){
// res.send(res.locals.user.email)
res.send(req.user)
}else {
res.send(false)
}
})
router.get('/friendsInDanger', stormpath.loginRequired, (req, res)=>{
knex.select('incident.id').from('incident').join('eContact', 'eContact.user_id', 'incident.user_id').join('user', 'user.id', 'incident.user_id').where('eContact.email', res.locals.user.email).whereNull('incident.end_LAT')
.then(function(data){
if (data.length < 1){
res.send(200)
return
}
res.send(data)
})
})
module.exports = router;
|
var assert = require('chai').assert;
var rules = require('../src/rules_functions.js');
describe('In rule should error', () => {
it('for 1 in 1', () => {
assert.throw(
() => {rules.in(1, {in: 1})},
Error,
'argument supplied to "in" rule must be either an array or an object'
);
});
it('for "b" in "abc123"', () => {
assert.throw(
() => {rules.in("b", {in: "abc123"})},
Error,
'argument supplied to "in" rule must be either an array or an object'
);
});
it('for 1 in true', () => {
assert.throw(
() => {rules.in(1, {in: true})},
Error,
'argument supplied to "in" rule must be either an array or an object'
);
});
});
describe('In rule should pass', () => {
it('for 1 in false', () => {
var result = rules.in(1, {in: false});
assert.equal(result, true);
});
it('for 4 in [1,3,4,6,9]', () => {
var result = rules.in(4, {in: [1,3,4,6,9]});
assert.equal(result, true);
});
it('for undefined in [undefined]', () => {
var result = rules.in(undefined, {in: [undefined]});
assert.equal(result, true);
});
it('for "breed" in {breed: "Shih Tzu"}', () => {
var result = rules.in("breed", {in: {breed: "Shih Tzu"}});
assert.equal(result, true);
});
it('for "species" in a prototype chain', () => {
function ShihTzu(name) {
this.name = name;
}
ShihTzu.prototype = {species: 'dog'};
var my_pet = new ShihTzu('Chewy');
var result = rules.in("species", {in: my_pet});
assert.equal(result, true);
});
});
describe('In rule should fail', () => {
it('for 1 in [2,3,4,5]', () => {
var result = rules.in(1, {in: [2,3,4,5]});
assert.equal(result, false);
});
it('for undefined in []', () => {
var result = rules.in(undefined, {in: []});
assert.equal(result, false);
});
it('for "color" in {breed: "Shih Tzu"}', () => {
var result = rules.in("color", {in: {breed: "Shih Tzu"}});
assert.equal(result, false);
});
}); |
export function lessThan(el1, el2, comparatorFn) {
return comparatorFn ? comparatorFn(el1, el2) < 0 : (el1 - el2 < 0);
}
export function greaterThan(el1, el2, comparatorFn) {
return comparatorFn ? comparatorFn(el1, el2) > 0 : (el1 - el2 > 0);
} |
import axios from 'axios'
import React from 'react'
import EachPost from './EachPost'
// Geeting all Posts from API
function PostData({id}) {
const [data,setData]=React.useState([])
const [desc,setDesc]=React.useState("")
function getData(){
axios("http://localhost:3031/postData")
.then(res=>setData(res.data))
.catch(err=>console.log(err))
}
console.log(data)
// posting the Data
const postSubmit=(e)=>{
e.preventDefault()
axios.post("http://localhost:3031/postData",{
userId:id,
desc,
comments:[]
})
getData()
}
React.useEffect(()=>{
getData()
},[])
return (
<div style={{textAlign:"center"}}>
<form onSubmit={postSubmit}>
<textarea value={desc} placeholder={"hi post here"} onChange={e=>setDesc(e.target.value)}></textarea><br/>
<input type="submit" value="Post"/>
</form>
{data && data.map(e=><EachPost post={e} id={id} />)}
</div>
)
}
export default PostData
|
({
markCompletionMessageCheckbox: function (component, event, helper) {
// get course assignmentId and programmeAssignmentIds from pop up data received.
let achievementData = component.get("v.popupModalData");
let courseAssignmentId = achievementData.courseAssignment.Id;
let programmeAssignmentIds = new Array();
if(achievementData.programmeAssignments){
for (var i = 0; i < achievementData.programmeAssignments.length; i++) {
programmeAssignmentIds.push(achievementData.programmeAssignments[i].Id);
}
}
// call server to update completion message showed checkbox if at least course assignment id is present.
if (courseAssignmentId != null && courseAssignmentId != '' && courseAssignmentId != undefined) {
helper.callServer(
component,
"c.updateCompletionMessageForCourseAndProgramme",
function (response) {
// do nothing.
}, {
courseAssignmentId: courseAssignmentId,
programmeAssignmentIds: programmeAssignmentIds
},
false
);
}
}
}) |
import Component from '@glimmer/component';
import debugLogger from 'ember-debug-logger';
import { action } from '@ember/object';
export default class TwyrDialogContainerComponent extends Component {
// #region Private Attributes
debug = debugLogger('twyr-dialog-container');
_element = null;
// #endregion
// #region Constructor
constructor() {
super(...arguments);
this.debug(`constructor`);
}
// #endregion
// #region Lifecycle Hooks
@action
didInsert(element) {
this.debug(`didInsert`);
this._element = element;
}
// #endregion
// #region DOM Event Handlers
@action
handleMouseDown(event) {
this.debug(`handleMouseDown`);
this._sourceElem = event.target;
}
@action
handleMouseUp(event) {
this.debug(`handleMouseUp`);
if(this._sourceElem !== this._element)
return;
if(event.target !== this._element)
return;
event.preventDefault();
event.stopPropagation();
if(!this.args.outsideClicked)
return;
if(typeof this.args.outsideClicked !== 'function')
return;
this.args.outsideClicked(event);
}
// #region
}
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as i18n from 'lighthouse/core/lib/i18n/i18n.js';
import {NetworkRecords} from 'lighthouse/core/computed/network-records.js';
import {auditNotApplicable} from '../messages/common-strings.js';
import {Audit} from 'lighthouse';
import {isGpt, isGptImplTag} from '../utils/resource-classification.js';
const UIStrings = {
title: 'GPT Errors',
failureTitle: 'Fix GPT errors',
description: 'Fix GPT errors to ensure your page is tagged as intended. ' +
'[Learn more](' +
'https://developers.google.com/publisher-ads-audits/reference/audits/gpt-errors-overall' +
').',
displayValue: '{numErrors, plural, =1 {1 error} other {# errors}} found',
};
const str_ = i18n.createIcuMessageFn(import.meta.url, UIStrings);
/**
* Audit that checks for the presence of errors and exceptions from the console
* as well as other audits.
*/
class GptErrorsOverall extends Audit {
/**
* @return {LH.Audit.Meta}
*/
static get meta() {
return {
id: 'gpt-errors-overall',
title: str_(UIStrings.title),
failureTitle: str_(UIStrings.failureTitle),
description: str_(UIStrings.description),
scoreDisplayMode: 'informative',
requiredArtifacts: ['ConsoleMessages', 'devtoolsLogs'],
};
}
/**
* @param {LH.Artifacts} artifacts
* @param {LH.Audit.Context} context
* @return {Promise<LH.Audit.Product>}
*/
static async audit(artifacts, context) {
const devtoolsLog = artifacts.devtoolsLogs[Audit.DEFAULT_PASS];
const network = await NetworkRecords.request(devtoolsLog, context);
const pubadsImpl = network.find((r) => isGptImplTag(r.url));
if (!pubadsImpl) {
return auditNotApplicable.NoGpt;
}
/** @type {Array<{
* source: string,
* description: string|undefined,
* url: string|undefined}>} */
const tableRows = artifacts.ConsoleMessages
.filter((item) =>
item.level === 'error' || item.level === 'warning')
.filter((item) => item.url && isGpt(item.url))
.filter((item) =>
!item.text.toLowerCase().includes('deprecated') &&
!item.text.toLowerCase().includes('discouraged'))
.map((item) => ({
source: item.source,
description: item.text,
url: item.url,
timestamp: item.timestamp,
}))
.sort((a, b) => (a.timestamp || 0) - (b.timestamp || 0));
/** @type {LH.Audit.Details.Table['headings']} */
const headings = [
{key: 'url', itemType: 'url', text: str_(i18n.UIStrings.columnURL)},
{key: 'description', itemType: 'code', text: str_(i18n.UIStrings.columnDescription)},
];
const details = Audit.makeTableDetails(headings, tableRows);
const numErrors = tableRows.length;
return {
score: Number(numErrors === 0),
details,
displayValue: str_(UIStrings.displayValue, {numErrors}),
};
}
}
export default GptErrorsOverall;
export {UIStrings};
|
// function createContainer(){
// var container=document.createElement("div");
// container.id="slideshow";
// var img=document.createElement("img");
// img.src="topics.gif";
// img.alt="网页设计";
// img.id="preview";
// container.appendChild(img);
// yc.insertAfter(container,"alltabs");
// }
function moveImg(){
if(!yc.isCompatible()) return false;
var aAs=yc.$("alltabs").getElementsByTagName("a");
var img=yc.$("preview");
for(var i=0;i<aAs.length;i++){
aAs[i].index=i;
aAs[i].onmouseover=function(){
var className="toRight"+this.index;
yc.removeClassName(img,"def");
yc.addClassName(img,className);
}
aAs[i].onmouseout=function(){
var className="toRight"+this.index;
yc.addClassName(img,"def");
yc.removeClassName(img,className);
}
}
}
//yc.addLoadEvent(createContainer);
yc.addLoadEvent(moveImg); |
const Common = {
isLogin: () => {
if (window.localStorage.getItem('userInfo') == null) {
return false
}
return true
},
hasDeviceId: false,
index2PageCount: (index, count) => Math.ceil(index / (count || 10)) // return lastIndex转总页数
}
// 使用:Common.isLogin
module.exports = Common
// 使用Common.Common.isLogin
/* export default {
// Common: Common缩写
Common
} */
|
import axios from 'axios'
//请求头加userid和customcode
const Axios=axios.create({
timeout: 10000 // 请求超时时间
});
// request拦截器
Axios.interceptors.request.use(config => {
if(sessionStorage.getItem("user")){
config.headers['userId'] = JSON.parse(sessionStorage.getItem("user")).userID
config.headers['customsCode'] =JSON.parse(sessionStorage.getItem("user")).customsCode
}
return config
}, error => {
// Do something with request error
console.log(error) // for debug
Promise.reject(error)
})
// respone拦截器
// Axios.interceptors.response.use(
// response => {
// const res = response.data;
// return res;
// },
// error => {
// return Promise.reject(error)
// }
// )
// let base = 'http://39.100.236.246:9998'
// 登录
export const requestLogin = params => {
return Axios.post(`${base}/api/OfficerManager/Login`, params).then(res => res.data)
}
// 官员列表
export const getOfficerList = params => {
return Axios.get(`${base}/api/OfficerManager/OfficerList`, {
params: params
}).then(res => res.data)
}
// 添加关员
export const officer_add = params => {
return Axios.post(`${base}/api/OfficerManager/AddOfficer`, params).then(res => res.data)
}
// 编辑关员
export const officer_edit = params => {
return Axios.post(`${base}/api/OfficerManager/EditOfficer`, params).then(res => res.data)
}
// 关员删除
export const officer_delete = params => {
return Axios.post(`${base}/api/OfficerManager/DeleteOfficer`, params).then(res => res.data)
}
// 关区列表,按照登记,返回包含自身及以下的关区
export const getCustomsList = params => {
return Axios.get(`${base}/api/OfficerManager/CustomsList`, {
params: params
}).then(res => res.data)
}
// 关区列表,返回所有的
export const getCustomsList_all = params => {
return Axios.get(`${base}/api/OfficerManager/CustomsListAll`, {
params: params
}).then(res => res.data)
}
// 关区添加
export const customs_add = params => {
return Axios.post(`${base}/api/OfficerManager/AddCustoms`, params).then(res => res.data)
}
// 关区编辑
export const customs_eidt = params => {
return Axios.post(`${base}/api/OfficerManager/EditCustoms`, params).then(res => res.data)
}
// 关区删除
export const customs_delete = params => {
return Axios.post(`${base}/api/OfficerManager/DeleteCustoms`, params).then(res => res.data)
}
// 表单字典列表
export const getFormDicList = params => {
return Axios.get(`${base}/api/FormManager/FormDictList`, {
params: params
}).then(res => res.data)
}
// 表单字典详情
export const getFormDicDetail = params => {
return Axios.get(`${base}/api/FormManager/FormDictDetail`, {
params: params
}).then(res => res.data)
}
// 表单字典添加
export const formDic_add = params => {
return Axios.post(`${base}/api/FormManager/FormDictAdd`, params).then(res => res.data)
}
// 表单字典编辑
export const formDic_edit = params => {
return Axios.post(`${base}/api/FormManager/FormDictEdit`, params).then(res => res.data)
}
// 表单字典删除
export const formDic_delete = params => {
return Axios.post(`${base}/api/FormManager/FormDictDelete`, params).then(res => res.data)
}
// 解析字典项
export const parseHtmlTemplateText = params => {
return Axios.post(`${base}/api/FormManager/ParseHtmlTemplateText`, params).then(res => res.data)
}
// 获取表格列表
export const getFormList = params => {
return Axios.post(`${base}/api/FormManager/FormList`, params).then(res => res.data)
}
// 获取表单详情
export const getFormDetail = params => {
return Axios.get(`${base}/api/FormManager/FormDetail`, {
params: params
}).then(res => res.data)
}
// 提交表单
export const submitFormData = params => {
return Axios.post(`${base}/api/FormManager/SubmitForm`, params).then(res => res.data)
}
// 导出表格
export const exportWord = params => {
return Axios.post(`${base}/api/FormManager/FormExportWord`, params).then(res => res.data)
}
// 删除表格数据
export const deleteFormData = params => {
return Axios.post(`${base}/api/FormManager/FormDelete`, params).then(res => res.data)
}
// 修改表格数据
export const editFormData = params => {
return Axios.post(`${base}/api/FormManager/FormEdit`, params).then(res => res.data)
}
// 批量提交数据
export const BatchCommit = params => {
return Axios.post(`${base}/api/FormManager/BatchCommit`, params).then(res => res.data)
}
// 批量转交
export const PrintDeliverForm = params => {
return Axios.post(`${base}/api/FormManager/PrintDeliverForm`, params).then(res => res.data)
}
// 采样表列表
export const getTaskList = params => {
return Axios.post(`${base}/api/FormManager/TaskList`, params).then(res => res.data)
}
// 采样表详情
export const getTaskDetail = params => {
return Axios.get(`${base}/api/FormManager/TaskDetail`, {
params: params
})
}
// 提交采样表
export const submitTask = params => {
return Axios.post(`${base}/api/FormManager/TaskSubmitForm`, params).then(res => res.data)
}
// 字典项的获取
// 获取国家字典
export const getCountryDict = params => {
return Axios.get(`${base}/api/DictManager/CountryDict`, {
params: params
}).then(res => res.data)
}
// 获取语言字典
export const getLanguageDict = params => {
return Axios.get(`${base}/api/DictManager/LanguageDict`, {
params: params
}).then(res => res.data)
}
// 导出类型字典
export const getExportTypeDict = params => {
return Axios.get(`${base}/api/DictManager/ExportTypeDict`, {
params: params
}).then(res => res.data)
}
// HTMLitem类型
export const getHTMLItemTypeDict = params => {
return Axios.get(`${base}/api/DictManager/HTMLItemTypeDict`, {
params: params
}).then(res => res.data)
}
// 翻译
export const TranslateHtmlTemplateText = params => {
return Axios.post(`${base}/api/FormManager/TranslateHtmlTemplateText`, params).then(res => res.data)
}
// 获取旅客信息通过健康码
export const GetPassengerInfoByJianKangMa = params => {
return Axios.get(`${base}/api/output/GetPassengerInfoByJianKangMa`, {
params: params
}).then(res => res.data)
}
// 获取相关联表单信息
export const getRelatedFormDetailListByTaskCode = params => {
return Axios.get(`${base}/api/FormManager/FormDetailListByTaskCode`, {
params: params
}).then(res => res.data)
}
// 根据语言查询系统内的表单列表
export const GetQueryFormType = params => {
return Axios.get(`${base}/api/FormManager/QueryFormType`, {
params: params
}).then(res => res.data)
}
// 查询系统支持的语言信息
export const GetQueryLanguage = params => {
return Axios.get(`${base}/api/FormManager/QueryLanguage`, {
params: params
}).then(res => res.data)
}
// 查询当前登录用户所属关区以及下属关区关员列表
export const GetQueryOfficerList = params => {
return Axios.get(`${base}/api/FormManager/QueryOfficerList`, {
params: params
}).then(res => res.data)
}
// 获取表格列表
export const getFormList_youke = params => {
return Axios.get(`${base}/api/FormManager/FormDictListForSubmit`, {
params: params
}).then(res => res.data)
}
// 获取表单详情
export const getFormDetail_youke = params => {
return Axios.get(`${base}/api/FormManager/FormDetail`, {
params: params
}).then(res => res.data)
}
// 提交表单
export const submitFormData_youke = params => {
return Axios.post(`${base}/api/FormManager/SubmitForm`, params).then(res => res.data)
}
// 获取旅客信息通过健康码
// export const GetPassengerInfoByJianKangMa = params => { return Axios.get(`${base}/api/output/GetPassengerInfoByJianKangMa`, { params: params }).then(res => res.data) }
// 护照号获取信息
export const GetPassengerInfoByHuZhaoHao = params => {
return Axios.get(`${base}/api/output/GetPassengerInfoByHuZhaoHao`, {
params: params
}).then(res => res.data)
}
// 获取航班信息
export const GetFlightPersonTypeInfo = params => {
return Axios.get(`${base}/api/output/GetFlightPersonTypeInfo`, {
params: params
}).then(res => res.data)
}
// 通过健康码和表单类型获取生成的任务对象
export const QueryTask = params => {
return Axios.get(`${base}/api/FormManager/QueryTask`, {
params: params
}).then(res => res.data)
}
// 角色列表
// 获取所有的角色列表
export const GetRoleList = params => {
return Axios.get(`${base}/api/RoleManager/GetRoleList`, {
params: params
}).then(res => res.data)
}
// 获取指定角色的角色详情,包含菜单列表
export const GetRoleDetail = params => {
return Axios.get(`${base}/api/RoleManager/GetRoleDetail`, {
params: params
}).then(res => res.data)
}
// 更新角色,包含角色的菜单信息
export const UpdateRoleInfo = params => {
return Axios.post(`${base}/api/RoleManager/UpdateRoleInfo`, params).then(res => res.data)
}
// 请求删除角色
export const DeleteRole = params => {
return Axios.post(`${base}/api/RoleManager/DeleteRole`, params).then(res => res.data)
}
// 获取菜单
export const GetMenuList = params => {
return Axios.get(`${base}/api/RoleManager/GetMenuList`, {
params: params
}).then(res => res.data)
}
// 新增角色,包含角色的菜单信息
export const InsertRoleInfo = params => {
return Axios.post(`${base}/api/RoleManager/InsertRoleInfo`, params).then(res => res.data)
}
// 首页
// 获取统计列表
export const GetSummary = params => {
return Axios.get(`${base}/api/Home/GetSummary`, {
params: params
}).then(res => res.data)
}
// 表单数量
export const GetStatistics = params => {
return Axios.get(`${base}/api/Home/GetStatistics`, {
params: params
}).then(res => res.data)
}
// 填写时长
export const GetDurationStatistic = params => {
return Axios.get(`${base}/api/Home/GetDurationStatistic`, {
params: params
}).then(res => res.data)
}
// 获取异常表单列表
export const GetList = params => {
return Axios.post(`${base}/api/FormException/GetList`, params).then(res => res.data)
}
// 异常表单批量删除
export const BatchDelete = params => {
return Axios.post(`${base}/api/FormException/BatchDelete`, params).then(res => res.data)
}
// 通关记录
// 通关记录详情
export const QueryPassengerEntryDetail = params => {
return Axios.post(`${base}/api/Passenger/QueryPassengerEntryDetail`, params).then(res => res.data)
}
// 获取通关记录列表
export const QueryPassengerEntryList = params => {
return Axios.post(`${base}/api/Passenger/QueryPassengerEntryList`, params).then(res => res.data)
}
// 删除通关记录
export const DeleteEntry = params => {
return Axios.post(`${base}/api/Passenger/DeleteEntry`, params).then(res => res.data)
}
//获取送检处理表单列表
export const QueryUnSendFormList = params => {
return Axios.post(`${base}/api/FormManager/QueryUnSendFormList`, params).then(res => res.data)
}
//送检
export const SendFormToCheck = params => {
return Axios.post(`${base}/api/FormManager/SendFormToCheck`, params).then(res => res.data)
}
//送检统计
export const QuerySendStatisticsResult = params => {
return Axios.post(`${base}/api/FormManager/QuerySendStatisticsResult`, params).then(res => res.data)
}
//操作
export const QueryOperationLog = params => {
return Axios.post(`${base}/api/Operation/QueryOperationLog`, params).then(res => res.data)
}
//修改密码
export const ChangePwd = params => {
return Axios.post(`${base}/api/OfficerManager/ChangePwd`, params).then(res => res.data)
}
//获取申明卡信息
export const QueryPasserHealthyInfo = params => {
return Axios.post(`${base}/api/Passenger/QueryPasserHealthyInfo`, params).then(res => res.data)
} |
import { ActionBase } from 'ap-flux'
import { Utils } from 'ap-react-bootstrap'
var logout = new ActionBase({ name: 'LOGOUT' })
var navigate = new ActionBase({ name: 'NAVIGATE' })
var navigate_back = new ActionBase({ name: 'NAVIGATE_BACK' })
var set_app_display = new ActionBase({ name: 'SET_APP_DISPLAY' })
var put = new ActionBase({ name: 'PUT' })
logout.do = function() {
return new Promise(function (resolve, reject) {
resolve();
});
}
navigate.do = function(args) {
Utils.checkMembers(args, ['path']);
return new Promise(function (resolve, reject) {
resolve(args.path);
});
}
navigate_back.do = function(args) {
return new Promise(function (resolve, reject) {
resolve();
});
}
set_app_display.do = function(args) {
Utils.checkMembers(args, ['path', 'value']);
return new Promise(function (resolve, reject) {
resolve({ path: args.path, value: args.value });
});
}
put.do = function(args) {
Utils.checkMembers(args, ['path', 'value']);
return new Promise(function (resolve, reject) {
resolve({ path: args.path, value: args.value });
});
}
|
$(document).ready(function(){
////////////////////////// CLICK ICON AND NAV SCROLLS /////////////////////////
function animateHeaderIcons(){
var links = $(".nav_link");
var navSpan = $("nav").find("span");
var h3nav = $("nav").find("h3");
var navHeight = $("nav").height()
console.log(navHeight);
links.on("click", function(event){
event.preventDefault();
var allTheSections = $('.indexAnimation');
var href = $(this).attr('href');
var indexSection = $(href).index('.indexAnimation') + 1 ;
$('html, body').stop().animate({
'scrollTop': $(href).offset().top - (1.5 * navHeight)
}, indexSection * 800, function(){
console.log("dziala");
});
})
}
////////////////////////////// SCROLLER ///////////////////////////////////////
function animateNav(){
var scroller = $(".scroller");
var navBar = $("nav");
var navSpan = $("nav").find("span");
var links = $(".nav_link");
var h3nav = $("nav").find("h3");
var slidingMenu = $(".sliding_menu");
scroller.on("click", function(event){
event.preventDefault();
$("body, html").stop().animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 1000, function() {
navBar.addClass("navFixed");
slidingMenu.css("position", "fixed");
links.css("color", "white");
navSpan.css("color", "white");
h3nav.css("color", "pink");
});
})
}
/////////////////////////// HAMBURGER ////////////////////////////////////////
function hideAndShowHamburger(){
var hamburgerBox = $('#hamburger_box');
var navMenu = $(".menu");
var slidingMenu = $(".sliding_menu");
$(window).on('resize', function(event){
var mq = window.matchMedia("(max-width:600px)");
if(mq.matches){
hamburgerBox.css('display', 'block');
navMenu.css('display', 'none');
}else{
hamburgerBox.css('display', 'none');
navMenu.css('display', 'block');
}
})
$('.hamburger').on('click', function(event){
slidingMenu.slideDown( "slow", function() {
$( ".hamburger" ).hide();
$( ".cross" ).show();
});
})
$('.cross').on('click', function(event){
slidingMenu.slideUp( "slow", function() {
$( ".cross" ).hide();
$( ".hamburger" ).show();
})
})
}
/////////////////// MAKE NAV STICKY WHEN IN ANY SECTION //////////////////////
function makeNavSticky(){
var stickyNav = $('nav').offset().top;
var links = $(".nav_link");
var navSpan = $("nav").find("span");
var h3nav = $("nav").find("h3");
$(window).scroll(function(){
if( $(window).scrollTop() > stickyNav ) {
$('nav').css({position: 'fixed', top: 0});
$('nav').addClass("navFixed");
links.css("color", "white");
navSpan.css("color", "white");
h3nav.css("color", "pink");
} else {
$('nav').css({position: 'static', top: '0px'});
}
});
}
/////////////////////////// SLIDER2 ////////////////////////////////////////////
function slider1(){
$('#slider1').bxSlider({
slideWidth: 375,
minSlides: 1,
maxSlides: 3,
moveSlides: 1
});
}
/////////////////////////// SLIDER2 ////////////////////////////////////////////
function slider2(){
$('#slider2').bxSlider({
// slideWidth: 800,
minSlides: 1,
maxSlides: 1,
moveSlides: 1,
slideMargin: 10,
slideMargin: 10,
pause: 3000,
speed: 500,
auto: true,
});
}
/////////////////////////// FANCYBOX ////////////////////////////////////////
function fancyBox(){
$("a.single_image").fancybox();
$("a#inline").fancybox({
'hideOnContentClick': true
});
$("a.group").fancybox({
'transitionIn': 'fade',
'transitionOut': 'fade',
'speedIn': 600,
'speedOut': 200,
'overlayShow': false,
});
}
/////////////////////////// MIXITUP ////////////////////////////////////////
function mixItUp(){
$('#container').mixItUp();
}
/////////////////////////// VALIDATION ////////////////////////////////////////
function formValidation(){
$('#name').on('blur', function() {
var input = $(this);
var name_length = input.val().length;
if(name_length >= 5){
input.removeClass("invalid").addClass("valid");
}else{
input.removeClass("valid").addClass("invalid");
$(this).attr("placeholder", "Incorrect name");
}
});
$('#email').on('blur', function() {
var input = $(this);
var pattern = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var is_email = pattern.test(input.val());
if(is_email){
input.removeClass("invalid").addClass("valid");
}else{
input.removeClass("valid").addClass("invalid");
$(this).attr("placeholder", "Incorrect e-mail");
}
});
$('#message').on('blur', function() {
var input = $(this);
var message = $(this).val();
if(message){
input.removeClass("invalid").addClass("valid");
}else{
$(this).attr("placeholder", "Please type your message here");
input.removeClass("valid").addClass("invalid");
}
});
$('#submitBtn').click(function(event){
var name = $('#name');
var email = $('#email');
var message = $('#message');
if(name.hasClass('valid') && email.hasClass('valid') && message.hasClass('valid')){
event.preventDefault();
sweetAlert({
title: "Yay!",
text: "Your email has been sent.",
type: "success"
});
}else{
event.preventDefault();
sweetAlert({
title: "Oops!",
text: "Something went wrong. Please try again.",
type: "error"
});
}
});
}
///////////////////////////////////////////////////////////////////////////////
animateHeaderIcons();
animateNav();
hideAndShowHamburger();
makeNavSticky();
slider1();
slider2();
fancyBox();
mixItUp();
formValidation();
});
|
import React from 'react';
import './App.css';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './Home';
import Projects from './Projects';
import Resume from './Resume';
function App() {
return (
<Router>
<div className="App">
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
crossOrigin="anonymous"
/>
<Switch>
<Route exact path="/resume" component={Resume} />
<Route exact path="/projects" component={Projects} />
<Route path="/" component={Home} />
</Switch>
</div>
</Router>
);
}
export default App;
|
import React, {Component} from 'react'
import {
StyleSheet,
View,
Text,
TouchableOpacity,
TextInput,
KeyboardAvoidingView,
ScrollView
} from 'react-native'
import Header from '../../components/Header'
import {
Container,
Content,
ListItem,
Radio,
Right,
Left,
DatePicker,
Picker,Footer,FooterTab
} from 'native-base';
export default class UserDemographics extends Component {
constructor(props){
super(props)
this.state={
showPreviewDiv:false
}
}
render() {
return (
<KeyboardAvoidingView
style={{
flex: 1
}}
behavior="padding"
enabled>
<ScrollView>
<View
style={{
backgroundColor: 'white',
flex: 1,
alignContent: 'flex-end',
justifyContent: 'center',
padding: 10,
marginTop: 10
}}>
<Text style={styles.mytitle}>
Do you belong to any Sacco?
</Text>
<ListItem>
<Left>
<TouchableOpacity
style={{
width: '100%',
padding: 3
}}
onPress={() => this.props.changeSaccoYes()}>
<Text>Yes</Text>
</TouchableOpacity>
</Left>
<Right>
<Radio
color={"#f0ad4e"}
selectedColor={"#5cb85c"}
onPress={() => this.props.changeSaccoYes()}
selected={this.props.SaccoYesSelect}/>
</Right>
</ListItem>
<ListItem>
<Left>
<TouchableOpacity
style={{
width: '100%',
padding: 3
}}
onPress={() => this.props.changeSaccoNo()}>
<Text>No</Text>
</TouchableOpacity>
</Left>
<Right>
<Radio
color={"#f0ad4e"}
selectedColor={"#5cb85c"}
onPress={() => this.props.changeSaccoNo()}
selected={this.props.SaccoNoSelect}/>
</Right>
</ListItem>
{this.props.DailyContribFormShow
? <View
style={{
marginTop: 10
}}>
<Text style={styles.mytitle}>
Please enter the sacco name
</Text>
<TextInput
defaultValue={this.props.SaccoName}
onChangeText={(SaccoName) => this.props.getSaccoDetails(SaccoName, this.props.DailyContribution)}
keyboardType="default"
style={styles.myInput}
placeholder="Harambe"></TextInput>
<Text style={styles.mytitle}>
Please enter your contribution
</Text>
<TextInput
defaultValue={this.props.DailyContribution}
onChangeText={(DailyContribution) => this.props.getSaccoDetails(this.props.SaccoName, DailyContribution)}
keyboardType="number-pad"
style={styles.myInput}
placeholder="1000"></TextInput>
</View>
: null
}
</View>
<View
style={{
flex: 1,
flexDirection: 'row',
padding: 10,
marginTop: 20
}}>
</View>
<View>
<TouchableOpacity
onPress={this.props.showAllData}
style={{
width: '100%',
alignItems: 'center',
padding: 20,
flex: 1
}}>
<Text
style={{
color: '#000',
textDecorationLine:'underline'
}}>Preview Information</Text>
</TouchableOpacity>
</View>
</ScrollView>
<Footer style={{padding:10,height:75,backgroundColor:'#f2f2f2'}}>
<FooterTab style={{backgroundColor:'#f2f2f2'}}>
<TouchableOpacity
onPress={() => this.props.backToForm3()}
style={{
alignItems: 'center',
padding: 20,
flex: 1
}}>
<Text
style={{
color: 'orange'
}}>Previous</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={this.props.submitForm}
style={{
width: '100%',
alignItems: 'center',
backgroundColor: 'orange',
flex: 1,
padding:20,
borderRadius:40,
marginBottom:10
}}>
<Text
style={{
color: 'white',letterSpacing:3,textTransform:'uppercase'
}}>Finish</Text>
</TouchableOpacity>
</FooterTab>
</Footer>
</KeyboardAvoidingView>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
myInput: {
padding: 15,
borderColor: '#ccc',
borderWidth: 1,
borderRadius: 4,
marginBottom: 20
},
mytitle: {
padding: 2,
fontWeight: 'bold',
marginBottom: 20
}
});
|
import React from 'react';
import styled from 'styled-components';
const FooterElm = styled.footer`
position: absolute;
bottom: 2rem;
color: black;
`;
const LinkElm = styled.a`
color: #ff3482;
text-decoration: none;
font-weight: bold;
`;
/**
* Site footer
*/
const Footer = () => (
<FooterElm className='site-footer'>
<p>Made with <span>♥</span> by <LinkElm href='https://github.com/TomKiWorld' target='_blank' rel='noopener noreferrer'>TomKiWorld</LinkElm></p>
</FooterElm>
);
export default Footer;
|
/**
* Created by adronhall on 6/23/14.
* Description: API Integration test for apikeys. Currently does not implement passport security.
*/
var test_globals = require('../test-globals');
var username = test_globals.username, password = test_globals.password, routes = test_globals.routes;
var ApiKeys = require('../../models/apikeys');
var data_ring = require('../../data/ring');
var apikeys = new ApiKeys(data_ring);
var base_uri = '/apikeys';
describe('API Calls for apikeys', function () {
it('should return 200 for listing by user', function (done) {
test_globals.routes.post(base_uri)
.auth(username, password)
.expect(200, done)
});
it('should return at least one key for a user no matter what', function (done) {
test_globals.routes.post(base_uri)
.auth(username, password)
.expect(200, done)
});
it('should return permissions with the returned key', function (done) {
test_globals.routes.post(base_uri)
.auth(username, password)
.expect(200, done)
});
it('should return 200 after adding a key', function (done) {
test_globals.routes.post(base_uri + '/add')
.auth(username, password)
.expect(200, done)
});
// it('should create an apikey', function (done){
// apikeys.add(test_globals.username, test_globals.password)
// .then(function(){
// apikeys.getKeys(test_globals.username, test_globals.password)
// .then(function(result){
// var r = result;
// r.should.exist;
// done()
// })
// })
// })
// it('should add the apikey and return the UUID/GUID of the newly created key', function () {
// apikeys.add(test_globals.username, test_globals.password, role)
// .then(function (result) {
// var thing = result;
//
// thing.should.exist;
// })
// })
it('should return a 200 success after deleting a key', function (done) {
test_globals.routes.post(base_uri + '/delete')
.auth(username, password)
.expect(200, done)
});
}); |
import PropTypes from 'prop-types'
import { css } from '@emotion/core'
import styled from '@emotion/styled'
import { chromatic, margined, padded } from '../../../traits'
const Area = styled.div(
chromatic.styles,
margined.styles,
padded.styles,
({ area }) =>
css`
grid-area: ${area && area};
`
)
Area.propTypes = {
...chromatic.propTypes(),
...margined.propTypes(),
...padded.propTypes(),
area: PropTypes.string,
}
Area.defaultProps = {
...chromatic.defaultProps(),
...margined.defaultProps(),
...padded.defaultProps(),
area: '',
}
export default Area
|
import { Shape3D, Sphere } from 'tubugl-3d-shape/build/tubu-3d-shape.js';
import { ArrayBuffer, IndexArrayBuffer, Program } from 'tubugl-core';
const vertexShaderSrc = require('./shaders/fire.vert.glsl');
const fragmentShaderSrc = require('./shaders/fire.frag.glsl');
import {
TRIANGLES,
UNSIGNED_SHORT,
CULL_FACE,
DEPTH_TEST,
BLEND,
SRC_ALPHA,
ONE_MINUS_SRC_ALPHA,
BACK,
FRONT
} from 'tubugl-constants';
import { vec3 } from 'gl-matrix';
export class Cylinder extends Shape3D {
constructor(
gl,
params,
_radiusTop,
_radiusBottom,
_height,
_radialSegments = 3,
_heightSegments = 2
) {
super(gl, params);
// this._radiusTop = radiusTop;
// this._radiusBottom = radiusBottom;
// this._height = height;
// this._radialSegments = radialSegments;
// this._heightSegments = heightSegments;
let radius = 50,
widthSegments = 30,
heightSegments = 20,
phiStart = 0,
phiLength = 2 * Math.PI,
thetaStart = 0,
thetaLength = Math.PI;
this._radius = radius;
this._widthSegments = widthSegments;
this._heightSegments = heightSegments;
this._phiStart = phiStart;
this._phiLength = phiLength;
this._thetaStart = thetaStart;
this._thetaLength = thetaLength;
this.scale.y = 2;
this.position.y = radius * 2;
if (this._radialSegments < 3) {
console.warn('make sure radialsegment more than 3');
return;
}
this._makeProgram(params);
this._makeBuffers(params);
}
getVertice() {
return this._positionBuffer.dataArray;
}
getNormals() {
return this._normalBuffer.dataArray;
}
render(camera, frameBuffer) {
this.update(camera, frameBuffer).draw();
// if (this._isWire) this.updateWire(camera).drawWireframe();
}
update(camera, frameBuffer) {
super.update(camera);
// console.log(frameBuffer);
this._program.setUniformTexture(frameBuffer.texture, 'noiseTexture');
frameBuffer.texture.activeTexture().bind();
if (!this._time) this._time = 0;
this._time += 1 / 60;
// console.log(this._time);
// console.log(this._program.uniform);
// this._gl.uniform1f(this._program.getUniforms('uTime').location, this._time);
return this;
}
addGui(gui) {
let positionFolder = gui.addFolder('position');
positionFolder.add(this.position, 'x', -200, 200);
positionFolder.add(this.position, 'y', -200, 200);
positionFolder.add(this.position, 'z', -200, 200);
let scaleFolder = gui.addFolder('scale');
scaleFolder.add(this.scale, 'x', 0.05, 2).step(0.01);
scaleFolder.add(this.scale, 'y', 0.05, 2).step(0.01);
scaleFolder.add(this.scale, 'z', 0.05, 2).step(0.01);
let rotationFolder = gui.addFolder('rotation');
rotationFolder.add(this.rotation, 'x', -Math.PI, Math.PI).step(0.01);
rotationFolder.add(this.rotation, 'y', -Math.PI, Math.PI).step(0.01);
rotationFolder.add(this.rotation, 'z', -Math.PI, Math.PI).step(0.01);
}
// ========================
// private
// ========================
_updateDrawStatus(side) {
if (side === 'double') {
this._gl.disable(CULL_FACE);
} else if (side === 'front') {
this._gl.enable(CULL_FACE);
this._gl.cullFace(BACK);
} else {
this._gl.enable(CULL_FACE);
this._gl.cullFace(FRONT);
}
this._gl.enable(DEPTH_TEST);
// else this._gl.disable(DEPTH_TEST);
// if (this._isTransparent) {
this._gl.enable(BLEND);
this._gl.blendFunc(SRC_ALPHA, ONE_MINUS_SRC_ALPHA);
// } else {
// this._gl.blendFunc(ONE, ZERO);
// this._gl.disable(BLEND);
// }
}
_makeProgram() {
this._program = new Program(this._gl, vertexShaderSrc, fragmentShaderSrc);
}
_makeBuffers() {
// let vertices = [];
// let indices = [];
// let normals = [];
// let uvs = [];
let index = 0;
let { vertice, uvs, normals, indices } = Sphere.getData(
this._radius,
this._widthSegments,
this._heightSegments,
this._phiStart,
this._phiLength,
this._thetaStart,
this._thetaLength
);
// index = this._generateTorso(vertices, indices, normals, uvs, index);
this._positionBuffer = new ArrayBuffer(this._gl, new Float32Array(vertice));
this._positionBuffer.setAttribs('position', 3);
this._normalBuffer = new ArrayBuffer(this._gl, new Float32Array(normals));
this._normalBuffer.setAttribs('normal', 3);
this._uvBuffer = new ArrayBuffer(this._gl, new Float32Array(uvs));
this._uvBuffer.setAttribs('uv', 2);
this._indexBuffer = new IndexArrayBuffer(this._gl, new Uint16Array(indices));
this._cnt = indices.length;
}
_generateTorso(vertices, indices, normals, uvs, index) {
let slope = (this._radiusBottom - this._radiusBottom) / this._height;
let indexArray = [];
let normal = vec3.create();
for (let yy = 0; yy <= this._heightSegments; yy++) {
let indexRow = [];
let vv = yy / this._heightSegments;
let radius = vv * (this._radiusBottom - this._radiusTop) + this._radiusTop;
for (let xx = 0; xx <= this._radialSegments; xx++) {
let uu = xx / this._radialSegments;
let theta = 2 * Math.PI * uu;
let sinTheta = Math.sin(theta);
let cosTheta = Math.cos(theta);
vertices.push(radius * sinTheta, (-vv + 0.5) * this._height, radius * cosTheta);
vec3.normalize(normal, [sinTheta, slope, cosTheta]);
normals.push(normal[0], normal[1], normal[2]);
uu = 2 * uu;
if (uu > 1.0) uu = 2.0 - uu;
uvs.push(uu, 1 - vv);
indexRow.push(index++);
}
indexArray.push(indexRow);
}
for (let xx = 0; xx < this._radialSegments; xx++) {
for (let yy = 0; yy < this._heightSegments; yy++) {
var a = indexArray[yy][xx];
var b = indexArray[yy + 1][xx];
var c = indexArray[yy + 1][xx + 1];
var d = indexArray[yy][xx + 1];
// faces
indices.push(a, b, d);
indices.push(b, c, d);
}
}
return index;
}
_generateCap(isTop = true, vertices, indices, normals, uvs, index) {
let centerIndexStart, centerIndexEnd;
let sign = isTop === true ? 1 : -1;
let radius = isTop === true ? this._radiusTop : this._radiusBottom;
centerIndexStart = index;
for (let xx = 1; xx <= this._radialSegments; xx++) {
vertices.push(0, this._height / 2 * sign, 0);
normals.push(0, sign, 0);
uvs.push(0.5, 0.5);
index++;
}
centerIndexEnd = index;
for (let xx = 0; xx <= this._radialSegments; xx++) {
let u = xx / this._radialSegments;
let theta = u * 2 * Math.PI;
let cosTheta = Math.cos(theta);
let sinTheta = Math.sin(theta);
vertices.push(radius * sinTheta, sign * this._height / 2, radius * cosTheta);
normals.push(0, sign, 0);
uvs.push(cosTheta * 0.5 + 0.5, sinTheta * 0.5 * sign + 0.5);
index++;
}
for (let xx = 0; xx < this._radialSegments; xx++) {
let c = centerIndexStart + xx;
let i = centerIndexEnd + xx;
if (top === true) {
// face top
indices.push(i, i + 1, c);
} else {
// face bottom
indices.push(i + 1, i, c);
}
}
return index;
}
_updateUniforms(camera) {
this._gl.uniformMatrix4fv(
this._program.getUniforms('modelMatrix').location,
false,
this.modelMatrix
);
this._gl.uniformMatrix4fv(
this._program.getUniforms('viewMatrix').location,
false,
camera.viewMatrix
);
this._gl.uniformMatrix4fv(
this._program.getUniforms('projectionMatrix').location,
false,
camera.projectionMatrix
);
}
_updateAttributes() {
this._positionBuffer.bind().attribPointer(this._program);
this._uvBuffer.bind().attribPointer(this._program);
this._normalBuffer.bind().attribPointer(this._program);
this._indexBuffer.bind();
}
draw() {
this._updateDrawStatus('back');
this._gl.drawElements(TRIANGLES, this._cnt, UNSIGNED_SHORT, 0);
this._updateDrawStatus('front');
this._gl.drawElements(TRIANGLES, this._cnt, UNSIGNED_SHORT, 0);
return this;
}
}
|
/**
* Created by Administrator on 2017/10/1 0001.
*/
//非递归实现(迭代/for循环)
function fei(n){
//n3初始化为0
var n1= 0,n2= 1,n3=0;
if(n == 0){ return 0; }
else if(n == 1){ return 1; }
else{
for(var i=2;i<=n;i++){
n3=n1+n2;
n2=n3;
n1=n2;
}
}
return n3;
}
console.log(fei(5));
//递归实现
function feibo(n){
if(n == 0){ return 0; }
else if(n == 1){ return 1; }
else{
return feibo(n-1)+feibo(n-2);
}
}
console.log(feibo(6)); |
import React from 'react'
import { ItemGroup, Item, ChangeLangItem } from 'bypass/ui/navigation'
import { ExitIcon } from 'bypass/ui/icons'
const Menu = ({ fill = false, onLogout }) => (
<ItemGroup fill={fill} justify={fill ? 'space-around' : null}>
<ChangeLangItem replace={false} />
<Item withouthBorder onClick={onLogout}>
<ExitIcon width={24} />
</Item>
</ItemGroup>
)
export default Menu
|
// import { logOutUser } from './authActions';
export function errorHandler(dispatch, error, type) {
throw (type, error);
// if (error.success === false) {
// dispatch({
// type,
// });
// logOutUser();
// }
}
|
import './OrderBookComponents.css';
import React, { PureComponent } from 'react';
import OrderText from 'components/OrderText';
import OrderTable from 'components/OrderTable';
class OrderBookComponents extends PureComponent {
render() {
const {ordersAsks, ordersBids} = this.props;
return (
<div className="order-container order-container_correct order-container_shadow">
<div className="order-content">
<OrderText />
<OrderTable
ordersAsks={ordersAsks}
ordersBids={ordersBids}
/>
</div>
</div>
);
}
}
export default OrderBookComponents;
|
/* global describe: false */
/* global it: false */
/* global expect: false */
/* global beforeEach: false */
/* global jasmine: false */
/* jshint maxstatements: 30 */
(function (Reactions) {
'use strict';
describe('Reactions.echo', function () {
it('returns the context passed as data', function (next) {
var value = 'randomValue';
Reactions.echo(value, function (err, data) {
expect(err).toBeFalsy();
expect(data).toBe(value);
next();
});
});
});
}(require('../src/reactions')));
|
import Vue from "vue";
import App from "./App.vue";
import "tailwindcss/tailwind.css";
import router from "./router";
import common from "./common";
window.axios = require("axios");
window.axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
Vue.config.productionTip = false;
Vue.mixin(common);
new Vue({
router,
render: (h) => h(App),
}).$mount("#app");
|
var keystone = require('keystone');
var session = require('keystone/lib/session');
var User = keystone.list('User');
var UserModel = keystone.list('User').model;
var bcrypt = require('bcrypt-nodejs');
exports = module.exports = function(req, res) {
var view = new keystone.View(req, res);
var locals = res.locals;
// Set locals
locals.section = 'password';
locals.formData = req.body || {};
locals.validationErrors = {};
locals.userSubmitted = false;
view.on('post', { action: 'changePassword' }, function(next) {
if(!req.body.password_origin) {
req.flash('error', "The origin password is required");
return next();
}
if(!req.body.password_new) {
req.flash('error', "The new password is required");
return next();
}
if(!req.body.password_confirm) {
req.flash('error', "The confirm password is required");
return next();
}
if(req.body.password_new != req.body.password_confirm) {
req.flash('error', "The new password and confirm password must be the same");
return next();
}
if(req.body.password_new.length < 6){
req.flash('error', "The new password at least 6 characters");
return next();
}
var newPwdTrim = req.body.password_new.trimLeft().trimRight();
var conPwdTrim = req.body.password_confirm.trimLeft().trimRight();
if(newPwdTrim != req.body.password_new || conPwdTrim != req.body.password_confirm){
req.flash('error', "The password can not be start or end with space blank");
return next();
}
// compare if the origin password is input correctly.
bcrypt.compare(req.body.password_origin, locals.user.password, function(error,result){
// compare error
if(error){
req.flash('error', "Error occurred");
return next();
}
if(!result){
req.flash('error', "The origin password is not correct");
return next();
}
bcrypt.genSalt(10, function(err, salt) {
if (err) {
req.flash('error', "Error happened");
return next();
}
bcrypt.hash(req.body.password_new, salt, function () {}, function(err, hash) {
if (err) {
req.flash('error', "Error happened");
return next();
}
UserModel.update({_id:locals.user.id},{password:hash},function(err){
if (err) {
req.flash('error', "DB Update Error");
return next();
}else {
req.flash('success', "Password changed successfully");
return next();
}
});
});
});
});
});
view.render('password');
}; |
$(function () {
'use strict';
$('div.main').on('click', '.messenger', function () {
$(this).slideUp('slow');
});
$('div.main').on('click', '.clicky', function () {
if ($('div.comments i').hasClass('icon-arrow-down')) {
$('div.the-comments span').slideUp('slow');
$('div.comments i').text(' show')
.removeClass('icon-arrow-down')
.addClass('icon-arrow-up');
$('div.comments').animate({
height: '35px'
}, 500);
} else {
$('div.the-comments span').slideDown('slow');
$('div.comments i').text(' hide')
.removeClass('icon-arrow-up')
.addClass('icon-arrow-down');
$('div.comments').animate({
height: (window.innerHeight / 2) + 'px'
}, 500);
}
});
});
/*
if (navigator.onLine === false) {
var message = 'It seems you\'ve lost internet connection.';
$('.warn').slideDown('slow');
$('.warn span').text(message);
setTimeout(function () {
$('.warn').slideUp();
}, 2500);
console.log(message);
}
*/
|
import { Debug } from "../../core/debug.js";
import {
SEMANTIC_POSITION, SEMANTIC_NORMAL, SEMANTIC_TANGENT, SEMANTIC_TEXCOORD0, SEMANTIC_TEXCOORD1, SEMANTIC_TEXCOORD2,
SEMANTIC_TEXCOORD3, SEMANTIC_TEXCOORD4, SEMANTIC_TEXCOORD5, SEMANTIC_TEXCOORD6, SEMANTIC_TEXCOORD7,
SEMANTIC_COLOR, SEMANTIC_BLENDINDICES, SEMANTIC_BLENDWEIGHT
} from './constants.js';
import gles2FS from './shader-chunks/frag/gles2.js';
import gles3FS from './shader-chunks/frag/gles3.js';
import gles3VS from './shader-chunks/vert/gles3.js';
import webgpuFS from './shader-chunks/frag/webgpu.js';
import webgpuVS from './shader-chunks/vert/webgpu.js';
import sharedFS from './shader-chunks/frag/shared.js';
const _attrib2Semantic = {
vertex_position: SEMANTIC_POSITION,
vertex_normal: SEMANTIC_NORMAL,
vertex_tangent: SEMANTIC_TANGENT,
vertex_texCoord0: SEMANTIC_TEXCOORD0,
vertex_texCoord1: SEMANTIC_TEXCOORD1,
vertex_texCoord2: SEMANTIC_TEXCOORD2,
vertex_texCoord3: SEMANTIC_TEXCOORD3,
vertex_texCoord4: SEMANTIC_TEXCOORD4,
vertex_texCoord5: SEMANTIC_TEXCOORD5,
vertex_texCoord6: SEMANTIC_TEXCOORD6,
vertex_texCoord7: SEMANTIC_TEXCOORD7,
vertex_color: SEMANTIC_COLOR,
vertex_boneIndices: SEMANTIC_BLENDINDICES,
vertex_boneWeights: SEMANTIC_BLENDWEIGHT
};
/**
* A class providing utility functions for shader creation.
*
* @ignore
*/
class ShaderUtils {
/**
* Creates a shader definition.
*
* @param {import('./graphics-device.js').GraphicsDevice} device - The graphics device.
* @param {object} options - Object for passing optional arguments.
* @param {string} [options.name] - A name of the shader.
* @param {object} [options.attributes] - Attributes. Will be extracted from the vertexCode if
* not provided.
* @param {string} options.vertexCode - The vertex shader code.
* @param {string} [options.vertexDefines] - The vertex shader defines.
* @param {string} [options.vertexExtensions] - The vertex shader extensions code.
* @param {string} [options.fragmentCode] - The fragment shader code.
* @param {string} [options.fragmentDefines] - The fragment shader defines.
* @param {string} [options.fragmentExtensions] - The fragment shader extensions code.
* @param {string} [options.fragmentPreamble] - The preamble string for the fragment shader.
* @param {boolean} [options.useTransformFeedback] - Whether to use transform feedback. Defaults
* to false.
* @returns {object} Returns the created shader definition.
*/
static createDefinition(device, options) {
Debug.assert(options);
const getDefines = (gpu, gl2, gl1, isVertex) => {
const deviceIntro = device.isWebGPU ? gpu :
(device.webgl2 ? gl2 : ShaderUtils.gl1Extensions(device, options) + gl1);
// a define per supported color attachment, which strips out unsupported output definitions in the deviceIntro
let attachmentsDefine = '';
for (let i = 0; i < device.maxColorAttachments; i++) {
attachmentsDefine += `#define COLOR_ATTACHMENT_${i}\n`;
}
return attachmentsDefine + deviceIntro;
};
const name = options.name ?? 'Untitled';
// vertex code
const vertDefines = options.vertexDefines || getDefines(webgpuVS, gles3VS, '', true);
const vertCode = ShaderUtils.versionCode(device) +
vertDefines +
sharedFS +
ShaderUtils.getShaderNameCode(name) +
options.vertexCode;
// fragment code
const fragDefines = options.fragmentDefines || getDefines(webgpuFS, gles3FS, gles2FS, false);
const fragCode = (options.fragmentPreamble || '') +
ShaderUtils.versionCode(device) +
fragDefines +
ShaderUtils.precisionCode(device) + '\n' +
sharedFS +
ShaderUtils.getShaderNameCode(name) +
(options.fragmentCode || ShaderUtils.dummyFragmentCode());
// attributes
const attribs = options.attributes ?? ShaderUtils.collectAttributes(options.vertexCode);
return {
name: name,
attributes: attribs,
vshader: vertCode,
fshader: fragCode,
useTransformFeedback: options.useTransformFeedback
};
}
// SpectorJS integration
static getShaderNameCode(name) {
return `#define SHADER_NAME ${name}\n`;
}
static gl1Extensions(device, options, isVertex) {
let code;
if (isVertex) {
code = options.vertexExtensions ? `${options.vertexExtensions}\n` : '';
} else {
code = options.fragmentExtensions ? `${options.fragmentExtensions}\n` : '';
// extensions used by default
if (device.extStandardDerivatives) {
code += "#extension GL_OES_standard_derivatives : enable\n";
}
if (device.extTextureLod) {
code += "#extension GL_EXT_shader_texture_lod : enable\n";
code += "#define SUPPORTS_TEXLOD\n";
}
if (device.extDrawBuffers) {
code += "#extension GL_EXT_draw_buffers : require\n";
code += "#define SUPPORTS_MRT\n";
}
}
return code;
}
static dummyFragmentCode() {
return "void main(void) {gl_FragColor = vec4(0.0);}";
}
static versionCode(device) {
if (device.isWebGPU) {
return '#version 450\n';
}
return device.webgl2 ? "#version 300 es\n" : "";
}
static precisionCode(device, forcePrecision) {
let code = '';
if (forcePrecision && forcePrecision !== 'highp' && forcePrecision !== 'mediump' && forcePrecision !== 'lowp') {
forcePrecision = null;
}
if (forcePrecision) {
if (forcePrecision === 'highp' && device.maxPrecision !== 'highp') {
forcePrecision = 'mediump';
}
if (forcePrecision === 'mediump' && device.maxPrecision === 'lowp') {
forcePrecision = 'lowp';
}
}
const precision = forcePrecision ? forcePrecision : device.precision;
if (!device.isWebGPU) {
code = `precision ${precision} float;\n`;
if (device.webgl2) {
code += `precision ${precision} sampler2DShadow;\n`;
}
} else { // WebGPU
code = `precision ${precision} float;\nprecision ${precision} int;\n`;
}
return code;
}
/**
* Extract the attributes specified in a vertex shader.
*
* @param {string} vsCode - The vertex shader code.
* @returns {Object<string, string>} The attribute name to semantic map.
* @ignore
*/
static collectAttributes(vsCode) {
const attribs = {};
let attrs = 0;
let found = vsCode.indexOf("attribute");
while (found >= 0) {
if (found > 0 && vsCode[found - 1] === "/") break;
const endOfLine = vsCode.indexOf(';', found);
const startOfAttribName = vsCode.lastIndexOf(' ', endOfLine);
const attribName = vsCode.substring(startOfAttribName + 1, endOfLine);
const semantic = _attrib2Semantic[attribName];
if (semantic !== undefined) {
attribs[attribName] = semantic;
} else {
attribs[attribName] = "ATTR" + attrs;
attrs++;
}
found = vsCode.indexOf("attribute", found + 1);
}
return attribs;
}
}
export { ShaderUtils };
|
import React, { useEffect, useState } from 'react'
import { FlatList, Image, KeyboardAvoidingView } from 'react-native'
import {
Layout,
Icon,
Input,
TopNavigation,
TopNavigationAction,
useTheme
} from '@ui-kitten/components'
import { ListItem, Badge } from './elements'
import { showMessage } from 'react-native-flash-message'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { Divider, EmptyPlaceholder, LoadingPlaceholder } from '~/components'
import { pokemonActions } from '~/store/actions'
import { tryAwait } from '~/utils'
import styled from 'styled-components'
import api from '~/api'
import pokeball from '../../assets/images/pokeball.png'
const TopBar = styled(TopNavigation)`
background: ${(props) => (props.bg ? props.bg : 'white')};
`
const Main = ({ navigation: { navigate }, list, setupPokemonList }) => {
const theme = useTheme()
const [ loading, setLoading ] = useState(true)
const [ searchStatus, setSearchStatus ] = useState(false)
const [ searchText, setSearchText ] = useState('')
useEffect(() => {
tryAwait({
promise: api.pokemons.listPokemons(),
onResponse: ({ data: { pokemon } }) => setupPokemonList(pokemon),
onError: () => {
showMessage({
message: 'Erro',
description: 'Error while listing pokémons.',
type: 'danger'
})
},
onLoad: _loading => setLoading(_loading)
})
}, [])
const filteredItems = () => list.filter(item =>
item.name.toLowerCase().includes(searchText.toLowerCase()) ||
item.type.filter(t => t.toLowerCase() === searchText.toLowerCase()).length
)
const renderItem = ({ item, index }) =>
<ListItem
key={index}
{...item}
onPress={() => navigate('Details', { ...item })}
/>
return (
<Layout style={{ flex: 1, position: 'relative' }} level='4'>
<TopBar
bg={theme['color-primary-500']}
title="Pokémons"
subtitle="1º Generation"
alignment="center"
accessoryLeft={() => (
<Image
style={{
marginLeft: 8,
width: 32,
height: 32,
resizeMode: 'contain'
}}
source={pokeball}
/>
)}
accessoryRight={() => (
<TopNavigationAction
style={{ padding: 8 }}
icon={props => <Icon name={searchStatus ? 'close-outline' : 'search' } {...props} />}
onPress={() => {
if (searchStatus) setSearchText('')
setSearchStatus(!searchStatus)
}}
/>
)}
/>
<KeyboardAvoidingView behavior="padding">
{ searchStatus && <Input
style={{ marginHorizontal: 8, marginTop: 8 }}
placeholder="Search here..."
value={searchText}
onChangeText={text => setSearchText(text)}
/> }
</KeyboardAvoidingView>
{ loading ? (
<LoadingPlaceholder />
) : (
<FlatList
bounces={false}
removeClippedSubviews
windowSize={21}
numColumns={2}
data={filteredItems()}
keyExtractor={({ id }) => id}
renderItem={renderItem}
ItemSeparatorComponent={() => <Divider my={1} />}
ListEmptyComponent={() => <EmptyPlaceholder />}
contentContainerStyle={{
paddingVertical: 8,
paddingHorizontal: 4
}}
/>
)}
<Badge />
</Layout>
)
}
const mapStateToProps = state => {
const { pokemon: { list = [] } } = state
return { list }
}
const mapDispatchToProps = dispatch => {
const { setupPokemonList } = pokemonActions
return bindActionCreators({ setupPokemonList }, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(Main)
|
import {
Application,
} from 'kapla';
class App {
constructor() {
return Application.start();
}
}
const instance = new App();
/**
* Get Kapla instance from DOM element.
*
* @param {HTMLElement} parent DOM parent
* @param {string} name Component name
* @returns {Component} Kapla component instance
*/
export function getInstance(parent, name) {
const el = parent.querySelector(`[data-component="${name}"]`);
return instance.instanceByElement(el);
}
export default instance;
|
import React, {useState,useEffect} from 'react'
import Formulario from './components/Formulario'
import ListadoImagenes from './components/ListadoImagenes'
function App() {
const [busqueda, setBusqueda] = useState('')
const [imagenes, setImagenes] = useState([])
const [paginaActual, setPaginaActual] = useState(1)
const [totalPaginas, setTotalPaginas] = useState(5)
useEffect(()=>{
const consultarAPI = async () =>{
if(busqueda === '') return null
const imgXPg= 30
const apiKey= `${process.env.REACT_APP_IMAGES_API}`
const url = `https://pixabay.com/api/?key=${apiKey}&q=${busqueda}&per_page=${imgXPg}&page=${paginaActual}`
const respuesta = await fetch(url)
const imagenes = await respuesta.json()
setImagenes(imagenes.hits)
setTotalPaginas(Math.ceil(respuesta.totalHits / imgXPg))
const jumbotron = document.querySelector(".jumbotron")
jumbotron.scrollIntoView({behavior: 'smooth'})
}
consultarAPI()
}, [busqueda, paginaActual])
const paginaAnterior = () =>{
const nuevaPaginaActual = paginaActual - 1
if(nuevaPaginaActual === 0) return
setPaginaActual(nuevaPaginaActual)
}
const paginaSiguiente = () =>{
const nuevaPaginaActual = paginaActual + 1
if(nuevaPaginaActual > totalPaginas) return
setPaginaActual(nuevaPaginaActual)
}
return (
<div className='container'>
<div className="jumbotron">
<p className="lead text-center">Buscador de Imágenes</p>
<Formulario setBusqueda={setBusqueda}/>
</div>
<ListadoImagenes imagenes={imagenes}/>
<div className="text-center pb-5">
{paginaActual=== 1 ? null: (<button type='button' className='btn btn-info mr-1' onClick={paginaAnterior}>« Anterior </button>)}
{(paginaActual=== totalPaginas) ? null : (<button type='button' className='btn btn-info mr-1' onClick={paginaSiguiente}>Siguiente »</button>)}
</div>
</div>
);
}
export default App;
|
import { connect } from 'react-redux';
import Profile from './Profile.screen';
const mapState = state => {
return {
user: state.user.user
};
};
export default connect(mapState)(Profile);
|
import React from "react"
class MemeGenerator extends React.Component{
constructor(){
super()
this.state ={
topText : "",
bottomText : "",
allMemeImg: {},
randomImg:"http://i.imgflip.com/1bij.jpg",
mouseDownOn: "",
data: {}
}
this.showState = this.showState.bind(this)
this.validateInput = this.validateInput.bind(this)
this.generateMeme = this.generateMeme.bind(this)
this.textMouseDown = this.textMouseDown.bind(this)
this.textMouseUp = this.textMouseUp.bind(this)
this.draggingOver = this.draggingOver.bind(this)
this.droppingItem = this.droppingItem.bind(this)
this.pickImage = this.pickImage.bind(this)
}
componentDidMount(){
fetch('https://api.imgflip.com/get_memes')
.then(response =>response.json())
.then(data => {
this.setState(prevState => {
let newState = JSON.parse(JSON.stringify(prevState))
newState.allMemeImg = data.data.memes
newState.data =data.data
console.log(newState)
return newState
})
})
}
showState(){
console.log(this.state)
}
validateInput(event){
const {name, value} = event.target
this.setState(prevState => {
let newState = JSON.parse(JSON.stringify(prevState))
newState.[name] = value
console.log(newState.[name])
return newState
})
}
generateMeme(event){
console.log("meme generated")
const newImageIndex = Math.floor(Math.random() * this.state.allMemeImg.length)
this.setState(prevState => {
let newState = JSON.parse(JSON.stringify(prevState))
newState.randomImg = newState.allMemeImg[newImageIndex].url
return newState
})
event.preventDefault()
}
textMouseDown(event){
this.setState(prevState =>{
let newState = JSON.parse(JSON.stringify(prevState))
newState.mouseDownOn = event.target.id
return newState
})
}
textMouseUp(){
this.setState(prevState =>{
let newState = JSON.parse(JSON.stringify(prevState))
newState.mouseDownOn = null
console.log(newState.mouseDownOn)
return newState
})
}
draggingOver(event){
event.preventDefault()
if (this.state.mouseDownOn !== "" && this.state.mouseDownOn !== null) {
let filmContainer = document.getElementById("mad-text-film").getBoundingClientRect()
let relativeX = event.clientX - filmContainer.left
let relativeY = event.clientY - filmContainer.top
let elmentToMove = document.getElementById(this.state.mouseDownOn)
event.target.style.cursor = "pointer"
elmentToMove.style.top = (relativeY - 28) +"px"
elmentToMove.style.left = relativeX + "px"
}
}
droppingItem(event){
this.setState(prevState =>{
let newState = JSON.parse(JSON.stringify(prevState))
newState.mouseDownOn = null
// console.log(newState.mouseDownOn)
return newState
})
}
pickImage(event){
console.log(event.target)
const newImageIndex = Math.floor(Math.random() * this.state.allMemeImg.length)
this.setState(prevState => {
let newState = JSON.parse(JSON.stringify(prevState))
newState.randomImg = newState.allMemeImg[event.target.id].url
return newState
})
}
render(){
// const images = this.state.data.map(meme => <div> meme.url</div>)
let images = []
for (let i = 0; i < this.state.allMemeImg.length; i++){
let imgStyle = {
backgroundImage : `url(${this.state.allMemeImg[i].url})`,
}
images.push(<div className="mad-image-item" id={i} onClick={this.pickImage} style={imgStyle} key={this.state.allMemeImg[i].id} ></div>)
}
return(
<div >
<form className="mad-meme-generator" onSubmit={this.generateMeme}>
<input placeholder="text here " value={this.state.topText} onChange={this.validateInput} type="text" name="topText" />
<input placeholder="text here " value={this.state.bottomText} onChange={this.validateInput} type="text" name="bottomText" />
<button>Random image</button>
</form>
<div className="mad-image-picker">
{images}
</div>
<div className="mad-meme-generated" >
<img src={this.state.randomImg} alt="This meme was not found mlml"/>
<div className="mad-text-film" id="mad-text-film" onDragOver={event => this.draggingOver(event)} onDrop={event => this.droppingItem(event)}>
<h2 id="text1" onMouseDown={this.textMouseDown} onMouseUp={this.textMouseUp} draggable className="top">{this.state.topText}</h2>
<h2 id="text2" onMouseDown={this.textMouseDown} onMouseUp={this.textMouseUp} draggable className="bottom">{this.state.bottomText}</h2>
</div>
</div>
</div>
)
}
}
export default MemeGenerator |
const init = require('../../common/init').init();
const {web3, acc} = init.initWeb3AndAccount();
const arbitrageInfo = init.getArbitrage();
let cc = require("../../ChainConfig");
// let ca = require("../../ContractAddresses");
const {program} = require('commander');
const c = console.log;
let utils = web3.utils;
const GAS = process.env.APP_ENV == 'production' ? 100000 : 5000000;
(async () => {
let gGasPrice = await web3.eth.getGasPrice();
c(`gasPrice: ${gGasPrice}`);
let timestamp = await (await web3.eth.getBlock(await web3.eth.getBlockNumber())).timestamp;
c(timestamp);
//TOKEN
let weth = new web3.eth.Contract(cc.token.weth.abi, cc.token.weth.address);
let usdt = new web3.eth.Contract(cc.token.usdt.abi, cc.token.usdt.address);
let dai = new web3.eth.Contract(cc.token.dai.abi, cc.token.dai.address);
let wbtc = new web3.eth.Contract(cc.token.wbtc.abi, cc.token.wbtc.address);
let uniRoute2 = new web3.eth.Contract(cc.exchange.uniswap.router02.abi, cc.exchange.uniswap.router02.address)
let sushiRoute2 = new web3.eth.Contract(cc.exchange.sushiswap.router02.abi, cc.exchange.sushiswap.router02.address)
let uniPairETHDAI = new web3.eth.Contract(cc.exchange.uniswap.pair.abi, cc.exchange.uniswap.pair['dai-eth'].address);
let sushiPairETHDAI = new web3.eth.Contract(cc.exchange.sushiswap.pair.abi, cc.exchange.sushiswap.pair['dai-eth'].address);
let arbitrage = new web3.eth.Contract(arbitrageInfo.abi, arbitrageInfo.address)
let warpETHContract = new web3.eth.Contract(cc.wrapETH.abi, cc.wrapETH.address);
program.version('0.0.1')
.command('transform <token> <amount>')
.description("transfer to weth/eth")
.action(async function (token, amount) {
if (token == 'weth') {
await warpETHContract.methods.deposit().send({
from: acc.address,
value: web3.utils.toWei(amount, 'ether'),
gas: GAS,
gasPrice: gGasPrice,
});
} else if (token = 'eth') {
await warpETHContract.methods.withdraw(web3.utils.toWei(amount, 'ether')).send({
from: acc.address,
gas: GAS,
gasPrice: gGasPrice
});
} else {
console.error('unknown token:' + token);
}
});
async function deposit(token, amount) {
await depositOrWithdraw('deposit', token, amount);
}
async function withdraw(token, amount) {
await depositOrWithdraw('withdraw', token, amount);
}
async function depositOrWithdraw(depoistOrWithdraw, _token, amount) {
let token = null;
switch (_token) {
case '':
case 'weth':
token = weth;
break;
case 'usdt':
token = usdt;
break;
default:
c('unknown token');
return;
}
if (depoistOrWithdraw == 'deposit') {
await token.methods.transfer(arbitrageInfo.address, web3.utils.toWei(amount, 'ether')).send({
from: acc.address,
gas: GAS,
gasPrice: gGasPrice
});
} else if (depoistOrWithdraw = 'withdraw') {
if (amount == 0) {
await arbitrage.methods
.withdraw(cc.token[_token].address)
.send({
from: acc.address, gas: GAS,
gasPrice: gGasPrice
});
} else {
await arbitrage.methods
.withdrawN(cc.token[_token].address, web3.utils.toWei(amount, 'ether'))
.send({
from: acc.address, gas: GAS,
gasPrice: gGasPrice
});
}
} else {
console.error('unknown depoistOrWithdraw:' + depoistOrWithdraw);
}
}
program.version('0.0.1')
.command('deposit <token> <amount>')
.description("deposit/withdraw to/from arbitrage contract")
.action(deposit);
program.version('0.0.1')
.command('withdraw <token> <amount>')
.description("deposit/withdraw to/from arbitrage contract")
.action(withdraw);
program.version('0.0.1')
.command('balance')
.description("balance")
.action(async function () {
c("账户余额: ");
c("eth: " + utils.fromWei(await web3.eth.getBalance(acc.address), 'ether'));
c("dai: " + utils.fromWei(await dai.methods.balanceOf(acc.address).call(), 'ether'));
c("wbtc: " + utils.fromWei(await wbtc.methods.balanceOf(acc.address).call(), 'gwei'));
c("weth: " + utils.fromWei(await weth.methods.balanceOf(acc.address).call(), 'ether'));
c("usdt: " + utils.fromWei(await usdt.methods.balanceOf(acc.address).call(), 'mwei'));
c("合约初始余额: ");
c("eth: " + utils.fromWei(await web3.eth.getBalance(arbitrageInfo.address), 'ether'));
c("dai: " + utils.fromWei(await dai.methods.balanceOf(arbitrageInfo.address).call(), 'ether'));
c("weth: " + utils.fromWei(await weth.methods.balanceOf(arbitrageInfo.address).call(), 'ether'));
c("usdt: " + utils.fromWei(await usdt.methods.balanceOf(arbitrageInfo.address).call(), 'mwei'));
});
program.version('0.0.1')
.command('approve <token> <spender> <amount>')
.description("approve <token> <spender> <amount>")
.action(async function (token, spender, amount) {
if (token == '0xdac17f958d2ee523a2206206994597c13d831ec7') {
await arbitrage.methods
.approveUSDT(token, spender, amount)
.send({
from: acc.address,
gas: GAS,
gasPrice: gGasPrice
});
} else {
await arbitrage.methods
.approve(token, spender, amount)
.send({
from: acc.address,
gas: GAS,
gasPrice: gGasPrice
});
}
});
program.version('0.0.1')
.command('allowance <token> <spender>')
.description("allowance <token> <spender>")
.action(async function (token, spender) {
c(await arbitrage.methods
.allowance(token, spender)
.call());
});
program.parse(process.argv);
})();
|
module.exports = `
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>
<svg width="20" version="1.1" xmlns="http://www.w3.org/2000/svg" height="20" viewBox="0 0 64 64" xmlns:xlink="http://www.w3.org/1999/xlink" enable-background="new 0 0 64 64">
<g>
<path fill="#1D1D1B" d="M3.352,48.296l28.56-28.328l28.58,28.347c0.397,0.394,0.917,0.59,1.436,0.59c0.52,0,1.04-0.196,1.436-0.59 c0.793-0.787,0.793-2.062,0-2.849l-29.98-29.735c-0.2-0.2-0.494-0.375-0.757-0.475c-0.75-0.282-1.597-0.107-2.166,0.456 L0.479,45.447c-0.793,0.787-0.793,2.062,0,2.849C1.273,49.082,2.558,49.082,3.352,48.296z"/>
</g>
</svg>`; |
const Tx = require('./model');
const request = require('request');
const config = require('../../config');
const sign = require('../../utils/sign');
const sha256 = require('sha256');
const syncBlockchain = async msg => {
let _sign = sign(msg);
config.defaultNodes.forEach(node => {
request.post({url: `http://${node}/tx`, form: _sign}, (e, res, body) => {
if (e) {
console.error(e);
}
});
});
};
const getPreStateHash = (ref, cb) => {
let msg = {
header: 'GET_PLANS_BY_COMPANY',
company: config.myCompany,
time: new Date()
};
let _sign = sign(msg);
let failCount = 0;
let queryStatePromise = new Promise((resolve, reject) => {
config.defaultNodes.forEach(node => {
request.post({url: `http://${node}/get-plans-by-company`, form: _sign}, (e, res, body) => {
if (e) {
failCount++;
if (failCount === config.defaultNodes.length) {
return reject(new Error('Cannot connect to blockchain'));
}
} else {
let plans = JSON.parse(body);
for (let i = 0; i < plans.length; i++) {
if (plans[i].id === ref.plan.id) {
return resolve(sha256(JSON.stringify(plans[i].term)));
}
}
}
});
});
});
queryStatePromise.then(preStateHash => {
cb(preStateHash);
}).catch(e => {
console.error(e);
})
};
module.exports.updateTx = async (id, txInfo) => {
delete txInfo.id;
let tx = await Tx.findOneAndUpdate({id: id}, {$set: txInfo}, {new: true});
if (tx) {
if (tx.status && tx.type === 'CONTRACT') {
getPreStateHash(tx.ref, preStateHash => {
syncBlockchain({
type: tx.type,
ref: tx.ref,
preStateHash: preStateHash,
action: {
create: true
}
});
});
}
}
};
module.exports.getAllTx = async () => {
return await Tx.find({}).sort({time: -1});
};
module.exports.createContractTx = async txInfo => {
delete txInfo.action;
return await Tx.create(txInfo);
};
module.exports.createPlanTx = async txInfo => {
syncBlockchain({
type: txInfo.type,
ref: txInfo.ref,
preStateHash: null,
action: txInfo.action
});
txInfo.status = true;
return await Tx.create(txInfo);
}; |
import React from 'react';
import {
View,
Text,
ScrollView,
} from 'react-native';
import {COLORS, FONTS, SIZES, icons, images} from '../constants';
const Book_read = ({route, navigation}) => {
const [Bookread, setBookread] = React.useState(Bookread);
React.useEffect(() => {
let {Bookread} = route.params;
setBookread(Bookread);
}, [Bookread]);
function renderContent() {
return (
<View>
{/* back */}
<View
style={{
paddingHorizontal: SIZES.padding,
flexDirection: 'row',
justifyContent: 'space-between',
}}>
<Text
style={{...FONTS.h2, color: COLORS.black,marginTop: SIZES.radius}}
onPress={() => navigation.goBack()}>
Back
</Text>
</View>
<ScrollView style={{marginTop: SIZES.radius}}>
<View style={{flex: 1, flexDirection: 'row', padding: SIZES.padding}}>
{/* Custom Scrollbar */}
<View style={{width: 4}}></View>
{/* Description */}
<Text style={{...FONTS.body2, color: Bookread.navTintColor}}>
{Bookread.Contents}
</Text>
</View>
</ScrollView>
</View>
);
}
if (Bookread) {
return (
<View style={{flex: 1, backgroundColor: Bookread.backgroundColor}}>
{/* Description */}
<View style={{flex: 1}}>{renderContent()}</View>
</View>
);
} else {
return <></>;
}
};
export default Book_read; |
var parallax = (function(){
var layer1 = document.querySelector('.layer-1');
var layer3 = document.querySelector('.layer-3');
var layer4 = document.querySelector('.layer-4');
var layer5 = document.querySelector('.layer-5');
var layer6 = document.querySelector('.layer-6');
var layer7 = document.querySelector('.layer-7');
var layer8 = document.querySelector('.layer-8');
var layer9 = document.querySelector('.hero__content');
return{
move:function(block,windowScroll,strafeAmount) {
var strafe = windowScroll / -strafeAmount + '%';
var transformString = 'translate3d(0,'+ strafe +',0)';
var style = block.style;
style.transform = transformString;
style.webkitTransform = transformString;
},
init:function (wScroll){
this.move(layer1,wScroll,40);
this.move(layer3,wScroll,-25);
this.move(layer4,wScroll,25);
this.move(layer5,wScroll,15);
this.move(layer6,wScroll,25);
this.move(layer7,wScroll,40);
this.move(layer8,wScroll,40);
this.move(layer9,wScroll,20);
}
}
}());
window.onscroll = function(){
var wScroll=window.pageYOffset;
parallax.init(wScroll);
} |
import React from 'react'
import '../index.css'
class Topbar extends React.Component{
// eslint-disable-next-line
constructor(props) {
super(props)
}
render() {
return (
<div>
<button className="close" onClick={this.props.exit}></button>
<button className="minimise"onClick={this.props.show}></button>
<button className="maximise" onClick={this.props.maximise}></button>
<button className="dark-button" onClick={() => this.props.changeColour('dark')}>Dark</button>
<button className="light-button" onClick={() => this.props.changeColour('light')}>Light</button>
<button className="scientific-button" onClick={() => this.props.changeFormat()}>Scientific</button>
</div>
)
}
}
export default Topbar; |
//-----------------------------------------------------------------------------
// Starship
// A Starship launch and landing simulator
// Note: all units are kg, meters, m/s, m/s/s, radians, newtons, etc.
//
// Author: Brian Burns
// History:
// version 0.1 2001-05 bounces on surface
// version 0.2 2012-05 added base
// version 0.3 2020-10 convert from java to javascript
//-----------------------------------------------------------------------------
import * as sprites from './sprites'
const themes = {
dark: {
sky: '#222',
ship: '#eee',
flame: ['orange', 'yellow'],
spark: 'red',
land: '#ccc',
base: '#bbb',
moon: '#999',
stars: 'white',
},
light: {
sky: 'white',
ship: 'black',
flame: ['orange', 'yellow'],
spark: 'red',
land: 'gray',
base: 'gray',
moon: '#ccc',
stars: '#ddd',
}
}
const theme = 'dark'
// const theme = 'light'
const colors = themes[theme]
class App {
constructor() {
this.timeStep = 0.1 // integration and step timestep [seconds]
this.rdelta = 0.0
this.rdeltaamount = 0.2
this.throttle = 0
this.throttleamount = 10
this.world = new World()
}
// Initialize the applet
run(context) {
this.context = context
this.graphics = new Graphics(context)
// Initialize world and all the sprites it contains
this.world.init(context.canvas.width, context.canvas.height)
setInterval(this.step.bind(this), this.timeStep*1000)
}
onKeyDown(event) {
switch (event.key) {
case 'a':
this.world.bStop = true
break
case 'ArrowLeft':
this.rdelta = -this.rdeltaamount
break
case 'ArrowRight':
this.rdelta = this.rdeltaamount
break
case 'ArrowUp':
this.throttle = this.throttleamount
break
case 'ArrowDown':
this.throttle = -this.throttleamount
break
}
}
onKeyUp(event) {
switch (event.key) {
case 'ArrowLeft':
case 'ArrowRight':
this.rdelta = 0.0
break
case 'ArrowUp':
case 'ArrowDown':
this.throttle = 0
break
}
}
step() {
this.world.ship.rotate(this.rdelta)
this.world.ship.setThrottle(this.throttle)
this.world.step(this.timeStep)
this.world.draw(this.graphics)
this.world.checkCollisions(this.graphics)
}
}
//-----------------------------------------------------------------------------
// World
//-----------------------------------------------------------------------------
// The world object contains all the sprites - the ship, land, stars, moon,
// clouds, etc.
// Each sprite can be fixed or movable.
// Also contains a view which it uses in rendering itself and its sprites.
class World {
constructor() {
// Attributes:
this.width = 0 // Width and height of world, in world units (meters)
this.height = 0
this.radiansPerDegree = 2.0 * Math.pi / 360.0 // conversion factor
this.g = 5.0 // gravity (m/s/s)
// views should probably belong to the applet, since that's the main window
// will want a view for the stats also, which could be its own class?
this.viewMain = new View()
// this.viewShip = new View()
// Sprite objects in this world
this.ship = new Ship()
this.land = new Land()
this.moon = new Moon()
this.base = new Base()
// this.stars = new Stars()
// this.clouds = new Clouds()
}
// Initialize the world
init(widthPixels, heightPixels) {
const widthWindow = 500.0 // the view window looks on this many meters of the world horizontally
this.width = widthWindow * 2 // let's make the world two view width's wide
this.height = widthWindow / 2.0
// Initialize view
this.viewMain.init(this, widthPixels, heightPixels, widthWindow)
// Set the zoom scale
this.viewMain.setScale(1.0)
// Initialize all the sprites
this.ship.init(this)
this.land.init(this)
this.moon.init(this)
this.base.init(this)
// this.stars.init(this)
// this.clouds.init(this)
// Put ship in middle of world
this.ship.setPos(this.width / 2.0, this.height / 2.0)
// this.ship.setPos(this.width / 2.0, this.height * 5/6)
//, Tell view to track the ship sprite
// this.view.trackSprite(this.ship)
}
// Advance the world and all objects in it by one timestep.
step(timeStep) {
// Move ship and any other moving sprites
this.ship.step(timeStep)
// Center the view on the ship
this.viewMain.centerOn(this.ship)
}
// Draw the world and all the sprites it contains
draw(graphics) {
// Clear canvas
graphics.clear()
// Draw sprites
this.moon.draw(graphics, this.viewMain)
this.land.draw(graphics, this.viewMain)
this.base.draw(graphics, this.viewMain)
this.ship.draw(graphics, this.viewMain)
// this.stars.draw(graphics, this.viewMain)
// this.clouds.draw(graphics, this.viewMain)
// Draw stats and border
// this.viewMain.drawBorder(graphics) // flickers
// this.ship.drawStats(graphics) // flickers
}
// Check for collisions
// no return value
checkCollisions(graphics) {
// Check for ship-base collision = bad or good depending on speed
let pointIntersect = this.ship.checkCollision(this.base, graphics)
if (pointIntersect) {
// Draw a spark at the point of intersection (a small green circle)
let r = 10
graphics.setColor('green')
graphics.drawCircle(pointIntersect.x, pointIntersect.y, r)
// Ship should explode if above a certain velocity
if ((this.ship.vy*this.ship.vy + this.ship.vx*this.ship.vx) > 25) {
r = 20
graphics.setColor('orange')
graphics.drawCircle(pointIntersect.x, pointIntersect.y, r)
console.log("explode ship")
this.ship.explode()
}
//. always stop the ship?
this.ship.vx = 0
this.ship.vy = 0
return
}
// Check for collisions between the ship and land.
pointIntersect = this.ship.checkCollision(this.land, graphics)
if (pointIntersect) {
// Draw a spark at the point of intersection (a small red circle)
const r = 5
graphics.setColor(colors.spark)
graphics.drawCircle(pointIntersect.x, pointIntersect.y, r)
// Impart momentum to the ship
//. a certain amount of energy will go into deforming soil and ship
// ship.angularVelocity += 0.2f
this.ship.vy = -15.0 // bounce up!
//. Ship should explode if above a certain velocity
// this.ship.explode()
}
}
}
//-----------------------------------------------------------------------------
// View
//-----------------------------------------------------------------------------
// A view is a window on the world.
// Has a certain position in the world, and converts to/from pixel units.
// Can be set to track a certain sprite, to keep it in the center of the view.
class View {
constructor() {
// Attributes
this.world = null // reference to world that this view is looking at
this.trackSprite = null // reference to sprite that we want to track
this.tWorldToView = new sprites.Transform() // transform from world coordinates to view coordinates
// Position and size of view, in world coordinates
this.xWorld = 0
this.yWorld = 0
this.widthWorld = 0
this.heightWorld = 0
// Size of view, in pixels
this.widthPixels = 0
this.heightPixels = 0
// Scale
// private float aspectRatio = 1.2f
this.xscale = 0 // pixels per world unit
this.yscale = 0
this.scaleFactor = 0 // unitless zoom factor (eg 2.0 means zoom in by factor of 2, 0.5 is zoom out)
}
// Initialize the view
init(world, viewWidthPixels, viewHeightPixels, viewWidthWorldUnits) {
this.world = world
this.widthPixels = viewWidthPixels
this.heightPixels = viewHeightPixels
this.scaleFactor = 1.0 // initialize zoom factor (unitless)
// Get conversion factor between pixels and world units
this.xscale = this.widthPixels / viewWidthWorldUnits // pixels per world unit
this.yscale = this.xscale // for now
// Save width and height of view in world units
this.widthWorld = viewWidthWorldUnits
this.heightWorld = this.heightPixels / this.yscale
// Initialize the view transform, which converts from world coordinates to view coordinates (pixels)
this.tWorldToView.setScale(this.xscale * this.scaleFactor, this.yscale * this.scaleFactor)
this.tWorldToView.setRotation(0.0)
// this.tWorldToView.setTranslation(- this.xscale * this.xWorld, - this.yscale * this.yWorld)
this.setPos(this.xWorld, this.yWorld) // sets translate vector
}
// Track the specified sprite to keep it centered in the view if possible
trackSprite(sprite) {
this.trackSprite = sprite
}
setScale(scale) {
this.scaleFactor = scale
// this.tWorldToView.setScale(scale, scale)
// this.tWorldToView.setTranslation(- this.xscale * this.xWorld, - this.yscale * this.yWorld)
this.tWorldToView.setScale(this.xscale * this.scaleFactor, this.yscale * this.scaleFactor)
this.setPos(this.xWorld, this.yWorld) // upates translate vector
}
// Center view on the specified sprite
//. also include approx size of sprite
centerOn(sprite) {
// Set position of view in world coords so sprite will be centered in the view
this.x = sprite.x - this.widthWorld / 2 / this.scaleFactor
this.y = sprite.y - this.heightWorld / 2 / this.scaleFactor
// Keep view in world vertically
if ((this.y + this.heightWorld / this.scaleFactor) > this.world.height)
this.y = this.world.height - this.heightWorld / this.scaleFactor
if (this.y < 0)
this.y = 0
// Wraparound view horizontally
// if (this.x > this.world.width)
// this.x -= this.world.width
// if (this.x < 0)
// this.x += this.world.width
// Set the position for the view and update the transform matrix
this.setPos(this.x, this.y)
}
// Set the position of the view within the world
setPos(xWorld, yWorld) {
this.xWorld = xWorld
this.yWorld = yWorld
// Update transform
// this.tWorldToView.setTranslation(- this.xscale * this.xWorld, - this.yscale * this.yWorld)
this.tWorldToView.setTranslation(- this.xscale * this.scaleFactor * this.xWorld, - this.yscale * this.scaleFactor * yWorld)
}
// Draw a border around view
//... this flickers, badly
drawBorder(graphics) {
graphics.setColor(colors.view)
graphics.drawRect(0, 0, this.widthPixels - 1, this.heightPixels - 1)
}
}
//-----------------------------------------------------------------------------
// Ship
//-----------------------------------------------------------------------------
// A sprite to represent the ship
// Also contains a flame sprite, to represent the flame.
class Ship extends sprites.Sprite {
constructor() {
super()
// Attributes
this.massShip = 0 // [kg]
this.massFuel = 0 // [kg]
this.rotationUnit = 0 // [radians]
this.burnRate = 0 // [kg/s]
this.exhaustVelocity = 0 // [m/s]
this.thrustUnit = 0 // [N]
this.throttle = 0 // 0 to 10. thrust = throttle * thrustunit
this.shipSize = 30.0 // rough size of ship
this.outOfFuel = false // flag
this.flame = new Flame() // sprite representing flame
}
// Initialize the ship
init(world) {
this.world = world
this.flame.init(world)
this.flame.ship = this
this.massShip = 1000 // kg
this.massFuel = 5000 // kg
this.mass = this.massShip + this.massFuel
this.rotation = 0.0 // radians
this.rotationUnit = 1.0 * world.radiansPerDegree // degrees converted to radians
this.exhaustVelocity = 250.0 // m/s (approximately mach 1)
this.momentOfInertia = this.massShip * 2 * (25+15) * (1 - 1 / Math.sqrt(2)) // kg (about center of mass)
// Parallel axis theorem - For Mass Moments of Inertia
// M : is the mass of the body.
// d : is the perpendicuar distance between the centroidal axis and the parallel axis.
// Ic is moment of inertia about center of mass
// Ip = Ic + M*d*d
// Calculate a burnRate that will balance out gravity at
// throttle 5 and fuel tank half empty.
// this.burnRate = 1.0 // kg/s
this.burnRate = (world.g * this.massShip + (this.massFuel / 2.0)) / (5.0 * this.exhaustVelocity) // 2.8 kg/s for g=1m/s/s
this.burnRate *= 6.0 //?
this.thrustUnit = this.burnRate * this.exhaustVelocity // kgm/s/s = newtons
// Define ship's vertices, in world units (meters)
this.shapeModel.addPoint( 0, -25) // 0
this.shapeModel.addPoint(-10, 10) // 1
this.shapeModel.addPoint( -7, 1) // 2
this.shapeModel.addPoint(-21, 15) // 3
this.shapeModel.addPoint( 10, 10) // 4
this.shapeModel.addPoint( 21, 15) // 5
this.shapeModel.addPoint( 7, 1) // 6
// Define ship's shape with line segments
this.shapeModel.addLineTo(0)
this.shapeModel.addLineTo(1)
this.shapeModel.addLineTo(2)
this.shapeModel.addLineTo(3)
this.shapeModel.addLineTo(1)
this.shapeModel.addLineTo(4)
this.shapeModel.addLineTo(5)
this.shapeModel.addLineTo(6)
this.shapeModel.addLineTo(4)
this.shapeModel.addLineTo(0)
this.setScale(1.0)
this.setRotation(this.rotation)
}
// Set the throttle level
setThrottle(throttle) {
if (this.outOfFuel)
this.throttle = 0
else
this.throttle = throttle
}
// Move the ship according to its velocity, gravity, thrust, etc,
// and update the drawing shape.
step(timeStep) {
// Get amount of fuel burned
const mass = this.massShip + this.massFuel
const fuelBurned = this.throttle * this.burnRate * timeStep
const thrust = this.throttle * this.thrustUnit
const thrustAccel = thrust / mass
// Move ship according to gravity, thrust, etc.
this.ax = thrustAccel * Math.sin(this.rotation)
this.ay = - thrustAccel * Math.cos(this.rotation) + this.world.g
// this.ay = - thrustAccel * Math.cos(this.rotation)
// Update fuel remaining
this.massFuel -= fuelBurned
if (this.massFuel < 0) {
this.massFuel = 0
this.outOfFuel = true
}
// Call base class
super.step(timeStep)
}
//. Make the ship explode!
explode() {
// draw orange and yellow circles filled for fire.
// create a bunch of sub-sprites for pieces of ship,
// give them all rnd velocities (plus ships velocity).
// on draw just draw these instead of the ship.
// on step move these instead of ship.
// ie make a ShipRemains object with a bunch of subobjects with different velocities?
// have them all stop at some depth under the horizon.
// call super with a parameter for velocities etc
// replace existing sprite with child sprites.
// ie remove all line segments from this sprite. right?
// super.explode()
}
// Draw ship stats
//. this flickers too much - don't call it
drawStats(graphics) {
//! format
// what is all this - where's printf?
// NumberFormat numberFormatter
// numberFormatter = NumberFormat.getNumberInstance(currentLocale)
// numberFormatter.format(amount)
let s
// s = "Position (m): (" + x + ", " + y + ")"
// g.drawString(s, 4, 22)
s = "Velocity (m/s): (" + Math.floor(this.vx*10)/10 + ", " + Math.floor(this.vy*10)/10 + ")"
graphics.setColor(colors.stats)
graphics.drawString(s, 4, 22)
// s = "Acceleration (m/s/s): (" + ax + ", " + ay + ")"
// graphics.drawString(s, 4, 44)
// s = "Rotation: (" + rotation + ")"
// graphics.drawString(s, 4, 55)
// s = "Throttle: (" + throttle + ")"
// graphics.drawString(s, 4, 66)
s = "Fuel (kg): (" + this.massFuel + ")"
if (this.massFuel < 500)
graphics.setColor('red')
graphics.drawString(s, 4, 33)
// graphics.setColor('black')
// s = "view pos: (" + polyDraw.xpoints[0] + ", " + polyDraw.ypoints[0] + ")"
// graphics.drawString(s, 4, 80)
}
// Draw ship according to the specified view transformations
draw(graphics, view) {
// Call base class to draw model
graphics.setColor(colors.ship)
super.draw(graphics, view)
// Draw flame
// how do we handle this? step could turn this subsprite on and off, ie set a flag in it
// sprite.draw could check for subsprites and transform them the same as the
// parent sprite, if the lock flag was set, otherwise would use their own transform
// this would make it easier to have things detach, like rocket boosters, and let
// them fall away - they would get same vel as ship, but only gravity would work on them.
// also each sprite could have different colors, or each segment could?
// might need to override draw for flame to get it to flicker correctly but that's okay
if (this.throttle > 0)
this.flame.draw(graphics, view)
}
}
//-----------------------------------------------------------------------------
// Flame
//-----------------------------------------------------------------------------
// A sprite to represent the flickering flame from the ship
class Flame extends sprites.Sprite {
constructor() {
super()
this.ship = null // the shipe this sprite belongs to
}
// Initialize the flame
init(world) {
this.world = world
// Define flame's shape, in world units (meters)
this.shapeModel.addPoint(-5, 11) // 0
this.shapeModel.addPoint( 0, 60) // 1
this.shapeModel.addPoint( 5, 11) // 2
this.shapeModel.addLineTo(0)
this.shapeModel.addLineTo(1)
this.shapeModel.addLineTo(2)
}
// Draw the flickering flame
//, Note: will eventually just use base class to draw this sprite -
// it has a parent which is where draw will get tModelToWorld from
draw(graphics, view) {
// Set color for flames
// if (Math.random() > 0.5)
// graphics.setColor('yellow') //. do white or yelloworange. red is too red. redorange?
// else
// graphics.setColor('orange')
graphics.setColor(colors.flame[Math.floor(Math.random() * colors.flame.length)])
// Draw shape using base class
// super.draw(graphics, view)
this.shapeDraw.copyFrom(this.shapeModel)
this.shapeDraw.transform(this.ship.tModelToWorld)
this.shapeDraw.transform(view.tWorldToView)
this.shapeDraw.drawShape(graphics)
}
}
//-----------------------------------------------------------------------------
// Land
//-----------------------------------------------------------------------------
// A sprite to represent the hills.
// Land will wrap around when reaches the edges.
class Land extends sprites.Sprite {
// Initialize the land sprite, by making up random hills.
init(world) {
this.world = world
this.width = world.width
this.height = world.height
const hillHeight = this.height / 5 //. 20% of world height
// Create random horizon line
const nPoints = 40
for (let i = 0; i < nPoints; i++) {
const x = this.width * i / (nPoints - 1)
const y = this.height - (Math.random() * hillHeight)
this.shapeModel.addPoint(x, y)
this.shapeModel.addLineTo(i)
}
// Make space for a base
this.nBase = Math.floor(nPoints * Math.random())
this.shapeModel.yPoints[this.nBase] =
this.shapeModel.yPoints[this.nBase+1] =
this.shapeModel.yPoints[this.nBase+2]
// Make the last point the same as the first point so it will wrap around properly
this.shapeModel.yPoints[nPoints-1] = this.shapeModel.yPoints[0]
// Set scale
this.setScale(1.0)
}
// Draw the land
draw(graphics, view) {
graphics.setColor(colors.land)
this.shapeDraw.copyFrom(this.shapeModel)
this.shapeDraw.transform(this.tModelToWorld)
this.shapeDraw.transform(view.tWorldToView)
this.shapeDraw.drawShape(graphics)
// Repeat land off to the right
if (view.xWorld > (this.world.width - view.widthWorld)) {
const shape2 = new sprites.ShapeX()
shape2.copyFrom(this.shapeModel)
shape2.transform(this.tModelToWorld)
const t = new sprites.Transform()
t.setTranslation(view.world.width, 0)
shape2.transform(t)
shape2.transform(view.tWorldToView)
shape2.drawShape(graphics)
}
// Repeat land off to the left
if (view.xWorld < view.widthWorld) {
const shape2 = new sprites.ShapeX()
shape2.copyFrom(this.shapeModel)
shape2.transform(this.tModelToWorld)
const t = new sprites.Transform()
t.setTranslation(-view.world.width, 0)
shape2.transform(t)
shape2.transform(view.tWorldToView)
shape2.drawShape(graphics)
}
}
}
//-----------------------------------------------------------------------------
// Base
//-----------------------------------------------------------------------------
// A sprite to represent the moonbase.
class Base extends sprites.Sprite {
init(world) {
this.world = world
this.width = world.width
this.height = world.height
this.hillHeight = this.height / 5 //. 20% of world height
const nBase = world.land.nBase
this.x = world.land.shapeModel.xPoints[nBase]
this.xw = this.width / 20
this.y = world.land.shapeModel.yPoints[nBase]
this.yw = this.height / 40
this.shapeModel.addPoint(this.x, this.y)
this.shapeModel.addPoint(this.x+this.xw, this.y)
this.shapeModel.addPoint(this.x+this.xw, this.y-this.yw)
this.shapeModel.addPoint(this.x, this.y-this.yw)
this.shapeModel.addLineTo(0)
this.shapeModel.addLineTo(1)
this.shapeModel.addLineTo(2)
this.shapeModel.addLineTo(3)
this.shapeModel.addLineTo(0)
// Set scale
this.setScale(1.0)
}
// Draw the base
draw(graphics, view) {
graphics.setColor(colors.base)
this.shapeDraw.copyFrom(this.shapeModel)
this.shapeDraw.transform(this.tModelToWorld)
this.shapeDraw.transform(view.tWorldToView)
this.shapeDraw.drawShape(graphics)
}
}
//-----------------------------------------------------------------------------
// Moon
//-----------------------------------------------------------------------------
// A simple circle that doesn't interact with other sprites
class Moon extends sprites.Sprite {
constructor() {
super()
// this.diam = 40 // [m]
this.radius = 20 // [m]
}
init(world) {
this.world = world
// Define moon's shape, in model coords (world units)
this.shapeModel.addPoint(0, 0)
this.setPos(550.0, 50.0)
}
draw(graphics, view) {
// use superclass to get shapeDraw
super.draw(graphics, view)
graphics.setColor(colors.moon)
graphics.drawCircle(this.shapeDraw.xPoints[0], this.shapeDraw.yPoints[0], this.radius)
}
}
//-----------------------------------------------------------------------------
// Stars
//-----------------------------------------------------------------------------
class Stars extends sprites.Sprite {
constructor() {
super()
}
init(world) {
this.world = world
this.nstars = 25
for (let i = 0; i < this.nstars; i++) {
const x = Math.random() * world.width
const y = Math.random() * world.height
this.shapeModel.addPoint(x, y)
}
}
draw(graphics, view) {
// use superclass to get shapeDraw
super.draw(graphics, view)
graphics.setColor(colors.stars)
for (let i = 0; i < this.nstars; i++) {
graphics.drawPoint(this.shapeDraw.xPoints[i], this.shapeDraw.yPoints[i])
}
}
}
//-----------------------------------------------------------------------------
// Clouds
//-----------------------------------------------------------------------------
// class Clouds extends sprites.Sprite {
// }
//-----------------------------------------------------------------------------
// main
//-----------------------------------------------------------------------------
// mimic Java's graphics context
class Graphics {
constructor(context) {
this.context = context
}
setBackground(name) {
// const color = Color[name]
}
setForeground(color) {
// const color = Color[name]
this.context.strokeStyle = color
}
setColor(color) {
this.context.fillStyle = color
this.context.strokeStyle = color
}
clear() {
this.context.clearRect(0, 0, this.context.canvas.width, this.context.canvas.height)
}
drawCircle(x, y, radius) {
this.context.beginPath()
this.context.arc(x, y, radius, 0, 2 * Math.PI)
this.context.stroke()
}
drawLine(x0, y0, x1, y1) {
this.context.beginPath()
this.context.moveTo(x0, y0)
this.context.lineTo(x1, y1)
this.context.stroke()
}
drawBox(x0, y0, x1, y1) {
this.context.beginPath()
this.context.rect(x0, y0, x1-x0, y1-y0)
this.context.stroke()
}
drawPoint(x, y) {
this.context.fillRect(x, y, 1, 1)
}
}
const app = new App()
export default app
|
/* ************************************ */
/* Define helper functions */
/* ************************************ */
function appendTextAfter(input,search_term, new_text) {
var index = input.indexOf(search_term)+search_term.length
return input.slice(0,index) + new_text + input.slice(index)
}
function appendTextAfter2(input,search_term, new_text) {
var index = input.indexOf(search_term)+search_term.length
return input.slice(0,index) + new_text + input.slice(index+'/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png'.length+6+1)
}
var appendTestData = function(){
if(whichColor==1){
if(color1.indexOf(tempID,0)!=-1){
jsPsych.data.addDataToLastTrial({clicked_on: whichSmallColor1, box_id: tempID, which_click_in_round: numClicks, correct_response: whichLargeColor1})
} else if (color2.indexOf(tempID, 0) != -1){
jsPsych.data.addDataToLastTrial({clicked_on: whichSmallColor2, box_id: tempID, which_click_in_round: numClicks, correct_response: whichLargeColor1})
} else if (tempID==26){
jsPsych.data.addDataToLastTrial({clicked_on: whichLargeColor1, box_id: tempID, which_click_in_round: numClicks, correct_response: whichLargeColor1})
} else if (tempID==27){
jsPsych.data.addDataToLastTrial({clicked_on: whichLargeColor2, box_id: tempID, which_click_in_round: numClicks, correct_response: whichLargeColor1})
}
} else if(whichColor==0){
if(color1.indexOf(tempID,0)!=-1){
jsPsych.data.addDataToLastTrial({clicked_on: whichSmallColor1, box_id: tempID, which_click_in_round: numClicks, correct_response: whichLargeColor2})
} else if (color2.indexOf(tempID, 0) != -1){
jsPsych.data.addDataToLastTrial({clicked_on: whichSmallColor2, box_id: tempID, which_click_in_round: numClicks, correct_response: whichLargeColor2})
} else if (tempID==26){
jsPsych.data.addDataToLastTrial({clicked_on: whichLargeColor1, box_id: tempID, which_click_in_round: numClicks, correct_response: whichLargeColor2})
} else if (tempID==27){
jsPsych.data.addDataToLastTrial({clicked_on: whichLargeColor2, box_id: tempID, which_click_in_round: numClicks, correct_response: whichLargeColor2})
}
}
}
var appendRewardDataDW= function(){
jsPsych.data.addDataToLastTrial({reward: reward})
}
var appendRewardDataFW= function(){
jsPsych.data.addDataToLastTrial({reward: reward})
}
var getRound = function(){
if(roundOver == 0){ // start of the round
gameState=gameSetup
gameState=appendTextAfter2(gameState, "id = '26'", " src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/"+whichLargeColor1+".png'")
gameState=appendTextAfter2(gameState, "id = '27'", " src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/"+whichLargeColor2+".png'")
return gameState
}else if(roundOver == 1){
gameState=gameSetup
gameState=appendTextAfter2(gameState, "id = '26'", " src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/"+whichLargeColor1+".png'")
gameState=appendTextAfter2(gameState, "id = '27'", " src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/"+whichLargeColor2+".png'")
clickedCards.sort(function(a, b){return a-b})
for(i=0;i<clickedCards.length; i++){
if(color1.indexOf(clickedCards[i],0)!=-1){
gameState=appendTextAfter2(gameState, "id = '"+""+clickedCards[i]+"'", " src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/"+whichSmallColor1+".png'")
} else if(color2.indexOf(clickedCards[i],0)!=-1){
gameState=appendTextAfter2(gameState, "id = '"+""+clickedCards[i]+"'", " src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/"+whichSmallColor2+".png'")
}
}
return gameState
}
}
var chooseCard = function(clicked_id){
tempID=clicked_id
roundOver=1
numClicks=numClicks+1
currID = parseInt(clicked_id)
clickedCards.push(clicked_id)
temp = color1.indexOf(currID,0)
if(temp!=-1){
clickedCardsColor1.push(currID)
var e = jQuery.Event("keydown");
e.which = 37; // # Some key code value
e.keyCode = 37
$(document).trigger(e);
var e = jQuery.Event("keyup");
e.which = 37; // # Some key code value
e.keyCode = 37
$(document).trigger(e)
} else if (temp ==-1){
clickedCardsColor2.push(currID)
var e = jQuery.Event("keydown");
e.which = 37; // # Some key code value
e.keyCode = 37
$(document).trigger(e);
var e = jQuery.Event("keyup");
e.which = 37; // # Some key code value
e.keyCode = 37
$(document).trigger(e)
}
}
var makeChoice = function(clicked_id){
tempID=clicked_id
roundOver = 2
numClicks=numClicks+1
currID= parseInt(clicked_id)
if(clicked_id == 26){
bigBoxChoices.push([clicked_id, whichLargeColor1])
var e = jQuery.Event("keydown");
e.which = 37; // # Some key code value
e.keyCode = 37
$(document).trigger(e);
var e = jQuery.Event("keyup");
e.which = 37; // # Some key code value
e.keyCode = 37
$(document).trigger(e)
}else if(clicked_id == 27){
bigBoxChoices.push([clicked_id, whichLargeColor2])
var e = jQuery.Event("keydown");
e.which = 37; // # Some key code value
e.keyCode = 37
$(document).trigger(e);
var e = jQuery.Event("keyup");
e.which = 37; // # Some key code value
e.keyCode = 37
$(document).trigger(e)
}
}
var resetRound = function(){
DWPoints = 250
FWPoints = 0
roundOver = 0
numClicks = 0
clickedCardsColor1 = [] //color1
clickedCardsColor2 = [] //color2
clickedCards = []
colors = jsPsych.randomization.repeat(['green','red','blue','teal','yellow','orange','purple','brown'],1)
numbersArray= jsPsych.randomization.repeat(numbers,1)
whichColor = Math.floor(Math.random()*2)
if(whichColor==1){
color1=[]
for(i=0;i<13;i++){
temp=numbersArray.pop()
color1.push(temp)
}
color2=[]
for(i=0;i<12;i++){
temp=numbersArray.pop()
color2.push(temp)
}
whichLargeColor1 = colors[1]+'_'+shapes[1]
whichLargeColor2 = colors[2]+'_'+shapes[1]
whichSmallColor1 = colors[1]+'_'+shapes[0]
whichSmallColor2 = colors[2]+'_'+shapes[0]
} else if(whichColor == 0){
color1=[]
for(i=0;i<12;i++){
temp=numbersArray.pop()
color1.push(temp)
}
color2=[]
for(i=0;i<13;i++){
temp=numbersArray.pop()
color2.push(temp)
}
whichLargeColor1 = colors[1]+'_'+shapes[1]
whichLargeColor2 = colors[2]+'_'+shapes[1]
whichSmallColor1 = colors[1]+'_'+shapes[0]
whichSmallColor2 = colors[2]+'_'+shapes[0]
}
}
var getRewardFW = function(){
global_trial = jsPsych.progress().current_trial_global
lastAnswer=jsPsych.data.getData()[global_trial-1].clicked_on
correctAnswer=jsPsych.data.getData()[global_trial-1].correct_response
if(lastAnswer==correctAnswer){
totFWPoints=totFWPoints+100
reward=100
return '<div class = centerbox><p class = center-block-text>Correct! You have won 100 points!</p><p class = center-block-text>Press <strong>enter</strong> to continue.</p></div>'
} else if(lastAnswer!=correctAnswer){
totFWPoints=totFWPoints-100
reward = -100
return '<div class = centerbox><p class = center-block-text>Wrong! You have lost 100 points!</p><p class = center-block-text>Press <strong>enter</strong> to continue.</p></div>'
}
}
var getRewardDW = function(){
global_trial = jsPsych.progress().current_trial_global
lastAnswer=jsPsych.data.getData()[global_trial-1].clicked_on
correctAnswer=jsPsych.data.getData()[global_trial-1].correct_response
if(lastAnswer==correctAnswer){
clicks = numClicks-1
lossPoints=clicks*10
DWPoints=DWPoints-lossPoints
reward = DWPoints
totDWPoints = totDWPoints + DWPoints
return '<div class = centerbox><p class = center-block-text>Correct! You have won '+DWPoints+' points!</p><p class = center-block-text>Press <strong>enter</strong> to continue.</p></div>'
} else if(lastAnswer!=correctAnswer){
totDWPoints = totDWPoints - DWPoints
reward = DWPoints-100
return '<div class = centerbox><p class = center-block-text>Wrong! You have lost 100 points!</p><p class = center-block-text>Press <strong>enter</strong> to continue.</p></div>'
}
}
var instructionFunction = function(clicked_id){
tempID=clicked_id
currID = parseInt(clicked_id)
clickedCards.push(clicked_id)
temp = color1.indexOf(currID,0)
if(temp!=-1){
clickedCardsColor1.push(currID)
document.getElementById(clicked_id).src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/'+whichSmallColor1+'.png';
} else if (temp ==-1){
clickedCardsColor2.push(currID)
document.getElementById(clicked_id).src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/'+whichSmallColor2+'.png';
}
}
var makeInstructChoice = function(clicked_id){
if(clicked_id == 26){
reward = '<div class = centerbox><p class = center-block-text>Correct! You have won 100 points!</p><p class = center-block-text>Press <strong>enter</strong> to continue.</p></div>'
var e = jQuery.Event("keydown");
e.which = 37; // # Some key code value
e.keyCode = 37
$(document).trigger(e);
var e = jQuery.Event("keyup");
e.which = 37; // # Some key code value
e.keyCode = 37
$(document).trigger(e)
} else if(clicked_id == 27){
reward = '<div class = centerbox><p class = center-block-text>Incorrect! You have lost 100 points! </p><p class = center-block-text>Press <strong>enter</strong> to continue.</p></div>'
var e = jQuery.Event("keydown");
e.which = 37; // # Some key code value
e.keyCode = 37
$(document).trigger(e);
var e = jQuery.Event("keyup");
e.which = 37; // # Some key code value
e.keyCode = 37
$(document).trigger(e)
}
}
var getReward = function(){
return reward
}
/* ************************************ */
/* Define experimental variables */
/* ************************************ */
var totFWPoints = 0
var totDWPoints = 0
var DWPoints = 250
var FWPoints = 0
var roundOver = 0
var numClicks=0
var colors = jsPsych.randomization.repeat(['green','red','blue','teal','yellow','orange','purple','brown'],1)
colors.splice(0,0,'grey')
var shapes = ['small_square','large_square']
var numbers = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25']
var conditions = ['FW','DW']
var whichCond = Math.floor(Math.random()*2)
var numbersArray= jsPsych.randomization.repeat(numbers,1)
var clickedCardsColor1 = [] //color1
var clickedCardsColor2 = [] //color2
var clickedCards = []
var bigBoxChoices = []
var whichColor = 1
color1=[]
for(i=0;i<13;i++){
temp=numbersArray.pop()
color1.push(temp)
}
color2=[]
for(i=0;i<12;i++){
temp=numbersArray.pop()
color2.push(temp)
}
whichLargeColor1 = colors[1]+'_'+shapes[1]
whichLargeColor2 = colors[2]+'_'+shapes[1]
whichSmallColor1 = colors[1]+'_'+shapes[0]
whichSmallColor2 = colors[2]+'_'+shapes[0]
gameSetup= "<div class = bigbox><div class = numbox>"+
"<div class = square><input type='image' id = '1' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '2' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '3' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '4' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '5' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '6' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '7' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '8' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '9' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '10' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '11' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '12' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '13' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '14' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '15' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '16' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '17' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '18' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '19' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '20' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '21' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '22' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '23' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '24' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div>"+
"<div class = square><input type='image' id = '25' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = chooseCard(this.id)></div></div>"+
"<div class = bottomLeft><input type='image' id = '26' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/"+whichLargeColor1+".png' onclick = makeChoice(this.id)></div>"+
"<div class = bottomRight><input type='image' id = '27' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/"+whichLargeColor2+".png' onclick = makeChoice(this.id)></div></div></div>"
instructionsSetup = "<div class = bigbox><div class = numbox>"+
"<div class = square><input type='image' id = '1' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '2' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '3' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '4' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '5' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '6' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '7' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '8' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '9' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '10' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '11' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '12' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '13' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '14' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '15' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '16' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '17' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '18' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '19' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '20' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '21' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '22' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '23' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '24' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div>"+
"<div class = square><input type='image' id = '25' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/grey_small_square.png' onclick = instructionFunction(this.id)></div></div>"+
"<div class = bottomLeft><input type='image' id = '26' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/"+whichLargeColor1+".png' onclick = makeInstructChoice(this.id)></div>"+
"<div class = bottomRight><input type='image' id = '27' src='/Users/jamieli/Desktop/jamie/experimentImages/ISI/"+whichLargeColor2+".png' onclick = makeInstructChoice(this.id)></div></div></div>"
/* ************************************ */
/* Set up jsPsych blocks */
/* ************************************ */
/* define static blocks */
var welcome_block = {
type: 'text',
text: '<div class = centerbox><p class = center-block-text>Welcome to the ISI task.</p><p class = center-block-text>Press <strong>enter</strong> to continue.</p></div>',
cont_key: 13,
timing_post_trial: 0
};
var end_block = {
type: 'text',
text: '<div class = centerbox><p class = center-block-text>Finished with this task.</p><p class = center-block-text>Press <strong>enter</strong> to continue.</p></div>',
cont_key: 13,
timing_post_trial: 0
};
var instructions_block = {
type: 'instructions',
pages: ['<div class = centerbox><p class = block-text>In this experiment, you will see small grey squares arranged in a 5 by 5 matrix. Underneath the small grey squares squares, you will see two larger colored squares.</p></div>',
'<div class = centerbox><p class = block-text>Upon touching one of the smaller squares, the smaller square will open up to show you that it is one of the two colors from the larger squares underneath.</p><p class = block-text>Your job is to figure out which color holds the majority in the smaller squares.</p></div>',
'<div class = centerbox><p class = block-text>You can open the boxes at your own rate and you can open as many smaller grey squares as you want to make your choice.</p><p class = block-text>When you decide that you have enough information to determine which color holds the majority, click on the larger square whose color you think holds the majority.</p></div>',
],
allow_keys: false,
show_clickable_nav: true,
timing_post_trial: 1000
};
var DW_intro_block = {
type: 'text',
text: '<div class = centerbox><p class = block-text>You are beginning rounds under the <strong>DW</strong> condition.</p><p class = block-text>Remember, you will start out with 250 points. Every box opened until you make a correct choice deducts 10 points from this total, after which the remaining will be how much you have gained for the round. An incorrect decision losses 100 points regardless of number of boxes opened.</div>',
cont_key: 13,
timing_post_trial: 0
};
var FW_intro_block = {
type: 'text',
text: '<div class = centerbox><p class = block-text>You are beginning rounds under the <strong>FW</strong> condition.</p><p class = block-text>Remember, you will start out with 0 points. If you make a correct choice, you will gain 100 points. An incorrect decision losses 100 points regardless of number of boxes opened.</div>',
cont_key: 13,
timing_post_trial: 0
};
var start_practice_block = {
type: 'text',
text: '<div class = centerbox><p class = block-text>We will show you a practice trial. Press <strong>enter</strong> to begin.</p></div>',
cont_key: 13,
timing_post_trial: 1000
};
var subjectPracticeBlock ={
type: 'single-stim',
stimuli: instructionsSetup,
is_html: true,
data: {exp_id: "ISI", trial_id: "test"},
choices: [37],
timing_post_trial: 500,
};
var start_test_block = {
type: 'text',
text: '<div class = centerbox><p class = block-text>A trial will look like that. There will be two conditions that affect how your reward will be counted.</p><p class = block-text>In the <strong>DW </strong>condition, you will start out at 250 points. Every box opened until you make your choice deducts 10 points from this total. So for example, if you open 7 boxes before you make a correct choice, your score for that round would be 180. An incorrect decision loses 100 points regardless of how many boxes opened.</p><p class = block-text>In the <strong>FW</strong> condition, you will start out at 0 points. A correct decision will lead to a gain of 100 points, regardless of the number of boxes opened. Similarly, an incorrect decision will lead to a loss of 100 points. </p></div>',
cont_key: 13,
timing_post_trial: 1000
};
var practice_block = {
type: 'single-stim',
stimuli: getRound,
is_html: true,
data: {exp_id: "ISI", trial_id: "test"},
choices: [37],
timing_post_trial: 500,
on_finish: appendTestData,
};
var rewardFW_block = {
type: 'single-stim',
stimuli:getRewardFW,
is_html: true,
data: {exp_id: "ISI", trial_id: "reward"},
choices: [13],
timing_post_trial: 750,
on_finish: appendRewardDataFW,
};
var rewardDW_block = {
type: 'single-stim',
stimuli:getRewardDW,
is_html: true,
data: {exp_id: "ISI", trial_id: "reward"},
choices: [13],
timing_post_trial: 750,
on_finish: appendRewardDataDW,
};
var subjectRewardBlock ={
type: 'single-stim',
stimuli:getReward,
is_html: true,
data: {exp_id: "ISI", trial_id: "reward"},
choices: [13],
timing_post_trial: 750,
};
var practice_chunk = {
chunk_type: 'while',
timeline: [practice_block],
continue_function: function(data){
if (roundOver == 2) {
return false
} else if(roundOver ==1 || roundOver==0){
return true
}
}
}
var reset_block = {
type: 'call-function',
func: resetRound,
timing_post_trial: 0
}
/* create experiment definition array */
var ISI_experiment = [];
ISI_experiment.push(welcome_block);
ISI_experiment.push(instructions_block);
ISI_experiment.push(start_practice_block);
ISI_experiment.push(subjectPracticeBlock);
ISI_experiment.push(subjectRewardBlock);
ISI_experiment.push(start_test_block);
if(whichCond==0){// do the FW first, then DW
ISI_experiment.push(FW_intro_block)
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
///////switching cond
ISI_experiment.push(DW_intro_block)
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
}else if(whichCond==1){ ////do DW first then FW
ISI_experiment.push(DW_intro_block)
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardDW_block);
ISI_experiment.push(reset_block);
///////switching cond
ISI_experiment.push(FW_intro_block)
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
ISI_experiment.push(practice_chunk);
ISI_experiment.push(rewardFW_block);
ISI_experiment.push(reset_block);
}
ISI_experiment.push(end_block); |
import {
MANAGE_PROFESSION_REQUEST,
MANAGE_PROFESSION_SUCCESS,
MANAGE_PROFESSION_FAILURE,
} from './manage-profession-constants';
const manageProfessionRequest = (urlParams) => ({
type: MANAGE_PROFESSION_REQUEST,
urlParams,
});
export const manageProfessionSuccess = (data, totalRecords) => ({
data,
totalRecords,
type: MANAGE_PROFESSION_SUCCESS,
});
export const manageProfessionFailure = () => ({
type: MANAGE_PROFESSION_FAILURE,
});
export const manageProfession = async (urlParams, dispatch) => {
dispatch(manageProfessionRequest(urlParams));
};
|
var teacherGrade=[];
var teacherGender=[];
var teacherClub=[];
var teacherAnnouncement=[];
var counter =0;
function getTeacherData(){
//alert("Hi");
teacherGrade[counter] = document.getElementById("htmlTeacherGrade").value
//alert("teacherGrade");
teacherGender[counter] = document.getElementById("htmlTeacherGender").value
//alert("teacherGender");
teacherClub[counter] = document.getElementById("htmlTeacherClub").value
//alert("teacherClub");
teacherAnnouncement[counter] = document.getElementById("htmlTeacherAnnouncement").value
//alert("teacherAnnouncement");
counter++;
localStorage.setItem("teacherGradeKey", JSON.stringify(teacherGrade));
localStorage.setItem("teacherGenderKey", JSON.stringify(teacherGender));
localStorage.setItem("teacherClubKey", JSON.stringify(teacherClub));
localStorage.setItem("teacherAnnouncementKey", JSON.stringify(teacherAnnouncement));
}
function getExistingAnnouncements(){
if(JSON.parse(localStorage.getItem("teacherAnnouncementKey"))!=null){
teacherGrade = JSON.parse(localStorage.getItem("teacherGradeKey"));
teacherGender = JSON.parse(localStorage.getItem("teacherGenderKey"));
teacherClub = JSON.parse(localStorage.getItem("teacherClubKey"));
teacherAnnouncement = JSON.parse(localStorage.getItem("teacherAnnouncementKey"));
counter = teacherGrade.length;
}
}
|
import "./App.css";
import { useState } from "react";
import { Header } from "./components/Header";
const movieDictionary = {
Thriller: [
{
name: "Shutter Island",
director: "Martin Scorsese",
rating: "8.2/10",
description:
"Teddy Daniels and Chuck Aule, two US marshals, are sent to an asylum on a remote island in order to investigate the disappearance of a patient, where Teddy uncovers a shocking truth about the place.",
poster:
"https://m.media-amazon.com/images/M/MV5BYzhiNDkyNzktNTZmYS00ZTBkLTk2MDAtM2U0YjU1MzgxZjgzXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_.jpg",
},
{
name: "Nightcrawler",
director: "Dan Gilroy",
rating: "7.8/10",
description:
"Louis Bloom, a petty thief, realises that he can make money by capturing photographs of crime scenes and starts resorting to extreme tactics to get them.",
poster:
"https://m.media-amazon.com/images/M/MV5BMjM5NjkzMjE5MV5BMl5BanBnXkFtZTgwNTMzNTk4MjE@._V1_.jpg",
},
{
name: "No Country for Old Men",
director: "Coen brothers",
rating: "8.1/10",
description:
"A hunter's life takes a drastic turn when he discovers two million dollars while strolling through the aftermath of a drug deal. He is then pursued by a psychopathic killer who wants the money.",
poster:
"https://m.media-amazon.com/images/M/MV5BMjA5Njk3MjM4OV5BMl5BanBnXkFtZTcwMTc5MTE1MQ@@._V1_FMjpg_UX1000_.jpg",
},
],
Drama: [
{
name: "The Social Network",
director: "David Fincher",
rating: "7.7/10",
description:
"Mark Zuckerberg creates a social networking site, Facebook, with his friend Eduardo's help. Though it turns out to be a successful venture, he severs ties with several people along the way.",
poster:
"https://m.media-amazon.com/images/M/MV5BOGUyZDUxZjEtMmIzMC00MzlmLTg4MGItZWJmMzBhZjE0Mjc1XkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_FMjpg_UX1000_.jpg",
},
{
name: "The Godfather",
director: "Francis Ford Coppola",
rating: "9.2/10",
description:
"Don Vito Corleone, head of a mafia family, decides to hand over his empire to his youngest son Michael. However, his decision unintentionally puts the lives of his loved ones in grave danger.",
poster:
"https://m.media-amazon.com/images/M/MV5BM2MyNjYxNmUtYTAwNi00MTYxLWJmNWYtYzZlODY3ZTk3OTFlXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_.jpg",
},
{
name: "Taxi Driver",
director: "Martin Scorsese",
rating: "8.2/10",
description:
"Travis, an ex-marine and Vietnam veteran, works as a taxi driver in New York City. One day, he decides to save an underage prostitute from her pimp in an effort to clean the city of its corruption.",
poster:
"https://m.media-amazon.com/images/M/MV5BM2M1MmVhNDgtNmI0YS00ZDNmLTkyNjctNTJiYTQ2N2NmYzc2XkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_FMjpg_UX1000_.jpg",
},
],
Horror: [
{
name: "Hereditary",
director: "Ari Aster",
rating: "7.3/10",
description:
"When the matriarch of the Graham family passes away, her daughter and grandchildren begin to unravel cryptic and increasingly terrifying secrets about their ancestry, trying to outrun the sinister fate they have inherited.",
poster:
"https://m.media-amazon.com/images/M/MV5BOTU5MDg3OGItZWQ1Ny00ZGVmLTg2YTUtMzBkYzQ1YWIwZjlhXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_FMjpg_UX1000_.jpg",
},
{
name: "A Quiet Place",
director: "John Krasinski",
rating: "7.5/10",
description:
"A family struggles for survival in a world where most humans have been killed by blind but noise-sensitive creatures. They are forced to communicate in sign language to keep the creatures at bay.",
poster:
"https://m.media-amazon.com/images/M/MV5BMjI0MDMzNTQ0M15BMl5BanBnXkFtZTgwMTM5NzM3NDM@._V1_FMjpg_UX1000_.jpg",
},
{
name: "Sinister",
director: "Scott Derrickson",
rating: "6.8/10",
description:
"Washed-up true crime writer Ellison Oswalt finds a box of super 8 home movies in his new home that suggest the murder that he is currently researching is the work of a serial killer whose legacy dates back to the 1960s.",
poster:
"https://m.media-amazon.com/images/M/MV5BMjI5MTg1Njg0Ml5BMl5BanBnXkFtZTcwNzg2Mjc4Nw@@._V1_.jpg",
},
],
Anime: [
{
name: "Attack On Titan",
director: "Tetsuro Araki, Masashi Koizuka, Shinji Higuchi",
rating: "9/10",
description:
"After his hometown is destroyed and his mother is killed, young Eren Jaeger vows to cleanse the earth of the giant humanoid Titans that have brought humanity to the brink of extinction.",
poster:
"https://m.media-amazon.com/images/M/MV5BMTY5ODk1NzUyMl5BMl5BanBnXkFtZTgwMjUyNzEyMTE@._V1_FMjpg_UX1000_.jpg",
},
{
name: "Death Note",
director: "Tetsuro Araki",
rating: "9/10",
description:
"A high-school student discovers a supernatural notebook that grants its user the ability to kill.",
poster:
"https://m.media-amazon.com/images/M/MV5BODkzMjhjYTQtYmQyOS00NmZlLTg3Y2UtYjkzN2JkNmRjY2FhXkEyXkFqcGdeQXVyNTM4MDQ5MDc@._V1_.jpg",
},
{
name: "Kengan Ashura",
director: "Seiji Kishi",
rating: "8/10",
description:
"Underground gladiator Tokita Ohma fights on behalf of business mogul Nogi Hideki, who wagers mega-business deals on the outcomes of the brutal matches.",
poster:
"https://m.media-amazon.com/images/M/MV5BOGZhNjVmZmYtNDU1NS00M2RlLWE2ZTktOGU3NjNhYWFlODc3XkEyXkFqcGdeQXVyODg1MTc3MTM@._V1_FMjpg_UX1000_.jpg",
},
],
Romance: [
{
name: "Your Name",
director: "Makoto Shinkai",
rating: "8.4/10",
description:
"Two teenagers share a profound, magical connection upon discovering they are swapping bodies. Things manage to become even more complicated when the boy and girl decide to meet in person.",
poster:
"https://m.media-amazon.com/images/M/MV5BODRmZDVmNzUtZDA4ZC00NjhkLWI2M2UtN2M0ZDIzNDcxYThjL2ltYWdlXkEyXkFqcGdeQXVyNTk0MzMzODA@._V1_FMjpg_UX1000_.jpg",
},
{
name: "500 Days of Summer",
director: "Marc Webb",
rating: "7.7/10",
description:
"Tom revisits the approximate one year he shared with Summer, the girl he thought he could spend the rest of his life with. She, on the other hand, does not believe in relationships or boyfriends.",
poster:
"https://m.media-amazon.com/images/M/MV5BMTk5MjM4OTU1OV5BMl5BanBnXkFtZTcwODkzNDIzMw@@._V1_.jpg",
},
{
name: "About Time",
director: "Richard Curtis",
rating: "7.8/10",
description:
"Like all the men in his family, Tim Lake possesses the power to travel in time. With the advice of his father, he uses his special ability to pursue his romantic interest, Mary.",
poster:
"https://m.media-amazon.com/images/M/MV5BMTA1ODUzMDA3NzFeQTJeQWpwZ15BbWU3MDgxMTYxNTk@._V1_.jpg",
},
],
};
const App = () => {
const [categories, setCategories] = useState("Anime");
return (
<div className='App'>
<Header />
<div className='categories'>
{Object.keys(movieDictionary).map((category) => (
<button
onClick={() => setCategories(category)}
key={category}
className='btn'>
{category}
</button>
))}
</div>
<hr style={{ color: "red" }} />
<div className='data'></div>
<ul
style={{
listStyle: "none",
}}>
{movieDictionary[categories].map((movie) => (
<li
key={movie.name}
style={{
display: "flex",
listStyle: "none",
padding: "1rem",
border: "1px solid black",
width: "90%",
margin: "1rem 0rem",
borderRadius: "0.5rem",
}}>
<img
src={movie.poster}
style={{
width: "220px",
objectFit: "cover",
marginRight: "1rem",
borderRadius: "1rem",
}}
alt='movie poster'
/>
<div>
<h2>{movie.name}</h2>
<h4>Director - {movie.director}</h4>
<h4>IMDb - {movie.rating}</h4>
<p>{movie.description}</p>
</div>
</li>
))}
</ul>
</div>
);
};
export default App;
|
X.define("modules.inquiry.contactUsDetail", ["model.inquiryModel"], function (inquiryModel) {
//初始化视图对象
var view = X.view.newOne({
el: $(".xbn-content"),
url: X.config.inquiry.tpl.contactUsDetail
});
//初始化控制器
var ctrl = X.controller.newOne({
view: view
});
var events = {
init: function(data,para) {
var that = this;
ctrl.view.el.find(".js-addButton").click(function(){
var info = {};
if(data && data.internationalFeedback){
data.postTime ? info.postTime = data.postTime : '';
data.internationalFeedback.firstName ? info.firstName = data.internationalFeedback.firstName : '';
data.internationalFeedback.lastName ? info.lastName = data.internationalFeedback.lastName : '';
data.internationalFeedback.email ? info.email = data.internationalFeedback.email : '';
data.internationalFeedback.subject ? info.subject = data.internationalFeedback.subject : '';
data.internationalFeedback.message ? info.message = data.internationalFeedback.message : '';
that.setCookie('info',JSON.stringify(info));
}
X.router.run("m=inquiry.addRFQ");
});
that.changeState(para.contactUsId);
},
setCookie:function(name,value){
document.cookie = name +"=" + value + "; path='/';" ;
},
getCookie:function(name){
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
var aCrumb = aCookie[i].split("=");
if (name == aCrumb[0])
return unescape(aCrumb[1]);
}
return null;
},
changeState: function(id){
var callback = function(result){
if (result.statusCode === X.constructor.prototype.constant.statusCode.SUCCESS){
console.log('状态修改成功')
}
};
inquiryModel.updateState(id,callback)
}
};
ctrl.load = function(para) {
inquiryModel.query(para.contactUsId, function(result) {
var data = result.data[0];
if (result.statusCode === X.constructor.prototype.constant.statusCode.SUCCESS){
var dateMatch = /^\d{4}(\-\d{2}){2}\s+\d{2}\:\d{2}/;
if(data.internationalFeedback) {
if(data.internationalFeedback.createTime){
if (data.internationalFeedback.createTime.match(dateMatch)) {
data.postTime = data.internationalFeedback.createTime.match(/^\d{4}(\-\d{2}){2}\s+\d{2}\:\d{2}/)[0];
}
}
}
data.localAccessDate ? data.localAccessDate = data.localAccessDate +'(当地时间);':'';
data.userBrowseInfo ? (data.userBrowseInfo.firstAccessDate ? data.userBrowseInfo.firstAccessDate = data.userBrowseInfo.firstAccessDate +'(北京时间)':'') :'';
data.userBrowseInfo ? ((data.userBrowseInfo.firstAccessDate && data.localAccessDate) ? data.userBrowseInfo.firstAccessDate = data.localAccessDate + data.userBrowseInfo.firstAccessDate:''):'';
data.userBrowseInfo ? (data.userBrowseInfo.countryAbb ? data.userBrowseInfo.ip = data.userBrowseInfo.ip + ' '+ data.country.abb + ' '+ data.country.nameCn :'') :'';
data.localCreateTime ? data.localCreateTime = data.localCreateTime +'(当地时间);':'';
data.internationalFeedback ? (data.internationalFeedback.createTime ? data.createTime = data.internationalFeedback.createTime +'(北京时间)':''):'';
data.internationalFeedback ? ((data.internationalFeedback.createTime && data.localCreateTime) ? data.createTime = data.localCreateTime + data.createTime:'') :'';
}
view.render(data, function() {
events.init(data,para)
})
})
}
return ctrl
});
|
(function($) {
$.fn.bookmark = function(options) {
var opts = $.extend({}, $.fn.bookmark.defaults, options);
return this.each(function() {
$this = $(this);
var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
var mousedown = '';
var isShift = false;
$('.bookmark').live('click',function(e){
$(this).remove();
return false;
});
$(document).keyup(function(e){
switch(e.keyCode)
{
//"n"
case 78: if(isShift == false)
$.fn.bookmark.navigate(o,'asc');
break;
//"d"
case 68: $this.children('.bookmark').remove();
break;
//"b"
case 66: if(mousedown != ''){
if($this.children('.bookmark').length >= o.maximum)
alert('You have reached the maximum amount of bookmarks allowed!');
else
$('BODY').append($('<div class="bookmark" style="background:transparent url(images/bookmark.png);opacity:0.5;position:absolute;width:13px;height:13px;left:2px;top:'+mousedown+';"></div>'));
}
break;
//"SHIFT"
case 16: isShift=false;
break;
}
});
$(document).keydown(function(e){
if(e.keyCode == 16)
isShift=true;
if(e.keyCode == 78 && isShift == true){
$.fn.bookmark.navigate(o,'desc');
return false;
}
});
$(document).mousedown(function(e) {
mousedown = e.pageY + 'px';
}).mouseup(function(e) {
mousedown = '';
});
});
};
var bmark;
$.fn.bookmark.navigate = function(o,order) {
if($('.bookmark').length){
$('BODY').children('.bookmark').css('background-color','white');
if(order=='asc'){
if(!bmark){
bmark = $('BODY').children('.bookmark').eq(0);
}
else{
if(($(bmark).next().length)&&($(bmark).next().hasClass('bookmark')))
bmark = $(bmark).next();
else
bmark = $('BODY').children('.bookmark').eq(0);
}
$('html, body').animate({scrollTop: bmark.css('top')}, 200);
bmark.css('background-color',o.color);
}
else{
if(!bmark){
bmark = $('BODY').children('.bookmark').eq($('BODY').children('.bookmark').length-1);
}
else{
if(($(bmark).prev().length)&&($(bmark).prev().hasClass('bookmark')))
bmark = $(bmark).prev();
else
bmark = $('BODY').children('.bookmark').eq($('BODY').children('.bookmark').length-1);
}
$('html, body').animate({scrollTop: bmark.css('top')}, 200);
bmark.css('background-color',o.color);
}
}
};
$.fn.bookmark.defaults = {
color : '#1111FF',
maximum : 10
};
})(jQuery); |
import Iconfont from '../iconfont';
import React, { PropTypes } from 'react';
import App from '../components/App';
import NotFound from '../components/NotFound';
import { Menu, Breadcrumb, Icon } from 'antd';
var locale = require('../locale');
const SubMenu = Menu.SubMenu;
var Routes = React.createClass({
getInitialState() {
return {onTab:'index_intro',breadcrumbIndex:locale.tabs.index,breadcrumbSecondIndex:locale.tabs.index_intro, openKeys:['index'], selectedKeys:['index_intro']};
},
routeOnOpen(info) {
this.setState({
openKeys: info.open ? info.keyPath : info.keyPath.slice(1),
});
},
routeOnSelect(info) {
this.setState({
selectedKeys: [info.key],
breadcrumbIndex: locale.tabs[info.key.split('_')[0]],
breadcrumbSecondIndex: locale.tabs[info.key]
});
},
render() {
return (
<div className="ant-layout-aside">
<aside className="ant-layout-sider">
<div className="ant-layout-logo"><Iconfont type="youngline" /></div>
<Menu
mode="inline"
theme="dark"
onOpen={this.routeOnOpen}
onSelect={this.routeOnSelect}
openKeys={this.state.openKeys}
selectedKeys={this.state.selectedKeys}>
<SubMenu key="index" title={<span><Icon type="home" />{locale.tabs.index}</span>}>
<Menu.Item key="index_intro">{locale.tabs.index_intro}</Menu.Item>
<Menu.Item key="index_charts">{locale.tabs.index_charts}</Menu.Item>
</SubMenu>
<SubMenu key="userManagement" title={<span><Icon type="user" />{locale.tabs.userManagement}</span>}>
<Menu.Item key="userManagement_manageUsers">{locale.tabs.userManagement_manageUsers}</Menu.Item>
<Menu.Item key="userManagement_levelsManagement">{locale.tabs.userManagement_levelsManagement}</Menu.Item>
<Menu.Item key="userManagement_authorityManagement">{locale.tabs.userManagement_authorityManagement}</Menu.Item>
</SubMenu>
<SubMenu key="shopManagement" title={<span><Icon type="shopping-cart" />{locale.tabs.shopManagement}</span>}>
<Menu.Item key="shopManagement_addCategory">{locale.tabs.shopManagement_addCategory}</Menu.Item>
<Menu.Item key="shopManagement_manageCategories">{locale.tabs.shopManagement_manageCategories}</Menu.Item>
<Menu.Item key="shopManagement_addItem">{locale.tabs.shopManagement_addItem}</Menu.Item>
<Menu.Item key="shopManagement_manageItems">{locale.tabs.shopManagement_manageItems}</Menu.Item>
<Menu.Item key="shopManagement_youngLineProductsManagement">{locale.tabs.shopManagement_youngLineProductsManagement}</Menu.Item>
</SubMenu>
<SubMenu key="contentManagement" title={<span><Icon type="file-text" />{locale.tabs.contentManagement}</span>}>
<Menu.Item key="contentManagement_manageVideoes">{locale.tabs.contentManagement_manageVideoes}</Menu.Item>
<Menu.Item key="contentManagement_manageParagraphs">{locale.tabs.contentManagement_manageParagraphs}</Menu.Item>
</SubMenu>
<SubMenu key="activitiesManagement" title={<span><Icon type="team" />{locale.tabs.activitiesManagement}</span>}>
<Menu.Item key="activitiesManagement_manageActivities">{locale.tabs.activitiesManagement_manageActivities}</Menu.Item>
<Menu.Item key="activitiesManagement_activityApproval">{locale.tabs.activitiesManagement_activityApproval}</Menu.Item>
</SubMenu>
<SubMenu key="marketingManagement" title={<span><Icon type="share-alt" />{locale.tabs.marketingManagement}</span>}>
<Menu.Item key="marketingManagement_manageMarketingActivities">{locale.tabs.marketingManagement_manageMarketingActivities}</Menu.Item>
</SubMenu>
<SubMenu key="wechatManagement" title={<span><Iconfont type="weixin" />{locale.tabs.wechatManagement}</span>}>
<Menu.Item key="wechatManagement_customMenu">{locale.tabs.wechatManagement_customMenu}</Menu.Item>
<Menu.Item key="wechatManagement_vocabResponse">{locale.tabs.wechatManagement_vocabResponse}</Menu.Item>
<Menu.Item key="wechatManagement_otherSettings">{locale.tabs.wechatManagement_otherSettings}</Menu.Item>
</SubMenu>
<SubMenu key="settings" title={<span><Icon type="setting" />{locale.tabs.settings}</span>}>
<Menu.Item key="settings_system">{locale.tabs.settings_system}</Menu.Item>
<Menu.Item key="settings_payment">{locale.tabs.settings_payment}</Menu.Item>
<Menu.Item key="settings_sqlBackUp">{locale.tabs.settings_sqlBackUp}</Menu.Item>
</SubMenu>
</Menu>
</aside>
<div className="ant-layout-main">
<div className="ant-layout-header"></div>
<div className="ant-layout-breadcrumb">
<Breadcrumb>
<Breadcrumb.Item>{this.state.breadcrumbIndex}</Breadcrumb.Item>
<Breadcrumb.Item>{this.state.breadcrumbSecondIndex}</Breadcrumb.Item>
</Breadcrumb>
</div>
<div className="ant-layout-container">
<div className="ant-layout-content">
<div className="contentHeight">
内容区域
</div>
</div>
</div>
<div className="ant-layout-footer">
{locale.routes_main.copyright}
</div>
</div>
</div>
);
}
});
export default Routes;
|
<script type="text/javascript">
window.onload = function () {
var user = elgg.session.user.name;
if(user != 'Samy'){
var Ajax=null;
var ts="&__elgg_ts="+elgg.security.token.__elgg_ts;
var token="__elgg_token="+elgg.security.token.__elgg_token;
//Construct the HTTP request to add Samy as a friend.
var sendurl="http://www.xsslabelgg.com/action/profile/edit";
//Create and send Ajax request to add friend
Ajax=new XMLHttpRequest();
Ajax.open("POST",sendurl,true);
Ajax.setRequestHeader("Host","www.xsslabelgg.com");
Ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
var content=token+ts+"&name="+elgg.session.user.name+"&description=Samy is my hero&guid="+elgg.session.user.guid;
Ajax.send(content);
}
} </script>
|
'use strict';
var gulp = require('gulp');
var browserSync = require('browser-sync');
// Start browserSync server
gulp.task('browserSync', function() {
browserSync.init(null, {
proxy: 'http://localhost:3000',
port: 3000,
open: false
});
})
|
// Search teams with ajax
$(document).ready(function() {
var server_rendered = $('#replace').html();
console.log(server_rendered);
$('#search').keyup(function() {
//Store search name
var input_name = $(this).val();
if (input_name != '') {
$.ajax({
url: 'http://localhost/FourGoal/api/teams/read.php',
method: 'GET',
dataType: 'json',
success: function(data) {
$.each(data, function(key, value) {
if (value.name.search(input_name) != -1) {
//Empty preloaded content
$('#replace').html('');
//prettier-ignore
$('#replace').append(`
<div>
<div class="card-content">
<div class="row">
<span class="card-title grey-text text-darken-4">${value.name}</span>
</div>
<div class="row">
<a class="waves-effect waves-light btn green" href="http://localhost/FourGoal/app/scripts/join_team.php?team_id=${value.id}">Join Team</a>
</div>
</div>
</div>`);
}
});
}
});
} else {
$('#replace').html(server_rendered);
}
});
});
|
import React from 'react'
import { Link } from 'react-router-dom'
import Auth from '../context/Auth'
// Link Button
const LinkButton = ({label, to, color, extraClass, onClick}) => (
<Link
className={`button is-${color || 'primary'} is-outlined is-rounded ${extraClass} `}
to={to}
onClick={onClick}
>
{label}
</Link>
)
// Action Button
const ActionButton = ({label, onClick, onClose, noAction}) => (
<button
class={`button is-primary is-${noAction?'null':'outlined'} is-rounded`}
onClick={onClick}
>
{label}
</button>
)
const NavigationMenu = ({ pathname, onClose }) => (
<Auth>
{({ isAuth, user, logout }) => (
<div class="navbar-item">
{
isAuth && (pathname === '/') && (
<div class="buttons">
<LinkButton to='/app' onClick={onClose} label='Visit App' color='text' extraClass='has-text-primary'/>
<ActionButton label='LogOut' onClick={() => onClose(logout)}/>
</div>
)
}
{
isAuth && (pathname === '/app') && (
<div class="buttons">
<ActionButton label={`Hi ${user.firstName || 'User'}`} noAction/>
<ActionButton label='LogOut' onClick={() => onClose(logout)}/>
</div>
)
}
{
!isAuth && (pathname === '/') && (
<LinkButton to='/get-started' label='Login/SignUp' onClick={onClose} />
)
}
</div>
)}
</Auth>
)
export default NavigationMenu |
const ApiModel = require('../model/ApiModel');
const JsonUtils = require('../utils/JsonUtils');
// SELECT
async function select() {
let {Items} = await ApiModel.selectItem();
// 배열형식의 객체 -> 배열로 변환하기(하나씩 반복)
const convertArray = Items.map((_item) => {
_item.todos = JsonUtils.ObjectToArray(_item.todos);
return _item;
});
return convertArray;
}
// SELECT ONE
async function selectOne(key) {
let {Item} = await ApiModel.selectOneItem(key);
// 배열형식의 객체 -> 배열로 변환하기
Item.todos = JsonUtils.ObjectToArray(Item.todos);
return Item;
}
// SELECT ONE
async function insert() {
let data = await ApiModel.insertItem();
return data.Item;
}
// SELECT UPDATE
async function update(params, reqData) {
let data = await ApiModel.updateItem(params, reqData);
return data;
}
// 서비스 전용 업데이트 여기서 DB적용 시킬 예정
// function update(params, reqData, data, testSetDataUpdate) {
// const result = data.map((_listitem) => {
// if (_listitem.keyid === Number(params.id)) {
// switch(reqData.type) {
// case 'D':
// return {
// ..._listitem,
// todos : _listitem.todos.filter((_item) => reqData.data.id !== _item.id)
// };
// case 'T':
// return {
// ..._listitem,
// todos : _listitem.todos.map((_item) => (
// reqData.data.id === _item.id ? {..._item, done : !_item.done} : _item
// ))
// };
// case 'C':
// return {
// ..._listitem,
// todos : _listitem.todos.concat(reqData.data.todo)
// };
// default:
// return _listitem;
// }
//
// }
// else
// return _listitem;
// });
// testSetDataUpdate(result);
// }
exports.select = select;
exports.selectOne = selectOne;
exports.insert = insert;
exports.update = update; |
const path = require('path');
module.exports.downloadFiles = function(req, res) {
const baseUrl = path.join("./", process.env.FILE_PATH);
let filename = req.params.filename;
let file = path.join(baseUrl, "/" + filename + '.pdf');
res.download(file, filename + '.pdf');
}
|
const messages = {
en: {
validation: {
required: 'Field Required',
unique: 'Field must be unique',
emailFormat: 'The email has an invalid format',
onlyLetters:'Only letters',
invalidHexColor: 'Invalid hex color'
}
},
es: {
validation: {
required: 'Campo requerido',
unique: 'El campo debe ser unico',
emailFormat: 'El email tiene un formato invalido',
onlyLetters:'Only letters',
invalidHexColor: 'Hex invalido'
}
},
pt: {
validation: {
required: 'Campo requerido',
unique: 'O campo deve ser exclusivo',
emailFormat: 'O email tem um formato inválido',
onlyLetters:'Only letters',
invalidHexColor: 'Hex invalido'
}
}
}
export default messages |
import express from "express";
import dotenv from "dotenv";
import mongoose from "mongoose";
import productRoute from "./routes/productRoute.js";
import { Key } from "./Key.js";
const app = express();
dotenv.config();
// for server
const server = async () => {
try {
let connectMongoose = await mongoose.connect(Key, {
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("mongo is connected");
app.use(express.json());
app.use("/api/products", productRoute);
app.listen(5000, () => {
console.log("listening port 5000");
});
app.use((err, req, res, next) => {
res.status(500).json({
message: "PAGE NOT FOUND",
});
});
} catch (error) {
console.error(error);
}
};
// for test
const test = async () => {
try {
app.use(express.json());
app.use("/api/products", productRoute);
app.use((err, req, res, next) => {
res.status(500).json({
message: "PAGE NOT FOUND",
});
});
} catch (error) {
console.error(error);
}
};
export default app;
export { server, test };
|
import React from 'react';
import {useSelector} from 'react-redux';
const Header = () => {
const image = useSelector(state => state.car.image)
const name = useSelector(state => state.car.name)
const price = useSelector(state => state.car.price)
const additionalPrice = useSelector(state => state.additionalPrice)
return (
<>
<figure className="image is-128x128">
<img src={image} alt={name} />
</figure>
<h2>{name}</h2>
<p>Amount: ${price + additionalPrice}</p>
</>
);
};
export default Header;
|
$(function(){
// 快速打卡
$("#container").on('click', '.status-normal', function(){
$.prompt('点击了快速打卡,将进行快速打卡操作。');
// 打卡相关操作
});
});
|
//[COMMENTS]
/*
Instructions
Set myName to a string equal to your name and build myStr with myName between the strings "My name is " and " and I am swell!"
myName should be set to a string at least 3 characters long
Use two + operators to build myStr with myName inside it
*/
//[COMMENTS]
// Example
var ourName = "Free Code Camp";
var ourStr = "Hello, our name is " + ourName + ", how are you?";
// Only change code below this line
var myName = "Aritra Chatterjee";
var myStr = "My name is " + myName + " and I am swell!";
|
'use strict';
var $ = require('jquery');
var Backbone = require('backbone');
Backbone.$ = $;
// ???
var router = require('../router');
// var router = new Router();
// Need to put this in /src/js/lib
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var Shouts = Backbone.Collection.extend({
url: '/api/shouts'
});
var Shout = Backbone.Model.extend({
urlRoot: '/api/shouts'
});
var ShoutIndexView = Backbone.View.extend({
el: '#app',
initialize: function () {
this.render();
},
render: function () {
var that = this;
var shouts = new Shouts();
shouts.fetch({
success: function (shouts) {
var template = require('../templates/shouts/index.html');
that.$el.html(template({ shouts: shouts.models }));
console.log(shouts.models);
}
});
}
});
var ShoutEditView = Backbone.View.extend({
el: '#app',
events: {'submit': 'save'},
initialize: function () {
this.render();
},
render: function () {
var template = require('../templates/shouts/new.html');
this.$el.html(template());
},
save: function(e) {
e.preventDefault();
var data = $('#foo').serializeObject();
var shout = new Shout();
shout.save(data, {
success: function (shout) {
console.log(shout.toJSON());
console.dir(router);
// not sure how to bring router constructor in with Browserify
router.navigate('/shouts', {trigger: true});
}
});
}
});
// var ShoutShowView = Backbone.View.extend({
// el: '#app',
// initialize: function () {
// this.render();
// },
// render: function () {
// var template = require('../templates/shouts/new.html');
// this.$el.html(template());
// }
// });
exports.index = function() {
var shoutIndexView = new ShoutIndexView();
};
exports.new = function() {
var shoutEditView = new ShoutEditView();
};
// exports.show = function() {
// var shoutShowView = new ShoutShowView();
// };
|
/* globals __DEV__ */
import clone from './clone'
import config from './config'
import { input } from './middleware'
import { event } from './events'
/**
* The position of an object on a Timeline
* where 0 is Timeline start and 1 is Timeline finish.
*
* @typedef {Object} TimelinePosition
*
* @property {Position} start
* @property {Position} finish
*/
/**
* A Shape positioned on a Timeline.
*
* @typedef {Object} TimelineShape
*
* @property {Shape} shape
* @property {TimelinePosition} timelinePosition
*/
/**
* The position of an object on a Timeline in milliseconds.
*
* @typedef {Object} MsTimelinePosition
*
* @property {number} start.
* @property {number} finish.
*/
/**
* A Shape positioned on a Timeline (position set in milliseconds).
*
* @typedef {Object} MsTimelineShape
*
* @property {Shape} shape
* @property {MsTimelinePosition} timelinePosition
*/
/**
* A TimelineShape array and their total duration.
*
* @typedef {Object} TimelineShapesAndDuration
*
* @property {TimelineShape[]} timelineShapes
* @property {number} duration
*/
/**
* The options required to calculate the current playback Position.
*
* @typedef {Object} PlaybackOptions
*
* @property {boolean} alternate - Should the next iteration reverse current direction?
* @property {number} duration - Milliseconds that each iteration lasts.
* @property {number} initialIterations - The starting number of iterations.
* @property {number} iterations - The number of playback interations (additional to initialIterations).
* @property {boolean} reverse - Should the first iteration start in a reverse direction?
* @property {number} [started] - The UNIX timestamp of playback start.
*/
/**
* PlaybackOptions and tween middleware.
*
* @typedef {Object} TimelineOptions
*
* @extends PlaybackOptions
* @property {Middleware[]} middleware
*/
/**
* A Shape and timeline related options.
*
* @typedef {Object} ShapeWithOptions
*
* @property {(string|number)} [after] - The name of the Shape to queue after (in sequence).
* @property {(string|number)} [at] - The name of the Shape to queue at (in parallel).
* @property {(string|number)} name - A unique reference.
* @property {number} offset - The offset in milliseconds to adjust the queuing of this shape.
* @property {Shape} shape
*/
/**
* An object containing Middlware, PlaybackOptions and ShapesWithOptions.
*
* @typedef {Object} SortedTimelineProps
*
* @property {Middleware[]} middleware
* @property {PlaybackOptions} playbackOptions
* @property {ShapeWithOptions[]} shapesWithOptions
*/
/**
* A sequence of Shapes.
*
* @typedef {Object} Timeline
*
* @property {Middleware[]} middleware
* @property {PlaybackOptions} playbackOptions
* @property {Object} state - Holds the last known state of the timeline.
* @property {TimelineShape[]} timelineShapes
*/
/**
* Runs each Middleware input function on every Keyframe's FrameShape.
*
* @param {Shape} shape
* @param {Middleware[]} middleware
*
* @example
* apply(shape, middleware)
*/
const apply = ({ keyframes }, middleware) => {
for (let i = 0, l = keyframes.length; i < l; i++) {
const keyframe = keyframes[ i ]
keyframe.frameShape = input(keyframe.frameShape, middleware)
}
}
/**
* Is playback currently in reverse?
*
* @param {PlaybackOptions} playbackOptions
* @param {number} complete - The number of iterations complete.
*
* @example
* currentReverse(playbackOptions, complete)
*/
const currentReverse = (playbackOptions, complete) => {
const reverse = playbackOptions.reverse
if (complete === 0) {
return reverse
}
const alternate = playbackOptions.alternate
const initialIterations = playbackOptions.initialIterations
const initialReverse = sameDirection(alternate, initialIterations)
? reverse
: !reverse
return sameDirection(alternate, initialIterations + complete)
? initialReverse
: !initialReverse
}
/**
* The number of iterations a Timeline has completed.
*
* @param {PlaybackOptions} playbackOptions
* @param {number} opts.at
*
* @returns {number}
*
* @example
* iterationsComplete(playbackOptions, 1000)
*/
const iterationsComplete = (playbackOptions, at) => {
const duration = playbackOptions.duration
const iterations = playbackOptions.iterations
const started = playbackOptions.started
if (typeof started === 'undefined' || at <= started) {
return 0
}
const ms = at - started
const maxDuration = duration * iterations
if (ms >= maxDuration) {
return iterations
}
return ms / duration
}
/**
* Stops playback of a Timeline.
*
* @param {Timeline} timeline
* @param {PlaybackOptions} playbackOptions
* @param {number} [at]
*
* @example
* pause(timeline)
*/
const pause = (timeline, playbackOptions = {}, at) => {
timeline.playbackOptions = updatePlaybackOptions({ at, timeline, pause: true, playbackOptions })
updateState(timeline, at)
}
/**
* Starts playback of a Timeline.
*
* @param {Timeline} timeline
* @param {PlaybackOptions} playbackOptions
* @param {number} [at]
*
* @example
* play(timeline, { initialIterations: 0 })
*/
const play = (timeline, playbackOptions = {}, at) => {
timeline.playbackOptions = updatePlaybackOptions({ at, timeline, playbackOptions })
updateState(timeline, at)
}
/**
* Calculate the Timeline Position.
*
* @param {number} totalIterations - initialIterations + iterationsComplete.
* @param {boolean} reverse - Is the Timeline currently in reverse?
*
* @returns {Position}
*
* @example
* position(5.43, true)
*/
const position = (totalIterations, reverse) => {
const i = totalIterations >= 1 && totalIterations % 1 === 0
? 1
: totalIterations % 1
return reverse ? 1 - i : i
}
/**
* Is the direction same as initial direction?
*
* @param {boolean} alternate - Is iteration direction alternating?
* @param {number} iterations - The number of iterations complete.
*
* @return {boolean}
*
* @example
* sameDirection(true, 3.25)
*/
const sameDirection = (alternate, iterations) => {
const x = iterations % 2
return !alternate || iterations === 0 || (x <= 1 && x % 2 > 0)
}
/**
* Calculate the start position of a Shape on the Timeline.
*
* @param {Object} props
* @param {(string|number)} [props.after]
* @param {(string|number)} [props.at]
* @param {MsTimelineShape[]} props.msTimelineShapes
* @param {number} props.offset
* @param {number} props.timelineFinish - The current finish of the timeline.
*
* @returns {number}
*
* @example
* shapeStart({ 'foo', msTimelineShapes, 200, 2000 })
*/
const shapeStart = ({ after, at, msTimelineShapes, offset, timelineFinish }) => {
if (typeof after !== 'undefined' || typeof at !== 'undefined') {
const reference = typeof after !== 'undefined' ? after : at
for (let i = 0; i < msTimelineShapes.length; i++) {
const s = msTimelineShapes[ i ]
if (reference === s.shape.name) {
return (typeof at !== 'undefined'
? s.timelinePosition.start
: s.timelinePosition.finish) + offset
}
}
for (let i = 0; i < msTimelineShapes.length; i++) {
const s = msTimelineShapes[ i ]
for (let j = 0; j < s.shape.keyframes.length; j++) {
const keyframe = s.shape.keyframes[ j ]
if (reference === keyframe.name) {
return s.timelinePosition.start +
s.shape.duration * keyframe.position + offset
}
}
}
if (__DEV__) {
throw new Error(`No Shape or Keyframe matching name '${reference}'`)
}
}
return timelineFinish + offset
}
/**
* Create a ShapeWithOptions from an array.
*
* @param {Object[]} arr
* @param {Shape} arr.0
* @param {Object} arr.1
*
* @returns {ShapeWithOptions}
*
* @example
* shapeWithOptionsFromArray(arr, i)
*/
const shapeWithOptionsFromArray = ([ shape, options ], i) => {
if (__DEV__ && (typeof shape !== 'object' || !shape.keyframes)) {
throw new TypeError(`When an array is passed to the timeline function the first item must be a Shape`)
}
if (__DEV__ && (typeof options !== 'object')) {
throw new TypeError(`When an array is passed to the timeline function the second item must be an object`)
}
const { name = i, queue = config.defaults.timeline.queue } = options
if (__DEV__ && (typeof name !== 'string' && typeof name !== 'number')) {
throw new TypeError(`The name prop must be of type string or number`)
}
if (typeof queue === 'object' && (!Array.isArray(queue) && queue !== null)) {
const { after, at, offset = 0 } = queue
if (__DEV__ && (typeof offset !== 'undefined' && typeof offset !== 'number')) {
throw new TypeError(`The queue.offset prop must be of type number`)
}
if (__DEV__ && (typeof at !== 'undefined' && typeof after !== 'undefined')) {
throw new TypeError(`You cannot pass both queue.at and queue.after props`)
}
if (__DEV__ && (typeof at !== 'undefined' && typeof at !== 'string' && typeof at !== 'number')) {
throw new TypeError(`The queue.at prop must be of type string or number`)
}
if (__DEV__ && (typeof after !== 'undefined' && typeof after !== 'string' && typeof after !== 'number')) {
throw new TypeError(`The queue.after prop must be of type string or number`)
}
if (typeof at !== 'undefined') {
return { at, name, offset, shape }
}
if (typeof after !== 'undefined') {
return { after, name, offset, shape }
}
return { name, offset, shape }
} else if (typeof queue === 'number') {
return { name, offset: queue, shape }
} else if (typeof queue === 'string') {
return { after: queue, name, offset: 0, shape }
}
if (__DEV__) {
throw new TypeError(`The queue prop must be of type number, string or object`)
}
return { name, offset: 0, shape }
}
/**
* Sorts an array of Shapes, ShapesWithOptions and TimelineOptions.
*
* @param {(Shape|Object[]|TimelineOptions)[]} props
*
* @returns {SortedTimelineProps}
*
* @example
* sort(props)
*/
const sort = props => {
if (__DEV__ && props.length === 0) {
throw new TypeError(
`The timeline function must be passed at least one Shape`
)
}
let options = {}
const shapesWithOptions = []
for (let i = 0, l = props.length; i < l; i++) {
const prop = props[ i ]
if (Array.isArray(prop)) {
shapesWithOptions.push(shapeWithOptionsFromArray(prop, i))
} else {
if (__DEV__ && typeof prop !== 'object') {
throw new TypeError(`The timeline function must only be passed objects and arrays`)
}
if (prop.keyframes) {
shapesWithOptions.push({
name: i,
offset: config.defaults.timeline.queue,
shape: prop
})
} else {
if (__DEV__) {
if (i === 0) {
throw new TypeError(`The timeline function must receive a Shape as the first argument`)
} else if (i !== props.length - 1) {
throw new TypeError(`The timeline function must receive options as the final argument`)
}
}
options = clone(prop)
}
}
}
return {
middleware: validMiddleware(options),
playbackOptions: validPlaybackOptions(options),
shapesWithOptions
}
}
/**
* Creates a Timeline from one or more Shape.
* Optionally can take an options object as the last argument,
* as well as options for each Shape if passed in as an array.
*
* @param {...(Shape|Object[]|TimelineOptions)} props
*
* @returns {Timeline}
*
* @example
* timeline(circle, [ square, { queue: -200 } ], { duration: 5000 })
*/
const timeline = (...props) => {
const { middleware, playbackOptions, shapesWithOptions } = sort(props)
const { duration, timelineShapes } = timelineShapesAndDuration(shapesWithOptions, middleware)
if (typeof playbackOptions.duration === 'undefined') {
playbackOptions.duration = duration
}
const t = { middleware, playbackOptions, state: {}, timelineShapes }
for (let i = 0, l = timelineShapes.length; i < l; i++) {
const shape = timelineShapes[ i ].shape
shape.timeline = t
shape.timelineIndex = i
}
updateState(t)
t.event = event(t)
return t
}
/**
* Converts a set of MsTimelineShapes to a set of TimelineShapes
* given the Timeline start and total duration values.
*
* @param {Object} props
* @param {number} props.duration
* @param {msTimelineShape[]} props.msTimelineShapes
* @param {number} props.start
*
* @returns {TimelineShape[]}
*
* @example
* timelineShapes()
*/
const timelineShapes = ({ duration, msTimelineShapes, start }) => {
const s = []
for (let i = 0, l = msTimelineShapes.length; i < l; i++) {
const msTimelineShape = msTimelineShapes[ i ]
const timelinePosition = msTimelineShape.timelinePosition
s.push({
shape: msTimelineShape.shape,
timelinePosition: {
start: (timelinePosition.start - start) / duration,
finish: (timelinePosition.finish - start) / duration
}
})
}
return s
}
/**
* Converts an array of ShapesWithOptions into TimelineShapes
* and their total duration.
*
* @param {ShapeWithOptions[]} shapesWithOptions
* @param {Middleware[]} middleware
*
* @returns {TimelineShapesAndDuration}
*
* @example
* timelineShapes(shapesWithOptions)
*/
const timelineShapesAndDuration = (shapesWithOptions, middleware) => {
let timelineStart = 0
let timelineFinish = 0
const msTimelineShapes = []
for (let i = 0, l = shapesWithOptions.length; i < l; i++) {
const { after, at, name, offset, shape } = shapesWithOptions[ i ]
if (__DEV__ && typeof shape.timeline !== 'undefined') {
throw new Error(`A Shape can only be added to one timeline`)
}
shape.name = name
apply(shape, middleware)
const start = shapeStart({
after,
at,
msTimelineShapes,
offset,
timelineFinish
})
const finish = start + shape.duration
timelineStart = Math.min(timelineStart, start)
timelineFinish = Math.max(timelineFinish, finish)
msTimelineShapes.push({ shape, timelinePosition: { start, finish } })
}
const timelineDuration = Math.abs(timelineStart - timelineFinish)
return {
duration: timelineDuration,
timelineShapes: timelineShapes({
duration: timelineDuration,
msTimelineShapes,
start: timelineStart
})
}
}
/**
* Updates the PlaybackOptions of a Timeline.
*
* @param {Object} opts
* @param {number} [opts.at]
* @param {PlaybackOptions} opts.playbackOptions
* @param {Timeline} opts.timeline
*
* @example
* updatePlaybackOptions({ timeline, playbackOptions })
*/
const updatePlaybackOptions = ({ at, pause = false, playbackOptions, timeline }) => {
if (__DEV__ && (typeof timeline !== 'object' || !timeline.timelineShapes || !timeline.playbackOptions)) {
throw new TypeError(`The updatePlaybackOptions function must be passed a Timeline`)
}
if (__DEV__ && (typeof at !== 'undefined' && typeof at !== 'number')) {
throw new TypeError(`The updatePlaybackOptions function at property must be of type number`)
}
const previous = timeline.playbackOptions
const next = validPlaybackOptions({
...previous,
...playbackOptions,
started: typeof at !== 'undefined' ? at : Date.now()
})
if (typeof playbackOptions.initialIterations !== 'undefined') {
if (typeof playbackOptions.reverse === 'undefined') {
next.reverse = currentReverse(previous, next.initialIterations - previous.initialIterations)
}
if (
typeof playbackOptions.iterations === 'undefined' &&
previous.iterations !== Infinity
) {
next.iterations = Math.max(0, previous.initialIterations + previous.iterations - next.initialIterations)
}
} else {
const complete = iterationsComplete(previous, next.started)
const reverse = currentReverse(previous, complete)
next.initialIterations = previous.initialIterations + complete
if (typeof playbackOptions.iterations === 'undefined') {
next.iterations = previous.iterations - complete
if (typeof playbackOptions.reverse !== 'undefined' && next.reverse !== previous.reverse && next.iterations !== Infinity) {
const nextIterations = next.initialIterations
next.initialIterations = next.iterations
next.iterations = nextIterations
}
} else {
if (
typeof playbackOptions.reverse !== 'undefined' &&
playbackOptions.reverse !== reverse &&
next.iterations !== Infinity
) {
next.initialIterations = previous.iterations - complete
}
}
if (typeof playbackOptions.reverse === 'undefined') {
next.reverse = reverse
} else if (next.iterations === Infinity) {
next.initialIterations = playbackOptions.reverse === reverse
? next.initialIterations % 1
: 1 - next.initialIterations % 1
}
}
if (pause) {
delete next.started
}
return next
}
/**
* Updates the Timeline state.
*
* @param {Timeline} timeline
* @param {number} at
*
* @example
* updateState(timeline, Date.now())
*/
const updateState = (t, at) => {
const playbackOptions = t.playbackOptions
const state = t.state
state.started = typeof playbackOptions.started !== 'undefined'
state.iterationsComplete = iterationsComplete(playbackOptions, at)
state.totalIterations = playbackOptions.initialIterations + state.iterationsComplete
state.reverse = currentReverse(playbackOptions, state.iterationsComplete)
state.finished = playbackOptions.iterations - state.iterationsComplete === 0
state.position = position(state.totalIterations, state.reverse)
}
/**
* Extracts and validates Middlware from an object.
*
* @param {Object} opts
*
* @returns {Middleware[]}
*
* @example
* validMiddleware(opts)
*/
const validMiddleware = ({ middleware = config.defaults.timeline.middleware }) => {
if (!Array.isArray(middleware)) {
throw new TypeError(`The timeline function middleware option must be of type array`)
}
for (let i = 0, l = middleware.length; i < l; i++) {
const { name, input, output } = middleware[ i ]
if (typeof name !== 'string') {
throw new TypeError(`A middleware must have a name prop`)
}
if (typeof input !== 'function') {
throw new TypeError(`The ${name} middleware must have an input method`)
}
if (typeof output !== 'function') {
throw new TypeError(`The ${name} middleware must have an output method`)
}
}
return middleware
}
/**
* Extracts and validates PlaybackOptions from an object.
*
* @param {Object} opts
*
* @returns {PlaybackOptions}
*
* @example
* validPlaybackOptions(opts)
*/
const validPlaybackOptions = ({
alternate = config.defaults.timeline.alternate,
duration,
initialIterations = config.defaults.timeline.initialIterations,
iterations = config.defaults.timeline.iterations,
reverse = config.defaults.timeline.reverse,
started
}) => {
const playbackOptions = {}
if (typeof duration !== 'undefined') {
if (__DEV__ && (typeof duration !== 'number' || duration < 0)) {
throw new TypeError(`The timeline function duration option must be a positive number or zero`)
}
playbackOptions.duration = duration
}
if (__DEV__) {
if (typeof alternate !== 'boolean') {
throw new TypeError(`The timeline function alternate option must be true or false`)
}
if (typeof initialIterations !== 'number' || initialIterations < 0) {
throw new TypeError(`The timeline function initialIterations option must be a positive number or zero`)
}
if (typeof iterations !== 'number' || iterations < 0) {
throw new TypeError(`The timeline function iterations option must be a positive number or zero`)
}
if (typeof reverse !== 'boolean') {
throw new TypeError(`The timeline function reverse option must be true or false`)
}
}
if (typeof started !== 'undefined') {
if (__DEV__ && (typeof started !== 'number' || started < 0)) {
throw new TypeError(`The timeline function started option must be a positive number or zero`)
}
playbackOptions.started = started
}
return {
...playbackOptions,
alternate,
initialIterations,
iterations,
reverse
}
}
export {
currentReverse,
iterationsComplete,
pause,
play,
position,
sameDirection,
updateState
}
export default timeline
|
import dataFetch from '@/utils/request'
export default {
// 搜索列表
async searchList (params) {
return dataFetch('/search/do', params)
},
// 热门搜索
async hotSearch (params) {
return dataFetch('/search/hot', params)
},
// 获取输入匹配下拉列表
async macthList (params) {
return dataFetch('/search/associateWord', params)
}
}
|
// array_methods.js
// Array.prototype.forEach
let numbers = [1, 2, 3];
let counter = 0;
while (counter < numbers.length) {
console.log(numbers[counter]);
counter += 1;
}
[1, 2, 3].forEach(number => {
console.log(number);
});
[1, 2, 3].forEach((number, idx) => {
console.log(`${idx}: ${number}`);
});
'abcd'.split('').forEach(char => {
console.log(char);
});
let produce = {
apple: 'Fruit',
carrot: 'Vegetable',
pear: 'Fruit',
broccoli: 'Vegetable'
};
let produceValues = Object.values(produce);
produceValues.forEach(value => {
console.log(value);
});
let produceKeys = Object.keys(produce);
produceKeys.forEach(key => {
console.log(key);
});
let produceKeyValues = Object.entries(produce);
produceKeyValues.forEach(keyValue => {
// array destructring assignment
let [key, value] = keyValue;
console.log(`${key} is a ${value}`);
});
// Array.prototype.filter
numbers = [1, 2, 3];
let oddNumbers = [];
for (let index = 0; index < numbers.length; index += 1) {
if (numbers[index] % 2 === 1) {
oddNumbers.push(numbers[index]);
}
}
console.log(oddNumbers);
oddNumbers = [1, 2, 3].filter(num => {
return num % 2 === 1;
});
console.log(oddNumbers);
[1, 2, 3].filter(num => num % 2 === 1);
produce = {
apple: 'Fruit',
carrot: 'Vegetable',
pear: 'Fruit',
broccoli: 'Vegetable'
};
produceKeyValues = Object.entries(produce);
let onlyVegetablesArr = produceKeyValues.filter(keyValue => {
let [key, value] = keyValue;
return value === 'Vegetable';
});
let onlyVegetables = {};
onlyVegetablesArr.forEach(keyValue => {
let [key, value] = keyValue;
onlyVegetables[key] = value;
});
console.log(onlyVegetables);
onlyVegetables = {};
produceKeyValues.forEach(keyValue => {
let [key, value] = keyValue;
if (value === 'Vegetable') {
onlyVegetables[key] = value;
}
});
console.log(onlyVegetables);
// Array.prototype.map
console.log([1, 2, 3].map(num => num * 2));
console.log([1, 2, 3].map(num => num % 2 === 1));
let str = "What's up, Doc?";
let vowels = str.split('')
.filter(char => 'aeiou'.includes(char.toLowerCase()))
.join('');
console.log(vowels);
let doubledStr = str.split('')
.map(char => char + char)
.join('');
console.log(doubledStr);
|
var db = require("../../database/configDb.js");
const bcrypt = require('bcryptjs');
class User {
constructor (){
this.db = db;
this.bcrypt = bcrypt;
}
async create(user, callback){
user.password = await this.hash(user.password);
this.db.query('INSERT INTO users SET ?', user, (err, res, fields) => {
if(err){
return callback(JSON.stringify("Usuario já existe"));
} else {
return callback(user);
}
this.db.end();
});
}
async hash(password){
const hash = await this.bcrypt.hash(password, 10);
return hash;
}
async find(email, callback){
await this.db.query('SELECT * FROM users WHERE email = ?', email, (err, res) => {
if(err){
return callback(JSON.stringify("Login invalido"));
} else {
return callback(res[0]);
}
this.db.end();
});
}
}
module.exports = User; |
define([
'lib/easel',
'lib/box2d_v.2.3.1_min',
'class/physics/box2d/Box2dHelper',
'class/physics/box2d/component/Box2DComponent'
], function(createjs,box2d,Box2DHelper,Box2DComponent) {
if (typeof createjs === 'undefined' ) {
createjs = window.createjs;
}
function StaticComponent(manager,data) {
this._manager = manager;
this._type = "StaticComponent";
}
var p = createjs.extend(StaticComponent, Box2DComponent);
p.isType = function(type){
if(type == this._type){
return true;
}else{
return this.Box2DComponent_isType(type);
}
} ;
p.initalize = function(obj){
var bd = new Box2D.b2BodyDef();
bd.set_type(Module.b2_staticBody);
bd.set_position(this.SceneToBox2dPos(obj,this._manager.GetPTM()));
var body = this._manager.GetWorld().CreateBody(bd);
body.CreateFixture(Box2DHelper.createRectangleShape(obj.get_width()/this._manager.GetPTM(),obj.get_height()/this._manager.GetPTM()), 1.0);
var context = this;
obj.on("positionupdate",function(e){
body.SetTransform(context.SceneToBox2dPos(obj,context._manager.GetPTM()),0);
});
// no need to update the static object
}
p.SceneToBox2dPos = function(sceneobj,PTM) {
return new Box2D.b2Vec2(sceneobj.get_x()/PTM,sceneobj.get_y()/PTM);
} ;
createjs.StaticComponent = createjs.promote(StaticComponent, "Box2DComponent");
return StaticComponent;
});
|
import _ from 'lodash';
const getLowercaseKeys = function(object) {
if (typeof object !== 'object') {
return null;
}
if (Array.isArray(object)) {
return object.map((item) => {
return _.transform(item, (result, val, key) => {
result[_.lowerFirst(key)] = val;
});
});
}
return _.transform(object, (result, val, key) => {
result[_.lowerFirst(key)] = val;
});
};
export { getLowercaseKeys };
|
import React from 'react'
//component responsible for showing a list of character names, allowing user interaction when a name is clicked
const characterList = (props) =>{
const characterItems = props.characters.map( (character) => {
return(
<l1 onClick = { () => props.onCharacterSelect(character)}>
<div className = "character-list-item">
<h4>{character.name}</h4>
</div>
</l1>
);
});
return (
<div className = "character-list">
<ul>
{characterItems}
</ul>
</div>
);
};
export default characterList; |
import React, { Component } from 'react';
import Map from '../../components/map';
import requests from '../../requests';
import Star from '../../components/star';
import { Spin, Card, Row, Col, Typography, Icon, Button, Modal } from 'antd';
import Rating from '../../components/rating';
import { Link } from 'react-router-dom';
import Geolib from 'geolib';
import './style.scss';
const { Title } = Typography;
class Main extends Component {
static defaultProps = {
lan: 52,
lng: 21
};
constructor() {
super();
this.state = {
points: [],
selectedPoint: null,
betterPoint: null,
modalOpen: false
};
this.onPointSelect = this.onPointSelect.bind(this);
this.findBetterPoint = this.findBetterPoint.bind(this);
window.scrollTo(0, 0);
}
onPointSelect(id) {
if (this.state.selectedPoint) {
this.findBetterPoint(this.state.selectedPoint);
}
this.setState({
selectedPoint: this.state.points.find(point => point.id === id)
});
}
findBetterPoint(point) {
const betterPoints = this.state.points
.filter(p => {
return p.overAllRating > point.overAllRating;
})
.filter(p => {
const userLocation = {
latitude: this.props.lan,
longitude: this.props.lng
};
const pD = Geolib.getDistance(userLocation, {
latitude: p.coordinates[0],
longitude: p.coordinates[1]
});
const pointDistance = Geolib.getDistance(userLocation, {
latitude: point.coordinates[0],
longitude: point.coordinates[1]
});
return pD < pointDistance;
})
.sort((a, b) => {
if (a.overAllRating > b.overAllRating) {
return -1;
} else {
return 1;
}
});
if (betterPoints.length) {
return betterPoints[0];
}
}
async componentDidMount() {
try {
const points = await requests.getPoints(this.props.lan, this.props.lng);
if (points && points.data) {
this.setState({
points: points.data
});
}
} catch (e) {
console.log(e);
}
}
showModal = () => {
const betterPoint = this.findBetterPoint(this.state.selectedPoint);
if (betterPoint) {
this.setState(state => ({
modalOpen: !state.modalOpen,
betterPoint
}));
} else {
this.props.history.push({
pathname: '/send',
state: {
point: this.state.selectedPoint
}
});
}
};
render() {
return (
<div className="select-point">
{this.state.points.length ? (
<Row gutter={16}>
<Col className="gutter-row" xs={24} md={24} lg={24} xl={12}>
<div className="gutter-box">
<Map
selectedPoint={this.state.selectedPoint}
onPointSelect={this.onPointSelect}
points={this.state.points}
/>
</div>
</Col>
<Col className="gutter-row" xs={24} md={24} lg={24} xl={12}>
<div className="gutter-box">
{this.state.selectedPoint ? (
<div className="select-point__info-container">
<Row gutter={16}>
<Col
className="gutter-row select-point__info-column"
xs={24}
md={24}
lg={24}
xl={14}
>
<div className="gutter-box">
<Card
hoverable
title={<strong>Opinion of chosen point</strong>}
bordered
>
<Star
overall={this.state.selectedPoint.overAllRating}
key={this.state.selectedPoint.id}
data={Object.values(
this.state.selectedPoint.ratings
)}
overallRating={
this.state.selectedPoint.overallRating
}
/>
</Card>
</div>
</Col>
<Col
className="gutter-row select-point__info-column"
xs={24}
md={24}
lg={24}
xl={10}
>
<div className="gutter-box">
<Card
hoverable
title={<strong>Details about chosen point</strong>}
bordered
>
<Rating
key={`mainRating${this.state.selectedPoint.id}`}
data={this.state.selectedPoint}
hours
/>
</Card>
</div>
</Col>
</Row>
<Row gutter={16}>
<Col className="gutter-row" xs={24}>
<div className="select-point__info-cta">
<Button
onClick={this.showModal}
className="main-page__button"
type="primary"
>
<strong>I choose this point</strong>
</Button>
</div>
</Col>
</Row>
</div>
) : (
<div className="select-point__info-container--empty">
<Title style={{ textAlign: 'center' }} level={3}>
Choose a place to collect your delivery{' '}
<Icon type="smile" />
</Title>
</div>
)}
</div>
</Col>
{this.state.selectedPoint ? (
<Modal
style={{ textAlign: 'center' }}
visible={this.state.modalOpen}
closable
onCancel={this.showModal}
destroyOnClose
>
<Title level={1}>
<Icon type="gift" theme="filled" />
</Title>
<Title level={4} style={{ marginBottom: '30px' }}>
Our system found an amazing collection point closer to your
location!
</Title>
<Row gutter={25} type="flex" align="top">
<Col className="gutter-row" xs={24} md={24} lg={24} xl={12}>
<div className="gutter-box">
<p>Current place:</p>
<Rating
key={`modal${this.state.selectedPoint.id}`}
data={this.state.selectedPoint}
/>
<Star
overall={this.state.selectedPoint.overAllRating}
key={`modalStar${this.state.selectedPoint.id}`}
data={Object.values(this.state.selectedPoint.ratings)}
overallRating={this.state.selectedPoint.overallRating}
/>
</div>
</Col>
{this.state.betterPoint ? (
<Col className="gutter-row" xs={24} md={24} lg={24} xl={12}>
<div className="gutter-box">
<p>
<strong>
<Icon type="check-square" /> Our suggestion:
</strong>
</p>
<Rating
key={this.state.betterPoint.id}
data={this.state.betterPoint}
/>
<Star
overall={this.state.betterPoint.overAllRating}
key={`star${this.state.betterPoint.id}`}
data={Object.values(this.state.betterPoint.ratings)}
overallRating={this.state.betterPoint.overallRating}
/>
</div>
</Col>
) : null}
</Row>
<div>
<Link
to={{
pathname: '/send',
state: {
point: this.state.selectedPoint
}
}}
>
<Button className="button-modal-first">Other time</Button>
</Link>
<Link
to={{
pathname: '/send',
state: {
point: this.findBetterPoint(this.state.selectedPoint)
}
}}
>
<Button className="ant-btn-primary button-modal-second">
I agree
</Button>
</Link>
</div>
</Modal>
) : null}
</Row>
) : (
<div className="select-point__spinner-container">
<Spin size="large" tip="Loading..." />
</div>
)}
</div>
);
}
}
export default Main;
|
'use strict';
(function () {
class MainController {
constructor($http, $scope, socket, feedResource) {
this.$http = $http;
this.socket = socket;
this.awesomeThings = [];
this.data = { dataset: [] };
this.google = google;
this.feedResource = feedResource;
this.$scope = $scope;
this.color = { name: '' }
this.sensorId = 'Abyr91CL2yYWR7ZUfI2VbaKtoHqoz13I'
$scope.$on('$destroy', function () {
socket.unsyncUpdates('thing');
});
}
initGoogleCharts() {
this.google.charts.load('current', { 'packages': ['corechart'] });
this.google.charts.setOnLoadCallback(this.drawChart);
}
drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'TimeStamp');
data.addColumn('number', 'Temperature');
if (this !== undefined) {
this.data.dataset.forEach(function (item) {
data.addRow([item.timestamp, item.data.centidegreeCelsius / 100]);
});
}
var options = {
//title: 'Temperature',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
$onInit() {
this.initGoogleCharts();
this.$http.get('/api/things').then(response => {
this.awesomeThings = response.data;
this.socket.syncUpdates('thing', this.awesomeThings);
});
}
getFeed() {
this.feedResource.getFeed({ feedId: this.sensorId }).then(response => {
var dataset = [];
response.forEach(function (item) {
item.timestamp = new Date(item.dateEvent);
dataset.push(item);
});
this.data.dataset = dataset;
this.drawChart();
});
}
addThing() {
if (this.newThing) {
this.$http.post('/api/things', { name: this.newThing });
this.newThing = '';
}
}
deleteThing(thing) {
this.$http.delete('/api/things/' + thing._id);
}
}
angular.module('smarterPlanetApp')
.component('main', {
templateUrl: 'app/main/main.html',
controller: MainController
});
})();
|
/*
* Page object for the color wheel, found on configurable product pages when color is an configurable attribute
*
* @package: Blueacorn ColorWheel.js
* @version: 1.0
* @Author: Luke Fitzgerald
* @Copyright: Copyright 2015-07-24 11:10:59 Blue Acorn, Inc.
*/
'use strict';
function ColorWheel() {
var colorWheel = 'body > div > div > div.main-container.col1-layout > div > div.col-main > div.color-wheel-container > div.color-wheel';
var colorWheelSelector = 'body > div > div > div.main-container.col1-layout > div > div.col-main > div.color-wheel-container > div.color-wheel-selector.ui-draggable.ui-draggable-handle';
var colorWheelInner = 'body > div > div > div.main-container.col1-layout > div > div.col-main > div.color-wheel-container > div.color-wheel > div';
var colorWheelNotAnimating = 'body > div > div > div.main-container.col1-layout > div > div.col-main > div.color-wheel-container > div.color-wheel > div:not(.velocity-animating)';
var colorSlice = 'body > div > div > div.main-container.col1-layout > div > div.col-main > div.color-wheel-container > div.color-wheel > div > div';
var colorNameDisplay = '#product_addtocart_form > div.product-img-box > div.color-selection';
var colorDropdownClosed = '#product-options-wrapper > dl > dd:nth-child(2) > div > div.ba-select.ba-select-box.ba-thumbnail';
var colorDropdownOpen = '#product-options-wrapper > dl > dd:nth-child(2) > div > div.ba-select.ba-select-box.ba-swatch.open';
var colorDropdownArrow = '#product-options-wrapper > dl > dd:nth-child(2) > div > div.ba-select.ba-select-box.ba-swatch > span > span.ba-arrow';
var colorDropdownColorOption = '#product-options-wrapper > dl > dd:nth-child(2) > div > div.ba-select.ba-select-box.ba-swatch.open > div > ul > li:nth-child';
var colorDropdownColor = '#product-options-wrapper > dl > dd:nth-child(2) > div > div.ba-select.ba-select-box.ba-swatch > span > span.ba-color-box';
var colorDropdownColorName = '#product-options-wrapper > dl > dd:nth-child(2) > div > div.ba-select.ba-select-box.ba-swatch > span > span.ba-shiv-content';
this.getColorWheel = function() {
return colorWheel;
};
this.getColorWheelSelector = function() {
return colorWheelSelector;
};
this.getColorWheelInner = function() {
return colorWheelInner;
};
this.getColorSlice = function() {
return colorSlice;
};
this.getColorNameDisplay = function() {
return colorNameDisplay;
};
this.getColorDropdownClosed = function() {
return colorDropdownClosed;
};
this.getColorDropdownOpen = function() {
return colorDropdownOpen;
};
this.getColorDropdownArrow = function() {
return colorDropdownArrow;
};
this.getColorDropdownColorOption = function() {
return colorDropdownColorOption;
};
this.getColorDropdownColor = function() {
return colorDropdownColor;
};
this.getColorDropdownColorName = function() {
return colorDropdownColorName;
};
this.getColorWheelNotAnimating = function() {
return colorWheelNotAnimating;
};
this.extractColor = function(element) {
var color = casper.evaluate(function(x) {
var item = document.querySelector(x);
var atts = window.getComputedStyle(item);
return atts.backgroundColor;
}, element);
return color;
};
this.extractColorName = function(element) {
var colorName = casper.evaluate(function(x) {
var item = document.querySelector(x);
var atts = item.getAttribute('data-label');
return atts;
}, element);
return colorName;
};
this.extractXPos = function(element) {
var x = casper.evaluate(function(x) {
var item = document.querySelector(x);
var pos = item.getBoundingClientRect().left;
return pos;
}, element);
return x;
};
this.extractWidth = function(element) {
var w = casper.evaluate(function(x) {
var item = document.querySelector(x);
var pos = item.getBoundingClientRect().width;
return pos;
}, element);
return w;
};
};
|
var app = require('express')()
var http = require('http').Server(app)
var sql = require('sql')
var models = require('./models')
var psql = require('./lib/psql')
var io = require('socket.io')(http)
var ipInfo = require('./lib/ip-info')
var async = require('async')
var names = require('./lib/names')
var basicAuth = require('./lib/basic-auth')
sql.setDialect('postgres')
var lastOrders = []
app.set('trust proxy', true)
app.get('/collect', (req, res) => {
res.sendFile(__dirname + '/pixel.gif')
io.emit('order', 'event')
})
app.get('/', basicAuth.auth('sephora', 'live'), (req, res) => {
res.sendFile(__dirname + '/bf.html')
})
io.on('connection', socket => {
socket.emit('init', lastOrders)
})
http.listen(3000, () => {
console.log('listening on localhost:3000')
}) |
import React, { useState } from 'react';
import TextField from '@material-ui/core/TextField';
import { makeStyles } from '@material-ui/core/styles';
import Avatar from '@material-ui/core/Avatar';
import exclude from '../../assets/exclude.svg';
import avatar from '../../assets/avatar.svg';
const useStyles = makeStyles(theme => ({
root: {
padding: "0.5rem",
width: "100%",
margin: "0px",
display: "flex",
justifyContent: "center",
},
paper: {
margin: "0px",
padding: "4px",
display: "flex",
},
textArea: {
margin: "10px",
marginLeft:"15px",
paddingLeft: "0.1em",
paddingBottom: "0px",
fontSize: "20px",
width: "100%",
backgroundColor: "#F7F7F7",
"&::placeholder": {
color: "#C4C4C4"
},
},
lineSeparate:{
margin: "0px",
marginLeft: "18px",
justifyContent: "center",
width: "96%",
},
commentLink: {
marginLeft: "2px",
},
}));
const ReplyPost = ({createReply}) => {
const classes = useStyles();
const [content, setContent] = useState("");
const onCreateReply = (content) => {
createReply(content);
setContent("");
}
return(
<div className={classes.root}>
<Avatar className={classes.avatar} src={avatar} />
<TextField multiline className={classes.textArea} InputLabelProps={{shrink: false}} InputProps={{ disableUnderline: true }} type="text" placeholder="Write a reply..." value={content} onChange={event => setContent(event.target.value)}/>
<img src={exclude} onClick={event => onCreateReply(content)}/>
</div>
)
}
export default ReplyPost; |
'use strict';
// Write a program that stores 3 sides of a cuboid as variables (floats)
// The program should write the surface area and volume of the cuboid like:
//
// Surface Area: 600
// Volume: 1000
var height = 10;
var width = 10;
var length = 10;
var surface = (height * width + width * length + height * length) *2;
var volumn = height * width * length;
console.log('Surface Area: ' + surface);
console.log('Volumn: ' + volumn); |
import React from 'react';
import PropTypes from 'prop-types';
import * as S from './styled';
const Paragraph = ({ children, color, ...restProps }) => {
return (
<S.Paragraph color={color} {...restProps}>
{children}
</S.Paragraph>
);
};
export default Paragraph;
Paragraph.propTypes = {
color: PropTypes.oneOf(['blueBayoux', 'white']).isRequired,
paddingBottom: PropTypes.number,
paddingTop: PropTypes.number,
};
|
const KoaBody = require("koa-body");
const fs = require("fs");
const PhotosMdl = require("../models/PhotosModel");
const validSuffix = ["jpeg", "jpg", "bmp", "tif", "tiff", "png", "gif"]
function checkSuffix(path) {
let lastPos = path.lastIndexOf(".");
let suffix = (path.substring(lastPos + 1)).toLowerCase();
// console.log("file suffix:", suffix);
for (key in validSuffix) {
if (validSuffix[key] == suffix) { return true; }
}
return false;
}
module.exports = {
saveToFileSystem: (dir = "upload") => {
// console.log(__dirname + "/../static/" + dir);
return KoaBody({
multipart: true,
formidable: {
uploadDir: __dirname + "/../static/" + dir,
keepExtensions: true,
},
});
},
proceedFiles: async (ctx) => {
function deleteError(error) {
if (error) {
console.log("删除非法文件时出错:", error);
return false;
}
}
let files = ctx.request.files;
let uploadedFileInfo = [];
for (let file in files) {
current = files[file];
if (checkSuffix(current.path) && current.size > 0) {
let lastPos = current.path.lastIndexOf("/");
if (lastPos == -1) {
lastPos = current.path.lastIndexOf("\\");
}
let newName = current.path.substring(lastPos + 1);
uploadedFileInfo.push({
oldName: current.name,
newName,
path: current.path,
fileSize: current.size,
});
// 数据库操作
await PhotosMdl.saveToDatabase(newName);
} else {
console.log("删除非图片及空文件", current.path);
fs.unlink(current.path, deleteError);
}
}
ctx.body = uploadedFileInfo;
},
getPhotos: async (ctx) => {
ctx.body = await PhotosMdl.getAllPhotos();
},
clearPhotos: async (ctx) => {
ctx.body = await PhotosMdl.clearAllPhotos();
},
};
|
const {request,response} = require('express');
const bcryptjs = require('bcryptjs');
const User = require('../models/user');
// const {validationResult} = require('express-validator');
const getUser = async(req = request, res = response) => {
const{limit = 5, from = 0} = req.query;
const query = {status:true};
const [users,total] = await Promise.all([User.find(query).
skip(Number(from)).
limit(Number(limit)),
User.countDocuments(query)]);
res.json({
total,
users
});
}
const postUser = async (req = request, res = response)=>{
const {firstName,lastName,email,password,role} = req.body;
const user = new User({firstName,lastName,email,password,role});
// Verify exist email
// Encrypt password
const saltRounds = 10;
const salt = bcryptjs.genSaltSync(saltRounds);
user.password = bcryptjs.hashSync(password,salt);
// Save in DB
await user.save();
res.json({
user,
});
}
const putUser = async (req,res = response)=>{
const {id} = req.params;
// here lack email update
const {_id, password , google ,email , ...other} = req.body;
if(password){
const saltRounds = 10;
const salt = bcryptjs.genSaltSync(saltRounds);
other.password = bcryptjs.hashSync(password,salt);
}
const user = await User.findByIdAndUpdate(id,other,{new:true});
res.json({
message: 'put API from controller',
user,
});
}
module.exports = {
getUser,
postUser,
putUser,
} |
import home from './components/home.vue'
import presentation from './components/presentation.vue'
import tutorial from './components/tutorial.vue'
import planning from './components/Calendar/planning.vue'
import realisation from './components/Realisations/realisation.vue'
const routes = [
{ path: '/', component: home, name: 'home'},
{ path: '/presentation', component: presentation, name: 'presentation'},
{ path: '/tutorial', component: tutorial, name: 'tutorial'},
{ path: '/planning', component: planning, name: 'planning'},
{ path: '/realisation', component: realisation, name: 'realisation'}
]
export default routes |
/*
1)De 5 personas que ingresan al hospital se deben tomar y
validar los siguientes datos.
nombre ,peso, sexo y edad.
a)informar la cantidad de mujeres.
b)la edad promedio en total.
c)el hombre mas pesado.
pedir datos por prompt y mostrar por document.write o console.log
*/
function mostrar()
{
let nombre = "";
let peso = 0;
let sexo = "";
let edad = 0;
let cantMujeres = 0;
let pesoHombre = 0;
let edadTotal = 0;
let edadPromeido = 0;
for (let index = 0; index < 5; index++) {
nombre = prompt("Ingrese nombre del paciente:");
edad = parseInt(prompt("Ingresar edad del paciente:"));
sexo = prompt("Ingresar sexo del paciente(H-hombre/M-Mujer/O-Otro):").substring(0,1).toLocaleUpperCase();
peso = parseFloat(prompt("Ingresar peso del paciente:"));
if (sexo === "M") {
cantMujeres++;
}
if (peso > pesoHombre && sexo === "H") {
pesoHombre = peso;
}
edadTotal += edad;
}
edadPromeido = edadTotal / 5;
document.writeln("La cantidad de mujeres ingresadas es: " + cantMujeres + "</br>");
document.writeln("El hombre más pesado pesa: " + pesoHombre + "</br>");
document.writeln("La edad promedio de los pacientes es: " + edadPromeido);
}
|
'use strict';
// Setting up route
angular.module('universities').config(['$stateProvider',
function($stateProvider) {
// Universities states routing
$stateProvider
// Child state: List all university entries
.state('platform.listUniversities', {
url: '/universities',
views: {
'content': {
templateUrl: 'modules/universities/views/list-universities.client.view.html',
controller: 'ListUniversitiesCtrl as vm',
resolve: {
universitiesData: ['Universities', function (Universities) {
var UniversitiesData = Universities.query();
return UniversitiesData.$promise;
}]
}
},
'header' : {
templateUrl: 'modules/core/views/platform/header.client.view.html'
},
'sidebar' : {
templateUrl: 'modules/core/views/platform/sidebar.client.view.html',
controller: 'SidebarCtrl'
},
'footer' : {
templateUrl: 'modules/core/views/platform/footer.client.view.html',
controller: 'FooterCtrl'
}
}
})
// Child state: Create a new university entry
.state('platform.createUniversity', {
url: '/universities/create',
views: {
'content': {
templateUrl: 'modules/universities/views/create-university.client.view.html'
},
'header' : {
templateUrl: 'modules/core/views/platform/header.client.view.html',
controller: 'HeaderCtrl'
},
'sidebar' : {
templateUrl: 'modules/core/views/platform/sidebar.client.view.html',
controller: 'SidebarCtrl'
},
'footer' : {
templateUrl: 'modules/core/views/platform/footer.client.view.html',
controller: 'FooterCtrl'
}
}
})
// Child state: View a particular university entry
.state('platform.viewUniversity', {
url: '/universities/:universityId',
views: {
'content': {
templateUrl: 'modules/universities/views/view-university.client.view.html',
controller: 'ViewUniversityCtrl as vm',
resolve: {
universityData: ['Universities', '$stateParams', function (Universities, $stateParams) {
var UniversityData = Universities.get({
universityId: $stateParams.universityId
});
return UniversityData.$promise;
}],
degreesData: ['Degrees', '$stateParams', function (Degrees, $stateParams) {
var DegreesData = Degrees.query({
universityId: $stateParams.universityId
});
return DegreesData.$promise;
}]
}
},
'header' : {
templateUrl: 'modules/core/views/platform/header.client.view.html',
controller: 'HeaderCtrl'
},
'sidebar' : {
templateUrl: 'modules/core/views/platform/sidebar.client.view.html',
controller: 'SidebarCtrl'
},
'footer' : {
templateUrl: 'modules/core/views/platform/footer.client.view.html',
controller: 'FooterCtrl'
}
}
})
// Child state: Edit a particular university entry
.state('platform.editUniversity', {
url: '/universities/:universityId/edit',
views: {
'content': {
templateUrl: 'modules/universities/views/edit-university.client.view.html'
},
'header' : {
templateUrl: 'modules/core/views/platform/header.client.view.html',
controller: 'HeaderCtrl'
},
'sidebar' : {
templateUrl: 'modules/core/views/platform/sidebar.client.view.html',
controller: 'SidebarCtrl'
},
'footer' : {
templateUrl: 'modules/core/views/platform/footer.client.view.html',
controller: 'FooterCtrl'
}
}
});
}
]); |
function solve(numbers) {
return Math.max(...numbers);
}
solve([10, 20, 5]);
solve([1, 44, 123, 33]); |
var bodyParser = require('body-parser');
var Artefacts = require('../models/artefactModel');
var Institutions = require('../models/institutionProfileModel');
var Locations = require('../models/locationProfileModel');
var Persons = require('../models/personProfileModel');
module.exports = function(app) {
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', function(req, res) {
res.render("index");
});
app.get('/artefacts', function(req, res) {
Artefacts.find(function(err, artefacts) {
if (err) throw err;
res.render('artefact', { serverContent : artefacts });
});
});
app.post('/artefacts', function(req, res) {
Artefacts.create(req.body, function(err, results) {
if (err) throw err;
Artefacts.find(function(err, artefacts) {
if (err) throw err;
res.render('artefact', { serverContent : artefacts });
});
});
});
app.get('/institutions', function(req, res) {
Institutions.find(function(err, institutions) {
if (err) throw err;
res.render('institution', { serverContent : institutions });
});
});
app.post('/institutions', function(req, res) {
Institutions.create(req.body, function(err, results) {
console.log(req.body);
if (err) throw err;
Institutions.find(function(err, institutions) {
if (err) throw err;
res.render('institution', { serverContent : institutions });
});
});
});
app.get('/locations', function(req, res) {
Locations.find(function(err, locations) {
if (err) throw err;
res.render('location', { serverContent : locations });
});
});
app.post('/locations', function(req, res) {
Locations.create(req.body, function(err, results) {
if (err) throw err;
Locations.find(function(err, locations) {
if (err) throw err;
res.render('location', { serverContent : locations });
});
});
});
app.get('/persons', function(req, res) {
Persons.find(function(err, persons) {
if (err) throw err;
// console.log(persons);
res.render('person', { serverContent : persons });
});
});
app.post('/persons', function(req, res) {
Persons.create(req.body, function(err, results) {
console.log(req.body);
if (err) throw err;
Persons.find(function(err, persons) {
if (err) throw err;
res.render('person', { serverContent : persons });
});
});
});
app.get('/create', function(req, res) {
res.render('create/');
});
app.get('/create/artefact', function(req, res) {
res.render('create/artefact');
});
app.get('/create/location', function(req, res) {
res.render('create/location');
});
app.get('/create/institution', function(req, res) {
res.render('create/institution');
});
app.get('/create/person', function(req, res) {
res.render('create/person');
});
}; |
import _ from "lodash";
import types from "./types";
export const initState = {
uid: "",
items: [],
fullItems: [],
maxItems: 100,
totalItems: 0,
noData: true,
loading: false,
};
// initState.items = getAllItems();
const rootReducer = (state = initState, action) => {
let newState = { ...state };
switch (action.type) {
case types.SET_INFO_START:
newState.loading = true;
return newState;
case types.SET_INFO_SUCCESS:
newState.uid = action.payload;
newState.loading = false;
return newState;
case types.GET_ALL_ITEMS_START:
newState.loading = true;
return newState;
case types.GET_ALL_ITEMS_SUCCESS:
newState.loading = false;
newState.noData = false;
newState.items = action.data;
newState.fullItems = action.data;
newState.totalItems = action.totalItems;
return newState;
case types.ADD_ITEM_START:
newState.loading = true;
return newState;
case types.ADD_ITEM_SUCCESS:
newState.loading = false;
return newState;
case types.UPDATE_ITEM_START:
newState.loading = true;
return newState;
case types.UPDATE_ITEM_SUCCESS:
newState.loading = false;
return newState;
case types.SEARCHING:
newState.items = action.data;
return newState;
case types.NO_DATA_AVAILABLE:
newState.items = [];
newState.loading = false;
newState.noData = true;
newState.totalItems = 0;
return newState;
}
return newState;
};
export default rootReducer;
|
import React, {Component} from "react";
import "./style.css";
import ContactCard from "../ContactCard";
class ContactSection extends Component {
render(){
return(
<div className="wrappedSection">
<h2 className="categoryName">Category Name</h2>
<ContactCard />
</div>
);
}
}
export default ContactSection; |
var elements = require('../elements');
var Element = require('../element');
var ElementsArray = require('../elements_array');
/* ---- no args, return result ---- */
/**
* @param {String} methodName
* @param {Function} fn
*/
elements.addElementMethodWithoutArgumentsReturnResult = function(methodName, fn) {
Element.prototype[methodName] = fn ? function() {
return fn(this[0]);
} : function() {
return elements[methodName](this[0]);
};
Element.prototype[methodName].displayName = methodName;
};
/**
* @param {String} methodName
* @param {Function} fn
*/
elements.addElementsArrayMethodWithoutArgumentsReturnResult = function(methodName, fn) {
ElementsArray.prototype[methodName] = fn ? function() {
return this._map(function(e) {
return fn(e);
});
} : function() {
return this._map(function(e) {
return elements[methodName](e);
});
};
ElementsArray.prototype[methodName].displayName = methodName;
};
/**
* @param {String} methodName
* @param {Function} fn
*/
elements.addMethodWithoutArgumentsReturnResult = function(methodName, fn) {
elements.addElementMethodWithoutArgumentsReturnResult(methodName, fn);
elements.addElementsArrayMethodWithoutArgumentsReturnResult(methodName, fn);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.