text
stringlengths 7
3.69M
|
|---|
import React, { useState } from "react";
import Dashboardfooter from '../Layout/DashboardFooter';
import Dashboardheader from '../Layout/DashboardHeader';
import Dashboardsidebar from '../Layout/DashboardSideBar';
import images from "../../utils/ImageHelper";
import { compose } from "redux";
import { useFirebase, useFirestore, withFirestore } from "react-redux-firebase";
import { connect, useDispatch } from "react-redux";
import moment from "moment";
import * as actions from "../../redux/action/actions";
import OffersRate from "./OffersRate";
import ConfirmedOffer from "../Company/Offers/ConfirmedOffer";
import OffersPayment from "./Component/OffersPayment";
import { useHistory } from "react-router-dom";
import $ from "jquery";
import { toast } from "react-toastify";
import ModalsSlider from "../CommonComponents/ModalsSlider";
import ProfileView from "../CommonComponents/ProfileView";
const Offers = ({ chatsDetails, userDetails, offerList, notificationList, projectMaster, ...props }) => {
let history = useHistory();
const firebase = useFirestore();
const fireStore = useFirebase();
const dispatch = useDispatch();
const [dataList, setData] = useState([]);
const [active, setActive] = useState(0);
const [message, setMsg] = useState("");
const [userIdMessage, setUserIdMessage] = useState("");
const [projectIdMessage, setProjectIdMessage] = useState("");
const [imageList, setImages] = useState([]);
const [isOpenModal, setOpenModal] = useState(false);
const [isProfileModalOpen, setProfileModal] = useState(false);
const chatsList = (dataList[active] && dataList[active].chat) || []
const activeUser = dataList[active]
const sendBy = localStorage.getItem('userId')
const urlParams = new URLSearchParams(props.location.search);
const projectId = urlParams.get('projectId') || (activeUser && activeUser.projectId);
const companyId = urlParams.get('companyId') || (activeUser && activeUser.companyId);
const notificationIdPrivate = localStorage.getItem("notificationIdPrivate") || ""
const activeChatUser = (dataList && dataList[active]) || {}
const isChatActive = projectMaster.find(p => p.id === activeChatUser.projectId)
React.useEffect(() => {
firebase.setListeners([
{
collection: 'tblChatMessage',
storeAs: 'chatsDetails',
orderBy: ["updatedDate", "desc"],
limit: 10000
},
{
collection: 'tblUser',
storeAs: 'userDetails'
},
// {
// collection: 'tblOffer',
// storeAs: 'offerList'
// },
{
collection: 'tblProjectMaster',
storeAs: 'projectMaster'
},
])
dispatch(actions.setLoader(true));
}, [firebase])
React.useEffect(() => {
if(props && props.history && props.history.location && props.history.location.state){
const data = props.history.location.state
const filterData = chatsDetails.filter(k => k.userId === sendBy)
const dataItem = filterData.map(l => {
const user = userDetails.find(k => k.id === l.companyId)
if (user && user.Email) {
return ({
...l,
userName: user.FullName || (user.Email && user.Email.split("@")[0]),
profileImage: user.ProfileImage || null
})
}
}).filter((x) => x)
let findIndex = dataItem.findIndex((k) => k.companyId === data.companyId && k.projectId === data.projectId)
if (findIndex !== -1) {
setActive(findIndex)
// eslint-disable-next-line no-mixed-operators
if (((findIndex !== active) && data.companyId) || findIndex === 0 && data.companyId) {
readMsg(findIndex, dataItem)
}
}
}
}, [props && props.history && props.history.location && props.history.location.state])
React.useEffect(() => {
const record = notificationList.find((x) => x.id === notificationIdPrivate) || {}
if (record && record.id) {
firebase.collection("tblNotification").doc(record.id).set({
...record,
isRead: true
}).then((doc) => {
localStorage.removeItem("notificationIdPrivate")
}).catch(error => {
toast.error("Something went wrong please try again");
});
}
}, [notificationIdPrivate])
React.useEffect(() => {
if ((chatsDetails && chatsDetails.length) && (userDetails && userDetails.length)) {
const dataList = chatsDetails.filter(p => p.userId === sendBy)
const dataItem = dataList.map(l => {
const user = userDetails.find(k => k.id === l.companyId)
if (user && user.Email) {
return ({
...l,
userName: user.FullName || (user.Email && user.Email.split("@")[0]),
profileImage: user.ProfileImage || null
})
}
}).filter((x) => x)
if (props.location && props.location.search) {
const urlParams = new URLSearchParams(props.location.search);
const companyId = urlParams.get('companyId');
const projectId = urlParams.get('projectId');
let findIndex = dataItem.findIndex((k) => k.companyId === companyId && k.projectId === projectId)
if (findIndex !== -1) {
setActive(findIndex)
// eslint-disable-next-line no-mixed-operators
if (((findIndex !== active) && projectId) || findIndex === 0 && projectId) {
setUserIdMessage(companyId)
setProjectIdMessage(projectId)
if (companyId !== userIdMessage && projectId !== projectIdMessage) {
readMsg(findIndex, dataItem)
}
}
}
}
setData(dataItem.sort((a, b) => (b.updatedDate) - (a.updatedDate)))
if(dataList && dataList.length > 0){
if(companyId !== dataList[0].companyId || projectId !== dataList[0].projectId){
setActive(0);
history.push(`/offers?companyId=${dataList[0].companyId}&projectId=${dataList[0].projectId}`);
}
}
dispatch(actions.setLoader(false));
} else {
dispatch(actions.setLoader(false));
}
}, [chatsDetails, userDetails, notificationList])
React.useEffect(() => {
return () => {
firebase.unsetListeners([
{
collection: 'tblChatMessage',
storeAs: 'chatsDetails',
orderBy: ["updatedDate", "desc"],
limit: 10000
},
{
collection: 'tblUser',
storeAs: 'userDetails'
},
// {
// collection: 'tblOffer',
// storeAs: 'offerList'
// },
])
};
}, [firebase]);
const keyPressed = (target) => {
if (target.charCode === 13) {
sendMsg()
}
}
const readMsg = (activeSet, dataItem) => {
const activeChat = dataItem[activeSet]
if(activeChat.chat.filter(p => !p.isRead).length > 0){
const { projectId, userName, userId, createdAt, companyId, id, jobTitle, jobDescription, jobImage } = activeChat
if (activeChat && activeChat.chat && activeChat.chat.length) {
const readData = activeChat.chat.map(item => ({
...item,
isRead: true
}))
firebase.collection("tblChatMessage").doc(id).set({
chat: readData || [],
companyId,
projectId,
userName,
userId,
createdAt,
jobTitle: jobTitle || "",
jobDescription: jobDescription || "",
jobImage: jobImage || "",
updatedDate: new Date()
}).then((doc) => {
dispatch(actions.setLoader(false));
console.log("success")
}).catch(error => {
dispatch(actions.setLoader(false));
console.log("error")
});
}
}
}
const sendMsg = (downloadURL) => {
const tempMessage = message
setMsg("")
if (downloadURL || message) {
const details = dataList[active]
const { projectId, userName, userId, createdAt, companyId, jobTitle, jobDescription, jobImage } = details
const clone = details.chat ? [...details.chat] : []
const messageId = clone.length + 1
const obj = {
messageDate: new Date(),
message: downloadURL || message,
sendBy: sendBy,
sendTo: companyId,
isRead: false,
isReadCompany: false,
messageId: messageId
}
clone.push(obj)
// dispatch(actions.setLoader(true));
firebase.collection("tblChatMessage").doc(details.id).set({
chat: clone,
companyId,
projectId,
userName,
userId,
createdAt,
jobTitle: jobTitle || "",
jobDescription: jobDescription || "",
jobImage: jobImage || "",
updatedDate: new Date()
}).then(async (doc) => {
const user = userDetails.find(k => k.id === companyId)
const loginUserDetails = userDetails.find(k => k.id === sendBy)
if (user && user.IsLogin === false) {
sendMail(user, loginUserDetails, jobTitle, tempMessage, userId, projectId)
}
console.log("success")
}).catch(error => {
setMsg("")
// dispatch(actions.setLoader(false));
console.log("error")
});
}
}
const sendMail = async (user, loginUserDetails, jobTitle, tempMessage, userId, projectId) => {
let response = await fetch(`${process.env.REACT_APP_API_SENDMAIL}?dest=${user.Email}&emailName=chat&docId=""&projectTitle=${jobTitle}&name=${loginUserDetails.FullName || loginUserDetails.UserName}&message=${tempMessage}&messageLink=${window.location.origin}/company/company-offers?userId=${userId}&projectId=${projectId}`, {
method: "GET",
});
response.json().then((res) => {
console.log("res", res)
}).catch((e) => {
console.log("e", e)
})
}
const handleImageSend = (e) => {
const file = (e.target && e.target.files && e.target.files[0])
if(file){
fireStore.uploadFile('/image', file).then((data) => {
data.uploadTaskSnapshot.ref.getDownloadURL().then(function (downloadURL) {
sendMsg(downloadURL)
});
})
}
}
// const acceptOfferPrivate = (info) => {
// firebase.collection("tblOffer").doc(info.id).set({
// ...info,
// isUserAccepted: true,
// isNewOffer: false,
// isReadNotification: false
// }).then((doc) => {
// const findCurrentNotification = (notificationList || []).find((x) => x.companyId === info.companyId && x.userId === info.userId && x.projectId === info.projectId && x.notificationType === "new" && x.isRead === false)
// // const findCurrentNotificationCompanyConform = (notificationList || []).find((x) => x.companyId === info.companyId && x.userId === info.userId && x.projectId === info.projectId && x.notificationType === "companyConform" && x.isRead === false)
// firebase.collection("tblNotification").add({
// companyId: info.companyId,
// userId: sendBy,
// createdAt: new Date(),
// projectId: info.projectId,
// notificationType: "userAccepted",
// isRead: false,
// isDeleted: false,
// notificationMessage: `${activeUser.userName} accepted your offer`
// }).then((res) => {
// if (findCurrentNotification && findCurrentNotification.id) {
// firebase.collection("tblNotification").doc(findCurrentNotification.id).set({
// ...findCurrentNotification,
// isRead: true
// })
// } /*else {
// if (findCurrentNotificationCompanyConform && findCurrentNotificationCompanyConform.id) {
// firebase.collection("tblNotification").doc(findCurrentNotificationCompanyConform.id).set({
// ...findCurrentNotificationCompanyConform,
// isRead: true
// })
// }
// }*/
// }).catch(error => {
// console.log("error")
// });
// dispatch(actions.setLoader(false));
// console.log("success")
// }).catch(error => {
// dispatch(actions.setLoader(false));
// console.log("error")
// });
// }
// const rejectOfferPrivate = (info) => {
// firebase.collection("tblOffer").doc(info.id).set({
// ...info,
// isUserRejected: true,
// isReadNotification: false,
// isPaid: true
// }).then((doc) => {
// const findCurrentNotification = (notificationList || []).find((x) => x.companyId === info.companyId && x.userId === info.userId && x.projectId === info.projectId && x.notificationType === "CompanyCompleted" && x.isRead === false)
// firebase.collection("tblNotification").add({
// companyId: info.companyId,
// userId: sendBy,
// createdAt: new Date(),
// projectId: info.projectId,
// notificationType: "offerRejected",
// isRead: false,
// isDeleted: false,
// notificationMessage: `${activeUser.userName} reject your offer`
// }).then((res) => {
// if (findCurrentNotification && findCurrentNotification.id) {
// firebase.collection("tblNotification").doc(findCurrentNotification.id).set({
// ...findCurrentNotification,
// isRead: true
// })
// }
// }).catch(error => {
// console.log("error")
// });
// }).catch(error => {
// console.log("error")
// });
// }
// const userConfirm = (info) => {
// firebase.collection("tblOffer").doc(info.id).set({
// ...info,
// isUserAccepted: true,
// isUserCompleted: true,
// }).then((doc) => {
// const findCurrentNotification = (notificationList || []).find((x) => x.companyId === info.companyId && x.userId === info.userId && x.projectId === info.projectId && x.notificationType === "CompanyCompleted" && x.isRead === false)
// firebase.collection("tblNotification").add({
// companyId: info.companyId,
// userId: sendBy,
// createdAt: new Date(),
// projectId: info.projectId,
// notificationType: "userCompleted",
// isRead: false,
// isDeleted: false,
// notificationMessage: `${activeUser.userName} completed your offer`
// }).then((res) => {
// if (findCurrentNotification && findCurrentNotification.id) {
// firebase.collection("tblNotification").doc(findCurrentNotification.id).set({
// ...findCurrentNotification,
// isRead: true
// })
// }
// }).catch(error => {
// console.log("error")
// });
// dispatch(actions.setLoader(false));
// console.log("success")
// }).catch(error => {
// dispatch(actions.setLoader(false));
// console.log("error")
// });
// }
// const makePayment = (info) => {
// dispatch(actions.setLoader(true));
// firebase.collection("tblOffer").doc(info.id).set({
// ...info,
// isPaid: true
// }).then((doc) => {
// firebase.collection("tblNotification").add({
// companyId: info.companyId,
// userId: sendBy,
// createdAt: new Date(),
// projectId: info.projectId,
// notificationType: "paymentComplete",
// isRead: false,
// isDeleted: false,
// notificationMessage: `${activeUser.userName} complete your offer payment`
// })
// firebase.collection("tblPaidPaymentInfo").add({
// companyId: info.companyId,
// userId: sendBy,
// projectId: info.projectId,
// amount: info.offerAmount,
// createdDate: new Date(),
// offerId: info.id
// })
// dispatch(actions.setLoader(false));
// toast.success("Payment Successfully")
// }).catch(error => {
// dispatch(actions.setLoader(false));
// toast.error("Something went wrong please try again")
// });
// }
const scroll = () => {
setTimeout(() => {
var div = document.getElementById("scroll");
if (div && div.scrollHeight) {
div.scrollTop = div.scrollHeight;
}
}, 0.00)
}
const onChetUser = (record, index) => {
setActive(index)
history.push(`/offers?companyId=${record.companyId}&projectId=${record.projectId}`);
const urlParams = new URLSearchParams(props.location.search);
const companyId = urlParams.get('companyId');
const projectId = urlParams.get('projectId');
const dataList = chatsDetails.filter(p => p.userId === sendBy)
const dataItem = dataList.map(l => {
const user = userDetails.find(k => k.id === l.companyId)
if (user && user.Email) {
return ({
...l,
userName: user.FullName || (user.Email && user.Email.split("@")[0]),
profileImage: user.ProfileImage || null
})
}
}).filter((x) => x)
let findIndex = dataItem.findIndex((k) => k.companyId === companyId && k.projectId === projectId)
if(findIndex !== -1){
readMsg(findIndex, dataItem)
}
}
const unlockJob = () =>{
const selectedUser = userDetails.find(k => k.id === activeChatUser.companyId)
firebase.collection("tblProjectMaster").doc(isChatActive.id).set({
...isChatActive,
isProjectLocked: false
}).then((doc) => {
firebase.collection("tblNotification").add({
companyId: selectedUser.id,
userId: sendBy,
createdAt: new Date(),
projectId: isChatActive.id,
notificationType: "cancelChat",
isRead: false,
isDeleted: false,
notificationMessage: `${isChatActive.Title} cancel offer from ${isChatActive.nameOfUser}`
}).then((res) => {
}).catch((e) => {
})
console.log("success")
}).catch(error => {
console.log("error")
});
}
const backUser = () => {
$(".chat-main-wrapper").removeClass('d-none');
}
$(window).resize(function () {
var widthWindow = $(window).width();
if (widthWindow <= '767') {
$('#chat-user-box').addClass('w-100');
$('#user-click').addClass('d-none');
$("#chat-active-user").removeClass('d-none');
$(".chat-main-wrapper").on('click', function (event) {
if (window.innerWidth <= 767) {
$(".chat-main-wrapper").addClass('d-none');
$('.chat-profile-view').addClass('d-none');
}
});
} else {
$('#chat-user-box').removeClass('w-100');
$('#user-click').removeClass('d-none');
$(".chat-main-wrapper").removeClass('d-none');
$("#chat-active-user").addClass('d-none');
$('.chat-profile-view').removeClass('d-none');
}
});
const handleModal = (img) => {
if (Array.isArray(img)) {
setImages(img)
setOpenModal(true)
} else {
setImages([])
setOpenModal(false)
}
}
const handleProfileModal = () =>{
setProfileModal(!isProfileModalOpen)
}
const selectedUser = userDetails.find(k => k.id === activeChatUser.companyId)
const projectDetails = (projectMaster || []).find(l => l.id === (activeUser && activeUser.projectId))
const aa = dataList.sort((a, b) => (b.messageDate) - (a.messageDate))
return (
<div id="wrapper">
<Dashboardheader />
<Dashboardsidebar />
{isProfileModalOpen &&
<ProfileView
isOpenModal={isProfileModalOpen}
profileDetails={selectedUser}
projectDetails={projectDetails}
closeModal={handleProfileModal}/>}
{/* {isOpenModal && <ModalsSlider isOpenModal={isOpenModal} handleModal={handleModal} imageList={imageList} />}*/}
<div className="chatwapper">
<div className="chat-main-wrapper" id="chat-user-box">
{
dataList.length > 0 ?
dataList.map((item, ind) => {
// const chatsList = (dataList[ind] && dataList[ind].chat) || []
// const offIds = chatsList.filter(p => p.offerId).map(k => k.offerId)
// let totalAmt = 0
// if ((offIds && offIds.length) > 0) {
// let allItem = []
//
// if (offerList && offerList.length && offIds && offIds.length) {
// offIds.forEach(t => {
// const isPaid = offerList.find(p => t === p.id && p.isCompanyConform)
// if (isPaid && isPaid.id) {
// allItem.push(isPaid)
// }
// })
//
// if (allItem && allItem.length) {
// const allData = allItem.map(l => Number(l.offerAmount))
// if (allData.length > 0) {
// totalAmt = allData.reduce(function (a, b) {
// return a + b;
// }, 0);
// }
// }
// }
// }
// const activeUserOffer = offerList.filter(l => (l.userId === item.userId) && (l.projectId === item.projectId))
// let isUserAccepted = false
// if (activeUserOffer.length > 0) {
// isUserAccepted = activeUserOffer[activeUserOffer.length - 1].isUserAccepted
// }
const time = (item && item.updatedDate && item.updatedDate.seconds) || ""
const date = time ? moment(new Date((time) * 1000)).fromNow(true) : ""
return (
<div key={ind} id="active-chat-user" className={`chat-side-box chatbox-body ${active === ind ? 'active' : ''}`} onClick={() => onChetUser(item, ind)}>
<a className="chat-img">
<img src={item.jobImage || images.privatelogo} alt="img" />
</a>
<div className="chat-box-body">
<h5>{item.userName}</h5>
<h5>{item.jobTitle}</h5>
<h6>{/*{isUserAccepted && 'ACCEPTED'}*/} <span>{date}</span></h6>
</div>
{/* <div className="salary">
<span>New</span>
<a>${totalAmt}</a>
</div>*/}
</div>
)
}) : "Inga aktiva uppdrag"
}
{/*<div className="chat-side-box chatbox-body opasity-box">*/}
{/* <a className="chat-img" href="/#">*/}
{/* <img src={images.chat1} alt=""></img>*/}
{/* </a>*/}
{/* <div className="chat-box-body">*/}
{/* <h5>Matthew Scott</h5>*/}
{/* <h4>12 Hours Ago</h4>*/}
{/* </div>*/}
{/* <div className="salary">*/}
{/* <a href="/#">$2000</a>*/}
{/* </div>*/}
{/*</div>*/}
</div>
<div className="chat-main-box" id="chat-msg-box">
{
(selectedUser && selectedUser.Email) &&
<div className="chat-profile-view">
<img style={{maxWidth: 75}} src={(selectedUser && selectedUser.ProfileImage) || images.avatarImg} alt={selectedUser && selectedUser.userName}/>
<p>{selectedUser && selectedUser.FullName}</p>
<button className="greenfill-btnbox" onClick={handleProfileModal}>Visa detaljer</button>
</div>
}
<div id="chat-active-user" className="chat-active-user">
<button id="back-btn" className="back-btn" onClick={() => backUser()}><i className="fas fa-arrow-left" /></button>
{
(selectedUser && selectedUser.Email) &&
<div className="res-user-img">
<img style={{maxWidth: 75}} src={(selectedUser && selectedUser.ProfileImage) || images.avatarImg} alt={selectedUser && selectedUser.userName}/>
</div>
}
<div className="chat-active-user-name">
<p>{activeChatUser && activeChatUser.userName}</p>
<p>{activeChatUser && activeChatUser.jobTitle}</p>
</div>
<button className="greenfill-btnbox" onClick={handleProfileModal}>Visa detaljer</button>
</div>
<div className="chat-inner-wrap" id={"scroll"}>
<div className="chat-inner">
{
// eslint-disable-next-line array-callback-return
chatsList.map((obj, i) => {
const date = new Date(obj.messageDate.seconds * 1000)
const time = moment(date).format('hh:mm A')
const isImage = obj.message.includes("googleapis")
// const isOffer = offerList.find(p => p.id === obj.offerId)
if ((chatsList && chatsList.length) === (i + 1)) {
scroll()
}
if (obj.message) {
return (
<div key={i} className={`row m-b-0 ${sendBy === obj.sendBy ? "send-chat" : "received-chat"}`}>
<div className="col">
<div className={`m-b-20 ${!isImage ? 'msg' : ''}`}>
<div className={`${!isImage ? '' : 'chatimg'}`}>
{
isImage ? <img src={obj.message} alt="img" onClick={() => handleModal([obj.message])} /> : <p>{obj.message}</p>
}
</div>
</div>
<p className="timetext">{time}</p>
</div>
</div>
)
}
// if (isOffer && isOffer.id) {
// const details = dataList[active]
// const offerDate = new Date((isOffer.createdAt && isOffer.createdAt.seconds) * 1000)
// const offerTime = moment(offerDate).format('hh:mm A')
// const sendToUser = userDetails.find(l => l.id === obj.sendTo)
// const sendByUser = userDetails.find(l => l.id === obj.sendBy)
//
// if (isOffer.isCompanyConform && isOffer.isUserAccepted && !isOffer.isCompanyCompleted) {
// return (
// <ConfirmedOffer
// key={i}
// sendToUser={sendToUser}
// sendByUser={sendByUser}
// isOffer={isOffer} />)
// } else if (isOffer.isUserAccepted && !isOffer.isCompanyCompleted) {
// return (
// <div className="accepted-box-bg m-b-0" key={i}>
// <div className="accepted-box-body offer_conform">
// <div className="right-img">
// <img src={sendToUser.ProfileImage || images.avatarImg} />
// <h5>{sendToUser.FullName}</h5>
// </div>
// <div className="line-wrapper">
// <a>${isOffer.offerAmount}</a>
// </div>
// <div className="right-img left-img">
// <img src={sendByUser.ProfileImage || images.avatarImg} />
// <h5>{sendByUser.FullName}</h5>
// </div>
// </div>
// <div className="bottom-two-btn private-confirm-msg">
// <a className="bottom-two-box mb-0">
// Accepted <i className="fa fa-check" aria-hidden="true" />
// </a>
// <h6>Confirmation Awaits!</h6>
// </div>
// </div>
// )
// } else if (isOffer.isCompanyCompleted && !isOffer.isUserCompleted) {
// return (
// <div className="offerbox-main chat-line" key={i}>
// <div className="offerbox-main-wrapper-box">
// <a className="chat-img">
// {details.jobImage && <img src={details.jobImage} />}
// </a>
// <div className="offer-body-wrapper">
// <h5>Work is Finished</h5>
// <h4>{offerTime}</h4>
// </div>
// </div>
// <div className="offer-price">
// <a>${isOffer.offerAmount}</a>
// </div>
// <div className="offer-message">
// <a className="confirm-btn" onClick={() => userConfirm(isOffer)}>Confirm</a>
// </div>
// <div className="offer-greenbox">
// <p>Worker has marked the job as completed, Please confirm the job has been done!</p>
// </div>
// </div>
// )
// } else if (isOffer.isUserCompleted) {
// return (
// <OffersPayment
// key={i}
// sendToUser={sendToUser}
// sendByUser={sendByUser}
// isOffer={isOffer}
// isPaid={isOffer.isPaid}
// projectId={projectId}
// companyId={companyId}
// makePayment={() => makePayment(isOffer)} />)
// } else {
// return (
// <div key={i} className="offerbox-main">
// <div className="offerbox-main-wrapper-box">
// <a className="chat-img">
// {details.jobImage && <img src={details.jobImage} />}
// </a>
// <div className="chat-box-body">
// <h5>{details.jobTitle}</h5>
// <h4>{offerTime}</h4>
// </div>
// </div>
// <div className="offer-price">
// <a>${isOffer.offerAmount}</a>
// </div>
// <div className="private-offer-btn">
// {
// isOffer.isUserRejected &&
// <div className="bottom-two-btn private-confirm-msg">
// <h6>Rejected!</h6>
// </div>
// }
// {
// !isOffer.isUserRejected && <a className="reject-btn" onClick={() => rejectOfferPrivate(isOffer)}>Reject</a>
// }
// {
// !isOffer.isUserRejected && <a onClick={() => acceptOfferPrivate(isOffer)}>Accept</a>
// }
// </div>
// </div>)
// }
// }
})
}
</div>
</div>
{/*<div className="sendoffer-box">*/}
{/* <div className="send-offer">*/}
{/* <div className="send-inner-box">*/}
{/* <h5>Send New <br /> Offer</h5>*/}
{/* <div className="offerbox">*/}
{/* <input type="number" placeholder="$650" />*/}
{/* </div>*/}
{/* <div className="send-btn">*/}
{/* <a>Send</a>*/}
{/* </div>*/}
{/* <a className="close-btn"><i className="fas fa-times" /></a>*/}
{/* </div>*/}
{/* </div>*/}
{/*</div>*/}
{
((dataList && dataList.length) > 0) && <div className="sendchat-box">
<div className="dolarbox">
{
isChatActive && isChatActive.isProjectLocked &&
<button className="close-chat" onClick={unlockJob}>Återpublicera uppdrag</button>
}
<div className="lingicon paperclip">
<div className="file-wrapper">
<input type="file" className="upload_btn" onChange={handleImageSend} />
<i className="fas fa-paperclip clipicon" />
</div>
<input className="message-box"
value={message}
onKeyPress={keyPressed}
onChange={(e) => setMsg(e.target.value)}
type="text" placeholder="Skriv ett meddelande…" />
<a><i className="fas fa-paper-plane papericon" onClick={() => sendMsg()} /></a>
</div>
</div>
</div>
}
</div>
</div>
</div>
);
}
export default compose(
withFirestore,
connect((state) => ({
chatsDetails: (state.firestore.ordered && state.firestore.ordered.chatsDetails) || [],
userDetails: (state.firestore.ordered && state.firestore.ordered.userDetails) || [],
// offerList: (state.firestore.ordered && state.firestore.ordered.offerList) || [],
notificationList: (state.firestore.ordered && state.firestore.ordered.notificationList) || [],
projectMaster: (state.firestore.ordered && state.firestore.ordered.projectMaster) || [],
}))
)(Offers)
|
var myApp = angular.module("webservice", ['ngResource']);
myApp.constant("baseUrl", "http://angularkea.azurewebsites.net/api/Internships/")
.controller("internshipsResourceController",
['$scope','$resource', 'baseUrl', '$stateParams', '$state',
function($scope, $resource, baseUrl, $stateParams, $state) {
$scope.visit = {};
$('.datepicker').pickadate();
console.log($stateParams.internship);
if ($stateParams.internship) {
$scope.visit = $stateParams.internship;
}
$scope.internshipsResource = $resource(baseUrl + ":id",
{ id: "@id"},{
update: {
method: 'PUT'
}
}
);
$scope.deleteVisit = function(internship){
var that = $scope.$parent;
internship.$delete({ id: internship._id }, function() {
that.internshipVisits.splice(
that.internshipVisits.indexOf(internship), 1);
$state.go('all-internships');
});
};
$scope.createInternship = function(internship) {
var that = $scope.$parent; //get a ref to parent controllers scope
//to be used inside $save - function
new $scope.internshipsResource(internship).$save(
function(newInternship) {
that.internshipVisits.push(newInternship);
$state.go('all-internships');
});
};
$scope.updateInternship = function(internship) {
new $scope.internshipsResource(internship).$update( {id: internship._id},
function() {
$state.go('all-internships');
});
};
$scope.saveVisit = function(){
var internship = $scope.visit;
if ($scope.visitForm.$valid) {
if (angular.isDefined(internship._id)) {
//update
$scope.updateInternship(internship);
}
else {
$scope.createInternship(internship);
}
}
};
}]);
|
angular.module('ngApp.express').controller("ExpressManifestController", function ($scope, $uibModal, ModalService, SessionService, config, $window, AppSpinner, ExpressManifestService, DirectBookingService, $rootScope, toaster, ExpressShipmentService, $http, $translate) {
//multilingual translation key
var setMultilingualOptions = function () {
$translate(['FrayteError', 'FrayteWarning', 'FrayteSuccess', 'Export_Manifest_Downloaded_Successfully', 'Driver_Manifest_Downloaded_Successfully',
'ReportCannotDownloadPleaseTryAgain', 'Could_Not_Download_TheReport', 'ErrorGettingRecord', 'To_Date', 'From_Date', 'To_Date_Validation', 'LoadingManifests',
'DownLoading_Driver_Manifest_PDF', 'DownLoad_Export_Manifest_PDF', 'DownLoading_Custom_Manifest', 'Custom_Manifest_Downloaded_Successfully']).then(function (translations) {
$scope.FrayteWarning = translations.FrayteWarning;
$scope.FrayteSuccess = translations.FrayteSuccess;
$scope.FrayteError = translations.FrayteError;
$scope.Export_Manifest_Downloaded_Successfully = translations.Export_Manifest_Downloaded_Successfully;
$scope.Driver_Manifest_Downloaded_Successfully = translations.Driver_Manifest_Downloaded_Successfully;
$scope.ReportCannotDownloadPleaseTryAgain = translations.ReportCannotDownloadPleaseTryAgain;
$scope.Could_Not_Download_TheReport = translations.Could_Not_Download_TheReport;
$scope.ErrorGettingRecord = translations.ErrorGettingRecord;
$scope.Loading_Manifests = translations.LoadingManifests;
$scope.To_Date = translations.To_Date;
$scope.From_Date = translations.From_Date;
$scope.To_Date_Validation = translations.To_Date_Validation;
$scope.DownLoading_Driver_Manifest_PDF = translations.DownLoading_Driver_Manifest_PDF;
$scope.DownLoad_Export_Manifest_PDF = translations.DownLoad_Export_Manifest_PDF;
$scope.DownLoading_Custom_Manifest = translations.DownLoading_Custom_Manifest;
$scope.Custom_Manifest_Downloaded_Successfully = translations.Custom_Manifest_Downloaded_Successfully;
$scope.getDetails();
});
};
$scope.shipmentDetail = function (TradelaneShipmentId) {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'tradelaneBooking/tradelaneBookingDetail/tradelaneBookingDetail.tpl.html',
controller: 'TradelaneBookingDetailController',
windowClass: 'CustomerAddress-Edit',
size: 'lg',
backdrop: 'static',
keyboard: false,
resolve: {
ShipmentId: function () {
return TradelaneShipmentId;
},
ModuleType: function () {
return "ExpressBooking";
}
}
});
modalInstance.result.then(function (response) {
// $state.go("loginView.userTabs.tradelane-shipments");
}, function () {
// $state.go("loginView.userTabs.tradelane-shipments");
});
};
$scope.expressUpdateMAWB = function (TradelaneShipmentId) {
var modalInstance = $uibModal.open({
Animation: true,
controller: 'ExpressUpdateManifestController',
templateUrl: 'express/expressManifest/updateMAWB.tpl.html',
keyboard: true,
size: 'lg',
backdrop: 'static',
resolve: {
ShipmentId: function () {
return TradelaneShipmentId;
}
}
});
modalInstance.result.then(function (response) {
}, function () {
});
};
$scope.ChangeFromdate = function (FromDate) {
$scope.TrackManifest.FromDate = $scope.SetTimeinDateObj(FromDate);
if ($scope.TrackManifest.ToDate === undefined || $scope.TrackManifest.ToDate === '' || $scope.TrackManifest.ToDate === null) {
$scope.TrackManifest.ToDate = new Date();
}
};
$scope.ChangeTodate = function (ToDate) {
$scope.TrackManifest.ToDate = $scope.SetTimeinDateObj(ToDate);
};
$scope.SetTimeinDateObj = function (DateValue) {
var newdate1 = new Date();
newdate = new Date(DateValue);
var gtDate = newdate.getDate();
var gtMonth = newdate.getMonth();
var gtYear = newdate.getFullYear();
var hour = newdate1.getHours();
var min = newdate1.getMinutes();
var Sec = newdate1.getSeconds();
var MilSec = new Date().getMilliseconds();
return new Date(gtYear, gtMonth, gtDate, hour, min, Sec, MilSec);
};
$scope.GetManifest = function (Searchtext) {
if (($scope.TrackManifest.ToDate === '' || $scope.TrackManifest.ToDate === null || $scope.TrackManifest.ToDate === undefined) && ($scope.TrackManifest.FromDate === '' || $scope.TrackManifest.FromDate === null || $scope.TrackManifest.FromDate === undefined)) {
AppSpinner.hideSpinnerTemplate();
}
else if (($scope.TrackManifest.ToDate !== null || $scope.TrackManifest.ToDate !== '' || $scope.TrackManifest.ToDate !== undefined) && ($scope.TrackManifest.FromDate === undefined || $scope.TrackManifest.FromDate === '' || $scope.TrackManifest.FromDate === null)) {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.From_Date,
showCloseButton: true
});
AppSpinner.hideSpinnerTemplate();
return;
}
else if (($scope.TrackManifest.ToDate === null || $scope.TrackManifest.ToDate === '' || $scope.TrackManifest.ToDate === undefined) && ($scope.TrackManifest.FromDate !== undefined || $scope.TrackManifest.FromDate !== '' || $scope.TrackManifest.FromDate !== null)) {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.To_Date,
showCloseButton: true
});
AppSpinner.hideSpinnerTemplate();
return;
}
else {
AppSpinner.hideSpinnerTemplate();
if (($scope.TrackManifest.FromDate !== undefined || $scope.TrackManifest.FromDate !== null || $scope.TrackManifest.FromDate !== "") && ($scope.TrackManifest.ToDate !== undefined || $scope.TrackManifest.ToDate !== null || $scope.TrackManifest.ToDate !== "")) {
var fromDate = new Date($scope.TrackManifest.FromDate);
var toDate = new Date($scope.TrackManifest.ToDate);
var from = (fromDate.getDate().toString().length === 1 ? "0" + fromDate.getDate() : fromDate.getDate()) + '/' + ((fromDate.getMonth() + 1).toString().length === 1 ? "0" + (fromDate.getMonth() + 1) : (fromDate.getMonth() + 1)) + '/' + fromDate.getFullYear();
var to = (toDate.getDate().toString().length === 1 ? "0" + toDate.getDate() : toDate.getDate()) + '/' + ((toDate.getMonth() + 1).toString().length === 1 ? "0" + (toDate.getMonth() + 1) : (toDate.getMonth() + 1)) + '/' + toDate.getFullYear();
var dateOne = new Date(from);
var dateTwo = new Date(to);
if (new Date(dateOne) > new Date(dateTwo)) {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.To_Date_Validation,
showCloseButton: true
});
return;
}
}
}
AppSpinner.showSpinnerTemplate($scope.Loading_Manifests, $scope.Template);
ExpressManifestService.GetManifestDetail($scope.TrackManifest).then(function (response) {
$scope.ManifestData = response.data;
if (response.data !== null && response.data.length > 0) {
$scope.totalItemCount = response.data[0].TotalRows;
}
else {
$scope.totalItemCount = 0;
}
if (response.data != null && response.data.length > 0) {
for (i = 0; i < response.data.length; i++) {
var date = new Date(response.data[i].CreatedOn);
var days = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var getdt = date.getDate();
var getmn1 = days[date.getMonth()];
var getyr = date.getFullYear();
response.data[i].CreatedOn = getdt + "-" + getmn1 + "-" + getyr + " " + response.data[i].CreatedOnTime;
}
}
AppSpinner.hideSpinnerTemplate();
}, function (response) {
AppSpinner.hideSpinnerTemplate();
if (response.status !== 401) {
toaster.pop({
type: "error",
title: $scope.FrayteError,
body: $scope.ErrorGettingRecord,
showCloseButton: true
});
}
});
};
$scope.openCalender = function ($event) {
$scope.status.opened = true;
};
$scope.openCalender1 = function ($event) {
$scope.status1.opened = true;
};
$scope.status1 = {
opened: false
};
$scope.status = {
opened: false
};
$scope.pageChanged = function (TrackManifest) {
$scope.GetManifest();
};
$scope.getDetails = function () {
$rootScope.rootModuleType = $scope.TrackManifest.ModuleType;
$scope.GetManifest();
};
$scope.getCustomerDetail = function (CustomerDetail) {
if (CustomerDetail !== undefined && CustomerDetail !== null && CustomerDetail !== '') {
$scope.CustomerId = CustomerDetail.CustomerId;
$scope.TrackManifest.UserId = CustomerDetail.CustomerId;
$rootScope.CustomerManId = CustomerDetail.CustomerId;
//$rootScope.isShow = true;
}
};
$scope.toggleMin = function () {
$scope.dateOptions.minDate = $scope.dateOptions.minDate ? null : new Date();
};
$scope.toggleMin1 = function () {
$scope.dateOptions1.minDate = $scope.dateOptions1.minDate ? null : new Date();
};
$scope.$watch('TrackManifest.ToDate', function () {
if ($scope.TrackManifest !== undefined && $scope.TrackManifest !== null && $scope.TrackManifest.ToDate !== undefined && $scope.TrackManifest.ToDate !== null && $scope.TrackManifest.ToDate !== "" && $scope.TrackManifest.ToDate.getFullYear() === 1970) {
$scope.TrackManifest.ToDate = null;
}
});
$scope.$watch('TrackManifest.FromDate', function () {
if ($scope.TrackManifest !== undefined && $scope.TrackManifest !== null && $scope.TrackManifest.FromDate !== undefined && $scope.TrackManifest.FromDate !== null && $scope.TrackManifest.FromDate !== "" && $scope.TrackManifest.FromDate.getFullYear() === 1970) {
$scope.TrackManifest.FromDate = null;
}
});
//breakbulk purchase order detail code
$scope.ExpressViewManifest = function (ManifestId) {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'express/expressManifest/expressViewManifest.tpl.html',
controller: 'ExpressViewManifestController',
windowClass: 'CustomerAddress-Edit',
size: 'lg',
backdrop: 'static',
keyboard: false,
resolve: {
ManifestId: function () {
return ManifestId;
}
}
});
modalInstance.result.then(function (response) {
}, function () {
});
};
//breakbulk purchase order detail code
$scope.breakbulkAddManifest = function () {
ModalInstance = $uibModal.open({
Animation: true,
controller: 'ExpressUpdateManifestController',
templateUrl: 'express/expressManifest/updateMAWB.tpl.html',
keyboard: true,
size: 'lg',
backdrop: 'static'
});
};
$scope.GetCustomers = function () {
if ($scope.RoleId === 6 || $scope.RoleId === 1 || $scope.RoleId === 20) {
ExpressShipmentService.GetExpressCustomers($scope.RoleId, $scope.createdBy).then(function (response) {
if (response !== null && response.data.length > 0) {
$scope.ManifestCustomers = [];
for (var i = 0; i < response.data.length; i++) {
$scope.Customer = {
CustomerId: "",
CompanyName: ""
};
$scope.Customer.CustomerId = response.data[i].CustomerId;
$scope.Customer.CompanyName = response.data[i].CompanyName + ' - ' + accBreak(response.data[i].AccountNumber.length, response.data[i].AccountNumber);
$scope.ManifestCustomers.push($scope.Customer);
}
$scope.CustomerId = $scope.ManifestCustomers[0].CustomerId;
if ($scope.RoleId === 1) {
$scope.ManifestCustomers.unshift({ CustomerId: 0, CompanyName: 'All' });
$scope.CustomerDetail = $scope.ManifestCustomers[0];
$scope.TrackManifest.UserId = $scope.ManifestCustomers[0].CustomerId;
}
else if ($scope.RoleId === 6) {
$scope.ManifestCustomers.unshift({ CustomerId: 0, CompanyName: 'All' });
$scope.CustomerDetail = $scope.ManifestCustomers[0];
$scope.TrackManifest.UserId = $scope.ManifestCustomers[0].CustomerId;
}
else if ($scope.RoleId === 20) {
$scope.ManifestCustomers.unshift({ CustomerId: $scope.createdBy, CompanyName: 'All' });
$scope.CustomerDetail = $scope.ManifestCustomers[0];
$scope.TrackManifest.UserId = $scope.ManifestCustomers[0].CustomerId;
}
$rootScope.isShow = true;
if ($rootScope.ChangeExpressManifest === true) {
$scope.ExpressCreateManifest();
$rootScope.ShowManifestButton = false;
$rootScope.ChangeExpressManifest = false;
}
else {
$rootScope.ShowManifestButton = false;
}
}
});
$scope.TrackManifest.CreatedBy = 0;
}
var accBreak = function (fiterCountryLength, AccountNo) {
var AccNo = AccountNo.split('');
var AccNonew = [];
AccNonew2 = "";
if (fiterCountryLength <= 3) {
for (j = 0; j < fiterCountryLength; j++) {
if (j === 0) {
AccNonew.push('a');
}
AccNonew.push(AccNo[j]);
}
AccNonew.splice(0, 1);
for (jj = 0; jj < AccNonew.length; jj++) {
AccNonew2 = AccNonew2 + AccNonew[jj].toString();
}
}
else if (fiterCountryLength >= 4 && fiterCountryLength <= 8) {
for (j = 0; j < fiterCountryLength; j++) {
if (j === 0) {
AccNonew.push('a');
}
AccNonew.push(AccNo[j]);
}
AccNonew.splice(0, 1);
for (jj = 0; jj < AccNonew.length; jj++) {
AccNonew2 = AccNonew2 + AccNonew[jj].toString();
}
}
else if (fiterCountryLength > 8) {
for (j = 0; j < fiterCountryLength; j++) {
if (j === 0) {
AccNonew.push('a');
}
AccNonew.push(AccNo[j]);
}
AccNonew.splice(0, 1);
for (jj = 0; jj < AccNonew.length; jj++) {
if (jj === 3) {
AccNonew2 = AccNonew2 + '-' + AccNonew[jj].toString();
}
else if (jj === 6) {
AccNonew2 = AccNonew2 + '-' + AccNonew[jj].toString();
}
else {
AccNonew2 = AccNonew2 + AccNonew[jj].toString();
}
}
}
return AccNonew2;
};
};
$scope.ExpressCreateManifest = function () {
var ModalInstance = $uibModal.open({
animation: true,
controller: 'expressManifestGeneratorController',
templateUrl: 'express/expressManifest/expressManifestGenerator.tpl.html',
resolve: {
TrackObj: function () {
return $scope.TrackManifest;
}
},
backdrop: true,
size: 'lg',
windowClass: 'CustomerAddress-Edit',
keyboard: false
});
};
$scope.DownLoadExportManifestPDF = function (ManifestDetail) {
AppSpinner.showSpinnerTemplate($scope.DownLoad_Export_Manifest_PDF, $scope.Template);
$scope.PdfDownloadModel.TradelaneShipmentId = ManifestDetail.TradelaneShipmentId;
$scope.PdfDownloadModel.CustomerId = ManifestDetail.CustomerId;
$scope.PdfDownloadModel.UserId = $scope.createdBy;
ExpressManifestService.GetExportManifest($scope.PdfDownloadModel).then(function (response) {
AppSpinner.hideSpinnerTemplate();
if (response.data !== null) {
var fileInfo = response.data;
var File = {
FileName: response.data.FileName,
TradelaneShipmentId: ManifestDetail.TradelaneShipmentId,
FilePath: response.data.FilePath
};
$http({
method: 'POST',
url: config.SERVICE_URL + '/ExpressManifest/DownloadExpressReport',
data: File,
responseType: 'arraybuffer'
}).success(function (data, status, headers) {
if (status == 200 && data !== null) {
headers = headers();
var filename = headers['x-filename'];
var contentType = headers['content-type'];
var linkElement = document.createElement('a');
try {
if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
alert("Browser is Safari");
}
else {
var blob = new Blob([data], { type: contentType });
var url = window.URL.createObjectURL(blob);
linkElement.setAttribute('href', url);
if (filename === undefined || filename === null) {
linkElement.setAttribute("download", "Generated_Report." + fileType);
}
else {
linkElement.setAttribute("download", filename);
}
var clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
linkElement.dispatchEvent(clickEvent);
toaster.pop({
type: 'success',
title: $scope.FrayteSuccess,
body: $scope.Export_Manifest_Downloaded_Successfully,
showCloseButton: true
});
}
} catch (ex) {
$window.open(File.FilePath, "_blank");
console.log(ex);
}
}
})
.error(function (data) {
AppSpinner.hideSpinner();
console.log(data);
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.Could_Not_Download_TheReport,
showCloseButton: true
});
});
}
else {
AppSpinner.hideSpinnerTemplate();
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.ReportCannotDownloadPleaseTryAgain,
showCloseButton: true
});
}
}, function () {
AppSpinner.hideSpinnerTemplate();
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.ReportCannotDownloadPleaseTryAgain,
showCloseButton: true
});
});
};
$scope.DownLoadDriverManifestPDF = function (ManifestDetail) {
AppSpinner.showSpinnerTemplate($scope.DownLoading_Driver_Manifest_PDF, $scope.Template);
$scope.PdfDownloadModel.TradelaneShipmentId = ManifestDetail.TradelaneShipmentId;
$scope.PdfDownloadModel.CustomerId = ManifestDetail.CustomerId;
$scope.PdfDownloadModel.UserId = $scope.createdBy;
ExpressManifestService.GetDriverManifest($scope.PdfDownloadModel).then(function (response) {
AppSpinner.hideSpinnerTemplate();
if (response.data !== null) {
var fileInfo = response.data;
var File = {
FileName: response.data.FileName,
TradelaneShipmentId: ManifestDetail.TradelaneShipmentId,
FilePath: response.data.FilePath
};
$http({
method: 'POST',
url: config.SERVICE_URL + '/ExpressManifest/DownloadExpressReport',
data: File,
responseType: 'arraybuffer'
}).success(function (data, status, headers) {
if (status == 200 && data !== null) {
headers = headers();
var filename = headers['x-filename'];
var contentType = headers['content-type'];
var linkElement = document.createElement('a');
try {
if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
alert("Browser is Safari");
}
else {
var blob = new Blob([data], { type: contentType });
var url = window.URL.createObjectURL(blob);
linkElement.setAttribute('href', url);
if (filename === undefined || filename === null) {
linkElement.setAttribute("download", "Generated_Report." + fileType);
}
else {
linkElement.setAttribute("download", filename);
}
var clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
linkElement.dispatchEvent(clickEvent);
toaster.pop({
type: 'success',
title: $scope.FrayteSuccess,
body: $scope.Driver_Manifest_Downloaded_Successfully,
showCloseButton: true
});
}
} catch (ex) {
$window.open(File.FilePath, "_blank");
console.log(ex);
}
}
})
.error(function (data) {
AppSpinner.hideSpinner();
console.log(data);
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.Could_Not_Download_TheReport,
showCloseButton: true
});
});
}
else {
AppSpinner.hideSpinnerTemplate();
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.ReportCannotDownloadPleaseTryAgain,
showCloseButton: true
});
}
}, function () {
AppSpinner.hideSpinnerTemplate();
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.ReportCannotDownloadPleaseTryAgain,
showCloseButton: true
});
});
};
$scope.DownLoadCustomManifest = function (ManifestDetail) {
AppSpinner.showSpinnerTemplate($scope.DownLoading_Custom_Manifest, $scope.Template);
ExpressManifestService.GetCustomManifest(ManifestDetail.ManifestId).then(function (response) {
AppSpinner.hideSpinnerTemplate();
if (response.data !== null && response.data.FileName !== null && response.data.FileName !== undefined && response.data.FileName !== '') {
var fileInfo = response.data;
var File = {
FileName: response.data.FileName,
FilePath: response.data.FilePath
};
$http({
method: 'POST',
url: config.SERVICE_URL + '/ExpressManifest/DownloadCustomManifest',
data: File,
responseType: 'arraybuffer'
}).success(function (data, status, headers) {
if (status == 200 && data !== null) {
headers = headers();
var filename = headers['x-filename'];
var contentType = headers['content-type'];
var linkElement = document.createElement('a');
try {
if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
alert("Browser is Safari");
}
else {
var blob = new Blob([data], { type: contentType });
var url = window.URL.createObjectURL(blob);
linkElement.setAttribute('href', url);
if (filename === undefined || filename === null) {
linkElement.setAttribute("download", "Generated_Report." + fileType);
}
else {
linkElement.setAttribute("download", filename);
}
var clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
linkElement.dispatchEvent(clickEvent);
toaster.pop({
type: 'success',
title: $scope.FrayteSuccess,
body: $scope.Custom_Manifest_Downloaded_Successfully,
showCloseButton: true
});
}
} catch (ex) {
$window.open(File.FilePath, "_blank");
console.log(ex);
}
}
})
.error(function (data) {
AppSpinner.hideSpinner();
console.log(data);
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.Could_Not_Download_TheReport,
showCloseButton: true
});
});
}
else {
AppSpinner.hideSpinnerTemplate();
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.ReportCannotDownloadPleaseTryAgain,
showCloseButton: true
});
}
}, function () {
AppSpinner.hideSpinnerTemplate();
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.ReportCannotDownloadPleaseTryAgain,
showCloseButton: true
});
});
};
function init() {
$scope.ImagePath = config.BUILD_URL;
$scope.Template = 'directBooking/ajaxLoader.tpl.html';
$scope.dateOptions = {
formatYear: 'yy',
minDate: new Date(),
maxDate: new Date(),
dateDisabled: function (data) {
var date = data.date,
mode = data.mode;
if ($scope.TrackManifest.ToDate !== undefined && $scope.TrackManifest.ToDate !== "" && $scope.TrackManifest.ToDate !== null && $scope.TrackManifest.ToDate.getDate() === date.getDate()) {
return mode === 'day' && false;
}
return mode === 'day' && (($scope.TrackManifest.ToDate !== undefined && $scope.TrackManifest.ToDate !== null && $scope.TrackManifest.ToDate !== "") && date > $scope.TrackManifest.ToDate);
}
};
$scope.dateOptions1 = {
formatYear: 'yy',
minDate: new Date(),
maxDate: new Date(),
dateDisabled: function (data) {
var date = data.date,
mode = data.mode;
if ($scope.TrackManifest.FromDate !== undefined && $scope.TrackManifest.FromDate !== "" && $scope.TrackManifest.FromDate !== null && $scope.TrackManifest.FromDate.getDate() === date.getDate()) {
return mode === 'day' && false;
}
return mode === 'day' && (date < $scope.TrackManifest.FromDate);
}
};
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
var afterTomorrow = new Date(tomorrow);
afterTomorrow.setDate(tomorrow.getDate() + 1);
$scope.toggleMin();
$scope.toggleMin1();
$scope.events = [
{
date: tomorrow,
status: 'full'
},
{
date: afterTomorrow,
status: 'partially'
}
];
$scope.PdfDownloadModel = {
TradelaneShipmentId: null,
CustomerId: null,
UserId: null
};
// Pagination Logic
$scope.viewby = 10;
$scope.currentPage = 1;
$scope.itemsPerPage = $scope.viewby;
$scope.totalItemCount = 1000;
$scope.maxSize = 2; //Number of pager buttons to show
$scope.TrackManifest = {
UserId: null,
FromDate: null,
ToDate: null,
CreatedBy: null,
ModuleType: $scope.moduleType,
subModuleType: "",
CurrentPage: $scope.currentPage,
TakeRows: $scope.itemsPerPage
};
var userInfo = SessionService.getUser();
$scope.RoleId = userInfo.RoleId;
$scope.createdBy = userInfo.EmployeeId;
if ($scope.RoleId === 3) {
$scope.CustomerId = userInfo.EmployeeId;
$rootScope.CustomerManId = userInfo.EmployeeId;
$scope.TrackManifest.UserId = userInfo.EmployeeId;
$scope.TrackManifest.CreatedBy = userInfo.EmployeeId;
if ($rootScope.ChangeExpressManifest === true) {
$scope.ExpressCreateManifest();
$rootScope.ShowManifestButton = false;
$rootScope.ChangeExpressManifest = false;
}
else {
$rootScope.ShowManifestButton = false;
}
}
if ($scope.RoleId === 17) {
$scope.CustomerId = userInfo.EmployeeId;
$rootScope.CustomerManId = userInfo.EmployeeId;
$scope.TrackManifest.UserId = userInfo.EmployeeCustomerId;
$scope.TrackManifest.CreatedBy = userInfo.EmployeeId;
if ($rootScope.ChangeExpressManifest === true) {
$scope.ExpressCreateManifest();
$rootScope.ShowManifestButton = false;
$rootScope.ChangeExpressManifest = false;
}
else {
$rootScope.ShowManifestButton = false;
}
}
if ($scope.RoleId === 20) {
$scope.CustomerId = userInfo.EmployeeId;
$rootScope.CustomerManId = userInfo.EmployeeId;
$scope.TrackManifest.UserId = userInfo.EmployeeId;
$scope.TrackManifest.CreatedBy = 0;
if ($rootScope.ChangeExpressManifest === true) {
$scope.ExpressCreateManifest();
$rootScope.ShowManifestButton = false;
$rootScope.ChangeExpressManifest = false;
}
else {
$rootScope.ShowManifestButton = false;
}
}
$scope.GetCustomers();
if (userInfo === undefined || userInfo === null || userInfo.SessionId === undefined || userInfo.SessionId === '') {
$state.go('home.welcome');
}
else {
$scope.userInfo = userInfo;
$scope.tabs = $scope.userInfo.tabs;
}
setMultilingualOptions();
}
init();
});
|
Ext.define('Gvsu.modules.tender.model.BidModel', {
extend: "Gvsu.modules.docs.model.OrgDocsModel"
,collection: 'gvsu_tenderbid'
,dirPrefix: 'bid-'
,fields: [{
name: '_id',
type: 'ObjectID',
exp: false,
visable: true
},{
name: 'pid',
exp: false,
type: 'int',
filterable: true,
editable: true,
visable: true
},{
name: 'orgid',
exp: false,
type: 'int',
filterable: true,
editable: true,
visable: true
},{
name: 'orgname',
type: 'string',
filterable: true,
editable: true,
visable: true
},{
name: 'file_name',
exp: false,
type: 'string',
filterable: true,
editable: true,
visable: true
},{
name: 'file1_name',
exp: false,
type: 'string',
filterable: true,
editable: true,
visable: true
},{
name: 'date_start',
type: 'date',
editable: true,
filterable: false,
visable: true
},{
name: 'date_fin',
type: 'date',
editable: true,
filterable: false,
visable: true
},{
name: 'price_pos',
type: 'float',
editable: true,
filterable: true,
visable: true
},{
name: 'price_full',
type: 'float',
editable: true,
filterable: true,
visable: true
},{
name: 'conditions_advance',
type: 'string',
filterable: true,
editable: true,
visable: true
},{
name: 'max_contract_val',
type: 'float',
filterable: true,
editable: true,
visable: true
},{
name: 'notes',
type: 'string',
editable: true,
filterable: false,
visable: true
},{
name: 'file_descript',
type: 'string',
editable: true,
filterable: false,
visable: true
},{
name: 'winner',
type: 'boolean',
editable: true,
filterable: true,
visable: true
},{
name: 'status',
type: 'int',
filterable: true,
editable: true,
visable: true
}]
,$getDocPreviewCount: function(data, cb) {
if(!data || !data._id) {
cb({pages: 0})
return;
}
var fs = require('fs')
,me = this
,pages = 0
,dir = me.config.userDocDir + '/bid-' + data._id + '/';
var func = function(i, next) {
fs.exists(dir + i + '.png', function(exists) {
if(exists) {
pages++;
func(i+1, next)
} else
next(pages)
})
}
func(0, function(n) {
out = {pages: n, pages1: 0}
pages = 0;
dir = me.config.userDocDir + '/bid1-' + data._id + '/';
func(0, function(n1) {
out.pages1 = n1
cb(out)
})
})
}
,sendWinnerLetter: function(data, cb) {
this.runOnServer('sendWinnerLetter', data, cb)
}
,$sendWinnerLetter: function(params, cb) {
var me = this;
[
function(next) {
me.src.db.collection(me.collection).update({_id: parseInt(params.bid)}, {$set: {winner: 1}}, function() {next()})
}
,function() {
me.callModel('Gvsu.modules.mail.controller.Mailer.winnerLetter', params, function(list) {
cb({})
})
}
].runEach();
}
,$read: function(data, cb) {
var me = this;
if(data && data.fieldSet) data.fieldSet.push('pid');
[
function(next) {
me.getPermissions(function(permis) {
if(permis.read)
me.getData(data, function(data) {
next(data, permis)
})
else
me.error(401)
})
}
,function(data, permis, next) {
if(!data || !data.list || !data.list.length) {
cb(data)
return;
}
if(permis.modify)
cb(data)
else
next(data)
}
,function(data, next) {
var ids = [];
data.list.each(function(d) {if(ids.indexOf(d.pid) == -1) ids.push(d.pid)})
me.src.db.collection('gvsu_tender').find({_id:{$in: ids}}, {date_doc: 1, _id: 1}, function(e, tends) {
if(tends && tends.length)
next(data, tends)
else
cb(data)
})
}
,function(data, tends) {
var now = new Date();
tends.each(function(tend) {
if(tend.date_doc > now) {
data.list.each(function(item) {
if(item.pid == tend._id) {
item.orgname = '???'
item.price_pos = '???'
item.price_full = '???'
}
return item;
}, true)
}
})
cb(data)
}
].runEach()
}
})
|
var db = require("../models");
var passport = require("../config/passport");
module.exports = function(app) {
app.post("/api/login", passport.authenticate("local"), function(req, res) {
res.json(req.user);
});
var settings = {
"async": true,
"crossDomain": true,
"url": "GET https://api.yelp.com/v3/businesses/search",
"method": "GET",
"headers": {
"Authorization": "bearer",
}
$.CHANGE(settings).done(function (response) {
console.log(response)
});
var unirest = require('unirest');
unirest.get('https://jsonwhois.com/api/v1/whois')
.headers({
'Accept': 'application/json',
'Authorization': 'Token token=<Api Key>'
})
.query({
"domain": "google.com"
})
.end(function (response) {
console.log(response.body);
});
|
var tokki = angular.module("reportesController");
tokki.config(["$stateProvider", "$urlRouterProvider",
function($stateProvider, $urlRouterProvider){
$stateProvider
.state('system.reportes.dtes', {
url: "/dtes",
templateUrl: "pages/reportes/dtes/dtes.html",
controller: "ReportesDtes",
resolve: {
tokkiData: ["$q", "tokkiApi",
function($q, tokkiApi){
var deferred = $q.defer();
var dtes = tokkiApi.query({action: 'dtes', control: 'xml'});
$q.all([dtes.$promise]).
then(function(response) {
deferred.resolve(response);
});
return deferred.promise;
}
]
}
})
}]
);
tokki.controller("ReportesDtes", ['$scope', '$rootScope', '$q', '$filter', 'tokkiData', 'tokkiApi',
function($scope, $rootScope, $q, $filter, tokkiData, tokkiApi) {
$scope.dtes = tokkiData[0];
$scope.choose = function(dte){
$scope.listo = false;
var tipo = dte.dte;
var id = dte.id;
var deferred = $q.defer();
var dteCall = tokkiApi.get({action: "dtes", dte: tipo, id: id});
var detalles = tokkiApi.query({action: "dtes", control: "detalles", dte: tipo, id: id});
var xml = tokkiApi.get({action: 'dtes', control: "xml", dte: tipo, id: id});
$q.all([detalles.$promise, xml.$promise, dteCall.$promise]).
then(function(response) {
$scope.detalles = response[0];
$scope.detallesResumido = $filter("groupBy")(response[0], "producto_id");
$scope.dte = response[2];
$scope.dte.xml = [response[1]['xml']];
if(dte.dte == 33 || dte.dte == 34){
$scope.notaCredito = true;
$scope.notaDebito = true;
}
else if(dte.dte == 61){
$scope.notaCredito = false;
$scope.notaDebito = true;
}
else if(dte.dte == 56){
$scope.notaCredito = true;
$scope.notaDebito = false;
}
else{
$scope.notaDebito = false;
$scope.notaCredito = false;
}
$scope.listo = true;
});
}
$scope.anularGuia = function(id){
tokkiApi.update({action: "dtes", control: "anular", dte: 52, id: id})
.$promise.then(function(response){
$scope.dte.anulado = true;
}, function(response){
})
}
$scope.desanularGuia = function(id){
tokkiApi.update({action: "dtes", control: "desanular", dte: 52, id: id})
.$promise.then(function(response){
$scope.dte.anulado = false;
}, function(response){
})
}
$scope.verificar = function(xml){
tokkiApi.save({action: "verificar", xml: xml})
.$promise.then(function(response){
if(response.estado == 0){
var glosa = $filter('estadodte')(response.status);
swal({
title: "DTE Recibido",
text: "<table class='table table-bordered'><tr><th>Recibido</th><td>" + response.recibido +"</td></tr><tr><th>Estado</th><td>" + response.status +"</td></tr><tr><th>Glosa</th><td>" + glosa +"</td></tr></table>",
html: true});
}
else{
swal("Error Servidor SII");
}
}, function(response){
swal("ERROR", "", "error");
})
}
}
]);
|
import React from 'react'
import "./Show.css";
import { Avatar } from "@material-ui/core";
function Show({ profileSrc, text, description }) {
return (
<div className="show">
<div className="services">
<div className="icon">
<Avatar className="show__avatar" src={profileSrc} />
</div>
<h3 className="alutitle">{text}</h3>
<p>{description}
</p>
</div>
</div>
)
}
export default Show
|
'use strict';
import React from 'react'
import classNames from 'classnames'
import styles from '../../css/components/header.css'
export default class Header extends React.Component {
render() {
const header = classNames(
styles.lHeader,
styles.header
);
return (
<header ref="header" className={header}>
<h1 className={styles.headerTitle}><a className="header-link" href="/"><span className={styles.headerBalloon}>誰得</span>Qiita記事検索</a></h1>
</header>
);
}
}
|
import { RestService } from '../../services/rest';
import { serviceOptions } from '../../services/serviceOptions';
export function neoScan(options) {
var inst = new RestService();
serviceOptions(inst, 'neoScan', options);
inst.getCurrentBlockHeight = getCurrentBlockHeight;
return inst;
}
function getCurrentBlockHeight () {
return this.$get('get_height');
}
|
define(['jquery', 'pubsub'], function ($, ps) {
return {
init: function (settings, events) {
ps.sub(events.gamesCountCompleted, function (promise) {
promise.success(function (data) {
if (data.ErrorMessage === null) {
$(document).find('#' + settings.gamesCountId).text(data.Count);
}
});
});
ps.pub(events.gamesCountStart);
}
};
});
|
'use strict';
var almost = {};
(function () {
var wordlist = [];
var request;
var uInt16Range;
var array;
var data;
var lines;
var line;
var words;
var word;
var pct;
var c;
var i;
var j;
almost.load = function (callback) {
if (wordlist.length > 0) {
// It's already loaded
callback();
return;
}
// Requires a web server; CORS will reject loading this via the file: protocol
request = new XMLHttpRequest();
request.open('GET', 'eff_large_wordlist.asc', true);
request.onload = function () {
if (request.status >= 200 && request.status < 400) {
// Extract the words
data = request.responseText;
lines = data.split('\n');
for (i = 0; i < lines.length; i++) {
line = lines[i];
if (line === '-----BEGIN PGP SIGNED MESSAGE-----') {
continue;
}
if (line === 'Hash: SHA256') {
continue;
}
if (line === '') {
continue;
}
if (
line ===
'https://www.eff.org/deeplinks/2016/07/new-wordlists-random-passphrases'
) {
continue;
}
if (line === '-----BEGIN PGP SIGNATURE-----') {
break;
}
word = /^\d{5}\s(.+)$/.exec(line);
if (word) {
wordlist.push(word[1]);
}
}
callback();
} else {
// We reached our target server, but it returned an error
// TODO: handle it
}
};
request.onerror = function () {
// There was a connection error of some sort
// TODO: handle it
};
request.send();
};
almost.getWords = function (howMany) {
c = window.crypto || window.msCrypto;
if (c && c.getRandomValues) {
// Get random values using a cryptographically sound method
// http://stackoverflow.com/questions/5651789/is-math-random-cryptographically-secure
if (howMany > 1000) {
howMany = 1000;
}
// Edge requires explicit type conversion
array = new Uint16Array(Number(howMany));
c.getRandomValues(array);
words = [];
uInt16Range = 65535; // 0xFFFF - 0x0000
for (i = 0; i < array.length; i++) {
// Get our random number as a percent along the range of possibilities
pct = array[i] / uInt16Range;
// Scale up for the number of words we have
j = Math.floor(pct * wordlist.length);
word = wordlist[j];
words.push(word);
}
return words.join(' ');
}
return (
'Error: Cannot find a cryptographically sound random number generator. ' +
'Please try another more modern browser.'
);
};
})();
|
(function () {
'use strict';
angular.module('events.admin')
.directive('manageUsers', userMgmtDirective);
function userMgmtDirective () {
UserMgmtDirectiveCtrl.$inject = ['$scope', '$log', 'ManageUserService', '$uibModal', 'SubscribeEventService'];
return {
restrict: 'A',
templateUrl: 'partials/admin/user-management/user-management.html',
controller: UserMgmtDirectiveCtrl,
controllerAs: 'vm'
};
function UserMgmtDirectiveCtrl ($scope, $log, ManageUserService, $uibModal, SubscribeEventService) {
var vm = this;
vm.currentPage = 0;
vm.pageSize = 5;
vm.numberOfPages = function () {
return 1;
};
getUsers();
vm.viewSubscriptions = function (size, userObj) {
$uibModal.open({
animation: true,
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'partials/admin/user-management/subscription-details.html',
controller: 'SubscriptionCtrl',
controllerAs: 'subscriptionCtrl',
size: size,
resolve: {
userObj: function () {
return userObj
}
}
});
};
vm.removeHealthDoc = function (fileName) {
ManageUserService.removeHealthDoc(fileName);
};
vm.deleteUser = function (userId) {
ManageUserService.deleteUser(userId).then(function () {
getUsers();
});
};
function getUsers () {
ManageUserService.getUsers().then(function (response) {
vm.users = response;
vm.currentPage = 0;
vm.pageSize = 5;
vm.numberOfPages=function(){
return Math.ceil(vm.users.length/vm.pageSize);
};
});
}
vm.toggleAdmin = function (userId) {
ManageUserService.updateUserDetails(userId).then(function () {
getUsers();
});
};
}
}
})();
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
var cloned;
var p = 0;
// load XML file
function loadStates()
{
initialize();
$.ajax({
type: "POST",
url: "/Strategic_Location_Determination/handlerequests?requestType=states",
dataType: "json"
})
.done(function(response)
{
//var data = JSON.parse(response);
var length = 0;
for (var dummy in response)
length++;
for (var i = 0; i < length; i++) {
$('#select_state').append($('<option >', {value: response[i][0]}).text(response[i][1]));
// var m=response;
//updateListing(data[x]);
}
cloned = $("#maindiv").clone(false);
dropdowneventlistner();
$("#btn_place").click(function() {
$('.btn').hide();
p++;
var c = cloned.clone(false);
c.find("*[id]").andSelf().each(function() {
$(this).attr("id", $(this).attr("id") + "_" + p);
})
// alert(c);
$("#content").append(c);
dropdowneventlistner();
});
});
}
function dropdowneventlistner(){
$('.states').change(function() {
var parent =$(this).parent();
//on change event for the select box
var place = $(this).val();
// var place = $('#select_state').val();
$.ajax({
type: "POST",
url: "/Strategic_Location_Determination/handlerequests?requestType=cities",
dataType: "json",
data: {place: place}
})
.done(function(response)
{
//var data = JSON.parse(response);
var length = 0;
for (var dummy in response)
length++;
parent.next().show();
for (var i = 0; i < length; i++) {
parent.next().find("select").append($('<option>', {value: response[i][1]}).text(response[i][0]));
// var m=response;
//updateListing(data[x]);
}
$(".btn").show();
});
});
}
function submitrequest()
{
var x=0;
var statesArray= new Array();
var jsonData = {};
var jsonArray = new Array();
$("body").find("select").each(function(){
x++;
//jsonData['state']=$(this).val();
// statesArray.push($(this).val());
if(x%2==0) {
x=0;
//jsonData['state']=statesArray[0];
jsonData['place']=$(this).val();
// statesArray=[];
jsonArray.push(jsonData);
jsonData={};
}else{
jsonData['state']=$(this).val();
}
});
$("#field_json").val(JSON.stringify(jsonArray));
//sending maps data to the server
$("#maps_json").val(JSON.stringify(lats));
}
|
import $ from '$';
import _ from 'underscore';
class HAWCModal {
constructor(){
// singleton modal instance
var $modalDiv = $('#hawcModal');
if ($modalDiv.length === 0){
$modalDiv = $('<div id="hawcModal" class="modal hide fade" tabindex="-1" role="dialog" data-backdrop="static"></div>')
.append('<div class="modal-header"></div>')
.append('<div class="modal-body"></div>')
.append('<div class="modal-footer"></div>')
.appendTo($('body'));
$(window).on('resize', this._resizeModal.bind(this));
}
this.$modalDiv = $modalDiv;
}
show(options, cb){
this.fixedSize = options && options.fixedSize || false;
this.maxWidth = options && options.maxWidth || Infinity;
this.maxHeight = options && options.maxHeight || Infinity;
this._resizeModal();
this.getBody().scrollTop(0);
if(cb) this.$modalDiv.on('shown', cb);
this.$modalDiv.modal('show');
return this;
}
hide(){
this.$modalDiv.modal('hide');
return this;
}
addHeader(html, options){
var noClose = (options && options.noClose) || false,
$el = this.$modalDiv.find('.modal-header');
$el.html(html);
if (!noClose) $el.prepend('<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>');
return this;
}
addTitleLinkHeader(name, url, options){
var txt = '<h4><a href="{0}" target="_blank">{1}</a></h4>'.printf(url, name);
return this.addHeader(txt, options);
}
addFooter(html, options){
var noClose = (options && options.noClose) || false,
$el = this.$modalDiv.find('.modal-footer');
$el.html(html);
if (!noClose) $el.append('<button class="btn" data-dismiss="modal">Close</button>');
return this;
}
getBody(){
return this.$modalDiv.find('.modal-body');
}
addBody(html){
this.getBody().html(html).scrollTop(0);
return this;
}
_resizeModal(){
var h = parseInt($(window).height(), 10),
w = parseInt($(window).width(), 10),
modalCSS = {
width: '',
height: '',
top: '',
left: '',
margin: '',
'max-height': '',
},
modalBodyCSS = {
'max-height': '',
};
if(!this.fixedSize){
var mWidth = Math.min(w-50, this.maxWidth),
mWidthPadding = parseInt((w-mWidth)*0.5, 10),
mHeight = Math.min(h-50, this.maxHeight);
_.extend(modalCSS, {
width: '{0}px'.printf(mWidth),
top: '25px',
left: '{0}px'.printf(mWidthPadding),
margin: '0px',
'max-height': '{0}px'.printf(mHeight),
});
_.extend(modalBodyCSS, {
'max-height': '{0}px'.printf(mHeight-150),
});
}
this.$modalDiv.css(modalCSS);
this.getBody().css(modalBodyCSS);
}
getModal(){
return this.$modalDiv;
}
}
export default HAWCModal;
|
'use strict';
var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');
var template = require('./slots.html');
var AnimationController = require('../../modules/AnimationController');
var Slots = Backbone.View.extend({
template: _.template(template()),
initialize: function() {
this.listenTo(this.model, 'change:route', this.onRouteChange);
this.$el.html(template());
$('.slots-container').removeClass('hasWon');
this.animate = new AnimationController();
this.gameMechanics();
},
// Game logic and mechanics/animation
gameMechanics: function() {
var content = {
data: this.model.get('data')
};
/**
* Mobile - Button
*/
$('#mobilePlay').on('click', function() {
console.log('lever pulled');
document.querySelector('#crank').play();
document.querySelector('#motion').play();
// snap lever back up
TweenMax.to('#lever', 0.35, {
y: -300,
ease: Back.easeOut
});
// game logic vars
this.spinOne = [1, 2, 3];
this.spinTwo = [1, 2, 3];
this.choiceOne = _.sample(this.spinOne, 1).toString();
this.choiceTwo = _.sample(this.spinTwo, 1).toString();
this.hasWon;
// stuff to do if win or lose
// if win - add hasWon class/asign three identical icons to display in slots
if (this.choiceOne === this.choiceTwo) {
this.hasWon = true;
$('.slots-container').addClass('hasWon');
$('.reveal').attr('src', _.sample(content.data.icons, 1).toString());
// if lose - grab three different icons
} else {
this.hasWon = false;
$('.slots-container').removeClass('hasWon');
$('.reveal-left').attr('src', _.sample(content.data.icons, 1).toString());
$('.reveal-center').attr('src', _.sample(content.data.icons, 1).toString());
$('.reveal-right').attr('src', _.sample(content.data.icons, 1).toString());
}
// hide revealed icons to make way for animated slots gif
TweenMax.set('.reveal', {display: 'none', autoAlpha: 0, top: '45%'});
// slots spinning animation
var tl = new TimelineMax();
tl.to('.inline-slots', 1, {autoAlpha: 1});
tl.to('.inline-slots', 3, {
autoAlpha: 1,
ease: Power4.easeInOut,
onComplete: function() { // when finished spin anim, reveal
TweenMax.to('.inline-slots', 0.25, {
autoAlpha: 0,
onComplete: function() { // when slots are done spinning...
// if win, display three identical icons
if ($('.slots-container').hasClass('hasWon')) {
TweenMax.staggerTo('.reveal', 0.5, {
display: 'block',
autoAlpha: 1,
top: '63%',
ease: Back.easeOut,
onComplete: function() { // reveal #greeting view
setTimeout(function() {
document.querySelector('#winner').play();
window.location.href = '#greeting';
}, 750);
}
}, 0.25);
// if lose, dispaly three different icons
} else {
setTimeout(function() {
document.querySelector('#loser').play();
}, 750);
TweenMax.staggerTo('.reveal', 0.5, {
display: 'block',
autoAlpha: 1,
top: '63%',
ease: Back.easeOut
}, 0.25);
}
} // end onComplete - winning or losing slot machine icons reveal
}); // end Tween - spin gifs end and reveal icons
} // end onComplete - spin gif animation and decide to reveal win or lose icons
}); // end Tween - slots spin animation
}); // end Mobile button onClick()
/**
* Desktop - Draggable Lever
*/
TweenMax.set('#lever', {y: -300, x: -40});
// game logic and animations happen in onDragEnd()
Draggable.create('#lever', {
type:'y',
throwProps: true,
edgeResistance: 1.5,
// bounds: {minY: -300, maxY: 0},
bounds: {minY: -300, maxY: 0},
cursor: '-webkit-grab',
onDragStart:function() {
TweenMax.set('#lever', {cursor:'-webkit-grabbing'});
},
onDragEnd:function() { // spin slots
console.log('lever pulled');
document.querySelector('#crank').play();
document.querySelector('#motion').play();
// snap lever back up
TweenMax.to('#lever', 0.35, {
y: -300,
ease: Back.easeOut
});
// game logic vars
this.spinOne = [1, 2, 3];
this.spinTwo = [1, 2, 3];
this.choiceOne = _.sample(this.spinOne, 1).toString();
this.choiceTwo = _.sample(this.spinTwo, 1).toString();
this.hasWon;
// stuff to do if win or lose
// if win - add hasWon class/asign three identical icons to display in slots
if (this.choiceOne === this.choiceTwo) {
this.hasWon = true;
$('.slots-container').addClass('hasWon');
$('.reveal').attr('src', _.sample(content.data.icons, 1).toString());
// if lose - grab three different icons
} else {
this.hasWon = false;
$('.slots-container').removeClass('hasWon');
$('.reveal-left').attr('src', _.sample(content.data.icons, 1).toString());
$('.reveal-center').attr('src', _.sample(content.data.icons, 1).toString());
$('.reveal-right').attr('src', _.sample(content.data.icons, 1).toString());
}
// hide revealed icons to make way for animated slots gif
TweenMax.set('.reveal', {display: 'none', autoAlpha: 0, top: '45%'});
// slots spinning animation
var tl = new TimelineMax();
tl.to('.inline-slots', 1, {autoAlpha: 1});
tl.to('.inline-slots', 3, {
autoAlpha: 1,
ease: Power4.easeInOut,
onComplete: function() { // when finished spin anim, reveal
TweenMax.to('.inline-slots', 0.25, {
autoAlpha: 0,
onComplete: function() { // when slots are done spinning...
// if win, display three identical icons
if ($('.slots-container').hasClass('hasWon')) {
TweenMax.staggerTo('.reveal', 0.5, {
display: 'block',
autoAlpha: 1,
top: '63%',
ease: Back.easeOut,
onComplete: function() { // reveal #greeting view
setTimeout(function() {
document.querySelector('#winner').play();
window.location.href = '#greeting';
}, 1000);
}
}, 0.25);
// if lose, dispaly three different icons
} else {
setTimeout(function() {
document.querySelector('#loser').play();
}, 750);
TweenMax.staggerTo('.reveal', 0.5, {
display: 'block',
autoAlpha: 1,
top: '63%',
ease: Back.easeOut
}, 0.25);
}
} // end onComplete - winning or losing slot machine icons reveal
}); // end Tween - spin gifs end and reveal icons
} // end onComplete - spin gif animation and decide to reveal win or lose icons
}); // end Tween - slots spin animation
} // end onDragEnd()
}); // end Draggable
}
});
module.exports = Slots;
|
import '../Login/Login.module.scss'
export { Login } from './Login';
export { Register } from './Register';
|
define(["dojox/charting/Theme", "dojo/_base/Color", "dojox/charting/themes/common"], function(Theme, Color, themes){
/*
A charting theme for Dayforce
*/
themes.FeussCharts = new Theme({
// The chart container
chart: {
stroke: null,
fill: "transparent"
},
// The area within the axis lines
plotarea: {
stroke: null,
fill: "transparent"
},
// The area within the axis lines
axis: {
stroke: {width: 1, color: "#adb7bc"},
tick: { // used as a foundation for all ticks
color: "#adb7bc",
position: "center",
font: "normal normal normal .75rem 'Open Sans', Helvetica, Arial, sans-serif", // labels on axis
fontColor: "#292f32" // color of labels
},
majorTick:{
color: "#dfe3e4",
width: 1,
length: 5
},
minorTick: {
color: "#eceeef",
width: 1,
length: 2
},
font: "normal normal normal .75rem 'Open Sans', Helvetica, Arial, sans-serif",
fontColor: "#adb7bc"
},
// The number at the end of the bars
series: {
outline: null,
stroke: {width: 1, color: "white"},
font: "normal normal normal .75rem 'Open Sans', Helvetica, Arial, sans-serif",
fontColor: "#515e63"
},
marker: {
stroke: {width: 1, color: "black"},
fill: "#292f32",
font: "normal normal normal .875rem 'Open Sans', Helvetica, Arial, sans-serif",
fontColor: "black"
},
colors:[
Color.fromHex("#88a4e8"),
Color.fromHex("#83c7e6"),
Color.fromHex("#8aeaa3"),
Color.fromHex("#fde568"),
Color.fromHex("#fdc766"),
Color.fromHex("#ed7dab")
]
});
// themes.FeussCharts.next = function(elementType, mixin, doPost){
// var isLine = elementType == "line";
// if(isLine || elementType == "area"){
// // custom processing for lines: substitute colors
// var s = this.seriesThemes[this._current % this.seriesThemes.length];
// s.fill.space = "plot";
// if(isLine){
// s.stroke = { width: 4, color: s.fill.colors[0].color};
// }
// var theme = Theme.prototype.next.apply(this, arguments);
// // cleanup
// delete s.outline;
// delete s.stroke;
// s.fill.space = "shape";
// return theme;
// }
// return Theme.prototype.next.apply(this, arguments);
// };
// themes.FeussCharts.post = function(theme, elementType){
// theme = Theme.prototype.post.apply(this, arguments);
// if((elementType == "slice" || elementType == "circle") && theme.series.fill && theme.series.fill.type == "radial"){
// theme.series.fill = gradutils.reverse(theme.series.fill);
// }
// return theme;
// };
return themes.FeussCharts;
});
|
import firebase from "firebase/app"
import "firebase/auth";
const app = firebase.initializeApp({
apiKey:process.env.REACT_APP_FIREBASE_API_KEY,
authDomain:process.env.REACT_APP_AUTH_DOMAIN,
projectId:process.env.REACT_APP_PROJECT_ID,
storageBucket:process.env.REACT_APP_STORAGE_BUCKET,
messagingSenderId:process.env.REACT_APP_MESSAGE_SENDER_ID,
appId:process.env.REACT_APP_APP_ID ,
measurementId:process.env.REACT_APP_MEASUREMENT_ID
});
export const auth =app.auth();
export default app;
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import './index.scss';
class Label extends Component {
render() {
const {
className,
// color,
labels,
} = this.props;
return (
<div className="labels">
{labels.length > 0
? labels.map((text, index) => (
<div
className={classNames(
className,
)}
key={index}
>
{text}
</div>
))
: null}
</div>
);
}
}
Label.propTypes = {
labels: PropTypes.array,
className: PropTypes.string,
// color: PropTypes.string,
};
Label.defaultProps = {
labels: [],
// color: 'light',
};
export default Label;
|
(async function () {
const controller = app.Controller;
const cssPath = "common/css";
controller.addStyle(cssPath);
controller.addStyle(cssPath, "radio-button");
controller.addStyle(cssPath, "square-button");
controller.addStyle(cssPath, "radio-label");
controller.addStyle(cssPath, "card");
controller.addStyle(cssPath, "card.md");
controller.addStyle(cssPath, "card.sm");
controller.addStyle(cssPath, "hotzone");
controller.addStyle(cssPath, "hotzone.md");
controller.addStyle(cssPath, "checkbox-label");
controller.addStyle(cssPath, "panel-section");
controller.addStyle(cssPath, "horizontal-spacing");
controller.addStyle(cssPath, "price-currency");
controller.addStyle(cssPath, "select-quantity");
controller.addStyle(cssPath, "round-button");
controller.addStyle(cssPath, "modal");
controller.view("partials/header");
controller.view("partials/footer");
controller.view("partials/view-cart");
switch(window.location.pathname) {
case "/":
case "/home":
controller.view("pages/home");
break;
case "/view-item":
controller.view("pages/view-item");
break;
default:
location.pathname = "/";
break;
}
})();
|
'use strict';
// 非高频使用,使用*sync api取代async api
const {readdirSync, statSync} = require('fs');
const {join} = require('path');
const {createHmac} = require('crypto');
const config = require('./config.json');
// 忽略文件列表、文件编码、调试模式
const {blackList} = config;
/**
* 获取目录中所有指定类型的文件
* @param {string} dirPath
* @param {string} ext
* @return {array}
*/
function getAllFiles(dirPath, ext) {
/**
* 递归扫描目录
* @param {string} dirPath
* @param {string} ext
* @return {array}
*/
function scanDir(dirPath, ext) {
const result = readdirSync(dirPath);
if (!result.length) return [];
return result.filter((name) => !(blackList || []).includes(name)).map((dirName) => {
const filePath = join(dirPath, dirName);
if (statSync(filePath).isDirectory()) {
return scanDir(join(dirPath, dirName), ext);
} else {
if (!ext) return filePath;
if (filePath.lastIndexOf(ext) === filePath.indexOf(ext) && filePath.indexOf(ext) > -1) {
return filePath;
}
return '';
}
});
}
/**
* 扁平数组
* @param {array} arr
* @return {array}
*/
function flatten(arr) {
return arr.reduce(function(flat, toFlatten) {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
}, []);
}
return flatten(scanDir(dirPath, ext)).filter((file) => file);
}
/**
* 计算文件Hash
* @param data
* @return {string}
*/
function md5(data) {
return createHmac('md5', data).digest('hex');
}
module.exports = {getAllFiles, md5};
|
import styled from "styled-components"
import { baseUnits } from "."
export const SmallTitle = styled.h4`
font-size: 1rem;
letter-spacing: 0.5px;
font-weight: 700;
margin-bottom: ${baseUnits(0.25)};
`
export const MediumTitle = styled.h3`
font-size: 1.66666rem;
font-weight: 500;
line-height: 1.2;
margin-bottom: ${baseUnits(0.5)};
`
export const LargeTitle = styled.h2`
font-size: 3rem;
line-height: 1;
font-weight: 500;
margin-bottom: ${baseUnits(0.5)};
`
|
import React, {Component} from 'react';
class FormEvent extends Component {
state = {
name: '',
fName: '',
phoneNo: '',
bio: '',
country: '',
skills: [],
birthDate: '',
email:'',
gender: '',
agree: false
}
submit = event =>{
console.log(this.state)
// console.log('Submit Done')
}
handleChange = event => {
//console.log(event.target.name)
this.setState({
[event.target.name] : event.target.value
})
}
handleCheckBox = event =>{
this.setState({
agree:event.target.checked
})
}
handleSkill = event =>{
if(event.target.checked){
this.setState({
skills: [...this.state.skills, event.target.value]
})
}else{
const skills = this.state.skills.filter(skill => skill !== event.target.value)
this.setState({skills})
}
}
render() {
//Destructor Value
const {name, bio, birthDate, email, fName, phoneNo, skills, agree, country} = this.state
return (
<div className='col-md-6'>
<div className='card-header mb-5'>
<h2 className='text-danger'>Form Event With State</h2>
</div>
<div className='form-row'>
<div className='row'>
<div className='col-md-6'>
<label className='col-form-label mb-1 text-danger'>Name</label>
<input value={name} onChange={this.handleChange} name='name' type='text' className='form-control' placeholder='Name'/>
</div>
<div className='col-md-6'>
<label className='col-form-label mb-1 text-danger'>Father Name</label>
<input value={fName} onChange={this.handleChange} name='fName' type='text' className='form-control' placeholder='Father Name'/>
</div>
<div className='col-md-6'>
<label className='col-form-label mb-1 text-danger'>Birth Date</label>
<input value={birthDate} onChange={this.handleChange} name='birthDate' type='date' className='form-control' placeholder='Father Name'/>
</div>
<div className='col-md-6'>
<label className='col-form-label mb-1 text-danger'>Country</label>
<select value={country} onChange={this.handleChange} name='country' className='text-dark form-control'>
<option className='form-control'>Please Select Country</option>
<option className='form-control' value='Bangladesh'>Bangladesh</option>
<option className='form-control' value='Pakistan'>Pakistan</option>
<option className='form-control' value='India'>India</option>
<option className='form-control' value='Canada'>Canada</option>
</select>
</div>
<div className='col-md-6'>
<label className='col-form-label mb-1 text-danger'>Mobile Number</label>
<input value={phoneNo} onChange={this.handleChange} name='phoneNo' className='form-control' type='number' placeholder='Mobile Number'/>
</div>
<div className='col-md-6'>
<label className='col-form-label mb-1 text-danger'>Email</label>
<input value={email} onChange={this.handleChange} name='email' className='form-control' type='email' placeholder='Email Address'/>
</div>
<div className="col-md-6 mt-2">
<input onChange={this.handleChange} className="form-check-input ml-0" type="radio" name="gender" value='Male'/>
<label className="form-check-label ml-3">Male</label>
</div>
<div className="col-md-6 mt-2">
<input onChange={this.handleChange} className="form-check-input ml-0" type="radio" name="gender" value='Female'/>
<label className="form-check-label ml-3">Female</label>
</div>
<div className="col-md-6 mt-2">
<input value='WordPress' onChange={this.handleSkill} className="form-check-input ml-0" type="checkbox" name="skills" checked={skills.includes('WordPress')}/>
<label className="form-check-label ml-3">
WordPress
</label>
<input value='Php' onChange={this.handleSkill} className="form-check-input ml-0" type="checkbox" name="skills" checked={skills.includes('Php')}/>
<label className="form-check-label ml-3">
Php
</label>
<input value='Java' onChange={this.handleSkill} className="form-check-input ml-0" type="checkbox" name="skills" checked={skills.includes('Java')}/>
<label className="form-check-label ml-3">
Java
</label>
</div>
<div className="col-md-12 mt-2">
<input onChange={this.handleCheckBox} className="form-check-input ml-0" type="checkbox" name="agree" checked={agree}/>
<label className="form-check-label ml-3">
I agree with your services, thank you.
</label>
</div>
<div className='col-md-12'>
<label className='col-form-label mb-1 text-danger'>Bio Information</label>
<textarea value={bio} onChange={this.handleChange} name='bio' className='form-control'></textarea>
</div>
</div>
<button onClick={this.submit} className='btn btn-outline-info mt-4'>Show Data</button>
</div>
</div>
);
}
}
export default FormEvent;
|
var name = "Hasan";
if (name == "Mahmud") {
console.log("My name is Mahmud");
}
else{
console.log("I don't know my name");
}
switch (name) {
case "Mahmud":
console.log("My name is Mahmud.");
break;
case "Hasan":
console.log("My name is Hasan.");
break;
default:
console.log("I don't know who the f I am.");
break;
}
var a = 1;
var b = '1';
var result = (a===b) ? "Equal" : "Not Equal";
console.log(result);
|
// miniprogram/pages/speak/speak.js
Page({
/**
* 页面的初始数据
*/
data: {
topicId:'',
index:0,
oneTopic:[],
userInfo:{},
talkBox:[],
},
goEdit() {
wx.navigateTo({
url: '../edit/edit?topicId=' + this.data.topicId + "&index=" + this.data.index,
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
const that = this;
that.setData({
topicId: options.topicId,
index: options.index
})
// 获取当前用户的信息
wx.login({
success: function () {
wx.getUserInfo({
success: function (res) {
// var simpleUser = res.userInfo;
// console.log(res.userInfo);
that.setData({
userInfo: res.userInfo
})
console.log(that.data.userInfo)
},
fail: function (error) {
console.log(error)
}
});
}
});
// 获取当前话题的信息
wx.cloud.callFunction({
name: 'getTopic',
data: {
topicId: options.topicId
},
success(res) {
console.log(res)
that.setData({
oneTopic: res.result.oneTopic.data
})
console.log(that.data.oneTopic)
wx.setNavigationBarTitle({
title: that.data.oneTopic[0].topicTitle
})
}
});
//获取当前的话题盒子数据
wx.cloud.callFunction({
name:'getSpeak',
data: {
topicId: options.topicId
},
success(res) {
console.log(res)
that.setData({
talkBox: res.result.talkBox.data
})
}
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
|
import React, { useState } from 'react';
import { Link, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { login } from '../actions/auth';
import Styles from './Components.module.css';
import { Spring } from 'react-spring/renderprops';
import axios from 'axios';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faFacebook, faGoogle, faTwitter } from "@fortawesome/free-brands-svg-icons"
const Login = ({ login, isAuthenticated }) => {
const [formData, setFormData] = useState({
email: '',
password: ''
});
const { email, password } = formData;
const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value });
const onSubmit = e => {
e.preventDefault();
login(email, password);
};
const continueWithGoogle = async()=>{
try{
const res = await axios.get('/auth/o/google-oauth2/?redirect_uri=http://localhost:8000/google')
window.location.replace(res.data.authorization_url);
}
catch(err){
// co
}
};
const continueWithFacebook = async()=>{
try{
const res = await axios.get('/auth/o/facebook/?redirect_uri=http://localhost:8000/facebook')
window.location.replace(res.data.authorization_url);
}
catch(err){
// co
}
};
const continueWithTwitter = async()=>{
try{
const res = await axios.get('/auth/o/twitter/?redirect_uri=http://localhost:8000/twitter')
window.location.replace(res.data.authorization_url);
}
catch(err){
// co
}
};
if (isAuthenticated)
return <Redirect to='/' />;
return (
<Spring
from={{opacity:0,marginLeft:-500}}
to={{opacity:1,marginLeft:0}}
config={{duration:1000}}
>
{props =>(
<div style={props}>
<div className={Styles.container}>
<div className='row mx-3'>
<div className="col-md-5 mx-auto my-auto">
<h1>Sign In</h1>
<p>Sign into your Account</p>
<form onSubmit={e => onSubmit(e)}>
<div className='form-group'>
<input
className='form-control'
type='email'
placeholder='Email'
name='email'
value={email}
onChange={e => onChange(e)}
required
/>
</div>
<div className='form-group'>
<input
className='form-control'
type='password'
placeholder='Password'
name='password'
value={password}
onChange={e => onChange(e)}
minLength='6'
required
/>
</div>
<button className={`${Styles.btn} ${Styles.fill_button}`} type='submit'>Login</button>
</form>
<p className='mt-3'>
OR
</p>
<p className='mt-3'>
<button className="btn btn-danger" onClick={continueWithGoogle}><FontAwesomeIcon icon={faGoogle} /> Continue with google</button>
</p>
<p className='mt-3'>
<button className="btn btn-primary" onClick={continueWithFacebook}><FontAwesomeIcon icon={faFacebook} /> Continue with facebook</button>
</p>
<p className='mt-3'>
<button className="btn btn-success"><a href="https://twitter.com/login?lang=en" className={Styles.navlink} target="_blank"><FontAwesomeIcon icon={faTwitter} /> Continue with twitter</a></button>
</p>
<p className='mt-3'>
Don't have an account? <Link to='/signup'>Sign Up</Link>
</p>
<p className='mt-3'>
Forgot your Password? <Link to='/reset_password'>Reset Password</Link>
</p>
</div>
</div>
</div>
</div>
)}
</Spring>
);
};
const mapStateToProps = state => ({
isAuthenticated: state.auth.isAuthenticated
});
export default connect(mapStateToProps, { login })(Login);
// import React,{Component, useState} from 'react';
// import {Link} from 'react-router-dom';
// import {connect} from 'react-redux';
// import Styles from './Components.module.css';
// class Login extends Component{
// constructor(props){
// super(props);
// this.state={
// username:"",
// password:""
// };
// this.onChangeInput=this.onChangeInput.bind(this);
// this.handleLogin=this.handleLogin.bind(this);
// }
// onChangeInput(event){
// this.setState({
// [event.target.name]:event.target.value
// })
// }
// handleLogin(event){
// event.preventDefault();
// }
// render(){
// return (
// <div className="row" >
// <div className="col-md-5 mx-auto my-5">
// <form method="GET">
// <div className={Styles.C_input}>
// <input onChange={this.onChangeInput} type="text" name="username" placeholder="Username"/><br/>
// </div>
// <div className={Styles.C_input}>
// <input onChange={this.onChangeInput} type="password" name="password" placeholder="Password"/><br/>
// </div>
// <div className="row">
// <div className="col-md-5 mx-auto" >
// <button onClick={this.handleLogin} className={`${Styles.btn} ${Styles.fill_button}`}>Login</button>
// </div>
// <div className="col-md-5 mx-auto" >
// <p>Don't have an account then </p>
// <button className={`${Styles.btn} ${Styles.fill_button}`}><Link to="/uregister" className={Styles.navlink}>Register</Link></button>
// </div>
// </div>
// </form>
// </div>
// </div>
// );
// }
// }
// export default Login;
|
const webpack = require('webpack')
const path = require('path')
const merge = require('webpack-merge')
const nodeExternals = require('webpack-node-externals')
const base = require('./webpack.base.config')()
const VueSSRServerPlugin = require('vue-server-renderer/server-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const isProd = process.env.NODE_ENV === 'production'
class ServerMiniCssExtractPlugin extends MiniCssExtractPlugin {
getCssChunkObject(mainChunk) {
return {}
}
}
module.exports = function () {
const config = merge(base, {
mode: 'production',
// 指定生成后的运行环境在node
target: 'node',
// 设置代码调试map
devtool: '#cheap-module-source-map',
// 配置编译的入口文件
entry: path.join(process.cwd(), 'src/entry-server.js'),
// 设置输出文件名,并设置模块导出为commonjs2类型
output: {
filename: 'server-bundle.js',
libraryTarget: 'commonjs2'
},
resolve: {
alias: {
'~http': path.resolve(`src/http/index-server.js`),
}
},
// 外置化应用程序依赖模块。可以使服务器构建速度更快,
// 并生成较小的 bundle 文件。
externals: nodeExternals({
// 不要外置化 webpack 需要处理的依赖模块。
// 你可以在这里添加更多的文件类型。例如,未处理 *.vue 原始文件,
// 你还应该将修改 `global`(例如 polyfill)的依赖模块列入白名单
whitelist: [/\.vue$/, /\.css$/]
}),
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
compilerOptions: {
preserveWhitespace: false
},
loaders: {
css: [isProd ? ServerMiniCssExtractPlugin.loader : 'vue-style-loader', 'css-loader', 'postcss-loader'],
stylus: [isProd ? ServerMiniCssExtractPlugin.loader : 'vue-style-loader', 'css-loader', 'postcss-loader',
{ loader: 'stylus-loader', options: isProd ? {} : { sourceMap: 'inline' } },
],
scss: [isProd ? ServerMiniCssExtractPlugin.loader : 'vue-style-loader', 'css-loader', 'postcss-loader',
{ loader: 'sass-loader', options: isProd ? {} : { sourceMap: true } },
]
}
}
},
{
test: /\.css$/,
use: [isProd ? ServerMiniCssExtractPlugin.loader : 'vue-style-loader', 'css-loader', 'postcss-loader']
},
{
test: /\.(styl|stylus)$/,
use: [isProd ? ServerMiniCssExtractPlugin.loader : 'vue-style-loader', 'css-loader', 'postcss-loader',
{
loader: 'stylus-loader',
options: isProd ? {} : { sourceMap: 'inline' }
}
]
},
{
test: /\.scss$/,
use: [isProd ? ServerMiniCssExtractPlugin.loader : 'vue-style-loader', 'css-loader', 'postcss-loader',
{
loader: 'sass-loader',
options: isProd ? {} : { sourceMap: true }
}
]
},
]
},
// 这是将服务器的整个输出
// 构建为单个 JSON 文件的插件。
// 默认文件名为 `vue-ssr-server-bundle.json`
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
'process.env.VUE_ENV': '"server"'
}),
new VueSSRServerPlugin()
]
})
if (isProd) {
config.plugins = (config.plugins || []).concat([
// 分离css文件
new ServerMiniCssExtractPlugin({
filename: '[name].[chunkhash:8].min.css',
//chunkFilename: '[name].[chunkhash:8].css',
})
])
}
return config
}
|
var AtomicHooks = require('./index');
var concat = require('concat-stream');
var util = require('util');
function LevelBucket(db, opts) {
db._configBucket = opts || {};
db._configBucket.default = db._configBucket.default || 'default';
db._configBucket.sep = db._configBucket.sep || '!';
if (!db.atomichooks) {
db = AtomicHooks(db);
}
db.registerKeyPreProcessor(function (key, opts) {
opts = opts || {};
var newkey = (opts.bucket || db._configBucket.default) + db._configBucket.sep + key;
console.log("KPP", key, "->", newkey);
return newkey;
});
db.registerKeyPostProcessor(function (key, opts) {
opts = opts || {};
var idx = key.indexOf(db._configBucket.sep);
if (idx !== -1) {
key = key.slice(idx + 1);
}
return key;
});
return db;
}
var levelup = require('./node_modules/levelup');
var tst = levelup('./testdbforme', {valueEncoding: 'json'});
tst = LevelBucket(tst);
tst.put('testkey', {test: 'no'}, {bucket: 'weee'}, function (err) {
});
/*
tst.batch()
.put('hi', {derp: 1}, {bucket: 'ham'})
.put('wat', {derp: 2}, {bucket: 'ham'})
.write(function (err) {
tst.get('hi', {bucket: 'ham'}, function (err, value) {
console.log(1);
console.log("%j", arguments);
});
tst.createReadStream({bucket: 'ham', start: '!', end: '~'}).pipe(concat(function () {
console.log(2);
console.log(util.inspect(arguments, {depth: 10}));
}));
tst.createKeyStream({bucket: 'ham', start: '!', end: '~'}).pipe(concat(function () {
console.log(3);
console.log(arguments);
}));
tst.createValueStream({bucket: 'ham', start: '!', end: '~'}).pipe(concat(function () {
console.log(4);
console.log(arguments);
}));
});
*/
|
import classes from '../classes'
describe("classes", () => {
it("接受一个classes", () => {
const result = classes("a")
expect(result).toEqual("a")
})
it("接受奇怪的classes", () => {
const result = classes("a", "中文")
expect(result).toEqual("a 中文")
})
})
|
import React, {Component} from 'react'
import {each, defaults, isObject, pick, merge} from 'lodash'
export default class SingletonComponent extends Component {
componentWillMount() {
if (isObject(this.constructor.state)) {
this.setState(this.constructor.state)
this.constructor.state = false
}
this.constructor.instance = this
}
componentWillUnmount() {
this.state = this.constructor.instance
this.constructor.instance = false
}
static one() {
if (!this.instance) {
console.warn(`${this.constructor.prototype} singleton does not exists`)
}
return this.instance
}
static getState() {
return this.instance ? this.instance.state : this.state
}
static get(propNames) {
return pick(this.getState(), propNames)
}
static set(state) {
return this.instance ? this.instance.setState(state) : merge(this.state, state)
}
}
|
export const getLastRecord = (state) => state.records[state.records.length - 1] || {};
export const getNextRecordId = (state) => {
const { id = 0 } = getLastRecord(state);
return id + 1;
};
|
function Controller() {
function setValue() {
args.params.callback && args.params.callback({
value: L(String(this.value))
});
APP.popOut();
return true;
}
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
this.__controllerPath = "Settings/StatePicker";
arguments[0] ? arguments[0]["__parentSymbol"] : null;
arguments[0] ? arguments[0]["$model"] : null;
arguments[0] ? arguments[0]["__itemTemplate"] : null;
var $ = this;
var exports = {};
var __defers = {};
$.__views.StatePicker = Ti.UI.createScrollView({
backgroundColor: "#ecf1f4",
layout: "vertical",
scrollType: "vertical",
id: "StatePicker"
});
$.__views.StatePicker && $.addTopLevelView($.__views.StatePicker);
$.__views.__alloyId1209 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "AL",
id: "__alloyId1209"
});
$.__views.StatePicker.add($.__views.__alloyId1209);
setValue ? $.__views.__alloyId1209.addEventListener("click", setValue) : __defers["$.__views.__alloyId1209!click!setValue"] = true;
$.__views.__alloyId1210 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Alabama",
id: "__alloyId1210"
});
$.__views.__alloyId1209.add($.__views.__alloyId1210);
$.__views.__alloyId1211 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1211"
});
$.__views.__alloyId1209.add($.__views.__alloyId1211);
$.__views.__alloyId1212 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1212"
});
$.__views.__alloyId1209.add($.__views.__alloyId1212);
$.__views.__alloyId1213 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "AK",
id: "__alloyId1213"
});
$.__views.StatePicker.add($.__views.__alloyId1213);
setValue ? $.__views.__alloyId1213.addEventListener("click", setValue) : __defers["$.__views.__alloyId1213!click!setValue"] = true;
$.__views.__alloyId1214 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Alaska",
id: "__alloyId1214"
});
$.__views.__alloyId1213.add($.__views.__alloyId1214);
$.__views.__alloyId1215 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1215"
});
$.__views.__alloyId1213.add($.__views.__alloyId1215);
$.__views.__alloyId1216 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1216"
});
$.__views.__alloyId1213.add($.__views.__alloyId1216);
$.__views.__alloyId1217 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "AZ",
id: "__alloyId1217"
});
$.__views.StatePicker.add($.__views.__alloyId1217);
setValue ? $.__views.__alloyId1217.addEventListener("click", setValue) : __defers["$.__views.__alloyId1217!click!setValue"] = true;
$.__views.__alloyId1218 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Arizona",
id: "__alloyId1218"
});
$.__views.__alloyId1217.add($.__views.__alloyId1218);
$.__views.__alloyId1219 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1219"
});
$.__views.__alloyId1217.add($.__views.__alloyId1219);
$.__views.__alloyId1220 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1220"
});
$.__views.__alloyId1217.add($.__views.__alloyId1220);
$.__views.__alloyId1221 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "AR",
id: "__alloyId1221"
});
$.__views.StatePicker.add($.__views.__alloyId1221);
setValue ? $.__views.__alloyId1221.addEventListener("click", setValue) : __defers["$.__views.__alloyId1221!click!setValue"] = true;
$.__views.__alloyId1222 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Arkansas",
id: "__alloyId1222"
});
$.__views.__alloyId1221.add($.__views.__alloyId1222);
$.__views.__alloyId1223 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1223"
});
$.__views.__alloyId1221.add($.__views.__alloyId1223);
$.__views.__alloyId1224 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1224"
});
$.__views.__alloyId1221.add($.__views.__alloyId1224);
$.__views.__alloyId1225 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "CA",
id: "__alloyId1225"
});
$.__views.StatePicker.add($.__views.__alloyId1225);
setValue ? $.__views.__alloyId1225.addEventListener("click", setValue) : __defers["$.__views.__alloyId1225!click!setValue"] = true;
$.__views.__alloyId1226 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "California",
id: "__alloyId1226"
});
$.__views.__alloyId1225.add($.__views.__alloyId1226);
$.__views.__alloyId1227 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1227"
});
$.__views.__alloyId1225.add($.__views.__alloyId1227);
$.__views.__alloyId1228 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1228"
});
$.__views.__alloyId1225.add($.__views.__alloyId1228);
$.__views.__alloyId1229 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "CO",
id: "__alloyId1229"
});
$.__views.StatePicker.add($.__views.__alloyId1229);
setValue ? $.__views.__alloyId1229.addEventListener("click", setValue) : __defers["$.__views.__alloyId1229!click!setValue"] = true;
$.__views.__alloyId1230 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Colorado",
id: "__alloyId1230"
});
$.__views.__alloyId1229.add($.__views.__alloyId1230);
$.__views.__alloyId1231 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1231"
});
$.__views.__alloyId1229.add($.__views.__alloyId1231);
$.__views.__alloyId1232 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1232"
});
$.__views.__alloyId1229.add($.__views.__alloyId1232);
$.__views.__alloyId1233 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "CT",
id: "__alloyId1233"
});
$.__views.StatePicker.add($.__views.__alloyId1233);
setValue ? $.__views.__alloyId1233.addEventListener("click", setValue) : __defers["$.__views.__alloyId1233!click!setValue"] = true;
$.__views.__alloyId1234 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Connecticut",
id: "__alloyId1234"
});
$.__views.__alloyId1233.add($.__views.__alloyId1234);
$.__views.__alloyId1235 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1235"
});
$.__views.__alloyId1233.add($.__views.__alloyId1235);
$.__views.__alloyId1236 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1236"
});
$.__views.__alloyId1233.add($.__views.__alloyId1236);
$.__views.__alloyId1237 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "DE",
id: "__alloyId1237"
});
$.__views.StatePicker.add($.__views.__alloyId1237);
setValue ? $.__views.__alloyId1237.addEventListener("click", setValue) : __defers["$.__views.__alloyId1237!click!setValue"] = true;
$.__views.__alloyId1238 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Delaware",
id: "__alloyId1238"
});
$.__views.__alloyId1237.add($.__views.__alloyId1238);
$.__views.__alloyId1239 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1239"
});
$.__views.__alloyId1237.add($.__views.__alloyId1239);
$.__views.__alloyId1240 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1240"
});
$.__views.__alloyId1237.add($.__views.__alloyId1240);
$.__views.__alloyId1241 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "DC",
id: "__alloyId1241"
});
$.__views.StatePicker.add($.__views.__alloyId1241);
setValue ? $.__views.__alloyId1241.addEventListener("click", setValue) : __defers["$.__views.__alloyId1241!click!setValue"] = true;
$.__views.__alloyId1242 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "District of Columbia",
id: "__alloyId1242"
});
$.__views.__alloyId1241.add($.__views.__alloyId1242);
$.__views.__alloyId1243 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1243"
});
$.__views.__alloyId1241.add($.__views.__alloyId1243);
$.__views.__alloyId1244 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1244"
});
$.__views.__alloyId1241.add($.__views.__alloyId1244);
$.__views.__alloyId1245 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "FL",
id: "__alloyId1245"
});
$.__views.StatePicker.add($.__views.__alloyId1245);
setValue ? $.__views.__alloyId1245.addEventListener("click", setValue) : __defers["$.__views.__alloyId1245!click!setValue"] = true;
$.__views.__alloyId1246 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Florida",
id: "__alloyId1246"
});
$.__views.__alloyId1245.add($.__views.__alloyId1246);
$.__views.__alloyId1247 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1247"
});
$.__views.__alloyId1245.add($.__views.__alloyId1247);
$.__views.__alloyId1248 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1248"
});
$.__views.__alloyId1245.add($.__views.__alloyId1248);
$.__views.__alloyId1249 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "GA",
id: "__alloyId1249"
});
$.__views.StatePicker.add($.__views.__alloyId1249);
setValue ? $.__views.__alloyId1249.addEventListener("click", setValue) : __defers["$.__views.__alloyId1249!click!setValue"] = true;
$.__views.__alloyId1250 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Georgia",
id: "__alloyId1250"
});
$.__views.__alloyId1249.add($.__views.__alloyId1250);
$.__views.__alloyId1251 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1251"
});
$.__views.__alloyId1249.add($.__views.__alloyId1251);
$.__views.__alloyId1252 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1252"
});
$.__views.__alloyId1249.add($.__views.__alloyId1252);
$.__views.__alloyId1253 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "HI",
id: "__alloyId1253"
});
$.__views.StatePicker.add($.__views.__alloyId1253);
setValue ? $.__views.__alloyId1253.addEventListener("click", setValue) : __defers["$.__views.__alloyId1253!click!setValue"] = true;
$.__views.__alloyId1254 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Hawaii",
id: "__alloyId1254"
});
$.__views.__alloyId1253.add($.__views.__alloyId1254);
$.__views.__alloyId1255 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1255"
});
$.__views.__alloyId1253.add($.__views.__alloyId1255);
$.__views.__alloyId1256 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1256"
});
$.__views.__alloyId1253.add($.__views.__alloyId1256);
$.__views.__alloyId1257 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "ID",
id: "__alloyId1257"
});
$.__views.StatePicker.add($.__views.__alloyId1257);
setValue ? $.__views.__alloyId1257.addEventListener("click", setValue) : __defers["$.__views.__alloyId1257!click!setValue"] = true;
$.__views.__alloyId1258 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Idaho",
id: "__alloyId1258"
});
$.__views.__alloyId1257.add($.__views.__alloyId1258);
$.__views.__alloyId1259 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1259"
});
$.__views.__alloyId1257.add($.__views.__alloyId1259);
$.__views.__alloyId1260 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1260"
});
$.__views.__alloyId1257.add($.__views.__alloyId1260);
$.__views.__alloyId1261 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "IL",
id: "__alloyId1261"
});
$.__views.StatePicker.add($.__views.__alloyId1261);
setValue ? $.__views.__alloyId1261.addEventListener("click", setValue) : __defers["$.__views.__alloyId1261!click!setValue"] = true;
$.__views.__alloyId1262 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Illinois",
id: "__alloyId1262"
});
$.__views.__alloyId1261.add($.__views.__alloyId1262);
$.__views.__alloyId1263 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1263"
});
$.__views.__alloyId1261.add($.__views.__alloyId1263);
$.__views.__alloyId1264 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1264"
});
$.__views.__alloyId1261.add($.__views.__alloyId1264);
$.__views.__alloyId1265 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "IN",
id: "__alloyId1265"
});
$.__views.StatePicker.add($.__views.__alloyId1265);
setValue ? $.__views.__alloyId1265.addEventListener("click", setValue) : __defers["$.__views.__alloyId1265!click!setValue"] = true;
$.__views.__alloyId1266 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Indiana",
id: "__alloyId1266"
});
$.__views.__alloyId1265.add($.__views.__alloyId1266);
$.__views.__alloyId1267 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1267"
});
$.__views.__alloyId1265.add($.__views.__alloyId1267);
$.__views.__alloyId1268 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1268"
});
$.__views.__alloyId1265.add($.__views.__alloyId1268);
$.__views.__alloyId1269 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "IA",
id: "__alloyId1269"
});
$.__views.StatePicker.add($.__views.__alloyId1269);
setValue ? $.__views.__alloyId1269.addEventListener("click", setValue) : __defers["$.__views.__alloyId1269!click!setValue"] = true;
$.__views.__alloyId1270 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Iowa",
id: "__alloyId1270"
});
$.__views.__alloyId1269.add($.__views.__alloyId1270);
$.__views.__alloyId1271 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1271"
});
$.__views.__alloyId1269.add($.__views.__alloyId1271);
$.__views.__alloyId1272 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1272"
});
$.__views.__alloyId1269.add($.__views.__alloyId1272);
$.__views.__alloyId1273 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "KS",
id: "__alloyId1273"
});
$.__views.StatePicker.add($.__views.__alloyId1273);
setValue ? $.__views.__alloyId1273.addEventListener("click", setValue) : __defers["$.__views.__alloyId1273!click!setValue"] = true;
$.__views.__alloyId1274 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Kansas",
id: "__alloyId1274"
});
$.__views.__alloyId1273.add($.__views.__alloyId1274);
$.__views.__alloyId1275 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1275"
});
$.__views.__alloyId1273.add($.__views.__alloyId1275);
$.__views.__alloyId1276 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1276"
});
$.__views.__alloyId1273.add($.__views.__alloyId1276);
$.__views.__alloyId1277 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "KY",
id: "__alloyId1277"
});
$.__views.StatePicker.add($.__views.__alloyId1277);
setValue ? $.__views.__alloyId1277.addEventListener("click", setValue) : __defers["$.__views.__alloyId1277!click!setValue"] = true;
$.__views.__alloyId1278 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Kentucky",
id: "__alloyId1278"
});
$.__views.__alloyId1277.add($.__views.__alloyId1278);
$.__views.__alloyId1279 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1279"
});
$.__views.__alloyId1277.add($.__views.__alloyId1279);
$.__views.__alloyId1280 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1280"
});
$.__views.__alloyId1277.add($.__views.__alloyId1280);
$.__views.__alloyId1281 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "LA",
id: "__alloyId1281"
});
$.__views.StatePicker.add($.__views.__alloyId1281);
setValue ? $.__views.__alloyId1281.addEventListener("click", setValue) : __defers["$.__views.__alloyId1281!click!setValue"] = true;
$.__views.__alloyId1282 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Louisiana",
id: "__alloyId1282"
});
$.__views.__alloyId1281.add($.__views.__alloyId1282);
$.__views.__alloyId1283 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1283"
});
$.__views.__alloyId1281.add($.__views.__alloyId1283);
$.__views.__alloyId1284 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1284"
});
$.__views.__alloyId1281.add($.__views.__alloyId1284);
$.__views.__alloyId1285 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "ME",
id: "__alloyId1285"
});
$.__views.StatePicker.add($.__views.__alloyId1285);
setValue ? $.__views.__alloyId1285.addEventListener("click", setValue) : __defers["$.__views.__alloyId1285!click!setValue"] = true;
$.__views.__alloyId1286 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Maine",
id: "__alloyId1286"
});
$.__views.__alloyId1285.add($.__views.__alloyId1286);
$.__views.__alloyId1287 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1287"
});
$.__views.__alloyId1285.add($.__views.__alloyId1287);
$.__views.__alloyId1288 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1288"
});
$.__views.__alloyId1285.add($.__views.__alloyId1288);
$.__views.__alloyId1289 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "MD",
id: "__alloyId1289"
});
$.__views.StatePicker.add($.__views.__alloyId1289);
setValue ? $.__views.__alloyId1289.addEventListener("click", setValue) : __defers["$.__views.__alloyId1289!click!setValue"] = true;
$.__views.__alloyId1290 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Maryland",
id: "__alloyId1290"
});
$.__views.__alloyId1289.add($.__views.__alloyId1290);
$.__views.__alloyId1291 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1291"
});
$.__views.__alloyId1289.add($.__views.__alloyId1291);
$.__views.__alloyId1292 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1292"
});
$.__views.__alloyId1289.add($.__views.__alloyId1292);
$.__views.__alloyId1293 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "MA",
id: "__alloyId1293"
});
$.__views.StatePicker.add($.__views.__alloyId1293);
setValue ? $.__views.__alloyId1293.addEventListener("click", setValue) : __defers["$.__views.__alloyId1293!click!setValue"] = true;
$.__views.__alloyId1294 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Massachusetts",
id: "__alloyId1294"
});
$.__views.__alloyId1293.add($.__views.__alloyId1294);
$.__views.__alloyId1295 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1295"
});
$.__views.__alloyId1293.add($.__views.__alloyId1295);
$.__views.__alloyId1296 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1296"
});
$.__views.__alloyId1293.add($.__views.__alloyId1296);
$.__views.__alloyId1297 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "MI",
id: "__alloyId1297"
});
$.__views.StatePicker.add($.__views.__alloyId1297);
setValue ? $.__views.__alloyId1297.addEventListener("click", setValue) : __defers["$.__views.__alloyId1297!click!setValue"] = true;
$.__views.__alloyId1298 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Michigan",
id: "__alloyId1298"
});
$.__views.__alloyId1297.add($.__views.__alloyId1298);
$.__views.__alloyId1299 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1299"
});
$.__views.__alloyId1297.add($.__views.__alloyId1299);
$.__views.__alloyId1300 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1300"
});
$.__views.__alloyId1297.add($.__views.__alloyId1300);
$.__views.__alloyId1301 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "MN",
id: "__alloyId1301"
});
$.__views.StatePicker.add($.__views.__alloyId1301);
setValue ? $.__views.__alloyId1301.addEventListener("click", setValue) : __defers["$.__views.__alloyId1301!click!setValue"] = true;
$.__views.__alloyId1302 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Minnesota",
id: "__alloyId1302"
});
$.__views.__alloyId1301.add($.__views.__alloyId1302);
$.__views.__alloyId1303 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1303"
});
$.__views.__alloyId1301.add($.__views.__alloyId1303);
$.__views.__alloyId1304 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1304"
});
$.__views.__alloyId1301.add($.__views.__alloyId1304);
$.__views.__alloyId1305 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "MS",
id: "__alloyId1305"
});
$.__views.StatePicker.add($.__views.__alloyId1305);
setValue ? $.__views.__alloyId1305.addEventListener("click", setValue) : __defers["$.__views.__alloyId1305!click!setValue"] = true;
$.__views.__alloyId1306 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Mississippi",
id: "__alloyId1306"
});
$.__views.__alloyId1305.add($.__views.__alloyId1306);
$.__views.__alloyId1307 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1307"
});
$.__views.__alloyId1305.add($.__views.__alloyId1307);
$.__views.__alloyId1308 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1308"
});
$.__views.__alloyId1305.add($.__views.__alloyId1308);
$.__views.__alloyId1309 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "MO",
id: "__alloyId1309"
});
$.__views.StatePicker.add($.__views.__alloyId1309);
setValue ? $.__views.__alloyId1309.addEventListener("click", setValue) : __defers["$.__views.__alloyId1309!click!setValue"] = true;
$.__views.__alloyId1310 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Missouri",
id: "__alloyId1310"
});
$.__views.__alloyId1309.add($.__views.__alloyId1310);
$.__views.__alloyId1311 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1311"
});
$.__views.__alloyId1309.add($.__views.__alloyId1311);
$.__views.__alloyId1312 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1312"
});
$.__views.__alloyId1309.add($.__views.__alloyId1312);
$.__views.__alloyId1313 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "MT",
id: "__alloyId1313"
});
$.__views.StatePicker.add($.__views.__alloyId1313);
setValue ? $.__views.__alloyId1313.addEventListener("click", setValue) : __defers["$.__views.__alloyId1313!click!setValue"] = true;
$.__views.__alloyId1314 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Montana",
id: "__alloyId1314"
});
$.__views.__alloyId1313.add($.__views.__alloyId1314);
$.__views.__alloyId1315 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1315"
});
$.__views.__alloyId1313.add($.__views.__alloyId1315);
$.__views.__alloyId1316 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1316"
});
$.__views.__alloyId1313.add($.__views.__alloyId1316);
$.__views.__alloyId1317 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "NE",
id: "__alloyId1317"
});
$.__views.StatePicker.add($.__views.__alloyId1317);
setValue ? $.__views.__alloyId1317.addEventListener("click", setValue) : __defers["$.__views.__alloyId1317!click!setValue"] = true;
$.__views.__alloyId1318 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Nebraska",
id: "__alloyId1318"
});
$.__views.__alloyId1317.add($.__views.__alloyId1318);
$.__views.__alloyId1319 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1319"
});
$.__views.__alloyId1317.add($.__views.__alloyId1319);
$.__views.__alloyId1320 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1320"
});
$.__views.__alloyId1317.add($.__views.__alloyId1320);
$.__views.__alloyId1321 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "NV",
id: "__alloyId1321"
});
$.__views.StatePicker.add($.__views.__alloyId1321);
setValue ? $.__views.__alloyId1321.addEventListener("click", setValue) : __defers["$.__views.__alloyId1321!click!setValue"] = true;
$.__views.__alloyId1322 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Nevada",
id: "__alloyId1322"
});
$.__views.__alloyId1321.add($.__views.__alloyId1322);
$.__views.__alloyId1323 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1323"
});
$.__views.__alloyId1321.add($.__views.__alloyId1323);
$.__views.__alloyId1324 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1324"
});
$.__views.__alloyId1321.add($.__views.__alloyId1324);
$.__views.__alloyId1325 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "NH",
id: "__alloyId1325"
});
$.__views.StatePicker.add($.__views.__alloyId1325);
setValue ? $.__views.__alloyId1325.addEventListener("click", setValue) : __defers["$.__views.__alloyId1325!click!setValue"] = true;
$.__views.__alloyId1326 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "New Hampshire",
id: "__alloyId1326"
});
$.__views.__alloyId1325.add($.__views.__alloyId1326);
$.__views.__alloyId1327 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1327"
});
$.__views.__alloyId1325.add($.__views.__alloyId1327);
$.__views.__alloyId1328 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1328"
});
$.__views.__alloyId1325.add($.__views.__alloyId1328);
$.__views.__alloyId1329 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "NJ",
id: "__alloyId1329"
});
$.__views.StatePicker.add($.__views.__alloyId1329);
setValue ? $.__views.__alloyId1329.addEventListener("click", setValue) : __defers["$.__views.__alloyId1329!click!setValue"] = true;
$.__views.__alloyId1330 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "New Jersey",
id: "__alloyId1330"
});
$.__views.__alloyId1329.add($.__views.__alloyId1330);
$.__views.__alloyId1331 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1331"
});
$.__views.__alloyId1329.add($.__views.__alloyId1331);
$.__views.__alloyId1332 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1332"
});
$.__views.__alloyId1329.add($.__views.__alloyId1332);
$.__views.__alloyId1333 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "NM",
id: "__alloyId1333"
});
$.__views.StatePicker.add($.__views.__alloyId1333);
setValue ? $.__views.__alloyId1333.addEventListener("click", setValue) : __defers["$.__views.__alloyId1333!click!setValue"] = true;
$.__views.__alloyId1334 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "New Mexico",
id: "__alloyId1334"
});
$.__views.__alloyId1333.add($.__views.__alloyId1334);
$.__views.__alloyId1335 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1335"
});
$.__views.__alloyId1333.add($.__views.__alloyId1335);
$.__views.__alloyId1336 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1336"
});
$.__views.__alloyId1333.add($.__views.__alloyId1336);
$.__views.__alloyId1337 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "NY",
id: "__alloyId1337"
});
$.__views.StatePicker.add($.__views.__alloyId1337);
setValue ? $.__views.__alloyId1337.addEventListener("click", setValue) : __defers["$.__views.__alloyId1337!click!setValue"] = true;
$.__views.__alloyId1338 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "New York",
id: "__alloyId1338"
});
$.__views.__alloyId1337.add($.__views.__alloyId1338);
$.__views.__alloyId1339 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1339"
});
$.__views.__alloyId1337.add($.__views.__alloyId1339);
$.__views.__alloyId1340 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1340"
});
$.__views.__alloyId1337.add($.__views.__alloyId1340);
$.__views.__alloyId1341 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "NC",
id: "__alloyId1341"
});
$.__views.StatePicker.add($.__views.__alloyId1341);
setValue ? $.__views.__alloyId1341.addEventListener("click", setValue) : __defers["$.__views.__alloyId1341!click!setValue"] = true;
$.__views.__alloyId1342 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "North Carolina",
id: "__alloyId1342"
});
$.__views.__alloyId1341.add($.__views.__alloyId1342);
$.__views.__alloyId1343 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1343"
});
$.__views.__alloyId1341.add($.__views.__alloyId1343);
$.__views.__alloyId1344 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1344"
});
$.__views.__alloyId1341.add($.__views.__alloyId1344);
$.__views.__alloyId1345 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "ND",
id: "__alloyId1345"
});
$.__views.StatePicker.add($.__views.__alloyId1345);
setValue ? $.__views.__alloyId1345.addEventListener("click", setValue) : __defers["$.__views.__alloyId1345!click!setValue"] = true;
$.__views.__alloyId1346 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "North Dakota",
id: "__alloyId1346"
});
$.__views.__alloyId1345.add($.__views.__alloyId1346);
$.__views.__alloyId1347 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1347"
});
$.__views.__alloyId1345.add($.__views.__alloyId1347);
$.__views.__alloyId1348 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1348"
});
$.__views.__alloyId1345.add($.__views.__alloyId1348);
$.__views.__alloyId1349 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "OH",
id: "__alloyId1349"
});
$.__views.StatePicker.add($.__views.__alloyId1349);
setValue ? $.__views.__alloyId1349.addEventListener("click", setValue) : __defers["$.__views.__alloyId1349!click!setValue"] = true;
$.__views.__alloyId1350 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Ohio",
id: "__alloyId1350"
});
$.__views.__alloyId1349.add($.__views.__alloyId1350);
$.__views.__alloyId1351 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1351"
});
$.__views.__alloyId1349.add($.__views.__alloyId1351);
$.__views.__alloyId1352 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1352"
});
$.__views.__alloyId1349.add($.__views.__alloyId1352);
$.__views.__alloyId1353 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "OK",
id: "__alloyId1353"
});
$.__views.StatePicker.add($.__views.__alloyId1353);
setValue ? $.__views.__alloyId1353.addEventListener("click", setValue) : __defers["$.__views.__alloyId1353!click!setValue"] = true;
$.__views.__alloyId1354 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Oklahoma",
id: "__alloyId1354"
});
$.__views.__alloyId1353.add($.__views.__alloyId1354);
$.__views.__alloyId1355 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1355"
});
$.__views.__alloyId1353.add($.__views.__alloyId1355);
$.__views.__alloyId1356 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1356"
});
$.__views.__alloyId1353.add($.__views.__alloyId1356);
$.__views.__alloyId1357 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "OR",
id: "__alloyId1357"
});
$.__views.StatePicker.add($.__views.__alloyId1357);
setValue ? $.__views.__alloyId1357.addEventListener("click", setValue) : __defers["$.__views.__alloyId1357!click!setValue"] = true;
$.__views.__alloyId1358 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Oregon",
id: "__alloyId1358"
});
$.__views.__alloyId1357.add($.__views.__alloyId1358);
$.__views.__alloyId1359 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1359"
});
$.__views.__alloyId1357.add($.__views.__alloyId1359);
$.__views.__alloyId1360 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1360"
});
$.__views.__alloyId1357.add($.__views.__alloyId1360);
$.__views.__alloyId1361 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "PA",
id: "__alloyId1361"
});
$.__views.StatePicker.add($.__views.__alloyId1361);
setValue ? $.__views.__alloyId1361.addEventListener("click", setValue) : __defers["$.__views.__alloyId1361!click!setValue"] = true;
$.__views.__alloyId1362 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Pennsylvania",
id: "__alloyId1362"
});
$.__views.__alloyId1361.add($.__views.__alloyId1362);
$.__views.__alloyId1363 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1363"
});
$.__views.__alloyId1361.add($.__views.__alloyId1363);
$.__views.__alloyId1364 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1364"
});
$.__views.__alloyId1361.add($.__views.__alloyId1364);
$.__views.__alloyId1365 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "PR",
id: "__alloyId1365"
});
$.__views.StatePicker.add($.__views.__alloyId1365);
setValue ? $.__views.__alloyId1365.addEventListener("click", setValue) : __defers["$.__views.__alloyId1365!click!setValue"] = true;
$.__views.__alloyId1366 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Puerto Rico",
id: "__alloyId1366"
});
$.__views.__alloyId1365.add($.__views.__alloyId1366);
$.__views.__alloyId1367 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1367"
});
$.__views.__alloyId1365.add($.__views.__alloyId1367);
$.__views.__alloyId1368 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1368"
});
$.__views.__alloyId1365.add($.__views.__alloyId1368);
$.__views.__alloyId1369 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "RI",
id: "__alloyId1369"
});
$.__views.StatePicker.add($.__views.__alloyId1369);
setValue ? $.__views.__alloyId1369.addEventListener("click", setValue) : __defers["$.__views.__alloyId1369!click!setValue"] = true;
$.__views.__alloyId1370 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Rhode Island",
id: "__alloyId1370"
});
$.__views.__alloyId1369.add($.__views.__alloyId1370);
$.__views.__alloyId1371 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1371"
});
$.__views.__alloyId1369.add($.__views.__alloyId1371);
$.__views.__alloyId1372 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1372"
});
$.__views.__alloyId1369.add($.__views.__alloyId1372);
$.__views.__alloyId1373 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "SC",
id: "__alloyId1373"
});
$.__views.StatePicker.add($.__views.__alloyId1373);
setValue ? $.__views.__alloyId1373.addEventListener("click", setValue) : __defers["$.__views.__alloyId1373!click!setValue"] = true;
$.__views.__alloyId1374 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "South Carolina",
id: "__alloyId1374"
});
$.__views.__alloyId1373.add($.__views.__alloyId1374);
$.__views.__alloyId1375 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1375"
});
$.__views.__alloyId1373.add($.__views.__alloyId1375);
$.__views.__alloyId1376 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1376"
});
$.__views.__alloyId1373.add($.__views.__alloyId1376);
$.__views.__alloyId1377 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "SD",
id: "__alloyId1377"
});
$.__views.StatePicker.add($.__views.__alloyId1377);
setValue ? $.__views.__alloyId1377.addEventListener("click", setValue) : __defers["$.__views.__alloyId1377!click!setValue"] = true;
$.__views.__alloyId1378 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "South Dakota",
id: "__alloyId1378"
});
$.__views.__alloyId1377.add($.__views.__alloyId1378);
$.__views.__alloyId1379 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1379"
});
$.__views.__alloyId1377.add($.__views.__alloyId1379);
$.__views.__alloyId1380 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1380"
});
$.__views.__alloyId1377.add($.__views.__alloyId1380);
$.__views.__alloyId1381 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "TN",
id: "__alloyId1381"
});
$.__views.StatePicker.add($.__views.__alloyId1381);
setValue ? $.__views.__alloyId1381.addEventListener("click", setValue) : __defers["$.__views.__alloyId1381!click!setValue"] = true;
$.__views.__alloyId1382 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Tennessee",
id: "__alloyId1382"
});
$.__views.__alloyId1381.add($.__views.__alloyId1382);
$.__views.__alloyId1383 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1383"
});
$.__views.__alloyId1381.add($.__views.__alloyId1383);
$.__views.__alloyId1384 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1384"
});
$.__views.__alloyId1381.add($.__views.__alloyId1384);
$.__views.__alloyId1385 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "TX",
id: "__alloyId1385"
});
$.__views.StatePicker.add($.__views.__alloyId1385);
setValue ? $.__views.__alloyId1385.addEventListener("click", setValue) : __defers["$.__views.__alloyId1385!click!setValue"] = true;
$.__views.__alloyId1386 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Texas",
id: "__alloyId1386"
});
$.__views.__alloyId1385.add($.__views.__alloyId1386);
$.__views.__alloyId1387 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1387"
});
$.__views.__alloyId1385.add($.__views.__alloyId1387);
$.__views.__alloyId1388 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1388"
});
$.__views.__alloyId1385.add($.__views.__alloyId1388);
$.__views.__alloyId1389 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "UT",
id: "__alloyId1389"
});
$.__views.StatePicker.add($.__views.__alloyId1389);
setValue ? $.__views.__alloyId1389.addEventListener("click", setValue) : __defers["$.__views.__alloyId1389!click!setValue"] = true;
$.__views.__alloyId1390 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Utah",
id: "__alloyId1390"
});
$.__views.__alloyId1389.add($.__views.__alloyId1390);
$.__views.__alloyId1391 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1391"
});
$.__views.__alloyId1389.add($.__views.__alloyId1391);
$.__views.__alloyId1392 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1392"
});
$.__views.__alloyId1389.add($.__views.__alloyId1392);
$.__views.__alloyId1393 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "VT",
id: "__alloyId1393"
});
$.__views.StatePicker.add($.__views.__alloyId1393);
setValue ? $.__views.__alloyId1393.addEventListener("click", setValue) : __defers["$.__views.__alloyId1393!click!setValue"] = true;
$.__views.__alloyId1394 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Vermont",
id: "__alloyId1394"
});
$.__views.__alloyId1393.add($.__views.__alloyId1394);
$.__views.__alloyId1395 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1395"
});
$.__views.__alloyId1393.add($.__views.__alloyId1395);
$.__views.__alloyId1396 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1396"
});
$.__views.__alloyId1393.add($.__views.__alloyId1396);
$.__views.__alloyId1397 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "VI",
id: "__alloyId1397"
});
$.__views.StatePicker.add($.__views.__alloyId1397);
setValue ? $.__views.__alloyId1397.addEventListener("click", setValue) : __defers["$.__views.__alloyId1397!click!setValue"] = true;
$.__views.__alloyId1398 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Virgin Islands",
id: "__alloyId1398"
});
$.__views.__alloyId1397.add($.__views.__alloyId1398);
$.__views.__alloyId1399 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1399"
});
$.__views.__alloyId1397.add($.__views.__alloyId1399);
$.__views.__alloyId1400 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1400"
});
$.__views.__alloyId1397.add($.__views.__alloyId1400);
$.__views.__alloyId1401 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "VA",
id: "__alloyId1401"
});
$.__views.StatePicker.add($.__views.__alloyId1401);
setValue ? $.__views.__alloyId1401.addEventListener("click", setValue) : __defers["$.__views.__alloyId1401!click!setValue"] = true;
$.__views.__alloyId1402 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Virginia",
id: "__alloyId1402"
});
$.__views.__alloyId1401.add($.__views.__alloyId1402);
$.__views.__alloyId1403 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1403"
});
$.__views.__alloyId1401.add($.__views.__alloyId1403);
$.__views.__alloyId1404 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1404"
});
$.__views.__alloyId1401.add($.__views.__alloyId1404);
$.__views.__alloyId1405 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "WA",
id: "__alloyId1405"
});
$.__views.StatePicker.add($.__views.__alloyId1405);
setValue ? $.__views.__alloyId1405.addEventListener("click", setValue) : __defers["$.__views.__alloyId1405!click!setValue"] = true;
$.__views.__alloyId1406 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Washington",
id: "__alloyId1406"
});
$.__views.__alloyId1405.add($.__views.__alloyId1406);
$.__views.__alloyId1407 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1407"
});
$.__views.__alloyId1405.add($.__views.__alloyId1407);
$.__views.__alloyId1408 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1408"
});
$.__views.__alloyId1405.add($.__views.__alloyId1408);
$.__views.__alloyId1409 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "WV",
id: "__alloyId1409"
});
$.__views.StatePicker.add($.__views.__alloyId1409);
setValue ? $.__views.__alloyId1409.addEventListener("click", setValue) : __defers["$.__views.__alloyId1409!click!setValue"] = true;
$.__views.__alloyId1410 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "West Virginia",
id: "__alloyId1410"
});
$.__views.__alloyId1409.add($.__views.__alloyId1410);
$.__views.__alloyId1411 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1411"
});
$.__views.__alloyId1409.add($.__views.__alloyId1411);
$.__views.__alloyId1412 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1412"
});
$.__views.__alloyId1409.add($.__views.__alloyId1412);
$.__views.__alloyId1413 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "WI",
id: "__alloyId1413"
});
$.__views.StatePicker.add($.__views.__alloyId1413);
setValue ? $.__views.__alloyId1413.addEventListener("click", setValue) : __defers["$.__views.__alloyId1413!click!setValue"] = true;
$.__views.__alloyId1414 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Wisconsin",
id: "__alloyId1414"
});
$.__views.__alloyId1413.add($.__views.__alloyId1414);
$.__views.__alloyId1415 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1415"
});
$.__views.__alloyId1413.add($.__views.__alloyId1415);
$.__views.__alloyId1416 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1416"
});
$.__views.__alloyId1413.add($.__views.__alloyId1416);
$.__views.__alloyId1417 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
value: "WY",
id: "__alloyId1417"
});
$.__views.StatePicker.add($.__views.__alloyId1417);
setValue ? $.__views.__alloyId1417.addEventListener("click", setValue) : __defers["$.__views.__alloyId1417!click!setValue"] = true;
$.__views.__alloyId1418 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: "Wyoming",
id: "__alloyId1418"
});
$.__views.__alloyId1417.add($.__views.__alloyId1418);
$.__views.__alloyId1419 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1419"
});
$.__views.__alloyId1417.add($.__views.__alloyId1419);
$.__views.__alloyId1420 = Ti.UI.createView({
backgroundColor: "#C0C6D0",
width: Ti.UI.FILL,
height: 1,
top: null,
bottom: 0,
id: "__alloyId1420"
});
$.__views.__alloyId1417.add($.__views.__alloyId1420);
exports.destroy = function() {};
_.extend($, $.__views);
var APP = require("/core");
var args = arguments[0] || {};
__defers["$.__views.__alloyId1209!click!setValue"] && $.__views.__alloyId1209.addEventListener("click", setValue);
__defers["$.__views.__alloyId1213!click!setValue"] && $.__views.__alloyId1213.addEventListener("click", setValue);
__defers["$.__views.__alloyId1217!click!setValue"] && $.__views.__alloyId1217.addEventListener("click", setValue);
__defers["$.__views.__alloyId1221!click!setValue"] && $.__views.__alloyId1221.addEventListener("click", setValue);
__defers["$.__views.__alloyId1225!click!setValue"] && $.__views.__alloyId1225.addEventListener("click", setValue);
__defers["$.__views.__alloyId1229!click!setValue"] && $.__views.__alloyId1229.addEventListener("click", setValue);
__defers["$.__views.__alloyId1233!click!setValue"] && $.__views.__alloyId1233.addEventListener("click", setValue);
__defers["$.__views.__alloyId1237!click!setValue"] && $.__views.__alloyId1237.addEventListener("click", setValue);
__defers["$.__views.__alloyId1241!click!setValue"] && $.__views.__alloyId1241.addEventListener("click", setValue);
__defers["$.__views.__alloyId1245!click!setValue"] && $.__views.__alloyId1245.addEventListener("click", setValue);
__defers["$.__views.__alloyId1249!click!setValue"] && $.__views.__alloyId1249.addEventListener("click", setValue);
__defers["$.__views.__alloyId1253!click!setValue"] && $.__views.__alloyId1253.addEventListener("click", setValue);
__defers["$.__views.__alloyId1257!click!setValue"] && $.__views.__alloyId1257.addEventListener("click", setValue);
__defers["$.__views.__alloyId1261!click!setValue"] && $.__views.__alloyId1261.addEventListener("click", setValue);
__defers["$.__views.__alloyId1265!click!setValue"] && $.__views.__alloyId1265.addEventListener("click", setValue);
__defers["$.__views.__alloyId1269!click!setValue"] && $.__views.__alloyId1269.addEventListener("click", setValue);
__defers["$.__views.__alloyId1273!click!setValue"] && $.__views.__alloyId1273.addEventListener("click", setValue);
__defers["$.__views.__alloyId1277!click!setValue"] && $.__views.__alloyId1277.addEventListener("click", setValue);
__defers["$.__views.__alloyId1281!click!setValue"] && $.__views.__alloyId1281.addEventListener("click", setValue);
__defers["$.__views.__alloyId1285!click!setValue"] && $.__views.__alloyId1285.addEventListener("click", setValue);
__defers["$.__views.__alloyId1289!click!setValue"] && $.__views.__alloyId1289.addEventListener("click", setValue);
__defers["$.__views.__alloyId1293!click!setValue"] && $.__views.__alloyId1293.addEventListener("click", setValue);
__defers["$.__views.__alloyId1297!click!setValue"] && $.__views.__alloyId1297.addEventListener("click", setValue);
__defers["$.__views.__alloyId1301!click!setValue"] && $.__views.__alloyId1301.addEventListener("click", setValue);
__defers["$.__views.__alloyId1305!click!setValue"] && $.__views.__alloyId1305.addEventListener("click", setValue);
__defers["$.__views.__alloyId1309!click!setValue"] && $.__views.__alloyId1309.addEventListener("click", setValue);
__defers["$.__views.__alloyId1313!click!setValue"] && $.__views.__alloyId1313.addEventListener("click", setValue);
__defers["$.__views.__alloyId1317!click!setValue"] && $.__views.__alloyId1317.addEventListener("click", setValue);
__defers["$.__views.__alloyId1321!click!setValue"] && $.__views.__alloyId1321.addEventListener("click", setValue);
__defers["$.__views.__alloyId1325!click!setValue"] && $.__views.__alloyId1325.addEventListener("click", setValue);
__defers["$.__views.__alloyId1329!click!setValue"] && $.__views.__alloyId1329.addEventListener("click", setValue);
__defers["$.__views.__alloyId1333!click!setValue"] && $.__views.__alloyId1333.addEventListener("click", setValue);
__defers["$.__views.__alloyId1337!click!setValue"] && $.__views.__alloyId1337.addEventListener("click", setValue);
__defers["$.__views.__alloyId1341!click!setValue"] && $.__views.__alloyId1341.addEventListener("click", setValue);
__defers["$.__views.__alloyId1345!click!setValue"] && $.__views.__alloyId1345.addEventListener("click", setValue);
__defers["$.__views.__alloyId1349!click!setValue"] && $.__views.__alloyId1349.addEventListener("click", setValue);
__defers["$.__views.__alloyId1353!click!setValue"] && $.__views.__alloyId1353.addEventListener("click", setValue);
__defers["$.__views.__alloyId1357!click!setValue"] && $.__views.__alloyId1357.addEventListener("click", setValue);
__defers["$.__views.__alloyId1361!click!setValue"] && $.__views.__alloyId1361.addEventListener("click", setValue);
__defers["$.__views.__alloyId1365!click!setValue"] && $.__views.__alloyId1365.addEventListener("click", setValue);
__defers["$.__views.__alloyId1369!click!setValue"] && $.__views.__alloyId1369.addEventListener("click", setValue);
__defers["$.__views.__alloyId1373!click!setValue"] && $.__views.__alloyId1373.addEventListener("click", setValue);
__defers["$.__views.__alloyId1377!click!setValue"] && $.__views.__alloyId1377.addEventListener("click", setValue);
__defers["$.__views.__alloyId1381!click!setValue"] && $.__views.__alloyId1381.addEventListener("click", setValue);
__defers["$.__views.__alloyId1385!click!setValue"] && $.__views.__alloyId1385.addEventListener("click", setValue);
__defers["$.__views.__alloyId1389!click!setValue"] && $.__views.__alloyId1389.addEventListener("click", setValue);
__defers["$.__views.__alloyId1393!click!setValue"] && $.__views.__alloyId1393.addEventListener("click", setValue);
__defers["$.__views.__alloyId1397!click!setValue"] && $.__views.__alloyId1397.addEventListener("click", setValue);
__defers["$.__views.__alloyId1401!click!setValue"] && $.__views.__alloyId1401.addEventListener("click", setValue);
__defers["$.__views.__alloyId1405!click!setValue"] && $.__views.__alloyId1405.addEventListener("click", setValue);
__defers["$.__views.__alloyId1409!click!setValue"] && $.__views.__alloyId1409.addEventListener("click", setValue);
__defers["$.__views.__alloyId1413!click!setValue"] && $.__views.__alloyId1413.addEventListener("click", setValue);
__defers["$.__views.__alloyId1417!click!setValue"] && $.__views.__alloyId1417.addEventListener("click", setValue);
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller;
|
document.write(
'<div class="footer">'
+' <p>@前端开发部 陈新垲</p>'
+' </div>'
);
|
import {NativeModules} from 'react-native';
const RNPreferences = NativeModules.RNPreferences;
export default RNPreferences;
|
const knex = require('../config/knex.js');
const bookshelf = require('bookshelf')(knex);
const model = bookshelf.Model.extend({
tableName: 'users',
hasTimestamps: true,
});
module.exports = {
fetch: id => model.where('id', id).fetch(),
save: (id, username) => {
return model.forge({
id,
username,
}).save({}, {
method: 'insert',
});
},
update: (id, data) => {
return model.where('id', id).save(data, {patch: true});
},
fetchByEmail: email => model.where('email', email).fetch(),
}
|
// Create array/objects of 4 movies, with individual rating and boolean has(n't) watched. Then print as a coherent sentence.
var movies = [
{
// movie 1
name: "The Lord of the Rings",
rating: 4.5,
hasWatched: true
},
{
// movie 2
name: "Jurassic World",
rating: 3,
hasWatched: false
},
{
// movie 3
name: "Rush",
rating: 5,
hasWatched: true
},
{
// movie 4
name: "London Spy",
rating: 4.5,
hasWatched: true
}
];
movies.forEach(function(movie) {
if (movie.hasWatched != false) {
console.log("You have seen " + movie.name + " - rating " + movie.rating);
}
else {
console.log("You haven't seen " + movie.name + " - rating " + movie.rating);
}
});
|
const apiURL = "https://api.openweathermap.org/data/2.5/weather?id=5604473&appid=164f498c15ca0ca0e8f322a9fd449b46&units=imperial";
fetch(apiURL)
.then((response) => response.json())
.then((jsObject) => {
console.log(jsObject);
let temp = jsObject.main.temp;
let windSpeed = jsObject.wind.speed;
//let windSpeed = jsObject.wind.speed;
//Current Condition
document.getElementById('currentCondition').textContent = jsObject.weather[0].main;
//Current Temp
document.getElementById('currentTemp').textContent = Math.round(temp) + " °F";
//Highest Temp
document.getElementById('high-temp').textContent = Math.round(jsObject.main.temp_max);
//Wind Speed
document.getElementById('wind-speed').textContent = windSpeed;
//Wind Chill
let speed = Math.pow(windSpeed, 0.16); //Math.pow(jsObject.wind.speed, 0.16);
let windChill = Math.round(35.74 + (0.6215 * temp) - (35.75 * speed) + (0.4275 * temp * speed));
if (temp <= 50 && windSpeed > 3) {
document.getElementById('wind-chill').textContent = windChill + " °F";
} else {
document.getElementById('wind-chill').textContent = "N/A";
}
//Humidity Level
document.getElementById('humidity').textContent = jsObject.main.humidity + " %";
});
const forecastURL = "https://api.openweathermap.org/data/2.5/forecast?id=5604473&appid=164f498c15ca0ca0e8f322a9fd449b46&units=imperial";
fetch(forecastURL)
.then((response) => response.json())
.then((jsObject) => {
console.log(jsObject);
const fiveDays = jsObject.list.filter(item => item.dt_txt.includes('18:00:00'));
for (i = 0; i < 1; i++) {
fiveDays.forEach(forecast => {
console.log(forecast);
let card = document.createElement('section');
let weekDay = document.createElement('p');
let image = document.createElement('img');
let temp = document.createElement('p');
var date = new Date(forecast.dt_txt);
var day = date.toString();
day = day.slice(0, 3);
weekDay.textContent = day;
image.setAttribute('src', "https://via.placeholder.com/100.png?text=Placeholder");
image.setAttribute('data-src', 'https://openweathermap.org/img/wn/' + forecast.weather[0].icon + '@2x.png');
image.setAttribute('alt', forecast.weather[0].description);
temp.textContent = Math.round(forecast.main.temp) + " °F";
card.className = "days";
card.appendChild(weekDay);
card.appendChild(image);
card.appendChild(temp);
document.querySelector('div.cards').appendChild(card);
})
}
})
.then(function(imagesToLoad = document.querySelectorAll('img[data-src]')) {
const loadImages = (image) => {
image.setAttribute('src', image.getAttribute('data-src'));
image.onload = () => {
image.removeAttribute('data-src');
};
};
const imgOptions = {
threshold: 0
};
if ('IntersectionObserver' in window) {
const observer = new IntersectionObserver((items, observer) => {
items.forEach((item) => {
if (item.isIntersecting) {
loadImages(item.target);
observer.unobserve(item.target);
}
});
}, imgOptions);
imagesToLoad.forEach((img) => {
observer.observe(img);
});
} else {
imagesToLoad.forEach((img) => {
loadImages(img);
});
}
}
);
|
const express = require('express')
const app = express()
require('dotenv').config()
const db = require('./dbConnect/connection')
const router = require('./routes/routes')
app.use(express.json())
app.use('/',router)
app.listen(process.env.PORT,()=>console.log(`Server is Running on port ${process.env.PORT}`))
|
//--- Loading Mask
window.onload = function () { $('#loading-mask').fadeOut(500); };
$('a:not([href^="#"]):not([href^="javascript://"]):not([target="_blank"]):not([tabindex="0"]):not([href^="javascript:if(window.print)window.print()"])').click(function (e) {
$(".loader").fadeIn("slow");
});
//---
//-- Form Validate
$('#frm').validate();
$('.frm').validate();
$('button:submit').click(function (e) {
var isValid = $(this).parents('form:first').valid();
if (isValid) {
$(".loader").fadeIn("slow");
}
});
//---
//--- Enabling checkbox to post their data
$('input:checkbox').click(function () {
var getAttr = $(this).attr('value');
if (getAttr == 'false') {
$(this).attr('checked', true);
$(this).attr('value', true);
}
if (getAttr == 'true') {
$(this).removeAttr('checked');
$(this).attr('value', false);
}
});
//---
//--- General Input Masks
$(function () {
$(".phoneMask").inputmask({
"alias": "phone",
"url": "../../../Scripts/Input Mask/phone-codes/phone-codes.js"
});
$(".numericMask").inputmask({ "alias": "numeric", "allowMinus": false, "allowPlus": false });
$(".decimalMask").inputmask({
"alias": "decimal",
"groupSeparator": ",",
"autoGroup": true,
"allowMinus": false,
"allowPlus": false,
"digits": "4",
"removeMaskOnSubmit": true
});
$(".urlMask").inputmask('Regex', { regex: "^(http\:\/\/|https\:\/\/)?([a-z0-9][a-z0-9\-]*\.)+[a-z0-9][a-z0-9\-]*$" });
$(".emailMask").inputmask({ "alias": "email" });
$(".zipCodeMask").inputmask({ "alias": "numeric", "allowMinus": false, "allowPlus": false });
$(".alphanumericMask").inputmask('Regex', { regex: "[a-zA-Z0-9 ]{1,50}" });
$(".alphanumericNoSpaceMask").inputmask('Regex', { regex: "[a-zA-Z0-9\-_]{1,50}" });
});
//---
|
import React from 'react'
import {Column, Row} from "simple-flexbox";
function DashBoardView(props) {
let {state, onChangeEvent} = props;
return (
<Column className="w-100 vh-100 align-items-center justify-content-center">
<div className="display-flex align-items-center fs-40">
DASHBOARD COMPONENT
</div>
</Column>
);
}
function HeaderComponent(props) {
return (
<Row vertical="center" className="justify-content-between">
<img src="/images/chilledblitz-logo.png" alt='app-logo' className="w-150"/>
</Row>
)
}
function dashboardComponent(props) {
return (
<Column horizontal={'center'} className="w-100 p-3 min-vh-100 h-100 justify-content-between">
<Column className="w-100">
{HeaderComponent(props)}
{DashBoardView(props)}
</Column>
</Column>
);
}
export default dashboardComponent;
|
import {combineReducers} from "redux";
import {loadingReducer} from "./loadingReducer";
export default combineReducers({
loadingReducer
})
|
var searchData=
[
['il9163_2fst7735_3a_20il9163_2fst7735_20control_20functions',['IL9163/ST7735: il9163/st7735 control functions',['../group___i_l9163___s_t7734___a_p_i.html',1,'']]],
['ili9341_3a_20ili9341_20control_20functions',['ili9341: ili9341 control functions',['../group__ili9341___a_p_i.html',1,'']]],
['i2c_2fspi_3a_20physical_20interface_20functions',['I2C/SPI: physical interface functions',['../group___l_c_d___h_w___i_n_t_e_r_f_a_c_e___a_p_i.html',1,'']]]
];
|
(function () {
'use strict';
angular
.module('StationCreator')
.directive('editorTools', EditorPanel);
EditorPanel.$inject = [
'$log', '$rootScope',
'StateManager', 'MobidulService'
];
function EditorPanel(
$log, $rootScope,
StateManager, MobidulService
) {
return {
restrict: 'E',
template:
'<div>' +
'<md-button ng-repeat="(element, config) in ctrl.editorConfig"' +
' ng-click="ctrl.addElement(element)" class="editor-add-button">' +
'<md-icon>{{config.icon}}</md-icon>' +
'<span class="button-label">{{element | translate}}</span>' +
'</md-button>' +
'</div>',
scope: {},
link: function ($scope, $element, $attr, ctrl) {
},
controller: EditorPanelController,
controllerAs: 'ctrl'
};
function EditorPanelController($scope, $element, $attrs) {
var ctrl = this;
var currentMobidulCode = StateManager.state.params.mobidulCode;
MobidulService.getMobidulConfig(currentMobidulCode)
.then(function(config){
//$log.info('config in editorpanel:');
//$log.debug(config);
ctrl.editorConfig = config.elements;
// if ( isCordova ) {
// delete ctrl.editorConfig.BLUETOOTH;
// }
});
ctrl.addElement = function(type){
//$log.debug(type);
$rootScope.$broadcast('add:editorElement', type);
}
}
}
})();
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _prosemirrorModel = require('prosemirror-model');
var _prosemirrorState = require('prosemirror-state');
var _prosemirrorTransform = require('prosemirror-transform');
var _prosemirrorView = require('prosemirror-view');
var _splitListItem = require('./splitListItem');
var _splitListItem2 = _interopRequireDefault(_splitListItem);
var _UICommand2 = require('./ui/UICommand');
var _UICommand3 = _interopRequireDefault(_UICommand2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ListSplitCommand = function (_UICommand) {
(0, _inherits3.default)(ListSplitCommand, _UICommand);
function ListSplitCommand(schema) {
(0, _classCallCheck3.default)(this, ListSplitCommand);
var _this = (0, _possibleConstructorReturn3.default)(this, (ListSplitCommand.__proto__ || (0, _getPrototypeOf2.default)(ListSplitCommand)).call(this));
_initialiseProps.call(_this);
return _this;
}
return ListSplitCommand;
}(_UICommand3.default);
var _initialiseProps = function _initialiseProps() {
this.execute = function (state, dispatch, view) {
var selection = state.selection,
schema = state.schema;
var tr = (0, _splitListItem2.default)(state.tr.setSelection(selection), schema);
if (tr.docChanged) {
dispatch && dispatch(tr);
return true;
} else {
return false;
}
};
};
exports.default = ListSplitCommand;
|
"use strict";
function showFirstMessage(text) {
console.log(text);
}
showFirstMessage("Hello world");
function calc (a , b){
return (a + b);
}
console.log(calc(1 , 2));
console.log(calc(1 , 3));
console.log(calc(5 , 2));
const logger = function() {
console.log("hellow")
};
logger();
const minus = (a , b) => a-b;
const t = a => {
//код более двух строк
};
|
$( document ).ready(function() {
$(".input").on("click",".btn_timeload", function(){
var flabel=false;
var index = $('#input_channels>.timer_input').length+1;
$(this).siblings("input:checked").each(function(){
if (!flabel){
var sourceLbl = document.createElement("div");
sourceLbl.innerHTML = "<label>Timer"+index+"</label>";
$('#input_channels').append(sourceLbl);
$('#input_channels>div:last-child').addClass("input_source changeWithPanel timer_input loaded_channel");
var sourceUl = document.createElement("ul");
$('#input_channels').append(sourceUl);
var listItem = document.createElement("li");
flabel=true;
}
var listItem = document.createElement("li");
listItem.innerHTML =
" <div>"+
" <a class='channel_title active'>current " + $(this).attr('name') + "</a>"+
" <button class='channel_delete' type='button'> - delete </button>"+
" <button class='channel_timestamp' type='button' title='set the input as a time-stamp'><span class='fa fa-clock-o'></span></button>"+
" <label class='channel_parameter timer_element'>" + $(this).attr('value') + "</label>" +
" </div>";
$('#input_channels>ul:last-child').append(listItem);
$('#input_channels>ul:last-child>li:last-child').addClass("timer_channel active");
$('#input_channels>ul:last-child>li:last-child .channel_parameter').hide();
inputData["current " + $(this).attr('name')]=[];
//var inputVirtualAlgo = "return getTime("+$(this).attr('value')+");";
var inputVirtualAlgoResult = new Function('return getTime("'+$(this).attr("value")+'")');
inputData["current " + $(this).attr('name')].push(inputVirtualAlgoResult);
InputNms["current " + $(this).attr('name')]="";
$('.input').removeClass('active');
$('.input').find('.panel_title').addClass('active');
$('.input').find('.vertical_bar').addClass('active');
$('.div_logic input[name="data"]').autocomplete({source:InputNms});
return true;
});
$('#div_addChoice').slideUp();
$('#input_modules').slideUp();
});
});
function getTime(input){
if (input=="yr"){var a = new Date().getFullYear(); return a;}
if (input=="mo"){var a = new Date().getMonth(); return a;}
if (input=="dt"){var a = new Date().getDate(); return a;}
if (input=="dy"){var a = new Date().getDay(); return a;}
if (input=="hr"){var a = new Date().getHours(); return a;}
if (input=="mi"){var a = new Date().getMinutes(); return a;}
if (input=="se"){var a = new Date().getSeconds(); return a;}
}
|
import React, {Component}from "react";
import {Col, Button} from 'reactstrap';
function CardContent(props) {
return (
<div className="round bg-light">
<div className="align-items-center p-3">
<h5 className="styleLocationLabel">{props.location}</h5>
<p className="styleCardTitle">{props.title}</p>
<Button color="danger rounded-pill px-3">Take Action</Button>
</div>
</div>
);
}
class Cards extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Col xs="12" sm="6" lg="3" id={this.props.id}>
<CardContent
title={this.props.title}
location={this.props.location}
description={this.props.category}
/>
</Col>
);
}
}
export default Cards
|
import { createSlice } from '@reduxjs/toolkit';
import { v4 as uuidv4 } from 'uuid';
let nextStepId = 1
export const trackerSlice = createSlice({
name: 'tracker',
initialState: {
logs: [],
session_id: uuidv4(),
user_id: uuidv4(),
current_filters: null,
impressions: null,
prices: null,
},
reducers: {
generateLog: {
reducer(state, action) {
const { id, data } = action.payload
const newLog = {
"user_id": state.user_id,
"session_id": state.session_id,
"timestamp": ~~(Date.now() / 1000),
"step": id,
"action_type": data.action_type,
"reference": data.reference.toString(),
"platform": "KR",
"city": "Seoul, South Korea",
"device": "desktop",
"current_filters": null,
"impressions": data.impressions ? data.impressions : state.impressions,
"prices": data.prices ? data.prices : state.prices
}
state.logs.push(newLog)
if (data.impressions && data.prices) {
state.impressions = data.impressions;
state.prices = data.prices;
}
// state.current_filters = data.current_filters;
},
prepare(data) {
return { payload: { data, id: nextStepId++ } }
}
},
addLastClickOut: {
reducer(state, action) {
const { id } = action.payload
const newLog = {
"user_id": state.user_id,
"session_id": state.session_id,
"timestamp": ~~(Date.now() / 1000),
"step": id,
"action_type": "clickout item",
"reference": "0",
"platform": "KR",
"city": "Seoul, South Korea",
"device": "desktop",
"current_filters": null,
"impressions": state.impressions,
"prices": state.prices
}
state.logs.push(newLog)
// state.current_filters = data.current_filters;
},
prepare() {
return { payload: { id: nextStepId++ } }
}
}
}
});
export const { generateLog, addLastClickOut } = trackerSlice.actions;
// export const selectCount = state => state.counter.value;
export default trackerSlice.reducer;
|
(function(win) {
'use strict';
NodeList.prototype.forEach = Array.prototype.forEach;
NodeList.prototype.indexOf = Array.prototype.indexOf;
win.qs = function (selector, context) {
return (context || document).querySelector(selector);
};
win.qsa = function (selector, context) {
return (context || document).querySelectorAll(selector);
};
win.$on = function (element, event, callback, capture) {
element.addEventListener(event, callback, !!capture);
}
// window.$delegate(qs('section'), 'click', function(){}, 'input')
win.$delegate = function (element, event, callback, target) {
function customEvent(ev) {
var currentElement = ev.target;
var targetElement = win.qsa(target, element);
var hasMatch = targetElement.indexOf(currentElement) > -1;
if (hasMatch) {
callback.call(currentElement, ev);
}
};
window.$on(element, event, customEvent, event === 'focus' || event === 'blur');
}
win.$parent = function (element, selector) {
if (!element.parentNode) return;
try {
if (element.parentNode.tagName.toLowerCase() === selector.toLowerCase()) {
return element.parentNode;
} else if (element.parentNode.classList.contains(selector)) {
return element.parentNode;
}
} catch(e) {
console.warn('cannot find element\'s parent');
return;
}
return win.$parent(element.parentNode, selector);
}
}(window));
|
// @flow
// import type { Point }
import { range } from '../util/array'
export type PlainCard = {
value: string
}
export default class Card {
static createRandomString(length: number): string {
const seed = '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ'
return range(1, length).map(number => seed[Math.floor(Math.random() * seed.length)]).join('')
}
constructor({
value,
}: PlainCard) {
this.value = value
this.id = Card.createRandomString(10)// TODO
}
value: string
}
|
import React, { useState } from "react";
import { v4 as uuid } from "uuid";
import DataEntry from "./DataEntry";
import "antd/dist/antd.css";
import { useSelector } from "react-redux";
import { selectCount } from "./features/counter/counterSlice";
import {
selectTodo,
addToDo,
editToDo,
removeToDo,
} from "./features/todos/todoSlice";
import { useDispatch } from "react-redux";
import Todo from "./Todo";
import "./styles.css";
const ToDoApp = () => {
const count = useSelector(selectCount);
const todoList = useSelector(selectTodo);
const [inputValue, setInputValue] = useState("");
const dispatch = useDispatch();
const inputChange = (e) => {
if (e) {
const el = { id: uuid(), value: e };
dispatch(addToDo(el));
setInputValue("");
}
};
const buttonChange = () => {
if (inputValue) {
const el = { id: uuid(), value: inputValue };
dispatch(addToDo(el));
setInputValue("");
}
};
const handleChange = (evt) => {
setInputValue(evt);
};
const updateTodo = (id, value) => {
dispatch(editToDo({ id: id, value: value }));
};
const allTodo = todoList.map((el) => {
return (
<Todo
key={"todo_" + el.id}
element={el}
updateTodo={updateTodo}
removeToDo={(id) => dispatch(removeToDo(id))}
/>
);
});
return (
<>
<div className="container">
<p className="title">To do List</p>
<p className="title sub"> Completed: {count}</p>
<div className="content">
<DataEntry
inputValue={inputValue}
onChangeInput={handleChange}
onPressEnterInput={inputChange}
onClickButton={buttonChange}
buttonText="Add"
/>
{allTodo}
</div>
</div>
</>
);
};
export default ToDoApp;
|
/*
* delegate prototype book
*/
const animal = {
animalType: '',
name: '',
describe() {
return `${this.name} is a ${this.animalType}`;
},
};
export default animal;
|
'use strict';
var fs = require('fs');
var split = require('split');
var obj = {};
fs.createReadStream('./purchases.txt')
.pipe(split())
.on('data', function (line) {
var cols = line.split('\t');
obj[cols[2]] = obj[cols[2]] ? obj[cols[2]] : 0;
obj[cols[2]] = Math.max(obj[cols[2]], parseFloat(cols[4]));
})
.on('end', function () {
console.log(
'Reno', obj['Reno'], '\n',
'Toledo', obj['Toledo'], '\n',
'Chandler', obj['Chandler']);
});
|
//singleActivityView constructor
var SingleActivityView = function (container, model, activity){
this.container = container.clone();
this.activity = activity;
this.day = null;
//creating the row + divs for one activity
this.div = this.container.find("#timeBox");
this.div2 = this.container.find("#colorBox");
this.updateSingle = function(){
this.div2.html(this.activity.getName());
//update the activity time in the parkedActivities
if(this.day == null){
this.div.html(this.activity.getLength() + " min");
}
//update the activity time for the day
else{
this.div.html(model.days[this.day].getActivityStart(this.activity.getUniqueId()));
}
//update rest of the activity
this.div2.removeClass();
this.div2.addClass("col-md-8 col-xs-8 activity");
var typeString = this.activity.getType().replace(' ','');
this.div2.addClass(typeString);
}
this.container.show();
//Register an observer to the model
model.addObserver(this);
//This function gets called when there is a change at the model
this.update = function(arg){
this.updateSingle();
}
this.updateSingle();
}
|
import profileImage2 from './../../resources/profile_image2.jpg';
import profileImage3 from './../../resources/profile_image3.jpg';
import profileImage4 from './../../resources/profile_image4.jpg';
const NEW_MESSAGE_CHANGE = 'NEW-MESSAGE-CHANGE';
const SEND_MESSAGE = 'SEND-MESSAGE';
let initialState = {
contacts: [
{
userId: 2,
name: "Leo",
imgSrc: profileImage2
},
{
userId: 3,
name: "Grey",
imgSrc: profileImage3
},
{
userId: 4,
name: "Flora",
imgSrc: profileImage4
}
],
dialogs: [
{
userId: 2,
name: "Leo",
imgSrc: profileImage2,
messages: [
{
messageId: 1,
from: "Leo",
data: "15/2/21, 13:00",
text: "Hi!",
recieved: true
},
{
messageId: 2,
from: "Leo",
data: "15/2/21, 14:00",
text: "Hi!!",
recieved: true
}
],
newMessageText: ""
},
{
userId: 3,
name: "Grey",
imgSrc: profileImage3,
messages: [
{
messageId: 1,
from: "Grey",
data: "14/2/21, 14:00",
text: "Good morning!",
recieved: true
}
],
newMessageText: ""
},
{
userId: 4,
name: "Flora",
imgSrc: profileImage4,
messages: [
{
messageId: 1,
from: "Flora",
data: "14/2/21, 14:00",
text: "Good morning!",
recieved: true
}
],
newMessageText: ""
}
]
};
function createNewMessage(text) { // TODO - add messages to currect dialog, messageId, from, data
return {
messageId: 1,
from: "Oscar",
data: "15/2/21, 13:00",
text: text,
recieved: false
};
}
export function dialogsReducer(state = initialState, action) {
switch (action.type) {
case NEW_MESSAGE_CHANGE:
{
let stateCopy = {
...state,
dialogs: [...state.dialogs]
};
stateCopy.dialogs[0].newMessageText = action.text;
return stateCopy;
}
case SEND_MESSAGE:
{
let stateCopy = {
...state,
dialogs: [...state.dialogs]
};
stateCopy.dialogs[0].messages = [...state.dialogs[0].messages, createNewMessage(state.dialogs[0].newMessageText)];
stateCopy.dialogs[0].newMessageText = "";
return stateCopy;
}
default:
return state;
}
}
export function updateNewMessageActionCreator(value) {
return {
type: NEW_MESSAGE_CHANGE,
text: value
};
}
export function sendMessageActionCreator() {
return {
type: SEND_MESSAGE
};
}
|
import React, { Component } from "react";
import logo from "../logo.png";
import BetAbi from "../abis/Bet";
import "./App.css";
import Web3 from "web3";
class App extends Component {
constructor(props) {
super(props);
this.state = {
account: null,
betContract: null,
playerEthId: null,
winnerEthId: null
};
}
async componentWillMount() {
await this.loadWeb3();
await this.loadAccount();
await this.loadContract();
}
async loadWeb3() {
if (window.ethereum) {
window.web3 = new Web3(window.ethereum);
await window.ethereum.enable();
} else if (window.web3) {
window.web3 = new Web3(window.web3.currentProvider);
} else {
alert("Please install MetaMask!");
}
}
async loadAccount() {
const web3 = window.web3;
// Load Account
const accounts = await web3.eth.getAccounts();
this.setState({ account: accounts[0] });
// console.log(this.state.account);
}
async loadContract() {
const web3 = window.web3;
// Load Meme Smart Contract
// Use web3.eth.Contract to fetch the contract. It requires the abi and contractAddress as parameters
// abi and contractAddress can be fetched from the abi json. It is imported as MemeAbi from "../abis/Meme"
// abi and contractAddress need to be fetched from the correct network where the contract is deployed
// network id is fetched using web3.eth.net.getId()
console.log("Fetching smart contract..");
const networkId = await web3.eth.net.getId();
const networkData = BetAbi.networks[networkId];
if (networkData) {
const abi = BetAbi.abi;
const contractAddress = networkData.address;
console.log("Meme Contract address: ", contractAddress);
const betContract = await web3.eth.Contract(abi, contractAddress);
console.log("Smart Contract fetched.");
this.setState({ betContract});
// console.log(this.state.betContract);
} else {
alert("Smart Contract not deployed to the detected network!");
}
}
betFor = event => {
event.preventDefault();
const playerEthId = document.getElementById("playerEthId").value;
const betContract = this.state.betContract;
betContract.methods.betFor(playerEthId, 200).send({ from: this.state.account }, r => {
console.log("Betted");
this.setState({ playerEthId });
});
}
betAgainst = event => {
event.preventDefault();
const playerEthId = document.getElementById("playerEthId").value;
const betContract = this.state.betContract;
betContract.methods.betAgainst(playerEthId, 200).send({ from: this.state.account }, r => {
console.log("Betted");
this.setState({ playerEthId });
});
}
getBettersFor = async event => {
event.preventDefault();
const winnerEthId = document.getElementById("winnerEthId").value;
const betContract = this.state.betContract;
const bettersFor = await betContract.methods.getBettersFor(winnerEthId).call();
console.log("bettersFor:", bettersFor);
};
getBettersAgainst = async event => {
event.preventDefault();
const winnerEthId = document.getElementById("winnerEthId").value;
const betContract = this.state.betContract;
const bettersAgainst = await betContract.methods.getBettersAgainst(winnerEthId).call();
console.log("bettersAgainst:", bettersAgainst);
};
render() {
return (
<div>
<nav className="navbar navbar-dark fixed-top bg-dark flex-md-nowrap p-0 shadow">
<a className="navbar-brand col-sm-3 col-md-2 mr-0" href="#" target="_blank" rel="noopener noreferrer">
AxieBets
</a>
<ul className="navbar-nav px-2">
<li className="nav-item">
<a href="#" className="nav-link">
<span className="text-white">Your wallet: {this.state.account}</span>
</a>
</li>
</ul>
</nav>
<div className="container-fluid mt-5">
<div className="row">
<main role="main" className="col-lg-12 d-flex text-center">
<div className="content mr-auto ml-auto">
<a href="#" target="_blank" rel="noopener noreferrer">
<img src={logo} className="App-logo" alt="logo" />
</a>
<p>Enter ETH address to bet on:</p>
<form onSubmit={this.betFor}>
<input type="text" id="playerEthId" />
<label className="btn btn-primary">
Bet For <input type="submit" hidden />
</label>
</form>
<form onSubmit={this.betAgainst}>
<input type="text" id="playerEthId" />
<label className="btn btn-primary">
Bet Against <input type="submit" hidden />
</label>
</form>
<form onSubmit={this.getBettersFor}>
<input type="text" id="winnerEthId" />
<label className="btn btn-primary">
Get BettersFor <input type="submit" hidden />
</label>
</form>
<form onSubmit={this.getBettersAgainst}>
<input type="text" id="winnerEthId" />
<label className="btn btn-primary">
Get BettersAgainst <input type="submit" hidden />
</label>
</form>
<p>Betted On: {this.state.playerEthId}</p>
<p>Winner: {this.state.winnerEthId}</p>
</div>
</main>
</div>
</div>
</div>
);
}
}
export default App;
|
(function ($) {
window.onload = function () {
$(document).ready(function () {
back_to_top();
moblie_bar();
height_banner();
fix_height_issue();
slider_related_post();
stuck_header();
search_header();
});
};
})(jQuery);
function back_to_top() {
// browser window scroll (in pixels) after which the "back to top" link is shown
var offset = 300,
//browser window scroll (in pixels) after which the "back to top" link opacity is reduced
offset_opacity = 1200,
//duration of the top scrolling animation (in ms)
scroll_top_duration = 700,
//grab the "back to top" link
$back_to_top = $('.cd-top');
//hide or show the "back to top" link
$(window).scroll(function () {
($(this).scrollTop() > offset) ? $back_to_top.addClass('cd-is-visible') : $back_to_top.removeClass('cd-is-visible cd-fade-out');
if ($(this).scrollTop() > offset_opacity) {
$back_to_top.addClass('cd-fade-out');
}
});
//smooth scroll to top
$back_to_top.on('click', function (event) {
event.preventDefault();
$('body,html').animate({
scrollTop: 0,
}, scroll_top_duration
);
});
}
function moblie_bar() {
var $main_nav = $('#main-nav');
var $toggle = $('.toggle');
var defaultData = {
maxWidth: false,
customToggle: $toggle,
// navTitle: 'All Categories',
levelTitles: true,
pushContent: '#container'
};
// add new items to original nav
$main_nav.find('li.add').children('a').on('click', function() {
var $this = $(this);
var $li = $this.parent();
var items = eval('(' + $this.attr('data-add') + ')');
$li.before('<li class="new"><a>' + items[0] + '</a></li>');
items.shift();
if (!items.length) {
$li.remove();
} else {
$this.attr('data-add', JSON.stringify(items));
}
Nav.update(true);
});
// call our plugin
var Nav = $main_nav.hcOffcanvasNav(defaultData);
// demo settings update
const update = (settings) => {
if (Nav.isOpen()) {
Nav.on('close.once', function() {
Nav.update(settings);
Nav.open();
});
Nav.close();
} else {
Nav.update(settings);
}
};
$('.actions').find('a').on('click', function(e) {
e.preventDefault();
var $this = $(this).addClass('active');
var $siblings = $this.parent().siblings().children('a').removeClass('active');
var settings = eval('(' + $this.data('demo') + ')');
update(settings);
});
$('.actions').find('input').on('change', function() {
var $this = $(this);
var settings = eval('(' + $this.data('demo') + ')');
if ($this.is(':checked')) {
update(settings);
} else {
var removeData = {};
$.each(settings, function(index, value) {
removeData[index] = false;
});
update(removeData);
}
});
}
function height_banner(){
var height_bn = $(".main-banner figure").height();
var height_minus = $(".header").height();
height_bn = height_bn - height_minus;
$(".main-banner figure").height(height_bn);
$(window).bind('resize', function(){
var height_bn = $(".main-banner figure").height();
var height_minus = $(".header").height();
height_bn = height_bn - height_minus;
$(".main-banner figure").height(height_bn);
})
}
function fix_height_issue(){
var width = $(".images-resue").width();
var height = $(".images-resue").height();
var height_2 = $(".title-product").height();
var width_blogs = $(".images-blogs").width();
var height_blog = $(".images-blogs").height();
height = width / 1.93;
$(".images-resue").height(height);
height_2 = height * 1.2;
$(".title-product").height(height_2);
height_blog = width_blogs / 1.1;
$(".images-blogs").height(height_blog);
$(window).bind('resize', function(){
var width = $(".images-resue").width();
var height = $(".images-resue").height();
var height_2 = $(".title-product").height();
var width_blogs = $(".images-blogs").width();
var height_blog = $(".images-blogs").height();
height = width / 1.93;
$(".images-resue").height(height);
height_2 = height * 1.2;
$(".title-product").height(height_2);
height_blog = width_blogs / 1.1;
$(".images-blogs").height(height_blog);
})
}
function slider_related_post(){
$('.related-post .owl-carousel').owlCarousel({
loop:true,
margin: 30,
autoplay:true,
nav:false,
dots: true,
autoplayTimeout:5000,
autoplayHoverPause:true,
responsiveClass:true,
responsive:{
0:{
items:1,
},
576:{
items:1,
},
768:{
items:2,
},
1024:{
items:3,
},
1400:{
items:3,
}
}
})
}
function stuck_header(){
var header = $(".header");
var check = true;
window.addEventListener("scroll", function(){
var off_set = window.pageYOffset;
if(off_set > 50){
if(check == true){
header.addClass("stuck");
check = false;
}
}
else{
if(check == false){
header.removeClass("stuck");
check = true;
}
}
})
}
function search_header(){
$("#search-hd").click(function(){
$("body").append("<div class = 'overlay-search'></div>");
$("body").append("<form class = 'form-s-header'><input class = 'form-control' placeholder='Search'/><button><i class='fa fa-search'></i></button></form>");
$(".form-s-header").fadeIn();
$(".form-s-header").addClass("d-flex");
$(".overlay-search").click(function(){
$(".form-s-header").remove();
$(".overlay-search").remove();
});
});
}
|
import React from 'react';
import ReactDOM from 'react-dom';
/************* first *****************/
// const name = 'zcreturn0';
// const element = <h2>Hello {name}</h2>;
// ReactDOM.render(
// element,
// document.getElementById('root')
// );
/************* 定时器 *****************/
// Date.prototype.Format = function (fmt) {
// var o = {
// "M+": this.getMonth() + 1, // 月份
// "d+": this.getDate(), // 日
// "h+": this.getHours(), // 小时
// "m+": this.getMinutes(), // 分
// "s+": this.getSeconds() // 秒
// };
// if (/(y+)/.test(fmt))
// fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
// for (var k in o)
// if (new RegExp("(" + k + ")").test(fmt))
// fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
// return fmt;
// }
// function tick(){
// const timer = <div>
// <p>time:</p>
// <p>{new Date().Format('yyyy-MM-dd hh:mm:ss')}</p>
// </div>;
// ReactDOM.render(timer, document.getElementById('root'));
// }
// setInterval(() => {
// tick();
// }, 1000);
/************* 组件定义方式 *****************/
// 自定义组件首字母必须大写
// 用函数定义组件
// function Welcome(props){
// return <h2>Welcome {props.name}</h2>
// }
// // 用 class 定义组件
// class Hello extends React.Component{
// render(){
// return <h2>Hello {this.props.name}</h2>;
// }
// }
/************* 组件使用方式 *****************/
// 属性会传到组件的props对象上,首字母大写
// const welcomeElement = <Welcome name="return0"></Welcome>;
// ReactDOM.render(
// welcomeElement,
// document.getElementById('root')
// );
// const HelloElement = <Hello name="zc"></Hello>;
// ReactDOM.render(
// HelloElement,
// document.getElementById('root')
// );
/************* 组合组件 *****************/
// props 为只读属性
function Welcome(props){
return <h2>Welcome {props.name}</h2>;
}
function App(props){
return <div>
<Welcome name='aaaaa'></Welcome>
<Welcome name='bbbbb'></Welcome>
<Welcome name='ccccc'></Welcome>
</div>
}
ReactDOM.render(
<App/>,
document.getElementById('root')
);
|
/**************************************************************
* MENU
*************************************************************/
var mainMenu = function(game){}
mainMenu.prototype = {
init: function(){
if(this.game.isDebug){
this.time.advancedTiming = true;
} else{
this.time.advancedTiming = false;
}
},
create: function(){
this.game.allAudios.play('menu');
// this add Text if come from libs/helper.js
addText(this.game, this.game.world.centerX,
this.game.world.centerY-100, "Quit\n Smoking", "80px Arial");
addText(this.game, this.game.world.centerX,
this.game.world.height-30, "Author: hexcola\n Inspired by a Quit Smoking Poster","14px Arial");
var btn_start = this.game.add.sprite(this.game.world.centerX,
this.game.world.centerY+100, 'defaultRes', 'btn_start.png');
btn_start.anchor.set(0.5);
btn_start.inputEnabled = true;
btn_start.events.onInputDown.add(this.startGame, this);
},
startGame: function(){
this.state.start('Gameplay');
this.game.allAudios.stop();
},
render: function(){
if(this.game.isDebug){
this.game.debug.text("FPS:" + this.game.time.fps, 10, 20, "#ffffff");
}
}
}
|
import React, {Component} from 'react';
import {render} from 'react-dom';
import {Link} from 'react-router';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import{IMG_CONSTANT,ICON_PATH} from '../constants/application.constants';
import {getNotificationsCount, showHideSearchCriteria} from '../actions/headerAction';
let imgPath=IMG_CONSTANT.BASE_PATH;
let iconPath=IMG_CONSTANT.ICON_PATH;
class Sidebar extends Component{
constructor(props,context){
super(props, context);
this.state={notificationCount: 0}
}
TriggerNotification(){
this.props.getNotificationsCount(this.props.activeUser.token).then((notificationLength)=>{
this.setState({notificationCount:notificationLength});
}).catch((error)=>{
});
if(screen.width<769){
$(".MobileNav").show();
$(".minGlobalSearch").animate({ height:'0px'});
}
}
headerMenuShow(){
if(screen.width<769){
$(".MobileNav").show();
$(".minGlobalSearch").animate({ height:'0px'});
}
}
render(){
return(
<div className="sidebar">
<div className="logo"><img src={imgPath+"Golf_CNX_Logo_02.svg"}/></div>
<div className="menuBox">
<ul>
<Link to="/home"><li id="home" className="menu home" onClick={this.TriggerNotification.bind(this)}>
<span className="home icons">
<img src="/assets/img/navagition images/Home_Nav_Icon.png" className="home-icon nrmlIcon" id="initial" />
<img src="/assets/img/navagition images/Home_Nav_Icon1_white.png" className="hover-homeIcon hoverIcon" id="onhover" />
</span>Home</li></Link>
<Link to="/feed">
<li id="feed" className="menu feed" onClick={this.headerMenuShow.bind(this)}>
<span className="feed icons">
<img src="/assets/img/navagition images/Feed_Nav_Icon.png" className="feed-icon nrmlIcon" id="initial" />
<img src="/assets/img/navagition images/Feed_Nav_Icon1_white.png" className="hover-feedIcon hoverIcon" id="onhover" />
</span>
Feed</li>
</Link>
<Link to="/groups"><li id="group" className="menu groups"onClick={this.headerMenuShow.bind(this)}>
<span className="groups icons">
<img src="/assets/img/navagition images/Groups_Nav_Icon.png" className="group-icon nrmlIcon" id="initial" />
<img src="/assets/img/navagition images/Groups_Nav_Icon1_white.png" className="hover-groupIcon hoverIcon" id="onhover" />
</span>
Groups</li></Link>
<Link to="/events_"><li id="event" className="menu events"onClick={this.headerMenuShow.bind(this)}>
<span className="events icons">
<img src="/assets/img/navagition images/Events_Nav_Icon1.png" className="event-icon nrmlIcon" id="initial" />
<img src="/assets/img/navagition images/Events_Nav_Icon_white.png" className="hover-eventIcon hoverIcon" id="onhover" />
</span>Events</li></Link>
<Link to="/courses_"><li id="course" className="menu courses"onClick={this.headerMenuShow.bind(this)}>
<span className="courses icons">
<img src="/assets/img/navagition images/Courses_Nav_Icon.png" className="course-icon nrmlIcon" id="initial" />
<img src="/assets/img/navagition images/Courses_Nav_Icon1_white.png" className="hover-courseIcon hoverIcon" id="onhover" />
</span>
Courses
</li></Link>
</ul>
</div>
</div>
);
}
}
Sidebar.contextTypes = {
router: React.PropTypes.object
};
function mapStateToProps(state) {
return {
activeUser: (state.activeUser!=null)?(state.activeUser):(JSON.parse(sessionStorage.getItem('userDetails'))),
};
}
function matchDispatchToProps(dispatch){
return bindActionCreators({ getNotificationsCount, showHideSearchCriteria}, dispatch);
}
export default connect(mapStateToProps, matchDispatchToProps)(Sidebar);
|
'use strict';
const Composer = require('../lib/composer.js');
module.exports = function(Currency) {
Composer.restrictModelMethods(Currency);
};
|
import DS from 'ember-data';
const { Model, belongsTo } = DS;
export default class DeliveryPlaceModel extends Model {
@belongsTo('delivery-kind') deliveryKind;
@belongsTo('geo-coordinate') geoCoordinate;
@belongsTo('postal-address') postalAddress;
}
|
module.exports = async(client) => {
const mysql = require('mysql')
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'Liamclyde*2001',
database: 'Pegasus'
});
console.log(`Ready to RP to Findout!`)
client.channels.cache.get('765193903586148402').send(`The bot has been started on the console!`)
client.user.setPresence({
activity: {
name: 'Crypticc',
type: "LISTENING",
},
status: 'idle'
})
con.connect(function(err) {
if (err) throw err;
client.channels.cache.get('765193903586148402').send("Connected to database **'Pegasus'**!")
});
}
|
import httpStatus from 'http-status/lib/index'
export function catchErrors (err) {
return {
error_type: httpStatus[err.status],
errors: {
default: {
msg: err.message,
stack: err.stack
}
}
}
}
|
import styled from "styled-components";
import { Link } from "react-router-dom";
export const HeaderContainer = styled.header`
grid-area: header;
border: 3px solid var(--gold);
display: flex;
align-items: center;
justify-content: space-between;
background-color: var(--green);
padding: 1rem 4rem;
`;
export const Logo = styled(Link)`
text-decoration: none;
color: var(--gold);
font-size: 2rem;
font-weight: 400;
font-family: "Montserrat", sans-serif;
`;
|
'use strict';
/* @flow */
import React from 'react';
import {
IconNames
} from "@blueprintjs/icons";
import {
options as commonOptions,
settings as commonSettings,
} from '../../utils/common';
import type {
// optionType,
settingsType as commonSettingsType
} from '../../utils/common';
import {
Map,
} from 'immutable';
import ErrorCatcher from '../shared/ErrorCatcher';
import TextInput from './TextInput';
export type settingsType = {
...commonSettingsType,
// options: optionType[],
};
export default function Phone ( props: settingsType ) {
const {
id,
state,
onChange,
value = state.get(`value`),
placeholder = state.get(`placeholder`),
required = state.get(`required`),
className = Phone.settings.className,
} = props;
return (
<ErrorCatcher>
<input
id={id}
name={id}
type="phone"
className={className}
required={required}
placeholder={placeholder}
value={value ? Phone.maskInput(value) : value}
onChange={e => onChange(Phone.unmaskInput(e?.target?.value || ``))} />
</ErrorCatcher>
);
}
Phone.phoneMaskMap = Map({
'usa': /(\d{1,3})?((\d{1,3})?(\d{1,4})?)?$/
});
Phone.maskRemove = /^\+1|[^0-9]/g;
// @TODO - allow country input
// Phone.maskReplace = Phone.phoneMaskMap.get(COUNTRY);
Phone.maskReplace = Phone.phoneMaskMap.get(`usa`);
/**
* @TODO - this assumes US phones - change to int'l once closer
*/
Phone.unmaskInput = value =>
value
.replace(Phone.maskRemove, ``)
.slice(0, 10);
/**
* @TODO - this assumes US phones - change to int'l once closer
*/
Phone.maskInput = value => {
const replacer = ( text, areaCode = ``, fullHalf = ``, prefix = ``, suffix = `` ) => {
let start = ``;
let middle = ``;
let end = ``;
// Example final output: 999
if ( areaCode ) {
start = areaCode;
// Example final output: (999) 999
if ( prefix ) {
start = `(${areaCode}) `;
middle = prefix;
// Example final output: (999) 999-9999
if ( suffix ) {
middle = `${prefix}-`;
end = suffix;
}
}
}
return `${start}${middle}${end}`;
};
if ( value ) {
const cleanValue = Phone.unmaskInput(value);
if ( cleanValue.length > 0 ) {
const prettyValue = cleanValue
.replace(Phone.maskReplace, replacer)
.trim();
return prettyValue;
}
return cleanValue;
}
return ``;
};
Phone.settings = {
...commonSettings,
'controlType': `Phone`,
'label': `Phone input`,
'icon': IconNames.PHONE,
'helpText': `(optional)`,
'className': TextInput.settings.className,
};
Phone.options = commonOptions;
|
'use strict';
var targetingSys = require('./targetingSystem');
module.exports = {
getTargetingSystem: function() {
targetingSys.activate();
}
};
|
class PrsmPara {
rowLength = 30 ;
blockLength = 10 ;
letterWidth = 28;
letterSize = 12 ;
gapWidth = 20;
rowHeight = 40;
topMargin = 46;
bottomMargin = 10 ;
rightMargin = 50;
leftMargin = 50;
middleMargin = 40;//extra space is needed when the start of sequence is skipped
extraPadding = 20;//increase svg width by this amount to prevent rightmost side of svg getting cutoff
numericalWidth = 20;
showNum = true ;
showSkippedLines = true ;
skipLineHeight = 40;
fontWidth = 12 ;//12px font width = 9pt
fontHeight = 18 ;
svgBackgroundColor = "white" ;
massShiftColor = "#64E9EC";
modAnnoYShifts = [-15, -30];
setShowNum = function (isShowNum) {
if (isShowNum) {
this.showNum = true;
this.leftMargin = 30;
this.rightMargin = 30;
}
else {
this.showNum = false;
this.leftMargin = 10;
this.rightMargin = 10;
}
}
/**
* Function to get x coordinate based on the position of the acid
* @param {number} position - Contains position of the Acid
* @param {number} start_value - Contains position of the first Acid
*/
getX = function (pos,startPos) {
let num = pos - startPos ;
let posInRow = num % this.rowLength ;
let gapNum = parseInt(posInRow/this.blockLength) ;
let x = (posInRow) * this.letterWidth + gapNum * this.gapWidth + this.leftMargin;
if (this.showNum) {
x = x + this.numericalWidth;
}
return x;
}
/**
* Function provides the Y coordinate based on the position of the Acid
* @param {number} position - Contains position of the Acid
* @param {number} start_value - Contains position of the first Acid
*/
getY = function (pos, startPos) {
let row = parseInt((pos - startPos) / this.rowLength);
let y = row * this.rowHeight + this.topMargin;
if(startPos != 0 && this.showSkippedLine) {
y = y + this.skipLineHeight;
}
return y;
}
getAACoordinates = function (pos, startPos) {
let x = this.getX(pos, startPos);
let y = this.getY(pos, startPos);
return [x,y];
}
getBpCoordinates = function (pos, startPos) {
let x = this.getX(pos-1, startPos) + this.letterWidth/2;
let y = this.getY(pos-1, startPos);
return [x,y];
}
/**
* Function provides position of the Numbers on the left side of the Acid Sequence
* @param {Integer} position - Provides the position of the left side number
* @param {Integer} start_value - Provides starting number the sequnce after trimming the skipped scids
*/
getLeftNumCoordinates = function (pos, startPos) {
let x = this.leftMargin;
let y = this.getY(pos, startPos);
return [x,y];
}
/**
* Function provides position of the Numbers on the right side of the Acid Sequence
* @param {Integer} position - Provides the position of the left side number
* @param {Integer} start_value - Provides starting number the sequnce after trimming the skipped scids
*/
getRightNumCoordinates = function (pos,startPos) {
let x = this.leftMargin + this.numericalWidth + (this.rowLength - 1 ) * this.letterWidth;
//buffer width-anno_width to make left and right numbers symmetrical as left numbers are left aligned
x = x + ((this.rowLength/ this.blockLength) - 1) * this.gapWidth + this.numericalWidth + this.fontWidth;
let y = this.getY(pos, startPos);
return [x,y];
}
/**
* Function provides position to write information of skipped amino acids at the top of Sequence SVG
*/
getSkipStartCoordinates = function () {
let x = this.leftMargin ;
let y = this.topMargin;
return [x, y]
}
/**
* Function provides position to write information of skipped amino acids at th bottom of Sequence SVG
* @param {Integer} position - Provides the position of the left side number
* @param {Integer} start_value - Provides starting number the sequnce after trimming the skipped scids
*/
getSkipEndCoordinates = function(pos, startPos) {
let x = this.leftMargin ;
let y = this.getY(pos, startPos) ;
return [x, y]
}
addHeight = function() {
this.rowHeight = this.rowHeight * 1.2;
this.topMargin = 40;
}
getSvgSize = function(rowNum, skipBegin, skipEnd) {
let blockNum = this.rowLength/this.blockLength - 1 ;
let width = this.letterWidth * (this.rowLength - 1) + blockNum * this.gapWidth + this.rightMargin + this.leftMargin + this.extraPadding;
if(this.showNum) {
width = width + this.numericalWidth * 2;
}
let height = this.rowHeight * (rowNum -1) + this.letterSize + this.bottomMargin + this.topMargin;
if (skipBegin) {
height = height + this.skipLineHeight;
}
if (skipEnd) {
height = height + this.skipLineHeight;
}
return [width,height];
}
}
|
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { getWeatherIfNeeded } from '../actions'
import AreaMap from '../components/area-map'
import { MAP_TEMP_PIECES, CITY } from '../constants'
import { getPresentWeathers } from '../selectors'
class MapContainer extends React.Component {
static propTypes = {
selectedDate: PropTypes.string.isRequired,
selectedTime: PropTypes.number.isRequired,
weathers: PropTypes.arrayOf(PropTypes.object).isRequired,
dispatch: PropTypes.func.isRequired,
}
componentDidMount() {
const { dispatch, weathers=[], date } = this.props
const cityNeedsFetch = weathers.filter((item) => (!item.isAvailable))
for (let item of cityNeedsFetch) {
const cityno = item.cityno
dispatch(getWeatherIfNeeded({ cityno, date }))
}
}
render() {
const { selectedDate, selectedTime, weathers=[] } = this.props
const date = selectedDate
const time = selectedTime
const data = weathers.map(function(item) {
return {
name: CITY[item.cityno],
value: item.temperature,
}
})
const areaMapData = {
data,
color: ['#0066FF', '#FFFF00', '#FFCC00', '#FF6600', '#FF3300', '#FF0000'],
pieces: MAP_TEMP_PIECES,
}
return (
<div>
<span>date: {date}, time: {time}</span>
<AreaMap
data={areaMapData}
loading={false}
/>
</div>
)
}
}
const mapStateToProps = state => {
return {
selectedDate: state.selectedDate,
selectedTime: state.selectedTime,
weathers: getPresentWeathers(state),
}
}
export default connect(mapStateToProps)(MapContainer)
|
$(document).ready(function(){
//define some globals
canvasWidth = 1000;
canvasHeight = 500;
numberOfBubbles = 30;
minRadius = 30;
maxRadius = 70;
minVelocity = -3;
maxVelocity = 3;
runAnimation = true;
//run main function
main();
//allow user to start and stop the animation
$("#start").click(function(){
runAnimation = true;
});
$("#stop").click(function(){
runAnimation = false;
})
});
//runs the canvas and animation
function main(){
bubbles = new Array(); //create array of bubbles
//initialise the bubbles array
for(var i = 0; i <= numberOfBubbles; i++){
//initialise bubble
bubbles[i] = initialiseBubble();
//draw bubble on canvas
drawBubble(bubbles[i]);
}
//move bubbles to their next position
moveBubble(bubbles);
//repeat this every 50 milliseconds
setInterval(moveBubble, 50);
}
//creates a bubble object, putting in in a random position on the canvas and giving it a random size
function initialiseBubble(){
bubble = new Object();
//keep track of bubbles position on X and Y axis
bubble.x = randomX();
bubble.y = randomY();
bubble.radius = randomRadius();
//ensure that the bubble starts fully within the canvas on the X axis
if((bubble.x + bubble.radius) > canvas.width){
//if it doesn't ensure that it does
bubble.x -= bubble.radius;
}else if((bubble.x - bubble.radius) < 0){
bubble.x += bubble.radius;
}
//ensure that the bubble starts fully within the canvas on the Y axis
if((bubble.y + bubble.radius) > canvas.height){
//if it doesn't ensure that it does
bubble.y -= bubble.radius;
}else if((bubble.y - bubble.radius) < 0){
bubble.y += bubble.radius;
}
//randomly decide whether to give bubble a positive or negative velocity on the X axis
if(decision() == 1){
//give a positive velocity
bubble.xVel = positiveVel();
}else{
//give a negative velocitu
bubble.xVel = minusVel();
}
//randomly decide whether to give bubble a positive or negative velocity on Y axis
if(decision() == true){
//give a positive velocity
bubble.yVel = positiveVel();
}else{
//negative velocity
bubble.yVel = minusVel();
}
//ensure bubble is not stationary
if((bubble.xVel == 0) && (bubble.yVel == 0)){
//if so make it move
bubble.xVel = 2;
}
return bubble;
}//end initialise bubble
//draws the bubble on the canvas using its X and Y position generated earlier
function drawBubble(object){
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc((object.x),(object.y),(object.radius),0,2*Math.PI);
ctx.stroke();
ctx.fillStyle="blue";
ctx.globalAlpha=0.4;
ctx.fill();
}//end drawBubble
//creates the effect of a moving bubble but in reality throws away all the old bubbles and moves each one to a slightly different position
function moveBubble(){
//only run if runAnimation is true - allows user to stop the animation
if(runAnimation == true){
var canvas = document.getElementById('canvas');
//Clear the canvas of all old bubbles
canvas.width = canvas.width;
//check to ensure a bubble is not going off the canvas
for(var i = 0; i <= 30; i++){
//if off to right
if((bubbles[i].x + bubbles[i].radius) > canvas.width){
//make xVel negative
bubbles[i].xVel = -bubbles[i].xVel;
}
//off to the left
else if((bubbles[i].x - bubbles[i].radius) < 0){
//make xVel positive
bubbles[i].xVel = bubbles[i].xVel * -1;
}
//move bubble to new position
bubbles[i].x += bubbles[i].xVel;
//is off at the top
if((bubbles[i].y + bubbles[i].radius) > canvas.height){
//make yVel negative
bubbles[i].yVel = -bubbles[i].yVel;
}//is off at bottom
else if((bubbles[i].y - bubbles[i].radius) < 0){
//make yVel positive
bubbles[i].yVel = bubbles[i].yVel * -1;
}
//move bubble to new position
bubbles[i].y += bubbles[i].yVel;
//re-draw the bubbles
drawBubble(bubbles[i]);
}
}//end if runAnimation
}//end moveBubble
//gives the bubble a random position on the X axis
function randomX(){
return Math.random() * (canvasWidth);
}
//gives the bubble a random position on the Y axis
function randomY(){
return Math.random() * (canvasHeight);
}
//gives the bubble a random size between 30 and 70 rounded to nearest integer
function randomRadius(){
return Math.floor(Math.random() * ((maxRadius - minRadius + 1) + minRadius));
}
//used as to make a decision on whether the bubble heads in a postive or negative direction along an axis
function decision(){
return Math.floor(Math.random() * (2));
}
//generates a random velocity for a bubble between -3 and 0
function minusVel(){
return (Math.random()* 0) + (minVelocity);
}
//generates a random velocity for a bubble between 0 and 3
function positiveVel(){
return (Math.random()* maxVelocity);
}
|
import { SAVED_TWEETS_KEY } from './constants';
import { DateTime } from 'luxon';
export function retrieveSavedTweetsFromLS() {
const savedTweets = localStorage.getItem(SAVED_TWEETS_KEY);
return savedTweets ? new Map((JSON.parse(savedTweets))) : new Map();
}
export function clearSavedTweetsFromLS() {
localStorage.removeItem(SAVED_TWEETS_KEY);
}
export function savedTweetsToTweetsIds(savedTweets) {
const savedTweetsIds = [];
savedTweets.forEach((tweet) => savedTweetsIds.push(tweet.id));
return savedTweetsIds;
}
export function formatDateToTwitterFormat(date) {
const jsDate = new Date(date);
const dateObj = DateTime.fromJSDate(jsDate);
const now = new Date();
if (dateObj.year < now.getFullYear()) {
return dateObj.toLocaleString(DateTime.DATETIME_MED_WITH_WEEKDAY);
}
return dateObj.toRelative();
}
export function formatDateForTooltip(date) {
const jsDate = new Date(date);
const dateObj = DateTime.fromJSDate(jsDate);
return dateObj.toLocaleString(DateTime.DATETIME_MED_WITH_WEEKDAY);
}
|
//This is the file with all the routes for the application
var express = require('express');
var router = express.Router();
var Person = require('../db');
// '/' shows the mainpage of the application
router.get('/', function(req, res, next) {
res.render('index', {title: 'The People Database'});
});
//Link used to get a list of the objects in the database
router.get('/show', function(req, res, next) {
return Person.find(function(err, people) {
if(err) {
next(err);
return;
}
res.send(people);
});
});
//Link used to get the edit page
router.get('/editpage', function(req, res) {
res.render('edit', {title: 'Edit the database'});
});
//POST-link used to add a new entity to the database,
//done by creating a new object and then inserting
//it into the database
router.post('/add', function(req, res) {
var person = new Person({
_id: req.body._id,
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
ssn: req.body.ssn,
dateOfBirth: new Date(req.body.dateOfBirth),
});
var promise = Person.create(person);
promise.then(function(person) {
console.log("created");
return res.status(201).send(person);
},function(err, person) {
console.log(err);
return res.status(400).send(person);
});
});
//Searches a person by the _id number and then tries to update with given values
router.put('/edit', function(req, res) {
return Person.findById(req.body._id, function(err, person) {
person.firstName = req.body.firstName;
person.lastName = req.body.lastName;
person.email = req.body.email;
person.ssn = req.body.ssn;
person.dateOfBirth = req.body.dateOfBirth;
return person.save(function(err) {
if(!err) {
console.log("updated");
}
else {
console.log(err);
}
return res.send(person);
});
});
});
//Searches a person by the _id number and then tries to delete it
router.delete('/delete', function(req, res) {
return Person.findById(req.body._id, function(err, person) {
return person.remove(function(err) {
if(!err) {
console.log("removed");
return res.send('');
}
else {
console.log(err);
}
});
});
});
//Server error handler
router.use(function(err, req, res, next) {
res.status(500).send("Internal server error");
})
module.exports = router;
|
// 登录管理
export default {
type: '店铺分类',
addType: '创建分类',
checkSelectorHolder: '请选择审批状态',
displaySelectorHolder: '请选择上架状态',
checkStatus: '审核状态',
checkStatusA: '待审',
checkStatusB: '已审',
checkStatusC: '驳回',
putaway: '上下架',
putawayA: '出售中',
putawayB: '仓库中',
putawayC: '上架',
putawayD: '指定上架时间',
putawayE: '下架(保存到仓库)',
putawayF: '回收站',
putawayG: '销售状态',
putawayTip: '点击可直接修改上下架状态',
price: '价格',
inventory: '库存',
saled: '已售',
piEdit: '库存及价格',
typeEdit: '商品分类编辑',
parentType: '父分类',
name: '名称',
intro: '简介',
goodsType: '商品类型',
goodsType1: '普通商品',
goodsType2: '团购商品',
goodsType3: '积分商品',
cobuy: '团购',
cobuyPrice: '团购价',
cobuyuser: '拼团人数',
cobuysec: '有效时间',
conbuytip1: '您开启了团购,请正确设置拼团人数(不小于2)',
conbuytip2: '请设置团购订单有效期(在该时间内如果未拼团成功,订单将自动取消)',
hour: '小时',
note: '备注',
edit: '商品编辑',
next: '下一步',
pre: '上一步',
placeholder: '请选择商品',
selectorTitle: '商品选择',
step1: '第一步',
step1Tip: '设置商品类别、属性',
step2: '第二步',
step2Tip: '选择分类以及商品展示图',
step3: '第三步',
step3Tip: '设置商品详细介绍',
step4: '第四步',
step4Tip: '设置商品规格、库存、价格',
sysType: '商品类别',
sysTypeProp: '类目属性',
goodsPic: '商品主图',
picdes: '图文介绍',
sp: '规格、属性',
spec: '规格名',
spec1: '+规格',
prop: '属性名',
prop1: '属性',
shareTip: '您不具有分销权限,如需开通请咨询管理员',
commissionPercent: '佣金比例(‰)',
commissionMoney: '佣金($)',
shareSet: '设置分销商品',
shareGoods: '分销商品',
shareAll: '所有已上架商品',
goodsSelect: '商品选择',
systip1: '请选择商品类别',
dpTypeTip1: '请先设置店铺分类',
dpTypeTip2: '请选择商品所属店铺分类',
nameTip: '请设置商品名称',
imgTip: '请上传商品介绍图',
ipTip: '请至少设置一种商品规格以及价格',
postageRuleTip: '请选择邮费规则',
addressIdTip: '请选择发货地',
needExp: '所需积分',
exp: '积分',
whole: '全部',
goodsInfo1: '基本信息',
goodsInfo2: '销售信息',
goodsInfo3: '图文描述',
goodsInfo4: '物流信息',
goodsInfo5: '售后服务',
riderPost: '同城配送',
riderPostSupport: '支持',
posageRule: '邮费规则',
postAddr: '发货地',
saveGoods: '保存商品信息',
saveTip1: '商品信息保存成功,是否继续添加?',
saveTip2: '商品信息保存成功!',
saveTip3: '是否继续添加?',
xgLabel: '商品限购',
xgLabel1: '不限购',
xgLabel2: '限购',
delTip: '确定删除当前商品?',
restore: '恢复',
commodityPreview: '商品预览',
goodsLang: '商品信息多语言设置',
goodsLangSet: '多语言内容',
goodsLangSetTip: '点击设置',
goodsLangSetTip1: '请先完成默认内容的设置',
baseSetTip: '请先完成以下基础数据设置',
addressSetTip: '地址设置',
postageSet: '邮费规则设置',
dpTypeSet: '店铺分类设置',
weight: '重量',
batchSet: '批量设置',
publishTime: '发布时间',
barcode: '条码',
skuNo: 'SKU 编码',
limitNo: '限购数量',
limitDays: '限购周期',
batchOptTip: '请选择您要操作的商品',
salePrice: '卖价',
originalPrice: '原价',
recommendTag: '推荐词',
serialNo: '排序',
notListed: '未上架',
shangJia: '上架',
refuse: '拒绝',
approvalSuccess: '审批成功',
pending: '待审批',
all: '所有',
publishResources: '发布资源',
pleaseEnterGoodsTypeName: '请输入商品分类的名称',
delCurrentResources: '确定删除当前资源?',
hasBeenAddedTo: '已上架',
removed: '已下架',
imgae: '商品图',
backGoodsList: '返回商品列表',
successTip: '成功提示',
lookGoodsInfo: '查看商品详情',
noSaveGoodsTip: '你有未保存的商品数据,是否恢复数据',
lijihuifusuju: '立即恢复数据',
cancelhuifusuju: '取消恢复数据',
distributionLowProfits: '是否为低利润商品',
yes: '是',
not: '否',
lowMarginGoods: '低利润商品',
noLowMarginGoods: '非低利润商品',
introGoods: '特色',
introDetail: '文字说明',
goodslist: '商品列表',
wkcgm: '无库存购买'
}
|
angular.module('esola').directive('esolaTodos', function () {
return {
scope: {url: '@', heartbeatUrl: '@'},
templateUrl: '/templates/todo-list.html',
controllerAs: 'todoCtrl',
controller: function ($http, $scope, $timeout) {
var vm = this;
vm.todos = [];
var refreshTime = 2500;
var refreshedAtTime = new Date().getTime();
loadUrl($scope.url);
vm.delete = function (todo) {
deleteTodo(todo)
};
vm.changeIsFinished = function (todo) {
$http.put($scope.url + '/' + todo.id, {is_finished: todo.is_finished}).then(function (success) {
}, function (error) {
alert('Ni bilo možno posodobiti status Todo z id ' + todo.id);
});
};
function deleteTodo(todo) {
$http.delete($scope.url + '/' + todo.id).then(function (success) {
removeTodoFromTodos(todo);
}, function (error) {
alert('Ni bilo možno izbrisati Todo z id ' + todo.id);
})
}
function refresh() {
refreshedAtTime = new Date().getTime();
loadUrl($scope.url);
}
function checkIfUpdated() {
$http.get($scope.heartbeatUrl).then(function (success) {
if (success.data.last_modified != null && success.data.last_modified > (refreshedAtTime / 1000))
{
refresh();
}
// If we are showing todos to the user and we get a null, force a refresh, because
// somebody somewhere could have deleted all the todos from the database
else if (vm.todos.length != 0 && success.data.last_modified == null)
{
refresh();
}
else
{
$timeout(function () {
checkIfUpdated();
}, refreshTime);
}
}, function (error) {
$timeout(function () {
checkIfUpdated();
}, refreshTime);
});
}
function loadUrl(url) {
vm.isLoading = true;
$http.get(url).then(function (data) {
vm.isLoading = false;
// Remove todos that are going to be updated
vm.todos.splice(data.data.from - 1, (data.data.to - data.data.from) + 1);
// Add updated todos
var counter = 0;
data.data.data.forEach(function (item) {
vm.todos.splice(data.data.from + counter - 1, 0, item);
counter++;
});
// Load the rest of the todos
if (data.data.next_page_url) {
loadUrl(data.data.next_page_url);
}
else {
// Remove left over todos
vm.todos.splice(data.data.total, vm.todos.length);
$timeout(function () {
checkIfUpdated();
}, refreshTime);
}
}, function (error) {
alert('Prišlo je do napake pri nalaganju Todo liste.')
});
}
function removeTodoFromTodos(todo) {
vm.todos.splice(vm.todos.indexOf(todo), 1);
}
}
};
});
|
import "./App.css";
import { useEffect, useState } from "react";
import {
Navbar,
Container,
CardColumns,
Card,
Button,
Modal,
} from "react-bootstrap";
import image from "./img/rick.png";
function App() {
const [data, setData] = useState([]);
useEffect(() => {
fetch("https://rickandmortyapi.com/api/character/")
.then((response) => response.json())
.then((data) => setData(data.results))
.catch((err) => {
console.log(err.message);
});
}, []);
function showModal() {
<Modal.Dialog>
<Modal.Header closeButton>
<Modal.Title>Modal title</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>Modal body text goes here.</p>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary">Close</Button>
<Button variant="primary">Save changes</Button>
</Modal.Footer>
</Modal.Dialog>;
}
return (
<>
<Navbar bg="dark" variant="dark">
<Navbar.Brand href="#home">
<img
alt=""
src={image}
width="50"
height="50"
className="d-inline-block align-center"
/>
Rick And Morty
</Navbar.Brand>
</Navbar>
<Container>
<CardColumns>
{data.map((character) => (
<Card className="m-4" key={character.id} style={{ width: "18rem" }}>
<Card.Img variant="top" src={character.image} />
<Card.Body>
<Card.Title>{character.name}</Card.Title>
<Card.Text>{character.species}</Card.Text>
<Button variant="primary">More Info</Button>
</Card.Body>
</Card>
))}
</CardColumns>
</Container>
</>
);
}
export default App;
|
angular.module("risevision.widget.common.storage-selector")
.controller("StorageCtrl", ["$scope", "$modalInstance", "storageUrl", "$window", "$log", "STORAGE_MODAL",
function($scope, $modalInstance, storageUrl, $window, $log, STORAGE_MODAL){
$scope.storageUrl = storageUrl;
$scope.isSameOrigin = function (origin) {
var parser = document.createElement("a");
parser.href = STORAGE_MODAL;
return origin.indexOf(parser.host) !== -1;
};
$scope.messageHandler = function (event) {
if (!$scope.isSameOrigin(event.origin)) {
return;
}
if (Array.isArray(event.data)) {
$modalInstance.close(event.data);
} else if (typeof event.data === "string") {
if (event.data === "close") {
$modalInstance.dismiss("cancel");
}
}
};
$window.addEventListener("message", $scope.messageHandler);
}]);
|
const Footer = () => {
return (
<foo>
</foo>
)
}
export default Footer
|
import React from "react";
import PropTypes from "prop-types";
// Components
import Select from "./Select";
const Options = props => (
<div className="currency-container">
<div className="currency" id={props.id}>{props.type}:</div>
<div className="options">
<Select options={props.options} value={props.value} handleChange={props.handleChange} />
</div>
</div>
)
Options.propTypes = {
type: PropTypes.string.isRequired,
id: PropTypes.string,
options: PropTypes.array.isRequired,
value: PropTypes.string.isRequired,
handleChange: PropTypes.func.isRequired
};
export default Options;
|
import firebase from 'firebase'
firebase.initializeApp({
apiKey: "AIzaSyBOJwx3pKj--PkRrGJWKKoyCbnfeeu4X0o",
authDomain: "recipe-46932.firebaseapp.com",
databaseURL: "https://recipe-46932.firebaseio.com",
projectId: "recipe-46932",
storageBucket: "recipe-46932.appspot.com",
messagingSenderId: "159950088877"
});
let authRef =firebase.auth();
//returns a promise after a user is successfully created in database using email and password
export const createUserWithEmailAndPassword = (email,password) =>{
return authRef.createUserWithEmailAndPassword(email,password);
};
//returns a promise after a user is successfully signed In using email and password
//presistance for user to log in or log out
// LOCAL ---- session remains until when explicitly not Signed-out
//SESSION ---- session ends when the page is refreshed or window is closed
export const signInWithEmailAndPassword = (email,password,presistance) =>{
let Presistance=null;
switch (presistance){
case 'LOCAL' : Presistance=firebase.auth.Auth.Persistence.LOCAL;
break;
case 'SESSION' : Presistance=firebase.auth.Auth.Persistence.SESSION;
break;
case 'NONE' : Presistance=firebase.auth.Auth.Persistence.NONE;
break;
}
return authRef.setPersistence(Presistance).then(()=>{
return authRef.signInWithEmailAndPassword(email,password);
});
};
// requires a provider name as a string eg-('GOOGLE') [all in CAPS]
//returns a promise after a user is successfully signed in with google account
// token = response.credential.accessToken
// userInfo = response.user
//presistance for user to log in or log out
// LOCAL ---- session remains until when explicitly not Signed-out
//SESSION ---- session ends when the page is refreshed or window is closed
export const signInWithProvider = (provider,presistance) =>{
let Provider=null;
switch (provider){
case 'GOOGLE': Provider = new firebase.auth.GoogleAuthProvider();
break;
case 'FACEBOOK':Provider = new firebase.auth.FacebookAuthProvider();
break;
case 'TWITTER': Provider = new firebase.auth.TwitterAuthProvider();
break;
case 'GITHUB': Provider = new firebase.auth.GithubAuthProvider();
break;
}
let Presistance=null;
switch (presistance){
case 'LOCAL' : Presistance=firebase.auth.Auth.Persistence.LOCAL;
break;
case 'SESSION' : Presistance=firebase.auth.Auth.Persistence.SESSION;
break;
case 'NONE' : Presistance=firebase.auth.Auth.Persistence.NONE;
break;
}
return authRef.setPersistence(Presistance).then(()=>{
return authRef.signInWithPopup(Provider);
});
};
//returns a promise after the user is successfully signedOut
export const signOut =() =>{
return authRef.signOut();
};
// used to check the user is signed in or not
//returns current user
// if user is null then user is not signedIn
export const getUser = () =>{
return authRef.currentUser;
};
|
'use strict';
var numbers = [2, 3];
var sumNumbers = function (numArray) {
let sumNums = 0;
if (numArray !== null) {
for (let i=0; i<numArray.length;i++) {
sumNums += numArray[i];
} return sumNums;
} else {
throw new Error('Null object not found');
};
};
module.exports = sumNumbers;
|
import React, { Component } from 'react';
import { graphql } from 'react-apollo';
import { Image } from 'semantic-ui-react';
import { QueryGetLoggedUserInfoTopNav } from '../GraphQL';
class TopNavMenu extends Component {
constructor(props) {
super(props)
this.state = {
username: '',
profilePic: null
}
}
componentWillReceiveProps(newProps){
this.setState({
...newProps
})
}
getUrl = (file) => {
try {
if (file) {
const { bucket, region, key } = file;
const url = `https://s3-${region}.amazonaws.com/${bucket}/${key}`;
return url;
}
return null;
} catch (err) {
console.error(err);
}
}
render() {
const { username, profilePic } = this.state
const imageUrl = profilePic ? this.getUrl(profilePic) : null
return (
<span>
{ imageUrl ? <Image avatar src={imageUrl} /> : null } {username}
</span>
)
}
}
export default graphql(
QueryGetLoggedUserInfoTopNav,
{
options: {
fetchPolicy: 'cache-and-network',
},
props: (props) => {
return {
...props.data.getLoggedUserInfo
}
}
}
)(TopNavMenu);
|
import React, { Component, PropTypes } from 'react';
import h from 'mgmt/utils/helpers';
class StudySortSelector extends Component {
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.state = props.studySorting;
this.defaults = {
order: props.orderOptions[0],
field: props.fieldOptions[0],
};
}
onChange({ currentTarget }) {
const { name, id } = currentTarget,
{ field, order } = this.state;
this.props.handleChange({
order: order ? order : this.defaults.order,
field: field ? field : this.defaults.field,
[name]: id,
});
this.setState({ [name]: id });
}
render() {
const { className, fieldOptions, orderOptions, studySorting } = this.props;
return (
<div className={className}>
<div className='flexRow-container'>
<div className='flex-1'>
<label className='control-label' htmlFor='study_sorting-field'>Sort studies by:</label>
<form id='study_sorting-field'>
{fieldOptions.map((field) => {
return (
<label key={field} htmlFor={field}>
<input onChange={this.onChange} checked={studySorting.field == field} type='radio' id={field} name='field' style={{margin: '0 4px'}}/>
{h.caseToWords(field)}
</label>);
})}
</form>
</div>
<div className='flex-1'>
<label className='control-label' htmlFor="study_sorting-order">Order studies by:</label>
<form id='study_sorting-order'>
{orderOptions.map((order) => {
return (
<label key={order} htmlFor={order}>
<input onChange={this.onChange} checked={studySorting.order === order} type='radio' id={order} name='order' style={{margin: '0 4px'}}/>
{h.caseToWords(order)}
</label>);
})}
</form>
</div>
</div>
</div>
);
}
}
StudySortSelector.propTypes = {
handleChange: PropTypes.func.isRequired,
studySorting: PropTypes.shape({
field: PropTypes.string,
order: PropTypes.string,
}).isRequired,
fieldOptions: PropTypes.array.isRequired,
orderOptions: PropTypes.array.isRequired,
};
export default StudySortSelector;
|
// Copyright 2013 - UDS/CNRS
// The Aladin Lite program is distributed under the terms
// of the GNU General Public License version 3.
//
// This file is part of Aladin Lite.
//
// Aladin Lite is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// Aladin Lite is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// The GNU General Public License is available in COPYING file
// along with Aladin Lite.
//
/******************************************************************************
* Aladin Lite project
*
* File ProgressiveCat.js
*
* Author: Thomas Boch[CDS]
*
*****************************************************************************/
// TODO: index sources according to their HEALPix ipix
// TODO : merge parsing with class Catalog
ProgressiveCat = (function() {
// TODO : test if CORS support. If no, need to pass through a proxy
// currently, we suppose CORS is supported
// constructor
ProgressiveCat = function(rootUrl, frameStr, maxOrder, options) {
options = options || {};
this.type = 'progressivecat';
this.rootUrl = rootUrl; // TODO: method to sanitize rootURL (absolute, no duplicate slashes, remove end slash if existing)
// fast fix for HTTPS support --> will work for all HiPS served by CDS
if (Utils.isHttpsContext() && ( /u-strasbg.fr/i.test(this.rootUrl) || /unistra.fr/i.test(this.rootUrl) ) ) {
this.rootUrl = this.rootUrl.replace('http://', 'https://');
}
this.frameStr = frameStr;
this.frame = CooFrameEnum.fromString(frameStr) || CooFrameEnum.J2000;
this.maxOrder = maxOrder;
this.isShowing = true; // TODO : inherit from catalogue
this.name = options.name || "progressive-cat";
this.color = options.color || Color.getNextColor();
this.shape = options.shape || "square";
this.sourceSize = options.sourceSize || 6;
this.selectSize = this.sourceSize + 2;
this.selectionColor = '#00ff00'; // TODO: to be merged with Catalog
this.onClick = options.onClick || undefined; // TODO: inherit from catalog
// we cache the list of sources in each healpix tile. Key of the cache is norder+'-'+npix
this.sourcesCache = new Utils.LRUCache(100);
this.updateShape(options);
this.maxOrderAllsky = 2;
this.isReady = false;
};
// TODO: to be put higher in the class diagram, in a HiPS generic class
ProgressiveCat.readProperties = function(rootUrl, successCallback, errorCallback) {
if (! successCallback) {
return;
}
var propertiesURL = rootUrl + '/properties';
$.ajax({
url: propertiesURL,
method: 'GET',
dataType: 'text',
success: function(propertiesTxt) {
var props = {};
var lines = propertiesTxt.split('\n');
for (var k=0; k<lines.length; k++) {
var line = lines[k];
var idx = line.indexOf('=');
var propName = $.trim(line.substring(0, idx));
var propValue = $.trim(line.substring(idx + 1));
props[propName] = propValue;
}
successCallback(props);
},
error: function(err) { // TODO : which parameters should we put in the error callback
errorCallback && errorCallback(err);
}
});
};
function getFields(instance, xml) {
var attributes = ["name", "ID", "ucd", "utype", "unit", "datatype", "arraysize", "width", "precision"];
var fields = [];
var k = 0;
instance.keyRa = instance.keyDec = null;
$(xml).find("FIELD").each(function() {
var f = {};
for (var i=0; i<attributes.length; i++) {
var attribute = attributes[i];
if ($(this).attr(attribute)) {
f[attribute] = $(this).attr(attribute);
}
}
if ( ! f.ID) {
f.ID = "col_" + k;
}
if (!instance.keyRa && f.ucd && (f.ucd.indexOf('pos.eq.ra')==0 || f.ucd.indexOf('POS_EQ_RA')==0)) {
if (f.name) {
instance.keyRa = f.name;
}
else {
instance.keyRa = f.ID;
}
}
if (!instance.keyDec && f.ucd && (f.ucd.indexOf('pos.eq.dec')==0 || f.ucd.indexOf('POS_EQ_DEC')==0)) {
if (f.name) {
instance.keyDec = f.name;
}
else {
instance.keyDec = f.ID;
}
}
fields.push(f);
k++;
});
return fields;
}
function getSources(instance, csv, fields) {
// TODO : find ra and dec key names (see in Catalog)
if (!instance.keyRa || ! instance.keyDec) {
return [];
}
lines = csv.split('\n');
var mesureKeys = [];
for (var k=0; k<fields.length; k++) {
if (fields[k].name) {
mesureKeys.push(fields[k].name);
}
else {
mesureKeys.push(fields[k].ID);
}
}
var sources = [];
var coo = new Coo();
var newSource;
// start at i=1, as first line repeat the fields names
for (var i=2; i<lines.length; i++) {
var mesures = {};
var data = lines[i].split('\t');
if (data.length<mesureKeys.length) {
continue;
}
for (var j=0; j<mesureKeys.length; j++) {
mesures[mesureKeys[j]] = data[j];
}
var ra, dec;
if (Utils.isNumber(mesures[instance.keyRa]) && Utils.isNumber(mesures[instance.keyDec])) {
ra = parseFloat(mesures[instance.keyRa]);
dec = parseFloat(mesures[instance.keyDec]);
}
else {
coo.parse(mesures[instance.keyRa] + " " + mesures[instance.keyDec]);
ra = coo.lon;
dec = coo.lat;
}
newSource = new cds.Source(ra, dec, mesures);
sources.push(newSource);
newSource.setCatalog(instance);
}
return sources;
};
//ProgressiveCat.prototype.updateShape = cds.Catalog.prototype.updateShape;
ProgressiveCat.prototype = {
init: function(view) {
var self = this;
this.view = view;
if (this.maxOrder && this.frameStr) {
this._loadMetadata();
}
else {
ProgressiveCat.readProperties(self.rootUrl,
function (properties) {
self.properties = properties;
self.maxOrder = self.properties['hips_order'];
self.frame = CooFrameEnum.fromString(self.properties['hips_frame']);
self._loadMetadata();
}, function(err) {
console.log('Could not find properties for HiPS ' + self.rootUrl);
}
);
}
},
updateShape: cds.Catalog.prototype.updateShape,
_loadMetadata: function() {
var self = this;
$.ajax({
url: self.rootUrl + '/' + 'Metadata.xml',
method: 'GET',
success: function(xml) {
self.fields = getFields(self, xml);
self._loadAllskyNewMethod();
},
error: function(err) {
self._loadAllskyOldMethod();
}
});
},
_loadAllskyNewMethod: function() {
var self = this;
$.ajax({
url: self.rootUrl + '/' + 'Norder1/Allsky.tsv',
method: 'GET',
success: function(tsv) {
self.order1Sources = getSources(self, tsv, self.fields);
if (self.order2Sources) {
self.isReady = true;
self._finishInitWhenReady();
}
},
error: function(err) {
console.log('Something went wrong: ' + err);
}
});
$.ajax({
url: self.rootUrl + '/' + 'Norder2/Allsky.tsv',
method: 'GET',
success: function(tsv) {
self.order2Sources = getSources(self, tsv, self.fields);
if (self.order1Sources) {
self.isReady = true;
self._finishInitWhenReady();
}
},
error: function(err) {
console.log('Something went wrong: ' + err);
}
});
},
_loadAllskyOldMethod: function() {
this.maxOrderAllsky = 3;
this._loadLevel2Sources();
this._loadLevel3Sources();
},
_loadLevel2Sources: function() {
var self = this;
$.ajax({
url: self.rootUrl + '/' + 'Norder2/Allsky.xml',
method: 'GET',
success: function(xml) {
self.fields = getFields(self, xml);
self.order2Sources = getSources(self, $(xml).find('CSV').text(), self.fields);
if (self.order3Sources) {
self.isReady = true;
self._finishInitWhenReady();
}
},
error: function(err) {
console.log('Something went wrong: ' + err);
}
});
},
_loadLevel3Sources: function() {
var self = this;
$.ajax({
url: self.rootUrl + '/' + 'Norder3/Allsky.xml',
method: 'GET',
success: function(xml) {
self.order3Sources = getSources(self, $(xml).find('CSV').text(), self.fields);
if (self.order2Sources) {
self.isReady = true;
self._finishInitWhenReady();
}
},
error: function(err) {
console.log('Something went wrong: ' + err);
}
});
},
_finishInitWhenReady: function() {
this.view.requestRedraw();
this.loadNeededTiles();
},
draw: function(ctx, projection, frame, width, height, largestDim, zoomFactor) {
if (! this.isShowing || ! this.isReady) {
return;
}
this.drawSources(this.order1Sources, ctx, projection, frame, width, height, largestDim, zoomFactor);
this.drawSources(this.order2Sources, ctx, projection, frame, width, height, largestDim, zoomFactor);
this.drawSources(this.order3Sources, ctx, projection, frame, width, height, largestDim, zoomFactor);
if (!this.tilesInView) {
return;
}
var sources, key, t;
for (var k=0; k<this.tilesInView.length; k++) {
t = this.tilesInView[k];
key = t[0] + '-' + t[1];
sources = this.sourcesCache.get(key);
if (sources) {
this.drawSources(sources, ctx, projection, frame, width, height, largestDim, zoomFactor);
}
}
},
drawSources: function(sources, ctx, projection, frame, width, height, largestDim, zoomFactor) {
if (! sources) {
return;
}
for (var k=0, len = sources.length; k<len; k++) {
cds.Catalog.drawSource(this, sources[k], ctx, projection, frame, width, height, largestDim, zoomFactor);
}
for (var k=0, len = sources.length; k<len; k++) {
if (! sources[k].isSelected) {
continue;
}
cds.Catalog.drawSourceSelection(this, sources[k], ctx);
}
},
getSources: function() {
var ret = [];
if (this.order1Sources) {
ret = ret.concat(this.order1Sources);
}
if (this.order2Sources) {
ret = ret.concat(this.order2Sources);
}
if (this.order3Sources) {
ret = ret.concat(this.order3Sources);
}
if (this.tilesInView) {
var sources, key, t;
for (var k=0; k<this.tilesInView.length; k++) {
t = this.tilesInView[k];
key = t[0] + '-' + t[1];
sources = this.sourcesCache.get(key);
if (sources) {
ret = ret.concat(sources);
}
}
}
return ret;
},
deselectAll: function() {
if (this.order1Sources) {
for (var k=0; k<this.order1Sources.length; k++) {
this.order1Sources[k].deselect();
}
}
if (this.order2Sources) {
for (var k=0; k<this.order2Sources.length; k++) {
this.order2Sources[k].deselect();
}
}
if (this.order3Sources) {
for (var k=0; k<this.order3Sources.length; k++) {
this.order3Sources[k].deselect();
}
}
var keys = this.sourcesCache.keys();
for (key in keys) {
if ( ! this.sourcesCache[key]) {
continue;
}
var sources = this.sourcesCache[key];
for (var k=0; k<sources.length; k++) {
sources[k].deselect();
}
}
},
show: function() {
if (this.isShowing) {
return;
}
this.isShowing = true;
this.loadNeededTiles();
this.reportChange();
},
hide: function() {
if (! this.isShowing) {
return;
}
this.isShowing = false;
this.reportChange();
},
reportChange: function() {
this.view.requestRedraw();
},
getTileURL: function(norder, npix) {
var dirIdx = Math.floor(npix/10000)*10000;
return this.rootUrl + "/" + "Norder" + norder + "/Dir" + dirIdx + "/Npix" + npix + ".tsv";
},
loadNeededTiles: function() {
if ( ! this.isShowing) {
return;
}
this.tilesInView = [];
var norder = this.view.realNorder;
if (norder>this.maxOrder) {
norder = this.maxOrder;
}
if (norder<=this.maxOrderAllsky) {
return; // nothing to do, hurrayh !
}
var cells = this.view.getVisibleCells(norder, this.frame);
var ipixList, ipix;
for (var curOrder=3; curOrder<=norder; curOrder++) {
ipixList = [];
for (var k=0; k<cells.length; k++) {
ipix = Math.floor(cells[k].ipix / Math.pow(4, norder - curOrder));
if (ipixList.indexOf(ipix)<0) {
ipixList.push(ipix);
}
}
// load needed tiles
for (var i=0; i<ipixList.length; i++) {
this.tilesInView.push([curOrder, ipixList[i]]);
}
}
var t, key;
var self = this;
for (var k=0; k<this.tilesInView.length; k++) {
t = this.tilesInView[k];
key = t[0] + '-' + t[1]; // t[0] is norder, t[1] is ipix
if (!this.sourcesCache.get(key)) {
(function(self, norder, ipix) { // wrapping function is needed to be able to retrieve norder and ipix in ajax success function
var key = norder + '-' + ipix;
$.ajax({
/*
url: Aladin.JSONP_PROXY,
data: {"url": self.getTileURL(norder, ipix)},
*/
// ATTENTIOn : je passe en JSON direct, car je n'arrive pas a choper les 404 en JSONP
url: self.getTileURL(norder, ipix),
method: 'GET',
//dataType: 'jsonp',
success: function(tsv) {
self.sourcesCache.set(key, getSources(self, tsv, self.fields));
self.view.requestRedraw();
},
error: function() {
// on suppose qu'il s'agit d'une erreur 404
self.sourcesCache.set(key, []);
}
});
})(this, t[0], t[1]);
}
}
},
reportChange: function() { // TODO: to be shared with Catalog
this.view && this.view.requestRedraw();
}
}; // END OF .prototype functions
return ProgressiveCat;
})();
|
// 리액트에서 state는 컴포넌트 내부에서 바뀔 수 있는 값을 의미합니다.
// 앞서 선언한 Counter 컴포넌트를 App.js 컴포넌트에서 불러와 렌더링 구현합니다.
import React from "react";
import Counter from "./components/Counter";
const App = () => {
return <Counter />;
};
export default App;
|
import React from "react";
import FilterAction from "./FilterAction";
import FilterRow from "./FilterRow";
import { ReactComponent as Add } from "../assets/svg/plus-circle.svg";
class FilterItem extends React.Component {
render() {
return (
<div className="filter--list">
{this.props.data.map((filter, i) => {
return (
<div className="filter--item" key={`mf__${i}`}>
<p
className="filter--item--title"
style={this.props.data[i].collapsed ? { margin: 0 } : {}}
>
{`${this.props.label} Filter #${i + 1}`}{" "}
<span
className="filter--item--collapse"
onClick={() => this.props.collapse(this.props.type, i)}
>
{this.props.data[i].collapsed ? "Expand" : "Collapse"}
</span>
<span
className="filter--item--remove"
onClick={() => this.props.removeFilter(this.props.type, i)}
>
Delete
</span>
</p>
{!this.props.data[i].collapsed ? (
<>
{this.props.data[i].rows.map((row, r) => {
return (
<FilterRow
key={`mf__${i}_r_${r}`}
row={r}
item={i}
data={row}
add={
r === this.props.data[i].rows.length - 1
? true
: false
}
type={this.props.type}
total={this.props.data[i].rows.length}
addRow={() => this.props.addRow(this.props.type, i)}
removeRow={() =>
this.props.removeRow(this.props.type, i, r)
}
inputChange={this.props.inputChange}
/>
);
})}
<FilterAction
servers={this.props.servers}
settings={this.props.settings}
item={i}
type={this.props.type}
inputChange={this.props.inputChange}
data={this.props.data[i].action}
addAction={this.props.addAction}
removeAction={this.props.removeAction}
/>
</>
) : null}
</div>
);
})}
<div
className="filter--add"
onClick={() => this.props.addFilter(this.props.type)}
>
<p>Add</p>
<Add />
</div>
</div>
);
}
}
export default FilterItem;
|
'use strict';
var dbInterface = require('./dbInterface');
var Collection = module.exports = function Collection(colName) {
this.colName = colName;
};
Collection.prototype.getCollectionName = function () {
return this.colName;
};
Collection.prototype.create = function (data, callback) {
dbInterface.create(this.colName, data, callback);
};
Collection.prototype.update = function (guid, data, callback) {
dbInterface.update(this.colName, guid, data, callback);
};
Collection.prototype.read = function (guid, callback) {
dbInterface.read(this.colName, guid, callback);
};
Collection.prototype.remove = function (guid, callback) {
dbInterface.remove(this.colName, guid, callback);
};
Collection.prototype.truncate = function (callback) {
dbInterface.truncate(this.colName, callback);
};
Collection.prototype.find = function(params, callback) {
dbInterface.find(this.colName, params, callback);
};
Collection.prototype.findOne = function(params, callback) {
dbInterface.findOne(this.colName, params, callback);
};
Collection.prototype.findBy = function (prop, val, callback) {
var query = {};
query[prop] = val;
this.find(query, callback);
};
|
import assessmentStartup from 'assessment/split';
window.app.assessmentStartup = assessmentStartup;
|
import {commentEl, responseEl} from "./templates";
import {commentsToModel, markersToComments} from "./cmtools";
import {template, createElement} from "../../../utilities/travrs";
import {emit, date, Memo, arrayCompare} from "../../../utilities/tools";
require('./comments.scss');
// Component scaffold
const scaffold = `
div.cnxb-comments >
h4 > "Comments"
`;
// ------------------------------------------------
// ---- COMMENTS CORE ----------------
// ------------------------
export default (function Comments () {
// const element = createElement('div.cnxb-comments');
const element = template(scaffold);
const commentsList = new Map();
const userData = {};
let commentsModel;
// Create empty placeholder.
let empty = element.appendChild(createElement('div.cnxb-empty', 'No comments for this revision'));
element.appendChild(empty);
/**
* Add/Remove 'active' class to selected/deselected element.
* @type {Memo}
*/
const active = new Memo((current, active) => {
if (active) active.classList.remove('active');
if (active !== current) {
active = current;
active.classList.add('active');
}
else {
active.classList.remove('active');
active = undefined;
}
return active;
});
const append = (comment) => {
if (empty.parentNode) element.removeChild(empty);
element.appendChild(comment);
return comment;
};
/**
* Run action according to user's choice.
* @param {Event} event Click event.
*/
const detectAction = (event) => {
const {response, cancel, close, scroll} = event.target.dataset;
// Close comment and remove it from display.
if (close) {
const comment = event.target.closest('div.cnxb-comment');
setTimeout(() => {
comment.classList.add('remove');
element.dispatchEvent(emit('remove', { id: close }));
setTimeout(() => {
commentsList.delete(close);
element.removeChild(comment);
if (commentsList.size === 0) element.appendChild(empty);
}, 300);
}, 500);
return;
}
// Send event for scrolling content to the comment position & select active comment.
else if (scroll) {
element.dispatchEvent(emit('scroll.content', { id: scroll }));
select(scroll);
}
// Add new response.
if (response) {
const input = event.target.parentNode.firstElementChild;
// Quit if no input data.
if (input.value.length === 0) return;
// Create comment data.
const data = {
...userData,
date:date(true),
note: input.value
};
input.value = '';
commentsList.get(response).model.responses.push(data);
element.querySelector(`div[data-comment-id="${response}"] div.cnxb-comment-responses`).appendChild(responseEl(data));
}
// Clear input.
else if (cancel) {
event.target.parentNode.firstElementChild.value = '';
}
};
// Set event listener.
element.addEventListener('click', detectAction);
// ---- API METHODS ----------------
/**
* Set user's data required to populate comment DB schema.
* @param {String} user User name.
* @param {String} avatar User selected color.
*/
const user = ({user, avatar}) => {
userData.user = user;
userData.avatar = avatar;
};
/**
* Add new comment to the current scope.
* @param {String} id Commnet ID.
* @param {String} content Commnet's content.
*/
const add = (id, content) => {
const model = {
id,
...userData,
responses: [],
note: content,
date: date(true)
};
if (commentsList.has(id)) throw "Duplicated comment ID";
commentsList.set(id, { model, ref: append(commentEl(model)) });
};
/**
* Get list of commnets for current scope, matches Bridge Archive DB structure.
* @return {Array} List of comments.
*/
const pull = () =>
Array.from(commentsList.values()).map(comment => comment.model);
/**
* Select Coment by its ID, and set it active.
* @param {String} id Comment ID.
* @return {HTMLElement} Reference to the comment node.
*/
const select = (id) => {
const comment = element.querySelector(`div[data-comment-id="${id}"]`);
if (!comment) return;
active(comment);
return comment;
};
/**
* Set commnet for current revision.
* @param {Array} comments List of comment in revision.
* @return {Map} Map with comments in current scope.
*/
const set = (comments) => {
commentsList.clear();
element.innerHTML = '';
// Display empty placeholder.
if (comments.length === 0) element.appendChild(empty);
// Update current scope's commentsList.
return comments.reduce((result, comment) => {
!commentsList.has(comment.id) && result.set(comment.id, { model: comment, ref: append(commentEl(comment)) });
return result;
}, commentsList);
};
/**
* Create searching function to detect which Comments from 'contentElement' are available in last revisoin.
* @param {HTMLElement} contentElement Content element
* @return {function} Function that takes all revisoins, slice latest and detect commnets.
*/
const find = (contentElement) => (revisoins) => {
if (!Array.isArray(revisoins)) revisoins = [revisoins];
// Get last revision.
const lastRevision = revisoins.slice(0,1)[0];
// Exit if no revision.
if (!lastRevision) return;
// Detect comments in content.
const ids = Array.from(contentElement.querySelectorAll('quote[type=comment]')).map((comment) => comment.id);
// Repalce only existing comments.
set(lastRevision.comments.filter((comment) => ~ids.indexOf(comment.id)));
};
/**
* Check if comments in 'container' matches those in 'commentsList' and remove missmatches.
* @param {HTMLElement} container Reference to the element with comments.
*/
const unify = (container) => {
const {added, removed} = arrayCompare (
Array.from(commentsList.keys()),
Array.from(container.querySelectorAll('quote[type=comment]')).map(comment => comment.id)
);
// IDs missing in content -> remove from the 'commentsList'.
removed.forEach(id => {
const comment = commentsList.get(id);
comment.ref.parentNode.removeChild(comment.ref);
commentsList.delete(id);
});
// IDs missing in comments -> remove from the 'container'.
added.forEach(id => {
const ref = container.querySelector(`quote[id="${id}"]`);
ref.parentNode.removeChild(ref);
});
};
/**
* Restotres comments after merge operation.
* @param {HTMLElement} container Containert where comments shpuld be restored.
*/
const restore = (container) => (markersToComments(container, commentsModel), unify(container));
/**
* Create commnets model for the source DOM tree.
* @param {HTMLElement} container Reference to the element containing commnets tags (quote[type=comment]).
*/
const model = (container) => commentsModel = commentsToModel(container);
// Pubic API.
return {
// Reference to the UI element.
element,
// Set user's data.
user,
// Display only those commnets that match current content.
find,
// Set comments for current revision.
set,
// Add new commnet to current scope.
add,
// Get all commnets from current scope.
pull,
// Find and set 'active' class to the comment with given ID.
select,
// Restore commenst after merge.
restore,
// Create commnets model for current content.
model,
// Compare Content coments with 'commentsModel' and remove missmatches.
unify
};
}());
|
var Long = require('long');
var NBT = require('../dist/PowerNBT');
var assert = require('assert');
describe('NBT.NBTTagByte', function(){
describe('constructor', function(){
it('should be equal 0' , function(){
assert.equal(0, new NBT.NBTTagByte());
assert.equal(0, new NBT.NBTTagByte(undefined));
assert.equal(0, new NBT.NBTTagByte(null));
assert.equal(0, new NBT.NBTTagByte(0));
assert.equal(0, new NBT.NBTTagByte(""));
assert.equal(0, new NBT.NBTTagByte("0"));
});
it('should have name' , function(){
assert.equal("name", new NBT.NBTTagByte(0, "name").name);
assert.equal("", new NBT.NBTTagByte(0, "").name);
assert.equal("", new NBT.NBTTagByte(0).name);
});
it('should have value' , function(){
assert.equal(1, new NBT.NBTTagByte(1));
});
});
describe('#type', function(){
it('should be equal TAG_BYTE' , function(){
assert.equal(NBT.Type.TAG_BYTE, new NBT.NBTTagByte().type);
});
});
describe('#setValue', function(){
var tag = new NBT.NBTTagByte();
it('should change numeric value' , function(){
tag.setValue(20);
assert.equal(20, tag);
});
it('should change string value' , function(){
tag.setValue("-20");
assert.equal(-20, tag);
tag.setValue("0x3a");
assert.equal(58, tag);
});
it('should change tag value' , function(){
tag.setValue(new NBT.NBTTagByte(15));
assert.equal(15, tag);
});
it('should apply max value', function(){
tag.setValue(NBT.NBTTagByte.MAX_VALUE);
assert.equal(NBT.NBTTagByte.MAX_VALUE, tag);
});
it('should apply min value', function(){
tag.setValue(NBT.NBTTagByte.MIN_VALUE);
assert.equal(NBT.NBTTagByte.MIN_VALUE, tag);
});
it('should apply overflow', function(){
tag.setValue(NBT.NBTTagByte.MAX_VALUE+1);
assert.equal(NBT.NBTTagByte.MIN_VALUE, tag);
tag.setValue(NBT.NBTTagByte.MIN_VALUE-1);
assert.equal(NBT.NBTTagByte.MAX_VALUE, tag);
});
});
describe('#clone', function(){
var a = new NBT.NBTTagByte(123);
var b = a.clone();
it('should not return this', function(){
assert.notEqual(a, b);
});
it('should return it instance', function(){
assert.ok(b instanceof NBT.NBTTagByte);
});
it('clone should be equal to this as number', function(){
assert.equal(a.valueOf(), b.valueOf());
});
it('clone should be equal to this as string', function(){
assert.equal(a.toString(), b.toString());
});
});
});
|
var searchData=
[
['terms',['terms',['../structefp__opts.html#a4ec4f0243a7e31d41130adc5d9989599',1,'efp_opts']]],
['total',['total',['../structefp__energy.html#a0db3434685baa95c90385830abc16473',1,'efp_energy']]]
];
|
$(function(){
nav.init();
});
nav={
init:function(){
$('#header .search').click(function(){
$("#header").hide();
$('#search').show();
$('input:text').focus();
});
$('#search .x').click(function(){
$("#header").show();
$('#search').hide();
});
$('input:text').blur(function(){
$(this).val("");
});
$('[name="kw"]').keyup(function(){
$.get('../php/search.php',{kw:$('[name="kw"]').val()},function(data){
$('#link').html(data);
});
});
/*$('#link>ul>li').click(function(){
$('[name="kw"]').val($(this).html());
console.log($(this).html());
});*/
$("#link>ul").on("click","li", function() {
$('[name="kw"]').val($(this).html());
console.log($(this).html());
});
//原生js方法
/*$('[name="kw"]').keyup(function(){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status===200){
$('#link').html(xhr.responseText);
}else{
console.log("错误");
}
}
};
xhr.open('GET','../php/search.php?kw='+$('[name="kw"]').val(),true);
xhr.send();
});*/
$('#header .go>a').click(function(e){
e.preventDefault();
if(($('#header .go>b').css('display')=="none")&&($('#go_box').css('display')=="none")){
$('#header .go>b').css('display','block');
$('#go_box').css('display','block');
}else{
$('#header .go>b').css('display','none');
$('#go_box').css('display','none');
}
});
},
};
|
var scene4_btn_save // save sketch
var scene4_btn_fb // share
var scene4_btn_clear // clear the canvas
var scene4_btn_home // go back to scene4
// painting parameters
var scene4_draw_thick = 10
var scene4_draw_color = 0
var scene4_thick
var scene4_rSlider
var scene4_gSlider
var scene4_bSlider
/**
* Listening out
* Draw some words and share to social media
* @author: Limin Deng
*/
var Scene4 = function() {
}
Scene4.prototype.preload = function() {
scene4_btn_home = new MySprite(0, 0, "assets/home_normal.png", "assets/home_hover.png", "assets/home_clicked.png")
scene4_btn_home.preload();
scene4_btn_home.locate(windowWidth/20, windowHeight/30)
scene4_btn_save = new MySprite(0, 0, "assets/save_normal.png", "assets/save_hover.png", "assets/save_clicked.png")
scene4_btn_save.preload();
scene4_btn_save.locate(windowWidth/9, windowHeight/30)
scene4_btn_fb = new MySprite(0, 0, "assets/fb_normal.png", "assets/fb_hover.png", "assets/fb_clicked.png")
scene4_btn_fb.preload();
scene4_btn_fb.locate(windowWidth/6, windowHeight/30)
scene4_btn_clear = new MySprite(0, 0, "assets/canvas_clear_normal.png", "assets/canvas_clear_hover.png", "assets/canvas_clear_clicked.png")
scene4_btn_clear.preload();
scene4_btn_clear.locate(windowWidth/4.5, windowHeight/30)
}
Scene4.prototype.setup = function() {
}
/**
* show content
* event trigger would be put in sketch.js
*/
Scene4.prototype.draw = function() {
drawBg()
scene4_btn_save.draw()
scene4_btn_fb.draw()
scene4_btn_clear.draw()
scene4_btn_home.draw()
drawColorParams()
// drawAd()
drawPrompt()
}
Scene4.prototype.onMouseClicked = function() {
scene4_btn_save.onMouseClicked(function() {
})
// share to social network
scene4_btn_fb.onMouseClicked(function() {
})
scene4_btn_clear.onMouseClicked(function() {
clear()
})
scene4_btn_home.onMouseClicked(function() {
clear()
sceneNo = 3
scene4_thick.remove()
scene4_rSlider.remove()
scene4_gSlider.remove()
scene4_bSlider.remove()
})
}
Scene4.prototype.onMousePressed = function() {
scene4_btn_save.onMousePressed()
scene4_btn_fb.onMousePressed()
scene4_btn_clear.onMousePressed()
scene4_btn_home.onMousePressed()
}
Scene4.prototype.onMouseMoved = function() {
scene4_btn_save.onMouseMoved()
scene4_btn_fb.onMouseMoved()
scene4_btn_clear.onMouseMoved()
scene4_btn_home.onMouseMoved()
}
Scene4.prototype.onMouseDragged = function() {
push()
stroke(scene4_rSlider.value(), scene4_gSlider.value(), scene4_bSlider.value())
strokeWeight(scene4_thick.value())
line(mouseX, mouseY, pmouseX, pmouseY)
pop()
}
Scene4.prototype.onMouseReleased = function() {
}
Scene4.prototype.onKeyPressed = function() {
}
/**
* @author: Limin Deng
*/
function drawBg() {
push()
noFill()
stroke("orange")
strokeWeight(height/4)
line(0, 0, width, 0)
line(0, 0, 0, height)
line(width, 0, width, height)
strokeWeight(height/8)
line(0, height, width, height)
pop()
}
/**
* @author: Limin Deng
*/
function setupColorParams() {
scene4_thick = createSlider(2, 10, 2);
scene4_thick.position(width/2, height/20);
scene4_rSlider = createSlider(0, 255, 100);
scene4_rSlider.position(scene4_thick.x + scene4_thick.width + height/20, height/20);
scene4_gSlider = createSlider(0, 255, 0);
scene4_gSlider.position(scene4_rSlider.x + scene4_rSlider.width + height/20, height/20);
scene4_bSlider = createSlider(0, 255, 255);
scene4_bSlider.position(scene4_gSlider.x + scene4_gSlider.width + height/20, height/20);
}
/**
* Limin Deng
*/
function drawColorParams(){
push()
const r = scene4_rSlider.value();
const g = scene4_gSlider.value();
const b = scene4_bSlider.value();
textAlign(CENTER, CENTER)
text('thickness: '+ `${scene4_thick.value()}`, scene4_thick.x+scene4_thick.width/2, height/10);
text('red', scene4_rSlider.x+scene4_rSlider.width/2, height/10);
text('green', scene4_gSlider.x+scene4_gSlider.width/2, height/10);
text('blue', scene4_bSlider.x+scene4_bSlider.width/2, height/10);
pop()
push()
noStroke()
fill(r, g, b)
rect(scene4_bSlider.x + scene4_bSlider.width + height/20, height/30, height/20, height/20)
pop()
}
/**
* @author: Limin Deng
*/
function drawAd() {
push()
textAlign(CENTER, CENTER)
text("Tutehub: Online AI Education Platform\nhttp://www.boygirl88.com", width/10, height/1.03)
pop()
}
function drawPrompt() {
}
|
// STYLING CONSTANTS
export const TOP_BAR_HEIGHT = "55px";
export const TOP_BAR_COLOR = "#655991";
export const PRIMARY_BACKGROUND_COLOR = "#332D51";
export const SECONDARY_BACKGROUND_COLOR = "#453967";
export const ACCENT_COLOR_LIGHT_BLUE = "#3cfcef";
export const ACCENT_COLOR_DARK_PURPLE = "#6f70aa";
//primary text color is also used in index.css so be careful when changing it
export const PRIMARY_TEXT_COLOR = "#c0bdd0";
// SERVER CONSTANTS
export const LOGIN = "/api/login";
export const LOGOUT = "/api/logout";
export const GET_ME = "/api/me";
// LINK CONTSANTS
export const GOLD_COIN_IMAGE_URL = "https://i.imgur.com/zQGwFs4.png";
export const PREMIUM_COIN_IMAGE_URL = "https://i.imgur.com/jgJem0d.png";
|
import React, { Component } from 'react';
import {
AppRegistry,
ListView,
StyleSheet,
Text,
TouchableOpacity,
TouchableHighlight,
View,
StatusBar,
Image,
InteractionManager,
FlatList,
Dimensions,
} from 'react-native';
import { SwipeListView, SwipeRow } from 'react-native-swipe-list-view';
import LoadView from '../view/loading';
import NetUitl from '../utils/netUitl';
var { height, width } = Dimensions.get('window');
import StringBufferUtils from '../utils/StringBufferUtil';
var BASEURL = 'http://121.42.238.246:8080/unitrip_bookstore/bookstore/app_recommend';
import Global from '../utils/global';
import StringUtil from '../utils/StringUtil';
// var RETURN_ICON = require('./images/tabs/icon_return.png');
import DeviceStorage from '../utils/deviceStorage';
import { CachedImage } from "react-native-img-cache";
import { toastShort } from '../utils/ToastUtil';
import RNFS from 'react-native-fs';
var navigate = null;
export default class RecommendAppActivity extends Component {
constructor(props) {
super(props);
this.state = {
show: false,
appList: []
};
}
componentDidMount() {
var that = this;
navigate = this.props.navigation;
this.getData();
}
componentWillUnmount() {
}
getData() {
this.setState({
show: true
});
StringBufferUtils.init();
StringBufferUtils.append('page=' + '0');
StringBufferUtils.append('&&count=' + 100);
StringBufferUtils.append('&&type=' + 'android');
let params = StringBufferUtils.toString();
this.fetchData(params);
}
// 数据请求
fetchData(params) {
var that = this;
console.log(BASEURL + params);
NetUitl.post(BASEURL, params, '', function (responseData) {
//下面的就是请求来的数据
if (null != responseData && responseData.return_code == '0') {
that.addItemKey(responseData.apps);
that.setState({
show: false
})
} else {
that.setState({
show: false
});
}
})
}
//整合数据
addItemKey(rulelist) {
var that = this;
if (null != rulelist && rulelist.length > 0) {
//整合法规数据
for (var i = 0; i < rulelist.length; i++) {
rulelist[i].key = i;
}
that.setState({
appList: rulelist,
show: false
});
} else {
that.setState({
show: false,
});
}
}
_backOnclick() {
this.props.navigator.pop(
{
}
);
}
//点击列表点击每一行
clickItem(item) {
var that = this;
// DeviceStorage.get(item.book_id + '.pdf', function (jsonValue) {
// if (jsonValue != null) {
// var isDownLoad = jsonValue.isDownLoad;
// if (!isDownLoad) {
// that._downLoadMethord(item);
// } else {
// navigate('PdfReadView', {
// book_id: item.book_id
// });
// }
// } else {
// that._downLoadMethord(item);
// }
// });
}
_downLoadMethord(item) {
var that = this;
that.setState({
show: true,
});
var DownloadFileOptions = {
fromUrl: item.freeread_url, // URL to download file from
toFile: RNFS.DocumentDirectoryPath + '/' + item.book_id + '.pdf', // Local filesystem path to save the file to
begin: function (val) {
toastShort('下载开始');
},
progress: function (val) {
tempLength = parseInt(val.bytesWritten);
totalSize = parseInt(val.contentLength);
percents = (tempLength / totalSize).toFixed(2);
if ((percents * 100) > 99) {
that.setState({
show: false
});
var obj = new Object();
obj.isDownLoad = true;
toastShort('下载完成');
navigate('PdfReadView', {
book_id: item.book_id
});
DeviceStorage.save(item.book_id + '.pdf', obj);
}
},
}
var result = RNFS.downloadFile(DownloadFileOptions);
}
_separator = () => {
return <View style={{ height: 1, backgroundColor: '#e2e2e2' }} />;
}
onClickListener(flag, item) {
switch (flag) {
case '0'://下载
alert('下载文件');
break;
}
}
// 返回国内法规Item
_renderSearchItem = (itemData, index) => {
return (
<View style={{ height: 102, justifyContent: 'center', backgroundColor: 'white' }}>
<TouchableOpacity onPress={() => this.clickItem(itemData, index)} activeOpacity={0.8}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', width: width, alignItems: 'center' }}>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<CachedImage style={{ height: 80, width: 60, marginLeft: 10 }} source={{ uri: itemData.item.app_icon }} />
<View style={{ height: 100, flexDirection: 'column', justifyContent: 'center', marginLeft: 10 }}>
<Text style={styles.news_item_title} numberOfLines={1}>{itemData.item.app_name}</Text>
<Text style={styles.rule_item_time}>{itemData.item.app_content}</Text>
</View>
</View>
<View style={{ width: 80, height: 45, alignItems: 'center', flexDirection: 'row', justifyContent: 'center' }}>
<TouchableOpacity activeOpacity={0.8} onPress={() => this.onClickListener('0', itemData)}>
<View style={{ width: 24, height: 24, alignItems: 'center' }}>
< Image source={require('../img/btn_download.png')} style={{ height: 17, width: 16 }} />
</View>
</TouchableOpacity>
</View>
</View>
<View style={{ height: 1, backgroundColor: '#e2e2e2', width: width }} />
</TouchableOpacity>
</View>
);
}
//此函数用于为给定的item生成一个不重复的key
_keyExtractor = (item, index) => item.key;
render() {
let self = this;
return (
<View style={styles.container}>
{this.state.show == true ? (<LoadView />) : (null)}
<View style={styles.main_bg}>
<FlatList
ref={(flatList) => this._flatList = flatList}
renderItem={this._renderSearchItem}
keyExtractor={this._keyExtractor}
data={this.state.appList}
extraData={this.state}
>
</FlatList>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: 'white',
flex: 1
},
standalone: {
marginTop: 30,
marginBottom: 30,
},
standaloneRowFront: {
alignItems: 'center',
backgroundColor: '#CCC',
justifyContent: 'center',
height: 50,
},
standaloneRowBack: {
alignItems: 'center',
backgroundColor: '#8BC645',
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
padding: 15
},
backTextWhite: {
color: '#FFF',
textAlign: 'center'
},
rowFront: {
alignItems: 'center',
backgroundColor: '#CCC',
borderBottomColor: 'black',
borderBottomWidth: 1,
justifyContent: 'center',
height: 50,
},
rowBack: {
alignItems: 'center',
backgroundColor: '#DDD',
flexDirection: 'row',
justifyContent: 'space-between',
height: 100,
},
backRightBtn: {
alignItems: 'center',
bottom: 0,
justifyContent: 'center',
position: 'absolute',
top: 0,
width: 80,
},
backRightBtnLeft: {
backgroundColor: 'blue',
right: 60,
},
backRightBtnRight: {
backgroundColor: 'red',
right: 0,
height: 100,
marginTop: 1,
},
controls: {
alignItems: 'center',
marginBottom: 30
},
switchContainer: {
flexDirection: 'row',
justifyContent: 'center',
marginBottom: 5
},
switch: {
alignItems: 'center',
borderWidth: 1,
borderColor: 'black',
paddingVertical: 10,
width: 100,
},
top_name: {
textAlign: 'center',
textAlignVertical: 'center',
color: '#000000',
fontSize: 14,
}, top_select_name: {
textAlign: 'center',
textAlignVertical: 'center',
color: '#ff9602',
fontSize: 14,
}, main_bg: {
backgroundColor: 'white',
margin: 10,
}
});
|
/**
* 创建目录
*/
var fs = require('fs');
console.log('在C:/Course目录下创建testDemo4-8');
fs.mkdir('C:/Course/testDemo4-8/', function (err) {
if (err) {
return console.error(err);
}
console.log("目录创建成功。")
});
|
/* eslint-disable prefer-destructuring */
/* eslint-disable global-require */
/* eslint-disable react/forbid-prop-types */
/* eslint-disable react/prop-types */
// @flow
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
const styles = theme => ({
root: {
padding: theme.spacing.unit * 4
},
innerRoot: {
// ...theme.mixins.gutters(),
padding: theme.spacing.unit * 4,
width: 500
},
commentTypo: {
borderBottom: '3px solid rgba(26, 43, 117, 1)',
paddingTop: 10,
paddingBottom: 5,
marginRight: 10,
marginBottom: 15
},
menu: {
width: 150
},
fab: {
margin: theme.spacing.unit
},
extendedIcon: {
marginRight: theme.spacing.unit
}
});
let authInfo;
class SignIn extends Component {
constructor(props) {
super(props);
this.state = {};
}
static getDerivedStateFromProps(nextProps, prevState) {
authInfo = nextProps.authInfo;
return null;
}
componentDidMount() {
authInfo.findOne(
{
fileName: 'signIn'
},
async (err, docs) => {
this.setState({
productKey: docs.productKey
});
}
);
}
render() {
const { classes } = this.props;
const { productKey } = this.state;
return (
<div className={classes.root}>
<div style={{ display: 'flex' }}>
<img
src={require('../../assets/images/logo.png')}
alt="logo"
width="50%"
height="80%"
/>
<div>
<Typography noWrap variant="h5">
TEAM DATA
</Typography>
<Typography noWrap variant="h6" color="textSecondary">
VER .01
</Typography>
</div>
</div>
<br />
<br />
<br />
<Typography noWrap variant="subtitle2" style={{ fontSize: 18 }}>
Developed by:
<span style={{ color: 'red' }}>
{' '}
http://www.teamdatasports-innovation.com/
</span>
</Typography>
<br />
<br />
<Typography variant="subtitle1" style={{ fontSize: 18 }}>
Product Key:
</Typography>
<Typography
variant="subtitle1"
style={{
fontSize: 18,
border: '1px solid red',
borderRadius: 50,
paddingLeft: 10
}}
>
{productKey}
</Typography>
<br />
<br />
<Typography variant="subtitle1" align="center">
Copyright © 2018 Merhaba Japan Co. Ltd. All Rights Reserved.
</Typography>
</div>
);
}
}
SignIn.propTypes = {
classes: PropTypes.object.isRequired
};
const mapStateToProps = state => ({ authInfo: state.authReducer.authInfo });
// const mapDispatchToProps = dispatch => ({
// getPlayers: (playerInfo) => dispatch(getPlayers(playerInfo))
// });
/** Updated For V2 */
export default connect(
mapStateToProps,
null
)(withStyles(styles)(SignIn));
|
/******************************************************************************
* Compilation: node StockAccount.js
*
* Purpose: Program to keep track of different Companies, their price per
* share & User Account to keep track of shares bought or sold.
* Implementation of Linked List, Stack & Queue is also used.
*
* @author Nishant Kumar
* @version 1.0
* @since 01-11-2018
*
******************************************************************************/
// Implementing the File System module in this application.
var fs = require("fs");
// Implementing the Readline Module in this application.
var rl = require('readline');
// Creating an Interface object of Readline Module by passing 'stdin' & 'stdout' as parameters.
var r = rl.createInterface(process.stdin, process.stdout);
// Implementing the LinkedList module in this application.
var ll = require('../DataStructurePrograms/LinkedList');
// Implementing the Stack module in this application.
var st = require('../DataStructurePrograms/Stack');
// Implementing the Queue module in this application.
var q = require('../DataStructurePrograms/Queue');
class CompanyShares {
/**
* Constructor to create an Object of CompanyShares.
*
* @param {String} name It is the name of the Company.
* @param {String} symbol It is the symbol used to recognize the Company.
* @param {Number} price It is the price per share of the Company.
*/
constructor(name, symbol, price) {
this.name = name;
this.symbol = symbol;
this.price = price;
}
}
class StockAccount {
/**
* Constructor to create an object of StockAccount.
*
* @param {String} name It is the name of the person whose new account will be opened,
*/
constructor(name) {
this.name = name;
}
/**
* Function to find the total value of each shares purchased by a user.
*/
valueOf() {
// Calling readFromJson() function to read user data.
var re = readFromJson('u');
var sum = 0;
// Loop for Searching the user by name in the file.
for (var i = 0; i < re.user.length; i++) {
if (re.user[i].name == this.name) {
// If name is found, adding it's amount into sum everytime.
sum += re.user[i].amount;
}
}
// Printing the value of account.
console.log("Total value of the account is: $" + sum);
return;
}
/**
* Function to buy shares from a company.
*
* @param {Number} amount It is the amount of which shares will be bought.
* @param {String} symbol It is the symbol of the company whose shares is to be bought.
*/
buy(amount, symbol) {
// Calling readFromJson() function to read Company data.
var com = readFromJson('c');
var i = 0;
// Storing the head node in temp variable.
var temp = com.head;
// For loop to find the symbol in the company file.
for (i = 0; i < com.size; i++) {
// When the symbol is found, break the loop, so temp points to that company.
if (temp.data.symbol == symbol) {
break;
}
temp = temp.next;
}
// Validating if temp's symbol is the symbol passed by the caller.
if (temp.data.symbol == symbol) {
// Calculating total shares bought according to the amount.
var sharesBought = amount / temp.data.price;
// Creating a user object having different properties.
var user = {
name: this.name,
amount: amount,
symbol: symbol,
bought: sharesBought,
time: new Date().toLocaleString()
}
// Writing user object into the user details file.
writeInJson(user, 'u');
// Writing symbol of the company into symbol transaction file.
writeInJson(user.symbol, 's');
// Writing Date & Time of the transaction into time transaction file.
writeInJson(user.time, 't');
} else {
// If not, then the symbol is incorrect. So promting the user again.
console.log("Invalid Input! Symbol not matched! Try Again.");
purposeUser(this.name);
}
}
/**
* Function to sell shares of a user.
*
* @param {Number} amount It is the amount of which shares will be bought.
* @param {String} symbol It is the symbol of the company whose shares has to be sold.
*/
sell(amount, symbol) {
// Calling readFromJson() function to read User data.
var j = readFromJson('u');
var i = 0;
// For loop to check the symbol & name matching arguments passed.
for (i = 0; i < j.user.length; i++) {
if (j.user[i].name == this.name && j.user[i].symbol == symbol) {
// If yes, then break the loop, so temp points to that account.
break;
}
}
// Validating if no such symbol realted to that name found.
if (i == j.user.length) {
console.log("\nINVALID! No such entry found! Please enter again!\n");
purposeUser(this.name);
} else {
// Validating if user has input an amount which is greater than he have bought.
if (amount > j.user[i].amount) {
// If yes, then it's not possible to sell those many shares.
console.log("Invalid! Enter amount is greater than you've bought!");
purposeUser(this.name);
} else {
//If no, then storing price per share value in share.
var share = j.user[i].amount / j.user[i].bought;
// Decrementing user amount by the amount passed in argument.
j.user[i].amount -= amount;
// Updating the shares bought & Time of the transaction.
j.user[i].bought = j.user[i].amount / share;
j.user[i].time = new Date().toLocaleString();
// Writing symbol of the company into symbol transaction file.
writeInJson(symbol, 's');
// Writing Date & Time of the transaction into time transaction file.
writeInJson(j.user[i].time, 't');
// Writing the file with updated data in UserShares file.
fs.writeFileSync('./JsonFiles/UserShares.json', JSON.stringify(j));
console.log("JSON File Saved!");
}
}
}
/**
* Function to print all the details in a report related to the name.
*/
printReport() {
// Calling readFromJson() function to read User data.
var re = readFromJson('u');
var count = 0;
// For loop to search for the name passed in the object.
for (var i = 0; i < re.user.length; i++) {
if (re.user[i].name == this.name) {
// If found, printing the details.
console.log(re.user[i]);
count++;
}
}
// If count is still zero, i.e. no transactions are found for that specific user.
if (count == 0) {
console.log("No transaction realted to \'" + this.name + "\' exists!");
process.exit();
}
// Also printing the total value of the account.
this.valueOf();
process.exit();
}
}
/**
* Function to display company details for each company.
*/
function displayCompanies() {
// Calling readFromJson() function to read Company data.
var com = readFromJson('c');
// Pointing temp to the head of the linked list.
var temp = com.head;
// For loop to print data of each node.
for (var i = 0; i < com.size; i++) {
console.log(temp.data);
temp = temp.next;
}
}
/**
* Function to read from the JSON file and return it to the caller in a specific
* format based on the string passed.
*
* @param {String} s It is the indication by the caller to which file to extract data from.
*
* @returns {any} It is the list/stack/queue/string which is returned back to the caller.s
*/
function readFromJson(s) {
var data;
// Checking if the passed string is either 'c' or 's' or 't'.
if (s == 'c' || s == 's' || s == 't') {
// If it's 'c', i.e. extract Company details.
if (s == 'c') {
// Reading the data from CompanyShares.json
data = fs.readFileSync('./JsonFiles/CompanyShares.json');
// Converting it into string.
var j = JSON.parse(data);
// Creating a new object of Linked List.
var l = new ll.LinkedList();
var temp = j.head;
// For loop to store all the data of the file into the LinkedList 'l'.
for (var i = 0; i < j.size; i++) {
l.addAppend(temp.data);
temp = temp.next;
}
// Returning the linked list.
return l;
}
// If it's 's', i.e. extract Symbol transaction details.
else if (s == 's') {
// Reading the data from SymbolTransaction.json
data = fs.readFileSync('./JsonFiles/SymbolTransaction.json');
// Converting it into string.
var j = JSON.parse(data);
// Creating a new object of Stack.
var ss = new st.Stack();
var temp = j.head;
// For loop to store all the data of the file into the Stack 'ss'.
for (var i = 0; i < j.size; i++) {
ss.push(temp.data);
temp = temp.next;
}
// Returning the Stack.
return ss;
}
// If it's 't', i.e. extract Date & Time transaction details.
else {
// Reading the data from DateTimeOfTransaction.json
data = fs.readFileSync('./JsonFiles/DateTimeOfTransaction.json');
// Converting it into string.
var j = JSON.parse(data);
// Creating a new object of Queue.
var qq = new q.Queue();
var temp = j.head;
// For loop to store all the data of the file into the Queue 'qq'.
for (var i = 0; i < j.size; i++) {
qq.enqueue(temp.data);
temp = temp.next;
}
// Returning the Queue.
return qq;
}
}
// If it's 'u', i.e. extract User Details.
else if (s == 'u') {
// Reading the data from UserShares.json
var data = fs.readFileSync('./JsonFiles/UserShares.json');
// Converting it into string.
var j = JSON.parse(data);
// Returning the string.
return j;
}
}
/**
* This function helps to convert any object or data passed into
* JSON format and write that JSON string to a file.
*
* @param {any} str It is the data passed by the caller.
*/
function writeInJson(str, s) {
// Checking if the passed string is either 'c' or 's' or 't'.
if (s == "c" || s == 's' || s == 't') {
// Reading the file from JSON passing 's' String.
var jsonArr = readFromJson(s);
// If String is 'c', add the data & write it in the file.
if (s == 'c') {
jsonArr.addAppend(str);
fs.writeFileSync('./JsonFiles/CompanyShares.json', JSON.stringify(jsonArr));
}
// If String is 's', add the data & write it in the file.
else if (s == 's') {
jsonArr.push(str);
fs.writeFileSync('./JsonFiles/SymbolTransaction .json', JSON.stringify(jsonArr));
}
// If String is 't', add the data & write it in the file.
else {
jsonArr.enqueue(str);
fs.writeFileSync('./JsonFiles/DateTimeOfTransaction.json', JSON.stringify(jsonArr));
}
console.log("JSON File Saved!");
r.close();
}
// If String is 't', add the data & write it in the file.
else {
// Reading the file from JSON passing 's' String.
jsonArr = readFromJson(s);
// Adding 'str' into the array.
jsonArr.user.push(str);
// Writing the 'str' in the UserShares file.
fs.writeFileSync('./JsonFiles/UserShares.json', JSON.stringify(jsonArr));
console.log("JSON File Saved!");
r.close();
}
}
/**
* Function to start the program & register User/Company.
*/
function registration() {
// Asking the user if he's a Company/Customer.
r.question("Enter 1 if you're a Company, 2 if you're a Customer: ", function(ans) {
if (!isNaN(ans.trim())) {
// If user entered 1, then it's a company
if (ans.trim() == 1) {
// Asking if he's new or existing.
r.question("Enter 1 if you're new, or 2 if you're existing: ", function(ans1) {
// If 1, then register the company.
if (ans1.trim() == 1) {
registerCompany();
}
// Else existing, so ask for his purpose.
else {
purposeCompany();
}
});
}
// If user entered 2, then it's a Customer, so register him.
else if (ans.trim() == 2) {
registerUser();
}
// Else Invalid input.
else {
console.log('Invalid Input!! Please enter 1 or 2!');
registration();
}
}
// Else Invalid input.
else {
console.log('Invalid Input!! Please enter a number!');
registration();
}
})
}
/**
* Function to check if the company exists in the database or not.
*
* @param {String} name It is the company name to be searched.
*
* @returns {Boolean} It returns true/false based on company found or not.
*/
function companyExists(name) {
// Taking Company data
var com = readFromJson('c');
var temp = com.head;
// For loop to run till the end of the Company list to find the company.
for (var i = 0; i < com.size; i++) {
// If the name is found, then return true.
if (temp.data.name == name) {
return true;
}
temp = temp.next;
}
// If not found, then return false.
return false;
}
/**
* Function to check the purpose of the company.
*/
function purposeCompany() {
// Asking company to enter it's name.
r.question("Enter your Company name: ", function(ans1) {
// If company does't exist, go for registration again!
if (!companyExists(ans1.trim())) {
console.log("INVALID! No such Company exists in our database! Try to register.");
registration();
}
// If the company exists, Ask for his purpose.
else {
// Asking the user to enter his purpose.
r.question("Hello " + ans1.trim() + "! What would you like to do today?\n" +
"1.Change Symbol\n2.Change Price Per share\n",
function(ans2) {
if (!isNaN(ans2.trim())) {
// Storing the answer in p
var p = Number(ans2.trim());
// Reading Company file.
var com = readFromJson('c');
var temp = com.head;
var i = 0;
// For loop to run till it finds the company
for (i = 0; i < com.size; i++) {
// When company name is found, break the loop.
if (temp.data.name == ans1.trim()) {
break;
}
temp = temp.next;
}
// If input is 1, Change Symbol
if (p == 1) {
// Printing it's previous symbol & asking to enter new one.
console.log("Your previous symbol was: " + temp.data.symbol);
r.question("What would you like to change it to? ",
function(ans3) {
// Overwriting the symbol with new one.
temp.data.symbol = ans3.trim();
// Writing the data in file.
fs.writeFileSync('./JsonFiles/CompanyShares.json', JSON.stringify(com));
console.log("Succesfully Changed!");
process.exit();
});
}
// If input is 2, Change price per share.
else {
// Printing it's previous price & asking to enter new one.
console.log("Your previous price per share was: " +
temp.data.price);
r.question("What would you like to change it to? ",
function(ans3) {
if (!isNaN(ans3.trim())) {
// Overwriting the price with new one.
temp.data.price = ans3.trim();
// Write the data in file.
fs.writeFileSync('./JsonFiles/CompanyShares.json', JSON.stringify(com));
console.log("Succesfully Changed!");
process.exit();
} else {
console.log("INVALID! Price should be a number!");
purposeCompany();
}
});
}
} else {
console.log("Invalid Input! Please enter again!");
purposeCompany();
}
});
}
});
}
/**
* Function to check the purpose of the user.
*
* @param {String} name It is the name of the customer.
*/
function purposeUser(name) {
// Asking the user about it's purpose.
r.question("Hello " + name + "! What do you want to do today?" +
"\n1.Buy shares\n2.Sell Shares\n3.Get account details\n",
function(ans) {
// Checking if it's a number or not.
if (!isNaN(ans)) {
// Creating a new object of StockAccount passing the name.
var stock = new StockAccount(name);
// If user entered 1, Buy shares.
if (Number(ans) == 1) {
// Asking user to enter the symbol of company.
r.question("Enter symbol of the company whose shares you\'d" +
" like to buy:\n" + displayCompanies() + "\n",
function(ans1) {
// Asking user to enter amount of shares to be bought.
r.question("Enter the amount: ", function(ans4) {
if (!isNaN(ans4)) {
var sym = ans1.trim();
var amt = Number(ans4.trim());
// Calling buy() function to buy 'amt' shares of 'sym'.
stock.buy(amt, sym);
} else {
console.log("Invalid Input! Please enter again!");
purposeUser();
}
});
});
}
// If user entered 2, Sell shares.
else if (Number(ans) == 2) {
// Asking the user to enter the company symbol who he'll sell.
r.question("Enter symbol of the company whose shares you\'d" +
" like to sell:\n" + displayCompanies() + "\n",
function a(ans1) {
// Asking the user amount to sell.
r.question("Enter the amount to sell: ", function(ans4) {
if (!isNaN(ans4)) {
var sym = ans1.trim();
var amt = Number(ans4.trim());
// Calling Sell() method to sell 'amt' shares of 'sym'.
stock.sell(amt, sym);
} else {
console.log("Invalid Input! Please enter again!");
purposeUser();
}
});
});
}
// If user entered 3, Print the report.
else if (Number(ans) == 3) {
// Calling printReport() function to print report of 'name' person's account.
stock.printReport();
} else {
console.log("INVALID INPUT! Please enter again! ");
purposeUser(name);
}
} else {
console.log("INVALID INPUT! Please enter again! ");
purposeUser(name);
}
});
}
/**
* Function to register a new company.
*/
function registerCompany() {
// Asking the company's full name, a symbol, and price per share.
r.question("Enter your company's full Name: ", function(ans1) {
r.question("Enter a symbol/nickname for the company: ", function(ans2) {
r.question("Enter what's your price per share: ", function(ans3) {
if (!isNaN(ans3)) {
// Storing inputs in name, symbol & price variables.
var name = ans1.trim();
var symbol = ans2.trim();
var price = Number(ans3.trim());
// Creating an object of CompanyShares to store name, symbol & price.
var t = new CompanyShares(name, symbol, price);
// Passing that object in writeFileSync() function to store it into file.
writeInJson(t, "c");
} else {
console.log("Invalid Input!");
registerCompany();
}
});
});
});
}
/**
* Function to register a user.
*/
function registerUser() {
// Asking the user it's full name.
r.question("Enter your full Name: ", function(ans1) {
var name = ans1.trim();
// Calling purposeUser() function to find the user's purpose.
purposeUser(name);
});
}
// Calling registration() function to start the program.
registration();
|
const should = require('should');
const rewire = require('rewire');
const nock = require('nock');
const request = rewire('../../../core/server/lib/request');
describe('Request', function () {
it('[success] should return response for http request', function () {
const url = 'http://some-website.com/endpoint/';
const expectedResponse = {
body: 'Response body',
url: 'http://some-website.com/endpoint/',
statusCode: 200
};
const options = {
headers: {
'User-Agent': 'Mozilla/5.0'
}
};
const requestMock = nock('http://some-website.com')
.get('/endpoint/')
.reply(200, 'Response body');
return request(url, options).then(function (res) {
requestMock.isDone().should.be.true();
should.exist(res);
should.exist(res.body);
res.body.should.be.equal(expectedResponse.body);
should.exist(res.url);
res.statusCode.should.be.equal(expectedResponse.statusCode);
should.exist(res.statusCode);
res.url.should.be.equal(expectedResponse.url);
});
});
it('[success] can handle redirect', function () {
const url = 'http://some-website.com/endpoint/';
const expectedResponse = {
body: 'Redirected response',
url: 'http://someredirectedurl.com/files/',
statusCode: 200
};
const options = {
headers: {
'User-Agent': 'Mozilla/5.0'
}
};
const requestMock = nock('http://some-website.com')
.get('/endpoint/')
.reply(301, 'Oops, got redirected',
{
location: 'http://someredirectedurl.com/files/'
});
const secondRequestMock = nock('http://someredirectedurl.com')
.get('/files/')
.reply(200, 'Redirected response');
return request(url, options).then(function (res) {
requestMock.isDone().should.be.true();
secondRequestMock.isDone().should.be.true();
should.exist(res);
should.exist(res.body);
res.body.should.be.equal(expectedResponse.body);
should.exist(res.url);
res.statusCode.should.be.equal(expectedResponse.statusCode);
should.exist(res.statusCode);
res.url.should.be.equal(expectedResponse.url);
});
});
it('[failure] can handle invalid url', function () {
const url = 'test';
const options = {
headers: {
'User-Agent': 'Mozilla/5.0'
}
};
return request(url, options).then(() => {
throw new Error('Request should have rejected with invalid url message');
}, (err) => {
should.exist(err);
err.message.should.be.equal('URL empty or invalid.');
});
});
it('[failure] can handle empty url', function () {
const url = '';
const options = {
headers: {
'User-Agent': 'Mozilla/5.0'
}
};
return request(url, options).then(() => {
throw new Error('Request should have rejected with invalid url message');
}, (err) => {
should.exist(err);
err.message.should.be.equal('URL empty or invalid.');
});
});
it('[failure] can handle an error with statuscode not 200', function () {
const url = 'http://nofilehere.com/files/test.txt';
const options = {
headers: {
'User-Agent': 'Mozilla/5.0'
}
};
const requestMock = nock('http://nofilehere.com')
.get('/files/test.txt')
.reply(404);
return request(url, options).then(() => {
throw new Error('Request should have errored');
}, (err) => {
requestMock.isDone().should.be.true();
should.exist(err);
err.statusMessage.should.be.equal('Not Found');
});
});
it('[failure] returns error if request errors', function () {
const url = 'http://nofilehere.com/files/test.txt';
const options = {
headers: {
'User-Agent': 'Mozilla/5.0'
}
};
const requestMock = nock('http://nofilehere.com')
.get('/files/test.txt')
.times(3) // 1 original request + 2 default retries
.reply(500, {message: 'something awful happened', code: 'AWFUL_ERROR'});
return request(url, options).then(() => {
throw new Error('Request should have errored with an awful error');
}, (err) => {
requestMock.isDone().should.be.true();
should.exist(err);
err.statusMessage.should.be.equal('Internal Server Error');
err.body.should.match(/something awful happened/);
err.body.should.match(/AWFUL_ERROR/);
});
});
});
|
google.charts.load('current', {packages: ['corechart', 'bar']});
// Draw Graph
function drawBarGraph(queryId, title, subtitle, columns, data) {
let graphDockingLocation = queryId;
let footerId = `${queryId}-footer`;
let footerTextId = `${queryId}-footer-text`;
data.forEach(record => {
for (let i = 0; i < record.length; i++) {
if (i > 0)
record[i] = parseFloat(record[i]);
}
});
console.log(data);
// Add Columns as the first element.
data.splice(0, 0, columns);
let dataforGraph = google.visualization.arrayToDataTable(data);
// Options
let options = {
chart: {
title: title,
subtitle: subtitle,
},
bars: 'vertical',
vAxis: {format: 'decimal'},
height: 400,
colors: ['#1b9e77', '#d95f02', '#7570b3']
};
let chart = new google.charts.Bar(document.getElementById(graphDockingLocation));
chart.draw(dataforGraph, google.charts.Bar.convertOptions(options));
}
// Pie chart
function drawPieChart(queryId, title, subtitle, columns, data) {
console.log('Drawing Pie chart');
data.forEach(record => record[1] = parseInt(record[1]));
console.log(data);
let graphDockingLocation = queryId;
let footerId = `${queryId}-footer`;
let footerTextId = `${queryId}-footer-text`;
let options = {
title: title,
pieHole: 0.4,
// is3D: true,
pieSliceText: 'value',
height: 400,
chartArea: {left: 20, top: 20, width: '100%', height: '100%'}
};
data.splice(0, 0, columns);
var dataforGraph = google.visualization.arrayToDataTable(data);
var chart = new google.visualization.PieChart(document.getElementById(graphDockingLocation));
chart.draw(dataforGraph, options);
}
|
/* global QUnit */
/**
* Before doing the test, import test-important-vs-urlblock.txt to AdGuard
*/
window.addEventListener('DOMContentLoaded', () => {
const adgCheck = getComputedStyle(window.document.getElementById('subscribe-to-test-important-vs-urlblock-filter'), null).display === 'none';
QUnit.test('Case 3: $important rule vs $urlblock exception', (assert) => {
const imageDisplayed = getComputedStyle(document.querySelector('#case3 > img'), null).display !== 'none';
assert.ok(adgCheck && imageDisplayed, '$urlblock exception should disable $important rule.');
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.