text
stringlengths 7
3.69M
|
|---|
import React from "react";
export default function MountaintCard(props) {
return (
<div
className="mountaint-"
style={{ width: "110%",
maxWidth: "1000px",
backgroundColor: "lightgrey",
borderRadius: "10px" }}
>
<h1 className="mountaint-head">{props.header}</h1>
<p className="mountaint-body">{props.body}</p>
<br />
<div>
<img
className="mountaint-img"
src={`img/${props.img}`}
alt=""
style={{ width: "100%", maxWidth: "700px", maxHeight: "500px" }}
/>
</div>
</div>
);
}
|
/*
* Reception Server
*
* This is the start up script for Reception Server, part of the kernel.
*/
require('./lib/baum.js');
require('./lib/_.js');
CONFIG = $.config.createConfig('./config/');
SESSION = {};
IPC = {};
outputError = function(e, code, message){
var output
= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
+ '<html><head>'
+ '<meta http-equiv="Content-Type" content="application/html; charset=utf-8" />'
+ '<title>' + CONFIG.get('site-name') + '</title>'
+ '<style type="text/css">body{background: #FFFFFF; text-align:center;}</style>'
+ '</head><body>'
+ '<h1>' + $.nodejs.http.STATUS_CODES[code] + '</h1>'
+ '<h3>Error Code ' + code + '</h3>'
+ ((undefined == message)?('Sorry, but the server have respond with an error. This is what we all know.'):(message))
+ '<br /><hr />'
+ '<font color="#FF0000">LOESUNG-PROJECT</font> Reception Server'
+ '</body></html>'
;
e.response.writeHead(code, {'Content-Type': 'text/html'});
e.response.write(output);
e.response.end();
};
var site = require('./site/entrance.js');
var port = CONFIG.get('http-port');
var socketPath = CONFIG.get('socket-path');
var HTTPServer = $.net.HTTP.server(port);
String('HTTP Server created at port: ' + port).NOTICE();
var IPCServer = $.net.IPC.server(socketPath);
String('IPC Server created at: ' + socketPath).NOTICE();
String('Read IPC map.').NOTICE();
var IPCMap = CONFIG.get('ipc-map');
for(var item in IPCMap){
String(
'Create IPC Client at [' + IPCMap[item] + '] for [' + item + '].'
).NOTICE();
IPC[item] = $.net.IPC.client(IPCMap[item]);
};
String('Initialize Botschaft-System communication.').NOTICE();
$.global.set('botschaft', _.botschaft(IPC['botschaft']));
$.global.get('botschaft').refreshTunnelInfo();
HTTPServer.on('data', site);
HTTPServer.start();
IPCServer.on('data', site);
IPCServer.start();
$.nodejs.memwatch.on('leak', function(e){
String('MEMWATCH detected potential memory leak:' + e).WARNING();
});
|
const sgMail = require('@sendgrid/mail');
const emailConfig = require('../config/emailConfig')();
exports.sendSendGridEmail = (recipients, message) => {
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const data = {
from: emailConfig.senderAddress,
to: recipients.to,
cc: recipients.cc,
bcc: recipients.bcc,
subject: message.subject,
text: message.text
};
// data object must be in the format example below
data.to && data.to.split(',');
data.cc && data.cc.split(',');
data.bcc && data.bcc.split(',');
return sgMail.send(data);
};
// let exampleSendGridMsg = {
// to: ['recipient@example.org', 'recipient2@example.org'],
// cc: ['someone@example.org', 'someone2@example.org'],
// bcc: ['me@example.org', 'you@example.org'],
// from: 'sender@example.org',
// subject: 'Hello world',
// text: 'Hello plain world!'
// };
|
/*
* @lc app=leetcode id=51 lang=javascript
*
* [51] N-Queens
*
* https://leetcode.com/problems/n-queens/description/
*
* algorithms
* Hard (43.70%)
* Likes: 1550
* Dislikes: 65
* Total Accepted: 185.6K
* Total Submissions: 418K
* Testcase Example: '4'
*
* The n-queens puzzle is the problem of placing n queens on an n×n chessboard
* such that no two queens attack each other.
*
*
*
* Given an integer n, return all distinct solutions to the n-queens puzzle.
*
* Each solution contains a distinct board configuration of the n-queens'
* placement, where 'Q' and '.' both indicate a queen and an empty space
* respectively.
*
* Example:
*
*
* Input: 4
* Output: [
* [".Q..", // Solution 1
* "...Q",
* "Q...",
* "..Q."],
*
* ["..Q.", // Solution 2
* "Q...",
* "...Q",
* ".Q.."]
* ]
* Explanation: There exist two distinct solutions to the 4-queens puzzle as
* shown above.
*
*
*/
// @lc code=start
/**
* @param {number} n
* @return {string[][]}
*/
var solveNQueens = function(n) {
const result = [];
const nRow = new Array(n).fill('.');
const puzzle = nRow.map(() => [...nRow]);
function isSafe(y, x) {
for (let i = 0; i < n; i++) {
if (i !== x && puzzle[y][i] === 'Q' || i !== y && puzzle[i][x] === 'Q') {
return false;
}
}
const step = [[1, 1], [1, -1], [-1, 1], [-1, -1]];
for (const [yStep, xStep] of step) {
let j = y + yStep;
let i = x + xStep;
while(j >= 0 && j < n && x >= 0 && x < n) {
if (puzzle[j][i] === 'Q') {
return false;
}
j += yStep;
i += xStep;
}
}
return true;
}
function backtrack(y = 0) {
if (y >= n) {
result.push([...puzzle.map(i => i.join(''))]);
return;
}
for (let x = 0; x < n; x++) {
if (isSafe(y, x)) {
puzzle[y][x] = 'Q';
backtrack(y + 1);
puzzle[y][x] = '.';
}
}
}
backtrack();
return result;
};
// @lc code=end
solveNQueens(4);
|
import { types } from './filters.actions'
const INITIAL_STATE = {
sports: [],
dates: [],
price: 'Infinity',
}
export default function filtersReducer(state = INITIAL_STATE, action = { type: '' }) {
switch (action.type) {
case types.SET_SPORT_FILTER:
return {
...state,
sports: action.payload,
}
case types.SET_DATE_FILTER:
return {
...state,
dates: action.payload,
}
case types.SET_PRICE_FILTER:
return {
...state,
price: action.payload,
}
default:
return state
}
}
|
function transformMap(mapObj, rand) {
var maxX = 0;
var maxY = 0;
for (var i = 0; i < mapObj.diagram.cells.length; i++) {
if(mapObj.diagram.cells[i].site.x > maxX) maxX = mapObj.diagram.cells[i].site.x;
if(mapObj.diagram.cells[i].site.y > maxY) maxY = mapObj.diagram.cells[i].site.y;
}
var grid = mapObj.diagram.cells;
// var grid = new Array(maxX + 1);
// for (i = 0; i < grid.length; i++) {
// grid[i] = new Array(maxY + 1);
// }
// for (i = 0; i < mapObj.diagram.cells.length; i++) {
// grid[mapObj.diagram.cells[i].site.x][mapObj.diagram.cells[i].site.y] = mapObj.diagram.cells[i];
// }
// var prev = null;
// for(i = 0; grid.length; i++) {
// for (var j = 0; j < grid[i].length; j++) {
// if(grid[i][j]) {
// prev = grid[i][j];
// break;
// }
// }
// if(prev) break;
// }
var totalGold = 0;
for (i = 0; i < grid.length; i++) {
grid[i].blocked = (!!grid[i].water || !!grid[i].ocean || !!grid[i].river);
grid[i].conquerability = grid[i].blocked ? 0 : grid[i].elevation + grid[i].trees - grid[i].trees;
grid[i].wildlife = grid[i].fauna;
switch(grid[i].biome) {
case 'VOLCANO':
case 'VOLCANO_OUTLINE':
case 'DEEP_WATER':
case 'OCEAN':
case 'MARSH':
case 'ICE':
case 'LAKE':
case 'TUNDRA':
case 'BARE':
case 'SCORCHED':
case 'SUBTROPICAL_DESERT':
grid[i].fertility = 0;
break;
case 'FISHING':
break;
case 'BEACH':
grid[i].fertility = rand(0, 10);
break;
case 'TAIGA':
grid[i].fertility = rand(20, 50);
break;
case 'SHRUBLAND':
grid[i].fertility = rand(0, 20);
break;
case 'TEMPERATE_DESERT':
grid[i].fertility = rand(0, 5);
break;
case 'TEMPERATE_RAIN_FOREST':
grid[i].fertility = rand(40, 80);
break;
case 'TEMPERATE_DECIDUOUS_FOREST':
grid[i].fertility = rand(50, 70);
break;
case 'GRASSLAND':
grid[i].fertility = rand(70, 90);
break;
case 'TROPICAL_RAIN_FOREST':
grid[i].fertility = rand(70, 100);
break;
case 'TROPICAL_SEASONAL_FOREST':
grid[i].fertility = rand(70, 90);
break;
}
totalGold += grid[i].minerals.gold;
}
// for (var x = 0; x < grid.length; x++) {
// for (var y = 0; y < grid[x].length; y++) {
// if(!grid[x][y]) grid[x][y] = clone(prev);
// prev = grid[x][y];
// grid[x][y].x = x;
// grid[x][y].y = y;
// grid[x][y].blocked = (grid[x][y].water || grid[x][y].ocean || grid[x][y].river);
// grid[x][y].conquerability = grid[x][y].blocked ? 0 : grid[x][y].elevation + grid[x][y].trees - grid[x][y].trees;
// switch(grid[x][y].biome) {
// case 'VOLCANO':
// case 'VOLCANO_OUTLINE':
// case 'FISHING':
// case 'DEEP_WATER':
// case 'OCEAN':
// case 'MARSH':
// case 'ICE':
// case 'LAKE':
// case 'SNOW':
// case 'TUNDRA':
// case 'BARE':
// case 'SCORCHED':
// case 'SUBTROPICAL_DESERT':
// grid[x][y].fertility = 0;
// break;
// case 'BEACH':
// grid[x][y].fertility = rand(0, 10)/100;
// break;
// case 'TAIGA':
// grid[x][y].fertility = rand(20, 50)/100;
// break;
// case 'SHRUBLAND':
// grid[x][y].fertility = rand(0, 20)/100;
// break;
// case 'TEMPERATE_DESERT':
// grid[x][y].fertility = rand(0, 5)/100;
// break;
// case 'TEMPERATE_RAIN_FOREST':
// grid[x][y].fertility = rand(40, 80)/100;
// break;
// case 'TEMPERATE_DECIDUOUS_FOREST':
// grid[x][y].fertility = rand(50, 70)/100;
// break;
// case 'GRASSLAND':
// grid[x][y].fertility = rand(70, 90)/10;
// break;
// case 'TROPICAL_RAIN_FOREST':
// grid[x][y].fertility = rand(70, 100)/100;
// break;
// case 'TROPICAL_SEASONAL_FOREST':
// grid[x][y].fertility = rand(70, 90)/100;
// break;
// }
// totalGold += grid[x][y].minerals.gold;
// }
// }
return {
grid: grid,
totalGold: totalGold
};
}
|
import * as types from './mutation-types'
import { $message } from '@/element'
export default {
// 获取系统公告
async getFindBulletinPage({ state, commit }, terms = {}) {
const res = await this.$ajax.post(this.$apis.getAllSystemMsgList, {
msgType: 3,
page: 1,
size: 5,
...terms,
})
if (res.ok) {
commit({
type: types.SET_FINDBULLETIN_PAGE,
newMessageList: res.data.list,
newMessageTotal: res.data.total,
})
}
},
// 获取校内公告
async getAllSystemMsgList({ commit }, terms = {}) {
const res = await this.$ajax.post(this.$apis.getAllSystemMsgList, {
msgType: 1,
page: 1,
size: 5,
...terms,
})
commit({
type: types.SET_ALL_SYSTEM_MSG_LIST,
allSystemMsgList: res.data.list,
allSystemMsgTotal: res.data.total,
})
},
// 获取课程公告
async getAllCourseMsgList({ commit }, terms = {}) {
const res = await this.$ajax.post(this.$apis.getAllCourseMsgList, {
page: 1,
size: 5,
...terms,
})
commit({
type: types.SET_ALL_COURSE_MSG_LIST,
allCourseMsgList: res.data.list,
allCourseMsgTotal: res.data.total,
})
},
// 学习中心课程公告
async getCourseMsgList({ commit }, courseObj) {
const res = await this.$ajax.post(this.$apis.getCourseMsgList, {
courseIdSign: courseObj.courseIdSign,
page: courseObj.page,
size: courseObj.size,
})
if (res.ok) {
commit({
type: types.SET_COURSE_MSG_LIST_GONG_GAO,
courseMsgList: res.data.list,
courseMsgTotal: res.data.total,
})
}
},
// 添加课程公告
async getAddMessageInfo({}, addMessageInfoReqObj) {
const res = await this.$ajax.post(this.$apis.getAddMessageInfo, {
content: addMessageInfoReqObj.content,
courseId: addMessageInfoReqObj.courseId,
title: addMessageInfoReqObj.title,
})
if (res.ok) {
$message.success('发布成功')
} else {
$message.error('发布失败')
}
},
// 获取首页轮播图
async getAllAdvertisingList({ commit }) {
const res = await this.$ajax.get(this.$apis.getAllAdvertisingList)
if (res.ok) {
commit({
type: types.GET_ALL_ADVER_TI_SING_LIST,
allAdvertisingList: res.data,
})
}
},
// 教师中心学员管理列表
async getFindStudentList({ commit }, searchReqObj) {
const res = await this.$ajax.post(this.$apis.getFindStudentList, {
courseId: searchReqObj.courseId,
page: searchReqObj.page,
size: searchReqObj.size,
})
if (res.ok) {
commit({
type: types.GET_FIND_STUDENT_NUMBERLIST,
findStudentList: res.data.list,
findStudentTotal: res.data.total,
})
}
},
// 教师中心退课
async getDeleteTeacher({}, studentList) {
const res = await this.$ajax.post(this.$apis.getDeleteTeacher, {
studentList: studentList,
})
if (res.ok) {
$message.success('删除成功')
} else {
$message.error(res.msg)
}
},
}
|
alert('Hello,Kotoha');
|
import React from 'react'
import {Row, Col} from 'react-bootstrap'
import { connect } from 'react-redux'
import Header from '../components/Header/customHeader'
import './index.scss'
function RefTC(props) {
console.log(props)
return (
<>
<Header title={'Affiliate – Terms & Conditions'} backButton backTo={() => props.history.push('/refer-friend')} />
<Row className='my-2'>
<Col className='col-10 offset-1'>
<p>This is a contract between {props.signinData && props.signinData.user && props.signinData.user.UserAttributes.find(el => el.Name === 'name').Value} (the “Affiliate”) and us (“Pvot” or “Effifront Technologies Private Ltd.”).
It describes how we will work together and other aspects of our business relationship.</p>
<h6>Commission </h6>
<ul>
<li>As defined by the program details </li>
</ul>
<h6>Non-Exclusivity</h6>
<p>This Agreement does not create an exclusive agreement between you and us.
Both you and we will have the right to recommend similar products and services of third parties and to
work with other parties in connection with the design, sale, installation, implementation and use of similar
services and products of third parties.</p>
<h6>Customer Transactions</h6>
<ul>
<li>Acceptance and Validity. An Affiliate Lead will be considered valid and accepted if,
in our reasonable determination: (i) it is a new potential customer of ours, and (ii) is not,
at the time of submission or forty five (45) days prior, one of our pre-existing customers, or
involved in our active sales process. Notwithstanding the foregoing, we may choose not to accept
an Affiliate Lead in our reasonable discretion. If an Affiliate Lead does not purchase the Subscription
Service within the time period, you will not be eligible for a Commission payment, even if the Affiliate
Lead decides to purchase after the time period has expired. An Affiliate Lead is not considered valid if
it’s first click on the Affiliate Link is after this Agreement has expired or terminated.</li>
<li>Engagement with Prospects. Once we have received the Affiliate Lead information, we may elect
to engage with the prospect directly, regardless of whether or not the Affiliate Lead is valid.
If an Affiliate Lead is not valid then we may choose to maintain it in our database and we may
choose to engage with such Affiliate Lead. Any engagement between Pvot and an Affiliate Lead will be at
Pvot’s discretion.</li>
<li>Commission and Payment. Requirements for Payment; Forfeiture. In order to receive payment under this
Agreement, you must have:
(i) agreed to the terms of this Agreement (generally completed through the Affiliate Tool);
(ii) completed all steps necessary to create your account in the Affiliate Tool in accordance with
our directions,
(iii) have a valid and up-to-date Bank account (iv)
completed any and all required tax documentation in order for Pvot to process any payments
that may be owed to you.</li>
<li>Commission Payment. We, or a Pvot Affiliate, will pay the Commission amount due to you within
thirty (30) days after the end of each month for any Commission amounts that you become eligible f
or according to the Eligibility section above. We will determine the currency in which we pay the
Commission, as well as the applicable conversion rate. We will not pay more than one Commission payment
or other similar referral fee on any given Customer Transaction (unless we choose to in our discretion). </li>
<li>Taxes. You are responsible for payment of all taxes applicable to the Commission. All amounts payable
by us to you are subject to offset by us against any amounts owed by you to us.</li>
</ul>
<h6>Training and Support</h6>
<ul>
<li>Affiliate Training and Support. We may make available to you, without charge, various webinars and
other resources made available as part of our Affiliate Program. If we make such resources available to you,
you will encourage your sales representatives and/or other relevant personnel to participate in training
and/or other certifications as we recommend and may make available to you from time-to-time. We may change
or discontinue any or all parts of the Affiliate Program benefits or offerings at any time without notice.</li>
</ul>
<h6>Trademarks</h6>
<p>You grant to us a nonexclusive, nontransferable, royalty-free right to use and display your trademarks, service marks
and logos (“Affiliate Marks”) in connection with the Affiliate Program and this Agreement.</p>
<p>During the term of this Agreement, in the event that we make our trademark available to you within the Affiliate Tool,
you may use our trademark as long as you follow the usage requirements in this section. You must:
<br/>(i) only use the images of our trademark that we make available to you, without altering them in any way;
<br/>(ii) only use our trademarks in connection with the Affiliate Program and this Agreement; and
<br/>(iii) immediately comply if we request that you discontinue use.
<br/>You must not:
<br/>(i) use our trademark in a misleading or disparaging way;
<br/>(ii) use our trademark in a way that implies we endorse, sponsor or approve of your services or products; or
<br/>(iii) use our trademark in violation of applicable law or in connection with an obscene, indecent, or unlawful topic or material.</p>
<h6>Proprietary Rights</h6>
<ul>
<li>Pvot’s Proprietary Rights. No license to any software is granted by this Agreement. The Pvot Products
are protected by intellectual property laws. The Pvot Products belong to and are the property of us or our licensors
(if any). We retain all ownership rights in the Pvot Products. You agree not to copy, rent, lease, sell, distribute, or
create derivative works based on the Pvot Content, or the Pvot Products in whole or in part, by any means, except as
expressly authorized in writing by us.</li>
<li>We encourage all customers, affiliates and partners to comment on the Pvot Products, provide suggestions for
improving them, and vote on suggestions they like. You agree that all such comments and suggestions will be non-confidential
and that we own all rights to use and incorporate them into the Pvot Products, without payment to you.</li>
<li>Customer’s Proprietary Rights. As between you and Customer, Customer retains the right to access and use the
Customer portal associated with the Pvot Products. For the avoidance of doubt, Customer will own and retain all
rights to the Customer Data.</li>
</ul>
<h6>Confidentiality</h6>
<p>
As used herein, “Confidential Information” means all confidential information disclosed by a party ("Disclosing Party")
to the other party (“Receiving Party”),
<br/>(i) whether orally or in writing, that is designated as confidential, and
<br/>(ii) Pvot customer and prospect information, whether or not otherwise designated as confidential.
<br/>Confidential Information does not include any information that
<br/>(i) is or becomes generally known to the public without breach of any obligation
owed to the Disclosing Party or
<br/>(ii) was known to the Receiving Party prior to its disclosure by the Disclosing Party
without breach of any obligation owed to the Disclosing Party.
<br/>The Receiving Party shall:
<br/>(i) protect the confidentiality
of the Confidential Information of the Disclosing Party using the same degree of care that it uses with its own confidential
information, but in no event less than reasonable care,
<br/>(ii) not use any Confidential Information of the Disclosing Party
for any purpose outside the scope of this Agreement,
<br/>(iii) not disclose Confidential Information of the Disclosing Party
to any third party, and
<br/>(iv) limit access to Confidential Information of the Disclosing Party to its employees,
contractors and agents. The Receiving Party may disclose Confidential Information of the Disclosing Party if required
to do so under any federal, state, or local law, statute, rule or regulation, subpoena or legal process.</p>
<h6>Opt Out and Unsubscribing</h6>
<p>You will comply promptly with all opt out, unsubscribe, "do not call" and "do not send" requests. For the duration of this
Agreement, you will establish and maintain systems and procedures appropriate to effectuate all opt out, unsubscribe, "do not
call" and "do not send" requests.</p>
<h6>Term and Termination</h6>
<ul>
<li>Term. This Agreement will apply for as long as you participate in the Affiliate Program, until terminated.</li>
<li>No cause Termination. Both you and we may terminate this Agreement on seven (7) days written notice to the other party.</li>
</ul>
<p>Upon termination or expiration, you will immediately discontinue all use of our trademark and references to
this Affiliate Program from your website(s) and other collateral. For the avoidance of doubt, termination or expiration
of this Agreement shall not cause a Customer’s subscription agreement to be terminated.</p>
<h6>Affiliate Representations and Warranties</h6>
<p>You represent and warrant that: (i) you have all sufficient rights and permissions to participate in the Affiliate
Program and to provision Pvot with Affiliate Lead’s for our use in sales and marketing efforts or as otherwise set forth
in this Agreement, (ii) your participation in this Affiliate Program will not conflict with any of your existing agreements
or arrangements; and (iii) you own or have sufficient rights to use and to grant to us our right to use the Affiliate Marks.</p>
<h6>Non-Solicitation</h6>
<p>You agree not to intentionally solicit for employment any of our employees or contractors during the term of this Agreement
and for a period of twelve (12) months following the termination or expiration of this Agreement.</p>
<h6>General</h6>
<ul>
<li>Applicable Law. This Agreement shall be governed by the laws of Republic of India, without regard to the conflict of
laws provisions thereof. In the event either of us initiates an action in connection with this Agreement or any other
dispute between the parties, the exclusive venue and jurisdiction of such action shall be in the state courts in Bengaluru, India.</li>
<li>Force Majeure. Neither party will be responsible for failure or delay of performance if caused by: an act of war, hostility,
or sabotage; act of God; electrical, internet, or telecommunication outage that is not caused by the obligated party; government
restrictions; or other event outside the reasonable control of the obligated party. Each party will use reasonable efforts to
mitigate the effect of a force majeure event.</li>
<li>Relationship of the Parties. Both you and we agree that no joint venture, partnership, employment, or agency relationship
exists between you and us as a result of this Agreement.</li>
<li>Entire Agreement. This Agreement is the entire agreement between us for the Affiliate Program and supersedes all other
proposals and agreements, whether electronic, oral or written, between us.</li>
<li>Assignment. You will not assign or transfer this Agreement, including any assignment or transfer by reason of merger,
reorganisation, sale of all or substantially all of its assets, change of control or operation of law, without our prior
written consent. We may assign this Agreement to any affiliate or in the event of merger, reorganization, sale of all or
substantially all of our assets, change of control or operation of law.</li>
<li>No Third Party Beneficiaries. Nothing in this Agreement, express or implied, is intended to or shall confer upon any
person or entity (other than the parties hereto) any right, benefit or remedy of any nature whatsoever under or by
reason of this Agreement.</li>
<li>No Licenses. We grant to you only the rights and licenses expressly stated in this Agreement, and you receive no
other rights or licenses with respect to us, the Pvot Products, our trademarks, or any other property or right of ours.</li>
<li>Sales by Pvot. This Agreement shall in no way limit our right to sell the Pvot Products, directly or indirectly,
to any current or prospective customers.</li>
<li>Authority. Each party represents and warrants to the other that it has full power and authority to enter into this
Agreement and that it is binding upon such party and enforceable in accordance with its terms.</li>
</ul>
</Col>
</Row>
</>
)
}
const mapStateToProps = state => ({
signinData: state.auth.signinData
})
export default connect(mapStateToProps)(RefTC)
|
if( isFileInURL( "portfolio" ) )
{
displayPortfolio();
}
function displayPortfolio()
{
if( sessionStorage.getItem( "current_sort" ) === null )
{
sessionStorage.setItem( "current_sort", "lang=fa-sort-asc" );
}
getProjects();
}
function getProjects() //display the projects and the current sorting buttons on protfolio.php
{
var getPair = sessionStorage.getItem( "current_sort" ).split( "=" );
//to use a variable-variable pair relationship to be sent in AJAX, you must use key value pairs, based on second answer http://stackoverflow.com/questions/11687217/variable-data-in-ajax-call-jquery
var currentSort = {};
currentSort[ getPair[ 0 ] ] = getPair[ 1 ];
$.ajax({
url: "./server_functionality/portfolio-functions.php",
type: "GET",
data: currentSort,
dataType: "json",
success: function( outputData )
{
$( "#main-container" ).html( outputData[ 0 ] + outputData[ 1 ] );
$( "#sort-buttons li a" ).each( function() //add the custom click listeners to sort the buttons without reloading the page
{
$( this ).click( function( link )
{
link.preventDefault(); //removes the # from the url, probably could be done by taking it out of the href for the buttons in protfolio-functions.php
sessionStorage.setItem( "current_sort", $( this ).attr( "id" ) );
displayPortfolio();
});
});
}
});
}
|
import { NavLink } from 'react-router-dom';
import routes from '../../routes';
import styles from './LoginBar.module.scss';
const LoginBar = () => {
return (
<div>
<NavLink
to={routes.register}
exact
className={styles.link}
activeClassName={styles.activeLink}
>
Sign up
</NavLink>
<NavLink
to={routes.login}
exact
className={styles.link}
activeClassName={styles.activeLink}
>
Sign In
</NavLink>
</div>
);
};
export default LoginBar;
|
import React from 'react';
import { connect } from 'react-redux';
import { withRouter, Redirect } from 'react-router-dom';
import { setSelectedReason } from '../actions'
import Employee from './Employee';
const mapStateToProps = state => {
return {
selectedEmployee: state.selectedEmployee,
reasons: state.reasons
}
}
const mapDispatchToProps = dispatch => {
return {
setSelectedReason: reason => {
dispatch( setSelectedReason(reason));
}
}
}
class Reason extends React.Component {
handleClick = (reason) => {
this.props.setSelectedReason(reason);
if (reason.need_visitor) {
this.props.history.push('/reception/visitor');
}
else {
this.props.history.push('/reception/result');
}
}
render() {
if (!this.props.selectedEmployee) {
return (
<Redirect to="/" />
)
}
return (
<div className="container">
<div className="row">
<div className="col-sm-4">
<Employee employee={this.props.selectedEmployee} />
</div>
</div>
<h3 className="my-3" >What brings you here?</h3>
<div className="row">
<div className="col-sm-4">
{
this.props.reasons.map(
(reason, i) => (
<ReasonItem reason={reason}
key={i}
onClick={() => { this.handleClick(reason)}} />
)
)
}
</div>
</div>
</div>
)
}
}
const ReasonItem = (props) => {
return (
<div className="card card-body mb-3 div-shadow" onClick={props.onClick}>
<h4 className="m-0" ><strong>{props.reason.message}</strong></h4>
</div>
)
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Reason));
|
import Snackbar from "./snackBar";
import Navbar from "./navbar";
import Footer from "./footer";
export { Snackbar, Navbar, Footer };
|
import React from 'react';
import '../../styles/style.scss';
/*
d is a string containing a series of path commands that define
the outline shape of the glyph it is unique for every svg image/icon.
*/
export const Button = ({cls, children, border, fn, icon, clsIcon, iconStroke, d}) => (
<div className="interactive_focus" style={{border: border}}>
<div className={cls} onClick={() => fn()}>
<svg
className={clsIcon}
style={{
display: {icon}
}}
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg">
<path
d={d}
stroke={iconStroke}
stroke-linecap="round"
stroke-linejoin="round"/>
</svg>
{children}
</div>
</div>
)
|
.html()
.text()
.replaceWith()
.remove()
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const command_1 = require("@oclif/command");
const toolbelt_api_test_1 = require("@thiagoveras/toolbelt-api-test");
class HelloB extends command_1.Command {
async run() {
this.parse(HelloB);
this.log(`Hello from Plugin B at ${toolbelt_api_test_1.Display.time()}`);
}
}
exports.default = HelloB;
HelloB.description = 'Single Command from Plugin B';
HelloB.examples = [
`$ clitest helloB`
];
HelloB.flags = {
help: command_1.flags.help({ char: 'h' }),
};
HelloB.args = [{ name: 'file' }];
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PartController = void 0;
const BaseController_1 = require("./interfaces/base/BaseController");
const PartsSchema_1 = require("../app/persistance/schemas/PartsSchema");
const PartService_1 = require("../app/services/PartService");
class PartController extends BaseController_1.BaseController {
constructor() {
super(PartsSchema_1.Part);
this.PartService = new PartService_1.PartsService();
}
}
exports.PartController = PartController;
|
//Server info
var hostname = 'webrtctest2.zapto.org';
var port = 80;
var socket = io(hostname + ':' + port);
var audio = document.querySelector('audio');
var id = document.getElementById('id');
/*socket.on('s', function(s) {
audio.src = window.URL.createObjectURL(s);
});*/
socket.on('id', function(id) {
id.value = id;
});
|
const s = "aabbaccc";
const solution = (s) => {
var answer = s.length;
for (let i = 1; i <= s.length; i++) {
//압축할 단어
let newString = "";
let count = 1;
for (let j = 0; j < s.length; j += i) {
let word = s.substring(j, j + i);
let nextWord = s.substring(j + i, j + i * 2);
if (word === nextWord) {
count++;
} else {
if (count === 1) {
newString = newString + word;
} else {
newString = newString + `${count}${word}`;
}
count = 1;
}
}
console.log(newString);
if (newString.length < answer) {
answer = newString.length;
}
}
return answer;
};
console.log(solution(s));
|
'use strict';
import React, {Component} from 'react';
import {
FlatList,
AppRegistry,
StyleSheet,
Text,
View,
Image,
Alert,
TouchableOpacity,
NativeModules,
Dimensions,
SectionList,
} from 'react-native';
export default class Zhibo_Match extends React.PureComponent{
static navigationOptions = ({navigation}) => ({
title: '标题',
headerTitleStyle: {fontSize: 18, color: 'red'},
headerStyle: {height: 40},
});
// 构造
constructor(props) {
super(props);
// 初始状态
this.state = {matchdata:null,loaded:false};
}
componentWillMount(){
this.mounted = true;
}
componentDidMount() {
this.getData();
}
componentWillUnmount() {
this.mounted = false;
}
onTabPress(item, mid){
NativeModules.WebviewRNModule.show("http://120.78.150.194:8080/video/getnbaurl.biz?url="+item.sourceValue+"&"+"mid="+mid+"&"+"sourceName="+item.sourceName+"&"+"liveSource="+item.liveSource);
//NativeModules.WebviewRNModule.show("http://192.168.100.104:8080/video/getnbaurl.biz?url="+item.sourceValue+"&"+"mid="+mid+"&"+"sourceName="+item.sourceName);
//NativeModules.WebviewRNModule.show("http://m.didiaokan.com");
//NativeModules.WebviewRNModule.show("http://192.168.100.104:8080/biz/test.html");
//NativeModules.WebviewRNModule.show("http://baishi.baidu.com/watch/04437156001742011395.html");
}
/** 渲染视图数据*/
renderLoadingView(){
return (
<View >
<Text>
正在加载...
</Text>
</View>
);
}
render(){
if (!this.state.loaded) {
return this.renderLoadingView();
}
let arr = [];
const matchData = this.state.matchdata.data;
//console.log(this.state.matchdata.data.matchSourceList[0].liveSource);
for(let i in this.state.matchdata.data.matchSourceList){
let customComponent = (
<View key={i}>
<TouchableOpacity onPress={this.onTabPress.bind(this, matchData.matchSourceList[i],matchData.mid)}
>
<Text>{matchData.matchSourceList[i].sourceName}</Text>
</TouchableOpacity>
</View>
);
arr.push(customComponent);
//console.log(this.state.matchdata.data.matchSourceList[i].liveSource);
}
return(
<View>
<View>{arr}</View>
</View>
);
}
//请求数据
getData(){
const navi = this.props.navigation;
const {state} = navi;
var list = [];
//const matchStatUrl = "http://120.78.150.194:8080/gamedata/matchStat.biz?mid="+state.params.item.mid+"&tabType=2&homeTeamName="+state.params.item.home_team+"&guestTeamName="+state.params.item.guest_team;
const matchStatUrl = "http://120.78.150.194:8080/gamedata/matchStat.biz?mid="+state.params.item.mid+"&tabType=2&homeTeamName="+state.params.item.home_team+"&guestTeamName="+state.params.item.guest_team;
fetch(matchStatUrl)
//var responses = fetch('http://192.168.100.104:8080/video/gamenbalist.biz')
.then((response) => response.json())
//获得返回的json
.then((responseJson)=>{
if(this.mounted){
//alert(JSON.stringify(responseJson));
this.setState({
loaded:true,
matchdata:responseJson
});
}
//console.log(JSON.stringify(data));
})
.catch((error) => {
//console.error(error);
});
}
}
|
function isLoadImg(el) {
let ele = typeof el === "object" ? el : document.querySelector(el)
let bound = ele.getBoundingClientRect()
let clientHight = window.innerHeight
let clientWidth = window.innerWidth
return !(
bound.top > clientHight ||
bound.bottom < 0 ||
bound.left > clientWidth ||
bound.right < 0
)
}
function checkAllLazyLoadImg() {
let imgs = document.querySelectorAll("img")
Array.from(imgs).forEach(el => {
if (isLoadImg(el)) {
loadImg(el)
}
})
}
// add src to img element
function loadImg(el) {
let ele = typeof el === "object" ? el : document.querySelectorAll(el)
if (ele.dataset.lazy === 'lazy') {
ele.src = ele.getAttribute("data-src")
}
}
export default checkAllLazyLoadImg
|
var map = L.map('map',{ zoomControl:true }).setView([4.344426, -74.358292],14);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>,<a href="http://cloudmade.com">CloudMade</a>',
}).addTo(map);
// Marcar la posicion
var drawnItems = new L.FeatureGroup()
map.addLayer(drawnItems);
function a(){
map.featureGroup.removeLayer(e.layer);
}
L.drawLocal = {
draw: {
toolbar: {
actions: {
title: '',
text: 'Cancelar'
},
finish: {
title: '',
text: 'Finalizar'
},
undo: {
title: '',
text: 'Limpiar el último punto'
},
buttons: {
circle: 'Dibuja un Circulo',
}
},
handlers: {
circle: {
tooltip: {
start: 'Haz clic y arrastra para dibujar'
},
radius: 'Radio'
},
circlemarker: {
tooltip: {
start: 'Click map to place circle marker.'
}
},
marker: {
tooltip: {
start: 'Click map to place marker.'
}
},
polygon: {
tooltip: {
start: 'Click to start drawing shape.',
cont: 'Click to continue drawing shape.',
end: 'Click first point to close this shape.'
}
},
polyline: {},
rectangle: {
tooltip: {
start: 'Click and drag to draw rectangle'
}
},
simpleshape: {
tooltip: {
end: 'Suelte el mouse para terminar de dibujar'
}
}
}
},
edit: {
toolbar: {
actions: {
save: {
title: '',
text: ' OK '
},
cancel: {
title: '',
text: 'Cancelar'
},
clearAll: {
title: '',
text: 'Borrar todo'
}
},
buttons: {
edit: 'Editar circulo',
editDisabled: 'Actualmente no se ha dibujado un circulo',
remove: 'Borrar circulo',
removeDisabled: 'Actualmente no se ha dibujado un circulo'
}
},
handlers: {
edit: {
tooltip: {
text: 'Cuando termine, haga clic en OK',
subtext: 'Cambiar el tamaño o mover'
}
},
remove: {
tooltip: {
text: 'Haga clic para eliminar'
}
}
}
}
};
var drawControl = new L.Control.Draw({
//definir botones
draw:{polygon: false,
rectangle: false,
polyline:false,
marker:false,
circlemarker:false,
circle : {
metric: 'metric'
}
},
//permitir que se editen el circulo
edit: {
featureGroup: drawnItems,
}
},);
map.addControl(drawControl);
|
import Joi from 'joi';
const expenseItemFields = {
type: Joi.string().max(250).required(),
date: Joi.date().iso().required(),
description: Joi.string().max(250).required(),
net: Joi.number().positive().precision(2).required(),
vat: Joi.number().positive().precision(2).default(0),
};
const expenseFields = {
date: Joi.date().iso(),
number: Joi.number().positive().integer(),
name: Joi.string().max(250),
status: Joi.string().valid('draft', 'final'),
items: Joi.array().items(Joi.object().keys(expenseItemFields)).min(1),
};
const validator = Joi.object().keys(expenseFields);
const requiredValidator = validator.requiredKeys(Object.keys(expenseFields));
export const postExpense = requiredValidator;
export const putExpense = requiredValidator;
export const patchExpense = validator;
|
DB.record.allow(
{'insert' :
function(userID, doc) {
var result = false
, room
;
doc.time = Date.now();
doc._id = (doc.time + '');
doc.user = userID;
if (userID === TRPG.adm || doc.room === TRPG.public.id) {
result = true;
}
else {
room = DB.room.findOne({'_id' : doc.room});
if (room && (room.adm.indexOf(userID) !== -1 || room.player.indexOf(userID) !== -1)) {
result = true;
}
}
//確定修改後
if (result) {
//若修改之文件有section,同步修改其時間
if (doc.section) {
DB.record.update(doc.section, {'$set' : {'time' : doc.time } });
}
//若修改之文件有chapter,同步修改其時間
if (doc.chapter) {
DB.record.update(doc.chapter, {'$set' : {'time' : doc.time } });
}
//若修改之文件有room,同步修改其時間
if (doc.room) {
DB.room.update(doc.room, {'$set' : {'time' : doc.time } });
}
return true;
}
return false;
}
,'update' :
function(userID, doc) {
var result = false
, now = Date.now()
, content= doc.conent
, room
;
//若修改者為最近一次的修改者則通過
if (userID == doc.user) {
result = true;
}
else {
doc.user = userID;
//若修改者為總adm則通過
if (userID === TRPG.adm) {
result = true;
}
else {
//若修改者為room adm則通過
room = DB.room.findOne({'_id' : doc.room});
if (room && room.adm.indexOf(userID) !== -1) {
result = true;
}
}
}
//確定修改後
if (result) {
//更新最後更新時間
DB.record.update({'_id' : doc._id}, {'$set' : {'time' : now } });
//若修改之文件有section,同步修改其時間
if (doc.section) {
DB.record.update({'_id' : doc.section}, {'$set' : {'time' : now } });
}
//若修改之文件有chapter,同步修改其時間
if (doc.chapter) {
DB.record.update({'_id' : doc.chapter}, {'$set' : {'time' : now } });
}
//若修改之文件有room,同步修改其時間
if (doc.room) {
DB.room.update({'_id' : doc.room}, {'$set' : {'time' : now } });
}
return true;
}
return false;
}
,'remove' :
function(userID, doc) {
var result = false
, now = Date.now()
;
if (userID === TRPG.adm || userID == doc.user) {
result = true;
}
var room = DB.room.findOne({'_id' : doc.room});
if (room && room.adm.indexOf(userID) !== -1) {
result = true;
}
//確定修改後
if (result) {
//更新最後更新時間
DB.record.update({'_id' : doc._id}, {'$set' : {'time' : now } });
//若修改之文件有section,同步修改其時間
if (doc.section) {
DB.record.update({'_id' : doc.section}, {'$set' : {'time' : now } });
}
//若修改之文件無section有chapter(為section)
else if (doc.chapter) {
//刪除所對應之地圖
DB.map.remove({'section' : doc._id});
}
//若修改之文件有chapter,同步修改其時間
if (doc.chapter) {
DB.record.update({'_id' : doc.chapter}, {'$set' : {'time' : now } });
}
//若修改之文件有room,同步修改其時間
if (doc.room) {
DB.room.update({'_id' : doc.room}, {'$set' : {'time' : now } });
}
return true;
}
return false;
}
}
);
Meteor.publish('chapter', function (room, chapter, sectionID) {
var secionFilter =
{'$or' :
//訂閱所有一週內更新的section
[ {'room' : room
,'chapter' : chapter
,'section' : {'$exists' : false}
,'time' : {'$gte' : (Date.now() - 604800000)}
}
//指定的section
, {'_id' : sectionID}
]
}
, section = DB.record.find(secionFilter)
, sectionIds = _.pluck(section.fetch(), '_id')
;
//條件中新增已訂閱的section下的所有段落
secionFilter.$or.push(
{'room' : room
,'chapter' : chapter
,'section' : {'$in' : sectionIds}
}
);
//移除第一條件,改為訂閱所有section
secionFilter.$or.shift();
secionFilter.$or.push(
{'room' : room
,'chapter' : chapter
,'section' : {'$exists' : false}
}
);
return [
DB.record.find(secionFilter)
//已訂閱章節下的所有擲骰跟場外訊息
, DB.message_all.find({'chapter' : chapter, 'type' : {'$in' : ['outside', 'dice']}})
];
});
Meteor.publish('section', function (section) {;
return [
DB.record.find(section)
//, DB.message_all.find({'section' : section})
];
});
/*
Meteor.methods(
{'paragraphIncrement' :
function(room, chapter, section, from, inc) {
DB.record.update({'room' : room
,'chapter' : chapter
,'section' : section
,'sort' : { '$gte' : from }
}
,{'$inc' :
{'sort' : inc
}
}
,{'multi' : true}
);
return true;
}
}
)
function strip_tags (input, allowed) {
// http://kevin.vanzonneveld.net
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Luke Godfrey
// + input by: Pul
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Onno Marsman
// + input by: Alex
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + input by: Marc Palau
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + input by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Eric Nagel
// + input by: Bobby Drake
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Tomasz Wesolowski
// + input by: Evertjan Garretsen
// + revised by: Rafał Kukawski (http://blog.kukawski.pl/)
// * example 1: strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>');
// * returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
// * example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
// * returns 2: '<p>Kevin van Zonneveld</p>'
// * example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
// * returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
// * example 4: strip_tags('1 < 5 5 > 1');
// * returns 4: '1 < 5 5 > 1'
// * example 5: strip_tags('1 <br/> 1');
// * returns 5: '1 1'
// * example 6: strip_tags('1 <br/> 1', '<br>');
// * returns 6: '1 1'
// * example 7: strip_tags('1 <br/> 1', '<br><br/>');
// * returns 7: '1 <br/> 1'
allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
});
}
*/
|
$(function() {
function showModal($id) {
if ($('#modal-' + $id + '').hasClass('modal-hide')) {
$('#modal-' + $id + '').removeClass('modal-hide');
}
$('#modal-' + $id + '').addClass('modal-display');
}
function hideModal($id) {
if ($('#modal-' + $id + '').hasClass('modal-display')) {
$('#modal-' + $id + '').removeClass('modal-display');
}
$('#modal-' + $id + '').addClass('modal-hide');
}
function delEntity($cId, $but, $url, $type) {
var token = $('#token').val();
$('#' + $but + '').prop('disabled', true);
$.ajax({
type: 'POST',
url: $url,
data: ({delete : $cId, token : token}),
dataType: "json",
success: function(message) {
hideModal($cId);
if ($type == 'comment') {
$('.msg-cont-aj').append('<div class="alert alert-info del-message">' + message + '</div>').delay(2000).queue( function(){
$('.del-message').fadeOut( 1000 ).queue(function() {
location.reload();
});
});
} else {
$('#row-' + $cId + '').remove();
$('.msg-cont-aj').append('<div class="alert alert-info del-message">' + message + '</div>').delay(4000).queue( function(){
$('.del-message').fadeOut( 2000 );
});
}
},
error : function(message){
hideModal($cId);
$('.msg-cont-aj').text();
$('.msg-cont-aj').append('<div class="alert alert-danger del-message">' + message['responseText'] + '</div>').delay(4000).queue( function(){
$('.del-message').fadeOut(2000).queue(function(){
$('#' + $but + '').prop('disabled', false);
});
});
}
});
}
$(document).ready(function(){
if ($('#title-admin').text() == 'Administration des articles postés') {
var $type = 'article';
}
if ($('#title-admin').text() == 'Administration des catégories') {
var $type = 'cat';
}
if ($('#title-admin').text() == 'Administration des commentaires') {
var $type = 'comment';
}
$('body').on('click', '.delete-cat', function(){
var $id = $(this).data('id'),
$butId = $(this).attr('id'),
$url = '/writer/web/ajax/delete-cat',
$type = 'cat';
delEntity($id, $butId, $url, $type);
});
$('body').on('click', '.delete-comment', function(){
var $id = $(this).data('id'),
$butId = $(this).attr('id'),
$url = '/writer/web/ajax/delete-comment',
$type = 'comment';
delEntity($id, $butId, $url, $type);
});
$('body').on('click', '.delete-article', function(){
var $id = $(this).data('id'),
$butId = $(this).attr('id'),
$url = '/writer/web/ajax/delete-article',
$type = 'article';
delEntity($id, $butId, $url, $type);
});
$('body').on('click', '.modal-delete-' + $type + '', function(){
var $id = $(this).data('id');
showModal($id);
});
$('body').on('click', '.cancel-delete', function(){
var $id = $(this).data('id');
hideModal($id);
});
});
});
|
const button = document.querySelector("button");
const header = document.querySelector("h1");
button.addEventListener("click", () => {
fetch("https://api.adviceslip.com/advice")
.then((monkey) => monkey.json())
.then((data) => {
header.innerHTML = data.slip.advice;
});
});
|
exports.up = async function(knex, Promise) {
await knex.schema.createTable("concerts", table => {
table
.increments('id')
.notNullable()
.primary;
table.string('title').notNullable();
table.string('band').notNullable();
table.string('venue').notNullable();
table.integer('price').notNullable();
table.datetime('performance_date').notNullable();
table.datetime('created_date').defaultTo(knex.fn.now());
});
};
exports.down = async function(knex, Promise) {
await knex.schema.dropTable("concerts");
};
|
import React, { Component } from "react";
import "./App.css";
const math = require("mathjs");
const buttons = [
{ key: "1", id: "one", type: "number" },
{ key: "2", id: "two", type: "number" },
{ key: "3", id: "three", type: "number" },
{ key: "4", id: "four", type: "number" },
{ key: "5", id: "five", type: "number" },
{ key: "6", id: "six", type: "number" },
{ key: "7", id: "seven", type: "number" },
{ key: "8", id: "eight", type: "number" },
{ key: "9", id: "nine", type: "number" },
{ key: "0", id: "zero", type: "number" },
{ key: ".", id: "decimal", type: "decimal" },
{ key: "+", id: "add", type: "operator" },
{ key: "-", id: "subtract", type: "operator" },
{ key: "*", id: "multiply", type: "operator" },
{ key: "/", id: "divide", type: "operator" },
{ key: "=", id: "equals", type: "equals" },
{ key: "C", id: "clear", type: "clear" }
];
class App extends Component {
constructor(props) {
super(props);
this.state = {
display: "0",
input: "",
result: ""
};
this.keyHandler = this.keyHandler.bind(this);
}
keyHandler(e) {
switch (e.type) {
case "clear":
this.clearHandler();
break;
case "operator":
if (this.isValidOperator(e.key)) {
if (!(this.state.result === "") && this.state.input === "") {
console.log("Setting prev result: " + +" to input and operating");
this.setState({ input: this.state.result }, () => this.appendKey(e.key));
} else {
this.appendKey(e.key);
}
}
break;
case "number":
if (this.isValidNumber(e.key)) {
this.appendKey(e.key);
}
break;
case "decimal":
if (this.isValidDecimal()) {
this.appendKey(e.key);
}
break;
case "equals":
this.validate();
}
}
validate(input = this.state.input) {
console.log("validating input: " + input);
let lastKey = input[input.length - 1];
if ("+-/*.".includes(lastKey)) {
console.log("found " + lastKey + " is operator");
let newInput = input.slice(0, input.length - 1);
console.log("removed " + lastKey + " to produce input: " + newInput);
this.validate(newInput);
} else {
console.log("input valid, setting state: " + input);
this.setState({ input: input }, this.resultHandler);
}
}
appendKey(key) {
console.log("appending:" + key);
let newInput = this.state.input.concat(key);
console.log("newInput: " + newInput);
this.setState({
input: newInput,
display: newInput
});
}
clearHandler() {
console.log("Clearing state");
this.setState({ display: "0", input: "", result: "" });
}
resultHandler() {
let input = this.state.input;
console.log("evaluating expression: " + input);
if (input.length) {
let evalInput = math.eval(input).toString();
console.log("expression evaluated: " + evalInput);
console.log(this.state);
this.setState({ display: evalInput, input: "", result: evalInput }, () => console.log(this.state));
}
}
isValidOperator(key) {
let { input, result } = this.state;
let lastKey = input[input.length - 1];
// if hit none && !result is empty, return false
// if hit operator, set state delete last operator, return true as callback
// if hit dec, return false
// if hit num, return true
if (input === "" && result === "") {
return false;
} else if ("+-/*".includes(lastKey)) {
let newInput = input.slice(0, input.length - 1);
return this.setState({ input: newInput }, () => {
// TODO, remove append call and return bool
this.appendKey(key);
});
} else if (lastKey === ".") {
return false;
} else {
return true;
}
}
isValidNumber(key) {
// if zero, isValidZero()
// else true
if (key === "0") {
return this.isValidZero();
} else {
return true;
}
}
isValidZero(count = 0) {
// recursively check back from end of string.
// else true
let input = this.state.input;
let prevKey = input[input.length - (1 + count)];
console.log("Prev: " + prevKey);
if ("123456789".includes(prevKey)) {
return true;
} else if (prevKey === "0") {
return this.isValidZero(count + 1);
} else if (!(prevKey === 0) && !count) {
return true;
} else {
return false;
}
}
isValidDecimal(count = 0) {
// recursively check back from end of string.
// if hit dec, return false
// else return true
let input = this.state.input;
let prevKey = input[input.length - (1 + count)];
if (prevKey === ".") {
return false;
} else if ("123456789".includes(prevKey)) {
return this.isValidDecimal(count + 1);
} else {
return true;
}
}
render() {
return (
<div className="App bg-secondary h-100 container-fluid d-flex justify-content-center align-items-center">
<div id="calculator" className="p-3 bg-dark card rounded d-flex justify-content-center align-items-center w-50">
<h1 className="card-title text-light">Javascript Calculator</h1>
<Display value={this.state.display} />
<ButtonPad keyHandler={this.keyHandler} />
</div>
</div>
);
}
}
const ButtonPad = props => {
let myButtons = buttons.map(x => (
<button id={x.id} onClick={() => props.keyHandler(x)} className="btn btn-secondary grid-item">
{x.key}
</button>
));
return (
<div id="button-pad" className="grid-container">
{myButtons}
</div>
);
};
const Display = props => {
return (
<div
className="w-100 card m-2 bg-light d-flex justify-content-center align-items-center"
style={{ height: "2.5rem" }}
>
<p className="text-primary m-0 text-center">
<strong id="display">{props.value}</strong>
</p>
</div>
);
};
export default App;
|
// SOURCE: https://binarysearch.io/room/Fords-of-Bellman-20465
// CATEGORY: EASY
/*
Given a 2-dimensional list matrix, return the number of even numbers in the matrix.
*/
// My first pass solution
function solve0(matrix) {
// Write your code here
// Track the count
let count = 0;
// Loop through outer array
for(let i=0; i<matrix.length; i++) {
// Loop through inner array
for(let j=0; j<matrix[i].length; j++){
// Increment count if inner el is even
if(matrix[i][j] % 2 === 0) {
count ++
}
}
}
// console.log(count)
return count
}
// COMPLETED, PASSES!
/*
Success!
Your submission took 6 milliseconds.
Your submission was faster than 61.24% of other javascript submissions for this question.
*/
const twodarr = [[1, 2, 8],[3, 5, 5],[4, 6, 6]]
solve(twodarr)
|
const ACCESS_TOKEN = 'Access-Token'
const TokenCache = {
getToken() {
return sessionStorage.getItem(ACCESS_TOKEN)
},
setToken(token) {
sessionStorage.setItem(ACCESS_TOKEN, token)
},
delToken() {
sessionStorage.removeItem(ACCESS_TOKEN)
}
}
export default TokenCache
|
import React, {Component, PropTypes} from 'react';
import classNames from 'classnames';
import UIGridConstants from './UIGridConstants.jsx';
const OFFSET_CLASSES = {
0: '',
1: 'col-sm-offset-1',
2: 'col-sm-offset-2',
3: 'col-sm-offset-3',
4: 'col-sm-offset-4',
5: 'col-sm-offset-5',
6: 'col-sm-offset-6',
7: 'col-sm-offset-7',
8: 'col-sm-offset-8',
9: 'col-sm-offset-9',
10: 'col-sm-offset-10',
11: 'col-sm-offset-11',
12: 'col-sm-offset-12'
};
const SIZE_CLASSES = {
1: 'col-sm-1',
2: 'col-sm-2',
3: 'col-sm-3',
4: 'col-sm-4',
5: 'col-sm-5',
6: 'col-sm-6',
7: 'col-sm-7',
8: 'col-sm-8',
9: 'col-sm-9',
10: 'col-sm-10',
11: 'col-sm-11',
12: 'col-sm-12'
};
const ALIGN_CLASSES = {
LEFT: 'text-left',
RIGHT: 'text-right'
};
class UIGridItem extends Component {
getClassName() {
const {size, offset, align, className} = this.props;
return classNames(SIZE_CLASSES[size], OFFSET_CLASSES[offset], ALIGN_CLASSES[align], className);
}
render() {
return (
<div {...this.props} className={this.getClassName()}>
{this.props.children}
</div>
);
}
}
UIGridItem.defaultProps = {
className: ''
};
UIGridItem.propTypes = {
offset: PropTypes.oneOf(UIGridConstants.OFFSET_RANGE),
size: PropTypes.oneOf(UIGridConstants.SIZE_RANGE).isRequired,
className: PropTypes.string,
children: PropTypes.node,
align: PropTypes.string
};
export default UIGridItem;
|
import {
PROJECTS_GET_SINGLE,
PROJECT_ADD_SUCCESS,
PROJECT_ADD_REQUEST,
PROJECTS_SUCCESS,
PROJECTS_REQUEST,
PROJECT_DELETE_REQUEST,
PROJECT_DELETE_SUCCESS,
PROJECT_DELETE_FAILURE,
TERMINAL_ADD_SUCCESS,
TERMINAL_REMOVE,
} from '../constants/actionTypes'
import { auth, db } from '../firebase/firebase'
import { snapshotToArray } from '../utils'
/*************************************************
*
* Get project(s)
*/
export const projectsGetAllRequest = () => ({
type: PROJECTS_REQUEST,
})
export const projectsGetSuccess = projects => ({
type: PROJECTS_SUCCESS,
payload: projects,
})
export const getSingleProject = id => ({
type: PROJECTS_GET_SINGLE,
payload: {
id,
},
})
/**
* Retrieve all projects
*/
export const getAllProjects = () => dispatch => {
dispatch(projectsGetAllRequest())
let uid = auth.currentUser !== null && auth.currentUser.uid
const ref = db.ref(`/projects/${uid}`)
ref.once('value', snapshot => {
let data = snapshot.val()
if (!data) {
return dispatch(projectsGetSuccess([]))
}
let formattedData = snapshotToArray(snapshot)
return dispatch(projectsGetSuccess(formattedData))
})
}
/*************************************************
*
* Create project
*/
export const createProjectRequest = () => ({
type: PROJECT_ADD_REQUEST,
})
export const createProjectSuccess = project => ({
type: PROJECT_ADD_SUCCESS,
payload: project
})
/**
* Create new project
* @param data
*/
export const createProject = data => dispatch => {
dispatch(createProjectRequest())
let uid = auth.currentUser !== null && auth.currentUser.uid
let project = { uid, ...data, terms: [], createAt: Date.now() }
db.ref(`/projects/${uid}`)
.push({ ...project })
.then(async snapshot => {
project.key = await snapshot.key;
return dispatch(createProjectSuccess(project))
})
.catch(err => {
console.log('error', err)
})
}
/*************************************************
*
* Delete project
*/
export const deleteProjectRequest = () => ({
type: PROJECT_DELETE_REQUEST,
})
export const deleteProjectSuccess = id => ({
type: PROJECT_DELETE_SUCCESS,
payload: {
id,
},
})
export const deleteProjectFailure = err => ({
type: PROJECT_DELETE_FAILURE,
payload: {
err,
},
})
export const deleteProject = id => dispatch => {
dispatch(deleteProjectRequest())
const uid = auth.currentUser !== null && auth.currentUser.uid
return new Promise((resolve, reject) => {
db.ref(`/projects/${uid}`)
.child(id)
.remove()
.then(() => {
setTimeout(() => {
dispatch(deleteProjectSuccess(id))
resolve()
}, 500)
})
.catch(err => {
dispatch(deleteProjectFailure(err))
reject(err)
})
})
}
|
import react from 'react';
import axios from 'axios';
const baseURL= 'http://api.openweathermap.org/data/2.5/forecast?';
const apiKey='3434a41e4751b5969309b9363a302a9b';
export const getWeatherData= async (cityName)=>{
try{
const {data}= await axios.get(baseURL + `q=${cityName}&appid=${apiKey}`);
//const {data}= await axios.get(baseURL + 'q=London&appid=a70472aab8b16f40783f2271ba271199');
console.log("i forecast5days" );
console.log(data)
return data;
}catch(error){
console.log(error.message);
throw error;
}
}
export default getWeatherData;
|
function createTriangle(n){
var output;
for (i=0; i<n; i++){
console.log(output += "*");
}
}
|
/*
Use forEach to print all the names in an array
Let's repeat the previous exercise using the forEach function.
*/
var names = ["Ben", "Ben2", "Ben3", "Priya", "rian"];
names.forEach(function (name){
console.log(name);
});
|
import { addGraphStory } from '../../utils/graphStory-utils.js'
import graphFactory from './graphFactory.js'
addGraphStory({namespace: 'colorFns', graphFactory, module})
|
exports.seed = function(knex) {
return knex("jobsheets").insert([
{
project_id: 1,
user_email: 'bob_johnson@lambdaschool.com',
name: 'HPU_Manifolds Jobsheet 1.csv',
},
]);
};
|
module.exports = require("npm:webcomponents.js@0.7.21/webcomponents");
|
/* eslint-disable react/prop-types */
import React from 'react';
import DropStyle from '../styles/drop';
import Controls from '../styles/controls';
import InputContainer from '../styles/inputContainer';
import Select from '../styles/select';
export default function Loan(props) {
//
function handleChange(e) {
const trouble = e.target.value.split(',');
props.onChange(trouble);
}
return (
<Controls>
<InputContainer>
<div>Loan Type</div>
</InputContainer>
<DropStyle>
<Select id="test" onChange={handleChange}>
<option value={[240, 2.88, 20]}> 30-year fixed </option>
<option value={[180, 2.93, 20]}> 20-year fixed </option>
<option value={[120, 2.55, 20]}> 15-year fixed </option>
<option value={[120, 2.64, 20]}> 10-year fixed </option>
<option value={[360, 2.25, 3.5]}> FHA 30-year fixed </option>
<option value={[180, 2.25, 3.5]}> FHA 15-year fixed </option>
<option value={[360, 2.41, 0]}> VA 30-year fixed </option>
<option value={[180, 2.42, 0]}> VA 15-year fixed </option>
</Select>
</DropStyle>
</Controls>
);
}
|
const Web3 = require('web3') // Web3 0.20.4 or web3 1 beta
const truffleContract = require("truffle-contract")
const contractArtifact = require('./build/contracts/TutorialToken.json')
const providerUrl = 'http://localhost:8545'
const provider = new Web3.providers.HttpProvider(providerUrl)
const contract = truffleContract(contractArtifact)
contract.setProvider(provider)
// dirty hack for web3@1.0.0 support for localhost testrpc, see https://github.com/trufflesuite/truffle-contract/issues/56#issuecomment-331084530
if (typeof contract.currentProvider.sendAsync !== "function") {
contract.currentProvider.sendAsync = function() {
return contract.currentProvider.send.apply(
contract.currentProvider,
arguments
);
};
}
contract.deployed()
.then(contractInstance => {
const event = contractInstance.Transfer(null, {fromBlock: 0}, (err, res) => {
if(err) {
throw Error(err)
}
})
event.watch(function(error, result){
if (error) { return console.log(error) }
if (!error) {
// DO ALL YOUR WORK HERE!
let { args: { from, to, value }, blockNumber } = result
console.log(`----BlockNumber (${blockNumber})----`)
console.log(`from = ${from}`)
console.log(`to = ${to}`)
console.log(`value = ${value}`)
console.log(`----BlockNumber (${blockNumber})----`)
}
})
})
.catch(e => {
console.error('Catastrophic Error!')
console.error(e)
})
|
var a = {'name':"Treant", age:27};
var b = a;
b.name="Panda";
b.age = 28;
console.log('-------a-------');
console.log(a);
console.log('---------b-------');
console.log(b);
var _ = require('underscore');
var c = {'name' : "ddg", isGood : true};
var d = _.clone(c);
d.name = "mntabc";
d.isGood = false;
console.log('##########c#####');
console.log(c);
console.log('$$$$$$$$d$$$$$$');
console.log(d);
|
import React from "react";
import Header from "./components/Header/Header";
import RecipeList from "./components/RecipeList/RecipeList";
// import Navigation from "./components/Navbar/NavBar";
import Navigation from "./components/Navigation/Navigation";
function FoodClone() {
return (
<div className="container-fluid m-0 p-0">
<Navigation />
<Header />
<RecipeList />
</div>
);
}
export default FoodClone;
|
export const format = (_date, arg = 0) => {
const year = _date.getFullYear();
const month =
_date.getMonth() <= 9 ? `0${_date.getMonth() + 1}` : _date.getMonth() + 1;
const date = _date.getDate() <= 9 ? `0${_date.getDate()}` : _date.getDate();
const hour =
_date.getHours() <= 9 ? `0${_date.getHours()}` : _date.getHours();
const minute =
_date.getMinutes() <= 9 ? `0${_date.getMinutes()}` : _date.getMinutes();
const second =
_date.getSeconds() <= 9 ? `0${_date.getSeconds()}` : _date.getSeconds();
const timezone =
_date.getTimezoneOffset() / -60 >= 0 ?
`+${_date.getTimezoneOffset() / -60}` :
`-${_date.getTimezoneOffset() / -60}`;
switch (arg) {
case 1:
return `${year}-${month}-${date} ${hour}:${minute}:${second} (UTC${timezone})`;
default:
return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
}
};
export const hhmmss = sec => {
const hour =
Math.floor(sec / 3600) <= 9 ?
`0${Math.floor(sec / 3600)}` :
Math.floor(sec / 3600);
const minute =
Math.floor(sec / 60) % 60 <= 9 ?
`0${Math.floor(sec / 60) % 60}` :
Math.floor(sec / 60) % 60;
const second = sec % 60 <= 9 ? `0${sec % 60}` : sec % 60;
return `${hour}:${minute}:${second}`;
};
export default format;
|
jQuery.fn.MSNAV = function(options) {
var y = 0;
// MSNAV default settings:
var defaults = {
nav: "",
currentClass: "",
elements: [],
parallex: [],
positions: [],
scrollSpeed: 500
},
// the extended options
settings = $.extend({}, defaults, options),
// the plugin methods
METHODS = {
/**
* @Method : getElementsPositions
* @Description : set array contain all elements positions
*/
'getElementsPositions': function() {
$(settings.elements).each(function(i, ele) {
// getthe elements positions
settings.positions.push($(ele).position().top);
// call append method
if (i === settings.elements.length - 1) {
METHODS.appendNavigationBullets();
}
});
},
/**
* @Method : appendNavigationBullets
* @Description : create the bullets of the navigation and handle the click event of each one of theme
*/
'appendNavigationBullets': function() {
var target = '';
$(settings.elements).each(function(i, ele) {
// append elements
$(settings.nav).append("<li><a href='" + ele + "' data-target='" + $(ele).position().top + "'></a></li>");
$(settings.nav).find('a').eq(0).addClass(settings.currentClass);
});
// handle click events once the append is done
$(settings.nav).promise().done(function() {
$(settings.nav).find('a').each(function(i, ele) {
$(ele).on('click', function(event) {
// prevent the default pehave of the element
event.preventDefault();
// set target
target = $(ele).data("target");
// animate the screen
METHODS.animatePageScroll(target);
});
});
// handle scrolling method
METHODS.handleScrolling();
});
},
/**
* @Method : animatePageScroll
* @Description : animate the screen to the target position
* @Param {target} : the next position
*/
'animatePageScroll': function(target) {
// animate the page scroll
$('html, body').animate({
scrollTop: target
}, settings.scrollSpeed);
},
/**
* @Method : searchInRange
* @Description : get the order of the target element by using manual scrolling and active the bullets
* @Param {value} : the value of the scroll top position
*/
'searchInRange': function(value) {
for (var i = 0; i < settings.positions.length; i++) {
var lastIndex = i + 1;
if (lastIndex < settings.positions.length) {
var start = settings.positions[i],
end = settings.positions[lastIndex];
if (value >= start && value < end) {
$(settings.nav).find('a').removeClass(settings.currentClass);
$(settings.nav).find('a').eq(settings.positions.indexOf(start)).addClass(settings.currentClass);
// apply the backGround scrolling animation
if (settings.parallex.length > 0) {
$(settings.parallex[settings.positions.indexOf(start)]).css('background-position', 'center ' + value / 30 + 'px');
}
}
}
if (value >= settings.positions[settings.positions.length - 1]) {
$(settings.nav).find('a').removeClass(settings.currentClass);
$(settings.nav).find('a').last().addClass(settings.currentClass);
}
}
},
/**
* @Method : handleScrolling
* @Description : bind the scrollTop value and path it to the searchInRange Method
*/
'handleScrolling': function() {
$(document).on('scroll', function(event) {
METHODS.searchInRange($(document).scrollTop());
});
},
/**
* @Method : init
* @Description : fire the plugin
*/
'init': function() {
return METHODS.getElementsPositions();
}
};
// init the plugin
METHODS.init();
};
|
var app = app || {};
app.homeViewBag = (function (){
function showHomePage(selector){
$.get("templates/loginAndRegister.html", function(templ){
selector.html(templ);
$("#loginButton").on("click", function(){
var username = $("#inputUsername").val();
var password = $("#inputPassword").val();
var data = {
username : username,
password : password
};
Sammy(function(){
this.trigger("loginUser", data);
});
});
$("#registerButton").on("click", function(){
var regiserUsername = $("#registerUsername").val();
var registerPassword = $("#registerPassword").val();
var repeatRegisterPassword = $("#repeatRegisterPassword").val();
if(registerPassword !== repeatRegisterPassword) {
noty({
theme: 'relax',
text: 'Passwords do not match !',
type: 'error',
timeout: 2000,
closeWith: ['click']
});
} else {
var data = {
username : regiserUsername,
password : registerPassword
};
Sammy(function(){
this.trigger("registerUser", data);
})
}
})
});
}
function showWelcomePage(selector, data){
selector.html("");
}
return {
load: function(){
return {
showHomePage: showHomePage,
showWelcomePage: showWelcomePage
}
}
}
}());
|
import React, { Component } from "react";
import { Link } from "gatsby";
import Img from "gatsby-image";
import "./header.sass";
import Content from "../utility/Content/Content";
import ReactGA from "react-ga";
class Headder extends Component {
constructor(props) {
super(props);
this.state = {
navlinks: [
{
title: "Home",
link: "/"
},
{
title: "Team",
link: "team"
},
{
title: "Program",
link: "program"
},
{
title: "Photos",
link: "photos"
},
{
title: "FAQs",
link: "faq"
},
{
title: "Enroll",
link: "enroll"
},
{
title: "Contribute",
link: "contribute"
},
{
title: "Contact",
link: "contact"
}
],
navOpen: false
};
this.logMobileNavEvent = this.logMobileNavEvent.bind(this);
this.toggleNav = this.toggleNav.bind(this);
}
toggleNav() {
const currentstate = this.state.navOpen;
this.setState({ navOpen: !currentstate });
}
logNavEvent() {
ReactGA.event({
category: `Navigation Click`,
action: `User click on Navigation Link`
});
}
logMobileNavEvent() {
this.toggleNav();
ReactGA.event({
category: `Mobile Navigation Click`,
action: `User click on Navigation Link`
});
}
render() {
return (
<div className="header__wrapper">
<Content>
<div className="header">
<div className="header__title">
<Link
to={"/"}
aria-label={`${this.props.siteTitle} ${this.props.subTitle}`}
>
<h1>
<div className="image">
<div className="image__container">
<Img
fluid={this.props.textLogo}
alt={this.props.textalt}
/>
</div>
</div>
</h1>
</Link>
</div>
<div className="header__logo">
<Img fluid={this.props.logo} alt={this.props.mainalt} />
</div>
{/* desktop nav */}
<div className="desktop">
<nav className="nav">
{/* this is for to pop up the cart
<a className="snipcart-checkout">cart</a> */}
{this.state.navlinks.map((link, index) => (
<div className="nav__link" key={index}>
<Link
activeClassName="nav__link__active"
to={link.link}
onClick={this.logNavEvent.bind(this)}
>
{link.title}
</Link>
</div>
))}
</nav>
</div>
{/* mobile nav */}
<div
className={`mobile ${
this.state.navOpen ? "nav__open" : "nav__closed"
}`}
>
<button
className="dot"
aria-label="click to expand nav"
onClick={() => this.toggleNav()}
>
<div className="dot__one" />
<div className="dot__two" />
<div className="dot__three" />
</button>
<nav className={`nav`}>
{this.state.navlinks.map((link, index) => (
<div key={index} className="nav__link">
<Link
to={link.link}
activeClassName="nav__link__active"
onClick={this.logMobileNavEvent.bind(this)}
>
{link.title}
</Link>
</div>
))}
</nav>
</div>
</div>
</Content>
</div>
);
}
}
export default Headder;
|
const program = require('commander');
const fs = require('fs');
const shell = require('shelljs');
const path = require('path');
program
.description('Test a smart contract as it would be executed on an L1 Dragonchain.', {
image: 'The docker image for this smart contract',
cmd: 'The command to run on this docker container',
containerArgs: '(optional) The arguments to pass in with the command for this smart contract'
})
.arguments('<image>')
.option('-p, --payload <payload>', 'The payload which you want to pass to your contract.')
.option('-d, --test-directory <testDirectory>', 'The folder which contains testing configuration files. Default: "./test"')
.option('-t, --tag <tag>', 'The tag you expect attached to the transaction')
.action((image, options) => {
const { payload, testDirectory } = options || {};
main()
.catch(e => console.error(`Error: ${e.message}`))
.then(killWebserver);
async function main() {
const { testRoot, localEnv, localHeap, localSecrets } = getPaths(testDirectory);
if (payload === undefined) throw new Error(`(-p) --payload is not defined.`);
const networkName = 'dragonchain-webserver';
const config = await getConfig(testRoot);
createDockerNetwork(networkName);
startWebserver(localEnv, networkName, localHeap);
await delay(1000); // Allow the server some time to start up
const contractRunShell = await runContract(image, payload, networkName, config.startCommand, localEnv, localSecrets);
await handleContractOutput(contractRunShell.stdout, localHeap);
}
})
.parse(process.argv);
function delay(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
/**
* stringifyIfObject
* Stringify an object if we need to to match the output of python on dragonchain
* @param {*} value
*/
function stringifyIfObject(value) {
if (typeof value === 'object') return JSON.stringify(value);
return value;
}
/**
* Parse values if possible to match the output on dragonchain
* @param {*} value
*/
function parseIfPossible(value) {
try {
return JSON.parse(value);
} catch (e) {
return value;
}
}
/**
* handleContractOutput
* @param {string} stdout
* @param {string} localHeap
*/
async function handleContractOutput(stdout, localHeap) {
try {
const obj = JSON.parse(stdout);
if (obj.OUTPUT_TO_HEAP && obj.OUTPUT_TO_HEAP === false) {
console.warn('warn: OUTPUT_TO_HEAP false. Not writing to heap state.');
}
await Promise.all(Object.entries(obj).map(([key, value]) => fs.promises.writeFile(path.join(localHeap, key), stringifyIfObject(value))));
} catch (err) {
const raw = path.join(localHeap, 'rawResponse');
console.warn(`warn: Contract output not valid JSON. Writing to "${raw}".`);
await fs.promises.writeFile(raw, stdout);
}
}
function createDockerNetwork(networkName) {
shell.exec(`docker network create ${networkName}`, { silent: true });
}
async function getConfig(testRoot) {
return JSON.parse(await fs.promises.readFile(path.join(testRoot, 'config.json'), 'utf-8'));
}
async function getLocalSecretFileNames(localSecrets) {
try {
return await fs.promises.readdir(localSecrets);
} catch (_) {
return [];
}
}
/**
*
* @param {*} image
* @param {*} payload
* @param {*} network
* @param {*} startCommand
* @param {*} localEnv
* @param {*} localSecrets
*/
async function runContract(image, payload, network, startCommand, localEnv, localSecrets) {
const arrOfSecretFiles = await getLocalSecretFileNames(localSecrets);
const arrOfMountScripts = arrOfSecretFiles.map(fileName => `-v ${path.join(localSecrets, fileName)}:/var/openfaas/secrets/sc-dummy-value-${fileName}:ro`);
const command = `docker run -i \
--name dragonchain-contract \
-l env=dragonchain_test_env \
--network ${network} \
--rm \
${arrOfMountScripts.join(' ')} \
--env-file ${localEnv} \
--entrypoint "" \
${image} ${startCommand}`;
return shell.echo(transaction(parseIfPossible(payload))).exec(command);
}
/**
* startWebserver
* @param {string} localEnv
* @param {string} webserverImage
* @param {string} networkName
* @param {string} localHeap
* @param {string} localSecrets
*/
function startWebserver(localEnv, networkName, localHeap) {
const remoteHeap = '/dragonchain/heap';
const command = `docker run \
--name dragonchain-webserver \
--network ${networkName} \
-d \
-v ${localHeap}:${remoteHeap} \
-l env=dragonchain_test_env \
-p 8080:8080 \
--env-file ${localEnv} \
docker.io/dragonchain/dragonchain_mock_webserver:0.0.3`;
shell.exec(command, { silent: true });
}
/**
* killWebserver
* cleanup the webserver docker images after the tests were run
*/
function killWebserver() {
shell.exec('docker rm -f dragonchain-webserver', { silent: true });
}
/**
* getPaths
* @param {string} testDirectory
*/
function getPaths(testDirectory) {
const testRoot = testDirectory || path.join('.', 'test');
const localHeap = path.resolve(testRoot, 'heap');
const localSecrets = path.resolve(path.join(testRoot, 'secrets'));
const localEnv = path.resolve(path.join(testRoot, '.env'));
if (!directoryExists(localHeap)) throw new Error(`Missing heap directory "${localHeap}". Try running 'dctl contract init --help'.`);
if (!directoryExists(localSecrets)) throw new Error(`Missing secrets directory "${localSecrets}". Try running 'dctl contract init --help'.`);
if (!fileExists(localEnv)) throw new Error(`Missing .env file ${localEnv}. Try running 'dctl contract init --help'.`);
return {
localEnv,
localHeap,
localSecrets,
testRoot
};
}
/**
* fileExists
* Check if a file exists and return boolean.
* @param {string} filePath
* @returns {boolean}
*/
async function fileExists(filePath) {
try {
const status = await fs.promises.stat(filePath);
return status.isFile();
} catch (e) {
return false;
}
}
/**
* directoryExists
* Check if a directory exists and return boolean.
* @param {string} dirPath
* @returns {boolean}
*/
async function directoryExists(dirPath) {
try {
const status = await fs.promises.stat(dirPath);
return status.isDirectory();
} catch (e) {
return false;
}
}
/**
*
* @param {string} payload
* @param {string} tag
*/
function transaction(payload, tag) {
return JSON.stringify({
version: '2',
dcrn: 'Transaction::L1::FullTransaction',
header: {
txn_type: 'test-txn-type',
dc_id: 'test-dcid',
txn_id: 'test-txn-id',
block_id: '',
timestamp: Math.floor(new Date().getTime() / 1000).toString(),
tag: tag || '',
invoker: ''
},
payload,
proof: {
full: "",
stripped: ""
}
});
}
|
define([
'client/views/table',
'extensions/views/table',
'extensions/collections/collection',
'extensions/models/model',
'jquery',
'modernizr'
],
function (Table, BaseTable, Collection, Model, $, Modernizr) {
describe('Table', function () {
describe('initialize', function () {
var table,
options;
beforeEach(function () {
spyOn(Table.prototype, 'render');
spyOn(BaseTable.prototype, 'initialize');
options = {
model: new Model(),
collection: new Collection({
'_timestamp': '2014-07-03T13:19:04+00:00',
value: 'hello world',
options: {
axes: {
x: { label: 'date', key: 'timestamp' },
y: [{ label: 'another', key: 'value' }]
}
}
}, {
axes: {
x: { label: 'date', key: 'timestamp' },
y: [{ label: 'another', key: 'value' }]
}
})
};
});
it('listens to sort on the collection', function () {
table = new Table(options);
table.collection.trigger('sort');
expect(table.render).toHaveBeenCalled();
});
it('calls initialize on TableView', function () {
table = new Table(options);
expect(BaseTable.prototype.initialize).toHaveBeenCalled();
});
it('uses an X axis if supplied', function () {
table = new Table(options);
expect(table.sortFields.timestamp.label).toEqual('date');
});
it('doesnt try to use an X axis if one isnt supplied', function () {
delete options.collection.options.axes.x;
table = new Table(options);
expect(table.sortFields.timestamp).toBeUndefined();
});
});
describe('renderSort', function () {
var table;
beforeEach(function () {
spyOn(BaseTable.prototype, 'renderBody');
spyOn(Table.prototype, 'render');
table = new Table({
model: new Model(),
collection: new Collection({
'_timestamp': '2014-07-03T13:19:04+00:00',
value: 'model 1'
}, {
axes: {
x: { label: 'date', key: 'timestamp' },
y: [{ label: 'another', key: 'value' }]
}
})
});
});
it('calls render', function () {
expect(table.render).not.toHaveBeenCalled();
table.render();
expect(table.render).toHaveBeenCalled();
});
});
describe('sort', function () {
var table;
beforeEach(function () {
// clear window.location.search
window.history.replaceState({}, '', window.location.href.split('?')[0]);
var $el = $('<div/>');
$el.html(
'<table><thead><tr><th scope="col" width="0" data-key="_timestamp">' +
'<a class="js-sort" href="#" role="button">date</a></th>' +
'<th scope="col" width="0" data-key="value"><a class="js-sort" href="#" role="button">another</a></th></tr></thead><tbody><tr><td class="" width="0">2014-07-03T13:21:04+00:00</td>' +
'<td class="" width="0">hello</td></tr>' +
'<tr><td class="" width="">2014-07-03T13:19:04+00:00</td>' +
'<td class="" width="">hello world</td></tr>' +
'<tr><td class="" width="">2014-07-03T13:23:04+00:00</td>' +
'<td class="" width="">hello world</td></tr></tbody></table>'
);
window.GOVUK = {
analytics: {
trackEvent: function () {}
}
};
table = new Table({
el: $el,
model: new Model(),
collection: new Collection([{
'_timestamp': '2014-07-03T13:21:04+00:00',
value: 'hello'
},
{
'_timestamp': '2014-07-03T13:19:04+00:00',
value: 'hello world'
},
{
'_timestamp': '2014-07-03T13:23:04+00:00',
value: 'hello world'
}], {
axes: {
x: { label: 'date', key: 'timestamp' },
y: [{ label: 'another', key: 'value' }]
}
}),
saveSortInUrl: true,
analytics: {
category: 'ppServices'
}
});
table.render();
});
function dateColumn() {
return table.$('thead th:first');
}
function valueColumn() {
return table.$('thead th:last');
}
it('adds a class of desc if the col isnt sorted', function () {
expect(dateColumn().attr('class')).toEqual(undefined);
expect(valueColumn().attr('class')).toEqual(undefined);
dateColumn().find('a').click();
expect(dateColumn().hasClass('descending')).toEqual(true);
expect(valueColumn().hasClass('descending')).toEqual(false);
});
it('adds a class of ascending if the col already descending', function () {
expect(dateColumn().attr('class')).toEqual(undefined);
expect(valueColumn().attr('class')).toEqual(undefined);
dateColumn().find('a').click();
dateColumn().find('a').click();
expect(dateColumn().hasClass('ascending')).toEqual(true);
expect(valueColumn().hasClass('ascending')).toEqual(false);
});
it('it removes asc from other cols', function () {
dateColumn().find('a').click();
dateColumn().find('a').click();
expect(dateColumn().hasClass('ascending')).toEqual(true);
expect(valueColumn().hasClass('ascending')).toEqual(false);
valueColumn().find('a').click();
expect(dateColumn().hasClass('descending')).toEqual(false);
expect(valueColumn().hasClass('descending')).toEqual(true);
});
it('it removes desc from other cols', function () {
dateColumn().find('a').click();
expect(dateColumn().hasClass('descending')).toEqual(true);
expect(valueColumn().hasClass('descending')).toEqual(false);
valueColumn().find('a').click();
expect(dateColumn().hasClass('descending')).toEqual(false);
expect(valueColumn().hasClass('descending')).toEqual(true);
});
it('stores the sort column and order in the browser address if option set', function() {
var sortByValue = table.$('thead th:last');
spyOn(Table.prototype, 'replaceUrlParams');
sortByValue.find('a').click();
expect(Table.prototype.replaceUrlParams.calls.first().args[0]).toEqual('sortby=value&sortorder=descending');
});
it('doesnt store the sort column and order in the browser address if option not set',
function() {
var sortByValue = table.$('thead th:last');
table.options.saveSortInUrl = false;
spyOn(Table.prototype, 'replaceUrlParams');
sortByValue.find('a').click();
expect(Table.prototype.replaceUrlParams.calls.count()).toEqual(0);
});
it('adds a click to sort label for screenreaders to all columns except the sorted one',
function() {
dateColumn().find('a').click();
expect(dateColumn().find('.js-click-sort').length).toEqual(0);
expect(valueColumn().find('.js-click-sort').length).toEqual(1);
valueColumn().find('a').click();
expect(valueColumn().find('.js-click-sort').length).toEqual(0);
expect(dateColumn().find('.js-click-sort').length).toEqual(1);
});
it('sends sort events to analytics', function() {
spyOn(window.GOVUK.analytics, 'trackEvent');
dateColumn().find('a').click();
expect(window.GOVUK.analytics.trackEvent).toHaveBeenCalledWith('ppServices', 'sort', {
label: '_timestamp',
value: 1,
nonInteraction: true
});
valueColumn().find('a').click();
expect(window.GOVUK.analytics.trackEvent).toHaveBeenCalledWith('ppServices', 'sort', {
label: 'value',
value: 1,
nonInteraction: true
});
valueColumn().find('a').click();
expect(window.GOVUK.analytics.trackEvent).toHaveBeenCalledWith('ppServices', 'sort', {
label: 'value',
value: 0,
nonInteraction: true
});
});
});
describe('render', function () {
var table;
beforeEach(function () {
spyOn(BaseTable.prototype, 'render');
table = new Table({
model: new Model(),
collection: new Collection({
'_timestamp': '2014-07-03T13:19:04+00:00',
value: 'hello world'
}, {
axes: {
x: { label: 'date', key: 'timestamp' },
y: [{ label: 'another', key: 'value' }]
}
})
});
});
it('adds a class of touch-table on touch devices', function () {
var isTouch = Modernizr.touch;
var touchTable = new Table({
model: new Model(),
collection: new Collection([], {
axes: {
x: { label: 'date', key: 'timestamp' },
y: [{ label: 'another', key: 'value' }]
}
})
}),
$table = $('<table></table>');
Modernizr.touch = true;
touchTable.$el.append($table);
touchTable.render();
expect($table.attr('class')).toContain('touch-table');
Modernizr.touch = isTouch;
});
it('adds a class of floated-header to the table element on the client-side when table body has more cells than the header', function () {
var tableHeader = '<thead><tr><th>Col1</th><th>Col2</th></tr></thead>',
tableBody = '<tbody><tr><td>Item1</td><td>Item2</td></tr><tr><td>Item1</td><td>Item2</td></tr></tbody>';
var $table = $('<table>' + tableHeader + tableBody + '</table>');
table.$el.append($table);
table.collection.push({
'_timestamp': '2014-07-03T13:19:04+00:00',
value: 'row 2'
});
table.render();
expect($table.attr('class')).toContain('floated-header');
});
it('doesnt a class of floated-header to the table element on the client-side when the table body has "no data"', function () {
var tableHeader = '<thead><tr><th>Col1</th><th>Col2</th></tr></thead>',
tableBody = '<tbody><tr><td>No data available</td></tr></tbody>';
var $table = $('<table>' + tableHeader + tableBody + '</table>');
table.$el.append($table);
table.render();
expect($table.attr('class')).not.toEqual('floated-header');
});
});
});
});
|
import ConverterController from '../converterController';
class DeltaConverter {
setQuillInstance(quillInstance) {
this.quillInstance = quillInstance;
}
toHtml() {
if (!this.quillInstance) {
return;
}
return this._isQuillEmpty() ? '' : this.quillInstance.getSemanticHTML(0, this.quillInstance.getLength() + 1);
}
_isQuillEmpty() {
var delta = this.quillInstance.getContents();
return delta.length() === 1 && this._isDeltaEmpty(delta);
}
_isDeltaEmpty(delta) {
return delta.reduce((__, _ref) => {
var {
insert
} = _ref;
return insert.indexOf('\n') !== -1;
});
}
}
ConverterController.addConverter('delta', DeltaConverter);
export default DeltaConverter;
|
/* eslint-disable no-extend-native */
export const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
export const getMonthName = month => monthNames[month]
export const getShortMonthName = month => getMonthName(month).substr(0, 3)
|
import React from "react";
import { Route, Redirect } from "react-router-dom";
import AuthHelper from '../../helpers/AuthHelper';
const PrivateRoute = ({ component: Component,role:role, ...rest }) => (
<Route {...rest} render={(props) => (
AuthHelper.isUserAuthenticated()
? checkForAuthorize(Component,props,role)
: <Redirect to='/login' />
)} />
)
function checkForAuthorize(Component,props,role){
if(AuthHelper.isAuthorized(role)){
return <Component {...props} />;
}
return <Redirect to='/401' />;
}
export default PrivateRoute;
|
import { useState, useEffect } from "react";
import { useSelector} from "react-redux";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import interactionPlugin from "@fullcalendar/interaction";
const Dash = (props) => {
const [games, setGames] = useState([]);
const { user } = useSelector((store) => store.auth);
const joinedGames = useSelector((store) => store.joinedGamesReducer);
useEffect(() => {
setGames(joinedGames.games);
}, [joinedGames, user]);
const eventClick = (e) => {
let game_id = e.event._def.publicId;
props.history.push(`/game/${game_id}`);
};
return (
<div id="dashContainer">
<h2 id="calendarTitle">Scheduled Games</h2>
<FullCalendar
headerToolbar={{
start: "title",
center: "",
end: "prev,next",
}}
height="80vh"
plugins={[dayGridPlugin, interactionPlugin]}
initialView="dayGridMonth"
weekends={true}
displayEventTime={true}
eventBackgroundColor={"#5FBFF9"}
eventClick={eventClick}
eventTextColor={"black"}
eventDisplay={"block"}
events={[
...games
.filter((game) => {
let today = new Date();
let comp = new Date(game.date);
let time = game.time.split(":");
comp.setHours(time[0], time[1]);
if (comp >= today) {
return game;
}
else return null;
})
.map((game) => {
let date = new Date(game.date);
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
if (day < 10) {
day = `0${day}`;
}
if (month < 10) {
month = `0${month}`;
}
let eventDate = `${year}-${month}-${day} ${game.time}`;
return {
title: game.title,
date: eventDate,
id: game.game_id,
};
}),
]}
/>
</div>
);
};
export default Dash;
|
const {Parser} = require('htmlparser2');
const {DomHandler} = require('domhandler');
const fs = require('fs');
const CSSselect = require('css-select');
const rawHtml = fs.readFileSync(__dirname + '/page.html');
function match(selector, ele, context) {
let res = CSSselect(selector, context);
return res.indexOf(ele) > -1;
}
const handler = new DomHandler((err, dom) => {
if (err) {
} else {
// console.log(dom);
let res = CSSselect('#flex', dom);
console.log(res);
let isMatch = match('#flex', res[0], dom);
console.log(isMatch);
}
});
const parser = new Parser(handler);
parser.write(rawHtml);
parser.end();
|
module.exports = function(app) {
return {
lista: function(req, res){
var grupos = [
{ _id: 1, nome: 'esporte' },
{ _id: 2, nome: 'lugares' },
{ _id: 3, nome: 'animais' }
];
res.json(grupos);
}
};
};
|
import React from 'react';
import ReactDOM from 'react-dom';
import CopyCat from '../components/CopyCat.js';
class CopyCatContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
copying: true,
input: ''
};
this.toggleTape = this.toggleTape.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({
input: event.target.value
});
}
toggleTape() {
this.setState({
copying: !this.state.copying
});
}
render() {
return <CopyCat
copying={this.state.copying}
toggleTape={this.toggleTape}
input={this.state.input}
onChange={this.handleChange}
/>;
};
}
ReactDOM.render(
<CopyCatContainer />,
document.getElementById('app'));
|
/* @flow */
'use strict'
import mongoose from 'mongoose'
const imageSchema = new mongoose.Schema({
img: {
type: Buffer,
required: false
},
mimetype: {
type: String,
required: false
}
})
export default mongoose.model('Image', imageSchema)
|
// Cross-broswer implementation of text ranges and selections
// documentation: http://bililite.com/blog/2011/01/17/cross-browser-text-ranges-and-selections/
// Version: 1.1
// Copyright (c) 2010 Daniel Wachsstock
// MIT license:
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
(function(){
bililiteRange = function(el, debug){
var ret;
if (debug){
ret = new NothingRange(); // Easier to force it to use the no-selection type than to try to find an old browser
}else if (document.selection){
// Internet Explorer
ret = new IERange();
}else if (window.getSelection && el.setSelectionRange){
// Standards. Element is an input or textarea
ret = new InputRange();
}else if (window.getSelection){
// Standards, with any other kind of element
ret = new W3CRange();
}else{
// doesn't support selection
ret = new NothingRange();
}
ret._el = el;
ret._textProp = textProp(el);
ret._bounds = [0, ret.length()];
return ret;
};
function textProp(el){
// returns the property that contains the text of the element
if (typeof el.value != 'undefined') return 'value';
if (typeof el.text != 'undefined') return 'text';
if (typeof el.textContent != 'undefined') return 'textContent';
return 'innerText';
}
// base class
function Range(){}
Range.prototype = {
length: function() {
return this._el[this._textProp].replace(/\r/g, '').length; // need to correct for IE's CrLf weirdness
},
bounds: function(s){
if (s === 'all'){
this._bounds = [0, this.length()];
}else if (s === 'start'){
this._bounds = [0, 0];
}else if (s === 'end'){
this._bounds = [this.length(), this.length()];
}else if (s === 'selection'){
this.bounds ('all'); // first select the whole thing for constraining
this._bounds = this._nativeSelection();
}else if (s){
this._bounds = s; // don't error check now; the element may change at any moment, so constrain it when we need it.
}else{
var b = [
Math.max(0, Math.min (this.length(), this._bounds[0])),
Math.max(0, Math.min (this.length(), this._bounds[1]))
];
return b; // need to constrain it to fit
}
return this; // allow for chaining
},
select: function(){
this._nativeSelect(this._nativeRange(this.bounds()));
return this; // allow for chaining
},
text: function(text, select){
if (arguments.length){
this._nativeSetText(text, this._nativeRange(this.bounds()));
if (select == 'start'){
this.bounds ([this._bounds[0], this._bounds[0]]);
this.select();
}else if (select == 'end'){
this.bounds ([this._bounds[0]+text.length, this._bounds[0]+text.length]);
this.select();
}else if (select == 'all'){
this.bounds ([this._bounds[0], this._bounds[0]+text.length]);
this.select();
}
return this; // allow for chaining
}else{
return this._nativeGetText(this._nativeRange(this.bounds()));
}
},
insertEOL: function (){
this._nativeEOL();
this._bounds = [this._bounds[0]+1, this._bounds[0]+1]; // move past the EOL marker
return this;
}
};
function IERange(){}
IERange.prototype = new Range();
IERange.prototype._nativeRange = function (bounds){
var rng;
if (this._el.tagName == 'INPUT'){
// IE 8 is very inconsistent; textareas have createTextRange but it doesn't work
rng = this._el.createTextRange();
}else{
rng = document.body.createTextRange ();
rng.moveToElementText(this._el);
}
if (bounds){
if (bounds[1] < 0) bounds[1] = 0; // IE tends to run elements out of bounds
if (bounds[0] > this.length()) bounds[0] = this.length();
if (bounds[1] < rng.text.replace(/\r/g, '').length){ // correct for IE's CrLf wierdness
// block-display elements have an invisible, uncounted end of element marker, so we move an extra one and use the current length of the range
rng.moveEnd ('character', -1);
rng.moveEnd ('character', bounds[1]-rng.text.replace(/\r/g, '').length);
}
if (bounds[0] > 0) rng.moveStart('character', bounds[0]);
}
return rng;
};
IERange.prototype._nativeSelect = function (rng){
rng.select();
};
IERange.prototype._nativeSelection = function (){
// returns [start, end] for the selection constrained to be in element
var rng = this._nativeRange(); // range of the element to constrain to
var len = this.length();
if (document.selection.type != 'Text') return [len, len]; // append to the end
var sel = document.selection.createRange();
try{
return [
iestart(sel, rng),
ieend (sel, rng)
];
}catch (e){
// IE gets upset sometimes about comparing text to input elements, but the selections cannot overlap, so make a best guess
return (sel.parentElement().sourceIndex < this._el.sourceIndex) ? [0,0] : [len, len];
}
};
IERange.prototype._nativeGetText = function (rng){
return rng.text.replace(/\r/g, ''); // correct for IE's CrLf weirdness
};
IERange.prototype._nativeSetText = function (text, rng){
rng.text = text;
};
IERange.prototype._nativeEOL = function(){
if (typeof this._el.value != 'undefined'){
this.text('\n'); // for input and textarea, insert it straight
}else{
this._nativeRange(this.bounds()).pasteHTML('<br/>');
}
};
// IE internals
function iestart(rng, constraint){
// returns the position (in character) of the start of rng within constraint. If it's not in constraint, returns 0 if it's before, length if it's after
var len = constraint.text.replace(/\r/g, '').length; // correct for IE's CrLf wierdness
if (rng.compareEndPoints ('StartToStart', constraint) <= 0) return 0; // at or before the beginning
if (rng.compareEndPoints ('StartToEnd', constraint) >= 0) return len;
for (var i = 0; rng.compareEndPoints ('StartToStart', constraint) > 0; ++i, rng.moveStart('character', -1));
return i;
}
function ieend (rng, constraint){
// returns the position (in character) of the end of rng within constraint. If it's not in constraint, returns 0 if it's before, length if it's after
var len = constraint.text.replace(/\r/g, '').length; // correct for IE's CrLf wierdness
if (rng.compareEndPoints ('EndToEnd', constraint) >= 0) return len; // at or after the end
if (rng.compareEndPoints ('EndToStart', constraint) <= 0) return 0;
for (var i = 0; rng.compareEndPoints ('EndToStart', constraint) > 0; ++i, rng.moveEnd('character', -1));
return i;
}
// an input element in a standards document. "Native Range" is just the bounds array
function InputRange(){}
InputRange.prototype = new Range();
InputRange.prototype._nativeRange = function(bounds) {
return bounds || [0, this.length()];
};
InputRange.prototype._nativeSelect = function (rng){
this._el.setSelectionRange(rng[0], rng[1]);
};
InputRange.prototype._nativeSelection = function(){
return [this._el.selectionStart, this._el.selectionEnd];
};
InputRange.prototype._nativeGetText = function(rng){
return this._el.value.substring(rng[0], rng[1]);
};
InputRange.prototype._nativeSetText = function(text, rng){
var val = this._el.value;
this._el.value = val.substring(0, rng[0]) + text + val.substring(rng[1]);
};
InputRange.prototype._nativeEOL = function(){
this.text('\n');
};
function W3CRange(){}
W3CRange.prototype = new Range();
W3CRange.prototype._nativeRange = function (bounds){
var rng = document.createRange();
rng.selectNodeContents(this._el);
if (bounds){
w3cmoveBoundary (rng, bounds[0], true, this._el);
rng.collapse (true);
w3cmoveBoundary (rng, bounds[1]-bounds[0], false, this._el);
}
return rng;
};
W3CRange.prototype._nativeSelect = function (rng){
window.getSelection().removeAllRanges();
window.getSelection().addRange (rng);
};
W3CRange.prototype._nativeSelection = function (){
// returns [start, end] for the selection constrained to be in element
var rng = this._nativeRange(); // range of the element to constrain to
if (window.getSelection().rangeCount == 0) return [this.length(), this.length()]; // append to the end
var sel = window.getSelection().getRangeAt(0);
return [
w3cstart(sel, rng),
w3cend (sel, rng)
];
};
W3CRange.prototype._nativeGetText = function (rng){
return rng.toString();
};
W3CRange.prototype._nativeSetText = function (text, rng){
rng.deleteContents();
rng.insertNode (document.createTextNode(text));
this._el.normalize(); // merge the text with the surrounding text
};
W3CRange.prototype._nativeEOL = function(){
var rng = this._nativeRange(this.bounds());
rng.deleteContents();
var br = document.createElement('br');
br.setAttribute ('_moz_dirty', ''); // for Firefox
rng.insertNode (br);
rng.insertNode (document.createTextNode('\n'));
rng.collapse (false);
};
// W3C internals
function nextnode (node, root){
// in-order traversal
// we've already visited node, so get kids then siblings
if (node.firstChild) return node.firstChild;
if (node.nextSibling) return node.nextSibling;
if (node===root) return null;
while (node.parentNode){
// get uncles
node = node.parentNode;
if (node == root) return null;
if (node.nextSibling) return node.nextSibling;
}
return null;
}
function w3cmoveBoundary (rng, n, bStart, el){
// move the boundary (bStart == true ? start : end) n characters forward, up to the end of element el. Forward only!
// if the start is moved after the end, then an exception is raised
if (n <= 0) return;
var node = rng[bStart ? 'startContainer' : 'endContainer'];
if (node.nodeType == 3){
// we may be starting somewhere into the text
n += rng[bStart ? 'startOffset' : 'endOffset'];
}
while (node){
if (node.nodeType == 3){
if (n <= node.nodeValue.length){
rng[bStart ? 'setStart' : 'setEnd'](node, n);
// special case: if we end next to a <br>, include that node.
if (n == node.nodeValue.length){
// skip past zero-length text nodes
for (var next = nextnode (node, el); next && next.nodeType==3 && next.nodeValue.length == 0; next = nextnode(next, el)){
rng[bStart ? 'setStartAfter' : 'setEndAfter'](next);
}
if (next && next.nodeType == 1 && next.nodeName == "BR") rng[bStart ? 'setStartAfter' : 'setEndAfter'](next);
}
return;
}else{
rng[bStart ? 'setStartAfter' : 'setEndAfter'](node); // skip past this one
n -= node.nodeValue.length; // and eat these characters
}
}
node = nextnode (node, el);
}
}
var START_TO_START = 0; // from the w3c definitions
var START_TO_END = 1;
var END_TO_END = 2;
var END_TO_START = 3;
// from the Mozilla documentation, for range.compareBoundaryPoints(how, sourceRange)
// -1, 0, or 1, indicating whether the corresponding boundary-point of range is respectively before, equal to, or after the corresponding boundary-point of sourceRange.
// * Range.END_TO_END compares the end boundary-point of sourceRange to the end boundary-point of range.
// * Range.END_TO_START compares the end boundary-point of sourceRange to the start boundary-point of range.
// * Range.START_TO_END compares the start boundary-point of sourceRange to the end boundary-point of range.
// * Range.START_TO_START compares the start boundary-point of sourceRange to the start boundary-point of range.
function w3cstart(rng, constraint){
if (rng.compareBoundaryPoints (START_TO_START, constraint) <= 0) return 0; // at or before the beginning
if (rng.compareBoundaryPoints (END_TO_START, constraint) >= 0) return constraint.toString().length;
rng = rng.cloneRange(); // don't change the original
rng.setEnd (constraint.endContainer, constraint.endOffset); // they now end at the same place
return constraint.toString().length - rng.toString().length;
}
function w3cend (rng, constraint){
if (rng.compareBoundaryPoints (END_TO_END, constraint) >= 0) return constraint.toString().length; // at or after the end
if (rng.compareBoundaryPoints (START_TO_END, constraint) <= 0) return 0;
rng = rng.cloneRange(); // don't change the original
rng.setStart (constraint.startContainer, constraint.startOffset); // they now start at the same place
return rng.toString().length;
}
function NothingRange(){}
NothingRange.prototype = new Range();
NothingRange.prototype._nativeRange = function(bounds) {
return bounds || [0,this.length()];
};
NothingRange.prototype._nativeSelect = function (rng){ // do nothing
};
NothingRange.prototype._nativeSelection = function(){
return [0,0];
};
NothingRange.prototype._nativeGetText = function (rng){
return this._el[this._textProp].substring(rng[0], rng[1]);
};
NothingRange.prototype._nativeSetText = function (text, rng){
var val = this._el[this._textProp];
this._el[this._textProp] = val.substring(0, rng[0]) + text + val.substring(rng[1]);
};
NothingRange.prototype._nativeEOL = function(){
this.text('\n');
};
})();
/*!
* jQuery Simulate v0.0.1 - simulate browser mouse and keyboard events
* https://github.com/jquery/jquery-simulate
*
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* Date: Sun Dec 9 12:15:33 2012 -0500
*/
;(function( $, undefined ) {
"use strict";
var rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rdocument = /\[object (?:HTML)?Document\]/;
function isDocument(ele) {
return rdocument.test(Object.prototype.toString.call(ele));
}
function windowOfDocument(doc) {
for (var i=0; i < window.frames.length; i+=1) {
if (window.frames[i].document === doc) {
return window.frames[i];
}
}
return window;
}
$.fn.simulate = function( type, options ) {
return this.each(function() {
new $.simulate( this, type, options );
});
};
$.simulate = function( elem, type, options ) {
var method = $.camelCase( "simulate-" + type );
this.target = elem;
this.options = options || {};
if ( this[ method ] ) {
this[ method ]();
} else {
this.simulateEvent( elem, type, this.options );
}
};
$.extend( $.simulate, {
keyCode: {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
},
buttonCode: {
LEFT: 0,
MIDDLE: 1,
RIGHT: 2
}
});
$.extend( $.simulate.prototype, {
simulateEvent: function( elem, type, options ) {
var event = this.createEvent( type, options );
this.dispatchEvent( elem, type, event, options );
},
createEvent: function( type, options ) {
if ( rkeyEvent.test( type ) ) {
return this.keyEvent( type, options );
}
if ( rmouseEvent.test( type ) ) {
return this.mouseEvent( type, options );
}
},
mouseEvent: function( type, options ) {
var event,
eventDoc,
doc = isDocument(this.target)? this.target : (this.target.ownerDocument || document),
docEle,
body;
options = $.extend({
bubbles: true,
cancelable: (type !== "mousemove"),
view: windowOfDocument(doc),
detail: 0,
screenX: 0,
screenY: 0,
clientX: 1,
clientY: 1,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
button: 0,
relatedTarget: undefined
}, options );
if ( doc.createEvent ) {
event = doc.createEvent( "MouseEvents" );
event.initMouseEvent( type, options.bubbles, options.cancelable,
options.view, options.detail,
options.screenX, options.screenY, options.clientX, options.clientY,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
options.button, options.relatedTarget || doc.body.parentNode );
// IE 9+ creates events with pageX and pageY set to 0.
// Trying to modify the properties throws an error,
// so we define getters to return the correct values.
if ( event.pageX === 0 && event.pageY === 0 && Object.defineProperty ) {
eventDoc = isDocument(event.relatedTarget)? event.relatedTarget : (event.relatedTarget.ownerDocument || document);
docEle = eventDoc.documentElement;
body = eventDoc.body;
Object.defineProperty( event, "pageX", {
get: function() {
return options.clientX +
( docEle && docEle.scrollLeft || body && body.scrollLeft || 0 ) -
( docEle && docEle.clientLeft || body && body.clientLeft || 0 );
}
});
Object.defineProperty( event, "pageY", {
get: function() {
return options.clientY +
( docEle && docEle.scrollTop || body && body.scrollTop || 0 ) -
( docEle && docEle.clientTop || body && body.clientTop || 0 );
}
});
}
} else if ( doc.createEventObject ) {
event = doc.createEventObject();
$.extend( event, options );
// standards event.button uses constants defined here: http://msdn.microsoft.com/en-us/library/ie/ff974877(v=vs.85).aspx
// old IE event.button uses constants defined here: http://msdn.microsoft.com/en-us/library/ie/ms533544(v=vs.85).aspx
// so we actually need to map the standard back to oldIE
event.button = {
0: 1,
1: 4,
2: 2
}[ event.button ] || event.button;
}
return event;
},
keyEvent: function( type, options ) {
var event, doc;
options = $.extend({
bubbles: true,
cancelable: true,
view: windowOfDocument(doc),
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
keyCode: 0,
charCode: undefined
}, options );
doc = isDocument(this.target)? this.target : (this.target.ownerDocument || document);
if ( doc.createEvent ) {
try {
event = doc.createEvent( "KeyEvents" );
event.initKeyEvent( type, options.bubbles, options.cancelable, options.view,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
options.keyCode, options.charCode );
// initKeyEvent throws an exception in WebKit
// see: http://stackoverflow.com/questions/6406784/initkeyevent-keypress-only-works-in-firefox-need-a-cross-browser-solution
// and also https://bugs.webkit.org/show_bug.cgi?id=13368
// fall back to a generic event until we decide to implement initKeyboardEvent
} catch( err ) {
event = doc.createEvent( "Events" );
event.initEvent( type, options.bubbles, options.cancelable );
$.extend( event, {
view: options.view,
ctrlKey: options.ctrlKey,
altKey: options.altKey,
shiftKey: options.shiftKey,
metaKey: options.metaKey,
keyCode: options.keyCode,
charCode: options.charCode
});
}
} else if ( doc.createEventObject ) {
event = doc.createEventObject();
$.extend( event, options );
}
if ( !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ) || (({}).toString.call( window.opera ) === "[object Opera]") ) {
event.keyCode = (options.charCode > 0) ? options.charCode : options.keyCode;
event.charCode = undefined;
}
return event;
},
dispatchEvent: function( elem, type, event, options ) {
if (options.jQueryTrigger === true) {
$(elem).trigger($.extend({}, event, options, {type: type}));
}
else if ( elem.dispatchEvent ) {
elem.dispatchEvent( event );
} else if ( elem.fireEvent ) {
elem.fireEvent( "on" + type, event );
}
},
simulateFocus: function() {
var focusinEvent,
triggered = false,
$element = $( this.target );
function trigger() {
triggered = true;
}
$element.bind( "focus", trigger );
$element[ 0 ].focus();
if ( !triggered ) {
focusinEvent = $.Event( "focusin" );
focusinEvent.preventDefault();
$element.trigger( focusinEvent );
$element.triggerHandler( "focus" );
}
$element.unbind( "focus", trigger );
},
simulateBlur: function() {
var focusoutEvent,
triggered = false,
$element = $( this.target );
function trigger() {
triggered = true;
}
$element.bind( "blur", trigger );
$element[ 0 ].blur();
// blur events are async in IE
setTimeout(function() {
// IE won't let the blur occur if the window is inactive
if ( $element[ 0 ].ownerDocument.activeElement === $element[ 0 ] ) {
$element[ 0 ].ownerDocument.body.focus();
}
// Firefox won't trigger events if the window is inactive
// IE doesn't trigger events if we had to manually focus the body
if ( !triggered ) {
focusoutEvent = $.Event( "focusout" );
focusoutEvent.preventDefault();
$element.trigger( focusoutEvent );
$element.triggerHandler( "blur" );
}
$element.unbind( "blur", trigger );
}, 1 );
}
});
/** complex events **/
function findCenter( elem ) {
var offset,
$document,
$elem = $( elem );
if ( isDocument($elem[0]) ) {
$document = $elem;
offset = { left: 0, top: 0 };
}
else {
$document = $( $elem[0].ownerDocument || document );
offset = $elem.offset();
}
return {
x: offset.left + $elem.outerWidth() / 2 - $document.scrollLeft(),
y: offset.top + $elem.outerHeight() / 2 - $document.scrollTop()
};
}
function findCorner( elem ) {
var offset,
$document,
$elem = $( elem );
if ( isDocument($elem[0]) ) {
$document = $elem;
offset = { left: 0, top: 0 };
}
else {
$document = $( $elem[0].ownerDocument || document );
offset = $elem.offset();
}
return {
x: offset.left - document.scrollLeft(),
y: offset.top - document.scrollTop()
};
}
$.extend( $.simulate.prototype, {
simulateDrag: function() {
var i = 0,
target = this.target,
options = this.options,
center = options.handle === "corner" ? findCorner( target ) : findCenter( target ),
x = Math.floor( center.x ),
y = Math.floor( center.y ),
coord = { clientX: x, clientY: y },
dx = options.dx || ( options.x !== undefined ? options.x - x : 0 ),
dy = options.dy || ( options.y !== undefined ? options.y - y : 0 ),
moves = options.moves || 3;
this.simulateEvent( target, "mousedown", coord );
for ( ; i < moves ; i++ ) {
x += dx / moves;
y += dy / moves;
coord = {
clientX: Math.round( x ),
clientY: Math.round( y )
};
this.simulateEvent( target.ownerDocument, "mousemove", coord );
}
if ( $.contains( document, target ) ) {
this.simulateEvent( target, "mouseup", coord );
this.simulateEvent( target, "click", coord );
} else {
this.simulateEvent( document, "mouseup", coord );
}
}
});
})( jQuery );
/*jshint camelcase:true, plusplus:true, forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, unused:true, curly:true, browser:true, devel:true, maxerr:100, white:false, onevar:false */
/*global jQuery:true $:true */
/* jQuery Simulate Extended Plugin 1.3.0
* http://github.com/j-ulrich/jquery-simulate-ext
*
* Copyright (c) 2014 Jochen Ulrich
* Licensed under the MIT license (MIT-LICENSE.txt).
*/
;(function( $ ) {
"use strict";
/* Overwrite the $.simulate.prototype.mouseEvent function
* to convert pageX/Y to clientX/Y
*/
var originalMouseEvent = $.simulate.prototype.mouseEvent,
rdocument = /\[object (?:HTML)?Document\]/;
$.simulate.prototype.mouseEvent = function(type, options) {
if (options.pageX || options.pageY) {
var doc = rdocument.test(Object.prototype.toString.call(this.target))? this.target : (this.target.ownerDocument || document);
options.clientX = (options.pageX || 0) - $(doc).scrollLeft();
options.clientY = (options.pageY || 0) - $(doc).scrollTop();
}
return originalMouseEvent.apply(this, [type, options]);
};
})( jQuery );
/*jshint camelcase:true, plusplus:true, forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, unused:true, curly:true, browser:true, devel:true, maxerr:100, white:false, onevar:false */
/*global jQuery:true $:true */
/* jQuery Simulate Drag-n-Drop Plugin 1.3.0
* http://github.com/j-ulrich/jquery-simulate-ext
*
* Copyright (c) 2014 Jochen Ulrich
* Licensed under the MIT license (MIT-LICENSE.txt).
*/
;(function($, undefined) {
"use strict";
/* Overwrite the $.fn.simulate function to reduce the jQuery set to the first element for the
* drag-n-drop interactions.
*/
$.fn.simulate = function( type, options ) {
switch (type) {
case "drag":
case "drop":
case "drag-n-drop":
var ele = this.first();
new $.simulate( ele[0], type, options);
return ele;
default:
return this.each(function() {
new $.simulate( this, type, options );
});
}
};
var now = Date.now || function() { return new Date().getTime(); };
var rdocument = /\[object (?:HTML)?Document\]/;
/**
* Tests whether an object is an (HTML) document object.
* @param {DOM Element} elem - the object/element to be tested
* @returns {Boolean} <code>true</code> if <i>elem</i> is an (HTML) document object.
* @private
* @author julrich
* @since 1.1
*/
function isDocument( elem ) {
return rdocument.test(Object.prototype.toString.call($(elem)[0]));
}
/**
* Selects the first match from an array.
* @param {Array} array - Array of objects to be be tested
* @param {Function} check - Callback function that accepts one argument (which will be one element
* from the <i>array</i>) and returns a boolean.
* @returns {Boolean|null} the first element in <i>array</i> for which <i>check</i> returns <code>true</code>.
* If none of the elements in <i>array</i> passes <i>check</i>, <code>null</code> is returned.
* @private
* @author julrich
* @since 1.1
*/
function selectFirstMatch(array, check) {
var i;
if ($.isFunction(check)) {
for (i=0; i < array.length; i+=1) {
if (check(array[i])) {
return array[i];
}
}
return null;
}
else {
for (i=0; i < array.length; i+=1) {
if (array[i]) {
return array[i];
}
}
return null;
}
}
// Based on the findCenter function from jquery.simulate.js
/**
* Calculates the position of the center of an DOM element.
* @param {DOM Element} elem - the element whose center should be calculated.
* @returns {Object} an object with the properties <code>x</code> and <code>y</code>
* representing the position of the center of <i>elem</i> in page relative coordinates
* (i.e. independent of any scrolling).
* @private
* @author julrich
* @since 1.0
*/
function findCenter( elem ) {
var offset,
$elem = $( elem );
if ( isDocument($elem[0]) ) {
offset = {left: 0, top: 0};
}
else {
offset = $elem.offset();
}
return {
x: offset.left + $elem.outerWidth() / 2,
y: offset.top + $elem.outerHeight() / 2
};
}
/**
* Converts page relative coordinates into client relative coordinates.
* @param {Numeric|Object} x - Either the x coordinate of the page relative coordinates or
* an object with the properties <code>pageX</code> and <code>pageY</code> representing page
* relative coordinates.
* @param {Numeric} [y] - If <i>x</i> is numeric (i.e. the x coordinate of page relative coordinates),
* then this is the y coordinate. If <i>x</i> is an object, this parameter is skipped.
* @param {DOM Document} [docRel] - Optional DOM document object used to calculate the client relative
* coordinates. The page relative coordinates are interpreted as being relative to that document and
* the scroll position of that document is used to calculate the client relative coordinates.
* By default, <code>document</code> is used.
* @returns {Object} an object representing the client relative coordinates corresponding to the
* given page relative coordinates. The object either provides the properties <code>x</code> and
* <code>y</code> when <i>x</i> and <i>y</i> were given as arguments, or <code>clientX</code>
* and <code>clientY</code> when the parameter <i>x</i> was given as an object (see above).
* @private
* @author julrich
* @since 1.0
*/
function pageToClientPos(x, y, docRel) {
var $document;
if ( isDocument(y) ) {
$document = $(y);
} else {
$document = $(docRel || document);
}
if (typeof x === "number" && typeof y === "number") {
return {
x: x - $document.scrollLeft(),
y: y - $document.scrollTop()
};
}
else if (typeof x === "object" && x.pageX && x.pageY) {
return {
clientX: x.pageX - $document.scrollLeft(),
clientY: x.pageY - $document.scrollTop()
};
}
}
/**
* Browser-independent implementation of <code>document.elementFromPoint()</code>.
*
* When run for the first time on a scrolled page, this function performs a check on how
* <code>document.elementFromPoint()</code> is implemented in the current browser. It stores
* the results in two static variables so that the check can be skipped for successive calls.
*
* @param {Numeric|Object} x - Either the x coordinate of client relative coordinates or an object
* with the properties <code>x</code> and <code>y</code> representing client relative coordinates.
* @param {Numeric} [y] - If <i>x</i> is numeric (i.e. the x coordinate of client relative coordinates),
* this is the y coordinate. If <i>x</i> is an object, this parameter is skipped.
* @param {DOM Document} [docRel] - Optional DOM document object
* @returns {DOM Element|Null}
* @private
* @author Nicolas Zeh (Basic idea), julrich
* @see http://www.zehnet.de/2010/11/19/document-elementfrompoint-a-jquery-solution/
* @since 1.0
*/
function elementAtPosition(x, y, docRel) {
var doc;
if ( isDocument(y) ) {
doc = y;
} else {
doc = docRel || document;
}
if(!doc.elementFromPoint) {
return null;
}
var clientX = x, clientY = y;
if (typeof x === "object" && (x.clientX || x.clientY)) {
clientX = x.clientX || 0 ;
clientY = x.clientY || 0;
}
if(elementAtPosition.prototype.check)
{
var sl, ele;
if ((sl = $(doc).scrollTop()) >0)
{
ele = doc.elementFromPoint(0, sl + $(window).height() -1);
if ( ele !== null && ele.tagName.toUpperCase() === 'HTML' ) { ele = null; }
elementAtPosition.prototype.nativeUsesRelative = ( ele === null );
}
else if((sl = $(doc).scrollLeft()) >0)
{
ele = doc.elementFromPoint(sl + $(window).width() -1, 0);
if ( ele !== null && ele.tagName.toUpperCase() === 'HTML' ) { ele = null; }
elementAtPosition.prototype.nativeUsesRelative = ( ele === null );
}
elementAtPosition.prototype.check = (sl<=0); // Check was not meaningful because we were at scroll position 0
}
if(!elementAtPosition.prototype.nativeUsesRelative)
{
clientX += $(doc).scrollLeft();
clientY += $(doc).scrollTop();
}
return doc.elementFromPoint(clientX,clientY);
}
// Default values for the check variables
elementAtPosition.prototype.check = true;
elementAtPosition.prototype.nativeUsesRelative = true;
/**
* Informs the rest of the world that the drag is finished.
* @param {DOM Element} ele - The element which was dragged.
* @param {Object} [options] - The drag options.
* @fires simulate-drag
* @private
* @author julrich
* @since 1.0
*/
function dragFinished(ele, options) {
var opts = options || {};
$(ele).trigger({type: "simulate-drag"});
if ($.isFunction(opts.callback)) {
opts.callback.apply(ele);
}
}
/**
* Generates a series of <code>mousemove</code> events for a drag.
* @param {Object} self - The simulate object.
* @param {DOM Element} ele - The element which is dragged.
* @param {Object} start - The start coordinates of the drag, represented using the properties
* <code>x</code> and <code>y</code>.
* @param {Object} drag - The distance to be dragged, represented using the properties <code>dx</code>
* and <code>dy</code>.
* @param {Object} options - The drag options. Must have the property <code>interpolation</code>
* containing the interpolation options (<code>stepWidth</code>, <code>stepCount</code>, etc.).
* @requires eventTarget
* @requires now()
* @private
* @author julrich
* @since 1.0
*/
function interpolatedEvents(self, ele, start, drag, options) {
var targetDoc = selectFirstMatch([ele, ele.ownerDocument], isDocument) || document,
interpolOptions = options.interpolation,
dragDistance = Math.sqrt(Math.pow(drag.dx,2) + Math.pow(drag.dy,2)), // sqrt(a^2 + b^2)
stepWidth, stepCount, stepVector;
if (interpolOptions.stepWidth) {
stepWidth = parseInt(interpolOptions.stepWidth, 10);
stepCount = Math.floor(dragDistance / stepWidth)-1;
var stepScale = stepWidth / dragDistance;
stepVector = {x: drag.dx*stepScale, y: drag.dy*stepScale };
}
else {
stepCount = parseInt(interpolOptions.stepCount, 10);
stepWidth = dragDistance / (stepCount+1);
stepVector = {x: drag.dx/(stepCount+1), y: drag.dy/(stepCount+1)};
}
var coords = $.extend({},start);
/**
* Calculates the effective coordinates for one <code>mousemove</code> event and fires the event.
* @requires eventTarget
* @requires targetDoc
* @requires coords
* @requires stepVector
* @requires interpolOptions
* @fires mousemove
* @inner
* @author julrich
* @since 1.0
*/
function interpolationStep() {
coords.x += stepVector.x;
coords.y += stepVector.y;
var effectiveCoords = {pageX: coords.x, pageY: coords.y};
if (interpolOptions.shaky && (interpolOptions.shaky === true || !isNaN(parseInt(interpolOptions.shaky,10)) )) {
var amplitude = (interpolOptions.shaky === true)? 1 : parseInt(interpolOptions.shaky,10);
effectiveCoords.pageX += Math.floor(Math.random()*(2*amplitude+1)-amplitude);
effectiveCoords.pageY += Math.floor(Math.random()*(2*amplitude+1)-amplitude);
}
var clientCoord = pageToClientPos(effectiveCoords, targetDoc),
eventTarget = elementAtPosition(clientCoord, targetDoc) || ele;
self.simulateEvent( eventTarget, "mousemove", {pageX: Math.round(effectiveCoords.pageX), pageY: Math.round(effectiveCoords.pageY)});
}
var lastTime;
/**
* Performs one interpolation step (i.e. cares about firing the event) and then sleeps for
* <code>stepDelay</code> milliseconds.
* @requires lastTime
* @requires stepDelay
* @requires step
* @requires ele
* @requires eventTarget
* @reuiqre targetDoc
* @requires start
* @requires drag
* @requires now()
* @inner
* @author julrich
* @since 1.0
*/
function stepAndSleep() {
var timeElapsed = now() - lastTime; // Work-around for Firefox & IE "bug": setTimeout can fire before the timeout
if (timeElapsed >= stepDelay) {
if (step < stepCount) {
interpolationStep();
step += 1;
lastTime = now();
setTimeout(stepAndSleep, stepDelay);
}
else {
var pageCoord = {pageX: Math.round(start.x+drag.dx), pageY: Math.round(start.y+drag.dy)},
clientCoord = pageToClientPos(pageCoord, targetDoc),
eventTarget = elementAtPosition(clientCoord, targetDoc) || ele;
self.simulateEvent( eventTarget, "mousemove", pageCoord);
dragFinished(ele, options);
}
}
else {
setTimeout(stepAndSleep, stepDelay - timeElapsed);
}
}
if ( (!interpolOptions.stepDelay && !interpolOptions.duration) || ((interpolOptions.stepDelay <= 0) && (interpolOptions.duration <= 0)) ) {
// Trigger as fast as possible
for (var i=0; i < stepCount; i+=1) {
interpolationStep();
}
var pageCoord = {pageX: Math.round(start.x+drag.dx), pageY: Math.round(start.y+drag.dy)},
clientCoord = pageToClientPos(pageCoord, targetDoc),
eventTarget = elementAtPosition(clientCoord, targetDoc) || ele;
self.simulateEvent( eventTarget, "mousemove", pageCoord);
dragFinished(ele, options);
}
else {
var stepDelay = parseInt(interpolOptions.stepDelay,10) || Math.ceil(parseInt(interpolOptions.duration,10) / (stepCount+1));
var step = 0;
lastTime = now();
setTimeout(stepAndSleep, stepDelay);
}
}
/**
* @returns {Object|undefined} an object containing information about the currently active drag
* or <code>undefined</code> when there is no active drag.
* The returned object contains the following properties:
* <ul>
* <li><code>dragElement</code>: the dragged element</li>
* <li><code>dragStart</code>: object with the properties <code>x</code> and <code>y</code>
* representing the page relative start coordinates of the drag</li>
* <li><code>dragDistance</code>: object with the properties <code>x</code> and <code>y</code>
* representing the distance of the drag in x and y direction</li>
* </ul>
* @public
* @author julrich
* @since 1.0
*/
$.simulate.activeDrag = function() {
if (!$.simulate._activeDrag) {
return undefined;
}
return $.extend(true,{},$.simulate._activeDrag);
};
$.extend( $.simulate.prototype,
/**
* @lends $.simulate.prototype
*/
{
/**
* Simulates a drag.
*
* @see https://github.com/j-ulrich/jquery-simulate-ext/blob/master/doc/drag-n-drop.md
* @public
* @author julrich
* @since 1.0
*/
simulateDrag: function() {
var self = this,
ele = self.target,
options = $.extend({
dx: 0,
dy: 0,
dragTarget: undefined,
clickToDrag: false,
eventProps: {},
interpolation: {
stepWidth: 0,
stepCount: 0,
stepDelay: 0,
duration: 0,
shaky: false
},
callback: undefined
}, this.options);
var start,
continueDrag = ($.simulate._activeDrag && $.simulate._activeDrag.dragElement === ele);
if (continueDrag) {
start = $.simulate._activeDrag.dragStart;
}
else {
start = findCenter( ele );
}
var x = Math.round( start.x ),
y = Math.round( start.y ),
coord = { pageX: x, pageY: y },
dx,
dy;
if (options.dragTarget) {
var end = findCenter(options.dragTarget);
dx = Math.round(end.x - start.x);
dy = Math.round(end.y - start.y);
}
else {
dx = options.dx || 0;
dy = options.dy || 0;
}
if (continueDrag) {
// We just continue to move the dragged element
$.simulate._activeDrag.dragDistance.x += dx;
$.simulate._activeDrag.dragDistance.y += dy;
coord = { pageX: Math.round(x + $.simulate._activeDrag.dragDistance.x) , pageY: Math.round(y + $.simulate._activeDrag.dragDistance.y) };
}
else {
if ($.simulate._activeDrag) {
// Drop before starting a new drag
$($.simulate._activeDrag.dragElement).simulate( "drop" );
}
// We start a new drag
$.extend(options.eventProps, coord);
self.simulateEvent( ele, "mousedown", options.eventProps );
if (options.clickToDrag === true) {
self.simulateEvent( ele, "mouseup", options.eventProps );
self.simulateEvent( ele, "click", options.eventProps );
}
$(ele).add(ele.ownerDocument).one('mouseup', function() {
$.simulate._activeDrag = undefined;
});
$.extend($.simulate, {
_activeDrag: {
dragElement: ele,
dragStart: { x: x, y: y },
dragDistance: { x: dx, y: dy }
}
});
coord = { pageX: Math.round(x + dx), pageY: Math.round(y + dy) };
}
if (dx !== 0 || dy !== 0) {
if ( options.interpolation && (options.interpolation.stepCount || options.interpolation.stepWidth) ) {
interpolatedEvents(self, ele, {x: x, y: y}, {dx: dx, dy: dy}, options);
}
else {
var targetDoc = selectFirstMatch([ele, ele.ownerDocument], isDocument) || document,
clientCoord = pageToClientPos(coord, targetDoc),
eventTarget = elementAtPosition(clientCoord, targetDoc) || ele;
$.extend(options.eventProps, coord);
self.simulateEvent( eventTarget, "mousemove", options.eventProps );
dragFinished(ele, options);
}
}
else {
dragFinished(ele, options);
}
},
/**
* Simulates a drop.
*
* @see https://github.com/j-ulrich/jquery-simulate-ext/blob/master/doc/drag-n-drop.md
* @public
* @author julrich
* @since 1.0
*/
simulateDrop: function() {
var self = this,
ele = this.target,
activeDrag = $.simulate._activeDrag,
options = $.extend({
clickToDrop: false,
eventProps: {},
callback: undefined
}, self.options),
moveBeforeDrop = true,
center = findCenter( ele ),
x = Math.round( center.x ),
y = Math.round( center.y ),
coord = { pageX: x, pageY: y },
targetDoc = ( (activeDrag)? selectFirstMatch([activeDrag.dragElement, activeDrag.dragElement.ownerDocument], isDocument) : selectFirstMatch([ele, ele.ownerDocument], isDocument) ) || document,
clientCoord = pageToClientPos(coord, targetDoc),
eventTarget = elementAtPosition(clientCoord, targetDoc);
if (activeDrag && (activeDrag.dragElement === ele || isDocument(ele))) {
// We already moved the mouse during the drag so we just simulate the drop on the end position
x = Math.round(activeDrag.dragStart.x + activeDrag.dragDistance.x);
y = Math.round(activeDrag.dragStart.y + activeDrag.dragDistance.y);
coord = { pageX: x, pageY: y };
clientCoord = pageToClientPos(coord, targetDoc);
eventTarget = elementAtPosition(clientCoord, targetDoc);
moveBeforeDrop = false;
}
if (!eventTarget) {
eventTarget = (activeDrag)? activeDrag.dragElement : ele;
}
$.extend(options.eventProps, coord);
if (moveBeforeDrop === true) {
// Else we assume the drop should happen on target, so we move there
self.simulateEvent( eventTarget, "mousemove", options.eventProps );
}
if (options.clickToDrop) {
self.simulateEvent( eventTarget, "mousedown", options.eventProps );
}
this.simulateEvent( eventTarget, "mouseup", options.eventProps );
if (options.clickToDrop) {
self.simulateEvent( eventTarget, "click", options.eventProps );
}
$.simulate._activeDrag = undefined;
$(eventTarget).trigger({type: "simulate-drop"});
if ($.isFunction(options.callback)) {
options.callback.apply(eventTarget);
}
},
/**
* Simulates a drag followed by drop.
*
* @see https://github.com/j-ulrich/jquery-simulate-ext/blob/master/doc/drag-n-drop.md
* @public
* @author julrich
* @since 1.0
*/
simulateDragNDrop: function() {
var self = this,
ele = this.target,
options = $.extend({
dragTarget: undefined,
dropTarget: undefined
}, self.options),
// If there is a dragTarget or dx/dy, then we drag there and simulate an independent drop on dropTarget or ele
dropEle = ((options.dragTarget || options.dx || options.dy)? options.dropTarget : ele) || ele;
/*
dx = (options.dropTarget)? 0 : (options.dx || 0),
dy = (options.dropTarget)? 0 : (options.dy || 0),
dragDistance = { dx: dx, dy: dy };
$.extend(options, dragDistance);
*/
$(ele).simulate( "drag", $.extend({},options,{
// If there is no dragTarget, no dx and no dy, we drag onto the dropTarget directly
dragTarget: options.dragTarget || ((options.dx || options.dy)?undefined:options.dropTarget),
callback: function() {
$(dropEle).simulate( "drop", options );
}
}));
}
});
}(jQuery));
/*jshint camelcase:true, plusplus:true, forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, unused:true, curly:true, browser:true, devel:true, maxerr:100, white:false, onevar:false */
/*global jQuery:true $:true bililiteRange:true */
/* jQuery Simulate Key-Sequence Plugin 1.3.0
* http://github.com/j-ulrich/jquery-simulate-ext
*
* Copyright (c) 2014 Jochen Ulrich
* Licensed under the MIT license (MIT-LICENSE.txt).
*
* The plugin is an extension and modification of the jQuery sendkeys plugin by Daniel Wachsstock.
* Therefore, the original copyright notice and license follow below.
*/
// insert characters in a textarea or text input field
// special characters are enclosed in {}; use {{} for the { character itself
// documentation: http://bililite.com/blog/2008/08/20/the-fnsendkeys-plugin/
// Version: 2.0
// Copyright (c) 2010 Daniel Wachsstock
// MIT license:
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
;(function($, undefined){
"use strict";
$.simulate.prototype.quirks = $.simulate.prototype.quirks || {};
$.extend($.simulate.prototype.quirks,
/**
* @lends $.simulate.prototype.quirks
*/
{
/**
* When simulating with delay in non-input elements,
* all spaces are simulated at the end of the sequence instead
* of the correct position.
* @see {@link https://github.com/j-ulrich/jquery-simulate-ext/issues/6|issues #6}
*/
delayedSpacesInNonInputGlitchToEnd: undefined
});
$.extend($.simulate.prototype,
/**
* @lends $.simulate.prototype
*/
{
/**
* Simulates sequencial key strokes.
*
* @see https://github.com/j-ulrich/jquery-simulate-ext/blob/master/doc/key-sequence.md
* @public
* @author Daniel Wachsstock, julrich
* @since 1.0
*/
simulateKeySequence: function() {
var target = this.target,
$target = $(target),
opts = $.extend({
sequence: "",
triggerKeyEvents: true,
eventProps: {},
delay: 0,
callback: undefined
}, this.options),
sequence = opts.sequence;
opts.delay = parseInt(opts.delay,10);
var localkeys = {};
// Fix for #6 (https://github.com/j-ulrich/jquery-simulate-ext/issues/6)
if ($.simulate.prototype.quirks.delayedSpacesInNonInputGlitchToEnd && !$target.is('input,textarea')) {
$.extend(localkeys, {
' ': function(rng, s, opts) {
var internalOpts = $.extend({}, opts, {
triggerKeyEvents: false,
delay: 0,
callback: undefined
});
$.simulate.prototype.simulateKeySequence.defaults.simplechar(rng, '\xA0', internalOpts);
$.simulate.prototype.simulateKeySequence.defaults['{leftarrow}'](rng, s, internalOpts);
$.simulate.prototype.simulateKeySequence.defaults.simplechar(rng, s, opts);
$.simulate.prototype.simulateKeySequence.defaults['{del}'](rng, s, internalOpts);
}
});
}
$.extend(localkeys, opts, $target.data('simulate-keySequence')); // allow for element-specific key functions
// most elements to not keep track of their selection when they lose focus, so we have to do it for them
var rng = $.data (target, 'simulate-keySequence.selection');
if (!rng){
rng = bililiteRange(target).bounds('selection');
$.data(target, 'simulate-keySequence.selection', rng);
$target.bind('mouseup.simulate-keySequence', function(){
// we have to update the saved range. The routines here update the bounds with each press, but actual keypresses and mouseclicks do not
$.data(target, 'simulate-keySequence.selection').bounds('selection');
}).bind('keyup.simulate-keySequence', function(evt){
// restore the selection if we got here with a tab (a click should select what was clicked on)
if (evt.which === 9){
// there's a flash of selection when we restore the focus, but I don't know how to avoid that.
$.data(target, 'simulate-keySequence.selection').select();
}else{
$.data(target, 'simulate-keySequence.selection').bounds('selection');
}
});
}
$target.focus();
if (typeof sequence === 'undefined') { // no string, so we just set up the event handlers
return;
}
sequence = sequence.replace(/\n/g, '{enter}'); // turn line feeds into explicit break insertions
/**
* Informs the rest of the world that the sequences is finished.
* @fires simulate-keySequence
* @requires target
* @requires sequence
* @requires opts
* @inner
* @author julrich
* @since 1.0
*/
function sequenceFinished() {
$target.trigger({type: 'simulate-keySequence', sequence: sequence});
if ($.isFunction(opts.callback)) {
opts.callback.apply(target, [{
sequence: sequence
}]);
}
}
/**
* Simulates the key stroke for one character (or special sequence) and sleeps for
* <code>opts.delay</code> milliseconds.
* @requires lastTime
* @requires now()
* @requires tokenRegExp
* @requires opts
* @requires rng
* @inner
* @author julrich
* @since 1.0
*/
function processNextToken() {
var timeElapsed = now() - lastTime; // Work-around for Firefox "bug": setTimeout can fire before the timeout
if (timeElapsed >= opts.delay) {
var match = tokenRegExp.exec(sequence);
if ( match !== null ) {
var s = match[0];
(localkeys[s] || $.simulate.prototype.simulateKeySequence.defaults[s] || $.simulate.prototype.simulateKeySequence.defaults.simplechar)(rng, s, opts);
setTimeout(processNextToken, opts.delay);
}
else {
sequenceFinished();
}
lastTime = now();
}
else {
setTimeout(processNextToken, opts.delay - timeElapsed);
}
}
if (!opts.delay || opts.delay <= 0) {
// Run as fast as possible
sequence.replace(/\{[^}]*\}|[^{]+/g, function(s){
(localkeys[s] || $.simulate.prototype.simulateKeySequence.defaults[s] || $.simulate.prototype.simulateKeySequence.defaults.simplechar)(rng, s, opts);
});
sequenceFinished();
}
else {
var tokenRegExp = /\{[^}]*\}|[^{]/g; // This matches curly bracket expressions or single characters
var now = Date.now || function() { return new Date().getTime(); },
lastTime = now();
processNextToken();
}
}
});
$.extend($.simulate.prototype.simulateKeySequence.prototype,
/**
* @lends $.simulate.prototype.simulateKeySequence.prototype
*/
{
/**
* Maps special character char codes to IE key codes (covers IE and Webkit)
* @author julrich
* @since 1.0
*/
IEKeyCodeTable: {
33: 49, // ! -> 1
64: 50, // @ -> 2
35: 51, // # -> 3
36: 52, // $ -> 4
37: 53, // % -> 5
94: 54, // ^ -> 6
38: 55, // & -> 7
42: 56, // * -> 8
40: 57, // ( -> 9
41: 48, // ) -> 0
59: 186, // ; -> 186
58: 186, // : -> 186
61: 187, // = -> 187
43: 187, // + -> 187
44: 188, // , -> 188
60: 188, // < -> 188
45: 189, // - -> 189
95: 189, // _ -> 189
46: 190, // . -> 190
62: 190, // > -> 190
47: 191, // / -> 191
63: 191, // ? -> 191
96: 192, // ` -> 192
126: 192, // ~ -> 192
91: 219, // [ -> 219
123: 219, // { -> 219
92: 220, // \ -> 220
124: 220, // | -> 220
93: 221, // ] -> 221
125: 221, // } -> 221
39: 222, // ' -> 222
34: 222 // " -> 222
},
/**
* Tries to convert character codes to key codes.
* @param {Numeric} character - A character code
* @returns {Numeric} The key code corresponding to the given character code,
* based on the key code table of InternetExplorer. If no corresponding key code
* could be found (which will be the case for all special characters except the common
* ones), the character code itself is returned. However, <code>keyCode === charCode</code>
* does not imply that no key code was found because some key codes are identical to the
* character codes (e.g. for uppercase characters).
* @requires $.simulate.prototype.simulateKeySequence.prototype.IEKeyCodeTable
* @see $.simulate.prototype.simulateKeySequence.prototype.IEKeyCodeTable
* @author julrich
* @since 1.0
*/
charToKeyCode: function(character) {
var specialKeyCodeTable = $.simulate.prototype.simulateKeySequence.prototype.IEKeyCodeTable;
var charCode = character.charCodeAt(0);
if (charCode >= 64 && charCode <= 90 || charCode >= 48 && charCode <= 57) {
// A-Z and 0-9
return charCode;
}
else if (charCode >= 97 && charCode <= 122) {
// a-z -> A-Z
return character.toUpperCase().charCodeAt(0);
}
else if (specialKeyCodeTable[charCode] !== undefined) {
return specialKeyCodeTable[charCode];
}
else {
return charCode;
}
}
});
// add the functions publicly so they can be overridden
$.simulate.prototype.simulateKeySequence.defaults = {
/**
* Simulates key strokes of "normal" characters (i.e. non-special sequences).
* @param {Object} rng - bililiteRange object of the simulation target element.
* @param {String} s - String of (simple) characters to be simulated.
* @param {Object} opts - The key-sequence options.
* @author Daniel Wachsstock, julrich
* @since 1.0
*/
simplechar: function (rng, s, opts){
rng.text(s, 'end');
if (opts.triggerKeyEvents) {
for (var i =0; i < s.length; i += 1){
var charCode = s.charCodeAt(i);
var keyCode = $.simulate.prototype.simulateKeySequence.prototype.charToKeyCode(s.charAt(i));
// a bit of cheating: rng._el is the element associated with rng.
$(rng._el).simulate('keydown', $.extend({}, opts.eventProps, {keyCode: keyCode}));
$(rng._el).simulate('keypress', $.extend({}, opts.eventProps,{keyCode: charCode, which: charCode, charCode: charCode}));
$(rng._el).simulate('keyup', $.extend({}, opts.eventProps, {keyCode: keyCode}));
}
}
},
/**
* Simulates key strokes of a curly opening bracket.
* @param {Object} rng - bililiteRange object of the simulation target element.
* @param {String} s - Ignored.
* @param {Object} opts - The key-sequence options.
* @author Daniel Wachsstock, julrich
* @since 1.0
*/
'{{}': function (rng, s, opts){
$.simulate.prototype.simulateKeySequence.defaults.simplechar(rng, '{', opts);
},
/**
* Simulates hitting the enter button.
* @param {Object} rng - bililiteRange object of the simulation target element.
* @param {String} s - Ignored.
* @param {Object} opts - The key-sequence options.
* @author Daniel Wachsstock, julrich
* @since 1.0
*/
'{enter}': function (rng, s, opts){
rng.insertEOL();
rng.select();
if (opts.triggerKeyEvents === true) {
$(rng._el).simulate('keydown', $.extend({}, opts.eventProps, {keyCode: 13}));
$(rng._el).simulate('keypress', $.extend({}, opts.eventProps, {keyCode: 13, which: 13, charCode: 13}));
$(rng._el).simulate('keyup', $.extend({}, opts.eventProps, {keyCode: 13}));
}
},
/**
* Simulates hitting the backspace button.
* @param {Object} rng - bililiteRange object of the simulation target element.
* @param {String} s - Ignored.
* @param {Object} opts - The key-sequence options.
* @author Daniel Wachsstock, julrich
* @since 1.0
*/
'{backspace}': function (rng, s, opts){
var b = rng.bounds();
if (b[0] === b[1]) { rng.bounds([b[0]-1, b[0]]); } // no characters selected; it's just an insertion point. Remove the previous character
rng.text('', 'end'); // delete the characters and update the selection
if (opts.triggerKeyEvents === true) {
$(rng._el).simulate('keydown', $.extend({}, opts.eventProps, {keyCode: 8}));
$(rng._el).simulate('keyup', $.extend({}, opts.eventProps, {keyCode: 8}));
}
},
/**
* Simulates hitting the delete button.
* @param {Object} rng - bililiteRange object of the simulation target element.
* @param {String} s - Ignored.
* @param {Object} opts - The key-sequence options.
* @author Daniel Wachsstock, julrich
* @since 1.0
*/
'{del}': function (rng, s, opts){
var b = rng.bounds();
if (b[0] === b[1]) { rng.bounds([b[0], b[0]+1]); } // no characters selected; it's just an insertion point. Remove the next character
rng.text('', 'end'); // delete the characters and update the selection
if (opts.triggerKeyEvents === true) {
$(rng._el).simulate('keydown', $.extend({}, opts.eventProps, {keyCode: 46}));
$(rng._el).simulate('keyup', $.extend({}, opts.eventProps, {keyCode: 46}));
}
},
/**
* Simulates hitting the right arrow button.
* @param {Object} rng - bililiteRange object of the simulation target element.
* @param {String} s - Ignored.
* @param {Object} opts - The key-sequence options.
* @author Daniel Wachsstock, julrich
* @since 1.0
*/
'{rightarrow}': function (rng, s, opts){
var b = rng.bounds();
if (b[0] === b[1]) { b[1] += 1; } // no characters selected; it's just an insertion point. Move to the right
rng.bounds([b[1], b[1]]).select();
if (opts.triggerKeyEvents === true) {
$(rng._el).simulate('keydown', $.extend({}, opts.eventProps, {keyCode: 39}));
$(rng._el).simulate('keyup', $.extend({}, opts.eventProps, {keyCode: 39}));
}
},
/**
* Simulates hitting the left arrow button.
* @param {Object} rng - bililiteRange object of the simulation target element.
* @param {String} s - Ignored.
* @param {Object} opts - The key-sequence options.
* @author Daniel Wachsstock, julrich
* @since 1.0
*/
'{leftarrow}': function (rng, s, opts){
var b = rng.bounds();
if (b[0] === b[1]) { b[0] -= 1; } // no characters selected; it's just an insertion point. Move to the left
rng.bounds([b[0], b[0]]).select();
if (opts.triggerKeyEvents === true) {
$(rng._el).simulate('keydown', $.extend({}, opts.eventProps, {keyCode: 37}));
$(rng._el).simulate('keyup', $.extend({}, opts.eventProps, {keyCode: 37}));
}
},
/**
* Selects all characters in the target element.
* @param {Object} rng - bililiteRange object of the simulation target element.
* @author Daniel Wachsstock, julrich
* @since 1.0
*/
'{selectall}' : function (rng){
rng.bounds('all').select();
}
};
//####### Quirk detection #######
if ($.simulate.ext_disableQuirkDetection !== true) { // Fixes issue #9 (https://github.com/j-ulrich/jquery-simulate-ext/issues/9)
$(document).ready(function() {
// delayedSpacesInNonInputGlitchToEnd
// See issues #6 (https://github.com/j-ulrich/jquery-simulate-ext/issues/6)
/* Append a div to the document (bililiteRange needs the element to be in the document), simulate
* a delayed sequence containing a space in the middle and check if the space moves to the end.
*/
var $testDiv = $('<div/>').css({height: 1, width: 1, position: 'absolute', left: -1000, top: -1000}).appendTo('body');
$testDiv.simulate('key-sequence', {sequence: '\xA0 \xA0', delay:1, callback: function() {
$.simulate.prototype.quirks.delayedSpacesInNonInputGlitchToEnd = ($testDiv.text() === '\xA0\xA0 ');
$testDiv.remove();
}});
});
}
})(jQuery);
/*jshint camelcase:true, plusplus:true, forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, unused:true, curly:true, browser:true, devel:true, maxerr:100, white:false, onevar:false */
/*global jQuery:true $:true */
/* jQuery Simulate Key-Combo Plugin 1.3.0
* http://github.com/j-ulrich/jquery-simulate-ext
*
* Copyright (c) 2014 Jochen Ulrich
* Licensed under the MIT license (MIT-LICENSE.txt).
*/
/**
*
* For details about key events, key codes, char codes etc. see http://unixpapa.com/js/key.html
*/
;(function($,undefined) {
"use strict";
/**
* Key codes of special keys.
* @private
* @author julrich
* @since 1.3.0
*/
var SpecialKeyCodes = {
// Modifier Keys
SHIFT: 16,
CONTROL: 17,
ALTERNATIVE: 18,
META: 91,
// Arrow Keys
LEFT_ARROW: 37,
UP_ARROW: 38,
RIGHT_ARROW: 39,
DOWN_ARROW: 40,
// Function Keys
F1: 112,
F2: 113,
F3: 114,
F4: 115,
F5: 116,
F6: 117,
F7: 118,
F8: 119,
F9: 120,
F10: 121,
F11: 122,
F12: 123,
// Other
ENTER: 13,
TABULATOR: 9,
ESCAPE: 27,
BACKSPACE: 8,
INSERT: 45,
DELETE: 46,
HOME: 36,
END: 35,
PAGE_UP: 33,
PAGE_DOWN: 34,
};
// SpecialKeyCode aliases
SpecialKeyCodes.CTRL = SpecialKeyCodes.CONTROL;
SpecialKeyCodes.ALT = SpecialKeyCodes.ALTERNATIVE;
SpecialKeyCodes.COMMAND = SpecialKeyCodes.META;
SpecialKeyCodes.TAB = SpecialKeyCodes.TABULATOR;
SpecialKeyCodes.ESC = SpecialKeyCodes.ESCAPE;
$.extend( $.simulate.prototype,
/**
* @lends $.simulate.prototype
*/
{
/**
* Simulates simultaneous key presses
*
* @see https://github.com/j-ulrich/jquery-simulate-ext/blob/master/doc/key-combo.md
* @public
* @author julrich
* @since 1.0
*/
simulateKeyCombo: function() {
var $target = $(this.target),
options = $.extend({
combo: "",
eventProps: {},
eventsOnly: false
}, this.options),
combo = options.combo,
comboSplit = combo.split(/(\+)/),
plusExpected = false,
holdKeys = [],
i;
if (combo.length === 0) {
return;
}
// Remove empty parts
comboSplit = $.grep(comboSplit, function(part) {
return (part !== "");
});
for (i=0; i < comboSplit.length; i+=1) {
var key = comboSplit[i],
keyLowered = key.toLowerCase(),
keySpecial = key.toUpperCase().replace('-','_');
if (plusExpected) {
if (key !== "+") {
throw 'Syntax error: expected "+"';
}
else {
plusExpected = false;
}
}
else {
var keyCode;
if ( key.length > 1) {
// Assume a special key
keyCode = SpecialKeyCodes[keySpecial];
if (keyCode === undefined) {
throw 'Syntax error: unknown special key "'+key+'" (forgot "+" between keys?)';
}
switch (keyCode) {
case SpecialKeyCodes.CONTROL:
case SpecialKeyCodes.ALT:
case SpecialKeyCodes.SHIFT:
case SpecialKeyCodes.META:
options.eventProps[keyLowered+"Key"] = true;
break;
}
holdKeys.unshift(keyCode);
options.eventProps.keyCode = keyCode;
options.eventProps.which = keyCode;
options.eventProps.charCode = 0;
$target.simulate("keydown", options.eventProps);
}
else {
// "Normal" key
keyCode = $.simulate.prototype.simulateKeySequence.prototype.charToKeyCode(key);
holdKeys.unshift(keyCode);
options.eventProps.keyCode = keyCode;
options.eventProps.which = keyCode;
options.eventProps.charCode = undefined;
$target.simulate("keydown", options.eventProps);
if (options.eventProps.shiftKey) {
key = key.toUpperCase();
}
options.eventProps.keyCode = key.charCodeAt(0);
options.eventProps.charCode = options.eventProps.keyCode;
options.eventProps.which = options.eventProps.keyCode;
$target.simulate("keypress", options.eventProps);
if (options.eventsOnly !== true && !options.eventProps.ctrlKey && !options.eventProps.altKey && !options.eventProps.metaKey) {
$target.simulate('key-sequence', {sequence: key, triggerKeyEvents: false});
}
}
plusExpected = true;
}
}
if (!plusExpected) {
throw 'Syntax error: expected key (trailing "+"?)';
}
// Release keys
options.eventProps.charCode = undefined;
for (i=0; i < holdKeys.length; i+=1) {
options.eventProps.keyCode = holdKeys[i];
options.eventProps.which = holdKeys[i];
switch (options.eventProps.keyCode) {
case SpecialKeyCodes.ALT: options.eventProps.altKey = false; break;
case SpecialKeyCodes.SHIFT: options.eventProps.shiftKey = false; break;
case SpecialKeyCodes.CONTROL: options.eventProps.ctrlKey = false; break;
case SpecialKeyCodes.META: options.eventProps.metaKey = false; break;
default:
break;
}
$target.simulate("keyup", options.eventProps);
}
}
});
}(jQuery));
|
export default {
routes: [
{ path: '/', breadcrumb: "首页", component: './index.js' },
{ path: '/goods/list', breadcrumb: "商品列表", component: './index.js' },
],
};
|
import React from 'react'
import { Row, Col,Card, Button,Select,Divider, Message, Radio,TextArea, Form, Input, Cascader,DatePicker} from 'antd';
import {provinces, cities, areas} from '../../constants/Area'
import {fetch} from '../../api/tools'
//出险记录添加
const Option= Select.Option;
const FormItem = Form.Item;
class CarInsuranceRecord extends React.Component {
state = {
formLayout: 'horizontal',
};
onChange = (value) =>{
// console.log(value)
}
handleSubmit = (e) => {
e && e.preventDefault();
/*this.props.form.setFieldsValue({
carNumber: this.state.carNumber,
carType: this.state.carType,
inspectionUser: this.state.inspectionUser,
inspectionDate: this.state.inspectionDate
});*/
this.props.form.validateFields((err, values) => {
if (!err) {
// this.props.submit(values)
// console.log('年检信息: ', values);
const filesValues = {
...values,
'beginTime':values['beginTime'].format('YYYY-MM-DD HH:mm:ss'),
'endTime':values['endTime'].format('YYYY-MM-DD HH:mm:ss'),
'insuranceTime':values['insuranceTime'].format('YYYY-MM-DD HH:mm:ss'),
};
/*alert(filesValues.commercialBeginTime+"--------"+filesValues.commercialEndTime);
return;*/
fetch('post','/chedui/zichan/carInsuranceRecord',filesValues).then(res=>{
if (res.code ===2000) {
Message.success('添加成功');
this.props.history.push('/app/car/CarInsuranceRecordList');
}
})
}
});
};
checkCardNo = (rule, value, callback) => {
if(value && !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)){
callback('请输入正确的管理员身份证号');
} else {
callback();
}
};
//校验手机号码
checkTel = (rule, value, callback)=>{
if(value && !(/^1\d{10}$/.test(value))){
callback('请输入正确的管理员手机号码')
}else{
callback();
}
};
getImgUrl = (type, url) => {
this.setState({[type]: url},()=>{
this.handleSubmit()
})
};
componentDidMount(){
const{ carNumber,carType} = this.props.match.params;
this.props.form.setFieldsValue({
carNumber:carNumber,
carType:carType
})
areas.forEach(area => {
const matchCity = cities.filter(city => city.code === area.cityCode)[0];
if (matchCity) {
matchCity.children = matchCity.children || [];
matchCity.children.push({
label: area.name,
value: area.name
});
}
});
cities.forEach(city => {
const matchProvince = provinces.filter(
province => province.code === city.provinceCode
)[0];
if (matchProvince) {
matchProvince.children = matchProvince.children || [];
matchProvince.children.push({
label: city.name,
value: city.name,
children: city.children
});
}
});
const options = provinces.map(province => ({
label: province.name,
value: province.name,
children: province.children
}));
this.setState({options: options})
}
render() {
const { getFieldDecorator} = this.props.form;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 8,
offset:0,
},
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 15,
offset:0,
},
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 15,
offset:11,
},
},
};
const {formLayout} = this.state;
const { TextArea } = Input;
return (
<div style={{background: 'white', padding: '26px 16px 16px',margin:'20px 0px'}}>
<Row><p style={{fontSize: '13px',fontWeight: '800'}}>出险记录</p></Row>
<Divider style={{margin: '10px 0'}}></Divider>
<Form onSubmit={this.handleSubmit} layout={formLayout}>
<Row>
<Col span={12}>
<FormItem
label="车牌号码"
{...formItemLayout}
>
{getFieldDecorator('carNumber', {
rules: [
{
required: true, message: '请输入车牌号码',
}
],
})(
<Input placeholder="请输入车牌号码" maxLength={50}/>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem
{...formItemLayout}
label="进厂时间"
>
{getFieldDecorator('beginTime', {
rules: [{
required:true,message:"请选择进厂时间"
}],
})(
<DatePicker placeholder={'请选择进厂时间'}/>
)}
</FormItem>
</Col>
</Row>
<Row>
<Col span={12}>
<FormItem
label="客户名称"
{...formItemLayout}
>
{getFieldDecorator('userName', {
rules: [{
required:true,message:"请输入客户名称"
}],
})(
<Input placeholder="请输入客户名称" maxLength={50}/>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem
label="修理厂地址"
{...formItemLayout}
>
{getFieldDecorator('maintainAddress', {
rules: [{
required:true,message:"请输入修理厂地址"
}],
})(
<Input placeholder="请输入修理厂地址" maxLength={50}/>
)}
</FormItem>
</Col>
</Row>
<Row>
<Col span={12}>
<FormItem
label="客户联系方式"
{...formItemLayout}
>
{getFieldDecorator('userTelephone', {
rules: [{
required:true,message:"请输入客户联系方式"
}],
})(
<Input placeholder="请输入客户联系方式" maxLength={50}/>
)}
</FormItem>
<FormItem
label="出险地址"
{...formItemLayout}
>
{getFieldDecorator('insuranceAddress', {
rules: [{
required:true,message:"请输入出险地址"
}],
})(
<Input placeholder="请输入出险地址" maxLength={50}/>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem
label="维修内容"
{...formItemLayout}
>
{getFieldDecorator('maintainRemark', {
rules: [{
required:true,message:"请输入维修内容"
}],
})(
<TextArea rows={5} placeholder={'请输入维修内容'} />
)}
</FormItem>
</Col>
</Row>
<Row>
<Col span={12}>
<FormItem
{...formItemLayout}
label="出险时间"
>
{getFieldDecorator('insuranceTime', {
rules: [{
required:true,message:"请选择出险时间"
}],
})(
<DatePicker placeholder={'请选择出险时间'}/>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem
label="维修状态"
{...formItemLayout}
>
{getFieldDecorator('maintainStatus', {
rules: [{
required:true,message:"请选择维修状态"
}],
})(
<Select dropdownMatchSelectWidth={false} allowClear={true} placeholder="请选择维修状态">
{maintainStatus.map((item,index)=>
<Option value={item.value} key={index}>{item.name}</Option>
)}
</Select>
)}
</FormItem>
</Col>
</Row>
<Row>
<Col span={12}>
<FormItem
label="理赔状态"
{...formItemLayout}
>
{getFieldDecorator('status', {
rules: [{
required:true,message:"请选择理赔状态"
}],
})(
<Select dropdownMatchSelectWidth={false} allowClear={true} placeholder="请选择理赔状态">
{status.map((item,index)=>
<Option value={item.value} key={index}>{item.name}</Option>
)}
</Select>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem
{...formItemLayout}
label="出厂日期"
>
{getFieldDecorator('endTime', {
rules: [{
required:true,message:"请选择出厂日期"
}],
})(
<DatePicker placeholder={'请选择出厂日期'}/>
)}
</FormItem>
</Col>
</Row>
<Row>
<Col span={12}>
<FormItem
label="己方金额"
{...formItemLayout}
>
{getFieldDecorator('money', {
rules: [{
required:true,message:"请输入己方金额"
}],
})(
<Input placeholder="请输入己方金额" maxLength={50}/>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem
label="订单状态"
{...formItemLayout}
>
{getFieldDecorator('maintainOrderStatus', {
rules: [{
required:true,message:"请选择订单状态"
}],
})(
<Select dropdownMatchSelectWidth={false} allowClear={true} placeholder="请选择订单状态">
{maintainOrderStatus.map((item,index)=>
<Option value={item.value} key={index}>{item.name}</Option>
)}
</Select>
)}
</FormItem>
</Col>
</Row>
<Row>
<Col span={12}>
<FormItem
label="第三方金额"
{...formItemLayout}
>
{getFieldDecorator('thirdPartyMoney', {
rules: [{
required:true,message:"请输入第三方金额"
}],
})(
<Input placeholder="请输入第三方金额" maxLength={50}/>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem
label="提车状态"
{...formItemLayout}
>
{getFieldDecorator('carStatus', {
rules: [{
required:true,message:"请选择提车状态"
}],
})(
<Select dropdownMatchSelectWidth={false} allowClear={true} placeholder="请选择提车状态">
{carStatus.map((item,index)=>
<Option value={item.value} key={index}>{item.name}</Option>
)}
</Select>
)}
</FormItem>
</Col>
</Row>
<Row>
<Col span={12}>
<FormItem
label="出险描述"
{...formItemLayout}
>
{getFieldDecorator('insuranceRemark', {
rules: [{
required:true,message:"请输入出险描述"
}],
})(
<TextArea rows={5} placeholder={'请输入出险描述'} />
)}
</FormItem>
</Col>
</Row>
<FormItem
{...tailFormItemLayout}
>
<Button type='primary' size='large' htmlType="submit">确认增加</Button>
</FormItem>
</Form>
</div>
)
}
}
const carStatus = [
{value:'0',name:'已提车'},
{value:'1',name:'未提车'}
]
const maintainStatus = [
{value:'0',name:'维修中'},
{value:'1',name:'已修好'}
]
const status = [
{value:'0',name:'未理赔'},
{value:'1',name:'已理赔'}
]
const maintainOrderStatus = [
{value:'0',name:'未结算'},
{value:'1',name:'已结算'},
{value:'2',name:'已确定'}
]
export default Form.create()(CarInsuranceRecord)
|
import React, { Component } from 'react';
import {convertSecondsToTimeObject} from "../util/convert";
import TimeDisplay from "./TimeDisplay";
export default class StopWatch extends Component {
state = {
currentTime: 0,
timerId: null,
timerRunning: false,
}
startTimer = () => {
let timerId = setInterval(this.tick, 1000);
this.setState({timerId, timerRunning: true,});
}
stopTimer = () => {
clearInterval(this.state.timerId);
this.setState({timerId: null, timerRunning: false});
}
logButtonPressed = () => {
this.props.stopwatchDone(this.state.currentTime);
this.setState({currentTime: 0});
}
resetTimer = () => {
this.stopTimer();
this.setState({currentTime: 0});
}
tick = () => {
let {currentTime} = this.state;
this.setState({currentTime: currentTime + 1});
}
buildStopwatchDisplay = ({hours, minutes, seconds}) => {
return (
<div className="timer-display">
<h3>{hours}:{minutes}:{seconds}</h3>
</div>
);
}
render() {
//press start - get the current time
//tick every second
// (Date.now() - startTime) / 1000 = number of seconds
let {startingValue} = this.props;
let {currentTime} = this.state;
return (
<div className="task-timer">
{/* <h3>{currentTime}</h3> */}
{/* <TimeDisplay currentTime={currentTime} editable={true} /> */}
<i class="fas fa-stopwatch"></i> Stopwatch
{this.buildStopwatchDisplay(convertSecondsToTimeObject(currentTime))}
<div className="timer-controls">
{!this.state.timerRunning ?
<div className="timer-control-container">
<button className="start-pause-button" onClick={this.startTimer}>Start</button>
<button className="start-pause-button" onClick={this.resetTimer}>Reset</button>
</div> :
<div className="timer-control-container">
<button className="start-pause-button" onClick={this.stopTimer}>Stop</button>
</div>
}
{
this.state.timerRunning ?
<h5>Press stop when you are done.</h5> :
<button className="log-button" onClick={this.logButtonPressed}>Log This</button>
}
</div>
</div>
);
}
}
|
exports.userModel = {
name: {required: true, type: 'string', encrypted: false},
email: {required: true, type: 'string', encrypted: true},
password: {required: true, type: 'string', encrypted: true},
};
|
/**
* @author xuyi 2018-09-05
*/
import { handleActions } from "redux-actions";
import cFetch from "./cFetch";
// 正在做异步请求还未响应的action
const isRequestAction = {};
// const asyncHandleActions = (...actions, initState) => {
// if (actions && Array.isArray(actions)) {
// const len = actions.length;
// const reducers = [];
// for (let i = 0; i < len ; i ++) {
// if (typeof ) {
// //
// }
// }
// }
// return new Error('new error');
// }
/**
* 根据method方法获取请求参数
* @param {*} method 请求的方法,分别为"GET","POST","PUT","DELETE","HEADER","OPTION"
* @param {*} param 请求的参数为Object
*/
const getRequestParams = (method, param) => {
switch (method) {
case "POST":
case "DELETE":
case "PUT":
return { body: param };
case "HEADER":
case "OPTION":
case "GET":
default:
return { params: param };
}
};
/**
* 创建是否可以重复请求的异步请求
* @param {*} url 请求url
* @param {*} dispatch store中的dispatch
* @param {*} actionType 异步请求的action type
* @param {*} params 异步请求的参数
* @param {*} repeat 是否可以重复请求
* @param {*} rj 请求异常的回调
*/
const createAsyncRequest = (
url,
dispatch,
actionType,
params = null,
repeat = true,
rj = err => null
) => {
const { type, pending, accept, reject } = actionType;
const flag = repeat || (!repeat && !isRequestAction[type]);
flag && dispatch({ type: pending });
!repeat ? (isRequestAction[type] = true) : null;
if (flag) {
return cFetch(url, params)
.then(result => {
dispatch({ type: accept, payload: result });
!repeat ? (isRequestAction[type] = false) : null;
return Promise.resolve(result);
})
.catch(errs => {
dispatch({ type: reject });
!repeat ? (isRequestAction[type] = false) : null;
rj && rj(errs);
return Promise.reject(errs);
});
}
};
/**
* 创建异步请求的action type
* @param {*} actionType 异步请求的action type
*/
const createAsyncActionType = actionType => {
return {
type: actionType,
pending: `${actionType}_pending`,
accept: `${actionType}_accept`,
reject: `${actionType}_reject`
};
};
/**
* 创建异步请求action的公共函数
* @param {*} url 异步请求的url
* @param {*} actionType 异步请求的action type,需通过createAsyncActionType函数创建
* @param {*} method 异步请求的方法,分别为"GET","POST","PUT","DELETE","HEADER","OPTION",默认值为"GET"
* @param {*} repeat 是否可以重复请求,true为可以重复请求,false为不能重复请求
* @param {*} headers 请求时发送的头部信息,默认值为{}
*/
const createAsyncAction = (
url,
actionType,
method = "GET",
repeat = true,
headers = {}
) => (params = null, rj = err => null) => dispatch => {
const { type, pending, accept, reject } = actionType;
const param = params ? getRequestParams(method, params) : null;
return createAsyncRequest(
url,
dispatch,
actionType,
{ method, headers, ...param },
repeat,
rj
);
};
/**
* 创建相关异步action的方法
* @param {*} actions 异步action数组
* @param {*} relatedActionType 异步action开始请求、全部成功或者某个请求失败dispatch的action type
*/
const createRelatedAsyncAction = (actions, relatedActionType) => (
params = [],
rjs = []
) => dispatch => {
let actionList = [];
const promiseList = [];
if (actions && Array.isArray(actions)) {
actionList = actions;
} else if (typeof actions === "object") {
actionList = [actions];
} else {
return Promise.reject();
}
dispatch({ type: relatedActionType.pending });
const len = actionList.length;
for (let i = 0; i < len; i++) {
const { url, actionType, method = "GET", headers = {} } = actionList[i];
const { type, pending, accept, reject } = actionType;
const param =
params && params[i] ? getRequestParams(method, params[i]) : null;
dispatch({ type: pending });
const promise = createAsyncRequest(
url,
dispatch,
actionType,
{
method,
headers,
...param
},
true,
rjs ? rjs[i] : null
);
promiseList.push(promise);
}
return Promise.all(promiseList)
.then(() => {
dispatch({ type: relatedActionType.accept });
return Promise.resolve();
})
.catch(e => {
dispatch({ type: relatedActionType.reject });
console.error(e);
return Promise.reject();
});
};
export { createAsyncActionType, createAsyncAction, createRelatedAsyncAction };
|
import React from 'react';
import '../App.css'
class Footer extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div class="footer pull-right">
Global Leadership Platform © 2019
</div>
);
}
}
export default Footer;
|
import fetch from 'isomorphic-fetch';
import config from './config';
export function getTopics() {
return fetch(`${config.getApiUrl()}/topic/`, {
method: 'GET',
headers: {
'x-access-token': config.getToken(),
},
});
}
export function createTopic(topic) {
return fetch(`${config.getApiUrl()}/topic`, {
method: 'POST',
headers: {
'x-access-token': config.getToken(),
'Content-Type': 'application/json',
},
body: JSON.stringify(topic),
});
}
|
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import KanyeQuote from "../Components/KanyeQuote";
import ChuckNorrisFact from "../Components/ChuckNorrisFacts";
import Img from '../img/fourire.jpg';
const useStyles = makeStyles({
title: {
fontSize: '3em',
textAlign: 'center',
},
img: {
height:"86vh",
width:"100%",
position:"relative",
top:20,
opacity:0.7,
borderRadius:30
}
});
const Home = () => {
const classes = useStyles();
return (
<div>
{/* <h1 className={classes.title}> HOME </h1> */}
<img className={classes.img} src={Img} alt="someone laughing" />
{/* <KanyeQuote/> */}
{/* <ChuckNorrisFact/> */}
</div>
);
};
export default Home;
|
import useSWR from 'swr'
import { fetchProfileWithSWR } from '../actions/userAction'
export function useProfile(token) {
const {data, error} = useSWR(`${token}`, fetchProfileWithSWR)
return {
profile: data,
isLoading: !error && !data,
isError: error
}
}
|
import React from 'react';
import {View, Text} from 'react-native';
import PropTypes from 'prop-types';
import styles from './styles';
const Container = ({children, title}) => {
return (
<View testID="Container" style={styles.container}>
<Text testId="ContainerTitle" style={styles.title}>
{title}
</Text>
{children}
</View>
);
};
Container.propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node,
]).isRequired,
title: PropTypes.string,
};
export default Container;
|
Page({
data: {
hasSend: false,
second: 60,
real_name: null,
wechat: null,
telephone: null,
code: null,
shop_name: null,
recruit_name: null,
content: null,
real_name: null,
real_name: null,
real_name: null,
},
getName(e) {
this.setData({
real_name: e.detail.value
})
},
getWechat(e) {
this.setData({
wechat: e.detail.value
})
},
getTelephone(e) {
this.setData({
telephone: e.detail.value
})
},
getCode(e) {
this.setData({
code: e.detail.value
})
},
getShopName(e) {
this.setData({
shop_name: e.detail.value
})
},
getRecruitName(e) {
this.setData({
recruit_name: e.detail.value
})
},
getContent(e) {
this.setData({
content: e.detail.value
})
},
sendCode() {
if (!this.data.telephone) {
wx.showToast({
title: '请输入手机号码',
icon: 'none'
})
return
}
const that = this
var timer = setInterval(function () {
that.setData({
second: that.data.second - 1
})
}, 1000)
app.fun.post('/user/code', {
record_type: 'bind',
telephone: this.data.telephone
}).then((res) => {
wx.hideLoading()
wx.showToast({
title: res.msg
})
this.setData({
hasSend: true
})
setTimeout(function () {
clearInterval(timer)
that.setData({
second: 60,
hasSend: false
})
}, 1000 * 60)
})
},
uploadAvatar() {
wx.chooseImage({
count: 1,
sizeType: ['original'],
success(res) {
const file = res.tempFilePaths
wx.showLoading({
title: '加载中'
})
wx.uploadFile({
url: app.globalData.host + '',
filePath: res.tempFilePaths[0],
name: 'img',
header: app.globalData.header,
formData: {
type: ''
},
success(res) {
wx.hideLoading()
const data = JSON.parse(res.data)
if (data.code === 200) {
this.setData({
})
} else {
wx.showToast({
title: data.msg,
icon: 'none'
})
}
}
})
}
})
}
})
|
$(function(){
$('#send').click(function(e){
e.preventDefault();
var playerBat, computerBat, ball;
var playerScore = 0, computerScore = 0;
var computerBatSpeed = 190;
var ballSpeed = 200;
var ballReleased = false;
var playerBatHalfWidth;
var playerScoreText,computerScoreText;
var user_input = $('#chat_box').val();
if(user_input == '/play pong'){
//removeCurrentGame(); maybe need to add function to remove current game.*/
var chat_history = $('#chat_history')
.append($("<li class='list-group-item current_game'></li>"));
var current_game = $('li:last-child')
.append($('<div id="current_game"></div'));
current_game.hide();
var hidden = true;
var game = new Phaser.Game(400,300,Phaser.AUTO,'current_game',{ preload: preload, create: create, update: update });
function preload(){
game.load.image('bat', 'assets/paddle.png');
game.load.image('ball', 'assets/ball.png');
game.load.image('background', 'assets/starfield.png');
}
function create(){
game.add.tileSprite(0,0,400,300,'background');
game.physics.startSystem(Phaser.Physics.ARCADE);
playerBat = createBat(game.world.centerX, 280);
computerBat = createBat(game.world.centerX, 20);
playerScoreText = game.add.text(50,10,'',{ font: "15px Arial", fill: "#19de65" ,fontWeight: 'bold'});
computerScoreText = game.add.text(350,10,'',{ font: "15px Arial", fill: "#19de65" ,fontWeight: 'bold'});
ball = createBall(game.world.centerX, game.world.centerY);
playerBatHalfWidth = playerBat.width / 2;
game.input.onDown.add(setBall, this);
}
function update (){
if(hidden){
hidden = false;
current_game.slideDown();
}
controlPlayerPaddle(this.game.input.x);
controlComputerPaddle();
processBallAndPaddleCollisions();
checkGoal();
updateScores();
}
function updateScores(){
playerScoreText.setText(playerScore);
computerScoreText.setText(computerScore);
if(playerScore > 4){
endGame(true);
} else if ( computerScore > 4){
endGame(false);
}
}
function createBat (x,y) {
var bat = game.add.sprite(x,y, 'bat');
game.physics.enable(bat);
bat.anchor.setTo(0.5,0.5);
bat.body.collideWorldBounds = true;
bat.body.bounce.setTo(1,1);
bat.body.immovable = true;
return bat;
}
function createBall (x,y) {
var tmpBall = game.add.sprite(x,y, 'ball');
game.physics.enable(tmpBall);
tmpBall.anchor.setTo(0.5,0.5);
tmpBall.body.collideWorldBounds = true;
tmpBall.body.bounce.setTo(1, 1);
return tmpBall;
}
function setBall () {
if (ballReleased) {
ball.x = game.world.centerX;
ball.y = game.world.centerY;
ball.body.velocity.x = 0;
ball.body.velocity.y = 0;
ballReleased = false;
} else {
ball.body.velocity.x = ballSpeed;
ball.body.velocity.y = -ballSpeed;
ballReleased = true;
}
}
function controlPlayerPaddle (x) {
playerBat.x = x;
if (playerBat.x < playerBatHalfWidth) {
playerBat.x = playerBatHalfWidth;
} else if (playerBat.x > game.width - playerBatHalfWidth) {
playerBat.x = game.width - playerBatHalfWidth;
}
}
function controlComputerPaddle () {
if (computerBat.x - ball.x < -15) {
computerBat.body.velocity.x = computerBatSpeed;
} else if(computerBat.x - ball.x > 15) {
computerBat.body.velocity.x = -computerBatSpeed;
} else {
computerBat.body.velocity.x = 0;
}
}
function processBallAndPaddleCollisions () {
game.physics.arcade.collide(ball, playerBat, ballHitsBat, null, this);
game.physics.arcade.collide(ball, computerBat, ballHitsBat, null, this);
}
function ballHitsBat (_ball, _bat) {
var diff = 0;
if (_ball.x < _bat.x) {
diff = _bat.x - _ball.x;
} else if (_ball.x > _bat.x) {
diff = _ball.x - _bat.x;
_ball.body.velocity.x = (10*diff);
} else {
_ball.body.velocity.x = 2 + Math.random() * 8;
}
}
function checkGoal () {
if (ball.y < 13) {
playerScore++;
setBall();
} else if (ball.y > 285) {
computerScore++;
setBall();
}
}
function endGame(playerWon){
game.destroy();
if(playerWon){
current_game.html('Congratulations! you won.');
} else {
current_game.html('Sorry, you lost.');
}
}
}
});
});
|
import { all } from 'redux-saga/effects';
import homePageSaga from './homePage';
import loginSage from './login';
export default function* rootSaga() {
yield all([
homePageSaga(),
loginSage(),
]);
}
|
import BookRegisterContainer from "./BookRegisterContainer";
export default BookRegisterContainer
|
"use strict";
/*
Copyright [2014] [Diagramo]
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.
*/
/**
* This command just clones an existing {Figure}. All it needs is an id of
* cloned {Figure}
* @this {FigureCloneCommand}
* @constructor
* @param {Number} parentFigureId - the Id of parent {Figure}
* @author Alex <alex@scriptoid.com>
* @author Janis Sejans <janis.sejans@towntech.lv>
*/
function FigureCloneCommand(parentFigureId){
this.oType = 'FigureCloneCommand';
this.firstExecute = true;
/**This will keep the newly created Figure id*/
this.figureId = null;
/**This keeps the cloned figure Id*/
this.parentFigureId = parentFigureId;
}
FigureCloneCommand.prototype = {
/**This method got called every time the Command must execute*/
execute : function(){
if(this.firstExecute){
//get old figure and clone it
var createdFigure = STACK.figureGetById(this.parentFigureId).clone();
//move it 10px low and 10px right
createdFigure.transform(Matrix.translationMatrix(10,10));
//store newly created figure
STACK.figureAdd(createdFigure);
//store newly created figure id
this.figureId = createdFigure.id;
//update diagram state
selectedFigureId = this.figureId;
setUpEditPanel(createdFigure);
state = STATE_FIGURE_SELECTED;
this.firstExecute = false;
}
else{ //redo
throw "Not implemented";
}
},
/**This method should be called every time the Command should be undone*/
undo : function(){
STACK.figureRemoveById(this.figureId);
state = STATE_NONE;
}
}
|
#!/usr/bin/env node
'use strict'
// process.title = 'sc';
var program = require('commander');
var chalk = require('chalk');
var inquirer = require('inquirer');
program.version(require('../package').version)
.usage('<command> [options]');
inquirer
.prompt([
/* Pass your questions in here */
{
type: 'rawlist',
name: 'type',
message: `${chalk.magenta(' What\'s your new job type?Please choose one of the following:')}`,
choices: ['USA','CAN','Print','NON WMT'],
default: 'USA'
}
])
.then(answers => {
// Use user feedback for... whatever!!
switch (answers.type){
case 'USA':
console.log('usa')
break;
case 'CAN':
console.log('usa')
break;
case 'Print':
console.log('usa')
break;
case 'NON WMT':
console.log('usa')
break;
}
});
program.parse(process.argv)
if(!program.args.length){
program.help()
}
|
import React from 'react';
import { MDBFooter } from 'mdbreact';
const Footer = () => (
<MDBFooter className="center">
<div className="border-top">
<p>© 2020 Jack.inc.</p>
</div>
</MDBFooter>
);
export default Footer;
|
"use strict";
//===== DZ 1 =====//
// Вычисления
function sum(a, b) {
return a + b
}
function minus(a, b) {
return a - b
}
function multiply(a, b) {
return a * b
}
function divide(a, b) {
return a / b
}
//Функция которая проверяет числа
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
//Функция которая проверяет оператор
function getTrueOperator (operator) {
var trueOperator;
switch (operator) {
case '+': trueOperator = operator;
break;
case '-': trueOperator = operator;
break;
case '*': trueOperator = operator;
break;
case '/': trueOperator = operator;
break;
default:
alert('Ввели не верный оператор');
}
return Boolean(trueOperator)
}
//Запрос значений
do {
var a = prompt('Введите первое число', '');
} while (!isNumeric(a));
do {
var b = prompt('Введите второе число', '');
} while (!isNumeric(b));
do {
var operator = prompt('Введите оператор', '');
} while ( !getTrueOperator (operator) );
console.log( getTrueOperator (operator) );
// Вызов функций при условии верного оператора
var result;
switch (operator) {
case '+':
result = sum( +a, +b );
break;
case '-':
result = minus( +a, +b );
break;
case '*':
result = multiply( +a, +b );
break;
case '/':
result = divide( +a, +b );
break;
}
// Вывод результата
alert('Результат вычислений:' + result);
console.log(a);
console.log(b);
console.log(operator);
console.log(result);
|
import React, { useContext } from 'react'
import { GlobalContext } from '../contexts/GlobalContext'
const IncomeExpenses = () => {
const { transactions } = useContext(GlobalContext);
const amounts = transactions.map(transaction=> transaction.amount);
const income = amounts.filter(item => item > 0)
.reduce((acc, item) => (acc += item), 0);
const expenses = amounts.filter(item => item < 0)
.reduce((acc, item) => (acc += item), 0);
return (
<div className="exp-inc-container">
<div>
<h3>Votre revenu</h3>
<p style={{color:'#4cd137'}}>+{income}€</p>
</div>
<div>
<h3>Vos dépenses</h3>
<p style={{color:'red'}}>-{Math.abs(expenses)}€</p>
</div>
</div>
)
}
export default IncomeExpenses;
|
(function() {
'use strict';
// Конструктор таблицы
// Можно выбрать количество отображаемых элементов на странице и путь к базе
function Table() {
var SEARCH_INPUT = document.getElementById('searchInput'), // Инпут с поиском
self = this;
self.nItemsOnPage = 5; // Сколько столбцов показывать на странице
self.pathToDatabase = 'js/data.json';
// Загрузка данных из базы и отрисовка таблицы
self.loadFromBase = function(pageFrom, searchValue) {
// Загружаем базу
var xhr = new XMLHttpRequest();
xhr.open('GET', self.pathToDatabase);
xhr.timeout = 10000;
xhr.onload = function(e) {
var data = JSON.parse(e.target.response);
loadTableInDom(data, pageFrom, searchValue);
};
xhr.send();
}
// Строит и заполняет таблицу в памяти
function fillTable(loadedData, pageFrom, searchValue) {
// Удаляем события, если есть
var paginationList = document.querySelector('.pagination');
if (paginationList !== null) {
paginationList.removeEventListener('click', _setPaginationEvent);
}
// Очистка таблицы и пагинации, если есть
if (document.getElementById('table') !== null) {
document.getElementById('table').innerHTML = '';
}
var itemsFrom = pageFrom * self.nItemsOnPage,
itemsTo = itemsFrom + self.nItemsOnPage;
// Создаем фрагмент
var fragment = document.createDocumentFragment(),
table = document.createElement('table'),
tableContainer = document.createElement('div'),
thead = document.createElement('thead'),
tbody = document.createElement('tbody'),
tr = document.createElement('tr'),
td = document.createElement('td');
// Добавляем стили к таблице и элементам
table.classList.add('table');
thead.classList.add('table__thead');
tr.classList.add('table__row');
tableContainer.id = 'table-container';
tableContainer.classList.add('table-container');
tableContainer.appendChild(table);
// Заполняем шапку
table.appendChild(thead);
for (var i = 0; i < 4; i++) {
var cloneTd = td.cloneNode();
thead.appendChild(cloneTd);
if (i == 0) {
cloneTd.textContent = 'ФИО';
} else if (i == 1) {
cloneTd.textContent = 'Дата рождения';
} else if (i == 2) {
cloneTd.textContent = 'Средний балл';
} else if (i == 3) {
cloneTd.textContent = 'Курс';
}
}
table.appendChild(tbody);
// Фильтрация массива через поиск
if (searchValue !== undefined) {
var searchVal = searchValue;
var filterData = loadedData.filter(function(item) {
var dataObject = Object.keys(item);
for (var i = 0; i < dataObject.length; i++) {
var valInBase = item[dataObject[i]].toString();
valInBase = valInBase.toLowerCase();
if (valInBase.indexOf(searchVal) !== -1) {
return item;
}
}
});
} else {
var filterData = loadedData.slice(0);
}
// Заполняем таблицу данными из базы
var showedData = filterData.slice(itemsFrom, itemsTo);
showedData.forEach(function(item) {
var cloneTr = tr.cloneNode(),
dataObject = Object.keys(item);
for (var i = 0; i < dataObject.length; i++) {
var cloneTd = td.cloneNode();
cloneTr.appendChild(cloneTd);
cloneTd.textContent = item[dataObject[i]];
}
tbody.appendChild(cloneTr);
});
fragment.appendChild(tableContainer);
// Выводим пагинацию, если надо
if (filterData.length > self.nItemsOnPage) {
var getPagination = setPagination(self.nItemsOnPage, filterData);
if (getPagination !== false) {
fragment.appendChild(getPagination);
var paginationItems = fragment.querySelectorAll('.pagination__item');
paginationItems[pageFrom].classList.add('active');
}
}
return fragment;
}
// Строит пагинацию
function setPagination(itemsOnPage, loadedData) {
if (loadedData.length > itemsOnPage) {
var paginationFragment = document.createDocumentFragment(),
paginationList = document.createElement('ul'),
paginationItem = document.createElement('li'),
paginationCount = Math.ceil(loadedData.length / itemsOnPage);
paginationList.classList.add('pagination');
paginationItem.classList.add('pagination__item');
for (var i = 0; i < paginationCount; i++) {
var clonePaginationItem = paginationItem.cloneNode();
clonePaginationItem.textContent = i + 1;
paginationList.appendChild(clonePaginationItem);
}
paginationFragment.appendChild(paginationList);
return paginationFragment;
} else {
return;
}
}
// Берет таблицу из базы и заполняет DOM
function loadTableInDom(loadedData, pageFrom, searchValue) {
var container = document.getElementById('table');
// Строим и заполняем фрагмент
var setFragment = fillTable(loadedData, pageFrom, searchValue);
// Загружаем фрагмент в DOM
container.appendChild(setFragment);
setTableFixed(container);
window.onresize = function() {
setTableFixed(container);
};
paginationEvents();
}
function setTableFixed(container) {
// Фиксированная высота для таблицы, чтобы удобно пользоваться пагинатором
var tr = container.querySelector('.table__row'),
table = container.querySelector('.table'),
tableContainer = document.getElementById('table-container');
if (tr !== null) {
var trHeight = tr.getBoundingClientRect().height;
tableContainer.style.height = trHeight * (self.nItemsOnPage + 1) + 'px';
} else {
var tbody = table.querySelector('tbody');
tbody.innerHTML = '<tr><td>Нет данных</td></tr>';
}
}
// События пагинации
function paginationEvents() {
var paginationList = document.querySelector('.pagination');
if (paginationList !== null) {
paginationList.addEventListener('click', _setPaginationEvent);
}
}
// Обработка клика в пагинации
function _setPaginationEvent(e) {
var clickedElement = e.target || e.srcElement,
paginationItems = this.querySelectorAll('.pagination__item');
if (clickedElement.classList.contains('active')) {
return;
}
Array.prototype.forEach.call(paginationItems, function(item) {
if (clickedElement.classList.contains('pagination__item')) {
item.classList.remove('active');
}
});
if (clickedElement.classList.contains('pagination__item')) {
var searchValue = SEARCH_INPUT.value;
self.loadFromBase(clickedElement.textContent - 1, searchValue);
}
}
// События поиска
SEARCH_INPUT.addEventListener('keyup', function(e) {
var searchVal = this.value;
searchVal.toString();
searchVal = searchVal.toLowerCase();
searchVal = searchVal.trim();
self.loadFromBase(0, searchVal);
});
}
// Запуск таблицы
var tableInit = new Table();
tableInit.loadFromBase(0);
})();
|
import styled from "styled-components";
import ImageComponent from "../utility/ImageComponent";
import Link from "next/link";
const ProjectPageWrapper = styled.main`
padding: 2rem;
border-radius: 2rem;
display: flex;
justify-content: center;
align-items: center;
column-gap: 3rem;
text-align: justify;
@media (max-width: 1000px) {
flex-direction: column;
row-gap: 2rem;
border-radius: 0;
}
h1 {
font-size: 1.7rem;
@media (max-width: 1000px){
font-size: 1.3rem;
}
}
div {
display: flex;
justify-content: center;
column-gap: 0.5rem;
}
div > a > div > img {
border-radius: 20px;
@media (max-width: 1000px) {
width: 80vw !important;
}
}
article {
width: 30rem;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
row-gap: 1.5rem;
@media (max-width: 1000px) {
width: 40%;
}
}
.tag {
display: flex;
align-items: center;
justify-content: center;
max-width: 8rem;
border: 1px solid #2e0347;
color: #2e0347;
border-radius: 5px;
padding: 0.5rem;
font-weight: bold;
}
`;
const ProjectPage = ({ project }) => {
const tagsArr = project.tags.split(",");
return (
<ProjectPageWrapper>
<article>
<h1>{project.title}</h1>
<div className="flex-row justify-center">
{tagsArr.map((tag) => (
<div key={tag} className="tag">
{tag}
</div>
))}
</div>
<p>{project.description}</p>
</article>
<Link href={project.url}>
<a>
<ImageComponent
width={700}
height={350}
phoneWidth={"80vw"}
src={project.img.url}
/>
</a>
</Link>
</ProjectPageWrapper>
);
};
export default ProjectPage;
|
// start slingin' some d3 here.
// var asteroids = [];
var scores = {
high: 0,
current: 0,
collisions: 0
};
var svg = d3.select('body').append('svg')
.attr('width', '100%')
.attr('height', '800');
var throttle = function(func, wait) {
var throttled = false;
return function() {
var args = Array.prototype.slice.call(arguments).slice(2);
if (!throttled) {
func.apply(this, args);
throttled = true;
setTimeout(function() {
throttled = false;
}, wait);
}
};
};
var getRandNum = function(min, max) {
return Math.random() * (max - min) + min;
};
var genRandPos = function(num) {
var positions = [];
for (var i = 0; i < num; i++) {
positions.push( {x: getRandNum(1, 700), y: getRandNum(1, 700)} );
}
return positions;
};
var updateAsteroids = function(data) {
var asteroids = d3.select('svg').selectAll('.asteroid');
// var asteroidPos = asteroids.data(data, function(d) { return d; });
//update existing nodes with their mapped data
asteroids.data(data)
.transition()
.attr('x', function(d) { return d.x; })
.attr('y', function(d) { return d.y; })
.duration(1000);
//create new asteroids
asteroids.data(data)
.enter()
//.append('circle')
.append('image')
//add asteroid class
.attr('class', 'asteroid')
// .attr('cx', function(d) { return d.x; })
// .attr('cy', function(d) { return d.y; })
// .attr('r', '30') //TODO create variating sizes
.attr('xlink:href', 'asteroid.png')
.attr('width', 100)
.attr('height', 100)
.attr('x', function(d) { return d.x; })
.attr('y', function(d) { return d.y; });
};
//var player = d3.select('svg').selectAll('circle.player');
var dragmove = function(d) {
var x = d3.event.x;
var y = d3.event.y;
d3.select(this)
.transition()
.attr('cx', x)
.attr('cy', y)
.duration(0);
};
var drag = d3.behavior.drag()
.on('drag', dragmove);
var updatePlayer = function(data) {
var player = d3.select('svg').selectAll('circle.player');
//create new player
player.data(data)
.enter()
.append('circle')
.attr('class', 'player')
.attr('cx', '400')
.attr('cy', '400')
.attr('r', '15')
.style('fill', 'orange')
.call(drag);
// svg.on('click', function(d) {
// var drag = d3.behavior.drag();
// player.call(drag);
// console.log('clicked');
// });
};
var updateScore = function(data) {
// var highScore = d3.select('.highscore').select('span');
// var score = d3.select('.current').select('span');
// var collisions = d3.select('.collisions').select('span');
var scoreBoard = d3.select('.scoreboard').selectAll('span');
scoreBoard.data(data).text(function(d) { return d; });
// //update highScore
// highScore.data([]).text();
// // update score
// score.text('test');
// // update collisions
// collisions.text('test');
};
var incrementScore = throttle(function() {
scores.high = scores.current > scores.high ? scores.current : scores.high;
scores.collisions++;
scores.current = 0;
updateScore([scores.high, scores.current, scores.collisions]);
}, 500);
var detectCollision = function(node1, node2) {
var x1 = Number(node1.attr('x'));
var y1 = Number(node1.attr('y'));
var x2 = Number(node2.attr('cx'));
var y2 = Number(node2.attr('cy'));
var distance = Math.sqrt ( Math.pow( x2 - x1, 2 )
+ Math.pow( y2 - y1, 2 ) );
return distance < 22.5;
};
var test = throttle(updateScore, 100);
//d3.select(node1).attr('cx')
var detectPlayerCollision = function() {
var asteroids = d3.select('svg').selectAll('.asteroid');
var player = d3.select('svg').selectAll('circle.player');
//check distance between player and each asteroid
for (var i = 0; i < asteroids[0].length; i++) {
if ( detectCollision( d3.select(asteroids[0][i]), player ) ) {
player.style('fill', 'green');
incrementScore();
// scores.high = scores.current > scores.high ? scores.current : scores.high;
// scores.collisions++;
// scores.current = 0;
// updateScore([scores.high, scores.current, scores.collisions]);
}
}
};
setInterval(function() { updateAsteroids(genRandPos(10)); }, 1000);
setInterval(function() { updatePlayer([{x: 1, y: 1}]); }, 10 );
setInterval(function() { scores.current++; }, 1000);
setInterval(function() { updateScore([scores.high, scores.current, scores.collisions]); }, 1000);
setInterval(function() { detectPlayerCollision(); }, 10);
//[{x: 100 y: 100}, {x: 100 y: 100} ]
/*
[{name: 'dan', val:2}, {name: 'cal', val:5}]
update([{name: 'dan', val:2}, {name: 'jonas', val:5}])
.text(function(){
return 'my name is' + name;
})
<div> dan 2 </div>
<div> jonas 5 </div>
*/
|
import React from 'react'
import { Header } from 'react-native-elements'
import ButtonHeader from './ButtonHeader'
const CustomHeader = ({ title, leftIcon, leftOnClick, rightIcon, rightOnClick }) => {
return(
<Header
backgroundColor={'#5458CC'}
centerComponent={{
text: title,
style: {
color: '#fff',
fontSize: 24,
fontWeight: 'bold'
}
}}
containerStyle={{
justifyContent: 'space-around',
}}
statusBarProps={{
translucent: true,
}}
leftComponent={
<ButtonHeader
color={'#5458CC'}
icon={leftIcon}
size={20}
onClick={leftOnClick}
/>
}
rightComponent={
<ButtonHeader
color={'#5458CC'}
icon={rightIcon}
size={20}
onClick={rightOnClick}
/>
}
/>
)
}
export default CustomHeader
|
import produce from 'immer'
import { cartActions } from './actions'
export default function cart(state = [], action) {
const { type } = action
switch (type) {
case cartActions.addToCartSuccess:
return produce(state, draft => {
draft.push(action.product)
})
case cartActions.removeFromCart:
return produce(state, draft => {
const productIndex = draft.findIndex(p => p.id === action.id)
if (productIndex >= 0) draft.splice(productIndex, 1)
})
case cartActions.updateAmount: {
if (action.amount <= 0) return state
return produce(state, draft => {
const productIndex = draft.findIndex(p => p.id === action.id)
if (productIndex >= 0)
draft[productIndex].amount = Number(action.amount)
})
}
default:
return state
}
}
|
import store from "../store";
import ConstantType from "../js/sdk/constant/ConstantType";
export default {
getAll() {
let newMap = new Map();
let groupMap = store.state.cache.cache.groupMap;
for(let item of groupMap) {
if(item[1].type != ConstantType.GroupTypeConstant.GROUP_CHATROOM){
newMap.set(item[0],item[1])
}
}
return newMap;
},
getOneByGroupId(groupId) {
let id = parseInt(groupId)
if (this.getAll().has(id)) {
return this.getAll().get(id)
}
return {}
},
getNameByGroup(group) {
if (group.groupName) return group.groupName;
return "";
},
isOwner(imUid, groupId) {
var group = this.getOneByGroupId(groupId)
if (group && imUid && imUid == group.owner) {
return true;
}
return false;
},
formatGroupType(groupType) {
switch (groupType) {
case ConstantType.GroupTypeConstant.Group_MAIN_COMPANY:
return "总部";
case ConstantType.GroupTypeConstant.Group_BRANCH_COMPANY:
return "分公司";
case ConstantType.GroupTypeConstant.Group_PROJECTDEPARTMENT:
return "项目部";
case ConstantType.GroupTypeConstant.Group_COMPANY:
return "部门";
case ConstantType.GroupTypeConstant.Group_PROJECT:
return "项目";
}
return "";
}
}
|
import { connect } from 'react-redux'
import * as evidencesActions from '../reducers/entities/evidences'
import * as evidencesSubscriber from '../reducers/evidences-subscriber'
import * as updatesFeedActions from '../reducers/ui/updates-feed'
import * as updatesFeedSelector from '../selectors/ui/updates-feed'
import { UpdatesFeed as UpdatesFeedComponent } from '../components/updates-feed'
export default connect(
(state, props) => ({
listStartDateISO: updatesFeedSelector.getStartDateISO(state, props),
isAutomaticMapFitting: updatesFeedSelector.isAutomaticMapFitting(state, props),
isRealtime: updatesFeedSelector.isRealtime(state, props),
onDemandCount: updatesFeedSelector.getOnDemandCount(state, props),
user: {
// TODO: we should pass real user's position
location: { lat: 0, long: 0 }
},
viewMode: updatesFeedSelector.getViewMode(state, props)
}),
(dispatch, props) => ({
enableRealtime: (enable) => dispatch(updatesFeedActions.enableRealtime(enable)),
loadItemsAfter: ({ lat, long, startDateISO }) => dispatch(evidencesActions.fetchEvidences({
lat,
long,
startDateISO
})),
onAutoMapFittingChange: (fit) => dispatch(updatesFeedActions.autoMapFitting(fit)),
moveOnDemandIdsToTheFeed: () => dispatch(updatesFeedActions.moveOnDemandIdsToTheFeed()),
setViewMode: viewMode => dispatch(updatesFeedActions.setViewMode(viewMode)),
subscribeUpdatesFeed: (payload) => dispatch(evidencesSubscriber.subscribeEvidences(payload)),
unsubscribeUpdatesFeed: () => dispatch(evidencesSubscriber.unsubscribeEvidences())
})
)(UpdatesFeedComponent)
|
import React from "react";
import { withRouter } from "react-router-dom";
import CollectionFinder from "../collection-finder/CollectionFinder";
const CollectionList = (props) => {
const { collectionsArray } = props.collectionsArray;
const { arrayNavbar } = props.arrayNavbar;
//const { id } = props.id;
return (
<div className="collection-List-Container">
{
/********** collectionElement - it's collection's code, like '000107' ********** */
/********** navbarElement - one element in Navbar with its submenu - array ********** */
collectionsArray.map((collectionElement) =>
arrayNavbar.map((navbarElement, index) => (
<div key={index}>
<CollectionFinder
collectionCode={collectionElement}
navbarElement={navbarElement}
index={index}
id={props.id}
/>
</div>
))
)
}
</div>
);
};
export default withRouter(CollectionList);
|
angular.module("app.game").directive("timer", function ($timeout) {
return {
restrict: "E",
templateUrl: "components/game/timer.html",
replace: true,
scope: {
time: "="
},
link: function ($scope, element, attrs) {
var curTime = (+new Date());
$scope.mins = 0;
$scope.secs = 0;
$timeout(tick, 1000 - 10);
function tick () {
var newTime = (+new Date());
$scope.time = newTime - curTime;
$scope.secs = Math.round($scope.time / 1000 % 60);
//$scope.secs = Math.round(time / 1000 - $scope.mins * 60);
$timeout(tick, 1000 - 10);
}
}
};
});
|
import React from "react";
import { connect } from "react-redux";
import { ReactComponent as ShoppingIcon } from "../../assets/shopping-bag.svg";
import { cartToggle } from "../../redux/cart/cartAction";
import { selectCartItemsCount } from "../../redux/cart/cartSelector";
import "./cart-icon.scss";
const CartIcon = ({ cartToggle, cartCount }) => (
<div className="cart-icon">
<ShoppingIcon className="shopping-icon" onClick={cartToggle} />
<span className="item-count">{cartCount}</span>
</div>
);
const mapDispatchToProps = (dispatch) => ({
cartToggle: () => dispatch(cartToggle()),
});
const mapStateToProps = (state) => ({
cartCount: selectCartItemsCount(state),
});
export default connect(mapStateToProps, mapDispatchToProps)(CartIcon);
|
UMessage = {}
UMessage.should = {
return:{
'Film.titre':{
failure:"La bonne valeur retournée devrait être #{expected}",
success:"`Film.titre()` retourne la bonne valeur (#{expected})"
}
}
}
|
/**
* Created by han on 31.08.14.
*/
var shoe = require('shoe'),
dnode = require('dnode'),
Trade = function (mount) {
var readyQueue = [],
server,
stream = shoe(mount),
d = dnode();
d.on('remote', function (connection) {
server = connection;
console.log('setup remote');
// call ready queue - and clear
readyQueue.forEach(function (cb) {
cb(server);
});
readyQueue = null;
});
d.pipe(stream).pipe(d);
this.ready = function (cb) {
if (readyQueue !== null) {
readyQueue.push(cb);
} else {
cb(server);
}
};
this.initConnection = function (clientConnection, cb) {
server.init(clientConnection, cb);
};
};
module.exports = Trade;
|
function validation(){
var name = document.getElementById('name').value;
var pass = document.getElementById('pass').value;
if(name == ""){
document.getElementById('name').innerHTML =" ** Please fill the Studentname field";
return false;
}
if((name.length <= 2) || (nme.length > 40)) {
document.getElementById('name').innerHTML =" ** Studentname lenght must be between 2 and 40";
return false;
}
if(!isNaN(name)){
document.getElementById('name').innerHTML =" ** only characters are allowed";
return false;
}
}
|
import { combineReducers } from 'redux';
import todos from './todoReducer';
//combineReducers is used to combine multiple reducers
const rootReducer = combineReducers({
todos,
});
//exporting the rootReducer
export default rootReducer;
|
const baseRule = require('./app/base/baseRule');
const baseFilter = require('./app/base/baseFilter');
module.exports = app => {
baseRule.addRule(app); //增加验证规则
baseFilter.addFilter(app); //增加过滤器
};
|
import React from 'react'
import { Link } from 'react-router-dom';
const CardListItem = (props) => {
let { item } = props
console.log('CardListItem: ', item, item.image, item.text )
return(
<div className="cardItem">
<h2>{item.unicorn}</h2>
<figure>
<img src={item.image} alt={item.unicorn}
/>
</figure>
<object data={item.text}>{item.text}</object>
<Link to={`/view/${item.id}`}>
<button className="button">
Vé a {item.unicorn}
</button>
</Link>
</div>
)
}
export default CardListItem
|
export function parseQuery(query) {
const queryObj = {}
query.split('&').forEach(param => {
const parts = param.replace(/\+/g, ' ').split('=')
const key = decodeURIComponent(parts.shift())
const val = parts.length > 0 ? decodeURIComponent(parts.join('=')) : null
if (queryObj[key] === undefined) {
queryObj[key] = val
} else if (Array.isArray(queryObj[key])) {
queryObj[key].push(val)
} else {
queryObj[key] = [queryObj[key], val]
}
})
return queryObj
}
export function stringifyQuery(queryObj) {
if (!queryObj) {
return ''
}
return Object.keys(queryObj)
.sort()
.map(key => {
const val = queryObj[key]
if (val === undefined) {
return ''
}
if (val === null) {
return encodeURIComponent(key)
}
if (Array.isArray(val)) {
const result = []
val.forEach(val2 => {
if (val2 === undefined) {
return
}
if (val2 === null) {
result.push(encodeURIComponent(key))
} else {
result.push(`${encodeURIComponent(key)}=${encodeURIComponent(val2)}`)
}
})
return result.join('&')
}
return `${encodeURIComponent(key)}=${encodeURIComponent(val)}`
})
.filter(it => it.length > 0)
.join('&')
}
|
let localStorageData = {
getUser() {
let user = JSON.parse(localStorage.user || null);
return user;
},
setUser(user) {
let newUser = { id: user.id };
localStorage.user = JSON.stringify(newUser);
},
signOut(user) {
localStorage.removeItem(user);
}
}
export default localStorageData;
|
import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import App from '../App';
import Enzyme, { shallow } from 'enzyme';
Enzyme.configure({adapter: new Adapter()});
describe('testing app.js', () => {
it('should show true', () => {
const wrapper = true;
expect(true).toBe(true);
});
});
|
const initState = {
language: 'mkd'
}
const rootReducer = (state = initState, action) => {
switch (action.type) {
case 'SET_LANGUAGE':
return {
...state,
language: action.payload.language
}
default:
return state;
}
}
export default rootReducer;
|
//Calculate Tip
document.getElementById("b5_value").addEventListener("click", b5_Functions);
document.getElementById("b10_value").addEventListener("click", b10_Functions);
document.getElementById("b15_value").addEventListener("click", b15_Functions);
document.getElementById("b25_value").addEventListener("click", b25_Functions);
document.getElementById("b50_value").addEventListener("click", b50_Functions);
function b5_Functions(){
alert();
b5_Tip();
}
function b10_Functions(){
alert();
b10_Tip()
}
function b15_Functions(){
alert();
b15_Tip()
}
function b25_Functions(){
alert();
b25_Tip()
}
function b50_Functions(){
alert();
b50_Tip()
}
function alert(){
var billAmt = document.getElementById("inputAmount").value;
var numOfPeople = document.getElementById("check_Input").value;
//validate input
if (billAmt =="" || numOfPeople == "") {
document.getElementById("my_error").style.display = "block";
document.getElementById("inputAmount").style.borderColor = "red";
document.getElementById("check_Input").style.borderColor = "red";
return false;
}
}
function b5_Tip() {
var billAmt = document.getElementById("inputAmount").value;
var numOfPeople = document.getElementById("check_Input").value;
//Calculate Tip
var bill_per_person = billAmt / numOfPeople;
var tip_amount = (bill_per_person * 5) / 100;
var total_person = bill_per_person + tip_amount;
//round to two decimal places
tip_amount = Math.round(tip_amount * 100) / 100;
//next line allows us to always have two digits after decimal point
tip_amount = tip_amount.toFixed(2);
total_person = Math.round(total_person*100)/100;
total_person = total_person.toFixed(2);
//Output result
document.getElementById("display_tip").style.display = "none";
document.getElementById("display_total").style.display ="none";
document.getElementById("tipAmount").innerHTML = "$" + tip_amount;
document.getElementById("totalAmount").innerHTML = "$" + total_person;
document.getElementById("delete").style.color = "hsl(183, 100%, 15%)";
document.getElementById("delete").style.background = "hsl(172, 67%, 45%)";
}
function b10_Tip(){
var billAmt = document.getElementById("inputAmount").value;
var numOfPeople = document.getElementById("check_Input").value;
//Calculate Tip
var bill_per_person = billAmt / numOfPeople;
var tip_amount = (bill_per_person * 10) / 100;
var total_person = bill_per_person + tip_amount;
//round to two decimal places
tip_amount = Math.round(tip_amount * 100) / 100;
//next line allows us to always have two digits after decimal point
tip_amount = tip_amount.toFixed(2);
total_person = Math.round(total_person*100)/100;
total_person = total_person.toFixed(2);
//Output result
document.getElementById("display_tip").style.display = "none";
document.getElementById("display_total").style.display ="none";
document.getElementById("tipAmount").innerHTML = "$" + tip_amount;
document.getElementById("totalAmount").innerHTML = "$" + total_person;
document.getElementById("delete").style.color = "hsl(183, 100%, 15%)";
document.getElementById("delete").style.background = "hsl(172, 67%, 45%)";
}
function b15_Tip(){
var billAmt = document.getElementById("inputAmount").value;
var numOfPeople = document.getElementById("check_Input").value;
//Calculate Tip
var bill_per_person = billAmt / numOfPeople;
var tip_amount = (bill_per_person * 15) / 100;
var total_person = bill_per_person + tip_amount;
//round to two decimal places
tip_amount = Math.round(tip_amount * 100) / 100;
//next line allows us to always have two digits after decimal point
tip_amount = tip_amount.toFixed(2);
total_person = Math.round(total_person*100)/100;
total_person = total_person.toFixed(2);
//Output result
document.getElementById("display_tip").style.display = "none";
document.getElementById("display_total").style.display ="none";
document.getElementById("tipAmount").innerHTML = "$" + tip_amount;
document.getElementById("totalAmount").innerHTML = "$" + total_person;
document.getElementById("delete").style.color = "hsl(183, 100%, 15%)";
document.getElementById("delete").style.background = "hsl(172, 67%, 45%)";
}
function b25_Tip(){
var billAmt = document.getElementById("inputAmount").value;
var numOfPeople = document.getElementById("check_Input").value;
//Calculate Tip
var bill_per_person = billAmt / numOfPeople;
var tip_amount = (bill_per_person * 25) / 100;
var total_person = bill_per_person + tip_amount;
//round to two decimal places
tip_amount = Math.round(tip_amount * 100) / 100;
//next line allows us to always have two digits after decimal point
tip_amount = tip_amount.toFixed(2);
total_person = Math.round(total_person*100)/100;
total_person = total_person.toFixed(2);
//Output result
document.getElementById("display_tip").style.display = "none";
document.getElementById("display_total").style.display ="none";
document.getElementById("tipAmount").innerHTML = "$" + tip_amount;
document.getElementById("totalAmount").innerHTML = "$" + total_person;
document.getElementById("delete").style.color = "hsl(183, 100%, 15%)";
document.getElementById("delete").style.background = "hsl(172, 67%, 45%)";
}
function b50_Tip(){
var billAmt = document.getElementById("inputAmount").value;
var numOfPeople = document.getElementById("check_Input").value;
//Calculate Tip
var bill_per_person = billAmt / numOfPeople;
var tip_amount = (bill_per_person * 50) / 100;
var total_person = bill_per_person + tip_amount;
//round to two decimal places
tip_amount = Math.round(tip_amount * 100) / 100;
//next line allows us to always have two digits after decimal point
tip_amount = tip_amount.toFixed(2);
total_person = Math.round(total_person*100)/100;
total_person = total_person.toFixed(2);
//Output result
document.getElementById("display_tip").style.display = "none";
document.getElementById("display_total").style.display ="none";
document.getElementById("tipAmount").innerHTML = "$" + tip_amount;
document.getElementById("totalAmount").innerHTML = "$" + total_person;
document.getElementById("delete").style.color = "hsl(183, 100%, 15%)";
document.getElementById("delete").style.background = "hsl(172, 67%, 45%)";
}
var custom_input = document.getElementById("custom_input");
custom_input.addEventListener("keypress", function(event) {
if (event.keyCode == 13){
alert();
var billAmt = document.getElementById("inputAmount").value;
var numOfPeople = document.getElementById("check_Input").value;
var custom_num = document.getElementById("custom_input").value;
var bill_per_person = billAmt / numOfPeople;
var tip_amount = (bill_per_person * custom_num) / 100;
var total_person = bill_per_person + tip_amount;
//round to two decimal places
tip_amount = Math.round(tip_amount * 100) / 100;
//next line allows us to always have two digits after decimal point
tip_amount = tip_amount.toFixed(2);
total_person = Math.round(total_person*100)/100;
total_person = total_person.toFixed(2);
//Output result
document.getElementById("display_tip").style.display = "none";
document.getElementById("display_total").style.display ="none";
document.getElementById("tipAmount").innerHTML = "$" + tip_amount;
document.getElementById("totalAmount").innerHTML = "$" + total_person;
document.getElementById("delete").style.color = "hsl(183, 100%, 15%)";
document.getElementById("delete").style.background = "hsl(172, 67%, 45%)";
}
});
function clr(){
document.getElementById("inputAmount").value = "";
document.getElementById("check_Input").value = "";
document.getElementById("custom_input").value = "";
document.getElementById("tipAmount").innerHTML = " ";
document.getElementById("totalAmount").innerHTML = " ";
document.getElementById("display_tip").style.display = "block";
document.getElementById("display_total").style.display ="block";
document.getElementById("delete").style.color = "hsl(183, 100%, 15%)";
document.getElementById("delete").style.background = "hsl(183, 100%, 10%)";
document.getElementById("my_error").style.display = "none";
document.getElementById("inputAmount").style.borderColor = "hsl(172, 67%, 45%) ";
document.getElementById("check_Input").style.borderColor = "hsl(172, 67%, 45%)";
}
|
function largestOfFour(arr) {
// Create a new array to store largest values of each sub array
var newArray = [];
// Use a for loop to iterate through the main array
for (var i = 0; i < arr.length; i++){
//Create a variable that wil store the largest number and assign it to the first index of the main array
var largestNum = arr[i][0];
//Use a second for lopp to iterate through sub arrays
for(var j = 1; j < arr[i].length; j++){
/*Create conditional if statment where if the number in the sub array is greater than the first number
of the first index of the sub array */
if(arr[i][j] > largestNum){
//Assign that number to the largest number variable
largestNum = arr[i][j];
}
}
//Assign the largest number of the "ith" index of the main array to the "ith" index of the new array
newArray[i] = largestNum;
}
return newArray;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
//Should output [4, 27, 39, 1001]
|
/**
* B-I-N-G-O
*
* A Bingo card contain 25 squares arranged in a 5x5 grid (five columns
* and five rows). Each space in the grid contains a number between 1
* and 75. The center space is marked "FREE" and is automatically filled.
*
* As the game is played, numbers are drawn. If the player's card has
* that number, that space on the grid is filled.
*
* A player wins BINGO by completing a row, column, or diagonal of filled
* spaces.
*
* Your job is to complete the function that takes a bingo card and array
* of drawn numbers and return 'true' if that card has achieved a win.
*
* A bingo card will be 25 element array. With the string 'FREE' as the
* center element (index 12). Although developers are unscrupulous, they
* will pass valid data to your function.
*/
const bingoCard = [
8, 29, 35, 54, 65,
13, 24, 44, 48, 67,
9, 21, 'FREE', 59, 63,
7, 19, 34, 53, 61,
1, 20, 33, 46, 72
];
// Test cases - created manually
const drawnNumbers = [8, 24, 'FREE', 53, 72]; // should return true against diagonal with 'FREE' check
// const drawnNumbers = [13, 24, 44, 48, 67]; // should return true against horizontal check
// const drawnNumbers = [9, 21, 59, 63]; // should return true against horizontal with 'FREE' check
// const drawnNumbers = [29, 24, 21, 19, 20]; // should return true against vertical check
// const drawnNumbers = [1, 25, 33, 46, 75]; // should return false
// create an object to store the winning combo patterns. we may use this for comparisons
const winningCombinations = [
[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24],
[0, 6, 12, 18, 24],
[4, 8, 12, 16, 20],
[0, 5, 10, 15, 20],
[1, 6, 11, 16, 21],
[2, 7, 12, 17, 22],
[3, 8, 13, 18, 23],
[4, 9, 14, 19, 24]
];
// isBingo flag to use later for eliminating repeated 'checkBingo' function executions
let isBingo = false;
// function to pass when needed to reset the bingoCheckCounter
const resetBingoCheckCounter = () => {
// console.log(`.:: DEBUG ::. Resetting bingoCheckCounter to 0`);
bingoCheckCounter = 0;
}
// announce win function
function youWin(sq1, sq2, sq3, sq4, sq5) {
console.log("BINGO! You win!");
// console.log(`.:: DEBUG ::. Your winning values are: ${sq1}, ${sq2}, ${sq3}, ${sq4}, ${sq5}`);
// resetBingoCheckCounter(); // Was for debugging purposes, can be removed
}
// function to check lines (drawnNumbrs) with bingoCard array values passed from 'checkBingo' functions
function checkLines(sq1, sq2, sq3, sq4, sq5) {
const isBingoWithFree = drawnNumbers.includes(parseInt(sq1)) && drawnNumbers.includes(parseInt(sq2)) && sq3 == 'FREE' && drawnNumbers.includes(parseInt(sq4)) && drawnNumbers.includes(parseInt(sq5));
// console.log(`.:: DEBUG ::. isBingoWithFree: ${isBingoWithFree}`);
const isBingoWithoutFree = drawnNumbers.includes(parseInt(sq1)) && drawnNumbers.includes(parseInt(sq2)) && drawnNumbers.includes(parseInt(sq3)) && drawnNumbers.includes(parseInt(sq4)) && drawnNumbers.includes(parseInt(sq5));
// console.log(`.:: DEBUG ::. isBingoWithoutFree: ${isBingoWithoutFree}`);
if(!isBingo){
// check drawnNumbers array combinations
// with the word 'FREE' or without the word 'FREE'
if ( isBingoWithFree || isBingoWithoutFree ) {
// if (isBingoWithFree) { // debugging messages, can remove later
// console.log(`.:: DEBUG ::. Checking drawnNumbers[] array with the word 'FREE'`);
// } else if (isBingoWithoutFree){
// console.log(`.:: DEBUG ::. Checking drawnNumbers[] array without the word 'FREE'`);
// } else {
// console.log(`.:: DEBUG ::. Something went wrong comparing the drawnNumbers[] array.`);
// }
// update our 'isBingo variable to true if all checks here pass
isBingo = true;
console.log(`setting isBingo flag to:`, isBingo);
// console.log(`${sq1}, ${sq2}, ${sq3}, ${sq4}, ${sq5}`);
// if successful, fire the youWin() function
youWin(sq1, sq2, sq3, sq4, sq5);
return true; // if successful match, return true
} else {
console.log(`Not a valid bingo! Keep trying!`);
return false; // if no match found, return false
}
} // end the (!isBingo) block
}
/* Assign drawnNumbers array position values vertical bingo pattern,
* then run checkLines function
*/
function checkVerticalBingo() { // checking for vertical bingo patterns here
// let bingoCheckCounter = 0; // Was for debugging purposes, can be removed
if(!isBingo) { // if isBingo == false, loop through array
for (let i = 0; i < 5; i++) { // for 0 - 4 positions, assign sq variables
var sq1 = bingoCard[i]; // for i = 0, => 0, 1, 2, 3, 4,
var sq2 = bingoCard[i + 5]; // for i = 1, => 5, 6, 7, 8, 9
var sq3 = bingoCard[i + 10]; // for i = 2, => 10, 11, 12, 13, 14
var sq4 = bingoCard[i + 15]; // for i = 3, => 15, 16, 17, 18, 19
var sq5 = bingoCard[i + 20]; // for i = 4, => 20, 21, 22, 23, 24
// counting the number of times this for loop is firing
// bingoCheckCounter++; // Was for debugging purposes, can be removed
checkLines(sq1, sq2, sq3, sq4, sq5);
}
};
// console.log(`.:: DEBUG ::. the checkVerticalBingo fn was run ${bingoCheckCounter} times.`);
}
function checkHorizontalBingo() { // checking for horizontal bingo patterns here
// let bingoCheckCounter = 0; // Was for debugging purposes, can be removed
if(!isBingo) { // if isBingo == false, loop through array or continue to loop
j = 0;
for (let i = 0; i < 5; i++) {
switch(i) {
case 0: // check row 1
var sq1 = bingoCard[i];
var sq2 = bingoCard[i + 1];
var sq3 = bingoCard[i + 2];
var sq4 = bingoCard[i + 3];
var sq5 = bingoCard[i + 4];
break;
case 1: // check row 2
var sq1 = bingoCard[i + 4];
var sq2 = bingoCard[i + 5];
var sq3 = bingoCard[i + 6];
var sq4 = bingoCard[i + 7];
var sq5 = bingoCard[i + 8];
break;
case 2: // check row 3
var sq1 = bingoCard[i + 8];
var sq2 = bingoCard[i + 9];
var sq3 = bingoCard[i + 10];
var sq4 = bingoCard[i + 11];
var sq5 = bingoCard[i + 12];
break;
case 3: // check row 4
var sq1 = bingoCard[i + 12];
var sq2 = bingoCard[i + 13];
var sq3 = bingoCard[i + 14];
var sq4 = bingoCard[i + 15];
var sq5 = bingoCard[i + 16];
break;
case 4: // check row 5
var sq1 = bingoCard[i + 16];
var sq2 = bingoCard[i + 17];
var sq3 = bingoCard[i + 18];
var sq4 = bingoCard[i + 19];
var sq5 = bingoCard[i + 20];
break;
}
// counting the number of times this function is being run
// bingoCheckCounter++; // Was for debugging purposes, can be removed
checkLines(sq1, sq2, sq3, sq4, sq5);
}
};
// console.log(`.:: DEBUG ::. the checkHorizontalBingo fn was run ${bingoCheckCounter} times.`);
}
function checkDiagonalBingo() {
// let bingoCheckCounter = 0; // Was for debugging purposes, can be removed
if(!isBingo) { // if isBingo == false, then loop through array
// loop through possible combinations
for (let i = 0; i < 2; i++) { // only two diagonal options can occur, limiting i < 2
switch(i) {
case 0: // upper left to lower right, only positions matter, order is irrelevant
var sq1 = bingoCard[0]; // for i = 0, => bingoCard array position 0
var sq2 = bingoCard[6]; // for i = 0, => bingoCard array position 6
var sq3 = bingoCard[12]; // for i = 0, => bingoCard array position 12
var sq4 = bingoCard[18]; // for i = 0, => bingoCard array position 18
var sq5 = bingoCard[24]; // for i = 0, => bingoCard array position 24
break;
case 1: // lower left to upper right, only positions matter, order is irrelevant
var sq1 = bingoCard[4]; // for i = 1, => bingoCard array position 4
var sq2 = bingoCard[8]; // for i = 1, => bingoCard array position 8
var sq3 = bingoCard[12]; // for i = 1, => bingoCard array position 12
var sq4 = bingoCard[16]; // for i = 1, => bingoCard array position 16
var sq5 = bingoCard[20]; // for i = 1, => bingoCard array position 20
break;
}
// counting the number of times this function is being run
// bingoCheckCounter++; // Was for debugging purposes, can be removed
checkLines(sq1, sq2, sq3, sq4, sq5);
}
};
// console.log(`.:: DEBUG ::. the checkDiagonalBingo fn was run ${bingoCheckCounter} times.`);
}
function checkForBingo (bingoCard, drawnNumbers) {
// this code for debug purposes, you can remove.
// console.log('Bingo Card: ' + JSON.stringify(bingoCard));
// this code for debug purposes, you can remove.
console.log('Drawn Numbers: ' + JSON.stringify(drawnNumbers));
// execute checkBingo functions
checkDiagonalBingo();
checkHorizontalBingo();
checkVerticalBingo();
// return false;
}
// module.exports = checkForBingo;
// Test cases for BINGO function
checkForBingo(bingoCard, drawnNumbers);
// checkForBingo(bingoCard, drawnNumbers1); // should return win / true
// checkForBingo(bingoCard, drawnNumbers2); // should return win / true
// checkForBingo(bingoCard, drawnNumbers3); // should return win / true
// checkForBingo(bingoCard, drawnNumbers4); // should return win / true
// checkForBingo(bingoCard, drawnNumbers5); // should return false
|
/**
* @description: loader配置入口
*/
const HTMLLoader = require('./html')
const stylusLoader = require('./stylus')
const lessLoader = require('./less')
const sassLoader = require('./sass')
const cssLoader = require('./css')
const javascriptLoader = require('./javascript')
const pugLoader = require('./pug')
const imageLoader = require('./image')
const fontLoader = require('./font')
module.exports = [
HTMLLoader,
stylusLoader,
lessLoader,
sassLoader,
cssLoader,
javascriptLoader,
pugLoader,
imageLoader,
fontLoader
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.