text stringlengths 7 3.69M |
|---|
var mWidth1 = 5,
mHeight1 = 4,
mWidth2 = 4,
mHeight2 = 5;
var flag = false,
endFlag = false;
let table1 = document.getElementById('table1'),
table2 = document.getElementById('table2'),
endTable = document.getElementById('endTable');
initTable(table1, mWidth1, mHeight1,1);
initTable(table2, mWidth2, mHeight2,2);
initTable(endTable,mWidth2 , mHeight1,3);
let textInputMatrix1 = document.getElementById('textInputMatrix1'),
textInputMatrix2 = document.getElementById('textInputMatrix2');
textInputMatrix1.addEventListener('input', function () {
table1 = document.getElementById('table1');
removeAllElementsFromTable(table1);
removeAllElementsFromTable(endTable);
mHeight1 = textInputMatrix1.value.split('x')[0];
mWidth1 = textInputMatrix1.value.split('x')[1];
// flag = false;
initTable(table1, +mWidth1, +mHeight1,1);
initTable(endTable,mWidth2 , mHeight1,3);
});
textInputMatrix2.addEventListener('input', function () {
table2 = document.getElementById('table2');
removeAllElementsFromTable(table2);
removeAllElementsFromTable(endTable);
mHeight2 = textInputMatrix2.value.split('x')[0];
mWidth2 = textInputMatrix2.value.split('x')[1];
// flag = true;
initTable(table2, +mWidth2, +mHeight2,2);
initTable(endTable,mWidth2 , mHeight1,3);
});
function removeAllElementsFromTable(table)
{
while (table.firstChild)
table.removeChild(table.firstChild);
}
function initTable(table, mWidth, mHeight,numberOfMatrix) {
let tr, th;
for (let i = 0; i < mHeight; i++) {
tr = document.createElement('tr');
th = document.createElement('th');
th.className = 'th';
table.appendChild(tr);
tr.appendChild(th);
}
th = document.body.querySelectorAll('.th');
let maxHeight;
if (numberOfMatrix==1) {
i = 0;
maxHeight = mHeight;
} else if (numberOfMatrix==2) {
i = mHeight1;
maxHeight = +(+(mHeight) + (+(mHeight1)));
}
else if(numberOfMatrix==3) {
i=(+mHeight1)+(+(mHeight2));
maxHeight=th.length;
}
for (i; i < maxHeight; i++) {
for (let j = 0; j < mWidth; j++) {
let newElement = document.createElement('input');
newElement.className = "textInput";
newElement.type = 'text';
newElement.id = 'textArea' + i + '' + (j);
newElement.textContent = j;
// console.log(th[i]);
th[i].appendChild(newElement);
//console.log(i + 4);
}
}
}
let mainButton = document.body.getElementsByClassName('mainButton');
mainButton[0].addEventListener('click', function () {
multiply();
});
function multiply() {
if (mWidth1 == mHeight2) {
while(endTable.firstChild)
endTable.removeChild(endTable.firstChild);
let matrix1 = new Array(0),
matrix2 = new Array(0);
let textInputs = document.body.getElementsByClassName('textInput');
for (let i = 0; i < mHeight1; i++) {
let arr = new Array(0);
for (let j = 0; j < mWidth1; j++) {
arr.push(textInputs[mWidth1 * i + j]);
}
matrix1[i] = arr;
}
for (i = 0; i < mHeight2; i++) {
let arr = new Array(0);
let num = 0;
for (let j = 0; j < mWidth2; j++) {
arr.push(textInputs[mWidth1 * mHeight1 + (mWidth2 * i + j)]);
}
matrix2[i] = arr;
}
let endMatrix = new Array(0);
for (i = 0; i < mHeight1; i++) {
let line = new Array(0);
for (j = 0; j < mWidth2; j++) {
let num = 0;
for (let n = 0; n < mWidth1; n++) {
num += (matrix1[i][n].value) * (matrix2[n][j].value);
}
line.push(num);
}
endMatrix.push(line);
}
// flag=false;
initTable(endTable,mWidth2,mHeight1,3);
insertNumbersIntoTable(endTable,endMatrix);
//alert('Result:\n' + printMatrix(endMatrix));
}
}
function insertNumbersIntoTable(table,matrix)
{
let eTable=document.querySelectorAll('.endTable');
let th= eTable[0].getElementsByClassName('th');
let textInputs=new Array(0);
for(let i=0;i<matrix.length;i++)
textInputs.push(th[i].querySelectorAll('.textInput'));
for(let i=0;i<matrix.length;i++)
{
for(let j=0;j<matrix[0].length;j++)
{
textInputs[i][j].value=matrix[i][j];
}
}
console.log(textInputs);
}
function printMatrix(matrix) {
let text = "";
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[0].length; j++) {
text += "[" + matrix[i][j] + "]";
}
text += "\n";
}
return text;
} |
/**
* 数据列表
* @param {} requestUrl
* @param {} tcolumn
* @param {} tbar
* @param {} id
*/
function queryInit(requestUrl,tcolumn,tbar,id){
$("#"+id).datagrid({
title:"数据列表",
iconCls:'icon-search',
pageSize: 10,
pageList: [5,10,15,20,25,30],
nowrap: false,
striped: true,
collapsible:true,
url:requestUrl,
loadMsg:'数据加载中......',
sortOrder: 'desc',
remoteSort: false,
fitColumns:true,
singleSelect:false,
idField:'id',
frozenColumns:[[{field:'id',checkbox:true}]],
columns:tcolumn,
pagination:true,
rownumbers:true,
toolbar:tbar
});
$("#"+id).datagrid('getPager').pagination({
beforePageText: '第',//页数文本框前显示的汉字
afterPageText: '页 共 {pages} 页',
displayMsg: '当前显示 {from} - {to} 条记录 共 {total} 条记录',
onBeforeRefresh:function(pageNumber, pageSize){
$(this).pagination('loading');
$(this).pagination('loaded');
}
});
}
//判断值是否为“-”
function checknull(val){
if(val=='-'){
val="";
}
return val;
}
//关闭 strs div id 如:#divid1
function openDiv(id){
setWindow(id);
$('#'+id).css('display','block');
$('#'+id).window('open');
}
//关闭 strs div id 如:#divid1
function closeDiv(id){
$('#'+id).window('close');
}
//设置窗体
function setWindow(id){
var height=$('#'+id).height();
var width=$('#'+id).width();
$('#'+id).window({
// top:($(document).height()-height) * 0.5,
top:100,
// left:($(document).width()-width) * 0.5,
left:30,
modal:true,
draggable:true,
shadow:true
});
}
//参数加密
function escapeParam(value){
return escape(escape(value));
}
//重置 id 表单id
function resetForm(id) {
$('#'+id).each(function(){
this.reset();
});
}
/**
* 格式化性别
* @param {} val
* @param {} rec
* @return {}
*/
function formatSex(val,rec){
if(rec.sex==0){
val = "男";
}else if(rec.sex==1){
val = "女";
}
return val ;
} |
/*
* @Author: mkq 873302396@qq.com
* @Date: 2018-01-07 11:36:04
* @LastEditors: mkq 873302396@qq.com
* @LastEditTime: 2022-07-30 15:32:26
* @FilePath: \workPlace_reactMusic\react-music\src\components\MusicSheet.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import React, { Component } from 'react'
export default class MusicSheet extends Component {
constructor(props){
super(props);
this.state = {
showMusicItem:true
}
}
render() {
return (
<div className='music-sheet'>
<div className='music-sheet-title' onClick={e => this.toggleSheets(e)}>
<i className={this.state.showMusicItem?'icon icon-down':'icon icon-down rotate-icon'} ref='switch'/>
<div className='sheet-des'>
<span>我创建的歌单</span>
<span>({this.props.sheetData.length})</span>
<i className='icon icon-setting' />
</div>
</div>
<div className='music-sheet-list' style={{display:+this.state.showMusicItem?'block':'none'}}>
{
this.props.sheetData.map((item,index)=>
<div key={index} className='music-item' >
<img src={item.coverImgUrl} alt="图片"/>
<div className='music-des'>
<p className='item-name'>{item.name}</p>
<span className='count'>{item.trackCount}首歌曲</span>
<i className='icon icon-list-circle'/>
<p className='border-1px'/>
</div>
</div>
)
}
{/* <div className='music-item'>
<img src={'http://oiq8j9er1.bkt.clouddn.com/music_far%20away.jpg'}/>
<div className='music-des'>
<p className='item-name'>我喜欢的音乐</p>
<span className='count'>20首歌曲</span>
<i className='icon icon-list-circle'/>
<p className='border-1px'/>
</div>
</div> */}
</div>
</div>
)
}
toggleSheets(e){
let shoshowMusicItem = this.state.showMusicItem;
this.setState({
showMusicItem:!shoshowMusicItem
})
}
}
|
import request from '@/utils/request.js';
export async function getTodo(params = {}) {
return request('https://jsonplaceholder.typicode.com/todos/1', params);
}
|
var express = require('express');
var router = express.Router();
var activity = require('./app/activity');
var user = require('./app/user');
var news = require('./app/news');
router.use('/activity', activity);
router.use('/user', user);
router.use('/news', news);
module.exports = router;
|
import { ApiDownload } from '../../api/api'
export let request = function (url) {
let result = { success: false }
return new Promise(function (resolve, reject) {
ApiDownload(url).then((res) => {
console.log(res)
switch (res.code) {
case 200:
result.success = true
result.msg = res.data
break
case 551:
case 552:
case 553:
case 554:
result.msg = res.message
break
default:
result.msg = '出错啦,您可以选择加入xxx群反馈错误'
}
resolve(result)
}, (error) => {
result.msg = '请求失败'
console.error(error)
resolve(result)
})
})
}
|
// Starting with the number 1 and moving to the right in a clockwise direction a
// 5 by 5 spiral is formed as follows:
// 21 22 23 24 25
// 20 7 8 9 10
// 19 6 1 2 11
// 18 5 4 3 12
// 17 16 15 14 13
// It can be verified that the sum of the numbers on the diagonals is 101.
// What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral
// formed in the same way?
(function () {
'use strict';
var n = 1001;
var sum = 1;
var num = 1;
for (var i = 3; i <= n; i+=2) {
for (var j = 0; j < 4; j++) {
num = num + (i - 1);
sum = sum + num;
}
}
console.log(sum);
})();
|
import React, { useState } from "react";
import { SetCount } from "./SetCount";
import { Count } from "./Count";
import { Pure } from "./Pure";
import { Button } from "antd";
import { getBg } from "../getColor";
export const Context = React.createContext({});
const Stage2 = () => {
const [count, setCount] = useState(0);
const [, forceReRender] = useState({});
console.log("render");
return (
<>
<Button style={getBg()} onClick={() => forceReRender({})}>
FORCE_RE_RENDER
</Button>
<Context.Provider value={{ count, setCount }}>
<Count />
<SetCount />
<Pure />
</Context.Provider>
</>
);
};
export default Stage2;
|
/*global ODSA */
$(document).ready(function() {
"use strict";
var av_name = "TernaryRelationshipStoreYSol1";
var interpret = ODSA.UTILS.loadConfig({av_name: av_name}).interpreter;
var av = new JSAV(av_name);
//some attributes controlling entities matrices
var arrayWidth=120;
var arrayLeft=60;
var arrayGap=250;
var arrayTop=50;
//line connecting distributor to original bridge (product/country/distributor including price
var Bdg1DistMtrxHorLine = av.g.line(560, 90, 480, 90,{opacity: 100, "stroke-width": 2});
Bdg1DistMtrxHorLine.hide();
var DistMtrxRgtCardLab=av.label("<span style='color:blue;'>M</span>", {left: 540, top:55 });
DistMtrxRgtCardLab.css({"font-weight": "bold", "font-size": 15});
DistMtrxRgtCardLab.hide();
var Bdg1MtrxLeftCardLab=av.label("<span style='color:blue;'>1</span>", {left: 485, top:55 });
Bdg1MtrxLeftCardLab.css({"font-weight": "bold", "font-size": 15});
Bdg1MtrxLeftCardLab.hide();
//line connecting product to original bridge (product/country/distributor including price
var Bdg1ProdMtrxHorLine = av.g.line(845, 90, 910, 90,{opacity: 100, "stroke-width": 2});
Bdg1ProdMtrxHorLine.hide();
var ProdMtrxLeftCardLab=av.label("<span style='color:blue;'>1</span>", {left: 900, top:55 });
ProdMtrxLeftCardLab.css({"font-weight": "bold", "font-size": 15});
ProdMtrxLeftCardLab.hide();
var Bdg1MtrxRgtCardLab=av.label("<span style='color:blue;'>M</span>", {left: 845, top:55 });
Bdg1MtrxRgtCardLab.css({"font-weight": "bold", "font-size": 15});
Bdg1MtrxRgtCardLab.hide();
//line connecting country to original bridge (product/country/distributor including price
var Bdg1ConMtrxVerLine = av.g.line(720, 165, 720, 245,{opacity: 100, "stroke-width": 2});
Bdg1ConMtrxVerLine.hide();
var ConMtrxUPCardLab=av.label("<span style='color:blue;'>M</span>", {left: 720, top:150 });
ConMtrxUPCardLab.css({"font-weight": "bold", "font-size": 15});
ConMtrxUPCardLab.hide();
//ConMtrxUPCardLabAlternative of value 1 is the alternative of ConMtrxUPCardLab of value M fore store Y second solution
var ConMtrxUPCardLabAlternative=av.label("<span style='color:blue;'>1</span>", {left: 720, top:150 });
ConMtrxUPCardLabAlternative.css({"font-weight": "bold", "font-size": 15});
ConMtrxUPCardLabAlternative.hide();
var Bdg1MtrxDwnCardLab=av.label("<span style='color:blue;'>1</span>", {left: 720, top:213 });
Bdg1MtrxDwnCardLab.css({"font-weight": "bold", "font-size": 15});
Bdg1MtrxDwnCardLab.hide();
var StoreYsol1Analysis=av.label("<span style='color:blue;'>Store Y First & Second Solution Analysis</span>", {left: 330, top: arrayTop-60 });
StoreYsol1Analysis.css({"font-weight": "bold", "font-size": 28});
var SolutionType1=av.label("<span style='color:red;'>First sol.:</span><span style='color:blue;'>One (N:M:P) Ternary relationship, between (country/distributor/product) including price as a relationship attribute</span>", {left: 70, top: arrayTop+40 });
SolutionType1.css({"font-weight": "bold", "font-size": 20});
var SolutionType2=av.label("<span style='color:red;'>Second sol.:</span><span style='color:blue;'>One (1:N:M) Ternary relationship, between (country/distributor/product) including price as a relationship attribute</span>", {left: 70, top: arrayTop+120 });
SolutionType2.css({"font-weight": "bold", "font-size": 20});
var comment=av.label("<span style='color:red;'>Note:</span> The difference between these two solutions is the <span style='color:blue;'> '1' </span> cardinality connecting <span style='color:blue;'>country</span> to the ternary relationship.</span>", {left: 70, top: arrayTop+200 });
comment.css({"font-weight": "bold", "font-size": 20});
var Note=av.label("<span style='color:red;'>NOTE:</span> The problem with Store Y proposed solutions is not that they hinder dataset Y records representation but they don't prevent faulty data as shown here in the visualization", {left: 70, top: arrayTop+290 });
Note.css({"font-weight": "bold", "font-size": 16});
// Slide 1
av.umsg(interpret("").bold().big());
av.displayInit(1);
av.step();
//slide 2
SolutionType1.hide();
SolutionType2.hide();
comment.hide();
StoreYsol1Analysis.hide();
Note.hide();
var theDataSetY = [["Country","Product","Distributer","Price"],["Egypt","TV","ali","3000"],["Egypt","watch","ali","5000"],["UK","blender","ali","2500"],["UK","watch","ali","2300"],["USA","TV","adam","4500"],["USA","watch","adam","4700"],["USA","blender","adam","2000"],["lebanon","TV","morad","4000"],["lebanon","blender","morad","3000"]];
av.umsg(interpret("4- Discuss pros and cons of all possible <span style='color:blue;'>Store Y solutions</span> to determine the correct one. <br> <span style='color:red;'>----->By analysing each solution according to the previously given datasets.</span><br><span style='color:blue;'> <u>Store Y First sol. analysis:</u></span> ").bold().big());
var RealDataSetY= av.ds.matrix(theDataSetY, {style: "table", top: 0, left: 20 });
var sate1X1st=av.label("These are tables representing first solution relations, try to fill tables with records <br> in dataset.<br> ", {left: 20, top:320 });
sate1X1st.css({"font-weight": "bold", "font-size": 16});
for (var i=0; i < theDataSetY.length; i++)
{
RealDataSetY._arrays[i].css([0,1,2,3], {"font-size": 12});
RealDataSetY._arrays[i].show();
}
var DistributorMatrixLab=av.label("<span style='color:blue;'>Distributor</span>", {left: 340, top:-15 });
DistributorMatrixLab.css({"font-weight": "bold", "font-size": 14});
var theDistributorArrays = [["D-no","D-name"],["d1","ali"],["d2","adam"],["d3","tarek"]];
var theDistributorMatrix= av.ds.matrix(theDistributorArrays, {style: "table", top: 0, left: 340 });
theDistributorMatrix._arrays[0].css([0,1], {"font-weight": "bold", "color": "black"});
theDistributorMatrix._arrays[0].css([0], {"text-decoration": "underline"});
var Bridge3MatrixLab=av.label("<span style='color:blue;'>Bridge</span>", {left: 560, top:-15 });
Bridge3MatrixLab.css({"font-weight": "bold", "font-size": 14});
var theBridge3Arrays = [["c-no","p-no","d-no","price"],["","","",""],["","","",""],["","","",""],["","","",""]];
var theBridge3Matrix= av.ds.matrix(theBridge3Arrays, {style: "table", top: 0, left: 560 });
theBridge3Matrix._arrays[0].css([0,1,2,3], {"font-weight": "bold", "color": "black"});
theBridge3Matrix._arrays[0].css([0,1,2], {"text-decoration": "underline"});
var CountryMatrixLab=av.label("<span style='color:blue;'>Country</span>", {left: 660, top:215 });
CountryMatrixLab.css({"font-weight": "bold", "font-size": 14});
var theCountryArrays = [["C-no","c-name"],["c1","Egypt"],["c2","USA"],["c3","UK"]];
var theCountryMatrix= av.ds.matrix(theCountryArrays, {style: "table", top: 230, left: 660 });
theCountryMatrix._arrays[0].css([0,1], {"font-weight": "bold", "color": "black"});
theCountryMatrix._arrays[0].css([0], {"text-decoration": "underline"});
var ProductMatrixLab=av.label("<span style='color:blue;'>Product</span>", {left: 910, top:-15 });
ProductMatrixLab.css({"font-weight": "bold", "font-size": 14});
var theProductArrays = [["p-no","p-name"],["p1","TV"],["p2","Watch"],["p3","blender"]];
var theProductMatrix= av.ds.matrix(theProductArrays, {style: "table", top: 0, left: 910 });
theProductMatrix._arrays[0].css([0,1], {"font-weight": "bold", "color": "black"});
theProductMatrix._arrays[0].css([0], {"text-decoration": "underline"});
Bdg1DistMtrxHorLine.show();
DistMtrxRgtCardLab.show();
Bdg1MtrxLeftCardLab.show();
ProdMtrxLeftCardLab.show();
Bdg1MtrxRgtCardLab.show();
Bdg1ProdMtrxHorLine.show();
Bdg1ConMtrxVerLine.show();
ConMtrxUPCardLab.show();
Bdg1MtrxDwnCardLab.show();
av.step();
//slide 3
sate1X1st.hide();
var sate2X1st=av.label("<span style='color:red;'>Try Adding</span> <span style='color:green;'>Records 1</span> in Store Y dataset to solution tables here.", {left: 20, top:310 });
sate2X1st.css({"font-weight": "bold", "font-size": 16});
RealDataSetY._arrays[1].highlight();
av.step();
//slide 4
sate2X1st.hide();
var sate3X1st=av.label("<span style='color:red;'>In which</span> Distributor: <span style='color:blue;'>ali</span> sells Product: <span style='color:blue;'>TV</span> in country: <span style='color:blue;'>Egypt</span> with price:<span style='color:blue;'>3000</span>.", {left: 20, top:310 });
sate3X1st.css({"font-weight": "bold", "font-size": 16});
theDistributorMatrix._arrays[1].highlight();
theCountryMatrix._arrays[1].highlight();
theProductMatrix._arrays[1].highlight();
av.step();
//slide 5
sate3X1st.hide();
var sate4X1st=av.label("<span style='color:red;'>Then</span> all these data will be added to the <span style='color:green;'>Bridge</span>.", {left: 20, top:310 });
sate4X1st.css({"font-weight": "bold", "font-size": 16});
theBridge3Matrix._arrays[1].value(0,"<span style='color:red;'>c1</span>");
theBridge3Matrix._arrays[1].value(1,"<span style='color:red;'>p1</span>");
theBridge3Matrix._arrays[1].value(2,"<span style='color:red;'>d1</span>");
theBridge3Matrix._arrays[1].value(3,"<span style='color:red;'>3000</span>");
av.step();
//slide 6
sate4X1st.hide();
var sate5X1st=av.label("<span style='color:red;'>IF</span> you try adding <span style='color:green;'>all</span> dataset records in the bridge, it will be added <span style='color:green;'>SUCCESSFULLY</span></br><span style='color:red;'>BUT</span> this solution <span style='color:green;'>remains a FAULTY solution</span></br><span style='color:red;'>AS</span> It <span style='color:green;'>doesn't prevent</span> adding <span style='color:green;'>erroneous</span> data to the brigde.", {left: 20, top:310 });
sate5X1st.css({"font-weight": "bold", "font-size": 16});
theDistributorMatrix._arrays[1].unhighlight();
theCountryMatrix._arrays[1].unhighlight();
theProductMatrix._arrays[1].unhighlight();
for (var i=1; i < theDataSetY.length; i++)
{
RealDataSetY._arrays[i].highlight();
}
av.step();
//slide 7
sate5X1st.hide();
var sate6X1st=av.label("<span style='color:red;'>For Example:</span> try to add this record <span style='color:blue;'>(Egypt, TV, adam, 2500)</span> in the bridge", {left: 20, top:310 });
sate6X1st.css({"font-weight": "bold", "font-size": 16});
for (var i=1; i < theDataSetY.length; i++)
{
RealDataSetY._arrays[i].unhighlight();
}
theDistributorMatrix._arrays[2].highlight();
theCountryMatrix._arrays[1].highlight();
theProductMatrix._arrays[1].highlight();
av.step();
//slide 8
sate6X1st.hide();
var sate7X1st=av.label("<span style='color:green;'>Here is the fault</span> It is also added <span style='color:blue;'>successfully</span> which is <span style='color:red;'>logically wrong</span></br><span style='color:red;'>As</span> It allows multiple distributors (ali & adam) to sell the same product (tv) in the </br>same country (Egypt) </br>Which is <span style='color:red;'>against</span> store Y policy that dedicates only one distributor for each country to sell all products of that country.", {left: 20, top:295 });
sate7X1st.css({"font-weight": "bold", "font-size": 16});
theBridge3Matrix._arrays[2].highlight();
theBridge3Matrix._arrays[2].value(0,"<span style='color:red;'>c1</span>");
theBridge3Matrix._arrays[2].value(1,"<span style='color:red;'>p1</span>");
theBridge3Matrix._arrays[2].value(2,"<span style='color:red;'>d2</span>");
theBridge3Matrix._arrays[2].value(3,"<span style='color:red;'>2500</span>");
var Errorpointer = av.pointer("<span style='color:red;'><b>EEROR </b> </br> Logically wrong record</br>should not be added</span>",theBridge3Matrix._arrays[3].index(2), {left: 200, top: 250});
av.step();
//slide 9
av.umsg(interpret("4- Discuss pros and cons of all possible <span style='color:blue;'>Store Y solutions</span> to determine the correct one. <br> <span style='color:orange;'>----->PAY ATTENTION: switching for the second solution of the '1' cardinality</span><br><span style='color:blue;'> <u>Store Y Second sol. analysis:</u></span> ").bold().big());
Errorpointer.hide();
sate7X1st.hide();
var sate8X1st=av.label("The <span style='color:red;'>differences</span> between first and this second solutions in store Y is: </br> <b>-</b> <span style='color:blue;'> '1' cardinality</span> of country entity to the ternary relationship</br> <b>-</b> <span style='color:blue;'>(c-no)</span> isn't part of the bridge composit primary key because of the one cardinality.", {left: 20, top:310 });
sate8X1st.css({"font-weight": "bold", "font-size": 16});
for (var i=1; i <=2; i++)
{
for (var y=1; y<=3; y++)
{
theBridge3Matrix._arrays[i].value(y," ");
theBridge3Matrix._arrays[i].unhighlight();
}
}
theDistributorMatrix._arrays[2].unhighlight();
theCountryMatrix._arrays[1].unhighlight();
theProductMatrix._arrays[1].unhighlight();
ConMtrxUPCardLab.hide();
ConMtrxUPCardLabAlternative.show();
//for (var i=1; i < theBridge3Arrays.length; i++)
// {
// theBridge3Matrix._arrays[i].hide();
// }
//var Bridge3MatrixLab=av.label("<span style='color:blue;'>Bridge</span>", {left: 560, top:-15 });
//Bridge3MatrixLab.css({"font-weight": "bold", "font-size": 14});
theBridge3Arrays = [["p-no","d-no","c-no","price"],["","","",""],["","","",""],["","","",""],["","","",""]];
theBridge3Matrix= av.ds.matrix(theBridge3Arrays, {style: "table", top: 0, left: 560 });
theBridge3Matrix._arrays[0].css([0,1,2,3], {"font-weight": "bold", "color": "black"});
theBridge3Matrix._arrays[0].css([0,1], {"text-decoration": "underline"});
var PKpointer = av.pointer("<span style='color:red;'><b>(C-no)</b> is not part of PK</span>",theBridge3Matrix._arrays[1].index(2), {left: 200, top: 250});
var card1= av.g.circle(725,175 ,10 , {stroke: "red","stroke-width": 2});
av.step();
//slide 10
av.umsg(interpret("4- Discuss pros and cons of all possible <span style='color:blue;'>Store Y solutions</span> to determine the correct one.<br><span style='color:blue;'> <u>Store Y Second sol. analysis:</u></span> ").bold().big());
PKpointer.hide();
card1.hide();
sate8X1st.hide();
var sate9X1st=av.label("If we try adding some selected records from dataset in the solution design here, </br> <span style='color:blue;'>For example</span> dataset's first record added as shown in the bridge here</br> <span style='color:blue;'>Where</span> distributor ali who is dedicated for egypt country according to store Y policy sells TV.", {left: 20, top:310 });
sate9X1st.css({"font-weight": "bold", "font-size": 16});
RealDataSetY._arrays[1].highlight();
theDistributorMatrix._arrays[1].highlight();
theCountryMatrix._arrays[1].highlight();
theProductMatrix._arrays[1].highlight();
theBridge3Matrix._arrays[1].value(0,"<span style='color:red;'>p1</span>");
theBridge3Matrix._arrays[1].value(1,"<span style='color:red;'>d1</span>");
theBridge3Matrix._arrays[1].value(2,"<span style='color:red;'>c1</span>");
theBridge3Matrix._arrays[1].value(3,"<span style='color:red;'>3000</span>");
av.step();
//slide 11
sate9X1st.hide();
var sate10X1st=av.label("<span style='color:red;'>Then:</span> Adding second record as shown</br><span style='color:red;'>Where</span> Egypt's distributor (ali) sells another product watch </br><span style='color:red;'>also,</span> done successfully without physical or logical errors.", {left: 20, top:310 });
sate10X1st.css({"font-weight": "bold", "font-size": 16});
RealDataSetY._arrays[1].unhighlight();
RealDataSetY._arrays[2].highlight();
theProductMatrix._arrays[1].unhighlight();
theProductMatrix._arrays[2].highlight();
//theBridge3Matrix._arrays[2].highlight();
theBridge3Matrix._arrays[2].value(0,"<span style='color:red;'>p2</span>");
theBridge3Matrix._arrays[2].value(1,"<span style='color:red;'>d1</span>");
theBridge3Matrix._arrays[2].value(2,"<span style='color:red;'>c1</span>");
theBridge3Matrix._arrays[2].value(3,"<span style='color:red;'>5000</span>");
av.step();
//slide 12
sate10X1st.hide();
var sate11X1st=av.label("Adding third record </br><span style='color:red;'>Notice:</span> the same distributor ali who distributes in egypt sells in other country (UK)</br><span style='color:red;'>Which is</span> allowed in store Y policy that the same distributor sells in different countries.", {left: 20, top:310 });
sate11X1st.css({"font-weight": "bold", "font-size": 16});
RealDataSetY._arrays[2].unhighlight();
RealDataSetY._arrays[3].highlight();
//theDistributorMatrix._arrays[1].unhighlight();
// theCountryMatrix._arrays[1].unhighlight();
theProductMatrix._arrays[3].highlight();
theProductMatrix._arrays[2].unhighlight();
//theBridge3Matrix._arrays[3].highlight();
theCountryMatrix._arrays[1].unhighlight();
theCountryMatrix._arrays[3].highlight();
theBridge3Matrix._arrays[3].value(0,"<span style='color:red;'>p3</span>");
theBridge3Matrix._arrays[3].value(1,"<span style='color:red;'>d1</span>");
theBridge3Matrix._arrays[3].value(2,"<span style='color:red;'>c3</span>");
theBridge3Matrix._arrays[3].value(3,"<span style='color:red;'>2500</span>");
av.step();
//slide 13
sate11X1st.hide();
var sate12X1st=av.label("Try adding forth record </br><span style='color:red;'>where</span> UK's distributor (ali) sells another product watch in UK </br><span style='color:red;'>Which is</span> allowed in store Y policy that the same distributor sells in different countries.", {left: 20, top:310 });
sate12X1st.css({"font-weight": "bold", "font-size": 16});
RealDataSetY._arrays[3].unhighlight();
RealDataSetY._arrays[4].highlight();
theProductMatrix._arrays[2].highlight();
theProductMatrix._arrays[3].unhighlight();
theBridge3Matrix._arrays[4].value(0,"<span style='color:red;'>p2</span>");
theBridge3Matrix._arrays[4].value(1,"<span style='color:red;'>d1</span>");
theBridge3Matrix._arrays[4].value(2,"<span style='color:red;'>c3</span>");
theBridge3Matrix._arrays[4].value(3,"<span style='color:red;'>2300</span>");
av.step();
//slide 14
sate12X1st.hide();
var sate13X1st=av.label("<span style='color:red;'>PHYSICAL ERROR</span> </br>In this solution design both (d-id & p-id) are composite PK that can not be repeated</br><span style='color:blue;'>But</span> ali previously sold watch in egypt <i><span style='color:green;'>(record 2 in bridge)</span>-----> (PK repetition)", {left: 20, top:310 });
sate13X1st.css({"font-weight": "bold", "font-size": 16});
theBridge3Matrix._arrays[0].highlight(0);
theBridge3Matrix._arrays[0].highlight(1);
theBridge3Matrix._arrays[2].highlight(0);
theBridge3Matrix._arrays[2].highlight(1);
theBridge3Matrix._arrays[4].highlight(0);
theBridge3Matrix._arrays[4].highlight(1);
theProductMatrix._arrays[2].unhighlight();
theCountryMatrix._arrays[3].unhighlight();
theDistributorMatrix._arrays[1].unhighlight();
av.step();
//slide 15
sate13X1st.hide();
var sate14X1st=av.label("<span style='color:red;'>PHYSICAL ERROR</span> </br><span style='color:red;'>So</span> that design is faulty as it doesn't fulfill store y requirements </br>that allows same distributor to sell in different countries & by the way he may sell the same product in those countries.", {left: 20, top:310 });
sate14X1st.css({"font-weight": "bold", "font-size": 16});
var ErrorPk= av.pointer("<span style='color:red;'><b>Physical EEROR:</b> PK repetition</span>",theBridge3Matrix._arrays[3].index(1), {left: 200, top: 230});
var ErrorPkrepeate= av.pointer("",theBridge3Matrix._arrays[4].index(1), {left: 230, top: 200});
av.step();
//slide 16
ErrorPk.hide();
ErrorPkrepeate.hide();
theBridge3Matrix._arrays[0].unhighlight(0);
theBridge3Matrix._arrays[0].unhighlight(1);
theBridge3Matrix._arrays[2].unhighlight(0);
theBridge3Matrix._arrays[2].unhighlight(1);
theBridge3Matrix._arrays[4].unhighlight(0);
theBridge3Matrix._arrays[4].unhighlight(1);
RealDataSetY._arrays[4].unhighlight();
RealDataSetY._arrays[1].highlight(0);
RealDataSetY._arrays[1].highlight(2);
RealDataSetY._arrays[2].highlight(0);
RealDataSetY._arrays[2].highlight(2);
theBridge3Matrix._arrays[4].value(0,"");
theBridge3Matrix._arrays[4].value(1,"");
theBridge3Matrix._arrays[4].value(2,"");
theBridge3Matrix._arrays[4].value(3," ");
sate14X1st.hide();
var sate15X1st=av.label("<span style='color:red;'> This solution</span> also results in a <span style='color:red;'> Logical Error </span> </br> Assume adding a faulty record as <span style='color:blue;'> (adam ,Egypt, TV, 1500) </span>, this is wrong data as </br>Egypt already has an execlusive distributor (ali) in the dataset.", {left: 20, top:310 });
sate15X1st.css({"font-weight": "bold", "font-size": 16});
theProductMatrix._arrays[1].highlight();
theCountryMatrix._arrays[1].highlight();
theDistributorMatrix._arrays[2].highlight();
av.step();
//slide 17
sate15X1st.hide();
var sate16X1st=av.label("<span style='color:red;'>Unfortunately </span> the record is added SUCCESSFULLY which is <span style='color:blue;'>WRONG</span></br><span style='color:blue;'>Now</span> (ali & adam both distribute in Egypt)</span>, <span style='color:blue;'>contradicting</span> store's Y policy of one </br> execlusive distributor for each country.", {left: 20, top:310 });
sate16X1st.css({"font-weight": "bold", "font-size": 16});
theBridge3Matrix._arrays[4].value(0,"<span style='color:red;'>p1</span>");
theBridge3Matrix._arrays[4].value(1,"<span style='color:red;'>d2</span>");
theBridge3Matrix._arrays[4].value(2,"<span style='color:red;'>c1</span>");
theBridge3Matrix._arrays[4].value(3,"<span style='color:red;'>1500</span>");
ErrorPkrepeate= av.pointer("<span style='color:red;'>Logically Wrong record </br> should not be added</span>",ConMtrxUPCardLabAlternative, {left: 210, top: 200});
RealDataSetY._arrays[1].unhighlight(0);
RealDataSetY._arrays[1].unhighlight(2);
RealDataSetY._arrays[2].unhighlight(0);
RealDataSetY._arrays[2].unhighlight(2);
theProductMatrix._arrays[1].unhighlight();
theCountryMatrix._arrays[1].unhighlight();
theDistributorMatrix._arrays[2].unhighlight();
theBridge3Matrix._arrays[1].highlight(1);
theBridge3Matrix._arrays[1].highlight(2);
theBridge3Matrix._arrays[2].highlight(1);
theBridge3Matrix._arrays[2].highlight(2);
theBridge3Matrix._arrays[4].highlight(1);
theBridge3Matrix._arrays[4].highlight(2);
var adamPointer= av.pointer("<span style='color:blue;'>d2=adam </br> c1=Egypt</span>",ConMtrxUPCardLabAlternative, {left: 210, top: 100});
var aliEgyptPointer= av.pointer("<span style='color:blue;'>d1=ali </br> c1=Egypt</span>",theBridge3Matrix._arrays[2].index(1), {left: 0, top: 155});
av.step();
av.recorded();
});
|
var chai = require ('chai');
var sinon = require ('sinon');
var assert = chai.assert;
var User = require('../db/models/').User;
const login = require('../controllers/loginController');
var jwt = require('jwt-simple');
describe("login", function(){
it ('Do not get the users for null emails ', async function(){
var spy = sinon.spy();
sinon.stub(User,"findOne").resolves({
email : "kirisanth@gmail.com"
});
req = {
body:{user:null}
}
res = {
json:spy
}
await login(req,res);
User.findOne.restore();
var dataForNull = {noEmail:"There is no user name!", correctUser:"false"};
assert.equal(spy.called,true);
assert.equal(spy.calledWith(dataForNull),true);
});
it ('not null emails didn\'t receive noEmail message', async function(){
var spy = sinon.spy();
sinon.stub(User,"findOne").resolves({
email : "kirisanth@gmail.com"
});
req = {
body:{emailId:"kirisanth@gmsil.com"}
}
res = {
json:spy
}
await login(req,res);
User.findOne.restore();
var dataForNull = {noEmail:"There is no user name!", correctUser:"false"};
assert.equal(spy.called,true);
assert.equal(spy.calledWith(dataForNull),false);
});
it ('There is no matched user', async function(){
var spy = sinon.spy();
sinon.stub(User,"findOne").resolves(null);
req = {
body:{emailId : "kirisanth@gmail.com"}
}
res = {
json : spy
}
await login(req,res);
User.findOne.restore();
var dataForNoUser = {userNotFound:"No user with this Email Address !", correctUser:"false"};
assert.equal(spy.called,true);
assert.equal(spy.calledWith(dataForNoUser),true);
});
it ('If The password is correct', async function(){
var spy = sinon.spy();
//var stub = sinon.stub().returnsThis();
var user = {
password : "1234",
id : "55",
email : "kirisanth@gmail.com",
firstName : "kirisanth",
lastName : "senthilnathan"
}
sinon.stub(User,"findOne").resolves({
password : "1234",
id : "55",
email : "kirisanth@gmail.com",
firstName : "kirisanth",
lastName : "senthilnathan"
});
req = {
body:{emailId:"kirisanth@gmail.com",password:"1234"}
}
res = {
json : spy
}
await login(req,res);
User.findOne.restore();
var token = jwt.encode({id:user.id}, "Your Secret code");
var dataForCorrectPw = {userToken:token,email:user.email,firstname:user.firstName,lastname:user.lastName,id:user.id,correctUser:"true"};
assert.equal(spy.called,true);
assert.equal(spy.calledWith(dataForCorrectPw),true);
});
it ('If The password is Wrong', async function(){
var spy = sinon.spy();
//var stub = sinon.stub().returnsThis();
var user = {
password : "1234",
id : "55",
email : "kirisanth@gmail.com",
firstName : "kirisanth",
lastName : "senthilnathan"
}
sinon.stub(User,"findOne").resolves({
password : "1234",
id : "55",
email : "kirisanth@gmail.com",
firstName : "kirisanth",
lastName : "senthilnathan"
});
req = {
body:{emailId:"kirisanth@gmail.com",password:"van"}
}
res = {
json : spy
}
await login(req,res);
User.findOne.restore();
var token = "wyewwuiui234423234rsr";
var dataForWrongPw = {"message" : "Wrong user name or password", correctUser:"false"};
assert.equal(spy.called,true);
assert.equal(spy.calledWith(dataForWrongPw),true);
});
});
|
import { Component } from 'react';
import PropTypes from "prop-types";
import { connect } from 'react-redux';
import { logout } from '../services/AuthenticationService';
import { removeToken } from '../actions/authentication';
class LogoutPage extends Component {
static propTypes = {
dispatch: PropTypes.func.isRequired
};
componentWillMount = async () => {
try {
const isLoggedOut = await logout();
if (isLoggedOut === true) {
await this.props.dispatch(removeToken());
this.props.history.push('/');
}
} catch (error) {
console.log(error);
}
}
render() {
return null;
}
}
export default connect() (LogoutPage); |
//验证真实名字格式
function userRealName(flag) {
var realName = $.trim($("#realName").val());
var rtn = false;
if (null==realName || realName=="") {
showError("realName", "真实姓名不能为空");
return false;
} else if (!/[^\x00-\x80]/.test(realName)) {
showError("realName", "请输入真实的中文姓名");
return false;
} else {
showSuccess('realName');
rtn = true;
}
if(!rtn){
return false;
}
return true;
}
//身份证号码验证
function idCardCheck() {
var rtn = false;
var idCard = $.trim($("#idCard").val());
var replayIdCard = $.trim($("#replayIdCard").val());
if (idCard=="") {
showError('idCard','请输入身份证号码');
return false;
}
//身份证号码为15位或18位,15位时全为数字,18位前17位为数字,最后一位是校验位,可能为数字或字符X
var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
if (!(reg.test(idCard))) {
showError('idCard','请输入正确的身份证号码');
return false;
} else if (idCard.length < 15 || idCard.length > 18 || idCard.length == 17) {
showError('idCard','身份证号码应为15或18位');
return false;
} else {
$.ajax({
url:"loan/checkIdCard",
type:"POST",
dataType:"json",
async:false,
data:"idCard="+idCard,
success:function(jsonMap) {
if(jsonMap.errorMessage == "ok") {
showSuccess("idCard");
rtn = true;
} else {
showError("idCard",jsonMap.errorMessage);
rtn = false;
}
},
error:function() {
showError("idCard","网络错误");
rtn = false;
}
});
}
if (replayIdCard != null && replayIdCard != null && idCard == replayIdCard) {
showSuccess('replayIdCard');
}
if(!rtn){
return false;
}
return true;
}
//两次密码是否相等验证
function idCardEequ() {
var idCard=$.trim($("#idCard").val());//身份证
var replayIdCard=$.trim($("#replayIdCard").val());//确认身份证
if (!idCardCheck()) {
hideError('replayIdCard');
return false;
}
if (idCard == "") {
showError('idCard','请输入身份证号码!');
return false;
} else if(replayIdCard == "") {
showError('replayIdCard','请再次输入身份证号码');
return false;
} else if(idCard!=replayIdCard) {
showError('replayIdCard','两次输入身份证号码不一致');
return false;
} else {
showSuccess('replayIdCard');
return true;
}
return true;
}
//验证码验证
function checkCaptcha() {
var rtn = false;
var captcha = $.trim($("#captcha").val());
if (captcha == "") {
showError('captcha','请输入图形验证码');
return false;
} else {
$.ajax({
type:"POST",
url:"loan/checkCaptcha",
async: false,
data:"captcha="+captcha,
success: function(retMap) {
if (retMap.errorCode) {
showSuccess('captcha');
rtn = true;
} else {
showError('captcha', retMap.errorMessage);
rtn = false;
}
},
error:function() {
showError('captcha','网络错误');
rtn = false;
}
});
}
if (!rtn) {
return false;
}
return true;
}
//错误提示
function showError(id,msg) {
$("#"+id+"Ok").hide();
$("#"+id+"Err").html("<i></i><p>"+msg+"</p>");
$("#"+id+"Err").show();
$("#"+id).addClass("input-red");
}
//错误隐藏
function hideError(id) {
$("#"+id+"Err").hide();
$("#"+id+"Err").html("");
$("#"+id).removeClass("input-red");
}
//成功
function showSuccess(id) {
$("#"+id+"Err").hide();
$("#"+id+"Err").html("");
$("#"+id+"Ok").show();
$("#"+id).removeClass("input-red");
}
//实名认证提交
function realName () {
var idCard = $.trim($("#idCard").val());
var replayIdCard = $.trim($("#replayIdCard").val());//确认身份证号
var realName = $.trim($("#realName").val());
var captcha = $.trim($("#captcha").val());
if(userRealName(0) && idCardEequ() && checkCaptcha() && idCardCheck()) {
$.ajax({
type:"POST",
url:"loan/checkRealName",
dataType: "json",
async: false,
data:"realName="+realName+"&idCard="+idCard+"&replayIdCard="+replayIdCard+"&captcha="+captcha,
success: function(retMap) {
if (retMap.errorMessage == "ok") {
window.location.href = "loan/showMyCenter";
} else {
showError('captcha', retMap.errorMessage);
}
},
error:function() {
showError('captcha','网络错误');
rtn = false;
}
});
}
}
//同意实名认证协议
$(function() {
$("#agree").click(function(){
var ischeck = document.getElementById("agree").checked;
if (ischeck) {
$("#btnRegist").attr("disabled", false);
$("#btnRegist").removeClass("fail");
} else {
$("#btnRegist").attr("disabled","disabled");
$("#btnRegist").addClass("fail");
}
});
});
//打开注册协议弹层
function alertBox(maskid,bosid){
$("#"+maskid).show();
$("#"+bosid).show();
}
//关闭注册协议弹层
function closeBox(maskid,bosid){
$("#"+maskid).hide();
$("#"+bosid).hide();
} |
var TestController = app.controller('Test');
TestController.action('another', 'views/Test/anotherPage.html', function($scope) {
return $scope;
});
|
import styled from 'styled-components'
const Paragraph = styled.p.attrs(props => ({
fontSize: props.fontSize || '1.6rem',
lineHeight: props.theme.lineHeight.expanded || 1.2,
}))`
font-size: ${props => props.fontSize};
margin: 0 0 2rem 0;
line-height: ${props => props.lineHeight};
`
export default Paragraph |
import React from 'react';
import Styled from 'styled-components/native';
const Container = Styled.TouchableWithoutFeedback`
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
`;
const BlackBackground = Styled.View`
background-color: #000;
opacity: 0.3;
width: 100%;
height: 100%;
`;
const Background = ({ onPress }) => {
return (
<Container onPress={onPress}>
<BlackBackground />
</Container>
);
};
export default Background; |
$(function(){
var iter = 0;
var canvas = $("#field")[0];
var context = canvas.getContext('2d');
context.beginPath();
for ( i = 1; i < 20; ++i )
{
context.moveTo( i * 20, 0 );
context.lineTo( i * 20, 400 );
context.moveTo( 0, i * 20 );
context.lineTo( 400, i * 20 );
}
context.stroke();
var parts = [];
for ( i = 0; i < 20; ++i)
{
parts.push([]);
for( j = 0; j < 20; ++j)
parts[i].push(0);
}
var temp = [];
for ( i = 0; i < 20; ++i )
{
temp.push([]);
for ( j = 0; j < 20; ++j )
temp[i].push(0);
}
function draw()
{
for ( i = 0; i < 20; ++i)
{
for ( j = 0; j < 20; ++j)
{
if(parts[i][j])
context.fillStyle = "red";
else
context.fillStyle = "#333333";
context.fillRect( i * 20, j * 20, 19, 19 )
}
}
}
draw();
canvas.addEventListener( "click", position, false )
function position(a)
{
var x = Math.floor ( a.clientX / 20 ) - 1;
var y = Math.floor ( a.clientY / 20 ) - 1;
parts[x][y] = !parts[x][y];
draw();
}
function search ( a, b )
{
var counter = 0;
for ( var i = a - 1; i <= a + 1; ++i )
{
for ( var j = b - 1; j <= b + 1; ++j )
{
if ((i != a || j != b) && parts[( i + 20 ) % 20][( j + 20 ) % 20])
++counter;
}
}
return counter;
}
var event = function()
{
for ( i = 0; i < 20; ++i )
{
for ( j = 0; j < 20; ++j )
{
temp[i][j] = parts[i][j];
var num = search( i, j );
if ( num < 2 || num > 3 )
temp[i][j] = 0;
if ( num == 3 )
temp[i][j] = 1;
}
}
for ( i = 0; i < 20; ++i )
{
for ( j = 0; j < 20; ++j )
{
parts[i][j] = temp[i][j];
}
}
draw();
iter+= 1;
$("#generationNum").text(iter);
}
$('#start').click(function(){
time = setInterval(event, 400);
});
$('#stop').click(function(){
clearInterval(time);
});
}); |
var Order = require('../models/order')
var OrderStatus = require('../models/order-status')
exports.save = function (req, res) {
var orderObj = req.body
if (orderObj._id) {
Order.update({_id: orderObj._id}, {$set: orderObj}, function (err) {
if (err) {
res.send({
success: false,
reason: err
})
} else {
res.send({
success: true
})
}
})
} else {
var orderStatus = []
OrderStatus.fetch(function (err, orderstatuses) {
if (err) {
console.log(err)
} else {
for (var item of orderstatuses) {
if (item.name == '暂挂') {
orderStatus[0] = item
} else if (item.name == '未支付') {
orderStatus[1] = item
}
}
orderObj.status = orderStatus[orderObj.status]._id
_order = new Order(orderObj)
_order.save(function (err, order) {
if (err) {
res.send({
success: false,
reason: err
})
} else {
res.send({
success: true
})
}
})
}
})
}
}
exports.search = function (req, res) {
var filterCondition = req.query
Order.find(filterCondition)
.populate('customer meals.meal')
.exec(function (err, orders) {
if (err) {
res.send({
success: false,
reason: err
})
} else {
res.send({
success: true,
orderList: orders
})
}
})
}
exports.del = function (req, res) {
var filterCondition = req.body
Order.remove(filterCondition, function (err) {
if (err) {
res.send({
success: false,
reason: err
})
} else {
res.send({
success: true
})
}
})
} |
// Very simple, given an integer or a floating-point number, find its opposite.
// Examples:
// 1: -1
// 14: -14
// -34: 34
// function opposite(number) {
// //your code here
// }
//should be an easy kata, just need to use math operators
// let opposite = number => {
// return - number
// }
//condensed
let opposite = number => -number
console.log(opposite(-5))
//standard function
function opposite (number) {
return -number
} |
import * as lollipop from "./graphs/lollipop.js";
import * as piechart from "./graphs/pie_chart.js";
// handles safely loading data
// returns a promise
// to use, load_data().then(callback)
const load_data= () =>
Promise.all(
[ d3.csv("./data/hybrid_summary.csv") ]
).then( ([ hybrid_summary ]) => {
// parse strings into numeric values
const processed_hybrid_sumamry = hybrid_summary.map(row => {
row.Total_Increment = +row.Total_Increment
row.Final_Height = +row.Final_Height
row.Average_Height = +row.Average_Height
return row
})
// change this to maybe load from file..
const pie_data = [
{healthy: 12, diseased: 1, dead: 11},
{healthy: 8, diseased: 1, dead: 15},
{healthy: 21, diseased: 3, dead: 0},
{healthy: 16, diseased: 8, dead: 0},
{healthy: 19, diseased: 5, dead: 0},
]
return {
hybrid_summary: processed_hybrid_sumamry,
pie_data: pie_data
}
}).catch(error => {
console.log(`Data load failed!\n${error.message}`)
})
load_data().then(data => {
lollipop.init("#lollipop", data.hybrid_summary)
piechart.init("#piechart", data.pie_data)
}).catch(error => {
console.log(`Failed to load and render graphs!\n${error.message}`)
})
// // // // // // // // // // // // // // // // // // // // // // // // // // // // //
// // // // // // // FINAL HEIGHT BOX PLOT / // // // // // // // // //
// // // // // // // // // // // // // // // // // // // // // // // // // // // // //
// // set the dimensions and margins of the graph
// var margin = {top: 10, right: 30, bottom: 30, left: 40},
// width = 460 - margin.left - margin.right,
// height = 400 - margin.top - margin.bottom;
// // append the svg object to the body of the page
// var svg = d3.select("#my_dataviz2")
// .append("svg")
// .attr("width", width + margin.left + margin.right)
// .attr("height", height + margin.top + margin.bottom)
// .append("g")
// .attr("transform",
// "translate(" + margin.left + "," + margin.top + ")");
// // Read the data and compute summary statistics for each specie
// d3.csv("https://raw.githubusercontent.com/ilkercancicek/Group-Design-Practical/main/hybrid_walnut.csv", function(data) {
// // Compute quartiles, median, inter quantile range min and max --> these info are then used to draw the box.
// var sumstat = d3.nest() // nest function allows to group the calculation per level of a factor
// .key(function(d) { return d.Species;})
// .rollup(function(d) {
// q1 = d3.quantile(d.map(function(g) { return g.Final_Height;}).sort(d3.ascending),.25)
// median = d3.quantile(d.map(function(g) { return g.Final_Height;}).sort(d3.ascending),.5)
// q3 = d3.quantile(d.map(function(g) { return g.Final_Height;}).sort(d3.ascending),.75)
// interQuantileRange = q3 - q1
// min = q1 - 1.5 * interQuantileRange
// max = q3 + 1.5 * interQuantileRange
// return({q1: q1, median: median, q3: q3, interQuantileRange: interQuantileRange, min: min, max: max})
// })
// .entries(data)
// // Show the X scale
// var x = d3.scaleBand()
// .range([ 0, width ])
// .domain(["Bressanvido", "IRTA X-80", "MJ209", "NG23", "NG38"])
// .paddingInner(1)
// .paddingOuter(.5)
// svg.append("g")
// .attr("transform", "translate(0," + height + ")")
// .call(d3.axisBottom(x))
// // Show the Y scale
// var y = d3.scaleLinear()
// .domain([0,625])
// .range([height, 0])
// svg.append("g").call(d3.axisLeft(y))
// // Show the main vertical line
// svg
// .selectAll("vertLines")
// .data(sumstat)
// .enter()
// .append("line")
// .attr("x1", function(d){return(x(d.key))})
// .attr("x2", function(d){return(x(d.key))})
// .attr("y1", function(d){return(y(d.value.min))})
// .attr("y2", function(d){return(y(d.value.max))})
// .attr("stroke", "black")
// .style("width", 40)
// // rectangle for the main box
// var boxWidth = 100
// svg
// .selectAll("boxes")
// .data(sumstat)
// .enter()
// .append("rect")
// .attr("x", function(d){return(x(d.key)-boxWidth/2)})
// .attr("y", function(d){return(y(d.value.q3))})
// .attr("height", function(d){return(y(d.value.q1)-y(d.value.q3))})
// .attr("width", boxWidth )
// .attr("stroke", "black")
// .style("fill", "#69b3a2")
// // Show the median
// svg
// .selectAll("medianLines")
// .data(sumstat)
// .enter()
// .append("line")
// .attr("x1", function(d){return(x(d.key)-boxWidth/2) })
// .attr("x2", function(d){return(x(d.key)+boxWidth/2) })
// .attr("y1", function(d){return(y(d.value.median))})
// .attr("y2", function(d){return(y(d.value.median))})
// .attr("stroke", "black")
// .style("width", 80)
// // Add individual points with jitter
// var jitterWidth = 50
// svg
// .selectAll("indPoints")
// .data(data)
// .enter()
// .append("circle")
// .attr("cx", function(d){return(x(d.Species) - jitterWidth/2 + Math.random()*jitterWidth )})
// .attr("cy", function(d){return(y(d.Final_Height))})
// .attr("r", 4)
// .style("fill", "white")
// .attr("stroke", "black")
// })
|
'use strict';
const extractBundles = require('./utils').extractBundles;
exports.done = function done(stats) {
stats = stats.toJson();
const bundles = extractBundles(stats);
const modules = stats.modules.reduce((map, module) => {
map[module.id] = module.name;
return map;
}, {});
bundles.forEach((stats) => {
//const event = {
//name: stats.name,
//action: 'built',
//time: stats.time,
//hash: stats.hash,
//warnings: stats.warnings || [],
//errors: stats.errors || [],
//modules: modules
//};
});
};
|
import React from "react"
import useGameLogic from "./hooks/useGameLogic"
import GameDisplay from "./components/GameDisplay";
import TimeSelector from "./components/TimeSelector"
import "./styles/App.css"
function App() {
const {
isTimeRunning,
timeRemaining,
updateGameLength,
gameLength,
startGame,
word,
wordCompleted,
wordCount,
displayResults,
} = useGameLogic()
return (
<div>
<h1>How fast do you type?</h1>
<GameDisplay
word={word}
wordCompleted={wordCompleted}
isDisabled={!isTimeRunning}
gameLength={gameLength}
displayResults={displayResults}
wordCount={wordCount}
/>
<h4>Time remaining: {timeRemaining}</h4>
<TimeSelector
updateGameLength={updateGameLength}
isTimeRunning={isTimeRunning}
/>
<button
onClick={startGame}
disabled={isTimeRunning}
>
Start
</button>
<h1>Word count: {wordCount}</h1>
</div>
)
}
export default App
|
// //FeetToMile
function feetToMile(feet){
var result=feet/5280
return result
}
//WoodCalculator
function WoodCalculator(chair,table,bed){
var WoodForChair=chair*1
var WoodForTable=table*3
var WoodForBed=bed*5
var totalWood=WoodForChair+WoodForTable+WoodForBed
return totalWood
}
//tinyFriend
function tinyFriend(friends){
var tiny=friends[0];
for(var i=0;i>friends.length;i--){
var friend1=friends[i];
if(friend1<tiny){
tiny=friend1
}
}
return tiny
}
|
;(function () {
/* global angular */
angular.module('musicLibrary.albums', [])
.config(routerConfig)
function routerConfig ($stateProvider) {
$stateProvider
.state('albums', {
url: '/albums',
templateUrl: 'app/albums/list.html',
controller: AlbumsController,
controllerAs: 'vm'
})
.state('albums_add', {
url: '/albums/add',
templateUrl: 'app/albums/add.html',
controller: AlbumsController,
controllerAs: 'vm'
})
.state('albums_edit', {
url: '/albums/:id/edit',
templateUrl: 'app/albums/edit.html',
controller: AlbumsController,
controllerAs: 'vm'
})
}
routerConfig.$inject = ['$stateProvider']
function AlbumsController ($resource, $state, $stateParams) {
const ctrl = this
const AlbumResource = $resource('/api/albums/:id', null, {update: {method: 'PUT'}})
ctrl.initList = () => {
ctrl.albums = AlbumResource.query()
}
ctrl.create = (album, form) => {
if (isValid(form)) {
AlbumResource
.save(album)
.$promise
.then(() => {
$state.go('albums')
})
}
}
ctrl.initArtists = () => {
ctrl.artists = $resource('/api/artists/:id').query()
}
ctrl.initEdit = () => {
ctrl.initArtists()
ctrl.album = AlbumResource.get({id: $stateParams.id})
}
ctrl.update = (album, form) => {
if (isValid(form)) {
AlbumResource
.update({id: album.id}, album)
.$promise
.then(() => {
$state.go('albums')
})
}
}
ctrl.remove = (id) => {
AlbumResource
.remove({id: id})
.$promise
.then(() => {
$state.reload()
})
}
function isValid (form) {
return form.$valid && form.$dirty && form.artistId.$valid
}
}
AlbumsController.$inject = ['$resource', '$state', '$stateParams']
})()
|
'use strict';
/** @type Egg.EggPlugin */
// 用于配置需要加载的插件
module.exports = {
// had enabled by egg
// static: {
// enable: true,
// }
validate: {
enable: true,
package: 'egg-validate',
},
watcherChokidar: {
enable: true,
package: 'egg-watcher-chokidar',
},
mysql: {
enable: true,
package: 'egg-mysql',
}
}
// exports.watcherChokidar = {
// enable: true,
// package: 'egg-watcher-chokidar',
// };
|
HomeController = RouteController.extend({
subscriptions: function() {
TAPi18n.subscribe("categories");
TAPi18n.subscribe("ages");
},
action: function() {
this.render('Home');
}
});
|
/**
* Created by Vic.Feng on 08/12/2015.
*/
function login() {
var username = $("#USERNAME");
var password = $("#PASSWORD");
var organisation = $("#org");
$.ajax({
url: "/home/login",
data: '{"username":"' + username.val() + '", "password":"' + password.val() + '", "organisation":"' + organisation.val() + '"}',
type: "POST",
dataType: "json",
contentType: "application/json",
async: false,
success: function (responseText) {
if (responseText.code == 0) {
window.location.href = '/asset/searchPage';
} else {
alert("Error");
}
},
error: function () {
alert("Error");
}
});
}
//Check if user press enter key
function checkEnterKey() {
if (event.keyCode == 13) {
login();
}
} |
const mongoose = require("mongoose");
const orangeBuyerSchema = new mongoose.Schema({
userName: String,
email: String,
password: String,
});
const Buyer = new mongoose.model("Buyers", orangeBuyerSchema);
module.exports = Buyer;
|
const logger = require('./logger');
const mongo = require('./mongo');
const email = require('./email');
const port = process.env.APP_PORT || 3000;
const env = process.env.NODE_ENV || 'development';
module.exports = {
env,
port,
logger,
mongo,
email,
};
|
const npmLogin = require("npm-cli-login");
const { exec } = require("child_process");
function getNpmLoginData() {
if (process.env["NODE_USERNAME"]) {
// use system env
const username = process.env["NODE_USERNAME"];
const password = process.env["NODE_PASSWORD"];
const email = process.env["NODE_EMAIL"];
const registry = process.env["NODE_REGISTRY"];
return { username, password, email, registry };
} else {
return require("../../publish-config.json");
}
}
function main() {
const { username, password, email, registry } = getNpmLoginData();
npmLogin(username, password, email, registry);
console.log(
"----------------\n" + "user login success\n" + "----------------"
);
exec(`npm publish --registry=${registry}`, (error, stdout, stderr) => {
if (error) {
throw error;
}
console.log(stdout);
});
}
// run main
main();
|
//截取字符串,text为字符串,totalCharLen为总字数,extChar是可选参数,为超出补充的样式,默认为“...”
export function cutOffText(text, totalCharLen, extChar = '...') {
if(!text || typeof totalCharLen !== "number")
return '';
if(totalCharLen >= text.length)
return text;
let idx = 0;
// for(let i = 0; i < totalCharLen; ++i) {
// if (text.codePointAt(i) < 27 || text.codePointAt(i) > 126) {
// idx += 2;
// } else {
// ++idx;
// }
// }
let result = text.substring(0, totalCharLen) + extChar;
return result;
} |
// packages
import React from "react";
// css
import "../css/LoginRegister.css";
class LoginView extends React.Component {
constructor(props) {
super(props);
this.refs = React.createRef();
this.state = {
isLoggedIn: !!localStorage.getItem("token")
};
}
login = (e) => {
e.preventDefault();
const mail = this.refs.login_mail.value;
const pass = this.refs.login_pass.value;
const usr = JSON.stringify({
email: mail,
password: pass
});
let token = undefined;
const xhr = new XMLHttpRequest();
xhr.onloadend = ()=> {
if(xhr.status !== 200) {
alert(xhr.response);
} else {
token = xhr.response;
localStorage.setItem("token", token);
this.setState({isLoggedIn: true});
}
};
// changed from 3000
xhr.open("POST", "https://obscure-sierra-52013.herokuapp.com/api/auth/");
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.send(usr);
}
render() {
return (
<div class="login-register-bg container-login">
<div class="infoPanel">
<p>
Miło cię widzieć z powrotem.
<br />
Co dzisiaj zjemy?
</p>
</div>
<div class="formPanel">
<form>
<p>Zaloguj się</p>
<input
type="text"
class="field"
placeholder="Adres email"
ref="login_mail"
required
/>
<input type="password" class="field" placeholder="Hasło" ref="login_pass" required />
<button type="submit" class="field btn">
Zaloguj
</button>
</form>
<a href="/register" class="field">
Zarejestruj się
</a>
<a href="/login" class="field">
Nie pamiętam hasła
</a>
</div>
</div>
);
}
}
export default LoginView;
|
import React from 'react';
import { render } from '@testing-library/react';
import { useDispatch, useSelector } from 'react-redux';
import ToastManager from './ToastManager';
import { initToast } from '../state/commonSlice';
jest.mock('../services/storage');
jest.useFakeTimers();
describe('ToastManager', () => {
const dispatch = jest.fn();
useDispatch.mockImplementation(() => dispatch);
const message = '에러 메시지입니다.';
beforeEach(() => {
dispatch.mockClear();
useSelector.mockImplementation((selector) => selector({
common: {
toast: {
triggered: given.triggered,
message: given.message,
},
},
}));
});
context('when trigger is true', () => {
it('show toast', () => {
given('triggered', () => true);
given('message', () => message);
const { getByText } = render(<ToastManager />);
expect(getByText(message)).not.toBeNull();
setTimeout(() => {}, 1600);
jest.runAllTimers();
expect(dispatch).toBeCalledWith(initToast());
});
});
context('when trigger is false', () => {
it('show toast', () => {
given('triggered', () => false);
given('message', () => message);
const { queryByText } = render(<ToastManager />);
expect(queryByText(message)).toBeNull();
setTimeout(() => {}, 1600);
jest.runAllTimers();
expect(dispatch).not.toBeCalledWith(initToast());
});
});
});
|
// pages/discountGoods/discountGoods.js
Page({
data: {
array: ['全部分类','肉类'],
index:0,
array2: ['默认排序', '肉类'],
index2: 0,
array3: ['筛选', '肉类'],
index3: 0,
addnum:0,
},
onLoad: function (options) {
},
change: function (e) {
this.setData({
index: e.detail.value
})
},
change2: function (e) {
this.setData({
index2: e.detail.value
})
},
change3: function (e) {
this.setData({
index3: e.detail.value
})
},
addGood: function () {
var addnum = this.data.addnum;
addnum ++;
this.setData({
addnum: addnum,
})
wx.showToast({
title: '已加入购物车',
icon: 'success',
duration: 2000
})
}
}) |
import React, {Component} from 'react';
import {
View,
Text,
ImageBackground,
Image,
TouchableOpacity,
StyleSheet,
TextInput,
ScrollView,
StatusBar,
FlatList,
Dimensions
}
from 'react-native';
import mainStyle from '../src/styles/mainStyle';
import Constants from 'expo-constants';
export default class GiaHanTaiKhoan extends Component {
render(){
return(
<View style = {mainStyle.container}>
<View style = {mainStyle.header4}>
<View style = {mainStyle.buttonBack2} >
<TouchableOpacity onPress = {() => alert('Icon Back')}>
<Image source = {require('../assets/iconBack.png')} style = {{width:25, width:25, resizeMode:'contain',zIndex:1}}></Image>
</TouchableOpacity>
</View>
<View style = {mainStyle.containTextHeader2}>
<Text style = {mainStyle.textHeader2}>Gia hạn tài khoản</Text>
</View>
</View>
<View style = {mainStyle.body4}>
<View style = {mainStyle.body4_content1}>
<Image source = {require('../assets/iconThanhToan.png')} style = {{width:150 * standarWidth/width , height:150 * standarHeight/height, resizeMode:'cover'}}></Image>
</View>
<View style = {mainStyle.body4_content2}>
<View style = {mainStyle.body4_content2a}>
<Text style = {{fontWeight:'bold', fontSize:15}}>Chọn gói gia hạn tài khoản:</Text>
</View>
<View style = {mainStyle.body4_content2b}>
<View style = {{flexDirection:'row', justifyContent:'space-between'}}>
<TouchableOpacity style = {mainStyle.body4_content2b_1}>
<Text style = {{color:'white'}}>30 ngày</Text>
<Text style = {{color:'white'}}>500.000đ</Text>
</TouchableOpacity>
<TouchableOpacity style = {mainStyle.body4_content2b_2}>
<Text>60 ngày</Text>
<Text>900.000đ</Text>
</TouchableOpacity>
<TouchableOpacity style = {mainStyle.body4_content2b_2}>
<Text>90 ngày</Text>
<Text>1.350.000đ</Text>
</TouchableOpacity>
</View>
<View style = {{flexDirection:'row', justifyContent:'space-between', marginTop:15,}}>
<TouchableOpacity style = {mainStyle.body4_content2b_2}>
<Text>120 ngày</Text>
<Text>2.300.000đ</Text>
</TouchableOpacity>
<TouchableOpacity style = {mainStyle.body4_content2b_2}>
<Text>150 ngày</Text>
<Text>4.000.000đ</Text>
</TouchableOpacity>
<TouchableOpacity style = {mainStyle.body4_content2b_2}>
<Text>180 ngày</Text>
<Text>5.200.000đ</Text>
</TouchableOpacity>
</View>
</View>
<View style = {mainStyle.body4_content2c}>
<View style = {{flexDirection:'row', marginBottom:30}}>
<Text>Hiệu lực tài khoản: </Text>
<Text style = {{color:'red', fontWeight:'bold'}}>20 ngày</Text>
</View>
</View>
</View>
</View>
<View style = {mainStyle.footer5}>
<TouchableOpacity style = {{justifyContent:'center', alignItems:'center',height:'100%'}}>
<Text style = {{color:'#ffffff',fontSize:15,fontWeight:'bold'}}>THANH TOÁN</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
const {height, width} = Dimensions.get('window');
const standarWidth = 360;
const standarHeight = 592;
const textFontSize = 10/standarWidth * width;
const textName = 12/standarWidth * width; |
/**
* @namespace BMap的所有library类均放在BMapLib命名空间下
*/
var BMapLib = window.BMapLib = BMapLib || {};
( function () {
var getExtendedBounds = function ( map, bounds, gridSize ) {
bounds = cutBoundsInRange( bounds );
var pixelNE = map.pointToPixel( bounds.getNorthEast() );
var pixelSW = map.pointToPixel( bounds.getSouthWest() );
pixelNE.x += gridSize;
pixelNE.y -= gridSize;
pixelSW.x -= gridSize;
pixelSW.y += gridSize;
var newNE = map.pixelToPoint( pixelNE );
var newSW = map.pixelToPoint( pixelSW );
return new BMap.Bounds( newSW, newNE )
};
var cutBoundsInRange = function ( bounds ) {
var maxX = getRange( bounds.getNorthEast().lng, -180, 180 );
var minX = getRange( bounds.getSouthWest().lng, -180, 180 );
var maxY = getRange( bounds.getNorthEast().lat, -74, 74 );
var minY = getRange( bounds.getSouthWest().lat, -74, 74 );
return new BMap.Bounds( new BMap.Point( minX, minY ), new BMap.Point( maxX, maxY ) )
};
var getRange = function ( i, mix, max ) {
mix && ( i = Math.max( i, mix ) );
max && ( i = Math.min( i, max ) );
return i
};
var isArray = function ( source ) {
return "[object Array]" === Object.prototype.toString.call( source )
};
var indexOf = function ( item, source ) {
var index = -1;
if ( isArray( source ) ) {
if ( source.indexOf ) {
index = source.indexOf( item )
} else {
for ( var i = 0, m; m = source[i]; i++ ) {
if ( m === item ) {
index = i;
break
}
}
}
}
return index
};
var MarkerClusterer = BMapLib.MarkerClusterer = function ( map, options ) {
if ( !map ) {
return
}
this._map = map;
this._markers = [];
this._clusters = [];
var opts = options || {};
this._gridSize = opts.gridSize || 60;
this._maxZoom = opts.maxZoom || 18;
this._minClusterSize = opts.minClusterSize || 2;
this._isAverageCenter = false;
if ( opts.isAverageCenter != undefined ) {
this._isAverageCenter = opts.isAverageCenter
}
this._styles = opts.styles || [];
var that = this;
this._map.addEventListener( "zoomend",
function () {
that._redraw();
if ( that._infoWindowMarker ) {
var windowType = that._infoWindow.toString();
if ( windowType == "[object Overlay]" ) { } else {
if ( windowType == "[object InfoWindow]" ) {
that.showInfoWindowOnCluster( that._infoWindowMarker, that._infoWindow )
}
}
}
} );
this._map.addEventListener( "moveend",
function () {
that._redraw()
} );
this.clickCallback = opts.clickCallback || null;
this.clusterPopupMaker = opts.clusterPopupMaker || null;
this._oldSelectedCluster = null;
this._infoWindowMarker = null;
this._infoWindow = null;
this.timeoutHandler = null;
var mkrs = opts.markers;
isArray( mkrs ) && this.addMarkers( mkrs )
};
MarkerClusterer.prototype.addMarkers = function ( markers ) {
for ( var i = 0, len = markers.length; i < len; i++ ) {
this._pushMarkerTo( markers[i] )
}
this._createClusters()
};
MarkerClusterer.prototype._pushMarkerTo = function ( marker ) {
var index = indexOf( marker, this._markers );
if ( index === -1 ) {
marker.isInCluster = false;
this._markers.push( marker )
}
};
MarkerClusterer.prototype.addMarker = function ( marker ) {
this._pushMarkerTo( marker );
this._createClusters()
};
MarkerClusterer.prototype._createClusters = function () {
var mapBounds = this._map.getBounds();
var extendedBounds = getExtendedBounds( this._map, mapBounds, this._gridSize );
for ( var i = 0, marker; marker = this._markers[i]; i++ ) {
if ( !marker.isInCluster && extendedBounds.containsPoint( marker.getPosition() ) ) {
this._addToClosestCluster( marker )
}
}
};
MarkerClusterer.prototype._addToClosestCluster = function ( marker ) {
var distance = 4000000;
var clusterToAddTo = null;
var position = marker.getPosition();
for ( var i = 0, cluster; cluster = this._clusters[i]; i++ ) {
var center = cluster.getCenter();
if ( center ) {
var d = this._map.getDistance( center, marker.getPosition() );
if ( d < distance ) {
distance = d;
clusterToAddTo = cluster
}
}
}
if ( clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds( marker ) ) {
clusterToAddTo.addMarker( marker )
} else {
var cluster = new Cluster( this );
cluster.addMarker( marker );
this._clusters.push( cluster )
}
};
MarkerClusterer.prototype._clearLastClusters = function () {
for ( var i = 0, cluster; cluster = this._clusters[i]; i++ ) {
cluster.remove()
}
this._clusters = [];
this._removeMarkersFromCluster()
};
MarkerClusterer.prototype._removeMarkersFromCluster = function () {
for ( var i = 0, marker; marker = this._markers[i]; i++ ) {
marker.isInCluster = false
}
};
MarkerClusterer.prototype._removeMarkersFromMap = function () {
for ( var i = 0, marker; marker = this._markers[i]; i++ ) {
marker.isInCluster = false;
tmplabel = marker.getLabel();
this._map.removeOverlay( marker );
marker.setLabel( tmplabel )
}
};
MarkerClusterer.prototype._removeMarker = function ( marker ) {
var index = indexOf( marker, this._markers );
if ( index === -1 ) {
return false
}
tmplabel = marker.getLabel();
this._map.removeOverlay( marker );
marker.setLabel( tmplabel );
this._markers.splice( index, 1 );
return true
};
MarkerClusterer.prototype.removeMarker = function ( marker ) {
var success = this._removeMarker( marker );
if ( success ) {
this._clearLastClusters();
this._createClusters()
}
return success
};
MarkerClusterer.prototype.removeMarkers = function ( markers ) {
var success = false;
for ( var i = 0; i < markers.length; i++ ) {
var r = this._removeMarker( markers[i] );
success = success || r
}
if ( success ) {
this._clearLastClusters();
this._createClusters()
}
return success
};
MarkerClusterer.prototype.clearMarkers = function () {
this._clearLastClusters();
this._removeMarkersFromMap();
this._markers = []
};
MarkerClusterer.prototype._redraw = function () {
this._clearLastClusters();
this._createClusters()
};
MarkerClusterer.prototype.getGridSize = function () {
return this._gridSize
};
MarkerClusterer.prototype.setGridSize = function ( size ) {
this._gridSize = size;
this._redraw()
};
MarkerClusterer.prototype.getMaxZoom = function () {
return this._maxZoom
};
MarkerClusterer.prototype.setMaxZoom = function ( maxZoom ) {
this._maxZoom = maxZoom;
this._redraw()
};
MarkerClusterer.prototype.getStyles = function () {
return this._styles
};
MarkerClusterer.prototype.setStyles = function ( styles ) {
this._styles = styles;
this._redraw()
};
MarkerClusterer.prototype.getMinClusterSize = function () {
return this._minClusterSize
};
MarkerClusterer.prototype.setMinClusterSize = function ( size ) {
this._minClusterSize = size;
this._redraw()
};
MarkerClusterer.prototype.isAverageCenter = function () {
return this._isAverageCenter
};
MarkerClusterer.prototype.getMap = function () {
return this._map
};
MarkerClusterer.prototype.getMarkers = function () {
return this._markers
};
MarkerClusterer.prototype.getClustersCount = function () {
var count = 0;
for ( var i = 0, cluster; cluster = this._clusters[i]; i++ ) {
cluster.isReal() && count++
}
return count
};
MarkerClusterer.prototype.getContainerCluster = function ( marker ) {
var contrainerCluster = null;
for ( var i = 0, cluster; cluster = this._clusters[i]; i++ ) {
if ( cluster.isMarkerInCluster( marker ) && cluster._isReal ) {
contrainerCluster = cluster;
break
}
}
return contrainerCluster
};
MarkerClusterer.prototype.showInfoWindowOnCluster = function ( marker, infoWindow ) {
if ( !marker ) {
return
}
var cluster = this.getContainerCluster( marker );
var point = null;
var windowType = infoWindow.toString();
if ( cluster ) {
point = cluster.getCenter();
if ( windowType == "[object Overlay]" ) {
infoWindow.open( point )
} else {
if ( windowType == "[object InfoWindow]" ) {
this._map.openInfoWindow( infoWindow, point )
}
}
this._infoWindowMarker = marker;
this._infoWindow = infoWindow;
if ( this.timeoutHandler ) {
clearTimeout( this.timeoutHandler );
this.timeoutHandler = null
}
this._map.setCenter( point )
} else {
if ( windowType == "[object Overlay]" ) {
infoWindow.close()
} else {
if ( windowType == "[object InfoWindow]" ) {
this._map.closeInfoWindow()
}
}
if ( marker ) {
this._map.setCenter( marker.getPosition() )
}
var that = this;
this.timeoutHandler = setTimeout( function () {
that._infoWindowMarker = null;
that._infoWindow = null
},
500 )
}
};
MarkerClusterer.prototype.destroyInfoWindow = function () {
this._infoWindowMarker = null;
this._infoWindow = null
};
MarkerClusterer.prototype.makeClusterSelected = function ( marker ) {
if ( this._oldSelectedCluster ) { }
var cluster = this.getContainerCluster( marker );
if ( cluster ) { }
};
function Cluster( markerClusterer ) {
this._markerClusterer = markerClusterer;
this._map = markerClusterer.getMap();
this._minClusterSize = markerClusterer.getMinClusterSize();
this._isAverageCenter = markerClusterer.isAverageCenter();
this._center = null;
this._markers = [];
this._gridBounds = null;
this._isReal = false;
this._clusterMarker = new BMapLib.TextIconOverlay( this._center, this._markers.length, {
styles: this._markerClusterer.getStyles()
} )
}
Cluster.prototype.addMarker = function ( marker ) {
if ( this.isMarkerInCluster( marker ) ) {
return false
}
if ( !this._center ) {
this._center = marker.getPosition();
this.updateGridBounds()
} else {
if ( this._isAverageCenter ) {
var l = this._markers.length + 1;
var lat = ( this._center.lat * ( l - 1 ) + marker.getPosition().lat ) / l;
var lng = ( this._center.lng * ( l - 1 ) + marker.getPosition().lng ) / l;
this._center = new BMap.Point( lng, lat );
this.updateGridBounds()
}
}
marker.isInCluster = true;
this._markers.push( marker );
var len = this._markers.length;
if ( len < this._minClusterSize ) {
this._map.addOverlay( marker );
return true
} else {
if ( len === this._minClusterSize ) {
for ( var i = 0; i < len; i++ ) {
tmplabel = this._markers[i].getLabel();
this._markers[i].getMap() && this._map.removeOverlay( this._markers[i] );
this._markers[i].setLabel( tmplabel )
}
}
}
this._map.addOverlay( this._clusterMarker );
this._isReal = true;
this.updateClusterMarker();
return true
};
Cluster.prototype.isMarkerInCluster = function ( marker ) {
if ( this._markers.indexOf ) {
return this._markers.indexOf( marker ) != -1
} else {
for ( var i = 0, m; m = this._markers[i]; i++ ) {
if ( m === marker ) {
return true
}
}
}
return false
};
Cluster.prototype.isMarkerInClusterBounds = function ( marker ) {
return this._gridBounds.containsPoint( marker.getPosition() )
};
Cluster.prototype.isReal = function ( marker ) {
return this._isReal
};
Cluster.prototype.updateGridBounds = function () {
var bounds = new BMap.Bounds( this._center, this._center );
this._gridBounds = getExtendedBounds( this._map, bounds, this._markerClusterer.getGridSize() )
};
Cluster.prototype.updateClusterMarker = function () {
if ( this._map.getZoom() > this._markerClusterer.getMaxZoom() ) {
this._clusterMarker && this._map.removeOverlay( this._clusterMarker );
for ( var i = 0, marker; marker = this._markers[i]; i++ ) {
this._map.addOverlay( marker )
}
return
}
if ( this._markers.length < this._minClusterSize ) {
this._clusterMarker.hide();
return
}
if ( this._markerClusterer.clusterPopupMaker ) {
var pois = [];
for ( var i = 0; i < this._markers.length; i++ ) {
pois.push( this._markers[i].poi )
}
var popup = this._markerClusterer.clusterPopupMaker( pois );
var infoWindowOpt = {};
if ( popup.size ) {
infoWindowOpt.width = popup.size.w;
infoWindowOpt.height = popup.size.h
}
if ( popup.offset ) {
infoWindowOpt.offset = new BMap.Size( popup.offset.x, popup.offset.y )
}
infoWindowOpt.enableMessage = false;
var clusterInfoWindow = new BMap.InfoWindow( popup.content, infoWindowOpt );
this._clusterMarker.addEventListener( "mouseover",
function () {
this._map.openInfoWindow( clusterInfoWindow, this.getPosition() )
} );
this._clusterMarker.addEventListener( "mouseout",
function () {
this._map.closeInfoWindow()
} )
}
this._clusterMarker.setPosition( this._center );
this._clusterMarker.setText( this._markers.length );
var thatMap = this._map;
var thatBounds = this.getBounds();
var that = this;
this._clusterMarker.addEventListener( "click",
function ( event ) {
thatMap.setViewport( thatBounds )
} )
};
Cluster.prototype.remove = function () {
for ( var i = 0, m; m = this._markers[i]; i++ ) {
var tmplabel = this._markers[i].getLabel();
this._markers[i].getMap() && this._map.removeOverlay( this._markers[i] );
this._markers[i].setLabel( tmplabel )
}
this._map.removeOverlay( this._clusterMarker );
this._markers.length = 0;
delete this._markers
};
Cluster.prototype.getBounds = function () {
var bounds = new BMap.Bounds( this._center, this._center );
for ( var i = 0, marker; marker = this._markers[i]; i++ ) {
bounds.extend( marker.getPosition() )
}
return bounds
};
Cluster.prototype.getCenter = function () {
return this._center
}
} )();
( function () {
var BMAP_ZOOM_IN = 0;
var BMAP_ZOOM_OUT = 1;
var RectangleZoom = BMapLib.RectangleZoom = function ( map, opts ) {
if ( !map ) {
return
}
this._map = map;
this._opts = {
zoomType: BMAP_ZOOM_IN,
followText: "",
strokeWeight: 2,
strokeColor: "#111",
style: "solid",
fillColor: "#ccc",
opacity: 0.4,
cursor: "crosshair",
autoClose: false
};
this._setOptions( opts );
this._opts.strokeWeight = this._opts.strokeWeight <= 0 ? 1 : this._opts.strokeWeight;
this._opts.opacity = this._opts.opacity < 0 ? 0 : this._opts.opacity > 1 ? 1 : this._opts.opacity;
if ( this._opts.zoomType < BMAP_ZOOM_IN || this._opts.zoomType > BMAP_ZOOM_OUT ) {
this._opts.zoomType = BMAP_ZOOM_IN
}
this._isOpen = false;
this._fDiv = null;
this._followTitle = null
};
RectangleZoom.prototype._setOptions = function ( opts ) {
if ( !opts ) {
return
}
for ( var p in opts ) {
if ( typeof ( opts[p] ) != "undefined" ) {
this._opts[p] = opts[p]
}
}
};
RectangleZoom.prototype.setStrokeColor = function ( color ) {
if ( typeof color == "string" ) {
this._opts.strokeColor = color;
this._updateStyle()
}
};
RectangleZoom.prototype.setLineStroke = function ( width ) {
if ( typeof width == "number" && Math.round( width ) > 0 ) {
this._opts.strokeWeight = Math.round( width );
this._updateStyle()
}
};
RectangleZoom.prototype.setLineStyle = function ( style ) {
if ( style == "solid" || style == "dashed" ) {
this._opts.style = style;
this._updateStyle()
}
};
RectangleZoom.prototype.setOpacity = function ( opacity ) {
if ( typeof opacity == "number" && opacity >= 0 && opacity <= 1 ) {
this._opts.opacity = opacity;
this._updateStyle()
}
};
RectangleZoom.prototype.setFillColor = function ( color ) {
this._opts.fillColor = color;
this._updateStyle()
};
RectangleZoom.prototype.setCursor = function ( cursor ) {
this._opts.cursor = cursor;
OperationMask.setCursor( this._opts.cursor )
};
RectangleZoom.prototype._updateStyle = function () {
if ( this._fDiv ) {
this._fDiv.style.border = [this._opts.strokeWeight, "px ", this._opts.style, " ", this._opts.color].join( "" );
var st = this._fDiv.style,
op = this._opts.opacity;
st.opacity = op;
st.MozOpacity = op;
st.KhtmlOpacity = op;
st.filter = "alpha(opacity=" + ( op * 100 ) + ")"
}
};
RectangleZoom.prototype.getCursor = function () {
return this._opts.cursor
};
RectangleZoom.prototype._bind = function () {
this.setCursor( this._opts.cursor );
var me = this;
addEvent( this._map.getContainer(), "mousemove",
function ( e ) {
if ( !me._isOpen ) {
return
}
if ( !me._followTitle ) {
return
}
e = window.event || e;
var t = e.target || e.srcElement;
if ( t != OperationMask.getDom( me._map ) ) {
me._followTitle.hide();
return
}
if ( !me._mapMoving ) {
me._followTitle.show()
}
var pt = OperationMask.getDrawPoint( e, true );
me._followTitle.setPosition( pt )
} );
if ( this._opts.followText ) {
var t = this._followTitle = new BMap.Label( this._opts.followText, {
offset: new BMap.Size( 14, 16 )
} );
this._followTitle.setStyles( {
color: "#333",
borderColor: "#ff0103"
} )
}
};
RectangleZoom.prototype.open = function () {
if ( this._isOpen == true ) {
return true
}
if ( !!BMapLib._toolInUse ) {
return
}
this._isOpen = true;
BMapLib._toolInUse = true;
if ( !this.binded ) {
this._bind();
this.binded = true
}
if ( this._followTitle ) {
this._map.addOverlay( this._followTitle );
this._followTitle.hide()
}
var me = this;
var map = this._map;
var ieVersion = 0;
if ( /msie (\d+\.\d)/i.test( navigator.userAgent ) ) {
ieVersion = document.documentMode || +RegExp["\x241"]
}
var beginDrawRect = function ( e ) {
e = window.event || e;
if ( e.button != 0 && !ieVersion || ieVersion && e.button != 1 ) {
return
}
if ( !!ieVersion && OperationMask.getDom( map ).setCapture ) {
OperationMask.getDom( map ).setCapture()
}
if ( !me._isOpen ) {
return
}
me._bind.isZooming = true;
addEvent( document, "mousemove", drawingRect );
addEvent( document, "mouseup", endDrawRect );
me._bind.mx = e.layerX || e.offsetX || 0;
me._bind.my = e.layerY || e.offsetY || 0;
me._bind.ix = e.pageX || e.clientX || 0;
me._bind.iy = e.pageY || e.clientY || 0;
insertHTML( OperationMask.getDom( map ), "beforeBegin", me._generateHTML() );
me._fDiv = OperationMask.getDom( map ).previousSibling;
me._fDiv.style.width = "0";
me._fDiv.style.height = "0";
me._fDiv.style.left = me._bind.mx + "px";
me._fDiv.style.top = me._bind.my + "px";
stopBubble( e );
return preventDefault( e )
};
var drawingRect = function ( e ) {
if ( me._isOpen == true && me._bind.isZooming == true ) {
var e = window.event || e;
var curX = e.pageX || e.clientX || 0;
var curY = e.pageY || e.clientY || 0;
var dx = me._bind.dx = curX - me._bind.ix;
var dy = me._bind.dy = curY - me._bind.iy;
var tw = Math.abs( dx ) - me._opts.strokeWeight;
var th = Math.abs( dy ) - me._opts.strokeWeight;
me._fDiv.style.width = ( tw < 0 ? 0 : tw ) + "px";
me._fDiv.style.height = ( th < 0 ? 0 : th ) + "px";
var mapSize = [map.getSize().width, map.getSize().height];
if ( dx >= 0 ) {
me._fDiv.style.right = "auto";
me._fDiv.style.left = me._bind.mx + "px";
if ( me._bind.mx + dx >= mapSize[0] - 2 * me._opts.strokeWeight ) {
me._fDiv.style.width = mapSize[0] - me._bind.mx - 2 * me._opts.strokeWeight + "px";
me._followTitle && me._followTitle.hide()
}
} else {
me._fDiv.style.left = "auto";
me._fDiv.style.right = mapSize[0] - me._bind.mx + "px";
if ( me._bind.mx + dx <= 2 * me._opts.strokeWeight ) {
me._fDiv.style.width = me._bind.mx - 2 * me._opts.strokeWeight + "px";
me._followTitle && me._followTitle.hide()
}
}
if ( dy >= 0 ) {
me._fDiv.style.bottom = "auto";
me._fDiv.style.top = me._bind.my + "px";
if ( me._bind.my + dy >= mapSize[1] - 2 * me._opts.strokeWeight ) {
me._fDiv.style.height = mapSize[1] - me._bind.my - 2 * me._opts.strokeWeight + "px";
me._followTitle && me._followTitle.hide()
}
} else {
me._fDiv.style.top = "auto";
me._fDiv.style.bottom = mapSize[1] - me._bind.my + "px";
if ( me._bind.my + dy <= 2 * me._opts.strokeWeight ) {
me._fDiv.style.height = me._bind.my - 2 * me._opts.strokeWeight + "px";
me._followTitle && me._followTitle.hide()
}
}
stopBubble( e );
return preventDefault( e )
}
};
var endDrawRect = function ( e ) {
if ( me._isOpen == true ) {
removeEvent( document, "mousemove", drawingRect );
removeEvent( document, "mouseup", endDrawRect );
if ( !!ieVersion && OperationMask.getDom( map ).releaseCapture ) {
OperationMask.getDom( map ).releaseCapture()
}
var centerX = parseInt( me._fDiv.style.left ) + parseInt( me._fDiv.style.width ) / 2;
var centerY = parseInt( me._fDiv.style.top ) + parseInt( me._fDiv.style.height ) / 2;
var mapSize = [map.getSize().width, map.getSize().height];
if ( isNaN( centerX ) ) {
centerX = mapSize[0] - parseInt( me._fDiv.style.right ) - parseInt( me._fDiv.style.width ) / 2
}
if ( isNaN( centerY ) ) {
centerY = mapSize[1] - parseInt( me._fDiv.style.bottom ) - parseInt( me._fDiv.style.height ) / 2
}
var ratio = Math.min( mapSize[0] / Math.abs( me._bind.dx ), mapSize[1] / Math.abs( me._bind.dy ) );
ratio = Math.floor( ratio );
var px1 = new BMap.Pixel( centerX - parseInt( me._fDiv.style.width ) / 2, centerY - parseInt( me._fDiv.style.height ) / 2 );
var px2 = new BMap.Pixel( centerX + parseInt( me._fDiv.style.width ) / 2, centerY + parseInt( me._fDiv.style.height ) / 2 );
if ( px1.x == px2.x && px1.y == px2.y ) {
me._bind.isZooming = false;
me._fDiv.parentNode.removeChild( me._fDiv );
me._fDiv = null;
return
}
var pt1 = map.pixelToPoint( px1 );
var pt2 = map.pixelToPoint( px2 );
var bds = new BMap.Bounds( pt1, pt2 );
delete me._bind.dx;
delete me._bind.dy;
delete me._bind.ix;
delete me._bind.iy;
if ( !isNaN( ratio ) ) {
if ( me._opts.zoomType == BMAP_ZOOM_IN ) {
targetZoomLv = Math.round( map.getZoom() + ( Math.log( ratio ) / Math.log( 2 ) ) );
if ( targetZoomLv < map.getZoom() ) {
targetZoomLv = map.getZoom()
}
} else {
targetZoomLv = Math.round( map.getZoom() + ( Math.log( 1 / ratio ) / Math.log( 2 ) ) );
if ( targetZoomLv > map.getZoom() ) {
targetZoomLv = map.getZoom()
}
}
} else {
targetZoomLv = map.getZoom() + ( me._opts.zoomType == BMAP_ZOOM_IN ? 1 : -1 )
}
var targetCenterPt = map.pixelToPoint( {
x: centerX,
y: centerY
},
map.getZoom() );
map.centerAndZoom( targetCenterPt, targetZoomLv );
var pt = OperationMask.getDrawPoint( e );
if ( me._followTitle ) {
me._followTitle.setPosition( pt );
me._followTitle.show()
}
me._bind.isZooming = false;
me._fDiv.parentNode.removeChild( me._fDiv );
me._fDiv = null
}
var southWestPoint = bds.getSouthWest(),
northEastPoint = bds.getNorthEast(),
southEastPoint = new BMap.Point( northEastPoint.lng, southWestPoint.lat ),
northWestPoint = new BMap.Point( southWestPoint.lng, northEastPoint.lat ),
rect = new BMap.Polygon( [southWestPoint, northWestPoint, northEastPoint, southEastPoint] );
rect.setStrokeWeight( 2 );
rect.setStrokeOpacity( 0.3 );
rect.setStrokeColor( "#111" );
rect.setFillColor( "" );
map.addOverlay( rect );
new Animation( {
duration: 240,
fps: 20,
delay: 500,
render: function ( t ) {
var opacity = 0.3 * ( 1 - t );
rect.setStrokeOpacity( opacity )
},
finish: function () {
map.removeOverlay( rect );
rect = null
}
} );
if ( me._opts.autoClose ) {
setTimeout( function () {
if ( me._isOpen == true ) {
me.close()
}
},
70 )
}
stopBubble( e );
return preventDefault( e )
};
OperationMask.show( this._map );
this.setCursor( this._opts.cursor );
if ( !this._isBeginDrawBinded ) {
addEvent( OperationMask.getDom( this._map ), "mousedown", beginDrawRect );
this._isBeginDrawBinded = true
}
return true
};
RectangleZoom.prototype.close = function () {
if ( !this._isOpen ) {
return
}
this._isOpen = false;
BMapLib._toolInUse = false;
this._followTitle && this._followTitle.hide();
OperationMask.hide()
};
RectangleZoom.prototype._generateHTML = function () {
return ["<div style='position:absolute;z-index:300;border:", this._opts.strokeWeight, "px ", this._opts.style, " ", this._opts.strokeColor, "; opacity:", this._opts.opacity, "; background: ", this._opts.fillColor, "; filter:alpha(opacity=", Math.round( this._opts.opacity * 100 ), "); width:0; height:0; font-size:0'></div>"].join( "" )
};
function insertHTML( element, position, html ) {
var range,
begin;
if ( element.insertAdjacentHTML ) {
element.insertAdjacentHTML( position, html )
} else {
range = element.ownerDocument.createRange();
position = position.toUpperCase();
if ( position == "AFTERBEGIN" || position == "BEFOREEND" ) {
range.selectNodeContents( element );
range.collapse( position == "AFTERBEGIN" )
} else {
begin = position == "BEFOREBEGIN";
range[begin ? "setStartBefore" : "setEndAfter"]( element );
range.collapse( begin )
}
range.insertNode( range.createContextualFragment( html ) )
}
return element
}
function beforeEndHTML( parent, chlidHTML ) {
insertHTML( parent, "beforeEnd", chlidHTML );
return parent.lastChild
}
function stopBubble( e ) {
var e = window.event || e;
e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true
}
function preventDefault( e ) {
var e = window.event || e;
e.preventDefault ? e.preventDefault() : e.returnValue = false;
return false
}
function addEvent( element, type, listener ) {
if ( !element ) {
return
}
type = type.replace( /^on/i, "" ).toLowerCase();
if ( element.addEventListener ) {
element.addEventListener( type, listener, false )
} else {
if ( element.attachEvent ) {
element.attachEvent( "on" + type, listener )
}
}
}
function removeEvent( element, type, listener ) {
if ( !element ) {
return
}
type = type.replace( /^on/i, "" ).toLowerCase();
if ( element.removeEventListener ) {
element.removeEventListener( type, listener, false )
} else {
if ( element.detachEvent ) {
element.detachEvent( "on" + type, listener )
}
}
}
var OperationMask = {
_map: null,
_html: "<div style='background:transparent url(http://api.map.baidu.com/images/blank.gif);position:absolute;left:0;top:0;width:100%;height:100%;z-index:1000' unselectable='on'></div>",
_maskElement: null,
_cursor: "default",
_inUse: false,
show: function ( map ) {
if ( !this._map ) {
this._map = map
}
this._inUse = true;
if ( !this._maskElement ) {
this._createMask( map )
}
this._maskElement.style.display = "block"
},
_createMask: function ( map ) {
this._map = map;
if ( !this._map ) {
return
}
var elem = this._maskElement = beforeEndHTML( this._map.getContainer(), this._html );
var stopAndPrevent = function ( e ) {
stopBubble( e );
return preventDefault( e )
};
addEvent( elem, "mouseup",
function ( e ) {
if ( e.button == 2 ) {
stopAndPrevent( e )
}
} );
addEvent( elem, "contextmenu", stopAndPrevent );
elem.style.display = "none"
},
getDrawPoint: function ( e, n ) {
e = window.event || e;
var x = e.layerX || e.offsetX || 0;
var y = e.layerY || e.offsetY || 0;
var t = e.target || e.srcElement;
if ( t != OperationMask.getDom( this._map ) && n == true ) {
while ( t && t != this._map.getContainer() ) {
if ( !( t.clientWidth == 0 && t.clientHeight == 0 && t.offsetParent && t.offsetParent.nodeName.toLowerCase() == "td" ) ) {
x += t.offsetLeft;
y += t.offsetTop
}
t = t.offsetParent
}
}
if ( t != OperationMask.getDom( this._map ) && t != this._map.getContainer() ) {
return
}
if ( typeof x === "undefined" || typeof y === "undefined" ) {
return
}
if ( isNaN( x ) || isNaN( y ) ) {
return
}
return this._map.pixelToPoint( new BMap.Pixel( x, y ) )
},
hide: function () {
if ( !this._map ) {
return
}
this._inUse = false;
if ( this._maskElement ) {
this._maskElement.style.display = "none"
}
},
getDom: function ( map ) {
if ( !this._maskElement ) {
this._createMask( map )
}
return this._maskElement
},
setCursor: function ( cursor ) {
this._cursor = cursor || "default";
if ( this._maskElement ) {
this._maskElement.style.cursor = this._cursor
}
}
};
function Animation( opts ) {
var defaultOptions = {
duration: 1000,
fps: 30,
delay: 0,
transition: Transitions.linear,
onStop: function () { }
};
if ( opts ) {
for ( var i in opts ) {
defaultOptions[i] = opts[i]
}
}
this._opts = defaultOptions;
if ( defaultOptions.delay ) {
var me = this;
setTimeout( function () {
me._beginTime = new Date().getTime();
me._endTime = me._beginTime + me._opts.duration;
me._launch()
},
defaultOptions.delay )
} else {
this._beginTime = new Date().getTime();
this._endTime = this._beginTime + this._opts.duration;
this._launch()
}
}
Animation.prototype._launch = function () {
var me = this;
var now = new Date().getTime();
if ( now >= me._endTime ) {
if ( typeof me._opts.render == "function" ) {
me._opts.render( me._opts.transition( 1 ) )
}
if ( typeof me._opts.finish == "function" ) {
me._opts.finish()
}
return
}
me.schedule = me._opts.transition(( now - me._beginTime ) / me._opts.duration );
if ( typeof me._opts.render == "function" ) {
me._opts.render( me.schedule )
}
if ( !me.terminative ) {
me._timer = setTimeout( function () {
me._launch()
},
1000 / me._opts.fps )
}
};
var Transitions = {
linear: function ( t ) {
return t
},
reverse: function ( t ) {
return 1 - t
},
easeInQuad: function ( t ) {
return t * t
},
easeInCubic: function ( t ) {
return Math.pow( t, 3 )
},
easeOutQuad: function ( t ) {
return -( t * ( t - 2 ) )
},
easeOutCubic: function ( t ) {
return Math.pow(( t - 1 ), 3 ) + 1
},
easeInOutQuad: function ( t ) {
if ( t < 0.5 ) {
return t * t * 2
} else {
return -2 * ( t - 2 ) * t - 1
}
},
easeInOutCubic: function ( t ) {
if ( t < 0.5 ) {
return Math.pow( t, 3 ) * 4
} else {
return Math.pow( t - 1, 3 ) * 4 + 1
}
},
easeInOutSine: function ( t ) {
return ( 1 - Math.cos( Math.PI * t ) ) / 2
}
}
} )();
/**
* @fileoverview 百度地图的鼠标绘制工具,对外开放。
* 允许用户在地图上点击完成鼠标绘制的功能。
* 使用者可以自定义所绘制结果的相关样式,例如线宽、颜色、测线段距离、面积等等。
* 主入口类是<a href="symbols/BMapLib.DrawingManager.html">DrawingManager</a>,
* 基于Baidu Map API 1.4。
*
* @author Baidu Map Api Group
* @version 1.4
* 绘制的矩形和多边形增加关闭按钮 @20140429 by wutiansheng
*/
/**
* 定义常量, 绘制的模式
* @final {Number} DrawingType
*/
var BMAP_DRAWING_MARKER = "marker", // 鼠标画点模式
BMAP_DRAWING_POLYLINE = "polyline", // 鼠标画线模式
BMAP_DRAWING_CIRCLE = "circle", // 鼠标画圆模式
BMAP_DRAWING_RECTANGLE = "rectangle", // 鼠标画矩形模式
BMAP_DRAWING_POLYGON = "polygon"; // 鼠标画多边形模式
( function () {
/**
* 声明baidu包
*/
var baidu = baidu || { guid: "$BAIDU$" };
( function () {
// 一些页面级别唯一的属性,需要挂载在window[baidu.guid]上
window[baidu.guid] = {};
/**
* 将源对象的所有属性拷贝到目标对象中
* @name baidu.extend
* @function
* @grammar baidu.extend(target, source)
* @param {Object} target 目标对象
* @param {Object} source 源对象
* @returns {Object} 目标对象
*/
baidu.extend = function ( target, source ) {
for ( var p in source ) {
if ( source.hasOwnProperty( p ) ) {
target[p] = source[p];
}
}
return target;
};
/**
* @ignore
* @namespace
* @baidu.lang 对语言层面的封装,包括类型判断、模块扩展、继承基类以及对象自定义事件的支持。
* @property guid 对象的唯一标识
*/
baidu.lang = baidu.lang || {};
/**
* 返回一个当前页面的唯一标识字符串。
* @function
* @grammar baidu.lang.guid()
* @returns {String} 当前页面的唯一标识字符串
*/
baidu.lang.guid = function () {
return "TANGRAM__" + ( window[baidu.guid]._counter++ ).toString( 36 );
};
window[baidu.guid]._counter = window[baidu.guid]._counter || 1;
/**
* 所有类的实例的容器
* key为每个实例的guid
*/
window[baidu.guid]._instances = window[baidu.guid]._instances || {};
/**
* Tangram继承机制提供的一个基类,用户可以通过继承baidu.lang.Class来获取它的属性及方法。
* @function
* @name baidu.lang.Class
* @grammar baidu.lang.Class(guid)
* @param {string} guid 对象的唯一标识
* @meta standard
* @remark baidu.lang.Class和它的子类的实例均包含一个全局唯一的标识guid。
* guid是在构造函数中生成的,因此,继承自baidu.lang.Class的类应该直接或者间接调用它的构造函数。<br>
* baidu.lang.Class的构造函数中产生guid的方式可以保证guid的唯一性,及每个实例都有一个全局唯一的guid。
*/
baidu.lang.Class = function ( guid ) {
this.guid = guid || baidu.lang.guid();
window[baidu.guid]._instances[this.guid] = this;
};
window[baidu.guid]._instances = window[baidu.guid]._instances || {};
/**
* 判断目标参数是否string类型或String对象
* @name baidu.lang.isString
* @function
* @grammar baidu.lang.isString(source)
* @param {Any} source 目标参数
* @shortcut isString
* @meta standard
*
* @returns {boolean} 类型判断结果
*/
baidu.lang.isString = function ( source ) {
return '[object String]' == Object.prototype.toString.call( source );
};
/**
* 判断目标参数是否为function或Function实例
* @name baidu.lang.isFunction
* @function
* @grammar baidu.lang.isFunction(source)
* @param {Any} source 目标参数
* @returns {boolean} 类型判断结果
*/
baidu.lang.isFunction = function ( source ) {
return '[object Function]' == Object.prototype.toString.call( source );
};
/**
* 重载了默认的toString方法,使得返回信息更加准确一些。
* @return {string} 对象的String表示形式
*/
baidu.lang.Class.prototype.toString = function () {
return "[object " + ( this._className || "Object" ) + "]";
};
/**
* 释放对象所持有的资源,主要是自定义事件。
* @name dispose
* @grammar obj.dispose()
*/
baidu.lang.Class.prototype.dispose = function () {
delete window[baidu.guid]._instances[this.guid];
for ( var property in this ) {
if ( !baidu.lang.isFunction( this[property] ) ) {
delete this[property];
}
}
this.disposed = true;
};
/**
* 自定义的事件对象。
* @function
* @name baidu.lang.Event
* @grammar baidu.lang.Event(type[, target])
* @param {string} type 事件类型名称。为了方便区分事件和一个普通的方法,事件类型名称必须以"on"(小写)开头。
* @param {Object} [target]触发事件的对象
* @meta standard
* @remark 引入该模块,会自动为Class引入3个事件扩展方法:addEventListener、removeEventListener和dispatchEvent。
* @see baidu.lang.Class
*/
baidu.lang.Event = function ( type, target ) {
this.type = type;
this.returnValue = true;
this.target = target || null;
this.currentTarget = null;
};
/**
* 注册对象的事件监听器。引入baidu.lang.Event后,Class的子类实例才会获得该方法。
* @grammar obj.addEventListener(type, handler[, key])
* @param {string} type 自定义事件的名称
* @param {Function} handler 自定义事件被触发时应该调用的回调函数
* @param {string} [key] 为事件监听函数指定的名称,可在移除时使用。如果不提供,方法会默认为它生成一个全局唯一的key。
* @remark 事件类型区分大小写。如果自定义事件名称不是以小写"on"开头,该方法会给它加上"on"再进行判断,即"click"和"onclick"会被认为是同一种事件。
*/
baidu.lang.Class.prototype.addEventListener = function ( type, handler, key ) {
if ( !baidu.lang.isFunction( handler ) ) {
return;
}
!this.__listeners && ( this.__listeners = {} );
var t = this.__listeners, id;
if ( typeof key == "string" && key ) {
if ( /[^\w\-]/.test( key ) ) {
throw ( "nonstandard key:" + key );
} else {
handler.hashCode = key;
id = key;
}
}
type.indexOf( "on" ) != 0 && ( type = "on" + type );
typeof t[type] != "object" && ( t[type] = {} );
id = id || baidu.lang.guid();
handler.hashCode = id;
t[type][id] = handler;
};
/**
* 移除对象的事件监听器。引入baidu.lang.Event后,Class的子类实例才会获得该方法。
* @grammar obj.removeEventListener(type, handler)
* @param {string} type 事件类型
* @param {Function|string} handler 要移除的事件监听函数或者监听函数的key
* @remark 如果第二个参数handler没有被绑定到对应的自定义事件中,什么也不做。
*/
baidu.lang.Class.prototype.removeEventListener = function ( type, handler ) {
if ( baidu.lang.isFunction( handler ) ) {
handler = handler.hashCode;
} else if ( !baidu.lang.isString( handler ) ) {
return;
}
!this.__listeners && ( this.__listeners = {} );
type.indexOf( "on" ) != 0 && ( type = "on" + type );
var t = this.__listeners;
if ( !t[type] ) {
return;
}
t[type][handler] && delete t[type][handler];
};
/**
* 派发自定义事件,使得绑定到自定义事件上面的函数都会被执行。引入baidu.lang.Event后,Class的子类实例才会获得该方法。
* @grammar obj.dispatchEvent(event, options)
* @param {baidu.lang.Event|String} event Event对象,或事件名称(1.1.1起支持)
* @param {Object} options 扩展参数,所含属性键值会扩展到Event对象上(1.2起支持)
* @remark 处理会调用通过addEventListenr绑定的自定义事件回调函数之外,还会调用直接绑定到对象上面的自定义事件。
* 例如:<br>
* myobj.onMyEvent = function(){}<br>
* myobj.addEventListener("onMyEvent", function(){});
*/
baidu.lang.Class.prototype.dispatchEvent = function ( event, options ) {
if ( baidu.lang.isString( event ) ) {
event = new baidu.lang.Event( event );
}
!this.__listeners && ( this.__listeners = {} );
options = options || {};
for ( var i in options ) {
event[i] = options[i];
}
var i, t = this.__listeners, p = event.type;
event.target = event.target || this;
event.currentTarget = this;
p.indexOf( "on" ) != 0 && ( p = "on" + p );
baidu.lang.isFunction( this[p] ) && this[p].apply( this, arguments );
if ( typeof t[p] == "object" ) {
for ( i in t[p] ) {
t[p][i].apply( this, arguments );
}
}
return event.returnValue;
};
/**
* 为类型构造器建立继承关系
* @name baidu.lang.inherits
* @function
* @grammar baidu.lang.inherits(subClass, superClass[, className])
* @param {Function} subClass 子类构造器
* @param {Function} superClass 父类构造器
* @param {string} className 类名标识
* @remark 使subClass继承superClass的prototype,
* 因此subClass的实例能够使用superClass的prototype中定义的所有属性和方法。<br>
* 这个函数实际上是建立了subClass和superClass的原型链集成,并对subClass进行了constructor修正。<br>
* <strong>注意:如果要继承构造函数,需要在subClass里面call一下,具体见下面的demo例子</strong>
* @shortcut inherits
* @meta standard
* @see baidu.lang.Class
*/
baidu.lang.inherits = function ( subClass, superClass, className ) {
var key, proto,
selfProps = subClass.prototype,
clazz = new Function();
clazz.prototype = superClass.prototype;
proto = subClass.prototype = new clazz();
for ( key in selfProps ) {
proto[key] = selfProps[key];
}
subClass.prototype.constructor = subClass;
subClass.superClass = superClass.prototype;
if ( "string" == typeof className ) {
proto._className = className;
}
};
/**
* @ignore
* @namespace baidu.dom 操作dom的方法。
*/
baidu.dom = baidu.dom || {};
/**
* 从文档中获取指定的DOM元素
*
* @param {string|HTMLElement} id 元素的id或DOM元素
* @meta standard
* @return {HTMLElement} DOM元素,如果不存在,返回null,如果参数不合法,直接返回参数
*/
baidu._g = baidu.dom._g = function ( id ) {
if ( baidu.lang.isString( id ) ) {
return document.getElementById( id );
}
return id;
};
/**
* 从文档中获取指定的DOM元素
* @name baidu.dom.g
* @function
* @grammar baidu.dom.g(id)
* @param {string|HTMLElement} id 元素的id或DOM元素
* @meta standard
*
* @returns {HTMLElement|null} 获取的元素,查找不到时返回null,如果参数不合法,直接返回参数
*/
baidu.g = baidu.dom.g = function ( id ) {
if ( 'string' == typeof id || id instanceof String ) {
return document.getElementById( id );
} else if ( id && id.nodeName && ( id.nodeType == 1 || id.nodeType == 9 ) ) {
return id;
}
return null;
};
/**
* 在目标元素的指定位置插入HTML代码
* @name baidu.dom.insertHTML
* @function
* @grammar baidu.dom.insertHTML(element, position, html)
* @param {HTMLElement|string} element 目标元素或目标元素的id
* @param {string} position 插入html的位置信息,取值为beforeBegin,afterBegin,beforeEnd,afterEnd
* @param {string} html 要插入的html
* @remark
*
* 对于position参数,大小写不敏感<br>
* 参数的意思:beforeBegin<span>afterBegin this is span! beforeEnd</span> afterEnd <br />
* 此外,如果使用本函数插入带有script标签的HTML字符串,script标签对应的脚本将不会被执行。
*
* @shortcut insertHTML
* @meta standard
*
* @returns {HTMLElement} 目标元素
*/
baidu.insertHTML = baidu.dom.insertHTML = function ( element, position, html ) {
element = baidu.dom.g( element );
var range, begin;
if ( element.insertAdjacentHTML ) {
element.insertAdjacentHTML( position, html );
} else {
// 这里不做"undefined" != typeof(HTMLElement) && !window.opera判断,其它浏览器将出错?!
// 但是其实做了判断,其它浏览器下等于这个函数就不能执行了
range = element.ownerDocument.createRange();
// FF下range的位置设置错误可能导致创建出来的fragment在插入dom树之后html结构乱掉
// 改用range.insertNode来插入html, by wenyuxiang @ 2010-12-14.
position = position.toUpperCase();
if ( position == 'AFTERBEGIN' || position == 'BEFOREEND' ) {
range.selectNodeContents( element );
range.collapse( position == 'AFTERBEGIN' );
} else {
begin = position == 'BEFOREBEGIN';
range[begin ? 'setStartBefore' : 'setEndAfter']( element );
range.collapse( begin );
}
range.insertNode( range.createContextualFragment( html ) );
}
return element;
};
/**
* 为目标元素添加className
* @name baidu.dom.addClass
* @function
* @grammar baidu.dom.addClass(element, className)
* @param {HTMLElement|string} element 目标元素或目标元素的id
* @param {string} className 要添加的className,允许同时添加多个class,中间使用空白符分隔
* @remark
* 使用者应保证提供的className合法性,不应包含不合法字符,className合法字符参考:http://www.w3.org/TR/CSS2/syndata.html。
* @shortcut addClass
* @meta standard
*
* @returns {HTMLElement} 目标元素
*/
baidu.ac = baidu.dom.addClass = function ( element, className ) {
element = baidu.dom.g( element );
var classArray = className.split( /\s+/ ),
result = element.className,
classMatch = " " + result + " ",
i = 0,
l = classArray.length;
for ( ; i < l; i++ ) {
if ( classMatch.indexOf( " " + classArray[i] + " " ) < 0 ) {
result += ( result ? ' ' : '' ) + classArray[i];
}
}
element.className = result;
return element;
};
/**
* @ignore
* @namespace baidu.event 屏蔽浏览器差异性的事件封装。
* @property target 事件的触发元素
* @property pageX 鼠标事件的鼠标x坐标
* @property pageY 鼠标事件的鼠标y坐标
* @property keyCode 键盘事件的键值
*/
baidu.event = baidu.event || {};
/**
* 事件监听器的存储表
* @private
* @meta standard
*/
baidu.event._listeners = baidu.event._listeners || [];
/**
* 为目标元素添加事件监听器
* @name baidu.event.on
* @function
* @grammar baidu.event.on(element, type, listener)
* @param {HTMLElement|string|window} element 目标元素或目标元素id
* @param {string} type 事件类型
* @param {Function} listener 需要添加的监听器
* @remark
* 1. 不支持跨浏览器的鼠标滚轮事件监听器添加<br>
* 2. 改方法不为监听器灌入事件对象,以防止跨iframe事件挂载的事件对象获取失败
* @shortcut on
* @meta standard
* @see baidu.event.un
*
* @returns {HTMLElement|window} 目标元素
*/
baidu.on = baidu.event.on = function ( element, type, listener ) {
type = type.replace( /^on/i, '' );
element = baidu._g( element );
var realListener = function ( ev ) {
// 1. 这里不支持EventArgument, 原因是跨frame的事件挂载
// 2. element是为了修正this
listener.call( element, ev );
},
lis = baidu.event._listeners,
filter = baidu.event._eventFilter,
afterFilter,
realType = type;
type = type.toLowerCase();
// filter过滤
if ( filter && filter[type] ) {
afterFilter = filter[type]( element, type, realListener );
realType = afterFilter.type;
realListener = afterFilter.listener;
}
// 事件监听器挂载
if ( element.addEventListener ) {
element.addEventListener( realType, realListener, false );
} else if ( element.attachEvent ) {
element.attachEvent( 'on' + realType, realListener );
}
// 将监听器存储到数组中
lis[lis.length] = [element, type, listener, realListener, realType];
return element;
};
/**
* 为目标元素移除事件监听器
* @name baidu.event.un
* @function
* @grammar baidu.event.un(element, type, listener)
* @param {HTMLElement|string|window} element 目标元素或目标元素id
* @param {string} type 事件类型
* @param {Function} listener 需要移除的监听器
* @shortcut un
* @meta standard
*
* @returns {HTMLElement|window} 目标元素
*/
baidu.un = baidu.event.un = function ( element, type, listener ) {
element = baidu._g( element );
type = type.replace( /^on/i, '' ).toLowerCase();
var lis = baidu.event._listeners,
len = lis.length,
isRemoveAll = !listener,
item,
realType, realListener;
//如果将listener的结构改成json
//可以节省掉这个循环,优化性能
//但是由于un的使用频率并不高,同时在listener不多的时候
//遍历数组的性能消耗不会对代码产生影响
//暂不考虑此优化
while ( len-- ) {
item = lis[len];
// listener存在时,移除element的所有以listener监听的type类型事件
// listener不存在时,移除element的所有type类型事件
if ( item[1] === type
&& item[0] === element
&& ( isRemoveAll || item[2] === listener ) ) {
realType = item[4];
realListener = item[3];
if ( element.removeEventListener ) {
element.removeEventListener( realType, realListener, false );
} else if ( element.detachEvent ) {
element.detachEvent( 'on' + realType, realListener );
}
lis.splice( len, 1 );
}
}
return element;
};
/**
* 获取event事件,解决不同浏览器兼容问题
* @param {Event}
* @return {Event}
*/
baidu.getEvent = baidu.event.getEvent = function ( event ) {
return window.event || event;
}
/**
* 获取event.target,解决不同浏览器兼容问题
* @param {Event}
* @return {Target}
*/
baidu.getTarget = baidu.event.getTarget = function ( event ) {
var event = baidu.getEvent( event );
return event.target || event.srcElement;
}
/**
* 阻止事件的默认行为
* @name baidu.event.preventDefault
* @function
* @grammar baidu.event.preventDefault(event)
* @param {Event} event 事件对象
* @meta standard
*/
baidu.preventDefault = baidu.event.preventDefault = function ( event ) {
var event = baidu.getEvent( event );
if ( event.preventDefault ) {
event.preventDefault();
} else {
event.returnValue = false;
}
};
/**
* 停止事件冒泡传播
* @param {Event}
*/
baidu.stopBubble = baidu.event.stopBubble = function ( event ) {
event = baidu.getEvent( event );
event.stopPropagation ? event.stopPropagation() : event.cancelBubble = true;
}
} )();
//用来存储用户实例化出来的drawingmanager对象
var instances = [];
/**
* @exports DrawingManager as BMapLib.DrawingManager
*/
var DrawingManager =
/**
* DrawingManager类的构造函数
* @class 鼠标绘制管理类,实现鼠标绘制管理的<b>入口</b>。
* 实例化该类后,即可调用该类提供的open
* 方法开启绘制模式状态。
* 也可加入工具栏进行选择操作。
*
* @constructor
* @param {Map} map Baidu map的实例对象
* @param {Json Object} opts 可选的输入参数,非必填项。可输入选项包括:<br />
* {"<b>isOpen</b>" : {Boolean} 是否开启绘制模式
* <br />"<b>enableDrawingTool</b>" : {Boolean} 是否添加绘制工具栏控件,默认不添加
* <br />"<b>drawingToolOptions</b>" : {Json Object} 可选的输入参数,非必填项。可输入选项包括
* <br /> "<b>anchor</b>" : {ControlAnchor} 停靠位置、默认左上角
* <br /> "<b>offset</b>" : {Size} 偏移值。
* <br /> "<b>scale</b>" : {Number} 工具栏的缩放比例,默认为1
* <br /> "<b>drawingModes</b>" : {DrawingType<Array>} 工具栏上可以选择出现的绘制模式,将需要显示的DrawingType以数组型形式传入,如[BMAP_DRAWING_MARKER, BMAP_DRAWING_CIRCLE] 将只显示画点和画圆的选项
* <br />"<b>enableCalculate</b>" : {Boolean} 绘制是否进行测距(画线时候)、测面(画圆、多边形、矩形)
* <br />"<b>markerOptions</b>" : {CircleOptions} 所画的点的可选参数,参考api中的<a href="http://developer.baidu.com/map/reference/index.php?title=Class:%E6%80%BB%E7%B1%BB/%E8%A6%86%E7%9B%96%E7%89%A9%E7%B1%BB">对应类</a>
* <br />"<b>circleOptions</b>" : {CircleOptions} 所画的圆的可选参数,参考api中的<a href="http://developer.baidu.com/map/reference/index.php?title=Class:%E6%80%BB%E7%B1%BB/%E8%A6%86%E7%9B%96%E7%89%A9%E7%B1%BB">对应类</a>
* <br />"<b>polylineOptions</b>" : {CircleOptions} 所画的线的可选参数,参考api中的<a href="http://developer.baidu.com/map/reference/index.php?title=Class:%E6%80%BB%E7%B1%BB/%E8%A6%86%E7%9B%96%E7%89%A9%E7%B1%BB">对应类</a>
* <br />"<b>polygonOptions</b>" : {PolygonOptions} 所画的多边形的可选参数,参考api中的<a href="http://developer.baidu.com/map/reference/index.php?title=Class:%E6%80%BB%E7%B1%BB/%E8%A6%86%E7%9B%96%E7%89%A9%E7%B1%BB">对应类</a>
* <br />"<b>rectangleOptions</b>" : {PolygonOptions} 所画的矩形的可选参数,参考api中的<a href="http://developer.baidu.com/map/reference/index.php?title=Class:%E6%80%BB%E7%B1%BB/%E8%A6%86%E7%9B%96%E7%89%A9%E7%B1%BB">对应类</a>
*
* @example <b>参考示例:</b><br />
* var map = new BMap.Map("container");<br />map.centerAndZoom(new BMap.Point(116.404, 39.915), 15);<br />
* var myDrawingManagerObject = new BMapLib.DrawingManager(map, {isOpen: true,
* drawingType: BMAP_DRAWING_MARKER, enableDrawingTool: true,
* enableCalculate: false,
* drawingToolOptions: {
* anchor: BMAP_ANCHOR_TOP_LEFT,
* offset: new BMap.Size(5, 5),
* drawingTypes : [
* BMAP_DRAWING_MARKER,
* BMAP_DRAWING_CIRCLE,
* BMAP_DRAWING_POLYLINE,
* BMAP_DRAWING_POLYGON,
* BMAP_DRAWING_RECTANGLE
* ]
* },
* polylineOptions: {
* strokeColor: "#333"
* });
*/
BMapLib.DrawingManager = function ( map, opts ) {
if ( !map ) {
return;
}
instances.push( this );
opts = opts || {};
this._initialize( map, opts );
}
// 通过baidu.lang下的inherits方法,让DrawingManager继承baidu.lang.Class
baidu.lang.inherits( DrawingManager, baidu.lang.Class, "DrawingManager" );
/**
* 开启地图的绘制模式
*
* @example <b>参考示例:</b><br />
* myDrawingManagerObject.open();
*/
DrawingManager.prototype.open = function () {
// 判断绘制状态是否已经开启
if ( this._isOpen == true ) {
return true;
}
closeInstanceExcept( this );
this._open();
}
/**
* 关闭地图的绘制状态
*
* @example <b>参考示例:</b><br />
* myDrawingManagerObject.close();
*/
DrawingManager.prototype.close = function () {
// 判断绘制状态是否已经开启
if ( this._isOpen == false ) {
return true;
}
this._close();
}
/**
* 设置当前的绘制模式,参数DrawingType,为5个可选常量:
* <br/>BMAP_DRAWING_MARKER 画点
* <br/>BMAP_DRAWING_CIRCLE 画圆
* <br/>BMAP_DRAWING_POLYLINE 画线
* <br/>BMAP_DRAWING_POLYGON 画多边形
* <br/>BMAP_DRAWING_RECTANGLE 画矩形
* @param {DrawingType} DrawingType
* @return {Boolean}
*
* @example <b>参考示例:</b><br />
* myDrawingManagerObject.setDrawingMode(BMAP_DRAWING_POLYLINE);
*/
DrawingManager.prototype.setDrawingMode = function ( drawingType ) {
//与当前模式不一样时候才进行重新绑定事件
if ( this._drawingType != drawingType ) {
closeInstanceExcept( this );
this._setDrawingMode( drawingType );
}
}
/**
* 获取当前的绘制模式
* @return {DrawingType} 绘制的模式
*
* @example <b>参考示例:</b><br />
* alert(myDrawingManagerObject.getDrawingMode());
*/
DrawingManager.prototype.getDrawingMode = function () {
return this._drawingType;
}
/**
* 打开距离或面积计算
*
* @example <b>参考示例:</b><br />
* myDrawingManagerObject.enableCalculate();
*/
DrawingManager.prototype.enableCalculate = function () {
this._addGeoUtilsLibrary();
this._enableCalculate = true;
}
/**
* 关闭距离或面积计算
*
* @example <b>参考示例:</b><br />
* myDrawingManagerObject.disableCalculate();
*/
DrawingManager.prototype.disableCalculate = function () {
this._enableCalculate = false;
}
/**
* 后续绘制的图形允许显示关闭按钮
*/
DrawingManager.prototype.enableCloseBtn = function () {
this._enableCloseBtn = true;
}
/**
* 后续绘制的图形不显示关闭按钮
*/
DrawingManager.prototype.diableCloseBtn = function () {
this._enableCloseBtn = false;
}
/**
* 鼠标绘制完成后,派发总事件的接口
* @name DrawingManager#overlaycomplete
* @event
* @param {Event Object} e 回调函数会返回event参数,包括以下返回值:
* <br />{"<b>drawingMode</b> : {DrawingType} 当前的绘制模式
* <br />"<b>overlay</b>:{Marker||Polyline||Polygon||Circle} 对应的绘制模式返回对应的覆盖物
* <br />"<b>calculate</b>:{Number} 需要开启计算模式才会返回这个值,当绘制线的时候返回距离、绘制多边形、圆、矩形时候返回面积,单位为米,
* <br />"<b>label</b>:{Label} 计算面积时候出现在Map上的Label对象
*
* @example <b>参考示例:</b>
* myDrawingManagerObject.addEventListener("overlaycomplete", function(e) {
* alert(e.drawingMode);
* alert(e.overlay);
* alert(e.calculate);
* alert(e.label);
* });
*/
/**
* 绘制点完成后,派发的事件接口
* @name DrawingManager#markercomplete
* @event
* @param {Marker} overlay 回调函数会返回相应的覆盖物,
* <br />{"<b>overlay</b> : {Marker}
*
* @example <b>参考示例:</b>
* myDrawingManagerObject.addEventListener("circlecomplete", function(e, overlay) {
* alert(overlay);
* });
*/
/**
* 绘制圆完成后,派发的事件接口
* @name DrawingManager#circlecomplete
* @event
* @param {Circle} overlay 回调函数会返回相应的覆盖物,
* <br />{"<b>overlay</b> : {Circle}
*/
/**
* 绘制线完成后,派发的事件接口
* @name DrawingManager#polylinecomplete
* @event
* @param {Polyline} overlay 回调函数会返回相应的覆盖物,
* <br />{"<b>overlay</b> : {Polyline}
*/
/**
* 绘制多边形完成后,派发的事件接口
* @name DrawingManager#polygoncomplete
* @event
* @param {Polygon} overlay 回调函数会返回相应的覆盖物,
* <br />{"<b>overlay</b> : {Polygon}
*/
/**
* 绘制矩形完成后,派发的事件接口
* @name DrawingManager#rectanglecomplete
* @event
* @param {Polygon} overlay 回调函数会返回相应的覆盖物,
* <br />{"<b>overlay</b> : {Polygon}
*/
/**
* 初始化状态
* @param {Map} 地图实例
* @param {Object} 参数
*/
DrawingManager.prototype._initialize = function ( map, opts ) {
/**
* map对象
* @private
* @type {Map}
*/
this._map = map;
/**
* 配置对象
* @private
* @type {Object}
*/
this._opts = opts;
/**
* 当前的绘制模式, 默认是绘制点
* @private
* @type {DrawingType}
*/
this._drawingType = opts.drawingMode || BMAP_DRAWING_MARKER;
/**
* 是否添加添加鼠标绘制工具栏面板
*/
if ( opts.enableDrawingTool ) {
var drawingTool = new DrawingTool( this, opts.drawingToolOptions );
this._drawingTool = drawingTool;
map.addControl( drawingTool );
}
//是否计算绘制出的面积
if ( opts.enableCalculate === true ) {
this.enableCalculate();
} else {
this.disableCalculate();
}
//是否显示关闭按钮
if ( opts.enableCloseBtn === true ) {
this.enableCloseBtn();
} else {
this.diableCloseBtn();
}
/**
* 是否已经开启了绘制状态
* @private
* @type {Boolean}
*/
this._isOpen = !!( opts.isOpen === true );
if ( this._isOpen ) {
this._open();
}
this.markerOptions = opts.markerOptions || {};
this.circleOptions = opts.circleOptions || {};
this.polylineOptions = opts.polylineOptions || {};
this.polygonOptions = opts.polygonOptions || {};
this.rectangleOptions = opts.rectangleOptions || {};
},
/**
* 开启地图的绘制状态
* @return {Boolean},开启绘制状态成功,返回true;否则返回false。
*/
DrawingManager.prototype._open = function () {
this._isOpen = true;
//添加遮罩,所有鼠标操作都在这个遮罩上完成
if ( !this._mask ) {
this._mask = new Mask();
}
this._map.addOverlay( this._mask );
this._setDrawingMode( this._drawingType );
}
/**
* 设置当前的绘制模式
* @param {DrawingType}
*/
DrawingManager.prototype._setDrawingMode = function ( drawingType ) {
this._drawingType = drawingType;
/**
* 开启编辑状态时候才重新进行事件绑定
*/
if ( this._isOpen ) {
//清空之前的自定义事件
this._mask.__listeners = {};
switch ( drawingType ) {
case BMAP_DRAWING_MARKER:
this._bindMarker();
break;
case BMAP_DRAWING_CIRCLE:
this._bindCircle();
break;
case BMAP_DRAWING_POLYLINE:
case BMAP_DRAWING_POLYGON:
this._bindPolylineOrPolygon();
break;
case BMAP_DRAWING_RECTANGLE:
this._bindRectangle();
break;
}
}
/**
* 如果添加了工具栏,则也需要改变工具栏的样式
*/
if ( this._drawingTool && this._isOpen ) {
this._drawingTool.setStyleByDrawingMode( drawingType );
}
}
/**
* 关闭地图的绘制状态
* @return {Boolean},关闭绘制状态成功,返回true;否则返回false。
*/
DrawingManager.prototype._close = function () {
this._isOpen = false;
if ( this._mask ) {
this._map.removeOverlay( this._mask );
}
/**
* 如果添加了工具栏,则关闭时候将工具栏样式设置为拖拽地图
*/
if ( this._drawingTool ) {
this._drawingTool.setStyleByDrawingMode( "hander" );
}
}
/**
* 绑定鼠标画点的事件
*/
DrawingManager.prototype._bindMarker = function () {
var me = this,
map = this._map,
mask = this._mask;
/**
* 鼠标点击的事件
*/
var clickAction = function ( e ) {
// 往地图上添加marker
var marker = new BMap.Marker( e.point, me.markerOptions );
map.addOverlay( marker );
me._dispatchOverlayComplete( marker );
}
mask.addEventListener( 'click', clickAction );
}
/**
* 绑定鼠标画圆的事件
*/
DrawingManager.prototype._bindCircle = function () {
var me = this,
map = this._map,
mask = this._mask,
circle = null,
centerPoint = null; //圆的中心点
/**
* 开始绘制圆形
*/
var startAction = function ( e ) {
centerPoint = e.point;
circle = new BMap.Circle( centerPoint, 0, me.circleOptions );
map.addOverlay( circle );
mask.enableEdgeMove();
mask.addEventListener( 'mousemove', moveAction );
baidu.on( document, 'mouseup', endAction );
}
/**
* 绘制圆形过程中,鼠标移动过程的事件
*/
var moveAction = function ( e ) {
circle.setRadius( me._map.getDistance( centerPoint, e.point ) );
}
/**
* 绘制圆形结束
*/
var endAction = function ( e ) {
var calculate = me._calculate( circle, e.point );
me._dispatchOverlayComplete( circle, calculate );
centerPoint = null;
mask.disableEdgeMove();
mask.removeEventListener( 'mousemove', moveAction );
baidu.un( document, 'mouseup', endAction );
}
/**
* 鼠标点击起始点
*/
var mousedownAction = function ( e ) {
baidu.preventDefault( e );
baidu.stopBubble( e );
if ( centerPoint == null ) {
startAction( e );
}
}
mask.addEventListener( 'mousedown', mousedownAction );
}
/**
* 画线和画多边形相似性比较大,公用一个方法
*/
DrawingManager.prototype._bindPolylineOrPolygon = function () {
var me = this,
map = this._map,
mask = this._mask,
points = [], //用户绘制的点
drawPoint = null; //实际需要画在地图上的点
overlay = null,
isBinded = false;
/**
* 鼠标点击的事件
*/
var startAction = function ( e ) {
points.push( e.point );
drawPoint = points.concat( points[points.length - 1] );
if ( points.length == 1 ) {
if ( me._drawingType == BMAP_DRAWING_POLYLINE ) {
overlay = new BMap.Polyline( drawPoint, me.polylineOptions );
} else if ( me._drawingType == BMAP_DRAWING_POLYGON ) {
overlay = new BMap.Polygon( drawPoint, me.polygonOptions );
}
map.addOverlay( overlay );
} else {
overlay.setPath( drawPoint );
}
if ( !isBinded ) {
isBinded = true;
mask.enableEdgeMove();
mask.addEventListener( 'mousemove', mousemoveAction );
mask.addEventListener( 'dblclick', dblclickAction );
}
}
/**
* 鼠标移动过程的事件
*/
var mousemoveAction = function ( e ) {
overlay.setPositionAt( drawPoint.length - 1, e.point );
}
/**
* 鼠标双击的事件
*/
var dblclickAction = function ( e ) {
baidu.stopBubble( e );
isBinded = false;
mask.disableEdgeMove();
mask.removeEventListener( 'mousemove', mousemoveAction );
mask.removeEventListener( 'dblclick', dblclickAction );
overlay.setPath( points );
var endPoint = points[points.length - 1];
var calculate = me._calculate( overlay, endPoint );
me._dispatchOverlayComplete( overlay, calculate );
if ( me._drawingType == BMAP_DRAWING_POLYGON ) {
//添加关闭按钮
me._addCloseIcon( endPoint, overlay, calculate );
}
points.length = 0;
drawPoint.length = 0;
}
mask.addEventListener( 'click', startAction );
//双击时候不放大地图级别
mask.addEventListener( 'dblclick', function ( e ) {
baidu.stopBubble( e );
} );
}
/**
* 绑定鼠标画矩形的事件
*/
DrawingManager.prototype._bindRectangle = function () {
var me = this,
map = this._map,
mask = this._mask,
polygon = null,
startPoint = null;
/**
* 开始绘制矩形
*/
var startAction = function ( e ) {
baidu.stopBubble( e );
baidu.preventDefault( e );
startPoint = e.point;
var endPoint = startPoint;
polygon = new BMap.Polygon( me._getRectanglePoint( startPoint, endPoint ), me.rectangleOptions );
map.addOverlay( polygon );
mask.enableEdgeMove();
mask.addEventListener( 'mousemove', moveAction );
baidu.on( document, 'mouseup', endAction );
}
/**
* 绘制矩形过程中,鼠标移动过程的事件
*/
var moveAction = function ( e ) {
polygon.setPath( me._getRectanglePoint( startPoint, e.point ) );
}
/**
* 绘制矩形结束
*/
var endAction = function ( e ) {
var calculate = me._calculate( polygon, polygon.getPath()[2] );
me._dispatchOverlayComplete( polygon, calculate );
startPoint = null;
mask.disableEdgeMove();
mask.removeEventListener( 'mousemove', moveAction );
baidu.un( document, 'mouseup', endAction );
//添加关闭按钮
me._addCloseIcon( polygon.getPath()[2], polygon, calculate );
}
mask.addEventListener( 'mousedown', startAction );
}
/**
* 添加显示所绘制图形的面积或者长度
* @param {overlay} 覆盖物
* @param {point} 显示的位置
*/
DrawingManager.prototype._calculate = function ( overlay, point ) {
var result = {
data: 0, //计算出来的长度或面积
label: null //显示长度或面积的label对象
};
if ( this._enableCalculate && BMapLib.GeoUtils ) {
var type = overlay.toString();
//不同覆盖物调用不同的计算方法
switch ( type ) {
case "[object Polyline]":
var data = BMapLib.GeoUtils.getPolylineDistance( overlay );
//异常情况处理
if ( !data || data < 0 ) {
data = 0;
} else {
//保留2位小数位
data = data.toFixed( 2 );
}
result.data = data + "米";
break;
case "[object Polygon]":
var data = BMapLib.GeoUtils.getPolygonArea( overlay );
//异常情况处理
if ( !data || data < 0 ) {
data = 0;
result.data = "面积:" + data + "平方米";
} else {
if ( data > 1000000 ) {
//保留2位小数位
data = ( data / 1000000 ).toFixed( 2 );
result.data = "面积:" + data + "平方公里";
}
else {
//保留2位小数位
data = data.toFixed( 2 );
result.data = "面积:" + data + "平方米";
}
}
break;
case "[object Circle]":
var radius = overlay.getRadius();
var data = Math.PI * radius * radius;
if ( data > 1000000 ) {
//保留2位小数位
data = ( data / 1000000 ).toFixed( 2 );
result.data = "面积:" + data + "平方公里";
}
else {
//保留2位小数位
data = data.toFixed( 2 );
result.data = "面积:" + data + "平方米";
}
break;
}
result.label = this._addLabel( point, result.data );
}
return result;
}
/**
* 开启测距和测面功能需要依赖于GeoUtils库
* 所以这里判断用户是否已经加载,若未加载则用js动态加载
*/
DrawingManager.prototype._addGeoUtilsLibrary = function () {
if ( !BMapLib.GeoUtils ) {
var script = document.createElement( 'script' );
script.setAttribute( "type", "text/javascript" );
script.setAttribute( "src", 'http://api.map.baidu.com/library/GeoUtils/1.2/src/GeoUtils_min.js' );
document.body.appendChild( script );
}
}
/**
* 添加关闭图标
* @param {Point} point 显示的位置,即鼠标最后位置
* @param {Overlay} overlay 绘制的图形
*/
DrawingManager.prototype._addCloseIcon = function ( point, overlay, calculate ) {
if ( !this._enableCloseBtn ) {
return;
}
var me = this;
var closeIcon = new BMap.Icon( "http://api.map.baidu.com/images/mapctrls.gif", new BMap.Size( 12, 12 ), { imageOffset: new BMap.Size( 0, -14 ) } );
var btnOffset = [14, -6];
var closeBtn = new BMap.Marker( point,
{
icon: closeIcon,
offset: new BMap.Size( btnOffset[0], btnOffset[1] ),
baseZIndex: 3600000,
enableMassClear: true
}
);
this._map.addOverlay( closeBtn );
closeBtn.setTitle( "清除绘制的图形" );
// 点击关闭按钮,绑定关闭按钮事件
closeBtn.addEventListener( "click", function ( e ) {
if ( calculate.label ) {
calculate.label.remove();
}
overlay.remove();
closeBtn.remove();
closeBtn = null;
//me.stopBubble(e);
} );
//me._drawingTool._close();
me._close();
}
/**
* 向地图中添加文本标注
* @param {Point}
* @param {String} 所以显示的内容
*/
DrawingManager.prototype._addLabel = function ( point, content ) {
var label = new BMap.Label( content, {
position: point
} );
this._map.addOverlay( label );
return label;
}
/**
* 根据起终点获取矩形的四个顶点
* @param {Point} 起点
* @param {Point} 终点
*/
DrawingManager.prototype._getRectanglePoint = function ( startPoint, endPoint ) {
return [
new BMap.Point( startPoint.lng, startPoint.lat ),
new BMap.Point( endPoint.lng, startPoint.lat ),
new BMap.Point( endPoint.lng, endPoint.lat ),
new BMap.Point( startPoint.lng, endPoint.lat )
];
}
/**
* 派发事件
*/
DrawingManager.prototype._dispatchOverlayComplete = function ( overlay, calculate ) {
var options = {
'overlay': overlay,
'drawingMode': this._drawingType
};
if ( calculate ) {
options.calculate = calculate.data || null;
options.label = calculate.label || null;
}
this.dispatchEvent( this._drawingType + 'complete', overlay );
this.dispatchEvent( 'overlaycomplete', options );
}
/**
* 创建遮罩对象
*/
function Mask() {
/**
* 鼠标到地图边缘的时候是否自动平移地图
*/
this._enableEdgeMove = false;
}
Mask.prototype = new BMap.Overlay();
/**
* 这里不使用api中的自定义事件,是为了更灵活使用
*/
Mask.prototype.dispatchEvent = baidu.lang.Class.prototype.dispatchEvent;
Mask.prototype.addEventListener = baidu.lang.Class.prototype.addEventListener;
Mask.prototype.removeEventListener = baidu.lang.Class.prototype.removeEventListener;
Mask.prototype.initialize = function ( map ) {
var me = this;
this._map = map;
var div = this.container = document.createElement( "div" );
var size = this._map.getSize();
div.style.cssText = "position:absolute;background:url(about:blank);cursor:crosshair;width:" + size.width + "px;height:" + size.height + "px";
this._map.addEventListener( 'resize', function ( e ) {
me._adjustSize( e.size );
} );
this._map.getPanes().floatPane.appendChild( div );
this._bind();
return div;
};
Mask.prototype.draw = function () {
var map = this._map,
point = map.pixelToPoint( new BMap.Pixel( 0, 0 ) ),
pixel = map.pointToOverlayPixel( point );
this.container.style.left = pixel.x + "px";
this.container.style.top = pixel.y + "px";
};
/**
* 开启鼠标到地图边缘,自动平移地图
*/
Mask.prototype.enableEdgeMove = function () {
this._enableEdgeMove = true;
}
/**
* 关闭鼠标到地图边缘,自动平移地图
*/
Mask.prototype.disableEdgeMove = function () {
clearInterval( this._edgeMoveTimer );
this._enableEdgeMove = false;
}
/**
* 绑定事件,派发自定义事件
*/
Mask.prototype._bind = function () {
var me = this,
map = this._map,
container = this.container,
lastMousedownXY = null,
lastClickXY = null;
/**
* 根据event对象获取鼠标的xy坐标对象
* @param {Event}
* @return {Object} {x:e.x, y:e.y}
*/
var getXYbyEvent = function ( e ) {
return {
x: e.clientX,
y: e.clientY
}
};
var domEvent = function ( e ) {
var type = e.type;
e = baidu.getEvent( e );
point = me.getDrawPoint( e ); //当前鼠标所在点的地理坐标
var dispatchEvent = function ( type ) {
e.point = point;
me.dispatchEvent( e );
}
if ( type == "mousedown" ) {
lastMousedownXY = getXYbyEvent( e );
}
var nowXY = getXYbyEvent( e );
//click经过一些特殊处理派发,其他同事件按正常的dom事件派发
if ( type == "click" ) {
//鼠标点击过程不进行移动才派发click和dblclick
if ( Math.abs( nowXY.x - lastMousedownXY.x ) < 5 && Math.abs( nowXY.y - lastMousedownXY.y ) < 5 ) {
if ( !lastClickXY || !( Math.abs( nowXY.x - lastClickXY.x ) < 5 && Math.abs( nowXY.y - lastClickXY.y ) < 5 ) ) {
dispatchEvent( 'click' );
lastClickXY = getXYbyEvent( e );
} else {
lastClickXY = null;
}
}
} else {
dispatchEvent( type );
}
}
/**
* 将事件都遮罩层的事件都绑定到domEvent来处理
*/
var events = ['click', 'mousedown', 'mousemove', 'mouseup', 'dblclick'],
index = events.length;
while ( index-- ) {
baidu.on( container, events[index], domEvent );
}
//鼠标移动过程中,到地图边缘后自动平移地图
baidu.on( container, 'mousemove', function ( e ) {
if ( me._enableEdgeMove ) {
me.mousemoveAction( e );
}
} );
};
//鼠标移动过程中,到地图边缘后自动平移地图
Mask.prototype.mousemoveAction = function ( e ) {
function getClientPosition( e ) {
var clientX = e.clientX,
clientY = e.clientY;
if ( e.changedTouches ) {
clientX = e.changedTouches[0].clientX;
clientY = e.changedTouches[0].clientY;
}
return new BMap.Pixel( clientX, clientY );
}
var map = this._map,
me = this,
pixel = map.pointToPixel( this.getDrawPoint( e ) ),
clientPos = getClientPosition( e ),
offsetX = clientPos.x - pixel.x,
offsetY = clientPos.y - pixel.y;
pixel = new BMap.Pixel(( clientPos.x - offsetX ), ( clientPos.y - offsetY ) );
this._draggingMovePixel = pixel;
var point = map.pixelToPoint( pixel ),
eventObj = {
pixel: pixel,
point: point
};
// 拖拽到地图边缘移动地图
this._panByX = this._panByY = 0;
if ( pixel.x <= 20 || pixel.x >= map.width - 20
|| pixel.y <= 50 || pixel.y >= map.height - 10 ) {
if ( pixel.x <= 20 ) {
this._panByX = 8;
} else if ( pixel.x >= map.width - 20 ) {
this._panByX = -8;
}
if ( pixel.y <= 50 ) {
this._panByY = 8;
} else if ( pixel.y >= map.height - 10 ) {
this._panByY = -8;
}
if ( !this._edgeMoveTimer ) {
this._edgeMoveTimer = setInterval( function () {
map.panBy( me._panByX, me._panByY, { "noAnimation": true } );
}, 30 );
}
} else {
if ( this._edgeMoveTimer ) {
clearInterval( this._edgeMoveTimer );
this._edgeMoveTimer = null;
}
}
}
/*
* 调整大小
* @param {Size}
*/
Mask.prototype._adjustSize = function ( size ) {
this.container.style.width = size.width + 'px';
this.container.style.height = size.height + 'px';
};
/**
* 获取当前绘制点的地理坐标
*
* @param {Event} e e对象
* @return Point对象的位置信息
*/
Mask.prototype.getDrawPoint = function ( e ) {
var map = this._map,
trigger = baidu.getTarget( e ),
x = e.offsetX || e.layerX || 0,
y = e.offsetY || e.layerY || 0;
if ( trigger.nodeType != 1 ) trigger = trigger.parentNode;
while ( trigger && trigger != map.getContainer() ) {
if ( !( trigger.clientWidth == 0 &&
trigger.clientHeight == 0 &&
trigger.offsetParent && trigger.offsetParent.nodeName == 'TD' ) ) {
x += trigger.offsetLeft || 0;
y += trigger.offsetTop || 0;
}
trigger = trigger.offsetParent;
}
var pixel = new BMap.Pixel( x, y );
var point = map.pixelToPoint( pixel );
return point;
}
/**
* 绘制工具面板,自定义控件
*/
function DrawingTool( drawingManager, drawingToolOptions ) {
this.drawingManager = drawingManager;
drawingToolOptions = this.drawingToolOptions = drawingToolOptions || {};
// 默认停靠位置和偏移量
this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
this.defaultOffset = new BMap.Size( 10, 10 );
//默认所有工具栏都显示
this.defaultDrawingModes = [
BMAP_DRAWING_MARKER,
BMAP_DRAWING_CIRCLE,
BMAP_DRAWING_POLYLINE,
BMAP_DRAWING_POLYGON,
BMAP_DRAWING_RECTANGLE
];
//工具栏可显示的绘制模式
if ( drawingToolOptions.drawingModes ) {
this.drawingModes = drawingToolOptions.drawingModes;
} else {
this.drawingModes = this.defaultDrawingModes
}
//用户设置停靠位置和偏移量
if ( drawingToolOptions.anchor ) {
this.setAnchor( drawingToolOptions.anchor );
}
if ( drawingToolOptions.offset ) {
this.setOffset( drawingToolOptions.offset );
}
}
// 通过JavaScript的prototype属性继承于BMap.Control
DrawingTool.prototype = new BMap.Control();
// 自定义控件必须实现自己的initialize方法,并且将控件的DOM元素返回
// 在本方法中创建个div元素作为控件的容器,并将其添加到地图容器中
DrawingTool.prototype.initialize = function ( map ) {
// 创建一个DOM元素
var container = this.container = document.createElement( "div" );
container.className = "BMapLib_Drawing";
//用来设置外层边框阴影
var panel = this.panel = document.createElement( "div" );
panel.className = "BMapLib_Drawing_panel";
if ( this.drawingToolOptions && this.drawingToolOptions.scale ) {
this._setScale( this.drawingToolOptions.scale );
}
container.appendChild( panel );
// 添加内容
panel.innerHTML = this._generalHtml();
//绑定事件
this._bind( panel );
// 添加DOM元素到地图中
map.getContainer().appendChild( container );
// 将DOM元素返回
return container;
}
//生成工具栏的html元素
DrawingTool.prototype._generalHtml = function ( map ) {
//鼠标经过工具栏上的提示信息
var tips = {};
tips["hander"] = "拖动地图";
tips[BMAP_DRAWING_MARKER] = "画点";
tips[BMAP_DRAWING_CIRCLE] = "画圆";
tips[BMAP_DRAWING_POLYLINE] = "画折线";
tips[BMAP_DRAWING_POLYGON] = "画多边形";
tips[BMAP_DRAWING_RECTANGLE] = "画矩形";
var getItem = function ( className, drawingType ) {
return '<a class="' + className + '" drawingType="' + drawingType + '" href="javascript:void(0)" title="' + tips[drawingType] + '" onfocus="this.blur()"></a>';
}
var html = [];
html.push( getItem( "BMapLib_box BMapLib_hander", "hander" ) );
for ( var i = 0, len = this.drawingModes.length; i < len; i++ ) {
var classStr = 'BMapLib_box BMapLib_' + this.drawingModes[i];
if ( i == len - 1 ) {
classStr += ' BMapLib_last';
}
html.push( getItem( classStr, this.drawingModes[i] ) );
}
return html.join( '' );
}
/**
* 设置工具栏的缩放比例
*/
DrawingTool.prototype._setScale = function ( scale ) {
var width = 390,
height = 50,
ml = -parseInt(( width - width * scale ) / 2, 10 ),
mt = -parseInt(( height - height * scale ) / 2, 10 );
this.container.style.cssText = [
"-moz-transform: scale(" + scale + ");",
"-o-transform: scale(" + scale + ");",
"-webkit-transform: scale(" + scale + ");",
"transform: scale(" + scale + ");",
"margin-left:" + ml + "px;",
"margin-top:" + mt + "px;",
"*margin-left:0px;", //ie6、7
"*margin-top:0px;", //ie6、7
"margin-left:0px\\0;", //ie8
"margin-top:0px\\0;", //ie8
//ie下使用滤镜
"filter: progid:DXImageTransform.Microsoft.Matrix(",
"M11=" + scale + ",",
"M12=0,",
"M21=0,",
"M22=" + scale + ",",
"SizingMethod='auto expand');"
].join( '' );
}
//绑定工具栏的事件
DrawingTool.prototype._bind = function ( panel ) {
var me = this;
baidu.on( this.panel, 'click', function ( e ) {
var target = baidu.getTarget( e );
var drawingType = target.getAttribute( 'drawingType' );
me.setStyleByDrawingMode( drawingType );
me._bindEventByDraingMode( drawingType );
} );
}
//设置工具栏当前选中的项样式
DrawingTool.prototype.setStyleByDrawingMode = function ( drawingType ) {
if ( !drawingType ) {
return;
}
var boxs = this.panel.getElementsByTagName( "a" );
for ( var i = 0, len = boxs.length; i < len; i++ ) {
var box = boxs[i];
if ( box.getAttribute( 'drawingType' ) == drawingType ) {
var classStr = "BMapLib_box BMapLib_" + drawingType + "_hover";
if ( i == len - 1 ) {
classStr += " BMapLib_last";
}
box.className = classStr;
} else {
box.className = box.className.replace( /_hover/, "" );
}
}
}
//设置工具栏当前选中的项样式
DrawingTool.prototype._bindEventByDraingMode = function ( drawingType ) {
var drawingManager = this.drawingManager;
//点在拖拽地图的按钮上
if ( drawingType == "hander" ) {
drawingManager.close();
} else {
drawingManager.setDrawingMode( drawingType );
drawingManager.open();
}
}
/*
* 关闭其他实例的绘制模式
* @param {DrawingManager} 当前的实例
*/
function closeInstanceExcept( instance ) {
var index = instances.length;
while ( index-- ) {
if ( instances[index] != instance ) {
instances[index].close();
}
}
}
} )();
/**
* @fileoverview 百度地图的可根据当前poi点来进行周边检索、公交、驾车查询的信息窗口,对外开放。
* 主入口类是<a href="symbols/BMapLib.SearchInfoWindow.html">SearchInfoWindow</a>,
* 基于Baidu Map API 1.4。
*
* @author Baidu Map Api Group
* @version 1.4
*
* version 1.4.1,wutiansheng@20140623
* 1.在点击地图后,自动关闭弹出的信息窗口
*/
//常量,searchInfoWindow可选择的检索类型
var BMAPLIB_TAB_SEARCH = 0, BMAPLIB_TAB_TO_HERE = 1, BMAPLIB_TAB_FROM_HERE = 2;
( function () {
//声明baidu包
var T, baidu = T = baidu || { version: '1.5.0' };
baidu.guid = '$BAIDU$';
//以下方法为百度Tangram框架中的方法,请到http://tangram.baidu.com 查看文档
( function () {
window[baidu.guid] = window[baidu.guid] || {};
baidu.lang = baidu.lang || {};
baidu.lang.isString = function ( source ) {
return '[object String]' == Object.prototype.toString.call( source );
};
baidu.lang.Event = function ( type, target ) {
this.type = type;
this.returnValue = true;
this.target = target || null;
this.currentTarget = null;
};
baidu.object = baidu.object || {};
baidu.extend =
baidu.object.extend = function ( target, source ) {
for ( var p in source ) {
if ( source.hasOwnProperty( p ) ) {
target[p] = source[p];
}
}
return target;
};
baidu.event = baidu.event || {};
baidu.event._listeners = baidu.event._listeners || [];
baidu.dom = baidu.dom || {};
baidu.dom._g = function ( id ) {
if ( baidu.lang.isString( id ) ) {
return document.getElementById( id );
}
return id;
};
baidu._g = baidu.dom._g;
baidu.event.on = function ( element, type, listener ) {
type = type.replace( /^on/i, '' );
element = baidu.dom._g( element );
var realListener = function ( ev ) {
// 1. 这里不支持EventArgument, 原因是跨frame的事件挂载
// 2. element是为了修正this
listener.call( element, ev );
},
lis = baidu.event._listeners,
filter = baidu.event._eventFilter,
afterFilter,
realType = type;
type = type.toLowerCase();
// filter过滤
if ( filter && filter[type] ) {
afterFilter = filter[type]( element, type, realListener );
realType = afterFilter.type;
realListener = afterFilter.listener;
}
// 事件监听器挂载
if ( element.addEventListener ) {
element.addEventListener( realType, realListener, false );
} else if ( element.attachEvent ) {
element.attachEvent( 'on' + realType, realListener );
}
// 将监听器存储到数组中
lis[lis.length] = [element, type, listener, realListener, realType];
return element;
};
baidu.on = baidu.event.on;
baidu.event.un = function ( element, type, listener ) {
element = baidu.dom._g( element );
type = type.replace( /^on/i, '' ).toLowerCase();
var lis = baidu.event._listeners,
len = lis.length,
isRemoveAll = !listener,
item,
realType, realListener;
while ( len-- ) {
item = lis[len];
if ( item[1] === type
&& item[0] === element
&& ( isRemoveAll || item[2] === listener ) ) {
realType = item[4];
realListener = item[3];
if ( element.removeEventListener ) {
element.removeEventListener( realType, realListener, false );
} else if ( element.detachEvent ) {
element.detachEvent( 'on' + realType, realListener );
}
lis.splice( len, 1 );
}
}
return element;
};
baidu.un = baidu.event.un;
baidu.dom.g = function ( id ) {
if ( 'string' == typeof id || id instanceof String ) {
return document.getElementById( id );
} else if ( id && id.nodeName && ( id.nodeType == 1 || id.nodeType == 9 ) ) {
return id;
}
return null;
};
baidu.g = baidu.G = baidu.dom.g;
baidu.string = baidu.string || {};
baidu.browser = baidu.browser || {};
baidu.browser.ie = baidu.ie = /msie (\d+\.\d+)/i.test( navigator.userAgent ) ? ( document.documentMode || +RegExp['\x241'] ) : undefined;
baidu.dom._NAME_ATTRS = ( function () {
var result = {
'cellpadding': 'cellPadding',
'cellspacing': 'cellSpacing',
'colspan': 'colSpan',
'rowspan': 'rowSpan',
'valign': 'vAlign',
'usemap': 'useMap',
'frameborder': 'frameBorder'
};
if ( baidu.browser.ie < 8 ) {
result['for'] = 'htmlFor';
result['class'] = 'className';
} else {
result['htmlFor'] = 'for';
result['className'] = 'class';
}
return result;
} )();
baidu.dom.setAttr = function ( element, key, value ) {
element = baidu.dom.g( element );
if ( 'style' == key ) {
element.style.cssText = value;
} else {
key = baidu.dom._NAME_ATTRS[key] || key;
element.setAttribute( key, value );
}
return element;
};
baidu.setAttr = baidu.dom.setAttr;
baidu.dom.setAttrs = function ( element, attributes ) {
element = baidu.dom.g( element );
for ( var key in attributes ) {
baidu.dom.setAttr( element, key, attributes[key] );
}
return element;
};
baidu.setAttrs = baidu.dom.setAttrs;
baidu.dom.create = function ( tagName, opt_attributes ) {
var el = document.createElement( tagName ),
attributes = opt_attributes || {};
return baidu.dom.setAttrs( el, attributes );
};
baidu.cookie = baidu.cookie || {};
baidu.cookie._isValidKey = function ( key ) {
// http://www.w3.org/Protocols/rfc2109/rfc2109
// Syntax: General
// The two state management headers, Set-Cookie and Cookie, have common
// syntactic properties involving attribute-value pairs. The following
// grammar uses the notation, and tokens DIGIT (decimal digits) and
// token (informally, a sequence of non-special, non-white space
// characters) from the HTTP/1.1 specification [RFC 2068] to describe
// their syntax.
// av-pairs = av-pair *(";" av-pair)
// av-pair = attr ["=" value] ; optional value
// attr = token
// value = word
// word = token | quoted-string
// http://www.ietf.org/rfc/rfc2068.txt
// token = 1*<any CHAR except CTLs or tspecials>
// CHAR = <any US-ASCII character (octets 0 - 127)>
// CTL = <any US-ASCII control character
// (octets 0 - 31) and DEL (127)>
// tspecials = "(" | ")" | "<" | ">" | "@"
// | "," | ";" | ":" | "\" | <">
// | "/" | "[" | "]" | "?" | "="
// | "{" | "}" | SP | HT
// SP = <US-ASCII SP, space (32)>
// HT = <US-ASCII HT, horizontal-tab (9)>
return ( new RegExp( "^[^\\x00-\\x20\\x7f\\(\\)<>@,;:\\\\\\\"\\[\\]\\?=\\{\\}\\/\\u0080-\\uffff]+\x24" ) ).test( key );
};
baidu.cookie.getRaw = function ( key ) {
if ( baidu.cookie._isValidKey( key ) ) {
var reg = new RegExp( "(^| )" + key + "=([^;]*)(;|\x24)" ),
result = reg.exec( document.cookie );
if ( result ) {
return result[2] || null;
}
}
return null;
};
baidu.cookie.get = function ( key ) {
var value = baidu.cookie.getRaw( key );
if ( 'string' == typeof value ) {
value = decodeURIComponent( value );
return value;
}
return null;
};
baidu.cookie.setRaw = function ( key, value, options ) {
if ( !baidu.cookie._isValidKey( key ) ) {
return;
}
options = options || {};
//options.path = options.path || "/"; // meizz 20100402 设定一个初始值,方便后续的操作
//berg 20100409 去掉,因为用户希望默认的path是当前路径,这样和浏览器对cookie的定义也是一致的
// 计算cookie过期时间
var expires = options.expires;
if ( 'number' == typeof options.expires ) {
expires = new Date();
expires.setTime( expires.getTime() + options.expires );
}
document.cookie =
key + "=" + value
+ ( options.path ? "; path=" + options.path : "" )
+ ( expires ? "; expires=" + expires.toGMTString() : "" )
+ ( options.domain ? "; domain=" + options.domain : "" )
+ ( options.secure ? "; secure" : '' );
};
baidu.cookie.set = function ( key, value, options ) {
baidu.cookie.setRaw( key, encodeURIComponent( value ), options );
};
baidu.cookie.remove = function ( key, options ) {
options = options || {};
options.expires = new Date( 0 );
baidu.cookie.setRaw( key, '', options );
};// 声明快捷
//检验是否是正确的手机号
baidu.isPhone = function ( phone ) {
return /\d{11}/.test( phone );
}
//检验是否是正确的激活码
baidu.isActivateCode = function ( vcode ) {
return /\d{4}/.test( vcode );
}
T.undope = true;
} )();
/**
* @exports SearchInfoWindow as BMapLib.SearchInfoWindow
*/
var SearchInfoWindow =
/**
* SearchInfoWindow类的构造函数
* @class SearchInfoWindow <b>入口</b>。
* 可以定义检索模版。
* @constructor
* @param {Map} map Baidu map的实例对象.
* @param {String} content searchInfoWindow中的内容,支持HTML内容.
* @param {Json Object} opts 可选的输入参数,非必填项。可输入选项包括:<br />
* {<br />"<b>title</b>" : {String} searchInfoWindow的标题内容,支持HTML内容<br/>
* {<br />"<b>width</b>" : {Number} searchInfoWindow的内容宽度<br/>
* {<br />"<b>height</b>" : {Number} searchInfoWindow的内容高度 <br/>
* {<br />"<b>offset</b>" : {Size} searchInfoWindow的偏移量<br/>
* <br />"<b>enableAutoPan</b>" : {Boolean} 是否启动自动平移功能,默认开启 <br />
* <br />"<b>panel</b>" : {String} 用来展现检索信息的面板,可以是dom元素或元素的ID值 <br />
* <br />"<b>searchTypes</b>" : {Array} 通过传入数组设置检索面板的Tab选项共有三个选项卡可选择,选项卡顺序也按照数组的顺序来排序,传入空数组则不显示检索模版,不设置此参数则默认所有选项卡都显示。数组可传入的值为常量:BMAPLIB_TAB_SEARCH<周边检索>, BMAPLIB_TAB_TO_HERE<到去这里>, BMAPLIB_TAB_FROM_HERE<从这里出发> <br />
* <br />"<b>enableSendToPhone</b>" : {Boolean} 是否启动发送到手机功能,默认开启 <br />
* }<br />.
* @example <b>参考示例:</b><br />
* var searchInfoWindow = new BMapLib.SearchInfoWindow(map,"百度地图api",{
* title "百度大厦",
* width : 280,
* height : 50,
* panel : "panel", //检索结果面板
* enableAutoPan : true, //自动平移
* enableSendToPhone : true, //是否启动发送到手机功能
* searchTypes :[
* BMAPLIB_TAB_SEARCH, //周边检索
* BMAPLIB_TAB_TO_HERE, //到这里去
* BMAPLIB_TAB_FROM_HERE //从这里出发
* ]
* });
*/
BMapLib.SearchInfoWindow = function ( map, content, opts ) {
//存储当前实例
this.guid = guid++;
BMapLib.SearchInfoWindow.instance[this.guid] = this;
this._isOpen = false;
this._map = map;
this._opts = opts = opts || {};
this._content = content || "";
this._opts.width = opts.width;
this._opts.height = opts.height;
this._opts._title = opts.title || "";
this._opts.offset = opts.offset || new BMap.Size( 0, 0 );
this._opts.enableAutoPan = opts.enableAutoPan === false ? false : true;
this._opts._panel = opts.panel || null;
this._opts._searchTypes = opts.searchTypes; //传入数组形式
this._opts.enableSendToPhone = opts.enableSendToPhone; //是否开启发送到手机
that = this;
this.mapClickFunction = function () {
//在发生地图点击事件时,关闭所有信息窗口
that._closeOtherSearchInfo();
};
}
SearchInfoWindow.prototype = new BMap.Overlay();
SearchInfoWindow.prototype.initialize = function ( map ) {
this._closeOtherSearchInfo();
var me = this;
var div = this._createSearchTemplate();
var floatPane = map.getPanes().floatPane;
floatPane.style.width = "auto";
floatPane.appendChild( div );
this._initSearchTemplate();
//设置完内容后,获取div的宽度,高度
this._getSearchInfoWindowSize();
this._boxWidth = parseInt( this.container.offsetWidth, 10 );
this._boxHeight = parseInt( this.container.offsetHeight, 10 );
//阻止各种冒泡事件
baidu.event.on( div, "onmousedown", function ( e ) {
me._stopBubble( e );
} );
baidu.event.on( div, "onmouseover", function ( e ) {
me._stopBubble( e );
} );
baidu.event.on( div, "click", function ( e ) {
me._stopBubble( e );
} );
baidu.event.on( div, "dblclick", function ( e ) {
me._stopBubble( e );
} );
return div;
}
SearchInfoWindow.prototype.draw = function () {
this._isOpen && this._adjustPosition( this._point );
}
/**
* 打开searchInfoWindow
* @param {Marker|Point} location 要在哪个marker或者point上打开searchInfoWindow
* @return none
*
* @example <b>参考示例:</b><br />
* searchInfoWindow.open();
*/
SearchInfoWindow.prototype.open = function ( anchor ) {
this._map.closeInfoWindow();
var me = this, poi;
if ( !this._isOpen ) {
/*
if (this._isHide) {
this.show();
this._isHide = false;
this._isOpen = true;
setTimeout(function(){
me._dispatchEvent(me,"open",{"point" : me._point});
me._map.addEventListener("click",mapClickFunction);
},10);
return;
}
*/
this._map.addOverlay( this );
this._isOpen = true;
//延迟10ms派发open事件,使后绑定的事件可以触发。
setTimeout( function () {
me._dispatchEvent( me, "open", { "point": me._point } );
//注册地图点击事件监听,用于关闭信息窗口
me._map.addEventListener( "click", me.mapClickFunction );
}, 10 );
}
if ( anchor instanceof BMap.Point ) {
poi = anchor;
//清除之前存在的marker事件绑定,如果存在的话
this._removeMarkerEvt();
this._marker = null;
} else if ( anchor instanceof BMap.Marker ) {
//如果当前marker不为空,说明是第二个marker,或者第二次点open按钮,先移除掉之前绑定的事件
if ( this._marker ) {
this._removeMarkerEvt();
}
poi = anchor.getPosition();
this._marker = anchor;
!this._markerDragend && this._marker.addEventListener( "dragend", this._markerDragend = function ( e ) {
me._point = e.point;
me._adjustPosition( me._point );
me._panBox();
me.show();
} );
//给marker绑定dragging事件,拖动marker的时候,searchInfoWindow也跟随移动
!this._markerDragging && this._marker.addEventListener( "dragging", this._markerDragging = function () {
me.hide();
me._point = me._marker.getPosition();
me._adjustPosition( me._point );
} );
}
//打开的时候,将infowindow显示
this.show();
this._point = poi;
this._panBox();
this._adjustPosition( this._point );
}
/**
* 关闭searchInfoWindow
* @return none
*
* @example <b>参考示例:</b><br />
* searchInfoWindow.close();
*/
SearchInfoWindow.prototype.close = function () {
if ( this._isOpen ) {
this._map.removeOverlay( this );
this._disposeAutoComplete();
this._isOpen = false;
//取消地图地点事件监听,防止事件重复触发
this._map.removeEventListener( "click", this.mapClickFunction );
this._dispatchEvent( this, "close", { "point": this._point } );
}
}
/**
* 打开searchInfoWindow时,派发事件的接口
* @name SearchInfoWindow#Open
* @event
* @param {Event Object} e 回调函数会返回event参数,包括以下返回值:
* <br />{"<b>target</b> : {BMap.Overlay} 触发事件的元素,
* <br />"<b>type</b>:{String} 事件类型,
* <br />"<b>point</b>:{Point} searchInfoWindow的打开位置}
*
* @example <b>参考示例:</b>
* searchInfoWindow.addEventListener("open", function(e) {
* alert(e.type);
* });
*/
/**
* 关闭searchInfoWindow时,派发事件的接口
* @name SearchInfoWindow#Close
* @event
* @param {Event Object} e 回调函数会返回event参数,包括以下返回值:
* <br />{"<b>target</b> : {BMap.Overlay} 触发事件的元素,
* <br />"<b>type</b>:{String} 事件类型,
* <br />"<b>point</b>:{Point} searchInfoWindow的关闭位置}
*
* @example <b>参考示例:</b>
* searchInfoWindow.addEventListener("close", function(e) {
* alert(e.type);
* });
*/
/**
* 启用自动平移
* @return none
*
* @example <b>参考示例:</b><br />
* searchInfoWindow.enableAutoPan();
*/
SearchInfoWindow.prototype.enableAutoPan = function () {
this._opts.enableAutoPan = true;
}
/**
* 禁用自动平移
* @return none
*
* @example <b>参考示例:</b><br />
* searchInfoWindow.disableAutoPan();
*/
SearchInfoWindow.prototype.disableAutoPan = function () {
this._opts.enableAutoPan = false;
}
/**
* 设置searchInfoWindow的内容
* @param {String|HTMLElement} content 弹出气泡中的内容,支持HTML格式
* @return none
*
* @example <b>参考示例:</b><br />
* searchInfoWindow.setContent("百度地图API");
*/
SearchInfoWindow.prototype.setContent = function ( content ) {
this._setContent( content );
this._getSearchInfoWindowSize();
this._adjustPosition( this._point );
},
/**
* 设置searchInfoWindow的内容
* @param {String|HTMLElement} title 弹出气泡中的内容,支持HTML格式
* @return none
*
* @example <b>参考示例:</b><br />
* searchInfoWindow.setTitle("百度地图API");
*/
SearchInfoWindow.prototype.setTitle = function ( title ) {
this.dom.title.innerHTML = title;
this._opts._title = title;
}
/**
* 获取searchInfoWindow的内容
* @return {String} String
*
* @example <b>参考示例:</b><br />
* alret(searchInfoWindow.getContent());
*/
SearchInfoWindow.prototype.getContent = function () {
return this.dom.content.innerHTML;
},
/**
* 获取searchInfoWindow的标题
* @return {String} String
*
* @example <b>参考示例:</b><br />
* alert(searchInfoWindow.getTitle());
*/
SearchInfoWindow.prototype.getTitle = function () {
return this.dom.title.innerHTML;
}
/**
* 设置信息窗的地理位置
* @param {Point} point 设置position
* @return none
*
* @example <b>参考示例:</b><br />
* searchInfoWindow.setPosition(new BMap.Point(116.35,39.911));
*/
SearchInfoWindow.prototype.setPosition = function ( poi ) {
this._point = poi;
this._adjustPosition( poi );
this._panBox();
this._removeMarkerEvt();
}
/**
* 获得信息窗的地理位置
* @return {Point} 信息窗的地理坐标
*
* @example <b>参考示例:</b><br />
* searchInfoWindow.getPosition();
*/
SearchInfoWindow.prototype.getPosition = function () {
return this._point;
}
/**
* 返回信息窗口的箭头距离信息窗口在地图
* 上所锚定的地理坐标点的像素偏移量。
* @return {Size} Size
*
* @example <b>参考示例:</b><br />
* searchInfoWindow.getOffset();
*/
SearchInfoWindow.prototype.getOffset = function () {
return this._opts.offset;
},
baidu.object.extend( SearchInfoWindow.prototype, {
/**
* 保持屏幕只有一个searchInfoWindow,关闭现在已打开的searchInfoWindow
*/
_closeOtherSearchInfo: function () {
var instance = BMapLib.SearchInfoWindow.instance,
len = instance.length;
while ( len-- ) {
if ( instance[len]._isOpen ) {
instance[len].close();
}
}
},
/**
* 设置searchInfoWindow的内容
* @param {String|HTMLElement} content 弹出气泡中的内容
* @return none
*
* @example <b>参考示例:</b><br />
* searchInfoWindow.setContent("百度地图API");
*/
_setContent: function ( content ) {
if ( !this.dom || !this.dom.content ) {
return;
}
//string类型的content
if ( typeof content.nodeType === "undefined" ) {
this.dom.content.innerHTML = content;
} else {
this.dom.content.appendChild( content );
}
var me = this;
me._adjustContainerWidth();
this._content = content;
},
/**
* 调整searchInfoWindow的position
* @return none
*/
_adjustPosition: function ( poi ) {
var pixel = this._getPointPosition( poi );
var icon = this._marker && this._marker.getIcon();
if ( this._marker ) {
this.container.style.bottom = -( pixel.y - this._opts.offset.height - icon.anchor.height + icon.infoWindowAnchor.height ) - this._marker.getOffset().height + 2 + 30 + "px";
this.container.style.left = pixel.x - icon.anchor.width + this._marker.getOffset().width + icon.infoWindowAnchor.width - this._boxWidth / 2 + 28 + "px";
} else {
this.container.style.bottom = -( pixel.y - this._opts.offset.height ) + 30 + "px";
this.container.style.left = pixel.x - this._boxWidth / 2 + 25 + "px";
}
},
/**
* 得到searchInfoWindow的position
* @return Point searchInfoWindow当前的position
*/
_getPointPosition: function ( poi ) {
this._pointPosition = this._map.pointToOverlayPixel( poi );
return this._pointPosition;
},
/**
* 得到searchInfoWindow的高度跟宽度
* @return none
*/
_getSearchInfoWindowSize: function () {
this._boxWidth = parseInt( this.container.offsetWidth, 10 );
this._boxHeight = parseInt( this.container.offsetHeight, 10 );
},
/**
* 阻止事件冒泡
* @return none
*/
_stopBubble: function ( e ) {
if ( e && e.stopPropagation ) {
e.stopPropagation();
} else {
window.event.cancelBubble = true;
}
},
/**
* 自动平移searchInfoWindow,使其在视野中全部显示
* @return none
*/
_panBox: function () {
if ( !this._opts.enableAutoPan ) {
return;
}
var mapH = parseInt( this._map.getContainer().offsetHeight, 10 ),
mapW = parseInt( this._map.getContainer().offsetWidth, 10 ),
boxH = this._boxHeight,
boxW = this._boxWidth;
//searchInfoWindow窗口本身的宽度或者高度超过map container
if ( boxH >= mapH || boxW >= mapW ) {
return;
}
//如果point不在可视区域内
if ( !this._map.getBounds().containsPoint( this._point ) ) {
this._map.setCenter( this._point );
}
var anchorPos = this._map.pointToPixel( this._point ),
panTop, panY,
//左侧超出
panLeft = boxW / 2 - 28 - anchorPos.x + 10,
//右侧超出
panRight = boxW / 2 + 28 + anchorPos.x - mapW + 10;
if ( this._marker ) {
var icon = this._marker.getIcon();
}
//上侧超出
var h = this._marker ? icon.anchor.height + this._marker.getOffset().height - icon.infoWindowAnchor.height : 0;
panTop = boxH - anchorPos.y + this._opts.offset.height + h + 31 + 10;
panX = panLeft > 0 ? panLeft : ( panRight > 0 ? -panRight : 0 );
panY = panTop > 0 ? panTop : 0;
this._map.panBy( panX, panY );
},
_removeMarkerEvt: function () {
this._markerDragend && this._marker.removeEventListener( "dragend", this._markerDragend );
this._markerDragging && this._marker.removeEventListener( "dragging", this._markerDragging );
this._markerDragend = this._markerDragging = null;
},
/**
* 集中派发事件函数
*
* @private
* @param {Object} instance 派发事件的实例
* @param {String} type 派发的事件名
* @param {Json} opts 派发事件里添加的参数,可选
*/
_dispatchEvent: function ( instance, type, opts ) {
type.indexOf( "on" ) != 0 && ( type = "on" + type );
var event = new baidu.lang.Event( type );
if ( !!opts ) {
for ( var p in opts ) {
event[p] = opts[p];
}
}
instance.dispatchEvent( event );
},
/**
* 检索infowindow模板的初始化操作
*/
_initSearchTemplate: function () {
this._initDom();
this._initPanelTemplate();
this.setTitle( this._opts._title );
if ( this._opts.height ) {
this.dom.content.style.height = parseInt( this._opts.height, 10 ) + "px";
}
this._setContent( this._content );
this._initService();
this._bind();
if ( this._opts._searchTypes ) {
this._setSearchTypes();
}
this._mendIE6();
},
/**
* 创建检索模板
* @return dom
*/
_createSearchTemplate: function () {
if ( !this._div ) {
var div = baidu.dom.create( 'div', {
"class": "BMapLib_SearchInfoWindow",
"id": "BMapLib_SearchInfoWindow" + this.guid
} );
var template = [
'<div class="BMapLib_bubble_top">',
'<div class="BMapLib_bubble_title" id="BMapLib_bubble_title' + this.guid + '"></div>',
'<div class="BMapLib_bubble_tools">',
'<div class="BMapLib_bubble_close" title="关闭" id="BMapLib_bubble_close' + this.guid + '">',
'</div>',
'<div class="BMapLib_sendToPhone" title="发送到手机" id="BMapLib_sendToPhone' + this.guid + '">',
'</div>',
'</div>',
'</div>',
'<div class="BMapLib_bubble_center">',
'<div class="BMapLib_bubble_content" id="BMapLib_bubble_content' + this.guid + '">',
'</div>',
'<div class="BMapLib_nav" id="BMapLib_nav' + this.guid + '">',
'<ul class="BMapLib_nav_tab" id="BMapLib_nav_tab' + this.guid + '">', //tab选项卡
'<li class="BMapLib_first BMapLib_current" id="BMapLib_tab_search' + this.guid + '" style="display:block;">',
'<span class="BMapLib_icon BMapLib_icon_nbs"></span>在附近找',
'</li>',
'<li class="" id="BMapLib_tab_tohere' + this.guid + '" style="display:block;">',
'<span class="BMapLib_icon BMapLib_icon_tohere"></span>到这里去',
'</li>',
'<li class="" id="BMapLib_tab_fromhere' + this.guid + '" style="display:block;">',
'<span class="BMapLib_icon BMapLib_icon_fromhere"></span>从这里出发',
'</li>',
'</ul>',
'<ul class="BMapLib_nav_tab_content">', //tab内容
'<li id="BMapLib_searchBox' + this.guid + '">',
'<table width="100%" align="center" border=0 cellpadding=0 cellspacing=0>',
'<tr><td style="padding-left:8px;"><input id="BMapLib_search_text' + this.guid + '" class="BMapLib_search_text" type="text" maxlength="100" autocomplete="off"></td><td width="55" style="padding-left:7px;"><input id="BMapLib_search_nb_btn' + this.guid + '" type="submit" value="搜索" class="iw_bt"></td></tr>',
'</table>',
'</li>',
'<li id="BMapLib_transBox' + this.guid + '" style="display:none">',
'<table width="100%" align="center" border=0 cellpadding=0 cellspacing=0>',
'<tr><td width="30" style="padding-left:8px;"><div id="BMapLib_stationText' + this.guid + '">起点</div></td><td><input id="BMapLib_trans_text' + this.guid + '" class="BMapLib_trans_text" type="text" maxlength="100" autocomplete="off"></td><td width="106" style="padding-left:7px;"><input id="BMapLib_search_bus_btn' + this.guid + '" type="button" value="公交" class="iw_bt" style="margin-right:5px;"><input id="BMapLib_search_drive_btn' + this.guid + '" type="button" class="iw_bt" value="驾车"></td></tr>',
'</table>',
'</li>',
'</ul>',
'</div>',
'</div>',
'<div class="BMapLib_bubble_bottom"></div>',
'<img src="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/iw_tail.png" width="58" height="31" alt="" class="BMapLib_trans" id="BMapLib_trans' + this.guid + '" style="left:144px;"/>'
];
div.innerHTML = template.join( "" );
this._div = div;
}
return this._div;
},
/**
* 创建面板
*/
_initPanelTemplate: function () {
var panel = baidu.g( this._opts._panel );
if ( !this.dom.panel && panel ) {
panel.innerHTML = "";
this.dom.panel = panel;
//供地址选择页用的提示文字
var address = baidu.dom.create( 'div' );
address.style.cssText = "display:none;background:#FD9;height:30px;line-height:30px;text-align:center;font-size:12px;color:#994C00;";
panel.appendChild( address );
this.dom.panel.address = address;
//供地址检索面板用
var localSearch = baidu.dom.create( 'div' );
panel.appendChild( localSearch );
this.dom.panel.localSearch = localSearch;
}
},
/**
* 获取相关的DOM元素
*/
_initDom: function () {
if ( !this.dom ) {
this.dom = {
container: baidu.g( "BMapLib_SearchInfoWindow" + this.guid ) //容器
, content: baidu.g( "BMapLib_bubble_content" + this.guid ) //主内容
, title: baidu.g( "BMapLib_bubble_title" + this.guid ) //标题
, closeBtn: baidu.g( "BMapLib_bubble_close" + this.guid ) //关闭按钮
, transIco: baidu.g( "BMapLib_trans" + this.guid ) //infowindow底下三角形
, navBox: baidu.g( "BMapLib_nav" + this.guid ) //检索容器
, navTab: baidu.g( "BMapLib_nav_tab" + this.guid ) //tab容器
, seartTab: baidu.g( "BMapLib_tab_search" + this.guid ) //在附近找tab
, tohereTab: baidu.g( "BMapLib_tab_tohere" + this.guid ) //到这里去tab
, fromhereTab: baidu.g( "BMapLib_tab_fromhere" + this.guid ) //从这里出发tab
, searchBox: baidu.g( "BMapLib_searchBox" + this.guid ) //普通检索容器
, transBox: baidu.g( "BMapLib_transBox" + this.guid ) //公交驾车检索容器,从这里出发和到这里去公用一个容器
, stationText: baidu.g( "BMapLib_stationText" + this.guid ) //起点或终点文本
, nbBtn: baidu.g( "BMapLib_search_nb_btn" + this.guid ) //普通检索按钮
, busBtn: baidu.g( "BMapLib_search_bus_btn" + this.guid ) //公交驾车检索按钮
, driveBtn: baidu.g( "BMapLib_search_drive_btn" + this.guid ) //驾车检索按钮
, searchText: baidu.g( "BMapLib_search_text" + this.guid ) //普通检索文本框
, transText: baidu.g( "BMapLib_trans_text" + this.guid ) //公交驾车检索文本框
, sendToPhoneBtn: baidu.g( "BMapLib_sendToPhone" + this.guid ) //发送到手机
}
this.container = this.dom.container;
}
},
/**
* 设置infowindow内容的宽度
*/
_adjustContainerWidth: function () {
var width = 250,
height = 0;
if ( this._opts.width ) {
width = parseInt( this._opts.width, 10 );
width += 10;
} else {
width = parseInt( this.dom.content.offsetWidth, 10 );
}
if ( width < 250 ) {
width = 250;
}
this._width = width;
//设置container的宽度
this.container.style.width = this._width + "px";
this._adjustTransPosition();
},
/**
* 调整infowindow下三角形的位置
*/
_adjustTransPosition: function () {
//调整三角形的位置
this.dom.transIco.style.left = this.container.offsetWidth / 2 - 2 - 29 + "px";
this.dom.transIco.style.top = this.container.offsetHeight - 2 + "px";
},
/**
* 初始化各检索服务
*/
_initService: function () {
var map = this._map;
var me = this;
var renderOptions = {}
renderOptions.map = map;
if ( this.dom.panel ) {
renderOptions.panel = this.dom.panel.localSearch;
}
if ( !this.localSearch ) {
this.localSearch = new BMap.LocalSearch( map, {
renderOptions: renderOptions
, onSearchComplete: function ( result ) {
me._clearAddress();
me._drawCircleBound();
}
} );
}
if ( !this.transitRoute ) {
this.transitRoute = new BMap.TransitRoute( map, {
renderOptions: renderOptions
, onSearchComplete: function ( results ) {
me._transitRouteComplete( me.transitRoute, results );
}
} );
}
if ( !this.drivingRoute ) {
this.drivingRoute = new BMap.DrivingRoute( map, {
renderOptions: renderOptions
, onSearchComplete: function ( results ) {
me._transitRouteComplete( me.drivingRoute, results );
}
} );
}
},
/**
* 绑定事件
*/
_bind: function () {
var me = this;
//关闭按钮
baidu.on( this.dom.closeBtn, "click", function ( e ) {
me.close();
} );
//发送到手机按钮
baidu.on( this.dom.sendToPhoneBtn, "click", function ( e ) {
me._sendToPhone();
} );
//周边检索tab键
baidu.on( this.dom.seartTab, "click", function ( e ) {
me._showTabContent( BMAPLIB_TAB_SEARCH );
} );
//到这里去tab
baidu.on( this.dom.tohereTab, "click", function ( e ) {
me._showTabContent( BMAPLIB_TAB_TO_HERE );
} );
//从这里出发tab
baidu.on( this.dom.fromhereTab, "click", function ( e ) {
me._showTabContent( BMAPLIB_TAB_FROM_HERE );
} );
//周边检索按钮
baidu.on( this.dom.nbBtn, "click", function ( e ) {
me._localSearchAction();
} );
//公交检索按钮
baidu.on( this.dom.busBtn, "click", function ( e ) {
me._transitRouteAction( me.transitRoute );
} );
//驾车检索按钮
baidu.on( this.dom.driveBtn, "click", function ( e ) {
me._transitRouteAction( me.drivingRoute );
} );
//文本框自动完成提示
this._autoCompleteIni();
if ( this._opts.enableSendToPhone === false ) {
this.dom.sendToPhoneBtn.style.display = 'none';
}
},
/**
* 显示tab内容
*/
_showTabContent: function ( type ) {
this._hideAutoComplete();
var tabs = this.dom.navTab.getElementsByTagName( "li" ),
len = tabs.length;
for ( var i = 0, len = tabs.length; i < len; i++ ) {
tabs[i].className = "";
}
//显示当前tab content并高亮tab
switch ( type ) {
case BMAPLIB_TAB_SEARCH:
this.dom.seartTab.className = "BMapLib_current";
this.dom.searchBox.style.display = "block";
this.dom.transBox.style.display = "none";
break;
case BMAPLIB_TAB_TO_HERE:
this.dom.tohereTab.className = "BMapLib_current";
this.dom.searchBox.style.display = "none";
this.dom.transBox.style.display = "block";
this.dom.stationText.innerHTML = "起点";
this._pointType = "endPoint";
break;
case BMAPLIB_TAB_FROM_HERE:
this.dom.fromhereTab.className = "BMapLib_current";
this.dom.searchBox.style.display = "none";
this.dom.transBox.style.display = "block";
this.dom.stationText.innerHTML = "终点";
this._pointType = "startPoint";
break;
}
this._firstTab.className += " BMapLib_first";
},
/**
* 绑定自动完成事件
*/
_autoCompleteIni: function () {
this.searchAC = new BMap.Autocomplete( {
"input": this.dom.searchText
, "location": this._map
} );
this.transAC = new BMap.Autocomplete( {
"input": this.dom.transText
, "location": this._map
} );
},
/**
* 关闭autocomplete
*/
_hideAutoComplete: function () {
this.searchAC.hide();
this.transAC.hide();
},
/**
* 销毁autoComplete对象
*/
_disposeAutoComplete: function () {
this.searchAC.dispose();
this.transAC.dispose();
},
/**
* 触发localsearch事件
*/
_localSearchAction: function () {
var kw = this._kw = this.dom.searchText.value;
if ( kw == "" ) {
//检测是否为空
this.dom.searchText.focus();
} else {
this._reset();
this.close();
var radius = this._radius = 1000;
this.localSearch.searchNearby( kw, this._point, radius );
}
},
/**
* 画周边检索的圆形圈
*/
_drawCircleBound: function () {
this._closeCircleBound();
var circle = this._searchCircle = new BMap.Circle( this._point, this._radius, {
strokeWeight: 3,
strokeOpacity: 0.4,
strokeColor: "#e00",
filColor: "#00e",
fillOpacity: 0.4
} );
var label = this._searchLabel = new RadiusToolBar( this._point, this.guid );
this._map.addOverlay( circle );
this._map.addOverlay( label );
this._hasCircle = true;
},
/**
* 修改周边检索的半径
*/
_changeSearchRadius: function () {
var radius = parseInt( baidu.g( "BMapLib_search_radius" + this.guid ).value, 10 );
if ( radius > 0 && radius != this._radius ) {
this._radius = radius;
this.localSearch.searchNearby( this._kw, this._point, radius );
this._closeCircleBound();
}
},
/**
* 关闭周边检索的圆形圈
*/
_closeCircleBound: function ( radius ) {
if ( this._searchCircle ) {
this._map.removeOverlay( this._searchCircle );
}
if ( this._searchLabel ) {
this._map.removeOverlay( this._searchLabel );
}
this._hasCircle = false;
},
/**
* 公交驾车检索查询
*/
_transitRouteAction: function ( transitDrive ) {
var kw = this.dom.transText.value;
if ( kw == "" ) {
//检测是否为空
this.dom.transText.focus();
} else {
this._reset();
this.close();
var transPoi = this._getTransPoi( kw );
transitDrive.search( transPoi.start, transPoi.end );
}
},
/**
* 公交驾车查询结束操作
*/
_transitRouteComplete: function ( transitDrive, results ) {
this._clearAddress();
var status = transitDrive.getStatus();
//导航结果未知的情况
if ( status == BMAP_STATUS_UNKNOWN_ROUTE ) {
var startStatus = results.getStartStatus(),
endStatus = results.getEndStatus(),
tip = "";
tip = "找不到相关的线路";
if ( startStatus == BMAP_ROUTE_STATUS_EMPTY && endStatus == BMAP_ROUTE_STATUS_EMPTY ) {
tip = "找不到相关的起点和终点";
} else {
if ( startStatus == BMAP_ROUTE_STATUS_EMPTY ) {
tip = "找不到相关的起点";
}
if ( endStatus == BMAP_ROUTE_STATUS_EMPTY ) {
tip = "找不到相关的终点";
}
}
//当前搜索的点找不到明确的路线,但是可以检索到poi点
if ( this._pointType == "startPoint" && endStatus == BMAP_ROUTE_STATUS_ADDRESS || this._pointType == "endPoint" && startStatus == BMAP_ROUTE_STATUS_ADDRESS ) {
this._searchAddress( transitDrive );
} else {
this.dom.panel.address.style.display = "block";
this.dom.panel.address.innerHTML = tip;
}
}
},
/**
* 检索起点或终点的可选地址
*/
_searchAddress: function ( transitDrive ) {
var me = this;
var panel = this.dom.panel;
if ( !this.lsAddress ) {
var renderOptions = { map: this._map };
if ( panel ) {
renderOptions.panel = this.dom.panel.localSearch;
}
this.lsAddress = new BMap.LocalSearch( this._map, { renderOptions: renderOptions } );
}
var station = me._pointType == "startPoint" ? "终点" : "起点";
if ( panel ) {
this.dom.panel.address.style.display = "block";
this.dom.panel.address.innerHTML = "请选择准确的" + station;
}
this.lsAddress.setInfoHtmlSetCallback( function ( poi, html ) {
var button = document.createElement( 'div' );
button.style.cssText = "position:relative;left:50%;margin:5px 0 0 -30px;width:60px;height:27px;line-height:27px;border:1px solid #E0C3A6;text-align:center;color:#B35900;cursor:pointer;background-color:#FFEECC;border-radius:2px; background-image: -webkit-gradient(linear, left top, left bottom, from(#FFFDF8), to(#FFEECC))";
button.innerHTML = '设为' + station;
html.appendChild( button );
baidu.on( button, "click", function () {
me._clearAddress();
var nowPoint = poi.marker.getPosition();
if ( station == "起点" ) {
transitDrive.search( nowPoint, me._point );
} else {
transitDrive.search( me._point, nowPoint );
}
} );
} );
this._reset();
this.lsAddress.search( this.dom.transText.value );
},
/**
* 获取公交驾车的起终点
*/
_getTransPoi: function ( kw ) {
var start, end;
if ( this._pointType == "startPoint" ) {
start = this._point;
end = kw;
} else {
start = kw;
end = this._point;
}
return {
"start": start,
"end": end
}
},
/**
* 设置当前可提供的检索类型
*/
_setSearchTypes: function () {
var searchTypes = this._unique( this._opts._searchTypes ),
navTab = this.dom.navTab,
tabs = [this.dom.seartTab, this.dom.tohereTab, this.dom.fromhereTab],
i = 0,
len = 0,
curIndex = 0,
tab;
this.tabLength = searchTypes.length;
tabWidth = Math.floor(( this._width - this.tabLength + 1 ) / this.tabLength );
if ( searchTypes.length == 0 ) {
//若为空则不显示检索面板
this.dom.navBox.style.display = "none";
} else {
for ( i = 0, len = tabs.length; i < len; i++ ) {
tabs[i].className = "";
tabs[i].style.display = "none";
}
for ( i = 0; i < this.tabLength; i++ ) {
tab = tabs[searchTypes[i]];
if ( i == 0 ) {
tab.className = "BMapLib_first BMapLib_current";
this._firstTab = tab;
curIndex = searchTypes[i];
}
if ( i == this.tabLength - 1 ) {
//最后一个tab的宽度
var lastWidth = this._width - ( this.tabLength - 1 ) * ( tabWidth + 1 );
if ( baidu.browser.ie == 6 ) {
tab.style.width = lastWidth - 3 + "px";
} else {
tab.style.width = lastWidth + "px";
}
} else {
tab.style.width = tabWidth + "px";
}
tab.style.display = "block";
}
//按照数组顺序排序tab
if ( searchTypes[1] != undefined ) {
navTab.appendChild( tabs[searchTypes[1]] )
}
if ( searchTypes[2] != undefined ) {
navTab.appendChild( tabs[searchTypes[2]] )
}
this._showTabContent( curIndex );
}
this._adjustTransPosition();
},
/**
* 对用户提供的检索类型去重,并剔除无效的结果
*/
_unique: function ( arr ) {
var len = arr.length,
result = arr.slice( 0 ),
i,
datum;
// 从后往前双重循环比较
// 如果两个元素相同,删除后一个
while ( --len >= 0 ) {
datum = result[len];
if ( datum < 0 || datum > 2 ) {
result.splice( len, 1 );
continue;
}
i = len;
while ( i-- ) {
if ( datum == result[i] ) {
result.splice( len, 1 );
break;
}
}
}
return result;
},
/**
* 清除最近的结果
*/
_reset: function () {
this.localSearch.clearResults();
this.transitRoute.clearResults();
this.drivingRoute.clearResults();
this._closeCircleBound();
this._hideAutoComplete();
},
/**
* 清除地址选择页结果
*/
_clearAddress: function () {
if ( this.lsAddress ) {
this.lsAddress.clearResults();
}
if ( this.dom.panel ) {
this.dom.panel.address.style.display = "none";
}
},
/**
* IE6下处理PNG半透明
* @param {Object} infoWin
*/
_mendIE6: function ( infoWin ) {
if ( !baidu.browser.ie || baidu.browser.ie > 6 ) {
return;
}
var popImg = this.container.getElementsByTagName( "IMG" );
for ( var i = 0; i < popImg.length; i++ ) {
if ( popImg[i].src.indexOf( '.png' ) < 0 ) {
continue;
}
popImg[i].style.cssText += ';FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + popImg[i].src + ',sizingMethod=crop)'
popImg[i].src = "http://api.map.baidu.com/images/blank.gif";
}
},
/**
* 发送到手机
*/
_sendToPhone: function () {
this.showPopup();
},
/**
* 弹出信息框
*/
showPopup: function () {
if ( !this.pop ) {
this.pop = new Popup( this );
}
this._map.addOverlay( this.pop );
}
} );
// 显示半径的自定义label
function RadiusToolBar( point, guid ) {
this._point = point;
this.guid = guid;
}
RadiusToolBar.prototype = new BMap.Overlay();
RadiusToolBar.prototype.initialize = function ( map ) {
this._map = map;
var div = this._div = document.createElement( "div" );
function stopBubble( e ) {
if ( e && e.stopPropagation ) {
e.stopPropagation();
} else {
window.event.cancelBubble = true;
}
}
baidu.on( div, 'mousedown', stopBubble );
baidu.on( div, 'click', stopBubble );
baidu.on( div, 'dblclick', stopBubble );
var searchInfoWindow = BMapLib.SearchInfoWindow.instance[this.guid];
div.style.cssText = 'position:absolute;white-space:nowrap;background:#fff;padding:1px;border:1px solid red;z-index:99;';
div.innerHTML = '<input type="text" value="' + searchInfoWindow._radius + '" style="width:30px;" id="BMapLib_search_radius' + this.guid + '"/>m <a href="javascript:void(0)" title="修改" onclick="BMapLib.SearchInfoWindow.instance[' + this.guid + ']._changeSearchRadius()" style="font-size:12px;text-decoration:none;color:blue;">修改</a><img src="http://api.map.baidu.com/images/iw_close1d3.gif" alt="关闭" title="关闭" style="cursor:pointer;padding:0 5px;" onclick="BMapLib.SearchInfoWindow.instance[' + this.guid + ']._closeCircleBound()"/>';
map.getPanes().labelPane.appendChild( div );
return div;
}
RadiusToolBar.prototype.draw = function () {
var map = this._map;
var pixel = map.pointToOverlayPixel( this._point );
this._div.style.left = pixel.x + 10 + "px";
this._div.style.top = pixel.y - 25 + "px";
}
//后端服务地址
var serviceHost = "http://api.map.baidu.com";
/**
* 创建弹层对象
*/
function Popup( iw ) {
this.iw = iw;
}
Popup.prototype = new BMap.Overlay();
baidu.extend( Popup.prototype, {
initialize: function ( map ) {
var me = this;
this._map = map;
this.container = this.generalDom();
this._map.getContainer().appendChild( this.container );
this.initDom();
this.bind();
this.getAddressByPoint();
this.getRememberPhone();
this.addPhoneNum = 0;
return this.container;
},
draw: function () {
},
generalDom: function () {
var dom = document.createElement( 'div' ),
size = this._map.getSize(),
top = 0,
left = 0;
if ( size.width > 450 ) {
left = ( size.width - 450 ) / 2;
}
if ( size.height > 260 ) {
top = ( size.height - 260 ) / 2;
}
dom.style.cssText = "position:absolute;background:#fff;width:480px;height:260px;top:" + top + "px;left:" + left + "px;ovflow:hidden;";
var html = [
'<div class="BMapLib_sms_tab_container">',
'<span>发送到手机</span>',
'<span id="BMapLib_sms_tip" style="display:none;">',
'</span>',
'</div>',
'<div id="BMapLib_sms_pnl_phone" class="BMapLib_sms_pnl_phone" style="display: block;">',
'<div class="BMapLib_ap" id="pnl_phone_left" style="display: block;">',
'<table>',
'<tr>',
'<th>发送方手机号</th>',
'<td><input type="text" bid="" id="BMapLib_phone_0" maxlength="11" class="BMapLib_sms_input BMapLib_sms_input_l" /><span id="BMapLib_activateTip"></span></td>',
'</tr>',
'<tr id="BMapLib_activateBox" style="display:none;">',
'<th>激活码</th>',
'<td><input type="text" id="BMapLib_activate" class="BMapLib_sms_input BMapLib_sms_input_s" maxlength="4"/><input type="button" value="获取" id="BMapLib_activate_btn" bid="activate" />',
'</tr>',
'<tr>',
'<th></th>',
'<td>',
'</td>',
'</tr>',
'<tr>',
'<th style="vertical-align:top;padding-top:7px;">接收方手机号</th>',
'<td><div><input type="text" id="BMapLib_phone_1" class="BMapLib_sms_input BMapLib_sms_input_l" maxlength="11"/><input type="checkbox" id="BMapLib_is_remember_phone"/>记住此号</div>',
'<div id="BMapLib_add_phone_con"></div>',
'<div><a href="javascript:void(0)" id="BMapLib_add_phone_btn" bid="addPhone">新增</a></div>',
'</td>',
'</tr>',
'<tr>',
'<th></th>',
'<td ><input type="text" id="BMapLib_ver_input" maxlength="4" style="width:67px;border: 1px solid #a5acb2;vertical-align: middle;height:18px;" tabindex="5" placeholder="验证码"><img width="69" height="20" id="BMapLib_ver_image" bid="BMapLib_ver_image" style="border: 1px solid #d5d5d5;vertical-align:middle;margin-left: 5px;" alt="点击更换数字" title="点击更换数字"></td>',
'</tr>',
'<tr>',
'<th></th>',
'<td><input type="button" value="免费发送到手机" bid="sendToPhoneBtn"/></td>',
'</tr>',
'</table>',
'</div>',
'<div class="BMapLib_mp" id="pnl_phone_right" style="display: block;">',
'<div class="BMapLib_mp_title">短信内容:</div>',
'<div id="BMapLib_msgContent" class="BMapLib_msgContent"></div>',
'</div>',
'<div style="clear:both;"></div>',
'<p id="BMapLib_sms_declare_phone" class="BMapLib_sms_declare_phone">百度保证不向任何第三方提供输入的手机号码</p>',
'<div id="tipError" class="tip fail" style="display:none;">',
'<span id="tipText"></span>',
'<a href="javascript:void(0)" id="tipClose" class="cut"></a>',
'</div>',
'<div id="sms_lack_tip" style="display:none;">已达每日5次短信上限</div>',
'<div id="sms_unlogin_tip" style="display:none;">',
'<div style="padding-left:40px;">',
'<ul class="login_ul"><li id="normal_login-2" class="login_hover"><a href="javascript:void(0)">手机登录</a></li></ul>',
'<div id="loginBox_02" class="loginBox">',
'<div id="pass_error_info-2" class="pass_error_style"></div>',
'<div id="passports-2"></div>',
'<div id="loginIframe_iph-2" style="display:none"></div>',
'</div>',
'</div>',
'<div class="nopass" style="padding-left:128px;">没有百度帐号?<a href="https://passport.baidu.com/v2/?reg&regType=1&tpl=ma" target="_blank">立即注册</a></div>',
'</div>',
'</div>',
'<button class="BMapLib_popup_close" bid="close"></button>',
'<div id="BMapLib_success_tip" style="display:none;">您的短信已经发送到您的手机,请注意查收!</div>'
].join( '' );
dom.innerHTML = html;
return dom;
},
initDom: function () {
this.dom = {
sms_tip: baidu.g( 'BMapLib_sms_tip' ), //提示框
activate_btn: baidu.g( 'BMapLib_activate_btn' ), //获取激活码按钮
fromphone: baidu.g( "BMapLib_phone_0" ),
tophone: baidu.g( "BMapLib_phone_1" ),
isRememberPhone: baidu.g( "BMapLib_is_remember_phone" ),
sms_container: baidu.g( 'BMapLib_sms_pnl_phone' ),
success_tip: baidu.g( 'BMapLib_success_tip' ), // 发送成功提示框
add_phone_con: baidu.g( 'BMapLib_add_phone_con' ),
add_phone_btn: baidu.g( 'BMapLib_add_phone_btn' ),
activateBox: baidu.g( 'BMapLib_activateBox' ),
activateTip: baidu.g( 'BMapLib_activateTip' ),
activate_input: baidu.g( "BMapLib_activate" ),
ver_image: baidu.g( "BMapLib_ver_image" ),
ver_input: baidu.g( "BMapLib_ver_input" )
}
},
showTip: function ( result ) {
var error = result.error;
var tipObj = {
'PHONE_NUM_INVALID': '手机号码无效',
'SMS_SEND_SUCCESS': '发送到手机成功',
'AK_INVALID': '你所使用的key无效',
'INTERNAL_ERROR': '服务器错误',
'OVER_MAX_ACTIVATE_TIME': '今天已超过发送激活码最大次数',
'SMS_ACTIVATE_SUCCESS': '激活码已发送到您的手机,请注意查收!',
'ACTIVATE_FAIL': '手机激活码无效',
'SMS_LACK': '今天您还能往5个手机发送短信',
'PARAM_INVALID': '请填完所有选项',
'SEND_ACTIVATE_FAIL': '激活码发送失败',
'VCODE_VERITY_FAIL': '验证码校验失败'
}
var tip = tipObj[error];
if ( error == 'SMS_LACK' ) {
var res_sms = result.res_sms;
tip = "今天您还能往" + res_sms + "个手机发送短信";
this.addPhoneNum = res_sms - 1;
}
this.renderImageVer();
if ( tip ) {
this.dom.sms_tip.innerHTML = tip;
this.dom.sms_tip.style.display = "inline";
}
if ( error == 'SMS_SEND_SUCCESS' ) {
this.rememberPhone();
this.sendSuccess();
}
},
//绑定事件
bind: function () {
var me = this;
me.renderImageVer();
baidu.on( this.container, 'click', function ( e ) {
var target = e.target || e.srcElement,
bid = target.getAttribute( 'bid' );
switch ( bid ) {
case 'close':
me.closeActon();
break;
case 'sendToPhoneBtn':
me.sendAction();
break;
case 'activate':
me.activateAction();
break;
case 'addPhone':
me.addPhoneAction();
break;
case 'deletePhone':
me.deletePhoneAction( target );
break;
case 'BMapLib_ver_image':
me.renderImageVer();
}
} );
var phone0 = baidu.g( 'BMapLib_phone_0' );
var phone1 = baidu.g( 'BMapLib_phone_1' );
//限制输入的字符,只能输数字和逗号
this.container.onkeypress = function ( e ) {
var event = e || window.e,
keyCode = event.which || event.keyCode,
result = false;
if ( keyCode >= 48 && keyCode <= 57 || keyCode == 44 || keyCode == 8 ) {
result = true;
}
return result;
};
this.dom.ver_input.onkeypress = function ( e ) {
me._stopBubble( e );
var event = e || window.e,
keyCode = event.which || event.keyCode,
result = false;
if ( keyCode >= 48 && keyCode <= 57 || keyCode >= 65 && keyCode <= 90 || keyCode >= 97 && keyCode <= 122 ) {
result = true;
}
return result;
};
baidu.on( this.dom.fromphone, 'blur', function () {
if ( baidu.isPhone( this.value ) ) {
me.checkActivateAction();
} else {
me.dom.activateTip.innerHTML = "";
me.dom.activateBox.style.display = "none";
}
} );
baidu.on( this.dom.activate_input, 'blur', function () {
if ( baidu.isActivateCode( this.value ) ) {
me.checkActivateAction();
}
} );
},
/**
* 阻止事件冒泡
* @return none
*/
_stopBubble: function ( e ) {
if ( e && e.stopPropagation ) {
e.stopPropagation();
} else {
window.event.cancelBubble = true;
}
},
//请求验证码.
renderImageVer: function () {
var me = this;
//验证码想着绑定
this.request( "http://map.baidu.com/maps/services/captcha?", { "cbName": "cb" }, function ( data ) {
me.vcode = data['content']['vcode'];
me.dom.ver_image.src = 'http://map.baidu.com/maps/services/captcha/image?vcode=' + me.vcode;
} );
},
//验证手机号是否已经激活
checkActivateAction: function () {
var param = {
phone: this.dom.fromphone.value,
activate: this.dom.activate_input.value,
cbName: 'callback'
}
var me = this;
this.request( this.config.ckActivateURL, param, function ( res ) {
if ( !res || res.isactivate == false ) {
//未激活
me.dom.activateBox.style.display = "table-row";
me.dom.activateTip.style.color = "red";
me.dom.activateTip.innerHTML = "未激活";
} else {
//已激活
me.dom.activateBox.style.display = "none";
me.dom.activateTip.style.color = "green";
me.dom.activateTip.innerHTML = "已激活";
}
} );
},
//点击激活按钮事件
activateAction: function () {
var me = this;
var ak = this._map.getKey();
var params = {
phone: this.dom.fromphone.value,
ak: ak,
cbName: "callback"
}
if ( baidu.isPhone( params.phone ) ) {
this.request( this.config.activateURL, params, function ( result ) {
if ( result ) {
me.showTip( result );
}
} );
} else {
this.showTip( {
error: 'PHONE_NUM_INVALID'
} );
}
},
//点击关闭按钮事件
closeActon: function () {
this._map.removeOverlay( this );
},
// 获取短信的内容
getMessage: function () {
},
// 免费发送到手机点击事件
sendAction: function () {
var me = this;
if ( this.validate() ) {
tophoneStr = baidu.g( "BMapLib_phone_1" ).value;
var addPhones = this.dom.add_phone_con.getElementsByTagName( 'input' );
for ( var i = 0, len = addPhones.length; i < len; i++ ) {
if ( baidu.isPhone( addPhones[i].value ) ) {
tophoneStr += ',' + addPhones[i].value;
} else {
this.showTip( {
error: 'PHONE_NUM_INVALID'
} );
return;
}
}
var ak = this._map.getKey();
var params = {
fromphone: baidu.g( "BMapLib_phone_0" ).value, //发送方手机
tophone: tophoneStr, //发送到手机
ak: ak, //用户ak
activate: this.dom.activate_input.value, //激活码
code_input: this.dom.ver_input.value,
vcode: this.vcode,
content: baidu.g( "BMapLib_phone_0" ).value + "分享一个位置给您," + this.messageContent,
cbName: 'callback'
};
this.request( this.config.sendURL, params, function ( result ) {
if ( result ) {
me.showTip( result );
}
} );
}
},
//检验数据格式是否正确
validate: function () {
var flag = true;
if ( !( baidu.isPhone( this.dom.fromphone.value ) && baidu.isPhone( this.dom.tophone.value ) ) ) {
flag = false;
this.showTip( {
error: 'PHONE_NUM_INVALID'
} );
};
return flag;
},
getAddressByPoint: function () {
var pt = this.iw._point,
me = this,
gc = new BMap.Geocoder();
gc.getLocation( pt, function ( rs ) {
if ( rs && rs.addressComponents ) {
var addComp = rs.addressComponents;
me.address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
me.generalMessage();
}
} );
},
generalMessage: function () {
var msgContent = baidu.g( 'BMapLib_msgContent' );
var msg = "";
var iw = this.iw;
var point = iw.getPosition();
if ( this.userPhone ) {
msg += this.userPhone + "分享一个位置给您,";
}
if ( iw.getTitle ) {
msg += "名称为:" + iw.getTitle() + ",";
}
if ( this.address ) {
msg += "大致位置在" + this.address + ",";
}
var uri = "http://api.map.baidu.com/marker?location=" + point.lat + "," + point.lng + "&title=" + encodeURIComponent( iw.getTitle() ) + "&content=" + encodeURIComponent( iw.getContent() ) + "&output=html";
var params = {
url: encodeURIComponent( uri ),
t: new Date().getTime(),
cbName: 'callback'
};
var me = this;
this.request( this.config.shortURL, params, function ( result ) {
msg += "查看地图:" + result.url ? result.url : uri;
me.messageContent = msg;
msgContent.innerHTML = msg;
} );
},
//记住手机号码
rememberPhone: function () {
if ( this.dom.isRememberPhone.checked ) {
var phone = this.dom.tophone.value;
baidu.cookie.set( 'BMapLib_phone', phone, {
path: '/',
expires: 30 * 24 * 60 * 60 * 1000
} );
}
},
//获取记住的手机号码
getRememberPhone: function () {
var phone = baidu.cookie.get( 'BMapLib_phone' );
if ( phone ) {
this.dom.tophone.value = phone;
this.dom.isRememberPhone.checked = true;
}
},
//发送成功后执行
sendSuccess: function () {
this.dom.sms_container.style.display = "none";
this.dom.success_tip.style.display = "block";
var me = this;
setTimeout( function () {
me._map.removeOverlay( me );
}, 1500 );
},
//新增手机号事件
addPhoneAction: function () {
if ( this.addPhoneNum >= 4 ) {
} else {
var div = document.createElement( 'div' );
div.innerHTML = '<input type="text" class="BMapLib_sms_input BMapLib_sms_input_l" maxlength="11"/><a href="javascript:void(0);" style="margin-left:5px;" bid="deletePhone">删除</a>';
this.dom.add_phone_con.appendChild( div );
this.addPhoneNum++;
}
},
//删除一个手机号事件
deletePhoneAction: function ( target ) {
target.parentNode.parentNode.removeChild( target.parentNode );
this.addPhoneNum--;
},
//jsonp 请求
request: function ( url, params, cbk ) {
// 生成随机数
var timeStamp = ( Math.random() * 100000 ).toFixed( 0 );
// 全局回调函数
BMapLib["BMapLib_cbk" + timeStamp] = function ( json ) {
cbk && cbk( json );
delete BMapLib["BMapLib_cbk" + timeStamp];
};
for ( var item in params ) {
if ( item != "cbName" ) {
url += '&' + item + "=" + params[item];
}
}
var me = this;
url += "&" + params.cbName + "=BMapLib.BMapLib_cbk" + timeStamp;
scriptRequest( url );
},
config: {
sendURL: serviceHost + "/ws/message?method=send",
activateURL: serviceHost + "/ws/message?method=activate",
ckActivateURL: serviceHost + "/ws/message?method=ckActivate",
shortURL: "http://j.map.baidu.com/?"
}
} );
/**
* script标签请求
* @param {String} url 请求脚本url
*/
function scriptRequest( url ) {
var script = document.createElement( "script" );
script.setAttribute( "type", "text/javascript" );
script.setAttribute( "src", url );
// 脚本加载完成后进行移除
if ( script.addEventListener ) {
script.addEventListener( 'load', function ( e ) {
var t = e.target || e.srcElement;
t.parentNode.removeChild( t );
}, false );
}
else if ( script.attachEvent ) {
script.attachEvent( 'onreadystatechange', function ( e ) {
var t = window.event.srcElement;
if ( t && ( t.readyState == 'loaded' || t.readyState == 'complete' ) ) {
t.parentNode.removeChild( t );
}
} );
}
// 使用setTimeout解决ie6无法发送问题
setTimeout( function () {
document.getElementsByTagName( 'head' )[0].appendChild( script );
script = null;
}, 1 );
}
//用来存储创建出来的实例
var guid = 0;
BMapLib.SearchInfoWindow.instance = [];
} )();
|
import moment from 'moment';
import isNumber from 'lodash.isnumber';
export default {
format: function format(date, _format) {
return moment(date).format(_format || 'DD/MM/YYYY');
},
parse: function parse(str, format) {
if (!str) return null;
if (isNumber(str)) return moment(str).toDate();
return moment(str, format || 'DD/MM/YYYY').toDate();
},
minusMonth: function minusMonth(number) {
return moment().subtract(number, 'months').toDate();
},
plusYears: function plusYears(number) {
return moment().add(number, 'years').toDate();
},
plusMonths: function plusMonths(number) {
return moment().add(number, 'months').toDate();
},
/**
* timestamp value
* @param value
* @returns {number}
*/
valueOf: function valueOf(value) {
if (!value) return null;
return moment(value).valueOf();
}
}; |
/**
* @file 基础配置
* @author dongkunshan(windwithfo@yeah.net)
*/
import path from 'path';
import webpack from 'webpack';
import entry from '../client/entry';
import Extract from 'extract-text-webpack-plugin';
let entries = Object.assign({}, entry.pages, entry.vendors);
let webpackConfig = {
entry: entries,
resolve: {
modules: [
'node_modules',
path.resolve(__dirname, '../'),
path.resolve(__dirname, '../node_modules')
],
alias: {
component: 'components',
assets: 'assets',
page: 'pages'
},
extensions: ['.web.js', '.js', '.jsx', '.json', '.less', '.css']
},
resolveLoader: {
moduleExtensions: ['-loader']
},
plugins: [
new Extract({
filename: 'css/[name].[contenthash].css',
disable: false,
allChunks: true
}),
new webpack.optimize.CommonsChunkPlugin({
names: ['vendor', 'manifest']
})
],
module: {
rules: [
{
test: /\.js(x)?$/,
use: {
loader: 'babel',
},
exclude: /node_modules/
},
// {
// test: /\.css$/,
// loader: Extract.extract({
// fallback: 'style',
// use: {
// loader: 'css'
// }
// })
// },
// {
// test: /\.less$/,
// loader: Extract.extract({
// fallback: 'style',
// use: [
// {
// loader: 'css'
// },
// {
// loader: 'less'
// }
// ]
// })
// },
{
test: /\.json$/,
use: [{
loader: 'json'
}]
},
// {
// test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
// use: [{
// loader: 'url',
// options: {
// limit: 10000,
// name: 'img/[name].[hash:7].[ext]'
// }
// }]
// },
// {
// test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
// use: [{
// loader: 'url',
// options: {
// limit: 10000,
// name: 'fonts/[name].[hash:7].[ext]'
// }
// }]
// }
]
}
};
export default {
...webpackConfig
};
|
import merge from "../merge"
describe("merge", () => {
it("should merge declarations added by add", () => {
const s = merge({ foo: "bar" }, { bar: "baz", foo: "biz" })
expect(s).toEqual({ bar: "baz", foo: "biz" })
})
it("should recursively merge objects in declarations", () => {
const s = merge({ foo: { biz: "buz" } }, { foo: { baz: "biz" } })
expect(s).toEqual({ foo: { biz: "buz", baz: "biz" } })
})
it("should not merge arrays in declarations", () => {
const s = merge({ foo: [ "buz" ] }, { foo: [ "baz" ] })
expect(s).toEqual({ foo: [ "baz" ] })
})
it("should ignore non plain object as source", () => {
expect(merge({}, null)).toEqual({})
expect(merge({}, undefined)).toEqual({})
expect(merge({}, new Date())).toEqual({})
})
it("should remove null and undefined properties", () => {
expect(merge({ foo: 4 }, { foo: null })).toEqual({})
expect(merge({ foo: 4 }, { foo: undefined })).toEqual({})
})
it("should replace non-plain objects", () => {
expect(merge({ foo: new Date() }, { foo: { bar: "baz" } })).toEqual({ foo: { bar: "baz" } })
})
it("should run a shallow merge if instructed to", () => {
expect(merge({ foo: { bar: 1 } }, { foo: { baz: 2 } }, true)).toEqual({
foo: { baz: 2 },
})
})
})
|
import { Fragment } from 'react';
import Head from 'next/head';
import { getFilteredEvents } from 'helpers/api-utils';
import EventList from 'components/events/event-list';
import ResultsTitle from 'components/results-title/results-title';
import Button from 'components/ui/button';
import ErrorAlert from 'components/ui/error-alert';
function FilteredEventPage({ hasError, notFound, date, filteredEvents, loading }) {
if (loading) {
return <p className='center'>Loading ...</p>;
}
if (hasError) {
return (
<Fragment>
<ErrorAlert>Invalid Filter. Please adjust your value.</ErrorAlert>
<div className='center'>
<Button link='/events'>Show All Events</Button>
</div>
</Fragment>
);
}
if (notFound) {
return (
<Fragment>
<ErrorAlert>No Event found.</ErrorAlert>
<div className='center'>
<Button link='/events'>Show All Events</Button>
</div>
</Fragment>
);
}
const formatedDate = new Date(date.year, date.month - 1);
return (
<div>
<Head>
<title>filteredEvents</title>
<meta name='description' content={`All Events for ${date.month}/${date.year}`} />
</Head>
<ResultsTitle date={formatedDate} />
<EventList items={filteredEvents} />
</div>
);
}
export async function getServerSideProps(context) {
const {
params: { slug: filteredData },
} = context;
const [filteredYear, filteredMonth] = filteredData;
if (!filteredData) {
return { props: { loading: true } };
}
const numYear = +filteredYear;
const numMonth = +filteredMonth;
if (isNaN(numYear) || isNaN(numMonth) || numYear > 2030 || numYear < 2021) {
return { props: { hasError: true } };
}
const filteredEvents = await getFilteredEvents({ year: numYear, month: numMonth });
if (!filteredEvents || filteredEvents.length === 0) {
return { props: { notFound: true } };
}
return { props: { date: { month: numMonth, year: numYear }, filteredEvents } };
}
export default FilteredEventPage;
|
import mongoose from 'mongoose';
const appSchema = mongoose.Schema({
title: {
type: String,
required: true
},
author: {
type: String,
required: true
},
description: {
type: String,
required: true
},
}, { timestamps: true });
export default mongoose.model('appData', appSchema); |
const db = require('../../dbConfig');
const Schools = require('./schoolsModel');
const mockSchools = [
{
name: 'High School',
address: 'Some Street',
funds_required: 500,
funds_donated: 0,
admin_id: 1
},
{
name: 'High School',
address: 'Some Street',
funds_donated: 0,
admin_id: 1
},
]
describe('SCHOOLS MODEL', () => {
beforeEach(async () => {
return await db('schools').truncate();
});
describe('getAllSchools()', () => {
it('should return an array', async () => {
const schools = await Schools.getAllSchools();
expect(Array.isArray(schools)).toBe(true);
});
it('should return all the schools in the database', async () => {
await Schools.addSchool(mockSchools[0]);
const schools = await Schools.getAllSchools();
expect(schools.length).toBe(1);
});
it('should return an empty array is no schools found', async () => {
const schools = await Schools.getAllSchools();
expect(schools.length).toBe(0);
expect(Array.isArray(schools));
});
});
describe('getSchoolById()', () => {
it('should return an array with a single shool', async () => {
await Schools.addSchool(mockSchools[0]);
const school = await Schools.getSchoolById(1);
expect(Array.isArray(school)).toBe(true);
expect(school.length).toBe(1);
});
it('should return the specified school', async () => {
await Schools.addSchool(mockSchools[0]);
const school = await Schools.getSchoolById(1);
expect(school[0].id).toBe(1);
});
it('should return an error message if no school by ID found', async () => {
const school = await Schools.getSchoolById(10);
expect(school).toEqual({ error: 'No School Found' });
});
});
describe('addSchool()', () => {
it('should return the id if the school is successfully added', async () => {
const successfulAdd = await Schools.addSchool(mockSchools[0]);
expect(successfulAdd).toBe(1);
});
it('should add the school to the database', async () => {
await Schools.addSchool(mockSchools[0]);
const school = await Schools.getAllSchools();
expect(school[0].name).toBe('High School');
});
it('should return an error message if a field is missing', async () => {
const failedAdd = await Schools.addSchool(mockSchools[1]);
expect(failedAdd).toEqual({ error: 'Missing Field' });
});
});
describe('editSchool()', () => {
it('should update a school\'s fields', async () => {
await Schools.addSchool(mockSchools[0]);
await Schools.editSchool(1, { name: 'Middle School' });
const school = await Schools.getSchoolById(1);
expect(school[0].name).toBe('Middle School');
});
it('should return an error message if no school found', async () => {
const failedEdit = await Schools.editSchool(10, { name: 'Middle School' });
expect(failedEdit).toEqual({ error: 'No School Found with ID' });
});
it('should return an error message if incorrect field is passed', async () => {
const failedEdit = await Schools.editSchool(1, { something: 'Middle School' });
expect(failedEdit).toEqual({ error: 'Incorrect Fields' });
});
});
describe('deleteSchool()', () => {
it('should remove a school from the database', async () => {
await Schools.addSchool(mockSchools[0]);
await Schools.deleteSchool(1);
const schools = await Schools.getAllSchools();
expect(schools.length).toBe(0);
});
it('should return an error message if no school found', async () => {
const failedDelete = await Schools.deleteSchool(10);
expect(failedDelete).toEqual({ error: 'No School Found By ID' });
});
});
}); |
import React from 'react'
import { Breadcrumb } from 'antd'
const Bread = props => {
let baseStyle = {
height: '60px',
padding: '0 20px',
display: 'flex',
alignItems: 'center',
background: '#fff',
}
return (
<div style={ baseStyle }>
<Breadcrumb>
<Breadcrumb.Item>Home</Breadcrumb.Item>
</Breadcrumb>
</div>
)
}
export default Bread |
require.config({
paths: {
'SubPage1': 'subpage1/subpage1',
'jquery': 'lib/jquery-1.9.1.min'
}
});
function bada() {
console.log('我是bada函数');
//测试点击的时候再加载js文件
require(['jquery'], function(jquery) {
$('#load-js-button').click(function() {
console.log('click load js');
require(['notAMD', 'SubPage1'], function(notAMD, SubPage1) {
not_a_amd_model();
var sub_page_1 = new SubPage1.Sub_Page_1();
sub_page_1.say();
});
});
});
}
|
import React from 'react';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
class DeletDialog extends React.Component {
state = {
open: false,
};
handleClickOpen = () => {
this.setState({ open: true });
};
handleClose = () => {
this.setState({ open: false });
};
handleAgree = () => {
this.setState({ open: false });
fetch(this.props.ServerUrl+'/api/del_pic', {
method: 'POST',
body: JSON.stringify({
pic: this.props.pic
})
}).then(res => {
console.log(res)
window.location.reload()
});
};
render() {
return (
<div>
<div className = "Delet" onClick={this.handleClickOpen}></div>
<Dialog
open={this.state.open}
onClose={this.handleClose}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">{"Warring"}</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
確定是否刪除此張圖片
</DialogContentText>
<div className = "DeletPic">
<img src = {this.props.picPath} alt=""/>
</div>
</DialogContent>
<DialogActions>
<Button onClick={this.handleClose} color="primary">
取消
</Button>
<Button onClick={this.handleAgree} color="primary" autoFocus>
確定
</Button>
</DialogActions>
</Dialog>
</div>
);
}
}
export default DeletDialog;
|
var express = require('express');
var bodyParser=require('body-parser');
var mysql=require('mysql');
var connection=mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'CHAEA'
});
connection.connect(function(error){
if (!!error) {
console.log('Error conectando');
}else {
console.log('Connected');
}
});
var app= express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine','jade');
app.get('/index',function(req,res){
res.render('index');
});
app.get('/',function(req,res){
res.render('index');
});
app.get('/admin',function(req,res){
res.render('administracion');
});
app.get('/cuest',function(req,res){
connection.query('SELECT texto FROM `Grupo`',function(error,rows,fields) {
if (!!error) {
console.log('Error al cargar grupos '+error);
}else {
connection.query('SELECT * FROM `Pregunta`',function(error2,rows2,fields2) {
if (!!error2) {
console.log('Error al cargar preguntas '+error2);
}else {
console.log(rows2);
res.render('cuestionario',{grupos:rows,preguntas:rows2});
}
});
}
});
});
app.post('/verResultado',function(req,res) {
connection.query('SELECT * FROM `Cuestionario` WHERE alumno='+req.body.inputIdAlumno+';',function(error,rows,fields){
if (!!error) {
console.log('Error');
}else {
res.render('verResultado',{resultados:rows});
}
});
});
app.post('/crearGrupo',function(req,res) {
connection.query('INSERT INTO `Grupo`(`texto`) VALUES("'+req.body.inputNombreGrupo+'");',function(error,rows,fields) {
if (!!error) {
console.log('Error creando grupo'+error);
}else{
res.render('grupoCreado');
}
});
});
app.post('/guardarResultados',function(req,res) {
connection.query('SELECT id FROM `Grupo` WHERE texto="'+req.body.selectGrupo+'";',function (error,rows,fields) {
if(!!error){
console.log('error buscando grupos '+error);
}else {
var idGrupo=rows[0].id;
connection.query('INSERT INTO `Alumno`(`grupo`) VALUES('+idGrupo+');',function(error2,rows2,fields2) {
if (!!error2) {
console.log('error creando alumno '+error2);
}else {
console.log('alumno creado');
connection.query('SELECT id FROM `Alumno` ORDER BY id DESC LIMIT 1;',function (error3,rows3,fields3) {
if (!!error3) {
console.log('error obteniendo indice alumno '+error3)
}else {
var idAlumno=rows3[0].id;
var activo=[req.body.pr3,req.body.pr5,req.body.pr7,req.body.pr9,req.body.pr13,req.body.pr20,req.body.pr26,req.body.pr27,req.body.pr35,req.body.pr37,req.body.pr41,req.body.pr43,req.body.pr46,req.body.pr48,req.body.pr51,req.body.pr61,req.body.pr67,req.body.pr74,req.body.pr75,req.body.pr77];
var reflexivo=[req.body.pr10,req.body.pr16,req.body.pr18,req.body.pr19,req.body.pr28,req.body.pr31,req.body.pr32,req.body.pr34,req.body.pr36,req.body.pr39,req.body.pr42,req.body.pr44,req.body.pr49,req.body.pr55,req.body.pr58,req.body.pr63,req.body.pr65,req.body.pr69,req.body.pr70,req.body.pr79];
var teorico=[req.body.pr2,req.body.pr4,req.body.pr6,req.body.pr11,req.body.pr15,req.body.pr17,req.body.pr21,req.body.pr23,req.body.pr25,req.body.pr29,req.body.pr33,req.body.pr45,req.body.pr50,req.body.pr54,req.body.pr60,req.body.pr64,req.body.pr66,req.body.pr71,req.body.pr78,req.body.pr80];
var pragmatico=[req.body.pr1,req.body.pr8,req.body.pr12,req.body.pr14,req.body.pr22,req.body.pr24,req.body.pr30,req.body.pr38,req.body.pr40,req.body.pr47,req.body.pr52,req.body.pr53,req.body.pr56,req.body.pr57,req.body.pr59,req.body.pr62,req.body.pr68,req.body.pr72,req.body.pr73,req.body.pr76];
var cantActivo=contar(activo);
var cantReflexivo=contar(reflexivo);
var cantTeorico=contar(teorico);
var cantPragmatico=contar(pragmatico);
console.log('Activo: '+cantActivo+' reflexivo: '+cantReflexivo+' teorico: '+cantTeorico+' pragmatico: '+cantPragmatico);
connection.query('INSERT INTO `Cuestionario`(`alumno`,`fecha`,`cantActivo`,`cantReflexivo`,`cantTeorico`,`cantPragmatico`) VALUES('+idAlumno+',CURDATE(),'+cantActivo+','+cantReflexivo+','+cantTeorico+','+cantPragmatico+');',function(error4,rows4,fields4) {
if (!!error4) {
console.log('error guardando resultados '+error4);
}else {
connection.query('SELECT * FROM `Cuestionario` WHERE alumno='+idAlumno+';',function (error5,rows5,fields5) {
if (!!error5) {
console.log('error obteniendo resultados '+error5);
} else {
res.render('verResultado',{resultados:rows5});
}
});
}
});
}
});
}
});
}
});
});
function contar(arreglo) {
var contador=0;
for (var i = 0; i < arreglo.length; i++) {
if(arreglo[i]!=undefined){
contador++;
}
}
return contador;
}
app.listen(8080); |
(($) => {
$('.form-field').each((index, el) => {
init($(el), $(el).find('.focus, input, textarea, select'));
});
function init($el, $area) {
const $formField = $el;
const $formFieldArea = $area;
$formFieldArea.on('focus', () => {
setFocusState($formField);
console.log('focus');
});
$formFieldArea.on('blur', () => {
setBlurState($formField);
});
setFilledState($formFieldArea, $formField);
$formFieldArea.on('keyup', () => {
setFilledState($formFieldArea, $formField);
});
}
function setFocusState($field) {
$field.addClass('form-field--is-focused');
}
function setBlurState($field) {
$field.removeClass('form-field--is-focused');
}
function setFilledState($area, $field) {
if ($area.val()) {
$field.addClass('form-field--is-filled');
} else {
$field.removeClass('form-field--is-filled');
}
}
})(jQuery);
|
/**
* @package eat
* @author Codilar Technologies
* @license https://opensource.org/licenses/OSL-3.0 Open Software License v. 3.0 (OSL-3.0)
* @link http://www.codilar.com/
*/
var config = {
'paths': {
'afbtHandler': 'Codilar_Afbt/js/afbt_block_handler',
'owlCarousel': 'Codilar_Afbt/js/owl.carousel',
},
'shim': {
'owlCarousel': {
'deps': ['jquery']
}
}
};
|
/**
* Created by Prateek Sharma on 02/01/17.
*/
var Hapi = require("hapi");
var routes = require("./routes/routes")
var config = require("./config.json")
var plugins = require('./plugins');
var server = new Hapi.Server({
connections: {
routes: {
cors: {
origin: ['*'],
headers: ['X-Requested-With', 'Content-Type']
}
}
}
});
server.connection({
port: process.env.PORT || config.dev.appPort
});
server.register(plugins.pluginsArray, function (err) {
if (err) {
console.log(err);
throw err;
}
routes.forEach(function (route) {
server.route(route);
});
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply("hello")
}
});
server.start(function () {
console.log('Server running at:', server.info.uri);
});
});
/*server.on('response', function (request) {
console.log('Request payload:', request.payload);
console.log('Response payload:', request.response.source);
});*/
|
define(function(){
var BM = Backbone.Model,
User = BM.extend({
defaults:{
userId: 0,
userName:'default',
avatar: 'img/placeholder1.png',
post:'Please Enter your comment here..'
}
});
console.log('USer',User.prototype);
return User;
}); |
angular
.module('StationCreator')
.factory('BluetoothBeaconService', BluetoothBeaconService);
BluetoothBeaconService.$inject = [
'$log', '$translate'
];
function BluetoothBeaconService (
$log, $translate
) {
/// BluetoothBeaconService
var service =
{
// vars
beacon : {},
isBeaconFound : false,
// functions
setBeaconFound : setBeaconFound,
setBeacon : setBeacon,
getBeacon : getBeacon,
checkBeaconFound : checkBeaconFound,
};
/// functions
function setBeaconFound (bool) {
service.isBeaconFound = bool;
}
function setBeacon (beacon) {
if (! service.isBeaconFound) {
service.isBeaconFound = true;
}
angular.copy(beacon, service.beacon);
}
function getBeacon () {
return service.beacon;
}
function checkBeaconFound () {
return service.isBeaconFound;
}
return service;
}
|
import React from 'react';
import Dialog from '@material-ui/core/Dialog';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import PropTypes from 'prop-types';
const ModalComp = (props) => {
return (
<div>
<Dialog
open={props.show}
onClose={props.onClose}
maxWidth="md"
scroll="body"
aria-labelledby="scroll-dialog-title"
aria-describedby="scroll-dialog-description"
>
{(props.title) && <DialogTitle>{props.title}</DialogTitle>}
<DialogContent>
{props.children}
</DialogContent>
</Dialog>
</div>
);
}
ModalComp.propTypes = {
title: PropTypes.string,
show: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired,
children: PropTypes.node
}
export default ModalComp; |
cc.Class({
properties: {
},
ctor() {
},
setMainView(view) {
this.MAIN_VIEW = view;
this.init();
},
init() {
this.node0 = this.MAIN_VIEW.getSendPokerPanel(0);
this.node1 = this.MAIN_VIEW.getSendPokerPanel(1);
this.node2 = this.MAIN_VIEW.getSendPokerPanel(2);
this.ws = cc.winSize;
let fixNum = this.ws.height / qf.dev_size.h;
this.showCardsPosT = [
{ x: 0, y: 0 },
{ x: 0, y: 0 },
{ x: 0, y: 0 },
];
this.sendCardsPosT = [
{ x: 0, y: 0 },
{ x: 0, y: 0 },
{ x: 0, y: 0 },
];
this.bombAnimationCards = {}; //记录最后的手牌,暂时只是用于炸弹的播放
},
sendCard(cardsNode, cardType, index, uin, notShowAction) {
this.bombAnimationCards = this.bombAnimationCards || {};
this.bombAnimationCards[index] = cardType;
if (index === 0) this.sendCard0(cardsNode, cardType, uin);
else if (index === 1) this.sendCard1(cardsNode, cardType, uin, notShowAction);
else if (index === 2) this.sendCard2(cardsNode, cardType, uin, notShowAction);
},
//index(0:自己,1:右上座位,2:左上座位)
getPos(alignedPos, number, scale, index, isMyHandCard, isSendPokerAni) {
let offsetTxtT = [{ x: 45, y: 0 }, { x: 0, y: 40 }, { x: 0, y: 40 }];
let pos = [];
let cardTypeTxtPos = {};
let maxLen = qf.pokerconfig.maxOutRowPokerNum;
if (isMyHandCard) maxLen = qf.pokerconfig.maxRowPokerNum;
let row = Math.floor((number - 1) / maxLen);
let len = 0;
let pokerDistance = qf.pokerconfig.outPokerDistance;
let pokerHeightDis = qf.pokerconfig.pokerSpace[1].height;
if (index === 0) {
pokerHeightDis = qf.pokerconfig.pokerSpace[0].height;
pokerDistance = qf.pokerconfig.outMyPokerDistance;
}
if (isMyHandCard) {
pokerDistance = qf.pokerconfig.pokerDistance;
}
if (isSendPokerAni) {
pokerDistance = pokerDistance / 2;
}
if (number >= maxLen) {
len = ((maxLen - 1) * pokerDistance + qf.pokerconfig.pokerWidth) * scale;
} else {
len = ((number - 1) * pokerDistance + qf.pokerconfig.pokerWidth) * scale;
}
let maxLength = len;
let mX = 0;
let mY = 0;
let xX = 0;
let xY = 0;
if (index === 0) { //中心对齐
mX = -1 / 2;
mY = -1 / 2;
xX = 1;
//xY = 0;
} else if (index === 1) { //右上对齐
mX = -1;
mY = -1;
xX = -1;
//xY = -1;
} else if (index === 2) { //左上对齐
mX = 0;
mY = -1;
xX = 1;
//xY = -1;
}
//最大坐标,最小坐标
let minX = null;
let maxX = null;
for (let i = 1; i <= number; i++) {
let curRow = Math.floor((i - 1) / maxLen);
let position = {};
let lastNum = (number - curRow * maxLen); //一行剩余量
if (lastNum > maxLen) {
len = maxLength;
} else {
len = ((lastNum - 1) * pokerDistance + qf.pokerconfig.pokerWidth) * scale;
}
position.x = alignedPos.x + mX * len + ((qf.pokerconfig.pokerWidth / 2 + ((i - 1) % maxLen) * pokerDistance) * scale);
position.y = alignedPos.y + mY * curRow * pokerHeightDis * scale - (qf.pokerconfig.pokerWidth / 2) * scale;
if (index === 0) {
position.y = alignedPos.y + (-curRow - mY * row) * pokerHeightDis * scale;
}
if (!minX || minX > position.x) {
minX = position.x;
}
if (!maxX || maxX < position.x) {
maxX = position.x;
}
pos.push(position);
}
cardTypeTxtPos.x = alignedPos.x + xX * maxLength / 2 + offsetTxtT[index].x;
cardTypeTxtPos.y = alignedPos.y + xY * (qf.pokerconfig.pokerWidth + row * pokerHeightDis) * scale + offsetTxtT[index].y;
let high = (qf.pokerconfig.pokerWidth + row * pokerHeightDis) * scale;
return { pos: pos, cardTypeTxtPos: cardTypeTxtPos, width: len, height: high, minX: minX, maxX: maxX };
},
sendCard2(cardsNode, cardType, uin, notShowAction) { //用户左
this.clearCards(2);
for (let i in cardsNode) {
cardsNode[i].setParent(this.node2);
cardsNode[i].destroy();
}
let count = 0;
for (let j in cardsNode) {
if (cardsNode.hasOwnProperty(j)) {
count++;
}
}
let objPos = this.getPos(this.sendCardsPosT[2], count, qf.pokerconfig.pokerScale.MIN * 1.2, 2);
let fianlObjPos = this.getPos(this.sendCardsPosT[2], count, qf.pokerconfig.pokerScale.MIN, 2);
let ppp = objPos.pos;
let fianlP = fianlObjPos.pos;
let txtPos = objPos.cardTypeTxtPos;
let minX = fianlObjPos.minX || fianlP[0];
let disPX = (objPos.width - fianlObjPos.width) / 2;
let showUnfoldAction = this.getCardTypeAction(cardType);
for (let k in cardsNode) {
cardsNode[k].opacity = 255;
if (notShowAction) {
cardsNode[k].setScale(qf.pokerconfig.pokerScale.MID);
cardsNode[k].setPosition(cc.v2(fianlP[k].x, fianlP[k].y));
continue;
}
let action = cc.sequence(
cc.scaleTo(0.1, qf.pokerconfig.pokerScale.MID + 0.02).easing(cc.easeElasticOut(0.9)),
cc.scaleTo(0.1, qf.pokerconfig.pokerScale.MID - 0.02).easing(cc.easeElasticOut(0.9)),
cc.scaleTo(0.1, qf.pokerconfig.pokerScale.MID).easing(cc.easeElasticOut(0.9))
)
if (showUnfoldAction) {
cardsNode[k].setPosition(cc.v2(minX - k * 15 - 20, fianlP[0].y));
action = cc.moveTo(0.3, cc.v2(fianlP[k].x, fianlP[k].y));
cardsNode[k].setScale(qf.pokerconfig.pokerScale.MID);
} else {
cardsNode[k].setPosition(cc.v2(fianlP[k].x, fianlP[k].y));
cardsNode[k].setScale(0);
}
cardsNode[k].runAction(action);
}
if (!notShowAction) {
this.showActionEffectAnimation({ type: cardType, user: this.MAIN_VIEW.getUserByIndex(2) });
}
if (qf.cache.desk.getEnterDeskMusicFlag()) {
qf.music.readCard(cardsNode, cardType, this.MAIN_VIEW.getUserByIndex(2));
}
},
sendCard1(cardsNode, cardType, uin, notShowAction) { //用户右
this.clearCards(1);
for (let i in cardsNode) {
cardsNode[i].setParent(this.node1);
cardsNode[i].destroy();
}
let count = 0;
for (let j in cardsNode) {
if (cardsNode.hasOwnProperty(j)) {
count++;
}
}
let objPos = this.getPos(this.sendCardsPosT[1], count, qf.pokerconfig.pokerScale.MIN * 1.2, 1);
let fianlObjPos = this.getPos(this.sendCardsPosT[1], count, qf.pokerconfig.pokerScale.MIN, 1);
let ppp = objPos.pos;
let fianlP = fianlObjPos.pos;
let txtPos = objPos.cardTypeTxtPos;
let maxX = fianlObjPos.maxX || fianlP[fianlP.length - 1];
let disPX = (objPos.width - fianlObjPos.width) / 2;
let showUnfoldAction = this.getCardTypeAction(cardType);
for (let k in cardsNode) {
cardsNode[k].opacity = 255;
if (notShowAction) {
cardsNode[k].setScale(qf.pokerconfig.pokerScale.MID);
cardsNode[k].setPosition(cc.v2(fianlP[k].x, fianlP[k].y));
continue;
}
let action = cc.sequence(
cc.scaleTo(0.1, qf.pokerconfig.pokerScale.MID + 0.02).easing(cc.easeElasticOut(0.9)),
cc.scaleTo(0.1, qf.pokerconfig.pokerScale.MID - 0.02).easing(cc.easeElasticOut(0.9)),
cc.scaleTo(0.1, qf.pokerconfig.pokerScale.MID).easing(cc.easeElasticOut(0.9))
)
if (showUnfoldAction) {
cardsNode[k].setPosition(cc.v2(maxX + k * 15 + 20, fianlP[0].y));
action = cc.moveTo(0.3, cc.v2(fianlP[k].x, fianlP[k].y));
cardsNode[k].setScale(qf.pokerconfig.pokerScale.MID);
} else {
cardsNode[k].setPosition(cc.v2(fianlP[k].x, fianlP[k].y));
cardsNode[k].setScale(0);
}
cardsNode[k].runAction(action);
}
if (!notShowAction) {
this.showActionEffectAnimation({ type: cardType, user: this.MAIN_VIEW.getUserByIndex(1) });
}
if (qf.cache.desk.getEnterDeskMusicFlag()) {
qf.music.readCard(cardsNode, cardType, this.MAIN_VIEW.getUserByIndex(1));
}
},
sendCard0(cardsNode, cardType, uin) {
this.clearCards(0);
for (let k in cardsNode) {
let pos = cardsNode[k].worldPosition;
if (qf.utils.isValidType(pos)) {
pos = this.node0.convertToNodeSpace(pos);
cardsNode[k].setPosition(pos);
}
cardsNode[k].setParent(this.node0);
cardsNode[k].destroy();
}
let count = 0;
for (let i in cardsNode) {
if (cardsNode.hasOwnProperty(i)) {
count++;
}
}
let objPos = this.getPos(this.sendCardsPosT[0], count, qf.pokerconfig.pokerScale.MID, 0);
let ppp = objPos.pos;
let txtPos = objPos.cardTypeTxtPos;
let isSelfPlaying = (uin === qf.cache.user.uin);
for (let j in cardsNode) {
let v = cardsNode[j];
let k = qf.func.checkint(j);
if (!isSelfPlaying) {
cardsNode[k].setPosition(cc.v2(ppp[k].x, ppp[k].y));
cardsNode[k].setScale(qf.pokerconfig.pokerScale.MID);
} else {
( (v, k) => {
let pos = cc.v2(ppp[k].x, ppp[k].y);
v.runAction(cc.sequence(
cc.spawn(
cc.fadeOut(0.1),
cc.moveBy(0.1, cc.v2(0, 50))
),
cc.moveTo(0.1, pos),
cc.callFunc( () => {
v.opacity = 255;
v.setScale(0);
}),
cc.scaleTo(0.1, qf.pokerconfig.pokerScale.MID + 0.05).easing(cc.easeElasticOut(0.9)),
cc.scaleTo(0.1, qf.pokerconfig.pokerScale.MID - 0.05).easing(cc.easeElasticOut(0.9)),
cc.scaleTo(0.1, qf.pokerconfig.pokerScale.MID).easing(cc.easeElasticOut(0.9))
))
})(v, k);
}
}
this.showActionEffectAnimation({ type: cardType, user: this.MAIN_VIEW.getUserByIndex(0) });
if (qf.cache.desk.getEnterDeskMusicFlag()) {
qf.music.readCard(cardsNode, cardType, this.MAIN_VIEW.getUserByIndex(0));
}
},
sendCard0WithReconnect(cardsNode) {
this.clearCards(0);
for (let k in cardsNode) {
cardsNode[k].setParent(this.node0);
cardsNode[k].destroy();
}
//mark: by Derrick
let count = 0;
for (let i in cardsNode) {
if (cardsNode.hasOwnProperty(i)) {
count++;
}
}
let objPos = this.getPos(this.sendCardsPosT[0], count, qf.pokerconfig.pokerScale.MID, 0);
let ppp = objPos.pos;
for (let k in cardsNode) {
cardsNode[k].setScale(qf.pokerconfig.pokerScale.MID);
cardsNode[k].setPosition(ppp[k].x, ppp[k].y);
}
},
sendCardByDrag(cardsNode, cardType, allpos, x, y) {
this.clearCards(0);
for (k in cardsNode) {
cardsNode[k].setScale(qf.pokerconfig.pokerScale.MID);
cardsNode[k].setPosition(x + qf.pokerconfig.pokerWidth * 0.5 * qf.pokerconfig.pokerScale.MID + allpos[k].x * qf.pokerconfig.pokerScale.MID,
y + qf.pokerconfig.pokerHeight * qf.pokerconfig.pokerScale.MID);
cardsNode[k].setParent(this.node0);
cardsNode[k].destroy();
}
//mark: by Derrick
let count = 0;
for (let i in cardsNode) {
if (cardsNode.hasOwnProperty(i)) {
count++;
}
}
let objPos = this.getPos(this.sendCardsPosT[0], count, qf.pokerconfig.pokerScale.MID, 0);
let ppp = objPos.pos;
let txtPos = objPos.cardTypeTxtPos;
for (k in cardsNode) {
cardsNode[k].runAction(cc.moveTo(0.15, cc.v2(ppp[k].x, ppp[k].y)));
}
if (qf.cache.desk.getEnterDeskMusicFlag()) {
qf.music.readCard(cardsNode, cardType, this.MAIN_VIEW.getUserByIndex(0));
}
},
showLastAnimation(cardsNode, index, parentNode, clear) {
let scale = qf.pokerconfig.pokerScale.MAX;
if (index === 0)
scale = qf.pokerconfig.pokerScale.MID;
parentNode.removeAllChildren(true);
//mark: by Derrick
let count = 0;
for (let i in cardsNode) {
if (cardsNode.hasOwnProperty(i)) {
count++;
}
}
let objPos = null;
if (index === 0)
objPos = this.getPos(this.showCardsPosT[index], count, scale, index);
else
objPos = this.getShowPos(this.showCardsPosT[index], count, scale, index);
let ppp = objPos.pos;
if (clear) {
this.clearCards(index);
}
for (k in cardsNode) {
cardsNode[k].setScale(scale);
cardsNode[k].setPosition(ppp[k].x, ppp[k].y);
cardsNode[k].setParent(parentNode);
cardsNode[k].destroy();
}
},
clearCards(index) {
if (this["node" + index]) {
this["node" + index].children.forEach(poker => {
poker.clear();
});
}
},
//三带几的出牌动画
showFeiJiAction(cardType, cardsNode) {
let count = 0;
for (let i in cardsNode) {
if (cardsNode.hasOwnProperty(i)) {
count++;
}
}
if (cardType === qf.const.LordPokerType.SAN || cardType === qf.const.LordPokerType.SANDAIDUIZI || cardType === qf.const.LordPokerType.SANDAI1) { //如果是飞机
if (Math.floor(cardsNode[1].id / 4) === Math.floor(cardsNode[3].id / 4)) { //前三张一样
cardsNode[1].runAction(cc.spawn(
cc.rotateBy(0.2, -32),
cc.moveBy(0.15, cc.v2(8, -6))));
cardsNode[2].runAction(cc.moveBy(0.15, cc.v2(0, 5)));
cardsNode[3].runAction(cc.spawn(
cc.rotateBy(0.2, 32),
cc.moveBy(0.15, cc.v2(-8, -6))));
for (let i = 4; i <= count; i++) {
cardsNode[i].runAction(cc.moveBy(0.1, cc.v2(80, -7)));
}
} else { //后三张一样
cardsNode[count - 2].runAction(cc.spawn(
cc.rotateBy(0.2, -32),
cc.moveBy(0.15, cc.v2(8, -6))));
cardsNode[count - 1].runAction(cc.moveBy(0.15, cc.v2(0, 5)));
cardsNode[count].runAction(cc.spawn(
cc.rotateBy(0.2, 32),
cc.moveBy(0.15, cc.v2(-8, -6))));
for (let i = 1; i <= count - 3; i++) {
cardsNode[i].runAction(cc.moveBy(0.1, cc.v2(-80, -7)));
}
}
}
},
//取用户头像坐标
getUserPosition(index) {
let tou = this.MAIN_VIEW.getUserByIndex(index);
let pt = [tou.getPositionX() + tou.getContentSize().width * 0.5 + (tou.index === 2 ? 25 : -25),
tou.y + tou.getContentSize().height * 0.5];
return cc.v2(pt[0], pt[1]);
},
//出牌牌型
showTypeTxt(index, cardType, pos) {
logd("showTypeTxt cardType=" + (cardType).toString());
if (cardType > 0) {
let txt = qf.txt.lord_type_txt[cardType];
if (qf.utils.isValidType(txt)) {
let pText = new cc.Node();
let lbl_com = pText.addComponent(cc.Label);
lbl_com.string = txt;
lbl_com.fontFamily = qf.res.font1,
lbl_com.fontSize = 30,
pText.setParent(this["node" + index]);
let xsX = 0;
if (index === 0) {
xsX = 1 / 2;
}
pText.setPosition(cc.v2(pos.x + xsX * pText.getContentSize().width, pos.y));
}
}
},
//index(0:自己,1:右上座位,2:左上座位)
getShowPos(alignedPos, number, scale, index) {
let pos = [];
let maxLen = qf.pokerconfig.maxOutRowPokerNum;
let len = 0;
let pokerDistance = qf.pokerconfig.pokerShowSpace.width;
let pokerHeightDis = qf.pokerconfig.pokerShowSpace.height;
if (number >= maxLen) {
len = ((maxLen - 1) * pokerDistance + qf.pokerconfig.pokerShowWidth) * scale;
} else {
len = ((number - 1) * pokerDistance + qf.pokerconfig.pokerShowWidth) * scale;
}
let maxLength = len;
let mX = 0;
let mY = 0;
let xX = 0;
let xY = 0;
if (index === 1) { //右上对齐
mX = -1;
mY = -1;
xX = -1;
//xY = -1;
} else if (index === 2) { //左上对齐
mX = 0;
mY = -1;
xX = 1;
//xY = -1;
}
for (let i = 1; i <= number; i++) {
let curRow = Math.floor((i - 1) / maxLen);
let position = {};
let lastNum = (number - curRow * maxLen); //一行剩余量
if (lastNum > maxLen) {
len = maxLength;
} else {
len = ((lastNum - 1) * pokerDistance + qf.pokerconfig.pokerShowWidth) * scale;
}
position.x = alignedPos.x + mX * len + ((qf.pokerconfig.pokerShowWidth / 2 + ((i - 1) % maxLen) * pokerDistance) * scale);
position.y = alignedPos.y + mY * curRow * pokerHeightDis * scale - (qf.pokerconfig.pokerShowWidth / 2) * scale;
pos.push(position);
}
return { pos: pos };
},
//牌型动画
showActionEffectAnimation(paras) {
let cardType = paras.type;
let fromUser = paras.user;
let ske = null;
let tex = null;
let name = null;
if (cardType === qf.const.LordPokerType.FEIJI || cardType === qf.const.LordPokerType.FEIJI1 || cardType === qf.const.LordPokerType.FEIJI2) {
//飞机
ske = qf.res.animation_feiji_ske;
tex = qf.res.animation_feiji_tex;
name = "Animation1";
qf.music.playMyEffect("feiji");
}
else if (cardType === qf.const.LordPokerType.SHUNZI) {
//顺子
ske = qf.res.animation_shunzi_ske;
tex = qf.res.animation_shunzi_tex;
name = "Animation1";
}
else if (cardType === qf.const.LordPokerType.SHUNZIDUIZI) {
//连对
ske = qf.res.animation_liandui_ske;
tex = qf.res.animation_liandui_tex;
name = "Animation1";
qf.music.playMyEffect("liandui");
}
else if (cardType === qf.const.LordPokerType.ZHADAN) {
//炸弹
ske = qf.res.animation_baozha_ske;
tex = qf.res.animation_baozha_tex;
name = "Animation1";
qf.music.playMyEffect("boom");
}
else if (cardType === qf.const.LordPokerType.WANGZHA) {
//王炸
ske = qf.res.animation_huojian_ske;
tex = qf.res.animation_huojian_tex;
name = "Animation1";
qf.music.playMyEffect("wangzha");
//qf.platform.playVibrate();//震动
}
if (ske && tex && this.MAIN_VIEW) {
let node = new cc.Node();
const armatureDisplay = qf.utils.createArmatureAnimation(node, {
dragonAsset: ske,
dragonAtlasAsset: tex,
armatureName: "armatureName",
});
node.setParent(this.MAIN_VIEW.node);
node.zIndex = 10;
let szWin = cc.winSize;
if (cardType === qf.const.LordPokerType.FEIJI || cardType === qf.const.LordPokerType.FEIJI1 || cardType === qf.const.LordPokerType.FEIJI2) {
//飞机
node.setPosition(-szWin.width * 0.2, szWin.height * 0.55);
node.runAction(cc.sequence(
cc.delayTime(0),
cc.moveTo(1.5, cc.v2(szWin.width * 1.2, szWin.height * 0.55)).easing(cc.easeOut(0.9)),
cc.callFunc( (sender) => {
if (node) {
node.stopAllActions();
node.destroy();
node = null;
}
})
));
armatureDisplay.playAnimation("Animation1");
}
else if (cardType === qf.const.LordPokerType.WANGZHA) {
//王炸
node.setPosition(szWin.width * 0.5, szWin.height * 0.22);
node.runAction(cc.sequence(
cc.delayTime(1),
cc.moveTo(0.5, cc.v2(szWin.width * 0.5, szWin.height * 1.22))
));
armatureDisplay.playAnimation("Animation1", -1, 0);
}
else if (cardType === qf.const.LordPokerType.ZHADAN) {
//炸弹
node.active = false;
let res = qf.rm.getSpriteFrame(qf.res.table, qf.res.bombPng2);
let sprite = node.addComponent(cc.Sprite);
sprite.spriteFrame = res;
node.setParent(this.MAIN_VIEW.node);
node.zIndex = 10;
let isReverse = fromUser.index === 1;
if (isReverse) {
node.setScaleX(-1);
sprite.setFlippedX(true);
}
let toPos = cc.v2(szWin.width * 0.5, szWin.height * 0.55);
let fromPos = cc.v2(fromUser.getCenPos());
node.setPosition(toPos);
sprite.setPosition(fromPos);
sprite.setScale(0.7);
node.setScale(1.2);
let bezierConfig = this.getBezierConfig(fromPos, toPos);
let spwan = cc.spawn(cc.bezierTo(0.5, bezierConfig),
cc.scaleTo(0.5, 1));
sprite.runAction(cc.sequence(
spwan,
cc.callFunc((sender) => {
if (node) {
node.active = true;
armatureDisplay.playAnimation("Animation1", -1, 0);
}
if (sprite) {
sprite.stopAllActions();
sprite.destroy();
sprite = null;
}
})
));
}
else {
if (cardType === qf.const.LordPokerType.SHUNZI || cardType === qf.const.LordPokerType.SHUNZIDUIZI) {
node.setPosition(szWin.width * 0.4, szWin.height * 0.55);
} else {
node.setPosition(szWin.width * 0.5, szWin.height * 0.55);
}
armatureDisplay.playAnimation("Animation1", -1, 0);
}
}
},
//设置贝塞尔曲线的参数
getBezierConfig(fromPos, toPos) {
let offPoint = cc.v2(toPos.x - fromPos.x, toPos.y - fromPos.y);
let controll1 = cc.v2(fromPos.x, fromPos.y + 100);
let controll2 = cc.v2(fromPos.x + offPoint.x * 3 / 5, toPos.y + 100);
let bezierConfig = [controll1
, controll2
, toPos];
return bezierConfig;
},
//获取牌型使用展示动画
getCardTypeAction(cardType) {
if (cardType === qf.const.LordPokerType.SANDAI1 || //三带一
cardType === qf.const.LordPokerType.SANDAIDUIZI || //三带二
cardType === qf.const.LordPokerType.SHUNZI || //顺子
cardType === qf.const.LordPokerType.SHUNZIDUIZI || //连对
cardType === qf.const.LordPokerType.FEIJI || //飞机
cardType === qf.const.LordPokerType.FEIJI1 ||
cardType === qf.const.LordPokerType.FEIJI2
) {
return true;
}
return false;
}
}); |
import firebase from 'firebase'
var firebaseConfig = {
apiKey: "AIzaSyBU3be_2tiOOfcfFy_Uq1PK-RS2FjlaUG4",
authDomain: "tinder-23b5e.firebaseapp.com",
databaseURL: "https://tinder-23b5e.firebaseio.com",
projectId: "tinder-23b5e",
storageBucket: "tinder-23b5e.appspot.com",
messagingSenderId: "383014450699",
appId: "1:383014450699:web:54c5b5edb13311dd3bb90e",
measurementId: "G-H0571FTC14"
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const database=firebaseApp.firestore()
export default database |
import React, {Component} from "react";
import { Button, FormGroup, FormControl, ControlLabel } from "react-bootstrap";
import { Link,withRouter } from 'react-router-dom';
import { auth } from '../firebase';
import * as routes from '../constants/routes';
import { SignUpLink } from './Signup';
const Login = ({ history }) =>
<div>
<h1>SignIn</h1>
<Signinform history={history} />
<SignUpLink />
</div>
const byPropKey = (propertyName, value) => () => ({
[propertyName]: value,
});
const INITIAL_STATE = {
email: '',
password: '',
error: null,
};
export class Signinform extends React.Component{
constructor(props)
{
super(props);
this.state = { ...INITIAL_STATE };
}
validateForm()
{
return this.state.email.length > 0 && this.state.password.length > 0;
}
handleChange = event => {
this.setState({
[event.target.id]: event.target.value
});
}
handleSubmit = event => {
const {
email,
password,
} = this.state;
const {
history,
} = this.props;
auth.doSignInWithEmailAndPassword(email, password)
.then(() => {
this.setState(() => ({ ...INITIAL_STATE }));
history.push(routes.HOME);
})
.catch(error => {
this.setState(byPropKey('error', error));
});
event.preventDefault();
}
render() {
const {
email,
password,
error,
} = this.state;
return (
<div className="Login">
<form onSubmit={this.handleSubmit}>
<FormGroup controlId="email" bsSize="large">
<ControlLabel>Email</ControlLabel>
<FormControl
autoFocus
type="email"
value={this.state.email}
onChange={this.handleChange}
/>
</FormGroup>
<FormGroup controlId="password" bsSize="large">
<ControlLabel>Password</ControlLabel>
<FormControl
value={this.state.password}
onChange={this.handleChange}
type="password"
/>
</FormGroup>
<Button
block
bsSize="large"
disabled={!this.validateForm()}
type="submit"
>
Login
</Button>
</form>
</div>
);
}
}
export default withRouter(Login);
//
// export {
// Signinform
// };
|
import React from 'react';
import PropTypes from 'prop-types';
import { Modal, Button, Alert } from 'react-bootstrap';
import { toastr } from 'react-redux-toastr';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import cx from 'classnames';
import s from './ChooseVerificationType.css';
import WizardLevels from '../WizardLevels/WizardLevels';
import PassportIcon from './passport.svg';
import DriversLicenseIcon from './driver-s-license.svg';
import IdentityCardIcon from './identity-card.svg';
import PassportActiveIcon from './passport-active.svg';
import DriversLicenseActiveIcon from './driver-s-license-active.svg';
import IdentityCardActiveIcon from './identity-card-active.svg';
import C from './constants';
/* eslint-disable css-modules/no-undef-class */
class ChooseVerificationType extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit() {
if (
!this.props.passportPicUploaded &&
!this.props.driversLicensePicUploaded &&
!this.props.identityCardPicUploaded
) {
toastr.error(C.ERROR_TITLE, C.ERROR_DESCRIPTION);
return;
}
this.props.onNextButton();
}
render() {
const properPassportIcon = this.props.passportPicUploaded
? PassportActiveIcon
: PassportIcon;
const properDriversLicenseIcon = this.props.driversLicensePicUploaded
? DriversLicenseActiveIcon
: DriversLicenseIcon;
const properIdentityCardIcon = this.props.identityCardPicUploaded
? IdentityCardActiveIcon
: IdentityCardIcon;
return (
<div>
<Modal.Header closeButton>
{this.props.waitingForModification && (
<Alert variant="warning">
We need you to modify your identity informations, Please check
your email for further informations.
</Alert>
)}
<WizardLevels level={2} />
</Modal.Header>
<Modal.Body style={{ padding: 40, paddingTop: 15, paddingBottom: 15 }}>
<p className={s.headerTitle}> {C.TITLE} </p>
<br />
<p className={s.description}> {C.DESCRIPTION} </p>
<div
style={{ width: '100%' }}
className={cx(s.iconsContainer, s.formInline)}
>
<div
onClick={() =>
this.props.onSelectVerificationType(
this.props.passportDocumentName,
)
}
className={s.formContainer}
role="presentation"
>
<img
width={34}
height={48}
src={properPassportIcon}
alt={`${this.props.passportDocumentName} icon`}
/>
<span
style={{ marginTop: 10 }}
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: this.props.passportDocumentName.replace(
/( )/g,
' ',
),
}}
/>
</div>
<div
onClick={() =>
this.props.onSelectVerificationType(
this.props.driversLicenseDocumentName,
)
}
className={s.formContainer}
role="presentation"
>
<img
width={52}
height={36}
src={properDriversLicenseIcon}
alt={`${this.props.driversLicenseDocumentName} icon`}
/>
<span
style={{ marginTop: 15 }}
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: this.props.driversLicenseDocumentName.replace(
/( )/g,
' ',
),
}}
/>
</div>
<div
onClick={() =>
this.props.onSelectVerificationType(
this.props.identityCardDocumentName,
)
}
className={s.formContainer}
role="presentation"
>
<img
width={52}
height={36}
src={properIdentityCardIcon}
alt={`${this.props.identityCardDocumentName} icon`}
/>
<span
style={{ marginTop: 15 }}
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: this.props.identityCardDocumentName.replace(
/( )/g,
' ',
),
}}
/>
</div>
</div>
<br />
<div>
<Button
onClick={this.handleSubmit}
disabled={
!this.props.passportPicUploaded &&
!this.props.driversLicensePicUploaded &&
!this.props.identityCardPicUploaded
}
className={cx(s.customBtn)}
>
{C.NEXT}
</Button>
</div>
<br />
<p
role="presentation"
onClick={() => this.props.onBackButton()}
className={s.description}
style={{ cursor: 'pointer' }}
>
{C.GO_BACK}
</p>
</Modal.Body>
</div>
);
}
}
ChooseVerificationType.propTypes = {
passportPicUploaded: PropTypes.bool.isRequired,
passportDocumentName: PropTypes.string.isRequired,
driversLicensePicUploaded: PropTypes.bool.isRequired,
driversLicenseDocumentName: PropTypes.string.isRequired,
identityCardPicUploaded: PropTypes.bool.isRequired,
identityCardDocumentName: PropTypes.string.isRequired,
onNextButton: PropTypes.func.isRequired,
onBackButton: PropTypes.func.isRequired,
onSelectVerificationType: PropTypes.func.isRequired,
waitingForModification: PropTypes.bool.isRequired,
};
export default withStyles(s)(ChooseVerificationType);
|
import { Link } from 'gatsby'
import PropTypes from 'prop-types'
import React from 'react'
import styled from 'styled-components'
import Image from './image'
import { ScrollButton } from './button'
const StyledHeader = styled.header`
position: absolute;
width: 100%;
`
const HeaderContent = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
flex: 1;
margin: 0 auto;
max-width: 960px;
padding: 1.45rem 1.0875rem;
`
const Brand = styled.h1`
display: flex;
flex: 1;
flex-basis: 100%;
margin: 0 auto;
@media (min-width: 576px) {
margin: 0;
flex-basis: 50%;
}
`
const ImageContainer = styled.div`
width: 100%;
margin: 0 auto;
@media (min-width: 576px) {
width: 200px;
margin: 0;
}
`
const ScrollButtonContainer = styled.div`
display: flex;
flex: 1;
flex-basis: 100%;
@media (min-width: 576px) {
flex-basis: 50%;
}
`
const StyledScrollButton = styled(ScrollButton)`
margin: 0 auto;
@media (min-width: 576px) {
margin: 0;
margin-left: auto;
}
`
const Header = ({ siteTitle }) => (
<StyledHeader>
<HeaderContent>
<Brand>
<Link
to="/"
style={{
display: 'flex',
color: `white`,
textDecoration: `none`,
flex: 1,
}}
>
<ImageContainer>
<Image style={{ width: '100%' }} />
</ImageContainer>
</Link>
</Brand>
<ScrollButtonContainer>
<StyledScrollButton to="apply" offset={-30} duration={500} smooth>
Apply Now
</StyledScrollButton>
</ScrollButtonContainer>
</HeaderContent>
</StyledHeader>
)
Header.propTypes = {
siteTitle: PropTypes.string,
}
Header.defaultProps = {
siteTitle: ``,
}
export default Header
|
import assert from 'assert'
import { base, angle, julian, sexagesimal as sexa } from '..'
describe('#angle', function () {
describe('single functions', function () {
var c1 = new base.Coord(
new sexa.RA(14, 15, 39.7).rad(),
new sexa.Angle(false, 19, 10, 57).rad()
)
var c2 = new base.Coord(
new sexa.RA(13, 25, 11.6).rad(),
new sexa.Angle(true, 11, 9, 41).rad()
)
it('sep', function () {
// Example 17.a, p. 110.0
var d = angle.sep(c1, c2)
assert.strictEqual(new sexa.Angle(d).toString(0), '32°47′35″')
})
it('sepHav', function () {
// Example 17.a, p. 110.0
var d = angle.sepHav(c1, c2)
assert.ok(new sexa.Angle(d).toString(0), '32°47′35″')
})
it('sepPauwels', function () {
// Example 17.b, p. 116.0
var d = angle.sepPauwels(c1, c2)
assert.ok(new sexa.Angle(d).toString(0), '32°47′35″')
})
it('relativePosition', function () {
var p = angle.relativePosition(c1, c2)
assert.strictEqual(new sexa.Angle(p).toString(0), '22°23′25″')
})
})
describe('movement of two celestial bodies', function () {
var jd1 = julian.CalendarGregorianToJD(1978, 9, 13)
var coords1 = [
new base.Coord(
new sexa.RA(10, 29, 44.27).rad(),
new sexa.Angle(false, 11, 2, 5.9).rad()
),
new base.Coord(
new sexa.RA(10, 36, 19.63).rad(),
new sexa.Angle(false, 10, 29, 51.7).rad()
),
new base.Coord(
new sexa.RA(10, 43, 1.75).rad(),
new sexa.Angle(false, 9, 55, 16.7).rad()
)
]
var jd3 = julian.CalendarGregorianToJD(1978, 9, 15)
var coords2 = [
new base.Coord(
new sexa.RA(10, 33, 29.64).rad(),
new sexa.Angle(false, 10, 40, 13.2).rad()
),
new base.Coord(
new sexa.RA(10, 33, 57.97).rad(),
new sexa.Angle(false, 10, 37, 33.4).rad()
),
new base.Coord(
new sexa.RA(10, 34, 26.22).rad(),
new sexa.Angle(false, 10, 34, 53.9).rad()
)
]
/**
* First exercise, p. 110.0
*/
it('sep', function () {
var c1 = new base.Coord(
new sexa.RA(4, 35, 55.2).rad(),
new sexa.Angle(false, 16, 30, 33).rad()
)
var c2 = new base.Coord(
new sexa.RA(16, 29, 24).rad(),
new sexa.Angle(true, 26, 25, 55).rad()
)
var d = angle.sep(c1, c2)
var answer = new sexa.Angle(false, 169, 58, 0).rad()
assert.ok(Math.abs(d - answer) < 1e-4, new sexa.Angle(d).toString())
})
/**
* Second exercise, p. 110.0
*/
it('minSep', function () {
var err
try {
var sep = angle.minSep(jd1, jd3, coords1, coords2)
} catch (e) {
err = e
}
assert.ok(!err, '' + err)
var exp = 0.5017 * Math.PI / 180 // on p. 111
assert.ok(Math.abs((sep - exp) / sep) < 1e-3, new sexa.Angle(sep).toString())
})
it('minSepHav', function () {
var err
try {
var sep = angle.minSepHav(jd1, jd3, coords1, coords2)
} catch (e) {
err = e
}
assert.ok(!err, '' + err)
var exp = 0.5017 * Math.PI / 180 // on p. 111
assert.ok(Math.abs((sep - exp) / sep) < 1e-3, new sexa.Angle(sep).toString())
})
it('minSepPauwels', function () {
var err
try {
var sep = angle.minSepPauwels(jd1, jd3, coords1, coords2)
} catch (e) {
err = e
}
assert.ok(!err, '' + err)
var exp = 0.5017 * Math.PI / 180 // on p. 111
assert.ok(Math.abs((sep - exp) / sep) < 1e-3, new sexa.Angle(sep).toString())
})
/**
* "rectangular coordinate" solution, p. 113.0
*/
it('minSepRect', function () {
try {
var sep = angle.minSepRect(jd1, jd3, coords1, coords2)
} catch (err) {
assert.ok(!err, '' + err)
}
var exp = 224 * Math.PI / 180 / 3600 // on p. 111
assert.ok(Math.abs((sep - exp) / sep) < 1e-2, new sexa.Angle(sep))
})
})
})
|
import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { Container, Form, Row, Col } from 'react-bootstrap';
import PropTypes from 'prop-types';
// Custom Styling
import StyledButton from '../common/Button/StyledButton';
import StyledTitle from '../common/Title/StyledTitle';
// actions
import { setMenu, previousMenu } from '../../actions/menu';
import { setGuest } from '../../actions/guest';
import { clearPizza } from '../../actions/pizza';
import { clearPizzas } from '../../actions/pizzas';
import { createGuestOrder, createMemberOrder } from '../../actions/order';
import './Cart.css';
import OrderSummary from './OrderSummary/OrderSummary';
import AppSpinner from '../AppSpinner/AppSpinner';
import UserDetails from './UserDetails';
import isAlpha from 'validator/lib/isAlpha';
import isEmail from 'validator/lib/isEmail';
/**
* Cart page component
* - displays a cart with user or guest information, and pizza information
*
* @param {*} setGuest - action for guest reducer
* @param {*} setMenu - action for menu reducer
* @param {*} step - menu reducer state
* @param {*} isAuthenticated - auth reducer state
* @param {*} user - user reducer
* @param {*} clearPizzas - clears the pizzas
*/
const Cart = ({
setGuest,
setMenu,
isAuthenticated,
user,
clearPizza,
clearPizzas,
createGuestOrder,
createMemberOrder,
order,
pizzas,
errors,
}) => {
const [guestData, setGuestData] = useState({
first_name: '',
last_name: '',
email: '',
phone: '',
});
const [prevTotal, setPrevTotal] = useState(0);
const [touched, setTouched] = useState({
first_name: false,
last_name: false,
email: false,
phone: false,
});
function isValidPhoneNumber(phone) {
const test1 = /^\d{10}$/;
const test2 = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if (phone.match(test1) || phone.match(test2)) {
return true;
}
return false;
}
const userDoesNotExist = !isAuthenticated || user === null;
// Adds guest and their information to the store's state
// Directs user to the Confirmation page
const handleClickSubmit = (e) => {
e.preventDefault();
const first_name = guestData.first_name.trim();
const last_name = guestData.last_name.trim();
const email = guestData.email.trim();
const phone = guestData.phone.trim();
const guest = { first_name, last_name, email, phone };
setGuest(guest);
if (isAuthenticated) {
createMemberOrder(() => {
clearPizzas();
setMenu(5);
});
} else {
createGuestOrder(guest, () => {
clearPizzas();
setMenu(5);
});
}
};
const handleGuestDataChange = (e) => {
const name = e.target.name;
const value = e.target.value;
setGuestData((d) => ({ ...d, [name]: value }));
};
console.log(isAuthenticated)
console.log(pizzas.length !== 0)
// Guest view: displays a form for inputting information
const renderGuestInput = () => {
return (
<Form className="cartOrderFormContainer">
<Form.Group as={Row} controlId="formHorizontalName">
<Form.Label column sm={2}>
Name:
</Form.Label>
<Col>
<Form.Control
className="cartOrderFormInput"
name="first_name"
type="text"
placeholder="first name"
value={guestData.first_name}
onChange={handleGuestDataChange}
isInvalid={touched.first_name && !isAlpha(guestData.first_name)}
isValid={isAlpha(guestData.first_name)}
onBlur={() => {
setTouched({ first_name: true });
}}
required
/>
<Form.Control.Feedback type="invalid">
Please enter a valid first name.
</Form.Control.Feedback>
<Form.Control.Feedback>Looks good!</Form.Control.Feedback>
</Col>
<Col>
<Form.Control
className="cartOrderFormInput"
name="last_name"
type="text"
placeholder="last name"
value={guestData.last_name}
onChange={handleGuestDataChange}
isInvalid={touched.last_name && !isAlpha(guestData.last_name)}
isValid={isAlpha(guestData.last_name)}
onBlur={() => {
setTouched({ last_name: true });
}}
required
/>
<Form.Control.Feedback type="invalid">
Please enter a valid last name.
</Form.Control.Feedback>
<Form.Control.Feedback>Looks good!</Form.Control.Feedback>
</Col>
</Form.Group>
<Form.Group as={Row} controlId="formHorizontalEmail">
<Form.Label column sm={2}>
Email:
</Form.Label>
<Col sm={10}>
<Form.Control
className="cartOrderFormInput"
name="email"
type="email"
placeholder="email"
value={guestData.email}
onChange={handleGuestDataChange}
isInvalid={
touched.email && (!isEmail(guestData.email) || errors !== null)
}
isValid={isEmail(guestData.email) && errors === null}
onBlur={() => {
setTouched({ email: true });
}}
required
/>
{errors ? (
<Form.Control.Feedback type="invalid">
{errors}
</Form.Control.Feedback>
) : (
<Form.Control.Feedback type="invalid">
Please enter a valid email address.
</Form.Control.Feedback>
)}
<Form.Control.Feedback>Looks good!</Form.Control.Feedback>
</Col>
</Form.Group>
<Form.Group as={Row} controlId="formHorizontalPhone">
<Form.Label column sm={2}>
Phone:
</Form.Label>
<Col sm={10}>
<Form.Control
className="cartOrderFormInput"
name="phone"
type="text"
placeholder="phone"
value={guestData.phone}
onChange={handleGuestDataChange}
isInvalid={touched.phone && !isValidPhoneNumber(guestData.phone)}
isValid={isValidPhoneNumber(guestData.phone)}
onBlur={() => {
setTouched({ phone: true });
}}
required
/>
<Form.Control.Feedback type="invalid">
Please enter a valid phone number.
</Form.Control.Feedback>
<Form.Control.Feedback>Looks good!</Form.Control.Feedback>
</Col>
</Form.Group>
</Form>
);
};
// Conditional rendering dependent on if guest or user
const customerSummary = () => {
if (userDoesNotExist) {
return renderGuestInput();
} else {
return (
<UserDetails
first_name={user.first_name}
last_name={user.last_name}
email={user.email}
phone={user.phone}
/>
);
}
};
useEffect(() => {
// Calculates the total price of all orders in the cart
const calcTotalPrice = () => {
let total = 0;
for (let pizza of pizzas) {
total += parseFloat(pizza.totalPrice);
}
total = parseFloat(total).toFixed(2);
setPrevTotal(total);
};
calcTotalPrice();
}, [pizzas]);
const handleAddAnotherPizza = (e) => {
e.preventDefault();
clearPizza();
setMenu(9);
};
const handleAddAPizza = (e) => {
e.preventDefault();
clearPizza();
setMenu(9);
};
return (
<div>
<StyledTitle text="Cart" className="CartTitle" />
<div className="centerStyle">
<h2>Review your order below</h2>
</div>
<div className="centerStyle">
<p>All orders are carry out and pay in store</p>
</div>
<Container>
<Row className="cartOrderFormContainerRow">
<Col className="cartOrderFormContainerWrapper">
<h2 className="cartSubTitle">Order for:</h2>
{customerSummary()}
</Col>
<Col className="cartOrderFormContainerWrapper">
<h2 className="cartSubTitle">Order Summary:</h2>
<h6>Total: ${prevTotal}</h6>
<OrderSummary />
{pizzas.length !== 0 ? (
<StyledButton
onClick={handleAddAnotherPizza}
variant="basicButton"
text="Add another pizza"
/>
) : (
<div>
<p>Pizza cart is currently empty.</p>
<StyledButton
onClick={handleAddAPizza}
variant="basicButton"
text="Add a pizza"
/>
</div>
)}
</Col>
</Row>
</Container>
<div className="centerStyle d-flex align-items-center">
<StyledButton
variant="basicButton"
onClick={handleClickSubmit}
type="button"
disabled={ isAuthenticated? pizzas.length === 0 : !isEmail(guestData.email) ||
!isAlpha(guestData.last_name) ||
!isAlpha(guestData.first_name) ||
!isValidPhoneNumber(guestData.phone) || pizzas.length === 0
}
text="Submit"
/>
{order.processing && <AppSpinner />}
</div>
</div>
);
};
const mapStateToProps = (state) => {
return {
isAuthenticated: state.auth.isAuthenticated,
user: state.auth.user,
guest: state.guest,
order: state.order,
pizzas: state.pizzas,
errors: state.order.errors,
};
};
Cart.propTypes = {
user: PropTypes.object,
guest: PropTypes.object.isRequired,
order: PropTypes.object.isRequired,
isAuthenticated: PropTypes.bool.isRequired,
setGuest: PropTypes.func.isRequired,
setMenu: PropTypes.func.isRequired,
createGuestOrder: PropTypes.func.isRequired,
createMemberOrder: PropTypes.func.isRequired,
};
export default connect(mapStateToProps, {
setGuest,
setMenu,
previousMenu,
clearPizza,
clearPizzas,
createGuestOrder,
createMemberOrder,
})(Cart);
|
const registerWish = require('../../logic/wishes/register-wish')
module.exports = async function (req, res) {
const { userId, body: { breed, gender, size, age: { years, months }, neutered, withDogs, withCats, withChildren, distance } } = req
try {
await registerWish(userId, { breed, gender, size, years, months, neutered, withDogs, withCats, withChildren, distance })
res.status(201).json({ message: 'wish registered correctly.' })
} catch ({ message }) {
res.status(400).json({ error: message })
}
} |
/*******************************************************************************
* Project MCMS, all source code and data files except images,
* Copyright 2008-2015 Grit-Innovation Software Pvt. Ltd., India
*
* Permission is granted to Magma Fin Corp. to use and modify as they see fit.
*******************************************************************************/
var dtCh= "/";
var minYear=1900;
var maxYear=2100;
function isInteger(s){
var i;
for (i = 0; i < s.length; i++){
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}
function stripCharsInBag(s, bag){
var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++){
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}
function daysInFebruary (year){
// February has 29 days in any year evenly divisible by four,
// EXCEPT for centurial years which are not also divisible by 400.
return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
for (var i = 1; i <= n; i++) {
this[i] = 31
if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
if (i==2) {this[i] = 29}
}
return this
}
function isDate(dtStr){
var daysInMonth = DaysArray(12)
var pos1=dtStr.indexOf(dtCh)
var pos2=dtStr.indexOf(dtCh,pos1+1)
var strDay=dtStr.substring(0,pos1)
var strMonth=dtStr.substring(pos1+1,pos2)
var strYear=dtStr.substring(pos2+1)
strYr=strYear
if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
for (var i = 1; i <= 3; i++) {
if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
}
month=parseInt(strMonth)
day=parseInt(strDay)
year=parseInt(strYr)
if (pos1==-1 || pos2==-1){
alert("The date format should be : dd/mm/yyyy")
return false
}
if (strMonth.length<1 || month<1 || month>12){
alert("Please enter a valid month")
return false
}
if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
alert("Please enter a valid day")
return false
}
if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
return false
}
if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
alert("Please enter a valid date")
return false
}
return true
}
var dateFormat = function () {
var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
timezoneClip = /[^-+\dA-Z]/g,
pad = function (val, len) {
val = String(val);
len = len || 2;
while (val.length < len) val = "0" + val;
return val;
};
// Regexes and supporting functions are cached through closure
return function (date, mask, utc) {
var dF = dateFormat;
// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
mask = date;
date = undefined;
}
// Passing date through Date applies Date.parse, if necessary
date = date ? new Date(date) : new Date;
if (isNaN(date)) throw SyntaxError("invalid date");
mask = String(dF.masks[mask] || mask || dF.masks["default"]);
// Allow setting the utc argument via the mask
if (mask.slice(0, 4) == "UTC:") {
mask = mask.slice(4);
utc = true;
}
var _ = utc ? "getUTC" : "get",
d = date[_ + "Date"](),
D = date[_ + "Day"](),
m = date[_ + "Month"](),
y = date[_ + "FullYear"](),
H = date[_ + "Hours"](),
M = date[_ + "Minutes"](),
s = date[_ + "Seconds"](),
L = date[_ + "Milliseconds"](),
o = utc ? 0 : date.getTimezoneOffset(),
flags = {
d: d,
dd: pad(d),
ddd: dF.i18n.dayNames[D],
dddd: dF.i18n.dayNames[D + 7],
m: m + 1,
mm: pad(m + 1),
mmm: dF.i18n.monthNames[m],
mmmm: dF.i18n.monthNames[m + 12],
yy: String(y).slice(2),
yyyy: y,
h: H % 12 || 12,
hh: pad(H % 12 || 12),
H: H,
HH: pad(H),
M: M,
MM: pad(M),
s: s,
ss: pad(s),
l: pad(L, 3),
L: pad(L > 99 ? Math.round(L / 10) : L),
t: H < 12 ? "a" : "p",
tt: H < 12 ? "am" : "pm",
T: H < 12 ? "A" : "P",
TT: H < 12 ? "AM" : "PM",
Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
};
return mask.replace(token, function ($0) {
return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
});
};
}();
// Some common format strings
dateFormat.masks = {
"default": "ddd mmm dd yyyy HH:MM:ss",
shortDate: "m/d/yy",
mediumDate: "mmm d, yyyy",
longDate: "mmmm d, yyyy",
fullDate: "dddd, mmmm d, yyyy",
shortTime: "h:MM TT",
mediumTime: "h:MM:ss TT",
longTime: "h:MM:ss TT Z",
isoDate: "yyyy-mm-dd",
isoTime: "HH:MM:ss",
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};
// Internationalization strings
dateFormat.i18n = {
dayNames: [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
]
};
// For convenience...
Date.prototype.format = function (mask, utc) {
return dateFormat(this, mask, utc);
}; |
'use strict';
const movieController = require('../../controllers/movie/MovieController');
module.exports = {
name: 'movie',
version: '1.0.0',
register: async (server) => {
server.route([
{
method: 'GET',
path: '/movie/findAll',
handler: movieController.getAllMovie,
options: {
description: 'List all movies',
tags: ['api'],
},
},
{
method: 'POST',
path: '/movie/save',
handler: movieController.saveMovie,
options: {
description: 'Create a movie',
tags: ['api'],
},
},
{
method: 'PUT',
path: '/movie/update',
handler: movieController.updateMovie,
options: {
description: 'Update a movie',
tags: ['api'],
},
},
{
method: 'GET',
path: '/movie/getMovieById/{id}',
handler: movieController.getMovieById,
options: {
description: 'Get a movie by its {id}',
tags: ['api'],
},
},
{
method: 'GET',
path: '/movie/getMovieByTitle/{title}',
handler: movieController.getMovieByTitle,
options: {
description: 'Get a movie by title',
tags: ['api'],
},
},
]);
}
}; |
module.exports = {
message: {
timeline: "Tidslinje",
explore: "Utforske",
maps: "Maps",
users: "Brukere",
register: "Registrere",
login: "Logg Inn",
logout: "Logg ut",
registerUserText: "Registrer ny bruker",
profile: "Profil",
save: "Lagre",
showOnMap: "Åpne på kart",
showOnMapTooltip: "Legg til dette på kartet",
reply: "Svare",
replyTooltip: "Legg inn et svar",
viewReplies: "Se svar",
hideReplies: "Skjul svar",
newPost: "Nytt innlegg",
accountLogin: "Kontoinnlogging",
name: "Navn",
password: "Passord",
cancel: "Avbryt",
privateCollections: "Private samlinger",
publicCollections: "Offentlige samlinger",
search: "Søke",
loadMore: "Last mer",
openMap: "Åpne kart",
chooseCollections: "Velg samlinger å følge",
checkCollectionsOut: "Se offentlige samlinger og følg dem",
inCollection: "I samling",
existingAccount: "Eksisterende konto",
newAccount: "Ny konto",
alreadyInUseMessage:
"Dette brukernavnet er allerede i bruk. Vennligst velg en annen.",
youAreRegistered: "Du har blitt registrert!",
youAreLoggedIn: "Du er logget inn!",
close: "Lukk",
post: "Post",
back: "Tilbake",
createdBy: "Laget av",
shareOn: "Del innlegget på",
shareLink: "Del lenken",
linkCopied:
"Koblingen er kopiert. Du kan lime inn hvor du vil med Control + V eller høyreklikk Lim inn",
userDescriptionHint:
"Hvis du liker deg, kan du skrive en kort beskrivelse om deg",
userNameMissing: "Brukernavn mangler.",
passwordMissing: "Passord mangler.",
passwordWeak: "For sikkerheten må passordet inneholde mer enn 8 tegn.",
emailErrorFormat: "E-postadressen må være i riktig format.",
emailMissing: "The email is necessary to register.",
credentialsError: "Innloggingsfeil",
searchResults: "Søkeresultater",
searchHint: "Du må oppgi minst 4 tegn",
noResults: "Ingen resultater",
noPublicCollections:
"Det er ingen offentlige samlinger. Legg til en ved å klikke",
publicCollectionsHint: "Samlinger som alle kan se og bruke med søkefeltet",
noPrivateCollections:
"Det arent noen private samlinger. Legg til en ved å klikke",
description: "Beskrivelse",
title: "Tittel",
privateCollectionsHint:
"Samlinger som bare deg og brukerne du inviterer, kan vise at de ikke kan søkes ved hjelp av søkefeltet",
collectionAddedToast: "Lagt til en samling!",
ofTheUser: "av brukeren",
membersNumber: "Medlemsnummer",
chooseUsersToShare: "Velg andre brukere for å dele samlingen",
deleteCollection: "Slett samling?",
allPostsWillBeDeleted: "Alle innlegg i denne samlingen vil bli fjernet",
yes: "Ja",
no: "Nei",
followCollection: "Følg samlingen",
stopFollowing: "Slutt å følge",
choose: "Velge",
newPostHint:
"Lag et nytt innlegg med kartelementer og tekst og publiser det",
newPostInThisCollection: "Nytt innlegg i denne samlingen",
noPosts: "Ingen innlegg",
chooseCollectionsToFollow: "Velg samlinger å følge",
liveMapUpdate: "Live kartoppdatering",
youMayWriteText: "Du kan skrive teksten din her",
youMayWriteAndSketch:
"Skriv teksten din her. Du kan også skisse på kartet!",
sketchToAddToPost:
"Skisse på kartet og geometrier vil bli lagt til innlegget!",
publish: "Publisere",
chooseCollection: "Velg samling",
collections: "Samlinger",
published: "Publisert!",
errorNoTextOrSketches:
"Det er ingen tekst eller geometri. Skriv en tekst eller skiss på kartet før du publiserer",
aPostPublished: "Et nytt innlegg ble publisert i samlinger du følger.",
aReplyPublished: "Et svar innlegg ble publisert i samlinger du følger.",
aReplyToYourPostPublished: "Μια απάντηση δημοσιεύτηκε στην ανάρτησή σας",
geometrySketched: "En geometri ble skissert fra folk du følger",
mapPublished: "Et kart ble publisert.",
invitedToCollection: "Du ble invitert i samling.",
invitationToCollectionAccepted: "Invitasjonen du sendte ble akseptert av",
collectionWasFollowed: "Samlingen din er blitt fulgt.",
collectionWasUnfollowed: "Samlingen din har blitt ufølge",
feature: "Geometry",
map: "Kart",
invitation: "Invitasjon",
collection: "Samling",
accept: "Godta",
decline: "Nedgang",
byUser: "av bruker",
newMessage: "Ny melding",
sendMessage: "Send",
outlineColor: "Outline",
fillColor: "Fyll",
strokeWidth: "Bredde",
symbologyStyle: "Stil",
noUserCollectionsFound: "Ingen offentlig samling funnet",
notifications: "Varsler",
markAllAsRead: "Marker alle som lest",
makeCollectionPublic: "Gjør denne samlingen offentlig",
makeCollectionPrivate: "Stopp deling",
sharingSettings: "Deling innstillinger",
questionnaires: "Spørreskjemaer",
questionnairesIcreated: "Spørreskjemaer jeg har opprettet",
questionnairesIanswered: "Spørreskjemaer jeg har svart på",
shareQuestionnaireMessage:
"Du kan dele denne lenken til de du vil svare på.",
createQuestionnaire: "Lag et spørreskjema",
questionnaireTitle: "Gi en tittel til spørreskjemaet.",
questionnaireDescription: "Gi mer informasjon om spørreskjemaet.",
questionnaireMapExtent: "Sett et spørreskjema referanseområde på kartet.",
previewQuestionnaire: "Forhåndsvis spørsmålet",
yourAnswer: "Ditt svar",
addLine: "Legg til linje",
changeSection: "Endre seksjonen",
section: "Seksjon",
questionOptions: "Spørsmål alternativer",
question: "Spørsmål",
optional: "Valgfritt",
addQuestion: "Legg til spørsmål",
questionType: "Spørstype",
saveQuestionnaire: "SPAR SPØRSMÅL",
text: "Tekst",
expandableMenu: "Utvidbar meny",
checkboxes: "Boksene",
multipleChoice: "Flere valg",
mapPointer: "Pek på kartet",
mapPointerMultiple: "Flere punkter på kartet",
mapLinesMultiple: "Flere linjer på kartet",
mapLineStringPointer: "Tegn linje på kartet",
sortingOptions: "Preferanse hierarki",
titleAndDescription: "Tittel og beskrivelse",
questionNotAnswered: "Du har ikke besvart spørsmålet",
nextSection: "Neste seksjon",
previousSection: "Forrige seksjon",
submitQuestionnaire: "Send spørreskjema",
thereAreErrorsInQuestionnaire:
"Det er feil. Se spørsmålene merket med rødt.",
questionnaireSubmitted: "Dine svar ble sendt inn.",
submitted: "Sendt inn",
noValue: "Ingen verdi",
listOfAnswers: "Liste over svar",
aggregates: "Aggregate",
allAnswers: "Alle svarene",
from: "fra",
to: "til",
exportToTable: "Eksporter til bord",
exportMapData: "Eksporter kartografiske data",
createMap: "Opprett kart",
questionnaireStart: "Adgang tillatt med start på",
questionnaireEnd: "Adgang tillatt siden",
enablePublicAccess: "Aktiver offentlig tilgang",
selectLanguage: "Velg språk",
selectValidationType: "Valideringstype"
}
};
|
import { get, post } from './http'
export const login = params => get('/login', params)
export const test = params => post('/test', params) |
var webdriver = require("selenium-webdriver"),
By = webdriver.By;
var chrome = require('selenium-webdriver/chrome');
var options = new chrome.Options();
var logging_prefs = new webdriver.logging.Preferences();
logging_prefs.setLevel(webdriver.logging.Type.PERFORMANCE, webdriver.logging.Level.ALL);
options.setLoggingPrefs(logging_prefs);
options.addArguments("--no-experiments");
options.addArguments("--disable-translate");
options.addArguments("--disable-plugins");
options.addArguments("--disable-extensions");
options.addArguments("--no-default-browser-check");
options.addArguments("--clear-token-service");
options.addArguments("--disable-default-apps");
options.addArguments("--enable-logging");
options.addArguments("--test-type");
var chromeCapabilities = options.toCapabilities();
var driver = new webdriver.Builder().forBrowser('chrome').withCapabilities(chromeCapabilities).build();
driver.get("http://dev.hq.adap.tv/adclient/harness/?autostart=1&tab=vast_adaptv_flash");
driver.sleep(2000);
driver.findElement(By.css('#harness-adtag-form-adtag input')).sendKeys('http://ads.adaptv.advertising.com/a/h/PtfytGA0Yf9nJzcgxDVnQkOBFiEjxV+F?cb=[CACHE_BREAKER]&pet=preroll&pageUrl=test15571.com&eov=eov&cowboy=1&ocb=784389');
driver.findElement(By.css('#harness-adtag-form-adtag button')).click();
driver.sleep(60000 * 2);
driver.manage().logs().get('performance').then(function(entries) {
console.log(entries);
});
driver.quit();
|
$(document).ready(function () {
//var jsfile = '@Url.Content("~/Scripts/AttendanceDialog.js")';
//document.write('<script type="text/javascript" src="'jsfile'"></script>');
//document.write('<script type="text/javascript" src="'
// + jsfile + '"></scr' + 'ipt>');
// Tells to the ajax calls not to use cache
$.ajaxSetup({
cache: false
});
$('.editableRecord').live('click', function () {
// The date of the record that should be changed
var dateOfRecord = $(this).attr('data-date');
// The position of the clicked cell, used to set the position of the dialog
var pos = $(this).offset();
pos.top = pos.top + 20;
var clickedEmployee = $(this).parent();
var idEmployee = $(clickedEmployee).attr('data-employeeid');
var normalEmpl = $(clickedEmployee).attr('data-normalempl');
var hasPaidHolidayLeft = $(clickedEmployee).attr('data-haspaidholidayleft');
var totalPartialUrl = $(clickedEmployee).attr('data-urltotalpartial');
var takeRecUrl = $(clickedEmployee).attr('data-urltakerecord') + "/";
var saveAttendanceUrl = $(clickedEmployee).attr('data-urlsaveattendance');
var takeRecordUrl = takeRecUrl + idEmployee + "?date=" + dateOfRecord;
var inputedValue = $.trim($(this).text())
$('#dialogHolder').html(ChoiceDialog(idEmployee, dateOfRecord, normalEmpl,
hasPaidHolidayLeft, saveAttendanceUrl, inputedValue));
$('#dialogHolder').dialog('option', 'height', 450);
$('#dialogHolder').dialog('option', 'width', 400);
$('#dialogHolder').dialog('option', 'position', [pos.left, pos.top]);
$('#dialogHolder').dialog('option', 'show', 'blind');
$('#dialogHolder button').click(function () {
var url = $(this).attr('data-href');
// Takes the chosen hours or letter (W,U,S,P)
var clicked = $(this).html();
var newReport = $('#Comments').val();
// Encodes the special characters (and lets me pass the report as a parameter
// without losing the formatting)
var rep = encodeURIComponent(newReport);
url += rep;
$('#dialogHolder').dialog('close');
//post the results form the attendance dialog to
$.ajax({
url: url,
type: 'POST',
dataType: 'html',
success: function (result) {
// result is either a number of hours selected from the user
// or the type of attendance he has chosen (a letter - W,U,S,P)
if (result.length == 1) {
var cell = $('tr[data-employeeid=' + idEmployee + '] td[data-date=' + dateOfRecord + ']');
$(cell).attr('data-report', newReport);
$(cell).html(result);
var linkToPartial = totalPartialUrl + "/" + idEmployee + "?date="
+ dateOfRecord;
// Cells containing information of type total
// should be removed before rendering the TotalPartialView
var totalCells = $('tr[data-employeeid=' + idEmployee + '] td[data-type=total]');
$.get(linkToPartial, function (partial) {
$(totalCells).remove();
$('tr[data-employeeid=' + idEmployee + ']').append(partial);
});
}
else {
alert(result);
}
}
});
});
$('#dialogHolder').dialog('open');
var thisHeight = $('#spinner').height();
var thisWidth = $('#spinner').width();
var textAreaPosition = $('#Comments').offset();
var textAreaHeight = $('#Comments').height();
var textAreaWidth = $('#Comments').width();
var newtop = textAreaPosition.top + textAreaHeight / 2 - thisHeight / 2;
var newleft = textAreaPosition.left + textAreaWidth / 2 - thisWidth / 2;
$("#spinner").offset({ top: newtop, left: newleft }).show();
$("#spinner").show();
//take the report:
$.ajax({
url: takeRecordUrl,
type: 'GET',
dataType: 'html',
success: function (reportTaken) {
$("#spinner").hide();
var Comments = $('#Comments');
Comments.val(reportTaken);
},
error: function () {
$("#spinner").hide();
}
});
//get all buttons and color the one showing the inputted information
var buttons = $('button');
for (var i = 0; i < buttons.length; i++) {
if ($($('button')[i]).text().trim() == inputedValue) {
$($('button')[i]).css("background-color", "#FFCF6D !important");
}
}
});
});
// Builds the dialog content
|
import React, { Component } from "react";
import { ScrollView, StyleSheet, Text, View, Image } from "react-native";
import { shows } from "../mockData";
import { mainStyles } from "../constants/mainStyles";
import { primaryColor } from "../constants/Colors";
import { header } from "../components/header";
import { cleanDate, cleanTime } from "../components/helper";
export default class ShowScreen extends Component {
render() {
const props = {
data: shows[0]
};
const { id, name, venue_name, poster_url, description } = props.data;
const { container } = mainStyles;
const { resultText, card, header, textHolder, scroll } = localStyles;
const date = cleanDate(props.data.date);
const time = cleanTime(props.data.date);
return (
<ScrollView contentContainerStyle={[container, scroll]}>
<View style={textHolder}>
<Text style={[resultText, header]}>{name}</Text>
<Text style={[resultText]}>
{date} - {time}
</Text>
<Text style={[resultText]}>{venue_name}</Text>
</View>
<Image
source={{ uri: poster_url }}
resizeMode={"contain"}
style={{ flex: 1 }}
/>
<Text style={[resultText]}>{description}</Text>
</ScrollView>
);
}
}
const localStyles = StyleSheet.create({
scroll: {
height: '100%'
},
resultText: {
color: "white",
textAlign: "center",
fontSize: 24
},
header: {
fontSize: 40
},
card: {
marginVertical: 3,
height: 150
},
textHolder: {
display: "flex",
height: 180,
justifyContent: "space-around",
padding: 10
}
});
ShowScreen.navigationOptions = header;
|
// initializes the variables needed for the input validation
// it is easier to access the DOM information in javascript, which is why we employed it here in conjunction with python
let count = 0;
let seats = [];
let checked = false;
let num;
let char;
let button;
// creates a list of all possible seats in a movie theatre
for (num = 1; num <= 10; num++) {
for (char of "ABCDEFGHIJ") {
seats.push("" + char + num);
}
}
// creates an array of seats that are currently booked by their respective screening
function createSeatArray(seat_list) {
let new_array = [];
seat_list = seat_list.replace("[","").replace("]","").split(", ");
for (let element of seat_list)
new_array.push(element.split("_"));
return new_array;
}
// whenever a different screening is selected, it resets all seats and respective checkboxes to unchecked, then goes
// through the list of booked seats and disables them and changes their class (so their colour is different)
function updateBookedSeats(booked, screening) {
count = 0;
for (num = 1; num <= 10; num++) {
for (char of "ABCDEFGHIJ") {
document.getElementById(char + num + "b").className = "seat zoom btn btn-outline-primary";
document.getElementById("" + char + num).checked = false;
document.getElementById(char + num + "b").disabled = false;
}
}
for (let element of booked) {
if (element[1] === screening.id.replace("screening_", "")) {
document.getElementById(element[0] + "b").disabled = true;
document.getElementById(element[0] + "b").className = "seat btn btn-danger";
document.getElementById(element[0]).checked = false;
}
}
}
// asserts that all fields are filled before the book button is enabled
function assertFilled() {
let student_id = document.getElementById("student_id").value;
let first_name = document.getElementById("first_name").value;
let last_name = document.getElementById("last_name").value;
document.getElementById("bookNow").disabled = !(student_id !== "" && first_name !== ""
&& last_name !== "" && count > 0 && checked);
}
// the toggleScreening and toggleSeat functions essentially emulate checkbox behaviour in the buttons that we put in
// their place, and checks the button's respective checkbox or radio so that that information is passed through the form
function toggleScreening(element) {
checked = true;
document.getElementById("" + element.id + "r").checked = true;
let radio_buttons = document.getElementsByName("screening_buttons");
for (button of radio_buttons){
button.className = "zoom btn btn-outline-primary";
}
element.className = "zoom btn btn-success";
assertFilled();
}
function toggleSeat(element) {
if (element.className === "seat zoom btn btn-outline-primary"){
element.className = "seat zoom btn btn-success";
document.getElementById("" + element.value).checked = true;
seats.splice(seats.indexOf(element.value), 1);
count++;
} else {
element.className = "seat zoom btn btn-outline-primary";
document.getElementById("" + element.value).checked = false;
seats.push(element.value);
count--;
}
// disables all seats if 5 seats are selected, if one is unselected then they all become available again
if (count === 5) {
document.getElementsByClassName("seat zoom btn btn-outline-primary").disabled = true;
for (element of seats) {
if(document.getElementById("" + element + "b").className !== "seat btn btn-danger") {
document.getElementById("" + element + "b").disabled = true;
}
}
} else {
document.getElementsByClassName("zoom btn btn-outline-primary").disabled = false;
for (element of seats) {
if(document.getElementById("" + element + "b").className !== "seat btn btn-danger") {
document.getElementById("" + element + "b").disabled = false;
}
}
}
assertFilled();
}
|
/*
*description:到店体验
*author:fanwei
*date:2014/06/22
*/
define(function(require, exports, module){
var param = require('../../../../global/js/global/getParam');
var FnDo = require('../../../../global/js/global/fnDo');
var until = require('../../../../global/js/global/until');
var url = reqBase + 'vgoods/getlist';
require('../../../../global/js/global/loading');
var tip = require('../../../../global/js/global/tip');
var focus = require('../../../../global/js/widget/focus/focus');
var loadingTimer;
$(document).ready(function(){
clearTimeout( loadingTimer );
loadingTimer = setTimeout(loading, 500);
});
//todo
var url = reqBase + 'vshop/like';
var todo = new FnDo({
oWrap: $('[script-role = product_footer]'),
sTarget: 'fav',
fnDo: function(oThis) {
wparam.shop_id = gparam.shop_id;
if ( !oThis.hasClass('active') ) {
this.req(url, wparam, function(data){
oTip.text('已收藏');
oThis.addClass('active');
});
} else {
this.req(url, wparam, function(data){
oTip.text('已取消收藏');
oThis.removeClass('active');
});
}
}
});
todo.init();
function Goshop() {
}
Goshop.prototype = {
init: function() {
this.showPage();
this.events();
},
events: function() {
},
showMap: function(l, t, name) {
var map = new BMap.Map("map");
map.centerAndZoom(new BMap.Point(l,t),15);
var marker1 = new BMap.Marker(new BMap.Point(l, t));
map.addOverlay(marker1);
var infoWindow1 = new BMap.InfoWindow(name);
marker1.addEventListener("click", function(){this.openInfoWindow(infoWindow1);});
},
showPage: function() {
var oTplShop,
oShop,
getDataUrl,
_this,
l,
t,
name;
oTplShop = require('../../tpl/build/shop/list');
oShop = $('[sc = go_shop]');
getDataUrl = reqBase + 'vshop/info';
//gparam.shop_id = gparam.shop_id;
wparam.shop_id = gparam.shop_id;
_this = this;
until.show(oTplShop, oShop, getDataUrl, wparam, function(data){
var foc = new focus({
cycle: true,
auto: true,
oWrap: $('[widget-role = focus-wrap]')
});
foc.init();
l = data.data.shop_longitude;
t = data.data.shop_latitude;
name = data.data.shop_address;
_this.showMap(l, t, name);
});
}
}
var oGoshop = new Goshop();
oGoshop.init();
}); |
import { SET_SEARCH } from '../../actions/search/search'
import { createReducer } from '../utils'
const initialState = {
search: '',
}
export default createReducer(initialState, {
[SET_SEARCH]: setSearch,
})
function setSearch(state, action) {
return {
search: action.payload || state.search,
}
}
|
/*
Write an Append() function which appends one linked list to another.
The head of the resulting list should be returned.
var listA = 1 -> 2 -> 3 -> null
var listB = 4 -> 5 -> 6 -> null
append(listA, listB) === 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null
If both listA and listB are null/NULL/None/nil, return null/NULL/None/nil.
If one list is null/NULL/None/nil and the other is not, simply return the non-null/NULL/None/nil list.
*/
function Node(data) {
this.data = data;
this.next = null;
}
function append(listOne, listTwo) {
if (!listOne && !listTwo) return null;
if (!listOne || !listTwo) return listOne || listTwo;
let currNode = listOne;
while (currNode.next !== null) {
currNode = currNode.next;
}
currNode.next = listTwo;
return listOne;
}
|
/* See license.txt for terms of usage */
define([
"firebug/lib/trace",
"firebug/lib/object",
"firebug/lib/url",
"firebug/lib/locale",
"firebug/lib/string",
"firebug/debugger/clients/grip",
"firebug/debugger/script/sourceLink",
"firebug/debugger/debuggerLib",
],
function (FBTrace, Obj, Url, Locale, Str, Grip, SourceLink, DebuggerLib) {
// ********************************************************************************************* //
// Constants
var TraceError = FBTrace.toError();
var Trace = FBTrace.to("DBG_STACK");
// ********************************************************************************************* //
// Stack Frame
function StackFrame(sourceFile, lineNo, functionName, args, nativeFrame, pc, context, newestFrame)
{
Grip.call(this, nativeFrame);
// Essential fields
this.sourceFile = sourceFile;
this.line = lineNo;
// xxxHonza: the way how the function name is computed is hacky. What about displayName?
var fileName = sourceFile.href ? Url.getFileName(sourceFile.href) : null;
this.fn = functionName || fileName || "(anonymous)";
this.context = context;
// the newest frame in the stack containing 'this' frame
this.newestFrame = (newestFrame ? newestFrame : this);
// optional
this.args = args;
// Derived from sourceFile
this.href = sourceFile.href;
// Mozilla
this.nativeFrame = nativeFrame;
this.pc = pc;
this.script = nativeFrame ? nativeFrame.script : null; // TODO-XB
};
/**
* This object represents JavaScript execution frame. Instance of this object are usually
* created when the debugger pauses JS execution.
* xxxHonza: should be derived from a client object?
*/
StackFrame.prototype = Obj.descend(Grip.prototype,
/** @lends StackFrame */
{
getURL: function()
{
return this.href;
},
getCompilationUnit: function()
{
return this.context.getCompilationUnit(this.href);
},
getStackNewestFrame: function()
{
return this.newestFrame;
},
getFunctionName: function()
{
return this.fn;
},
toSourceLink: function()
{
var sourceLink = new SourceLink(this.sourceFile.href, this.line, "js");
// Source link from a frame is always marked as the current debug location so,
// the underlying source view knows that the target line should be decorated.
sourceLink.options.debugLocation = true;
return sourceLink;
},
toString: function()
{
return this.fn + ", " +
(this.sourceFile ? this.sourceFile.href : "no source file") +
"@" + this.line;
},
setCallingFrame: function(caller, frameIndex)
{
this.callingFrame = caller;
this.frameIndex = frameIndex;
},
// xxxHonza: not used, should be refactored or removed.
getCallingFrame: function()
{
Trace.sysout("stackFrame.getCallingFrame; " + this, this);
if (!this.callingFrame && this.nativeFrame && this.nativeFrame.isValid)
{
var nativeCallingFrame = this.nativeFrame.callingFrame;
if (nativeCallingFrame)
this.callingFrame = StackFrame.getStackFrame(nativeCallingFrame, this.context,
this.newestFrame);
}
return this.callingFrame;
},
getFrameIndex: function()
{
return this.frameIndex;
},
getLineNumber: function()
{
return this.line;
},
destroy: function()
{
Trace.sysout("stackFrame.destroy; " + this.uid);
this.script = null;
this.nativeFrame = null;
this.context = null;
},
signature: function()
{
return this.getActor();
},
/**
* Compare two StackFrame instances and returns true if their actor is the same.
* (Used in bindings.xml in getObjectItem())
*
* @param {StackFrame} other The other object to compare with.
* @return {boolean} true if their actor is the same.
*/
equals: function(other)
{
// Note: do not compare directly with their nativeFrame => they are not always equal.
return other.nativeFrame && this.nativeFrame &&
other.nativeFrame.actor === this.nativeFrame.actor;
}
});
// ********************************************************************************************* //
// Static Methods
StackFrame.getStackDump = function()
{
var lines = [];
for (var frame = Components.stack; frame; frame = frame.caller)
lines.push(frame.filename + " (" + frame.lineNumber + ")");
return lines.join("\n");
};
StackFrame.getStackSourceLink = function()
{
for (var frame = Components.stack; frame; frame = frame.caller)
{
if (frame.filename && frame.filename.indexOf("://firebug/") > 0)
{
for (; frame; frame = frame.caller)
{
var firebugComponent = "/modules/firebug-";
if (frame.filename && frame.filename.indexOf("://firebug/") < 0 &&
frame.filename.indexOf(firebugComponent) == -1)
break;
}
break;
}
}
return StackFrame.getFrameSourceLink(frame);
}
/**
* Converts from RDP stack frame packet to {@link StackFrame}
*/
StackFrame.buildStackFrame = function(frame, context)
{
if (!frame)
{
TraceError.sysout("stackFrame.buildStackFrame; ERROR no frame!");
return;
}
var sourceFile = context.getSourceFile(frame.where.url);
if (!sourceFile)
sourceFile = {href: frame.where.url};
var args = [];
var bindings = frame.environment.bindings;
var arguments = bindings ? bindings.arguments : [];
for (var i = 0; i < arguments.length; i++)
{
var arg = arguments[i];
args.push({
name: getArgName(arg),
value: getArgValue(arg, context)
});
}
var funcName = StackFrame.getFunctionName(frame);
return new StackFrame(sourceFile, frame.where.line, funcName,
args, frame, 0, context);
};
StackFrame.getFunctionName = function(frame)
{
var func = frame.callee;
if (!func)
return "";
// Use custom displayName (coming from the script) if provided.
if (func.userDisplayName)
return func.userDisplayName;
return func.displayName || func.name;
};
StackFrame.guessFunctionName = function(url, lineNo, sourceFile)
{
if (sourceFile)
return StackFrame.guessFunctionNameFromLines(url, lineNo, sourceFile);
return Url.getFileName(url) + "@" + lineNo;
}
var reGuessFunction = /['"]?([$0-9A-Za-z_]+)['"]?\s*[:=]\s*(function|eval|new Function)/;
var reFunctionArgNames = /function ([^(]*)\(([^)]*)\)/;
StackFrame.guessFunctionNameFromLines = function(url, lineNo, sourceFile)
{
// Walk backwards from the first line in the function until we find the line which
// matches the pattern above, which is the function definition
var line = "";
for (var i = 0; i < 4; ++i)
{
// xxxHonza: the source can be fetched asynchronously, we should use callback.
line = sourceFile.getLine(lineNo - i) + line;
if (line != undefined)
{
var m = reGuessFunction.exec(line);
if (m)
{
return m[1];
}
else
{
Trace.sysout("stackFrame.guessFunctionNameFromLines; re failed for lineNo-i=" +
lineNo + "-" + i + " line=" + line);
}
m = reFunctionArgNames.exec(line);
if (m && m[1])
return m[1];
}
}
return Url.getFileName(url) + "@" + lineNo;
}
// ********************************************************************************************* //
// Helpers
function getArgName(arg)
{
for (var p in arg)
return p;
}
function getArgValue(arg, context)
{
var name = getArgName(arg);
var grip = arg[name].value;
var object = context.clientCache.getObject(grip);
if (object && typeof(object) == "object")
return object.getValue();
return object;
}
// ********************************************************************************************* //
// JSD1 Artifacts
StackFrame.suspendShowStackTrace = function(){}
StackFrame.resumeShowStackTrace = function(){}
// ********************************************************************************************* //
// Firefox 30 introduced also column number in the URL (see Bug 762556)
// functionName@fileName:lineNo:columnNo
// xxxHonza: at some point we might want to utilize the column number as well.
// The regular expression can be simplified to expect both (:line:column) as soon
// as Firefox 30 (Fx30) is the minimum required version.
var reErrorStackLine = /^(.*)@(.*?):(\d*)(?::(\d*))?$/
StackFrame.parseToStackFrame = function(line, context)
{
var m = reErrorStackLine.exec(line);
if (!m)
return;
return new StackFrame({href:m[2]}, m[3], m[1], [], null, null, context);
};
StackFrame.guessFunctionArgNamesFromSource = function(source)
{
// XXXsimon: This fails with ES6 destructuring and parentheses in default parameters.
// We'd need a proper JavaScript parser for that.
var m = /[^\(]*\(([^\)]*)\)/.exec(source);
if (!m)
return null;
var args = m[1].split(",");
for (var i = 0; i < args.length; i++)
{
var arg = args[i];
if (arg.indexOf("=") !== -1)
arg = arg.substr(0, arg.indexOf("="));
arg = arg.trim();
if (!/^[a-zA-Z$_][a-zA-Z$_0-9]*$/.test(arg))
return null;
args[i] = arg;
}
return args;
};
StackFrame.removeChromeFrames = function(trace)
{
var frames = trace ? trace.frames : null;
if (!frames || !frames.length)
return null;
var filteredFrames = [];
for (var i = 0; i < frames.length; i++)
{
var href = frames[i].href;
if (href.startsWith("chrome:") || href.startsWith("resource:"))
continue;
// xxxFlorent: should be reverted if we integrate
// https://github.com/fflorent/firebug/commit/d5c65e8 (related to issue6268)
if (DebuggerLib.isFrameLocationEval(href))
continue;
filteredFrames.push(frames[i]);
}
trace.frames = filteredFrames;
return trace;
}
StackFrame.getFrameSourceLink = function(frame)
{
if (frame && frame.filename)
return new SourceLink(frame.filename, frame.lineNumber, "js");
else
return null;
};
// ********************************************************************************************* //
// Registration
return StackFrame;
// ********************************************************************************************* //
});
|
const db = wx.cloud.database();
const admin = db.collection('fabu');
const _=db.command;
Page({
/**
* 页面的初始数据
*/
data: {
ne:[],
array: ['暂未选择', '电子产品', '生活日用品', '化妆品', '鞋子', '男士衣物', '女士衣物', '书籍', '军训相关用品', '交通工具', '游戏账号'],
index: 0,
name:'',
new1:'',
jiage:'',
miaoshu:'',
lianxifangshi:'',
thingImage:'',
arr:[],
fileList:'',
fileID_pay:'',
fileList_pay:'',
payCode:''
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let that=this
let id=options.data;
let array=JSON.parse(options.data1)
that.setData({
ne:array
})
that.setData({
index:that.data.ne.index
})
that.setData({
thingImage:that.data.ne.fileList
})
that.setData({
name:that.data.ne.name
})
that.setData({
new1:that.data.ne.new1
})
that.setData({
jiage:that.data.ne.jiage
})
that.setData({
miaoshu:that.data.ne.miaoshu
})
that.setData({
lianxifangshi:that.data.ne.lianxifangshi
})
that.setData({
fileList:that.data.ne.fileList
})
that.setData({
payCode:that.data.ne.fileList_pay
})
//console.log(that.data.ne)
},
getName(res){
this.setData({
name:res.detail
})
},
getNew(res){
this.setData({
new1:res.detail
})
},
getJiaGe(res){
this.setData({
jiage:res.detail
})
},
bindPickerChange(res){
let that=this
that.setData({
index: res.detail.value
})
},
bindPayCode(res){
var that=this
var fileList_pay=that.data.ne.fileList_pay
var file=[]
var fileID_pay=[]
var timestamp=Date.parse(new Date());
var number=(Math.random()*1000).toFixed(0);
timestamp=timestamp/1000;
if(that.data.ne.fileList_pay!==""){
wx.cloud.callFunction({
name:'DeleteImage',
data:{
fileList:fileList_pay
},
success(res){
console.log("图片删除成功",res)
},
fail(res){
console.log("图片删除失败",res)
}
})
wx.chooseImage({
count:1,
sizeType:['original','compressed'],
sourceType:['album','camera'],
success(res){
//tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths=res.tempFilePaths
console.log('tempFilePath:',tempFilePaths)
that.setData({
payCode:res.tempFilePaths
})
wx.cloud.uploadFile({
cloudPath:'payCode/' + timestamp+'-'+number,
filePath:tempFilePaths[0],//文件路径
success(res){
console.log('res.fileID_pay',res.fileID)
fileID_pay.push(res.fileID)
console.log(fileID_pay)
that.setData({
fileID_pay:fileID_pay
})
wx.cloud.getTempFileURL({
fileList: fileID_pay,
success: res => {
console.log("fileList_pay",res.fileList[0].tempFileURL)
that.setData({
fileList_pay:res.fileList[0].tempFileURL
})
},
fail:res=>{
console.log("失败",res)
}
})
},
fail(res){
console.log("获取fileID失败",res)
}
})
}
})
}else{
wx.chooseImage({
count:1,
sizeType:['original','compressed'],
sourceType:['album','camera'],
success(res){
var timestamp=Date.parse(new Date());
timestamp=timestamp/1000
//tempFilePath可以作为img标签的src属性显示图片
const tempFilePaths=res.tempFilePaths
console.log('tempFilePath:',tempFilePaths)
that.setData({
payCode:res.tempFilePaths
})
wx.cloud.uploadFile({
cloudPath:'payCode/' + timestamp+'-'+number,
filePath:tempFilePaths[0],//文件路径
success(res){
console.log('res.fileID',res.fileID)
fileID_pay.push(res.fileID)
console.log(fileID_pay)
that.setData({
fileID_pay:fileID_pay
})
that.setData({
img_pay:that.data.img_pay.concat(res.fileID)
})
wx.cloud.getTempFileURL({
fileList: fileID_pay,
success: res => {
console.log("fileList_pay",res.fileList[0].tempFileURL)
that.setData({
fileList_pay:res.fileList[0].tempFileURL
})
}
})
},
fail(res){
console.log("获取fileID失败",res)
}
})
}
})
}
},
bindThingImageInput(){
var that = this;
var fileList=that.data.ne.fileList
var file = []
var timestamp = Date.parse(new Date());
timestamp = timestamp / 1000;
wx.cloud.callFunction({
name: 'DeleteImage',
data: {
fileList: fileList
},
success(res) {
console.log("图片删除成功", res)
},
fail(res) {
console.log("图片删除失败", res)
},
})
wx.chooseImage({
count: 1,
sourceType: ['album', 'camera'],
success: function (res) {
const thingImage = res.tempFilePaths;
that.setData({
thingImage: thingImage
})
const cloudPath = [];
thingImage.forEach((item, i) => {
cloudPath.push('shop/' + timestamp)
})
for (let i = 0, h = thingImage.length; i < h; i++) {
wx.cloud.uploadFile({
cloudPath: cloudPath[i],
filePath: thingImage[i],
success(res) {
that.data.arr.push(res.fileID)
wx.cloud.getTempFileURL({
fileList: that.data.arr,
success: res => {
//console.log("res.fileList=", res.fileList[0].tempFileURL)
that.setData({
fileList: res.fileList[0].tempFileURL
})
}
})
}
})
}
}
})
},
getMiaoShu(res){
this.setData({
miaoshu:res.detail
})
},
getLianXiFangShi(res){
this.setData({
lianxifangshi:res.detail
})
},
fabu(){
let that = this
let dataId=that.data.ne._id
if (that.data.index == 0) {
wx.showToast({
icon: 'none',
title: '请选择物品类型',
})
return
}
console.log(that.data.fileID_pay,that.data.fileList_pay)
wx.cloud.callFunction({
name:'changeThing',
data:{
dataId:dataId,
name: that.data.name,
new1: that.data.new1,
jiage: that.data.jiage,
miaoshu: that.data.miaoshu,
lianxifangshi: that.data.lianxifangshi,
array: that.data.array[that.data.index],
index: that.data.index,
fileID: that.data.arr,
fileList: that.data.fileList,
fileID_pay:that.data.fileID_pay,
fileList_pay:that.data.fileList_pay
},
success(res) {
console.log("上传成功", res)
wx.switchTab({
url: '../mine/mine',
})
wx.showToast({
title: '修改成功',
})
},
fail(res) {
console.log("上传失败", res)
wx.switchTab({
url: '../mine/mine',
})
wx.showToast({
icon:'none',
title: '修改失败',
})
}
})
/*db.collection("fabu").doc(id).update({
data:{
name: that.data.name,
new1: that.data.new1,
jiage: that.data.jiage,
miaoshu: that.data.miaoshu,
lianxifangshi: that.data.lianxifangshi,
array: that.data.array[that.data.index],
index: that.data.index,
fileID: that.data.arr,
thingImage: that.data.thingImage,
fileList: that.data.fileList
},
success(res){
console.log("上传成功",res)
wx.switchTab({
url: '../shouye/shouye',
})
wx.showToast({
title: '已提交审核',
})
},
fail(res){
console.log("上传失败",res)
}
})*/
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
wx.showToast({
icon: 'none',
title: '别滑了兄弟!到底了',
})
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
}) |
var sel = document.getElementById('selection');
var selection = document.getElementsByName('tipo');
console.log(selection.toString());
function addingPregunta() {
alert('nueva Pregunta');
}
function cambioRadio(){
var resultado;
for(var i = 0; i<selection.length;i++){
if(selection[i].checked){
resultado = selection[i].value;
console.log(resultado+'Seleccionado');
break;
}else{
console.log('No select' +selection[i].value);
}
}
if(resultado ==='VerFal'){
var divCambia = document.getElementById('correcto0');
console.log(divCambia.toString());
divCambia.innerHTML='<p> Elije la respuesta correcta <input type="radio" name="VF" value="verdadero">Verdadero<input type="radio" name="VF" value="falso">Falso</p>';
}else if (resultado ==='OpcionesPer') {
var divCambia = document.getElementById('correcto0');
divCambia.innerHTML=' <p><input type="text" name="textoPregunta1" value=""><input type="radio" name="VF" value="opc1"><br> <input type="text" name="textoPregunta2" value=""><input type="radio" name="VF" value="opc2"><br> <input type="text" name="textoPregunta3" value=""><input type="radio" name="VF" value="opc3"><br> <input type="text" name="textoPregunta4" value=""><input type="radio" name="VF" value="opc3"><br></p>';
}
}
|
const Handlebars = require('handlebars');
module.exports = function (data) {
let filepath = require(`../images/${ data.filename }`);
let expression = /\.(gif|jpg|jpeg|tiff|png|svg)$/i;
let ext = data.filename.match(expression);
let b4ext = data.filename.replace(expression, '');
let title = b4ext.replace(/-/g, ' ').replace(/\b\w/gi, function(l){return l.toUpperCase()});
let altname = data.alt || "Chris Murphy portfolio image.";
if(data.widths){
let srcStr = '';
for(let i = 1; i < data.widths.length; i++){
let elFilename = require(`../images/${b4ext}-${data.widths[i]}w${ext[0]}`);
srcStr += elFilename + ' ' + data.widths[i] + 'w, ';
}
return new Handlebars.SafeString(`
<img src="${filepath}" title="${title}" alt="${altname}"
srcset="${srcStr}"
sizes="(max-width:739px) ${data.mobileWidth}, ${data.defaultWidth}"
>`);
}else {
return new Handlebars.SafeString(`<img src="${filepath}" title="${title}" alt="${altname}">`);
}
} |
const express = require('express');
const postModel = require('../models/post');
const commentModel = require('../models/comment');
const router = express.Router();
router.get('/:id', (req, res) => {
postModel.getPostById(req.params.id)
.then(result => res.status(200).send(result))
.catch(err => res.status(err.code).send(err));
});
router.get('/', (req, res) => {
postModel.getPosts(req.query.userId)
.then(result => res.status(200).send(result))
.catch(err => res.status(err.code).send(err));
});
router.get('/', (req, res) => {
postModel.getPostByUserId(req.query.userId)
.then(result => res.status(200).send(result))
.catch(err => res.status(err.code).send(err));
});
router.post('/', (req, res) => {
postModel.insert(req.body)
.then(result => res.status(201).send(result))
.catch(err => res.status(err.code).send(err));
});
router.post('/:id/comments', (req, res) => {
commentModel.insert(req.params.id, req.body)
.then(result => res.status(201).send(result))
.catch(err => res.status(err.code).send(err));
});
module.exports = router; |
function mostrar()
{
var repetir;
for(i=1;i!=0;i++)
{
alert(i);
}
}//FIN DE LA FUNCIÓN |
$(document).ready(function() {
"use strict";
// Click handler for pointer
JSAV._types.Pointer.prototype.click = function(fn) {
var pointer = this;
this.element.click(function() {
fn(pointer);
});
};
JSAV._types.ds.ListNode.prototype.llist_next = {};
JSAV._types.ds.ListNode.prototype.llist_tail = {};
JSAV._types.ds.ListNode.prototype.llist_edgeToNext = {};
JSAV._types.ds.ListNode.prototype.llist_pleft = null;
JSAV._types.ds.ListNode.prototype.llist_pright = null;
});
|
/**
* @author Sven Koelpin
*/
const Database = {
find(id){
return new Promise(resolve => {
setTimeout(() => {
resolve({data: id});
}, 500);
})
}
};
//1. call Database.find with the ids 1, 2 and 3. Log each result. The next call can only be done when the previous call returned a value
const receiveDataInSequence = async () => {
const one = await Database.find(1);
console.log(one);
const two = await Database.find(2);
console.log(two);
const three = await Database.find(3);
console.log(three);
};
receiveDataInSequence();
//2. Do the same again, but let the calls run concurrently. Log the result
const receiveDataConcurrently = async () => {
const result = await Promise.all([Database.find(1), Database.find(2), Database.find(3)]);
console.log(result);
};
receiveDataConcurrently();
|
//biojs-vis-tree is proudly based on code by Miguel Pignatellis TnT Library and edited for npm using CJS
if (typeof biojs === 'undefined') {
module.exports = biojs = {}
}
if (typeof biojs.vis === 'undefined') {
module.exports = biojs.vis = {}
}
biojs.vis.tree = require('./')
|
//colocar en el <head>
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(mostrarUbicacion);
} else {alert("¡Error! Este navegador no soporta la Geolocalización.");}
function mostrarUbicacion(position) {
//var times = position.timestamp;
var latitud = position.coords.latitude;
var longitud = position.coords.longitude;
//var altitud = position.coords.altitude;
//var exactitud = position.coords.accuracy;
//alert(longitud);
localStorage.setItem('varLatitud', latitud);
localStorage.setItem('varLongitud', longitud);
} |
/*
Copyright 2016-2018 Stratumn SAS. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import create from '../../src/create';
import memoryStore from '../../src/memoryStore';
export default function(plugin, assertions1) {
const assertions = Object.assign(
{
'#init()': () => {},
'#action()': () => {},
'#createMap()': () => {},
'#createSegment()': () => {}
},
assertions1
);
const actions = {
init(a, b, c) {
assertions['#init()'](this);
this.state = { a, b, c };
this.append();
},
action(d) {
assertions['#action()'](this);
this.state.d = d;
this.append();
}
};
describe(`Agent With Plugin ${plugin.name}`, () => {
let agent;
let process;
beforeEach(() => {
agent = create(actions, memoryStore(), null, {
agentUrl: 'http://localhost'
});
process = agent.addProcess('basic', actions, memoryStore(), null, {
plugins: [plugin]
});
});
afterEach(() => {
delete actions.events;
});
describe('#createMap()', () => {
it('creates a Map', () =>
process.createMap([], [], 1, 2, 3).then(assertions['#createMap()']));
});
describe('#createSegment()', () => {
it('creates a segment', () =>
process
.createMap(null, null, 1, 2, 3)
.then(segment1 =>
process
.createSegment(segment1.meta.linkHash, 'action', [], [], 4)
.then(assertions['#createSegment()'])
));
});
});
}
|
const mysql=require('mysql');
const express=require('express');
var app=express();
const bodyparser=require('body-parser');
app.use(bodyparser.json( ));
var mysqlConnection= mysql.createConnection({
host:'localhost',
user:'root',
password:'Kyalo1999',
database:'classdb',
multipleStatements:true
});
mysqlConnection.connect((err)=>{
if(!err)
console.log('DB connection suceeded.');
else
console.log('DB connection failed \n Error:'+ JSON.stringify(err,undefined,2));
});
app.listen(3000 ,()=>console.log('Express server is running at port no:3000'));
app.get('/students',(req,res)=>{
mysqlConnection.query('SELECT * FROM students' , (err , rows ,fields)=>{
if(!err)
res.send(rows);
else
console.log(err);
})
});
app.get('/students/:id',(req,res)=>{
mysqlConnection.query('SELECT * FROM students WHERE id=?' ,[req.params.id], (err , rows ,fields)=>{
if(!err)
res.send(rows);
else
console.log(err);
})
});
app.delete('/students/:id',(req,res)=>{
mysqlConnection.query('DELETE FROM students' , (err , rows ,fields)=>{
if(!err)
res.send('Deleted successfully!');
else
console.log(err);
})
});
app.post('/students',(req,res)=>{
let clas=req.body;
var sql= "SET @id=?;SET @fname= ?;SET @email =? ;SET @tel=? ;\
CALL studentsAddOrEdit(@id,@fname ,@email ,@tel);";
mysqlConnection.query(sql,[clas.id ,clas.fname,clas.email, clas.tel], (err , rows ,fields)=>{
if(!err)
rows.forEach(element=>{
if(element.constructor ==Array)
res.send('inserted students id : ' + element[0].id);
});
else
console.log(err);
})
});
app.put('/students',(req,res)=>{
let clas=req.body;
var sql= "SET @id=?;SET @fname= ?;SET @email =? ;SET @tel=? ;\
CALL studentsAddOrEdit(@id,@fname ,@email ,@tel);";
mysqlConnection.query(sql,[clas.id ,clas.fname,clas.email, clas.tel], (err , rows ,fields)=>{
if(!err)
res.send('updated successfully');
else
console.log(err);
})
}); |
function Slime(attributes = {}) {
this.x = attributes.x || 275;
this.y = attributes.y || 600;
this.radius = 80;
this.speed = attributes.speed || 3;
this.color = attributes.color || 'red';
this.context = attributes.context;
this.keysDown = attributes.keysDown;
this.canvas = attributes.canvas;
this.ball = attributes.ball;
this.player = attributes.player;
this.jumping = false;
this.ai = false;
}
Slime.prototype.render = function() {
this.drawSlime();
this.drawEyes();
this.drawPupils();
};
Slime.prototype.drawSlime = function () {
this.context.beginPath();
this.context.arc(this.x, this.y, this.radius, Math.PI, false);
this.context.fillStyle = this.color;
this.context.fill();
this.context.closePath();
};
Slime.prototype.drawEyes = function() {
this.context.beginPath();
this.shouldDrawPlayer1Eye();
this.shouldDrawPlayer2Eye();
this.fillEyes();
};
Slime.prototype.shouldDrawPlayer1Eye = function() {
if (this.player === "player 1") {
this.drawPlayer1Eye();
}
};
Slime.prototype.shouldDrawPlayer2Eye = function() {
if (this.player === "player 2") {
this.drawPlayer2Eye();
}
};
Slime.prototype.drawPlayer1Eye = function() {
this.context.arc(this.x + 43, this.y -54, 10, Math.PI * 2, false);
};
Slime.prototype.drawPlayer2Eye = function() {
this.context.arc(this.x - 43, this.y -54, 10, Math.PI * 2, false);
};
Slime.prototype.fillEyes = function() {
this.context.fillStyle = "white";
this.context.fill();
this.context.closePath();
};
Slime.prototype.drawPupils = function() {
this.context.beginPath();
this.shouldDrawPlayer1Pupil();
this.shouldDrawPlayer2Pupil();
this.fillPupils();
};
Slime.prototype.shouldDrawPlayer1Pupil = function() {
if (this.player === "player 1") {
this.drawPlayer1Pupil();
}
};
Slime.prototype.shouldDrawPlayer2Pupil = function() {
if (this.player === "player 2") {
this.drawPlayer2Pupil();
}
};
Slime.prototype.drawPlayer1Pupil = function() {
this.context.arc((this.x + 40 + (this.ball.x/120)), this.y - 53.5 - (this.ball.y / 175), 4, Math.PI * 2, false);
};
Slime.prototype.drawPlayer2Pupil = function() {
this.context.arc((this.x - 47 + (this.ball.x/120)), this.y - 53.5 - (this.ball.y / 175), 4, Math.PI * 2, false);
};
Slime.prototype.fillPupils = function() {
this.context.fillStyle = "black";
this.context.fill();
this.context.closePath();
};
Slime.prototype.move = function(x, y) {
this.x += x;
this.y += y;
};
Slime.prototype.gravity = function() {
if (this.isJumping()) { this.y += 7.5; }
};
Slime.prototype.isJumping = function() {
return (this.y < 600);
};
Slime.prototype.updatePosition = function(moveLeft, moveRight, jump) {
if(this.ai === false){
for (var key in this.keysDown) {
var value = Number(key);
this.ifMoveRight(value, moveRight);
this.ifMoveLeft(value, moveLeft);
this.ifFinishJump(value, jump);
this.ifJumping(value, jump);
this.ifStayingStill();
}
}
this.ifAI(jump);
return this;
};
Slime.prototype.ifAI = function(jump) {
if (this.ai === true && this.ball.x > this.canvas.width / 2) {
var x_difference = (this.x - this.ball.x);
if (this.ball.x === 775){
x_difference = 0.5;
} else if (x_difference === 0) {
x_difference = 5;
} else if (-80 > x_difference > 0.1) {
x_difference = 15;
} else if (0.1 < x_difference < 80) {
x_difference = -15;
}
this.move(x_difference, 0);
var y_difference = ((this.y - this.radius - 60) < this.ball.y && x_difference < 80);
if (y_difference === true) {
var value = jump;
this.ifFinishJump(value, jump);
this.ifJumping(value, jump);
}
this.moveAI();
}
};
Slime.prototype.moveAI = function() {
if (this.x < (this.canvas.width / 2) + this.radius) {
this.x = (this.canvas.width / 2) + this.radius;
} else if (this.x + this.radius > this.canvas.width) {
this.x = this.canvas.width - this.radius;
}
};
Slime.prototype.ifMoveRight = function(value, moveRight) {
if (value === moveRight && this.isNotTouchingRightWall() && this.isNotTouchingLeftSideOfNet()) {
this.moveToRight();
}
};
Slime.prototype.ifMoveLeft = function(value, moveLeft){
if (value === moveLeft && this.isNotTouchingLeftWall() && this.isNotTouchingRightSideOfNet()) {
this.moveToLeft();
}
};
Slime.prototype.ifFinishJump = function(value, jump) {
if (value === jump && this.isOnTheGround() && !this.jumping) {
this.finishJump();
}
};
Slime.prototype.ifJumping = function(value, jump) {
if (value === jump && this.jumping) {
this.jump();
}
};
Slime.prototype.isNotTouchingRightWall = function() {
return this.x < this.canvas.width - this.radius;
};
Slime.prototype.isNotTouchingLeftSideOfNet = function() {
return this.x !== (this.canvas.width / 2 - this.radius - 5);
};
Slime.prototype.isNotTouchingLeftWall = function() {
return this.x > (0 + this.radius);
};
Slime.prototype.isNotTouchingRightSideOfNet = function() {
return this.x !== (this.canvas.width / 2 + this.radius + 5);
};
Slime.prototype.isOnTheGround = function() {
return this.y === 600;
};
Slime.prototype.moveToRight = function() {
return this.move(10, 0);
};
Slime.prototype.moveToLeft = function() {
return this.move(-10, 0);
};
Slime.prototype.finishJump = function() {
this.jump();
this.jumping = true;
};
Slime.prototype.ifStayingStill = function() {
this.move(0, 0);
};
Slime.prototype.jump = function() {
if (this.y >= 520) { this.move(0, -15); }
if (this.y <= 520) { this.jumping = false; }
};
Slime.prototype.resetPosition = function() {
if (this.player === 'player 1') { this.x = 275; }
if (this.player === 'player 2') { this.x = 775; }
this.y = 600;
};
module.exports = Slime;
|
/* Object object ES5 */
/* defineProperty() */
// 파라미터 : 대상오브젝트, 프로퍼티 이름, 속성
// 대상 오브젝트에 프로퍼티 주가 또는 프로퍼티 속성 변경
// 프로퍼티마다 상태(변경/삭제/열거 가능여부)를 갖고 있다. 상태가 가능일 때만 처리할 수 있다.
// 프로퍼티를 추가할 때 상태 결정 (enumerable)
var obj = {}; /* 상태 디폴트 값 : true */
// defineProperty에서 상태 디폴트 값 : false 그래서 상태를 true로 변경해줘야함
Object.defineProperty(obj, "book", {
value: "JS북",
enumerable: true
});
console.log(obj);
/* defineProperties() */
// 다수의 프로퍼티를 추가하거나 속성 변경
var obj2 = {};
Object.defineProperties(obj2, {
soccer: {
value: "축구", enumerable: true
},
basketball: {
value: "농구", enumerable: true
}
});
for (var name in obj2){
console.log(name + ":" + obj2[name]);
};
/* 프로퍼티 디스크립터
프로퍼티의 속성 이름과 속성 값을 정의
디스크립터 타입 분류 - 데이터 프로퍼티 디스크립터
- 악세스(Access) 프로퍼티 디스크립터
- 공용 프로퍼티 디스크립터
디스크립터 타입에 속한 속상만 같이 사용할 수 있다.
데이터와 악세스는 함께 작성 할 수 없으므로 그것으로 어떤 프로퍼티 디스크립터인지 구분
*/
/* value 속성 */
// get/set속성과 함께 작성 불가
var obj3 = {};
Object.defineProperty(obj3, "book", {
value: "JS북",
enumerable: true
});
for (var name in obj3){
console.log(name);
console.log(obj3[name]);
};
/* writable 속성 */
// 프로퍼티 값 변경 가능, 불가능
// true: 프로퍼티 변경가능 false: 프로퍼티 변경 불가, 디폴트 값
var obj3 = {};
Object.defineProperty(obj3, "book", {
value: "JS북",
//변경 가능
writable: true
});
obj3.book = "변경 가능";
console.log(obj3.book);
// fasle면 프로퍼티 변경 불가, 에러가 발생하지 않지만 값 변경되지 않음
var obj3 = {};
Object.defineProperty(obj3, "book", {
value: "JS북",
//변경 가능
writable: false
});
obj3.book = "변경 불가능";
console.log(obj3.book);
/* enumerable 속성 */
// for ~ in으로 열거 가능 여부
// true : 열거 가능 false: 열거 불가능, 디폴트 값
var obj3 = {};
Object.defineProperty(obj3, "book", {
value: "JS책",
// 열거 가능 디폴트 값: false 이므로 무조건 작성해야함
enumerable: true
});
for (var name in obj3){
console.log(name + ":" + obj3[name]);
};
/* configurable 속성 */
// 프로퍼티 삭제 가능, 불가능
// true : 삭제 가능, value 이외 속성 변경 가능
// false : 삭제 불가능, value 이외 속성 변경 불가, 디폴트 값
var obj3 = {};
Object.defineProperty(obj3, "book", {
value: "JS북",
//삭제 가능
configurable: true
});
delete obj3.book;
console.log(obj3.book);
/* get 속성 */
// getter: OOP 용어
// 프로퍼티로 값을 구할 때 value속성이 없으면 get속성 호출하게 되는데 그것이 getter
var obj3 = {};
Object.defineProperty(obj3, "book", {
get: function () {
return "JS책";
}
});
var result = obj3.book;
console.log(result);
/* set 속성 */
// setter : OOP용어
// obj3.book에다가 "JS책"을 할당할 때 value속성이 없으니깐 set을 호출하게 된다 이것이 setter
var obj3 = {}, data = {};
Object.defineProperty(obj3, "book", {
set: function(param) {
data.title = param;
},
get: function() {
return data.title;
}
});
obj3.book = "JS책";
console.log(obj3.book);
/* getPrototypeOf() */
// 파라미터에 인스턴스를 작성하는데 인스턴스의 prototype에 연결된 프로퍼티 반환
function Book(point) {
this.point = point;
};
Book.prototype.getPoint = function () {};
Book.prototype.setPoint = function () {};
var obj = new Book(100);
var result = Object.getPrototypeOf(obj);
for (var key in result){
console.log(key + ":" + result[key]);
};
/* getOwnPropertyNames() */
// 파라미터에 오브젝트 작성. 오브젝트의 프로퍼티 이름을 배열로 반환
// 열거 가능 여부 체크하지 않음
// 자신이 만든 프로퍼티가 대상. 다른 오브젝트에서 받은 프로퍼티는 제외
var obj = {};
Object.defineProperties(obj, {
book: {value: "책"},
point: {value: 123}
});
var names = Object.getOwnPropertyNames(obj);
for (var k = 0; k < names.length; k++) {
console.log(names[k]);
};
/* keys() */
// 파라미터에 오브젝트 작성. 열거 가능 프로퍼티 이름 반환
var obj = {};
Object.defineProperties(obj, {
book: {
value: "책", enumerable: true},
point: {value: 123}
});
var names = Object.keys(obj);
for (var k = 0; k < names.length; k++) {
console.log(names[k]);
};
/* getOwnPropertyDescriptor() */
// 프로퍼티 디스크립터의 속성 이름, 값 반환
// 다른 오브젝트에서 받은 프로퍼티는 제외
var obj = {};
Object.defineProperty(obj, "book", {
value : "책",
writable: true, enumerable: true
});
var desc = Object.getOwnPropertyDescriptor(obj, "book");
for (var key in desc) {
console.log(key + ":" + desc[key]);
};
/* preventExtensions() */
// 오브젝트에 프로퍼티 추가 금지 설정
// 프로퍼티 삭제, 변경 가능
// 추가 금지를 설정한 후에는 추가 가능을 변경 불가
var obj = {};
Object.preventExtensions(obj);
try {
Object.defineProperty(obj, "book", {
value: "책"
});
} catch (e) {
console.log("추가 불가");
};
/* isExtensible() */
// 오브젝트에 프로퍼티 추가 금지 여부 반환
// true: 추가 가능 false: 추가 불가능
var obj = {};
Object.defineProperty(obj, "book", {
value : "책",
});
console.log(Object.isExtensible(obj));
Object.preventExtensions(obj);
console.log(Object.isExtensible(obj));
/* seal() */
// 프로퍼티 추가, 삭제 금지 설정
// 추가 금지 - 오브젝트 단위, 삭제 금지 - 프로퍼티 단위
var obj = {};
Object.defineProperty(obj, "book", {
value : "책", writable: true
});
Object.seal(obj);
try {
Object.defineProperty(obj, "sports", {
value: "스포츠"
});
} catch (e) {
console.log("추가 불가");
};
/* isSealed() */
// 추가, 삭제 금지 여부 반환
// true : 불가, false: 기능
var obj = {};
Object.defineProperty(obj, "book", {
value : "책", writable: true
});
console.log(Object.isSealed(obj));
Object.seal(obj);
console.log(Object.isSealed(obj));
/* freeze() */
// 추가, 삭제, 변경 금지 설정
var obj = {};
Object.defineProperty(obj, "book", {
value : "책", writable: true
});
Object.freeze(obj);
try {
Object.defineProperty(obj, "sports", {
value: "스포츠"
});
} catch (e) {
console.log("변경 불가")
}
console.log(obj.book);
/* isFrozen() */
// 추가, 삭제, 변경 금지 여부 반환
var obj = {};
Object.defineProperty(obj, "book", {
value : "책", writable: true
});
console.log(Object.isFrozen(obj));
Object.freeze(obj);
console.log(Object.isFrozen(obj)); |
function showHide(div) {
var target = document.getElementById(div);
if (target.style.display == "block") {
target.style.display = "none";
} else {
target.style.display = "block";
}
} |
class Constants
{
constructor()
{
this.SET_SCORE = "setScore"; //constant in uppercase
this.UP_POINTS = "upPoints";
this.SCORE_UPDATED="scoreUpdated";
this.PLAY_SOUND="playSound";
}
} |
// VARIABLES
let p1 = $('#p1');
let p2 = $('#p2');
let p3 = $('#p3');
let p1_w = $('#p1_w');
let p2_w = $('#p2_w');
let p3_w = $('#p3_w');
let reset5 = $('#m5');
let reset15 =$('#m15');
let reset35 = $('#m35');
let reset100 = $('#m100');
let objeto = $('#ball');
let cronometro = $('#chron');
let scene2 = $('#world1');
let scene1 = $('#scene1');
let portal1 = $('#portal1');
let portal2 = $('#portal2');
let portal3 = $('#portal3');
let portal4 = $('#portal4');
let env = $('#env')
//DEFAULT
let place = 'space';
let radius = 0.25
var currentTimestamp = moment();
var clockrun = false
var ultimoTiempo = 0;
var tiemposHistoricos = [];
var tiempo;
// let weight = 0.5; No usado por el momento
class Hint {
constructor() {
this.btn_tooltips1 = document.querySelector('#btn_tooltips1');
this.btn_tooltips2 = document.querySelector('#btn_tooltips2');
this.hint_rectangle = document.querySelector("#hint_rectangle");
this.dom = document.querySelector("#hints");
this.active = false;
this.step = 0;
// Cambios necesarios tutorial
this.planet = 'Tierra'
this.drop = 2
this.changeHintText("Hola!, bienvenido a umVRal experiencia 1: Caida libre. Para comenzar, selecciona hacia la derecha una esfera mirando a su peso (etiqueta).");
}
reset() {
this.step = 1;
this.active = false;
this.change_temp = 0;
//tengo q cambiar angulo horizontal 2 veces
this.pos_count = 3;
this.angle_count = 3;
}
fade_in() {
let that = this;
that.active = true;
that.dom.setAttribute('visible', true);
console.log("in fade in")
setTimeout(function(){
that.hint_rectangle.setAttribute('animation',"property: slice9.opacity; dir: alternate; dur: 1000; easing: easeInSine; loop: false; to: 0.7");
that.dom.setAttribute('animation',"property: text.opacity; dir: alternate; dur: 1000; easing: easeInSine; loop: false; to: 0.8");
}, 500);
}
fade_out() {
let that = this;
this.active = false;
setTimeout(function(){
that.hint_rectangle.setAttribute('animation',"property: slice9.opacity; dir: alternate; dur: 1000; easing: easeInSine; loop: false; to: 0");
that.dom.setAttribute('animation',"property: text.opacity; dir: alternate; dur: 1000; easing: easeInSine; loop: false; to: 0");
setTimeout(function(){
that.active = false;
that.hint_rectangle.setAttribute('visible', 'false');
that.dom.setAttribute('visible', 'false');
}, 1000);
}, 4000);
};
changeHintText(text) {
this.dom.setAttribute('text', {'value': text});
}
/* Funciones de Pasos*/
toStep1(){
let that = this;
if (that.step === 0 && that.active){
that.changeHintText('Bien!. Ahora, selecciona el planeta en el cual quieres experimentar la caida libre, en el panel de la izquierda.');
that.step = 1;
}
}
toStep2(){
let that = this;
if (that.step === 1 && that.active){
that.changeHintText('¡Bienvenido '+that.planet+'!. Ahora, centra la mira en las etiquetas destacadas de la regla Vertical, para lanzar pelota unas '+that.drop+' veces.');
that.step = 2;
}
}
toStep3(){
let that = this;
if (that.step === 2 && that.active){
that.changeHintText('Ahora, cambia la masa del objeto soltado en el panel de la izquierda. Selecciona un peso diferente a 0.5 kg.');
that.step = 3;
}
}
toStep4(){
let that = this;
if (that.step === 3 && that.active){
that.changeHintText('Bien!. Ahora lanza de nuevo la pelota una vez.');
that.step = 4;
}
}
toStep5(){
let that = this;
if (that.step === 4){
that.changeHintText('¡Muy bien!. Ya tienes los conocimientos para poder continuar con la experiencia.');
that.step = 5;
setTimeout(function(){ that.toStep6() }, 3000);
}
}
toStep6(){
let that = this;
if (that.step === 5){
that.changeHintText('Si miras hacia la derecha, puedes ver un portal. En el, puedes cambiar el planeta de la experiencia, para cambiar la gravedad. ¡Que rinda el estudio!.');
that.step = 6;
that.fade_out();
}
}
/* funciones conteo y auxiliares */
change_drop(){
let that = this;
console.log("in change drop");
if (that.step === 2){
console.log("si, entre al if del step = 2")
that.drop--;
if (that.drop === 1) {that.changeHintText('Lanza la pelota una vez más.');}
else {that.changeHintText('Lanza la pelota unas '+that.drop+' veces más.');}
if (that.drop <= 0){
that.toStep3();
}
}
}
}
hints = new Hint();
hints.btn_tooltips1.addEventListener('click', function(){
hints.active = true;
hints.fade_in();
hints.btn_tooltips2.setAttribute('visible', 'false')
pay = {
student_id: 301,
experience_id: 3,
slug: 'tutorial',
value: true,
//value_num: algun numero
}
this.setAttribute('visible', 'false');
//send2api(pay);
})
hints.btn_tooltips2.addEventListener('click', function(){
hints.active = true;
hints.step = 2;
hints.fade_in();
hints.btn_tooltips1.setAttribute('visible', 'false')
pay = {
student_id: 301,
experience_id: 3,
slug: 'tutorial',
value: true,
//value_num: algun numero
}
this.setAttribute('visible', 'false');
//send2api(pay);
})
// FUNCIONES
function setScene(world) {
if (world == 'luna') {
env.querySelectorAll("a-entity").forEach(e => e.parentNode.removeChild(e));
env.querySelectorAll("a-sky").forEach(e => e.parentNode.removeChild(e));
env.removeAttribute('environment');
env.setAttribute('environment', {preset: 'starry', active: 'true', grid: false, playArea: 1.1, groundColor: '#858585', groundColor2: '#898585', dressing: 'stones', dressingColor: '#6f6c6c', ground: 'canyon'});
colorRegla('cyan');
$('#selector').setAttribute('material','color: yellow; shader: flat');
$('a-scene').systems.physics.driver.world.gravity.y = -1.62;
$('#ball').setAttribute('geometry', 'primitive:sphere; radius: '+ radius +';');
}
if (world == 'tierra') {
env.querySelectorAll("a-entity").forEach(e => e.parentNode.removeChild(e));
env.querySelectorAll("a-sky").forEach(e => e.parentNode.removeChild(e));
env.removeAttribute('environment');
env.setAttribute('environment', {active: true, seed: 8, skyType: 'atmosphere', skyColor: '#2642b3', horizonColor: '#eff9b7', fog: 0.8, playArea: 1.2, ground: 'noise', groundYScale: 4.18, groundTexture: 'walkernoise', groundColor: '#17351c', groundColor2: '#2d2e1f', dressing: 'trees', dressingAmount: 80, dressingColor: '#003c00', dressingScale: 1, gridColor: '#c5a543', preset: 'forest'});
env.setAttribute('environment', {shadow: true})
colorRegla('black');
$('#regla100').setAttribute('visibility','');
$('a-scene').systems.physics.driver.world.gravity.y = -9.8;
$('#ball').setAttribute('geometry', 'primitive:sphere; radius: '+ radius +';');
}
if (world == 'marte') {
env.querySelectorAll("a-entity").forEach(e => e.parentNode.removeChild(e));
env.querySelectorAll("a-sky").forEach(e => e.parentNode.removeChild(e));
env.removeAttribute('environment');
env.setAttribute('environment', {active: true, preset: 'yavapai', skyType: 'atmosphere',skyColor: '#3c0404', horizonColor: '#ffaaaa', fog: 0.8, playArea: 1.1, dressingAmount: 165});
env.setAttribute('environment', {shadow: true});
$('#lights').setAttribute('visible', false);
colorRegla('black');
$('a-scene').systems.physics.driver.world.gravity.y = -3.7;
$('#ball').setAttribute('geometry', 'primitive:sphere; radius: '+ radius +';');
}
if (world == 'space') {
env.removeAttribute('environment');
$('#selector').setAttribute('material','color: black; shader: flat');
env.setAttribute('environment', {active: 'false'});
$('#lights').setAttribute('visible', true);
stopChron();
cleanButton(p1);
cleanButton(p2);
cleanButton(p3);
}
}
function colorRegla(color){
$('#regla').setAttribute('color', color);
$('#regla10').setAttribute('color', color);
$('#regla20').setAttribute('color', color);
$('#regla30').setAttribute('color', color);
$('#regla40').setAttribute('color', color);
$('#regla50').setAttribute('color', color);
$('#regla60').setAttribute('color', color);
$('#regla70').setAttribute('color', color);
$('#regla80').setAttribute('color', color);
$('#regla90').setAttribute('color', color);
}
function changeScene(sn1, sn2) {
var father = sn1.parentNode;
removeScene(father,sn1);
createScene(father,sn2);
setScene(place);
}
function registrarCaida(){
}
function removeScene(father, child) {
father.removeChild(child);
}
function createScene(father, child) {
father.appendChild(child);
}
function initChron() {
cronometro.setAttribute("value","00:00:00");
}
function resetChron(){
currentTimestamp = moment();
var nuevaMedicion = 0;
console.log($('#chron'));
console.log($('clock-text'));
console.log (ultimoTiempo);
var nuevoRegistro = ["luna",1.4,5,15,ultimoTiempo];
tiemposHistoricos.push(nuevoRegistro);
console.log(tiemposHistoricos);
}
function stopChron () {
clockrun = false;
}
function startChron() {
clockrun = true;
}
function setHeight(height) {
hints.change_drop();
objeto.body.position.set(0, height, -15);
objeto.body.velocity.set(0, 0, 0);
}
function cleanButton (btn) {
var temp = btn.querySelectorAll("a-entity");
if (temp.length != 1){
temp[0].parentNode.removeChild(temp[0]);
temp[1].parentNode.removeChild(temp[1]);
}
btn.querySelectorAll("a-sound").forEach(e => e.parentNode.removeChild(e));
}
function changeColor(value) {
if (value == 'p1') {
$('#obj1').setAttribute('color', 'red')
$('#obj2').setAttribute('color', 'blue')
$('#obj3').setAttribute('color', 'blue')
weight = "0.5";
radius = "0.25";
}
else if (value == 'p2') {
$('#obj1').setAttribute('color', 'blue')
$('#obj2').setAttribute('color', 'red')
$('#obj3').setAttribute('color', 'blue')
weight = "10";
radius = "0.6";
}
else if (value == 'p3') {
$('#obj1').setAttribute('color', 'blue')
$('#obj2').setAttribute('color', 'blue')
$('#obj3').setAttribute('color', 'red')
weight = "100";
radius = "1";
}
else if (value == 'p1_w') {
$('#p1_w').setAttribute('button-color', 'red');
$('#p2_w').setAttribute('button-color', 'blue');
$('#p3_w').setAttribute('button-color', 'blue');
weight = "0.5";
radius = "0.25";
$('#ball').removeAttribute('dynamic-body');
$('#ball').object3D.position.set(0,3,-15);
$('#ball').setAttribute('geometry', 'primitive:sphere; radius: '+ radius +';');
$('#ball').setAttribute('dynamic-body','mass:'+weight+';');
}
else if (value == 'p2_w') {
$('#p1_w').setAttribute('button-color', 'blue');
$('#p2_w').setAttribute('button-color', 'red');
$('#p3_w').setAttribute('button-color', 'blue');
weight = "10";
radius = "0.6";
$('#ball').removeAttribute('dynamic-body');
$('#ball').object3D.position.set(0,3,-15);
$('#ball').removeAttribute('geometry');
$('#ball').setAttribute('geometry', 'primitive:sphere; radius: '+ radius +';');
$('#ball').setAttribute('dynamic-body','mass:'+weight+';');
}
else if (value == 'p3_w') {
$('#p1_w').setAttribute('button-color', 'blue');
$('#p2_w').setAttribute('button-color', 'blue');
$('#p3_w').setAttribute('button-color', 'red');
weight = "100";
radius = "1";
$('#ball').removeAttribute('dynamic-body');
$('#ball').object3D.position.set(0,3,-15);
$('#ball').setAttribute('geometry', 'primitive:sphere; radius: '+ radius +';');
$('#ball').setAttribute('dynamic-body','mass:'+weight+';');
}
}
p1_w.addEventListener('click', function () {
changeColor('p1_w');
});
p2_w.addEventListener('click', function () {
changeColor('p2_w');
hints.toStep4();
});
p3_w.addEventListener('click', function () {
changeColor('p3_w');
hints.toStep4();
});
p1.addEventListener('click', function () {
changeColor('p1');
hints.toStep1();
});
p2.addEventListener('click', function () {
changeColor('p2');
hints.toStep1();
});
p3.addEventListener('click', function () {
changeColor('p3');
hints.toStep1();
});
$('#obj1').addEventListener('click', function () {
hints.toStep1();
changeColor('p1');
});
$('#obj2').addEventListener('click', function () {
hints.toStep1();
changeColor('p2');
});
$('#obj3').addEventListener('click', function () {
hints.toStep1();
changeColor('p3');
});
$('#box1').addEventListener('click', function () {
changeColor('p1');
});
$('#box2').addEventListener('click', function () {
changeColor('p2');
});
$('#box3').addEventListener('click', function () {
changeColor('p3');
});
reset5.addEventListener("click", function(){
setHeight(5);
resetChron();
startChron();
});
$('#regla5').addEventListener("click", function(){
setHeight(5);
hints.toStep5();
resetChron();
startChron();
});
reset15.addEventListener("click", function(){
setHeight(15);
hints.toStep5();
resetChron();
startChron();
});
$('#regla15').addEventListener("click", function(){
setHeight(15);
hints.toStep5();
resetChron();
startChron();
});
reset35.addEventListener("click", function(){
setHeight(35);
hints.toStep5();
resetChron();
startChron();
});
$('#regla35').addEventListener("click", function(){
setHeight(35);
hints.toStep5();
resetChron();
startChron();
});
reset100.addEventListener("click", function(){
setHeight(100);
hints.toStep5();
resetChron();
startChron();
});
$('#regla100').addEventListener("click", function(){
setHeight(100);
hints.toStep5();
resetChron();
startChron();
});
portal1.addEventListener("click", function () {
place = 'tierra';
hints.step = 1;
hints.planet = "al planeta Tierra"
hints.toStep2();
//correccion de angulo de observador
var x = $('#cam').getAttribute('rotation').x;
var y = ($('#cam').getAttribute('rotation').y)*(-1);
var z = $('#cam').getAttribute('rotation').z;
$('#camWrapper').setAttribute('rotation','0 '+y+' 0');
changeScene(scene1, scene2);
initChron();
});
portal2.addEventListener("click", function () {
place = 'luna';
hints.planet = "a la Luna"
hints.step = 1;
hints.toStep2();
var x = $('#cam').getAttribute('rotation').x;
var y = ($('#cam').getAttribute('rotation').y)*(-1);
var z = $('#cam').getAttribute('rotation').z;
$('#camWrapper').setAttribute('rotation','0 '+y+' 0');
changeScene(scene1, scene2);
initChron();
});
portal3.addEventListener("click", function () {
place = 'marte';
hints.planet = "al planeta Marte"
hints.step = 1;
hints.toStep2();
var x = $('#cam').getAttribute('rotation').x;
var y = ($('#cam').getAttribute('rotation').y)*(-1);
var z = $('#cam').getAttribute('rotation').z;
$('#camWrapper').setAttribute('rotation', '0 '+y+' 0');
changeScene(scene1, scene2);
initChron();
});
portal4.addEventListener("click", function () {
place = 'space'; //Default
var x = $('#cam').getAttribute('rotation').x;
var y = ($('#cam').getAttribute('rotation').y)*(-1);
var z = $('#cam').getAttribute('rotation').z;
$('#camWrapper').setAttribute('rotation', '0 '+y+' 0');
changeScene(scene2, scene1);
})
on(objeto, 'collide', (e) => {
stopChron();
// En el eventual caso que siga cayendo la pelota, aqui colocar la posición especifica
});
|
(function(shoptet) {
function validateRequiredField(el) {
if (el.classList.contains('js-validation-suspended')) {
return true;
}
// TODO: support for other than text fields
if (!el.value.length && !el.classList.contains('no-js-validation')) {
shoptet.validator.addErrorMessage(
el,
shoptet.validatorRequired.messageType
);
shoptet.scripts.signalCustomEvent('ShoptetValidationError', el);
} else {
phoneWrapper = el.parentElement;
shoptet.validator.removeErrorMessage(el, shoptet.validatorRequired.messageType);
}
}
shoptet.validatorRequired = shoptet.validatorRequired || {};
shoptet.scripts.libs.validatorRequired.forEach(function(fnName) {
var fn = eval(fnName);
shoptet.scripts.registerFunction(fn, 'validatorRequired');
});
shoptet.validatorRequired.messageType = 'validatorRequired';
shoptet.validatorRequired.validators = {
requiredInputs: {
elements: document.getElementsByClassName('js-validate-required'),
events: ['change', 'blur', 'validatedFormSubmit'],
validator: shoptet.validatorRequired.validateRequiredField,
fireEvent: false
}
};
for (var i = 0; i < shoptet.validator.events.length; i++) {
document.addEventListener(shoptet.validator.events[i], function() {
shoptet.validator.handleValidators(shoptet.validatorRequired.validators);
});
}
})(shoptet);
|
angular.module('issueTrackingSystem.users.changePassword', [])
.config([
'$routeProvider',
function ($routeProvider) {
$routeProvider.when('/profile/password', {
controller: 'ProfileController',
templateUrl: 'app/users/change-password.html',
resolve: {
access: ['$location', 'identity', function($location, identity){
if(!identity.isAuthenticated()){
$location.path('/');
}
}]
}
})
}])
.controller('ProfileController', [
'$scope',
'authentication',
'Notification',
function($scope, authentication, Notification){
$scope.changePassword = function(changedPassword){
authentication.changePassword(changedPassword)
.then(function(){
Notification.success('Password changed succesfully!');
});
}
}
]) |
import React, { Component } from 'react'
import { func, string } from 'prop-types';
import styled from 'styled-components'
import { Relative, Button, Heading, Flex, Text, Donut } from 'rebass'
export default class Guess extends Component {
state = {
currentCount: 30,
}
static propTypes = {
nextWord: func.isRequired,
team: string.isRequired,
word: string.isRequired,
onChallenge: func.isRequired,
}
componentDidMount() {
this.intervalId = setInterval(this.timer, 1000);
}
componentWillUnmount() {
clearInterval(this.intervalId);
}
componentWillReceiveProps(nextProps) {
this.setState({ currentCount: 30 })
}
timer = () => {
this.setState({
currentCount: this.state.currentCount - 1
})
if (this.state.currentCount < 1) {
this.props.nextWord(this.props.team, 0)()
this.setState({ currentCount: 30 })
}
}
warning = (colour) => {
return this.state.currentCount <= 5 ? 'red' : colour
}
render() {
const { word, nextWord, team, onChallenge } = this.props
const { currentCount } = this.state
return(
<div>
<Heading
center
f={75}
bg={this.warning('primary')}
px={6}
py={3}
color='textP'
children={word.toUpperCase()}
/>
<Text center pt={4}>
<Button
onClick={onChallenge}
bg="pink"
px={5}
children="CHALLENGE"
/>
</Text>
<Flex px={5} mt={4} justify='center' align='center' >
<Relative>
<Donut
value={currentCount/30}
strokeWidth={5}
size={250}
color={this.warning('secondary')}
/>
<Count
bold
f={6}
children={currentCount}
color='primary'
/>
</Relative>
</Flex>
<Text center py={4}>
<Button
onClick={nextWord(team, 1)}
bg='green'
px={3}
mx={3}
children="GOT IT"
/>
<Button
onClick={nextWord(team, 0)}
bg='red'
px={3}
mx={3}
children="I SUCK"
/>
</Text>
</div>
)
}
}
// STYLES
const Count = styled(Text)`
position: absolute;
top: 50%; /* position the top edge of the element at the middle of the parent */
left: 50%; /* position the left edge of the element at the middle of the parent */
transform: translate(-50%, -50%);
`
|
// A. Q + A
// How do we assign a value to a variable?
// You use var, let, or const. = to whatever value or string you want it to be.
// How do we change the value of a variable?
// you would call the variable and then = to another value.
// How do we assign an existing variable to a new variable?
// you would first call the new variable and then = it to the exisiting variable
// Remind me, what are declare, assign, and define?
// Declaring refers to the variable and scope you are defining, and assigning is the value you are giving
// that variable
// For example, let(declare) num(define) =(assign)100; you use let, var, or const to
// What is pseudocoding and why should you do it?
// This is when you are formulating out what the code should run for the situtation.
// You break down the process step by step, so you can easily see what exactly you need to accomplish.
// This is good to organize your thoughts and to prepare the system to run the code.
// What percentage of time should be spent thinking about how you're going to solve a
// problem vs actually typing in code to solve it?
// You should spend 75%-80% thinking about how to solve the problem and the rest of the time typing code to solve it.
// B. Strings
// Create a variable called firstVariable.
let firstVariable;
// Assign it the value of the string "Hello World"
firstVariable = "Hello World";
// Change the value of this variable to some number.
firstVariable = 9000;
// Store the value of firstVariable in a new variable called secondVariable
let secondVariable = firstVariable;
// Change the value of secondVariable to any string.
secondVariable = "It's over 9000!!"
// What is the value of firstVariable?
// 9000
// Create a variable called yourName and set it equal to your name as a string.
let yourName = "Joshua Ablan"
// Then, write an expression that takes the string "Hello, my name is " and the
// variable yourName
// so that it returns a new string with them concatenated.
console.log(`Hello my name is ${yourName}`)
// C. Booleans
// Using the provided variable definitions,
// replace the blanks so that all log statements
// print true in the console. Answers should be all be
// valid JS syntax and not weird things that
// don't make sense but happen to print true to the console.
const a = 4;
const b = 53;
const c = 57;
const d = 16;
const e = 'Kevin';
console.log(a !== b);
console.log(c !== d);
console.log('Name' === 'Name');
console.log(true !== false);
console.log(false && false && false && false && false && false || true);
console.log(false === false);
console.log(e == 'Kevin');
console.log(a !== b !== c);
console.log(a === a || d);
console.log(48 == '48');
// D. The farm
// Declare a variable animal. Set it to be either "cow"
// or something else.
let animal = "yup";
// Write code that will print out "mooooo" if the it is equal to cow.
if (animal === "cow") {
console.log("Moooooooo")
// Change your code so that if the variable animal is
// anything other than a cow, it will print "Hey! You're not a cow."
} else {
console.log("Hey! You're not a cow!");
}
// Commit.
// E. Driver's Ed
// Make a variable that will hold a person's age. Be semantic.
let age = 19;
// // Write code that will print out "Here are the keys",
// if the age is 16 years or older.
if (age >= 16) {
console.log(`Here are the keys. You are ${age} years old.`)
} else {
console.log(`Sorry! you're too young. You are only ${age} years old!`)
};
// // If the age is younger than 16, a message
// should print "Sorry, you're too young."
// // Commit.
// II. Loops
// A. The basics
// Write a loop that will print out all the numbers from 0 to 10, inclusive.
for (let i = 0; i < 10; i++) {
console.log(i);
}
// Write a loop that will print out all the numbers from 10 up to and including 400.
for (let i = 10; i <= 400; i++) {
console.log(i);
}
// Write a loop that will print out every third number starting with 12 and going no higher than 4000.
for (let i = 12; i < 4000; i+=3) {
console.log(i);
}
// 🔴 Commit.
// B. Get even
// Print out the even numbers that are within the range of 1 - 100.
for (let i = 0; i <=100; i++)
if (i % 2 ===0) {
console.log(i);
}
// Adjust your code to add a message next to even numbers only that says: "<-- is an even number".
for (let i = 0; i <=100; i++)
if (i % 2 ===0) {
console.log(`${i} <---- is an even number`);
}
// 🔴 Commit.
// C. Give me Five
// For the numbers 0 - 100, print out
//"I found a number. High five!" if the number is a multiple of five.
// Example Output:
// I found a 5. High five!
// I found a 10. High five!
// Add to the code from above to print out "I found a number.
// Three is a crowd" if the number is a multiple of three.
// Example Output:
// I found a 3. Three is a crowd
// I found a 5. High five!
// I found a 6. Three is a crowd
// I found a 9. Three is a crowd
// I found a 10. High five!
for (let i = 0; i <=100; i++) {
if (i % 3 ===0) {
console.log(`I found a ${i}. Three is a crowd!`)
} else if (i % 5 === 0) {
console.log(`I found a ${i}. High five!`)
};
};
// 🔴 Commit.
// D. Savings account
// Write code that will save the sum of all the numbers between 1 - 10 to a
//variable called bank_account.
// Check your work! Your bank_account should have $55 in it.
let bank_account = 0;
for (let i =0; i <= 10; i++) {
bank_account += i;
};
// You got a bonus! Your pay is now doubled each week. Write code that will
// save the sum of all the numbers between 1 - 100 multiplied by 2.
// Check your work! Your bank_account should have $10,100 in it.
let dank_Account = 0;
for (let i =0; i <= 100; i++) {
dank_Account += i * 2;
}; console.log(`Your bank account is dank! It has $${dank_Account} doll-hairs!`);
// 🔴 Commit.
// E. Multiples of 3 and 5
// If we list all the natural numbers below 10 that are multiples of 3 or 5,
//we get 3, 5, 6 and 9. The sum of these multiples is 23.
// Find the sum of all the multiples of 3 or 5 below 1000. If a previous
// question you've done has helpful bits of code in it that partially
// solves this problem, look back at them.
// You just solved Project Euler problem 1!
// Are you having dejà vu? This just in! From the
//"Read the entire problem before you start" dept:
//This problem was on a previous assignment. You may skip it
//if you've already done it, just include a comment saying that you've
//already done it. If you've now done the problem twice, perhaps next
// time you'll read the whole problem before starting it.
console.log("I have already done this!");
// 🔴 Commit.
// III. Arrays & Control flow
// A. Talk about it:
// What are the things in an array called?
// They are called elements.
// Do Arrays guarantee those things will be in order?
// Elements are set in a order starting at an index of 0.
// What real-life thing could you model with an array?
// You can model anything that is a list!
//For example, you can list the people who live in your house.
// 🔴 Commit.
// B. Easy Does It
// Create an array that contains three quotes and store it in a variable called quotes.
const quotes = ["Don't think, FEEEL","The Force is strong with this one.","A quote within a qoute."]
// 🔴 Commit.
// C. Accessing elements
// Given the following array const randomThings = [1, 10, "Hello", true]
const randomThings = [1, 10, "Hello", true]
// How do you access the 1st element in the array?
randomThings[0];
// Change the value of "Hello" to "World".
randomThings[2] = "World";
// Check the value of the array to make sure it updated the array. How? Why, yes! console.log();
console.log(randomThings);
// 🔴 Commit.
// D. Change values
// Given the following array const ourClass = ["Salty", "Zoom", "Sardine", "Slack", "Github"]
const ourClass = ["Salty", "Zoom", "Sardine", "Slack", "Github"];
// What would you write to access the 3rd element of the array?
ourClass[2];
// Change the value of "Github" to "Octocat"
ourClass[4] = "Outcocat";
// Add a new element, "Cloud City" to the array.
ourClass.push("Cloud City");
// 🔴 Commit.
// E. Mix It Up
// Given the following array: const myArray = [5, 10, 500, 20]
const myArray = [5, 10, 500, 20]
// Add the string "Egon" to the end of the array.
// Add another string of your choice to the end of the array.
myArray.push("Egon","Pie");
// Remove the 5 from the beginning of the array.
myArray.shift();
// Add the string "Bob Marley" to the beginning of the array.
myArray.unshift("Bob Marley");
// Remove the string of your choise from the end of the array.
myArray.pop();
// Reverse this array using Array.prototype.reverse().
myArray.reverse();
// Did you mutate the array? What does mutate mean?
// Yes, we mutated the array. This means we did not make myArray equal another array,
// but we changes the contents/values inside the array itself.
// Did the .reverse() method return anything?
// It reversed the order of the array.
// 🔴 Commit.
// F. Biggie Smalls
// Create a variable that contains an integer.
const integer = 87;
// Write an if ... else statement that:
if (integer <= 100) {
console.log("little number");
} else {
console.log("big number");
};
// console.log()s "little number" if the number is entered is less than 100
// console.log()s big number if the number is greater than or equal to 100.
// 🔴 Commit.
// G. Monkey in the Middle
// Write an if ... else if ... else statement:
let num = 7;
if (num < 5){
// console.log() little number if the number entered is less than 5.
console.log("Little number");
// If the number entered is more than 10, log big number.
} else if (num > 10) {
console.log("Big number");
// Otherwise, log "monkey".
} else {
console.log("monkey");
};
// 🔴 Commit.
// H. What's in Your Closet?
// Below, we've given you examples of Kristyn and Thom's closets modeled as data in JavaScript.
const kristynsCloset = [
'left shoe',
'cowboy boots',
'right sock',
'GA hoodie',
'green pants',
'yellow knit hat',
'marshmallow peeps'
];
// Thom's closet is more complicated. Check out this nested data structure!!
const thomsCloset = [
[
// These are Thom's shirts
'grey button-up',
'dark grey button-up',
'light blue button-up',
'blue button-up'
],
[
// These are Thom's pants
'grey jeans',
'jeans',
'PJs'
],
[
// Thom's accessories
'wool mittens',
'wool scarf',
'raybans'
]
];
// What's Kristyn wearing today? Using bracket notation to access items in kristynsCloset,
//log the sentence "Kristyn is rocking that " + the third item in Kristyn's closet + " today!" to the console.
console.log("Kristyn is rocking that " + kristynsCloset[2] + " today!")
// Kristyn just bought some sweet shades! Add "raybans" to her closet after "yellow knit hat".
kristynsCloset.splice(6,0,"raybans");
// Kristyn spilled coffee on her hat... modify this item to read "stained knit hat" instead of yellow.
kristynsCloset[5] = "stained knit hat";
// Put together an outfit for Thom! Using bracket notation, access the first element in Thom's shirts array.
thomsCloset[0][2];
// In the same way, access one item from Thom's pants array.
thomsCloset[1][1];
// Access one item from Thom's accessories array.
thomsCloset[2][1];
// Log a sentence about what Thom's wearing. Example: "Thom is looking fierce in a grey button-up, jeans and wool scarf!"
console.log(` Thom is lookin fire in his ${thomsCloset[0][3]} and his flashy ${thomsCloset[2][2]}.`)
// Get more specific about what kind of PJs Thom's wearing this winter. Modify the name of his PJ pants to Footie Pajamas.
thomsCloset[1][2] = "Footie Pajamas";
// 🔴 Commit.
// IV. Functions
// A. printGreeting
console.log("I already complete printGreeting!");
// B. printCool
// Write a function printCool that accepts one parameter,
// name as an argument. The function should print the name and a message
// saying that that person is cool.
const printCool = (str) => {
console.log(`${str} is cool!`);
};
printCool("GA");
// console.log(printCool('Captain Reynolds'));
// => "Captain Reynolds is cool";
// 🔴 Commit.
// C. calculateCube
// Write a function calculateCube that takes a single number
// and prints the volume of a cube made from that number.
const calculateCube = (num) => {
console.log(Math.pow(num, 3));
};
calculateCube(3);
// console.log(calculateCube(5));
// => 125
// 🔴 Commit.
// D. isVowel
// Write a function isVowel that takes a character
// (i.e. a string of length 1) and returns true if it
// is a vowel, false otherwise. The vowel could be upper or lower case.
let vowels = ["a","e","i","o","u"]
const isVowel = (str) => {
return vowels.indexOf(str.toLowerCase()) !== -1;
}
// console.log(isVowel('a'));
// => true
// 🔴 Commit.
// E. getTwoLengths
// Write a function getTwoLengths that accepts two parameters (strings).
// The function should return an array of numbers where each number is
// the length of the corresponding string.
let value = [];
const getTwoLengths = (a,b) => {
value.push(a.length, b.length);
console.log(value);
};
getTwoLengths("hellllooo","threeee");
// console.log(getTwoLengths('Hank', 'Hippopopalous'));
// => [4, 13]
// 🔴 Commit.
// F. getMultipleLengths
// Write a function getMultipleLengths that accepts a single parameter
// as an argument: an array of strings. The function should return an array
// of numbers where each number is the length of the corresponding string.
let emptyArray = [];
const getMultipleLengths = (array) => {
for (let i = 0; i < array.length; i++) {
emptyArray.push(array[i].length);
}; console.log(emptyArray)
};
getMultipleLengths(["Get","these","lengths","now"]);
// console.log(getMultipleLengths(['hello', 'what', 'is', 'up', 'dude']));
// => [5, 4, 2, 2, 4]
// 🔴 Commit.
// G. maxOfThree
// Define a function maxOfThree that takes three numbers as arguments
// and returns the largest of them. If all numbers are the same, it doesn't
// matter which one is returned. If the two largest numbers are the same, one of them
// should be returned.
const maxOfThree = (a,b,c) => {
console.log(Math.max(a,b,c));
};
maxOfThree(2,1,3);
// console.log(maxOfThree(6, 9, 1));
// => 9
// 🔴 Commit.
// H. printLongestWord
// Write a function printLongestWord that accepts a single
// argument, an array of strings. The method should return the longest word in the
// array. In case of a tie, the method should return the word that appears first in the array.
let longestFirst = [];
const printLongestWord = (arr) => {
longestFirst = arr.sort();
console.log(longestFirst[0]);
};
printLongestWord(["This is short","This is Lonnnngggestttt","this is loooonger","This is small"]);
// console.log(
// printLongestWord([
// 'BoJack',
// 'Princess',
// 'Diane',
// 'a',
// 'Max',
// 'Peanutbutter',
// 'big',
// 'Todd'
// ])
// );
// => "Peanutbutter"
// 🔴 Commit.
// I. transmogrify
// Write a Javascript function called transmogrify. This function should accept three arguments,
// which you can assume will be numbers. Your function should return the "transmogrified" result.
// The transmogrified result of three numbers is the product of the first two numbers,
// raised to the power of the third number.
// For example, the transmogrified result of 5, 3, and 2 is (5 times 3) to the power of 2 is 225.
// console.log(transmogrify(5, 3, 2));
// => 225
const transmogrify = (e,d,f) => {
console.log(Math.pow((e*d),f));
};
transmogrify(9,5,5);
// 🔴 Commit.
// J. reverseWordOrder v2
// Without using .split(), .reverse(), or .join(), write a function
// reverseWordOrder that accepts a single argument, a string. The function should
// return a string with the order of the words reversed. Don't worry about punctuation.
// See if you can do it without googling.
// Remember: Jim showed you today that you can index directly into a string:
// 'hello world'[6];
// => "w"
// That and basic loops and variables and arrays are all you need to solve this
// without the Array methods.
// console.log(reverseWordOrder('Ishmael me Call'));
// => "Call me Ishmael"
// console.log(reverseWordOrder('I use Lâncome on my comb'));
// => "comb my on Lâncome use I"
let newWords = [""];
let revSent = "";
const reverseWordOrder = (str) => {
for(let i = 0; i < str.length; i++){
if(str[i] !== " ")
newWords[newWords.length - 1] += str[i];
else if(newWords[newWords.length - 1])
newWords.push("");
}
for (let i = newWords.length-1; i >= 0; i--) {
revSent += newWords.pop() + " ";
// revSent += newWords[i] + " ";
} return console.log(revSent);
}
reverseWordOrder("Hello my name is Joshua");
// 🔴 Commit.
// K. Get down and dirty with Math.random()
// Write a function that will return a random integer between 1 and 10. Test it.
const ran1 = (num1,num2) => {
console.log(Math.floor(Math.random() * (num2-num1 +1) + 1));
}
ran1(1,10);
// Write a function that will return a random integer between 10 and 100. Test it.
const ran2 = (a,b) => {
console.log(Math.floor(Math.random() * (b-a +1) + 1));
}
ran2(10,100);
// Write a function that will return a random number between 532 and 13267. Test it.
const ran3 = (num1,num2) => {
console.log(Math.random() * (num2-num1) + num1);
}
ran3(532,13267);
// Write a function that will return a random number between 1 and 10. Test it.
const ran4 = (num1,num2) => {
console.log(Math.random() * (num2-num1) + num1);
}
ran4(1,10);
// Add a few more quotes to the quotes array from question III-B-1 above.
quotes.push("This is the Fellowship of the Ring!","I read you straight out of a comic book.");
// Write a function that will take an array as a parameter, and return a
const getRandomElement = (arrr) => {
console.log(arrr[Math.floor(Math.random()* arrr.length)])
};
getRandomElement(quotes);
// random element from that array. Call your function a few times,
// passing in the quotes array. Give it a nice semantic name like getRandomElement.
// 🔴 Commit.
// A. Make a user object
// Create an object called user.
// Write in to the object the key-value pairs for name, email, age,
// and purchased. Set the value of purchased to an empty array [].
const user = {
name: "Cowboy Bep",
email: "bepop@hotmail.com",
age: 25,
purchased: [],
};
//Set the other values to whatever you would like.
// 🔴 Commit.
// B. Update the user
// Our user has changed his or her email address. Without changing
//the original user object, update the email value to a new email address.
user.email = "ghostinthe@shell.com";
// Our user has had a birthday! Without changing the original user object,
// increment the age value using the postfix operator. Hint: age++
user.age++;
// 🔴 Commit.
// C. Adding keys and values
// You have decided to add your user's location to the data that you want to collect.
user.location = "The Hidden Lead Village";
// Without changing the original user object, add a new key location to
//the object, and give it a value or some-or-other location (a string).
// 🔴 Commit.
// D. Shopaholic!
// Our user has purchased an item! They have purchased some "carbohydrates".
// Using .push(), add the string "carbohydrates" to the purchased array.
user.purchased.push("carbohydrates");
// Our user has purchased an item! They have purchased some "peace of mind".
//Using .push(), add the string "peace of mind" to the purchased array.
user.purchased.push("peace of mind");
// Our user has purchased an item! They have purchased some "Merino jodhpurs".
//Using .push(), add the string "Merino jodhpurs" to the purchased array.
user.purchased.push("Merino jodhpurs");
// Console.log just the "Merino jodhpurs" from the purchased array.
console.log(user.purchased[2]);
// 🔴 Commit.
// E. Object-within-object
// Remember that you can add an object to an existing object in the same way
//that you can add any new property/value pair.
// If we want to give our user a friend with a name and age, we could write:
// user.friend = {
// name: 'Grace Hopper',
// age: 85
// };
// When we console.log user, we would see the friend object added to our user object.
// Write a friend object into your user object and give the friend a name, age,
//location, and purchased array (empty for now)
user.friend = {
name: "Sasake",
age: 31,
location: "Missing",
purchased: [],
};
// Console.log just the friend's name
console.log(user.friend.name);
// Console.log just the friend's location
console.log(user.friend.location);
// CHANGE the friend's age to 55
user.friend.age = 55;
// The friend has purchased "The One Ring". Use .push() to add "The One Ring" to
//the friend's purchased array.
user.friend.purchased.push("The One Ring");
// The friend has purchased "A latte". Use .push() to add "A latte" to the friend's
// purchased array.
user.friend.purchased.push("A latte");
// Console.log just "A latte" from the friend's purchased array.
console.log(user.friend.purchased[1]);
// 🔴 Commit.
// F. Loops
// Write a for loop that iterates over the User's purchased array
//(NOT the friend's purchased array), and prints each element to the console.
for (let i = 0; i < user.purchased.length; i++) {
console.log(user.purchased[i]);
}
// Write a for loop that iterates over the Friend's purchased array,
//and prints each element to the console.
for (let i = 0; i < user.friend.purchased.length; i++) {
console.log(user.friend.purchased[i]);
}
// 🔴 Commit.
// G. Functions can operate on objects
// Write a single function updateUser that takes no parameters.
const updateUser = () => {
user.age++
user.name = user.name.toUpperCase();
};
//When the function is run, it should:
// it should increment the user's age by 1
// make the user's name uppercase
// The function does not need a return statement, it will merely modify the user object.
// Write a function oldAndLoud that performs the exact same tasks as
// updateUser, but instead of hard-coding it to only work on our user object,
// make it take a parameter person, and have it modify the object that is passed in as
//an argument when the function is called. Call your oldAndLoud function with user as the argument.
const updateUser2 = (obj) => {
obj.age++
obj.name = obj.name.toUpperCase();
};
updateUser2(user);
// 🔴 Commit. |
;(function($,window, undefined){
// 'use strict';
var pluginName = 'html5-video',
win = $(window);
function playPause(videoID) {
var vid = document.getElementById(videoID);
if(vid.paused){
vid.play();
} else {
vid.pause();
}
}
function Plugin(element, options) {
this.element = $(element);
this.options = $.extend({}, $.fn[pluginName].defaults, this.element.data(), options);
this.init();
}
Plugin.prototype = {
init: function() {
var that = this,
el= this.element;
el.find('[data-video-html5-control]').on('click', function() {
var elDataPluginVideo = $(this).closest('[data-plugin-video]');
var vidId = elDataPluginVideo.find('video').attr('id');
elDataPluginVideo.find('[data-video-background]').fadeOut(300);
$(this).fadeOut(300);
playPause.call(this, vidId);
});
win.on('resize.' + pluginName, function() {
console.log('resize');
});
},
destroy: function() {
this.element.off('init.' + pluginName);
win.off('resize.' + pluginName);
$.removeData(this.element[0], pluginName);
}
};
$.fn[pluginName] = function(options, params) {
return this.each(function() {
var instance = $.data(this, pluginName);
if (!instance) {
$.data(this, pluginName, new Plugin(this, options));
} else if (instance[options]) {
instance[options](params);
}
});
};
$.fn[pluginName].defaults = {
};
$(function() {
$('[data-' + pluginName + ']')[pluginName]();
});
}(jQuery, window));
|
var concat = require('gulp-concat');
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var paths = {
exclude: '!./node_modules/**',
javascript: './src/**/*.js'
};
var watches = {
javascript: 'javascript-watch'
}
/************************Javascript*****************************/
gulp.task('javascript', function() {
return gulp.src([paths.javascript, paths.exclude])
.pipe(concat('all.js'))
.pipe(gulp.dest("./dist"));
});
gulp.task(watches.javascript, ['javascript'], function() {
browserSync.reload();
console.log("javascript reload complete");
});
/************************Javascript*****************************/
/************************Watch Settings*************************/
gulp.task('watch', ['browser-sync'], function() {
gulp.watch([paths.javascript, paths.exclude], [watches.javascript]);
});
gulp.task('default', ['watch'], function () {
var pathNames = Object.getOwnPropertyNames(paths);
pathNames.forEach(function(item) {
console.log("Watching " + item);
});
});
/************************Watch Settings*************************/ |
/**
* Code to calculate distribution based on molecular formula
*/
class MolecularFormulae{
constructor(){
this.averagine = "C4.9384H7.7583N1.3577O1.4773S0.0417" ;
this.avrgMass = 111.0543055992;
this.atomList = ["C","H","N","O","S"]
this.carbonCnt = 4.9384;
this.hydrogenCnt = 7.7583;
this.nitrogenCnt = 1.3577;
this.oxygenCnt = 1.4773
this.sulphurCnt = 0.0417;
this.minintensity = 0.0001;
this.protonMass = 1.00727647 ;
this.eachAtomCount;
this.toleraceMassDiff = 0.01;
this.mininte = 1;
this.intensityTolerance = 1 ;
}
/**
* Function to calculate the emass distrubution fo the given sequence
* @param {Double} mass - Contains the mass at that position of the sequence
* @param {Array} peakDataList - Contains the peak list provided by the user
* @param {Float} charge - Contains the chrage of the ion
*/
emass(mass,charge, modifiedPeakList){
//Give the count of each atom in molecule
this.eachAtomCount = mass/this.avrgMass ;
let calculatedMass;
let atomCountList ;
[atomCountList,calculatedMass] = this.getMolecularFormula() ;
let massError = mass - calculatedMass ;
let len = atomCountList.length;
let totDistributionList = [] ;
let numOfAtoms = this.atomList.length ;
for(let i=0;i<len;i++)
{
for(let j=0;j<atomCountList[i].count;j++)
{
let atomdist = getIsotopicMassRef(atomCountList[i].atom);
totDistributionList = this.getMassAndIntensity(totDistributionList,atomdist);
}
}
for(let k=0;k<totDistributionList.length;k++)
{
for(let i = 0; i < numOfAtoms ; i++)
{
let IsotopicMass = getIsotopicMassOfAtom(atomCountList[i].atom);
totDistributionList[k].mass = totDistributionList[k].mass + (IsotopicMass[0].mass * atomCountList[i].count) ;
}
}
totDistributionList = this.getMZwithHighInte(totDistributionList,charge,massError,modifiedPeakList);
this.getNormalizedIntensityAndAdjustedEnvelopes(totDistributionList,modifiedPeakList);
return totDistributionList;
}
/**
* Logic to calculate distribution
* @param {Array} totDistributionList - Array with current total distribution
* @param {Array} aminoAcidDist - Array with existing calculated distribution of amino acid
*/
getMassAndIntensity(totDistributionList,atomdist){
let maxintensity = 0 ;
if(totDistributionList.length == 0)
{
return atomdist ;
}
else
{
let len = totDistributionList.length + atomdist.length - 1;
let completeDistributionList = new Array(len).fill(0) ;
for(let i=0;i<totDistributionList.length;i++)
{
for(let j=0;j<atomdist.length;j++)
{
let intensity = 0;
let index = i+j ;
let mass = totDistributionList[i].mass+atomdist[j].mass ;
intensity = totDistributionList[i].intensity * atomdist[j].intensity ;
if(completeDistributionList[index] != 0) intensity = intensity + completeDistributionList[index].intensity ;
completeDistributionList[index] = {mass:mass,intensity:intensity};
if(intensity > maxintensity) maxintensity = intensity ;
}
}
let completeDistributionList_temp = [];
for(let i = 0; i<completeDistributionList.length; i++)
{
let tempintensityVal = (completeDistributionList[i].intensity/maxintensity)*100;
if( tempintensityVal > this.minintensity)
{
completeDistributionList[i].intensity = Math.round(tempintensityVal * 1000000) / 1000000;//tempintensityVal//Math.round(tempintensityVal * 1000000) / 1000000; //parseFloat(((tempDistributionList[i].intensity/maxintensity)*100).toFixed(6)) ;
completeDistributionList_temp.push(completeDistributionList[i]);
}
}
completeDistributionList = completeDistributionList_temp ;
return completeDistributionList ;
}
}
/**
* Code to get the molecular formular based on the mass.
* Number of atoms of each atom in the averagine * number of
* atoms of each atom calculated from mass gives the total number of atoms.
*/
getMolecularFormula(){
let atomListwithCnt = new Array(5) ;
let len = this.atomList.length;
let mass = 0;
for(let i=0;i<len;i++)
{
let count ;
if(this.atomList[i] == "C"){
count = parseInt(this.eachAtomCount * this.carbonCnt) ;
mass = mass + count*getIsotopicMassOfAtom(this.atomList[i])[0].mass;
}
else if(this.atomList[i] == "H"){
count = parseInt(this.eachAtomCount * this.hydrogenCnt) ;
mass = mass + count*getIsotopicMassOfAtom(this.atomList[i])[0].mass;
}
else if(this.atomList[i] == "N"){
count = parseInt(this.eachAtomCount * this.nitrogenCnt) ;
mass = mass + count*getIsotopicMassOfAtom(this.atomList[i])[0].mass;
}
else if(this.atomList[i] == "O"){
count = parseInt(this.eachAtomCount * this.oxygenCnt) ;
mass = mass + count*getIsotopicMassOfAtom(this.atomList[i])[0].mass;
}
else if(this.atomList[i] == "S"){
count = parseInt(this.eachAtomCount * this.sulphurCnt) ;
mass = mass + count*getIsotopicMassOfAtom(this.atomList[i])[0].mass;
}
atomListwithCnt[i] = {atom:this.atomList[i],count:count};
}
return [atomListwithCnt,mass] ;
}
/**
* Code to calculate MZ(mass/charge) and remove low intensity values
* @param {Array} totDistributionList - Array with total distribution
* @param {Float} charge - Float from mass list
* @param {Float} massError - Calculated massError needed to be added
* as we taken int values of number of atoms eleminating mass from the float values.
* @param {Array} peakDataList - Array of peak list from user
*/
getMZwithHighInte(totDistributionList,charge,massError,modifiedPeakList)
{
let len = totDistributionList.length;
let newtotDistributionList = [];
let overaAllMaxIntensity = 0 ;
let onePerctInte = 0;
let peakListLen = modifiedPeakList.length;
for(let k=0;k<peakListLen ; k++)
{
if(modifiedPeakList[k].getIntensity() > overaAllMaxIntensity) overaAllMaxIntensity = modifiedPeakList[k].getIntensity() ;
}
onePerctInte = overaAllMaxIntensity/100 ;
for(let i=0;i<len;i++)
{
let intensity = totDistributionList[i].intensity ;
intensity = overaAllMaxIntensity * intensity/100 ;
if(intensity > onePerctInte)
{
let mz = (totDistributionList[i].mass+massError)/charge + this.protonMass;
let intensity = totDistributionList[i].intensity ;
//Converting mass variable to mz(mass/charge)
let tempdistObj = {mz:mz,intensity:intensity};
newtotDistributionList.push(tempdistObj);
}
}
return newtotDistributionList ;
}
//modification of getNormalizedIntensity to add envelope y pos adjustment
getNormalizedIntensityAndAdjustedEnvelopes(totDistributionList,modifiedPeakList)
{
let len = totDistributionList.length;
let peakListLen = modifiedPeakList.length;
let count = 0 ;
let maxinte = 0;
let mininte = 100;
let peakMaxinte = 0;
let peakMininte = 10000000;
let maxMz = 0;
let minMz = 10000000;
let matchedPeakList = [];
for(let i=0;i<len;i++)//iterating through actual peaks in this envelope
{
let maxMzDifference = 0;
for(let j=0;j<peakListLen;j++)//iterating through theo peaks in the data
{
let mzDifference = Math.abs(totDistributionList[i].mz - modifiedPeakList[j].getPos());
if(mzDifference <= this.toleraceMassDiff)
{
if(maxMz < totDistributionList[i].mz){
maxMz = totDistributionList[i].mz;
}
if(minMz > totDistributionList[i].mz){
minMz = totDistributionList[i].mz;
}
matchedPeakList.push([i,j]); //i is env index, j is peak index
/*if (mzDifference > maxMzDifference){
matchedPeakList.push([i,j]); //i is env index, j is peak index
maxMzDifference = mzDifference;
}*/
count = count + 1;
}
}
}
maxMz = maxMz + this.toleraceMassDiff;
minMz = minMz - this.toleraceMassDiff;
for(let i=0;i<len;i++)
{
if(minMz <= totDistributionList[i].mz && totDistributionList[i].mz <= maxMz)
{
if(maxinte < totDistributionList[i].intensity){
maxinte = totDistributionList[i].intensity;
}
if(mininte > totDistributionList[i].intensity){
mininte = totDistributionList[i].intensity;
}
}
}
/*previous function skews the result if there are > 1 peaks in the mz range and later one has high intensity
make sure the max min value changed when it is the peak that is closest to the given env
for now, will check if the peak has any envelopes within error tolerance
*/
for(let j=0;j<peakListLen;j++)
{
if(modifiedPeakList[j].getPos() >= minMz && modifiedPeakList[j].getPos() <= maxMz)
{
if(peakMaxinte < modifiedPeakList[j].getIntensity()){
//for all env dots, check if this peak really belongs to this envelope
for (let env = 0; env < totDistributionList.length; env++){
if (Math.abs(totDistributionList[env].mz - modifiedPeakList[j].getPos()) <= this.toleraceMassDiff){
peakMaxinte = modifiedPeakList[j].getIntensity();
}
}
}
if(peakMininte > modifiedPeakList[j].getIntensity()){
for (let env = 0; env < totDistributionList.length; env++){
if (Math.abs(totDistributionList[env].mz - modifiedPeakList[j].getPos()) <= this.toleraceMassDiff){
peakMininte = modifiedPeakList[j].getIntensity();
}
}
}
}
}
/*when calculating new y pos, when a later envelope has higher y pos, evaluate again after reducing peak inte
based on that higher envelope, not in the previous left-to-right order.
keep marking peak as shared peak as moving from left to right, and when an envelope meets a shared peak,
check if the previous envelope with which it shares the peak had higher intensity at that peak.
In order to compare, save the original intensity value in each envelope property for envelopes with shared
peak. Then compare, and rewrite the previous y pos if needed. */
if(count !=0 )
{
let avg ;
let distributionAvgInte;
avg = (peakMaxinte + peakMininte)/2;
distributionAvgInte = (maxinte+mininte)/2;
for (let i = 0; i < totDistributionList.length; i++){
if (avg == 0){
avg = 1;
}
totDistributionList[i].intensity = (avg * totDistributionList[i].intensity)/distributionAvgInte ;
if (totDistributionList[i].intensity < 0 || distributionAvgInte <= 0) {
totDistributionList[i].intensity = 0;
};
for (let j = 0; j < matchedPeakList.length; j++){
if (matchedPeakList[j][0] == i) {
let p = matchedPeakList[j][1];
//store original peak intensity value only when it is evaluted for the first time
//not going to run when called from peakData because it is already evaluated there
/*if (Object.keys(modifiedPeakList[p]).indexOf("isPeakShared") < 0){
modifiedPeakList[p]["origIntensity"] = modifiedPeakList[p].intensity;
}*/
let newInte = modifiedPeakList[p].getIntensity() - totDistributionList[i].intensity;
modifiedPeakList[p].setIntensity(newInte)
if (modifiedPeakList[p].getIntensity() < 0){
modifiedPeakList[p].setIntensity(0);
}
modifiedPeakList[p]["isPeakShared"] = true;
}
}
}
}
//remove envelopes without matching peaks
this.removeEnvelopes(totDistributionList, matchedPeakList);
}
/**
* Code to normalize the Intensity.
* Take the average of intensity from the peaks entered by the user.
* Take the average of the calculated distribution for each Array element in the Array.
* Make both of them equal and calculating the rest of the
* distribution intensity based on the avg value from the peak list.
* @param {Array} totDistributionList - Total distribution calculated
* @param {Array} peakDataList - Peak Data entered by the user
*
* below is original function by Sreekanth
*/
getNormalizedIntensity(totDistributionList,peakDataList)
{
let len = totDistributionList.length;
let peakListLen = peakDataList.length;
let intensity = 0;
let count = 0 ;
let distributionInte = 0;
let maxinte = 0;
let mininte = 100;
let peakMaxinte = 0;
let peakMininte = 10000000;
let maxMz = 0;
let minMz = 10000000;
for(let i=0;i<len;i++)
{
for(let j=0;j<peakListLen;j++)
{
if((totDistributionList[i].mz - peakDataList[j].mz) <= this.toleraceMassDiff
&& (totDistributionList[i].mz - peakDataList[j].mz) >= 0-this.toleraceMassDiff )
{
if(maxMz < totDistributionList[i].mz){
maxMz = totDistributionList[i].mz;
}
if(minMz > totDistributionList[i].mz){
minMz = totDistributionList[i].mz;
}
count = count + 1;
}
}
}
maxMz = maxMz + this.toleraceMassDiff;
minMz = minMz - this.toleraceMassDiff;
for(let i=0;i<len;i++)
{
if(minMz <= totDistributionList[i].mz && totDistributionList[i].mz <= maxMz)
{
if(maxinte < totDistributionList[i].intensity){
maxinte = totDistributionList[i].intensity;
}
if(mininte > totDistributionList[i].intensity){
mininte = totDistributionList[i].intensity;
}
}
}
for(let j=0;j<peakListLen;j++)
{
if(peakDataList[j].mz >= minMz && peakDataList[j].mz <= maxMz)
{
if(peakMaxinte < peakDataList[j].intensity){
peakMaxinte = peakDataList[j].intensity;
}
if(peakMininte > peakDataList[j].intensity){
peakMininte = peakDataList[j].intensity;
}
}
}
if(count !=0 )
{
let avg ;
let distributionAvgInte;
avg = (peakMaxinte + peakMininte)/2;
distributionAvgInte = (maxinte+mininte)/2;
for(let i=0;i<len;i++)
{
totDistributionList[i].intensity = (avg * totDistributionList[i].intensity)/distributionAvgInte ;
}
}
return totDistributionList ;
}
removeEnvelopes(envList, matchedPeakList){
let threshold = 0.95;
let totalInte = 0;
let remainInte = 0;
let keepRemove = true;
let idx = envList.length - 1;
/*keep removing dots with no matching peaks while
(remainig peaks intensity/all peaks intensity) >= threshold
remove from the right, but stop when prev dot is not removed -- no remove in the middle only*/
for (let i = 0; i < envList.length; i++){
totalInte = totalInte + envList[i].intensity;
}
remainInte = totalInte;
/*removing from the right*/
/*
while (idx >= 0 && keepRemove){
//keep removing peaks at idx if it is not in the matchedpeaklist
let noPeakMatch = true;//if true, means there are no env matching peaks
for (let p = matchedPeakList.length - 1; p >= 0; p--){
if (matchedPeakList[p][0] == idx){
noPeakMatch = false;
break;
}
}
if (noPeakMatch){
remainInte = remainInte - envList[idx].intensity;
if (remainInte / totalInte >= threshold){
envList.splice(idx, 1);
}
else{
keepRemove = false;
}
}
else{
//when current env is not going to be removed. Then remove process should stop there.
keepRemove = false;
}
idx--;
}*/
let start = 0;
let end = envList.length - 1;
let removeEndEnv = true;
let removeStartEnv = true;
let endEnvInte = Number.MAX_VALUE;
let startEnvInte = Number.MAX_VALUE; ;
/*removing dots from both side: start evaluating from start and end index.
while end >= start, and keepRemove is true (at least one of the dots could be removed)
keep removing the envelopes from the both sides in turn, removing whichever that has lower inte.
first, iterate matchedPeakList to see if end index is there. If exists, no more removal from end.
If not exists, remove the env, end = end - 1. The matchedPeakList entry can also be removed.
Same with start index.
The while loop exists when no removal from both end or no more env left to evaluate.
*/
while (end >= start && (removeEndEnv || removeStartEnv)){
//keep removing peaks at idx if it is not in the matchedpeaklist
for (let p = matchedPeakList.length - 1; p >= 0; p--){
if (matchedPeakList[p][0] == end){//no removal
removeEndEnv = false;
}
else if (matchedPeakList[p][0] == start){//no removal
removeStartEnv = false;
}
}
if (removeEndEnv){
remainInte = remainInte - envList[end].intensity;
if (remainInte / totalInte >= threshold){
endEnvInte = envList[end].intensity;
}
else{
removeEndEnv = false;
}
}
if (removeStartEnv){
remainInte = remainInte - envList[start].intensity;
if (remainInte / totalInte >= threshold){
startEnvInte = envList[start].intensity;
}
else{
removeStartEnv = false;
}
}
//decide which one has lower intensity --and to be removed
if (endEnvInte < startEnvInte && removeEndEnv){
envList.splice(end, 1);
end--;
}
else if (startEnvInte <= endEnvInte && removeStartEnv){
envList.splice(start, 1);
end--;
}
}
return envList;
}
} |
import React from 'react'
import {
configure,
shallow
} from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import App from '../../App'
configure({
adapter: new Adapter()
})
describe('Probando component <App />', () => {
test('Renderizado de componente App', () => {
const wrapper = shallow(<App />)
expect(wrapper.find('h1').html('<h1>Jest and Enzyme</h1>'))
expect(wrapper.find('h1')).toHaveLength(1)
// console.log(wrapper.find('[type="checkbox"]').html())
// console.log(wrapper.find('div ~ p').length)
// console.log(wrapper.find('h1').html())
})
test('', () => {
})
})
|
const { blob } = require("buffer-layout");
const { publicKey, u64, u8, u128, u32, bool, struct } = require("@project-serum/borsh");
const FARMS = {
RayUsdcVault: 0,
RaySolVault: 1,
RayUsdtVault: 2,
RaySrmVault: 3,
MerUsdcVault: 4,
MediaUsdcVault: 5,
CopeUsdcVault: 6,
RayEthVault: 7,
StepUsdcVault: 8,
RopeUsdcVault: 9,
AlephUsdcVault: 10,
TulipUsdcVault: 11,
SnyUsdcVault: 12,
BopRayVault: 13,
SlrsUsdcVault: 14,
SamoRayVault: 15,
Unknown: 255,
};
const VAULT_LAYOUT = struct([
blob(8),
publicKey("authority"),
publicKey("token_program"),
publicKey("pda_token_account"),
publicKey("pda"),
u8("nonce"),
u8("info_nonce"),
u8("reward_a_nonce"),
u8("reward_b_nonce"),
u8("swap_to_nonce"),
u64("total_vault_balance"),
publicKey("info_account"),
publicKey("lp_token_account"),
publicKey("lp_token_mint"),
publicKey("reward_a_account"),
publicKey("reward_b_account"),
publicKey("swap_to_account"),
u64("total_vlp_shares")
]);
const filters = [
{
dataSize: VAULT_LAYOUT.span
}
];
const USER_BALANCE_LAYOUT = struct([
blob(8),
publicKey("owner"),
u64("amount")
]);
const STAKE_INFO_LAYOUT_V4 = struct([
u64("state"),
u64("nonce"),
publicKey("poolLpTokenAccount"),
publicKey("poolRewardTokenAccount"),
u64("totalReward"),
u128("perShare"),
u64("perBlock"),
u8("option"),
publicKey("poolRewardTokenAccountB"),
blob(7),
u64("totalRewardB"),
u128("perShareB"),
u64("perBlockB"),
u64("lastBlock"),
publicKey("owner")
]);
const STAKE_INFO_LAYOUT = struct([
u64("state"),
u64("nonce"),
publicKey("poolLpTokenAccount"),
publicKey("poolRewardTokenAccount"),
publicKey("owner"),
publicKey("feeOwner"),
u64("feeY"),
u64("feeX"),
u64("totalReward"),
u128("rewardPerShareNet"),
u64("lastBlock"),
u64("rewardPerBlock")
]);
const ACCOUNT_LAYOUT = struct([
publicKey("mint"),
publicKey("owner"),
u64("amount"),
u32("delegateOption"),
publicKey("delegate"),
u8("state"),
u32("isNativeOption"),
u64("isNative"),
u64("delegatedAmount"),
u32("closeAuthorityOption"),
publicKey("closeAuthority")
]);
const MINT_LAYOUT = struct([
u32('mintAuthorityOption'),
publicKey('mintAuthority'),
u64('supply'),
u8('decimals'),
bool('initialized'),
u32('freezeAuthorityOption'),
publicKey('freezeAuthority')
]);
const AMM_INFO_LAYOUT_V4 = struct([
u64('status'),
u64('nonce'),
u64('orderNum'),
u64('depth'),
u64('coinDecimals'),
u64('pcDecimals'),
u64('state'),
u64('resetFlag'),
u64('minSize'),
u64('volMaxCutRatio'),
u64('amountWaveRatio'),
u64('coinLotSize'),
u64('pcLotSize'),
u64('minPriceMultiplier'),
u64('maxPriceMultiplier'),
u64('systemDecimalsValue'),
// Fees
u64('minSeparateNumerator'),
u64('minSeparateDenominator'),
u64('tradeFeeNumerator'),
u64('tradeFeeDenominator'),
u64('pnlNumerator'),
u64('pnlDenominator'),
u64('swapFeeNumerator'),
u64('swapFeeDenominator'),
// OutPutData
u64('needTakePnlCoin'),
u64('needTakePnlPc'),
u64('totalPnlPc'),
u64('totalPnlCoin'),
u128('poolTotalDepositPc'),
u128('poolTotalDepositCoin'),
u128('swapCoinInAmount'),
u128('swapPcOutAmount'),
u64('swapCoin2PcFee'),
u128('swapPcInAmount'),
u128('swapCoinOutAmount'),
u64('swapPc2CoinFee'),
publicKey('poolCoinTokenAccount'),
publicKey('poolPcTokenAccount'),
publicKey('coinMintAddress'),
publicKey('pcMintAddress'),
publicKey('lpMintAddress'),
publicKey('ammOpenOrders'),
publicKey('serumMarket'),
publicKey('serumProgramId'),
publicKey('ammTargetOrders'),
publicKey('poolWithdrawQueue'),
publicKey('poolTempLpTokenAccount'),
publicKey('ammOwner'),
publicKey('pnlOwner')
]);
const LENDING_OBLIGATION_LIQUIDITY = struct(
[
publicKey('borrowReserve'),
u128('cumulativeBorrowRateWads'), // decimal
u128('borrowedAmountWads'), // decimal
u128('marketValue'), // decimal
]
);
const LENDING_OBLIGATION_LAYOUT = struct([
u8("version"),
struct([u64("slot"), bool("stale")], "lastUpdateSlot"),
publicKey("lendingMarket"),
publicKey("owner"),
u128("borrowedValue"), // decimal
u64("vaultShares"), // decimal
u64("lpTokens"), // decimal
u64("coinDeposits"), // decimal
u64("pcDeposits"), // decimal
u128("depositsMarketValue"), // decimal
u8("lpDecimals"),
u8("coinDecimals"),
u8("pcDecimals"),
u8("depositsLen"),
u8("borrowsLen"),
struct(
[
publicKey("borrowReserve"),
u128("cumulativeBorrowRateWads"), // decimal
u128("borrowedAmountWads"), // decimal
u128("marketValue") // decimal
],
"obligationBorrowOne"
),
struct(
[
publicKey("borrowReserve"),
u128("cumulativeBorrowRateWads"), // decimal
u128("borrowedAmountWads"), // decimal
u128("marketValue") // decimal
],
"obligationBorrowTwo"
)
]);
const OBLIGATION_LAYOUT = struct([
publicKey('obligationAccount'),
u64('coinAmount'),
u64('pcAmount'),
u64('depositedLPTokens'),
u8('positionState'),
]);
const USER_FARM = struct([
blob(76),
struct(
[OBLIGATION_LAYOUT, OBLIGATION_LAYOUT, OBLIGATION_LAYOUT], "obligations"
)
]);
module.exports = {
filters,
FARMS,
VAULT_LAYOUT,
USER_BALANCE_LAYOUT,
STAKE_INFO_LAYOUT_V4,
STAKE_INFO_LAYOUT,
ACCOUNT_LAYOUT,
MINT_LAYOUT,
AMM_INFO_LAYOUT_V4,
AMM_INFO_LAYOUT_V3,
LENDING_OBLIGATION_LIQUIDITY,
LENDING_OBLIGATION_LAYOUT,
OBLIGATION_LAYOUT,
USER_FARM,
};
|
/**
* @author: Arie M. Prasetyo (2020)
*/
import Button from './Button';
import Donut from './Donut';
import LineChart from './LineChart';
export {
Button,
Donut,
LineChart
}; |
//1.理解原型对象
function Person(){
}
Person.prototype.name="xiaochuan";
Person.prototype.age=21;
Person.prototype.getName=function(){
console.log(this.name);
};
var person1=new Person();
console.log(person1.__proto__); //{name: "xiaochuan", age: 21, getName: ƒ, constructor: ƒ}
console.log(person1.__proto__==Person.prototype); //true
//实例属性会屏蔽原型中的属性
function Person(){
}
Person.prototype.name="xiaochuan";
Person.prototype.age=21;
Person.prototype.getName=function(){
console.log(this.name);
};
var person1=new Person();
var person2=new Person();
person1.name = "dachaun";
person1.getName(); //dachaun来自实例
person2.getName(); //xiaochuan来自原型
delete person1.name;
person1.getName(); //xiaochuan来自原型
//hasOwnProperty()方法检测属性位于实例还是原型
function Person(){
}
Person.prototype.name="xiaochuan";
Person.prototype.age=21;
Person.prototype.getName=function(){
console.log(this.name);
};
var person1=new Person();
var person2=new Person();
console.log(person1.hasOwnProperty("name")); //false来自原型
person1.name = "dachuan";
console.log(person1.hasOwnProperty("name")); //true来自实例 |
function connect() {
var socket = navigator.mozTCPSocket.open('147.87.46.10', 8000);
socket.onopen = function() {
socket.send('hello');
}
socket.ondata = function(event) {
socket.send(event.data);
}
}
|
function main(){
$("#image").on('change',function(){
readURL(this);
});
$('#reset').on('click', function(){
$('#img').attr('src','#').css('display','none');
$('#divCarousel').empty();
})
$('#carousel').on('change', function(){
$('#divCarousel').empty();
readURL(this);
})
}
function readURL(input) {
for(let i=0;i<input.files.length;i++){
if (input.files && input.files[i]) {
var reader = new FileReader();
reader.onload = function (e) {
if(input.id == 'image')
$('#img').attr('src', e.target.result).css('display','block').addClass('display');
else
$('#divCarousel').append($('<img>').attr({'src' : e.target.result, 'alt' : 'imagen'}).addClass(['image','mr-2']));
}
reader.readAsDataURL(input.files[i]);
}
}
}
window.addEventListener('load',main); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.