text
stringlengths 7
3.69M
|
|---|
import Vue from 'vue'
import Buefy from 'buefy'
import 'buefy/lib/buefy.css'
import Router from 'vue-router'
import Index from '@/components/Index'
import Revenue from '@/components/Revenue'
import Expenses from '@/components/Expenses'
import Receivables from '@/components/Receivables'
import AddRevenue from '@/components/AddRevenue'
Vue.use(Buefy)
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Index',
component: Index
},
{
path: '/revenue',
name: 'Revenue',
component: Revenue
},
{
path: '/expenses',
name: 'Expenses',
component: Expenses
},
{
path: '/receivables',
name: 'Receivables',
component: Receivables
},
{
path: '/revenue/add-revenue',
name: 'AddRevenue',
component: AddRevenue
}
]
})
|
import React, {useEffect, useState} from 'react';
import { Autocomplete } from "@material-ui/lab";
import { Grid, FormControl, InputLabel, Select, TextField } from "@material-ui/core";
import { ChordLibrary } from "../GuitarUtil";
import { NATURALS, SHARPS } from "../GuitarUtil/Note";
const NOTE_OPTIONS = [...NATURALS, ...SHARPS].sort();
const ChordExplorer = (props) => {
const onSelection = props.onSelection || (() => {});
const library = ChordLibrary.standard();
const types = library.get_all_types();
const [note, setNote] = useState(NOTE_OPTIONS[0]);
const [chordType, setChordType] = useState(types[0]);
const [autocompleteValue, setAutocompleteValue] = useState(`${note}${chordType}`)
const chords = library.get_all_by_root_and_name(note, chordType, false);
const shapeNames = chords.map((chord) => chord.label);
const [chordShape, setChordShape] = useState(shapeNames[0])
const chord = chords.filter((chord) => chord.label === chordShape)[0];
const handleChangeAutocompleteBox = (ignoreMe, fullName) => {
let newRoot, newChordType;
if (!fullName) {
// User hit clear, don't change anything yet
return;
}
if (fullName[1] === "#" || fullName[1] === "b") {
newRoot = fullName.substring(0, 2);
newChordType = fullName.substring(2);
} else {
newRoot = fullName.substring(0, 1);
newChordType = fullName.substring(1);
}
setNote(newRoot);
setChordType(newChordType);
setChordShape(library.get_all_by_root_and_name(newRoot, newChordType, false)[0].label)
setAutocompleteValue(fullName);
}
const handleChangeRoot = (event) => {
setNote(event.target.value);
setAutocompleteValue(`${event.target.value}${chordType}`);
}
const handleChangeChordType = (event) => {
setChordType(event.target.value);
setChordShape(library.get_all_by_root_and_name(note, event.target.value, false)[0].label)
setAutocompleteValue(`${note}${event.target.value}`);
}
const handleChangeChordName = (event) => {
setChordShape(event.target.value);
}
useEffect(() => {
onSelection(chord);
}, [note, chordType, chordShape]);
return (
<Grid container direction="column" spacing={2} alignContent="stretch">
<Grid container item direction="row" justify="flex-start">
<FormControl>
<InputLabel shrink htmlFor="select-root">
Root
</InputLabel>
<Select
native
value={note}
onChange={handleChangeRoot}
inputProps={{id: "select-root"}}
>
{NOTE_OPTIONS.map((newRoot) => (<option key={newRoot} value={newRoot}>{newRoot}</option>))}
</Select>
</FormControl>
<FormControl>
<InputLabel shrink htmlFor="select-chord-type">
Chord
</InputLabel>
<Select
native
value={chordType}
onChange={handleChangeChordType}
inputProps={{id: "select-chord-type"}}
>
{types.map((type) => (<option key={type} value={type}>{type}</option>))}
</Select>
</FormControl>
<FormControl>
<InputLabel shrink htmlFor="select-chord-shape">
Shape
</InputLabel>
<Select
native
value={chordShape}
onChange={handleChangeChordName}
inputProps={{id: "select-chord-shape"}}
>
{shapeNames.map((shapeName) => (<option key={shapeName} value={shapeName}>{shapeName}</option>))}
</Select>
</FormControl>
</Grid>
<Grid item>
<Autocomplete
autoComplete={true}
autoSelect={true}
value={autocompleteValue}
id="type-in-chord"
onChange={handleChangeAutocompleteBox}
options={library.get_autocomplete_dictionary()}
renderInput={(params) => {
return <TextField {...params} label="...Or Type A Chord By Name" variant="outlined" />
}} />
</Grid>
</Grid>
)
}
export default ChordExplorer
|
import React from 'react';
import {Row, Col, Button, Form, FormGroup, FormControl, ControlLabel} from 'react-bootstrap'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { addNewUser } from '../../actions/usersActions';
import {validateName, validateEmail, validatePassword} from '../../helpers/validationHelper';
class SignUp extends React.Component{
constructor(props){
super(props);
this.state = { name: '', email: '', password: ''}
}
renderFieldGroup = (fieldName, type, label, validationResult) =>{
return (
<FormGroup controlId={fieldName}
validationState={validationResult ? 'error' : 'success'}
>
<ControlLabel>{label}</ControlLabel>
<FormControl type={type}
placeholder={label}
value={this.state[fieldName]}
onChange={(e) => this.onInputChange(e.target.value, fieldName)} />
<div className="error">{validationResult}</div>
</FormGroup>
)
};
signup = (e) => {
e.preventDefault();
let {name, email, password } = this.state;
let hasError = validateName(name) + validateEmail(email) + validatePassword(password);
if(!hasError){
let user ={
name: name,
email: email,
password: password
};
this.props.addNewUser(user);
this.props.history.push("/login");
}
};
onInputChange(value, field){
this.setState({[field]: value});
}
render(){
const {name, email, password} = this.state;
return (<Row><Col className="user-register-container" sm={6} smOffset={3}>
<Form horizontal>
{this.renderFieldGroup("name","text","Name",validateName(name))}
{this.renderFieldGroup("email","email","Email",validateEmail(email))}
{this.renderFieldGroup("password","password","Password",validatePassword(password))}
<FormGroup>
<Button type="submit" bsStyle="info" onClick={this.signup}>Sign up</Button>
</FormGroup>
</Form>
</Col></Row>
)}
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators({ addNewUser }, dispatch)
}
}
export default connect(mapDispatchToProps, {addNewUser})(SignUp);
|
import React from 'react';
import { Grid, Typography } from '@material-ui/core';
import PokemonCard from './PokemonCard';
function PokemonList(props) {
return (
<Grid container spacing={2}>
<Grid item>
<Typography>{`${props.result.length} Pokémon found`}</Typography>
</Grid>
<Grid container justify="space-evenly" item spacing={1} style={{maxHeight:"80vh", overflowY:"auto"}}>
{
props.result?.map((pokemon) =>
<PokemonCard
key={pokemon.name}
pokemon={pokemon}
setLoading={props.setLoading}
setSelectedPokemon={props.setSelectedPokemon}
/>
)
}
</Grid>
</Grid>
);
}
export default PokemonList;
|
// https://leetcode.com/problems/decode-string/
/**
* @param {string} s
* @return {string}
*/
var decodeString = function(s) {
let foundACode = true;
let res = s;
let tempRes = '';
let nums = '0123456789';
let i = 0;
while (foundACode) {
foundACode = false;
console.log(res);
while (i < res.length) {
// console.log(tempRes);
if (nums.includes(res[i])) {
foundACode = true;
let currentNum = res[i];
i++;
while (nums.includes(res[i])) {
currentNum += res[i];
i++;
};
currentNum = parseInt(currentNum);
i++;
let subStr = '';
let bracketCount = 1;
while (bracketCount !== 0) {
if (res[i] === "]") {
if (bracketCount === 1) break;
bracketCount--;
} else if (res[i] === "[") {
bracketCount++;
}
subStr += res[i];
i++;
}
for (let j = 0; j < currentNum; j++) {
tempRes += subStr;
}
i++;
} else {
tempRes += res[i];
i++;
}
}
res = tempRes;
tempRes = '';
i = 0;
}
return res;
};
// const translate = subStr => {
// let i = 0;
// let currentNum = subStr[i];
// let res = '';
// i++;
// while (nums.includes(subStr[i])) {
// currentNum += subStr[i];
// i++;
// };
// currentNum = parseInt(currentNum);
// i++;
// let subStr = '';
// while (subStr[i] !== "]") {
// subStr += subStr[i];
// i++;
// }
// for (let j = 0; j < currentNum; j++) {
// res += subStr;
// }
// i++;
// }
const s1 = "3[a]2[bc]" // "aaabcbc".
const s2 = "3[a2[c]]" // "accaccacc".
const s3 = "2[abc]3[cd]ef" // "abcabccdcdcdef".
const s4 = "100[leetcode]";
const s5 = "3[a10[bc]]";
console.log(decodeString(s1));
console.log(decodeString(s2));
console.log(decodeString(s3));
console.log(decodeString(s4));
console.log(decodeString(s5));
|
const express = require('express');
// /api/users
var userRoutes = express.Router();
userRoutes.post("/create", function(req, res) {});
userRoutes.put("/:_id", function(req, res) {});
userRoutes.delete("/:_id", function(req, res) {});
userRoutes.get("/:_id", function(req, res) {});
module.exports = userRoutes;
|
import validator from 'validator';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import mongoose from 'mongoose';
import sendEmailInvite from './../utils/sendEmail';
const secret = process.env.SECRET_TOKEN;
/**
* Module dependencies.
*/
// TODO: Add/Import Email Helper Method and Libraries
const avatars = require('./avatars').all();
// import avatars from './avatars';
// avatar.all();
const User = mongoose.model('User');
// const mongoose = require('mongoose'),
// User = mongoose.model('User');
/**
* Signup a new user
* @param {object} req The user's information
* @param {object} res The server's response
* @param {object} next The server's response
* @returns {object} The server's response
*/
exports.authCallback = function (req, res, next) {
res.redirect('/chooseavatars');
};
/**
* Signup a new user
* @param {object} req The user's information
* @param {object} res The server's response
* @returns {object} The server's response
*/
exports.signin = function (req, res) {
if (!req.user) {
res.redirect('/#!/signin?error=invalid');
} else {
res.redirect('/#!/app');
}
};
/**
* Signup a new user
* @param {object} req The user's information
* @param {object} res The server's response
* @returns {object} The server's response
*/
exports.signup = function (req, res) {
if (!req.user) {
res.redirect('/#!/signup');
} else {
res.redirect('/#!/app');
}
};
/**
* Signup a new user
* @param {object} req The user's information
* @param {object} res The server's response
* @returns {object} The server's response
*/
exports.signout = function (req, res) {
req.logout();
res.redirect('/');
};
/**
* Signup a new user
* @param {object} req The user's information
* @param {object} res The server's response
* @returns {object} The server's response
*/
exports.session = function (req, res) {
res.redirect('/');
};
/**
* Check Avartar
* @param {object} req The user's information
* @param {object} res The server's response
* @returns {object} The server's response
*/
exports.checkAvatar = function (req, res) {
if (req.user && req.user._id) {
User.findOne({
_id: req.user._id
})
.exec((err, user) => {
if (user.avatar !== undefined) {
res.redirect('/#!/');
} else {
res.redirect('/#!/choose-avatar');
}
});
} else {
// If user doesn't even exist, redirect to /
res.redirect('/');
}
};
/**
* Signup a new user
* @param {object} req The user's information
* @param {object} res The server's response
* @returns {object} The server's response
*/
exports.create = (req, res) => {
if (
req.body.name &&
req.body.name.trim() &&
req.body.password &&
req.body.password.length > 7 &&
req.body.email &&
validator.isEmail(req.body.email)
) {
User.findOne({
email: req.body.email
}).exec((err, existingUser) => {
if (existingUser) {
return res.status(400).send({
success: false,
error: 'existingUser',
message: 'A user already exists with that mail'
});
}
const user = new User(req.body);
// Switch the user's avatar index to an actual avatar url
user.avatar = avatars[user.avatar];
user.provider = 'local';
user.save((err) => {
if (err) {
return res.status(400).send({
success: false,
message: 'an error occured while trying to save the user'
});
}
// sign token
const token = jwt.sign({
name: user.name,
email: user.email,
id: user._id
}, secret);
// login user
return res.status(200).send({
success: true,
id: user._id,
name: user.name,
email: user.email,
token
});
});
});
} else {
return res.status(400).send({
success: false,
error: 'invalid',
message: 'Invalid Credentials'
});
}
};
/**
* Login a user
* @param {object} req The user's information
* @param {object} res The server's response
* @returns {object} The server's response
*/
exports.login = (req, res) => {
if (
req.body.email &&
req.body.password
) {
User.findOne({
email: req.body.email
}).exec((err, user) => {
// if an error occurs when finding user
if (err) {
return res.status(400).send({
success: false,
error: 'invalid'
});
}
// if no user exists
if (!user) {
return res.status(400).send({
success: false,
error: 'invalid'
});
}
// compare passwords
if (!bcrypt.compareSync(req.body.password, user.hashed_password)) {
return res.status(400).send({
success: false,
error: 'invalid'
});
}
// sign token
const token = jwt.sign({
name: user.name,
email: user.email,
id: user._id
}, secret);
// login user
return res.status(200).send({
success: true,
id: user._id,
name: user.name,
email: user.email,
token
});
});
} else {
return res.status(400).send({
success: false,
error: 'invalid',
message: 'Invalid Credentials'
});
}
};
/**
* Login a user
* @param {object} req The user's information
* @param {object} res The server's response
* @returns {object} The server's response
*/
exports.retrieveDonation = (req, res) => {
const email = jwt.decode(req.headers.token).email;
User.find({ email }).select('-_id').exec((err, user) => {
if (err) {
res.render('error', {
status: 500
});
} else {
res.json(user[0].donations);
}
});
};
/**
* Avartar
* @param {object} req The user's information
* @param {object} res The server's response
* @returns {object} The server's response
*/
exports.avatars = function (req, res) {
// Update the current user's profile to include the avatar choice they've made
if (req.user && req.user._id && req.body.avatar !== undefined &&
/\d/.test(req.body.avatar) && avatars[req.body.avatar]) {
User.findOne({
_id: req.user._id
})
.exec((err, user) => {
user.avatar = avatars[req.body.avatar];
user.save();
});
}
return res.redirect('/#!/app');
};
exports.addDonation = function (req, res) {
if (req.body && req.user && req.user._id) {
// Verify that the object contains crowdrise data
if (req.body.amount && req.body.crowdrise_donation_id && req.body.donor_name) {
User.findOne({
_id: req.user._id
})
.exec((err, user) => {
// Confirm that this object hasn't already been entered
let duplicate = false;
for (let i = 0; i < user.donations.length; i += 1) {
if (
user.donations[i].crowdrise_donation_id ===
req.body.crowdrise_donation_id
) {
duplicate = true;
}
if (!duplicate) {
user.donations.push(req.body);
user.premium = 1;
user.save();
}
}
});
}
res.send();
}
};
/**
* show a user
* @param {object} req The user's information
* @param {object} res The server's response
* @returns {object} The server's response
*/
exports.show = function (req, res) {
const user = req.profile;
res.render('users/show', {
title: user.name,
user
});
};
/**
* me
* @param {object} req The user's information
* @param {object} res The server's response
* @returns {object} The server's response
*/
exports.me = function (req, res) {
res.jsonp(req.user || null);
};
/**
* User
* @param {object} req The user's information
* @param {object} res The server's response
* @param {object} next The next action
* @param {object} id The user id
* @returns {object} The server's response
*/
exports.user = (req, res, next, id) => {
User
.findOne({
_id: id
})
.exec((err, user) => {
if (err) return next(err);
if (!user) return next(new Error(`Failed to load User + ${id}`));
req.profile = user;
next();
});
};
// Search all Users registered in app
module.exports.search = (req, res) => {
const searchQuery = req.query.name;
User.find({ name: { $regex: `.*${searchQuery}.*` } })
.select('name email')
.then((allUsers) => {
res.status(200)
.json(allUsers);
}).catch((error) => {
res.status(500)
.json({ message: 'An error Occured', error });
});
};
// module.exports.allUsers = (req, res) => {
// // get all the users from mongoDB
// User.find({}, (err, users) => {
// if (err) {
// return res.json({ err });
// }
// return res.json(users);
// });
// };
// Get all user in the datatabase
// module.exports.allUsers = (req, res, next) => {
// if (req.user) {
// // get all the users from mongoDB except current user
// User.find({ $ne: { email: req.user.email } })
// .select('name email')
// // .exec((err, allUsers) => {
// // if (err) return res.json({ err });
// // if (!allUsers) return next(new Error('Failed to load Users'));
// // return res.json(allUsers);
// // });
// .then(allUsers => res.status(200).json(allUsers))
// .catch((error) => {
// res.status(400).json({ message: 'An Error Occured', error });
// });
// }
// };
// send invites as email to users who are not friends
module.exports.sendInviteAsEmail = (req, res) => {
if (req.user) {
const url = decodeURIComponent(req.body.gameUrl);
const guestUser = req.body.userEmail;
if (guestUser !== null && url !== null) {
sendEmailInvite(guestUser, url);
res.status(200)
.json(guestUser);
} else {
res.status(400)
.send('Bad Request !');
}
} else {
res.status(401)
.send('Hey Kindly Login first!');
}
};
// send invitation to user as in-app notification
// module.exports.invitePlayers = (req, res) => {
// console.log('===> inviting User');
// };
// add user as friend
// sendInvites to friends in-app
|
import React from 'react';
import * as T from 'prop-types';
import CapacityTitle from './CapacityTitle';
import styles from './HeroesStyle.css';
const INITIAL_STATE = {
inputName: '',
}
const makeOptions = num => {
const elements = [];
for (let i = 0; i <= num; i += 1) {
elements.push(
<option key={i} value={i}>
{i}
</option>,
);
}
return elements;
};
this.state = {
...INITIAL_STATE
};
const ChooseCapacity = ({inputName, onInputChange, value}) => (
<div className={styles.form}>
<CapacityTitle value={inputName} />
<select
name={inputName}
value={ value }
onChange={onInputChange}
>
{makeOptions(10)}
</select>
</div>
);
ChooseCapacity.propTypes = {
inputName: T.string.isRequired,
onInputChange: T.func.isRequired,
value: T.number.isRequired
}
export default ChooseCapacity;
|
import React, { useState, useEffect, useCallback, useRef } from 'react';
import axios from 'axios';
import './List.scss';
const List = ({ changeCount }) => {
const [items, setItems] = useState([]);
// const [page, setPage] = useState(1);
let page = useRef(1);
const getItems = async () => {
try {
const res = await axios.get(
`https://node.wingeat.com/test-api/items?page=${page.current}`
);
setItems((prev) => prev.concat(res.data));
} catch (e) {
console.log(e);
}
};
useEffect(() => {
getItems();
}, []);
const onClick = ({ itemName, price, image, id }) => {
const itemList = JSON.parse(localStorage.getItem('items'));
let isExist = false;
let update = [];
if (itemList) {
for (let i = 0; i < itemList.length; i++) {
if (itemList[i].id === id) {
isExist = true;
update = [
...update,
{ ...itemList[i], amount: itemList[i].amount + 1 },
];
} else {
update = [...update, { ...itemList[i] }];
}
}
}
if (!isExist) {
update.push({ itemName, price, image, id, amount: 1 });
}
localStorage.setItem('items', JSON.stringify(update));
changeCount(update.length);
alert('상품이 추가되었습니다.');
};
const infiniteScroll = useCallback(() => {
const scrollHeight = Math.max(
document.documentElement.scrollHeight,
document.body.scrollHeight
);
const scrollTop = Math.ceil(
Math.max(document.documentElement.scrollTop, document.body.scrollTop)
);
const clientHeight = document.documentElement.clientHeight;
if (scrollTop + clientHeight >= scrollHeight) {
if (page.current < 6) {
page.current = page.current + 1;
getItems();
}
}
}, []);
useEffect(() => {
window.addEventListener('scroll', infiniteScroll);
return () => {
window.removeEventListener('scroll', infiniteScroll);
};
}, [infiniteScroll]);
return (
<>
<div className="title">
<h1>윙잇 MADE</h1>
</div>
<div className="list">
{items
? items.map((item) => (
<div key={item.id} className="list-item">
<img
src={`https://image.wingeat.com/${item.image}`}
alt="item-img"
onClick={() => onClick(item)}
/>
<div className="item-name">{item.itemName}</div>
<div className="item-price">
{item.price.toLocaleString()}원
</div>
</div>
))
: null}
</div>
</>
);
};
export default List;
|
var fleetCommanderServices = angular.module('fleetCommanderServices', [ 'ngResource' ]);
fleetCommanderServices.factory('GamesService', [ '$http', function($http) {
return {
create : function(playerName) {
return $http({
method : 'POST',
url : 'api/games',
data : {
'playerName' : playerName
}
});
},
join : function(playerName, joinCode) {
return $http({
method : 'POST',
url : 'api/games',
data : {
'playerName' : playerName,
'joinCode' : joinCode
}
});
},
get : function(gameId, token) {
return $http({
method : 'GET',
url : 'api/games/' + gameId,
headers : {
'Authorization' : 'Bearer ' + token
}
});
},
quit : function(gameId, token) {
return $http({
method : 'DELETE',
url : 'api/games/' + gameId,
headers : {
'Authorization' : 'Bearer ' + token
}
});
},
start : function(gameId, token) {
return $http({
method : 'POST',
url : 'api/games/' + gameId,
headers : {
'Authorization' : 'Bearer ' + token
},
data : {
isStarted : true
}
});
}
};
} ]);
fleetCommanderServices.factory('JoinCodesService', [ '$http', function($http) {
return {
create : function(gameId, token) {
return $http({
method : 'POST',
url : 'api/games/' + gameId + '/joinCodes',
headers : {
'Authorization' : 'Bearer ' + token
}
});
},
getAllActive : function(gameId, token) {
return $http({
method : 'GET',
url : 'api/games/' + gameId + '/joinCodes',
headers : {
'Authorization' : 'Bearer ' + token
}
});
}
};
} ]);
fleetCommanderServices.factory('PlayersService', [ '$http', function($http) {
return {
addComputerPlayer : function(gameId, token) {
return $http({
method : 'POST',
url : 'api/games/' + gameId + '/players',
headers : {
'Authorization' : 'Bearer ' + token
}
});
}
};
} ]);
fleetCommanderServices.factory('TurnsService', [ '$http', function($http) {
return {
endTurn : function(gameId, token) {
return $http({
method : 'POST',
url : 'api/games/' + gameId + '/turns',
headers : {
'Authorization' : 'Bearer ' + token
}
});
}
};
} ]);
fleetCommanderServices.factory('PlanetsService', [ '$http', function($http) {
return {
buildFactory : function(gameId, token, planetId) {
return $http({
method : 'POST',
url : 'api/games/' + gameId + '/universe/planets/' + planetId + '/factories',
headers : {
'Authorization' : 'Bearer ' + token
}
});
},
changeProductionFocus : function(gameId, token, planetId, focus) {
return $http({
method : 'POST',
url : 'api/games/' + gameId + '/universe/planets/' + planetId,
headers : {
'Authorization' : 'Bearer ' + token
},
data : {
productionFocus : focus
}
});
}
};
} ]);
fleetCommanderServices.factory('ShipsService', [ '$http', function($http) {
return {
sendShips : function(gameId, token, ships, origin, dest) {
return $http({
method : 'POST',
url : 'api/games/' + gameId + '/universe/travellingShipFormations',
headers : {
'Authorization' : 'Bearer ' + token
},
data : {
'shipCount' : ships,
'originPlanetId' : origin,
'destinationPlanetId' : dest
}
});
}
};
} ]);
|
const dotenv = require('dotenv');
const mongoose = require('mongoose');
// Allow server to read from .env file
dotenv.config();
const app = require('./app');
// Connect to DB
mongoose
.connect(process.env.DB_URL, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
})
.then(() => {
console.log('[+]..Connected to DB');
})
.catch((error) => {
console.log(error);
});
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log(`Server is running on port : ${port}`);
});
|
import config from './config';
let ChoiceQueryAPI = (words) => {
let url = config.API_URL + '/search/choice?choice_one=' + words.word1 + '&choice_two=' + words.word2;
let token = localStorage.getItem('token');
return fetch(url, {
method: 'GET',
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer" + " " + token
}
})
.then((res) => {
return res.json();
})
.catch((error) => {
console.log('API ChoiceQueryAPI.js: ', error);
});
}
export default ChoiceQueryAPI;
|
function uint8( data ){
let len = data.length;
let out = new Uint8Array( len );
if( typeof data == "string" ){
for( let i=0; i<len; ++i )
out[i] = data.charCodeAt(i);
}else
out.set( data );
return out;
}
function BYTE( ...args ){
let out = new Uint8Array( args.length );
out.set( args );
return out;
}
function WORD( ...args ){
let tmp = new Uint16Array( args.length );
tmp.set( args );
let out = new Uint8Array( tmp.buffer );
return out;
}
class gif1b {
constructor(){
}
add( data, time ){
if( !this.blocks ){
let packed = 0x80,
bg = 0,
ratio = 0;
this.blocks = [
uint8("GIF87a"),
WORD( data.width, data.height ),
BYTE(
packed, bg, ratio,
0, 0, 0,
0xFF, 0xFF, 0xFF,
0x21, 0xFF, 0x0B
),
uint8("NETSCAPE2.0"),
BYTE(0x03, 0x01, 0, 0, 0)
];
}
time = Math.round(time|0) || 1;
this.blocks.push(
BYTE(0x21, 0xF9, 0x04, 0x04),
WORD( time/10, 0 )
);
this.blocks.push( BYTE(0x2C),
WORD(0, 0, data.width, data.height),
BYTE(0, 2)
);
this.lzw( data.data, data.width );
}
lzw( data, width ){
var out;
const CC = 4, EOI = 5;
var nc = 0, op = 0, opoff = 0, bits = 3;
var table, string;
let end = () => {
out[0] = op-1;
// op++;
this.blocks.push( out.slice(0, op) );
}
function init(){
let needsCC = !!out;
if( out ){
// write(table[CC], 0);
end();
}
out = new Uint8Array(256);
nc = 0;
table = [];
string = table;
table[0] = [,,nc++];
table[1] = [,,nc++];
table[2] = [];
table[3] = [];
table[CC] = [,,CC];
table[EOI] = [,,EOI];
nc = CC+2;
op = 0;
opoff = 0;
out[op++] = 0;
write(table[CC], 0);
}
for( let i=0; i<data.length; i+=4 ){
if( !out || ((op > 128 || bits>11) && !((bits+opoff)%8)) ){
if( string )
write( string, 0 );
init();
}
let ch = data[i+3] > 128 ? 1 : 0;
if( string[ch] )
string = string[ch];
else
write( string, ch );
}
write( string, 0 );
op++;
end();
this.blocks.push( BYTE(0) );
function mask( bits ){
return ((~0)>>>(31-(bits-1)));
}
function write( arr, next ){
if( arr == table )
return;
let code = arr[2]|0;
// console.log( code );
out[op] |= code << opoff;
opoff += bits;
while( opoff >= 8 ){
opoff -= 8;
op++;
out[op] = code >>> (bits - opoff);
}
if( nc == mask(bits)+1 )
bits++;
if( arr != table[CC] ){
arr[next] = [,,nc++];
string = table[ next ];
}else{
string = table;
bits = 3;
}
}
}
write(){
let sum = 1;
for( let i=0, l=this.blocks.length; i<l; ++i )
sum += this.blocks[i].length;
let acc = new Uint8Array(sum);
sum = 0;
for( let i=0, l=this.blocks.length; i<l; ++i ){
acc.set( this.blocks[i], sum );
sum += this.blocks[i].length;
}
acc[ sum ] = 0x3B; // trailer
return acc;
}
}
if( typeof module !== "undefined" )
module.exports = gif1b;
|
import React from 'react';
import logo from '../img/logo.png';
import './Header.css';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
function Header() {
return (
<div className="header">
<div className="header__right">
<img src={logo} alt='Hello Fresh logo' className='header__rightLogo'/>
<div className='header__rightContent'>
<div className='header__rightContentText'>Our Recipe Boxes</div>
<div className='header__rightContentText dropdown' >How it Works
<div className='dropDownContent'>
<p>How it Works</p>
<p>Sustainability</p>
<p>CO2 Neutral</p>
</div>
<div className='dropDownArrow' >
<ExpandMoreIcon />
</div>
</div>
<div className='header__rightContentText dropdown'>Our Recipes
<div className='dropDownContent'>
<p>Our Menu</p>
<p>Recipe hub</p>
</div>
<div className='dropDownArrow' >
<ExpandMoreIcon />
</div>
</div>
<div className='header__rightContentText'>Gift Cards</div>
</div>
</div>
<div className="header__left">
<div className='header_leftLogin'>
<button className='header_leftLoginButton'>Log in</button>
</div>
</div>
</div>
)
}
export default Header
|
module.exports = {
pluginConfig: {},
registerConfig: {
routes: {
prefix: '/demo/'
}
}
}
|
const bcrypt = require('bcryptjs');
module.exports = {
register: (req, res) => {
const db = req.app.get('db');
const { session } = req;
const { name, username, email, password } = req.body;
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(password, salt, async (err, hash) => {
try {
let user = await db.register({ name, username, email, password: hash });
user = user[0]
session.user = user;
res.status(200).send(user[0]);
} catch (err) {
res.sendStatus(500);
}
})
})
},
login: async (req, res) => {
const db = req.app.get('db');
const { session } = req;
const { username, password } = req.body;
try {
let user = await db.login({ username });
user = user[0];
if (user) {
bcrypt.compare(password, user.password, (err, answer) => {
if (answer) {
session.user = user;
res.status(200).send(user);
} else {
res.sendStatus(401);
}
})
} else {
res.sendStatus(401);
}
} catch (err) {
res.sendStatus(500);
}
},
logout: (req, res) => {
req.session.destroy();
res.sendStatus(200);
}
}
|
import React, { useEffect, useState } from 'react'
import IdeaList from '../IdeaList/IdeaList'
const Home = () => {
const [ideas, setIdeas] = useState(null);
const [isPending, setPending ] = useState(true)
useEffect(() => {
fetch('http://localhost:8000/ideas' )
.then((res) => res.json())
.then(data => {
setIdeas(data)
setPending(false)
})
.catch( erorr => {
console.log(erorr.message)
})
},[])
return (
<div className="home">
{isPending && <p>Loading....</p> }
{ ideas && <IdeaList ideas={ideas} title=" The Ideas " />}
</div>
)
}
export default Home
|
/*
* Jump to selected section:
*/
function goToSection(evt) {
//using event.target to know which section to go
let toGo = document.querySelectorAll('[data-nav=\"' + evt.target.getAttribute('data-nav') + '\"]');
toGo[1].scrollIntoView({ block: 'start', behavior: 'smooth' });
}
/*
* Build Navigation Bar Dynamicly:
*/
function buildNavigationBar() {
let pageSections = document.getElementsByTagName('section');
let mainUl = document.getElementById('navbar__list');
let fragment = document.createDocumentFragment();
for (const sec of pageSections) {
const secTitle = sec.getAttribute("data-nav");
const listItem = document.createElement('LI');
const htmlText = '<a data-nav=\"' + secTitle + '\">' + secTitle + '</a>';
listItem.insertAdjacentHTML('beforeend', htmlText);
listItem.addEventListener('click', goToSection);
//using DocumentFragment because appendChild is a expensive proccess, for better performance
fragment.appendChild(listItem);
}
//painting and reflow happens only one time after the loop
mainUl.appendChild(fragment);
}
/*
* Setting active section and active list title on scrolling:
*/
window.addEventListener('scroll', function () {
let pageSections = document.getElementsByTagName('section');
for (const sec of pageSections) {
let liElement = document.querySelector('[data-nav=\"' + sec.getAttribute('data-nav') + '\"]');
if (sec.getBoundingClientRect().y < 300 && sec.getBoundingClientRect().y > -300) {
sec.classList.add('your-active-class');
liElement.classList.add('your-active-class');
} else {
sec.classList.remove('your-active-class');
liElement.classList.remove('your-active-class');
}
}
//Display top btn when scrolled down
if (document.documentElement.scrollTop > 300) {
topButton.style.display = "block";
} else {
topButton.style.display = "none";
}
});
/*
* back to top btn and function:
*/
topButton = document.getElementById("top_btn");
topButton.addEventListener('click',function(){
window.scrollTo({top: 0, behavior: 'smooth'});
});
/*
* Calling Functions:
*/
buildNavigationBar();
|
/**
* Display information about relevant CSS attributes to users
*/
let $ = require("jquery");
let Plugin = require("../base");
let annotate = require("../shared/annotate")("labels");
let el2Partition = require("./filterCss");
let _ = require("lodash");
let propListTemplate = require("./prop-list.handlebars");
require("./style.less");
class A11yTextWand extends Plugin {
getTitle() {
return "Highlight Elements";
}
getDescription() {
return "Hover over elements to view their CSS";
}
// Takes an object of properties,
// creates a Handlebars context,
// evaluates the template and returns the HTML
propList(props) {
return propListTemplate({
props: props,
});
}
run() {
const that = this;
let $highlight;
// Provide a fake summary to force the info panel to render
// this.summary(" ");
// When CONTAINERS_ONLY is active,
// highlighting and clicking will only work on:
// div, section, article, aside, nav, header,
// footer, and menu elements
const CONTAINERS = [
"div",
"section",
"article",
"aside",
"nav",
"header",
"footer",
"menu",
"li",
];
// Mousemove handler controls highlighting behavior
$(document).on("mousemove.wand", function(e) {
const currentEl = document.elementFromPoint(e.clientX, e.clientY);
const tag = _.toLower(currentEl.tagName);
const CONTAINERS_ONLY = that.selectionMode === "BLOCK";
// Don't outline something if it's part of the app,
// or not a container element when CONTAINERS_ONLY is true
const invalidTarget = _.some([
_.includes(currentEl.tagName, "body"),
CONTAINERS_ONLY && !_.includes(CONTAINERS, tag),
_.includes(currentEl.className, "tota11y")
]);
// Outline the element currently being hovered over
if (!invalidTarget) {
$(".tota11y-outlined").removeClass("tota11y-outlined");
$(currentEl).addClass("tota11y-outlined");
// console.log(currentEl);
}
});
// Click handler gets and displays CSS information
$(document).on("click", ".tota11y-outlined", function(e) {
// Prevent default if we clicked the application
const isApp = this.className.indexOf("tota11y") !== -1;
const hasOutline = this.className.indexOf("tota11y-outlined") !== -1;
// Continue iff the element is outlined
if (!hasOutline) {
return true;
} else {
e.stopPropagation();
}
// After we stop propagating, set clickedEl
const clickedEl = this;
const $el = $(clickedEl);
console.log(clickedEl);
// Control highlighting
if ($highlight) {
$highlight.remove();
}
$highlight = annotate.highlight($el);
const partition = el2Partition(clickedEl);
const propTypeOrder = [
"position",
"box_model",
"typography",
"visual",
"misc"
];
// Iterate over partition classes in the above order.
// For each, we create the Handlebars ul,
// and pass it to the base Plugin error handler using
// the propList method.
let propObjList = [];
propTypeOrder.forEach(function (type) {
const props = partition[type];
if (Object.keys(props).length > 0) {
const title = type.replace("_", " "); // TODO: change this
// Evaluate the prop list template
let $list = $(this.propList(props));
const prediction = {"2":["overflow","display","min-height","background-color","text-align","margin-left","width","left","height","position","margin-bottom","bottom","min-width","text-indent","margin","vertical-align","top","margin-top","right","margin-right","z-index"],"3":["background-size","background-attachment","background-position","background","background-repeat","background-image"]};
// // Add "priority: med"
// prediction["2"].forEach(function (propName) {
// $list.find("li").each(function (index) {
// const txt = $(this).find(".style-list-property").text().slice(0, -1);
// if (prediction["2"].indexOf(txt) !== -1) {
// $(this).addClass("priority-med");
// console.log($(this));
// }
// });
// });
// Add "priority: high"
prediction["3"].forEach(function (propName) {
$list.find("li").each(function (index) {
const txt = $(this).find(".style-list-property").text().slice(0, -1);
if (prediction["3"].indexOf(txt) !== -1) {
$(this).addClass("priority-high");
}
});
});
const propObj = { title, $list, $el };
propObjList.push(propObj);
}
}, that);
let propEntries = that.props(propObjList);
// propEntries.forEach((entry) => {
// if (entry) {
// const context = [entry.$el, "", entry.title, entry];
// annotate.errorLabel(...context);
// // Highlight the current element on the page
// const highlight = annotate.highlight(entry.$el);
// }
// });
// Render updates
that.panel.render();
// const styleStrings = "";
// // Populate the info panel
// if (!styleStrings) {
// $(".tota11y-info-section.active").html(
// <i className="tota11y-nothingness">
// Nothing available
// </i>
// );
// } else {
// // Place an error label on the element and register it as an
// // error in the info panel
// // let entry = this.error(title, $(this.errorMessage($el)), $el);
// // annotate.errorLabel($el, "", title, entry);
// $(".tota11y-info-section.active").html(
// styleStrings
// );
// }
});
}
cleanup() {
$(".tota11y-outlined").removeClass("tota11y-outlined");
$(document).off("mousemove.wand");
$(document).off("click.wand");
}
}
module.exports = A11yTextWand;
|
import gifActions from '../../actions/gifActions';
// import favoriteAc from '../../src/actions/favoriteActions';
describe('Test gifActions', () => {
it('actionCreator: failedSearchGifs', () => {
expect(gifActions.creators.failedSearchGifs()).toEqual({ type: 'SEARCH_GIFS_FAILED' });
});
it('actionCreator: receivedSearchGifs', () => {
const receivedSearchGifsDefault = gifActions.creators.receivedSearchGifs();
expect(receivedSearchGifsDefault).toEqual({ type: 'SEARCH_GIFS_RECEIVED', payload: {} })
const receivedSearchGifs = gifActions.creators.receivedSearchGifs([]);
expect(receivedSearchGifs).toEqual({ type: 'SEARCH_GIFS_RECEIVED', payload: [] })
});
it('actionCreator: searchGifs', () => {
const searchGifsDefault = gifActions.creators.searchGifs();
expect(searchGifsDefault).toEqual({ type: 'SEARCH_GIFS_GET', payload: {} })
const searchGifs = gifActions.creators.searchGifs('dog');
expect(searchGifs).toEqual({ type: 'SEARCH_GIFS_GET', payload: 'dog' })
});
it('actionCreator: failedTrendingGifs', () => {
expect(gifActions.creators.failedTrendingGifs()).toEqual({ type: 'TRENDING_GIFS_FAILED' });
});
it('actionCreator: getTrendingGifs', () => {
expect(gifActions.creators.getTrendingGifs()).toEqual({ type: 'TRENDING_GIFS_GET' });
});
it('actionCreator: receivedTrendingGifs', () => {
const receivedTrendingGifsDefault = gifActions.creators.receivedTrendingGifs();
expect(receivedTrendingGifsDefault).toEqual({ type: 'TRENDING_GIFS_RECEIVED', payload: {} })
const receivedTrendingGifs = gifActions.creators.receivedTrendingGifs([]);
expect(receivedTrendingGifs).toEqual({ type: 'TRENDING_GIFS_RECEIVED', payload: [] })
});
});
|
import React, {useEffect, useState} from 'react';
import { useParams } from 'react-router';
import axios from 'axios';
const DisplayPage = () => {
// parameters that are coming from the route
const {category, id} = useParams();
// creating state variable that will store the information returned from the axios api call
const [info, setInfo] = useState({});
useEffect(() => {
axios.get(`https://swapi.dev/api/${category}/${id}/`)
.then(response => {
console.log(response)
setInfo(response.data)
})
.catch(error => console.log(error))
}, [category,id])
return (
<div>
{category == "people" ?
<>
<h3>{info.name}</h3>
<p>Height: {info.height}cm</p>
<p>Mass: {info.mass}kg</p>
<p>Hair Color: {info.hair_color}</p>
<p>Eye Color: {info.eye_color}</p>
</> :
category == "planets" ?
<>
<h3>{info.name}</h3>
<p>Climate: {info.climate}</p>
<p>Terrain: {info.terrain}</p>
<p>Diameter: {info.diameter}</p>
<p>Population: {info.population}</p>
</> :
<>
<h3>These aren't the droids you're looking for!</h3>
<p>Try searching for people or planets</p>
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAoHCBYWFRgVFhYVGBUaHBgaGBkaGBoYGBoYHBoaGhgaGBgcIy4lHB4rIRgYJjgmKy8xNTU1GiQ7QDs0Py40NTEBDAwMEA8QHxISHjQrJCs2NDE0NDQ0NDQ0NDQ0NDQ2NDQ0NDQ0NDQ0NDQ0NDU0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NP/AABEIAJ8BPgMBIgACEQEDEQH/xAAcAAABBQEBAQAAAAAAAAAAAAAAAQIEBQYDBwj/xAA4EAABAgQEAwUGBgIDAQAAAAABAAIDBBEhBRIxQQZRcSJhgaGxEzKRwdHwB1JicuHxI0IUM0Mk/8QAGgEAAgMBAQAAAAAAAAAAAAAAAAMBAgQFBv/EACkRAAIBBAICAQQBBQAAAAAAAAABAgMRITEEEhNBUQUiMnFhFCNCobH/2gAMAwEAAhEDEQA/APGUIQgAQhCABCEIAEoQgq0cZAWqKpEit2sQOBS+0KYhHkklZMLDsyXOmIQqkl7JH1QUxKCrKpfDIsIUIKEpkgurYbtgbpITKkBafDJSuyXKfUvCPYoWSjya5fouzcPcASW1K3sjhgOyv2YOzLTKKpaqNjfCeLRoBbr4LpITjoTg5p6jYhbziDAKgkBefzEEsdQpsZdkKlFxPRpWO17GvboQo2KSzXjK7R2/J2xHkqrhCaJa6GT7t29DqrucbVh7rql3GWC6yjCTku5jix2o8xzUcLS4xLe0ZnHvsF+9v8LObrrUqnlimzPKPV2ABBKCkWiTtgqhWhSpSFUqMxWsoxOoQ7SQqrLqi4wyXq4Ady9s4Iw/2cHMRd2nQLzHhSQL3tAGpAXtEd7YMEnQNb8kfVKrSjRW2c7j2lVlUeor/ZgfxDxOrsgNgKeO68smX1qtBxLOl73E6kklZSai8ltpxVChGJXjp1JOb23chTTxVQiV1jGtyuNVya87yOvCNkNN05NCe1qywvf9l2cUIQsZYEIQgAQEIUoBQkKcmlWegAoQhUAEIQgAQhCABCEIAEIQgCww9m/M+i2mDQdFkJH3qV0AHjS622Bt0Weps1UcI1clLi1lcQ4XMKHJN0pdWQd2qJaHMjT8iHMNhWi8Y4ukvZvr3r3qJDqwrx/8QpfKapsXlCZq8WZjhqPljt5Oq36LbPFnBYDBf++H+4Lfg6+KvLYqOiphvyvvoagrPYtJ+zfb3XXb05eCv5kUcknpb2sIge83tN+YTuPV6zV9ETjdGTcUyqc9I1dKbblZCESJVlSr6RhVIVbIw1qMDlczhbddbiQUI9mc3l1bJno/4e4bSryLNFupVjx7iOSGIYNzc9ArvApMQYIGhpV3VeY8b4p7SI4g2rQdAubRX9VzHJ6QiadLjKn/AJSd2YrEI1SSqKZfup85E1VNHfUrocuojXxqdkc3mq5hOJQFxZLtK5vQuVPakaN0pcnRilkhkZCELllwQhCAAJQhKrxRAhSJSkUPZIIQhVAEIQgAQhCABCEIAF2lxep0Fz4LirGQhiw/Nc/tB+voobsi0VdjJUtrmc5wdqKCp+C0uGYg9tHBrizc5SBYkfJQ4GFOY8EAPY7bX7K2crkZLvh5GtD7uNO0aVp2jWlK7JbcWn8jVGSeCRgWMh7gM1+Sv489kq4+C8/wGB/9IIrSq9VjyrHBoLdvkkNZHRbtkyk1xa5vZJY0Hdxp6rH8aR2xIeb2jXGo0IPotjPYIx5o9jhldma5poRSnMdwK8943lmtityNytDQ3vtpU7nVPjGNk75Ezcs/BUcPtrHb8Vt2nVZDhZlYteQWvYbHxUy2VjorZ9q6SET4ps0K1XKSNCqFilx+UyRSR7r+0PmFXQWVK2ONyntIRoO0ztDv5hZeUZVdjhvyJX2jLW+0spKHovSeA8KzRGkiw7R6BYfC5ergvbuC5DJBzEXd6Lrc2r4ePZbeDjNeauoetsncSTvsoDjoSMo8V4XjE1mcV6J+ImKdrIDZo8915RNxKlV+nUvFQ7vbJm/LyG/Swiumnqre5dph9SVwWLkzcpWR1KUeqBoSoQkrCGDhomlO2TFMvgDkhCFzC4ICEIAVFUJCVZsAQhCqAIQhAAhCEACEIQAIQgBAHWDDzGnx6KVKxavrtoOg0XFxytp/s7Xuby8aJsq4B11D0WWGeiYRFBbQ0UjFIlGm6osGjVCsMUByrK8OxqTujrw5DJiNcNivU4jfd6BeV8PYg1rwC1wuL0t0Xpb8Ra8MytecwF6WsOZUWJRYTEBrhXei8d/EVrWuoBe69bc8ioOi8X/EiPWNlTI5aKSxFkXhOXo1zzvYffgrpm644TDywWD9IJXdys3dlFhEKaOtVHga/Bd5kVC5S4upQF1LCqz87IeziEAdl3ab46rRSrV3npHOz9Tbjpuuz9Mj1mr6Zj5b+xsXhLDi97RTUgL2aK8QYROzW+gWO/D7DqAxCNBQdTqrDjzEQyGGA3dc9Bp5pnMk+RyY0o6RyaEvHRnXe3hf8PMeJZ4vc4k3JKyE1GoFZ4lHq4rPzL11ORJU4KC9F+JSwrkR7qlNQlAXH/LJ1dCAJ4bTVBskc7ZGIoNiPNSmlKAkJS5fIHJCELnlwQhCAFKRCFLAEIQoAEIQgAQhCABCEIAFIl4YNSfdbc/TxXJrKkAbrvMHKAwbe93u/hBKOESISSTukYaEFNQgg0uDxHVbTfT0stLHhgAZ3AfuWU4dmDna0AW38f6W5maEDfms01ZmiDuiRgAYCaPYSGnKCQPAK0hPcWNo4VF6FwqPBQ5OVhAZqMPULQyMBhaKMZ4N18VSyHqyQyUxXO3K6htYg1XjnEcQxZ0t/UG+d16disVrHvc0Adm4HOi8qwftzRcb3c7z/lNp+2IqP0a1gpbkBRco7rLpouMVqCDiRVcIDaPousubkd6eIXaruE2lHtKxEnZF1KsV9hctmcO9U8g2oC2/CsjVwJFhf6LtxtSpORz+Q3L7V7NRhsmIUMNFqXPVeVcc4pniupoLDoF6bxFN+ygOcDelB4rwrGJnM43V/pNJynKtIw8y3aNFaWSkm3qljuqVYzb1VON0zmTuzbQjZAujW2qkY1DnLGlbJoY1xSBCGlUk7slClMSppKpJkjEIQsJIIQhAAhCEACEIQAIQhAAhCEACAEKRBg1ubDcoJSHQeyC7fRvX+FFJXaK+p7hYD73TXwiLlQDOae1hKfMQcp7tjzVhgkHOXDofr8kN2QJBg/ZeDt86i3ct/Kvz6i1jTwsPIrLjDcp0sfX7orWQD2VNTfWqTJp5HwjZGmgQxlve9PNW0vNFgOQ25Kglp2hqdOyAFEmseaygDqkm7W9pxvyGiUl8DO1ti8RTdA9xNOydCPjfXULE8L3iuJ/L6lGPzD4ji42YDZtbDv67Lnwu+kVw5tPkQnxjaIiUryNW5col9Oq6xdFGab0KqWG5bhw0OvXmp8BlbrlLNBsfvkpkvDymmy6HDp9pCqsrItMJh1dTZeo4DLZYYO5v4bLDcOyWZ7RTUr0eI8MYTs0LXz56po59L7pym9IzHF0zmBYNga9SvEJ99yvTsWmsz3V3uvLcabliPaeZ+q6HFtRpdf4uJcXOSm/ZTzL1EaLrs4VKYBRYqj7SN0FZA9y5pXpwFBVLk7susDEiHFIlSlmxYKpAE6ic0qts3A4IQhYyQQhCABCEIAEIQgAQhCABKAkXeCxQ3YlK46DBvfRPmHbaAbLrXZRY7hoL8yoTuTpCQWZiABv9/JWs1LDKGjU/Jc8Kl9CR3/QKZOu7bKclEnkmKwQpOD7RpYfeZUjpS4Vjw/ByRmV0Lsp6FcPcjNeNHa/MK2fCyEPGgLHW6/wobwCVjYT2GWqB90qPvvCpZmKGLfy8MRIbXC7S0HvBA9fospPcKTEeZLGDLCNy8+629HCm7q1oOVNEtoZGVsMpcNl400/JBbYe+8+6wcyefctdC4ThwWHKMzyDmefePTkO5bXBsFhy0JsGGLC5J1cd3OPM/wBJMe/xwnOAq80a3vcbD77lNkglK58+cSwaRHMGjfe68vD5qlw6Z9nEa7YG/Q2K2nFWH5BzNy48ydT8arBxDe2iZHVhT2ehF2ZoI8OVFwfDrQi5VNw1iH/m4/trpTkr0DIe5VUc2GXurnSX1B+KupaFWirYMO+YaLR4NLVcF3uJBQj2Zh5FSyZtOFJPK0uI7h81J4mnMkPKNXeis5GAGMDeQv13WJ4nnczzTQWHgslJefkdnpCJJwpKHt7M5ORK35LBcQscYjnZTlOhpYrXT0T/AF3Ovcq15oKbLTyOR0ejTTpXSRhXWK5PddbCNCY4VyNPgoM/hsJrC/KQ4g5QCfMcli/q1LFrDvE0ZzdDykKQpzkVsNKVqQJ1EtZySKglBCapYHNCELESCEIQAIQhAAhCEACEIQAqkS6a5vxXKtFDyW0SY0elgnSck51yLev8KIOaupHE21o4AWtyJ+ShppYBZeSW5vs2UGp0HLmVxmmdqG7uPqujnZiDyqnx4VWA7tI89R6JYwJ5lWtPL1VrIjPCLd8jvKhHzUJjMzFN4biUe0HSpB8QR80A0ek8GxwYQZsRbuNL+BrX4rTSMPKTTfUcnC3p6LHcEQ/9fyEtPQEhp+IW/l4N67/dvDY8ioKkmAygqqPGogc+pPZh16ZiO0fAW8SridmMjC7fRo5uOn33LyzinG85MFh7A9935nb35IIjlmW4znxFc5rPcFRXntXosDEgkUtrotfMMzuyjTf6Ksn4Y9qxg7z5K8WTKJRQopa4OGoNQt7hsw2MwO5i/ceSx+JSBY6ux8lNwGaMN36T7w+a2cei6juhUpdNm4loZBot7wjJVIcRYX+iyeGsD6eVF6dgMpkhC13XPyXR5UvFR6e2YX/cqpLW2SMVj5IbjW9KDxXmWIx7krYcVTt8g0GvVeeYhGqTRV4cOlJzfss33qt/GCvjPq41UaYNV1cVHilczlVO0joU1ZDYLADU2AqT0VdEmGxGRHjTK4DuGy645GyQDQ0LyGeBu7yHmoUraA/9jvRIgspl2/RnymEoJS0W9vthCACe0bpoCc8qVgBtUwlOcUgCXJ/ADEIQsxIIQhAAhCEACEIQAIQhAD2vogmtAkpZDdQgliFIpUeHaqioTBqx3gTDmGx8NloJGabEY4aOpcehWYVjgcSkZvfUfFVkromLszSSoq3wuuEs7LE8f6UuTFLfdFGnGZX5vilDT0XgKPWYdyNz4gE+YK9Ta2i8g/DuIf8AkD8pbfuobO7x2qL0Li3HBLQCQR7V9WwxvXd3QfRShctmX474h7RgQjdtQ5w0BOtO/b4rzyajZRQald48XVxNSbknc81WZ8zi4+CgYlY6QxkaSdVRyz88xmNwDT1Ck4rOUBAP2VHk2BkMuc7ITQ1pvqAPgrxRVs0U7IB7FSQZQsdQhaOSxaC5rRnbUgW796qRMYdmIcB8F3PpkOrXYw8uX2tovOApdznhprl16c1609wawnYD0WQ4Aw3KwxCL6D5q14txEQoJ5nbn3JXNfn5PWP6MnFk4UJVZ+9fr0YjibESXkA9o1PQLOPNkj4xeS83JK5zD6BauY1RpqC9GjiRuk2cMy5E1NFzz7ImIwhtfE5Co/dsPjReem+zOmsIruIqOhVGjHAHxBB8yFFlz/heP0n0UuDBzSbq3c4Of41zKHLV9g80/1IVo+v2V/kowEqChjardrCEjg1NcU5zlzCJP0AicEOTSUp4JGoQhIAEIQgAQhCABCEIAEIQgB1bJoSkpEEssWXaowYu0u6yRzbKqLEV4oVJwv/tZ+5cJgXU/AGVi15AlS3ghbNNL6k95SYmyoBTZY6KTNNqEkaT+DsX/AOPGD3CraODhqSCNB8Au2KYo+ZiGLENa2YNmN2AHqs9Juo+neFNmYtAQgCLORSTlCjxzlb0XWC2t1Fxl9GeSlbBlPCYYsQNrbU9ApWJwS6hBOVoo0dw1PVdcDl6NLzqTQdN1MdCzGm1fJaaMe00hUnaJCw6QcaEDVb7hZj8wY5pINgeX8KFh0uBQUXoXCOHguDiNL+K77qKlx22jlV05SUU8vBrpGXENgaNAP7Xl/HmKZ4paD2Wmg+q9LxiZ9nCe7uoOpXh8/GzxCTzWb6VT7TlVl6K8z8o0Y62wGgUeafZSHWCrpp3zWTn1e02jp8eFojGXKh8RP7DGDV7h8B9hT5Ubqti/5ZnuhinjuuYt3NEtFxAg0htZtlI8qLOk5ZZ3fQed1pohplWdxO0Fw/WR5lWh+SIlooCU+GkpZMa6i3OVmJFcUjUhKc1L7XYWEdqmFOcmpcn6JP/Z" alt="Obi Wan Kenobi wearing hood and holding blue lightsaber" />
</>
}
</div>
);
};
export default DisplayPage;
|
"use strict";
// Defines helper functions for saving and getting tweets, using the database `db`
module.exports = function makeDataHelpers(knex) {
return {
// get or add user
getUsers: function(cb) {
knex
.select("*")
.from("users")
.then(results => cb(null, results))
.catch(err => cb(err, null));
},
// get by username
getUser: function(username, cb) {
knex
.select("*")
.from("users")
.where({name: username})
.then(results => cb(null, results))
.catch(err => cb(err, null));
},
fetchUser: function(username, cb) {
let query = {name: username};
knex
.select("*")
.from("users")
.where(query)
.then(results => {
if (results.length < 1)
knex("users").insert([query])
.then(results => this.getUser(username, cb))
else
cb(null, results)
})
.catch(err => cb(err, null))
},
insertGame(gameState, cb) {
knex("games")
.insert([{game_id: gameState.game_id,
player1_id: gameState.player1_id(),
player2_id: gameState.player2_id(),
game_state: gameState,
p1Score: gameState.calculateP1Score(),
p2Score: gameState.calculateP2Score()}])
.then(result => cb(null, result))
.catch(err => cb(err, null));
},
updateGame(gameState, cb) {
knex("games")
.where({game_id: gameState.game_id})
.update([{player1_id: gameState.player1_id(),
player2_id: gameState.player2_id(),
game_state: gameState,
p1Score: gameState.calculateP1Score(),
p2Score: gameState.calculateP2Score()}])
.then(result => cb(null, result))
.catch(err => cb(err, null));
}
}
}
|
import React, {Component} from 'react';
import './stylesheets/styleSheet.css';
// Component to render About Page
export class AboutPage extends Component {
render() {
return (
<div className = "body">
{/* Header Picture*/}
<img className = "headerPic" src = "harmandirSahibHeaderPic.jpg" alt = "Picture of Harmandir Sahib"/>
{/* Main Heading*/}
<h1 className = "inPicHeading"> GURDWARA </h1>
{/* Body Text*/}
<div className = "textContainer">
<h2 className = "centerText"> What is a Gurdwara? </h2>
<p className = "centerText">A gurdwara is defined as a place of worship for Sikhs. The literal meaning of the word "Gurdwara" is a gateway to which the guru could be reached or "the door that leads to the guru".</p>
<h2 className = "centerText"> The Purpose of a Gurdwara </h2>
<ol>
<li> To learn spiritual wisdom taught by Sri Guru Granth Sahib Ji </li>
<li> Gurdwaras are home to many Sikh religious ceremonies. </li>
<li> Gurdwaras can teach children about the Sikh faith, ethics, customs, traditions, and text. </li>
<li> A Gurdwara also acts as a community centre and offers food, shelter, and companionship to whoever is in need, from any religion or background. </li>
<li> A Gurdwara can also act as a hub to which the Sikh population can give back to the community to which it resides through volunteer and charity. </li>
</ol>
</div>
<img className = "headerPic" src = "cambridgeHeaderPic.jpg" alt = "Picture of Cambridge" style={{"margin-top": 75}}/>
<div className = "textContainer" id = "widerPara">
<h2 className = "centerText"> Cambridge, Ontario </h2>
<p>
Located accessibly off highway 401, the city of Cambridge has witnessed great growth over the last couple of decades. Under 100 km west of the Greater Toronto Area, and next door to the technology hub of Waterloo Ontario, Cambridge is poised for further growth in population and industry. The Sikh community has also been apart of this growth. With a small town feel, Cambridge offers families a sense of comfort, security, belonging, and peace. The Sikh population has grown tremendously in Cambridge within the last 10 years, and is in a position to grow further in the next coming years. The Sikh community in Cambridge is dedicated in building a new home for Sri Guru Granth Sahib Ji that will be able meet the needs of the growing population.
<br/> <br/> For further information to our beloved city feel free to click on the following images:
</p>
{/* Image Grip Container */}
<div className = "imageContainer">
<a href = "https://www.cambridge.ca/en/index.aspx" target = "_blank"> <img className = "imageRow img1" src = "cambridgeLogoPic.jpg" alt = "Picture of cambridge.ca Logo"/> </a>
<a href = "http://visitcambridgeontario.com/" target = "_blank"> <img className = "imageRow img2" src = "visitCambridgeOntarioLogoPic.png" alt = "Picture of visitcambridgeontario.com Logo"/> </a>
<a href = "https://www.cambridgetimes.ca/" target = "_blank"> <img className = "imageRow img3" src = "cambridgeTimesLogoPic.png" alt = "Picture of Cambridge Times Logo"/> </a>
</div>
</div>
</div>
);
}
}
|
import React from "react";
import Sidebar from "../components/staff-ui/sidebar/Sidebar";
import DashboardOutlinedIcon from "@material-ui/icons/DashboardOutlined";
import Topbar from "../components/staff-ui/topbar/Topbar";
import "./layout.css";
import { Switch, Route } from "react-router-dom";
import CreditCardIcon from "@material-ui/icons/CreditCard";
import Mobile from "@material-ui/icons/MobileFriendly";
import LocalAtmIcon from "@material-ui/icons/LocalAtm";
import { Typography } from "@material-ui/core";
import DisplayCredit from "../components/staff-ui/DisplayCredit";
import PaymentDashbord from "../pages/staff-ui/paymenentAdmin/PaymentDashbord";
import MobilePayPayments from "../pages/staff-ui/paymenentAdmin/mobilePayData";
import RefundData from "../pages/staff-ui/paymenentAdmin/RefundData";
const PaymentAdmin = () => {
let temp = sessionStorage.getItem("user");
let currentUser = JSON.parse(temp);
const user = {
name: currentUser?.firstName + " " + currentUser?.lastName,
role: currentUser?.role,
list: [
{
path: "",
exact: true,
icon: <DashboardOutlinedIcon className="sidebarIcon" />,
// style={inline-size: max-content;}
iconlabel: (
<Typography style={{ inlineSize: "max-content" }}>
Dashboard
</Typography>
),
id: 1,
},
{
path: "creditCard",
icon: <CreditCardIcon className="sidebarIcon" />,
iconlabel: (
<Typography style={{ inlineSize: "max-content" }}>
Creditcard Payments
</Typography>
),
id: 2,
},
{
path: "mobilePay",
icon: <Mobile className="sidebarIcon" />,
iconlabel: (
<Typography style={{ inlineSize: "max-content" }}>
Mobile-pay Payments
</Typography>
),
id: 3,
},
{
path: "refunds",
icon: <LocalAtmIcon className="sidebarIcon" />,
iconlabel: (
<Typography style={{ inlineSize: "max-content" }}>Refunds</Typography>
),
id: 4,
},
],
};
return (
<div>
<div className="container">
<Sidebar user={user} />
<div className="others">
<Topbar style={{}} page={user.list} />
<Switch>
<Route path="/staff/Paymentadmin/creditCard">
<DisplayCredit />
</Route>
<Route path="/staff/Paymentadmin/mobilePay">
<MobilePayPayments />
</Route>
<Route path="/staff/Paymentadmin/refunds">
<RefundData />
</Route>
<Route path="/staff/Paymentadmin/">
<PaymentDashbord />
</Route>
</Switch>
</div>
</div>
</div>
);
};
export default PaymentAdmin;
|
// pages/activity_publish/activity_publish.js
const app = getApp();
const request_01 = require('../../utils/request/request_01.js');
const request_05 = require('../../utils/request/request_05.js');
const router = require('../../utils/tool/router.js');
Page({
/**
* 页面的初始数据
*/
data: {
IMGSERVICEZ:app.globalData.IMGSERVICE,
},
headerBack: function (e) {
let activity_id = this.data.activity_id;
router.jump_nav({
url: `/pages/vote/vote?activity_id=${activity_id}`,
})
},
toVote(){
let activity_id = this.data.activity_id;
router.jump_nav({
url: `/pages/vote/vote?activity_id=${activity_id}`,
})
},
initData(options){
let activity_id = options.activity_id;
let user_id = wx.getStorageSync('userInfo').user_id;
request_05.voteIndex({ activity_id, user_id}).then(res=>{
let rank_list = res.data.data.rank_list;
let is_win = res.data.data.is_win;
let rating_time = res.data.data.rating_time;
this.setData({
rank_list,
is_win,
rating_time,
activity_id,
})
})
request_05.myVote({ activity_id, user_id}).then(res=>{
console.log(res);
let userInfo = res.data.data.info;
this.setData({
userInfo,
})
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
request_01.login(()=>{
this.initData(options);
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
|
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
mode: 'history',
base: '/gsbx',
routes: [
{
path: '/',
name: 'home',
component: () => import('@/views/Home')
},
{
path: '/articleDetail',
name: 'articleDetail',
component: () => import('@/views/ArticleDetail')
},
{
path: '/admin',
name: 'admin',
component: () => import('@/views/Admin'),
redirect: '/admin/login',
children: [
{
path: '/admin/login',
name: 'adminLogin',
component: () => import('@/views/Admin/Login')
},
{
path: '/admin/home',
name: 'adminHome',
component: () => import('@/views/Admin/Home'),
redirect: '/admin/home/workbench',
children: [
{
path: '/admin/home/workbench',
name: 'workbench',
component: () => import('@/views/Admin/Workbench')
},
{
path: '/admin/home/personal',
name: 'personal',
component: () => import('@/views/Admin/Personal')
},
{
path: '/admin/home/writeArticle',
name: 'writeArticle',
component: () => import('@/views/Admin/WriteArticle')
},
{
path: '/admin/home/articleUpdate',
name: 'articleUpdate',
component: () => import('@/views/Admin/ArticleUpdate')
}
]
}
]
}
]
})
|
const _ = require("lodash");
const { CachedVideo } = require("../../../models");
const storage = require("../../../storage");
const { Room } = require("../../../models");
describe('Storage: Room Spec', () => {
beforeEach(async () => {
await Room.destroy({ where: {} });
});
it('should return room object without extra properties', async done => {
await storage.saveRoom({ name: "example", title: "Example Room", description: "This is an example room.", visibility: "public" });
storage.getRoomByName("example").then(room => {
expect(room).not.toBeNull();
expect(room).toBeDefined();
expect(typeof room).toEqual("object");
expect(room).not.toBeInstanceOf(Room);
expect(room.id).toBeUndefined();
expect(room.createdAt).toBeUndefined();
expect(room.updatedAt).toBeUndefined();
expect(room.name).toBeDefined();
expect(room.name).toEqual("example");
expect(room.title).toBeDefined();
expect(room.title).toEqual("Example Room");
expect(room.description).toBeDefined();
expect(room.description).toEqual("This is an example room.");
expect(room.visibility).toEqual("public");
done();
}).catch(err => {
done.fail(err);
});
});
it('should return room object from room name, case insensitive', async () => {
await storage.saveRoom({ name: "CapitalizedExampleRoom", title: "Example Room", description: "This is an example room.", visibility: "public" });
let room = await storage.getRoomByName("capitalizedexampleroom");
expect(room).toEqual({
name: "CapitalizedExampleRoom",
title: "Example Room",
description: "This is an example room.",
visibility: "public",
owner: null,
});
});
it('should create room in database', async done => {
expect(await Room.findOne({ where: { name: "example" }})).toBeNull();
expect(await storage.saveRoom({ name: "example", title: "Example Room", description: "This is an example room.", visibility: "public" })).toBe(true);
Room.findOne({ where: { name: "example" }}).then(room => {
expect(room).toBeInstanceOf(Room);
expect(room.id).toBeDefined();
expect(room.name).toBeDefined();
expect(room.name).toEqual("example");
expect(room.title).toBeDefined();
expect(room.title).toEqual("Example Room");
expect(room.description).toBeDefined();
expect(room.description).toEqual("This is an example room.");
expect(room.visibility).toEqual("public");
done();
}).catch(err => {
done.fail(err);
});
});
it('should not create room if name matches existing room, case insensitive', async () => {
await storage.saveRoom({ name: "CapitalizedExampleRoom", visibility: "public" });
expect(await storage.saveRoom({ name: "capitalizedexampleroom", visibility: "public" })).toBe(false);
});
it('should update the matching room in the database with the provided properties', async done => {
expect(await Room.findOne({ where: { name: "example" }})).toBeNull();
expect(await storage.saveRoom({ name: "example" })).toBe(true);
expect(await storage.updateRoom({ name: "example", title: "Example Room", description: "This is an example room.", visibility: "unlisted" })).toBe(true);
Room.findOne({ where: { name: "example" }}).then(room => {
expect(room).toBeInstanceOf(Room);
expect(room.id).toBeDefined();
expect(room.name).toBeDefined();
expect(room.name).toEqual("example");
expect(room.title).toBeDefined();
expect(room.title).toEqual("Example Room");
expect(room.description).toBeDefined();
expect(room.description).toEqual("This is an example room.");
expect(room.visibility).toEqual("unlisted");
done();
}).catch(err => {
done.fail(err);
});
});
it('should fail to update if provided properties does not include name', () => {
return expect(storage.updateRoom({ title: "Example Room", description: "This is an example room.", visibility: "unlisted" })).rejects.toThrow();
});
it('should return true if room name is taken', async () => {
expect(await Room.findOne({ where: { name: "example" }})).toBeNull();
expect(await storage.isRoomNameTaken("example")).toBe(false);
expect(await storage.saveRoom({ name: "example" })).toBe(true);
expect(await storage.isRoomNameTaken("example")).toBe(true);
});
it('should return true if room name is taken, case insensitive', async () => {
await storage.saveRoom({ name: "Example" });
expect(await storage.isRoomNameTaken("example")).toBe(true);
expect(await storage.isRoomNameTaken("exAMple")).toBe(true);
});
});
describe('Storage: CachedVideos Spec', () => {
afterEach(async () => {
await CachedVideo.destroy({ where: {} });
});
it('should create or update cached video without failing', async () => {
let video = {
service: "youtube",
id: "-29I-VbvPLQ",
title: "tmp181mfK",
description: "tmp181mfK",
thumbnail: "https://i.ytimg.com/vi/-29I-VbvPLQ/mqdefault.jpg",
length: 10,
};
expect(await storage.updateVideoInfo(video)).toBe(true);
});
it('should fail validation, no null allowed for service', async () => {
let video = {
service: null,
id: "-29I-VbvPLQ",
title: "tmp181mfK",
description: "tmp181mfK",
thumbnail: "https://i.ytimg.com/vi/-29I-VbvPLQ/mqdefault.jpg",
length: 10,
};
expect(await storage.updateVideoInfo(video, false)).toBe(false);
});
it('should fail validation, no null allowed for serviceId', async () => {
let video = {
service: "youtube",
id: null,
title: "tmp181mfK",
description: "tmp181mfK",
thumbnail: "https://i.ytimg.com/vi/-29I-VbvPLQ/mqdefault.jpg",
length: 10,
};
expect(await storage.updateVideoInfo(video, false)).toBe(false);
});
it('should return the attributes that a video object should have', () => {
let attributes = storage.getVideoInfoFields();
expect(attributes.length).toBeGreaterThan(0);
expect(attributes).not.toContain("id");
expect(attributes).not.toContain("service");
expect(attributes).not.toContain("serviceId");
expect(attributes).not.toContain("createdAt");
expect(attributes).not.toContain("updatedAt");
attributes = storage.getVideoInfoFields("youtube");
expect(attributes).not.toContain("mime");
attributes = storage.getVideoInfoFields("googledrive");
expect(attributes).not.toContain("description");
});
it('should create or update multiple videos without failing', async () => {
let videos = [
{
service: "fakeservice",
id: "abc123",
title: "test video 1",
},
{
service: "fakeservice",
id: "abc456",
title: "test video 2",
},
{
service: "fakeservice",
id: "abc789",
title: "test video 3",
},
{
service: "fakeservice",
id: "def123",
title: "test video 4",
},
{
service: "fakeservice",
id: "def456",
title: "test video 5",
},
];
expect(await storage.updateManyVideoInfo(videos)).toBe(true);
});
it('should get multiple videos without failing', async () => {
let videos = [
{
service: "fakeservice",
id: "abc123",
title: "test video 1",
},
{
service: "fakeservice",
id: "abc456",
title: "test video 2",
},
{
service: "fakeservice",
id: "abc789",
title: "test video 3",
},
{
service: "fakeservice",
id: "def123",
title: "test video 4",
},
{
service: "fakeservice",
id: "def456",
title: "test video 5",
},
];
await CachedVideo.bulkCreate(_.cloneDeep(videos).map(video => {
video.serviceId = video.id;
delete video.id;
return video;
}));
expect(await storage.getManyVideoInfo(videos)).toEqual(videos);
});
it('should return the same number of videos as requested even when some are not in the database', async () => {
let videos = [
{
service: "fakeservice",
id: "abc123",
title: "test video 1",
},
{
service: "fakeservice",
id: "abc456",
title: "test video 2",
},
{
service: "fakeservice",
id: "abc789",
title: "test video 3",
},
{
service: "fakeservice",
id: "def123",
},
{
service: "fakeservice",
id: "def456",
},
];
await CachedVideo.bulkCreate(_.cloneDeep(videos).splice(0, 3).map(video => {
video.serviceId = video.id;
delete video.id;
return video;
}));
expect(await storage.getManyVideoInfo(videos)).toEqual(videos);
});
});
describe('Storage: CachedVideos: bulk inserts/updates', () => {
beforeEach(async () => {
await CachedVideo.destroy({ where: {} });
});
afterEach(async () => {
await CachedVideo.destroy({ where: {} });
});
it('should create 2 entries and update 3 entries', async () => {
// setup
let existingVideos = [
{
service: "fakeservice",
serviceId: "abc123",
title: "existing video 1",
},
{
service: "fakeservice",
serviceId: "abc456",
title: "existing video 2",
},
{
service: "fakeservice",
serviceId: "abc789",
title: "existing video 3",
},
];
for (let video of existingVideos) {
await CachedVideo.create(video);
}
// test
let videos = [
{
service: "fakeservice",
id: "abc123",
title: "test video 1",
},
{
service: "fakeservice",
id: "abc456",
title: "test video 2",
},
{
service: "fakeservice",
id: "abc789",
title: "test video 3",
},
{
service: "fakeservice",
id: "def123",
title: "test video 4",
},
{
service: "fakeservice",
id: "def456",
title: "test video 5",
},
];
expect(await storage.updateManyVideoInfo(videos)).toBe(true);
expect(await storage.getVideoInfo("fakeservice", "abc123")).toEqual(videos[0]);
expect(await storage.getVideoInfo("fakeservice", "abc456")).toEqual(videos[1]);
expect(await storage.getVideoInfo("fakeservice", "abc789")).toEqual(videos[2]);
expect(await storage.getVideoInfo("fakeservice", "def123")).toEqual(videos[3]);
expect(await storage.getVideoInfo("fakeservice", "def456")).toEqual(videos[4]);
});
});
|
export const msgs = [
{
img: '../shared/images/profile.png',
msg: 'wah bhai full msg bazi',
name: 'Ali',
time: 'Just Now',
id: 1
},
{
img: '../shared/images/profile.png',
msg: 'meri jan jan jae',
name: 'Adnan',
time: '30 mints ago',
id: 2
},
{
img: '../shared/images/profile.png',
msg: 'Party scene on hai',
name: 'Siddique',
time: '1 hours ago',
id: 3
},
{
img: '../shared/images/profile.png',
msg: 'han yaar soch ke bataonga',
name: 'Ayaaz',
time: '1 day ago',
id: 4
},
{
img: '../shared/images/profile.png',
msg: 'wah bhai full msg bazi',
name: 'Ali',
time: '2 day ago',
id: 5
},
{
img: '../shared/images/profile.png',
msg: 'meri jan jan jae',
name: 'Adnan',
time: '3 weeks ago',
id: 6
},
{
img: '../shared/images/profile.png',
msg: 'Party scene on hai',
name: 'Siddique',
time: '1 month ago',
id: 7
},
{
img: '../shared/images/profile.png',
msg: 'han yaar soch ke bataonga',
name: 'Ayaaz',
time: '1 year ago',
id: 8
}
]
|
import React, { useState, useEffect } from 'react'
import { useParams } from 'react-router-dom'
import Commerce from '@chec/commerce.js';
import '../style/Izdelek.css'
import CircularProgress from '@material-ui/core/CircularProgress';
import { Swiper, SwiperSlide } from 'swiper/react';
import SwiperCore, { Navigation, Pagination, Thumbs } from 'swiper';
import 'swiper/swiper-bundle.css';
import useMediaQuery from '@material-ui/core/useMediaQuery'
import $ from "jquery";
SwiperCore.use([Navigation, Pagination, Thumbs])
const commerce = new Commerce(process.env.REACT_APP_COMMERCE_KEY);
function Izdelek(props) {
const [thumbsSwiper, setThumbsSwiper] = useState(null);
const [izdelek, setIzdelek]=useState();
const { id } = useParams()
const isMobile = useMediaQuery("(max-width:800px)");
const fetchIzdelek = async (izdelekId) =>{
const fetchedIzdelek = await commerce.products.retrieve(izdelekId)
setIzdelek(fetchedIzdelek)
}
useEffect(()=>{
if(izdelek === undefined){
fetchIzdelek(id)
}
},[])
if(izdelek){
const ProductPictures=[];
const thumbs=[];
izdelek.assets.map((asset)=>{
ProductPictures.push(
<SwiperSlide key={asset.id} className='IzdelekSwiperSlide' >
<img id='MainImg' className='IzdelekImg' alt={izdelek.name} src={asset.url}/>
</SwiperSlide>
)
thumbs.push(
<SwiperSlide key={asset.id} >
<img className='IzdelekSwiperSlideThumbs' alt='' src={asset.url}/>
</SwiperSlide>
)
return ''
})
// ko kliknes na sliko izdelka ti odpre sliko in vse ostalo zamegli
$( document ).ready(function (){
// Get the modal
var modal = document.getElementById('myModal');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
var span = document.getElementsByClassName("close")[0];
// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.querySelectorAll('#MainImg');
let keys = Object.keys(img)
keys.map( key =>{
img[key].onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
})
// Get the <span> element that closes the modal
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
})
return (
<div className='Ozadje' style={{display:'flex','alignItems':'center',justifyContent:'center'}}>
<div className='IzdelekOutterDiv '>
<div className='IzdelekImgDiv'>
<Swiper
// style ={{border:'1px solid black'}}
thumbs={{ swiper: thumbsSwiper }}
spaceBetween={0}
slidesPerView={1}
pagination
>
{ProductPictures}
</Swiper>
<div id="myModal" className="modal">
<span className="close">×</span>
<img className="modal-content" id="img01"/>
<div id="caption"></div>
</div>
{isMobile ? <Swiper
id="thumbs"
spaceBetween={0}
slidesPerView={3}
onSwiper={setThumbsSwiper}
>
{thumbs}
</Swiper>
:
<Swiper
id="thumbs"
spaceBetween={0}
slidesPerView={4}
style={{'margin':'auto','width':'620px'}}
onSwiper={setThumbsSwiper}
>
{thumbs}
</Swiper>
}
</div>
<div className='IzdelekDescriptionDiv'>
<div className='IzdelekBesedilo'>
<h1 style={{fontWeight:'300'}}>{izdelek.name}</h1>
<h3 style={{textAlign:'left'}}>Opis:</h3>
<hr style={{width:'90%','marginLeft':'10px','margin':'10px 10px 20px 10px'}}/>
<div dangerouslySetInnerHTML={{__html:izdelek.description}} className='IzdelekDescriptionBesedilo' />
</div>
<div>
<p>{izdelek.price.formatted_with_code}</p>
<button onClick={() => props.handleAddItemToCart(izdelek.id)} className='IzdelekKupiBtn' >
Dodaj v košarico
</button>
</div>
</div>
</div>
</div>
)
}
else{
return(
<div className='Ozadje'>
<CircularProgress className='VrteciStvor'/>
</div>
)
}
}
export default Izdelek
|
// UFX.maximize: expand a canvas to take up the whole window or screen
// May require polyfill for fullscreening
// UFX.maximize.full(canvas): fullscreen
// UFX.maximize.fill(canvas): fill window
// UFX.maximize.maximize(canvas): fullscreen if possible, fill window otherwise
// When resizing or maximizing, the callback UFX.maximize.onadjust will be invoked with arguments
// (canvas, width, height).
// UFX.maximize.resizemode can be set to "none", "fixed", "aspect", or "total", depending on how
// you want the canvas resized upon maximization.
// For more details and options, see the UFX.maximize documentation here:
// https://code.google.com/p/unifac/wiki/UFXDocumentation#UFX.maximize_:_resize_canvas_to_fit_screen/window
"use strict"
var UFX = UFX || {}
UFX.maximize = {
resizemode: "fixed",
preventscroll: true,
fillcolor: "black",
onadjust: null,
init: function (element) {
this.element = element
this.mode = null
function c(obj, method) { return function () { obj[method]() } }
this.calladjust = c(this, "adjust")
this.getsettings()
},
setmode: function (mode) {
if (this.mode == mode) return
if (this.mode == "fill") window.removeEventListener("resize", this.calladjust)
if (this.mode == "full") {
document.cancelFullscreen()
window.removeEventListener("resize", this.calladjust)
}
this.mode = mode
if (this.mode == "fill") window.addEventListener("resize", this.calladjust)
if (this.mode == "full") {
this.element.requestFullscreen()
window.addEventListener("resize", this.calladjust)
}
},
adjust: function () {
var wx = window.innerWidth, wy = window.innerHeight
var ex = this.element.width, ey = this.element.height
var dx, dy, gx, gy
if (this.resizemode == "none") {
} else if (this.resizemode == "fixed") {
if (ex * wy > ey * wx) {
dx = wx
dy = Math.round(wx * ey / ex)
} else {
dx = Math.round(wy * ex / ey)
dy = wy
}
} else if (this.resizemode == "aspect") {
if (ex * wy > ey * wx) {
gx = dx = wx
gy = dy = Math.round(wx * ey / ex)
} else {
gx = dx = Math.round(wy * ex / ey)
gy = dy = wy
}
} else if (this.resizemode == "total") {
gx = dx = wx
gy = dy = wy
}
var es = this.element.style
if (dx) {
es.width = dx + "px"
es.height = dy + "px"
}
if (gx) {
this.element.width = gx
this.element.height = gy
}
if (this.mode == "fill") {
var bx = wx - (dx || gx || this.element.width)
var by = wy - (dy || gy || this.element.height)
es.borderLeft = es.borderRight = bx > 0 ? (0.5 * bx + 1) + "px " + this.fillcolor + " solid" : "none"
es.borderTop = es.borderBottom = by > 0 ? (0.5 * by + 1) + "px " + this.fillcolor + " solid" : "none"
setTimeout(function () { window.scrollTo(0, 1) }, 1)
} else if (this.mode == "full") {
es.borderLeft = es.borderRight = "none"
es.borderTop = es.borderBottom = "none"
}
if (this.onadjust) {
this.onadjust(this.element, this.element.width, this.element.height)
}
},
fill: function (element, resizemode) {
if (resizemode) this.resizemode = resizemode
if (element) this.init(element)
this.setmode("fill")
if (this.preventscroll) {
document.body.addEventListener('touchstart', this.preventdefault)
this.scrollprevented = true
}
this.adjust()
var es = this.element.style
es.position = "absolute"
es.left = "0px"
es.top = "1px"
document.body.style.overflow = "hidden"
},
full: function (element, resizemode) {
if (resizemode) this.resizemode = resizemode
if (element) this.init(element)
this.setmode("full")
var fs = this
setTimeout(function () {
if (fs.getfullscreenelement() === fs.element) {
fs.adjust()
} else {
fs.restore()
}
}, 100)
},
maximize: function (element, resizemode) {
if (resizemode) this.resizemode = resizemode
if (element) this.init(element)
if (!this.element.requestFullscreen) {
this.fill()
return
}
this.setmode("full")
var fs = this
setTimeout(function () {
if (fs.getfullscreenelement() === fs.element) {
} else {
fs.fill()
}
}, 100)
},
getfullscreenelement: function () {
return document.getFullscreenElement
},
restore: function () {
this.setmode()
if (this.scrollprevented) {
document.body.removeEventListener('touchstart', this.preventdefault)
this.scrollprevented = false
}
this.restoresettings()
if (this.onadjust) {
this.onadjust(this.element, this.element.width, this.element.height)
}
},
getsettings: function () {
var es = this.element.style, ds = this.settings = {
width: this.element.width,
height: this.element.height,
overflow: document.body.style.overflow,
style: {},
}
var vars = "width height position left top borderLeft borderRight borderTop borderBottom border".split(" ")
vars.forEach(function (v) {
ds.style[v] = es[v]
})
},
restoresettings: function () {
var es = this.element.style, ds = this.settings
width: this.element.width = this.settings.width
height: this.element.height = this.settings.height
overflow: document.body.style.overflow = this.settings.overflow
var vars = "width height position left top borderLeft borderRight borderTop borderBottom border".split(" ")
vars.forEach(function (v) {
es[v] = ds.style[v]
})
},
fillnoresize: function () {
es.position = "absolute"
es.left = "0px"
es.top = "1px"
this.setbordersizes(wx - px, wy - py)
document.body.style.overflow = "hidden"
},
preventdefault: function (event) {
event.preventDefault()
},
}
|
import React from 'react';
import { useContext } from 'react';
import {
useParams
} from "react-router-dom";
import { __RouterContext as RouterContext } from 'react-router';
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableRow from '@material-ui/core/TableRow';
import axios from 'axios';
import PrimarySearchAppBar from './header'
import Drawer from '@material-ui/core/Drawer';
import List from '@material-ui/core/List';
import Divider from '@material-ui/core/Divider';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import ListIcon from '@material-ui/icons/List';
import AddBoxIcon from '@material-ui/icons/AddBox';
export function useRouter() {
return useContext(RouterContext);
}
const useStylesBar = makeStyles(theme => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
},
}));
const useStylesGrid = makeStyles(theme => ({
root: {
flexGrow: 1,
overflow: 'hidden',
marginTop: "5%",
marginBottom: 25,
marginLeft: "5%",
marginRight: "5%",
},
paper: {
marginTop: 10,
marginBottom: 10,
padding: theme.spacing(2),
border: '1px solid #BDBDBD',
backgroundColor: '#F5F5F5',
marginLeft: "5px",
},
title: {
fontWeight: 'bold',
fontSize: '24px',
color: '#34495e',
},
nameField: {
fontWeight: 'bold',
fontSize: '16px',
color: '#34495e',
},
}));
const drawerWidth = 240;
const useStylesSide = makeStyles(theme => ({
root: {
display: 'flex',
},
appBar: {
width: `calc(100% - ${drawerWidth}px)`,
marginLeft: drawerWidth,
},
drawer: {
width: drawerWidth,
flexShrink: 0,
},
drawerPaper: {
width: drawerWidth,
backgroundColor: '#f4f4f4'
},
toolbar: theme.mixins.toolbar,
content: {
flexGrow: 1,
backgroundColor: theme.palette.background.default,
padding: theme.spacing(3),
},
}));
export default function Employee() {
const classesBar = useStylesBar();
const { history } = useRouter();
const [anchorEl, setAnchorEl] = React.useState(null);
let { id } = useParams();
const classesGrid = useStylesGrid();
const classesSide = useStylesSide();
const [auth, setAuth] = React.useState(false);
const [data, setDataEmp] = React.useState({});
React.useEffect(() => {
if (JSON.parse(window.sessionStorage.getItem("user")) != null) {
var auth_check = JSON.parse(window.sessionStorage.getItem("user")).role;
if (auth_check === 1) {
setAuth(true);
}
else {
history.push('/404');
}
}
else {
history.push('/404');
}
console.log(`/api/employees/` + id);
axios.get(`/api/employees/` + id)
.then(res => {
const data_emp = res.data;
console.log(data_emp);
setDataEmp(data_emp);
})
.catch(error => {
history.push('/404');
});
}, [])
return (
<div className={classesBar.root}>
<PrimarySearchAppBar username={JSON.parse(window.sessionStorage.getItem("user")).emp_code} />
<div className={classesGrid.root}>
<Paper className={classesGrid.paper}>
<Grid container spacing={2}>
<Grid item>
<div className={classesGrid.title}>Employee Information</div>
</Grid>
</Grid>
<Grid container spacing={2}>
<TableContainer component={Paper}>
<Table aria-label="caption table">
<TableBody>
<TableRow>
<TableCell width={'16.67%'} className={classesGrid.nameField} component="th" scope="row">
ID:
</TableCell>
<TableCell width={'16.67%'} align="left">{data.id}</TableCell>
<TableCell width={'16.67%'} className={classesGrid.nameField} component="th" scope="row">
USERNAME:
</TableCell>
<TableCell width={'16.67%'} align="left">{data.emp_code}</TableCell>
<TableCell width={'16.67%'} className={classesGrid.nameField} component="th" scope="row">
NAME:
</TableCell>
<TableCell width={'16.67%'} align="left">{data.emp_name}</TableCell>
</TableRow>
<TableRow >
<TableCell width={'16.67%'} className={classesGrid.nameField} component="th" scope="row">
GENDER:
</TableCell>
<TableCell width={'16.67%'} align="left">{data.gender}</TableCell>
<TableCell width={'16.67%'} className={classesGrid.nameField} component="th" scope="row">
BIRTHDAY:
</TableCell>
<TableCell width={'16.67%'} align="left">{data.dob}</TableCell>
</TableRow>
</TableBody>
</Table>
</TableContainer>
</Grid>
</Paper>
<Paper className={classesGrid.paper}>
<Grid container spacing={2}>
<Grid item>
<div className={classesGrid.title}>Contact Information</div>
</Grid>
</Grid>
<Grid container spacing={2}>
<TableContainer component={Paper}>
<Table aria-label="caption table">
<TableBody>
<TableRow>
<TableCell width={'16.67%'} className={classesGrid.nameField} component="th" scope="row">
ADDRESS:
</TableCell>
<TableCell width={'16.67%'} align="left">{data.address}</TableCell>
<TableCell width={'16.67%'} className={classesGrid.nameField} component="th" scope="row">
IDENTIFICATION CARD:
</TableCell>
<TableCell width={'16.67%'} align="left">{data.identification_card}</TableCell>
<TableCell width={'16.67%'} className={classesGrid.nameField} component="th" scope="row">
PHONE NUMBER:
</TableCell>
<TableCell width={'16.67%'} align="left">{data.phone_number}</TableCell>
</TableRow>
<TableRow >
<TableCell width={'16.67%'} className={classesGrid.nameField} component="th" scope="row">
ROOM:
</TableCell>
<TableCell width={'16.67%'} align="left">{data.emp_department}</TableCell>
<TableCell width={'16.67%'} className={classesGrid.nameField} component="th" scope="row">
POSITION:
</TableCell>
<TableCell width={'16.67%'} align="left">{data.emp_title}</TableCell>
<TableCell width={'16.67%'} className={classesGrid.nameField} component="th" scope="row">
HIRE DATE:
</TableCell>
<TableCell width={'16.67%'} align="left">{data.date_join}</TableCell>
</TableRow>
<TableRow >
<TableCell width={'16.67%'} className={classesGrid.nameField} component="th" scope="row">
LEFT DATE:
</TableCell>
<TableCell width={'16.67%'} align="left">{data.date_left}</TableCell>
</TableRow>
</TableBody>
</Table>
</TableContainer>
</Grid>
</Paper>
</div>
</div>
)
}
|
import React from 'react';
import FormControl from '@material-ui/core/FormControl';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import Select from '@material-ui/core/Select';
import {connect} from "react-redux";
import {testAPICall} from "../reducers";
import compose from 'recompose/compose';
import {withStyles} from '@material-ui/core/styles';
import {CREATE_ALERT, CREATE_TODO, CREATE_UPCOMING_ALERT,} from "../actions";
import DialogTitle from "@material-ui/core/DialogTitle/";
import DialogContent from "@material-ui/core/DialogContent/";
import Dialog from "@material-ui/core/Dialog/";
import DialogActions from '@material-ui/core/DialogActions';
import NotEmptyTextField from '../validatedFields/notEmptyTextField';
const styles = theme => ({
root: {
...theme.mixins.gutters(),
paddingTop: theme.spacing.unit * 2,
paddingBottom: theme.spacing.unit * 2,
height: "auto",
},
textField: {
marginTop: theme.spacing.unit,
marginBottom: theme.spacing.unit,
},
button: {
marginTop: theme.spacing.unit,
marginBottom: theme.spacing.unit,
},
input: {
display: 'none',
},
hiddenTextField: {
display: 'none',
}
});
class CreateReminder extends React.Component {
state = {
reminderForm: {
title: '',
alert_time: '',
is_todo: false,
category: '',
},
};
handleClose = () => {
this.props.onClose();
};
handleChange = name => event => {
const reminderForm = Object.assign({}, this.state.reminderForm, {[name]: event.target.value,});
this.setState({
reminderForm: reminderForm,
});
};
handleCheckboxChange = name => event => {
const reminderForm = Object.assign({}, this.state.reminderForm, {[name]: event.target.checked,});
this.setState({
reminderForm: reminderForm,
});
};
handleSubmit = () => {
const {dispatch} = this.props;
let payload = {
title: this.state.reminderForm.title,
is_todo: this.state.reminderForm.is_todo,
category: this.state.reminderForm.category,
account: this.accountId,
};
let message = "To Do Created";
let type = CREATE_TODO;
const alertDate = new Date(this.state.reminderForm.alert_time);
const currentDate = new Date();
if (!this.state.reminderForm.is_todo) {
type = CREATE_ALERT;
if (alertDate > currentDate) {
type = CREATE_UPCOMING_ALERT;
}
payload['alert_time'] = this.state.reminderForm.alert_time;
message = "Alert Created";
}
dispatch(testAPICall(`/api/v1/accounts/alert/`,
type,
payload,
() => {
this.handleClose();
this.setState({
reminderForm: {
title: '',
alert_time: '',
is_todo: false,
category: '',
}
})
},
'POST',
null,
message))
};
accountId = this.props.id;
render() {
const {accounts, categories, classes, open} = this.props;
const account = accounts[this.accountId];
let accountName = "";
if (account !== undefined) {
accountName = account.name;
}
return (
<Dialog fullWidth={true} onClose={this.handleClose} aria-labelledby="dialog-title" open={open}>
<DialogTitle id="dialog-title">Alert for Account - {accountName}</DialogTitle>
<DialogContent>
<FormControl fullWidth>
<NotEmptyTextField
required
id="title"
label="Title"
className={classes.textField}
value={this.state.reminderForm.title}
onChange={this.handleChange('title')}
margin="none"
/>
<FormControlLabel
control={
<Checkbox
checked={this.state.reminderForm.is_todo}
onChange={this.handleCheckboxChange('is_todo')}
value="is_todo"
/>
}
label="Is Todo?"
/>
<TextField
required
id="alert_time"
label="Alert Date"
className={!this.state.reminderForm.is_todo ? classes.textField : classes.hiddenTextField}
value={this.state.reminderForm.alert_time}
onChange={this.handleChange('alert_time')}
margin="none"
type="date"
InputLabelProps={{shrink: true}}
/>
<FormControl fullWidth required className={classes.formControl}>
<InputLabel htmlFor="type">Category</InputLabel>
<Select
value={this.state.reminderForm.category}
onChange={this.handleChange('category')}
name="type"
inputProps={{
id: 'category',
}}
className={classes.selectEmpty}
>
{Object.keys(categories).map(key => (
<MenuItem
key={categories[key].id}
value={categories[key].id}
>
{categories[key].name}
</MenuItem>
))}
</Select>
</FormControl>
</FormControl>
</DialogContent>
<DialogActions>
<Button onClick={this.handleClose} color="primary">
Cancel
</Button>
<Button
color="secondary"
className={classes.button}
onClick={(event) => {
this.handleSubmit(event)
}}
>
Save
</Button>
</DialogActions>
</Dialog>
);
}
}
const mapStateToProps = state => {
return {
accounts: state.accounts.accounts,
categories: state.accounts.categories,
}
};
const mapDispatchToProps = dispatch => {
return {
dispatch: dispatch
}
};
export default compose(
withStyles(styles),
connect(mapStateToProps, mapDispatchToProps)
)(CreateReminder)
|
import { combineReducers } from 'redux';
import productReducer from './productReducer';
import userReducer from './userLoginReducer';
import { addCartReducer, countCartReducer, userCartReducer } from './cartReducer'
export default combineReducers({
products: productReducer,
user: userReducer,
cart: addCartReducer,
usercart: userCartReducer
});
|
var vows = require('./setup')
, assert = require('assert')
, baker = require('../lib/baker')
, path = require('path')
var PNGFILE = path.join(__dirname, 'no-badge-data.png');
vows.describe('bake some badges').addBatch({
'A clean PNG': {
'should fail if not given data': function(){
assert.throws(function(){ baker.prepare(PNGFILE) }, Error);
},
'can be a prepared with badge data': function(){
var badge = baker.prepare(PNGFILE, 'https://location-of-badge');
var data = baker.read(badge);
assert.equal(data, 'https://location-of-badge');
},
},
'A prepared PNG': {
topic: function(){
return baker.prepare(PNGFILE, 'https://location-of-badge');
},
'should fail if another is given': function(buf){
assert.throws(function(){ baker.prepare(buf, 'new-stuff') }, Error);
}
}
}).export(module);
|
let mongoose = require('mongoose');
let ExpenditureTypeSchema = require('../schemas/ExpenditureTypeSchema');
let ExpenditureType = mongoose.model('expenditureType', ExpenditureTypeSchema);
module.exports = ExpenditureType;
|
import React from "react";
import StateDataArray from "../Data/StateDataArray";
import { useHistory } from "react-router-dom";
const StatesGrid = ({ gridState, keywords }) => {
const history = useHistory();
function check(slug) {
console.log(slug);
history.push(`/cities/${slug}`);
}
const search = (keywords) => (gridState) =>
gridState.title.toLowerCase().includes(keywords);
return (
<div className="states-parent-grid-container">
{gridState
.filter(search(keywords))
.map(({ id, code, title, slug, background }) => {
return (
<div
key={id}
className={`states-child-grid-container`}
id={`child-${id}`}
>
<div
style={{ background: background }}
className="child child-1"
onClick={() => check(slug)}
>
{code}
</div>
<div className="state-name">{title}</div>
</div>
);
})}
</div>
);
};
export default StatesGrid;
/* <div className="states-child-grid-container top-child" id="top-child-2">
<div className="child child-2">AP</div>
<div className="state-name">Andhra Pradesh</div>
</div>
<div className="states-child-grid-container">
<div className="child child-3">AR</div>
<div className="state-name">Arunachal Pradesh</div>
</div>
<div className="states-child-grid-container">
<div className="child child-4">AS</div>
<div className="state-name">Assam</div>
</div>
<div className="states-child-grid-container">
<div className="child child-5">BR</div>
<div className="state-name">Bihar</div>
</div>
<div className="states-child-grid-container">
<div className="child child-6">CH</div>
<div className="state-name">Chandigarh</div>
</div>
<div className="states-child-grid-container">
<div className="child child-7">CG</div>
<div className="state-name">Chattisgarh</div>
</div>
<div className="states-child-grid-container">
<div className="child child-8">DN</div>
<div className="state-name">Dadra and Nagar Haveli</div>
</div>
<div className="states-child-grid-container">
<div className="child child-9">DD</div>
<div className="state-name">Daman and DILI</div>
</div>
<div className="states-child-grid-container">
<div className="child child-10">DL</div>
<div className="state-name">Delhi</div>
</div>
<div className="states-child-grid-container">
<div className="child child-11">GA</div>
<div className="state-name">Goa</div>
</div>
<div className="states-child-grid-container">
<div className="child child-12">GJ</div>
<div className="state-name">Gujarat</div>
</div>
<div className="states-child-grid-container">
<div className="child child-13">HR</div>
<div className="state-name">Haryana</div>
</div>
<div className="states-child-grid-container">
<div className="child child-14">HP</div>
<div className="state-name">Himachal Pradesh</div>
</div>
<div className="states-child-grid-container">
<div className="child child-15">JK</div>
<div className="state-name">Jammu & Kashmir</div>
</div>
<div className="states-child-grid-container">
<div className="child child-16">JH</div>
<div className="state-name">Jharkand</div>
</div>
<div className="states-child-grid-container">
<div className="child child-17">KA</div>
<div className="state-name">Karnataka</div>
</div>
<div className="states-child-grid-container">
<div className="child child-18">KL</div>
<div className="state-name">Kerala</div>
</div>
<div className="states-child-grid-container">
<div className="child child-19">LD</div>
<div className="state-name">Lakshadweep</div>
</div>
<div className="states-child-grid-container">
<div className="child child-20">MP</div>
<div className="state-name">Madhya Pradesh</div>
</div>
<div className="states-child-grid-container">
<div className="child child-21">MH</div>
<div className="state-name">Maharashtra</div>
</div>
<div className="states-child-grid-container">
<div className="child child-22">MM</div>
<div className="state-name">Manipur</div>
</div>
<div className="states-child-grid-container">
<div className="child child-23">ML</div>
<div className="state-name">Meghalaya</div>
</div>
<div className="states-child-grid-container">
<div className="child child-24">MZ</div>
<div className="state-name">Mizoram</div>
</div>
<div className="states-child-grid-container">
<div className="child child-25">NL</div>
<div className="state-name">Nagaland</div>
</div>
<div className="states-child-grid-container">
<div className="child child-26">OR</div>
<div className="state-name">Orissa</div>
</div>
<div className="states-child-grid-container">
<div className="child child-27">PY</div>
<div className="state-name">Pondicherry</div>
</div>
<div className="states-child-grid-container">
<div className="child child-28">PB</div>
<div className="state-name">Punjab</div>
</div>
<div className="states-child-grid-container">
<div className="child child-29">RJ</div>
<div className="state-name">Rajasthan</div>
</div>
<div className="states-child-grid-container">
<div className="child child-30">SK</div>
<div className="state-name">Sikkim</div>
</div>
<div className="states-child-grid-container">
<div className="child child-31">TN</div>
<div className="state-name">Tamil Nadu</div>
</div>
<div className="states-child-grid-container">
<div className="child child-32">TS</div>
<div className="state-name">Telengana</div>
</div>
<div className="states-child-grid-container">
<div className="child child-33">TR</div>
<div className="state-name">Tripura</div>
</div>
<div className="states-child-grid-container">
<div className="child child-34">UP</div>
<div className="state-name">Uttar Pradesh</div>
</div>
<div className="states-child-grid-container" id="bottom-child-1">
<div className="child child-35">WB</div>
<div className="state-name">West Bengal</div>
</div>
<div className="states-child-grid-container" id="bottom-child-2">
<div className="child child-36">XX</div>
<div className="state-name">Other</div>
</div>*/
|
import HorizontalScroll from './HorizontalScroll';
import VerticalScroll from './VerticalScroll';
export { HorizontalScroll, VerticalScroll };
|
function toolbarClickPatient(args) {
if (args.item.id === 'editInformations') {
var gridInformation = document.getElementById("Grid").ej2_instances[0];
var rowInformation = gridInformation.getSelectedRecords();
window.location.href = 'Informations/Informations' + '/' + rowInformation[0].Id;
}
if (args.item.id === 'editFamily') {
var gridFamily = document.getElementById("Grid").ej2_instances[0];
var rowFamily = gridFamily.getSelectedRecords();
window.location.href = 'Family/Index' + '/' + rowFamily[0].Id;
}
if (args.item.id === 'editConsultations') {
var gridConsultations = document.getElementById("Grid").ej2_instances[0];
var rowConsultations = gridConsultations.getSelectedRecords();
window.location.href = 'Consultations/Index' + '/' + rowConsultations[0].Id;
}
//if (args.item.id === "collapseall") {
// this.groupModule.collapseAll();
//}
}
// Pregnancy Value Change
function pregnancyValueChange() {
var listObj = document.getElementById('pregnancyType').ej2_instances[0];
var pregnancyRow = document.getElementById('pregnancyRow');
if (listObj.value !== 'Prématurité') {
pregnancyRow.hidden = true;
} else {
pregnancyRow.hidden = false;
}
}
function toolbarClickConsultation(args) {
if (args.item.id === 'editConsultation') {
var gridInformation = document.getElementById("GridConsultation").ej2_instances[0];
var rowInformation = gridInformation.getSelectedRecords();
// window.location =
window.location.pathname = "";
window.location.assign(window.location.origin + '/Consultations/Consultation' + '/' + rowInformation[0].Id);
}
if (args.item.id === 'addConsultation') {
window.location.pathname = "";
window.location.assign(window.location.origin + '/Consultations/Consultation');
}
}
function submitSiblingsGridOnClick(args) {
var gridSiblings = document.getElementById("GridSiblings").ej2_instances[0];
$("#GridData").val(JSON.stringify(gridSiblings.dataSource));
}
function girdSiblingsOnCreated(args) {
var gridInformation = document.getElementById("GridSiblings").ej2_instances[0];
$("#GridData").val(JSON.stringify(gridInformation.dataSource));
}
//function testClickButton(args) {
// var gridInformation = document.getElementById("GridSiblings").ej2_instances[0];
// var siblings = (gridInformation.dataSource);
// //var form = document.getElementById("formFamily");
// //var patients = form.dataset;
// var data = $('#formFamily').serializeArray();
// // var test = JSON.stringify(siblings);
// $.ajax({
// type: 'POST',
// accepts: 'application/json',
// url: '/Family/SiblingsFromGrid',
// contentType: 'application/json',
// data: JSON.stringify({ ViewModel: data, Siblings: siblings }),
// error: function (jqXHR, textStatus, errorThrown) {
// alert('here');
// },
// success: function (result) {
// getData();
// $('#add-name').val('');
// }
// });
//}
//$.ajax({
// url: "/Family/Data",
// type: "POST",
// datatype: "json",
// contentType: 'application/json',
// data: JSON.stringify({ gid: JSON.stringify(gridInformation.dataSource) }),
// success: function (result) {
// debugger;
// }
//});
ej.base.L10n.load({
// To set the culture globally
'fr': {
'grid': {
EmptyRecord: "Aucun patient à afficher",
GroupDropArea: "Faites glisser un en-tête de colonne ici pour groupe sa colonne",
DeleteOperationAlert: "Aucun patients sélectionnés pour l'opération de suppression",
EditOperationAlert: "Aucun patients sélectionnés pour l'opération d'édition",
SaveButton: "sauvegarder",
OKButton: "OK",
CancelButton: "Annuler",
EditFormTitle: "Les détails de patient ",
AddFormTitle: "Ajouter un nouvel patient",
GroupCaptionFormat: "{{:headerText}}: {{:key}} - {{:count}} {{if count == 1 }} article {{else}} articles {{/if}} ",
BatchSaveConfirm: "Etes-vous sûr que vous voulez enregistrer les modifications?",
BatchSaveLostChanges: "Les modifications non enregistrées seront perdues. Es-tu sur de vouloir continuer?",
ConfirmDelete: "Etes-vous sûr de vouloir supprimer le patient?",
CancelEdit: "Etes-vous sûr que vous voulez annuler les modifications?",
PagerInfo: "{0} sur {1} pages ({2} patients)",
FrozenColumnsViewAlert: "colonnes congelés doivent être dans la zone gridview",
FrozenColumnsScrollAlert: "Activer permettre le défilement, tout en utilisant des colonnes congelés",
FrozenNotSupportedException: "Les colonnes et les lignes figées sont pas pris en charge pour le regroupement, modèle Row, modèle de Détail, Hiérarchie Grid et Batch Édition",
Add: "Ajouter",
Edit: "modifier",
Delete: "Effacer",
Update: "Mettre à jour",
Cancel: "Annuler",
Done: "Terminé",
Columns: "colonnes",
SelectAll: "(Sélectionner tout)",
PrintGrid: "Impression",
ExcelExport: "Excel Export",
WordExport: "parole Export",
PdfExport: "PDF Export",
StringMenuOptions: [{ text: "Commence avec", value: "StartsWith" }, { text: "Se termine par", value: "EndsWith" }, { text: "contient", value: "Contains" }, { text: "Égal", value: "Equal" }, { text: "Inequal", value: "NotEqual" }],
NumberMenuOptions: [{ text: "Moins que", value: "LessThan" }, { text: "Plus grand que", value: "GreaterThan" }, { text: "Inférieur ou equal", value: "LessThanOrEqual" }, { text: "Meilleur que ou equal", value: "GreaterThanOrEqual" }, { text: "Égal", value: "Equal" }, { text: "Inequal", value: "NotEqual" }, { text: "Entre", value: "Between" }],
PredicateAnd: "ET",
PredicateOr: "OU",
Filter: "Filtre",
FilterMenuCaption: "Valeur du filtre",
FilterMenuFromCaption: "De",
FilterMenuToCaption: "À",
FilterbarTitle: "s bar filtre cellulaire",
MatchCase: "Cas de correspondance",
Clear: "Clair",
ResponsiveFilter: "Filtre",
ResponsiveSorting: "Trier",
Search: "Chercher",
NumericTextBoxWaterMark: "Entrer la valeur",
DatePickerWaterMark: "Sélectionner une date",
EmptyDataSource: "DataSource doit pas être vide au chargement initial car les colonnes sont générés à partir dataSource dans AutoGénéré Colonne Grille",
ForeignKeyAlert: "La valeur mise à jour devrait être une valeur de clé étrangère valide",
True: "vrai",
False: "faux",
UnGroup: "Cliquez ici pour dégrouper",
AddRecord: "Ajouter un patient",
EditRecord: "edit patient",
DeleteRecord: "supprimer le patient",
Save: "sauvegarder",
Grouping: "Groupe",
Ungrouping: "Dissocier",
SortInAscendingOrder: "Tri par ordre croissant",
SortInDescendingOrder: "Trier par ordre décroissant",
NextPage: "Page suivante",
PreviousPage: "page précédente",
FirstPage: "Première page",
LastPage: "Dernière page",
EmptyRowValidationMessage: "Au moins un champ doit être mis à jour",
NoResult: "Aucun résultat",
Item: 'Patient',
Items: 'Patients'
},
'pager': {
currentPageInfo: "{0} de {1} pages",
totalItemsInfo: '({0} patients)',
firstPageTooltip: "Aller à la première page",
lastPageTooltip: "Aller à la dernière page",
nextPageTooltip: "Aller à la page suivante",
previousPageTooltip: "Aller à la page précédente",
nextPagerTooltip: "Aller à la page suivante",
previousPagerTooltip: "Aller à la page précédente"
},
'schedule': {
"day": "journée",
"week": "La semaine",
"workWeek": "Semaine de travail",
"month": "Mois"
}
},
'de-DE': {
'grid': {
EmptyRecord: "Keine Aufzeichnungen angezeigt",
GroupDropArea: "Ziehe Sie einen Spaltenkopf hierher um die Spalten zu gruppieren",
DeleteOperationAlert: "Für den Löschvorgang wurden keine Datensätze ausgewählt",
EditOperationAlert: "Für den Bearbeitungsvorgang wurden keine Datensätze ausgewählt",
SaveButton: "sparen",
OKButton: "OK",
CancelButton: "Stornieren",
EditFormTitle: "Informationen von ",
AddFormTitle: "Fügen Sie einen neuen Datensatz hinzu",
GroupCaptionFormat: "{{:headerText}}: {{:key}} - {{:count}} {{if count == 1 }} Artikel {{else}} Artikel {{/if}} ",
BatchSaveConfirm: "Sind Sie sicher Sie wollen das Speichern?",
BatchSaveLostChanges: "Ungespeicherte Änderungen gehen verloren. Wollen Sie fortfahren?",
ConfirmDelete: "Sind Sie sicher Sie wollen diesen Datensatz löschen?",
CancelEdit: "Sind Sie sicher Sie wollen die Änderungen löschen?",
PagerInfo: "{0} von {1} Seiten ({2} Beiträge)",
FrozenColumnsViewAlert: "Fixierte Spalte soll in den Gitternetzansichtsbereich",
FrozenColumnsScrollAlert: "AllowScrolling erlauben während der Verwendung von fixierten Spalten",
FrozenNotSupportedException: "Fixierte Spalten und Zeilen werden, für Gruppierungszeilenvorlage, Detailvorlage, Hierachieraster und Stapelbearbeitung nicht unterstützt",
Add: "Hinzufügen",
Edit: "Bearbeiten",
Delete: "Löschen",
Update: "Aktualisieren",
Cancel: "Stornieren",
Done: "Erledigt",
Columns: "Columns",
SelectAll: "(Alles auswählen)",
PrintGrid: "Drucken",
ExcelExport: "Excel Export",
WordExport: "Word-Export",
PdfExport: "PDF-Export",
StringMenuOptions: [{ text: "Beginnt mit", value: "StartsWith" }, { text: "Endet mit", value: "EndsWith" }, { text: "Enthält", value: "Contains" }, { text: "Gleich", value: "Equal" }, { text: "Nicht equal", value: "NotEqual" }],
NumberMenuOptions: [{ text: "Weniger als", value: "LessThan" }, { text: "Größer als", value: "GreaterThan" }, { text: "Kleiner als oder equal", value: "LessThanOrEqual" }, { text: "Größer als oder equal", value: "GreaterThanOrEqual" }, { text: "Gleich", value: "Equal" }, { text: "Nicht equal", value: "NotEqual" }, { text: "Zwischen", value: "Between" }],
PredicateAnd: "UND",
PredicateOr: "ODER",
Filter: "Filter",
FilterMenuCaption: "Filterwert",
FilterMenuFromCaption: "Von",
FilterMenuToCaption: "Nach",
FilterbarTitle: "Filterleiste für Spalte",
MatchCase: "Kleinschreibung",
Clear: "Löschen",
ResponsiveFilter: "Filter",
ResponsiveSorting: "Sortieren",
Search: "Suche",
NumericTextBoxWaterMark: "Geben Sie den Wert ein",
DatePickerWaterMark: "Select date",
EmptyDataSource: "Die Quelldaten dürfen bei Inizialisierung nicht leer sein, da die Spalten im AutoGenerierungs Spalten Gitternetz generiert werden",
ForeignKeyAlert: "Der aktualiserte Wert sollte einen gültiger Fremdschlüsselwert haben",
True: "wahr",
False: "falsch",
UnGroup: "Hier Klicken um Gruppierung aufzuheben",
AddRecord: "Datensatz hinzufügen",
EditRecord: "Datensatz bearbeiten",
DeleteRecord: "Datensatz löschen",
Save: "sparen",
Grouping: "Gruppieren",
Ungrouping: "Gruppierung aufheben",
SortInAscendingOrder: "Aufsteigend sortieren",
SortInDescendingOrder: "Absteigend sortieren",
NextPage: "Nächte Seite",
PreviousPage: "Vorherige Seite",
FirstPage: "Erste Seite",
LastPage: "Letzte Seite",
EmptyRowValidationMessage: "Zumindestens ein Feld muss aktualisiert werden",
NoResult: "Keine Treffer gefunden"
},
'pager':{
pagerInfo: "{0} von {1} Seiten ({2} Stück)",
firstPageTooltip: "Erste Seite",
lastPageTooltip: "Letzte Seite",
nextPageTooltip: "Nächste Seite",
previousPageTooltip: "Vorherige Seite",
nextPagerTooltip: "Nächste Seitengruppe",
previousPagerTooltip: "Vorherige Seitengruppe"
}
}
});
//ej.base.loadcldr('cldr-data/main/fr/ca-gregorian.json');
//ej.base.setCulture('fr');
// copy from https://github.com/syncfusion/ej-global/tree/master/l10n
loadCultureFiles('fr');
function loadCultureFiles(name) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
//debugger;
ajax = new ej.base.Ajax(location.origin + '/scripts/cldr-data/main/' + name + '/' + files[prop], 'GET', false);
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
ej.base.setCulture(name);
ej.base.setCurrencyCode('EUR');
}
|
export default {
set_company_info(state, value) {
state.company = value;
},
set_myproducts_info(state, value) {
state.products = value;
},
set_allproducts_info(state, value) {
state.allProducts = value;
},
set_MyCoupons_info(state, value) {
state.MyCoupons = value;
},
set_MyUsedCoupons_info(state, value) {
state.MyUsedCoupons = value;
},
set_MyExpCoupons_info(state, value) {
state.MyExpCoupons = value;
},
set_prcoupons_info(state, value) {
state.prcoupons = value;
}
};
|
import React from "react";
const tableStyle = {
width:'100%',
}
const Stats = ({stats}) => (
<table className='w3-table w3-bordered' style={tableStyle}>
{stats.map(stats=>
<tbody>
<tr><td>{stats.h_shots_on_goal}</td><td>Shots on Goal</td><td>{stats.a_shots_on_goal}</td></tr>
<tr><td>{stats.h_total_shots}</td><td>Total Shots</td><td>{stats.a_total_shots}</td></tr>
<tr><td>{stats.h_fouls}</td><td>Fouls</td><td>{stats.a_fouls}</td></tr>
<tr><td>{stats.h_corners}</td><td>Corner Kicks</td><td>{stats.a_corners}</td></tr>
<tr><td>{stats.h_offsides}</td><td>Offsides</td><td>{stats.a_offsides}</td></tr>
<tr><td>{stats.h_possestiontime}%</td><td>Possession</td><td>{stats.a_possestiontime}%</td></tr>
<tr><td>{stats.h_yellowcards}</td><td>Yellow Cards</td><td>{stats.a_yellowcards}</td></tr>
<tr><td>{stats.h_redcards}</td><td>Red Cards</td><td>{stats.a_redcards}</td></tr>
<tr><td>{stats.h_saves}</td><td>Saves</td><td>{stats.a_saves}</td></tr>
</tbody>
)}
</table>
);
export default Stats
|
import React from 'react'
const MESSAGES = {
'rock': 'Rock',
'paper': 'Paper',
'scissors': 'Scissors',
'p1Wins': 'Player 1 Wins',
'p2Wins': 'Player 2 Wins',
'draw': 'Draw',
}
export default class PlayForm extends React.Component {
constructor(props) {
super(props)
this.state = {
result: null,
rounds: null,
}
}
invalid() {
this.setState({
result: 'Invalid Input'
})
}
p1Wins() {
this.setState({
result: 'Player 1 Wins!'
})
}
p2Wins() {
this.setState({
result: 'Player 2 Wins!'
})
}
draw() {
this.setState({
result: 'Draw!'
})
}
onClickSubmit() {
this.props.request.play(
this.state.player1Input,
this.state.player2Input,
this)
}
onChangePlayer1Input(event) {
this.setState({
player1Input: event.target.value
});
}
onChangePlayer2Input(event) {
this.setState({
player2Input: event.target.value
});
}
onHistoryClick() {
this.props.request.getHistory(this)
}
noRounds() {
this.setState({rounds: []})
}
rounds(rounds) {
this.setState({rounds})
}
displayRounds() {
if (this.state.rounds === null) {
return
}
if (this.state.rounds.length === 0) {
return <p>no rounds played</p>
}
return this.state.rounds.map((round, index) => (
<div key={index}>
<p>{MESSAGES[round.p1]} {MESSAGES[round.p2]} {MESSAGES[round.result]}</p>
</div>
))
}
render() {
return (
<div>
<h1>RPS App</h1>
<input name='player1'
onChange={this.onChangePlayer1Input.bind(this)}/>
<input name='player2'
onChange={this.onChangePlayer2Input.bind(this)}/>
<button name="play" onClick={this.onClickSubmit.bind(this)}>登録</button>
<div>{this.state.result}</div>
<div>
<button name="history" onClick={this.onHistoryClick.bind(this)}>History</button>
<br/>
{this.displayRounds()}
</div>
</div>
)
}
}
|
import React, { useEffect, useState } from 'react';
import './style.scss';
const AnimateText = ({ text, period, play, unmount, style }) => {
const [delta, setDelta] = useState(200);
const [loopNum, setLoopNum] = useState(0);
const [word, setWord] = useState('');
const [isDeleting, setIsDeleting] = useState(false);
const [pause, setPause] = useState(false);
const [times, settimes] = useState(null);
useEffect(() => {
const inteval = play
? setInterval(() => {
const loop = async () => {
const i = loopNum % text.length;
const fullTxt = text[i];
if (!pause) {
if (isDeleting) setWord(fullTxt.substring(0, word.length - 1));
else setWord(fullTxt.substring(0, word.length + 1));
}
setDelta(200 - Math.random() * 100);
if (isDeleting) {
setDelta(delta / 1.2);
}
if (!isDeleting && word === fullTxt) {
setDelta(period);
setIsDeleting(true);
setPause(true);
const timeout = setTimeout(function () {
setPause(false);
}, 1000);
settimes(timeout);
} else if (isDeleting && word === '') {
setIsDeleting(false);
setLoopNum(loopNum + 1);
setDelta(500);
}
};
loop();
}, delta)
: null;
return () => {
clearInterval(inteval);
if (unmount) clearTimeout(times);
};
}, [
delta,
isDeleting,
loopNum,
pause,
period,
play,
text,
times,
unmount,
word,
]);
return play ? (
<p className='typee' style={style}>
{word}
<span className='cursor'></span>
</p>
) : null;
};
export default AnimateText;
|
/// Resources.js
// This is simple an image loading utility. called engine.js
(function() {
var MyresourceCache = {};
var readyForCallbacks = [];
/// This is the public image loading function.
function load(urlOrArray) {
if(urlOrArray instanceof Array)
{
urlOrArray.forEach(function(url)
{
_load(url);
});
} else {
_load(urlOrArray);
}
}
// This is our private image loader function.
function _load(url) {
if(MyresourceCache[url]) {
// chcek for If this URL has been loaded before then
//it will exist with on the
// our MyresourceCache array.
//Just return for that image not
// our re-loading the image.
return MyresourceCache[url];
} else {
// This URL is not before loaded and is not present.
var img = new Image();
img.onload = function() {
// Once our image has properly loaded.
MyresourceCache[url] = img;
// When the image is loaded and cached,
// call all of the onReady functions.
if(Ready()) {
//Check for each
readyForCallbacks.forEach(function(func) { func(); });
}
};
// Set initial value to false.
MyresourceCache[url] = false;
img.src = url;
}
}
// This is used for grab some referances.
function get(url) {
return MyresourceCache[url];
}
// This function determines if all of the images that have been requested.
function Ready() {
var ready = true;
for(var k in MyresourceCache) {
//Check for property
if(MyresourceCache.hasOwnProperty(k) &&
!MyresourceCache[k]) { ready = false;
}
}
return ready;
}
// This function will add a function to the callback stack.
function onReady(func) {
readyForCallbacks.push(func);
}
// This object defines the publicly accessible functions.
window.Resources = {
load: load,
get: get,
onReady: onReady,
Ready: Ready
};
})();
|
import React,{ useContext,useState } from 'react'
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup'
import { UserContext } from '../../UserContext';
import TextError from './TextError';
import { Link, useHistory } from "react-router-dom";
import "react-loader-spinner/dist/loader/css/react-spinner-loader.css";
import Loader from "react-loader-spinner";
import {db} from '../../firebase';
const Login = () => {
const {signin, state} = useContext(UserContext);
const [error, setError] = useState('');
const [loading, setLoading] = useState(false)
const history = useHistory();
const initialValues = {
email: '',
password: '',
}
const onSubmit = (values) => {
setError('');
setLoading(true);
const email = values.email;
const password = values.password;
signin(email, password )
.then((ref) => {
db.collection('userProfile')
.doc(email)
.get()
.then((data) => {
if(data.data().admin === true){
setLoading(false);
history.push("/admin")
}else{
setLoading(false);
history.push("/")
console.log(data)
}
}).catch(err => {
setError(err.message)
})
})
.catch((err) => {
setError(err.message);
setLoading(false);
});
};
const validationSchema = Yup.object({
email: Yup.string().email('Invalid email format').required('Required'),
password: Yup.string().required('Required'),
})
if(loading){
return (
<Loader
type="Puff"
color="#00BFFF"
height={100}
width={100}
timeout={3000} //3 secs
/>
)
}
else{
return (
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={onSubmit}>
<div className='body'>
<div className='form'>
<Form>
<div className='form-logo'>
<Link to='/'><h2>materialhub</h2></Link>
{error ? <p className='form-error'>{error}</p>: null }
</div>
<div className='form-group'>
<Field
placeholder='Email please'
type='text' id='email' name='email' className='form-input'/>
<ErrorMessage name='email' component={TextError}/>
</div>
<div className='form-group'>
<Field
placeholder='Your Password'
type='password' id='password' name='password' className='form-input'/>
<ErrorMessage name='password' component={TextError}/>
</div>
<div className="form-group">
<button className="form-btn" disabled={loading} type='submit'>Log in</button>
</div>
<span className="form-delimiter">
or connect with
</span>
<div className="form-social">
<a href="#" className="form-social-item fb">
<i className="fab fa-facebook-square"></i>
</a>
<a href="#" className="form-social-item tw">
<i className="fab fa-twitter"></i>
</a>
<a href="#" className="form-social-item gg">
<i className="fab fa-google"></i>
</a>
</div>
<span className="form-txt">
Don't have an account?
<Link to='/signup'>Register</Link>
</span>
<span className="form-txt">
<a href="#">Forgot password?</a>
</span>
</Form>
</div>
</div>
</Formik>
)
}
}
export default Login
|
import React, { Component } from 'react'
import {
Badge,
Button,
ButtonDropdown,
ButtonGroup,
ButtonToolbar,
Card,
CardBody,
CardFooter,
CardHeader,
CardTitle,
Col,
Dropdown,
DropdownItem,
DropdownMenu,
DropdownToggle,
Progress,
Row,
Table,
} from 'reactstrap';
import p6 from '../../images/p6.png'
import './ProductBox.scss'
class ProductBox extends Component {
render() {
return (
<Row className="ProductBox align-items-center">
<Col md="4">
<img src={p6} alt="p1" className="img-fluid" />
</Col>
<Col className="text-black text-right" md="8">
<h6 className="font-weight-normal">Soniclean Soft Carpet Vacuum</h6>
<h6 className="mt-1">$225/unit</h6>
<h6 className="mt-1">QTY: 2</h6>
</Col>
</Row>
)
}
}
export default ProductBox
|
import React, {Fragment, PureComponent} from 'react';
import {StyleSheet, View, Text, TouchableOpacity, Image} from 'react-native';
import {SvgXml} from 'react-native-svg';
import SVG from '../components/SvgComponent';
export default class Footer extends PureComponent {
constructor(props) {
super(props);
this.state = {
infoVisible: 'none',
};
}
render() {
return (
<Fragment>
{/*예스침한의원,공지,베블링칭찬하기,베블링카카오플러스친구,유투브,인스타,블로그 주석,1:1문의 작성하기*/}
<View>
{/*} <Image
source={require('../images/add02.png')}
style={{width: '100%'}}
resizeMode="contain"
/>
</View> */}
{/* */}
{/* <View
style={{
paddingHorizontal: 16,
backgroundColor: 'white',
marginBottom: 3,
}}>
<View
style={{
flexDirection: 'row',
padding: 10,
borderBottomWidth: 1,
borderBottomColor: '#6b6b6b',
}}>
<View style={{justifyContent: 'center'}}>
<Text style={{fontWeight: '500', marginRight: 20, fontSize: 13}}>
공지
</Text>
</View>
<View style={{justifyContent: 'center'}}>
<Text style={{color: 'gray', fontSize: 13}}>
공지 제목 공지 제목 공지 제목
</Text>
</View>
</View>
<View style={{flexDirection: 'row', padding: 10}}>
<View style={{justifyContent: 'center'}}>
<Text style={{fontWeight: '600', marginRight: 20, fontSize: 13}}>
공지
</Text>
</View>
<View style={{justifyContent: 'center'}}>
<Text style={{color: 'gray', fontSize: 13}}>
공지 제목 공지 제목 공지 제목
</Text>
</View>
</View>
</View> */}
{/* */}
{/* <View style={{backgroundColor: '#f9f9f9', height: 400}}> */}
{/* box */}
{/* <View style={{padding: 16, backgroundColor: 'white'}}>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
backgroundColor: 'white',
padding: 5,
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.1,
shadowRadius: 3.84,
elevation: 5,
}}> */}
{/* 칭찬 */}
{/* <TouchableOpacity
style={{
padding: 8,
alignItems: 'center',
}}>
<SvgXml xml={SVG('BABBLING')} style={{margin: 10}} />
<Text
style={{color: '#32cc73', fontSize: 12, fontWeight: '500'}}>
베블링 칭찬하기
</Text>
</TouchableOpacity> */}
{/* 카플 */}
{/* <View
style={{
backgroundColor: '#dadada',
width: 1,
marginTop: 5,
marginBottom: 5,
}}></View> */}
{/* */}
{/* <TouchableOpacity
style={{
// flex: 1,
padding: 8,
alignItems: 'center',
}}>
<SvgXml xml={SVG('KAKAOPLUS')} style={{margin: 10}} />
<Text
style={{color: '#32cc73', fontSize: 12, fontWeight: '500'}}>
베블링 카카오 플러스 친구
</Text>
</TouchableOpacity> */}
{/* */}
{/* <View
style={{
backgroundColor: '#dadada',
width: 1,
marginTop: 5,
marginBottom: 5,
}}></View> */}
{/* 기타 */}
{/* <View
style={{
padding: 8,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
}}>
<TouchableOpacity>
<SvgXml xml={SVG('YOUTUBE')} style={{margin: 3}} />
</TouchableOpacity>
<TouchableOpacity>
<SvgXml xml={SVG('INSTAGRAM')} style={{margin: 3}} />
</TouchableOpacity>
<TouchableOpacity>
<SvgXml xml={SVG('NAVERBLOG')} style={{margin: 3}} />
</TouchableOpacity>
</View>
</View>
</View> */}
{/* 고객 */}
<View
style={{
padding: 15,
paddingTop: 0,
paddingBottom: 0,
}}>
<View
style={{
flexDirection: 'row',
borderBottomWidth: 1,
borderBottomColor: '#6b6b6b',
height: 60,
justifyContent: 'space-between',
paddingRight: 10,
alignItems: 'center',
}}>
<View style={{paddingLeft: 20}}>
<Text style={{fontSize: 15}} fontWeight="500">
온라인 고객센터
</Text>
</View>
<View
style={{
flexDirection: 'row',
flexGrow: 1,
justifyContent: 'flex-end',
}}>
{/* <TouchableOpacity
style={{
backgroundColor: 'white',
padding: 4,
paddingLeft: 10,
paddingRight: 10,
borderRadius: 50,
shadowColor: '#aaa',
shadowOffset: {
width: 0,
height: 3,
},
shadowOpacity: 0.1,
shadowRadius: 3.84,
elevation: 1,
marginRight: 10,
// QnA화면으로 이동
}}
onPress={() => this.props.navigation.navigate('QnA')}>
<Text
style={{
color: '#32cc73',
fontSize: 12,
fontWeight: '500',
}}>
1:1 문의 작성하기
</Text>
</TouchableOpacity> */}
<TouchableOpacity
style={{
backgroundColor: 'white',
padding: 4,
paddingLeft: 10,
paddingRight: 10,
borderRadius: 50,
shadowColor: '#aaa',
shadowOffset: {
width: 0,
height: 3,
},
shadowOpacity: 0.1,
shadowRadius: 3.84,
elevation: 1,
}}
// FAQ화면이동
onPress={() => this.props.navigation.navigate('FAQ')}>
<Text
style={{
color: '#32cc73',
fontSize: 12,
fontWeight: '500',
}}>
FAQ 보러가기
</Text>
</TouchableOpacity>
</View>
</View>
<View
style={{
flexDirection: 'row',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<View
style={{
flexGrow: 1,
borderRightColor: 'gray',
borderRightWidth: 1,
margin: 5,
paddingLeft: 5,
alignItems: 'flex-start',
}}>
{/* ACCESSTERMS화면으로 이동 */}
<TouchableOpacity
onPress={() => this.props.navigation.navigate('ACCESSTERMS')}>
<Text style={{fontSize: 10}}>
이용약관 및 개인정보처리방침
</Text>
</TouchableOpacity>
</View>
{/* <View
style={{width: 1, height: '90%', backgroundColor: 'gray'}}></View> */}
<View
style={{
flexGrow: 1,
margin: 5,
alignItems: 'center',
}}>
{/* CompanyProfile화면으로 이동 */}
<TouchableOpacity
onPress={() =>
this.props.navigation.navigate('CompanyProfile')
}>
<Text style={{fontSize: 10}}>회사소개</Text>
</TouchableOpacity>
</View>
<View
style={{
margin: 5,
borderLeftColor: 'gray',
borderLeftWidth: 1,
flexGrow: 1,
paddingRight: 10,
alignItems: 'flex-end',
}}>
<Text style={{fontSize: 10}}>사업자정보확인</Text>
</View>
</View>
</View>
{/* 화살표필요 */}
<TouchableOpacity
onPress={() => {
this.setState({
infoVisible: this.state.infoVisible == 'flex' ? 'none' : 'flex',
});
}}
style={{
// backgroundColor: 'gray',
// height: 5,
// justifyContent: 'flex-end',
paddingRight: 24,
alignItems: 'flex-end',
}}>
<SvgXml xml={SVG('DOWNMORE')} />
</TouchableOpacity>
{/* */}
<View
style={[
{
paddingHorizontal: 20,
paddingVertical: 10,
display: this.state.infoVisible,
},
this.state.infoVisible == 'flex' ? 'none' : {height: 0},
]}>
<Text style={{fontSize: 10}}>주식회사 베이비랩</Text>
<View style={{flexDirection: 'row'}}>
<Text style={{fontSize: 10, marginRight: 20}}>
대표이사 | 이지백
</Text>
<Text style={{fontSize: 10}}>사업자등록번호 | 850-87-01216</Text>
</View>
<View style={{flexDirection: 'row', flexWrap: 'wrap'}}>
<Text style={{fontSize: 10, marginRight: 15}}>
Tel | 042-826-6212
</Text>
<Text style={{fontSize: 10, marginRight: 15}}>
Fax | 050-4889-3993
</Text>
<Text style={{fontSize: 10}}>Mail | babylab.v@gmail.com</Text>
</View>
<Text style={{fontSize: 10}}>
주소 | 본사:대전광역시 유성구 덕명로 97번길 19,1층
</Text>
<Text style={{fontSize: 10}}>
기업 부설 연구소:대전광역시 유성구 대학로99, 산학연교육연구관 별관
308호
</Text>
</View>
</View>
</Fragment>
);
}
}
const styles = StyleSheet.create({});
|
$(function(){
$('p').calculateResult();
});
$('p').calculateResult({
passmarks: 33
});
$('p').calculateResult({
marks: [80, 70, 60, 50, 40, 33],
grades: ['A+','A','A-','B','C','D'],
points: [5.00, 4.00, 3.50, 3.00, 2.00, 1.00, 0.00]
});
$('p').calculateResult({
success:function(response) {
var result = response,
mark = response.mark;
console.log(response);
console.log(mark + 10);
}
});
|
'use strict';
describe('Service: goSocketManager', function () {
// load the service's module
beforeEach(module('playerApp'));
// instantiate service
var goSocketManager;
beforeEach(inject(function (_goSocketManager_) {
goSocketManager = _goSocketManager_;
}));
it('should do something', function () {
expect(!!goSocketManager).toBe(true);
});
});
|
'use strict';
var ajaja = require( 'ajaja' );
var antisync = {
series: require( 'antisync/series' )
};
var EventEmitter = require( 'eventemitter2' ).EventEmitter2;
var extend = require( 'extend' );
var diff = require( 'deep-diff' ).diff;
module.exports = DataStore;
function DataStore( hone ) {
var self = this;
EventEmitter.call( self );
self.hone = hone;
self.cache = {};
self.readCache = {};
}
DataStore.prototype = Object.create( EventEmitter.prototype, {} );
function noop() {}
DataStore.prototype._cacheObject = function( key, obj, readonlyObj ) {
var self = this;
self.readCache[ key ] = extend( true, {}, ( typeof( readonlyObj ) !== 'undefined' ? readonlyObj : obj ) );
self.cache[ key ] = obj;
};
DataStore.prototype._decorateObject = function( obj, type, key ) {
var self = this;
obj.__type = type;
obj.__key = key;
obj.save = self._save.bind( self, obj );
obj.delete = self._delete.bind( self, obj );
obj.bare = self._bare.bind( self, obj );
};
DataStore.prototype.create = function( opts, callback ) {
var self = this;
var saveObject = typeof opts.save !== 'undefined' ? opts.save : false;
var cacheObject = typeof opts.cache !== 'undefined' ? opts.cache : true;
var decorateObject = typeof opts.decorate !== 'undefined' ? opts.decorate : true;
var obj = self.hone.objectFactory.create( opts.type.toLowerCase() );
extend( obj, opts.data );
var key = opts.type + ':' + obj._id;
if ( cacheObject ) {
self._cacheObject( key, obj, {} ); // pass an empty read-only object, since we started from nothing here
}
if ( decorateObject ) {
self._decorateObject( obj, opts.type, key );
}
antisync.series( [
function( next ) {
if ( !saveObject ) {
next();
return;
}
ajaja( {
method: 'POST',
url: self.hone.url( '/api/2.0/store/' + opts.type ),
data: opts.data
}, function( error, _obj ) {
if ( error ) {
next( error );
return;
}
var key = opts.type + ':' + _obj._id;
if ( cacheObject ) {
self._cacheObject( key, _obj );
}
if ( decorateObject ) {
self._decorateObject( _obj, opts.type, key );
}
obj = _obj;
next();
} );
}
], function( error ) {
if ( error ) {
callback( error, obj );
return;
}
callback( null, obj );
self.emit( 'create', {
type: opts.type,
id: obj._id,
obj: obj,
saved: saveObject,
cached: cacheObject,
decorated: decorateObject
} );
} );
};
DataStore.prototype.get = function( opts, callback ) {
var self = this;
if ( ( opts.id && opts.query ) || !( opts.id || opts.query ) ) {
callback( {
error: 'invalid query',
message: 'You must specify either an id or a query.'
} );
return;
}
var key = null;
if ( opts.id ) {
key = opts.type + ':' + opts.id;
if ( !opts.force && self.cache[ key ] ) {
self.emit( 'get', {
type: opts.type,
id: opts.id,
result: self.cache[ key ]
} );
callback( null, self.cache[ key ] );
return;
}
}
var fetchOptions = {
method: 'GET',
url: self.hone.url( '/api/2.0/store/' + opts.type ) + ( opts.id ? ( '/' + opts.id ) : '' ),
data: opts.data || {}
};
if ( opts.query ) {
var prevToJSON = RegExp.prototype.toJSON;
RegExp.prototype.toJSON = function() {
return '!!RE:' + this.toString();
};
fetchOptions.data.query = JSON.stringify( opts.query );
if ( opts.view ) {
fetchOptions.data.view = JSON.stringify( opts.view );
}
RegExp.prototype.toJSON = prevToJSON;
}
ajaja( fetchOptions, function( error, result ) {
if ( error ) {
callback( error );
return;
}
// do not cache objects when a view is specified
// TODO: add a hash of the view to the key and cache? need to manage cache size tho
if ( !opts.view ) {
if ( opts.id ) {
self._cacheObject( key, result );
self._decorateObject( result, opts.type, key );
}
else {
if ( Array.isArray( result ) ) {
for( var i = 0; i < result.length; ++i ) {
var obj = result[ i ];
var objKey = opts.type + ':' + obj._id;
self._cacheObject( objKey, obj );
self._decorateObject( obj, opts.type, objKey );
}
}
}
}
self.emit( 'get', {
type: opts.type,
id: opts.id,
query: opts.query,
view: opts.view,
result: result
} );
callback( null, result );
} );
};
DataStore.prototype.load = function( type, obj ) {
var self = this;
var key = type + ':' + obj._id;
self._cacheObject( key, obj );
self._decorateObject( obj, type, key );
return obj;
};
DataStore.prototype._save = function( obj, callback ) {
var self = this;
callback = callback || noop;
var key = obj.__type + ':' + obj._id;
var base = self.readCache[ key ];
var bare = obj.bare();
var changes = diff( base, bare );
if ( !changes ) {
callback( null, obj );
return;
}
ajaja( {
method: 'PUT',
url: self.hone.url( '/api/2.0/store/' + obj.__type + '/' + obj._id ),
data: changes
}, function( error, _obj ) {
if ( error ) {
callback( error );
return;
}
self._cacheObject( key, obj, _obj );
extend( obj, _obj );
var changeObj = {
type: obj.__type,
id: obj._id,
result: obj,
changes: changes
};
self.emit( 'save', changeObj );
self.emit( 'change', changeObj );
self.emit( 'change.' + obj.__type, changeObj );
self.emit( 'change.' + obj.__type + '.' + obj._id, changeObj );
callback( null, obj );
} );
};
DataStore.prototype._delete = function( obj, callback ) {
var self = this;
callback = callback || noop;
var type = obj.__type;
var id = obj._id;
var key = obj.__key;
ajaja( {
method: 'DELETE',
url: self.hone.url( '/api/2.0/store/' + type + '/' + id )
}, function( error ) {
if ( error ) {
self._decorateObject( obj, type, key );
callback( error );
return;
}
delete self.readCache[ key ];
delete self.cache[ key ];
var event = {
type: type,
id: id
};
self.emit( 'delete', event );
callback();
} );
};
DataStore.prototype._bare = function( obj ) {
var bare = extend( true, {}, obj );
delete bare.__type;
delete bare.__key;
delete bare.save;
delete bare.delete;
delete bare.bare;
// remove local variables (__ prefixed, TODO: make configurable?)
for ( var key in bare ) {
if ( !bare.hasOwnProperty( key ) ) {
continue;
}
if ( key.indexOf( '__' ) === 0 ) {
delete bare[ key ];
}
}
return bare;
};
|
import React from 'react'
import PropTypes from 'prop-types'
import Radium from '@instacart/radium'
import NavigationPill from './NavigationPill'
import ScrollTrack from '../ScrollTrack/ScrollTrack'
import colors from '../../styles/colors'
import spacing from '../../styles/spacing'
const styles = {
labelStyles: {
margin: '0 10px 0 0',
display: 'inline',
fontSize: 'inherit',
},
wrapperStyles: {
display: 'inline-block',
height: '56px',
minWidth: '100%',
...spacing.PADDING_TOP_XS,
...spacing.PADDING_RIGHT_XS,
...spacing.PADDING_BOTTOM_XS,
...spacing.PADDING_LEFT_MD,
backgroundColor: colors.WHITE,
boxSizing: 'border-box',
},
pillsContainerStyles: {
display: 'inline-block',
marginTop: '0',
marginRight: '0',
marginBottom: '0',
marginLeft: '0',
},
}
class NavigationPills extends React.Component {
static propTypes = {
/** Any additonal props to add to the element (e.g. data attributes). */
elementAttributes: PropTypes.object,
/** Any additonal props to add to the inner ul element (e.g. data attributes). */
listItemAttributes: PropTypes.object,
/** array of pill objects */
pills: PropTypes.array,
/** Callback function called after pill click
* @param {SyntheticEvent} event The react `SyntheticEvent`
* @param {props} object All the props passed to the component
*/
onPillClick: PropTypes.func,
/** optional label placed in front of pills */
label: PropTypes.string,
/** string matching the text of one of the pills. Determines which pill is active, if any */
activePill: PropTypes.string,
/** optional string for overriding the tag name of the label which appears in front of pills */
labelElementType: PropTypes.string,
}
static defaultProps = {
elementAttributes: {},
labelElementType: 'label',
}
render() {
const {
label,
activePill,
onPillClick,
pills,
elementAttributes,
listItemAttributes,
} = this.props
const renderLabel = () => {
if (!label) {
return
}
const { labelElementType: LabelElementType } = this.props
return <LabelElementType style={styles.labelStyles}>{label}</LabelElementType>
}
const renderPill = (pill, idx) => {
return (
<NavigationPill
isActive={activePill === pill.text}
onClick={e => onPillClick(e, pill)}
text={pill.text}
key={`pill-${idx}`}
elementAttributes={pill.elementAttributes}
anchorItemAttributes={pill.anchorItemAttributes}
/>
)
}
const { pillsContainerStyles, wrapperStyles } = styles
if (!pills || pills.length <= 1) {
return null
}
return (
<ScrollTrack>
<div style={wrapperStyles} ref="pillsTrack" {...elementAttributes}>
{renderLabel()}
<ul style={pillsContainerStyles} {...listItemAttributes}>
{pills.map(renderPill)}
</ul>
</div>
</ScrollTrack>
)
}
}
export default Radium(NavigationPills)
|
module.exports = {
TorrentFile : TorrentFile,
RemoteTorrent: RemoteTorrent
}
var pTorrent = require('../lib/parseTorrent')
var httpClient = require('../lib/httpClient')
var blobToBuffer = require('blob-to-buffer')
var EventEmitter = require('events').EventEmitter
var inherits = require('inherits')
var parallel = require('run-parallel')
var qs = require('querystring')
var path = require('path')
inherits(TorrentFile, EventEmitter)
function TorrentFile (file) {
var self = this
EventEmitter.call(self)
if (!isTorrentFile(file)) {
throw new Error('file should be torrent file')
}
var fileName = file.name
blobToBuffer(file, function (err, buff) {
if (err) {
}
torrent = pTorrent.parseTorrent(buff)
var name = document.querySelector('#name')
name.innerHTML = torrent.name
getTrackers.bind(self, torrent['infoHash'], torrent['announce'])()
})
}
inherits(RemoteTorrent, EventEmitter)
function RemoteTorrent(remoteUrl) {
var self = this
EventEmitter.call(self)
self.url = remoteUrl
pTorrent.parseRemoteTorrent(remoteUrl, function (err, torrent) {
var name = document.querySelector('#name')
name.innerHTML = torrent.name
getTrackers.bind(self, torrent['infoHash'], torrent['announce'])()
})
return self
}
function getTrackers(infoHash, announces) {
var self = this
var parallelTask = announces.map(function (announce) {
return function (cb) {
setTimeout(function () {
httpClient.get('/api/announce?' + qs.stringify({
infoHash: infoHash,
announce: announce
}), function (err, res, body){
if (err) {
return cb(err)
}
try {
var ips = JSON.parse(body)
self.emit('peers', ips)
} catch (e) {
return cb(null)
}
return cb (err)
})
}, 2000)
}
})
parallel(parallelTask, function (err, res) {
if (err) {
self.emit('error')
}
self.emit('done')
})
}
function isTorrentFile (file) {
var extname = path.extname(file.name).toLowerCase()
return extname === '.torrent'
}
|
module.exports = (sequelize, DataTypes) => {
const TagsFlavors = sequelize.define(
'TagsFlavors',
{
tagId: {
type: DataTypes.BIGINT,
allowNull: false,
primaryKey: true,
references: {
model: sequelize.Tag,
key: 'id'
}
},
flavorId: {
type: DataTypes.BIGINT,
allowNull: false,
primaryKey: true,
references: {
model: sequelize.Flavor,
key: 'id'
}
},
created: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW
},
creatorId: {
type: DataTypes.BIGINT,
allowNull: false
}
},
{
sequelize,
underscored: true,
tableName: 'tags_flavors',
createdAt: 'created',
updatedAt: false
}
);
TagsFlavors.associate = function (models) {
this.belongsTo(models.Tag, { foreignKey: 'tagId' });
this.belongsTo(models.User, { foreignKey: 'creatorId' });
this.belongsTo(models.Flavor, { foreignKey: 'flavorId' });
};
return TagsFlavors;
};
|
import axios from 'axios'
export function request(config) {
// 1.创建axios是咧
const instance = axios.create({
baseURL: 'http://123.207.32.32:8000',
timeout: 5000,
})
// 2.axios拦截器 请求
instance.interceptors.request.use(
config => {
// console.log(config);
// 2.1请求拦截的作用
// 1.比如config中的一些信息不符合服务器的要求 添加一些header
// 2.比如每次发送请求的时候,都希望在界面上显示一个请求图标
// 3.某些网络请求(比如登录(token)),必须携带一些特殊的符号
return config
}, err => {
console.log(err);
}
)
// 3. 响应
instance.interceptors.response.use(res => {
console.log(res);
return res
},
err => {
console.log(err);
})
// 3.发送真正的网络请求
return instance(config)
}
|
$(document).ready(function() {
$('a.createCommunity').click(function()
{
if(json.global.logged)
{
loadDialog("createCommunity","/community/create");
showDialog(json.community.createCommunity,false);
}
else
{
createNotive(json.community.contentCreateLogin,4000)
$("div.TopDynamicBar").show('blind');
loadAjaxDynamicBar('login','/user/login');
}
});
$('a.moreDescription').click(function(){
$(this).parents('div').find('.shortDescription').hide();
$(this).parents('div').find('.fullDescription').show();
return false;
})
$('a.lessDescription').click(function(){
$(this).parents('div').find('.shortDescription').show();
$(this).parents('div').find('.fullDescription').hide();
return false;
})
$('.communityBlock').click(function(){
$(location).attr('href',($('> .communityTitle',this).attr('href')));
})
});
|
var http = require("http");
var st = require("st");
var Router = require("routes-router");
var sendJSON = require('send-data/json');
var sendHTML = require('send-data/html');
var getTracklist = require('./lib/orm').getTracklist;
var getArtists = require('./lib/orm').getArtists;
var tracklist = [];
var artists = [];
var baseTmp = require('./templates/base');
var listTmp = require('./templates/list');
var infoTmp = require('./templates/info');
getTracklist(function(trax) {
tracklist = trax;
});
getArtists(function(artists) {
artists = artists;
});
var app = Router()
var port = 6969;
var staticHandler = st({
path: __dirname+'/public',
cache: false
});
app.addRoute("/playlist", function(req, res) {
if (tracklist.length) sendJSON(req, res, tracklist);
else {
getTracklist(function(err, tracklist) {
if (!err) sendJSON(req, res, tracklist);
})
}
})
app.addRoute("/artists", function(req, res) {
if (artists.length) sendJSON(req, res, artists);
else {
getArtists(function(err, artists) {
if (!err) sendJSON(req, res, artists);
})
}
})
app.addRoute("/", function(req, res) {
sendHTML(req, res,
baseTmp(listTmp(tracklist),
infoTmp(tracklist[0]),
{tracklist:tracklist}).outerHTML)
})
app.addRoute("*", function(req, res) {
staticHandler(req, res);
})
var server = http.createServer(app);
server.listen(port);
console.log("Server listening on port: ", port);
|
/* eslint-disable @typescript-eslint/no-var-requires */
const axios = require("axios")
const fetchTeamsFromTBA = async (eventKey, event) => {
try {
let teams = await axios
.get(`https://www.thebluealliance.com/api/v3/event/${eventKey}/teams`, {
headers: {
"X-TBA-Auth-Key":
"dN035xmkiTaxfsfyaKBMs7qlXImozqoe0Umw3WpjaPhoSz7S4Pm0hweEUjMoXGmT",
},
})
.then(res => res.data)
.then(data =>
data.map(t => ({
...t,
competition: event,
}))
)
return teams
} catch (err) {
console.error(err)
}
}
fetchTeamsFromTBA("2019casj").then(teams => teams.map(t => console.log(t.team_number + " " + t.nickname)))
exports.fetchTeamsFromTBA = fetchTeamsFromTBA
/* GET https://sheets.googleapis.com/v4/spreadsheets/[SPREADSHEETID]/values/[RANGE]?key=[YOUR_API_KEY] HTTP/1.1 */
exports.fetchDataFromSheets = async () => {
try {
const spreadsheetid = "141SgP1Cjn_40LeReGRav2M0dSUk0g6YPJDrP8Bgn-7c"
const range = "A:AC"
let data = await axios.get(
`https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetid}/values/${range}?key=AIzaSyAukpHDfLv6_IAWzjFJnyjHtcA1dDJqZiU`
)
return data.data.values
} catch (err) {
console.error(err)
}
}
|
f (typeof webkitSpeechRecognition != 'function') {
alert('크롬에서만 동작 합니다.');
return false;
}
var recognition = new webkitSpeechRecognition();
var isRecognizing = false;
var ignoreOnend = false;
var finalTranscript = '';
var audio = document.getElementById('audio');
var $btnMic = $('#btn-mic');
var $result = $('#result');
var $iconMusic = $('#icon-music');
recognition.continuous = true;
recognition.interimResults = true;
recognition.onstart = function() {
console.log('onstart', arguments);
isRecognizing = true;
$btnMic.attr('class', 'on');
};
recognition.onend = function() {
console.log('onend', arguments);
isRecognizing = false;
if (ignoreOnend) {
return false;
}
// DO end process
$btnMic.attr('class', 'off');
if (!finalTranscript) {
console.log('empty finalTranscript');
return false;
}
if (window.getSelection) {
window.getSelection().removeAllRanges();
var range = document.createRange();
range.selectNode(document.getElementById('final-span'));
window.getSelection().addRange(range);
}
};
recognition.onresult = function(event) {
console.log('onresult', event);
var interimTranscript = '';
if (typeof(event.results) == 'undefined') {
recognition.onend = null;
recognition.stop();
return;
}
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
finalTranscript += event.results[i][0].transcript;
} else {
interimTranscript += event.results[i][0].transcript;
}
}
finalTranscript = capitalize(finalTranscript);
final_span.innerHTML = linebreak(finalTranscript);
interim_span.innerHTML = linebreak(interimTranscript);
console.log('finalTranscript', finalTranscript);
console.log('interimTranscript', interimTranscript);
fireCommand(interimTranscript);
};
/**
* changeColor
*
*/
/*
.red { background: red; }
.blue { background: blue; }
.green { background: green; }
.yellow { background: yellow; }
.orange { background: orange; }
.grey { background: grey; }
.gold { background: gold; }
.white { background: white; }
.black { background: black; }
*/
function fireCommand(string) {
if (string.endsWith('레드')) {
$result.attr('class', 'red');
} else if (string.endsWith('블루')) {
$result.attr('class', 'blue');
} else if (string.endsWith('그린')) {
$result.attr('class', 'green');
} else if (string.endsWith('옐로우')) {
$result.attr('class', 'yellow');
} else if (string.endsWith('오렌지')) {
$result.attr('class', 'orange');
} else if (string.endsWith('그레이')) {
$result.attr('class', 'grey');
} else if (string.endsWith('골드')) {
$result.attr('class', 'gold');
} else if (string.endsWith('화이트')) {
$result.attr('class', 'white');
} else if (string.endsWith('블랙')) {
$result.attr('class', 'black');
} else if (string.endsWith('알람') || string.endsWith('알 람')) {
alert('알람');
} else if (string.endsWith('노래 켜') || string.endsWith('음악 켜')) {
audio.play();
$iconMusic.addClass('visible');
} else if (string.endsWith('노래 꺼') || string.endsWith('음악 꺼')) {
audio.pause();
$iconMusic.removeClass('visible');
} else if (string.endsWith('볼륨 업') || string.endsWith('볼륨업')) {
audio.volume += 0.2;
} else if (string.endsWith('볼륨 다운') || string.endsWith('볼륨다운')) {
audio.volume -= 0.2;
} else if (string.endsWith('스피치') || string.endsWith('말해줘') || string.endsWith('말 해 줘')) {
textToSpeech($('#final_span').text() || '전 음성 인식된 글자를 읽습니다.');
}
}
recognition.onerror = function(event) {
console.log('onerror', event);
if (event.error == 'no-speech') {
ignoreOnend = true;
} else if (event.error == 'audio-capture') {
ignoreOnend = true;
} else if (event.error == 'not-allowed') {
ignoreOnend = true;
}
$btnMic.attr('class', 'off');
};
var two_line = /\n\n/g;
var one_line = /\n/g;
var first_char = /\S/;
function linebreak(s) {
return s.replace(two_line, '<p></p>').replace(one_line, '<br>');
}
function capitalize(s) {
return s.replace(first_char, function(m) {
return m.toUpperCase();
});
}
function start(event) {
if (isRecognizing) {
recognition.stop();
return;
}
recognition.lang = 'ko-KR';
recognition.start();
ignoreOnend = false;
finalTranscript = '';
final_span.innerHTML = '';
interim_span.innerHTML = '';
}
/**
* textToSpeech
* 지원: 크롬, 사파리, 오페라, 엣지
*/
function textToSpeech(text) {
console.log('textToSpeech', arguments);
/*
var u = new SpeechSynthesisUtterance();
u.text = 'Hello world';
u.lang = 'en-US';
u.rate = 1.2;
u.onend = function(event) {
log('Finished in ' + event.elapsedTime + ' seconds.');
};
speechSynthesis.speak(u);
*/
// simple version
speechSynthesis.speak(new SpeechSynthesisUtterance(text));
}
/**
* requestServer
* key - AIzaSyDiMqfg8frtoZflA_2LPqfGdpjmgTMgWhg
*/
function requestServer() {
$.ajax({
method: 'post',
url: 'https://www.google.com/speech-api/v2/recognize?output=json&lang=en-us&key=AIzaSyDiMqfg8frtoZflA_2LPqfGdpjmgTMgWhg',
data: '/examples/speech-recognition/hello.wav',
contentType: 'audio/l16; rate=16000;', // 'audio/x-flac; rate=44100;',
success: function(data) {
},
error: function(xhr) {
}
});
}
/**
* init
*/
$btnMic.click(start);
$('#btn-tts').click(function() {
textToSpeech($('#final_span').text() || '전 음성 인식된 글자를 읽습니다.');
});
});
|
import React, { useEffect, useState } from "react";
import './c3p4.scss';
import bg from "../../../assets/bgC3P3.jpg";
import nuclearWaste from "../../../assets/nuclear_waste.png";
import tv from "../../../assets/tv.png";
import nature from "../../../assets/nature.png";
import Infos from "../../../components/molecules/Infos";
import gsap from "gsap";
const Chapter3Part4 = () => {
const [nuclearAnim, setNuclearAnim] = useState();
const [nuclearIsHover, setNuclearIsHover] = useState(false);
const [tvAnim, setTvAnim] = useState({});
const [tvIsHover, setTvIsHover] = useState(false);
const [bgAnim, setBgAnim] = useState();
const [bgIsHover, setBgIsHover] = useState(false);
useEffect(() => {
setNuclearAnim(gsap.to(".nuclearWaste", { y: "-60vh", filter: "grayscale(0)", paused: true }))
setTvAnim({
natureAnim: gsap.to('.nature', { filter: "grayscale(0)", y: -40, delay: 1, paused: true }),
tvAnim: gsap.to('.tvContainer', { y: -300, x: -150, scale: 1.4, paused: true })
})
setBgAnim(gsap.to(".bgC3P3", { filter: "grayscale(0)", duration: 0.4, paused: true }))
}, [])
const NuclearHover = () => {
if (nuclearIsHover) {
nuclearAnim.reverse();
} else {
nuclearAnim.play();
}
setNuclearIsHover(!nuclearIsHover);
};
const BgHover = () => {
if (bgIsHover) {
bgAnim.reverse();
} else {
bgAnim.play();
}
setBgIsHover(!bgIsHover);
};
const TvHover = () => {
if (tvIsHover) {
for (const key in tvAnim) {
tvAnim[key].reverse()
}
} else {
for (const key in tvAnim) {
tvAnim[key].play();
}
}
setTvIsHover(!tvIsHover);
};
return (<>
<div className="chapter-container">
<img src={bg} alt="" className="bg bgC3P3" />
<img src={nuclearWaste} alt="" className="nuclearWaste" />
<div className="tvContainer">
<div className="relative">
<img src={nature} alt="" className="nature" />
<img src={tv} alt="" className="tv" />
</div>
</div>
<Infos
setIsAnimated={NuclearHover}
title={"NUCLEAR WASTE"}
content="NUCLEAR WASTE NUCLEAR WASTE"
bottom="20"
left="80"
rightCard="-500"
bottomCard="-150"
/>
<Infos
setIsAnimated={TvHover}
title={"TV TV TV"}
content="TV TV TV TV TV TV"
bottom="53"
left="61"
rightCard="700"
bottomCard="200"
/>
<Infos
setIsAnimated={BgHover}
title={"NUCLEAR BOMB"}
content="NUCLEAR BOMB NUCLEAR BOMB"
bottom="60"
left="20"
rightCard="-400"
bottomCard="-150"
/>
</div>
</>
);
};
export default Chapter3Part4;
|
//保证金提取FinancialPositDeposit
import React, { Component, PureComponent } from "react";
import {
StyleSheet,
Dimensions,
View,
Text,
Button,
Image,
TouchableOpacity
} from "react-native";
import { connect } from "rn-dva";
import Header from "../../components/Header";
import CommonStyles from "../../common/Styles";
import * as requestApi from "../../config/requestApi";
import * as regular from "../../config/regular";
import ImageView from "../../components/ImageView";
import Content from "../../components/ContentItem";
import CommonButton from '../../components/CommonButton';
const { width, height } = Dimensions.get("window");
export default class FinancialPositDeposit extends PureComponent {
static navigationOptions = {
header: null
};
constructor(props) {
super(props);
this.state = {
topParams:props.navigation.state.params || {}
}
}
componentDidMount() {
}
changeState(key, value) {
this.setState({
[key]: value
});
}
componentWillUnmount() {
}
render() {
const { navigation} = this.props;
const { topParams } = this.state;
return (
<View style={styles.container}>
<Header
navigation={navigation}
goBack={true}
title="保证金提取"
/>
<View style={styles.content}>
<Content style={{paddingHorizontal:15,paddingVertical:30,alignItems:'center'}}>
<ImageView
source={require("../../images/caiwu/pay_failed.png")}
sourceWidth={66}
sourceHeight={66}
/>
<Text style={styles.text1}>您确定要提取联盟商{topParams.name}身份的保证金吗?提取后该身份将无法正常使用,您也无法获得该身份的相关收益!</Text>
<CommonButton
title='确认提取'
style={{width:width-50,marginBottom:0}}
onPress={()=>navigation.navigate('AccountConfirmDeposit',topParams)}
/>
<CommonButton
title='暂不提取'
style={{width:width-50,backgroundColor:'#fff'}}
textStyle={{color:CommonStyles.globalHeaderColor}}
onPress={()=>navigation.goBack()}
/>
</Content>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
...CommonStyles.containerWithoutPadding,
},
content: {
width: width - 20,
marginHorizontal: 10,
marginTop: 10,
},
whiteBlock: {
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
height: 192,
backgroundColor: "#fff",
},
text1: {
fontSize: 14,
color: "#222",
marginTop: 18,
lineHeight:24
},
});
|
Favoris.getOne = function(selector) {
Favoris.log.trace("Favoris.getOne selector ", selector);
return FavorisCollection.findOne(selector);
}
Favoris.getOneByUserIdAndCitationId = function(userId, citationId) {
Favoris.log.trace("Favoris.getOneByUserIdAndCitationId ", userId, citationId);
return Favoris.getOne({
user_id: userId,
citation_id: citationId
});
};
|
const {Datastore} = require('@google-cloud/datastore');
const uuidv4 = require('uuid/v4');
const config = require('./config');
const projectId = config.projectId;
const datastore = new Datastore({
projectId: projectId,
});
exports.addEvent = async function (req, res) {
const eventKey = datastore.key(['Events', uuidv4()]);
const eventId = uuidv4();
const event = {
key: eventKey,
data: {...req.body, id: eventId}
};
await datastore.save(event);
for (let i = 0; i < req.body.guests.length; i++) {
const invitationKey = datastore.key(['Invitations', uuidv4()]);
const d = new Date();
const invitation = {
key: invitationKey,
data: {
"event_id": eventId,
"sender": req.body.email,
"receiver": req.body.guests[i],
"response": "no",
"date": d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate()
}
};
await datastore.save(invitation);
}
res.json({msg: "done"})
};
exports.getEvents = async function (req, res) {
const query = datastore.createQuery('Events');
let list = await query.run();
res.json({response: list[0]})
};
exports.getEvent = async function (req, res) {
const query = datastore.createQuery('Events').filter("id", "=", req.params.id);
let event = await query.run();
res.json({response: event[0]})
};
|
"use strict";
postInit(function(){
var componentObj = new HIPI.framework.Component();
componentObj.defineHtmlElementSelector("main");
componentObj.addHtmlGenerator(function(elementIdOfComponentInstanceWrapper, componentPropertiesObj, stateSlicesObj){
var retStr = "<header>" +
"<img class='logo' src='images/HIPI-Nav-Logo.png' title='Human Intelligence Protocol Interface' alt='HIPI' />" +
"<select id='domainSelectMenu"+elementIdOfComponentInstanceWrapper+"'>";
for(var i=0; i<stateSlicesObj.domainNames.length; i++)
retStr += "<option "+ (stateSlicesObj.selectedDomain === stateSlicesObj.domainNames[i] ? "selected='selected'" : "" ) +" value='"+stateSlicesObj.domainNames[i]+"'>Domain: "+stateSlicesObj.domainNames[i]+"</option>";
retStr +=
"</select>" +
"<div class='header-links'>" +
"<userSettings></userSettings>" +
"</div>" +
"</header>" +
"<mainTabs domain='"+stateSlicesObj.selectedDomain+"'></mainTabs>";
return retStr;
});
componentObj.addStateExtractor(function(componentPropertiesObj, globalStateObj){
var stateSlices = {};
if(globalStateObj.domains){
stateSlices.domainNames = globalStateObj.domains.map(function(domainObj){
return domainObj.domainName;
});
}
else{
stateSlices.domainNames = [];
}
stateSlices.selectedDomain = globalStateObj.selectedDomain;
if(!stateSlices.selectedDomain && stateSlices.domainNames.length)
stateSlices.selectedDomain = stateSlices.domainNames[0];
return stateSlices;
});
componentObj.addReducer(function(stateObj, actionObj){
HIPI.framework.Utilities.ensureTypeObject(stateObj);
HIPI.framework.Utilities.ensureValidActionObject(actionObj);
switch(actionObj.type){
case HIPI.state.ActionNames.CHANGE_DOMAIN :
stateObj.selectedDomain = actionObj.domainName;
// This isn't necessary and it could cause a wait on a large database, but will increase runtime performance after the domain is selected.
stateObj = HIPI.lib.Dialogs.cacheDialogDepths(stateObj, stateObj.selectedDomain, "", false);
stateObj = HIPI.lib.Dialogs.cacheAnsweredStatus(stateObj, stateObj.selectedDomain, "", false);
break;
}
return stateObj;
});
componentObj.addStateCleaner(function(stateObj){
HIPI.framework.Utilities.ensureTypeObject(stateObj);
// The selected domain isn't something that should be shared with others.
// Always reset to the first domain in the collection.
if(stateObj.domains.length)
stateObj.selectedDomain = stateObj.domains[0].domainName
else
delete stateObj.selectedDomain;
return stateObj;
});
componentObj.addDomBindRoutine(function(elementIdOfComponentInstanceWrapper, componentPropertiesObj, stateSlicesObj){
var domainSelectObj = document.getElementById('domainSelectMenu'+elementIdOfComponentInstanceWrapper);
domainSelectObj.addEventListener("change", function(){
HIPI.state.ActionMethods.changeDomainName(domainSelectObj.value);
});
});
HIPI.framework.ComponentCollection.addComponent(componentObj);
});
|
import { createElement, render, renderDom } from './element'
import diff from './diff'
import patch from './patch'
let virtualDom = createElement('ul', { class: 'list' }, [
createElement('li', { class: 'item' }, ['A']),
createElement('li', { class: 'item' }, ['B']),
createElement('li', { class: 'item' }, ['C'])
])
let virtualDom2 = createElement('ul', { class: 'list-group' }, [
createElement('li', { class: 'item' }, ['A changed']),
createElement('li', { class: 'item' }, ['B']),
createElement('p', { class: 'page' }, [
createElement('a', { class: 'link', href: 'https://blog.alvin.run' }, ['C replaced'])
]),
createElement('li', { class: 'item' }, ['这个是新增的节点'])
])
let el = render(virtualDom)
renderDom(el, document.getElementById('root'))
let patches = diff(virtualDom, virtualDom2)
console.log(patches)
// 给元素打补丁,重新更新视图
patch(el, patches)
// 遗留问题
// 如果平级互换,会导致重新渲染
// 新增节点 不生效
// index
|
let arregloDeSeries=[];
function agregarSeries(){
let cargar=document.getElementById("serie").value;
arregloDeSeries.push(cargar);
console.log(arregloDeSeries);
//para guardar los datos en LCS
localStorage.setItem("nombreClaveInventadoPorMiKey",JSON.stringify(arregloDeSeries));
mostrarSeriesDeLCS();
}
function mostrarSeriesDeLCS(){
if(localStorage.length>0){
//aqui el local storage no esta vacio
let almacenamientoDeLCS=JSON.parse(localStorage.getItem("nombreClaveInventadoPorMiKey"));
let padreUl=document.getElementById("padreListaSeries");
padreUl.innerHTML="";
// for(let i=0; almacenamientoDeLCS.length; i++){}
for (const valor of almacenamientoDeLCS){
let li= document.createElement("li");
li.innerText = valor;
li.className = "list-group-item";
li.id=valor;
padreUl.appendChild(li);
}
}else{
}
}
|
alert('Число загадано!');
let tryToGuess;
function playGame() {
toHideNumber = Math.floor(Math.random() *100);
return toHideNumber;
}
playGame();
function checkNumber(tryToGuess, numberIsLow, numberIsMuch, success){
while (toHideNumber != tryToGuess) {
const tryToGuess = prompt('Попробуй угадать число!','');
if (!tryToGuess) {
break
} else if (tryToGuess < toHideNumber){
numberIsLow = alert('Мало!');
}
else if (tryToGuess > toHideNumber){
numberIsMuch = alert('Много!');
} else if (tryToGuess == toHideNumber){
const success = alert('Успех!');
const oneMoreGame = confirm('Попробуешь еще раз?');
if (!oneMoreGame) {
break
} else {
function playGame() {
toHideNumber = Math.floor(Math.random() *100);
}
playGame();
const tryToGuess = prompt('Попробуй угадать число!','');
if (!tryToGuess) {
break
} else if (tryToGuess < toHideNumber){
numberIsLow = alert('Мало!');
} else if (tryToGuess > toHideNumber){
numberIsMuch = alert('Много!');
} else if (tryToGuess == toHideNumber){
const success = alert('Успех!');
const oneMoreGame = confirm('Попробуешь еще раз?');
if (!oneMoreGame) {
break
}
}
}
}
}
return tryToGuess;
};
checkNumber(tryToGuess);
|
import * as React from 'react';
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/core/styles';
import { Rating } from '@material-ui/lab';
import { DataGrid} from '@material-ui/data-grid';
import Korea from "./son.jpg"
import England from "./england.png"
import Egypt from "./aicap.png"
import Portugal from "./portugal.png"
import Senegal from "./senegal.png"
import Belgium from "./belgium.png"
import Gabon from "./gabon.jpg"
import Germany from "./germany.png"
import France from "./france.png"
import Brazil from "./brasil.png"
import Spain from "./tbn.png"
import Tot from "../../images/club18.png"
import Arsernal from "../../images/club7.png"
import MU from "../../images/club5.png"
import MC from "../../images/club6.png"
import Chelsea from "../../images/club10.png"
import Liverpool from "../../images/club15.png"
import AstonVilla from "../../images/club19.png"
import Leisester from "../../images/club14.png"
import Everton from "../../images/club11.png"
import Leed from "../../images/club13.png"
import Newcastle from "../../images/club16.png"
const columnFields= [
{
field: "name",
headerName: "Tên cầu thủ",
flex:0.3
},
{
field: "avatar",
filterable: false,
disableColumnMenu: true,
headerName: "Quốc tịch",
sortable: false,
flex:0.2,
renderCell: (params) => (
<>
<img src={params.value} style={{width:'50px',height:'40px'}}/>
</>
)
},
{
field: 'club',
headerName: "Câu lạc bộ",
flex:0.3,
renderCell: (params) => (
<>
<span><img src={
params.value == "Tottemham Hostpur" ? Tot:
(params.value == "Leisester City" ? Leisester :
(
params.value == "Liverpool" ? Liverpool :
(
params.value == "Manchester United" ? MU:
(
params.value == "Manchester City" ? MC :
(
params.value == "Aston Villa" ? AstonVilla :
(
params.value == "Chelsea" ? Chelsea :
(
params.value == "Leeds United" ? Leed :
(
params.value == "Newcastle United" ? Newcastle :
Arsernal
)
)
)
)
)
)
))
}
style={{width:'30px',marginTop:'15px'}}/></span>
<span style={{marginLeft:5}}>{params.value}</span>
</>
)
},
{
field: "goal",
headerName: "Số bàn thắng",
flex:0.2
},
]
const dataFields = [
{id:'1',avatar: Egypt,name:'Mohamed Salah',club:'Liverpool',goal:13},
{id:'2',avatar: England,name:'Harry Kane',club:'Tottemham Hostpur',goal:12},
{id:'3',avatar: Korea, name:'Son Heugh-min',club:'Tottemham Hostpur',goal:12},
{id:'4',avatar: Portugal,name:'Bruno Fernandes',club:'Manchester United',goal:11},
{id:'5',avatar: England,name:'Dominic Calvert-Lewin',club:'Everton',goal:11},
{id:'6',avatar: England,name:'Jamie Vardy',club:'Leisester City',goal:11},
{id:'7',avatar: England,name:'Patrick Bamford',club:'Leeds United',goal:10},
{id:'8',avatar: England,name:'Callumn Wilson',club:'Newcastle United',goal:8},
{id:'9',avatar: Belgium,name:'Kevin De Bruyne',club:'Manchester City',goal:7},
{id:'10',avatar: England,name:'James Maddison',club:'Leisester City',goal:7},
{id:'11',avatar: England,name:'Erid Dier',club:'Tottemham Hostpur',goal:7},
{id:'12',avatar: Gabon,name:'Pierre-Emerick Aubameyang',club:'Arsernal',goal:7},
{id:'13',avatar: Germany,name:'Timo Werner',club:'Chelsea',goal:7},
{id:'14',avatar: France,name:'Paul Pogba',club:'Manchester United',goal:7},
{id:'15',avatar: England,name:'Trent Alexander-Arnold',club:'Liverpool',goal:6},
{id:'16',avatar: England,name:'Jesse Lingard',club:'Manchester United',goal:2},
{id:'17',avatar: England,name:'Jack Grealish',club:'Aston Villa',goal:1},
{id:'18',avatar: Germany,name:'Antonio Rüdiger',club:'Chelsea',goal:1},
{id:'19',avatar: Spain,name:'Thiago Alcantara',club:'Liverpool',goal:1},
{id:'20',avatar: Brazil,name:'Thiago Silva',club:'Chelsea',goal:1}
]
const useStyles = makeStyles({
root: {
display: 'inline-flex',
flexDirection: 'row',
alignItems: 'center',
height: 48,
paddingLeft: 20,
},
});
function RatingInputValue(props) {
const classes = useStyles();
const { item, applyValue } = props;
const handleFilterChange = (event) => {
applyValue({ ...item, value: event.target.value });
};
return (
<div className={classes.root}>
<Rating
name="custom-rating-filter-operator"
placeholder="Filter value"
value={Number(item.value)}
onChange={handleFilterChange}
precision={0.5}
/>
</div>
);
}
RatingInputValue.propTypes = {
applyValue: PropTypes.func.isRequired,
item: PropTypes.shape({
columnField: PropTypes.string,
id: PropTypes.number,
operatorValue: PropTypes.string,
value: PropTypes.string,
}).isRequired,
};
const filterModel = {
items: [{ columnField: 'club'}],
};
export default function CustomRatingFilterOperator() {
return (
<div style={{ height: '40rem', width: '100%'}}>
<DataGrid
rows={dataFields}
columns={columnFields}
filterModel={filterModel}
rowsPerPageOptions={[10,20,30]}
pageSize={10}
/>
</div>
);
}
|
const { Model } = require('sequelize');
const { OrderStatus } = require('../../common/config');
const values = require('lodash/values');
class Order extends Model {
static fields({ DATE, ENUM, TEXT }) {
return {
createdAt: {
type: DATE,
field: 'created_at'
},
updatedAt: {
type: DATE,
field: 'updated_at'
},
deletedAt: {
type: DATE,
field: 'deleted_at'
},
status: ENUM(values(OrderStatus)),
note: TEXT
};
}
static associate({ Product, ProductOrder, User }) {
this.belongsToMany(Product, {
through: ProductOrder,
foreignKey: { name: 'orderId', field: 'order_id' }
});
this.hasMany(ProductOrder, {
foreignKey: { name: 'orderId', field: 'order_id' }
});
this.belongsTo(User, {
foreignKey: { name: 'userId', field: 'user_id' }
});
}
static scopes({ ProductOrder, Product }) {
const timestamps = ['createdAt', 'updatedAt', 'deletedAt'];
return {
withAll: {
include: {
model: ProductOrder,
attributes: {
exclude: ['orderId', 'productId', ...timestamps]
},
include: {
model: Product,
attributes: {
exclude: ['quantity', ...timestamps]
}
}
},
attributes: {
exclude: ['userId']
}
}
};
}
static withAll() {
return this.scope('withAll');
}
}
module.exports = Order;
|
import React, {useState} from 'react';
const Pokemon = () => {
const [allPokemon, setAllPokemon] = useState([]);
const clickHandler = () => {
fetch("https://pokeapi.co/api/v2/pokemon?limit=1200")
.then(response => {
return response.json();
})
.then(response => {
// console.log("--------------");
// console.log(response);
setAllPokemon(response.results);
})
.catch(error => {
console.log(error);
})
// console.log(allPokemon);
};
return (
<div>
<h1>Welcome to the Pokemon API!</h1>
<button onClick={clickHandler}>Fetch Pokemon</button>
{
allPokemon.map((pokemon, index) => {
return <p key={index}>{index+1}. {pokemon.name}</p>
})
}
</div>
);
};
export default Pokemon;
|
import axios from 'axios'
export function userLogin(data) {
return axios.post(`${process.env.VUE_APP_USERS}/login`, data)
}
export function userValidate(data) {
return axios.post(`${process.env.VUE_APP_USERS}/verify`, data)
}
export function userRegister(data) {
return axios.post(`${process.env.VUE_APP_USERS}/create`, data)
}
|
(function (angular) {
"use strict";
angular.module("math", [])
.controller("MathController", function ($scope) {
$scope.add = function (a, b) {
return parseFloat(a) + parseFloat(b);
};
});
})(window.angular);
|
var express = require('express')
var app = express()
var founders = require('./founders.js')
var houses = require('./houses.js')
var members = require('./members.js')
app.get('/founders', getFounders);
app.get('/founders/:index', getFounderIndex, founderIndexShow);
app.delete('/founders/:index', getFounderIndex, founderIndexDelete);
app.get('/houses', getHouses);
app.get('/houses/:index', getHouseIndex, houseIndexShow);
app.delete('/houses/:index', getHouseIndex, houseIndexDelete);
app.get('/members', getMembers)
app.get('/members/:index', getMemberIndex, memberIndexShow);
app.delete('/members/:index', getMemberIndex, memberIndexDelete);
app.listen(3000, listenHandler)
function getFounders(req, res) {
res.json(founders);
}
function getFounderIndex(req, res, next) {
var index = req.params.index;
var founder = founders[index];
req.founder = founder;
next();
}
function founderIndexShow(req, res) {
res.json(req.founder);
}
function founderIndexDelete(req, res) {
founders.splice(req.params.index, 1);
res.json(req.founder);
}
///=====
function getHouses(req, res) {
res.json(houses);
}
function getHouseIndex(req, res, next) {
var index = req.params.index;
var house = houses[index];
req.house = house;
next();
}
function houseIndexShow(req, res) {
res.json(req.house);
}
function houseIndexDelete(req, res) {
houses.splice(req.params.index, 1);
res.json(req.house);
}
//////////////////////////////////////////
function getMembers(req, res) {
res.json(members);
}
function getMemberIndex(req, res, next) {
var index = req.params.index;
var member = members[index];
req.member = member;
next();
}
function memberIndexShow(req, res) {
res.json(req.member);
}
function memberIndexDelete(req, res) {
members.splice(req.params.index, 1);
res.json(req.member);
}
///////////////////////////
function listenHandler() {
console.log(`Listening on localhost:3000`);
}
|
'use strict';
angular
.module('rankSelector')
.component('rankSelector', {
templateUrl : 'rank-selector/rank-selector.template.html',
controller : function () {
//list of ranks
this.ranks = ['None', 'Tenderfoot', 'Second Class', 'First Class', 'Star', 'Life', 'Eagle'];
//rank is initially unknown
this.selectedRank = undefined;
//update rank when known
this.click = function (buttonRank) {
this.selectedRank = buttonRank;
};
}
});
|
import React, { useEffect, useContext } from 'react';
import Card from '../cards/Card';
import Loader from '../utils/Loader';
import ProfileContext from '../../context/profile/profileContext';
const Training = () => {
const profileContext = useContext(ProfileContext);
const { profile, getProfile, isLoading, language } = profileContext;
useEffect(() => {
getProfile();
// eslint-disable-next-line
}, [language]);
if(profile === null || profile.trainings === null || isLoading) {
return <Loader />;
}
return profile.trainings.map(training => {
const data = {
title: training.title,
description: training.school,
info: training.location,
start: training.start,
end: training.end,
isCurrent: training.isCurrent
};
return <Card key={training._id} data={data} />
});
}
export default Training;
|
const path = require(`path`)
const { pages } = require('./pages.js')
exports.createPages = async ({ actions }) => {
const { createPage } = actions
pages.forEach((page) => {
let context = {}
createPage({
path: page.path,
component: path.resolve(`src/templates${page.component}`),
context
})
})
}
|
import axios from 'axios';
let base = '';
export const requestLogin = params => {
return axios({ url: `${base}/login`, method: 'POST', data: params }).then(res => res.data);
};
export const getUserListPage = params => {
return axios({
method: 'GET',
url: `${base}/user/listpage`,
params: params
}).then(res => res.data)
};
|
import React, { Component } from "react";
import { View, Text, StyleSheet, ScrollView } from "react-native";
import { global } from "../style/global";
import { TouchableOpacity } from "react-native-gesture-handler";
import Icon from "react-native-vector-icons/FontAwesome";
class CauTraLoiText extends Component {
constructor(props) {
super(props);
this.state = { show: false };
}
renderhtml = () => {
return this.props.data.NoiDungCauTraLoi.map((item, index) => {
return (
<Text key={index}>
<Text style={{ color: "#5f5f5f" }}>{index + 1}. </Text>
{item}
</Text>
);
});
};
render() {
return (
<View style={global.inputGroup}>
<View style={styles.contentParent}>
<View style={{ borderBottomColor: "#eeeeee", borderBottomWidth: 1 }}>
<Text style={{ fontSize: 18, fontWeight: "500" }}>
{this.props.data.TenCauHoi}
</Text>
</View>
<View
style={{
minHeight: 100,
maxHeight: this.state.show ? 2000 : 205,
marginTop: 20,
overflow: "hidden",
}}
>
<View style={styles.content}>{this.renderhtml()}</View>
</View>
{this.props.data.NoiDungCauTraLoi.length > 10 && !this.state.show ? (
<TouchableOpacity
onPress={() => {
this.setState({ show: true });
}}
>
<View style={{ alignItems: "center" }}>
<Text
style={{
textAlign: "center",
color: "white",
backgroundColor: "#59b900",
borderRadius: 8,
fontSize: 14,
alignItems: "center",
width: 100,
paddingVertical: 5,
}}
>
Xem Thêm
</Text>
</View>
</TouchableOpacity>
) : (
<></>
)}
<Text
style={{
marginTop: 10,
paddingTop: 10,
borderTopWidth: 1,
borderTopColor: "#eeeeee",
}}
>
Tổng số câu trả lời : {this.props.data.SoLuong}
</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
content: {
marginTop: 10,
marginBottom: 5,
},
});
export default CauTraLoiText;
|
angular.module('petapaw').config(['$routeProvider', setRoutes]);
function setRoutes($routeProvider) {
$routeProvider
.when('/', {
template: "<h1>Hello world</h1>"
})
.when('/register', {
templateUrl: 'app/components/shelterRegistration/view.html',
controller: 'PpShelterRegistrationFormCtrl as srf',
reloadOnSearch: false,
});
}
|
module.exports = function(grunt) {
grunt.initConfig({
copy: {
main: {
files: [
{expand: true, cwd: 'app/json', src: ['**'], dest: 'build/json'},
{expand: true, cwd: 'app/views', src: ['**'], dest: 'build/views'},
{expand: true, cwd: 'app/img', src: ['**'], dest: 'build/img'},
{expand: true, cwd: 'app/css', src: ['**'], dest: 'build/css'},
{expand: true, cwd: 'app/js/plugins', src: ['**', '!*.js.map'], dest: 'build/js/plugins'},
{expand: true, cwd: 'app/js/vendor', src: ['**', '!*.js.map'], dest: 'build/js/vendor'},
{expand: true, cwd: 'app/video', src: ['**'], dest: 'build/video'},
{expand: true, cwd: 'app/audio', src: ['**'], dest: 'build/audio'},
{src: ['app/index.html'], dest: 'build/index.html'},
]
},
images: {
files:[
{expand: true, cwd: 'src/img', src: ['**', '!**/responsive/**'], dest: 'app/img'},
]
},
images_step2: {
files:[
{expand: true, cwd: 'app/img/about/responsive', src: ['**'], dest: 'app/img/about'},
{expand: true, cwd: 'app/img/home/responsive', src: ['**'], dest: 'app/img/home'},
{expand: true, cwd: 'app/img/work/responsive', src: ['**'], dest: 'app/img/work'},
{expand: true, cwd: 'app/img/contact/responsive', src: ['**'], dest: 'app/img/contact'},
{expand: true, cwd: 'app/img/work_item/responsive', src: ['**'], dest: 'app/img/work_item'},
]
},
},
responsive_images: { //1600 70 quality
dev:{
options:{
sizes: [{
width:"100%"
}, {
width: "50%"
}],
engine:"im",
quality:80,
newFilesOnly:"false"
},
files: [{
expand:true,
src: [ 'img/**/responsive/*.{gif,jpg,png}', 'img/**/responsive/**/*.{gif,jpg,png}' ] ,
cwd: 'src/',
dest: 'app/'
}]
},
},
clean: {
yourTarget : {
src : [ "app/img/**" ]
},
images:{
src: [ "app/img/**/responsive" ]
}
},
concat: {
generated: {
files: [{
dest: '.tmp/concat/js/app.js',
src: [
'app/js/*.js',
]
}]
},
scripts: {
files:[{
dest: 'build/js/scripts.js',
src: [
'app/js/vendor/respimage.min.js',
'app/js/plugins/jquery.flexslider.min.js',
'app/js/plugins/jquery.resizeimagetoparent.min.js',
'app/js/plugins/jquery.widowFix-1.3.2.min.js',
'app/js/plugins/ScrollToPlugin.min.js',
'app/js/plugins/videogular.min.js',
'app/js/plugins/angular-route.min.js',
'app/js/plugins/angular-loader.min.js',
'app/js/plugins/angular-flexslider.min.js',
'app/js/plugins/angular-sanitize.min.js',
'app/js/plugins/angular-hammer.min.js',
'app/js/plugins/angulartics.js',
'app/js/plugins/angulartics-ga.js',
'app/js/plugins/angular-socialshare.min.js',
'app/js/plugins/angular-swfobject.js',
'js/plugins/froogaloop2.min.js',
'css/fonts/font-sourcehansans-tc.min.js'
]
}]
}
},
uglify: {
generated: {
files: [{
dest: 'build/js/app.js',
src: [ '.tmp/concat/js/app.js' ]
}]
}
},
useminPrepare: {
html: 'app/index.html',
options: {
dest: 'build'
}
},
usemin:{
html: ['build/index.html']
},
cssmin: {
target: {
files: [{
expand: true,
cwd: 'build/css',
src: ['*.css', '!*.min.css'],
dest: 'build/css',
ext: '.min.css'
}]
}
},
processhtml: {
dist: {
options: {
data: {
message: 'This is development environment'
}
},
files: {
'build/index.html': 'build/index.html'
}
}
}
});
grunt.registerTask('default', ['jshint', 'qunit', 'concat', 'uglify']);
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-filerev');
grunt.loadNpmTasks('grunt-usemin');
grunt.loadNpmTasks('grunt-responsive-images');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-processhtml');
grunt.registerTask('responsive', [
'copy:images',
'responsive_images',
'copy:images_step2',
'clean:images',
]);
grunt.registerTask('responsive_all', [
'clean:images',
'copy:images',
'responsive_images',
'copy:images_step2'
]);
grunt.registerTask('build', [
'copy:main',
'useminPrepare',
'concat:generated',
'concat:scripts',
'uglify:generated',
'usemin',
'cssmin',
'processhtml'
]);
}
|
import React, { Component } from 'react'
import GifSearch from '../components/GifSearch'
import GifList from '../components/GifList'
class GifListContainer extends Component {
constructor(props) {
super(props)
this.state = {
gifs: []
}
}
render() {
return(
<div>
<GifSearch handleSearch={this.handleSearch}/>
<GifList gifs={this.state.gifs} />
</div>
)
}
handleSearch = (value) => {
fetch(`http://api.giphy.com/v1/gifs/search?q=${value}&api_key=dc6zaTOxFJmzC&rating=g`)
.then(resp => resp.json())
.then(data => this.setState({gifs: data.data.slice(0, 3)}))
}
}
export default GifListContainer
|
goog.provide('morning.parallax.effects.EffectFactory');
goog.require('morning.parallax.effects.CounterEffect');
goog.require('morning.parallax.effects.ParallaxEffect');
goog.require('morning.parallax.effects.StyleEffect');
goog.require('morning.parallax.effects.AttributeEffect');
/**
* @constructor
*/
morning.parallax.effects.EffectFactory = function()
{
};
/**
* @param {Object} config
* @return {morning.parallax.effects.Effect}
*/
morning.parallax.effects.EffectFactory.prototype.getEffect = function(config)
{
var effect = null;
switch (config['type'])
{
case 'parallax':
effect = new morning.parallax.effects.ParallaxEffect();
effect.setConfig(config);
break;
case 'attribute':
effect = new morning.parallax.effects.AttributeEffect();
effect.setConfig(config);
break;
case 'style':
effect = new morning.parallax.effects.StyleEffect();
effect.setConfig(config);
break;
case 'counter':
effect = new morning.parallax.effects.CounterEffect();
effect.setConfig(config);
break;
}
return effect;
};
|
import { Col, Row } from "antd";
import _ from "lodash";
import Head from "next/head";
import { useRouter } from "next/router";
import * as React from "react";
import { useSelector } from "react-redux";
import slugify from "slugify";
import { FEATURE_IDS } from "../common/defines";
import useProductData from "../common/useProductData";
import LayoutOne from "../components/layouts/LayoutOne";
import Container from "../components/other/Container";
import Banners from "../components/shop/Banners";
import ShopLayout from "../components/shop/ShopLayout";
import productData from "../data/product.json";
export default function Home() {
const router = useRouter();
const handleIdentifyUser = () => {
window.AicactusSDK.identify("4b247b8e-c1b0-44f2-8729-cc3236de89bc", {
name: "Grace Hopper",
email: "grace@usnavy.gov",
});
};
const handleSyncCookie = () => {
window.AicactusSDK.cookieSync({
vendorCode: "google",
vendorUserId: "2B559491-2D37-4338-8F71-7FEAA691A401",
});
};
return (
<LayoutOne title="Home">
<Head>
<script type="text/javascript" src="/libs/ads.js"></script>
</Head>
<div className="shop-layout">
<Container type={"fluid"}>
<Row gutter={30}>
<Col className="gutter-row" xs={24} lg={4}>
<div className="shop-sidebar">123131</div>
</Col>
<Col className="gutter-row" xs={24} lg={4}>
<button onClick={handleIdentifyUser}>Identify User</button>
</Col>
<Col className="gutter-row" xs={24} lg={4}>
<button onClick={handleSyncCookie}>Sync Cookie</button>
</Col>
<Col className="gutter-row" xs={24} lg={4}>
{/* <div id="display_ads_2"></div> */}
</Col>
</Row>
</Container>
</div>
</LayoutOne>
);
}
|
import React, { Component } from 'react';
import _ from 'lodash';
import { connect } from 'react-redux';
import Slider from 'riskofbias/robVisual/components/ScoreSlider';
import { fetchRobScores, setScoreThreshold } from 'riskofbias/robVisual/actions/Filter';
class ScoreSlider extends Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
componentWillMount() {
this.props.dispatch(fetchRobScores());
this.setState({ threshold: 0 });
}
handleChange(e) {
let threshold = parseInt(e.target.value);
this.setState({ threshold });
this.props.dispatch(setScoreThreshold(threshold));
}
render() {
let threshold = this.state.threshold,
max = _.maxBy(this.props.scores, (item) => {
return item.final_score;
}).final_score;
return _.isEmpty(this.props.effects) ? null : (
<Slider max={max} threshold={threshold} handleChange={this.handleChange} />
);
}
}
function mapStateToProps(state) {
return {
effects: state.filter.selectedEffects,
scores: state.filter.robScores,
};
}
export default connect(mapStateToProps)(ScoreSlider);
|
const http = require('http')
const fs = require('fs')
const host = '127.0.0.1'
function serve(id, port, status){
console.log('index'+ id+ ".html");
fs.readFile('./index' + id + ".html", function(err, html){
if(err){
throw err;
}
http.createServer(function(req, res){
res.writeHead(status, {'Content-Type': 'text/html'});
res.write(html);
res.write('<center><h1> Listening on port ' + port + '</h1></center>');
res.end();
}).listen(port);
});
}
serve(1, 8081, 200);
serve(2, 8082, 200);
serve(3, 8083, 200);
//serve(4, 8084);
|
angular.module('ngApp.ecommerceSetting').factory('ecommerceSettingService', function ($http, config, SessionService) {
var GetCountryList = function () {
return $http.get(config.SERVICE_URL + '/eCommerceSetting/CountryList');
};
var AddEditHSCode = function (obj) {
return $http.post(config.SERVICE_URL + '/eCommerceSetting/AddEditHSCodeSetting', obj);
};
var GetHSCodeDetailList = function (countryId) {
return $http.get(config.SERVICE_URL + '/eCommerceSetting/GeteCommerceHSCodeDetail',
{
params: {
countryId: countryId
}
});
};
var DeleteHSCodeSetting = function (HSCodeId) {
return $http.get(config.SERVICE_URL + '/eCommerceSetting/DeleteHSCodeSetting',
{
params: {
HSCodeId: HSCodeId
}
});
};
return {
GetCountryList: GetCountryList,
GetHSCodeDetailList: GetHSCodeDetailList,
AddEditHSCode: AddEditHSCode,
DeleteHSCodeSetting: DeleteHSCodeSetting
};
});
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const UserToken_1 = require("./UserToken");
const UserProfile_1 = require("../../model/user/UserProfile");
const UserPermission_1 = require("../../model/user/UserPermission");
const DataHelper_1 = require("../../../helpers/DataHelper");
class UserAuthentication {
constructor(model) {
if (!model)
return;
this._id = DataHelper_1.default.handleIdDataModel(model._id);
this.profile = new UserProfile_1.default(model);
this.permission = model.permission && new UserPermission_1.default(model.permission);
this.token = model.token && new UserToken_1.default(model.token);
}
}
Object.seal(UserAuthentication);
exports.default = UserAuthentication;
|
$(function () {
$(':checkbox').on('click', function (event) {
$(this).parents('tr').toggleClass("error");
}
);
$("table").on('dblclick', ".field", function () {
var id = $(".number", this);
var var2 = $(this).text();
$(this).html('<input name="change_cookie" class="input-cookie" autofocus="autofocus" value="' + var2 + '" /><td><input class="edit" type="submit" value="change"/></td><td><input class="delete" type="submit" value="delete"/></td>');
$('.edit', this).click(function () {
var var3 = $("input[name='change_cookie']").val();
$(this).parent().html(var3);
console.log(var2);
console.log(var3);
$.post("ControllerCookie", {prediction: var2, predictionUpdate: var3, method: 'update'}, function () {
console.log('update success');
});
});
$(".delete", this).click(function () {
var var3 = $("input[name='change_cookie']").val();
$(this).closest('tr').remove();
console.log(var2);
$.post("ControllerCookie", {var3key: var3, method: 'delete'}, function () {
console.log('delete success');
});
});
});
$(".add").click(function () {
var var1 = $("input[name='insert_cookie']").val();
var obj = document.getElementById("table_prediction");
if (var1 != 0) {
$(obj).append('<tr><td style="width: 14px;" class="editor">' + var1 + '</td></tr>');
submit(var1);
}
return false;
});
});
|
const fs = require('fs')
const path = require('path')
const { execSync } = require('child_process')
const archiver = require('archiver')
const puppeteer = require('puppeteer')
const version = 'v' + require('./package.json').version;
(async () => {
const builds = [
{
platform: 'linux',
version: 756035,
chromeFolder: 'chrome-linux',
fsExec: 'flaresolverr-linux',
fsZipExec: 'flaresolverr',
fsZipName: 'linux-x64',
fsLicenseName: 'LICENSE'
},
{
platform: 'win64',
version: 756035,
chromeFolder: 'chrome-win',
fsExec: 'flaresolverr-win.exe',
fsZipExec: 'flaresolverr.exe',
fsZipName: 'windows-x64',
fsLicenseName: 'LICENSE.txt'
}
// TODO: this is working but changes are required in session.ts to find chrome path
// {
// platform: 'mac',
// version: 756035,
// chromeFolder: 'chrome-mac',
// fsExec: 'flaresolverr-macos',
// fsZipExec: 'flaresolverr',
// fsZipName: 'macos',
// fsLicenseName: 'LICENSE'
// }
]
// generate executables
console.log('Generating executables...')
if (fs.existsSync('bin')) {
fs.rmdirSync('bin', { recursive: true })
}
execSync('pkg -t node14-win-x64,node14-linux-x64 --out-path bin .')
// execSync('pkg -t node14-win-x64,node14-mac-x64,node14-linux-x64 --out-path bin .')
// download Chrome and zip together
for (const os of builds) {
console.log('Building ' + os.fsZipName + ' artifact')
// download chrome
console.log('Downloading Chrome...')
const f = puppeteer.createBrowserFetcher({
platform: os.platform,
path: path.join(__dirname, 'bin', 'puppeteer')
})
await f.download(os.version)
// compress in zip
console.log('Compressing zip file...')
const zipName = 'bin/flaresolverr-' + version + '-' + os.fsZipName + '.zip'
const output = fs.createWriteStream(zipName)
const archive = archiver('zip')
output.on('close', function () {
console.log('File ' + zipName + ' created. Size: ' + archive.pointer() + ' bytes')
})
archive.on('error', function (err) {
throw err
})
archive.pipe(output)
archive.file('LICENSE', { name: 'flaresolverr/' + os.fsLicenseName })
archive.file('bin/' + os.fsExec, { name: 'flaresolverr/' + os.fsZipExec })
archive.directory('bin/puppeteer/' + os.platform + '-' + os.version + '/' + os.chromeFolder, 'flaresolverr/chrome')
await archive.finalize()
}
})()
|
var searchData=
[
['back_5fbutton_5fx',['BACK_BUTTON_X',['../proj_macros_8h.html#a0dd9463547b28463178780654d195439',1,'projMacros.h']]],
['back_5fbutton_5fy',['BACK_BUTTON_Y',['../proj_macros_8h.html#ae944d763493bac5f53bd7cd3a3d8fbc4',1,'projMacros.h']]],
['bios_5fvmode_5ftext_5f25x80_5f16c',['BIOS_VMODE_TEXT_25x80_16C',['../v__macros_8h.html#a75ddd290c6892f896dec9208123985d2',1,'v_macros.h']]],
['bit',['BIT',['../i8042_8h.html#a3a8ea58898cb58fc96013383d39f482c',1,'i8042.h']]],
['blue_5fammo_5fmake',['BLUE_AMMO_MAKE',['../proj_macros_8h.html#a6611b0e3c36b2b916da249a7080d6fa2',1,'projMacros.h']]],
['bullet_5fanimation_5frate',['BULLET_ANIMATION_RATE',['../proj_macros_8h.html#af68d3a7ad3b6da5e376130aacbf82f6c',1,'projMacros.h']]],
['bullet_5finit_5fx_5fpos',['BULLET_INIT_X_POS',['../proj_macros_8h.html#a749585868dbe781c481201bd89ea9997',1,'projMacros.h']]],
['bullet_5finit_5fy_5fpos',['BULLET_INIT_Y_POS',['../proj_macros_8h.html#a57f85c0c3ab633cbd15a0030376d234f',1,'projMacros.h']]],
['bullet_5frefresh_5ftime',['BULLET_REFRESH_TIME',['../proj_macros_8h.html#a14b417c4156ef4e3b7b71bf111702ee2',1,'projMacros.h']]]
];
|
import React, { Component } from 'react';
import { PropTypes } from 'prop-types';
export class Pencil extends Component {
constructor(props) {
super(props);
this.state = {
outline: '',
};
}
render() {
const { selectDraw } = this.props;
const { outline } = this.state;
return (
<div>
<input type="image" alt="pencil" onClick={() => { selectDraw('pencil'); }} style={{ outline }} />
</div>
);
}
}
Pencil.propTypes = {
selectDraw: PropTypes.func.isRequired,
};
export default Pencil;
|
/**
* @param {string} s
* @return {number}
*/
var numDecodings = function(s) {
if (s === null || s.length === 0) {
return 0;
}
let builder = "";
let result = resolve(s, builder);
return result;
};
function numToChar(str) {
let minCharCode = "a".charCodeAt(0) - 96;
let maxCharCode = "z".charCodeAt(0) - 96;
let strInt = parseInt(str);
if (strInt.toString().length != str.length) {
return false;
}
if (strInt < minCharCode || strInt > maxCharCode) {
return false;
}
return true;
}
// 12
function resolve(rem, builder) {
if (rem.length == 0) {
if (numToChar(builder)) {
return 1;
}
return 0;
}
let total = 0;
for (let i = 0; i < rem.length; i++) {
let builder2 = builder + rem[i];
let rem2 = rem.slice(i + 1);
total += resolve(rem2, builder2);
}
return total;
}
function test1() {
let result = numDecodings("12");
console.log(result);
}
function test2() {
let result = numDecodings("226");
console.log(result);
}
function test3() {
let result = numDecodings("01");
console.log(result);
}
function test4() {
let result = numDecodings("10");
console.log(result);
}
// test1(); // 2
// test2(); // 3
test3(); // 0
test4(); // 10
|
require('colors');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const helmet = require('helmet');
const logger = require('./common/logger');
const othorLogger = logger.getLogger('oth');
const config = require('./config/baseConfig');
const path = require('path');
const static = path.join(__dirname,'public');
const compress = require('compression');
const csurf = require('csurf');
// const session = require('express-session');
const middleware = require('./middlewares');
const cors = require('cors');
const router = require('./routers');
require('./models');
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '/views'));
app.use('/public', express.static(static))
app.use(helmet.frameguard('sameorigin')); //防止点击劫持,使用iframe的时候必须同源才允许访问
app.use(bodyParser.json({limit: '1mb'}));
app.use(bodyParser.urlencoded({ extended: true, limit: '1mb' }));
app.use(middleware.requestLog);
app.use(middleware.errorPage);
app.use('/cors',cors(config.corsOptions),require('./test/corsrouter'));
app.use(compress()); //压缩资源
// app.set(session({ //使用了登陆方式
// secret: config.session_secret,
// resave:false,
// saveUninitialized:false,
// name:'session_id',
// cookie:{
// maxAge: 5000
// }
// }))
//如果不是开发状态下,防止cusrf攻击,设置模板缓存
if( !config.debug ){
app.use((req, res, next) => {
// if(req.path.indexOf('/api') === -1) {
// csurf()(req,res,next);
// return;
// }
next();
})
app.set('view cache', true);
}
// app.use(csurf({cookie:false}));
// app.use(middleware.checkCsrfToken(app));
app.use('/api',router);
app.use('/',require('./test/test'));
app.listen(config.port,() => {
othorLogger.info(`project listen port${config.port}`);
})
module.exports = app;
|
/*
Clock shows 'h' hours, 'm' minutes and 's' seconds after midnight.
Your task is to make 'Past' function which returns time converted to miliseconds.
#####Example:
past(0, 1, 1) == 61000
Note! h, m and s will be only Natural numbers! Waiting for translations and Feedback! Thanks!
*/
function past(h, m, s) {
let hoursToSecs = h * 60 * 60;
let minutesToSecs = m * 60;
let totalSeconds = hoursToSecs + minutesToSecs + s;
return totalSeconds * 1000;
}
|
if (location.search !== "?foo") {
location.search = "?foo";
throw new Error;
}
onload = function () {
document.getElementById("so_search").focus();
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("so_search").addEventListener('keypress', enter_click);
document.getElementById("search_button").addEventListener("click", check_query);
});
function enter_click(e) {
var key = e.which || e.keyCode;
if (key == 13 && query != '') {
// code will continue to run to check_query() function
} else {
return;
}
}
function check_query(e) {
query = document.getElementById("so_search").value;
search_stackoverflow(query);
}
function search_stackoverflow(query) {
chrome.tabs.create({ 'url': "http://stackoverflow.com/search?q=" + encodeURIComponent(query) });
}
|
exports.up = function(knex, Promise) {
return knex.schema.table('clients', function(table) {
table.json('config');
});
};
exports.down = function(knex, Promise) {
return knex.schema.table('clients', function(table) {
table.dropColumn('config')
});
};
|
//on ready
// Initialize Firebase
var config = {
apiKey: "AIzaSyD6jlfyD-3S4AziudfEKY_fD70zSJdjcco",
authDomain: "train-schedule-988d2.firebaseapp.com",
databaseURL: "https://train-schedule-988d2.firebaseio.com",
projectId: "train-schedule-988d2",
storageBucket: "train-schedule-988d2.appspot.com",
messagingSenderId: "55370344969"
};
firebase.initializeApp(config);
var database = firebase.database();
$("#add-train-btn").on("click", function (event) {
event.preventDefault();
//train info
var trainName = $("#train-name-input").val();
var destination = $("#destination-input").val();
var firstTrain = moment($("#first-train-input").val().trim(), "HH:mm").format("HH:mm");
var frequency = $("#frequency-input").val();
console.log(frequency);
// First Time (pushed back 1 year to make sure it comes before current time)
var firstTimeConverted = moment(firstTrain, "HH:mm").subtract(1, "years");
console.log(firstTimeConverted);
// Current Time
var currentTime = moment();
console.log("CURRENT TIME: " + moment(currentTime).format("HH:mm"));
// Difference between the times
var diffTime = moment().diff(moment(firstTimeConverted), "minutes");
console.log("DIFFERENCE IN TIME: " + diffTime);
// Time apart (remainder)
var tRemainder = diffTime % frequency;
console.log(tRemainder);
// Minute Until Train
var tMinutesTillTrain = frequency - tRemainder;
console.log("MINUTES TILL TRAIN: " + tMinutesTillTrain);
// Next Train
var nextTrain = moment().add(tMinutesTillTrain, "minutes").format("HH:mm");
console.log("ARRIVAL TIME: " + nextTrain)
//temp train info
var newTrain = {
title: trainName ,
destination: destination,
freq: frequency,
next: nextTrain,
timeLeft: tMinutesTillTrain,
};
database.ref().push(newTrain);
console.log(newTrain.title);
console.log(newTrain.destination);
console.log(newTrain.freq);
console.log(newTrain.next);
console.log(newTrain.timeLeft)
$("#train-name-input").val("");
$("#destination-input").val("");
$("#first-train-input").val("");
$("#frequency-input").val("");
database.ref().on("child_added", function(childSnap){
console.log(childSnap.val());
var trainName = childSnap.val().title;
var destination = childSnap.val().destination;
var nextTrain = childSnap.val().next;
var frequency = childSnap.val().freq;
var tMinutesTillTrain = childSnap.val().timeLeft
var newRow = $("<tr>").append(
$("<td>").text(trainName),
$("<td>").text(destination),
$("<td>").text(frequency),
$("<td>").text(nextTrain),
$("<td>").text(tMinutesTillTrain),
);
$("#train-table > tbody").append(newRow)
});
});
|
export const SET_TOKEN = "SET_TOKEN";
export const DELETE_TOKEN = "DELETE_TOKEN";
export const AUTH_ERROR = "AUTH_ERROR";
|
import React, { PureComponent } from 'react';
import { Image, Modal, Slider, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import PropTypes from 'prop-types';
import Icon from 'react-native-vector-icons/FontAwesome';
import * as colors from 'kitsu/constants/colors';
import { styles } from './styles';
const TextSize = {
Tiny: 10,
Small: 12,
Normal: 18,
};
const ImageSize = {
Tiny: 10,
Small: 20,
Normal: 30,
};
function displayRatingFromTwenty(ratingTwenty, type) {
if (type === 'regular') {
return Math.round(ratingTwenty / 2) / 2;
} else if (type === 'advanced') {
return ratingTwenty / 2;
} else if (type === 'simple') {
return ratingTwenty;
}
throw new Error(`Unknown rating type ${type}.`);
}
function getRatingTwentyProperties(ratingTwenty, type) {
const ratingProperties = {};
const rating = displayRatingFromTwenty(ratingTwenty, type);
switch (type) {
case 'advanced':
ratingProperties.text = rating >= 10 ? rating : rating.toFixed(1);
ratingProperties.textStyle = styles.textStar;
break;
case 'regular':
ratingProperties.text = rating >= 5 ? rating : rating.toFixed(1);
ratingProperties.textStyle = styles.textStar;
break;
case 'simple':
default:
if (rating < 6) {
ratingProperties.text = 'AWFUL';
ratingProperties.textStyle = styles.textAwful;
} else if (rating < 10) {
ratingProperties.text = 'MEH';
ratingProperties.textStyle = styles.textMeh;
} else if (rating < 16) {
ratingProperties.text = 'GOOD';
ratingProperties.textStyle = styles.textGood;
} else {
ratingProperties.text = 'GREAT';
ratingProperties.textStyle = styles.textGreat;
}
break;
}
return ratingProperties;
}
function getRatingTwentyForText(text, type) {
if (type !== 'simple') {
throw new Error('This function should only be used in simple ratings.');
}
switch (text) {
case 'awful':
return 2;
case 'meh':
return 8;
case 'good':
return 14;
case 'great':
return 20;
default:
throw new Error(`Unknown text while determining simple rating type: "${text}"`);
}
}
export class Rating extends PureComponent {
static propTypes = {
disabled: PropTypes.bool,
onRatingChanged: PropTypes.func,
rating: PropTypes.number,
ratingSystem: PropTypes.oneOf(['simple', 'regular', 'advanced']),
showNotRated: PropTypes.bool,
size: PropTypes.string,
style: PropTypes.any,
viewType: PropTypes.oneOf(['single', 'select']),
}
static defaultProps = {
disabled: false,
onRatingChanged: () => { },
rating: null,
ratingSystem: 'simple',
showNotRated: true,
size: 'normal',
style: null,
viewType: 'select',
}
state = {
inlineFacesVisible: false,
modalVisible: false,
ratingTwenty: this.props.rating,
}
onModalClosed = () => {
this.cancel();
}
setSimpleRating = (ratingTwenty) => {
this.setState({ ratingTwenty });
}
toggleModal = (selectedButton) => {
const { ratingSystem } = this.props;
// If there's a specific simple system rating we can action, just do that, otherwise
// go down to the two modals.
if (selectedButton) {
const ratingTwenty = getRatingTwentyForText(selectedButton, ratingSystem);
this.setState({
modalVisible: false,
ratingTwenty,
});
this.props.onRatingChanged(ratingTwenty);
} else {
// All other modes get the modal, which should render itself correctly
// based on our ratingSystem prop.
this.setState({ modalVisible: !this.state.modalVisible });
}
}
confirm = () => {
this.toggleModal();
this.props.onRatingChanged(this.state.ratingTwenty);
}
cancel = () => {
this.toggleModal();
// Reset the rating.
this.setState({ ratingTwenty: this.props.rating });
}
sliderValueChanged = (ratingTwenty, ratingSystem) => {
// We use the 0 or 1 rating to indicate 'no rating',
// but we don't want to deal with that in our actual state.
if ((ratingSystem !== 'advanced' && ratingTwenty >= 1) ||
(ratingSystem === 'advanced' && ratingTwenty >= 1.5)) {
this.setState({ ratingTwenty });
} else {
this.setState({ ratingTwenty: null });
}
}
styleForRatingTwenty(ratingTwenty, image) {
const { ratingSystem, showNotRated, size, viewType } = this.props;
let defaultStyle = [styles.default];
let selectedStyle = [styles.selected];
switch (size) {
case 'tiny':
defaultStyle.push({ width: ImageSize.Tiny, height: ImageSize.Tiny });
selectedStyle.push({ width: ImageSize.Tiny, height: ImageSize.Tiny });
break;
case 'small':
defaultStyle.push({ width: ImageSize.Small, height: ImageSize.Small });
selectedStyle.push({ width: ImageSize.Small, height: ImageSize.Small });
break;
case 'normal':
default:
defaultStyle.push({ width: ImageSize.Normal, height: ImageSize.Normal });
selectedStyle.push({ width: ImageSize.Normal, height: ImageSize.Normal });
break;
}
if (viewType === 'single' || ratingSystem !== 'simple') {
defaultStyle.push({ display: 'none' });
}
selectedStyle = StyleSheet.flatten(selectedStyle);
defaultStyle = StyleSheet.flatten(defaultStyle);
if (ratingTwenty === null) {
if (ratingSystem !== 'simple') {
return image === 'no-rating-star' && showNotRated ? selectedStyle : defaultStyle;
}
return image === 'no-rating' && showNotRated ? selectedStyle : defaultStyle;
} else if (image === 'no-rating' || image === 'no-rating-star') {
return { display: 'none' };
}
if (ratingSystem === 'regular' || ratingSystem === 'advanced') {
return image === 'star' ? selectedStyle : defaultStyle;
} else if (image === 'star') {
return { display: 'none' };
}
if (ratingTwenty < 3) {
return image === 'awful' ? selectedStyle : defaultStyle;
} else if (ratingTwenty < 9) {
return image === 'meh' ? selectedStyle : defaultStyle;
} else if (ratingTwenty < 15) {
return image === 'good' ? selectedStyle : defaultStyle;
}
return image === 'great' ? selectedStyle : defaultStyle;
}
textForRatingTwenty(ratingTwenty) {
const { ratingSystem, size, viewType } = this.props;
if (viewType !== 'single') {
return null;
}
let fontSize;
switch (size) {
case 'tiny': fontSize = TextSize.Tiny; break;
case 'small': fontSize = TextSize.Small; break;
case 'normal': default: fontSize = TextSize.Normal; break;
}
if (ratingTwenty === null) {
return this.props.showNotRated
? <Text style={[styles.textNotRated, { fontSize }]}>Not Rated</Text>
: null;
}
const { text, textStyle } = getRatingTwentyProperties(ratingTwenty, ratingSystem);
return <Text style={[textStyle, { fontSize }]}>{text}</Text>;
}
render() {
const { ratingSystem } = this.props;
const { ratingTwenty } = this.state;
return (
<View {...this.props} style={[styles.wrapper, this.props.style]}>
<TouchableOpacity
onPress={() => this.toggleModal()}
disabled={this.props.disabled}
>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Image source={require('kitsu/assets/img/ratings/no-rating.png')} style={this.styleForRatingTwenty(ratingTwenty, 'no-rating')} />
<Image source={require('kitsu/assets/img/ratings/no-rating-star.png')} style={this.styleForRatingTwenty(ratingTwenty, 'no-rating-star')} />
<TouchableOpacity
onPress={() => this.toggleModal('awful')}
disabled={this.props.disabled}
>
<Image source={require('kitsu/assets/img/ratings/awful.png')} style={this.styleForRatingTwenty(ratingTwenty, 'awful')} />
</TouchableOpacity>
<TouchableOpacity
onPress={() => this.toggleModal('meh')}
disabled={this.props.disabled}
>
<Image source={require('kitsu/assets/img/ratings/meh.png')} style={this.styleForRatingTwenty(ratingTwenty, 'meh')} />
</TouchableOpacity>
<TouchableOpacity
onPress={() => this.toggleModal('good')}
disabled={this.props.disabled}
>
<Image source={require('kitsu/assets/img/ratings/good.png')} style={this.styleForRatingTwenty(ratingTwenty, 'good')} />
</TouchableOpacity>
<TouchableOpacity
onPress={() => this.toggleModal('great')}
disabled={this.props.disabled}
>
<Image source={require('kitsu/assets/img/ratings/great.png')} style={this.styleForRatingTwenty(ratingTwenty, 'great')} />
</TouchableOpacity>
<Image source={require('kitsu/assets/img/ratings/star.png')} style={this.styleForRatingTwenty(ratingTwenty, 'star')} />
{this.textForRatingTwenty(ratingTwenty)}
</View>
</TouchableOpacity>
<Modal
animationType="slide"
visible={this.state.modalVisible}
onRequestClose={this.onModalClosed}
transparent
>
<View style={ratingSystem === 'simple' ? styles.modalContentSimple : styles.modalContent}>
<View style={styles.modalHeader}>
{/* Cancel, Slide / Tap to Rate, Done */}
<TouchableOpacity onPress={this.cancel}>
<Text style={[styles.modalHeaderText, styles.modalCancelButton]}>Cancel</Text>
</TouchableOpacity>
<Text style={styles.modalHeaderText}>
{ratingSystem === 'simple' ? 'Tap' : 'Slide'} to Rate</Text>
<TouchableOpacity onPress={this.confirm}>
<Text style={[styles.modalHeaderText, styles.modalDoneButton]}>Done</Text>
</TouchableOpacity>
</View>
{ratingSystem === 'simple' &&
<View style={styles.modalBodySimple} >
<Rating
rating={this.state.ratingTwenty}
onRatingChanged={this.setSimpleRating}
/>
</View>
}
{ratingSystem !== 'simple' &&
<View style={styles.modalBody}>
{ /* Star, 4.5 */
ratingTwenty ?
<View style={styles.modalStarRow}>
<Icon name="star" size={65} color={colors.yellow} />
<Text style={styles.modalRatingText}>
{getRatingTwentyProperties(ratingTwenty, ratingSystem).text}
</Text>
</View>
:
<View style={styles.modalStarRow}>
<Text style={styles.modalNoRatingText}>
No Rating
</Text>
</View>
}
{/* Slider */}
<Slider
minimumValue={ratingSystem === 'regular' ? 0 : 1}
maximumValue={20}
step={ratingSystem === 'regular' ? 2 : 1}
value={ratingTwenty}
minimumTrackTintColor={colors.tabRed}
maximumTrackTintColor={'rgb(43, 33, 32)'}
onValueChange={this.sliderValueChanged}
style={styles.modalSlider}
/>
</View>
}
</View>
</Modal>
</View>
);
}
}
|
Ext.onReady(function () {
if (Ext.form.Panel) {
CHANNEL_NAME = "賣場名稱";
IMPORT_TYPE = "匯入格式";
IMPORT_FILE = "選擇欲匯入之訂單(excel)";
CHOOSE_IMPORT_FILE = "選擇匯入檔案";
STORE_DISPATCH_FILE = "上傳超商提貨單檔";
CHOOSE_STORE_DISPATCH_FILE = "選擇提貨單檔";
IMPORT_SUCCESS_INFO = "共選擇 {0} 筆訂單,成功匯入 {1} 筆訂單";
WAIT_TITLE = "請稍等";
FILE_UPLOADING = "文件上傳中...";
TEMPLATE_DOWNLOAD = "範本下載";
}
if (Ext.grid.Panel) {
SERIAL_NUM = "訂單編號";
PRODUCT_ID = "商品編號";
PRODUCT_NAME = "商品名稱";
SUM_PRICE = "金額小計";
BUY_COUNT = "數量";
DELIVERY = "物流";
ORDER_NAME = "訂購人";
TRANS_DATE = "轉單日";
ERROR_INFO = "錯誤信息";
FILE_REFRESH = "上傳新文件";
}
});
FILE_TYPE_WRONG = "上傳文件格式錯誤";
IMPORT_TYPE_HOME = "一般";
IMPORT_TYPE_STORE = "有提貨單";
ORDER_SERIAL_ID = "訂單流水號:";
// add by zhuoqin0830w 2015/07/09
SITE = "站臺";
// add by mingwei0727w 2015/07/24
INFORMATION = "提示信息";
PLEASE_DOWN_MODEL_ESSAY_COMPARE="請下載範本與上傳Excel比較后再上傳~";
|
// API url and variables
let req, json, date;
let dataset = [];
const url = 'https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json';
// get JSON data
req = new XMLHttpRequest();
req.open('GET', url, true);
req.send();
req.onload = function() {
json = JSON.parse(req.responseText);
// loop through json data
json.data.forEach(function(item) {
// get just the year from the date string
const date = Date.parse(item[0]);
dataset.push([date, item[1], item[0]]);
});
// set chart dimensions
const w = 960;
const h = 500;
const padding = 20;
// set x and y scales
const xScale = d3.scaleLinear()
.domain([d3.min(dataset, (d) => d[0]), d3.max(dataset, (d) => d[0])])
.range([padding, w - padding]);
const yScale = d3.scaleLinear()
.domain([0, d3.max(dataset, (d) => d[1])])
.range([h - padding, padding]);
// create tooltip
const tip = d3.tip()
.attr('class', 'd3-tip')
.attr('id', 'tooltip')
.html((d) => {
d3.select('#tooltip').attr('data-date', d[2]);
const formatTime = d3.timeFormat("%B %Y");
const formatNum = d3.format("~s")(d[1] * 1000000000);
return `${formatTime(new Date(d[2]))}<br>$${formatNum}`;
});
// create svg area in container
const svg = d3.select('#container')
.append('svg')
.attr('width', w)
.attr('height', h)
.call(tip);
// create bar elements and text for tooltips
svg.selectAll('rect')
.data(dataset)
.enter()
.append('rect')
.attr('width', 3.5)
.attr('height', (d) => (h - padding) - yScale(d[1]))
.attr('x', (d) => xScale(d[0]))
.attr('y', (d) => yScale(d[1]))
.attr('class', 'bar')
.attr('data-date', (d) => d[2])
.attr('data-gdp', (d) => d[1])
.style('fill', '#39ff14')
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
// set axes and append to DOM
const xAxis = d3.axisBottom(xScale)
.tickFormat(d3.timeFormat('%Y'));
const yAxis = d3.axisRight(yScale);
svg.append('g')
.attr('transform', `translate(0, ${h - padding})`)
.attr('id', 'x-axis')
.call(xAxis)
svg.append('g')
.attr('transform', 'translate(0, 0)')
.attr('id', 'y-axis')
.call(yAxis);
// set text for axes and append to DOM
svg.append('text')
.attr('transform', `translate(440, ${h - padding - 10})`)
.attr('class', 'axis-text')
.text('Year (Quarterly)')
.style('pointer-events', 'none');
svg.append('text')
.attr('transform', 'translate(70, 290)rotate(270)')
.attr('class', 'axis-text')
.text('GDP (in billions)');
};
|
// LauncherOSX
//
// Created by Boris Schneiderman.
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// 3. Neither the name of the organization nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
define(['jquery','eventEmitter'], function($, EventEmitter) {
var DEBUG = false;
/**
* Top level ReadiumSDK namespace
* @namespace
*/
var Globals = {
/**
* Current version of the JS SDK
* @static
* @return {string} version
*/
version: function () {
return "0.8.0";
},
/**
* @namespace
*/
Views: {
/**
* Landscape Orientation
*/
ORIENTATION_LANDSCAPE: "orientation_landscape",
/**
* Portrait Orientation
*/
ORIENTATION_PORTRAIT: "orientation_portrait"
},
/**
* @namespace
*/
Events: {
/**
* @event
*/
READER_INITIALIZED: "ReaderInitialized",
/**
* This gets triggered on every page turnover. It includes spine information and such.
* @event
*/
PAGINATION_CHANGED: "PaginationChanged",
/**
* @event
*/
SETTINGS_APPLIED: "SettingsApplied",
/**
* @event
*/
FXL_VIEW_RESIZED: "FXLViewResized",
/**
* @event
*/
READER_VIEW_CREATED: "ReaderViewCreated",
/**
* @event
*/
READER_VIEW_DESTROYED: "ReaderViewDestroyed",
/**
* @event
*/
CONTENT_DOCUMENT_LOAD_START: "ContentDocumentLoadStart",
/**
* @event
*/
CONTENT_DOCUMENT_LOADED: "ContentDocumentLoaded",
/**
* @event
*/
CONTENT_DOCUMENT_UNLOADED: "ContentDocumentUnloaded",
/**
* @event
*/
MEDIA_OVERLAY_STATUS_CHANGED: "MediaOverlayStatusChanged",
/**
* @event
*/
MEDIA_OVERLAY_TTS_SPEAK: "MediaOverlayTTSSpeak",
/**
* @event
*/
MEDIA_OVERLAY_TTS_STOP: "MediaOverlayTTSStop",
/**
* @event
*/
PLUGINS_LOADED: "PluginsLoaded"
},
/**
* Internal Events
*
* @desc Should not be triggered outside of {@link Views.ReaderView}.
* @namespace
*/
InternalEvents: {
/**
* @event
*/
CURRENT_VIEW_PAGINATION_CHANGED: "CurrentViewPaginationChanged",
},
logEvent: function(eventName, eventType, eventSource) {
if (DEBUG) {
console.debug("#### ReadiumSDK.Events." + eventName + " - "+eventType+" - " + eventSource);
}
}
};
$.extend(Globals, new EventEmitter());
return Globals;
});
//This is default implementation of reading system object that will be available for the publication's javascript to analyze at runtime
//To extend/modify/replace this object reading system should subscribe Globals.Events.READER_INITIALIZED and apply changes in reaction to this event
navigator.epubReadingSystem = {
name: "",
version: "0.0.0",
layoutStyle: "paginated",
hasFeature: function (feature, version) {
// for now all features must be version 1.0 so fail fast if the user has asked for something else
if (version && version !== "1.0") {
return false;
}
if (feature === "dom-manipulation") {
// Scripts may make structural changes to the document???s DOM (applies to spine-level scripting only).
return true;
}
if (feature === "layout-changes") {
// Scripts may modify attributes and CSS styles that affect content layout (applies to spine-level scripting only).
return true;
}
if (feature === "touch-events") {
// The device supports touch events and the Reading System passes touch events to the content.
return false;
}
if (feature === "mouse-events") {
// The device supports mouse events and the Reading System passes mouse events to the content.
return true;
}
if (feature === "keyboard-events") {
// The device supports keyboard events and the Reading System passes keyboard events to the content.
return true;
}
if (feature === "spine-scripting") {
//Spine-level scripting is supported.
return true;
}
return false;
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.